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.

113 lines
2.2 KiB

  1. package db
  2. // modified from https://github.com/iden3/go-iden3/blob/master/db/leveldb.go
  3. import (
  4. "encoding/json"
  5. "github.com/syndtr/goleveldb/leveldb"
  6. // "github.com/syndtr/goleveldb/leveldb/errors"
  7. "github.com/syndtr/goleveldb/leveldb/opt"
  8. "github.com/syndtr/goleveldb/leveldb/util"
  9. "github.com/syndtr/goleveldb/leveldb/iterator"
  10. )
  11. type LevelDbStorage struct {
  12. ldb *leveldb.DB
  13. prefix []byte
  14. }
  15. func NewLevelDbStorage(path string, errorIfMissing bool) (*LevelDbStorage, error) {
  16. o := &opt.Options{
  17. ErrorIfMissing: errorIfMissing,
  18. }
  19. ldb, err := leveldb.OpenFile(path, o)
  20. if err != nil {
  21. return nil, err
  22. }
  23. return &LevelDbStorage{ldb, []byte{}}, nil
  24. }
  25. type storageInfo struct {
  26. KeyCount int
  27. }
  28. func (l *LevelDbStorage) Count() int {
  29. keycount := 0
  30. db := l.ldb
  31. iter := db.NewIterator(util.BytesPrefix(l.prefix), nil)
  32. for iter.Next() {
  33. keycount++
  34. }
  35. iter.Release()
  36. if err := iter.Error(); err != nil {
  37. panic(err)
  38. }
  39. return keycount
  40. }
  41. func (l *LevelDbStorage) Info() string {
  42. keycount := 0
  43. db := l.ldb
  44. iter := db.NewIterator(util.BytesPrefix(l.prefix), nil)
  45. for iter.Next() {
  46. keycount++
  47. }
  48. iter.Release()
  49. if err := iter.Error(); err != nil {
  50. return err.Error()
  51. }
  52. json, _ := json.MarshalIndent(
  53. storageInfo{keycount},
  54. "", " ",
  55. )
  56. return string(json)
  57. }
  58. func (l *LevelDbStorage) WithPrefix(prefix []byte) *LevelDbStorage {
  59. return &LevelDbStorage{l.ldb, append(l.prefix, prefix...)}
  60. }
  61. func (l *LevelDbStorage) Get(key []byte) ([]byte, error) {
  62. v, err := l.ldb.Get(append(l.prefix, key[:]...), nil)
  63. if err != nil {
  64. return nil, err
  65. }
  66. return v, err
  67. }
  68. func (l *LevelDbStorage) Put(key []byte, value []byte) error {
  69. err := l.ldb.Put(append(l.prefix, key[:]...), value, nil)
  70. if err != nil {
  71. return err
  72. }
  73. return nil
  74. }
  75. func (l *LevelDbStorage) Delete(key []byte) error {
  76. err := l.ldb.Delete(append(l.prefix, key[:]...), nil)
  77. if err != nil {
  78. return err
  79. }
  80. return nil
  81. }
  82. func (l *LevelDbStorage) Close() {
  83. if err := l.ldb.Close(); err != nil {
  84. panic(err)
  85. }
  86. }
  87. func (l *LevelDbStorage) Iter() iterator.Iterator {
  88. db := l.ldb
  89. i := db.NewIterator(util.BytesPrefix(l.prefix), nil)
  90. return i
  91. }
  92. func (l *LevelDbStorage) LevelDB() *leveldb.DB {
  93. return l.ldb
  94. }