"""Alembic environment configuration. The migration runner is sync; the runtime service is async. To support a single configured ``ARTIFACTSTORE_DATABASE_URL``, this module rewrites async driver URLs (``+aiosqlite``, ``+asyncpg``) to their sync counterparts when invoking Alembic. """ from __future__ import annotations import sys from logging.config import fileConfig from pathlib import Path from alembic import context from sqlalchemy import engine_from_config, pool _ROOT = Path(__file__).resolve().parent.parent _SRC = _ROOT / "src" if str(_SRC) not in sys.path: sys.path.insert(0, str(_SRC)) from artifactstore.config import get_settings # noqa: E402 from artifactstore.db.schema import metadata as target_metadata # noqa: E402 config = context.config if config.config_file_name is not None: fileConfig(config.config_file_name) def _sync_url(url: str) -> str: """Translate an async driver URL to its sync counterpart for Alembic.""" if "+aiosqlite" in url: return url.replace("+aiosqlite", "") if "+asyncpg" in url: return url.replace("+asyncpg", "+psycopg") return url _settings = get_settings() config.set_main_option("sqlalchemy.url", _sync_url(_settings.database_url)) def run_migrations_offline() -> None: """Emit SQL without a live DB connection.""" context.configure( url=config.get_main_option("sqlalchemy.url"), target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, ) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: """Run migrations against a live DB connection.""" section = config.get_section(config.config_ini_section) or {} connectable = engine_from_config( section, prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()