Skip to content

Commit 0069721

Browse files
authored
feat(redis): add Do/DoCtx for generic command execution #5417 (#5442)
1 parent ba9c275 commit 0069721

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

core/stores/redis/redis.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ type (
6565
// RedisNode interface represents a redis node.
6666
RedisNode interface {
6767
red.Cmdable
68+
Do(ctx context.Context, args ...any) *red.Cmd
6869
}
6970

7071
// GeoLocation is used with GeoAdd to add geospatial location.
@@ -421,6 +422,25 @@ func (s *Redis) EvalCtx(ctx context.Context, script string, keys []string,
421422
return conn.Eval(ctx, script, keys, args...).Result()
422423
}
423424

425+
// Do executes a generic redis command with given arguments.
426+
func (s *Redis) Do(args ...any) (any, error) {
427+
return s.DoCtx(context.Background(), args...)
428+
}
429+
430+
// DoCtx executes a generic redis command with given arguments using the provided context.
431+
func (s *Redis) DoCtx(ctx context.Context, args ...any) (any, error) {
432+
if len(args) == 0 {
433+
return nil, errors.New("missing redis command")
434+
}
435+
436+
conn, err := getRedis(s)
437+
if err != nil {
438+
return nil, err
439+
}
440+
441+
return conn.Do(ctx, args...).Result()
442+
}
443+
424444
// EvalSha is the implementation of redis evalsha command.
425445
func (s *Redis) EvalSha(sha string, keys []string, args ...any) (any, error) {
426446
return s.EvalShaCtx(context.Background(), sha, keys, args...)

core/stores/redis/redis_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,36 @@ func TestRedis_Eval(t *testing.T) {
275275
})
276276
}
277277

278+
func TestRedis_Do(t *testing.T) {
279+
runOnRedis(t, func(client *Redis) {
280+
_, err := newRedis(client.Addr, badType()).Do("PING")
281+
assert.NotNil(t, err)
282+
283+
pong, err := client.Do("PING")
284+
assert.Nil(t, err)
285+
assert.Equal(t, "PONG", pong)
286+
287+
ok, err := client.Do("SET", "key1", "value1")
288+
assert.Nil(t, err)
289+
assert.Equal(t, "OK", ok)
290+
291+
val, err := client.Do("GET", "key1")
292+
assert.Nil(t, err)
293+
assert.Equal(t, "value1", val)
294+
295+
_, err = client.Do("GET", "not_exist")
296+
assert.Equal(t, Nil, err)
297+
298+
_, err = client.Do()
299+
assert.NotNil(t, err)
300+
301+
ctx, cancel := context.WithCancel(context.Background())
302+
cancel()
303+
_, err = client.DoCtx(ctx, "PING")
304+
assert.Equal(t, context.Canceled, err)
305+
})
306+
}
307+
278308
func TestRedis_ScriptRun(t *testing.T) {
279309
runOnRedis(t, func(client *Redis) {
280310
sc := NewScript(`redis.call("EXISTS", KEYS[1])`)

0 commit comments

Comments
 (0)