What is a DML Statement?

I know this seems like a really stupid question. But I am still often amazed by the SalesForce platform. Consider the following test:

static testMethod void testLimitDmlStatements()
{
    SObject record; // custom object set up elsewhere
    Test.startTest();
        insert record;
        system.assertEquals(1, Limits.getDmlStatements());
    Test.stopTest();
}

I somehow get an assertion error:

System.AssertException: Assertion Failed: Expected: 1, Actual: 0

The documentation on the Limits Class states:

getDMLStatements()

Returns the number of DML statements (such as insert, update or the database.EmptyRecycleBin method) that have been called.

How is it possible that inserting a record would not count as a DML Statement? I have a similar update test and the same assertion fails. Strangely enough, if I add another operation, the count does increment.

static testMethod void testLimitDmlStatements()
{
    SObject record; // custom object set up elsewhere
    Test.startTest();
        insert record;
        SObjectFactory.create(User.sObjectType); // inserts a User
        system.assertEquals(1, Limits.getDmlStatements());
    Test.stopTest();
}

The above test passes, as does the below…

static testMethod void testLimitDmlStatements()
{
    SObject record; // custom object set up elsewhere
    Test.startTest();
        system.assertEquals(0, Limits.getDmlStatements());
        insert record;
        system.assertEquals(1, Limits.getDmlStatements());
    Test.stopTest();
}

Answer

If the list to operate on is empty, it doesn’t count as an operation. In older releases, empty lists still counted against governor limits, but this is no longer true. The DML statement becomes a noop. This old behavior is the reason why you’ll often see code like “if(!mylist.isEmpty() update mylist;” Also, you can combine up to ten types of records into a single Sobject list, and it only counts as a single statement. The records in the list should be grouped together, as you’ll get an error if there are more than ten chunks. Each chunk is a contiguous set of the same Sobject type. The ten thousand record limit still applies normally.

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : sfdcfox

Leave a Comment