python config_error ai_generated true

sqlite3.IntegrityError: 外键约束失败

sqlite3.IntegrityError: FOREIGN KEY constraint failed

ID: python/sqlalchemy-sqlite-foreign-key-off

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 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()
  2. 80% 成功率
    Clean up orphaned records before enabling FK constraints.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Data inconsistency persists.

  2. 60% 失败

    May lose data and doesn't fix the root cause.