Within Apex
, is there a way to build up a static SOQL
query using query "parts" or "fragments"?
Consider the following silly example:
public with sharing class MyController {
@AuraEnabled(cacheable=true)
public static List<Asset> getAssets(Boolean shouldSortDescending) {
SomeType query = [SELECT Name from Asset];
// Can we append to the query based on some conditions?
if (shouldSortDescending) {
query.push([ORDER BY Name DESC]);
} else {
query.push([ORDER BY Name ASC]);
}
return query;
}
}
The best I can find is to drop down to Dynamic SOQL, build up the query using a String
and then call Database.query()
or Database.queryWithBinds()
.
One use-case for conditionally building up a static query would be to factor out some complex logic in the query into a helper function that could just return the relevant fragment.
(e.x.: This Apex class might have several methods that return Assets. In each case, we want to return the same fields. So the SELECT ... From Asset
is identical in each case and it would be nice to just return that from a single function.)