Database Class Methods
Database Class Methods are alternate ways of using DML statements, except Database Class Methods offer more functionality and flexibility.
DML Statements | Database Class Methods |
---|---|
Partial updates are not allowed | Allows for partial updates |
No way of getting list of successful / failed records | Methods are available to get list of records that were inserted or failed. |
Using Database Class Methods requires knowledge of in-built classes.
- Database Class
- SaveResult Class
- Error Class
Database Class
Database Class’ methods allow you to manipulate data into the org database and allow for partial updates, which means you can manipulate multiple records of an Object and the operation would go through even if some fail. The syntax is"
Database.statement(Record_Or_List, allOrNone);
Database
is the keywordstatement
is the operation we are doing on a single record or list. This can beinsert,
update
,upsert
,delete
orundelete
Single_Or_List
can be a single record being inserted or a list of objects.allOrNone
can be eithertrue
orfalse
to indicate if the records should be operated on despite some of them failing.
Let’s now insert 2 records in the contact object, one that succeds and the other fails.
List<Contact> finalList = new List<Contact>();
Contact con = new Contact();
con.lastName = 'Smith';
finalList.add(con);
Contact failCon = new Contact();
failCon.firstName = 'John';
finalList.add(failCon);
Database.insert(finalList, true);
When this code is run, it throws an error stating Last Name is a required field, but if the last statement is switched to false, it inserts the values that can be inserted and omits the rest
Database.insert(finalList, false);
On opening our console log and entering “Debug Only” section, there is no log. This is because we need the SaveResult
class to save the results.
SaveResult
SaveResult class is the result of an insert or update operation returned by the Database Class. Every Database operation returns an array (arrays are like List, but use
[ ]
instead of <>
) of SaveResult. To use it, we just save the result of a Database operation into a Database.SaveResult[] variableName
. Let’s add this to our code and loop over it:
List<Contact> finalList = new List<Contact>();
Contact con = new Contact();
con.lastName = 'Smith';
finalList.add(con);
Contact failCon = new Contact();
failCon.firstName = 'John';
finalList.add(failCon);
Database.SaveResult[] resultList = Database.insert(finalList, false); //Allow partial updates
for (Database.SaveResult iterator: resultList){
System.debug(iterator);
}
You will get the following in your Debug Only logs:
01:53:17:158 USER_DEBUG [14]|DEBUG|Database.SaveResult[getErrors=();getId=0036F00003XBWVJQA5;isSuccess=true;]
01:53:17:167 USER_DEBUG [14]|DEBUG|Database.SaveResult[getErrors=(Database.Error[getFields=(LastName);getMessage=Required fields are missing:[LastName];getStatusCode=REQUIRED_FIELD_MISSING;]);getId=null;isSuccess=false;]
You will notice the successful field has getErrors
, getId
and isSuccess
fields, which can actually be used in our code to filter out
successful results and get their IDs, and only output the failed fields. Let’s update our for loop to reflect this change and pretty up our logs:
for (Database.SaveResult iterator: resultList){
if (iterator.isSuccess()){
System.debug('Successfuly inserted: ' + iterator.getID());
}
else {
System.debug(iterator);
}
}
Great! now to deal with the errors, we make use of the methods available in Error
class.
Error
The Error class is used for error reporting and has 3 methods:
getFields()
to get an array of fields that failedgetMessage()
to get why the record failedgetStatusCode()
to get the status code of the error
This is used in combination with the Database Class and it’s .getErrors()
method.
Let’s add this in our for loop
for (Database.SaveResult iterator: resultList){
if (iterator.isSuccess()){
System.debug('Successfuly inserted: ' + iterator.getID());
}
else {
for (Database.error errorIterator: iterator.getErrors()){
System.debug(errorIterator.getStatusCode() + ' ' + errorIterator.getMessage() );
System.debug('The following fields were affected: ' + errorIterator.getFields());
}
}
}
The log now states:
02:10:12:126 USER_DEBUG [15]|DEBUG|Successfuly inserted: 0036F00003XBWWvQAP
02:10:12:143 USER_DEBUG [19]|DEBUG|REQUIRED_FIELD_MISSING Required fields are missing: [LastName]
02:10:12:143 USER_DEBUG [20]|DEBUG|The following fields were affected: (LastName)
Now out logs are much cleaner and output our errors very clearly! The Database class has more methods that we will learn over the course of next few days.
Summary
- Database Class Methods has extended functionality and allows for partial updates
- SaveResult class allows to save results of the database operations
- Error class allows to navigate through errors
- An Array is similar to a list, with the only exception of
[ ]
instead of< >