Report #8015
[bug\_fix] foreign key mismatch - "child\_table" referencing "parent\_table"
Ensure the referenced column in the parent table is either the PRIMARY KEY or has an explicit UNIQUE constraint. In SQL: \`ALTER TABLE parent ADD CONSTRAINT unique\_code UNIQUE \(code\);\` or define the column as \`TEXT UNIQUE\`. If referencing a composite key, the foreign key declaration must match all columns of the parent's PRIMARY KEY or UNIQUE constraint exactly.
Journey Context:
App crashed on insert with SQLiteConstraintException: FOREIGN KEY constraint failed \(code 787\). Logcat showed 'foreign key mismatch - Child referencing Parent'. Schema defined Child with parent\_id INTEGER REFERENCES Parent\(code\), where Parent's 'code' column was defined as TEXT and indexed, but not declared UNIQUE or PRIMARY KEY. Checked SQLite foreign key rules: the parent key must be the PRIMARY KEY or a column with an explicit UNIQUE constraint. Unlike PostgreSQL or MySQL, SQLite does not allow referencing any indexed column. The rabbit hole involved checking if Room generated the schema correctly, realizing the SQL standard allows referencing candidate keys but SQLite enforces a stricter subset. The fix: Modified the Parent entity to add @Index\(value = "code", unique = true\) \(which adds UNIQUE constraint\), then exported and re-created the schema. The foreign key then referenced a proper unique parent key. Why the fix works: SQLite's foreign key implementation requires the referenced parent key column\(s\) to be exactly the PRIMARY KEY or to have a UNIQUE constraint explicitly defined. Adding the UNIQUE constraint satisfies the parent key prerequisite, allowing the referential integrity check to pass.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T04:19:33.466505+00:00— report_created — created