forked from cayleygraph/cayley
/
database.go
295 lines (271 loc) · 7.31 KB
/
database.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
package command
import (
"errors"
"fmt"
"os"
"runtime"
"runtime/pprof"
"sort"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/internal"
"github.com/cayleygraph/cayley/quad"
)
const (
KeyBackend = "store.backend"
KeyAddress = "store.address"
KeyPath = "store.path"
KeyReadOnly = "store.read_only"
KeyOptions = "store.options"
KeyLoadBatch = "load.batch"
)
const (
flagLoad = "load"
flagLoadFormat = "load_format"
flagDump = "dump"
flagDumpFormat = "dump_format"
)
var ErrNotPersistent = errors.New("database type is not persistent")
func registerLoadFlags(cmd *cobra.Command) {
// TODO: allow to load multiple files
cmd.Flags().StringP(flagLoad, "i", "", `quad file to load after initialization (".gz" supported, "-" for stdin)`)
var names []string
for _, f := range quad.Formats() {
if f.Reader != nil {
names = append(names, f.Name)
}
}
sort.Strings(names)
cmd.Flags().String(flagLoadFormat, "", `quad file format to use for loading instead of auto-detection ("`+strings.Join(names, `", "`)+`")`)
}
func registerDumpFlags(cmd *cobra.Command) {
cmd.Flags().StringP(flagDump, "o", "", `quad file to dump the database to (".gz" supported, "-" for stdout)`)
var names []string
for _, f := range quad.Formats() {
if f.Writer != nil {
names = append(names, f.Name)
}
}
sort.Strings(names)
cmd.Flags().String(flagDumpFormat, "", `quad file format to use instead of auto-detection ("`+strings.Join(names, `", "`)+`")`)
}
func NewInitDatabaseCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "init",
Short: "Create an empty database.",
RunE: func(cmd *cobra.Command, args []string) error {
printBackendInfo()
name := viper.GetString(KeyBackend)
if graph.IsRegistered(name) && !graph.IsPersistent(name) {
return ErrNotPersistent
}
// TODO: maybe check read-only flag in config before that?
if err := initDatabase(); err != nil {
return err
}
return nil
},
}
return cmd
}
func NewLoadDatabaseCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "load",
Short: "Bulk-load a quad file into the database.",
RunE: func(cmd *cobra.Command, args []string) error {
printBackendInfo()
p := mustSetupProfile(cmd)
defer mustFinishProfile(p)
load, _ := cmd.Flags().GetString(flagLoad)
if load == "" && len(args) == 1 {
load = args[0]
}
if load == "" {
return errors.New("one quads file must be specified")
}
if init, err := cmd.Flags().GetBool("init"); err != nil {
return err
} else if init {
if err = initDatabase(); err != nil {
return err
}
}
h, err := openDatabase()
if err != nil {
return err
}
defer h.Close()
// TODO: check read-only flag in config before that?
typ, _ := cmd.Flags().GetString(flagLoadFormat)
if err = internal.Load(h.QuadWriter, quad.DefaultBatch, load, typ); err != nil {
return err
}
if dump, _ := cmd.Flags().GetString(flagDump); dump != "" {
typ, _ := cmd.Flags().GetString(flagDumpFormat)
if err = dumpDatabase(h, dump, typ); err != nil {
return err
}
}
return nil
},
}
cmd.Flags().Bool("init", false, "initialize the database before using it")
registerLoadFlags(cmd)
registerDumpFlags(cmd)
return cmd
}
func NewDumpDatabaseCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "dump",
Short: "Bulk-dump the database into a quad file.",
RunE: func(cmd *cobra.Command, args []string) error {
printBackendInfo()
dump, _ := cmd.Flags().GetString(flagDump)
if dump == "" && len(args) == 1 {
dump = args[0]
}
if dump == "" {
dump = "-"
}
h, err := openDatabase()
if err != nil {
return err
}
defer h.Close()
typ, _ := cmd.Flags().GetString(flagDumpFormat)
return dumpDatabase(h, dump, typ)
},
}
registerDumpFlags(cmd)
return cmd
}
func NewUpgradeCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "upgrade",
Short: "Upgrade Cayley database to current supported format.",
RunE: func(cmd *cobra.Command, args []string) error {
printBackendInfo()
name := viper.GetString(KeyBackend)
if graph.IsRegistered(name) && !graph.IsPersistent(name) {
return ErrNotPersistent
}
addr := viper.GetString(KeyAddress)
opts := graph.Options(viper.GetStringMap(KeyOptions))
clog.Infof("upgrading database...")
return graph.UpgradeQuadStore(name, addr, opts)
},
}
return cmd
}
func printBackendInfo() {
name := viper.GetString(KeyBackend)
path := viper.GetString(KeyAddress)
if path != "" {
path = " (" + path + ")"
}
clog.Infof("using backend %q%s", name, path)
}
func initDatabase() error {
name := viper.GetString(KeyBackend)
path := viper.GetString(KeyAddress)
opts := viper.GetStringMap(KeyOptions)
return graph.InitQuadStore(name, path, graph.Options(opts))
}
func openDatabase() (*graph.Handle, error) {
name := viper.GetString(KeyBackend)
path := viper.GetString(KeyAddress)
opts := graph.Options(viper.GetStringMap(KeyOptions))
qs, err := graph.NewQuadStore(name, path, opts)
if err != nil {
return nil, err
}
qw, err := graph.NewQuadWriter("single", qs, opts)
if err != nil {
return nil, err
}
return &graph.Handle{QuadStore: qs, QuadWriter: qw}, nil
}
func openForQueries(cmd *cobra.Command) (*graph.Handle, error) {
if init, err := cmd.Flags().GetBool("init"); err != nil {
return nil, err
} else if init {
if err = initDatabase(); err == graph.ErrDatabaseExists {
clog.Infof("database already initialized, skipping init")
} else if err != nil {
return nil, err
}
}
var load string
h, err := openDatabase()
if err == graph.ErrQuadStoreNotPersistent {
load = viper.GetString(KeyAddress)
viper.Set(KeyAddress, "")
h, err = openDatabase()
}
if err == graph.ErrQuadStoreNotPersistent {
return nil, fmt.Errorf("%v; did you mean -i flag?", err)
} else if err != nil {
return nil, err
}
if load2, _ := cmd.Flags().GetString(flagLoad); load2 != "" {
if load != "" {
h.Close()
return nil, fmt.Errorf("both -a and -i flags cannot be specified")
}
load = load2
}
if load != "" {
typ, _ := cmd.Flags().GetString(flagLoadFormat)
// TODO: check read-only flag in config before that?
start := time.Now()
if err = internal.Load(h.QuadWriter, quad.DefaultBatch, load, typ); err != nil {
h.Close()
return nil, err
}
clog.Infof("loaded %q in %v", load, time.Since(start))
}
return h, nil
}
type profileData struct {
cpuProfile *os.File
memPath string
}
func mustSetupProfile(cmd *cobra.Command) profileData {
p := profileData{}
mpp := cmd.Flag("memprofile")
p.memPath = mpp.Value.String()
cpp := cmd.Flag("cpuprofile")
v := cpp.Value.String()
if v != "" {
f, err := os.Create(v)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not open CPU profile file %s\n", v)
os.Exit(1)
}
p.cpuProfile = f
pprof.StartCPUProfile(f)
}
return p
}
func mustFinishProfile(p profileData) {
if p.cpuProfile != nil {
pprof.StopCPUProfile()
p.cpuProfile.Close()
}
if p.memPath != "" {
f, err := os.Create(p.memPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not open memory profile file %s\n", p.memPath)
os.Exit(1)
}
runtime.GC()
if err := pprof.WriteHeapProfile(f); err != nil {
fmt.Fprintf(os.Stderr, "Could not write memory profile file %s\n", p.memPath)
}
f.Close()
}
}