On the App Engine Google group, Thomas Kuczek asked:
I have a query object representing a query. How can I print the resulting Gql to log it with the logger framework?
I thought this sounded like an interesting and possibly useful thing to do, so I wrote a small module which can convert either a db.Query or a db.GqlQuery object to a meaningful string.
This code depends on details of the query implementation (a lot of the required fields are private), so I can be fairly safe in saying that not only may it break in the next release of the App Engine environment, but it almost certainly will break.
In the code samples which follow the test class is:
First some setup code for the tests:
>>> from google.appengine.ext import db
Now try printing some queries:
>>> q = Person.all()
If we have more than one filter, showQuery will always output them in sorted order rather than the order in which they were input. This is simply to make doctests easier:
>>> print showQuery(q.filter('height <', 72))
We can even handle an ancestor on the query although the key may be a bit of a mouthful:
>>> p = Person(first_name='Duncan', last_name='Booth', city='Oxford', height=183)
There is also a showGqlQuery function to convert GQL back to the equivalent query:
>>> q = db.GqlQuery("SELECT * FROM Person WHERE last_name = :1 AND height < :2", "Smith", 72)
Notice that once again the output may have the clauses in a different order than they were originally input.
>>> print showGqlQuery(db.GqlQuery("SELECT * FROM Person WHERE last_name = :name AND height < :height"))
We can also handle literal values in queries:
>>> print showGqlQuery(db.GqlQuery("SELECT * FROM Person WHERE last_name = 'Smith'"))
Sorting is also handled. The ORDER BY clause does preserve the original order:
>>> print showGqlQuery(db.GqlQuery("SELECT * FROM Person WHERE height < :1 ORDER BY last_name ASC"))
Ancestor, limit, and offset classes also all work. If you specify limit and offset separately then they are output together:
>>> print showGqlQuery(db.GqlQuery("SELECT * FROM Person WHERE ANCESTOR IS :1 AND height < 72"))
The source code (showquery.py) looks like this:
from google.appengine.ext import db