在Alembic后处理中修改ForeignKeyConstraint模式

时间:2019-06-19 04:43:08

标签: python-3.x sqlalchemy alembic

我正在使用process_revision_directives对根据参考模式生成的操作进行一些后处理。我一直坚持要从指令中删除postgres模式,因此可以使用another question的答案在运行时进行一般性的更改。

以下代码正确地从ForeignKeyConstraints中的CreateTableOp中删除了该模式。

def process_foreign_key(col: sa.ForeignKeyConstraint):
    col.referred_table.schema = None  # Doesn't work


def process_revision_directives(context, revision, directives):
    # Remove the schema from the generated operations
    for op in chain(directives[0].upgrade_ops.ops, directives[0].downgrade_ops.ops):
        if isinstance(op, ops.CreateTableOp):
            op.columns = [
                process_foreign_key(col) if isinstance(col, sa.ForeignKeyConstraint) else col
                for col in op.columns
            ]
        op.schema = None

这当前会生成类似

的输出
op.create_table('user',
    sa.Column('id', sa.Integer, nullable=False),
    sa.ForeignKeyConstraint(['id'], ['reference_schema.group.id'], name='group_group_id', onupdate='CASCADE', ondelete='CASCADE'),
)

关于如何修改这些约束对象以使目标表中没有reference_schema.的任何想法?

1 个答案:

答案 0 :(得分:1)

如果您查看渲染链,则可以找到最后一个架构引用的位置。它在docker build -t my-redis:latest . docker run -p 6379:6379 my-redis:latest 上,但重要的是在此表上两次。

将以下内容放入您的op._orig_table循环中。

for

其中op._orig_table.schema = None op._orig_table = op._orig_table.tometadata(clear_meta) 是一个没有模式的clear_meta对象,例如

MetaData