from contextlib import contextmanager from pathlib import Path import psycopg from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from src.config import secret pool = ConnectionPool( conninfo=secret("DATABASE_URL"), min_size=1, max_size=8, timeout=2, max_waiting=32, reconnect_timeout=5, open=False, kwargs={"connect_timeout": 2, "row_factory": dict_row, "options": "-c statement_timeout=2000 -c lock_timeout=1500 -c idle_in_transaction_session_timeout=5000 -c timezone=UTC"}, ) def migrate(): # One transaction + advisory lock serializes concurrent API bootstraps. with psycopg.connect(secret("DATABASE_URL"), connect_timeout=3) as conn: conn.execute("SET LOCAL lock_timeout = '10s'") conn.execute("SET LOCAL statement_timeout = '15s'") conn.execute("SELECT pg_advisory_xact_lock(202602)") conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())") for path in sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql")): if not conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone(): conn.execute(path.read_text()) conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (path.name,)) @contextmanager def connection(): with pool.connection() as conn: # psycopg context commits on success, rolls back on EVERY exception. yield conn if __name__ == "__main__": migrate() print("PASS: versioned migrations applied (already applied versions skipped)")