Skip to content

Commit

Permalink
fix the cursor automatically moving to next position when delete an i…
Browse files Browse the repository at this point in the history
…tem from a node

Refer to boltdb/bolt#357

Signed-off-by: Benjamin Wang <[email protected]>
  • Loading branch information
ahrtr committed Nov 16, 2023
1 parent a5ed8bc commit de2fb69
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,20 @@ func (c *Cursor) Delete() error {
}
c.node().del(key)

pos := c.curPos()
// If the deleted item is the first item in the node, we should keep
// the cursor's position (decrease by 1). Otherwise, the cursor will
// automatically move to the next item, and when clients call `Next`
// method afterward, it will skip one item in the node.
//
// Note if there isn't any write on current page in current transaction,
// then the cursor only iterates items against the page instead of the
// in-memory node. Since the page is immutable, so we don't need to change
// pos.index in such case.
if pos != nil && pos.index == 0 && pos.node != nil {
pos.index = -1
}

return nil
}

Expand Down Expand Up @@ -377,6 +391,14 @@ func (c *Cursor) keyValue() ([]byte, []byte, uint32) {
return elem.Key(), elem.Value(), elem.Flags()
}

// curPos returns current position of the cursor.
func (c *Cursor) curPos() *elemRef {
if len(c.stack) == 0 {
return nil
}
return &c.stack[len(c.stack)-1]
}

// node returns the node that the cursor is currently positioned on.
func (c *Cursor) node() *node {
common.Assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack")
Expand Down

0 comments on commit de2fb69

Please sign in to comment.