erigon-pulse/ethdb/database.go

89 lines
1.6 KiB
Go
Raw Normal View History

2014-02-14 22:56:09 +00:00
package ethdb
import (
2015-02-12 16:06:15 +00:00
"fmt"
2014-08-23 09:00:33 +00:00
2015-02-12 16:06:15 +00:00
"github.com/ethereum/go-ethereum/compression/rle"
2015-03-16 10:27:38 +00:00
"github.com/ethereum/go-ethereum/common"
2014-02-14 22:56:09 +00:00
"github.com/syndtr/goleveldb/leveldb"
2014-11-02 23:31:15 +00:00
"github.com/syndtr/goleveldb/leveldb/iterator"
2014-02-14 22:56:09 +00:00
)
type LDBDatabase struct {
2014-11-02 23:31:15 +00:00
db *leveldb.DB
comp bool
2014-02-14 22:56:09 +00:00
}
func NewLDBDatabase(file string) (*LDBDatabase, error) {
2014-02-14 22:56:09 +00:00
// Open the db
db, err := leveldb.OpenFile(file, nil)
2014-02-14 22:56:09 +00:00
if err != nil {
return nil, err
}
2014-11-02 23:31:15 +00:00
database := &LDBDatabase{db: db, comp: true}
2014-02-14 22:56:09 +00:00
return database, nil
}
2014-11-02 23:31:15 +00:00
func (self *LDBDatabase) Put(key []byte, value []byte) {
if self.comp {
value = rle.Compress(value)
}
err := self.db.Put(key, value, nil)
2014-02-14 22:56:09 +00:00
if err != nil {
fmt.Println("Error put", err)
}
}
2014-11-02 23:31:15 +00:00
func (self *LDBDatabase) Get(key []byte) ([]byte, error) {
dat, err := self.db.Get(key, nil)
if err != nil {
return nil, err
}
if self.comp {
return rle.Decompress(dat)
}
2014-02-14 22:56:09 +00:00
2014-11-02 23:31:15 +00:00
return dat, nil
2014-02-24 11:12:01 +00:00
}
2014-11-02 23:31:15 +00:00
func (self *LDBDatabase) Delete(key []byte) error {
return self.db.Delete(key, nil)
2014-02-25 10:21:03 +00:00
}
2014-11-02 23:31:15 +00:00
func (self *LDBDatabase) LastKnownTD() []byte {
data, _ := self.Get([]byte("LTD"))
2014-02-14 22:56:09 +00:00
if len(data) == 0 {
data = []byte{0x0}
}
return data
}
2014-11-02 23:31:15 +00:00
func (self *LDBDatabase) NewIterator() iterator.Iterator {
return self.db.NewIterator(nil, nil)
}
2014-12-23 14:18:48 +00:00
func (self *LDBDatabase) Write(batch *leveldb.Batch) error {
return self.db.Write(batch, nil)
}
2014-11-02 23:31:15 +00:00
func (self *LDBDatabase) Close() {
2014-02-14 22:56:09 +00:00
// Close the leveldb database
2014-11-02 23:31:15 +00:00
self.db.Close()
2014-02-14 22:56:09 +00:00
}
2014-11-02 23:31:15 +00:00
func (self *LDBDatabase) Print() {
iter := self.db.NewIterator(nil, nil)
2014-02-14 22:56:09 +00:00
for iter.Next() {
key := iter.Key()
value := iter.Value()
fmt.Printf("%x(%d): ", key, len(key))
2015-03-16 10:27:38 +00:00
node := common.NewValueFromBytes(value)
2014-02-14 22:56:09 +00:00
fmt.Printf("%v\n", node)
}
}