我们有一个通常具有以下结构的数据库:
Master Record Table
id (pk)
MasterRecordId <-- constrained to be unique
儿童/兄弟姐妹(第二代,如果你愿意的话):
Table1
( table1ID (pk),
MasterRecordID (fk))
Table2
( Table2ID(pk),
MasterRecordID (fk))
孙子(第三代):
Table3
( Table3ID (pk)
Table1ID (fk))
Table4
(Table4ID (pk)
Table1ID (fk))
Table5
(Table5ID (pk)
Table2ID (fk))
并非第二代的每张桌子都有孩子。应用程序中存在受限的删除功能(您可以删除任何单个记录,但 FK 在许多情况下会阻止删除;删除功能很糟糕,并且不会优雅地失败)。
我的任务是调查处理删除的最佳方法。为了清除从大师到孙子的整个记录,后端是唯一的方法。这让 The Powers That Be 很高兴。但是,你知道,用户撒谎,所以事实证明我们可能需要改变这一点(这样我就不必偶尔充当官方记录删除者,而且因为有某些类型的 Gen 2 记录用户经常删除。
Cascading Deletes were the first option, because TPTB would prefer this not require work on a new build of the app. And because it's what popped out of my bosses' mouth at the end of that particular meeting. My Gen 2 -> Gen 3 cascades are all working fine (and this covers the most frequent Use Case/Story/What Have You). I then updated all the Master -> Gen 2 Foreign Keys to cascade on Delete. In hoped this would allow a deletion of the master record and that all other kids and grand kids would go with it. No good; I get an error message violating the first Master -> Gen 2 FK to come up when I try to delete the master record. I've double checked; FKs are set to cascade on delete.
What am I not understanding about cascading deletes with more than 1 level of table relationships? I'm reading as much as I can (as time permits) but I haven't yet discovered the knowledge that will lead me out of this dark time. Is cascading the wrong approach?
Secondly, there are two other options as I see it:
Do all deletion in the app. Not preferred, but if it's the only option it's the only option. I know there are arguments that it's the best option, but TPTB have different views of best than I do (and while they're all batshit crazy, they sign the checks).
Handle deletes via trigger? I'm unclear if Foreign Keys will get inthe way of this, but it occured to me this might be an option.
Well, also:
- Do the Gen 2 -> Gen 3 cascading. And then the few people with delete permissions will just have to follow the rituals to do full deleting (that would be: delete all Gen 2 records individually, then delete the master). Or, I'll be stuck as Official Record Deleter.