Sub topic 8
Database methods and AccessLevel
This chapter assumes you know static WITH USER_MODE queries and the as user keyword from the earlier chapters. It also assumes you can read Database.SaveResult objects.
Why the Database methods take an AccessLevel
WITH USER_MODE and as user are keywords that the compiler checks. They only work when the query or DML statement is written in the source. When the query is built at run time, or when you need partial-success DML, you use the Database class instead. Its methods accept an AccessLevel argument that sets the mode explicitly.
System.AccessLevel has two values:
| Value | Enforces object permissions, FLS, and sharing of the running user |
|---|---|
| `AccessLevel.USER_MODE` | Yes. Sharing is enforced even if the class is declared `without sharing`. |
| `AccessLevel.SYSTEM_MODE` | No. This is the default behavior of Apex. Sharing follows the class declaration. |
Because the mode is a value, you can pass it in as a parameter. One method can then serve both a user-facing caller and a trusted background caller.
Methods that accept an AccessLevel
The query methods are Database.query, Database.queryWithBinds, Database.countQuery, Database.countQueryWithBinds, Database.getQueryLocator, and Database.getQueryLocatorWithBinds. The DML methods are Database.insert, update, upsert, delete, and undelete. Each has an overload that takes an AccessLevel as the last argument. For DML, that argument follows either the allOrNone boolean or a DmlOptions object.
Running dynamic queries and counts
The first example runs a query built at run time, then counts records. Both calls run in user mode.
public with sharing class AccountSearch {
public static List<Account> byIndustry(String industry) {
Map<String, Object> binds = new Map<String, Object>{ 'industry' => industry };
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Industry = :industry',
binds,
AccessLevel.USER_MODE
);
}
public static Integer countAll() {
return Database.countQuery('SELECT COUNT() FROM Account', AccessLevel.USER_MODE);
}
}A user without read access to Account, or to a field named in the SELECT or WHERE clause, causes a QueryException. Prefer the WithBinds variants. They let you pass values safely without concatenating strings into the query.
For Batch Apex, Database.getQueryLocator(query, AccessLevel.USER_MODE) applies the same checks to the records the batch reads.
Partial-success DML
The as user keyword has no way to set allOrNone. The Database overloads do. With allOrNone set to false, a failing record does not roll back the others, and you inspect each result.
public with sharing class ContactLoader {
public static List<String> insertContacts(List<Contact> contacts) {
List<String> problems = new List<String>();
List<Database.SaveResult> results =
Database.insert(contacts, false, AccessLevel.USER_MODE);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
problems.add('Row ' + i + ': ' + err.getMessage());
}
}
}
return problems;
}
}Results are returned in the same order as the input list, so index i identifies the failing record. Do not rely on partial-success mode alone to catch every permission problem. A user who lacks object-level access can still cause an exception, so wrap the call in a try/catch for DmlException when the caller needs a clean message.
Passing the mode as a parameter
Because AccessLevel is a value, a service method can accept it:
public with sharing class AccountWriter {
public static void rename(List<Account> accounts, AccessLevel level) {
Database.update(accounts, true, level);
}
}Be careful with this pattern. Never let user-supplied input decide the level. Pass SYSTEM_MODE only from code paths you have reviewed, and keep USER_MODE as the default for anything reachable from a UI or API.
Common errors
- Forgetting the overload.
Database.insert(contacts, false)compiles but runs in system mode. Only the version withAccessLevelenforces permissions. - Ignoring the returned results when
allOrNoneisfalse. Errors then pass silently. - Treating
with sharingas enough. It does not check CRUD or FLS on theDatabasecall unless you passUSER_MODE.
Exercise
A trigger-free service method must insert a list of Lead records, keep going if some rows fail, and respect the running user's field-level security. Which call do you use, and where do you find the failure for the third record?
Show answer
Use Database.insert(leads, false, AccessLevel.USER_MODE). The allOrNone value of false allows partial success. The failure for the third record is in the returned list at index 2, in results[2].getErrors(), because results keep the input order.