首页  >  问答  >  正文

Alembic - 使用复合主键在MySQL中导致表定义不正确的问题

<p>我有多个使用复合主键的“versioned”数据库SQLAlchemy模型,通过组合自增整型字段(“id”)和日期时间字段(“record_valid_from”)来实现。我正在尝试在本地的Docker容器中运行这个模型对MySQL数据库进行设置。</p><p>模型定义大致如下:</p><p><br /></p> <pre class="brush:php;toolbar:false;">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</pre> <p>其他模型看起来类似,它们之间有各种不同的关系。</p><p>当使用Alembic自动生成迁移脚本(alembic revision --autogenerate -m "init database")时,生成的Python代码似乎会产生无效的SQL语句。</p><p>更具体地说,我遇到了:</p><p><br /></p> <pre class="brush:php;toolbar:false;">(pymysql.err.OperationalError) (1075, 'Incorrect table definition; there can be only one auto column and it must be defined as a key')</pre> <p>以下是迁移代码(注意:我对其进行了简化):</p> <pre class="brush:php;toolbar:false;">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)</pre> <p>有人经历过类似的情况吗?或者知道如何解决这个问题吗?</p><p>我尝试过以下方法:</p><p><br /></p> <ul> <li>在创建表后调用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, '定义了多个主键')。<code></code></li> <li>移除sa.PrimaryKeyConstraint然后直接调用op.create_primary_key。结果: <ul> <li>迁移成功正常运行。</li> <li>尝试创建一个新的ORM模型导致了以下错误:sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1364, "字段'id'没有默认值")。<code></code></li> </ul> </li> </ul><p><br /></p>
P粉183077097P粉183077097428 天前557

全部回复(1)我来回复

  • P粉921165181

    P粉9211651812023-07-25 14:49:14

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

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

    希望这可以帮到你。


    回复
    0
  • 取消回复