This repository has been archived by the owner on Mar 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
cache.go
139 lines (113 loc) · 2.45 KB
/
cache.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
package goloquent
import (
"fmt"
"log"
"reflect"
"strings"
"sync"
)
type structDefinition struct {
fields []structField
}
type structField struct {
t reflect.Type
tag structTag
def *structDefinition
}
type structTag struct {
name string
opts map[string]string
}
func parseStructTag(tags []string, f reflect.StructField) (t structTag) {
t.name = f.Name
t.opts = make(map[string]string)
var paths []string
for _, tag := range tags {
v, ok := f.Tag.Lookup(tag)
if !ok {
continue
}
paths = strings.Split(v, ",")
paths[0] = strings.TrimSpace(paths[0])
if len(paths[0]) > 0 {
t.name = paths[0]
paths = paths[1:]
}
for _, p := range paths {
t.opts[p] = p
}
}
return
}
type entityCache struct {
mu sync.Mutex
tag []string
cache map[reflect.Type]*structDefinition
}
var ec = &entityCache{
tag: []string{"db", "datastore", "goloquent"},
cache: make(map[reflect.Type]*structDefinition),
}
func codecByType(t reflect.Type) *structDefinition {
sd, ok := ec.cache[t]
if ok {
return sd
}
ec.mu.Lock()
defer ec.mu.Unlock()
sd, err := getCodec(ec.tag, t)
if err != nil {
panic(err)
}
ec.cache[t] = sd
return ec.cache[t]
}
type typeQueue struct {
t reflect.Type
parentPath string
}
func getCodec(tagName []string, t reflect.Type) (*structDefinition, error) {
queue := []typeQueue{}
queue = append(queue, typeQueue{elem(t), ""})
sd := new(structDefinition)
for len(queue) > 0 {
q := queue[0]
sf := structField{}
for i := 0; i < q.t.NumField(); i++ {
f := q.t.Field(i)
// skip unexported fields
if len(f.PkgPath) != 0 && !f.Anonymous {
continue
}
log.Println(f)
tag := parseStructTag(tagName, f)
switch {
case tag.name == "-":
continue
case !isValidFieldName(tag.name):
return nil, fmt.Errorf("goloquent: struct tag has invalid field name: %q", tag.name)
case isReserveFieldName(tag.name):
return nil, fmt.Errorf("goloquent: struct tag has reserved field name: %q", tag.name)
// case st.isPrimaryKey():
// if sf.Type != typeOfPtrKey {
// return nil, fmt.Errorf("goloquent: %s field on struct %v must be *datastore.Key", keyFieldName, ft)
// }
}
sf.t = f.Type
sf.tag = tag
ft := elem(f.Type)
if ft.Kind() == reflect.Struct {
}
sd.fields = append(sd.fields, sf)
}
queue = queue[1:]
}
log.Println(sd)
return sd, nil
}
func elem(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}