如何从SQLAlchemy表达式获取原始的编译SQL查询?

我有一个SQLAlchemy查询对象,想获取已编译的SQL语句的文本,并绑定了所有参数(例如,否%s或其他变量正等待语句编译器或MySQLdb方言引擎的绑定等)。


调用str()查询将显示如下内容:


SELECT id WHERE date_added <= %s AND date_added >= %s ORDER BY count DESC

我试着在query._params中查找,但这是一个空字典。我使用装饰器的这个示例sqlalchemy.ext.compiler.compiles编写了自己的编译器,但是即使那里的语句仍然有%s我想要的数据。


我无法弄清楚何时混入参数来创建查询。当检查查询对象时,它们始终是一个空字典(尽管查询执行得很好,并且当您打开echo记录时引擎会打印出来)。


我开始收到消息,SQLAlchemy不想让我知道底层查询,因为它破坏了表达式API接口的所有不同DB-API的一般性质。我不在乎查询是否在我发现查询之前就已经执行了;我只是想知道!


九州编程
浏览 1045回答 3
3回答

潇潇雨雨

这应该适用于Sqlalchemy> = 0.6from sqlalchemy.sql import compilerfrom psycopg2.extensions import adapt as sqlescape# or use the appropiate escape function from your db driverdef compile_query(query):&nbsp; &nbsp; dialect = query.session.bind.dialect&nbsp; &nbsp; statement = query.statement&nbsp; &nbsp; comp = compiler.SQLCompiler(dialect, statement)&nbsp; &nbsp; comp.compile()&nbsp; &nbsp; enc = dialect.encoding&nbsp; &nbsp; params = {}&nbsp; &nbsp; for k,v in comp.params.iteritems():&nbsp; &nbsp; &nbsp; &nbsp; if isinstance(v, unicode):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v = v.encode(enc)&nbsp; &nbsp; &nbsp; &nbsp; params[k] = sqlescape(v)&nbsp; &nbsp; return (comp.string.encode(enc) % params).decode(enc)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python
MySQL