Skip to content

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

Require explicit user approval for agent data access (#69280)

Ngoc Khuat636dc63968fc
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 667de922cc4..c611f5c7db2 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -2455,6 +2455,7 @@
metabase-enterprise.workspaces.init}
:uses #{api
api-keys
+ app-db
config
database-routing
driver
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index c88c7496266..1071222c441 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -134,6 +134,7 @@
;; serialization, hence we should revisit this later in the project.
"WorkspaceInput"
"WorkspaceInputExternal"
+ "WorkspaceInputTransform"
"WorkspaceLog"
"WorkspaceMerge"
"WorkspaceMergeTransform"
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/api.clj b/enterprise/backend/src/metabase_enterprise/workspaces/api.clj
index c444563ac68..557dd408005 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/api.clj
@@ -8,6 +8,7 @@
[medley.core :as m]
[metabase-enterprise.workspaces.common :as ws.common]
[metabase-enterprise.workspaces.impl :as ws.impl]
+ [metabase-enterprise.workspaces.isolation :as ws.isolation]
[metabase-enterprise.workspaces.merge :as ws.merge]
[metabase-enterprise.workspaces.models.workspace :as ws.model]
[metabase-enterprise.workspaces.models.workspace-input-external]
@@ -135,6 +136,7 @@
"/graph$"
"/problem$"
"/external/transform$"
+ "/input/pending$"
"/transform$"
"/transform/[^/]+$"]
;; Manage & run transforms
@@ -959,6 +961,15 @@
(ws.impl/increment-graph-version! ws-id)
nil)
+(defn- check-inputs-granted! [ws-id tx-id]
+ (let [ungranted (ws.impl/ungranted-inputs-for-transform ws-id tx-id)]
+ (when (seq ungranted)
+ (let [tables (mapv #(select-keys % [:db_id :schema :table]) ungranted)]
+ (throw (ex-info (str "Transform cannot run: the following input tables have not been granted access: "
+ (pr-str tables))
+ {:status-code 400
+ :ungranted-tables tables}))))))
+
(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/run"
:- ::ws.t/execution-result
"Run a transform in a workspace.
@@ -976,6 +987,7 @@
transform (api/check-404 (t2/select-one :model/WorkspaceTransform :workspace_id ws-id :ref_id tx-id))
_ (api/check-400 (not= :archived (:base_status workspace)) "Cannot execute archived workspace")
_ (check-transforms-enabled! (:database_id workspace))
+ _ (check-inputs-granted! ws-id tx-id)
graph (ws.impl/get-or-calculate-graph! workspace)
run-ancestors? (flag-enabled? run_stale_ancestors)
ancestors-result (when run-ancestors?
@@ -1008,6 +1020,7 @@
transform (api/check-404 (t2/select-one :model/WorkspaceTransform :workspace_id ws-id :ref_id tx-id))
_ (api/check-400 (not= :archived (:base_status workspace)) "Cannot execute archived workspace")
_ (check-transforms-enabled! (:database_id workspace))
+ _ (check-inputs-granted! ws-id tx-id)
graph (ws.impl/get-or-calculate-graph! workspace)
run-ancestors? (flag-enabled? run_stale_ancestors)
ancestors-result (when run-ancestors?
@@ -1041,6 +1054,105 @@
graph (ws.impl/get-or-calculate-graph! workspace)]
(ws.impl/execute-adhoc-query workspace graph sql)))
+;;; ---------------------------------------- Input Grant Endpoints ----------------------------------------
+
+(def ^:private PendingInput
+ [:map
+ [:db_id ::ws.t/appdb-id]
+ [:schema [:maybe :string]]
+ [:table :string]])
+
+(defn- pending-inputs
+ "Pending (ungranted) inputs in a workspace, excluding tables shadowed by workspace outputs.
+ Only includes inputs that are still referenced by at least one current transform version.
+ Unlike query-ungranted-external-inputs, this includes tables that may not exist yet in metabase_table."
+ [workspace-id]
+ (t2/select [:model/WorkspaceInput :db_id :schema :table]
+ {:where [:and
+ [:= :workspace_input.workspace_id workspace-id]
+ [:= :workspace_input.access_granted false]
+ ;; Only include inputs referenced by a current transform version.
+ [:exists {:select [1]
+ :from [[:workspace_input_transform :wit]]
+ :where [:and
+ [:= :wit.workspace_input_id :workspace_input.id]
+ [:= :wit.transform_version
+ {:select [[:%max.transform_version]]
+ :from [[:workspace_input_transform :wit2]]
+ :where [:and
+ [:= :wit2.workspace_id :wit.workspace_id]
+ [:= :wit2.ref_id :wit.ref_id]]}]]}]
+ ;; Ignore tables that will be shadowed by outputs of other transforms.
+ [:not [:exists {:select [1]
+ :from [[:workspace_output :wo]]
+ :where [:and
+ [:= :wo.workspace_id :workspace_input.workspace_id]
+ [:= :wo.db_id :workspace_input.db_id]
+ [:or
+ [:and [:= :wo.global_schema nil] [:= :workspace_input.schema nil]]
+ [:= :wo.global_schema :workspace_input.schema]]
+ [:= :wo.global_table :workspace_input.table]]}]]
+ [:not [:exists {:select [1]
+ :from [[:workspace_output_external :woe]]
+ :where [:and
+ [:= :woe.workspace_id :workspace_input.workspace_id]
+ [:= :woe.db_id :workspace_input.db_id]
+ [:or
+ [:and [:= :woe.global_schema nil] [:= :workspace_input.schema nil]]
+ [:= :woe.global_schema :workspace_input.schema]]
+ [:= :woe.global_table :workspace_input.table]]}]]]
+ :order-by [:db_id :schema :table]}))
+
+(api.macros/defendpoint :get "/:ws-id/input/pending"
+ :- [:map [:inputs [:sequential PendingInput]]]
+ "List all input tables that haven't been granted access yet, excluding tables shadowed by workspace outputs."
+ {:access :workspace}
+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]]
+ (api/check-404 (t2/select-one :model/Workspace :id ws-id))
+ {:inputs (pending-inputs ws-id)})
+
+(api.macros/defendpoint :post "/:ws-id/input/grant"
+ :- [:map
+ [:already_granted [:sequential [:map [:db_id ms/PositiveInt] [:schema [:maybe :string]] [:table :string]]]]
+ [:newly_granted [:sequential [:map [:db_id ms/PositiveInt] [:schema [:maybe :string]] [:table :string]]]]]
+ "Grant read access to input tables by table coordinates. Superuser only.
+ Idempotent - returns which tables were already granted vs newly granted."
+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]
+ _query-params
+ {:keys [tables]} :- [:map [:tables [:sequential [:map
+ [:db_id ms/PositiveInt]
+ [:schema [:maybe :string]]
+ [:table :string]]]]]]
+ (let [workspace (api/check-404 (t2/select-one :model/Workspace ws-id))
+ ;; Batch lookup: one query per (db_id, schema) group for efficiency
+ input-lookup (into {}
+ (for [[_ group] (group-by (juxt :db_id :schema) tables)
+ :let [db-id (:db_id (first group))
+ schema (:schema (first group))
+ names (mapv :table group)]
+ row (t2/select [:model/WorkspaceInput :id :db_id :schema :table :access_granted]
+ :workspace_id ws-id
+ :db_id db-id
+ :schema schema
+ :table [:in names])]
+ [[(:db_id row) (:schema row) (:table row)] row]))
+ all-inputs (mapv #(get input-lookup [(:db_id %) (:schema %) (:table %)]) tables)]
+ (when (some nil? all-inputs)
+ (api/check-400 false
+ (str "The following tables do not have corresponding input rows: "
+ (pr-str (keep (fn [[table input]] (when-not input table))
+ (map vector tables all-inputs))))))
+ (let [{already-granted true ungranted false} (group-by :access_granted all-inputs)]
+ ;; Grant access to ungranted tables, grouped by db_id
+ (when (seq ungranted)
+ (doseq [[db-id inputs] (group-by :db_id ungranted)
+ :let [database (t2/select-one :model/Database :id db-id)
+ tables (mapv (fn [{:keys [schema table]}] {:schema schema :name table}) inputs)]]
+ (ws.isolation/grant-read-access-to-tables! database workspace tables))
+ (t2/update! :model/WorkspaceInput {:id [:in (map :id ungranted)]} {:access_granted true}))
+ {:already_granted (mapv #(select-keys % [:db_id :schema :table]) already-granted)
+ :newly_granted (mapv #(select-keys % [:db_id :schema :table]) ungranted)})))
+
(def ^:private CheckoutTransformLegacy
"Legacy format for workspace checkout transforms (DEPRECATED)."
[:map
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/dag.clj b/enterprise/backend/src/metabase_enterprise/workspaces/dag.clj
index d218e19c594..a4f3b7af690 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/dag.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/dag.clj
@@ -67,17 +67,23 @@
;; Get the latest version - which may have changed since we started this graph analysis (!!!)
;; Unfortunately, since each transform is versioned separately, it's not trivial to freeze to a snapshot.
;; NOTE: Perhaps this is a reason to snapshot these rows, or pre-query them all :thinking:
+ ;;
+ ;; After normalization (BOT-955), workspace_input no longer has ref_id/transform_version.
+ ;; We JOIN through workspace_input_transform to find which inputs belong to this transform.
(t2/select-fn-vec (fn [table-coord]
{:node-type :table, :id (t2.realize/realize table-coord)})
[:model/WorkspaceInput [:db_id :db] :schema :table [:table_id :id]]
- :workspace_id ws-id
- :ref_id ref-id
- {:where [:= :transform_version
- {:select [[:%max.transform_version]]
- :from [:workspace_input]
- :where [:and
- [:= :workspace_id ws-id]
- [:= :ref_id ref-id]]}]}))
+ {:join [[:workspace_input_transform :wit]
+ [:= :wit.workspace_input_id :workspace_input.id]]
+ :where [:and
+ [:= :wit.workspace_id ws-id]
+ [:= :wit.ref_id ref-id]
+ [:= :wit.transform_version
+ {:select [[:%max.transform_version]]
+ :from [:workspace_input_transform]
+ :where [:and
+ [:= :workspace_id ws-id]
+ [:= :ref_id ref-id]]}]]}))
(defn- table-producers [ws-id id-or-coord]
;; Work with either logical co-ords or an id
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/dependencies.clj b/enterprise/backend/src/metabase_enterprise/workspaces/dependencies.clj
index 8ab567e6ac9..5066efea514 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/dependencies.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/dependencies.clj
@@ -4,7 +4,8 @@
Unlike the global `dependency` table which links to `table_id` (requiring the table to exist),
workspace dependencies use two tables that support logical references:
- - `workspace_input` - external tables transforms consume (may not exist yet), with ref_id linking to transform
+ - `workspace_input` - external tables transforms consume (may not exist yet)
+ - `workspace_input_transform` - join table linking inputs to transforms (ref_id + transform_version)
- `workspace_output` - tables transforms produce
## Example: Internal Dependency (Transform B depends on Transform A's output)
@@ -36,15 +37,22 @@
If Transform A also depended on an external table ORDERS:
workspace_input:
- | id | ref_id | schema | table | table_id |
- |-----|-------------------|--------|--------|----------|
- | 201 | happy-dolphin-a1b2 | PUBLIC | ORDERS | 42 |
+ | id | schema | table | table_id |
+ |-----|--------|--------|----------|
+ | 201 | PUBLIC | ORDERS | 42 |
- The ref_id directly links the input to its transform, no join table needed."
+ workspace_input_transform:
+ | workspace_input_id | ref_id | transform_version |
+ |--------------------|--------------------|-------------------|
+ | 201 | happy-dolphin-a1b2 | 1 |
+
+ The join table links inputs to transforms, allowing multiple transforms to share a single input row."
(:require
[metabase-enterprise.workspaces.models.workspace-input]
+ [metabase-enterprise.workspaces.models.workspace-input-transform]
[metabase-enterprise.workspaces.models.workspace-output]
[metabase-enterprise.workspaces.util :as ws.u]
+ [metabase.app-db.core :as app-db]
[metabase.driver :as driver]
[metabase.driver.sql :as driver.sql]
;; TODO (Chris 2025-12-17) -- I solemnly declare that we will clean up this coupling nightmare for table normalization
@@ -245,23 +253,38 @@
[default-schema input]
(update input :schema #(or % default-schema)))
+(defn- upsert-workspace-input!
+ "Ensure a workspace_input row exists for the given table coordinate.
+ Returns the workspace_input id (existing or newly created)."
+ [workspace-id {:keys [db_id schema table table_id]}]
+ (app-db/update-or-insert!
+ :model/WorkspaceInput
+ {:workspace_id workspace-id
+ :db_id db_id
+ :schema schema
+ :table table}
+ (fn [existing]
+ (cond-> {:workspace_id workspace-id
+ :db_id db_id
+ :schema schema
+ :table table
+ :table_id (:table_id existing)}
+ table_id (assoc :table_id table_id)))))
+
(defn- insert-workspace-inputs!
- "Insert workspace_input records for the given inputs with the given transform_version.
- Each input row is linked to a specific transform via ref_id.
- With epochal versioning, we always insert new rows - cleanup of old versions happens separately.
- Silently ignores constraint violations from concurrent inserts."
+ "Insert a single workspace_input record per table, with a join entry per transform that uses that table."
[workspace-id ref-id inputs transform-version]
(when (seq inputs)
- (ws.u/ignore-constraint-violation
- (t2/insert! :model/WorkspaceInput
- (for [{:keys [db_id schema table table_id]} inputs]
- {:workspace_id workspace-id
- :ref_id ref-id
- :transform_version transform-version
- :db_id db_id
- :schema schema
- :table table
- :table_id table_id}))))
+ ;; N+1 query here: we query once per input to handle race conditions. Native SQL upserts would be faster
+ ;; but we don't have a driver-independent helper for that.
+ (let [input-ids (mapv (partial upsert-workspace-input! workspace-id) inputs)]
+ (ws.u/ignore-constraint-violation
+ (t2/insert! :model/WorkspaceInputTransform
+ (for [input-id input-ids]
+ {:workspace_input_id input-id
+ :workspace_id workspace-id
+ :ref_id ref-id
+ :transform_version transform-version})))))
nil)
(defn transform-output-exists-for-version?
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/impl.clj b/enterprise/backend/src/metabase_enterprise/workspaces/impl.clj
index f8323b7d9ab..cee59ec06dd 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/impl.clj
@@ -2,11 +2,13 @@
"Glue code connecting workspace subsystems (dependencies, isolation)."
(:require
[clojure.set :as set]
+ [clojure.string :as str]
[metabase-enterprise.workspaces.dag :as ws.dag]
[metabase-enterprise.workspaces.dependencies :as ws.deps]
[metabase-enterprise.workspaces.execute :as ws.execute]
[metabase-enterprise.workspaces.isolation :as ws.isolation]
[metabase-enterprise.workspaces.util :as ws.u]
+ [metabase.api.common :as api]
[metabase.driver.sql :as driver.sql]
[metabase.driver.sql.util :as sql.util]
[metabase.util :as u]
@@ -58,6 +60,24 @@
{:schema schema
:name table})
+(defn ungranted-inputs-for-transform
+ "Return ungranted WorkspaceInput rows that are linked to the given transform (by ref-id).
+ Uses the latest transform_version from workspace_input_transform."
+ [ws-id ref-id]
+ (t2/select [:model/WorkspaceInput :id :db_id :schema :table :table_id]
+ {:join [[:workspace_input_transform :wit]
+ [:= :wit.workspace_input_id :workspace_input.id]]
+ :where [:and
+ [:= :wit.workspace_id ws-id]
+ [:= :wit.ref_id ref-id]
+ [:= :workspace_input.access_granted false]
+ [:= :wit.transform_version
+ {:select [[:%max.transform_version]]
+ :from [:workspace_input_transform]
+ :where [:and
+ [:= :workspace_id ws-id]
+ [:= :ref_id ref-id]]}]]}))
+
(defn sync-grant-accesses!
"Grant read access to external input tables for a workspace that haven't been granted yet.
External inputs are tables that are read by transforms but not produced by any transform in the workspace.
@@ -82,6 +102,13 @@
(when-not (some->> (ex-message e) (re-find #"(?i)(does not exist|not found|no such table)"))
(log/warn e "Error granting RO table permissions")))))))))
+(defn grant-accesses-if-superuser!
+ "Grant read access to external input tables if the current user is a superuser.
+ Wrapper around sync-grant-accesses! that checks superuser permission."
+ [workspace]
+ (when api/*is-superuser?*
+ (sync-grant-accesses! workspace)))
+
(defn- batch-lookup-table-ids
"Given a bounded list of tables, all within the same database, return an association list of [db schema table] => id"
[db-id schema-key table-key table-refs]
@@ -463,7 +490,7 @@
(defn- cleanup-old-transform-versions!
"Delete obsolete analysis for a given workspace transform."
[ws-id ref-id]
- (doseq [model [:model/WorkspaceOutput :model/WorkspaceInput]]
+ (doseq [model [:model/WorkspaceOutput :model/WorkspaceInputTransform]]
(t2/delete! model
:workspace_id ws-id
:ref_id ref-id
@@ -521,7 +548,7 @@
;; Grant any missing read access. Do this even if no transforms were stale, as we may have been unable to grant
;; some permissions previously (insufficient permissions, table didn't exist yet, etc.)
(when (= :ready db-status)
- (sync-grant-accesses! workspace))
+ (grant-accesses-if-superuser! workspace))
(boolean (seq stale-transforms))))
(defn analyze-transform-if-stale!
@@ -530,7 +557,7 @@
[{ws-id :id :as workspace} {:keys [ref_id analysis_version] :as transform}]
(when-not (ws.deps/transform-output-exists-for-version? ws-id ref_id analysis_version)
(analyze-transform! workspace transform)
- (sync-grant-accesses! workspace)))
+ (grant-accesses-if-superuser! workspace)))
(defn- insert-workspace-graph!
"Insert a new graph for the given version. Silently ignores constraint violations
@@ -804,24 +831,68 @@
ref-id-or-id
(str "global-id:" ref-id-or-id)))
+(defn- ungranted-transform-ref-ids
+ "Return the set of workspace transform ref-ids that have at least one ungranted input
+ at their current (max) transform version. str/trim is needed because ref_id is char(36)
+ which pads with trailing spaces."
+ [ws-id]
+ (into #{}
+ (map (comp str/trim :ref_id))
+ (t2/query {:select-distinct [:wit.ref_id]
+ :from [[:workspace_input_transform :wit]]
+ :join [[:workspace_input :wi]
+ [:= :wi.id :wit.workspace_input_id]]
+ :where [:and
+ [:= :wit.workspace_id ws-id]
+ [:= :wi.access_granted false]
+ [:= :wit.transform_version
+ {:select [[:%max.transform_version]]
+ :from [[:workspace_input_transform :wit2]]
+ :where [:and
+ [:= :wit2.workspace_id ws-id]
+ [:= :wit2.ref_id :wit.ref_id]]}]]})))
+
+(defn- ungranted-external-transform-ids
+ "Return the set of external transform IDs (integers) that have at least one ungranted external input.
+ Joins workspace_input_external (ungranted tables) with the dependency table to find which
+ external transforms depend on those tables."
+ [ws-id]
+ (into #{}
+ (map :from_entity_id)
+ (t2/query {:select-distinct [:d.from_entity_id]
+ :from [[:workspace_input_external :wie]]
+ :join [[:dependency :d]
+ [:and
+ [:= :d.to_entity_type "table"]
+ [:= :d.to_entity_id :wie.table_id]
+ [:= :d.from_entity_type "transform"]]]
+ :where [:and
+ [:= :wie.workspace_id ws-id]
+ [:= :wie.access_granted false]
+ [:not= :wie.table_id nil]]})))
+
(defn execute-workspace!
- "Execute all the transforms within a given workspace."
+ "Execute all the transforms within a given workspace.
+ Skips transforms whose inputs have not been granted access."
[workspace graph & {:keys [stale-only?] :or {stale-only? false}}]
(let [ws-id (:id workspace)
- remapping (build-remapping workspace graph)]
+ remapping (build-remapping workspace graph)
+ ungranted-ref-ids (ungranted-transform-ref-ids ws-id)
+ ungranted-external-tx-ids (ungranted-external-transform-ids ws-id)]
(reduce
(fn [acc {external-id :id ref-id :ref_id :as transform}]
(let [node-type (if external-id :external-transform :workspace-transform)
id-str (id->str (or external-id ref-id))]
- (try
- ;; Perhaps we want to return some of the metadata from this as well?
- (if (= :succeeded (:status (run-transform! workspace graph transform remapping)))
- (update acc :succeeded conj id-str)
- ;; Perhaps the status might indicate it never ran?
- (update acc :failed conj id-str))
- (catch Exception e
- (log/error e "Failed to execute transform" {:workspace-id ws-id :node-type node-type :id id-str})
- (update acc :failed conj id-str)))))
+ (if (or (and ref-id (contains? ungranted-ref-ids ref-id))
+ (and external-id (contains? ungranted-external-tx-ids external-id)))
+ (update acc :not_run conj id-str)
+ (try
+ (if (= :succeeded (:status (run-transform! workspace graph transform remapping)))
+ (update acc :succeeded conj id-str)
+ (update acc :failed conj id-str))
+ (catch Exception e
+ (log/error e "Failed to execute transform" {:workspace-id ws-id :node-type node-type :id id-str})
+ (update acc :failed conj id-str))))))
{:succeeded []
:failed []
:not_run []}
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace_input.clj b/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace_input.clj
index 5345d57138b..ca98507d05b 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace_input.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace_input.clj
@@ -1,8 +1,8 @@
(ns metabase-enterprise.workspaces.models.workspace-input
- "Model for WorkspaceInput - external tables that workspace transforms consume.
- Each input is linked to a specific transform via ref_id."
+ "Model for WorkspaceInput - unique external tables that workspace transforms consume.
+ Each row represents a unique (workspace_id, db_id, schema, table) tuple.
+ The m2m relationship to transforms is in workspace_input_transform."
(:require
- [metabase.models.interface :as mi]
[methodical.core :as methodical]
[toucan2.core :as t2]))
@@ -11,6 +11,3 @@
(doto :model/WorkspaceInput
(derive :metabase/model)
(derive :hook/timestamped?))
-
-(t2/deftransforms :model/WorkspaceInput
- {:ref_id mi/transform-trim})
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace_input_transform.clj b/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace_input_transform.clj
new file mode 100644
index 00000000000..594db8120fa
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace_input_transform.clj
@@ -0,0 +1,15 @@
+(ns metabase-enterprise.workspaces.models.workspace-input-transform
+ "Model for WorkspaceInputTransform - join table linking workspace inputs to the transforms that depend on them.
+ Each row associates a unique input table (in workspace_input) with a specific transform version."
+ (:require
+ [metabase.models.interface :as mi]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/WorkspaceInputTransform [_model] :workspace_input_transform)
+
+(doto :model/WorkspaceInputTransform
+ (derive :metabase/model))
+
+(t2/deftransforms :model/WorkspaceInputTransform
+ {:ref_id mi/transform-trim})
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
index 5dd17327901..93317944d95 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
@@ -116,6 +116,7 @@
:model/Workspace
:model/WorkspaceInput
:model/WorkspaceInputExternal
+ :model/WorkspaceInputTransform
:model/WorkspaceLog
:model/WorkspaceMerge
:model/WorkspaceMergeTransform
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/api_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/api_test.clj
index fd3c2741ce4..d7793692938 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/api_test.clj
@@ -1404,7 +1404,6 @@
;; (x1) -> x2 -> (x3)
{:global {:x1 [:t0], :x2 [:x1], :x3 [:x2]}
:workspace {:checkouts [:x1 :x3]}}]
- (ws.tu/ws-done! workspace-id)
(let [ref-x1 (workspace-map :x1)
ref-x3 (workspace-map :x3)
global-x2 (str "global-id:" (global-map :x2))
@@ -1495,7 +1494,6 @@
:properties {:x1 {:definition_changed true}
:x2 {:definition_changed false}
:x3 {:definition_changed false}}}}]
- (ws.tu/ws-done! workspace-id)
(let [x1-ref (workspace-map :x1)
x2-ref (workspace-map :x2)
x3-ref (workspace-map :x3)]
@@ -1529,7 +1527,6 @@
:properties {:x1 {:definition_changed true}
:x2 {:definition_changed false}
:x3 {:definition_changed false}}}}]
- (ws.tu/ws-done! workspace-id)
(let [x1-ref (workspace-map :x1)
x2-ref (workspace-map :x2)
x3-ref (workspace-map :x3)]
@@ -2281,6 +2278,123 @@
(is (= other-db-id
(get-in (t2/select-one :model/Transform :id (:x1 (:global-map result))) [:target :database])))))))))
+;;; ============================================ Input Grant Endpoint Tests ============================================
+
+(deftest run-rejects-ungranted-inputs-test
+ (testing "POST /run and /dry-run reject transforms whose inputs have not been granted access"
+ (ws.tu/with-workspaces! [ws {:name "Ungranted Run Test"}]
+ (let [transform {:name "Transform with input"
+ :source {:type "query"
+ :query (->native (mt/mbql-query orders {:aggregation [[:count]]}))}
+ :target {:type "table"
+ :database (mt/id)
+ :schema "public"
+ :name "ungranted_run_test"}}
+ ref-id (:ref_id (mt/user-http-request :crowberto :post 200
+ (ws-url (:id ws) "/transform") transform))
+ ws (ws.tu/ws-done! (:id ws))]
+ ;; Explicitly trigger analysis to populate workspace_input_transform table
+ (ws.tu/analyze-workspace! (:id ws))
+ ;; Set all inputs for this workspace to ungranted
+ (t2/update! :model/WorkspaceInput {:workspace_id (:id ws)} {:access_granted false})
+ (testing "POST /transform/:tx-id/run returns 400 when inputs are ungranted"
+ (is (str/includes?
+ (mt/user-http-request :crowberto :post 400
+ (ws-url (:id ws) "/transform/" ref-id "/run"))
+ "not been granted access")))
+ (testing "POST /transform/:tx-id/dry-run returns 400 when inputs are ungranted"
+ (is (str/includes?
+ (mt/user-http-request :crowberto :post 400
+ (ws-url (:id ws) "/transform/" ref-id "/dry-run"))
+ "not been granted access")))
+ (testing "After granting access, /run succeeds (does not return 400)"
+ (t2/update! :model/WorkspaceInput {:workspace_id (:id ws)} {:access_granted true})
+ ;; We just check it's not a 400 — the transform may succeed or fail depending on DB state,
+ ;; but it should pass the grant check.
+ (let [result (mt/user-http-request :crowberto :post 200
+ (ws-url (:id ws) "/transform/" ref-id "/run"))]
+ (is (contains? result :status))))))))
+
+(deftest input-pending-test
+ (testing "GET /:ws-id/input/pending returns ungranted inputs"
+ (let [mp (mt/metadata-provider)
+ query (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ ws (ws.tu/create-empty-ws! "Pending Input Test")]
+ (mt/with-dynamic-fn-redefs [ws.isolation/grant-read-access-to-tables! (constantly nil)]
+ ;; Add a transform so workspace has inputs
+ (ws.common/add-to-changeset! (mt/user->id :crowberto) ws
+ :transform nil
+ {:name "Transform with input"
+ :source {:type "query" :query query}
+ :target {:database (mt/id)
+ :schema "analytics"
+ :name "pending_test_table"}})
+ (ws.tu/analyze-workspace! (:id ws))
+ ;; Ensure inputs are ungranted
+ (t2/update! :model/WorkspaceInput {:workspace_id (:id ws)} {:access_granted false})
+ (testing "returns pending (ungranted) inputs"
+ (let [resp (mt/user-http-request :crowberto :get 200
+ (ws-url (:id ws) "/input/pending"))]
+ (is (seq (:inputs resp)) "Should have at least one pending input")
+ (is (every? #(contains? % :table) (:inputs resp)))))
+ (testing "after granting, returns empty list"
+ (t2/update! :model/WorkspaceInput {:workspace_id (:id ws)} {:access_granted true})
+ (let [resp (mt/user-http-request :crowberto :get 200
+ (ws-url (:id ws) "/input/pending"))]
+ (is (empty? (:inputs resp)) "Should have no pending inputs after granting")))))))
+
+(deftest input-grant-test
+ (testing "POST /:ws-id/input/grant grants access to input tables"
+ (let [mp (mt/metadata-provider)
+ query (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ ws (ws.tu/create-empty-ws! "Grant Input Test")]
+ (mt/with-dynamic-fn-redefs [ws.isolation/grant-read-access-to-tables!
+ (fn [_database _workspace _tables] nil)]
+ ;; Add a transform so workspace has inputs
+ (ws.common/add-to-changeset! (mt/user->id :crowberto) ws
+ :transform nil
+ {:name "Transform with input"
+ :source {:type "query" :query query}
+ :target {:database (mt/id)
+ :schema "analytics"
+ :name "grant_test_table"}})
+ (ws.tu/analyze-workspace! (:id ws))
+ ;; Reset inputs to ungranted so we can test the grant endpoint
+ (t2/update! :model/WorkspaceInput {:workspace_id (:id ws)} {:access_granted false})
+ (let [input-tables (t2/select [:model/WorkspaceInput :db_id :schema :table]
+ :workspace_id (:id ws))
+ grant-calls (atom [])]
+ (mt/with-dynamic-fn-redefs [ws.isolation/grant-read-access-to-tables!
+ (fn [_database _workspace tables]
+ (swap! grant-calls conj (set (map :name tables))))]
+ (testing "granting with valid table coordinates succeeds"
+ (let [result (mt/user-http-request :crowberto :post 200
+ (ws-url (:id ws) "/input/grant")
+ {:tables input-tables})]
+ (is (seq @grant-calls) "grant-read-access-to-tables! should have been called")
+ (is (= input-tables (:newly_granted result))
+ "All inputs should be in newly_granted")
+ (is (empty? (:already_granted result))
+ "No inputs should be in already_granted yet")
+ (is (every? #(true? (t2/select-one-fn :access_granted :model/WorkspaceInput
+ :workspace_id (:id ws)
+ :db_id (:db_id %)
+ :schema (:schema %)
+ :table (:table %)))
+ input-tables)
+ "All inputs should be marked as granted"))
+ (testing "granting already-granted tables is idempotent"
+ (reset! grant-calls [])
+ (let [result (mt/user-http-request :crowberto :post 200
+ (ws-url (:id ws) "/input/grant")
+ {:tables input-tables})]
+ (is (empty? @grant-calls)
+ "grant-read-access-to-tables! should not be called for already-granted tables")
+ (is (= input-tables (:already_granted result))
+ "All inputs should be in already_granted")
+ (is (empty? (:newly_granted result))
+ "No inputs should be in newly_granted"))))))))))
+
;;; ============================================ Authorization Test Matrix ============================================
(def ^:private admin-only-routes
@@ -2295,6 +2409,7 @@
[:delete "/:ws-id"]
[:post "/:ws-id/merge"]
[:post "/:ws-id/transform/:tx-id/merge"]
+ [:post "/:ws-id/input/grant"]
[:post "/test-resources"]])
(def ^:private service-user-routes
@@ -2303,6 +2418,7 @@
[:get "/:ws-id/table"]
[:get "/:ws-id/log"]
[:get "/:ws-id/graph"]
+ [:get "/:ws-id/input/pending"]
[:get "/:ws-id/problem"]
[:get "/:ws-id/external/transform"]
[:get "/:ws-id/transform"]
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/dependencies_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/dependencies_test.clj
index 4102e1b616e..7a0d08fe19c 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/dependencies_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/dependencies_test.clj
@@ -187,8 +187,11 @@
(is (some? input))
(is (= (:db_id orders-table) (:db_id input)))
(is (= (:name orders-table) (:table input)))
- (testing "input has ref_id linking to transform"
- (is (= (:ref_id wt) (:ref_id input))))))))))
+ (testing "input is linked to transform via workspace_input_transform"
+ (is (t2/exists? :model/WorkspaceInputTransform
+ :workspace_input_id (:id input)
+ :workspace_id (:id workspace)
+ :ref_id (:ref_id wt))))))))))
(deftest write-dependencies-updates-on-change-test
(testing "write-dependencies! replaces inputs when dependencies change"
@@ -211,7 +214,8 @@
:inputs [{:db_id (:db_id orders-table)
:schema (:schema orders-table)
:table (:name orders-table)}]})
- (is (= 1 (t2/count :model/WorkspaceInput :workspace_id (:id workspace) :ref_id (:ref_id wt))))
+ (is (= 1 (t2/count :model/WorkspaceInput :workspace_id (:id workspace))))
+ (is (= 1 (t2/count :model/WorkspaceInputTransform :workspace_id (:id workspace) :ref_id (:ref_id wt))))
;; Update to depend on products instead
(write-analysis! (:id workspace) "test_isolated_schema" :transform (:ref_id wt)
@@ -225,16 +229,13 @@
;; Trigger clean-up
(#'ws.impl/cleanup-old-transform-versions! (:id workspace) (:ref_id wt))
- (testing "old input is removed, new input exists"
- (is (= 1 (t2/count :model/WorkspaceInput :workspace_id (:id workspace) :ref_id (:ref_id wt))))
- (is (t2/exists? :model/WorkspaceInput
- :workspace_id (:id workspace)
- :ref_id (:ref_id wt)
- :table (:name products-table)))
- (is (not (t2/exists? :model/WorkspaceInput
- :workspace_id (:id workspace)
- :ref_id (:ref_id wt)
- :table (:name orders-table)))))))))
+ (testing "old input link is removed, new input exists"
+ ;; After cleanup, old WorkspaceInputTransform rows are removed.
+ ;; The WorkspaceInput for orders may still exist (orphaned) but the join row is gone.
+ (is (= 1 (t2/count :model/WorkspaceInputTransform :workspace_id (:id workspace) :ref_id (:ref_id wt))))
+ (let [wit (t2/select-one :model/WorkspaceInputTransform :workspace_id (:id workspace) :ref_id (:ref_id wt))
+ input (t2/select-one :model/WorkspaceInput :id (:workspace_input_id wit))]
+ (is (= (:name products-table) (:table input)))))))))
;;; ---------------------------------------- Integration test ----------------------------------------
@@ -262,7 +263,10 @@
(testing "output record created"
(is (= 1 (t2/count :model/WorkspaceOutput :workspace_id (:id workspace)))))
- (testing "input record created for ORDERS table with ref_id"
+ (testing "input record created for ORDERS table, linked via workspace_input_transform"
(is (= 1 (t2/count :model/WorkspaceInput :workspace_id (:id workspace))))
(let [input (t2/select-one :model/WorkspaceInput :workspace_id (:id workspace))]
- (is (= (:ref_id wt) (:ref_id input))))))))))
+ (is (t2/exists? :model/WorkspaceInputTransform
+ :workspace_input_id (:id input)
+ :workspace_id (:id workspace)
+ :ref_id (:ref_id wt))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/impl_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/impl_test.clj
index c35891396b8..cfc25d8db1b 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/impl_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/impl_test.clj
@@ -5,6 +5,7 @@
[metabase-enterprise.workspaces.impl :as ws.impl]
[metabase-enterprise.workspaces.isolation :as ws.isolation]
[metabase-enterprise.workspaces.test-util :as ws.tu]
+ [metabase.api.common :as api]
[metabase.driver.sql :as driver.sql]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
@@ -92,7 +93,8 @@
(deftest build-remapping-creates-nil-schema-entries-for-default-schema-outputs-test
(testing "build-remapping creates [db_id nil table] entries for outputs in the default schema"
- (ws.tu/with-resources! [{:keys [workspace-id]} {:workspace {:definitions {:x1 [:t0]}}}]
+ (ws.tu/with-resources! [{:keys [workspace-id]} {:workspace {:definitions {:x1 [:t0]}
+ :skip-init true}}]
(let [db (t2/select-one [:model/Database :id :engine :details] (mt/id))
default-schema (or (driver.sql/default-schema (:engine db))
((some-fn :dbname :db) (:details db)))
@@ -482,6 +484,146 @@
(testing "Empty graph returns nil"
(is (nil? (ws.impl/upstream-nodes {:entities [] :dependencies nil} "t1")))))
+;;;; Grant gating tests
+
+(deftest non-superuser-does-not-auto-grant-test
+ (testing "sync-grant-accesses! is skipped when non-superuser triggers analysis"
+ (let [mp (mt/metadata-provider)
+ query (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ workspace (ws.tu/create-empty-ws! "Grant Gating Test")
+ grant-calls (atom [])]
+ (mt/with-dynamic-fn-redefs [ws.isolation/grant-read-access-to-tables!
+ (fn [_database _workspace tables]
+ (swap! grant-calls conj (set (map :name tables))))]
+ ;; Add a transform as superuser so it has source tables
+ (ws.common/add-to-changeset! (mt/user->id :crowberto) workspace
+ :transform nil
+ {:name "Transform A"
+ :source {:type "query" :query query}
+ :target {:database (mt/id)
+ :schema "analytics"
+ :name "grant_gate_table"}})
+ ;; Wait for workspace initialization to complete
+ (ws.tu/ws-done! (:id workspace))
+ ;; Reset access_granted to false and clear grant-calls to isolate the test
+ (t2/update! :model/WorkspaceInput {:workspace_id (:id workspace)} {:access_granted false})
+ (reset! grant-calls [])
+ ;; Increment analysis_version to make the transform stale so analyze-stale-transforms! has work to do
+ (let [ref-id (t2/select-one-fn :ref_id :model/WorkspaceTransform :workspace_id (:id workspace))]
+ (ws.impl/increment-analysis-version! (:id workspace) ref-id))
+ (let [workspace (t2/select-one :model/Workspace (:id workspace))]
+ (testing "as non-superuser, grant is NOT called"
+ (binding [api/*is-superuser?* false]
+ (#'ws.impl/analyze-stale-transforms! workspace))
+ (is (empty? @grant-calls) "Should not auto-grant when non-superuser"))
+ (testing "as superuser, grant IS called"
+ (binding [api/*is-superuser?* true]
+ (#'ws.impl/analyze-stale-transforms! workspace))
+ (is (seq @grant-calls) "Should auto-grant when superuser")))))))
+
+;;;; Workspace input normalization tests
+
+(deftest workspace-input-normalization-test
+ (testing "Two transforms sharing an input table produce one WorkspaceInput but two WorkspaceInputTransform rows"
+ (let [mp (mt/metadata-provider)
+ query (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ ws (ws.tu/create-empty-ws! "Normalization Test")]
+ (mt/with-dynamic-fn-redefs [ws.isolation/grant-read-access-to-tables! (constantly nil)]
+ ;; Add two transforms that both read from ORDERS
+ (ws.common/add-to-changeset! (mt/user->id :crowberto) ws
+ :transform nil
+ {:name "Transform A"
+ :source {:type "query" :query query}
+ :target {:database (mt/id)
+ :schema "analytics"
+ :name "norm_table_a"}})
+ (ws.common/add-to-changeset! (mt/user->id :crowberto) ws
+ :transform nil
+ {:name "Transform B"
+ :source {:type "query" :query query}
+ :target {:database (mt/id)
+ :schema "analytics"
+ :name "norm_table_b"}})
+ (ws.tu/analyze-workspace! (:id ws))
+ (let [orders-name (mt/format-name :orders)]
+ (testing "exactly one WorkspaceInput row for ORDERS"
+ (is (= 1 (t2/count :model/WorkspaceInput
+ :workspace_id (:id ws)
+ :table orders-name))))
+ (testing "at least two WorkspaceInputTransform rows (one per transform)"
+ (let [input-id (t2/select-one-fn :id :model/WorkspaceInput
+ :workspace_id (:id ws)
+ :table orders-name)
+ ref-ids (t2/select-fn-set :ref_id :model/WorkspaceInputTransform
+ :workspace_input_id input-id)]
+ (is (= 2 (count ref-ids))
+ "Two distinct transforms should reference this input"))))))))
+
+;;;; Execute workspace ungranted transform tests
+
+(deftest execute-workspace-fails-ungranted-test
+ (testing "execute-workspace! fails transforms with ungranted inputs"
+ ;; Use different input tables so each transform has an independent WorkspaceInput
+ (ws.tu/with-resources! [{:keys [workspace-id workspace-map]}
+ {:workspace {:definitions {:x1 [:t0] :x2 [:t1]}}}]
+ (let [t1-ref (workspace-map :x1)
+ t2-ref (workspace-map :x2)]
+ ;; Un-grant only t2's inputs
+ (let [t2-input-ids (t2/select-fn-set :workspace_input_id
+ :model/WorkspaceInputTransform
+ :workspace_id workspace-id
+ :ref_id t2-ref)]
+ (is (seq t2-input-ids) "t2 should have WorkspaceInputTransform records after analysis")
+ (t2/update! :model/WorkspaceInput
+ {:id [:in t2-input-ids]}
+ {:access_granted false}))
+ (let [workspace (t2/select-one :model/Workspace workspace-id)
+ graph (ws.impl/get-or-calculate-graph! workspace)]
+ (ws.tu/with-mocked-execution
+ (let [result (ws.impl/execute-workspace! workspace graph)]
+ (testing "granted transform succeeds"
+ (is (some #{t1-ref} (:succeeded result))))
+ (testing "ungranted transform is in :not_run"
+ (is (some #{t2-ref} (:not_run result)))))))))))
+
+(deftest execute-workspace-skips-ungranted-external-transforms-test
+ (testing "execute-workspace! skips external transforms with ungranted external inputs"
+ ;; Graph: (x1) -> x2 -> (x3) where x2 is an enclosed external transform
+ ;; x1 and x3 are workspace checkouts, x2 is external
+ (ws.tu/with-resources! [{:keys [workspace-id workspace-map global-map]}
+ {:global {:x1 [:t0] :x2 [:x1] :x3 [:x2]}
+ :workspace {:checkouts [:x1 :x3]}}]
+ (let [x1-ref (workspace-map :x1)
+ x2-id (global-map :x2)
+ x2-str (str "global-id:" x2-id)
+ x3-ref (workspace-map :x3)
+ ;; x2 reads from t0 (a table that exists in the DB); simulate this as an ungranted external input.
+ t0-id (global-map :t0)]
+ ;; Insert input dependency: x2 depends on table t0
+ (t2/insert! :model/Dependency {:from_entity_type "transform"
+ :from_entity_id x2-id
+ :to_entity_type "table"
+ :to_entity_id t0-id})
+ ;; Insert an ungranted WorkspaceInputExternal row for t0
+ (let [{:keys [db_id schema name]} (t2/select-one [:model/Table :db_id :schema :name] t0-id)]
+ (t2/insert! :model/WorkspaceInputExternal
+ {:workspace_id workspace-id
+ :graph_version 0
+ :db_id db_id
+ :schema schema
+ :table name
+ :table_id t0-id
+ :access_granted false}))
+ (let [workspace (t2/select-one :model/Workspace workspace-id)
+ graph (ws.impl/get-or-calculate-graph! workspace)]
+ (ws.tu/with-mocked-execution
+ (let [result (ws.impl/execute-workspace! workspace graph)]
+ (testing "workspace transforms with granted inputs succeed"
+ (is (some #{x1-ref} (:succeeded result)))
+ (is (some #{x3-ref} (:succeeded result))))
+ (testing "external transform with ungranted external input is in :not_run"
+ (is (some #{x2-str} (:not_run result)))))))))))
+
;;;; run-stale-ancestors! tests
(deftest run-stale-ancestors-runs-only-stale-ancestors-test
@@ -593,7 +735,6 @@
:workspace {:checkouts [:x1 :x3]
:properties {:x1 {:definition_changed true}
:x3 {:definition_changed false}}}}]
- (ws.tu/ws-done! workspace-id)
(let [x1-ref (workspace-map :x1)
x2-global (str "global-id:" (global-map :x2))
x3-ref (workspace-map :x3)]
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/test_util.clj b/enterprise/backend/test/metabase_enterprise/workspaces/test_util.clj
index 779960b8568..39a415b16f9 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/test_util.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/test_util.clj
@@ -167,6 +167,32 @@
(mt/with-current-user creator-id
(ws.common/create-workspace! creator-id props))))
+(defn ws-done!
+ "Poll until workspace status is no longer :pending.
+ Returns immediately if workspace has not started initializing, which requires a transform being added."
+ [ws-or-id]
+ (let [ws-id (cond-> ws-or-id
+ (map? ws-or-id) :id)]
+ (or (u/poll {:thunk #(t2/select-one :model/Workspace :id ws-id)
+ :done? #(not= :pending (:db_status %))
+ ;; some cloud drivers are really slow
+ :timeout-ms (if config/is-dev? 10000 60000)})
+ (throw (ex-info "Timeout waiting for workspace to finish initializing" {:workspace-id ws-id})))))
+
+(defn analyze-workspace!
+ "Trigger the reconstruction and persistence of the workspace graph."
+ [id]
+ (mt/user-http-request :crowberto :get 200 (str "ee/workspace/" id "/graph")))
+
+(defn force-grant-all-inputs!
+ "Mark all WorkspaceInput records for a workspace as granted.
+ Test tables created by [[create-tables!]] are metadata-only (no physical DB tables),
+ so the isolation layer's GRANT fails silently and `access_granted` stays false.
+ Triggers graph calculation first to ensure WorkspaceInput records exist."
+ [workspace-id]
+ (analyze-workspace! workspace-id)
+ (t2/update! :model/WorkspaceInput {:workspace_id workspace-id} {:access_granted true}))
+
(defn create-resources!
"Create test resources from shorthand notation for both global and workspace transforms.
@@ -262,7 +288,13 @@
_ (when-let [props (:properties workspace)]
(doseq [[tx-sym updates] props]
(when-let [ref-id (workspace-map tx-sym)]
- (t2/update! :model/WorkspaceTransform {:workspace_id ws-id :ref_id ref-id} updates))))]
+ (t2/update! :model/WorkspaceTransform {:workspace_id ws-id :ref_id ref-id} updates))))
+ ;; Wait for workspace DB initialization and grant all inputs by default.
+ ;; Test tables are metadata-only (no physical DB tables), so the isolation layer's GRANT
+ ;; fails silently and `access_granted` stays false — we force-grant to avoid that.
+ _ (when (and ws-id (not (:skip-init workspace)))
+ (ws-done! ws-id)
+ (force-grant-all-inputs! ws-id))]
{:workspace-id ws-id
:global-map global-map
:workspace-map workspace-map}))
@@ -336,6 +368,7 @@
:model/Workspace
:model/WorkspaceTransform
:model/WorkspaceInput
+ :model/WorkspaceInputTransform
:model/WorkspaceOutput]
(tests))))))))
@@ -353,22 +386,10 @@
(log/warn e "Failed to destroy isolation" {:workspace workspace})))
workspace)
-(defn ws-done!
- "Poll until workspace status is no longer :pending.
- Returns immediately if workspace has not started initializing, which requires a transform being added."
- [ws-or-id]
- (let [ws-id (cond-> ws-or-id
- (map? ws-or-id) :id)]
- (or (u/poll {:thunk #(t2/select-one :model/Workspace :id ws-id)
- :done? #(not= :pending (:db_status %))
- ;; some cloud drivers are really slow
- :timeout-ms (if config/is-dev? 10000 60000)})
- (throw (ex-info "Timeout waiting for workspace to finish initializing" {:workspace-id ws-id})))))
-
(defn create-empty-ws!
- "Create a simple workspace and wait for it to be ready."
+ "Create a simple workspace with no transforms. Skips auto-init since there is nothing to analyze."
[name]
- (t2/select-one :model/Workspace (:workspace-id (create-resources! {:workspace {:name name}}))))
+ (t2/select-one :model/Workspace (:workspace-id (create-resources! {:workspace {:name name :skip-init true}}))))
(defn initialize-ws!
"Create a workspace with a transform to trigger initialization, and wait for it to finish.
@@ -432,11 +453,6 @@
(fn [[~@syms]]
~@body))))
-(defn analyze-workspace!
- "Trigger the reconstruction and persistence of the workspace graph."
- [id]
- (mt/user-http-request :crowberto :get 200 (str "ee/workspace/" id "/graph")))
-
(defn- replace-entity [{:keys [input-table workspace-transform external-transform]} entity-type entity-id]
(get
(case entity-type
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/util_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/util_test.clj
index 69a2b141015..aeda5eacb3b 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/util_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/util_test.clj
@@ -7,6 +7,8 @@
(set! *warn-on-reflection* true)
+(ws.tu/ws-fixtures!)
+
(deftest ignore-constraint-violation-test
(testing "ignore-constraint-violation catches duplicate key violations"
(let [ws (ws.tu/create-empty-ws! "Test Workspace")]
diff --git a/resources/migrations/059_update_migrations.yaml b/resources/migrations/059_update_migrations.yaml
index 9e30e59a2ad..6028b702323 100644
--- a/resources/migrations/059_update_migrations.yaml
+++ b/resources/migrations/059_update_migrations.yaml
@@ -3015,6 +3015,428 @@ databaseChangeLog:
constraints:
nullable: false
+ # ---------- Group 15: Normalize workspace_input (BOT-955) ----------
+ # Drop and recreate workspace_input with new schema (without ref_id / transform_version).
+ # Create workspace_input_transform join table for the m2m relationship.
+ # Truncate analysis tables so they repopulate on next workspace load.
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:00
+ author: qnkhuat
+ comment: Drop workspace_input table to recreate with normalized schema
+ preConditions:
+ - onFail: MARK_RAN
+ - tableExists:
+ tableName: workspace_input
+ - columnExists:
+ tableName: workspace_input
+ columnName: ref_id
+ changes:
+ - dropTable:
+ tableName: workspace_input
+ rollback:
+ - createTable:
+ tableName: workspace_input
+ remarks: External tables that workspace transforms consume from source databases
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: workspace_id
+ type: int
+ constraints:
+ nullable: false
+ - column:
+ name: db_id
+ type: int
+ constraints:
+ nullable: false
+ - column:
+ name: schema
+ type: varchar(254)
+ constraints:
+ nullable: true
+ - column:
+ name: table
+ type: varchar(254)
+ constraints:
+ nullable: false
+ - column:
+ name: table_id
+ type: int
+ constraints:
+ nullable: true
+ - column:
+ name: ref_id
+ type: char(36)
+ constraints:
+ nullable: false
+ - column:
+ name: access_granted
+ type: ${boolean.type}
+ defaultValueBoolean: false
+ constraints:
+ nullable: false
+ - column:
+ name: transform_version
+ type: bigint
+ defaultValueNumeric: 0
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ constraints:
+ nullable: false
+ - column:
+ name: updated_at
+ type: ${timestamp_type}
+ constraints:
+ nullable: false
+ # Recreate FKs that Group 7 changesets added, so their auto-rollback
+ # (dropForeignKeyConstraint) succeeds when rolling back further.
+ - addForeignKeyConstraint:
+ baseTableName: workspace_input
+ baseColumnNames: workspace_id
+ constraintName: fk_workspace_input_workspace_id
+ referencedTableName: workspace
+ referencedColumnNames: id
+ onDelete: CASCADE
+ - addForeignKeyConstraint:
+ baseTableName: workspace_input
+ baseColumnNames: table_id
+ constraintName: fk_workspace_input_table_id
+ referencedTableName: metabase_table
+ referencedColumnNames: id
+ onDelete: SET NULL
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:01
+ author: qnkhuat
+ comment: Create workspace_input with normalized schema (no ref_id or transform_version)
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - tableExists:
+ tableName: workspace_input
+ changes:
+ - createTable:
+ tableName: workspace_input
+ remarks: External tables that workspace transforms consume from source databases
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: workspace_id
+ type: int
+ remarks: FK to workspace
+ constraints:
+ nullable: false
+ - column:
+ name: db_id
+ type: int
+ remarks: Database containing the source table
+ constraints:
+ nullable: false
+ - column:
+ name: schema
+ type: varchar(254)
+ remarks: Schema of the source table (nullable for DBs without schemas)
+ constraints:
+ nullable: true
+ - column:
+ name: table
+ type: varchar(254)
+ remarks: Name of the source table
+ constraints:
+ nullable: false
+ - column:
+ name: table_id
+ type: int
+ remarks: FK to metabase_table if table exists and is synced
+ constraints:
+ nullable: true
+ - column:
+ name: access_granted
+ type: ${boolean.type}
+ remarks: Whether read access has been granted to the workspace user
+ defaultValueBoolean: false
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ remarks: Timestamp when the input was created
+ constraints:
+ nullable: false
+ - column:
+ name: updated_at
+ type: ${timestamp_type}
+ remarks: Timestamp when the input was last updated
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:02
+ author: qnkhuat
+ comment: Add index on workspace_input.workspace_id
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: workspace_input
+ indexName: idx_workspace_input_workspace_id
+ changes:
+ - createIndex:
+ tableName: workspace_input
+ indexName: idx_workspace_input_workspace_id
+ columns:
+ - column:
+ name: workspace_id
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:03
+ author: qnkhuat
+ comment: Add index on workspace_input.table_id
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: workspace_input
+ indexName: idx_workspace_input_table_id
+ changes:
+ - createIndex:
+ tableName: workspace_input
+ indexName: idx_workspace_input_table_id
+ columns:
+ - column:
+ name: table_id
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:04
+ author: qnkhuat
+ comment: Add FK from workspace_input.workspace_id to workspace with CASCADE
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - foreignKeyConstraintExists:
+ foreignKeyName: fk_workspace_input_workspace_id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: workspace_input
+ baseColumnNames: workspace_id
+ constraintName: fk_workspace_input_workspace_id
+ referencedTableName: workspace
+ referencedColumnNames: id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:05
+ author: qnkhuat
+ comment: Add FK from workspace_input.table_id to metabase_table with SET NULL
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - foreignKeyConstraintExists:
+ foreignKeyName: fk_workspace_input_table_id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: workspace_input
+ baseColumnNames: table_id
+ constraintName: fk_workspace_input_table_id
+ referencedTableName: metabase_table
+ referencedColumnNames: id
+ onDelete: SET NULL
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:06
+ author: qnkhuat
+ comment: Add unique constraint on workspace_input (workspace_id, db_id, schema, table)
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: workspace_input
+ indexName: uq_workspace_input_table
+ changes:
+ - addUniqueConstraint:
+ tableName: workspace_input
+ columnNames: workspace_id, db_id, schema, table
+ constraintName: uq_workspace_input_table
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:07
+ author: qnkhuat
+ comment: Create workspace_input_transform join table for m2m between workspace_input and workspace_transform
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - tableExists:
+ tableName: workspace_input_transform
+ changes:
+ - createTable:
+ tableName: workspace_input_transform
+ remarks: Join table linking workspace inputs to the transforms that depend on them
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: workspace_input_id
+ type: int
+ remarks: FK to workspace_input
+ constraints:
+ nullable: false
+ - column:
+ name: workspace_id
+ type: int
+ remarks: FK to workspace (denormalized for query convenience)
+ constraints:
+ nullable: false
+ - column:
+ name: ref_id
+ type: char(36)
+ remarks: ref_id of the workspace_transform that depends on this input
+ constraints:
+ nullable: false
+ - column:
+ name: transform_version
+ type: bigint
+ remarks: The analysis_version of the transform when this row was created
+ defaultValueNumeric: 0
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ remarks: Timestamp when the link was created
+ defaultValueComputed: current_timestamp
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:08
+ author: qnkhuat
+ comment: Add index on workspace_input_transform.workspace_input_id
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: workspace_input_transform
+ indexName: idx_workspace_input_transform_input_id
+ changes:
+ - createIndex:
+ tableName: workspace_input_transform
+ indexName: idx_workspace_input_transform_input_id
+ columns:
+ - column:
+ name: workspace_input_id
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:09
+ author: qnkhuat
+ comment: Add composite index on workspace_input_transform (workspace_id, ref_id)
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: workspace_input_transform
+ indexName: idx_workspace_input_transform_ws_ref
+ changes:
+ - createIndex:
+ tableName: workspace_input_transform
+ indexName: idx_workspace_input_transform_ws_ref
+ columns:
+ - column:
+ name: workspace_id
+ - column:
+ name: ref_id
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:10
+ author: qnkhuat
+ comment: Add FK from workspace_input_transform.workspace_input_id to workspace_input with CASCADE
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - foreignKeyConstraintExists:
+ foreignKeyName: fk_wit_workspace_input_id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: workspace_input_transform
+ baseColumnNames: workspace_input_id
+ constraintName: fk_wit_workspace_input_id
+ referencedTableName: workspace_input
+ referencedColumnNames: id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:11
+ author: qnkhuat
+ comment: Add FK from workspace_input_transform.workspace_id to workspace with CASCADE
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - foreignKeyConstraintExists:
+ foreignKeyName: fk_wit_workspace_id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: workspace_input_transform
+ baseColumnNames: workspace_id
+ constraintName: fk_wit_workspace_id
+ referencedTableName: workspace
+ referencedColumnNames: id
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:12
+ author: qnkhuat
+ comment: Add unique constraint on workspace_input_transform (workspace_input_id, workspace_id, ref_id, transform_version)
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: workspace_input_transform
+ indexName: uq_workspace_input_transform_versioned
+ changes:
+ - addUniqueConstraint:
+ tableName: workspace_input_transform
+ columnNames: workspace_input_id, workspace_id, ref_id, transform_version
+ constraintName: uq_workspace_input_transform_versioned
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:13
+ author: qnkhuat
+ comment: Truncate workspace_graph so analysis will re-run
+ changes:
+ - delete:
+ tableName: workspace_graph
+ rollback:
+
+ - changeSet:
+ id: v59.2026-02-09T12:00:14
+ author: qnkhuat
+ comment: Truncate workspace_output so analysis will re-run
+ changes:
+ - delete:
+ tableName: workspace_output
+ rollback:
+
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
########################################################################################################################
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 6597aaa8d63..d3ffd8cda60 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -118,6 +118,7 @@
:model/Workspace metabase-enterprise.workspaces.models.workspace
:model/WorkspaceInput metabase-enterprise.workspaces.models.workspace-input
:model/WorkspaceInputExternal metabase-enterprise.workspaces.models.workspace-input-external
+ :model/WorkspaceInputTransform metabase-enterprise.workspaces.models.workspace-input-transform
:model/WorkspaceLog metabase-enterprise.workspaces.models.workspace-log
:model/WorkspaceMerge metabase-enterprise.workspaces.models.workspace-merge
:model/WorkspaceMergeTransform metabase-enterprise.workspaces.models.workspace-merge-transform
diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.clj
index 348ccb03f69..5c557f0493c 100644
--- a/test/metabase/app_db/schema_migrations_test.clj
+++ b/test/metabase/app_db/schema_migrations_test.clj
@@ -2868,3 +2868,65 @@
(is (= [{:first_name "SAML" :provider "saml"}
{:first_name "JWT" :provider "jwt"}]
results))))))
+
+(deftest workspace-input-normalization-migration-test
+ (testing "Migrations v59.2026-02-09T12:00:00 through v59.2026-02-09T12:00:14:
+ Drop/recreate workspace_input with normalized schema and create workspace_input_transform"
+ (impl/test-migrations ["v59.2026-02-09T12:00:00" "v59.2026-02-09T12:00:14"] [migrate!]
+ ;; Create workspace
+ (let [ws-id (first (t2/insert-returning-pks! :workspace
+ {:name "Test Workspace"
+ :creator_id 1
+ :api_key_id 1
+ :execution_user 1
+ :database_id 1
+ :db_status "ready"
+ :base_status "active"
+ :graph_version 1
+ :created_at :%now
+ :updated_at :%now}))]
+ ;; Insert workspace_input rows with OLD schema (includes ref_id and transform_version).
+ (t2/insert-returning-pks! :workspace_input
+ {:workspace_id ws-id
+ :db_id 1
+ :schema "public"
+ :table "orders"
+ :ref_id (str (random-uuid))
+ :access_granted true
+ :transform_version 1
+ :created_at :%now
+ :updated_at :%now})
+ (migrate!)
+ ;; 1. Old workspace_input data is dropped (table recreated with new schema)
+ (testing "workspace_input table is empty after drop/recreate"
+ (is (= 0 (count (mdb.query/query {:select [:id] :from [:workspace_input]})))))
+ ;; 2. ref_id and transform_version columns no longer exist
+ (testing "ref_id column removed"
+ (is (thrown? Exception
+ (mdb.query/query {:select [:ref_id] :from [:workspace_input] :limit 1}))))
+ (testing "transform_version column removed"
+ (is (thrown? Exception
+ (mdb.query/query {:select [:transform_version] :from [:workspace_input] :limit 1}))))
+ ;; 3. workspace_input_transform table exists
+ (testing "workspace_input_transform table created"
+ (is (= 0 (count (mdb.query/query {:select [:id] :from [:workspace_input_transform]})))))
+ ;; 4. New unique constraint on (workspace_id, db_id, schema, table)
+ (testing "can insert into new schema"
+ (t2/insert-returning-pks! :workspace_input
+ {:workspace_id ws-id
+ :db_id 1
+ :schema "public"
+ :table "orders"
+ :access_granted false
+ :created_at :%now
+ :updated_at :%now}))
+ (testing "unique constraint prevents duplicate table entries"
+ (is (thrown? Exception
+ (t2/insert-returning-pks! :workspace_input
+ {:workspace_id ws-id
+ :db_id 1
+ :schema "public"
+ :table "orders"
+ :access_granted false
+ :created_at :%now
+ :updated_at :%now}))))))))
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index ef096a1adea..30b9edc0489 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -64,6 +64,7 @@
:model/WorkspaceGraph
:model/WorkspaceInput
:model/WorkspaceInputExternal
+ :model/WorkspaceInputTransform
:model/WorkspaceLog
:model/WorkspaceMerge
:model/WorkspaceMergeTransform