如何使用 alembic --autogenerate 忽略某些模式

How can I ignore certain schemas with alembic --autogenerate

我有一个图书馆,它是一个更大项目的一部分。该库在与较大项目共享的 (PostgreSQL) 数据库中使用自己的模式。

我想使用 alembic revision --autogenerate 仅为库的架构生成迁移,而忽略对 main/default 架构中的表的更改。有什么选择吗?

FWIW,我已经在 env.py 中尝试将 include_schemas=False 参数设置为 context.configure,但它似乎没有任何作用。

看来我可以将 include_objectinclude_schemas

结合使用

alembic/env.py中:

def include_object(object, name, type_, reflected, compare_to):
    if type_ == 'table' and object.schema != MY_SCHEMA:
        return False

    return True

...
context.configure(..., include_object=include_object, ...)

基于 Oin 的响应,最终在 运行 db revision --autogenerate

时忽略表的方法

在alembic/env.py 或migrations/env.py:

def include_object(object, name, type_, reflected, compare_to):
    if (type_ == "table" and object.schema == "exclude_from_migrations"):
        return False
    else:
       return True

在alembic/env.py 或migrations/env.py:

def run_migrations_online():
   ....
   context.configure(connection=connection,
                  target_metadata=target_metadata,
                  include_object = include_object,
                  process_revision_directives=process_revision_directives,
                  **current_app.extensions['migrate'].configure_args)
   ...

现在在您要忽略的表格中:

class MyClass(db.Model):
__tablename__='my_class'
__table_args__ = {"schema": "exclude_from_migrations"}

尝试使用 include_namehttps://alembic.sqlalchemy.org/en/latest/api/runtime.html#alembic.runtime.environment.EnvironmentContext.configure.params.include_name

这是在 alembic==1.5 中添加的新钩子,是 autogenerate 期间过滤模式的推荐方法:

对于当 EnvironmentContext.configure.include_schemas 设置为 True 时从目标数据库中省略特定模式的用例,可以为传递给挂钩的每个 Table 对象检查模式属性,但是在使用 EnvironmentContext.configure.[=31 进行对象反射之前过滤模式更有效=]勾.

相关讨论: https://github.com/sqlalchemy/alembic/issues/650