github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/addition_group_by.go (about)

     1  package sqlbuilder
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  type GroupByAddition interface {
     8  	Addition
     9  	Having(cond SqlExpr) GroupByAddition
    10  }
    11  
    12  func GroupBy(groups ...SqlExpr) GroupByAddition {
    13  	return &groupBy{
    14  		groups: groups,
    15  	}
    16  }
    17  
    18  type groupBy struct {
    19  	groups []SqlExpr
    20  	// HAVING
    21  	havingCond SqlExpr
    22  }
    23  
    24  func (groupBy) AdditionType() AdditionType {
    25  	return AdditionGroupBy
    26  }
    27  
    28  func (g groupBy) Having(cond SqlExpr) GroupByAddition {
    29  	g.havingCond = cond
    30  	return &g
    31  }
    32  
    33  func (g *groupBy) IsNil() bool {
    34  	return g == nil || len(g.groups) == 0
    35  }
    36  
    37  func (g *groupBy) Ex(ctx context.Context) *Ex {
    38  	expr := Expr("GROUP BY ")
    39  
    40  	for i, group := range g.groups {
    41  		if i > 0 {
    42  			expr.WriteQueryByte(',')
    43  		}
    44  		expr.WriteExpr(group)
    45  	}
    46  
    47  	if !(IsNilExpr(g.havingCond)) {
    48  		expr.WriteQuery(" HAVING ")
    49  		expr.WriteExpr(g.havingCond)
    50  	}
    51  
    52  	return expr.Ex(ctx)
    53  }