-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.go
180 lines (169 loc) · 4.99 KB
/
scanner.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
package sqlz
import (
"context"
"database/sql"
"fmt"
"reflect"
)
// A Scanner is for scanning result sets from rows into a destination structure.
// It maintains an internal type cache for mapping struct fields to database columns.
// It's safe for concurrent use by multiple goroutines. The zero value is ready to use.
type Scanner struct {
tc cache
// IgnoreUnknownColumns controls whether Scan will return an error if a column in the result set has no corresponding struct field.
// Default is false (return an error).
IgnoreUnknownColumns bool
}
// Scan is for scanning the result set from rows into a destination structure.
// It supports scanning into a struct, a slice of structs, or a channel that emits structs.
//
// The destination (dest) must be a pointer to a struct, a pointer to a slice of structs, or a channel of structs.
// If the destination is a channel, Scan will send a struct for each row in the result set until the context is canceled
// or the result set is exhausted.
//
// The structure of the destination struct must match the structure of the result set. The field name or its `db` tag must match the column name.
// The field order does not need to match the column order. If a column has no corresponding struct field, Scan returns an error.
//
// Scan blocks until the context is canceled, the result set is exhausted, or an error occurs.
func (s *Scanner) Scan(ctx context.Context, rows Rows, dest any) error {
destValue := reflect.ValueOf(dest)
if kind := destValue.Kind(); kind == reflect.Chan {
return s.scanChan(ctx, destValue, rows)
} else if kind != reflect.Pointer {
panic("dest must be a pointer or chan")
}
elemValue := destValue.Elem()
switch elemValue.Kind() {
case reflect.Struct:
destValues, err := s.mapFieldDest(elemValue, rows)
if err != nil {
return err
}
if !rows.Next() {
if err = rows.Err(); err != nil {
return err
}
return sql.ErrNoRows
}
return rows.Scan(destValues...)
case reflect.Slice:
return s.scanSlice(destValue.Elem(), rows)
default:
panic("dest must point to a struct or slice")
}
}
func (s *Scanner) scanSlice(dest reflect.Value, rows Rows) error {
elemType := dest.Type().Elem()
isPtrElem := elemType.Kind() == reflect.Pointer
if isPtrElem {
elemType = elemType.Elem()
}
if elemType.Kind() != reflect.Struct {
panic("dest slice of non-struct elements")
}
elem := reflect.New(elemType).Elem()
destValues, err := s.mapFieldDest(elem, rows)
if err != nil {
return err
}
dlen, dcap := dest.Len(), dest.Cap()
for rows.Next() {
if err := rows.Scan(destValues...); err != nil {
return err
}
newElem := elem
if isPtrElem {
newElem = reflect.New(elemType)
newElem.Elem().Set(elem)
}
// Inlining the append step like this is much faster than using [reflect.Append].
if dlen+1 > dcap {
// Extend the slice when needed.
dest.Grow(1)
dcap = dest.Cap()
}
dest.SetLen(dlen + 1)
dest.Index(dlen).Set(newElem)
dlen++
// Resetting the elem to zero is needed to handle null cells correctly.
elem.SetZero()
}
if err = rows.Err(); err != nil {
return err
}
return nil
}
func (s *Scanner) scanChan(ctx context.Context, dest reflect.Value, rows Rows) error {
elemType := dest.Type().Elem()
isPtrElem := elemType.Kind() == reflect.Pointer
if isPtrElem {
elemType = elemType.Elem()
}
if elemType.Kind() != reflect.Struct {
panic("dest chan of non-struct elements")
}
elem := reflect.New(elemType).Elem()
destValues, err := s.mapFieldDest(elem, rows)
if err != nil {
return err
}
selectOps := []reflect.SelectCase{
{
Dir: reflect.SelectSend,
Chan: dest,
},
{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ctx.Done()),
},
}
for rows.Next() {
if err := rows.Scan(destValues...); err != nil {
return err
}
newElem := elem
if isPtrElem {
newElem = reflect.New(elemType)
newElem.Elem().Set(elem)
}
selectOps[0].Send = newElem
if chosen, _, _ := reflect.Select(selectOps); chosen == 1 {
// select on ctx.Done()
return ctx.Err()
}
// Resetting the elem to zero is needed to handle null cells correctly.
elem.SetZero()
}
return rows.Err()
}
func (s *Scanner) mapFieldDest(dest reflect.Value, rows Rows) ([]any, error) {
columns, err := rows.Columns()
if err != nil {
return nil, err
}
fieldIndex := s.tc.getStructFieldIndex(dest.Type())
scanValues := make([]any, len(columns))
placeholder := new(any)
for i, column := range columns {
x, ok := fieldIndex[column]
if ok {
scanValues[i] = fieldByIndex(dest, x).Addr().Interface()
} else if !s.IgnoreUnknownColumns {
return nil, fmt.Errorf("sqlz: missing field mapping for column %q", column)
} else {
scanValues[i] = placeholder
}
}
return scanValues, nil
}
// PurgeCache purges the internal type cache.
func (s *Scanner) PurgeCache() {
s.tc.purge()
}
// fieldByIndex has the same functionality as [reflect.Value.FieldByIndex] but uses uint16's as indexes.
func fieldByIndex(v reflect.Value, index []uint16) reflect.Value {
for _, i := range index {
v = v.Field(int(i))
}
return v
}