Skip to content

Instantly share code, notes, and snippets.

@yaojialyu
Created December 25, 2015 11:56
Show Gist options
  • Save yaojialyu/f31f58d527cb89de57ed to your computer and use it in GitHub Desktop.
Save yaojialyu/f31f58d527cb89de57ed to your computer and use it in GitHub Desktop.
get sqlalchemy raw query
# coding: utf-8
from sqlalchemy.sql import compiler
from MySQLdb.converters import conversions, escape
def compile_query(query):
dialect = query.session.bind.dialect
statement = query.statement
comp = compiler.SQLCompiler(dialect, statement)
comp.compile()
enc = dialect.encoding
params = []
for k in comp.positiontup:
v = comp.params[k]
if isinstance(v, unicode):
v = v.encode(enc)
params.append(escape(v, conversions))
return (comp.string.encode(enc) % tuple(params)).decode(enc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment