from pathlib import Path import asyncpg def _migrations_dir() -> Path: here = Path(__file__).resolve().parent for candidate in (here.parent.parent / "migrations", Path("/app/migrations")): if candidate.is_dir(): return candidate raise RuntimeError("migrations directory not found") MIGRATIONS = _migrations_dir() async def apply_migrations(pool: asyncpg.Pool) -> None: async with pool.acquire() as conn: await conn.execute( """ CREATE TABLE IF NOT EXISTS schema_migrations ( filename TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now() ) """ ) applied = {row["filename"] for row in await conn.fetch("SELECT filename FROM schema_migrations")} files = sorted(p for p in MIGRATIONS.glob("*.sql") if p.is_file()) for path in files: 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(filename) VALUES($1)", path.name, )