2

I'm trying to log all SQLAlchemy queries to the console while parsing the query and filling in the parameters (e.g. translating :param_1 to 123). I managed to find this answer on SO that does just that. The issue I'm running into is that parameters don't always get translated.

Here is the event I'm latching onto -

@event.listens_for(Engine, 'after_execute', named=True)
def after_cursor_execute(**kw):
    conn = kw['conn']
    params = kw['params']
    result = kw['result']
    stmt = kw['clauseelement']
    multiparams = kw['multiparams']

    print(literalquery(stmt))

Running this query will fail to translate my parameters. Instead, I'll see :param_1 in the output -

Model.query.get(123)

It yields a CompileError exception with message Bind parameter '%(38287064 param)s' without a renderable value not allowed here..

However, this query will translate :param_1 to 123 like I would expect -

db.session.query(Model).filter(Model.id == 123).first()

Is there any way to translate any and all queries that are run using SQLAlchemy?

FWIW I'm targeting SQL Server using the pyodbc driver.

Community
  • 1
  • 1
onetwothree
  • 672
  • 1
  • 10
  • 20

1 Answers1

1

If you set up the logging framework, you can get the SQL statements logged by setting the sqlalchemy.engine logger at INFO level, e.g.:

import logging

logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
TheArchitect
  • 2,161
  • 1
  • 12
  • 16
  • 2
    Issue with this is that parameters are not inlined into the query making it difficult to copy/paste into the database without manually filling in the missing parameter placeholders. – onetwothree Feb 01 '17 at 18:20