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.

55 lines
1.2 KiB

  1. package db
  2. import (
  3. "github.com/syndtr/goleveldb/leveldb"
  4. )
  5. // Db is the database with the specified prefix
  6. type Db struct {
  7. ldb *leveldb.DB
  8. prefix []byte
  9. }
  10. // New creates a new Db database
  11. func New(path string) (*Db, error) {
  12. ldb, err := leveldb.OpenFile(path, nil)
  13. if err != nil {
  14. return nil, err
  15. }
  16. return &Db{ldb, []byte{}}, nil
  17. }
  18. // WithPrefix returns a subdatabase with the specified prefix
  19. func (db *Db) WithPrefix(prefix []byte) *Db {
  20. return &Db{db.ldb, append(db.prefix, prefix...)}
  21. }
  22. // Put adds the key value to the database
  23. func (db *Db) Put(key, value []byte) error {
  24. err := db.ldb.Put(append(db.prefix, key[:]...), value, nil)
  25. return err
  26. }
  27. // Get retreives a value from the database for a given key
  28. func (db *Db) Get(key []byte) ([]byte, error) {
  29. v, err := db.ldb.Get(append(db.prefix, key[:]...), nil)
  30. if err != nil {
  31. return nil, err
  32. }
  33. return v, nil
  34. }
  35. // Iterate iterates over the database
  36. func (db *Db) Iterate(f func([]byte, []byte)) error {
  37. snapshot, err := db.ldb.GetSnapshot()
  38. if err != nil {
  39. return err
  40. }
  41. iter := snapshot.NewIterator(nil, nil)
  42. for iter.Next() {
  43. f(iter.Key(), iter.Value())
  44. }
  45. iter.Release()
  46. err = iter.Error()
  47. return err
  48. }