arnaucube
arnaucube/arboPublic Self-hosted repository
arbo/db/metadb/metadb.go
db/metadb/metadb.goRaw
 1// Package metadb opens supported database implementations by type.
 2package metadb
 3
 4import (
 5	"fmt"
 6	"os"
 7	"testing"
 8
 9	"github.com/arnaucube/arbo/db"
10	"github.com/arnaucube/arbo/db/goleveldb"
11	"github.com/arnaucube/arbo/db/pebbledb"
12)
13
14// New opens a database of the requested type in dir.
15func New(typ, dir string) (db.Database, error) {
16	var database db.Database
17	var err error
18	opts := db.Options{Path: dir}
19	switch typ {
20	case db.TypePebble:
21		database, err = pebbledb.New(opts)
22		if err != nil {
23			return nil, err
24		}
25	case db.TypeLevelDB:
26		database, err = goleveldb.New(opts)
27		if err != nil {
28			return nil, err
29		}
30	default:
31		return nil, fmt.Errorf("invalid dbType: %q. Available types: %q %q",
32			typ, db.TypePebble, db.TypeLevelDB)
33	}
34	return database, nil
35}
36
37// ForTest selects the test database type from DVOTE_DB_TYPE, defaulting to Pebble.
38func ForTest() (typ string) {
39	if typ := os.Getenv("DVOTE_DB_TYPE"); typ != "" {
40		return typ
41	}
42	return db.TypePebble // default to Pebble
43}
44
45// NewTest opens a temporary database and registers its cleanup.
46func NewTest(tb testing.TB) db.Database {
47	database, err := New(ForTest(), tb.TempDir())
48	if err != nil {
49		tb.Fatal(err)
50	}
51	tb.Cleanup(func() {
52		if err := database.Close(); err != nil {
53			tb.Error(err)
54		}
55	})
56	return database
57}