Is it possible to count the number of SQL queries with Flask / SQLAlchemy / Pytest / SQLite?

749 Views Asked by At

I have a Flask project which uses SQLAlchemy and a database. For testing, I replace the database by an SQLite database.

Now I would like to run some of the views and test for the number of queries executed. Essentially, I want to avoid to accidentially run into the (n+1) select problem. Is it possible to get the number of executed SQL Queries from SQLite or a Pytest / Flask plugin?

1

There are 1 best solutions below

0
Ashish Bhatt On

You can do this by https://docs.sqlalchemy.org/en/13/core/events.html (logging events)

event.listen(engine, "before_cursor_execute")

Now you can use the function as mentioned in the documentation :

    @event.listens_for(conn, 'before_cursor_execute')
    def before_cursor_execute(conn, cursor, statement, parameters,
                                    context, executemany):
        log.info("Received statement: %s", statement)```