github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/sqlbuilder/addition_order_by.go (about) 1 package sqlbuilder 2 3 import ( 4 "context" 5 ) 6 7 func OrderBy(orders ...*Order) Addition { 8 finalOrders := make([]*Order, 0) 9 10 for i := range orders { 11 if IsNilExpr(orders[i]) { 12 continue 13 } 14 finalOrders = append(finalOrders, orders[i]) 15 } 16 17 return &orderBy{ 18 orders: finalOrders, 19 } 20 } 21 22 type orderBy struct { 23 orders []*Order 24 } 25 26 func (orderBy) AdditionType() AdditionType { 27 return AdditionOrderBy 28 } 29 30 func (o *orderBy) IsNil() bool { 31 return o == nil || len(o.orders) == 0 32 } 33 34 func (o *orderBy) Ex(ctx context.Context) *Ex { 35 e := Expr("ORDER BY ") 36 for i := range o.orders { 37 if i > 0 { 38 e.WriteQueryByte(',') 39 } 40 e.WriteExpr(o.orders[i]) 41 } 42 return e.Ex(ctx) 43 } 44 45 func AscOrder(target SqlExpr) *Order { 46 return &Order{target: target, typ: "ASC"} 47 } 48 49 func DescOrder(target SqlExpr) *Order { 50 return &Order{target: target, typ: "DESC"} 51 } 52 53 var _ SqlExpr = (*Order)(nil) 54 55 type Order struct { 56 target SqlExpr 57 typ string 58 } 59 60 func (o *Order) IsNil() bool { 61 return o == nil || IsNilExpr(o.target) 62 } 63 64 func (o *Order) Ex(ctx context.Context) *Ex { 65 e := Expr("") 66 e.Grow(1) 67 68 e.WriteGroup(func(e *Ex) { 69 e.WriteExpr(o.target) 70 }) 71 72 if o.typ != "" { 73 e.WriteQueryByte(' ') 74 e.WriteQuery(o.typ) 75 } 76 77 return e.Ex(ctx) 78 }