]>
git.saurik.com Git - redis.git/blob - src/db.c
1a30034e811306e2848c4d27cee2c2511b3789d2
5 /*-----------------------------------------------------------------------------
7 *----------------------------------------------------------------------------*/
9 robj
*lookupKey(redisDb
*db
, robj
*key
) {
10 dictEntry
*de
= dictFind(db
->dict
,key
->ptr
);
12 robj
*val
= dictGetEntryVal(de
);
14 /* Update the access time for the aging algorithm.
15 * Don't do it if we have a saving child, as this will trigger
16 * a copy on write madness. */
17 if (server
.bgsavechildpid
== -1 && server
.bgrewritechildpid
== -1)
18 val
->lru
= server
.lruclock
;
20 if (server
.ds_enabled
&& val
->storage
== REDIS_DS_SAVING
) {
21 /* FIXME: change this code to just wait for our object to
22 * get out of the IO Job. */
23 waitEmptyIOJobsQueue();
24 processAllPendingIOJobs();
25 redisAssert(val
->storage
!= REDIS_DS_SAVING
);
27 server
.stat_keyspace_hits
++;
33 /* Key not found in the in memory hash table, but if disk store is
34 * enabled we may have this key on disk. If so load it in memory
37 * FIXME: race condition here. If there was an already scheduled
38 * async loading of this key, what may happen is that the old
39 * key is loaded in memory if this gets deleted in the meantime. */
40 if (server
.ds_enabled
&& cacheKeyMayExist(db
,key
)) {
41 redisLog(REDIS_DEBUG
,"Force loading key %s via lookup",
43 val
= dsGet(db
,key
,&expire
);
45 int retval
= dbAdd(db
,key
,val
);
46 redisAssert(retval
== REDIS_OK
);
47 if (expire
!= -1) setExpire(db
,key
,expire
);
48 server
.stat_keyspace_hits
++;
52 server
.stat_keyspace_misses
++;
57 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
58 expireIfNeeded(db
,key
);
59 return lookupKey(db
,key
);
62 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
63 expireIfNeeded(db
,key
);
64 return lookupKey(db
,key
);
67 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
68 robj
*o
= lookupKeyRead(c
->db
, key
);
69 if (!o
) addReply(c
,reply
);
73 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
74 robj
*o
= lookupKeyWrite(c
->db
, key
);
75 if (!o
) addReply(c
,reply
);
79 /* Add the key to the DB. If the key already exists REDIS_ERR is returned,
80 * otherwise REDIS_OK is returned, and the caller should increment the
81 * refcount of 'val'. */
82 int dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
83 /* Perform a lookup before adding the key, as we need to copy the
85 if (dictFind(db
->dict
, key
->ptr
) != NULL
) {
88 sds copy
= sdsdup(key
->ptr
);
89 dictAdd(db
->dict
, copy
, val
);
90 if (server
.ds_enabled
) {
91 /* FIXME: remove entry from negative cache */
97 /* If the key does not exist, this is just like dbAdd(). Otherwise
98 * the value associated to the key is replaced with the new one.
100 * On update (key already existed) 0 is returned. Otherwise 1. */
101 int dbReplace(redisDb
*db
, robj
*key
, robj
*val
) {
104 if ((oldval
= dictFetchValue(db
->dict
,key
->ptr
)) == NULL
) {
105 sds copy
= sdsdup(key
->ptr
);
106 dictAdd(db
->dict
, copy
, val
);
109 val
->storage
= oldval
->storage
;
110 dictReplace(db
->dict
, key
->ptr
, val
);
115 int dbExists(redisDb
*db
, robj
*key
) {
116 return dictFind(db
->dict
,key
->ptr
) != NULL
;
119 /* Return a random key, in form of a Redis object.
120 * If there are no keys, NULL is returned.
122 * The function makes sure to return keys not already expired. */
123 robj
*dbRandomKey(redisDb
*db
) {
124 struct dictEntry
*de
;
130 de
= dictGetRandomKey(db
->dict
);
131 if (de
== NULL
) return NULL
;
133 key
= dictGetEntryKey(de
);
134 keyobj
= createStringObject(key
,sdslen(key
));
135 if (dictFind(db
->expires
,key
)) {
136 if (expireIfNeeded(db
,keyobj
)) {
137 decrRefCount(keyobj
);
138 continue; /* search for another key. This expired. */
145 /* Delete a key, value, and associated expiration entry if any, from the DB */
146 int dbDelete(redisDb
*db
, robj
*key
) {
147 /* If diskstore is enabled make sure to awake waiting clients for this key
148 * as it is not really useful to wait for a key already deleted to be
149 * loaded from disk. */
150 if (server
.ds_enabled
) handleClientsBlockedOnSwappedKey(db
,key
);
152 /* Mark this key as non existing on disk as well */
153 cacheSetKeyDoesNotExistRemember(db
,key
);
155 /* Deleting an entry from the expires dict will not free the sds of
156 * the key, because it is shared with the main dictionary. */
157 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
158 return dictDelete(db
->dict
,key
->ptr
) == DICT_OK
;
161 /* Empty the whole database */
162 long long emptyDb() {
164 long long removed
= 0;
166 for (j
= 0; j
< server
.dbnum
; j
++) {
167 removed
+= dictSize(server
.db
[j
].dict
);
168 dictEmpty(server
.db
[j
].dict
);
169 dictEmpty(server
.db
[j
].expires
);
174 int selectDb(redisClient
*c
, int id
) {
175 if (id
< 0 || id
>= server
.dbnum
)
177 c
->db
= &server
.db
[id
];
181 /*-----------------------------------------------------------------------------
182 * Hooks for key space changes.
184 * Every time a key in the database is modified the function
185 * signalModifiedKey() is called.
187 * Every time a DB is flushed the function signalFlushDb() is called.
188 *----------------------------------------------------------------------------*/
190 void signalModifiedKey(redisDb
*db
, robj
*key
) {
191 touchWatchedKey(db
,key
);
192 if (server
.ds_enabled
)
193 cacheScheduleForFlush(db
,key
);
196 void signalFlushedDb(int dbid
) {
197 touchWatchedKeysOnFlush(dbid
);
198 if (server
.ds_enabled
)
202 /*-----------------------------------------------------------------------------
203 * Type agnostic commands operating on the key space
204 *----------------------------------------------------------------------------*/
206 void flushdbCommand(redisClient
*c
) {
207 server
.dirty
+= dictSize(c
->db
->dict
);
208 signalFlushedDb(c
->db
->id
);
209 dictEmpty(c
->db
->dict
);
210 dictEmpty(c
->db
->expires
);
211 addReply(c
,shared
.ok
);
214 void flushallCommand(redisClient
*c
) {
216 server
.dirty
+= emptyDb();
217 addReply(c
,shared
.ok
);
218 if (server
.bgsavechildpid
!= -1) {
219 kill(server
.bgsavechildpid
,SIGKILL
);
220 rdbRemoveTempFile(server
.bgsavechildpid
);
222 rdbSave(server
.dbfilename
);
226 void delCommand(redisClient
*c
) {
229 for (j
= 1; j
< c
->argc
; j
++) {
230 if (server
.ds_enabled
) {
231 lookupKeyRead(c
->db
,c
->argv
[j
]);
232 /* FIXME: this can be optimized a lot, no real need to load
233 * a possibly huge value. */
235 if (dbDelete(c
->db
,c
->argv
[j
])) {
236 signalModifiedKey(c
->db
,c
->argv
[j
]);
239 } else if (server
.ds_enabled
) {
240 if (cacheKeyMayExist(c
->db
,c
->argv
[j
]) &&
241 dsExists(c
->db
,c
->argv
[j
]))
243 cacheScheduleForFlush(c
->db
,c
->argv
[j
]);
248 addReplyLongLong(c
,deleted
);
251 void existsCommand(redisClient
*c
) {
252 expireIfNeeded(c
->db
,c
->argv
[1]);
253 if (dbExists(c
->db
,c
->argv
[1])) {
254 addReply(c
, shared
.cone
);
256 addReply(c
, shared
.czero
);
260 void selectCommand(redisClient
*c
) {
261 int id
= atoi(c
->argv
[1]->ptr
);
263 if (selectDb(c
,id
) == REDIS_ERR
) {
264 addReplyError(c
,"invalid DB index");
266 addReply(c
,shared
.ok
);
270 void randomkeyCommand(redisClient
*c
) {
273 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
274 addReply(c
,shared
.nullbulk
);
282 void keysCommand(redisClient
*c
) {
285 sds pattern
= c
->argv
[1]->ptr
;
286 int plen
= sdslen(pattern
), allkeys
;
287 unsigned long numkeys
= 0;
288 void *replylen
= addDeferredMultiBulkLength(c
);
290 di
= dictGetIterator(c
->db
->dict
);
291 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
292 while((de
= dictNext(di
)) != NULL
) {
293 sds key
= dictGetEntryKey(de
);
296 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
297 keyobj
= createStringObject(key
,sdslen(key
));
298 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
299 addReplyBulk(c
,keyobj
);
302 decrRefCount(keyobj
);
305 dictReleaseIterator(di
);
306 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
309 void dbsizeCommand(redisClient
*c
) {
310 addReplyLongLong(c
,dictSize(c
->db
->dict
));
313 void lastsaveCommand(redisClient
*c
) {
314 addReplyLongLong(c
,server
.lastsave
);
317 void typeCommand(redisClient
*c
) {
321 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
326 case REDIS_STRING
: type
= "string"; break;
327 case REDIS_LIST
: type
= "list"; break;
328 case REDIS_SET
: type
= "set"; break;
329 case REDIS_ZSET
: type
= "zset"; break;
330 case REDIS_HASH
: type
= "hash"; break;
331 default: type
= "unknown"; break;
334 addReplyStatus(c
,type
);
337 void saveCommand(redisClient
*c
) {
338 if (server
.bgsavechildpid
!= -1) {
339 addReplyError(c
,"Background save already in progress");
342 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
343 addReply(c
,shared
.ok
);
345 addReply(c
,shared
.err
);
349 void bgsaveCommand(redisClient
*c
) {
350 if (server
.bgsavechildpid
!= -1) {
351 addReplyError(c
,"Background save already in progress");
354 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
355 addReplyStatus(c
,"Background saving started");
357 addReply(c
,shared
.err
);
361 void shutdownCommand(redisClient
*c
) {
362 if (prepareForShutdown() == REDIS_OK
)
364 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
367 void renameGenericCommand(redisClient
*c
, int nx
) {
370 /* To use the same key as src and dst is probably an error */
371 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
372 addReply(c
,shared
.sameobjecterr
);
376 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
380 if (dbAdd(c
->db
,c
->argv
[2],o
) == REDIS_ERR
) {
383 addReply(c
,shared
.czero
);
386 dbReplace(c
->db
,c
->argv
[2],o
);
388 dbDelete(c
->db
,c
->argv
[1]);
389 signalModifiedKey(c
->db
,c
->argv
[1]);
390 signalModifiedKey(c
->db
,c
->argv
[2]);
392 addReply(c
,nx
? shared
.cone
: shared
.ok
);
395 void renameCommand(redisClient
*c
) {
396 renameGenericCommand(c
,0);
399 void renamenxCommand(redisClient
*c
) {
400 renameGenericCommand(c
,1);
403 void moveCommand(redisClient
*c
) {
408 /* Obtain source and target DB pointers */
411 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
412 addReply(c
,shared
.outofrangeerr
);
416 selectDb(c
,srcid
); /* Back to the source DB */
418 /* If the user is moving using as target the same
419 * DB as the source DB it is probably an error. */
421 addReply(c
,shared
.sameobjecterr
);
425 /* Check if the element exists and get a reference */
426 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
428 addReply(c
,shared
.czero
);
432 /* Try to add the element to the target DB */
433 if (dbAdd(dst
,c
->argv
[1],o
) == REDIS_ERR
) {
434 addReply(c
,shared
.czero
);
439 /* OK! key moved, free the entry in the source DB */
440 dbDelete(src
,c
->argv
[1]);
442 addReply(c
,shared
.cone
);
445 /*-----------------------------------------------------------------------------
447 *----------------------------------------------------------------------------*/
449 int removeExpire(redisDb
*db
, robj
*key
) {
450 /* An expire may only be removed if there is a corresponding entry in the
451 * main dict. Otherwise, the key will never be freed. */
452 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
453 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
456 void setExpire(redisDb
*db
, robj
*key
, time_t when
) {
459 /* Reuse the sds from the main dict in the expire dict */
460 de
= dictFind(db
->dict
,key
->ptr
);
461 redisAssert(de
!= NULL
);
462 dictReplace(db
->expires
,dictGetEntryKey(de
),(void*)when
);
465 /* Return the expire time of the specified key, or -1 if no expire
466 * is associated with this key (i.e. the key is non volatile) */
467 time_t getExpire(redisDb
*db
, robj
*key
) {
470 /* No expire? return ASAP */
471 if (dictSize(db
->expires
) == 0 ||
472 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
474 /* The entry was found in the expire dict, this means it should also
475 * be present in the main dict (safety check). */
476 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
477 return (time_t) dictGetEntryVal(de
);
480 /* Propagate expires into slaves and the AOF file.
481 * When a key expires in the master, a DEL operation for this key is sent
482 * to all the slaves and the AOF file if enabled.
484 * This way the key expiry is centralized in one place, and since both
485 * AOF and the master->slave link guarantee operation ordering, everything
486 * will be consistent even if we allow write operations against expiring
488 void propagateExpire(redisDb
*db
, robj
*key
) {
491 argv
[0] = createStringObject("DEL",3);
495 if (server
.appendonly
)
496 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
497 if (listLength(server
.slaves
))
498 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
500 decrRefCount(argv
[0]);
501 decrRefCount(argv
[1]);
504 int expireIfNeeded(redisDb
*db
, robj
*key
) {
505 time_t when
= getExpire(db
,key
);
507 /* If we are running in the context of a slave, return ASAP:
508 * the slave key expiration is controlled by the master that will
509 * send us synthesized DEL operations for expired keys.
511 * Still we try to return the right information to the caller,
512 * that is, 0 if we think the key should be still valid, 1 if
513 * we think the key is expired at this time. */
514 if (server
.masterhost
!= NULL
) {
515 return time(NULL
) > when
;
518 if (when
< 0) return 0;
520 /* Return when this key has not expired */
521 if (time(NULL
) <= when
) return 0;
524 server
.stat_expiredkeys
++;
525 propagateExpire(db
,key
);
526 return dbDelete(db
,key
);
529 /*-----------------------------------------------------------------------------
531 *----------------------------------------------------------------------------*/
533 void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
537 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
541 de
= dictFind(c
->db
->dict
,key
->ptr
);
543 addReply(c
,shared
.czero
);
547 if (dbDelete(c
->db
,key
)) server
.dirty
++;
548 addReply(c
, shared
.cone
);
549 signalModifiedKey(c
->db
,key
);
552 time_t when
= time(NULL
)+seconds
;
553 setExpire(c
->db
,key
,when
);
554 addReply(c
,shared
.cone
);
555 signalModifiedKey(c
->db
,key
);
561 void expireCommand(redisClient
*c
) {
562 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
565 void expireatCommand(redisClient
*c
) {
566 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
569 void ttlCommand(redisClient
*c
) {
570 time_t expire
, ttl
= -1;
572 expire
= getExpire(c
->db
,c
->argv
[1]);
574 ttl
= (expire
-time(NULL
));
575 if (ttl
< 0) ttl
= -1;
577 addReplyLongLong(c
,(long long)ttl
);
580 void persistCommand(redisClient
*c
) {
583 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
585 addReply(c
,shared
.czero
);
587 if (removeExpire(c
->db
,c
->argv
[1])) {
588 addReply(c
,shared
.cone
);
591 addReply(c
,shared
.czero
);