-
Notifications
You must be signed in to change notification settings - Fork 16
/
runner.go
405 lines (357 loc) · 11.9 KB
/
runner.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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package proteus
import (
"context"
"fmt"
"reflect"
"strings"
"database/sql"
"github.com/jonbodner/proteus/logger"
"github.com/jonbodner/proteus/mapper"
"github.com/jonbodner/stackerr"
)
func buildQueryArgs(c context.Context, funcArgs []reflect.Value, paramOrder []paramInfo) ([]interface{}, error) {
//walk through the rest of the input parameters and build a slice for args
var out []interface{}
for _, v := range paramOrder {
val, err := mapper.Extract(c, funcArgs[v.posInParams].Interface(), strings.Split(v.name, "."))
if err != nil {
return nil, err
}
if v.isSlice {
curSlice := reflect.ValueOf(val)
for i := 0; i < curSlice.Len(); i++ {
out = append(out, curSlice.Index(i).Interface())
}
} else {
out = append(out, val)
}
}
return out, nil
}
var (
errType = reflect.TypeOf((*error)(nil)).Elem()
errZero = reflect.Zero(errType)
zeroInt64 = reflect.ValueOf(int64(0))
zeroSQLResult = reflect.ValueOf((sql.Result)(nil))
sqlResultType = reflect.TypeOf((*sql.Result)(nil)).Elem()
)
func makeContextExecutorImplementation(c context.Context, funcType reflect.Type, query queryHolder, paramOrder []paramInfo) func(args []reflect.Value) []reflect.Value {
buildRetVals := makeExecutorReturnVals(funcType)
return func(args []reflect.Value) []reflect.Value {
executor := args[1].Interface().(ContextExecutor)
ctx := args[0].Interface().(context.Context)
// if the passed-in context doesn't contain any logging settings, use the one that were supplied
// at build time
if _, ok := logger.LevelFromContext(ctx); !ok {
if defaultLevel, ok := logger.LevelFromContext(c); ok {
ctx = logger.WithLevel(ctx, defaultLevel)
}
}
// copy over any logging values that were supplied at build time
if defaultVals, ok := logger.ValuesFromContext(c); ok {
ctx = logger.WithValues(ctx, defaultVals...)
}
var result sql.Result
finalQuery, err := query.finalize(ctx, args)
if err != nil {
return buildRetVals(result, err)
}
queryArgs, err := buildQueryArgs(ctx, args, paramOrder)
if err != nil {
return buildRetVals(result, err)
}
logger.Log(ctx, logger.DEBUG, fmt.Sprintln("calling", finalQuery, "with params", queryArgs))
result, err = executor.ExecContext(ctx, finalQuery, queryArgs...)
return buildRetVals(result, err)
}
}
func makeExecutorImplementation(c context.Context, funcType reflect.Type, query queryHolder, paramOrder []paramInfo) func(args []reflect.Value) []reflect.Value {
buildRetVals := makeExecutorReturnVals(funcType)
return func(args []reflect.Value) []reflect.Value {
executor := args[0].Interface().(Executor)
var result sql.Result
finalQuery, err := query.finalize(c, args)
if err != nil {
return buildRetVals(result, err)
}
queryArgs, err := buildQueryArgs(c, args, paramOrder)
if err != nil {
return buildRetVals(result, err)
}
logger.Log(c, logger.DEBUG, fmt.Sprintln("calling", finalQuery, "with params", queryArgs))
result, err = executor.Exec(finalQuery, queryArgs...)
return buildRetVals(result, err)
}
}
func makeExecutorReturnVals(funcType reflect.Type) func(sql.Result, error) []reflect.Value {
numOut := funcType.NumOut()
//handle the 0,1,2 out parameter cases
if numOut == 0 {
return func(sql.Result, error) []reflect.Value {
return []reflect.Value{}
}
}
sType := funcType.Out(0)
if numOut == 1 {
return func(result sql.Result, err error) []reflect.Value {
if err != nil {
if sType == sqlResultType {
return []reflect.Value{zeroSQLResult}
}
return []reflect.Value{zeroInt64}
}
if sType == sqlResultType {
return []reflect.Value{reflect.ValueOf(result)}
}
val, err := result.RowsAffected()
if err != nil {
return []reflect.Value{zeroInt64}
}
return []reflect.Value{reflect.ValueOf(val).Convert(sType)}
}
}
if numOut == 2 {
return func(result sql.Result, err error) []reflect.Value {
eType := funcType.Out(1)
if sType == sqlResultType {
if err != nil {
return []reflect.Value{zeroSQLResult, reflect.ValueOf(err).Convert(eType)}
}
return []reflect.Value{reflect.ValueOf(result), errZero}
}
if err != nil {
return []reflect.Value{zeroInt64, reflect.ValueOf(err).Convert(eType)}
}
val, err := result.RowsAffected()
if err != nil {
return []reflect.Value{zeroInt64, reflect.ValueOf(err).Convert(eType)}
}
return []reflect.Value{reflect.ValueOf(val).Convert(sType), errZero}
}
}
// impossible case since validation should happen first, but be safe
return func(result sql.Result, err error) []reflect.Value {
impossibleErr := reflect.ValueOf(stackerr.New("should never get here"))
if sType == sqlResultType {
return []reflect.Value{zeroSQLResult, impossibleErr}
}
return []reflect.Value{zeroInt64, impossibleErr}
}
}
func makeContextQuerierImplementation(c context.Context, funcType reflect.Type, query queryHolder, paramOrder []paramInfo) (func(args []reflect.Value) []reflect.Value, error) {
numOut := funcType.NumOut()
var builder mapper.Builder
var err error
if numOut > 0 {
builder, err = mapper.MakeBuilder(c, funcType.Out(0))
if err != nil {
return nil, err
}
}
buildRetVals := makeQuerierReturnVals(c, funcType, builder)
return func(args []reflect.Value) []reflect.Value {
querier := args[1].Interface().(ContextQuerier)
ctx := args[0].Interface().(context.Context)
// if the passed-in context doesn't contain any logging settings, use the one that were supplied
// at build time
if _, ok := logger.LevelFromContext(ctx); !ok {
if defaultLevel, ok := logger.LevelFromContext(c); ok {
ctx = logger.WithLevel(ctx, defaultLevel)
}
}
// copy over any logging values that were supplied at build time
if defaultVals, ok := logger.ValuesFromContext(c); ok {
ctx = logger.WithValues(ctx, defaultVals...)
}
var rows *sql.Rows
finalQuery, err := query.finalize(ctx, args)
if err != nil {
return buildRetVals(rows, err)
}
queryArgs, err := buildQueryArgs(ctx, args, paramOrder)
if err != nil {
return buildRetVals(rows, err)
}
logger.Log(ctx, logger.DEBUG, fmt.Sprintln("calling", finalQuery, "with params", queryArgs))
// going to work around the defective Go MySQL driver, which refuses to convert the text protocol properly.
// It is used when doing a query without parameters.
if len(queryArgs) == 0 {
type ContextPreparer interface {
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
}
if cp, ok := querier.(ContextPreparer); ok {
var stmt *sql.Stmt
stmt, err = cp.PrepareContext(ctx, finalQuery)
if err != nil {
return buildRetVals(rows, err)
}
defer stmt.Close()
rows, err = stmt.QueryContext(ctx)
return buildRetVals(rows, err)
}
}
rows, err = querier.QueryContext(ctx, finalQuery, queryArgs...)
return buildRetVals(rows, err)
}, nil
}
func makeQuerierImplementation(c context.Context, funcType reflect.Type, query queryHolder, paramOrder []paramInfo) (func(args []reflect.Value) []reflect.Value, error) {
numOut := funcType.NumOut()
var builder mapper.Builder
var err error
if numOut > 0 {
builder, err = mapper.MakeBuilder(c, funcType.Out(0))
if err != nil {
return nil, err
}
}
buildRetVals := makeQuerierReturnVals(c, funcType, builder)
return func(args []reflect.Value) []reflect.Value {
querier := args[0].Interface().(Querier)
var rows *sql.Rows
finalQuery, err := query.finalize(c, args)
if err != nil {
return buildRetVals(rows, err)
}
queryArgs, err := buildQueryArgs(c, args, paramOrder)
if err != nil {
return buildRetVals(rows, err)
}
logger.Log(c, logger.DEBUG, fmt.Sprintln("calling", finalQuery, "with params", queryArgs))
// going to work around the defective Go MySQL driver, which refuses to convert the text protocol properly.
// It is used when doing a query without parameters.
if len(queryArgs) == 0 {
type Preparer interface {
Prepare(query string) (*sql.Stmt, error)
}
if cp, ok := querier.(Preparer); ok {
var stmt *sql.Stmt
stmt, err = cp.Prepare(finalQuery)
if err != nil {
return buildRetVals(rows, err)
}
defer stmt.Close()
rows, err = stmt.Query()
return buildRetVals(rows, err)
}
}
rows, err = querier.Query(finalQuery, queryArgs...)
return buildRetVals(rows, err)
}, nil
}
func makeQuerierReturnVals(c context.Context, funcType reflect.Type, builder mapper.Builder) func(*sql.Rows, error) []reflect.Value {
numOut := funcType.NumOut()
//handle the 0,1,2 out parameter cases
if numOut == 0 {
return func(*sql.Rows, error) []reflect.Value {
return []reflect.Value{}
}
}
sType := funcType.Out(0)
qZero := reflect.Zero(sType)
if numOut == 1 {
return func(rows *sql.Rows, err error) []reflect.Value {
if err != nil {
return []reflect.Value{qZero}
}
// handle mapping
val, err := handleMapping(c, sType, rows, builder)
if err != nil {
return []reflect.Value{qZero}
}
if val == nil {
return []reflect.Value{qZero}
}
return []reflect.Value{reflect.ValueOf(val).Convert(sType)}
}
}
if numOut == 2 {
return func(rows *sql.Rows, err error) []reflect.Value {
eType := funcType.Out(1)
if err != nil {
return []reflect.Value{qZero, reflect.ValueOf(err).Convert(eType)}
}
// handle mapping
val, err := handleMapping(c, sType, rows, builder)
var eVal reflect.Value
if err == nil {
eVal = errZero
} else {
eVal = reflect.ValueOf(err).Convert(eType)
}
if val == nil {
return []reflect.Value{qZero, eVal}
}
return []reflect.Value{reflect.ValueOf(val).Convert(sType), eVal}
}
}
// impossible case since validation should happen first, but be safe
return func(*sql.Rows, error) []reflect.Value {
return []reflect.Value{qZero, reflect.ValueOf(stackerr.New("should never get here!"))}
}
}
func handleMapping(c context.Context, sType reflect.Type, rows *sql.Rows, builder mapper.Builder) (interface{}, error) {
var val interface{}
var err error
if sType.Kind() == reflect.Slice {
s := reflect.MakeSlice(sType, 0, 0)
var result interface{}
for {
result, err = mapRows(c, rows, builder)
if err != nil {
return nil, err
}
if result == nil {
break
}
s = reflect.Append(s, reflect.ValueOf(result))
}
val = s.Interface()
} else {
val, err = mapRows(c, rows, builder)
}
rows.Close()
return val, err
}
// Map takes the next value from Rows and uses it to create a new instance of the specified type
// If the type is a primitive and there are more than 1 values in the current row, only the first value is used.
// If the type is a map of string to interface, then the column names are the keys in the map and the values are assigned
// If the type is a struct that has prop tags on its fields, then any matching tags will be associated with values with the associate columns
// Any non-associated values will be set to the zero value
// If any columns cannot be assigned to any types, then an error is returned
// If next returns false, then nil is returned for both the interface and the error
// If an error occurs while processing the current row, nil is returned for the interface and the error is non-nil
// If a value is successfully extracted from the current row, the instance is returned and the error is nil
func mapRows(c context.Context, rows *sql.Rows, builder mapper.Builder) (interface{}, error) {
//fmt.Println(sType)
if rows == nil {
return nil, stackerr.New("rows must be non-nil")
}
if !rows.Next() {
if err := rows.Err(); err != nil {
return nil, err
}
return nil, nil
}
cols, err := rows.Columns()
if err != nil {
return nil, err
}
if len(cols) == 0 {
return nil, stackerr.New("No values returned from query")
}
vals := make([]interface{}, len(cols))
colTypes, err := rows.ColumnTypes()
if err != nil {
return nil, err
}
for i := 0; i < len(vals); i++ {
newVal := reflect.New(colTypes[i].ScanType()).Interface()
vals[i] = &newVal
}
err = rows.Scan(vals...)
if err != nil {
logger.Log(c, logger.WARN, "scan failed")
return nil, err
}
return builder(cols, vals)
}