|
9 | 9 | import asyncpg
|
10 | 10 | import collections
|
11 | 11 | import collections.abc
|
| 12 | +from datetime import datetime, timezone |
12 | 13 | import functools
|
13 | 14 | import itertools
|
14 | 15 | import inspect
|
@@ -305,6 +306,25 @@ def is_in_transaction(self):
|
305 | 306 | """
|
306 | 307 | return self._protocol.is_in_transaction()
|
307 | 308 |
|
| 309 | + def log_statement(self, context: str, statement: str, args=None): |
| 310 | + when = datetime.now(timezone.utc) |
| 311 | + |
| 312 | + if self._recent_statements: |
| 313 | + most_recently_logged = self._recent_statements[-1] |
| 314 | + # Each entry is (timestamp, calling context, sql statement, args (if any)) tuple. |
| 315 | + ( |
| 316 | + _, |
| 317 | + _, |
| 318 | + prior_statement, |
| 319 | + _, |
| 320 | + ) = most_recently_logged |
| 321 | + if prior_statement == statement: |
| 322 | + # Do not double-log same query. |
| 323 | + return |
| 324 | + |
| 325 | + to_log = (when.strftime("%Y-%m-%d %H:%M:%S UTC"), context, statement, args) |
| 326 | + self._recent_statements.append(to_log) |
| 327 | + |
308 | 328 | async def execute(self, query: str, *args, timeout: float = None) -> str:
|
309 | 329 | """Execute an SQL command (or commands).
|
310 | 330 |
|
@@ -335,12 +355,8 @@ async def execute(self, query: str, *args, timeout: float = None) -> str:
|
335 | 355 | """
|
336 | 356 | self._check_open()
|
337 | 357 |
|
338 |
| - # Append to circular buffer of most recent executed statements |
339 |
| - # for debugging. |
340 |
| - self._recent_statements.append(query) |
341 |
| - |
342 | 358 | if not args:
|
343 |
| - self._recent_statements.append(query) |
| 359 | + self.log_statement("execute no args", query) |
344 | 360 | return await self._protocol.query(query, timeout)
|
345 | 361 |
|
346 | 362 | _, status, _ = await self._execute(
|
@@ -541,7 +557,7 @@ def cursor(self, query, *args, prefetch=None, timeout=None, record_class=None):
|
541 | 557 | """
|
542 | 558 | self._check_open()
|
543 | 559 |
|
544 |
| - self._recent_statements.append(query) |
| 560 | + self.log_statement("cursor", query, args) |
545 | 561 |
|
546 | 562 | return cursor.CursorFactory(
|
547 | 563 | self,
|
@@ -1802,7 +1818,7 @@ async def _do_execute(
|
1802 | 1818 | ignore_custom_codec=False,
|
1803 | 1819 | record_class=None,
|
1804 | 1820 | ):
|
1805 |
| - self._recent_statements.append(query) |
| 1821 | + self.log_statement("_do_execute", query) |
1806 | 1822 | if timeout is None:
|
1807 | 1823 | stmt = await self._get_statement(
|
1808 | 1824 | query,
|
|
0 commit comments