【问题标题】:How can I ignore certain schemas with alembic --autogenerate如何使用 alembic --autogenerate 忽略某些模式
【发布时间】:2016-05-22 09:48:00
【问题描述】:

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

我想使用alembic revision --autogenerate 只为库的架构生成迁移,并忽略对主/默认架构中的表的更改。有什么选择吗?

FWIW,我已经尝试了 env.py 中 context.configure 的 include_schemas=False 参数,但它似乎没有做任何事情。

【问题讨论】:

    标签: python sqlalchemy database-migration alembic


    【解决方案1】:

    尝试使用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.include_name 挂钩对模式进行过滤会更有效。

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

    【讨论】:

    • 是的,这实际上比上述答案更快,更不容易出错。很高兴 alembic 添加了此内容,并感谢您添加答案!
    【解决方案2】:

    基于 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"}
    

    【讨论】:

      【解决方案3】:

      看来我可以将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, ...)
      

      【讨论】:

        猜你喜欢
        • 2013-01-19
        • 2021-08-08
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        • 2017-02-16
        相关资源
        最近更新 更多