-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathexpr.go
More file actions
949 lines (799 loc) · 20.9 KB
/
expr.go
File metadata and controls
949 lines (799 loc) · 20.9 KB
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
package squirrel
import (
"bytes"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"sort"
"strings"
)
const (
// Portable true/false literals.
sqlTrue = "(1=1)"
sqlFalse = "(1=0)"
)
type expr struct {
sql string
args []any
}
// Expr builds an expression from a SQL fragment and arguments.
//
// Ex:
//
// Expr("FROM_UNIXTIME(?)", t)
func Expr(sql string, args ...any) Sqlizer {
return expr{sql: sql, args: args}
}
func (e expr) ToSql() (sql string, args []any, err error) {
simple := true
for _, arg := range e.args {
if _, ok := arg.(Sqlizer); ok {
simple = false
}
if isListType(arg) {
simple = false
}
}
if simple {
return e.sql, e.args, nil
}
buf := &bytes.Buffer{}
ap := e.args
sp := e.sql
var isql string
var iargs []any
for err == nil && len(ap) > 0 && sp != "" {
i := strings.Index(sp, "?")
if i < 0 {
// no more placeholders
break
}
if len(sp) > i+1 && sp[i+1:i+2] == "?" {
// escaped "??"; append it and step past
buf.WriteString(sp[:i+2])
sp = sp[i+2:]
continue
}
if as, ok := ap[0].(Sqlizer); ok {
// sqlizer argument; expand it and append the result
isql, iargs, err = nestedToSql(as)
buf.WriteString(sp[:i])
buf.WriteString(isql)
args = append(args, iargs...)
} else {
// normal argument; append it and the placeholder
buf.WriteString(sp[:i+1])
args = append(args, ap[0])
}
// step past the argument and placeholder
ap = ap[1:]
sp = sp[i+1:]
}
// append the remaining sql and arguments
buf.WriteString(sp)
return buf.String(), append(args, ap...), err
}
type concatExpr []any
func (ce concatExpr) ToSql() (sql string, args []any, err error) {
for _, part := range ce {
switch p := part.(type) {
case string:
sql += p
case Sqlizer:
pSql, pArgs, err := nestedToSql(p)
if err != nil {
return "", nil, err
}
sql += pSql
args = append(args, pArgs...)
default:
return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part)
}
}
return
}
// ConcatExpr builds an expression by concatenating strings and other expressions.
//
// Ex:
//
// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName)
// ConcatExpr("COALESCE(full_name,", name_expr, ")")
func ConcatExpr(parts ...any) concatExpr {
return concatExpr(parts)
}
// aliasExpr helps to alias part of SQL query generated with underlying "expr".
type aliasExpr struct {
expr Sqlizer
alias string
}
// Alias allows to define alias for column in SelectBuilder. Useful when column is
// defined as complex expression like IF or CASE
// Ex:
//
// .Column(Alias(caseStmt, "case_column"))
func Alias(e Sqlizer, a string) aliasExpr {
return aliasExpr{e, a}
}
func (e aliasExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("(%s) AS %s", sql, e.alias)
}
return
}
// Eq is syntactic sugar for use with Where/Having/Set methods.
type Eq map[string]any
type eqOperators struct {
equal string
in string
null string
inEmpty string
}
func getEqOperators(useNotOpr bool) eqOperators {
if useNotOpr {
return eqOperators{
equal: "<>",
in: "NOT IN",
null: "IS NOT",
inEmpty: sqlTrue,
}
}
return eqOperators{
equal: "=",
in: "IN",
null: "IS",
inEmpty: sqlFalse,
}
}
func unwrapValue(val any) (any, error) {
if v, ok := val.(driver.Valuer); ok {
return v.Value()
}
return val, nil
}
func dereferencePointer(val any) any {
r := reflect.ValueOf(val)
if r.Kind() == reflect.Ptr {
if r.IsNil() {
return nil
}
return r.Elem().Interface()
}
return val
}
func buildListExpr(key string, val any, ops eqOperators, args []any) (sql string, result []any) {
valVal := reflect.ValueOf(val)
if valVal.Len() == 0 {
if args == nil {
args = []any{}
}
return ops.inEmpty, args
}
for i := 0; i < valVal.Len(); i++ {
args = append(args, valVal.Index(i).Interface())
}
return fmt.Sprintf("%s %s (%s)", key, ops.in, Placeholders(valVal.Len())), args
}
func buildSubqueryExpr(
key string, sb SelectBuilder, ops eqOperators, args []any,
) (sql string, result []any, err error) {
subSql, subArgs, err := sb.toSqlRaw()
if err != nil {
return "", nil, err
}
return fmt.Sprintf("%s %s (%s)", key, ops.in, subSql), append(args, subArgs...), nil
}
func buildEqExpr(key string, val any, ops eqOperators, args []any) (sql string, result []any, err error) {
if val == nil {
return fmt.Sprintf("%s %s NULL", key, ops.null), args, nil
}
if isListType(val) {
expr, newArgs := buildListExpr(key, val, ops, args)
return expr, newArgs, nil
}
if sb, ok := val.(SelectBuilder); ok {
return buildSubqueryExpr(key, sb, ops, args)
}
return fmt.Sprintf("%s %s ?", key, ops.equal), append(args, val), nil
}
func (eq Eq) toSQL(useNotOpr bool) (sql string, args []any, err error) {
if len(eq) == 0 {
return sqlTrue, args, nil
}
ops := getEqOperators(useNotOpr)
exprs := make([]string, 0, len(eq))
sortedKeys := getSortedKeys(eq)
for _, key := range sortedKeys {
val := eq[key]
val, err = unwrapValue(val)
if err != nil {
return "", nil, err
}
val = dereferencePointer(val)
var expr1 string
expr1, args, err = buildEqExpr(key, val, ops, args)
if err != nil {
return "", nil, err
}
exprs = append(exprs, expr1)
}
return strings.Join(exprs, " AND "), args, nil
}
func (eq Eq) ToSql() (sql string, args []any, err error) {
return eq.toSQL(false)
}
// NotEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(NotEq{"id": 1}) == "id <> 1"
type NotEq Eq
func (neq NotEq) ToSql() (sql string, args []any, err error) {
return Eq(neq).toSQL(true)
}
// Like is syntactic sugar for use with LIKE conditions.
// Ex:
//
// .Where(Like{"name": "%irrel"})
type Like map[string]any
func (lk Like) toSql(opr string) (sql string, args []any, err error) {
exprs := make([]string, 0, len(lk))
for key, val := range lk {
var expr1 string
if v, ok := val.(driver.Valuer); ok {
if val, err = v.Value(); err != nil {
return
}
}
if val == nil {
err = errors.New("cannot use null with like operators")
return
} else {
if isListType(val) {
err = errors.New("cannot use array or slice with like operators")
return
} else {
expr1 = fmt.Sprintf("%s %s ?", key, opr)
args = append(args, val)
}
}
exprs = append(exprs, expr1)
}
sql = strings.Join(exprs, " AND ")
return
}
func (lk Like) ToSql() (sql string, args []any, err error) {
return lk.toSql("LIKE")
}
// NotLike is syntactic sugar for use with LIKE conditions.
// Ex:
//
// .Where(NotLike{"name": "%irrel"})
type NotLike Like
func (nlk NotLike) ToSql() (sql string, args []any, err error) {
return Like(nlk).toSql("NOT LIKE")
}
// ILike is syntactic sugar for use with ILIKE conditions.
// Ex:
//
// .Where(ILike{"name": "sq%"})
type ILike Like
func (ilk ILike) ToSql() (sql string, args []any, err error) {
return Like(ilk).toSql("ILIKE")
}
// NotILike is syntactic sugar for use with ILIKE conditions.
// Ex:
//
// .Where(NotILike{"name": "sq%"})
type NotILike Like
func (nilk NotILike) ToSql() (sql string, args []any, err error) {
return Like(nilk).toSql("NOT ILIKE")
}
// Lt is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(Lt{"id": 1})
type Lt map[string]any
func (lt Lt) toSql(opposite, orEq bool) (sql string, args []any, err error) {
var (
exprs = make([]string, 0, len(lt))
opr = "<"
)
if opposite {
opr = ">"
}
if orEq {
opr = fmt.Sprintf("%s%s", opr, "=")
}
sortedKeys := getSortedKeys(lt)
for _, key := range sortedKeys {
var expr1 string
val := lt[key]
if v, ok := val.(driver.Valuer); ok {
if val, err = v.Value(); err != nil {
return "", nil, err
}
}
if val == nil {
err = errors.New("cannot use null with less than or greater than operators")
return "", nil, err
}
if isListType(val) {
err = errors.New("cannot use array or slice with less than or greater than operators")
return "", nil, err
}
expr1 = fmt.Sprintf("%s %s ?", key, opr)
args = append(args, val)
exprs = append(exprs, expr1)
}
sql = strings.Join(exprs, " AND ")
return sql, args, nil
}
func (lt Lt) ToSql() (sql string, args []any, err error) {
return lt.toSql(false, false)
}
// LtOrEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(LtOrEq{"id": 1}) == "id <= 1"
type LtOrEq Lt
func (ltOrEq LtOrEq) ToSql() (sql string, args []any, err error) {
return Lt(ltOrEq).toSql(false, true)
}
// Gt is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(Gt{"id": 1}) == "id > 1"
type Gt Lt
func (gt Gt) ToSql() (sql string, args []any, err error) {
return Lt(gt).toSql(true, false)
}
// GtOrEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(GtOrEq{"id": 1}) == "id >= 1"
type GtOrEq Lt
func (gtOrEq GtOrEq) ToSql() (sql string, args []any, err error) {
return Lt(gtOrEq).toSql(true, true)
}
type conj []Sqlizer
func (c conj) join(sep, defaultExpr string) (sql string, args []any, err error) {
if len(c) == 0 {
return defaultExpr, []any{}, nil
}
var sqlParts []string
for _, sqlizer := range c {
partSQL, partArgs, err := nestedToSql(sqlizer)
if err != nil {
return "", nil, err
}
if partSQL != "" {
sqlParts = append(sqlParts, partSQL)
args = append(args, partArgs...)
}
}
if len(sqlParts) > 0 {
sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep))
}
return
}
// And conjunction Sqlizers.
type And conj
func (a And) ToSql() (sql string, args []any, err error) {
return conj(a).join(" AND ", sqlTrue)
}
// Or conjunction Sqlizers.
type Or conj
func (o Or) ToSql() (sql string, args []any, err error) {
return conj(o).join(" OR ", sqlFalse)
}
func getSortedKeys(exp map[string]any) []string {
sortedKeys := make([]string, 0, len(exp))
for k := range exp {
sortedKeys = append(sortedKeys, k)
}
sort.Strings(sortedKeys)
return sortedKeys
}
func isListType(val any) bool {
if driver.IsValue(val) {
return false
}
valVal := reflect.ValueOf(val)
return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice
}
// sumExpr helps to use aggregate function SUM in SQL query.
type sumExpr struct {
expr Sqlizer
}
// Sum allows to use SUM function in SQL query.
// Ex: SelectBuilder.Select("id", Sum("amount")).
func Sum(e Sqlizer) sumExpr {
return sumExpr{e}
}
func (e sumExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("SUM(%s)", sql)
}
return
}
// countExpr helps to use aggregate function COUNT in SQL query.
type countExpr struct {
expr Sqlizer
}
// Count allows to use COUNT function in SQL query.
// Ex: SelectBuilder.Select("id", Count("amount")).
func Count(e Sqlizer) countExpr {
return countExpr{e}
}
func (e countExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("COUNT(%s)", sql)
}
return
}
// minExpr helps to use aggregate function MIN in SQL query.
type minExpr struct {
expr Sqlizer
}
// Min allows to use MIN function in SQL query.
// Ex: SelectBuilder.Select("id", Min("amount")).
func Min(e Sqlizer) minExpr {
return minExpr{e}
}
func (e minExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("MIN(%s)", sql)
}
return
}
// maxExpr helps to use aggregate function MAX in SQL query.
type maxExpr struct {
expr Sqlizer
}
// Max allows to use MAX function in SQL query.
// Ex: SelectBuilder.Select("id", Max("amount")).
func Max(e Sqlizer) maxExpr {
return maxExpr{e}
}
func (e maxExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("MAX(%s)", sql)
}
return
}
// avgExpr helps to use aggregate function AVG in SQL query.
type avgExpr struct {
expr Sqlizer
}
// Avg allows to use AVG function in SQL query.
// Ex: SelectBuilder.Select("id", Avg("amount")).
func Avg(e Sqlizer) avgExpr {
return avgExpr{e}
}
func (e avgExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("AVG(%s)", sql)
}
return
}
// existsExpr helps to use EXISTS in SQL query.
type existsExpr struct {
expr Sqlizer
}
// Exists allows to use EXISTS in SQL query.
// Ex: SelectBuilder.Where(Exists(Select("id").From("accounts").Where(Eq{"id": 1}))).
func Exists(e Sqlizer) existsExpr {
return existsExpr{e}
}
func (e existsExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("EXISTS (%s)", sql)
}
return
}
// notExistsExpr helps to use NOT EXISTS in SQL query.
type notExistsExpr struct {
expr Sqlizer
}
// NotExists allows to use NOT EXISTS in SQL query.
// Ex: SelectBuilder.Where(NotExists(Select("id").From("accounts").Where(Eq{"id": 1}))).
func NotExists(e Sqlizer) notExistsExpr {
return notExistsExpr{e}
}
func (e notExistsExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("NOT EXISTS (%s)", sql)
}
return
}
// equalExpr helps to use = in SQL query.
type equalExpr struct {
expr Sqlizer
value any
}
// Equal allows to use = in SQL query.
// Ex: SelectBuilder.Where(Equal(sq.Select(...), 1)).
func Equal(e Sqlizer, v any) equalExpr {
return equalExpr{e, v}
}
func (e equalExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("(%s) = ?", sql)
args = append(args, e.value)
}
return
}
// notEqualExpr helps to use <> in SQL query.
type notEqualExpr equalExpr
// NotEqual allows to use <> in SQL query.
// Ex: SelectBuilder.Where(NotEqual(sq.Select(...), 1)).
func NotEqual(e Sqlizer, v any) notEqualExpr {
return notEqualExpr{e, v}
}
func (e notEqualExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("(%s) <> ?", sql)
args = append(args, e.value)
}
return
}
// greaterExpr helps to use > in SQL query.
type greaterExpr equalExpr
// Greater allows to use > in SQL query.
// Ex: SelectBuilder.Where(Greater(sq.Select(...), 1)).
func Greater(e Sqlizer, v any) greaterExpr {
return greaterExpr{e, v}
}
func (e greaterExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("(%s) > ?", sql)
args = append(args, e.value)
}
return
}
// greaterOrEqualExpr helps to use >= in SQL query.
type greaterOrEqualExpr equalExpr
// GreaterOrEqual allows to use >= in SQL query.
// Ex: SelectBuilder.Where(GreaterOrEqual(sq.Select(...), 1)).
func GreaterOrEqual(e Sqlizer, v any) greaterOrEqualExpr {
return greaterOrEqualExpr{e, v}
}
func (e greaterOrEqualExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("(%s) >= ?", sql)
args = append(args, e.value)
}
return
}
// lessExpr helps to use < in SQL query.
type lessExpr equalExpr
// Less allows to use < in SQL query.
// Ex: SelectBuilder.Where(Less(sq.Select(...), 1)).
func Less(e Sqlizer, v any) lessExpr {
return lessExpr{e, v}
}
func (e lessExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("(%s) < ?", sql)
args = append(args, e.value)
}
return
}
// lessOrEqualExpr helps to use <= in SQL query.
type lessOrEqualExpr equalExpr
// LessOrEqual allows to use <= in SQL query.
// Ex: SelectBuilder.Where(LessOrEqual(sq.Select(...), 1)).
func LessOrEqual(e Sqlizer, v any) lessOrEqualExpr {
return lessOrEqualExpr{e, v}
}
func (e lessOrEqualExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("(%s) <= ?", sql)
args = append(args, e.value)
}
return
}
// inExpr helps to use IN in SQL query.
type inExpr struct {
column string
expr any
}
// In allows to use IN in SQL query.
// Ex: SelectBuilder.Where(In("id", 1, 2, 3)).
func In(column string, e any) inExpr {
return inExpr{column, e}
}
func (e inExpr) ToSql() (sql string, args []any, err error) {
return inNotInToSql(e.column, e.expr, "IN", "=", "=ANY")
}
// notInExpr helps to use NOT IN in SQL query.
type notInExpr inExpr
// NotIn allows to use NOT IN in SQL query.
// Ex: SelectBuilder.Where(NotIn("id", 1, 2, 3)).
func NotIn(column string, e any) notInExpr {
return notInExpr{column, e}
}
func (e notInExpr) ToSql() (sql string, args []any, err error) {
return inNotInToSql(e.column, e.expr, "NOT IN", "<>", "<>ALL")
}
func inNotInToSql(column string, expr any, inOp, singleOp, multiOp string) (sql string, args []any, err error) {
switch v := expr.(type) {
case Sqlizer:
sql, args, err = nestedToSql(v)
if err == nil && sql != "" {
sql = fmt.Sprintf("%s %s (%s)", column, inOp, sql)
}
default:
if isListType(v) {
if reflect.ValueOf(v).Len() == 0 {
return "", nil, nil
}
if reflect.ValueOf(v).Len() == 1 {
args = []any{reflect.ValueOf(v).Index(0).Interface()}
sql = column + singleOp + "?"
} else {
args = []any{v}
sql = column + multiOp + "(?)"
}
} else {
args = []any{v}
sql = column + singleOp + "?"
}
}
return sql, args, err
}
// rangeExpr helps to use BETWEEN in SQL query.
type rangeExpr struct {
column string
start any
end any
}
// Range allows to use range in SQL query.
// Ex: SelectBuilder.Where(Range("id", 1, 3)) -> "id BETWEEN 1 AND 3".
// If start or end is nil, it will be omitted from the query.
// Ex: SelectBuilder.Where(Range("id", 1, nil)) -> "id >= 1".
// Ex: SelectBuilder.Where(Range("id", nil, 3)) -> "id <= 3".
func Range(column string, start, end any) rangeExpr {
return rangeExpr{column, start, end}
}
// ToSql builds the query into a SQL string and bound args.
func (e rangeExpr) ToSql() (sql string, args []any, err error) {
hasStart := e.start != nil && !reflect.ValueOf(e.start).IsZero()
hasEnd := e.end != nil && !reflect.ValueOf(e.end).IsZero()
if !hasStart && !hasEnd {
return "", nil, nil
}
var s Sqlizer
if hasStart && hasEnd {
s = Expr(e.column+" BETWEEN ? AND ?", e.start, e.end)
} else if hasStart {
s = GtOrEq{e.column: e.start}
} else {
s = LtOrEq{e.column: e.end}
}
return nestedToSql(s)
}
// EqNotEmpty ignores empty and zero values in Eq map.
// Ex: EqNotEmpty{"id1": 1, "name": nil, id2: 0, "desc": ""} -> "id1 = 1".
type EqNotEmpty map[string]any
// ToSql builds the query into a SQL string and bound args.
func (eq EqNotEmpty) ToSql() (sql string, args []any, err error) {
vals := make(Eq, len(eq))
for k, v := range eq {
v = clearEmptyValue(v)
if v != nil {
vals[k] = v
}
}
return nestedToSql(vals)
}
// clearEmptyValue recursively clears empty and zero values in any type.
func clearEmptyValue(v any) any {
if v == nil {
return nil
}
t := reflect.ValueOf(v)
switch t.Kind() { //nolint:exhaustive // only specific kinds are supported for SQL type conversion
case reflect.Array, reflect.Slice:
if t.Len() != 0 {
newSlice := reflect.MakeSlice(t.Type(), 0, t.Len())
for i := 0; i < t.Len(); i++ {
itemVal := clearEmptyValue(t.Index(i).Interface())
if itemVal != nil {
newSlice = reflect.Append(newSlice, t.Index(i))
}
}
if newSlice.Len() != 0 {
return newSlice.Interface()
}
}
default:
if !t.IsZero() {
return v
}
}
return nil
}
type cteExpr struct {
expr Sqlizer
cte string
}
// Cte allows to define CTE (Common Table Expressions) in SQL query.
func Cte(e Sqlizer, cte string) cteExpr {
return cteExpr{e, cte}
}
// ToSql builds the query into a SQL string and bound args.
func (e cteExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("%s AS (%s)", e.cte, sql)
}
return
}
type notExpr struct {
expr Sqlizer
}
// ToSql builds the query into a SQL string and bound args.
func (e notExpr) ToSql() (sql string, args []any, err error) {
sql, args, err = nestedToSql(e.expr)
if err == nil {
sql = fmt.Sprintf("NOT (%s)", sql)
}
return
}
// Not is a helper function to negate a condition.
func Not(e Sqlizer) Sqlizer {
// check nested NOT
if n, ok := e.(notExpr); ok {
return n.expr
}
return notExpr{e}
}
type coalesceExpr struct {
exprs []Sqlizer
null any
}
// Coalesce is a helper function to use COALESCE in SQL query.
func Coalesce(nullValue any, exprs ...Sqlizer) Sqlizer {
return coalesceExpr{exprs, nullValue}
}
// ToSql builds the query into a SQL string and bound args.
func (e coalesceExpr) ToSql() (sql string, args []any, err error) {
exprs := make([]string, 0, len(e.exprs))
allArgs := make([]any, 0)
for _, expr := range e.exprs {
var exprSQL string
var a []any
exprSQL, a, err = nestedToSql(expr)
if err != nil {
return
}
if exprSQL == "" {
continue
}
exprs = append(exprs, fmt.Sprintf("(%s)", exprSQL))
if len(a) > 0 {
allArgs = append(allArgs, a...)
}
}
if len(exprs) == 0 {
return "", nil, nil
}
sql = fmt.Sprintf("COALESCE(%s, ?)", strings.Join(exprs, ", "))
allArgs = append(allArgs, e.null)
return sql, allArgs, nil
}