Skip to content

Commit

Permalink
feat: provide support for groupby
Browse files Browse the repository at this point in the history
Signed-off-by: Muhammad Aaqil <[email protected]>
  • Loading branch information
aaqilniz committed Jan 14, 2024
1 parent 012c2de commit 807e70b
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion lib/sql.js
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,25 @@ SQLConnector.prototype.buildSelect = function(model, filter, options) {
}
}

let extraSelect = '';
if (filter.sum) {
extraSelect = `SUM(${filter.sum}) as sumOf${filter.sum}, `;
}
if (filter.count) {
extraSelect += `COUNT(${filter.count}) as countOf${filter.count}, `;
}
if (filter.avg) {
extraSelect += `AVG(${filter.avg}) as avgOf${filter.avg}, `;
}
if (filter.min) {
extraSelect += `MIN(${filter.min}) as minOf${filter.min}, `;
}
if (filter.max) {
extraSelect += `MAX(${filter.max}) as maxOf${filter.max}, `;
}

let selectStmt = new ParameterizedSQL('SELECT ' +
extraSelect +
this.buildColumnNames(model, filter) +
' FROM ' + this.tableEscaped(model));

Expand All @@ -1449,6 +1467,10 @@ SQLConnector.prototype.buildSelect = function(model, filter, options) {
selectStmt.merge(whereStmt);
}

if (filter.groupBy) {
selectStmt.merge(this.buildGroupBy(filter.groupBy));
}

if (filter.order) {
selectStmt.merge(this.buildOrderBy(model, filter.order));
}
Expand Down Expand Up @@ -1510,7 +1532,23 @@ SQLConnector.prototype.all = function find(model, filter, options, cb) {
}

const objs = data.map(function(obj) {
return self.fromRow(model, obj);
const object = self.fromRow(model, obj);
if (obj[`sumOf${filter.sum}`]) {
object[`sumOf${filter.sum}`] = obj[`sumOf${filter.sum}`];
}
if (obj[`countOf${filter.count}`]) {
object[`countOf${filter.count}`] = obj[`countOf${filter.count}`];
}
if (obj[`avgOf${filter.avg}`]) {
object[`avgOf${filter.avg}`] = obj[`avgOf${filter.avg}`];
}
if (obj[`minOf${filter.min}`]) {
object[`minOf${filter.min}`] = obj[`minOf${filter.min}`];
}
if (obj[`maxOf${filter.max}`]) {
object[`maxOf${filter.max}`] = obj[`maxOf${filter.max}`];
}
return object;
});
if (filter && filter.include) {
self.getModelDefinition(model).model.include(
Expand Down

0 comments on commit 807e70b

Please sign in to comment.