return an error on invalid fallback param serialization

This commit is contained in:
Gani Georgiev
2026-09-02 12:15:34 +03:00
parent 1b3edbbf5c
commit 56f1d1dfdd
3 changed files with 38 additions and 9 deletions
+8 -5
View File
@@ -69,15 +69,18 @@ func (f FilterData) BuildExprWithLimit(
case bool, float64, float32, int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
replacement = cast.ToString(v)
default:
replacement = cast.ToString(v)
casted, err := cast.ToStringE(v)
// try to json serialize as fallback
if replacement == "" {
raw, _ := json.Marshal(v, json.Deterministic(true))
replacement = string(raw)
if err != nil {
raw, err := json.Marshal(v, json.Deterministic(true))
if err != nil {
return nil, fmt.Errorf("failed to serialize param %q: %w", key, err)
}
casted = string(raw)
}
replacement = strconv.Quote(replacement)
replacement = strconv.Quote(casted)
}
replacements = append(replacements, "{:"+key+"}", replacement)
+27 -1
View File
@@ -242,13 +242,39 @@ func TestFilterDataBuildExprWithParams(t *testing.T) {
t.Fatalf("Expected 1 query, got %d", len(calledQueries))
}
expectedQuery := `SELECT * WHERE ([[test1]] = 1 OR [[test2]] = 0 OR [[test3a]] = 123.456 OR [[test3b]] = 123.456 OR ([[test4]] = '' OR [[test4]] IS NULL) OR [[test5]] = '""' OR [[test6]] = 'simple' OR [[test7]] = '''single_quotes''' OR [[test8]] = '"double_quotes"' OR [[test9]] = '''"quote_with_backslash\' OR [[test10]] = '2023-01-01 00:00:00 +0000 UTC' OR [[test11]] = '["a","''quote","\"quote"]' OR [[test12]] = '{"a":123,"b":"quote\""}' OR [[test13]] = 'a`
expectedQuery := `SELECT * WHERE ([[test1]] = 1 OR [[test2]] = 0 OR [[test3a]] = 123.456 OR [[test3b]] = 123.456 OR ([[test4]] = '' OR [[test4]] IS NULL) OR ([[test5]] = '' OR [[test5]] IS NULL) OR [[test6]] = 'simple' OR [[test7]] = '''single_quotes''' OR [[test8]] = '"double_quotes"' OR [[test9]] = '''"quote_with_backslash\' OR [[test10]] = '2023-01-01 00:00:00 +0000 UTC' OR [[test11]] = '["a","''quote","\"quote"]' OR [[test12]] = '{"a":123,"b":"quote\""}' OR [[test13]] = 'a`
expectedQuery += "\nb')"
if expectedQuery != calledQueries[0] {
t.Fatalf("Expected query \n%s, \ngot \n%s", expectedQuery, calledQueries[0])
}
}
func TestFilterDataBuildExprWithParamsFallbackError(t *testing.T) {
t.Parallel()
resolver := search.NewSimpleFieldResolver("test")
filter := search.FilterData(`test = {:test}`)
t.Run("non-string type but valid marshalized json", func(t *testing.T) {
_, err := filter.BuildExpr(resolver, dbx.Params{
"test": map[string]any{"a": "123"},
})
if err != nil {
t.Fatal(err)
}
})
t.Run("non-string type but invalid marshalized json", func(t *testing.T) {
_, err := filter.BuildExpr(resolver, dbx.Params{
"test": map[string]any{"a": "123\xc3"},
})
if err == nil {
t.Fatal("Expected filter build error, got nil")
}
})
}
func TestFilterDataBuildExprWithLimit(t *testing.T) {
resolver := search.NewSimpleFieldResolver(`^\w+$`)