13

I have a sql like:

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

and I want to explain this sql using SQLAlchemy.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Tallmad
  • 1,951
  • 4
  • 22
  • 29

2 Answers2

21

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}')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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.

Leszek Zarna
  • 3,253
  • 26
  • 26