Files
mtusi2026lab5/src/migrate.py
T

17 lines
910 B
Python

"""One-shot migrations, serialized and recorded in PostgreSQL."""
from pathlib import Path
import psycopg
from .database import get_database_url
with psycopg.connect(get_database_url()) as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(310026)")
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())")
for path in sorted((Path(__file__).resolve().parents[1] / "db/migrations").glob("*.sql")):
if not conn.execute("SELECT 1 FROM schema_migrations WHERE name=%s", (path.name,)).fetchone():
conn.execute(path.read_text())
conn.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (path.name,))
print("Applied", path.name, flush=True)
else:
print("Already applied", path.name, flush=True)