-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.go
222 lines (202 loc) · 5.09 KB
/
filter.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package golf
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/iancoleman/strcase"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var OperationMap = map[Filter]Filter{
Equal: Equal,
Lt: Lt,
Lte: Lte,
Gt: Gt,
Gte: Gte,
Like: Like,
NotLike: NotLike,
In: In,
NotIn: NotIn,
}
type GolfQuery interface {
// Field map key is target column, value is support operation slice
Field() map[string][]Filter
}
type Golf struct {
db *gorm.DB
isBuild bool
Error error
filters []OperationWithType
originalQuery map[string][]string
count int64
offset int64
}
func NewGolf(db *gorm.DB) *Golf {
return &Golf{
db: db,
}
}
func (g *Golf) GetGormDB() *gorm.DB {
return g.db
}
// Build Golf wile call checkQuery before generate real query
func (g *Golf) Build(model GolfQuery, query map[string][]string) *Golf {
if g.db == nil {
g.Error = errors.New("golf db is nil")
return g
}
if reflect.ValueOf(model).Kind() != reflect.Ptr {
g.Error = errors.New("model need a struct pointer")
return g
}
g.originalQuery = query
fields := model.Field()
elem := reflect.TypeOf(model).Elem()
var lowerQuery = make(map[string][]Filter)
var goStructMap = make(map[string]reflect.StructField)
for k, v := range fields {
localStruct, ok := elem.FieldByName(k)
if !ok {
g.Error = fmt.Errorf(fmt.Sprintf("invalidate model field: %s", k))
break
}
lowerColumn := strcase.ToSnake(k)
goStructMap[lowerColumn] = localStruct
// TODO Origin SQL
lowerQuery[lowerColumn] = v
}
queryMap, err := g.checkAndBuildQuery(lowerQuery)
if err != nil {
g.Error = err
return g
}
g.filters, g.Error = g.parseOperation(queryMap, goStructMap)
return g.buildGormQuery()
}
func (g *Golf) buildGormQuery() *Golf {
if err := g.buildPagination().Error; err != nil {
return g
}
for _, operation := range g.filters {
switch operation.Filter {
case In, NotIn:
g.db = g.db.Where(fmt.Sprintf("%s %s (?)", operation.Column, getSQLOperation(operation.Filter)), operation.Value)
default:
g.db = g.db.Where(fmt.Sprintf("%s %s ?", operation.Column, getSQLOperation(operation.Filter)), operation.Value)
}
}
g.isBuild = true
return g
}
func (g *Golf) Find(dest interface{}, conds ...interface{}) *Golf {
if g.Error != nil {
return g
}
if !g.isBuild {
g.Error = errors.New("before call find, you should call build first")
}
if g.offset != 0 || g.count != 0 {
g.Error = g.db.Limit(int(g.count)).Offset(int(g.offset)).Find(dest, conds...).Error
return g
}
g.Error = g.db.Find(dest, conds...).Error
return g
}
func (g *Golf) First(dest interface{}, conds ...interface{}) *Golf {
if g.Error != nil {
return g
}
if !g.isBuild {
g.Error = errors.New("before call first, you should call build first")
}
g.Error = g.db.First(dest, conds...).Error
return g
}
func (g *Golf) parseOperation(queryMap []ValueOperation, structMap map[string]reflect.StructField) ([]OperationWithType, error) {
var ret []OperationWithType
for _, v := range queryMap {
goStruct := structMap[v.Column]
switch goStruct.Type.String() {
case "int", "int64", "int32", "uint", "uint64":
i, err := strconv.ParseInt(v.Value.(string), 10, 64)
if err != nil {
return nil, err
}
v.Value = i
case "string":
v.Value = v.Value.(string)
}
oper := OperationWithType{
ValueOperation: v,
}
ret = append(ret, oper)
}
return ret, nil
}
// checkAndBuildQuery check url query and build column value map
// urlQuery eg: eq_id=1
func (g *Golf) checkAndBuildQuery(lowerQuery map[string][]Filter) ([]ValueOperation, error) {
var ret []ValueOperation
for k, v := range g.originalQuery {
if len(strings.Split(k, querySep)) < 1 {
return nil, fmt.Errorf("format query param failed,query param should like `eq_id=1`")
}
splitQuery := strings.Split(k, querySep)
if len(splitQuery) <= 1 {
continue
}
filter, ok := OperationMap[Filter(splitQuery[0])]
if !ok {
return nil, fmt.Errorf(fmt.Sprintf("un support oper: %s", splitQuery[1]))
}
// extract real query column support for gte_user_id=1
queryColumn := strings.Replace(k, fmt.Sprintf("%s%s", splitQuery[0], querySep), "", 1)
supportFilter, ok := lowerQuery[queryColumn]
if !ok {
return nil, fmt.Errorf(fmt.Sprintf("Undefined field %s", queryColumn))
}
var support bool
for _, q := range supportFilter {
if q == filter {
support = true
}
}
if !support {
return nil, fmt.Errorf(fmt.Sprintf("field:%s un support operation: %s", splitQuery[1], splitQuery[0]))
}
for _, vv := range v {
singleQ := ValueOperation{
Value: vv,
Column: queryColumn,
Filter: filter,
}
ret = append(ret, singleQ)
}
}
return ret, nil
}
func (g *Golf) buildPagination() *Golf {
for k, v := range g.originalQuery {
if len(v) > 0 {
switch k {
case "offset":
offset, err := strconv.ParseInt(v[0], 10, 64)
if err != nil {
g.Error = err
}
g.offset = offset
case "count":
offset, err := strconv.ParseInt(v[0], 10, 64)
if err != nil {
g.Error = err
}
g.count = offset
default:
g.count = 10
g.offset = 0
}
}
}
return g
}