You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.2 KiB

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