Reputation: 2050
The simplest possible way to get "raw" SQL for any query is just print
it (actually, convert it to str
).
But, this is not working for count()
queries because count()
is "firing" method - a method which is stated as "This results in an execution of the underlying query". Other "firing" methods include all()
, first()
and so on.
How to get SQL for such methods?
I'm especially interested in count()
because it transforms underlying query in some way (actually, this way is described explicitly in docs, but things may vary). Other methods can alter resulting SQL as well, for example, first()
.
So, sometimes it is useful to get raw SQL of such queries in order to investigate how thing goes under the hood.
I read answers about "getting raw SQL" but this case is special because such methods don't return Query
objects.
Note that I mean that I need a SQL of existing Query
objects which are already constructed in some way.
Upvotes: 4
Views: 576
Reputation: 9405
The following example will return a count of any query object, which you should then be able to convert to a string representation:
from sqlalchemy import func
...
existing_query = session.query(Something)\
.join(OtherThing)\
.filter(OtherThing.foo = 'FOO')\
.subquery()
query = session.query(func.count(existing_query.c.bar).label('bar_count'))
print(query)
actual_count = query.as_scalar() # Executes query
Notice that you have to specify a field from the query output to count. In the example defined by existing_query.c.bar
.
Upvotes: 2