Newer Version Available
Enforce User Mode for Database Operations
You can run database operations in user mode rather than in the default system mode
by using SOQL or SOSL queries with special keywords or by using DML method
overloads.
Apex code runs in system mode by default, which means that it runs with substantially elevated permissions over the user running the code. To enhance the security context of Apex, you can specify user mode access for database operations. Field-level security (FLS) and object permissions of the running user are respected in user mode, unlike in system mode. User mode always applies sharing rules, but in system mode they’re controlled by sharing keywords on the class. See Using the with sharing, without sharing, and inherited sharing Keywords.
You can indicate the mode of the operation by using WITH
USER_MODE or WITH SYSTEM_MODE in your
SOQL or SOSL query. This example specifies user mode in SOQL.
1List<Account> acc = [SELECT Id FROM Account WITH USER_MODE];
2Salesforce recommends that you enforce Field Level Security (FLS) by using WITH USER_MODE rather than WITH
SECURITY-ENFORCED because of these additional advantages.
- WITH USER_MODE takes into account polymorphic fields like Owner and Task.whatId.
- WITH USER_MODE processes all clauses in the SOQL SELECT statement including the WHERE clause.
- WITH USER_MODE finds all FLS errors in your SOQL query, while WITH SECURITY ENFORCED finds only the first error. Further, in user mode, you can use the getInaccessibleFields() method on QueryException to examine the full set of access errors.
Database operations can specify user or system mode. This example inserts a new account
in user mode.
1Account acc = new Account(Name='test');
2insert as user acc;The AccessLevel class represents the two modes in
which Apex runs database operations. Use this class to define the execution mode as user
mode or system mode. An optional accessLevel parameter in Database
and Search methods specifies whether the method runs in system mode (AccessLevel.SYSTEM_MODE) or user mode (AccessLevel.USER_MODE). Use these overloaded methods to
perform DML and query operations.
- Database.query method. See Dynamic SOQL.
- Database.getQueryLocator methods
- Database.countQuery method
- Search.query method
-
Database DML methods (insert, update, upsert, merge, delete,
undelete, and convertLead)
- Includes the *Immediate and *Async methods, such as insertImmediate and deleteAsync.
These methods require the accessLevel parameter.