2014-08-03 15:59:56 +02:00
|
|
|
// Copyright 2014 by Sascha L. Teichmann
|
|
|
|
// Use of this source code is governed by the MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
2014-08-03 11:25:25 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
leveldb "github.com/jmhodges/levigo"
|
|
|
|
)
|
|
|
|
|
|
|
|
type LevelDBBackend struct {
|
|
|
|
cache *leveldb.Cache
|
|
|
|
db *leveldb.DB
|
|
|
|
tx *leveldb.WriteBatch
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewLeveDBBackend(path string, cacheSize int) (ldb *LevelDBBackend, err error) {
|
|
|
|
cache := leveldb.NewLRUCache(cacheSize * 1024 * 1024)
|
|
|
|
opts := leveldb.NewOptions()
|
|
|
|
opts.SetCache(cache)
|
|
|
|
opts.SetCreateIfMissing(true)
|
|
|
|
var db *leveldb.DB
|
|
|
|
if db, err = leveldb.Open(path, opts); err != nil {
|
|
|
|
cache.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ldb = &LevelDBBackend{
|
|
|
|
cache: cache,
|
|
|
|
db: db}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ldb *LevelDBBackend) Shutdown() error {
|
2014-08-03 14:52:24 +02:00
|
|
|
tx := ldb.tx
|
|
|
|
if tx != nil {
|
|
|
|
ldb.tx = nil
|
|
|
|
tx.Close()
|
|
|
|
}
|
2014-08-03 11:25:25 +02:00
|
|
|
ldb.db.Close()
|
|
|
|
ldb.cache.Close()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ldb *LevelDBBackend) Fetch(hash, key []byte) ([]byte, error) {
|
|
|
|
ro := leveldb.NewReadOptions()
|
|
|
|
defer ro.Close()
|
|
|
|
return ldb.db.Get(ro, key)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ldb *LevelDBBackend) InTransaction() bool {
|
|
|
|
return ldb.tx != nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ldb *LevelDBBackend) keyExists(key []byte) (exists bool, err error) {
|
|
|
|
ro := leveldb.NewReadOptions()
|
|
|
|
defer ro.Close()
|
|
|
|
var data []byte
|
|
|
|
if data, err = ldb.db.Get(ro, key); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
exists = data != nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ldb *LevelDBBackend) Store(hash, key, value []byte) (exists bool, err error) {
|
|
|
|
|
|
|
|
if exists, err = ldb.keyExists(key); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if ldb.tx != nil {
|
|
|
|
ldb.tx.Put(key, value)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
wo := leveldb.NewWriteOptions()
|
2014-08-04 15:28:01 +02:00
|
|
|
err = ldb.db.Put(wo, key, value)
|
|
|
|
wo.Close()
|
2014-08-03 11:25:25 +02:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ldb *LevelDBBackend) BeginTransaction() error {
|
|
|
|
ldb.tx = leveldb.NewWriteBatch()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-08-04 15:28:01 +02:00
|
|
|
func (ldb *LevelDBBackend) CommitTransaction() (err error) {
|
2014-08-03 11:25:25 +02:00
|
|
|
tx := ldb.tx
|
|
|
|
ldb.tx = nil
|
|
|
|
wo := leveldb.NewWriteOptions()
|
2014-08-04 15:28:01 +02:00
|
|
|
err = ldb.db.Write(wo, tx)
|
|
|
|
wo.Close()
|
|
|
|
return
|
2014-08-03 11:25:25 +02:00
|
|
|
}
|