-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathscanner.go
231 lines (193 loc) · 5.8 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
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
// Package scan provides functionality for scanning database/sql rows into slices,
// structs, and primative types dynamically
package scan
import (
"database/sql"
"errors"
"reflect"
"strings"
)
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 mytable` 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
)
var (
// nothing is a pointer which will be scanned to for columns that have no place
// on the struct
nothing = reflect.New(reflect.TypeOf([]byte{})).Elem().Addr().Interface()
)
// Row scans a single row into a single variable
func Row(v interface{}, rows RowsScanner) error {
vType := reflect.TypeOf(v)
if k := vType.Kind(); k != reflect.Ptr {
panic(k.String() + ": must be a pointer")
}
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(), rows)
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{}, rows RowsScanner) error {
if AutoClose {
defer rows.Close()
}
vType := reflect.TypeOf(v)
if k := vType.Kind(); k != reflect.Ptr {
panic(k.String() + ": must be a pointer")
}
sliceType := vType.Elem()
if reflect.Slice != sliceType.Kind() {
panic(sliceType.String() + ": must be a slice")
}
sliceVal := reflect.Indirect(reflect.ValueOf(v))
itemType := sliceType.Elem()
cols, err := rows.Columns()
if err != nil {
return err
}
isPrimitive := itemType.Kind() != reflect.Struct
for rows.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)
}
if len(pointers) == 0 {
return nil
}
err := rows.Scan(pointers...)
if err != nil {
return err
}
sliceVal.Set(reflect.Append(sliceVal, sliceItem))
}
return rows.Err()
}
// Columns creates a list of columns that should be selected from a database query and
// all fields that are primitive types that are not flagged with a struct tag db:"-"
// should be used
func Columns(v interface{}) []string {
vType := reflect.TypeOf(v)
if k := vType.Kind(); k == reflect.Ptr {
vType = vType.Elem()
}
vVal := reflect.Indirect(reflect.ValueOf(v))
if k := vType.Kind(); k != reflect.Struct {
panic(k.String() + " must be a struct")
}
numField := vVal.NumField()
fields := make([]string, 0, numField)
for i := 0; i < numField; i++ {
f := vType.Field(i)
switch f.Type.Kind() {
case reflect.Invalid, reflect.Complex64, reflect.Complex128, reflect.Chan,
reflect.Func, reflect.Map, reflect.Slice, reflect.Struct,
reflect.UnsafePointer:
continue
}
if dbTag, ok := f.Tag.Lookup("db"); ok {
if dbTag != "-" {
fields = append(fields, dbTag)
}
continue
}
fields = append(fields, f.Name)
}
return fields
}
// Values creates a list of values to be used for inserting into a database. all fields
// that are primitive types that are not flagged with a struct tag db:"-" should be used
func Values(v interface{}) []interface{} {
vType := reflect.TypeOf(v)
if k := vType.Kind(); k == reflect.Ptr {
vType = vType.Elem()
}
vVal := reflect.Indirect(reflect.ValueOf(v))
if k := vType.Kind(); k != reflect.Struct {
panic(k.String() + " must be a struct")
}
numField := vVal.NumField()
fields := make([]interface{}, 0, numField)
for i := 0; i < numField; i++ {
f := vType.Field(i)
switch f.Type.Kind() {
case reflect.Invalid, reflect.Complex64, reflect.Complex128, reflect.Chan,
reflect.Func, reflect.Map, reflect.Slice, reflect.Struct,
reflect.UnsafePointer:
continue
}
if dbTag, _ := f.Tag.Lookup("db"); dbTag == "-" {
continue
}
fields = append(fields, vVal.Field(i).Interface())
}
return fields
}
// fieldByName gets a struct's field by first looking up the db struct tag and falling
// back to the field's name in Title case.
func fieldByName(v reflect.Value, name string) reflect.Value {
typ := v.Type()
for i := 0; i < v.NumField(); i++ {
tag, ok := typ.Field(i).Tag.Lookup("db")
if ok && tag == name {
return v.Field(i)
}
}
return v.FieldByName(strings.Title(name))
}
func structPointers(stct reflect.Value, cols []string) []interface{} {
pointers := make([]interface{}, 0, len(cols))
for _, colName := range cols {
fieldVal := fieldByName(stct, 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
// nowhere
pointers = append(pointers, nothing)
continue
}
pointers = append(pointers, fieldVal.Addr().Interface())
}
return pointers
}
// RowsScanner is a database scanner for many rows. It is most commonly the result of
// *(database/sql).DB.Query(...) but can be mocked or stubbed
type RowsScanner interface {
Close() error
Scan(dest ...interface{}) error
Columns() ([]string, error)
ColumnTypes() ([]*sql.ColumnType, error)
Err() error
Next() bool
NextResultSet() bool
}
// Scanner is a single row scanner. It is most commonly the result of
// *(database/sql).DB.QueryRow(...) but can be mocked or stubbed
type Scanner interface {
Scan(dest ...interface{}) error
}