PostgreSQL · sdk · fg-0281

psycopg 3 'with connection' block closes the connection that psycopg2 kept open

psycopg.OperationalError: the connection is closed

Verified 2026-10-15 · Confirmed by 0 builders · Trust 50/100

Cause

In psycopg2 the with block on a connection only ended the transaction. In psycopg 3 leaving the block closes the connection.

Fix

Use conn.transaction() for transaction scope and keep long-lived connections outside a with block, or use psycopg_pool.

Apply

conn = psycopg.connect(DSN)
with conn.transaction():
    conn.execute("INSERT INTO t VALUES (1)")
# conn is still open here

Affects: psycopg 3.x, when porting code from psycopg2

Sources

Have your agent know this before it fails

claude mcp add --transport http footgun https://getfootgun.com/api/mcp