Sub topic 7
Dynamic SOQL in User Mode
Static queries in square brackets can take WITH USER_MODE. Dynamic SOQL is built as a string and run at runtime, so it needs a different mechanism. This chapter shows how to run a dynamic query in user mode and why bind variables belong in it.
This chapter assumes you know basic Apex and SOQL, that Apex runs in system mode by default, and that you have seen WITH USER_MODE on a static query.
Why dynamic queries need their own treatment
Dynamic SOQL means the query text is a String that Apex parses when the code runs. You use it when the object, fields, or filters are not known at compile time. Without extra care, a dynamic query runs in system mode, so it ignores the running user's object permissions and field-level security (FLS).
Dynamic queries also carry a second risk. If you build the string by concatenating user input, an attacker can change the meaning of the query. This is SOQL injection. Bind variables fix this, and Database.queryWithBinds combines them with user mode.
Running a dynamic query with queryWithBinds
Database.queryWithBinds takes three arguments:
- The query string, which refers to bind variables with a colon, such as
:industry. - A
Map<String, Object>that supplies the value for each bind variable name. - An
AccessLevel, eitherAccessLevel.USER_MODEorAccessLevel.SYSTEM_MODE.
public with sharing class SafeQuery {
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);
}
}The value of industry is never pasted into the query text. Apex treats it as data, so input such as ' OR Name != ' cannot add new conditions. User mode checks object access, FLS, and sharing for the running user, and that includes the fields used in the WHERE clause.
Avoid string concatenation
The next version works but is unsafe. It also runs in system mode, which is worse.
public with sharing class UnsafeQuery {
public static List<Account> findByIndustry(String industry) {
// Do not do this: injectable and ignores FLS.
String soql = 'SELECT Id, Name FROM Account WHERE Industry = \'' + industry + '\'';
return Database.query(soql);
}
}with sharing on the class applies sharing rules only. It does not enforce object permissions or FLS, so a user without access to Industry still gets results.
Other forms that accept an access level
Database.query also has an overload that takes an AccessLevel. It runs the query in user mode but has no bind map, so it can only read variables in scope with the colon syntax.
public with sharing class ScopedQuery {
public static List<Account> findByIndustry(String industry) {
String soql = 'SELECT Id, Name FROM Account WHERE Industry = :industry';
return Database.query(soql, AccessLevel.USER_MODE);
}
}This form is safe from injection as long as the query text contains no concatenated input. Prefer queryWithBinds when the binds are built in a different place from the query, because the map makes each value explicit.
Failures
When the user lacks access, the dynamic query throws a QueryException, the same as a static user mode query. A later chapter covers handling it. The point to remember here is that the exception is thrown at runtime. A dynamic query that names a field the user cannot read compiles without problems and fails only when it runs.
Common mistakes
- Using
Database.query(soql)with no access level and assumingwith sharingis enough. - Concatenating input into the query string and passing
AccessLevel.USER_MODE. User mode protects data access but does not prevent injection. - Building bind map keys that do not match the names in the query. A missing key causes a runtime error.
Exercise
A developer writes Database.query('SELECT Id FROM Contact WHERE LastName = \'' + name + '\'', AccessLevel.USER_MODE). User mode is enabled. Which problem remains, and how do you fix it?
Show answer
The query is still open to SOQL injection because name is concatenated into the string. User mode checks permissions but does not sanitize input. Replace the concatenation with a bind variable, as in Database.queryWithBinds('SELECT Id FROM Contact WHERE LastName = :name', new Map<String, Object>{ 'name' => name }, AccessLevel.USER_MODE).
Exercise
Why can you not pass a field name from user input as a bind variable?
Show answer
Bind variables supply values only, not identifiers such as object or field names. Validate the field name against an allowed list or Schema describe results, then add it to the query string.