Skip to content

Commit

Permalink
storage/memory: Fix upsert with pre-existing key will causes duplicat…
Browse files Browse the repository at this point in the history
…e records (#88)

Closes #80

Signed-off-by: minchao <[email protected]>
  • Loading branch information
minchao authored and aeneasr committed Feb 27, 2019
1 parent 698e161 commit 1cb8a36
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
16 changes: 14 additions & 2 deletions storage/manager_memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,21 @@ func (m *MemoryManager) Upsert(_ context.Context, collection, key string, value

// no need to evaluate, just create collection if necessary.
m.collection(collection)

m.Lock()
m.items[collection] = append(m.items[collection], memoryItem{Key: key, Data: b.Bytes()})
m.Unlock()
defer m.Unlock()

var found bool
for k, i := range m.items[collection] {
if i.Key == key {
m.items[collection][k].Data = b.Bytes()
found = true
break
}
}
if !found {
m.items[collection] = append(m.items[collection], memoryItem{Key: key, Data: b.Bytes()})
}

return nil
}
Expand Down
15 changes: 15 additions & 0 deletions storage/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,21 @@ func TestMemoryManager(t *testing.T) {
assert.EqualValues(t, 1234, vs)
})

t.Run("case=upsert", func(t *testing.T) {
var v string
require.NoError(t, m.Upsert(ctx, "test-upsert", "foo", "bar"))
require.NoError(t, m.Get(ctx, "test-upsert", "foo", &v))
assert.Equal(t, "bar", v)

require.NoError(t, m.Upsert(ctx, "test-upsert", "foo", "baz"))
require.NoError(t, m.Get(ctx, "test-upsert", "foo", &v))
assert.Equal(t, "baz", v)

var vs []string
require.NoError(t, m.List(ctx, "test-upsert", &vs, 10, 0))
assert.Equal(t, 1, len(vs))
})

t.Run("case=list", func(t *testing.T) {
for i := 0; i < 10; i++ {
require.NoError(t, m.Upsert(ctx, "test-list", fmt.Sprintf("list-%d", i), i))
Expand Down

0 comments on commit 1cb8a36

Please sign in to comment.