datastore.go 1.79 KB
Newer Older
1 2 3
package leveldb

import (
4 5
	"io"

6 7 8
	ds "github.com/jbenet/go-datastore"
	"github.com/jbenet/go-datastore/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb"
	"github.com/jbenet/go-datastore/Godeps/_workspace/src/github.com/syndtr/goleveldb/leveldb/opt"
9 10
)

11 12 13 14 15 16
type Datastore interface {
	ds.ThreadSafeDatastore
	io.Closer
}

type datastore struct {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
17
	DB *leveldb.DB
18 19 20 21
}

type Options opt.Options

22
func NewDatastore(path string, opts *Options) (Datastore, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23 24 25 26
	var nopts opt.Options
	if opts != nil {
		nopts = opt.Options(*opts)
	}
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
27 28 29 30
	db, err := leveldb.OpenFile(path, &nopts)
	if err != nil {
		return nil, err
	}
31

32
	return &datastore{
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
33 34
		DB: db,
	}, nil
35 36 37 38 39 40
}

// Returns ErrInvalidType if value is not of type []byte.
//
// Note: using sync = false.
// see http://godoc.org/github.com/syndtr/goleveldb/leveldb/opt#WriteOptions
41
func (d *datastore) Put(key ds.Key, value interface{}) (err error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42 43
	val, ok := value.([]byte)
	if !ok {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
44 45 46
		return ds.ErrInvalidType
	}
	return d.DB.Put(key.Bytes(), val, nil)
47 48
}

49
func (d *datastore) Get(key ds.Key) (value interface{}, err error) {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
50 51 52 53 54 55 56 57
	val, err := d.DB.Get(key.Bytes(), nil)
	if err != nil {
		if err == leveldb.ErrNotFound {
			return nil, ds.ErrNotFound
		}
		return nil, err
	}
	return val, nil
58 59
}

60
func (d *datastore) Has(key ds.Key) (exists bool, err error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
	return d.DB.Has(key.Bytes(), nil)
62 63
}

64
func (d *datastore) Delete(key ds.Key) (err error) {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
65 66 67 68 69
	err = d.DB.Delete(key.Bytes(), nil)
	if err == leveldb.ErrNotFound {
		return ds.ErrNotFound
	}
	return err
70 71
}

72
func (d *datastore) KeyList() ([]ds.Key, error) {
Jeromy's avatar
Jeromy committed
73 74
	i := d.DB.NewIterator(nil, nil)
	var keys []ds.Key
Ethan Buchman's avatar
Ethan Buchman committed
75
	for i.Next() {
Jeromy's avatar
Jeromy committed
76 77
		keys = append(keys, ds.NewKey(string(i.Key())))
	}
78
	return keys, nil
Jeromy's avatar
Jeromy committed
79 80
}

81
// LevelDB needs to be closed.
82
func (d *datastore) Close() (err error) {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
83
	return d.DB.Close()
84
}
85

86
func (d *datastore) IsThreadSafe() {}