且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

软删除关于级联恢复的常见属性

更新时间:2023-02-02 22:45:59

在一个情况下,您不仅要跟踪发生了什么,但是当发生时, 为什么,人们经常使用事务日志



事务日志表通常具有以下列:事件的日期/时间,事件的性质(插入,更新,删除,...)以及执行操作的用户和/或进程。事务日志和基表中受影响的记录之间也有一个链接。这可以通过基表上的外键到事务日志表来完成,但是更常见的是将事务日志包含到基表的外键。如果事务日志表在各个基表之间共享,则需要一个基表指示符和一个基表外键。



在你的情况下,如果删除是主要关注的是,您可以将日志条目限制为删除,并区分级联删除与其他删除。您可以(应该)也考虑使用事务包装器一次写入所有软删除(主加级别)。您可以在日志中包含某种类型的标识符,例如身份值或GUID作为业务事务ID,并将此ID放入作为同一操作一部分的每个条目。这可以清楚地表明发生了什么,发生了什么,为什么发生了,以及发生了哪些记录。您可以使用此信息来决定如何扭转任何特定交易,包括执行级联恢复。


What type of fields are generally used to accompany soft delete? Any of these, any others?

bool IsDeleted // nice because the default value is 0 (no) just in case
date DateDeleted // is this a common one?
date DateCreated // more of a temporal db aspect
date DateModified // same with respect to created

The reason I ask is that when using soft-deletes, cascading must still be implemented in order to maintain integrity. However, the real trick is not cascade deleting, which is rather easy.

The trick is cascade restoring. On cascade delete, with a soft-delete scenario, all records in the relational graph are flagged as deleted, inactive, whatever the flag is, perhaps the difference is to change the datedeleted to a value from null. On cascade restore, record references must be evaluated to see if the reason they were deleted was a result of a cascade delete related to the record being restored, reactiviated, undeleted.

How are cascade restore operations handled with regards to stored data?

In a case where you want to track not only the results of what has happened, but also when it happened and why, people often use a transaction log.

A transaction log table typically has columns such as: date/time of the event, nature of the event (insert, update, delete,...), and the user and/or process that performed the action. There is also a link between the transaction log and the affected record in the base table. This can be done with a foreign key on the base table to the transaction log table, but it is more common to have the transaction log contain a foreign key to the base table. If the transaction log table is shared amongst various base tables, you'd need a base table indicator plus a base table foreign key.

In your case, if deletions are the main concern, you could restrict log entries to deletions and make a distinction between a cascade delete vs. other deletes. You could (should) also consider using transaction wrappers to write all of the soft deletes (primary plus cascading) at one time. You can include some kind of identifier, like an identity value or a GUID as a "business transaction ID" in your log and place this ID into every entry that is part of the same operation. This gives you a clear indication of what happened, when it happened, why it happened, and which records it happened to. You'll be able to use this information to decide how to reverse any particular transaction, including performing a cascade restore.