Question

Lets say you have a table(A) holding a limited amount of data, and one of the fields being a primary key is being referenced by not one, but many foreign keys from other tables.

The foreign keys of these tables have constraints against the before mentioned table(A) where should a row from table(A) be deleted and one of the other tables FKs holds a reference to it, the deletion will fail.

OK, with the database design taken care of, it is now a matter of the software, PHP in this case. An attempt is made to delete a row from table(A), how should a check be made to ensure that the row cannot be deleted if a reference is held?

I have seen cases where every table is checked before hand, however that involves coding in every check which becomes a maintenance nightmare. Additionally, I can't simply let the deletion be attempted, as this needs to be a cross database application, therefore the returned error codes wont be consistent.

I am interested to know how people usually tackle this scenario. I mentioned I am using PHP, but this situation should apply in any language.

Was it helpful?

Solution

In general, you handle this by attempting to execute the DELETE statement on the PRIMARY KEY table, trapping for an exception, and rolling back the transaction when it happens. You can then report the failure in whatever form you want to the user. This works if all the referencing tables really declare the FOREIGN KEY back to the PRIMARY KEY table.

If you really need to check first you'll need to write code to "introspect" the keys that exist in the database, extract the table and column name(s) for each referencing foreign key, and issue SELECT COUNTs against each table. Unfortunately, each database engine has its own methods to learn about the database structure, so you'll have to write some code for each database engine you want to support.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top