python
config_error
ai_generated
true
sqlite3.IntegrityError: 外键约束失败
sqlite3.IntegrityError: FOREIGN KEY constraint failed
ID: python/sqlalchemy-sqlite-foreign-key-off
80%修复率
85%置信度
0证据数
2024-01-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.4.x | active | — | — | — |
| 2.0.x | active | — | — | — |
根因分析
SQLite 默认不强制执行外键约束,除非设置 PRAGMA foreign_keys=ON;但如果关闭,引用完整性可能被违反,当打开时,现有错误数据会导致错误。
English
SQLite by default does not enforce foreign key constraints unless PRAGMA foreign_keys=ON is set; but if it's off, referential integrity can be violated, and when turned on, existing bad data causes errors.
解决方案
-
90% 成功率
Enable foreign key enforcement per connection: from sqlalchemy import event; @event.listens_for(engine, 'connect') def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor(); cursor.execute('PRAGMA foreign_keys=ON'); cursor.close() -
80% 成功率
Clean up orphaned records before enabling FK constraints.
无效尝试
常见但无效的做法:
-
90% 失败
Data inconsistency persists.
-
60% 失败
May lose data and doesn't fix the root cause.