/
load_by_id.go
98 lines (93 loc) · 2.47 KB
/
load_by_id.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
package beeorm
import (
"fmt"
"reflect"
"strconv"
)
const cacheNilValue = ""
func loadByID(serializer *serializer, engine *engineImplementation, id uint64, entity Entity, useCache bool, references ...string) (found bool, schema *entitySchema) {
orm := initIfNeeded(engine.registry, entity)
schema = orm.entitySchema
localCache, hasLocalCache := schema.GetLocalCache(engine)
redisCache, hasRedis := schema.GetRedisCache(engine)
var cacheKey string
if useCache {
if hasLocalCache {
e, has := localCache.Get(id)
if has {
if e == cacheNilValue {
return false, schema
}
data := e.([]byte)
fillFromBinary(serializer, engine.registry, data, entity)
if len(references) > 0 {
warmUpReferences(serializer, engine, schema, orm.value, references, false)
}
return true, schema
}
}
if hasRedis {
cacheKey = strconv.FormatUint(id, 10)
row, has := redisCache.HGet(schema.cachePrefix, cacheKey)
if has {
if row == cacheNilValue {
if localCache != nil {
localCache.Set(cacheKey, cacheNilValue)
}
return false, schema
}
fillFromBinary(serializer, engine.registry, []byte(row), entity)
if len(references) > 0 {
warmUpReferences(serializer, engine, schema, orm.value, references, false)
}
if localCache != nil {
localCache.Set(id, orm.copyBinary())
}
return true, schema
}
}
}
where := NewWhere("`ID` = ?", id)
found, _, data := searchRow(serializer, engine, where, entity, false, nil)
if !found {
if localCache != nil {
localCache.Set(cacheKey, cacheNilValue)
}
if redisCache != nil {
redisCache.HSet(schema.cachePrefix, cacheKey, cacheNilValue)
}
return false, schema
}
if useCache {
if localCache != nil {
localCache.Set(cacheKey, orm.copyBinary())
}
if redisCache != nil {
redisCache.HSet(schema.cachePrefix, cacheKey, orm.binary)
}
}
if len(references) > 0 {
warmUpReferences(serializer, engine, schema, orm.elem, references, false)
} else {
data[0] = id
}
return true, schema
}
func initIfNeeded(registry *validatedRegistry, entity Entity) *ORM {
orm := entity.getORM()
if !orm.initialised {
orm.initialised = true
value := reflect.ValueOf(entity)
elem := value.Elem()
t := elem.Type()
entitySchema := getEntitySchema(registry, t)
if entitySchema == nil {
panic(fmt.Errorf("entity '%s' is not registered", t.String()))
}
orm.entitySchema = entitySchema
orm.value = value
orm.elem = elem
orm.idElem = elem.Field(1)
}
return orm
}