A Dynamic SOQL Query Builder for the Force.com Platform
Deploy the Apex classes from the ./force-app/main/default/classes/
repository into your Salesforce project.
Q query = new Q(Account.SObjectType)
.selectFields(SObjectType.Account.fieldSets.Example)
.addSubquery(new Q('Contacts'))
.add(Q.condition('Name').isLike('%Acme%'))
.add(Q.condition('BillingCountry').isNotNull())
.addLimit(5);
System.debug(query.build());
// SELECT CreatedById, Description, Owner.Email, (SELECT Id FROM Contacts) FROM Account WHERE Name LIKE '%Acme%' AND BillingCountry != null LIMIT 5
While chaining methods is a convenient way to initialise your query, you also have the ability to manually build complex queries depending on specific conditions.
Q query = new Q(Contact.SObjectType).addLimit(5);
if (String.isNotBlank(firstName)) {
query.add(Q.condition('FirstName').equalsTo(firstName))
}
if (String.isNotBlank(lastName)) {
query.add(Q.condition('LastName').equalsTo(lastName))
}
System.debug(query.build());
// SELECT Id FROM Contact WHERE FirstName = 'Céline' AND LastName = 'Dion' LIMIT 5
This library is being initially developed for one of my internal project, so API methods will likely be implemented in the order that they are needed by my project. Eventually, I would like to cover the entire SOQL and SOSL query language, so contributions are of course always welcome. Adding new methods is relatively straightforward, so feel free to join the fun!
This library is distributed under the MIT license found in the LICENSE file.