-
Notifications
You must be signed in to change notification settings - Fork 1
/
querying.go
474 lines (390 loc) · 11.2 KB
/
querying.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package gos
import (
"context"
"database/sql"
"fmt"
"reflect"
"strings"
"github.com/mitranim/refut"
)
/*
Executes an SQL query and prepares a `Scanner` that can decode individual rows
into structs or scalars. A `Scanner` is used similarly to `*sql.Rows`, but
automatically maps columns to struct fields. Just like `*sql.Rows`, this avoids
buffering all results in memory, which is especially useful for large sets.
The returned scanner MUST be closed after finishing.
Example:
scan, err := QueryScanner(ctx, conn, query, args)
panic(err)
defer scan.Close()
for scan.Next() {
var result ResultType
err := scan.Scan(&result)
panic(err)
}
*/
func QueryScanner(ctx context.Context, conn Queryer, query string, args []interface{}) (Scanner, error) {
rows, err := conn.QueryContext(ctx, query, args...)
if err != nil {
return nil, Err{While: `querying rows`, Cause: err}
}
return &scanner{Rows: rows}, nil
}
/*
Shortcut for scanning columns into the destination, which may be one of:
* Nil interface{}.
* Nil pointer.
* Pointer to single scalar.
* Pointer to slice of scalars.
* Pointer to single struct.
* Pointer to slice of structs.
When the output is nil interface{} or nil pointer, this calls
`conn.ExecContext`, discarding the result.
When the output is a slice, the query should use a small `limit`. When
processing a large data set, prefer `QueryScanner()` to scan rows one-by-one
without buffering the result.
If the destination is a non-slice, there must be exactly one row. Less or more
will result in an error. If the destination is a struct, this will decode
columns into struct fields, following the rules outlined above in the package
overview.
The `select` part of the query should follow the common convention for selecting
nested fields, see below.
type Inner struct {
InnerValue string `db:"inner_value"`
}
type OuterValue struct {
Inner Inner `db:"inner"`
OuterValue string `db:"outer_value"`
}
The query should have:
select
outer_value as "outer_value",
(inner).inner_value as "inner.inner_value"
The easiest way to generate the query correctly is by calling `sqlb.Cols(dest)`,
using the sibling package "github.com/mitranim/sqlb".
*/
func Query(ctx context.Context, conn QueryExecer, dest interface{}, query string, args []interface{}) error {
if isNilDest(dest) {
_, err := conn.ExecContext(ctx, query, args...)
if err != nil {
return Err{While: `executing query`, Cause: err}
}
return nil
}
err := validateDestPtr(dest)
if err != nil {
return err
}
scan, err := QueryScanner(ctx, conn, query, args)
if err != nil {
return err
}
defer scan.Close()
if expectManyRows(dest) {
return scanMany(dest, scan)
}
return scanOne(dest, scan)
}
/* Internal */
const expectedStructDepth = 8
type tDestSpec struct {
colNames []string
colRtypes map[string]reflect.Type
typeSpec tTypeSpec
}
type tTypeSpec struct {
rtype reflect.Type
fieldSpecs []tFieldSpec
}
type tFieldSpec struct {
parentFieldSpec *tFieldSpec
typeSpec tTypeSpec
fieldIndex int
fieldPath []int // Relative to root struct.
colName string
uniqColAlias string
colIndex int // Must be initialized to -1.
sfield reflect.StructField
}
type tDecodeState struct {
colPtrs []interface{}
}
func scanMany(dest interface{}, scan Scanner) error {
rval := reflect.ValueOf(dest)
sliceRval := refut.RvalDerefAlloc(rval)
truncateSliceRval(sliceRval)
elemRtype := rtypeDerefElem(rval.Type())
for scan.Next() {
ptrRval := reflect.New(elemRtype)
err := scan.Scan(ptrRval.Interface())
if err != nil {
return err
}
sliceRval.Set(reflect.Append(sliceRval, ptrRval.Elem()))
}
return nil
}
func scanOne(dest interface{}, scan Scanner) error {
if !scan.Next() {
err := scan.Err()
if err != nil {
return Err{While: `preparing row`, Cause: err}
}
return ErrNoRows.while(`preparing row`)
}
err := scan.Scan(dest)
if err != nil {
return err
}
if scan.Next() {
return ErrMultipleRows.while(`verifying row count`)
}
return nil
}
type scanner struct {
*sql.Rows
rtype reflect.Type
spec *tDestSpec
}
func (self *scanner) Scan(dest interface{}) error {
rval := reflect.ValueOf(dest)
err := validateDestPtr(dest)
if err != nil {
return err
}
rtype := rval.Type()
if self.rtype == nil {
self.rtype = rtype
} else {
err := validateMatchingDestType(self.rtype, rtype)
if err != nil {
return err
}
}
if isRtypeStructNonScannable(rtype) {
return self.scanStruct(rval)
}
return self.scanScalar(dest)
}
func (self *scanner) scanStruct(rval reflect.Value) error {
if self.spec == nil {
spec, err := prepareDestSpec(self.Rows, self.rtype)
if err != nil {
return err
}
self.spec = spec
}
state, err := prepareDecodeState(self.Rows, self.spec)
if err != nil {
return err
}
err = self.Rows.Scan(state.colPtrs...)
if err != nil {
return ErrScan.because(err)
}
return traverseDecode(rval, self.spec, state, &self.spec.typeSpec, nil)
}
func (self *scanner) scanScalar(dest interface{}) error {
err := self.Rows.Scan(dest)
if err != nil {
return ErrScan.because(err)
}
return nil
}
func prepareDestSpec(rows *sql.Rows, rtype reflect.Type) (*tDestSpec, error) {
if rtype == nil || rtype.Kind() != reflect.Ptr || rtypeDerefKind(rtype) != reflect.Struct {
return nil, Err{
Code: ErrCodeInvalidDest,
While: `preparing destination spec`,
Cause: fmt.Errorf(`expected destination type to be a struct pointer, got %q`, rtype),
}
}
colNames, err := rows.Columns()
if err != nil {
return nil, Err{While: `getting columns`, Cause: err}
}
spec := &tDestSpec{
typeSpec: tTypeSpec{rtype: rtype},
colNames: colNames,
colRtypes: map[string]reflect.Type{},
}
colPath := make([]string, 0, expectedStructDepth)
fieldPath := make([]int, 0, expectedStructDepth)
err = traverseMakeSpec(spec, &spec.typeSpec, nil, colPath, fieldPath)
if err != nil {
return nil, err
}
for _, colName := range colNames {
if spec.colRtypes[colName] == nil {
return nil, Err{
Code: ErrCodeNoColDest,
While: `preparing destination spec`,
Cause: fmt.Errorf(`column %q doesn't have a matching destination in type %q`, colName, rtype),
}
}
}
return spec, nil
}
func prepareDecodeState(rows *sql.Rows, spec *tDestSpec) (*tDecodeState, error) {
colPtrs := make([]interface{}, 0, len(spec.colNames))
for _, colName := range spec.colNames {
if spec.colRtypes[colName] == nil {
return nil, Err{
Code: ErrCodeNoColDest,
While: `preparing decode state`,
Cause: fmt.Errorf(`column %q doesn't have a matching destination in type %q`,
colName, spec.typeSpec.rtype),
}
}
colPtrs = append(colPtrs, reflect.New(reflect.PtrTo(spec.colRtypes[colName])).Interface())
}
return &tDecodeState{colPtrs: colPtrs}, nil
}
func traverseMakeSpec(
spec *tDestSpec, typeSpec *tTypeSpec, parentFieldSpec *tFieldSpec, colPath []string, fieldPath []int,
) error {
rtypeElem := refut.RtypeDeref(typeSpec.rtype)
typeSpec.fieldSpecs = make([]tFieldSpec, rtypeElem.NumField())
for i := 0; i < rtypeElem.NumField(); i++ {
sfield := rtypeElem.Field(i)
fieldRtype := refut.RtypeDeref(sfield.Type)
fieldPath := append(fieldPath, i)
fieldSpec := &typeSpec.fieldSpecs[i]
*fieldSpec = tFieldSpec{
parentFieldSpec: parentFieldSpec,
typeSpec: tTypeSpec{rtype: sfield.Type},
fieldIndex: i,
fieldPath: copyIntSlice(fieldPath),
colIndex: -1,
sfield: sfield,
}
if !refut.IsSfieldExported(sfield) {
continue
}
if sfield.Anonymous && fieldRtype.Kind() == reflect.Struct {
err := traverseMakeSpec(spec, &fieldSpec.typeSpec, fieldSpec, colPath, fieldPath)
if err != nil {
return err
}
continue
}
fieldSpec.colName = sfieldColumnName(sfield)
if fieldSpec.colName == "" {
continue
}
colPath := append(colPath, fieldSpec.colName)
fieldSpec.uniqColAlias = strings.Join(colPath, ".")
fieldSpec.colIndex = stringIndex(spec.colNames, fieldSpec.uniqColAlias)
if spec.colRtypes[fieldSpec.uniqColAlias] != nil {
return Err{
Code: ErrCodeRedundantCol,
While: `preparing destination spec`,
Cause: fmt.Errorf(`redundant occurrence of column %q`, fieldSpec.uniqColAlias),
}
}
spec.colRtypes[fieldSpec.uniqColAlias] = sfield.Type
if isRtypeStructNonScannable(fieldRtype) {
err := traverseMakeSpec(spec, &fieldSpec.typeSpec, fieldSpec, colPath, fieldPath)
if err != nil {
return err
}
}
}
return nil
}
func traverseDecode(
rootRval reflect.Value, spec *tDestSpec, state *tDecodeState, typeSpec *tTypeSpec, fieldSpec *tFieldSpec,
) error {
everyColValueIsNil := true
for i := range typeSpec.fieldSpecs {
fieldSpec := &typeSpec.fieldSpecs[i]
sfield := fieldSpec.sfield
fieldRtype := refut.RtypeDeref(sfield.Type)
if !refut.IsSfieldExported(sfield) {
continue
}
if sfield.Anonymous && fieldRtype.Kind() == reflect.Struct {
err := traverseDecode(rootRval, spec, state, &fieldSpec.typeSpec, fieldSpec)
if err != nil {
return err
}
continue
}
if fieldSpec.colName == "" {
continue
}
if isRtypeStructNonScannable(fieldRtype) {
err := traverseDecode(rootRval, spec, state, &fieldSpec.typeSpec, fieldSpec)
if err != nil {
return err
}
continue
}
if !(fieldSpec.colIndex >= 0) {
continue
}
colRval := reflect.ValueOf(state.colPtrs[fieldSpec.colIndex]).Elem()
if !colRval.IsNil() {
everyColValueIsNil = false
}
}
isNested := fieldSpec != nil
if everyColValueIsNil && isNested && isNilableOrHasNilableNonRootAncestor(fieldSpec) {
return nil
}
for _, fieldSpec := range typeSpec.fieldSpecs {
if !(fieldSpec.colIndex >= 0) {
continue
}
sfield := fieldSpec.sfield
colRval := reflect.ValueOf(state.colPtrs[fieldSpec.colIndex]).Elem()
if colRval.IsNil() {
if refut.IsRkindNilable(sfield.Type.Kind()) {
rvalZeroAtPath(rootRval, fieldSpec.fieldPath)
continue
}
fieldRval := refut.RvalFieldByPathAlloc(rootRval, fieldSpec.fieldPath)
scanner, ok := fieldRval.Addr().Interface().(sql.Scanner)
if ok {
err := scanner.Scan(nil)
if err != nil {
return Err{Code: ErrCodeScan, While: `scanning into field`, Cause: err}
}
continue
}
return Err{
Code: ErrCodeNull,
While: `decoding into struct`,
Cause: fmt.Errorf(`type %q at field %q of struct %q is not nilable, but corresponding column %q was null`,
sfield.Type, sfield.Name, typeSpec.rtype, fieldSpec.uniqColAlias),
}
}
set(refut.RvalFieldByPathAlloc(rootRval, fieldSpec.fieldPath), colRval.Elem())
}
return nil
}
func isNilDest(val interface{}) bool {
if val == nil {
return true
}
rval := reflect.ValueOf(val)
return rval.Kind() == reflect.Ptr && rval.IsNil()
}
func validateDestPtr(val interface{}) error {
rval := reflect.ValueOf(val)
if rval.Kind() != reflect.Ptr || rval.IsNil() {
return ErrInvalidDest.because(fmt.Errorf(
`destination must be non-nil pointer, received %#v`, val,
))
}
return nil
}
func validateMatchingDestType(expected, found reflect.Type) error {
if expected != found {
return ErrInvalidDest.because(fmt.Errorf(`destination must be of type %v, received %v`, expected, found))
}
return nil
}
func expectManyRows(val interface{}) bool {
return rtypeDerefKind(reflect.TypeOf(val)) == reflect.Slice
}