]>
git.saurik.com Git - redis.git/blob - src/db.c
73ee9166a001bdb3df4fc417012cd290d35a2afc
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
) {
229 int id
= atoi(c
->argv
[1]->ptr
);
231 if (selectDb(c
,id
) == REDIS_ERR
) {
232 addReplyError(c
,"invalid DB index");
234 addReply(c
,shared
.ok
);
238 void randomkeyCommand(redisClient
*c
) {
241 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
242 addReply(c
,shared
.nullbulk
);
250 void keysCommand(redisClient
*c
) {
253 sds pattern
= c
->argv
[1]->ptr
;
254 int plen
= sdslen(pattern
), allkeys
;
255 unsigned long numkeys
= 0;
256 void *replylen
= addDeferredMultiBulkLength(c
);
258 di
= dictGetIterator(c
->db
->dict
);
259 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
260 while((de
= dictNext(di
)) != NULL
) {
261 sds key
= dictGetKey(de
);
264 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
265 keyobj
= createStringObject(key
,sdslen(key
));
266 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
267 addReplyBulk(c
,keyobj
);
270 decrRefCount(keyobj
);
273 dictReleaseIterator(di
);
274 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
277 void dbsizeCommand(redisClient
*c
) {
278 addReplyLongLong(c
,dictSize(c
->db
->dict
));
281 void lastsaveCommand(redisClient
*c
) {
282 addReplyLongLong(c
,server
.lastsave
);
285 void typeCommand(redisClient
*c
) {
289 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
294 case REDIS_STRING
: type
= "string"; break;
295 case REDIS_LIST
: type
= "list"; break;
296 case REDIS_SET
: type
= "set"; break;
297 case REDIS_ZSET
: type
= "zset"; break;
298 case REDIS_HASH
: type
= "hash"; break;
299 default: type
= "unknown"; break;
302 addReplyStatus(c
,type
);
305 void shutdownCommand(redisClient
*c
) {
309 addReply(c
,shared
.syntaxerr
);
311 } else if (c
->argc
== 2) {
312 if (!strcasecmp(c
->argv
[1]->ptr
,"nosave")) {
313 flags
|= REDIS_SHUTDOWN_NOSAVE
;
314 } else if (!strcasecmp(c
->argv
[1]->ptr
,"save")) {
315 flags
|= REDIS_SHUTDOWN_SAVE
;
317 addReply(c
,shared
.syntaxerr
);
321 if (prepareForShutdown(flags
) == REDIS_OK
) exit(0);
322 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
325 void renameGenericCommand(redisClient
*c
, int nx
) {
329 /* To use the same key as src and dst is probably an error */
330 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
331 addReply(c
,shared
.sameobjecterr
);
335 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
339 expire
= getExpire(c
->db
,c
->argv
[1]);
340 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
343 addReply(c
,shared
.czero
);
346 /* Overwrite: delete the old key before creating the new one with the same name. */
347 dbDelete(c
->db
,c
->argv
[2]);
349 dbAdd(c
->db
,c
->argv
[2],o
);
350 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
351 dbDelete(c
->db
,c
->argv
[1]);
352 signalModifiedKey(c
->db
,c
->argv
[1]);
353 signalModifiedKey(c
->db
,c
->argv
[2]);
355 addReply(c
,nx
? shared
.cone
: shared
.ok
);
358 void renameCommand(redisClient
*c
) {
359 renameGenericCommand(c
,0);
362 void renamenxCommand(redisClient
*c
) {
363 renameGenericCommand(c
,1);
366 void moveCommand(redisClient
*c
) {
371 /* Obtain source and target DB pointers */
374 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
375 addReply(c
,shared
.outofrangeerr
);
379 selectDb(c
,srcid
); /* Back to the source DB */
381 /* If the user is moving using as target the same
382 * DB as the source DB it is probably an error. */
384 addReply(c
,shared
.sameobjecterr
);
388 /* Check if the element exists and get a reference */
389 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
391 addReply(c
,shared
.czero
);
395 /* Return zero if the key already exists in the target DB */
396 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
397 addReply(c
,shared
.czero
);
400 dbAdd(dst
,c
->argv
[1],o
);
403 /* OK! key moved, free the entry in the source DB */
404 dbDelete(src
,c
->argv
[1]);
406 addReply(c
,shared
.cone
);
409 /*-----------------------------------------------------------------------------
411 *----------------------------------------------------------------------------*/
413 int removeExpire(redisDb
*db
, robj
*key
) {
414 /* An expire may only be removed if there is a corresponding entry in the
415 * main dict. Otherwise, the key will never be freed. */
416 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
417 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
420 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
423 /* Reuse the sds from the main dict in the expire dict */
424 kde
= dictFind(db
->dict
,key
->ptr
);
425 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
426 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
427 dictSetSignedIntegerVal(de
,when
);
430 /* Return the expire time of the specified key, or -1 if no expire
431 * is associated with this key (i.e. the key is non volatile) */
432 long long getExpire(redisDb
*db
, robj
*key
) {
435 /* No expire? return ASAP */
436 if (dictSize(db
->expires
) == 0 ||
437 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
439 /* The entry was found in the expire dict, this means it should also
440 * be present in the main dict (safety check). */
441 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
442 return dictGetSignedIntegerVal(de
);
445 /* Propagate expires into slaves and the AOF file.
446 * When a key expires in the master, a DEL operation for this key is sent
447 * to all the slaves and the AOF file if enabled.
449 * This way the key expiry is centralized in one place, and since both
450 * AOF and the master->slave link guarantee operation ordering, everything
451 * will be consistent even if we allow write operations against expiring
453 void propagateExpire(redisDb
*db
, robj
*key
) {
456 argv
[0] = shared
.del
;
458 incrRefCount(argv
[0]);
459 incrRefCount(argv
[1]);
461 if (server
.aof_state
!= REDIS_AOF_OFF
)
462 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
463 if (listLength(server
.slaves
))
464 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
466 decrRefCount(argv
[0]);
467 decrRefCount(argv
[1]);
470 int expireIfNeeded(redisDb
*db
, robj
*key
) {
471 long long when
= getExpire(db
,key
);
473 if (when
< 0) return 0; /* No expire for this key */
475 /* Don't expire anything while loading. It will be done later. */
476 if (server
.loading
) return 0;
478 /* If we are running in the context of a slave, return ASAP:
479 * the slave key expiration is controlled by the master that will
480 * send us synthesized DEL operations for expired keys.
482 * Still we try to return the right information to the caller,
483 * that is, 0 if we think the key should be still valid, 1 if
484 * we think the key is expired at this time. */
485 if (server
.masterhost
!= NULL
) {
486 return mstime() > when
;
489 /* Return when this key has not expired */
490 if (mstime() <= when
) return 0;
493 server
.stat_expiredkeys
++;
494 propagateExpire(db
,key
);
495 return dbDelete(db
,key
);
498 /*-----------------------------------------------------------------------------
500 *----------------------------------------------------------------------------*/
502 /* Given an string object return true if it contains exactly the "ms"
503 * or "MS" string. This is used in order to check if the last argument
504 * of EXPIRE, EXPIREAT or TTL is "ms" to switch into millisecond input/output */
505 int stringObjectEqualsMs(robj
*a
) {
507 return tolower(arg
[0]) == 'm' && tolower(arg
[1]) == 's' && arg
[2] == '\0';
510 void expireGenericCommand(redisClient
*c
, long long offset
, int unit
) {
512 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
513 long long milliseconds
;
515 if (getLongLongFromObjectOrReply(c
, param
, &milliseconds
, NULL
) != REDIS_OK
)
518 if (unit
== UNIT_SECONDS
) milliseconds
*= 1000;
519 milliseconds
-= offset
;
521 de
= dictFind(c
->db
->dict
,key
->ptr
);
523 addReply(c
,shared
.czero
);
526 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
527 * should never be executed as a DEL when load the AOF or in the context
528 * of a slave instance.
530 * Instead we take the other branch of the IF statement setting an expire
531 * (possibly in the past) and wait for an explicit DEL from the master. */
532 if (milliseconds
<= 0 && !server
.loading
&& !server
.masterhost
) {
535 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
538 /* Replicate/AOF this as an explicit DEL. */
539 aux
= createStringObject("DEL",3);
540 rewriteClientCommandVector(c
,2,aux
,key
);
542 signalModifiedKey(c
->db
,key
);
543 addReply(c
, shared
.cone
);
546 long long when
= mstime()+milliseconds
;
547 setExpire(c
->db
,key
,when
);
548 addReply(c
,shared
.cone
);
549 signalModifiedKey(c
->db
,key
);
555 void expireCommand(redisClient
*c
) {
556 expireGenericCommand(c
,0,UNIT_SECONDS
);
559 void expireatCommand(redisClient
*c
) {
560 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
563 void pexpireCommand(redisClient
*c
) {
564 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
567 void pexpireatCommand(redisClient
*c
) {
568 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
571 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
572 long long expire
, ttl
= -1;
574 expire
= getExpire(c
->db
,c
->argv
[1]);
576 ttl
= expire
-mstime();
577 if (ttl
< 0) ttl
= -1;
580 addReplyLongLong(c
,-1);
582 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
586 void ttlCommand(redisClient
*c
) {
587 ttlGenericCommand(c
, 0);
590 void pttlCommand(redisClient
*c
) {
591 ttlGenericCommand(c
, 1);
594 void persistCommand(redisClient
*c
) {
597 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
599 addReply(c
,shared
.czero
);
601 if (removeExpire(c
->db
,c
->argv
[1])) {
602 addReply(c
,shared
.cone
);
605 addReply(c
,shared
.czero
);
610 /* -----------------------------------------------------------------------------
611 * API to get key arguments from commands
612 * ---------------------------------------------------------------------------*/
614 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
615 int j
, i
= 0, last
, *keys
;
618 if (cmd
->firstkey
== 0) {
623 if (last
< 0) last
= argc
+last
;
624 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
625 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
626 redisAssert(j
< argc
);
633 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
634 if (cmd
->getkeys_proc
) {
635 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
637 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
641 void getKeysFreeResult(int *result
) {
645 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
646 if (flags
& REDIS_GETKEYS_PRELOAD
) {
650 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
654 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
655 if (flags
& REDIS_GETKEYS_PRELOAD
) {
656 int *keys
= zmalloc(sizeof(int));
661 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
665 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
668 REDIS_NOTUSED(flags
);
670 num
= atoi(argv
[2]->ptr
);
671 /* Sanity check. Don't return any key if the command is going to
672 * reply with syntax error. */
673 if (num
> (argc
-3)) {
677 keys
= zmalloc(sizeof(int)*num
);
678 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;