forked from mtusi2026/mtusi2026lab2
61 lines
2.1 KiB
Python
61 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Versioned SQL migrations: applied once, checksum-verified, safe to re-run."""
|
|
import hashlib
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
|
|
import psycopg
|
|
|
|
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
|
MIGRATIONS = ROOT / "migrations"
|
|
LOCK_ID = 2026_0002
|
|
|
|
|
|
def database_url() -> str:
|
|
path = os.environ.get("DATABASE_URL_FILE")
|
|
if path:
|
|
return pathlib.Path(path).read_text(encoding="utf-8").strip()
|
|
url = os.environ.get("DATABASE_URL", "").strip()
|
|
if not url:
|
|
sys.exit("DATABASE_URL or DATABASE_URL_FILE is required")
|
|
return url
|
|
|
|
|
|
def main() -> None:
|
|
files = sorted(MIGRATIONS.glob("*.sql"))
|
|
if not files:
|
|
sys.exit("no migration files found in %s" % MIGRATIONS)
|
|
with psycopg.connect(database_url(), autocommit=True, connect_timeout=10) as conn:
|
|
conn.execute(
|
|
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
|
" version text PRIMARY KEY,"
|
|
" checksum text NOT NULL,"
|
|
" applied_at timestamptz NOT NULL DEFAULT now())"
|
|
)
|
|
conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
|
|
rows = conn.execute("SELECT version, checksum FROM schema_migrations").fetchall()
|
|
applied = {row[0]: row[1] for row in rows}
|
|
for path in files:
|
|
version = path.stem
|
|
body = path.read_text(encoding="utf-8")
|
|
checksum = hashlib.sha256(body.encode("utf-8")).hexdigest()
|
|
if version in applied:
|
|
if applied[version] != checksum:
|
|
sys.exit("migration %s changed after it was applied" % version)
|
|
print("skip %s" % version)
|
|
continue
|
|
with conn.transaction():
|
|
conn.execute(body)
|
|
conn.execute(
|
|
"INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)",
|
|
(version, checksum),
|
|
)
|
|
print("apply %s" % version)
|
|
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
|
|
print("migrations complete: %d file(s)" % len(files))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|