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

import (
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
4 5 6
	ds "github.com/jbenet/datastore.go"
	"github.com/syndtr/goleveldb/leveldb"
	"github.com/syndtr/goleveldb/leveldb/opt"
7 8 9 10
)

// Datastore uses a standard Go map for internal storage.
type Datastore struct {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
11
	DB *leveldb.DB
12 13 14 15 16
}

type Options opt.Options

func NewDatastore(path string, opts *Options) (*Datastore, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18 19 20
	var nopts opt.Options
	if opts != nil {
		nopts = opt.Options(*opts)
	}
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
21 22 23 24
	db, err := leveldb.OpenFile(path, &nopts)
	if err != nil {
		return nil, err
	}
25

Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
26 27 28
	return &Datastore{
		DB: db,
	}, nil
29 30 31 32 33 34 35
}

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

func (d *Datastore) Get(key ds.Key) (value interface{}, err error) {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
44 45 46 47 48 49 50 51
	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
52 53 54
}

func (d *Datastore) Has(key ds.Key) (exists bool, err error) {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
55
	return ds.GetBackedHas(d, key)
56 57 58
}

func (d *Datastore) Delete(key ds.Key) (err error) {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
59 60 61 62 63
	err = d.DB.Delete(key.Bytes(), nil)
	if err == leveldb.ErrNotFound {
		return ds.ErrNotFound
	}
	return err
64 65
}

66
func (d *Datastore) KeyList() ([]ds.Key, error) {
Jeromy's avatar
Jeromy committed
67 68 69 70 71
	i := d.DB.NewIterator(nil, nil)
	var keys []ds.Key
	for ; i.Valid(); i.Next() {
		keys = append(keys, ds.NewKey(string(i.Key())))
	}
72
	return keys, nil
Jeromy's avatar
Jeromy committed
73 74
}

75 76
// LevelDB needs to be closed.
func (d *Datastore) Close() (err error) {
Juan Batiz-Benet's avatar
go fmt  
Juan Batiz-Benet committed
77
	return d.DB.Close()
78
}