FIX: a search term containing '& could lead to errors

FIX: a search term containing '& could lead to errors

This also makes sure that the search term in front or after special characters isn’t ignored.

From c376670bd22ca60f47cf9736da10fa354707e632 Mon Sep 17 00:00:00 2001
From: Gerhard Schlager <mail@gerhard-schlager.at>
Date: Wed, 21 Nov 2018 22:07:13 +0100
Subject: [PATCH] FIX: a search term containing '& could lead to errors

This also makes sure that the search term in front or after special characters isn't ignored.

diff --git a/lib/search.rb b/lib/search.rb
index d711413..dd41ed9 100644
--- a/lib/search.rb
+++ b/lib/search.rb
@@ -832,8 +832,8 @@ class Search
     ts_config = ActiveRecord::Base.connection.quote(ts_config) if ts_config
     all_terms = data.scan(/'([^']+)'\:\d+/).flatten
     all_terms.map! do |t|
-      t.split(/[\)\(&']/)[0]
-    end.compact!
+      t.split(/[\)\(&']/).find(&:present?)
+    end.reject!(&:blank?)
 
     query = ActiveRecord::Base.connection.quote(
       all_terms
diff --git a/spec/components/search_spec.rb b/spec/components/search_spec.rb
index 15d67ad..877812d 100644
--- a/spec/components/search_spec.rb
+++ b/spec/components/search_spec.rb
@@ -945,12 +945,18 @@ describe Search do
     end
   end
 
-  it 'can parse complex strings using ts_query helper' do
-    str = " grigio:babel deprecated? "
-    str << "page page on Atmosphere](https://atmospherejs.com/grigio/babel)xxx: aaa.js:222 aaa'\"bbb"
+  context '#ts_query' do
+    it 'can parse complex strings using ts_query helper' do
+      str = " grigio:babel deprecated? "
+      str << "page page on Atmosphere](https://atmospherejs.com/grigio/babel)xxx: aaa.js:222 aaa'\"bbb"
 
-    ts_query = Search.ts_query(term: str, ts_config: "simple")
-    DB.exec("SELECT to_tsvector('bbb') @@ " << ts_query)
+      ts_query = Search.ts_query(term: str, ts_config: "simple")
+      expect { DB.exec("SELECT to_tsvector('bbb') @@ " << ts_query) }.to_not raise_error
+
+      ts_query = Search.ts_query(term: "foo.bar/'&baz", ts_config: "simple")
+      expect { DB.exec("SELECT to_tsvector('bbb') @@ " << ts_query) }.to_not raise_error
+      expect(ts_query).to include("baz")
+    end
   end
 
   context '#word_to_date' do

GitHub

1 Like
[11] pry(main)> [["","    "].find(&:present?), "hi"].reject!(&:blank?)
=> ["hi"]
[12] pry(main)> [["","    "].find(&:present?), "hi"].compact!
=> ["hi"]

Minor… but in this case compact! does the trick cause you already eliminated blanks.

2 Likes

Right, that happened because of the order in which I fixed those 2 issues. Fixed in https://github.com/discourse/discourse/commit/bf27aecce25c2b8267312045b93b511dd5eb3b92

3 Likes