From 6baae97b5de3a2a39f94f9f4864d370b8794a2e9 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Sat, 19 Aug 2023 16:33:45 +0300 Subject: [PATCH] added json marshal fallback for complex structs as placeholder param --- tools/search/filter.go | 11 ++++++++++- tools/search/filter_test.go | 8 ++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/tools/search/filter.go b/tools/search/filter.go index 0ac02b7e..18447af6 100644 --- a/tools/search/filter.go +++ b/tools/search/filter.go @@ -1,6 +1,7 @@ package search import ( + "encoding/json" "errors" "fmt" "strconv" @@ -49,7 +50,15 @@ func (f FilterData) BuildExpr( case bool, float64, float32, int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8: replacement = cast.ToString(v) default: - replacement = strconv.Quote(cast.ToString(v)) + replacement = cast.ToString(v) + + // try to json serialize as fallback + if replacement == "" { + raw, _ := json.Marshal(v) + replacement = string(raw) + } + + replacement = strconv.Quote(replacement) } raw = strings.ReplaceAll(raw, "{:"+key+"}", replacement) } diff --git a/tools/search/filter_test.go b/tools/search/filter_test.go index 6a6472c3..7b45065c 100644 --- a/tools/search/filter_test.go +++ b/tools/search/filter_test.go @@ -200,7 +200,9 @@ func TestFilterDataBuildExprWithParams(t *testing.T) { test7 = {:test7} || test8 = {:test8} || test9 = {:test9} || - test10 = {:test10} + test10 = {:test10} || + test11 = {:test11} || + test12 = {:test12} `) replacements := []dbx.Params{ @@ -210,6 +212,8 @@ func TestFilterDataBuildExprWithParams(t *testing.T) { {"test4": nil}, {"test5": "", "test6": "simple", "test7": `'single_quotes'`, "test8": `"double_quotes"`, "test9": `escape\"quote`}, {"test10": date}, + {"test11": []string{"a", "b", `"quote`}}, + {"test12": map[string]any{"a": 123, "b": `quote"`}}, } expr, err := filter.BuildExpr(resolver, replacements...) @@ -223,7 +227,7 @@ 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 [[test5]] IS NULL) OR [[test6]] = 'simple' OR [[test7]] = '''single_quotes''' OR [[test8]] = '"double_quotes"' OR [[test9]] = 'escape\\"quote' OR [[test10]] = '2023-01-01 00:00:00 +0000 UTC')` + 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]] = 'escape\\"quote' OR [[test10]] = '2023-01-01 00:00:00 +0000 UTC' OR [[test11]] = '["a","b","\\"quote"]' OR [[test12]] = '{"a":123,"b":"quote\\""}')` if expectedQuery != calledQueries[0] { t.Fatalf("Expected query \n%s, \ngot \n%s", expectedQuery, calledQueries[0]) }