Why this matters
Guarantees atomicity and consistent data on failures.
Wrap multi-statement DB operations in a transaction; commit on success and rollback on any exception.
Guarantees atomicity and consistent data on failures.
Side-by-side examples engineers can pattern-match during review.
conn.execute('INSERT ...')
conn.execute('UPDATE ...') # no transactiontx = conn.begin()
try:
conn.execute('INSERT ...')
conn.execute('UPDATE ...')
tx.commit()
except Exception:
tx.rollback()
logger.exception('db tx failed')
raisedo_many_writes(conn) # no txwith conn.begin(): do_many_writes(conn)From the same buckets as this rule.
Review SQL/database migrations for operations that can lock large tables or cause downtime. Examples: creating indexes without CONCURRENTLY (Postgres), ALTER COLUMN TYPE on big tables, adding NOT NULL without backfill, long-running updates without batching. Require an online migration strategy (CONCURRENTLY, backfill in batches, dual-write/expand-contract) and a rollback plan.