from pathlib import Path import asyncpg MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations" async def apply_migrations(pool: asyncpg.Pool) -> None: async with pool.acquire() as conn: await conn.execute( """ CREATE TABLE IF NOT EXISTS applied_migrations ( name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now() ) """ ) applied = { row["name"] for row in await conn.fetch("SELECT name FROM applied_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 applied_migrations (name) VALUES ($1)", path.name, ) print(f"applied migration: {path.name}", flush=True)