Skip to content

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

Add rename-tables! driver method (#63302)

Ngoc Khuat29c013a78ab9
diff --git a/docs/developers-guide/driver-changelog.md b/docs/developers-guide/driver-changelog.md
index ba9248d73f8..a91cecc05b3 100644
--- a/docs/developers-guide/driver-changelog.md
+++ b/docs/developers-guide/driver-changelog.md
@@ -17,6 +17,9 @@ title: Driver interface changelog
metabase.driver/connection-spec, metabase.driver/table-exists?, metabase.driver.sql/normalize-name,
and metabase.driver.sql/default-schema to implement sql transforms.
+- Added `metabase.driver/rename-tables!*` multimethod for atomic table renaming operations. Takes a map of {from-table to-table}
+ pairs that has been topologically sorted.
+
- Added the driver multi-methods `metabase.driver/schema-exists?` and `metabase.driver/create-schema-if-needed!` which should be implemented by drivers that support `:schemas` and `:transforms/table`.
- `metabase.driver/humanize-connection-error-message` now takes a list of all messages in the exception chain,
diff --git a/src/metabase/driver.clj b/src/metabase/driver.clj
index 4f6b14a1581..1bc31a39f65 100644
--- a/src/metabase/driver.clj
+++ b/src/metabase/driver.clj
@@ -1278,6 +1278,35 @@
dispatch-on-initialized-driver
:hierarchy #'hierarchy)
+(defmulti rename-tables!*
+ "Driver-specific implementation of table renaming. Takes a pre-sorted map of {from-table to-table}.
+ The input map has already been topologically sorted by the public rename-tables! function.
+ Implementations should perform the actual rename operations atomically as supported by the database.
+ NOTE: Do not call this directly - use rename-tables! instead which handles the topological sort."
+ {:added "0.57.0", :arglists '([driver db-id sorted-rename-map])}
+ dispatch-on-initialized-driver
+ :hierarchy #'hierarchy)
+
+(defn rename-tables!
+ "Rename multiple tables atomically. Takes a map of {from-table to-table}.
+ Performs topological sort to determine correct rename order, then delegates to driver-specific implementation.
+ Implementations should use transactions, compound operations, or metadata locks as supported by the database.
+ Table names may be qualified by schema e.g. :schema/table"
+ {:added "0.57.0"}
+ [driver db-id rename-map]
+ (let [sorted-rename-map (-> rename-map
+ (update-vals vector)
+ u/topological-sort
+ (update-vals first))]
+ (rename-tables!* driver db-id sorted-rename-map)))
+
+#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
+(defn rename-table!
+ "Rename a single table."
+ {:added "0.57.0"}
+ [driver db-id from-table to-table]
+ (rename-tables!* driver db-id {from-table to-table}))
+
(defmulti insert-into!
"Insert `values` into a table named `table-name`. `values` is a lazy sequence of rows, where each row's order matches
`column-names`.
diff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.clj
index 050b470eb69..8147f35d5b3 100644
--- a/src/metabase/driver/mysql.clj
+++ b/src/metabase/driver/mysql.clj
@@ -297,7 +297,20 @@
[_]
:sunday)
-;;; +----------------------------------------------------------------------------------------------------------------+
+(defmethod driver/rename-tables!* :mysql
+ [_driver db-id sorted-rename-map]
+ (let [rename-clauses (map (fn [[from-table to-table]]
+ (str (sql/format-entity from-table) " TO " (sql/format-entity to-table)))
+ sorted-rename-map)
+ sql (str "RENAME TABLE " (str/join ", " rename-clauses))]
+ (sql-jdbc.execute/do-with-connection-with-options
+ :mysql
+ db-id
+ nil
+ (fn [^java.sql.Connection conn]
+ (jdbc/execute! {:connection conn} [sql])))))
+
+;; +----------------------------------------------------------------------------------------------------------------+
;;; | metabase.driver.sql impls |
;;; +----------------------------------------------------------------------------------------------------------------+
diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.clj
index 4602937ac55..3efd1c4f3ef 100644
--- a/src/metabase/driver/postgres.clj
+++ b/src/metabase/driver/postgres.clj
@@ -1057,6 +1057,20 @@
[driver]
(= driver :postgres))
+(defmethod driver/rename-tables!* :postgres
+ [driver db-id sorted-rename-map]
+ (let [sqls (mapv (fn [[from-table to-table]]
+ (first (sql/format {:alter-table (keyword from-table)
+ :rename-table (keyword (name to-table))}
+ :quoted true
+ :dialect (sql.qp/quote-style driver))))
+ sorted-rename-map)]
+ (jdbc/with-db-transaction [t-conn (sql-jdbc.conn/db->pooled-connection-spec db-id)]
+ (with-open [stmt (.createStatement ^java.sql.Connection (:connection t-conn))]
+ (doseq [sql sqls]
+ (.addBatch ^java.sql.Statement stmt ^String sql))
+ (.executeBatch ^java.sql.Statement stmt)))))
+
(defn- alter-column-using-hsql-expr
"In postgres some ALTER COLUMN statements generated by replacing or appending csv files
will result in an error, e.g. boolean columns cannot be changed to bigint.
diff --git a/test/metabase/driver/sql_jdbc_test.clj b/test/metabase/driver/sql_jdbc_test.clj
index 2e664828072..d3b6f540721 100644
--- a/test/metabase/driver/sql_jdbc_test.clj
+++ b/test/metabase/driver/sql_jdbc_test.clj
@@ -3,6 +3,7 @@
[clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.driver.common.table-rows-sample :as table-rows-sample]
+ [metabase.driver.mysql :as mysql]
[metabase.driver.sql-jdbc.sync.describe-database :as sql-jdbc.describe-database]
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.util :as driver.u]
@@ -281,3 +282,96 @@
(let [e (Exception. (Exception. (Exception. (SQLTimeoutException.))))]
(testing "checks for SQLTimeoutException as the default case"
(is (true? (driver/query-canceled? :sql-jdbc e)))))))
+
+(defn- qualified-table-name
+ "Create a qualified table name keyword from schema and name."
+ [schema table-name]
+ (if schema
+ (keyword schema table-name)
+ (keyword table-name)))
+
+(defn- table-rows
+ "Helper function to get table rows for testing"
+ [qualified-table-name]
+ (->> (driver/table-rows-seq driver/*driver* (mt/db) {:name (name qualified-table-name)
+ :schema (namespace qualified-table-name)})
+ (map #(vector (:id %) (:name %)))
+ sort))
+
+#_{:clj-kondo/ignore [:metabase/disallow-hardcoded-driver-names-in-tests]}
+(deftest rename-tables-test
+ (mt/test-drivers #{:postgres :mysql}
+ (when-not (mysql/mariadb? (mt/db))
+ (testing "rename-tables should rename multiple tables atomically"
+ (let [db-id (mt/id)
+ driver driver/*driver*
+ schema (sql.tx/session-schema driver)
+ test-table-1 (mt/random-name)
+ test-table-2 (mt/random-name)
+ qualified-table-1 (qualified-table-name schema test-table-1)
+ qualified-table-2 (qualified-table-name schema test-table-2)
+ temp-table-1 (str test-table-1 "_temp")
+ temp-table-2 (str test-table-2 "_temp")
+ qualified-temp-1 (qualified-table-name schema temp-table-1)
+ qualified-temp-2 (qualified-table-name schema temp-table-2)
+ test-data-1 [[1 "Alice"] [2 "Bob"]]
+ test-data-2 [[1 "Product A"] [2 "Product B"]]]
+
+ ;; so the create-table is using qp and it requires permission setup
+ ;; TODO we should change the implementation of create-table to use jdbc direclty
+ (mt/with-current-user (mt/user->id :crowberto)
+ (driver/create-table! driver db-id qualified-table-1
+ {"id" "INTEGER", "name" "VARCHAR(255)"} {})
+ (driver/create-table! driver db-id qualified-table-2
+ {"id" "INTEGER", "name" "VARCHAR(255)"} {})
+
+ (try
+ (driver/insert-into! driver db-id qualified-table-1 ["id" "name"] test-data-1)
+ (driver/insert-into! driver db-id qualified-table-2 ["id" "name"] test-data-2)
+
+ (testing "basic rename operations work correctly"
+ (driver/rename-tables! driver db-id
+ {qualified-table-1 qualified-temp-1
+ qualified-table-2 qualified-temp-2})
+
+ (is (driver/table-exists? driver (mt/db) {:name temp-table-1 :schema schema}))
+ (is (driver/table-exists? driver (mt/db) {:name temp-table-2 :schema schema}))
+ (is (not (driver/table-exists? driver (mt/db) {:name test-table-1 :schema schema})))
+ (is (not (driver/table-exists? driver (mt/db) {:name test-table-2 :schema schema})))
+
+ (is (= test-data-1 (table-rows qualified-temp-1)))
+ (is (= test-data-2 (table-rows qualified-temp-2)))
+
+ (driver/rename-tables! driver db-id
+ {qualified-temp-1 qualified-table-1
+ qualified-temp-2 qualified-table-2}))
+
+ (testing "atomicity: all renames fail if any rename fails"
+ (let [conflict-table (str test-table-2 "_conflict")
+ qualified-conflict (qualified-table-name schema conflict-table)]
+ (driver/create-table! driver db-id qualified-conflict {"id" "INTEGER"} {})
+
+ (try
+ (is (thrown? Exception
+ (driver/rename-tables! driver db-id
+ {qualified-table-1 qualified-temp-1
+ qualified-table-2 qualified-conflict})))
+
+ (testing "original tables should still exist after failed atomic rename"
+ (is (driver/table-exists? driver (mt/db) {:name test-table-1 :schema schema}))
+ (is (driver/table-exists? driver (mt/db) {:name test-table-2 :schema schema})))
+
+ (testing "temp tables should not exist after failed atomic rename"
+ (is (not (driver/table-exists? driver (mt/db) {:name temp-table-1 :schema schema})))
+ (is (not (driver/table-exists? driver (mt/db) {:name temp-table-2 :schema schema}))))
+
+ (testing "original data should be intact after failed atomic rename"
+ (is (= test-data-1 (table-rows qualified-table-1)))
+ (is (= test-data-2 (table-rows qualified-table-2))))
+
+ (finally
+ (driver/drop-table! driver db-id qualified-conflict)))))
+
+ (finally
+ (driver/drop-table! driver db-id qualified-table-1)
+ (driver/drop-table! driver db-id qualified-table-2)))))))))