This repository has been archived by the owner on Nov 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_builder.go
685 lines (614 loc) · 16.7 KB
/
query_builder.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
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
package rushia
import (
"fmt"
"reflect"
"regexp"
"strings"
"github.com/iancoleman/strcase"
)
// isOmitted searchs for the field in the query omit option.
func (q *Query) isOmitted(field string) bool {
for _, v := range q.omits {
if v == field {
return true
}
}
return false
}
// bindOptions is the option for different binding situations.
type bindOptions struct {
// noParentheses decides to wrap the sub query in the parentheses or not.
noParentheses bool
// keepStringValue returns the original string value instead of treating it like a prepared statement.
// usually used for column names, so it won't be convert to `?` symbol.
keepStringValue bool
}
// bindParams loops the bindParam function for each value in the slice, and the values will be bind into the Query.
func (q *Query) bindParams(data []interface{}, options *bindOptions) string {
var qu string
for _, v := range data {
qu += fmt.Sprintf("%s, ", q.bindParam(v, options))
}
return q.trim(qu)
}
// bindParam binds the value to the Query and returns how it should look in SQL based on it's type.
// If the value was a sub query, `bindParam` builds it and push the params from the sub query to the current query, and returns the sub query SQL.
func (q *Query) bindParam(data interface{}, options *bindOptions) string {
switch v := data.(type) {
case *Query:
qu, p := Build(v)
q.params = append(q.params, p...)
if options != nil && options.noParentheses {
return qu
}
return fmt.Sprintf("(%s)", qu)
case *Expr:
exprQ, exprP := buildExpr(v)
q.params = append(q.params, exprP...)
return exprQ
case nil:
return "NULL"
case string:
if options != nil && options.keepStringValue {
return q.escapeCol(v)
}
q.params = append(q.params, data)
return "?"
default:
q.params = append(q.params, data)
return "?"
}
}
// separateStrings separates the strings with commas.
func (q *Query) separateStrings(strs []string) (result string) {
for _, v := range strs {
result += fmt.Sprintf("%s, ", q.escapeCol(v))
}
return strings.TrimSuffix(result, ", ")
}
// separateParams binds the values while separating them.
func (q *Query) separateParams(j []interface{}) string {
var qu string
for _, v := range j {
qu += fmt.Sprintf("%s, ", q.bindParam(v, nil))
}
return q.trim(qu)
}
// separatePairs binds the values and making the key value as a pair.
func (q *Query) separatePairs(h H) string {
var qu string
for k, v := range h {
qu += fmt.Sprintf("%s = %s, ", q.escapeCol(k), q.bindParam(v, nil))
}
return q.trim(qu)
}
func (q *Query) escapeCol(v string) string {
// Ignore if `table.column`
if strings.Contains(v, ".") || strings.Contains(v, " ") || strings.Contains(v, "(") {
return v
}
return fmt.Sprintf("`%s`", v)
}
// separateGroups binds the value group and wraps each group in parentheses.
func (q *Query) separateGroups(j [][]interface{}) string {
var qu string
for _, v := range j {
qu += fmt.Sprintf("(%s), ", q.separateParams(v))
}
return q.trim(qu)
}
// padSpace adds the space in the end of the string if it was not empty.
func (q *Query) padSpace(s string) string {
if s != "" {
return fmt.Sprintf("%s ", s)
}
return s
}
//=======================================================
// Build
//=======================================================
func (q *Query) buildQuery() string {
switch q.typ {
case queryTypeInsert:
return q.buildInsert(insertTypeInsert)
case queryTypeReplace:
return q.buildReplace()
case queryTypeUpdate:
return q.buildUpdate(false)
case queryTypeSelect:
return q.buildSelect()
case queryTypePatch:
return q.buildPatch()
case queryTypeExists:
return q.buildExists()
case queryTypeInsertSelect:
return q.buildInsertSelect()
case queryTypeRawQuery:
return q.buildRawQuery()
case queryTypeDelete:
return q.buildDelete()
default:
return q.buildNothing()
}
}
func buildExpr(expr *Expr) (query string, params []interface{}) {
for i, j := range expr.params {
switch v := j.(type) {
case *Query:
q, p := Build(v)
expr.rawQuery = replaceNth(expr.rawQuery, "?", q, i+1)
params = append(params, p...)
default:
params = append(params, j)
}
}
query = expr.rawQuery
return
}
func (q *Query) buildInsert(typ insertType) string {
columns, values, _ := q.explodeData(q.data, []string{})
insertQuery := typ.toQuery()
beforeQuery := q.padSpace(q.trim(q.buildBeforeQueryOptions()))
tableQuery := q.bindParam(q.table, &bindOptions{
keepStringValue: true,
})
columnsQuery := q.separateStrings(columns)
valuesQuery := q.separateGroups(values)
return fmt.Sprintf("%s %sINTO %s (%s) VALUES %s",
insertQuery,
beforeQuery,
tableQuery,
columnsQuery,
valuesQuery,
)
}
func (q *Query) buildReplace() string {
return q.buildInsert(insertTypeReplace)
}
func (q *Query) buildUpdate(isPatch bool) string {
_, _, h := q.explodeData(q.data, []string{})
data := h[0]
if isPatch {
data = q.patchH(data)
}
beforeQuery := q.padSpace(q.trim(q.buildBeforeQueryOptions()))
tableQuery := q.bindParam(q.table, &bindOptions{
keepStringValue: true,
})
pairsQuery := q.separatePairs(data)
return fmt.Sprintf("UPDATE %s%s SET %s",
beforeQuery,
tableQuery,
pairsQuery,
)
}
func (q *Query) buildDelete() string {
tableQuery := q.bindParam(q.table, &bindOptions{
keepStringValue: true,
})
return fmt.Sprintf("DELETE FROM %s", tableQuery)
}
func (q *Query) buildNothing() string {
tableQuery := q.bindParam(q.table, &bindOptions{
keepStringValue: true,
})
return tableQuery
}
func (q *Query) buildSelect() string {
beforeQuery := q.padSpace(q.trim(q.buildBeforeQueryOptions()))
selectQuery := "*"
if len(q.selects) != 0 {
selectQuery = q.bindParams(q.selects, &bindOptions{keepStringValue: true})
}
tableQuery := q.bindParam(q.table, &bindOptions{keepStringValue: true})
return fmt.Sprintf("SELECT %s%s FROM %s", beforeQuery, selectQuery, tableQuery)
}
func (q *Query) buildPatch() string {
return q.buildUpdate(true)
}
func (q *Query) buildExists() string {
query, params := Build(NewRawQuery("SELECT EXISTS(?)", q.Copy().Select()))
q.params = params
return query
}
func (q *Query) buildInsertSelect() string {
beforeQuery := q.padSpace(q.trim(q.buildBeforeQueryOptions()))
tableQuery := q.bindParam(q.table, &bindOptions{
keepStringValue: true,
})
fieldQuery := q.bindParams(q.selects, &bindOptions{
keepStringValue: true,
})
selectQuery, selectParams := Build(q.subQuery)
q.bindParams(selectParams, nil)
return fmt.Sprintf("INSERT %sINTO %s (%s) %s",
beforeQuery,
tableQuery,
fieldQuery,
selectQuery,
)
}
func (q *Query) buildRawQuery() string {
query, params := buildExpr(NewExpr(q.rawQuery, q.params...))
q.params = params
return query
}
func (q *Query) buildUnion() string {
if len(q.unions) == 0 {
return ""
}
var unionQuery string
for _, v := range q.unions {
query, params := Build(v.query)
q.bindParams(params, nil)
if v.all {
unionQuery += fmt.Sprintf("UNION ALL %s", query)
} else {
unionQuery += fmt.Sprintf("UNION (%s)", query)
}
}
return unionQuery
}
func (q *Query) buildAs() string {
if q.alias == "" {
return ""
}
return fmt.Sprintf("AS %s", q.alias)
}
func (q *Query) buildDuplicate() string {
if q.duplicate == nil {
return ""
}
duplicateQuery := q.separatePairs(q.duplicate)
return fmt.Sprintf("ON DUPLICATE KEY UPDATE %s", duplicateQuery)
}
func (q *Query) buildJoin() string {
var jqu string
for _, v := range q.joins {
var table string
switch {
// .Join(subQuery, "Column = Column")
case v.subQuery != nil:
table = q.bindParam(v.subQuery, nil)
// .Join("Table", "Column = Column")
case v.table != "":
table = q.escapeCol(v.table)
}
jqu += fmt.Sprintf("%s %s ON (%s) ", v.typ.toQuery(), table, q.buildConditions(v.conditions))
}
return q.trim(jqu)
}
func removeIndex(s []interface{}, index int) []interface{} {
return append(s[:index], s[index+1:]...)
}
func (q *Query) buildConditions(conditions []condition) string {
var qu string
for i, condition := range conditions {
// Don't apply the AND/OR connector to the first item.
if i != 0 {
qu += fmt.Sprintf("%s ", condition.connector.toQuery())
}
if len(condition.args) == 0 {
qu += fmt.Sprintf("%s ", condition.query)
continue
}
// ?
if !strings.Contains(condition.query, "?") {
panic("rushia: incorrect where condition usage")
}
if strings.Contains(condition.query, "??") {
r := regexp.MustCompile(`(?m)(\?\?|\?)`)
found := r.FindAllString(condition.query, -1)
count := strings.Count(condition.query, "??")
for i := len(found) - 1; i >= 0; i-- {
if found[i] != "??" {
continue
}
condition.query = replaceNth(condition.query, "??", fmt.Sprintf("`%s`", condition.args[i].(string)), count)
count--
condition.args = removeIndex(condition.args, i)
}
}
//
for argIndex, arg := range condition.args {
//
if v, ok := arg.(*Query); ok {
query, params := Build(v)
//replacement := query
//if strings.Contains(condition.query, "EXISTS") {
// replacement = fmt.Sprintf("(%s)", query)
//}
condition.query = replaceNth(condition.query, "?", fmt.Sprintf("(%s)", query), argIndex+1)
q.bindParams(params, nil)
continue
}
//
if reflect.TypeOf(arg).Kind() == reflect.Slice {
var params []interface{}
s := reflect.ValueOf(arg)
if s.Len() == 0 {
panic("rushia: no len slice was passed as arg, stop it before sending to rushia")
}
for i := 0; i < s.Len(); i++ {
params = append(params, s.Index(i).Interface())
}
condition.query = replaceNth(condition.query, "?", fmt.Sprintf("(%s)", q.bindParams(params, nil)), argIndex+1)
continue
}
q.bindParam(arg, nil)
}
qu += fmt.Sprintf("%s ", condition.query)
}
return q.trim(qu)
}
func (q *Query) processEscaped(qu string, args ...interface{}) (string, []interface{}) {
if !strings.Contains(qu, "??") {
return qu, args
}
r := regexp.MustCompile(`(?m)(\?\?|\?)`)
found := r.FindAllString(qu, -1)
count := strings.Count(qu, "??")
for i := len(found) - 1; i >= 0; i-- {
if found[i] != "??" {
continue
}
qu = replaceNth(qu, "??", fmt.Sprintf("`%s`", args[i].(string)), count)
count--
args = removeIndex(args, i)
}
return qu, args
}
func (q *Query) buildWhere() string {
if len(q.wheres) == 0 {
return ""
}
return fmt.Sprintf("WHERE %s", q.buildConditions(q.wheres))
}
func (q *Query) buildHaving() string {
if len(q.havings) == 0 {
return ""
}
return fmt.Sprintf("HAVING %s", q.buildConditions(q.havings))
}
func (q *Query) buildOrderBy() string {
if len(q.orders) == 0 {
return ""
}
var qu string
for _, v := range q.orders {
switch {
// .OrderBy("RAND()")
// .OrderBy("ID ASC")
case v.column != "":
qu += fmt.Sprintf("%s, ", v.column)
// .OrderByField("UserGroup ASC", "SuperUser", "Admin")
case v.field != "":
qu += fmt.Sprintf("FIELD (%s, %s), ", v.field, q.bindParams(v.values, nil))
}
}
return fmt.Sprintf("ORDER BY %s", q.trim(qu))
}
func (q *Query) buildGroupBy() string {
if len(q.groups) == 0 {
return ""
}
var result string
for _, v := range q.groups {
result += fmt.Sprintf("%s, ", q.escapeCol(v))
}
return fmt.Sprintf("GROUP BY %s", strings.TrimSuffix(result, ", "))
}
func (q *Query) buildLimit() string {
if q.limit.from != 0 && q.limit.count == 0 {
return fmt.Sprintf("LIMIT %d", q.limit.from)
} else if q.limit.count != 0 {
return fmt.Sprintf("LIMIT %d, %d", q.limit.from, q.limit.count)
} else {
return ""
}
}
func (q *Query) buildOffset() string {
if q.offset.count == 0 && q.offset.offset == 0 {
return ""
}
return fmt.Sprintf("LIMIT %d OFFSET %d", q.offset.count, q.offset.offset)
}
func (q *Query) buildBeforeQueryOptions() string {
var qu string
for _, v := range q.queryOptions {
switch v {
case "ALL", "DISTINCT", "SQL_CACHE", "SQL_NO_CACHE", "DISTINCTROW", "HIGH_PRIORITY", "STRAIGHT_JOIN", "SQL_SMALL_RESULT", "SQL_BIG_RESULT", "SQL_BUFFER_RESULT", "SQL_CALC_FOUND_ROWS", "LOW_PRIORITY", "QUICK", "IGNORE", "DELAYED":
qu += fmt.Sprintf("%s, ", v)
}
}
return qu
}
func (q *Query) buildAfterQueryOptions() string {
var qu string
for _, v := range q.queryOptions {
switch v {
case "FOR UPDATE", "LOCK IN SHARE MODE":
qu += fmt.Sprintf("%s, ", v)
}
}
return qu
}
//=======================================================
// Helpers
//=======================================================
func (q *Query) explodeData(data any, preferCols []string) (cols []string, vals [][]any, datas []H) {
switch v := data.(type) {
case H:
val := q.omitH(v)
expCols, expVal := q.explodeH(val, preferCols)
return expCols, [][]any{expVal}, []H{val}
case []H:
for _, j := range v {
expCols, expVals, expDatas := q.explodeData(j, preferCols)
if len(preferCols) == 0 {
preferCols = expCols
cols = expCols
}
vals = append(vals, expVals...)
datas = append(datas, expDatas...)
}
return cols, vals, datas
case map[string]interface{}:
return q.explodeData(H(v), preferCols)
case []map[string]interface{}:
return q.explodeData(q.mapsToHs(v), preferCols)
case reflect.Value:
switch v.Kind() {
case reflect.Ptr:
return q.explodeData(reflect.Indirect(v), preferCols)
default:
return q.explodeData(q.explodeValue(v), preferCols)
}
default:
switch reflect.TypeOf(data).Kind() {
case reflect.Slice:
s := reflect.ValueOf(data)
for i := 0; i < s.Len(); i++ {
expCols, expVals, expDatas := q.explodeData(s.Index(i), preferCols)
if len(preferCols) == 0 {
preferCols = expCols
cols = expCols
}
vals = append(vals, expVals...)
datas = append(datas, expDatas...)
}
return cols, vals, datas
case reflect.Struct:
return q.explodeData(reflect.ValueOf(data), preferCols)
case reflect.Ptr:
return q.explodeData(reflect.Indirect(reflect.ValueOf(data)), preferCols)
}
}
panic("rushia: parsing unknown type")
}
// explodeH
func (q *Query) explodeH(data H, preferCols []string) (cols []string, vals []interface{}) {
if len(preferCols) == 0 {
for k, v := range data {
cols = append(cols, k)
vals = append(vals, v)
}
} else {
for _, colKey := range preferCols {
cols = append(cols, colKey)
vals = append(vals, data[colKey]) // Ignore the error check and panic
}
}
return
}
// patchH eliminates the zero values of a H data,
// and it also refers to the Query exclude option.
func (q *Query) patchH(data H) H {
for k, v := range data {
if q.shouldEliminate(k, v) {
delete(data, k)
}
}
return data
}
// omitH omits the fields of a H data based on the Query omit option.
func (q *Query) omitH(data H) H {
for k := range data {
if q.isOmitted(k) {
delete(data, k)
}
}
return data
}
// explodeValue converts a struct to H data and rename/omit it by the rushia struct tag.
func (q *Query) explodeValue(val reflect.Value) H {
h := make(H)
t := val.Type()
for i := 0; i < t.NumField(); i++ {
k := strcase.ToSnake(t.Field(i).Name)
if name, ok := t.Field(i).Tag.Lookup("rushia"); ok {
if name == "" || name == "-" {
continue
}
k = name
}
h[k] = val.Field(i).Interface()
}
return h
}
// mapsToHs converts map slice to H slice.
func (q *Query) mapsToHs(data []map[string]interface{}) []H {
var hs []H
for _, j := range data {
hs = append(hs, H(j))
}
return hs
}
// shouldEliminate is designed for Patch.
// Returns true if the value was a zero value to indicates the value should be skipped,
// returns false if the value was not a zero value, either the type/field name was in the exclude list.
func (q *Query) shouldEliminate(k string, v interface{}) bool {
var isExcludedColumn bool
for _, j := range q.exclude.fields {
if k == j {
isExcludedColumn = true
break
}
}
valueOf := reflect.ValueOf(v)
var isExcludedKind bool
kind := valueOf.Kind()
for _, j := range q.exclude.kinds {
if kind == j {
isExcludedKind = true
break
}
}
return (!isExcludedColumn && !isExcludedKind) && valueOf.IsZero()
}
// trim trims the unnecessary commas in the end of the string.
func (q *Query) trim(s string) string {
return strings.TrimRight(strings.TrimSpace(s), ",")
}
// replaceNth removes the nth repeated occurrence of the specified string,
// usually used for sub query prepared statment `?` symbol replacement.
func replaceNth(s, old, new string, n int) string {
i := 0
for m := 1; m <= n; m++ {
x := strings.Index(s[i:], old)
if x < 0 {
break
}
i += x
if m == n {
return s[:i] + new + s[i+len(old):]
}
i += len(old)
}
return s
}
// putJoin
func (q *Query) putJoin(typ joinType, t interface{}, conditions ...interface{}) *Query {
j := join{
typ: typ,
}
switch v := t.(type) {
case *Query:
j.subQuery = v
case string:
j.table = v
}
if len(conditions) != 0 {
j.conditions = []condition{
{
query: conditions[0].(string),
args: conditions[1:],
// It's fine to be `And` or `Or`
// since the build doesn't build the first connector.
connector: connectorTypeAnd,
},
}
}
q.joins = append(q.joins, j)
return q
}