-
Notifications
You must be signed in to change notification settings - Fork 28
/
expression.go
793 lines (701 loc) · 18.7 KB
/
expression.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
package sqlingo
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
"unsafe"
)
type priority uint8
// Expression is the interface of an SQL expression.
type Expression interface {
// get the SQL string
GetSQL(scope scope) (string, error)
getOperatorPriority() priority
// <> operator
NotEquals(other interface{}) BooleanExpression
// == operator
Equals(other interface{}) BooleanExpression
// < operator
LessThan(other interface{}) BooleanExpression
// <= operator
LessThanOrEquals(other interface{}) BooleanExpression
// > operator
GreaterThan(other interface{}) BooleanExpression
// >= operator
GreaterThanOrEquals(other interface{}) BooleanExpression
IsNull() BooleanExpression
IsNotNull() BooleanExpression
IsTrue() BooleanExpression
IsNotTrue() BooleanExpression
IsFalse() BooleanExpression
IsNotFalse() BooleanExpression
In(values ...interface{}) BooleanExpression
NotIn(values ...interface{}) BooleanExpression
Between(min interface{}, max interface{}) BooleanExpression
NotBetween(min interface{}, max interface{}) BooleanExpression
Desc() OrderBy
As(alias string) Alias
If(trueValue interface{}, falseValue interface{}) UnknownExpression
IfNull(altValue interface{}) UnknownExpression
}
// Alias is the interface of an table/column alias.
type Alias interface {
GetSQL(scope scope) (string, error)
}
// BooleanExpression is the interface of an SQL expression with boolean value.
type BooleanExpression interface {
Expression
And(other interface{}) BooleanExpression
Or(other interface{}) BooleanExpression
Xor(other interface{}) BooleanExpression
Not() BooleanExpression
}
// NumberExpression is the interface of an SQL expression with number value.
type NumberExpression interface {
Expression
Add(other interface{}) NumberExpression
Sub(other interface{}) NumberExpression
Mul(other interface{}) NumberExpression
Div(other interface{}) NumberExpression
IntDiv(other interface{}) NumberExpression
Mod(other interface{}) NumberExpression
Sum() NumberExpression
Avg() NumberExpression
Min() UnknownExpression
Max() UnknownExpression
}
// StringExpression is the interface of an SQL expression with string value.
type StringExpression interface {
Expression
Min() UnknownExpression
Max() UnknownExpression
Like(other interface{}) BooleanExpression
Contains(substring string) BooleanExpression
Concat(other interface{}) StringExpression
IfEmpty(altValue interface{}) StringExpression
IsEmpty() BooleanExpression
Lower() StringExpression
Upper() StringExpression
Left(count interface{}) StringExpression
Right(count interface{}) StringExpression
Trim() StringExpression
}
type ArrayExpression interface {
Expression
}
type DateExpression interface {
Expression
Min() UnknownExpression
Max() UnknownExpression
}
// UnknownExpression is the interface of an SQL expression with unknown value.
type UnknownExpression interface {
Expression
And(other interface{}) BooleanExpression
Or(other interface{}) BooleanExpression
Xor(other interface{}) BooleanExpression
Not() BooleanExpression
Add(other interface{}) NumberExpression
Sub(other interface{}) NumberExpression
Mul(other interface{}) NumberExpression
Div(other interface{}) NumberExpression
IntDiv(other interface{}) NumberExpression
Mod(other interface{}) NumberExpression
Sum() NumberExpression
Avg() NumberExpression
Min() UnknownExpression
Max() UnknownExpression
Like(other interface{}) BooleanExpression
Contains(substring string) BooleanExpression
Concat(other interface{}) StringExpression
IfEmpty(altValue interface{}) StringExpression
IsEmpty() BooleanExpression
Lower() StringExpression
Upper() StringExpression
Left(count interface{}) StringExpression
Right(count interface{}) StringExpression
Trim() StringExpression
}
type expression struct {
sql string
builder func(scope scope) (string, error)
priority priority
isTrue bool
isFalse bool
isBool bool
}
func (e expression) GetTable() Table {
return nil
}
type scope struct {
Database *database
Tables []Table
lastJoin *join
}
func staticExpression(sql string, priority priority, isBool bool) expression {
return expression{
sql: sql,
priority: priority,
isBool: isBool,
}
}
func True() BooleanExpression {
return expression{
sql: "1",
isTrue: true,
isBool: true,
}
}
func False() BooleanExpression {
return expression{
sql: "0",
isFalse: true,
isBool: true,
}
}
// Raw create a raw SQL statement
func Raw(sql string) UnknownExpression {
return expression{
sql: sql,
priority: 99,
}
}
// And creates an expression with AND operator.
func And(expressions ...BooleanExpression) (result BooleanExpression) {
if len(expressions) == 0 {
result = True()
return
}
for _, condition := range expressions {
if result == nil {
result = condition
} else {
result = result.And(condition)
}
}
return
}
// Or creates an expression with OR operator.
func Or(expressions ...BooleanExpression) (result BooleanExpression) {
if len(expressions) == 0 {
result = False()
return
}
for _, condition := range expressions {
if result == nil {
result = condition
} else {
result = result.Or(condition)
}
}
return
}
func (e expression) As(name string) Alias {
return expression{builder: func(scope scope) (string, error) {
expressionSql, err := e.GetSQL(scope)
if err != nil {
return "", err
}
return expressionSql + " AS " + name, nil
}}
}
func (e expression) If(trueValue interface{}, falseValue interface{}) UnknownExpression {
return If(e, trueValue, falseValue)
}
func (e expression) IfNull(altValue interface{}) UnknownExpression {
return Function("IFNULL", e, altValue)
}
func (e expression) IfEmpty(altValue interface{}) StringExpression {
return If(e.NotEquals(""), e, altValue)
}
func (e expression) IsEmpty() BooleanExpression {
return e.Equals("")
}
func (e expression) Lower() StringExpression {
return function("LOWER", e)
}
func (e expression) Upper() StringExpression {
return function("UPPER", e)
}
func (e expression) Left(count interface{}) StringExpression {
return function("LEFT", e, count)
}
func (e expression) Right(count interface{}) StringExpression {
return function("RIGHT", e, count)
}
func (e expression) Trim() StringExpression {
return function("TRIM", e)
}
func (e expression) CharLength() NumberExpression {
return function("CHAR_LENGTH", e)
}
func (e expression) HasPrefix(prefix interface{}) BooleanExpression {
return e.Left(function("CHAR_LENGTH", prefix)).Equals(prefix)
}
func (e expression) HasSuffix(suffix interface{}) BooleanExpression {
return e.Right(function("CHAR_LENGTH", suffix)).Equals(suffix)
}
func (e expression) GetSQL(scope scope) (string, error) {
if e.sql != "" {
return e.sql, nil
}
return e.builder(scope)
}
var needsEscape = [256]int{
0: 1,
'\n': 1,
'\r': 1,
'\\': 1,
'\'': 1,
'"': 1,
0x1a: 1,
}
func quoteIdentifier(identifier string) (result dialectArray) {
for dialect := dialect(0); dialect < dialectCount; dialect++ {
switch dialect {
case dialectMySQL:
result[dialect] = "`" + identifier + "`"
case dialectMSSQL:
result[dialect] = "[" + identifier + "]"
default:
result[dialect] = "\"" + identifier + "\""
}
}
return
}
func quoteString(s string) string {
if s == "" {
return "''"
}
buf := make([]byte, len(s)*2+2)
buf[0] = '\''
n := 1
for i := 0; i < len(s); i++ {
b := s[i]
buf[n] = '\\'
n += needsEscape[b]
buf[n] = b
n++
}
buf[n] = '\''
n++
buf = buf[:n]
return *(*string)(unsafe.Pointer(&buf))
}
func getSQL(scope scope, value interface{}) (sql string, priority priority, err error) {
const mysqlTimeFormat = "2006-01-02 15:04:05.000000"
if value == nil {
sql = "NULL"
return
}
switch value.(type) {
case int:
sql = strconv.Itoa(value.(int))
case string:
sql = quoteString(value.(string))
case Expression:
sql, err = value.(Expression).GetSQL(scope)
priority = value.(Expression).getOperatorPriority()
case Assignment:
sql, err = value.(Assignment).GetSQL(scope)
case toSelectFinal:
sql, err = value.(toSelectFinal).GetSQL()
if err != nil {
return
}
sql = "(" + sql + ")"
case toUpdateFinal:
sql, err = value.(toUpdateFinal).GetSQL()
case Table:
sql = value.(Table).GetSQL(scope)
case CaseExpression:
sql, err = value.(CaseExpression).End().GetSQL(scope)
case time.Time:
tm := value.(time.Time)
if tm.IsZero() {
sql = "NULL"
} else {
tmStr := tm.Format(mysqlTimeFormat)
sql = quoteString(tmStr)
}
case *time.Time:
tm := value.(*time.Time)
if tm == nil || tm.IsZero() {
sql = "NULL"
} else {
tmStr := tm.Format(mysqlTimeFormat)
sql = quoteString(tmStr)
}
default:
v := reflect.ValueOf(value)
sql, priority, err = getSQLFromReflectValue(scope, v)
}
return
}
func getSQLFromReflectValue(scope scope, v reflect.Value) (sql string, priority priority, err error) {
if v.Kind() == reflect.Ptr {
// dereference pointers
for {
if v.IsNil() {
sql = "NULL"
return
}
v = v.Elem()
if v.Kind() != reflect.Ptr {
break
}
}
sql, priority, err = getSQL(scope, v.Interface())
return
}
switch v.Kind() {
case reflect.Bool:
if v.Bool() {
sql = "1"
} else {
sql = "0"
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
sql = strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
sql = strconv.FormatUint(v.Uint(), 10)
case reflect.Float32, reflect.Float64:
sql = strconv.FormatFloat(v.Float(), 'g', -1, 64)
case reflect.String:
sql = quoteString(v.String())
case reflect.Array, reflect.Slice:
length := v.Len()
values := make([]interface{}, length)
for i := 0; i < length; i++ {
values[i] = v.Index(i).Interface()
}
sql, err = commaValues(scope, values)
if err == nil {
sql = "(" + sql + ")"
}
default:
if vs, ok := v.Interface().(interface{ String() string }); ok {
sql = quoteString(vs.String())
} else {
err = fmt.Errorf("invalid type %s", v.Kind().String())
}
}
return
}
/*
1 INTERVAL
2 BINARY, COLLATE
3 !
4 - (unary minus), ~ (unary bit inversion)
5 ^
6 *, /, DIV, %, MOD
7 -, +
8 <<, >>
9 &
10 |
11 = (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
12 BETWEEN, CASE, WHEN, THEN, ELSE
13 NOT
14 AND, &&
15 XOR
16 OR, ||
17 = (assignment), :=
*/
func (e expression) NotEquals(other interface{}) BooleanExpression {
return e.binaryOperation("<>", other, 11, true)
}
func (e expression) Equals(other interface{}) BooleanExpression {
return e.binaryOperation("=", other, 11, true)
}
func (e expression) LessThan(other interface{}) BooleanExpression {
return e.binaryOperation("<", other, 11, true)
}
func (e expression) LessThanOrEquals(other interface{}) BooleanExpression {
return e.binaryOperation("<=", other, 11, true)
}
func (e expression) GreaterThan(other interface{}) BooleanExpression {
return e.binaryOperation(">", other, 11, true)
}
func (e expression) GreaterThanOrEquals(other interface{}) BooleanExpression {
return e.binaryOperation(">=", other, 11, true)
}
func toBooleanExpression(value interface{}) BooleanExpression {
e, ok := value.(expression)
switch {
case !ok:
return nil
case e.isTrue:
return True()
case e.isFalse:
return False()
case e.isBool:
return e
default:
return nil
}
}
func (e expression) And(other interface{}) BooleanExpression {
switch {
case e.isFalse:
return e
case e.isTrue:
if exp := toBooleanExpression(other); exp != nil {
return exp
}
}
return e.binaryOperation("AND", other, 14, true)
}
func (e expression) Or(other interface{}) BooleanExpression {
switch {
case e.isTrue:
return e
case e.isFalse:
if exp := toBooleanExpression(other); exp != nil {
return exp
}
}
return e.binaryOperation("OR", other, 16, true)
}
func (e expression) Xor(other interface{}) BooleanExpression {
return e.binaryOperation("XOR", other, 15, true)
}
func (e expression) Add(other interface{}) NumberExpression {
return e.binaryOperation("+", other, 7, false)
}
func (e expression) Sub(other interface{}) NumberExpression {
return e.binaryOperation("-", other, 7, false)
}
func (e expression) Mul(other interface{}) NumberExpression {
return e.binaryOperation("*", other, 6, false)
}
func (e expression) Div(other interface{}) NumberExpression {
return e.binaryOperation("/", other, 6, false)
}
func (e expression) IntDiv(other interface{}) NumberExpression {
return e.binaryOperation("DIV", other, 6, false)
}
func (e expression) Mod(other interface{}) NumberExpression {
return e.binaryOperation("%", other, 6, false)
}
func (e expression) Sum() NumberExpression {
return function("SUM", e)
}
func (e expression) Avg() NumberExpression {
return function("AVG", e)
}
func (e expression) Min() UnknownExpression {
return function("MIN", e)
}
func (e expression) Max() UnknownExpression {
return function("MAX", e)
}
func (e expression) Like(other interface{}) BooleanExpression {
return e.binaryOperation("LIKE", other, 11, true)
}
func (e expression) Concat(other interface{}) StringExpression {
return Concat(e, other)
}
func (e expression) Contains(substring string) BooleanExpression {
return function("LOCATE", substring, e).GreaterThan(0)
}
func (e expression) binaryOperation(operator string, value interface{}, priority priority, isBool bool) expression {
return expression{builder: func(scope scope) (string, error) {
leftSql, err := e.GetSQL(scope)
if err != nil {
return "", err
}
leftPriority := e.priority
rightSql, rightPriority, err := getSQL(scope, value)
if err != nil {
return "", err
}
shouldParenthesizeLeft := leftPriority > priority
shouldParenthesizeRight := rightPriority >= priority
var sb strings.Builder
sb.Grow(len(leftSql) + len(operator) + len(rightSql) + 6)
if shouldParenthesizeLeft {
sb.WriteByte('(')
}
sb.WriteString(leftSql)
if shouldParenthesizeLeft {
sb.WriteByte(')')
}
sb.WriteByte(' ')
sb.WriteString(operator)
sb.WriteByte(' ')
if shouldParenthesizeRight {
sb.WriteByte('(')
}
sb.WriteString(rightSql)
if shouldParenthesizeRight {
sb.WriteByte(')')
}
return sb.String(), nil
}, priority: priority, isBool: isBool}
}
func (e expression) prefixSuffixExpression(prefix string, suffix string, priority priority, isBool bool) expression {
if e.sql != "" {
return expression{
sql: prefix + e.sql + suffix,
priority: priority,
isBool: isBool,
}
}
return expression{
builder: func(scope scope) (string, error) {
exprSql, err := e.GetSQL(scope)
if err != nil {
return "", err
}
var sb strings.Builder
sb.Grow(len(prefix) + len(exprSql) + len(suffix) + 2)
sb.WriteString(prefix)
shouldParenthesize := e.priority > priority
if shouldParenthesize {
sb.WriteByte('(')
}
sb.WriteString(exprSql)
if shouldParenthesize {
sb.WriteByte(')')
}
sb.WriteString(suffix)
return sb.String(), nil
},
priority: priority,
isBool: isBool,
}
}
func (e expression) IsNull() BooleanExpression {
return e.prefixSuffixExpression("", " IS NULL", 11, true)
}
func (e expression) Not() BooleanExpression {
switch {
case e.isTrue:
return False()
case e.isFalse:
return True()
default:
return e.prefixSuffixExpression("NOT ", "", 13, true)
}
}
func (e expression) IsNotNull() BooleanExpression {
return e.prefixSuffixExpression("", " IS NOT NULL", 11, true)
}
func (e expression) IsTrue() BooleanExpression {
return e.prefixSuffixExpression("", " IS TRUE", 11, true)
}
func (e expression) IsNotTrue() BooleanExpression {
return e.prefixSuffixExpression("", " IS NOT TRUE", 11, true)
}
func (e expression) IsFalse() BooleanExpression {
return e.prefixSuffixExpression("", " IS FALSE", 11, true)
}
func (e expression) IsNotFalse() BooleanExpression {
return e.prefixSuffixExpression("", " IS NOT FALSE", 11, true)
}
func expandSliceValue(value reflect.Value) (result []interface{}) {
result = make([]interface{}, 0, 16)
kind := value.Kind()
switch kind {
case reflect.Array, reflect.Slice:
length := value.Len()
for i := 0; i < length; i++ {
result = append(result, expandSliceValue(value.Index(i))...)
}
case reflect.Interface, reflect.Ptr:
result = append(result, expandSliceValue(value.Elem())...)
default:
result = append(result, value.Interface())
}
return
}
func expandSliceValues(values []interface{}) (result []interface{}) {
result = make([]interface{}, 0, 16)
for _, v := range values {
value := reflect.ValueOf(v)
result = append(result, expandSliceValue(value)...)
}
return
}
func (e expression) In(values ...interface{}) BooleanExpression {
values = expandSliceValues(values)
if len(values) == 0 {
return False()
}
joiner := func(exprSql, valuesSql string) string { return exprSql + " IN (" + valuesSql + ")" }
builder := e.getBuilder(e.Equals, joiner, values...)
return expression{builder: builder, priority: 11}
}
func (e expression) NotIn(values ...interface{}) BooleanExpression {
values = expandSliceValues(values)
if len(values) == 0 {
return True()
}
joiner := func(exprSql, valuesSql string) string { return exprSql + " NOT IN (" + valuesSql + ")" }
builder := e.getBuilder(e.NotEquals, joiner, values...)
return expression{builder: builder, priority: 11}
}
type joinerFunc = func(exprSql, valuesSql string) string
type booleanFunc = func(other interface{}) BooleanExpression
type builderFunc = func(scope scope) (string, error)
func (e expression) getBuilder(single booleanFunc, joiner joinerFunc, values ...interface{}) builderFunc {
return func(scope scope) (string, error) {
var valuesSql string
var err error
if len(values) == 1 {
value := values[0]
if selectStatus, ok := value.(toSelectFinal); ok {
// IN subquery
valuesSql, err = selectStatus.GetSQL()
if err != nil {
return "", err
}
} else {
// IN a single value
return single(value).GetSQL(scope)
}
} else {
// IN a list
valuesSql, err = commaValues(scope, values)
if err != nil {
return "", err
}
}
exprSql, err := e.GetSQL(scope)
if err != nil {
return "", err
}
return joiner(exprSql, valuesSql), nil
}
}
func (e expression) Between(min interface{}, max interface{}) BooleanExpression {
return e.buildBetween(" BETWEEN ", min, max)
}
func (e expression) NotBetween(min interface{}, max interface{}) BooleanExpression {
return e.buildBetween(" NOT BETWEEN ", min, max)
}
func (e expression) buildBetween(operator string, min interface{}, max interface{}) BooleanExpression {
return expression{builder: func(scope scope) (string, error) {
exprSql, err := e.GetSQL(scope)
if err != nil {
return "", err
}
minSql, _, err := getSQL(scope, min)
if err != nil {
return "", err
}
maxSql, _, err := getSQL(scope, max)
if err != nil {
return "", err
}
return exprSql + operator + minSql + " AND " + maxSql, nil
}, priority: 12}
}
func (e expression) getOperatorPriority() priority {
return e.priority
}
func (e expression) Desc() OrderBy {
return orderBy{by: e, desc: true}
}