0

I want to ignore a bunch of records (Custom settings in fact) and want the transaction to ignore Duplicate errors. All other errors should make the insert fail. If a duplicate exists simply skip the insert.

This is how I try to solve this. If there is an alternative it would be great.

0

Can't you prepare your data upfront by looking at whatever the unique key happens to be? Stick existing data into Map<String, CustomSetting__c>, then loop through the items you want to insert and compare? Less attempted DMLs (and rows wasted), less pain with rollbacks if needed...

For List custom settings you should only need the getAll() method, something like this:

Map<String, CustomSetting__c> m = CustomSetting__c.getAll();
List<CustomSetting__c> toInsert = new List<CustomSetting__c>();

for(CustomSetting__c c : scope){
    if(m.containsKey(c.Name)){
        continue;
    }
    m.put(c.Name, c);
    toInsert.add(c);
}

insert toInsert;

(might be smart to sprinkle some String.toLower() or String.equalsIgnoreCase() around because with Strings as map keys the case matters).

For hierarchy custom settings it's bit more annoying as there's no "getAll" approach. You could carefully do the matching by looking at what's the type of SetupOwnerId, call getOrgDefaults() if it's equal to UserInfo.getOrganizationId(), else call getValue()... But I'd be tempted to just query them all (if there aren't too many rows)

Map<Id, CustomSetting__c> m = new Map<Id, CustomSetting__c>();
for(CustomSetting__c c : [SELECT SetupOwnerId, Name FROM CustomSetting__c]){
    m.put(c.SetupOwnerId, c);
}

and then proceed as with list settings.

Another idea for hierarchy settings:

  1. generate Set<Id> containing SetupOwnerIds of data you're about to insert
  2. SELECT SetupOwnerId FROM CustomSetting__c WHERE Id IN :myIds, throw it into a Map where key is also SetupOwnerId
  3. Do some magic with Maps, their (key)Sets,containsKey() or Set.remove() methods.
|improve this answer|||||

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.