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

     1  package builder
     2  
     3  import "context"
     4  
     5  type orderby struct {
     6  	orders []*Order
     7  	AdditionType
     8  }
     9  
    10  func (o *orderby) IsNil() bool { return o == nil || len(o.orders) == 0 }
    11  
    12  func (o *orderby) Ex(ctx context.Context) *Ex {
    13  	e := Expr("ORDER BY ")
    14  	for i := range o.orders {
    15  		if i > 0 {
    16  			e.WriteQueryByte(',')
    17  		}
    18  		e.WriteExpr(o.orders[i])
    19  	}
    20  	return e.Ex(ctx)
    21  }
    22  
    23  func OrderBy(orders ...*Order) *orderby {
    24  	o := &orderby{AdditionType: AdditionOrderBy}
    25  	for i := range orders {
    26  		if !IsNilExpr(orders[i]) {
    27  			o.orders = append(o.orders, orders[i])
    28  		}
    29  	}
    30  	return o
    31  }
    32  
    33  type Order struct {
    34  	target SqlExpr
    35  	order  string
    36  }
    37  
    38  func (o *Order) IsNil() bool { return o == nil || IsNilExpr(o.target) }
    39  
    40  func (o *Order) Ex(ctx context.Context) *Ex {
    41  	e := Expr("")
    42  	e.Grow(1)
    43  	e.WriteGroup(func(e *Ex) {
    44  		e.WriteExpr(o.target)
    45  	})
    46  	if o.order != "" {
    47  		e.WriteQueryByte(' ')
    48  		e.WriteQuery(o.order)
    49  	}
    50  	return e.Ex(ctx)
    51  }
    52  
    53  func AscOrder(target SqlExpr) *Order {
    54  	return &Order{target: target, order: "ASC"}
    55  }
    56  func DescOrder(target SqlExpr) *Order {
    57  	return &Order{target: target, order: "DESC"}
    58  }