"""PostgreSQL connection pool and versioned migration runner.""" import logging from pathlib import Path import asyncpg logger = logging.getLogger("app.db") MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations" _pool: asyncpg.Pool | None = None async def init_pool(dsn: str) -> asyncpg.Pool: global _pool _pool = await asyncpg.create_pool( dsn, min_size=2, max_size=10, command_timeout=5, timeout=5, ) return _pool async def close_pool() -> None: global _pool if _pool is not None: await _pool.close() _pool = None def pool() -> asyncpg.Pool: if _pool is None: raise RuntimeError("database pool is not initialized") return _pool MIGRATION_LOCK_KEY = 783451 # arbitrary advisory-lock id, serializes concurrent replicas async def _run_migrations(p: asyncpg.Pool) -> None: async with p.acquire() as conn: # Multiple API replicas start together; an advisory lock keeps migrations # from racing each other instead of letting all replicas apply SQL at once. await conn.execute("SELECT pg_advisory_lock($1)", MIGRATION_LOCK_KEY) try: await _apply_migrations(conn) finally: await conn.execute("SELECT pg_advisory_unlock($1)", MIGRATION_LOCK_KEY) async def run_migrations(dsn: str) -> None: p = await asyncpg.create_pool(dsn, min_size=1, max_size=2, command_timeout=5, timeout=5) try: await _run_migrations(p) finally: await p.close() async def _apply_migrations(conn: asyncpg.Connection) -> None: await conn.execute( """ CREATE TABLE IF NOT EXISTS schema_migrations ( version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now() ) """ ) applied = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")} for path in sorted(MIGRATIONS_DIR.glob("*.sql")): if path.name in applied: continue sql = path.read_text(encoding="utf-8") async with conn.transaction(): await conn.execute(sql) await conn.execute( "INSERT INTO schema_migrations (version) VALUES ($1)", path.name ) logger.info("applied migration %s", path.name) async def ping() -> bool: try: async with pool().acquire() as conn: await conn.fetchval("SELECT 1") return True except Exception: # noqa: BLE001 - readiness probe, any failure means not ready return False