【发布时间】:2019-04-30 14:26:46
【问题描述】:
软件版本:alembic 1.0.5、SQLAlchemy 1.2.14、MySQL 5.7、Python 3.6.7
我正在尝试使用 alembic 来保持 MySQL 数据库架构和 Python ORM 表示的同步。
我看到的问题是迁移总是有多余的删除并为外键创建命令。似乎 autogenerate 认为某些东西有所不同,但它们实际上是相同的。
关于命令的重复调用:
alembic revision --autogenerate
alembic upgrade head
...将产生相同的 drop 和 create 命令。
记录到标准输出显示类似(例如):
INFO [alembic.autogenerate.compare] Detected removed foreign key (t1_id)(id) on table table_two
INFO [alembic.autogenerate.compare] Detected added foreign key (t1_id)(id) on table test_fktdb.table_two
迁移脚本有:
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('fk_table1', 'table_two', type_='foreignkey')
op.create_foreign_key('fk_table1', 'table_two', 'table_one', ['t1_id'], ['id'], source_schema='test_fktdb', referent_schema='test_fktdb')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('fk_table1', 'table_two', schema='test_fktdb', type_='foreignkey')
op.create_foreign_key('fk_table1', 'table_two', 'table_one', ['t1_id'], ['id'])
# ### end Alembic commands ###
这个问题可以复制,我做了一个最小的例子(https://github.com/sqlalchemy/alembic/files/2625781/FK_test.tar.gz 上的 tar.gz)。示例中的 ORM 类似于:
[...import and bobs...]
class TableOne(Base):
"""Class representing a table with an id."""
__tablename__ = "table_one"
id = Column(UNSIGNED_INTEGER, nullable=False, autoincrement=True, primary_key=True)
__table_args__ = (
dict(mysql_engine='InnoDB'),
)
class TableTwo(Base):
"""A table representing records with a foreign key link to table one."""
__tablename__ = "table_two"
id = Column(UNSIGNED_INTEGER, nullable=False, autoincrement=True, primary_key=True)
t1_id = Column(UNSIGNED_INTEGER, nullable=False)
__table_args__ = (
ForeignKeyConstraint(["t1_id"], ["test_fktdb.table_one.id"], name="fk_table1"),
dict(mysql_engine='InnoDB'),
)
有什么办法可以让 alembic “看到”数据库中的 FK 与 ORM 中的 FK 相同?例如,通过env.py 应用一些配置?
我环顾四周寻找这个问题,并在 alembic GitHub 中发现了一些旧问题(请参阅 [1]、[2]、[3])。有解决方案的问题似乎与 postgres 数据库和公开的模式有关。我不确定这是否适用于这种情况,因为我使用的是 MySQL;公共 postgres 模式的相关文档在这里:https://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#remote-schema-table-introspection-and-postgresql-search-path
我现在已将自己的问题添加到 alembic GitHub 存储库:https://github.com/sqlalchemy/alembic/issues/519
alembic 问题跟踪器中的已关闭问题,显示出类似的症状,但其解决方案不适用(据我所知):
[1]https://github.com/sqlalchemy/alembic/issues/444
【问题讨论】:
标签: python mysql sqlalchemy alembic