forked from mtusi2026/mtusi2026lab4
24 lines
1.1 KiB
Python
24 lines
1.1 KiB
Python
"""Run once before API instances; transactional and advisory-lock coordinated migrations."""
|
|
import os
|
|
from pathlib import Path
|
|
import psycopg
|
|
|
|
MIGRATIONS = Path(__file__).resolve().parents[1] / "db" / "migrations"
|
|
|
|
def main():
|
|
with psycopg.connect(os.environ["DATABASE_URL"], autocommit=False) as conn:
|
|
with conn.transaction():
|
|
conn.execute("SELECT pg_advisory_xact_lock(62132103)")
|
|
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
|
|
for path in sorted(MIGRATIONS.glob("[0-9]*.sql")):
|
|
applied = conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
|
if applied:
|
|
continue
|
|
conn.execute(path.read_text(encoding="utf-8"))
|
|
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (path.name,))
|
|
print("Applied", path.name, flush=True)
|
|
print("Migrations up to date", flush=True)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|