Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve executed SQL code from SQLAlchemy

I am using SQLAlchemy and would like to log executed SQL code (i.e. the code with all bind parameters already quoted and replaced). In case of psycopg2 it was possible using the query attribute of the Cursor object (see psycopg documentation). In case of MySQLdb it is possible using the _last_executed attribute of the Cursor object.

My question is: How can I retrieve the just executed query string using SQLAlchemy interfaces? Does it provide such functionality or should I write my own helper function?

Thanks in advance for any help.

like image 942
Dariusz Walczak Avatar asked Jun 14 '11 21:06

Dariusz Walczak


People also ask

What does SQLAlchemy query return?

It returns an instance based on the given primary key identifier providing direct access to the identity map of the owning Session. It creates a SQL JOIN against this Query object's criterion and apply generatively, returning the newly resulting Query.

Is SQL injection possible with SQLAlchemy?

SQLAlchemy through 1.2. 17 and 1.3. x through 1.3. 0b2 allows SQL Injection via the order_by parameter.

How do I run a raw SQL query in SQLAlchemy?

Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.


1 Answers

SQLAlchemy uses the standard Python logging library. To log queries to a file named db.log:

import logging

logging.basicConfig(filename='db.log')
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

When using Python logging, ensure all echo flags are set to False, to avoid duplicate logging. Now add something to the db:

>>> Movie(title=u"Blade Runner", year=1982)
>>> session.commit()

Which will log something like:

INFO:sqlalchemy.engine.base.Engine:BEGIN (implicit)
INFO:sqlalchemy.engine.base.Engine:INSERT INTO models_movie (title, year, description) VALUES (%(title)s, %(year)s, %(description)s) RETURNING models_movie.id
INFO:sqlalchemy.engine.base.Engine:{'title': u'Blade Runner', 'description': None, 'year': 1982}
INFO:sqlalchemy.engine.base.Engine:COMMIT
like image 141
zeekay Avatar answered Oct 24 '22 17:10

zeekay