Skip to content

Commit

Permalink
Uses a separate slice to make DeleteAll safe.
Browse files Browse the repository at this point in the history
  • Loading branch information
James Phillips committed Oct 13, 2015
1 parent f5a621a commit b769a39
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 5 deletions.
14 changes: 11 additions & 3 deletions txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,19 +258,27 @@ func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error)
return 0, fmt.Errorf("cannot delete in read-only transaction")
}

// Get all the objects
// Get all the objects.
iter, err := txn.Get(table, index, args...)
if err != nil {
return 0, err
}

// Delete all
var num int
// Put them into a slice so there are no safety concerns while actually
// performing the deletes.
var objs []interface{}
for {
obj := iter.Next()
if obj == nil {
break
}

objs = append(objs, obj)
}

// Do the deletes.
num := 0
for _, obj := range(objs) {
if err := txn.Delete(table, obj); err != nil {
return num, err
}
Expand Down
62 changes: 60 additions & 2 deletions txn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,13 +391,22 @@ func TestTxn_DeleteAll_Simple(t *testing.T) {
t.Fatalf("err: %v", err)
}

// Do a delete that doesn't hit any objects
num, err := txn.DeleteAll("main", "id", "dogs")
if err != nil {
t.Fatalf("err: %v", err)
}
if num != 0 {
t.Fatalf("bad: %d", num)
}

// Delete a specific ID
num, err := txn.DeleteAll("main", "id", obj1.ID)
num, err = txn.DeleteAll("main", "id", obj1.ID)
if err != nil {
t.Fatalf("err: %v", err)
}
if num != 1 {
t.Fatalf("Bad: %d", num)
t.Fatalf("bad: %d", num)
}

// Ensure we cannot lookup
Expand Down Expand Up @@ -428,6 +437,55 @@ func TestTxn_DeleteAll_Simple(t *testing.T) {
}
}

func TestTxn_DeleteAll_Prefix(t *testing.T) {
db := testDB(t)
txn := db.Txn(true)

obj1 := &TestObject{
ID: "my-object",
Foo: "abc",
}
obj2 := &TestObject{
ID: "my-cool-thing",
Foo: "xyz",
}
obj3 := &TestObject{
ID: "my-other-cool-thing",
Foo: "xyz",
}

err := txn.Insert("main", obj1)
if err != nil {
t.Fatalf("err: %v", err)
}
err = txn.Insert("main", obj2)
if err != nil {
t.Fatalf("err: %v", err)
}
err = txn.Insert("main", obj3)
if err != nil {
t.Fatalf("err: %v", err)
}

// Delete a prefix
num, err := txn.DeleteAll("main", "id_prefix", "my-")
if err != nil {
t.Fatalf("err: %v", err)
}
if num != 3 {
t.Fatalf("bad: %d", num)
}

// Ensure we cannot lookup
raw, err := txn.First("main", "id_prefix", "my-")
if err != nil {
t.Fatalf("err: %v", err)
}
if raw != nil {
t.Fatalf("bad: %#v", raw)
}
}

func TestTxn_InsertGet_Prefix(t *testing.T) {
db := testDB(t)
txn := db.Txn(true)
Expand Down

0 comments on commit b769a39

Please sign in to comment.