Files
mtusi2026lab5/app/migrate.py
T

84 lines
2.3 KiB
Python

from __future__ import annotations
import hashlib
import os
from pathlib import Path
import psycopg
MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
MIGRATION_LOCK_ID = 202602001
def apply_migrations() -> None:
files = sorted(MIGRATIONS_DIR.glob("[0-9]*_*.sql"))
if not files:
raise RuntimeError("Migration files not found")
with psycopg.connect(
host=os.getenv("PGHOST", "postgres"),
port=int(os.getenv("PGPORT", "5432")),
dbname=os.getenv("PGDATABASE", "messenger"),
user=os.getenv("PGUSER", "messenger"),
password=os.environ["PGPASSWORD"],
connect_timeout=5,
options="-c statement_timeout=30000 -c lock_timeout=10000",
) as conn:
conn.execute(
"SELECT pg_advisory_xact_lock(%s)",
(MIGRATION_LOCK_ID,),
)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
checksum TEXT NOT NULL,
applied_at TIMESTAMPTZ NOT NULL
DEFAULT clock_timestamp()
)
"""
)
for path in files:
version = path.name
content = path.read_bytes()
checksum = hashlib.sha256(content).hexdigest()
row = conn.execute(
"""
SELECT checksum
FROM schema_migrations
WHERE version = %s
""",
(version,),
).fetchone()
if row is not None:
if row[0] != checksum:
raise RuntimeError(
f"Applied migration was modified: {version}"
)
print(f"Already applied: {version}", flush=True)
continue
conn.execute(content.decode("utf-8"), prepare=False)
conn.execute(
"""
INSERT INTO schema_migrations (version, checksum)
VALUES (%s, %s)
""",
(version, checksum),
)
print(f"Executed: {version} (pending commit)", flush=True)
print("Migrations committed successfully", flush=True)
if __name__ == "__main__":
apply_migrations()