From b400eb6c145f0522c3810422efa30f5c539929d8 Mon Sep 17 00:00:00 2001 From: Kryvchun Date: Tue, 11 Apr 2023 08:43:29 +0300 Subject: [PATCH] feat: safely quote terms --- sonic/search.go | 11 ++++++++++- sonic/search_test.go | 45 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/sonic/search.go b/sonic/search.go index 116b9ab..2ef1fa5 100644 --- a/sonic/search.go +++ b/sonic/search.go @@ -65,7 +65,16 @@ func (s searchChannel) Query(collection, bucket, term string, limit, offset int, } defer d.close() - err = d.write(fmt.Sprintf("%s %s %s \"%s\" LIMIT(%d) OFFSET(%d)"+langFormat(lang), query, collection, bucket, term, limit, offset, lang)) + err = d.write(fmt.Sprintf( + "%s %s %s %q LIMIT(%d) OFFSET(%d)"+langFormat(lang), + query, + collection, + bucket, + term, + limit, + offset, + lang, + )) if err != nil { return nil, err } diff --git a/sonic/search_test.go b/sonic/search_test.go index 3e27a03..6535650 100644 --- a/sonic/search_test.go +++ b/sonic/search_test.go @@ -58,6 +58,51 @@ func TestSearch(t *testing.T) { } }) + t.Run("Query_quote", func(t *testing.T) { + t.Parallel() + + _, err := srch.Query(col, bucket, `'quote' "hello"`, 1, 0, sonic.LangAutoDetect) + if err != nil { + t.Fatal("Query", err) + } + }) + + t.Run("Query_escape", func(t *testing.T) { + t.Parallel() + + _, err := srch.Query(col, bucket, `escape symbol \`, 1, 0, sonic.LangAutoDetect) + if err != nil { + t.Fatal("Query", err) + } + }) + + t.Run("Query_tab", func(t *testing.T) { + t.Parallel() + + _, err := srch.Query(col, bucket, "\t", 1, 0, sonic.LangAutoDetect) + if err != nil { + t.Fatal("Query", err) + } + }) + + t.Run("Query_space", func(t *testing.T) { + t.Parallel() + + _, err := srch.Query(col, bucket, " ", 1, 0, sonic.LangAutoDetect) + if err == nil { + t.Fatal("Expected error, but got nil") + } + }) + + t.Run("Query_empty", func(t *testing.T) { + t.Parallel() + + _, err := srch.Query(col, bucket, "", 1, 0, sonic.LangAutoDetect) + if err == nil { + t.Fatal("Expected error, but got nil") + } + }) + t.Run("Query_empty", func(t *testing.T) { t.Parallel()