fix txns for postgres

The real issue: psycopg2 operates in "implicit transaction" mode by default. Every query — even a simple SELECT — starts a transaction. So after runWithConnection runs a SELECT, the connection is "in a transaction" even though nothing needs committing. Twisted's
  ConnectionPool.runWithConnection handled this by calling rollback() after each runWithConnection call to close the implicit transaction.

  The fix should be: commit/rollback after runWithConnection completes (not before the next call), matching Twisted's behavior:
This commit is contained in:
Matthew Hodgson
2026-03-24 22:04:50 -04:00
parent a4a37b48f7
commit 40bed9f2be

View File

@@ -186,7 +186,15 @@ class NativeConnectionPool:
# Get connection inside the executor thread so that
# _thread_local resolves to this thread's connection.
conn = self._get_connection()
return func(conn, *args, **kwargs)
try:
return func(conn, *args, **kwargs)
finally:
# psycopg2 auto-starts a transaction on every query, even
# SELECTs. Roll back to close the implicit transaction,
# matching Twisted's ConnectionPool.runWithConnection
# which did the same to keep connections clean.
if self._engine.in_transaction(conn):
conn.rollback()
loop = asyncio.get_running_loop()
return await loop.run_in_executor(self._executor, _inner)