Skip to content
Sarj Code Standards

prefer-single-psycopg-cursor

Review repeated Psycopg cursor creation within one function.

Why

Repeated cursor construction can obscure one function's query orchestration and duplicate setup that could share a cursor.

Fix

Review whether one cursor can own these operations. Consume each result before reuse, retain distinct row factories or independent pipeline results when required, and preserve connection and transaction boundaries.

Examples

Before — flagged Review repeated cursor scopes
app/store.py
from psycopg import AsyncConnection
async def load(connection: AsyncConnection):
async with connection.cursor() as cursor:
await cursor.execute("SELECT id FROM item")
async with connection.cursor() as cursor:
await cursor.execute("SELECT id FROM owner")
After — preferred Reuse a cursor after consuming the result
app/store.py
from psycopg import AsyncConnection
async def load(connection: AsyncConnection):
async with connection.cursor() as cursor:
await cursor.execute("SELECT id FROM item")
rows = await cursor.fetchall()
await cursor.execute("SELECT id FROM owner")
return rows, await cursor.fetchall()