support raw order
This commit is contained in:
parent
56fa213a6e
commit
7d4e88c1b9
@ -432,21 +432,24 @@ func (t *dbTables) getOrderSQL(orders []*clauses.Order) (orderSQL string) {
|
||||
orderSqls := make([]string, 0, len(orders))
|
||||
for _, order := range orders {
|
||||
column := order.GetColumn()
|
||||
var sort string
|
||||
switch order.GetSort() {
|
||||
case clauses.SortAscending:
|
||||
sort = "ASC"
|
||||
case clauses.SortDescending:
|
||||
sort = "DESC"
|
||||
}
|
||||
clause := strings.Split(column, ExprSep)
|
||||
clause := strings.Split(column, clauses.ExprDot)
|
||||
|
||||
index, _, fi, suc := t.parseExprs(t.mi, clause)
|
||||
if !suc {
|
||||
panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(clause, ExprSep)))
|
||||
}
|
||||
if order.IsRaw() {
|
||||
if len(clause) == 2 {
|
||||
orderSqls = append(orderSqls, fmt.Sprintf("%s.%s%s%s %s", clause[0], Q, clause[1], Q, order.SortString()))
|
||||
} else if len(clause) == 1 {
|
||||
orderSqls = append(orderSqls, fmt.Sprintf("%s%s%s %s", Q, clause[0], Q, order.SortString()))
|
||||
} else {
|
||||
panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(clause, ExprSep)))
|
||||
}
|
||||
} else {
|
||||
index, _, fi, suc := t.parseExprs(t.mi, clause)
|
||||
if !suc {
|
||||
panic(fmt.Errorf("unknown field/column name `%s`", strings.Join(clause, ExprSep)))
|
||||
}
|
||||
|
||||
orderSqls = append(orderSqls, fmt.Sprintf("%s.%s%s%s %s", index, Q, fi.column, Q, sort))
|
||||
orderSqls = append(orderSqls, fmt.Sprintf("%s.%s%s%s %s", index, Q, fi.column, Q, order.SortString()))
|
||||
}
|
||||
}
|
||||
|
||||
orderSQL = fmt.Sprintf("ORDER BY %s ", strings.Join(orderSqls, ", "))
|
||||
|
||||
@ -2,4 +2,5 @@ package clauses
|
||||
|
||||
const (
|
||||
ExprSep = "__"
|
||||
ExprDot = "."
|
||||
)
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
package clauses
|
||||
|
||||
import "strings"
|
||||
|
||||
type Sort int8
|
||||
|
||||
const (
|
||||
@ -33,6 +35,18 @@ func (o *Order) GetSort() Sort {
|
||||
return o.sort
|
||||
}
|
||||
|
||||
func (o *Order) SortString() string {
|
||||
switch o.GetSort() {
|
||||
case SortAscending:
|
||||
return "ASC"
|
||||
case SortDescending:
|
||||
return "DESC"
|
||||
}
|
||||
|
||||
return ``
|
||||
}
|
||||
|
||||
|
||||
func (o *Order) IsRaw() bool {
|
||||
return o.isRaw
|
||||
}
|
||||
@ -41,10 +55,10 @@ func ParseOrder(expressions ...string) []*Order {
|
||||
var orders []*Order
|
||||
for _, expression := range expressions {
|
||||
sort := SortAscending
|
||||
column := expression
|
||||
if expression[0] == '-' {
|
||||
column := strings.ReplaceAll(expression, ExprSep, ExprDot)
|
||||
if column[0] == '-' {
|
||||
sort = SortDescending
|
||||
column = expression[1:]
|
||||
column = column[1:]
|
||||
}
|
||||
|
||||
orders = append(orders, &Order{
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user