top of page
Writer's pictureSalesforceFresher

SAVEPOINT IN APEX

Sometimes during the processing of records, your business rules require that partial work (already executed DML statements) be “rolled back” so that the processing can continue in another direction. Apex gives you the ability to generate a savepoint, that is, a point in the request that specifies the state of the database at that time. Any DML statement that occurs after the savepoint can be discarded, and the database can be restored to the same condition it was in at the time you generated the savepoint.

The following limitations apply to generating savepoint variables and rolling back the database:

  • If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2would no longer be valid. You will receive a runtime error if you try to use it.

  • References to savepoints cannot cross trigger invocations because each trigger invocation is a new trigger context. If you declare a savepoint as a static variable then try to use it across trigger contexts, you will receive a run-time error.

  • Each savepoint you set counts against the governor limit for DML statements.

  • Static variables are not reverted during a rollback. If you try to run the trigger again, the static variables retain the values from the first run.

  • Each rollback counts against the governor limit for DML statements. You will receive a runtime error if you try to rollback the database additional times.

  • The ID on an sObject inserted after setting a savepoint is not cleared after a rollback. Create an sObject to insert after a rollback. Attempting to insert the sObject using the variable created before the rollback fails because the sObject variable has an ID. Updating or upserting the sObject using the same variable also fails because the sObject is not in the database and, thus, cannot be updated.

Usage:–

Account a = newAccount(Name = 'xxx'); inserta;02System.assertEquals(null, [SELECTAccountNumber FROMAccount WHEREId = :a.Id].03AccountNumber);0405// Create a savepoint while AccountNumber is null06Savepoint sp = Database.setSavepoint();0708// Change the account number09a.AccountNumber = '123';10updatea;11System.assertEquals('123', [SELECTAccountNumber FROMAccount WHEREId = :a.Id].12AccountNumber);1314// Rollback to the previous null value15Database.rollback(sp);16System.assertEquals(null, [SELECTAccountNumber FROMAccount WHEREId = :a.Id].17AccountNumber);


278 views0 comments

Comments


bottom of page