From 5526e6046474cc92ad405b58d490d1caf9aaa8f4 Mon Sep 17 00:00:00 2001 From: SpiritOfWill Date: Tue, 15 May 2018 15:07:35 +0300 Subject: [PATCH] Add aggregation function to select query builder (#39) qb: added min, max, avg, sum, and count to SelectBuilder --- qb/select.go | 41 +++++++++++++++++++++++++++++++++++++++++ qb/select_test.go | 16 ++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/qb/select.go b/qb/select.go index 5cc0ce5..0287dec 100644 --- a/qb/select.go +++ b/qb/select.go @@ -163,3 +163,44 @@ func (b *SelectBuilder) AllowFiltering() *SelectBuilder { b.allowFiltering = true return b } + +// Count produces 'count(column)'. +func (b *SelectBuilder) Count(column string) *SelectBuilder { + b.fn("count", column) + return b +} + +// CountAll produces 'count(*)'. +func (b *SelectBuilder) CountAll() *SelectBuilder { + b.Count("*") + return b +} + +// Min produces 'min(column)' aggregation function. +func (b *SelectBuilder) Min(column string) *SelectBuilder { + b.fn("min", column) + return b +} + +// Max produces 'max(column)' aggregation function. +func (b *SelectBuilder) Max(column string) *SelectBuilder { + b.fn("max", column) + return b +} + +// Avg produces 'avg(column)' aggregation function. +func (b *SelectBuilder) Avg(column string) *SelectBuilder { + b.fn("avg", column) + return b +} + +// Sum produces 'sum(column)' aggregation function. +func (b *SelectBuilder) Sum(column string) *SelectBuilder { + b.fn("sum", column) + return b +} + +func (b *SelectBuilder) fn(name, column string) *SelectBuilder { + b.Columns(name + "(" + column + ")") + return b +} diff --git a/qb/select_test.go b/qb/select_test.go index 9d42c06..3423873 100644 --- a/qb/select_test.go +++ b/qb/select_test.go @@ -78,6 +78,22 @@ func TestSelectBuilder(t *testing.T) { S: "SELECT * FROM cycling.cyclist_name WHERE id=? ALLOW FILTERING ", N: []string{"expr"}, }, + // Add COUNT all + { + B: Select("cycling.cyclist_name").CountAll().Where(Gt("stars")), + S: "SELECT count(*) FROM cycling.cyclist_name WHERE stars>? ", + N: []string{"stars"}, + }, + // Add COUNT with GROUP BY + { + B: Select("cycling.cyclist_name").Count("stars").GroupBy("id"), + S: "SELECT id,count(stars) FROM cycling.cyclist_name GROUP BY id ", + }, + // Add Min + { + B: Select("cycling.cyclist_name").Min("stars"), + S: "SELECT min(stars) FROM cycling.cyclist_name ", + }, } for _, test := range table {