Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In sqlite3, is there a foreign_key integrity check?

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

like image 688
Eradicatore Avatar asked May 04 '13 14:05

Eradicatore


People also ask

Does SQLite enforce referential integrity?

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.

Does SQLite enforce foreign key constraint?

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.

Does SQLite have foreign keys?

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.

Can foreign keys be null SQLite?

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.


2 Answers

Beginning with SQLite 3.7.16, there is PRAGMA foreign_key_check.

like image 58
CL. Avatar answered Sep 28 '22 05:09

CL.


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

like image 45
Oussama EL Issaoui Avatar answered Sep 28 '22 05:09

Oussama EL Issaoui