python - How do I get a raw, compiled SQL query from a SQLAlchemy expression? -


i have sqlalchemy query object , want text of compiled sql statement, parameters bound (e.g. no %s or other variables waiting bound statement compiler or mysqldb dialect engine, etc).

calling str() on query reveals this:

select id date_added <= %s , date_added >= %s order count desc 

i've tried looking in query._params it's empty dict. wrote own compiler using this example of sqlalchemy.ext.compiler.compiles decorator statement there still has %s want data.

i can't quite figure out when parameters mixed in create query; when examining query object they're empty dictionary (though query executes fine , engine prints out when turn echo logging on).

i'm starting message sqlalchemy doesn't want me know underlying query, breaks general nature of expression api's interface different db-apis. don't mind if query gets executed before found out was; want know!

this should work sqlalchemy >= 0.6

from sqlalchemy.sql import compiler  psycopg2.extensions import adapt sqlescape # or use appropiate escape function db driver  def compile_query(query):     dialect = query.session.bind.dialect     statement = query.statement     comp = compiler.sqlcompiler(dialect, statement)     comp.compile()     enc = dialect.encoding     params = {}     k,v in comp.params.iteritems():         if isinstance(v, unicode):             v = v.encode(enc)         params[k] = sqlescape(v)     return (comp.string.encode(enc) % params).decode(enc) 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -