Sub topic 3
Database Methods and AccessLevel
Assume you know basic Apex, SOQL, DML, and permission concepts. This chapter focuses on Database methods, testing, and choosing an enforcement strategy.
Database methods and AccessLevel
Database methods provide overloads that accept an AccessLevel. Use AccessLevel.USER_MODE when a query or DML operation must enforce the running user's sharing rules, object permissions, and field-level security.
public with sharing class ContactService {
public static List<Database.SaveResult> createContacts(
List<Contact> contacts
) {
return Database.insert(
contacts,
false,
AccessLevel.USER_MODE
);
}
public static List<Account> findAccounts(String industry) {
Map<String, Object> binds = new Map<String, Object>{
'industry' => industry
};
String soql =
'SELECT Id, Name FROM Account WHERE Industry = :industry';
return Database.queryWithBinds(
soql,
binds,
AccessLevel.USER_MODE
);
}
}The false argument allows partial success. Each SaveResult reports whether one record succeeded and includes errors for failures.
flowchart LR
A[Database method] --> B{AccessLevel}
B -->|USER_MODE| C[Enforce user permissions]
B -->|SYSTEM_MODE| D[Use system permissions]
C --> E[Success or access error]Testing enforcement with System.runAs
Apex tests execute in system mode. System.runAs changes the user context, but it does not by itself enforce CRUD or FLS. Combine it with a user-mode operation to test permission behavior.
System.runAs(lowPrivilegeUser) {
try {
ContactService.createContacts(
new List<Contact>{ new Contact(LastName = 'Example') }
);
} catch (DmlException e) {
System.assert(e.getMessage().contains('access'));
}
}Older approaches
| Approach | Behavior |
|---|---|
| `WITH SECURITY_ENFORCED` | Throws when queried fields or objects are inaccessible |
| `Security.stripInaccessible` | Removes inaccessible fields and returns partial records |
| Describe checks | Lets code inspect permissions manually, but requires more code |
User mode usually gives the clearest single operation. stripInaccessible remains useful when partial data is acceptable.
Choosing an approach
Use USER_MODE for normal user-facing reads and writes. Use stripInaccessible when removing restricted fields is preferable to failing. Use describe checks only when custom branching is required.
When system mode is deliberate
System mode can suit controlled automation, such as scheduled maintenance or internal aggregation. Scope it to the smallest operation, document the reason, and avoid returning protected data directly to users. with sharing alone does not enforce CRUD or FLS.
Exercise
Does System.runAs alone prove that a user lacks field access?
Show answer
No. Run the operation with USER_MODE inside System.runAs to enforce and test object and field permissions.