Skip to content

Commit

Permalink
support SET NX GET special case
Browse files Browse the repository at this point in the history
  • Loading branch information
alicebob committed Mar 8, 2023
1 parent 5cd31f7 commit 5c16d55
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
36 changes: 25 additions & 11 deletions cmd_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,27 @@ func (m *Miniredis) cmdSet(c *server.Peer, cmd string, args []string) {
withTx(m, c, func(c *server.Peer, ctx *connCtx) {
db := m.db(ctx.selectedDB)

readonly := false
if opts.nx {
if db.exists(opts.key) {
c.WriteNull()
return
if opts.get {
// special case for SET NX GET
readonly = true
} else {
c.WriteNull()
return
}
}
}
if opts.xx {
if !db.exists(opts.key) {
c.WriteNull()
return
if opts.get {
// special case for SET XX GET
readonly = true
} else {
c.WriteNull()
return
}
}
}
if opts.keepttl {
Expand All @@ -154,14 +165,17 @@ func (m *Miniredis) cmdSet(c *server.Peer, cmd string, args []string) {
return
}
}

old, existed := db.stringKeys[opts.key]
db.del(opts.key, true) // be sure to remove existing values of other type keys.
// a vanilla SET clears the expire
if opts.ttl >= 0 { // EXAT/PXAT can expire right away
db.stringSet(opts.key, opts.value)
}
if opts.ttl != 0 {
db.ttl[opts.key] = opts.ttl
if !readonly {
db.del(opts.key, true) // be sure to remove existing values of other type keys.
// a vanilla SET clears the expire
if opts.ttl >= 0 { // EXAT/PXAT can expire right away
db.stringSet(opts.key, opts.value)
}
if opts.ttl != 0 {
db.ttl[opts.key] = opts.ttl
}
}
if opts.get {
if !existed {
Expand Down
7 changes: 7 additions & 0 deletions integration/string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ func TestString(t *testing.T) {
c.Do("SET", "gone", "bar", "EXAT", "123")
c.Do("EXISTS", "gone")

// SET NX GET
c.Do("SET", "unique", "value1", "NX", "GET")
c.Do("SET", "unique", "value2", "NX", "GET")
c.Do("SET", "unique", "value3", "XX", "GET")
c.Do("SET", "unique", "value4", "XX", "GET")
c.Do("SET", "uniquer", "value5", "XX", "GET")

// Failure cases
c.Error("wrong number", "SET")
c.Error("wrong number", "SET", "foo")
Expand Down

0 comments on commit 5c16d55

Please sign in to comment.