]> git.saurik.com Git - redis.git/blob - src/t_zset.c
Use fstat to detect if stdin was redirected
[redis.git] / src / t_zset.c
1 #include "redis.h"
2
3 #include <math.h>
4
5 /*-----------------------------------------------------------------------------
6 * Sorted set API
7 *----------------------------------------------------------------------------*/
8
9 /* ZSETs are ordered sets using two data structures to hold the same elements
10 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
11 * data structure.
12 *
13 * The elements are added to an hash table mapping Redis objects to scores.
14 * At the same time the elements are added to a skip list mapping scores
15 * to Redis objects (so objects are sorted by scores in this "view"). */
16
17 /* This skiplist implementation is almost a C translation of the original
18 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
19 * Alternative to Balanced Trees", modified in three ways:
20 * a) this implementation allows for repeated values.
21 * b) the comparison is not just by key (our 'score') but by satellite data.
22 * c) there is a back pointer, so it's a doubly linked list with the back
23 * pointers being only at "level 1". This allows to traverse the list
24 * from tail to head, useful for ZREVRANGE. */
25
26 zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
27 zskiplistNode *zn = zmalloc(sizeof(*zn));
28
29 zn->forward = zmalloc(sizeof(zskiplistNode*) * level);
30 if (level > 1)
31 zn->span = zmalloc(sizeof(unsigned int) * (level - 1));
32 else
33 zn->span = NULL;
34 zn->score = score;
35 zn->obj = obj;
36 return zn;
37 }
38
39 zskiplist *zslCreate(void) {
40 int j;
41 zskiplist *zsl;
42
43 zsl = zmalloc(sizeof(*zsl));
44 zsl->level = 1;
45 zsl->length = 0;
46 zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
47 for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
48 zsl->header->forward[j] = NULL;
49
50 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
51 if (j < ZSKIPLIST_MAXLEVEL-1)
52 zsl->header->span[j] = 0;
53 }
54 zsl->header->backward = NULL;
55 zsl->tail = NULL;
56 return zsl;
57 }
58
59 void zslFreeNode(zskiplistNode *node) {
60 decrRefCount(node->obj);
61 zfree(node->forward);
62 zfree(node->span);
63 zfree(node);
64 }
65
66 void zslFree(zskiplist *zsl) {
67 zskiplistNode *node = zsl->header->forward[0], *next;
68
69 zfree(zsl->header->forward);
70 zfree(zsl->header->span);
71 zfree(zsl->header);
72 while(node) {
73 next = node->forward[0];
74 zslFreeNode(node);
75 node = next;
76 }
77 zfree(zsl);
78 }
79
80 int zslRandomLevel(void) {
81 int level = 1;
82 while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
83 level += 1;
84 return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
85 }
86
87 void zslInsert(zskiplist *zsl, double score, robj *obj) {
88 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
89 unsigned int rank[ZSKIPLIST_MAXLEVEL];
90 int i, level;
91
92 x = zsl->header;
93 for (i = zsl->level-1; i >= 0; i--) {
94 /* store rank that is crossed to reach the insert position */
95 rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
96
97 while (x->forward[i] &&
98 (x->forward[i]->score < score ||
99 (x->forward[i]->score == score &&
100 compareStringObjects(x->forward[i]->obj,obj) < 0))) {
101 rank[i] += i > 0 ? x->span[i-1] : 1;
102 x = x->forward[i];
103 }
104 update[i] = x;
105 }
106 /* we assume the key is not already inside, since we allow duplicated
107 * scores, and the re-insertion of score and redis object should never
108 * happpen since the caller of zslInsert() should test in the hash table
109 * if the element is already inside or not. */
110 level = zslRandomLevel();
111 if (level > zsl->level) {
112 for (i = zsl->level; i < level; i++) {
113 rank[i] = 0;
114 update[i] = zsl->header;
115 update[i]->span[i-1] = zsl->length;
116 }
117 zsl->level = level;
118 }
119 x = zslCreateNode(level,score,obj);
120 for (i = 0; i < level; i++) {
121 x->forward[i] = update[i]->forward[i];
122 update[i]->forward[i] = x;
123
124 /* update span covered by update[i] as x is inserted here */
125 if (i > 0) {
126 x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]);
127 update[i]->span[i-1] = (rank[0] - rank[i]) + 1;
128 }
129 }
130
131 /* increment span for untouched levels */
132 for (i = level; i < zsl->level; i++) {
133 update[i]->span[i-1]++;
134 }
135
136 x->backward = (update[0] == zsl->header) ? NULL : update[0];
137 if (x->forward[0])
138 x->forward[0]->backward = x;
139 else
140 zsl->tail = x;
141 zsl->length++;
142 }
143
144 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
145 void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
146 int i;
147 for (i = 0; i < zsl->level; i++) {
148 if (update[i]->forward[i] == x) {
149 if (i > 0) {
150 update[i]->span[i-1] += x->span[i-1] - 1;
151 }
152 update[i]->forward[i] = x->forward[i];
153 } else {
154 /* invariant: i > 0, because update[0]->forward[0]
155 * is always equal to x */
156 update[i]->span[i-1] -= 1;
157 }
158 }
159 if (x->forward[0]) {
160 x->forward[0]->backward = x->backward;
161 } else {
162 zsl->tail = x->backward;
163 }
164 while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL)
165 zsl->level--;
166 zsl->length--;
167 }
168
169 /* Delete an element with matching score/object from the skiplist. */
170 int zslDelete(zskiplist *zsl, double score, robj *obj) {
171 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
172 int i;
173
174 x = zsl->header;
175 for (i = zsl->level-1; i >= 0; i--) {
176 while (x->forward[i] &&
177 (x->forward[i]->score < score ||
178 (x->forward[i]->score == score &&
179 compareStringObjects(x->forward[i]->obj,obj) < 0)))
180 x = x->forward[i];
181 update[i] = x;
182 }
183 /* We may have multiple elements with the same score, what we need
184 * is to find the element with both the right score and object. */
185 x = x->forward[0];
186 if (x && score == x->score && equalStringObjects(x->obj,obj)) {
187 zslDeleteNode(zsl, x, update);
188 zslFreeNode(x);
189 return 1;
190 } else {
191 return 0; /* not found */
192 }
193 return 0; /* not found */
194 }
195
196 /* Delete all the elements with score between min and max from the skiplist.
197 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
198 * Note that this function takes the reference to the hash table view of the
199 * sorted set, in order to remove the elements from the hash table too. */
200 unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) {
201 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
202 unsigned long removed = 0;
203 int i;
204
205 x = zsl->header;
206 for (i = zsl->level-1; i >= 0; i--) {
207 while (x->forward[i] && x->forward[i]->score < min)
208 x = x->forward[i];
209 update[i] = x;
210 }
211 /* We may have multiple elements with the same score, what we need
212 * is to find the element with both the right score and object. */
213 x = x->forward[0];
214 while (x && x->score <= max) {
215 zskiplistNode *next = x->forward[0];
216 zslDeleteNode(zsl, x, update);
217 dictDelete(dict,x->obj);
218 zslFreeNode(x);
219 removed++;
220 x = next;
221 }
222 return removed; /* not found */
223 }
224
225 /* Delete all the elements with rank between start and end from the skiplist.
226 * Start and end are inclusive. Note that start and end need to be 1-based */
227 unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
228 zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
229 unsigned long traversed = 0, removed = 0;
230 int i;
231
232 x = zsl->header;
233 for (i = zsl->level-1; i >= 0; i--) {
234 while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) {
235 traversed += i > 0 ? x->span[i-1] : 1;
236 x = x->forward[i];
237 }
238 update[i] = x;
239 }
240
241 traversed++;
242 x = x->forward[0];
243 while (x && traversed <= end) {
244 zskiplistNode *next = x->forward[0];
245 zslDeleteNode(zsl, x, update);
246 dictDelete(dict,x->obj);
247 zslFreeNode(x);
248 removed++;
249 traversed++;
250 x = next;
251 }
252 return removed;
253 }
254
255 /* Find the first node having a score equal or greater than the specified one.
256 * Returns NULL if there is no match. */
257 zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
258 zskiplistNode *x;
259 int i;
260
261 x = zsl->header;
262 for (i = zsl->level-1; i >= 0; i--) {
263 while (x->forward[i] && x->forward[i]->score < score)
264 x = x->forward[i];
265 }
266 /* We may have multiple elements with the same score, what we need
267 * is to find the element with both the right score and object. */
268 return x->forward[0];
269 }
270
271 /* Find the rank for an element by both score and key.
272 * Returns 0 when the element cannot be found, rank otherwise.
273 * Note that the rank is 1-based due to the span of zsl->header to the
274 * first element. */
275 unsigned long zslistTypeGetRank(zskiplist *zsl, double score, robj *o) {
276 zskiplistNode *x;
277 unsigned long rank = 0;
278 int i;
279
280 x = zsl->header;
281 for (i = zsl->level-1; i >= 0; i--) {
282 while (x->forward[i] &&
283 (x->forward[i]->score < score ||
284 (x->forward[i]->score == score &&
285 compareStringObjects(x->forward[i]->obj,o) <= 0))) {
286 rank += i > 0 ? x->span[i-1] : 1;
287 x = x->forward[i];
288 }
289
290 /* x might be equal to zsl->header, so test if obj is non-NULL */
291 if (x->obj && equalStringObjects(x->obj,o)) {
292 return rank;
293 }
294 }
295 return 0;
296 }
297
298 /* Finds an element by its rank. The rank argument needs to be 1-based. */
299 zskiplistNode* zslistTypeGetElementByRank(zskiplist *zsl, unsigned long rank) {
300 zskiplistNode *x;
301 unsigned long traversed = 0;
302 int i;
303
304 x = zsl->header;
305 for (i = zsl->level-1; i >= 0; i--) {
306 while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank)
307 {
308 traversed += i > 0 ? x->span[i-1] : 1;
309 x = x->forward[i];
310 }
311 if (traversed == rank) {
312 return x;
313 }
314 }
315 return NULL;
316 }
317
318 /*-----------------------------------------------------------------------------
319 * Sorted set commands
320 *----------------------------------------------------------------------------*/
321
322 /* This generic command implements both ZADD and ZINCRBY.
323 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
324 * the increment if the operation is a ZINCRBY (doincrement == 1). */
325 void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) {
326 robj *zsetobj;
327 zset *zs;
328 double *score;
329
330 zsetobj = lookupKeyWrite(c->db,key);
331 if (zsetobj == NULL) {
332 zsetobj = createZsetObject();
333 dbAdd(c->db,key,zsetobj);
334 } else {
335 if (zsetobj->type != REDIS_ZSET) {
336 addReply(c,shared.wrongtypeerr);
337 return;
338 }
339 }
340 zs = zsetobj->ptr;
341
342 /* Ok now since we implement both ZADD and ZINCRBY here the code
343 * needs to handle the two different conditions. It's all about setting
344 * '*score', that is, the new score to set, to the right value. */
345 score = zmalloc(sizeof(double));
346 if (doincrement) {
347 dictEntry *de;
348
349 /* Read the old score. If the element was not present starts from 0 */
350 de = dictFind(zs->dict,ele);
351 if (de) {
352 double *oldscore = dictGetEntryVal(de);
353 *score = *oldscore + scoreval;
354 } else {
355 *score = scoreval;
356 }
357 if (isnan(*score)) {
358 addReplySds(c,
359 sdsnew("-ERR resulting score is not a number (NaN)\r\n"));
360 zfree(score);
361 /* Note that we don't need to check if the zset may be empty and
362 * should be removed here, as we can only obtain Nan as score if
363 * there was already an element in the sorted set. */
364 return;
365 }
366 } else {
367 *score = scoreval;
368 }
369
370 /* What follows is a simple remove and re-insert operation that is common
371 * to both ZADD and ZINCRBY... */
372 if (dictAdd(zs->dict,ele,score) == DICT_OK) {
373 /* case 1: New element */
374 incrRefCount(ele); /* added to hash */
375 zslInsert(zs->zsl,*score,ele);
376 incrRefCount(ele); /* added to skiplist */
377 touchWatchedKey(c->db,c->argv[1]);
378 server.dirty++;
379 if (doincrement)
380 addReplyDouble(c,*score);
381 else
382 addReply(c,shared.cone);
383 } else {
384 dictEntry *de;
385 double *oldscore;
386
387 /* case 2: Score update operation */
388 de = dictFind(zs->dict,ele);
389 redisAssert(de != NULL);
390 oldscore = dictGetEntryVal(de);
391 if (*score != *oldscore) {
392 int deleted;
393
394 /* Remove and insert the element in the skip list with new score */
395 deleted = zslDelete(zs->zsl,*oldscore,ele);
396 redisAssert(deleted != 0);
397 zslInsert(zs->zsl,*score,ele);
398 incrRefCount(ele);
399 /* Update the score in the hash table */
400 dictReplace(zs->dict,ele,score);
401 touchWatchedKey(c->db,c->argv[1]);
402 server.dirty++;
403 } else {
404 zfree(score);
405 }
406 if (doincrement)
407 addReplyDouble(c,*score);
408 else
409 addReply(c,shared.czero);
410 }
411 }
412
413 void zaddCommand(redisClient *c) {
414 double scoreval;
415 if (getDoubleFromObjectOrReply(c,c->argv[2],&scoreval,NULL) != REDIS_OK) return;
416 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
417 }
418
419 void zincrbyCommand(redisClient *c) {
420 double scoreval;
421 if (getDoubleFromObjectOrReply(c,c->argv[2],&scoreval,NULL) != REDIS_OK) return;
422 zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
423 }
424
425 void zremCommand(redisClient *c) {
426 robj *zsetobj;
427 zset *zs;
428 dictEntry *de;
429 double *oldscore;
430 int deleted;
431
432 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
433 checkType(c,zsetobj,REDIS_ZSET)) return;
434
435 zs = zsetobj->ptr;
436 de = dictFind(zs->dict,c->argv[2]);
437 if (de == NULL) {
438 addReply(c,shared.czero);
439 return;
440 }
441 /* Delete from the skiplist */
442 oldscore = dictGetEntryVal(de);
443 deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]);
444 redisAssert(deleted != 0);
445
446 /* Delete from the hash table */
447 dictDelete(zs->dict,c->argv[2]);
448 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
449 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
450 touchWatchedKey(c->db,c->argv[1]);
451 server.dirty++;
452 addReply(c,shared.cone);
453 }
454
455 void zremrangebyscoreCommand(redisClient *c) {
456 double min;
457 double max;
458 long deleted;
459 robj *zsetobj;
460 zset *zs;
461
462 if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) ||
463 (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return;
464
465 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
466 checkType(c,zsetobj,REDIS_ZSET)) return;
467
468 zs = zsetobj->ptr;
469 deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict);
470 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
471 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
472 if (deleted) touchWatchedKey(c->db,c->argv[1]);
473 server.dirty += deleted;
474 addReplyLongLong(c,deleted);
475 }
476
477 void zremrangebyrankCommand(redisClient *c) {
478 long start;
479 long end;
480 int llen;
481 long deleted;
482 robj *zsetobj;
483 zset *zs;
484
485 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
486 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
487
488 if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
489 checkType(c,zsetobj,REDIS_ZSET)) return;
490 zs = zsetobj->ptr;
491 llen = zs->zsl->length;
492
493 /* convert negative indexes */
494 if (start < 0) start = llen+start;
495 if (end < 0) end = llen+end;
496 if (start < 0) start = 0;
497
498 /* Invariant: start >= 0, so this test will be true when end < 0.
499 * The range is empty when start > end or start >= length. */
500 if (start > end || start >= llen) {
501 addReply(c,shared.czero);
502 return;
503 }
504 if (end >= llen) end = llen-1;
505
506 /* increment start and end because zsl*Rank functions
507 * use 1-based rank */
508 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
509 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
510 if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
511 if (deleted) touchWatchedKey(c->db,c->argv[1]);
512 server.dirty += deleted;
513 addReplyLongLong(c, deleted);
514 }
515
516 typedef struct {
517 dict *dict;
518 double weight;
519 } zsetopsrc;
520
521 int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
522 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
523 unsigned long size1, size2;
524 size1 = d1->dict ? dictSize(d1->dict) : 0;
525 size2 = d2->dict ? dictSize(d2->dict) : 0;
526 return size1 - size2;
527 }
528
529 #define REDIS_AGGR_SUM 1
530 #define REDIS_AGGR_MIN 2
531 #define REDIS_AGGR_MAX 3
532 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
533
534 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
535 if (aggregate == REDIS_AGGR_SUM) {
536 *target = *target + val;
537 /* The result of adding two doubles is NaN when one variable
538 * is +inf and the other is -inf. When these numbers are added,
539 * we maintain the convention of the result being 0.0. */
540 if (isnan(*target)) *target = 0.0;
541 } else if (aggregate == REDIS_AGGR_MIN) {
542 *target = val < *target ? val : *target;
543 } else if (aggregate == REDIS_AGGR_MAX) {
544 *target = val > *target ? val : *target;
545 } else {
546 /* safety net */
547 redisPanic("Unknown ZUNION/INTER aggregate type");
548 }
549 }
550
551 void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
552 int i, j, setnum;
553 int aggregate = REDIS_AGGR_SUM;
554 zsetopsrc *src;
555 robj *dstobj;
556 zset *dstzset;
557 dictIterator *di;
558 dictEntry *de;
559 int touched = 0;
560
561 /* expect setnum input keys to be given */
562 setnum = atoi(c->argv[2]->ptr);
563 if (setnum < 1) {
564 addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
565 return;
566 }
567
568 /* test if the expected number of keys would overflow */
569 if (3+setnum > c->argc) {
570 addReply(c,shared.syntaxerr);
571 return;
572 }
573
574 /* read keys to be used for input */
575 src = zmalloc(sizeof(zsetopsrc) * setnum);
576 for (i = 0, j = 3; i < setnum; i++, j++) {
577 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
578 if (!obj) {
579 src[i].dict = NULL;
580 } else {
581 if (obj->type == REDIS_ZSET) {
582 src[i].dict = ((zset*)obj->ptr)->dict;
583 } else if (obj->type == REDIS_SET) {
584 src[i].dict = (obj->ptr);
585 } else {
586 zfree(src);
587 addReply(c,shared.wrongtypeerr);
588 return;
589 }
590 }
591
592 /* default all weights to 1 */
593 src[i].weight = 1.0;
594 }
595
596 /* parse optional extra arguments */
597 if (j < c->argc) {
598 int remaining = c->argc - j;
599
600 while (remaining) {
601 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
602 j++; remaining--;
603 for (i = 0; i < setnum; i++, j++, remaining--) {
604 if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
605 "weight value is not a double") != REDIS_OK)
606 {
607 zfree(src);
608 return;
609 }
610 }
611 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
612 j++; remaining--;
613 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
614 aggregate = REDIS_AGGR_SUM;
615 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
616 aggregate = REDIS_AGGR_MIN;
617 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
618 aggregate = REDIS_AGGR_MAX;
619 } else {
620 zfree(src);
621 addReply(c,shared.syntaxerr);
622 return;
623 }
624 j++; remaining--;
625 } else {
626 zfree(src);
627 addReply(c,shared.syntaxerr);
628 return;
629 }
630 }
631 }
632
633 /* sort sets from the smallest to largest, this will improve our
634 * algorithm's performance */
635 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
636
637 dstobj = createZsetObject();
638 dstzset = dstobj->ptr;
639
640 if (op == REDIS_OP_INTER) {
641 /* skip going over all entries if the smallest zset is NULL or empty */
642 if (src[0].dict && dictSize(src[0].dict) > 0) {
643 /* precondition: as src[0].dict is non-empty and the zsets are ordered
644 * from small to large, all src[i > 0].dict are non-empty too */
645 di = dictGetIterator(src[0].dict);
646 while((de = dictNext(di)) != NULL) {
647 double *score = zmalloc(sizeof(double)), value;
648 *score = src[0].weight * zunionInterDictValue(de);
649
650 for (j = 1; j < setnum; j++) {
651 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
652 if (other) {
653 value = src[j].weight * zunionInterDictValue(other);
654 zunionInterAggregate(score, value, aggregate);
655 } else {
656 break;
657 }
658 }
659
660 /* skip entry when not present in every source dict */
661 if (j != setnum) {
662 zfree(score);
663 } else {
664 robj *o = dictGetEntryKey(de);
665 dictAdd(dstzset->dict,o,score);
666 incrRefCount(o); /* added to dictionary */
667 zslInsert(dstzset->zsl,*score,o);
668 incrRefCount(o); /* added to skiplist */
669 }
670 }
671 dictReleaseIterator(di);
672 }
673 } else if (op == REDIS_OP_UNION) {
674 for (i = 0; i < setnum; i++) {
675 if (!src[i].dict) continue;
676
677 di = dictGetIterator(src[i].dict);
678 while((de = dictNext(di)) != NULL) {
679 /* skip key when already processed */
680 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue;
681
682 double *score = zmalloc(sizeof(double)), value;
683 *score = src[i].weight * zunionInterDictValue(de);
684
685 /* because the zsets are sorted by size, its only possible
686 * for sets at larger indices to hold this entry */
687 for (j = (i+1); j < setnum; j++) {
688 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
689 if (other) {
690 value = src[j].weight * zunionInterDictValue(other);
691 zunionInterAggregate(score, value, aggregate);
692 }
693 }
694
695 robj *o = dictGetEntryKey(de);
696 dictAdd(dstzset->dict,o,score);
697 incrRefCount(o); /* added to dictionary */
698 zslInsert(dstzset->zsl,*score,o);
699 incrRefCount(o); /* added to skiplist */
700 }
701 dictReleaseIterator(di);
702 }
703 } else {
704 /* unknown operator */
705 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
706 }
707
708 if (dbDelete(c->db,dstkey)) {
709 touchWatchedKey(c->db,dstkey);
710 touched = 1;
711 server.dirty++;
712 }
713 if (dstzset->zsl->length) {
714 dbAdd(c->db,dstkey,dstobj);
715 addReplyLongLong(c, dstzset->zsl->length);
716 if (!touched) touchWatchedKey(c->db,dstkey);
717 server.dirty++;
718 } else {
719 decrRefCount(dstobj);
720 addReply(c, shared.czero);
721 }
722 zfree(src);
723 }
724
725 void zunionstoreCommand(redisClient *c) {
726 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
727 }
728
729 void zinterstoreCommand(redisClient *c) {
730 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
731 }
732
733 void zrangeGenericCommand(redisClient *c, int reverse) {
734 robj *o;
735 long start;
736 long end;
737 int withscores = 0;
738 int llen;
739 int rangelen, j;
740 zset *zsetobj;
741 zskiplist *zsl;
742 zskiplistNode *ln;
743 robj *ele;
744
745 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
746 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
747
748 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
749 withscores = 1;
750 } else if (c->argc >= 5) {
751 addReply(c,shared.syntaxerr);
752 return;
753 }
754
755 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
756 || checkType(c,o,REDIS_ZSET)) return;
757 zsetobj = o->ptr;
758 zsl = zsetobj->zsl;
759 llen = zsl->length;
760
761 /* convert negative indexes */
762 if (start < 0) start = llen+start;
763 if (end < 0) end = llen+end;
764 if (start < 0) start = 0;
765
766 /* Invariant: start >= 0, so this test will be true when end < 0.
767 * The range is empty when start > end or start >= length. */
768 if (start > end || start >= llen) {
769 addReply(c,shared.emptymultibulk);
770 return;
771 }
772 if (end >= llen) end = llen-1;
773 rangelen = (end-start)+1;
774
775 /* check if starting point is trivial, before searching
776 * the element in log(N) time */
777 if (reverse) {
778 ln = start == 0 ? zsl->tail : zslistTypeGetElementByRank(zsl, llen-start);
779 } else {
780 ln = start == 0 ?
781 zsl->header->forward[0] : zslistTypeGetElementByRank(zsl, start+1);
782 }
783
784 /* Return the result in form of a multi-bulk reply */
785 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",
786 withscores ? (rangelen*2) : rangelen));
787 for (j = 0; j < rangelen; j++) {
788 ele = ln->obj;
789 addReplyBulk(c,ele);
790 if (withscores)
791 addReplyDouble(c,ln->score);
792 ln = reverse ? ln->backward : ln->forward[0];
793 }
794 }
795
796 void zrangeCommand(redisClient *c) {
797 zrangeGenericCommand(c,0);
798 }
799
800 void zrevrangeCommand(redisClient *c) {
801 zrangeGenericCommand(c,1);
802 }
803
804 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
805 * If justcount is non-zero, just the count is returned. */
806 void genericZrangebyscoreCommand(redisClient *c, int justcount) {
807 robj *o;
808 double min, max;
809 int minex = 0, maxex = 0; /* are min or max exclusive? */
810 int offset = 0, limit = -1;
811 int withscores = 0;
812 int badsyntax = 0;
813
814 /* Parse the min-max interval. If one of the values is prefixed
815 * by the "(" character, it's considered "open". For instance
816 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
817 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
818 if (((char*)c->argv[2]->ptr)[0] == '(') {
819 min = strtod((char*)c->argv[2]->ptr+1,NULL);
820 minex = 1;
821 } else {
822 min = strtod(c->argv[2]->ptr,NULL);
823 }
824 if (((char*)c->argv[3]->ptr)[0] == '(') {
825 max = strtod((char*)c->argv[3]->ptr+1,NULL);
826 maxex = 1;
827 } else {
828 max = strtod(c->argv[3]->ptr,NULL);
829 }
830
831 /* Parse "WITHSCORES": note that if the command was called with
832 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
833 * enter the following paths to parse WITHSCORES and LIMIT. */
834 if (c->argc == 5 || c->argc == 8) {
835 if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0)
836 withscores = 1;
837 else
838 badsyntax = 1;
839 }
840 if (c->argc != (4 + withscores) && c->argc != (7 + withscores))
841 badsyntax = 1;
842 if (badsyntax) {
843 addReplySds(c,
844 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
845 return;
846 }
847
848 /* Parse "LIMIT" */
849 if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) {
850 addReply(c,shared.syntaxerr);
851 return;
852 } else if (c->argc == (7 + withscores)) {
853 offset = atoi(c->argv[5]->ptr);
854 limit = atoi(c->argv[6]->ptr);
855 if (offset < 0) offset = 0;
856 }
857
858 /* Ok, lookup the key and get the range */
859 o = lookupKeyRead(c->db,c->argv[1]);
860 if (o == NULL) {
861 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
862 } else {
863 if (o->type != REDIS_ZSET) {
864 addReply(c,shared.wrongtypeerr);
865 } else {
866 zset *zsetobj = o->ptr;
867 zskiplist *zsl = zsetobj->zsl;
868 zskiplistNode *ln;
869 robj *ele, *lenobj = NULL;
870 unsigned long rangelen = 0;
871
872 /* Get the first node with the score >= min, or with
873 * score > min if 'minex' is true. */
874 ln = zslFirstWithScore(zsl,min);
875 while (minex && ln && ln->score == min) ln = ln->forward[0];
876
877 if (ln == NULL) {
878 /* No element matching the speciifed interval */
879 addReply(c,justcount ? shared.czero : shared.emptymultibulk);
880 return;
881 }
882
883 /* We don't know in advance how many matching elements there
884 * are in the list, so we push this object that will represent
885 * the multi-bulk length in the output buffer, and will "fix"
886 * it later */
887 if (!justcount) {
888 lenobj = createObject(REDIS_STRING,NULL);
889 addReply(c,lenobj);
890 decrRefCount(lenobj);
891 }
892
893 while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) {
894 if (offset) {
895 offset--;
896 ln = ln->forward[0];
897 continue;
898 }
899 if (limit == 0) break;
900 if (!justcount) {
901 ele = ln->obj;
902 addReplyBulk(c,ele);
903 if (withscores)
904 addReplyDouble(c,ln->score);
905 }
906 ln = ln->forward[0];
907 rangelen++;
908 if (limit > 0) limit--;
909 }
910 if (justcount) {
911 addReplyLongLong(c,(long)rangelen);
912 } else {
913 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",
914 withscores ? (rangelen*2) : rangelen);
915 }
916 }
917 }
918 }
919
920 void zrangebyscoreCommand(redisClient *c) {
921 genericZrangebyscoreCommand(c,0);
922 }
923
924 void zcountCommand(redisClient *c) {
925 genericZrangebyscoreCommand(c,1);
926 }
927
928 void zcardCommand(redisClient *c) {
929 robj *o;
930 zset *zs;
931
932 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
933 checkType(c,o,REDIS_ZSET)) return;
934
935 zs = o->ptr;
936 addReplyUlong(c,zs->zsl->length);
937 }
938
939 void zscoreCommand(redisClient *c) {
940 robj *o;
941 zset *zs;
942 dictEntry *de;
943
944 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
945 checkType(c,o,REDIS_ZSET)) return;
946
947 zs = o->ptr;
948 de = dictFind(zs->dict,c->argv[2]);
949 if (!de) {
950 addReply(c,shared.nullbulk);
951 } else {
952 double *score = dictGetEntryVal(de);
953
954 addReplyDouble(c,*score);
955 }
956 }
957
958 void zrankGenericCommand(redisClient *c, int reverse) {
959 robj *o;
960 zset *zs;
961 zskiplist *zsl;
962 dictEntry *de;
963 unsigned long rank;
964 double *score;
965
966 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
967 checkType(c,o,REDIS_ZSET)) return;
968
969 zs = o->ptr;
970 zsl = zs->zsl;
971 de = dictFind(zs->dict,c->argv[2]);
972 if (!de) {
973 addReply(c,shared.nullbulk);
974 return;
975 }
976
977 score = dictGetEntryVal(de);
978 rank = zslistTypeGetRank(zsl, *score, c->argv[2]);
979 if (rank) {
980 if (reverse) {
981 addReplyLongLong(c, zsl->length - rank);
982 } else {
983 addReplyLongLong(c, rank-1);
984 }
985 } else {
986 addReply(c,shared.nullbulk);
987 }
988 }
989
990 void zrankCommand(redisClient *c) {
991 zrankGenericCommand(c, 0);
992 }
993
994 void zrevrankCommand(redisClient *c) {
995 zrankGenericCommand(c, 1);
996 }