Skip to content

Instantly share code, notes, and snippets.

@nZac
Last active April 16, 2019 13:07
Show Gist options
  • Save nZac/9d7399ae78467bfaa401 to your computer and use it in GitHub Desktop.
Save nZac/9d7399ae78467bfaa401 to your computer and use it in GitHub Desktop.
SQLAlchemy query to compiled SQL string
try:
import sqlparse.format as sqlformat
except ImportError:
def sqlformat(query, **kwargs):
"""Monkey patch sqlparse.format if package not installed"""
return query
def debug_query(query, engine):
"""Return a parametrized and formated sql query for debugging
See the docs http://goo.gl/eshjL2 for the details on how this works
"""
q = unicode(query.compile(engine, compile_kwargs={'literal_binds': True}))
return sqlformat(q, reindent=True)
# One liner for pdb/tracebacks
import sqlparse; print(sqlparse.format(query.statement.compile(db.engine, compile_kwargs={'literal_binds': True}), reindent=True))
# Without sqlparse
print(query.statement.compile(db.engine, compile_kwargs={'literal_binds': True}))
import sqlparse; q=sqlparse.format(query.statement.compile(db.engine, compile_kwargs={'literal_binds': True}), reindent=True); f = open('debug.sql', mode='r'); f.write(q); f.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment