plugeth/ethdb/database.go

94 lines
1.7 KiB
Go
Raw Normal View History

2014-02-14 22:56:09 +00:00
package ethdb
import (
2014-08-23 09:00:33 +00:00
"path"
2015-02-12 16:06:15 +00:00
"fmt"
2014-08-23 09:00:33 +00:00
"github.com/ethereum/go-ethereum/ethutil"
2015-02-12 16:06:15 +00:00
"github.com/ethereum/go-ethereum/compression/rle"
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
}
2014-02-25 10:21:03 +00:00
func NewLDBDatabase(name string) (*LDBDatabase, error) {
dbPath := path.Join(ethutil.Config.ExecPath, name)
2014-02-14 22:56:09 +00:00
// Open the db
db, err := leveldb.OpenFile(dbPath, nil)
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))
node := ethutil.NewValueFromBytes(value)
fmt.Printf("%v\n", node)
}
}