-
Notifications
You must be signed in to change notification settings - Fork 683
Expand file tree
/
Copy pathbind.go
More file actions
970 lines (908 loc) · 29.4 KB
/
Copy pathbind.go
File metadata and controls
970 lines (908 loc) · 29.4 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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
package clickhouse
import (
std_driver "database/sql/driver"
"errors"
"fmt"
"math"
"math/big"
"reflect"
"strconv"
"strings"
"time"
"github.com/ClickHouse/clickhouse-go/v2/lib/column"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
)
var (
ErrInvalidTimezone = errors.New("invalid timezone value")
)
// Named gives a query argument a name. It works with both placeholder
// styles: with server-side query parameters (`{name:Type}`) the value is
// sent to the server separately from the query, with client-side binding
// (`@name`) it is written into the query text as a SQL literal.
//
// Either way, a time.Time keeps the moment it points to, whatever timezone
// it or the target carries: query parameters send it as epoch seconds, and
// client-side binding emits a SQL form that carries the zone when it needs
// to. On the query-parameter path, sub-second precision is kept when the
// value has any — fine for `DateTime64`, but a plain `DateTime` parameter
// rejects fractions. Use DateNamed to choose the precision yourself.
func Named(name string, value any) driver.NamedValue {
return driver.NamedValue{
Name: name,
Value: value,
}
}
type TimeUnit uint8
const (
Seconds TimeUnit = iota
MilliSeconds
MicroSeconds
NanoSeconds
)
type GroupSet struct {
Value []any
}
type ArraySet []any
// DateNamed is Named for a time.Time with the precision chosen by you
// instead of inferred from the value: the scale decides how many fractional
// digits are sent (Seconds none, MilliSeconds 3, and so on), and anything
// finer is dropped. Pick the scale that matches the parameter's type —
// Seconds for `DateTime`, MilliSeconds for `DateTime64(3)`. Like Named, the
// moment the value points to is preserved regardless of timezones.
func DateNamed(name string, value time.Time, scale TimeUnit) driver.NamedDateValue {
return driver.NamedDateValue{
Name: name,
Value: value,
Scale: uint8(scale),
}
}
func bind(tz *time.Location, query string, args ...any) (string, error) {
if len(args) == 0 {
return query, nil
}
var (
haveNumeric bool
havePositional bool
)
allArgumentsNamed, err := checkAllNamedArguments(args...)
if err != nil {
return "", err
}
if allArgumentsNamed {
return bindNamed(tz, query, args...)
}
haveNumeric, havePositional = bindParamsFormats(query)
if haveNumeric && havePositional {
return "", ErrBindMixedParamsFormats
}
if haveNumeric {
return bindNumeric(tz, query, args...)
}
return bindPositional(tz, query, args...)
}
func checkAllNamedArguments(args ...any) (bool, error) {
var (
haveNamed bool
haveAnonymous bool
)
for _, v := range args {
switch v.(type) {
case driver.NamedValue, driver.NamedDateValue:
haveNamed = true
default:
haveAnonymous = true
}
if haveNamed && haveAnonymous {
return haveNamed, ErrBindMixedParamsFormats
}
}
return haveNamed, nil
}
// bindQuoteState tracks whether the scanner is currently inside a region of the
// query where bind placeholders ('?', '$N', '@name') must NOT be substituted: a
// quoted identifier (backtick or double quote), a string literal (single quote),
// or a comment.
//
// ClickHouse comment syntax: single-line comments start with "--", "#" or "#!"
// and run to the end of the line; block comments are delimited by "/*" and "*/"
// and may be nested.
type bindQuoteState struct {
inBacktick bool
inSingle bool
inDouble bool
inLineComment bool
blockComment int // nesting depth of /* */ comments (ClickHouse nests them)
}
// inProtectedContext reports whether the current position is inside a quoted
// identifier, string literal, or comment: any region where '?', '$N' and
// '@name' markers are part of the query text rather than bind placeholders.
func (s *bindQuoteState) inProtectedContext() bool {
return s.inBacktick || s.inSingle || s.inDouble || s.inLineComment || s.blockComment > 0
}
// inIdentifierOrComment reports whether the current position is inside a quoted
// identifier (backtick or double quote) or a comment. In these contexts the
// query text is passed through untouched, including any backslash that precedes
// a '?'. This is deliberately distinct from a single-quoted string literal,
// where a "\?" is unescaped to a literal "?" for backward compatibility (see
// bindPositional).
func (s *bindQuoteState) inIdentifierOrComment() bool {
return s.inBacktick || s.inDouble || s.inLineComment || s.blockComment > 0
}
// update consumes the byte at pos and advances the quote/comment state. It
// returns the index of the last byte it consumed, which may be pos+1 when a
// two-byte token (a doubled quote delimiter, "--", "/*" or "*/") is recognized
// so the caller's loop skips the second byte. Doubled delimiters and backslash
// escapes keep the scanner inside the current quoted context.
func (s *bindQuoteState) update(query string, pos int) int {
switch {
case s.inLineComment:
if query[pos] == '\n' {
s.inLineComment = false
}
case s.blockComment > 0:
// Block comments nest in ClickHouse, so track depth rather than a bool.
switch {
case query[pos] == '/' && pos+1 < len(query) && query[pos+1] == '*':
s.blockComment++
return pos + 1
case query[pos] == '*' && pos+1 < len(query) && query[pos+1] == '/':
s.blockComment--
return pos + 1
}
case s.inBacktick:
if query[pos] == '`' && !isEscaped(query, pos) {
if pos+1 < len(query) && query[pos+1] == '`' {
return pos + 1
}
s.inBacktick = false
}
case s.inSingle:
if query[pos] == '\'' && !isEscaped(query, pos) {
if pos+1 < len(query) && query[pos+1] == '\'' {
return pos + 1
}
s.inSingle = false
}
case s.inDouble:
if query[pos] == '"' && !isEscaped(query, pos) {
if pos+1 < len(query) && query[pos+1] == '"' {
return pos + 1
}
s.inDouble = false
}
default:
// Raw context: a backslash-escaped delimiter does not open anything.
if isEscaped(query, pos) {
return pos
}
switch {
case query[pos] == '`':
s.inBacktick = true
case query[pos] == '\'':
s.inSingle = true
case query[pos] == '"':
s.inDouble = true
case query[pos] == '#':
// "#" and "#!" both start a single-line comment.
s.inLineComment = true
case query[pos] == '-' && pos+1 < len(query) && query[pos+1] == '-':
s.inLineComment = true
return pos + 1
case query[pos] == '/' && pos+1 < len(query) && query[pos+1] == '*':
s.blockComment++
return pos + 1
}
}
return pos
}
func isEscaped(query string, pos int) bool {
backslashes := 0
for i := pos - 1; i >= 0 && query[i] == '\\'; i-- {
backslashes++
}
return backslashes%2 == 1
}
func isDigit(ch byte) bool {
return ch >= '0' && ch <= '9'
}
// isNameChar reports whether ch is valid in a named placeholder (@name); it
// mirrors the previous bindNamedRe pattern `@[a-zA-Z0-9_]+`.
func isNameChar(ch byte) bool {
return ch == '_' ||
(ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z')
}
func bindParamsFormats(query string) (haveNumeric, havePositional bool) {
var state bindQuoteState
for i := 0; i < len(query); i++ {
if !state.inProtectedContext() {
switch {
case query[i] == '?' && (i == 0 || query[i-1] != '\\'):
havePositional = true
case query[i] == '$' && i+1 < len(query) && isDigit(query[i+1]):
haveNumeric = true
}
if haveNumeric && havePositional {
return haveNumeric, havePositional
}
}
i = state.update(query, i)
}
return haveNumeric, havePositional
}
func bindPositional(tz *time.Location, query string, args ...any) (_ string, err error) {
var (
lastMatchIndex = -1 // Position of previous match for copying
argIndex = 0 // Index for the argument at current position
buf = make([]byte, 0, len(query))
unbindCount = 0 // Number of positional arguments that couldn't be matched
state bindQuoteState
)
for i := 0; i < len(query); i++ {
// It's fine looping through the query string as bytes, because the (fixed) characters we're looking for
// are in the ASCII range to won't take up more than one byte.
if query[i] == '?' {
// Inside identifier quotes or comments the text is passed through
// unchanged, including any backslash that precedes the '?'.
if state.inIdentifierOrComment() {
continue
}
if i > 0 && query[i-1] == '\\' {
// Escaped "\?" becomes a literal "?" (the backslash is dropped).
// Applies in raw and single-quoted contexts; kept for backward
// compatibility.
buf = append(buf, query[lastMatchIndex+1:i-1]...)
buf = append(buf, '?')
lastMatchIndex = i
continue
}
if state.inSingle {
// An unescaped '?' inside a string literal is verbatim.
continue
}
// Copy all previous index to here characters
buf = append(buf, query[lastMatchIndex+1:i]...)
// Append the argument value
if argIndex < len(args) {
v := args[argIndex]
if fn, ok := v.(std_driver.Valuer); ok {
if v, err = fn.Value(); err != nil {
return "", err
}
}
value, err := format(tz, Seconds, v)
if err != nil {
return "", err
}
buf = append(buf, value...)
argIndex++
} else {
unbindCount++
}
lastMatchIndex = i
continue
}
i = state.update(query, i)
}
// If there were no replacements, quick return without copying the string
if lastMatchIndex < 0 {
return query, nil
}
// Append the remainder
buf = append(buf, query[lastMatchIndex+1:]...)
if unbindCount > 0 {
return "", fmt.Errorf("have no arg for param ? at last %d positions", unbindCount)
}
return string(buf), nil
}
func bindNumeric(tz *time.Location, query string, args ...any) (_ string, err error) {
var (
lastMatchIndex = -1
unbind = make(map[string]struct{})
params = make(map[string]string)
buf = make([]byte, 0, len(query))
state bindQuoteState
)
for i, v := range args {
if fn, ok := v.(std_driver.Valuer); ok {
if v, err = fn.Value(); err != nil {
return "", err
}
}
val, err := format(tz, Seconds, v)
if err != nil {
return "", err
}
params[fmt.Sprintf("$%d", i+1)] = val
}
for i := 0; i < len(query); i++ {
if !state.inProtectedContext() && query[i] == '$' && i+1 < len(query) && isDigit(query[i+1]) {
j := i + 2
for j < len(query) && isDigit(query[j]) {
j++
}
param := query[i:j]
buf = append(buf, query[lastMatchIndex+1:i]...)
if value, found := params[param]; found {
buf = append(buf, value...)
} else {
unbind[param] = struct{}{}
}
lastMatchIndex = j - 1
i = j - 1
continue
}
i = state.update(query, i)
}
if lastMatchIndex < 0 {
return query, nil
}
buf = append(buf, query[lastMatchIndex+1:]...)
for param := range unbind {
return "", fmt.Errorf("have no arg for %s param", param)
}
return string(buf), nil
}
func bindNamed(tz *time.Location, query string, args ...any) (_ string, err error) {
var (
lastMatchIndex = -1
unbind = make(map[string]struct{})
params = make(map[string]string)
buf = make([]byte, 0, len(query))
state bindQuoteState
)
for _, v := range args {
switch v := v.(type) {
case driver.NamedValue:
value := v.Value
if fn, ok := v.Value.(std_driver.Valuer); ok {
if value, err = fn.Value(); err != nil {
return "", err
}
}
val, err := format(tz, Seconds, value)
if err != nil {
return "", err
}
params["@"+v.Name] = val
case driver.NamedDateValue:
val, err := format(tz, TimeUnit(v.Scale), v.Value)
if err != nil {
return "", err
}
params["@"+v.Name] = val
}
}
for i := 0; i < len(query); i++ {
// A named placeholder is "@" followed by at least one name character, and
// only counts outside of quoted identifiers, string literals and comments.
if !state.inProtectedContext() && query[i] == '@' && i+1 < len(query) && isNameChar(query[i+1]) {
j := i + 1
for j < len(query) && isNameChar(query[j]) {
j++
}
param := query[i:j]
buf = append(buf, query[lastMatchIndex+1:i]...)
if value, found := params[param]; found {
buf = append(buf, value...)
} else {
unbind[param] = struct{}{}
}
lastMatchIndex = j - 1
i = j - 1
continue
}
i = state.update(query, i)
}
// If there were no replacements, quick return without copying the string.
if lastMatchIndex < 0 {
return query, nil
}
buf = append(buf, query[lastMatchIndex+1:]...)
for param := range unbind {
return "", fmt.Errorf("have no arg for %q param", param)
}
return string(buf), nil
}
func formatTime(tz *time.Location, scale TimeUnit, value time.Time) (string, error) {
locVal := value.Location().String()
switch locVal {
case "Local", "":
// It's required to pass timestamp as string due to decimal overflow for higher precision,
// but zero-value string "toDateTime('0')" will be not parsed by ClickHouse.
if value.Unix() == 0 {
return "toDateTime(0)", nil
}
switch scale {
case Seconds:
return fmt.Sprintf("toDateTime('%d')", value.Unix()), nil
case MilliSeconds:
return fmt.Sprintf("toDateTime64('%d', 3)", value.UnixMilli()), nil
case MicroSeconds:
return fmt.Sprintf("toDateTime64('%d', 6)", value.UnixMicro()), nil
case NanoSeconds:
return fmt.Sprintf("toDateTime64('%d', 9)", value.UnixNano()), nil
}
case tz.String():
if scale == Seconds {
return value.Format("toDateTime('2006-01-02 15:04:05')"), nil
}
return fmt.Sprintf("toDateTime64('%s', %d)", value.Format(fmt.Sprintf("2006-01-02 15:04:05.%0*d", int(scale*3), 0)), int(scale*3)), nil
}
// Escape the timezone string (timezone may contain malicious SQL query)
escapedTimezone := stringQuoteReplacer.Replace(locVal)
if locVal != escapedTimezone {
return "", fmt.Errorf("%w: %q", ErrInvalidTimezone, locVal)
}
if scale == Seconds {
return fmt.Sprintf("toDateTime('%s', '%s')", value.Format("2006-01-02 15:04:05"), escapedTimezone), nil
}
return fmt.Sprintf("toDateTime64('%s', %d, '%s')", value.Format(fmt.Sprintf("2006-01-02 15:04:05.%0*d", int(scale*3), 0)), int(scale*3), escapedTimezone), nil
}
// Escape order: backslash first so later replacements are not re-escaped.
// NUL is written as \0 so binary String values survive client-side bind.
var stringQuoteReplacer = strings.NewReplacer(`\`, `\\`, `'`, `\'`, "\x00", `\0`)
// formatMode says which syntax formatValue should produce. A value spliced
// into the query text needs SQL syntax; a server-side query parameter needs
// the text format the server parses instead. The two disagree for bools,
// maps, floats, and times, so the caller has to pick one.
type formatMode uint8
const (
// formatSQL produces SQL literals for client-side binding (the ?, $1,
// and @name placeholders): bools as 1/0, maps as map('k', v), floats as
// cast(..., 'Float64'), times as toDateTime(...).
formatSQL formatMode = iota
// formatParamText produces the text format the server expects for
// {name:Type} query parameters: bools as true/false, maps as {'k':v},
// floats as plain numbers, times as quoted epoch seconds like
// '1577934245' (see formatTimeParam). The server parses these values
// with the declared type's text reader, which does not understand SQL
// function syntax.
formatParamText
)
// format turns v into a SQL literal for client-side binding, where
// placeholders like `?`, `$1`, and `@name` are replaced directly in the query
// text. Server-side query parameters need formatParamText instead.
func format(tz *time.Location, scale TimeUnit, v any) (string, error) {
return formatValue(tz, scale, v, formatSQL)
}
// formatDuration renders a time.Duration as a quoted ClickHouse Time/Time64
// literal: 'HH:MM:SS' or 'HH:MM:SS.frac' with trailing fractional zeros
// trimmed. It returns the quoted form directly, like formatTime does with
// its toDateTime('...') wrapper, so the API is consistent.
func formatDuration(d time.Duration) string {
return "'" + stringQuoteReplacer.Replace(formatDurationBody(d)) + "'"
}
// formatDurationBody is the unquoted Time/Time64 text. Top-level {name:Time}
// query parameters send this raw; client-side bind wraps it in quotes.
func formatDurationBody(d time.Duration) string {
sign := ""
u := uint64(d)
if d < 0 {
sign = "-"
u = -u
}
hours := u / uint64(time.Hour)
u -= hours * uint64(time.Hour)
mins := u / uint64(time.Minute)
u -= mins * uint64(time.Minute)
secs := u / uint64(time.Second)
frac := u % uint64(time.Second)
if frac == 0 {
return fmt.Sprintf("%s%02d:%02d:%02d", sign, hours, mins, secs)
}
fracStr := strings.TrimRight(fmt.Sprintf("%09d", frac), "0")
return fmt.Sprintf("%s%02d:%02d:%02d.%s", sign, hours, mins, secs, fracStr)
}
// formatValue turns v into a string in the given mode. The mode carries down
// into nested values, so a bool or map keeps its formatting at any depth.
//
// In formatParamText mode, values come out quoted the way the server expects
// them *inside* a composite type. Top-level String and DateTime parameters
// must be sent raw instead — bindQueryOrAppendParameters takes care of those
// before calling here.
func formatValue(tz *time.Location, scale TimeUnit, v any, mode formatMode) (string, error) {
return formatValueAt(tz, scale, v, mode, false)
}
func formatValueAt(tz *time.Location, scale TimeUnit, v any, mode formatMode, nested bool) (string, error) {
quote := func(v string) string {
return "'" + stringQuoteReplacer.Replace(v) + "'"
}
switch v := v.(type) {
case nil:
return "NULL", nil
case string:
return quote(v), nil
case []byte:
// Top-level []byte is a driver.Value for String (issue #1942).
// A nil []byte is the driver.Value convention for SQL NULL.
// Nested []uint8 is the same Go type and must stay Array(UInt8)
// so map[K][]uint8 / Array(Array(UInt8)) keep working.
if v == nil {
return "NULL", nil
}
if !nested {
return quote(string(v)), nil
}
values := make([]string, len(v))
for i, b := range v {
values[i] = strconv.FormatUint(uint64(b), 10)
}
return fmt.Sprintf("[%s]", strings.Join(values, ", ")), nil
case time.Time:
if mode == formatParamText {
return quote(formatTimeParam(v)), nil
}
return formatTime(tz, scale, v)
case *time.Time:
if v == nil {
return "NULL", nil
}
if mode == formatParamText {
return quote(formatTimeParam(*v)), nil
}
return formatTime(tz, scale, *v)
case time.Duration:
// Must precede fmt.Stringer: Duration.String() is Go's "14h30m0s".
// formatDuration already returns a quoted literal like formatTime.
return formatDuration(v), nil
case *time.Duration:
if v == nil {
return "NULL", nil
}
return formatDuration(*v), nil
case bool:
if mode == formatParamText {
if v {
return "true", nil
}
return "false", nil
}
if v {
return "1", nil
}
return "0", nil
case float32:
return formatFloat(float64(v), 32, mode), nil
case float64:
return formatFloat(v, 64, mode), nil
case GroupSet:
val, err := join(tz, scale, v.Value, mode)
if err != nil {
return "", err
}
return fmt.Sprintf("(%s)", val), nil
case []GroupSet:
val, err := join(tz, scale, v, mode)
if err != nil {
return "", err
}
return val, err
case ArraySet:
// An ArraySet of big.Int values gets the same single-type treatment as
// a plain slice (see bigIntArray); otherwise join formats each element.
if s, ok := bigIntArray(reflect.ValueOf(v), mode); ok {
return s, nil
}
val, err := join(tz, scale, v, mode)
if err != nil {
return "", err
}
return fmt.Sprintf("[%s]", val), nil
case big.Int:
return formatBigInt(&v, mode)
case *big.Int:
if v == nil {
return "NULL", nil
}
return formatBigInt(v, mode)
case fmt.Stringer:
if v := reflect.ValueOf(v); v.Kind() == reflect.Pointer &&
v.IsNil() &&
v.Type().Elem().Implements(reflect.TypeOf((*fmt.Stringer)(nil)).Elem()) {
return "NULL", nil
}
return quote(v.String()), nil
case column.OrderedMap:
entries := make([]mapEntry, 0)
for key := range v.Keys() {
name, err := formatValueAt(tz, scale, key, mode, true)
if err != nil {
return "", err
}
value, _ := v.Get(key)
val, err := formatValueAt(tz, scale, value, mode, true)
if err != nil {
return "", err
}
entries = append(entries, mapEntry{name, val})
}
return formatMap(entries, mode), nil
case column.IterableOrderedMap:
entries := make([]mapEntry, 0)
iter := v.Iterator()
for iter.Next() {
key, value := iter.Key(), iter.Value()
name, err := formatValueAt(tz, scale, key, mode, true)
if err != nil {
return "", err
}
val, err := formatValueAt(tz, scale, value, mode, true)
if err != nil {
return "", err
}
entries = append(entries, mapEntry{name, val})
}
return formatMap(entries, mode), nil
}
switch v := reflect.ValueOf(v); v.Kind() {
case reflect.String:
return quote(v.String()), nil
case reflect.Slice, reflect.Array:
// A slice whose elements are all big.Int renders with one wide-integer
// conversion for the whole array (see bigIntArray); every other slice
// formats element by element.
if s, ok := bigIntArray(v, mode); ok {
return s, nil
}
values := make([]string, 0, v.Len())
for i := 0; i < v.Len(); i++ {
val, err := formatValueAt(tz, scale, v.Index(i).Interface(), mode, true)
if err != nil {
return "", err
}
values = append(values, val)
}
return fmt.Sprintf("[%s]", strings.Join(values, ", ")), nil
case reflect.Map: // map
entries := make([]mapEntry, 0, v.Len())
for _, key := range v.MapKeys() {
name, err := formatValueAt(tz, scale, key.Interface(), mode, true)
if err != nil {
return "", err
}
val, err := formatValueAt(tz, scale, v.MapIndex(key).Interface(), mode, true)
if err != nil {
return "", err
}
entries = append(entries, mapEntry{name, val})
}
return formatMap(entries, mode), nil
case reflect.Float32:
return formatFloat(v.Float(), 32, mode), nil
case reflect.Float64:
return formatFloat(v.Float(), 64, mode), nil
case reflect.Ptr:
if v.IsNil() {
return "NULL", nil
}
return formatValueAt(tz, scale, v.Elem().Interface(), mode, nested)
}
return fmt.Sprint(v), nil
}
// mapEntry is one already-formatted key/value pair of a map.
type mapEntry struct {
key, value string
}
// formatMap joins formatted key/value pairs into a whole map: map('k', v)
// in SQL mode, {'k':v} in query-parameter text mode.
func formatMap(entries []mapEntry, mode formatMode) string {
pairs := make([]string, len(entries))
if mode == formatParamText {
for i, e := range entries {
pairs[i] = e.key + ":" + e.value
}
return "{" + strings.Join(pairs, ",") + "}"
}
for i, e := range entries {
pairs[i] = e.key + ", " + e.value
}
return "map(" + strings.Join(pairs, ", ") + ")"
}
// formatFloat renders a float.
//
// In SQL mode it wraps the number in a CAST to the matching Float type.
// Without it, a value like 1.0 renders as the bare literal "1", which
// ClickHouse treats as an integer and later narrows, breaking typed float
// scans. NaN and infinities are quoted in the lowercase form ClickHouse
// accepts, since Go's "NaN" and "+Inf" are not valid SQL.
//
// In query-parameter text mode none of that applies: the parameter already
// has a declared type, and the server's text reader rejects cast(...) but
// happily takes plain numbers and bare nan/inf/-inf.
func formatFloat(f float64, bitSize int, mode formatMode) string {
if mode == formatParamText {
switch {
case math.IsNaN(f):
return "nan"
case math.IsInf(f, 1):
return "inf"
case math.IsInf(f, -1):
return "-inf"
}
return strconv.FormatFloat(f, 'g', -1, bitSize)
}
chType := "Float64"
if bitSize == 32 {
chType = "Float32"
}
switch {
case math.IsNaN(f):
return fmt.Sprintf("cast('nan', '%s')", chType)
case math.IsInf(f, 1):
return fmt.Sprintf("cast('inf', '%s')", chType)
case math.IsInf(f, -1):
return fmt.Sprintf("cast('-inf', '%s')", chType)
}
return fmt.Sprintf("cast(%s, '%s')", strconv.FormatFloat(f, 'g', -1, bitSize), chType)
}
// Bounds of ClickHouse's wide-integer types, used to pick the narrowest
// conversion that holds a big.Int exactly. Read-only after init.
var (
int128Min = new(big.Int).Neg(new(big.Int).Lsh(big.NewInt(1), 127)) // -2^127
int128Max = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 127), big.NewInt(1)) // 2^127-1
uint128Max = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 128), big.NewInt(1)) // 2^128-1
int256Min = new(big.Int).Neg(new(big.Int).Lsh(big.NewInt(1), 255)) // -2^255
int256Max = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 255), big.NewInt(1)) // 2^255-1
uint256Max = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) // 2^256-1
)
// formatBigInt renders a big.Int, the Go type behind Int128/UInt128/Int256/
// UInt256.
//
// In query-parameter text mode the {name:Type} placeholder already declares the
// type, so the server parses the bare decimal with the matching reader and the
// value stays exact.
//
// In SQL mode there is no declared type, and the server reads a bare decimal
// literal wider than 64 bits as Float64, losing precision (a WHERE on an Int128
// column then matches nothing). Wrapping the exact decimal in the narrowest
// wide-integer conversion that fits keeps both the value and an integer type,
// the same way times bind as toDateTime(...) and floats as cast(..., 'Float64').
func formatBigInt(v *big.Int, mode formatMode) (string, error) {
if mode == formatParamText {
return v.String(), nil
}
fn, err := bigIntConvFunc(v)
if err != nil {
return "", err
}
// big.Int.String is only an optional sign followed by digits, so it needs
// no escaping inside the quotes.
return fn + "('" + v.String() + "')", nil
}
// bigIntConvFunc returns the ClickHouse conversion function for the narrowest
// wide-integer type that holds v exactly, or an error if v fits none of them.
func bigIntConvFunc(v *big.Int) (string, error) {
if v.Sign() >= 0 {
switch {
case v.Cmp(int128Max) <= 0:
return "toInt128", nil
case v.Cmp(uint128Max) <= 0:
return "toUInt128", nil
case v.Cmp(int256Max) <= 0:
return "toInt256", nil
case v.Cmp(uint256Max) <= 0:
return "toUInt256", nil
}
} else {
switch {
case v.Cmp(int128Min) >= 0:
return "toInt128", nil
case v.Cmp(int256Min) >= 0:
return "toInt256", nil
}
}
return "", fmt.Errorf("big.Int value %s is out of range for Int128, UInt128, Int256 and UInt256", v.String())
}
// bigIntArray renders v — a slice or array — as one ClickHouse array literal
// when every element is a big.Int or *big.Int, using a single wide-integer
// conversion for all of them (see commonBigIntConvFunc). ok is false for any
// other slice, in query-parameter text mode (where the declared type already
// covers the array), or when no single wide type holds every element; the
// caller then formats the elements itself.
func bigIntArray(v reflect.Value, mode formatMode) (string, bool) {
if mode != formatSQL {
return "", false
}
fn, ok := commonBigIntConvFunc(v)
if !ok {
return "", false
}
values := make([]string, 0, v.Len())
for i := 0; i < v.Len(); i++ {
switch e := v.Index(i).Interface().(type) {
case *big.Int:
if e == nil {
values = append(values, "NULL")
continue
}
values = append(values, fn+"('"+e.String()+"')")
case big.Int:
values = append(values, fn+"('"+e.String()+"')")
}
}
return fmt.Sprintf("[%s]", strings.Join(values, ", ")), true
}
// commonBigIntConvFunc reports whether every element of slice v is a big.Int or
// *big.Int and, if so, returns the single wide-integer conversion function that
// holds them all. ok is false when the elements are not all big.Int, when there
// is no non-nil element, or when no one wide-integer type holds every value; the
// caller then formats each element on its own.
//
// A slice binds as one array literal, so every element needs the same
// conversion. Choosing the narrowest type per value can mix e.g. toInt128 and
// toUInt256, which have no common ClickHouse type unless use_variant_as_common_type
// is on (off by default before 26.x) — [toUInt256('1'), toUInt256('...')] is a
// plain Array(UInt256), while [toInt128('1'), toUInt256('...')] makes
// WHERE ... IN ? fail.
//
// The unification is one level deep: mixed-magnitude big.Int values nested in a
// map, in a nested array, or in a tuple used as an IN set still get per-element
// conversions and can still hit NO_COMMON_TYPE.
func commonBigIntConvFunc(v reflect.Value) (string, bool) {
var lo, hi *big.Int
for i := 0; i < v.Len(); i++ {
var b *big.Int
switch e := v.Index(i).Interface().(type) {
case *big.Int:
b = e
case big.Int:
b = &e
default:
return "", false
}
if b == nil {
continue
}
if lo == nil || b.Cmp(lo) < 0 {
lo = b
}
if hi == nil || b.Cmp(hi) > 0 {
hi = b
}
}
if lo == nil {
return "", false
}
// A non-negative range is held by the type of its largest value. A range
// that includes a negative value needs a signed type wide enough for both
// ends; if none is, fall back to per-element formatting.
if lo.Sign() >= 0 {
fn, err := bigIntConvFunc(hi)
return fn, err == nil
}
switch {
case lo.Cmp(int128Min) >= 0 && hi.Cmp(int128Max) <= 0:
return "toInt128", true
case lo.Cmp(int256Min) >= 0 && hi.Cmp(int256Max) <= 0:
return "toInt256", true
}
return "", false
}
func join[E any](tz *time.Location, scale TimeUnit, values []E, mode formatMode) (string, error) {
items := make([]string, len(values))
for i := range values {
val, err := formatValueAt(tz, scale, values[i], mode, true)
if err != nil {
return "", err
}
items[i] = val
}
return strings.Join(items, ", "), nil
}
func rebind(in []std_driver.NamedValue) []any {
args := make([]any, 0, len(in))
for _, v := range in {
switch {
case len(v.Name) != 0:
args = append(args, driver.NamedValue{
Name: v.Name,
Value: v.Value,
})
default:
args = append(args, v.Value)
}
}
return args
}