在 Alembic post 进程中修改 ForeignKeyConstraint 模式
Modfying ForeignKeyConstraint schema in Alembic post process
我正在使用 process_revision_directives to apply some post-processing of the operations generated against a reference schema. The one I'm stuck on is removing the postgres schema from the instructions, so it can be generically changed at runtime using the answer from 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'),
)
关于我应该如何修改这些约束对象以在目标 table 中没有 reference_schema.
的任何想法?
如果查看呈现链,您可以找到最后一个架构引用所在的位置。它在 op._orig_table
上,但重要的是它在 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)
我正在使用 process_revision_directives to apply some post-processing of the operations generated against a reference schema. The one I'm stuck on is removing the postgres schema from the instructions, so it can be generically changed at runtime using the answer from 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'),
)
关于我应该如何修改这些约束对象以在目标 table 中没有 reference_schema.
的任何想法?
如果查看呈现链,您可以找到最后一个架构引用所在的位置。它在 op._orig_table
上,但重要的是它在 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)