Search code examples
salesforcesalesforce-communities

Salesforce - Best way to delete multiple records from an Object hierarchy and error handling in Salesforce


Context: We would like to delete multiple records in the Case and its related/child objects. The child objects have few related objects. There are 4 to 5 levels of hierarchy as follows

  • Case
  • --Task
  • -----Child1
  • --------Child2
  • -----------Child3

      The related objects are having master-child relationship with cascade delete set to false.

Currently the way we are deleting cases in a batch is as follows

  1. Collect all cases in the batch
  2. Collect all the tasks for all cases in the batch
  3. Collect all the Child1 records for all Cases in the batch
  4. Collect all the Child2 records for all Cases in the batch
  5. Collect all the Child3 records for all Cases in the batch

Then delete each set of records in batch using bulk delete. The advantage is we will have only 5 deletes per batch and we don't hit governor limits.

However the down side of this process is, when there is error in deleting in any of the steps above, whole transaction is rolled back. Though we can get which delete caused he error, we cannot role back objects related to only that particular case.

Question:

  1. Is there are any better way to handle deleting of records and child records.
  2. Is there a way to rollback only the cases and the child records which had error

Solution

  • Use bottoms up approach along with batch.

    For example start with Child3. collect all the records that needs to be purged in each related object and case object. Then delete in batch.

    • Child3
    • --Child2
    • -----Child1
    • --------Task
    • -----------Case

    There are 2 ways:

    1. Declarative method: Use the Process Event and Process Builder/flow field count in each object is less than 350. The advantage of this method is you don't have to write code.

    2. Using Apex class: Write apex code to get all the related objects that needs to be purged/deleted and execute in batch.

      a) Set the batch size of 1 so that any error while deleting, only the related records will be rolled back.

      b) If batch size is set to higher than 1, whole batch will be rolled back. In this case you need to identify the parent (Case object) id and mark them for error and re-read all the other records which were rolled back as part of the batch and run again. In this method, identifying the failed record (if the records failed in child3) and its root parent (case) id could be challenging.