"""Alembic environment. The database URL and the metadata come from the application itself, so a migration can never drift from the models the app actually uses. """ from __future__ import annotations from logging.config import fileConfig from sqlalchemy import engine_from_config, pool # Importing the ORM module registers every table on Base.metadata. import app.infrastructure.db.models # noqa: F401,E402 from alembic import context from app.core.config import settings from app.core.database import Base config = context.config if config.config_file_name is not None: fileConfig(config.config_file_name) target_metadata = Base.metadata def _sync_url() -> str: """Alembic runs synchronously; strip the async driver from the URL.""" url = settings.database_url return ( url.replace("+aiosqlite", "") .replace("+asyncpg", "+psycopg") .replace("+psycopg_async", "+psycopg") ) def run_migrations_offline() -> None: context.configure( url=_sync_url(), target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, compare_type=True, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: section = config.get_section(config.config_ini_section) or {} section["sqlalchemy.url"] = _sync_url() connectable = engine_from_config( section, prefix="sqlalchemy.", poolclass=pool.NullPool ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, compare_type=True ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()