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
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.
解决方案
-
90% 成功率
Implement optimistic locking with version_id_col: class User(Base): __mapper_args__ = {'version_id_col': version} -
85% 成功率
Catch StaleDataError and retry the whole transaction with fresh data: for attempt in range(3): try: update() break except StaleDataError: session.rollback()
无效尝试
常见但无效的做法:
-
70% 失败
Autoflush doesn't affect the underlying row version; the issue is concurrent modification, not flush timing.
-
60% 失败
Refresh may still see stale data if the other transaction hasn't committed yet; it doesn't solve the race condition.