forked from square/squalor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.go
1087 lines (963 loc) · 28.6 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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Square Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package squalor
import (
"fmt"
"regexp"
"strings"
"time"
)
// DeleteBuilder aids the construction of DELETE statements, providing
// methods for setting the clauses of a delete statement.
type DeleteBuilder struct {
Delete
}
func makeDeleteBuilder(table abstractTable, tables ...*Table) *DeleteBuilder {
var tableNames TableNames
for _, table := range tables {
tableNames = append(tableNames, &TableName{Name: table.Name})
}
b := &DeleteBuilder{}
b.Delete.Table = table
b.Delete.TableNames = tableNames
return b
}
// Limit sets the LIMIT clause for the statement, replacing any
// existing limit clause.
func (b *DeleteBuilder) Limit(count interface{}) *DeleteBuilder {
if b.Delete.Limit == nil {
b.Delete.Limit = &Limit{}
}
b.Delete.Limit.Rowcount = makeValExpr(count)
return b
}
// OrderBy sets the ORDER BY clause for the statement, replacing any
// existing order by clause.
func (b *DeleteBuilder) OrderBy(exprs ...interface{}) *DeleteBuilder {
b.Delete.OrderBy = makeOrderBy(exprs...)
return b
}
// Where sets the WHERE clause for the statement, replacing any
// existing where clause.
func (b *DeleteBuilder) Where(expr BoolExpr) *DeleteBuilder {
b.Delete.Where = &Where{
Type: astWhere,
Expr: unwrapBoolExpr(expr),
}
return b
}
// Comments sets comments for the statement, replacing any
// existing comments.
func (b *DeleteBuilder) Comments(comments []string) *DeleteBuilder {
b.Delete.Comments = comments
return b
}
// abstractTable represents either a concrete table or the result of
// joining two tables.
type abstractTable interface {
tableExpr() TableExpr
tableExists(name string) bool
column(name string) *ColName
columnCount(name string) int
}
// The Selectable interface is a type for structs that provide the Select function.
// The types that implement this interface are Table and JoinBuilder.
// This interface is not used by Squalor itself, it is provided so that users can create functions
// that can accept either of these two types.
type Selectable interface {
Select(exprs ...interface{}) *SelectBuilder
}
var _ Selectable = &JoinBuilder{}
var _ Selectable = &Table{}
// The Deletable interface is a type for structs that provide the Delete function.
// The types that implement this interface are Table and JoinBuilder.
// This interface is not used by Squalor itself, it is provided so that users can create functions
// that can accept either of these two types.
type Deletable interface {
Delete(table ...*Table) *DeleteBuilder
}
var _ Deletable = &JoinBuilder{}
var _ Deletable = &Table{}
// JoinBuilder aids the construction of JOIN expressions, providing
// methods for specifying the join condition.
type JoinBuilder struct {
JoinTableExpr
leftTable abstractTable
rightTable abstractTable
}
func makeJoinBuilder(join string, left, right abstractTable) *JoinBuilder {
j := &JoinBuilder{}
j.Join = join
j.leftTable = left
j.LeftExpr = left.tableExpr()
j.rightTable = right
j.RightExpr = right.tableExpr()
return j
}
// InnerJoin creates a INNER JOIN statement builder
func (b *JoinBuilder) InnerJoin(other *Table) *JoinBuilder {
return makeJoinBuilder("INNER JOIN", b, other)
}
// LeftJoin creates a LEFT JOIN statement builder.
func (b *JoinBuilder) LeftJoin(other *Table) *JoinBuilder {
return makeJoinBuilder("LEFT JOIN", b, other)
}
// RightJoin creates a RIGHT JOIN statement builder.
func (b *JoinBuilder) RightJoin(other *Table) *JoinBuilder {
return makeJoinBuilder("RIGHT JOIN", b, other)
}
// Select creates a SELECT statement builder.
func (b *JoinBuilder) Select(exprs ...interface{}) *SelectBuilder {
return makeSelectBuilder(b, exprs...)
}
// Delete creates a DELETE statement builder.
func (b *JoinBuilder) Delete(tables ...*Table) *DeleteBuilder {
return makeDeleteBuilder(b, tables...)
}
// On sets an ON join condition for the expression, replacing any
// existing join condition.
func (b *JoinBuilder) On(expr BoolExpr) *JoinBuilder {
b.Cond = &OnJoinCond{Expr: unwrapBoolExpr(expr)}
return b
}
// Using sets a USING join condition for the expression, replacing any
// existing join condition. The columns must exist in both the left
// and right sides of the join expression.
func (b *JoinBuilder) Using(cols ...interface{}) *JoinBuilder {
var vals Columns
for _, c := range cols {
var name string
switch t := c.(type) {
case string:
name = t
case ValExprBuilder:
if n, ok := t.ValExpr.(*ColName); ok {
name = n.Name
break
}
}
var v ValExpr
if len(name) == 0 {
v = makeErrVal("unsupported type %T: %v", c, c)
} else if b.leftTable.column(name) == nil ||
b.rightTable.column(name) == nil {
v = makeErrVal("invalid join column: %s", name)
} else {
v = &ColName{Name: name}
}
vals = append(vals, &NonStarExpr{Expr: v})
}
b.Cond = &UsingJoinCond{Cols: vals}
return b
}
func (b *JoinBuilder) tableExpr() TableExpr {
return &b.JoinTableExpr
}
func (b *JoinBuilder) tableExists(name string) bool {
return b.leftTable.tableExists(name) || b.rightTable.tableExists(name)
}
func (b *JoinBuilder) column(name string) *ColName {
if col := b.leftTable.column(name); col != nil {
return col
}
return b.rightTable.column(name)
}
func (b *JoinBuilder) columnCount(name string) int {
return b.leftTable.columnCount(name) + b.rightTable.columnCount(name)
}
// InsertBuilder aids the construction of INSERT statements, providing
// methods for adding rows to the statement.
type InsertBuilder struct {
Insert
table *Table
}
func makeInsertBuilder(table *Table, kind string, cols ...interface{}) *InsertBuilder {
b := &InsertBuilder{
table: table,
}
b.Insert.Kind = kind
b.Insert.Table = &TableName{
Name: table.Name,
}
for _, c := range cols {
var name string
switch t := c.(type) {
case string:
name = t
case ValExprBuilder:
if n, ok := t.ValExpr.(*ColName); ok {
name = n.Name
break
}
}
var v ValExpr
if len(name) == 0 {
v = makeErrVal("unsupported type %T: %v", c, c)
} else if table.column(name) == nil {
v = makeErrVal("invalid insert column: %s", name)
} else {
v = &ColName{Name: name}
}
b.Insert.Columns = append(b.Insert.Columns, &NonStarExpr{Expr: v})
}
return b
}
// Add appends a single row of values to the statement.
func (b *InsertBuilder) Add(vals ...interface{}) *InsertBuilder {
var rows Values
if b.Insert.Rows != nil {
rows = b.Insert.Rows.(Values)
}
b.Insert.Rows = append(rows, makeValTuple(vals))
return b
}
// AddRows appends multiple rows of values to the statement.
func (b *InsertBuilder) AddRows(rows Values) *InsertBuilder {
if b.Insert.Rows == nil {
b.Insert.Rows = rows
} else {
b.Insert.Rows = append(b.Insert.Rows.(Values), rows...)
}
return b
}
// Comments sets comments for the statement, replacing any
// existing comments.
func (b *InsertBuilder) Comments(comments []string) *InsertBuilder {
b.Insert.Comments = comments
return b
}
// OnDupKeyUpdate specifies an ON DUPLICATE KEY UPDATE expression to
// be performed when a duplicate primary key is encountered during
// insertion. The specified column must exist within the table being
// inserted into.
func (b *InsertBuilder) OnDupKeyUpdate(col interface{}, val interface{}) *InsertBuilder {
b.Insert.OnDup = append(b.Insert.OnDup, makeUpdateExpr(b.table, col, val))
return b
}
// OnDupKeyUpdateColumn specifies on ON DUPLICATE KEY UPDATE
// expression to be performed when a duplicate primary key is
// encountered during insertion. The specified column must exist
// within the table being inserted into. The value to use for updating
// is taken from the corresponding column value in the row being
// inserted.
func (b *InsertBuilder) OnDupKeyUpdateColumn(col interface{}) *InsertBuilder {
colName := getColName(b.table, col)
val := &FuncExpr{Name: "VALUES", Exprs: []SelectExpr{&NonStarExpr{Expr: colName}}}
return b.OnDupKeyUpdate(col, val)
}
// ReplaceBuilder aids the construction of REPLACE expressions,
// providing methods for adding rows to the statement.
type ReplaceBuilder struct {
Insert
table *Table
}
func makeReplaceBuilder(table *Table, cols ...interface{}) *ReplaceBuilder {
b := &ReplaceBuilder{
table: table,
}
b.Insert.Kind = "REPLACE"
b.Insert.Table = &TableName{
Name: table.Name,
}
for _, c := range cols {
var name string
switch t := c.(type) {
case string:
name = t
case ValExprBuilder:
if n, ok := t.ValExpr.(*ColName); ok {
name = n.Name
break
}
}
var v ValExpr
if len(name) == 0 {
v = makeErrVal("unsupported type %T: %v", c, c)
} else if table.column(name) == nil {
v = makeErrVal("invalid replace column: %s", name)
} else {
v = &ColName{Name: name}
}
b.Insert.Columns = append(b.Insert.Columns, &NonStarExpr{Expr: v})
}
return b
}
// Add appends a single row of values to the statement.
func (b *ReplaceBuilder) Add(vals ...interface{}) *ReplaceBuilder {
var rows Values
if b.Insert.Rows != nil {
rows = b.Insert.Rows.(Values)
}
b.Insert.Rows = append(rows, makeValTuple(vals))
return b
}
// AddRows appends multiple rows of values to the statement.
func (b *ReplaceBuilder) AddRows(rows Values) *ReplaceBuilder {
if b.Insert.Rows == nil {
b.Insert.Rows = rows
} else {
b.Insert.Rows = append(b.Insert.Rows.(Values), rows...)
}
return b
}
// Comments sets comments for the statement, replacing any
// existing comments.
func (b *ReplaceBuilder) Comments(comments []string) *ReplaceBuilder {
b.Insert.Comments = comments
return b
}
// SelectBuilder aids the construction of SELECT statements, providing
// methods for setting the clauses of the select statement.
type SelectBuilder struct {
Select
table abstractTable
}
func makeSelectBuilder(table abstractTable, exprs ...interface{}) *SelectBuilder {
b := &SelectBuilder{table: table}
for _, e := range exprs {
b.addSelectExpr(e)
}
b.From = append(b.From, table.tableExpr())
return b
}
func (b *SelectBuilder) addSelectExpr(expr interface{}) {
var s SelectExpr
switch v := expr.(type) {
case StrVal:
s = b.stringToSelectExpr(string(v))
case string:
s = b.stringToSelectExpr(v)
case ValExprBuilder:
switch t := v.ValExpr.(type) {
case StrVal:
s = b.stringToSelectExpr(string(t))
case ValTuple:
for _, q := range t.Exprs {
b.addSelectExpr(q)
}
return
default:
s = &NonStarExpr{Expr: v.ValExpr}
}
case Expr:
s = &NonStarExpr{Expr: v}
case *NonStarExpr:
s = v
case SelectExpr:
s = v
default:
s = &NonStarExpr{Expr: makeValExpr(expr)}
}
b.Exprs = append(b.Exprs, s)
}
func (b *SelectBuilder) stringToSelectExpr(v string) SelectExpr {
if v == "*" {
return &StarExpr{}
}
parts := strings.Split(v, ".")
if len(parts) > 2 {
return &NonStarExpr{
Expr: makeErrVal("invalid select expression: %s", v),
}
}
if len(parts) == 2 {
if !b.table.tableExists(parts[0]) {
return &NonStarExpr{
Expr: makeErrVal("unknown table: %s", parts[0]),
}
}
if parts[1] == "*" {
return &StarExpr{TableName: parts[0]}
}
}
if len(parts) == 1 && b.table.columnCount(v) > 1 {
return &NonStarExpr{
Expr: makeErrVal("ambiguous column: %s", v),
}
}
// Note that column() will internally split v into table name and
// column name.
if col := b.table.column(v); col != nil {
return &NonStarExpr{Expr: col}
}
return &NonStarExpr{
Expr: makeErrVal("unknown column: %s", v),
}
}
// Distinct sets the DISTINCT tag on the statement causing duplicate
// row results to be removed.
func (b *SelectBuilder) Distinct() *SelectBuilder {
b.Select.Distinct = "DISTINCT "
return b
}
// ForUpdate sets the FOR UPDATE tag on the statement causing the
// result rows to be locked (dependent on the specific MySQL storage
// engine).
func (b *SelectBuilder) ForUpdate() *SelectBuilder {
b.Select.Lock = " FOR UPDATE"
return b
}
// WithSharedLock sets the LOCK IN SHARE MODE tag on the statement
// causing the result rows to be read locked (dependent on the
// specific MySQL storage engine).
func (b *SelectBuilder) WithSharedLock() *SelectBuilder {
b.Select.Lock = " LOCK IN SHARE MODE"
return b
}
// Where sets the WHERE clause for the statement, replacing any
// existing where clause.
func (b *SelectBuilder) Where(expr BoolExpr) *SelectBuilder {
b.Select.Where = &Where{
Type: astWhere,
Expr: unwrapBoolExpr(expr),
}
return b
}
// Comments sets comments for the statement, replacing any
// existing comments.
func (b *SelectBuilder) Comments(comments []string) *SelectBuilder {
b.Select.Comments = comments
return b
}
// Having sets the HAVING clause for the statement, replacing any
// existing having clause.
func (b *SelectBuilder) Having(expr BoolExpr) *SelectBuilder {
b.Select.Having = &Where{
Type: astHaving,
Expr: unwrapBoolExpr(expr),
}
return b
}
// GroupBy sets the GROUP BY clause for the statement, replacing any
// existing group by clause.
func (b *SelectBuilder) GroupBy(vals ...ValExpr) *SelectBuilder {
for i := range vals {
vals[i] = unwrapValExpr(vals[i])
}
b.Select.GroupBy = GroupBy(vals)
return b
}
// OrderBy sets the ORDER BY clause for the statement, replacing any
// existing order by clause.
func (b *SelectBuilder) OrderBy(exprs ...interface{}) *SelectBuilder {
b.Select.OrderBy = makeOrderBy(exprs...)
return b
}
// Limit sets the LIMIT clause for the statement, replacing any
// existing limit clause.
func (b *SelectBuilder) Limit(count interface{}) *SelectBuilder {
if b.Select.Limit == nil {
b.Select.Limit = &Limit{}
}
b.Select.Limit.Rowcount = makeValExpr(count)
return b
}
// Offset sets the OFFSET clause for the statement. It is an error to
// set the offset before setting the limit.
func (b *SelectBuilder) Offset(offset interface{}) *SelectBuilder {
if b.Select.Limit == nil {
panic("offset without limit")
}
b.Select.Limit.Offset = makeValExpr(offset)
return b
}
// UpdateBuilder aids the construction of UPDATE statements, providing
// methods for specifying which columns are to be updated and setting
// other clauses of the update statement.
type UpdateBuilder struct {
Update
table *Table
}
func makeUpdateBuilder(table *Table) *UpdateBuilder {
b := &UpdateBuilder{table: table}
b.Update.Table = &TableName{
Name: table.Name,
}
return b
}
// Limit sets the limit clause for the statement, replacing any
// existing limit clause.
func (b *UpdateBuilder) Limit(count interface{}) *UpdateBuilder {
if b.Update.Limit == nil {
b.Update.Limit = &Limit{}
}
b.Update.Limit.Rowcount = makeValExpr(count)
return b
}
// OrderBy sets the order by clause for the statement, replacing any
// existing order by clause.
func (b *UpdateBuilder) OrderBy(exprs ...interface{}) *UpdateBuilder {
b.Update.OrderBy = makeOrderBy(exprs...)
return b
}
// Set appends a Set expression to the statement. The specified column
// must exist within the table being updated.
func (b *UpdateBuilder) Set(col interface{}, val interface{}) *UpdateBuilder {
b.Update.Exprs = append(b.Update.Exprs, makeUpdateExpr(b.table, col, val))
return b
}
// Where sets the where clause for the statement, replacing any
// existing where clause.
func (b *UpdateBuilder) Where(expr BoolExpr) *UpdateBuilder {
b.Update.Where = &Where{
Type: astWhere,
Expr: unwrapBoolExpr(expr),
}
return b
}
// Comments sets comments for the statement, replacing any
// existing comments.
func (b *UpdateBuilder) Comments(comments []string) *UpdateBuilder {
b.Update.Comments = comments
return b
}
// ValExprBuilder aids the construction of boolean expressions from
// values such as "foo == 1" or "bar IN ('a', 'b', 'c')" and value
// expressions such as "count + 1".
type ValExprBuilder struct {
ValExpr
}
func makeValExpr(arg interface{}) ValExpr {
switch t := arg.(type) {
case ValExprBuilder:
return t.ValExpr
case ValExpr:
return t
}
return RawVal{arg}
}
func unwrapValExpr(expr ValExpr) ValExpr {
if b, ok := expr.(ValExprBuilder); ok {
return b.ValExpr
}
return expr
}
func (b ValExprBuilder) makeComparisonExpr(op string, expr ValExpr) BoolExprBuilder {
return BoolExprBuilder{
&ComparisonExpr{
Operator: op,
Left: b.ValExpr,
Right: expr,
}}
}
// As creates an AS (alias) expression.
func (b ValExprBuilder) As(s string) SelectExpr {
if !isValidIdentifier(s) {
return &NonStarExpr{Expr: makeErrVal("invalid AS identifier: %s", s)}
}
return &NonStarExpr{Expr: b.ValExpr, As: s}
}
// Eq creates a = comparison expression.
func (b ValExprBuilder) Eq(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astEQ, makeValExpr(val))
}
// Neq creates a != comparison expression.
func (b ValExprBuilder) Neq(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astNE, makeValExpr(val))
}
// NullSafeEq creates a <=> comparison expression that is safe for use
// when the either the left or right value of the expression may be
// NULL. The null safe equal operator performs an equality comparison
// like the = operator, but returns 1 rather than NULL if both
// operands are NULL, and 0 rather than NULL if one operand is NULL.
func (b ValExprBuilder) NullSafeEq(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astNSE, makeValExpr(val))
}
// Lt creates a < comparison expression.
func (b ValExprBuilder) Lt(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astLT, makeValExpr(val))
}
// Lte creates a <= comparison expression.
func (b ValExprBuilder) Lte(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astLE, makeValExpr(val))
}
// Gt creates a > comparison expression.
func (b ValExprBuilder) Gt(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astGT, makeValExpr(val))
}
// Gte creates a >= comparison expression.
func (b ValExprBuilder) Gte(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astGE, makeValExpr(val))
}
// In creates an IN expression from a list of values.
func (b ValExprBuilder) In(list ...interface{}) BoolExprBuilder {
return b.InTuple(makeValTuple(list))
}
// InTuple creates an IN expression from a tuple.
func (b ValExprBuilder) InTuple(tuple Tuple) BoolExprBuilder {
if valTuple, ok := tuple.(ValTuple); ok {
if len(valTuple.Exprs) == 0 {
return b.makeComparisonExpr(astIn, makeErrVal("empty list"))
}
}
return b.makeComparisonExpr(astIn, tuple)
}
// NotIn creates a NOT IN expression from a list of values.
func (b ValExprBuilder) NotIn(list ...interface{}) BoolExprBuilder {
return b.NotInTuple(makeValTuple(list))
}
// NotInTuple creates a NOT IN expression from a tuple.
func (b ValExprBuilder) NotInTuple(tuple Tuple) BoolExprBuilder {
if valTuple, ok := tuple.(ValTuple); ok {
if len(valTuple.Exprs) == 0 {
return b.makeComparisonExpr(astNotIn, makeErrVal("empty list"))
}
}
return b.makeComparisonExpr(astNotIn, tuple)
}
// Like creates a LIKE expression.
func (b ValExprBuilder) Like(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astLike, makeValExpr(val))
}
// NotLike creates a NOT LIKE expression.
func (b ValExprBuilder) NotLike(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astNotLike, makeValExpr(val))
}
// RegExp creates a REGEXP expression.
func (b ValExprBuilder) RegExp(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astRegExp, makeValExpr(val))
}
// NotRegExp creates a NOT REGEXP expression.
func (b ValExprBuilder) NotRegExp(val interface{}) BoolExprBuilder {
return b.makeComparisonExpr(astNotRegExp, makeValExpr(val))
}
func (b ValExprBuilder) makeRangeCond(
op string, from interface{}, to interface{}) BoolExprBuilder {
return BoolExprBuilder{
&RangeCond{
Operator: op,
Left: b.ValExpr,
From: makeValExpr(from),
To: makeValExpr(to),
}}
}
// Between creates a BETWEEN expression.
func (b ValExprBuilder) Between(from interface{}, to interface{}) BoolExprBuilder {
return b.makeRangeCond(astBetween, from, to)
}
// NotBetween creates a NOT BETWEEN expression.
func (b ValExprBuilder) NotBetween(from interface{}, to interface{}) BoolExprBuilder {
return b.makeRangeCond(astNotBetween, from, to)
}
func (b ValExprBuilder) makeNullCheck(op string) BoolExprBuilder {
return BoolExprBuilder{
&NullCheck{
Operator: op,
Expr: b.ValExpr,
}}
}
// IsNull creates an IS NULL expression.
func (b ValExprBuilder) IsNull() BoolExprBuilder {
return b.makeNullCheck(astIsNull)
}
// IsNotNull creates an IS NOT NULL expression.
func (b ValExprBuilder) IsNotNull() BoolExprBuilder {
return b.makeNullCheck(astIsNotNull)
}
// Ascending creates an ASC order expression.
func (b ValExprBuilder) Ascending() *Order {
return &Order{
Expr: b.ValExpr,
Direction: " ASC",
}
}
// Descending creates a DESC order expression.
func (b ValExprBuilder) Descending() *Order {
return &Order{
Expr: b.ValExpr,
Direction: " DESC",
}
}
func (b ValExprBuilder) makeFunc(name string, distinct bool) ValExprBuilder {
if !isValidIdentifier(name) {
return ValExprBuilder{makeErrVal("invalid FUNC identifier: %s", name)}
}
var exprs SelectExprs
switch t := b.ValExpr.(type) {
case ValTuple:
for _, e := range t.Exprs {
exprs = append(exprs, &NonStarExpr{Expr: unwrapValExpr(e)})
}
default:
exprs = SelectExprs([]SelectExpr{&NonStarExpr{Expr: b.ValExpr}})
}
return ValExprBuilder{
&FuncExpr{
Name: name,
Distinct: distinct,
Exprs: exprs,
}}
}
// Count creates a COUNT(...) expression.
func (b ValExprBuilder) Count() ValExprBuilder {
return b.makeFunc("COUNT", false)
}
// CountDistinct creates a COUNT(DISTINCT ...) expression.
func (b ValExprBuilder) CountDistinct() ValExprBuilder {
return b.makeFunc("COUNT", true)
}
// Max creates a MAX(...) expression.
func (b ValExprBuilder) Max() ValExprBuilder {
return b.makeFunc("MAX", false)
}
// Min creates a MIN(...) expression.
func (b ValExprBuilder) Min() ValExprBuilder {
return b.makeFunc("MIN", false)
}
// Func creates a function expression where name is the name of the
// function. The function will be invoked as name(val).
func (b ValExprBuilder) Func(name string) ValExprBuilder {
return b.makeFunc(name, false)
}
// FuncDistinct creates a function expression where name is the name
// of the function. The function will be invoked as name(DISTINCT val).
func (b ValExprBuilder) FuncDistinct(name string) ValExprBuilder {
return b.makeFunc(name, true)
}
func (b ValExprBuilder) makeBinaryExpr(op byte, expr interface{}) ValExprBuilder {
left := b.ValExpr
switch left.(type) {
case *BinaryExpr:
left = makeValTuple([]interface{}{left})
}
return ValExprBuilder{
&BinaryExpr{
Operator: op,
Left: left,
Right: makeValExpr(expr),
}}
}
// BitAnd creates a & expression.
func (b ValExprBuilder) BitAnd(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('&', expr)
}
// BitOr creates a | expression.
func (b ValExprBuilder) BitOr(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('|', expr)
}
// BitXor creates a ^ expression.
func (b ValExprBuilder) BitXor(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('^', expr)
}
// Plus creates a + expression.
func (b ValExprBuilder) Plus(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('+', expr)
}
// Minus creates a - expression.
func (b ValExprBuilder) Minus(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('-', expr)
}
// Mul creates a * expression.
func (b ValExprBuilder) Mul(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('*', expr)
}
// Div creates a / expression.
func (b ValExprBuilder) Div(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('/', expr)
}
// Mod creates a % expression.
func (b ValExprBuilder) Mod(expr interface{}) ValExprBuilder {
return b.makeBinaryExpr('%', expr)
}
// BoolExprBuilder aids the construction of boolean expressions from
// other boolean expressions.
type BoolExprBuilder struct {
BoolExpr
}
func unwrapBoolExpr(expr BoolExpr) BoolExpr {
if b, ok := expr.(BoolExprBuilder); ok {
return b.BoolExpr
}
return expr
}
// And creates an AND expression.
func (e BoolExprBuilder) And(expr BoolExpr) BoolExprBuilder {
var conditions []BoolExpr
if andExpr, ok := e.BoolExpr.(*AndExpr); ok {
conditions = append(conditions, andExpr.Exprs...)
} else {
conditions = append(conditions, e.BoolExpr)
}
unwrapped := unwrapBoolExpr(expr)
if andExpr, ok := unwrapped.(*AndExpr); ok {
conditions = append(conditions, andExpr.Exprs...)
} else {
conditions = append(conditions, unwrapped)
}
return BoolExprBuilder{
&AndExpr{
Op: astAndExpr,
Exprs: conditions,
}}
}
// Or creates an OR expression.
func (e BoolExprBuilder) Or(expr BoolExpr) BoolExprBuilder {
var conditions []BoolExpr
if orExpr, ok := e.BoolExpr.(*OrExpr); ok {
conditions = append(conditions, orExpr.Exprs...)
} else {
conditions = append(conditions, e.BoolExpr)
}
unwrapped := unwrapBoolExpr(expr)
if orExpr, ok := unwrapped.(*OrExpr); ok {
conditions = append(conditions, orExpr.Exprs...)
} else {
conditions = append(conditions, unwrapped)
}
return BoolExprBuilder{
&OrExpr{
Op: astOrExpr,
Exprs: conditions,
}}
}
// Not creates a NOT expression.
func (e BoolExprBuilder) Not() BoolExprBuilder {
return BoolExprBuilder{
&NotExpr{
Op: astNotExpr,
Expr: &ParenBoolExpr{Expr: e.BoolExpr},
}}
}
func makeValTuple(list []interface{}) ValTuple {
var result ValExprs
for _, arg := range list {
// Handle various types of slices in order to make it easier to
// pass concrete slice types to In() and NotIn().
switch t := arg.(type) {
case []int:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []int16:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []int32:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []int64:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []uint:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []uint16:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []uint32:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []uint64:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []float32:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []float64:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case []string:
for _, v := range t {
result = append(result, makeValExpr(v))
}
case [][]byte:
for _, v := range t {
result = append(result, makeValExpr(v))