Files
2026-09-30 12:13:29 +03:00

79 lines
2.0 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"
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 migrate() -> None:
connection = await asyncpg.connect(
plain_postgres_url(read_database_url())
)
try:
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())