Home >Backend Development >Python Tutorial >How to Print Actual SQL Queries with Values During Debugging in SQLAlchemy?
When debugging SQLAlchemy expressions, it's valuable to see the actual SQL query being executed, including specific values instead of bind parameters. While SQLAlchemy doesn't provide an explicit method for this, there are a few ways to achieve it.
In most cases, you can simply call str() on the SQLAlchemy statement or query:
print(str(statement))
This works for both ORM queries (Query objects) and pure SQL statements (select(), etc.).
If you need the statement compiled for a specific database engine, you can use the compile() method:
print(statement.compile(some_engine))
Or, if you don't have an engine, you can specify a dialect:
from sqlalchemy.dialects import postgresql print(statement.compile(dialect=postgresql.dialect()))
In certain circumstances, you may want to inline bound parameters into the final SQL string. This can be achieved using the literal_binds flag:
print(statement.compile(compile_kwargs={"literal_binds": True}))
Note that this is only supported for basic types like integers and strings. For more complex types, you may need to create a custom type decorator.
To support inline rendering of unsupported types, you can create a custom type decorator with a process_literal_param method:
class MyFancyType(TypeDecorator): ... def process_literal_param(self, value, dialect): return f"my_fancy_formatting({value})"
With this decorator, you can inline complex values:
print(tab.select().where(tab.c.x > 5).compile(compile_kwargs={"literal_binds": True}))
yielding output like:
SELECT mytable.x FROM mytable WHERE mytable.x > my_fancy_formatting(5)
The above is the detailed content of How to Print Actual SQL Queries with Values During Debugging in SQLAlchemy?. For more information, please follow other related articles on the PHP Chinese website!