Skip to content

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

Compile the LIKE ESCAPE character as h2x/literal so driver inlining can't touch it (#81704)

Nicola Mometto0fec254d6db1
diff --git a/src/metabase/util/honey_sql_2.clj b/src/metabase/util/honey_sql_2.clj
index 8bc0107f8fe..4cd896e1c32 100644
--- a/src/metabase/util/honey_sql_2.clj
+++ b/src/metabase/util/honey_sql_2.clj
@@ -27,7 +27,9 @@
([s]
(like-pattern s identity))
([s wrap]
- [:escape (wrap (escape-like-pattern s)) ^:allow-raw-sql [:inline "!"]]))
+ ;; `::literal` rather than [:inline "!"]: with a driver bound, inline strings compile via driver-specific
+ ;; `inline-value` (MySQL emits `_utf8mb4 X'21'`, whose collation can clash with LIKE's other operands)
+ [:escape (wrap (escape-like-pattern s)) [::literal "!"]]))
(defn like-substring
"`LIKE` right-hand side matching `s` case-insensitively as a literal substring; compare it against a lowercased column."
diff --git a/test/metabase/driver/mysql_test.clj b/test/metabase/driver/mysql_test.clj
index bb860aa70d0..36c78cc18ec 100644
--- a/test/metabase/driver/mysql_test.clj
+++ b/test/metabase/driver/mysql_test.clj
@@ -75,6 +75,17 @@
:from [[:venues]]
:where [:= :venues/name "a\\' OR 1 = 1 --"]}))))))
+(deftest ^:parallel like-pattern-escape-char-not-driver-inlined-test
+ (testing "LIKE's ESCAPE character compiles to a plain `'!'` even with a driver bound — a `_utf8mb4 X'21'` hex
+ literal carries utf8mb4's default collation and makes MySQL app DBs on another collation fail with
+ `Illegal mix of collations` (#81161 follow-up)"
+ (binding [driver/*driver* :mysql]
+ (is (= ["SELECT * FROM `t` WHERE LOWER(`name`) LIKE ? ESCAPE '!'" "%a!%b%"]
+ (sql/format {:select [:*]
+ :from [:t]
+ :where [:like [:lower :name] (h2x/like-substring "a%b")]}
+ {:dialect :mysql}))))))
+
(deftest all-zero-dates-test
(mt/test-driver :mysql
(testing (str "MySQL allows 0000-00-00 dates, but JDBC does not; make sure that MySQL is converting them to NULL "