Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Fix regexp QP perf issue (#75548)

Alexander Polyankin4855069483a9
diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.clj
index 3efe987dc7c..0adf3a69b5c 100644
--- a/src/metabase/driver/sql/query_processor.clj
+++ b/src/metabase/driver/sql/query_processor.clj
@@ -43,7 +43,10 @@
"See [[make-nestable-sql]] but does not wrap in result in parens."
[sql]
(-> sql
- (str/replace #";([\s;]*(--.*\n?)*)*$" "")
+ ;; Strip the trailing run of semicolons / whitespace / line comments. Possessive quantifiers (`*+`) make
+ ;; this match in a single forward pass: without them the nested unbounded quantifiers over overlapping
+ ;; character classes backtrack super-linearly (O(n^2) on many trailing comment lines), which can wedge the JVM.
+ (str/replace #";[\s;]*+(?:--.*+[\s;]*+)*+$" "")
str/trimr
(as-> trimmed
;; Query could potentially end with a comment.
diff --git a/test/metabase/driver/sql/query_processor_test.clj b/test/metabase/driver/sql/query_processor_test.clj
index a5e3e4cd39f..d412d929133 100644
--- a/test/metabase/driver/sql/query_processor_test.clj
+++ b/test/metabase/driver/sql/query_processor_test.clj
@@ -1280,6 +1280,13 @@
-- c3"
"(SELECT ';')")))
+(deftest ^:parallel make-nestable-sql-no-superlinear-backtracking-test
+ (testing "Stripping trailing comments/semicolons completes in linear time, without catastrophic backtracking"
+ (let [sql (str "SELECT 1;\n"
+ (apply str (repeat 20000 "-- a comment line\n"))
+ "SELECT 2")]
+ (is (= (str "(" sql ")") (sql.qp/make-nestable-sql sql))))))
+
(deftest ^:parallel string-inline-value-test
(testing `String
(let [honeysql {:select [[:%count.*]]