In MySQL, can I defer referential integrity checks until commit

MysqlReferential Integrity

Mysql Problem Overview


As in this question, I've been reading PoEAA and wondering if it's possible to defer referential integrity checks until commit in MySQL.

I've run into this problem when wanting to insert a bunch of products and related products in the same commit. Even within a transaction, I get constraint errors when I try to insert into the related_products join table.

If it helps, I'm using PHP PDO for database connections.

I'd appreciate any help you could offer.

Mysql Solutions


Solution 1 - Mysql

Looks like my answer is here...

> Like MySQL in general, in an SQL statement that inserts, deletes, or updates many rows, InnoDB checks UNIQUE and FOREIGN KEY constraints row-by-row. When performing foreign key checks, InnoDB sets shared row-level locks on child or parent records it has to look at. InnoDB checks foreign key constraints immediately; the check is not deferred to transaction commit. According to the SQL standard, the default behavior should be deferred checking. That is, constraints are only checked after the entire SQL statement has been processed. Until InnoDB implements deferred constraint checking, some things will be impossible, such as deleting a record that refers to itself using a foreign key.

Back to the drawing board.

Solution 2 - Mysql

If you are asking if MySQL supports the DEFERRABLE attribute for foreign keys (including the option INITIALLY DEFERRED) then the answer is a clear no.

You can't defer constraint checking until commit time in MySQL.

And - as you have already pointed out - they are always evaluated at "row level" not on "statement level".

Solution 3 - Mysql

You may handle this limitation of innodb engine, by temporarily disabling foreign key checks by setting server variable:

set foreign_key_checks=0;

From MySQL manual:

mysqldump also produces correct definitions of tables in the dump file, and does not forget about the foreign keys.

To make it easier to reload dump files for tables that have foreign key relationships, mysqldump automatically includes a statement in the dump output to set foreign_key_checks to 0. This avoids problems with tables having to be reloaded in a particular order when the dump is reloaded. It is also possible to set this variable manually:

mysql> SET foreign_key_checks = 0;
mysql> SOURCE dump_file_name;
mysql> SET foreign_key_checks = 1;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoss McFarlaneView Question on Stackoverflow
Solution 1 - MysqlRoss McFarlaneView Answer on Stackoverflow
Solution 2 - Mysqla_horse_with_no_nameView Answer on Stackoverflow
Solution 3 - MysqlThavaView Answer on Stackoverflow