【问题标题】:Is it possible to deactivate the autogenerated Drop?是否可以停用自动生成的 Drop?
【发布时间】:2022-12-19 19:11:38
【问题描述】:

我正在为一个 python 项目测试 Alembic。自动生成非常好,但是如果您需要处理具有许多不同版本的客户数据库,则删除并不是很有帮助。

为不同的场景激活或停用 Dropping。这将是最好的解决方案。

我在 env.py 中做了自己的配置,所以我可以使用多个基本脚本。但是如果我创建一个新脚本(定义一个新表)并自动生成一个迁移脚本,我会自动删除所有以前迁移的表。 我已经在寻找 mako 文件了。如何在 mako 文件中集成限制?

【问题讨论】:

  • 问题是如何更改 script.py.mako 以限制自动生成的丢弃

标签: alembic


【解决方案1】:

我发现可以过滤我的迁移操作列表。 如果您将过滤列表的过滤方法移交给配置标志“process_revision_directives”。 (env.py 中的所有配置)

from alembic.operations import ops
    def process_revision_directives(context, revision, directives):
        script = directives[0]

        # process both "def upgrade()", "def downgrade()"
        for directive in (script.upgrade_ops, script.downgrade_ops):

            # now rewrite the list of "ops" such that DropColumnOp and DropTableOp
            # are removed for those tables.   Needs a recursive function.
            directive.ops = list(
                _filter_drop_elm(directive.ops)
            )



    def _filter_drop_elm(directives):
        # given a set of (tablename, schemaname) to be dropped, filter
        # out Drop-Op from the list of directives and yield the result.
        for directive in directives:
            # ModifyTableOps is a container of ALTER TABLE types of
            # commands.  process those in place recursively.
            if isinstance(directive, ops.DropTableOp):
                continue
            elif isinstance(directive, ops.ModifyTableOps):

                directive.ops = list(
                    _filter_drop_elm(directive.ops)
                )
                if not directive.ops:
                    continue

            elif isinstance(directive, ops.AlterTableOp) and isinstance(directive, ops.DropColumnOp):
                    continue

            # otherwise if not filtered, yield out the directive
            yield directive

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    相关资源
    最近更新 更多