from __future__ import annotations import asyncio import os from pathlib import Path from sqlalchemy import pool from sqlalchemy.ext.asyncio import async_engine_from_config from alembic import context from app.repository import postgres_ssl_context def migration_url() -> str: path = os.getenv("BITRIX_SYNC_MIGRATION_DATABASE_URL_FILE") if not path: raise RuntimeError("BITRIX_SYNC_MIGRATION_DATABASE_URL_FILE is required") value = Path(path).read_text(encoding="utf-8").rstrip("\r\n") if not value: raise RuntimeError("Bitrix migration database URL file is empty") return value def run_migrations_offline() -> None: context.configure( url=migration_url(), target_metadata=None, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations() async def run_async_migrations() -> None: configuration = context.config.get_section(context.config.config_ini_section) or {} configuration["sqlalchemy.url"] = migration_url() engine = async_engine_from_config( configuration, prefix="sqlalchemy.", poolclass=pool.NullPool, connect_args={"ssl": postgres_ssl_context()}, ) def run_sync_migrations(connection) -> None: context.configure(connection=connection, target_metadata=None, compare_type=True) with context.begin_transaction(): context.run_migrations() async with engine.connect() as connection: await connection.run_sync(run_sync_migrations) await engine.dispose() if context.is_offline_mode(): run_migrations_offline() else: asyncio.run(run_async_migrations())