Skip to content

Commit

Permalink
fix(core): Auto convert double to integers in lua scripts
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Oleshko <[email protected]>
  • Loading branch information
dranikpg committed Mar 8, 2023
1 parent b7abe26 commit 7359de0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/core/interpreter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,18 @@ void RedisTranslator::OnString(std::string_view str) {
ArrayPost();
}

// Doubles are not supported by Redis, however we can support them.
// Here is the use-case:
// local foo = redis.call('zscore', 'myzset', 'one')
// assert(type(foo) == "number")
void RedisTranslator::OnDouble(double d) {
static constexpr double kConvertEps = std::numeric_limits<double>::epsilon();

double fractpart, intpart;
fractpart = modf(d, &intpart);

ArrayPre();
lua_pushnumber(lua_, d);
if (abs(fractpart) < kConvertEps && intpart < std::numeric_limits<lua_Integer>::max() &&
intpart > std::numeric_limits<lua_Integer>::min())
lua_pushinteger(lua_, (lua_Integer)d);
else
lua_pushnumber(lua_, d);
ArrayPost();
}

Expand Down
10 changes: 10 additions & 0 deletions src/server/multi_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,16 @@ TEST_F(MultiTest, Eval) {
ASSERT_THAT(resp, ArrLen(3));
const auto& arr = resp.GetVec();
EXPECT_THAT(arr, ElementsAre("a", "b", "c"));

Run({"zadd", "z1", "123", "a", "12345678912345", "b", "12.5", "c"});
const char* kGetScore = "return redis.call('ZSCORE', KEYS[1], ARGV[1]) .. '-works'";

resp = Run({"eval", kGetScore, "1", "z1", "a"});
EXPECT_EQ(resp, "123-works");
resp = Run({"eval", kGetScore, "1", "z1", "b"});
EXPECT_EQ(resp, "12345678912345-works");
resp = Run({"eval", kGetScore, "1", "z1", "c"});
EXPECT_EQ(resp, "12.5-works");
}

TEST_F(MultiTest, Watch) {
Expand Down

0 comments on commit 7359de0

Please sign in to comment.