Sub topic 6
Reading SaveResult, UpsertResult, and DeleteResult
This chapter assumes you can write basic Apex classes and methods, use collections, and catch exceptions with try/catch. It also assumes you know that Apex runs in transactions with governor limits. You should have seen Database.insert(records, false) from the previous chapter on allOrNone.
What the Database methods return
A DML statement such as insert accounts; returns nothing. It either succeeds or throws a DmlException. A Database method returns one result object for each record you passed in. The result object tells you what happened to that record.
| Database method | Result type |
|---|---|
| `Database.insert`, `Database.update` | `Database.SaveResult` |
| `Database.upsert` | `Database.UpsertResult` |
| `Database.delete` | `Database.DeleteResult` |
| `Database.undelete` | `Database.UndeleteResult` |
The results come back in a list, in the same order as the input list. The record at index 0 of the input matches the result at index 0 of the output. The next chapters build on this rule.
When you pass allOrNone as true, which is the default, the first failure still throws a DmlException. You only get results for failed records when allOrNone is false. Record-level errors then do not throw.
The common methods
All four result types share these methods:
isSuccess()returnstrueif the operation worked for that record.getId()returns the record ID. For a failed insert, it returnsnull.getErrors()returns a list ofDatabase.Errorobjects. The list is empty when the operation succeeded.
UpsertResult adds isCreated(). It returns true if the upsert inserted a new record and false if it updated an existing one.
Reading SaveResult
The loop below inserts two accounts. The second has no name, so it fails.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account() // Name is required, so this record fails
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
Database.SaveResult sr = results[i];
if (sr.isSuccess()) {
System.debug('Inserted ' + sr.getId());
} else {
for (Database.Error err : sr.getErrors()) {
System.debug('Record ' + i + ' failed: ' + err.getStatusCode() + ' - ' + err.getMessage() + ' ' + err.getFields());
}
}
}The loop uses an index instead of a for-each loop. The index lets you find the input record that matches a failed result. A failed record can carry more than one error, so the inner loop reads every entry in getErrors().
Reading UpsertResult
An upsert inserts or updates depending on whether the record already exists. UpsertResult tells you which one happened.
// External_Id__c is a hypothetical custom external ID field on Account.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme', External_Id__c = 'A-100'),
new Account(Name = 'Globex', External_Id__c = 'G-200')
};
List<Database.UpsertResult> results = Database.upsert(accounts, Account.External_Id__c, false);
for (Database.UpsertResult ur : results) {
if (ur.isSuccess()) {
System.debug((ur.isCreated() ? 'Created ' : 'Updated ') + ur.getId());
}
}Reading DeleteResult
DeleteResult has isSuccess(), getId(), and getErrors(). For a delete, getId() returns the ID of the record you tried to delete, even when the delete failed.
List<Account> toDelete = [SELECT Id FROM Account LIMIT 5];
List<Database.DeleteResult> results = Database.delete(toDelete, false);
for (Database.DeleteResult dr : results) {
if (!dr.isSuccess()) {
System.debug('Could not delete ' + dr.getId() + ': ' + dr.getErrors()[0].getMessage());
}
}Common errors
- Ignoring the results. With
allOrNoneset tofalse, a failed record raises no exception. If you never read the results, failures go unnoticed. - Assuming
getId()is set after a failure. On a failed insert it isnull. Use the index to find the input record instead. - Reading only the first error. A record can have several errors. Loop over
getErrors()if you need all of them. - Using a for-each loop and losing the position. If you need to map a failure back to the input record, keep the index.
Exercise
You call Database.update(contacts, false) with 10 contacts. Two fail validation. What do you get back, and how do you find the two failed contacts?
Show answer
You get a List<Database.SaveResult> with 10 entries, in the same order as the input list. No exception is thrown for the failures. Loop over the results by index, and for each result where isSuccess() is false, the contact at contacts[i] is the failed record. Read getErrors() on that result for the reason.