I updated from 1.0 to 2.0 and got into a bit of a mess - which has mostly cleared up now. One thing though - how do I print sql queries? I used to be able to do SelectQuery.sql() but not it requires a compiler argument, but what should I put into that? I cannot find any mention in the docs...
Thanks!
I added a little helper here:
https://github.com/coleifer/peewee/commit/a5ec7bb90b1882db95c6f4eae94ea373f7f6a50f
Great, thanks!
@coleifer Can you please give an example of how to use that helper function?
That function actually went away. Now you can just call:
q = MyModel.select().where(MyModel.id == 3)
print q.sql()
sql, params = q.sql()
@coleifer What if the result of q = MyModel.select().where(MyModel.id == 3) fails and caused an error? Is it possible to get the query that was sent to the DB and failed?
You can log all queries.
import logging
logger = logging.getLogger('peewee')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
Or you can add try/except or use an interactive debugger...it's just Python, remember!
@TimothyBramlett you can use the logging package:
import logging
logging.basicConfig(level=logging.DEBUG)
Peewee will print all queries that it sends to the DB.
As per peewee 3.13, if you are connecting to a postgres database with peewee's underlying psycopg2 (thanks @coleifer), you can print SQL queries by first getting the cursor, then calling the mogrify() method for your query.
query = <YOUR PEEWEE QUERY>
cur = database.cursor()
print(cur.mogrify(*query.sql()))
Where database is the Peewee Database object representing the connection to your database.
mogrify may be a psycopg2-only thing, and no supported by other drivers. For example, the standard lib sqlite3 does not provide this method.
Most helpful comment
That function actually went away. Now you can just call: