-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnamed.go
More file actions
239 lines (193 loc) · 5.5 KB
/
Copy pathnamed.go
File metadata and controls
239 lines (193 loc) · 5.5 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
package sqlz
import (
"fmt"
"reflect"
"regexp"
"strings"
"github.com/rfberaldo/sqlz/internal/parser"
"github.com/rfberaldo/sqlz/internal/reflectutil"
)
type namedQuery struct {
*config
fieldIndexByKey map[string][]int
// result
query string
args []any
}
func processNamed(query string, arg any, cfg *config) (string, []any, error) {
n := &namedQuery{config: applyDefaults(cfg)}
if err := n.process(query, arg); err != nil {
return "", nil, err
}
return n.query, n.args, nil
}
func (n *namedQuery) process(query string, arg any) error {
argValue := reflect.Indirect(reflect.ValueOf(arg))
if !argValue.IsValid() {
return fmt.Errorf("sqlz/named: argument is nil pointer")
}
switch kind := argValue.Kind(); kind {
case reflect.Map, reflect.Struct:
return n.processOne(query, argValue, kind)
case reflect.Slice:
return n.processSlice(query, argValue)
}
return fmt.Errorf("sqlz/named: unsupported argument type: %T", arg)
}
func (n *namedQuery) processOne(query string, argValue reflect.Value, kind reflect.Kind) (err error) {
query, idents := parser.Parse(n.bind, query)
switch kind {
case reflect.Map:
err = n.bindMapArgs(idents, argValue)
case reflect.Struct:
err = n.bindStructArgs(idents, argValue)
}
if err != nil {
return err
}
n.query, n.args, err = parser.ParseInClause(n.bind, query, n.args)
if err != nil {
return err
}
return nil
}
func (n *namedQuery) structValue(v reflect.Value) any {
v = reflect.Indirect(v)
if !v.IsValid() {
return nil
}
if reflectutil.ImplementsValuer(v.Type()) {
return v.Interface()
}
// this helps allocating less than necessary
return reflectutil.TypedValue(v)
}
// bindStructArgs maps idents to the argValue struct fields, binding their values,
// binded args may have slices, meaning an "IN" clause.
func (n *namedQuery) bindStructArgs(idents []string, argValue reflect.Value) error {
argValue = reflect.Indirect(argValue)
if !argValue.IsValid() {
return fmt.Errorf("sqlz/named: argument is nil pointer")
}
if n.args == nil {
n.args = make([]any, 0, len(idents))
}
if n.fieldIndexByKey == nil {
n.fieldIndexByKey = reflectutil.StructFieldMap(
argValue.Type(), n.structTag, ".", n.fieldNameTransformer,
)
}
for _, ident := range idents {
index, ok := n.fieldIndexByKey[ident]
if !ok {
return fmt.Errorf("sqlz/named: field not found: '%s' (maybe unexported?)", ident)
}
v, err := argValue.FieldByIndexErr(index)
if err != nil {
return fmt.Errorf("sqlz/named: field is nil pointer: '%s'", ident)
}
n.args = append(n.args, n.structValue(v))
}
return nil
}
// bindMapArgs maps idents to the argValue map keys, binding their values,
// binded args may have slices, meaning an "IN" clause.
func (n *namedQuery) bindMapArgs(idents []string, argValue reflect.Value) error {
m, err := assertMap(argValue.Interface())
if err != nil {
return err
}
if n.args == nil {
n.args = make([]any, 0, len(idents))
}
for _, ident := range idents {
value, ok := getMapValue(ident, m)
if !ok {
return fmt.Errorf("sqlz/named: could not find '%s' in %+v", ident, m)
}
n.args = append(n.args, value)
}
return nil
}
func (n *namedQuery) processSlice(query string, sliceValue reflect.Value) error {
if sliceValue.Len() == 0 {
return fmt.Errorf("sqlz/named: slice is zero length: %s", sliceValue.Type())
}
elType := reflectutil.Deref(sliceValue.Type().Elem())
switch elType.Kind() {
case reflect.Map:
return n.bindSliceArgs(query, sliceValue, n.bindMapArgs)
case reflect.Struct:
return n.bindSliceArgs(query, sliceValue, n.bindStructArgs)
default:
return fmt.Errorf("sqlz/named: unsupported slice type: %s", sliceValue.Type())
}
}
func (n *namedQuery) bindSliceArgs(
query string,
sliceValue reflect.Value,
fn func(idents []string, argValue reflect.Value) error,
) (err error) {
idents := parser.ParseIdents(n.bind, query)
if n.args == nil {
n.args = make([]any, 0, len(idents)*sliceValue.Len())
}
for i := range sliceValue.Len() {
if err := fn(idents, sliceValue.Index(i)); err != nil {
return err
}
}
// if bind is '?', parse query before expanding
if n.bind == parser.BindQuestion {
n.query = parser.ParseQuery(n.bind, query)
n.query, err = expandInsertSyntax(n.query, sliceValue.Len())
return err
}
n.query, err = expandInsertSyntax(query, sliceValue.Len())
if err != nil {
return err
}
n.query = parser.ParseQuery(n.bind, n.query)
return nil
}
var regValues = regexp.MustCompile(`(?i)\)\s*VALUES\s*\(`)
// expandInsertSyntax multiply the 'VALUES' part of a INSERT query by count.
func expandInsertSyntax(query string, count int) (string, error) {
loc := regValues.FindStringIndex(query)
if loc == nil {
return "", fmt.Errorf("sqlz/named: slice is only supported in INSERT query with 'VALUES' clause")
}
openIdx := loc[1] - 1
closeIdx := endingParensIndex(query[openIdx:])
if closeIdx == -1 {
return "", fmt.Errorf("sqlz/named: could not parse batch INSERT, missing ending parenthesis")
}
closeIdx += openIdx + 1
beginning := query[:closeIdx]
values := strings.Repeat(","+query[openIdx:closeIdx], count-1)
ending := query[closeIdx:]
return beginning + values + ending, nil
}
// endingParensIndex find the ending parenthesis of a string starting with '(',
// returns -1 if not found.
//
// endingParensIndex("(NOW())") // Output: 6
func endingParensIndex(s string) int {
if len(s) <= 1 || s[0] != '(' {
return -1
}
count := 0
for i, ch := range s {
if ch == '(' {
count++
continue
}
if ch == ')' {
count--
if count == 0 {
return i
}
}
}
return -1
}