From f5311cc2e0024f186efa75243799e1158a89a08d Mon Sep 17 00:00:00 2001 From: tdakkota Date: Wed, 4 Dec 2024 06:29:34 +0300 Subject: [PATCH] feat(chsql): add `GROUP BY` --- internal/chstorage/chsql/chsql.go | 5 +++++ internal/chstorage/chsql/select.go | 24 ++++++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/internal/chstorage/chsql/chsql.go b/internal/chstorage/chsql/chsql.go index 0e936367..512930bf 100644 --- a/internal/chstorage/chsql/chsql.go +++ b/internal/chstorage/chsql/chsql.go @@ -214,6 +214,11 @@ func (p *Printer) Where() { p.Ident("WHERE") } +// Group writes `GROUP` ident. +func (p *Printer) Group() { + p.Ident("GROUP") +} + // Order writes `ORDER` ident. func (p *Printer) Order() { p.Ident("ORDER") diff --git a/internal/chstorage/chsql/select.go b/internal/chstorage/chsql/select.go index c1ff6a45..ba745b44 100644 --- a/internal/chstorage/chsql/select.go +++ b/internal/chstorage/chsql/select.go @@ -21,8 +21,9 @@ type SelectQuery struct { // prewhere is a set of expression joined by AND prewhere []Expr // where is a set of expression joined by AND - where []Expr - order []orderExpr + where []Expr + groupBy []Expr + order []orderExpr limit int } @@ -68,6 +69,12 @@ func (q *SelectQuery) Where(filters ...Expr) *SelectQuery { return q } +// GroupBy adds grouping to query. +func (q *SelectQuery) GroupBy(groups ...Expr) *SelectQuery { + q.groupBy = append(q.groupBy, groups...) + return q +} + // Order adds order to query. func (q *SelectQuery) Order(e Expr, order Order) *SelectQuery { q.order = append(q.order, orderExpr{expr: e, order: order}) @@ -175,6 +182,19 @@ func (q *SelectQuery) WriteSQL(p *Printer) error { } } } + if len(q.groupBy) > 0 { + p.Group() + p.By() + + for i, e := range q.groupBy { + if i != 0 { + p.Comma() + } + if err := p.WriteExpr(e); err != nil { + return errors.Wrapf(err, "group by %d", i) + } + } + } if len(q.order) > 0 { p.Order() p.By()