D'fflib
WHATFeatures

Selectors 2.0

Providing full SOQL support, while unlocking proper unit test methods for the selector layer.

Highlights & takeaways

D'fflib enables security/sharing-agnostic methods by enabling calling classes to define the Database Context. This unlocks proper test assertions, while preventing query-calls and comes with a full set of supporting methods to reduce complexity and repetitive code. Additionally, there is now full support for AggregateResults, Cursor and SOQL functions like DISTANCE and TYPEOF. Each selector can be upgraded individually, allowing a gradual adoption.

Selectors have the single responsibility to fetch the desired SObject records from the database, while respecting security and sharing settings. D'fflib aims to enable developers to apply best-practices (like proper unit tests and asserts), while reducing the number of code lines and complexity needed to achieve this.

Main enrichments to the Selectors and QueryFactory

All enrichments are elaborated with code examples below.

Simplified application of security management, making methods automatically reusable for different Contexts

To deviate sharing (without or inherit) for a selector method in fflib, one had to create a without sharing annotated inner class and optionally introduce a withSharing Boolean input parameter to allow method reuse for different sharing contexts (see snippet below). D'fflib simplifies this by allowing you to construct a Selector instance in a specific Database Context, implying:

  • Methods become agnostic for Database Contexts, enabling reuse and making context specific logic redundant;
  • enforceFLS/enforceCRUD are replaced by Context (like FLSEnforcement and DataAccess before), reducing the number of Booleans for newQueryFactory( true )

Proper test assertions and support

For this simplification (#1), the responsibility of calling Database-query-methods shifted to the Query Proxy class, as no Database.query is called anymore in a selector method. This means all Database methods can now be mocked/avoided during unit test runtime.

Additionally, to centralise and eliminate repetitive boilerplate code D'fflib comes with built-in unit test methods, automatically mocking the Proxy class to prevent query-execution and providing simple verification methods.

For unit tests of classes calling selector methods, defineMock() was introduced to centralise layer-mocking, but also significantly reduce boilerplate code and prevent unexpected behaviour when not mocking the sObjectType() selector class method.

Full Aggregate Results support (construction and mocking)

D'fflib fully supports:

  • The construction of queries with SOQL functions like AVG, SUM, COUNT, MIN and MAX (also in legacy form with enforceFLS and getFieldPath())
  • Applying a HAVING condition to filter GROUP BY queries
  • The ability to validate and mock AggregateResults. Introducing dfflib_AggregateResult to overcome Apex's AggregateResult construction restriction.

→ Code example

Cursor support

With Spring '26 (API 66) Salesforce introduced Database.Cursor to break down large SOQL query results into manageable chunks, preventing heap size limits or governor limits while processing large volume data. Our Selectors support all Cursor-related Database methods, and bring assertion-shortcuts for unit tests. → Code example

Support for SOQL functions like DISTANCE, TYPEOF and FOR-clauses

The QueryFactory now supports TYPEOF (WHEN [SObjectType] THEN [FieldList]), the ability to add ORDER BY DISTANCE..., or to specify for what reason the record is retrieved (FOR VIEW, FOR REFERENCE or FOR UPDATE). This is done through the following new methods and enum:

  • DistanceUnit being a new enum with MILES and KILOMETERS values
  • getDistanceString( SObjectField field, DistanceUnit unit )
  • selectFieldsTypeOf( String field, Map<Schema.SObjectType, Set<Schema.SObjectField>> typeOfMapping )
  • setForView( Boolean ), setForReference( Boolean ), setForUpdate( Boolean )
  • setAllRows( Boolean allRows )

Ability to auto-select (parent/)related fields

Comparable to getSObjectFieldList() we've added virtual Set<String> getRelatedFieldSet() to simplify default inclusion of related (parent-)fields. This is e.g. most useful for junction objects (like PricebookEntry) where you'd always want information from the related Product and Pricebook.

  • newQueryFactory( Boolean includeSelectorFields, Boolean includeRelatedFieldSetFields )

Performance benefits

Selectors 2.0 removes overhead that is rarely needed, reducing CPU time for every query and unit test:

  • Simplified field-selection - With dfflib_Database.Context the Field Level Security validation moves to the platform (USER_MODE/SYSTEM_MODE), so getFieldPath() no longer performs regex matching, SObjectDescribe lookups and getDescribe() calls for each field and relationship. Only legacy constructions where enforceFLS = true will still resolve describes to secure with a client-side FLS check;
  • Unsorted select fields by default - Originally, fflib would default sort all fields before performing the query, which thus consumed CPU time on each query without a SOQL benefit. Subselects follow the setting of their parent QueryFactory;
  • Faster unit tests - With mockExecuteQuery() selector unit tests no longer need to insert data or perform queries, which significantly reduces unit test runtime and data setup boilerplate (→ Unit test validations).

Possible impact by default unsorted queries

dfflib_SObjectSelector.m_sortSelectFields now defaults to false (previously true). This only impacts logic depending on the field order, like unit tests comparing the full toSOQL() string. If an external system really depends on the sequence, it's recommended to disconnect this dependency via middleware or a wrapper-class. When still really needed, it's possible to call setSortSelectFields( true ) on a QueryFactory instance to revert to sorting behaviour.

Correction for getSObjectType() and getSObjectFieldList()

Per API 65, an abstract or override method requires a protected, public, or global access modifier. If these aren't explicitly set, the method access defaults to private. Which will cause the (new) Apex compilation error "Abstract methods require at least one of the following: global, public, protected.", since the implementing class would otherwise have no access to the abstract method.

Hence, we've added the protected access modifier, which impacts all existing implementations, by making the abstract method visible and should therefore be overridden when implemented. More information can be found in the upgrade guide.

Migration & Examples

Each selector can individually be migrated to D'fflib, allowing a gradual approach. Due to backward compatibility, all original constructions with enforceFLS, FLSEnforcement and DataAccess continue to work as expected.

Calling class changes

SEL_Assets.newInstance( dfflib_Database.Context.NONE )
    .selectCarsBySerialNumber( new Set<String>{ 'SN123', 'SN456' } );
SEL_Assets.newInstance()
    .selectCarsBySerialNumber( new Set<String>{ 'SN123', 'SN456' }, false );

Selector class changes

Enabling the calling class to define the dfflib_Database.Context for the selector instance, allows you to omit the local WithoutSharing inner-class and the withSharing Boolean parameter. Additionally, it omits the need for local copies of static for bind variables to work, as these can be directly passed into the Map as shown in the example for the recordtype static.

public with sharing class SEL_Assets extends dfflib_SObjectSelector{
    public static SEL_Assets newInstance( dfflib_Database.Context ctx ){ 
        return ( SEL_Assets ) dfflib.selector.newInstance( Asset.SObjectType, ctx ); 
    }

    public override Schema.SObjectType getSObjectType(){
        return Asset.SObjectType;
    }

    public override List<Schema.SObjectField> getSObjectFieldList(){
        return new List<Schema.SObjectField>{
            Asset.AccountId,
            // ...
        };
    }

    public List<Asset> selectCarsBySerialNumber( Set<String> serialNums ){
        dfflib_QueryFactory query = newQueryFactory( true ); 
        query.setCondition( String.join( new List<String>{
            'RecordType.DeveloperName = :carsRecType',
            'SerialNumber IN :serialNums'
        }, ' AND ' ) );

        return this.executeQuery( query, new Map<String, Object>{ 
            'carsRecType' => DOM_Assets.RECTYPE_CARS, 
            'serialNums' => serialNums 
        } ); 
    }
}
public with sharing class SEL_Assets extends fflib_SObjectSelector{
    public static SEL_Assets newInstance(){ 
        return ( SEL_Assets ) Application.selector.newInstance( Asset.SObjectType ); 
    }

    public override Schema.SObjectType getSObjectType(){
        return Asset.SObjectType;
    }

    public override List<Schema.SObjectField> getSObjectFieldList(){
        return new List<Schema.SObjectField>{
            Asset.AccountId,
            // ...
        };
    }

    public List<Asset> selectCarsBySerialNumber( Set<String> serialNums, Boolean withSharing ){
        fflib_QueryFactory query = newQueryFactory( withSharing, withSharing, true );
        String carsRecType = DOM_Assets.RECTYPE_CARS; 
        query.setCondition( String.join( new List<String>{
            'RecordType.DeveloperName = :carsRecType',
            'SerialNumber IN :serialNums'
        }, ' AND ' ) );

        return ( withSharing ) 
            ? Database.query( query.toSOQL() ) 
            : new WithoutSharing().queryWithFramenumbersAndRecType( query, serialNums, carsRecType ); 
    }

    public without sharing class WithoutSharing{ 
        public List<Asset> queryWithFramenumbersAndRecType( fflib_QueryFactory query, Set<String> serialNums, String carsRecType ){ 
            return Database.query( query.toSOQL() ); 
        } 
    } 
}

Test class changes

Once the D'fflib method executeQuery() is called in the Selector it is possible to avoid the query to be performed in unit tests and thoroughly validate the single responsibility of the selector.

Before there were three sub-optimal unit test assertion approaches:

  • Create data and validate a proper return. Causing longer unit-test runtimes.
  • Use Limits.getQueryRows() to assert the number of queries performed. Only validating Database.query() but not the query construction.
  • Implement a @TestVisible lastQueryFactory in fflib_QueryFactory which is set upon toSOQL() to allow assertions

Now you can:

  1. mockExecuteQuery() to avoid database interactions in unit test
  2. Leverage selector.verifyQuery() with the SelectorVerificationResults methods (see next section)
  3. Optionally fetch the QueryFactory for additional assertions (like subselects)

Examples of a unit test for a selector method

@IsTest
private static void selectCarsBySerialNumber(){
    // create mocks to prevent database calls
    SEL_Assets selector = SEL_Assets.newInstance( dfflib_Database.Context.FULL );
    fflib_ApexMocks mocks = selector.mockExecuteQuery();

    // Given - setup Set to validate bind-passing
    Set<String> serialNums = new Set<String>{ '12345' };

    // When - perform test
    selector.selectCarsBySerialNumber( serialNums );

    // Then - validate query, condition and fields
    selector.verifyQueryAndBindVariableKeys( mocks )
        .validateCondition( 'SerialNumber IN :serialNums' )
        .validateBindVariableValue( 'serialNums', serialNums )
        .validateFields( new Set<SObjectField>{ Asset.AccountId, Asset.SerialNumber } );
}
@IsTest
private static void selectCarsBySerialNumber_Data(){
    // Given - create data
    Asset a = new Asset(
        SerialNumber = '12345',
        RecordTypeId = // ...
    );
    insert a;

    // When - perform test
    List<Asset> assList = SEL_Assets.newInstance().selectCarsBySerialNumber( new Set<String>{ a.SerialNumber }, false );

    // Then - validate data returned
    System.Assert.areEqual( 1, assList?.size(), 'Expected one Asset to match the soql criteria' );
}

@IsTest
private static void selectCarsBySerialNumber_Limits(){
    // When - perform test in both contexts (for coverage)
    SEL_Assets.newInstance().selectCarsBySerialNumber( new Set<String>{ '12345' }, false );
    SEL_Assets.newInstance().selectCarsBySerialNumber( new Set<String>{ '12345' }, true );

    // Then - validate only one query per context was performed
    System.Assert.areEqual( 2, Limits.getQueryRows(), 'Expected two queries to be performed, in both contexts' );
}
@IsTest
private static void selectCarsBySerialNumber(){
    // When - perform test
    SEL_Assets.newInstance().selectCarsBySerialNumber( new Set<String>{ '12345' }, false );

    // Then - validate QueryFactory instance used at last toSOQL() on condition and fields
    fflib_QueryFactory qf = fflib_QueryFactory.lastQueryFactory;
    System.assertEquals( 'SerialNumber IN :serialNums', qf.getCondition(), 'Expected different condition string' );
    Set<String> queriedFields = qf.getSelectedFields();
    Assert.isTrue( queriedFields.contains( 'AccountId' ), 'AccountId is required to check for Asset updates in API' );
    Assert.isTrue( queriedFields.contains( 'SerialNumber' ), 'SerialNumber is required to check for match in API input' );
}

Unit test validations

Each selector class automatically implements the following set of methods to simplify and strengthen unit test assertions:

Method signatureDescription
  • mockExecuteQuery()
  • mockExecuteAggregateQuery()

Prepares mocking to prevent database calls and initiates (and returns) the fflib_ApexMocks instance. For AggregateQuery the query-calls are automatically stubbed to return List<dfflib_AggregateResult>.

  • verifyQuery( fflib_ApexMocks )
  • verifyQueryLocator( fflib_ApexMocks )

Verifies whether the Query Proxy was called once with a query (locator) and captures the query string. Returns the SelectorVerificationResults instance for further validations.

  • verifyQueryAndBindVariableKeys( fflib_ApexMocks )
  • verifyQueryLocatorAndBindVariableKeys( fflib_ApexMocks )

Verifies whether the Query Proxy was called once with a query (locator) and bind variables and captures the query string and map. Automatically validates whether the bind variable keys in the query string match those in the map (keys). An Assertion is thrown when the number of variables and/or keys don't match. Returns the SelectorVerificationResults instance for further validations.

SelectorVerificationResults

To simplify assertions and reduce repetitive code the SelectorVerificationResults wrapper was introduced. It contains three variables for extensive validations (like subselects) and a couple frequently occurring methods.

VariableDescription
  • dfflib_QueryFactory qf
dfflib_QueryFactory instance used during last toSOQL().
  • String query
Query string captured from executeQuery(), thus sent to backend.
  • Map<String, Object> map_bindVariables
Map of bind-variables captured from executeQuery(), thus sent to backend.
Method signatureDescription
  • validateTable( SObjectType sObjType )
Assertion on matching SObjectType table.
  • validateFields( Set<SObjectField> fields )
  • validateFields( Set<String> fields )

Assertion on whether all input-fields are included in the QueryFactory. Automatically converts to lowercase to match on deduplicated fields.

  • validateCondition( String expectedCondition )
  • validateCondition( String expectedCondition, Boolean partialMatch )

Assertion on the SOQL condition, with an optional Boolean to allow partial matching.

  • validateBindVariableValue( String bindkey, Object expectedObj )

Assertion on the existence and value of a bind-variable in the captured map.


Except for the listed items, the content on this site is licensed under CC-BY-NC-4.0
and allows sharing, provided an appropriate credit and link to source.

On this page