forked from mtusi2026/mtusi2026lab2
47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
"""Transactional, checksummed migrations, serialized across concurrent starts."""
|
|
|
|
import hashlib
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import psycopg
|
|
|
|
from messenger.settings import secret
|
|
|
|
|
|
def migrate(conninfo: str, directory: Path):
|
|
with psycopg.connect(conninfo, connect_timeout=5) as conn:
|
|
conn.execute("SELECT pg_advisory_xact_lock(2301002)")
|
|
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")):
|
|
content = path.read_text()
|
|
checksum = hashlib.sha256(content.encode()).hexdigest()
|
|
current = conn.execute(
|
|
"SELECT checksum FROM schema_migrations WHERE version=%s", (path.stem,)
|
|
).fetchone()
|
|
if current:
|
|
if current[0] != checksum:
|
|
raise RuntimeError("Applied migration checksum changed: " + path.stem)
|
|
continue
|
|
conn.execute(content)
|
|
conn.execute(
|
|
"INSERT INTO schema_migrations (version,checksum) VALUES (%s,%s)",
|
|
(path.stem, checksum),
|
|
)
|
|
print("Applied migration " + path.stem)
|
|
|
|
|
|
def main():
|
|
migrate(
|
|
secret("DATABASE_URL_FILE", "/run/secrets/database_url"),
|
|
Path(os.getenv("MIGRATIONS_DIR", "/app/migrations")),
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|