Skip to content

Commit

Permalink
Merge pull request boltdb#23 from heyitsanthony/del-nonexisting
Browse files Browse the repository at this point in the history
Fix deletion of non-existing keys
  • Loading branch information
Anthony Romano authored Aug 11, 2017
2 parents a6c45c1 + 6336a42 commit 9fc2cf1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
7 changes: 6 additions & 1 deletion bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,12 @@ func (b *Bucket) Delete(key []byte) error {

// Move cursor to correct position.
c := b.Cursor()
_, _, flags := c.seek(key)
k, _, flags := c.seek(key)

// Return nil if the key doesn't exist.
if !bytes.Equal(key, k) {
return nil
}

// Return an error if there is already existing bucket value.
if (flags & bucketLeafFlag) != 0 {
Expand Down
33 changes: 33 additions & 0 deletions bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,39 @@ func TestBucket_Delete_FreelistOverflow(t *testing.T) {
}
}

// Ensure that deleting of non-existing key is a no-op.
func TestBucket_Delete_NonExisting(t *testing.T) {
db := MustOpenDB()
defer db.MustClose()

if err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucket([]byte("widgets"))
if err != nil {
t.Fatal(err)
}

if _, err = b.CreateBucket([]byte("nested")); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}

if err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("widgets"))
if err := b.Delete([]byte("foo")); err != nil {
t.Fatal(err)
}
if b.Bucket([]byte("nested")) == nil {
t.Fatal("nested bucket has been deleted")
}
return nil
}); err != nil {
t.Fatal(err)
}
}

// Ensure that accessing and updating nested buckets is ok across transactions.
func TestBucket_Nested(t *testing.T) {
db := MustOpenDB()
Expand Down

0 comments on commit 9fc2cf1

Please sign in to comment.