velofy/migrations/env.py

47 lines
1.4 KiB
Python

"""Configure Alembic's migration environment."""
import os
from logging import config as log_config
import sqlalchemy as sa
from alembic import context
from velofy import config as pkg_config
from velofy import db
# Disable the --sql option, a.k.a, the "offline mode"
if context.is_offline_mode():
msg = "The --sql option is not implemented in this project"
raise NotImplementedError(msg)
# Set up the default Python logger from the alembic.ini file
log_config.fileConfig(context.config.config_file_name)
def include_object(obj, _name, type_, _reflected, _compare_to):
"""Only include the clean schema into --autogenerate migrations."""
return not (
type_ in {"table", "column"}
and hasattr(obj, "schema") # => Fix for rare edge case
and obj.schema != pkg_config.CLEAN_SCHEMA
)
# Without a `pool`, the `connection` really closes after the migrations
engine = sa.create_engine(pkg_config.DATABASE_URI, poolclass=sa.pool.NullPool)
test_schema = f"_{pkg_config.CLEAN_SCHEMA}" if os.getenv("TESTING") else ""
with engine.connect() as connection:
context.configure(
connection=connection,
include_object=include_object,
target_metadata=db.Base.metadata,
version_table=f"{pkg_config.ALEMBIC_TABLE}{test_schema}",
version_table_schema=pkg_config.ALEMBIC_TABLE_SCHEMA,
)
with context.begin_transaction():
context.run_migrations()