/
graphdb.go
71 lines (64 loc) · 1.58 KB
/
graphdb.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
package grids
import (
"fmt"
"os"
"path/filepath"
"github.com/bmeg/grip/gdbi"
"github.com/bmeg/grip/gripql"
"github.com/bmeg/grip/log"
)
// GridsGDB implements the GripInterface using a generic key/value storage driver
type GDB struct {
basePath string
drivers map[string]*Graph
}
// NewKVGraphDB intitalize a new grids graph driver
func NewGraphDB(baseDir string) (gdbi.GraphDB, error) {
log.Warning("GRIP driver is development. Do not use")
_, err := os.Stat(baseDir)
if os.IsNotExist(err) {
os.Mkdir(baseDir, 0700)
}
return &GDB{basePath: baseDir, drivers: map[string]*Graph{}}, nil
}
// Graph obtains the gdbi.DBI for a particular graph
func (kgraph *GDB) Graph(graph string) (gdbi.GraphInterface, error) {
err := gripql.ValidateGraphName(graph)
if err != nil {
return nil, err
}
if g, ok := kgraph.drivers[graph]; ok {
return g, nil
}
dbPath := filepath.Join(kgraph.basePath, graph)
if _, err := os.Stat(dbPath); err == nil {
g, err := newGraph(kgraph.basePath, graph)
if err != nil {
return nil, err
}
kgraph.drivers[graph] = g
return g, nil
}
return nil, fmt.Errorf("graph '%s' was not found", graph)
}
// ListGraphs lists the graphs managed by this driver
func (gdb *GDB) ListGraphs() []string {
out := []string{}
for k := range gdb.drivers {
out = append(out, k)
}
if ds, err := filepath.Glob(filepath.Join(gdb.basePath, "*")); err == nil {
for _, d := range ds {
b := filepath.Base(d)
out = append(out, b)
}
}
return out
}
// Close the graphs
func (kgraph *GDB) Close() error {
for _, g := range kgraph.drivers {
g.Close()
}
return nil
}