driver.go raw
1 package bdb
2
3 import (
4 "fmt"
5
6 "github.com/p9c/p9/pkg/walletdb"
7 )
8
9 const (
10 dbType = "bdb"
11 )
12
13 // parseArgs parses the arguments from the walletdb Open/Create methods.
14 func parseArgs(funcName string, args ...interface{}) (string, error) {
15 if len(args) != 1 {
16 return "", fmt.Errorf(
17 "invalid arguments to %s.%s -- "+
18 "expected database path", dbType, funcName,
19 )
20 }
21 dbPath, ok := args[0].(string)
22 if !ok {
23 return "", fmt.Errorf(
24 "first argument to %s.%s is invalid -- "+
25 "expected database path string", dbType, funcName,
26 )
27 }
28 return dbPath, nil
29 }
30
31 // openDBDriver is the callback provided during driver registration that opens
32 // an existing database for use.
33 func openDBDriver(args ...interface{}) (d walletdb.DB, e error) {
34 var dbPath string
35 if dbPath, e = parseArgs("Open", args...); E.Chk(e) {
36 return
37 }
38 return openDB(dbPath, false)
39 }
40
41 // createDBDriver is the callback provided during driver registration that
42 // creates, initializes, and opens a database for use.
43 func createDBDriver(args ...interface{}) (d walletdb.DB, e error) {
44 var dbPath string
45 if dbPath, e = parseArgs("Create", args...); E.Chk(e) {
46 return
47 }
48 return openDB(dbPath, true)
49 }
50 func init() {
51 // Register the driver.
52 driver := walletdb.Driver{
53 DbType: dbType,
54 Create: createDBDriver,
55 Open: openDBDriver,
56 }
57 var e error
58 if e = walletdb.RegisterDriver(driver); E.Chk(e) {
59 panic(
60 fmt.Sprintf(
61 "Failed to regiser database driver '%s': %v",
62 dbType, e,
63 ),
64 )
65 }
66 }
67