Skip to content

Commit

Permalink
Merge pull request #2 from hashicorp/b-delete-all
Browse files Browse the repository at this point in the history
Uses a separate slice to make DeleteAll safe.
  • Loading branch information
slackpad committed Oct 13, 2015
2 parents f5a621a + b64db35 commit 47057ce
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 4 deletions.
12 changes: 10 additions & 2 deletions txn.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,13 +264,21 @@ func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error)
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 47057ce

Please sign in to comment.