Files
mtusi2026lab2/src/app/migrate.py
T
dawuduk 7329d94740
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / application (pull_request) Canceled after 0s
finished
2026-11-06 20:40:12 +03:00

39 lines
1.2 KiB
Python

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,
)