Skip to content

Commit

Permalink
Merge pull request #74 from dotslashbit/issue-66
Browse files Browse the repository at this point in the history
feat: INCR command added
  • Loading branch information
kelvinmwinuka authored Jun 21, 2024
2 parents f3cf011 + 11450c7 commit 83308ba
Show file tree
Hide file tree
Showing 6 changed files with 1,529 additions and 1,232 deletions.
2,458 changes: 1,239 additions & 1,219 deletions coverage/coverage.out

Large diffs are not rendered by default.

27 changes: 25 additions & 2 deletions echovault/api_generic.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@
package echovault

import (
"github.com/echovault/echovault/internal"
"strconv"
"strings"

"github.com/echovault/echovault/internal"
)

// SetOptions modifies the behaviour for the Set command
Expand Down Expand Up @@ -349,7 +350,7 @@ func (server *EchoVault) PExpire(key string, milliseconds int, options PExpireOp
return internal.ParseBooleanResponse(b)
}

// ExpireAt set the given key's expiry in unix epoch seconds.
// ExpireAt sets the given key's expiry in unix epoch seconds.
// This command turns a persistent key into a volatile one.
//
// Parameters:
Expand Down Expand Up @@ -416,3 +417,25 @@ func (server *EchoVault) PExpireAt(key string, unixMilliseconds int, options PEx

return internal.ParseIntegerResponse(b)
}

// Incr increments the value at the given key if it's an integer.
// If the key does not exist, it's created with an initial value of 0 before incrementing.
//
// Parameters:
//
// `key` - string
//
// Returns: The new value as an integer.
func (server *EchoVault) Incr(key string) (int, error) {
// Construct the command
cmd := []string{"INCR", key}

// Execute the command
b, err := server.handleCommand(server.context, internal.EncodeCommand(cmd), nil, false, true)
if err != nil {
return 0, err
}

// Parse the integer response
return internal.ParseIntegerResponse(b)
}
69 changes: 67 additions & 2 deletions echovault/api_generic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ package echovault

import (
"context"
"github.com/echovault/echovault/internal"
"github.com/echovault/echovault/internal/clock"
"reflect"
"slices"
"strings"
"testing"
"time"

"github.com/echovault/echovault/internal"
"github.com/echovault/echovault/internal/clock"
)

func TestEchoVault_DEL(t *testing.T) {
Expand Down Expand Up @@ -918,3 +919,67 @@ func TestEchoVault_TTL(t *testing.T) {
})
}
}

func TestEchoVault_INCR(t *testing.T) {
server := createEchoVault()

tests := []struct {
name string
key string
presetValues map[string]internal.KeyData
want int
wantErr bool
}{
{
name: "1. Increment non-existent key",
key: "IncrKey1",
presetValues: nil,
want: 1,
wantErr: false,
},
{
name: "2. Increment existing key with integer value",
key: "IncrKey2",
presetValues: map[string]internal.KeyData{
"IncrKey2": {Value: "5"},
},
want: 6,
wantErr: false,
},
{
name: "3. Increment existing key with non-integer value",
key: "IncrKey3",
presetValues: map[string]internal.KeyData{
"IncrKey3": {Value: "not_an_int"},
},
want: 0,
wantErr: true,
},
{
name: "4. Increment existing key with int64 value",
key: "IncrKey4",
presetValues: map[string]internal.KeyData{
"IncrKey4": {Value: int64(10)},
},
want: 11,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.presetValues != nil {
for k, d := range tt.presetValues {
presetKeyData(server, context.Background(), k, d)
}
}
got, err := server.Incr(tt.key)
if (err != nil) != tt.wantErr {
t.Errorf("TTL() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("TTL() got = %v, want %v", got, tt.want)
}
})
}
}
69 changes: 63 additions & 6 deletions internal/modules/generic/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ package generic
import (
"errors"
"fmt"
"github.com/echovault/echovault/internal"
"github.com/echovault/echovault/internal/constants"
"log"
"strconv"
"strings"
"time"

"github.com/echovault/echovault/internal"
"github.com/echovault/echovault/internal/constants"
)

type KeyObject struct {
Expand Down Expand Up @@ -382,14 +383,61 @@ func handleExpireAt(params internal.HandlerFuncParams) ([]byte, error) {
return []byte(":1\r\n"), nil
}

func handleIncr(params internal.HandlerFuncParams) ([]byte, error) {
// Extract key from command
keys, err := incrKeyFunc(params.Command)
if err != nil {
return nil, err
}

key := keys.WriteKeys[0]
values := params.GetValues(params.Context, []string{key}) // Get the current values for the specified keys
currentValue, ok := values[key] // Check if the key exists

var newValue int64
var currentValueInt int64

// Check if the key exists and its current value
if !ok || currentValue == nil {
// If key does not exist, initialize it with 1
newValue = 1
} else {
// Use type switch to handle different types of currentValue
switch v := currentValue.(type) {
case string:
var err error
currentValueInt, err = strconv.ParseInt(v, 10, 64) // Parse the string to int64
if err != nil {
return nil, errors.New("value is not an integer or out of range")
}
case int:
currentValueInt = int64(v) // Convert int to int64
case int64:
currentValueInt = v // Use int64 value directly
default:
fmt.Printf("unexpected type for currentValue: %T\n", currentValue)
return nil, errors.New("unexpected type for currentValue") // Handle unexpected types
}
newValue = currentValueInt + 1 // Increment the value
}

// Set the new incremented value
if err := params.SetValues(params.Context, map[string]interface{}{key: fmt.Sprintf("%d", newValue)}); err != nil {
return nil, err
}

// Prepare response with the actual new value
return []byte(fmt.Sprintf(":%d\r\n", newValue)), nil
}

func Commands() []internal.Command {
return []internal.Command{
{
Command: "set",
Module: constants.GenericModule,
Categories: []string{constants.WriteCategory, constants.SlowCategory},
Description: `
(SET key value [NX | XX] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds])
(SET key value [NX | XX] [GET] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds])
Set the value of a key, considering the value's type.
NX - Only set if the key does not exist.
XX - Only set if the key exists.
Expand Down Expand Up @@ -442,7 +490,7 @@ PXAT - Expire at the exat time in unix milliseconds (positive integer).`,
Command: "persist",
Module: constants.GenericModule,
Categories: []string{constants.KeyspaceCategory, constants.WriteCategory, constants.FastCategory},
Description: `(PERSIST key) Removes the TTl associated with a key,
Description: `(PERSIST key) Removes the TTl associated with a key,
turning it from a volatile key to a persistent key.`,
Sync: true,
KeyExtractionFunc: persistKeyFunc,
Expand Down Expand Up @@ -525,7 +573,7 @@ LT - Only set the expiry time if the new expiry time is less than the current on
Module: constants.GenericModule,
Categories: []string{constants.KeyspaceCategory, constants.WriteCategory, constants.FastCategory},
Description: `(EXPIREAT key unix-time-seconds [NX | XX | GT | LT])
Expire the key in at the exact unix time in seconds.
Expire the key in at the exact unix time in seconds.
This commands turns a key into a volatile one.
NX - Only set the expiry time if the key has no associated expiry.
XX - Only set the expiry time if the key already has an expiry time.
Expand All @@ -540,7 +588,7 @@ LT - Only set the expiry time if the new expiry time is less than the current on
Module: constants.GenericModule,
Categories: []string{constants.KeyspaceCategory, constants.WriteCategory, constants.FastCategory},
Description: `(PEXPIREAT key unix-time-milliseconds [NX | XX | GT | LT])
Expire the key in at the exact unix time in milliseconds.
Expire the key in at the exact unix time in milliseconds.
This commands turns a key into a volatile one.
NX - Only set the expiry time if the key has no associated expiry.
XX - Only set the expiry time if the key already has an expiry time.
Expand All @@ -550,5 +598,14 @@ LT - Only set the expiry time if the new expiry time is less than the current on
KeyExtractionFunc: expireAtKeyFunc,
HandlerFunc: handleExpireAt,
},
{
Command: "incr",
Module: constants.GenericModule,
Categories: []string{constants.KeyspaceCategory, constants.WriteCategory, constants.FastCategory},
Description: `(INCR key) Increments the number stored at key by one. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that cannot be represented as integer. This operation is limited to 64 bit signed integers.`,
Sync: true,
KeyExtractionFunc: incrKeyFunc,
HandlerFunc: handleIncr,
},
}
}
128 changes: 125 additions & 3 deletions internal/modules/generic/commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,17 @@ package generic_test
import (
"errors"
"fmt"
"strconv"
"strings"
"testing"
"time"

"github.com/echovault/echovault/echovault"
"github.com/echovault/echovault/internal"
"github.com/echovault/echovault/internal/clock"
"github.com/echovault/echovault/internal/config"
"github.com/echovault/echovault/internal/constants"
"github.com/tidwall/resp"
"strings"
"testing"
"time"
)

type KeyData struct {
Expand Down Expand Up @@ -1894,4 +1896,124 @@ func Test_Generic(t *testing.T) {
}
})

t.Run("Test_HandlerINCR", func(t *testing.T) {
t.Parallel()
conn, err := internal.GetConnection("localhost", port)
if err != nil {
t.Error(err)
return
}
defer func() {
_ = conn.Close()
}()
client := resp.NewConn(conn)

tests := []struct {
name string
key string
presetValue interface{}
command []resp.Value
expectedResponse int64
expectedError error
}{
{
name: "1. Increment non-existent key",
key: "IncrKey1",
presetValue: nil,
command: []resp.Value{resp.StringValue("INCR"), resp.StringValue("IncrKey1")},
expectedResponse: 1,
expectedError: nil,
},
{
name: "2. Increment existing key with integer value",
key: "IncrKey2",
presetValue: "5",
command: []resp.Value{resp.StringValue("INCR"), resp.StringValue("IncrKey2")},
expectedResponse: 6,
expectedError: nil,
},
{
name: "3. Increment existing key with non-integer value",
key: "IncrKey3",
presetValue: "not_an_int",
command: []resp.Value{resp.StringValue("INCR"), resp.StringValue("IncrKey3")},
expectedResponse: 0,
expectedError: errors.New("value is not an integer or out of range"),
},
{
name: "4. Increment existing key with int64 value",
key: "IncrKey4",
presetValue: int64(10),
command: []resp.Value{resp.StringValue("INCR"), resp.StringValue("IncrKey4")},
expectedResponse: 11,
expectedError: nil,
},
{
name: "5. Command too short",
key: "IncrKey5",
presetValue: nil,
command: []resp.Value{resp.StringValue("INCR")},
expectedResponse: 0,
expectedError: errors.New(constants.WrongArgsResponse),
},
{
name: "6. Command too long",
key: "IncrKey6",
presetValue: nil,
command: []resp.Value{
resp.StringValue("INCR"),
resp.StringValue("IncrKey6"),
resp.StringValue("IncrKey6"),
},
expectedResponse: 0,
expectedError: errors.New(constants.WrongArgsResponse),
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.presetValue != nil {
command := []resp.Value{resp.StringValue("SET"), resp.StringValue(test.key), resp.StringValue(fmt.Sprintf("%v", test.presetValue))}
if err = client.WriteArray(command); err != nil {
t.Error(err)
}
res, _, err := client.ReadValue()
if err != nil {
t.Error(err)
}
if !strings.EqualFold(res.String(), "ok") {
t.Errorf("expected preset response to be OK, got %s", res.String())
}
}

if err = client.WriteArray(test.command); err != nil {
t.Error(err)
}

res, _, err := client.ReadValue()
if err != nil {
t.Error(err)
}

if test.expectedError != nil {
if !strings.Contains(res.Error().Error(), test.expectedError.Error()) {
t.Errorf("expected error \"%s\", got \"%s\"", test.expectedError.Error(), err.Error())
}
return
}

if err != nil {
t.Error(err)
} else {
responseInt, err := strconv.ParseInt(res.String(), 10, 64)
if err != nil {
t.Errorf("error parsing response to int64: %s", err)
}
if responseInt != test.expectedResponse {
t.Errorf("expected response %d, got %d", test.expectedResponse, responseInt)
}
}
})
}
})
}
Loading

0 comments on commit 83308ba

Please sign in to comment.