forked from mtusi2026/mtusi2026lab3
lab3 load balancer haproxy
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply SQL migrations once, before any API replica is started."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import time
|
||||
import psycopg
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CONNINFO = os.getenv("DATABASE_URL", "")
|
||||
|
||||
def main():
|
||||
last_error = None
|
||||
for _ in range(30):
|
||||
try:
|
||||
with psycopg.connect(CONNINFO, connect_timeout=3) as conn:
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
|
||||
conn.commit()
|
||||
for path in sorted((ROOT / "migrations").glob("*.sql")):
|
||||
version = path.name
|
||||
if conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (version,)).fetchone():
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
with conn.transaction():
|
||||
for statement in sql.split(";"):
|
||||
if statement.strip():
|
||||
conn.execute(statement)
|
||||
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (version,))
|
||||
print(f"APPLIED {version}", flush=True)
|
||||
print("PASS: migrations complete", flush=True)
|
||||
return
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
time.sleep(1)
|
||||
raise SystemExit(f"Migration failed after retries: {type(last_error).__name__}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user