Search code examples
pythonsqlobject

Print SQL generated by SQLObject


from sqlobject import *

class Data(SQLObject):
    ts = TimeCol()
    val = FloatCol()

Data.select().count()

Fails with:

AttributeError: No connection has been defined for this thread or process

How do I get the SQL which would be generated, without declaring a connection?


Solution

  • It's impossible for two reasons. 1st, .count() not only generates a query, it also executes it, so not only it requires a connection, it also requires a database and a populated table. 2nd, different queries could be generated for different backends (esp. in the area of quoting strings) so a connection is required to render a query object to a string.

    To generate a query string with accumulator function you need to repeat the code that generates the query. So the full solution for your question is

    #! /usr/bin/env python
    
    from sqlobject import *
    
    __connection__ = "sqlite:/:memory:?debug=1"
    
    class Data(SQLObject):
        ts = TimeCol()
        val = FloatCol()
    
    print(Data.select().queryForSelect().newItems("COUNT(*)"))