]>
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
.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 redisAssert(val
->storage
!= REDIS_DS_SAVING
);
26 server
.stat_keyspace_hits
++;
29 /* FIXME: Check if the object is on disk, if it is, load it
30 * in a blocking way now. */
31 server
.stat_keyspace_misses
++;
36 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
37 expireIfNeeded(db
,key
);
38 return lookupKey(db
,key
);
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. If the key already exists REDIS_ERR is returned,
59 * otherwise REDIS_OK is returned, and the caller should increment the
60 * refcount of 'val'. */
61 int dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
62 /* Perform a lookup before adding the key, as we need to copy the
64 if (dictFind(db
->dict
, key
->ptr
) != NULL
) {
67 sds copy
= sdsdup(key
->ptr
);
68 dictAdd(db
->dict
, copy
, val
);
73 /* If the key does not exist, this is just like dbAdd(). Otherwise
74 * the value associated to the key is replaced with the new one.
76 * On update (key already existed) 0 is returned. Otherwise 1. */
77 int dbReplace(redisDb
*db
, robj
*key
, robj
*val
) {
78 if (dictFind(db
->dict
,key
->ptr
) == NULL
) {
79 sds copy
= sdsdup(key
->ptr
);
80 dictAdd(db
->dict
, copy
, val
);
83 dictReplace(db
->dict
, key
->ptr
, val
);
88 int dbExists(redisDb
*db
, robj
*key
) {
89 return dictFind(db
->dict
,key
->ptr
) != NULL
;
92 /* Return a random key, in form of a Redis object.
93 * If there are no keys, NULL is returned.
95 * The function makes sure to return keys not already expired. */
96 robj
*dbRandomKey(redisDb
*db
) {
103 de
= dictGetRandomKey(db
->dict
);
104 if (de
== NULL
) return NULL
;
106 key
= dictGetEntryKey(de
);
107 keyobj
= createStringObject(key
,sdslen(key
));
108 if (dictFind(db
->expires
,key
)) {
109 if (expireIfNeeded(db
,keyobj
)) {
110 decrRefCount(keyobj
);
111 continue; /* search for another key. This expired. */
118 /* Delete a key, value, and associated expiration entry if any, from the DB */
119 int dbDelete(redisDb
*db
, robj
*key
) {
120 /* If VM is enabled make sure to awake waiting clients for this key:
121 * deleting the key will kill the I/O thread bringing the key from swap
122 * to memory, so the client will never be notified and unblocked if we
123 * don't do it now. */
124 if (server
.ds_enabled
) handleClientsBlockedOnSwappedKey(db
,key
);
126 /* FIXME: we need to delete the IO Job loading the key, or simply we can
127 * wait for it to finish. */
129 /* Deleting an entry from the expires dict will not free the sds of
130 * the key, because it is shared with the main dictionary. */
131 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
132 return dictDelete(db
->dict
,key
->ptr
) == DICT_OK
;
135 /* Empty the whole database */
136 long long emptyDb() {
138 long long removed
= 0;
140 for (j
= 0; j
< server
.dbnum
; j
++) {
141 removed
+= dictSize(server
.db
[j
].dict
);
142 dictEmpty(server
.db
[j
].dict
);
143 dictEmpty(server
.db
[j
].expires
);
148 int selectDb(redisClient
*c
, int id
) {
149 if (id
< 0 || id
>= server
.dbnum
)
151 c
->db
= &server
.db
[id
];
155 /*-----------------------------------------------------------------------------
156 * Type agnostic commands operating on the key space
157 *----------------------------------------------------------------------------*/
159 void flushdbCommand(redisClient
*c
) {
160 server
.dirty
+= dictSize(c
->db
->dict
);
161 touchWatchedKeysOnFlush(c
->db
->id
);
162 dictEmpty(c
->db
->dict
);
163 dictEmpty(c
->db
->expires
);
164 addReply(c
,shared
.ok
);
167 void flushallCommand(redisClient
*c
) {
168 touchWatchedKeysOnFlush(-1);
169 server
.dirty
+= emptyDb();
170 addReply(c
,shared
.ok
);
171 if (server
.bgsavechildpid
!= -1) {
172 kill(server
.bgsavechildpid
,SIGKILL
);
173 rdbRemoveTempFile(server
.bgsavechildpid
);
175 rdbSave(server
.dbfilename
);
179 void delCommand(redisClient
*c
) {
182 for (j
= 1; j
< c
->argc
; j
++) {
183 if (dbDelete(c
->db
,c
->argv
[j
])) {
184 touchWatchedKey(c
->db
,c
->argv
[j
]);
189 addReplyLongLong(c
,deleted
);
192 void existsCommand(redisClient
*c
) {
193 expireIfNeeded(c
->db
,c
->argv
[1]);
194 if (dbExists(c
->db
,c
->argv
[1])) {
195 addReply(c
, shared
.cone
);
197 addReply(c
, shared
.czero
);
201 void selectCommand(redisClient
*c
) {
202 int id
= atoi(c
->argv
[1]->ptr
);
204 if (selectDb(c
,id
) == REDIS_ERR
) {
205 addReplyError(c
,"invalid DB index");
207 addReply(c
,shared
.ok
);
211 void randomkeyCommand(redisClient
*c
) {
214 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
215 addReply(c
,shared
.nullbulk
);
223 void keysCommand(redisClient
*c
) {
226 sds pattern
= c
->argv
[1]->ptr
;
227 int plen
= sdslen(pattern
), allkeys
;
228 unsigned long numkeys
= 0;
229 void *replylen
= addDeferredMultiBulkLength(c
);
231 di
= dictGetIterator(c
->db
->dict
);
232 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
233 while((de
= dictNext(di
)) != NULL
) {
234 sds key
= dictGetEntryKey(de
);
237 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
238 keyobj
= createStringObject(key
,sdslen(key
));
239 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
240 addReplyBulk(c
,keyobj
);
243 decrRefCount(keyobj
);
246 dictReleaseIterator(di
);
247 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
250 void dbsizeCommand(redisClient
*c
) {
251 addReplyLongLong(c
,dictSize(c
->db
->dict
));
254 void lastsaveCommand(redisClient
*c
) {
255 addReplyLongLong(c
,server
.lastsave
);
258 void typeCommand(redisClient
*c
) {
262 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
267 case REDIS_STRING
: type
= "string"; break;
268 case REDIS_LIST
: type
= "list"; break;
269 case REDIS_SET
: type
= "set"; break;
270 case REDIS_ZSET
: type
= "zset"; break;
271 case REDIS_HASH
: type
= "hash"; break;
272 default: type
= "unknown"; break;
275 addReplyStatus(c
,type
);
278 void saveCommand(redisClient
*c
) {
279 if (server
.bgsavechildpid
!= -1) {
280 addReplyError(c
,"Background save already in progress");
283 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
284 addReply(c
,shared
.ok
);
286 addReply(c
,shared
.err
);
290 void bgsaveCommand(redisClient
*c
) {
291 if (server
.bgsavechildpid
!= -1) {
292 addReplyError(c
,"Background save already in progress");
295 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
296 addReplyStatus(c
,"Background saving started");
298 addReply(c
,shared
.err
);
302 void shutdownCommand(redisClient
*c
) {
303 if (prepareForShutdown() == REDIS_OK
)
305 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
308 void renameGenericCommand(redisClient
*c
, int nx
) {
311 /* To use the same key as src and dst is probably an error */
312 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
313 addReply(c
,shared
.sameobjecterr
);
317 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
321 if (dbAdd(c
->db
,c
->argv
[2],o
) == REDIS_ERR
) {
324 addReply(c
,shared
.czero
);
327 dbReplace(c
->db
,c
->argv
[2],o
);
329 dbDelete(c
->db
,c
->argv
[1]);
330 touchWatchedKey(c
->db
,c
->argv
[1]);
331 touchWatchedKey(c
->db
,c
->argv
[2]);
333 addReply(c
,nx
? shared
.cone
: shared
.ok
);
336 void renameCommand(redisClient
*c
) {
337 renameGenericCommand(c
,0);
340 void renamenxCommand(redisClient
*c
) {
341 renameGenericCommand(c
,1);
344 void moveCommand(redisClient
*c
) {
349 /* Obtain source and target DB pointers */
352 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
353 addReply(c
,shared
.outofrangeerr
);
357 selectDb(c
,srcid
); /* Back to the source DB */
359 /* If the user is moving using as target the same
360 * DB as the source DB it is probably an error. */
362 addReply(c
,shared
.sameobjecterr
);
366 /* Check if the element exists and get a reference */
367 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
369 addReply(c
,shared
.czero
);
373 /* Try to add the element to the target DB */
374 if (dbAdd(dst
,c
->argv
[1],o
) == REDIS_ERR
) {
375 addReply(c
,shared
.czero
);
380 /* OK! key moved, free the entry in the source DB */
381 dbDelete(src
,c
->argv
[1]);
383 addReply(c
,shared
.cone
);
386 /*-----------------------------------------------------------------------------
388 *----------------------------------------------------------------------------*/
390 int removeExpire(redisDb
*db
, robj
*key
) {
391 /* An expire may only be removed if there is a corresponding entry in the
392 * main dict. Otherwise, the key will never be freed. */
393 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
394 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
397 void setExpire(redisDb
*db
, robj
*key
, time_t when
) {
400 /* Reuse the sds from the main dict in the expire dict */
401 de
= dictFind(db
->dict
,key
->ptr
);
402 redisAssert(de
!= NULL
);
403 dictReplace(db
->expires
,dictGetEntryKey(de
),(void*)when
);
406 /* Return the expire time of the specified key, or -1 if no expire
407 * is associated with this key (i.e. the key is non volatile) */
408 time_t getExpire(redisDb
*db
, robj
*key
) {
411 /* No expire? return ASAP */
412 if (dictSize(db
->expires
) == 0 ||
413 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
415 /* The entry was found in the expire dict, this means it should also
416 * be present in the main dict (safety check). */
417 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
418 return (time_t) dictGetEntryVal(de
);
421 /* Propagate expires into slaves and the AOF file.
422 * When a key expires in the master, a DEL operation for this key is sent
423 * to all the slaves and the AOF file if enabled.
425 * This way the key expiry is centralized in one place, and since both
426 * AOF and the master->slave link guarantee operation ordering, everything
427 * will be consistent even if we allow write operations against expiring
429 void propagateExpire(redisDb
*db
, robj
*key
) {
432 argv
[0] = createStringObject("DEL",3);
436 if (server
.appendonly
)
437 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
438 if (listLength(server
.slaves
))
439 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
441 decrRefCount(argv
[0]);
442 decrRefCount(argv
[1]);
445 int expireIfNeeded(redisDb
*db
, robj
*key
) {
446 time_t when
= getExpire(db
,key
);
448 /* If we are running in the context of a slave, return ASAP:
449 * the slave key expiration is controlled by the master that will
450 * send us synthesized DEL operations for expired keys.
452 * Still we try to return the right information to the caller,
453 * that is, 0 if we think the key should be still valid, 1 if
454 * we think the key is expired at this time. */
455 if (server
.masterhost
!= NULL
) {
456 return time(NULL
) > when
;
459 if (when
< 0) return 0;
461 /* Return when this key has not expired */
462 if (time(NULL
) <= when
) return 0;
465 server
.stat_expiredkeys
++;
466 propagateExpire(db
,key
);
467 return dbDelete(db
,key
);
470 /*-----------------------------------------------------------------------------
472 *----------------------------------------------------------------------------*/
474 void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
478 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
482 de
= dictFind(c
->db
->dict
,key
->ptr
);
484 addReply(c
,shared
.czero
);
488 if (dbDelete(c
->db
,key
)) server
.dirty
++;
489 addReply(c
, shared
.cone
);
490 touchWatchedKey(c
->db
,key
);
493 time_t when
= time(NULL
)+seconds
;
494 setExpire(c
->db
,key
,when
);
495 addReply(c
,shared
.cone
);
496 touchWatchedKey(c
->db
,key
);
502 void expireCommand(redisClient
*c
) {
503 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
506 void expireatCommand(redisClient
*c
) {
507 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
510 void ttlCommand(redisClient
*c
) {
511 time_t expire
, ttl
= -1;
513 expire
= getExpire(c
->db
,c
->argv
[1]);
515 ttl
= (expire
-time(NULL
));
516 if (ttl
< 0) ttl
= -1;
518 addReplyLongLong(c
,(long long)ttl
);
521 void persistCommand(redisClient
*c
) {
524 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
526 addReply(c
,shared
.czero
);
528 if (removeExpire(c
->db
,c
->argv
[1])) {
529 addReply(c
,shared
.cone
);
532 addReply(c
,shared
.czero
);