Skip to content

Commit

Permalink
address review suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
bailinhe committed Oct 17, 2023
1 parent 0da27f3 commit ba2bff0
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 10 deletions.
15 changes: 5 additions & 10 deletions pkg/jsonschema/unique_constraint.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,16 @@ func (s *UniqueConstraintSchema) Validate(_ jsonschema.ValidationContext, v inte
qms = append(qms, qm.Where("id != ?", *s.ResourceID))
}

for k, value := range mappedValue {
// Convert the value to string
v := fmt.Sprint(value)

for k, v := range mappedValue {
fieldType, exists := s.UniqueFieldTypesMap[k]
if !exists {
continue
}

if fieldType == "string" {
v = fmt.Sprintf(`"%s"`, v)
if vStr, ok := v.(string); ok {
v = fmt.Sprintf(`"%s"`, vStr)
}
}

qms = append(qms, qm.Where(`resource->? = ?`, k, v))
Expand Down Expand Up @@ -192,11 +191,7 @@ func (uc *UniqueConstraintCompiler) compileUniqueConstraint(

// Checks if the provided field type is valid for unique constraints
func isValidType(fieldType string) bool {
_, ok := map[string]bool{
"string": true, "number": true, "integer": true, "boolean": true,
}[fieldType]

return fieldType == "string" || fieldType == "number" || fieldType == "integer" || fieldType == "boolean"
return fieldType == "string" || fieldType == "number" || fieldType == "integer" || fieldType == "boolean"
}

// helper function to assert string slice type
Expand Down
46 changes: 46 additions & 0 deletions pkg/jsonschema/unique_constraint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package jsonschema
import (
"context"
"database/sql"
"reflect"
"testing"

"github.com/cockroachdb/cockroach-go/v2/testserver"
Expand Down Expand Up @@ -266,6 +267,51 @@ func (s *UniqueConstrainTestSuite) TestValidate() {
}
}

func TestAssertStringSlice(t *testing.T) {
tests := []struct {
name string
input interface{}
expected []string
expectedErr string
}{
{
name: "valid string slice",
input: []interface{}{"foo", "bar", "baz"},
expected: []string{"foo", "bar", "baz"},
expectedErr: "",
},
{
name: "invalid type",
input: "not a slice",
expected: nil,
expectedErr: "to string array",
},
{
name: "invalid element type",
input: []interface{}{"foo", 42, "baz"},
expected: nil,
expectedErr: "to string",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual, err := assertStringSlice(tt.input)

if tt.expectedErr == "" {
assert.Nil(t, err)
if !reflect.DeepEqual(actual, tt.expected) {
t.Errorf("assertStringSlice() = %v, expected %v", actual, tt.expected)
}
} else {
assert.NotNil(t, err)
assert.Contains(t, err.Error(), tt.expectedErr)
return
}
})
}
}

func TestUniqueConstraintSuite(t *testing.T) {
suite.Run(t, new(UniqueConstrainTestSuite))
}

0 comments on commit ba2bff0

Please sign in to comment.