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

     1  package builder
     2  
     3  import "context"
     4  
     5  type Function struct {
     6  	name  string
     7  	exprs []SqlExpr
     8  }
     9  
    10  func Func(name string, es ...SqlExpr) *Function {
    11  	if name == "" {
    12  		return nil
    13  	}
    14  	return &Function{name: name, exprs: es}
    15  }
    16  
    17  func (f *Function) IsNil() bool { return f == nil || f.name == "" }
    18  
    19  func (f *Function) Ex(ctx context.Context) *Ex {
    20  	e := Expr(f.name)
    21  	e.WriteGroup(func(e *Ex) {
    22  		if len(f.exprs) == 0 {
    23  			e.WriteQueryByte('*')
    24  		}
    25  		for i := range f.exprs {
    26  			if i > 0 {
    27  				e.WriteQueryByte(',')
    28  			}
    29  			e.WriteExpr(f.exprs[i])
    30  		}
    31  	})
    32  	return e.Ex(ctx)
    33  }
    34  
    35  func Count(es ...SqlExpr) *Function {
    36  	if len(es) == 0 {
    37  		return Func("COUNT", Expr("1"))
    38  	}
    39  	return Func("COUNT", es...)
    40  }
    41  
    42  func Avg(es ...SqlExpr) *Function { return Func("AVG", es...) }
    43  
    44  func Distinct(es ...SqlExpr) *Function { return Func("DISTINCT", es...) }
    45  
    46  func Min(es ...SqlExpr) *Function { return Func("MIN", es...) }
    47  
    48  func Max(es ...SqlExpr) *Function { return Func("MAX", es...) }
    49  
    50  func First(es ...SqlExpr) *Function { return Func("FIRST", es...) }
    51  
    52  func Last(es ...SqlExpr) *Function { return Func("LAST", es...) }
    53  
    54  func Sum(es ...SqlExpr) *Function { return Func("SUM", es...) }