102 lines
3.1 KiB
Python

"""Alembic environment for canonical document metadata migrations."""
from logging.config import fileConfig
from typing import Any
from alembic import context
from sqlalchemy import engine_from_config, pool
from ekp_core.config import get_settings
from ekp_domain import Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
TARGET_TABLE_NAMES = frozenset(target_metadata.tables)
def _include_name(
name: str | None,
type_: str,
parent_names: dict[str, str | None],
) -> bool:
"""Keep Alembic reflection inside EKP-owned canonical tables.
The target OceanBase database is shared with another application and
contains provider-specific VECTOR columns. Excluding unrelated tables
before reflection prevents schema checks from inspecting or proposing
changes to objects outside this repository's ownership boundary.
"""
del parent_names
return type_ != "table" or name in TARGET_TABLE_NAMES
def _include_oceanbase_object(
object_: Any,
name: str | None,
type_: str,
reflected: bool,
compare_to: Any,
) -> bool:
"""Skip constraints the stock MySQL reflector cannot parse from OceanBase.
OceanBase appends `BLOCK_SIZE ... LOCAL` to secondary constraints. SQLAlchemy
consequently reports model constraints as missing even when they exist.
Columns, types, defaults and primary keys remain in the real drift check;
constraints are covered by migration tests and targeted live invariants.
"""
del object_, name, reflected, compare_to
return type_ not in {"index", "unique_constraint", "foreign_key_constraint"}
def _database_url() -> str:
"""Allow tests to override the URL without changing runtime settings."""
override = config.attributes.get("database_url")
return override if isinstance(override, str) else get_settings().database_url.get_secret_value()
def run_migrations_offline() -> None:
"""Render migration SQL without creating an engine or connection."""
context.configure(
url=_database_url(),
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
include_name=_include_name,
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations through a short-lived SQLAlchemy engine."""
connectable = engine_from_config(
{"sqlalchemy.url": _database_url()},
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
include_name=_include_name,
include_object=(
_include_oceanbase_object if connection.dialect.name == "mysql" else None
),
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()