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.

97 lines
1.9 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) Info() string {
  29. keycount := 0
  30. iter := l.ldb.NewIterator(nil, nil)
  31. for iter.Next() {
  32. keycount++
  33. }
  34. iter.Release()
  35. if err := iter.Error(); err != nil {
  36. return err.Error()
  37. }
  38. json, _ := json.MarshalIndent(
  39. storageInfo{keycount},
  40. "", " ",
  41. )
  42. return string(json)
  43. }
  44. func (l *LevelDbStorage) WithPrefix(prefix []byte) *LevelDbStorage {
  45. return &LevelDbStorage{l.ldb, append(l.prefix, prefix...)}
  46. }
  47. func (l *LevelDbStorage) Get(key []byte) ([]byte, error) {
  48. v, err := l.ldb.Get(append(l.prefix, key[:]...), nil)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return v, err
  53. }
  54. func (l *LevelDbStorage) Put(key []byte, value []byte) error {
  55. err := l.ldb.Put(append(l.prefix, key[:]...), value, nil)
  56. if err != nil {
  57. return err
  58. }
  59. return nil
  60. }
  61. func (l *LevelDbStorage) Delete(key []byte) error {
  62. err := l.ldb.Delete(append(l.prefix, key[:]...), nil)
  63. if err != nil {
  64. return err
  65. }
  66. return nil
  67. }
  68. func (l *LevelDbStorage) Close() {
  69. if err := l.ldb.Close(); err != nil {
  70. panic(err)
  71. }
  72. }
  73. func (l *LevelDbStorage) Iter() iterator.Iterator {
  74. db := l.ldb
  75. i := db.NewIterator(util.BytesPrefix(l.prefix), nil)
  76. return i
  77. }
  78. func (l *LevelDbStorage) LevelDB() *leveldb.DB {
  79. return l.ldb
  80. }