Skip to content

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

Stop sending MariaDB-only timeout syntax to MySQL 26 (#78802)

Chris Truter426d1b617cff
diff --git a/enterprise/backend/src/metabase_enterprise/security_center/matching.clj b/enterprise/backend/src/metabase_enterprise/security_center/matching.clj
index 54ddcd09745..82f9fc9cf7a 100644
--- a/enterprise/backend/src/metabase_enterprise/security_center/matching.clj
+++ b/enterprise/backend/src/metabase_enterprise/security_center/matching.clj
@@ -7,6 +7,7 @@
[metabase.config.core :as config]
[metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
[metabase.models.interface :as mi]
+ [metabase.util.connection :as u.connection]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[next.jdbc.result-set :as rs]
@@ -74,7 +75,7 @@
(.setAutoCommit conn false)
(try
(with-open [stmt (doto (sql-jdbc.execute/prepared-statement driver conn sql params)
- (.setQueryTimeout *query-timeout-seconds*))
+ (u.connection/set-query-timeout! *query-timeout-seconds*))
rs (sql-jdbc.execute/execute-prepared-statement! driver stmt)]
(rs/datafiable-result-set rs conn {}))
(finally
diff --git a/src/metabase/app_db/cluster_lock.clj b/src/metabase/app_db/cluster_lock.clj
index 23778d75756..3eded7e8780 100644
--- a/src/metabase/app_db/cluster_lock.clj
+++ b/src/metabase/app_db/cluster_lock.clj
@@ -22,12 +22,13 @@
[metabase.app-db.query :as mdb.query]
[metabase.app-db.query-cancelation :as app-db.query-cancelation]
[metabase.app-db.transient-error :as transient-error]
+ [metabase.util.connection :as u.connection]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.retry :as retry]
[toucan2.core :as t2])
(:import
- (java.sql Connection PreparedStatement SQLIntegrityConstraintViolationException)
+ (java.sql Connection PreparedStatement SQLException SQLIntegrityConstraintViolationException)
(java.util.concurrent ConcurrentHashMap)
(java.util.concurrent.locks Lock ReentrantReadWriteLock)
(java.util.function Function)))
@@ -46,6 +47,7 @@
(instance? SQLIntegrityConstraintViolationException (ex-cause e))
;; Postgres does just uses PSQLException, so we need to fall back to checking the message.
(some-> (ex-message e) (str/includes? "duplicate key value violates unique constraint \"metabase_cluster_lock_pkey\""))
+ (true? (::acquisition-timeout (ex-data e)))
(app-db.query-cancelation/query-canceled-exception? (mdb.connection/db-type) e)))
(defn- retry-if-error?
@@ -91,15 +93,52 @@
^PreparedStatement [^Connection conn lock-name-str timeout mode]
(let [stmt (.prepareStatement conn (lock-sql mode))]
(try
+ (u.connection/set-query-timeout! stmt timeout)
(doto stmt
- (.setQueryTimeout timeout)
(.setString 1 lock-name-str)
(.setMaxRows 1))
(catch Throwable e
(.close stmt)
(throw e)))))
-(defn- acquire-lock-row!
+(def ^:private lock-wait-timeout-error-code
+ "MySQL's ER_LOCK_WAIT_TIMEOUT."
+ 1205)
+
+(defn- session-lock-wait-timeout
+ [^Connection conn]
+ (with-open [stmt (.createStatement conn)
+ rset (.executeQuery stmt "SELECT @@session.innodb_lock_wait_timeout")]
+ (when (.next rset)
+ (.getLong rset 1))))
+
+(defn- set-session-lock-wait-timeout!
+ [^Connection conn seconds]
+ (with-open [stmt (.createStatement conn)]
+ (.execute stmt (str "SET SESSION innodb_lock_wait_timeout = " (long seconds)))))
+
+(defn- do-with-lock-wait-timeout
+ "Run `f` with InnoDB's session lock-wait timeout set to `timeout-seconds`, restoring the old value afterwards.
+ Used where the driver cannot carry the timeout itself (see [[u.connection/set-query-timeout!]]): acquisition blocks
+ on the lock row, so the lock-wait timeout is what bounds it.
+ A timeout here means we lost the race for the lock, so it surfaces as an acquisition failure the retry loop knows."
+ [^Connection conn timeout-seconds f]
+ ;; the connection is usually pooled, so the old value has to go back before it is handed to anyone else
+ (let [previous (session-lock-wait-timeout conn)]
+ (set-session-lock-wait-timeout! conn timeout-seconds)
+ (try
+ (f)
+ (catch SQLException e
+ (if (= (.getErrorCode e) lock-wait-timeout-error-code)
+ (throw (ex-info "Timed out waiting for the cluster lock row"
+ {::acquisition-timeout true}
+ e))
+ (throw e)))
+ (finally
+ (when previous
+ (set-session-lock-wait-timeout! conn previous))))))
+
+(defn- acquire-lock-row!*
[^Connection conn lock-name-str timeout mode]
(with-open [stmt (prepare-statement conn lock-name-str timeout mode)
result-set (.executeQuery stmt)]
@@ -113,12 +152,17 @@
:columns [:lock_name]
:values [[[:raw "?"]]]})]
(with-open [insert-stmt (.prepareStatement conn ^String sql)]
- (doto insert-stmt
- (.setQueryTimeout timeout)
- (.setString 1 lock-name-str))
+ (u.connection/set-query-timeout! insert-stmt timeout)
+ (.setString insert-stmt 1 lock-name-str)
(.executeUpdate insert-stmt)))))
(log/debugf "Obtained cluster lock: %s (%s)" lock-name-str mode))
+(defn- acquire-lock-row!
+ [^Connection conn lock-name-str timeout mode]
+ (if (u.connection/server-rejects-query-timeout? conn)
+ (do-with-lock-wait-timeout conn timeout #(acquire-lock-row!* conn lock-name-str timeout mode))
+ (acquire-lock-row!* conn lock-name-str timeout mode)))
+
(def ^:private ^:dynamic *detached-locks-held*
"Lock-name strings currently held by [[do-with-detached-cluster-lock]] in this dynamic scope. A detached
hold lives on a dedicated connection, so re-acquiring the same name from this scope — detached or
diff --git a/src/metabase/driver/sql_jdbc/execute.clj b/src/metabase/driver/sql_jdbc/execute.clj
index 2b1df9e7af9..66dcfd0c029 100644
--- a/src/metabase/driver/sql_jdbc/execute.clj
+++ b/src/metabase/driver/sql_jdbc/execute.clj
@@ -24,6 +24,7 @@
[metabase.premium-features.core :refer [defenterprise]]
[metabase.tracing.core :as tracing]
[metabase.util :as u]
+ [metabase.util.connection :as u.connection]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
@@ -601,11 +602,13 @@
`unreturnedConnectionTimeout` to kill long queries. Transforms rebind `*query-timeout-ms*` so their statements get
the transform timeout instead of the shorter default. Drivers that opt out via the `:jdbc/set-query-timeout`
feature flag (e.g. SparkSQL — calling it closes the Hive Thrift transport) skip the call entirely; for the rest,
- individual implementations that throw fall back to the c3p0 leak-detector via the `catch Throwable`."
+ individual implementations that throw fall back to the c3p0 leak-detector via the `catch Throwable`.
+ A MySQL 26 or newer warehouse also falls back, because there the driver would turn the timeout into MariaDB syntax
+ the server rejects, failing every query outright — the query is still bounded by the QP's own cancelation."
[driver ^Statement stmt]
(when (driver/database-supports? driver :jdbc/set-query-timeout nil)
(try
- (.setQueryTimeout stmt (long (/ driver.settings/*query-timeout-ms* 1000)))
+ (u.connection/set-query-timeout! stmt (long (/ driver.settings/*query-timeout-ms* 1000)))
(catch Throwable e
(log/debug e "Error setting statement query timeout")))))
diff --git a/src/metabase/driver/sql_jdbc/sync/describe_database.clj b/src/metabase/driver/sql_jdbc/sync/describe_database.clj
index 0851de87653..a2b03c23023 100644
--- a/src/metabase/driver/sql_jdbc/sync/describe_database.clj
+++ b/src/metabase/driver/sql_jdbc/sync/describe_database.clj
@@ -11,6 +11,7 @@
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.sync :as driver.s]
[metabase.driver.util :as driver.u]
+ [metabase.util.connection :as u.connection]
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
@@ -78,9 +79,8 @@
;; attempting to execute the SQL statement will throw an Exception if we don't have permissions; otherwise it will
;; truthy whether or not it returns a ResultSet, but we can ignore that since we have enough info to proceed at
;; this point.
- (doto stmt
- (.setQueryTimeout *select-probe-query-timeout-seconds*)
- (.execute))))
+ (u.connection/set-query-timeout! stmt *select-probe-query-timeout-seconds*)
+ (.execute stmt)))
(defn- pr-table [table-schema table-name]
(str (when table-schema
diff --git a/src/metabase/util/connection.clj b/src/metabase/util/connection.clj
index aed9d251ba4..0b218575fe8 100644
--- a/src/metabase/util/connection.clj
+++ b/src/metabase/util/connection.clj
@@ -1,10 +1,12 @@
(ns metabase.util.connection
(:require
[clojure.set :as set]
+ [clojure.string :as str]
[metabase.util :as u]
+ [metabase.util.log :as log]
[toucan2.core :as t2])
(:import
- (java.sql Connection DatabaseMetaData ResultSet ResultSetMetaData)))
+ (java.sql Connection DatabaseMetaData ResultSet ResultSetMetaData Statement)))
(set! *warn-on-reflection* true)
@@ -64,3 +66,33 @@
{:child-table (name table-name')
:child-column (u/lower-case-en (.getString fks "FKCOLUMN_NAME"))
:parent-column (u/lower-case-en (.getString fks "PKCOLUMN_NAME"))}]))))))))))
+
+;;; ------------------------------------------ statement timeouts ------------------------------------------
+
+(defn server-rejects-query-timeout?
+ "Whether calling `.setQueryTimeout` on `conn` makes the driver send SQL this server cannot parse.
+
+ MariaDB Connector/J implements the timeout by prefixing the statement with `SET STATEMENT max_statement_time=N FOR`,
+ and turns that on for any server reporting version 10.1.2 or newer.
+ It never consults the MariaDB flag it already read from the handshake, so MySQL — below 10 until the
+ calendar-versioned 26.x releases — now clears the check and gets syntax only MariaDB understands."
+ [^Connection conn]
+ (boolean
+ (try
+ (let [md (.getMetaData conn)]
+ (and (str/includes? (str (.getDriverName md)) "MariaDB")
+ (not (str/includes? (str (.getDatabaseProductVersion md)) "MariaDB"))
+ (>= (.getDatabaseMajorVersion md) 10)))
+ (catch Throwable e
+ (log/debug e "Could not read server version; assuming statement timeouts work")
+ false))))
+
+(defn set-query-timeout!
+ "Bound `stmt` to `timeout-seconds` with `.setQueryTimeout`, unless that would send the server unparseable SQL.
+ Returns false when the timeout could not be set, leaving it to the caller to bound the statement another way."
+ [^Statement stmt timeout-seconds]
+ (if (server-rejects-query-timeout? (.getConnection stmt))
+ false
+ (do
+ (.setQueryTimeout stmt (int timeout-seconds))
+ true)))
diff --git a/test/metabase/util/connection_test.clj b/test/metabase/util/connection_test.clj
new file mode 100644
index 00000000000..cbe98af142d
--- /dev/null
+++ b/test/metabase/util/connection_test.clj
@@ -0,0 +1,61 @@
+(ns metabase.util.connection-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.util.connection :as u.connection])
+ (:import
+ (java.sql Connection DatabaseMetaData Statement)))
+
+(set! *warn-on-reflection* true)
+
+(defn- fake-metadata
+ ^DatabaseMetaData [driver-name product-version major]
+ (reify DatabaseMetaData
+ (getDriverName [_] driver-name)
+ (getDatabaseProductVersion [_] product-version)
+ (getDatabaseMajorVersion [_] major)))
+
+(defn- fake-connection
+ ^Connection [driver-name product-version major]
+ (reify Connection
+ (getMetaData [_] (fake-metadata driver-name product-version major))))
+
+(deftest server-rejects-query-timeout?-test
+ (testing "MySQL 26+ trips the driver's version-only check and gets MariaDB syntax it cannot parse"
+ (is (true? (u.connection/server-rejects-query-timeout?
+ (fake-connection "MariaDB Connector/J" "26.7.0" 26)))))
+ (testing "a MariaDB server understands the syntax, however high its version"
+ (is (false? (u.connection/server-rejects-query-timeout?
+ (fake-connection "MariaDB Connector/J" "10.6.16-MariaDB-1:10.6.16+maria~ubu2004" 10))))
+ (is (false? (u.connection/server-rejects-query-timeout?
+ (fake-connection "MariaDB Connector/J" "11.4.2-MariaDB" 11)))))
+ (testing "MySQL below 26 stays under the driver's threshold"
+ (is (false? (u.connection/server-rejects-query-timeout?
+ (fake-connection "MariaDB Connector/J" "8.0.36" 8))))
+ (is (false? (u.connection/server-rejects-query-timeout?
+ (fake-connection "MariaDB Connector/J" "9.7.1" 9)))))
+ (testing "only the MariaDB driver builds the timeout out of SQL"
+ (is (false? (u.connection/server-rejects-query-timeout?
+ (fake-connection "PostgreSQL JDBC Driver" "16.2" 16)))))
+ (testing "an unreadable server version is assumed to be fine"
+ (is (false? (u.connection/server-rejects-query-timeout?
+ (reify Connection
+ (getMetaData [_] (throw (ex-info "no metadata" {})))))))))
+
+(defn- recording-statement
+ "A `Statement` over `conn` that records the timeouts set on it into `timeouts`."
+ ^Statement [^Connection conn timeouts]
+ (reify Statement
+ (getConnection [_] conn)
+ (setQueryTimeout [_ seconds] (swap! timeouts conj seconds))))
+
+(deftest set-query-timeout!-test
+ (testing "the timeout is set, and reported as set, when the server can take it"
+ (let [timeouts (atom [])
+ stmt (recording-statement (fake-connection "MariaDB Connector/J" "8.0.36" 8) timeouts)]
+ (is (true? (u.connection/set-query-timeout! stmt 7)))
+ (is (= [7] @timeouts))))
+ (testing "on MySQL 26 the call is skipped entirely, so the caller can bound the statement itself"
+ (let [timeouts (atom [])
+ stmt (recording-statement (fake-connection "MariaDB Connector/J" "26.7.0" 26) timeouts)]
+ (is (false? (u.connection/set-query-timeout! stmt 7)))
+ (is (= [] @timeouts)))))