-
Notifications
You must be signed in to change notification settings - Fork 2
/
result.go
266 lines (233 loc) · 7.43 KB
/
result.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
package sol
import (
"database/sql"
"fmt"
"reflect"
)
// Scanner is used for building mock result rows for testing
type Scanner interface {
Close() error
Columns() ([]string, error)
Err() error
Next() bool
Scan(...interface{}) error
}
// Result is returned by a database query - it embeds a Scanner
type Result struct {
stmt string
Scanner
}
// All returns all result rows scanned into the given interface, which
// must be a pointer to a slice of either structs or values. If there
// is only a single result column, then the destination can be a
// slice of a single native type (e.g. []int).
func (r Result) All(obj interface{}) error {
value := reflect.ValueOf(obj)
if value.Kind() != reflect.Ptr {
return fmt.Errorf(
"sol: received a non-pointer destination for result.All",
)
}
list := value.Elem()
if list.Kind() != reflect.Slice {
return fmt.Errorf(
"sol: received a non-slice destination for result.All",
)
}
elem := list.Type().Elem()
columns, err := r.Columns()
if err != nil {
return fmt.Errorf("sol: error returning columns from result: %s", err)
}
switch elem.Kind() {
case reflect.Struct:
return r.allStruct(columns, elem, list)
case reflect.Map:
return r.allMap(columns, obj, list)
default: // TODO enumerate types?
return r.allNative(columns, elem, list)
}
// TODO Until types are enumerated above this return will never run
return fmt.Errorf(
"sol: unsupported destination type %T for Result.All", obj,
)
}
// allStruct scanes the results into a slice of struct types
func (r Result) allStruct(columns []string, elem reflect.Type, list reflect.Value) error {
fields := DeepFields(reflect.New(elem).Interface())
aligned := AlignFields(columns, fields)
// If nothing matched and the number of fields equals the number
// columns, then blindly align columns and fields
// TODO This may be too friendly of a feature
if NoMatchingFields(aligned) && len(fields) == len(columns) {
aligned = fields
}
// How many elements already exist? Merge scanned fields instead of
// overwriting an entire new element
existingElements := list.Len()
index := 0
dest := make([]interface{}, len(columns))
for r.Next() {
var newElem reflect.Value
if index < existingElements {
newElem = list.Index(index) // Merge with the existing element
} else {
newElem = reflect.New(elem).Elem() // Create a new element
}
for i, field := range aligned {
if field.Exists() {
dest[i] = newElem.FieldByIndex(field.Type.Index).Addr().Interface()
} else {
dest[i] = &dest[i] // Discard
}
}
if err := r.Scan(dest...); err != nil {
return fmt.Errorf("sol: error scanning struct: %s", err)
}
if index >= existingElements {
list.Set(reflect.Append(list, newElem))
}
index += 1
}
return r.Err() // Check for delayed scan errors
}
// allMap scans the results into a slice of Values
func (r Result) allMap(columns []string, obj interface{}, list reflect.Value) error {
// TODO support scaning into existing or partially populated slices?
_, ok := obj.(*[]Values)
if !ok {
return fmt.Errorf(
"sol: slices of maps must have an element type of sol.Values",
)
}
// TODO How to scan directly into values?
addr := make([]interface{}, len(columns))
dest := make([]interface{}, len(columns))
for i := range addr {
dest[i] = &addr[i]
}
for r.Next() {
if err := r.Scan(dest...); err != nil {
return fmt.Errorf("sol: error scanning map slice: %s", err)
}
values := Values{}
for i, name := range columns {
values[name] = addr[i]
}
list.Set(reflect.Append(list, reflect.ValueOf(values)))
}
return r.Err() // Check for delayed scan errors
}
// allNative scans the results into a slice of a single native type,
// such as []int
func (r Result) allNative(columns []string, elem reflect.Type, list reflect.Value) error {
// TODO support scaning into existing or partially populated slices?
if len(columns) != 1 {
return fmt.Errorf(
"sol: unsupported type for multi-column Result.All: %s",
elem.Kind(),
)
}
for r.Next() {
newElem := reflect.New(elem).Elem()
if err := r.Scan(newElem.Addr().Interface()); err != nil {
return fmt.Errorf("sol: error scanning native slice: %s", err)
}
list.Set(reflect.Append(list, newElem))
}
return r.Err() // Check for delayed scan errors
}
// One returns a single row from Result. The destination must be a pointer
// to a struct or Values type. If there is only a single result column,
// then the destination can be a single native type.
func (r Result) One(obj interface{}) error {
// There must be at least one row to return
if ok := r.Next(); !ok {
return sql.ErrNoRows
}
columns, err := r.Columns()
if err != nil {
return fmt.Errorf("sol: error returning columns from result: %s", err)
}
// Since maps are already pointers, they can be used as destinations
// no matter what - as long as they are of type Values
value := reflect.ValueOf(obj)
switch value.Kind() {
case reflect.Map:
return r.oneMap(columns, value, obj)
case reflect.Ptr:
// Other types must be given as pointers to be valid destinations
elem := reflect.Indirect(value)
switch elem.Kind() {
case reflect.Struct:
return r.oneStruct(columns, elem, obj)
default: // TODO enumerate types?
return r.oneNative(columns, elem)
}
}
return fmt.Errorf(
"sol: unsupported destination type %T for Result.One", obj,
)
}
// oneMap scans the result into a single Values type
func (r Result) oneMap(columns []string, value reflect.Value, obj interface{}) error {
if value.IsNil() {
// TODO this might be a lie...
return fmt.Errorf("sol: map types must be initialized before being used as destinations")
}
values, ok := obj.(Values)
if !ok {
return fmt.Errorf("sol: map types can be destinations only if they are of type Values")
}
// TODO scan directly into values?
addr := make([]interface{}, len(columns))
dest := make([]interface{}, len(columns))
for i := range addr {
dest[i] = &addr[i]
}
if err := r.Scan(dest...); err != nil {
return fmt.Errorf("sol: error scanning map: %s", err)
}
for i, name := range columns {
values[name] = addr[i]
}
return r.Err() // Check for delayed scan errors
}
// oneStruct scans the result into a single struct type
func (r Result) oneStruct(columns []string, elem reflect.Value, obj interface{}) error {
fields := DeepFields(obj)
aligned := AlignFields(columns, fields)
// Create an interface pointer for each column's destination.
// Unmatched scanner values will be discarded
dest := make([]interface{}, len(columns))
// If nothing matched and the number of fields equals the number
// columns, then blindly align columns and fields
// TODO This may be too friendly of a feature
if NoMatchingFields(aligned) && len(fields) == len(columns) {
aligned = fields
}
for i, field := range aligned {
if field.Exists() {
dest[i] = elem.FieldByIndex(field.Type.Index).Addr().Interface()
} else {
dest[i] = &dest[i] // Discard
}
}
if err := r.Scan(dest...); err != nil {
return fmt.Errorf("sol: error scanning struct: %s", err)
}
return r.Err() // Check for delayed scan errors
}
// oneNative scans the result into a single native type, such as int
func (r Result) oneNative(columns []string, elem reflect.Value) error {
if len(columns) != 1 {
return fmt.Errorf(
"sol: unsupported type for multi-column Result.One: %s",
elem.Kind(),
)
}
if err := r.Scan(elem.Addr().Interface()); err != nil {
return fmt.Errorf("sol: error scanning native type: %s", err)
}
return r.Err() // Check for delayed scan errors
}