Skip to content

Commit

Permalink
add TestOverwriteFirstKeyOnly, fix cursor bug with single overwritten…
Browse files Browse the repository at this point in the history
… key (#18)
  • Loading branch information
Preetam authored Nov 3, 2016
1 parent bab6b72 commit 44897eb
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 2 deletions.
29 changes: 27 additions & 2 deletions cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,30 @@ func (c *Collection) NewCursor() (*Cursor, error) {
if err != nil {
return nil, err
}
return &Cursor{
cur := &Cursor{
collection: c,
current: head,
first: true,
snapshot: c.LastCommit,
}, nil
}

var rec *record
cur.current.lock.RLock()
for (cur.current.Deleted != 0 && cur.current.Deleted <= cur.snapshot) ||
(cur.current.Offset >= cur.snapshot) {
rec, err = cur.collection.readRecord(cur.current.Next)
if err != nil {
cur.current.lock.RUnlock()
cur.current = nil
return cur, nil
}
cur.current.lock.RUnlock()
cur.current = rec
cur.current.lock.RLock()
}
cur.current.lock.RUnlock()

return cur, nil
}

// Valid returns true if the cursor's Key() and Value()
Expand Down Expand Up @@ -125,6 +143,13 @@ func (c *Cursor) Seek(key string) {
for rec != nil {
rec.lock.RLock()
if rec.Key > key {
if (rec.Deleted > 0 && rec.Deleted <= c.snapshot) || (rec.Offset >= c.snapshot) {
oldRec := rec
rec = c.collection.nextRecord(rec)
oldRec.lock.RUnlock()
c.current = rec
continue
}
rec.lock.RUnlock()
break
}
Expand Down
46 changes: 46 additions & 0 deletions lm2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -549,3 +549,49 @@ func TestOverwriteFirstKey(t *testing.T) {
t.Fatalf("expected cursor key to be 'b', got %v", cur.Key())
}
}

func TestOverwriteFirstKeyOnly(t *testing.T) {
c, err := NewCollection("/tmp/test_overwritefirstkeyonly.lm2", 100)
if err != nil {
t.Fatal(err)
}
defer c.Destroy()

wb := NewWriteBatch()
wb.Set("a", "1")
_, err = c.Update(wb)
if err != nil {
t.Fatal(err)
}

wb = NewWriteBatch()
wb.Set("a", "2")
_, err = c.Update(wb)
if err != nil {
t.Fatal(err)
}

cur, err := c.NewCursor()
if err != nil {
t.Fatal(err)
}

cur.Seek("")
if !cur.Valid() {
t.Fatal("expected cursor to be valid")
}

if !cur.Next() {
t.Fatal("expected Next() to return true")
}

if cur.Key() != "a" {
t.Fatalf("expected cursor key to be 'a', got %v", cur.Key())
}
t.Log(cur.Key(), "=>", cur.Value())

if cur.Next() {
t.Error("expected Next() to return false")
t.Log(cur.Key(), "=>", cur.Value())
}
}

0 comments on commit 44897eb

Please sign in to comment.