-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinder_struct.go
78 lines (62 loc) · 1.29 KB
/
binder_struct.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
package sqle
import (
"reflect"
"strings"
"github.com/iancoleman/strcase"
)
type structBinder struct {
fieldIndexes map[string]int
fieldColumnNames []string
}
func newStructBinder(t reflect.Type, v reflect.Value) Binder {
sb := &structBinder{
fieldIndexes: make(map[string]int),
}
for i := 0; i < v.NumField(); i++ {
f := t.Field(i)
tagName := f.Tag.Get("db")
if tagName == "-" {
continue
}
if tagName != "" {
sb.fieldIndexes[tagName] = i
sb.fieldColumnNames = append(sb.fieldColumnNames, tagName)
continue
}
sb.fieldIndexes[strings.ToLower(f.Name)] = i
sb.fieldColumnNames = append(sb.fieldColumnNames, strcase.ToSnake(f.Name))
}
return sb
}
func (b *structBinder) Bind(v reflect.Value, columns []string) []any {
values := make([]any, len(columns))
var missed any
for k, n := range columns {
i, ok := b.fieldIndexes[n]
if ok {
values[k] = v.Field(i).Addr().Interface()
} else {
values[k] = &missed
}
}
return values
}
func getStructBinder(t reflect.Type, v reflect.Value) Binder {
bindersMu.RLock()
var b Binder
var cached bool
defer func() {
bindersMu.RUnlock()
if !cached {
bindersMu.Lock()
binders[t] = b
bindersMu.Unlock()
}
}()
b, cached = binders[t]
if cached {
return b
}
b = newStructBinder(t, v)
return b
}