Skip to content

Instantly share code, notes, and snippets.

@gsakkis
Created January 19, 2013 11:25
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
Copy link

nezda 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
Copy link

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

@samkit-jain
Copy link

For Python 3, if isinstance(value, long): can be replaced with if isinstance(value, int):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment