]>
git.saurik.com Git - redis.git/blob - src/db.c
2 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
35 void SlotToKeyAdd(robj
*key
);
36 void SlotToKeyDel(robj
*key
);
38 /*-----------------------------------------------------------------------------
40 *----------------------------------------------------------------------------*/
42 robj
*lookupKey(redisDb
*db
, robj
*key
) {
43 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
45 robj
*val
= dictGetVal(de
);
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. */
50 if (server
.rdb_child_pid
== -1 && server
.aof_child_pid
== -1)
51 val
->lru
= server
.lruclock
;
58 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
61 expireIfNeeded(db
,key
);
62 val
= lookupKey(db
,key
);
64 server
.stat_keyspace_misses
++;
66 server
.stat_keyspace_hits
++;
70 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
71 expireIfNeeded(db
,key
);
72 return lookupKey(db
,key
);
75 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
76 robj
*o
= lookupKeyRead(c
->db
, key
);
77 if (!o
) addReply(c
,reply
);
81 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
82 robj
*o
= lookupKeyWrite(c
->db
, key
);
83 if (!o
) addReply(c
,reply
);
87 /* Add the key to the DB. It's up to the caller to increment the reference
88 * counte of the value if needed.
90 * The program is aborted if the key already exists. */
91 void dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
92 sds copy
= sdsdup(key
->ptr
);
93 int retval
= dictAdd(db
->dict
, copy
, val
);
95 redisAssertWithInfo(NULL
,key
,retval
== REDIS_OK
);
98 /* Overwrite an existing key with a new value. Incrementing the reference
99 * count of the new value is up to the caller.
100 * This function does not modify the expire time of the existing key.
102 * The program is aborted if the key was not already present. */
103 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
104 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
106 redisAssertWithInfo(NULL
,key
,de
!= NULL
);
107 dictReplace(db
->dict
, key
->ptr
, val
);
110 /* High level Set operation. This function can be used in order to set
111 * a key, whatever it was existing or not, to a new object.
113 * 1) The ref count of the value object is incremented.
114 * 2) clients WATCHing for the destination key notified.
115 * 3) The expire time of the key is reset (the key is made persistent). */
116 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
117 if (lookupKeyWrite(db
,key
) == NULL
) {
120 dbOverwrite(db
,key
,val
);
123 removeExpire(db
,key
);
124 signalModifiedKey(db
,key
);
127 int dbExists(redisDb
*db
, robj
*key
) {
128 return dictFind(db
->dict
,key
->ptr
) != NULL
;
131 /* Return a random key, in form of a Redis object.
132 * If there are no keys, NULL is returned.
134 * The function makes sure to return keys not already expired. */
135 robj
*dbRandomKey(redisDb
*db
) {
136 struct dictEntry
*de
;
142 de
= dictGetRandomKey(db
->dict
);
143 if (de
== NULL
) return NULL
;
145 key
= dictGetKey(de
);
146 keyobj
= createStringObject(key
,sdslen(key
));
147 if (dictFind(db
->expires
,key
)) {
148 if (expireIfNeeded(db
,keyobj
)) {
149 decrRefCount(keyobj
);
150 continue; /* search for another key. This expired. */
157 /* Delete a key, value, and associated expiration entry if any, from the DB */
158 int dbDelete(redisDb
*db
, robj
*key
) {
159 /* Deleting an entry from the expires dict will not free the sds of
160 * the key, because it is shared with the main dictionary. */
161 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
162 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
169 long long emptyDb() {
171 long long removed
= 0;
173 for (j
= 0; j
< server
.dbnum
; j
++) {
174 removed
+= dictSize(server
.db
[j
].dict
);
175 dictEmpty(server
.db
[j
].dict
);
176 dictEmpty(server
.db
[j
].expires
);
181 int selectDb(redisClient
*c
, int id
) {
182 if (id
< 0 || id
>= server
.dbnum
)
184 c
->db
= &server
.db
[id
];
188 /*-----------------------------------------------------------------------------
189 * Hooks for key space changes.
191 * Every time a key in the database is modified the function
192 * signalModifiedKey() is called.
194 * Every time a DB is flushed the function signalFlushDb() is called.
195 *----------------------------------------------------------------------------*/
197 void signalModifiedKey(redisDb
*db
, robj
*key
) {
198 touchWatchedKey(db
,key
);
201 void signalFlushedDb(int dbid
) {
202 touchWatchedKeysOnFlush(dbid
);
205 /*-----------------------------------------------------------------------------
206 * Type agnostic commands operating on the key space
207 *----------------------------------------------------------------------------*/
209 void flushdbCommand(redisClient
*c
) {
210 server
.dirty
+= dictSize(c
->db
->dict
);
211 signalFlushedDb(c
->db
->id
);
212 dictEmpty(c
->db
->dict
);
213 dictEmpty(c
->db
->expires
);
214 addReply(c
,shared
.ok
);
217 void flushallCommand(redisClient
*c
) {
219 server
.dirty
+= emptyDb();
220 addReply(c
,shared
.ok
);
221 if (server
.rdb_child_pid
!= -1) {
222 kill(server
.rdb_child_pid
,SIGKILL
);
223 rdbRemoveTempFile(server
.rdb_child_pid
);
225 if (server
.saveparamslen
> 0) {
226 /* Normally rdbSave() will reset dirty, but we don't want this here
227 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
228 int saved_dirty
= server
.dirty
;
229 rdbSave(server
.rdb_filename
);
230 server
.dirty
= saved_dirty
;
235 void delCommand(redisClient
*c
) {
238 for (j
= 1; j
< c
->argc
; j
++) {
239 if (dbDelete(c
->db
,c
->argv
[j
])) {
240 signalModifiedKey(c
->db
,c
->argv
[j
]);
245 addReplyLongLong(c
,deleted
);
248 void existsCommand(redisClient
*c
) {
249 expireIfNeeded(c
->db
,c
->argv
[1]);
250 if (dbExists(c
->db
,c
->argv
[1])) {
251 addReply(c
, shared
.cone
);
253 addReply(c
, shared
.czero
);
257 void selectCommand(redisClient
*c
) {
260 if (getLongFromObjectOrReply(c
, c
->argv
[1], &id
,
261 "invalid DB index") != REDIS_OK
)
264 if (selectDb(c
,id
) == REDIS_ERR
) {
265 addReplyError(c
,"invalid DB index");
267 addReply(c
,shared
.ok
);
271 void randomkeyCommand(redisClient
*c
) {
274 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
275 addReply(c
,shared
.nullbulk
);
283 void keysCommand(redisClient
*c
) {
286 sds pattern
= c
->argv
[1]->ptr
;
287 int plen
= sdslen(pattern
), allkeys
;
288 unsigned long numkeys
= 0;
289 void *replylen
= addDeferredMultiBulkLength(c
);
291 di
= dictGetSafeIterator(c
->db
->dict
);
292 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
293 while((de
= dictNext(di
)) != NULL
) {
294 sds key
= dictGetKey(de
);
297 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
298 keyobj
= createStringObject(key
,sdslen(key
));
299 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
300 addReplyBulk(c
,keyobj
);
303 decrRefCount(keyobj
);
306 dictReleaseIterator(di
);
307 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
310 void dbsizeCommand(redisClient
*c
) {
311 addReplyLongLong(c
,dictSize(c
->db
->dict
));
314 void lastsaveCommand(redisClient
*c
) {
315 addReplyLongLong(c
,server
.lastsave
);
318 void typeCommand(redisClient
*c
) {
322 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
327 case REDIS_STRING
: type
= "string"; break;
328 case REDIS_LIST
: type
= "list"; break;
329 case REDIS_SET
: type
= "set"; break;
330 case REDIS_ZSET
: type
= "zset"; break;
331 case REDIS_HASH
: type
= "hash"; break;
332 default: type
= "unknown"; break;
335 addReplyStatus(c
,type
);
338 void shutdownCommand(redisClient
*c
) {
342 addReply(c
,shared
.syntaxerr
);
344 } else if (c
->argc
== 2) {
345 if (!strcasecmp(c
->argv
[1]->ptr
,"nosave")) {
346 flags
|= REDIS_SHUTDOWN_NOSAVE
;
347 } else if (!strcasecmp(c
->argv
[1]->ptr
,"save")) {
348 flags
|= REDIS_SHUTDOWN_SAVE
;
350 addReply(c
,shared
.syntaxerr
);
354 if (prepareForShutdown(flags
) == REDIS_OK
) exit(0);
355 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
358 void renameGenericCommand(redisClient
*c
, int nx
) {
362 /* To use the same key as src and dst is probably an error */
363 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
364 addReply(c
,shared
.sameobjecterr
);
368 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
372 expire
= getExpire(c
->db
,c
->argv
[1]);
373 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
376 addReply(c
,shared
.czero
);
379 /* Overwrite: delete the old key before creating the new one with the same name. */
380 dbDelete(c
->db
,c
->argv
[2]);
382 dbAdd(c
->db
,c
->argv
[2],o
);
383 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
384 dbDelete(c
->db
,c
->argv
[1]);
385 signalModifiedKey(c
->db
,c
->argv
[1]);
386 signalModifiedKey(c
->db
,c
->argv
[2]);
388 addReply(c
,nx
? shared
.cone
: shared
.ok
);
391 void renameCommand(redisClient
*c
) {
392 renameGenericCommand(c
,0);
395 void renamenxCommand(redisClient
*c
) {
396 renameGenericCommand(c
,1);
399 void moveCommand(redisClient
*c
) {
404 /* Obtain source and target DB pointers */
407 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
408 addReply(c
,shared
.outofrangeerr
);
412 selectDb(c
,srcid
); /* Back to the source DB */
414 /* If the user is moving using as target the same
415 * DB as the source DB it is probably an error. */
417 addReply(c
,shared
.sameobjecterr
);
421 /* Check if the element exists and get a reference */
422 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
424 addReply(c
,shared
.czero
);
428 /* Return zero if the key already exists in the target DB */
429 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
430 addReply(c
,shared
.czero
);
433 dbAdd(dst
,c
->argv
[1],o
);
436 /* OK! key moved, free the entry in the source DB */
437 dbDelete(src
,c
->argv
[1]);
439 addReply(c
,shared
.cone
);
442 /*-----------------------------------------------------------------------------
444 *----------------------------------------------------------------------------*/
446 int removeExpire(redisDb
*db
, robj
*key
) {
447 /* An expire may only be removed if there is a corresponding entry in the
448 * main dict. Otherwise, the key will never be freed. */
449 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
450 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
453 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
456 /* Reuse the sds from the main dict in the expire dict */
457 kde
= dictFind(db
->dict
,key
->ptr
);
458 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
459 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
460 dictSetSignedIntegerVal(de
,when
);
463 /* Return the expire time of the specified key, or -1 if no expire
464 * is associated with this key (i.e. the key is non volatile) */
465 long long getExpire(redisDb
*db
, robj
*key
) {
468 /* No expire? return ASAP */
469 if (dictSize(db
->expires
) == 0 ||
470 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
472 /* The entry was found in the expire dict, this means it should also
473 * be present in the main dict (safety check). */
474 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
475 return dictGetSignedIntegerVal(de
);
478 /* Propagate expires into slaves and the AOF file.
479 * When a key expires in the master, a DEL operation for this key is sent
480 * to all the slaves and the AOF file if enabled.
482 * This way the key expiry is centralized in one place, and since both
483 * AOF and the master->slave link guarantee operation ordering, everything
484 * will be consistent even if we allow write operations against expiring
486 void propagateExpire(redisDb
*db
, robj
*key
) {
489 argv
[0] = shared
.del
;
491 incrRefCount(argv
[0]);
492 incrRefCount(argv
[1]);
494 if (server
.aof_state
!= REDIS_AOF_OFF
)
495 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
496 if (listLength(server
.slaves
))
497 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
499 decrRefCount(argv
[0]);
500 decrRefCount(argv
[1]);
503 int expireIfNeeded(redisDb
*db
, robj
*key
) {
504 long long when
= getExpire(db
,key
);
506 if (when
< 0) return 0; /* No expire for this key */
508 /* Don't expire anything while loading. It will be done later. */
509 if (server
.loading
) return 0;
511 /* If we are running in the context of a slave, return ASAP:
512 * the slave key expiration is controlled by the master that will
513 * send us synthesized DEL operations for expired keys.
515 * Still we try to return the right information to the caller,
516 * that is, 0 if we think the key should be still valid, 1 if
517 * we think the key is expired at this time. */
518 if (server
.masterhost
!= NULL
) {
519 return mstime() > when
;
522 /* Return when this key has not expired */
523 if (mstime() <= when
) return 0;
526 server
.stat_expiredkeys
++;
527 propagateExpire(db
,key
);
528 return dbDelete(db
,key
);
531 /*-----------------------------------------------------------------------------
533 *----------------------------------------------------------------------------*/
535 /* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
536 * and PEXPIREAT. Because the commad second argument may be relative or absolute
537 * the "basetime" argument is used to signal what the base time is (either 0
538 * for *AT variants of the command, or the current time for relative expires).
540 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
541 * the argv[2] parameter. The basetime is always specified in milliesconds. */
542 void expireGenericCommand(redisClient
*c
, long long basetime
, int unit
) {
544 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
545 long long when
; /* unix time in milliseconds when the key will expire. */
547 if (getLongLongFromObjectOrReply(c
, param
, &when
, NULL
) != REDIS_OK
)
550 if (unit
== UNIT_SECONDS
) when
*= 1000;
553 de
= dictFind(c
->db
->dict
,key
->ptr
);
555 addReply(c
,shared
.czero
);
558 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
559 * should never be executed as a DEL when load the AOF or in the context
560 * of a slave instance.
562 * Instead we take the other branch of the IF statement setting an expire
563 * (possibly in the past) and wait for an explicit DEL from the master. */
564 if (when
<= mstime() && !server
.loading
&& !server
.masterhost
) {
567 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
570 /* Replicate/AOF this as an explicit DEL. */
571 aux
= createStringObject("DEL",3);
572 rewriteClientCommandVector(c
,2,aux
,key
);
574 signalModifiedKey(c
->db
,key
);
575 addReply(c
, shared
.cone
);
578 setExpire(c
->db
,key
,when
);
579 addReply(c
,shared
.cone
);
580 signalModifiedKey(c
->db
,key
);
586 void expireCommand(redisClient
*c
) {
587 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
590 void expireatCommand(redisClient
*c
) {
591 expireGenericCommand(c
,0,UNIT_SECONDS
);
594 void pexpireCommand(redisClient
*c
) {
595 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
598 void pexpireatCommand(redisClient
*c
) {
599 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
602 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
603 long long expire
, ttl
= -1;
605 expire
= getExpire(c
->db
,c
->argv
[1]);
607 ttl
= expire
-mstime();
608 if (ttl
< 0) ttl
= -1;
611 addReplyLongLong(c
,-1);
613 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
617 void ttlCommand(redisClient
*c
) {
618 ttlGenericCommand(c
, 0);
621 void pttlCommand(redisClient
*c
) {
622 ttlGenericCommand(c
, 1);
625 void persistCommand(redisClient
*c
) {
628 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
630 addReply(c
,shared
.czero
);
632 if (removeExpire(c
->db
,c
->argv
[1])) {
633 addReply(c
,shared
.cone
);
636 addReply(c
,shared
.czero
);
641 /* -----------------------------------------------------------------------------
642 * API to get key arguments from commands
643 * ---------------------------------------------------------------------------*/
645 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
646 int j
, i
= 0, last
, *keys
;
649 if (cmd
->firstkey
== 0) {
654 if (last
< 0) last
= argc
+last
;
655 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
656 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
657 redisAssert(j
< argc
);
664 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
665 if (cmd
->getkeys_proc
) {
666 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
668 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
672 void getKeysFreeResult(int *result
) {
676 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
677 if (flags
& REDIS_GETKEYS_PRELOAD
) {
681 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
685 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
686 if (flags
& REDIS_GETKEYS_PRELOAD
) {
687 int *keys
= zmalloc(sizeof(int));
692 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
696 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
699 REDIS_NOTUSED(flags
);
701 num
= atoi(argv
[2]->ptr
);
702 /* Sanity check. Don't return any key if the command is going to
703 * reply with syntax error. */
704 if (num
> (argc
-3)) {
708 keys
= zmalloc(sizeof(int)*num
);
709 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;