]>
git.saurik.com Git - redis.git/blob - src/db.c
d545345cb9fdf893ad4546f99bfa4b1c8ccb364d
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
++;
30 /* FIXME: Check if the object is on disk, if it is, load it
31 * in a blocking way now. */
32 server
.stat_keyspace_misses
++;
37 robj
*lookupKeyRead(redisDb
*db
, robj
*key
) {
38 expireIfNeeded(db
,key
);
39 return lookupKey(db
,key
);
42 robj
*lookupKeyWrite(redisDb
*db
, robj
*key
) {
43 expireIfNeeded(db
,key
);
44 return lookupKey(db
,key
);
47 robj
*lookupKeyReadOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
48 robj
*o
= lookupKeyRead(c
->db
, key
);
49 if (!o
) addReply(c
,reply
);
53 robj
*lookupKeyWriteOrReply(redisClient
*c
, robj
*key
, robj
*reply
) {
54 robj
*o
= lookupKeyWrite(c
->db
, key
);
55 if (!o
) addReply(c
,reply
);
59 /* Add the key to the DB. If the key already exists REDIS_ERR is returned,
60 * otherwise REDIS_OK is returned, and the caller should increment the
61 * refcount of 'val'. */
62 int dbAdd(redisDb
*db
, robj
*key
, robj
*val
) {
63 /* Perform a lookup before adding the key, as we need to copy the
65 if (dictFind(db
->dict
, key
->ptr
) != NULL
) {
68 sds copy
= sdsdup(key
->ptr
);
69 dictAdd(db
->dict
, copy
, val
);
70 if (server
.ds_enabled
) {
71 /* FIXME: remove entry from negative cache */
77 /* If the key does not exist, this is just like dbAdd(). Otherwise
78 * the value associated to the key is replaced with the new one.
80 * On update (key already existed) 0 is returned. Otherwise 1. */
81 int dbReplace(redisDb
*db
, robj
*key
, robj
*val
) {
82 if (dictFind(db
->dict
,key
->ptr
) == NULL
) {
83 sds copy
= sdsdup(key
->ptr
);
84 dictAdd(db
->dict
, copy
, val
);
87 dictReplace(db
->dict
, key
->ptr
, val
);
92 int dbExists(redisDb
*db
, robj
*key
) {
93 return dictFind(db
->dict
,key
->ptr
) != NULL
;
96 /* Return a random key, in form of a Redis object.
97 * If there are no keys, NULL is returned.
99 * The function makes sure to return keys not already expired. */
100 robj
*dbRandomKey(redisDb
*db
) {
101 struct dictEntry
*de
;
107 de
= dictGetRandomKey(db
->dict
);
108 if (de
== NULL
) return NULL
;
110 key
= dictGetEntryKey(de
);
111 keyobj
= createStringObject(key
,sdslen(key
));
112 if (dictFind(db
->expires
,key
)) {
113 if (expireIfNeeded(db
,keyobj
)) {
114 decrRefCount(keyobj
);
115 continue; /* search for another key. This expired. */
122 /* Delete a key, value, and associated expiration entry if any, from the DB */
123 int dbDelete(redisDb
*db
, robj
*key
) {
124 /* If VM is enabled make sure to awake waiting clients for this key:
125 * deleting the key will kill the I/O thread bringing the key from swap
126 * to memory, so the client will never be notified and unblocked if we
127 * don't do it now. */
128 if (server
.ds_enabled
) handleClientsBlockedOnSwappedKey(db
,key
);
130 /* FIXME: we need to delete the IO Job loading the key, or simply we can
131 * wait for it to finish. */
133 /* Deleting an entry from the expires dict will not free the sds of
134 * the key, because it is shared with the main dictionary. */
135 if (dictSize(db
->expires
) > 0) dictDelete(db
->expires
,key
->ptr
);
136 return dictDelete(db
->dict
,key
->ptr
) == DICT_OK
;
139 /* Empty the whole database */
140 long long emptyDb() {
142 long long removed
= 0;
144 for (j
= 0; j
< server
.dbnum
; j
++) {
145 removed
+= dictSize(server
.db
[j
].dict
);
146 dictEmpty(server
.db
[j
].dict
);
147 dictEmpty(server
.db
[j
].expires
);
152 int selectDb(redisClient
*c
, int id
) {
153 if (id
< 0 || id
>= server
.dbnum
)
155 c
->db
= &server
.db
[id
];
159 /*-----------------------------------------------------------------------------
160 * Hooks for key space changes.
162 * Every time a key in the database is modified the function
163 * signalModifiedKey() is called.
165 * Every time a DB is flushed the function signalFlushDb() is called.
166 *----------------------------------------------------------------------------*/
168 void signalModifiedKey(redisDb
*db
, robj
*key
) {
169 touchWatchedKey(db
,key
);
170 if (server
.ds_enabled
)
171 cacheScheduleForFlush(db
,key
);
174 void signalFlushedDb(int dbid
) {
175 touchWatchedKeysOnFlush(dbid
);
176 if (server
.ds_enabled
)
180 /*-----------------------------------------------------------------------------
181 * Type agnostic commands operating on the key space
182 *----------------------------------------------------------------------------*/
184 void flushdbCommand(redisClient
*c
) {
185 server
.dirty
+= dictSize(c
->db
->dict
);
186 signalFlushedDb(c
->db
->id
);
187 dictEmpty(c
->db
->dict
);
188 dictEmpty(c
->db
->expires
);
189 addReply(c
,shared
.ok
);
192 void flushallCommand(redisClient
*c
) {
194 server
.dirty
+= emptyDb();
195 addReply(c
,shared
.ok
);
196 if (server
.bgsavechildpid
!= -1) {
197 kill(server
.bgsavechildpid
,SIGKILL
);
198 rdbRemoveTempFile(server
.bgsavechildpid
);
200 rdbSave(server
.dbfilename
);
204 void delCommand(redisClient
*c
) {
207 for (j
= 1; j
< c
->argc
; j
++) {
208 if (server
.ds_enabled
) {
209 lookupKeyRead(c
->db
,c
->argv
[j
]);
210 /* FIXME: this can be optimized a lot, no real need to load
211 * a possibly huge value. */
213 if (dbDelete(c
->db
,c
->argv
[j
])) {
214 signalModifiedKey(c
->db
,c
->argv
[j
]);
217 } else if (server
.ds_enabled
) {
218 if (cacheKeyMayExist(c
->db
,c
->argv
[j
]) &&
219 dsExists(c
->db
,c
->argv
[j
]))
221 cacheScheduleForFlush(c
->db
,c
->argv
[j
]);
226 addReplyLongLong(c
,deleted
);
229 void existsCommand(redisClient
*c
) {
230 expireIfNeeded(c
->db
,c
->argv
[1]);
231 if (dbExists(c
->db
,c
->argv
[1])) {
232 addReply(c
, shared
.cone
);
234 addReply(c
, shared
.czero
);
238 void selectCommand(redisClient
*c
) {
239 int id
= atoi(c
->argv
[1]->ptr
);
241 if (selectDb(c
,id
) == REDIS_ERR
) {
242 addReplyError(c
,"invalid DB index");
244 addReply(c
,shared
.ok
);
248 void randomkeyCommand(redisClient
*c
) {
251 if ((key
= dbRandomKey(c
->db
)) == NULL
) {
252 addReply(c
,shared
.nullbulk
);
260 void keysCommand(redisClient
*c
) {
263 sds pattern
= c
->argv
[1]->ptr
;
264 int plen
= sdslen(pattern
), allkeys
;
265 unsigned long numkeys
= 0;
266 void *replylen
= addDeferredMultiBulkLength(c
);
268 di
= dictGetIterator(c
->db
->dict
);
269 allkeys
= (pattern
[0] == '*' && pattern
[1] == '\0');
270 while((de
= dictNext(di
)) != NULL
) {
271 sds key
= dictGetEntryKey(de
);
274 if (allkeys
|| stringmatchlen(pattern
,plen
,key
,sdslen(key
),0)) {
275 keyobj
= createStringObject(key
,sdslen(key
));
276 if (expireIfNeeded(c
->db
,keyobj
) == 0) {
277 addReplyBulk(c
,keyobj
);
280 decrRefCount(keyobj
);
283 dictReleaseIterator(di
);
284 setDeferredMultiBulkLength(c
,replylen
,numkeys
);
287 void dbsizeCommand(redisClient
*c
) {
288 addReplyLongLong(c
,dictSize(c
->db
->dict
));
291 void lastsaveCommand(redisClient
*c
) {
292 addReplyLongLong(c
,server
.lastsave
);
295 void typeCommand(redisClient
*c
) {
299 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
304 case REDIS_STRING
: type
= "string"; break;
305 case REDIS_LIST
: type
= "list"; break;
306 case REDIS_SET
: type
= "set"; break;
307 case REDIS_ZSET
: type
= "zset"; break;
308 case REDIS_HASH
: type
= "hash"; break;
309 default: type
= "unknown"; break;
312 addReplyStatus(c
,type
);
315 void saveCommand(redisClient
*c
) {
316 if (server
.bgsavechildpid
!= -1) {
317 addReplyError(c
,"Background save already in progress");
320 if (rdbSave(server
.dbfilename
) == REDIS_OK
) {
321 addReply(c
,shared
.ok
);
323 addReply(c
,shared
.err
);
327 void bgsaveCommand(redisClient
*c
) {
328 if (server
.bgsavechildpid
!= -1) {
329 addReplyError(c
,"Background save already in progress");
332 if (rdbSaveBackground(server
.dbfilename
) == REDIS_OK
) {
333 addReplyStatus(c
,"Background saving started");
335 addReply(c
,shared
.err
);
339 void shutdownCommand(redisClient
*c
) {
340 if (prepareForShutdown() == REDIS_OK
)
342 addReplyError(c
,"Errors trying to SHUTDOWN. Check logs.");
345 void renameGenericCommand(redisClient
*c
, int nx
) {
348 /* To use the same key as src and dst is probably an error */
349 if (sdscmp(c
->argv
[1]->ptr
,c
->argv
[2]->ptr
) == 0) {
350 addReply(c
,shared
.sameobjecterr
);
354 if ((o
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.nokeyerr
)) == NULL
)
358 if (dbAdd(c
->db
,c
->argv
[2],o
) == REDIS_ERR
) {
361 addReply(c
,shared
.czero
);
364 dbReplace(c
->db
,c
->argv
[2],o
);
366 dbDelete(c
->db
,c
->argv
[1]);
367 signalModifiedKey(c
->db
,c
->argv
[1]);
368 signalModifiedKey(c
->db
,c
->argv
[2]);
370 addReply(c
,nx
? shared
.cone
: shared
.ok
);
373 void renameCommand(redisClient
*c
) {
374 renameGenericCommand(c
,0);
377 void renamenxCommand(redisClient
*c
) {
378 renameGenericCommand(c
,1);
381 void moveCommand(redisClient
*c
) {
386 /* Obtain source and target DB pointers */
389 if (selectDb(c
,atoi(c
->argv
[2]->ptr
)) == REDIS_ERR
) {
390 addReply(c
,shared
.outofrangeerr
);
394 selectDb(c
,srcid
); /* Back to the source DB */
396 /* If the user is moving using as target the same
397 * DB as the source DB it is probably an error. */
399 addReply(c
,shared
.sameobjecterr
);
403 /* Check if the element exists and get a reference */
404 o
= lookupKeyWrite(c
->db
,c
->argv
[1]);
406 addReply(c
,shared
.czero
);
410 /* Try to add the element to the target DB */
411 if (dbAdd(dst
,c
->argv
[1],o
) == REDIS_ERR
) {
412 addReply(c
,shared
.czero
);
417 /* OK! key moved, free the entry in the source DB */
418 dbDelete(src
,c
->argv
[1]);
420 addReply(c
,shared
.cone
);
423 /*-----------------------------------------------------------------------------
425 *----------------------------------------------------------------------------*/
427 int removeExpire(redisDb
*db
, robj
*key
) {
428 /* An expire may only be removed if there is a corresponding entry in the
429 * main dict. Otherwise, the key will never be freed. */
430 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
431 return dictDelete(db
->expires
,key
->ptr
) == DICT_OK
;
434 void setExpire(redisDb
*db
, robj
*key
, time_t when
) {
437 /* Reuse the sds from the main dict in the expire dict */
438 de
= dictFind(db
->dict
,key
->ptr
);
439 redisAssert(de
!= NULL
);
440 dictReplace(db
->expires
,dictGetEntryKey(de
),(void*)when
);
443 /* Return the expire time of the specified key, or -1 if no expire
444 * is associated with this key (i.e. the key is non volatile) */
445 time_t getExpire(redisDb
*db
, robj
*key
) {
448 /* No expire? return ASAP */
449 if (dictSize(db
->expires
) == 0 ||
450 (de
= dictFind(db
->expires
,key
->ptr
)) == NULL
) return -1;
452 /* The entry was found in the expire dict, this means it should also
453 * be present in the main dict (safety check). */
454 redisAssert(dictFind(db
->dict
,key
->ptr
) != NULL
);
455 return (time_t) dictGetEntryVal(de
);
458 /* Propagate expires into slaves and the AOF file.
459 * When a key expires in the master, a DEL operation for this key is sent
460 * to all the slaves and the AOF file if enabled.
462 * This way the key expiry is centralized in one place, and since both
463 * AOF and the master->slave link guarantee operation ordering, everything
464 * will be consistent even if we allow write operations against expiring
466 void propagateExpire(redisDb
*db
, robj
*key
) {
469 argv
[0] = createStringObject("DEL",3);
473 if (server
.appendonly
)
474 feedAppendOnlyFile(server
.delCommand
,db
->id
,argv
,2);
475 if (listLength(server
.slaves
))
476 replicationFeedSlaves(server
.slaves
,db
->id
,argv
,2);
478 decrRefCount(argv
[0]);
479 decrRefCount(argv
[1]);
482 int expireIfNeeded(redisDb
*db
, robj
*key
) {
483 time_t when
= getExpire(db
,key
);
485 /* If we are running in the context of a slave, return ASAP:
486 * the slave key expiration is controlled by the master that will
487 * send us synthesized DEL operations for expired keys.
489 * Still we try to return the right information to the caller,
490 * that is, 0 if we think the key should be still valid, 1 if
491 * we think the key is expired at this time. */
492 if (server
.masterhost
!= NULL
) {
493 return time(NULL
) > when
;
496 if (when
< 0) return 0;
498 /* Return when this key has not expired */
499 if (time(NULL
) <= when
) return 0;
502 server
.stat_expiredkeys
++;
503 propagateExpire(db
,key
);
504 return dbDelete(db
,key
);
507 /*-----------------------------------------------------------------------------
509 *----------------------------------------------------------------------------*/
511 void expireGenericCommand(redisClient
*c
, robj
*key
, robj
*param
, long offset
) {
515 if (getLongFromObjectOrReply(c
, param
, &seconds
, NULL
) != REDIS_OK
) return;
519 de
= dictFind(c
->db
->dict
,key
->ptr
);
521 addReply(c
,shared
.czero
);
525 if (dbDelete(c
->db
,key
)) server
.dirty
++;
526 addReply(c
, shared
.cone
);
527 signalModifiedKey(c
->db
,key
);
530 time_t when
= time(NULL
)+seconds
;
531 setExpire(c
->db
,key
,when
);
532 addReply(c
,shared
.cone
);
533 signalModifiedKey(c
->db
,key
);
539 void expireCommand(redisClient
*c
) {
540 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],0);
543 void expireatCommand(redisClient
*c
) {
544 expireGenericCommand(c
,c
->argv
[1],c
->argv
[2],time(NULL
));
547 void ttlCommand(redisClient
*c
) {
548 time_t expire
, ttl
= -1;
550 expire
= getExpire(c
->db
,c
->argv
[1]);
552 ttl
= (expire
-time(NULL
));
553 if (ttl
< 0) ttl
= -1;
555 addReplyLongLong(c
,(long long)ttl
);
558 void persistCommand(redisClient
*c
) {
561 de
= dictFind(c
->db
->dict
,c
->argv
[1]->ptr
);
563 addReply(c
,shared
.czero
);
565 if (removeExpire(c
->db
,c
->argv
[1])) {
566 addReply(c
,shared
.cone
);
569 addReply(c
,shared
.czero
);