Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion filter/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,15 @@ func (c *Converter) convertFilter(filter map[string]any, paramIndex int) (string
return "", nil, fmt.Errorf("invalid comparison value (must be a primitive): %v", value)
}

// If we aren't comparing columns, and the field is a numeric scalar, we also see = ($eq) and != ($ne) as numeric operators.
// This way we can use ::numeric on jsonb values to prevent getting postgres errors like:
// ERROR: operator does not exist: text = numeric
if isNumeric(value) && !isNumericOperator {
if op == "=" || op == "!=" {
isNumericOperator = true
}
}

if isNumericOperator && isNumeric(value) && c.isNestedColumn(key) {
inner = append(inner, fmt.Sprintf("((%s)::numeric %s $%d)", c.columnName(key), op, paramIndex))
} else {
Expand Down Expand Up @@ -330,7 +339,12 @@ func (c *Converter) convertFilter(filter map[string]any, paramIndex int) (string
if !isScalar(value) {
return "", nil, fmt.Errorf("invalid comparison value (must be a primitive): %v", value)
}
conditions = append(conditions, fmt.Sprintf("(%s = $%d)", c.columnName(key), paramIndex))
if isNumeric(value) && c.isNestedColumn(key) {
// If the value is numeric and the column is a nested JSONB column, we need to cast the column to numeric.
conditions = append(conditions, fmt.Sprintf("((%s)::numeric = $%d)", c.columnName(key), paramIndex))
} else {
conditions = append(conditions, fmt.Sprintf("(%s = $%d)", c.columnName(key), paramIndex))
}
paramIndex++
values = append(values, value)
}
Expand Down
16 changes: 16 additions & 0 deletions filter/converter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,22 @@ func TestConverter_Convert(t *testing.T) {
nil,
fmt.Errorf("invalid value for $eq operator (must be object with $field key only): map[foo:bar]"),
},
{
"numeric comparison with nested jsonb",
[]filter.Option{filter.WithNestedJSONB("meta")},
`{"foo": 12}`,
`(("meta"->>'foo')::numeric = $1)`,
[]any{float64(12)},
nil,
},
{
"numeric comparison with nested jsonb with $eq",
[]filter.Option{filter.WithNestedJSONB("meta")},
`{"foo": { "$eq": 12 }}`,
`(("meta"->>'foo')::numeric = $1)`,
[]any{float64(12)},
nil,
},
}

for _, tt := range tests {
Expand Down
Loading