Skip to content

Commit

Permalink
Merge pull request #27 from ulfox/fix/delete-array-item
Browse files Browse the repository at this point in the history
fix: [issues/26] deleteArrayItem
  • Loading branch information
ulfox authored Sep 15, 2021
2 parents db7c95e + bca151e commit 11eaa40
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 13 deletions.
30 changes: 17 additions & 13 deletions db/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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)
}

Expand Down
14 changes: 14 additions & 0 deletions tests/delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 11eaa40

Please sign in to comment.