Sub topic 8
Database methods and AccessLevel
What you need first
This chapter assumes you can read and write basic Apex classes. It also assumes you know SOQL and DML, and that you know what object permissions (CRUD) and field-level security (FLS) are. Earlier chapters covered WITH USER_MODE in static SOQL and the as user keyword. Here you will apply the same enforcement to code that is built at runtime or that needs the options only the Database class offers.
Why the Database class needs its own switch
Static SOQL and plain DML statements have keywords for user mode: WITH USER_MODE and as user. Dynamic SOQL is a string, and the Database methods are ordinary method calls. Neither can take a keyword, so Apex gives them an extra argument of type System.AccessLevel.
AccessLevel has two constants:
| Value | Meaning |
|---|---|
| `AccessLevel.USER_MODE` | Enforces the running user's object permissions, field-level security, and sharing rules. |
| `AccessLevel.SYSTEM_MODE` | Ignores object permissions and FLS. Sharing is still decided by the class declaration (`with sharing` or `without sharing`). |
Two details matter here:
- Methods called without an
AccessLevelargument behave as before.Database.query('...')andDatabase.insert(records)run in system mode with respect to CRUD and FLS. Adding the argument is what changes behavior. - User mode also enforces sharing. A
without sharingclass that callsDatabase.query(soql, AccessLevel.USER_MODE)still gets sharing applied to that one query. The access level on the call overrides the class declaration for that operation.
Dynamic queries
The Database class has an AccessLevel overload for each way of running a query:
| Method | Purpose |
|---|---|
| `Database.query(String, AccessLevel)` | Runs a dynamic query. |
| `Database.queryWithBinds(String, Map<String, Object>, AccessLevel)` | Runs a dynamic query with bind variables taken from a map. |
| `Database.countQuery(String, AccessLevel)` | Runs a `SELECT COUNT()` query. |
| `Database.countQueryWithBinds(String, Map<String, Object>, AccessLevel)` | Same, with a bind map. |
| `Database.getQueryLocator(String, AccessLevel)` | Returns a query locator for Batch Apex or pagination. |
| `Database.getQueryLocatorWithBinds(String, Map<String, Object>, AccessLevel)` | Same, with a bind map. |
Prefer the WithBinds variants
The plain Database.query method resolves bind variables such as :industry from local variables in scope. That works, but it ties the query text to the variable names around it. The WithBinds methods take an explicit map, which keeps the string and its values together and avoids building queries by concatenation.
public with sharing class AccountSearch {
public static List<Account> findByIndustry(String industry, Integer maxRows) {
Map<String, Object> binds = new Map<String, Object>{
'industry' => industry,
'maxRows' => maxRows
};
String soql =
'SELECT Id, Name, Industry ' +
'FROM Account ' +
'WHERE Industry = :industry ' +
'ORDER BY Name ' +
'LIMIT :maxRows';
return Database.queryWithBinds(soql, binds, AccessLevel.USER_MODE);
}
}The string is still assembled with +, but only from fixed text. The user-supplied values travel through the bind map, so they cannot change the query structure.
What user mode checks in a dynamic query
In user mode, Apex checks every field the query refers to, not only the ones in the SELECT list. That includes fields in WHERE, ORDER BY, and GROUP BY, and fields reached through relationships. If the user cannot read Account.Industry, the query above fails even if Industry appeared only in WHERE.
This is stricter than many developers expect. A field that is hidden from a profile can no longer be used to filter results, which closes a route for inferring hidden values.
Counting and query locators
countQuery is easy to forget because it returns a number, not records. A count can still leak information about records the user cannot see, so apply the access level:
public with sharing class AccountCounter {
public static Integer countByIndustry(String industry) {
Map<String, Object> binds = new Map<String, Object>{ 'industry' => industry };
return Database.countQueryWithBinds(
'SELECT COUNT() FROM Account WHERE Industry = :industry',
binds,
AccessLevel.USER_MODE
);
}
}For Batch Apex, the start method can return a query locator in user mode:
public with sharing class UserModeBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Name FROM Account WHERE Industry != null',
AccessLevel.USER_MODE
);
}
public void execute(Database.BatchableContext bc, List<SObject> scope) {
// Process the records in this chunk.
}
public void finish(Database.BatchableContext bc) {}
}Think about which user a batch job runs as before you choose this. A batch job runs as the user who started it. If a scheduler or an admin starts it, user mode enforces that person's permissions, not those of the users whose data is being processed.
Data changes
Each DML method on Database has overloads that accept an access level as the last argument. The common ones are:
Database.insert(records, allOrNone, accessLevel)Database.update(records, allOrNone, accessLevel)Database.upsert(records, allOrNone, accessLevel)Database.delete(records, allOrNone, accessLevel)Database.undelete(records, allOrNone, accessLevel)
Overloads that take a Database.DMLOptions object instead of the Boolean are also available for insert and update, which lets you control things like duplicate-rule behavior. Check the Apex Reference for the exact signatures in your API version, because the set of overloads has grown over several releases.
Choosing between `as user` and Database methods
Both forms enforce the same rules. The difference is in what else you get:
| Need | Use |
|---|---|
| One DML statement, all-or-nothing, shortest code | `insert as user records;` |
| Partial success, with a result per record | `Database.insert(records, false, AccessLevel.USER_MODE)` |
| Choose the access level at runtime | A `Database` method, with `AccessLevel` held in a variable |
The last row is a real advantage. Because AccessLevel is a type, you can pass it as a parameter:
public with sharing class FlexibleWriter {
public static List<Database.SaveResult> save(List<Contact> contacts, AccessLevel level) {
return Database.insert(contacts, false, level);
}
}Be careful with this pattern. A method that accepts a caller-chosen access level lets any caller request system mode. Keep such methods private or internal, and have public entry points fix the level to USER_MODE.
Partial success with allOrNone set to false
With allOrNone set to false, record-level problems such as a failed validation rule or a required field left empty are reported in the result list instead of thrown. You must read the results, because nothing stops execution:
public with sharing class ContactImporter {
public static Integer importContacts(List<Contact> contacts) {
List<Database.SaveResult> results =
Database.insert(contacts, false, AccessLevel.USER_MODE);
Integer saved = 0;
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
saved++;
} else {
for (Database.Error err : results[i].getErrors()) {
System.debug(
LoggingLevel.WARN,
'Row ' + i + ' failed: ' + err.getStatusCode() + ' ' + err.getMessage()
);
}
}
}
return saved;
}
}Do not assume that allOrNone = false turns every permission problem into a per-record error. A missing object permission or an inaccessible field is a problem with the whole operation, not with one record, and user mode raises an exception for it. The exact behavior can differ by operation and API version, so test the failure you care about with System.runAs (covered in a later chapter) instead of relying on memory.
How the decision flows
The diagram shows what happens when a Database method receives an access level.
Handling failures
A failed user mode operation throws an exception you can catch. Queries throw QueryException. DML throws DmlException. Catch these narrowly and avoid leaking raw messages to the user, which may name fields or objects they should not know about.
public with sharing class SafeAccountApi {
@AuraEnabled
public static List<Account> search(String industry) {
try {
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
);
} catch (QueryException e) {
System.debug(LoggingLevel.WARN, 'Account search denied: ' + e.getMessage());
throw new AuraHandledException('You do not have access to this data.');
}
}
}Log the real message for administrators and return a generic one to the client.
Common errors
- Forgetting the argument on one call. In a class where most queries use user mode, a single
Database.query(soql)quietly runs in system mode. Search your code forDatabase.calls that lack anAccessLevel, or add a PMD or code-scanner rule. - Assuming
with sharingis enough. The class keyword controls only sharing. Without an access level, CRUD and FLS are not checked. - Filtering on a hidden field. The query fails because the field in
WHEREis not readable. Fix the permission set or change the design. Do not switch the query to system mode to make the error disappear. - Ignoring results when
allOrNoneis false. If you never read theSaveResultlist, failed records vanish silently. - Treating count queries as harmless. They are subject to the same visibility rules.
- Passing an access level from an untrusted source. If a value from a client decides between
USER_MODEandSYSTEM_MODE, you have built a permission bypass.
Summary of the pattern
- Use a
Databasemethod when the query is dynamic, when you need partial success, or when the access level is a runtime value. - Always pass
AccessLevel.USER_MODEunless you have a documented reason for system mode. - Prefer
queryWithBindsandcountQueryWithBindsover concatenating values into the query string. - Catch
QueryExceptionandDmlException, and inspectSaveResultobjects whenallOrNoneis false. - Test each path as a user who lacks the permission.
Exercise
A class declared without sharing runs Database.query('SELECT Id FROM Account WHERE Industry = \'Banking\'', AccessLevel.USER_MODE). The running user has no read access to Account.Industry, and no sharing access to some Banking accounts. What happens, and what would change if the AccessLevel argument were removed?
Show answer
With AccessLevel.USER_MODE, the query throws a QueryException, because Industry is used in the WHERE clause and the user cannot read it. If the user could read the field, sharing would still be enforced for this query, so the user would see only the Banking accounts shared with them, even though the class is without sharing. Without the AccessLevel argument, the query would run in system mode for CRUD and FLS, so the field restriction would be ignored. Sharing would then follow the class declaration, so a without sharing class would return every Banking account.
Exercise
You call Database.insert(contacts, false, AccessLevel.USER_MODE) and the method returns without throwing. Does that prove every contact was saved? What should you do next?
Show answer
No. With allOrNone set to false, record-level failures such as validation rule errors are returned in the SaveResult list instead of being thrown. Loop through the results, check isSuccess() on each one, and read getErrors() for the failures. Also remember that missing object or field permissions are normally raised as an exception, so confirm the behavior for your case with a System.runAs test.