"""Versioned SQL migrations: `python -m messenger.migrate` (compose service `migrate`). * Files `migrations/NNNN_name.sql` are applied in name order, each in its own transaction together with its row in `schema_migrations` (DDL is transactional in PostgreSQL, so a failed migration leaves nothing behind). * Re-running is safe: applied versions are skipped, so data is never duplicated. * The SHA-256 of every applied file is stored; if an applied file was edited later, the run stops instead of silently diverging from the real schema. * `pg_advisory_lock` serialises concurrent runs (two API replicas starting at once). """ from __future__ import annotations import hashlib import sys import time from pathlib import Path import psycopg from .config import ConfigError, _secret MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / "migrations" LOCK_ID = 2026_02 # arbitrary application-wide advisory lock id def say(text: str) -> None: print(f"migrate: {text}", flush=True) def connect(url: str, wait_seconds: float = 60) -> psycopg.Connection: deadline = time.monotonic() + wait_seconds while True: try: return psycopg.connect(url, autocommit=True, connect_timeout=3, application_name="messenger-migrate") except psycopg.OperationalError as exc: if time.monotonic() > deadline: raise SystemExit(f"migrate: database is not reachable: {type(exc).__name__}") from None time.sleep(1) def main() -> int: try: url = _secret("DATABASE_URL", required=True) except ConfigError as exc: print(f"configuration error: {exc}", file=sys.stderr) return 2 files = sorted(MIGRATIONS_DIR.glob("*.sql")) with connect(url) as conn: conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,)) try: conn.execute( "CREATE TABLE IF NOT EXISTS schema_migrations (" " version text PRIMARY KEY, checksum text NOT NULL," " applied_at timestamptz NOT NULL DEFAULT now())") applied = dict(conn.execute("SELECT version, checksum FROM schema_migrations").fetchall()) for path in files: version, sql = path.stem, path.read_bytes() checksum = hashlib.sha256(sql).hexdigest() if version in applied: if applied[version] != checksum: say(f"{version}: file changed after it was applied; create a new migration instead") return 1 say(f"{version}: already applied, skipped") continue with conn.transaction(): conn.execute(sql.decode("utf-8")) conn.execute("INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)", (version, checksum)) say(f"{version}: applied") finally: conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,)) say(f"done, {len(files)} migration file(s) checked") return 0 if __name__ == "__main__": sys.exit(main())