Skip to content

Commit

Permalink
feat: set command support NX
Browse files Browse the repository at this point in the history
  • Loading branch information
satoshi-099 committed Aug 30, 2024
1 parent 57847e8 commit b7511c6
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
18 changes: 15 additions & 3 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
var (
WITH_SCORES = "WITHSCORES"
KEEP_TTL = "KEEPTTL"
NX = "NX"
EX = "EX"
PX = "PX"
)
Expand Down Expand Up @@ -97,8 +98,10 @@ func setCommand(writer *RESPWriter, args []RESP) {
var ttl int64

for len(extra) > 0 {
arg := extra[0].ToStringUnsafe()

// EX
if equalFold(extra[0].ToStringUnsafe(), EX) && len(extra) >= 2 {
if equalFold(arg, EX) && len(extra) >= 2 {
n, err := extra[1].ToInt()
if err != nil {
writer.WriteError(errParseInteger)
Expand All @@ -108,7 +111,7 @@ func setCommand(writer *RESPWriter, args []RESP) {
extra = extra[2:]

// PX
} else if equalFold(extra[0].ToStringUnsafe(), PX) && len(extra) >= 2 {
} else if equalFold(arg, PX) && len(extra) >= 2 {
n, err := extra[1].ToInt()
if err != nil {
writer.WriteError(errParseInteger)
Expand All @@ -118,9 +121,18 @@ func setCommand(writer *RESPWriter, args []RESP) {
extra = extra[2:]

// KEEPTTL
} else if equalFold(extra[0].ToStringUnsafe(), KEEP_TTL) {
} else if equalFold(arg, KEEP_TTL) {
extra = extra[1:]
ttl = -1

// NX
} else if equalFold(arg, NX) {
if _, ttl := db.dict.Get(key); ttl != dict.KEY_NOT_EXIST {
writer.WriteNull()
return
}
extra = extra[1:]

} else {
writer.WriteError(errSyntax)
return
Expand Down
9 changes: 9 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ func TestCommand(t *testing.T) {

n, _ := rdb.Del(ctx, "foo", "none").Result()
assert.Equal(n, int64(1))

// setnx
ok, err := rdb.SetNX(ctx, "key-nx", "123", redis.KeepTTL).Result()
assert.Nil(err)
assert.True(ok)

ok, err = rdb.SetNX(ctx, "key-nx", "123", redis.KeepTTL).Result()
assert.Nil(err)
assert.False(ok)
})

t.Run("error-get", func(t *testing.T) {
Expand Down
1 change: 0 additions & 1 deletion rotom.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ READ:
client.recvx += n

if readSize == 0 {
log.Info().Msgf("client %d read query empty, now free", fd)
freeClient(client)
return
}
Expand Down

0 comments on commit b7511c6

Please sign in to comment.