出于调试目的,我想显示实际执行的sql。
我有一个简单的查询示例:
SELECT (id, title)
FROM some_table AS t
WHERE
t.id IN :id_sequence
LIMIT :count
我的python看起来像这样:
def resolve(query, **params):
"""Returns the resolved query using the input params
Example:
>>> query = "SELECT (id, title) FROM table AS t WHERE t.id IN :id_sequence LIMIT :count"
>>> resolve(query, id_sequence=('1', '2'), count=5)
SELECT (id, title) FROM table AS t WHERE t.id IN ('1', '2') LIMIT 5
Args:
query: the text to query
params: the map of bound parameters and their values
Returns:
fully resolved text
"""
import sqlalchemy
sql = sqlalchemy.text(query)
# Capture only the parameters that are actually in the query
bound_parameters = sql.params(**params).compile().params
# Then bind only those captured parameters
bound_sql = sql.bindparams(**bound_params)
compiled_sql = bound_sql.compile(compile_kwargs={"literal_binds": True})
return str(compiled_sql)
对于以下参数值:
{'id_sequence': ('1', '2'), 'limit': 5}
使用上述sql,我的期望是最终得到:
SELECT (id, title)
FROM some_table AS t
WHERE
t.id IN ('1', '2')
LIMIT 5
我真正看到的是:
SELECT (id, title)
FROM some_table AS t
WHERE
t.id IN NULL
LIMIT 5