asmt/db/db.go
db/db.goRaw
1/**
2 * @file
3 * @copyright defined in aergo/LICENSE.txt
4 */
5
6/*
7Package db is an wrapper of key-value database implementations. Currently, this supports badgerdb (https://github.com/dgraph-io/badger).
8
9Basic Usage
10
11You can create database using a newdb func like this
12 database := NewDB(BadgerImpl, "./test")
13
14A first argument is a backend db type to use, and a second is a root directory to store db files.
15After creating db, you can write, read or delete single key-value using funcs in DB interface.
16 // write data
17 database.Set([]byte("key"), []byte("val"))
18
19 // read data
20 read := Get([]byte("key"))
21
22 // delete data
23 database.Delete([]byte("key"))
24
25Transaction
26
27A Transaction is a bulk set of operations to ensure atomic success or fail.
28 // create a new transaction
29 tx := database.NewTX(true)
30
31 // reserve writing
32 tx.Set([]byte("keyA"), []byte("valA"))
33 tx.Set([]byte("keyB"), []byte("valB"))
34
35 // Get will return a value reserved to write in this transaction
36 mustBeValA := tx.Get([]byte("keyA"))
37
38 // Perform writing
39 tx.Commit()
40If you want to cancel and discard operations in tx, then you must call Discard() func to prevent a memory leack
41 // If you create a tx, but do not commit, than you have to call this
42 tx.Discard()
43
44Iterator
45
46An iteractor provides a way to get all keys sequentially.
47 // create an iterator that covers all range
48 for iter := database.Iterator(nil, nil); iter.Valid(); iter.Next() {
49 // print each key-value pair
50 fmt.Printf("%s = %s", string(iter.Key()), string(iter.Value()))
51 }
52
53You can find more detail usages at a db_test.go file
54*/
55package db
56
57import (
58 "fmt"
59
60 "github.com/aergoio/aergo-lib/log"
61)
62
63var dbImpls = map[ImplType]dbConstructor{}
64var logger *extendedLog
65
66func registorDBConstructor(dbimpl ImplType, constructor dbConstructor) {
67 dbImpls[dbimpl] = constructor
68}
69
70// NewDB creates new database or load existing database in the directory
71func NewDB(dbimpltype ImplType, dir string) DB {
72 logger = &extendedLog{Logger: log.NewLogger("db")}
73 db, err := dbImpls[dbimpltype](dir)
74
75 if err != nil {
76 panic(fmt.Sprintf("Fail to Create New DB: %v", err))
77 }
78
79 return db
80}
81
82func convNilToBytes(byteArray []byte) []byte {
83 if byteArray == nil {
84 return []byte{}
85 }
86 return byteArray
87}