schema.go
1.73 KB
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
package db
import (
"reflect"
"strings"
)
type Schema struct {
mgo *MgoColl
reflectValue *reflect.Value
reflectType reflect.Type
cacheFields map[string]interface{}
pri interface{}
schema interface{}
}
func NewSchema(key string, schema interface{}) *Schema {
s := reflect.ValueOf(schema)
if s.Kind() == reflect.Ptr {
s = reflect.ValueOf(schema).Elem()
}
sch := &Schema{
reflectValue: &s,
reflectType: s.Type(),
cacheFields: make(map[string]interface{}),
schema: schema,
}
sch.mgo = NewMongoColl(sch)
sch.pri = GetBsonD(sch.getPriTag(), key)
return sch
}
func (s *Schema) GetSchemaType() reflect.Type {
return s.reflectType
}
func (s *Schema) GetCollName() string {
return strings.ToLower(s.GetSchemaType().Name())
}
func (s *Schema) getPriTag() string {
var pri string
for i := 0; i < s.reflectType.NumField(); i++ {
if s.reflectType.Field(i).Tag.Get("pri") == "1" {
pri = strings.ToLower(s.reflectType.Field(i).Name)
break
}
}
return pri
}
func (s *Schema) GetPri() interface{} {
return s.pri
}
func (s *Schema) GetSchema() interface{} {
return s.schema
}
func (s *Schema) Load() error {
return s.mgo.Load()
}
func (s *Schema) Create() error {
_, err := s.mgo.Create()
return err
}
func (s *Schema) Update() {
if s.cacheFields != nil {
s.mgo.UpdateProperties(s.cacheFields)
s.cacheFields = make(map[string]interface{})
}
}
func (s *Schema) SetProperty(key string, val interface{}) {
s.reflectValue.FieldByName(key).Set(reflect.ValueOf(val))
s.cacheFields[strings.ToLower(key)] = val
}
func (s *Schema) SetProperties(properties map[string]interface{}) {
for key, val := range properties {
s.reflectValue.FieldByName(key).Set(reflect.ValueOf(val))
s.cacheFields[strings.ToLower(key)] = val
}
}