shmth
shmth

Reputation: 498

Redis how to make EVAL script behave like MULTI / EXEC?

One thing I noticed when playing around with Lua scripts is that, in a script containing multiple operations, if an error is thrown halfway through the execution of the script, the operations that completed before the error will actually be reflected in the database. This is in contrast to MULTI / EXEC, where either all operations succeed or fail.

For example, if I have a script like the following:

redis.call("hset", "mykey", "myfield", "val")
local expiry = someFunctionThatMightThrow()
redis.call("expire", "mykey", expiry)

I tested this and the results of the first hset call were reflected in redis. Is there any way to make the lua script behave so that if any error is thrown during the script, then all actions performed during that script execution are reverted?

Upvotes: 0

Views: 770

Answers (1)

tabreaz
tabreaz

Reputation: 659

Sample script for my comment above, on error manually rollback. Note: Syntax is not verified.

redis.call("hset", "mykey", "myfield", "val")
local expiry,error = pcall(someFunctionThatMightThrow())
if expiry ~= nil then
  redis.call("expire", "mykey", expiry)
else
  redis.call("hdel", "mykey", "myfield")
end

Upvotes: 1

Related Questions