github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/databases/orm/clauses/order.go (about) 1 // The original package is migrated from beego and modified, you can find orignal from following link: 2 // "github.com/beego/beego/" 3 // 4 // Copyright 2023 IAC. All Rights Reserved. 5 // 6 // Licensed under the Apache License, Version 2.0 (the "License"); 7 // you may not use this file except in compliance with the License. 8 // You may obtain a copy of the License at 9 // 10 // http://www.apache.org/licenses/LICENSE-2.0 11 // 12 // Unless required by applicable law or agreed to in writing, software 13 // distributed under the License is distributed on an "AS IS" BASIS, 14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 // See the License for the specific language governing permissions and 16 // limitations under the License. 17 18 package clauses 19 20 import ( 21 "strings" 22 ) 23 24 type Sort int8 25 26 const ( 27 None Sort = 0 28 Ascending Sort = 1 29 Descending Sort = 2 30 ) 31 32 type Option func(order *Order) 33 34 type Order struct { 35 column string 36 sort Sort 37 isRaw bool 38 } 39 40 func Clause(options ...Option) *Order { 41 o := &Order{} 42 for _, option := range options { 43 option(o) 44 } 45 46 return o 47 } 48 49 func (o *Order) GetColumn() string { 50 return o.column 51 } 52 53 func (o *Order) GetSort() Sort { 54 return o.sort 55 } 56 57 func (o *Order) SortString() string { 58 switch o.GetSort() { 59 case Ascending: 60 return "ASC" 61 case Descending: 62 return "DESC" 63 } 64 65 return `` 66 } 67 68 func (o *Order) IsRaw() bool { 69 return o.isRaw 70 } 71 72 func ParseOrder(expressions ...string) []*Order { 73 var orders []*Order 74 for _, expression := range expressions { 75 sort := Ascending 76 column := strings.ReplaceAll(expression, ExprSep, ExprDot) 77 if column[0] == '-' { 78 sort = Descending 79 column = column[1:] 80 } 81 82 orders = append(orders, &Order{ 83 column: column, 84 sort: sort, 85 }) 86 } 87 88 return orders 89 } 90 91 func Column(column string) Option { 92 return func(order *Order) { 93 order.column = strings.ReplaceAll(column, ExprSep, ExprDot) 94 } 95 } 96 97 func sort(sort Sort) Option { 98 return func(order *Order) { 99 order.sort = sort 100 } 101 } 102 103 func SortAscending() Option { 104 return sort(Ascending) 105 } 106 107 func SortDescending() Option { 108 return sort(Descending) 109 } 110 111 func SortNone() Option { 112 return sort(None) 113 } 114 115 func Raw() Option { 116 return func(order *Order) { 117 order.isRaw = true 118 } 119 }