Why this matters
Prevents connection leaks and ensures consistent transaction semantics.
Provide a decorator/context manager that opens/closes DB sessions and handles commit/rollback automatically.
Prevents connection leaks and ensures consistent transaction semantics.
Side-by-side examples engineers can pattern-match during review.
def repo_op():
s = Session()
s.add(obj)
s.commit()
s.close() # error paths may leakfrom contextlib import contextmanager
@contextmanager
def session_scope():
s = Session()
try:
yield s
s.commit()
except Exception:
s.rollback()
raise
finally:
s.close()
def repo_op():
with session_scope() as s:
s.add(obj)s = Session(); ...; # no finallywith session_scope() as s: ...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.