python data_error ai_generated true

sqlalchemy.exc.StaleDataError: 对 'users' 表的 UPDATE 语句预期更新 1 行,但实际匹配到 0 行。

sqlalchemy.exc.StaleDataError: UPDATE statement on table 'users' expected to update 1 row(s); 0 were matched.

ID: python/sqlalchemy-stale-data-race

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-05-20首次发现

版本兼容性

版本状态引入弃用备注
1.4.x active
2.0.x active

根因分析

在 SELECT 和 UPDATE 之间,另一个事务删除或修改了该行,导致 ORM 的版本检查或行计数失败。

English

Another transaction deleted or modified the row between the SELECT and UPDATE, causing the ORM's version check or rowcount to fail.

generic

解决方案

  1. 90% 成功率
    Implement optimistic locking with version_id_col: class User(Base): __mapper_args__ = {'version_id_col': version}
  2. 85% 成功率
    Catch StaleDataError and retry the whole transaction with fresh data: for attempt in range(3): try: update() break except StaleDataError: session.rollback()

无效尝试

常见但无效的做法:

  1. 70% 失败

    Autoflush doesn't affect the underlying row version; the issue is concurrent modification, not flush timing.

  2. 60% 失败

    Refresh may still see stale data if the other transaction hasn't committed yet; it doesn't solve the race condition.