forked from go-gorp/gorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.go
454 lines (395 loc) · 11.4 KB
/
select.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright 2012 James Cooper. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gorp
import (
"context"
"database/sql"
"fmt"
"reflect"
)
// TypedSelector provides type-safe select operations
type TypedSelector[T any] struct {
dbmap *DbMap
exec SqlExecutor
hooks *HookMap[T]
ctx context.Context
}
// NewTypedSelector creates a new TypedSelector for type T
func NewTypedSelector[T any](ctx context.Context, dbmap *DbMap, exec SqlExecutor) *TypedSelector[T] {
return &TypedSelector[T]{
dbmap: dbmap,
exec: exec,
hooks: NewHookMap[T](),
ctx: ctx,
}
}
// WithHooks sets the hooks for this selector
func (s *TypedSelector[T]) WithHooks(hooks *HookMap[T]) *TypedSelector[T] {
s.hooks = hooks
return s
}
// SelectOne executes a type-safe select for a single row
func (s *TypedSelector[T]) SelectOne(query string, args ...interface{}) (*T, error) {
var result T
err := SelectOne(s.dbmap, s.exec, &result, query, args...)
if err != nil {
return nil, err
}
// Execute after select hooks
if s.hooks != nil {
if err := s.hooks.ExecuteHooks(s.ctx, AfterSelect, s.exec); err != nil {
return nil, &HookError{
Point: AfterSelect,
Entity: result,
Err: err,
}
}
}
return &result, nil
}
// Select executes a type-safe select for multiple rows
func (s *TypedSelector[T]) Select(query string, args ...interface{}) ([]T, error) {
var result T
list, err := hookedselect(s.dbmap, s.exec, &result, query, args...)
if err != nil {
return nil, err
}
typedList := make([]T, len(list))
for i, v := range list {
typedList[i] = *v.(*T)
}
return typedList, nil
}
// SelectInt executes the given query, which should be a SELECT statement for a single
// integer column, and returns the value of the first row returned. If no rows are
// found, zero is returned.
func SelectInt(e SqlExecutor, query string, args ...interface{}) (int64, error) {
var h int64
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return 0, err
}
return h, nil
}
// SelectNullInt executes the given query, which should be a SELECT statement for a single
// integer column, and returns the value of the first row returned. If no rows are
// found, the empty sql.NullInt64 value is returned.
func SelectNullInt(e SqlExecutor, query string, args ...interface{}) (sql.NullInt64, error) {
var h sql.NullInt64
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return h, err
}
return h, nil
}
// SelectFloat executes the given query, which should be a SELECT statement for a single
// float column, and returns the value of the first row returned. If no rows are
// found, zero is returned.
func SelectFloat(e SqlExecutor, query string, args ...interface{}) (float64, error) {
var h float64
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return 0, err
}
return h, nil
}
// SelectNullFloat executes the given query, which should be a SELECT statement for a single
// float column, and returns the value of the first row returned. If no rows are
// found, the empty sql.NullFloat64 value is returned.
func SelectNullFloat(e SqlExecutor, query string, args ...interface{}) (sql.NullFloat64, error) {
var h sql.NullFloat64
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return h, err
}
return h, nil
}
// SelectStr executes the given query, which should be a SELECT statement for a single
// char/varchar column, and returns the value of the first row returned. If no rows are
// found, an empty string is returned.
func SelectStr(e SqlExecutor, query string, args ...interface{}) (string, error) {
var h string
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return "", err
}
return h, nil
}
// SelectNullStr executes the given query, which should be a SELECT statement for a single
// char/varchar column, and returns the value of the first row returned. If no rows are
// found, the empty sql.NullString is returned.
func SelectNullStr(e SqlExecutor, query string, args ...interface{}) (sql.NullString, error) {
var h sql.NullString
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return h, err
}
return h, nil
}
// SelectBool executes the given query, which should be a SELECT statement for a single
// boolean column, and returns the value of the first row returned. If no rows are
// found, false is returned.
func SelectBool(e SqlExecutor, query string, args ...interface{}) (bool, error) {
var h bool
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return false, err
}
return h, nil
}
// SelectNullBool executes the given query, which should be a SELECT statement for a single
// boolean column, and returns the value of the first row returned. If no rows are
// found, the empty sql.NullBool is returned.
func SelectNullBool(e SqlExecutor, query string, args ...interface{}) (sql.NullBool, error) {
var h sql.NullBool
err := selectVal(e, &h, query, args...)
if err != nil && err != sql.ErrNoRows {
return h, err
}
return h, nil
}
// SelectOne executes the given query (which should be a SELECT statement)
// and binds the result to holder, which must be a pointer.
//
// # If no row is found, an error (sql.ErrNoRows specifically) will be returned
//
// If more than one row is found, an error will be returned.
func SelectOne(m *DbMap, e SqlExecutor, holder interface{}, query string, args ...interface{}) error {
t := reflect.TypeOf(holder)
if t.Kind() == reflect.Ptr {
t = t.Elem()
} else {
return fmt.Errorf("gorp: SelectOne holder must be a pointer, but got: %T", holder)
}
// Handle pointer to pointer
isptr := false
if t.Kind() == reflect.Ptr {
isptr = true
t = t.Elem()
}
if t.Kind() == reflect.Struct {
var nonFatalErr error
list, err := hookedselect(m, e, holder, query, args...)
if err != nil {
if !NonFatalError(err) {
return err
}
nonFatalErr = err
}
dest := reflect.ValueOf(holder)
if isptr {
dest = dest.Elem()
}
if list != nil && len(list) > 0 {
// Check for multiple rows
if len(list) > 1 {
return fmt.Errorf("gorp: multiple rows returned for: %s - %v", query, args)
}
// Initialize if nil
if dest.IsNil() {
dest.Set(reflect.New(t))
}
// Only one row found
src := reflect.ValueOf(list[0])
dest.Elem().Set(src.Elem())
} else {
// No rows found, return a proper error
return sql.ErrNoRows
}
return nonFatalErr
}
return selectVal(e, holder, query, args...)
}
// selectVal executes the given query (which should be a SELECT statement)
// and binds the result to holder
func selectVal(e SqlExecutor, holder interface{}, query string, args ...interface{}) error {
if len(args) == 1 {
switch m := e.(type) {
case *DbMap:
query, args = maybeExpandNamedQuery(m, query, args)
case *Transaction:
query, args = maybeExpandNamedQuery(m.dbmap, query, args)
}
}
rows, err := e.Query(query, args...)
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
if err := rows.Err(); err != nil {
return err
}
return sql.ErrNoRows
}
return rows.Scan(holder)
}
// hookedselect executes the given query (which should be a SELECT statement)
// and returns the results
func hookedselect(m *DbMap, exec SqlExecutor, i interface{}, query string,
args ...interface{}) ([]interface{}, error) {
var nonFatalErr error
list, err := rawselect(m, exec, i, query, args...)
if err != nil {
if !NonFatalError(err) {
return nil, err
}
nonFatalErr = err
}
// Execute after select hooks
if len(list) > 0 {
for _, v := range list {
if v, ok := v.(HasPostGet); ok {
ctx := context.Background()
if execCtx, ok := exec.(hasContext); ok {
ctx = execCtx.Context()
}
if err := v.PostGet(ctx, exec); err != nil {
return nil, &HookError{
Point: AfterSelect,
Entity: v,
Err: err,
}
}
}
}
}
return list, nonFatalErr
}
// rawselect executes the given query (which should be a SELECT statement)
// and returns the results
func rawselect(m *DbMap, exec SqlExecutor, i interface{}, query string,
args ...interface{}) ([]interface{}, error) {
var (
appendToSlice = false // Write results to i directly?
intoStruct = true // Selecting into a struct?
pointerElements = true // Are the slice elements pointers (vs values)?
)
var nonFatalErr error
tableName := ""
var dynObj DynamicTable
isDynamic := false
if dynObj, isDynamic = i.(DynamicTable); isDynamic {
tableName = dynObj.TableName()
}
// get type for i, verifying it's a supported destination
t, err := toType(i)
if err != nil {
var err2 error
if t, err2 = toSliceType(i); t == nil {
if err2 != nil {
return nil, err2
}
return nil, err
}
pointerElements = t.Kind() == reflect.Ptr
if pointerElements {
t = t.Elem()
}
appendToSlice = true
intoStruct = t.Kind() == reflect.Struct
}
// If the caller supplied a single struct/map argument, assume a "named
// parameter" query. Extract the named arguments from the struct/map, create
// the flat arg slice, and rewrite the query to use the dialect's placeholder.
if len(args) == 1 {
query, args = maybeExpandNamedQuery(m, query, args)
}
// Run the query
rows, err := exec.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// Fetch the column names as returned from db
cols, err := rows.Columns()
if err != nil {
return nil, err
}
if !intoStruct && len(cols) > 1 {
return nil, fmt.Errorf("gorp: select into non-struct slice requires 1 column, got %d", len(cols))
}
var colToFieldIndex [][]int
if intoStruct {
colToFieldIndex, err = columnToFieldIndex(m, t, tableName, cols)
if err != nil {
if !NonFatalError(err) {
return nil, err
}
nonFatalErr = err
}
}
conv := m.TypeConverter
// Add results to one of these two slices.
var (
list = make([]interface{}, 0)
sliceValue = reflect.Indirect(reflect.ValueOf(i))
)
for {
if !rows.Next() {
// if error occured return rawselect
if rows.Err() != nil {
return nil, rows.Err()
}
// time to exit from outer "for" loop
break
}
v := reflect.New(t)
if isDynamic {
v.Interface().(DynamicTable).SetTableName(tableName)
}
dest := make([]interface{}, len(cols))
custScan := make([]CustomScanner, 0)
for x := range cols {
f := v.Elem()
if intoStruct {
index := colToFieldIndex[x]
if index == nil {
// this field is not present in the struct, so create a dummy
// value for rows.Scan to scan into
var dummy dummyField
dest[x] = &dummy
continue
}
f = f.FieldByIndex(index)
}
target := f.Addr().Interface()
if conv != nil {
scanner, ok := conv.FromDb(target)
if ok {
target = scanner.Holder
custScan = append(custScan, scanner)
}
}
dest[x] = target
}
err = rows.Scan(dest...)
if err != nil {
return nil, err
}
for _, c := range custScan {
err = c.Bind()
if err != nil {
return nil, err
}
}
if appendToSlice {
if !pointerElements {
v = v.Elem()
}
sliceValue.Set(reflect.Append(sliceValue, v))
} else {
list = append(list, v.Interface())
}
}
if appendToSlice && sliceValue.IsNil() {
sliceValue.Set(reflect.MakeSlice(sliceValue.Type(), 0, 0))
}
return list, nonFatalErr
}
// hasContext is an interface that is implemented by the context.Context and
// context.Value objects
type hasContext interface {
Context() context.Context
}