Sub topic 7
Fixing mixed DML errors
This chapter assumes you know basic Apex syntax, SOQL and DML, and how to declare a future method with @future. The goal is to understand why the mixed DML error happens and how a future method fixes it.
What the error is
Salesforce splits objects into two groups:
- Setup objects configure the org. Examples are
User,UserRole,Group,GroupMember,PermissionSet, andPermissionSetAssignment. - Non-setup objects hold business data. Examples are
Account,Contact,Opportunity, and custom objects.
Apex does not let you run DML on both kinds in the same transaction. If you try, it throws this error:
System.DmlException: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)The order does not matter. Setup then non-setup fails, and so does non-setup then setup.
Some objects have exceptions. For example, you can insert some non-setup objects together with certain setup objects in specific cases. Do not rely on this. Check the Apex Developer Guide for the object you are using.
A failing example
This method creates an account and then a role in one transaction.
public class MixedDmlDemo {
public static void run() {
insert new Account(Name = 'Acme');
// Throws MIXED_DML_OPERATION
insert new UserRole(Name = 'Sales Lead', DeveloperName = 'Sales_Lead');
}
}The Account insert is non-setup DML. The UserRole insert is setup DML. Both run in the same transaction, so the second statement fails.
The fix: move one side into a future method
A future method runs in its own transaction after the current one finishes. If you put the setup DML in a future method, the two kinds of DML never share a transaction.
public class SetupDmlHelper {
@future
public static void createRole(String roleName, String developerName) {
insert new UserRole(Name = roleName, DeveloperName = developerName);
}
}Now the caller can do its non-setup work and hand off the setup work.
public class MixedDmlFixed {
public static void run() {
insert new Account(Name = 'Acme');
SetupDmlHelper.createRole('Sales Lead', 'Sales_Lead');
}
}The Account insert commits with the original transaction. The role insert runs later, in a separate transaction.
Design points to keep in mind
The fix works because of how future methods behave. Each of these follows from earlier chapters.
- Separate transactions. If the future method fails, the first transaction is not rolled back. If the first transaction fails and rolls back, the future call is discarded. Plan for a partial result.
- No immediate result. The caller cannot read the new role right away. Anything that depends on it must also run in the future method or later.
- Parameters must be primitives or collections of primitives. That is why
createRoletakes strings and not aUserRolerecord. Pass IDs and re-query when you need records. - Limits apply. Each call counts toward the future-call limit for the transaction. If you assign roles or permission sets for many records, collect the values and make one call.
Mixed DML in tests
Tests hit the same error. A test often creates a User and then creates an Account in the same context. There are two common fixes.
- Wrap the setup DML in
System.runAs(). Code run this way is not subject to the mixed DML restriction in tests. - Move the setup DML into a future method and use
Test.startTest()andTest.stopTest()to force it to run.
@isTest
private class RoleCreationTest {
@isTest
static void futureCreatesRole() {
insert new Account(Name = 'Test Account');
Test.startTest();
SetupDmlHelper.createRole('Test Role', 'Test_Role');
Test.stopTest();
Integer count = [SELECT COUNT() FROM UserRole WHERE DeveloperName = 'Test_Role'];
System.assertEquals(1, count);
}
}Without Test.stopTest(), the future method would not have finished, and the assertion would fail.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Setup and non-setup DML in the same method | `MIXED_DML_OPERATION` | Move one side into a future method |
| Passing a `UserRole` record to the future method | Compile error, because sObjects are not allowed as parameters | Pass primitive values and build the record inside |
| Asserting before `Test.stopTest()` | Assertion fails because the future method has not run | Assert after `Test.stopTest()` |
| Calling the future method once per record in a loop | Future call limit reached | Pass a collection and call once |
Exercise
A trigger on Account inserts a Group record for each new account. It fails with MIXEDDMLOPERATION. Why does a future method fix this, and what should the future method accept as parameters?
Show answer
Group is a setup object and Account is a non-setup object, so both cannot be changed in one transaction. A future method runs in a separate transaction, so the Group DML no longer shares one with the Account DML. The method must be static and return void. It should accept primitives or collections of primitives, such as a Set<Id> of account IDs or a List<String> of names, and build the Group records inside. To stay within limits, the trigger should call it once with all the values from Trigger.new, not once per record.