]>
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
);
67 if (server
.cluster_enabled
) SlotToKeyAdd(key
);
70 /* Overwrite an existing key with a new value. Incrementing the reference
71 * count of the new value is up to the caller.
72 * This function does not modify the expire time of the existing key.
74 * The program is aborted if the key was not already present. */
75 void dbOverwrite(redisDb
*db
, robj
*key
, robj
*val
) {
76 struct dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
78 redisAssertWithInfo(NULL
,key
,de
!= NULL
);
79 dictReplace(db
->dict
, key
->ptr
, val
);
82 /* High level Set operation. This function can be used in order to set
83 * a key, whatever it was existing or not, to a new object.
85 * 1) The ref count of the value object is incremented.
86 * 2) clients WATCHing for the destination key notified.
87 * 3) The expire time of the key is reset (the key is made persistent). */
88 void setKey(redisDb
*db
, robj
*key
, robj
*val
) {
89 if (lookupKeyWrite(db
,key
) == NULL
) {
92 dbOverwrite(db
,key
,val
);
96 signalModifiedKey(db
,key
);
99 int dbExists(redisDb
*db
, robj
*key
) {
100 return dictFind(db
->dict
,key
->ptr
) != NULL
;
103 /* Return a random key, in form of a Redis object.
104 * If there are no keys, NULL is returned.
106 * The function makes sure to return keys not already expired. */
107 robj
*dbRandomKey(redisDb
*db
) {
108 struct dictEntry
*de
;
114 de
= dictGetRandomKey(db
->dict
);
115 if (de
== NULL
) return NULL
;
117 key
= dictGetKey(de
);
118 keyobj
= createStringObject(key
,sdslen(key
));
119 if (dictFind(db
->expires
,key
)) {
120 if (expireIfNeeded(db
,keyobj
)) {
121 decrRefCount(keyobj
);
122 continue; /* search for another key. This expired. */
129 /* Delete a key, value, and associated expiration entry if any, from the DB */
130 int dbDelete(redisDb
*db
, robj
*key
) {
131 /* Deleting an entry from the expires dict will not free the sds of
132 * the key, because it is shared with the main dictionary. */
133 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
134 if (dictDelete(db
->dict
,key
->ptr
) == DICT_OK
) {
135 if (server
.cluster_enabled
) SlotToKeyDel(key
);
142 long long emptyDb() {
144 long long removed
= 0;
146 for (j
= 0; j
< server
.dbnum
; j
++) {
147 removed
+= dictSize(server
.db
[j
].dict
);
148 dictEmpty(server
.db
[j
].dict
);
149 dictEmpty(server
.db
[j
].expires
);
154 int selectDb(redisClient
*c
, int id
) {
155 if (id
< 0 || id
>= server
.dbnum
)
157 c
->db
= &server
.db
[id
];
161 /*-----------------------------------------------------------------------------
162 * Hooks for key space changes.
164 * Every time a key in the database is modified the function
165 * signalModifiedKey() is called.
167 * Every time a DB is flushed the function signalFlushDb() is called.
168 *----------------------------------------------------------------------------*/
170 void signalModifiedKey(redisDb
*db
, robj
*key
) {
171 touchWatchedKey(db
,key
);
174 void signalFlushedDb(int dbid
) {
175 touchWatchedKeysOnFlush(dbid
);
178 /*-----------------------------------------------------------------------------
179 * Type agnostic commands operating on the key space
180 *----------------------------------------------------------------------------*/
182 void flushdbCommand(redisClient
*c
) {
183 server
.dirty
+= dictSize(c
->db
->dict
);
184 signalFlushedDb(c
->db
->id
);
185 dictEmpty(c
->db
->dict
);
186 dictEmpty(c
->db
->expires
);
187 addReply(c
,shared
.ok
);
190 void flushallCommand(redisClient
*c
) {
192 server
.dirty
+= emptyDb();
193 addReply(c
,shared
.ok
);
194 if (server
.rdb_child_pid
!= -1) {
195 kill(server
.rdb_child_pid
,SIGKILL
);
196 rdbRemoveTempFile(server
.rdb_child_pid
);
198 if (server
.saveparamslen
> 0) {
199 /* Normally rdbSave() will reset dirty, but we don't want this here
200 * as otherwise FLUSHALL will not be replicated nor put into the AOF. */
201 int saved_dirty
= server
.dirty
;
202 rdbSave(server
.rdb_filename
);
203 server
.dirty
= saved_dirty
;
208 void delCommand(redisClient
*c
) {
211 for (j
= 1; j
< c
->argc
; j
++) {
212 if (dbDelete(c
->db
,c
->argv
[j
])) {
213 signalModifiedKey(c
->db
,c
->argv
[j
]);
218 addReplyLongLong(c
,deleted
);
221 void existsCommand(redisClient
*c
) {
222 expireIfNeeded(c
->db
,c
->argv
[1]);
223 if (dbExists(c
->db
,c
->argv
[1])) {
224 addReply(c
, shared
.cone
);
226 addReply(c
, shared
.czero
);
230 void selectCommand(redisClient
*c
) {
231 int id
= atoi(c
->argv
[1]->ptr
);
233 if (server
.cluster_enabled
&& id
!= 0) {
234 addReplyError(c
,"SELECT is not allowed in cluster mode");
237 if (selectDb(c
,id
) == REDIS_ERR
) {
238 addReplyError(c
,"invalid DB index");
240 addReply(c
,shared
.ok
);
244 void randomkeyCommand(redisClient
*c
) {
247 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
248 addReply(c
,shared
.nullbulk
);
256 void keysCommand(redisClient
*c
) {
259 sds pattern
= c
->argv
[1]->ptr
;
260 int plen
= sdslen(pattern
), allkeys
;
261 unsigned long numkeys
= 0;
262 void *replylen
= addDeferredMultiBulkLength(c
);
264 di
= dictGetIterator(c
->db
->dict
);
265 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
266 while((de
= dictNext(di
)) != NULL
) {
267 sds key
= dictGetKey(de
);
270 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
271 keyobj
= createStringObject(key
,sdslen(key
));
272 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
273 addReplyBulk(c
,keyobj
);
276 decrRefCount(keyobj
);
279 dictReleaseIterator(di
);
280 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
283 void dbsizeCommand(redisClient
*c
) {
284 addReplyLongLong(c
,dictSize(c
->db
->dict
));
287 void lastsaveCommand(redisClient
*c
) {
288 addReplyLongLong(c
,server
.lastsave
);
291 void typeCommand(redisClient
*c
) {
295 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
300 case REDIS_STRING
: type
= "string"; break;
301 case REDIS_LIST
: type
= "list"; break;
302 case REDIS_SET
: type
= "set"; break;
303 case REDIS_ZSET
: type
= "zset"; break;
304 case REDIS_HASH
: type
= "hash"; break;
305 default: type
= "unknown"; break;
308 addReplyStatus(c
,type
);
311 void shutdownCommand(redisClient
*c
) {
315 addReply(c
,shared
.syntaxerr
);
317 } else if (c
->argc
== 2) {
318 if (!strcasecmp(c
->argv
[1]->ptr
,"nosave")) {
319 flags
|= REDIS_SHUTDOWN_NOSAVE
;
320 } else if (!strcasecmp(c
->argv
[1]->ptr
,"save")) {
321 flags
|= REDIS_SHUTDOWN_SAVE
;
323 addReply(c
,shared
.syntaxerr
);
327 if (prepareForShutdown(flags
) == REDIS_OK
) exit(0);
328 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
331 void renameGenericCommand(redisClient
*c
, int nx
) {
335 /* To use the same key as src and dst is probably an error */
336 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
337 addReply(c
,shared
.sameobjecterr
);
341 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
345 expire
= getExpire(c
->db
,c
->argv
[1]);
346 if (lookupKeyWrite(c
->db
,c
->argv
[2]) != NULL
) {
349 addReply(c
,shared
.czero
);
352 /* Overwrite: delete the old key before creating the new one with the same name. */
353 dbDelete(c
->db
,c
->argv
[2]);
355 dbAdd(c
->db
,c
->argv
[2],o
);
356 if (expire
!= -1) setExpire(c
->db
,c
->argv
[2],expire
);
357 dbDelete(c
->db
,c
->argv
[1]);
358 signalModifiedKey(c
->db
,c
->argv
[1]);
359 signalModifiedKey(c
->db
,c
->argv
[2]);
361 addReply(c
,nx
? shared
.cone
: shared
.ok
);
364 void renameCommand(redisClient
*c
) {
365 renameGenericCommand(c
,0);
368 void renamenxCommand(redisClient
*c
) {
369 renameGenericCommand(c
,1);
372 void moveCommand(redisClient
*c
) {
377 if (server
.cluster_enabled
) {
378 addReplyError(c
,"MOVE is not allowed in cluster mode");
382 /* Obtain source and target DB pointers */
385 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
386 addReply(c
,shared
.outofrangeerr
);
390 selectDb(c
,srcid
); /* Back to the source DB */
392 /* If the user is moving using as target the same
393 * DB as the source DB it is probably an error. */
395 addReply(c
,shared
.sameobjecterr
);
399 /* Check if the element exists and get a reference */
400 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
402 addReply(c
,shared
.czero
);
406 /* Return zero if the key already exists in the target DB */
407 if (lookupKeyWrite(dst
,c
->argv
[1]) != NULL
) {
408 addReply(c
,shared
.czero
);
411 dbAdd(dst
,c
->argv
[1],o
);
414 /* OK! key moved, free the entry in the source DB */
415 dbDelete(src
,c
->argv
[1]);
417 addReply(c
,shared
.cone
);
420 /*-----------------------------------------------------------------------------
422 *----------------------------------------------------------------------------*/
424 int removeExpire(redisDb
*db
, robj
*key
) {
425 /* An expire may only be removed if there is a corresponding entry in the
426 * main dict. Otherwise, the key will never be freed. */
427 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
428 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
431 void setExpire(redisDb
*db
, robj
*key
, long long when
) {
434 /* Reuse the sds from the main dict in the expire dict */
435 kde
= dictFind(db
->dict
,key
->ptr
);
436 redisAssertWithInfo(NULL
,key
,kde
!= NULL
);
437 de
= dictReplaceRaw(db
->expires
,dictGetKey(kde
));
438 dictSetSignedIntegerVal(de
,when
);
441 /* Return the expire time of the specified key, or -1 if no expire
442 * is associated with this key (i.e. the key is non volatile) */
443 long long getExpire(redisDb
*db
, robj
*key
) {
446 /* No expire? return ASAP */
447 if (dictSize(db
->expires
) == 0 ||
448 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
450 /* The entry was found in the expire dict, this means it should also
451 * be present in the main dict (safety check). */
452 redisAssertWithInfo(NULL
,key
,dictFind(db
->dict
,key
->ptr
) != NULL
);
453 return dictGetSignedIntegerVal(de
);
456 /* Propagate expires into slaves and the AOF file.
457 * When a key expires in the master, a DEL operation for this key is sent
458 * to all the slaves and the AOF file if enabled.
460 * This way the key expiry is centralized in one place, and since both
461 * AOF and the master->slave link guarantee operation ordering, everything
462 * will be consistent even if we allow write operations against expiring
464 void propagateExpire(redisDb
*db
, robj
*key
) {
467 argv
[0] = shared
.del
;
469 incrRefCount(argv
[0]);
470 incrRefCount(argv
[1]);
472 if (server
.aof_state
!= REDIS_AOF_OFF
)
473 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
474 if (listLength(server
.slaves
))
475 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
477 decrRefCount(argv
[0]);
478 decrRefCount(argv
[1]);
481 int expireIfNeeded(redisDb
*db
, robj
*key
) {
482 long long when
= getExpire(db
,key
);
484 if (when
< 0) return 0; /* No expire for this key */
486 /* Don't expire anything while loading. It will be done later. */
487 if (server
.loading
) return 0;
489 /* If we are running in the context of a slave, return ASAP:
490 * the slave key expiration is controlled by the master that will
491 * send us synthesized DEL operations for expired keys.
493 * Still we try to return the right information to the caller,
494 * that is, 0 if we think the key should be still valid, 1 if
495 * we think the key is expired at this time. */
496 if (server
.masterhost
!= NULL
) {
497 return mstime() > when
;
500 /* Return when this key has not expired */
501 if (mstime() <= when
) return 0;
504 server
.stat_expiredkeys
++;
505 propagateExpire(db
,key
);
506 return dbDelete(db
,key
);
509 /*-----------------------------------------------------------------------------
511 *----------------------------------------------------------------------------*/
513 /* Given an string object return true if it contains exactly the "ms"
514 * or "MS" string. This is used in order to check if the last argument
515 * of EXPIRE, EXPIREAT or TTL is "ms" to switch into millisecond input/output */
516 int stringObjectEqualsMs(robj
*a
) {
518 return tolower(arg
[0]) == 'm' && tolower(arg
[1]) == 's' && arg
[2] == '\0';
521 /* This is the generic command implementation for EXPIRE, PEXPIRE, EXPIREAT
522 * and PEXPIREAT. Because the commad second argument may be relative or absolute
523 * the "basetime" argument is used to signal what the base time is (either 0
524 * for *AT variants of the command, or the current time for relative expires).
526 * unit is either UNIT_SECONDS or UNIT_MILLISECONDS, and is only used for
527 * the argv[2] parameter. The basetime is always specified in milliesconds. */
528 void expireGenericCommand(redisClient
*c
, long long basetime
, int unit
) {
530 robj
*key
= c
->argv
[1], *param
= c
->argv
[2];
531 long long when
; /* unix time in milliseconds when the key will expire. */
533 if (getLongLongFromObjectOrReply(c
, param
, &when
, NULL
) != REDIS_OK
)
536 if (unit
== UNIT_SECONDS
) when
*= 1000;
539 de
= dictFind(c
->db
->dict
,key
->ptr
);
541 addReply(c
,shared
.czero
);
544 /* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
545 * should never be executed as a DEL when load the AOF or in the context
546 * of a slave instance.
548 * Instead we take the other branch of the IF statement setting an expire
549 * (possibly in the past) and wait for an explicit DEL from the master. */
550 if (when
<= mstime() && !server
.loading
&& !server
.masterhost
) {
553 redisAssertWithInfo(c
,key
,dbDelete(c
->db
,key
));
556 /* Replicate/AOF this as an explicit DEL. */
557 aux
= createStringObject("DEL",3);
558 rewriteClientCommandVector(c
,2,aux
,key
);
560 signalModifiedKey(c
->db
,key
);
561 addReply(c
, shared
.cone
);
564 setExpire(c
->db
,key
,when
);
565 addReply(c
,shared
.cone
);
566 signalModifiedKey(c
->db
,key
);
572 void expireCommand(redisClient
*c
) {
573 expireGenericCommand(c
,mstime(),UNIT_SECONDS
);
576 void expireatCommand(redisClient
*c
) {
577 expireGenericCommand(c
,0,UNIT_SECONDS
);
580 void pexpireCommand(redisClient
*c
) {
581 expireGenericCommand(c
,mstime(),UNIT_MILLISECONDS
);
584 void pexpireatCommand(redisClient
*c
) {
585 expireGenericCommand(c
,0,UNIT_MILLISECONDS
);
588 void ttlGenericCommand(redisClient
*c
, int output_ms
) {
589 long long expire
, ttl
= -1;
591 expire
= getExpire(c
->db
,c
->argv
[1]);
593 ttl
= expire
-mstime();
594 if (ttl
< 0) ttl
= -1;
597 addReplyLongLong(c
,-1);
599 addReplyLongLong(c
,output_ms
? ttl
: ((ttl
+500)/1000));
603 void ttlCommand(redisClient
*c
) {
604 ttlGenericCommand(c
, 0);
607 void pttlCommand(redisClient
*c
) {
608 ttlGenericCommand(c
, 1);
611 void persistCommand(redisClient
*c
) {
614 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
616 addReply(c
,shared
.czero
);
618 if (removeExpire(c
->db
,c
->argv
[1])) {
619 addReply(c
,shared
.cone
);
622 addReply(c
,shared
.czero
);
627 /* -----------------------------------------------------------------------------
628 * API to get key arguments from commands
629 * ---------------------------------------------------------------------------*/
631 int *getKeysUsingCommandTable(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
) {
632 int j
, i
= 0, last
, *keys
;
635 if (cmd
->firstkey
== 0) {
640 if (last
< 0) last
= argc
+last
;
641 keys
= zmalloc(sizeof(int)*((last
- cmd
->firstkey
)+1));
642 for (j
= cmd
->firstkey
; j
<= last
; j
+= cmd
->keystep
) {
643 redisAssert(j
< argc
);
650 int *getKeysFromCommand(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
651 if (cmd
->getkeys_proc
) {
652 return cmd
->getkeys_proc(cmd
,argv
,argc
,numkeys
,flags
);
654 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
658 void getKeysFreeResult(int *result
) {
662 int *noPreloadGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
663 if (flags
& REDIS_GETKEYS_PRELOAD
) {
667 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
671 int *renameGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
672 if (flags
& REDIS_GETKEYS_PRELOAD
) {
673 int *keys
= zmalloc(sizeof(int));
678 return getKeysUsingCommandTable(cmd
,argv
,argc
,numkeys
);
682 int *zunionInterGetKeys(struct redisCommand
*cmd
,robj
**argv
, int argc
, int *numkeys
, int flags
) {
685 REDIS_NOTUSED(flags
);
687 num
= atoi(argv
[2]->ptr
);
688 /* Sanity check. Don't return any key if the command is going to
689 * reply with syntax error. */
690 if (num
> (argc
-3)) {
694 keys
= zmalloc(sizeof(int)*num
);
695 for (i
= 0; i
< num
; i
++) keys
[i
] = 3+i
;
700 /* Slot to Key API. This is used by Redis Cluster in order to obtain in
701 * a fast way a key that belongs to a specified hash slot. This is useful
702 * while rehashing the cluster. */
703 void SlotToKeyAdd(robj
*key
) {
704 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
706 zslInsert(server
.cluster
.slots_to_keys
,hashslot
,key
);
710 void SlotToKeyDel(robj
*key
) {
711 unsigned int hashslot
= keyHashSlot(key
->ptr
,sdslen(key
->ptr
));
713 zslDelete(server
.cluster
.slots_to_keys
,hashslot
,key
);
716 unsigned int GetKeysInSlot(unsigned int hashslot
, robj
**keys
, unsigned int count
) {
721 range
.min
= range
.max
= hashslot
;
722 range
.minex
= range
.maxex
= 0;
724 n
= zslFirstInRange(server
.cluster
.slots_to_keys
, range
);
725 while(n
&& n
->score
== hashslot
&& count
--) {
727 n
= n
->level
[0].forward
;