Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions force-app/main/default/classes/Q.cls
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class Q {
private Integer numberOfRowsToSkip;

private Set<String> fieldList = new Set<String>();
private Set<String> groupBy = new Set<String>();
private List<QOrder> orders = new List<QOrder>();
private List<QCondition> conditions = new List<QCondition>();
private List<Q> subQueries = new List<Q>();
Expand Down Expand Up @@ -77,6 +78,22 @@ public class Q {
return this;
}

/**
* Add a GROUP BY statement
*/
public Q groupBy(String fieldName) {
this.groupBy.add(fieldName);
return this;
}

/**
* Add a GROUP BY statement
*/
public Q groupBy(Set<String> fieldNames) {
this.groupBy.addAll(fieldNames);
return this;
}

/**
* Add a LIMIT statement
*/
Expand Down Expand Up @@ -125,6 +142,17 @@ public class Q {
}
}

/**
* Build the GROUP BY statement
*/
public String buildGroupBy() {
if (!this.groupBy.isEmpty()) {
return 'GROUP BY ' + String.join(new List<String>(this.groupBy), ', ');
} else {
return null;
}
}

/**
* Build the ORDER BY statement
*/
Expand Down Expand Up @@ -160,6 +188,10 @@ public class Q {
queryParts.add(this.buildOrderBy());
}

if (!this.groupBy.isEmpty()) {
queryParts.add(this.buildGroupBy());
}

if (this.numberOfRows != null) {
queryParts.add('LIMIT ' + this.numberOfRows);
}
Expand Down
24 changes: 24 additions & 0 deletions force-app/main/default/classes/QTest.cls
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,28 @@ private class QTest {
Database.query(query);
}

@isTest
static void testGroupBy() {
String query =
new Q(Lead.SObjectType)
.selectFields(new Set<String>{'LeadSource', 'COUNT(Name)'})
.groupBy('LeadSource')
.build();

System.assertEquals('SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource', query);
Database.query(query);
}

@isTest
static void testGroupByMultiple() {
String query =
new Q(Lead.SObjectType)
.selectFields(new Set<String>{'Status', 'LeadSource', 'COUNT(Name)'})
.groupBy(new Set<String>{'Status', 'LeadSource'})
.build();

System.assertEquals('SELECT Status, LeadSource, COUNT(Name) FROM Lead GROUP BY Status, LeadSource', query);
Database.query(query);
}

}