forked from glennliao/apijson-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.go
More file actions
executable file
·377 lines (287 loc) · 7.92 KB
/
query.go
File metadata and controls
executable file
·377 lines (287 loc) · 7.92 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package executor
import (
"context"
"regexp"
"strings"
"github.com/glennliao/apijson-go/config"
"github.com/glennliao/apijson-go/consts"
"github.com/glennliao/apijson-go/model"
"github.com/glennliao/apijson-go/query"
"github.com/glennliao/apijson-go/util"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
"github.com/samber/lo"
)
type DbResolver func(ctx context.Context) gdb.DB
type SqlExecutor struct {
ctx context.Context
Role string
// 保存where条件 [ ["user_id",">", 123], ["user_id","<=",345] ]
Where [][]any
accessCondition map[string][]any
Columns []string
Order string
Group string
// 是否最终为空结果, 用于node中中断数据获取
WithEmptyResult bool
config *config.ExecutorConfig
DbResolver DbResolver
}
func New(ctx context.Context, config *config.ExecutorConfig) (query.QueryExecutor, error) {
return &SqlExecutor{
ctx: ctx,
Where: [][]any{},
Columns: nil,
Order: "",
Group: "",
WithEmptyResult: false,
config: config,
DbResolver: func(ctx context.Context) gdb.DB {
return g.DB()
},
}, nil
}
// ParseCondition 解析查询条件
// accessVerify 内部调用时, 不校验是否可使用该种查询方式
func (e *SqlExecutor) ParseCondition(conditions model.MapStrAny, accessVerify bool) error {
for key, condition := range conditions {
switch {
case strings.HasSuffix(key, consts.OpIn):
e.parseMultiCondition(util.RemoveSuffix(key, consts.OpIn), condition)
case strings.HasSuffix(key, consts.OpLike):
e.Where = append(e.Where, []any{key[0 : len(key)-1], consts.SqlLike, gconv.String(condition)})
case strings.HasSuffix(key, consts.OpRegexp):
e.Where = append(e.Where, []any{key[0 : len(key)-1], consts.SqlRegexp, gconv.String(condition)})
case key == consts.Raw && !accessVerify:
e.accessCondition = condition.(map[string][]any)
default:
e.Where = append(e.Where, []any{key, consts.SqlEqual, condition})
}
}
if !accessVerify {
return nil
}
if e.config.NoVerify { // 可任意字段搜索
return nil
}
inFieldsMap := e.config.GetFieldsGetInByRole()
dbStyle := e.config.DbFieldStyle
tableName := e.config.TableName()
for _, where := range e.Where {
k := dbStyle(e.ctx, tableName, where[0].(string))
if val, exists := inFieldsMap[k]; exists {
if len(val) == 0 {
continue
}
if val[0] == "*" {
continue
}
op := where[1].(string)
if op == consts.SqlLike {
condition := where[2].(string)
op = consts.OpLike
if strings.HasPrefix(condition, "%") {
op = "%" + op
}
if strings.HasSuffix(condition, "%") {
op = op + "%"
}
}
if !lo.Contains(val, op) {
return consts.NewValidReqErr("不允许使用" + where[0].(string) + "的搜索方式:" + op)
}
} else {
return consts.NewValidReqErr("不允许使用" + where[0].(string) + "搜索")
}
}
return nil
}
// ParseCondition 解析批量查询条件
func (e *SqlExecutor) parseMultiCondition(k string, condition any) {
var conditions [][]string
var value = condition
if _str, ok := condition.(string); ok {
for _, s := range strings.Split(_str, ",") {
var item []string
ops := []string{"<=", "<", ">=", ">"}
isEq := true
for _, op := range ops {
if strings.HasPrefix(s, op) {
item = append(item, op, s[len(op):])
isEq = false
break
}
}
if isEq {
item = append(item, " = ", s)
}
conditions = append(conditions, item)
}
value = conditions
}
getK := func(k string) string {
return k[0 : len(k)-1]
}
switch k[len(k)-1] {
case '&', '|', '!':
e.Where = append(e.Where, []any{getK(k), k[len(k)-1], value})
default:
e.Where = append(e.Where, []any{k, "in", value})
}
}
var exp = regexp.MustCompile(`^[\s\w][\w()]+`) // 匹配 field, COUNT(field)
// ParseCtrl 解析 @column,@group等控制类
func (e *SqlExecutor) ParseCtrl(ctrl model.Map) error {
fieldStyle := e.config.DbFieldStyle
tableName := e.config.TableName()
for k, v := range ctrl {
// 使用;分割字段
fieldStr := strings.ReplaceAll(gconv.String(v), ";", ",")
fieldList := strings.Split(fieldStr, ",")
for i, item := range fieldList {
fieldList[i] = exp.ReplaceAllStringFunc(item, func(field string) string {
return fieldStyle(e.ctx, tableName, field)
}) // 将请求字段转化为数据库字段风格
}
switch k {
case "@column":
e.Columns = fieldList
case "@order":
fieldStr = strings.Join(fieldList, ",")
order := strings.ReplaceAll(fieldStr, "-", " DESC")
order = strings.ReplaceAll(order, "+", " ")
e.Order = order
case "@group":
fieldStr = strings.Join(fieldList, ",")
e.Group = fieldStr
}
}
return nil
}
func (e *SqlExecutor) build() *gdb.Model {
tableName := e.config.TableName()
m := e.DbResolver(e.ctx).Model(tableName).Ctx(e.ctx)
if e.Order != "" {
m = m.Order(e.Order)
}
whereBuild := m.Builder()
fieldStyle := e.config.DbFieldStyle
for _, whereItem := range e.Where {
key := fieldStyle(e.ctx, tableName, whereItem[0].(string))
op := whereItem[1]
value := whereItem[2]
if conditions, ok := value.([][]string); ok { // multiCondition
switch op {
case '&':
b := m.Builder()
for _, c := range conditions {
b = b.Where(key+" "+c[0], c[1])
}
whereBuild = whereBuild.Where(b)
case '|':
b := m.Builder()
for _, c := range conditions {
b = b.WhereOr(key+" "+c[0], c[1])
}
whereBuild = whereBuild.Where(b)
case '!':
whereBuild = whereBuild.WhereNotIn(key, conditions)
default:
whereBuild = whereBuild.WhereIn(key, conditions)
}
} else {
switch op {
case consts.SqlLike:
whereBuild = whereBuild.WhereLike(key, value.(string))
case consts.SqlRegexp:
whereBuild = whereBuild.Where(key+" "+consts.SqlRegexp, value.(string))
case "in":
whereBuild = whereBuild.WhereIn(key, value)
case consts.SqlEqual:
whereBuild = whereBuild.Where(key, value)
}
}
}
m = m.Where(whereBuild)
if e.accessCondition != nil {
for k, v := range e.accessCondition {
m = m.Where(k, v...)
}
}
if e.Group != "" {
m = m.Group(e.Group)
}
return m
}
func (e *SqlExecutor) column() []string {
outFields := e.config.GetFieldsGetOutByRole()
tableName := e.config.TableName()
var columns []string
if e.Columns != nil {
columns = e.Columns
} else {
columns = e.config.TableColumns()
}
var fields = make([]string, 0, len(columns))
fieldStyle := e.config.JsonFieldStyle
dbStyle := e.config.DbFieldStyle
for _, column := range columns {
fieldName := column
column = strings.ReplaceAll(column, ":", " AS ")
if !strings.Contains(column, " AS ") {
field := fieldStyle(e.ctx, tableName, column)
if field != column {
column = "`" + column + "`" + " AS " + field
} else {
column = "`" + column + "`"
}
} else {
fieldName = strings.TrimSpace(strings.Split(fieldName, "AS")[0])
}
// 过滤可访问字段
if e.config.NoVerify || lo.Contains(outFields, dbStyle(e.ctx, tableName, fieldName)) ||
len(outFields) == 0 /* 数据库中未设置, 则看成全部可访问 */ {
fields = append(fields, column)
}
}
return fields
}
func (e *SqlExecutor) SetEmptyResult() {
e.WithEmptyResult = true
}
func (e *SqlExecutor) Count() (total int64, err error) {
m := e.build()
_total, err := m.Count()
if err != nil || _total == 0 {
return 0, err
} else {
total = int64(_total)
}
return total, nil
}
func (e *SqlExecutor) List(page int, count int) (list []model.Map, err error) {
if e.WithEmptyResult {
return nil, err
}
m := e.build()
m = m.Fields(e.column())
m = m.Page(page, count)
all, err := m.All()
if err != nil {
return nil, err
}
for _, item := range all.List() {
list = append(list, item)
}
return list, nil
}
func (e *SqlExecutor) One() (model.Map, error) {
if e.WithEmptyResult {
return nil, nil
}
m := e.build()
m = m.Fields(e.column())
one, err := m.One()
return one.Map(), err
}