]> git.saurik.com Git - redis.git/blame - src/db.c
Query the archive to provide a complete KEYS list.
[redis.git] / src / db.c
CommitLineData
d288ee65 1/*
2 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * * Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * * Neither the name of Redis nor the names of its contributors may be used
14 * to endorse or promote products derived from this software without
15 * specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 */
29
e2641e09 30#include "redis.h"
31
32#include <signal.h>
7dcc10b6 33#include <ctype.h>
e2641e09 34
c772d9c6 35void SlotToKeyAdd(robj *key);
36void SlotToKeyDel(robj *key);
37
e2641e09 38/*-----------------------------------------------------------------------------
39 * C-level DB API
40 *----------------------------------------------------------------------------*/
41
42robj *lookupKey(redisDb *db, robj *key) {
43 dictEntry *de = dictFind(db->dict,key->ptr);
44 if (de) {
c0ba9ebe 45 robj *val = dictGetVal(de);
e2641e09 46
7d0966a6 47 /* Update the access time for the aging algorithm.
48 * Don't do it if we have a saving child, as this will trigger
49 * a copy on write madness. */
f48cd4b9 50 if (server.rdb_child_pid == -1 && server.aof_child_pid == -1)
7d0966a6 51 val->lru = server.lruclock;
e2641e09 52 return val;
53 } else {
8e2a225a 54 return recover(db, key);
e2641e09 55 }
56}
57
58robj *lookupKeyRead(redisDb *db, robj *key) {
b80b1c59 59 robj *val;
60
e2641e09 61 expireIfNeeded(db,key);
b80b1c59 62 val = lookupKey(db,key);
63 if (val == NULL)
64 server.stat_keyspace_misses++;
65 else
66 server.stat_keyspace_hits++;
67 return val;
e2641e09 68}
69
70robj *lookupKeyWrite(redisDb *db, robj *key) {
bcf2995c 71 expireIfNeeded(db,key);
8e2a225a
JF
72 robj *val = lookupKey(db,key);
73 if (val) val->archived = 0;
74 return val;
e2641e09 75}
76
77robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
78 robj *o = lookupKeyRead(c->db, key);
79 if (!o) addReply(c,reply);
80 return o;
81}
82
83robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
84 robj *o = lookupKeyWrite(c->db, key);
85 if (!o) addReply(c,reply);
86 return o;
87}
88
f85cd526 89/* Add the key to the DB. It's up to the caller to increment the reference
90 * counte of the value if needed.
91 *
92 * The program is aborted if the key already exists. */
93void dbAdd(redisDb *db, robj *key, robj *val) {
94 sds copy = sdsdup(key->ptr);
95 int retval = dictAdd(db->dict, copy, val);
7c24c300 96 val->archived = 0;
f85cd526 97
eab0e26e 98 redisAssertWithInfo(NULL,key,retval == REDIS_OK);
f85cd526 99 }
100
101/* Overwrite an existing key with a new value. Incrementing the reference
102 * count of the new value is up to the caller.
103 * This function does not modify the expire time of the existing key.
104 *
105 * The program is aborted if the key was not already present. */
106void dbOverwrite(redisDb *db, robj *key, robj *val) {
107 struct dictEntry *de = dictFind(db->dict,key->ptr);
108
eab0e26e 109 redisAssertWithInfo(NULL,key,de != NULL);
f85cd526 110 dictReplace(db->dict, key->ptr, val);
e2641e09 111}
112
f85cd526 113/* High level Set operation. This function can be used in order to set
114 * a key, whatever it was existing or not, to a new object.
e2641e09 115 *
f85cd526 116 * 1) The ref count of the value object is incremented.
117 * 2) clients WATCHing for the destination key notified.
118 * 3) The expire time of the key is reset (the key is made persistent). */
119void setKey(redisDb *db, robj *key, robj *val) {
120 if (lookupKeyWrite(db,key) == NULL) {
121 dbAdd(db,key,val);
e2641e09 122 } else {
f85cd526 123 dbOverwrite(db,key,val);
e2641e09 124 }
f85cd526 125 incrRefCount(val);
126 removeExpire(db,key);
89f6f6ab 127 signalModifiedKey(db,key);
e2641e09 128}
129
130int dbExists(redisDb *db, robj *key) {
813ed292
JF
131 if (dictFind(db->dict,key->ptr) != NULL)
132 return 1;
133 if (recover(db, key) != NULL)
134 return 1;
135 return 0;
e2641e09 136}
137
138/* Return a random key, in form of a Redis object.
139 * If there are no keys, NULL is returned.
140 *
141 * The function makes sure to return keys not already expired. */
142robj *dbRandomKey(redisDb *db) {
143 struct dictEntry *de;
144
145 while(1) {
146 sds key;
147 robj *keyobj;
148
149 de = dictGetRandomKey(db->dict);
150 if (de == NULL) return NULL;
151
c0ba9ebe 152 key = dictGetKey(de);
e2641e09 153 keyobj = createStringObject(key,sdslen(key));
154 if (dictFind(db->expires,key)) {
155 if (expireIfNeeded(db,keyobj)) {
156 decrRefCount(keyobj);
157 continue; /* search for another key. This expired. */
158 }
159 }
160 return keyobj;
161 }
162}
163
164/* Delete a key, value, and associated expiration entry if any, from the DB */
35e29472 165int dbDeleteSoft(redisDb *db, robj *key) {
e2641e09 166 /* Deleting an entry from the expires dict will not free the sds of
167 * the key, because it is shared with the main dictionary. */
168 if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
c772d9c6 169 if (dictDelete(db->dict,key->ptr) == DICT_OK) {
c772d9c6 170 return 1;
171 } else {
172 return 0;
173 }
e2641e09 174}
175
35e29472
JF
176/* Delete a key, value, and associated expiration entry if any, even archived */
177int dbDelete(redisDb *db, robj *key) {
178 purge(key);
179 return dbDeleteSoft(db, key);
180}
181
e2641e09 182long long emptyDb() {
183 int j;
184 long long removed = 0;
185
186 for (j = 0; j < server.dbnum; j++) {
187 removed += dictSize(server.db[j].dict);
188 dictEmpty(server.db[j].dict);
189 dictEmpty(server.db[j].expires);
190 }
191 return removed;
192}
193
194int selectDb(redisClient *c, int id) {
195 if (id < 0 || id >= server.dbnum)
196 return REDIS_ERR;
197 c->db = &server.db[id];
198 return REDIS_OK;
199}
200
cea8c5cd 201/*-----------------------------------------------------------------------------
202 * Hooks for key space changes.
203 *
204 * Every time a key in the database is modified the function
205 * signalModifiedKey() is called.
206 *
207 * Every time a DB is flushed the function signalFlushDb() is called.
208 *----------------------------------------------------------------------------*/
209
210void signalModifiedKey(redisDb *db, robj *key) {
211 touchWatchedKey(db,key);
cea8c5cd 212}
213
214void signalFlushedDb(int dbid) {
215 touchWatchedKeysOnFlush(dbid);
cea8c5cd 216}
217
e2641e09 218/*-----------------------------------------------------------------------------
219 * Type agnostic commands operating on the key space
220 *----------------------------------------------------------------------------*/
221
222void flushdbCommand(redisClient *c) {
223 server.dirty += dictSize(c->db->dict);
cea8c5cd 224 signalFlushedDb(c->db->id);
e2641e09 225 dictEmpty(c->db->dict);
226 dictEmpty(c->db->expires);
227 addReply(c,shared.ok);
228}
229
230void flushallCommand(redisClient *c) {
cea8c5cd 231 signalFlushedDb(-1);
e2641e09 232 server.dirty += emptyDb();
233 addReply(c,shared.ok);
f48cd4b9 234 if (server.rdb_child_pid != -1) {
235 kill(server.rdb_child_pid,SIGKILL);
236 rdbRemoveTempFile(server.rdb_child_pid);
e2641e09 237 }
13cd1515 238 if (server.saveparamslen > 0) {
239 /* Normally rdbSave() will reset dirty, but we don't want this here
240 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
241 int saved_dirty = server.dirty;
f48cd4b9 242 rdbSave(server.rdb_filename);
13cd1515 243 server.dirty = saved_dirty;
244 }
e2641e09 245 server.dirty++;
246}
247
248void delCommand(redisClient *c) {
249 int deleted = 0, j;
250
251 for (j = 1; j < c->argc; j++) {
252 if (dbDelete(c->db,c->argv[j])) {
cea8c5cd 253 signalModifiedKey(c->db,c->argv[j]);
e2641e09 254 server.dirty++;
255 deleted++;
256 }
257 }
258 addReplyLongLong(c,deleted);
259}
260
261void existsCommand(redisClient *c) {
262 expireIfNeeded(c->db,c->argv[1]);
263 if (dbExists(c->db,c->argv[1])) {
264 addReply(c, shared.cone);
265 } else {
266 addReply(c, shared.czero);
267 }
268}
269
270void selectCommand(redisClient *c) {
b58f03a0 271 long id;
272
273 if (getLongFromObjectOrReply(c, c->argv[1], &id,
274 "invalid DB index") != REDIS_OK)
275 return;
e2641e09 276
277 if (selectDb(c,id) == REDIS_ERR) {
3ab20376 278 addReplyError(c,"invalid DB index");
e2641e09 279 } else {
280 addReply(c,shared.ok);
281 }
282}
283
284void randomkeyCommand(redisClient *c) {
285 robj *key;
286
287 if ((key = dbRandomKey(c->db)) == NULL) {
288 addReply(c,shared.nullbulk);
289 return;
290 }
291
292 addReplyBulk(c,key);
293 decrRefCount(key);
294}
295
296void keysCommand(redisClient *c) {
297 dictIterator *di;
298 dictEntry *de;
299 sds pattern = c->argv[1]->ptr;
e0e1c195 300 int plen = sdslen(pattern), allkeys;
e2641e09 301 unsigned long numkeys = 0;
b301c1fc 302 void *replylen = addDeferredMultiBulkLength(c);
e2641e09 303
9311d2b5 304 di = dictGetSafeIterator(c->db->dict);
e0e1c195 305 allkeys = (pattern[0] == '*' && pattern[1] == '\0');
e2641e09 306 while((de = dictNext(di)) != NULL) {
c0ba9ebe 307 sds key = dictGetKey(de);
e2641e09 308 robj *keyobj;
309
e0e1c195 310 if (allkeys || stringmatchlen(pattern,plen,key,sdslen(key),0)) {
e2641e09 311 keyobj = createStringObject(key,sdslen(key));
312 if (expireIfNeeded(c->db,keyobj) == 0) {
313 addReplyBulk(c,keyobj);
314 numkeys++;
315 }
316 decrRefCount(keyobj);
317 }
318 }
319 dictReleaseIterator(di);
bfbf8c88
JF
320
321 rummage(c, &numkeys);
322
b301c1fc 323 setDeferredMultiBulkLength(c,replylen,numkeys);
e2641e09 324}
325
326void dbsizeCommand(redisClient *c) {
b70d3555 327 addReplyLongLong(c,dictSize(c->db->dict));
e2641e09 328}
329
330void lastsaveCommand(redisClient *c) {
b70d3555 331 addReplyLongLong(c,server.lastsave);
e2641e09 332}
333
334void typeCommand(redisClient *c) {
335 robj *o;
336 char *type;
337
338 o = lookupKeyRead(c->db,c->argv[1]);
339 if (o == NULL) {
3ab20376 340 type = "none";
e2641e09 341 } else {
342 switch(o->type) {
3ab20376
PN
343 case REDIS_STRING: type = "string"; break;
344 case REDIS_LIST: type = "list"; break;
345 case REDIS_SET: type = "set"; break;
346 case REDIS_ZSET: type = "zset"; break;
347 case REDIS_HASH: type = "hash"; break;
348 default: type = "unknown"; break;
e2641e09 349 }
350 }
3ab20376 351 addReplyStatus(c,type);
e2641e09 352}
353
e2641e09 354void shutdownCommand(redisClient *c) {
4ab8695d 355 int flags = 0;
356
357 if (c->argc > 2) {
358 addReply(c,shared.syntaxerr);
359 return;
360 } else if (c->argc == 2) {
361 if (!strcasecmp(c->argv[1]->ptr,"nosave")) {
362 flags |= REDIS_SHUTDOWN_NOSAVE;
363 } else if (!strcasecmp(c->argv[1]->ptr,"save")) {
364 flags |= REDIS_SHUTDOWN_SAVE;
365 } else {
366 addReply(c,shared.syntaxerr);
367 return;
368 }
369 }
370 if (prepareForShutdown(flags) == REDIS_OK) exit(0);
3ab20376 371 addReplyError(c,"Errors trying to SHUTDOWN. Check logs.");
e2641e09 372}
373
374void renameGenericCommand(redisClient *c, int nx) {
375 robj *o;
7dcc10b6 376 long long expire;
e2641e09 377
378 /* To use the same key as src and dst is probably an error */
379 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
380 addReply(c,shared.sameobjecterr);
381 return;
382 }
383
384 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
385 return;
386
387 incrRefCount(o);
4ab18a33 388 expire = getExpire(c->db,c->argv[1]);
f85cd526 389 if (lookupKeyWrite(c->db,c->argv[2]) != NULL) {
e2641e09 390 if (nx) {
391 decrRefCount(o);
392 addReply(c,shared.czero);
393 return;
394 }
4ab18a33 395 /* Overwrite: delete the old key before creating the new one with the same name. */
396 dbDelete(c->db,c->argv[2]);
e2641e09 397 }
4ab18a33 398 dbAdd(c->db,c->argv[2],o);
399 if (expire != -1) setExpire(c->db,c->argv[2],expire);
e2641e09 400 dbDelete(c->db,c->argv[1]);
cea8c5cd 401 signalModifiedKey(c->db,c->argv[1]);
402 signalModifiedKey(c->db,c->argv[2]);
e2641e09 403 server.dirty++;
404 addReply(c,nx ? shared.cone : shared.ok);
405}
406
407void renameCommand(redisClient *c) {
408 renameGenericCommand(c,0);
409}
410
411void renamenxCommand(redisClient *c) {
412 renameGenericCommand(c,1);
413}
414
415void moveCommand(redisClient *c) {
416 robj *o;
417 redisDb *src, *dst;
418 int srcid;
419
420 /* Obtain source and target DB pointers */
421 src = c->db;
422 srcid = c->db->id;
423 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
424 addReply(c,shared.outofrangeerr);
425 return;
426 }
427 dst = c->db;
428 selectDb(c,srcid); /* Back to the source DB */
429
430 /* If the user is moving using as target the same
431 * DB as the source DB it is probably an error. */
432 if (src == dst) {
433 addReply(c,shared.sameobjecterr);
434 return;
435 }
436
437 /* Check if the element exists and get a reference */
438 o = lookupKeyWrite(c->db,c->argv[1]);
439 if (!o) {
440 addReply(c,shared.czero);
441 return;
442 }
443
f85cd526 444 /* Return zero if the key already exists in the target DB */
445 if (lookupKeyWrite(dst,c->argv[1]) != NULL) {
e2641e09 446 addReply(c,shared.czero);
447 return;
448 }
f85cd526 449 dbAdd(dst,c->argv[1],o);
e2641e09 450 incrRefCount(o);
451
452 /* OK! key moved, free the entry in the source DB */
453 dbDelete(src,c->argv[1]);
454 server.dirty++;
455 addReply(c,shared.cone);
456}
457
458/*-----------------------------------------------------------------------------
459 * Expires API
460 *----------------------------------------------------------------------------*/
461
462int removeExpire(redisDb *db, robj *key) {
463 /* An expire may only be removed if there is a corresponding entry in the
464 * main dict. Otherwise, the key will never be freed. */
eab0e26e 465 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
a539d29a 466 return dictDelete(db->expires,key->ptr) == DICT_OK;
e2641e09 467}
468
7dcc10b6 469void setExpire(redisDb *db, robj *key, long long when) {
470 dictEntry *kde, *de;
e2641e09 471
472 /* Reuse the sds from the main dict in the expire dict */
7dcc10b6 473 kde = dictFind(db->dict,key->ptr);
474 redisAssertWithInfo(NULL,key,kde != NULL);
475 de = dictReplaceRaw(db->expires,dictGetKey(kde));
476 dictSetSignedIntegerVal(de,when);
e2641e09 477}
478
479/* Return the expire time of the specified key, or -1 if no expire
480 * is associated with this key (i.e. the key is non volatile) */
7dcc10b6 481long long getExpire(redisDb *db, robj *key) {
e2641e09 482 dictEntry *de;
483
484 /* No expire? return ASAP */
485 if (dictSize(db->expires) == 0 ||
486 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
487
488 /* The entry was found in the expire dict, this means it should also
489 * be present in the main dict (safety check). */
eab0e26e 490 redisAssertWithInfo(NULL,key,dictFind(db->dict,key->ptr) != NULL);
7dcc10b6 491 return dictGetSignedIntegerVal(de);
e2641e09 492}
493
bcf2995c 494/* Propagate expires into slaves and the AOF file.
495 * When a key expires in the master, a DEL operation for this key is sent
496 * to all the slaves and the AOF file if enabled.
497 *
498 * This way the key expiry is centralized in one place, and since both
499 * AOF and the master->slave link guarantee operation ordering, everything
500 * will be consistent even if we allow write operations against expiring
501 * keys. */
502void propagateExpire(redisDb *db, robj *key) {
bcf2995c 503 robj *argv[2];
504
355f8591 505 argv[0] = shared.del;
bcf2995c 506 argv[1] = key;
355f8591 507 incrRefCount(argv[0]);
508 incrRefCount(argv[1]);
bcf2995c 509
e394114d 510 if (server.aof_state != REDIS_AOF_OFF)
1b1f47c9 511 feedAppendOnlyFile(server.delCommand,db->id,argv,2);
bcf2995c 512 if (listLength(server.slaves))
513 replicationFeedSlaves(server.slaves,db->id,argv,2);
514
c25a5d3b 515 decrRefCount(argv[0]);
516 decrRefCount(argv[1]);
bcf2995c 517}
518
e2641e09 519int expireIfNeeded(redisDb *db, robj *key) {
7dcc10b6 520 long long when = getExpire(db,key);
bcf2995c 521
3a73be75 522 if (when < 0) return 0; /* No expire for this key */
523
040b0ade
HW
524 /* Don't expire anything while loading. It will be done later. */
525 if (server.loading) return 0;
526
bcf2995c 527 /* If we are running in the context of a slave, return ASAP:
528 * the slave key expiration is controlled by the master that will
529 * send us synthesized DEL operations for expired keys.
530 *
531 * Still we try to return the right information to the caller,
532 * that is, 0 if we think the key should be still valid, 1 if
533 * we think the key is expired at this time. */
534 if (server.masterhost != NULL) {
92dd4e43 535 return mstime() > when;
bcf2995c 536 }
537
e2641e09 538 /* Return when this key has not expired */
7dcc10b6 539 if (mstime() <= when) return 0;
e2641e09 540
541 /* Delete the key */
542 server.stat_expiredkeys++;
bcf2995c 543 propagateExpire(db,key);
e2641e09 544 return dbDelete(db,key);
545}
546
547/*-----------------------------------------------------------------------------
548 * Expires Commands
549 *----------------------------------------------------------------------------*/
550
3aad0de2 551/* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
552 * and PEXPIREAT. Because the commad second argument may be relative or absolute
553 * the "basetime" argument is used to signal what the base time is (either 0
554 * for *AT variants of the command, or the current time for relative expires).
555 *
556 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
557 * the argv[2] parameter. The basetime is always specified in milliesconds. */
558void expireGenericCommand(redisClient *c, long long basetime, int unit) {
e2641e09 559 dictEntry *de;
7dcc10b6 560 robj *key = c->argv[1], *param = c->argv[2];
3aad0de2 561 long long when; /* unix time in milliseconds when the key will expire. */
e2641e09 562
3aad0de2 563 if (getLongLongFromObjectOrReply(c, param, &when, NULL) != REDIS_OK)
7dcc10b6 564 return;
e2641e09 565
3aad0de2 566 if (unit == UNIT_SECONDS) when *= 1000;
567 when += basetime;
e2641e09 568
569 de = dictFind(c->db->dict,key->ptr);
570 if (de == NULL) {
571 addReply(c,shared.czero);
572 return;
573 }
812ecc8b 574 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
575 * should never be executed as a DEL when load the AOF or in the context
576 * of a slave instance.
577 *
578 * Instead we take the other branch of the IF statement setting an expire
579 * (possibly in the past) and wait for an explicit DEL from the master. */
3aad0de2 580 if (when <= mstime() && !server.loading && !server.masterhost) {
812ecc8b 581 robj *aux;
582
eab0e26e 583 redisAssertWithInfo(c,key,dbDelete(c->db,key));
812ecc8b 584 server.dirty++;
585
586 /* Replicate/AOF this as an explicit DEL. */
587 aux = createStringObject("DEL",3);
588 rewriteClientCommandVector(c,2,aux,key);
589 decrRefCount(aux);
cea8c5cd 590 signalModifiedKey(c->db,key);
812ecc8b 591 addReply(c, shared.cone);
e2641e09 592 return;
593 } else {
3aad0de2 594 setExpire(c->db,key,when);
0cf5b7b5 595 addReply(c,shared.cone);
cea8c5cd 596 signalModifiedKey(c->db,key);
0cf5b7b5 597 server.dirty++;
e2641e09 598 return;
599 }
600}
601
602void expireCommand(redisClient *c) {
81a28fe1 603 expireGenericCommand(c,mstime(),UNIT_SECONDS);
e2641e09 604}
605
606void expireatCommand(redisClient *c) {
81a28fe1 607 expireGenericCommand(c,0,UNIT_SECONDS);
e2641e09 608}
609
12d293ca 610void pexpireCommand(redisClient *c) {
81a28fe1 611 expireGenericCommand(c,mstime(),UNIT_MILLISECONDS);
12d293ca 612}
52d46855 613
12d293ca 614void pexpireatCommand(redisClient *c) {
81a28fe1 615 expireGenericCommand(c,0,UNIT_MILLISECONDS);
12d293ca 616}
617
618void ttlGenericCommand(redisClient *c, int output_ms) {
619 long long expire, ttl = -1;
e2641e09 620
621 expire = getExpire(c->db,c->argv[1]);
622 if (expire != -1) {
7dcc10b6 623 ttl = expire-mstime();
e2641e09 624 if (ttl < 0) ttl = -1;
625 }
7dcc10b6 626 if (ttl == -1) {
627 addReplyLongLong(c,-1);
628 } else {
52d46855 629 addReplyLongLong(c,output_ms ? ttl : ((ttl+500)/1000));
7dcc10b6 630 }
e2641e09 631}
a539d29a 632
12d293ca 633void ttlCommand(redisClient *c) {
634 ttlGenericCommand(c, 0);
635}
636
637void pttlCommand(redisClient *c) {
638 ttlGenericCommand(c, 1);
639}
640
a539d29a 641void persistCommand(redisClient *c) {
642 dictEntry *de;
643
644 de = dictFind(c->db->dict,c->argv[1]->ptr);
645 if (de == NULL) {
646 addReply(c,shared.czero);
647 } else {
1fb4e8de 648 if (removeExpire(c->db,c->argv[1])) {
a539d29a 649 addReply(c,shared.cone);
1fb4e8de 650 server.dirty++;
651 } else {
a539d29a 652 addReply(c,shared.czero);
1fb4e8de 653 }
a539d29a 654 }
655}
9791f0f8 656
657/* -----------------------------------------------------------------------------
658 * API to get key arguments from commands
659 * ---------------------------------------------------------------------------*/
660
661int *getKeysUsingCommandTable(struct redisCommand *cmd,robj **argv, int argc, int *numkeys) {
662 int j, i = 0, last, *keys;
663 REDIS_NOTUSED(argv);
664
665 if (cmd->firstkey == 0) {
666 *numkeys = 0;
667 return NULL;
668 }
669 last = cmd->lastkey;
670 if (last < 0) last = argc+last;
671 keys = zmalloc(sizeof(int)*((last - cmd->firstkey)+1));
672 for (j = cmd->firstkey; j <= last; j += cmd->keystep) {
673 redisAssert(j < argc);
b4b51446 674 keys[i++] = j;
9791f0f8 675 }
b4b51446 676 *numkeys = i;
9791f0f8 677 return keys;
678}
679
680int *getKeysFromCommand(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
681 if (cmd->getkeys_proc) {
682 return cmd->getkeys_proc(cmd,argv,argc,numkeys,flags);
683 } else {
684 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
685 }
686}
687
688void getKeysFreeResult(int *result) {
689 zfree(result);
690}
691
692int *noPreloadGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
693 if (flags & REDIS_GETKEYS_PRELOAD) {
694 *numkeys = 0;
695 return NULL;
696 } else {
697 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
698 }
699}
700
701int *renameGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
702 if (flags & REDIS_GETKEYS_PRELOAD) {
703 int *keys = zmalloc(sizeof(int));
704 *numkeys = 1;
705 keys[0] = 1;
4b61ca46 706 return keys;
9791f0f8 707 } else {
708 return getKeysUsingCommandTable(cmd,argv,argc,numkeys);
709 }
710}
711
712int *zunionInterGetKeys(struct redisCommand *cmd,robj **argv, int argc, int *numkeys, int flags) {
713 int i, num, *keys;
714 REDIS_NOTUSED(cmd);
715 REDIS_NOTUSED(flags);
716
717 num = atoi(argv[2]->ptr);
718 /* Sanity check. Don't return any key if the command is going to
719 * reply with syntax error. */
720 if (num > (argc-3)) {
721 *numkeys = 0;
722 return NULL;
723 }
6e1b9b58 724 keys = zmalloc(sizeof(int)*num);
9791f0f8 725 for (i = 0; i < num; i++) keys[i] = 3+i;
726 *numkeys = num;
727 return keys;
728}