-
Notifications
You must be signed in to change notification settings - Fork 1
/
document.go
122 lines (98 loc) · 2.15 KB
/
document.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
package bingodb
import (
"encoding/json"
)
type Data map[string]interface{}
type Document struct {
data Data
schema *TableSchema
}
func (data *Data) Length() int {
var d map[string]interface{} = *data
return len(d)
}
func Merge(doc *Document, op *Document) *Document {
if op == nil {
return doc
}
if doc == nil {
return op
}
if doc.schema != op.schema {
panic("The schema of the two docs are different")
}
newbie := make(map[string]interface{})
for k, v := range doc.data {
newbie[k] = v
}
for k, v := range op.data {
newbie[k] = v
}
return &Document{data: newbie, schema: doc.schema}
}
func (doc *Document) Merge(op *Document) *Document {
if op == nil {
return doc
}
if doc.schema != op.schema {
panic("The schema of the two docs are different")
}
newbie := make(map[string]interface{})
for k, v := range doc.data {
newbie[k] = v
}
for k, v := range op.data {
newbie[k] = v
}
return &Document{data: newbie, schema: doc.schema}
}
func ParseDoc(data *Data, schema *TableSchema) (*Document, error) {
//for doc, parsing nil equivalent to success
if data == nil || data.Length() == 0 {
return nil, nil
}
for _, field := range schema.fields {
raw, present := (*data)[field.Name]
if present {
val, err := field.Parse(raw)
if err != nil {
return nil, err
}
(*data)[field.Name] = val
}
}
return &Document{data: *data, schema: schema}, nil
}
func (doc *Document) Data() Data {
return doc.data
}
func (doc *Document) ToJSON() []byte {
bytes, err := json.Marshal(doc.data)
if err != nil {
return nil
}
return bytes
}
func (doc *Document) Get(schema *FieldSchema) interface{} {
if schema != nil {
return doc.data[schema.Name]
} else {
return nil
}
}
func (doc *Document) Fetch(field string) interface{} {
return doc.data[field]
}
func (doc *Document) GetExpiresAt() (int64, bool) {
if doc.schema.expireField == nil {
return 0, false
}
value, ok := doc.data[doc.schema.expireField.Name]
if !ok {
return 0, false
}
return value.(int64), ok
}
func (doc *Document) NewKeyTuple(schema *KeySchema) *KeyTuple {
return &KeyTuple{hash: doc.Get(schema.hashKey), sort: doc.Get(schema.sortKey)}
}