forked from Vinovest/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind.go
More file actions
283 lines (243 loc) · 6.75 KB
/
bind.go
File metadata and controls
283 lines (243 loc) · 6.75 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
package sqlx
import (
"database/sql/driver"
"errors"
"reflect"
"strconv"
"strings"
"sync"
"github.com/muir/sqltoken"
"github.com/vinovest/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", "pq-timeouts", "cloudsqlpostgres", "ql", "nrpostgres", "cockroach"},
QUESTION: {"mysql", "sqlite3", "nrmysql", "nrsqlite3"},
NAMED: {"oci8", "ora", "goracle", "godror"},
AT: {"sqlserver", "azuresql"},
}
var binds sync.Map
var rebindConfigs = func() []sqltoken.Config {
configs := make([]sqltoken.Config, AT+1)
pg := sqltoken.PostgreSQLConfig()
pg.NoticeQuestionMark = true
pg.NoticeDollarNumber = false
pg.SeparatePunctuation = true
configs[DOLLAR] = pg
ora := sqltoken.OracleConfig()
ora.NoticeColonWord = false
ora.NoticeQuestionMark = true
ora.SeparatePunctuation = true
configs[NAMED] = ora
ssvr := sqltoken.SQLServerConfig()
ssvr.NoticeAtWord = false
ssvr.NoticeQuestionMark = true
ssvr.SeparatePunctuation = true
configs[AT] = ssvr
return configs
}()
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.
func Rebind(bindType int, query string) string {
switch bindType {
case QUESTION, UNKNOWN:
return query
}
config := rebindConfigs[bindType]
tokens := sqltoken.Tokenize(query, config)
rqb := make([]byte, 0, len(query)+10)
var j int
for _, token := range tokens {
if token.Type != sqltoken.QuestionMark {
rqb = append(rqb, ([]byte)(token.Text)...)
continue
}
switch bindType {
case DOLLAR:
rqb = append(rqb, '$')
case NAMED:
rqb = append(rqb, ':', 'a', 'r', 'g')
case AT:
rqb = append(rqb, '@', 'p')
}
j++
rqb = strconv.AppendInt(rqb, int64(j), 10)
}
return string(rqb)
}
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.TypeFor[[]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.
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
arg, err = callValuerValue(a)
if err != nil {
return "", nil, err
}
}
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 int
config := rebindConfigs[DOLLAR] // specific config doesn't matter, we just need the tokenizer to return QuestionMarks
tokens := sqltoken.Tokenize(query, config)
inIn := false // found `in (`
for pos, token := range tokens {
if !inIn && token.Type == sqltoken.Punctuation && token.Text == "(" {
// look backwards to see if the previous word is "in"
for i := pos - 1; i >= 0; i-- {
if tokens[i].Type == sqltoken.Word {
inIn = strings.ToLower(tokens[i].Text) == "in"
break
}
}
}
if token.Type == sqltoken.QuestionMark {
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 an in-list
if !inIn {
newArgs = append(newArgs, argMeta.i)
buf.WriteString(token.Text)
continue
}
buf.WriteString("?")
for si := 1; si < argMeta.length; si++ {
buf.WriteString(", ?")
}
newArgs = appendReflectSlice(newArgs, argMeta.v, argMeta.length)
} else if inIn && token.Type == sqltoken.Punctuation && token.Text == ")" {
inIn = false
buf.WriteString(token.Text)
} else {
buf.WriteString(token.Text)
}
}
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 := range vlen {
args = append(args, v.Index(si).Interface())
}
}
return args
}
// callValuerValue returns vr.Value(), with one exception:
// If vr.Value is an auto-generated method on a pointer type and the
// pointer is nil, it would panic at runtime in the panicwrap
// method. Treat it like nil instead.
// Issue 8415.
//
// This is so people can implement driver.Value on value types and
// still use nil pointers to those types to mean nil/NULL, just like
// string/*string.
//
// This function is copied from database/sql/driver package
// and mirrored in the database/sql package.
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(reflect.TypeFor[driver.Valuer]()) {
return nil, nil
}
return vr.Value()
}