Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix cursor delete iteration #629

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ func (c *Cursor) Delete() error {
}
c.node().del(key)

// Rewind the cursor when an element is deleted.
if c.node().unbalanced {
c.stack[len(c.stack)-1].index--
}

return nil
}

Expand Down
46 changes: 46 additions & 0 deletions cursor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,52 @@ func TestCursor_Delete(t *testing.T) {
}
}

// https://github.com/etcd-io/bbolt/issues/146
func TestCursor_Position_After_Delete(t *testing.T) {
db := btesting.MustCreateDB(t)
seen := map[string]bool{"a": false, "b": false, "c": false}

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

// put k/v entries
for s, _ := range seen {
if err := b.Put([]byte(s), []byte("value")); err != nil {
t.Fatal(err)
}
}

c := tx.Bucket([]byte("widgets")).Cursor()

// iterate k/v entries
for key, _ := c.First(); key != nil; key, _ = c.Next() {
seen[string(key)] = true

// delete a value
if bytes.Equal(key, []byte("a")) {
err := c.Delete()
if err != nil {
return err
}
continue
}
}

return nil
}); err != nil {
t.Fatal(err)
}

// every key should have been iterated over
if !reflect.DeepEqual(seen, map[string]bool{"a": true, "b": true, "c": true}) {
fmt.Println(seen)
t.Fatal("failed to iterate over all keys")
}
}

// Ensure that a Tx cursor can seek to the appropriate keys when there are a
// large number of keys. This test also checks that seek will always move
// forward to the next key.
Expand Down