Skip to content

Commit

Permalink
feat: new method--HSetNX(#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
qishenonly committed Jul 6, 2023
1 parent 6975c35 commit 18cbeb4
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
37 changes: 37 additions & 0 deletions structure/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -726,3 +726,40 @@ func (hs *HashStructure) HMove(source, destination, field []byte) (bool, error)

return true, nil
}

// HSetNX sets field in the hash stored at key to value, only if field does not yet exist.
func (hs *HashStructure) HSetNX(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
}

// 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 {
_, err := hs.HSet(key, field, value)
if err != nil {
return false, err
}
return true, nil
} else {
return false, nil
}

}
29 changes: 29 additions & 0 deletions structure/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,32 @@ func TestHashStructure_HMove(t *testing.T) {
assert.Equal(t, v3, []byte("111-10"))

}

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

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

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

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

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

ok5, err := hash.HSetNX(randkv.GetTestKey(1), []byte("field2"), []byte("100"))
assert.Nil(t, err)
assert.False(t, ok5)

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

}

0 comments on commit 18cbeb4

Please sign in to comment.