-
Notifications
You must be signed in to change notification settings - Fork 2
/
scope_cache.go
72 lines (58 loc) · 1.36 KB
/
scope_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
package goen
import (
"sync"
)
type ScopeCache struct {
Meta *MetaSchema
mu sync.RWMutex
data map[string]interface{}
}
func NewScopeCache(meta *MetaSchema) *ScopeCache {
return &ScopeCache{
Meta: meta,
data: map[string]interface{}{},
}
}
func (sc *ScopeCache) GetObject(rowKey RowKey) interface{} {
sc.mu.RLock()
defer sc.mu.RUnlock()
key := sc.Meta.KeyStringFromRowKey(rowKey)
return sc.data[key]
}
func (sc *ScopeCache) AddObject(v interface{}) {
sc.mu.Lock()
defer sc.mu.Unlock()
pk := sc.Meta.PrimaryKeyOf(v)
pkKey := sc.Meta.KeyStringFromRowKey(pk)
sc.data[pkKey] = v
refes := sc.Meta.ReferenceKeysOf(v)
for _, refe := range refes {
refeKey := sc.Meta.KeyStringFromRowKey(refe)
if pkKey == refeKey {
continue
}
var slice []interface{}
if cached, ok := sc.data[refeKey]; ok {
slice = cached.([]interface{})
}
sc.data[refeKey] = append(slice, v)
}
}
func (sc *ScopeCache) HasObject(rowKey RowKey) bool {
sc.mu.RLock()
defer sc.mu.RUnlock()
key := sc.Meta.KeyStringFromRowKey(rowKey)
_, ok := sc.data[key]
return ok
}
func (sc *ScopeCache) RemoveObject(v interface{}) {
sc.mu.Lock()
defer sc.mu.Unlock()
var keys []RowKey
keys = append(keys, sc.Meta.ReferenceKeysOf(v)...)
keys = append(keys, sc.Meta.PrimaryKeyOf(v))
for _, rowKey := range keys {
key := sc.Meta.KeyStringFromRowKey(rowKey)
delete(sc.data, key)
}
}