-
Notifications
You must be signed in to change notification settings - Fork 0
/
scripts.go
84 lines (65 loc) · 2 KB
/
scripts.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package redisLuaScriptUtils
import (
"fmt"
"strings"
)
type RedisScript struct {
scriptText string
args []string
keys []string
}
func NewRedisScript(keys []string, args []string, scriptText string) *RedisScript {
return &RedisScript{
scriptText: scriptText,
args: args,
keys: keys,
}
}
func getScriptsUniqueArgNames(scripts []*RedisScript) []string {
uniqueArgs := make(map[string]bool, 0)
uniqueArgsSlice := []string{}
for _, script := range scripts {
for _, key := range script.args {
if !uniqueArgs[key] {
uniqueArgsSlice = append(uniqueArgsSlice, key)
uniqueArgs[key] = true
}
}
}
return uniqueArgsSlice
}
func joinRedisScripts(scripts []*RedisScript, keys []*RedisKey, args []string) *RedisScript {
result := &RedisScript{}
var functionCalls []string
for scriptIndex, script := range scripts {
compiledArgs := ""
for argIndex, arg := range args {
result.args = append(result.args, arg)
compiledArgs = compiledArgs + fmt.Sprintf("local %s = ARGV[%d];\n", arg, argIndex+1)
}
compiledKeys := ""
for keyIndex, key := range keys {
result.keys = append(result.keys, key.Key())
compiledKeys = compiledKeys + fmt.Sprintf("local %s = KEYS[%d];\n", key.Key(), keyIndex+1)
}
functionName := fmt.Sprintf("____joinedRedisScripts_%d____", scriptIndex)
envelopedScriptText := fmt.Sprintf("local function %s()\n%s\n%s\n%s\nend", functionName, compiledKeys, compiledArgs, script.scriptText)
functionCalls = append(functionCalls, fmt.Sprintf("%s()", functionName))
if len(result.scriptText) > 0 {
result.scriptText = result.scriptText + "\n" + envelopedScriptText
} else {
result.scriptText = envelopedScriptText
}
}
result.scriptText = result.scriptText + "\n" + "return {" + strings.Join(functionCalls, ", ") + "}\n"
return result
}
func (this *RedisScript) String() string {
return this.scriptText
}
func (this *RedisScript) Keys() []string {
return this.keys
}
func (this *RedisScript) Args() []string {
return this.args
}