Sub topic 9
Rolling back to a savepoint with Database.rollback
This chapter assumes you can write basic Apex, run insert and update statements, catch a DmlException, and know that governor limits exist. It also assumes you have read the previous chapter on setting a savepoint. Here you will learn what Database.rollback does, what it leaves alone, and how to use it safely.
What Database.rollback does
Database.rollback(Savepoint sp) restores the database to the state it had when you called Database.setSavepoint() and got sp. Every DML change made after that point is undone. That includes inserts, updates, deletes, and undeletes. Work done before the savepoint is untouched.
The call does not end the transaction. Your code keeps running, and anything you do afterward is part of the same transaction. When the transaction finishes normally, the work from before the savepoint is committed, along with any new work you did after the rollback.
Database.rollback(sp);The method returns nothing. It throws a runtime exception if the savepoint is invalid. The next chapter covers when that happens.
A first complete example
This example inserts a record that should survive, sets a savepoint, then does related work that fails.
Account keep = new Account(Name = 'Kept');
insert keep;
Savepoint sp = Database.setSavepoint();
Account temp = new Account(Name = 'Temp');
try {
insert temp;
insert new Contact(); // LastName is required, so this throws a DmlException
} catch (DmlException e) {
Database.rollback(sp);
System.debug('Rolled back: ' + e.getMessage());
}
System.debug([SELECT COUNT() FROM Account WHERE Id = :keep.Id]); // 1
System.debug([SELECT COUNT() FROM Account WHERE Id = :temp.Id]); // 0The Kept account was inserted before the savepoint, so it stays. The Temp account was inserted after it, so the rollback removes it. The catch block is what makes this work. Catching the exception stops the automatic rollback, so you must undo the partial work yourself.
The rollback target is a point in time
A savepoint marks a position in the sequence of DML operations. Rolling back to it discards everything after that position, no matter how many statements or objects were involved. You do not list the records to undo. The following code undoes three different kinds of change with one call:
Account existing = new Account(Name = 'Original');
insert existing;
Savepoint sp = Database.setSavepoint();
existing.Name = 'Changed';
update existing;
insert new Contact(LastName = 'Doe', AccountId = existing.Id);
delete [SELECT Id FROM Opportunity WHERE AccountId = :existing.Id];
Database.rollback(sp);
Account fresh = [SELECT Name FROM Account WHERE Id = :existing.Id];
System.debug(fresh.Name); // OriginalAfter the rollback, the name is back to Original, the contact is gone, and any deleted opportunities are restored.
Rolling back and then continuing
Because the transaction stays open, you can roll back one attempt and try another. A common case is trying a preferred approach and falling back to a simpler one.
public with sharing class AccountSetup {
public static Id createAccount(String name, Boolean withContact) {
Savepoint sp = Database.setSavepoint();
Account acct = new Account(Name = name);
try {
insert acct;
if (withContact) {
insert new Contact(LastName = name, AccountId = acct.Id);
}
return acct.Id;
} catch (DmlException e) {
Database.rollback(sp);
throw e;
}
}
}This method either completes all of its work or leaves the database as it found it, and then reports the failure. Rethrowing matters. If you roll back and swallow the exception, the caller thinks the operation worked.
Rollback versus all-or-none DML
A single DML statement is already atomic by default. If one record in insert accts; fails, no record from that statement is saved, and you do not need a savepoint for it. You need a savepoint when several statements must succeed or fail together, or when you catch an exception and want to undo earlier statements in the same transaction.
| Situation | Is a savepoint needed? |
|---|---|
| One `insert` of a list, all-or-none | No. The statement is atomic. |
| Two or more related DML statements, exception caught | Yes. Otherwise the first statement stays committed. |
| Exception is not caught | No. The whole transaction rolls back automatically. |
| `Database.insert(list, false)` with some failures | No, unless you want to undo the successful records too. |
The last row deserves a note. Partial success saves the valid records. If your business rule says that any failure should discard everything, inspect the SaveResult array and call Database.rollback(sp) if any result failed.
Savepoint sp = Database.setSavepoint();
List<Account> accts = new List<Account>{
new Account(Name = 'Good'),
new Account() // missing required Name
};
Boolean anyFailed = false;
for (Database.SaveResult sr : Database.insert(accts, false)) {
if (!sr.isSuccess()) {
anyFailed = true;
}
}
if (anyFailed) {
Database.rollback(sp);
}Cost against governor limits
Both Database.setSavepoint() and Database.rollback() count as DML statements. A transaction is allowed 150 DML statements, so a savepoint and a rollback together use two of them. Inside a loop this adds up quickly. A loop that sets a savepoint and rolls back for each of 100 records would use 200 statements and hit the limit.
What the rollback does not restore
The rollback acts on the database only. Your Apex variables are not part of the database, so they keep whatever values they had. Two effects follow.
First, an sObject keeps its Id after the rollback, even though its row no longer exists. Inserting the same variable again fails with a "cannot specify Id in an insert call" error unless you clear the Id.
Savepoint sp = Database.setSavepoint();
Account a = new Account(Name = 'Temp');
insert a;
Database.rollback(sp);
System.debug(a.Id); // still set, but the row is gone
a.Id = null; // clear it before inserting again
insert a;Second, static variables, instance fields, and other in-memory state stay as they were. If you incremented a static counter after the savepoint, the counter is still incremented after the rollback. If your code tracks "records created so far" in memory, reset it yourself.
Common errors
- Swallowing the exception after rollback. The caller never learns the operation failed. Rethrow, or return a clear failure result.
- Rolling back in a
finallyblock unconditionally. This undoes successful work too. Roll back only on the failure path. - Using a savepoint from a different transaction. A savepoint variable is only meaningful in the transaction that created it. Do not carry it into asynchronous work.
- Reinserting a record without clearing its Id. The stale Id causes an error.
- Counting on the rollback to reset state in memory. It does not.
Checking the result
Verify a rollback by querying, not by looking at your variables. The query reflects what is really in the database.
@IsTest
private class RollbackKeepsEarlierWorkTest {
@IsTest
static void rollbackUndoesOnlyLaterWork() {
Account keep = new Account(Name = 'Kept');
insert keep;
Savepoint sp = Database.setSavepoint();
Account temp = new Account(Name = 'Temp');
insert temp;
Database.rollback(sp);
System.assertEquals(1, [SELECT COUNT() FROM Account WHERE Id = :keep.Id]);
System.assertEquals(0, [SELECT COUNT() FROM Account WHERE Id = :temp.Id]);
}
}Exercise
A method inserts an Account, sets a savepoint, inserts a Contact that fails with a DmlException, catches the exception, calls Database.rollback to the savepoint, and does not rethrow. When the transaction ends, which records exist, and what two things could go wrong for the caller or later code?
Show answer
The Account exists, because it was inserted before the savepoint and the exception was handled, so the transaction commits. The Contact does not exist. First, the caller is not told that the Contact failed, because the exception was swallowed, so it may assume the full operation succeeded. Second, any in-memory state set after the savepoint, such as a Contact variable that still holds an Id or a static counter, is not reverted and may be stale.