From aa2bf6ba8bec776c02d8055ac856d96926137895 Mon Sep 17 00:00:00 2001 From: antirez Date: Mon, 12 Nov 2012 23:04:36 +0100 Subject: [PATCH 1/1] TTL API change: TTL returns -2 for non existing keys. The previous behavior was to return -1 if: 1) Existing key but without an expire set. 2) Non existing key. Now the second case is handled in a different, and TTL will return -2 if the key does not exist at all. PTTL follows the same behavior as well. --- src/db.c | 7 +++++++ tests/unit/expire.tcl | 20 +++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/db.c b/src/db.c index 9fe9a003..a73d1fbf 100644 --- a/src/db.c +++ b/src/db.c @@ -614,6 +614,13 @@ void ttlGenericCommand(redisClient *c, int output_ms) { long long expire, ttl = -1; expire = getExpire(c->db,c->argv[1]); + /* If the key does not exist at all, return -2 */ + if (expire == -1 && lookupKeyRead(c->db,c->argv[1]) == NULL) { + addReplyLongLong(c,-2); + return; + } + /* The key exists. Return -1 if it has no expire, or the actual + * TTL value otherwise. */ if (expire != -1) { ttl = expire-mstime(); if (ttl < 0) ttl = -1; diff --git a/tests/unit/expire.tcl b/tests/unit/expire.tcl index 56a59f76..57497fe5 100644 --- a/tests/unit/expire.tcl +++ b/tests/unit/expire.tcl @@ -121,13 +121,31 @@ start_server {tags {"expire"}} { list $a $b } {somevalue {}} - test {PTTL returns millisecond time to live} { + test {TTL returns tiem to live in seconds} { + r del x + r setex x 10 somevalue + set ttl [r ttl x] + assert {$ttl > 8 && $ttl <= 10} + } + + test {PTTL returns time to live in milliseconds} { r del x r setex x 1 somevalue set ttl [r pttl x] assert {$ttl > 900 && $ttl <= 1000} } + test {TTL / PTTL return -1 if key has no expire} { + r del x + r set x hello + list [r ttl x] [r pttl x] + } {-1 -1} + + test {TTL / PTTL return -2 if key does not exit} { + r del x + list [r ttl x] [r pttl x] + } {-2 -2} + test {Redis should actively expire keys incrementally} { r flushdb r psetex key1 500 a -- 2.45.2