-
Notifications
You must be signed in to change notification settings - Fork 32
/
scanner.go
204 lines (169 loc) · 5.19 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package scan
import (
"database/sql"
"errors"
"fmt"
"io"
"reflect"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var (
// ErrTooManyColumns indicates that a select query returned multiple columns and
// attempted to bind to a slice of a primitive type. For example, trying to bind
// `select col1, col2 from mutable` to []string
ErrTooManyColumns = errors.New("too many columns returned for primitive slice")
// ErrSliceForRow occurs when trying to use Row on a slice
ErrSliceForRow = errors.New("cannot scan Row into slice")
// AutoClose is true when scan should automatically close Scanner when the scan
// is complete. If you set it to false, then you must defer rows.Close() manually
AutoClose = true
// OnAutoCloseError can be used to log errors which are returned from rows.Close()
// By default this is a NOOP function
OnAutoCloseError = func(error) {}
// ScannerMapper transforms database field names into struct/map field names
// E.g. you can set function for convert snake_case into CamelCase
ScannerMapper = func(name string) string { return cases.Title(language.English).String(name) }
)
// Row scans a single row into a single variable. It requires that you use
// db.Query and not db.QueryRow, because QueryRow does not return column names.
// There is no performance impact in using one over the other. QueryRow only
// defers returning err until Scan is called, which is an unnecessary
// optimization for this library.
func Row(v interface{}, r RowsScanner) error {
if AutoClose {
defer closeRows(r)
}
return row(v, r, false)
}
// RowStrict scans a single row into a single variable. It is identical to
// Row, but it ignores fields that do not have a db tag
func RowStrict(v interface{}, r RowsScanner) error {
if AutoClose {
defer closeRows(r)
}
return row(v, r, true)
}
func row(v interface{}, r RowsScanner, strict bool) error {
vType := reflect.TypeOf(v)
if k := vType.Kind(); k != reflect.Ptr {
return fmt.Errorf("%q must be a pointer: %w", k.String(), ErrNotAPointer)
}
vType = vType.Elem()
vVal := reflect.ValueOf(v).Elem()
if vType.Kind() == reflect.Slice {
return ErrSliceForRow
}
sl := reflect.New(reflect.SliceOf(vType))
err := rows(sl.Interface(), r, strict)
if err != nil {
return err
}
sl = sl.Elem()
if sl.Len() == 0 {
return sql.ErrNoRows
}
vVal.Set(sl.Index(0))
return nil
}
// Rows scans sql rows into a slice (v)
func Rows(v interface{}, r RowsScanner) (outerr error) {
if AutoClose {
defer closeRows(r)
}
return rows(v, r, false)
}
// RowsStrict scans sql rows into a slice (v) only using db tags
func RowsStrict(v interface{}, r RowsScanner) (outerr error) {
if AutoClose {
defer closeRows(r)
}
return rows(v, r, true)
}
func rows(v interface{}, r RowsScanner, strict bool) (outerr error) {
vType := reflect.TypeOf(v)
if k := vType.Kind(); k != reflect.Ptr {
return fmt.Errorf("%q must be a pointer: %w", k.String(), ErrNotAPointer)
}
sliceType := vType.Elem()
if reflect.Slice != sliceType.Kind() {
return fmt.Errorf("%q must be a slice: %w", sliceType.String(), ErrNotASlicePointer)
}
sliceVal := reflect.Indirect(reflect.ValueOf(v))
itemType := sliceType.Elem()
cols, err := r.Columns()
if err != nil {
return err
}
isPrimitive := itemType.Kind() != reflect.Struct
for r.Next() {
sliceItem := reflect.New(itemType).Elem()
var pointers []interface{}
if isPrimitive {
if len(cols) > 1 {
return ErrTooManyColumns
}
pointers = []interface{}{sliceItem.Addr().Interface()}
} else {
pointers = structPointers(sliceItem, cols, strict)
}
if len(pointers) == 0 {
return nil
}
err := r.Scan(pointers...)
if err != nil {
return err
}
sliceVal.Set(reflect.Append(sliceVal, sliceItem))
}
return r.Err()
}
// Initialization the tags from struct.
func initFieldTag(sliceItem reflect.Value, fieldTagMap *map[string]reflect.Value) {
typ := sliceItem.Type()
for i := 0; i < sliceItem.NumField(); i++ {
if typ.Field(i).Anonymous || typ.Field(i).Type.Kind() == reflect.Struct {
// found an embedded struct
sliceItemOfAnonymous := sliceItem.Field(i)
initFieldTag(sliceItemOfAnonymous, fieldTagMap)
}
tag, ok := typ.Field(i).Tag.Lookup("db")
if ok && tag != "" {
(*fieldTagMap)[tag] = sliceItem.Field(i)
}
}
}
func structPointers(sliceItem reflect.Value, cols []string, strict bool) []interface{} {
pointers := make([]interface{}, 0, len(cols))
fieldTag := make(map[string]reflect.Value, len(cols))
initFieldTag(sliceItem, &fieldTag)
for _, colName := range cols {
var fieldVal reflect.Value
if v, ok := fieldTag[colName]; ok {
fieldVal = v
} else {
if strict {
fieldVal = reflect.ValueOf(nil)
} else {
fieldVal = sliceItem.FieldByName(ScannerMapper(colName))
}
}
if !fieldVal.IsValid() || !fieldVal.CanSet() {
// have to add if we found a column because Scan() requires
// len(cols) arguments or it will error. This way we can scan to
// a useless pointer
var nothing interface{}
pointers = append(pointers, ¬hing)
continue
}
pointers = append(pointers, fieldVal.Addr().Interface())
}
return pointers
}
func closeRows(c io.Closer) {
if err := c.Close(); err != nil {
if OnAutoCloseError != nil {
OnAutoCloseError(err)
}
}
}