### Complete Examples Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Provides complete examples of using the DML library for common operations like inserting records and verifying the results. ```APIDOC ### Basic Insert with Result ```apex Account account = new Account(Name = 'Test Account'); DML.Result result = new DML() .toInsert(account) .commitWork(); // Verify result Assert.areEqual(1, result.inserts().size()); DML.OperationResult operationResult = result.insertsOf(Account.SObjectType); Assert.areEqual(1, operationResult.records().size()); Assert.areEqual(1, operationResult.successes().size()); Assert.areEqual(0, operationResult.failures().size()); Assert.isFalse(operationResult.hasFailures()); Assert.areEqual(DML.OperationType.INSERT_DML, operationResult.operationType()); Assert.areEqual(Account.SObjectType, operationResult.objectType()); // Check record result DML.RecordResult recordResult = operationResult.recordResults()[0]; Assert.isTrue(recordResult.isSuccess()); Assert.isNotNull(recordResult.id()); Assert.areEqual(account.Id, recordResult.id()); ``` ``` -------------------------------- ### Install DML Lib via Unmanaged Package Source: https://context7.com/beyond-the-cloud-dev/dml-lib/llms.txt Install the DML Lib using the provided unmanaged package URL for either a Salesforce Sandbox or Production environment. ```bash # Install on Sandbox https://test.salesforce.com/packaging/installPackage.apexp?p0=04tP60000029HoT # Install on Production https://login.salesforce.com/packaging/installPackage.apexp?p0=04tP60000029HoT ``` -------------------------------- ### Install DML Lib via Unlocked Package Source: https://context7.com/beyond-the-cloud-dev/dml-lib/llms.txt Install the DML Lib using the provided unlocked package URL for either a Salesforce Sandbox or Production environment. ```bash # Install on Sandbox https://test.salesforce.com/packaging/installPackage.apexp?p0=04tP6000002RDBJIA4 # Install on Production https://login.salesforce.com/packaging/installPackage.apexp?p0=04tP6000002RDBJIA4 ``` -------------------------------- ### DML Result Example Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Perform a DML operation and inspect the results using the Result and OperationResult interfaces. This example demonstrates inserting accounts and checking the operation's metadata and outcomes. ```apex DML.Result result = new DML() .toInsert(accounts) .commitWork(); DML.OperationResult operationResult = result.insertsOf(Account.SObjectType); // Operation metadata Assert.areEqual(DML.OperationType.INSERT_DML, operationResult.operationType()); Assert.areEqual(Account.SObjectType, operationResult.objectType()); // Check for failures if (operationResult.hasFailures()) { List failedRecords = operationResult.failures(); List allErrors = operationResult.errors(); } // Get successful records List successfulRecords = operationResult.successes(); ``` -------------------------------- ### Standard DML with Sharing Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/sharing-mode.md Example of a 'with sharing' class context in standard Apex DML, where sharing rules are enforced. ```apex // In a "with sharing" class context public with sharing class MyClass { public void updateRecord(Contact contact) { update contact; // Sharing rules enforced } } ``` -------------------------------- ### DML Operation Commit Example Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Demonstrates how to commit DML operations and access the results. ```APIDOC ## POST /api/dml/commit ### Description Commits a set of DML operations and returns a Result object. ### Method POST ### Endpoint /api/dml/commit ### Request Body - **operations** (List) - Required - A list of DML operations to perform. ### Request Example ```json { "operations": [ { "type": "insert", "sobject": {"Name": "Test Account"} }, { "type": "update", "sobject": {"Id": "001xxxxxxxxxxxx", "Name": "Updated Account"} } ] } ``` ### Response #### Success Response (200) - **result** (Result) - An object containing the results of the DML operations. #### Response Example ```json { "result": { "inserts": [ { "operationType": "insert", "objectType": "Account", "hasFailures": false, "successes": [{"Id": "001xxxxxxxxxxxx", "Name": "Test Account"}], "failures": [], "recordResults": [ { "id": "001xxxxxxxxxxxx", "record": {"Name": "Test Account"}, "isSuccess": true, "errors": [] } ], "errors": [] } ], "updates": [ { "operationType": "update", "objectType": "Account", "hasFailures": false, "successes": [{"Id": "001xxxxxxxxxxxx", "Name": "Updated Account"}], "failures": [], "recordResults": [ { "id": "001xxxxxxxxxxxx", "record": {"Id": "001xxxxxxxxxxxx", "Name": "Updated Account"}, "isSuccess": true, "errors": [] } ], "errors": [] } ] } } ``` ``` -------------------------------- ### Publish multiple event types Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/publish.md Example of a service class that publishes multiple event types. This snippet demonstrates the code that would be tested. ```apex public class EventService { public void publishEvents() { new DML() .toPublish(new OrderEvent__e(OrderId__c = '12345')) .toPublish(new ShipmentEvent__e(TrackingNumber__c = 'ABC123')) .identifier('EventService.publishEvents') .commitWork(); } } ``` -------------------------------- ### Publish AlertEvent__e Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/publish.md Example of a service class that publishes an AlertEvent__e. This snippet demonstrates the code that would be tested. ```apex public class NotificationService { public void sendAlert() { new DML() .toPublish(new AlertEvent__e(Message__c = 'System Alert')) .identifier('NotificationService.sendAlert') .commitWork(); } } ``` -------------------------------- ### Publish AccountCreatedEvent__e Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/publish.md Example of a service class that publishes an AccountCreatedEvent__e. This snippet demonstrates the code that would be tested. ```apex public class NotificationService { public void notifyAccountCreated(Account account) { AccountCreatedEvent__e event = new AccountCreatedEvent__e( AccountId__c = account.Id, AccountName__c = account.Name ); new DML() .toPublish(event) .identifier('NotificationService.notifyAccountCreated') .commitWork(); } } ``` -------------------------------- ### Basic Account Insert Verification Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Perform a basic insert operation on an Account and thoroughly verify the results using assertions. This example checks the number of records, successes, failures, and details of the record result. ```apex Account account = new Account(Name = 'Test Account'); DML.Result result = new DML() .toInsert(account) .commitWork(); // Verify result Assert.areEqual(1, result.inserts().size()); DML.OperationResult operationResult = result.insertsOf(Account.SObjectType); Assert.areEqual(1, operationResult.records().size()); Assert.areEqual(1, operationResult.successes().size()); Assert.areEqual(0, operationResult.failures().size()); Assert.isFalse(operationResult.hasFailures()); Assert.areEqual(DML.OperationType.INSERT_DML, operationResult.operationType()); Assert.areEqual(Account.SObjectType, operationResult.objectType()); // Check record result DML.RecordResult recordResult = operationResult.recordResults()[0]; Assert.isTrue(recordResult.isSuccess()); Assert.isNotNull(recordResult.id()); Assert.areEqual(account.Id, recordResult.id()); ``` -------------------------------- ### Standard DML without Sharing Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/sharing-mode.md Example of a 'without sharing' class context in standard Apex DML, where sharing rules are bypassed. ```apex // In a "without sharing" class context public without sharing class MyClass { public void updateRecord(Contact contact) { update contact; // Sharing rules bypassed } } ``` -------------------------------- ### Upsert Records with DML Lib Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/upsert.md Insert new records or update existing ones based on record ID using the DML library. This example demonstrates upserting both an existing and a new account record. ```apex Account existingAccount = [SELECT Id, Name FROM Account LIMIT 1]; existingAccount.Name = 'Updated Name'; Account newAccount = new Account(Name = 'New Account'); new DML() .toUpsert(existingAccount) .toUpsert(newAccount) .systemMode() .withoutSharing() .commitWork(); ``` -------------------------------- ### Stage, Commit, and Push Changes Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/CONTRIBUTING.md Stage all your changes, commit them with a descriptive message, and push the branch to your fork. ```bash git add . git commit -m "feat: add support for XYZ feature" git push origin feature/my-awesome-feature ``` -------------------------------- ### Combining DML Options Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/dml-options.md Demonstrates how to chain multiple DML configuration methods to achieve complex DML behaviors in a single operation. ```APIDOC ## POST /dml/commitWork (Combined Options) ### Description Executes DML operations by combining multiple configuration methods, such as `allowPartialSuccess`, `skipDuplicateRules`, `systemMode`, and `withoutSharing`, for comprehensive control over the transaction. ### Method POST ### Endpoint /dml/commitWork ### Parameters #### Request Body - **operation** (string) - Required - The type of DML operation (e.g., 'insert', 'update'). - **records** (array) - Required - An array of SObject records. - **options** (object) - Optional - An object containing combined DML settings. - **allowPartialSuccess** (boolean) - Optional - Enables partial success mode. - **skipDuplicateRules** (boolean) - Optional - Skips duplicate rule evaluation. - **systemMode** (boolean) - Optional - Executes the operation in system context. - **withoutSharing** (boolean) - Optional - Executes the operation without enforcing user's sharing rules. ### Request Example ```json { "operation": "insert", "records": [ { "sobjectType": "Account", "Name": "Account 1" }, { "sobjectType": "Account" } ], "options": { "allowPartialSuccess": true, "skipDuplicateRules": true, "systemMode": true, "withoutSharing": true } } ``` ### Response #### Success Response (200) - **operationResults** (object) - Contains results of the DML operation, detailing successes and failures. #### Response Example ```json { "operationResults": { "insert": { "Account": { "successes": [ { "Id": "001aaaaaaaaaaa", "Name": "Account 1" } ], "failures": [ { "errors": [ { "message": "Required fields are missing: Name", "statusCode": "REQUIRED_FIELD_MISSING", "fields": ["Name"] } ], "record": { "sobjectType": "Account" } } ] } } } } ``` ``` -------------------------------- ### Basic DML Inserts with allOrNone=true Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture.md Demonstrates multiple DML insert operations where `allOrNone` is set to true. If any row fails, the entire `Database.insert` call fails and throws a `DmlException`. ```java Database.insert(accounts, true); Database.update(contacts, true); Database.insert(opportunities, true); ``` -------------------------------- ### Clone DML Lib Repository Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/CONTRIBUTING.md Clone your forked repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/YOUR_USERNAME/dml-lib.git cd dml-lib ``` -------------------------------- ### Discarding Pending DML Work Source: https://context7.com/beyond-the-cloud-dev/dml-lib/llms.txt Clears all pending DML operations without executing them. This is useful for resetting the DML state before starting new operations. ```apex DML dml = new DML(); dml.toInsert(account); dml.discardWork(); ``` -------------------------------- ### Insert Account and Contact with Relationship Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/introduction.md Demonstrates inserting an Account and a Contact, automatically setting the Contact's AccountId relationship using DML Lib. Ensure DML Lib is imported before use. ```apex Account account = new Account(Name = 'Acme Corp'); Contact contact = new Contact(LastName = 'Smith'); new DML() .toInsert(account) .toInsert(DML.Record(contact).withRelationship(Contact.AccountId, account)) .commitWork(); // contact.AccountId is automatically set to account.Id ``` -------------------------------- ### Get Insert Results by Operation Type Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Retrieve all insert operation results. This is useful for batch processing of inserts across different SObject types. ```apex DML.Result result = new DML() .toInsert(accounts) .toInsert(contacts) .commitWork(); // Get all insert results (one per SObject type) List insertResults = result.inserts(); Assert.areEqual(2, insertResults.size()); // Account and Contact ``` -------------------------------- ### Immediate Insert with Result Handling Source: https://context7.com/beyond-the-cloud-dev/dml-lib/llms.txt Perform an immediate insert operation and handle the results. Check for failures and access individual record results. ```apex // Immediate insert with result handling Account newAccount = new Account(Name = 'My Account'); DML.OperationResult result = new DML().insertImmediately(newAccount); if (!result.hasFailures()) { System.debug('Inserted with Id: ' + result.recordResults()[0].id()); } ``` -------------------------------- ### Get Insert Results for Specific SObject Type Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Retrieve insert operation results specifically for the Account SObject type. Use this to filter results for a particular object. ```apex DML.Result result = new DML() .toInsert(accounts) .toInsert(contacts) .commitWork(); // Get insert results for Accounts only DML.OperationResult accountResults = result.insertsOf(Account.SObjectType); DML.OperationResult contactResults = result.insertsOf(Contact.SObjectType); ``` -------------------------------- ### Iterating Through Record Results Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Process individual record results after a DML operation, handling both successful and failed records. This example shows how to log success messages with record IDs or error details. ```apex DML.Result result = new DML() .toInsert(accounts) .allowPartialSuccess() .commitWork(); DML.OperationResult operationResult = result.insertsOf(Account.SObjectType); for (DML.RecordResult recordResult : operationResult.recordResults()) { if (recordResult.isSuccess()) { System.debug('Record inserted with Id: ' + recordResult.id()); System.debug('Record: ' + recordResult.record()); } else { System.debug('Record failed:'); for (DML.Error error : recordResult.errors()) { System.debug(' - ' + error.message()); } } } ``` -------------------------------- ### Create Account with Mockable DML Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/mocking.md This Apex class demonstrates how to add an identifier to a DML insert operation for mocking purposes. ```apex public class AccountService { public void createAccount() { new DML() .toInsert(new Account(Name = 'Acme')) .identifier('AccountService.createAccount') .commitWork(); } } ``` -------------------------------- ### DML Lib Registration Order with Relationships Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture/registration.md DML Lib automatically resolves dependencies and commits records in the correct order using Kahn's algorithm. Register records in any sequence; DML Lib handles the execution order, including relationships. ```apex Account account = new Account(Name = 'Acme'); Contact contact = new Contact(LastName = 'Smith'); Opportunity opportunity = new Opportunity(Name = 'Deal', StageName = 'New', CloseDate = Date.today()); new DML() .toInsert(account) .toInsert(DML.Record(contact).withRelationship(Contact.AccountId, account)) .toInsert(DML.Record(opportunity).withRelationship(Opportunity.AccountId, account)) .commitWork(); ``` -------------------------------- ### Create Multiple Records with DML Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/insert.md This Apex code shows how to insert an Account and a Contact using the DML library. It chains `toInsert` calls and assigns an identifier for later result retrieval. This method is used to demonstrate mocking multiple SObject types. ```apex public class DataService { public void createRecords() { Account account = new Account(Name = 'Test Account'); Contact contact = new Contact(LastName = 'Doe'); new DML() .toInsert(account) .toInsert(contact) .identifier('DataService.createRecords') .commitWork(); } } ``` -------------------------------- ### Mock Account Creation in Apex Test Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/mocking.md This Apex test class shows how to register a mock for a specific DML operation, execute the code, and verify the mock results. ```apex @IsTest static void shouldCreateAccount() { // 1. Register mock DML.mock('AccountService.createAccount').allInserts(); // 2. Execute Test.startTest(); new AccountService().createAccount(); Test.stopTest(); // 3. Verify - no records in database, but results captured DML.Result result = DML.retrieveResultFor('AccountService.createAccount'); Assert.areEqual(1, result.insertsOf(Account.SObjectType).successes().size()); } ``` -------------------------------- ### Insert Single Account Immediately (DML Lib) Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Insert a single Account record immediately using the DML library, returning an OperationResult. DML settings are inherited. ```apex Account account = new Account(Name = 'My Account'); DML.OperationResult result = new DML().insertImmediately(account); ``` -------------------------------- ### Create Account with Contacts using DML Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/insert.md This Apex code demonstrates how to insert an Account and its related Contact using the DML library. It uses `toInsert` for both records and `commitWork` to execute the operations. The `identifier` is crucial for retrieving results later. ```apex public class AccountService { public void createAccountWithContacts() { Account account = new Account(Name = 'Test Account'); Contact contact = new Contact(LastName = 'Doe'); new DML() .toInsert(account) .toInsert(DML.Record(contact).withRelationship(Contact.AccountId, account)) .identifier('AccountService.createAccountWithContacts') .commitWork(); } } ``` -------------------------------- ### DML with try-catch and rethrow exception (allOrNone=true) Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture.md Demonstrates catching a `DmlException` and then rethrowing it. Rethrowing the exception causes the entire transaction to roll back, as the exception remains unhandled by the calling context. ```java try { Database.insert(accounts, true); Database.update(contacts, true); Database.insert(opportunities, true); } catch (DmlException e) { // logger throw e; } ``` -------------------------------- ### Insert Accounts with Partial Success Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/dml-options.md Use `allowPartialSuccess()` to permit some records to succeed while others fail. Always check the result for failures to prevent data integrity issues. ```apex List accounts = new List{ new Account(Name = 'Valid Account'), new Account() // Missing required Name field }; new DML() .toInsert(accounts) .allowPartialSuccess() .commitWork(); ``` -------------------------------- ### Apply Custom DML Options Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/dml-options.md Configure fine-grained DML behavior by passing custom `Database.DmlOptions` to the `options()` method. This allows for advanced control over DML operations. ```apex Database.DmlOptions options = new Database.DmlOptions(); options.optAllOrNone = false; options.allowFieldTruncation = true; new DML() .toInsert(account) .options(options) .commitWork(); ``` -------------------------------- ### Insert Single Record with Dynamic Field Setting Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Shows how to insert a single record and set field values dynamically using `DML.Record.with`. ```APIDOC ## POST /api/dml/insert ### Description Inserts a single record, allowing dynamic setting of field values. ### Method POST ### Endpoint /api/dml/insert ### Parameters #### Request Body - **record** (DML.Record) - Required - The record to insert, with dynamic fields specified. ### Request Example ```json { "record": { "sobject": { "type": "Contact", "LastName": "Doe" }, "fields": { "Email": "john@example.com" } } } ``` ### Response #### Success Response (200) - **operationResult** (DML.OperationResult) - Details of the insert operation. #### Response Example ```json { "operationResult": { "success": true, "errors": [], "recordId": "003XXXXXXXXXXXX" } } ``` ``` -------------------------------- ### Publish Multiple Platform Events Immediately with DML Lib Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/publish.md Publish multiple platform events immediately without calling `commitWork()`. All DML settings configured on the `DML` instance are inherited. ```apex List events = new List{ new MyEvent__e(Message__c = 'Event 1'), new MyEvent__e(Message__c = 'Event 2') }; DML.OperationResult result = new DML().publishImmediately(events); ``` -------------------------------- ### Insert Multiple Records with Dynamic Field Setting Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Demonstrates inserting multiple records and setting a common field value for all of them using `DML.Records.with`. ```APIDOC ## POST /api/dml/insert/multiple/fields ### Description Inserts multiple records, setting a specified field to a common value for all records. ### Method POST ### Endpoint /api/dml/insert/multiple/fields ### Parameters #### Request Body - **records** (DML.Records) - Required - A collection of records to insert, with a specified field and value to apply to all. ### Request Example ```json { "records": { "sobjects": [ { "attributes": {"type": "Contact"}, "LastName": "Doe" }, { "attributes": {"type": "Contact"}, "LastName": "Smith" } ], "field": "LeadSource", "value": "Web" } } ``` ### Response #### Success Response (200) - **operationResult** (DML.OperationResult) - Details of the insert operation for the batch. #### Response Example ```json { "operationResult": { "success": true, "errors": [], "recordIds": ["003XXXXXXXXXXXX", "003YYYYYYYYYYYY"] } } ``` ``` -------------------------------- ### Basic DML Inserts with allOrNone=false Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture.md Shows multiple DML insert operations with `allOrNone` set to false. This allows for partial commits, where successful rows are committed, and failed rows are not. No `DmlException` is thrown for row errors. ```java Database.insert(accounts, false); Database.update(contacts, false); Database.insert(opportunities, false); ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/CONTRIBUTING.md Create a new branch for your feature or bug fix. Use a descriptive name for the branch. ```bash git checkout -b feature/my-awesome-feature ``` -------------------------------- ### Test Account and Contact Inserts with Mocking Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/insert.md This Apex test verifies the `createAccountWithContacts` method by mocking all insert operations. It uses `DML.mock()` with an identifier and `allInserts()` to prevent database writes. Results are then retrieved using `DML.retrieveResultFor()` to assert that no records were actually inserted. ```apex @IsTest static void shouldCreateAccountWithContacts() { // Setup DML.mock('AccountService.createAccountWithContacts').allInserts(); // Test Test.startTest(); new AccountService().createAccountWithContacts(); Test.stopTest(); // Verify DML.Result result = DML.retrieveResultFor('AccountService.createAccountWithContacts'); Assert.areEqual(0, [SELECT COUNT() FROM Account], 'No records should be in database'); DML.OperationResult accountResult = result.insertsOf(Account.SObjectType); Assert.areEqual(1, accountResult.successes().size(), '1 account should be inserted'); DML.OperationResult contactResult = result.insertsOf(Contact.SObjectType); Assert.areEqual(1, contactResult.successes().size(), '1 contact should be inserted'); } ``` -------------------------------- ### Combine Multiple DML Options Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/dml-options.md Chain multiple configuration methods together to combine various DML behaviors, such as partial success, skipping duplicate rules, and specifying sharing modes. ```apex new DML() .toInsert(accounts) .allowPartialSuccess() .skipDuplicateRules() .systemMode() .withoutSharing() .commitWork(); ``` -------------------------------- ### Insert Parent and Child Records with DML Lib Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Use DML.Record to automatically handle parent-child relationships during insertion. Ensure the parent record is inserted first to obtain its ID. ```apex Account account = new Account(Name = 'Parent Account'); new DML().insertImmediately(account); Contact contact = new Contact(FirstName = 'John', LastName = 'Doe'); DML.OperationResult result = new DML() .insertImmediately(DML.Record(contact).withRelationship(Contact.AccountId, account)); ``` -------------------------------- ### Insert Multiple Accounts (DML Lib) Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Insert a list of Account records using the DML library. The operations are registered and executed upon commitWork(). ```apex List accounts = new List{ new Account(Name = 'Account 1'), new Account(Name = 'Account 2') }; new DML() .toInsert(accounts) .commitWork(); ``` -------------------------------- ### withSharing Method Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/sharing-mode.md Execute DML operations enforcing sharing rules. Records the user doesn't have access to will cause errors. ```APIDOC ## withSharing By default, the DML library uses `with sharing`, meaning it respects the sharing context of the calling class. Sharing mode is enforced by `userMode()`, which is the default mode. Only when `.systemMode()` is used, `.withSharing()` can control the sharing mode. Execute DML operations enforcing sharing rules. Records the user doesn't have access to will cause errors. ### Signature ```apex Commitable withSharing(); ``` ### Standard DML ```apex // In a "with sharing" class context public with sharing class MyClass { public void updateRecord(Contact contact) { update contact; // Sharing rules enforced } } ``` ### DML Lib ```apex new DML() .toUpdate(contact) .systemMode() .withSharing() .commitWork(); ``` ``` -------------------------------- ### Insert Single Account Immediately (Standard DML) Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Standard Apex DML to insert a single Account record immediately, returning a Database.SaveResult. ```apex Account account = new Account(Name = 'My Account'); Database.SaveResult result = Database.insert(account); ``` -------------------------------- ### Publish Multiple Platform Events with DML Lib Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/publish.md Register multiple platform events for publishing. The actual publish is executed when `commitWork()` is called. ```apex List events = new List{ new MyEvent__e(Message__c = 'Event 1'), new MyEvent__e(Message__c = 'Event 2'), new MyEvent__e(Message__c = 'Event 3') }; new DML() .toPublish(events) .commitWork(); ``` -------------------------------- ### Insert Multiple Accounts (Standard DML) Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Standard Apex DML for inserting a list of Account records. ```apex List accounts = new List{ new Account(Name = 'Account 1'), new Account(Name = 'Account 2') }; insert accounts; ``` -------------------------------- ### DML.Record and DML.Records for Dynamic Field/Relationship Handling Source: https://context7.com/beyond-the-cloud-dev/dml-lib/llms.txt Utilize `DML.Record()` for single record operations and `DML.Records()` for bulk operations, both supporting dynamic field assignment and relationship management. `DML.Record()` can also create records from an ID for updates. ```apex // Single record with dynamic fields Contact contact = new Contact(LastName = 'Doe'); new DML() .toInsert(DML.Record(contact) .with(Contact.Email, 'john@example.com') .with(Contact.Phone, '555-1234') .withRelationship(Contact.AccountId, account)) .commitWork(); ``` ```apex // Multiple records with shared values List contacts = new List{ new Contact(LastName = 'Doe'), new Contact(LastName = 'Smith') }; new DML() .toInsert(DML.Records(contacts) .with(Contact.LeadSource, 'Web') .withRelationship(Contact.AccountId, account)) .commitWork(); ``` ```apex // Create record from ID for updates Id contactId = '003xx000004TmlAAA'; new DML() .toUpdate(DML.Record(contactId) .with(Contact.Email, 'new@example.com')) .commitWork(); ``` ```apex // External ID relationship new DML() .toInsert(DML.Record(contact) .withRelationship(Contact.AccountId, Account.MyExternalId__c, 'EXT-001')) .commitWork(); ``` -------------------------------- ### Control Duplicate Rule Behavior with DML Options Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/dml-options.md Configure duplicate rule handling using `Database.DmlOptions`. Set `allowSave` to true to permit saving duplicates and `runAsCurrentUser` to respect the current user's permissions. ```apex Database.DmlOptions options = new Database.DmlOptions(); options.duplicateRuleHeader.allowSave = true; options.duplicateRuleHeader.runAsCurrentUser = true; new DML() .toInsert(accounts) .options(options) .commitWork(); ``` -------------------------------- ### Publish Single Platform Event Immediately with DML Lib Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/publish.md Publish a single platform event immediately without calling `commitWork()`. All DML settings configured on the `DML` instance are inherited. ```apex MyEvent__e event = new MyEvent__e(Message__c = 'Hello World'); DML.OperationResult result = new DML().publishImmediately(event); ``` -------------------------------- ### Insert Multiple Records with Parent Relationship Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Shows how to insert multiple child records and associate them with a parent record using `DML.Records.with`. ```APIDOC ## POST /api/dml/insert/multiple/relationship ### Description Inserts multiple records, establishing a relationship with a parent record for all of them. ### Method POST ### Endpoint /api/dml/insert/multiple/relationship ### Parameters #### Request Body - **records** (DML.Records) - Required - A collection of records to insert, with a specified relationship field and parent. ### Request Example ```json { "records": { "sobjects": [ { "attributes": {"type": "Contact"}, "LastName": "Doe" }, { "attributes": {"type": "Contact"}, "LastName": "Smith" } ], "relationship": { "field": "AccountId", "parentRecordId": "001XXXXXXXXXXXX" } } } ``` ### Response #### Success Response (200) - **operationResult** (DML.OperationResult) - Details of the insert operation for the batch. #### Response Example ```json { "operationResult": { "success": true, "errors": [], "recordIds": ["003XXXXXXXXXXXX", "003YYYYYYYYYYYY"] } } ``` ``` -------------------------------- ### DML.mock(String identifier).allInserts() Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/insert.md Mock all insert operations regardless of SObject type for a given identifier. ```APIDOC ## DML.mock(String identifier).allInserts() Mock all insert operations regardless of SObject type. ### Method ```apex DML.mock(String identifier).allInserts(); ``` ### Class Example ```apex public class DataService { public void createRecords() { Account account = new Account(Name = 'Test Account'); Contact contact = new Contact(LastName = 'Doe'); new DML() .toInsert(account) .toInsert(contact) .identifier('DataService.createRecords') .commitWork(); } } ``` ### Test Example ```apex @IsTest static void shouldMockMultipleSObjectTypes() { // Setup DML.mock('DataService.createRecords').allInserts(); // Test Test.startTest(); new DataService().createRecords(); Test.stopTest(); // Verify DML.Result result = DML.retrieveResultFor('DataService.createRecords'); Assert.areEqual(0, [SELECT COUNT() FROM Account], 'No accounts in database'); Assert.areEqual(0, [SELECT COUNT() FROM Contact], 'No contacts in database'); Assert.areEqual(2, result.inserts().size(), '2 SObject types mocked'); } ``` ``` -------------------------------- ### Combining FLS with Sharing Mode Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/field-level-security.md Demonstrates how Field-Level Security (FLS) and sharing modes can be combined for DML operations. ```APIDOC ## Combining FLS with Sharing Mode ### Description Field-level security and sharing mode are independent settings that work together. This section shows examples of combining `systemMode()` with sharing options. ### Method `systemMode().withSharing()` `systemMode().withoutSharing()` ### Endpoint N/A (Methods within DML object) ### Parameters None ### Request Example ```apex // Bypass FLS but enforce sharing rules new DML() .toUpdate(record) .systemMode() .withSharing() .commitWork(); // Bypass both FLS and sharing rules new DML() .toUpdate(record) .systemMode() .withoutSharing() .commitWork(); ``` ### Response N/A (Methods return a Commitable object) ### Response Example N/A ``` -------------------------------- ### DML Lib combineOnDuplicate() for Merging Duplicates Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture/registration.md Use `combineOnDuplicate()` to automatically merge duplicate registrations. Later registrations override earlier ones for specified fields, while preserving fields unique to earlier registrations. ```apex Account account = [SELECT Id, Name FROM Account LIMIT 1]; new DML() .combineOnDuplicate() .toUpdate(new Account(Id = account.Id, Name = 'New Account 1', Website = 'mywebsite.com')) .toUpdate(new Account(Id = account.Id, Name = 'New Account 2')) .commitWork(); ``` -------------------------------- ### DML Lib Dynamic Field Update Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/upsert.md DML Lib allows setting field values dynamically for multiple records in a single operation using `DML.Records.with()`. This is more efficient and readable for bulk updates. ```apex List contacts = new List{ new Contact(LastName = 'Doe'), new Contact(Id = existingId, LastName = 'Smith') }; DML.OperationResult result = new DML() .upsertImmediately(DML.Records(contacts).with(Contact.LeadSource, 'Web')); ``` -------------------------------- ### DML with try-catch and allOrNone=false Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture.md Demonstrates handling exceptions when `allOrNone` is false. While row errors do not throw `DmlException`, other exceptions like limit or mixed DML errors can still occur and should be handled. ```java try { Database.insert(accounts, false); Database.update(contacts, false); Database.insert(opportunities, false); } catch (DmlException e) { // logger } ``` -------------------------------- ### Best Practice: Always Check for DML Failures Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/result.md Iterate through all operation results using `result.all()` and check `operationResult.hasFailures()` to ensure proper error handling, especially when `allowPartialSuccess()` is used. ```apex DML.Result result = new DML() .toInsert(records) .allowPartialSuccess() .commitWork(); for (DML.OperationResult operationResult : result.all()) { if (operationResult.hasFailures()) { // Handle failures appropriately for (DML.Error error : operationResult.errors()) { System.debug('Error: ' + error.message()); } } } ``` -------------------------------- ### DML with Savepoint, try-catch, and rollback (allOrNone=true) Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture.md Shows how to use savepoints to achieve cross-call atomicity. If a `DmlException` occurs, `Database.rollback(sp)` is called to undo all DML operations performed since the savepoint was set. ```java Savepoint sp = Database.setSavepoint(); try { Database.insert(accounts, true); Database.update(contacts, true); Database.insert(opportunities, true); } catch (DmlException e) { Database.rollback(sp); // logger } ``` -------------------------------- ### Publish Platform Events with DML Source: https://context7.com/beyond-the-cloud-dev/dml-lib/llms.txt Publish platform events using `toPublish()` or `publishImmediately()`. Events can be combined with other DML operations in a single transaction. Supports publishing single or multiple events. ```apex // Publish single event MyEvent__e event = new MyEvent__e(Message__c = 'Hello World'); new DML() .toPublish(event) .commitWork(); ``` ```apex // Publish multiple events List events = new List{ new MyEvent__e(Message__c = 'Event 1'), new MyEvent__e(Message__c = 'Event 2') }; new DML() .toPublish(events) .commitWork(); ``` ```apex // Combine with DML operations Account account = new Account(Name = 'New Account'); AccountCreatedEvent__e event = new AccountCreatedEvent__e(AccountName__c = 'New Account'); new DML() .toInsert(account) .toPublish(event) .commitWork(); ``` -------------------------------- ### Mocking Merge Operations Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/merge.md This section covers how to mock merge operations using `DML.mock()` to prevent actual database writes during tests. It explains the prerequisites and how to retrieve the results of mocked operations. ```APIDOC ## Mocking Merge Operations Mock merge operations in unit tests to avoid actual database merges. ::: warning The `DML.mock()` and `DML.retrieveResultFor()` methods are `@TestVisible` and should only be used in test classes. ::: ::: tip - **No database operations**: Mocked merges don't touch the database - **Records must have IDs**: Both master and duplicate records must have IDs assigned before mocking - **Results are captured**: All operation details are available via `DML.retrieveResultFor()` - **Selective mocking**: Use `mergesFor()` to mock specific SObject types while allowing others to execute ::: ### Example Usage This example demonstrates mocking a merge operation within a service class and verifying it in a test. **Service Class:** ```apex public class AccountService { public void mergeAccounts(Id masterId, Id duplicateId) { Account master = [SELECT Id FROM Account WHERE Id = :masterId]; Account duplicate = [SELECT Id FROM Account WHERE Id = :duplicateId]; new DML() .toMerge(master, duplicate) .identifier('AccountService.mergeAccounts') .commitWork(); } } ``` **Test Class:** ```apex @IsTest static void shouldMergeAccounts() { // Setup Account master = new Account( Id = DML.randomIdGenerator.get(Account.SObjectType), Name = 'Master' ); Account duplicate = new Account( Id = DML.randomIdGenerator.get(Account.SObjectType), Name = 'Duplicate' ); DML.mock('AccountService.mergeAccounts').allMerges(); // Test Test.startTest(); new AccountService().mergeAccounts(master.Id, duplicate.Id); Test.stopTest(); // Verify DML.Result result = DML.retrieveResultFor('AccountService.mergeAccounts'); DML.OperationResult mergeResult = result.mergesOf(Account.SObjectType); Assert.areEqual(1, mergeResult.successes().size(), '1 merge should succeed'); } ``` ``` -------------------------------- ### Insert Single Record with Parent Relationship Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Demonstrates how to insert a child record and automatically establish its parent relationship using `DML.Record.withRelationship`. ```APIDOC ## POST /api/dml/insert ### Description Inserts a single record, automatically handling parent-child relationships when specified. ### Method POST ### Endpoint /api/dml/insert ### Parameters #### Request Body - **record** (DML.Record) - Required - The record to insert, potentially with relationship information. ### Request Example ```json { "record": { "sobject": { "type": "Contact", "FirstName": "John", "LastName": "Doe" }, "relationship": { "field": "AccountId", "parentRecordId": "001XXXXXXXXXXXX" } } } ``` ### Response #### Success Response (200) - **operationResult** (DML.OperationResult) - Details of the insert operation. #### Response Example ```json { "operationResult": { "success": true, "errors": [], "recordId": "003XXXXXXXXXXXX" } } ``` ``` -------------------------------- ### DML with try-catch and allOrNone=true Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture.md Illustrates handling potential `DmlException`s when `allOrNone` is true. Catching the exception prevents an unhandled exception from rolling back the entire transaction, but the failing call is reverted. ```java try { Database.insert(accounts, true); Database.update(contacts, true); Database.insert(opportunities, true); } catch (DmlException e) { // logger } ``` -------------------------------- ### Publish Single Platform Event with DML Lib Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/publish.md Register a single platform event for publishing. The actual publish is executed when `commitWork()` is called. ```apex MyEvent__e event = new MyEvent__e(Message__c = 'Hello World'); new DML() .toPublish(event) .commitWork(); ``` -------------------------------- ### Implement Merge Operation in Apex Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/mocking/merge.md This Apex class demonstrates how to implement a merge operation for Account records using the DML library. Ensure both master and duplicate records have IDs assigned before calling this method. ```apex public class AccountService { public void mergeAccounts(Id masterId, Id duplicateId) { Account master = [SELECT Id FROM Account WHERE Id = :masterId]; Account duplicate = [SELECT Id FROM Account WHERE Id = :duplicateId]; new DML() .toMerge(master, duplicate) .identifier('AccountService.mergeAccounts') .commitWork(); } } ``` -------------------------------- ### Insert Multiple Records Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/insert.md Demonstrates inserting a list of records using the `insertImmediately` method that accepts a list of SObjects. ```APIDOC ## POST /api/dml/insert/multiple ### Description Inserts multiple records from a list of SObjects. ### Method POST ### Endpoint /api/dml/insert/multiple ### Parameters #### Request Body - **records** (List) - Required - A list of SObject records to insert. ### Request Example ```json { "records": [ { "attributes": {"type": "Account"}, "Name": "Account 1" }, { "attributes": {"type": "Account"}, "Name": "Account 2" } ] } ``` ### Response #### Success Response (200) - **operationResult** (DML.OperationResult) - Details of the insert operation for the batch. #### Response Example ```json { "operationResult": { "success": true, "errors": [], "recordIds": ["001XXXXXXXXXXXX", "001YYYYYYYYYYYY"] } } ``` ``` -------------------------------- ### Combine DML Operations and Event Publishing with DML Lib Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/publish.md Combine event publishing with other DML operations like inserts. The actual publish is executed when `commitWork()` is called. ```apex Account account = new Account(Name = 'New Account'); AccountCreatedEvent__e event = new AccountCreatedEvent__e( AccountName__c = 'New Account' ); new DML() .toInsert(account) .toPublish(event) .commitWork(); ``` -------------------------------- ### DML with Savepoint, try-catch, and rollback (allOrNone=false) Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/architecture.md Illustrates using savepoints with `allOrNone=false`. Even though row errors don't throw exceptions, this pattern allows for rolling back a unit of work if other types of exceptions occur. ```java Savepoint sp = Database.setSavepoint(); try { Database.insert(accounts, false); Database.update(contacts, false); Database.insert(opportunities, false); } catch (DmlException e) { Database.rollback(sp); // logger } ``` -------------------------------- ### Sharing Mode Overview Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/configuration/sharing-mode.md Control how DML operations respect record-level sharing rules. ```APIDOC ## Sharing Mode Control how DML operations respect record-level sharing rules. ### Example ```apex System.runAs(minimalAccessUser) { new DML() .toUpdate(contact) .systemMode() .withSharing() .commitWork(); } ``` ### Use Cases #### Administrative Operations When performing admin-level operations that should bypass sharing: ```apex public class DataMigrationService { public void migrateRecords(List accounts) { new DML() .toUpdate(accounts) .systemMode() .withoutSharing() .commitWork(); } } ``` We suggest using `.systemMode().withoutSharing()` in triggers, as trigger logic should always be executed. ``` -------------------------------- ### Publish Platform Events Immediately Source: https://github.com/beyond-the-cloud-dev/dml-lib/blob/main/website/dml/publish.md Publish platform events immediately and return the operation result without calling `commitWork()`. All DML settings configured on the `DML` instance are inherited. ```APIDOC ## POST /dml/publishImmediately ### Description Publishes platform events immediately and returns the operation result without calling `commitWork()`. All DML settings configured on the `DML` instance are inherited. ### Method POST ### Endpoint /dml/publishImmediately ### Parameters #### Request Body - **records** (List) - Required - A list of platform event objects to be published. - **operation** (string) - Required - Must be 'publishImmediately'. ### Request Example ```json { "records": [ { "__Type__": "MyEvent__e", "Message__c": "Hello World" } ], "operation": "publishImmediately" } ``` ### Response #### Success Response (200) - **operationResult** (OperationResult) - An object containing the result of the publish operation. #### Response Example ```json { "operationResult": { "isSuccess": true, "errors": [] } } ``` ```