forked from mtusi2026/mtusi2026lab5
49 lines
2.0 KiB
Python
49 lines
2.0 KiB
Python
"""Версионируемые миграции с проверкой checksum и блокировкой."""
|
|
import hashlib
|
|
from pathlib import Path
|
|
|
|
from src import db
|
|
|
|
|
|
DIRECTORY = Path(__file__).resolve().parents[1] / "migrations"
|
|
|
|
|
|
def check():
|
|
"""API только проверяет схему; DDL выполняет отдельный migrate-service."""
|
|
with db.connection() as conn:
|
|
for path in sorted(DIRECTORY.glob("*.sql")):
|
|
row = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
|
if row is None or row["checksum"] != hashlib.sha256(path.read_bytes()).hexdigest():
|
|
raise RuntimeError("Сначала выполните миграции: " + path.name)
|
|
|
|
|
|
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()
|