0

I am trying to delete accounts using a batch class. I am firing platform events from the batch class, and handling the deletion logic platform event subscribed trigger, but not all account records are deleting - only 2 records are deleting.

global class accountDeletionBatchClass implements Database.Batchable<sObject>,Schedulable{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query;
        query='Select id,name from account';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,List<Account> accs)
    {
        List<AccountEvent__e> aevents=new List<AccountEvent__e>();
        if(accs.size()>0)
        {
            for(Account acc:accs)
            {
                aevents.add(new AccountEvent__e(Event__c='DELETE',Id__c=acc.Id));
            }

            if(aevents.size()>0)
            {
                List<Database.SaveResult> results=EventBus.publish(aevents);
            }
        }
    }

    global void finish(Database.BatchableContext BC)
    {

    }

    global void execute(SchedulableContext ctx)
    {
        accountDeletionBatchClass b=new accountDeletionBatchClass();
        database.executebatch(b);
    }
}

enter image description here

enter image description here

trigger AccountTrigger on AccountEvent__e (after insert) {
set<id> rids=new set<id>();
       for(AccountEvent__e r:Trigger.New)
       {
           if(r.Event__c=='DELETE')
           {
               rids.add(r.Id__c);
           }
       }

       List<Account> delids=[select id from account where id IN:rids];

       delete delids;
}
1

Remove the LIMIT from your query. Every batch of 200 records will only delete a single record.

Also, you don't need to check for empty lists before you iterate over them/DML on them.

Here's the optimized version:

global void execute(Database.BatchableContext BC,List<Account> accs) {
    List<AccountEvent__e> aevents=new List<AccountEvent__e>();
        for(Account acc:accs) {
            aevents.add(new AccountEvent__e(Event__c='DELETE',Id__c=acc.Id));
        }
        EventBus.publish(aevents);
    }
}
2
  • even though i removed limit i am not able to delete the record only one or two records are deleting May 29 '20 at 6:25
  • 1
    @SaiVinayManapuram You would need to do some debugging then. I see no reason why this shouldn't work, although I'm not sure why you're using a platform event to do the deletion to begin with.
    – sfdcfox
    May 29 '20 at 6:36
0

I was able to solve this. That DML delete statement was causing a problem if one record failed to delete, so I used Database.delete(list,false)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.