-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind.go
210 lines (173 loc) · 4.82 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
package zinc
import (
"database/sql/driver"
"errors"
"fmt"
"reflect"
"strings"
)
func (db *DB) Bind(q string, unnamedArgs Args, namedArgs NamedArgs) (string, []any, error) {
return bind(q, unnamedArgs, namedArgs, db.options)
}
func bind(q string, unnamedArgs Args, namedArgs NamedArgs, opts *Options) (string, []any, error) {
hasInKeyword := func(s string) bool {
return strings.Contains(strings.ToUpper(s), "IN")
}
isEmpty := func() bool {
return len(unnamedArgs) <= 0 && len(namedArgs) <= 0
}
hasNamed := func() bool {
return len(namedArgs) > 0
}
if isEmpty() {
return q, []any{}, nil
} else if hasNamed() {
bound, argNames, err := opts.Dialect.CompileNamedQuery(q, opts)
if err != nil {
return "", nil, fmt.Errorf("%w(%s)", ErrBind, err.Error())
}
boundArgs := append([]any{}, unnamedArgs...)
for _, name := range argNames {
argVal, ok := namedArgs[name]
if !ok {
return "", nil, fmt.Errorf("%w(missing named arg %s)", ErrBind, name)
}
boundArgs = append(boundArgs, argVal)
}
if hasInKeyword(bound) {
bound, boundArgs, err = bindVariable(bound, boundArgs...)
if err != nil {
return "", nil, fmt.Errorf("%w(%s)", ErrBind, err.Error())
}
}
return bound, boundArgs, nil
} else {
var err error
boundArgs := append([]any{}, unnamedArgs...)
if hasInKeyword(q) {
q, boundArgs, err = bindVariable(q, boundArgs...)
if err != nil {
return "", nil, fmt.Errorf("%w(%s)", ErrBind, err.Error())
}
}
return q, boundArgs, nil
}
}
// 下面的代码来自sqlx
func bindVariable(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 = a.Value()
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, 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
}
func asSliceForIn(i any) (v reflect.Value, ok bool) {
if i == nil {
return reflect.Value{}, false
}
v = reflect.ValueOf(i)
t := 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
}