当表的模式与引用的列不同时, Alembic删除并创建外键约束(自动生成)



我正在尝试使用alembic的自动生成功能来更新MSSQL数据库的模式。

class Table1(Base):
__tablename__ = "table1"
__table_args__ = (
PrimaryKeyConstraint("ID", name="PK_Table1"),
)
ID = Column(Integer, nullable=False)
class Table2(Base):
__tablename__ = "table2"
__table_args__ = (
ForeignKeyConstraint(['Table1ID'], ['Table1.ID'], name='fk_Table2_Table1')
{'schema': 'foo'}
)
Table1ID = Column(Integer, nullable=False)
Table1_ = relationship('Table1', back_populates='Table2')

执行命令alembic revision --autogenerate后,我得到的upgrade()函数如下:

def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('fk_Table2_Table1', 'Table2', schema='foo', type_='foreignkey')
op.create_foreign_key('fk_Table2_Table1', 'Table2', 'Table1', ['Table1ID'], ['ID'], source_schema='foo')
# ### end Alembic commands ###

深入研究代码后,我发现当alembic比较代码中模式和模型之间的外键时,sqlalchemy将dbo模式强制到表1。ID引用列:

数据库外键:("foo"、"表"("Table1ID")、"dbo","表1",("ID"),没有,没有,没有可延期的)

模型外键:("foo"、"表"("Table1ID"),"表1",("ID"),没有,没有,没有可延期的)

这个差异导致稍后在upgrade()函数中删除和创建命令。如果我在__table_args__中删除{'schema': 'foo'},问题就消失了,所以我的猜测是表模式(不同于默认模式)强制外键引用上的模式。

我想知道是否有办法克服这个问题。

我也面临这个问题。也没能找到答案。现在我只是编辑alembic生成的代码,并做数据库升级。但是这是非常烦人的重复的事情,尤其是当表格变大的时候。

最新更新