def queries_captured( include_savepoints: bool = False, keep_cache_warm: bool = False ) -> Generator[List[Dict[str, Union[str, bytes]]], None, None]: """ Allow a user to capture just the queries executed during the with statement. """ queries: List[Dict[str, Union[str, bytes]]] = [] def wrapper_execute( self: TimeTrackingCursor, action: Callable[[Query, ParamsT], None], sql: Query, params: ParamsT, ) -> None: start = time.time() try: return action(sql, params) finally: stop = time.time() duration = stop - start if include_savepoints or not isinstance( sql, str) or "SAVEPOINT" not in sql: queries.append({ "sql": self.mogrify(sql, params).decode(), "time": f"{duration:.3f}", }) def cursor_execute(self: TimeTrackingCursor, sql: Query, params: Optional[Params] = None) -> None: return wrapper_execute(self, super(TimeTrackingCursor, self).execute, sql, params) def cursor_executemany(self: TimeTrackingCursor, sql: Query, params: Iterable[Params]) -> None: return wrapper_execute( self, super(TimeTrackingCursor, self).executemany, sql, params) # nocoverage -- doesn't actually get used in tests if not keep_cache_warm: cache = get_cache_backend(None) cache.clear() with mock.patch.multiple(TimeTrackingCursor, execute=cursor_execute, executemany=cursor_executemany): yield queries
def wrapper_execute(self, action, sql, params=()): # type: (TimeTrackingCursor, Callable, NonBinaryStr, Iterable[Any]) -> None cache = get_cache_backend(None) cache.clear() start = time.time() try: return action(sql, params) finally: stop = time.time() duration = stop - start if include_savepoints or ('SAVEPOINT' not in sql): queries.append({ 'sql': self.mogrify(sql, params).decode('utf-8'), 'time': "%.3f" % duration, })
def wrapper_execute(self: TimeTrackingCursor, action: Callable[[str, Iterable[Any]], None], sql: str, params: Iterable[Any] = ()) -> None: cache = get_cache_backend(None) cache.clear() start = time.time() try: return action(sql, params) finally: stop = time.time() duration = stop - start if include_savepoints or ('SAVEPOINT' not in sql): queries.append({ 'sql': self.mogrify(sql, params).decode('utf-8'), 'time': "%.3f" % (duration, ), })
def wrapper_execute(self: TimeTrackingCursor, action: Callable[[str, ParamsT], None], sql: Query, params: ParamsT) -> None: cache = get_cache_backend(None) cache.clear() start = time.time() try: return action(sql, params) finally: stop = time.time() duration = stop - start if include_savepoints or not isinstance(sql, str) or 'SAVEPOINT' not in sql: queries.append({ 'sql': self.mogrify(sql, params).decode('utf-8'), 'time': f"{duration:.3f}", })