-
Notifications
You must be signed in to change notification settings - Fork 31
/
values.go
71 lines (58 loc) · 1.59 KB
/
values.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
package scan
import (
"fmt"
"reflect"
"sync"
)
var valuesCache cache = &sync.Map{}
// Values scans a struct and returns the values associated with the columns
// provided. Only simple value types are supported (i.e. Bool, Ints, Uints,
// Floats, Interface, String)
func Values(cols []string, v interface{}) ([]interface{}, error) {
vals := make([]interface{}, len(cols))
model, err := reflectValue(v)
if err != nil {
return nil, fmt.Errorf("values: %w", err)
}
fields := loadFields(model)
for i, col := range cols {
j, ok := fields[col]
if !ok {
return nil, fmt.Errorf("field %T.%q either does not exist or is unexported: %w", v, col, ErrStructFieldMissing)
}
vals[i] = model.FieldByIndex(j).Interface()
}
return vals, nil
}
func loadFields(val reflect.Value) map[string][]int {
if cache, cached := valuesCache.Load(val.Type()); cached {
return cache.(map[string][]int)
}
return writeFieldsCache(val)
}
func writeFieldsCache(val reflect.Value) map[string][]int {
m := map[string][]int{}
writeFields(val, m, []int{})
valuesCache.Store(val.Type(), m)
return m
}
func writeFields(val reflect.Value, m map[string][]int, index []int) {
typ := val.Type()
numfield := val.NumField()
for i := 0; i < numfield; i++ {
valField := val.Field(i)
if !valField.CanSet() {
continue
}
field := typ.Field(i)
fieldIndex := append(index, field.Index...)
if field.Type.Kind() == reflect.Struct && !isValidSqlValue(valField) {
writeFields(valField, m, fieldIndex)
continue
}
m[field.Name] = fieldIndex
if tag, ok := field.Tag.Lookup(dbTag); ok {
m[tag] = fieldIndex
}
}
}