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
Agent API for Workspaces (#70496)
Chris Truter2830b3c94a4b
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 435922b0f49..ccd149919d7 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1977,7 +1977,9 @@requestserverutil- enterprise/metabot-v3}}+ enterprise/api+ enterprise/metabot-v3+ enterprise/workspaces}}enterprise/ai-entity-analysis{:team "Metabot"@@ -2566,8 +2568,8 @@{:team "Metabot":api #{metabase-enterprise.workspaces.apimetabase-enterprise.workspaces.init}+ :friends #{enterprise/agent-api}:uses #{api- api-keysapp-dbconfigdatabase-routingdiff --git a/enterprise/backend/src/metabase_enterprise/agent_api/api.clj b/enterprise/backend/src/metabase_enterprise/agent_api/api.cljindex 7b464cf1c71..a6ed331fdcd 100644--- a/enterprise/backend/src/metabase_enterprise/agent_api/api.clj+++ b/enterprise/backend/src/metabase_enterprise/agent_api/api.clj@@ -4,6 +4,7 @@(:require[clojure.string :as str][malli.core :as mc]+ [metabase-enterprise.agent-api.workspace :as agent-workspace][metabase-enterprise.metabot-v3.tools.api :as tools.api][metabase-enterprise.metabot-v3.tools.deftool :as deftool][metabase-enterprise.metabot-v3.tools.entity-details :as entity-details]@@ -15,6 +16,7 @@[metabase.api.macros :as api.macros][metabase.api.macros.scope :as scope][metabase.api.routes.common :as api.routes.common]+ [metabase.api.util.handlers :as handlers][metabase.auth-identity.core :as auth-identity][metabase.query-processor :as qp][metabase.query-processor.streaming :as qp.streaming]@@ -537,4 +539,6 @@(def ^{:arglists '([request respond raise])} routes"`/api/agent/` routes."- (api.macros/ns-handler *ns* +auth))+ (handlers/routes+ (api.macros/ns-handler *ns* +auth)+ (agent-workspace/workspace-handler +auth)))diff --git a/enterprise/backend/src/metabase_enterprise/agent_api/reference.md b/enterprise/backend/src/metabase_enterprise/agent_api/reference.mdindex e8da424aab4..f8618960df9 100644--- a/enterprise/backend/src/metabase_enterprise/agent_api/reference.md+++ b/enterprise/backend/src/metabase_enterprise/agent_api/reference.md@@ -572,3 +572,493 @@ Row limits:| 401 | Authentication failure || 403 | Insufficient permissions || 404 | Entity not found |++---++# Workspace API++The Workspace API provides endpoints for managing data workspaces — isolated+environments for building and running data transforms (ETL pipelines).++Requires the `workspaces` Metabase Pro/Enterprise feature.++## Workspace status++| Status | Description |+|-----------------|----------------------------------------------|+| uninitialized | Workspace created but database not set up |+| pending | Database setup in progress |+| ready | Workspace is ready for use |+| broken | Workspace encountered an error during setup |+| archived | Workspace has been archived |++## Read endpoints++### GET /v1/workspace/{ws-id}++Get a single workspace by ID.++**Scope**: `agent:workspace:read`++Response:++```json+{+ "id": 1,+ "name": "Revenue Analysis",+ "collection_id": 42,+ "database_id": 5,+ "status": "ready",+ "created_at": "2024-06-01T10:00:00Z",+ "updated_at": "2024-06-15T14:30:00Z"+}+```++### GET /v1/workspace/{ws-id}/table++Get workspace input and output tables.++**Scope**: `agent:workspace:read`++Response:++```json+{+ "inputs": [+ {"db_id": 1, "schema": "PUBLIC", "table": "ORDERS", "table_id": 42}+ ],+ "outputs": [+ {+ "db_id": 5,+ "global": {+ "transform_id": 10,+ "schema": "PUBLIC",+ "table": "DAILY_REVENUE",+ "table_id": 100+ },+ "isolated": {+ "transform_id": "tx-abc123",+ "schema": "mb__isolation_ws_1",+ "table": "DAILY_REVENUE",+ "table_id": 101+ }+ }+ ]+}+```++### GET /v1/workspace/{ws-id}/log++Get workspace creation status and recent log entries (up to 20).++**Scope**: `agent:workspace:read`++Response:++```json+{+ "workspace_id": 1,+ "status": "ready",+ "updated_at": "2024-06-15T14:30:00Z",+ "last_completed_at": "2024-06-15T14:30:00Z",+ "logs": [+ {+ "id": 1,+ "task": "setup",+ "description": "Creating isolated database schema",+ "started_at": "2024-06-01T10:00:00Z",+ "updated_at": "2024-06-01T10:01:00Z",+ "completed_at": "2024-06-01T10:01:00Z",+ "status": "completed",+ "message": null+ }+ ]+}+```++### GET /v1/workspace/{ws-id}/graph++Get the dependency graph for a workspace.++**Scope**: `agent:workspace:read`++Response:++```json+{+ "nodes": [+ {+ "id": 42,+ "type": "input-table",+ "dependents_count": {"workspace-transform": 1},+ "data": {"table": "ORDERS", "schema": "PUBLIC"}+ },+ {+ "id": "tx-abc123",+ "type": "workspace-transform",+ "dependents_count": {},+ "data": {"name": "Daily Revenue"}+ }+ ],+ "edges": [+ {+ "from_entity_id": 42,+ "from_entity_type": "input-table",+ "to_entity_id": "tx-abc123",+ "to_entity_type": "workspace-transform"+ }+ ]+}+```++### GET /v1/workspace/{ws-id}/problem++Detect problems in the workspace (stale transforms, cycles, failures, etc.).++**Scope**: `agent:workspace:read`++Response:++```json+[+ {+ "category": "internal",+ "problem": "stale",+ "severity": "warning",+ "block_merge": false,+ "data": {"transform_ref_id": "tx-abc123"}+ }+]+```++| Field | Description |+|-------------|--------------------------------------------------------------|+| category | `unused`, `internal-downstream`, `external-downstream`, |+| | `internal`, or `external` |+| problem | Problem type (e.g., `not-run`, `stale`, `failed`) |+| severity | `error`, `warning`, or `info` |+| block_merge | Whether this problem prevents merging to production |++### GET /v1/workspace/{ws-id}/external/transform++List external (global) transforms not checked out into this workspace.++**Scope**: `agent:workspace:read`++Query parameters:++| Parameter | Type | Required | Description |+|-------------|---------|----------|--------------------------------|+| database-id | integer | No | Filter by specific database ID |++Response:++```json+{+ "transforms": [+ {+ "id": 10,+ "name": "Daily Revenue",+ "source_type": "python",+ "checkout_disabled": null+ }+ ]+}+```++`checkout_disabled` is non-null (e.g., `"mbql"`, `"card-reference"`) when the+transform cannot be added to a workspace.++### GET /v1/workspace/{ws-id}/input/pending++List input tables that haven't been granted access yet.++**Scope**: `agent:workspace:read`++Response:++```json+{+ "inputs": [+ {"db_id": 1, "schema": "PUBLIC", "table": "CUSTOMERS"}+ ]+}+```++### GET /v1/workspace/{ws-id}/transform++List all transforms in a workspace.++**Scope**: `agent:workspace:read`++Response:++```json+{+ "transforms": [+ {+ "ref_id": "tx-abc123",+ "global_id": 10,+ "name": "Daily Revenue",+ "source_type": "python",+ "creator_id": 1+ }+ ]+}+```++### GET /v1/workspace/{ws-id}/transform/{tx-id}++Get full details for a specific transform.++**Scope**: `agent:workspace:read`++Response:++```json+{+ "ref_id": "tx-abc123",+ "global_id": 10,+ "name": "Daily Revenue",+ "description": "Aggregate daily revenue from orders",+ "source": {"type": "python", "code": "..."},+ "target": {"type": "table", "schema": "PUBLIC", "name": "DAILY_REVENUE"},+ "target_stale": false,+ "workspace_id": 1,+ "creator_id": 1,+ "archived_at": null,+ "created_at": "2024-06-01T10:00:00Z",+ "updated_at": "2024-06-15T14:30:00Z",+ "last_run_at": "2024-06-15T14:30:00Z",+ "last_run_status": "succeeded",+ "last_run_message": null+}+```++## Write endpoints++### POST /v1/workspace/{ws-id}/archive++Archive a workspace.++**Scope**: `agent:workspace:write`++Request body: empty.++Response: the archived workspace object (same schema as GET /v1/workspace/{ws-id}).++### POST /v1/workspace/{ws-id}/transform++Create a new transform in the workspace.++**Scope**: `agent:workspace:write`++Request:++```json+{+ "name": "Daily Revenue",+ "description": "Aggregate daily revenue from orders",+ "source": {"type": "python", "code": "..."}+}+```++| Field | Type | Required | Description |+|-------------|--------|----------|-------------------------------|+| name | string | Yes | Transform name |+| description | string | No | Transform description |+| source | object | Yes | Transform source (see below) |++Response: the created transform (same schema as GET /v1/workspace/{ws-id}/transform/{tx-id}).++### PUT /v1/workspace/{ws-id}/transform/{tx-id}++Update an existing transform, or create one with the given ref_id if it does+not exist.++**Scope**: `agent:workspace:write`++Request (all fields optional for updates):++```json+{+ "name": "Updated Name",+ "description": "Updated description",+ "source": {"type": "python", "code": "..."},+ "target": {"type": "table", "schema": "PUBLIC", "name": "DAILY_REVENUE"}+}+```++Response: the updated transform (same schema as GET /v1/workspace/{ws-id}/transform/{tx-id}).++### POST /v1/workspace/{ws-id}/transform/{tx-id}/archive++Mark a transform for archival.++**Scope**: `agent:workspace:write`++Request body: empty.++Response: 204 No Content.++### POST /v1/workspace/{ws-id}/transform/{tx-id}/unarchive++Restore an archived transform.++**Scope**: `agent:workspace:write`++Request body: empty.++Response: 204 No Content.++### DELETE /v1/workspace/{ws-id}/transform/{tx-id}++Permanently delete a transform from the workspace.++**Scope**: `agent:workspace:write`++Response: 204 No Content.++### POST /v1/workspace/{ws-id}/transform/validate/target++Validate a target table configuration for a transform.++**Scope**: `agent:workspace:write`++Query parameters:++| Parameter | Type | Required | Description |+|--------------|--------|----------|----------------------------------------------|+| transform-id | string | No | Transform ref_id to exclude from conflict check |++Request:++```json+{+ "target": {+ "type": "table",+ "schema": "PUBLIC",+ "name": "DAILY_REVENUE"+ }+}+```++Response (200 if valid):++```json+{"status": 200, "body": "OK"}+```++Response (403 if invalid):++```json+{"status": 403, "body": "Unsupported target type"}+```++## Execute endpoints++### POST /v1/workspace/{ws-id}/run++Execute all transforms in the workspace in dependency order.++**Scope**: `agent:workspace:execute`++Request:++```json+{"stale_only": true}+```++| Field | Type | Required | Description |+|------------|---------|----------|------------------------------------------|+| stale_only | boolean | No | Only run stale transforms (default false) |++Response:++```json+{+ "succeeded": ["tx-abc123", "tx-def456"],+ "failed": [],+ "not_run": []+}+```++### POST /v1/workspace/{ws-id}/transform/{tx-id}/run++Run a single transform.++**Scope**: `agent:workspace:execute`++Request:++```json+{"run_stale_ancestors": true}+```++| Field | Type | Required | Description |+|---------------------|---------|----------|-----------------------------------------------|+| run_stale_ancestors | boolean | No | Run stale ancestor transforms first |++Response:++```json+{+ "status": "succeeded",+ "start_time": "2024-06-15T14:30:00Z",+ "end_time": "2024-06-15T14:30:05Z",+ "message": null,+ "table": {"name": "DAILY_REVENUE", "schema": "PUBLIC"},+ "ancestors": {"succeeded": [], "failed": [], "not_run": []}+}+```++### POST /v1/workspace/{ws-id}/transform/{tx-id}/dry-run++Dry-run a transform — execute the query without persisting to the target table.++**Scope**: `agent:workspace:execute`++Request:++```json+{"run_stale_ancestors": true}+```++Response:++```json+{+ "status": "succeeded",+ "message": null,+ "running_time": 142,+ "started_at": "2024-06-15T14:30:00Z",+ "data": {+ "cols": [+ {"name": "DATE", "base_type": "type/Date"},+ {"name": "REVENUE", "base_type": "type/Float"}+ ],+ "rows": [+ ["2024-06-01", 15234.50],+ ["2024-06-02", 18102.75]+ ]+ }+}+```++### POST /v1/workspace/{ws-id}/query++Execute an ad-hoc SQL query in the workspace's isolated database context.++**Scope**: `agent:workspace:execute`++Request:++```json+{"sql": "SELECT * FROM daily_revenue LIMIT 10"}+```++| Field | Type | Required | Description |+|-------|--------|----------|----------------------|+| sql | string | Yes | SQL query to execute |++Response: same format as dry-run (query result with status, data, cols, rows).diff --git a/enterprise/backend/src/metabase_enterprise/agent_api/workspace.clj b/enterprise/backend/src/metabase_enterprise/agent_api/workspace.cljnew file mode 100644index 00000000000..d049c8f286b--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/agent_api/workspace.clj@@ -0,0 +1,341 @@+(ns metabase-enterprise.agent-api.workspace+ "Workspace endpoints for the Agent API, mounted at `/api/agent/v1/workspace/...`.+ Provides workspace access with JWT-based agent authentication."+ (:require+ [metabase-enterprise.api.core :as ee.api]+ [metabase-enterprise.workspaces.api.common :as ws.api.common]+ [metabase-enterprise.workspaces.types :as ws.t]+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.api.routes.common :as api.routes.common]+ [metabase.api.util.handlers :as handlers]+ [metabase.util.i18n :as i18n :refer [deferred-tru]]+ [metabase.util.malli.schema :as ms]))++(set! *warn-on-reflection* true)++;;; ------------------------------------------------ Agent API Schemas -----------------------------------------------+;;+;; These schemas define the agent API contract independently of the EE workspace API.+;; In practice we will often sync with ws.api.common, but we must be conscious and explicit about breaking changes+;; so that we can keep our skills and integrations (e.g. CLI, MCP) updated.++(def ^:private WorkspaceStatus+ "Computed workspace status enum."+ (into [:enum] ws.api.common/computed-statuses))++(def ^:private Workspace+ "Schema for a workspace API response."+ [:map+ [:id ::ws.t/appdb-id]+ [:name :string]+ [:collection_id ::ws.t/appdb-id]+ [:database_id ::ws.t/appdb-id]+ [:status WorkspaceStatus]+ [:created_at ms/TemporalInstant]+ [:updated_at ms/TemporalInstant]])++(def ^:private TransformSource ws.api.common/TransformSource)++(def ^:private TransformTarget+ [:map {:closed true}+ [:database {:optional true} ::ws.t/appdb-id]+ [:type [:enum "table"]]+ [:schema {:optional true} [:maybe [:string {:min 1}]]]+ [:name [:string {:min 1}]]])++(def ^:private InputTable+ [:map+ [:db_id ::ws.t/appdb-id]+ [:schema [:maybe :string]]+ [:table :string]+ [:table_id [:maybe ::ws.t/appdb-id]]])++(def ^:private OutputTable+ [:map+ [:db_id ::ws.t/appdb-id]+ [:global [:map+ [:transform_id [:maybe ::ws.t/appdb-id]]+ [:schema [:maybe :string]]+ [:table :string]+ [:table_id [:maybe ::ws.t/appdb-id]]]]+ [:isolated [:map+ [:transform_id [:or ::ws.t/ref-id ::ws.t/appdb-id]]+ [:schema :string]+ [:table :string]+ [:table_id [:maybe ::ws.t/appdb-id]]]]])++(def ^:private WorkspaceTransform+ "Schema for a full workspace transform API response."+ [:map+ [:ref_id ::ws.t/ref-id]+ [:global_id [:maybe ::ws.t/appdb-id]]+ [:name :string]+ [:description [:maybe :string]]+ [:source :map]+ [:target :map]+ [:target_stale [:maybe :boolean]]+ [:workspace_id ::ws.t/appdb-id]+ [:creator_id [:maybe ::ws.t/appdb-id]]+ [:archived_at :any]+ [:created_at :any]+ [:updated_at :any]+ [:last_run_at :any]+ [:last_run_status [:maybe :string]]+ [:last_run_message [:maybe :string]]])++(def ^:private WorkspaceTransformListing+ "Schema for a transform in a workspace listing."+ [:map {:closed true}+ [:ref_id ::ws.t/ref-id]+ [:global_id [:maybe ::ws.t/appdb-id]]+ [:name :string]+ [:source_type [:maybe :keyword]]+ [:creator_id [:maybe ::ws.t/appdb-id]]])++(def ^:private ExternalTransform+ "Schema for an external (non-workspace) transform visible to a workspace."+ [:map+ [:id ::ws.t/appdb-id]+ [:name :string]+ [:source_type :keyword]+ [:checkout_disabled [:maybe :string]]])++(def ^:private PendingInput+ "Schema for an input table that has not yet been granted access."+ [:map+ [:db_id ::ws.t/appdb-id]+ [:schema [:maybe :string]]+ [:table :string]])++(def ^:private GraphNode+ [:map+ [:id [:or ::ws.t/appdb-id ::ws.t/ref-id]]+ [:type [:enum :input-table :external-transform :workspace-transform]]+ [:dependents_count [:map-of [:enum :input-table :external-transform :workspace-transform] ms/PositiveInt]]+ [:data :map]])++(def ^:private GraphEdge+ [:map+ [:from_entity_id [:or ::ws.t/appdb-id ::ws.t/ref-id]]+ [:from_entity_type :string]+ [:to_entity_id [:or ::ws.t/appdb-id ::ws.t/ref-id]]+ [:to_entity_type :string]])++(def ^:private GraphResult+ "Schema for the workspace dependency graph response."+ [:map+ [:nodes [:sequential GraphNode]]+ [:edges [:sequential GraphEdge]]])++;;; ------------------------------------------------ Read Endpoints ---------------------------------------------------++(api.macros/defendpoint :get "/:ws-id" :- Workspace+ "Get a single workspace by ID."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]+ _query-params]+ (ws.api.common/get-workspace ws-id))++(api.macros/defendpoint :get "/:ws-id/table"+ :- [:map {:closed true}+ [:inputs [:sequential InputTable]]+ [:outputs [:sequential OutputTable]]]+ "Get workspace input and output tables."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]+ _query-params]+ (ws.api.common/get-workspace-tables ws-id))++(api.macros/defendpoint :get "/:ws-id/log"+ :- [:map+ [:workspace_id ms/PositiveInt]+ [:status WorkspaceStatus]+ [:updated_at :any]+ [:last_completed_at [:maybe :any]]+ [:logs [:sequential [:map+ [:id ms/PositiveInt]+ [:task :keyword]+ [:description ms/LocalizedString]+ [:started_at :any]+ [:updated_at :any]+ [:completed_at [:maybe :any]]+ [:status [:maybe :keyword]]+ [:message [:maybe :string]]]]]]+ "Get workspace creation status and recent log entries."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]+ _query-params]+ (ws.api.common/get-workspace-log ws-id))++(api.macros/defendpoint :get "/:ws-id/graph" :- GraphResult+ "Get the dependency graph for a workspace."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]+ _query-params]+ (ws.api.common/get-workspace-graph ws-id))++(api.macros/defendpoint :get "/:ws-id/problem" :- [:sequential ::ws.t/problem]+ "Detect problems in the workspace."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]+ _query-params]+ (ws.api.common/get-workspace-problems ws-id))++(api.macros/defendpoint :get "/:ws-id/external/transform" :- [:map [:transforms [:sequential ExternalTransform]]]+ "List external transforms not checked out into this workspace."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]+ {:keys [database-id]} :- [:map [:database-id {:optional true} ::ws.t/appdb-id]]]+ (ws.api.common/get-external-transforms ws-id database-id))++(api.macros/defendpoint :get "/:ws-id/input/pending"+ :- [:map [:inputs [:sequential PendingInput]]]+ "List pending input grants."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]]+ (ws.api.common/get-pending-inputs ws-id))++;;; ------------------------------------------ Transform CRUD ---------------------------------------------------------++(api.macros/defendpoint :get "/:ws-id/transform" :- [:map [:transforms [:sequential WorkspaceTransformListing]]]+ "List all transforms in a workspace."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]]+ (ws.api.common/list-transforms ws-id))++(api.macros/defendpoint :get "/:ws-id/transform/:tx-id" :- WorkspaceTransform+ "Get a specific transform in a workspace."+ {:scope "agent:workspace:read"}+ [{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]+ (ws.api.common/fetch-ws-transform ws-id tx-id))++(api.macros/defendpoint :post "/:ws-id/archive" :- Workspace+ "Archive a workspace."+ {:scope "agent:workspace:write"}+ [{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]+ _query-params+ _body-params]+ (ws.api.common/archive-workspace! ws-id))++(api.macros/defendpoint :post "/:ws-id/transform"+ :- WorkspaceTransform+ "Create a new transform in the workspace."+ {:scope "agent:workspace:write"}+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]+ _query-params+ body :- [:map #_{:closed true}+ [:name :string]+ [:description {:optional true} [:maybe :string]]+ [:source TransformSource]+ #_[:target TransformTarget]]]+ (ws.api.common/create-workspace-transform! ws-id body))++(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/archive" :- :nil+ "Mark a transform for archival."+ {:scope "agent:workspace:write"}+ [{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]+ (ws.api.common/archive-transform! ws-id tx-id))++(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/unarchive" :- :nil+ "Unmark a transform for archival."+ {:scope "agent:workspace:write"}+ [{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]+ (ws.api.common/unarchive-transform! ws-id tx-id))++(api.macros/defendpoint :post "/:ws-id/transform/validate/target"+ :- [:map [:status :int] [:body [:or :string i18n/LocalizedString]]]+ "Validate the target table for a workspace transform."+ {:scope "agent:workspace:write"}+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]+ {:keys [transform-id]} :- [:map [:transform-id {:optional true} ::ws.t/ref-id]]+ {:keys [db_id target]} :- [:map+ [:db_id {:optional true} ::ws.t/appdb-id]+ [:target [:map+ [:database {:optional true} ::ws.t/appdb-id]+ [:type :string]+ [:schema [:maybe :string]]+ [:name :string]]]]]+ (ws.api.common/validate-target ws-id transform-id db_id target))++;;; ---------------------------------------- Run / Query Endpoints ----------------------------------------------------++(api.macros/defendpoint :post "/:ws-id/run"+ :- [:map+ [:succeeded [:sequential ::ws.t/ref-id]]+ [:failed [:sequential ::ws.t/ref-id]]+ [:not_run [:sequential ::ws.t/ref-id]]]+ "Execute all transforms in the workspace in dependency order."+ {:scope "agent:workspace:execute"}+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]+ _query-params+ {:keys [stale_only]} :- [:map [:stale_only {:optional true} ::ws.t/flag]]]+ (ws.api.common/run-workspace! ws-id stale_only))++(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/run"+ :- ::ws.t/execution-result+ "Run a single transform in a workspace."+ {:scope "agent:workspace:execute"}+ [{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]+ _query-params+ {:keys [run_stale_ancestors]} :- [:map [:run_stale_ancestors {:optional true} ::ws.t/flag]]]+ (ws.api.common/run-transform! ws-id tx-id run_stale_ancestors))++(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/dry-run"+ :- ::ws.t/query-result+ "Dry-run a transform without persisting to the target table."+ {:scope "agent:workspace:execute"}+ [{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]+ _query-params+ {:keys [run_stale_ancestors]} :- [:map [:run_stale_ancestors {:optional true} ::ws.t/flag]]]+ (ws.api.common/dry-run-transform! ws-id tx-id run_stale_ancestors))++(api.macros/defendpoint :post "/:ws-id/query"+ :- ::ws.t/query-result+ "Execute a SQL query in the workspace's isolated database context."+ {:scope "agent:workspace:execute"}+ [{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]+ _query-params+ {:keys [sql]} :- [:map [:sql [:string {:min 1}]]]]+ (ws.api.common/execute-query! ws-id sql))++;;; ------------------------------------------ Update / Delete --------------------------------------------------------++(api.macros/defendpoint :put "/:ws-id/transform/:tx-id" :- WorkspaceTransform+ "Update or create a transform in a workspace."+ {:scope "agent:workspace:write"}+ [{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]+ _query-params+ body :- [:map+ [:name {:optional true} :string]+ [:description {:optional true} [:maybe :string]]+ [:source {:optional true} TransformSource]+ [:target {:optional true} TransformTarget]]]+ (ws.api.common/update-transform! ws-id tx-id body))++(api.macros/defendpoint :delete "/:ws-id/transform/:tx-id" :- :nil+ "Delete a transform from the workspace."+ {:scope "agent:workspace:write"}+ [{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]+ (ws.api.common/delete-transform! ws-id tx-id))++;;; ------------------------------------------------ Handler ----------------------------------------------------------++(defn- authorize-workspace-access+ "Authorization middleware for agent workspace routes. Requires superuser."+ [handler]+ (fn [request respond raise]+ (api/check-superuser)+ (handler request respond raise)))++(def ^:private +authorize+ (api.routes.common/wrap-middleware-for-open-api-spec-generation authorize-workspace-access))++(defn workspace-handler+ "Returns the workspace routes for the agent API, keyed by version prefix.+ Currently only v1; new versions can be added here without changing api.clj."+ [+auth]+ (handlers/route-map-handler+ {"/v1" {"/workspace" (ee.api/+require-premium-feature+ :workspaces (deferred-tru "Workspaces")+ (api.macros/ns-handler 'metabase-enterprise.agent-api.workspace +authorize +auth))}}))diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/util.cljindex b0762a79072..ffa0dbbcc7a 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj@@ -56,8 +56,9 @@[:= :pgm.user_id user-id]]}):table)- impersonations-with-group-ids (t2/select :model/ConnectionImpersonation- :group_id [:in user-group-ids])+ impersonations-with-group-ids (when (seq user-group-ids)+ (t2/select :model/ConnectionImpersonation+ :group_id [:in user-group-ids]))group-id->impersonations (->> impersonations-with-group-ids(group-by :group_id))group-id->sandboxes (->> sandboxes-with-group-idsdiff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.cljindex b66688fd5ee..0178a9feedc 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj@@ -22,9 +22,10 @@"Find the GTAP for current user that apply to table `table-id`."[table-id](let [group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id api/*current-user-id*)- sandboxes (t2/select :model/Sandbox- :group_id [:in group-ids]- :table_id table-id)]+ sandboxes (when (seq group-ids)+ (t2/select :model/Sandbox+ :group_id [:in group-ids]+ :table_id table-id))](when sandboxes(sandboxing/assert-one-sandbox-per-table sandboxes);; there should be only one gtap per table and we only need one table herediff --git a/enterprise/backend/src/metabase_enterprise/workspaces/api.clj b/enterprise/backend/src/metabase_enterprise/workspaces/api.cljindex c80663c759d..706cb30fc8a 100644--- a/enterprise/backend/src/metabase_enterprise/workspaces/api.clj+++ b/enterprise/backend/src/metabase_enterprise/workspaces/api.clj@@ -2,12 +2,10 @@"`/api/ee/workspace/` routes"(:require[clojure.set :as set]- [clojure.string :as str][clojure.walk :as walk][honey.sql.helpers :as sql.helpers]- [medley.core :as m]+ [metabase-enterprise.workspaces.api.common :as ws.api.common][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]@@ -15,45 +13,24 @@[metabase-enterprise.workspaces.models.workspace-log][metabase-enterprise.workspaces.models.workspace-output-external][metabase-enterprise.workspaces.types :as ws.t]- [metabase-enterprise.workspaces.validation :as ws.validation][metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.api.routes.common :as routes.common :refer [+auth]]+ [metabase.api.routes.common :refer [+auth]][metabase.config.core :as config]- [metabase.database-routing.core :as database-routing]- ^{:clj-kondo/ignore [:metabase/modules]}- [metabase.driver.sql.normalize :as sql.normalize][metabase.driver.util :as driver.u]- [metabase.lib.core :as lib]- [metabase.queries.schema :as queries.schema][metabase.request.core :as request]- [metabase.transforms-base.util :as transforms-base.u]- [metabase.transforms.core :as transforms]- [metabase.transforms.feature-gating :as transforms.gating]- [metabase.transforms.util :as transforms.u][metabase.util :as u]- [metabase.util.i18n :as i18n :refer [deferred-tru tru]]+ [metabase.util.i18n :as i18n :refer [tru]][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]- [metabase.util.secret :as u.secret][toucan2.core :as t2]))(set! *warn-on-reflection* true)-(def ^:private log-limit "Maximum number of recent workspace log items to show" 20)+;;; --------------------------------------------------- Schemas --------------------------------------------------------(defn- flag-enabled?- "Coerce a flag parameter (true, false, or 1) to boolean."- [v]- (boolean (#{1 true} v)))--(mr/def ::appdb-or-ref-id [:or ::ws.t/appdb-id ::ws.t/ref-id])--(def ^:private computed-statuses- "All possible values returned by computed-status (computed from base_status, etc.)"- #{:uninitialized :pending :ready :broken :archived})--(mr/def ::status (into [:enum] computed-statuses))+(def ^:private WorkspaceStatus+ (into [:enum] ws.api.common/computed-statuses))(def ^:private Workspace[:map@@ -61,151 +38,106 @@[:name :string][:collection_id ::ws.t/appdb-id][:database_id ::ws.t/appdb-id]- [:status ::status]+ [:status WorkspaceStatus][:created_at ms/TemporalInstant]- [:updated_at ms/TemporalInstant]- ;; Only present in POST response - the unmasked API key for workspace service user.- ;; This is the only time the key is available; after creation it's hashed and unrecoverable.- [:api_key {:optional true} :string]])+ [:updated_at ms/TemporalInstant]])-;; Transform-related schemas (adapted from transforms/api.clj)-;; TODO (Chris 2026-02-02) -- We should reuse these schemas, by exposing common types from the transforms module. They *can* match exactly.+(def ^:private TransformSource ws.api.common/TransformSource)-(mr/def ::transform-source- [:multi {:dispatch (comp keyword :type)}- [:query- [:map- [:type [:= "query"]]- [:query ::queries.schema/query]]]- [:python- [:map {:closed true}- [:source-database {:optional true} :int]- ;; TODO (Ngoc 2026-03-04) -- remove decode/normalize when FE sends array format for source-tables- [:source-tables [:sequential {:decode/normalize (fn [st]- (if (map? st)- (transforms-base.u/source-tables-map->vec st)- st))}- [:map [:alias [:string {:min 1}]] [:table_id :int]]]]- [:type [:= "python"]]- [:body :string]]]])--(mr/def ::transform-target+(def ^:private TransformTarget[:map {:closed true}[:database {:optional true} ::ws.t/appdb-id][:type [:enum "table"]][:schema {:optional true} [:maybe [:string {:min 1}]]][:name [:string {:min 1}]]])-(mr/def ::run-trigger- [:enum "none" "global-schedule"])--(defn- check-transforms-enabled!- [db-id]- (let [database (api/check-400 (t2/select-one :model/Database db-id)- (deferred-tru "The target database cannot be found."))]- (api/check (transforms.gating/any-transforms-enabled?)- [402 (deferred-tru "Premium features required for transforms are not enabled.")])- (api/check-400 (not (:is_sample database))- (deferred-tru "Cannot run transforms on the sample database."))- (api/check-400 (not (:is_audit database))- (deferred-tru "Cannot run transforms on audit databases."))- (api/check-400 (driver.u/supports? (:engine database) :transforms/table database)- (deferred-tru "The database does not support the requested transform target type."))- (api/check-400 (not (database-routing/db-routing-enabled? database))- (deferred-tru "Transforms are not supported on databases with DB routing enabled."))))--(def ^:private ws-prefix "/api/ee/workspace/\\d+")--(defn- ws-pattern- "Compile a regex matching the workspace API prefix followed by `suffix`."- ^java.util.regex.Pattern [suffix]- (re-pattern (str ws-prefix suffix)))--;; Service users may read workspace state, manage transforms, and archive their own workspace.-;; All other routes relate to the lifecycle of the workspace itself, and require superuser — including:-;; GET/POST / (list/create workspaces)-;; GET /enabled, /database, /checkout (cross-workspace state)-;; PUT /:ws-id (reconfigure workspace)-;; POST /:ws-id/unarchive (unarchive workspace)-;; DELETE /:ws-id (delete workspace)-;; POST /:ws-id/merge (merge workspace)-;; POST /:ws-id/transform/:tx-id/merge (merge single transform)-;; POST /test-resources (create test resources - available in non-prod environments only)-(def ^:private service-user-patterns- "URI patterns that workspace service users may access.- New routes default to admin-only for safety."- (update-vals- {;; Read workspace state- :get ["$"- "/table$"- "/log$"- "/graph$"- "/problem$"- "/external/transform$"- "/input/pending$"- "/transform$"- "/transform/[^/]+$"]- ;; Manage & run transforms- :post ["/archive$"- "/transform$"- "/transform/[^/]+/archive$"- "/transform/[^/]+/unarchive$"- "/transform/validate/target$"- "/run$"- "/transform/[^/]+/run$"- "/transform/[^/]+/dry-run$"- "/query$"]- :put ["/transform/[^/]+$"]- :delete ["/transform/[^/]+$"]}- (partial mapv ws-pattern)))--(defn- service-user-allowed?- "True if this request can be made by a workspace's service user."- [{:keys [uri request-method]}]- (when-let [patterns (get service-user-patterns request-method)]- (some #(re-matches % uri) patterns)))--(defn- owns-workspace?- "True if the current user is the service user for the workspace in this request's URI."- [uri]- (when-let [[_ ws-id-str] (re-find #"/api/ee/workspace/(\d+)" uri)]- (let [ws-id (parse-long ws-id-str)- user-id api/*current-user-id*]- (and user-id (t2/exists? :model/Workspace :id ws-id :execution_user user-id)))))--(defn- authorize*- "Authorization middleware for workspace routes.-- Access rules:- - Service user routes: superuser OR the workspace's own service user- - All other routes: superuser required (default)"- [handler]- (fn [request respond raise]- (if (service-user-allowed? request)- (api/check-403 (or api/*is-superuser?* (owns-workspace? (:uri request))))- (api/check-superuser))- (handler request respond raise)))--(def ^:private +authorize- (routes.common/wrap-middleware-for-open-api-spec-generation authorize*))--(defn- ws->response- "Transform a workspace record into an API response, computing the backwards-compatible status.- If :api_key is present (only at creation time), it is preserved in the response."- [ws]- (-> ws- (select-keys [:id :name :collection_id :database_id :created_at :updated_at :api_key])- (assoc :status (ws.model/computed-status ws))- (cond-> (:api_key ws) (update :api_key u.secret/expose))))--;;; routes+(def ^:private InputTable+ [:map+ [:db_id ::ws.t/appdb-id]+ [:schema [:maybe :string]]+ [:table :string]+ [:table_id [:maybe ::ws.t/appdb-id]]])++(def ^:private OutputTable+ [:map+ [:db_id ::ws.t/appdb-id]+ [:global [:map+ [:transform_id [:maybe ::ws.t/appdb-id]]+ [:schema [:maybe :string]]+ [:table :string]+ [:table_id [:maybe ::ws.t/appdb-id]]]]+ [:isolated [:map+ [:transform_id [:or ::ws.t/ref-id ::ws.t/appdb-id]]+ [:schema :string]+ [:table :string]+ [:table_id [:maybe ::ws.t/appdb-id]]]]])++(def ^:private WorkspaceTransform+ [:map+ [:ref_id ::ws.t/ref-id]+ [:global_id [:maybe ::ws.t/appdb-id]]+ [:name :string]+ [:description [:maybe :string]]+ [:source :map]+ [:target :map]+ [:target_stale [:maybe :boolean]]+ [:workspace_id ::ws.t/appdb-id]+ [:creator_id [:maybe ::ws.t/appdb-id]]+ [:archived_at :any]+ [:created_at :any]+ [:updated_at :any]+ [:last_run_at :any]+ [:last_run_status [:maybe :string]]+ [:last_run_message [:maybe :string]]])++(def ^:private WorkspaceTransformListing+ [:map {:closed true}+ [:ref_id ::ws.t/ref-id]+ [:global_id [:maybe ::ws.t/appdb-id]]+ [:name :string]+ [:source_type [:maybe :keyword]]+ [:creator_id [:maybe ::ws.t/appdb-id]]])++(def ^:private ExternalTransform+ [:map+ [:id ::ws.t/appdb-id]+ [:name :string]+ [:source_type :keyword]+ [:checkout_disabled [:maybe :string]]])++(def ^:private PendingInput+ [:map+ [:db_id ::ws.t/appdb-id]+ [:schema [:maybe :string]]+ [:table :string]])++(def ^:private GraphNode+ [:map+ [:id [:or ::ws.t/appdb-id ::ws.t/ref-id]]+ [:type [:enum :input-table :external-transform :workspace-transform]]+ [:dependents_count [:map-of [:enum :input-table :external-transform :workspace-transform] ms/PositiveInt]]+ [:data :map]])++(def ^:private GraphEdge+ [:map+ [:from_entity_id [:or ::ws.t/appdb-id ::ws.t/ref-id]]+ [:from_entity_type :string]+ [:to_entity_id [:or ::ws.t/appdb-id ::ws.t/ref-id]]+ [:to_entity_type :string]])++(def ^:private GraphResult+ [:map+ [:nodes [:sequential GraphNode]]+ [:edges [:sequential GraphEdge]]])++;;; --------------------------------------------------- Routes -------------------------------------------------------(def ^:private WorkspaceListing[:map {:closed true}[:id ::ws.t/appdb-id][:database_id ::ws.t/appdb-id][:name :string]- [:status ::status]+ [:status WorkspaceStatus][:updated_at ms/TemporalInstant]])(api.macros/defendpoint :get "/" :- [:map {:closed true}@@ -225,106 +157,25 @@:limit (request/limit):offset (request/offset)})-(mr/def ::input-table- [:map- ;; Future-proof with cross-db Python transforms- [:db_id ::ws.t/appdb-id]- [:schema [:maybe :string]]- [:table :string]- [:table_id [:maybe ::ws.t/appdb-id]]])--(mr/def ::output-table- [:map- ;; Future-proof with multi-db Workspaces, plus necessary to resolve table references when id is null.- [:db_id ::ws.t/appdb-id]- [:global [:map- ;; transform_id is nil for workspace outputs, int for external outputs- [:transform_id [:maybe ::ws.t/appdb-id]]- [:schema [:maybe :string]]- [:table :string]- [:table_id [:maybe ::ws.t/appdb-id]]]]- [:isolated [:map- ;; transform_id is ref_id (string) for workspace outputs, int for external outputs- [:transform_id [:or ::ws.t/ref-id ::ws.t/appdb-id]]- [:schema :string]- [:table :string]- [:table_id [:maybe ::ws.t/appdb-id]]]]])-(api.macros/defendpoint :get "/:ws-id/table":- [:map {:closed true}- [:inputs [:sequential ::input-table]]- [:outputs [:sequential ::output-table]]]+ [:inputs [:sequential InputTable]]+ [:outputs [:sequential OutputTable]]]"Get workspace tables"- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]_query-params]- (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))- ;; Trigger creation of the Workspace*External entries- _ (ws.impl/get-or-calculate-graph! workspace)- order-by {:order-by [:db_id :global_schema :global_table]}- outputs (t2/select [:model/WorkspaceOutput- :db_id :global_schema :global_table :global_table_id- :isolated_schema :isolated_table :isolated_table_id :ref_id]- :workspace_id ws-id order-by)- external-outputs (t2/select [:model/WorkspaceOutputExternal- :db_id :global_schema :global_table :global_table_id- :isolated_schema :isolated_table :isolated_table_id :transform_id]- :workspace_id ws-id order-by)- all-outputs (concat outputs external-outputs)- raw-inputs (distinct- (t2/select [:model/WorkspaceInput :db_id :schema :table :table_id]- :workspace_id ws-id {:order-by [:db_id :schema :table]}))- external-inputs (distinct- (t2/select [:model/WorkspaceInputExternal :db_id :schema :table :table_id]- :workspace_id ws-id {:order-by [:db_id :schema :table]}))- all-raw-inputs (concat raw-inputs external-inputs)- ;; Some of our inputs may be shadowed by the outputs of other transforms. We only want external inputs.- shadowed? (into #{} (map (juxt :db_id :global_schema :global_table)) all-outputs)- inputs (remove (comp shadowed? (juxt :db_id :schema :table)) all-raw-inputs)- ;; Build a map of [d s t] => id for every table that has been synced since the output row was written.- fallback-map (merge- (ws.impl/table-ids-fallbacks :global_schema :global_table :global_table_id all-outputs)- (ws.impl/table-ids-fallbacks :isolated_schema :isolated_table :isolated_table_id all-outputs))]- {:inputs (sort-by (juxt :db_id :schema :table) inputs)- :outputs (sort-by- (juxt :db_id (comp (juxt :schema :table) :global))- (concat- ;; Workspace transform outputs- (for [{:keys [ref_id db_id global_schema global_table global_table_id- isolated_schema isolated_table isolated_table_id]} outputs]- {:db_id db_id- :global {:transform_id nil- :schema global_schema- :table global_table- :table_id (or global_table_id (get fallback-map [db_id global_schema global_table]))}- :isolated {:transform_id ref_id- :schema isolated_schema- :table isolated_table- :table_id (or isolated_table_id (get fallback-map [db_id isolated_schema isolated_table]))}})- ;; External transform outputs- (for [{:keys [transform_id db_id global_schema global_table global_table_id- isolated_schema isolated_table isolated_table_id]} external-outputs]- {:db_id db_id- :global {:transform_id transform_id- :schema global_schema- :table global_table- :table_id (or global_table_id (get fallback-map [db_id global_schema global_table]))}- :isolated {:transform_id transform_id- :schema isolated_schema- :table isolated_table- :table_id (or isolated_table_id (get fallback-map [db_id isolated_schema isolated_table]))}})))}))+ (ws.api.common/get-workspace-tables ws-id))(api.macros/defendpoint :get "/:ws-id" :- Workspace"Get a single workspace by ID"- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]_query-params]- (-> (t2/select-one :model/Workspace :id ws-id) api/check-404 ws->response))+ (ws.api.common/get-workspace ws-id))(api.macros/defendpoint :get "/:ws-id/log":- [:map[:workspace_id ms/PositiveInt]- [:status ::status]+ [:status WorkspaceStatus][:updated_at :any][:last_completed_at [:maybe :any]][:logs [:sequential [:map@@ -337,21 +188,9 @@[:status [:maybe :keyword]][:message [:maybe :string]]]]]]"Get workspace creation status and recent log entries for polling during async setup"- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]_query-params]- (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))- logs (t2/select [:model/WorkspaceLog- :id :task :started_at :completed_at :status :message- :updated_at]- :workspace_id ws-id- {:order-by [[:started_at :desc]]- :limit log-limit})]- {:workspace_id ws-id- :status (ws.model/computed-status workspace)- :logs logs- :updated_at (->> (map :updated_at logs) sort reverse first)- :last_completed_at (->> (seq (keep :completed_at logs)) sort reverse first)}))+ (ws.api.common/get-workspace-log ws-id))(def ^:private CreateWorkspace[:map@@ -374,17 +213,17 @@_query-params{:keys [database_id] :as body} :- CreateWorkspace](when database_id- (check-transforms-enabled! database_id))+ (ws.api.common/check-transforms-enabled! database_id));; If no database_id provided, use first supported DB as provisional default (uninitialized workspace)(let [provisional? (not database_id)database-id (or database_id(api/check-400 (first-supported-database-id)(tru "No supported databases configured. Please add a database that supports workspaces.")))]- (ws->response (ws.common/create-workspace! api/*current-user-id*- (assoc body- :database_id database-id- :provisional? provisional?)))))+ (ws.api.common/ws->response (ws.common/create-workspace! api/*current-user-id*+ (assoc body+ :database_id database-id+ :provisional? provisional?)))))(defn- db-unsupported-reason [db](when (not (driver.u/supports? (:engine db) :workspace db))@@ -439,10 +278,10 @@database_id (-> (u/prog1(api/check-400 (= :uninitialized (:db_status workspace))"Can only set database_id on uninitialized workspace")- (check-transforms-enabled! database_id))+ (ws.api.common/check-transforms-enabled! database_id))(assoc :database_id database_id))name (assoc :name name))]- (ws->response+ (ws.api.common/ws->response(if (seq data)(do(t2/update! :model/Workspace ws-id data)@@ -451,15 +290,10 @@(api.macros/defendpoint :post "/:ws-id/archive" :- Workspace"Archive a workspace. Deletes the isolated schema and tables, but preserves mirrored entities."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]_query-params_body-params]- (let [ws (api/check-404 (t2/select-one :model/Workspace :id ws-id))]- (api/check-400 (not= :archived (:base_status ws)) "You cannot archive an archived workspace")- (ws.model/archive! ws)- (-> (t2/select-one :model/Workspace :id ws-id)- ws->response)))+ (ws.api.common/archive-workspace! ws-id))(api.macros/defendpoint :post "/:ws-id/unarchive" :- Workspace"Restore an archived workspace. Recreates the isolated schema and tables."@@ -470,7 +304,7 @@(api/check-400 (= :archived (:base_status ws)) "You cannot unarchive a workspace that is not archived")(ws.model/unarchive! ws)(-> (t2/select-one :model/Workspace :id ws-id)- ws->response)))+ ws.api.common/ws->response)))(api.macros/defendpoint :delete "/:ws-id" :- [:map [:ok [:= true]]]"Delete a workspace and all its contents, including mirrored entities."@@ -481,48 +315,11 @@(ws.model/delete! ws){:ok true}))-(defn- checkout-disabled-reason- "Returns reason why a transform cannot be checked out, or nil if checkout is allowed."- [{:keys [source_type source]}]- (case source_type- :mbql "mbql"- :native (when (seq (lib/template-tags-referenced-cards (:query source)))- "card-reference")- :python nil- "unknown-type"))--(def ^:private ExternalTransform- ;; Might be interesting to show whether they're enclosed, once we have the graph.- ;; When they're enclosed, it could also be interesting to know whether they're stale.- [:map- [:id ::ws.t/appdb-id]- [:name :string]- [:source_type :keyword]- [:checkout_disabled [:maybe :string]]])-(api.macros/defendpoint :get "/:ws-id/external/transform" :- [:map [:transforms [:sequential ExternalTransform]]]"Get transforms that are external to the workspace, i.e. no matching workspace_transform row exists."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]{:keys [database-id]} :- [:map [:database-id {:optional true} ::ws.t/appdb-id]]]- (let [db-id (or database-id- (:database_id (api/check-404 (t2/select-one [:model/Workspace :database_id] ws-id))))- transforms (t2/select [:model/Transform :id :name :source_type :source]- {:left-join [[:workspace_transform :wt]- [:and- [:= :transform.id :wt.global_id]- [:= :wt.workspace_id ws-id]]]- ;; NULL workspace_id means transform is not checked out into this workspace- :where [:and- [:= nil :wt.workspace_id]- [:= :target_db_id db-id]]- :order-by [[:id :asc]]})]- {:transforms- (into []- (map #(-> %- (dissoc :source)- (assoc :checkout_disabled (checkout-disabled-reason %))))- transforms)}))+ (ws.api.common/get-external-transforms ws-id database-id))(api.macros/defendpoint :post "/:ws-id/run":- [:map@@ -531,147 +328,17 @@[:not_run [:sequential ::ws.t/ref-id]]]"Execute all transforms in the workspace in dependency order.Returns which transforms succeeded, failed, and were not run."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]_query-params;; Hmmm, I wonder why this isn't a boolean? T_T{:keys [stale_only]} :- [:map [:stale_only {:optional true} ::ws.t/flag]]]- (let [workspace (t2/select-one :model/Workspace :id ws-id)- _ (api/check-404 workspace)- _ (api/check-400 (not= :archived (:base_status workspace)) "Cannot execute archived workspace")- graph (ws.impl/get-or-calculate-graph! workspace)]- (ws.impl/execute-workspace! workspace graph {:stale-only? (flag-enabled? stale_only)})))--(mr/def ::graph-node-type [:enum :input-table :external-transform :workspace-transform])--(mr/def ::graph-node- [:map- [:id ::appdb-or-ref-id]- [:type [:enum :input-table :external-transform :workspace-transform]]- [:dependents_count [:map-of ::graph-node-type ms/PositiveInt]]- [:data :map]])--(mr/def ::graph-edge- [:map- [:from_entity_id ::appdb-or-ref-id]- [:from_entity_type :string]- [:to_entity_id ::appdb-or-ref-id]- [:to_entity_type :string]])--(def ^:private GraphResult- [:map- [:nodes [:sequential ::graph-node]]- [:edges [:sequential ::graph-edge]]])--(defn- node-type [node]- (let [nt (:node-type node)]- (case nt- :table :input-table- nt)))--(defn- node-id [{:keys [node-type id]}]- (case node-type- :workspace-transform id- :external-transform id- :table (str (:db id) "-" (:schema id) "-" (:table id))))--(defn- table-ids-by-target- "Batch lookup table IDs for transform targets.- Returns {[db_id normalized_schema normalized_name] -> table-record}.- Schema and table names are normalized per database driver to match how tables are stored in metabase_table."- [db-id driver transforms]- (when (seq transforms)- (let [table-keys (into #{}- (keep (fn [{:keys [target]}]- (when (:database target)- [db-id- (sql.normalize/normalize-name driver (:schema target))- (sql.normalize/normalize-name driver (:name target))])))- transforms)- with-schema (filter second table-keys)- without-schema (keep (fn [[db-id schema table-name]]- (when-not schema [db-id table-name]))- table-keys)]- (when (or (seq with-schema) (seq without-schema))- (let [tables (t2/select [:model/Table :id :db_id :schema :name]- {:where [:or- (when (seq with-schema)- [:in [:composite :db_id :schema :name] with-schema])- (when (seq without-schema)- [:and- [:= :schema nil]- [:in [:composite :db_id :name] without-schema]])]})]- (m/index-by (juxt :db_id :schema :name) tables))))))--(defn- target->spec [driver table-id-map {:keys [target] :as tx}]- (let [table-key [(:database target)- (sql.normalize/normalize-name driver (:schema target))- (sql.normalize/normalize-name driver (:name target))]- table-id (:id (get table-id-map table-key))]- (assoc tx :target {:db (:database target)- :schema (:schema target)- :table (:name target)- :table_id table-id})))--(defn- fetch-transforms-for-graph- "Batch fetch all transforms needed for the graph. Returns {:external {id -> tx}, :workspace {ref_id -> tx}}."- [ws-id entities]- (let [external-ids (into [] (keep #(when (= :external-transform (:node-type %)) (:id %))) entities)- ref-ids (into [] (keep #(when (= :workspace-transform (:node-type %)) (:id %))) entities)- external-txs (when (seq external-ids)- (m/index-by :id (t2/select [:model/Transform :id :name :target] :id [:in external-ids])))- workspace-txs (when (seq ref-ids)- (m/index-by :ref_id (t2/select [:model/WorkspaceTransform :ref_id :name :target]- :workspace_id ws-id :ref_id [:in ref-ids])))]- {:external external-txs- :workspace workspace-txs}))--(defn- node-data [driver transforms-map table-id-map {:keys [node-type id]}]- (case node-type- :table id- :external-transform (some->> (get-in transforms-map [:external id])- (target->spec driver table-id-map))- :workspace-transform (some->> (get-in transforms-map [:workspace id])- (target->spec driver table-id-map))))+ (ws.api.common/run-workspace! ws-id stale_only))(api.macros/defendpoint :get "/:ws-id/graph" :- GraphResult"Display the dependency graph between the Changeset and the (potentially external) entities that they depend on."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]_query-params]- (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))- db-id (:database_id workspace)- driver (t2/select-one-fn :engine [:model/Database :engine] :id db-id)- {:keys [inputs entities dependencies]} (ws.impl/get-or-calculate-graph! workspace)- ;; Batch fetch all transforms and build table-id lookup map- transforms-map (fetch-transforms-for-graph ws-id entities)- all-transforms (concat (vals (:external transforms-map))- (vals (:workspace transforms-map)))- table-id-map (table-ids-by-target db-id driver all-transforms)- ;; We may want to cache this inverted graph in the database JSON to avoid recalculating it each time.- inverted (reduce- (fn [inv [c parents]]- (reduce (fn [inv p] (update inv p (fnil conj #{}) c)) inv parents))- {}- dependencies)- dep-count #(frequencies (map node-type (get inverted %)))]-- {:nodes (concat (for [i inputs]- {:type :input-table- ;; Use an id that's independent of whether the table exists yet.- :id (node-id {:id i, :node-type :table})- :data i- :dependents_count (dep-count {:node-type :table, :id i})})- (for [e entities]- {:type (node-type e)- :id (:id e)- :data (node-data driver transforms-map table-id-map e)- :dependents_count (dep-count e)}))- :edges (for [[child parents] dependencies, parent parents]- {:to_entity_type (name (node-type parent))- :to_entity_id (node-id parent)- :from_entity_type (name (node-type child))- :from_entity_id (node-id child)})}))+ (ws.api.common/get-workspace-graph ws-id));;; ---------------------------------------- Problems/Validation ----------------------------------------@@ -686,29 +353,13 @@- data: extra information, shape depends on the problem typeSee `metabase-enterprise.workspaces.types/problem-types` for the full list."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]_query-params]- (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))- graph (ws.impl/get-or-calculate-graph! workspace)]- (ws.validation/find-downstream-problems ws-id graph)))--(def ^:private db+schema+table (juxt :database :schema :name))--(defn- internal-target-conflict?- "Check whether the given table is the target of another transform within the workspace. Ignores global transforms."- [ws-id target & [tx-id]]- (contains?- (t2/select-fn-set (comp db+schema+table :target)- [:model/WorkspaceTransform :target]- :ref_id [:not= tx-id]- :workspace_id ws-id)- (db+schema+table target)))+ (ws.api.common/get-workspace-problems ws-id))(api.macros/defendpoint :post "/:ws-id/transform/validate/target":- [:map [:status :int] [:body [:or :string i18n/LocalizedString]]]"Validate the target table for a workspace transform"- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]{:keys [transform-id]} :- [:map [:transform-id {:optional true} ::ws.t/ref-id]]{:keys [db_id target]} :- [:map@@ -718,268 +369,60 @@[:type :string][:schema [:maybe :string]][:name :string]]]]]- (let [workspace (api/check-404 (t2/select-one [:model/Workspace :database_id :db_status] ws-id))- target (update target :database #(or % db_id))- tx-id (when transform-id (parse-long transform-id))- ;; For uninitialized workspaces we skip over checks for their db id- ws-db-id (when (not= :uninitialized (:db_status workspace)) (:database_id workspace))]- (cond- (not= "table" (:type target))- {:status 403 :body (deferred-tru "Unsupported target type")}-- (and db_id ws-db-id (not= db_id ws-db-id))- {:status 403 :body (deferred-tru "Must target the workspace database")}-- (not (or db_id ws-db-id))- {:status 403 :body (deferred-tru "Must target a database")}-- (when-let [schema (:schema target)] (str/starts-with? schema "mb__isolation_"))- {:status 403 :body (deferred-tru "Must not target an isolated workspace schema")}-- ;; Within a workspace, we defer blocking on conflicts outside the workspace- #_{:status 403 :body (deferred-tru "A table with that name already exists.")}-- ;; Consider deferring this validation until merge also.- (internal-target-conflict? ws-id target tx-id)- {:status 403 :body (deferred-tru "Another transform in this workspace already targets that table")}-- :else- {:status 200 :body "OK"})))--(defn- malli-map-keys [schema]- (into [] (map first) (rest schema)))--(defn- select-malli-keys- "Like select-keys, but with the arguments reversed, and taking the malli schema for the output map.- Nothing smart - for example, it doesn't understand optional verus maybe."- ([schema m]- (select-keys m (malli-map-keys schema)))- ([schema alias-map m]- (merge (select-malli-keys schema m)- (u/for-map [[to from] alias-map] [to (from m)]))))--(defn- select-model-malli-keys- "Build the model-fields vector for a t2/select from a malli schema for the output row(s)"- ([model schema]- (into [model] (malli-map-keys schema)))- ([model schema alias-map]- (into [model]- (map (fn [to] (if-let [from (to alias-map)] [from to] to)))- (malli-map-keys schema))))--(def ^:private WorkspaceTransform- [:map- [:ref_id ::ws.t/ref-id]- [:global_id [:maybe ::ws.t/appdb-id]]- [:name :string]- [:description [:maybe :string]]- [:source :map]- [:target :map]- ;; Not yet calculated, see https://linear.app/metabase/issue/BOT-684/mark-stale-transforms-workspace-only- [:target_stale [:maybe :boolean]]- [:workspace_id ::ws.t/appdb-id]- [:creator_id [:maybe ::ws.t/appdb-id]]- [:archived_at :any]- [:created_at :any]- [:updated_at :any]- [:last_run_at :any]- [:last_run_status [:maybe :string]]- [:last_run_message [:maybe :string]]])--(def ^:private workspace-transform-alias {:target_stale :definition_changed})--(defn- attach-isolated-target [{:keys [workspace_id ref_id] :as ws-transform}]- (let [{:keys [db_id isolated_schema isolated_table]}- (t2/select-one :model/WorkspaceOutput :workspace_id workspace_id :ref_id ref_id)]- (assoc ws-transform :target_isolated {:type "table"- :database db_id- :schema isolated_schema- :name isolated_table})))--(defn- create-workspace-transform!- "Shared logic for creating a new workspace transform.- Validates the transform, checks constraints, and inserts it into the changeset.- Returns the created transform with isolated target info attached.-- Options:- - `:ref-id` - Optional custom ref_id for the transform (defaults to auto-generated)"- [ws-id body & {:keys [ref-id]}]- (doseq [field [:name :source :target]]- (api/check-400 (get body field) (str (name field) " is required when creating a new transform")))- ;; Check premium feature requirements- (api/check (transforms.u/check-feature-enabled body)- [402 (deferred-tru "Premium features required for this transform type are not enabled.")])- (t2/with-transaction [_tx]- (let [workspace (u/prog1 (api/check-404 (t2/select-one :model/Workspace :id ws-id))- (api/check-400 (not= :archived (:base_status <>))- "Cannot create transforms in an archived workspace"))- global-id (:global_id body (:id body))- ;; Verify transform source is allowed in workspaces (not MBQL, no card references, etc.)- _ (let [source-type (transforms/transform-source-type (:source body))- reason (checkout-disabled-reason {:source_type source-type :source (:source body)})]- (api/check-400 (nil? reason)- (case reason- "mbql"- (deferred-tru "MBQL transforms cannot be added to workspaces.")- "card-reference"- (deferred-tru "Transforms referencing questions cannot be added to workspaces.")- (deferred-tru "This transform cannot be added to a workspace: {0}." reason))))- ;; For uninitialized workspaces, preserve the target database from the request body- ;; For initialized workspaces, ensure the target database matches the workspace database- body (-> body (dissoc :global_id)- (cond-> (not= :uninitialized (:db_status workspace))- (update :target assoc :database (:database_id workspace))))- ;; Check for internal target conflict AFTER adding database to target- _ (api/check-400 (not (internal-target-conflict? ws-id (:target body)))- (deferred-tru "Another transform in this workspace already targets that table"))- transform (ws.common/add-to-changeset! api/*current-user-id* workspace :transform global-id body- :ref-id ref-id)]- (-> (select-malli-keys WorkspaceTransform workspace-transform-alias transform)- attach-isolated-target- ;; TODO (Ngoc 2026-03-04) -- remove when FE sends/expects array format for source-tables- transforms/source-tables-vec->map-for-fe))))+ (ws.api.common/validate-target ws-id transform-id db_id target))(api.macros/defendpoint :post "/:ws-id/transform":- WorkspaceTransform"Add another transform to the Changeset. This could be a fork of an existing global transform, or something new."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]_query-paramsbody :- [:map #_{:closed true}[:name :string][:description {:optional true} [:maybe :string]]- [:source ::transform-source]+ [:source TransformSource];; Not sure why this schema is giving trouble- #_[:target ::transform-target]]]- (create-workspace-transform! ws-id body))--;; TODO (Sanya 2025-12-12) -- Confirm precisely which fields are needed by the FE-(def ^:private WorkspaceTransformListing- "Schema for a transform in a workspace"- [:map {:closed true}- [:ref_id ::ws.t/ref-id]- [:global_id [:maybe ::ws.t/appdb-id]]- [:name :string]- [:source_type [:maybe :keyword]]- [:creator_id [:maybe ::ws.t/appdb-id]]- ;[:last_run :map]- ; See https://metaboat.slack.com/archives/C099RKNLP6U/p1765205882655869?thread_ts=1765205222.888209&cid=C099RKNLP6U- #_[:target_stale :boolean]])--;; Global transforms precalculate these in a toucan hook - maybe we should do that too? Let's review later.-(defn- map-source-type [ws-tx]- (-> ws-tx- (assoc :source_type (transforms/transform-source-type (:source ws-tx)))- (dissoc :source)))+ #_[:target TransformTarget]]]+ (ws.api.common/create-workspace-transform! ws-id body))(api.macros/defendpoint :get "/:ws-id/transform" :- [:map [:transforms [:sequential WorkspaceTransformListing]]]"Get all transforms in a workspace."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]]- (api/check-404 (t2/select-one :model/Workspace :id ws-id))- {:transforms (->> (t2/select [:model/WorkspaceTransform :ref_id :global_id :name :source :creator_id]- :workspace_id ws-id {:order-by [:created_at]})- (map map-source-type))})--(defn- fetch-ws-transform [ws-id tx-id]- (-> (select-model-malli-keys :model/WorkspaceTransform WorkspaceTransform workspace-transform-alias)- (t2/select-one :workspace_id ws-id :ref_id tx-id)- api/check-404- attach-isolated-target- ;; TODO (Ngoc 2026-03-04) -- remove when FE sends/expects array format for source-tables- transforms/source-tables-vec->map-for-fe))+ (ws.api.common/list-transforms ws-id))(api.macros/defendpoint :get "/:ws-id/transform/:tx-id" :- WorkspaceTransform"Get a specific transform in a workspace."- {:access :workspace}[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]- (fetch-ws-transform ws-id tx-id))+ (ws.api.common/fetch-ws-transform ws-id tx-id))(api.macros/defendpoint :put "/:ws-id/transform/:tx-id" :- WorkspaceTransform"Update or create a transform in a workspace.If the transform exists, updates it. If it doesn't exist, creates a new transform with the provided ref_id.For creation, name, source, and target are required."- {:access :workspace}[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]_query-paramsbody :- [:map[:name {:optional true} :string][:description {:optional true} [:maybe :string]]- [:source {:optional true} ::transform-source]- [:target {:optional true} ::transform-target]]]- ;; We use explicit check-then-branch rather than app-db/update-or-insert! because:- ;; 1. WorkspaceTransform has a compound primary key which that helper doesn't support- ;; 2. Update and insert have very different logic (update merges + increments versions,- ;; insert requires full validation, workspace initialization, status transitions)- (let [existing (t2/select-one :model/WorkspaceTransform :ref_id tx-id :workspace_id ws-id)]- (if existing- ;; UPDATE path- (t2/with-transaction [_tx]- (let [;; Merge only :database and :schema from existing target to preserve them when not explicitly provided.- ;; Other fields are NOT merged, allowing them to be removed by omitting from the request.- base (select-keys (:target existing) [:database :schema])- merged-body (cond-> body- (:target body) (update :target #(merge base %)))- source-or-target-changed? (or (:source body) (:target body))]- ;; If target is changing, check for conflicts with other transforms (excluding this one)- (when (:target body)- (api/check-400 (not (internal-target-conflict? ws-id (:target merged-body) tx-id))- (deferred-tru "Another transform in this workspace already targets that table")))- (t2/update! :model/WorkspaceTransform {:workspace_id ws-id :ref_id tx-id} merged-body)- ;; If source or target changed, increment versions for re-analysis- (when source-or-target-changed?- (ws.impl/increment-analysis-version! ws-id tx-id)- ;; It's unfortunate that we are using an extra SQL statement for this, rather than doing it in the earlier- ;; statement that set the [[body]]. Combining them would be tricky, as we still need the model transforms to- ;; serialize the fields in the body, but the increment requires using an SQL expression.- (ws.impl/increment-graph-version! ws-id)))- (fetch-ws-transform ws-id tx-id))- ;; INSERT path (upsert creates new transform)- (create-workspace-transform! ws-id body :ref-id tx-id))))+ [:source {:optional true} TransformSource]+ [:target {:optional true} TransformTarget]]]+ (ws.api.common/update-transform! ws-id tx-id body))(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/archive" :- :nil"Mark the given transform to be archived when the workspace is merged.For provisional transforms we will skip even creating it in the first place."- {:access :workspace}[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]- (api/check-404 (pos? (t2/update! :model/WorkspaceTransform- {:workspace_id ws-id, :ref_id tx-id}- {:archived_at [:now]})))- ;; Increment graph version since transform is leaving the graph- (ws.impl/increment-graph-version! ws-id)- nil)+ (ws.api.common/archive-transform! ws-id tx-id))(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/unarchive" :- :nil"Unmark the given transform for archival. This will recall the last definition it had within the workspace."- {:access :workspace}[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]- (api/check-404 (pos? (t2/update! :model/WorkspaceTransform- {:workspace_id ws-id, :ref_id tx-id}- {:archived_at nil})))- ;; Increment both versions - transform re-enters graph and needs re-analysis- (ws.impl/increment-analysis-version! ws-id tx-id)- ;; We could merge this with the initial WorkspaceTransform update to save a statement, but it adds complexity.- (ws.impl/increment-graph-version! ws-id)- nil)+ (ws.api.common/unarchive-transform! ws-id tx-id))(api.macros/defendpoint :delete "/:ws-id/transform/:tx-id" :- :nil"Discard a transform from the changeset.Equivalent to resetting a checked-out transform to its global definition, or deleting a provisional transform."- {:access :workspace}[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]- (api/check-404 (pos? (t2/delete! :model/WorkspaceTransform :workspace_id ws-id :ref_id tx-id)))- ;; Increment graph version since transform is potentially leaving the graph, or reverting to the global definition.- (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}))))))+ (ws.api.common/delete-transform! ws-id tx-id))(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/run":- ::ws.t/execution-result@@ -990,28 +433,10 @@When run_stale_ancestors is true, any stale ancestor transforms will be executed firstin dependency order. If any ancestor fails, execution stops and remaining ancestorsare marked as not_run. The target transform will not run if any ancestor failed."- {:access :workspace}[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]_query-params{:keys [run_stale_ancestors]} :- [:map [:run_stale_ancestors {:optional true} ::ws.t/flag]]]- (let [workspace (api/check-404 (t2/select-one :model/Workspace ws-id))- 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?- (ws.impl/run-stale-ancestors! workspace graph tx-id))- failed-ancestors (:failed ancestors-result)- transform-result (if (seq failed-ancestors)- {:status :failed- :message (str "Ancestor transform failed: "- (str/join ", " failed-ancestors))- :table (select-keys (:target transform) [:schema :name])}- (ws.impl/run-transform! workspace graph transform))]- (cond-> transform-result- run-ancestors? (assoc :ancestors ancestors-result))))+ (ws.api.common/run-transform! ws-id tx-id run_stale_ancestors))(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/dry-run":- ::ws.t/query-result@@ -1023,104 +448,28 @@When run_stale_ancestors is true, any stale ancestor transforms will be executed firstin dependency order (these ARE persisted). If any ancestor fails, execution stops andthe dry-run will not proceed."- {:access :workspace}[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]_query-params{:keys [run_stale_ancestors]} :- [:map [:run_stale_ancestors {:optional true} ::ws.t/flag]]]- (let [workspace (api/check-404 (t2/select-one :model/Workspace ws-id))- 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?- (ws.impl/run-stale-ancestors! workspace graph tx-id))- failed-ancestors (:failed ancestors-result)- dry-run-result (if (seq failed-ancestors)- {:status :failed- :message (str "Ancestor transform failed: "- (str/join ", " failed-ancestors))}- (ws.impl/dry-run-transform workspace graph transform))]- (cond-> dry-run-result- run-ancestors? (assoc :ancestors ancestors-result))))+ (ws.api.common/dry-run-transform! ws-id tx-id run_stale_ancestors))(api.macros/defendpoint :post "/:ws-id/query":- ::ws.t/query-result"Execute an arbitrary SQL query in the workspace's isolated database context.Table references are remapped to isolated workspace tables.Returns the first 2000 rows of query results."- {:access :workspace}[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]_query-params{:keys [sql]} :- [:map [:sql [:string {:min 1}]]]]- (let [workspace (api/check-404 (t2/select-one :model/Workspace ws-id))- _ (api/check-400 (not= :archived (:base_status workspace))- "Cannot query archived workspace")- _ (api/check-400 (not= :uninitialized (:db_status workspace))- "Workspace is not initialized")- _ (api/check-400 (some? (:database_details workspace))- "Workspace is not ready for queries")- _ (check-transforms-enabled! (:database_id workspace))- graph (ws.impl/get-or-calculate-graph! workspace)]- (ws.impl/execute-adhoc-query workspace graph sql)))+ (ws.api.common/execute-query! ws-id 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)})+ (ws.api.common/get-pending-inputs ws-id))(api.macros/defendpoint :post "/:ws-id/input/grant":- [:map@@ -1164,6 +513,8 @@{:already_granted (mapv #(select-keys % [:db_id :schema :table]) already-granted):newly_granted (mapv #(select-keys % [:db_id :schema :table]) ungranted)})))+;;; ---------------------------------------- Checkout ----------------------------------------+(def ^:private CheckoutTransformLegacy"Legacy format for workspace checkout transforms (DEPRECATED)."[:map@@ -1178,7 +529,7 @@[:map[:id ::ws.t/appdb-id][:name :string]- [:status ::status]+ [:status WorkspaceStatus][:existing [:maybe [:map[:ref_id ::ws.t/ref-id][:name :string]]]]])@@ -1209,7 +560,7 @@:global_id transform-id)ws-id->checkouts (into {} (map (juxt :workspace_id identity) checkouts))id->workspace (into {} (map (juxt :id identity) workspaces))]- {:checkout_disabled (checkout-disabled-reason transform)+ {:checkout_disabled (ws.api.common/checkout-disabled-reason transform):workspaces (for [{:keys [id name] :as ws} workspaces:let [checkout (get ws-id->checkouts id)]]{:id id@@ -1225,6 +576,8 @@:name name:workspace {:id (:id ws) :name (:name ws)}})}))+;;; ---------------------------------------- Merge ----------------------------------------+(api.macros/defendpoint :post "/:ws-id/merge":- [:or[:map@@ -1366,4 +719,4 @@(def ^{:arglists '([request respond raise])} routes"`/api/ee/workspace/` routes."- (api.macros/ns-handler *ns* +authorize +auth))+ (api.macros/ns-handler *ns* api/+check-superuser +auth))diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/api/common.clj b/enterprise/backend/src/metabase_enterprise/workspaces/api/common.cljnew file mode 100644index 00000000000..17ba26b8560--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/workspaces/api/common.clj@@ -0,0 +1,700 @@+(ns metabase-enterprise.workspaces.api.common+ "Shared schemas, validations, and handler logic for workspace API routes.+ Used by both `workspaces.api` and `agent-api.workspace` (agent routes)."+ (:require+ [clojure.string :as str]+ [medley.core :as m]+ [metabase-enterprise.workspaces.common :as ws.common]+ [metabase-enterprise.workspaces.impl :as ws.impl]+ [metabase-enterprise.workspaces.models.workspace :as ws.model]+ [metabase-enterprise.workspaces.models.workspace-input-external]+ [metabase-enterprise.workspaces.models.workspace-log]+ [metabase-enterprise.workspaces.models.workspace-output-external]+ [metabase-enterprise.workspaces.types :as ws.t]+ [metabase-enterprise.workspaces.validation :as ws.validation]+ [metabase.api.common :as api]+ [metabase.database-routing.core :as database-routing]+ ^{:clj-kondo/ignore [:metabase/modules]}+ [metabase.driver.sql.normalize :as sql.normalize]+ [metabase.driver.util :as driver.u]+ [metabase.lib.core :as lib]+ [metabase.queries.schema :as queries.schema]+ [metabase.transforms-base.util :as transforms-base.u]+ [metabase.transforms.core :as transforms]+ [metabase.transforms.feature-gating :as transforms.gating]+ [metabase.transforms.util :as transforms.u]+ [metabase.util :as u]+ [metabase.util.i18n :refer [deferred-tru]]+ [metabase.util.malli.registry :as mr]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++;;; --------------------------------------------------- Schemas ------------------------------------------------------++(def computed-statuses+ "All possible values returned by computed-status (computed from base_status, etc.)"+ #{:uninitialized :pending :ready :broken :archived})++(def workspace-transform-alias+ "Alias map for workspace transform fields (e.g. :target_stale -> :definition_changed)."+ {:target_stale :definition_changed})++(mr/def ::run-trigger+ [:enum "none" "global-schedule"])++(def TransformSource+ "Schema for a transform source. Shared across APIs — this is a data model concern, not an API contract."+ [:multi {:dispatch transforms-base.u/keyword-type-dispatch}+ [:query+ [:map+ [:type [:= "query"]]+ [:query ::queries.schema/query]]]+ [:python+ [:map {:closed true}+ [:source-database {:optional true} :int]+ [:source-tables [:sequential {:decode/normalize transforms-base.u/normalize-source-tables-structure}+ [:map [:alias [:string {:min 1}]] [:table_id :int]]]]+ [:type [:= "python"]]+ [:body :string]]]])++(def ^:private WorkspaceTransform+ "Internal schema used by handler functions for column selection. Each API namespace maintains+ its own copy of this schema for response validation — keep them in sync."+ [:map+ [:ref_id ::ws.t/ref-id]+ [:global_id [:maybe ::ws.t/appdb-id]]+ [:name :string]+ [:description [:maybe :string]]+ [:source :map]+ [:target :map]+ [:target_stale [:maybe :boolean]]+ [:workspace_id ::ws.t/appdb-id]+ [:creator_id [:maybe ::ws.t/appdb-id]]+ [:archived_at :any]+ [:created_at :any]+ [:updated_at :any]+ [:last_run_at :any]+ [:last_run_status [:maybe :string]]+ [:last_run_message [:maybe :string]]])++;;; ------------------------------------------------- Utilities ------------------------------------------------------++(defn flag-enabled?+ "Coerce a flag parameter (true, false, or 1) to boolean."+ [v]+ (boolean (#{1 true} v)))++(defn ws->response+ "Transform a workspace record into an API response, computing the backwards-compatible status."+ [ws]+ (-> ws+ (select-keys [:id :name :collection_id :database_id :created_at :updated_at])+ (assoc :status (ws.model/computed-status ws))))++(defn check-transforms-enabled!+ "Validates that the database supports transforms: exists, is not sample/audit, supports :transforms/table, and no DB routing."+ [db-id]+ (let [database (api/check-400 (t2/select-one :model/Database db-id)+ (deferred-tru "The target database cannot be found."))]+ (api/check (transforms.gating/any-transforms-enabled?)+ [402 (deferred-tru "Premium features required for transforms are not enabled.")])+ (api/check-400 (not (:is_sample database))+ (deferred-tru "Cannot run transforms on the sample database."))+ (api/check-400 (not (:is_audit database))+ (deferred-tru "Cannot run transforms on audit databases."))+ (api/check-400 (driver.u/supports? (:engine database) :transforms/table database)+ (deferred-tru "The database does not support the requested transform target type."))+ (api/check-400 (not (database-routing/db-routing-enabled? database))+ (deferred-tru "Transforms are not supported on databases with DB routing enabled."))))++(defn checkout-disabled-reason+ "Returns reason why a transform cannot be checked out, or nil if checkout is allowed."+ [{:keys [source_type source]}]+ (case source_type+ :mbql "mbql"+ :native (when (seq (lib/template-tags-referenced-cards (:query source)))+ "card-reference")+ :python nil+ "unknown-type"))++(def ^:private db+schema+table (juxt :database :schema :name))++(defn internal-target-conflict?+ "Check whether the given table is the target of another transform within the workspace. Ignores global transforms.+ NOTE: This intentionally includes archived transforms in the conflict check. Excluding them would allow a new+ transform to target the same table, creating a catch-22 when unarchiving the original (it can't be edited until+ after unarchiving, but unarchiving would create a conflict). Revisit if product decides on a UX for this."+ [ws-id target & [tx-id]]+ (contains?+ (t2/select-fn-set (comp db+schema+table :target)+ [:model/WorkspaceTransform :target]+ :ref_id [:not= tx-id]+ :workspace_id ws-id)+ (db+schema+table target)))++(defn check-inputs-granted!+ "Throws 400 if any input tables required by the transform have not been granted access."+ [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}))))))++;;; ---------------------------------------- Schema-driven select-keys ----------------------------------------++(defn- malli-map-keys [schema]+ (into [] (map first) (rest schema)))++(defn select-malli-keys+ "Like select-keys, but with the arguments reversed, and taking the malli schema for the output map.+ Nothing smart - for example, it doesn't understand optional versus maybe."+ ([schema m]+ (select-keys m (malli-map-keys schema)))+ ([schema alias-map m]+ (merge (select-malli-keys schema m)+ (u/for-map [[to from] alias-map] [to (from m)]))))++(defn select-model-malli-keys+ "Build the model-fields vector for a t2/select from a malli schema for the output row(s)"+ ([model schema]+ (into [model] (malli-map-keys schema)))+ ([model schema alias-map]+ (into [model]+ (map (fn [to] (if-let [from (to alias-map)] [from to] to)))+ (malli-map-keys schema))))++;;; ---------------------------------------- Transform CRUD helpers ----------------------------------------++(defn attach-isolated-target+ "Attaches the isolated (workspace-scoped) target table info to a workspace transform."+ [{:keys [workspace_id ref_id] :as ws-transform}]+ (let [{:keys [db_id isolated_schema isolated_table]}+ (t2/select-one :model/WorkspaceOutput :workspace_id workspace_id :ref_id ref_id)]+ (assoc ws-transform :target_isolated {:type "table"+ :database db_id+ :schema isolated_schema+ :name isolated_table})))++;; Global transforms precalculate these in a toucan hook - maybe we should do that too? Let's review later.+(defn map-source-type+ "Derives :source_type from the transform's :source and removes :source from the map."+ [ws-tx]+ (-> ws-tx+ (assoc :source_type (transforms/transform-source-type (:source ws-tx)))+ (dissoc :source)))++(defn fetch-ws-transform+ "Fetches a single workspace transform by workspace-id and ref-id, with isolated target attached. 404s if not found."+ [ws-id tx-id]+ (-> (select-model-malli-keys :model/WorkspaceTransform WorkspaceTransform workspace-transform-alias)+ (t2/select-one :workspace_id ws-id :ref_id tx-id)+ api/check-404+ attach-isolated-target+ ;; TODO (Ngoc 2026-03-04) -- remove when FE sends/expects array format for source-tables+ transforms/source-tables-vec->map-for-fe))++(defn create-workspace-transform!+ "Shared logic for creating a new workspace transform.+ Validates the transform, checks constraints, and inserts it into the changeset.+ Returns the created transform with isolated target info attached.++ Options:+ - `:ref-id` - Optional custom ref_id for the transform (defaults to auto-generated)"+ [ws-id body & {:keys [ref-id]}]+ (doseq [field [:name :source :target]]+ (api/check-400 (get body field) (str (name field) " is required when creating a new transform")))+ ;; Check premium feature requirements+ (api/check (transforms.u/check-feature-enabled body)+ [402 (deferred-tru "Premium features required for this transform type are not enabled.")])+ (t2/with-transaction [_tx]+ (let [workspace (u/prog1 (api/check-404 (t2/select-one :model/Workspace :id ws-id))+ (api/check-400 (not= :archived (:base_status <>))+ "Cannot create transforms in an archived workspace"))+ global-id (:global_id body (:id body))+ ;; Verify transform source is allowed in workspaces (not MBQL, no card references, etc.)+ _ (let [source-type (transforms/transform-source-type (:source body))+ reason (checkout-disabled-reason {:source_type source-type :source (:source body)})]+ (api/check-400 (nil? reason)+ (case reason+ "mbql"+ (deferred-tru "MBQL transforms cannot be added to workspaces.")+ "card-reference"+ (deferred-tru "Transforms referencing questions cannot be added to workspaces.")+ (deferred-tru "This transform cannot be added to a workspace: {0}." reason))))+ ;; For uninitialized workspaces, preserve the target database from the request body+ ;; For initialized workspaces, ensure the target database matches the workspace database+ body (-> body (dissoc :global_id)+ (cond-> (not= :uninitialized (:db_status workspace))+ (update :target assoc :database (:database_id workspace))))+ ;; Check for internal target conflict AFTER adding database to target+ _ (api/check-400 (not (internal-target-conflict? ws-id (:target body)))+ (deferred-tru "Another transform in this workspace already targets that table"))+ transform (ws.common/add-to-changeset! api/*current-user-id* workspace :transform global-id body+ :ref-id ref-id)]+ (-> (select-malli-keys WorkspaceTransform workspace-transform-alias transform)+ attach-isolated-target+ ;; TODO (Ngoc 2026-03-04) -- remove when FE sends/expects array format for source-tables+ transforms/source-tables-vec->map-for-fe))))++;;; ---------------------------------------- Pending inputs ----------------------------------------++(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]}))++;;; ---------------------------------------- Graph helpers ----------------------------------------++(defn node-type+ "Returns the graph node type, mapping :table to :input-table."+ [node]+ (let [nt (:node-type node)]+ (case nt+ :table :input-table+ nt)))++(defn node-id+ "Returns a unique string identifier for a graph node."+ [{:keys [node-type id]}]+ (case node-type+ :workspace-transform id+ :external-transform id+ :table (str (:db id) "-" (:schema id) "-" (:table id))))++(defn table-ids-by-target+ "Batch lookup table IDs for transform targets.+ Returns {[db_id normalized_schema normalized_name] -> table-record}.+ Schema and table names are normalized per database driver to match how tables are stored in metabase_table."+ [db-id driver transforms]+ (when (seq transforms)+ (let [table-keys (into #{}+ (keep (fn [{:keys [target]}]+ (when (:database target)+ [db-id+ (sql.normalize/normalize-name driver (:schema target))+ (sql.normalize/normalize-name driver (:name target))])))+ transforms)+ with-schema (filter second table-keys)+ without-schema (keep (fn [[db-id schema table-name]]+ (when-not schema [db-id table-name]))+ table-keys)]+ (when (or (seq with-schema) (seq without-schema))+ (let [tables (t2/select [:model/Table :id :db_id :schema :name]+ {:where [:or+ (when (seq with-schema)+ [:in [:composite :db_id :schema :name] with-schema])+ (when (seq without-schema)+ [:and+ [:= :schema nil]+ [:in [:composite :db_id :name] without-schema]])]})]+ (m/index-by (juxt :db_id :schema :name) tables))))))++(defn target->spec+ "Resolves a transform's target to a spec map with :db, :schema, :table, and :table_id."+ [driver table-id-map {:keys [target] :as tx}]+ (let [table-key [(:database target)+ (sql.normalize/normalize-name driver (:schema target))+ (sql.normalize/normalize-name driver (:name target))]+ table-id (:id (get table-id-map table-key))]+ (assoc tx :target {:db (:database target)+ :schema (:schema target)+ :table (:name target)+ :table_id table-id})))++(defn fetch-transforms-for-graph+ "Batch fetch all transforms needed for the graph. Returns {:external {id -> tx}, :workspace {ref_id -> tx}}."+ [ws-id entities]+ (let [external-ids (into [] (keep #(when (= :external-transform (:node-type %)) (:id %))) entities)+ ref-ids (into [] (keep #(when (= :workspace-transform (:node-type %)) (:id %))) entities)+ external-txs (when (seq external-ids)+ (m/index-by :id (t2/select [:model/Transform :id :name :target] :id [:in external-ids])))+ workspace-txs (when (seq ref-ids)+ (m/index-by :ref_id (t2/select [:model/WorkspaceTransform :ref_id :name :target]+ :workspace_id ws-id :ref_id [:in ref-ids])))]+ {:external external-txs+ :workspace workspace-txs}))++(defn node-data+ "Returns the data payload for a graph node, resolving targets to specs."+ [driver transforms-map table-id-map {:keys [node-type id]}]+ (case node-type+ :table id+ :external-transform (some->> (get-in transforms-map [:external id])+ (target->spec driver table-id-map))+ :workspace-transform (some->> (get-in transforms-map [:workspace id])+ (target->spec driver table-id-map))))++;;; ---------------------------------------- Shared endpoint handlers ----------------------------------------+;; These functions contain the handler logic shared between the regular workspace API+;; (`workspaces/api.clj`) and the agent workspace API (`agent-api/workspace.clj`).+;; Each `defendpoint` becomes a thin wrapper that calls the corresponding function here.++(def ^:private log-limit "Maximum number of recent workspace log items to show" 20)++(defn get-pending-inputs+ "Handler body for GET /:ws-id/input/pending."+ [ws-id]+ (api/check-404 (t2/select-one :model/Workspace :id ws-id))+ {:inputs (pending-inputs ws-id)})++(defn get-workspace+ "Handler body for GET /:ws-id."+ [ws-id]+ (-> (t2/select-one :model/Workspace :id ws-id) api/check-404 ws->response))++(defn get-workspace-tables+ "Handler body for GET /:ws-id/table."+ [ws-id]+ (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))+ ;; Trigger creation of the Workspace*External entries+ _ (ws.impl/get-or-calculate-graph! workspace)+ order-by {:order-by [:db_id :global_schema :global_table]}+ outputs (t2/select [:model/WorkspaceOutput+ :db_id :global_schema :global_table :global_table_id+ :isolated_schema :isolated_table :isolated_table_id :ref_id]+ :workspace_id ws-id order-by)+ external-outputs (t2/select [:model/WorkspaceOutputExternal+ :db_id :global_schema :global_table :global_table_id+ :isolated_schema :isolated_table :isolated_table_id :transform_id]+ :workspace_id ws-id order-by)+ all-outputs (concat outputs external-outputs)+ raw-inputs (distinct+ (t2/select [:model/WorkspaceInput :db_id :schema :table :table_id]+ :workspace_id ws-id {:order-by [:db_id :schema :table]}))+ external-inputs (distinct+ (t2/select [:model/WorkspaceInputExternal :db_id :schema :table :table_id]+ :workspace_id ws-id {:order-by [:db_id :schema :table]}))+ all-raw-inputs (concat raw-inputs external-inputs)+ ;; Some of our inputs may be shadowed by the outputs of other transforms. We only want external inputs.+ shadowed? (into #{} (map (juxt :db_id :global_schema :global_table)) all-outputs)+ inputs (remove (comp shadowed? (juxt :db_id :schema :table)) all-raw-inputs)+ ;; Build a map of [d s t] => id for every table that has been synced since the output row was written.+ fallback-map (merge+ (ws.impl/table-ids-fallbacks :global_schema :global_table :global_table_id all-outputs)+ (ws.impl/table-ids-fallbacks :isolated_schema :isolated_table :isolated_table_id all-outputs))]+ {:inputs (sort-by (juxt :db_id :schema :table) inputs)+ :outputs (sort-by+ (juxt :db_id (comp (juxt :schema :table) :global))+ (concat+ ;; Workspace transform outputs+ (for [{:keys [ref_id db_id global_schema global_table global_table_id+ isolated_schema isolated_table isolated_table_id]} outputs]+ {:db_id db_id+ :global {:transform_id nil+ :schema global_schema+ :table global_table+ :table_id (or global_table_id (get fallback-map [db_id global_schema global_table]))}+ :isolated {:transform_id ref_id+ :schema isolated_schema+ :table isolated_table+ :table_id (or isolated_table_id (get fallback-map [db_id isolated_schema isolated_table]))}})+ ;; External transform outputs+ (for [{:keys [transform_id db_id global_schema global_table global_table_id+ isolated_schema isolated_table isolated_table_id]} external-outputs]+ {:db_id db_id+ :global {:transform_id transform_id+ :schema global_schema+ :table global_table+ :table_id (or global_table_id (get fallback-map [db_id global_schema global_table]))}+ :isolated {:transform_id transform_id+ :schema isolated_schema+ :table isolated_table+ :table_id (or isolated_table_id (get fallback-map [db_id isolated_schema isolated_table]))}})))}))++(defn get-workspace-log+ "Handler body for GET /:ws-id/log."+ [ws-id]+ (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))+ logs (t2/select [:model/WorkspaceLog+ :id :task :started_at :completed_at :status :message+ :updated_at]+ :workspace_id ws-id+ {:order-by [[:started_at :desc]]+ :limit log-limit})]+ {:workspace_id ws-id+ :status (ws.model/computed-status workspace)+ :logs logs+ :updated_at (->> (map :updated_at logs) sort reverse first)+ :last_completed_at (->> (seq (keep :completed_at logs)) sort reverse first)}))++(defn get-workspace-graph+ "Handler body for GET /:ws-id/graph."+ [ws-id]+ (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))+ db-id (:database_id workspace)+ driver (t2/select-one-fn :engine [:model/Database :engine] :id db-id)+ {:keys [inputs entities dependencies]} (ws.impl/get-or-calculate-graph! workspace)+ ;; Batch fetch all transforms and build table-id lookup map+ transforms-map (fetch-transforms-for-graph ws-id entities)+ all-transforms (concat (vals (:external transforms-map))+ (vals (:workspace transforms-map)))+ table-id-map (table-ids-by-target db-id driver all-transforms)+ ;; We may want to cache this inverted graph in the database JSON to avoid recalculating it each time.+ inverted (reduce+ (fn [inv [c parents]]+ (reduce (fn [inv p] (update inv p (fnil conj #{}) c)) inv parents))+ {}+ dependencies)+ dep-count #(frequencies (map node-type (get inverted %)))]++ {:nodes (concat (for [i inputs]+ {:type :input-table+ ;; Use an id that's independent of whether the table exists yet.+ :id (node-id {:id i, :node-type :table})+ :data i+ :dependents_count (dep-count {:node-type :table, :id i})})+ (for [e entities]+ {:type (node-type e)+ :id (:id e)+ :data (node-data driver transforms-map table-id-map e)+ :dependents_count (dep-count e)}))+ :edges (for [[child parents] dependencies, parent parents]+ {:to_entity_type (name (node-type parent))+ :to_entity_id (node-id parent)+ :from_entity_type (name (node-type child))+ :from_entity_id (node-id child)})}))++(defn get-workspace-problems+ "Handler body for GET /:ws-id/problem."+ [ws-id]+ (let [workspace (api/check-404 (t2/select-one :model/Workspace :id ws-id))+ graph (ws.impl/get-or-calculate-graph! workspace)]+ (ws.validation/find-downstream-problems ws-id graph)))++(defn get-external-transforms+ "Handler body for GET /:ws-id/external/transform."+ [ws-id database-id]+ (let [db-id (or database-id+ (:database_id (api/check-404 (t2/select-one [:model/Workspace :database_id] ws-id))))+ transforms (t2/select [:model/Transform :id :name :source_type :source]+ {:left-join [[:workspace_transform :wt]+ [:and+ [:= :transform.id :wt.global_id]+ [:= :wt.workspace_id ws-id]]]+ ;; NULL workspace_id means transform is not checked out into this workspace+ :where [:and+ [:= nil :wt.workspace_id]+ [:= :target_db_id db-id]]+ :order-by [[:id :asc]]})]+ {:transforms+ (into []+ (map #(-> %+ (dissoc :source)+ (assoc :checkout_disabled (checkout-disabled-reason %))))+ transforms)}))++(defn list-transforms+ "Handler body for GET /:ws-id/transform."+ [ws-id]+ (api/check-404 (t2/select-one :model/Workspace :id ws-id))+ {:transforms (->> (t2/select [:model/WorkspaceTransform :ref_id :global_id :name :source :creator_id]+ :workspace_id ws-id {:order-by [:created_at]})+ (map map-source-type))})++(defn archive-workspace!+ "Handler body for POST /:ws-id/archive."+ [ws-id]+ (let [ws (api/check-404 (t2/select-one :model/Workspace :id ws-id))]+ (api/check-400 (not= :archived (:base_status ws)) "You cannot archive an archived workspace")+ (ws.model/archive! ws)+ (-> (t2/select-one :model/Workspace :id ws-id) ws->response)))++(defn archive-transform!+ "Handler body for POST /:ws-id/transform/:tx-id/archive."+ [ws-id tx-id]+ (api/check-404 (pos? (t2/update! :model/WorkspaceTransform+ {:workspace_id ws-id, :ref_id tx-id}+ {:archived_at [:now]})))+ ;; Increment graph version since transform is leaving the graph+ (ws.impl/increment-graph-version! ws-id)+ nil)++(defn unarchive-transform!+ "Handler body for POST /:ws-id/transform/:tx-id/unarchive."+ [ws-id tx-id]+ (api/check-404 (pos? (t2/update! :model/WorkspaceTransform+ {:workspace_id ws-id, :ref_id tx-id}+ {:archived_at nil})))+ ;; Increment both versions - transform re-enters graph and needs re-analysis+ (ws.impl/increment-analysis-version! ws-id tx-id)+ ;; We could merge this with the initial WorkspaceTransform update to save a statement, but it adds complexity.+ (ws.impl/increment-graph-version! ws-id)+ nil)++(defn validate-target+ "Handler body for POST /:ws-id/transform/validate/target."+ [ws-id transform-id db_id target]+ (let [workspace (api/check-404 (t2/select-one [:model/Workspace :database_id :db_status] ws-id))+ target (update target :database #(or % db_id))+ target-db-id (:database target)+ ;; For uninitialized workspaces we skip over checks for their db id+ ws-db-id (when (not= :uninitialized (:db_status workspace)) (:database_id workspace))]+ (cond+ (not= "table" (:type target))+ {:status 403 :body (deferred-tru "Unsupported target type")}++ (and target-db-id ws-db-id (not= target-db-id ws-db-id))+ {:status 403 :body (deferred-tru "Must target the workspace database")}++ (not (or target-db-id ws-db-id))+ {:status 403 :body (deferred-tru "Must target a database")}++ (when-let [schema (:schema target)] (str/starts-with? schema "mb__isolation_"))+ {:status 403 :body (deferred-tru "Must not target an isolated workspace schema")}++ ;; Within a workspace, we defer blocking on conflicts outside the workspace+ #_{:status 403 :body (deferred-tru "A table with that name already exists.")}++ ;; Consider deferring this validation until merge also.+ (internal-target-conflict? ws-id target transform-id)+ {:status 403 :body (deferred-tru "Another transform in this workspace already targets that table")}++ :else+ {:status 200 :body "OK"})))++(defn run-workspace!+ "Handler body for POST /:ws-id/run."+ [ws-id stale_only]+ (let [workspace (t2/select-one :model/Workspace :id ws-id)+ _ (api/check-404 workspace)+ _ (api/check-400 (not= :archived (:base_status workspace)) "Cannot execute archived workspace")+ graph (ws.impl/get-or-calculate-graph! workspace)]+ (ws.impl/execute-workspace! workspace graph {:stale-only? (flag-enabled? stale_only)})))++(defn run-transform!+ "Handler body for POST /:ws-id/transform/:tx-id/run."+ [ws-id tx-id run_stale_ancestors]+ (let [workspace (api/check-404 (t2/select-one :model/Workspace ws-id))+ 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?+ (ws.impl/run-stale-ancestors! workspace graph tx-id))+ failed-ancestors (:failed ancestors-result)+ transform-result (if (seq failed-ancestors)+ {:status :failed+ :message (str "Ancestor transform failed: "+ (str/join ", " failed-ancestors))+ :table (select-keys (:target transform) [:schema :name])}+ (ws.impl/run-transform! workspace graph transform))]+ (cond-> transform-result+ run-ancestors? (assoc :ancestors ancestors-result))))++(defn dry-run-transform!+ "Handler body for POST /:ws-id/transform/:tx-id/dry-run."+ [ws-id tx-id run_stale_ancestors]+ (let [workspace (api/check-404 (t2/select-one :model/Workspace ws-id))+ 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?+ (ws.impl/run-stale-ancestors! workspace graph tx-id))+ failed-ancestors (:failed ancestors-result)+ dry-run-result (if (seq failed-ancestors)+ {:status :failed+ :message (str "Ancestor transform failed: "+ (str/join ", " failed-ancestors))}+ (ws.impl/dry-run-transform workspace graph transform))]+ (cond-> dry-run-result+ run-ancestors? (assoc :ancestors ancestors-result))))++(defn execute-query!+ "Handler body for POST /:ws-id/query."+ [ws-id sql]+ (let [workspace (api/check-404 (t2/select-one :model/Workspace ws-id))+ _ (api/check-400 (not= :archived (:base_status workspace))+ "Cannot query archived workspace")+ _ (api/check-400 (not= :uninitialized (:db_status workspace))+ "Workspace is not initialized")+ _ (api/check-400 (some? (:database_details workspace))+ "Workspace is not ready for queries")+ _ (check-transforms-enabled! (:database_id workspace))+ graph (ws.impl/get-or-calculate-graph! workspace)]+ (ws.impl/execute-adhoc-query workspace graph sql)))++(defn update-transform!+ "Handler body for PUT /:ws-id/transform/:tx-id."+ [ws-id tx-id body]+ ;; We use explicit check-then-branch rather than app-db/update-or-insert! because:+ ;; 1. WorkspaceTransform has a compound primary key which that helper doesn't support+ ;; 2. Update and insert have very different logic (update merges + increments versions,+ ;; insert requires full validation, workspace initialization, status transitions)+ (let [existing (t2/select-one :model/WorkspaceTransform :ref_id tx-id :workspace_id ws-id)]+ (if existing+ ;; UPDATE path+ (t2/with-transaction [_tx]+ (let [;; Merge only :database and :schema from existing target to preserve them when not explicitly provided.+ ;; Other fields are NOT merged, allowing them to be removed by omitting from the request.+ base (select-keys (:target existing) [:database :schema])+ merged-body (cond-> body+ (:target body) (update :target #(merge base %)))+ source-or-target-changed? (or (:source body) (:target body))]+ ;; If target is changing, check for conflicts with other transforms (excluding this one)+ (when (:target body)+ (api/check-400 (not (internal-target-conflict? ws-id (:target merged-body) tx-id))+ (deferred-tru "Another transform in this workspace already targets that table")))+ (t2/update! :model/WorkspaceTransform {:workspace_id ws-id :ref_id tx-id} merged-body)+ ;; If source or target changed, increment versions for re-analysis+ (when source-or-target-changed?+ (ws.impl/increment-analysis-version! ws-id tx-id)+ ;; It's unfortunate that we are using an extra SQL statement for this, rather than doing it in the earlier+ ;; statement that set the [[body]]. Combining them would be tricky, as we still need the model transforms to+ ;; serialize the fields in the body, but the increment requires using an SQL expression.+ (ws.impl/increment-graph-version! ws-id)))+ (fetch-ws-transform ws-id tx-id))+ ;; INSERT path (upsert creates new transform)+ (create-workspace-transform! ws-id body :ref-id tx-id))))++(defn delete-transform!+ "Handler body for DELETE /:ws-id/transform/:tx-id."+ [ws-id tx-id]+ (api/check-404 (pos? (t2/delete! :model/WorkspaceTransform :workspace_id ws-id :ref_id tx-id)))+ ;; Increment graph version since transform is potentially leaving the graph, or reverting to the global definition.+ (ws.impl/increment-graph-version! ws-id)+ nil)diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/common.clj b/enterprise/backend/src/metabase_enterprise/workspaces/common.cljindex 6df7b59b6f0..f280474d9a3 100644--- a/enterprise/backend/src/metabase_enterprise/workspaces/common.clj+++ b/enterprise/backend/src/metabase_enterprise/workspaces/common.clj@@ -4,7 +4,6 @@[metabase-enterprise.workspaces.isolation :as ws.isolation][metabase-enterprise.workspaces.models.workspace-log :as ws.log][metabase-enterprise.workspaces.util :as ws.u]- [metabase.api-keys.core :as api-key][metabase.api.common :as api][metabase.transforms-base.interface :as transforms-base.i][metabase.util.log :as log]@@ -41,37 +40,23 @@(str stripped-name " (" next-num ")"))))(defn- create-workspace-container!- "Create the workspace and its related collection, user, and api key.- Returns the workspace with :api_key attached (unmasked, only available at creation time)."+ "Create the workspace and its related collection.+ Returns the workspace."[creator-id db-id workspace-name]- (let [key-name (format "API key for Workspace: %s" workspace-name)- ;; Ensure the key-name is unique.- key-name (if-not (t2/exists? :model/ApiKey :name key-name)- key-name- ;; Rather than figuring out all the escapes we need for [[workspace-name]], just over fetch.- (let [used? (t2/select-fn-set :name [:model/ApiKey :name] :name [:like "API key for Workspace: %"])]- ;; By trying N + 1 names, we know at least 1 of them must be available.- (first (remove used? (for [i (range (inc (count used?)))]- (str key-name "(" (inc i) ")"))))))- api-key (api-key/create-api-key-with-new-user! {:key-name key-name})- ws (t2/insert-returning-instance! :model/Workspace- {:name workspace-name- :creator_id creator-id- :database_id db-id- :api_key_id (:id api-key)- :execution_user (:user_id api-key)- :base_status :empty- :db_status :uninitialized})- coll (t2/insert-returning-instance! :model/Collection- {:name (format "Collection for Workspace %s" workspace-name)- :namespace "workspace"- :workspace_id (:id ws)})- ws (assoc ws :collection_id (:id coll))]- ;; Set the backlink from the workspace to the collection inside it and set the schema.+ (let [ws (t2/insert-returning-instance! :model/Workspace+ {:name workspace-name+ :creator_id creator-id+ :database_id db-id+ :base_status :empty+ :db_status :uninitialized})+ coll (t2/insert-returning-instance! :model/Collection+ {:name (format "Collection for Workspace %s" workspace-name)+ :namespace "workspace"+ :workspace_id (:id ws)})+ ws (assoc ws :collection_id (:id coll))]+ ;; Set the backlink from the workspace to the collection inside it.(t2/update! :model/Workspace (:id ws) {:collection_id (:id coll)})- ;; Return the workspace with the unmasked API key attached.- ;; This is the only time the key is available - after this it's hashed and unrecoverable.- (assoc ws :api_key (:unmasked_key api-key))))+ ws))(defn- unique-constraint-violation?"Check if an exception is due to a unique constraint violation."diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace.clj b/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace.cljindex 9f223cd13f7..b238bcbaab7 100644--- a/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace.clj+++ b/enterprise/backend/src/metabase_enterprise/workspaces/models/workspace.clj@@ -7,6 +7,11 @@[methodical.core :as methodical][toucan2.core :as t2]))+;; NOTE: The `workspace` table still has an `execution_user` column in the DB. This was used by the service-user+;; mechanism removed in c42c2ef1f20. It is no longer read or written by any code, but remains because the associated+;; CoreUser rows may own dependent resources (e.g. transforms) that would cascade on delete.+;; The `api_key_id` column and its associated API key rows were cleaned up in migration v60.2026-03-07.+(methodical/defmethod t2/table-name :model/Workspace [_model] :workspace)(def ^:private base-statusesdiff --git a/enterprise/backend/test/metabase_enterprise/agent_api/workspace_test.clj b/enterprise/backend/test/metabase_enterprise/agent_api/workspace_test.cljnew file mode 100644index 00000000000..cdac92edb07--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/agent_api/workspace_test.clj@@ -0,0 +1,258 @@+(ns ^:mb/driver-tests metabase-enterprise.agent-api.workspace-test+ (:require+ [buddy.sign.jwt :as jwt]+ [clojure.test :refer :all]+ [metabase-enterprise.sso.test-setup :as sso.test-setup]+ [metabase-enterprise.workspaces.test-util :as ws.tu]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.test.http-client :as client]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once+ (fixtures/initialize :db :test-users)+ (fn [thunk] (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table) (thunk))))++(ws.tu/ws-fixtures!)++;;; ---------------------------------------- Auth helpers ----------------------------------------++(defn- current-epoch-seconds []+ (int (/ (System/currentTimeMillis) 1000)))++(defn- sign-jwt [claims]+ (jwt/sign (merge {:iat (current-epoch-seconds)} claims) sso.test-setup/default-jwt-secret))++(defmacro ^:private with-agent-workspace-setup!+ "Sets up JWT auth and premium features needed for agent API + workspaces."+ [& body]+ `(sso.test-setup/with-jwt-default-setup!+ (mt/with-additional-premium-features #{:agent-api :metabot-v3 :workspaces :transforms}+ ~@body)))++(defn- auth-headers+ ([] (auth-headers "[email protected]"))+ ([email]+ {"authorization" (str "Bearer " (sign-jwt {:email email}))}))++(defn- agent-ws-client+ "Make an authenticated agent API workspace request."+ ([method expected-status endpoint]+ (agent-ws-client method expected-status endpoint nil))+ ([method expected-status endpoint body]+ (apply client/client method expected-status endpoint+ {:request-options {:headers (auth-headers)}}+ (when body [body]))))++;;; ---------------------------------------- Tests ----------------------------------------++(deftest agent-workspace-auth-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:name "Auth Test"}}]+ (let [ws-id (:workspace-id res)]+ (testing "Valid JWT accesses workspace endpoint"+ (is (=? {:id ws-id}+ (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id)))))++ (testing "No JWT gets 401"+ (is (= {:error "missing_authorization"+ :message "Authentication required. Use X-Metabase-Session header or Authorization: Bearer <jwt>."}+ (client/client :get 401 (str "agent/v1/workspace/" ws-id)))))++ (testing "Non-superuser gets 403"+ (is (= "You don't have permissions to do that."+ (client/client :get 403 (str "agent/v1/workspace/" ws-id)+ {:request-options {:headers (auth-headers "[email protected]")}}))))))))++(deftest agent-workspace-get-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:name "GET Test"}}]+ (let [ws-id (:workspace-id res)]+ (testing "GET workspace returns workspace details"+ (is (=? {:id ws-id+ :name "GET Test"}+ (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id)))))++ (testing "GET non-existent workspace returns 404"+ (is (= "Not found."+ (agent-ws-client :get 404 "agent/v1/workspace/999999"))))))))++(deftest agent-workspace-table-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)]+ (testing "GET tables returns inputs and outputs"+ (let [result (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/table"))]+ (is (contains? result :inputs))+ (is (contains? result :outputs))))))))++(deftest agent-workspace-log-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:name "Log Test"}}]+ (let [ws-id (:workspace-id res)]+ (testing "GET log returns workspace status and logs"+ (let [result (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/log"))]+ (is (= ws-id (:workspace_id result)))+ (is (contains? result :status))+ (is (sequential? (:logs result)))))))))++(deftest agent-workspace-transform-crud-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)+ ref-id (get-in res [:workspace-map :x1])]+ (testing "GET transforms listing"+ (let [result (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/transform"))]+ (is (sequential? (:transforms result)))+ (is (some #(= ref-id (:ref_id %)) (:transforms result)))))++ (testing "GET specific transform"+ (let [result (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/transform/" ref-id))]+ (is (= ref-id (:ref_id result)))))++ (testing "POST archive transform"+ (is (nil? (agent-ws-client :post 204 (str "agent/v1/workspace/" ws-id "/transform/" ref-id "/archive")))))++ (testing "POST unarchive transform"+ (is (nil? (agent-ws-client :post 204 (str "agent/v1/workspace/" ws-id "/transform/" ref-id "/unarchive")))))))))++(deftest agent-workspace-graph-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)]+ (testing "GET graph returns nodes and edges"+ (let [result (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/graph"))]+ (is (contains? result :nodes))+ (is (contains? result :edges))))))))++(deftest agent-workspace-problem-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)]+ (testing "GET problems returns a sequence"+ (is (sequential? (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/problem")))))))))++(deftest agent-workspace-pending-inputs-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)]+ (testing "GET pending inputs"+ (let [result (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/input/pending"))]+ (is (contains? result :inputs))))))))++(deftest agent-workspace-archive-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:name "Archive Test"}}]+ (let [ws-id (:workspace-id res)]+ (testing "POST archive workspace"+ (let [result (agent-ws-client :post 200 (str "agent/v1/workspace/" ws-id "/archive"))]+ (is (= "archived" (:status result)))))))))++(deftest agent-workspace-run-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)]+ (testing "POST run workspace returns execution result"+ (ws.tu/with-mocked-execution+ (let [result (agent-ws-client :post 200 (str "agent/v1/workspace/" ws-id "/run"))]+ (is (contains? result :succeeded))+ (is (contains? result :failed))+ (is (contains? result :not_run)))))))))++(deftest agent-workspace-external-transforms-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:global {:x1 [:t1]}+ :workspace {:name "External Test"}}]+ (let [ws-id (:workspace-id res)]+ (testing "GET external transforms"+ (let [result (agent-ws-client :get 200 (str "agent/v1/workspace/" ws-id "/external/transform"))]+ (is (contains? result :transforms))+ (is (sequential? (:transforms result)))))))))++(deftest agent-workspace-execute-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)+ ref-id (get-in res [:workspace-map :x1])]+ (testing "POST transform run returns execution result"+ (let [result (agent-ws-client :post 200 (str "agent/v1/workspace/" ws-id "/transform/" ref-id "/run"))]+ (is (contains? result :status))))++ (testing "POST transform dry-run returns query result"+ (let [result (agent-ws-client :post 200 (str "agent/v1/workspace/" ws-id "/transform/" ref-id "/dry-run"))]+ (is (contains? result :status))))++ (testing "POST query returns query result"+ (let [result (agent-ws-client :post 200 (str "agent/v1/workspace/" ws-id "/query") {:sql "SELECT 1"})]+ (is (contains? result :status))))++ (testing "POST run on archived workspace returns 400"+ (agent-ws-client :post 200 (str "agent/v1/workspace/" ws-id "/archive"))+ (is (= "Cannot execute archived workspace"+ (agent-ws-client :post 400 (str "agent/v1/workspace/" ws-id "/run")))))))))++(deftest agent-workspace-validate-target-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:definitions {:x1 [:t1]}}}]+ (let [ws-id (:workspace-id res)+ ref-id (get-in res [:workspace-map :x1])+ target (-> (t2/select-one [:model/WorkspaceTransform :target]+ :workspace_id ws-id :ref_id ref-id)+ :target)]+ (testing "Validating a transform's own target with its ref-id returns 200 (no self-conflict)"+ (is (= "OK"+ (client/client :post 200 (str "agent/v1/workspace/" ws-id "/transform/validate/target")+ {:request-options {:headers (auth-headers)}}+ {:target target}+ :transform-id ref-id))))++ (testing "Validating a conflicting target without transform-id returns 403"+ (is (= "Another transform in this workspace already targets that table"+ (agent-ws-client :post 403 (str "agent/v1/workspace/" ws-id "/transform/validate/target")+ {:target target}))))))))++(defn- scoped-auth-headers [scope]+ {"authorization" (str "Bearer " (sign-jwt {:email "[email protected]" :scope scope}))})++(deftest agent-workspace-scope-enforcement-test+ (with-agent-workspace-setup!+ (ws.tu/with-resources! [res {:workspace {:name "Scope Test"}}]+ (let [ws-id (:workspace-id res)]+ (testing "read scope can GET but not POST"+ (let [headers (scoped-auth-headers "agent:workspace:read")]+ (is (=? {:id ws-id}+ (client/client :get 200 (str "agent/v1/workspace/" ws-id)+ {:request-options {:headers headers}})))+ (is (= {:error "unsupported_scope"+ :message "Token does not have required scope: agent:workspace:write"}+ (client/client :post 403 (str "agent/v1/workspace/" ws-id "/archive")+ {:request-options {:headers headers}})))))++ (testing "write scope can POST archive but not run"+ (let [headers (scoped-auth-headers "agent:workspace:write")]+ (is (= {:error "unsupported_scope"+ :message "Token does not have required scope: agent:workspace:execute"}+ (client/client :post 403 (str "agent/v1/workspace/" ws-id "/run")+ {:request-options {:headers headers}})))))++ (testing "execute scope can POST run but not GET workspace"+ (let [headers (scoped-auth-headers "agent:workspace:execute")]+ (is (= {:error "unsupported_scope"+ :message "Token does not have required scope: agent:workspace:read"}+ (client/client :get 403 (str "agent/v1/workspace/" ws-id)+ {:request-options {:headers headers}})))))))))++(deftest agent-workspace-feature-gating-test+ ;; Feature gates fire before routing, so we don't need a real workspace - just a valid-looking URL.+ (sso.test-setup/with-jwt-default-setup!+ (testing "Returns 402 when :agent-api feature is not enabled"+ (mt/with-additional-premium-features #{:workspaces}+ (is (= 402 (:status (client/client-full-response :get 402 "agent/v1/workspace/1"+ {:request-options {:headers (auth-headers)}}))))))++ (testing "Returns 402 when :workspaces feature is not enabled"+ (mt/with-additional-premium-features #{:agent-api}+ (is (= 402 (:status (client/client-full-response :get 402 "agent/v1/workspace/1"+ {:request-options {:headers (auth-headers)}}))))))))diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/api_parity_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/api_parity_test.cljnew file mode 100644index 00000000000..7e58c9eeb3e--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/workspaces/api_parity_test.clj@@ -0,0 +1,68 @@+(ns metabase-enterprise.workspaces.api-parity-test+ "Verifies that Agent API schemas stay in sync with their implementations.+ In general, the implementations will be shared with the regular EE APIs, so we can use their schemas as a baseline.+ For now there is no divergence, so we catch unintentional drift by comparing the response schemas of both routes."+ (:require+ [clojure.test :refer :all]+ [clojure.walk]+ [metabase-enterprise.agent-api.workspace]+ [metabase-enterprise.workspaces.api]+ [metabase.api.macros :as api.macros]))++(set! *warn-on-reflection* true)++(def ^:private agent-only-endpoints+ "Agent API endpoints that intentionally have no EE equivalent.+ Add entries here when an agent endpoint is agent-specific by design."+ #{;; example: [:post "/:ws-id/agent-specific-action"]+ })++(def ^:private route-mapping+ "Explicit mapping from agent route to EE route for endpoints with different paths.+ Keys are [method agent-route], values are [method ee-route]."+ {;; example: [:get "/:ws-id/agent-path"] [:get "/:ws-id/ee-path"]+ })++(defn- resolve-schema-form+ "Resolve symbols in a schema form to their var values within `ns-sym`, leaving+ everything else (keywords, vectors, maps) untouched. This avoids false positives+ from two namespaces defining the same symbol name with different values."+ [ns-sym form]+ (clojure.walk/prewalk+ (fn [x]+ (if (symbol? x)+ (if-let [v (ns-resolve (the-ns ns-sym) x)]+ (var-get v)+ x)+ x))+ form))++(defn- endpoint-schemas+ "Returns a map of {[method route] -> resolved-response-schema} for a namespace.+ Symbols in schema forms are resolved to their var values so that comparisons+ don't produce false positives when two namespaces define the same symbol name."+ [ns-sym]+ (into {}+ (keep (fn [[[method route _params] info]]+ (when-let [schema (get-in info [:form :response-schema])]+ [[method route] (resolve-schema-form ns-sym schema)])))+ (api.macros/ns-routes ns-sym)))++(deftest response-schemas-in-sync-test+ (let [agent-schemas (endpoint-schemas 'metabase-enterprise.agent-api.workspace)+ ee-schemas (endpoint-schemas 'metabase-enterprise.workspaces.api)]+ ;; In the future, we may want to diverge in certain ways. Let's tackle that when we get there, but it will probably+ ;; involve skipping those routes, or defining precisely how we expect them to differ (e.g. wrapping)+ (testing "Every agent API endpoint should have a matching EE endpoint with the same response schema"+ (is (seq agent-schemas) "Agent API should have endpoints")+ (doseq [[[method route :as agent-key] agent-schema] (sort-by key agent-schemas)+ :when (not (agent-only-endpoints agent-key))]+ (let [ee-key (get route-mapping agent-key agent-key)+ ee-schema (ee-schemas ee-key)]+ (testing (str (name method) " " route)+ (if ee-schema+ (is (= ee-schema agent-schema))+ (is false+ (str "No matching EE endpoint for agent route " agent-key ". "+ "Update `route-mapping` to map it to the correct EE route, "+ "or add it to `agent-only-endpoints` if there is no equivalent.")))))))))diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/api_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/api_test.cljindex 8463e7935fd..d16ff0a64e3 100644--- a/enterprise/backend/test/metabase_enterprise/workspaces/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/workspaces/api_test.clj@@ -4,14 +4,12 @@[clojure.test :refer :all][java-time.api :as t][medley.core :as m]- [metabase-enterprise.workspaces.api :as ws.api][metabase-enterprise.workspaces.common :as ws.common][metabase-enterprise.workspaces.execute :as ws.execute][metabase-enterprise.workspaces.impl :as ws.impl][metabase-enterprise.workspaces.isolation :as ws.isolation][metabase-enterprise.workspaces.test-util :as ws.tu][metabase-enterprise.workspaces.util :as ws.u]- [metabase.api.macros :as api.macros][metabase.audit-app.core :as audit][metabase.driver :as driver][metabase.driver.sql :as driver.sql]@@ -44,8 +42,6 @@"It's convenient to construct queries using MBQL helper, but only native queries can be used in workspaces."(comp mt/native-query ws.tu/mbql->native))-;;; Authorization tests for all workspace routes are in service-user-authorization-test at the bottom of this file.-(deftest workspace-crud-flow-test(let [workspace-name (str "Workspace " (random-uuid))created (mt/user-http-request :crowberto :post 200 "ee/workspace"@@ -225,7 +221,7 @@:model/User user-b {:first_name "UserB" :last_name "Test" :email "[email protected]" :is_superuser true}:model/User user-c {:first_name "UserC" :last_name "Test" :email "[email protected]" :is_superuser true}];; mt/with-temp with users will trigger their cleanup and those tables fail with their fks to core_user- (mt/with-model-cleanup [:model/WorkspaceMerge :model/ApiKey]+ (mt/with-model-cleanup [:model/WorkspaceMerge];; User A creates the workspace(let [{ws-id :id ws-name :name} (mt/user-http-request user-a :post 200 "ee/workspace"{:name (mt/random-name)@@ -877,11 +873,11 @@(deftest validate-target-test(let [table (t2/select-one :model/Table :db_id (mt/id) :active true {:where [:not [:like :schema "mb__%"]]})](ws.tu/with-workspaces! [ws {:name "test" :database_id (:db_id table)}]- (mt/with-temp [:model/WorkspaceTransform _x1 {:workspace_id (:id ws)- :target {:database (:db_id table)- :type "table"- :schema (:schema table)- :name (str "q_" (:name table))}}]+ (mt/with-temp [:model/WorkspaceTransform x1 {:workspace_id (:id ws)+ :target {:database (:db_id table)+ :type "table"+ :schema (:schema table)+ :name (str "q_" (:name table))}}](testing "Unique"(is (= "OK"(mt/with-log-level [metabase.driver.sql-jdbc.sync.describe-table :fatal]@@ -916,7 +912,17 @@{:db_id (:db_id table):target {:type "table":schema (:schema table)- :name (str "q_" (:name table))}})))))))))+ :name (str "q_" (:name table))}})))))++ (testing "No self-conflict when transform-id matches"+ (is (= "OK"+ (mt/with-log-level [metabase.driver.sql-jdbc.sync.describe-table :fatal]+ (mt/user-http-request :crowberto :post 200 (ws-url (:id ws) "/transform/validate/target")+ {:db_id (:db_id table)+ :target {:type "table"+ :schema (:schema table)+ :name (str "q_" (:name table))}}+ :transform-id (:ref_id x1))))))))));;;; Async workspace creation tests@@ -2383,128 +2389,10 @@;;; ============================================ Authorization Test Matrix ============================================-(def ^:private admin-only-routes- "Routes that require superuser access"- [[:get "/"]- [:post "/"]- [:get "/enabled"]- [:get "/database"]- [:get "/checkout"]- [:put "/:ws-id"]- [:post "/:ws-id/unarchive"]- [: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- "Routes that allow workspace service users ({:access :workspace})"- [[:get "/:ws-id"]- [: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"]- [:post "/:ws-id/archive"]- [:post "/:ws-id/transform"]- [:get "/:ws-id/transform/:tx-id"]- [:put "/:ws-id/transform/:tx-id"]- [:delete "/:ws-id/transform/:tx-id"]- [:post "/:ws-id/transform/:tx-id/archive"]- [:post "/:ws-id/transform/:tx-id/unarchive"]- [:post "/:ws-id/run"]- [:post "/:ws-id/transform/:tx-id/run"]- [:post "/:ws-id/transform/:tx-id/dry-run"]- [:post "/:ws-id/transform/validate/target"]- [:post "/:ws-id/query"]])--(def ^:private permission-denied-msg "You don't have permissions to do that.")--(deftest service-user-authorization-test- (ws.tu/with-workspaces! [ws1 {:name "Workspace 1"}- ws2 {:name "Workspace 2"}]- (mt/with-temp [:model/WorkspaceTransform tx {:name "Test Transform"- :workspace_id (:id ws1)}]- (let [service-user-1 (:execution_user ws1)- service-user-2 (:execution_user ws2)- resolve-url (fn [pattern]- (-> pattern- (str/replace ":ws-id" (str (:id ws1)))- (str/replace ":tx-id" (:ref_id tx))- (->> (str "ee/workspace"))))]-- ;; We don't test whether an admin can access the routes - that's implicit in the regular tests for each route.-- (testing "Admin-only routes reject service users and other non-admins"- (doseq [[method pattern] admin-only-routes- :let [url (resolve-url pattern)]]- (testing (str method " " pattern)- (is (= permission-denied-msg (mt/user-http-request :rasta method 403 url))- "Should reject regular users")- (is (= permission-denied-msg (mt/user-http-request service-user-1 method 403 url))- "Should reject even its own service user"))))-- (testing "Workspace routes allow own service user, reject others"- (doseq [[method pattern] service-user-routes- :let [url (resolve-url pattern)]]- (testing (str method " " pattern)- ;; We check for NOT 403 since some routes may 404 without full setup.- ;; If auth passes, we won't get the permission-denied message.- (let [resp (mt/user-http-request-full-response service-user-1 method url)]- (is (not= 403 (:status_code resp)) "Should allow its own service user")- (is (not= permission-denied-msg (:body resp)) "Should allow its own service user"))- (is (= permission-denied-msg (mt/user-http-request service-user-2 method 403 url))- "Should reject other service users"))))))))--(deftest service-user-access-metadata-matches-patterns-test- (testing "Endpoint {:access :workspace} metadata matches service-user-patterns"- (let [;; Get all endpoints from the workspace API namespace- endpoints (api.macros/ns-routes 'metabase-enterprise.workspaces.api)- ;; Convert route path to the expected pattern suffix (what comes after /api/ee/workspace/\d+)- ;; e.g., /:ws-id/run -> /run, /:ws-id/transform/:tx-id -> /transform/[^/]+- route->suffix (fn [route]- (-> route- (str/replace #"^/:ws-id" "") ; Remove ws-id prefix- (str/replace #"/:tx-id" "/[^/]+"))) ; tx-id is string- ;; Extract [method route] pairs with {:access :workspace} metadata- workspace-access (into #{}- (keep (fn [[[method route _] info]]- (when (= :workspace (get-in info [:form :metadata :access]))- [method route])))- endpoints)- ;; Get the private vars from the API namespace- patterns @#'ws.api/service-user-patterns- ws-prefix @#'ws.api/ws-prefix- ;; Check the inverse: for each pattern, find endpoints that match- pattern->endpoints (fn [method pattern]- (filter (fn [[[m route _] _info]]- (and (= m method)- (let [suffix (route->suffix route)- expected-pattern (str ws-prefix suffix "$")]- (= (str pattern) expected-pattern))))- endpoints))]-- (testing "Every endpoint with {:access :workspace} is covered by service-user-patterns"- (doseq [[method route] workspace-access]- (testing (str method " " route)- (let [suffix (route->suffix route)- expected-pattern (str ws-prefix suffix "$")- method-patterns (get patterns method)]- (is (some #(= (str %) expected-pattern) method-patterns)- (str "Endpoint has {:access :workspace} but no matching pattern in service-user-patterns. "- "Expected pattern: " expected-pattern))))))-- (testing "Every pattern in service-user-patterns matches only endpoints with {:access :workspace}"- (doseq [[method method-patterns] patterns- pattern method-patterns]- (let [matching-endpoints (pattern->endpoints method pattern)]- (testing (str method " " pattern)- (is (seq matching-endpoints)- "Pattern doesn't match any endpoint. Remove the stale pattern.")- (doseq [[[_ route _] info] matching-endpoints]- (is (= :workspace (get-in info [:form :metadata :access]))- (str "Pattern matches " route " but endpoint lacks {:access :workspace} metadata. "- "Add the metadata or remove the pattern."))))))))))+(deftest superuser-authorization-test+ (testing "All workspace routes require superuser (spot-check)"+ (ws.tu/with-workspaces! [ws {:name "Auth Test"}]+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 "ee/workspace")))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 (ws-url (:id ws))))))))diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/test_util.clj b/enterprise/backend/test/metabase_enterprise/workspaces/test_util.cljindex b2dd0c90bc2..f788c5ef459 100644--- a/enterprise/backend/test/metabase_enterprise/workspaces/test_util.clj+++ b/enterprise/backend/test/metabase_enterprise/workspaces/test_util.clj@@ -346,10 +346,11 @@Useful for testing workspace execution logic without running real transforms."[& body]`(mt/with-dynamic-fn-redefs [ws.execute/run-transform-with-remapping- (fn [_transform# _remapping#]+ (fn [transform# _remapping#]{:status :succeeded:end_time (Instant/now)- :message "Mocked execution"})]+ :message "Mocked execution"+ :table (select-keys (:target transform#) [:schema :name])})]~@body))(defn mock-run-transform!diff --git a/resources/migrations/060/20260307_workspace_api_key_cleanup.yaml b/resources/migrations/060/20260307_workspace_api_key_cleanup.yamlnew file mode 100644index 00000000000..439c48f40f3--- /dev/null+++ b/resources/migrations/060/20260307_workspace_api_key_cleanup.yaml@@ -0,0 +1,48 @@+## Clean up workspace API keys and drop the api_key_id column from workspace table++databaseChangeLog:+ - logicalFilePath: migrations/060_update_migrations.yaml+ - changeSet:+ id: v60.2026-03-07T00:00:00+ author: christruter+ comment: Delete orphaned API keys that were created for workspace service users+ preConditions:+ - onFail: MARK_RAN+ - columnExists:+ tableName: workspace+ columnName: api_key_id+ changes:+ - sql:+ sql: >-+ DELETE FROM api_key WHERE id IN (SELECT api_key_id FROM workspace WHERE api_key_id IS NOT NULL);+ rollback:++ - changeSet:+ id: v60.2026-03-07T00:00:01+ author: christruter+ comment: Drop index on workspace.api_key_id+ preConditions:+ - onFail: MARK_RAN+ - indexExists:+ tableName: workspace+ indexName: idx_workspace_api_key_id+ changes:+ - dropIndex:+ tableName: workspace+ indexName: idx_workspace_api_key_id+ rollback:++ - changeSet:+ id: v60.2026-03-07T00:00:02+ author: christruter+ comment: Drop unused api_key_id column from workspace table+ preConditions:+ - onFail: MARK_RAN+ - columnExists:+ tableName: workspace+ columnName: api_key_id+ changes:+ - dropColumn:+ tableName: workspace+ columnName: api_key_id+ rollback:diff --git a/src/metabase/transforms_base/util.clj b/src/metabase/transforms_base/util.cljindex 4157b7a5a47..94ecc69dafb 100644--- a/src/metabase/transforms_base/util.clj+++ b/src/metabase/transforms_base/util.clj@@ -678,6 +678,17 @@(assoc v :alias (name alias))))m)))+(defn normalize-source-tables-structure+ "Converts legacy map format to vec format if needed, otherwise passes through."+ [st]+ (if (map? st)+ (source-tables-map->vec st)+ st))++(def keyword-type-dispatch+ "Dispatch function for malli :multi schemas that dispatch on `(keyword (:type m))`."+ (comp keyword :type))+;;; ------------------------------------------------- Timestamp Helpers -------------------------------------------------(defn ->instantdiff --git a/src/metabase/warehouse_schema/models/field_values.clj b/src/metabase/warehouse_schema/models/field_values.cljindex 41b65597c85..cb86bcaed6d 100644--- a/src/metabase/warehouse_schema/models/field_values.clj+++ b/src/metabase/warehouse_schema/models/field_values.clj@@ -451,7 +451,8 @@This may implicitly delete shadowed entries in the database, see [[delete-duplicates-and-return-latest!]]"[field-ids](delete-duplicates-and-return-latest!- (t2/select :model/FieldValues :field_id [:in field-ids] :type :full :hash_key nil)))+ (when (seq field-ids)+ (t2/select :model/FieldValues :field_id [:in field-ids] :type :full :hash_key nil))))(defn create-or-update-full-field-values!"Create or update the full FieldValues object for `field`. If the FieldValues object already exists, then update values fordiff --git a/test/metabase/test/data/impl.clj b/test/metabase/test/data/impl.cljindex 26ffd8fa967..236aedc37b9 100644--- a/test/metabase/test/data/impl.clj+++ b/test/metabase/test/data/impl.clj@@ -260,7 +260,8 @@;; now copy the FieldValues as well.(let [old-field-id->name (t2/select-pk->fn :name :model/Field :table_id old-table-id :active true)new-field-name->id (t2/select-fn->pk :name :model/Field :table_id new-table-id :active true)- old-field-values (t2/select :model/FieldValues :field_id [:in (set (keys old-field-id->name))])]+ old-field-values (when-let [field-ids (seq (keys old-field-id->name))]+ (t2/select :model/FieldValues :field_id [:in (set field-ids)]))](t2/insert! :model/FieldValues(for [{old-field-id :field_id, :as field-values} old-field-values:let [field-name (get old-field-id->name old-field-id)]]