Skip to content

Commit

Permalink
feat(chsql): add GROUP BY
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Dec 4, 2024
1 parent db0db99 commit f5311cc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
5 changes: 5 additions & 0 deletions internal/chstorage/chsql/chsql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
24 changes: 22 additions & 2 deletions internal/chstorage/chsql/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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})
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit f5311cc

Please sign in to comment.