forked from ClickHouse/clickhouse-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind.go
226 lines (212 loc) · 5.69 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
// 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/supresu/clickhouse-go/v2/lib/driver"
)
func Named(name string, value interface{}) driver.NamedValue {
return driver.NamedValue{
Name: name,
Value: value,
}
}
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:
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] = format(tz, v)
}
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
}
}
params[fmt.Sprintf("$%d", i+1)] = format(tz, v)
}
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
}
}
params["@"+v.Name] = format(tz, value)
}
}
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 format(tz *time.Location, v interface{}) string {
quote := func(v string) string {
return "'" + strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace(v) + "'"
}
switch v := v.(type) {
case nil:
return "NULL"
case string:
return quote(v)
case time.Time:
switch v.Location().String() {
case "Local":
return fmt.Sprintf("toDateTime(%d)", v.Unix())
case tz.String():
return v.Format("toDateTime('2006-01-02 15:04:05')")
}
return v.Format("toDateTime('2006-01-02 15:04:05', '" + v.Location().String() + "')")
case []interface{}: // tuple
elements := make([]string, 0, len(v))
for _, e := range v {
elements = append(elements, format(tz, e))
}
return "(" + strings.Join(elements, ", ") + ")"
case [][]interface{}:
items := make([]string, 0, len(v))
for _, t := range v {
items = append(items, format(tz, t))
}
return strings.Join(items, ", ")
case fmt.Stringer:
return quote(v.String())
}
switch v := reflect.ValueOf(v); v.Kind() {
case reflect.String:
return quote(v.String())
case reflect.Slice:
values := make([]string, 0, v.Len())
for i := 0; i < v.Len(); i++ {
values = append(values, format(tz, v.Index(i).Interface()))
}
return strings.Join(values, ", ")
}
return fmt.Sprint(v)
}
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
}