github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/builder/builder_addition_groupby.go (about)

     1  package builder
     2  
     3  import "context"
     4  
     5  type groupby struct {
     6  	AdditionType
     7  	groups []SqlExpr
     8  	having SqlCondition
     9  }
    10  
    11  func GroupBy(grps ...SqlExpr) *groupby {
    12  	return &groupby{
    13  		AdditionType: AdditionGroupBy,
    14  		groups:       grps,
    15  	}
    16  }
    17  
    18  func (g groupby) Having(c SqlCondition) *groupby {
    19  	g.having = c
    20  	return &g
    21  }
    22  
    23  func (g *groupby) IsNil() bool { return g == nil || len(g.groups) == 0 }
    24  
    25  func (g *groupby) Ex(ctx context.Context) *Ex {
    26  	e := Expr("GROUP BY ")
    27  
    28  	for i, grp := range g.groups {
    29  		if i > 0 {
    30  			e.WriteQueryByte(',')
    31  		}
    32  		e.WriteExpr(grp)
    33  	}
    34  	if !IsNilExpr(g.having) {
    35  		e.WriteQuery(" HAVING ")
    36  		e.WriteExpr(g.having)
    37  	}
    38  	return e.Ex(ctx)
    39  }