-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathutil.go
85 lines (76 loc) · 1.76 KB
/
util.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
package dbr
import (
"bytes"
"database/sql/driver"
"reflect"
"unicode"
)
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()
}
// 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
}
var (
typeValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
)
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)
}
if _, ok := m[tag]; !ok {
m[tag] = append(head, i)
}
structTraverse(m, field.Type, append(head, i))
}
}
}
// extractOriginal removes all ptr and interface wrappers
func extractOriginal(v reflect.Value) (reflect.Value, reflect.Kind) {
switch v.Kind() {
case reflect.Ptr:
if v.IsNil() {
return v, reflect.Ptr
}
return extractOriginal(v.Elem())
case reflect.Interface:
if v.IsNil() {
return v, reflect.Interface
}
return extractOriginal(v.Elem())
default:
return v, v.Kind()
}
}