]>
git.saurik.com Git - redis.git/blob - src/db.c
6 void SlotToKeyAdd(robj
*key
);
7 void SlotToKeyDel(robj
*key
);
9 /*-----------------------------------------------------------------------------
11 *----------------------------------------------------------------------------*/
13 robj
*lookupKey(redisDb
*db
, robj
*key
) {
14 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
16 robj
*val
= dictGetVal(de
);
18 /* Update the access time for the aging algorithm.
19 * Don't do it if we have a saving child, as this will trigger
20 * a copy on write madness. */
21 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1)
22 val
->lru
= server
.lruclock
;
29 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
32 expireIfNeeded(db
,key
);
33 val
= lookupKey(db
,key
);
35 server
.stat_keyspace_misses
++;
37 server
.stat_keyspace_hits
++;
41 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
42 expireIfNeeded(db
,key
);
43 return lookupKey(db
,key
);
46 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
47 robj
*o
= lookupKeyRead(c
->db
, key
);
48 if (!o
) addReply(c
,reply
);
52 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
53 robj
*o
= lookupKeyWrite(c
->db
, key
);
54 if (!o
) addReply(c
,reply
);
58 /* Add the key to the DB. It's up to the caller to increment the reference
59 * counte of the value if needed.
61 * The program is aborted if the key already exists. */
62 void dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
63 sds copy
= sdsdup(key
->ptr
);
64 int retval
= dictAdd(db
->dict
, copy
, val
);
66 redisAssertWithInfo(NULL
,key
,retval
== REDIS_OK
);
69 /* Overwrite an existing key with a new value. Incrementing the reference
70 * count of the new value is up to the caller.
71 * This function does not modify the expire time of the existing key.
73 * The program is aborted if the key was not already present. */
74 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
75 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
77 redisAssertWithInfo(NULL
,key
,de
!= NULL
);
78 dictReplace(db
->dict
, key
->ptr
, val
);
81 /* High level Set operation. This function can be used in order to set
82 * a key, whatever it was existing or not, to a new object.
84 * 1) The ref count of the value object is incremented.
85 * 2) clients WATCHing for the destination key notified.
86 * 3) The expire time of the key is reset (the key is made persistent). */
87 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
88 if (lookupKeyWrite(db
,key
) == NULL
) {
91 dbOverwrite(db
,key
,val
);
95 signalModifiedKey(db
,key
);
98 int dbExists(redisDb
*db
, robj
*key
) {
99 return dictFind(db
->dict
,key
->ptr
) != NULL
;
102 /* Return a random key, in form of a Redis object.
103 * If there are no keys, NULL is returned.
105 * The function makes sure to return keys not already expired. */
106 robj
*dbRandomKey(redisDb
*db
) {
107 struct dictEntry
*de
;
113 de
= dictGetRandomKey(db
->dict
);
114 if (de
== NULL
) return NULL
;
116 key
= dictGetKey(de
);
117 keyobj
= createStringObject(key
,sdslen(key
));
118 if (dictFind(db
->expires
,key
)) {
119 if (expireIfNeeded(db
,keyobj
)) {
120 decrRefCount(keyobj
);
121 continue; /* search for another key. This expired. */
128 /* Delete a key, value, and associated expiration entry if any, from the DB */
129 int dbDelete(redisDb
*db
, robj
*key
) {
130 /* Deleting an entry from the expires dict will not free the sds of
131 * the key, because it is shared with the main dictionary. */
132 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
133 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
140 long long emptyDb() {
142 long long removed
= 0;
144 for (j
= 0; j
< server
.dbnum
; j
++) {
145 removed
+= dictSize(server
.db
[j
].dict
);
146 dictEmpty(server
.db
[j
].dict
);
147 dictEmpty(server
.db
[j
].expires
);
152 int selectDb(redisClient
*c
, int id
) {
153 if (id
< 0 || id
>= server
.dbnum
)
155 c
->db
= &server
.db
[id
];
159 /*-----------------------------------------------------------------------------
160 * Hooks for key space changes.
162 * Every time a key in the database is modified the function
163 * signalModifiedKey() is called.
165 * Every time a DB is flushed the function signalFlushDb() is called.
166 *----------------------------------------------------------------------------*/
168 void signalModifiedKey(redisDb
*db
, robj
*key
) {
169 touchWatchedKey(db
,key
);
172 void signalFlushedDb(int dbid
) {
173 touchWatchedKeysOnFlush(dbid
);
176 /*-----------------------------------------------------------------------------
177 * Type agnostic commands operating on the key space
178 *----------------------------------------------------------------------------*/
180 void flushdbCommand(redisClient
*c
) {
181 server
.dirty
+= dictSize(c
->db
->dict
);
182 signalFlushedDb(c
->db
->id
);
183 dictEmpty(c
->db
->dict
);
184 dictEmpty(c
->db
->expires
);
185 addReply(c
,shared
.ok
);
188 void flushallCommand(redisClient
*c
) {
190 server
.dirty
+= emptyDb();
191 addReply(c
,shared
.ok
);
192 if (server
.rdb_child_pid
!= -1) {
193 kill(server
.rdb_child_pid
,SIGKILL
);
194 rdbRemoveTempFile(server
.rdb_child_pid
);
196 if (server
.saveparamslen
> 0) {
197 /* Normally rdbSave() will reset dirty, but we don't want this here
198 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
199 int saved_dirty
= server
.dirty
;
200 rdbSave(server
.rdb_filename
);
201 server
.dirty
= saved_dirty
;
206 void delCommand(redisClient
*c
) {
209 for (j
= 1; j
< c
->argc
; j
++) {
210 if (dbDelete(c
->db
,c
->argv
[j
])) {
211 signalModifiedKey(c
->db
,c
->argv
[j
]);
216 addReplyLongLong(c
,deleted
);
219 void existsCommand(redisClient
*c
) {
220 expireIfNeeded(c
->db
,c
->argv
[1]);
221 if (dbExists(c
->db
,c
->argv
[1])) {
222 addReply(c
, shared
.cone
);
224 addReply(c
, shared
.czero
);
228 void selectCommand(redisClient
*c
) {
231 if (getLongFromObjectOrReply(c
, c
->argv
[1], &id
,
232 "invalid DB index") != REDIS_OK
)
235 if (selectDb(c
,id
) == REDIS_ERR
) {
236 addReplyError(c
,"invalid DB index");
238 addReply(c
,shared
.ok
);
242 void randomkeyCommand(redisClient
*c
) {
245 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
246 addReply(c
,shared
.nullbulk
);
254 void keysCommand(redisClient
*c
) {
257 sds pattern
= c
->argv
[1]->ptr
;
258 int plen
= sdslen(pattern
), allkeys
;
259 unsigned long numkeys
= 0;
260 void *replylen
= addDeferredMultiBulkLength(c
);
262 di
= dictGetSafeIterator(c
->db
->dict
);
263 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
264 while((de
= dictNext(di
)) != NULL
) {
265 sds key
= dictGetKey(de
);
268 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
269 keyobj
= createStringObject(key
,sdslen(key
));
270 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
271 addReplyBulk(c
,keyobj
);
274 decrRefCount(keyobj
);
277 dictReleaseIterator(di
);
278 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
281 void dbsizeCommand(redisClient
*c
) {
282 addReplyLongLong(c
,dictSize(c
->db
->dict
));
285 void lastsaveCommand(redisClient
*c
) {
286 addReplyLongLong(c
,server
.lastsave
);
289 void typeCommand(redisClient
*c
) {
293 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
298 case REDIS_STRING
: type
= "string"; break;
299 case REDIS_LIST
: type
= "list"; break;
300 case REDIS_SET
: type
= "set"; break;
301 case REDIS_ZSET
: type
= "zset"; break;
302 case REDIS_HASH
: type
= "hash"; break;
303 default: type
= "unknown"; break;
306 addReplyStatus(c
,type
);
309 void shutdownCommand(redisClient
*c
) {
313 addReply(c
,shared
.syntaxerr
);
315 } else if (c
->argc
== 2) {
316 if (!strcasecmp(c
->argv
[1]->ptr
,"nosave")) {
317 flags
|= REDIS_SHUTDOWN_NOSAVE
;
318 } else if (!strcasecmp(c
->argv
[1]->ptr
,"save")) {
319 flags
|= REDIS_SHUTDOWN_SAVE
;
321 addReply(c
,shared
.syntaxerr
);
325 if (prepareForShutdown(flags
) == REDIS_OK
) exit(0);
326 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
329 void renameGenericCommand(redisClient
*c
, int nx
) {
333 /* To use the same key as src and dst is probably an error */
334 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
335 addReply(c
,shared
.sameobjecterr
);
339 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
343 expire
= getExpire(c
->db
,c
->argv
[1]);
344 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
347 addReply(c
,shared
.czero
);
350 /* Overwrite: delete the old key before creating the new one with the same name. */
351 dbDelete(c
->db
,c
->argv
[2]);
353 dbAdd(c
->db
,c
->argv
[2],o
);
354 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
355 dbDelete(c
->db
,c
->argv
[1]);
356 signalModifiedKey(c
->db
,c
->argv
[1]);
357 signalModifiedKey(c
->db
,c
->argv
[2]);
359 addReply(c
,nx
? shared
.cone
: shared
.ok
);
362 void renameCommand(redisClient
*c
) {
363 renameGenericCommand(c
,0);
366 void renamenxCommand(redisClient
*c
) {
367 renameGenericCommand(c
,1);
370 void moveCommand(redisClient
*c
) {
375 /* Obtain source and target DB pointers */
378 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
379 addReply(c
,shared
.outofrangeerr
);
383 selectDb(c
,srcid
); /* Back to the source DB */
385 /* If the user is moving using as target the same
386 * DB as the source DB it is probably an error. */
388 addReply(c
,shared
.sameobjecterr
);
392 /* Check if the element exists and get a reference */
393 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
395 addReply(c
,shared
.czero
);
399 /* Return zero if the key already exists in the target DB */
400 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
401 addReply(c
,shared
.czero
);
404 dbAdd(dst
,c
->argv
[1],o
);
407 /* OK! key moved, free the entry in the source DB */
408 dbDelete(src
,c
->argv
[1]);
410 addReply(c
,shared
.cone
);
413 /*-----------------------------------------------------------------------------
415 *----------------------------------------------------------------------------*/
417 int removeExpire(redisDb
*db
, robj
*key
) {
418 /* An expire may only be removed if there is a corresponding entry in the
419 * main dict. Otherwise, the key will never be freed. */
420 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
421 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
424 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
427 /* Reuse the sds from the main dict in the expire dict */
428 kde
= dictFind(db
->dict
,key
->ptr
);
429 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
430 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
431 dictSetSignedIntegerVal(de
,when
);
434 /* Return the expire time of the specified key, or -1 if no expire
435 * is associated with this key (i.e. the key is non volatile) */
436 long long getExpire(redisDb
*db
, robj
*key
) {
439 /* No expire? return ASAP */
440 if (dictSize(db
->expires
) == 0 ||
441 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
443 /* The entry was found in the expire dict, this means it should also
444 * be present in the main dict (safety check). */
445 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
446 return dictGetSignedIntegerVal(de
);
449 /* Propagate expires into slaves and the AOF file.
450 * When a key expires in the master, a DEL operation for this key is sent
451 * to all the slaves and the AOF file if enabled.
453 * This way the key expiry is centralized in one place, and since both
454 * AOF and the master->slave link guarantee operation ordering, everything
455 * will be consistent even if we allow write operations against expiring
457 void propagateExpire(redisDb
*db
, robj
*key
) {
460 argv
[0] = shared
.del
;
462 incrRefCount(argv
[0]);
463 incrRefCount(argv
[1]);
465 if (server
.aof_state
!= REDIS_AOF_OFF
)
466 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
467 if (listLength(server
.slaves
))
468 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
470 decrRefCount(argv
[0]);
471 decrRefCount(argv
[1]);
474 int expireIfNeeded(redisDb
*db
, robj
*key
) {
475 long long when
= getExpire(db
,key
);
477 if (when
< 0) return 0; /* No expire for this key */
479 /* Don't expire anything while loading. It will be done later. */
480 if (server
.loading
) return 0;
482 /* If we are running in the context of a slave, return ASAP:
483 * the slave key expiration is controlled by the master that will
484 * send us synthesized DEL operations for expired keys.
486 * Still we try to return the right information to the caller,
487 * that is, 0 if we think the key should be still valid, 1 if
488 * we think the key is expired at this time. */
489 if (server
.masterhost
!= NULL
) {
490 return mstime() > when
;
493 /* Return when this key has not expired */
494 if (mstime() <= when
) return 0;
497 server
.stat_expiredkeys
++;
498 propagateExpire(db
,key
);
499 return dbDelete(db
,key
);
502 /*-----------------------------------------------------------------------------
504 *----------------------------------------------------------------------------*/
506 /* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
507 * and PEXPIREAT. Because the commad second argument may be relative or absolute
508 * the "basetime" argument is used to signal what the base time is (either 0
509 * for *AT variants of the command, or the current time for relative expires).
511 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
512 * the argv[2] parameter. The basetime is always specified in milliesconds. */
513 void expireGenericCommand(redisClient
*c
, long long basetime
, int unit
) {
515 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
516 long long when
; /* unix time in milliseconds when the key will expire. */
518 if (getLongLongFromObjectOrReply(c
, param
, &when
, NULL
) != REDIS_OK
)
521 if (unit
== UNIT_SECONDS
) when
*= 1000;
524 de
= dictFind(c
->db
->dict
,key
->ptr
);
526 addReply(c
,shared
.czero
);
529 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
530 * should never be executed as a DEL when load the AOF or in the context
531 * of a slave instance.
533 * Instead we take the other branch of the IF statement setting an expire
534 * (possibly in the past) and wait for an explicit DEL from the master. */
535 if (when
<= mstime() && !server
.loading
&& !server
.masterhost
) {
538 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
541 /* Replicate/AOF this as an explicit DEL. */
542 aux
= createStringObject("DEL",3);
543 rewriteClientCommandVector(c
,2,aux
,key
);
545 signalModifiedKey(c
->db
,key
);
546 addReply(c
, shared
.cone
);
549 setExpire(c
->db
,key
,when
);
550 addReply(c
,shared
.cone
);
551 signalModifiedKey(c
->db
,key
);
557 void expireCommand(redisClient
*c
) {
558 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
561 void expireatCommand(redisClient
*c
) {
562 expireGenericCommand(c
,0,UNIT_SECONDS
);
565 void pexpireCommand(redisClient
*c
) {
566 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
569 void pexpireatCommand(redisClient
*c
) {
570 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
573 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
574 long long expire
, ttl
= -1;
576 expire
= getExpire(c
->db
,c
->argv
[1]);
578 ttl
= expire
-mstime();
579 if (ttl
< 0) ttl
= -1;
582 addReplyLongLong(c
,-1);
584 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
588 void ttlCommand(redisClient
*c
) {
589 ttlGenericCommand(c
, 0);
592 void pttlCommand(redisClient
*c
) {
593 ttlGenericCommand(c
, 1);
596 void persistCommand(redisClient
*c
) {
599 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
601 addReply(c
,shared
.czero
);
603 if (removeExpire(c
->db
,c
->argv
[1])) {
604 addReply(c
,shared
.cone
);
607 addReply(c
,shared
.czero
);
612 /* -----------------------------------------------------------------------------
613 * API to get key arguments from commands
614 * ---------------------------------------------------------------------------*/
616 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
617 int j
, i
= 0, last
, *keys
;
620 if (cmd
->firstkey
== 0) {
625 if (last
< 0) last
= argc
+last
;
626 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
627 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
628 redisAssert(j
< argc
);
635 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
636 if (cmd
->getkeys_proc
) {
637 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
639 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
643 void getKeysFreeResult(int *result
) {
647 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
648 if (flags
& REDIS_GETKEYS_PRELOAD
) {
652 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
656 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
657 if (flags
& REDIS_GETKEYS_PRELOAD
) {
658 int *keys
= zmalloc(sizeof(int));
663 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
667 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
670 REDIS_NOTUSED(flags
);
672 num
= atoi(argv
[2]->ptr
);
673 /* Sanity check. Don't return any key if the command is going to
674 * reply with syntax error. */
675 if (num
> (argc
-3)) {
679 keys
= zmalloc(sizeof(int)*num
);
680 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;