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
Fake sync for Redshift tests (branch-conditional, refactored) (#67603)
bryanad60b57c4af3
diff --git a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj b/modules/drivers/redshift/test/metabase/driver/redshift_test.cljindex a6e2d978a08..66354199b63 100644--- a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj+++ b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj@@ -6,15 +6,19 @@[metabase.driver :as driver][metabase.driver.sql-jdbc.connection :as sql-jdbc.conn][metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]- [metabase.driver.sql-jdbc.sync.describe-database :as sql-jdbc.describe-database][metabase.driver.sql-jdbc.sync.interface :as sql-jdbc.sync][metabase.driver.sql.query-processor :as sql.qp]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.lib.test-util :as lib.tu][metabase.plugins.jdbc-proxy :as jdbc-proxy][metabase.query-processor :as qp]+ ^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store][metabase.sync.core :as sync][metabase.sync.util :as sync-util][metabase.system.core :as system][metabase.test :as mt]+ [metabase.test.data.impl.get-or-create :as test.get-or-create][metabase.test.data.interface :as tx][metabase.test.data.redshift :as redshift.tx][metabase.test.data.sql :as sql.tx]@@ -134,37 +138,41 @@;; stored as textfile;; location 's3://mb-rs-test/tickit/spectrum/sales/';; table properties ('numRows'='172000');-;;+(deftest ^:parallel test-external-table- (mt/test-driver :redshift- (testing "expects spectrum schema to exist"- (is (=? [{:table_id (mt/id :extsales)- :name "buyerid"- :source :fields- :field_ref [:field (mt/id :extsales :buyerid) nil]- :id (mt/id :extsales :buyerid)- :visibility_type :normal- :display_name "Buyerid"- :base_type :type/Integer- :effective_type :type/Integer}- {:table_id (mt/id :extsales)- :name "salesid"- :source :fields- :field_ref [:field (mt/id :extsales :salesid) nil]- :id (mt/id :extsales :salesid)- :visibility_type :normal- :display_name "Salesid"- :base_type :type/Integer- :effective_type :type/Integer}]- ;; in different Redshift instances, the fingerprint on these columns is different.- (map #(dissoc % :fingerprint)- (get-in (qp/process-query (mt/mbql-query extsales- {:limit 1- :fields [$buyerid $salesid]- :order-by [[:asc $buyerid]- [:asc $salesid]]- :filter [:= [:field (mt/id :extsales :buyerid) nil] 11498]}))- [:data :cols])))))))+ ;; The extsales table is an AWS Redshift Spectrum external table that only exists in the real+ ;; Redshift database - it's not part of our test data definitions. Skip this test when using+ ;; fake sync since the table won't be synced.+ (when (tx/on-master-or-release-branch?)+ (mt/test-driver :redshift+ (testing "expects spectrum schema to exist"+ (is (=? [{:table_id (mt/id :extsales)+ :name "buyerid"+ :source :fields+ :field_ref [:field (mt/id :extsales :buyerid) nil]+ :id (mt/id :extsales :buyerid)+ :visibility_type :normal+ :display_name "Buyerid"+ :base_type :type/Integer+ :effective_type :type/Integer}+ {:table_id (mt/id :extsales)+ :name "salesid"+ :source :fields+ :field_ref [:field (mt/id :extsales :salesid) nil]+ :id (mt/id :extsales :salesid)+ :visibility_type :normal+ :display_name "Salesid"+ :base_type :type/Integer+ :effective_type :type/Integer}]+ ;; in different Redshift instances, the fingerprint on these columns is different.+ (map #(dissoc % :fingerprint)+ (get-in (qp/process-query (mt/mbql-query extsales+ {:limit 1+ :fields [$buyerid $salesid]+ :order-by [[:asc $buyerid]+ [:asc $salesid]]+ :filter [:= [:field (mt/id :extsales :buyerid) nil] 11498]}))+ [:data :cols]))))))))(deftest parameters-test(mt/test-driver :redshift@@ -344,12 +352,14 @@"CREATE MATERIALIZED VIEW %2$s AS SELECT * FROM %1$s;")qual-tbl-nmqual-mview-nm)- (is (some #(= mview-nm (:name %))- (:tables (sql-jdbc.describe-database/describe-database :redshift database))))))))))+ (binding [redshift.tx/*override-describe-database-to-filter-by-db-name?* false]+ (is (contains?+ (set (map :name (:tables (driver/describe-database :redshift database))))+ mview-nm)))))))))(mt/defdataset unix-timestamps[["timestamps"- [{:field-name "timestamp", :base-type {:native "numeric"}}]+ [{:field-name "timestamp", :base-type {:native "numeric"}, :effective-type :type/Decimal}][[1642704550656]]]])(deftest unix-timestamp-test@@ -362,12 +372,19 @@(is (= [1 1642704550656M](mt/first-row (qp/process-query query)))))))(testing "WITH coercion strategy"- (mt/with-temp-vals-in-db :model/Field (mt/id :timestamps :timestamp) {:coercion_strategy :Coercion/UNIXMilliSeconds->DateTime- :effective_type :type/Instant}- (let [query (mt/mbql-query timestamps)]- (mt/with-native-query-testing-context query- (is (= [1 "2022-01-20T18:49:10.656Z"]- (mt/first-row (qp/process-query query))))))))))))+ ;; Use merged-mock-metadata-provider to set coercion strategy, avoiding+ ;; caching issues with with-temp-vals-in-db (see coercion_test.clj for pattern)+ (let [mp (lib.tu/merged-mock-metadata-provider+ (mt/metadata-provider)+ {:fields [{:id (mt/id :timestamps :timestamp)+ :coercion-strategy :Coercion/UNIXMilliSeconds->DateTime+ :effective-type :type/Instant}]})+ query (lib/query mp (lib.metadata/table mp (mt/id :timestamps)))]+ (mt/with-native-query-testing-context query+ (is (= [[1 "2022-01-20T18:49:10.656Z"]]+ (mt/formatted-rows [int str]+ (qp.store/with-metadata-provider mp+ (qp/process-query query))))))))))))(deftest interval-test(mt/test-drivers #{:postgres :redshift}@@ -399,9 +416,9 @@conn-spec (sql-jdbc.conn/db->pooled-connection-spec database)get-privileges (fn [](sql-jdbc.conn/with-connection-spec-for-testing-connection- [spec [:redshift (assoc (:details database) :user username)]]+ [spec [:redshift (assoc (:details database) :user username)](with-redefs [sql-jdbc.conn/db->pooled-connection-spec (fn [_] spec)]- (set (sql-jdbc.sync/current-user-table-privileges driver/*driver* spec)))))]+ (set (sql-jdbc.sync/current-user-table-privileges driver/*driver* spec)))]))](try(execute! (format(str@@ -563,3 +580,116 @@(is (= {:classname "com.amazon.redshift.jdbc42.Driver", :subprotocol "redshift", :subname "//test.example.com:/test-db", :ssl true, :OpenSourceSubProtocolOverride false}(sql-jdbc.conn/connection-details->spec :redshift (assoc options :dbname "test-dbname" :db "test-db")))":db should take precedence"))))++;;; ------------------------------------------------ Real Sync Test ------------------------------------------------+;; This test uses real sync (not fake sync) to validate that fake sync produces equivalent metadata.+;; It uses a minimal dataset to keep sync time reasonable (~30s instead of ~6min for test-data).++(deftest real-sync-validation-test+ (mt/test-driver :redshift+ (testing "Forces a real sync for a minimal dataset to test real sync logic"+ ;; Disable fake sync for this test to force a real sync+ (tx/with-driver-supports-feature! [:redshift :test/use-fake-sync false]+ (mt/dataset (mt/dataset-definition "real-sync-validation"+ [["sync_test_table"+ [{:field-name "text_col" :base-type :type/Text}+ {:field-name "int_col" :base-type :type/Integer}]+ [["hello" 1]+ ["world" 2]]]])+ (testing "Table was synced with correct schema"+ (let [table (t2/select-one :model/Table :db_id (mt/id) :name "real_sync_validation_sync_test_table")]+ (is (some? table) "Table should exist")+ (is (= (redshift.tx/unique-session-schema) (:schema table)) "Schema should match session schema")))+ (testing "Fields were synced with correct types"+ (let [fields (t2/select [:model/Field :name :base_type :semantic_type]+ :table_id (mt/id :sync_test_table)+ :active true+ {:order-by [:database_position]})]+ (is (= 3 (count fields)) "Should have 3 fields (id + 2 defined)")+ (is (= "id" (:name (first fields))) "First field should be auto-generated PK")+ (is (= :type/PK (:semantic_type (first fields))) "PK should have :type/PK semantic type")+ (is (= :type/Text (:base_type (second fields))) "text_col should be :type/Text")+ (is (= :type/Integer (:base_type (nth fields 2))) "int_col should be :type/Integer"))))))))++;;; ---------------------------------------- Fake Sync Transformation Test ----------------------------------------+;; Tests the pure transformation functions that convert dbdefs to Table/Field row maps.+;; These are the "debuggable" pure functions separated from the stateful insertion code.++(deftest ^:parallel fake-sync-transformation-test+ (mt/test-driver :redshift+ (testing "dbdef->fake-sync-rows produces correct Table and Field row maps"+ (let [dbdef {:database-name "transform-test"+ :table-definitions+ [{:table-name "users"+ :table-comment "User accounts"+ :field-definitions+ [{:field-name "name" :base-type :type/Text :field-comment "User name"}+ {:field-name "age" :base-type :type/Integer}+ {:field-name "org_id" :base-type :type/Integer :fk :organizations}]}+ {:table-name "organizations"+ :field-definitions+ [{:field-name "org_name" :base-type :type/Text}]}]}+ rows (@#'test.get-or-create/dbdef->fake-sync-rows :redshift 123 dbdef)]+ (testing "returns one entry per table"+ (is (= 2 (count rows)))+ (is (= ["users" "organizations"] (mapv :table-name rows))))++ (testing "table rows have correct structure"+ (let [users-table (:table-row (first rows))]+ (is (= 123 (:db_id users-table)))+ (is (= "transform_test_users" (:name users-table)))+ (is (= (redshift.tx/unique-session-schema) (:schema users-table)))+ (is (= "Users" (:display_name users-table)))+ (is (= "User accounts" (:description users-table)))+ (is (= "complete" (:initial_sync_status users-table)))))++ (testing "auto PK field is injected at position 0"+ (let [users-fields (:field-rows (first rows))+ pk-field (first users-fields)]+ (is (= 4 (count users-fields)) "Should have 4 fields: auto PK + 3 defined")+ (is (= "id" (:name pk-field)))+ (is (= :type/PK (:semantic_type pk-field)))+ (is (= 0 (:position pk-field)))))++ (testing "user-defined fields have correct positions and types"+ (let [users-fields (:field-rows (first rows))+ name-field (second users-fields)+ age-field (nth users-fields 2)+ fk-field (nth users-fields 3)]+ (is (= "name" (:name name-field)))+ (is (= 1 (:position name-field)))+ (is (= :type/Text (:base_type name-field)))+ (is (= "User name" (:description name-field)))++ (is (= "age" (:name age-field)))+ (is (= 2 (:position age-field)))+ (is (= :type/Integer (:base_type age-field)))++ (is (= "org_id" (:name fk-field)))+ (is (= 3 (:position fk-field)))+ (is (= :type/FK (:semantic_type fk-field)) "FK fields get :type/FK semantic type"))))))++ (testing "native type maps are handled correctly"+ (let [dbdef {:database-name "native-types"+ :table-definitions+ [{:table-name "binary_data"+ :field-definitions+ [{:field-name "raw_bytes"+ :base-type {:native "VARBYTE"}+ :effective-type :type/Text}+ {:field-name "multi_driver"+ :base-type {:natives {:redshift "SUPER" :postgres "JSONB"}}+ :effective-type :type/JSON}]}]}+ rows (@#'test.get-or-create/dbdef->fake-sync-rows :redshift 456 dbdef)+ fields (:field-rows (first rows))]+ (testing "{:native ...} form"+ (let [raw-field (second fields)] ; first is auto PK+ (is (= "VARBYTE" (:database_type raw-field)))+ (is (= :type/Text (:effective_type raw-field)))+ ;; When effective-type is provided, base_type uses it; otherwise would be :type/*+ (is (= :type/Text (:base_type raw-field)))))++ (testing "{:natives ...} form picks driver-specific type"+ (let [multi-field (nth fields 2)]+ (is (= "SUPER" (:database_type multi-field)))+ (is (= :type/JSON (:effective_type multi-field))))))))diff --git a/modules/drivers/redshift/test/metabase/test/data/redshift.clj b/modules/drivers/redshift/test/metabase/test/data/redshift.cljindex 1960e00b2c0..99baafbd1a0 100644--- a/modules/drivers/redshift/test/metabase/test/data/redshift.clj+++ b/modules/drivers/redshift/test/metabase/test/data/redshift.clj@@ -42,18 +42,19 @@;; extensions;; Time, UUID types aren't supported by redshift-(doseq [[base-type database-type] {:type/BigInteger "BIGINT"- :type/Boolean "BOOL"- :type/Date "DATE"- :type/DateTime "TIMESTAMP"- :type/Decimal "DECIMAL"- :type/Float "FLOAT8"- :type/Integer "INTEGER"+(doseq [[base-type database-type] {:type/BigInteger "BIGINT"+ :type/Boolean "BOOL"+ :type/Date "DATE"+ :type/DateTime "TIMESTAMP"+ :type/DateTimeWithTZ "TIMESTAMPTZ"+ :type/Decimal "DECIMAL"+ :type/Float "FLOAT8"+ :type/Integer "INTEGER";; Use VARCHAR because TEXT in Redshift is VARCHAR(256);; https://docs.aws.amazon.com/redshift/latest/dg/r_Character_types.html#r_Character_types-varchar-or-character-varying;; But don't use VARCHAR(MAX) either because of performance impact;; https://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-smallest-column-size.html- :type/Text "VARCHAR(1024)"}]+ :type/Text "VARCHAR(1024)"}](defmethod sql.tx/field-base-type->sql-type [:redshift base-type] [_ _] database-type));; If someone tries to run Time column tests with Redshift give them a heads up that Redshift does not support it@@ -88,7 +89,7 @@@db-routing-connection-details@db-connection-details))-(defmethod sql.tx/create-db-sql :redshift [& _] nil)+(defmethod sql.tx/create-db-sql :redshift [& _] nil)(defmethod sql.tx/drop-db-if-exists-sql :redshift [& _] nil)(defmethod sql.tx/pk-sql-type :redshift [_] "INTEGER IDENTITY(1,1)")@@ -196,7 +197,7 @@(defn- create-session-schema! [^java.sql.Connection conn](with-open [stmt (.createStatement conn)](doseq [^String sql [(format "DROP SCHEMA IF EXISTS \"%s\" CASCADE;" (unique-session-schema))- (format "CREATE SCHEMA \"%s\";" (unique-session-schema))]]+ (format "CREATE SCHEMA \"%s\";" (unique-session-schema))]](log/info (u/format-color 'blue "[redshift] %s" sql))(.execute stmt sql))))@@ -314,9 +315,19 @@;; if the ResultSet returns anything we know the table is already loaded.(.next rset)))))))+(defmethod driver/database-supports? [:redshift :test/use-fake-sync]+ [_driver _feature _database]+ ;; Use real sync in tests on master/release branches to catch sync regressions.+ ;; Use fake sync in tests on feature branches for speed (~10 min savings per test run).+ (not (tx/on-master-or-release-branch?)))++(defmethod tx/fake-sync-schema :redshift+ [_driver]+ (unique-session-schema))+(defn drop-if-exists-and-create-roles![driver details roles]- (let [spec (sql-jdbc.conn/connection-details->spec driver details)]+ (let [spec (sql-jdbc.conn/connection-details->spec driver details)](doseq [[role-name _table-perms] roles](let [role-name (sql.tx/qualify-and-quote driver role-name)](doseq [statement [(format "DROP USER IF EXISTS %s;" role-name)@@ -325,7 +336,7 @@(defn grant-table-perms-to-roles![driver details roles]- (let [spec (sql-jdbc.conn/connection-details->spec driver details)+ (let [spec (sql-jdbc.conn/connection-details->spec driver details)schema (sql.tx/qualify-and-quote driver (unique-session-schema))](doseq [[role-name table-perms] roles](let [role-name (sql.tx/qualify-and-quote driver role-name)]@@ -341,7 +352,7 @@(defmethod tx/drop-roles! :redshift[driver details roles _user-name]- (let [spec (sql-jdbc.conn/connection-details->spec driver details)+ (let [spec (sql-jdbc.conn/connection-details->spec driver details)schema (sql.tx/qualify-and-quote driver (unique-session-schema))](doseq [[role-name _table-perms] roles](let [role-name (sql.tx/qualify-and-quote driver role-name)]diff --git a/src/metabase/driver.clj b/src/metabase/driver.cljindex 1496913e8dd..b81cd8594d0 100644--- a/src/metabase/driver.clj+++ b/src/metabase/driver.clj@@ -779,6 +779,11 @@;; There are drivers that support uuids in queries, but not in create table as eg. Athena.:test/uuids-in-create-table-statements+ ;; Use fake sync for slow drivers (e.g., Redshift). When enabled, the test infrastructure directly inserts+ ;; Table/Field rows from the dbdef instead of calling sync-database!, which can take ~10 minutes for Redshift.+ ;; Generally should be enabled for any driver where sync-database! takes longer than a few seconds.+ :test/use-fake-sync+;; Does this driver support Metabase's database routing feature?:database-routing@@ -843,6 +848,7 @@:test/create-table-without-data true:test/dynamic-dataset-loading true:test/uuids-in-create-table-statements true+ :test/use-fake-sync false:metadata/table-existence-check false:metadata/table-writable-check false}](defmethod database-supports? [::driver feature] [_driver _feature _db] supported?))diff --git a/test/metabase/test/data/impl/get_or_create.clj b/test/metabase/test/data/impl/get_or_create.cljindex a13f2b62369..636bd8b566a 100644--- a/test/metabase/test/data/impl/get_or_create.clj+++ b/test/metabase/test/data/impl/get_or_create.clj@@ -9,6 +9,7 @@[metabase.models.humanization :as humanization][metabase.permissions.models.data-permissions :as data-perms][metabase.permissions.models.permissions-group :as perms-group]+ [metabase.sync.analyze :as sync.analyze][metabase.sync.core :as sync][metabase.sync.util :as sync-util][metabase.test.data.interface :as tx]@@ -116,29 +117,180 @@(defonce ^:private reference-sync-durations(delay (edn/read-string (slurp "test_resources/sync-durations.edn"))))+;;; -------------------------------------------------- Fake Sync --------------------------------------------------+;; For drivers with slow network sync (e.g., Redshift), we can skip sync-database! and directly insert+;; Table/Field rows from the dbdef. This saves ~10 minutes per test run.+;;+;; Architecture: The code is split into two parts for testability:+;; 1. Pure transformation functions (field-def->row, table-def->rows, dbdef->fake-sync-rows)+;; - Convert database definitions into row maps ready for insertion+;; - No database side effects, easily testable+;; 2. Insertion functions (insert-fake-sync-rows!, resolve-fk-relationships!)+;; - Actually insert the rows into the app DB+;; - Stateful, requires database connection++;; ---------------------- Pure Transformation Functions ----------------------++(defn- field-def->row+ "Convert a FieldDefinition to a Field row map (without table_id, added during insertion).+ Handles three forms of base-type:+ 1. {:native \"BINARY(8)\"} - driver-specific native type string+ 2. {:natives {:postgres \"BYTEA\" :redshift \"VARBYTE\"}} - per-driver native types+ 3. :type/Text - standard base type keyword"+ [driver position {:keys [field-name base-type semantic-type visibility-type+ effective-type coercion-strategy field-comment fk pk?]}]+ (let [database-type (cond+ (and (map? base-type) (contains? base-type :native))+ (:native base-type)++ (and (map? base-type) (contains? base-type :natives))+ (get-in base-type [:natives driver])++ :else+ ;; Use the SQL type from sql.tx/field-base-type->sql-type to get+ ;; the actual database type (e.g., "TIMESTAMPTZ" instead of "DateTimeWithTZ").+ ;; Use requiring-resolve to avoid cyclic dependency.+ ((requiring-resolve 'metabase.test.data.sql/field-base-type->sql-type) driver base-type))+ actual-base-type (if (map? base-type)+ (or effective-type :type/*)+ base-type)+ semantic-type (cond+ pk? :type/PK+ (some? fk) :type/FK+ :else semantic-type)]+ {:name field-name+ :display_name (humanization/name->human-readable-name :simple field-name)+ :database_type database-type+ :base_type actual-base-type+ :effective_type (or effective-type actual-base-type)+ :semantic_type semantic-type+ :coercion_strategy coercion-strategy+ :visibility_type (or visibility-type :normal)+ :description field-comment+ :position position+ :database_position position+ :active true}))++(defn- table-def->rows+ "Convert a TableDefinition to a map of {:table-name, :table-row, :field-rows}.+ This is a pure function - no database insertion."+ [driver db-id database-name {:keys [table-name table-comment field-definitions] :as _table-def}]+ (let [schema (tx/fake-sync-schema driver)+ qualified-name (tx/db-qualified-table-name database-name table-name)+ has-custom-pk? (some :pk? field-definitions)+ table-row {:db_id db-id+ :name qualified-name+ :schema schema+ :display_name (humanization/name->human-readable-name :simple table-name)+ :description table-comment+ :active true+ :visibility_type nil+ :initial_sync_status "complete"+ :field_order "database"}+ ;; Build field rows: auto PK (if needed) + user-defined fields+ pk-field-row (when-not has-custom-pk?+ (field-def->row driver 0+ {:field-name "id"+ :base-type (tx/id-field-type driver)+ :pk? true}))+ user-field-rows (map-indexed+ (fn [idx field-def]+ (field-def->row driver (if has-custom-pk? idx (inc idx)) field-def))+ field-definitions)+ field-rows (if pk-field-row+ (cons pk-field-row user-field-rows)+ user-field-rows)]+ {:table-name table-name+ :table-row table-row+ :field-rows (vec field-rows)}))++(defn- dbdef->fake-sync-rows+ "Convert database definition to table and field rows for fake sync.+ This is a pure function - no database insertion.+ Returns a vector of {:table-name, :table-row, :field-rows} maps."+ [driver db-id {:keys [database-name table-definitions]}]+ (mapv #(table-def->rows driver db-id database-name %) table-definitions))++;; ---------------------- Insertion Functions ----------------------++(defn- insert-fake-sync-rows!+ "Insert pre-computed table and field rows into the app DB.+ Returns map of table-name -> inserted table for FK resolution."+ [rows]+ (into {}+ (for [{:keys [table-name table-row field-rows]} rows]+ (let [table (first (t2/insert-returning-instances! :model/Table table-row))]+ (doseq [field-row field-rows]+ (t2/insert-returning-instances! :model/Field (assoc field-row :table_id (:id table))))+ [table-name table]))))++(defn- resolve-fk-relationships!+ "Second pass: resolve FK relationships by setting fk_target_field_id on FK fields."+ [table-name->table {:keys [table-definitions]}]+ (doseq [{:keys [table-name field-definitions]} table-definitions+ :let [table (get table-name->table table-name)]+ {:keys [field-name fk]} field-definitions+ :when fk]+ (let [target-table-name (if (keyword? fk) (name fk) fk)+ target-table (get table-name->table target-table-name)+ target-pk-field (when target-table+ (t2/select-one :model/Field+ :table_id (:id target-table)+ :semantic_type :type/PK))+ source-field (t2/select-one :model/Field+ :table_id (:id table)+ :%lower.name (u/lower-case-en field-name))]+ (when (and source-field target-pk-field)+ (t2/update! :model/Field (:id source-field)+ {:fk_target_field_id (:id target-pk-field)})))))++;; ---------------------- Main Entry Point ----------------------++(defn- fake-sync-database!+ "Insert Table and Field rows directly from the dbdef instead of calling sync-database!.+ This skips network calls for metadata sync, which is useful for slow remote databases like Redshift.+ When scan is :full, also runs fingerprinting to enable fingerprint-dependent tests."+ [driver {:keys [database-name] :as database-definition} db scan]+ (log/infof "Using FAKE SYNC for %s Database %s (skipping network calls to database)" driver database-name)+ (let [rows (dbdef->fake-sync-rows driver (:id db) database-definition)+ table-name->tbl (insert-fake-sync-rows! rows)]+ (resolve-fk-relationships! table-name->tbl database-definition)+ ;; Only run fingerprinting for :full scan, matching the real sync behavior+ (when (= scan :full)+ (log/info "Running real fingerprinting for :full scan after fake sync")+ (sync.analyze/analyze-db! db))))++;;; ----------------------------------------------- End Fake Sync -----------------------------------------------+(defn- sync-newly-created-database! [driver {:keys [database-name], :as database-definition} connection-details db](assert (= (humanization/humanization-strategy) :simple)"Humanization strategy is not set to the default value of :simple! Metadata will be broken!")(try(u/with-timeout sync-timeout-ms- (let [reference-duration (or (some-> (get @reference-sync-durations database-name) u/format-nanoseconds)- "NONE")- full-sync? (= database-name "test-data")]- (u/profile (format "%s %s Database %s (reference H2 duration: %s)"- (if full-sync? "Sync" "QUICK sync") driver database-name reference-duration)- ;; only do "quick sync" for non `test-data` datasets, because it can take literally MINUTES on CI.- ;;- ;; MEGA SUPER HACK !!! I'm experimenting with this so Redshift tests stop being so flaky on CI! It seems like- ;; if we ever delete a table sometimes Redshift still thinks it's there for a bit and sync can fail because it- ;; tries to sync a Table that is gone! So enable normal resilient sync behavior for Redshift tests to fix the- ;; flakes. If this fixes things I'll try to come up with a more robust solution. -- Cam 2024-07-19. See #45874- (binding [sync-util/*log-exceptions-and-continue?* (= driver :redshift)]- (sync/sync-database! db {:scan (if full-sync? :full :schema)}))- ;; add extra metadata for fields- (try- (add-extra-metadata! database-definition db)- (catch Throwable e- (log/error e "Error adding extra metadata"))))))+ (let [;; only do "full sync" (with fingerprinting) for test-data, because it can take literally MINUTES on CI.+ scan (if (= database-name "test-data") :full :schema)]+ (if (driver/database-supports? driver :test/use-fake-sync nil)+ ;; Use fake sync - directly insert Table/Field rows from dbdef, skipping network calls+ (fake-sync-database! driver database-definition db scan)+ ;; Original sync path - call sync-database! against the actual database+ (let [reference-duration (or (some-> (get @reference-sync-durations database-name) u/format-nanoseconds)+ "NONE")+ full-sync? (= scan :full)]+ (u/profile (format "%s %s Database %s (reference H2 duration: %s)"+ (if full-sync? "Sync" "QUICK sync") driver database-name reference-duration)+ ;; only do "quick sync" for non `test-data` datasets, because it can take literally MINUTES on CI.+ ;;+ ;; MEGA SUPER HACK !!! I'm experimenting with this so Redshift tests stop being so flaky on CI! It seems like+ ;; if we ever delete a table sometimes Redshift still thinks it's there for a bit and sync can fail because it+ ;; tries to sync a Table that is gone! So enable normal resilient sync behavior for Redshift tests to fix the+ ;; flakes. If this fixes things I'll try to come up with a more robust solution. -- Cam 2024-07-19. See #45874+ (binding [sync-util/*log-exceptions-and-continue?* (= driver :redshift)]+ (sync/sync-database! db {:scan scan}))+ ;; add extra metadata for fields+ (try+ (add-extra-metadata! database-definition db)+ (catch Throwable e+ (log/error e "Error adding extra metadata"))))))))(catch Throwable e(let [message (format "Failed to sync test database %s: %s" (pr-str database-name) (ex-message e))e (ex-info messagediff --git a/test/metabase/test/data/interface.clj b/test/metabase/test/data/interface.cljindex ee320e2df48..cd945cf3278 100644--- a/test/metabase/test/data/interface.clj+++ b/test/metabase/test/data/interface.clj@@ -10,6 +10,7 @@[buddy.core.codecs :as codecs][buddy.core.hash :as buddy-hash][clojure.core.memoize :as memoize]+ [clojure.java.shell :as shell][clojure.string :as str][clojure.test :as t][clojure.tools.reader.edn :as edn]@@ -339,7 +340,7 @@"Run [[metabase.test.data.interface/after-run]] methods for drivers."[_options](doseq [driver (tx.env/test-drivers)- :when (isa? driver/hierarchy driver ::test-extensions)]+ :when (isa? driver/hierarchy driver ::test-extensions)](log/infof "Running after-run hooks for %s..." driver)(after-run driver)))@@ -515,6 +516,53 @@[_driver _dbdef]false)+(defmulti fake-sync-schema+ "Return the schema name to use for fake sync Table rows. Returns nil by default.+ Drivers opting into fake sync (via `:test/use-fake-sync` feature) should implement this to return+ their session schema name."+ {:arglists '([driver]), :added "0.56.0"}+ dispatch-on-driver-with-test-extensions+ :hierarchy #'driver/hierarchy)++(defmethod fake-sync-schema ::test-extensions+ [_driver]+ nil)++(defn on-master-or-release-branch?+ "Returns true if running on master or a release-* branch.+ Detection methods (in priority order):+ 1. GITHUB_REF_NAME env var (set in GitHub Actions CI)+ 2. Git branch name via shell (local development)++ Used to conditionally enable features like fake-sync that should be disabled+ on master/release branches to ensure full test coverage."+ []+ (let [branch-name (or (System/getenv "GITHUB_REF_NAME")+ (try (-> (shell/sh "git" "rev-parse" "--abbrev-ref" "HEAD")+ :out+ str/trim)+ (catch Exception _ nil)))]+ (boolean+ (and branch-name+ (or (= branch-name "master")+ (str/starts-with? branch-name "release-"))))))++(defmacro with-driver-supports-feature!+ "Temporarily override `driver/database-supports?` to return a specific value for a driver/feature combo.+ Useful for testing code paths that depend on driver features.++ Example:+ (with-driver-supports-feature! [:redshift :test/use-fake-sync false]+ (do-something-that-requires-real-sync))"+ [[driver feature value] & body]+ `(let [original-db-supports?# driver/database-supports?]+ (with-redefs [driver/database-supports?+ (fn [driver-arg# feature-arg# db-arg#]+ (if (and (= driver-arg# ~driver) (= feature-arg# ~feature))+ ~value+ (original-db-supports?# driver-arg# feature-arg# db-arg#)))]+ ~@body)))+(defmulti track-dataset"Track the creation or the usage of the database.This is useful for cloud databases with shared state to ensure that stale datasets can be deleted and dataset loading is not done more than necessary. Pairs well with [[dataset-already-loaded?]]"@@ -589,7 +637,7 @@([_ aggregation-type](assert (#{:count :cum-count} aggregation-type)){:base_type (case aggregation-type- :count :type/BigInteger+ :count :type/BigInteger:cum-count :type/Decimal):semantic_type :type/Quantity:name "count"@@ -903,7 +951,7 @@(-> fk-table(str/replace #"ies$" "y")(str/replace #"s$" "")- (str \_ (flatten-field-name fk-dest-name))))))+ (str \_ (flatten-field-name fk-dest-name))))))(mu/defn flattened-dataset-definition"Create a flattened version of `dbdef` by following resolving all FKs and flattening all rows into the table with