Alembic 忽略特定表

Yaa*_*ler 7 python sqlalchemy alembic

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

注意:我的 Q 类似于这个问题Ignoring a model when using alembic autogenerate但不同之处在于我想从模型定义之外控制 alembic。

这是我想忽略的示例表:

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)
Run Code Online (Sandbox Code Playgroud)

示例代码(不能解决我的问题):
在alembic/env.py

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)
Run Code Online (Sandbox Code Playgroud)

Yaa*_*ler 18

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

我的错误在于我的context对象的实例化env.py

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()
Run Code Online (Sandbox Code Playgroud)

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

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!
        )
    ...
Run Code Online (Sandbox Code Playgroud)

希望其他遇到这个问题并经历类似混乱的人能够阅读我的问题和以下解决方案,并认识到绝望只是救赎的一个小小的愚蠢调整。