Skip to content

Commit d6a0224

Browse files
Simplify code
1 parent 1dda34b commit d6a0224

File tree

2 files changed

+17
-24
lines changed

2 files changed

+17
-24
lines changed

filter/converter.go

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -256,31 +256,24 @@ func (c *Converter) convertFilter(filter map[string]any, paramIndex int) (string
256256

257257
// If the value is a map with a $field key, we need to compare the column to another column.
258258
if vv, ok := value.(map[string]any); ok {
259-
if field, ok := vv["$field"].(string); ok {
260-
if isNumericOperator {
261-
if c.isNestedColumn(key) {
262-
if c.isNestedColumn(field) {
263-
// (a->>b)::numeric > (c->>d)::numeric
264-
inner = append(inner, fmt.Sprintf("((%s)::numeric %s (%s)::numeric)", c.columnName(key), op, c.columnName(field)))
265-
} else {
266-
// (a->>b)::numeric > c
267-
inner = append(inner, fmt.Sprintf("((%s)::numeric %s %s)", c.columnName(key), op, c.columnName(field)))
268-
}
269-
} else {
270-
if c.isNestedColumn(field) {
271-
// a > (c->>d)::numeric
272-
inner = append(inner, fmt.Sprintf("(%s %s (%s)::numeric)", c.columnName(key), op, c.columnName(field)))
273-
} else {
274-
// a > c
275-
inner = append(inner, fmt.Sprintf("(%s %s %s)", c.columnName(key), op, c.columnName(field)))
276-
}
277-
}
278-
} else {
279-
inner = append(inner, fmt.Sprintf("(%s %s %s)", c.columnName(key), op, c.columnName(field)))
259+
field, ok := vv["$field"].(string)
260+
if !ok || len(vv) > 1 {
261+
return "", nil, fmt.Errorf("invalid value for %s operator (must be object with $field key only): %v", operator, value)
262+
}
263+
264+
left := c.columnName(key)
265+
right := c.columnName(field)
266+
267+
if isNumericOperator {
268+
if c.isNestedColumn(key) {
269+
left = fmt.Sprintf("(%s)::numeric", left)
270+
}
271+
if c.isNestedColumn(field) {
272+
right = fmt.Sprintf("(%s)::numeric", right)
280273
}
281-
} else {
282-
return "", nil, fmt.Errorf("invalid value for %s operator (must be object with $field key): %v", operator, value)
283274
}
275+
276+
inner = append(inner, fmt.Sprintf("(%s %s %s)", left, op, right))
284277
} else {
285278
// Prevent cryptic errors like:
286279
// unexpected error: sql: converting argument $1 type: unsupported type []interface {}, a slice of interface

filter/converter_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ func TestConverter_Convert(t *testing.T) {
420420
`{"name": {"$eq": {"foo": "bar"}}}`,
421421
``,
422422
nil,
423-
fmt.Errorf("invalid value for $eq operator (must be object with $field key): map[foo:bar]"),
423+
fmt.Errorf("invalid value for $eq operator (must be object with $field key only): map[foo:bar]"),
424424
},
425425
}
426426

0 commit comments

Comments
 (0)