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.Contextprovides 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 viaSystem.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
IDMLimplementations for Unit of Work, as all different flavours are now pre-defined indfflib_Database_DMLProxy. - No need for
without sharinginner 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 = trueis unlocked when less test data is created. - Ability to move to simpler SObjectType (
ContactRequestandSolution) 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
→ HOW: Selector examples
→ HOW: Unit of Work examples
→ WHAT: Additional Selector enrichments
→ WHAT: Additional Unit of Work enrichments
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.
| Option | Sharing | FLS/CRUD | AccessLevel | Examples |
|---|---|---|---|---|
FULL | with sharing | USER_MODE | ||
SHARING_SKIP_PERMISSIONS | with sharing | SYSTEM_MODE | ||
NONE | without sharing | SYSTEM_MODE | ||
INHERIT | inherit sharing | SYSTEM_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.
-
Introduction of Proxy classes for Database operations
dfflib_Database_DMLProxyanddfflib_Database_QueryProxy
Centralising all DML and SOQL operations for the different 'sharing' flavours (with,withoutandinherit) and modes (USER_MODE,SYSTEM_MODE). Thus, listing allDatabasemethods wrapped in specific classes, like the originalIDML.
-
Introduction of
dfflib_Databaseclass- 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).
-
Introduction of
dfflib_Database.Contextenums- Defining the security context within the proxy interface and (independently!) controlling both sharing rules' context, and FLS/CRUD permission level
-
Updated
dfflib_ApplicationfactorynewInstance()methods to accept adfflib_Database.Contextparameter -
Introduction of
executeQuerymethods in selectors (see Selectors 2.0). -
Introduction of
SelectorVerificationResultsandmockExecuteQuerymethods 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.
Individualis only available when "Data Protection and Privacy" is enabled, which has become default disabled in newer environments.ContactRequest,EmailMessage,Image,Macro,QuickText, andScoreCarewere considered, but by default Salesforce grants FLS, preventing FLS test methods.
-
When Shield encrypts the
Namefield 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 aSystem.UnexpectedExceptionwhen trying to publish an SObject instead of an Event.
- Per API 61 (Summer '24)
Accelerators & Utilities
Our ambition is to reduce code repetitions and ease the life of developers, therefore a proper set of utilities and accelerating methods and defaults couldn't be missed.
Metadata driven
D'fflib is fully metadata-driven, meaning all layer definitions and configurations are stored in metadata files. Originally these definitions/mappings were hardcoded in Apex classes, which increased the risk for conflicts.