Files
mtusi2026lab3/src/migrate.py
T
2026-10-29 13:00:25 +03:00

40 lines
1.5 KiB
Python

"""Версионируемые миграции с проверкой checksum и блокировкой."""
import hashlib
from pathlib import Path
from src import db
DIRECTORY = Path(__file__).resolve().parents[1] / "migrations"
def apply():
applied = []
with db.connection() as conn:
conn.execute("SELECT pg_advisory_xact_lock(202602)")
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 sorted(DIRECTORY.glob("*.sql")):
checksum = hashlib.sha256(path.read_bytes()).hexdigest()
existing = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
if existing:
if existing["checksum"] != checksum:
raise RuntimeError("Изменена применённая миграция: " + path.name)
continue
conn.execute(path.read_text(), prepare=False)
conn.execute("INSERT INTO schema_migrations(version, checksum) VALUES (%s, %s)", (path.name, checksum))
applied.append(path.name)
return applied
if __name__ == "__main__":
db.pool.open(wait=True, timeout=15)
try:
print("Migrations:", ", ".join(apply()) or "already applied")
finally:
db.pool.close()