From 41ddfe2410e0922df52b907bb0a1266114e765bd Mon Sep 17 00:00:00 2001 From: Tianle Xu Date: Thu, 1 Oct 2020 13:46:15 +0800 Subject: [PATCH] feat(bucket): implement list method --- bucket.go | 8 ++++++++ drivers/memory/driver.go | 8 ++++++-- drivers/persistent-memory/driver.go | 6 ++++++ drivers/redis/driver.go | 20 ++++++++++++++++++++ 4 files changed, 40 insertions(+), 2 deletions(-) diff --git a/bucket.go b/bucket.go index f18b43c..1fc7d2f 100644 --- a/bucket.go +++ b/bucket.go @@ -3,6 +3,7 @@ package unikv import ( "encoding/gob" "fmt" + "reflect" "strconv" "strings" ) @@ -42,6 +43,13 @@ func (b *Bucket) List() ([]Key, error) { sl[i] = NewKey(v) } return sl, nil + case []reflect.Value: + ksa := ks.([]reflect.Value) + sl := make([]Key, len(ksa)) + for i, v := range ksa { + sl[i] = NewKey(v.String()) + } + return sl, nil } return nil, fmt.Errorf("Unknown driver error") } diff --git a/drivers/memory/driver.go b/drivers/memory/driver.go index ad41643..5be181a 100644 --- a/drivers/memory/driver.go +++ b/drivers/memory/driver.go @@ -1,7 +1,6 @@ package memorydriver import ( - "reflect" "sync" "github.com/apiles/unikv" @@ -35,7 +34,12 @@ func (d *Driver) Unset(key string) error { // List lists the keys func (d *Driver) List() (interface{}, error) { - return reflect.ValueOf(d.data).MapKeys(), nil + var rslt []string + d.data.Range(func(k, _v interface{}) bool { + rslt = append(rslt, k.(string)) + return true + }) + return rslt, nil } // Close closes driver diff --git a/drivers/persistent-memory/driver.go b/drivers/persistent-memory/driver.go index 90a220e..4630737 100644 --- a/drivers/persistent-memory/driver.go +++ b/drivers/persistent-memory/driver.go @@ -3,6 +3,7 @@ package persistentmemorydriver import ( "encoding/gob" "os" + "reflect" "sync" "github.com/apiles/unikv" @@ -65,6 +66,11 @@ func (d *Driver) Put(key string, value string) error { return nil } +// List lists the keys +func (d *Driver) List() (interface{}, error) { + return reflect.ValueOf(d.data).MapKeys(), nil +} + // Unset unsets data func (d *Driver) Unset(key string) error { key = unikv.ConcatPrefix(d.prefix, key) diff --git a/drivers/redis/driver.go b/drivers/redis/driver.go index 22998f2..42cc179 100644 --- a/drivers/redis/driver.go +++ b/drivers/redis/driver.go @@ -72,6 +72,26 @@ func (d *Driver) Unset(key string) error { return err } +// List lists the keys +func (d *Driver) List() (interface{}, error) { + data, err := d.conn.Do("KEYS", "*") + if err != nil { + if err == redis.ErrNil { + return "", unikv.ErrNotFound + } + if !d.reconnected { + d.connect() + d.reconnected = true + return d.List() + } + return "", err + } + if d.reconnected { + d.reconnected = false + } + return data, err +} + // Close closes driver func (d *Driver) Close() error { return d.conn.Close()