Skip to content

Commit

Permalink
feat: new method--HUpdate(#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
qishenonly committed Jul 5, 2023
1 parent 569825e commit 6b820fc
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
49 changes: 49 additions & 0 deletions structure/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,3 +383,52 @@ func (hs *HashStructure) HLen(key []byte) (int, error) {

return int(hashMeta.counter), nil
}

// HUpdate updates the string value of a hash field.
func (hs *HashStructure) HUpdate(key, field, value []byte) (bool, error) {
// Check the parameters
if len(key) == 0 || len(field) == 0 || len(value) == 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{
field: field,
key: key,
version: hashMeta.version,
}

// Encode the HashField
hfBuf := hf.encodeHashField()

// Get the field from the database
_, err = hs.db.Get(hfBuf)
if err != nil && err == _const.ErrKeyNotFound {
return false, nil
}

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

// Put the field to the database
_ = batch.Put(hfBuf, value)

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

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

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

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

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

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

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

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

ok6, err := hash.HUpdate(randkv.GetTestKey(1), []byte("field4"), randkv.RandomValue(10))
assert.Nil(t, err)
assert.False(t, ok6)

l, err := hash.HLen(randkv.GetTestKey(1))
assert.Nil(t, err)
assert.Equal(t, l, 3)
}

0 comments on commit 6b820fc

Please sign in to comment.