You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.6 KiB

  1. package redis
  2. import (
  3. "context"
  4. "crypto/sha1"
  5. "encoding/hex"
  6. "io"
  7. "strings"
  8. )
  9. type Scripter interface {
  10. Eval(ctx context.Context, script string, keys []string, args ...interface{}) *Cmd
  11. EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *Cmd
  12. ScriptExists(ctx context.Context, hashes ...string) *BoolSliceCmd
  13. ScriptLoad(ctx context.Context, script string) *StringCmd
  14. }
  15. var (
  16. _ Scripter = (*Client)(nil)
  17. _ Scripter = (*Ring)(nil)
  18. _ Scripter = (*ClusterClient)(nil)
  19. )
  20. type Script struct {
  21. src, hash string
  22. }
  23. func NewScript(src string) *Script {
  24. h := sha1.New()
  25. _, _ = io.WriteString(h, src)
  26. return &Script{
  27. src: src,
  28. hash: hex.EncodeToString(h.Sum(nil)),
  29. }
  30. }
  31. func (s *Script) Hash() string {
  32. return s.hash
  33. }
  34. func (s *Script) Load(ctx context.Context, c Scripter) *StringCmd {
  35. return c.ScriptLoad(ctx, s.src)
  36. }
  37. func (s *Script) Exists(ctx context.Context, c Scripter) *BoolSliceCmd {
  38. return c.ScriptExists(ctx, s.hash)
  39. }
  40. func (s *Script) Eval(ctx context.Context, c Scripter, keys []string, args ...interface{}) *Cmd {
  41. return c.Eval(ctx, s.src, keys, args...)
  42. }
  43. func (s *Script) EvalSha(ctx context.Context, c Scripter, keys []string, args ...interface{}) *Cmd {
  44. return c.EvalSha(ctx, s.hash, keys, args...)
  45. }
  46. // Run optimistically uses EVALSHA to run the script. If script does not exist
  47. // it is retried using EVAL.
  48. func (s *Script) Run(ctx context.Context, c Scripter, keys []string, args ...interface{}) *Cmd {
  49. r := s.EvalSha(ctx, c, keys, args...)
  50. if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") {
  51. return s.Eval(ctx, c, keys, args...)
  52. }
  53. return r
  54. }