Database Operation Access Level

Apex code, by default, operates in system mode, granting it significantly higher permissions compared to the user executing it.

Apex code, by default, operates in system mode, granting it significantly higher permissions compared to the user executing it.

To enhance the security context of Apex, you can specify user-mode access for database operations.

It is important to use proper context depending on the requirements to ensure the data is secure.

Let’s check an example

Remember, using USER_MODE enforces sharing access even in without sharing Apex class context!

Do this
// Respecting security of the running user
List<Account> acc = [SELECT Id, Name FROM Account WITH USER_MODE];

// Running in the system mode
List<Account> acc = [SELECT Id, Name FROM Account WITH SYSTEM_MODE];

It is recommended to use WITH USER_MODE instead of WITH SECURITY_ENFORCED because it has few advantages like accounting for polymorphic fields like Task.WhatId or finding all the errors of the query.

Don't do this
List<Account> acc = [SELECT Id, Name FROM Account WITH SECURITY_ENFORCED];
Do this
Account acc = new Account(Name = 'Acme Inc.');

// Respecting security of the running user
insert as user acc;

// Running in the system mode
update as system acc;

User and System modes are available also from other overloaded Apex methods, and can be used via AccessLevel modes (USER_MODE, SYSTEM_MODE).

apex
// Some query methods with AccessLevel support
Database.query(String queryString, System.AccessLevel accessLevel);
Database.queryWithBinds(String queryString, Map<String, Object> bindMap, System.AccessLevel accessLevel);
Database.getQueryLocator(sObject [] listofQueries, System.AccessLevel accessLevel);
Database.countQuery(String query, System.AccessLevel accessLevel);

Search.query(String query, System.AccessLevel accessLevel);

// Some DML methods with AccessLevel support
Database.insert(List<SObject> records, Boolean allOrNone, System.AccessLevel accessLevel);
Database.update(List<SObject> records, Boolean allOrNone, System.AccessLevel accessLevel);
Database.delete(List<SObject> records, Boolean allOrNone, System.AccessLevel accessLevel);

Best practice dictates that the mode be explicitly set for each database operation, regardless of whether the default system mode is selected. This approach provides a clear understanding of the context in which your code operates, enhancing transparency.

Don't do this
Account acc = new Account(Name = 'Acme Inc.');

// Should insert record in system mode
insert acc;
Do this
Account acc = new Account(Name = 'Acme Inc.');

// Should insert record in system mode
insert as system acc;

Text and code were extracted from the original slide. Plain-text version of the whole catalog