]> git.saurik.com Git - redis.git/blame - src/db.c
Merged with split
[redis.git] / src / db.c
CommitLineData
e2641e09 1#include "redis.h"
2
3#include <signal.h>
4
5/*-----------------------------------------------------------------------------
6 * C-level DB API
7 *----------------------------------------------------------------------------*/
8
9robj *lookupKey(redisDb *db, robj *key) {
10 dictEntry *de = dictFind(db->dict,key->ptr);
11 if (de) {
12 robj *val = dictGetEntryVal(de);
13
14 if (server.vm_enabled) {
15 if (val->storage == REDIS_VM_MEMORY ||
16 val->storage == REDIS_VM_SWAPPING)
17 {
18 /* If we were swapping the object out, cancel the operation */
19 if (val->storage == REDIS_VM_SWAPPING)
20 vmCancelThreadedIOJob(val);
21 /* Update the access time for the aging algorithm. */
22 val->lru = server.lruclock;
23 } else {
24 int notify = (val->storage == REDIS_VM_LOADING);
25
26 /* Our value was swapped on disk. Bring it at home. */
27 redisAssert(val->type == REDIS_VMPOINTER);
28 val = vmLoadObject(val);
29 dictGetEntryVal(de) = val;
30
31 /* Clients blocked by the VM subsystem may be waiting for
32 * this key... */
33 if (notify) handleClientsBlockedOnSwappedKey(db,key);
34 }
35 }
36 return val;
37 } else {
38 return NULL;
39 }
40}
41
42robj *lookupKeyRead(redisDb *db, robj *key) {
43 expireIfNeeded(db,key);
44 return lookupKey(db,key);
45}
46
47robj *lookupKeyWrite(redisDb *db, robj *key) {
48 deleteIfVolatile(db,key);
49 touchWatchedKey(db,key);
50 return lookupKey(db,key);
51}
52
53robj *lookupKeyReadOrReply(redisClient *c, robj *key, robj *reply) {
54 robj *o = lookupKeyRead(c->db, key);
55 if (!o) addReply(c,reply);
56 return o;
57}
58
59robj *lookupKeyWriteOrReply(redisClient *c, robj *key, robj *reply) {
60 robj *o = lookupKeyWrite(c->db, key);
61 if (!o) addReply(c,reply);
62 return o;
63}
64
65/* Add the key to the DB. If the key already exists REDIS_ERR is returned,
66 * otherwise REDIS_OK is returned, and the caller should increment the
67 * refcount of 'val'. */
68int dbAdd(redisDb *db, robj *key, robj *val) {
69 /* Perform a lookup before adding the key, as we need to copy the
70 * key value. */
71 if (dictFind(db->dict, key->ptr) != NULL) {
72 return REDIS_ERR;
73 } else {
74 sds copy = sdsdup(key->ptr);
75 dictAdd(db->dict, copy, val);
76 return REDIS_OK;
77 }
78}
79
80/* If the key does not exist, this is just like dbAdd(). Otherwise
81 * the value associated to the key is replaced with the new one.
82 *
83 * On update (key already existed) 0 is returned. Otherwise 1. */
84int dbReplace(redisDb *db, robj *key, robj *val) {
85 if (dictFind(db->dict,key->ptr) == NULL) {
86 sds copy = sdsdup(key->ptr);
87 dictAdd(db->dict, copy, val);
88 return 1;
89 } else {
90 dictReplace(db->dict, key->ptr, val);
91 return 0;
92 }
93}
94
95int dbExists(redisDb *db, robj *key) {
96 return dictFind(db->dict,key->ptr) != NULL;
97}
98
99/* Return a random key, in form of a Redis object.
100 * If there are no keys, NULL is returned.
101 *
102 * The function makes sure to return keys not already expired. */
103robj *dbRandomKey(redisDb *db) {
104 struct dictEntry *de;
105
106 while(1) {
107 sds key;
108 robj *keyobj;
109
110 de = dictGetRandomKey(db->dict);
111 if (de == NULL) return NULL;
112
113 key = dictGetEntryKey(de);
114 keyobj = createStringObject(key,sdslen(key));
115 if (dictFind(db->expires,key)) {
116 if (expireIfNeeded(db,keyobj)) {
117 decrRefCount(keyobj);
118 continue; /* search for another key. This expired. */
119 }
120 }
121 return keyobj;
122 }
123}
124
125/* Delete a key, value, and associated expiration entry if any, from the DB */
126int dbDelete(redisDb *db, robj *key) {
127 /* Deleting an entry from the expires dict will not free the sds of
128 * the key, because it is shared with the main dictionary. */
129 if (dictSize(db->expires) > 0) dictDelete(db->expires,key->ptr);
130 return dictDelete(db->dict,key->ptr) == DICT_OK;
131}
132
133/* Empty the whole database */
134long long emptyDb() {
135 int j;
136 long long removed = 0;
137
138 for (j = 0; j < server.dbnum; j++) {
139 removed += dictSize(server.db[j].dict);
140 dictEmpty(server.db[j].dict);
141 dictEmpty(server.db[j].expires);
142 }
143 return removed;
144}
145
146int selectDb(redisClient *c, int id) {
147 if (id < 0 || id >= server.dbnum)
148 return REDIS_ERR;
149 c->db = &server.db[id];
150 return REDIS_OK;
151}
152
153/*-----------------------------------------------------------------------------
154 * Type agnostic commands operating on the key space
155 *----------------------------------------------------------------------------*/
156
157void flushdbCommand(redisClient *c) {
158 server.dirty += dictSize(c->db->dict);
159 touchWatchedKeysOnFlush(c->db->id);
160 dictEmpty(c->db->dict);
161 dictEmpty(c->db->expires);
162 addReply(c,shared.ok);
163}
164
165void flushallCommand(redisClient *c) {
166 touchWatchedKeysOnFlush(-1);
167 server.dirty += emptyDb();
168 addReply(c,shared.ok);
169 if (server.bgsavechildpid != -1) {
170 kill(server.bgsavechildpid,SIGKILL);
171 rdbRemoveTempFile(server.bgsavechildpid);
172 }
173 rdbSave(server.dbfilename);
174 server.dirty++;
175}
176
177void delCommand(redisClient *c) {
178 int deleted = 0, j;
179
180 for (j = 1; j < c->argc; j++) {
181 if (dbDelete(c->db,c->argv[j])) {
182 touchWatchedKey(c->db,c->argv[j]);
183 server.dirty++;
184 deleted++;
185 }
186 }
187 addReplyLongLong(c,deleted);
188}
189
190void existsCommand(redisClient *c) {
191 expireIfNeeded(c->db,c->argv[1]);
192 if (dbExists(c->db,c->argv[1])) {
193 addReply(c, shared.cone);
194 } else {
195 addReply(c, shared.czero);
196 }
197}
198
199void selectCommand(redisClient *c) {
200 int id = atoi(c->argv[1]->ptr);
201
202 if (selectDb(c,id) == REDIS_ERR) {
203 addReplySds(c,sdsnew("-ERR invalid DB index\r\n"));
204 } else {
205 addReply(c,shared.ok);
206 }
207}
208
209void randomkeyCommand(redisClient *c) {
210 robj *key;
211
212 if ((key = dbRandomKey(c->db)) == NULL) {
213 addReply(c,shared.nullbulk);
214 return;
215 }
216
217 addReplyBulk(c,key);
218 decrRefCount(key);
219}
220
221void keysCommand(redisClient *c) {
222 dictIterator *di;
223 dictEntry *de;
224 sds pattern = c->argv[1]->ptr;
225 int plen = sdslen(pattern);
226 unsigned long numkeys = 0;
227 robj *lenobj = createObject(REDIS_STRING,NULL);
228
229 di = dictGetIterator(c->db->dict);
230 addReply(c,lenobj);
231 decrRefCount(lenobj);
232 while((de = dictNext(di)) != NULL) {
233 sds key = dictGetEntryKey(de);
234 robj *keyobj;
235
236 if ((pattern[0] == '*' && pattern[1] == '\0') ||
237 stringmatchlen(pattern,plen,key,sdslen(key),0)) {
238 keyobj = createStringObject(key,sdslen(key));
239 if (expireIfNeeded(c->db,keyobj) == 0) {
240 addReplyBulk(c,keyobj);
241 numkeys++;
242 }
243 decrRefCount(keyobj);
244 }
245 }
246 dictReleaseIterator(di);
247 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",numkeys);
248}
249
250void dbsizeCommand(redisClient *c) {
251 addReplySds(c,
252 sdscatprintf(sdsempty(),":%lu\r\n",dictSize(c->db->dict)));
253}
254
255void lastsaveCommand(redisClient *c) {
256 addReplySds(c,
257 sdscatprintf(sdsempty(),":%lu\r\n",server.lastsave));
258}
259
260void typeCommand(redisClient *c) {
261 robj *o;
262 char *type;
263
264 o = lookupKeyRead(c->db,c->argv[1]);
265 if (o == NULL) {
266 type = "+none";
267 } else {
268 switch(o->type) {
269 case REDIS_STRING: type = "+string"; break;
270 case REDIS_LIST: type = "+list"; break;
271 case REDIS_SET: type = "+set"; break;
272 case REDIS_ZSET: type = "+zset"; break;
273 case REDIS_HASH: type = "+hash"; break;
274 default: type = "+unknown"; break;
275 }
276 }
277 addReplySds(c,sdsnew(type));
278 addReply(c,shared.crlf);
279}
280
281void saveCommand(redisClient *c) {
282 if (server.bgsavechildpid != -1) {
283 addReplySds(c,sdsnew("-ERR background save in progress\r\n"));
284 return;
285 }
286 if (rdbSave(server.dbfilename) == REDIS_OK) {
287 addReply(c,shared.ok);
288 } else {
289 addReply(c,shared.err);
290 }
291}
292
293void bgsaveCommand(redisClient *c) {
294 if (server.bgsavechildpid != -1) {
295 addReplySds(c,sdsnew("-ERR background save already in progress\r\n"));
296 return;
297 }
298 if (rdbSaveBackground(server.dbfilename) == REDIS_OK) {
299 char *status = "+Background saving started\r\n";
300 addReplySds(c,sdsnew(status));
301 } else {
302 addReply(c,shared.err);
303 }
304}
305
306void shutdownCommand(redisClient *c) {
307 if (prepareForShutdown() == REDIS_OK)
308 exit(0);
309 addReplySds(c, sdsnew("-ERR Errors trying to SHUTDOWN. Check logs.\r\n"));
310}
311
312void renameGenericCommand(redisClient *c, int nx) {
313 robj *o;
314
315 /* To use the same key as src and dst is probably an error */
316 if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
317 addReply(c,shared.sameobjecterr);
318 return;
319 }
320
321 if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
322 return;
323
324 incrRefCount(o);
325 deleteIfVolatile(c->db,c->argv[2]);
326 if (dbAdd(c->db,c->argv[2],o) == REDIS_ERR) {
327 if (nx) {
328 decrRefCount(o);
329 addReply(c,shared.czero);
330 return;
331 }
332 dbReplace(c->db,c->argv[2],o);
333 }
334 dbDelete(c->db,c->argv[1]);
335 touchWatchedKey(c->db,c->argv[2]);
336 server.dirty++;
337 addReply(c,nx ? shared.cone : shared.ok);
338}
339
340void renameCommand(redisClient *c) {
341 renameGenericCommand(c,0);
342}
343
344void renamenxCommand(redisClient *c) {
345 renameGenericCommand(c,1);
346}
347
348void moveCommand(redisClient *c) {
349 robj *o;
350 redisDb *src, *dst;
351 int srcid;
352
353 /* Obtain source and target DB pointers */
354 src = c->db;
355 srcid = c->db->id;
356 if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
357 addReply(c,shared.outofrangeerr);
358 return;
359 }
360 dst = c->db;
361 selectDb(c,srcid); /* Back to the source DB */
362
363 /* If the user is moving using as target the same
364 * DB as the source DB it is probably an error. */
365 if (src == dst) {
366 addReply(c,shared.sameobjecterr);
367 return;
368 }
369
370 /* Check if the element exists and get a reference */
371 o = lookupKeyWrite(c->db,c->argv[1]);
372 if (!o) {
373 addReply(c,shared.czero);
374 return;
375 }
376
377 /* Try to add the element to the target DB */
378 deleteIfVolatile(dst,c->argv[1]);
379 if (dbAdd(dst,c->argv[1],o) == REDIS_ERR) {
380 addReply(c,shared.czero);
381 return;
382 }
383 incrRefCount(o);
384
385 /* OK! key moved, free the entry in the source DB */
386 dbDelete(src,c->argv[1]);
387 server.dirty++;
388 addReply(c,shared.cone);
389}
390
391/*-----------------------------------------------------------------------------
392 * Expires API
393 *----------------------------------------------------------------------------*/
394
395int removeExpire(redisDb *db, robj *key) {
396 /* An expire may only be removed if there is a corresponding entry in the
397 * main dict. Otherwise, the key will never be freed. */
398 redisAssert(dictFind(db->dict,key->ptr) != NULL);
399 if (dictDelete(db->expires,key->ptr) == DICT_OK) {
400 return 1;
401 } else {
402 return 0;
403 }
404}
405
406int setExpire(redisDb *db, robj *key, time_t when) {
407 dictEntry *de;
408
409 /* Reuse the sds from the main dict in the expire dict */
410 redisAssert((de = dictFind(db->dict,key->ptr)) != NULL);
411 if (dictAdd(db->expires,dictGetEntryKey(de),(void*)when) == DICT_ERR) {
412 return 0;
413 } else {
414 return 1;
415 }
416}
417
418/* Return the expire time of the specified key, or -1 if no expire
419 * is associated with this key (i.e. the key is non volatile) */
420time_t getExpire(redisDb *db, robj *key) {
421 dictEntry *de;
422
423 /* No expire? return ASAP */
424 if (dictSize(db->expires) == 0 ||
425 (de = dictFind(db->expires,key->ptr)) == NULL) return -1;
426
427 /* The entry was found in the expire dict, this means it should also
428 * be present in the main dict (safety check). */
429 redisAssert(dictFind(db->dict,key->ptr) != NULL);
430 return (time_t) dictGetEntryVal(de);
431}
432
433int expireIfNeeded(redisDb *db, robj *key) {
434 time_t when = getExpire(db,key);
435 if (when < 0) return 0;
436
437 /* Return when this key has not expired */
438 if (time(NULL) <= when) return 0;
439
440 /* Delete the key */
441 server.stat_expiredkeys++;
442 server.dirty++;
443 return dbDelete(db,key);
444}
445
446int deleteIfVolatile(redisDb *db, robj *key) {
447 if (getExpire(db,key) < 0) return 0;
448
449 /* Delete the key */
450 server.stat_expiredkeys++;
451 server.dirty++;
452 return dbDelete(db,key);
453}
454
455/*-----------------------------------------------------------------------------
456 * Expires Commands
457 *----------------------------------------------------------------------------*/
458
459void expireGenericCommand(redisClient *c, robj *key, robj *param, long offset) {
460 dictEntry *de;
461 time_t seconds;
462
463 if (getLongFromObjectOrReply(c, param, &seconds, NULL) != REDIS_OK) return;
464
465 seconds -= offset;
466
467 de = dictFind(c->db->dict,key->ptr);
468 if (de == NULL) {
469 addReply(c,shared.czero);
470 return;
471 }
472 if (seconds <= 0) {
473 if (dbDelete(c->db,key)) server.dirty++;
474 addReply(c, shared.cone);
475 return;
476 } else {
477 time_t when = time(NULL)+seconds;
478 if (setExpire(c->db,key,when)) {
479 addReply(c,shared.cone);
480 server.dirty++;
481 } else {
482 addReply(c,shared.czero);
483 }
484 return;
485 }
486}
487
488void expireCommand(redisClient *c) {
489 expireGenericCommand(c,c->argv[1],c->argv[2],0);
490}
491
492void expireatCommand(redisClient *c) {
493 expireGenericCommand(c,c->argv[1],c->argv[2],time(NULL));
494}
495
496void ttlCommand(redisClient *c) {
497 time_t expire;
498 int ttl = -1;
499
500 expire = getExpire(c->db,c->argv[1]);
501 if (expire != -1) {
502 ttl = (int) (expire-time(NULL));
503 if (ttl < 0) ttl = -1;
504 }
505 addReplySds(c,sdscatprintf(sdsempty(),":%d\r\n",ttl));
506}
507
508