"""One-shot, idempotent schema migration runner. The compose stack starts this module as a separate service before any API replica, so replicas never race on DDL. """ from __future__ import annotations import asyncio import sys from pathlib import Path import psycopg from .settings import load_settings MIGRATION_FILE = Path(__file__).resolve().parents[1] / "migrations" / "001_init.sql" MIGRATION_VERSION = "001_init" ADVISORY_LOCK_ID = 727_001_003 def statements(sql: str) -> list[str]: return [part.strip() for part in sql.split(";") if part.strip()] async def wait_for_database(database_url: str, attempts: int = 60) -> psycopg.AsyncConnection: last_error: Exception | None = None for _ in range(attempts): try: return await psycopg.AsyncConnection.connect(database_url) except psycopg.OperationalError as exc: last_error = exc await asyncio.sleep(1) raise SystemExit(f"database is not reachable: {type(last_error).__name__}") async def main() -> None: settings = load_settings() sql = MIGRATION_FILE.read_text(encoding="utf-8") conn = await wait_for_database(settings.database_url) async with conn: async with conn.cursor() as cur: await cur.execute("SELECT pg_advisory_lock(%s)", (ADVISORY_LOCK_ID,)) try: for statement in statements(sql): await cur.execute(statement) await cur.execute( "INSERT INTO schema_migrations (version) VALUES (%s) ON CONFLICT DO NOTHING", (MIGRATION_VERSION,), ) finally: await cur.execute("SELECT pg_advisory_unlock(%s)", (ADVISORY_LOCK_ID,)) await conn.commit() print(f"migrations applied: {MIGRATION_VERSION}") if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: sys.exit(130)