Permalink
Browse files

adding a raw sql method

  • Loading branch information...
coleifer committed Oct 12, 2012
1 parent 3aa06e8 commit a5ec7bb90b1882db95c6f4eae94ea373f7f6a50f
Showing with 4 additions and 0 deletions.
  1. +4 −0 peewee.py
View
@@ -2089,3 +2089,7 @@ def dfs(model):
for m in sorted(models, key=names, reverse=True):
dfs(m)
return list(reversed(ordering)) # want parents first in output ordering
+
+def raw_sql(query):
+ db = query.model_class._meta.database
+ return query.sql(db.get_compiler())

4 comments on commit a5ec7bb

@kevinisaac

This comment has been minimized.

Show comment
Hide comment
@kevinisaac

kevinisaac Feb 17, 2015

Can someone please give an example of how to use this helper function?

Can someone please give an example of how to use this helper function?

@coleifer

This comment has been minimized.

Show comment
Hide comment
@coleifer

coleifer Feb 17, 2015

Owner

query = MyModel.select()
print raw_sql(query)

Owner

coleifer replied Feb 17, 2015

query = MyModel.select()
print raw_sql(query)

@MarSoft

This comment has been minimized.

Show comment
Hide comment
@MarSoft

MarSoft Feb 26, 2016

Because this page is one of first Google's results on the topic, I'll leave it here.
Here is how we can determine exact SQL produced by query, with all parameters substituted.
This works for PostgreSQL, but not sure about other database types.

query = MyModel.select().where(field1='value', fields2<datetime.datetime.now())
query.database.get_cursor().mogrify(*query.sql())

Because this page is one of first Google's results on the topic, I'll leave it here.
Here is how we can determine exact SQL produced by query, with all parameters substituted.
This works for PostgreSQL, but not sure about other database types.

query = MyModel.select().where(field1='value', fields2<datetime.datetime.now())
query.database.get_cursor().mogrify(*query.sql())
@alxnet

This comment has been minimized.

Show comment
Hide comment
@alxnet

alxnet Jul 22, 2017

For sqlite3 the following works for me (peewee 2.10.1):

sql, params = query.sql()
raw_sql = sql.replace('?',"'{}'").format(*params)

For sqlite3 the following works for me (peewee 2.10.1):

sql, params = query.sql()
raw_sql = sql.replace('?',"'{}'").format(*params)
Please sign in to comment.