Skip to content

Commit

Permalink
Implement $nor
Browse files Browse the repository at this point in the history
  • Loading branch information
erikdubbelboer committed Jun 8, 2024
1 parent a827073 commit 696d4da
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 8 deletions.
20 changes: 12 additions & 8 deletions filter/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (c *Converter) convertFilter(filter map[string]any, paramIndex int) (string
value := filter[key]

switch key {
case "$or", "$and":
case "$or", "$and", "$nor":
opConditions, ok := anyToSliceMapAny(value)
if !ok {
return "", nil, fmt.Errorf("invalid value for $or operator (must be array of objects): %v", value)
Expand All @@ -108,14 +108,18 @@ func (c *Converter) convertFilter(filter map[string]any, paramIndex int) (string
inner = append(inner, innerConditions)
values = append(values, innerValues...)
}
op := "AND"
if key == "$or" {
op = "OR"
}
if len(inner) > 1 {
conditions = append(conditions, "("+strings.Join(inner, " "+op+" ")+")")
if key == "$nor" {
conditions = append(conditions, "NOT ("+strings.Join(inner, " OR ")+")")
} else {
conditions = append(conditions, strings.Join(inner, " "+op+" "))
op := "AND"
if key == "$or" {
op = "OR"
}
if len(inner) > 1 {
conditions = append(conditions, "("+strings.Join(inner, " "+op+" ")+")")
} else {
conditions = append(conditions, strings.Join(inner, " "+op+" "))
}
}
default:
if !isValidPostgresIdentifier(key) {
Expand Down
8 changes: 8 additions & 0 deletions filter/converter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ func TestConverter_Convert(t *testing.T) {
nil,
fmt.Errorf("$or as scalar operator not supported"),
},
{
"$nor operator basic",
nil,
`{"$nor": [{"name": "John"}, {"name": "Doe"}]}`,
`NOT (("name" = $1) OR ("name" = $2))`,
[]any{"John", "Doe"},
nil,
},
{
"and operator basic",
nil,
Expand Down
1 change: 1 addition & 0 deletions fuzz/fuzz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func FuzzConverter(f *testing.F) {
`{"$or": [{"org": "poki", "admin": true}, {"age": {"$gte": 18}}]}`,
`{"$or": [{"$or": [{"name": "John"}, {"name": "Doe"}]}, {"name": "Jane"}]}`,
`{"foo": { "$or": [ "bar", "baz" ] }}`,
`{"$nor": [{"name": "John"}, {"name": "Doe"}]}`,
`{"$and": [{"name": "John"}, {"version": 3}]}`,
`{"$and": [{"name": "John", "version": 3}]}`,
`{"name": {"$regex": "John"}}`,
Expand Down
6 changes: 6 additions & 0 deletions integration/postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,12 @@ func TestIntegration_BasicOperators(t *testing.T) {
[]int{7, 8, 9, 10},
nil,
},
{
"$nor",
`{"$nor": [{"name": "Alice"}, {"name": "Bob"}]}`,
[]int{3, 4, 5, 6, 7, 8, 9, 10},
nil,
},
}

for _, tt := range tests {
Expand Down

0 comments on commit 696d4da

Please sign in to comment.