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.
The only way you can enforce referential integrity in MySQL is by using a foreign key. This is an indexed column in a child table that refers to a primary key in a parent table. This is achievable if you design your tables with MySQL InnoDB database engine.
Referential Integrity prevents your table from having incorrect or incomplete relationships e.g. If you have two tables Order and Customer where Customer is parent table with primary key customer_id and Order is child table with foreign key customer_id.
Referential integrity is an important concept in database. design. The term refers to a state when all the references in a database are. valid and no invalid links exist between the various tables that make up the. system.
Checking of deferrable constraints can be postponed until the end of the transaction (using the SET CONSTRAINTS command). NOT DEFERRABLE is the default. Currently, only UNIQUE, PRIMARY KEY, EXCLUDE, and REFERENCES (foreign key) constraints accept this clause. NOT NULL and CHECK constraints are not deferrable.
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.
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".
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