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
Create stub databases for missing databases on serdes import (#83574)
Alexander Polyankin2dd2330f979d
diff --git a/e2e/support/assets/example_synced_stub_database/collections/StubDbCollection12345_stub_database_collection/StubDbCollection12345_stub_database_collection.yaml b/e2e/support/assets/example_synced_stub_database/collections/StubDbCollection12345_stub_database_collection/StubDbCollection12345_stub_database_collection.yamlnew file mode 100644index 00000000000..614760eed75--- /dev/null+++ b/e2e/support/assets/example_synced_stub_database/collections/StubDbCollection12345_stub_database_collection/StubDbCollection12345_stub_database_collection.yaml@@ -0,0 +1,18 @@+description: null+archived: false+slug: stub_database_collection+archive_operation_id: null+name: Stub Database Collection+personal_owner_id: null+type: null+is_sample: false+parent_id: null+serdes/meta:+- model: Collection+ id: StubDbCollection12345+ label: stub_database_collection+archived_directly: null+entity_id: StubDbCollection12345+namespace: null+created_at: '2026-10-05T09:00:00.000000-07:00'+is_remote_synced: truediff --git a/e2e/support/assets/example_synced_stub_database/collections/StubDbCollection12345_stub_database_collection/cards/StubDbQuestion1234567_stub_database_question.yaml b/e2e/support/assets/example_synced_stub_database/collections/StubDbCollection12345_stub_database_collection/cards/StubDbQuestion1234567_stub_database_question.yamlnew file mode 100644index 00000000000..8a57bea0a58--- /dev/null+++ b/e2e/support/assets/example_synced_stub_database/collections/StubDbCollection12345_stub_database_collection/cards/StubDbQuestion1234567_stub_database_question.yaml@@ -0,0 +1,58 @@+description: null+archived: false+collection_position: null+source_card_id: null+table_id:+- Stub Postgres+- public+- products+result_metadata: null+card_schema: 22+database_id: Stub Postgres+enable_embedding: false+collection_id: StubDbCollection12345+query_type: query+name: Stub Database Question+document_id: null+type: question+creator_id: [email protected]+made_public_by_id: null+embedding_params: null+dataset_query:+ database: Stub Postgres+ type: query+ query:+ source-table:+ - Stub Postgres+ - public+ - products+ fields:+ - - field+ - - Stub Postgres+ - public+ - products+ - title+ - null+ order-by:+ - - asc+ - - field+ - - Stub Postgres+ - public+ - products+ - id+ - null+ limit: 1+parameter_mappings: []+serdes/meta:+- model: Card+ id: StubDbQuestion1234567+ label: stub_database_question+display: table+archived_directly: false+entity_id: StubDbQuestion1234567+collection_preview: true+visualization_settings: {}+parameters: []+dashboard_id: null+created_at: '2026-10-05T09:00:00.000000-07:00'+public_uuid: nulldiff --git a/e2e/support/helpers/e2e-remote-sync-helpers.ts b/e2e/support/helpers/e2e-remote-sync-helpers.tsindex f345dcf9738..24504552d16 100644--- a/e2e/support/helpers/e2e-remote-sync-helpers.ts+++ b/e2e/support/helpers/e2e-remote-sync-helpers.ts@@ -21,6 +21,9 @@ export const SYNCED_TRANSFORMS_COLLECTION_FIXTURE_PATH ="/e2e/support/assets/example_synced_transforms_collection";export const SYNCED_LIBRARY_FIXTURE_PATH =Cypress.config("projectRoot") + "/e2e/support/assets/example_synced_library";+export const SYNCED_STUB_DATABASE_FIXTURE_PATH =+ Cypress.config("projectRoot") ++ "/e2e/support/assets/example_synced_stub_database";// Copy the sample synced collection from the fixture folder to the working directoryexport const copySyncedCollectionFixture = () => {@@ -44,6 +47,14 @@ export const copySyncedLibraryFixture = () => {});};+// Copy a synced collection whose card references a database the instance doesn't have+export const copySyncedStubDatabaseFixture = () => {+ cy.task("copyDirectory", {+ source: SYNCED_STUB_DATABASE_FIXTURE_PATH,+ destination: LOCAL_GIT_PATH,+ });+};+export const checkoutSyncedCollectionBranch = (branch: string) => {cy.exec("git -C " + LOCAL_GIT_PATH + ` checkout -b '${branch}'`);};diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.tsindex ef7d7f01254..6084ce3a046 100644--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts@@ -1,6 +1,6 @@import yaml from "js-yaml";-import { WRITABLE_DB_ID } from "e2e/support/cypress_data";+import { QA_POSTGRES_PORT, WRITABLE_DB_ID } from "e2e/support/cypress_data";import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import {ADMIN_PERSONAL_COLLECTION_ID,@@ -8,6 +8,7 @@ import {} from "e2e/support/cypress_sample_instance_data";import type {Collection,+ Database,RemoteSyncDependencyErrorResponse,} from "metabase-types/api";@@ -31,6 +32,8 @@ const MONTHLY_DEPENDENT_NAME = "Monthly Summary";const SNIPPET_NAME = "active_users";const SNIPPET_QUESTION_NAME = "Snippet Dependent Question";const PERSONAL_QUESTION_NAME = "Personal Source Question";+const STUB_DATABASE_NAME = "Stub Postgres";+const STUB_QUESTION_NAME = "Stub Database Question";const setup = (snapshot = "default") => {H.restore(snapshot);@@ -1289,6 +1292,64 @@ describe("Remote Sync", () => {});});});++ describe("stub databases", { tags: ["@external"] }, () => {+ beforeEach(() => {+ setup();+ });++ it("imports a card on a missing database as a stub that runs once connected", () => {+ H.copySyncedStubDatabaseFixture();+ H.commitToRepo();+ H.configureGitAndPullChanges("read-write");++ cy.log("the missing database is created as a stub");+ cy.visit("/admin/databases");+ cy.findByRole("link", { name: STUB_DATABASE_NAME })+ .closest("tr")+ .findByText("Stubbed")+ .should("be.visible");+ cy.findByRole("link", { name: STUB_DATABASE_NAME }).click();+ cy.findByTestId("database-connection-info-section")+ .findByText(+ "This database has placeholder connection details. Replace that with actual connection details to make this connection Active.",+ )+ .should("be.visible");++ cy.log("connect the stub database");+ cy.intercept("PUT", "/api/database/*").as("updateDatabase");+ cy.button("Edit connection details").click();+ cy.findByTestId("database-form").within(() => {+ cy.findByLabelText(/Host/).type("localhost");+ cy.findByLabelText(/Port/).type(String(QA_POSTGRES_PORT));+ cy.findByLabelText(/Database name/).type("sample");+ cy.findByLabelText(/Username/).type("metabase");+ cy.findByLabelText(/Password/).type("metasample123");+ });+ cy.button("Save changes").click();+ cy.wait("@updateDatabase");++ cy.request<{ data: Database[] }>("GET", "/api/database").then(+ ({ body }) => {+ const database = body.data.find(+ ({ name }) => name === STUB_DATABASE_NAME,+ );+ expect(database?.is_stub).to.equal(false);+ H.waitForSyncToFinish({+ dbId: database?.id,+ tableName: "products",+ tableAlias: "productsTable",+ });+ },+ );++ cy.log("the imported card now runs against the connected database");+ cy.visit("/collection/root");+ H.goToSyncedCollection("Stub Database Collection");+ H.collectionTable().findByText(STUB_QUESTION_NAME).click();+ H.tableInteractive().findByText("Rustic Paper Wallet").should("exist");+ });+ });});const ensureSyncedCollectionIsVisible = () => {diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/db.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/db.cljindex 62720d05919..c42ca1fda65 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_config/db.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/db.clj@@ -68,11 +68,15 @@[](t2/exists? :model/Database :is_sample true))-(mu/defn database-id-by-engine-and-name- "The ID of the Database of `engine` named `database-name`, or nil."- [engine :- :string- database-name :- :string]- (t2/select-one-pk :model/Database :engine engine :name database-name))+(mu/defn database-by-name+ "The `:id` and `:is_stub` of the Database named `database-name`, or nil."+ [database-name :- :string]+ (t2/select-one [:model/Database :id :is_stub] :name database-name))++(mu/defn database+ "The Database with `database-id`, or nil."+ [database-id :- ::lib.schema.id/database]+ (t2/select-one :model/Database database-id))(mu/defn insert-database!"Insert `database` and return the new instance."diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.cljindex c06d20007e2..a5ff8b360b3 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.clj@@ -93,6 +93,13 @@(log/info (u/format-color :green "Recreating Sample Database from is_sample config entry"))(sample-data/extract-and-sync-sample-database!))))+(defn- sync-if-configured!+ "Kick off a sync of `database` when syncing databases from the config file is enabled."+ [database]+ (if (advanced-config.settings/config-from-file-sync-databases)+ (quick-task/submit-task! (fn [] (sync/sync-database! database)))+ (log/info "Sync on database creation when initializing from file is disabled. Skipping sync.")))+(defn- init-from-config-file)(throw (ex-info (format "To delete database %s set `delete` to %s" (pr-str (:name database)) (pr-str magic-request)){:database-name (:name database)})))- (when-let [existing-database-id (advanced-config.db/database-id-by-engine-and-name (:engine database) (:name database))]- (log/info (u/format-color :blue "Deleting Database %s with ID %s" (:engine database) existing-database-id))+ (when-let [{existing-database-id :id} (advanced-config.db/database-by-name (:name database))]+ (log/info (u/format-color :blue "Deleting Database with ID %s" existing-database-id))(advanced-config.db/delete-database! existing-database-id)))(:is_sample database)@@ -119,29 +126,30 @@(when-not (:is_stub database)(driver.u/with-database-network-policy database(driver.u/can-connect-with-details? (keyword (:engine database)) (:details database) :throw-exceptions)))- (if-let [existing-database-id (advanced-config.db/database-id-by-engine-and-name (:engine database) (:name database))]- (if (:is_stub database)- ;; A stub entry is just a placeholder to satisfy serdes references. If a real database- ;; with this name+engine already exists, leave it alone — overwriting it with `:details {}`- ;; and `:is_stub true` would break a working database.- (log/info (u/format-color :yellow "Database %s with ID %s already exists; ignoring stub entry"- (:engine database) existing-database-id))- (let [database (cond-> database- (:is_attached_dwh database) strip-attached-dwh-update-ks)]- (log/info (u/format-color :blue "Updating Database %s with ID %s" (:engine database) existing-database-id))- (advanced-config.db/update-database! existing-database-id (normalize-settings database))))- (do- (log/info (u/format-color :green "Creating new %s Database" (:engine database)))- (let [db (advanced-config.db/insert-database! (normalize-settings database))]- (cond- (:is_stub database)+ (let [existing (advanced-config.db/database-by-name (:name database))]+ (cond+ (and existing (:is_stub database))+ ;; A stub entry only creates a missing database; it never overwrites an existing one with `:details {}`.+ (log/info (u/format-color :yellow "Database with ID %s already exists; ignoring stub entry" (:id existing)))++ existing+ (do+ (log/info (u/format-color :blue "Updating Database %s with ID %s" (:engine database) (:id existing)))+ (advanced-config.db/update-database! (:id existing)+ (cond-> (normalize-settings database)+ (:is_attached_dwh database) strip-attached-dwh-update-ks+ (:is_stub existing) (assoc :is_stub false+ :initial_sync_status "incomplete")))+ (when (:is_stub existing)+ (sync-if-configured! (advanced-config.db/database (:id existing)))))++ :else+ (let [db (advanced-config.db/insert-database! (cond-> (normalize-settings database)+ (:is_stub database) (assoc :initial_sync_status "complete")))]+ (log/info (u/format-color :green "Created new %s Database" (:engine database)))+ (if (:is_stub database)(log/info "Created stub database; skipping sync.")-- (advanced-config.settings/config-from-file-sync-databases)- (quick-task/submit-task! (fn [] (sync/sync-database! db)))-- :else- (log/info "Sync on database creation when initializing from file is disabled. Skipping sync."))))))))+ (sync-if-configured! db))))))))(defmethod advanced-config.file.i/initialize-section! :databases[_section-name databases]diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex 0634f51aeb3..f02405f45b8 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -122,23 +122,13 @@(remove nil?)(str/join " ")))-(defn- cause-with-error- "Returns the first exception in `e`'s cause chain whose ex-data `:error` is `error-type`, or nil."- [e error-type]- (->> (iterate ex-cause e)- (take-while some?)- (some (fn [ex]- (when (= error-type (:error (ex-data ex)))- ex)))))-(defn source-error-message"Constructs user-friendly error messages from remote sync source exceptions.Takes a throwable exception and returns a string message that categorizes the error (network, authentication,repository not found, branch, or generic) based on the exception type and message content."[e]- (let [missing-db (cause-with-error e :metabase.models.serialization.resolve.db/database-not-found)- message (or (ex-message e) "")]+ (let [message (or (ex-message e) "")](cond(or (instance? java.net.UnknownHostException e)(instance? java.net.UnknownHostException (ex-cause e)))@@ -164,11 +154,6 @@(missing-reference-message {:missing {:model model :id id}:referrer referrer}))- ;; the entity that failed to load is the one holding the reference to the absent database- missing-db- (missing-reference-message {:missing {:model "Database" :id (:db-name (ex-data missing-db))}- :referrer (:entity (ex-data e))})-(= (:error (ex-data e)) :metabase-enterprise.serialization.v2.load/load-failure)(let [{:keys [entity stripped-keys]} (ex-data e)](load-failure-message {:entity entitydiff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.cljindex fcc9f84239f..6ad42b87aa1 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj@@ -218,8 +218,12 @@(try(with-retries 3 200(fn []- (t2/with-transaction [_tx]- (serdes/load-one! ingested local-or-nil))))+ (try+ (t2/with-transaction [_tx]+ (serdes/load-one! ingested local-or-nil))+ (catch Throwable e+ (serdes/reset-import-cache!)+ (throw e)))))ctx(catch Exception e;; if the entity was part of a dependency loop, a stripped version of it may already be committed; withdiff --git a/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.cljindex a97874a303e..7dc08ae1f3b 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_config/file/databases_test.clj@@ -139,7 +139,7 @@(t2/delete! :model/Database :name test-db-name))))))(deftest init-from-config-file-stub-does-not-clobber-existing-test- (testing "Stub config entries with the same name+engine as an existing real DB must not overwrite it.+ (testing "Stub config entries with the same name as an existing real DB must not overwrite it, whatever their engine.This protects round-trip workflows where /config emits stubs for the same instance's other DBs."(mt/with-temporary-setting-values [config-from-file-sync-databases false](mt/with-temp [:model/Database existing {:name test-db-name@@ -149,7 +149,7 @@(advanced-config.file/initialize!{:version 1:config {:databases [{:name test-db-name- :engine "h2"+ :engine "postgres":details {}:is_stub true}]}})))(let [reloaded (t2/select-one :model/Database :id (:id existing))]@@ -158,6 +158,31 @@(testing "existing :is_stub flag is preserved (still false)"(is (false? (:is_stub reloaded)))))))))+(deftest init-from-config-file-connects-existing-stub-test+ (testing "A real config entry named like an existing stub connects that stub in place, whatever its engine"+ (mt/with-temporary-setting-values [config-from-file-sync-databases true]+ (let [db-type (mdb/db-type)+ details (:details (mt/with-driver db-type (mt/db)))+ submit-calls (atom 0)]+ (mt/with-temp [:model/Database stub {:name test-db-name+ :engine (if (= db-type :postgres) "mysql" "postgres")+ :details {}+ :is_stub true+ :initial_sync_status "complete"}]+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [_] (swap! submit-calls inc))]+ (is (= :ok+ (advanced-config.file/initialize!+ {:version 1+ :config {:databases [{:name test-db-name+ :engine (name db-type)+ :details details}]}}))))+ (is (= 1 (t2/count :model/Database :name test-db-name)))+ (is (=? {:engine db-type+ :is_stub false+ :initial_sync_status "incomplete"}+ (t2/select-one :model/Database :id (:id stub))))+ (is (= 1 @submit-calls)))))))+(deftest init-from-config-file-sample-recreates-missing-test(testing "An is_sample entry triggers recreation of the Sample Database when one is not present."(let [delete-existing! (fn []diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.cljindex 320d2c0e316..bb08537f666 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj@@ -130,28 +130,6 @@(format "Database (`%s`)" db-name))(format "expected %s to be quoted verbatim" (pr-str db-name)))))))-(deftest source-error-message-database-not-found-test- (testing "source-error-message names the card and the missing database for FK database-not-found errors"- (let [cause (ex-info "table id present, but database not found: [clickhouse nil some_table]"- {:table-id ["clickhouse" nil "some_table"]- :db-name "clickhouse"- :error :metabase.models.serialization.resolve.db/database-not-found})- e (ex-info "Failed to load into database for Card abc123"- {:path "Card abc123"- :entity {:model "Card" :id "abc123" :name "Some card"}}- cause)]- (is (= (str "Import failed: Card `Some card` (`abc123`) references Database (`clickhouse`), which does not "- "exist on this instance. Make sure all referenced databases and other dependencies are set up "- "before importing.")- (impl/source-error-message e)))))- (testing "database-not-found is found anywhere in the cause chain, not only at the immediate cause"- (let [root (ex-info "table id present, but database not found: [clickhouse nil t]"- {:db-name "clickhouse"- :error :metabase.models.serialization.resolve.db/database-not-found})- middle (ex-info "wrapped by an intervening helper" {} root)- e (ex-info "Failed to load into database for Card abc123" {:path "Card abc123"} middle)]- (is (str/includes? (impl/source-error-message e) "Database (`clickhouse`)")))))-(deftest source-error-message-load-failure-test(testing "source-error-message names the entity and the underlying reason (GHY-3992)"(let [cause (ex-info "NOT NULL constraint failed: report_card.display" {})@@ -186,15 +164,6 @@(is (= (str "Import failed: could not save Dashboard `Sales` (`xyz`). some db error. ""It may have been saved without: `dashcards`, `parameters`.")(impl/source-error-message e)))))- (testing "a database-not-found cause still wins over the generic load-failure branch"- (let [cause (ex-info "table id present, but database not found: [ch nil t]"- {:db-name "ch"- :error :metabase.models.serialization.resolve.db/database-not-found})- e (ex-info "Failed to load into database for Card abc123"- {:entity {:model "Card" :id "abc123" :name "Some card"}- :error :metabase-enterprise.serialization.v2.load/load-failure}- cause)]- (is (str/includes? (impl/source-error-message e) "references Database (`ch`)"))))(testing "a tenant-collection cause still wins over the generic load-failure branch"(let [cause (ex-info "Can't create a tenant collection without tenants enabled" {})e (ex-info "Failed to load into database for Collection abc"diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.cljindex 3a6f83eb6e7..ee1ab298733 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj@@ -525,8 +525,7 @@(is (= #{[{:id dash-eid :model "Dashboard"}][{:id coll-eid :model "Collection"}][{:id model-eid :model "Card"}]- [{:id card-eid :model "Card"}]- [{:id "Linked database" :model "Database"}]}+ [{:id card-eid :model "Card"}]}(set (serdes/deserialization-dependencies extracted-dashboard))))(storage/store! (seq extraction) (storage.files/file-writer dump-dir))))(testing "ingest and load"@@ -1089,6 +1088,38 @@(is (= (:id table) (lib/primary-source-table-id imported)))(is (=? [[:field {} (:id field)]] (lib/fields imported)))))))+(deftest card-on-missing-database-imports-into-stub-database-test+ (testing "Importing a Card whose database is absent from the export and the target creates a stub database"+ (ts/with-random-dump-dir [dump-dir "serdesv2-"]+ (ts/with-dbs [source-db dest-db]+ (ts/with-db source-db+ (let [db (ts/create! :model/Database :name "source-only-db" :engine :h2)+ table (ts/create! :model/Table :name "customers" :schema "PUBLIC" :db_id (:id db))+ coll (ts/create! :model/Collection :name "coll")+ mp (lib-be/application-database-metadata-provider (:id db))]+ (ts/create! :model/Card+ :name "Customers"+ :collection_id (:id coll)+ :database_id (:id db)+ :table_id (:id table)+ :dataset_query (lib/query mp (lib.metadata/table mp (:id table))))+ (storage/store! (serdes/with-cache (into [] (extract/extract {:no-settings true+ :no-data-model true})))+ (storage.files/file-writer dump-dir))))+ (ts/with-db dest-db+ (is (not (t2/exists? :model/Database :name "source-only-db")))+ (is (serdes/with-cache (serdes.load/load-metabase! (ingest/ingest-yaml dump-dir))))+ (let [stub (t2/select-one :model/Database :name "source-only-db")+ table (t2/select-one :model/Table :db_id (:id stub) :name "customers")]+ (is (=? {:engine :postgres+ :details {}+ :is_stub true}+ stub))+ (is (=? {:schema "PUBLIC" :active false} table))+ (is (=? {:database_id (:id stub)+ :table_id (:id table)}+ (t2/select-one :model/Card :name "Customers")))))))))+(deftest orphaned-transform-yaml-round-trip-test(testing "A Transform whose source database was deleted round-trips through YAML storage as a tombstone"(mt/with-premium-features #{:transforms-basic}diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.cljindex c5042f56b23..7833e749dfb 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj@@ -315,9 +315,8 @@:created_at string?}ser))(is (not (contains? ser :id)))- (testing "cards depend on their Collection and the query's Database (not the Tables/Fields it references)"- (is (= #{[{:model "Database" :id "My Database"}]- [{:model "Collection" :id coll-eid}]}+ (testing "cards depend on their Collection (not the Database/Tables/Fields the query references)"+ (is (= #{[{:model "Collection" :id coll-eid}]}(set (serdes/deserialization-dependencies ser))))))(let [ser (serdes/extract-one "Card" {} (t2/select-one :model/Card :id c2-id))](is (=? {:serdes/meta [{:model "Card" :id c2-eid :label "second_question"}]@@ -333,9 +332,8 @@(is (not (contains? ser :id)))(is (not (contains? ser :table_id)) "table_id always skipped for cards — re-derived on import")(is (contains? ser :database_id) "database_id kept when query is empty")- (testing "cards depend on their Database (kept because query is empty), Collection, and parameter_mappings card refs (not the Fields)"- (is (= #{[{:model "Database" :id "My Database"}]- [{:model "Collection" :id coll-eid}]+ (testing "cards depend on their Collection and parameter_mappings card refs (not the Database or the Fields)"+ (is (= #{[{:model "Collection" :id coll-eid}][{:model "Card" :id c1-eid}]}(set (serdes/deserialization-dependencies ser))))))(let [ser (serdes/extract-one "Card" {} (t2/select-one :model/Card :id c3-id))]@@ -367,9 +365,8 @@:created_at string?}ser))(is (not (contains? ser :id)))- (testing "cards depend on their Database (kept, query empty) and Collection (not the Fields in visualization_settings)"- (is (= #{[{:model "Database" :id "My Database"}]- [{:model "Collection" :id coll-eid}]}+ (testing "cards depend on their Collection (not the Database or the Fields in visualization_settings)"+ (is (= #{[{:model "Collection" :id coll-eid}]}(set (serdes/deserialization-dependencies ser)))))))(testing "Cards can be based on other cards"(let [ser (serdes/extract-one "Card" {} (t2/select-one :model/Card :id c5-id))]@@ -384,9 +381,8 @@(is (not (contains? ser :id)))(is (not (contains? ser :table_id)) "table_id stripped")(is (not (contains? ser :database_id)) "database_id stripped — derivable from query")- (testing "and depend on their Collection, Database (from query), and the upstream Card"- (is (= #{[{:model "Database" :id "My Database"}]- [{:model "Collection" :id coll-eid}]+ (testing "and depend on their Collection and the upstream Card"+ (is (= #{[{:model "Collection" :id coll-eid}][{:model "Card" :id c4-eid}]}(set (serdes/deserialization-dependencies ser)))))))(testing "Dashboards include their Dashcards"@@ -416,10 +412,9 @@:created_at string?}ser))(is (not (contains? ser :id)))- (testing "and depend on all referenced cards and actions, plus the Database of fields referenced in visualization_settings"+ (testing "and depend on all referenced cards and actions"(is (= #{[{:model "Card" :id c2-eid}][{:model "Action" :id action-eid}]- [{:model "Database" :id "My Database"}][{:model "Collection" :id (:entity_id (personal-collection dave-id))}]}(set (serdes/deserialization-dependencies ser)))))))(testing "Dashboards with parameters where the source is a card"@@ -435,9 +430,7 @@:values_source_type :card}]}ser))(is (= #{[{:model "Collection" :id (:entity_id (personal-collection dave-id))}]- [{:model "Card" :id c1-eid}]- ;; the parameter's value_field references a Field, but only its Database is a dependency- [{:model "Database", :id "My Database"}]}+ [{:model "Card" :id c1-eid}]}(set (serdes/deserialization-dependencies ser))))))(testing "Cards with parameters where the source is a card"(let [ser (ts/extract-one "Dashboard" param-dash-id)]@@ -452,9 +445,7 @@:values_source_type :card}]}ser))(is (= #{[{:model "Collection" :id (:entity_id (personal-collection dave-id))}]- [{:model "Card" :id c1-eid}]- ;; the parameter's value_field references a Field, but only its Database is a dependency- [{:model "Database", :id "My Database"}]}+ [{:model "Card" :id c1-eid}]}(set (serdes/deserialization-dependencies ser))))))(testing "collection filtering based on :user option"(testing "only unowned collections are returned with no user"@@ -558,8 +549,8 @@ser))(is (not (contains? ser :id)))(is (not (contains? ser :field_id)) ":field_id is dropped; it's implied by the path")- (testing "depend only on the Database; the Table and Field are synthesized on import if missing"- (is (= #{[{:model "Database" :id "My Database"}]}+ (testing "have no dependencies; the Database, Table and Field are synthesized on import if missing"+ (is (= #{}(set (serdes/deserialization-dependencies ser)))))))(testing "a foreign key dimension is its own entity under its Field"(let [ser (ts/extract-one "Dimension" (t2/select-one-fn :entity_id :model/Dimension :field_id fk-id))]@@ -571,8 +562,8 @@:human_readable_field_id ["My Database" "PUBLIC" "Customers" "name"]:created_at string?}ser))- (testing "depend only on the Database; the FK target and human-readable Fields are synthesized on import if missing"- (is (= #{[{:model "Database" :id "My Database"}]}+ (testing "have no dependencies; the Database, FK target and human-readable Fields are synthesized on import if missing"+ (is (= #{}(set (serdes/deserialization-dependencies ser)))))))(testing "Fields carry no dimensions"(is (not (contains? (ts/extract-one "Field" fk-id) :dimensions)))))))@@ -826,8 +817,8 @@:created_at string?}ser))(is (not (contains? ser :id)))- (testing "depend only on the Database; the Table/Fields from the definition are not dependencies"- (is (= #{[{:model "Database" :id "My Database"}]}+ (testing "have no dependencies; the Database/Table/Fields from the definition are not dependencies"+ (is (= #{}(set (serdes/deserialization-dependencies ser))))))))))(defn- mbql5-measure-definition@@ -867,8 +858,8 @@:created_at string?}ser))(is (not (contains? ser :id)))- (testing "depend only on the Database; the Table/Fields from the definition are not dependencies"- (is (= #{[{:model "Database" :id "My Database"}]}+ (testing "have no dependencies; the Database/Table/Fields from the definition are not dependencies"+ (is (= #{}(set (serdes/deserialization-dependencies ser))))))))))))(deftest measure-referencing-measure-test@@ -1092,9 +1083,8 @@:model_id card-eid-1}ser))(is (not (contains? ser :id)))- (testing "depends on the Model and Database"- (is (= #{[{:model "Database" :id "My Database"}]- [{:model "Card" :id card-eid-1}]}+ (testing "depends on the Model"+ (is (= #{[{:model "Card" :id card-eid-1}]}(set (serdes/deserialization-dependencies ser)))))))))))))(deftest field-values-test@@ -1132,8 +1122,8 @@(is (not (contains? ser :id)))(is (not (contains? ser :field_id))":field_id is dropped; its implied by the path")- (testing "depend only on the Database; the parent Field is synthesized on import if missing"- (is (= #{[{:model "Database" :id "My Database"}]}+ (testing "have no dependencies; the Database and parent Field are synthesized on import if missing"+ (is (= #{}(set (serdes/deserialization-dependencies ser)))))))(testing "extract-metabase behavior"(testing "without :include-field-values"@@ -1296,10 +1286,7 @@:values_source_config {:card_id card-eid-1,:value_field [:field ["My Database" nil "Schemaless Table" "A Field"] nil]}}](:parameters ser)))- ;; The parameter's value_field references a Field, but Tables/Fields are not dependencies — only their- ;; Database is.- (is (= #{[{:model "Database" :id "My Database"}]- [{:model "Collection" :id coll-eid-2}]+ (is (= #{[{:model "Collection" :id coll-eid-2}][{:model "Card" :id card-eid-1}]}(set (serdes/deserialization-dependencies ser))))))(testing "Nullable transformations are omitted"@@ -1771,6 +1758,13 @@(is (= #{"Postgres DB"} (ids-by-model "Database" ser))"Only non-H2 databases should appear in the extract"))))))+(deftest skip-stub-databases-test+ (testing "Stub databases are not extracted, so an import can never turn a real database into a stub"+ (mt/with-empty-h2-app-db!+ (mt/with-temp [:model/Database _stub {:name "Stub DB" :engine :postgres :is_stub true}+ :model/Database _real {:name "Postgres DB" :engine :postgres}]+ (is (= #{"Postgres DB"} (ids-by-model "Database" (extract/extract {:no-settings true}))))))))+(deftest xray-of-analytics-model-export-test(testing "X-rays of analytics models can be exported without errors"(mt/with-empty-h2-app-db!@@ -2328,10 +2322,10 @@positions (map :position (:tags ser))](is (= [hourly-tag-eid custom-tag-eid daily-tag-eid] tag-ids))(is (= [0 1 2] positions))))- (testing "dependencies include collection, source database, and tags (the source Table itself is not a dependency)"+ (testing "dependencies include collection and tags (the source Database and Table are not dependencies)"(let [deps (set (serdes/deserialization-dependencies ser))](is (contains? deps [{:model "Collection" :id coll-eid}]))- (is (contains? deps [{:model "Database" :id "My Database"}]))+ (is (not (contains? deps [{:model "Database" :id "My Database"}])))(is (not (contains? deps [{:model "Database" :id "My Database"}{:model "Table" :id "Schemaless Table"}])))(is (contains? deps [{:model "TransformTag" :id hourly-tag-eid}]))@@ -2845,13 +2839,8 @@:display :table}](let [ser (serdes/extract-one "Card" {} (t2/select-one :model/Card card-id))deps (serdes/deserialization-dependencies ser)]- ;; Database dep comes from mbql-deps on the query's :database key- (is (contains? (set deps) [{:model "Database" :id "Test DB"}])- "Database dependency should come from the query")- ;; Tables/Fields are intentionally not dependencies — they're synthesized as inactive rows on import- ;; if missing, and upserted otherwise.- (is (not-any? #(some (fn [step] (#{"Table" "Field"} (:model step))) %) deps)- "Table/Field should not be dependencies"))))))+ (is (not-any? #(some (fn [step] (#{"Database" "Table" "Field"} (:model step))) %) deps)+ "Database/Table/Field should not be dependencies"))))))(deftest segment-export-strips-table-id-test(testing "Segment export omits table_id — derivable from definition"diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.cljindex ca8dad9e6f7..286138dc1c9 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj@@ -218,6 +218,63 @@(testing "the imported Dimension replaces the Field's local one"(is (= ["Email"] (t2/select-fn-vec :name :model/Dimension :field_id (:id email)))))))))))+(deftest user-settings-import-on-missing-database-test+ (testing "Table settings, Field settings and Dimensions alone create a stub database when theirs is missing"+ (let [serialized (atom nil)+ extract (fn [model-name filter-column ids]+ (serdes/extract-all model-name {:filter-column filter-column :filter-ids ids}))]+ (ts/with-dbs [source-db dest-db]+ (ts/with-db source-db+ (let [db (ts/create! :model/Database :name "source-only-db")+ table (ts/create! :model/Table :name "customers" :db_id (:id db))+ age (ts/create! :model/Field :name "age" :table_id (:id table))+ email (ts/create! :model/Field :name "email" :table_id (:id table))]+ (t2/insert! :model/TableUserSettings {:table_id (:id table) :display_name "Renamed"})+ (t2/insert! :model/FieldUserSettings {:field_id (:id age) :description "edited"})+ (ts/create! :model/Dimension :field_id (:id email) :name "Email" :type :internal)+ (reset! serialized+ (-> []+ (into (extract "TableUserSettings" :table_id [(:id table)]))+ (into (extract "FieldUserSettings" :field_id [(:id age)]))+ (into (extract "Dimension" :field_id [(:id email)]))))))+ (ts/with-db dest-db+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))+ (let [stub (t2/select-one :model/Database :name "source-only-db")+ table (t2/select-one :model/Table :db_id (:id stub) :name "customers")]+ (is (true? (:is_stub stub)))+ (is (= "Renamed" (t2/select-one-fn :display_name :model/TableUserSettings :table_id (:id table))))+ (is (= "edited" (t2/select-one-fn :description :model/FieldUserSettings+ :field_id (t2/select-one-pk :model/Field :table_id (:id table) :name "age"))))+ (is (= ["Email"] (t2/select-fn-vec :name :model/Dimension+ :field_id (t2/select-one-pk :model/Field :table_id (:id table) :name "email"))))))))))++(deftest stub-database-survives-a-rolled-back-referrer-test+ (testing "A stub created inside a failed entity's transaction is not reused from the cache by the next entity"+ (let [serialized (atom nil)]+ (ts/with-dbs [source-db dest-db]+ (ts/with-db source-db+ (let [db (ts/create! :model/Database :name "source-only-db")+ table (ts/create! :model/Table :name "customers" :db_id (:id db))+ coll (ts/create! :model/Collection :name "coll")+ mp (lib-be/application-database-metadata-provider (:id db))+ query (lib/query mp (lib.metadata/table mp (:id table)))+ bad (ts/create! :model/Card :name "bad" :collection_id (:id coll) :database_id (:id db)+ :table_id (:id table) :dataset_query query)+ good (ts/create! :model/Card :name "good" :collection_id (:id coll) :database_id (:id db)+ :table_id (:id table) :dataset_query query)]+ (reset! serialized [(serdes/extract-one "Collection" {} coll)+ (serdes/extract-one "Card" {} bad)+ (serdes/extract-one "Card" {} good)])))+ (ts/with-db dest-db+ (serdes/with-cache+ (serdes.load/load-metabase! (ingestion-in-memory (update @serialized 1 assoc :name nil))+ :continue-on-error true))+ (let [stub (t2/select-one :model/Database :name "source-only-db")]+ (is (true? (:is_stub stub)))+ (is (not (t2/exists? :model/Card :name "bad")))+ (is (=? {:database_id (:id stub)}+ (t2/select-one :model/Card :name "good")))))))))+(deftest legacy-field-dimensions-import-test(testing "a Field file written before Dimensions got files of their own still carries them"(mt/with-empty-h2-app-db!@@ -800,8 +857,7 @@(let [derived-measure (first (filter #(= "Double Sales" (:name %)) (by-model @serialized "Measure")))](is (=? {:definition {:stages [{:aggregation [[:* {} [:measure {} (:entity_id @msr1s)] 2]]}]}}derived-measure))- (is (= #{[{:id "my-db", :model "Database"}]- [{:id (:entity_id @msr1s), :model "Measure"}]}+ (is (= #{[{:id (:entity_id @msr1s), :model "Measure"}]}(serdes/mbql-deps false (:definition derived-measure))))))(testing "deserializing adjusts the measure IDs properly"(ts/with-db dest-db@@ -1428,7 +1484,7 @@:table_id ["my-db" nil "CUSTOMERS"]:visualization_settings {}}])](is (some? (serdes.load/load-metabase! ingestion)))))- (testing "depending on nonexisting values fails"+ (testing "depending on a nonexisting database creates a stub database"(let [ingestion (ingestion-in-memory [{:serdes/meta [{:model "Card" :id "0123456789abcdef_0123"}]:created_at (t/instant):creator_id "[email protected]"@@ -1441,6 +1497,31 @@:name "Some card":table_id ["bad-db" nil "CUSTOMERS"]:visualization_settings {}}])+ _ (serdes.load/load-metabase! ingestion)+ stub (t2/select-one :model/Database :name "bad-db")]+ (is (=? {:engine :postgres+ :details {}+ :is_stub true}+ stub))+ (testing "the stub's table is synthesized as inactive"+ (is (=? {:active false}+ (t2/select-one :model/Table :db_id (:id stub) :name "CUSTOMERS"))))+ (is (= (:id stub)+ (t2/select-one-fn :database_id :model/Card :entity_id "0123456789abcdef_0123")))))+ (testing "depending on nonexisting values fails"+ (let [ingestion (ingestion-in-memory [{:serdes/meta [{:model "Card" :id "0123456789abcdef_0124"}]+ :collection_id "missingcollection0001"+ :created_at (t/instant)+ :creator_id "[email protected]"+ :database_id "my-db"+ :dataset_query {:database "my-db"+ :type :query+ :query {:source-table ["my-db" nil "CUSTOMERS"]}}+ :display :table+ :entity_id "0123456789abcdef_0124"+ :name "Other card"+ :table_id ["my-db" nil "CUSTOMERS"]+ :visualization_settings {}}])e (try(serdes.load/load-metabase! ingestion)nil@@ -1448,20 +1529,16 @@(is (some? e))(is (re-find #"was not found" (ex-message e)))(testing "the not-found error names the entity holding the dangling reference (GHY-3992)"- (is (= {:model "Database" :id "bad-db"}+ (is (= {:model "Collection" :id "missingcollection0001"}(select-keys (ex-data e) [:model :id])))- (is (= {:model "Card" :id "0123456789abcdef_0123" :name "Some card"}+ (is (= {:model "Card" :id "0123456789abcdef_0124" :name "Other card"}(:referrer (ex-data e)))));; attaching the referrer must not nest the original beneath itself: error reporting renders the;; whole cause chain, and a self-nested exception prints the same message twice(testing "attaching the referrer does not duplicate the error through the cause chain"(is (nil? (ex-cause e))))))- ;; `result-metadata-deps` derives deps only from each entry's `:field_ref`, never from its `:table_id`.- ;; So a result_metadata `:table_id` naming an absent database gets past dependency resolution and only- ;; fails inside `serdes/load-one!`, where `import-table-fk` raises ::database-not-found. (The Card's own- ;; top-level `table_id` cannot be used here: `populate-query-fields` recomputes it from `dataset_query`.)- (testing "a result_metadata table_id naming an absent database names the database and the card (GHY-3992)"- (let [ingestion (ingestion-in-memory [{:serdes/meta [{:model "Card" :id "0123456789abcdef_0123"}]+ (testing "a result_metadata table_id naming an absent database creates a stub database"+ (let [ingestion (ingestion-in-memory [{:serdes/meta [{:model "Card" :id "0123456789abcdef_0125"}]:created_at (t/instant):creator_id "[email protected]":database_id "my-db"@@ -1469,29 +1546,15 @@:type :query:query {:source-table ["my-db" nil "CUSTOMERS"]}}:display :table- :entity_id "0123456789abcdef_0123"+ :entity_id "0123456789abcdef_0125":name "Some card":result_metadata [{:name "STATE":base_type :type/Text:table_id ["absent-db" nil "CUSTOMERS"]}]:table_id ["my-db" nil "CUSTOMERS"]- :visualization_settings {}}])- e (try- (serdes.load/load-metabase! ingestion)- nil- (catch clojure.lang.ExceptionInfo e e))- root (->> (iterate ex-cause e)- (take-while some?)- (some #(when (= :metabase.models.serialization.resolve.db/database-not-found- (:error (ex-data %)))- %)))]- (is (some? e))- (testing "the root cause carries the missing database name"- (is (some? root))- (is (= "absent-db" (:db-name (ex-data root)))))- (testing "the outer load-failure names the card that failed to load"- (is (= {:model "Card" :id "0123456789abcdef_0123" :name "Some card"}- (:entity (ex-data e)))))))))))+ :visualization_settings {}}])]+ (serdes.load/load-metabase! ingestion)+ (is (true? (t2/select-one-fn :is_stub :model/Database :name "absent-db")))))))))(deftest card-with-snippet-test(let [db1s (atom nil)@@ -2350,8 +2413,8 @@(testing "table is linked to imported collection"(is (= (:id imported-coll) (:collection_id imported-table))))))))))))-(deftest import-published-table-without-database-fails-test- (testing "Importing a published table fails when database doesn't exist on target"+(deftest import-published-table-without-database-creates-stub-database-test+ (testing "Importing a published table creates a stub database when the database doesn't exist on target"(let [serialized (atom nil)](ts/with-dbs [source-db dest-db](testing "export published table"@@ -2368,13 +2431,33 @@{:targets [["Collection" (:id coll)]]:no-data-model true:no-settings true}))))))- (testing "import fails when database doesn't exist"+ (testing "import creates a stub database"(ts/with-db dest-db- ;; Don't create the database - import should fail- (is (thrown-with-msg?- Exception- #"source-only-db|not found|Failed"- (serdes.load/load-metabase! (ingestion-in-memory @serialized))))))))))+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))+ (let [stub (t2/select-one :model/Database :name "source-only-db")]+ (is (=? {:engine :postgres+ :details {}+ :is_stub true}+ stub))+ (testing "the published table is imported into the stub database"+ (is (=? {:db_id (:id stub)+ :is_published true}+ (t2/select-one :model/Table :name "published_table")))))))))))++(deftest database-is-stub-is-not-serialized-test+ (testing "`is_stub` is neither exported nor imported, so an import never turns a real database into a stub"+ (let [serialized (atom nil)]+ (ts/with-dbs [source-db dest-db]+ (ts/with-db source-db+ (let [stub (ts/create! :model/Database :name "Prod" :engine :postgres :details {} :is_stub true)]+ (reset! serialized (serdes/extract-one "Database" {} stub))+ (is (not (contains? @serialized :is_stub)))))+ (ts/with-db dest-db+ (let [real (ts/create! :model/Database :name "Prod" :engine :postgres :details {:host "prod"})]+ (serdes.load/load-metabase! (ingestion-in-memory [(assoc @serialized :is_stub true)]))+ (is (=? {:details {:host "prod"}+ :is_stub false}+ (t2/select-one :model/Database :id (:id real))))))))))(deftest segment-minimal-required-properties-test(testing "Segment deserialized with only: entity_id, name, definition, creator_id"diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/metric_dimensions_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/metric_dimensions_test.cljindex e63d62eaf5f..3cb53a03061 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/metric_dimensions_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/metric_dimensions_test.clj@@ -123,10 +123,10 @@:target [:field {:source-field ["metric-db" nil "sales" "product_id"]}["metric-db" nil "products" "title"]]}](:dimension_mappings card)))- (is (contains? (metrics/dimension-mappings-deps (:dimension_mappings card))- [{:model "Database" :id "metric-db"}]))- (is (contains? (serdes/deserialization-dependencies card)- [{:model "Database" :id "metric-db"}]))))+ (is (not (contains? (set (metrics/dimension-mappings-deps (:dimension_mappings card)))+ [{:model "Database" :id "metric-db"}])))+ (is (not (contains? (set (serdes/deserialization-dependencies card))+ [{:model "Database" :id "metric-db"}])))))(defn- prepare-destination! [](let [other-db (ts/create! :model/Database :name "other-db")diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.cljindex 224024de760..2d78610b942 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.clj@@ -117,13 +117,7 @@they don't have to be declared in `serdes/deserialization-dependencies`. Everything else MUST be declared— otherwise `*import-fk*` throws \"Could not find foreign key target\" and aborts thewhole import (see GDGT-2444 for an example)."- #{:model/User :model/Table :model/Field})--(def ^:private fk-completeness-known-exceptions- "`[model field]` pairs that look like FK-completeness violations but are intentionally- exempt. The map value is a human reason kept for grep-ability."- {["Database" :router_database_id]- "router_database_id rows are filtered out of `extract-query` (router DBs aren't serialized), so this FK never reaches the load path."})+ #{:model/User :model/Database :model/Table :model/Field})(defn- inlined-via-nested?"True if `model-name` is loaded only as a nested child of some parent, never as a root.@@ -161,10 +155,7 @@;; nil `generate-path` (the convention for nested-only models like;; QueryAction / ImplicitAction).:when (not (or (inlined? m) (inlined-via-nested? m)))- :let [fks (->> (:transform (serdes/make-spec m nil))- direct-fks- (remove (fn [[field _]]- (contains? fk-completeness-known-exceptions [m field]))))]+ :let [fks (direct-fks (:transform (serdes/make-spec m nil)))]:when (seq fks)](testing (format "%s\n" m)(let [entity (into {:serdes/meta [{:model m :id "self"}]}diff --git a/frontend/src/metabase-types/api/database.ts b/frontend/src/metabase-types/api/database.tsindex a3bd8ddef1f..5d785fb3f54 100644--- a/frontend/src/metabase-types/api/database.ts+++ b/frontend/src/metabase-types/api/database.ts@@ -81,6 +81,7 @@ export interface Database extends DatabaseData {uploads_table_prefix: string | null;is_audit?: boolean;is_attached_dwh?: boolean;+ is_stub?: boolean;router_database_id?: number | null;router_user_attribute?: string | null;@@ -165,6 +166,7 @@ export type ListDatabasesRequest = {exclude_uneditable_details?: boolean;include_only_uploadable?: boolean;include_analytics?: boolean;+ include_stubs?: boolean;router_database_id?: DatabaseId;"can-query"?: boolean;"can-write-metadata"?: boolean;diff --git a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsx b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsxindex c97ff3eaa16..0af220ff682 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.tsx@@ -57,7 +57,7 @@ export const DatabaseConnectionInfoSection = ({return (<DatabaseInfoSection- condensed+ condensed={!database.is_stub}name={t`Connection and sync`}description={t`Manage details about the database connection and when Metabase ingests new data.`}data-testid="database-connection-info-section"@@ -76,7 +76,7 @@ export const DatabaseConnectionInfoSection = ({</Tooltip></Flex>- <DatabaseInfoSectionDivider condensed />+ {!database.is_stub && <DatabaseInfoSectionDivider condensed />}{isSyncAborted(database) && database.initial_sync_error && (<Alert@@ -90,7 +90,7 @@ export const DatabaseConnectionInfoSection = ({</Alert>)}- {!database.is_attached_dwh && (+ {!database.is_attached_dwh && !database.is_stub && (<Flex gap="sm" wrap="wrap">{!isSynced && <Button disabled>{t`Syncing database…`}</Button>}<ActionButtondiff --git a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsx b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsxindex be390c969cc..10eb1290b90 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsx@@ -217,6 +217,18 @@ describe("DatabaseConnectionInfoSection", () => {});});+ describe("Stub databases", () => {+ it("should hide the sync actions but allow editing the connection details", async () => {+ setup({ database: createMockDatabase({ is_stub: true }) });+ expect(+ screen.queryByText(/Sync database schema/i),+ ).not.toBeInTheDocument();+ expect(+ await screen.findByRole("button", { name: /Edit connection details/i }),+ ).toBeEnabled();+ });+ });+describe("Sample database", () => {it("should disable editing the connection details", async () => {setup({ database: createMockDatabase({ is_sample: true }) });diff --git a/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.tsx b/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.tsxindex 813cb61b0ec..c574e13887f 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.tsx@@ -34,12 +34,11 @@ export const DatabaseDangerZoneSection = ({return deleteDatabase(database.id).then(() => deleteDbModal.close());};- const hasCompletedSync = isSyncCompleted(database);- const shouldHideSection =- database.is_attached_dwh ||- [hasCompletedSync, isAdmin].every((bool) => bool === false);+ const canDiscardFieldValues =+ !database.is_attached_dwh && isSyncCompleted(database) && !database.is_stub;+ const canDelete = !database.is_attached_dwh && isAdmin;- if (shouldHideSection) {+ if (!canDiscardFieldValues && !canDelete) {return null;}@@ -50,7 +49,7 @@ export const DatabaseDangerZoneSection = ({data-testid="database-danger-zone-section"><Flex gap="sm" wrap="wrap">- {isSyncCompleted(database) && (+ {canDiscardFieldValues && (<><Buttonvariant="filled"@@ -67,7 +66,7 @@ export const DatabaseDangerZoneSection = ({/></>)}- {isAdmin && (+ {canDelete && (<><Buttonvariant="filled"diff --git a/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsx b/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsxindex a616e538bd0..5d38b24c833 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsx@@ -120,6 +120,28 @@ describe("DatabaseDangerZoneSection", () => {).not.toBeInTheDocument();});});++ it("is hidden for stub databases", () => {+ setup({ database: createMockDatabase({ is_stub: true }) });++ expect(+ screen.queryByText(/Discard saved field values/i),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /Remove this database/i }),+ ).toBeInTheDocument();+ });+ });++ it("is hidden for stub databases when the user is not an admin", () => {+ setup({+ database: createMockDatabase({ is_stub: true }),+ isAdmin: false,+ });++ expect(+ screen.queryByTestId("database-danger-zone-section"),+ ).not.toBeInTheDocument();});describe("remove database", () => {diff --git a/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.tsx b/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.tsxindex f9713c72abd..48ee9e8e903 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.tsx@@ -70,6 +70,7 @@ export const DatabaseList = ({<tr><th>{t`Name`}</th><th>{t`Engine`}</th>+ <th>{t`Status`}</th></tr></thead><tbody>@@ -98,6 +99,7 @@ export const DatabaseList = ({{engines?.[database.engine ?? ""]?.["driver-name"] ??database.engine}</td>+ <td>{database.is_stub ? t`Stubbed` : t`Active`}</td></tr>))) : (diff --git a/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsx b/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsxindex 5022fd97a34..c029fa93009 100644--- a/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsx+++ b/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsx@@ -6,12 +6,19 @@ import { DatabaseList } from "./DatabaseList";const CREATE_SAMPLE_DATABASE_BUTTON_LABEL = "Bring the sample database back";interface SetupOpts {- isSampleDb: boolean;+ isSampleDb?: boolean;+ isStub?: boolean;isAdmin: boolean;}-async function setup({ isSampleDb, isAdmin }: SetupOpts) {- const databases = [createMockDatabase({ is_sample: isSampleDb })];+async function setup({+ isSampleDb = false,+ isStub = false,+ isAdmin,+}: SetupOpts) {+ const databases = [+ createMockDatabase({ is_sample: isSampleDb, is_stub: isStub }),+ ];render(<DatabaseList@@ -44,6 +51,20 @@ describe("DatabaseListApp", () => {).not.toBeInTheDocument();});+ it("shows stub databases as stubbed", async () => {+ await setup({ isStub: true, isAdmin: true });++ expect(screen.getByText("Stubbed")).toBeInTheDocument();+ expect(screen.queryByText("Active")).not.toBeInTheDocument();+ });++ it("shows regular databases as active", async () => {+ await setup({ isAdmin: true });++ expect(screen.getByText("Active")).toBeInTheDocument();+ expect(screen.queryByText("Stubbed")).not.toBeInTheDocument();+ });+it("does not show restore sample database button to non-admins", async () => {await setup({ isSampleDb: false, isAdmin: false });diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsxindex f548ca65cb2..35125881fe1 100644--- a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx+++ b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.tsx@@ -114,29 +114,33 @@ function DatabaseEditAppInner({><DatabaseConnectionInfoSection database={database} />- <PLUGIN_WRITABLE_CONNECTION.WritableConnectionInfoSection- database={database}- />-- <DatabaseModelFeaturesSection- database={database}- isModelPersistenceEnabled={isModelPersistenceEnabled}- updateDatabase={updateDatabase}- />-- <PLUGIN_DATABASE_REPLICATION.DatabaseReplicationSection- database={database}- />-- <PLUGIN_TABLE_EDITING.AdminDatabaseTableEditingSection- database={database}- settingsAvailable={settingsAvailable?.settings}- updateDatabase={updateDatabase}- />-- <PLUGIN_DB_ROUTING.DatabaseRoutingSection- database={database}- />+ {!database.is_stub && (+ <>+ <PLUGIN_WRITABLE_CONNECTION.WritableConnectionInfoSection+ database={database}+ />++ <DatabaseModelFeaturesSection+ database={database}+ isModelPersistenceEnabled={isModelPersistenceEnabled}+ updateDatabase={updateDatabase}+ />++ <PLUGIN_DATABASE_REPLICATION.DatabaseReplicationSection+ database={database}+ />++ <PLUGIN_TABLE_EDITING.AdminDatabaseTableEditingSection+ database={database}+ settingsAvailable={settingsAvailable?.settings}+ updateDatabase={updateDatabase}+ />++ <PLUGIN_DB_ROUTING.DatabaseRoutingSection+ database={database}+ />+ </>+ )}<DatabaseDangerZoneSectionisAdmin={isAdmin}diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.unit.spec.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.unit.spec.tsxnew file mode 100644index 00000000000..c4b47b0dfc3--- /dev/null+++ b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.unit.spec.tsx@@ -0,0 +1,70 @@+import fetchMock from "fetch-mock";++import {+ setupDatabaseEndpoints,+ setupDatabaseUsageInfoEndpoint,+} from "__support__/server-mocks";+import { createMockState } from "__support__/state";+import { renderWithProviders, screen } from "__support__/ui";+import { Route } from "metabase/router";+import type { Database } from "metabase-types/api";+import { createMockDatabase, createMockUser } from "metabase-types/api/mocks";++import { DatabaseEditApp } from "./DatabaseEditApp";++const setup = ({ database }: { database: Database }) => {+ setupDatabaseEndpoints(database);+ setupDatabaseUsageInfoEndpoint(database, {+ question: 0,+ dataset: 0,+ metric: 0,+ segment: 0,+ transform: 0,+ });+ fetchMock.get(`path:/api/database/${database.id}/settings-available`, {+ settings: {},+ });++ renderWithProviders(+ <Route path="/admin/databases/:databaseId" element={<DatabaseEditApp />} />,+ {+ withRouter: true,+ initialRoute: `/admin/databases/${database.id}`,+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: true }),+ }),+ },+ );+};++describe("DatabaseEditApp", () => {+ it("shows every section for a regular database", async () => {+ setup({ database: createMockDatabase({ features: ["actions"] }) });++ expect(+ await screen.findByTestId("database-connection-info-section"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("database-model-features-section"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("database-danger-zone-section"),+ ).toBeInTheDocument();+ });++ it("shows only the connection and danger zone sections for a stub database", async () => {+ setup({+ database: createMockDatabase({ features: ["actions"], is_stub: true }),+ });++ expect(+ await screen.findByTestId("database-connection-info-section"),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId("database-model-features-section"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("database-danger-zone-section"),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseListApp.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseListApp.tsxindex 2b9d8f71e63..a72942297a1 100644--- a/frontend/src/metabase/admin/databases/containers/DatabaseListApp.tsx+++ b/frontend/src/metabase/admin/databases/containers/DatabaseListApp.tsx@@ -29,7 +29,10 @@ export const DatabaseListApp = (props: DatabaseListAppProps) => {const [pollingInterval, setPollingInterval] = useState<number>();const databasesReq = useListDatabasesQuery(- PLUGIN_FEATURE_LEVEL_PERMISSIONS.databaseDetailsQueryProps,+ {+ ...PLUGIN_FEATURE_LEVEL_PERMISSIONS.databaseDetailsQueryProps,+ include_stubs: true,+ },{ pollingInterval },);diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseListApp.unit.spec.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseListApp.unit.spec.tsxnew file mode 100644index 00000000000..ea3d9c64ead--- /dev/null+++ b/frontend/src/metabase/admin/databases/containers/DatabaseListApp.unit.spec.tsx@@ -0,0 +1,30 @@+import fetchMock from "fetch-mock";++import { setupDatabaseListEndpoint } from "__support__/server-mocks";+import { createMockState } from "__support__/state";+import { renderWithProviders, screen } from "__support__/ui";+import { createMockDatabase, createMockUser } from "metabase-types/api/mocks";++import { DatabaseListApp } from "./DatabaseListApp";++const setup = () => {+ setupDatabaseListEndpoint([+ createMockDatabase({ id: 1, name: "Stubbed DB", is_stub: true }),+ ]);++ renderWithProviders(<DatabaseListApp />, {+ storeInitialState: createMockState({+ currentUser: createMockUser({ is_superuser: true }),+ }),+ });+};++describe("DatabaseListApp", () => {+ it("requests stub databases so they can be listed", async () => {+ setup();++ expect(await screen.findByText("Stubbed DB")).toBeInTheDocument();+ const [call] = fetchMock.callHistory.calls("path:/api/database");+ expect(new URL(call.url).searchParams.get("include_stubs")).toBe("true");+ });+});diff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex a8d96d44ba7..5cd3103fa37 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -587,12 +587,8 @@[[{:model "Collection" :id collection-id}]])(when-let [model-id (:model_id action)][[{:model "Card" :id model-id}]])- ;; this method is called on ingested data before transformation, and so here it always will be a string(when (= (:type action) "query")- (let [{:keys [database_id dataset_query]} (first (:query action))]- (concat- [[{:model "Database" :id database_id}]]- (serdes/mbql-deps false dataset_query)))))))+ (serdes/mbql-deps false (:dataset_query (first (:query action))))))))(defmethod serdes/serialization-dependencies "Action" [_model-name {:keys [id collection_id model_id type]}];; Serialization runs on the raw entity, whose query lives in the `query_action` child table (`:type` is a keyworddiff --git a/src/metabase/metabot/db.clj b/src/metabase/metabot/db.cljindex 1910031e4fb..cdd72c38d87 100644--- a/src/metabase/metabot/db.clj+++ b/src/metabase/metabot/db.clj@@ -420,10 +420,12 @@(t2/select-fn-set :id :model/Database :id [:in database-ids] :router_database_id [:not= nil]))(mu/defn non-audit-databases- "The ID, name, engine, description, and audit flag of every non-audit, non-destination Database, ordered by name."+ "The ID, name, engine, description, and audit flag of every non-audit, non-stub, non-destination Database, ordered+ by name."[](t2/select [:model/Database :id :name :engine :description :is_audit]:is_audit false+ :is_stub false:router_database_id nil{:order-by [[:%lower.name :asc]]}))diff --git a/src/metabase/models/db.clj b/src/metabase/models/db.cljindex 2f7e677bd4f..2dcabe0781c 100644--- a/src/metabase/models/db.clj+++ b/src/metabase/models/db.clj@@ -259,11 +259,6 @@[database-id :- [:maybe ::lib.schema.id/database]](t2/select-one-fn :name [:model/Database :id :name] :id database-id))-(mu/defn database-names- "The names of every Database."- []- (t2/select-fn-vec :name :model/Database))-(mu/defn database-id-by-name"The id of the Database named `database-name`, or nil."[database-name :- :string]@@ -276,6 +271,15 @@database-id :- ::lib.schema.id/database](t2/select-one-fn :id :model/Table :name table-name :schema schema :db_id database-id {:from [(warehouse-schema-overlay/table-query {:user-settings? false})]}))+(mu/defn insert-stub-database!+ "Insert a stub Postgres Database named `database-name` with empty connection details and return its id."+ [database-name :- :string]+ (t2/insert-returning-pk! :model/Database {:name database-name+ :engine :postgres+ :details {}+ :is_stub true+ :initial_sync_status "complete"}))+(mu/defn insert-inactive-table!"Insert an inactive Table named `table-name` in `schema` of the Database with `database-id` and return its id."[database-id :- ::lib.schema.id/databasediff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.cljindex 75b8bc3cd58..a349d0a8e7b 100644--- a/src/metabase/models/serialization.clj+++ b/src/metabase/models/serialization.clj@@ -631,7 +631,8 @@dependency is represented by its abstract path (its `:serdes/meta` value).NOTE: This is called during **LOAD**. Its export-time counterpart is [[serialization-dependencies]], which runs on a- raw entity and additionally reports tables/fields (which import synthesizes on the fly, so they aren't load deps).+ raw entity and additionally reports databases/tables/fields (which import synthesizes on the fly, so they aren't load+ deps).Keyed on the model name for this entity.Default implementation returns `nil`, so only models that have dependencies need to implement this."@@ -924,7 +925,8 @@"Given a portable database name, resolve it back to a numeric ID.[[*export-database-fk*]] is the inverse."[db-name]- (*import-fk-keyed* db-name :model/Database :name))+ (when db-name+ (resolve/import-database-fk (import-resolver) db-name)));;; ## Tables@@ -1341,16 +1343,6 @@[allow-int-ids? x](and allow-int-ids? (pos-int? x)))-(defn- ref->db-dep- "Given a portable table or field reference (a vector like `[db-name schema table-name ...]`), return a set with- its Database dependency, or nil. Table and Field references are intentionally *not* dependencies — missing ones- are synthesized as inactive rows on import — but their Database is, since it can't be synthesized. We can't rely- on the query's top-level `:database` for this because some references (e.g. dashboard parameter mappings) are- bare field refs with no surrounding query."- [ref]- (when-let [db-name (first ref)]- #{[{:model "Database" :id db-name}]}))-(def ^:private mbql-ref-tag->model"The serdes model that a `:metric`/`:segment`/`:measure` MBQL reference clause depends on."{:metric "Card", "metric" "Card"@@ -1360,11 +1352,10 @@(defn- mbql-deps-vector [allow-int-ids? entity](match/match-one entity;; --- serialized (portable) refs, walked at load time ---- ;; A serialized `:field` clause's only dependency is the Database of its referenced field; the Field/Table- ;; themselves are synthesized on import, and a field clause never nests metric/segment/card refs, so we don't- ;; descend.- [#{:field "field"} (_opts :guard map?) (ref :guard vector?)]- (ref->db-dep ref)+ ;; A serialized `:field` clause has no dependencies: its Database, Table and Field are synthesized on import, and+ ;; a field clause never nests metric/segment/card refs, so we don't descend.+ [#{:field "field"} (_opts :guard map?) (_ref :guard vector?)]+ nil[(tag :guard #{:metric "metric" :segment "segment" :measure "measure"})(opts :guard map?)@@ -1373,8 +1364,8 @@(mbql-deps-map allow-int-ids? opts));; legacy (MBQL 4) serialized refs- [#{:field "field" :field-id "field-id"} (ref :guard vector?) _opts]- (ref->db-dep ref)+ [#{:field "field" :field-id "field-id"} (_ref :guard vector?) _opts]+ nil[(tag :guard #{:metric "metric" :segment "segment" :measure "measure"}) (field :guard portable-id?)]#{[{:model (mbql-ref-tag->model tag) :id field}]}@@ -1408,17 +1399,15 @@(into #{}(mapcat (fn [[k v]](cond- ;; --- serialized (portable) refs. Table/Field references contribute only their Database as a- ;; dependency (see `ref->db-dep`); the referenced Table/Field are synthesized on import. ---- (and (= k :database)- (string? v)- (not= v "database/__virtual")) #{[{:model "Database" :id v}]}- (and (= k :source-table) (vector? v)) (ref->db-dep v)+ ;; --- serialized (portable) refs. Database/Table/Field references are not dependencies; they are+ ;; synthesized on import. ---+ (and (= k :database) (string? v)) nil+ (and (= k :source-table) (vector? v)) nil(and (= k :source-table) (portable-id? v)) #{[{:model "Card" :id v}]}(and (= k :source-card) (portable-id? v)) #{[{:model "Card" :id v}]}- (and (= k :source-field) (vector? v)) (ref->db-dep v)+ (and (= k :source-field) (vector? v)) nil(and (= k :snippet-id) (portable-id? v)) #{[{:model "NativeQuerySnippet" :id v}]}- (and (= k :table-id) (vector? v)) (ref->db-dep v)+ (and (= k :table-id) (vector? v)) nil(and (#{:card_id :card-id} k) (string? v)) #{[{:model "Card" :id v}]};; --- raw (numeric) refs, walked at export time: the referenced Table/Field are real appdb ids to;; existence-check. `allow-int-ids?` gates these (see `raw-ref-id?`). ---@@ -1793,12 +1782,11 @@(defn- viz-link-card-deps[allow-int-ids? settings](when-let [{:keys [model id]} (get-in settings [:link :entity])]- (if (= model "table")- ;; Serialized: a linked Table is not a dependency (synthesized on import), but its Database is. Raw (export- ;; time): the numeric table id is a real Table to existence-check.- (cond- (vector? id) #{[{:model "Database" :id (first id)}]}- (raw-ref-id? allow-int-ids? id) #{[{:model "Table" :id id}]})+ (if (#{"table" "database"} model)+ ;; Serialized: a linked Table or Database is not a dependency (synthesized on import). Raw (export time): the+ ;; numeric id is a real row to existence-check.+ (when (raw-ref-id? allow-int-ids? id)+ #{[{:model (name (link-card-model->toucan-model model)) :id id}]})#{[{:model (name (link-card-model->toucan-model model)):id id}]})))@@ -1973,3 +1961,9 @@`(binding [resolve/*export-resolver* (resolve.default/cached-export-resolver)resolve/*import-resolver* (resolve.default/cached-import-resolver)]~@body))++(defn reset-import-cache!+ "Drop the memoized lookups of the bound import resolver, if it caches any."+ []+ (when (satisfies? resolve/ResettableCache resolve/*import-resolver*)+ (resolve/reset-cache! resolve/*import-resolver*)))diff --git a/src/metabase/models/serialization/resolve.clj b/src/metabase/models/serialization/resolve.cljindex dc3f69372b7..1887647e164 100644--- a/src/metabase/models/serialization/resolve.clj+++ b/src/metabase/models/serialization/resolve.clj@@ -32,9 +32,14 @@(import-fk [this eid model] "Given a portable ID and model, return the numeric PK.")(import-fk-keyed [this portable model field] "Given a portable identifying field value, return the numeric :id.")(import-user [this email] "Import a user by email, creating if needed. Returns PK.")+ (import-database-fk [this db-name] "Given a portable database name, return the numeric database id.")(import-table-fk [this path] "Given [db-name schema table-name], return numeric table_id.")(import-field-fk [this path] "Given [db-name schema table-name field-name], return numeric field_id."))+(defprotocol ResettableCache+ "A resolver whose memoized lookups can be dropped."+ (reset-cache! [this] "Drop every memoized lookup."))+;;; ============================================================;;; Dynamic vars — bound to resolver instances;;; ============================================================@@ -143,7 +148,7 @@(-> &match(assoc :database (if (= fully-qualified-name "database/__virtual")lib.schema.id/saved-questions-virtual-database-id- (import-fk-keyed resolver fully-qualified-name :model/Database :name)))+ (import-database-fk resolver fully-qualified-name)))(->> (mbql-fully-qualified-names->ids* resolver))){:card-id (entity-id :guard content-ref?)}diff --git a/src/metabase/models/serialization/resolve/default.clj b/src/metabase/models/serialization/resolve/default.cljindex 86960b40944..8fe50636c1c 100644--- a/src/metabase/models/serialization/resolve/default.clj+++ b/src/metabase/models/serialization/resolve/default.clj@@ -87,6 +87,12 @@;; Need to break a circular dependency here.(:id ((clojure.core/resolve 'metabase.users.models.user/serdes-synthesize-user!) {:email email :is_active false})))))+(defn- synthesize-database!+ "Creates a new stub Database for a deserialized reference whose name doesn't match any existing row. Returns the new+ database id."+ [db-name]+ (models.db/insert-stub-database! db-name))+(defn- synthesize-table!"Creates a new inactive Table for a deserialized reference whose `[db-name schema table-name]`triple doesn't match any existing row. Returns the new table id."@@ -105,21 +111,22 @@(recur field-id (rest remaining)))parent-id)))+(defn import-database-fk+ "Given a portable database name, return the numeric database id. If the database doesn't exist, synthesize a stub+ Database so we can still resolve the reference."+ [db-name]+ (when db-name+ (or (models.db/database-id-by-name db-name)+ (synthesize-database! db-name))))+(defn import-table-fk- "Given [db-name schema table-name], return numeric table_id. If the database exists but the table- doesn't, synthesize an inactive Table from the path so we can still resolve the reference. The thrown ex-data's- `:error` is pinned to `:metabase.models.serialization.resolve.db/database-not-found` — this code's old namespace,- before this file replaced it — since other modules and tests compare against that literal keyword value."- [[db-name schema table-name :as table-id]]+ "Given [db-name schema table-name], return numeric table_id. If the database or the table is missing, synthesize a+ stub Database or an inactive Table from the path so we can still resolve the reference."+ [resolver [db-name schema table-name :as table-id]](when table-id- (if-let [db-id (models.db/database-id-by-name db-name)]+ (let [db-id (resolve/import-database-fk resolver db-name)](or (models.db/table-id-by-name table-name schema db-id)- (synthesize-table! db-id schema table-name))- (throw (ex-info (format "table id present, but database not found: %s" table-id)- {:table-id table-id- :db-name db-name- :database-names (sort (models.db/database-names))- :error :metabase.models.serialization.resolve.db/database-not-found})))))+ (synthesize-table! db-id schema table-name)))))(defn import-field-fk"Given [db-name schema table-name field-name ...], return numeric field_id. If part of the parent@@ -150,7 +157,8 @@(resolve/import-fk [_ eid model] (import-fk eid model))(resolve/import-fk-keyed [_ portable model field] (import-fk-keyed portable model field))(resolve/import-user [this email] (import-user this email))- (resolve/import-table-fk [_ path] (import-table-fk path))+ (resolve/import-database-fk [_ db-name] (import-database-fk db-name))+ (resolve/import-table-fk [this path] (import-table-fk this path))(resolve/import-field-fk [this path] (import-field-fk this path))))(def lenient-import-resolver@@ -162,6 +170,7 @@nil)))(resolve/import-fk-keyed [_ portable model field] (resolve/import-fk-keyed default-import-resolver portable model field))(resolve/import-user [_ email] (resolve/import-user default-import-resolver email))+ (resolve/import-database-fk [_ db-name] (resolve/import-database-fk default-import-resolver db-name))(resolve/import-table-fk [_ path] (resolve/import-table-fk default-import-resolver path))(resolve/import-field-fk [_ path] (resolve/import-field-fk default-import-resolver path))))@@ -180,17 +189,29 @@(resolve/export-table-fk [_ table-id] (export-table-fk* table-id))(resolve/export-field-fk [this field-id] (export-field-fk* this field-id)))))+(defn- cached+ "Return the value memoized in `cache` under `k`, computing and memoizing it with `f` when absent. Nil is not memoized."+ [cache k f]+ (if-some [v (get @cache k)]+ v+ (let [v (f)]+ (when (some? v)+ (swap! cache assoc k v))+ v)))+(defn cached-import-resolver- "Returns a database-backed import resolver with memoized lookups."+ "Returns a database-backed import resolver with memoized lookups, dropped by [[resolve/reset-cache!]]."[]- (let [import-fk* (memoize import-fk)- import-fk-keyed* (memoize import-fk-keyed)- import-user* (memoize import-user)- import-table-fk* (memoize import-table-fk)- import-field-fk* (memoize import-field-fk)]- (reify resolve/SerdesImportResolver- (resolve/import-fk [_ eid model] (import-fk* eid model))- (resolve/import-fk-keyed [_ portable model field] (import-fk-keyed* portable model field))- (resolve/import-user [this email] (import-user* this email))- (resolve/import-table-fk [_ path] (import-table-fk* path))- (resolve/import-field-fk [this path] (import-field-fk* this path)))))+ (let [cache (atom {})]+ (reify+ resolve/SerdesImportResolver+ (import-fk [_ eid model] (cached cache [:fk eid model] #(import-fk eid model)))+ (import-fk-keyed [_ portable model field] (cached cache [:fk-keyed portable model field]+ #(import-fk-keyed portable model field)))+ (import-user [this email] (cached cache [:user email] #(import-user this email)))+ (import-database-fk [_ db-name] (cached cache [:database db-name] #(import-database-fk db-name)))+ (import-table-fk [this path] (cached cache [:table path] #(import-table-fk this path)))+ (import-field-fk [this path] (cached cache [:field path] #(import-field-fk this path)))++ resolve/ResettableCache+ (reset-cache! [_] (reset! cache {})))))diff --git a/src/metabase/models/serialization/resolve/mp.clj b/src/metabase/models/serialization/resolve/mp.cljindex 5eee4d85f00..9873ad26470 100644--- a/src/metabase/models/serialization/resolve/mp.clj+++ b/src/metabase/models/serialization/resolve/mp.clj@@ -16,9 +16,9 @@MBQL suitable for `lib.query/query` / the QP.Implemented scope for the representations pipeline:- * `import-table-fk`, `import-field-fk`, `export-table-fk`, `export-field-fk` for+ * `import-database-fk`, `import-table-fk`, `import-field-fk`, `export-table-fk`, `export-field-fk` forwarehouse metadata.- * `import-fk-keyed` / `export-fk-keyed` for `:model/Database` by `:name`.+ * `export-fk-keyed` for `:model/Database` by `:name`.* `import-fk` / `export-fk` for `Card`, `Measure`, and `Segment` references by `entity_id`.Everything else throws `:not-implemented-yet` for now.@@ -732,9 +732,7 @@with `metabase.metabot.tools.shared.content-store/read-checked`.Implemented methods:- * `import-table-fk`, `import-field-fk`.- * `import-fk-keyed` for `:model/Database` by `:name` (needed because- `resolve/import-mbql` dispatches on `:database` keys).+ * `import-database-fk`, `import-table-fk`, `import-field-fk`.* `import-fk` for `Card`, `Measure`, and `Segment` by `entity_id`.Other methods throw `:not-implemented-yet`."@@ -760,15 +758,11 @@(measure-model? model) (import-measure-by-entity-id metadata-provider content-store eid)(segment-model? model) (import-segment-by-entity-id metadata-provider content-store eid):else (not-implemented! :import-fk)))- (import-fk-keyed [_ portable model field]- (cond- (and (or (= model :model/Database) (= model 'Database))- (= field :name))- (import-database-by-name metadata-provider portable)-- :else- (not-implemented! :import-fk-keyed)))+ (import-fk-keyed [_ _portable _model _field] (not-implemented! :import-fk-keyed))(import-user [_ _email] (not-implemented! :import-user))+ (import-database-fk [_ db-name]+ (when db-name+ (import-database-by-name metadata-provider db-name)))(import-table-fk [_ path](when path(:id (find-table metadata-provider path))))diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 85ce1ad627c..8a5ea294c92 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -1551,7 +1551,7 @@(mapcat #(serdes/mbql-deps allow-int-ids? %) parameter_mappings)(metrics/dimension-mappings-deps allow-int-ids? dimension_mappings)(serdes/parameters-deps allow-int-ids? parameters)- (when database_id [[{:model "Database" :id database_id}]])+ (when (and allow-int-ids? database_id) [[{:model "Database" :id database_id}]])(when source_card_id #{[{:model "Card" :id source_card_id}]})(when collection_id #{[{:model "Collection" :id collection_id}]})(when dashboard_id #{[{:model "Dashboard" :id dashboard_id}]})diff --git a/src/metabase/search/in_place/legacy.clj b/src/metabase/search/in_place/legacy.cljindex 681a300dbda..f4ea78f6649 100644--- a/src/metabase/search/in_place/legacy.clj+++ b/src/metabase/search/in_place/legacy.clj@@ -564,7 +564,7 @@(defmethod search-query-for-model "database"[model search-ctx](-> (base-query-for-model model search-ctx)- (sql.helpers/where [:= :router_database_id nil])))+ (sql.helpers/where [:= :router_database_id nil] [:= :is_stub false])))(defmethod search-query-for-model "transform"[model search-ctx]diff --git a/src/metabase/sync/events/sync_database.clj b/src/metabase/sync/events/sync_database.cljindex 2403bba7f29..541c6586c3e 100644--- a/src/metabase/sync/events/sync_database.clj+++ b/src/metabase/sync/events/sync_database.clj@@ -11,13 +11,19 @@(events/derive! ::event :metabase/event)(events/derive! :event/database-create ::event)+(events/derive! :event/database-update ::event)(methodical/defmethod events/publish-event! ::event- "When a new Database is created, kick off a sync process for it in a different thread."- [topic {database :object :as _event}]+ "When a new Database is created or a stub Database gets connected, kick off a sync process for it in a different+ thread."+ [topic {database :object previous-database :previous-object :as _event}];; try/catch here to prevent individual topic processing exceptions from bubbling up. better to handle them here.(try- (when (and database (not (warehouses/disable-auto-sync)))+ (when (and database+ (not (:is_stub database))+ (or (= topic :event/database-create)+ (:is_stub previous-database))+ (not (warehouses/disable-auto-sync)));; just kick off a sync on another thread(quick-task/submit-task!(fn []diff --git a/src/metabase/transforms/models/transform.clj b/src/metabase/transforms/models/transform.cljindex 5ad5fc3b624..47146acadc9 100644--- a/src/metabase/transforms/models/transform.clj+++ b/src/metabase/transforms/models/transform.clj@@ -525,19 +525,14 @@:indexes (serdes/nested :model/TableIndex :transform_id (merge {:sort-by :index_name} opts))}})(defmethod serdes/deserialization-dependencies "Transform"- [{:keys [collection_id source tags source_database_id]}]- (let [checkpoint-field-ref (get-in source [:source-incremental-strategy :checkpoint-filter-field-id])]- (set- (concat- (when collection_id- [[{:model "Collection" :id collection_id}]])- (when source_database_id- [[{:model "Database" :id source_database_id}]])- (for [{tag-id :tag_id} tags]- [{:model "TransformTag" :id tag-id}])- (when (some-> checkpoint-field-ref pos-int? not)- [(serdes/field->path checkpoint-field-ref)])- (serdes/mbql-deps false source)))))+ [{:keys [collection_id source tags]}]+ (set+ (concat+ (when collection_id+ [[{:model "Collection" :id collection_id}]])+ (for [{tag-id :tag_id} tags]+ [{:model "TransformTag" :id tag-id}])+ (serdes/mbql-deps false source))))(defmethod serdes/storage-path "Transform" [transform ctx](serdes/storage-default-collection-path transform ctx "transforms"))diff --git a/src/metabase/warehouse_schema/models/dimension.clj b/src/metabase/warehouse_schema/models/dimension.cljindex bbd83cd9969..7850227ba23 100644--- a/src/metabase/warehouse_schema/models/dimension.clj+++ b/src/metabase/warehouse_schema/models/dimension.clj@@ -34,9 +34,6 @@(when-let [field (serdes/load-find-local (pop path))](warehouse-schema.db/dimension-for-field (:id field)))))-(defmethod serdes/deserialization-dependencies "Dimension" [dimension]- [[(first (serdes/path dimension))]])-(defmethod serdes/load-update! "Dimension" [model-name ingested local]((get-method serdes/load-update! :default) model-name (merge {:human_readable_field_id nil} ingested) local))diff --git a/src/metabase/warehouse_schema/models/field.clj b/src/metabase/warehouse_schema/models/field.cljindex d452c4003ff..5c2ea50f85d 100644--- a/src/metabase/warehouse_schema/models/field.clj+++ b/src/metabase/warehouse_schema/models/field.clj@@ -468,10 +468,6 @@((:import-with-context legacy-dimensions) field :dimensions (:dimensions ingested)))field))-(defmethod serdes/deserialization-dependencies "Field" [field]- (let [db-path (first (serdes/path field))]- #{[db-path]}))-(defmethod serdes/make-spec "Field" [_model-name _opts]{:copy [:active :base_type :caveats :coercion_strategy :data_sensitivity :database_default :database_indexed:database_is_auto_increment :database_is_generated :database_is_nullable :database_is_pkdiff --git a/src/metabase/warehouse_schema/models/field_user_settings.clj b/src/metabase/warehouse_schema/models/field_user_settings.cljindex ee4f806201e..15da7d15386 100644--- a/src/metabase/warehouse_schema/models/field_user_settings.clj+++ b/src/metabase/warehouse_schema/models/field_user_settings.clj@@ -110,9 +110,6 @@(conj (serdes/generate-path "Field" {:id field_id}){:model "FieldUserSettings" :id "1"}))-(defmethod serdes/deserialization-dependencies "FieldUserSettings" [field-user-settings]- [[(first (serdes/path field-user-settings))]])-(defmethod serdes/load-find-local "FieldUserSettings" [path](when-let [field (serdes/load-find-local (pop path))](warehouse-schema.db/field-user-settings (:id field))))diff --git a/src/metabase/warehouse_schema/models/field_values.clj b/src/metabase/warehouse_schema/models/field_values.cljindex 07b796f1e78..c1d77c00cae 100644--- a/src/metabase/warehouse_schema/models/field_values.clj+++ b/src/metabase/warehouse_schema/models/field_values.clj@@ -695,10 +695,6 @@(conj (serdes/generate-path "Field" {:id field_id}){:model "FieldValues" :id "0"}))-(defmethod serdes/deserialization-dependencies "FieldValues" [fv]- (let [db-path (first (serdes/path fv))]- [[db-path]]))-(defmethod serdes/load-find-local "FieldValues" [path];; Delegate to finding the parent Field, then look up its corresponding FieldValues.(let [field (serdes/load-find-local (pop path))]diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.cljindex 9f4fd4fcb6f..e8ffc39fa6c 100644--- a/src/metabase/warehouse_schema/models/table.clj+++ b/src/metabase/warehouse_schema/models/table.clj@@ -560,8 +560,8 @@(warehouse-schema.db/database (:db_id table)));;; ------------------------------------------------- Serialization --------------------------------------------------(defmethod serdes/deserialization-dependencies "Table" [{:keys [db_id collection_id transform_id]}]- (cond-> [[{:model "Database" :id db_id}]]+(defmethod serdes/deserialization-dependencies "Table" [{:keys [collection_id transform_id]}]+ (cond-> []collection_id (conj [{:model "Collection" :id collection_id}])transform_id (conj [{:model "Transform" :id transform_id}])))@@ -597,7 +597,8 @@(-> path second :id))table-name (-> path last :id)db-id (warehouse-schema.db/database-id-by-name db-name)]- (warehouse-schema.db/table-by-name db-id schema-name table-name)))+ (when db-id+ (warehouse-schema.db/table-by-name db-id schema-name table-name))))(defmethod serdes/make-spec "Table" [_model-name _opts]{:copy [:name :description :entity_type :active :display_name :visibility_type :schemadiff --git a/src/metabase/warehouse_schema/models/table_user_settings.clj b/src/metabase/warehouse_schema/models/table_user_settings.cljindex 3ba3c6c9ea8..8b9c57c8213 100644--- a/src/metabase/warehouse_schema/models/table_user_settings.clj+++ b/src/metabase/warehouse_schema/models/table_user_settings.clj@@ -160,10 +160,9 @@(conj (serdes/table->path (serdes/*export-table-fk* table_id)){:model "TableUserSettings" :id "1"}))-(defmethod serdes/deserialization-dependencies "TableUserSettings" [tus]- (let [db-path (first (serdes/path tus))]- (cond-> [[db-path]]- (:collection_id tus) (conj [{:model "Collection" :id (:collection_id tus)}]))))+(defmethod serdes/deserialization-dependencies "TableUserSettings" [{:keys [collection_id]}]+ (when collection_id+ [[{:model "Collection" :id collection_id}]]))(defmethod serdes/load-find-local "TableUserSettings" [path](let [found-table (serdes/load-find-local (pop path))]diff --git a/src/metabase/warehouses/db.clj b/src/metabase/warehouses/db.cljindex 5da3d2f0de9..53fde593478 100644--- a/src/metabase/warehouses/db.clj+++ b/src/metabase/warehouses/db.clj@@ -47,13 +47,14 @@(t2/update! :model/Database database-id {:provider_name provider-name}))(mu/defn health-check-candidate-ids- "The `:id` of the lowest-id non-audit, non-sample, non-destination Database of each engine."+ "The `:id` of the lowest-id non-audit, non-sample, non-stub, non-destination Database of each engine."[](t2/query {:select [[:%min.id :id]]:from [(t2/table-name :model/Database)]:where [:and[:= :is_audit false][:= :is_sample false]+ [:= :is_stub false][:= :router_database_id nil]]:group-by [:engine]}))@@ -147,7 +148,7 @@{:from [(warehouse-schema-overlay/field-query)]}))(mu/defn databases-for-serdes-reducible- "A reducible of the Databases to export via serdes: routing destinations and the sample database are always+ "A reducible of the Databases to export via serdes: routing destinations, stubs and the sample database are alwaysexcluded, H2 databases unless `include-h2?`, and the export is restricted to the rows whose `filter-column` is oneof `filter-ids` when `filter-column` is given."[filter-column :- [:maybe :keyword]@@ -160,6 +161,7 @@[:= :router_database_id nil];; never export the sample database, regardless of its driver[:not= :is_sample true]+ [:not= :is_stub true](when-not include-h2?[:not= :engine "h2"])]}))diff --git a/src/metabase/warehouses/models/database.clj b/src/metabase/warehouses/models/database.cljindex 50a05f31b5c..42e1a0b75b6 100644--- a/src/metabase/warehouses/models/database.clj+++ b/src/metabase/warehouses/models/database.clj@@ -478,21 +478,6 @@"Every place a Database stores a set of connection details."[:details :write_data_details :admin_details])-(defn- exempt-audit-db?- "Whether `database` is the Audit DB as the analytics installer writes it: a clone of the *application* database- rather than a warehouse anybody pointed somewhere, carrying no details of its own and reached over the app-db- connection. There is no user-supplied host in it to police, and checking it anyway refuses the instance's own app- db -- empty details read as `localhost`, since every `:sql-jdbc` client substitutes that. The refusal lands during- init, so the instance fails to boot rather than failing a request.-- Narrowed to a database with no details at all, which is the only shape the installer produces- ([[metabase-enterprise.audit-app.audit/install-database!]] writes none and nothing else adds any). `:is_audit`- alone would be too much to hang this on: it is not writable through the API, but it is in the Database serdes- `:copy` set, and serialization import is one of the routes this check exists to cover."- [database]- (and (:is_audit database)- (every? #(empty? (get database %)) details-keys)))-(defn- validate-connection-hosts!"Refuse to store details pointing at a private/internal network address. Enforcing this on the model, and not just onthe endpoints that test a connection, covers the routes that write a Database without ever testing it: serialization@@ -502,16 +487,15 @@[[metabase.driver.connection/effective-details]] resolves it -- merged onto `:details` -- since that, and not theoverlay by itself, is what a connection is opened with: one holding nothing but credentials repoints nothing.- The Audit DB is exempt -- see [[exempt-audit-db?]]."+ An empty details map configures no connection, so it is not checked."[engine database keys-to-check]- (when-not (exempt-audit-db? database)- (when-let [engine (some-> engine keyword)]- (driver.u/with-database-network-policy database- (doseq [k keys-to-check- :let [details (get database k)]- :when (map? details)]- (driver.u/validate-connection-hosts! engine (cond->> details- (not= k :details) (merge (:details database)))))))))+ (when-let [engine (some-> engine keyword)]+ (driver.u/with-database-network-policy database+ (doseq [k keys-to-check+ :let [details (get database k)]+ :when (and (map? details) (seq details))]+ (driver.u/validate-connection-hosts! engine (cond->> details+ (not= k :details) (merge (:details database))))))))(t2/define-before-update :model/Database[database]@@ -695,7 +679,7 @@(let [details-transform {:export-with-context (fn [_current _ _details] ::serdes/skip):import identity}]{:copy [:auto_run_queries :cache_field_values_schedule :caveats :dbms_version- :description :engine :is_audit :is_attached_dwh :is_full_sync :is_on_demand :is_sample :is_stub+ :description :engine :is_audit :is_attached_dwh :is_full_sync :is_on_demand :is_sample:default_schema :metadata_sync_schedule :name :points_of_interest :provider_name :refingerprint :settings :timezone :uploads_enabled:uploads_schema_name :uploads_table_prefix]:skip [;; deprecated field@@ -708,7 +692,9 @@:admin_details details-transform:creator_id (serdes/fk :model/User):router_database_id (serdes/fk :model/Database)- :initial_sync_status {:export identity :import (constantly "complete")}}+ :initial_sync_status {:export identity :import (constantly "complete")}+ :is_stub {:export-with-context (fn [_current _ _is-stub] ::serdes/skip)+ :import (constantly false)}}:defaults {:auto_run_queries true:is_attached_dwh false:is_audit false@@ -781,7 +767,7 @@:updated-at true}:search-terms {:name search.spec/explode-camel-case:description true}- :where [:= :router_database_id nil]+ :where [:and [:= :router_database_id nil] [:= :is_stub false]]:render-terms {:initial-sync-status true}})(defenterprise hydrate-router-user-attributediff --git a/src/metabase/warehouses_rest/api.clj b/src/metabase/warehouses_rest/api.cljindex 50496a3611b..4d1ef753dee 100644--- a/src/metabase/warehouses_rest/api.clj+++ b/src/metabase/warehouses_rest/api.clj@@ -289,6 +289,7 @@include-saved-questions-tables?include-editable-data-model?include-analytics?+ include-stubs?exclude-uneditable-details?include-only-uploadable?router-database-id@@ -302,7 +303,7 @@filter-on-router-database-id))dbs (warehouses-rest.db/databases-where api/*current-user-id* (mi/superuser?) api/*is-data-analyst?*filter-by-data-access? filter-on-router-database-id- include-analytics?)+ include-analytics? include-stubs?);; everything below walks the list one database at a time_ (perms/prime-database-perms-cache {:db-ids (into #{} (map :id) dbs)})](cond-> (-> dbs add-native-perms-info add-transforms-perms-info)@@ -346,6 +347,8 @@* `include_only_uploadable` will only include DBs into which Metabase can insert new data.+ * `include_stubs` includes stub DBs, which serialization creates for missing databases. Default: `false`.+* `can-query` will only include DBs for which the current user has query permissions. Default: `false`.* `can-write-metadata` will only include DBs for which the current user has data model editing permissions@@ -358,12 +361,13 @@{:scope api-scope/data-app}[_route-params{:keys [include saved include_editable_data_model exclude_uneditable_details include_only_uploadable include_analytics- router_database_id can-query can-write-metadata]}+ include_stubs router_database_id can-query can-write-metadata]}:- [:map {:closed true}[:include {:optional true} (mu/with-api-error-message[:maybe [:enum "tables" "schemas"]](deferred-tru "include must be either empty, ''tables'', or ''schemas''"))][:include_analytics {:default false} [:maybe :boolean]]+ [:include_stubs {:default false} [:maybe :boolean]][:saved {:default false} [:maybe :boolean]][:include_editable_data_model {:default false} [:maybe :boolean]][:exclude_uneditable_details {:default false} [:maybe :boolean]]@@ -387,6 +391,7 @@:include-editable-data-model? include_editable_data_model:exclude-uneditable-details? only-editable?:include-analytics? include_analytics+ :include-stubs? include_stubs:include-only-uploadable? include_only_uploadable:router-database-id router_database_id:can-query? can-query@@ -1041,16 +1046,18 @@:refingerprint refingerprint:is_full_sync full-sync?:is_on_demand on-demand?- :is_stub (when (and (or details-changed? engine-changed?)- (nil? main-conn-error))- false):description description:caveats caveats:points_of_interest points_of_interest:auto_run_queries auto_run_queries:settings (when (seq settings) pending-settings)}- :non-nil #{:name :engine :details :refingerprint :is_full_sync :is_on_demand :is_stub+ :non-nil #{:name :engine :details :refingerprint :is_full_sync :is_on_demand:description :caveats :points_of_interest :auto_run_queries :settings})+ (when (and (:is_stub existing-database)+ (or details-changed? engine-changed?))+ {:is_stub false+ :initial_sync_status "incomplete"+ :initial_sync_error nil});; these fields can be nil(when (contains? body :provider_name){:provider_name provider_name})@@ -1422,12 +1429,15 @@connection-type (or connection-type :default)connection-details (driver.conn/details-for-exact-type database connection-type)](api/check-400 connection-details (tru "No {0} connection configured for this database" (name connection-type)))- ;; we only want to prevent creating new H2 databases. Testing the existing database is fine.- (binding [driver.settings/*allow-testing-h2-connections* true- driver.settings/*allow-testing-sqlite-connections* true]- (if-let [err-map (warehouses/test-database-connection engine connection-details)]- (merge err-map {:status "error"})- {:status "ok"}))))+ (if (:is_stub database)+ {:status "error"+ :message (tru "This database has placeholder connection details. Replace that with actual connection details to make this connection Active.")}+ ;; we only want to prevent creating new H2 databases. Testing the existing database is fine.+ (binding [driver.settings/*allow-testing-h2-connections* true+ driver.settings/*allow-testing-sqlite-connections* true]+ (if-let [err-map (warehouses/test-database-connection engine connection-details)]+ (merge err-map {:status "error"})+ {:status "ok"})))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/src/metabase/warehouses_rest/db.clj b/src/metabase/warehouses_rest/db.cljindex 7df660462f8..6b9470bf8a6 100644--- a/src/metabase/warehouses_rest/db.clj+++ b/src/metabase/warehouses_rest/db.clj@@ -78,19 +78,21 @@(mu/defn databases-where"The Databases visible to the user with `user-id` (`is-superuser?`/`is-data-analyst?` further widen visibility), in- name then engine order. Excludes stub Databases and, unless `include-analytics?`, the audit Database. Restricted- to Databases routed from `router-database-id` when given, otherwise to non-routed Databases. When- `filter-by-data-access?` is true, further restricted to Databases the user can query, manage, or edit the- metadata of."+ name then engine order. Excludes stub Databases unless `include-stubs?` and the audit Database unless+ `include-analytics?`. Restricted to Databases routed from `router-database-id` when given, otherwise to non-routed+ Databases. When `filter-by-data-access?` is true, further restricted to Databases the user can query, manage, or edit+ the metadata of."[user-id :- ::lib.schema.id/useris-superuser? :- :booleanis-data-analyst? :- :booleanfilter-by-data-access? :- :booleanrouter-database-id :- [:maybe ::lib.schema.id/database]- include-analytics? :- :boolean]+ include-analytics? :- :boolean+ include-stubs? :- :boolean](let [user-info {:user-id user-id :is-superuser? is-superuser? :is-data-analyst? is-data-analyst?}base-where [:and- [:= :is_stub false]+ (when-not include-stubs?+ [:= :is_stub false])(when-not include-analytics?[:= :is_audit false])(if router-database-iddiff --git a/test/metabase/models/serialization/resolve/default_test.clj b/test/metabase/models/serialization/resolve/default_test.cljindex 819ad4f9d6b..7cbe15e4162 100644--- a/test/metabase/models/serialization/resolve/default_test.clj+++ b/test/metabase/models/serialization/resolve/default_test.clj@@ -36,11 +36,31 @@:active false}(t2/select-one :model/Table :id table-id))))))))-(deftest import-table-fk-throws-when-database-missing-test- (testing "throws when the database itself does not exist"- (is (thrown-with-msg? clojure.lang.ExceptionInfo- #"database not found"- (serdes/*import-table-fk* ["does-not-exist" "public" "users"])))))+(deftest import-database-fk-existing-test+ (testing "returns the existing database id when found"+ (mt/with-temp [:model/Database {db-id :id} {:name "test-db"}]+ (is (= db-id (serdes/*import-database-fk* "test-db"))))))++(deftest import-database-fk-synthesizes-stub-database-test+ (testing "creates a stub database when the database doesn't exist"+ (mt/with-model-cleanup [:model/Database]+ (let [db-id (serdes/*import-database-fk* "does-not-exist")]+ (is (=? {:id db-id+ :name "does-not-exist"+ :engine :postgres+ :details {}+ :is_stub true}+ (t2/select-one :model/Database :id db-id)))))))++(deftest import-table-fk-synthesizes-stub-database-test+ (testing "creates a stub database and an inactive table when the database doesn't exist"+ (mt/with-model-cleanup [:model/Database :model/Table]+ (let [table-id (serdes/*import-table-fk* ["does-not-exist" "public" "users"])+ table (t2/select-one :model/Table :id table-id)]+ (is (=? {:name "users" :schema "public" :active false}+ table))+ (is (=? {:name "does-not-exist" :is_stub true}+ (t2/select-one :model/Database :id (:db_id table))))))))(deftest import-field-fk-existing-test(testing "returns the existing field id when found"diff --git a/test/metabase/models/serialization_test.clj b/test/metabase/models/serialization_test.cljindex 4466a2f14f8..368da79031f 100644--- a/test/metabase/models/serialization_test.clj+++ b/test/metabase/models/serialization_test.clj@@ -307,23 +307,23 @@(get-in (#'serdes/import-mbql* exported) ["table" :table-id])))))))(deftest ^:parallel template-tag-table-id-deps-test- (testing "template tag :table-id contributes only its Database dependency — the referenced Table itself is not a- dependency (it's synthesized on import if missing)"- (is (= #{[{:model "Database" :id "DB"}]}+ (testing "template tag :table-id is not a dependency — the referenced Database and Table are synthesized on import if+ missing"+ (is (= #{}(#'serdes/mbql-deps-map false {:table-id ["DB" "SCHEMA" "TABLE"]})))))(deftest ^:parallel mbql-deps-format-parity-test(testing "mbql-deps finds each reference on both the serialized (portable) and the raw (numeric) form of a query.serialization-dependencies runs on raw entities and existence-checks the referenced Table/Field;- deserialization-dependencies runs on the serialized form, where Table/Field are synthesized on import, so- it reports only their Database. Every other ref type resolves to the same model in both forms. This is the- parity guard for the two dependency codepaths sharing mbql-deps."+ deserialization-dependencies runs on the serialized form, where Database/Table/Field are synthesized on+ import, so it reports none of them. Every other ref type resolves to the same model in both forms. This is+ the parity guard for the two dependency codepaths sharing mbql-deps."(let [models (fn [deps] (into #{} (map (comp :model last)) deps))eid (fn [c] (apply str (repeat 21 c)))](testing "MBQL ref clauses"(doseq [[label serialized raw ser-models raw-models]- [["field (MBQL 5)" [:field {} ["DB" "S" "T" "F"]] [:field {} 53] #{"Database"} #{"Field"}]- ["field (legacy)" [:field ["DB" "S" "T" "F"] {}] [:field 53 {}] #{"Database"} #{"Field"}]+ [["field (MBQL 5)" [:field {} ["DB" "S" "T" "F"]] [:field {} 53] #{} #{"Field"}]+ ["field (legacy)" [:field ["DB" "S" "T" "F"] {}] [:field 53 {}] #{} #{"Field"}]["metric" [:metric {} (eid \a)] [:metric {} 99] #{"Card"} #{"Card"}]["segment" [:segment {} (eid \b)] [:segment {} 5] #{"Segment"} #{"Segment"}]["measure" [:measure {} (eid \c)] [:measure {} 3] #{"Measure"} #{"Measure"}]]]@@ -333,7 +333,7 @@"raw (numeric) form"))))(testing "MBQL map keys"(doseq [[label serialized raw ser-models raw-models]- [["source-table" {:source-table ["DB" "S" "T"]} {:source-table 9} #{"Database"} #{"Table"}]+ [["source-table" {:source-table ["DB" "S" "T"]} {:source-table 9} #{} #{"Table"}]["source-card" {:source-card (eid \d)} {:source-card 7} #{"Card"} #{"Card"}]["snippet-id" {:snippet-id (eid \e)} {:snippet-id 2} #{"NativeQuerySnippet"} #{"NativeQuerySnippet"}]]](testing labeldiff --git a/test/metabase/sync/events/sync_database_test.clj b/test/metabase/sync/events/sync_database_test.cljindex a0105bac695..47f873d9f0a 100644--- a/test/metabase/sync/events/sync_database_test.clj+++ b/test/metabase/sync/events/sync_database_test.clj@@ -25,3 +25,31 @@(mt/with-temporary-setting-values [disable-auto-sync true](events/publish-event! :event/database-create {:object db :user-id (mt/user->id :crowberto)}))(is (zero? @calls))))))))++(deftest database-update-event-syncs-connected-stub-test+ (testing "The :event/database-update handler kicks off a sync only when a stub database gets connected"+ (mt/with-temp [:model/Database {:as stub} {:is_full_sync true :is_stub true}+ :model/Database {:as db} {:is_full_sync true}]+ (let [calls (atom 0)+ connected (assoc stub :is_stub false)]+ (mt/with-dynamic-fn-redefs [quick-task/submit-task! (fn [task] (task))+ sync/sync-database! (fn [_] (swap! calls inc))+ sync-metadata/sync-db-metadata! (fn [_] (swap! calls inc))]+ (testing "a stub that gets connected is synced"+ (reset! calls 0)+ (events/publish-event! :event/database-update {:object connected+ :previous-object stub+ :user-id (mt/user->id :crowberto)})+ (is (= 1 @calls)))+ (testing "a stub that stays a stub is not synced"+ (reset! calls 0)+ (events/publish-event! :event/database-update {:object stub+ :previous-object stub+ :user-id (mt/user->id :crowberto)})+ (is (zero? @calls)))+ (testing "a regular database update is not synced"+ (reset! calls 0)+ (events/publish-event! :event/database-update {:object db+ :previous-object db+ :user-id (mt/user->id :crowberto)})+ (is (zero? @calls))))))))diff --git a/test/metabase/warehouses/models/database_test.clj b/test/metabase/warehouses/models/database_test.cljindex 9d0dd6989aa..24107f76c70 100644--- a/test/metabase/warehouses/models/database_test.clj+++ b/test/metabase/warehouses/models/database_test.clj@@ -137,6 +137,7 @@:model/Database {dest :id} {:engine :mysql :router_database_id router}:model/Database {sample :id} {:engine :mysql :is_sample true}:model/Database {audit :id} {:engine :mysql :is_audit true}+ :model/Database {stub :id} {:engine :mysql :is_stub true}:model/Database {_mysql :id} {:engine :mysql}:model/Database {pg2 :id} {:engine :postgres}:model/Database {pg3 :id} {:engine :postgres}]@@ -156,7 +157,9 @@(testing "sample databases can't claim an engine's slot"(is (not (contains? candidate-ids sample))))(testing "audit databases are never candidates"- (is (not (contains? candidate-ids audit))))))))+ (is (not (contains? candidate-ids audit))))+ (testing "stub databases can't claim an engine's slot"+ (is (not (contains? candidate-ids stub))))))))(deftest check-health!-test(mt/test-drivers (mt/normal-drivers)@@ -816,34 +819,17 @@#"private or internal network address"(t2/update! :model/Database (:id db) {:admin_details {:host "127.0.0.1" :user "hummingbird"}})))))))-(deftest audit-db-is-not-subject-to-the-network-policy-test- ;; The Audit DB is a clone of the *application* database, not a warehouse an admin pointed somewhere: it carries no- ;; `:details` and is reached over the app-db connection. Under the policy its empty details read as `localhost` --- ;; every `:sql-jdbc` client substitutes that -- so validating it refuses the instance's own app db.- ;;- ;; This has to hold on update as well as insert, because- ;; [[metabase-enterprise.audit-app.audit/adjust-audit-db-to-source!]] flips `:engine` to "postgres" on every boot- ;; that installs analytics, and an `:engine` change is what makes `before-update` validate every details map. A- ;; refusal there is thrown during init, so Metabase fails to start rather than failing a request.+(deftest empty-details-are-not-subject-to-the-network-policy-test(mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]- (testing "the audit db can be created"- (mt/with-temp [:model/Database db {:is_audit true, :engine :h2, :details {}}]- (testing "and its engine can be flipped the way installing analytics flips it"- (is (pos? (t2/update! :model/Database (:id db) {:engine "postgres"}))))))- (testing "an ordinary database with the same empty details is still refused"- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"private or internal network address"- (t2/insert! :model/Database {:name "not the audit db", :engine :postgres, :details {}}))))- (testing "`is_audit` is not itself a way past the policy -- serdes import can set it, so the exemption is- narrowed to the detail-less shape the analytics installer actually writes"- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"private or internal network address"- (t2/insert! :model/Database {:name "audit-flavored smuggling"- :is_audit true- :engine (u/qualified-name ::host-details-driver)- :details {:host "127.0.0.1"}}))))))+ (testing "a database with empty details can be created"+ (mt/with-temp [:model/Database db {:engine :h2, :details {}}]+ (testing "and its engine changed, the way installing analytics flips the audit db's"+ (is (pos? (t2/update! :model/Database (:id db) {:engine "postgres"}))))+ (testing "but giving it an internal address is refused"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"private or internal network address"+ (t2/update! :model/Database (:id db) {:details {:host "127.0.0.1"}}))))))))(deftest attached-dwh-relaxes-the-network-policy-test(mt/with-temp-env-var-value! [mb-warehouse-allowed-networks "external-only"]@@ -883,13 +869,11 @@(t2/select-one-fn :engine :model/Database :id db-id))))))(deftest ^:parallel serdes-extract-is-stub-test- (testing "serdes/extract-one preserves :is_stub true and elides it when false"+ (testing "serdes/extract-one never exports :is_stub"(mt/with-temp [:model/Database stub {:engine :h2 :name "stub" :is_stub true}:model/Database non-stub {:engine :h2 :name "non-stub"}]- (testing "stub DB carries :is_stub true into the extracted map"- (is (true? (:is_stub (serdes/extract-one "Database" nil stub)))))- (testing "non-stub DB elides :is_stub from the extracted map (matches default)"- (is (not (contains? (serdes/extract-one "Database" nil non-stub) :is_stub)))))))+ (is (not (contains? (serdes/extract-one "Database" nil stub) :is_stub)))+ (is (not (contains? (serdes/extract-one "Database" nil non-stub) :is_stub))))))(deftest create-database-with-null-details-test(testing "Details should get a default value of {} if unspecified"diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.cljindex 7e5d8544496..41c3721f768 100644--- a/test/metabase/warehouses_rest/api_test.clj+++ b/test/metabase/warehouses_rest/api_test.clj@@ -220,7 +220,14 @@:model/Database {db-id-2 :id} {:is_stub false}](let [{databases :data} (mt/user-http-request :lucky :get 200 "database")](is (nil? (m/find-first #(= (:id %) db-id-1) databases)))- (is (some? (m/find-first #(= (:id %) db-id-2) databases))))))))+ (is (some? (m/find-first #(= (:id %) db-id-2) databases))))+ (testing "unless include_stubs is passed"+ (let [{databases :data} (mt/user-http-request :crowberto :get 200 "database" :include_stubs true)]+ (is (some? (m/find-first #(= (:id %) db-id-1) databases)))+ (is (some? (m/find-first #(= (:id %) db-id-2) databases)))))+ (testing "A stub database can be fetched by id"+ (is (=? {:id db-id-1 :is_stub true}+ (mt/user-http-request :crowberto :get 200 (format "database/%d" db-id-1)))))))))(deftest get-database-legacy-no-self-service-test(testing "GET /api/database/:id"@@ -645,6 +652,21 @@:details {:db "my_db"}:is_stub true})))))))+(deftest connect-stub-database-test+ (testing "PUT /api/database/:id with connection details for a stub clears is_stub and restarts the initial sync"+ (mt/with-temporary-setting-values [disable-auto-sync true]+ (mt/with-temp [:model/Database {db-id :id} {:engine :postgres+ :details {}+ :is_stub true+ :initial_sync_status "complete"+ :initial_sync_error "stale"}]+ (with-redefs [driver/can-connect? (constantly true)]+ (api-update-database! 200 db-id {:details {:host "localhost" :dbname "prod"}}))+ (is (=? {:is_stub false+ :initial_sync_status "incomplete"+ :initial_sync_error nil}+ (t2/select-one :model/Database :id db-id)))))))+(deftest reject-is-stub-in-update-test(testing "PUT /api/database/:id returns a 400 when :is_stub=true is in the request body"(mt/with-temp [:model/Database {db-id :id} {:engine ::test-driver}]@@ -2991,6 +3013,13 @@(is (= {:status "error":message "Failed to connect to Database"}(mt/user-http-request :crowberto :get 200 (str "database/" id "/healthcheck")))))))+ (testing "stub database reports that it has no connection details without trying to connect"+ (mt/with-temp [:model/Database {id :id} {:is_stub true :details {}}]+ (with-redefs [driver/available? (constantly true)+ driver/can-connect? (constantly true)]+ (is (= {:status "error"+ :message "This database has placeholder connection details. Replace that with actual connection details to make this connection Active."}+ (mt/user-http-request :crowberto :get 200 (str "database/" id "/healthcheck")))))))(when config/ee-available?(testing "connection-type passed and configured"(mt/with-premium-features #{:writable-connection}