-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscan_struct.go
More file actions
390 lines (363 loc) · 10.2 KB
/
scan_struct.go
File metadata and controls
390 lines (363 loc) · 10.2 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
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
package sqlpro
import (
"database/sql"
"encoding/json"
"reflect"
"time"
"github.com/pkg/errors"
)
var (
typeTime = reflect.TypeOf(time.Time{})
typeRawMessage = reflect.TypeOf(json.RawMessage(nil))
sharedVoidScan = &voidScan{}
)
// scanKind classifies how a result column maps onto a struct field. It is
// derived once from the field's static type so the per-row loop needs no
// type discovery.
type scanKind uint8
const (
kindSkip scanKind = iota // column not mapped to any field
kindDirect // scan straight into the field's address
kindString
kindInt64
kindFloat64
kindBool
kindTime
kindJson // db:",json" tag
kindRaw // json.RawMessage
)
// colPlan is the precomputed scan plan for one result column against a struct
// row type. It is built once per Scan() (slice-of-struct mode) and reused for
// every row, so the per-row work does no FieldByName lookup, no type discovery,
// and (for the null-scanner kinds) no per-row allocation.
type colPlan struct {
kind scanKind
index []int // struct field index path, for FieldByIndex
ptr bool // the field is a pointer
jsonIgnoreError bool
scanner any // reused null-scanner instance (kindString..kindRaw)
}
func isUintKind(k reflect.Kind) bool {
switch k {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return true
}
return false
}
func isIntKind(k reflect.Kind) bool {
switch k {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return true
}
return isUintKind(k)
}
// buildColPlan maps each result column to a struct field and the cheapest way
// to scan it. Each null-scanner kind gets one reused scanner instance.
func buildColPlan(cols []string, info structInfo) []colPlan {
plan := make([]colPlan, len(cols))
for i, col := range cols {
finfo, ok := info[col]
if !ok {
plan[i].kind = kindSkip
continue
}
p := &plan[i]
p.index = finfo.structField.Index
p.jsonIgnoreError = finfo.jsonIgnoreError
ft := finfo.structField.Type
p.ptr = ft.Kind() == reflect.Ptr
et := ft
if p.ptr {
et = et.Elem()
}
switch {
case finfo.isJson:
p.kind = kindJson
p.scanner = &NullJson{}
case ft == typeRawMessage || et == typeRawMessage:
p.kind = kindRaw
p.scanner = &NullRawMessage{}
case et.Kind() == reflect.String:
p.kind = kindString
p.scanner = &sql.NullString{}
case isIntKind(et.Kind()):
p.kind = kindInt64
p.scanner = &sql.NullInt64{}
case et.Kind() == reflect.Float32 || et.Kind() == reflect.Float64:
p.kind = kindFloat64
p.scanner = &sql.NullFloat64{}
case et.Kind() == reflect.Bool:
p.kind = kindBool
p.scanner = &sql.NullBool{}
case et == typeTime:
p.kind = kindTime
p.scanner = &NullTime{}
default:
p.kind = kindDirect
}
}
return plan
}
// resetScanner clears the two custom scanners whose Scan() does not reset on a
// NULL/empty value; reusing them across rows would otherwise leak the previous
// row's value. The stdlib sql.Null* scanners and NullTime reset themselves.
func resetScanner(p *colPlan) {
switch p.kind {
case kindJson:
s := p.scanner.(*NullJson)
s.Valid, s.Data = false, nil
case kindRaw:
s := p.scanner.(*NullRawMessage)
s.Valid, s.Data = false, nil
}
}
// readbackCol copies one reused scanner's value into the struct field. It always
// copies by value (never captures the address of a reused scanner's field), so
// the next row's Scan cannot corrupt an already-stored value.
func readbackCol(fieldV reflect.Value, p *colPlan) error {
switch p.kind {
case kindString:
s := p.scanner.(*sql.NullString)
if p.ptr {
if s.Valid {
nv := reflect.New(fieldV.Type().Elem())
nv.Elem().SetString(s.String)
fieldV.Set(nv)
} else {
fieldV.SetZero()
}
} else {
fieldV.SetString(s.String)
}
case kindInt64:
s := p.scanner.(*sql.NullInt64)
if p.ptr {
if s.Valid {
nv := reflect.New(fieldV.Type().Elem())
if isUintKind(nv.Elem().Kind()) {
nv.Elem().SetUint(uint64(s.Int64))
} else {
nv.Elem().SetInt(s.Int64)
}
fieldV.Set(nv)
} else {
fieldV.SetZero()
}
} else if isUintKind(fieldV.Kind()) {
fieldV.SetUint(uint64(s.Int64))
} else {
fieldV.SetInt(s.Int64)
}
case kindFloat64:
s := p.scanner.(*sql.NullFloat64)
if p.ptr {
if s.Valid {
nv := reflect.New(fieldV.Type().Elem())
nv.Elem().SetFloat(s.Float64)
fieldV.Set(nv)
} else {
fieldV.SetZero()
}
} else {
fieldV.SetFloat(s.Float64)
}
case kindBool:
s := p.scanner.(*sql.NullBool)
if p.ptr {
if s.Valid {
nv := reflect.New(fieldV.Type().Elem())
nv.Elem().SetBool(s.Bool)
fieldV.Set(nv)
} else {
fieldV.SetZero()
}
} else {
fieldV.SetBool(s.Bool)
}
case kindTime:
s := p.scanner.(*NullTime)
if p.ptr {
if s.Valid {
nv := reflect.New(typeTime)
nv.Elem().Set(reflect.ValueOf(s.Time))
fieldV.Set(nv)
} else {
fieldV.SetZero()
}
} else if s.Valid {
fieldV.Set(reflect.ValueOf(s.Time))
} else {
fieldV.SetZero()
}
case kindRaw:
s := p.scanner.(*NullRawMessage)
if s.Valid {
d := append([]byte(nil), s.Data...) // copy: scanner data is reused/reset
if p.ptr {
nv := reflect.New(fieldV.Type().Elem())
nv.Elem().SetBytes(d)
fieldV.Set(nv)
} else {
fieldV.SetBytes(d)
}
} else {
fieldV.SetZero()
}
case kindJson:
s := p.scanner.(*NullJson)
if s.Valid {
nv := reflect.New(fieldV.Type())
if err := json.Unmarshal(s.Data, nv.Interface()); err != nil {
if !p.jsonIgnoreError {
return errors.Wrapf(err, "Error unmarshalling data: %q", string(s.Data))
}
}
fieldV.Set(nv.Elem())
} else {
fieldV.SetZero()
}
}
return nil
}
// scalarScanKind classifies a slice element type for the scalar-slice fast
// path. It matches only the predeclared scalar types (and time.Time), exactly
// like the concrete-type switches in scanRow: named types such as
// "type ID int64" keep using the generic path (direct scan, no null-scanner).
// ok is false for types the fast path does not handle.
func scalarScanKind(baseType reflect.Type, isPtr bool) (kind scanKind, ok bool) {
if baseType == typeTime {
// []*time.Time keeps the generic path: it scans through the
// dereferenced struct, so a NULL yields a non-nil pointer to a zero
// time there — the fast path would yield nil instead.
return kindTime, !isPtr
}
if baseType.PkgPath() != "" {
return 0, false
}
switch baseType.Kind() {
case reflect.String:
return kindString, true
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return kindInt64, true
case reflect.Float32, reflect.Float64:
return kindFloat64, true
case reflect.Bool:
return kindBool, true
}
return 0, false
}
// scanScalarSlice scans the first column of every row into target, a slice of
// predeclared scalar values ([]int64, []string, []*int64, []time.Time, ...).
// The null-scanner and the scan-destination buffer are allocated once and
// reused for every row; columns past the first are ignored, as in scanRow.
// This is the fast path for the common "SELECT id FROM ..." bulk query.
func scanScalarSlice(target reflect.Value, elemType reflect.Type, elemIsPtr bool, kind scanKind, rows *sql.Rows) error {
cols, err := rows.Columns()
if err != nil {
return err
}
var scanner any
switch kind {
case kindString:
scanner = &sql.NullString{}
case kindInt64:
scanner = &sql.NullInt64{}
case kindFloat64:
scanner = &sql.NullFloat64{}
case kindBool:
scanner = &sql.NullBool{}
case kindTime:
scanner = &NullTime{}
}
// Only the first column maps onto the value, the rest is discarded.
data := make([]any, len(cols))
if len(cols) > 0 {
data[0] = scanner
}
for i := 1; i < len(cols); i++ {
data[i] = sharedVoidScan
}
p := &colPlan{kind: kind, ptr: elemIsPtr, scanner: scanner}
// Work on a local slice header and write it back to the target once (and
// on error, so rows scanned before a failure stay visible, as in the
// generic path).
slice := target
for rows.Next() {
if err := rows.Scan(data...); err != nil {
target.Set(slice)
return err
}
slice = reflect.Append(slice, reflect.Zero(elemType))
if len(cols) == 0 {
continue
}
if err := readbackCol(slice.Index(slice.Len()-1), p); err != nil {
target.Set(slice)
return err
}
}
target.Set(slice)
return rows.Err()
}
// scanStructSlice scans every row into target, a slice of struct or *struct.
// The column plan, the scan-destination buffer and the null-scanners are built
// once and reused across all rows; only the new element itself is allocated per
// row. This is the fast path for the common []*Struct / []Struct query.
func scanStructSlice(target reflect.Value, structType reflect.Type, elemIsPtr bool, rows *sql.Rows) error {
cols, err := rows.Columns()
if err != nil {
return err
}
plan := buildColPlan(cols, getStructInfo(structType))
data := make([]any, len(cols))
elemType := target.Type().Elem()
for rows.Next() {
// Grow the destination by one and obtain the new, addressable element
// (reflect.Append amortizes the backing growth).
target.Set(reflect.Append(target, reflect.Zero(elemType)))
elemV := target.Index(target.Len() - 1)
structV := elemV
if elemIsPtr {
structV = reflect.New(structType)
elemV.Set(structV)
structV = structV.Elem()
}
// Bind scan destinations: reused scanners for null-scanner columns,
// the field address itself for direct columns.
for i := range plan {
p := &plan[i]
switch p.kind {
case kindSkip:
data[i] = sharedVoidScan
case kindDirect:
fieldV := structV.FieldByIndex(p.index)
if p.ptr {
if fieldV.IsNil() {
fieldV.Set(reflect.New(fieldV.Type().Elem()))
}
data[i] = fieldV.Interface()
} else {
data[i] = fieldV.Addr().Interface()
}
default:
resetScanner(p)
data[i] = p.scanner
}
}
if err := rows.Scan(data...); err != nil {
return err
}
// Read back the null-scanner columns into the struct fields.
for i := range plan {
p := &plan[i]
if p.kind == kindSkip || p.kind == kindDirect {
continue
}
if err := readbackCol(structV.FieldByIndex(p.index), p); err != nil {
return err
}
}
}
return rows.Err()
}