-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
schema.go
412 lines (370 loc) · 9.58 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*
* Copyright 2016-2018 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package schema
import (
"bytes"
"fmt"
"sync"
"github.com/dgraph-io/badger"
"github.com/golang/glog"
"golang.org/x/net/trace"
"github.com/dgraph-io/dgraph/protos/pb"
"github.com/dgraph-io/dgraph/tok"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/x"
)
var (
pstate *state
pstore *badger.DB
)
func (s *state) init() {
s.predicate = make(map[string]*pb.SchemaUpdate)
s.types = make(map[string]*pb.TypeUpdate)
s.elog = trace.NewEventLog("Dgraph", "Schema")
}
type state struct {
sync.RWMutex
// Map containing predicate to type information.
predicate map[string]*pb.SchemaUpdate
types map[string]*pb.TypeUpdate
elog trace.EventLog
}
// SateFor returns the schema for given group
func State() *state {
return pstate
}
func (s *state) DeleteAll() {
s.Lock()
defer s.Unlock()
for pred := range s.predicate {
// Predicates in x.InitialPreds represent internal predicates which
// shouldn't be dropped.
if !x.IsReservedPredicate(pred) {
delete(s.predicate, pred)
}
}
for typ := range s.types {
delete(s.types, typ)
}
}
// Delete updates the schema in memory and disk
func (s *state) Delete(attr string) error {
s.Lock()
defer s.Unlock()
glog.Infof("Deleting schema for predicate: [%s]", attr)
delete(s.predicate, attr)
txn := pstore.NewTransactionAt(1, true)
if err := txn.Delete(x.SchemaKey(attr)); err != nil {
return err
}
// Delete is called rarely so sync write should be fine.
return txn.CommitAt(1, nil)
}
// DeleteType updates the schema in memory and disk
func (s *state) DeleteType(typeName string) error {
s.Lock()
defer s.Unlock()
glog.Infof("Deleting type definition for type: [%s]", typeName)
delete(s.types, typeName)
txn := pstore.NewTransactionAt(1, true)
if err := txn.Delete(x.TypeKey(typeName)); err != nil {
return err
}
// Delete is called rarely so sync write should be fine.
return txn.CommitAt(1, nil)
}
func logUpdate(schema pb.SchemaUpdate, pred string) string {
typ := types.TypeID(schema.ValueType).Name()
if schema.List {
typ = fmt.Sprintf("[%s]", typ)
}
return fmt.Sprintf("Setting schema for attr %s: %v, tokenizer: %v, directive: %v, count: %v\n",
pred, typ, schema.Tokenizer, schema.Directive, schema.Count)
}
func logTypeUpdate(typ pb.TypeUpdate, typeName string) string {
return fmt.Sprintf("Setting type definition for type %s: %v\n", typeName, typ)
}
// Set sets the schema for the given predicate in memory.
// Schema mutations must flow through the update function, which are synced to the db.
func (s *state) Set(pred string, schema pb.SchemaUpdate) {
s.Lock()
defer s.Unlock()
s.predicate[pred] = &schema
s.elog.Printf(logUpdate(schema, pred))
}
// SetType sets the type for the given predicate in memory.
// schema mutations must flow through the update function, which are synced to the db.
func (s *state) SetType(typeName string, typ pb.TypeUpdate) {
s.Lock()
defer s.Unlock()
s.types[typeName] = &typ
s.elog.Printf(logTypeUpdate(typ, typeName))
}
// Get gets the schema for the given predicate.
func (s *state) Get(pred string) (pb.SchemaUpdate, bool) {
s.RLock()
defer s.RUnlock()
schema, has := s.predicate[pred]
if !has {
return pb.SchemaUpdate{}, false
}
return *schema, true
}
// GetType gets the type definition for the given type name.
func (s *state) GetType(typeName string) (pb.TypeUpdate, bool) {
s.RLock()
defer s.RUnlock()
typ, has := s.types[typeName]
if !has {
return pb.TypeUpdate{}, false
}
return *typ, true
}
// TypeOf returns the schema type of predicate
func (s *state) TypeOf(pred string) (types.TypeID, error) {
s.RLock()
defer s.RUnlock()
if schema, ok := s.predicate[pred]; ok {
return types.TypeID(schema.ValueType), nil
}
return types.UndefinedID, x.Errorf("Schema not defined for predicate: %v.", pred)
}
// IsIndexed returns whether the predicate is indexed or not
func (s *state) IsIndexed(pred string) bool {
s.RLock()
defer s.RUnlock()
if schema, ok := s.predicate[pred]; ok {
return len(schema.Tokenizer) > 0
}
return false
}
// IndexedFields returns the list of indexed fields
func (s *state) IndexedFields() []string {
s.RLock()
defer s.RUnlock()
var out []string
for k, v := range s.predicate {
if len(v.Tokenizer) > 0 {
out = append(out, k)
}
}
return out
}
// Predicates returns the list of predicates for given group
func (s *state) Predicates() []string {
s.RLock()
defer s.RUnlock()
var out []string
for k := range s.predicate {
out = append(out, k)
}
return out
}
// Types returns the list of types.
func (s *state) Types() []string {
s.RLock()
defer s.RUnlock()
var out []string
for k := range s.types {
out = append(out, k)
}
return out
}
// Tokenizer returns the tokenizer for given predicate
func (s *state) Tokenizer(pred string) []tok.Tokenizer {
s.RLock()
defer s.RUnlock()
schema, ok := s.predicate[pred]
x.AssertTruef(ok, "schema state not found for %s", pred)
var tokenizers []tok.Tokenizer
for _, it := range schema.Tokenizer {
t, found := tok.GetTokenizer(it)
x.AssertTruef(found, "Invalid tokenizer %s", it)
tokenizers = append(tokenizers, t)
}
return tokenizers
}
// TokenizerNames returns the tokenizer names for given predicate
func (s *state) TokenizerNames(pred string) []string {
var names []string
tokenizers := s.Tokenizer(pred)
for _, t := range tokenizers {
names = append(names, t.Name())
}
return names
}
// HasTokenizer is a convenience func that checks if a given tokenizer is found in pred.
// Returns true if found, else false.
func (s *state) HasTokenizer(id byte, pred string) bool {
for _, t := range s.Tokenizer(pred) {
if t.Identifier() == id {
return true
}
}
return false
}
// IsReversed returns whether the predicate has reverse edge or not
func (s *state) IsReversed(pred string) bool {
s.RLock()
defer s.RUnlock()
if schema, ok := s.predicate[pred]; ok {
return schema.Directive == pb.SchemaUpdate_REVERSE
}
return false
}
// HasCount returns whether we want to mantain a count index for the given predicate or not.
func (s *state) HasCount(pred string) bool {
s.RLock()
defer s.RUnlock()
if schema, ok := s.predicate[pred]; ok {
return schema.Count
}
return false
}
// IsList returns whether the predicate is of list type.
func (s *state) IsList(pred string) bool {
s.RLock()
defer s.RUnlock()
if schema, ok := s.predicate[pred]; ok {
return schema.List
}
return false
}
func (s *state) HasUpsert(pred string) bool {
s.RLock()
defer s.RUnlock()
if schema, ok := s.predicate[pred]; ok {
return schema.Upsert
}
return false
}
func (s *state) HasLang(pred string) bool {
s.RLock()
defer s.RUnlock()
if schema, ok := s.predicate[pred]; ok {
return schema.Lang
}
return false
}
func Init(ps *badger.DB) {
pstore = ps
reset()
}
func Load(predicate string) error {
if len(predicate) == 0 {
return x.Errorf("Empty predicate")
}
key := x.SchemaKey(predicate)
txn := pstore.NewTransactionAt(1, false)
defer txn.Discard()
item, err := txn.Get(key)
if err == badger.ErrKeyNotFound {
return nil
}
if err != nil {
return err
}
var s pb.SchemaUpdate
err = item.Value(func(val []byte) error {
x.Check(s.Unmarshal(val))
return nil
})
if err != nil {
return err
}
State().Set(predicate, s)
State().elog.Printf(logUpdate(s, predicate))
glog.Infoln(logUpdate(s, predicate))
return nil
}
// LoadFromDb reads schema information from db and stores it in memory
func LoadFromDb() error {
if err := LoadSchemaFromDb(); err != nil {
return err
}
if err := LoadTypesFromDb(); err != nil {
return err
}
return nil
}
func LoadSchemaFromDb() error {
prefix := x.SchemaPrefix()
txn := pstore.NewTransactionAt(1, false)
defer txn.Discard()
itr := txn.NewIterator(badger.DefaultIteratorOptions) // Need values, reversed=false.
defer itr.Close()
for itr.Seek(prefix); itr.Valid(); itr.Next() {
item := itr.Item()
key := item.Key()
if !bytes.HasPrefix(key, prefix) {
break
}
pk := x.Parse(key)
if pk == nil {
continue
}
attr := pk.Attr
var s pb.SchemaUpdate
err := item.Value(func(val []byte) error {
if len(val) == 0 {
s = pb.SchemaUpdate{Predicate: attr, ValueType: pb.Posting_DEFAULT}
}
x.Checkf(s.Unmarshal(val), "Error while loading schema from db")
State().Set(attr, s)
return nil
})
if err != nil {
return err
}
}
return nil
}
func LoadTypesFromDb() error {
prefix := x.TypePrefix()
txn := pstore.NewTransactionAt(1, false)
defer txn.Discard()
itr := txn.NewIterator(badger.DefaultIteratorOptions) // Need values, reversed=false.
defer itr.Close()
for itr.Seek(prefix); itr.Valid(); itr.Next() {
item := itr.Item()
key := item.Key()
if !bytes.HasPrefix(key, prefix) {
break
}
pk := x.Parse(key)
if pk == nil {
continue
}
attr := pk.Attr
var t pb.TypeUpdate
err := item.Value(func(val []byte) error {
if len(val) == 0 {
t = pb.TypeUpdate{TypeName: attr}
}
x.Checkf(t.Unmarshal(val), "Error while loading types from db")
State().SetType(attr, t)
return nil
})
if err != nil {
return err
}
}
return nil
}
func reset() {
pstate = new(state)
pstate.init()
}