-
-
Save pabloh007/1880e7ac081d4337d096 to your computer and use it in GitHub Desktop.
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, int): # change for python 3 as it does not use the long anymore | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment