MCPcopy Create free account
hub / github.com/alphagov/notifications-api / QueryRecorder

Class QueryRecorder

tests/utils.py:16–47  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14
15
16class QueryRecorder:
17 def __init__(self) -> None:
18 self.queries: list[QueryInfo] = []
19 self._listeners: list[Callable] = []
20
21 def __enter__(self):
22 # Register listeners for all engines to capture bind_key
23 for bind_key, engine in db.engines.items():
24 listener = self._listener(bind_key)
25 event.listen(engine, "before_cursor_execute", listener)
26 self._listeners.append((engine, listener))
27 return self
28
29 def __exit__(self, exc_type, exc_val, exc_tb):
30 # Remove all listeners
31 for engine, listener in self._listeners:
32 event.remove(engine, "before_cursor_execute", listener)
33 self._listeners.clear()
34
35 def _listener(self, bind_key):
36 """Create a listener function that captures the bind_key in its closure."""
37
38 def listener(conn, cursor, statement, parameters, context, executemany):
39 self.queries.append(
40 QueryInfo(
41 statement=statement,
42 parameters=parameters,
43 bind_key=bind_key,
44 )
45 )
46
47 return listener

Calls

no outgoing calls