Last active
March 27, 2017 14:32
-
-
Save absent1706/0c7d017f0cfb98b4d322b2d9f4987d6e to your computer and use it in GitHub Desktop.
SQLAlchemy debug utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def to_sql(query, dialect_name=None): | |
from sqlalchemy import dialects | |
import operator | |
if dialect_name: | |
dialect_module = getattr(dialects, dialect_name) | |
if not dialect_module: | |
raise KeyError('Wrong dialect {}'.format(dialect_name)) | |
dialect = dialect_module.dialect() | |
else: | |
try: | |
# think about it as getattr(query, 'session.bind.dialect') | |
dialect = operator.attrgetter('session.bind.dialect')(query) | |
except AttributeError: | |
raise KeyError('dialect_name was not passed ' | |
'and cant get dialect from session.' | |
'Pass dialect_name or bound query to session') | |
return str( | |
query.statement.compile(compile_kwargs={"literal_binds": True}, | |
dialect=dialect)) | |
def register_sqlalchemy_echo_with_bound_params(): | |
""" | |
it's like | |
create_engine(echo=True), | |
but binds params to query, so you have real raw SQL | |
""" | |
import sys | |
from datetime import datetime | |
from sqlalchemy.engine import Engine | |
from sqlalchemy import event | |
@event.listens_for(Engine, "before_cursor_execute") | |
def before_cursor_execute(conn, cursor, statement, | |
parameters, context, executemany): | |
# wrap non-integers in quotes | |
if isinstance(parameters, dict): | |
escaped_params = {} | |
for k, v in parameters.items(): | |
escaped_params[k] = v if isinstance(v, (int, long)) \ | |
else "'{}'".format(v) | |
sys.stdout.write("\n{} QUERY: \n{}\n".format( | |
datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
statement % escaped_params)) | |
else: | |
sys.stdout.write("\n{} QUERY: \n{}\nParams: {}\n".format( | |
datetime.now().strftime('%Y-%m-%d %H:%M:%S'), | |
statement, parameters)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment