forked from cosmos/cosmos-db
-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.go
69 lines (59 loc) · 1.8 KB
/
db.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
package db
import (
"fmt"
"strings"
)
type BackendType string
// These are valid backend types.
const (
// GoLevelDBBackend represents goleveldb (github.com/syndtr/goleveldb - most
// popular implementation)
// - pure go
// - stable
GoLevelDBBackend BackendType = "goleveldb"
// MemDBBackend represents in-memory key value store, which is mostly used
// for testing.
MemDBBackend BackendType = "memdb"
// RocksDBBackend represents rocksdb (uses github.com/linxGnu/grocksdb)
// - requires gcc
// - use rocksdb build tag (go build -tags rocksdb)
RocksDBBackend BackendType = "rocksdb"
// PebbleDBDBBackend represents pebble (uses github.com/cockroachdb/pebble)
// - pure go
// - use pebble build tag (go build -tags pebbledb)
PebbleDBBackend BackendType = "pebbledb"
)
type (
dbCreator func(name string, dir string, opts Options) (DB, error)
Options interface {
Get(string) interface{}
}
)
var backends = map[BackendType]dbCreator{}
func registerDBCreator(backend BackendType, creator dbCreator, force bool) {
_, ok := backends[backend]
if !force && ok {
return
}
backends[backend] = creator
}
// NewDB creates a new database of type backend with the given name.
func NewDB(name string, backend BackendType, dir string) (DB, error) {
return NewDBwithOptions(name, backend, dir, nil)
}
func NewDBwithOptions(name string, backend BackendType, dir string, opts Options) (DB, error) {
dbCreator, ok := backends[backend]
if !ok {
keys := make([]string, 0, len(backends))
for k := range backends {
keys = append(keys, string(k))
}
return nil, fmt.Errorf("unknown db_backend %s, expected one of %v",
backend, strings.Join(keys, ","))
}
db, err := dbCreator(name, dir, opts)
if err != nil {
return nil, fmt.Errorf("failed to initialize database: %w", err)
}
return db, nil
}