forked from doug-martin/goqu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expressions.go
1333 lines (1175 loc) · 40 KB
/
expressions.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
package goqu
import (
"fmt"
"reflect"
"regexp"
"sort"
"strings"
)
type (
//Alternative to writing map[string]interface{}. Can be used for Inserts, Updates or Deletes
Record map[string]interface{}
//Parent of all expression types
Expression interface {
Clone() Expression
Expression() Expression
}
//An Expression that generates its own sql (e.g Dataset)
SqlExpression interface {
Expression
ToSql() (string, []interface{}, error)
}
)
type (
ExpressionListType int
//A list of expressions that should be joined together
// And(I("a").Eq(10), I("b").Eq(11)) //(("a" = 10) AND ("b" = 11))
// Or(I("a").Eq(10), I("b").Eq(11)) //(("a" = 10) OR ("b" = 11))
ExpressionList interface {
Expression
//Returns type (e.g. OR, AND)
Type() ExpressionListType
//Slice of expressions that should be joined togehter
Expressions() []Expression
//Returns a new expression list with the given expressions appended to the current Expressions list
Append(...Expression) ExpressionList
}
expressionList struct {
operator ExpressionListType
expressions []Expression
}
)
const (
AND_TYPE ExpressionListType = iota
OR_TYPE
)
func getExMapKeys(ex map[string]interface{}) []string {
var keys []string
for key, _ := range ex {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func mapToExpressionList(ex map[string]interface{}, eType ExpressionListType) (ExpressionList, error) {
keys := getExMapKeys(ex)
ret := make([]Expression, len(keys))
for i, key := range keys {
lhs := I(key)
rhs := ex[key]
var exp Expression
if op, ok := rhs.(Op); ok {
opKeys := getExMapKeys(op)
ors := make([]Expression, len(opKeys))
for j, opKey := range opKeys {
var ored Expression
switch strings.ToLower(opKey) {
case "eq":
ored = lhs.Eq(op[opKey])
case "neq":
ored = lhs.Neq(op[opKey])
case "is":
ored = lhs.Is(op[opKey])
case "isnot":
ored = lhs.IsNot(op[opKey])
case "gt":
ored = lhs.Gt(op[opKey])
case "gte":
ored = lhs.Gte(op[opKey])
case "lt":
ored = lhs.Lt(op[opKey])
case "lte":
ored = lhs.Lte(op[opKey])
case "in":
ored = lhs.In(op[opKey])
case "notin":
ored = lhs.NotIn(op[opKey])
case "like":
ored = lhs.Like(op[opKey])
case "notlike":
ored = lhs.NotLike(op[opKey])
case "ilike":
ored = lhs.ILike(op[opKey])
case "notilike":
ored = lhs.NotILike(op[opKey])
default:
return nil, NewGoquError("Unsupported expression type %s", op)
}
ors[j] = ored
}
exp = Or(ors...)
} else {
exp = lhs.Eq(rhs)
}
ret[i] = exp
}
if eType == OR_TYPE {
return Or(ret...), nil
}
return And(ret...), nil
}
// A list of expressions that should be ORed together
// Or(I("a").Eq(10), I("b").Eq(11)) //(("a" = 10) OR ("b" = 11))
func Or(expressions ...Expression) expressionList {
return expressionList{operator: OR_TYPE, expressions: expressions}
}
// A list of expressions that should be ANDed together
// And(I("a").Eq(10), I("b").Eq(11)) //(("a" = 10) AND ("b" = 11))
func And(expressions ...Expression) expressionList {
return expressionList{operator: AND_TYPE, expressions: expressions}
}
func (me expressionList) Clone() Expression {
newExps := make([]Expression, len(me.expressions))
for i, exp := range me.expressions {
newExps[i] = exp.Clone()
}
return expressionList{operator: me.operator, expressions: newExps}
}
func (me expressionList) Expression() Expression {
return me
}
func (me expressionList) Type() ExpressionListType {
return me.operator
}
func (me expressionList) Expressions() []Expression {
return me.expressions
}
func (me expressionList) Append(expressions ...Expression) ExpressionList {
ret := new(expressionList)
ret.operator = me.operator
exps := me.expressions
for _, exp := range expressions {
exps = append(exps, exp)
}
ret.expressions = exps
return ret
}
type (
//A map of expressions to be ANDed together where the keys are string that will be used as Identifiers and values will be used in a boolean operation.
//The Ex map can be used in tandem with Op map to create more complex expression such as LIKE, GT, LT... See examples.
Ex map[string]interface{}
//A map of expressions to be ORed together where the keys are string that will be used as Identifiers and values will be used in a boolean operation.
//The Ex map can be used in tandem with Op map to create more complex expression such as LIKE, GT, LT... See examples.
ExOr map[string]interface{}
//Used in tandem with the Ex map to create complex comparisons such as LIKE, GT, LT... See examples
Op map[string]interface{}
)
func (me Ex) Expression() Expression {
return me
}
func (me Ex) Clone() Expression {
ret := Ex{}
for key, val := range me {
ret[key] = val
}
return ret
}
func (me Ex) ToExpressions() (ExpressionList, error) {
return mapToExpressionList(me, AND_TYPE)
}
func (me ExOr) Expression() Expression {
return me
}
func (me ExOr) Clone() Expression {
ret := Ex{}
for key, val := range me {
ret[key] = val
}
return ret
}
func (me ExOr) ToExpressions() (ExpressionList, error) {
return mapToExpressionList(me, OR_TYPE)
}
type (
//A list of columns. Typically used internally by Select, Order, From
ColumnList interface {
Expression
//Returns the list of columns
Columns() []Expression
//Returns a new ColumnList with the columns appended.
Append(...Expression) ColumnList
}
columnList struct {
columns []Expression
}
)
func emptyCols() ColumnList {
return columnList{}
}
func cols(vals ...interface{}) ColumnList {
var cols []Expression
for _, val := range vals {
switch val.(type) {
case string:
cols = append(cols, I(val.(string)))
case Expression:
cols = append(cols, val.(Expression))
default:
_, valKind, _ := getTypeInfo(val, reflect.Indirect(reflect.ValueOf(val)))
if valKind == reflect.Struct {
cm, err := getColumnMap(val)
if err != nil {
panic(err.Error())
}
var structCols []string
for key, col := range cm {
if !col.Transient {
structCols = append(structCols, key)
}
}
sort.Strings(structCols)
for _, col := range structCols {
cols = append(cols, I(col))
}
} else {
panic(fmt.Sprintf("Cannot created expression from %+v", val))
}
}
}
return columnList{columns: cols}
}
func orderList(vals ...OrderedExpression) ColumnList {
exps := make([]Expression, len(vals))
for i, col := range vals {
exps[i] = col.Expression()
}
return columnList{columns: exps}
}
func (me columnList) Clone() Expression {
newExps := make([]Expression, len(me.columns))
for i, exp := range me.columns {
newExps[i] = exp.Clone()
}
return columnList{columns: newExps}
}
func (me columnList) Expression() Expression {
return me
}
func (me columnList) Columns() []Expression {
return me.columns
}
func (me columnList) Append(cols ...Expression) ColumnList {
ret := new(columnList)
exps := append(ret.columns, me.columns...)
for _, exp := range cols {
exps = append(exps, exp)
}
ret.columns = exps
return ret
}
type (
JoinType int
JoinCondition int
//Parent type for join expressions
joinExpression interface {
Expression
JoinCondition() JoinCondition
}
//Container for all joins within a dataset
JoiningClause struct {
//The JoinType
JoinType JoinType
//If this is a conditioned join (e.g. NATURAL, or INNER)
IsConditioned bool
//The table expressions (e.g. LEFT JOIN "my_table", ON (....))
Table Expression
//The condition to join (e.g. USING("a", "b"), ON("my_table"."fkey" = "other_table"."id")
Condition joinExpression
}
JoiningClauses []JoiningClause
joinClause struct {
joinCondition JoinCondition
}
)
const (
INNER_JOIN JoinType = iota
FULL_OUTER_JOIN
RIGHT_OUTER_JOIN
LEFT_OUTER_JOIN
FULL_JOIN
RIGHT_JOIN
LEFT_JOIN
NATURAL_JOIN
NATURAL_LEFT_JOIN
NATURAL_RIGHT_JOIN
NATURAL_FULL_JOIN
CROSS_JOIN
USING_COND JoinCondition = iota
ON_COND
)
func (me JoiningClause) Clone() JoiningClause {
return JoiningClause{JoinType: me.JoinType, IsConditioned: me.IsConditioned, Table: me.Table.Clone(), Condition: me.Condition.Clone().(joinExpression)}
}
func (me JoiningClauses) Clone() JoiningClauses {
ret := make(JoiningClauses, len(me))
for i, jc := range me {
ret[i] = jc.Clone()
}
return ret
}
func (me joinClause) Clone() Expression {
return joinClause{me.joinCondition}
}
func (me joinClause) Expression() Expression {
return me
}
func (me joinClause) JoinCondition() JoinCondition {
return me.joinCondition
}
type (
//A join expression that uses an ON clause
JoinOnExpression interface {
joinExpression
On() ExpressionList
}
joinOnClause struct {
joinClause
on ExpressionList
}
)
//Creates a new ON clause to be used within a join
// ds.Join(I("my_table"), On(I("my_table.fkey").Eq(I("other_table.id")))
func On(expressions ...Expression) joinExpression {
return joinOnClause{joinClause{ON_COND}, And(expressions...)}
}
func (me joinOnClause) Clone() Expression {
return joinOnClause{me.joinClause.Clone().(joinClause), me.on.Clone().(ExpressionList)}
}
func (me joinOnClause) Expression() Expression {
return me
}
func (me joinOnClause) On() ExpressionList {
return me.on
}
type (
JoinUsingExpression interface {
joinExpression
Using() ColumnList
}
//A join expression that uses an USING clause
joinUsingClause struct {
joinClause
using ColumnList
}
)
//Creates a new USING clause to be used within a join
func Using(expressions ...interface{}) joinExpression {
return joinUsingClause{joinClause{USING_COND}, cols(expressions...)}
}
func (me joinUsingClause) Clone() Expression {
return joinUsingClause{me.joinClause.Clone().(joinClause), me.using.Clone().(ColumnList)}
}
func (me joinUsingClause) Expression() Expression {
return me
}
func (me joinUsingClause) Using() ColumnList {
return me.using
}
type (
//Interface that an expression should implement if it can be aliased.
AliasMethods interface {
//Returns an AliasedExpression
// I("col").As("other_col") //"col" AS "other_col"
// I("col").As(I("other_col")) //"col" AS "other_col"
As(interface{}) AliasedExpression
}
//Interface that an expression should implement if it can be compared with other values.
ComparisonMethods interface {
//Creates a Boolean expression comparing equality
// I("col").Eq(1) //("col" = 1)
Eq(interface{}) BooleanExpression
//Creates a Boolean expression comparing in-equality
// I("col").Neq(1) //("col" != 1)
Neq(interface{}) BooleanExpression
//Creates a Boolean expression for greater than comparisons
// I("col").Gt(1) //("col" > 1)
Gt(interface{}) BooleanExpression
//Creates a Boolean expression for greater than or equal to than comparisons
// I("col").Gte(1) //("col" >= 1)
Gte(interface{}) BooleanExpression
//Creates a Boolean expression for less than comparisons
// I("col").Lt(1) //("col" < 1)
Lt(interface{}) BooleanExpression
//Creates a Boolean expression for less than or equal to comparisons
// I("col").Lte(1) //("col" <= 1)
Lte(interface{}) BooleanExpression
}
//Interface that an expression should implement if it can be used in an IN expression
InMethods interface {
//Creates a Boolean expression for IN clauses
// I("col").In([]string{"a", "b", "c"}) //("col" IN ('a', 'b', 'c'))
In(...interface{}) BooleanExpression
//Creates a Boolean expression for NOT IN clauses
// I("col").NotIn([]string{"a", "b", "c"}) //("col" NOT IN ('a', 'b', 'c'))
NotIn(...interface{}) BooleanExpression
}
//Interface that an expression should implement if it can be ORDERED.
OrderedMethods interface {
//Creates an Ordered Expression for sql ASC order
// ds.Order(I("a").Asc()) //ORDER BY "a" ASC
Asc() OrderedExpression
//Creates an Ordered Expression for sql DESC order
// ds.Order(I("a").Desc()) //ORDER BY "a" DESC
Desc() OrderedExpression
}
//Interface that an expression should implement if it can be used in string operations (e.g. LIKE, NOT LIKE...).
StringMethods interface {
//Creates an Boolean expression for LIKE clauses
// ds.Where(I("a").Like("a%")) //("a" LIKE 'a%')
Like(interface{}) BooleanExpression
//Creates an Boolean expression for NOT LIKE clauses
// ds.Where(I("a").NotLike("a%")) //("a" NOT LIKE 'a%')
NotLike(interface{}) BooleanExpression
//Creates an Boolean expression for case insensitive LIKE clauses
// ds.Where(I("a").ILike("a%")) //("a" ILIKE 'a%')
ILike(interface{}) BooleanExpression
//Creates an Boolean expression for case insensitive NOT LIKE clauses
// ds.Where(I("a").NotILike("a%")) //("a" NOT ILIKE 'a%')
NotILike(interface{}) BooleanExpression
}
//Interface that an expression should implement if it can be used in simple boolean operations (e.g IS, IS NOT).
BooleanMethods interface {
//Creates an Boolean expression IS clauses
// ds.Where(I("a").Is(nil)) //("a" IS NULL)
// ds.Where(I("a").Is(true)) //("a" IS TRUE)
// ds.Where(I("a").Is(false)) //("a" IS FALSE)
Is(interface{}) BooleanExpression
//Creates an Boolean expression IS NOT clauses
// ds.Where(I("a").IsNot(nil)) //("a" IS NOT NULL)
// ds.Where(I("a").IsNot(true)) //("a" IS NOT TRUE)
// ds.Where(I("a").IsNot(false)) //("a" IS NOT FALSE)
IsNot(interface{}) BooleanExpression
//Shortcut for Is(nil)
IsNull() BooleanExpression
//Shortcut for IsNot(nil)
IsNotNull() BooleanExpression
//Shortcut for Is(true)
IsTrue() BooleanExpression
//Shortcut for IsNot(true)
IsNotTrue() BooleanExpression
//Shortcut for Is(false)
IsFalse() BooleanExpression
//Shortcut for IsNot(false)
IsNotFalse() BooleanExpression
}
//Interface that an expression should implement if it can be casted to another SQL type .
CastMethods interface {
//Casts an expression to the specified type
// I("a").Cast("numeric")//CAST("a" AS numeric)
Cast(val string) CastExpression
}
updateMethods interface {
//Used internally by update sql
Set(interface{}) UpdateExpression
}
//Interface that an expression should implement if it can be used in a DISTINCT epxression.
DistinctMethods interface {
//Creates a DISTINCT clause
// I("a").Distinct() //DISTINCT("a")
Distinct() SqlFunctionExpression
}
)
type (
//An Identifier that can contain schema, table and column identifiers
IdentifierExpression interface {
Expression
AliasMethods
ComparisonMethods
InMethods
StringMethods
BooleanMethods
OrderedMethods
updateMethods
DistinctMethods
CastMethods
//Returns a new IdentifierExpression with the specified schema
Schema(string) IdentifierExpression
//Returns the current schema
GetSchema() string
//Returns a new IdentifierExpression with the specified table
Table(string) IdentifierExpression
//Returns the current table
GetTable() string
//Returns a new IdentifierExpression with the specified column
Col(interface{}) IdentifierExpression
//Returns the current column
GetCol() interface{}
//Returns a new IdentifierExpression with the column set to *
// I("my_table").All() //"my_table".*
All() IdentifierExpression
}
identifier struct {
schema string
table string
col interface{}
}
)
//Creates a new Identifier, the generated sql will use adapter specific quoting or '"' by default, this ensures case sensitivity and in certain databases allows for special characters, (e.g. "curr-table", "my table").
//An Identifier can represent a one or a combination of schema, table, and/or column.
// I("column") -> "column" //A Column
// I("table.column") -> "table"."column" //A Column and table
// I("schema.table.column") //Schema table and column
// I("table.*") //Also handles the * operator
func I(ident string) IdentifierExpression {
parts := strings.Split(ident, ".")
switch len(parts) {
case 2:
return identifier{}.Table(parts[0]).Col(parts[1])
case 3:
return identifier{}.Schema(parts[0]).Table(parts[1]).Col(parts[2])
}
return identifier{}.Col(ident)
}
func (me identifier) clone() identifier {
return identifier{schema: me.schema, table: me.table, col: me.col}
}
func (me identifier) Clone() Expression {
return me.clone()
}
//Sets the table on the current identifier
// I("col").Table("table") -> "table"."col" //postgres
// I("col").Table("table") -> `table`.`col` //mysql
// I("col").Table("table") -> `table`.`col` //sqlite3
func (me identifier) Table(table string) IdentifierExpression {
ret := me.clone()
if s, ok := me.col.(string); ok && s != "" && me.table == "" && me.schema == "" {
ret.schema = s
ret.col = nil
}
ret.table = table
return ret
}
func (me identifier) GetTable() string {
return me.table
}
//Sets the table on the current identifier
// I("table").Schema("schema") -> "schema"."table" //postgres
// I("col").Schema("table") -> `schema`.`table` //mysql
// I("col").Schema("table") -> `schema`.`table` //sqlite3
func (me identifier) Schema(schema string) IdentifierExpression {
ret := me.clone()
ret.schema = schema
return ret
}
func (me identifier) GetSchema() string {
return me.schema
}
//Sets the table on the current identifier
// I("table").Col("col") -> "table"."col" //postgres
// I("table").Schema("col") -> `table`.`col` //mysql
// I("table").Schema("col") -> `table`.`col` //sqlite3
func (me identifier) Col(col interface{}) IdentifierExpression {
ret := me.clone()
if s, ok := me.col.(string); ok && s != "" && me.table == "" {
ret.table = s
}
if col == "*" {
ret.col = Star()
} else {
ret.col = col
}
return ret
}
func (me identifier) Expression() Expression { return me }
//Qualifies the epression with a * literal (e.g. "table".*)
func (me identifier) All() IdentifierExpression { return me.Col("*") }
//Gets the column identifier
func (me identifier) GetCol() interface{} { return me.col }
//Used within updates to set a column value
func (me identifier) Set(val interface{}) UpdateExpression { return set(me, val) }
//Alias an identifer (e.g "my_col" AS "other_col")
func (me identifier) As(val interface{}) AliasedExpression { return aliased(me, val) }
//Returns a BooleanExpression for equality (e.g "my_col" = 1)
func (me identifier) Eq(val interface{}) BooleanExpression { return eq(me, val) }
//Returns a BooleanExpression for in equality (e.g "my_col" != 1)
func (me identifier) Neq(val interface{}) BooleanExpression { return neq(me, val) }
//Returns a BooleanExpression for checking that a identifier is greater than another value (e.g "my_col" > 1)
func (me identifier) Gt(val interface{}) BooleanExpression { return gt(me, val) }
//Returns a BooleanExpression for checking that a identifier is greater than or equal to another value (e.g "my_col" >= 1)
func (me identifier) Gte(val interface{}) BooleanExpression { return gte(me, val) }
//Returns a BooleanExpression for checking that a identifier is less than another value (e.g "my_col" < 1)
func (me identifier) Lt(val interface{}) BooleanExpression { return lt(me, val) }
//Returns a BooleanExpression for checking that a identifier is less than or equal to another value (e.g "my_col" <= 1)
func (me identifier) Lte(val interface{}) BooleanExpression { return lte(me, val) }
//Returns a BooleanExpression for checking that a identifier is in a list of values or (e.g "my_col" > 1)
func (me identifier) In(vals ...interface{}) BooleanExpression { return in(me, vals...) }
func (me identifier) NotIn(vals ...interface{}) BooleanExpression { return notIn(me, vals...) }
func (me identifier) Like(val interface{}) BooleanExpression { return like(me, val) }
func (me identifier) NotLike(val interface{}) BooleanExpression { return notLike(me, val) }
func (me identifier) ILike(val interface{}) BooleanExpression { return iLike(me, val) }
func (me identifier) NotILike(val interface{}) BooleanExpression { return notILike(me, val) }
func (me identifier) Is(val interface{}) BooleanExpression { return is(me, val) }
func (me identifier) IsNot(val interface{}) BooleanExpression { return isNot(me, val) }
func (me identifier) IsNull() BooleanExpression { return is(me, nil) }
func (me identifier) IsNotNull() BooleanExpression { return isNot(me, nil) }
func (me identifier) IsTrue() BooleanExpression { return is(me, true) }
func (me identifier) IsNotTrue() BooleanExpression { return isNot(me, true) }
func (me identifier) IsFalse() BooleanExpression { return is(me, false) }
func (me identifier) IsNotFalse() BooleanExpression { return isNot(me, false) }
func (me identifier) Asc() OrderedExpression { return asc(me) }
func (me identifier) Desc() OrderedExpression { return desc(me) }
func (me identifier) Distinct() SqlFunctionExpression { return DISTINCT(me) }
func (me identifier) Cast(t string) CastExpression { return Cast(me, t) }
type (
//Expression for representing "literal" sql.
// L("col = 1") -> col = 1)
// L("? = ?", I("col"), 1) -> "col" = 1
LiteralExpression interface {
Expression
AliasMethods
ComparisonMethods
OrderedMethods
//Returns the literal sql
Literal() string
//Arguments to be replaced within the sql
Args() []interface{}
}
literal struct {
literal string
args []interface{}
}
)
//Alias for L
func Literal(val string, args ...interface{}) LiteralExpression {
return L(val, args...)
}
//Creates a new SQL literal with the provided arguments.
// L("a = 1") -> a = 1
//You can also you placeholders. All placeholders within a Literal are represented by '?'
// L("a = ?", "b") -> a = 'b'
//Literals can also contain placeholders for other expressions
// L("(? AND ?) OR (?)", I("a").Eq(1), I("b").Eq("b"), I("c").In([]string{"a", "b", "c"}))
func L(val string, args ...interface{}) LiteralExpression {
return literal{literal: val, args: args}
}
//Returns a literal for DEFAULT sql keyword
func Default() LiteralExpression {
return literal{literal: "DEFAULT"}
}
//Returns a literal for the '*' operator
func Star() LiteralExpression {
return literal{literal: "*"}
}
func (me literal) Clone() Expression {
return Literal(me.literal)
}
func (me literal) Literal() string {
return me.literal
}
func (me literal) Args() []interface{} {
return me.args
}
func (me literal) Expression() Expression { return me }
func (me literal) As(val interface{}) AliasedExpression { return aliased(me, val) }
func (me literal) Eq(val interface{}) BooleanExpression { return eq(me, val) }
func (me literal) Neq(val interface{}) BooleanExpression { return neq(me, val) }
func (me literal) Gt(val interface{}) BooleanExpression { return gt(me, val) }
func (me literal) Gte(val interface{}) BooleanExpression { return gte(me, val) }
func (me literal) Lt(val interface{}) BooleanExpression { return lt(me, val) }
func (me literal) Lte(val interface{}) BooleanExpression { return lte(me, val) }
func (me literal) Asc() OrderedExpression { return asc(me) }
func (me literal) Desc() OrderedExpression { return desc(me) }
type (
UpdateExpression interface {
Col() IdentifierExpression
Val() interface{}
}
update struct {
col IdentifierExpression
val interface{}
}
)
func set(col IdentifierExpression, val interface{}) UpdateExpression {
return update{col: col, val: val}
}
func (me update) Expression() Expression {
return me
}
func (me update) Clone() Expression {
return update{col: me.col.Clone().(IdentifierExpression), val: me.val}
}
func (me update) Col() IdentifierExpression {
return me.col
}
func (me update) Val() interface{} {
return me.val
}
type (
BooleanOperation int
BooleanExpression interface {
Expression
//Returns the operator for the expression
Op() BooleanOperation
//The left hand side of the expression (e.g. I("a")
Lhs() Expression
//The right hand side of the expression could be a primitive value, dataset, or expression
Rhs() interface{}
}
boolean struct {
lhs Expression
rhs interface{}
op BooleanOperation
}
)
const (
//=
EQ_OP BooleanOperation = iota
//!= or <>
NEQ_OP
//IS
IS_OP
//IS NOT
IS_NOT_OP
//>
GT_OP
//>=
GTE_OP
//<
LT_OP
//<=
LTE_OP
//IN
IN_OP
//NOT IN
NOT_IN_OP
//LIKE, LIKE BINARY...
LIKE_OP
//NOT LIKE, NOT LIKE BINARY...
NOT_LIKE_OP
//ILIKE, LIKE
I_LIKE_OP
//NOT ILIKE, NOT LIKE
NOT_I_LIKE_OP
//~, REGEXP BINARY
REGEXP_LIKE_OP
//!~, NOT REGEXP BINARY
REGEXP_NOT_LIKE_OP
//~*, REGEXP
REGEXP_I_LIKE_OP
//!~*, NOT REGEXP
REGEXP_NOT_I_LIKE_OP
)
//used internally for inverting operators
var operator_inversions = map[BooleanOperation]BooleanOperation{
IS_OP: IS_NOT_OP,
EQ_OP: NEQ_OP,
GT_OP: LTE_OP,
GTE_OP: LT_OP,
LT_OP: GTE_OP,
LTE_OP: GT_OP,
IN_OP: NOT_IN_OP,
LIKE_OP: NOT_LIKE_OP,
I_LIKE_OP: NOT_I_LIKE_OP,
REGEXP_LIKE_OP: REGEXP_NOT_LIKE_OP,
REGEXP_I_LIKE_OP: REGEXP_NOT_I_LIKE_OP,
IS_NOT_OP: IS_OP,
NEQ_OP: EQ_OP,
NOT_IN_OP: IN_OP,
NOT_LIKE_OP: LIKE_OP,
NOT_I_LIKE_OP: I_LIKE_OP,
REGEXP_NOT_LIKE_OP: REGEXP_LIKE_OP,
REGEXP_NOT_I_LIKE_OP: REGEXP_I_LIKE_OP,
}
func (me boolean) Clone() Expression {
return boolean{op: me.op, lhs: me.lhs.Clone(), rhs: me.rhs}
}
func (me boolean) Expression() Expression {
return me
}
func (me boolean) Rhs() interface{} {
return me.rhs
}
func (me boolean) Lhs() Expression {
return me.lhs
}
func (me boolean) Op() BooleanOperation {
return me.op
}
//used internally to create an equality BooleanExpression
func eq(lhs Expression, rhs interface{}) BooleanExpression {
return checkBoolExpType(EQ_OP, lhs, rhs, false)
}
//used internally to create an in-equality BooleanExpression
func neq(lhs Expression, rhs interface{}) BooleanExpression {
return checkBoolExpType(EQ_OP, lhs, rhs, true)
}
//used internally to create an gt comparison BooleanExpression
func gt(lhs Expression, rhs interface{}) BooleanExpression {
return boolean{op: GT_OP, lhs: lhs, rhs: rhs}
}
//used internally to create an gte comparison BooleanExpression
func gte(lhs Expression, rhs interface{}) BooleanExpression {
return boolean{op: GTE_OP, lhs: lhs, rhs: rhs}
}
//used internally to create an lt comparison BooleanExpression
func lt(lhs Expression, rhs interface{}) BooleanExpression {
return boolean{op: LT_OP, lhs: lhs, rhs: rhs}
}
//used internally to create an lte comparison BooleanExpression
func lte(lhs Expression, rhs interface{}) BooleanExpression {
return boolean{op: LTE_OP, lhs: lhs, rhs: rhs}
}
//used internally to create an IN BooleanExpression
func in(lhs Expression, vals ...interface{}) BooleanExpression {
if len(vals) == 1 && reflect.Indirect(reflect.ValueOf(vals[0])).Kind() == reflect.Slice {
return boolean{op: IN_OP, lhs: lhs, rhs: vals[0]}
}
return boolean{op: IN_OP, lhs: lhs, rhs: vals}
}
//used internally to create a NOT IN BooleanExpression
func notIn(lhs Expression, vals ...interface{}) BooleanExpression {
if len(vals) == 1 && reflect.Indirect(reflect.ValueOf(vals[0])).Kind() == reflect.Slice {
return boolean{op: NOT_IN_OP, lhs: lhs, rhs: vals[0]}
}
return boolean{op: NOT_IN_OP, lhs: lhs, rhs: vals}
}
//used internally to create an IS BooleanExpression
func is(lhs Expression, val interface{}) BooleanExpression {
return checkBoolExpType(IS_OP, lhs, val, false)
}
//used internally to create an IS NOT BooleanExpression
func isNot(lhs Expression, val interface{}) BooleanExpression {
return checkBoolExpType(IS_OP, lhs, val, true)
}
//used internally to create a LIKE BooleanExpression
func like(lhs Expression, val interface{}) BooleanExpression {
return checkLikeExp(LIKE_OP, lhs, val, false)
}
//used internally to create an ILIKE BooleanExpression
func iLike(lhs Expression, val interface{}) BooleanExpression {
return checkLikeExp(I_LIKE_OP, lhs, val, false)
}
//used internally to create a NOT LIKE BooleanExpression
func notLike(lhs Expression, val interface{}) BooleanExpression {
return checkLikeExp(LIKE_OP, lhs, val, true)
}
//used internally to create a NOT ILIKE BooleanExpression
func notILike(lhs Expression, val interface{}) BooleanExpression {
return checkLikeExp(I_LIKE_OP, lhs, val, true)
}
//checks an like rhs to create the proper like expression for strings or regexps
func checkLikeExp(op BooleanOperation, lhs Expression, val interface{}, invert bool) BooleanExpression {
rhs := val
switch val.(type) {
case *regexp.Regexp:
if op == LIKE_OP {
op = REGEXP_LIKE_OP
} else if op == I_LIKE_OP {
op = REGEXP_I_LIKE_OP
}
rhs = val.(*regexp.Regexp).String()
}
if invert {
op = operator_inversions[op]
}
return boolean{op: op, lhs: lhs, rhs: rhs}
}
//checks a boolean operation normalizing the operation based on the RHS (e.g. "a" = true vs "a" IS TRUE
func checkBoolExpType(op BooleanOperation, lhs Expression, rhs interface{}, invert bool) BooleanExpression {
if rhs == nil {
op = IS_OP
} else {
switch reflect.Indirect(reflect.ValueOf(rhs)).Kind() {
case reflect.Bool:
op = IS_OP
case reflect.Slice:
//if its a slice of bytes dont treat as an IN
if _, ok := rhs.([]byte); !ok {
op = IN_OP
}
case reflect.Struct:
switch rhs.(type) {
case SqlExpression:
op = IN_OP
case *regexp.Regexp:
return checkLikeExp(LIKE_OP, lhs, rhs, invert)
}
}
}
if invert {