Sub topic 2
Querying with `WITH USER_MODE`
Assume you know basic Apex classes, SOQL, DML, and Salesforce CRUD and field-level security (FLS). Apex runs in system mode by default. It can therefore read or change records even when the running user lacks access. The with sharing declaration enforces record-sharing rules, but it does not enforce object permissions or FLS.
Querying with `WITH USER_MODE`
Add WITH USER_MODE to a static SOQL query when the result must follow the current user's access. It enforces object permissions, FLS, and sharing. It also checks fields used in clauses such as WHERE.
public with sharing class AccountService {
public static List<Account> getAccounts() {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Industry != null
WITH USER_MODE
LIMIT 50
];
}
}A user without access to Account, Name, or Industry cannot successfully run this query.
Writing data with `as user`
Use as user for DML that must respect the current user's permissions.
public with sharing class ContactService {
public static void createContact(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
insert as user c;
}
}The operation can fail when the user lacks create access to Contact or edit access to one of the populated fields.
Handling permission failures
User-mode queries generally throw QueryException when access is missing. Catch it at a boundary where you can provide a useful response.
try {
List<Account> accounts = AccountService.getAccounts();
} catch (QueryException e) {
throw new AuraHandledException('You do not have access to this data.');
}For DML, inspect Database.SaveResult values when using partial success. Each failed record has an error message. Do not assume that a successful query means later DML will also succeed.
Dynamic SOQL in user mode
Use bind variables instead of concatenating input into a query. Database.queryWithBinds accepts an access level.
public static List<Account> findByIndustry(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
);
}Exercise
Which access checks does WITH USER_MODE add to a SOQL query?
Show answer
It enforces object permissions, field-level security, and sharing for the running user.