This repository has been archived by the owner on Jan 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bind.go
224 lines (195 loc) · 4.8 KB
/
bind.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
package reiner
// 來源:https://github.com/bgaifullin/dbr
// 來源:https://github.com/bgaifullin/dbr/blob/master/load.go
import (
"bytes"
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"unicode"
)
var (
dummyDest sql.Scanner = dummyScanner{}
typeScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
typeKeyValueMap = reflect.TypeOf(keyValueMap(nil))
typeValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
)
type pointersExtractor func(columns []string, value reflect.Value) []interface{}
type dummyScanner struct{}
func (dummyScanner) Scan(interface{}) error {
return nil
}
type keyValueMap map[string]interface{}
type kvScanner struct {
column string
m keyValueMap
}
func (kv *kvScanner) Scan(v interface{}) error {
kv.m[kv.column] = v
return nil
}
func load(rows *sql.Rows, value interface{}) (int, error) {
if value == nil {
count := 0
for rows.Next() {
count++
}
return count, nil
}
column, err := rows.Columns()
if err != nil {
return 0, err
}
v := reflect.ValueOf(value)
if v.Kind() != reflect.Ptr || v.IsNil() {
return 0, ErrInvalidPointer
}
isSlice := v.Elem().Kind() == reflect.Slice && v.Elem().Type().Elem().Kind() != reflect.Uint8
if isSlice {
v.Elem().Set(reflect.MakeSlice(v.Type().Elem(), 0, v.Elem().Cap()))
}
v = v.Elem()
count := 0
var elemType reflect.Type
if isSlice {
elemType = v.Type().Elem()
} else {
elemType = v.Type()
}
extractor, err := findExtractor(elemType)
if err != nil {
return count, err
}
for rows.Next() {
var elem reflect.Value
if isSlice {
elem = reflect.New(v.Type().Elem()).Elem()
} else {
elem = v
}
ptr := extractor(column, elem)
err = rows.Scan(ptr...)
if err != nil {
return count, err
}
count++
if isSlice {
v.Set(reflect.Append(v, elem))
} else {
break
}
}
err = rows.Close()
if err != nil {
return 0, err
}
return count, nil
}
// structMap builds index to fast lookup fields in struct
func structMap(t reflect.Type) map[string][]int {
m := make(map[string][]int)
structTraverse(m, t, nil)
return m
}
func camelCaseToSnakeCase(name string) string {
buf := new(bytes.Buffer)
runes := []rune(name)
for i := 0; i < len(runes); i++ {
buf.WriteRune(unicode.ToLower(runes[i]))
if i != len(runes)-1 && unicode.IsUpper(runes[i+1]) &&
(unicode.IsLower(runes[i]) || unicode.IsDigit(runes[i]) ||
(i != len(runes)-2 && unicode.IsLower(runes[i+2]))) {
buf.WriteRune('_')
}
}
return buf.String()
}
func structTraverse(m map[string][]int, t reflect.Type, head []int) {
if t.Implements(typeValuer) {
return
}
switch t.Kind() {
case reflect.Ptr:
structTraverse(m, t.Elem(), head)
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" && !field.Anonymous {
// unexported
continue
}
tag := field.Tag.Get("db")
if tag == "-" {
// ignore
continue
}
if tag == "" {
// no tag, but we can record the field name
//tag = camelCaseToSnakeCase(field.Name)
tag = field.Name
}
if _, ok := m[tag]; !ok {
m[tag] = append(head, i)
}
structTraverse(m, field.Type, append(head, i))
}
}
}
func getStructFieldsExtractor(t reflect.Type) pointersExtractor {
mapping := structMap(t)
return func(columns []string, value reflect.Value) []interface{} {
var ptr []interface{}
for _, key := range columns {
if index, ok := mapping[key]; ok {
ptr = append(ptr, value.FieldByIndex(index).Addr().Interface())
} else {
ptr = append(ptr, dummyDest)
}
}
return ptr
}
}
func getIndirectExtractor(extractor pointersExtractor) pointersExtractor {
return func(columns []string, value reflect.Value) []interface{} {
if value.IsNil() {
value.Set(reflect.New(value.Type().Elem()))
}
return extractor(columns, value.Elem())
}
}
func mapExtractor(columns []string, value reflect.Value) []interface{} {
if value.IsNil() {
value.Set(reflect.MakeMap(value.Type()))
}
m := value.Convert(typeKeyValueMap).Interface().(keyValueMap)
var ptr []interface{}
for _, c := range columns {
ptr = append(ptr, &kvScanner{column: c, m: m})
}
return ptr
}
func dummyExtractor(columns []string, value reflect.Value) []interface{} {
return []interface{}{value.Addr().Interface()}
}
func findExtractor(t reflect.Type) (pointersExtractor, error) {
if reflect.PtrTo(t).Implements(typeScanner) {
return dummyExtractor, nil
}
switch t.Kind() {
case reflect.Map:
if !t.ConvertibleTo(typeKeyValueMap) {
return nil, fmt.Errorf("expected %v, got %v", typeKeyValueMap, t)
}
return mapExtractor, nil
case reflect.Ptr:
inner, err := findExtractor(t.Elem())
if err != nil {
return nil, err
}
return getIndirectExtractor(inner), nil
case reflect.Struct:
return getStructFieldsExtractor(t), nil
}
return dummyExtractor, nil
}