Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use SQLAlchemy to do "mysql explain"

I have a sql like:

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

and I want to explain this sql using SQLAlchemy.

like image 231
Tallmad Avatar asked Jun 23 '13 14:06

Tallmad


People also ask

Can we use SQLAlchemy for MySQL?

SQLAlchemy supports MySQL starting with version 5.0. 2 through modern releases, as well as all modern versions of MariaDB.

How do I connect to SQLAlchemy in MySQL?

Finally, you have the hostname or IP address of the database and the database name. These data are all you need to establish a connection. The port is optional, but SQLAlchemy is smart enough to know the MySQL database resides at port 3306. Finally, you create the connection object and invoke the connect method.

Is SQLAlchemy same as MySQL?

SQLAlchemy provides a nice “Pythonic” way of interacting with databases. So rather than dealing with the differences between specific dialects of traditional SQL such as MySQL or PostgreSQL or Oracle, you can leverage the Pythonic framework of SQLAlchemy to streamline your workflow and more efficiently query your data.

How do you use MySQL explain?

In MySQL, EXPLAIN can be used in front of a query beginning with SELECT , INSERT , DELETE , REPLACE , and UPDATE . For a simple query, it would look like the following: EXPLAIN SELECT * FROM foo WHERE foo. bar = 'infrastructure as a service' OR foo.


2 Answers

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}')
like image 117
Martijn Pieters Avatar answered Oct 10 '22 23:10

Martijn Pieters


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.

like image 41
Leszek Zarna Avatar answered Oct 11 '22 00:10

Leszek Zarna