Alembic - 使用复合主键在MySQL中导致表定义不正确的问题
P粉183077097
P粉183077097 2023-07-24 22:17:01
0
1
496

我有多个使用复合主键的“versioned”数据库SQLAlchemy模型,通过组合自增整型字段(“id”)和日期时间字段(“record_valid_from”)来实现。我正在尝试在本地的Docker容器中运行这个模型对MySQL数据库进行设置。

模型定义大致如下:


from sqlalchemy.orm import (DeclarativeBase, Mapped) class classA(DeclarativeBase): id: Mapped[int] = mapped_column(primary_key=True, index=True, autoincrement=True) record_valid_from: Mapped[datetime] = mapped_column(DateTime, primary_key=True, default=get_current_timestamp # this is a python method returning datetime.now() ) active: Mapped[bool] = mapped_column(Boolean, default=True, comment="TRUE if latest version, FALSE otherwise" ) ... # some more fields and logic

其他模型看起来类似,它们之间有各种不同的关系。

当使用Alembic自动生成迁移脚本(alembic revision --autogenerate -m "init database")时,生成的Python代码似乎会产生无效的SQL语句。

更具体地说,我遇到了:


(pymysql.err.OperationalError) (1075, 'Incorrect table definition; there can be only one auto column and it must be defined as a key')

以下是迁移代码(注意:我对其进行了简化):

def upgrade() -> None: op.create_table('classA', sa.Column('name', sa.String(length=100), nullable=False), sa.Column('record_valid_from', sa.DateTime(), nullable=False), sa.Column('active', sa.Boolean(), nullable=False), sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.PrimaryKeyConstraint('record_valid_from', 'id') ) op.create_index(op.f('ix_classA_id'), 'classA', ['id'], unique=False)

有人经历过类似的情况吗?或者知道如何解决这个问题吗?

我尝试过以下方法:


  • 在创建表后调用op.create_primary_key(参见:https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.create_primary_key)。结果:sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1068, '定义了多个主键')。
  • 移除sa.PrimaryKeyConstraint然后直接调用op.create_primary_key。结果:
    • 迁移成功正常运行。
    • 尝试创建一个新的ORM模型导致了以下错误:sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1364, "字段'id'没有默认值")。


P粉183077097
P粉183077097

全部回复 (1)
P粉921165181

我花了几个小时解决了这个问题,并且自己修复了它。对于遇到类似问题的人,这是答案:

实际上,主键字段在PrimaryKeyConstraint中的顺序是有影响的。我的问题是通过改变顺序来解决的,而不是使用sa.PrimaryKeyConstraint('record_valid_from', 'id'),我改成了sa.PrimaryKeyConstraint("id", "record_valid_from")。

希望这可以帮到你。


    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责声明 Sitemap
    PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!