D'fflib
WHATFeatures

Database context

D'fflib uses the user mode features from Spring '23 (API 57) to simplify how you control sharing and FLS/CRUD, and to (finally) enable proper unit tests for selectors.

Highlights & takeaways

D'fflib separates database interactions from Selectors and the Unit of Work, giving developers a much simpler and standardised way to define and control sharing and FLS/CRUD access. It also unlocks the ability to unit test a Selector, improves performance and reduces repetitive code.

Spring '23 (API 57) introduced WITH USER_MODE, System.AccessLevel and queryWithBinds. These made it possible to separate Database concerns from the Unit of Work and Selectors, significantly simplifying sharing and FLS controls, while reducing code volumes.

Main benefits

The new database context is fully backward compatible and can be gradually adopted, since each (selector) class can individually be migrated to leverage the (below) benefits:

Simplified security control

  • dfflib_Database.Context provides one enum that bundles both Sharing- & Permissions controls in one. Simplifying complexity (especially to junior developers).
  • Standardised syntax for both Selectors and Unit of Work to specify the desired Security Access Control (Database Context) (see #2).

Calling class specifies running Database Context

Each calling class can construct a Selector and/or Unit of Work in the desired Database Context, making methods reusable for different sharing contexts, without the need for customisations in the called-method (see #6), while granting full control over sharing- and FLS/CRUD enforcement.

dfflib_ISObjectUnitOfWork uow = dfflib.unitOfWork.newInstance( dfflib_Database.Context.INHERIT );
List<Lead> newLeads = SEL_Leads.newInstance( dfflib_Database.Context.FULL ).getPendingLeads();

Proper asserts in selector unit tests

Originally, one needed to call Database.query() directly in a selector. This made it impossible to prevent the query from executing in unit tests, and also required (time-consuming) test data creation to do some proper asserts. Now System.Database operations have been moved to the Database Proxy, making it possible to mock, and assert solely the single responsibility of the selector method (see #6).

Thus, this not only enables proper assertions, but also improves performance by eliminating the query and the need for test data creation.

Improved separation of concerns

We've untangled some responsibility ambiguity, giving each class a single and clear responsibility.

  • dfflib_SObjectUnitOfWork - record registration and memoisation;
  • dfflib_QueryFactory - query string construction;
  • dfflib_SObjectSelector - security control and calling QueryFactory;
  • dfflib_Database_DMLProxy - actual database interactions via System.Database.

Performance benefits by eliminating getFieldPath()

Originally in fflib, when enforcing FLS (Field Level Security), logic would gather DescribeFieldResult for each field in the QueryFactory to call .isAccessible(). With the introduction of WITH USER_MODE this validation is moved to optimised Salesforce backend, resulting in quite some performance benefit upon query execution and also eliminating custom regex to allow casts and other SOQL functions to pass getFieldPath().

Reduced custom implementations and duplicate code

  • Deprecation of custom IDML implementations for Unit of Work, as all different flavours are now pre-defined in dfflib_Database_DMLProxy.
  • No need for without sharing inner classes in selectors to bypass sharing context.

Faster and project independent fflib unit tests

Originally, the Unit of Work had to assert all complex scenarios, like relational insertions, requiring more complex test data constructions (like Opportunities with Line Items). Due to the separation of concerns UoW only needs to assert the registrations, since the Database Proxy is mocked. The Proxy in turn only needs to insert the 'simple' Database.insert() methods, resulting in:

  • Faster unit tests, as isParallel = true is unlocked when less test data is created.
  • Ability to move to simpler SObjectType (ContactRequest and Solution) in unit tests, as e.g. relations don't need to be tested in the database. Reducing test-failures due to project specific required fields or validations.
  • Cleaner and fewer unit test methods, due to untangled logic.

How it works

Database Context enum

The dfflib_Database.Context enum provides four options which can be specified for record/event manipulations (DML operations) and the retrieval of records (SOQL queries) to specify the desired running security context.

OptionSharingFLS/CRUDAccessLevelExamples
FULLwith sharingUSER_MODE
SHARING_SKIP_PERMISSIONSwith sharingSYSTEM_MODE
NONEwithout sharingSYSTEM_MODE
INHERITinherit sharingSYSTEM_MODE

Not all scenarios are 'encouraged'

No enum is introduced to enforce FLS/CRUD while relaxing sharing as we believe this is a rare use-case which conflicts with the best-practice of minimal record access. Additionally, this would add a dependency from the new dfflib_Database.Context structure to the legacy enforce-Booleans.

If you need to run a selector without sharing, while enforcing FLS and CRUD, this can be achieved by constructing dfflib_Database.Context.NONE while setting enforceFLS and enforceCRUD to TRUE using the legacy newQueryFactory (see Selector 2.0). This still eliminates the need for an inner-class (boilerplate code), while supporting existing requirements/implementations.

High-level setup

To gather a better understanding of the new Database Context functionality, here's a high-level overview of the involved classes and their responsibilities.

  1. Introduction of Proxy classes for Database operations

    • dfflib_Database_DMLProxy and dfflib_Database_QueryProxy
      Centralising all DML and SOQL operations for the different 'sharing' flavours (with, without and inherit) and modes (USER_MODE, SYSTEM_MODE). Thus, listing all Database methods wrapped in specific classes, like the original IDML.
  2. Introduction of dfflib_Database class

    • As (internal) access point to the Proxy classes.
    • Centralising database security modes to be used for setting sharing context and enforcement of CRUD/FLS on the respective interface implementation.
    • Deliberate shorter class name given the frequent references (e.g. dfflib_Database.Context.FULL).
  3. Introduction of dfflib_Database.Context enums

    • Defining the security context within the proxy interface and (independently!) controlling both sharing rules' context, and FLS/CRUD permission level
  4. Updated dfflib_Application factory newInstance() methods to accept a dfflib_Database.Context parameter

  5. Introduction of executeQuery methods in selectors (see Selectors 2.0).

  6. Introduction of SelectorVerificationResults and mockExecuteQuery methods for simplified selector unit test validations.

Technical storyline/background

It took quite some effort to get this functionality scalable and for those who're interested, this was because of the following:

  • Challenge to find a proper SObjectType which is available in all standard Salesforce instances.

    • Individual is only available when "Data Protection and Privacy" is enabled, which has become default disabled in newer environments.
    • ContactRequest, EmailMessage, Image, Macro, QuickText, and ScoreCare were considered, but by default Salesforce grants FLS, preventing FLS test methods.
  • When Shield encrypts the Name field of an object, this can't be sorted in a query and should thus be excluded in selector unit tests.

  • Changing Salesforce behaviours for stable unit tests

    • Per API 61 (Summer '24) EventBus.publish() throws a System.UnexpectedException when trying to publish an SObject instead of an Event.

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