From 807e70bab5a0af644d05e62a018f64c17ecf225e Mon Sep 17 00:00:00 2001 From: Muhammad Aaqil Date: Thu, 28 Dec 2023 08:46:29 +0500 Subject: [PATCH] feat: provide support for groupby Signed-off-by: Muhammad Aaqil --- lib/sql.js | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/lib/sql.js b/lib/sql.js index 4f07a6bc..0de9191f 100644 --- a/lib/sql.js +++ b/lib/sql.js @@ -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)); @@ -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)); } @@ -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(