4

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?

davidism
  • 121,510
  • 29
  • 395
  • 339
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

1 Answers1

1

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)```
Ashish Bhatt
  • 77
  • 1
  • 4