Created
January 19, 2013 11:25
Generate an SQL expression string with bound parameters rendered inline for the given SQLAlchemy statement.
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
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) |
Brilliant. Thank you. I wonder why SQLAlchemy doesn't provide this functionality out of the box?
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
As of SQLAlchemy 1.x, need to change
statement. _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!