How can I use SQLAlchemy to do "mysql explain"
Asked Answered
C

2

13

I have a sql like:

DBSession().query(Model).filter(***)

and I want to explain this sql using SQLAlchemy.

Colecolectomy answered 23/6, 2013 at 14:10 Comment(0)
J
22

You want to compile your SQLAlchemy query into a string; use the correct dialect and use literal values for bind parameters

query = DBSession().query(Model).filter(***)
# you should have an engine reference used to create the DBSession object
sql = query.statement.compile(engine, compile_kwargs={"literal_binds": True})

You can then use that to ask for a MySQL explanation:

DBSession().execute(f'EXPLAIN {sql}')
Jeffreyjeffreys answered 23/6, 2013 at 14:22 Comment(0)
D
4

You can prepare your explain sql string like this:

'EXPLAIN' + query.compile(
    compile_kwargs={"literal_binds": True},
    dialect=mysql.dialect()
)

Advantage is query has parameters filled in.

Drawer answered 4/9, 2020 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.