from __future__ import annotations from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool from poorbird.config import get_settings from poorbird.models import Base from poorbird.schema_compare import COMPARE_OPTS config = context.config if config.config_file_name is not None: fileConfig(config.config_file_name) # One source of truth for the URL: the environment, via Settings. An explicit # override still wins, so tests can point a run at a scratch database. if not config.get_main_option("sqlalchemy.url", None): config.set_main_option("sqlalchemy.url", get_settings().database_url) target_metadata = Base.metadata OPTS = COMPARE_OPTS def run_migrations_offline() -> None: context.configure( url=config.get_main_option("sqlalchemy.url"), target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, **OPTS, ) with context.begin_transaction(): context.run_migrations() def _run(connection) -> None: context.configure(connection=connection, target_metadata=target_metadata, **OPTS) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: # A caller may hand us a live connection (the schema-drift test does). injected = config.attributes.get("connection", None) if injected is not None: _run(injected) return connectable = engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: _run(connection) if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()