-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkeys.go
99 lines (92 loc) · 2.31 KB
/
keys.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package godis
import (
"errors"
"regexp"
)
// EXISTS returns in a key exists or not in the DB
func (g *Godis) EXISTS(keys ...string) (int, error) {
count := 0
for _, key := range keys {
if _, ok := g.db[key]; ok {
count++
}
}
return count, nil
}
// DEL removes all keys if it exists and returns the number of keys removed,
// error returned by DEL key is always <nil>.
func (g *Godis) DEL(keys ...string) (int, error) {
count, _ := g.EXISTS(keys...)
for _, key := range keys {
delete(g.db, key)
}
return count, nil
}
// RENAME renames a key to newkey. Returns an error when the key
// and newkey are the same, or when key does not exist. If new key
// already exists it is overwritten.
func (g *Godis) RENAME(key, newKey string) (string, error) {
if key == newKey {
return "", errors.New("samekeys")
}
if got, _ := g.EXISTS(key); got == 0 {
return "", errors.New("keynotexists")
}
if got, _ := g.EXISTS(newKey); got > 0 {
g.DEL(newKey)
}
val, _ := g.GET(key)
g.DEL(key)
got, _ := g.SET(newKey, val)
return got, nil
}
// RENAMENX is used to rename key to newkey if newkey does not yet exist.
// Returns an error under the same conditions as RENAME.
func (g *Godis) RENAMENX(key, newKey string) (string, error) {
if key == newKey {
return "", errors.New("samekeys")
}
if got, _ := g.EXISTS(key); got == 0 {
return "", errors.New("keynotexists")
}
if got, _ := g.EXISTS(newKey); got != 0 {
return "", errors.New("newkeyexists")
}
val, _ := g.GET(key)
g.DEL(key)
got, _ := g.SET(newKey, val)
return got, nil
}
// RANDOMKEY returns a random key from the currently selected database.
func (g *Godis) RANDOMKEY() (*SDS, error) {
keys := make([]string, len(g.db))
i := 0
// TODO : Move below logic to KEYS command when its implemented.
for k := range g.db {
keys[i] = k
i++
}
if len(keys) == 0 {
return nil, errors.New("emptydb")
}
rnum := g.generateRandnum(len(keys))
return g.db[keys[rnum]], nil
}
// Returns all keys matching pattern.
func (g *Godis) KEYS(pattern string) ([]string, error) {
allKeys := g.getAllKeys()
var matchs []string
r, err := regexp.Compile(pattern)
if err != nil {
return matchs, errors.New("invalidregex")
}
if len(allKeys) == 0 {
return matchs, nil
}
for _, k := range allKeys {
if r.MatchString(k) {
matchs = append(matchs, k)
}
}
return matchs, nil
}