redis/script.go

53 lines
1.1 KiB
Go
Raw Normal View History

2013-05-22 18:56:59 +04:00
package redis
import (
"crypto/sha1"
"encoding/hex"
"io"
"strings"
)
2014-05-11 11:42:40 +04:00
type scripter interface {
Eval(script string, keys []string, args ...interface{}) *Cmd
EvalSha(sha1 string, keys []string, args ...interface{}) *Cmd
2014-05-11 11:42:40 +04:00
ScriptExists(scripts ...string) *BoolSliceCmd
ScriptLoad(script string) *StringCmd
}
2013-05-22 18:56:59 +04:00
type Script struct {
src, hash string
}
func NewScript(src string) *Script {
h := sha1.New()
io.WriteString(h, src)
return &Script{
src: src,
hash: hex.EncodeToString(h.Sum(nil)),
}
}
2014-05-11 11:42:40 +04:00
func (s *Script) Load(c scripter) *StringCmd {
2013-05-22 18:56:59 +04:00
return c.ScriptLoad(s.src)
}
2014-05-11 11:42:40 +04:00
func (s *Script) Exists(c scripter) *BoolSliceCmd {
2013-05-22 18:56:59 +04:00
return c.ScriptExists(s.src)
}
func (s *Script) Eval(c scripter, keys []string, args ...interface{}) *Cmd {
return c.Eval(s.src, keys, args...)
2013-05-22 18:56:59 +04:00
}
func (s *Script) EvalSha(c scripter, keys []string, args ...interface{}) *Cmd {
return c.EvalSha(s.hash, keys, args...)
2013-05-22 18:56:59 +04:00
}
func (s *Script) Run(c scripter, keys []string, args ...interface{}) *Cmd {
r := s.EvalSha(c, keys, args...)
2013-05-22 18:56:59 +04:00
if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") {
return s.Eval(c, keys, args...)
2013-05-22 18:56:59 +04:00
}
return r
}