File: script.go

package info (click to toggle)
golang-gopkg-redis.v2 2.3.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 280 kB
  • sloc: makefile: 6
file content (52 lines) | stat: -rw-r--r-- 1,110 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package redis

import (
	"crypto/sha1"
	"encoding/hex"
	"io"
	"strings"
)

type scripter interface {
	Eval(script string, keys []string, args []string) *Cmd
	EvalSha(sha1 string, keys []string, args []string) *Cmd
	ScriptExists(scripts ...string) *BoolSliceCmd
	ScriptLoad(script string) *StringCmd
}

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)),
	}
}

func (s *Script) Load(c scripter) *StringCmd {
	return c.ScriptLoad(s.src)
}

func (s *Script) Exists(c scripter) *BoolSliceCmd {
	return c.ScriptExists(s.src)
}

func (s *Script) Eval(c scripter, keys []string, args []string) *Cmd {
	return c.Eval(s.src, keys, args)
}

func (s *Script) EvalSha(c scripter, keys []string, args []string) *Cmd {
	return c.EvalSha(s.hash, keys, args)
}

func (s *Script) Run(c *Client, keys []string, args []string) *Cmd {
	r := s.EvalSha(c, keys, args)
	if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") {
		return s.Eval(c, keys, args)
	}
	return r
}