Savepoints

Savepoints are markers indicating the state of the database at a specific point in the execution of your Apex program. They allow the database to be restored to a known state in case of error or any scenario requiring a reversal of all DML operations performed since the savepoint.

Set a new savepoint using the Database.setSavepoint method, which returns a Savepoint object. To restore the database to a savepoint, call the Database.rollback method, which takes a Savepoint object as its only argument.

Several limitations exist on the use of savepoints. The number of savepoints and rollbacks contributes toward the overall limit on DML statements, which is 150. If you create multiple savepoints and roll back, all savepoints created after the savepoint you roll back to are invalidated. Finally, you cannot share a savepoint across triggers using a static variable.

Listing 5.19 is an example of using the setSavepoint and rollback methods. First, a savepoint is set. Then, all the Project records in your database are deleted, assuming your database doesn’t contain more than the governor limit of 10,000 records for DML. Finally, the database is rolled back to the savepoint. The number of records in the Project object is counted before each operation in the program to illustrate its behavior.

Listing 5.19 Savepoint and Rollback Usage


void printRecordCount() {
  System.debug([ SELECT COUNT() FROM Project__c ] + ' records'),
}
printRecordCount();
Savepoint sp = Database.setSavepoint();

delete [ SELECT Id FROM Project__c ];
printRecordCount();

Database.rollback(sp);
printRecordCount();


The results of running the code snippet in the Execute Anonymous view are shown in Figure 5.7. The debug log indicates that the Project object initially contains five records. They are all deleted, leaving zero records. Then the database is rolled back to the savepoint established before the deletion, resulting in a count of five records again.

Image

Figure 5.7 Results of savepoint and rollback sample code

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.162.105