Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate an SQL expression string with bound parameters rendered inline for the given SQLAlchemy statement.
from datetime import datetime, date
from sqlalchemy.orm.query import Query
def render_query(statement, bind=None):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement.
WARNING: This method of escaping is insecure, incomplete, and for debugging
purposes only. Executing SQL statements with inline-rendered user values is
extremely insecure.
Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
"""
if isinstance(statement, Query):
if bind is None:
bind = statement.session.get_bind(statement._mapper_zero_or_none())
statement = statement.statement
elif bind is None:
bind = statement.bind
class LiteralCompiler(bind.dialect.statement_compiler):
def visit_bindparam(self, bindparam, within_columns_clause=False,
literal_binds=False, **kwargs):
return self.render_literal_value(bindparam.value, bindparam.type)
def render_literal_value(self, value, type_):
if isinstance(value, long):
return str(value)
elif isinstance(value, (date, datetime)):
return "'%s'" % value
return super(LiteralCompiler, self).render_literal_value(value, type_)
return LiteralCompiler(bind.dialect, statement).process(statement)
@nezda

This comment has been minimized.

Copy link

commented Oct 22, 2017

As of SQLAlchemy 1.x, need to changestatement. _mapper_zero_or_none() -> statement._mapper_zero() to (thanks to https://groups.google.com/d/msg/sqlalchemy/iPknF8X6x-w/_K2gJkxhbvMJ !) This is a very useful function!

@mefergus

This comment has been minimized.

Copy link

commented Nov 23, 2017

Brilliant. Thank you. I wonder why SQLAlchemy doesn't provide this functionality out of the box?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.