before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
package logger
import (
"io"
"log/slog"
"os"
"github.com/dicedb/dice/config"
"github.com/rs/zerolog"
)
func getLogLevel() slog.Leveler {
var level slog.Leveler
switch config.DiceConfig.Server.LogLevel {
case "debug":
level = slog.LevelDebug
case "info":
level = slog.LevelInfo
case "warn":
level = slo... | Same as above, remove `case "info"` as default will take care of it to reduce code redundancy. | package logger
import (
"io"
"log/slog"
"os"
"github.com/dicedb/dice/config"
"github.com/rs/zerolog"
)
func getLogLevel() slog.Leveler {
var level slog.Leveler
switch config.DiceConfig.Server.LogLevel {
case "debug":
level = slog.LevelDebug
case "warn":
level = slog.LevelWarn
case "error":
level = sl... | @@ -0,0 +1,45 @@
+package logger
+
+import (
+ "io"
+ "log/slog"
+ "os"
+
+ "github.com/dicedb/dice/config"
+ "github.com/rs/zerolog"
+)
+
+func getLogLevel() slog.Leveler {
+ var level slog.Leveler
+ switch config.DiceConfig.Server.LogLevel {
+ case "debug":
+ level = slog.LevelDebug
+ case "info":
+ level = slog.Le... | internal/logger/logger.go | 18 | Go | 0.429 | suggestion | 94 | 43 | 43 | false | Setup slog with zerolog | 584 | DiceDB/dice | 10,326 | C | vinitparekh17 | KaviiSuri |
switch utils.GetJSONFieldType(jsonData) {
case utils.NumberType:
oldVal := jsonData.(float64)
if isIncrFloat {
jsonData = oldVal + incrFloat
} else {
jsonData = oldVal + float64(incrInt)
}
resultArray = append(resultArray, formatFloat(jsonData.(float64), isIncrFloat))
case utils.IntegerType... | Use Modify instead of MustModify. We can't panic in case of an invalid expression - this means that if a user sends an invalid string the server crashes. | }
if err := object.AssertEncoding(obj.TypeEncoding, object.ObjEncodingSetStr); err != nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
// only if the count is greater than 0, we need to check the other sets
if count > 0 {
// Get the set object.
set := obj.Value.(map[str... | @@ -2782,3 +2783,153 @@ func evalSELECT(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+
+func formatFloat(f float64, b bool) string {
+ formatted := strconv.FormatFloat(f, 'f', -1, 64)
+ if b {
+ parts := strings.Split(formatted, ".")
+ if len(parts) == 1 {
+ formatted += ".0"
+ }
+ }
... | internal/eval/eval.go | 26 | Go | 0.429 | bug | 153 | 51 | 51 | false | #496: Feature `JSON.NUMINCRBY` | 585 | DiceDB/dice | 10,326 | C | JyotinderSingh | apoorvyadav1111 |
package eval
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracelet/log"
"github.com/dicedb/dic... | There is a lot of code duplication here.
You can replace this with:
```go
if path == defaultRootPath {
newValue, resultString, modified := incrementValue(jsonData, isIncrFloat, incrFloat, incrInt)
if modified {
jsonData = newValue
}
resultArray = append(resultArray, resultString)
} else {
_, ... |
if len(results) == 0 {
respString := "[]"
return clientio.Encode(respString, false)
}
resultArray := make([]string, 0, len(results))
if path == defaultRootPath {
newValue, resultString, isModified := incrementValue(jsonData, isIncrFloat, incrFloat, incrInt)
if isModified {
jsonData = newValue
}
re... | @@ -2782,3 +2783,153 @@ func evalSELECT(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+
+func formatFloat(f float64, b bool) string {
+ formatted := strconv.FormatFloat(f, 'f', -1, 64)
+ if b {
+ parts := strings.Split(formatted, ".")
+ if len(parts) == 1 {
+ formatted += ".0"
+ }
+ }
... | internal/eval/eval.go | 26 | Go | 1 | suggestion | 1,571 | 2,936 | 32 | false | #496: Feature `JSON.NUMINCRBY` | 585 | DiceDB/dice | 10,326 | C | JyotinderSingh | apoorvyadav1111 |
resultArray = append(resultArray, resultString)
return newValue, isModified
})
if err != nil {
return diceerrors.NewErrWithMessage("invalid JSONPath")
}
}
resultString := `[` + strings.Join(resultArray, ",") + `]`
newObj := &object.Obj{
Value: jsonData,
TypeEncoding: object.ObjTypeJSON,
... | I think you may not need this chunk of code.
We can probably just replace this with:
```suggestion
obj.Value = jsonData
```
| package eval
import (
"bytes"
"errors"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracelet/log"
"g... | @@ -3174,3 +3175,147 @@ func evalSELECT(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+
+func formatFloat(f float64, b bool) string {
+ formatted := strconv.FormatFloat(f, 'f', -1, 64)
+ if b {
+ parts := strings.Split(formatted, ".")
+ if len(parts) == 1 {
+ formatted += ".0"
+ }
+ }
... | internal/eval/eval.go | 26 | Go | 0.786 | suggestion | 126 | 29 | 3,306 | false | #496: Feature `JSON.NUMINCRBY` | 585 | DiceDB/dice | 10,326 | C | JyotinderSingh | apoorvyadav1111 |
}
}
// evalDBSIZE returns the number of keys in the database.
func evalDBSIZE(args []string, store *dstore.Store) []byte {
if len(args) > 0 {
return diceerrors.NewErrArity("DBSIZE")
}
// return the RESP encoded value
return clientio.Encode(dstore.KeyspaceStat[0]["keys"], false)
}
// evalGETDEL returns the val... | ```suggestion
// getting the key based on previous touch value
``` | }
}
// evalDBSIZE returns the number of keys in the database.
func evalDBSIZE(args []string, store *dstore.Store) []byte {
if len(args) > 0 {
return diceerrors.NewErrArity("DBSIZE")
}
// return the RESP encoded value
return clientio.Encode(dstore.KeyspaceStat[0]["keys"], false)
}
// evalGETDEL returns the val... | @@ -311,21 +311,53 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
key := args[0]
- // Get the key from the hash table
- obj := store.GetDel(key)
+ //Getting the key based on previous touch value | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 69 | 51 | 51 | false | Enhance GETDEL to handle Set, JSON,ByteArray, String, and Integer and Expand Test Coverage | 586 | DiceDB/dice | 10,326 | C | JyotinderSingh | rushabhk04 |
// evalDBSIZE returns the number of keys in the database.
func evalDBSIZE(args []string, store *dstore.Store) []byte {
if len(args) > 0 {
return diceerrors.NewErrArity("DBSIZE")
}
// return the RESP encoded value
return clientio.Encode(dstore.KeyspaceStat[0]["keys"], false)
}
// evalGETDEL returns the value for... | ```suggestion
// if key does not exist, return RESP encoded nil
``` | // evalDBSIZE returns the number of keys in the database.
func evalDBSIZE(args []string, store *dstore.Store) []byte {
if len(args) > 0 {
return diceerrors.NewErrArity("DBSIZE")
}
// return the RESP encoded value
return clientio.Encode(dstore.KeyspaceStat[0]["keys"], false)
}
// evalGETDEL returns the value for... | @@ -311,21 +311,53 @@ func evalGETDEL(args []string, store *dstore.Store) []byte {
key := args[0]
- // Get the key from the hash table
- obj := store.GetDel(key)
+ //Getting the key based on previous touch value
+ obj := store.GetNoTouch(key)
- // if key does not exist, return RESP encoded nil
+ //Check if obj ... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 70 | 51 | 51 | false | Enhance GETDEL to handle Set, JSON,ByteArray, String, and Integer and Expand Test Coverage | 586 | DiceDB/dice | 10,326 | C | JyotinderSingh | rushabhk04 |
}
// evalJSONINGEST stores a value at a dynamically generated key
// The key is created using a provided key prefix combined with a unique identifier
// args must contains key_prefix and json value
// Returns encoded error response if incorrect number of arguments
// Returns encoded error if the JSON string is invalid... | Please correct me if I'm missing something, can we not use a call to `JSONSET` here? | default:
return diceerrors.NewErrWithMessage(diceerrors.SyntaxErr)
}
}
// Parse the JSON string
var jsonValue interface{}
if err := sonic.UnmarshalString(jsonStr, &jsonValue); err != nil {
return diceerrors.NewErrWithFormattedMessage("invalid JSON: %v", err.Error())
}
// Retrieve existing object or cre... | @@ -1126,6 +1127,34 @@ func evalJSONARRAPPEND(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultsArray, false)
}
+// evalJSONINGEST stores a value at a dynamically generated key
+// The key is created using a provided key prefix combined with a unique identifier
+// args must contains key_p... | internal/eval/eval.go | 26 | Go | 0.429 | question | 85 | 51 | 51 | false | #551 Added JSON.INGEST support for HTTP | 588 | DiceDB/dice | 10,326 | C | lucifercr07 | kushal0511-not |
if !modified {
// If no modification was made, it means the path did not exist or was not an array
return clientio.Encode([]interface{}{nil}, false)
}
jsonData = newData
obj.Value = jsonData
return clientio.Encode(resultsArray, false)
}
// evalJSONINGEST stores a value at a dynamically generated key
// The ... | Not sure if we required a 128 bits uuid for this. May be we can use some other lib here. | case XX, Xx:
if i != len(args)-1 {
return diceerrors.NewErrWithMessage(diceerrors.SyntaxErr)
}
obj := store.Get(key)
if obj == nil {
return clientio.RespNIL
}
default:
return diceerrors.NewErrWithMessage(diceerrors.SyntaxErr)
}
}
// Parse the JSON string
var jsonValue interface{}
i... | @@ -1126,6 +1127,34 @@ func evalJSONARRAPPEND(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultsArray, false)
}
+// evalJSONINGEST stores a value at a dynamically generated key
+// The key is created using a provided key prefix combined with a unique identifier
+// args must contains key_p... | internal/eval/eval.go | 26 | Go | 0.286 | suggestion | 88 | 51 | 51 | false | #551 Added JSON.INGEST support for HTTP | 588 | DiceDB/dice | 10,326 | C | lucifercr07 | kushal0511-not |
package eval
import (
"bytes"
"errors"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracelet/log"
"github.com/d... | @AshikBN Thanks for contributing.
Can we make use of existing [evalSET](https://github.com/DiceDB/dice/blob/df66d8cc45e5af8214f264536333c14cbde76ba5/internal/eval/eval.go#L116) function ?
since
```
SETEX key seconds value
```
is equivalent to
```
SET key value EX seconds
```
Let me know if i am mis... | package eval
import (
"bytes"
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/... | @@ -3484,3 +3484,38 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
obj.Value = jsonData
return clientio.Encode(resultString, false)
}
+func evalSETEX(args []string, store *dstore.Store) []byte {
+ if len(args) != 3 {
+ return diceerrors.NewErrArity("SETEX")
+ }
+
+ var key, value string | internal/eval/eval.go | 26 | Go | 0.857 | suggestion | 335 | 3,522 | 3,636 | false | #570: Adds support for SETEX command | 590 | DiceDB/dice | 10,326 | C | kushal0511-not | AshikBN |
package eval
import (
"bytes"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/bytedance/sonic"
"github.com/ohler55/ojg/jp"
"github.com/axiomhq/hyperloglog"
"github.com/dicedb/dice/internal/clientio"
"github.com/dicedb/dice/internal/object"
dstore "github.com/dicedb/dice/intern... | ```suggestion
"set and get": {
```
| },
input: []string{"MOCK_KEY", "$", "2"},
output: []byte(":0\r\n"),
validator: func(ouput []byte) {
key := "MOCK_KEY"
obj := store.Get(key)
want := []interface{}{float64(0), float64(1), float64(3), float64(4), float64(5)}
equal := reflect.DeepEqual(obj.Value, want)
assert.Equal(t, equal... | @@ -2552,3 +2552,91 @@ func testEvalJSONARRPOP(t *testing.T, store *dstore.Store) {
runEvalTests(t, tests, evalJSONARRPOP, store)
}
+
+func testEvalSETEX(t *testing.T, store *dstore.Store) {
+ tests := map[string]evalTestCase{
+ "nil value": {input: nil, output: []byte("-ERR wrong num... | internal/eval/eval_test.go | 26 | Go | 0.429 | suggestion | 37 | 2,643 | 51 | false | #570: Adds support for SETEX command | 590 | DiceDB/dice | 10,326 | C | JyotinderSingh | AshikBN |
package eval
import (
"bytes"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/bytedance/sonic"
"github.com/ohler55/ojg/jp"
"github.com/axiomhq/hyperloglog"
"github.com/dicedb/dice/internal/clientio"
"github.com/dicedb/dice/internal/object"
dstore "github.com/dicedb/dice/intern... | ```suggestion
"update existing key": {
```
| results := expr.Get(obj.Value)
assert.Equal(t, len(results), 1)
want := []interface{}{float64(0), float64(1), float64(3), float64(4), float64(5)}
equal := reflect.DeepEqual(results[0], want)
assert.Equal(t, equal, true)
},
},
}
runEvalTests(t, tests, evalJSONARRPOP, store)
}
func testEval... | @@ -2552,3 +2552,91 @@ func testEvalJSONARRPOP(t *testing.T, store *dstore.Store) {
runEvalTests(t, tests, evalJSONARRPOP, store)
}
+
+func testEvalSETEX(t *testing.T, store *dstore.Store) {
+ tests := map[string]evalTestCase{
+ "nil value": {input: nil, output: []byte("-ERR wrong num... | internal/eval/eval_test.go | 26 | Go | 0.429 | suggestion | 45 | 2,643 | 51 | false | #570: Adds support for SETEX command | 590 | DiceDB/dice | 10,326 | C | JyotinderSingh | AshikBN |
if len(args) != 1 {
return diceerrors.NewErrArity("TYPE")
}
key := args[0]
obj := store.Get(key)
if obj == nil {
return clientio.Encode("none", false)
}
var typeStr string
switch oType, _ := object.ExtractTypeEncoding(obj); oType {
case object.ObjTypeString, object.ObjTypeInt, object.ObjTypeByteArray:
t... | @AshikBN Could you please addcomment above the function? | package eval
import (
"bytes"
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/... | @@ -3760,3 +3760,22 @@ func evalTYPE(args []string, store *dstore.Store) []byte {
return clientio.Encode(typeStr, false)
}
+func evalSETEX(args []string, store *dstore.Store) []byte { | internal/eval/eval.go | 26 | Go | 0.286 | question | 56 | 45 | 3,636 | false | #570: Adds support for SETEX command | 590 | DiceDB/dice | 10,326 | C | kushal0511-not | AshikBN |
// Check if the object is of JSON type
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
path := args[1]
// Parse the JSONPath expression
expr, err := jp.ParseString(path)
if err != nil {
return d... | thanks for your contribution. in redis. when **len(results) == 0** then redis return a string "[]"
`
127.0.0.1:6379> JSON.SET user $ '{"a": "b","b":[{"a":2}, {"a":5}, {"a":"c"}]}'
OK
127.0.0.1:6379> JSON.NUMMULTBY user $..fe 2
"[]"
`
when result is not empty. I find you return a string val... |
// If neither parsing succeeds, return an error
err = errors.New("invalid input: not a valid int or float")
return
}
// Returns the new value after incrementing or multiplying the existing value
func incrMultValue(value any, multiplier interface{}, operation jsonOperation) (newVal interface{}, resultString string,... | @@ -1181,6 +1188,164 @@ func evalJSONSET(args []string, store *dstore.Store) []byte {
return clientio.RespOK
}
+// Parses and returns the input string as an int64 or float64
+func parseFloatInt(input string) (result interface{}, err error) {
+ // Try to parse as an integer
+ if intValue, parseErr := strconv.ParseI... | internal/eval/eval.go | 26 | Go | 0.643 | suggestion | 959 | 51 | 51 | false | Added support for JSON.NUMMULTBY | 592 | DiceDB/dice | 10,326 | C | jujiale | c-harish |
// and objects cleared + number of matching JSON numerical values zeroed.
func evalJSONCLEAR(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("JSON.CLEAR")
}
key := args[0]
// Default path is root if not specified
path := defaultRootPath
if len(args) > 1 {
path = ... | If the `obj` doesn't exist it should just return `nil`
> JSON.OBJLEN returns an array of integer replies for each path specified as the number of keys in the object or nil, if the matching JSON value is not an object. | // if index is out of bound then limit it to the first index
if idx < -len(arr) {
idx = 0
} else {
idx = len(arr) + idx
}
}
return idx
}
// evalJSONOBJLEN return the number of keys in the JSON object at path in key.
// Returns an array of integer replies, an integer for each matching value,
// which i... | @@ -587,6 +587,73 @@ func evalJSONARRLEN(args []string, store *dstore.Store) []byte {
return clientio.Encode(arrlenList, false)
}
+
+// evalJSONOBJLEN return the number of keys in the JSON object at path in key.
+// Returns an array of integer replies, an integer for each matching value,
+// which is the json obje... | internal/eval/eval.go | 26 | Go | 0.643 | suggestion | 218 | 51 | 51 | false | #499: Add support for command JSON.OBJLEN | 593 | DiceDB/dice | 10,326 | C | lucifercr07 | phaneesh707 |
arrlenList = append(arrlenList, len(result.([]interface{})))
default:
arrlenList = append(arrlenList, nil)
}
}
return clientio.Encode(arrlenList, false)
}
// evalJSONOBJLEN return the number of keys in the JSON object at path in key.
// Returns an array of integer replies, an integer for each matching va... | `.` is not an invalid path. We should return the length of complete parent object if the arg contains `.` as `path`.
```
127.0.0.1:6379> JSON.OBJLEN doc .
(integer) 2
``` | case utils.ArrayType:
arrlenList = append(arrlenList, len(result.([]interface{})))
default:
arrlenList = append(arrlenList, nil)
}
}
return clientio.Encode(arrlenList, false)
}
func evalJSONARRPOP(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("json.arrp... | @@ -587,6 +587,73 @@ func evalJSONARRLEN(args []string, store *dstore.Store) []byte {
return clientio.Encode(arrlenList, false)
}
+
+// evalJSONOBJLEN return the number of keys in the JSON object at path in key.
+// Returns an array of integer replies, an integer for each matching value,
+// which is the json obje... | internal/eval/eval.go | 26 | Go | 0.786 | suggestion | 174 | 51 | 51 | false | #499: Add support for command JSON.OBJLEN | 593 | DiceDB/dice | 10,326 | C | lucifercr07 | phaneesh707 |
package commands
import (
"fmt"
"strings"
"testing"
"github.com/dicedb/dice/internal/server/utils"
"github.com/dicedb/dice/testutils"
"gotest.tools/v3/assert"
)
func TestJSONOperations(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
simpleJSON := `{"name":"John","age":30}`
nestedJSON := `{... | Would suggest also adding some negative test cases as part of test here. | name string
commands []string
expected []interface{}
}{
{
name: "JSON.OBJLEN with root path",
commands: []string{"json.set obj $ " + a, "json.objlen obj $"},
expected: []interface{}{"OK", []interface{}{int64(2)}},
},
{
name: "JSON.OBJLEN with nested path",
commands: []string{"jso... | @@ -628,3 +628,57 @@ func TestJsonStrlen(t *testing.T) {
})
}
}
+
+func TestJsonObjLen(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ a := `{"name":"jerry","partner":{"name":"tom","language":["rust"]}}`
+ b := `{"name":"jerry","partner":{"name":"tom","language":["rust"]},"partner2":{"name... | integration_tests/commands/json_test.go | 26 | Go | 0.214 | suggestion | 72 | 685 | 51 | false | #499: Add support for command JSON.OBJLEN | 593 | DiceDB/dice | 10,326 | C | lucifercr07 | phaneesh707 |
key := args[0]
// Retrieve the object from the database
obj := store.Get(key)
if obj == nil {
return clientio.RespNIL
}
// check if the object is json
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessa... | Let's not do type casting on the fly, this can lead to server panic if the cast fails.
Instead use
```go
casted, ok := jsonData.(map[string] interface {})
```
And check the ok value to be true |
var index string
if len(args) >= 3 {
index = args[2]
}
// Retrieve the object from the database
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithMessage("could not perform this operation on a key that doesn't exist")
}
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, obje... | @@ -587,6 +587,71 @@ func evalJSONARRLEN(args []string, store *dstore.Store) []byte {
return clientio.Encode(arrlenList, false)
}
+
+// evalJSONOBJLEN return the number of keys in the JSON object at path in key.
+// Returns an array of integer replies, an integer for each matching value,
+// which is the json obje... | internal/eval/eval.go | 26 | Go | 0.929 | bug | 192 | 51 | 51 | false | #499: Add support for command JSON.OBJLEN | 593 | DiceDB/dice | 10,326 | C | JyotinderSingh | phaneesh707 |
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
// get the value & check for marsheling error
jsonData := obj.Value
_,err := sonic.Marshal(jsonData)
if err != nil {
return diceerrors.NewErrWithMes... | The error should match with redis | return diceerrors.NewErrWithMessage("could not perform this operation on a key that doesn't exist")
}
errWithMessage := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeJSON, object.ObjEncodingJSON)
if errWithMessage != nil {
return errWithMessage
}
jsonData := obj.Value
_, err := sonic.Marshal(... | @@ -587,6 +587,71 @@ func evalJSONARRLEN(args []string, store *dstore.Store) []byte {
return clientio.Encode(arrlenList, false)
}
+
+// evalJSONOBJLEN return the number of keys in the JSON object at path in key.
+// Returns an array of integer replies, an integer for each matching value,
+// which is the json obje... | internal/eval/eval.go | 26 | Go | 0.286 | suggestion | 33 | 51 | 51 | false | #499: Add support for command JSON.OBJLEN | 593 | DiceDB/dice | 10,326 | C | JyotinderSingh | phaneesh707 |
},
"subpath array arrlen": {
setup: func() {
key := "EXISTING_KEY"
value := "{\"age\":13,\"high\":1.60,\"pet\":null,\"language\":[\"python\",\"golang\"], " +
"\"flag\":false, \"partner\":{\"name\":\"tom\"}}"
var rootData interface{}
_ = sonic.Unmarshal([]byte(value), &rootData)
obj := st... | Add test cases that validate behaviour of objlen on incompatible fields (integers, arrays, strings) | obj := store.NewObj(rootData, -1, object.ObjTypeJSON, object.ObjEncodingJSON)
store.Put(key, obj)
},
input: []string{"EXISTING_KEY", "$.*"},
output: []byte("*5\r\n$-1\r\n$-1\r\n$-1\r\n$-1\r\n$-1\r\n"),
},
"subpath array arrlen": {
setup: func() {
key := "EXISTING_KEY"
value := "{\"age\... | @@ -462,6 +463,117 @@ func testEvalJSONARRLEN(t *testing.T, store *dstore.Store) {
runEvalTests(t, tests, evalJSONARRLEN, store)
}
+func testEvalJSONOBJLEN(t *testing.T, store *dstore.Store) { | internal/eval/eval_test.go | 26 | Go | 0.214 | suggestion | 99 | 51 | 51 | false | #499: Add support for command JSON.OBJLEN | 593 | DiceDB/dice | 10,326 | C | JyotinderSingh | phaneesh707 |
// putting the k and value in a Hash Table
store.Put(key, store.NewObj(storedValue, exDurationMs, oType, oEnc), dstore.WithKeepTTL(keepttl))
return clientio.RespOK
}
// evalMSET puts multiple <key, value> pairs in db as in the args
// MSET is atomic, so all given keys are set at once.
// args must contain key and... | I believe the fix should be the save the val by encoding it into the associated type similar to `evalSET` operation.
Redis does the same thing trying to deduce the encoding type and save it accordingly.
```
for (j = 1; j < c->argc; j += 2) {
c->argv[j+1] = tryObjectEncoding(c->argv[j+1]);
setKey(c,... | default:
return clientio.Encode(fmt.Errorf("ERR unsupported encoding: %d", oEnc), false)
}
// putting the k and value in a Hash Table
store.Put(key, store.NewObj(storedValue, exDurationMs, oType, oEnc), dstore.WithKeepTTL(keepttl))
return clientio.RespOK
}
// evalMSET puts multiple <key, value> pairs in db as... | @@ -235,7 +235,7 @@ func evalMSET(args []string, store *dstore.Store) []byte {
insertMap := make(map[string]*object.Obj, len(args)/2)
for i := 0; i < len(args); i += 2 {
key, value := args[i], args[i+1]
- oType, oEnc := deduceTypeEncoding(value)
+ oType, oEnc := object.ObjTypeString, object.ObjEncodingRaw | internal/eval/eval.go | 26 | Go | 1 | suggestion | 375 | 51 | 51 | false | #406 Fix MSET command consistency issue with Redis | 594 | DiceDB/dice | 10,326 | C | lucifercr07 | ar1fKhan |
package eval
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracelet/log"
"github.com/dicedb/dice/config"
... | Can you please add some integration tests? | package eval
import (
"bytes"
"errors"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracele... | internal/eval/eval.go | 1 | Go | 0.071 | question | 42 | 26 | 26 | false | #406 Fix MSET command consistency issue with Redis | 594 | DiceDB/dice | 10,326 | C | lucifercr07 | ar1fKhan | |
package commands
import (
"testing"
dstore "github.com/dicedb/dice/internal/store"
"gotest.tools/v3/assert"
)
func TestType(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
testCases := []struct {
name string
commands []string
expected []interface{}
setup func(store *dstore.Store... | Just a question, why are we using store directly here in integration tests. Any setup we want to do can be done using FireCommand(conn," " ) | package commands
import (
"testing"
"gotest.tools/v3/assert"
)
func TestType(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
testCases := []struct {
name string
commands []string
expected []interface{}
}{
{
name: "TYPE with invalid number of arguments",
commands: []string... | @@ -0,0 +1,57 @@
+package commands
+
+import (
+ "testing"
+
+ dstore "github.com/dicedb/dice/internal/store"
+ "gotest.tools/v3/assert"
+)
+
+func TestType(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testCases := []struct {
+ name string
+ commands []string
+ expected []interface{}
+... | integration_tests/commands/type_test.go | 18 | Go | 0.357 | suggestion | 142 | 43 | 43 | false | #571: Add support for Redis TYPE command | 601 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | meetghodasara |
resultArray = append(resultArray, resultString)
return newValue, isModified
})
if err != nil {
return diceerrors.NewErrWithMessage("invalid JSONPath")
}
}
resultString := `[` + strings.Join(resultArray, ",") + `]`
obj.Value = jsonData
return clientio.Encode(resultString, false)
}
func evalTYPE(arg... | We might be able to use predefined function for extracting the type. This way we can remove `const ObjTypeMask = 0b11110000` as well.
```suggestion
switch oType, _ := object.ExtractTypeEncoding(obj); oType {
``` | formatted := strconv.FormatFloat(f, 'f', -1, 64)
if b {
parts := strings.Split(formatted, ".")
if len(parts) == 1 {
formatted += ".0"
}
}
return formatted
}
// takes original value, increment values (float or int), a flag representing if increment is float
// returns new value, string representation, a bo... | @@ -3439,3 +3440,30 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
obj.Value = jsonData
return clientio.Encode(resultString, false)
}
+
+func evalTYPE(args []string, store *dstore.Store) []byte {
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("TYPE")
+ }
+ key := args[0]
+ obj := st... | internal/eval/eval.go | 26 | Go | 1 | refactor | 224 | 41 | 51 | false | #571: Add support for Redis TYPE command | 601 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | meetghodasara |
package eval
import (
"bytes"
"errors"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"syscall"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracelet/log"
"g... | Also, I checked the code for data created using setbit commands. It should return "string" but dice returns "non-supported type". Please find evidence below:=


}
func evalTYPE(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("TYPE")
}
key := args[0]
obj := store.Get(key)
if obj == nil {
return clientio.Encode("none", false)
}
var typeStr string
switch... | @@ -3439,3 +3440,30 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
obj.Value = jsonData
return clientio.Encode(resultString, false)
}
+
+func evalTYPE(args []string, store *dstore.Store) []byte {
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("TYPE")
+ }
+ key := args[0]
+ obj := st... | internal/eval/eval.go | 26 | Go | 0.643 | suggestion | 344 | 3,470 | 31 | false | #571: Add support for Redis TYPE command | 601 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | meetghodasara |
commands: []string{"TYPE k1"},
expected: []interface{}{"none"},
},
{
name: "TYPE for key with String value",
commands: []string{"SET k1 v1", "TYPE k1"},
expected: []interface{}{"OK", "string"},
},
{
name: "TYPE for key with List value",
commands: []string{"LPUSH k1 v1", "TYPE k1"},
... | Could you please add a testcase for data created using `SETBIT` Command as well test case for number of arguments. This will complete tests for this command. | },
{
name: "TYPE for non-existent key",
commands: []string{"TYPE k1"},
expected: []interface{}{"none"},
},
{
name: "TYPE for key with String value",
commands: []string{"SET k1 v1", "TYPE k1"},
expected: []interface{}{"OK", "string"},
},
{
name: "TYPE for key with List value"... | @@ -0,0 +1,57 @@
+package commands
+
+import (
+ "testing"
+
+ dstore "github.com/dicedb/dice/internal/store"
+ "gotest.tools/v3/assert"
+)
+
+func TestType(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testCases := []struct {
+ name string
+ commands []string
+ expected []interface{}
+... | integration_tests/commands/type_test.go | 26 | Go | 0.571 | suggestion | 158 | 37 | 50 | false | #571: Add support for Redis TYPE command | 601 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | meetghodasara |
} else {
viper.AddConfigPath(filepath.Dir(configFilePath))
}
viper.SetConfigType("toml")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Warn("config file not found. Using default configurations.")
return
}
log.Errorf("Error reading config file: ... | not needed.
```suggestion
``` |
if configFilePath == utils.EmptyStr {
viper.AddConfigPath(DefaultConfigFilePath)
} else {
viper.AddConfigPath(filepath.Dir(configFilePath))
}
viper.SetConfigType("toml")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Warn("config file not found. Us... | @@ -237,6 +240,12 @@ func setUpViperConfig(configFilePath string) {
}
// override default configurations with command line flags
+ mergeFlagsWithConfig()
+
+ log.Info("configurations loaded successfully.") | config/config.go | 26 | Go | 0.429 | suggestion | 31 | 51 | 51 | false | #609 fix: auth command line flags should be respected during server startup | 605 | DiceDB/dice | 10,326 | C | JyotinderSingh | vinitparekh17 |
"github.com/axiomhq/hyperloglog"
"github.com/dicedb/dice/internal/clientio"
"github.com/dicedb/dice/internal/object"
dstore "github.com/dicedb/dice/internal/store"
testifyAssert "github.com/stretchr/testify/assert"
"gotest.tools/v3/assert"
)
type evalTestCase struct {
setup func()
input []string
outpu... | @psrvere can you please uncomment these. | "github.com/axiomhq/hyperloglog"
"github.com/dicedb/dice/internal/clientio"
"github.com/dicedb/dice/internal/object"
dstore "github.com/dicedb/dice/internal/store"
testifyAssert "github.com/stretchr/testify/assert"
"gotest.tools/v3/assert"
)
type evalTestCase struct {
setup func()
input []string
outpu... | @@ -38,42 +38,43 @@ func setupTest(store *dstore.Store) *dstore.Store {
func TestEval(t *testing.T) {
store := dstore.NewStore(nil)
- testEvalMSET(t, store)
- testEvalPING(t, store)
- testEvalHELLO(t, store)
- testEvalSET(t, store)
- testEvalGET(t, store)
- testEvalDebug(t, store)
- testEvalJSONARRPOP(t, store)
- ... | internal/eval/eval_test.go | 26 | Go | 0.071 | suggestion | 40 | 51 | 51 | false | Added COMMAND HELP | 608 | DiceDB/dice | 10,326 | C | lucifercr07 | psrvere |
Eval func([]string, *dstore.Store) []byte
Arity int // number of arguments, it is possible to use -N to say >= N
KeySpecs
}
type KeySpecs struct {
BeginIndex int
Step int
LastKey int
}
var (
DiceCmds = map[string]DiceCmdMeta{}
pingCmdMeta = DiceCmdMeta{
Name: "PING",
Info: `PING returns with ... | Hi, for commands with arguments without keys, we can omit KeySpecs. | Eval func([]string, *dstore.Store) []byte
Arity int // number of arguments, it is possible to use -N to say >= N
KeySpecs
}
type KeySpecs struct {
BeginIndex int
Step int
LastKey int
}
var (
DiceCmds = map[string]DiceCmdMeta{}
pingCmdMeta = DiceCmdMeta{
Name: "PING",
Info: `PING returns with ... | @@ -25,6 +25,13 @@ var (
Eval: evalPING,
Arity: -1,
}
+ echoCmdMeta = DiceCmdMeta{
+ Name: "ECHO",
+ Info: `ECHO returns the string given as argument.`,
+ Eval: evalECHO,
+ Arity: 1,
+ KeySpecs: KeySpecs{BeginIndex: 1}, | internal/eval/commands.go | 26 | Go | 0.214 | suggestion | 67 | 51 | 51 | false | #622: Add ECHO command | 626 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | hgupta12 |
// If any message is added with the ping command,
// the message will be returned.
func evalPING(args []string, store *dstore.Store) []byte {
var b []byte
if len(args) >= 2 {
return diceerrors.NewErrArity("PING")
}
if len(args) == 0 {
b = clientio.Encode("PONG", true)
} else {
b = clientio.Encode(args[0], ... | nit:
```suggestion
return clientio.Encode(args[0], false)
``` | // If any message is added with the ping command,
// the message will be returned.
func evalPING(args []string, store *dstore.Store) []byte {
var b []byte
if len(args) >= 2 {
return diceerrors.NewErrArity("PING")
}
if len(args) == 0 {
b = clientio.Encode("PONG", true)
} else {
b = clientio.Encode(args[0], ... | @@ -72,6 +72,16 @@ func evalPING(args []string, store *dstore.Store) []byte {
return b
}
+// evalECHO returns the argument passed by the user
+func evalECHO(args []string, store *dstore.Store) []byte {
+ if len(args) != 1 {
+ return diceerrors.NewErrArity("ECHO")
+ }
+
+ b := clientio.Encode(args[0], false)
+ re... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 65 | 51 | 51 | false | #622: Add ECHO command | 626 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | hgupta12 |
obj.Value = jsonData
return clientio.Encode(resultString, false)
}
// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
// It takes two arguments: the key where the JSON document is stored, and an optional JSON path.
// It returns a list of keys from the object at the specified path or ... | thanks for your contribution. in redis. if the key is not exist. should return an error.
`
127.0.0.1:6379> JSON.SET doc $ '{"a":[3], "nested": {"a": {"b":2, "c": 1}}}'
OK
127.0.0.1:6379> JSON.OBJKEYS docs $..a
(error) ERR could not perform this operation on a key that doesn't exist
`
... | if obj != nil {
currKeyHll, ok := obj.Value.(*hyperloglog.Sketch)
if !ok {
return diceerrors.NewErrWithMessage(diceerrors.WrongTypeHllErr)
}
err := unionHll.Merge(currKeyHll)
if err != nil {
return diceerrors.NewErrWithMessage(diceerrors.InvalidHllErr)
}
}
}
return clientio.Encode(union... | @@ -3553,6 +3553,82 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
+// It takes two arguments: the key where the JSON document is stored, and an optional JSON path... | internal/eval/eval.go | 26 | Go | 0.786 | suggestion | 555 | 51 | 51 | false | #498: Add support for JSON.OBJKEYS | 629 | DiceDB/dice | 10,326 | C | jujiale | iamskp11 |
package eval
import (
"bytes"
"errors"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/charmbracele... | if the jsonpath query is empty. should return an empty array.
`
127.0.0.1:6379> JSON.SET doc $ '{"a":[3], "nested": {"a": {"b":2, "c": 1}}}'
OK
127.0.0.1:6379> JSON.OBJKEYS doc $..ddd
(empty array)
` | _,err := sonic.Marshal(jsonData)
if err != nil {
return diceerrors.NewErrWithMessage("Existing key has wrong Dice type")
}
// If path is root, return all keys of the entire JSON
if len(args) == 1 {
if utils.GetJSONFieldType(jsonData) == utils.ObjectType {
keys := make([]string,0)
for key := range jsonDa... | @@ -3553,6 +3553,82 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
+// It takes two arguments: the key where the JSON document is stored, and an optional JSON path... | internal/eval/eval.go | 26 | Go | 0.643 | suggestion | 227 | 3,658 | 51 | false | #498: Add support for JSON.OBJKEYS | 629 | DiceDB/dice | 10,326 | C | jujiale | iamskp11 |
package eval
import (
"bytes"
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/... | nit: newline before singline line comment | _, err := expr.Modify(jsonData, func(value any) (interface{}, bool) {
newValue, resultString, isModified := incrementValue(value, isIncrFloat, incrFloat, incrInt)
resultArray = append(resultArray, resultString)
return newValue, isModified
})
if err != nil {
return diceerrors.NewErrWithMessage("invalid... | @@ -3621,6 +3621,81 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
+// It takes two arguments: the key where the JSON document is stored, and an optional JSON path... | internal/eval/eval.go | 26 | Go | 0.071 | nitpick | 41 | 3,790 | 51 | false | #498: Add support for JSON.OBJKEYS | 629 | DiceDB/dice | 10,326 | C | manishrw | iamskp11 |
package eval
import (
"bytes"
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/... | why not handle it in a way consistent to other commands?
`clientio.Encode(0, false)` |
resultString := `[` + strings.Join(resultArray, ",") + `]`
obj.Value = jsonData
return clientio.Encode(resultString, false)
}
// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
// It takes two arguments: the key where the JSON document is stored, and an optional JSON path.
// It ret... | @@ -3621,6 +3621,81 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
+// It takes two arguments: the key where the JSON document is stored, and an optional JSON path... | internal/eval/eval.go | 26 | Go | 0.5 | question | 85 | 3,790 | 51 | false | #498: Add support for JSON.OBJKEYS | 629 | DiceDB/dice | 10,326 | C | manishrw | iamskp11 |
package eval
import (
"bytes"
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"github.com/bytedance/sonic"
"github.com/... | I have a suggestion to improve error handling. Instead of directly returning `errWithMessage`, it would be better to wrap it with additional context for better readability and debugging. You can use `diceerrors.NewErrWithFormattedMessage(errWithMessage)`.
For example:
```go
errWithMessage := object.AssertTypeAndEn... |
// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
// It takes two arguments: the key where the JSON document is stored, and an optional JSON path.
// It returns a list of keys from the object at the specified path or an error if the path is invalid.
func evalJSONOBJKEYS(args []string, s... | @@ -3621,6 +3621,81 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+// evalJSONOBJKEYS retrieves the keys of a JSON object stored at path specified.
+// It takes two arguments: the key where the JSON document is stored, and an optional JSON path... | internal/eval/eval.go | 26 | Go | 1 | bug | 485 | 3,790 | 51 | false | #498: Add support for JSON.OBJKEYS | 629 | DiceDB/dice | 10,326 | C | manishrw | iamskp11 |
package eval
import dstore "github.com/dicedb/dice/internal/store"
type DiceCmdMeta struct {
Name string
Info string
Eval func([]string, *dstore.Store) []byte
Arity int // number of arguments, it is possible to use -N to say >= N
KeySpecs
}
type KeySpecs struct {
BeginIndex int
Step int
LastKey i... | nit:
```suggestion
Arity: 1,
KeySpecs: KeySpecs{BeginIndex: 1},
``` | hlenCmdMeta = DiceCmdMeta{
Name: "HLEN",
Info: `HLEN key
Returns the number of fields contained in the hash stored at key.`,
Eval: evalHLEN,
Arity: 2,
}
selectCmdMeta = DiceCmdMeta{
Name: "SELECT",
Info: `Select the logical database having the specified zero-based numeric index. New connections alwa... | @@ -761,6 +761,13 @@ var (
Arity: 3,
KeySpecs: KeySpecs{BeginIndex: 1},
}
+ dumpkeyCMmdMeta=DiceCmdMeta{
+ Name: "DUMP",
+ Info: `Serialize the value stored at key in a Redis-specific format and return it to the user.
+ The returned value can be synthesized back into a Redis key using the RESTORE comma... | internal/eval/commands.go | 26 | Go | 0.571 | suggestion | 92 | 884 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
obj.Value = jsonData
return clientio.Encode(resultString, false)
}
func evalDUMP(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("DUMP")
}
key := args[0]
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithFormattedMess... | since the first byte of rdbSerialize is a fixed value ` buf.WriteByte(0x09)` and second is the type, we need atleast 3 as third will be data.
```suggestion
if len(args) < 3 {
``` |
return clientio.Encode(members, false)
}
func evalSREM(args []string, store *dstore.Store) []byte {
if len(args) < 2 {
return diceerrors.NewErrArity("SREM")
}
key := args[0]
// Get the set object from the store.
obj := store.Get(key)
var count = 0
if obj == nil {
return clientio.Encode(count, false)
}
... | @@ -3522,6 +3528,142 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 0.857 | suggestion | 185 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
func evalDUMP(args []string, store *dstore.Store) []byte {
if len(args) < 1 {
return diceerrors.NewErrArity("DUMP")
}
key := args[0]
obj := store.Get(key)
if obj == nil {
return diceerrors.NewErrWithFormattedMessage("-ERR could not perform this operation on a key that doesn't exist... | Restore have ttl as a mandatory field
```
RESTORE key ttl serialized-value [REPLACE] [ABSTTL]
[IDLETIME seconds] [FREQ frequency]
```
```suggestion
ttl := args[1]
encodedValue := args[3]
``` | func evalSREM(args []string, store *dstore.Store) []byte {
if len(args) < 2 {
return diceerrors.NewErrArity("SREM")
}
key := args[0]
// Get the set object from the store.
obj := store.Get(key)
var count = 0
if obj == nil {
return clientio.Encode(count, false)
}
// If the object exists, check if it is a ... | @@ -3522,6 +3528,142 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 0.857 | suggestion | 209 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
if err != nil {
return diceerrors.NewErrWithMessage("serialization failed")
}
encodedResult := base64.StdEncoding.EncodeToString(serializedValue)
return clientio.Encode(encodedResult, false)
}
func evalRestore(args []string, store *dstore.Store) []byte {
if len(args) < 2 {
return diceerrors.New... | ```suggestion
return clientio.RespOK
``` |
// If the object exists, check if it is a set object.
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeSet); err != nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
if err := object.AssertEncoding(obj.TypeEncoding, object.ObjEncodingSetStr); err != nil {
return diceerro... | @@ -3522,6 +3528,142 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 50 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
serializedValue, err := rdbSerialize(obj)
if err != nil {
return diceerrors.NewErrWithMessage("serialization failed")
}
encodedResult := base64.StdEncoding.EncodeToString(serializedValue)
return clientio.Encode(encodedResult, false)
}
func evalRestore(args []string, store *dstore.Store) []byte... | we might need to handle ttl here. | }
// If the object exists, check if it is a set object.
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeSet); err != nil {
return diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
if err := object.AssertEncoding(obj.TypeEncoding, object.ObjEncodingSetStr); err != nil {
return dicee... | @@ -3522,6 +3528,142 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 0.214 | suggestion | 33 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
obj, err := rdbDeserialize(serializedData)
if err != nil {
return diceerrors.NewErrWithMessage("deserialization failed: " + err.Error())
}
store.Put(key, obj)
return []byte("OK")
}
func rdbDeserialize(data []byte) (*object.Obj, error) {
if len(data) < 2 {
return nil, errors.New("insufficient data for deser... | I changed back the string type as I was testing string. Also I was wondering if we can actually use the predefined values of encoding here instead of defining our own. We can use encoding from original key to actually restore in the same type and encoding
```suggestion
func rdbDeserialize(data []byte) (*object.Obj,... | }
return clientio.Encode(count, false)
}
func evalSCARD(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("SCARD")
}
key := args[0]
// Get the set object from the store.
obj := store.Get(key)
if obj == nil {
return clientio.Encode(0, false)
}
// If the ob... | @@ -3522,6 +3528,142 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 1 | suggestion | 756 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
DiceCmds["COPY"] = copyCmdMeta
DiceCmds["DECR"] = decrCmdMeta
DiceCmds["EXISTS"] = existsCmdMeta
DiceCmds["GETDEL"] = getDelCmdMeta
DiceCmds["DECRBY"] = decrByCmdMeta
DiceCmds["RENAME"] = renameCmdMeta
DiceCmds["GETEX"] = getexCmdMeta
DiceCmds["PTTL"] = pttlCmdMeta
DiceCmds["HSET"] = hsetCmdMeta
DiceCmds["OBJ... | Please add KeySpecs here as well | Name: "SELECT",
Info: `Select the logical database having the specified zero-based numeric index. New connections always use the database 0`,
Eval: evalSELECT,
Arity: 1,
}
jsonnumincrbyCmdMeta = DiceCmdMeta{
Name: "JSON.NUMINCRBY",
Info: `Increment the number value stored at path by number.`,
... | @@ -797,11 +797,27 @@ var (
Arity: 3,
KeySpecs: KeySpecs{BeginIndex: 1},
}
+ dumpkeyCMmdMeta=DiceCmdMeta{
+ Name: "DUMP",
+ Info: `Serialize the value stored at key in a Redis-specific format and return it to the user.
+ The returned value can be synthesized back into a Redis key using the RESTORE comm... | internal/eval/commands.go | 26 | Go | 0.071 | suggestion | 32 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
obj, err := rdbDeserialize(serializedData)
if err != nil {
return diceerrors.NewErrWithMessage("deserialization failed: " + err.Error())
}
newobj:=store.NewObj(obj.Value,ttl,obj.TypeEncoding,obj.TypeEncoding)
var keepttl=true
if(ttl>0){
store.Put(key, newobj, dstore.WithKeepTTL(keepttl))
}else{
store.Put... | any particular reason 0x00 and 0xC0 were chosen? I have not delved much into redis implementation so I am not sure about this. |
func evalSCARD(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("SCARD")
}
key := args[0]
// Get the set object from the store.
obj := store.Get(key)
if obj == nil {
return clientio.Encode(0, false)
}
// If the object exists, check if it is a set object.
i... | @@ -3522,6 +3528,150 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 0.357 | suggestion | 127 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | TheRanomial |
// Execute the JSONPath query
_, err := expr.Modify(jsonData, func(value any) (interface{}, bool) {
newValue, resultString, isModified := incrementValue(value, isIncrFloat, incrFloat, incrInt)
resultArray = append(resultArray, resultString)
return newValue, isModified
})
if err != nil {
return dicee... | Let's keep it consistent with Redis output for non-existent key.
```
127.0.0.1:6379> DUMP k1
(nil)
``` |
func evalSINTER(args []string, store *dstore.Store) []byte {
if len(args) < 2 {
return diceerrors.NewErrArity("SINTER")
}
sets := make([]map[string]struct{}, 0, len(args))
var empty = 0
for _, arg := range args {
// Get the set object from the store.
obj := store.Get(arg)
if obj == nil {
empty++
... | @@ -3679,6 +3685,150 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 0.714 | suggestion | 106 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | lucifercr07 | TheRanomial |
ttl, _ := strconv.ParseInt(ttlStr, 10, 64)
encodedValue := args[2]
serializedData, err := base64.StdEncoding.DecodeString(encodedValue)
if err != nil {
return diceerrors.NewErrWithMessage("failed to decode base64 value")
}
obj, err := rdbDeserialize(serializedData)
if err != nil {
return diceerrors.NewErr... | I'd suggest moving DUMP and Restore to a single file like `BITPOS` maybe. Both function are related and all these other functions in these file won't be required for other commands here anyways. |
count := 0
resultSet := make(map[string]struct{}, len(sets[0]))
// init the result set with the first set
// store the number of elements in the first set in count
// we will decrement the count if we do not find the elements in the other sets
for k := range sets[0] {
resultSet[k] = struct{}{}
count++
}
... | @@ -3679,6 +3685,150 @@ func evalJSONNUMINCRBY(args []string, store *dstore.Store) []byte {
return clientio.Encode(resultString, false)
}
+
+func evalDUMP(args []string, store *dstore.Store) []byte {
+ if len(args) < 1 {
+ return diceerrors.NewErrArity("DUMP")
+ }
+ key := args[0]
+ obj := store... | internal/eval/eval.go | 26 | Go | 0.5 | suggestion | 194 | 51 | 51 | false | #281: added support for DUMP command | 633 | DiceDB/dice | 10,326 | C | lucifercr07 | TheRanomial |
type KeySpecs struct {
BeginIndex int
Step int
LastKey int
}
var (
DiceCmds = map[string]DiceCmdMeta{}
CommandSubCommands []string
pingCmdMeta = DiceCmdMeta{
Name: "PING",
Info: `PING returns with an encoded "PONG" If any message is added with the ping command,the message will be returned.`,
E... | Can this be moved info the diceCmdMetadata struct for COMMAND? |
// IsMigrated indicates whether a command has been migrated to a new evaluation
// mechanism. If true, the command uses the newer evaluation logic represented by
// the NewEval function. This allows backward compatibility for commands that have
// not yet been migrated, ensuring they continue to use the older Eval... | @@ -18,6 +18,7 @@ type KeySpecs struct {
var (
DiceCmds = map[string]DiceCmdMeta{}
+ CommandSubCommands []string | internal/eval/commands.go | 26 | Go | 0.286 | question | 62 | 51 | 51 | false | #635: List Command Subcommands as separate commands | 673 | DiceDB/dice | 10,326 | C | KaviiSuri | hgupta12 |
}
return clientio.Encode(typeStr, false)
}
// evalGETRANGE returns the substring of the string value stored at key, determined by the offsets start and end
// The offsets are zero-based and can be negative values to index from the end of the string
//
// If the start offset is larger than the end offset, or if the ... | This check could be moved closer to the part where you fetch the key from store, which also guarantees an early return in case of invalid key. | }
return clientio.Encode(typeStr, false)
}
// evalGETRANGE returns the substring of the string value stored at key, determined by the offsets start and end
// The offsets are zero-based and can be negative values to index from the end of the string
//
// If the start offset is larger than the end offset, or if the ... | @@ -3548,3 +3548,64 @@ func evalTYPE(args []string, store *dstore.Store) []byte {
return clientio.Encode(typeStr, false)
}
+
+// evalGETRANGE returns the substring of the string value stored at key, determined by the offsets start and end
+// The offsets are zero-based and can be negative values to index from the ... | internal/eval/eval.go | 26 | Go | 0.429 | suggestion | 142 | 51 | 51 | false | Add support for GETRANGE | 679 | DiceDB/dice | 10,326 | C | sairayapureddy | KaviiSuri |
return clientio.Encode("", false)
}
var str string
switch _, oEnc := object.ExtractTypeEncoding(obj); oEnc {
case object.ObjEncodingEmbStr, object.ObjEncodingRaw:
if val, ok := obj.Value.(string); ok {
str = val
} else {
return diceerrors.NewErrWithMessage("expected string but got another type")
}
c... | I believe this could be broken down for better readability. The check for empty string could be done right after switch construct. Once you are sure that string has length > 0, you could add the checks for normalising the start and end. | return diceerrors.NewErrWithFormattedMessage(diceerrors.IntOrOutOfRangeErr)
}
var str string
switch _, oEnc := object.ExtractTypeEncoding(obj); oEnc {
case object.ObjEncodingEmbStr, object.ObjEncodingRaw:
if val, ok := obj.Value.(string); ok {
str = val
} else {
return diceerrors.NewErrWithMessage("exp... | @@ -3548,3 +3548,64 @@ func evalTYPE(args []string, store *dstore.Store) []byte {
return clientio.Encode(typeStr, false)
}
+
+// evalGETRANGE returns the substring of the string value stored at key, determined by the offsets start and end
+// The offsets are zero-based and can be negative values to index from the ... | internal/eval/eval.go | 26 | Go | 0.5 | bug | 236 | 40 | 44 | false | Add support for GETRANGE | 679 | DiceDB/dice | 10,326 | C | sairayapureddy | KaviiSuri |
"runtime"
"strings"
"time"
"github.com/dicedb/dice/internal/server/utils"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
)
const (
DefaultHost string = "0.0.0.0"
DefaultPort int = 7379
DefaultConfigName string = "dice.toml"
DefaultConfigFilePath string = "./"
EvictSi... | BY default lets make it false, till out multithreading stabalises. | "runtime"
"strings"
"time"
"github.com/dicedb/dice/internal/server/utils"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
)
const (
DefaultHost string = "0.0.0.0"
DefaultPort int = 7379
DefaultConfigName string = "dice.toml"
DefaultConfigFilePath string = "./"
EvictSi... | @@ -29,8 +29,9 @@ var (
Host = DefaultHost
Port = DefaultPort
- EnableHTTP = true
- HTTPPort = 8082
+ EnableMultiThreading = true | config/config.go | 26 | Go | 0.357 | suggestion | 66 | 51 | 51 | false | Add flag to enable/disable multi-threading on server | 682 | DiceDB/dice | 10,326 | C | AshwinKul28 | lucifercr07 |
}
}
// gather collects the responses from multiple shards and writes the results into the provided buffer.
// It first waits for responses from all the shards and then processes the result based on the command type (SingleShard, Custom, or Multishard).
func (s *AsyncServer) gather(redisCmd *cmd.RedisCmd, buf *bytes.B... | I am not sure whether the string will replace the characters \r\n hence kept it as a byte slice. But if you can check an error scenario then it would be great. | }
}
// gather collects the responses from multiple shards and writes the results into the provided buffer.
// It first waits for responses from all the shards and then processes the result based on the command type (SingleShard, Custom, or Multishard).
func (s *AsyncServer) gather(redisCmd *cmd.RedisCmd, buf *bytes.B... | @@ -75,7 +75,7 @@ func (s *AsyncServer) gather(redisCmd *cmd.RedisCmd, buf *bytes.Buffer, numShard
switch c {
case SingleShard, Custom:
if evalResp[0].Error != nil {
- buf.Write([]byte(evalResp[0].Error.Error()))
+ buf.WriteString(evalResp[0].Error.Error()) | internal/server/multitherading.go | 26 | Go | 0.571 | suggestion | 160 | 35 | 35 | false | Add flag to enable/disable multi-threading on server | 682 | DiceDB/dice | 10,326 | C | AshwinKul28 | lucifercr07 |
setup: func() {
key := "EXISTING_KEY"
value := "mock_value"
obj := &object.Obj{
Value: value,
LastAccessedAt: uint32(time.Now().Unix()),
}
store.Put(key, obj)
},
input: []string{"EXISTING_KEY", strconv.FormatInt(-1, 10)},
output: []byte("-ERR invalid expire time in '... | This is incorrect, redis gives the following output when running EXPIRE command with empty expiry: `ERR wrong number of arguments for command` | setup: func() {
key := "EXISTING_KEY"
value := "mock_value"
obj := &object.Obj{
Value: value,
LastAccessedAt: uint32(time.Now().Unix()),
}
store.Put(key, obj)
},
input: []string{"EXISTING_KEY", strconv.FormatInt(-1, 10)},
output: []byte("-ERR invalid expire time in '... | @@ -473,6 +473,34 @@ func testEvalEXPIRE(t *testing.T, store *dstore.Store) {
input: []string{"EXISTING_KEY", strconv.FormatInt(-1, 10)},
output: []byte("-ERR invalid expire time in 'expire' command\r\n"),
},
+ "invalid expiry time exists - empty string": {
+ setup: func() {
+ key := "EXISTING_KEY"
+ ... | internal/eval/eval_test.go | 26 | Go | 0.5 | bug | 142 | 51 | 51 | false | #671: Inconsistent EXPIRE: EXPIRE with empty string as TTL should report an… | 691 | DiceDB/dice | 10,326 | C | JyotinderSingh | Abh-ay |
if err := object.AssertType(obj.TypeEncoding, object.ObjTypeByteList); err != nil {
return clientio.Encode(err, false)
}
if err := object.AssertEncoding(obj.TypeEncoding, object.ObjEncodingDeque); err != nil {
return clientio.Encode(err, false)
}
deq := obj.Value.(*Deque)
x, err := deq.RPop()
if err != ni... | Hi, upon checking the redis behavior for handling this command, I think we can order the validation to ensure we are consistent with the output when there are multiple issues with the command. The order in redis is:
1. Check arity
2. Check value is integer
3. Get or Create object and validate type
4. Check field is... | }
field := args[1]
numkey, err := hashmap.incrementValue(field, increment)
if err != nil {
return diceerrors.NewErrWithMessage(err.Error())
}
obj = store.NewObj(hashmap, -1, object.ObjTypeHashMap, object.ObjEncodingHashMap)
store.Put(key, obj)
return clientio.Encode(numkey, false)
}
func evalHSETNX(args [... | @@ -2733,6 +2733,43 @@ func evalHSET(args []string, store *dstore.Store) []byte {
return clientio.Encode(numKeys, false)
}
+func evalHINCRBY(args []string, store *dstore.Store) []byte {
+ if len(args) < 3 {
+ return diceerrors.NewErrArity("HINCRBY")
+ }
+
+ key := args[0]
+ obj := store.Get(key)
+ var hashmap Has... | internal/eval/eval.go | 26 | Go | 1 | bug | 975 | 51 | 51 | false | #647: Added HINCRBY Command | 701 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | ankkyprasad |
value = *val
default:
return nil, diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
return clientio.Encode(value, false), nil
}
func (h HashMap) incrementValue(field string, increment int64) (int64, error) {
val, ok := h[field]
if !ok {
h[field] = fmt.Sprintf("%v", increment)
return increm... | Another suggestion here would be to check overflow after incrementing. Please check the following scenario:

| }
value = *val
default:
return nil, diceerrors.NewErrWithFormattedMessage(diceerrors.WrongTypeErr)
}
return clientio.Encode(value, false), nil
}
func (h HashMap) incrementValue(field string, increment int64) (int64, error) {
val, ok := h[field]
if !ok {
h[field] = fmt.Sprintf("%v", increment)
return in... | @@ -83,3 +84,21 @@ func getValueFromHashMap(key, field string, store *dstore.Store) (val, err []byt
return clientio.Encode(value, false), nil
}
+
+func (h HashMap) incrementValue(field string, increment int64) (int64, error) {
+ val, ok := h[field]
+ if !ok {
+ h[field] = fmt.Sprintf("%v", increment)
+ return in... | internal/eval/hmap.go | 26 | Go | 0.571 | bug | 200 | 26 | 31 | false | #647: Added HINCRBY Command | 701 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | ankkyprasad |
Arity: -2,
KeySpecs: KeySpecs{BeginIndex: 2},
}
touchCmdMeta = DiceCmdMeta{
Name: "TOUCH",
Info: `TOUCH key1 key2 ... key_N
Alters the last access time of a key(s).
A key is ignored if it does not exist.`,
Eval: evalTOUCH,
Arity: -2,
KeySpecs: KeySpecs{BeginIndex: 1},
}
expiretimeCmdMeta... | nit:
```suggestion
Arity: 3,
``` | Eval: evalHGET,
Arity: -3,
KeySpecs: KeySpecs{BeginIndex: 1},
}
hgetAllCmdMeta = DiceCmdMeta{
Name: "HGETALL",
Info: `Returns all fields and values of the hash stored at key. In the returned value,
every field name is followed by its value, so the length of the reply is twice the size of the ... | @@ -593,6 +593,15 @@ var (
Arity: -2,
KeySpecs: KeySpecs{BeginIndex: 1},
}
+ hincrbyCmdMeta = DiceCmdMeta{
+ Name: "HINCRBY",
+ Info: `Increments the number stored at field in the hash stored at key by increment.
+ If key does not exist, a new key holding a hash is created.
+ If field does not exist the ... | internal/eval/commands.go | 26 | Go | 0.429 | suggestion | 40 | 51 | 51 | false | #647: Added HINCRBY Command | 701 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | ankkyprasad |
expected: []interface{}{int64(1), int64(10)},
},
{
name: "HINCRBY should increment on existing key and field",
commands: []string{"HINCRBY key field-1 10"},
expected: []interface{}{int64(20)},
},
{
name: "HINCRBY should give error when trying to increment a value which is not integer",
... | Hi, Changes look good, Can you please add one test case with following scenario:
**_"HINCRBY should give integer error when trying to increment a key which is not a hash value with a value which is not integer"_**
Thanks,
Apoorv | name: "HINCRBY should increment when key exists and a field doesn't exist",
commands: []string{"HSET new-key field-1 10", "HINCRBY new-key field-2 10"},
expected: []interface{}{int64(1), int64(10)},
},
{
name: "HINCRBY should increment on existing key and field",
commands: []string{"HINCRBY k... | @@ -0,0 +1,77 @@
+package async
+
+import (
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestHINCRBY(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testcases := []TestCase{
+ {
+ name: "HINCRBY Wrong number of arguments provided",
+ commands: []string{"HINCRBY", "HINCRBY key", "... | integration_tests/commands/async/hincrby_test.go | 26 | Go | 0.643 | suggestion | 233 | 51 | 51 | false | #647: Added HINCRBY Command | 701 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | ankkyprasad |
expected: []interface{}{"ERR value is not an integer or out of range"},
},
{
name: "HINCRBY should give error when trying to increment a key which is not a hash value",
commands: []string{"SET key value", "HINCRBY key value 10"},
expected: []interface{}{"OK", "WRONGTYPE Operation against a key holdi... | Hi, Thanks for adding this test case. Please check the expected output in redis.
<img width="444" alt="image" src="https://github.com/user-attachments/assets/e4303c12-c826-4b04-9ae5-46aeda651a31">
We need to return an integer error in this case. | name: "HINCRBY should give error when increment value is not an integer",
commands: []string{"HINCRBY key field value"},
expected: []interface{}{"ERR value is not an integer or out of range"},
},
{
name: "HINCRBY should give error when trying to increment a key which is not a hash value",
com... | @@ -0,0 +1,82 @@
+package async
+
+import (
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestHINCRBY(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ testcases := []TestCase{
+ {
+ name: "HINCRBY Wrong number of arguments provided",
+ commands: []string{"HINCRBY", "HINCRBY key", "... | integration_tests/commands/async/hincrby_test.go | 26 | Go | 0.643 | suggestion | 248 | 37 | 39 | false | #647: Added HINCRBY Command | 701 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | ankkyprasad |
keyPrefix := queryParams.Get(KeyPrefix)
if keyPrefix != "" && command == "JSON.INGEST" {
args = append(args, keyPrefix)
}
// Step 1: Handle JSON body if present
if r.Body != nil {
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
if len(body) > 0 {
var jsonBody map[string]interfac... | We can split this function later between `priorityKeys` append and rest keys to args. | command = strings.ToUpper(command)
var args []string
// Extract query parameters
queryParams := r.URL.Query()
keyPrefix := queryParams.Get(KeyPrefix)
if keyPrefix != "" && command == "JSON.INGEST" {
args = append(args, keyPrefix)
}
// Step 1: Handle JSON body if present
if r.Body != nil {
body, err := io... | @@ -52,15 +57,43 @@ func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
// Define keys to exclude and process their values first
// Update as we support more commands
- var priorityKeys = [5]string{
+ var priorityKeys = [10]string{ | internal/server/utils/redisCmdAdapter.go | 26 | Go | 0.357 | refactor | 85 | 51 | 51 | false | add more tests and enhance support for commands over HTTP | 708 | DiceDB/dice | 10,326 | C | lucifercr07 | pratikpandey21 |
obj := store.Get(key)
var hashMap HashMap
var numKeys int64
if obj != nil {
if err := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeHashMap, object.ObjEncodingHashMap); err != nil {
return diceerrors.NewErrWithMessage(diceerrors.WrongTypeErr)
}
hashMap = obj.Value.(HashMap)
}
keyValuePa... | Please add documentation for the function | if !isExpirySet {
return clientio.RespMinusOne
}
// compute the time remaining for the key to expire and
// return the RESP encoded form of it
durationMs := exp - uint64(utils.GetCurrentTime().UnixMilli())
return clientio.Encode(int64(durationMs), false)
}
// evalHSET sets the specified fields to their
// res... | @@ -2768,6 +2903,26 @@ func evalHSET(args []string, store *dstore.Store) []byte {
return clientio.Encode(numKeys, false)
}
+func evalHSETNX(args []string, store *dstore.Store) []byte { | internal/eval/eval.go | 26 | Go | 0.071 | suggestion | 41 | 51 | 51 | false | #656: added HVALS command | 710 | DiceDB/dice | 10,326 | C | princejha95 | bijuli74 |
hashMap = obj.Value.(HashMap)
}
for hmKey, hmValue := range hashMap {
results = append(results, hmKey, hmValue)
}
return clientio.Encode(results, false)
}
func evalHGET(args []string, store *dstore.Store) []byte {
if len(args) != 2 {
return diceerrors.NewErrArity("HGET")
}
key := args[0]
hmKey := args... | I believe you pushed it by mistake. Please remove | return errWithMessage
}
if !bytes.Equal(val, clientio.RespNIL) { // hmKey is already present in hash map
return clientio.RespZero
}
evalHSET(args, store)
return clientio.RespOne
}
func evalHGETALL(args []string, store *dstore.Store) []byte {
if len(args) != 1 {
return diceerrors.NewErrArity("HGETALL")
}
... | @@ -2809,6 +2964,7 @@ func evalHGET(args []string, store *dstore.Store) []byte {
return val
}
+<<<<<<< HEAD | internal/eval/eval.go | 26 | Go | 0.143 | suggestion | 49 | 51 | 51 | false | #656: added HVALS command | 710 | DiceDB/dice | 10,326 | C | princejha95 | bijuli74 |
}
keyValuePairs := args[1:]
hashMap, numKeys, err := hashMapBuilder(keyValuePairs, hashMap)
if err != nil {
return diceerrors.NewErrWithMessage(err.Error())
}
obj = store.NewObj(hashMap, -1, object.ObjTypeHashMap, object.ObjEncodingHashMap)
store.Put(key, obj)
return clientio.Encode(numKeys, false)
}
fun... | Error handling needs to be improved. Instead of directly returning errWithMessage, it would be better to wrap it with additional context for better readability and debugging. You can use `diceerrors.NewErrWithFormattedMessage(errWithMessage)`.
For example:
```go
errWithMessage := object.AssertTypeAndEncoding(obj.T... | }
keyValuePairs := args[1:]
hashMap, numKeys, err := hashMapBuilder(keyValuePairs, hashMap)
if err != nil {
return diceerrors.NewErrWithMessage(err.Error())
}
obj = store.NewObj(hashMap, -1, object.ObjTypeHashMap, object.ObjEncodingHashMap)
store.Put(key, obj)
return clientio.Encode(numKeys, false)
}
fun... | @@ -2883,6 +2883,26 @@ func evalHSET(args []string, store *dstore.Store) []byte {
return clientio.Encode(numKeys, false)
}
+func evalHSETNX(args []string, store *dstore.Store) []byte {
+ if len(args) != 3 {
+ return diceerrors.NewErrArity("HSETNX")
+ }
+
+ key := args[0]
+ hmKey := args[1]
+
+ val, errWithMessage... | internal/eval/eval.go | 26 | Go | 1 | bug | 473 | 51 | 51 | false | #654: feat: Implement HSETNX command | 715 | DiceDB/dice | 10,326 | C | manishrw | shreyas23sk |
{
name: "hmget with wrongtype",
commands: []string{"SET key_hmGet1 field", "HMGET key_hmGet1 field"},
expected: []interface{}{"OK", "WRONGTYPE Operation against a key holding the wrong kind of value"},
},
{
name: "wrong number of arguments",
commands: []string{"HMGET key_hmGet", "HMGET"},
... | Hi @vishnuchandrashekar , I see we are using reflect to test the map. Would it be okay to check if we can achieve this using `github.com/stretchr/testify/assert` package as we are already transitioning to it. This will ensure consistency with other files.
If it is possible, I would like to suggest using this package ... | package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestHMGET(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
defer FireCommand(conn, "DEL key_hmGet key_hmGet1")
testCases := []TestCase{
{
name: "hmget existing keys and fields",
commands: []string{"HSET key_hmGet field... | @@ -0,0 +1,101 @@
+package async
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestHMGET(t *testing.T) {
+ conn := getLocalConnection()
+ var smallHashKeys []string
+ var smallHashValues []string
+ var bigHashKeys []string
+ var bigHashValues []string
+ // Setup smallHa... | integration_tests/commands/async/hmget_test.go | 26 | Go | 0.571 | suggestion | 362 | 36 | 58 | false | #650: Implementation `HMGET` command | 743 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | vishnuchandrashekar |
name: "wrong number of arguments",
commands: []string{"HMGET key_hmGet", "HMGET"},
expected: []interface{}{"ERR wrong number of arguments for 'hmget' command",
"ERR wrong number of arguments for 'hmget' command"},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
for i, c... | We can format this in a much nicer and readable way instead of using such if conditions.
```go
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
for i, cmd := range tc.commands {
// Fire the command and get the result
result := FireCommand(conn, cmd)
// Extract expected result... | package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestHMGET(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
defer FireCommand(conn, "DEL key_hmGet key_hmGet1")
testCases := []TestCase{
{
name: "hmget existing keys and fields",
commands: []string{"HSET key_hmGet field... | @@ -0,0 +1,101 @@
+package async
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestHMGET(t *testing.T) {
+ conn := getLocalConnection()
+ var smallHashKeys []string
+ var smallHashValues []string
+ var bigHashKeys []string
+ var bigHashValues []string
+ // Setup smallHa... | integration_tests/commands/async/hmget_test.go | 26 | Go | 0.857 | refactor | 1,523 | 30 | 58 | false | #650: Implementation `HMGET` command | 743 | DiceDB/dice | 10,326 | C | JyotinderSingh | vishnuchandrashekar |
"gotest.tools/v3/assert"
)
func TestHMGET(t *testing.T) {
conn := getLocalConnection()
var smallHashKeys []string
var smallHashValues []string
var bigHashKeys []string
var bigHashValues []string
// Setup smallHash
for i := 0; i < 8; i++ {
key := fmt.Sprintf("field%d", i)
value := fmt.Sprintf("value%d", i)... | Why do we need so many values? This looks more like a benchmark here. A test should ideally be small, easy to understand, and easy to debug. |
func TestHMGET(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
defer FireCommand(conn, "DEL key_hmGet key_hmGet1")
testCases := []TestCase{
{
name: "hmget existing keys and fields",
commands: []string{"HSET key_hmGet field value", "HSET key_hmGet field2 value_new", "HMGET key_hmGet fie... | @@ -0,0 +1,101 @@
+package async
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestHMGET(t *testing.T) {
+ conn := getLocalConnection()
+ var smallHashKeys []string
+ var smallHashValues []string
+ var bigHashKeys []string
+ var bigHashValues []string
+ // Setup smallHa... | integration_tests/commands/async/hmget_test.go | 26 | Go | 0.571 | bug | 140 | 51 | 51 | false | #650: Implementation `HMGET` command | 743 | DiceDB/dice | 10,326 | C | JyotinderSingh | vishnuchandrashekar |
package async
import (
"fmt"
"reflect"
"strings"
"testing"
"gotest.tools/v3/assert"
)
func TestHMGET(t *testing.T) {
conn := getLocalConnection()
var smallHashKeys []string
var smallHashValues []string
var bigHashKeys []string
var bigHashValues []string
// Setup smallHash
for i := 0; i < 8; i++ {
key :... | To reduce any chances of flakiness, defer a method which cleans up any keys created by this test at the end of execution. | package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestHMGET(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
defer FireCommand(conn, "DEL key_hmGet key_hmGet1")
testCases := []TestCase{
{
name: "hmget existing keys and fields",
commands: []string{"HSET key_hmGet field... | @@ -0,0 +1,101 @@
+package async
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestHMGET(t *testing.T) { | integration_tests/commands/async/hmget_test.go | 9 | Go | 0.357 | suggestion | 121 | 34 | 34 | false | #650: Implementation `HMGET` command | 743 | DiceDB/dice | 10,326 | C | JyotinderSingh | vishnuchandrashekar |
elems := make([]interface{}, count)
for i := range elems {
elem, err := rp.DecodeOne()
if err != nil {
return nil, err
}
elems[i] = elem
}
return elems, nil
}
func encodeString(v string) []byte {
return []byte(fmt.Sprintf("$%d\r\n%s\r\n", len(v), v))
}
// encodeBool encodes bool as simple strings
func... | Maybe this can be replaced by the following snippet. And in that case it doesn't need to be a separate function, it can be written directly inside the switch case of the overall `Encode` function.
```suggestion
func encodeBool(v bool) []byte {
return []byte(fmt.Sprintf("+%t\r\n", v))
}
``` | elems := make([]interface{}, count)
for i := range elems {
elem, err := rp.DecodeOne()
if err != nil {
return nil, err
}
elems[i] = elem
}
return elems, nil
}
func encodeString(v string) []byte {
return []byte(fmt.Sprintf("$%d\r\n%s\r\n", len(v), v))
}
// encodeBool encodes bool as simple strings
func... | @@ -152,17 +152,42 @@ func encodeString(v string) []byte {
return []byte(fmt.Sprintf("$%d\r\n%s\r\n", len(v), v))
}
+// encodeBool encodes bool as simple strings
+func encodeBool(v bool) []byte {
+ var val string
+ switch v {
+ case true:
+ val = "true"
+ case false:
+ val = "false"
+ }
+ return []byte(fmt.Sprin... | internal/clientio/resp.go | 26 | Go | 0.857 | suggestion | 296 | 51 | 51 | false | #500: Added JSON.RESP Command | 751 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
// encodeBool encodes bool as simple strings
func encodeBool(v bool) []byte {
var val string
switch v {
case true:
val = "true"
case false:
val = "false"
}
return []byte(fmt.Sprintf("+%v\r\n", val))
}
func Encode(value interface{}, isSimple bool) []byte {
switch v := value.(type) {
case string:
// encode... | ```suggestion
// In case the element being encoded was obtained after parsing a JSON value, it is possible for integers to have been encoded as floats (since encoding/json unmarshals numeric values as floats). Therefore, we need to check if value is an integer
``` | // encodeBool encodes bool as simple strings
func encodeBool(v bool) []byte {
return []byte(fmt.Sprintf("+%t\r\n", v))
}
func Encode(value interface{}, isSimple bool) []byte {
switch v := value.(type) {
case string:
// encode as simple strings
if isSimple || v == "[" || v == "{" {
return []byte(fmt.Sprintf("... | @@ -152,17 +152,42 @@ func encodeString(v string) []byte {
return []byte(fmt.Sprintf("$%d\r\n%s\r\n", len(v), v))
}
+// encodeBool encodes bool as simple strings
+func encodeBool(v bool) []byte {
+ var val string
+ switch v {
+ case true:
+ val = "true"
+ case false:
+ val = "false"
+ }
+ return []byte(fmt.Sprin... | internal/clientio/resp.go | 26 | Go | 0.786 | suggestion | 268 | 51 | 51 | false | #500: Added JSON.RESP Command | 751 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
switch v {
case true:
val = "true"
case false:
val = "false"
}
return []byte(fmt.Sprintf("+%v\r\n", val))
}
func Encode(value interface{}, isSimple bool) []byte {
switch v := value.(type) {
case string:
// encode as simple strings
if isSimple || v == "[" || v == "{" {
return []byte(fmt.Sprintf("+%s\r... | Are we sure this modified logic doesn't end up messing up cases where someone stores a whole number in floating point representation? Something like `5.0`? How does redis behave in such cases? | }
func Encode(value interface{}, isSimple bool) []byte {
switch v := value.(type) {
case string:
// encode as simple strings
if isSimple || v == "[" || v == "{" {
return []byte(fmt.Sprintf("+%s\r\n", v))
}
// encode as bulk strings
return encodeString(v)
case int, int8, int16, int32, int64, uint, uint8... | @@ -152,17 +152,42 @@ func encodeString(v string) []byte {
return []byte(fmt.Sprintf("$%d\r\n%s\r\n", len(v), v))
}
+// encodeBool encodes bool as simple strings
+func encodeBool(v bool) []byte {
+ var val string
+ switch v {
+ case true:
+ val = "true"
+ case false:
+ val = "false"
+ }
+ return []byte(fmt.Sprin... | internal/clientio/resp.go | 26 | Go | 0.5 | question | 192 | 51 | 51 | false | #500: Added JSON.RESP Command | 751 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"g... | Love how clean this implementation is! | for i := 0; i < abs(count); i++ {
if count > 0 && len(resultSet) == len(keys) {
break
}
randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(keys))))
randomField := keys[randomIndex.Int64()]
if count > 0 {
if _, exists := resultSet[randomField]; exists {
i--
continue
}
resultSet... | @@ -4232,3 +4232,80 @@ func selectRandomFields(hashMap HashMap, count int, withValues bool) []byte {
return clientio.Encode(results, false)
}
+
+func evalJSONRESP(args []string, store *dstore.Store) []byte { | internal/eval/eval.go | 26 | Go | 0.071 | suggestion | 38 | 4,312 | 51 | false | #500: Added JSON.RESP Command | 751 | DiceDB/dice | 10,326 | C | JyotinderSingh | psrvere |
"net/http/httptest"
"strings"
"testing"
"github.com/dicedb/dice/internal/cmd"
"github.com/stretchr/testify/assert"
)
func TestParseHTTPRequest(t *testing.T) {
commands := []struct {
name string
method string
url string
body string
expectedCmd string
expectedArgs []str... | Can we add more tests for this?
Have arrays and submaps inside value | "net/http/httptest"
"strings"
"testing"
"github.com/dicedb/dice/internal/cmd"
"github.com/stretchr/testify/assert"
)
func TestParseHTTPRequest(t *testing.T) {
commands := []struct {
name string
method string
url string
body string
expectedCmd string
expectedArgs []str... | @@ -26,6 +26,14 @@ func TestParseHTTPRequest(t *testing.T) {
expectedCmd: "SET",
expectedArgs: []string{"k1", "v1", "nx"},
},
+ { | internal/server/utils/redisCmdAdapter_test.go | 26 | Go | 0.214 | question | 69 | 51 | 51 | false | Marshalling the value in set command | 757 | DiceDB/dice | 10,326 | C | pratikpandey21 | lovish2525 |
package async
import (
"math/rand"
"testing"
"time"
"gotest.tools/v3/assert"
)
func randString(n int, charset string) string {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, n)
for i := range b {
b[i] = charset[r.Intn(len(charset))]
}
return string(b)
}
func TestAPPEND(t *testing.... | No need for randomly generated keys in a test. It makes it harder to debug. | package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestAPPEND(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
defer FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
setErrorMsg := "WRONGTYPE Operation against ... | @@ -0,0 +1,100 @@
+package async
+
+import (
+ "math/rand"
+ "testing"
+ "time"
+
+ "gotest.tools/v3/assert"
+)
+
+func randString(n int, charset string) string {
+ r := rand.New(rand.NewSource(time.Now().UnixNano()))
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = charset[r.Intn(len(charset))]
+ }
+ return strin... | integration_tests/commands/async/append_test.go | 18 | Go | 0.357 | bug | 75 | 43 | 43 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
{
name: "APPEND to Integer Values",
commands: []string{
"DEL key",
"APPEND key 1",
"APPEND key 2",
"GET key",
"SET key 1",
"APPEND key 2",
"GET key",
},
expected: []interface{}{int64(0), int64(1), int64(2), "12", "OK", int64(2), "12"},
},
}
for fuzzType, charset := range t... | why are we running a for loop for so many values? This looks more like a benchmark. A test should ideally be fast, small, easy to follow, and easy to debug.
We probably don't need so many iterations. | {
name: "APPEND with Various Data Types",
commands: []string{
"LPUSH listKey lValue", // Add element to a list
"SETBIT bitKey 0 1", // Set a bit in a bitmap
"HSET hashKey hKey hValue", // Set a field in a hash
"SADD setKey sValue", // Add element to a set
"APPEND listKey val... | @@ -0,0 +1,100 @@
+package async
+
+import (
+ "math/rand"
+ "testing"
+ "time"
+
+ "gotest.tools/v3/assert"
+)
+
+func randString(n int, charset string) string {
+ r := rand.New(rand.NewSource(time.Now().UnixNano()))
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = charset[r.Intn(len(charset))]
+ }
+ return strin... | integration_tests/commands/async/append_test.go | 26 | Go | 0.643 | bug | 202 | 51 | 28 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
package async
import (
"math/rand"
"testing"
"time"
"gotest.tools/v3/assert"
)
func randString(n int, charset string) string {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, n)
for i := range b {
b[i] = charset[r.Intn(len(charset))]
}
return string(b)
}
func TestAPPEND(t *testing.... | A good way to understand the kind of tests you should be trying to write is to look at the redis documentation for the command, and ensure that every single case being talked about there is easily being tested as a part of your function.
Additionally, ensure that you are covering any potential edge cases. | package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestAPPEND(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
defer FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
setErrorMsg := "WRONGTYPE Operation against ... | @@ -0,0 +1,100 @@
+package async
+
+import (
+ "math/rand"
+ "testing"
+ "time"
+
+ "gotest.tools/v3/assert"
+)
+
+func randString(n int, charset string) string {
+ r := rand.New(rand.NewSource(time.Now().UnixNano()))
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = charset[r.Intn(len(charset))]
+ }
+ return strin... | integration_tests/commands/async/append_test.go | 9 | Go | 0.643 | bug | 309 | 34 | 34 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
for fuzzType, charset := range types {
buf := ""
commands := []string{"DEL key"}
expected := []interface{}{int64(0)}
for i := 0; i < 1000; i++ {
bin := randString(rand.Intn(10)+1, charset)
buf += bin
commands = append(commands, "APPEND key "+bin)
expected = append(expected, int64(len(buf)))
}
... | It's not instantly clear what is happening here, which is a sign that it can probably be structured better with some comments. | package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestAPPEND(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
defer FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
setErrorMsg := "WRONGTYPE Operation against ... | @@ -0,0 +1,100 @@
+package async
+
+import (
+ "math/rand"
+ "testing"
+ "time"
+
+ "gotest.tools/v3/assert"
+)
+
+func randString(n int, charset string) string {
+ r := rand.New(rand.NewSource(time.Now().UnixNano()))
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = charset[r.Intn(len(charset))]
+ }
+ return strin... | integration_tests/commands/async/append_test.go | 26 | Go | 0.429 | suggestion | 126 | 39 | 76 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"g... | Ensure that the error messages match those of redis for all the error cases. Please also add tests for them. | }
randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(keys))))
randomField := keys[randomIndex.Int64()]
if count > 0 {
if _, exists := resultSet[randomField]; exists {
i--
continue
}
resultSet[randomField] = struct{}{}
}
results = append(results, randomField)
if withValues {
... | @@ -4232,3 +4232,49 @@ func selectRandomFields(hashMap HashMap, count int, withValues bool) []byte {
return clientio.Encode(results, false)
}
+
+func evalAPPEND(args []string, store *dstore.Store) []byte { | internal/eval/eval.go | 26 | Go | 0.5 | suggestion | 108 | 4,281 | 51 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
}
}
return clientio.Encode(results, false)
}
func evalAPPEND(args []string, store *dstore.Store) []byte {
if len(args) != 2 {
return diceerrors.NewErrArity("APPEND")
}
key, value := args[0], args[1]
obj := store.Get(key)
if obj == nil {
// Key does not exist path
oType, oEnc := deduceTypeEncoding(val... | You would ideally store the error message in a constant inside the constants file. | end = len(str) + end
}
if start >= len(str) || end < 0 || start > end {
return clientio.Encode("", false)
}
if start < 0 {
start = 0
}
if end >= len(str) {
end = len(str) - 1
}
return clientio.Encode(str[start:end+1], false)
}
// evalHRANDFIELD returns random fields from a hash stored at key.
// If... | @@ -4232,3 +4232,49 @@ func selectRandomFields(hashMap HashMap, count int, withValues bool) []byte {
return clientio.Encode(results, false)
}
+
+func evalAPPEND(args []string, store *dstore.Store) []byte {
+ if len(args) != 2 {
+ return diceerrors.NewErrArity("APPEND")
+ }
+
+ key, value := args[0], args[1]
+ obj... | internal/eval/eval.go | 26 | Go | 0.357 | suggestion | 82 | 51 | 51 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.com/axiomhq/hyperloglog"
"g... | Maybe a better way to implement this would be as follows. It reduces duplication, and makes it easier to follow the flow.
You may need to change parts of it so that the error messages match those of redis.
```go
func evalAPPEND(args []string, store *dstore.Store) []byte {
if len(args) != 2 {
return... | }
randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(keys))))
randomField := keys[randomIndex.Int64()]
if count > 0 {
if _, exists := resultSet[randomField]; exists {
i--
continue
}
resultSet[randomField] = struct{}{}
}
results = append(results, randomField)
if withValues {
... | @@ -4232,3 +4232,49 @@ func selectRandomFields(hashMap HashMap, count int, withValues bool) []byte {
return clientio.Encode(results, false)
}
+
+func evalAPPEND(args []string, store *dstore.Store) []byte { | internal/eval/eval.go | 26 | Go | 1 | style | 1,589 | 4,281 | 51 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestAPPEND(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
setErrorMsg := "WRONGTYPE Operation against a key holding the wrong kind of value"
testCases := []struct {
name string
commands []string
expected []interface{}
... | Cleanup before and after the test to ensure stability
```suggestion
FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
defer FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
``` | package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestAPPEND(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
defer FireCommand(conn, "DEL key listKey bitKey hashKey setKey")
setErrorMsg := "WRONGTYPE Operation against ... | @@ -0,0 +1,72 @@
+package async
+
+import (
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestAPPEND(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+ | integration_tests/commands/async/append_test.go | 12 | Go | 0.786 | suggestion | 212 | 37 | 37 | false | #638: Adds APPEND Command | 759 | DiceDB/dice | 10,326 | C | JyotinderSingh | arbha1erao |
KeyValues = "key_values"
True = "true"
QwatchQuery = "query"
)
func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
commandParts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
if len(commandParts) == 0 {
return nil, errors.New("invalid command")
}
command := strings.ToUpper(co... | Are there any cases for this scenario? | Seconds = "seconds"
KeyValues = "key_values"
True = "true"
QwatchQuery = "query"
Offset = "offset"
Member = "member"
Members = "members"
Index = "index"
JSON = "json"
)
func ParseHTTPRequest(r *http.Request) (*cmd.DiceDBCmd, error) {
commandParts := strings.Split(strin... | @@ -28,14 +28,29 @@ const (
)
func ParseHTTPRequest(r *http.Request) (*cmd.RedisCmd, error) {
- command := strings.TrimPrefix(r.URL.Path, "/")
- if command == "" {
+ commandParts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
+ if len(commandParts) == 0 {
return nil, errors.New("invalid command")
}... | internal/server/utils/redisCmdAdapter.go | 26 | Go | 0.071 | question | 38 | 51 | 51 | false | #735: tests: COMMAND GETKEYS, COMMAND INFO, COMMAND LIST, COMMAND RENAME, COPY | 768 | DiceDB/dice | 10,326 | C | pratikpandey21 | Indranil0603 |
package http
import (
"testing"
"gotest.tools/v3/assert"
)
func TestGetKeys(t *testing.T) {
exec := NewHTTPCommandExecutor()
testCases := []TestCase{
{
name: "Set command",
commands: []HTTPCommand{
{Command: "COMMAND/GETKEYS/SET", Body: map[string]interface{}{"key": "1", "value": "2"}},
},
exp... | Please use the same set of tests that exists for async | package http
import (
"testing"
"gotest.tools/v3/assert"
)
func TestCommandGetKeys(t *testing.T) {
exec := NewHTTPCommandExecutor()
testCases := []TestCase{
{
name: "Set command",
commands: []HTTPCommand{
{Command: "COMMAND/GETKEYS", Body: map[string]interface{}{"key": "SET", "keys": []interface{}{"... | @@ -0,0 +1,30 @@
+package http
+
+import (
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestGetKeys(t *testing.T) { | integration_tests/commands/http/command_getkeys_test.go | 9 | Go | 0.286 | suggestion | 54 | 31 | 34 | false | #735: tests: COMMAND GETKEYS, COMMAND INFO, COMMAND LIST, COMMAND RENAME, COPY | 768 | DiceDB/dice | 10,326 | C | pratikpandey21 | Indranil0603 |
t.Run(tc.name, func(t *testing.T) {
FireCommand(conn, tc.setCommand)
expected := tc.expected
out := FireCommand(conn, tc.testCommand)
_, isString := out.(string)
if isString {
outInterface := []interface{}{out}
assert.DeepEqual(t, outInterface, expected)
} else {
assert.DeepEqual(t, out... | Let's add some cleanup code here which will ensure other tests don't interfere with this one, and this test doesn't interfere with them.
```suggestion
defer conn.Close()
a := `[0,1,2]`
b := `{"connection":{"wireless":true,"names":[0,1,2,3,4]},"names":[0,1,2,3,4]}`
FireCommand(conn, "DEL a b")
... | t.Run(tc.name, func(t *testing.T) {
FireCommand(conn, tc.setCommand)
expected := tc.expected
out := FireCommand(conn, tc.testCommand)
_, isString := out.(string)
if isString {
outInterface := []interface{}{out}
assert.DeepEqual(t, outInterface, expected)
} else {
assert.DeepEqual(t, out... | @@ -1296,3 +1296,82 @@ func TestJsonObjKeys(t *testing.T) {
}
}
+func TestJsonARRTRIM(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+ a := `[0,1,2]`
+ b := `{"connection":{"wireless":true,"names":[0,1,2,3,4]},"names":[0,1,2,3,4]}`
+
+ testCases := []struct { | integration_tests/commands/async/json_test.go | 26 | Go | 0.786 | suggestion | 390 | 51 | 51 | false | #490: feat:add support for command [JSON.ARRTRIM] | 769 | DiceDB/dice | 10,326 | C | JyotinderSingh | jujiale |
// evalHEXISTS returns if field is an existing field in the hash stored at key.
//
// This command returns 0, if the specified field doesn't exist in the key and 1 if it exists.
//
// If key doesn't exist, it returns 0.
//
// Usage: HEXISTS key field
func evalHEXISTS(args []string, store *dstore.Store) []byte {
if len... | This should be structured as follows for better readability:
```go
if obj == nil {
return Encode(0, false)
}
if err := assertType(...) {
return err
}
``` | //
// Usage: HEXISTS key field
func evalHEXISTS(args []string, store *dstore.Store) []byte {
if len(args) != 2 {
return diceerrors.NewErrArity("HEXISTS")
}
key := args[0]
hmKey := args[1]
obj := store.Get(key)
var hashMap HashMap
if obj == nil {
return clientio.Encode(0, false)
}
if err := object.Assert... | @@ -3236,6 +3236,41 @@ func evalHSTRLEN(args []string, store *dstore.Store) []byte {
return clientio.Encode(0, false)
}
+// evalHEXISTS returns if field is an existing field in the hash stored at key.
+//
+// This command returns 0, if the specified field doesn't exist in the key and 1 if it exists.
+//
+// If key... | internal/eval/eval.go | 26 | Go | 0.929 | suggestion | 162 | 51 | 51 | false | #646: Adds support for HEXISTS command | 864 | DiceDB/dice | 10,326 | C | JyotinderSingh | c-harish |
package async
import (
"testing"
"gotest.tools/v3/assert"
)
func TestHEXISTS(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
defer FireCommand(conn, "DEL key_hExists1 key_hExists2 key_hExists3 key")
testCases := []TestCase{
{
commands: []string{"HEXISTS", "HEXISTS KEY", "HEXISTS KEY FIELD... | Clear the keys both before and after the test for better stability
```suggestion
FireCommand(conn, "DEL key_hExists1 key_hExists2 key_hExists3 key")
defer FireCommand(conn, "DEL key_hExists1 key_hExists2 key_hExists3 key")
```
| package async
import (
"testing"
testifyAssert "github.com/stretchr/testify/assert"
)
func TestHEXISTS(t *testing.T) {
conn := getLocalConnection()
FireCommand(conn, "DEL key_hExists1 key_hExists2 key_hExists3 key")
defer conn.Close()
defer FireCommand(conn, "DEL key_hExists1 key_hExists2 key_hExists3 key")
... | @@ -0,0 +1,45 @@
+package async
+
+import (
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestHEXISTS(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+ defer FireCommand(conn, "DEL key_hExists1 key_hExists2 key_hExists3 key") | integration_tests/commands/async/hexists_test.go | 14 | Go | 0.857 | suggestion | 232 | 39 | 39 | false | #646: Adds support for HEXISTS command | 864 | DiceDB/dice | 10,326 | C | JyotinderSingh | c-harish |
}
}
type WebsocketCommand struct {
Message string
}
func (e *WebsocketCommandExecutor) ConnectToServer() *websocket.Conn {
// connect with Websocket Server
conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
return nil
}
if resp != nil {
resp.Body.Close()
}
return conn
}
func (e *W... | I believe we should retain this and test explicitly for error/negative cases. May be we can add in another PR but we should test explicitly invoked error scenarios. | }
func (e *WebsocketCommandExecutor) ConnectToServer() *websocket.Conn {
// connect with Websocket Server
conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
return nil
}
if resp != nil {
resp.Body.Close()
}
return conn
}
func (e *WebsocketCommandExecutor) FireCommand(conn *websocket.... | @@ -65,28 +60,28 @@ func (e *WebsocketCommandExecutor) ConnectToServer() *websocket.Conn {
return conn
}
-func (e *WebsocketCommandExecutor) FireCommand(conn *websocket.Conn, cmd WebsocketCommand) (interface{}, error) {
- command := []byte(cmd.Message)
+func (e *WebsocketCommandExecutor) FireCommand(conn *websocke... | integration_tests/commands/websocket/setup.go | 26 | Go | 0.571 | suggestion | 164 | 51 | 51 | false | Websocket integration tests - SET and GET | 878 | DiceDB/dice | 10,326 | C | lucifercr07 | psrvere |
func TestJsonSTRAPPEND(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
simpleJSON := `{"name":"John","age":30}`
testCases := []struct {
name string
setCmd string
getCmd string
expected interface{}
}{
{
name: "STRAPPEND to nested string",
setCmd: `JSON.SET doc $ ` + s... | Would it be possible to add the cleanup logic using defer here. | expected: []interface{}{"OK", []interface{}{int64(0)}, `{"names":[],"connection":{"wireless":true,"names":[0,1,2,3,4]}}`},
assertType: []string{"equal", "deep_equal", "jsoneq"},
},
}
for _, tcase := range testCases {
t.Run(tcase.name, func(t *testing.T) {
for i := 0; i < len(tcase.commands); i++ {
... | @@ -1378,3 +1378,62 @@ func TestJsonARRTRIM(t *testing.T) {
})
}
}
+
+func TestJsonSTRAPPEND(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+ | integration_tests/commands/async/json_test.go | 26 | Go | 0.214 | suggestion | 64 | 51 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | karandixit10 |
DiceCmds["JSON.GET"] = jsongetCmdMeta
DiceCmds["JSON.TYPE"] = jsontypeCmdMeta
DiceCmds["JSON.CLEAR"] = jsonclearCmdMeta
DiceCmds["JSON.DEL"] = jsondelCmdMeta
DiceCmds["JSON.ARRAPPEND"] = jsonarrappendCmdMeta
DiceCmds["JSON.FORGET"] = jsonforgetCmdMeta
DiceCmds["JSON.ARRLEN"] = jsonarrlenCmdMeta
DiceCmds["JSON.N... | Since JSON.STRAPPEND takes only 3 arguments, we can set Arity to 3. | If the key already exists then the value and expiry will be overwritten`,
Arity: 3,
KeySpecs: KeySpecs{BeginIndex: 1},
IsMigrated: true,
NewEval: evalSETEX,
}
hrandfieldCmdMeta = DiceCmdMeta{
Name: "HRANDFIELD",
Info: `Returns one or more random fields from a hash.`,
Eval: evalHR... | @@ -971,6 +971,16 @@ var (
Arity: -4,
KeySpecs: KeySpecs{BeginIndex: 1},
}
+ jsonstrappendCmdMeta = DiceCmdMeta{
+ Name: "JSON.STRAPPEND",
+ Info: `JSON.STRAPPEND key [path] value
+ Append the JSON string values to the string at path
+ Returns an array of integer replies for each path, the string's new l... | internal/eval/commands.go | 26 | Go | 0.214 | suggestion | 67 | 51 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | karandixit10 |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/google/btree"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.... | Hi, this return can to be updated. Currently the message in dice is:

But in redis:

I understand we have to replace dice with redis, but ... |
// if path is not root then extract value at path
expr, err := jp.ParseString(path)
if err != nil {
return diceerrors.NewErrWithMessage("invalid JSONPath")
}
results := expr.Get(jsonData)
// process value at each path
ret := []any{}
for _, result := range results {
resp := parseJSONStructure(result, false... | @@ -4534,3 +4534,72 @@ func evalHINCRBYFLOAT(args []string, store *dstore.Store) []byte {
return clientio.Encode(numkey, false)
}
+
+// evalJSONSTRAPPEND appends a string value to the JSON string value at the specified path
+// in the JSON object saved at the key in arguments.
+// Args must contain at least a key ... | internal/eval/eval.go | 26 | Go | 1 | bug | 1,015 | 4,606 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | karandixit10 |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/google/btree"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.... | ```suggestion
_, modifyErr := expr.Modify(jsonData, func(data any) (interface{}, bool) {
switch v := data.(type) {
case string:
unquotedValue := strings.Trim(value, "\"")
newValue := v + unquotedValue
resultsArray = append([]interface{}{int64(len(newValue))}, resultsArray...)
return newVa... | }
default:
resp = append(resp, []byte("(unsupported type)"))
}
return resp
}
// evalZADD adds all the specified members with the specified scores to the sorted set stored at key.
// If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position... | @@ -4534,3 +4534,72 @@ func evalHINCRBYFLOAT(args []string, store *dstore.Store) []byte {
return clientio.Encode(numkey, false)
}
+
+// evalJSONSTRAPPEND appends a string value to the JSON string value at the specified path
+// in the JSON object saved at the key in arguments.
+// Args must contain at least a key ... | internal/eval/eval.go | 26 | Go | 0.929 | suggestion | 673 | 4,606 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | karandixit10 |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/google/btree"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.... | nit:
```suggestion
return clientio.RespEmptyArray
``` | case string, bool:
resp = append(resp, json)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, nil:
resp = append(resp, json)
case map[string]interface{}:
resp = append(resp, "{")
for key, value := range json {
resp = append(resp, key)
resp = append(resp, parse... | @@ -4534,3 +4534,72 @@ func evalHINCRBYFLOAT(args []string, store *dstore.Store) []byte {
return clientio.Encode(numkey, false)
}
+
+// evalJSONSTRAPPEND appends a string value to the JSON string value at the specified path
+// in the JSON object saved at the key in arguments.
+// Args must contain at least a key ... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 67 | 4,606 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | karandixit10 |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/google/btree"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.... | ```suggestion
return clientio.RespEmptyArray
``` | resp = append(resp, parseJSONStructure(value, true)...)
}
// wrap in another array to offset print
if nested {
resp = []interface{}{resp}
}
default:
resp = append(resp, []byte("(unsupported type)"))
}
return resp
}
// evalZADD adds all the specified members with the specified scores to the sorted se... | @@ -4534,3 +4534,72 @@ func evalHINCRBYFLOAT(args []string, store *dstore.Store) []byte {
return clientio.Encode(numkey, false)
}
+
+// evalJSONSTRAPPEND appends a string value to the JSON string value at the specified path
+// in the JSON object saved at the key in arguments.
+// Args must contain at least a key ... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 62 | 4,606 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | karandixit10 |
package eval
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"math/bits"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unsafe"
"github.com/google/btree"
"github.com/dicedb/dice/internal/object"
"github.com/rs/xid"
"github.com/dicedb/dice/internal/sql"
"github.... | nit:
```suggestion
return clientio.RespEmptyArray
``` | return clientio.Encode(ret, false)
}
func parseJSONStructure(jsonData interface{}, nested bool) (resp []any) {
switch json := jsonData.(type) {
case string, bool:
resp = append(resp, json)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, nil:
resp = append(resp, json)... | @@ -4534,3 +4534,72 @@ func evalHINCRBYFLOAT(args []string, store *dstore.Store) []byte {
return clientio.Encode(numkey, false)
}
+
+// evalJSONSTRAPPEND appends a string value to the JSON string value at the specified path
+// in the JSON object saved at the key in arguments.
+// Args must contain at least a key ... | internal/eval/eval.go | 26 | Go | 0.571 | suggestion | 61 | 4,606 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | karandixit10 |
"incr on array element": {
setup: func() {
key := "number"
value := "{\"a\": [1, 2, 3]}"
var rootData interface{}
_ = sonic.Unmarshal([]byte(value), &rootData)
obj := store.NewObj(rootData, -1, object.ObjTypeJSON, object.ObjEncodingJSON)
store.Put(key, obj)
},
input: []string{"number... | Is this change in line with Redis output? | }
store.Put(key, obj)
srcKey := "EXISTING_SRC_KEY"
srcValue := hyperloglog.New()
value.Insert([]byte("SRC_VALUE"))
srcKeyObj := &object.Obj{
Value: srcValue,
LastAccessedAt: uint32(time.Now().Unix()),
}
store.Put(srcKey, srcKeyObj)
},
input: []string{"EXISTING_D... | @@ -2520,7 +2521,7 @@ func testEvalLLEN(t *testing.T, store *dstore.Store) {
evalSET([]string{"EXISTING_KEY", "mock_value"}, store)
},
input: []string{"EXISTING_KEY"},
- output: []byte("-ERR Existing key has wrong Dice type\r\n"),
+ output: []byte("-Existing key has wrong Dice type\r\n"), | internal/eval/eval_test.go | 26 | Go | 0.143 | question | 41 | 51 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | lucifercr07 | karandixit10 |
expected: []interface{}{int64(7)},
},
{
name: "STRAPPEND to non-string",
setCmd: `JSON.SET doc $ ` + simpleJSON,
getCmd: `JSON.STRAPPEND doc $.age " years"`,
expected: []interface{}{"(nil)"},
},
{
name: "STRAPPEND with empty string",
setCmd: `JSON.SET doc $ ` + simpleJSON,
... | Why're two `DEL` invocations required here? Can we have it as part of logic above as @apoorvyadav1111 suggested: https://github.com/DiceDB/dice/pull/882/files#r1782010024 | conn := getLocalConnection()
defer conn.Close()
simpleJSON := `{"name":"John","age":30}`
testCases := []struct {
name string
setCmd string
getCmd string
expected interface{}
}{
{
name: "STRAPPEND to nested string",
setCmd: `JSON.SET doc $ ` + simpleJSON,
getCmd: `JSON.STRAPPEND... | @@ -1378,3 +1379,62 @@ func TestJsonARRTRIM(t *testing.T) {
})
}
}
+
+func TestJsonSTRAPPEND(t *testing.T) {
+ conn := getLocalConnection()
+ defer conn.Close()
+
+ simpleJSON := `{"name":"John","age":30}`
+
+ testCases := []struct {
+ name string
+ setCmd string
+ getCmd string
+ expected interface{}... | integration_tests/commands/async/json_test.go | 26 | Go | 0.5 | question | 170 | 37 | 51 | false | Add support for command JSON.STRAPPEND #501 | 882 | DiceDB/dice | 10,326 | C | lucifercr07 | karandixit10 |
The key should be the only param in args else returns with an error
Returns
RESP encoded time (in secs) remaining for the key to expire
RESP encoded -2 stating key doesn't exist or key is expired
RESP encoded -1 in case no expiration is set on the key`,
Eval: evalPTTL,
Arity: 2,
KeySpecs: KeySpec... | Since HKEYS only accepts key as the argument, we can keep Arity as 1. | The key should be the only param in args else returns with an error
Returns
RESP encoded time (in secs) remaining for the key to expire
RESP encoded -2 stating key doesn't exist or key is expired
RESP encoded -1 in case no expiration is set on the key`,
Eval: evalPTTL,
Arity: 2,
KeySpecs: KeySpec... | @@ -620,6 +620,13 @@ var (
Arity: -4,
KeySpecs: KeySpecs{BeginIndex: 1},
}
+ hkeysCmdMeta = DiceCmdMeta{
+ Name: "HKEYS",
+ Info: `HKEYS command is used to retrieve all the keys(or field names) within a hash. Complexity is O(n) where n is the size of the hash.`,
+ Eval: evalHKEYS,
+ Arity: -1, | internal/eval/commands.go | 26 | Go | 0.214 | suggestion | 69 | 51 | 51 | false | Add Support for HKEYS command. | 886 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | swarajrb7 |
obj := store.Get(key)
var hashMap HashMap
var numKeys int64
if obj != nil {
if err := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeHashMap, object.ObjEncodingHashMap); err != nil {
return diceerrors.NewErrWithMessage(diceerrors.WrongTypeErr)
}
hashMap = obj.Value.(HashMap)
}
keyValueP... | Could you please add 2-3 lines of comment describing the function on a higher level.
Thanks |
obj := store.Get(key)
var hashMap HashMap
var numKeys int64
if obj != nil {
if err := object.AssertTypeAndEncoding(obj.TypeEncoding, object.ObjTypeHashMap, object.ObjEncodingHashMap); err != nil {
return diceerrors.NewErrWithMessage(diceerrors.WrongTypeErr)
}
hashMap = obj.Value.(HashMap)
}
keyValueP... | @@ -3030,6 +3030,33 @@ func evalHSET(args []string, store *dstore.Store) []byte {
return clientio.Encode(numKeys, false)
}
| internal/eval/eval.go | 26 | Go | 0.286 | suggestion | 92 | 51 | 51 | false | Add Support for HKEYS command. | 886 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | swarajrb7 |
"runtime"
"sync"
"syscall"
"github.com/dicedb/dice/config"
diceerrors "github.com/dicedb/dice/internal/errors"
"github.com/dicedb/dice/internal/logger"
"github.com/dicedb/dice/internal/server"
"github.com/dicedb/dice/internal/server/resp"
"github.com/dicedb/dice/internal/shard"
dstore "github.com/dicedb/dice... | ```suggestion
flag.IntVar(&config.KeysLimit, "keys-limit", config.KeysLimit, "keys limit for the dice server. This flag controls the number of keys each shard holds at startup. You can multiply this number with the total number of shard threads to estimate how much memory will be required at system start up.")
``` | "runtime"
"sync"
"syscall"
"github.com/dicedb/dice/config"
diceerrors "github.com/dicedb/dice/internal/errors"
"github.com/dicedb/dice/internal/logger"
"github.com/dicedb/dice/internal/server"
"github.com/dicedb/dice/internal/server/resp"
"github.com/dicedb/dice/internal/shard"
dstore "github.com/dicedb/dice... | @@ -32,6 +32,7 @@ func init() {
flag.StringVar(&config.CustomConfigFilePath, "o", config.CustomConfigFilePath, "dir path to create the config file")
flag.StringVar(&config.FileLocation, "c", config.FileLocation, "file path of the config file")
flag.BoolVar(&config.InitConfigCmd, "init-config", false, "initialize ... | main.go | 26 | Go | 0.929 | suggestion | 318 | 51 | 51 | false | fix: Allows users to customize the KeysLimit value at server start | 888 | DiceDB/dice | 10,326 | C | JyotinderSingh | vpsinghg |
package http
import (
"fmt"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCount(t *testing.T) {
exec := NewHTTPCommandExecutor()
t.Run("Command count should be positive", func(t *testing.T) {
commandCount := getCommandCount(exec)
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of... | We can add one more scenario for below case
```
redis> COMMAND COUNT 123
(error) wrong number of arguments for 'command|count' command
``` | package http
import (
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCount(t *testing.T) {
exec := NewHTTPCommandExecutor()
testCases := []struct {
name string
commands []HTTPCommand
expected []interface{}
errorExpected bool
assertType []string
}{
{
name: "Command cou... | @@ -0,0 +1,38 @@
+package http
+
+import (
+ "fmt"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCount(t *testing.T) { | integration_tests/commands/http/command_count_test.go | 9 | Go | 0.857 | bug | 142 | 34 | 34 | false | #734: Http Integration tests for COMMAND and COMMAND/COUNT | 899 | DiceDB/dice | 10,326 | C | lucifercr07 | svkaizoku |
package http
import (
"fmt"
"testing"
"gotest.tools/v3/assert"
)
func TestCommandCount(t *testing.T) {
exec := NewHTTPCommandExecutor()
t.Run("Command count should be positive", func(t *testing.T) {
commandCount := getCommandCount(exec)
assert.Assert(t, commandCount > 0,
fmt.Sprintf("Unexpected number of... | Do we not support commands in form of `COMMAND COUNT`? | name: "Command count should not support any argument",
commands: []HTTPCommand{
{Command: "COMMAND/COUNT", Body: map[string]interface{}{"key": ""}},
},
expected: []interface{}{"ERR wrong number of arguments for 'command|count' command"},
assertType: []string{"equal"},
},
}
for _, tc := range te... | @@ -0,0 +1,38 @@
+package http
+
+import (
+ "fmt"
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+func TestCommandCount(t *testing.T) {
+ exec := NewHTTPCommandExecutor()
+ t.Run("Command count should be positive", func(t *testing.T) {
+ commandCount := getCommandCount(exec)
+ assert.Assert(t, commandCount > 0,
+ f... | integration_tests/commands/http/command_count_test.go | 26 | Go | 0.357 | question | 54 | 39 | 45 | false | #734: Http Integration tests for COMMAND and COMMAND/COUNT | 899 | DiceDB/dice | 10,326 | C | lucifercr07 | svkaizoku |
assertType: []string{"equal", "equal"},
delays: []time.Duration{0, 0},
},
{
name: "LPUSH, LPOP, RPUSH, RPOP a key holding a set",
commands: []HTTPCommand{
{Command: "SADD", Body: map[string]interface{}{"key": "foo", "member": "bar"}},
{Command: "LPUSH", Body: map[string]interface{}{"key": "f... | Thanks for taking up my suggestion. Yes, the code format for the file was not as per the requirements, but there are lot of other PRs with the same change, I am sure one of those will have it fixed before this is merged. I have question with this` if ` condition, given that none of the test cases have an empty array.
... | assertType: []string{"equal", "equal"},
delays: []time.Duration{0, 0},
},
{
name: "LPUSH, LPOP, RPUSH, RPOP a key holding a set",
commands: []HTTPCommand{
{Command: "SADD", Body: map[string]interface{}{"key": "foo", "member": "bar"}},
{Command: "LPUSH", Body: map[string]interface{}{"key": "f... | @@ -0,0 +1,125 @@
+package http
+
+import (
+ "testing"
+ "time"
+
+ "gotest.tools/v3/assert"
+)
+
+// This file may contain test cases for checking error messages accross all commands
+func TestErrorsForSetData(t *testing.T) {
+ exec := NewHTTPCommandExecutor()
+ setErrorMsg := "WRONGTYPE Operation against a key holdi... | integration_tests/commands/http/check_type_test.go | 26 | Go | 0.643 | suggestion | 326 | 38 | 34 | false | #734 : Http Commands Error Messages Test | 900 | DiceDB/dice | 10,326 | C | apoorvyadav1111 | svkaizoku |
package async
import (
"testing"
"gotest.tools/v3/assert"
)
var THREE int64 = 3
var FOUR int64 = 4
func TestHSCAN(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
testCases := []TestCase{
{
commands: []string{"HSCAN empty_hash 0"},
expected: []interface{}{[]interface{}{"0", []interface{... | Please add a test case where a new cursor value is returned, then use that cursor value to get the remaining elements. | package async
import (
"testing"
"gotest.tools/v3/assert"
)
var THREE int64 = 3
var FOUR int64 = 4
func TestHSCAN(t *testing.T) {
conn := getLocalConnection()
defer conn.Close()
testCases := []TestCase{
{
commands: []string{"HSCAN empty_hash 0"},
expected: []interface{}{[]interface{}{"0", []interface{... | @@ -0,0 +1,86 @@
+package async
+
+import (
+ "testing"
+
+ "gotest.tools/v3/assert"
+)
+
+var THREE int64 = 3
+var FOUR int64 = 4
+
+func TestHSCAN(t *testing.T) { | integration_tests/commands/async/hscan_test.go | 12 | Go | 0.429 | suggestion | 118 | 37 | 37 | false | #653: Added HSCAN command | 907 | DiceDB/dice | 10,326 | C | JyotinderSingh | manishrw |
count := 10
// Parse optional arguments
for i := 2; i < len(args); i += 2 {
switch strings.ToUpper(args[i]) {
case "MATCH":
if i+1 < len(args) {
pattern = args[i+1]
}
case CountConst:
if i+1 < len(args) {
parsedCount, err := strconv.Atoi(args[i+1])
if err != nil || parsedCount < 1 {
... | This makes our method have O(n) complexity (which is different from redis, which offers O(1)), please add a comment here mentioning the same. Could you also update this commands doc page in the docs directory with this information? | count := 10
// Parse optional arguments
for i := 2; i < len(args); i += 2 {
switch strings.ToUpper(args[i]) {
case "MATCH":
if i+1 < len(args) {
pattern = args[i+1]
}
case CountConst:
if i+1 < len(args) {
parsedCount, err := strconv.Atoi(args[i+1])
if err != nil || parsedCount < 1 {
... | @@ -3238,6 +3240,83 @@ func evalHDEL(args []string, store *dstore.Store) []byte {
return clientio.Encode(count, false)
}
+func evalHSCAN(args []string, store *dstore.Store) []byte {
+ if len(args) < 2 {
+ return diceerrors.NewErrArity("HSCAN")
+ }
+
+ key := args[0]
+ cursor, err := strconv.ParseInt(args[1], 10, ... | internal/eval/eval.go | 26 | Go | 0.5 | performance | 231 | 51 | 51 | false | #653: Added HSCAN command | 907 | DiceDB/dice | 10,326 | C | JyotinderSingh | manishrw |
CustomConfigFilePath = utils.EmptyStr
FileLocation = utils.EmptyStr
InitConfigCmd = false
)
type Config struct {
Server struct {
Addr string `mapstructure:"addr"`
Port int `mapstructure:"port"`
KeepAlive int32 `mapstructure:"k... | Not utilised anywhere, removing. | RequirePass = utils.EmptyStr
CustomConfigFilePath = utils.EmptyStr
FileLocation = utils.EmptyStr
InitConfigCmd = false
KeysLimit = DefaultKeysLimit
)
type Config struct {
Server struct {
Addr string `mapstructure:"addr"`
Port int `mapstructure:"... | @@ -61,13 +61,13 @@ type Config struct {
EvictionRatio float64 `mapstructure:"evictionratio"`
KeysLimit int `mapstructure:"keyslimit"`
AOFFile string `mapstructure:"aoffile"`
- PersistenceEnabled bool `mapstructure:"persistenceenabled"` | config/config.go | 26 | Go | 0.071 | suggestion | 32 | 51 | 51 | false | Adding default config file to be used when dice server starts | 908 | DiceDB/dice | 10,326 | C | lucifercr07 | lucifercr07 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.