/
gomdise.go
95 lines (84 loc) · 1.83 KB
/
gomdise.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
package gomdise
import (
"errors"
"reflect"
"runtime"
"sync"
"github.com/garyburd/redigo/redis"
"github.com/LindenY/gomdise/mdl"
"github.com/LindenY/gomdise/tpl"
"github.com/LindenY/gomdise/trans"
)
type Gomdise struct {
sync.RWMutex
pool *redis.Pool
opts map[string]interface{}
}
func (gom *Gomdise) SetOption(key string, val interface{}) {
gom.Lock()
defer gom.Unlock()
gom.opts[key] = val
}
func (gom *Gomdise) GetOption(key string) (interface{}, bool) {
gom.RLock()
defer gom.RUnlock()
val, ok := gom.opts[key]
return val, ok
}
func (gom *Gomdise) Save(arg interface{}) (key string, err error) {
defer func() {
err = errorRecover()
if err != nil {
key = ""
}
}()
tpl := tpl.TCSave.GetTemplate(reflect.TypeOf(arg))
tran := trans.NewTransaction(gom.pool)
v := reflect.ValueOf(arg)
key = mdl.NewKey(v)
tpl.Engrave(&tran.Actions, key, v)
tran.Exec()
return key, nil
}
func (gom *Gomdise) SaveWithKey(arg interface{}, key string) (err error) {
defer func() {
err = errorRecover()
}()
tpl := tpl.TCSave.GetTemplate(reflect.TypeOf(arg))
tran := trans.NewTransaction(gom.pool)
v := reflect.ValueOf(arg)
tpl.Engrave(&tran.Actions, key, v)
tran.Exec()
return nil
}
func (gom *Gomdise) Find(key string, dest interface{}) (err error) {
defer func() {
err = errorRecover()
}()
tpl := tpl.TCFind.GetTemplate(reflect.TypeOf(dest))
tran := trans.NewTransaction(gom.pool)
tpl.Engrave(&tran.Actions, key)
root := tran.Actions[0]
tran.Exec()
mdl.Decode(root, dest)
return nil
}
func New(pool *redis.Pool) *Gomdise {
gom := &Gomdise{
pool: pool,
opts: make(map[string]interface{}, 0),
}
return gom
}
func errorRecover() (err error) {
if r := recover(); r != nil {
if _, ok := r.(runtime.Error); ok {
panic(r)
}
if s, ok := r.(string); ok {
err = errors.New(s)
}
err = r.(error)
}
return nil
}