From 0ee44c7064b58ad19de811dec1b12cf252d6c64b Mon Sep 17 00:00:00 2001 From: #Suyghur Date: Sat, 2 Mar 2024 10:15:10 +0800 Subject: [PATCH] feat(redis): added and impl `ZADDNX` command (#3944) --- core/stores/redis/redis.go | 39 +++++++++++++++++++++++++++++++++ core/stores/redis/redis_test.go | 18 +++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/core/stores/redis/redis.go b/core/stores/redis/redis.go index 40fb008c..96881115 100644 --- a/core/stores/redis/redis.go +++ b/core/stores/redis/redis.go @@ -2074,6 +2074,45 @@ func (s *Redis) ZaddFloatCtx(ctx context.Context, key string, score float64, val return } +// Zaddnx is the implementation of redis zadd nx command. +func (s *Redis) Zaddnx(key string, score int64, value string) (val bool, err error) { + return s.ZaddnxCtx(context.Background(), key, score, value) +} + +// ZaddnxCtx is the implementation of redis zadd nx command. +func (s *Redis) ZaddnxCtx(ctx context.Context, key string, score int64, value string) (val bool, err error) { + return s.ZaddnxFloatCtx(ctx, key, float64(score), value) +} + +// ZaddnxFloat is the implementation of redis zaddnx command. +func (s *Redis) ZaddnxFloat(key string, score float64, value string) (bool, error) { + return s.ZaddFloatCtx(context.Background(), key, score, value) +} + +// ZaddnxFloatCtx is the implementation of redis zaddnx command. +func (s *Redis) ZaddnxFloatCtx(ctx context.Context, key string, score float64, value string) ( + val bool, err error) { + err = s.brk.DoWithAcceptable(func() error { + conn, err := getRedis(s) + if err != nil { + return err + } + + v, err := conn.ZAddNX(ctx, key, red.Z{ + Score: score, + Member: value, + }).Result() + if err != nil { + return err + } + + val = v == 1 + return nil + }, acceptable) + + return +} + // Zadds is the implementation of redis zadds command. func (s *Redis) Zadds(key string, ps ...Pair) (int64, error) { return s.ZaddsCtx(context.Background(), key, ps...) diff --git a/core/stores/redis/redis_test.go b/core/stores/redis/redis_test.go index b455523c..1515d1cb 100644 --- a/core/stores/redis/redis_test.go +++ b/core/stores/redis/redis_test.go @@ -1584,6 +1584,24 @@ func TestRedis_SortedSetByFloat64(t *testing.T) { }) } +func TestRedis_Zaddnx(t *testing.T) { + runOnRedis(t, func(client *Redis) { + ok, err := client.Zadd("key", 1, "value1") + assert.Nil(t, err) + assert.True(t, ok) + ok, err = client.Zaddnx("key", 2, "value1") + assert.Nil(t, err) + assert.False(t, ok) + + ok, err = client.ZaddFloat("key", 1.1, "value2") + assert.Nil(t, err) + assert.True(t, ok) + ok, err = client.ZaddnxFloat("key", 1.1, "value3") + assert.Nil(t, err) + assert.True(t, ok) + }) +} + func TestRedis_IncrbyFloat(t *testing.T) { runOnRedis(t, func(client *Redis) { incrVal, err := client.IncrbyFloat("key", 0.002)