"""One-shot migration runner: applies app/migrations/*.sql exactly once. Run as a dedicated compose service (or `python -m app.migrate`) before the API replicas start, so schema changes are never raced between replicas. """ import asyncio import os import pathlib import sys import asyncpg MIGRATIONS_DIR = pathlib.Path(__file__).resolve().parent / "migrations" ADVISORY_LOCK_KEY = 424242 async def run() -> int: dsn = os.environ.get("DATABASE_URL") if not dsn: print("DATABASE_URL environment variable is required", file=sys.stderr) return 2 conn = await asyncpg.connect(dsn) try: await conn.execute( "CREATE TABLE IF NOT EXISTS schema_migrations (" "version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())" ) await conn.execute("SELECT pg_advisory_lock($1)", ADVISORY_LOCK_KEY) try: applied = 0 for path in sorted(MIGRATIONS_DIR.glob("*.sql")): version = path.stem already = await conn.fetchval( "SELECT 1 FROM schema_migrations WHERE version = $1", version ) if already: print(f"migration {version}: already applied") continue sql = path.read_text(encoding="utf-8") # Strip `--` line comments before splitting on ';' so a semicolon # inside a comment cannot produce a bogus statement fragment. cleaned_lines = [] for line in sql.splitlines(): idx = line.find("--") cleaned_lines.append(line if idx < 0 else line[:idx]) cleaned = "\n".join(cleaned_lines) statements = [chunk.strip() for chunk in cleaned.split(";") if chunk.strip()] async with conn.transaction(): for statement in statements: await conn.execute(statement) await conn.execute( "INSERT INTO schema_migrations (version) VALUES ($1)", version ) print(f"migration {version}: applied ({len(statements)} statement(s))") applied += 1 print(f"migrations complete: {applied} newly applied") return 0 finally: await conn.execute("SELECT pg_advisory_unlock($1)", ADVISORY_LOCK_KEY) finally: await conn.close() if __name__ == "__main__": sys.exit(asyncio.run(run()))