-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrows.go
101 lines (78 loc) · 1.62 KB
/
rows.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
package sqle
import (
"database/sql"
"reflect"
)
type Rows struct {
*sql.Rows
stmt *Stmt
query string
}
func (r *Rows) Close() error {
if r.stmt != nil {
r.stmt.Reuse()
}
if r.Rows == nil {
return nil
}
return r.Rows.Close()
}
func (r *Rows) Scan(dest ...any) error {
return r.Rows.Scan(dest...)
}
func (r *Rows) Bind(dest any) error {
defer r.Close()
v := reflect.ValueOf(dest)
if v.Kind() != reflect.Pointer {
return ErrMustPointer
}
if v.IsNil() {
return ErrMustNotNilPointer
}
list := v.Elem()
if list.Kind() != reflect.Slice {
return ErrMustSlice
}
var err error
cols, err := getColumns(r.query, r.Rows)
if err != nil {
return err
}
listType := list.Type() // list type
itemType := listType.Elem() // item type
item := reflect.New(itemType) // item value
switch itemType.Kind() {
case reflect.Slice: // [][]T
list, err = scanToList(v, itemType, list, cols, r.Rows)
if err != nil {
return err
}
case reflect.Struct: // []T
_, ok := item.Interface().(Binder)
if ok {
list, err = scanToBinderList(item.Elem(), itemType, list, cols, r.Rows)
if err != nil {
return err
}
} else {
list, err = scanToStructList(item.Elem(), itemType, list, cols, r.Rows)
if err != nil {
return err
}
}
case reflect.Map: // []map[string]T
list, err = scanToMapList(item.Elem(), itemType, list, cols, r.Rows)
if err != nil {
return err
}
default:
return ErrTypeNotBindable
}
err = r.Rows.Err()
if err != nil {
return err
}
v.Elem().Set(list)
// Make sure the query can be processed to completion with no errors.
return r.Rows.Close()
}