The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Remove the long-deprecated `describe-table-fks` method (#75267)
Cam Sauld5f19b86341c
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 191fd75dab7..d7d843b1de0 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -2173,6 +2173,7 @@eventsinterestingnesslib+ lib-bemodelspremium-featuresquery-processordiff --git a/docs/developers-guide/driver-changelog.md b/docs/developers-guide/driver-changelog.mdindex 0ba96fccb0b..263507da45b 100644--- a/docs/developers-guide/driver-changelog.md+++ b/docs/developers-guide/driver-changelog.md@@ -4,6 +4,30 @@ title: Driver interface changelog# Driver Interface Changelog+## Metabase 0.63.0++- `metabase.driver/describe-table-fks`, deprecated in 0.49.0, has been removed. Please implement+ `metabase.driver/describe-fks` instead. This method is now required for drivers that support+ `:metadata/key-constraints`.++ - JDBC-based drivers can implement `metabase.driver.sql-jdbc.sync.describe-table/describe-fks-sql` to take advantage+ of a more performant shared `:sql-jdbc` implementation of `describe-fks`; if they do not implement this method+ they will fall back to a default implementation of `describe-fks` that uses JDBC metadata for each matching table,+ similar to the old default implementation of `describe-table-fks`.++ - The `metabase.driver.sql-jdbc.sync/describe-table-fks` helper function has been removed, but helper functions+ `metabase.driver.sql-jdbc.sync/reducible-fks-for-tables-matching-options` and+ `metabase.driver.sql-jdbc.sync/reducible-table-fks-from-jdbc-metadata` have been added for use if you want to+ write an implementation that works on a per-table basis similar to how the old `describe-table-fks` method worked.++ - `metabase.driver-api.core/reducible-sync-tables` has been exposed in the driver API to fetch a set of matching+ tables that match the `{:schema-names ... :table-names ...}` options passed to `describe-fks`, useful if you want+ to implement a version that fetches FK metadata on a per-table basis.++ - The `:describe-fks` driver feature flag has been removed as a feature since it is no longer needed to differentiate+ between the aforementioned FK description methods; you should remove any `metabase.driver/database-supports?`+ implementations for it.+## Metabase 0.62.0- `sql.params.substitution/field->clause`, `to-clause`, `desugar-filter-clause`, `wrap-value-literals-in-mbql`, and@@ -499,7 +523,7 @@ title: Driver interface changelog`metabase.test.data.sql.ddl/insert-rows-dml-statements`, since `INSERT` is DML, not DDL. Please update your methodimplementations accordingly.-- The `:foreign-keys` driver feature has been removed. `:metadata/keys-constraints` should be used for drivers that+- The `:foreign-keys` driver feature has been removed. `:metadata/key-constraints` should be used for drivers thatsupport foreign key relationships reporting during sync. Implicit joins now depend on the `:left-join` featureinstead. The default value is true for `:sql` based drivers. All join features are now enabled for `:sql` baseddrivers by default. Previously, those depended on the `:foreign-keys` feature. If your driver supports `:left-join`,diff --git a/enterprise/backend/src/metabase_enterprise/checker/provider.clj b/enterprise/backend/src/metabase_enterprise/checker/provider.cljindex 5bd6c5d11d5..9812cffbd0f 100644--- a/enterprise/backend/src/metabase_enterprise/checker/provider.clj+++ b/enterprise/backend/src/metabase_enterprise/checker/provider.clj@@ -125,7 +125,7 @@:name (:name data):engine (keyword (:engine data)):dbms-version (:dbms_version data)- :features #{:foreign-keys :nested-queries :expressions :native-parameters+ :features #{:metadata/key-constraints :nested-queries :expressions :native-parameters:basic-aggregations :standard-deviation-aggregations:expression-aggregations :left-join :right-join :inner-join :full-join}:settings (:settings data)})diff --git a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.cljindex 7f07a6e1d5c..b0a0fb4c785 100644--- a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj+++ b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj@@ -46,7 +46,6 @@:database-routing false:datetime-diff true:describe-default-expr true- :describe-fks false;; JDBC driver always provides "NO" for the IS_GENERATEDCOLUMN JDBC metadata:describe-is-generated false:describe-is-nullable true@@ -390,11 +389,10 @@(let [sql [[(format "CREATE DATABASE IF NOT EXISTS %s;" (quote-schema schema))]]](driver/execute-raw-queries! driver conn-spec sql)))-#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod driver/describe-table-fks :clickhouse- [_driver _database _table]- (log/warn "Clickhouse does not support foreign keys. `describe-table-fks` should not have been called!")- #{})+(defmethod driver/describe-fks :clickhouse+ [_driver _database & {:as _options}]+ (log/warn "Clickhouse does not support foreign keys. `describe-fks` should not have been called!")+ nil)(defmethod driver/table-known-to-not-exist? :clickhouse[_driver e]diff --git a/modules/drivers/databricks/src/metabase/driver/databricks.clj b/modules/drivers/databricks/src/metabase/driver/databricks.cljindex c83acb84c62..c892d4c0311 100644--- a/modules/drivers/databricks/src/metabase/driver/databricks.clj+++ b/modules/drivers/databricks/src/metabase/driver/databricks.clj@@ -44,18 +44,17 @@(doseq [[feature supported?] {:basic-aggregations true:binning true+ :database-routing true:describe-fields true- :describe-fks true:expression-aggregations true:expression-literals true:expressions true+ :multi-level-schema true:native-parameters true:nested-queries true- :multi-level-schema true:set-timezone true:standard-deviation-aggregations true- :test/jvm-timezone-setting false- :database-routing true}]+ :test/jvm-timezone-setting false}](defmethod driver/database-supports? [:databricks feature] [_driver _feature _db] supported?))(defmethod sql-jdbc.sync/database-type->base-type :databricksdiff --git a/modules/drivers/databricks/test/metabase/driver/databricks_test.clj b/modules/drivers/databricks/test/metabase/driver/databricks_test.cljindex 0da13aa43b7..cb5b1772f55 100644--- a/modules/drivers/databricks/test/metabase/driver/databricks_test.clj+++ b/modules/drivers/databricks/test/metabase/driver/databricks_test.clj@@ -149,10 +149,11 @@(set fields)))))))(deftest ^:parallel describe-fks-test- (mt/test-driver- :databricks- (let [fks (vec (driver/describe-fks :databricks (mt/db) {:schema-names [(maybe-qualify-schema "test-data")]- :table-names ["orders"]}))]+ (mt/test-driver :databricks+ (let [fks (vec (driver/describe-fks :databricks+ (lib.metadata/database (mt/metadata-provider))+ {:schema-names [(maybe-qualify-schema "test-data")]+ :table-names ["orders"]}))](testing "Only fks from current catalog are registered"(is (= 2 (count fks))))(testing "Expected fks are returned"diff --git a/modules/drivers/mongo/src/metabase/driver/mongo.clj b/modules/drivers/mongo/src/metabase/driver/mongo.cljindex e7a48458b3a..8a592a4ad5a 100644--- a/modules/drivers/mongo/src/metabase/driver/mongo.clj+++ b/modules/drivers/mongo/src/metabase/driver/mongo.clj@@ -507,11 +507,11 @@;; We say Mongo supports foreign keys so that the front end can use implicit;; joins. In reality, Mongo doesn't support foreign keys.-;; Only define an implementation for `:foreign-keys` if none exists already.+;; Only define an implementation for `:metadata/key-constraints` if none exists already.;; In test extensions we define an alternate implementation, and we don't want;; to stomp over that if it was loaded already.-(when-not (get (methods driver/database-supports?) [:mongo :foreign-keys])- (defmethod driver/database-supports? [:mongo :foreign-keys] [_driver _feature _db] true))+(when-not (get (methods driver/database-supports?) [:mongo :metadata/key-constraints])+ (defmethod driver/database-supports? [:mongo :metadata/key-constraints] [_driver _feature _db] true))(defmethod driver/mbql->native :mongo[_ query]diff --git a/modules/drivers/mongo/test/metabase/test/data/mongo.clj b/modules/drivers/mongo/test/metabase/test/data/mongo.cljindex 49634216f7f..4f1d1095135 100644--- a/modules/drivers/mongo/test/metabase/test/data/mongo.clj+++ b/modules/drivers/mongo/test/metabase/test/data/mongo.clj@@ -26,7 +26,7 @@false));; During tests don't treat Mongo as having FK support-(defmethod driver/database-supports? [:mongo :foreign-keys] [_driver _feature _db] (not config/is-test?))+(defmethod driver/database-supports? [:mongo :metadata/key-constraints] [_driver _feature _db] (not config/is-test?))(defn ssl-required?"Returns if the mongo server requires an SSL connection."diff --git a/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj b/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.cljindex 39957c46e36..20c69c6f749 100644--- a/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj+++ b/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj@@ -634,9 +634,8 @@;;; The Presto JDBC driver DOES NOT support the `.getImportedKeys` method so just return `nil` here so the `:sql-jdbc`;;; implementation doesn't try to use it.-#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod driver/describe-table-fks :presto-jdbc- [_driver _database _table]+(defmethod driver/describe-fks :presto-jdbc+ [_driver _database & {:as _options}]nil)(defmethod driver/can-connect? :presto-jdbcdiff --git a/modules/drivers/redshift/src/metabase/driver/redshift.clj b/modules/drivers/redshift/src/metabase/driver/redshift.cljindex 2dbb178b935..ed4356ae064 100644--- a/modules/drivers/redshift/src/metabase/driver/redshift.clj+++ b/modules/drivers/redshift/src/metabase/driver/redshift.clj@@ -48,7 +48,6 @@:database-routing true:describe-default-expr false:describe-fields true- :describe-fks true:describe-is-generated false:describe-is-nullable false:expression-literals truediff --git a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj b/modules/drivers/snowflake/src/metabase/driver/snowflake.cljindex c3d97b2332e..0360e478739 100644--- a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj+++ b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj@@ -29,6 +29,8 @@[metabase.driver.sql.util :as sql.u][metabase.driver.sync :as driver.s][metabase.driver.util :as driver.u]+ [metabase.lib.schema.common :as lib.schema.common]+ [metabase.lib.schema.metadata :as lib.schema.metadata][metabase.util :as u][metabase.util.date-2 :as u.date][metabase.util.honey-sql-2 :as h2x]@@ -36,7 +38,7 @@[metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.performance :refer [mapv empty? not-empty select-keys]]+ [metabase.util.performance :refer [empty? mapv not-empty select-keys]][ring.util.codec :as codec])(:import(java.io File)@@ -77,8 +79,8 @@:workspace false}](defmethod driver/database-supports? [:snowflake feature] [_driver _feature _db] supported?))-(defn- quote-schema [s] (sql.u/quote-name :snowflake :schema s))-(defn- quote-field [s] (sql.u/quote-name :snowflake :field s))+(mu/defn- quote-schema ^String [s :- :string] (sql.u/quote-name :snowflake :schema s))+(mu/defn- quote-field ^String [s :- :string] (sql.u/quote-name :snowflake :field s))(defmethod driver/humanize-connection-error-message :snowflake[_ messages]@@ -780,12 +782,15 @@[_ entity-name](escape-name-for-metadata entity-name))-(defn- dynamic-table?+(mu/defn- dynamic-table?"Check if the table is a dynamic table.You can't rely on :table_type from INFORMATION_SCHEMA.TABLES or :type from getTables because inboth cases it returns `Table` for dynamic tables."- [^Connection conn ^String db-name ^String schema-name ^String table-name]+ [^Connection conn :- (lib.schema.common/instance-of-class Connection)+ ^String db-name :- :string+ ^String schema-name :- :string+ ^String table-name :- :string](try;; there is another way of checking this by using SHOW TABLES command and check `is_dynamic` column.;; But this column is not documented on https://docs.snowflake.com/en/sql-reference/sql/show-tables (2024/05/07),@@ -808,12 +813,10 @@driver-api/databasedb-name)))-;; The Snowflake JDBC driver is buggy: schema and table name are interpreted as patterns-;; in getPrimaryKeys and getImportedKeys calls. When this bug gets fixed, the-;; [[sql-jdbc.describe-table/get-table-pks]] method and the [[describe-table-fks*]] and-;; [[describe-table-fks]] functions can be dropped and the call to [[describe-table-fks]]-;; can be replaced with a call to [[sql-jdbc.sync/describe-table-fks]]. See #26054 for-;; more context.+;; The Snowflake JDBC driver is buggy: schema and table name are interpreted as patterns in getPrimaryKeys and+;; getImportedKeys calls. When this bug gets fixed, the [[sql-jdbc.describe-table/get-table-pks]] method can be+;; dropped and the the [[reducible-table-fks-from-jdbc-metadata]] function can be simplified. See #26054 for more+;; context.(defmethod sql-jdbc.describe-table/get-table-pks :snowflake[_driver ^Connection conn db-name-or-nil table](let [^DatabaseMetaData metadata (.getMetaData conn)@@ -831,45 +834,30 @@[](throw e))))))-(defn- describe-table-fks*- "Stolen from [[sql-jdbc.describe-table]].- The only change is that it escapes `schema` and `table-name`."- [_driver ^Connection conn {^String schema :schema, ^String table-name :name} db-name]+(mu/defn- reducible-table-fks-from-jdbc-metadata :- ::driver/describe-fks.result+ "Wrapper around [[metabase.driver.sql-jdbc.sync/reducible-table-fks-from-jdbc-metadata]].+ The only changes are that it escapes `schema` and `table-name`, and catches errors when trying to get FKs for+ dynamic tables."+ [^Connection conn :- (lib.schema.common/instance-of-class Connection)+ ^DatabaseMetaData metadata :- (lib.schema.common/instance-of-class DatabaseMetaData)+ ^String db-name :- [:maybe :string]+ ^String schema :- [:maybe :string]+ ^String table-name :- :string];; Snowflake bug: schema and table name are interpreted as patterns- (let [metadata (.getMetaData conn)- schema-name (escape-name-for-metadata schema)- table-name (escape-name-for-metadata table-name)]- (try- (into- #{}- (sql-jdbc.sync.common/reducible-results #(.getImportedKeys metadata db-name schema-name table-name)- (fn [^ResultSet rs]- (fn []- {:fk-column-name (.getString rs "FKCOLUMN_NAME")- :dest-table {:name (.getString rs "PKTABLE_NAME")- :schema (.getString rs "PKTABLE_SCHEM")}- :dest-column-name (.getString rs "PKCOLUMN_NAME")}))))- (catch SnowflakeSQLException e- ;; dynamic tables doesn't support fks so it's fine to suppress the exception- (if (dynamic-table? conn db-name schema table-name)- #{}- (throw e))))))--(defn- describe-table-fks- "Stolen from [[sql-jdbc.describe-table]].- The only change is that it calls the stolen function [[describe-table-fks*]]."- [driver db-or-id-or-spec table db-name]- (sql-jdbc.execute/do-with-connection-with-options- driver- db-or-id-or-spec- nil- (fn [conn]- (describe-table-fks* driver conn table db-name))))--#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod driver/describe-table-fks :snowflake- [driver database table]- (describe-table-fks driver database table (db-name database)))+ (let [schema (escape-name-for-metadata schema)+ table-name (escape-name-for-metadata table-name)]+ (when-not (dynamic-table? conn db-name schema table-name)+ (sql-jdbc.sync/reducible-table-fks-from-jdbc-metadata metadata db-name schema table-name))))++(mu/defmethod driver/describe-fks :snowflake :- ::driver/describe-fks.result+ [driver :- :keyword+ database :- ::lib.schema.metadata/database+ & {:as options} :- ::driver/describe-fks.options]+ (let [db-name (db-name database)+ f (fn f [^Connection conn table]+ (let [metadata (.getMetaData conn)]+ (reducible-table-fks-from-jdbc-metadata conn metadata db-name (:schema table) (:name table))))]+ (sql-jdbc.sync/reducible-fks-for-tables-matching-options driver database options f)))(defmethod sql.qp/current-datetime-honeysql-form :snowflake [_] :%current_timestamp)diff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.cljindex 50b8bf87dfd..314ebea82f3 100644--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj@@ -1,5 +1,5 @@(ns ^:mb/driver-tests metabase.driver.snowflake-test- {:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.driver.snowflake-test]}+ {:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.driver.snowflake-test]}metabase.test.data/run-mbql-query {:namespaces [metabase.driver.snowflake-test]}}}}}}(:require[buddy.core.codecs :as codecs]@@ -390,11 +390,12 @@[["metabase_users"[{:field-name "name" :base-type :type/Text}][["mb_qnkhuat"]]]])- (let [details (:details (mt/db))]+ (let [{{db-name :db, :as details} :details} (mt/db)](jdbc/execute! (sql-jdbc.conn/connection-details->spec driver/*driver* details)[(format "CREATE OR REPLACE DYNAMIC TABLE \"%s\".\"PUBLIC\".\"metabase_fan\" target_lag = '1 minute' warehouse = 'COMPUTE_WH' ASSELECT * FROM \"%s\".\"PUBLIC\".\"metabase_users\" WHERE \"%s\".\"PUBLIC\".\"metabase_users\".\"name\" LIKE 'MB_%%';"- (:db details) (:db details) (:db details))])+ db-name db-name db-name)])+ (sync/sync-database! (t2/select-one :model/Database (mt/id)) {:scan :schema})(thunk))))(defmacro with-dynamic-table!@@ -406,7 +407,6 @@(testing "Should be able to sync dynamic tables"(mt/test-driver :snowflake(with-dynamic-table!- (sync/sync-database! (t2/select-one :model/Database (mt/id)))(testing "both base tables and dynamic tables should be synced"(is (= #{"metabase_fan" "metabase_users"}(t2/select-fn-set :name :model/Table :db_id (mt/id))))@@ -425,8 +425,10 @@(mt/db)nil(fn [conn]- (let [dynamic-table (t2/select-one :model/Table :name "metabase_fan" :db_id (mt/id))- normal-table (t2/select-one :model/Table :name "metabase_users" :db_id (mt/id))+ (let [dynamic-table (or (t2/select-one :model/Table :name "metabase_fan" :db_id (mt/id))+ (throw (ex-info "Failed to find dynamic table" {:database-id (mt/id)})))+ normal-table (or (t2/select-one :model/Table :name "metabase_users" :db_id (mt/id))+ (throw (ex-info "Failed to find normal table" {:database-id (mt/id)})))db-name (-> (mt/db) :details :db)](testing "dynamic-table?"(testing "returns true for dynamic table"@@ -440,9 +442,13 @@(is (= [] (sql-jdbc.describe-table/get-table-pks :snowflake conn db-name dynamic-table))))(testing "also works if db-name is nil"(is (= [] (sql-jdbc.describe-table/get-table-pks :snowflake conn nil dynamic-table)))))- (testing "driver/describe-table-fks returns empty set for dynamic table"- #_{:clj-kondo/ignore [:deprecated-var]}- (is (= #{} (driver/describe-table-fks :snowflake (mt/db) dynamic-table)))))))))))+ (testing "driver/describe-fks returns empty set for dynamic table"+ (is (= #{}+ (into #{}+ (driver/describe-fks :snowflake+ (lib.metadata/database (mt/metadata-provider))+ {:schema-names [(:schema dynamic-table)]+ :table-names [(:name dynamic-table)]}))))))))))))(deftest ^:sequential describe-table-fields-uuid-column-test(mt/test-driver :snowflake@@ -681,14 +687,23 @@(-> (driver/describe-table :snowflake (assoc (mt/db) :name "ABC") (t2/select-one :model/Table :id (mt/id :categories)))(update :fields (partial sort-by :name))))))))-(deftest ^:sequential describe-table-fks-test+(deftest ^:sequential describe-fks-test(mt/test-driver :snowflake- (testing "make sure describe-table-fks uses the NAME FROM DETAILS too"- (is (= #{{:fk-column-name "category_id"- :dest-table {:name "categories", :schema "PUBLIC"}- :dest-column-name "id"}}- #_{:clj-kondo/ignore [:deprecated-var]}- (driver/describe-table-fks :snowflake (assoc (mt/db) :name "ABC") (t2/select-one :model/Table :id (mt/id :venues))))))))+ (testing "make sure describe-fks uses the NAME FROM DETAILS too"+ (let [table (t2/select-one [:model/Table :schema :name] :id (mt/id :venues))]+ (is (= [{:fk-table-schema "PUBLIC"+ :fk-table-name "venues"+ :fk-column-name "category_id"+ :pk-table-schema "PUBLIC"+ :pk-table-name "categories"+ :pk-column-name "id"}]+ (into []+ (driver/describe-fks+ :snowflake+ (-> (lib.metadata/database (mt/metadata-provider))+ (assoc :name "ABC"))+ {:schema-names [(:schema table)]+ :table-names [(:name table)]}))))))))(deftest can-change-from-password-test(mt/test-driverdiff --git a/modules/drivers/starburst/src/metabase/driver/starburst.clj b/modules/drivers/starburst/src/metabase/driver/starburst.cljindex b3488c74d54..c57bdd884f1 100644--- a/modules/drivers/starburst/src/metabase/driver/starburst.clj+++ b/modules/drivers/starburst/src/metabase/driver/starburst.clj@@ -110,8 +110,8 @@;;; The Starburst JDBC driver DOES NOT support the `.getImportedKeys` method so just return `nil` here so the;;; implementation doesn't try to use it.#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod driver/describe-table-fks :starburst- [_driver _database _table]+(defmethod driver/describe-fks :starburst+ [_driver _database & {:as _options}];; starburst does not support finding foreign key metadata tables, but some connectors support foreign keys.;; We have this return nil to avoid running unnecessary queries during fks sync.nil)diff --git a/src/metabase/driver.clj b/src/metabase/driver.cljindex da58da55fec..553567e9a48 100644--- a/src/metabase/driver.clj+++ b/src/metabase/driver.clj@@ -8,7 +8,6 @@these drivers define additional multimethods that child drivers should implement; see [[metabase.driver.sql]] and[[metabase.driver.sql-jdbc]] for more details."(:refer-clojure :exclude [mapv empty?])- #_{:clj-kondo/ignore [:metabase/modules]}(:require[clojure.java.io :as io][clojure.set :as set]@@ -18,14 +17,16 @@[metabase.driver.impl :as driver.impl][metabase.driver.settings][metabase.lib.schema :as lib.schema]+ [metabase.lib.schema.common :as lib.schema.common][metabase.lib.schema.metadata :as lib.schema.metadata][metabase.query-processor.error-type :as qp.error-type][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.json :as json]+ [metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.performance :refer [mapv empty?]]+ [metabase.util.performance :refer [empty? mapv]][potemkin :as p]))(set! *warn-on-reflection* true)@@ -410,34 +411,59 @@(defmethod qualified-name-components ::driver [_driver] [:schema])-(defmulti describe-table-fks- "Return information about the foreign keys in a `table`. Required for drivers that support :metadata/key-constraints- but not :describe-fks. Results should match the [[metabase.sync.interface/FKMetadata]] schema."- {:added "0.32.0" :deprecated "0.49.0" :arglists '([driver database table])}- dispatch-on-initialized-driver- :hierarchy #'hierarchy)--#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod describe-table-fks ::driver [_ _ _]- nil)+(mr/def ::describe-fks.options+ [:maybe+ [:map+ {:closed true}+ [:schema-names {:optional true} [:maybe+ [:or+ [:sequential :string]+ [:set :string]]]]+ [:table-names {:optional true} [:maybe+ [:or+ [:sequential :string]+ [:set :string]]]]]])++(mr/def ::describe-fks.result+ "Schema for the results for [[describe-fks]]; results are ordered by `fk-table-schema` and `fk-table-name` in+ ascending order."+ [:maybe+ [:or+ [:sequential [:ref :metabase.sync.interface/FKMetadataEntry]]+ ;; reducible sequence of FK metadata entries+ (lib.schema.common/instance-of-class clojure.lang.IReduceInit)]])(defmulti describe-fks"Returns a reducible collection of maps, each containing information about foreign keys.Takes optional keyword arguments to narrow down the results to a set of `schema-names`and `table-names`.- `database` should be a Lib-style `:metadata/database` (i.e., should use kebab-case keys).+ `database` should be a Lib-style `:metadata/database` (i.e., should use kebab-case keys, and conform to the+ `:metabase.lib.schema.metadata/database` schema).- Results match [[metabase.sync.interface/FKMetadataEntry]].- Results are optionally filtered by `schema-names` and `table-names` provided.- Results are ordered by `fk-table-schema` and `fk-table-name` in ascending order.+ Results should match `::describe-fks.result`.++ Results are optionally filtered by `schema-names` and `table-names` provided; you can use the+ `::describe-fks.options` schema for the options map.++ Results should be ordered by `fk-table-schema` and `fk-table-name` in ascending order.- Required for drivers that support `:describe-fks`."- {:added "0.49.0" :arglists '([driver database & {:keys [schema-names table-names]}])}+ This method *must* be implemented for drivers that support `:metadata/key-constraints`."+ {:added "0.49.0" :arglists '([driver database & {:keys [schema-names table-names], :as _options}])}dispatch-on-initialized-driver:hierarchy #'hierarchy)-(defmethod describe-fks ::driver [_ _]+(declare database-supports?)++(mu/defmethod describe-fks ::driver :- ::describe-fks.result+ [driver :- :keyword+ database :- ::lib.schema.metadata/database+ & {:as _options} :- ::describe-fks.options]+ (if (database-supports? driver :metadata/key-constraints database)+ (throw (ex-info "Drivers that support :metadata/key-constraints must implement metabase.driver/describe-fks"+ {:driver driver, :type ::qp.error-type/driver}))+ (log/warnf "metabase.driver/describe-fks should not be called for a driver that does not support :metadata/key-constraints; called for %s"+ driver))nil);;; this is no longer used but we can leave it around for not for documentation purposes. Maybe we can actually do@@ -732,10 +758,6 @@;; Does the driver support column(s) support storing index info:index-info;;- ;; Does the driver support a faster `sync-fks` step by fetching all FK metadata in a single collection?- ;; if so, `metabase.driver/describe-fks` must be implemented instead of `metabase.driver/describe-table-fks`- :describe-fks- ;;;; Does the driver support a faster `sync-fields` step by fetching all FK metadata in a single collection?;; if so, `metabase.driver/describe-fields` must be implemented instead of `metabase.driver/describe-table`:describe-fields@@ -972,7 +994,7 @@as keywords whenever possible. This provides for both unified error messages and categories which let us pointusers to the erroneous input fields.Error messages can also be strings, or localized strings, as returned by [[metabase.util.i18n/trs]] and- `metabase.util.i18n/tru`.+ [[metabase.util.i18n/tru]].Passed a collection of all non-nil exception messages that were thrown during connection attempt."{:added "0.32.0" :arglists '([this messages])}dispatch-on-initialized-driverdiff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.cljindex 150de7c4756..42873ac1e2e 100644--- a/src/metabase/driver/mysql.clj+++ b/src/metabase/driver/mysql.clj@@ -64,7 +64,6 @@:connection-impersonation true:connection-impersonation-requires-role true:describe-fields true- :describe-fks true:convert-timezone true:datetime-diff true:full-join falsediff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.cljindex cee74c19aea..c732f5f5b80 100644--- a/src/metabase/driver/postgres.clj+++ b/src/metabase/driver/postgres.clj@@ -66,35 +66,34 @@(defmethod driver/display-name :postgres [_] "PostgreSQL");; Features that are supported by Postgres and all of its child drivers like Redshift-(doseq [[feature supported?] {:connection-impersonation true- :describe-fields true- :describe-fks true- :describe-indexes true- :describe-default-expr true- :describe-is-generated true- :describe-is-nullable true- :convert-timezone true- :datetime-diff true- :now true- :rename true- :atomic-renames true- :persist-models true- :schemas true- :identifiers-with-spaces true- :uuid-type true- :split-part true- :uploads true- :expression-literals true- :expressions/text true- :expressions/integer true- :expressions/float true- :expressions/date true- :database-routing true- :transforms/table true- :transforms/python true- :transforms/index-ddl true+(doseq [[feature supported?] {:atomic-renames true+ :connection-impersonation true+ :convert-timezone true+ :database-routing true+ :datetime-diff true+ :describe-default-expr true+ :describe-fields true+ :describe-indexes true+ :describe-is-generated true+ :describe-is-nullable true+ :expression-literals true+ :expressions/date true+ :expressions/float true+ :expressions/integer true+ :expressions/text true+ :identifiers-with-spaces true:metadata/table-existence-check true- :workspace true}]+ :now true+ :persist-models true+ :rename true+ :schemas true+ :split-part true+ :transforms/index-ddl true+ :transforms/python true+ :transforms/table true+ :uploads true+ :uuid-type true+ :workspace true}](defmethod driver/database-supports? [:postgres feature] [_driver _feature _db] supported?))(defmethod driver/database-supports? [:postgres :nested-field-columns]diff --git a/src/metabase/driver/sql_jdbc.clj b/src/metabase/driver/sql_jdbc.cljindex 27369d5c956..368a8d0bad0 100644--- a/src/metabase/driver/sql_jdbc.clj+++ b/src/metabase/driver/sql_jdbc.clj@@ -20,6 +20,7 @@[metabase.driver.sql-jdbc.sync.describe-database :as sql-jdbc.describe-database][metabase.driver.sql.query-processor :as sql.qp][metabase.driver.sync :as driver.s]+ [metabase.lib.schema.metadata :as lib.schema.metadata][metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]@@ -115,14 +116,11 @@[driver database & {:as args}](sql-jdbc.sync/describe-indexes driver database args))-#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod driver/describe-table-fks :sql-jdbc- [driver database table]- (sql-jdbc.sync/describe-table-fks driver database table))--(defmethod driver/describe-fks :sql-jdbc- [driver database & {:as args}]- (sql-jdbc.sync/describe-fks driver database args))+(mu/defmethod driver/describe-fks :sql-jdbc :- ::driver/describe-fks.result+ [driver :- :keyword+ database :- ::lib.schema.metadata/database+ & {:as options} :- ::driver/describe-fks.options]+ (sql-jdbc.sync/describe-fks driver database options))(defmethod driver/describe-table-indexes :sql-jdbc[driver database table]diff --git a/src/metabase/driver/sql_jdbc/execute.clj b/src/metabase/driver/sql_jdbc/execute.cljindex 62a1f73d257..10fa868640e 100644--- a/src/metabase/driver/sql_jdbc/execute.clj+++ b/src/metabase/driver/sql_jdbc/execute.clj@@ -5,7 +5,6 @@for JDBC drivers that do not support `java.time` classes can be found in`metabase.driver.sql-jdbc.execute.legacy-impl`. "(:refer-clojure :exclude [mapv empty? get-in])- #_{:clj-kondo/ignore [:metabase/modules]}(:require[clojure.core.async :as a][clojure.java.jdbc :as jdbc]@@ -20,6 +19,7 @@[metabase.driver.sql-jdbc.execute.diagnostic :as sql-jdbc.execute.diagnostic][metabase.driver.sql-jdbc.execute.old-impl :as sql-jdbc.execute.old][metabase.driver.sql-jdbc.sync.interface :as sql-jdbc.sync.interface]+ [metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.info :as lib.schema.info][metabase.premium-features.core :refer [defenterprise]][metabase.tracing.core :as tracing]@@ -27,26 +27,11 @@[metabase.util.i18n :refer [tru]][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.performance :as perf :refer [mapv empty? get-in]]+ [metabase.util.performance :as perf :refer [empty? get-in mapv]][potemkin :as p])(:import- (java.sql- Connection- JDBCType- PreparedStatement- ResultSet- ResultSetMetaData- SQLFeatureNotSupportedException- Statement- Types)- (java.time- Instant- LocalDate- LocalDateTime- LocalTime- OffsetDateTime- OffsetTime- ZonedDateTime)+ (java.sql Connection JDBCType PreparedStatement ResultSet ResultSetMetaData SQLFeatureNotSupportedException Statement Types)+ (java.time Instant LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)(java.util.concurrent Executors)(javax.sql DataSource)))@@ -345,7 +330,7 @@deprecated [[sql-jdbc.execute.old/connection-with-timezone]] method."{:added "0.47.0"}[driver :- :keyword- db-or-id-or-spec :- [:or :int :map]+ db-or-id-or-spec :- [:or ::lib.schema.id/database :map]options :- ConnectionOptionsf :- fn?](binding [*connection-recursion-depth* (inc *connection-recursion-depth*)]diff --git a/src/metabase/driver/sql_jdbc/sync.clj b/src/metabase/driver/sql_jdbc/sync.cljindex f0a2b041a7a..6b2ab83d4f5 100644--- a/src/metabase/driver/sql_jdbc/sync.clj+++ b/src/metabase/driver/sql_jdbc/sync.clj@@ -39,10 +39,11 @@describe-tabledescribe-table-fieldsdescribe-table-fields-xf- describe-table-fksdescribe-table-indexesget-catalogs- pattern-based-database-type->base-type]+ pattern-based-database-type->base-type+ reducible-fks-for-tables-matching-options+ reducible-table-fks-from-jdbc-metadata][sql-jdbc.describe-databasedescribe-databasefast-active-tablesdiff --git a/src/metabase/driver/sql_jdbc/sync/describe_table.clj b/src/metabase/driver/sql_jdbc/sync/describe_table.cljindex 3ab6c3de645..eb277a26b6d 100644--- a/src/metabase/driver/sql_jdbc/sync/describe_table.clj+++ b/src/metabase/driver/sql_jdbc/sync/describe_table.clj@@ -1,6 +1,5 @@(ns metabase.driver.sql-jdbc.sync.describe-table- "SQL JDBC impl for `describe-fields`, `describe-table`, `describe-fks`, `describe-table-fks`, and `describe-nested-field-columns`.- `describe-table-fks` is deprecated and will be replaced by `describe-fks` in the future."+ "SQL JDBC impl for `describe-fields`, `describe-table`, `describe-fks`, and `describe-nested-field-columns`."(:refer-clojure :exclude [some select-keys every? mapv empty? not-empty])(:require[clojure.java.jdbc :as jdbc]@@ -18,9 +17,12 @@[metabase.driver.sql-jdbc.sync.common :as sql-jdbc.sync.common][metabase.driver.sql-jdbc.sync.interface :as sql-jdbc.sync.interface][metabase.driver.sql.query-processor :as sql.qp]+ [metabase.lib.schema.common :as lib.schema.common]+ [metabase.lib.schema.metadata :as lib.schema.metadata][metabase.util :as u][metabase.util.honey-sql-2 :as h2x][metabase.util.log :as log]+ [metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.performance :refer [some select-keys every? mapv empty? not-empty]][potemkin :as p]@@ -401,27 +403,72 @@(map (fn [col] (select-keys col [:table-schema :table-name :field-name])))(sql-jdbc.execute/reducible-query db (describe-indexes-sql driver (assoc args :details (driver.conn/effective-details db)))))))-(defn- describe-table-fks*- [_driver ^Connection conn {^String schema :schema, ^String table-name :name} & [^String db-name-or-nil]]- (into- #{}- (sql-jdbc.sync.common/reducible-results #(.getImportedKeys (.getMetaData conn) db-name-or-nil schema table-name)- (fn [^ResultSet rs]- (fn []- {:fk-column-name (.getString rs "FKCOLUMN_NAME")- :dest-table {:name (.getString rs "PKTABLE_NAME")- :schema (.getString rs "PKTABLE_SCHEM")}- :dest-column-name (.getString rs "PKCOLUMN_NAME")})))))--(defn describe-table-fks- "Default implementation of [[metabase.driver/describe-table-fks]] for SQL JDBC drivers. Uses JDBC DatabaseMetaData."- [driver db-or-id-or-spec table & [db-name-or-nil]]- (sql-jdbc.execute/do-with-connection-with-options- driver- db-or-id-or-spec- nil- (fn [^Connection conn]- (describe-table-fks* driver conn table db-name-or-nil))))+(mu/defn reducible-table-fks-from-jdbc-metadata :- ::driver/describe-fks.result+ "Part of the implementation for [[describe-fks-with-jdbc-metadata]], which is the default implementation+ of [[metabase.driver/describe-fks]]. Made available if you'd like to implement [[metabase.driver/describe-fks]]+ individually for each Table.++ Return a reducible sequence of foreign key information maps (as expected by [[metabase.driver/describe-fks]]) for+ Table with `schema`, `table-name`, and, optionally `db-name-or-nil` using+ `java.sql.DatabaseMetaData/getImportedKeys`. These strings act like filters for the returned results."+ [^DatabaseMetaData metadata :- (lib.schema.common/instance-of-class DatabaseMetaData)+ ^String db-name-or-nil :- [:maybe :string]+ ^String schema :- [:maybe :string]+ ^String table-name :- :string]+ (sql-jdbc.sync.common/reducible-results+ #(.getImportedKeys metadata db-name-or-nil schema table-name)+ (fn [^ResultSet rs]+ (fn []+ {:fk-table-schema schema+ :fk-table-name table-name+ :fk-column-name (.getString rs "FKCOLUMN_NAME")+ :pk-table-schema (.getString rs "PKTABLE_SCHEM")+ :pk-table-name (.getString rs "PKTABLE_NAME")+ :pk-column-name (.getString rs "PKCOLUMN_NAME")}))))++(mu/defn reducible-fks-for-tables-matching-options :- ::driver/describe-fks.result+ "Part of the implementation for [[describe-fks-with-jdbc-metadata]], which is the default implementation+ of [[metabase.driver/describe-fks]]. Made available if you'd like to implement [[metabase.driver/describe-fks]]+ individually for each Table.++ Return a reducible sequence of foreign key information maps (as expected by [[metabase.driver/describe-fks]]) by+ calling++ (f ^java.sql.Connection conn table)++ for each Table that matches the `options` spec and concatenating the results."+ [driver :- :keyword+ database :- ::lib.schema.metadata/database+ options :- ::driver/describe-fks.options+ f :- [:=>+ [:cat+ (lib.schema.common/instance-of-class Connection)+ [:map+ {:description "Table"}+ [:schema {:optional true} [:maybe :string]]+ [:name :string]]]+ ::driver/describe-fks.result]]+ (reify clojure.lang.IReduceInit+ (reduce [_this rf init]+ (let [reducible-tables (driver-api/reducible-sync-tables database options)]+ (sql-jdbc.execute/do-with-connection-with-options+ driver+ database+ nil+ (fn [^Connection conn]+ (let [xform (mapcat (partial f conn)) ; (f conn table) => [fk1 fk2 ...]+ reducible-fks (eduction xform reducible-tables)]+ (reduce rf init reducible-fks))))))))++(mu/defn- describe-fks-with-jdbc-metadata :- ::driver/describe-fks.result+ "Default implementation of [[metabase.driver/describe-fks]] for JDBC-based drivers."+ [driver :- :keyword+ database :- ::lib.schema.metadata/database+ options :- ::driver/describe-fks.options]+ (letfn [(f [^java.sql.Connection conn {schema :schema, table-name :name, :as _table}]+ (let [metadata (.getMetaData conn)]+ (reducible-table-fks-from-jdbc-metadata metadata nil schema table-name)))]+ (reducible-fks-for-tables-matching-options driver database options f)))(defmulti describe-fks-sql"Returns a SQL query ([sql & params]) for use in the default JDBC implementation of [[metabase.driver/describe-fks]],@@ -431,13 +478,24 @@driver/dispatch-on-initialized-driver:hierarchy #'driver/hierarchy)-(defn describe-fks- "Default implementation of [[metabase.driver/describe-fks]] for JDBC drivers. Uses JDBC DatabaseMetaData."- [driver db & {:keys [schema-names table-names] :as args}]+(mu/defn- describe-fks-with-sql :- ::driver/describe-fks.result+ [driver :- :keyword+ db :- ::lib.schema.metadata/database+ {:keys [schema-names table-names] :as options} :- ::driver/describe-fks.options](if (or (and schema-names (empty? schema-names))(and table-names (empty? table-names)))[]- (sql-jdbc.execute/reducible-query db (describe-fks-sql driver (assoc args :details (driver.conn/effective-details db))))))+ (sql-jdbc.execute/reducible-query db (describe-fks-sql driver (assoc options :details (driver.conn/effective-details db))))))++(mu/defn describe-fks :- ::driver/describe-fks.result+ "Default implementation of [[metabase.driver/describe-fks]] for JDBC drivers. Uses JDBC DatabaseMetaData."+ [driver :- :keyword+ database :- ::lib.schema.metadata/database+ options :- ::driver/describe-fks.options]+ (let [f (if (get-method describe-fks-sql driver)+ describe-fks-with-sql+ describe-fks-with-jdbc-metadata)]+ (f driver database options)))(defn describe-table-indexes"Default implementation of [[metabase.driver/describe-table-indexes]] for SQL JDBC drivers. Uses JDBC DatabaseMetaData."diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.cljindex 0ebeeba0587..8c80e88531a 100644--- a/src/metabase/driver_api/core.clj+++ b/src/metabase/driver_api/core.clj@@ -171,6 +171,7 @@secrets/uploaded-base-64-prefix-patternsetting/defsettingsync-util/name-for-logging+ sync-util/reducible-sync-tablessystem/site-uuidupload.db/current-database)diff --git a/src/metabase/sync/fetch_metadata.clj b/src/metabase/sync/fetch_metadata.cljindex ecd5c0c44b0..883ef04e529 100644--- a/src/metabase/sync/fetch_metadata.clj+++ b/src/metabase/sync/fetch_metadata.clj@@ -7,6 +7,7 @@[metabase.driver :as driver][metabase.driver.connection :as driver.conn][metabase.driver.util :as driver.u]+ [metabase.lib-be.core :as lib-be][metabase.sync.interface :as i][metabase.sync.util :as sync-util][metabase.util.log :as log]@@ -130,33 +131,15 @@(mu.fn/instrument-ns? *ns*)(eduction (map #(mu.fn/validate-output {} i/FieldMetadataEntry %)))))))-(defn- describe-fks-using-describe-table-fks- "Replaces [[metabase.driver/describe-fks]] for drivers that haven't implemented it. Uses [[driver/describe-table-fks]]- which is deprecated."- [driver database & {:keys [schema-names table-names]}]- (let [tables (sync-util/reducible-sync-tables database :schema-names schema-names :table-names table-names)]- (eduction- (mapcat (fn [table]- #_{:clj-kondo/ignore [:deprecated-var]}- (for [x (driver/describe-table-fks driver database table)]- {:fk-table-name (:name table)- :fk-table-schema (:schema table)- :fk-column-name (:fk-column-name x)- :pk-table-name (:name (:dest-table x))- :pk-table-schema (:schema (:dest-table x))- :pk-column-name (:dest-column-name x)})))- tables)))-(mu/defn fk-metadata"Effectively a wrapper for [[metabase.driver/describe-fks]] that also validates the output against the schema.- If the driver doesn't support [[metabase.driver/describe-fks]] it uses [[driver/describe-table-fks]] instead.- This will be deprecated inIn workspace mode, expands `:schema-names` to include workspace-isolation schemas sothe warehouse driver finds FKs on the physical tables that back canonical Tables, thenback-translates workspace-side identifiers in the result so the rows match canonicalTable rows in app-db."- [database :- i/DatabaseInstance & {:as args}]+ [database :- i/DatabaseInstance+ & {:as args} :- ::driver/describe-fks.options](log-if-error "fk-metadata"(let [driver (driver.u/database->driver database)db-id (:id database)@@ -164,12 +147,7 @@(:schema-names args)(update :schema-names ws.table-remapping/expand-schema-names-with-workspace db-id))](when (driver.u/supports? driver :metadata/key-constraints database)- (let [describe-fks-fn (if (driver.u/supports? driver :describe-fks database)- driver/describe-fks- ;; In version 52 we'll remove [[driver/describe-table-fks]]- ;; and we'll just use [[driver/describe-fks]] here- describe-fks-using-describe-table-fks)- ;; Workspace cross-DB swaps (today: MySQL whose iso table lives in a+ (let [ ;; Workspace cross-DB swaps (today: MySQL whose iso table lives in a;; *different* bound database than the canonical) need describe-fks to;; run with the JDBC connection pointed at the iso DB. Loop per iso-DB;; via the workspace hook and concatenate row results. OSS fallback@@ -177,7 +155,9 @@row-batches (ws.table-remapping/call-with-fk-probe-iso-dbsdb-id(fn []- (vec (describe-fks-fn driver database expanded-args))))+ (into [] (driver/describe-fks driver+ (lib-be/instance->metadata database :metadata/database)+ expanded-args))))raw-rows (vec (mapcat identity row-batches))rewritten-rows (ws.table-remapping/rewrite-fk-result-canonical raw-rows db-id)](cond->> rewritten-rowsdiff --git a/src/metabase/sync/interface.clj b/src/metabase/sync/interface.cljindex ffbb748001a..da83af4ce4e 100644--- a/src/metabase/sync/interface.clj+++ b/src/metabase/sync/interface.clj@@ -116,12 +116,12 @@(mr/def ::FKMetadataEntry[:map- [:fk-table-name ::lib.schema.common/non-blank-string]- [:fk-table-schema [:maybe ::lib.schema.common/non-blank-string]]- [:fk-column-name ::lib.schema.common/non-blank-string]- [:pk-table-name ::lib.schema.common/non-blank-string]- [:pk-table-schema [:maybe ::lib.schema.common/non-blank-string]]- [:pk-column-name ::lib.schema.common/non-blank-string]])+ [:fk-table-name ::lib.schema.common/non-blank-string]+ [:fk-table-schema [:maybe ::lib.schema.common/non-blank-string]]+ [:fk-column-name ::lib.schema.common/non-blank-string]+ [:pk-table-name ::lib.schema.common/non-blank-string]+ [:pk-table-schema [:maybe ::lib.schema.common/non-blank-string]]+ [:pk-column-name ::lib.schema.common/non-blank-string]])(def FKMetadataEntry"Schema for an entry in the expected output of [[metabase.driver/describe-fks]]."diff --git a/src/metabase/sync/sync_metadata/fks.clj b/src/metabase/sync/sync_metadata/fks.cljindex 14f937fb402..6360d638f66 100644--- a/src/metabase/sync/sync_metadata/fks.clj+++ b/src/metabase/sync/sync_metadata/fks.clj@@ -118,11 +118,10 @@(mu/defn sync-fks!"Sync the foreign keys in a `database`. This sets appropriate values for relevant Fields in the Metabase application- DB based on values returned by [[metabase.driver/describe-table-fks]].+ DB based on values returned by [[metabase.driver/describe-fks]].- If the driver supports the `:describe-fks` feature, [[metabase.driver/describe-fks]] is used to fetch the FK metadata.-- This function also sets all the tables that should be synced to have `initial-sync-status=complete` once the sync is done."+ This function also sets all the tables that should be synced to have `initial-sync-status=complete` once the sync is+ done."[database :- i/DatabaseInstance](u/prog1 (sync-util/with-error-handling (format "Error syncing FKs for %s" (sync-util/name-for-logging database))(let [driver (driver.u/database->driver database)diff --git a/src/metabase/sync/util.clj b/src/metabase/sync/util.cljindex 1000dc9910f..df2560f393e 100644--- a/src/metabase/sync/util.clj+++ b/src/metabase/sync/util.clj@@ -10,6 +10,7 @@[metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.events.core :as events]+ [metabase.lib.schema.id :as lib.schema.id][metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.query-processor.interface :as qp.i]@@ -458,15 +459,23 @@(into [:and] (for [[k v] sync-tables-kv-args][:= k v])))-(defn reducible-sync-tables- "Returns a reducible of all the Tables that should go through the sync processes for `database-or-id`."- [database-or-id & {:keys [schema-names table-names]}]+(mu/defn reducible-sync-tables+ "Returns a reducible of all the Tables that should go through the sync processes for `database-or-id`.++ Returns tables ordered by `[schema name]` so results match the order expected by [[metabase.driver/describe-fks]]."+ [database-or-id :- [:or+ ::lib.schema.id/database+ [:map+ [:id ::lib.schema.id/database]]]+ & {:keys [schema-names table-names]} :- ::driver/describe-fks.options](eduction (map t2.realize/realize)(t2/reducible-select :model/Table:db_id (u/the-id database-or-id){:where [:and sync-tables-clause(when (seq schema-names) [:in :schema schema-names])- (when (seq table-names) [:in :name table-names])]})))+ (when (seq table-names) [:in :name table-names])]+ :order-by [[:schema :asc]+ [:name :asc]]})))(defn sync-tables-count"The count of all tables that should be synced for `database-or-id`."diff --git a/test/metabase/driver/sql_jdbc/sync/describe_table_test.clj b/test/metabase/driver/sql_jdbc/sync/describe_table_test.cljindex 12ce3db1ef5..9fe7a7b2616 100644--- a/test/metabase/driver/sql_jdbc/sync/describe_table_test.clj+++ b/test/metabase/driver/sql_jdbc/sync/describe_table_test.clj@@ -16,6 +16,7 @@[metabase.driver.sql-jdbc.sync.describe-table :as sql-jdbc.describe-table][metabase.driver.sql-jdbc.sync.interface :as sql-jdbc.sync.interface][metabase.driver.util :as driver.u]+ [metabase.lib.metadata :as lib.metadata][metabase.query-processor.timeseries-test.util :as tqpt][metabase.sync.core :as sync][metabase.test :as mt]@@ -49,7 +50,7 @@(mt/test-driver :h2(assert (uses-default-describe-table? :h2)"Make sure H2 uses the default `describe-table` implementation")- (is (= {:name "VENUES",+ (is (= {:name "VENUES":fields#{{:name "ID":database-type "BIGINT"@@ -183,7 +184,7 @@[_driver _feature _database]true))-(deftest describe-fields-shared-attributes-test+(deftest ^:parallel describe-fields-shared-attributes-test(testing "common metadata attributes"(mt/test-drivers (mt/normal-drivers-with-feature :actions)(is (=?@@ -199,7 +200,10 @@:database-required:database-is-auto-increment(comp boolean :pk?))- (describe-fields-for-table (mt/db) (t2/select-one :model/Table :id (mt/id :venues))))))))+ (describe-fields-for-table (mt/db) (t2/select-one :model/Table :id (mt/id :venues))))))))))++(deftest ^:parallel describe-fields-shared-attributes-test-2+ (testing "common metadata attributes"(mt/test-drivers (mt/normal-drivers-without-feature :actions)(is (=?[[0 (driver/database-supports? driver/*driver* ::describe-pks (mt/db))]@@ -318,12 +322,12 @@(is (= types (#'sql-jdbc.describe-table/json-map->types row)))))(testing "JSON json-map->types handles bigint that comes in and gets interpreted as Java bigint OK (#22732)"(let [int-row {:zlob (json/encode {"blob" (java.math.BigInteger. "123124124312134235234235345344324352")})}]- (is (= #{{:name "zlob → blob",- :database-type "decimal",- :base-type :type/BigInteger,- :database-position 0,+ (is (= #{{:name "zlob → blob"+ :database-type "decimal"+ :base-type :type/BigInteger+ :database-position 0:json-unfolding false- :visibility-type :normal,+ :visibility-type :normal:nfc-path [:zlob "blob"]}}(-> int-row(#'sql-jdbc.describe-table/json-map->types)@@ -340,68 +344,68 @@(filter #(= (:name %) "json_bit"))first((juxt :base-type :semantic-type)))))- (is (= #{{:name "json_bit → 1234123412314",- :database-type "timestamp",- :base-type :type/DateTime,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ (is (= #{{:name "json_bit → 1234123412314"+ :database-type "timestamp"+ :base-type :type/DateTime+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "1234123412314"]}- {:name "json_bit → boop",- :database-type "timestamp",- :base-type :type/DateTime,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → boop"+ :database-type "timestamp"+ :base-type :type/DateTime+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "boop"]}- {:name "json_bit → genres",- :database-type "text",- :base-type :type/Array,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → genres"+ :database-type "text"+ :base-type :type/Array+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "genres"]}- {:name "json_bit → 1234",- :database-type "decimal",- :base-type :type/Integer,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → 1234"+ :database-type "decimal"+ :base-type :type/Integer+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "1234"]}- {:name "json_bit → doop",- :database-type "text",- :base-type :type/Text,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → doop"+ :database-type "text"+ :base-type :type/Text+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "doop"]}- {:name "json_bit → noop",- :database-type "timestamp",- :base-type :type/DateTime,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → noop"+ :database-type "timestamp"+ :base-type :type/DateTime+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "noop"]}- {:name "json_bit → zoop",- :database-type "timestamp",- :base-type :type/DateTime,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → zoop"+ :database-type "timestamp"+ :base-type :type/DateTime+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "zoop"]}- {:name "json_bit → published",- :database-type "text",- :base-type :type/Text,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → published"+ :database-type "text"+ :base-type :type/Text+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "published"]}- {:name "json_bit → title",- :database-type "text",- :base-type :type/Text,- :database-position 0,- :json-unfolding false,- :visibility-type :normal,+ {:name "json_bit → title"+ :database-type "text"+ :base-type :type/Text+ :database-position 0+ :json-unfolding false+ :visibility-type :normal:nfc-path [:json_bit "title"]}}(sql-jdbc.sync/describe-nested-field-columnsdriver/*driver*@@ -477,7 +481,7 @@(mt/defdataset long-json[["long_json_table"- ;; `short_json` and `long_json` have the same schema,+ ;; `short_json` and `long_json` have the same schema;; in the first row, both have an "a" key.;; in the second row, both have a "b" key, except `long_json` has a longer value.[{:field-name "short_json", :base-type :type/JSON}@@ -851,3 +855,81 @@(log/error e "Exception occurred."))(finally(tx/drop-view! driver/*driver* (mt/db) view-name {:materialized? materialized?})))))))++(deftest ^:parallel describe-fks-with-jdbc-metadata-test+ (testing "Make sure the fallback default JDBC-metadata-based implementation of `describe-fks` works correctly"+ (are [options] (= #{{:fk-table-schema "PUBLIC"+ :fk-table-name "ORDERS"+ :fk-column-name "USER_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "PEOPLE"+ :pk-column-name "ID"}+ {:fk-table-schema "PUBLIC"+ :fk-table-name "CHECKINS"+ :fk-column-name "VENUE_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "VENUES"+ :pk-column-name "ID"}+ {:fk-table-schema "PUBLIC"+ :fk-table-name "ORDERS"+ :fk-column-name "PRODUCT_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "PRODUCTS"+ :pk-column-name "ID"}+ {:fk-table-schema "PUBLIC"+ :fk-table-name "VENUES"+ :fk-column-name "CATEGORY_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "CATEGORIES"+ :pk-column-name "ID"}+ {:fk-table-schema "PUBLIC"+ :fk-table-name "REVIEWS"+ :fk-column-name "PRODUCT_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "PRODUCTS"+ :pk-column-name "ID"}+ {:fk-table-schema "PUBLIC"+ :fk-table-name "CHECKINS"+ :fk-column-name "USER_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "USERS"+ :pk-column-name "ID"}}+ (into+ #{}+ (#'sql-jdbc.describe-table/describe-fks-with-jdbc-metadata+ :h2+ (lib.metadata/database (mt/metadata-provider))+ options)))+ {}+ {:schema-names ["PUBLIC"]}+ {:schema-names ["PUBLIC" "PUBLIC2"]})+ (testing "Filter by schema/table name that does not exist, should return nothing"+ (are [options] (= #{}+ (into+ #{}+ (#'sql-jdbc.describe-table/describe-fks-with-jdbc-metadata+ :h2+ (lib.metadata/database (mt/metadata-provider))+ options)))+ {:schema-names ["PUBLIC2"]}+ {:schema-names ["PUBLIC2"], :table-names ["CHECKINS"]}+ {:table-names ["CHECKINS2"]}))+ (testing "Filter by table name"+ (is (= #{{:fk-table-schema "PUBLIC"+ :fk-table-name "CHECKINS"+ :fk-column-name "VENUE_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "VENUES"+ :pk-column-name "ID"}+ {:fk-table-schema "PUBLIC"+ :fk-table-name "CHECKINS"+ :fk-column-name "USER_ID"+ :pk-table-schema "PUBLIC"+ :pk-table-name "USERS"+ :pk-column-name "ID"}}+ (into+ #{}+ (#'sql-jdbc.describe-table/describe-fks-with-jdbc-metadata+ :h2+ (lib.metadata/database (mt/metadata-provider))+ {:table-names ["CHECKINS"]})))))))diff --git a/test/metabase/driver_test.clj b/test/metabase/driver_test.cljindex d43b7380568..1cf65866b22 100644--- a/test/metabase/driver_test.clj+++ b/test/metabase/driver_test.clj@@ -10,6 +10,7 @@[metabase.driver.impl :as driver.impl][metabase.driver.settings :as driver.settings][metabase.driver.util :as driver.u]+ [metabase.lib.metadata :as lib.metadata][metabase.query-processor.compile :as qp.compile][metabase.query-processor.test :as qp][metabase.sync.task.sync-databases :as task.sync-databases]@@ -44,7 +45,7 @@(is (= @classloader/shared-context-classloader(.getContextClassLoader (Thread/currentThread))))))-(deftest available?-test+(deftest ^:parallel available?-test(mt/with-dynamic-fn-redefs [driver.impl/concrete? (constantly true)](is (driver/available? ::test-driver))(is (driver/available? "metabase.driver-test/test-driver")@@ -76,13 +77,13 @@(let [props (driver/connection-properties d)props-by-name (driver.u/collect-all-props-by-name props)total-props (count-named-props props)]- ;; If there are duplicate names, some will be overwritten in the map,+ ;; If there are duplicate names, some will be overwritten in the map;; so the map size will be less than the total count of named properties(is (= total-props (count props-by-name))(format "Property(s) with duplicate name: %d total properties but only %d unique names in %s"total-props (count props-by-name) d)))))))-(deftest supports-schemas-matches-describe-database-test+(deftest ^:parallel supports-schemas-matches-describe-database-test(mt/test-drivers (mt/normal-drivers)(if (driver/database-supports? driver/*driver* :schemas (mt/db))(testing "`describe-database` should return schemas with tables if the database supports schemas"@@ -180,7 +181,7 @@;; clean up the database(t2/delete! :model/Database (u/the-id db))))))))-(deftest supports-table-privileges-matches-implementations-test+(deftest ^:parallel supports-table-privileges-matches-implementations-test(mt/test-drivers (mt/normal-drivers-with-feature :table-privileges)(is (some? (driver/current-user-table-privileges driver/*driver* (mt/db))))))@@ -349,7 +350,8 @@[a b c] (->> ["a" "b" "c"](map #(ddl.i/format-name driver/*driver* %))(map (u/index-by :name fields)))]- ;; this test only properties of the field-meta returned by the driver, not whether it syncs, for that see sync_metadata/fields_test.clj+ ;; this test only properties of the field-meta returned by the driver, not whether it syncs, for that see+ ;; sync_metadata/fields_test.clj(if (driver/database-supports? driver/*driver* :describe-is-generated (mt/db))(testing ":database-is-generated should be provided"(is (= [false true false] (mapv :database-is-generated [a b c]))))@@ -357,33 +359,44 @@(is (= [nil nil nil] (mapv :database-is-generated [a b c])))))))))(deftest ^:parallel describe-table-fks-test- (testing "`describe-table-fks` should work for drivers that do not support `describe-fks`"- (mt/test-drivers (set/difference (mt/normal-drivers-with-feature :metadata/key-constraints)- (mt/normal-drivers-with-feature :describe-fks))- (let [orders (t2/select-one :model/Table (mt/id :orders))- products (t2/select-one :model/Table (mt/id :products))- people (t2/select-one :model/Table (mt/id :people))+ (testing "`describe-fks` should be usable in the way we used to use the old `describe-table-fks` method"+ (mt/test-drivers (mt/normal-drivers-with-feature :metadata/key-constraints)+ (let [orders (t2/select-one [:model/Table :name :schema] (mt/id :orders))+ products (t2/select-one [:model/Table :name :schema] (mt/id :products))+ people (t2/select-one [:model/Table :name :schema] (mt/id :people))fmt (partial ddl.i/format-name driver/*driver*)]- (is (= #{{:fk-column-name (fmt "user_id")- :dest-table (select-keys people [:name :schema])- :dest-column-name (fmt "id")}- {:fk-column-name (fmt "product_id")- :dest-table (select-keys products [:name :schema])- :dest-column-name (fmt "id")}}- #_{:clj-kondo/ignore [:deprecated-var]}- (driver/describe-table-fks driver/*driver* (mt/db) orders)))))))+ (is (= #{{:fk-table-schema (:schema orders)+ :fk-table-name (:name orders)+ :fk-column-name (fmt "user_id")+ :pk-table-schema (:schema people)+ :pk-table-name (:name people)+ :pk-column-name (fmt "id")}+ {:fk-table-schema (:schema orders)+ :fk-table-name (:name orders)+ :fk-column-name (fmt "product_id")+ :pk-table-schema (:schema products)+ :pk-table-name (:name products)+ :pk-column-name (fmt "id")}}+ (into #{}+ (driver/describe-fks+ driver/*driver*+ (lib.metadata/database (mt/metadata-provider))+ {:schema-names (when (:schema orders)+ #{(:schema orders)})+ :table-names #{(:name orders)}}))))))))(deftest ^:parallel describe-fks-test- (testing "`describe-fks` works for drivers that support `describe-fks`"- (mt/test-drivers (mt/normal-drivers-with-feature :metadata/key-constraints :describe-fks)- (let [fmt (partial ddl.i/format-name driver/*driver*)+ (testing `driver/describe-fks+ (mt/test-drivers (mt/normal-drivers-with-feature :metadata/key-constraints)+ (let [db (lib.metadata/database (mt/metadata-provider))+ fmt (partial ddl.i/format-name driver/*driver*)orders (t2/select-one :model/Table (mt/id :orders))products (t2/select-one :model/Table (mt/id :products))people (t2/select-one :model/Table (mt/id :people))- entire-db-fks (driver/describe-fks driver/*driver* (mt/db))- schema-db-fks (driver/describe-fks driver/*driver* (mt/db)+ entire-db-fks (driver/describe-fks driver/*driver* db)+ schema-db-fks (driver/describe-fks driver/*driver* db:schema-names (when (:schema orders) [(:schema orders)]))- table-db-fks (driver/describe-fks driver/*driver* (mt/db)+ table-db-fks (driver/describe-fks driver/*driver* db:schema-names (when (:schema orders) [(:schema orders)]):table-names [(:name orders)])](doseq [[description orders-fks]@@ -421,7 +434,7 @@;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; TODO: Uncomment when https://github.com/metabase/metabase/pull/60263 is merged-#_(deftest data-editing-requires-describe-features-test+#_(deftest ^:parallel data-editing-requires-describe-features-test(testing "Drivers supporting :actions/data-editing must support relevant describe-X features"(mt/test-drivers (mt/normal-drivers-with-feature :actions/data-editing)(testing "describe-default-expr feature"@@ -466,7 +479,7 @@(driver/register! ::mock-no-deps-driver, :abstract? true)-(deftest deps-ignores-invalid-drivers-test+(deftest ^:parallel deps-ignores-invalid-drivers-test(is (= #{}(driver/native-query-deps ::mock-no-deps-driver nil nil))))@@ -476,6 +489,8 @@[_driver _feature _database]true)-(deftest deps-flags-when-supported-driver-is-not-covered-test- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Database that supports :dependencies/native does not provide an implementation of driver/native-query-deps"- (driver/native-query-deps ::mock-deps-driver nil nil))))+(deftest ^:parallel deps-flags-when-supported-driver-is-not-covered-test+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Database that supports :dependencies/native does not provide an implementation of driver/native-query-deps"+ (driver/native-query-deps ::mock-deps-driver nil nil))))diff --git a/test/metabase/sync/sync_test.clj b/test/metabase/sync/sync_test.cljindex 8d8c1b54736..6226d2354f8 100644--- a/test/metabase/sync/sync_test.clj+++ b/test/metabase/sync/sync_test.clj@@ -7,12 +7,14 @@(:require[clojure.test :refer :all][metabase.driver :as driver]+ [metabase.lib.schema.metadata :as lib.schema.metadata][metabase.sync.sync :as sync][metabase.sync.util :as sync-util][metabase.test :as mt][metabase.test.mock.util :as mock.util][metabase.test.util :as tu][metabase.util :as u]+ [metabase.util.malli :as mu][metabase.warehouse-schema.models.field-values :as field-values][toucan2.core :as t2]))@@ -83,14 +85,18 @@[_ _ table](get (sync-test-tables) (:name table)))-#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod driver/describe-table-fks ::sync-test- [_ _ table]- (set (when (= "movie" (:name table))- #{{:fk-column-name "studio"- :dest-table {:name "studio"- :schema (when *supports-schemas?* "public")}- :dest-column-name "studio"}})))+(mu/defmethod driver/describe-fks ::sync-test :- ::driver/describe-fks.result+ [_driver :- :keyword+ _database :- ::lib.schema.metadata/database+ & {:keys [table-names], :as _options} :- ::driver/describe-fks.options]+ (when (or (empty? table-names)+ (contains? (set table-names) "movie"))+ [{:fk-table-schema (when *supports-schemas?* "default")+ :fk-table-name "movie"+ :fk-column-name "studio"+ :pk-table-schema (when *supports-schemas?* "public")+ :pk-table-name "studio"+ :pk-column-name "studio"}]))(defmethod driver/database-supports? [::sync-test :metadata/key-constraints][_driver _feature _db]diff --git a/test/metabase/test/mock/moviedb.clj b/test/metabase/test/mock/moviedb.cljindex 97b3c394e0c..16a28758667 100644--- a/test/metabase/test/mock/moviedb.clj+++ b/test/metabase/test/mock/moviedb.clj@@ -1,7 +1,9 @@(ns metabase.test.mock.moviedb"A simple relational schema based mocked for testing. 4 tables w/ some FKs."(:require- [metabase.driver :as driver]))+ [metabase.driver :as driver]+ [metabase.lib.schema.metadata :as lib.schema.metadata]+ [metabase.util.malli :as mu]));; TODO - this whole fake driver is used in exactly one test. Can definitely remove a lot of the stuff here since it's;; not used.@@ -84,11 +86,20 @@(update :fields (partial map-indexed (fn [idx field](assoc field :database-position idx))))))-#_{:clj-kondo/ignore [:deprecated-var]}-(defmethod driver/describe-table-fks ::moviedb [_ _ table]- (-> (get moviedb-tables (:name table))- :fks- set))+(mu/defmethod driver/describe-fks ::moviedb :- ::driver/describe-fks.result+ [_driver :- :keyword+ _database :- ::lib.schema.metadata/database+ & {:keys [table-names], :as _options} :- ::driver/describe-fks.options]+ (for [[table-name table] moviedb-tables+ :when (or (empty? table-names)+ (contains? (set table-names) table-name))+ fk (:fks table)]+ {:fk-table-name table-name+ :fk-table-schema nil+ :fk-column-name (:fk-column-name fk)+ :pk-table-name (get-in fk [:dest-table :name])+ :pk-table-schema (get-in fk [:dest-table :schema])+ :pk-column-name (:dest-column-name fk)}))(defmethod driver/table-rows-seq ::moviedb [_ _ table](when (= (:name table) "_metabase_metadata")diff --git a/test/metabase/test/util/namespace.clj b/test/metabase/test/util/namespace.cljdeleted file mode 100644index 2c92ff466ed..00000000000--- a/test/metabase/test/util/namespace.clj+++ /dev/null@@ -1,16 +0,0 @@-(ns metabase.test.util.namespace- "Test utilities for namespace operations."- (:require- [clojure.java.classpath :as classpath]- [clojure.string :as str]- [clojure.tools.namespace.find :as ns.find]))--(defonce ^{:doc "Vector of symbols of all Metabase namespaces, excluding test namespaces. This is intended- for use by various test routines that need to load related namespaces.-- This was moved from metabase.util.jvm for testing purposes only."}- ^:deprecated metabase-namespace-symbols- (vec (sort (for [ns-symb (ns.find/find-namespaces (classpath/system-classpath))- :when (and (str/starts-with? ns-symb "metabase")- (not (str/includes? ns-symb "test")))]- ns-symb))))