-
Notifications
You must be signed in to change notification settings - Fork 3
/
builder.go
829 lines (743 loc) · 19.5 KB
/
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
package sql
import (
"math"
"reflect"
"strings"
"time"
"github.com/abulo/ratel/v3/stores/null"
"github.com/pkg/errors"
)
// BETWEEN ...
const (
BETWEEN = "BETWEEN"
NOTBETWEEN = "NOT BETWEEN"
IN = "IN"
NOTIN = "NOT IN"
AND = "AND"
OR = "OR"
ISNULL = "IS NULL"
ISNOTNULL = "IS NOT NULL"
EQUAL = "="
NOTEQUAL = "!="
GREATER = ">"
GREATEREQUAL = ">="
LESS = "<"
LESSEQUAL = "<="
LIKE = "LIKE"
JOIN = "JOIN"
INNERJOIN = "INNER JOIN"
LEFTJOIN = "LEFT JOIN"
RIGHTJOIN = "RIGHT JOIN"
UNION = "UNION"
UNIONALL = "UNION ALL"
DESC = "DESC"
ASC = "ASC"
)
// Builder 查询构造器
type Builder struct {
table []string
columns []string
where []w
orders []string
groups []string
limit int64
offset int64
distinct bool
joins []join
unions []union
unLimit int64
unOffset int64
unOrders []string
args []any
whereArgs []any
data []map[string]any
}
type join struct {
table string
on string
operator string
}
type union struct {
builder Builder
operator string
}
type w struct {
column string
operator string
valueNum int64
do string
}
// NewBuilder 创建查询构造器
func NewBuilder() *Builder {
return &Builder{}
}
// Table 设置操作的表名称
func (builder *Builder) Table(tableName ...string) *Builder {
builder.table = tableName
return builder
}
// Select 查询字段
func (builder *Builder) Select(columns ...string) *Builder {
builder.columns = columns
return builder
}
// Where 构造条件语句
func (builder *Builder) Where(column string, value ...any) *Builder {
if len(value) == 0 { //一个参数直接where
builder.toWhere(column, "", 0, AND)
} else if len(value) == 1 { //2个参数直接where =
builder.toWhere(column, EQUAL, 1, AND)
builder.addArg(value[0])
} else { //3个参数
switch v := value[0].(type) {
case string:
builder.toWhere(column, v, 1, AND)
builder.addArg(value[1])
}
}
return builder
}
// OrWhere 构造OR条件
func (builder *Builder) OrWhere(column string, value ...any) *Builder {
if len(value) == 0 { //一个参数直接where
builder.toWhere(column, "", 0, OR)
} else if len(value) == 1 { //2个参数直接where =
builder.toWhere(column, EQUAL, 1, OR)
builder.addArg(value[0])
} else {
switch v := value[0].(type) {
case string:
builder.toWhere(column, v, 1, OR)
builder.addArg(value[1])
}
}
return builder
}
// Equal 构造等于
func (builder *Builder) Equal(column string, value any) *Builder {
builder.toWhere(column, EQUAL, 1, AND)
builder.addArg(value)
return builder
}
// OrEqual 构造或者等于
func (builder *Builder) OrEqual(column string, value any) *Builder {
builder.toWhere(column, EQUAL, 1, OR)
builder.addArg(value)
return builder
}
// NotEqual 构造不等于
func (builder *Builder) NotEqual(column string, value any) *Builder {
builder.toWhere(column, NOTEQUAL, 1, AND)
builder.addArg(value)
return builder
}
// Greater 构造大于
func (builder *Builder) Greater(column string, value any) *Builder {
builder.toWhere(column, GREATER, 1, AND)
builder.addArg(value)
return builder
}
// Greater 构造大于等于
func (builder *Builder) GreaterEqual(column string, value any) *Builder {
builder.toWhere(column, GREATEREQUAL, 1, AND)
builder.addArg(value)
return builder
}
// Greater 构造小于
func (builder *Builder) Less(column string, value any) *Builder {
builder.toWhere(column, LESS, 1, AND)
builder.addArg(value)
return builder
}
// Greater 构造小于等于
func (builder *Builder) LessEqual(column string, value any) *Builder {
builder.toWhere(column, LESSEQUAL, 1, AND)
builder.addArg(value)
return builder
}
// OrNotEqual 构造或者不等于
func (builder *Builder) OrNotEqual(column string, value any) *Builder {
builder.toWhere(column, NOTEQUAL, 1, OR)
builder.addArg(value)
return builder
}
// Between 构造Between
func (builder *Builder) Between(column string, value1 any, value2 any) *Builder {
builder.toWhere(column, BETWEEN, 2, AND)
builder.addArg(value1, value2)
return builder
}
// OrBetween 构造 或者 Between
func (builder *Builder) OrBetween(column string, value1 any, value2 any) *Builder {
builder.toWhere(column, BETWEEN, 2, OR)
builder.addArg(value1, value2)
return builder
}
// NotBetween 构造不Not Between
func (builder *Builder) NotBetween(column string, value1 any, value2 any) *Builder {
builder.toWhere(column, NOTBETWEEN, 2, AND)
builder.addArg(value1, value2)
return builder
}
// NotOrBetween 构造 Not Between OR Not Between
func (builder *Builder) NotOrBetween(column string, value1 any, value2 any) *Builder {
builder.toWhere(column, NOTBETWEEN, 2, OR)
builder.addArg(value1, value2)
return builder
}
// In 构造 in语句
func (builder *Builder) In(column string, value ...any) *Builder {
builder.toWhere(column, IN, int64(len(value)), AND)
builder.addArg(value...)
return builder
}
// OrIn orin语句
func (builder *Builder) OrIn(column string, value ...any) *Builder {
builder.toWhere(column, IN, int64(len(value)), OR)
builder.addArg(value...)
return builder
}
// NotIn .
func (builder *Builder) NotIn(column string, value ...any) *Builder {
builder.toWhere(column, NOTIN, int64(len(value)), AND)
builder.addArg(value...)
return builder
}
// OrNotIn .
func (builder *Builder) OrNotIn(column string, value ...any) *Builder {
builder.toWhere(column, NOTIN, int64(len(value)), OR)
builder.addArg(value...)
return builder
}
// IsNULL .
func (builder *Builder) IsNULL(column string) *Builder {
builder.toWhere(column, ISNULL, 0, AND)
return builder
}
// OrIsNULL .
func (builder *Builder) OrIsNULL(column string) *Builder {
builder.toWhere(column, ISNULL, 0, OR)
return builder
}
// IsNotNULL .
func (builder *Builder) IsNotNULL(column string) *Builder {
builder.toWhere(column, ISNOTNULL, 0, AND)
return builder
}
// OrIsNotNULL .
func (builder *Builder) OrIsNotNULL(column string) *Builder {
builder.toWhere(column, ISNOTNULL, 0, OR)
return builder
}
// Like .
func (builder *Builder) Like(column string, value any) *Builder {
builder.toWhere(column, LIKE, 1, AND)
builder.addArg(value)
return builder
}
// OrLike .
func (builder *Builder) OrLike(column string, value any) *Builder {
builder.toWhere(column, LIKE, 1, OR)
builder.addArg(value)
return builder
}
// Join .
func (builder *Builder) Join(tablename string, on string) *Builder {
builder.joins = append(builder.joins, join{table: tablename, on: on, operator: JOIN})
return builder
}
// InnerJoin ...
func (builder *Builder) InnerJoin(tablename string, on string) *Builder {
builder.joins = append(builder.joins, join{table: tablename, on: on, operator: INNERJOIN})
return builder
}
// LeftJoin .
func (builder *Builder) LeftJoin(tablename string, on string) *Builder {
builder.joins = append(builder.joins, join{table: tablename, on: on, operator: LEFTJOIN})
return builder
}
// RightJoin .
func (builder *Builder) RightJoin(tablename string, on string) *Builder {
builder.joins = append(builder.joins, join{table: tablename, on: on, operator: RIGHTJOIN})
return builder
}
// Union .
func (builder *Builder) Union(unions ...Builder) *Builder {
for i, len := 0, len(unions); i < len; i++ {
builder.unions = append(builder.unions, union{builder: unions[i], operator: UNION})
builder.addArg(unions[i].args...)
}
return builder
}
// UnionOffset .
func (builder *Builder) UnionOffset(offset int64) *Builder {
builder.unOffset = offset
return builder
}
// UnionLimit .
func (builder *Builder) UnionLimit(limit int64) *Builder {
builder.unLimit = limit
return builder
}
// UnionOrderBy .
func (builder *Builder) UnionOrderBy(column string, direction string) *Builder {
if strings.ToUpper(direction) == DESC {
column += " " + DESC
} else {
column += " " + ASC
}
builder.unOrders = append(builder.unOrders, column)
return builder
}
// UnionAll .
func (builder *Builder) UnionAll(unions ...Builder) *Builder {
for i, len := 0, len(unions); i < len; i++ {
builder.unions = append(builder.unions, union{builder: unions[i], operator: UNIONALL})
builder.addArg(unions[i].args...)
}
return builder
}
// Distinct .
func (builder *Builder) Distinct() *Builder {
builder.distinct = true
return builder
}
// GroupBy .
func (builder *Builder) GroupBy(groups ...string) *Builder {
builder.groups = groups
return builder
}
// OrderBy .
func (builder *Builder) OrderBy(column string, direction string) *Builder {
if strings.ToUpper(direction) == DESC {
column += " " + DESC
} else {
column += " " + ASC
}
builder.orders = append(builder.orders, column)
return builder
}
// Offset .
func (builder *Builder) Offset(offset int64) *Builder {
builder.offset = offset
return builder
}
// Skip .
func (builder *Builder) Skip(offset int64) *Builder {
builder.offset = offset
return builder
}
// Limit .
func (builder *Builder) Limit(limit int64) *Builder {
builder.limit = limit
return builder
}
// ToSQL 输出SQL语句
func (builder *Builder) ToSQL(method string) string {
grammar := Grammar{builder: builder, method: method}
return grammar.ToSQL()
}
func (builder *Builder) toWhere(column string, operator string, valueNum int64, do string) *Builder {
builder.where = append(
builder.where,
w{column: column, operator: operator, valueNum: valueNum, do: do})
return builder
}
func (builder *Builder) addArg(value ...any) {
builder.args = append(builder.args, value...)
}
func (builder *Builder) beforeArg(value ...any) {
builder.whereArgs = append(builder.whereArgs, value...)
}
func (builder *Builder) setData(data ...map[string]any) {
builder.data = data
}
func (builder *Builder) getInsertMap(data any) (columns []string, values map[string][]any, err error) {
stValue := reflect.Indirect(reflect.ValueOf(data))
values = make(map[string][]any, 0)
switch stValue.Kind() {
case reflect.Struct:
var ignore bool
for i := 0; i < stValue.NumField(); i++ {
v := reflect.Indirect(stValue.Field(i))
//处理嵌套的struct中的db映射字段
if v.Kind() == reflect.Struct {
var ignore bool
switch v.Interface().(type) {
case time.Time:
ignore = true
case null.Bool:
ignore = true
case null.Byte:
ignore = true
case null.Bytes:
ignore = true
case null.CTime:
ignore = true
case null.Date:
ignore = true
case null.DateTime:
ignore = true
case null.Float32:
ignore = true
case null.Float64:
ignore = true
case null.Int:
ignore = true
case null.Int8:
ignore = true
case null.Int16:
ignore = true
case null.Int32:
ignore = true
case null.Int64:
ignore = true
case null.JSON:
ignore = true
case null.String:
ignore = true
case null.Time:
ignore = true
case null.TimeStamp:
ignore = true
case null.Uint:
ignore = true
case null.Uint8:
ignore = true
case null.Uint16:
ignore = true
case null.Uint32:
ignore = true
case null.Uint64:
ignore = true
}
if !ignore {
cols, vals, err := builder.getInsertMap(v.Interface())
if err != nil {
return nil, nil, err
}
for _, column := range cols {
if _, ok := values[column]; !ok {
columns = append(columns, column)
}
}
for column, v := range vals {
if _, ok := values[column]; ok {
values[column] = append(values[column], v...)
} else {
values[column] = v
}
}
}
}
tag := stValue.Type().Field(i).Tag.Get("db")
attrList := strings.Split(tag, ",")
ignore = false
if len(attrList) > 0 {
for _, attr := range attrList {
if attr == "-" {
ignore = true
break
}
}
}
if ignore {
continue
}
column := attrList[0]
if column != "" && !builder.IsZero(v) {
if _, ok := values[column]; ok {
values[column] = append(values[column], v.Interface())
} else {
columns = append(columns, column)
values[column] = []any{v.Interface()}
}
}
}
case reflect.Map:
keys := stValue.MapKeys()
for _, k := range keys {
column := k.String()
if _, ok := values[column]; ok {
values[column] = append(values[column], stValue.MapIndex(k).Interface())
} else {
columns = append(columns, column)
values[column] = []any{stValue.MapIndex(k).Interface()}
}
}
case reflect.Slice:
n := stValue.Len()
for i := 0; i < n; i++ {
item := stValue.Index(i)
cols, vals, err := builder.getInsertMap(item.Interface())
if err != nil {
return nil, nil, err
}
for _, column := range cols {
if _, ok := values[column]; !ok {
columns = append(columns, column)
}
}
for column, v := range vals {
if _, ok := values[column]; ok {
values[column] = append(values[column], v...)
} else {
values[column] = v
}
}
}
}
return
}
// IsZero ...
func (builder *Builder) IsZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return math.Float64bits(v.Float()) == 0
case reflect.Complex64, reflect.Complex128:
c := v.Complex()
return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0
case reflect.Array:
for i := 0; i < v.Len(); i++ {
if !v.Index(i).IsZero() {
return false
}
}
return true
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
return v.IsNil()
case reflect.String:
return v.Len() == 0
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
if !v.Field(i).IsZero() {
return false
}
}
return true
default:
// This should never happens, but will act as a safeguard for
// later, as a default value doesn't makes sense here.
panic(&reflect.ValueError{
Method: "reflect.Value.IsZero",
Kind: v.Kind(),
})
}
}
// MultiInsert 批量插入
func (builder *Builder) MultiInsert(data ...any) (sql string, args []any, err error) {
stVal := reflect.ValueOf(data)
if stVal.Kind() != reflect.Slice {
err = errors.New("data is not []any type")
return
}
n := stVal.Len()
if n < 1 {
err = errors.New("insert data cannot be empty")
return
}
columns, values, errBuild := builder.getInsertMap(data)
if errBuild != nil {
err = errBuild
return
}
bindingsArr := make([]map[string]any, n)
for i := 0; i < n; i++ {
bindings := make(map[string]any, 0)
for _, column := range columns {
bindings[column] = values[column][i]
}
bindingsArr[i] = bindings
}
builder.setData(bindingsArr...)
grammar := Grammar{builder: builder}
sql = grammar.Insert()
if len(builder.columns) < 1 {
err = errors.New("insert data cannot be empty")
return
}
args, err = builder.args, nil
return
}
// Replace 替换
func (builder *Builder) Replace(data ...any) (sql string, args []any, err error) {
stVal := reflect.ValueOf(data)
if stVal.Kind() != reflect.Slice {
err = errors.New("data is not []any type")
return
}
n := stVal.Len()
if n < 1 {
err = errors.New("insert data cannot be empty")
return
}
columns, values, errBuild := builder.getInsertMap(data)
if errBuild != nil {
err = errBuild
return
}
bindingsArr := make([]map[string]any, n)
for i := 0; i < n; i++ {
bindings := make(map[string]any, 0)
for _, column := range columns {
bindings[column] = values[column][i]
}
bindingsArr[i] = bindings
}
builder.setData(bindingsArr...)
grammar := Grammar{builder: builder}
sql = grammar.Replace()
if len(builder.columns) < 1 {
err = errors.New("insert data cannot be empty")
return
}
args, err = builder.args, nil
return
}
// InsertUpdate ...
func (builder *Builder) InsertUpdate(insert any, update any) (sql string, args []any, err error) {
columns, values, err := builder.getInsertMap(insert)
if err != nil {
return
}
bindingsInsert := map[string]any{}
for _, column := range columns {
bindingsInsert[column] = values[column][0]
}
columns, values, errBuild := builder.getInsertMap(update)
if errBuild != nil {
err = errBuild
return
}
bindingsUpdate := map[string]any{}
for _, column := range columns {
bindingsUpdate[column] = values[column][0]
}
builder.setData(bindingsInsert, bindingsUpdate)
grammar := Grammar{builder: builder}
sql = grammar.InsertUpdate()
args, err = builder.args, nil
return
}
// Insert 插入数据
func (builder *Builder) Insert(data any) (sql string, args []any, err error) {
columns, values, errBuild := builder.getInsertMap(data)
if errBuild != nil {
err = errBuild
return
}
bindings := map[string]any{}
for _, column := range columns {
bindings[column] = values[column][0]
}
builder.setData(bindings)
grammar := Grammar{builder: builder}
sql = grammar.Insert()
args, err = builder.args, nil
return
}
// Update 更新
func (builder *Builder) Update(data any) (sql string, args []any, err error) {
columns, values, errBuild := builder.getInsertMap(data)
if errBuild != nil {
err = errBuild
return
}
bindings := map[string]any{}
for _, column := range columns {
bindings[column] = values[column][0]
}
builder.setData(bindings)
grammar := Grammar{builder: builder}
sql = grammar.Update()
args = append(builder.whereArgs, builder.args...)
err = nil
return
}
// Delete .
func (builder *Builder) Delete() (sql string, args []any, err error) {
grammar := Grammar{builder: builder}
sql = grammar.Delete()
args, err = builder.args, nil
return
}
// Count ...
func (builder *Builder) Count() (sql string, args []any, err error) {
builder.Select("COUNT(1) AS _C")
grammar := Grammar{builder: builder}
sql = grammar.Select()
args, err = builder.args, nil
return
}
// Rows
func (builder *Builder) Rows() (sql string, args []any, err error) {
grammar := Grammar{builder: builder}
sql = grammar.Select()
args, err = builder.args, nil
return
}
// Row
func (builder *Builder) Row() (sql string, args []any, err error) {
builder.offset = 0
builder.limit = 1
grammar := Grammar{builder: builder}
sql = grammar.Select()
args, err = builder.args, nil
return
}
// // QueryRowsSQL ...
// func (builder *Builder) QueryRowsSQL(sql string, args ...any) string {
// builder.connection.LastSQL(sql, args...)
// return builder.connection.SQLRaw()
// }
// // QueryRowSQL ...
// func (builder *Builder) QueryRowSQL(sql string, args ...any) string {
// builder.connection.LastSQL(sql, args...)
// return builder.connection.SQLRaw()
// }
// // QueryRow ...
// func (builder *Builder) QueryRow(sql string, args ...any) *Row {
// rs := builder.QueryRows(sql, args...)
// r := new(Row)
// r.rs = rs
// return r
// }
// // Row 获取一条记录
// func (builder *Builder) Row() *Row {
// builder.offset = 0
// builder.limit = 1
// rs := builder.Rows()
// r := new(Row)
// r.rs = rs
// return r
// }
// // RowSQL ...
// func (builder *Builder) RowSQL() string {
// grammar := Grammar{builder: builder}
// sql := grammar.Select()
// builder.connection.LastSQL(sql, builder.args...)
// return builder.connection.SQLRaw()
// }
// // RowsSQL ...
// func (builder *Builder) RowsSQL() string {
// grammar := Grammar{builder: builder}
// sql := grammar.Select()
// builder.connection.LastSQL(sql, builder.args...)
// return builder.connection.SQLRaw()
// }
// // Rows 获取多条记录
// func (builder *Builder) Rows() *Rows {
// grammar := Grammar{builder: builder}
// sql := grammar.Select()
// rows, err := builder.connection.Query(builder.ctx, sql, builder.args...)
// if err != nil {
// return &Rows{rs: nil, lastError: err}
// }
// return &Rows{rs: rows, lastError: err}
// }