-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
90 lines (81 loc) · 2.28 KB
/
helper.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package gosql
import (
"strings"
"time"
"unicode/utf8"
)
// Sorting fields
// Example: ['createdAt:desc', 'name', 'qty:asc']
type Sorting []string
// Allowed return all sorting columns according to allowed sort map
func (s Sorting) Allowed(items map[string]string) []string {
var result = make([]string, 0, len(s))
for _, field := range s {
parts := strings.Split(strings.Trim(field, " "), ":")
if v, ok := items[parts[0]]; ok {
if len(parts) > 1 {
if strings.ToLower(parts[1]) == "desc" {
v += " DESC"
}
}
result = append(result, v)
}
}
return result
}
// Contains check if sorting contains sort field
// contained == true if sorting has sorted field
// direction == nil if no sort direction provided
// direction == true if provided sort direction is ascending
// direction == false if provided sort direction is descending
func (s Sorting) Contains(field string) (contained bool, direction *bool) {
for _, sortOrder := range s {
if parts := strings.Split(sortOrder, ":"); field == parts[0] {
contained = true
if len(parts) == 1 {
break
} else {
dir := strings.ToLower(parts[1]) != "desc"
direction = &dir
}
return
}
}
return
}
// PeriodFilter filter by datetime columns
type PeriodFilter struct {
// begins from
Start *time.Time `json:"start"`
// ended when
End *time.Time `json:"end"`
}
// IsEmpty if filter is empty
func (p *PeriodFilter) IsEmpty() bool {
return p == nil || p.Start == nil && p.End == nil
}
// FieldCondition получить условие для фильтрации
func (p *PeriodFilter) FieldCondition(field string) *Condition {
cond := NewSqlCondition(ConditionOperatorAnd)
if p.Start != nil {
cond.AddExpression(field+" >= ?", p.Start.Local())
}
if p.End != nil {
cond.AddExpression(field+" <= ?", p.End.Local())
}
return cond
}
// SearchString search by text columns
type SearchString string
// PrepareLikeValue prepare search like condition
func (s SearchString) PrepareLikeValue(column string) *Condition {
cond := NewSqlCondition(ConditionOperatorAnd)
normal := strings.ToLower(strings.Trim(string(s), " "))
if utf8.RuneCountInString(normal) > 0 {
parts := strings.Split(normal, " ")
for _, part := range parts {
cond.AddExpression(column+" like lower(?)", "%"+part+"%")
}
}
return cond
}