views:

31

answers:

1

So you have a relational database and you define some foreign keys for reference integrity. But now, what's the better way to leverage them? Assume we are going to delete a row in a table with foreign keys to other tables.

  1. Use them as a garbage collector - Set all constraints to cascade. So in your application, you first check if the target row has any "children" and present the user the option to abort the delete operation if it is undesirable to have the dependent rows deleted as well.

  2. Use them as actual constraints - In your application, just attempt to delete the target row. If the operation failed, then check if it has children and present the options to the user; If the user wants to proceed with the operation, manually delete the depending rows first.

The second option makes deleting circular references rather arduous - You have to set the foreign keys to null before you can even delete anything.

+1  A: 

There are 2 typical foreign key scenarios:

  • Association: link 2 entities that can exist on their own
  • Composition: link a child entity to its parent entity (the child entity does it exist without a parent, for instance: order and order item)

I'd cascade only in the case of composition and treat each association case individually.

vc 74
I think you answered the wrong question, or maybe I'm misinterpreting your answer... But my dilemma applies to _both_ your cases. My question asks _who_ should **enforce** the integrity - Not whether it should _be_ enforced or not. In both cases one row depends on the other; The question is, when deleting, who makes the check - The database or the application?
Core Xii
I would rely on the database to handle the composition cascade deletes because it does not make sense to keep children while deleting parents. For associations, the logic is more complex and depends on where your business rules are. If it they are outside the db then the business layer (app, service) should take care of cascading the deletes. But there is no golden rule for such cases. When you delete the last employee associated to a department, do you delete the department? Maybe, probably not, it depends...
vc 74
I'm not looking for a golden rule; I want to hear which way other people are doing it in _practice_. Still, thanks for the input.
Core Xii
You're welcome, hopefully you'll get more feedback than just mine.
vc 74