Alembic 忽略特定表

Alembic ignore specific tables

我正在使用 alembic 根据用户定义的 sqlalchemy 模型管理数据库迁移。我的挑战是 我希望 alembic 忽略对特定 table 集合的任何创建、删除或更改。

注意:我的问题类似于这个问题但不同之处在于我想从模型定义之外控制蒸馏器。

这是一个示例table我想忽略:

from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(metadata=MetaData())

class Ignore1(Base):
    """
    Signed in to the account...
    """
    __tablename__ = 'ignore_1'
    __table_args__ = {
        'info':{'skip_autogenerate':True}
        }
    id = Column(Integer, primary_key=True)
    foo = Column(String(20), nullable=True)

示例代码(没有解决我的问题):
alembic/env.py

# Ideally this is stored in my actual database, but for now, let's assume we have a list...
IGNORE_TABLES = ['ignore_1', 'ignore_2']

def include_object(object, name, type_, reflected, compare_to):
    """
    Should you include this table or not?
    """

    if type_ == 'table' and (name in IGNORE_TABLES or object.info.get("skip_autogenerate", False)):
        return False

    elif type_ == "column" and object.info.get("skip_autogenerate", False):
        return False

    return True

# Then add to config
context.configure(
    ...
    include_object=include_object,
    ...
    )

我找到了解决问题的方法!

我的错误是在 env.py

中实例化我的 context 对象
def run_migrations_offline():
    ...
    context.configure(
        url=url,
        target_metadata=target_metadata,
        include_object=include_object,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()

我没有将此更改应用于在线迁移的上下文:

def run_migrations_online():
    ...
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
            # THE FOLLOWING LINE WAS MISSING FROM MY ORIGINAL CODE
            include_object=include_object, # <----------------------- THIS!
        )
    ...

希望遇到此问题并经历类似动荡的其他任何人都可以通读我的问题和以下解决方案,并认识到绝望只是救赎中的一个小愚蠢的调整。