Skip to content

DML_Transaction ​

Class · Group: DML

Learn it: Fast Start - DML and DML guide

apex
global virtual inherited sharing class DML_Transaction

Known Derived Types: API_Base, API_CallCurrentOrg, API_Inbound, API_Outbound

The engine that saves a set of DML operations across many SObjects as one transaction. This set is called a unit of work: the records registered to be saved together. By default, if one record fails, the whole save is rolled back. In partial mode, the records that save stay saved. The engine saves parent object types before their children, by sorting the types so each parent comes first. It fills each child's lookup with its parent's new Id. It also offers hooks, methods a subclass can override to run its own code at fixed points of the save.

Example

apex
DML_Transaction aTransaction = new DML_Transaction();
aTransaction.registerInsert(account);
aTransaction.registerInsert(contact, Contact.AccountId, account);
aTransaction.commitWork();

See Also: DML_Builder


Methods ​

MethodDescription
global virtual void commitWork()Commits all registered DML operations using inherited sharing.
global virtual void commitWork(Boolean enforceSharing)Saves all registered DML operations, with the record sharing you choose.
global void doDelete(List<SObject> records)Registers multiple records for deletion.
global void doDelete(SObject record)Registers a record for deletion.
global void doInsert(List<SObject> records)Registers multiple records for insertion.
global void doInsert(SObject record)Registers a record for insertion.
global void doInsert(SObject child, SObjectField relationshipField, SObject parent)Registers a child record for insertion with a relationship to a parent record.
global void doSave(SObject record)Saves a record by inserting (if no Id) or updating (if Id exists).
global void doUndelete(List<SObject> records)Registers multiple records for undelete.
global void doUndelete(SObject record)Registers a record for undelete.
global void doUpdate(List<SObject> records)Registers multiple records for update.
global void doUpdate(SObject record)Registers a record for update.
global void doUpdate(SObject record, SObjectField relationshipField, SObject parent)Registers a record for update with a relationship to a parent record.
global void doUpsert(List<SObject> records)Registers multiple records for upsert without an external ID field.
global void doUpsert(List<SObject> records, SObjectField externalIdField)Registers multiple records for upsert using a specific external ID field.
global void doUpsert(SObject record)Registers a record for upsert without an external ID field.
global void doUpsert(SObject record, SObjectField externalIdField)Registers a record for upsert using a specific external ID field.
global void doUpsert(SObject child, SObjectField relationshipField, SObjectField externalIdField, SObject parent)Registers a child record for upsert with a parent relationship and external ID field.
global virtual void onCommitWorkFinished(Boolean wasSuccessful)Hook called after the commit process finalizes, indicating success or failure.
global virtual void onCommitWorkFinishing()Hook called after DML operations but before finalization.
global virtual void onCommitWorkStarting()Hook called before the commit process starts.
global virtual void onDMLFinished()Hook called after DML operations complete.
global virtual void onDMLStarting()Hook called before DML operations start.
global void setAccessLevel(AccessLevel accessLevel)Sets the AccessLevel passed to every DML operation through the DML_SharingProxy methods that take an access level.
global void setAllowPartial(Boolean allow)Sets whether partial success is allowed for DML operations.
global void setSuppressLogging(Boolean suppress)Sets whether to turn off LOG_Builder error logging for DML failures.

commitWork ​

apex
global virtual void commitWork()

Commits all registered DML operations using inherited sharing.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doInsert(new Account(Name = 'Test'));
dmlTransaction.commitWork();
apex
global virtual void commitWork(Boolean enforceSharing)

Saves all registered DML operations, with the record sharing you choose. A retry count can be set, usually through DML_Builder.withRetryOnLock. When it is set and the platform refuses a row lock, the save is rolled back and runs again. The hooks run once for each attempt. Static values a failed attempt set are not reset. A retry puts back the registered records as they were when commitWork was called. Records a hook registers during an attempt are not put back, and a record the hook registers again keeps the Id the rolled-back attempt gave it. Every attempt empties the transaction's in-memory query cache (the query results kept in memory for reuse) before its first statement and again when it ends, whatever the outcome. So a read after a save never gets rows from before the save, or from a save that was rolled back.

In user mode (no access level set while the UserModeDml_Enabled flag is on, or setAccessLevel(AccessLevel.USER_MODE)), enforceSharing set to false still keeps the running user's object and field permissions. A field the user cannot create or edit is left out of the save and logged as a warning, with no error. A save the user has no object permission for, an upsert on an external Id field the user cannot read or edit, and a save that would leave out the field that links a record to its parent are refused as user mode refuses them. A record that names its parent only by an external Id the user cannot read is refused by Salesforce, with a message that does not name the field. These checks use only the running user's own permissions. When you set user mode with a permission set, through setAccessLevel(AccessLevel.USER_MODE.withPermissionSetId(permissionSetId)), these checks do not run. The save goes to Salesforce as it is, in user mode with that permission set. Salesforce applies the running user's object and field permissions plus those of the permission set. It also applies record sharing. So false does not ignore record sharing for such a save. A save that must ignore record sharing cannot use a permission set. Set AccessLevel.USER_MODE and give the user the permissions, or set system mode. In system mode, set through setAccessLevel(AccessLevel.SYSTEM_MODE) or by turning the flag off, false waives those permission checks too.

A commit that ignores record sharing or that runs in the system mode you chose is recorded in the bypass audit. When enforceSharing is false, each commit that saves records writes one entry for each object it saves, with the target sharing: followed by the object's API name, such as sharing:Account. When you set AccessLevel.SYSTEM_MODE through setAccessLevel and the level is still system mode, each such commit also writes a system-mode: entry for each object. Each entry names the object, the operations, the number of rows and the class and method that called commitWork. The entries are written once for each call, before the first statement, even when the save is retried after a row lock. A commit that saves nothing writes none.

Parameters

ParameterTypeDescription
enforceSharingBooleanTrue enforces the running user's record sharing, null uses the calling class's sharing, and false ignores record sharing.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpdate(recordOwnedByAnotherUser);
// Ignores record sharing; the running user's object and field permissions still apply.
dmlTransaction.commitWork(false);
DML_Transaction systemTransaction = new DML_Transaction();
systemTransaction.setAccessLevel(AccessLevel.SYSTEM_MODE);
systemTransaction.doUpdate(recordOwnedByAnotherUser);
// Ignores record sharing and the running user's object and field permissions.
systemTransaction.commitWork(false);

doDelete ​

apex
global void doDelete(List<SObject> records)

Registers multiple records for deletion.

Parameters

ParameterTypeDescription
recordsListThe list of SObjects to delete.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doDelete(obsoleteRecords);
dmlTransaction.commitWork();
apex
global void doDelete(SObject record)

Registers a record for deletion.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to delete.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doDelete(obsoleteRecord);
dmlTransaction.commitWork();

doInsert ​

apex
global void doInsert(List<SObject> records)

Registers multiple records for insertion.

Parameters

ParameterTypeDescription
recordsListThe list of SObjects to insert.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doInsert(new List<Account>{new Account(Name = 'A'), new Account(Name = 'B')});
dmlTransaction.commitWork();
apex
global void doInsert(SObject record)

Registers a record for insertion.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to insert.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doInsert(new Account(Name = 'Test'));
dmlTransaction.commitWork();
apex
global void doInsert(SObject child, SObjectField relationshipField, SObject parent)

Registers a child record for insertion with a relationship to a parent record. The child's relationship field will be populated with the parent's Id after commit.

Parameters

ParameterTypeDescription
childSObjectThe child SObject to insert.
relationshipFieldSObjectFieldThe field linking the child to the parent (e.g., Contact.AccountId).
parentSObjectThe parent SObject.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
Account parent = new Account(Name = 'Parent');
Contact child = new Contact(LastName = 'Child');
dmlTransaction.doInsert(parent);
dmlTransaction.doInsert(child, Contact.AccountId, parent);
dmlTransaction.commitWork();

doSave ​

apex
global void doSave(SObject record)

Saves a record by inserting (if no Id) or updating (if Id exists). Convenience method for mixed operations.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to save.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doSave(new Account(Name = 'Test'));
dmlTransaction.commitWork();

doUndelete ​

apex
global void doUndelete(List<SObject> records)

Registers multiple records for undelete.

Parameters

ParameterTypeDescription
recordsListThe list of SObjects to undelete.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUndelete(deletedAccounts);
dmlTransaction.commitWork();
apex
global void doUndelete(SObject record)

Registers a record for undelete.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to undelete.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUndelete(deletedAccount);
dmlTransaction.commitWork();

doUpdate ​

apex
global void doUpdate(List<SObject> records)

Registers multiple records for update.

Parameters

ParameterTypeDescription
recordsListThe list of SObjects to update.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpdate(existingAccounts);
dmlTransaction.commitWork();
apex
global void doUpdate(SObject record)

Registers a record for update.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to update.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpdate(existingAccount);
dmlTransaction.commitWork();
apex
global void doUpdate(SObject record, SObjectField relationshipField, SObject parent)

Registers a record for update with a relationship to a parent record.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to update.
relationshipFieldSObjectFieldThe field linking the record to the parent.
parentSObjectThe parent SObject whose Id will be set on the relationship field.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpdate(contact, Contact.AccountId, newAccount);
dmlTransaction.commitWork();

doUpsert ​

apex
global void doUpsert(List<SObject> records)

Registers multiple records for upsert without an external ID field.

Parameters

ParameterTypeDescription
recordsListThe list of SObjects to upsert.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpsert(accounts);
dmlTransaction.commitWork();
apex
global void doUpsert(List<SObject> records, SObjectField externalIdField)

Registers multiple records for upsert using a specific external ID field.

Parameters

ParameterTypeDescription
recordsListThe list of SObjects to upsert.
externalIdFieldSObjectThe external ID field for matching.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpsert(accounts, Account.ExternalId__c);
dmlTransaction.commitWork();
apex
global void doUpsert(SObject record)

Registers a record for upsert without an external ID field. Uses the record's Id field for matching if present.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to upsert.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpsert(account);
dmlTransaction.commitWork();
apex
global void doUpsert(SObject record, SObjectField externalIdField)

Registers a record for upsert using a specific external ID field. All records of the same SObjectType within a single transaction must use the same external ID field.

Parameters

ParameterTypeDescription
recordSObjectThe SObject to upsert.
externalIdFieldSObjectFieldThe external ID field for matching.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpsert(account, Account.ExternalId__c);
dmlTransaction.commitWork();
apex
global void doUpsert(SObject child, SObjectField relationshipField, SObjectField externalIdField, SObject parent)

Registers a child record for upsert with a parent relationship and external ID field.

Parameters

ParameterTypeDescription
childSObjectThe child SObject to upsert.
relationshipFieldSObjectFieldThe field linking the child to the parent.
externalIdFieldSObjectFieldThe external ID field for matching.
parentSObjectThe parent SObject.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.doUpsert(child, Contact.AccountId, Contact.ExternalId__c, parent);
dmlTransaction.commitWork();

onCommitWorkFinished ​

apex
global virtual void onCommitWorkFinished(Boolean wasSuccessful)

Hook called after the commit process finalizes, indicating success or failure. It runs after the transaction's in-memory query cache has been emptied, so a read made here is cached like any other and sees the rows as they are after the attempt, whether it was saved or rolled back. It runs once for each attempt of the commit: when the commit is set to try again after a row lock (DML_Builder.withRetryOnLock does that, and an API handler's commit tries again once), it runs with false after the attempt that was refused and again after the next attempt. So write what you do here so that it is safe to run more than once, and do work that must happen once only when the value is true.

Parameters

ParameterTypeDescription
wasSuccessfulBooleanWhether the attempt that just ended was successful.

Example

apex
global override void onCommitWorkFinished(Boolean wasSuccessful)
{
    super.onCommitWorkFinished(wasSuccessful);
    if(wasSuccessful)
    {
        // custom post-commit logic
    }
}

onCommitWorkFinishing ​

apex
global virtual void onCommitWorkFinishing()

Hook called after DML operations but before finalization.

Example

apex
global override void onCommitWorkFinishing()
{
    super.onCommitWorkFinishing();
    // custom pre-finalization logic
}

onCommitWorkStarting ​

apex
global virtual void onCommitWorkStarting()

Hook called before the commit process starts. Work registered here is committed with the rest and, in an all-or-nothing commit, rolled back with it when a later statement fails. A read made here is cached like any other read and is from before this commit's write. It runs once for each attempt of the commit: when the commit is set to try again after a row lock (DML_Builder.withRetryOnLock does that, and an API handler's commit tries again once), it runs again for the new attempt. So write what you do here so that it is safe to run more than once.

Example

apex
global override void onCommitWorkStarting()
{
    super.onCommitWorkStarting();
    // custom pre-commit logic
}

onDMLFinished ​

apex
global virtual void onDMLFinished()

Hook called after DML operations complete.

Example

apex
global override void onDMLFinished()
{
    super.onDMLFinished();
    // custom post-DML logic
}

onDMLStarting ​

apex
global virtual void onDMLStarting()

Hook called before DML operations start. A read made here is cached like any other read and is from before this commit's write.

Example

apex
global override void onDMLStarting()
{
    super.onDMLStarting();
    // custom pre-DML logic
}

setAccessLevel ​

apex
global void setAccessLevel(AccessLevel accessLevel)

Sets the AccessLevel passed to every DML operation through the DML_SharingProxy methods that take an access level. When it is null, the proxy uses the default that the UserModeDml_Enabled flag sets.

System mode skips the running user's object and field permission checks, so it is recorded in the bypass audit. When you set AccessLevel.SYSTEM_MODE here and the level is still system mode when you call commitWork, each commit that saves records writes one audit entry for each object it saves. The entry's target is system-mode: followed by the object's API name, such as system-mode:Account. It also names the object, the operations (insert, update and so on), the number of rows and the class and method that called commitWork. If you set another level before the commit, or the commit saves nothing, no entry is written.

Parameters

ParameterTypeDescription
accessLevelAccessLevelThe AccessLevel to apply; null to use the default that the flag sets.

Example

apex
DML_Transaction transaction = new DML_Transaction();
transaction.setAccessLevel(AccessLevel.SYSTEM_MODE);
transaction.doInsert(records);
transaction.commitWork();

setAllowPartial ​

apex
global void setAllowPartial(Boolean allow)

Sets whether partial success is allowed for DML operations. When enabled, failed records do not cause the entire transaction to roll back.

Parameters

ParameterTypeDescription
allowBooleanTrue to allow partial success, false for all-or-nothing (default).

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.setAllowPartial(true);
dmlTransaction.doInsert(records);
dmlTransaction.commitWork();

setSuppressLogging ​

apex
global void setSuppressLogging(Boolean suppress)

Sets whether to turn off LOG_Builder error logging for DML failures. When it is on, failed rows in a partial save are not logged, and neither is a failed save. That covers the ERROR entry an all-or-nothing save writes after it rolls back, just before it throws the exception again. It also covers the ERROR entry a partial save writes when it catches an exception thrown during the save and carries on. It also covers the warning commitWork(false) logs in user mode when it leaves out fields the user cannot create or edit.

Parameters

ParameterTypeDescription
suppressBooleanTrue to suppress logging, false to allow logging (default).

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();
dmlTransaction.setAllowPartial(true);
dmlTransaction.setSuppressLogging(true);
dmlTransaction.doInsert(records);
dmlTransaction.commitWork();

Constructors ​

ConstructorDescription
global DML_Transaction()Initializes a new transaction with empty collections for managing DML operations.

DML_Transaction() ​

apex
global DML_Transaction()

Initializes a new transaction with empty collections for managing DML operations.

Example

apex
DML_Transaction dmlTransaction = new DML_Transaction();