首页 > 解决方案 > SQLAlchemy/FastAPI:TestClient 如何测试序列(使用 sqlite)

问题描述

我正在使用此处描述的 FastAPI TestClient 。工作正常,除了创建资源,因为我使用 ID 列的序列:

ItemID = Column(
    BigInteger,
    Sequence("item_id_seq"),
    index=True,
    primary_key=True,
    nullable=False,
)

我知道 sqlite 不支持音序器。所以它只是被忽略了。但是在创建项目时,我得到一个 NULL 约束异常,因为 ID 从未设置。

有解决方法吗?是否有用于此类测试的替代 SQL 数据库?

标签: sqlitesqlalchemyfastapi

解决方案


基于@rfkortekaas 的评论(所有功劳归他所有):我们现在使用AUTOINCREMENT而不是Sequence。由于这是primary_key为整数时的默认设置,因此以下内容就足够了:

ItemID = Column(
    BigIntegerType,
    index=True,
    primary_key=True,
)

由于这不适用于BigInteger和 sqlite,我们使用我们自己的数据类型 ( BigIntegerType ),因此在生产环境中的 MS SQL Server 上使用 BigInteger,在 sqlite 中使用 Integer 进行测试:

BigIntegerType = BigInteger()
BigIntegerType = BigIntegerType.with_variant(sqlite.INTEGER(), "sqlite")

推荐阅读