-
Notifications
You must be signed in to change notification settings - Fork 8
/
fmt.go
1207 lines (1117 loc) · 42.1 KB
/
fmt.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 sq
import (
"bytes"
"context"
"database/sql"
"database/sql/driver"
"encoding/hex"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
"unicode"
)
// Writef is a fmt.Sprintf-style function that will write a format string and
// values slice into an Output. The only recognized placeholder is '{}'.
// Placeholders can be anonymous (e.g. {}), ordinal (e.g. {1}, {2}, {3}) or
// named (e.g. {name}, {email}, {age}).
//
// - Anonymous placeholders refer to successive values in the values slice.
// Anonymous placeholders are treated like a series of incrementing ordinal
// placeholders.
//
// - Ordinal placeholders refer to a specific value in the values slice using
// 1-based indexing.
//
// - Named placeholders refer to their corresponding sql.NamedArg value in the
// values slice. If there are multiple sql.NamedArg values with the same name,
// the last one wins.
//
// If a value is an SQLWriter, its WriteSQL method will be called. Else if a
// value is a slice, it will undergo slice expansion
// (https://bokwoon.neocities.org/sq.html#value-expansion). Otherwise, the
// value is added to the query args slice.
func Writef(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, format string, values []any) error {
return writef(ctx, dialect, buf, args, params, format, values, nil, nil)
}
func writef(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, format string, values []any, runningValuesIndex *int, ordinalIndex map[int]int) error {
// optimized case when the format string does not contain any '{}'
// placeholders
if i := strings.IndexByte(format, '{'); i < 0 {
buf.WriteString(format)
return nil
}
// namedIndex tracks the indexes of the namedArgs that are inside the
// values slice
namedIndex := make(map[string]int)
for i, value := range values {
var name string
switch arg := value.(type) {
case sql.NamedArg:
name = arg.Name
case Parameter:
name = arg.Name
case ArrayParameter:
name = arg.Name
case BinaryParameter:
name = arg.Name
case BooleanParameter:
name = arg.Name
case EnumParameter:
name = arg.Name
case JSONParameter:
name = arg.Name
case NumberParameter:
name = arg.Name
case StringParameter:
name = arg.Name
case TimeParameter:
name = arg.Name
case UUIDParameter:
name = arg.Name
}
if name != "" {
if _, ok := namedIndex[name]; ok {
return fmt.Errorf("named parameter {%s} provided more than once", name)
}
namedIndex[name] = i
}
}
buf.Grow(len(format))
if runningValuesIndex == nil {
n := 0
runningValuesIndex = &n
}
// ordinalIndex tracks the index of the ordinals that have already been
// written into the args slice
if ordinalIndex == nil {
ordinalIndex = make(map[int]int)
}
// jump to each '{' character in the format string
for i := strings.IndexByte(format, '{'); i >= 0; i = strings.IndexByte(format, '{') {
// Unescape '{{' to '{'
if i+1 <= len(format) && format[i+1] == '{' {
buf.WriteString(format[:i])
buf.WriteByte('{')
format = format[i+2:]
continue
}
buf.WriteString(format[:i])
format = format[i:]
// If we can't find the terminating '}' return an error
j := strings.IndexByte(format, '}')
if j < 0 {
return fmt.Errorf("no '}' found")
}
paramName := format[1:j]
format = format[j+1:]
for _, char := range paramName {
if char != '_' && !unicode.IsLetter(char) && !unicode.IsDigit(char) {
return fmt.Errorf("%q is not a valid param name (only letters, digits and '_' are allowed)", paramName)
}
}
// is it an anonymous placeholder? e.g. {}
if paramName == "" {
if *runningValuesIndex >= len(values) {
return fmt.Errorf("too few values passed in to Writef, expected more than %d", runningValuesIndex)
}
value := values[*runningValuesIndex]
*runningValuesIndex++
err := WriteValue(ctx, dialect, buf, args, params, value)
if err != nil {
return err
}
continue
}
// is it an ordinal placeholder? e.g. {1}, {2}, {3}
ordinal, err := strconv.Atoi(paramName)
if err == nil {
err = writeOrdinalValue(ctx, dialect, buf, args, params, values, ordinal, ordinalIndex)
if err != nil {
return err
}
continue
}
// is it a named placeholder? e.g. {name}, {age}, {email}
index, ok := namedIndex[paramName]
if !ok {
availableParams := make([]string, 0, len(namedIndex))
for name := range namedIndex {
availableParams = append(availableParams, name)
}
sort.Strings(availableParams)
return fmt.Errorf("named parameter {%s} not provided (available params: %s)", paramName, strings.Join(availableParams, ", "))
}
value := values[index]
err = WriteValue(ctx, dialect, buf, args, params, value)
if err != nil {
return err
}
}
buf.WriteString(format)
return nil
}
// WriteValue is the equivalent of Writef but for writing a single value into
// the Output.
func WriteValue(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, value any) error {
if namedArg, ok := value.(sql.NamedArg); ok {
return writeNamedArg(ctx, dialect, buf, args, params, namedArg)
}
if w, ok := value.(SQLWriter); ok {
return w.WriteSQL(ctx, dialect, buf, args, params)
}
if isExpandableSlice(value) {
return expandSlice(ctx, dialect, buf, args, params, value)
}
value, err := preprocessValue(dialect, value)
if err != nil {
return err
}
*args = append(*args, value)
index := len(*args) - 1
switch dialect {
case DialectPostgres, DialectSQLite:
buf.WriteString("$" + strconv.Itoa(index+1))
case DialectSQLServer:
buf.WriteString("@p" + strconv.Itoa(index+1))
default:
buf.WriteString("?")
}
return nil
}
// QuoteIdentifier quotes an identifier if necessary using dialect-specific
// quoting rules.
func QuoteIdentifier(dialect string, identifier string) string {
var needsQuoting bool
switch identifier {
case "":
needsQuoting = true
case "EXCLUDED", "INSERTED", "DELETED", "NEW", "OLD":
needsQuoting = false
default:
for i, char := range identifier {
if i == 0 && (char >= '0' && char <= '9') {
// first character cannot be a number
needsQuoting = true
break
}
if char == '_' || (char >= '0' && char <= '9') || (char >= 'a' && char <= 'z') {
continue
}
// If there are capital letters, the identifier is quoted to preserve
// capitalization information (because databases treat capital letters
// differently based on their dialect or configuration).
// If the character is anything else, we also quote. In general there
// may be some special characters that are allowed in unquoted
// identifiers (e.g. '$'), but different databases allow different
// things. We only recognize _a-z0-9 as the true standard.
needsQuoting = true
break
}
if !needsQuoting && dialect != "" {
switch dialect {
case DialectSQLite:
_, needsQuoting = sqliteKeywords[strings.ToLower(identifier)]
case DialectPostgres:
_, needsQuoting = postgresKeywords[strings.ToLower(identifier)]
case DialectMySQL:
_, needsQuoting = mysqlKeywords[strings.ToLower(identifier)]
case DialectSQLServer:
_, needsQuoting = sqlserverKeywords[strings.ToLower(identifier)]
}
}
}
if !needsQuoting {
return identifier
}
switch dialect {
case DialectMySQL:
return "`" + EscapeQuote(identifier, '`') + "`"
case DialectSQLServer:
return "[" + EscapeQuote(identifier, ']') + "]"
default:
return `"` + EscapeQuote(identifier, '"') + `"`
}
}
// EscapeQuote will escape the relevant quote in a string by doubling up on it
// (as per SQL rules).
func EscapeQuote(str string, quote byte) string {
i := strings.IndexByte(str, quote)
if i < 0 {
return str
}
var b strings.Builder
b.Grow(len(str) + strings.Count(str, string(quote)))
for i >= 0 {
b.WriteString(str[:i])
b.WriteByte(quote)
b.WriteByte(quote)
if len(str[i:]) > 2 && str[i] == quote && str[i+1] == quote {
str = str[i+2:]
} else {
str = str[i+1:]
}
i = strings.IndexByte(str, quote)
}
b.WriteString(str)
return b.String()
}
// Sprintf will interpolate SQL args into a query string containing prepared
// statement parameters. It returns an error if an argument cannot be properly
// represented in SQL. This function may be vulnerable to SQL injection and
// should be used for logging purposes only.
func Sprintf(dialect string, query string, args []any) (string, error) {
if len(args) == 0 {
return query, nil
}
buf := bufpool.Get().(*bytes.Buffer)
buf.Reset()
defer bufpool.Put(buf)
buf.Grow(len(query))
namedIndices := make(map[string]int)
for i, arg := range args {
switch arg := arg.(type) {
case sql.NamedArg:
namedIndices[arg.Name] = i
}
}
runningArgsIndex := 0
mustWriteCharAt := -1
insideStringOrIdentifier := false
var openingQuote rune
var paramName []rune
for i, char := range query {
// do we unconditionally write in the current char?
if mustWriteCharAt == i {
buf.WriteRune(char)
continue
}
// are we currently inside a string or identifier?
if insideStringOrIdentifier {
buf.WriteRune(char)
switch openingQuote {
case '\'', '"', '`':
// does the current char terminate the current string or identifier?
if char == openingQuote {
// is the next char the same as the current char, which
// escapes it and prevents it from terminating the current
// string or identifier?
if i+1 < len(query) && rune(query[i+1]) == openingQuote {
mustWriteCharAt = i + 1
} else {
insideStringOrIdentifier = false
}
}
case '[':
// does the current char terminate the current string or identifier?
if char == ']' {
// is the next char the same as the current char, which
// escapes it and prevents it from terminating the current
// string or identifier?
if i+1 < len(query) && query[i+1] == ']' {
mustWriteCharAt = i + 1
} else {
insideStringOrIdentifier = false
}
}
}
continue
}
// does the current char mark the start of a new string or identifier?
if char == '\'' || char == '"' || (char == '`' && dialect == DialectMySQL) || (char == '[' && dialect == DialectSQLServer) {
insideStringOrIdentifier = true
openingQuote = char
buf.WriteRune(char)
continue
}
// are we currently inside a parameter name?
if len(paramName) > 0 {
// does the current char terminate the current parameter name?
if char != '_' && !unicode.IsLetter(char) && !unicode.IsDigit(char) {
paramValue, err := lookupParam(dialect, args, paramName, namedIndices, runningArgsIndex)
if err != nil {
return buf.String(), err
}
buf.WriteString(paramValue)
buf.WriteRune(char)
if len(paramName) == 1 && paramName[0] == '?' {
runningArgsIndex++
}
paramName = paramName[:0]
} else {
paramName = append(paramName, char)
}
continue
}
// does the current char mark the start of a new parameter name?
if (char == '$' && (dialect == DialectSQLite || dialect == DialectPostgres)) ||
(char == ':' && dialect == DialectSQLite) ||
(char == '@' && (dialect == DialectSQLite || dialect == DialectSQLServer)) {
paramName = append(paramName, char)
continue
}
// is the current char the anonymous '?' parameter?
if char == '?' && dialect != DialectPostgres {
// for sqlite, just because we encounter a '?' doesn't mean it
// is an anonymous param. sqlite also supports using '?' for
// ordinal params (e.g. ?1, ?2, ?3) or named params (?foo,
// ?bar, ?baz). Hence we treat it as an ordinal/named param
// first, and handle the edge case later when it isn't.
if dialect == DialectSQLite {
paramName = append(paramName, char)
continue
}
if runningArgsIndex >= len(args) {
return buf.String(), fmt.Errorf("too few args provided, expected more than %d", runningArgsIndex+1)
}
paramValue, err := Sprint(dialect, args[runningArgsIndex])
if err != nil {
return buf.String(), err
}
buf.WriteString(paramValue)
runningArgsIndex++
continue
}
// if all the above questions answer false, we just write the current
// char in and continue
buf.WriteRune(char)
}
// flush the paramName buffer (to handle edge case where the query ends with a parameter name)
if len(paramName) > 0 {
paramValue, err := lookupParam(dialect, args, paramName, namedIndices, runningArgsIndex)
if err != nil {
return buf.String(), err
}
buf.WriteString(paramValue)
}
if insideStringOrIdentifier {
return buf.String(), fmt.Errorf("unclosed string or identifier")
}
return buf.String(), nil
}
// Sprint is the equivalent of Sprintf but for converting a single value into
// its SQL representation.
func Sprint(dialect string, v any) (string, error) {
const (
timestamp = "2006-01-02 15:04:05"
timestampWithTimezone = "2006-01-02 15:04:05.9999999-07:00"
)
switch v := v.(type) {
case nil:
return "NULL", nil
case bool:
if v {
if dialect == DialectSQLServer {
return "1", nil
}
return "TRUE", nil
}
if dialect == DialectSQLServer {
return "0", nil
}
return "FALSE", nil
case []byte:
switch dialect {
case DialectPostgres:
// https://www.postgresql.org/docs/current/datatype-binary.html
// (see 8.4.1. bytea Hex Format)
return `'\x` + hex.EncodeToString(v) + `'`, nil
case DialectSQLServer:
return `0x` + hex.EncodeToString(v), nil
default:
return `x'` + hex.EncodeToString(v) + `'`, nil
}
case string:
str := v
i := strings.IndexAny(str, "\r\n")
if i < 0 {
return `'` + strings.ReplaceAll(str, `'`, `''`) + `'`, nil
}
var b strings.Builder
if dialect == DialectMySQL || dialect == DialectSQLServer {
b.WriteString("CONCAT(")
}
for i >= 0 {
if str[:i] != "" {
b.WriteString(`'` + strings.ReplaceAll(str[:i], `'`, `''`) + `'`)
if dialect == DialectMySQL || dialect == DialectSQLServer {
b.WriteString(", ")
} else {
b.WriteString(" || ")
}
}
switch str[i] {
case '\r':
if dialect == DialectPostgres {
b.WriteString("CHR(13)")
} else {
b.WriteString("CHAR(13)")
}
case '\n':
if dialect == DialectPostgres {
b.WriteString("CHR(10)")
} else {
b.WriteString("CHAR(10)")
}
}
if str[i+1:] != "" {
if dialect == DialectMySQL || dialect == DialectSQLServer {
b.WriteString(", ")
} else {
b.WriteString(" || ")
}
}
str = str[i+1:]
i = strings.IndexAny(str, "\r\n")
}
if str != "" {
b.WriteString(`'` + strings.ReplaceAll(str, `'`, `''`) + `'`)
}
if dialect == DialectMySQL || dialect == DialectSQLServer {
b.WriteString(")")
}
return b.String(), nil
case time.Time:
if dialect == DialectPostgres || dialect == DialectSQLServer {
return `'` + v.Format(timestampWithTimezone) + `'`, nil
}
return `'` + v.UTC().Format(timestamp) + `'`, nil
case int:
return strconv.FormatInt(int64(v), 10), nil
case int8:
return strconv.FormatInt(int64(v), 10), nil
case int16:
return strconv.FormatInt(int64(v), 10), nil
case int32:
return strconv.FormatInt(int64(v), 10), nil
case int64:
return strconv.FormatInt(v, 10), nil
case uint:
return strconv.FormatUint(uint64(v), 10), nil
case uint8:
return strconv.FormatUint(uint64(v), 10), nil
case uint16:
return strconv.FormatUint(uint64(v), 10), nil
case uint32:
return strconv.FormatUint(uint64(v), 10), nil
case uint64:
return strconv.FormatUint(v, 10), nil
case float32:
return strconv.FormatFloat(float64(v), 'g', -1, 64), nil
case float64:
return strconv.FormatFloat(v, 'g', -1, 64), nil
case sql.NamedArg:
return Sprint(dialect, v.Value)
case sql.NullBool:
if !v.Valid {
return "NULL", nil
}
if v.Bool {
if dialect == DialectSQLServer {
return "1", nil
}
return "TRUE", nil
}
if dialect == DialectSQLServer {
return "0", nil
}
return "FALSE", nil
case sql.NullFloat64:
if !v.Valid {
return "NULL", nil
}
return strconv.FormatFloat(v.Float64, 'g', -1, 64), nil
case sql.NullInt64:
if !v.Valid {
return "NULL", nil
}
return strconv.FormatInt(v.Int64, 10), nil
case sql.NullInt32:
if !v.Valid {
return "NULL", nil
}
return strconv.FormatInt(int64(v.Int32), 10), nil
case sql.NullString:
if !v.Valid {
return "NULL", nil
}
return Sprint(dialect, v.String)
case sql.NullTime:
if !v.Valid {
return "NULL", nil
}
if dialect == DialectPostgres || dialect == DialectSQLServer {
return `'` + v.Time.Format(timestampWithTimezone) + `'`, nil
}
return `'` + v.Time.UTC().Format(timestamp) + `'`, nil
case driver.Valuer:
vv, err := v.Value()
if err != nil {
return "", fmt.Errorf("error when calling Value(): %w", err)
}
switch vv.(type) {
case int64, float64, bool, []byte, string, time.Time, nil:
return Sprint(dialect, vv)
default:
return "", fmt.Errorf("invalid driver.Value type %T (must be one of int64, float64, bool, []byte, string, time.Time, nil)", vv)
}
}
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
rv = rv.Elem()
if !rv.IsValid() {
return "NULL", nil
}
}
switch v := rv.Interface().(type) {
case bool, []byte, string, time.Time, int, int8, int16, int32, int64, uint,
uint8, uint16, uint32, uint64, float32, float64, sql.NamedArg,
sql.NullBool, sql.NullFloat64, sql.NullInt64, sql.NullInt32,
sql.NullString, sql.NullTime, driver.Valuer:
return Sprint(dialect, v)
default:
return "", fmt.Errorf("%T has no SQL representation", v)
}
}
// isExpandableSlice checks if a value is an expandable slice.
func isExpandableSlice(value any) bool {
// treat byte slices as a special case that we never want to expand
if _, ok := value.([]byte); ok {
return false
}
valueType := reflect.TypeOf(value)
if valueType == nil {
return false
}
return valueType.Kind() == reflect.Slice
}
// expandSlice expands a slice value into Output. Make sure the value is an
// expandable slice first by checking it with isExpandableSlice().
func expandSlice(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, value any) error {
slice := reflect.ValueOf(value)
var err error
for i := 0; i < slice.Len(); i++ {
if i > 0 {
buf.WriteString(", ")
}
arg := slice.Index(i).Interface()
if v, ok := arg.(SQLWriter); ok {
err = v.WriteSQL(ctx, dialect, buf, args, params)
if err != nil {
return err
}
continue
}
switch dialect {
case DialectPostgres, DialectSQLite:
buf.WriteString("$" + strconv.Itoa(len(*args)+1))
case DialectSQLServer:
buf.WriteString("@p" + strconv.Itoa(len(*args)+1))
default:
buf.WriteString("?")
}
arg, err = preprocessValue(dialect, arg)
if err != nil {
return err
}
*args = append(*args, arg)
}
return nil
}
// writeNamedArg writes an sql.NamedArg into the Output.
func writeNamedArg(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, namedArg sql.NamedArg) error {
if w, ok := namedArg.Value.(SQLWriter); ok {
return w.WriteSQL(ctx, dialect, buf, args, params)
}
if isExpandableSlice(namedArg.Value) {
return expandSlice(ctx, dialect, buf, args, params, namedArg.Value)
}
var err error
namedArg.Value, err = preprocessValue(dialect, namedArg.Value)
if err != nil {
return err
}
paramIndices := params[namedArg.Name]
if len(paramIndices) > 0 {
index := paramIndices[0]
switch dialect {
case DialectSQLite:
(*args)[index] = namedArg
buf.WriteString("$" + namedArg.Name)
return nil
case DialectPostgres:
(*args)[index] = namedArg.Value
buf.WriteString("$" + strconv.Itoa(index+1))
return nil
case DialectSQLServer:
(*args)[index] = namedArg
buf.WriteString("@" + namedArg.Name)
return nil
default:
for _, index := range paramIndices {
(*args)[index] = namedArg.Value
}
}
}
switch dialect {
case DialectSQLite:
*args = append(*args, namedArg)
if params != nil {
index := len(*args) - 1
params[namedArg.Name] = []int{index}
}
buf.WriteString("$" + namedArg.Name)
case DialectPostgres:
*args = append(*args, namedArg.Value)
index := len(*args) - 1
if params != nil {
params[namedArg.Name] = []int{index}
}
buf.WriteString("$" + strconv.Itoa(index+1))
case DialectSQLServer:
*args = append(*args, namedArg)
if params != nil {
index := len(*args) - 1
params[namedArg.Name] = []int{index}
}
buf.WriteString("@" + namedArg.Name)
default:
*args = append(*args, namedArg.Value)
if params != nil {
index := len(*args) - 1
params[namedArg.Name] = append(paramIndices, index)
}
buf.WriteString("?")
}
return nil
}
// writeOrdinalValue writes an ordinal value into the Output. The
// ordinalIndices map is there to keep track of which ordinal values we have
// already appended to args (which we do not want to append again).
func writeOrdinalValue(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int, values []any, ordinal int, ordinalIndices map[int]int) error {
index := ordinal - 1
if index < 0 || index >= len(values) {
return fmt.Errorf("ordinal parameter {%d} is out of bounds", ordinal)
}
value := values[index]
if namedArg, ok := value.(sql.NamedArg); ok {
return writeNamedArg(ctx, dialect, buf, args, params, namedArg)
}
if w, ok := value.(SQLWriter); ok {
return w.WriteSQL(ctx, dialect, buf, args, params)
}
if isExpandableSlice(value) {
return expandSlice(ctx, dialect, buf, args, params, value)
}
var err error
value, err = preprocessValue(dialect, value)
if err != nil {
return err
}
switch dialect {
case DialectSQLite, DialectPostgres, DialectSQLServer:
index, ok := ordinalIndices[ordinal]
if !ok {
*args = append(*args, value)
index = len(*args) - 1
ordinalIndices[ordinal] = index
}
switch dialect {
case DialectSQLite, DialectPostgres:
buf.WriteString("$" + strconv.Itoa(index+1))
case DialectSQLServer:
buf.WriteString("@p" + strconv.Itoa(index+1))
}
default:
err := WriteValue(ctx, dialect, buf, args, params, value)
if err != nil {
return err
}
}
return nil
}
// lookupParam returns the SQL representation of a paramName (inside the args
// slice).
func lookupParam(dialect string, args []any, paramName []rune, namedIndices map[string]int, runningArgsIndex int) (paramValue string, err error) {
var maybeNum string
if paramName[0] == '@' && dialect == DialectSQLServer && len(paramName) >= 2 && (paramName[1] == 'p' || paramName[1] == 'P') {
maybeNum = string(paramName[2:])
} else {
maybeNum = string(paramName[1:])
}
// is paramName an anonymous parameter?
if maybeNum == "" {
if paramName[0] != '?' {
return "", fmt.Errorf("parameter name missing")
}
paramValue, err = Sprint(dialect, args[runningArgsIndex])
if err != nil {
return "", err
}
return paramValue, nil
}
// is paramName an ordinal paramater?
ordinal, err := strconv.Atoi(maybeNum)
if err == nil {
index := ordinal - 1
if index < 0 || index >= len(args) {
return "", fmt.Errorf("args index %d out of bounds", ordinal)
}
paramValue, err = Sprint(dialect, args[index])
if err != nil {
return "", err
}
return paramValue, nil
}
// if we reach here, we know that the paramName is not an ordinal parameter
// i.e. it is a named parameter
if dialect == DialectPostgres || dialect == DialectMySQL {
return "", fmt.Errorf("%s does not support %s named parameter", dialect, string(paramName))
}
index, ok := namedIndices[string(paramName[1:])]
if !ok {
return "", fmt.Errorf("named parameter %s not provided", string(paramName))
}
if index < 0 || index >= len(args) {
return "", fmt.Errorf("args index %d out of bounds", ordinal)
}
paramValue, err = Sprint(dialect, args[index])
if err != nil {
return "", err
}
return paramValue, nil
}
func quoteTableColumns(dialect string, table Table) string {
tableWithColumns, ok := table.(interface{ GetColumns() []string })
if !ok {
return ""
}
columns := tableWithColumns.GetColumns()
if len(columns) == 0 {
return ""
}
var b strings.Builder
b.WriteString(" (")
for i, column := range columns {
if i > 0 {
b.WriteString(", ")
}
b.WriteString(QuoteIdentifier(dialect, column))
}
b.WriteString(")")
return b.String()
}
// Params is a shortcut for typing map[string]interface{}.
type Params = map[string]any
// Parameter is identical to sql.NamedArg, but implements the Field interface.
type Parameter sql.NamedArg
var _ Field = (*Parameter)(nil)
// Param creates a new Parameter.
func Param(name string, value any) Parameter {
return Parameter{Name: name, Value: value}
}
// WriteSQL implements the SQLWriter interface.
func (p Parameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error {
return writeNamedArg(ctx, dialect, buf, args, params, sql.NamedArg(p))
}
// IsField implements the Field interface.
func (p Parameter) IsField() {}
// ArrayParameter is identical to sql.NamedArg, but implements the Array interface.
type ArrayParameter sql.NamedArg
var _ Field = (*ArrayParameter)(nil)
// ArrayParam creates a new ArrayParameter. It wraps the value with
// ArrayValue().
func ArrayParam(name string, value any) ArrayParameter {
return ArrayParameter{Name: name, Value: ArrayValue(value)}
}
// WriteSQL implements the SQLWriter interface.
func (p ArrayParameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error {
return writeNamedArg(ctx, dialect, buf, args, params, sql.NamedArg(p))
}
// IsField implements the Field interface.
func (p ArrayParameter) IsField() {}
// IsArray implements the Array interface.
func (p ArrayParameter) IsArray() {}
// BinaryParameter is identical to sql.NamedArg, but implements the Binary
// interface.
type BinaryParameter sql.NamedArg
var _ Binary = (*BinaryParameter)(nil)
// BytesParam creates a new BinaryParameter using a []byte value.
func BytesParam(name string, b []byte) BinaryParameter {
return BinaryParameter{Name: name, Value: b}
}
// WriteSQL implements the SQLWriter interface.
func (p BinaryParameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error {
return writeNamedArg(ctx, dialect, buf, args, params, sql.NamedArg(p))
}
// IsField implements the Field interface.
func (p BinaryParameter) IsField() {}
// IsBinary implements the Binary interface.
func (p BinaryParameter) IsBinary() {}
// BooleanParameter is identical to sql.NamedArg, but implements the Boolean
// interface.
type BooleanParameter sql.NamedArg
var _ Boolean = (*BooleanParameter)(nil)
// BoolParam creates a new BooleanParameter from a bool value.
func BoolParam(name string, b bool) BooleanParameter {
return BooleanParameter{Name: name, Value: b}
}
// WriteSQL implements the SQLWriter interface.
func (p BooleanParameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error {
return writeNamedArg(ctx, dialect, buf, args, params, sql.NamedArg(p))
}
// IsField implements the Field interface.
func (p BooleanParameter) IsField() {}
// IsBoolean implements the Boolean interface.
func (p BooleanParameter) IsBoolean() {}
// EnumParameter is identical to sql.NamedArg, but implements the Enum
// interface.
type EnumParameter sql.NamedArg
var _ Field = (*EnumParameter)(nil)
// EnumParam creates a new EnumParameter. It wraps the value with EnumValue().
func EnumParam(name string, value Enumeration) EnumParameter {
return EnumParameter{Name: name, Value: EnumValue(value)}
}
// WriteSQL implements the SQLWriter interface.
func (p EnumParameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error {
return writeNamedArg(ctx, dialect, buf, args, params, sql.NamedArg(p))
}
// IsField implements the Field interface.
func (p EnumParameter) IsField() {}
// IsEnum implements the Enum interface.
func (p EnumParameter) IsEnum() {}
// JSONParameter is identical to sql.NamedArg, but implements the JSON
// interface.
type JSONParameter sql.NamedArg
var _ Field = (*JSONParameter)(nil)
// JSONParam creates a new JSONParameter. It wraps the value with JSONValue().
func JSONParam(name string, value any) JSONParameter {
return JSONParameter{Name: name, Value: JSONValue(value)}
}
// WriteSQL implements the SQLWriter interface.
func (p JSONParameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error {
return writeNamedArg(ctx, dialect, buf, args, params, sql.NamedArg(p))
}
// IsField implements the Field interface.
func (p JSONParameter) IsField() {}
// IsJSON implements the JSON interface.
func (p JSONParameter) IsJSON() {}
// NumberParameter is identical to sql.NamedArg, but implements the Number
// interface.
type NumberParameter sql.NamedArg
var _ Number = (*NumberParameter)(nil)
// IntParam creates a new NumberParameter from an int value.
func IntParam(name string, num int) NumberParameter {
return NumberParameter{Name: name, Value: num}
}
// Int64Param creates a new NumberParameter from an int64 value.
func Int64Param(name string, num int64) NumberParameter {
return NumberParameter{Name: name, Value: num}
}
// Float64Param creates a new NumberParameter from an float64 value.
func Float64Param(name string, num float64) NumberParameter {
return NumberParameter{Name: name, Value: num}
}
// WriteSQL implements the SQLWriter interface.
func (p NumberParameter) WriteSQL(ctx context.Context, dialect string, buf *bytes.Buffer, args *[]any, params map[string][]int) error {
return writeNamedArg(ctx, dialect, buf, args, params, sql.NamedArg(p))
}
// IsField implements the Field interface.
func (p NumberParameter) IsField() {}
// IsNumber implements the Number interface.
func (p NumberParameter) IsNumber() {}
// StringParameter is identical to sql.NamedArg, but implements the String
// interface.
type StringParameter sql.NamedArg
var _ String = (*StringParameter)(nil)
// StringParam creates a new StringParameter from a string value.