2014-01-07 22:20:29 +01:00
|
|
|
import time
|
|
|
|
from psycopg2.extensions import cursor, connection
|
|
|
|
|
2017-03-03 19:01:52 +01:00
|
|
|
from typing import Callable, Optional, Iterable, Any, Dict, List, Union, TypeVar, \
|
2018-05-10 19:13:36 +02:00
|
|
|
Mapping
|
2016-06-05 04:20:00 +02:00
|
|
|
|
|
|
|
CursorObj = TypeVar('CursorObj', bound=cursor)
|
2018-05-10 19:13:36 +02:00
|
|
|
ParamsT = Union[Iterable[Any], Mapping[str, Any]]
|
2016-06-05 04:20:00 +02:00
|
|
|
|
2014-01-07 22:20:29 +01:00
|
|
|
# Similar to the tracking done in Django's CursorDebugWrapper, but done at the
|
|
|
|
# psycopg2 cursor level so it works with SQLAlchemy.
|
2017-11-05 11:15:10 +01:00
|
|
|
def wrapper_execute(self: CursorObj,
|
2018-11-27 20:21:55 +01:00
|
|
|
action: Callable[[str, Optional[ParamsT]], CursorObj],
|
|
|
|
sql: str,
|
2017-11-05 11:15:10 +01:00
|
|
|
params: Optional[ParamsT]=()) -> CursorObj:
|
2014-01-07 22:20:29 +01:00
|
|
|
start = time.time()
|
|
|
|
try:
|
|
|
|
return action(sql, params)
|
|
|
|
finally:
|
|
|
|
stop = time.time()
|
|
|
|
duration = stop - start
|
|
|
|
self.connection.queries.append({
|
2019-04-20 01:00:46 +02:00
|
|
|
'time': "%.3f" % (duration,),
|
2017-01-24 06:34:26 +01:00
|
|
|
})
|
2014-01-07 22:20:29 +01:00
|
|
|
|
|
|
|
class TimeTrackingCursor(cursor):
|
|
|
|
"""A psycopg2 cursor class that tracks the time spent executing queries."""
|
|
|
|
|
2018-11-27 20:21:55 +01:00
|
|
|
def execute(self, query: str,
|
2017-11-05 11:15:10 +01:00
|
|
|
vars: Optional[ParamsT]=None) -> 'TimeTrackingCursor':
|
2017-10-27 08:28:23 +02:00
|
|
|
return wrapper_execute(self, super().execute, query, vars)
|
2014-01-07 22:20:29 +01:00
|
|
|
|
2018-11-27 20:21:55 +01:00
|
|
|
def executemany(self, query: str,
|
2017-11-05 11:15:10 +01:00
|
|
|
vars: Iterable[Any]) -> 'TimeTrackingCursor':
|
2017-10-27 08:28:23 +02:00
|
|
|
return wrapper_execute(self, super().executemany, query, vars)
|
2014-01-07 22:20:29 +01:00
|
|
|
|
|
|
|
class TimeTrackingConnection(connection):
|
|
|
|
"""A psycopg2 connection class that uses TimeTrackingCursors."""
|
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
2017-05-17 21:06:51 +02:00
|
|
|
self.queries = [] # type: List[Dict[str, str]]
|
2017-10-27 08:28:23 +02:00
|
|
|
super().__init__(*args, **kwargs)
|
2014-01-07 22:20:29 +01:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def cursor(self, *args: Any, **kwargs: Any) -> TimeTrackingCursor:
|
2016-10-14 09:36:27 +02:00
|
|
|
kwargs.setdefault('cursor_factory', TimeTrackingCursor)
|
|
|
|
return connection.cursor(self, *args, **kwargs)
|
2014-01-07 22:20:29 +01:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def reset_queries() -> None:
|
2014-01-07 22:20:29 +01:00
|
|
|
from django.db import connections
|
|
|
|
for conn in connections.all():
|
2015-11-24 07:01:35 +01:00
|
|
|
if conn.connection is not None:
|
|
|
|
conn.connection.queries = []
|