Skip to content

Commit

Permalink
feat: method--HDel(#136 ID 5)
Browse files Browse the repository at this point in the history
  • Loading branch information
qishenonly committed Jul 5, 2023
1 parent b48e9a9 commit bf8c1c4
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
59 changes: 59 additions & 0 deletions structure/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,62 @@ func (hs *HashStructure) HGet(key, field []byte) ([]byte, error) {

return value, nil
}

// HDel deletes one or more hash fields.
func (hs *HashStructure) HDel(key []byte, fields ...[]byte) (bool, error) {
// Check the parameters
if len(key) == 0 || len(fields) == 0 {
return false, _const.ErrKeyIsEmpty
}

// Find the hash metadata by the given key
hashMeta, err := hs.findHashMeta(key, Hash)
if err != nil {
return false, err
}

// If the counter is 0, return 0
if hashMeta.counter == 0 {
return false, nil
}

// Create a new HashField
hf := &HashField{
key: key,
version: hashMeta.version,
}

var count int64

// new a write batch
batch := hs.db.NewWriteBatch(config.DefaultWriteBatchOptions)

// Delete the fields one by one
for _, field := range fields {
// If the field is not found, continue
hf.field = field
hfBuf := hf.encodeHashField()
_, err = hs.db.Get(hfBuf)
if err != nil && err == _const.ErrKeyNotFound {
continue
}

// Delete the field
_ = batch.Delete(hfBuf)

// Decrease the counter
hashMeta.counter--
count++
}

// Put the hash metadata to the database
_ = batch.Put(key, hashMeta.encodeHashMeta())

// Commit the write batch
err = batch.Commit()
if err != nil {
return false, err
}

return true, nil
}
29 changes: 29 additions & 0 deletions structure/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,32 @@ func TestHashStructure_HGet(t *testing.T) {
assert.Equal(t, err, _const.ErrKeyNotFound)

}

func TestHashStructure_HDel(t *testing.T) {
hash := initHashDB()

ok, err := hash.HDel(randkv.GetTestKey(1), []byte("field1"))
assert.Nil(t, err)
assert.False(t, ok)

ok1, err := hash.HSet(randkv.GetTestKey(1), []byte("field1"), randkv.RandomValue(10))
assert.Nil(t, err)
assert.True(t, ok1)

ok2, err := hash.HDel(randkv.GetTestKey(1), []byte("field1"))
assert.Nil(t, err)
assert.True(t, ok2)

ok3, err := hash.HSet(randkv.GetTestKey(1), []byte("field1"), randkv.RandomValue(10))
assert.Nil(t, err)
assert.True(t, ok3)

ok4, err := hash.HSet(randkv.GetTestKey(1), []byte("field2"), randkv.RandomValue(10))
assert.Nil(t, err)
assert.True(t, ok4)

ok5, err := hash.HDel(randkv.GetTestKey(1), []byte("field1"), []byte("field2"))
assert.Nil(t, err)
assert.True(t, ok5)

}

0 comments on commit bf8c1c4

Please sign in to comment.