Browse Source

db: fix MemDB.Close

Fixes https://github.com/tendermint/tmlibs/issues/55

MemDB previously mistakenly set the actual DB pointer to nil
although that side effect is not visible to the outside world
since p is an identifier within the scope of just that function
call. However, @melekes and I had a discussion in which we
came to the conclusion that Close for an in-memory DB should
instead be a noop and not cause any data loss. See the
discussion on https://github.com/tendermint/tmlibs/pull/56.
pull/1842/head
Emmanuel Odeke 7 years ago
parent
commit
8be8127351
No known key found for this signature in database GPG Key ID: 1CA47A292F89DD40
2 changed files with 25 additions and 3 deletions
  1. +5
    -3
      db/mem_db.go
  2. +20
    -0
      db/mem_db_test.go

+ 5
- 3
db/mem_db.go View File

@ -52,9 +52,11 @@ func (db *MemDB) DeleteSync(key []byte) {
}
func (db *MemDB) Close() {
db.mtx.Lock()
defer db.mtx.Unlock()
db = nil
// Close is a noop since for an in-memory
// database, we don't have a destination
// to flush contents to nor do we want
// any data loss on invoking Close()
// See the discussion in https://github.com/tendermint/tmlibs/pull/56
}
func (db *MemDB) Print() {


+ 20
- 0
db/mem_db_test.go View File

@ -4,6 +4,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMemDbIterator(t *testing.T) {
@ -26,3 +27,22 @@ func TestMemDbIterator(t *testing.T) {
}
assert.Equal(t, i, len(db.db), "iterator didnt cover whole db")
}
func TestMemDBClose(t *testing.T) {
db := NewMemDB()
copyDB := func(orig map[string][]byte) map[string][]byte {
copy := make(map[string][]byte)
for k, v := range orig {
copy[k] = v
}
return copy
}
k, v := []byte("foo"), []byte("bar")
db.Set(k, v)
require.Equal(t, db.Get(k), v, "expecting a successful get")
copyBefore := copyDB(db.db)
db.Close()
require.Equal(t, db.Get(k), v, "Close is a noop, expecting a successful get")
copyAfter := copyDB(db.db)
require.Equal(t, copyBefore, copyAfter, "Close is a noop and shouldn't modify any internal data")
}

Loading…
Cancel
Save