Skip to main content

Hi everybody, I think this is a question for those with knowledge of Apex. We want to automate the regular deletion of test data. This would be created by a user in a sandbox whose 'title' field on their user record contains the string 'automatedTest' and the code (or flow if it's possible) would need to delete the records that user creates every 2 months or 8 weeks from whenever they were created.

 

We could have a scheduled flow that will delete records of one object and I think it's relatively easy to write code that runs a SOQL query to find records created by the automated test user but the query becomes very long and we would have to write an extra line of SOQL for every object and our tester could create records of any object for testing. Also it'd be good to future proof this for custom objects that haven't been created yet. So I need a way of getting all the objects that exist when the code runs, checking if records of any of those were created by the automated test user and when they were created then deleting the records that meet the criteria whatever object they're from.

 

Does anybody have any ideas? Am I looking at this the wrong way?

 

Below is some code I got from ChatGPT that I think looks promising but it may be rubbish.

 

I'd be very grateful for any help.

 

Thanks in advance,

 

Matt

 

ChatGPT's attempt:

 

// Query to find the User Id with 'automatedTest' in the Title field

String targetUserQuery = 'SELECT Id FROM User WHERE Title LIKE \'%automatedTest%\' LIMIT 1';

 

// Initialize the targetUserId variable

String targetUserId;

 

try {

    User targetUser = Database.query(targetUserQuery);

    targetUserId = targetUser.Id;

} catch (QueryException e) {

    System.debug('User not found: ' + e.getMessage());

}

 

// Check if a targetUserId was found

if (String.isNotBlank(targetUserId)) {

    // List to store all the records to be deleted

    List<sObject> recordsToDelete = new List<sObject>();

 

    // Get a list of all sObjects

    List<String> objectNames = new List<String>();

    for (Schema.SObjectType objType : Schema.getGlobalDescribe().values()) {

        objectNames.add(objType.getDescribe().getName());

    }

 

    // Query and delete records for each object type

    for (String objectName : objectNames) {

        String query = 'SELECT Id FROM ' + objectName + ' WHERE CreatedById = :targetUserId';

 

        List<sObject> objects = Database.query(query);

        recordsToDelete.addAll(objects);

    }

 

    // Delete all records in a single transaction

    if (!recordsToDelete.isEmpty()) {

        try {

            delete recordsToDelete;

            System.debug('Records deleted successfully');

        } catch (Exception e) {

            System.debug('Error deleting records: ' + e.getMessage());

        }

    }

} else {

    System.debug('No user with Title containing "automatedTest" found.');

}

 

#Flow  #Sales Cloud  #Automation

1 个回答
  1. 2023年11月1日 19:27

    I would not recommend to use that script generated by chat as it tries to query data in a loop which is not a wise thing to do and generally process like that need a little preparation.

     

    Firstly I would probably do a little data analysis to asses how many objects do you have and what volumes we are talking about. Probably creating some list of handled object will shorten time of execution of future process - could be easier than just going for all.

     

    In case of actual solution I would go with a batch job per object:

    1. You could create a list of handled objects and additional where parameters in custom metadata
    2. Then create a simple batch which in start method creates and run a query for one object from your config and removes records in execute
    3. Next in finish it runs another bath for different object from you config

    I did similar thing some time ago for one of my clients and it worked without any issue. Only problem could be with potential record locks. For example if you try remove contacts and will have some rollup on account removal of contact will lock an account. That way any other process like flow will not be ably to make any change to that specific account (for a moment but can take longer if there is more records)

     

    Good thing is also to consider some kind of logger to know what records fail and maybe also retry functionality.

     

    And of course testing that before running on PROD is also a crucial thing.

0/9000