Skip to content

require-explicit-psycopg-transaction

Make Psycopg locking reads and related writes explicitly transactional.

Why

Pool checkout does not start a transaction in autocommit mode. Locks can expire before use and earlier writes can survive a later failure.

Fix

Enclose the complete atomic operation in the same connection's transaction() context, or use one atomic SQL statement. Document intentionally independent writes with an exact suppression.

Examples

Before — flagged A pool checkout alone does not retain a lock
repository.py
from psycopg_pool import AsyncConnectionPool
async def save(pool: AsyncConnectionPool):
async with pool.connection() as conn:
await conn.execute("SELECT id FROM items FOR UPDATE")
await conn.execute("UPDATE items SET n = 1")
After — preferred Retain locks for the atomic operation
repository.py
from psycopg_pool import AsyncConnectionPool
async def save(pool: AsyncConnectionPool):
async with pool.connection() as conn, conn.transaction():
await conn.execute("SELECT id FROM items FOR UPDATE")
await conn.execute("UPDATE items SET n = 1")