Created
September 3, 2021 14:07
-
-
Save mhamzas/ac7480e9058ac7b06281ef6f5a60526f to your computer and use it in GitHub Desktop.
Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void saveSobjectSet(List <Sobject> listToUpdate) { | |
Integer SFDC_CHUNK_LIMIT = 10; | |
// Developed this part due to System.TypeException: Cannot have more than 10 chunks in a single operation | |
Map<String, List<Sobject>> sortedMapPerObjectType = new Map<String, List<Sobject>>(); | |
Map<String, Integer> numberOf200ChunkPerObject = new Map<String, Integer>(); | |
for (Sobject obj : listToUpdate) { | |
String objTypeREAL = String.valueOf(obj.getSObjectType()); | |
if (! numberOf200ChunkPerObject.containsKey(objTypeREAL)){ | |
numberOf200ChunkPerObject.put(objTypeREAL, 1); | |
} | |
// Number of 200 chunk for a given Object | |
Integer numnberOf200Record = numberOf200ChunkPerObject.get(objTypeREAL); | |
// Object type + number of 200 records chunk | |
String objTypeCURRENT = String.valueOf(obj.getSObjectType()) + String.valueOf(numnberOf200Record); | |
// CurrentList | |
List<sObject> currentList = sortedMapPerObjectType.get(objTypeCURRENT); | |
if (currentList == null || currentList.size() > 199) { | |
if(currentList != null && currentList.size() > 199){ | |
numberOf200ChunkPerObject.put(objTypeREAL, numnberOf200Record + 1); | |
objTypeCURRENT = String.valueOf(obj.getSObjectType()) + String.valueOf(numnberOf200Record); | |
} | |
sortedMapPerObjectType.put(objTypeCURRENT, new List<Sobject>()); | |
} | |
sortedMapPerObjectType.get(objTypeCURRENT).add(obj); | |
} | |
while(sortedMapPerObjectType.size() > 0) { | |
// Create a new list, which can contain a max of chunking limit, and sorted, so we don't get any errors | |
List<Sobject> safeListForChunking = new List<Sobject>(); | |
List<String> keyListSobjectType = new List<String>(sortedMapPerObjectType.keySet()); | |
for (Integer i = 0;i<SFDC_CHUNK_LIMIT && !sortedMapPerObjectType.isEmpty();i++) { | |
List<Sobject> listSobjectOfOneType = sortedMapPerObjectType.remove(keyListSobjectType.remove(0)); | |
safeListForChunking.addAll(listSobjectOfOneType); | |
} | |
update safeListForChunking; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment