Skip to content
Sarj Code Standards

prefer-psycopg-executemany

Use Psycopg executemany for a serial loop of invariant parameterized writes without row results.

Why

A bare execute loop repeats the same statement through separate client calls. Psycopg executemany centralizes batch execution and can pipeline those operations.

Fix

Prefer an existing bulk store method; otherwise send bounded parameter batches through cursor.executemany. Preserve transaction ownership, per-row failure behavior, ordering and backpressure.

Examples

Before — flagged Batch the same parameterized statement
app/user_store.py
from psycopg import AsyncCursor
async def save(cursor: AsyncCursor, rows):
for row in rows:
await cursor.execute("INSERT INTO users (id) VALUES (%s)", (row.id,))
After — preferred Use the cursor's batch API
app/user_store.py
from psycopg import AsyncCursor
async def save(cursor: AsyncCursor, rows):
await cursor.executemany(
"INSERT INTO users (id) VALUES (%s)", [(row.id,) for row in rows]
)