"""Atomic, serialized, versioned migrations; changed applied files are rejected.""" import hashlib import os from pathlib import Path import psycopg with psycopg.connect(Path(os.environ["DATABASE_URL_FILE"]).read_text().strip()) as conn: conn.execute("SELECT pg_advisory_xact_lock(20260002)") conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL)") for path in sorted(Path("migrations").glob("*.sql")): sql = path.read_text() digest = hashlib.sha256(sql.encode()).hexdigest() row = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone() if row: if row[0] != digest: raise RuntimeError("Applied migration changed: " + path.name) continue conn.execute(sql) conn.execute("INSERT INTO schema_migrations VALUES (%s,%s)", (path.name,digest)) print("Applied", path.name) print("Migrations OK")