Sub topic 7
Safe LIKE Searches and User-Supplied Wildcards
This chapter assumes you can write static SOQL with WHERE and LIMIT. It also assumes you know what a bind variable is and have seen Database.queryWithBinds. Here you will handle one case that bind variables do not fully cover: LIKE searches.
What a bind variable does not protect
A bind variable keeps user input out of the query text. A quote typed by the user can no longer close a string literal. That stops SOQL injection.
LIKE adds a second layer. The bound value is treated as a pattern, so two characters in it have special meaning.
| Character | Meaning in a LIKE pattern |
|---|---|
| `%` | Matches zero or more characters |
| `_` | Matches exactly one character |
| `\` | Escape character, so `\%` matches a literal percent sign |
If a user types %, the pattern becomes %% and matches every row. If the user types A_me, the query also matches Acme. Nothing here changes the structure of the query, so this is not injection. It is still a problem, for three reasons:
- Results are broader than the user asked for.
- Patterns such as
%a%b%c%force slow scans on large objects. - A search box meant for exact fragments becomes a tool to list every record the user can see.
The pattern to follow
Build the pattern in Apex, then pass it as a bind value. Decide which wildcards you add yourself, and neutralize the ones the user typed.
Escape the backslash first. If you escape % first, the backslash you add would be doubled by the next step.
public with sharing class AccountSearch {
public static String escapeLike(String input) {
if (input == null) {
return '';
}
return input
.replace('\\', '\\\\')
.replace('%', '\\%')
.replace('_', '\\_');
}
public static List<Account> searchByName(String input) {
String term = '%' + escapeLike(input) + '%';
Map<String, Object> binds = new Map<String, Object>{ 'term' => term };
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name LIKE :term LIMIT 50',
binds,
AccessLevel.USER_MODE
);
}
}In Apex source, '\\' is a single backslash character. So replace('\\', '\\\\') turns one backslash into two.
The same helper works with static SOQL, where the bind variable is written directly in the query.
String term = '%' + AccountSearch.escapeLike(input) + '%';
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Name LIKE :term LIMIT 50];Choosing where your own wildcards go
You control the position of the % characters you add. The position affects performance.
term + '%'matches names that start with the text. Salesforce can often use an index for this.'%' + term + '%'matches names that contain the text. It is more convenient but cannot use an index efficiently.
Pick the narrowest form that fits the feature. Also reject very short input, for example fewer than two characters, so a single letter does not scan the whole object. Always keep a LIMIT.
Test the behavior
A test should prove that typed wildcards are treated as plain text. The data below includes a name with an underscore, which an unescaped _ would also match against Acme.
@IsTest
private class AccountSearchTest {
@IsTest
static void typedWildcardsAreLiteral() {
insert new List<Account>{
new Account(Name = 'Acme'),
new Account(Name = 'A_me')
};
List<Account> underscore = AccountSearch.searchByName('A_me');
Assert.areEqual(1, underscore.size(), '_ must not match any single character');
Assert.areEqual('A_me', underscore[0].Name);
List<Account> percent = AccountSearch.searchByName('%');
Assert.areEqual(0, percent.size(), '% must not match every row');
}
}Without escapeLike, the first search returns two rows and the second returns both accounts, so the test fails. That makes it a useful regression guard.
Common mistakes
- Escaping
%before\, which doubles the backslashes you just added. - Concatenating the raw input into the query string "because the value is only a pattern". The bind variable is still required.
- Forgetting
LIMITon a search that can match many rows. - Escaping the input and then also adding user-controlled
%back in through a second field.
Exercise
A user types the search text 50%_off. After you call escapeLike and wrap the result with % at both ends, what pattern is bound to the query, and why does the order of the replace calls matter?
Show answer
The bound pattern is %50\%\_off%. The user's % and _ become \% and \_, so they match literal characters, and your own outer % characters still act as wildcards. The backslash must be replaced first. If % and _ were escaped first, the backslashes just added would then be doubled to \\, which breaks the escaping.