python-3.x - 在 Alembic 后处理中修改foreignkeyconstraint模式

标签 python-3.x sqlalchemy alembic

我正在使用process_revision_directives对引用模式生成的操作进行一些后处理。我坚持的一个问题是从说明中删除 postgres 架构,因此可以使用 another question 中的答案在运行时一般更改它。 .

以下代码正确地从 CreateTableOp 中除 ForeignKeyConstraints 之外的操作中删除架构。

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. 有什么想法吗?

最佳答案

如果您查看渲染链,您可以找到最后一个架构引用的位置。它位于 op._orig_table 上,但重要的是它在该表上出现了两次。

将以下内容放入 for 循环中。

op._orig_table.schema = None
op._orig_table = op._orig_table.tometadata(clear_meta)

其中clear_meta是一个没有架构的MetaData对象,例如

clear_meta = sa.MetaData(bind=session.connection(), schema=None)

关于python-3.x - 在 Alembic 后处理中修改foreignkeyconstraint模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56660181/

相关文章:

python - 分发依赖于包的 Python 脚本

python - Django 通过列表中的值从数据库中查找项目?

python - Flask-SQLAlchemy关联表

python - 以 SQLAlchemy 有效的方式处理一对多关系

python - 如何在 Alembic/SQLAlchemy 中使用 USING 子句?

python - Python 中的可选链接

python - SelectField WTforms 无效选择和 sa_instance_state

python - 当我希望通过升级内的 Session 对象更改数据时,如何测试 alembic 迁移?

python - Flask-Migrate/Alembic 未使用基类和多文件结构检测模型

python-3.x - 没有名为 NaiveBayes 的模块