Alembic 无法检测唯一约束

问题描述 投票:0回答:1

我正在使用 tiangolo sqlmodel,在我的数据库模型中我想添加唯一约束,因此一个是业务密钥,另一个用于映射表 - 两者都不能被 alembic 识别。

业务键位于基表中(因为所有非映射表都继承自此类),如下所示:

class BusinessKeyModel(PydanticBase):
    businessKey: Optional[str] = Field(
        alias="businessKey",
        max_length=255,
        description=DescriptionConstants.BUSINESS_KEY,
        nullable=True,
        unique=True  # <-- added this before generating new migration
    )

class BaseTableModel(SQLModel, BusinessKeyModel):
    ...

class User(GUIDModel, BaseTableModel):
    guid: Optional[UUID] = Field(
        ...,
        primary_key=True,
        description=DescriptionConstants.GUID,
        sa_column=Column(
            "guid",
            UNIQUEIDENTIFIER,
            nullable=False,
            primary_key=True,
            server_default=text("newsequentialid()"),
        ),
    )

因此,当我现在将

unique=True
添加到 BusinessKeyModel.businessKey 并尝试使用 alembic 生成新的迁移(使用自动生成)时,它不会检测到更改。

我的映射表也是如此,在我将

UniqueConstraint
添加到我的
__table_args__
中后,我认为它应该检测到更改:

class UserRoleMappingBase(BaseMappingModel, GUIDModel):

    userId: UUID
    roleId: UUID


class UserRoleMapping(UserRoleMappingBase, table=True):
    __table_args__ = (
        UniqueConstraint("userId", "roleId"), # <-- added this before generating new migration
        {"schema": "dbx_v2"}
    )
python sqlalchemy alembic sqlmodel
1个回答
0
投票

事实证明,Alembic 无法检测唯一约束的更改,至少对于 SQL Server 来说是这样。既不添加它们,也不删除它们。 无论如何要定义答案,解决方案是创建一个新的迁移并在

upgrade()
:

中手动添加它们
op.create_unique_constraint('uq_user_businessKey', 'user', ['businessKey'], schema='dbx_v2')

并在

downgrade()

op.drop_constraint('uq_user_businessKey', 'user', schema='dbx_v2')
© www.soinside.com 2019 - 2024. All rights reserved.