from __future__ import annotations import asyncio import logging import sys from pathlib import Path import asyncpg from app import config logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") logger = logging.getLogger("migrate") MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" LOCK_ID = 2026_0002 async def connect_with_retry(attempts: int = 30) -> asyncpg.Connection: for attempt in range(1, attempts + 1): try: return await asyncpg.connect(config.DATABASE_URL, timeout=config.DB_CONNECT_TIMEOUT) except (OSError, asyncpg.PostgresError, asyncpg.InterfaceError) as exc: logger.warning("database not reachable (attempt %d/%d): %s", attempt, attempts, type(exc).__name__) await asyncio.sleep(1) raise SystemExit("database is not reachable") async def migrate() -> int: if not config.DATABASE_URL: raise SystemExit("DATABASE_URL or DATABASE_URL_FILE is required") conn = await connect_with_retry() applied_now = 0 try: await conn.execute("SELECT pg_advisory_lock($1)", LOCK_ID) await conn.execute( """ CREATE TABLE IF NOT EXISTS schema_migrations ( version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now() ) """ ) done = {r["version"] for r in await conn.fetch("SELECT version FROM schema_migrations")} for path in sorted(MIGRATIONS_DIR.glob("*.sql")): version = path.stem if version in done: continue logger.info("applying %s", version) async with conn.transaction(): await conn.execute(path.read_text(encoding="utf-8")) await conn.execute("INSERT INTO schema_migrations (version) VALUES ($1)", version) applied_now += 1 logger.info("migrations up to date: %d applied now, %d before", applied_now, len(done)) finally: await conn.execute("SELECT pg_advisory_unlock($1)", LOCK_ID) await conn.close() return applied_now if __name__ == "__main__": asyncio.run(migrate()) sys.exit(0)