-
Notifications
You must be signed in to change notification settings - Fork 562
/
bind.go
314 lines (294 loc) · 8.04 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
// 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/driver"
)
func Named(name string, value interface{}) driver.NamedValue {
return driver.NamedValue{
Name: name,
Value: value,
}
}
type TimeUnit uint8
const (
Seconds TimeUnit = iota
MilliSeconds
MicroSeconds
NanoSeconds
)
type GroupSet struct {
Value []interface{}
}
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 ...interface{}) (string, error) {
if len(args) == 0 {
return query, nil
}
var (
haveNamed bool
haveNumeric bool
havePositional bool
)
haveNumeric = bindNumericRe.MatchString(query)
havePositional = bindPositionalRe.MatchString(query)
if haveNumeric && havePositional {
return "", ErrBindMixedParamsFormats
}
for _, v := range args {
switch v.(type) {
case driver.NamedValue, driver.NamedDateValue:
haveNamed = true
default:
}
if haveNamed && (haveNumeric || havePositional) {
return "", ErrBindMixedParamsFormats
}
}
if haveNamed {
return bindNamed(tz, query, args...)
}
if haveNumeric {
return bindNumeric(tz, query, args...)
}
return bindPositional(tz, query, args...)
}
var bindPositionCharRe = regexp.MustCompile(`[?]`)
func bindPositional(tz *time.Location, query string, args ...interface{}) (_ string, err error) {
var (
unbind = make(map[int]struct{})
params = make([]string, len(args))
)
for i, v := range args {
if fn, ok := v.(std_driver.Valuer); ok {
if v, err = fn.Value(); err != nil {
return "", nil
}
}
params[i], err = format(tz, Seconds, v)
if err != nil {
return "", err
}
}
i := 0
query = bindPositionalRe.ReplaceAllStringFunc(query, func(n string) string {
if i >= len(params) {
unbind[i] = struct{}{}
return ""
}
val := params[i]
i++
return bindPositionCharRe.ReplaceAllStringFunc(n, func(m string) string {
return val
})
})
for param := range unbind {
return "", fmt.Errorf("have no arg for param ? at position %d", param)
}
// replace \? escape sequence
return strings.ReplaceAll(query, "\\?", "?"), nil
}
func bindNumeric(tz *time.Location, query string, args ...interface{}) (_ 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 ...interface{}) (_ 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
}
func format(tz *time.Location, scale TimeUnit, v interface{}) (string, error) {
quote := func(v string) string {
return "'" + strings.NewReplacer(`\`, `\\`, `'`, `\'`).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 GroupSet:
elements := make([]string, 0, len(v.Value))
for _, e := range v.Value {
val, err := format(tz, scale, e)
if err != nil {
return "", err
}
elements = append(elements, val)
}
return fmt.Sprintf("(%s)", strings.Join(elements, ", ")), nil
case []GroupSet:
items := make([]string, 0, len(v))
for _, t := range v {
val, err := format(tz, scale, t)
if err != nil {
return "", err
}
items = append(items, fmt.Sprintf("%s", val))
}
return strings.Join(items, ", "), nil
case fmt.Stringer:
return quote(v.String()), nil
}
switch v := reflect.ValueOf(v); v.Kind() {
case reflect.String:
return quote(v.String()), nil
case reflect.Slice:
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 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
}
if v.MapIndex(key).Kind() == reflect.Slice {
// assume slices in maps are arrays
val = fmt.Sprintf("[%s]", val)
}
values = append(values, fmt.Sprintf("%s : %s", name, val))
}
return "{" + strings.Join(values, ", ") + "}", nil
}
return fmt.Sprint(v), nil
}
func rebind(in []std_driver.NamedValue) []interface{} {
args := make([]interface{}, 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
}