]>
git.saurik.com Git - redis.git/blob - src/db.c
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
.vm_enabled
) {
21 if (val
->storage
== REDIS_VM_MEMORY
||
22 val
->storage
== REDIS_VM_SWAPPING
)
24 /* If we were swapping the object out, cancel the operation */
25 if (val
->storage
== REDIS_VM_SWAPPING
)
26 vmCancelThreadedIOJob(val
);
28 int notify
= (val
->storage
== REDIS_VM_LOADING
);
30 /* Our value was swapped on disk. Bring it at home. */
31 redisAssert(val
->type
== REDIS_VMPOINTER
);
32 val
= vmLoadObject(val
);
33 dictGetEntryVal(de
) = val
;
35 /* Clients blocked by the VM subsystem may be waiting for
37 if (notify
) handleClientsBlockedOnSwappedKey(db
,key
);
40 server
.stat_keyspace_hits
++;
43 server
.stat_keyspace_misses
++;
48 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
49 expireIfNeeded(db
,key
);
50 return lookupKey(db
,key
);
53 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
54 expireIfNeeded(db
,key
);
55 return lookupKey(db
,key
);
58 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
59 robj
*o
= lookupKeyRead(c
->db
, key
);
60 if (!o
) addReply(c
,reply
);
64 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
65 robj
*o
= lookupKeyWrite(c
->db
, key
);
66 if (!o
) addReply(c
,reply
);
70 /* Add the key to the DB. If the key already exists REDIS_ERR is returned,
71 * otherwise REDIS_OK is returned, and the caller should increment the
72 * refcount of 'val'. */
73 int dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
74 /* Perform a lookup before adding the key, as we need to copy the
76 if (dictFind(db
->dict
, key
->ptr
) != NULL
) {
79 sds copy
= sdsdup(key
->ptr
);
80 dictAdd(db
->dict
, copy
, val
);
85 /* If the key does not exist, this is just like dbAdd(). Otherwise
86 * the value associated to the key is replaced with the new one.
88 * On update (key already existed) 0 is returned. Otherwise 1. */
89 int dbReplace(redisDb
*db
, robj
*key
, robj
*val
) {
90 if (dictFind(db
->dict
,key
->ptr
) == NULL
) {
91 sds copy
= sdsdup(key
->ptr
);
92 dictAdd(db
->dict
, copy
, val
);
95 dictReplace(db
->dict
, key
->ptr
, val
);
100 int dbExists(redisDb
*db
, robj
*key
) {
101 return dictFind(db
->dict
,key
->ptr
) != NULL
;
104 /* Return a random key, in form of a Redis object.
105 * If there are no keys, NULL is returned.
107 * The function makes sure to return keys not already expired. */
108 robj
*dbRandomKey(redisDb
*db
) {
109 struct dictEntry
*de
;
115 de
= dictGetRandomKey(db
->dict
);
116 if (de
== NULL
) return NULL
;
118 key
= dictGetEntryKey(de
);
119 keyobj
= createStringObject(key
,sdslen(key
));
120 if (dictFind(db
->expires
,key
)) {
121 if (expireIfNeeded(db
,keyobj
)) {
122 decrRefCount(keyobj
);
123 continue; /* search for another key. This expired. */
130 /* Delete a key, value, and associated expiration entry if any, from the DB */
131 int dbDelete(redisDb
*db
, robj
*key
) {
132 /* If VM is enabled make sure to awake waiting clients for this key:
133 * deleting the key will kill the I/O thread bringing the key from swap
134 * to memory, so the client will never be notified and unblocked if we
135 * don't do it now. */
136 if (server
.vm_enabled
) handleClientsBlockedOnSwappedKey(db
,key
);
137 /* Deleting an entry from the expires dict will not free the sds of
138 * the key, because it is shared with the main dictionary. */
139 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
140 return dictDelete(db
->dict
,key
->ptr
) == DICT_OK
;
143 /* Empty the whole database */
144 long long emptyDb() {
146 long long removed
= 0;
148 for (j
= 0; j
< server
.dbnum
; j
++) {
149 removed
+= dictSize(server
.db
[j
].dict
);
150 dictEmpty(server
.db
[j
].dict
);
151 dictEmpty(server
.db
[j
].expires
);
156 int selectDb(redisClient
*c
, int id
) {
157 if (id
< 0 || id
>= server
.dbnum
)
159 c
->db
= &server
.db
[id
];
163 /*-----------------------------------------------------------------------------
164 * Type agnostic commands operating on the key space
165 *----------------------------------------------------------------------------*/
167 void flushdbCommand(redisClient
*c
) {
168 server
.dirty
+= dictSize(c
->db
->dict
);
169 touchWatchedKeysOnFlush(c
->db
->id
);
170 dictEmpty(c
->db
->dict
);
171 dictEmpty(c
->db
->expires
);
172 addReply(c
,shared
.ok
);
175 void flushallCommand(redisClient
*c
) {
176 touchWatchedKeysOnFlush(-1);
177 server
.dirty
+= emptyDb();
178 addReply(c
,shared
.ok
);
179 if (server
.bgsavechildpid
!= -1) {
180 kill(server
.bgsavechildpid
,SIGKILL
);
181 rdbRemoveTempFile(server
.bgsavechildpid
);
183 rdbSave(server
.dbfilename
);
187 void delCommand(redisClient
*c
) {
190 for (j
= 1; j
< c
->argc
; j
++) {
191 if (dbDelete(c
->db
,c
->argv
[j
])) {
192 touchWatchedKey(c
->db
,c
->argv
[j
]);
197 addReplyLongLong(c
,deleted
);
200 void existsCommand(redisClient
*c
) {
201 expireIfNeeded(c
->db
,c
->argv
[1]);
202 if (dbExists(c
->db
,c
->argv
[1])) {
203 addReply(c
, shared
.cone
);
205 addReply(c
, shared
.czero
);
209 void selectCommand(redisClient
*c
) {
210 int id
= atoi(c
->argv
[1]->ptr
);
212 if (selectDb(c
,id
) == REDIS_ERR
) {
213 addReplyError(c
,"invalid DB index");
215 addReply(c
,shared
.ok
);
219 void randomkeyCommand(redisClient
*c
) {
222 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
223 addReply(c
,shared
.nullbulk
);
231 void keysCommand(redisClient
*c
) {
234 sds pattern
= c
->argv
[1]->ptr
;
235 int plen
= sdslen(pattern
), allkeys
;
236 unsigned long numkeys
= 0;
237 void *replylen
= addDeferredMultiBulkLength(c
);
239 di
= dictGetIterator(c
->db
->dict
);
240 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
241 while((de
= dictNext(di
)) != NULL
) {
242 sds key
= dictGetEntryKey(de
);
245 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
246 keyobj
= createStringObject(key
,sdslen(key
));
247 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
248 addReplyBulk(c
,keyobj
);
251 decrRefCount(keyobj
);
254 dictReleaseIterator(di
);
255 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
258 void dbsizeCommand(redisClient
*c
) {
259 addReplyLongLong(c
,dictSize(c
->db
->dict
));
262 void lastsaveCommand(redisClient
*c
) {
263 addReplyLongLong(c
,server
.lastsave
);
266 void typeCommand(redisClient
*c
) {
270 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
275 case REDIS_STRING
: type
= "string"; break;
276 case REDIS_LIST
: type
= "list"; break;
277 case REDIS_SET
: type
= "set"; break;
278 case REDIS_ZSET
: type
= "zset"; break;
279 case REDIS_HASH
: type
= "hash"; break;
280 default: type
= "unknown"; break;
283 addReplyStatus(c
,type
);
286 void saveCommand(redisClient
*c
) {
287 if (server
.bgsavechildpid
!= -1) {
288 addReplyError(c
,"Background save already in progress");
291 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
292 addReply(c
,shared
.ok
);
294 addReply(c
,shared
.err
);
298 void bgsaveCommand(redisClient
*c
) {
299 if (server
.bgsavechildpid
!= -1) {
300 addReplyError(c
,"Background save already in progress");
303 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
304 addReplyStatus(c
,"Background saving started");
306 addReply(c
,shared
.err
);
310 void shutdownCommand(redisClient
*c
) {
311 if (prepareForShutdown() == REDIS_OK
)
313 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
316 void renameGenericCommand(redisClient
*c
, int nx
) {
319 /* To use the same key as src and dst is probably an error */
320 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
321 addReply(c
,shared
.sameobjecterr
);
325 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
329 if (dbAdd(c
->db
,c
->argv
[2],o
) == REDIS_ERR
) {
332 addReply(c
,shared
.czero
);
335 dbReplace(c
->db
,c
->argv
[2],o
);
337 dbDelete(c
->db
,c
->argv
[1]);
338 touchWatchedKey(c
->db
,c
->argv
[1]);
339 touchWatchedKey(c
->db
,c
->argv
[2]);
341 addReply(c
,nx
? shared
.cone
: shared
.ok
);
344 void renameCommand(redisClient
*c
) {
345 renameGenericCommand(c
,0);
348 void renamenxCommand(redisClient
*c
) {
349 renameGenericCommand(c
,1);
352 void moveCommand(redisClient
*c
) {
357 /* Obtain source and target DB pointers */
360 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
361 addReply(c
,shared
.outofrangeerr
);
365 selectDb(c
,srcid
); /* Back to the source DB */
367 /* If the user is moving using as target the same
368 * DB as the source DB it is probably an error. */
370 addReply(c
,shared
.sameobjecterr
);
374 /* Check if the element exists and get a reference */
375 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
377 addReply(c
,shared
.czero
);
381 /* Try to add the element to the target DB */
382 if (dbAdd(dst
,c
->argv
[1],o
) == REDIS_ERR
) {
383 addReply(c
,shared
.czero
);
388 /* OK! key moved, free the entry in the source DB */
389 dbDelete(src
,c
->argv
[1]);
391 addReply(c
,shared
.cone
);
394 /*-----------------------------------------------------------------------------
396 *----------------------------------------------------------------------------*/
398 int removeExpire(redisDb
*db
, robj
*key
) {
399 /* An expire may only be removed if there is a corresponding entry in the
400 * main dict. Otherwise, the key will never be freed. */
401 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
402 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
405 void setExpire(redisDb
*db
, robj
*key
, time_t when
) {
408 /* Reuse the sds from the main dict in the expire dict */
409 de
= dictFind(db
->dict
,key
->ptr
);
410 redisAssert(de
!= NULL
);
411 dictReplace(db
->expires
,dictGetEntryKey(de
),(void*)when
);
414 /* Return the expire time of the specified key, or -1 if no expire
415 * is associated with this key (i.e. the key is non volatile) */
416 time_t getExpire(redisDb
*db
, robj
*key
) {
419 /* No expire? return ASAP */
420 if (dictSize(db
->expires
) == 0 ||
421 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
423 /* The entry was found in the expire dict, this means it should also
424 * be present in the main dict (safety check). */
425 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
426 return (time_t) dictGetEntryVal(de
);
429 /* Propagate expires into slaves and the AOF file.
430 * When a key expires in the master, a DEL operation for this key is sent
431 * to all the slaves and the AOF file if enabled.
433 * This way the key expiry is centralized in one place, and since both
434 * AOF and the master->slave link guarantee operation ordering, everything
435 * will be consistent even if we allow write operations against expiring
437 void propagateExpire(redisDb
*db
, robj
*key
) {
438 struct redisCommand
*cmd
;
441 cmd
= lookupCommand("del");
442 argv
[0] = createStringObject("DEL",3);
446 if (server
.appendonly
)
447 feedAppendOnlyFile(cmd
,db
->id
,argv
,2);
448 if (listLength(server
.slaves
))
449 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
451 decrRefCount(argv
[0]);
452 decrRefCount(argv
[1]);
455 int expireIfNeeded(redisDb
*db
, robj
*key
) {
456 time_t when
= getExpire(db
,key
);
458 /* If we are running in the context of a slave, return ASAP:
459 * the slave key expiration is controlled by the master that will
460 * send us synthesized DEL operations for expired keys.
462 * Still we try to return the right information to the caller,
463 * that is, 0 if we think the key should be still valid, 1 if
464 * we think the key is expired at this time. */
465 if (server
.masterhost
!= NULL
) {
466 return time(NULL
) > when
;
469 if (when
< 0) return 0;
471 /* Return when this key has not expired */
472 if (time(NULL
) <= when
) return 0;
475 server
.stat_expiredkeys
++;
476 propagateExpire(db
,key
);
477 return dbDelete(db
,key
);
480 /*-----------------------------------------------------------------------------
482 *----------------------------------------------------------------------------*/
484 void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
488 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
492 de
= dictFind(c
->db
->dict
,key
->ptr
);
494 addReply(c
,shared
.czero
);
498 if (dbDelete(c
->db
,key
)) server
.dirty
++;
499 addReply(c
, shared
.cone
);
500 touchWatchedKey(c
->db
,key
);
503 time_t when
= time(NULL
)+seconds
;
504 setExpire(c
->db
,key
,when
);
505 addReply(c
,shared
.cone
);
506 touchWatchedKey(c
->db
,key
);
512 void expireCommand(redisClient
*c
) {
513 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
516 void expireatCommand(redisClient
*c
) {
517 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
520 void ttlCommand(redisClient
*c
) {
521 time_t expire
, ttl
= -1;
523 expire
= getExpire(c
->db
,c
->argv
[1]);
525 ttl
= (expire
-time(NULL
));
526 if (ttl
< 0) ttl
= -1;
528 addReplyLongLong(c
,(long long)ttl
);
531 void persistCommand(redisClient
*c
) {
534 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
536 addReply(c
,shared
.czero
);
538 if (removeExpire(c
->db
,c
->argv
[1])) {
539 addReply(c
,shared
.cone
);
542 addReply(c
,shared
.czero
);