Newer Version Available
Enforce User Mode for Database Operations (Beta)
Database methods support an AccessLevel
parameter that lets you run database operations in user mode instead of in the default
system mode.
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; in system mode they’re controlled by class sharing keywords. 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 query. This example specifies user mode.
1List<Account> acc = [SELECT Id FROM Account WITH USER_MODE];
2Database 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 new AccessLevel class represents the two modes in
which Apex runs database operations. Use this new 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 new overloaded methods
to perform DML and query operations:
- The Database.query method with the optional accessLevel parameter. See Dynamic SOQL.
- Search.query methods
- Database DML methods (insert, update, upsert, merge, delete, undelete, and convertLead)