Files
mtusi2026lab2/src/messenger/migrate.py
T

32 lines
1.1 KiB
Python

"""Apply versioned migrations under one PostgreSQL transaction and lock."""
from pathlib import Path
import psycopg
from .config import postgres_options
def main() -> None:
migrations = Path(__file__).with_name("migrations").glob("*.sql")
with psycopg.connect(**postgres_options()) as conn:
conn.execute("SELECT pg_advisory_xact_lock(202602)")
conn.execute("""
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
)
""")
applied = {row[0] for row in conn.execute("SELECT version FROM schema_migrations")}
pending = []
for path in sorted(migrations):
if path.stem not in applied:
conn.execute(path.read_text(encoding="utf-8"))
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.stem,))
pending.append(path.stem)
print("Applied: " + ", ".join(pending) if pending else "Schema is up to date")
if __name__ == "__main__":
main()