-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathorderby.go
76 lines (62 loc) · 1.63 KB
/
orderby.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package querybuilder
import (
"fmt"
"github.com/goal-web/contracts"
"strings"
)
const RandomOrder contracts.OrderType = "RANDOM()"
const RandOrder contracts.OrderType = "RAND()"
type OrderBy struct {
field string
fieldOrderType contracts.OrderType
}
type OrderByFields []OrderBy
func (this OrderByFields) IsEmpty() bool {
return len(this) == 0
}
func (this OrderByFields) String() string {
if this.IsEmpty() {
return ""
}
columns := make([]string, 0)
for _, orderBy := range this {
if orderBy.field == "" {
columns = append(columns, fmt.Sprintf("%s", orderBy.fieldOrderType))
} else {
columns = append(columns, fmt.Sprintf("%s %s", orderBy.field, orderBy.fieldOrderType))
}
}
return strings.Join(columns, ",")
}
func (builder *Builder) OrderBy(field string, columnOrderType ...contracts.OrderType) contracts.QueryBuilder {
if len(columnOrderType) > 0 {
builder.orderBy = append(builder.orderBy, OrderBy{
field: field,
fieldOrderType: columnOrderType[0],
})
} else {
builder.orderBy = append(builder.orderBy, OrderBy{
field: field,
fieldOrderType: contracts.Asc,
})
}
return builder
}
func (builder *Builder) OrderByDesc(field string) contracts.QueryBuilder {
builder.orderBy = append(builder.orderBy, OrderBy{
field: field,
fieldOrderType: contracts.Desc,
})
return builder
}
func (builder *Builder) InRandomOrder(orderFunc ...contracts.OrderType) contracts.QueryBuilder {
fn := RandomOrder
if len(orderFunc) > 0 {
fn = orderFunc[0]
}
builder.orderBy = append(builder.orderBy, OrderBy{
field: "",
fieldOrderType: fn,
})
return builder
}