From f87c47424cb3d116ce72b32bb0c7a85887e089e9 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Mon, 31 Mar 2014 12:24:06 -0700 Subject: [PATCH] consul: Implement KVSDelete --- consul/state_store.go | 22 ++++++++++++++++++++-- consul/state_store_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/consul/state_store.go b/consul/state_store.go index b0496dcb65..7b0808528c 100644 --- a/consul/state_store.go +++ b/consul/state_store.go @@ -754,8 +754,26 @@ func (s *StateStore) KVSList() (uint64, structs.DirEntries, error) { } // KVSDelete is used to delete a KVS entry -func (s *StateStore) KVSDelete() error { - return nil +func (s *StateStore) KVSDelete(index uint64, key string) error { + // Start a new txn + tx, err := s.kvsTable.StartTxn(false, nil) + if err != nil { + return err + } + defer tx.Abort() + + num, err := s.kvsTable.DeleteTxn(tx, "id", key) + if err != nil { + return err + } + + if num > 0 { + if err := s.kvsTable.SetLastIndexTxn(tx, index); err != nil { + return err + } + defer s.watch[s.kvsTable].Notify() + } + return tx.Commit() } // KVSDeleteTree is used to delete all keys with a given prefix diff --git a/consul/state_store_test.go b/consul/state_store_test.go index 87fd0ac02c..c2f64dbc7b 100644 --- a/consul/state_store_test.go +++ b/consul/state_store_test.go @@ -1013,3 +1013,34 @@ func TestKVSSet_Get(t *testing.T) { t.Fatalf("bad: %v", d) } } + +func TestKVSDelete(t *testing.T) { + store, err := testStateStore() + if err != nil { + t.Fatalf("err: %v", err) + } + defer store.Close() + + // Create the entry + d := &structs.DirEntry{Key: "/foo", Flags: 42, Value: []byte("test")} + if err := store.KVSSet(1000, d); err != nil { + t.Fatalf("err: %v", err) + } + + // Delete the entry + if err := store.KVSDelete(1020, "/foo"); err != nil { + t.Fatalf("err: %v", err) + } + + // Should not exist + idx, d, err := store.KVSGet("/foo") + if err != nil { + t.Fatalf("err: %v", err) + } + if idx != 1020 { + t.Fatalf("bad: %v", idx) + } + if d != nil { + t.Fatalf("bad: %v", d) + } +}