|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "math" |
| 5 | + "strconv" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/dicedb/dice/internal/errors" |
| 9 | + "github.com/dicedb/dice/internal/eval/sortedset" |
| 10 | + "github.com/dicedb/dice/internal/object" |
| 11 | + "github.com/dicedb/dice/internal/shardmanager" |
| 12 | + dsstore "github.com/dicedb/dice/internal/store" |
| 13 | +) |
| 14 | + |
| 15 | +var cZADD = &CommandMeta{ |
| 16 | + Name: "ZADD", |
| 17 | + Syntax: "ZADD key [NX | XX] [GT | LT] [CH] [INCR] score member [score member...]", |
| 18 | + HelpShort: "Adds all the specified members with the specified scores to the sorted set stored at key", |
| 19 | + HelpLong: ` |
| 20 | +Adds all the specified members with the specified scores to the sorted set stored at key |
| 21 | +Options: NX, XX, CH, INCR, GT, LT, CH |
| 22 | +- NX: Only add new elements and do not update existing elements |
| 23 | +- XX: Only update existing elements and do not add new elements |
| 24 | +- CH: Modify the return value from the number of new elements added, to the total number of elements changed |
| 25 | +- INCR: When this option is specified, the elements are treated as increments to the score of the existing elements |
| 26 | +- GT: Only add new elements if the score is greater than the existing score |
| 27 | +- LT: Only add new elements if the score is less than the existing score |
| 28 | +Returns the number of elements added to the sorted set, not including elements already existing for which the score was updated. |
| 29 | + `, |
| 30 | + Examples: ` |
| 31 | +localhost:7379> ZADD mySortedSet 1 foo 2 bar |
| 32 | +OK 2 |
| 33 | +`, |
| 34 | + Eval: evalZADD, |
| 35 | + Execute: executeZADD, |
| 36 | +} |
| 37 | + |
| 38 | +func init() { |
| 39 | + CommandRegistry.AddCommand(cZADD) |
| 40 | +} |
| 41 | + |
| 42 | +func evalZADD(c *Cmd, s *dsstore.Store) (*CmdRes, error) { |
| 43 | + if len(c.C.Args) < 3 { |
| 44 | + return cmdResNil, errors.ErrWrongArgumentCount("ZADD") |
| 45 | + } |
| 46 | + |
| 47 | + key := c.C.Args[0] |
| 48 | + params := map[float64]string{} |
| 49 | + flags := map[string]bool{} |
| 50 | + |
| 51 | + for i := 1; i < len(c.C.Args); i++ { |
| 52 | + arg := strings.ToUpper(c.C.Args[i]) |
| 53 | + switch arg { |
| 54 | + // Only valid options are allowed |
| 55 | + case "XX", "NX", "LT", "GT", "CH", "INCR": |
| 56 | + flags[arg] = true |
| 57 | + default: |
| 58 | + // This should be a float repesneting the score. If its not, its a problem. |
| 59 | + score, err := strconv.ParseFloat(arg, 64) |
| 60 | + if err != nil || math.IsNaN(score) { |
| 61 | + return cmdResNil, errors.ErrInvalidNumberFormat |
| 62 | + } |
| 63 | + if i+1 >= len(c.C.Args) { |
| 64 | + return cmdResNil, errors.ErrWrongArgumentCount("ZADD") |
| 65 | + } |
| 66 | + // Its a score-member pair |
| 67 | + params[score] = c.C.Args[i+1] |
| 68 | + i++ |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + if flags["NX"] && flags["XX"] { |
| 73 | + return cmdResNil, errors.ErrGeneral("XX and NX options at the same time are not compatible") |
| 74 | + } |
| 75 | + if (flags["GT"] && flags["NX"]) || (flags["LT"] && flags["NX"]) || (flags["GT"] && flags["LT"]) { |
| 76 | + return cmdResNil, errors.ErrGeneral("GT, LT, and/or NX options at the same time are not compatible") |
| 77 | + } |
| 78 | + if flags["INCR"] && len(params) > 1 { |
| 79 | + return cmdResNil, errors.ErrGeneral("INCR option supports a single increment-element pair") |
| 80 | + } |
| 81 | + sortedSet, err := getOrCreateSortedSet(s, key) |
| 82 | + if err != nil { |
| 83 | + return cmdResNil, err |
| 84 | + } |
| 85 | + // all processing takes place here |
| 86 | + return processMembersWithFlags(params, sortedSet, s, key, flags) |
| 87 | +} |
| 88 | + |
| 89 | +func executeZADD(c *Cmd, sm *shardmanager.ShardManager) (*CmdRes, error) { |
| 90 | + if len(c.C.Args) < 3 { |
| 91 | + return cmdResNil, errors.ErrWrongArgumentCount("ZADD") |
| 92 | + } |
| 93 | + |
| 94 | + shard := sm.GetShardForKey(c.C.Args[0]) |
| 95 | + return evalZADD(c, shard.Thread.Store()) |
| 96 | +} |
| 97 | + |
| 98 | +func getOrCreateSortedSet(store *dsstore.Store, key string) (*sortedset.Set, error) { |
| 99 | + obj := store.Get(key) |
| 100 | + if obj != nil { |
| 101 | + sortedSet, err := sortedset.FromObject(obj) |
| 102 | + if err != nil { |
| 103 | + return nil, errors.ErrWrongTypeOperation |
| 104 | + } |
| 105 | + return sortedSet, nil |
| 106 | + } |
| 107 | + return sortedset.New(), nil |
| 108 | +} |
| 109 | + |
| 110 | +// processMembersWithFlags processes the members and scores while handling flags. |
| 111 | +func processMembersWithFlags(params map[float64]string, sortedSet *sortedset.Set, store *dsstore.Store, key string, flags map[string]bool) (*CmdRes, error) { |
| 112 | + added, updated := 0, 0 |
| 113 | + |
| 114 | + for score, member := range params { |
| 115 | + currentScore, exists := sortedSet.Get(member) |
| 116 | + |
| 117 | + // If INCR is used, increment the score first |
| 118 | + if flags["INCR"] { |
| 119 | + if exists { |
| 120 | + score += currentScore |
| 121 | + } else { |
| 122 | + score = 0.0 + score |
| 123 | + } |
| 124 | + |
| 125 | + // Now check GT and LT conditions based on the incremented score and return accordingly |
| 126 | + if (flags["GT"] && exists && score <= currentScore) || |
| 127 | + (flags["LT"] && exists && score >= currentScore) { |
| 128 | + return nil, nil |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + // Check if the member should be skipped based on NX or XX flags |
| 133 | + if shouldSkipMember(score, currentScore, exists, flags) { |
| 134 | + continue |
| 135 | + } |
| 136 | + |
| 137 | + // Insert or update the member in the sorted set |
| 138 | + wasInserted := sortedSet.Upsert(score, member) |
| 139 | + |
| 140 | + if wasInserted && !exists { |
| 141 | + added++ |
| 142 | + } else if exists && score != currentScore { |
| 143 | + updated++ |
| 144 | + } |
| 145 | + |
| 146 | + // If INCR is used, exit after processing one score-member pair |
| 147 | + if flags["INCR"] { |
| 148 | + return cmdResFloat(score), nil |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + // Store the updated sorted set in the store |
| 153 | + storeUpdatedSet(store, key, sortedSet) |
| 154 | + |
| 155 | + if flags["CH"] { |
| 156 | + return cmdResInt(int64(added + updated)), nil |
| 157 | + } |
| 158 | + |
| 159 | + // Return only the count of added members |
| 160 | + return cmdResInt(int64(added)), nil |
| 161 | +} |
| 162 | + |
| 163 | +// shouldSkipMember determines if a member should be skipped based on flags. |
| 164 | +func shouldSkipMember(score, currentScore float64, exists bool, flags map[string]bool) bool { |
| 165 | + if flags["NX"] && exists || flags["XX"] && !exists { |
| 166 | + return true |
| 167 | + } |
| 168 | + if exists { |
| 169 | + if flags["LT"] && score >= currentScore { |
| 170 | + return true |
| 171 | + } |
| 172 | + if flags["GT"] && score <= currentScore { |
| 173 | + return true |
| 174 | + } |
| 175 | + } |
| 176 | + return false |
| 177 | +} |
| 178 | + |
| 179 | +// storeUpdatedSet stores the updated sorted set in the store. |
| 180 | +func storeUpdatedSet(store *dsstore.Store, key string, sortedSet *sortedset.Set) { |
| 181 | + store.Put(key, store.NewObj(sortedSet, -1, object.ObjTypeSortedSet), dsstore.WithPutCmd(dsstore.ZAdd)) |
| 182 | +} |
0 commit comments