Repository navigation
Expand file tree
/
Copy pathbind.go
More file actions
346 lines (295 loc) · 8.29 KB
/
Copy pathbind.go
File metadata and controls
346 lines (295 loc) · 8.29 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
package sqlx
import (
"bytes"
"database/sql/driver"
"errors"
"reflect"
"strconv"
"strings"
"sync"
"github.com/gookit/sqlx/reflectx"
)
// Bindvar types supported by Rebind, BindMap and BindStruct.
const (
UNKNOWN = iota
QUESTION
DOLLAR
NAMED
AT
)
var defaultBinds = map[int][]string{
DOLLAR: {"postgres", "pgx", "pgx/v4", "pgx/v5", "pq-timeouts", "cloudsqlpostgres", "ql", "nrpostgres", "cockroach"},
QUESTION: {"mysql", "sqlite", "sqlite3", "nrmysql", "nrsqlite3"},
NAMED: {"oci8", "ora", "goracle", "godror"},
AT: {"sqlserver", "azuresql"},
}
var binds sync.Map
func init() {
for bind, drivers := range defaultBinds {
for _, driver := range drivers {
BindDriver(driver, bind)
}
}
}
// BindType returns the bindtype for a given database given a drivername.
func BindType(driverName string) int {
itype, ok := binds.Load(driverName)
if !ok {
return UNKNOWN
}
return itype.(int)
}
// BindDriver sets the BindType for driverName to bindType.
func BindDriver(driverName string, bindType int) {
binds.Store(driverName, bindType)
}
// Rebind a query from the default bindtype (QUESTION) to the target bindtype.
//
// A '?' inside a string constant ('...' or "..."), a quoted identifier or a SQL comment
// (-- to the end of the line, /* ... */) is left alone, so `WHERE name = 'a?b'` and a
// commented out `?` do not consume a placeholder. A quote is escaped by doubling it
// ('it”s') or with a backslash ('it\'s'), as the drivers accept.
func Rebind(bindType int, query string) string {
switch bindType {
case QUESTION, UNKNOWN:
return query
}
// room for a few params before the append has to grow
rqb := make([]byte, 0, len(query)+10)
var n int // placeholder counter
var quote byte // active quote character, 0 outside a string
var lineCmt bool // inside a -- comment
var blockCmt bool // inside a /* */ comment
for i := 0; i < len(query); i++ {
c := query[i]
if lineCmt {
rqb = append(rqb, c)
if c == '\n' {
lineCmt = false
}
continue
}
if blockCmt {
rqb = append(rqb, c)
if c == '*' && i+1 < len(query) && query[i+1] == '/' {
rqb = append(rqb, '/')
i++
blockCmt = false
}
continue
}
if quote != 0 {
rqb = append(rqb, c)
if c == '\\' && i+1 < len(query) {
// a backslash escapes the next byte inside the string
rqb = append(rqb, query[i+1])
i++
continue
}
if c == quote {
// a doubled quote is an escaped quote, not the end of the string
if i+1 < len(query) && query[i+1] == quote {
rqb = append(rqb, query[i+1])
i++
continue
}
quote = 0
}
continue
}
switch c {
case '?':
n++
switch bindType {
case DOLLAR:
rqb = append(rqb, '$')
case NAMED:
rqb = append(rqb, ':', 'a', 'r', 'g')
case AT:
rqb = append(rqb, '@', 'p')
}
rqb = strconv.AppendInt(rqb, int64(n), 10)
case '\'', '"':
quote = c
rqb = append(rqb, c)
case '-':
if i+1 < len(query) && query[i+1] == '-' {
lineCmt = true
rqb = append(rqb, '-', '-')
i++
continue
}
rqb = append(rqb, c)
case '/':
if i+1 < len(query) && query[i+1] == '*' {
blockCmt = true
rqb = append(rqb, '/', '*')
i++
continue
}
rqb = append(rqb, c)
default:
rqb = append(rqb, c)
}
}
return string(rqb)
}
// Experimental implementation of Rebind which uses a bytes.Buffer. The code is
// much simpler and should be more resistant to odd unicode, but it is twice as
// slow. Kept here for benchmarking purposes and to possibly replace Rebind if
// problems arise with its somewhat naive handling of unicode.
func rebindBuff(bindType int, query string) string {
if bindType != DOLLAR {
return query
}
b := make([]byte, 0, len(query))
rqb := bytes.NewBuffer(b)
j := 1
for _, r := range query {
if r == '?' {
rqb.WriteRune('$')
rqb.WriteString(strconv.Itoa(j))
j++
} else {
rqb.WriteRune(r)
}
}
return rqb.String()
}
func asSliceForIn(i any) (v reflect.Value, ok bool) {
if i == nil {
return reflect.Value{}, false
}
v = reflect.ValueOf(i)
t := reflectx.Deref(v.Type())
// Only expand slices
if t.Kind() != reflect.Slice {
return reflect.Value{}, false
}
// []byte is a driver.Value type so it should not be expanded
if t == reflect.TypeOf([]byte{}) {
return reflect.Value{}, false
}
return v, true
}
// In expands slice values in args, returning the modified query string
// and a new arg list that can be executed by a database. The `query` should
// use the `?` bindVar. The return value uses the `?` bindVar.
//
// In only expands `?` placeholders, whatever the driver: with PostgreSQL write
// `IN (?)` and then rebind the result with db.Rebind, instead of writing `IN ($1)`,
// which would leave the placeholder unexpanded and fail with a bindVar count error.
func In(query string, args ...any) (string, []any, error) {
// argMeta stores reflect.Value and length for slices and
// the value itself for non-slice arguments
type argMeta struct {
v reflect.Value
i any
length int
}
var flatArgsCount int
var anySlices bool
var stackMeta [32]argMeta
var meta []argMeta
if len(args) <= len(stackMeta) {
meta = stackMeta[:len(args)]
} else {
meta = make([]argMeta, len(args))
}
for i, arg := range args {
if a, ok := arg.(driver.Valuer); ok {
var err error
if arg, err = callValuerValue(a); err != nil {
return "", nil, err
}
// keep the unwrapped value for the no-slice fast path below
args[i] = arg
}
if v, ok := asSliceForIn(arg); ok {
meta[i].length = v.Len()
meta[i].v = v
anySlices = true
flatArgsCount += meta[i].length
if meta[i].length == 0 {
return "", nil, errors.New("empty slice passed to 'in' query")
}
} else {
meta[i].i = arg
flatArgsCount++
}
}
// don't do any parsing if there aren't any slices; note that this means
// some errors that we might have caught below will not be returned.
if !anySlices {
return query, args, nil
}
newArgs := make([]any, 0, flatArgsCount)
var buf strings.Builder
buf.Grow(len(query) + len(", ?")*flatArgsCount)
var arg, offset int
for i := strings.IndexByte(query[offset:], '?'); i != -1; i = strings.IndexByte(query[offset:], '?') {
if arg >= len(meta) {
// if an argument wasn't passed, lets return an error; this is
// not actually how database/sql Exec/Query works, but since we are
// creating an argument list programmatically, we want to be able
// to catch these programmer errors earlier.
return "", nil, errors.New("number of bindVars exceeds arguments")
}
argMeta := meta[arg]
arg++
// not a slice, continue.
// our questionmark will either be written before the next expansion
// of a slice or after the loop when writing the rest of the query
if argMeta.length == 0 {
offset = offset + i + 1
newArgs = append(newArgs, argMeta.i)
continue
}
// write everything up to and including our ? character
buf.WriteString(query[:offset+i+1])
for si := 1; si < argMeta.length; si++ {
buf.WriteString(", ?")
}
newArgs = appendReflectSlice(newArgs, argMeta.v, argMeta.length)
// slice the query and reset the offset. this avoids some bookkeeping for
// the write after the loop
query = query[offset+i+1:]
offset = 0
}
buf.WriteString(query)
if arg < len(meta) {
return "", nil, errors.New("number of bindVars less than number arguments")
}
return buf.String(), newArgs, nil
}
func appendReflectSlice(args []any, v reflect.Value, vlen int) []any {
switch val := v.Interface().(type) {
case []any:
args = append(args, val...)
case []int:
for i := range val {
args = append(args, val[i])
}
case []string:
for i := range val {
args = append(args, val[i])
}
default:
for si := 0; si < vlen; si++ {
args = append(args, v.Index(si).Interface())
}
}
return args
}
// callValuerValue returns vr.Value(), except when vr is a nil pointer whose element type
// implements driver.Valuer: calling Value on it would panic, so it is treated as nil.
// This mirrors the unexported helper of the database/sql package, so `In` accepts a nil
// pointer to a value type the same way database/sql does.
func callValuerValue(vr driver.Valuer) (v driver.Value, err error) {
if rv := reflect.ValueOf(vr); rv.Kind() == reflect.Pointer &&
rv.IsNil() &&
rv.Type().Elem().Implements(_valuerInterface) {
return nil, nil
}
return vr.Value()
}