-
Notifications
You must be signed in to change notification settings - Fork 678
/
repo.go
111 lines (91 loc) · 2.39 KB
/
repo.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
// _ _
// __ _____ __ ___ ___ __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
// \ V V / __/ (_| |\ V /| | (_| | || __/
// \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
// Copyright © 2016 - 2021 SeMI Technologies B.V. All rights reserved.
//
// CONTACT: hello@semi.technology
//
package schema
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/pkg/errors"
"github.com/semi-technologies/weaviate/adapters/repos/db/helpers"
schemauc "github.com/semi-technologies/weaviate/usecases/schema"
"github.com/sirupsen/logrus"
bolt "go.etcd.io/bbolt"
)
var (
schemaBucket = []byte("schema")
schemaKey = []byte("schema")
)
type Repo struct {
logger logrus.FieldLogger
baseDir string
db *bolt.DB
}
func NewRepo(baseDir string, logger logrus.FieldLogger) (*Repo, error) {
r := &Repo{
baseDir: baseDir,
logger: logger,
}
err := r.init()
return r, err
}
func (r *Repo) DBPath() string {
return fmt.Sprintf("%s/schema.db", r.baseDir)
}
func (r *Repo) init() error {
if err := os.MkdirAll(r.baseDir, 0o777); err != nil {
return errors.Wrapf(err, "create root path directory at %s", r.baseDir)
}
boltdb, err := bolt.Open(r.DBPath(), 0o600, nil)
if err != nil {
return errors.Wrapf(err, "open bolt at %s", r.DBPath())
}
err = boltdb.Update(func(tx *bolt.Tx) error {
if _, err := tx.CreateBucketIfNotExists(schemaBucket); err != nil {
return errors.Wrapf(err, "create schema bucket '%s'",
string(helpers.ObjectsBucket))
}
return nil
})
if err != nil {
return errors.Wrapf(err, "create bolt buckets")
}
r.db = boltdb
return nil
}
func (r *Repo) SaveSchema(ctx context.Context, schema schemauc.State) error {
schemaJSON, err := json.Marshal(schema)
if err != nil {
return errors.Wrapf(err, "marshal schema state to json")
}
return r.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(schemaBucket)
return b.Put(schemaKey, schemaJSON)
})
}
func (r *Repo) LoadSchema(ctx context.Context) (*schemauc.State, error) {
var schemaJSON []byte
r.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(schemaBucket)
schemaJSON = b.Get(schemaKey)
return nil
})
if len(schemaJSON) == 0 {
return nil, nil
}
var state schemauc.State
err := json.Unmarshal(schemaJSON, &state)
if err != nil {
return nil, errors.Wrapf(err, "parse schema state from JSON")
}
return &state, nil
}
var _ = schemauc.Repo(&Repo{})