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
Improve memory usage of `sync-tables-and-database!` (#76330)
Alexander Polyankin9315930aa71e
diff --git a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.cljindex c84c55c19d2..536b47a1778 100644--- a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj+++ b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj@@ -808,7 +808,7 @@driver/*driver*(t2/select-one :model/Database (mt/id))):tables- set)+ (into #{}))default-table-set (tables-set)do-with-resolved-connection (mt/original-fn #'sql-jdbc.execute/do-with-resolved-connection)](mt/with-dynamic-fn-redefs [sql-jdbc.execute/do-with-resolved-connectiondiff --git a/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.cljindex 3f68f9f7566..bc1b0015159 100644--- a/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.clj+++ b/enterprise/backend/test/metabase_enterprise/workspaces/e2e_test.clj@@ -510,7 +510,7 @@;; that's always null, same as `:model/Table.schema`. Use `tbl-schema`;; (the per-driver translation we already do for synced rows).(testing "describe-database returns only input-schema tables"- (let [{described :tables} (driver/describe-database admin-driver ws-db)+ (let [described (into [] (:tables (driver/describe-database admin-driver ws-db)))iso-tbl-schema (table-row-schema-value admin-driver isolation-schema)](is (some #(and (= tbl-schema (:schema %))(= src-name (:name %)))diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.cljindex 572cf080e8a..9f3bf9bdea1 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj@@ -259,7 +259,7 @@(defmethod driver/describe-database* :bigquery-cloud-sdk[driver database]- {:tables (into #{} (describe-database-tables driver database))})+ {:tables (describe-database-tables driver database)})(defn- database-type->base-type[database-type]diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.cljindex a20f316288b..c9b45e85a66 100644--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj@@ -464,7 +464,7 @@(mt/datasetnative-dataset(let [view-name "category_view"]- (is (contains? (:tables (driver/describe-database :bigquery-cloud-sdk (mt/db)))+ (is (contains? (into #{} (:tables (driver/describe-database :bigquery-cloud-sdk (mt/db)))){:schema (get-test-data-name) :name view-name :database_require_filter false})"`describe-database` should see the view")(is (= [{:name "id", :database-type "INTEGER" :base-type :type/Integer :database-position 0 :database-partitioned false :table-name view-name :table-schema (get-test-data-name)}@@ -541,7 +541,7 @@(mt/datasetnested-records(let [database (driver/describe-database :bigquery-cloud-sdk (mt/db))- tables (sort-by :name (:tables database))]+ tables (sort-by :name (into [] (:tables database)))](is (=? [{:name "records"} {:name "records_o"}] tables))(is (=? [{:name "id"}{:name "name"}@@ -934,7 +934,7 @@decimal-valbignumeric-valbigdecimal-val)- (is (contains? (:tables (driver/describe-database :bigquery-cloud-sdk (mt/db)))+ (is (contains? (into #{} (:tables (driver/describe-database :bigquery-cloud-sdk (mt/db)))){:schema (get-test-data-name) :name tbl-nm :database_require_filter false})"`describe-database` should see the table")(is (= [{:base-type :type/Decimaldiff --git a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_introspection_test.clj b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_introspection_test.cljindex 5c3fedec0eb..6efb058fe1b 100644--- a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_introspection_test.clj+++ b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_introspection_test.clj@@ -513,17 +513,18 @@:clickhouse :db{:database-name "default"}){:db-filters-type "all"})}]- (let [describe-result (driver/describe-database :clickhouse db)]+ (let [describe-result (driver/describe-database :clickhouse db)+ tables (into #{} (:tables describe-result))];; check the existence of at least some test tables here(doseq [table test-tables]- (is (contains? (:tables describe-result) table)))+ (is (contains? tables table)));; should not contain any ClickHouse system tables(is (not (some #(= (:schema %) "system")- (:tables describe-result))))+ tables)))(is (not (some #(= (:schema %) "information_schema")- (:tables describe-result))))+ tables)))(is (not (some #(= (:schema %) "INFORMATION_SCHEMA")- (:tables describe-result)))))))))+ tables))))))))(deftest ^:parallel clickhouse-describe-database-multiple(mt/test-driver :clickhousediff --git a/modules/drivers/databricks/src/metabase/driver/databricks.clj b/modules/drivers/databricks/src/metabase/driver/databricks.cljindex c892d4c0311..2c88ba0bc18 100644--- a/modules/drivers/databricks/src/metabase/driver/databricks.clj+++ b/modules/drivers/databricks/src/metabase/driver/databricks.clj@@ -133,20 +133,22 @@(defmethod driver/describe-database* :databricks[driver database]- (try- {:tables- (let [[inclusion-patterns- exclusion-patterns] (driver.s/db-details->schema-filter-patterns database)- included? (fn [schema]- (sql-jdbc.describe-database/include-schema-logging-exclusion inclusion-patterns exclusion-patterns schema))]- (into- #{}- (filter (comp included? :schema))- (sql-jdbc.execute/reducible-query database (get-tables-sql driver (driver.conn/effective-details database)))))}- (catch Throwable e- (throw (ex-info (format "Error in %s describe-database: %s" driver (ex-message e))- {}- e)))))+ {:tables+ (reify clojure.lang.IReduceInit+ (reduce [_this rf init]+ (try+ (let [[inclusion-patterns+ exclusion-patterns] (driver.s/db-details->schema-filter-patterns database)+ included? (fn [schema]+ (sql-jdbc.describe-database/include-schema-logging-exclusion inclusion-patterns exclusion-patterns schema))]+ (reduce rf init+ (eduction+ (filter (comp included? :schema))+ (sql-jdbc.execute/reducible-query database (get-tables-sql driver (driver.conn/effective-details database))))))+ (catch Throwable e+ (throw (ex-info (format "Error in %s describe-database: %s" driver (ex-message e))+ {}+ e))))))})(defn- schema-names-filter [schema-names multi-level-schema catalog-column schema-column](when schema-namesdiff --git a/modules/drivers/databricks/test/metabase/driver/databricks_test.clj b/modules/drivers/databricks/test/metabase/driver/databricks_test.cljindex cb5b1772f55..f1455e53ac3 100644--- a/modules/drivers/databricks/test/metabase/driver/databricks_test.clj+++ b/modules/drivers/databricks/test/metabase/driver/databricks_test.clj@@ -32,20 +32,21 @@(mt/test-driver:databricks(testing "`driver/describe-database` implementation returns expected results for inclusion of test-data schema."- (is (= {:tables- #{{:name "venues", :schema (maybe-qualify-schema "test-data"), :description nil}- {:name "checkins", :schema (maybe-qualify-schema "test-data"), :description nil}- {:name "users", :schema (maybe-qualify-schema "test-data"), :description nil}- {:name "people", :schema (maybe-qualify-schema "test-data"), :description nil}- {:name "categories", :schema (maybe-qualify-schema "test-data"), :description nil}- {:name "reviews", :schema (maybe-qualify-schema "test-data"), :description nil}- {:name "orders", :schema (maybe-qualify-schema "test-data"), :description nil}- {:name "products", :schema (maybe-qualify-schema "test-data"), :description nil}}}- (driver/describe-database :databricks (mt/db)))))+ (is (= #{{:name "venues", :schema (maybe-qualify-schema "test-data"), :description nil}+ {:name "checkins", :schema (maybe-qualify-schema "test-data"), :description nil}+ {:name "users", :schema (maybe-qualify-schema "test-data"), :description nil}+ {:name "people", :schema (maybe-qualify-schema "test-data"), :description nil}+ {:name "categories", :schema (maybe-qualify-schema "test-data"), :description nil}+ {:name "reviews", :schema (maybe-qualify-schema "test-data"), :description nil}+ {:name "orders", :schema (maybe-qualify-schema "test-data"), :description nil}+ {:name "products", :schema (maybe-qualify-schema "test-data"), :description nil}}+ (into #{} (:tables (driver/describe-database :databricks (mt/db)))))))(testing "`driver/describe-database` returns expected results for `all` schema filters."- (let [actual-tables (driver/describe-database :databricks (-> (mt/db)- (update :details dissoc :schema-filters-patterns)- (update :details assoc :schema-filters-type "all")))]+ (let [actual-tables (update (driver/describe-database :databricks (-> (mt/db)+ (update :details dissoc :schema-filters-patterns)+ (update :details assoc :schema-filters-type "all")))+ ;; `:tables` is a reducible (streamed); realize it for the set ops below+ :tables #(into #{} %))](testing "tables from multiple schemas were found"(are [name schema] (contains? (:tables actual-tables){:name name, :schema schema, :description nil})@@ -56,9 +57,11 @@(testing "information_schema is excluded"(is (empty? (filter #(str/includes? "information_schema" (:schema %)) (:tables actual-tables)))))))(testing "`driver/describe-database` returns expected results for `exclusion` schema filters."- (let [actual-tables (driver/describe-database :databricks (update (mt/db) :details assoc- :schema-filters-patterns (maybe-qualify-schema "test-data")- :schema-filters-type "exclusion"))]+ (let [actual-tables (update (driver/describe-database :databricks (update (mt/db) :details assoc+ :schema-filters-patterns (maybe-qualify-schema "test-data")+ :schema-filters-type "exclusion"))+ ;; `:tables` is a reducible (streamed); realize it for the set ops below+ :tables #(into #{} %))](testing "tables from multiple schemas were found"(is (not (contains? (set (map :schema (:tables actual-tables))) (maybe-qualify-schema "test-data"))))(is (contains? (:tables actual-tables) {:name "airport", :schema (maybe-qualify-schema "airports"), :description nil}))diff --git a/modules/drivers/druid-jdbc/test/metabase/driver/druid_jdbc_test.clj b/modules/drivers/druid-jdbc/test/metabase/driver/druid_jdbc_test.cljindex 333aef5d233..9efb6cd0535 100644--- a/modules/drivers/druid-jdbc/test/metabase/driver/druid_jdbc_test.clj+++ b/modules/drivers/druid-jdbc/test/metabase/driver/druid_jdbc_test.clj@@ -31,10 +31,10 @@:druid-jdbc(tqpt/with-flattened-dbdef(testing "describe-database"- (is (= {:tables #{{:schema "druid", :name "checkins" :description nil, :is_writable nil}- {:schema "druid", :name "json" :description nil, :is_writable nil}- {:schema "druid", :name "big_json" :description nil, :is_writable nil}}}- (driver/describe-database :druid-jdbc (mt/db)))))+ (is (= #{{:schema "druid", :name "checkins" :description nil, :is_writable nil}+ {:schema "druid", :name "json" :description nil, :is_writable nil}+ {:schema "druid", :name "big_json" :description nil, :is_writable nil}}+ (into #{} (:tables (driver/describe-database :druid-jdbc (mt/db)))))))(testing "describe-table"(is (=? {:schema "druid":name "checkins"diff --git a/modules/drivers/presto-jdbc/test/metabase/driver/presto_jdbc_test.clj b/modules/drivers/presto-jdbc/test/metabase/driver/presto_jdbc_test.cljindex 41306332993..55fe9217c08 100644--- a/modules/drivers/presto-jdbc/test/metabase/driver/presto_jdbc_test.clj+++ b/modules/drivers/presto-jdbc/test/metabase/driver/presto_jdbc_test.clj@@ -33,11 +33,11 @@{:name "test_data_users" :schema "default"}{:name "test_data_venues" :schema "default"}}}(-> (driver/describe-database :presto-jdbc (mt/db))- (update :tables (comp set (partial filter (comp #{"test_data_categories"- "test_data_venues"- "test_data_checkins"- "test_data_users"}- :name)))))))))+ (update :tables #(into #{} (filter (comp #{"test_data_categories"+ "test_data_venues"+ "test_data_checkins"+ "test_data_users"}+ :name)) %)))))))(deftest ^:parallel describe-table-test(mt/test-driver :presto-jdbcdiff --git a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj b/modules/drivers/redshift/test/metabase/driver/redshift_test.cljindex 793540b9583..10465c3e7f7 100644--- a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj+++ b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj@@ -328,7 +328,7 @@:model/Database db {:engine :redshift, :details details}](binding [redshift.tx/*override-describe-database-to-filter-by-db-name?* false](persist-models!)- (let [synced-schemas (set (map :schema (:tables (driver/describe-database :redshift db))))]+ (let [synced-schemas (into #{} (map :schema) (:tables (driver/describe-database :redshift db)))](testing "sense check: there are results matching some schemas in the schema-filters-patterns"(is (some #(re-matches #"20(.*)" %) synced-schemas)))(let [all-schemas (map :table_schema (jdbc/query (sql-jdbc.conn/db->pooled-connection-spec (mt/db))@@ -358,7 +358,7 @@qual-mview-nm)(binding [redshift.tx/*override-describe-database-to-filter-by-db-name?* false](u/auto-retry 3- (let [table-names (set (map :name (:tables (driver/describe-database :redshift database))))]+ (let [table-names (into #{} (map :name) (:tables (driver/describe-database :redshift database)))](when-not (contains? table-names mview-nm)(Thread/sleep 1000)(throw (ex-info "Materialized view not yet visible in describe-database results"diff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.cljindex 54c92b1b2fa..5502f6f5576 100644--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj@@ -316,10 +316,10 @@{:name "airport", :schema "PUBLIC", :description nil}}](testing "should work with normal details"(is (= expected-tables- (:tables (driver/describe-database :snowflake (mt/db))))))+ (into #{} (:tables (driver/describe-database :snowflake (mt/db)))))))(testing "should accept either `:db` or `:dbname` in the details, working around a bug with the original impl"(is (= expected-tables- (:tables (driver/describe-database :snowflake (update (mt/db) :details set/rename-keys {:db :dbname}))))))+ (into #{} (:tables (driver/describe-database :snowflake (update (mt/db) :details set/rename-keys {:db :dbname})))))))(testing "should throw an Exception if details have neither `:db` nor `:dbname`"(is (thrown? Exception(driver/describe-database :snowflake (update (mt/db) :details set/rename-keys {:db :xyz})))))diff --git a/modules/drivers/starburst/test/metabase/driver/starburst_test.clj b/modules/drivers/starburst/test/metabase/driver/starburst_test.cljindex f0f33be72c2..1d57c4b20b1 100644--- a/modules/drivers/starburst/test/metabase/driver/starburst_test.clj+++ b/modules/drivers/starburst/test/metabase/driver/starburst_test.clj@@ -82,11 +82,11 @@{:name "checkins" :schema "default"}{:name "users" :schema "default"}}}(-> (driver/describe-database :starburst (mt/db))- (update :tables (comp set (partial filter (comp #{"categories"- "venues"- "checkins"- "users"}- :name)))))))))+ (update :tables #(into #{} (filter (comp #{"categories"+ "venues"+ "checkins"+ "users"}+ :name)) %)))))))(deftest describe-table-test(mt/test-driver :starburstdiff --git a/modules/drivers/vertica/src/metabase/driver/vertica.clj b/modules/drivers/vertica/src/metabase/driver/vertica.cljindex af88135cef7..571d7e48c92 100644--- a/modules/drivers/vertica/src/metabase/driver/vertica.clj+++ b/modules/drivers/vertica/src/metabase/driver/vertica.clj@@ -1,7 +1,6 @@(ns metabase.driver.vertica(:require[clojure.java.jdbc :as jdbc]- [clojure.set :as set][honey.sql :as sql][java-time.api :as t][metabase.driver :as driver]@@ -301,8 +300,10 @@(defmethod driver/describe-database* :vertica[driver database]+ ;; the JDBC default returns `:tables` as a reducible; fold it (and the materialized views) into a+ ;; set rather than `set/union`, which would call `count` on the reducible(-> ((get-method driver/describe-database* :sql-jdbc) driver database)- (update :tables set/union (materialized-views database))))+ (update :tables #(into (materialized-views database) %))))(defmethod driver/db-default-timezone :vertica[_driver _database]diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.cljindex 9199275a70c..48dfe0e2408 100644--- a/src/metabase/driver/postgres.clj+++ b/src/metabase/driver/postgres.clj@@ -316,9 +316,7 @@(defmethod driver/describe-database* :postgres[_driver database]- ;; TODO: we should figure out how to sync tables using transducer, this way we don't have to hold 100k tables in- ;; memory in a set like this- {:tables (into #{} (describe-syncable-tables database))})+ {:tables (describe-syncable-tables database)})(defn- nullable-in"Build a HoneySQL clause that handles nil values in `xs` correctly.diff --git a/src/metabase/driver/sql_jdbc/sync/describe_database.clj b/src/metabase/driver/sql_jdbc/sync/describe_database.cljindex e346c7f0ba4..0851de87653 100644--- a/src/metabase/driver/sql_jdbc/sync/describe_database.clj+++ b/src/metabase/driver/sql_jdbc/sync/describe_database.clj@@ -301,18 +301,26 @@nil))(mu/defn describe-database- "Default implementation of [[metabase.driver/describe-database]] for SQL JDBC drivers. Uses JDBC DatabaseMetaData."+ "Default implementation of [[metabase.driver/describe-database]] for SQL JDBC drivers. Uses JDBC DatabaseMetaData.++ `:tables` is a reducible that opens its own connection when reduced (the same pattern used by+ [[metabase.driver.sql-jdbc.sync.describe-table]]'s `describe-fields`/`describe-fks`), so a large table+ list streams a batch at a time instead of being realized into a set up front. Building the reducible is+ eager -- satisfying [[metabase.driver/do-with-resilient-connection]], which requires an eager `f` -- while+ the connection is opened lazily at reduction time (with a fresh connection, outside the resilient scope)."[driver :- :keyworddb-or-id-or-spec :- [:or :int :map]]{:tables- (sql-jdbc.execute/do-with-connection-with-options- driver- db-or-id-or-spec- nil- (fn [^Connection conn]- (let [schema-filter-prop (driver.u/find-schema-filters-prop driver)- database (db-or-id-or-spec->database db-or-id-or-spec)- [inclusion-patterns- exclusion-patterns] (when (some? schema-filter-prop)- (driver.s/db-details->schema-filter-patterns (:name schema-filter-prop) database))]- (into #{} (sql-jdbc.sync.interface/active-tables driver conn inclusion-patterns exclusion-patterns)))))})+ (reify clojure.lang.IReduceInit+ (reduce [_this rf init]+ (sql-jdbc.execute/do-with-connection-with-options+ driver+ db-or-id-or-spec+ nil+ (fn [^Connection conn]+ (let [schema-filter-prop (driver.u/find-schema-filters-prop driver)+ database (db-or-id-or-spec->database db-or-id-or-spec)+ [inclusion-patterns+ exclusion-patterns] (when (some? schema-filter-prop)+ (driver.s/db-details->schema-filter-patterns (:name schema-filter-prop) database))]+ (reduce rf init (sql-jdbc.sync.interface/active-tables driver conn inclusion-patterns exclusion-patterns)))))))})diff --git a/src/metabase/sync/interface.clj b/src/metabase/sync/interface.cljindex da83af4ce4e..9e57d301fac 100644--- a/src/metabase/sync/interface.clj+++ b/src/metabase/sync/interface.clj@@ -27,7 +27,8 @@(mr/def ::DatabaseMetadata[:map- [:tables [:set DatabaseMetadataTable]]+ [:tables [:fn {:error/message "a set, sequential, or reducible collection of tables"}+ (fn [x] (or (set? x) (sequential? x) (instance? clojure.lang.IReduceInit x)))]][:version {:optional true} [:maybe ::lib.schema.common/non-blank-string]]])(def DatabaseMetadatadiff --git a/src/metabase/sync/sync_metadata.clj b/src/metabase/sync/sync_metadata.cljindex 88d8dff3afc..11721101d79 100644--- a/src/metabase/sync/sync_metadata.clj+++ b/src/metabase/sync/sync_metadata.clj@@ -69,6 +69,9 @@(catch Throwable e(sync-util/set-initial-database-sync-aborted! database)(throw e)))+ ;; holder the `sync-tables` step fills with any `_metabase_metadata` table(s) as it streams+ ;; `:tables`, so the later `sync-metabase-metadata` step doesn't have to re-scan them+ db-metadata (assoc db-metadata :metabase-metadata-tables (volatile! []))steps (make-sync-steps db-metadata)essential-steps (into #{} (comp (filter :essential?) (map :step-name)) steps)results (sync-util/run-sync-operation "sync" database steps)]diff --git a/src/metabase/sync/sync_metadata/metabase_metadata.clj b/src/metabase/sync/sync_metadata/metabase_metadata.cljindex 56e9d61a968..1fe741726dc 100644--- a/src/metabase/sync/sync_metadata/metabase_metadata.clj+++ b/src/metabase/sync/sync_metadata/metabase_metadata.clj@@ -93,17 +93,23 @@This table contains information about type information, descriptions, and other properties thatshould be set for Metabase objects like Tables and Fields."([database :- i/DatabaseInstance]- (sync-metabase-metadata! database (fetch-metadata/db-metadata database)))+ ;; Standalone entry point: no `sync-tables` step ran to capture the `_metabase_metadata` table(s),+ ;; so scan the freshly fetched metadata here and hand the 2-arity the same `:metabase-metadata-tables`+ ;; holder it gets during a full sync. (`:tables` may be a reduce-only reducible, so reduce, don't `seq`.)+ (let [db-metadata (fetch-metadata/db-metadata database)+ captured (into [] (filter is-metabase-metadata-table?) (:tables db-metadata))]+ (sync-metabase-metadata! database (assoc db-metadata :metabase-metadata-tables (volatile! captured)))))- ([database :- i/DatabaseInstance db-metadata]+ ([database :- i/DatabaseInstance+ db-metadata :- i/DatabaseMetadata](sync-util/with-error-handling (format "Error syncing _metabase_metadata table for %s"(sync-util/name-for-logging database))(let [driver (driver.u/database->driver database)];; `sync-metabase-metadata-table!` relies on `driver/table-rows-seq` being defined(when (get-method driver/table-rows-seq driver)- ;; If there's more than one metabase metadata table (in different schemas) we'll sync each one in turn.- ;; Hopefully this is never the case.- (doseq [table (:tables db-metadata)]- (when (is-metabase-metadata-table? table)- (sync-metabase-metadata-table! driver database table))))+ ;; The `sync-tables` step captured any `_metabase_metadata` table(s) while streaming `:tables`,+ ;; so we don't re-scan them here. If there's more than one (in different schemas) we sync each in+ ;; turn.+ (doseq [table @(:metabase-metadata-tables db-metadata)]+ (sync-metabase-metadata-table! driver database table))){}))))diff --git a/src/metabase/sync/sync_metadata/tables.clj b/src/metabase/sync/sync_metadata/tables.cljindex 6798536efb6..55155d02a65 100644--- a/src/metabase/sync/sync_metadata/tables.clj+++ b/src/metabase/sync/sync_metadata/tables.clj@@ -9,6 +9,7 @@[metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.lib.schema.common :as lib.schema.common]+ [metabase.lib.schema.id :as lib.schema.id][metabase.models.humanization :as humanization][metabase.models.interface :as mi][metabase.sync.fetch-metadata :as fetch-metadata]@@ -84,6 +85,12 @@;;; ---------------------------------------------------- Syncing -----------------------------------------------------+(def ^:private TableNameAndSchema+ "The `{:name :schema}` identity a Table is keyed on during sync."+ [:map {:closed true}+ [:name ::lib.schema.common/non-blank-string]+ [:schema [:maybe ::lib.schema.common/non-blank-string]]])+(mu/defn- update-database-metadata!"If there is a version in the db-metadata update the DB to have that in the DB model"[database :- i/DatabaseInstance@@ -93,9 +100,10 @@{:details(assoc (:details database) :version (:version db-metadata))}))-(mu/defn- cruft-dependent-cols [{table-name :name :as table}- database- sync-stage :- [:enum ::reactivate ::create ::update]]+(mu/defn- cruft-dependent-cols :- :map+ [{table-name :name :as table} :- :map+ database :- i/DatabaseInstance+ sync-stage :- [:enum ::reactivate ::create ::update]](let [is-crufty? (if (and (= sync-stage ::update)(not (:is_attached_dwh database)));; TODO: we should add an updated_by column to metabase_table in@@ -120,10 +128,11 @@:else "incomplete"):visibility_type (when is-crufty? :cruft)}))-(defn create-table!+(mu/defn create-table! :- (ms/InstanceOf :model/Table)"Creates a new table in the database, ready to be synced.Throws an exception if there is already a table with the same name, schema and database ID."- [database table]+ [database :- i/DatabaseInstance+ table :- :map](t2/insert-returning-instance!:model/Table(merge (cruft-dependent-cols table database ::create)@@ -136,6 +145,8 @@(humanization/name->human-readable-name (:name table))):name (:name table):is_writable (:is_writable table)}+ (when (:field_order table)+ {:field_order (:field_order table)})(when (:data_source table){:data_source (:data_source table)})(when (:data_authority table)@@ -144,29 +155,29 @@{:data_authority :ingested:data_source :ingested}))))-(defn create-or-reactivate-table!- "Create a single new table in the database, or mark it as active if it already exists."- [database {schema :schema table-name :name :as table}]- (if-let [existing-id (t2/select-one-pk :model/Table- :db_id (u/the-id database)- :schema schema- :name table-name- :active false)]- (let [table (t2/select-one :model/Table existing-id)]- ;; if the table already exists but is marked *inactive*, mark it as *active*- (t2/update! :model/Table existing-id (cond-> (cruft-dependent-cols table database ::reactivate)-- ;; do not unhide tables w/ cruft settings- (some? (:visibility_type table))- (dissoc :visibility_type)-- true- (assoc :active true)-- (:is_sample database)- (assoc :data_authority :ingested- :data_source :ingested))))- ;; otherwise create a new Table+(mu/defn- reactivate-table!+ "Mark an existing inactive Table active again, refreshing its cruft-dependent columns. `existing`+ is the app-DB Table instance we already hold, so we don't re-select it."+ [database :- i/DatabaseInstance+ existing :- (ms/InstanceOf :model/Table)]+ (t2/update! :model/Table (:id existing)+ (cond-> (cruft-dependent-cols existing database ::reactivate)+ ;; do not unhide tables w/ cruft settings+ (some? (:visibility_type existing)) (dissoc :visibility_type)+ true (assoc :active true)+ (:is_sample database) (assoc :data_authority :ingested+ :data_source :ingested))))++(mu/defn create-or-reactivate-table!+ "Create a single new table in the database, or mark it as active if a matching inactive one exists."+ [database :- i/DatabaseInstance+ {schema :schema table-name :name :as table} :- :map]+ (if-let [existing (t2/select-one :model/Table+ :db_id (u/the-id database)+ :schema schema+ :name table-name+ :active false)]+ (reactivate-table! database existing)(create-table! database table)));; TODO - should we make this logic case-insensitive like it is for fields?@@ -187,12 +198,13 @@1024 characters."254)-(defn- table-name-or-schema-too-long?+(mu/defn- table-name-or-schema-too-long? :- :boolean"Whether `table`'s name or schema is too long to store in the application DB (see `table-name-max-length` /`table-schema-max-length`)."- [{table-name :name, table-schema :schema}]- (or (< table-name-max-length (count table-name))- (< table-schema-max-length (count (or table-schema "")))))+ [{table-name :name, table-schema :schema} :- :map]+ (boolean+ (or (< table-name-max-length (count table-name))+ (< table-schema-max-length (count (or table-schema ""))))))(mu/defn- remove-tables-with-too-long-names :- [:set i/DatabaseMetadataTable]"Drop any tables in `db-metadata-tables` whose name or schema is too long to store in the application DB (see@@ -208,37 +220,31 @@(pr-str (sort (map (fn [{:keys [schema name]}] (str schema "." name)) too-long)))))(set ok)))-(mu/defn- create-or-reactivate-tables!- "Create `new-tables` for database, or if they already exist, mark them as active."+(mu/defn- create-tables! :- [:sequential (ms/InstanceOf :model/Table)]+ "Insert brand-new tables for `database`, returning the created `:model/Table` instances. Sorted by+ `[schema name]` so auto-increment ids are assigned deterministically."[database :- i/DatabaseInstancenew-table-metadatas :- [:set i/DatabaseMetadataTable]](doseq [table-metadata new-table-metadatas](log/info "Found new table:"(sync-util/name-for-logging (mi/instance :model/Table table-metadata))))- (doseq [table-metadata (sort-by (juxt :schema :name) new-table-metadatas)]- (create-or-reactivate-table! database table-metadata)))+ (let [field-order (some-> (:engine database) driver/default-field-order)]+ (mapv (fn [table-metadata]+ (create-table! database (m/assoc-some table-metadata :field_order field-order)))+ (sort-by (juxt :schema :name) new-table-metadatas))))(mu/defn- retire-tables!- "Mark any `old-tables` belonging to `database` as inactive."- [database :- i/DatabaseInstance- old-tables :- [:set [:map- [:name ::lib.schema.common/non-blank-string]- [:schema [:maybe ::lib.schema.common/non-blank-string]]]]]- (log/info "Marking tables as inactive:"- (for [table old-tables]- (sync-util/name-for-logging (mi/instance :model/Table table))))- (doseq [{schema :schema table-name :name :as _table} old-tables]- (t2/update! :model/Table {:db_id (u/the-id database)- :schema schema- :name table-name- :active true}- {:active false})))+ "Mark the active Tables with `table-ids` as inactive."+ [table-ids :- [:set ::lib.schema.id/table]]+ (when (seq table-ids)+ (log/info "Marking tables as inactive:" (pr-str table-ids))+ (t2/update! :model/Table {:id [:in table-ids] :active true} {:active false})))(def ^:private keys-to-update[:description :database_require_filter :estimated_row_count :visibility_type :initial_sync_status :is_writable])(mu/defn- update-table-metadata-if-needed!- "Update the table metadata if it has changed."+ "Update the table metadata if it has changed. Returns true if a row was updated."[table-metadata :- i/DatabaseMetadataTablemetabase-table :- (ms/InstanceOf :model/Table)metabase-database :- (ms/InstanceOf :model/Database)]@@ -272,65 +278,81 @@(sync-util/name-for-logging metabase-table)(get metabase-table k)v))- (when (seq changes)- (t2/update! :model/Table (:id metabase-table) changes))))--(mu/defn- update-tables-metadata-if-needed!+ (boolean+ (when (seq changes)+ (t2/update! :model/Table (:id metabase-table) changes)+ true))))++(mu/defn- update-tables-metadata-if-needed! :- :int+ "Update metadata for the tables present in both `table-metadatas` and `metabase-tables`. Returns+ the number of tables actually updated."[table-metadatas :- [:set i/DatabaseMetadataTable]metabase-tables :- [:set (ms/InstanceOf :model/Table)]metabase-database :- (ms/InstanceOf :model/Database)](let [name+schema->table-metadata (m/index-by (juxt :name :schema) table-metadatas)name+schema->metabase-table (m/index-by (juxt :name :schema) metabase-tables)]- (doseq [name+schema (set/intersection (set (keys name+schema->table-metadata)) (set (keys name+schema->metabase-table)))]- (update-table-metadata-if-needed! (name+schema->table-metadata name+schema)- (name+schema->metabase-table name+schema)- metabase-database))))--(mu/defn- table-set :- [:set i/DatabaseMetadataTable]- "So there exist tables for the user and metabase metadata tables for internal usage by metabase.- Get set of user tables only, excluding metabase metadata tables."- [db-metadata :- i/DatabaseMetadata]- (into #{}- (remove (fn [table]- (or (metabase-metadata/is-metabase-metadata-table? table)- (sync-util/is-temp-transform-table? table))))- (:tables db-metadata)))--(mu/defn- select-tables :- [:set (ms/InstanceOf :model/Table)]- "Selects the columns we need for `:model/Table`, with some optional filters"+ (reduce (fn [updated name+schema]+ (cond-> updated+ (update-table-metadata-if-needed! (name+schema->table-metadata name+schema)+ (name+schema->metabase-table name+schema)+ metabase-database)+ inc))+ 0+ (set/intersection (set (keys name+schema->table-metadata))+ (set (keys name+schema->metabase-table))))))++(def ^:private table-sync-batch-size+ "How many warehouse tables to reconcile against the app DB at a time. Bounds peak memory so a+ database with tens of thousands of tables doesn't have to be diffed all at once."+ 1000)++(mu/defn- ignore-table? :- :boolean+ "Tables we never create `:model/Table` rows for: the special `_metabase_metadata` table (its+ contents are applied to other Tables/Fields instead) and temporary transform output tables."+ [table :- :map]+ (boolean+ (or (metabase-metadata/is-metabase-metadata-table? table)+ (sync-util/is-temp-transform-table? table))))++(mu/defn- table-name+schema :- TableNameAndSchema+ "The `{:name :schema}` identity a Table is keyed on during sync."+ [table :- :map]+ (select-keys table [:name :schema]))++(mu/defn- existing-tables-by-name+schema :- :map+ "The `:model/Table` rows (active *and* inactive) for `database` matching any name in `tables`,+ indexed by `{:name :schema}`. Queries by name only -- not schema -- since `:schema` can be `nil`+ and `IN (NULL, ...)` wouldn't match; the exact `(name, schema)` match falls out of the index key."[database :- i/DatabaseInstance- & filters]- (set (apply- t2/select- (into [:model/Table :id :name :schema :data_authority] keys-to-update)- :db_id (u/the-id database)- filters)))--(mu/defn- db->our-metadata :- [:set (ms/InstanceOf :model/Table)]- "Return information about what Tables we have for this DB in the Metabase application DB. Only includes active tables."- [database :- i/DatabaseInstance]- (select-tables database :active true))--(mu/defn- db->our-tables :- [:set (ms/InstanceOf :model/Table)]- "Return *all* tables we have for this DB in the Metabase appDB, including inactive ones."- [database :- i/DatabaseInstance]- (select-tables database))+ tables]+ (let [names (into [] (comp (map :name) (distinct)) tables)]+ (if (seq names)+ (t2/select-fn->fn table-name+schema identity+ (into [:model/Table :id :name :schema :data_authority :active] keys-to-update)+ :db_id (u/the-id database)+ :name [:in names])+ {})))(mu/defn- adjusted-schemas :- [:maybe [:map-of :string :string]]- "Returns a map of schemas that should be adjusted to their new names."+ "Returns a map of `{old-schema new-schema}` for the app-DB schemas the driver re-qualifies. Streams+ the distinct schemas straight from the DB (selecting only `:schema`) so we never materialize every+ table just to read their schemas."[driver- database- our-tables :- [:set (ms/InstanceOf :model/Table)]]- (reduce- (fn [accum schema]- (let [new-schema (driver/adjust-schema-qualification driver database schema)]- (cond-> accum- (not= schema new-schema) (assoc schema new-schema))))+ database :- i/DatabaseInstance]+ (transduce+ (comp (map :schema) (distinct))+ (completing+ (fn [accum schema]+ (let [new-schema (driver/adjust-schema-qualification driver database schema)]+ (cond-> accum+ (not= schema new-schema) (assoc schema new-schema)))))nil- (into #{} (map :schema our-tables))))+ (t2/reducible-select [:model/Table :schema] :db_id (u/the-id database))))-(defn- adjust-table-schemas!- [database schemas-to-update]+(mu/defn- adjust-table-schemas!+ "Apply the `{old-schema new-schema}` renames from [[adjusted-schemas]] to the app-DB Table rows."+ [database :- i/DatabaseInstance+ schemas-to-update :- [:maybe [:map-of :string :string]]](when schemas-to-update(log/infof "Renaming schemas: %s" (pr-str schemas-to-update)))(doseq [[schema new-schema] schemas-to-update]@@ -343,11 +365,12 @@^{:doc "threshold after which deactivated tables will be archived"}archive-tables-threshold [-14 :day])-(defn- archive-tables!+(mu/defn- archive-tables! :- :int"Mark tables that have been deactivated for longer than the configured threshold as archivedand suffixes their names. Skips tables with `transform_target = true` (provisional transform- output entries) since transforms still reference them by their original name."- [database]+ output entries) since transforms still reference them by their original name. Returns the number+ of tables archived."+ [database :- i/DatabaseInstance](let [;; we use UTC offset time for suffix, may not match db time but;; it doesn't matter much, the source of time truth is `archived_at`,;; we're just using this as a cheap namespace@@ -390,67 +413,126 @@(swap! archived + did-update)))))@archived))+(def ^:private SyncContext+ "State threaded through [[sync-table-batch!]] across the single reconcile pass."+ [:map {:closed true}+ [:created :int] ; running count of created/reactivated tables+ [:updated :int] ; running count of metadata-updated tables+ [:complete? :boolean] ; false once any batch fails -- then we don't retire+ [:seen :any] ; transient set of reconciled `:model/Table` ids+ [:metabase-metadata [:vector i/DatabaseMetadataTable]]]) ; captured `_metabase_metadata` table++(mu/defn- sync-table-batch! :- SyncContext+ "Reconcile one batch of warehouse tables against the app DB, threading the sync `context`.++ Captures any `_metabase_metadata` table(s) from the raw batch (for the downstream metabase-metadata+ step), then narrows the batch -- dropping tables we never sync, collapsing duplicate `(name, schema)`,+ dropping names too long for the app DB, and dropping workspace-isolated tables (they back canonical+ Tables via remap, so they get no `:model/Table` of their own) -- and creates/reactivates new tables+ and updates metadata on existing ones. The reconcile is error-handled per batch: on failure we log,+ skip the batch, and mark the sync incomplete so retirement is skipped."+ [database :- i/DatabaseInstance+ db-name :- :string+ context :- SyncContext+ batch :- [:sequential i/DatabaseMetadataTable]]+ (letfn [(reconcile! []+ (let [tables (as-> batch <>+ (into #{} (comp (remove ignore-table?) (m/distinct-by table-name+schema)) <>)+ (remove-tables-with-too-long-names database <>)+ (ws.table-remapping/filter-workspace-side-tables <> (u/the-id database)))+ existing (existing-tables-by-name+schema database tables)+ existing-row #(get existing (table-name+schema %))+ already-active (into #{} (filter #(:active (existing-row %))) tables)+ to-create (into #{} (remove existing-row) tables)+ to-reactivate (into #{} (filter #(and (existing-row %) (not (:active (existing-row %))))) tables)+ created (when (seq to-create)+ (create-tables! database to-create))]+ (doseq [table-metadata to-reactivate]+ (reactivate-table! database (existing-row table-metadata)))+ (when (seq to-reactivate)+ (let [rows (existing-tables-by-name+schema database to-reactivate)]+ (update-tables-metadata-if-needed! to-reactivate+ (into #{} (keep #(get rows (table-name+schema %))) to-reactivate)+ database)))+ {:created (+ (count to-create) (count to-reactivate))+ :updated (if (seq already-active)+ (update-tables-metadata-if-needed! already-active+ (into #{} (keep existing-row) already-active)+ database)+ 0)+ :seen (-> []+ (into (map :id) created)+ (into (keep (comp :id existing-row)) to-reactivate)+ (into (keep (comp :id existing-row)) already-active))}))+ (conj-metabase-metadata [acc table]+ (cond-> acc+ (metabase-metadata/is-metabase-metadata-table? table) (conj table)))]+ (let [result (sync-util/with-error-handling (format "Error creating/reactivating tables for %s" db-name)+ (reconcile!))]+ (if (map? result)+ (-> context+ (update :created + (:created result))+ (update :updated + (:updated result))+ (update :seen (fn [acc] (reduce conj! acc (:seen result))))+ (update :metabase-metadata (fn [acc] (reduce conj-metabase-metadata acc batch))))+ (assoc context :complete? false)))))++(mu/defn- retire-unseen-tables! :- :int+ "Retire active app-DB tables the warehouse no longer reports. `seen` holds the `:model/Table` id of+ every table reconciled this sync (accumulated by [[sync-table-batch!]], including the injected+ workspace-canonical tuples). Streams the active app-DB table ids and retires, a batch at a time, the+ ones not in `seen` -- so we never hold either the full active set or the full retire set in memory.+ Returns the number retired."+ [database :- i/DatabaseInstance+ seen :- [:set ::lib.schema.id/table]]+ (transduce+ (comp (map :id) (remove seen) (partition-all table-sync-batch-size))+ (completing (fn [retired batch]+ (retire-tables! (set batch))+ (+ retired (count batch))))+ 0+ (t2/reducible-select [:model/Table :id] :db_id (u/the-id database) :active true)))+(mu/defn sync-tables-and-database!- "Sync the Tables recorded in the Metabase application database with the ones obtained by calling `database`'s driver's- implementation of `describe-database`.- Also syncs the database metadata taken from describe-database if there is any"+ "Sync the `:model/Table` rows for `database` against its driver's `describe-database`, and the DB+ metadata (e.g. version) if present.++ Reconciles the warehouse tables against the app DB one batch at a time (see [[table-sync-batch-size]]),+ then retires the active app-DB tables the warehouse no longer reports -- so a database with tens of+ thousands of tables never has to be held or `clojure.data/diff`ed all at once. Returns+ `{:updated-tables <n> :total-tables <n>}`."([database :- i/DatabaseInstance](sync-tables-and-database! database (fetch-metadata/db-metadata database)))- ([database :- i/DatabaseInstance db-metadata]- ;; determine what's changed between what info we have and what's in the DB- (let [driver (driver.u/database->driver database)- db-table-metadatas (table-set db-metadata)- ;; drop tables whose names can't be stored in the app DB before they reach an INSERT and abort creation of- ;; the remaining new tables for this database- db-table-metadatas (remove-tables-with-too-long-names database db-table-metadatas)- ;; DEV-1898: workspace-isolated tables (`ws_*`) live on the warehouse but must not- ;; become :model/Table rows. They back canonical Tables via remap, not their own identity.- db-table-metadatas (ws.table-remapping/filter-workspace-side-tables db-table-metadatas (:id database))- ;; Inject synthetic canonical-side tuples for any remap whose to-side is materialized.- ;; Without this, the diff retires canonical Table rows whose physical backing only- ;; exists at the workspace location (not at the canonical name on the warehouse).- db-table-metadatas (ws.table-remapping/inject-workspace-canonical-tuples db-table-metadatas (:id database))- name+schema #(select-keys % [:name :schema])- name+schema->db-table (m/index-by name+schema db-table-metadatas)- our-metadata (db->our-metadata database)- multi-level-support? (driver.u/supports? driver :multi-level-schema database)- schemas-to-update (when multi-level-support?- ;; we want to adjust the schemas for all tables (not just active ones from `our-metadata`)- (adjusted-schemas driver database (db->our-tables database)))- our-metadata (cond->> our-metadata- multi-level-support?- (into #{} (map (fn [table]- (update table :schema #(get schemas-to-update %1 %1))))))- keep-name+schema-set (fn [metadata]- (set (map name+schema metadata)))- [new-table-metadatas- old-table-metadatas] (data/diff- (keep-name+schema-set (set (map name+schema db-table-metadatas)))- (keep-name+schema-set (set (map name+schema our-metadata))))]- (sync-util/with-error-handling (format "Error updating table schemas for %s"- (sync-util/name-for-logging database))+ ([database :- i/DatabaseInstance+ db-metadata :- i/DatabaseMetadata]+ (let [driver (driver.u/database->driver database)+ db-name (sync-util/name-for-logging database)+ multi-level-support? (driver.u/supports? driver :multi-level-schema database)+ schemas-to-update (when multi-level-support?+ (adjusted-schemas driver database))]+ (sync-util/with-error-handling (format "Error updating table schemas for %s" db-name)(adjust-table-schemas! database schemas-to-update))- ;; update database metadata from database(when (some? (:version db-metadata))- (sync-util/with-error-handling (format "Error creating/reactivating tables for %s"- (sync-util/name-for-logging database))+ (sync-util/with-error-handling (format "Error updating database metadata for %s" db-name)(update-database-metadata! database db-metadata)))- ;; create new tables as needed or mark them as active again- (when (seq new-table-metadatas)- (let [new-tables-info (set (map #(get name+schema->db-table (name+schema %)) new-table-metadatas))]- (sync-util/with-error-handling (format "Error creating/reactivating tables for %s"- (sync-util/name-for-logging database))- (create-or-reactivate-tables! database new-tables-info))))- ;; mark old tables as inactive- (when (seq old-table-metadatas)- (sync-util/with-error-handling (format "Error retiring tables for %s" (sync-util/name-for-logging database))- (retire-tables! database old-table-metadatas)))- (sync-util/with-error-handling (format "Error updating table metadata for %s" (sync-util/name-for-logging database))- ;; we need to fetch the tables again because we might have retired tables in the previous steps- (update-tables-metadata-if-needed! db-table-metadatas (db->our-metadata database) database))- (let [archived-tables (sync-util/with-error-handling (format "Error archiving tables for %s"- (sync-util/name-for-logging database))- (archive-tables! database))]- {:updated-tables (+ (count new-table-metadatas) (count old-table-metadatas) (or archived-tables 0))- :total-tables (count our-metadata)}))))+ (let [reconcile-batch (fn reconcile-batch [context batch]+ (sync-table-batch! database db-name context batch))+ context (transduce (partition-all table-sync-batch-size)+ (completing reconcile-batch)+ {:created 0, :updated 0, :complete? true+ :seen (transient #{}), :metabase-metadata []}+ (:tables db-metadata))+ context (reconcile-batch context (ws.table-remapping/inject-workspace-canonical-tuples [] (u/the-id database)))+ {:keys [created updated complete?]} context]+ (when-let [holder (:metabase-metadata-tables db-metadata)]+ (vreset! holder (:metabase-metadata context)))+ (let [retired (when complete?+ (sync-util/with-error-handling (format "Error retiring tables for %s" db-name)+ (retire-unseen-tables! database (persistent! (:seen context)))))+ archived (sync-util/with-error-handling (format "Error archiving tables for %s" db-name)+ (archive-tables! database))]+ {:updated-tables (cond-> (+ created updated)+ (int? retired) (+ retired)+ (int? archived) (+ archived))+ :total-tables (t2/count :model/Table :db_id (u/the-id database) :active true)})))))diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.cljindex ae65b37c213..09a6acad3fc 100644--- a/src/metabase/warehouse_schema/models/table.clj+++ b/src/metabase/warehouse_schema/models/table.clj@@ -175,7 +175,8 @@;; Default both curation columns here so model inserts are consistent across app DBs; a migration;; reasserts matching DB-level defaults for non-model insert paths.(let [defaults {:display_name (humanization/name->human-readable-name (:name table))- :field_order (driver/default-field-order (t2/select-one-fn :engine :model/Database :id (:db_id table)))+ :field_order (or (:field_order table)+ (driver/default-field-order (t2/select-one-fn :engine :model/Database :id (:db_id table)))):data_layer :internal:data_authority :unconfigured}](collection/check-allowed-content :table (:collection_id table))diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.cljindex 94e4c38252b..81ed40738ea 100644--- a/test/metabase/driver/postgres_test.clj+++ b/test/metabase/driver/postgres_test.clj@@ -270,6 +270,7 @@[& args](->> (apply driver/describe-database args):tables+ (into [])(sort-by :name)))(deftest materialized-views-testdiff --git a/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj b/test/metabase/driver/sql_jdbc/sync/describe_database_test.cljindex 51b18a57f24..878b7d4f49f 100644--- a/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj+++ b/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj@@ -101,7 +101,7 @@{:name "PEOPLE", :schema "PUBLIC", :description nil, :is_writable true}{:name "PRODUCTS", :schema "PUBLIC", :description nil, :is_writable true}{:name "REVIEWS", :schema "PUBLIC", :description nil, :is_writable true}}- (:tables (sql-jdbc.describe-database/describe-database :h2 (mt/id))))))+ (into #{} (:tables (sql-jdbc.describe-database/describe-database :h2 (mt/id)))))))(defn- describe-database-with-open-resultset-count!"Just like `describe-database`, but instead of returning the database description returns the number of ResultSet@@ -123,9 +123,10 @@dbnil(fn [_conn]- (sql-jdbc.describe-database/describe-database driver db)- (reduce + (for [^ResultSet rs @resultsets]- (if (.isClosed rs) 0 1))))))))+ ;; `:tables` is a reducible -- realize it so `active-tables` actually opens (and closes) its ResultSets+ (let [_ (into [] (:tables (sql-jdbc.describe-database/describe-database driver db)))]+ (reduce + (for [^ResultSet rs @resultsets]+ (if (.isClosed rs) 0 1)))))))))(defn- count-active-tables-in-db[db-id]@@ -297,7 +298,7 @@(vreset! closed-first true)(.close conn))(execute-select-probe-query driver conn query))]- (let [table-names #(->> % :tables (map :name) set)+ (let [table-names #(into #{} (map :name) (:tables %))all-tables-sans-one (table-names (driver/describe-database driver/*driver* (mt/id)))];; there is at maximum one missing table(is (>= 1 (count (set/difference all-tables all-tables-sans-one)))))))))))diff --git a/test/metabase/driver/sql_jdbc_test.clj b/test/metabase/driver/sql_jdbc_test.cljindex f75ca91cc64..908a716a537 100644--- a/test/metabase/driver/sql_jdbc_test.clj+++ b/test/metabase/driver/sql_jdbc_test.clj@@ -29,7 +29,7 @@"ORDERS" "PEOPLE" "PRODUCTS" "REVIEWS"]]{:name table, :schema "PUBLIC",:description nil, :is_writable true}))- (:tables (driver/describe-database :h2 (mt/db))))))+ (into #{} (:tables (driver/describe-database :h2 (mt/db)))))))(deftest describe-fields-sync-with-composite-pks-test(testing "Make sure syncing a table that has a composite pks works"diff --git a/test/metabase/driver/sqlite_test.clj b/test/metabase/driver/sqlite_test.cljindex 3d142974bc9..5c9d4bdb587 100644--- a/test/metabase/driver/sqlite_test.clj+++ b/test/metabase/driver/sqlite_test.clj@@ -165,8 +165,8 @@(mt/with-db db(testing "timestamp columns"(testing "database should be synced"- (is (= {:tables (set (map default-table-result ["timestamp_table"]))}- (driver/describe-database driver db))))+ (is (= (set (map default-table-result ["timestamp_table"]))+ (into #{} (:tables (driver/describe-database driver db))))))(testing "timestamp column should exist"(is (=? {:name "timestamp_table":schema nildiff --git a/test/metabase/driver_test.clj b/test/metabase/driver_test.cljindex 8a6a6645ba4..20a1ba5c313 100644--- a/test/metabase/driver_test.clj+++ b/test/metabase/driver_test.clj@@ -89,10 +89,12 @@(testing "`describe-database` should return schemas with tables if the database supports schemas"(is (some? (->> (driver/describe-database driver/*driver* (mt/db)):tables+ (into [])(some :schema)))))(testing "`describe-database` should not return schemas with tables if the database doesn't support schemas"(is (nil? (->> (driver/describe-database driver/*driver* (mt/db)):tables+ (into [])(some :schema))))))))(defn- basic-db-definition [database-name]diff --git a/test/metabase/sync/sync_metadata/tables_test.clj b/test/metabase/sync/sync_metadata/tables_test.cljindex 2898f5a1a2f..9718fae2090 100644--- a/test/metabase/sync/sync_metadata/tables_test.clj+++ b/test/metabase/sync/sync_metadata/tables_test.clj@@ -48,25 +48,25 @@normal-table {:name "orders":schema "public"}db-metadata {:tables #{temp-table normal-table}}]- (testing "with no premium features, table-set excludes transform temporary tables"+ (testing "with no premium features, sync excludes transform temporary tables"(mt/with-premium-features #{}(is (= #{normal-table}- (#'sync-tables/table-set db-metadata)))))+ (into #{} (remove #'sync-tables/ignore-table?) (:tables db-metadata))))))(testing "when hosted, includes transform temporary tables"(mt/with-premium-features #{:hosting}(is (= #{normal-table temp-table}- (#'sync-tables/table-set db-metadata)))))+ (into #{} (remove #'sync-tables/ignore-table?) (:tables db-metadata))))))(testing "when hosted with `transforms` enabled, excludes the temp tables"(mt/with-premium-features #{:hosting :transforms-basic}(is (= #{normal-table}- (#'sync-tables/table-set db-metadata)))))))+ (into #{} (remove #'sync-tables/ignore-table?) (:tables db-metadata))))))))(deftest retire-tables-test(testing "`retire-tables!` should retire the Table(s) passed to it, not all Tables in the DB -- see #9593"- (mt/with-temp [:model/Database db {}- :model/Table table-1 {:name "Table 1" :db_id (u/the-id db)}- :model/Table _ {:name "Table 2" :db_id (u/the-id db)}]- (#'sync-tables/retire-tables! db #{{:name "Table 1" :schema (:schema table-1)}})+ (mt/with-temp [:model/Database db {}+ :model/Table {table-1-id :id} {:name "Table 1" :db_id (u/the-id db)}+ :model/Table _ {:name "Table 2" :db_id (u/the-id db)}]+ (#'sync-tables/retire-tables! #{table-1-id})(is (= {"Table 1" false "Table 2" true}(t2/select-fn->fn :name :active :model/Table :db_id (u/the-id db)))))))@@ -362,7 +362,7 @@{:schema "public" :name "apple"}{:schema "public" :name "mango"}}](mt/with-temp [:model/Database db {}]- (#'sync-tables/create-or-reactivate-tables! db metadatas)+ (#'sync-tables/create-tables! db metadatas)(is (= ["beta" "apple" "mango" "zebra"](map :name (t2/select [:model/Table :name]:db_id (u/the-id db)diff --git a/test/metabase/sync/sync_metadata_test.clj b/test/metabase/sync/sync_metadata_test.cljindex 14a46de6440..63e71c8db3e 100644--- a/test/metabase/sync/sync_metadata_test.clj+++ b/test/metabase/sync/sync_metadata_test.clj@@ -28,7 +28,7 @@(deftest survive-table-errors(testing "Make sure we survive table sync failing"- (sync-survives-crash?! sync-tables/create-or-reactivate-tables!)+ (sync-survives-crash?! sync-tables/create-tables!)(sync-survives-crash?! sync-tables/retire-tables!)(sync-survives-crash?! sync-tables/update-tables-metadata-if-needed!)))diff --git a/test/metabase/test/data/impl/verify.clj b/test/metabase/test/data/impl/verify.cljindex 4263eecf81c..ce35cff00d5 100644--- a/test/metabase/test/data/impl/verify.clj+++ b/test/metabase/test/data/impl/verify.clj@@ -18,10 +18,7 @@(defn- loaded-tables"Actual Tables loaded into `database`. Returns a set of `[schema-name table-name]` pairs."[{:keys [driver database]}]- (->> (driver/describe-database driver database)- :tables- (map (juxt :schema :name))- set))+ (into #{} (map (juxt :schema :name)) (:tables (driver/describe-database driver database))))(defn- loaded-fields"Actual Fields loaded into a Table. Returns set of field names."