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.

116 lines
2.2 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package db
  2. import (
  3. "fmt"
  4. "path"
  5. "github.com/syndtr/goleveldb/leveldb"
  6. "github.com/syndtr/goleveldb/leveldb/errors"
  7. "github.com/syndtr/goleveldb/leveldb/opt"
  8. . "github.com/tendermint/go-common"
  9. )
  10. func init() {
  11. registerDBCreator(GoLevelDBBackendStr, func(name string, dir string) (DB, error) {
  12. return NewGoLevelDB(name, dir)
  13. }, false)
  14. }
  15. type GoLevelDB struct {
  16. db *leveldb.DB
  17. }
  18. func NewGoLevelDB(name string, dir string) (*GoLevelDB, error) {
  19. dbPath := path.Join(dir, name+".db")
  20. db, err := leveldb.OpenFile(dbPath, nil)
  21. if err != nil {
  22. return nil, err
  23. }
  24. database := &GoLevelDB{db: db}
  25. return database, nil
  26. }
  27. func (db *GoLevelDB) Get(key []byte) []byte {
  28. res, err := db.db.Get(key, nil)
  29. if err != nil {
  30. if err == errors.ErrNotFound {
  31. return nil
  32. } else {
  33. PanicCrisis(err)
  34. }
  35. }
  36. return res
  37. }
  38. func (db *GoLevelDB) Set(key []byte, value []byte) {
  39. err := db.db.Put(key, value, nil)
  40. if err != nil {
  41. PanicCrisis(err)
  42. }
  43. }
  44. func (db *GoLevelDB) SetSync(key []byte, value []byte) {
  45. err := db.db.Put(key, value, &opt.WriteOptions{Sync: true})
  46. if err != nil {
  47. PanicCrisis(err)
  48. }
  49. }
  50. func (db *GoLevelDB) Delete(key []byte) {
  51. err := db.db.Delete(key, nil)
  52. if err != nil {
  53. PanicCrisis(err)
  54. }
  55. }
  56. func (db *GoLevelDB) DeleteSync(key []byte) {
  57. err := db.db.Delete(key, &opt.WriteOptions{Sync: true})
  58. if err != nil {
  59. PanicCrisis(err)
  60. }
  61. }
  62. func (db *GoLevelDB) DB() *leveldb.DB {
  63. return db.db
  64. }
  65. func (db *GoLevelDB) Close() {
  66. db.db.Close()
  67. }
  68. func (db *GoLevelDB) Print() {
  69. iter := db.db.NewIterator(nil, nil)
  70. for iter.Next() {
  71. key := iter.Key()
  72. value := iter.Value()
  73. fmt.Printf("[%X]:\t[%X]\n", key, value)
  74. }
  75. }
  76. func (db *GoLevelDB) NewBatch() Batch {
  77. batch := new(leveldb.Batch)
  78. return &goLevelDBBatch{db, batch}
  79. }
  80. //--------------------------------------------------------------------------------
  81. type goLevelDBBatch struct {
  82. db *GoLevelDB
  83. batch *leveldb.Batch
  84. }
  85. func (mBatch *goLevelDBBatch) Set(key, value []byte) {
  86. mBatch.batch.Put(key, value)
  87. }
  88. func (mBatch *goLevelDBBatch) Delete(key []byte) {
  89. mBatch.batch.Delete(key)
  90. }
  91. func (mBatch *goLevelDBBatch) Write() {
  92. err := mBatch.db.db.Write(mBatch.batch, nil)
  93. if err != nil {
  94. PanicCrisis(err)
  95. }
  96. }