redis/script.go

66 lines
1.6 KiB
Go
Raw Normal View History

2013-05-22 18:56:59 +04:00
package redis
import (
2020-03-11 17:26:42 +03:00
"context"
2013-05-22 18:56:59 +04:00
"crypto/sha1"
"encoding/hex"
"io"
"strings"
)
2014-05-11 11:42:40 +04:00
type scripter interface {
2020-03-11 17:26:42 +03:00
Eval(ctx context.Context, script string, keys []string, args ...interface{}) *Cmd
EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *Cmd
ScriptExists(ctx context.Context, hashes ...string) *BoolSliceCmd
ScriptLoad(ctx context.Context, script string) *StringCmd
2014-05-11 11:42:40 +04:00
}
2020-07-16 09:52:07 +03:00
var (
_ scripter = (*Client)(nil)
_ scripter = (*Ring)(nil)
_ scripter = (*ClusterClient)(nil)
)
2013-05-22 18:56:59 +04:00
type Script struct {
src, hash string
}
func NewScript(src string) *Script {
h := sha1.New()
2019-07-25 13:53:00 +03:00
_, _ = io.WriteString(h, src)
2013-05-22 18:56:59 +04:00
return &Script{
src: src,
hash: hex.EncodeToString(h.Sum(nil)),
}
}
2017-05-24 15:24:47 +03:00
func (s *Script) Hash() string {
return s.hash
}
2020-03-11 17:26:42 +03:00
func (s *Script) Load(ctx context.Context, c scripter) *StringCmd {
return c.ScriptLoad(ctx, s.src)
2013-05-22 18:56:59 +04:00
}
2020-03-11 17:26:42 +03:00
func (s *Script) Exists(ctx context.Context, c scripter) *BoolSliceCmd {
return c.ScriptExists(ctx, s.hash)
2013-05-22 18:56:59 +04:00
}
2020-03-11 17:26:42 +03:00
func (s *Script) Eval(ctx context.Context, c scripter, keys []string, args ...interface{}) *Cmd {
return c.Eval(ctx, s.src, keys, args...)
2013-05-22 18:56:59 +04:00
}
2020-03-11 17:26:42 +03:00
func (s *Script) EvalSha(ctx context.Context, c scripter, keys []string, args ...interface{}) *Cmd {
return c.EvalSha(ctx, s.hash, keys, args...)
2013-05-22 18:56:59 +04:00
}
2017-04-08 09:35:56 +03:00
// Run optimistically uses EVALSHA to run the script. If script does not exist
// it is retried using EVAL.
2020-03-11 17:26:42 +03:00
func (s *Script) Run(ctx context.Context, c scripter, keys []string, args ...interface{}) *Cmd {
r := s.EvalSha(ctx, c, keys, args...)
2013-05-22 18:56:59 +04:00
if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") {
2020-03-11 17:26:42 +03:00
return s.Eval(ctx, c, keys, args...)
2013-05-22 18:56:59 +04:00
}
return r
}