Skip to content

Commit

Permalink
[Experimental] Add new hmsetnx lua command
Browse files Browse the repository at this point in the history
Would be nice to have this in Redis core, but doesn't look like
it's likely to happen. Ref. redis/redis#542

Note that there's another Lua implementation floating around
(https://redisgreen.net/library/hmsetnx.html), but that doesn't account
for a pre-existing hash key without the given fields.
  • Loading branch information
ptaoussanis committed Feb 1, 2019
1 parent 6f9a87b commit dc68821
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/lua/hmsetnx.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
local hkey = KEYS[1];

if redis.call('exists', hkey) == 0 then
redis.call('hmset', hkey, unpack(ARGV));
return 1;
else
local proceed = true;
for i,x in ipairs(ARGV) do
if (i % 2 ~= 0) then -- odd i => `x` is field
if redis.call('hexists', hkey, x) == 1 then
proceed = false;
break;
end
end
end

if proceed then
redis.call('hmset', hkey, unpack(ARGV));
return 1;
else
return 0;
end
end
11 changes: 11 additions & 0 deletions src/taoensso/carmine.clj
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,17 @@

;;;;

(def hmsetnx "Experimental."
(let [script (enc/slurp-resource "lua/hmsetnx.lua")]
(fn [key field value & more]
(-eval* script 1 (into [key field value] more)))))

(comment
(wcar {} (hgetall "foo"))
(wcar {} (hmsetnx "foo" "f1" "v1" "f2" "v2")))

;;;;

(defn reduce-scan
"For use with `scan`, `zscan`, etc. Takes:
- (fn rf [acc scan-result]) -> next accumulator
Expand Down

0 comments on commit dc68821

Please sign in to comment.