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

Make ResultIteration safe for use after mutation (option 2) #87

Merged
merged 3 commits into from
Jan 28, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (txn *Txn) readableIndex(table, index string) *iradix.Txn {
key := tableIndex{table, index}
exist, ok := txn.modified[key]
if ok {
return exist
return exist.Clone()
}
}

Expand Down Expand Up @@ -850,7 +850,7 @@ func (txn *Txn) getIndexIterator(table, index string, args ...interface{}) (*ira
indexTxn := txn.readableIndex(table, indexSchema.Name)
indexRoot := indexTxn.Root()

// Get an interator over the index
// Get an iterator over the index
indexIter := indexRoot.Iterator()
return indexIter, val, nil
}
Expand Down
50 changes: 50 additions & 0 deletions txn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2178,3 +2178,53 @@ func TestTxn_Changes(t *testing.T) {
})
}
}

func TestTxn_GetIterAndDelete(t *testing.T) {
schema := &DBSchema{
Tables: map[string]*TableSchema{
"main": {
Name: "main",
Indexes: map[string]*IndexSchema{
"id": {
Name: "id",
Unique: true,
Indexer: &StringFieldIndex{Field: "ID"},
},
"foo": {
Name: "foo",
Indexer: &StringFieldIndex{Field: "Foo"},
},
},
},
},
}
db, err := NewMemDB(schema)
assertNilError(t, err)

key := "aaaa"
txn := db.Txn(true)
assertNilError(t, txn.Insert("main", &TestObject{ID: "1", Foo: key}))
assertNilError(t, txn.Insert("main", &TestObject{ID: "123", Foo: key}))
assertNilError(t, txn.Insert("main", &TestObject{ID: "2", Foo: key}))
txn.Commit()

txn = db.Txn(true)
// Delete something
assertNilError(t, txn.Delete("main", &TestObject{ID: "123", Foo: key}))

iter, err := txn.Get("main", "foo", key)
assertNilError(t, err)

for obj := iter.Next(); obj != nil; obj = iter.Next() {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without this code change, this test would panic here on iter.Next() the second iteration.

assertNilError(t, txn.Delete("main", obj))
}

txn.Commit()
}

func assertNilError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("expected nil error, got %v", err)
}
}