Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
99 lines
2.8 KiB
Python
99 lines
2.8 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import asyncpg
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
MIGRATIONS_DIR = ROOT / "migrations"
|
|
# Lab3: migrations run once in the "migrate" service before the API replicas
|
|
# start. The advisory lock still serialises two accidental parallel runs
|
|
# (e.g. a manual run during a rolling update); the second one then sees all
|
|
# versions in schema_migrations and only prints SKIP.
|
|
MIGRATION_LOCK_ID = 727003
|
|
|
|
|
|
def read_database_url() -> str:
|
|
file_name = os.getenv("DATABASE_URL_FILE")
|
|
|
|
if file_name:
|
|
return Path(file_name).read_text(encoding="utf-8").strip()
|
|
|
|
value = os.getenv("DATABASE_URL")
|
|
|
|
if not value:
|
|
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required.")
|
|
|
|
return value
|
|
|
|
|
|
def plain_postgres_url(url: str) -> str:
|
|
if url.startswith("postgresql+asyncpg://"):
|
|
return url.replace("postgresql+asyncpg://", "postgresql://", 1)
|
|
|
|
return url
|
|
|
|
|
|
async def connect_with_retry(url: str, attempts: int = 30):
|
|
for attempt in range(1, attempts + 1):
|
|
try:
|
|
return await asyncpg.connect(url, timeout=3)
|
|
except (OSError, asyncpg.PostgresError) as exc:
|
|
if attempt == attempts:
|
|
raise
|
|
print(f"WAIT database ({type(exc).__name__}), retry {attempt}")
|
|
await asyncio.sleep(1)
|
|
|
|
|
|
async def migrate() -> None:
|
|
connection = await connect_with_retry(
|
|
plain_postgres_url(read_database_url())
|
|
)
|
|
|
|
try:
|
|
await connection.execute(
|
|
"SELECT pg_advisory_lock($1)",
|
|
MIGRATION_LOCK_ID,
|
|
)
|
|
await connection.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version TEXT PRIMARY KEY,
|
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
)
|
|
"""
|
|
)
|
|
|
|
applied_rows = await connection.fetch(
|
|
"SELECT version FROM schema_migrations"
|
|
)
|
|
applied = {row["version"] for row in applied_rows}
|
|
|
|
for migration_file in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
|
version = migration_file.name
|
|
|
|
if version in applied:
|
|
print(f"SKIP {version}")
|
|
continue
|
|
|
|
sql = migration_file.read_text(encoding="utf-8")
|
|
|
|
print(f"APPLY {version}")
|
|
|
|
async with connection.transaction():
|
|
await connection.execute(sql)
|
|
await connection.execute(
|
|
"INSERT INTO schema_migrations (version) VALUES ($1)",
|
|
version,
|
|
)
|
|
|
|
print("PASS: migrations applied")
|
|
finally:
|
|
await connection.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(migrate()) |