-
Notifications
You must be signed in to change notification settings - Fork 562
/
bind.go
405 lines (369 loc) · 10.1 KB
/
bind.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
// Licensed to ClickHouse, Inc. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. ClickHouse, Inc. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package clickhouse
import (
std_driver "database/sql/driver"
"fmt"
"reflect"
"regexp"
"strings"
"time"
"github.com/ClickHouse/clickhouse-go/v2/lib/column"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
)
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
func DateNamed(name string, value time.Time, scale TimeUnit) driver.NamedDateValue {
return driver.NamedDateValue{
Name: name,
Value: value,
Scale: uint8(scale),
}
}
var bindNumericRe = regexp.MustCompile(`\$[0-9]+`)
var bindPositionalRe = regexp.MustCompile(`[^\\][?]`)
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 = bindNumericRe.MatchString(query)
havePositional = bindPositionalRe.MatchString(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
}
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
)
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] == '?' {
if i > 0 && query[i-1] == '\\' {
// Copy all previous index to here characters
buf = append(buf, query[lastMatchIndex+1:i-1]...)
buf = append(buf, '?')
} else {
// 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 "", nil
}
}
value, err := format(tz, Seconds, v)
if err != nil {
return "", err
}
buf = append(buf, value...)
argIndex++
} else {
unbindCount++
}
}
lastMatchIndex = 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 (
unbind = make(map[string]struct{})
params = make(map[string]string)
)
for i, v := range args {
if fn, ok := v.(std_driver.Valuer); ok {
if v, err = fn.Value(); err != nil {
return "", nil
}
}
val, err := format(tz, Seconds, v)
if err != nil {
return "", err
}
params[fmt.Sprintf("$%d", i+1)] = val
}
query = bindNumericRe.ReplaceAllStringFunc(query, func(n string) string {
if _, found := params[n]; !found {
unbind[n] = struct{}{}
return ""
}
return params[n]
})
for param := range unbind {
return "", fmt.Errorf("have no arg for %s param", param)
}
return query, nil
}
var bindNamedRe = regexp.MustCompile(`@[a-zA-Z0-9\_]+`)
func bindNamed(tz *time.Location, query string, args ...any) (_ string, err error) {
var (
unbind = make(map[string]struct{})
params = make(map[string]string)
)
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
}
}
query = bindNamedRe.ReplaceAllStringFunc(query, func(n string) string {
if _, found := params[n]; !found {
unbind[n] = struct{}{}
return ""
}
return params[n]
})
for param := range unbind {
return "", fmt.Errorf("have no arg for %q param", param)
}
return query, nil
}
func formatTime(tz *time.Location, scale TimeUnit, value time.Time) (string, error) {
switch value.Location().String() {
case "Local", "":
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
}
if scale == Seconds {
return value.Format(fmt.Sprintf("toDateTime('2006-01-02 15:04:05', '%s')", value.Location().String())), 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), value.Location().String()), nil
}
var stringQuoteReplacer = strings.NewReplacer(`\`, `\\`, `'`, `\'`)
func format(tz *time.Location, scale TimeUnit, v any) (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 time.Time:
return formatTime(tz, scale, v)
case bool:
if v {
return "1", nil
}
return "0", nil
case GroupSet:
val, err := join(tz, scale, v.Value)
if err != nil {
return "", err
}
return fmt.Sprintf("(%s)", val), nil
case []GroupSet:
val, err := join(tz, scale, v)
if err != nil {
return "", err
}
return val, err
case ArraySet:
val, err := join(tz, scale, v)
if err != nil {
return "", err
}
return fmt.Sprintf("[%s]", val), nil
case fmt.Stringer:
return quote(v.String()), nil
case column.OrderedMap:
values := make([]string, 0)
for key := range v.Keys() {
name, err := format(tz, scale, key)
if err != nil {
return "", err
}
value, _ := v.Get(key)
val, err := format(tz, scale, value)
if err != nil {
return "", err
}
values = append(values, fmt.Sprintf("%s, %s", name, val))
}
return "map(" + strings.Join(values, ", ") + ")", nil
case column.IterableOrderedMap:
values := make([]string, 0)
iter := v.Iterator()
for iter.Next() {
key, value := iter.Key(), iter.Value()
name, err := format(tz, scale, key)
if err != nil {
return "", err
}
val, err := format(tz, scale, value)
if err != nil {
return "", err
}
values = append(values, fmt.Sprintf("%s, %s", name, val))
}
return "map(" + strings.Join(values, ", ") + ")", nil
}
switch v := reflect.ValueOf(v); v.Kind() {
case reflect.String:
return quote(v.String()), nil
case reflect.Slice, reflect.Array:
values := make([]string, 0, v.Len())
for i := 0; i < v.Len(); i++ {
val, err := format(tz, scale, v.Index(i).Interface())
if err != nil {
return "", err
}
values = append(values, val)
}
return fmt.Sprintf("[%s]", strings.Join(values, ", ")), nil
case reflect.Map: // map
values := make([]string, 0, len(v.MapKeys()))
for _, key := range v.MapKeys() {
name := fmt.Sprint(key.Interface())
if key.Kind() == reflect.String {
name = fmt.Sprintf("'%s'", name)
}
val, err := format(tz, scale, v.MapIndex(key).Interface())
if err != nil {
return "", err
}
values = append(values, fmt.Sprintf("%s, %s", name, val))
}
return "map(" + strings.Join(values, ", ") + ")", nil
case reflect.Ptr:
if v.IsNil() {
return "NULL", nil
}
return format(tz, scale, v.Elem().Interface())
}
return fmt.Sprint(v), nil
}
func join[E any](tz *time.Location, scale TimeUnit, values []E) (string, error) {
items := make([]string, len(values), len(values))
for i := range values {
val, err := format(tz, scale, values[i])
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
}