kvstore.go 2.02 KB
Newer Older
tavit ohanian's avatar
tavit ohanian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
package coreindex

import (
	"fmt"
	"sync"

	ds "gitlab.dms3.io/dms3/go-datastore"
	query "gitlab.dms3.io/dms3/go-datastore/query"
)

type kvstore struct {
	lock sync.RWMutex
	d    ds.Datastore
}

// KVStore Datastore interface
type KVStore interface {
	ds.Datastore
	/*
	   Put(i int64, value []byte) error
	   Get(i int64) (value []byte, err error)
	   Delete(i int64) error
	*/
}

var kvs *kvstore

func init() {
	kvs = &kvstore{
		d: ds.NewMapDatastore(), // tests use go map []byte datastore
	}
}

// InitIndexKVStore call to change datastore to use
func InitIndexKVStore(d ds.Datastore) {
	kvs.d = d
}

// GetIndexKVStore return key-value store
func GetIndexKVStore() KVStore {
	return kvs
}

func (kvs *kvstore) Put(key ds.Key, value []byte) error {
	kvs.lock.Lock()
	defer kvs.lock.Unlock()

	if err := kvs.d.Put(key, value); err != nil {
		return fmt.Errorf("cannot store key value properties: %v", err)
	}
	return nil
}

func (kvs *kvstore) Get(key ds.Key) (value []byte, err error) {
	kvs.lock.Lock()
	defer kvs.lock.Unlock()

	//log.Debugf("Get key %v\n", key)
	value, err = kvs.d.Get(key)
	if err != nil {
		return nil, fmt.Errorf("cannot get key value properties: %v", err)
	}
	return value, nil
}

func (kvs *kvstore) Has(key ds.Key) (exists bool, err error) {
	return kvs.d.Has(key)
}

func (kvs *kvstore) Delete(key ds.Key) error {
	kvs.lock.Lock()
	defer kvs.lock.Unlock()

	//log.Debugf("Delete key %v\n", key)
	if err := kvs.d.Delete(key); err != nil {
		return fmt.Errorf("cannot store key value properties: %v", err)
	}
	return nil
}

func (kvs *kvstore) Query(q query.Query) (query.Results, error) {
	return kvs.d.Query(q)

	//var r []query.Entry
	//return  query.ResultsWithEntries(q, r), nil

	//var c <-chan query.Result = make(chan query.Result, 1)
	//return  query.ResultsWithChan(q, c), nil
}

func (kvs *kvstore) GetSize(key ds.Key) (size int, err error) {
	return ds.GetBackedSize(kvs, key)
}

// Sync implements Datastore.Sync
func (kvs *kvstore) Sync(prefix ds.Key) error {
	return nil
}

func (kvs *kvstore) Close() error {
	return nil
}