Peewee: Print SQL queries

Created on 11 Oct 2012  路  10Comments  路  Source: coleifer/peewee

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!

Most helpful comment

That function actually went away. Now you can just call:

q = MyModel.select().where(MyModel.id == 3)
print q.sql()
sql, params = q.sql()

All 10 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rayzorben picture rayzorben  路  4Comments

aellwein picture aellwein  路  3Comments

mmongeon-aa picture mmongeon-aa  路  4Comments

kalimalrazif picture kalimalrazif  路  3Comments

ezk84 picture ezk84  路  4Comments