Created
November 9, 2019 04:13
-
-
Save compwron/72396cf37d3d7480a9d101ea7c625bc9 to your computer and use it in GitHub Desktop.
Demo of how to test for n+1 queries produced by sqlalchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # for use with sqlalchemy | |
| def test_foo(): | |
| stmts = [] | |
| def catch_queries(conn, cursor, statement, a, b, c): | |
| stmts.append(statement) | |
| event.listen(engine, "before_cursor_execute", catch_queries) | |
| do_thing() | |
| assert _most_frequent_queries(queries=stmts, query_count=4, query_type='SELECT', query_print_length=50) == [('SELECT X FROM Y', 5)] | |
| def _most_frequent_queries(queries, query_count, query_type, query_print_length): | |
| select_sql_statement_groupings = {} | |
| for statement in queries: | |
| if statement.startswith(query_type): | |
| select_sql_statement_groupings.setdefault(statement, 0) | |
| select_sql_statement_groupings[statement] += 1 | |
| return list(map(lambda x: (x[0][:query_print_length], x[1]), list(OrderedDict( | |
| sorted(select_sql_statement_groupings.items(), key=lambda x: x[1], reverse=True)).items())[:query_count])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment