Sub topic 3
Validating Dynamic Field and Object Names with Schema Describe
Assume you know Apex classes, static SOQL, strings, collections, and basic sharing and field-level security. This chapter focuses on names that cannot be bind variables, such as object names, field names, and sort directions.
Validate identifiers with Schema describe
Bind variables protect values, but they cannot replace an identifier. For example, FROM :objectName and ORDER BY :fieldName are invalid SOQL. Validate each identifier before adding it to the query string.
Schema.getGlobalDescribe() returns the objects available in the org. Each object’s describe result provides its canonical name and field map.
public with sharing class AccountSearch {
public static List<SObject> selectField(String objectName, String fieldName) {
Map<String, Schema.SObjectType> objects = Schema.getGlobalDescribe();
Schema.SObjectType objectType = objects.get(objectName);
if (objectType == null) {
throw new IllegalArgumentException('Unknown object');
}
Schema.DescribeSObjectResult objectDescribe = objectType.getDescribe();
if (!objectDescribe.isAccessible()) {
throw new IllegalArgumentException('Inaccessible object');
}
Schema.SObjectField field = objectDescribe.fields.getMap().get(fieldName);
if (field == null || !field.getDescribe().isAccessible()) {
throw new IllegalArgumentException('Unknown or inaccessible field');
}
String objectApiName = objectDescribe.getName();
String fieldApiName = field.getDescribe().getName();
String soql = 'SELECT Id, ' + fieldApiName +
' FROM ' + objectApiName + ' LIMIT 50';
return Database.queryWithBinds(
soql,
new Map<String, Object>(),
AccessLevel.USER_MODE
);
}
}A fixed allowlist is simpler when the supported fields are known. Use Schema describe when configuration must support several objects or fields. Always validate sort direction separately, accepting only ASC or DESC.
String.escapeSingleQuotes: a last resort
String.escapeSingleQuotes escapes quotes inside a string literal. It does not validate field names, object names, numbers, keywords, or sort directions. It also does not remove % or _ from a LIKE pattern.
Prefer bind variables for values. Use escaping only when a string value genuinely cannot be bound, and escape it immediately before placing it inside a quoted literal.
Test injection payloads
Tests should submit query syntax as data and verify that validation rejects it.
@IsTest
private class AccountSearchTest {
@IsTest
static void rejectsInjectedFieldName() {
String payload = 'Name FROM Account WHERE Name != \'';
try {
AccountSearch.selectField('Account', payload);
Assert.fail('The injected field name should be rejected');
} catch (IllegalArgumentException error) {
Assert.areEqual('Unknown or inaccessible field', error.getMessage());
}
}
}Exercise
Why can Schema describe validate a field name but cannot replace a bind variable for a search value?
Show answer
A field name changes query structure, so it must be validated before string construction. A search value is data and should be passed with a bind variable.