Files
mtusi2026lab2/app/migrate.py
T

38 lines
1.6 KiB
Python

"""Apply numbered migrations atomically; safe to repeat and serialize."""
import hashlib
from pathlib import Path
import psycopg
from .config import secret
ROOT = Path(__file__).resolve().parents[1]
def migrate():
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=2,
options="-c statement_timeout=10000 -c lock_timeout=5000") as conn:
conn.execute("SELECT pg_advisory_xact_lock(202602)")
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY, sha256 text NOT NULL,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp())""")
for path in sorted((ROOT / "migrations").glob("[0-9]*.sql")):
# Git checkout may change LF to CRLF on Windows; SQL is unchanged.
content = path.read_text(encoding="utf-8").encode("utf-8")
checksum = hashlib.sha256(content).hexdigest()
row = conn.execute("SELECT sha256 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
if row:
if row[0] != checksum:
raise RuntimeError("Applied migration checksum differs: " + path.name)
print("Unchanged:", path.name)
continue
conn.execute(content.decode("utf-8"))
conn.execute("INSERT INTO schema_migrations(version, sha256) VALUES (%s, %s)",
(path.name, checksum))
print("Applied:", path.name)
print("PASS: migrations committed")
if __name__ == "__main__":
migrate()