forked from jostyee/dbr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select_load.go
310 lines (249 loc) · 9.11 KB
/
select_load.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
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
package dbr
import (
"reflect"
"time"
)
// Unvetted thots:
// Given a query and given a structure (field list), there's 2 sets of fields.
// Take the intersection. We can fill those in. great.
// For fields in the structure that aren't in the query, we'll let that slide if db:"-"
// For fields in the structure that aren't in the query but without db:"-", return error
// For fields in the query that aren't in the structure, we'll ignore them.
// LoadStructs executes the SelectBuilder and loads the resulting data into a slice of structs
// dest must be a pointer to a slice of pointers to structs
// Returns the number of items found (which is not necessarily the # of items set)
func (b *SelectBuilder) LoadStructs(dest interface{}) (int, error) {
//
// Validate the dest, and extract the reflection values we need.
//
// This must be a pointer to a slice
valueOfDest := reflect.ValueOf(dest)
kindOfDest := valueOfDest.Kind()
if kindOfDest != reflect.Ptr {
panic("invalid type passed to LoadStructs. Need a pointer to a slice")
}
// This must a slice
valueOfDest = reflect.Indirect(valueOfDest)
kindOfDest = valueOfDest.Kind()
if kindOfDest != reflect.Slice {
panic("invalid type passed to LoadStructs. Need a pointer to a slice")
}
// The slice elements must be pointers to structures
recordType := valueOfDest.Type().Elem()
if recordType.Kind() != reflect.Ptr {
panic("Elements need to be pointers to structures")
}
recordType = recordType.Elem()
if recordType.Kind() != reflect.Struct {
panic("Elements need to be pointers to structures")
}
//
// Get full SQL
//
fullSql, err := Interpolate(b.ToSql())
if err != nil {
return 0, b.EventErr("dbr.select.load_all.interpolate", err)
}
numberOfRowsReturned := 0
// Start the timer:
startTime := time.Now()
defer func() { b.TimingKv("dbr.select", time.Since(startTime).Nanoseconds(), kvs{"sql": fullSql}) }()
// Run the query:
rows, err := b.runner.Query(fullSql)
if err != nil {
return 0, b.EventErrKv("dbr.select.load_all.query", err, kvs{"sql": fullSql})
}
defer rows.Close()
// Get the columns returned
columns, err := rows.Columns()
if err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_one.rows.Columns", err, kvs{"sql": fullSql})
}
// Create a map of this result set to the struct fields
fieldMap, err := b.calculateFieldMap(recordType, columns, false)
if err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_all.calculateFieldMap", err, kvs{"sql": fullSql})
}
// Build a 'holder', which is an []interface{}. Each value will be the set to address of the field corresponding to our newly made records:
holder := make([]interface{}, len(fieldMap))
// Iterate over rows and scan their data into the structs
sliceValue := valueOfDest
for rows.Next() {
// Create a new record to store our row:
pointerToNewRecord := reflect.New(recordType)
newRecord := reflect.Indirect(pointerToNewRecord)
// Prepare the holder for this record
scannable, err := b.prepareHolderFor(newRecord, fieldMap, holder)
if err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_all.holderFor", err, kvs{"sql": fullSql})
}
// Load up our new structure with the row's values
err = rows.Scan(scannable...)
if err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_all.scan", err, kvs{"sql": fullSql})
}
// Append our new record to the slice:
sliceValue = reflect.Append(sliceValue, pointerToNewRecord)
numberOfRowsReturned++
}
valueOfDest.Set(sliceValue)
// Check for errors at the end. Supposedly these are error that can happen during iteration.
if err = rows.Err(); err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_all.rows_err", err, kvs{"sql": fullSql})
}
return numberOfRowsReturned, nil
}
// LoadStruct executes the SelectBuilder and loads the resulting data into a struct
// dest must be a pointer to a struct
// Returns ErrNotFound if nothing was found
func (b *SelectBuilder) LoadStruct(dest interface{}) error {
//
// Validate the dest, and extract the reflection values we need.
//
valueOfDest := reflect.ValueOf(dest)
indirectOfDest := reflect.Indirect(valueOfDest)
kindOfDest := valueOfDest.Kind()
if kindOfDest != reflect.Ptr || indirectOfDest.Kind() != reflect.Struct {
panic("you need to pass in the address of a struct")
}
recordType := indirectOfDest.Type()
//
// Get full SQL
//
fullSql, err := Interpolate(b.ToSql())
if err != nil {
return err
}
// Start the timer:
startTime := time.Now()
defer func() { b.TimingKv("dbr.select", time.Since(startTime).Nanoseconds(), kvs{"sql": fullSql}) }()
// Run the query:
rows, err := b.runner.Query(fullSql)
if err != nil {
return b.EventErrKv("dbr.select.load_one.query", err, kvs{"sql": fullSql})
}
defer rows.Close()
// Get the columns of this result set
columns, err := rows.Columns()
if err != nil {
return b.EventErrKv("dbr.select.load_one.rows.Columns", err, kvs{"sql": fullSql})
}
// Create a map of this result set to the struct columns
fieldMap, err := b.calculateFieldMap(recordType, columns, false)
if err != nil {
return b.EventErrKv("dbr.select.load_one.calculateFieldMap", err, kvs{"sql": fullSql})
}
// Build a 'holder', which is an []interface{}. Each value will be the set to address of the field corresponding to our newly made records:
holder := make([]interface{}, len(fieldMap))
if rows.Next() {
// Build a 'holder', which is an []interface{}. Each value will be the address of the field corresponding to our newly made record:
scannable, err := b.prepareHolderFor(indirectOfDest, fieldMap, holder)
if err != nil {
return b.EventErrKv("dbr.select.load_one.holderFor", err, kvs{"sql": fullSql})
}
// Load up our new structure with the row's values
err = rows.Scan(scannable...)
if err != nil {
return b.EventErrKv("dbr.select.load_one.scan", err, kvs{"sql": fullSql})
}
return nil
}
if err := rows.Err(); err != nil {
return b.EventErrKv("dbr.select.load_one.rows_err", err, kvs{"sql": fullSql})
}
return ErrNotFound
}
// LoadValues executes the SelectBuilder and loads the resulting data into a slice of primitive values
// Returns ErrNotFound if no value was found, and it was therefore not set.
func (b *SelectBuilder) LoadValues(dest interface{}) (int, error) {
// Validate the dest and reflection values we need
// This must be a pointer to a slice
valueOfDest := reflect.ValueOf(dest)
kindOfDest := valueOfDest.Kind()
if kindOfDest != reflect.Ptr {
panic("invalid type passed to LoadValues. Need a pointer to a slice")
}
// This must a slice
valueOfDest = reflect.Indirect(valueOfDest)
kindOfDest = valueOfDest.Kind()
if kindOfDest != reflect.Slice {
panic("invalid type passed to LoadValues. Need a pointer to a slice")
}
recordType := valueOfDest.Type().Elem()
recordTypeIsPtr := recordType.Kind() == reflect.Ptr
if recordTypeIsPtr {
reflect.ValueOf(dest)
}
//
// Get full SQL
//
fullSql, err := Interpolate(b.ToSql())
if err != nil {
return 0, err
}
numberOfRowsReturned := 0
// Start the timer:
startTime := time.Now()
defer func() { b.TimingKv("dbr.select", time.Since(startTime).Nanoseconds(), kvs{"sql": fullSql}) }()
// Run the query:
rows, err := b.runner.Query(fullSql)
if err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_all_values.query", err, kvs{"sql": fullSql})
}
defer rows.Close()
sliceValue := valueOfDest
for rows.Next() {
// Create a new value to store our row:
pointerToNewValue := reflect.New(recordType)
newValue := reflect.Indirect(pointerToNewValue)
err = rows.Scan(pointerToNewValue.Interface())
if err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_all_values.scan", err, kvs{"sql": fullSql})
}
// Append our new value to the slice:
sliceValue = reflect.Append(sliceValue, newValue)
numberOfRowsReturned++
}
valueOfDest.Set(sliceValue)
if err := rows.Err(); err != nil {
return numberOfRowsReturned, b.EventErrKv("dbr.select.load_all_values.rows_err", err, kvs{"sql": fullSql})
}
return numberOfRowsReturned, nil
}
// LoadValue executes the SelectBuilder and loads the resulting data into a primitive value
// Returns ErrNotFound if no value was found, and it was therefore not set.
func (b *SelectBuilder) LoadValue(dest interface{}) error {
// Validate the dest
valueOfDest := reflect.ValueOf(dest)
kindOfDest := valueOfDest.Kind()
if kindOfDest != reflect.Ptr {
panic("Destination must be a pointer")
}
//
// Get full SQL
//
fullSql, err := Interpolate(b.ToSql())
if err != nil {
return err
}
// Start the timer:
startTime := time.Now()
defer func() { b.TimingKv("dbr.select", time.Since(startTime).Nanoseconds(), kvs{"sql": fullSql}) }()
// Run the query:
rows, err := b.runner.Query(fullSql)
if err != nil {
return b.EventErrKv("dbr.select.load_value.query", err, kvs{"sql": fullSql})
}
defer rows.Close()
if rows.Next() {
err = rows.Scan(dest)
if err != nil {
return b.EventErrKv("dbr.select.load_value.scan", err, kvs{"sql": fullSql})
}
return nil
}
if err := rows.Err(); err != nil {
return b.EventErrKv("dbr.select.load_value.rows_err", err, kvs{"sql": fullSql})
}
return ErrNotFound
}