I am attempting to use foreign key support in SQLite to maintain referential integrity on a single-table database that has a reflexive join.
e.g.
PRAGMA foreign_keys = ON;
create table tree (
objectId text unique not null,
parentObjectID text,
foreign key (parentObjectID) references tree(parentObjectID) on delete cascade
)
The behavior that I am hoping for is that when a parent row is deleted, its children and their children are deleted as well.
However, when I attempt to delete the root row (where the expected behavior would be that every other row in the database is also deleted), I get this error:
sqlite> delete from tree where objectid = '0';
Error: foreign key mismatch
Are my expectations out of whack with with SQLite foreign key support (and delete behaviors) can provide?
Your problem is pretty simple, your FK on
parentObjectIdreferencesparentObjectIdrather thanobjectIdand SQLite doesn’t detect this bit of confusion until you try to use the table. If your FK is defined like this:From the fine manual:
The third point would seem to apply here since
parentObjectIdis neither a PK nor constrained to be unique so that’s why you don’t see an error until you try to modify the table’s content (i.e. use a DML statement rather than a DDL statement).