"""Alembic environment: async engine, URL from the service settings (or -x dsn=...).""" import asyncio from alembic import context from sqlalchemy.ext.asyncio import create_async_engine from estimator.infra.db.session import normalize_dsn from estimator.infra.db.tables import Base, include_object config = context.config target_metadata = Base.metadata def _dsn() -> str: override = context.get_x_argument(as_dictionary=True).get("dsn") if override: return normalize_dsn(override) from estimator.config import get_settings return normalize_dsn(get_settings().database.dsn.get_secret_value()) def _configure(connection) -> None: context.configure( connection=connection, target_metadata=target_metadata, compare_type=True, render_as_batch=connection.dialect.name == "sqlite", include_object=lambda *args: include_object(*args, dialect=connection.dialect.name), ) def _run_sync(connection) -> None: _configure(connection) with context.begin_transaction(): context.run_migrations() async def _run_online() -> None: engine = create_async_engine(_dsn()) try: async with engine.connect() as conn: await conn.run_sync(_run_sync) finally: await engine.dispose() def run_migrations_offline() -> None: context.configure( url=_dsn(), target_metadata=target_metadata, literal_binds=True, compare_type=True ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: asyncio.run(_run_online())