-
Notifications
You must be signed in to change notification settings - Fork 639
Expand file tree
/
Copy pathstruct_map.go
More file actions
94 lines (88 loc) · 1.82 KB
/
struct_map.go
File metadata and controls
94 lines (88 loc) · 1.82 KB
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
package clickhouse
import (
"fmt"
"reflect"
"sync"
)
type structMap struct {
cache sync.Map
}
func (m *structMap) Map(op string, columns []string, s any, ptr bool) ([]any, error) {
v := reflect.ValueOf(s)
if v.Kind() != reflect.Ptr {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("must pass a pointer, not a value, to %s destination", op),
}
}
if v.IsNil() {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("nil pointer passed to %s destination", op),
}
}
t := reflect.TypeOf(s)
if v = reflect.Indirect(v); t.Kind() == reflect.Ptr {
t = t.Elem()
}
if v.Kind() != reflect.Struct {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("%s expects a struct dest", op),
}
}
var (
index map[string][]int
values = make([]any, 0, len(columns))
)
switch idx, found := m.cache.Load(t); {
case found:
index = idx.(map[string][]int)
default:
index = structIdx(t)
m.cache.Store(t, index)
}
for _, name := range columns {
idx, found := index[name]
if !found {
return nil, &OpError{
Op: op,
Err: fmt.Errorf("missing destination name %q in %T", name, s),
}
}
switch field := v.FieldByIndex(idx); {
case ptr:
values = append(values, field.Addr().Interface())
default:
values = append(values, field.Interface())
}
}
return values, nil
}
func structIdx(t reflect.Type) map[string][]int {
fields := make(map[string][]int)
for i := 0; i < t.NumField(); i++ {
var (
f = t.Field(i)
name = f.Name
)
if tn := f.Tag.Get("ch"); len(tn) != 0 {
name = tn
}
switch {
case name == "-", len(f.PkgPath) != 0 && !f.Anonymous:
continue
}
switch {
case f.Anonymous:
if f.Type.Kind() != reflect.Ptr {
for k, idx := range structIdx(f.Type) {
fields[k] = append(f.Index, idx...)
}
}
default:
fields[name] = f.Index
}
}
return fields
}