""" Alembic environment — async engine against Base.metadata. Two entry paths: - CLI (``alembic upgrade head``): builds an async engine from Settings.database_url and runs migrations on it. - App startup (db.database.init_db): passes an already-open connection via ``config.attributes["connection"]`` so migrations run inside the app's engine instead of opening a second one. """ import asyncio from logging.config import fileConfig from alembic import context from sqlalchemy import pool from sqlalchemy.ext.asyncio import create_async_engine from config import get_settings from db.database import Base config = context.config # Only configure logging on standalone CLI runs — inside the app this # would clobber uvicorn's logger setup. if config.config_file_name is not None and config.attributes.get("connection") is None: fileConfig(config.config_file_name, disable_existing_loggers=False) target_metadata = Base.metadata def run_migrations_offline() -> None: """Emit SQL to stdout without a live connection (--sql mode).""" context.configure( url=get_settings().database_url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations() def do_run_migrations(connection) -> None: context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() async def run_async_migrations() -> None: engine = create_async_engine(get_settings().database_url, poolclass=pool.NullPool) async with engine.connect() as connection: await connection.run_sync(do_run_migrations) await engine.dispose() def run_migrations_online() -> None: connection = config.attributes.get("connection") if connection is not None: do_run_migrations(connection) else: asyncio.run(run_async_migrations()) if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()