This repository has been archived by the owner on Feb 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmake_query.go
420 lines (387 loc) · 12.3 KB
/
make_query.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package sqlr
import (
"database/sql"
"fmt"
"reflect"
"github.com/jjeffery/kv"
"github.com/jjeffery/sqlr/dataloader"
)
func makeQuery(funcType reflect.Type, schema *Schema) (func(*Session) reflect.Value, error) {
if f := schema.funcMap.lookup(funcType); f != nil {
return f, nil
}
for _, maker := range []func(reflect.Type, *Schema) (func(*Session) reflect.Value, error){
selectFunc,
getOneFunc,
getManyFunc,
loadOneFunc,
} {
f, err := maker(funcType, schema)
if err != nil {
return nil, err
}
if f != nil {
f = schema.funcMap.add(funcType, f)
return f, nil
}
}
return nil, newError("cannot recognize function: %v", funcType.String())
}
// selectFunc returns a func implementation if the func is a select func.
// input args alternatives:
// (query string, args ...interface{})
// output args alternatives:
// ([]*Row, error)
// (*Row, error)
// (int, error)
// (int64, error)
// Returns nil if not a match, returns error if the function looks like a query
// but is not quite conformant.
func selectFunc(funcType reflect.Type, schema *Schema) (func(*Session) reflect.Value, error) {
if funcType.NumIn() < 1 {
return nil, nil // not a select function
}
if funcType.In(0) != wellKnownTypes.stringType {
return nil, nil // not a select function
}
if funcType.NumIn() == 1 {
return nil, nil
}
const invalidInputsMsg = "expect query function inputs to be like (query string, args ...interface{})"
if funcType.NumIn() != 2 {
return nil, newError(invalidInputsMsg)
}
if funcType.In(1) != wellKnownTypes.sliceOfInterfaceType {
return nil, newError(invalidInputsMsg)
}
rowTypeName := "Row" // don't know the type yet
invalidOutputsMsg := fmt.Sprintf("MakeQuery: expect query function outputs to be like ([]*%s, error) or (*%s, error)", rowTypeName, rowTypeName)
if funcType.NumOut() != 2 {
return nil, newError(invalidOutputsMsg)
}
if funcType.Out(1) != wellKnownTypes.errorType {
return nil, newError(invalidOutputsMsg)
}
rowType := funcType.Out(0)
switch rowType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return makeSelectIntFunc(funcType), nil
}
if rowType.Kind() == reflect.Slice {
rowType = rowType.Elem()
}
if rowType.Kind() == reflect.Ptr {
rowType = rowType.Elem()
}
if rowType.Kind() != reflect.Struct {
return nil, newError("expected struct type, got %v", rowType.String())
}
tbl := schema.TableFor(rowType)
rowPtrType := reflect.PtrTo(rowType)
if funcType.Out(0) == rowPtrType {
return makeSelectRowFunc(funcType, tbl), nil
}
sliceOfRowPtrType := reflect.SliceOf(rowPtrType)
if funcType.Out(0) == sliceOfRowPtrType {
return makeSelectRowsFunc(funcType, tbl), nil
}
return nil, newError(invalidOutputsMsg)
}
func makeSelectIntFunc(funcType reflect.Type) func(*Session) reflect.Value {
return func(sess *Session) reflect.Value {
return reflect.MakeFunc(funcType, func(args []reflect.Value) []reflect.Value {
intType := funcType.Out(0)
intPtrValue := reflect.New(intType)
query := args[0].Interface().(string)
queryArgs := args[1].Interface().([]interface{})
rows, err := sess.Query(query, queryArgs...)
if err != nil {
err = kv.Wrap(err, "cannot query").With(
"query", query,
"args", queryArgs,
)
return []reflect.Value{
intPtrValue.Elem(),
errorValueFor(err),
}
}
defer rows.Close()
if !rows.Next() {
return []reflect.Value{
intPtrValue.Elem(),
errorValueFor(sql.ErrNoRows),
}
}
if err := rows.Scan(intPtrValue.Interface()); err != nil {
return []reflect.Value{
intPtrValue.Elem(),
errorValueFor(err),
}
}
if err := rows.Err(); err != nil {
return []reflect.Value{
intPtrValue.Elem(),
errorValueFor(err),
}
}
return []reflect.Value{
intPtrValue.Elem(),
wellKnownTypes.nilErrorValue,
}
})
}
}
func makeSelectRowsFunc(funcType reflect.Type, tbl *Table) func(*Session) reflect.Value {
return func(sess *Session) reflect.Value {
return reflect.MakeFunc(funcType, func(args []reflect.Value) []reflect.Value {
rowsPtrValue := reflect.New(reflect.SliceOf(reflect.PtrTo(tbl.RowType())))
query := args[0].Interface().(string)
queryArgs := args[1].Interface().([]interface{})
_, err := sess.Select(rowsPtrValue.Interface(), query, queryArgs...)
if err != nil {
err = kv.Wrap(err, "cannot query rows").With(
"rowType", tbl.RowType(),
"query", query,
"args", queryArgs,
)
}
rowsValue := rowsPtrValue.Elem()
errValue := errorValueFor(err)
return []reflect.Value{
rowsValue,
errValue,
}
})
}
}
func makeSelectRowFunc(funcType reflect.Type, tbl *Table) func(*Session) reflect.Value {
return func(sess *Session) reflect.Value {
return reflect.MakeFunc(funcType, func(args []reflect.Value) []reflect.Value {
rowPtrValue := reflect.New(tbl.RowType())
query := args[0].Interface().(string)
queryArgs := args[1].Interface().([]interface{})
n, err := sess.Select(rowPtrValue.Interface(), query, queryArgs...)
if err != nil {
err = kv.Wrap(err, "cannot query one row").With(
"rowType", tbl.RowType(),
"query", query,
"args", queryArgs,
)
rowPtrValue = reflect.Zero(reflect.PtrTo(tbl.RowType()))
}
if n == 0 {
// no rows returned
rowPtrValue = reflect.Zero(reflect.PtrTo(tbl.RowType()))
}
return []reflect.Value{
rowPtrValue,
errorValueFor(err),
}
})
}
}
func getOneFunc(funcType reflect.Type, schema *Schema) (func(*Session) reflect.Value, error) {
if funcType.NumIn() != 1 {
return nil, nil
}
if funcType.NumOut() != 2 {
return nil, nil
}
if funcType.In(0).Kind() == reflect.Slice {
return nil, nil
}
if funcType.Out(1) != wellKnownTypes.errorType {
return nil, newError("expecting second return arg to be error")
}
rowType := funcType.Out(0)
if rowType.Kind() != reflect.Ptr {
return nil, newError("expecting first return arg to be a pointer to struct")
}
rowType = rowType.Elem()
if rowType.Kind() != reflect.Struct {
return nil, newError("expecting first return arg to be a pointer to struct")
}
tbl := schema.TableFor(rowType)
if len(tbl.PrimaryKey()) == 0 {
}
pkCol, err := getPKCol(tbl)
if err != nil {
return nil, err
}
inType := funcType.In(0)
if inType != pkCol.info.Field.Type {
return nil, newError("looks like a get func, but %s has primary key type of %s", tbl.RowType().String(), pkCol.info.Field.Type.String())
}
return makeGetOneFunc(funcType, tbl), nil
}
func makeGetOneFunc(funcType reflect.Type, tbl *Table) func(*Session) reflect.Value {
return func(sess *Session) reflect.Value {
return reflect.MakeFunc(funcType, func(args []reflect.Value) []reflect.Value {
rowPtrValue := reflect.New(tbl.RowType())
query := fmt.Sprintf("select {} from %s where {}", tbl.Name())
queryArgs := []interface{}{args[0].Interface()}
n, err := sess.Select(rowPtrValue.Interface(), query, queryArgs...)
if err != nil {
err = kv.Wrap(err, "cannot get one row").With(
"rowType", tbl.RowType(),
"query", query,
"args", queryArgs,
)
rowPtrValue = reflect.Zero(reflect.PtrTo(tbl.RowType()))
} else if n == 0 {
// nothing returned, so zero out the pointer
rowPtrValue = reflect.Zero(reflect.PtrTo(tbl.RowType()))
}
return []reflect.Value{
rowPtrValue,
errorValueFor(err),
}
})
}
}
func getManyFunc(funcType reflect.Type, schema *Schema) (func(*Session) reflect.Value, error) {
if funcType.NumIn() != 1 {
return nil, nil
}
if funcType.NumOut() != 2 {
return nil, nil
}
if funcType.In(0).Kind() != reflect.Slice {
return nil, nil
}
if funcType.Out(1) != wellKnownTypes.errorType {
return nil, newError("expecting second return arg to be error")
}
rowType := funcType.Out(0)
if rowType.Kind() != reflect.Slice {
return nil, newError("expecting first return arg to be a slice of pointer to struct")
}
rowType = rowType.Elem()
if rowType.Kind() != reflect.Ptr {
return nil, newError("expecting first return arg to be a slice of pointer to struct")
}
rowType = rowType.Elem()
if rowType.Kind() != reflect.Struct {
return nil, newError("expecting first return arg to be a slice of pointer to struct")
}
tbl := schema.TableFor(rowType)
pkCol, err := getPKCol(tbl)
if err != nil {
return nil, err
}
inType := funcType.In(0)
if inType != reflect.SliceOf(pkCol.info.Field.Type) {
return nil, newError("looks like a get func, but %s has primary key type of %s", tbl.RowType().String(), pkCol.info.Field.Type.String())
}
return makeGetManyFunc(funcType, tbl), nil
}
func makeGetManyFunc(funcType reflect.Type, tbl *Table) func(*Session) reflect.Value {
return func(sess *Session) reflect.Value {
return reflect.MakeFunc(funcType, func(args []reflect.Value) []reflect.Value {
var err error
rowsPtrValue := reflect.New(reflect.SliceOf(reflect.PtrTo(tbl.RowType())))
idsValue := args[0]
if idsValue.Len() > 0 {
pkColName := tbl.PrimaryKey()[0].Name()
query := fmt.Sprintf("select {} from %s where `%s` in (?)", tbl.Name(), pkColName)
ids := idsValue.Interface()
_, err = sess.Select(rowsPtrValue.Interface(), query, ids)
if err != nil {
err = kv.Wrap(err, "cannot get rows").With(
"rowType", tbl.RowType(),
"query", query,
"args", ids,
)
}
}
rowsValue := rowsPtrValue.Elem()
return []reflect.Value{
rowsValue,
errorValueFor(err),
}
})
}
}
func loadOneFunc(funcType reflect.Type, schema *Schema) (func(*Session) reflect.Value, error) {
if funcType.NumIn() != 1 {
return nil, nil
}
if funcType.NumOut() != 1 {
return nil, nil
}
if funcType.In(0).Kind() == reflect.Slice {
return nil, nil
}
thunkType := funcType.Out(0)
if thunkType.Kind() != reflect.Func {
return nil, newError("looks like a load function, but does not return a thunk (function): %s", funcType.String())
}
if thunkType.NumIn() != 0 {
return nil, newError("thunk function cannot accept arguments: %s", funcType.String())
}
invalidOutputsErr := newError("expect thunk to return a pointer to struct and an error)")
if thunkType.NumOut() != 2 {
return nil, invalidOutputsErr
}
if thunkType.Out(1) != wellKnownTypes.errorType {
return nil, invalidOutputsErr
}
rowType := thunkType.Out(0)
if rowType.Kind() != reflect.Ptr {
return nil, invalidOutputsErr
}
rowType = rowType.Elem()
if rowType.Kind() != reflect.Struct {
return nil, invalidOutputsErr
}
tbl := schema.TableFor(rowType)
pkCol, err := getPKCol(tbl)
if err != nil {
return nil, err
}
inType := funcType.In(0)
if inType != pkCol.info.Field.Type {
return nil, newError("looks like a load func, but %s has primary key type of %s", tbl.RowType().String(), pkCol.info.Field.Type.String())
}
return makeLoadOneFunc(funcType, tbl), nil
}
func makeLoadOneFunc(funcType reflect.Type, tbl *Table) func(*Session) reflect.Value {
return func(sess *Session) reflect.Value {
pkCol := tbl.PrimaryKey()[0]
queryFuncIn := []reflect.Type{reflect.SliceOf(pkCol.fieldType())}
queryFuncOut := []reflect.Type{reflect.SliceOf(reflect.PtrTo(tbl.RowType())), wellKnownTypes.errorType}
queryFuncType := reflect.FuncOf(queryFuncIn, queryFuncOut, false)
queryFuncValue := makeGetManyFunc(queryFuncType, tbl)(sess)
keyFuncIn := []reflect.Type{reflect.PtrTo(tbl.RowType())}
keyFuncOut := []reflect.Type{pkCol.fieldType()}
keyFuncType := reflect.FuncOf(keyFuncIn, keyFuncOut, false)
keyFuncValue := reflect.MakeFunc(keyFuncType, func(args []reflect.Value) []reflect.Value {
rowPtrValue := args[0]
rowValue := rowPtrValue.Elem()
keyValue := rowValue.FieldByIndex([]int(pkCol.fieldIndex()))
return []reflect.Value{keyValue}
})
loadFuncPtrValue := reflect.New(funcType)
dataloader.Make(loadFuncPtrValue.Interface(), queryFuncValue.Interface(), keyFuncValue.Interface())
return loadFuncPtrValue.Elem()
}
}
func getPKCol(tbl *Table) (*Column, error) {
pkCols := tbl.PrimaryKey()
if len(pkCols) > 1 {
return nil, newError("compositeprimary key not supported: %s", tbl.RowType().String())
}
if len(pkCols) == 0 {
return nil, newError("no primary key defined for %s (table %s)", tbl.RowType().String(), tbl.Name())
}
return pkCols[0], nil
}
type rowFuncError string
func newError(format string, args ...interface{}) rowFuncError {
msg := fmt.Sprintf(format, args...)
return rowFuncError(msg)
}
func (e rowFuncError) Error() string {
return string(e)
}