I'm just teaching myself sqlite and so I was surprised to see my foreign_key
constraint not working when I was able to delete a parent entry. I then learned after reading more that the pragma for foreign_key
is off
by default for each session. Seems odd there isn't a resource file (something like .exrc for vi for example) that you can use to setup pragmas by default for each session, but fine. So I have to recompile sqlite3 or just set it every time.
Anyway, my question is, after I deleted the parent, is there a way to do a post integrity check on foreign key constraints? I.e. just tell sqlite to run the same logic it runs when it does it originally if you had the pragma turned on at the time of the insert or delete etc?
I see a pragma integrity_check
but that's just looking for corruption it seems.
Thanks, Justin
Does SQLite support referential integrity? In SQLite referential integrity constraints are used to maintain the relationship between the tables and these constraints will make sure that the value in one table referenced to value in another table like a foreign key relationship.
If the SQLite library is compiled with foreign key constraint support, the application can use the PRAGMA foreign_keys command to enable or disable foreign key constraints at runtime.
What is a Foreign Key in SQLite? A foreign key is a way to enforce referential integrity within your SQLite database. A foreign key means that values in one table must also appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table.
What is a Foreign Key with "Set Null on Delete" in SQLite? A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to null.
Beginning with SQLite 3.7.16, there is PRAGMA foreign_key_check.
Run the following command:
PRAGMA foreign_keys;
Result will be:
0 // foreign keys Disabled
1 // foreign keys Enabled
To enable or disable foreign keys run:
PRAGMA foreign_keys = ON;
or
PRAGMA foreign_keys = OFF;
More information Here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With