From bca151e2e362d0130a2c8066c65617f4109466e7 Mon Sep 17 00:00:00 2001 From: Christos Kotsis Date: Wed, 15 Sep 2021 15:10:24 +0300 Subject: [PATCH] fix: [issues/26] deleteArrayItem Fix interface conversion error Additional info: https://github.com/ulfox/dby/issues/26 --- db/sql.go | 30 +++++++++++++++++------------- tests/delete_test.go | 14 ++++++++++++++ 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/db/sql.go b/db/sql.go index fc8fca2..72ed7b2 100644 --- a/db/sql.go +++ b/db/sql.go @@ -154,20 +154,24 @@ func (s *SQL) getPath(k []string, o interface{}) (interface{}, error) { return nil, wrapErr(keyDoesNotExist, k[0]) } -func (s *SQL) deleteArrayItem(k string, o interface{}) bool { +func (s *SQL) deleteArrayItem(k string, o interface{}) error { if o == nil { - return false + return wrapErr(notArrayObj) } - for ki, kn := range o.([]interface{}) { - if kn.(map[interface{}]interface{})[k] != nil { - o.([]interface{})[ki] = emptyMap() - return true - } + + i, err := s.getIndex(k) + if err != nil { + return wrapErr(err) } - return false + + o.([]interface{})[i] = o.([]interface{})[len(o.([]interface{}))-1] + o.([]interface{})[len(o.([]interface{}))-1] = "" + o = o.([]interface{})[:len(o.([]interface{}))-1] + + return nil } -func (s *SQL) deleteItem(k string, o interface{}) bool { +func (s *SQL) deleteItem(k string, o interface{}) error { _, ok := o.(map[interface{}]interface{}) if !ok { return s.deleteArrayItem(k, o) @@ -176,10 +180,10 @@ func (s *SQL) deleteItem(k string, o interface{}) bool { for kn := range o.(map[interface{}]interface{}) { if kn.(string) == k { delete(o.(map[interface{}]interface{}), kn) - return true + return nil } } - return false + return wrapErr(keyDoesNotExist, k) } func (s *SQL) delPath(k string, o interface{}) error { @@ -193,7 +197,7 @@ func (s *SQL) delPath(k string, o interface{}) error { } if len(keys) == 1 { - if !s.deleteItem(keys[0], o) { + if err := s.deleteItem(keys[0], o); err != nil { return wrapErr(keyDoesNotExist, k) } return nil @@ -206,7 +210,7 @@ func (s *SQL) delPath(k string, o interface{}) error { } s.Cache.DropKeys() - if !s.deleteItem(keys[len(keys)-1], obj) { + if err := s.deleteItem(keys[len(keys)-1], obj); err != nil { return wrapErr(keyDoesNotExist, k) } diff --git a/tests/delete_test.go b/tests/delete_test.go index e36028b..05e3e9f 100644 --- a/tests/delete_test.go +++ b/tests/delete_test.go @@ -39,6 +39,20 @@ func TestDelete(t *testing.T) { err = storage.Delete("test.path.key-12") assert.NotEqual(t, err, nil) + err = storage.Upsert( + "key-33", + map[string][]string{ + "key-5": {"value-5"}, + "key-6": {"value-6"}, + }, + ) + + assert.Equal(t, err, nil) + err = storage.Delete("key-33.key-5") + assert.Equal(t, err, nil) + err = storage.Delete("key-33.key-6.[0]") + assert.Equal(t, err, nil) + err = os.Remove(path) assert.Equal(t, err, nil) }