import hashlib import logging from pathlib import Path import psycopg from .config import secret def migrate(): files = sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql")) if not files: raise RuntimeError("No migrations found") with psycopg.connect(secret("DATABASE_URL_FILE"), connect_timeout=5) as connection: with connection.transaction(): connection.execute("SELECT pg_advisory_xact_lock(230402)") connection.execute(""" CREATE TABLE IF NOT EXISTS schema_migrations ( version text PRIMARY KEY, checksum char(64) NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp() ) """) for file in files: content = file.read_text(encoding="utf-8") checksum = hashlib.sha256(content.encode("utf-8")).hexdigest() with connection.transaction(): connection.execute("SELECT pg_advisory_xact_lock(230402)") old = connection.execute( "SELECT checksum FROM schema_migrations WHERE version = %s", (file.name,) ).fetchone() if old: if old[0] != checksum: raise RuntimeError("Applied migration was changed") print("Already applied: " + file.name, flush=True) continue connection.execute(content) connection.execute( "INSERT INTO schema_migrations(version, checksum) VALUES (%s, %s)", (file.name, checksum), ) print("Applied: " + file.name, flush=True) if __name__ == "__main__": try: migrate() except Exception as error: logging.error("Migration failed: %s", type(error).__name__) raise SystemExit(1)