datastore.go 1.41 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
go fmt  
Juan Batiz-Benet committed
17 18 19 20 21
	nopts := opt.Options(*opts)
	db, err := leveldb.OpenFile(path, &nopts)
	if err != nil {
		return nil, err
	}
22

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

// 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
go fmt  
Juan Batiz-Benet committed
33 34 35 36 37
	val, failed := value.([]byte)
	if failed {
		return ds.ErrInvalidType
	}
	return d.DB.Put(key.Bytes(), val, nil)
38 39 40
}

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

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

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

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