forked from dgraph-io/dgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
102 lines (92 loc) · 2.11 KB
/
schema.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
package main
import (
"fmt"
"log"
"sync"
"github.com/dgraph-io/badger"
"github.com/dgraph-io/dgraph/protos"
"github.com/dgraph-io/dgraph/types"
wk "github.com/dgraph-io/dgraph/worker"
"github.com/dgraph-io/dgraph/x"
)
type schemaState struct {
strict bool
*protos.SchemaUpdate
}
type schemaStore struct {
sync.RWMutex
m map[string]schemaState
}
func newSchemaStore(initial []*protos.SchemaUpdate, opt options) *schemaStore {
s := &schemaStore{
m: map[string]schemaState{
"_predicate_": {
strict: true,
SchemaUpdate: &protos.SchemaUpdate{
ValueType: uint32(types.StringID),
List: true,
},
},
},
}
if opt.StoreXids {
s.m["xid"] = schemaState{
strict: true,
SchemaUpdate: &protos.SchemaUpdate{
ValueType: uint32(protos.Posting_STRING),
Tokenizer: []string{"hash"},
},
}
}
for _, sch := range initial {
p := sch.Predicate
sch.Predicate = ""
if _, ok := s.m[p]; ok {
x.Check(fmt.Errorf("predicate %q already exists in schema", p))
}
s.m[p] = schemaState{true, sch}
}
return s
}
func (s *schemaStore) getSchema(pred string) *protos.SchemaUpdate {
s.RLock()
defer s.RUnlock()
return s.m[pred].SchemaUpdate
}
func (s *schemaStore) validateType(de *protos.DirectedEdge, objectIsUID bool) {
if objectIsUID {
de.ValueType = uint32(protos.Posting_UID)
}
s.RLock()
sch, ok := s.m[de.Attr]
s.RUnlock()
if !ok {
s.Lock()
sch, ok = s.m[de.Attr]
if !ok {
sch = schemaState{false, &protos.SchemaUpdate{ValueType: de.ValueType}}
s.m[de.Attr] = sch
}
s.Unlock()
}
schTyp := types.TypeID(sch.ValueType)
err := wk.ValidateAndConvert(de, schTyp)
if sch.strict && err != nil {
// TODO: It's unclear to me as to why it's only an error to have a bad
// conversion if the schema was established explicitly rather than
// automatically.
log.Fatalf("RDF doesn't match schema: %v", err)
}
}
func (s *schemaStore) write(kv *badger.KV) {
for pred, sch := range s.m {
k := x.SchemaKey(pred)
var v []byte
var err error
if sch.SchemaUpdate != nil {
v, err = sch.SchemaUpdate.Marshal()
x.Check(err)
}
x.Check(kv.Set(k, v, 0x00))
}
}