Skip to content

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

Record dependencies for actions in the dependency graph (#84312)

Alexander Polyankina9a9a82c5da3
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index f9c3a3d2a90..21cfc2604f6 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -3892,7 +3892,8 @@
{:team "Graphy"
:module-exports #{enterprise/dependencies.replacement}
:api #{metabase-enterprise.dependencies.api metabase-enterprise.dependencies.init metabase-enterprise.dependencies.models.dependency}
- :uses #{api
+ :uses #{actions
+ api
app-db
batch-processing
collections
@@ -3923,7 +3924,8 @@
util.graph
warehouse-schema-overlay
enterprise/permissions.sandbox}
- :model-imports #{:model/Card
+ :model-imports #{:model/Action
+ :model/Card
:model/Collection
:model/Dashboard
:model/DashboardCard
@@ -3936,6 +3938,7 @@
:model/FieldUserSettings
:model/Measure
:model/NativeQuerySnippet
+ :model/QueryAction
:model/Sandbox
:model/Segment
:model/Table
diff --git a/e2e/support/helpers/e2e-dependency-helpers.ts b/e2e/support/helpers/e2e-dependency-helpers.ts
index d162bead5e0..276579958c7 100644
--- a/e2e/support/helpers/e2e-dependency-helpers.ts
+++ b/e2e/support/helpers/e2e-dependency-helpers.ts
@@ -13,6 +13,7 @@ export const DependencyGraph = {
entrySearchInput: () => cy.findByTestId("graph-entry-search-input"),
selectionButton: () => cy.findByTestId("graph-selection-button"),
dependencyPanel: () => cy.findByTestId("graph-dependency-panel"),
+ infoPanel: () => cy.findByTestId("graph-info-panel"),
};
export const DependencyDiagnostics = {
diff --git a/e2e/test/scenarios/dependencies/dependency-diagnostics.cy.spec.ts b/e2e/test/scenarios/dependencies/dependency-diagnostics.cy.spec.ts
index a6b59a288ed..dbb40e44837 100644
--- a/e2e/test/scenarios/dependencies/dependency-diagnostics.cy.spec.ts
+++ b/e2e/test/scenarios/dependencies/dependency-diagnostics.cy.spec.ts
@@ -667,7 +667,7 @@ describe(
});
H.DependencyDiagnostics.filterButton().click();
- H.popover().findByText("Snippet").click();
+ H.popover().findByText("SQL snippet").click();
checkList({
visibleEntities: [MODEL_FOR_NATIVE_QUESTION_CARD_TAG],
hiddenEntities: [SNIPPET_FOR_SNIPPET_TAG],
@@ -689,7 +689,7 @@ describe(
cy.log("type");
H.DependencyDiagnostics.filterButton().click();
- H.popover().findByText("Snippet").click();
+ H.popover().findByText("SQL snippet").click();
checkList({ visibleEntities: SEARCHABLE_ENTITY_NAMES });
H.popover().findByText("Model").click();
diff --git a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
index fa1fd7e74b7..eb9753ec27d 100644
--- a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
+++ b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
@@ -16,8 +16,15 @@ import type {
IconName,
MeasureId,
NativeQuerySnippetId,
+ OpaqueDatasetQuery,
SegmentId,
TableId,
+ TestAggregationSpec,
+ TestNativeQuerySpec,
+ TestStageSpec,
+ TestStageWithSourceSpec,
+ WritebackActionId,
+ WritebackParameter,
} from "metabase-types/api";
import { createMockCard } from "metabase-types/api/mocks";
@@ -56,6 +63,10 @@ const SEGMENT_BASED_MODEL_NAME = "Segment-based model";
const SEGMENT_BASED_MEASURE_NAME = "Segment-based measure";
const SEGMENT_BASED_METRIC_NAME = "Segment-based metric";
const SEGMENT_BASED_SEGMENT_NAME = "Segment-based segment";
+const DATA_ACTIONS_FOLDER_NAME = "Data actions folder";
+const TABLE_BASED_ACTION_NAME = "Table-based data action";
+const SNIPPET_BASED_ACTION_NAME = "Snippet-based data action";
+const DATA_ACTIONS_ROOT_NAME = "Data actions";
const ROOT_COLLECTION_NAME = "Our analytics";
const FIRST_COLLECTION_NAME = "First collection";
const DASHBOARD_NAME = "Dashboard";
@@ -136,13 +147,20 @@ describe("scenarios > dependencies > dependency graph", () => {
cy.findByLabelText("Close").click();
});
H.DependencyGraph.entryButton().icon("close").click();
+ }
+ function testEntityPickerSearch({
+ itemName,
+ itemIcon,
+ }: {
+ itemName: string;
+ itemIcon: IconName;
+ }) {
cy.log(`verify that "${itemName}" can be found via search"`);
H.DependencyGraph.entrySearchInput().click();
H.popover().findByText("Browse all").click();
H.entityPickerModal().within(() => {
- // Unjustified type cast. FIXME
- cy.findByPlaceholderText(/Search/).type(itemName as string);
+ cy.findByPlaceholderText(/Search/).type(itemName);
cy.findByText(/results for/).should("be.visible");
cy.findByTestId("search-scope-selector")
.findByText("Everywhere")
@@ -159,6 +177,10 @@ describe("scenarios > dependencies > dependency graph", () => {
createTableBasedMetric({ tableId });
createTableBasedTransform({ tableName: TABLE_NAME });
});
+ createEmptySnippet();
+ createDataActionsFolder().then(({ body: folder }) =>
+ createTableBasedAction({ collectionId: folder.id }),
+ );
visitGraph();
testEntitySearch({
@@ -201,22 +223,54 @@ describe("scenarios > dependencies > dependency graph", () => {
path: ["Databases", /Sample Database/, "Products"],
itemIcon: "table",
});
+ testEntityPickerSearch({
+ itemName: "Products",
+ itemIcon: "table",
+ });
testEntityPicker({
path: ["Our analytics", "Orders, Count, Grouped by Created At (year)"],
itemIcon: "line",
});
+ testEntityPickerSearch({
+ itemName: "Orders, Count, Grouped by Created At (year)",
+ itemIcon: "line",
+ });
testEntityPicker({
path: ["Our analytics", "Orders Model"],
itemIcon: "model",
});
+ testEntityPickerSearch({
+ itemName: "Orders Model",
+ itemIcon: "model",
+ });
testEntityPicker({
path: ["Our analytics", TABLE_BASED_METRIC_NAME],
itemIcon: "metric",
});
+ testEntityPickerSearch({
+ itemName: TABLE_BASED_METRIC_NAME,
+ itemIcon: "metric",
+ });
testEntityPicker({
path: [/Transforms/, TABLE_BASED_TRANSFORM_NAME],
itemIcon: "transform",
});
+ testEntityPickerSearch({
+ itemName: TABLE_BASED_TRANSFORM_NAME,
+ itemIcon: "transform",
+ });
+ testEntityPicker({
+ path: ["SQL Snippets", EMPTY_SNIPPET_NAME],
+ itemIcon: "snippet",
+ });
+ testEntityPicker({
+ path: [
+ DATA_ACTIONS_ROOT_NAME,
+ DATA_ACTIONS_FOLDER_NAME,
+ TABLE_BASED_ACTION_NAME,
+ ],
+ itemIcon: "bolt",
+ });
});
});
@@ -262,6 +316,7 @@ describe("scenarios > dependencies > dependency graph", () => {
);
createTableBasedSegment({ tableId });
createTableBasedMeasure({ tableId });
+ createTableBasedAction();
visitGraphForEntity(tableId, "table");
});
@@ -339,6 +394,12 @@ describe("scenarios > dependencies > dependency graph", () => {
groupTitle: "1 measure",
dependentItemTitle: TABLE_BASED_MEASURE_NAME,
});
+ verifyPanelNavigation({
+ itemTitle: TABLE_DISPLAY_NAME,
+ groupTitle: "1 data action",
+ dependentItemTitle: TABLE_BASED_ACTION_NAME,
+ dependentItemLocation: DATA_ACTIONS_ROOT_NAME,
+ });
cy.log("transform dependents");
H.DependencyGraph.graph()
@@ -402,7 +463,7 @@ describe("scenarios > dependencies > dependency graph", () => {
it("should display dependencies for a question and a model and navigate to them", () => {
getScoreboardTableId().then((tableId) => {
- createTableBasedQuestion({ tableId }).then(({ body: card }) => {
+ createTableBasedQuestion({ tableId }).then((card) => {
createCardBasedDependents({
cardId: card.id,
namePrefix: QUESTION_BASED_NAME_PREFIX,
@@ -410,7 +471,7 @@ describe("scenarios > dependencies > dependency graph", () => {
});
cy.wrap(card.id).as("questionId");
});
- createTableBasedModel({ tableId }).then(({ body: card }) => {
+ createTableBasedModel({ tableId }).then((card) => {
createCardBasedDependents({
cardId: card.id,
namePrefix: MODEL_BASED_NAME_PREFIX,
@@ -494,7 +555,7 @@ describe("scenarios > dependencies > dependency graph", () => {
it("should display dependencies for a metric and navigate to them", () => {
getScoreboardTableId().then((tableId) =>
- createTableBasedMetric({ tableId }).then(({ body: card }) => {
+ createTableBasedMetric({ tableId }).then((card) => {
createMetricBasedQuestion({ tableId, metricId: card.id });
createMetricBasedModel({ tableId, metricId: card.id });
createMetricBasedMetric({ tableId, metricId: card.id });
@@ -542,6 +603,11 @@ describe("scenarios > dependencies > dependency graph", () => {
snippetName: snippet.name,
});
createSnippetBasedSnippet({ snippetName: snippet.name });
+ createSnippetBasedAction({
+ tableName: TABLE_NAME,
+ snippetId: snippet.id,
+ snippetName: snippet.name,
+ });
visitGraphForEntity(snippet.id, "snippet");
});
verifyPanelNavigation({
@@ -561,9 +627,54 @@ describe("scenarios > dependencies > dependency graph", () => {
});
verifyPanelNavigation({
itemTitle: EMPTY_SNIPPET_NAME,
- groupTitle: "1 snippet",
+ groupTitle: "1 SQL snippet",
dependentItemTitle: SNIPPET_BASED_SNIPPET_NAME,
});
+ verifyPanelNavigation({
+ itemTitle: EMPTY_SNIPPET_NAME,
+ groupTitle: "1 data action",
+ dependentItemTitle: SNIPPET_BASED_ACTION_NAME,
+ });
+ });
+
+ it("should display the dependencies and parameters of a data action", () => {
+ createDataActionsFolder().then(({ body: folder }) =>
+ createTableBasedAction({ collectionId: folder.id }).then(
+ ({ body: action }) => {
+ H.waitForBackfillComplete();
+ cy.visit(`/data-studio/actions/${action.id}`);
+ },
+ ),
+ );
+
+ cy.log("open the dependencies tab of the data action");
+ cy.findByRole("link", { name: "Dependencies" }).click();
+ H.DependencyGraph.graph().within(() => {
+ cy.findByLabelText(TABLE_DISPLAY_NAME).should("be.visible");
+ cy.findByLabelText(TABLE_BASED_ACTION_NAME).should("be.visible");
+ });
+
+ cy.log("the info panel shows the data action's folder and parameters");
+ H.DependencyGraph.graph()
+ .findByLabelText(TABLE_BASED_ACTION_NAME)
+ .findByText(TABLE_BASED_ACTION_NAME)
+ .click();
+ H.DependencyGraph.infoPanel().within(() => {
+ cy.findByText(DATA_ACTIONS_FOLDER_NAME).should("be.visible");
+ cy.findByText("Parameters").should("be.visible");
+ cy.findByText("Team ID").should("be.visible");
+ });
+
+ cy.log("navigate from the table to the data action");
+ getScoreboardTableId().then((tableId) =>
+ visitGraphForEntity(tableId, "table"),
+ );
+ verifyPanelNavigation({
+ itemTitle: TABLE_DISPLAY_NAME,
+ groupTitle: "1 data action",
+ dependentItemTitle: TABLE_BASED_ACTION_NAME,
+ dependentItemLocation: DATA_ACTIONS_FOLDER_NAME,
+ });
});
});
});
@@ -634,9 +745,14 @@ function verifyCardDependentsNavigation({
});
verifyPanelNavigation({
itemTitle,
- groupTitle: "1 snippet",
+ groupTitle: "1 SQL snippet",
dependentItemTitle: names.snippet,
});
+ verifyPanelNavigation({
+ itemTitle,
+ groupTitle: "1 data action",
+ dependentItemTitle: names.action,
+ });
}
function getElementCenter(element: HTMLElement) {
@@ -712,6 +828,75 @@ function getScoreboardTableId() {
return cy.get<number>(`@${TABLE_ID_ALIAS}`);
}
+function createWritableQuery(stage: TestStageWithSourceSpec) {
+ return H.createTestQuery({ database: WRITABLE_DB_ID, stages: [stage] });
+}
+
+function createWritableNativeQuery(spec: TestNativeQuerySpec) {
+ return H.createTestNativeQuery({ database: WRITABLE_DB_ID, ...spec });
+}
+
+function createCardFromStage({
+ name,
+ type,
+ stage,
+ collectionId,
+ dashboardId,
+}: {
+ name: string;
+ type: CardType;
+ stage: TestStageWithSourceSpec;
+ collectionId?: CollectionId | null;
+ dashboardId?: DashboardId | null;
+}) {
+ return createWritableQuery(stage).then((query) =>
+ H.createCard({
+ name,
+ type,
+ dataset_query: query,
+ collection_id: collectionId,
+ dashboard_id: dashboardId,
+ }),
+ );
+}
+
+function createTransformFromQuery({
+ name,
+ tableName,
+ query,
+}: {
+ name: string;
+ tableName: string;
+ query: OpaqueDatasetQuery;
+}) {
+ return H.createTransform({
+ name,
+ source: { type: "query", query },
+ target: {
+ type: "table",
+ database: WRITABLE_DB_ID,
+ schema: "public",
+ name: tableName,
+ },
+ });
+}
+
+function getSnippetTemplateTags({
+ snippetId,
+ snippetName,
+}: {
+ snippetId: NativeQuerySnippetId;
+ snippetName: string;
+}): TestNativeQuerySpec["templateTags"] {
+ return {
+ [`snippet: ${snippetName}`]: {
+ type: "snippet",
+ "snippet-id": snippetId,
+ "snippet-name": snippetName,
+ },
+ };
+}
+
function createTableBasedCard({
name,
type,
@@ -725,15 +910,12 @@ function createTableBasedCard({
collectionId?: CollectionId | null;
dashboardId?: DashboardId | null;
}) {
- return H.createQuestion({
+ return createCardFromStage({
name,
type,
- database: WRITABLE_DB_ID,
- query: {
- "source-table": tableId,
- },
- collection_id: collectionId,
- dashboard_id: dashboardId,
+ stage: { source: { type: "table", id: tableId } },
+ collectionId,
+ dashboardId,
});
}
@@ -752,7 +934,7 @@ function createTableBasedQuestion({
name,
type: "question",
tableId,
- collectionId: collectionId,
+ collectionId,
dashboardId,
});
}
@@ -764,7 +946,7 @@ function createTableBasedModel({
}: {
name?: string;
tableId: TableId;
- collectionId?: number | null;
+ collectionId?: CollectionId | null;
}) {
return createTableBasedCard({
name,
@@ -781,6 +963,7 @@ function getCardBasedDependentNames(namePrefix: string) {
metric: `${namePrefix} metric`,
transform: `${namePrefix} transform`,
snippet: `${namePrefix} snippet`,
+ action: `${namePrefix} data action`,
};
}
@@ -794,59 +977,30 @@ function createCardBasedDependents({
transformTableName: string;
}) {
const names = getCardBasedDependentNames(namePrefix);
- createCardBasedCard({ name: names.question, type: "question", cardId });
- createCardBasedCard({ name: names.model, type: "model", cardId });
- H.createQuestion({
+ const source = { type: "card", id: cardId } as const;
+ createCardFromStage({
+ name: names.question,
+ type: "question",
+ stage: { source },
+ });
+ createCardFromStage({ name: names.model, type: "model", stage: { source } });
+ createCardFromStage({
name: names.metric,
type: "metric",
- database: WRITABLE_DB_ID,
- query: {
- "source-table": `card__${cardId}`,
- aggregation: [["count"]],
- },
- });
- H.createTransform({
- name: names.transform,
- source: {
- type: "query",
- query: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": `card__${cardId}`,
- },
- },
- },
- target: {
- type: "table",
- database: WRITABLE_DB_ID,
- schema: "public",
- name: transformTableName,
- },
+ stage: { source, aggregations: [{ type: "operator", operator: "count" }] },
});
+ createWritableQuery({ source }).then((query) =>
+ createTransformFromQuery({
+ name: names.transform,
+ tableName: transformTableName,
+ query,
+ }),
+ );
H.createSnippet({
name: names.snippet,
content: `{{#${cardId}}}`,
});
-}
-
-function createCardBasedCard({
- name,
- type,
- cardId,
-}: {
- name: string;
- type: CardType;
- cardId: CardId;
-}) {
- return H.createQuestion({
- name,
- type,
- database: WRITABLE_DB_ID,
- query: {
- "source-table": `card__${cardId}`,
- },
- });
+ createCardBasedAction({ name: names.action, cardId });
}
function createMetricBasedCard({
@@ -860,13 +1014,12 @@ function createMetricBasedCard({
tableId: TableId;
metricId: CardId;
}) {
- return H.createQuestion({
+ return createCardFromStage({
name,
type,
- database: WRITABLE_DB_ID,
- query: {
- "source-table": tableId,
- aggregation: [["metric", metricId]],
+ stage: {
+ source: { type: "table", id: tableId },
+ aggregations: [{ type: "metric", id: metricId }],
},
});
}
@@ -914,24 +1067,10 @@ function createSnippetBasedCard({
snippetId: NativeQuerySnippetId;
snippetName: string;
}) {
- return H.createNativeQuestion({
- name,
- type,
- database: WRITABLE_DB_ID,
- native: {
- query: `SELECT * FROM ${tableName} WHERE {{snippet:${snippetName}}}`,
- "template-tags": {
- [`snippet:${snippetName}`]: {
- id: "4b77cc1f-ea70-4ef6-84db-58432fce6928",
- name: `snippet:${snippetName}`,
- "display-name": `snippet:${snippetName}`,
- type: "snippet",
- "snippet-id": snippetId,
- "snippet-name": snippetName,
- },
- },
- },
- });
+ return createWritableNativeQuery({
+ query: `SELECT * FROM ${tableName} WHERE {{snippet: ${snippetName}}}`,
+ templateTags: getSnippetTemplateTags({ snippetId, snippetName }),
+ }).then((query) => H.createCard({ name, type, dataset_query: query }));
}
function createSnippetBasedQuestion({
@@ -971,13 +1110,12 @@ function createSnippetBasedModel({
}
function createTableBasedMetric({ tableId }: { tableId: TableId }) {
- return H.createQuestion({
+ return createCardFromStage({
name: TABLE_BASED_METRIC_NAME,
type: "metric",
- database: WRITABLE_DB_ID,
- query: {
- "source-table": tableId,
- aggregation: [["count"]],
+ stage: {
+ source: { type: "table", id: tableId },
+ aggregations: [{ type: "operator", operator: "count" }],
},
});
}
@@ -989,38 +1127,24 @@ function createMetricBasedMetric({
tableId: TableId;
metricId: CardId;
}) {
- return H.createQuestion({
+ return createMetricBasedCard({
name: METRIC_BASED_METRIC_NAME,
type: "metric",
- database: WRITABLE_DB_ID,
- query: {
- "source-table": tableId,
- aggregation: [["metric", metricId]],
- },
+ tableId,
+ metricId,
});
}
function createTableBasedTransform({ tableName }: { tableName: string }) {
- return H.createTransform({
- name: TABLE_BASED_TRANSFORM_NAME,
- source: {
- type: "query",
- query: {
- database: WRITABLE_DB_ID,
- type: "native",
- native: {
- query: `SELECT * from ${tableName}`,
- "template-tags": {},
- },
- },
- },
- target: {
- type: "table",
- database: WRITABLE_DB_ID,
- schema: "public",
- name: TRANSFORM_TABLE_NAME,
- },
- });
+ return createWritableNativeQuery({
+ query: `SELECT * from ${tableName}`,
+ }).then((query) =>
+ createTransformFromQuery({
+ name: TABLE_BASED_TRANSFORM_NAME,
+ tableName: TRANSFORM_TABLE_NAME,
+ query,
+ }),
+ );
}
function createMetricBasedTransform({
@@ -1030,29 +1154,101 @@ function createMetricBasedTransform({
tableId: TableId;
metricId: CardId;
}) {
- return H.createTransform({
- name: METRIC_BASED_TRANSFORM_NAME,
- source: {
- type: "query",
- query: {
- database: WRITABLE_DB_ID,
+ return createWritableQuery({
+ source: { type: "table", id: tableId },
+ aggregations: [{ type: "metric", id: metricId }],
+ }).then((query) =>
+ createTransformFromQuery({
+ name: METRIC_BASED_TRANSFORM_NAME,
+ tableName: TRANSFORM_TABLE_NAME,
+ query,
+ }),
+ );
+}
+
+function createSnippetBasedTransform({
+ tableName,
+ snippetId,
+ snippetName,
+}: {
+ tableName: string;
+ snippetId: NativeQuerySnippetId;
+ snippetName: string;
+}) {
+ return createWritableNativeQuery({
+ query: `SELECT * FROM ${tableName} WHERE {{snippet: ${snippetName}}}`,
+ templateTags: getSnippetTemplateTags({ snippetId, snippetName }),
+ }).then((query) =>
+ createTransformFromQuery({
+ name: SNIPPET_BASED_TRANSFORM_NAME,
+ tableName: TRANSFORM_TABLE_NAME,
+ query,
+ }),
+ );
+}
+
+function createDataActionsFolder() {
+ return cy.request<{ id: CollectionId }>("POST", "/api/collection", {
+ name: DATA_ACTIONS_FOLDER_NAME,
+ namespace: "data-actions",
+ });
+}
+
+function createDataAction({
+ name,
+ query,
+ templateTags,
+ parameters = [],
+ collectionId = null,
+}: {
+ name: string;
+ query: string;
+ templateTags?: TestNativeQuerySpec["templateTags"];
+ parameters?: WritebackParameter[];
+ collectionId?: CollectionId | null;
+}) {
+ H.setActionsEnabledForDB(WRITABLE_DB_ID);
+ return createWritableNativeQuery({ query, templateTags }).then(
+ (datasetQuery) =>
+ cy.request<{ id: WritebackActionId }>("POST", "/api/action", {
+ name,
type: "query",
- query: {
- "source-table": tableId,
- aggregation: [["metric", metricId]],
- },
+ database_id: WRITABLE_DB_ID,
+ collection_id: collectionId,
+ dataset_query: datasetQuery,
+ parameters,
+ }),
+ );
+}
+
+function createTableBasedAction({
+ collectionId = null,
+}: { collectionId?: CollectionId | null } = {}) {
+ return createDataAction({
+ name: TABLE_BASED_ACTION_NAME,
+ query: `DELETE FROM ${TABLE_NAME} WHERE id = {{team_id}}`,
+ templateTags: {
+ team_id: {
+ type: "number",
+ "display-name": "Team ID",
+ required: true,
},
},
- target: {
- type: "table",
- database: WRITABLE_DB_ID,
- schema: "public",
- name: TRANSFORM_TABLE_NAME,
- },
+ parameters: [
+ {
+ id: "team_id",
+ slug: "team_id",
+ name: "Team ID",
+ type: "number/=",
+ target: ["variable", ["template-tag", "team_id"]],
+ required: true,
+ },
+ ],
+ collectionId,
});
}
-function createSnippetBasedTransform({
+function createSnippetBasedAction({
tableName,
snippetId,
snippetName,
@@ -1061,33 +1257,25 @@ function createSnippetBasedTransform({
snippetId: NativeQuerySnippetId;
snippetName: string;
}) {
- return H.createTransform({
- name: SNIPPET_BASED_TRANSFORM_NAME,
- source: {
- type: "query",
- query: {
- database: WRITABLE_DB_ID,
- type: "native",
- native: {
- query: `SELECT * FROM ${tableName} WHERE {{snippet:${snippetName}}}`,
- "template-tags": {
- [`snippet:${snippetName}`]: {
- id: "4b77cc1f-ea70-4ef6-84db-58432fce6928",
- name: `snippet:${snippetName}`,
- "display-name": `snippet:${snippetName}`,
- type: "snippet",
- "snippet-id": snippetId,
- "snippet-name": snippetName,
- },
- },
- },
- },
- },
- target: {
- type: "table",
- database: WRITABLE_DB_ID,
- schema: "public",
- name: TRANSFORM_TABLE_NAME,
+ return createDataAction({
+ name: SNIPPET_BASED_ACTION_NAME,
+ query: `DELETE FROM ${tableName} WHERE {{snippet: ${snippetName}}}`,
+ templateTags: getSnippetTemplateTags({ snippetId, snippetName }),
+ });
+}
+
+function createCardBasedAction({
+ name,
+ cardId,
+}: {
+ name: string;
+ cardId: CardId;
+}) {
+ return createDataAction({
+ name,
+ query: `DELETE FROM ${TABLE_NAME} WHERE id IN (SELECT id FROM {{#${cardId}}})`,
+ templateTags: {
+ [`#${cardId}`]: { type: "card", "card-id": cardId },
},
});
}
@@ -1102,23 +1290,30 @@ function createEmptySnippet() {
function createSnippetBasedSnippet({ snippetName }: { snippetName: string }) {
return H.createSnippet({
name: SNIPPET_BASED_SNIPPET_NAME,
- content: `{{snippet:${snippetName}}}`,
+ content: `{{snippet: ${snippetName}}}`,
});
}
function createTableBasedSegment({ tableId }: { tableId: TableId }) {
- return H.createSegment({
- name: TABLE_BASED_SEGMENT_NAME,
- description: "Segment description",
- definition: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": tableId,
- filter: ["=", 1, 1],
+ return createWritableQuery({
+ source: { type: "table", id: tableId },
+ filters: [
+ {
+ type: "operator",
+ operator: "=",
+ args: [
+ { type: "literal", value: 1 },
+ { type: "literal", value: 1 },
+ ],
},
- },
- });
+ ],
+ }).then((definition) =>
+ H.createSegment({
+ name: TABLE_BASED_SEGMENT_NAME,
+ description: "Segment description",
+ definition,
+ }),
+ );
}
function createSegmentBasedSegment({
@@ -1128,18 +1323,16 @@ function createSegmentBasedSegment({
tableId: TableId;
segmentId: SegmentId;
}) {
- return H.createSegment({
- name: SEGMENT_BASED_SEGMENT_NAME,
- description: "Segment description",
- definition: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": tableId,
- filter: ["segment", segmentId],
- },
- },
- });
+ return createWritableQuery({
+ source: { type: "table", id: tableId },
+ filters: [{ type: "segment", id: segmentId }],
+ }).then((definition) =>
+ H.createSegment({
+ name: SEGMENT_BASED_SEGMENT_NAME,
+ description: "Segment description",
+ definition,
+ }),
+ );
}
function createSegmentBasedCard({
@@ -1153,14 +1346,13 @@ function createSegmentBasedCard({
tableId: TableId;
segmentId: SegmentId;
}) {
- return H.createQuestion({
+ return createCardFromStage({
name,
type,
- database: WRITABLE_DB_ID,
- query: {
- "source-table": tableId,
- filter: ["segment", segmentId],
- aggregation: [["count"]],
+ stage: {
+ source: { type: "table", id: tableId },
+ filters: [{ type: "segment", id: segmentId }],
+ aggregations: [{ type: "operator", operator: "count" }],
},
});
}
@@ -1223,37 +1415,46 @@ function createDocumentWithTableBasedQuestion({
name: string;
tableId: TableId;
}) {
- return H.createDocument({
- name: DOCUMENT_NAME,
- document: { type: "doc", content: [] },
- cards: {
- "-1": createMockCard({
- id: -1,
- name,
- dataset_query: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": tableId,
- },
+ return createWritableQuery({ source: { type: "table", id: tableId } }).then(
+ (query) =>
+ H.createDocument({
+ name: DOCUMENT_NAME,
+ document: { type: "doc", content: [] },
+ cards: {
+ "-1": createMockCard({
+ id: -1,
+ name,
+ dataset_query: query,
+ description: "Table based question",
+ }),
},
- description: "Table based question",
}),
- },
- });
+ );
+}
+
+function createMeasure({
+ name,
+ tableId,
+ aggregation,
+ filters,
+}: {
+ name: string;
+ tableId: TableId;
+ aggregation: TestAggregationSpec;
+ filters?: TestStageSpec["filters"];
+}) {
+ return createWritableQuery({
+ source: { type: "table", id: tableId },
+ filters,
+ aggregations: [aggregation],
+ }).then((definition) => H.createMeasure({ name, definition }));
}
function createTableBasedMeasure({ tableId }: { tableId: TableId }) {
- return H.createMeasure({
+ return createMeasure({
name: TABLE_BASED_MEASURE_NAME,
- definition: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": tableId,
- aggregation: [["count"]],
- },
- },
+ tableId,
+ aggregation: { type: "operator", operator: "count" },
});
}
@@ -1264,15 +1465,34 @@ function createSegmentBaseMeasure({
tableId: TableId;
segmentId: SegmentId;
}) {
- return H.createMeasure({
+ return createMeasure({
name: SEGMENT_BASED_MEASURE_NAME,
- definition: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": tableId,
- aggregation: [["count-where", ["segment", segmentId]]],
- },
+ tableId,
+ aggregation: {
+ type: "operator",
+ operator: "count-where",
+ args: [{ type: "segment", id: segmentId }],
+ },
+ });
+}
+
+function createMeasureBasedCard({
+ name,
+ type,
+ tableId,
+ measureId,
+}: {
+ name: string;
+ type: CardType;
+ tableId: TableId;
+ measureId: MeasureId;
+}) {
+ return createCardFromStage({
+ name,
+ type,
+ stage: {
+ source: { type: "table", id: tableId },
+ aggregations: [{ type: "measure", id: measureId }],
},
});
}
@@ -1284,12 +1504,11 @@ function createMeasureBasedQuestion({
tableId: TableId;
measureId: MeasureId;
}) {
- return H.createQuestion({
+ return createMeasureBasedCard({
name: MEASURE_BASED_QUESTION_NAME,
- query: {
- "source-table": tableId,
- aggregation: [["measure", measureId]],
- },
+ type: "question",
+ tableId,
+ measureId,
});
}
@@ -1300,13 +1519,11 @@ function createMeasureBasedModel({
tableId: TableId;
measureId: MeasureId;
}) {
- return H.createQuestion({
+ return createMeasureBasedCard({
name: MEASURE_BASED_MODEL_NAME,
type: "model",
- query: {
- "source-table": tableId,
- aggregation: [["measure", measureId]],
- },
+ tableId,
+ measureId,
});
}
@@ -1317,13 +1534,11 @@ function createMeasureBasedMetric({
tableId: TableId;
measureId: MeasureId;
}) {
- return H.createQuestion({
+ return createMeasureBasedCard({
name: MEASURE_BASED_METRIC_NAME,
type: "metric",
- query: {
- "source-table": tableId,
- aggregation: [["measure", measureId]],
- },
+ tableId,
+ measureId,
});
}
@@ -1334,26 +1549,16 @@ function createMeasureBasedTransform({
tableId: TableId;
measureId: MeasureId;
}) {
- return H.createTransform({
- name: MEASURE_BASED_TRANSFORM_NAME,
- source: {
- type: "query",
- query: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": tableId,
- aggregation: [["measure", measureId]],
- },
- },
- },
- target: {
- type: "table",
- database: WRITABLE_DB_ID,
- schema: "public",
- name: TRANSFORM_TABLE_NAME,
- },
- });
+ return createWritableQuery({
+ source: { type: "table", id: tableId },
+ aggregations: [{ type: "measure", id: measureId }],
+ }).then((query) =>
+ createTransformFromQuery({
+ name: MEASURE_BASED_TRANSFORM_NAME,
+ tableName: TRANSFORM_TABLE_NAME,
+ query,
+ }),
+ );
}
function createMeasureBasedMeasure({
@@ -1363,15 +1568,16 @@ function createMeasureBasedMeasure({
tableId: TableId;
measureId: MeasureId;
}) {
- return H.createMeasure({
+ return createMeasure({
name: MEASURE_BASED_MEASURE_NAME,
- definition: {
- database: WRITABLE_DB_ID,
- type: "query",
- query: {
- "source-table": tableId,
- aggregation: ["+", 1, ["measure", measureId]],
- },
+ tableId,
+ aggregation: {
+ type: "operator",
+ operator: "+",
+ args: [
+ { type: "literal", value: 1 },
+ { type: "measure", id: measureId },
+ ],
},
});
}
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
index c517ea5e38e..5800c7240e7 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
@@ -7,6 +7,7 @@
[metabase-enterprise.dependencies.models.dependency :as dependency]
[metabase-enterprise.dependencies.models.dependency-status :as deps.dependency-status]
[metabase-enterprise.sandbox.schema]
+ [metabase.actions.schema :as actions.schema]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
@@ -49,18 +50,19 @@
:collection :collection_id]
:sandbox [:table :table_id]
:segment [:name :description :created_at :creator :creator_id :table :table_id]
- :measure [:name :description :created_at :creator :creator_id :table :table_id]})
+ :measure [:name :description :created_at :creator :creator_id :table :table_id]
+ :action [:name :description :type :model_id :parameters :created_at :creator :creator_id :collection :collection_id]})
(defn- format-subentity [entity]
(case (t2/model entity)
- :model/Collection (select-keys entity [:id :name :authority_level :is_personal])
+ :model/Collection (select-keys entity [:id :name :authority_level :is_personal :namespace :location])
:model/Dashboard (select-keys entity [:id :name])
:model/Document (select-keys entity [:id :name])
entity))
(mr/def ::usages
[:map-of
- [:enum :table :snippet :transform :dashboard :document :sandbox :segment :question :model :metric :measure]
+ [:enum :table :snippet :transform :dashboard :document :sandbox :segment :question :model :metric :measure :action]
::deps.dependency-types/entity-id])
(mr/def ::dependent-error
@@ -152,6 +154,13 @@
[:type [:= :measure]]
[:data (fields-for :measure)]]])
+(mr/def ::action-entity
+ [:merge ::base-entity
+ [:map
+ [:id ::lib.schema.id/action]
+ [:type [:= :action]]
+ [:data (fields-for :action)]]])
+
(mr/def ::entity
[:multi {:dispatch :type}
[:table [:ref ::table-entity]]
@@ -162,7 +171,8 @@
[:document [:ref ::document-entity]]
[:sandbox [:ref ::sandbox-entity]]
[:segment [:ref ::segment-entity]]
- [:measure [:ref ::measure-entity]]])
+ [:measure [:ref ::measure-entity]]
+ [:action [:ref ::action-entity]]])
(def ^:private Entity
"Any dependency-tracked entity `entity-value` accepts, hydrated the way `hydrate-entities` hydrates it."
@@ -175,7 +185,8 @@
:metabase.native-query-snippets.schema/native-query-snippet
:metabase-enterprise.sandbox.schema/sandbox
:metabase.segments.schema/segment
- :metabase.measures.schema/measure])
+ :metabase.measures.schema/measure
+ ::actions.schema/action])
(mu/defn- entity-value :- ::entity
[entity-type :- ::deps.dependency-types/dependency-types
@@ -219,7 +230,8 @@
:snippet [:id :name :description :created_at :creator_id :collection_id]
:sandbox [:id :table_id]
:segment [:id :name :description :created_at :creator_id :table_id]
- :measure [:id :name :description :created_at :creator_id :table_id]})
+ :measure [:id :name :description :created_at :creator_id :table_id]
+ :action [:id :name :description :type :model_id :parameters :created_at :creator_id :collection_id]})
(defn- current-user-visibility
"The current user, as the `:visible` filter-spec opts consumed by `metabase-enterprise.dependencies.db`.
@@ -325,7 +337,12 @@
:snippet (-> entities
(t2/hydrate :creator :collection)
(->> (map #(collection.root/hydrate-root-collection % (collection.root/hydrated-root-collection :snippets)))))
- (:segment :measure) (t2/hydrate entities :creator [:table :db])))
+ (:segment :measure) (t2/hydrate entities :creator [:table :db])
+ :action (->> (t2/hydrate entities :creator [:collection :is_personal])
+ (map #(collection.root/hydrate-root-collection
+ %
+ (collection.root/root-collection-with-ui-details
+ (dependencies.db/action-root-namespace (nil? (:model_id %)))))))))
(defn- fetch-and-hydrate-nodes
"Fetches and hydrates entities for the given nodes.
@@ -409,7 +426,7 @@
(-> data :document :name)
(-> data :collection :name))
:table (-> data :db :name)
- (:transform :snippet :dashboard :document) (-> data :collection :name)
+ (:transform :snippet :dashboard :document :action) (-> data :collection :name)
:sandbox nil
(:segment :measure) (-> data :table :display_name)
nil)))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj b/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
index 9c3d7339845..b0288749f1a 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
@@ -4,6 +4,7 @@
[metabase-enterprise.dependencies.native-validation :as deps.native]
[metabase-enterprise.dependencies.schema :as deps.schema]
[metabase-enterprise.sandbox.schema]
+ [metabase.actions.schema :as actions.schema]
[metabase.documents.prose-mirror :as prose-mirror]
[metabase.documents.schema :as documents.schema]
[metabase.lib-be.core :as lib-be]
@@ -23,7 +24,8 @@
(def ^:private Entity
"Any dependency-tracked entity `calculate-deps` accepts. A `:dashboard` entity arrives hydrated with `:dashcards`,
- each of those in turn hydrated with `:series`; every other entity is a plain row of its model."
+ each of those in turn hydrated with `:series`; a query `:action` arrives with the `:dataset_query` of its
+ QueryAction; every other entity is a plain row of its model."
[:or
::queries.schema/card
:metabase.warehouse-schema.schema/table
@@ -33,7 +35,8 @@
::documents.schema/document
:metabase-enterprise.sandbox.schema/sandbox
:metabase.segments.schema/segment
- :metabase.measures.schema/measure])
+ :metabase.measures.schema/measure
+ ::actions.schema/action])
(defmulti calculate-deps*
"Implementation multimethod for [[calculate-deps]]. Dispatches on entity-type keyword.
@@ -198,3 +201,9 @@
:segment (or (lib/all-segment-ids definition) #{})
:table (cond-> (into #{} (lib/all-implicitly-joined-table-ids definition))
table_id (conj table_id))})
+
+(defmethod calculate-deps* :action
+ [_ {action-type :type, model-id :model_id, query :dataset_query}]
+ (case action-type
+ :implicit {:card #{model-id}}
+ :query (upstream-deps:query (lib-be/normalize-query query))))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/db.clj b/enterprise/backend/src/metabase_enterprise/dependencies/db.clj
index 620d2c59c6e..4ef9dd2b7bb 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/db.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/db.clj
@@ -58,7 +58,8 @@
Handles different entity types:
- Superuser-only (`:model/Sandbox`): only if `is-superuser?` is true
- - Collection-based (`:model/Card`, `:model/Dashboard`, `:model/Document`, `:model/NativeQuerySnippet`): filters
+ - Collection-based (`:model/Card`, `:model/Dashboard`, `:model/Document`, `:model/NativeQuerySnippet`,
+ `:model/Action`): filters
by collection visibility and archived status. Native query snippets have additional restrictions for
sandboxed users.
- Table: filters by table visibility permissions. Tables are NOT filtered by active/visibility_type regardless
@@ -98,8 +99,15 @@
:is-data-analyst? is-data-analyst?}
{:perms/create-queries :query-builder})]}]])
- (:model/Card :model/Dashboard :model/Document :model/NativeQuerySnippet)
- (let [archived-column (keyword (name table-name) "archived")]
+ (:model/Card :model/Dashboard :model/Document :model/NativeQuerySnippet :model/Action)
+ (let [archived-column (keyword (name table-name) "archived")
+ visible-in-root (fn [root-namespace]
+ (collection/visible-collection-filter-clause
+ (keyword (name table-name) "collection_id")
+ {:include-archived-items include-archived-items
+ :root-namespace root-namespace}
+ {:current-user-id user-id
+ :is-superuser? is-superuser?}))]
(when-not (and (= model :model/NativeQuerySnippet)
(or (perms/sandboxed-user?)
(not (perms/user-has-any-perms-of-type? user-id :perms/create-queries))))
@@ -110,13 +118,16 @@
{:select [:id]
:from [table-name]
:where [:and
- (collection/visible-collection-filter-clause
- (keyword (name table-name) "collection_id")
- {:include-archived-items include-archived-items
- :root-namespace (when (= model :model/NativeQuerySnippet)
- collection/snippets-ns)}
- {:current-user-id user-id
- :is-superuser? is-superuser?})
+ (case model
+ :model/NativeQuerySnippet (visible-in-root collection/snippets-ns)
+ :model/Action [:or
+ [:and
+ [:not= :action.model_id nil]
+ (visible-in-root nil)]
+ [:and
+ [:= :action.model_id nil]
+ (visible-in-root collection/data-actions-ns)]]
+ (visible-in-root nil))
(case include-archived-items
:exclude [:= archived-column false]
:only [:= archived-column true]
@@ -269,6 +280,13 @@
[]
(t2/select-pks-vec :model/Collection :personal_owner_id [:not= nil] :location "/"))
+(defn action-root-namespace
+ "The namespace of the root collection an action without a collection sits in: the data actions root for a
+ `model-less?` action, and the default root for an action of a model."
+ [model-less?]
+ (when model-less?
+ :data-actions))
+
(defn- entity-type-config
"The table name and name/location column expressions to select an item list row for `entity-type`."
[entity-type]
@@ -286,7 +304,8 @@
:document :document
:sandbox :sandboxes
:segment :segment
- :measure :measure)
+ :measure :measure
+ :action :action)
:name-column (case entity-type
:table :entity.display_name
:sandbox [:cast :entity.id (if (= :mysql (mdb/db-type)) :char :text)]
@@ -298,6 +317,13 @@
:else [:coalesce :collection.name (:name root-collection)]]
:table :database.name
(:transform :snippet :dashboard :document) [:coalesce :collection.name (:name root-collection)]
+ :action [:coalesce
+ :collection.name
+ [:case
+ [:= :entity.model_id nil]
+ (:name (collection.root/root-collection-with-ui-details (action-root-namespace true)))
+ :else
+ (:name (collection.root/root-collection-with-ui-details (action-root-namespace false)))]]
:sandbox [:cast :entity.id (if (= :mysql (mdb/db-type)) :char :text)]
(:segment :measure) :table.display_name)}))
@@ -330,7 +356,7 @@
[entity-type]
(case entity-type
:card #{:collection :dashboard :document}
- (:transform :snippet :dashboard :document) #{:collection}
+ (:transform :snippet :dashboard :document :action) #{:collection}
(:segment :measure) #{:table}
:table #{:database}
#{}))
@@ -367,13 +393,13 @@
;; broken by dropped tables stay visible
archived-expr (when-not (= query-type :breaking)
{:expr (case entity-type
- (:card :dashboard :document :snippet :segment :measure)
+ (:card :dashboard :document :snippet :segment :measure :action)
[:= :entity.archived false]
nil)
:joins #{}})
personal-expr (when-not include-personal-collections?
(case entity-type
- (:card :dashboard :document :snippet)
+ (:card :dashboard :document :snippet :action)
(let [personal-ids (personal-root-collection-ids)]
(when (seq personal-ids)
{:expr [:or
@@ -574,6 +600,11 @@
(t2/select-one (into [(deps.dependency-types/dependency-type->model entity-type)] columns)
:id id (entity-source entity-type)))
+(mu/defn query-action-queries
+ "The `:dataset_query` of the QueryActions of the Actions with `action-ids`, keyed by Action id."
+ [action-ids :- [:sequential ::lib.schema.id/action]]
+ (t2/select-fn->fn :action_id :dataset_query :model/QueryAction :action_id [:in action-ids]))
+
(mu/defn card
"The Card with `card-id`, or nil."
[card-id :- ::lib.schema.id/card]
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/dependency_types.clj b/enterprise/backend/src/metabase_enterprise/dependencies/dependency_types.clj
index 7f20139b543..1a68b578756 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/dependency_types.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/dependency_types.clj
@@ -14,7 +14,8 @@
:model/Document :document
:model/Sandbox :sandbox
:model/Segment :segment
- :model/Measure :measure})
+ :model/Measure :measure
+ :model/Action :action})
(def dependency-type->model
"A map relating dependency types to their corresponding model."
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/hooks.clj b/enterprise/backend/src/metabase_enterprise/dependencies/hooks.clj
index 69cd1891d49..1edde6ea56c 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/hooks.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/hooks.clj
@@ -90,8 +90,8 @@
(defmethod before-update* :default [_model _instance] nil)
(defmethod before-delete* :default [_model _instance] nil)
-(doseq [model [:model/Card :model/Dashboard :model/Document :model/Measure :model/NativeQuerySnippet :model/Sandbox
- :model/Segment :model/Transform]]
+(doseq [model [:model/Action :model/Card :model/Dashboard :model/Document :model/Measure :model/NativeQuerySnippet
+ :model/Sandbox :model/Segment :model/Transform]]
(defmethod before-insert* model
[_model _instance]
(trigger-jobs!))
@@ -99,7 +99,8 @@
[model instance]
(mark-changed! (deps.dependency-types/model->dependency-type model) (:id instance))))
-(doseq [[model columns] {:model/Card #{:type :dataset_query :dimension_mappings :parameters}
+(doseq [[model columns] {:model/Action #{:model_id :type}
+ :model/Card #{:type :dataset_query :dimension_mappings :parameters}
:model/Dashboard #{:parameters}
:model/Document #{:content_type :document}
:model/Measure #{:definition :table_id}
@@ -111,6 +112,15 @@
[model instance]
(mark-entity-changed! model instance columns)))
+(defmethod before-insert* :model/QueryAction
+ [_model query-action]
+ (mark-changed! :action (:action_id query-action)))
+
+(defmethod before-update* :model/QueryAction
+ [_model query-action]
+ (when (changed? query-action #{:dataset_query})
+ (mark-changed! :action (:action_id query-action))))
+
(defmethod before-insert* :model/DashboardCard
[_model dashcard]
(mark-changed! :dashboard (:dashboard_id dashcard)))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj
index 55815a561c6..de66599e3ab 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj
@@ -252,6 +252,9 @@
(defmethod add-override :sandbox [^OverridingMetadataProvider mp _entity-type _id _updates]
mp)
+(defmethod add-override :action [^OverridingMetadataProvider mp _entity-type _id _updates]
+ mp)
+
(defmethod add-override :segment [^OverridingMetadataProvider mp _entity-type id updates]
{[:metadata/segment id] (delay (merge (when id
(lib.metadata/segment (inner-mp mp) id))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj
index 5897873b179..772c7036612 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj
@@ -4,6 +4,7 @@
[metabase-enterprise.dependencies.db :as dependencies.db]
[metabase-enterprise.dependencies.dependency-types :as deps.dependency-types]
[metabase-enterprise.sandbox.schema]
+ [metabase.actions.schema :as actions.schema]
[metabase.documents.schema :as documents.schema]
[metabase.graph.core :as graph]
[metabase.lib.core :as lib]
@@ -201,7 +202,8 @@
::documents.schema/document
:metabase-enterprise.sandbox.schema/sandbox
:metabase.segments.schema/segment
- :metabase.measures.schema/measure]]]]
+ :metabase.measures.schema/measure
+ ::actions.schema/action]]]]
(boolean
(case entity-type
:card (some-> entity
@@ -212,6 +214,7 @@
:query
lib/any-native-stage?)
:snippet true
+ :action (= :query (:type entity))
false)))
(defn- native-lookup-map [children]
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj
index 20f69662c0b..28e3dffc71a 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj
@@ -41,6 +41,14 @@
(defmethod hydrate-for-deps :dashboard [_ instances]
(t2/hydrate instances [:dashcards :series]))
+(defmethod hydrate-for-deps :action [_ instances]
+ (let [queries (when (seq instances)
+ (dependencies.db/query-action-queries (mapv :id instances)))]
+ (mapv (fn [{:keys [id] :as action}]
+ (cond-> action
+ (contains? queries id) (assoc :dataset_query (queries id))))
+ instances)))
+
(defn instances-for-dependency-calculation
"Find a batch of instances of type `entity-type` and maximum size `batch-size` that need
dependency calculation: no status row yet, stale=true, OR version < current.
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
index 90dd9755518..8bd8650d9e0 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
@@ -918,6 +918,63 @@
(is (= 1 (count response)))
(is (= (:id card) (:id (first response))))))))))))
+(deftest graph-action-dependents-test
+ (testing "GET /api/ee/dependencies/graph/dependents returns the actions a user can read"
+ (mt/with-premium-features #{:dependencies}
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection readable-collection {}
+ :model/Collection unreadable-collection {:namespace "data-actions"}
+ :model/Card {model-id :id} (assoc (basic-card "Venues model" :venues)
+ :type :model
+ :collection_id (:id readable-collection))
+ :model/Action {readable-id :id} {:type :implicit
+ :name "Create venue"
+ :model_id model-id}
+ :model/ImplicitAction _ {:action_id readable-id, :kind "row/create"}
+ :model/Action {unreadable-id :id} {:type :query
+ :name "Delete venue"
+ :collection_id (:id unreadable-collection)}
+ :model/Action {root-id :id} {:type :query
+ :name "Archive venue"}
+ :model/QueryAction _ {:action_id root-id
+ :database_id (mt/id)
+ :dataset_query (-> (lib/native-query (mt/metadata-provider)
+ (str "DELETE FROM venues WHERE id IN "
+ "(SELECT id FROM {{#" model-id "}})"))
+ (lib/with-template-tags
+ {(str "#" model-id) {:id "model-tag"
+ :type :card
+ :name (str "#" model-id)
+ :display-name "Venues model"
+ :card-id model-id}}))}
+ :model/QueryAction _ {:action_id unreadable-id
+ :database_id (mt/id)
+ :dataset_query (-> (lib/native-query (mt/metadata-provider)
+ (str "DELETE FROM venues WHERE id IN "
+ "(SELECT id FROM {{#" model-id "}})"))
+ (lib/with-template-tags
+ {(str "#" model-id) {:id "model-tag"
+ :type :card
+ :name (str "#" model-id)
+ :display-name "Venues model"
+ :card-id model-id}}))}]
+ (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
+ (perms/grant-collection-read-permissions! (perms/all-users-group) readable-collection)
+ (deps.test/synchronously-run-backfill!)
+ (let [dependents (fn [user]
+ (->> (mt/user-http-request user :get 200 "ee/dependencies/graph/dependents"
+ :id model-id
+ :type "card"
+ :dependent-types "action")
+ (map (juxt :type :id (comp :name :data) (comp (juxt :name :namespace) :collection :data)))
+ set))]
+ (is (= #{["action" readable-id "Create venue" [(:name readable-collection) nil]]
+ ["action" unreadable-id "Delete venue" [(:name unreadable-collection) "data-actions"]]
+ ["action" root-id "Archive venue" ["Data actions" "data-actions"]]}
+ (dependents :crowberto)))
+ (is (= #{["action" readable-id "Create venue" [(:name readable-collection) nil]]}
+ (dependents :rasta))))))))))
+
(deftest graph-measure-root-test
(testing "GET /api/ee/dependencies/graph with measure as root node"
(mt/with-test-user :crowberto
@@ -2796,3 +2853,60 @@
(testing "analyst-wide visibility pauses while advanced-permissions is unavailable"
(mt/with-premium-features #{:data-studio :dependencies :transforms-basic :hosting}
(is (not (contains? (unreferenced-transform-ids) transform-id)))))))))))
+
+(defn- delete-venue-query []
+ (lib/native-query (mt/metadata-provider) "DELETE FROM venues WHERE id = {{id}}"))
+
+(deftest graph-root-data-action-permissions-test
+ (testing "the graph shows a data action at the data-actions root only to users who can read that root"
+ (mt/with-premium-features #{:dependencies}
+ (mt/with-non-admin-groups-no-root-collection-for-namespace-perms :data-actions
+ (mt/with-temp [:model/Action {action-id :id} {:type :query :name "Root data action permtest"}
+ :model/QueryAction _ {:action_id action-id
+ :database_id (mt/id)
+ :dataset_query (delete-venue-query)}]
+ (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
+ (deps.test/synchronously-run-backfill!)
+ (let [dependent-ids (fn []
+ (->> (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/dependents"
+ :id (mt/id :venues)
+ :type "table"
+ :dependent-types "action")
+ (into #{} (map :id))))
+ unreferenced-ids (fn []
+ (->> (mt/user-http-request :rasta :get 200 "ee/dependencies/graph/unreferenced"
+ :types "action"
+ :query "permtest")
+ :data
+ (into #{} (map :id))))]
+ (testing "a user who can read the default root but not the data-actions root"
+ (is (not (contains? (dependent-ids) action-id)))
+ (is (not (contains? (unreferenced-ids) action-id))))
+ (testing "a user who can read the data-actions root"
+ (perms/grant-collection-read-permissions! (perms/all-users-group)
+ (assoc collection/root-collection :namespace "data-actions"))
+ (is (contains? (dependent-ids) action-id))
+ (is (contains? (unreferenced-ids) action-id))))))))))
+
+(deftest ^:synchronized unreferenced-root-data-action-location-test
+ (testing "GET /api/ee/dependencies/graph/unreferenced locates a data action at the data-actions root in that root"
+ (mt/with-premium-features #{:dependencies}
+ (mt/with-temp [:model/Action {action-id :id} {:type :query :name "Root data action locationtest"}
+ :model/QueryAction _ {:action_id action-id
+ :database_id (mt/id)
+ :dataset_query (delete-venue-query)}]
+ (mt/with-model-cleanup [:model/Dependency :model/DependencyStatus]
+ (deps.test/synchronously-run-backfill!)
+ (let [unreferenced (fn [query]
+ (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph/unreferenced"
+ :types "action"
+ :query query))
+ matches? (fn [query]
+ (contains? (into #{} (map :id) (:data (unreferenced query))) action-id))]
+ (testing "the response names the data-actions root"
+ (is (=? {:data [{:id action-id
+ :data {:collection {:name "Data actions" :namespace "data-actions"}}}]}
+ (unreferenced "locationtest"))))
+ (testing "a search for the data-actions root name finds the action"
+ (is (matches? "Data actions"))
+ (is (not (matches? "Our analytics"))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
index 1d0e68a3f3a..9402ccaf1ce 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.test :refer [deftest is testing]]
[metabase-enterprise.dependencies.calculation :as calculation]
+ [metabase.actions.core :as actions]
[metabase.documents.prose-mirror :as prose-mirror]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
@@ -682,3 +683,35 @@
{:dashcards [{:visualization_settings
{:click_behavior {:linkType "question" :targetId 7777}}}]})]
(is (= #{7777} (:card deps))))))
+
+(deftest upstream-deps-query-action-test
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Action {action-id :id} {:type :query, :name "Move check-ins"}
+ :model/QueryAction _ {:action_id action-id
+ :database_id (mt/id)
+ :dataset_query (-> (lib/native-query mp (str "UPDATE checkins SET user_id = {{user}} "
+ "WHERE venue_id IN (SELECT id FROM {{#" card-id "}})"))
+ (lib/with-template-tags
+ {"user" {:id "user-tag"
+ :type :number
+ :name "user"
+ :display-name "User"
+ :required true}
+ (str "#" card-id) {:id "card-tag"
+ :type :card
+ :name (str "#" card-id)
+ :display-name "Venues"
+ :card-id card-id}}))}]
+ (is (= {:card #{card-id}
+ :table #{(mt/id :checkins) (mt/id :venues)}}
+ (calculation/calculate-deps :action (actions/select-action :id action-id)))))))
+
+(deftest upstream-deps-implicit-action-test
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card {model-id :id} {:type :model
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Action {action-id :id} {:type :implicit, :name "Create venue", :model_id model-id}
+ :model/ImplicitAction _ {:action_id action-id, :kind "row/create"}]
+ (is (= {:card #{model-id}}
+ (calculation/calculate-deps :action (actions/select-action :id action-id)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj
index 275b10a7b9e..776153a69df 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj
@@ -186,6 +186,18 @@
(is (= {} (dependencies/errors-from-proposed-edits {:card [card']}
:base-provider provider
:graph graph))))))))
+(deftest ^:parallel model-edit-with-action-dependent-test
+ (testing "editing a card that an action depends on doesn't throw"
+ (let [{:keys [provider mbql-base]} (testbed)
+ graph (graph/in-memory {[:card 101] #{[:action 900]}})
+ card' (-> mbql-base
+ (update :dataset-query lib/filter (lib/> (lib.metadata/field (mt/metadata-provider) (mt/id :orders :quantity))
+ 100))
+ (dissoc :result-metadata))]
+ (is (= {} (dependencies/errors-from-proposed-edits {:card [card']}
+ :base-provider provider
+ :graph graph))))))
+
(deftest ^:parallel sql-snippet->card->transform->cards-test
(testing "changing a snippet correctly finds downstream errors when asked"
(let [{:keys [provider graph snippet-inner]
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
index 57006cb47d4..353dd9f2436 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
@@ -582,6 +582,89 @@
(deps.test/synchronously-run-backfill!)
(is (empty? (t2/select :model/Dependency :from_entity_id measure-id :from_entity_type :measure))))))))))
+(deftest action-update-sets-correct-dependencies
+ (run-with-dependencies-setup!
+ (fn [mp]
+ (let [action-deps (fn [action-id]
+ (t2/select-fn-set (juxt :to_entity_type :to_entity_id)
+ :model/Dependency :from_entity_type :action :from_entity_id action-id))
+ sql-query #(lib/native-query mp (str "DELETE FROM " % " WHERE id = 1"))]
+ (mt/with-temp [:model/Action {action-id :id} {:type :query, :name "Delete row"}
+ :model/QueryAction _ {:action_id action-id
+ :database_id (mt/id)
+ :dataset_query (sql-query "venues")}]
+ (testing "creating an action creates dependencies on the tables its query reads"
+ (assert-stale :action action-id)
+ (deps.test/synchronously-run-backfill!)
+ (is (= #{[:table (mt/id :venues)]}
+ (action-deps action-id))))
+ (testing "updating an action's query recalculates its dependencies"
+ (t2/update! :model/QueryAction action-id {:dataset_query (sql-query "checkins")})
+ (assert-stale :action action-id)
+ (deps.test/synchronously-run-backfill!)
+ (is (= #{[:table (mt/id :checkins)]}
+ (action-deps action-id))))
+ (testing "deleting an action removes its dependencies and status"
+ (t2/delete! :model/Action action-id)
+ (deps.test/synchronously-run-backfill!)
+ (is (empty? (action-deps action-id)))
+ (is (not (t2/exists? :model/DependencyStatus :entity_type :action :entity_id action-id)))))))))
+
+(defn- action-dependency-rows
+ "The Dependency and DependencyStatus rows of the actions with `action-ids`."
+ [action-ids]
+ {:dependencies (set (t2/select-fn-set :from_entity_id :model/Dependency
+ :from_entity_type :action :from_entity_id [:in action-ids]))
+ :statuses (set (t2/select-fn-set :entity_id :model/DependencyStatus
+ :entity_type :action :entity_id [:in action-ids]))})
+
+(deftest model-delete-removes-dependency-rows-of-its-actions-test
+ (run-with-dependencies-setup!
+ (fn [mp]
+ (mt/with-temp [:model/Card {model-id :id} {:type :model
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Action {implicit-id :id} {:type :implicit, :name "Create venue", :model_id model-id}
+ :model/ImplicitAction _ {:action_id implicit-id, :kind "row/create"}
+ :model/Action {query-id :id} {:type :query, :name "Delete venue", :model_id model-id}
+ :model/QueryAction _ {:action_id query-id
+ :database_id (mt/id)
+ :dataset_query (lib/native-query mp "DELETE FROM venues WHERE id = 1")}]
+ (deps.test/synchronously-run-backfill!)
+ (testing "the model's actions have dependency rows"
+ (is (= {:dependencies #{implicit-id query-id}, :statuses #{implicit-id query-id}}
+ (action-dependency-rows [implicit-id query-id]))))
+ (testing "deleting the model removes the dependency rows of its actions"
+ (t2/delete! :model/Card model-id)
+ (deps.test/synchronously-run-backfill!)
+ (is (= {:dependencies #{}, :statuses #{}}
+ (action-dependency-rows [implicit-id query-id]))))))))
+
+(deftest database-delete-removes-dependency-rows-of-its-models-actions-test
+ (run-with-dependencies-setup!
+ (fn [_mp]
+ (mt/with-temp [:model/Database {db-id :id} {:engine :h2, :details (:details (mt/db))}
+ :model/Table {table-id :id} {:db_id db-id, :name "VENUES", :schema "PUBLIC"}]
+ (let [db-mp (lib-be/application-database-metadata-provider db-id)]
+ (mt/with-temp [:model/Card {model-id :id} {:type :model
+ :database_id db-id
+ :dataset_query (lib/native-query db-mp "SELECT * FROM venues")}
+ :model/Action {implicit-id :id} {:type :implicit, :name "Create venue", :model_id model-id}
+ :model/ImplicitAction _ {:action_id implicit-id, :kind "row/create"}
+ :model/Action {query-id :id} {:type :query, :name "Delete venue", :model_id model-id}
+ :model/QueryAction _ {:action_id query-id
+ :database_id db-id
+ :dataset_query (lib/native-query db-mp "DELETE FROM venues WHERE id = 1")}]
+ (deps.test/synchronously-run-backfill!)
+ (testing "the actions of the database's model have status rows"
+ (is (= #{implicit-id query-id}
+ (:statuses (action-dependency-rows [implicit-id query-id])))))
+ (testing "deleting the database removes the dependency rows of the actions of its models"
+ (t2/delete! :model/Database db-id)
+ (deps.test/synchronously-run-backfill!)
+ (is (= {:dependencies #{}, :statuses #{}}
+ (action-dependency-rows [implicit-id query-id]))))
+ (is (some? table-id))))))))
+
(deftest measure-with-measure-dependencies
(run-with-dependencies-setup!
(fn [mp]
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index 50a6850f93c..536f2470a26 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -10,6 +10,7 @@ import {
provideUserTags,
} from "metabase/api/tags";
import {
+ type ActionDependencyNode,
type CardDependencyNode,
DEPENDENCY_TYPES,
type DashboardDependencyNode,
@@ -193,6 +194,18 @@ function provideMeasureDependencyNodeTags(
];
}
+function provideActionDependencyNodeTags(
+ node: ActionDependencyNode,
+): TagDescription<EnterpriseTagType>[] {
+ return [
+ idTag("action", node.id),
+ ...(node.data.creator != null ? provideUserTags(node.data.creator) : []),
+ ...(node.data.collection != null
+ ? provideCollectionTags(node.data.collection)
+ : []),
+ ];
+}
+
export function provideDependencyNodeTags(
node: DependencyNode,
): TagDescription<EnterpriseTagType>[] {
@@ -215,6 +228,8 @@ export function provideDependencyNodeTags(
return provideSegmentDependencyNodeTags(node);
case "measure":
return provideMeasureDependencyNodeTags(node);
+ case "action":
+ return provideActionDependencyNodeTags(node);
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts
index 505678720b6..11ad1e64329 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts
@@ -24,7 +24,7 @@ export function getHeaderLabel(
case "transform":
return t`Transforms that use ${nodeLabel}`;
case "snippet":
- return t`Snippets that use ${nodeLabel}`;
+ return t`SQL snippets that use ${nodeLabel}`;
case "dashboard":
return t`Dashboards that use ${nodeLabel}`;
case "document":
@@ -35,5 +35,7 @@ export function getHeaderLabel(
return t`Segments that use ${nodeLabel}`;
case "measure":
return t`Measures that use ${nodeLabel}`;
+ case "action":
+ return t`Data actions that use ${nodeLabel}`;
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.ts
index 2f46f50fa0e..4343820c787 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/constants.ts
@@ -29,4 +29,6 @@ export const ENTRY_PICKER_MODELS: EntityPickerProps["models"] = [
"metric",
"dashboard",
"transform",
+ "snippet",
+ "action",
];
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.ts
index 83f40ceff56..c7132bbc866 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.ts
@@ -1,5 +1,6 @@
import type {
OmniPickerCollectionItem,
+ OmniPickerCollectionItemValue,
OmniPickerItem,
OmniPickerQuestionItem,
OmniPickerTableItem,
@@ -13,7 +14,7 @@ import type {
SearchModel,
} from "metabase-types/api";
-import { getDependencyType } from "../../../../utils";
+import { getDependencyType, isDataStudioAction } from "../../../../utils";
import { SEARCH_MODEL_TO_GROUP_TYPE } from "../constants";
export function getTablePickerItem(
@@ -99,6 +100,28 @@ export function getDashboardPickerItem(
return { id: node.id, model: "dashboard", name: node.data.name };
}
+export function getSnippetPickerItem(
+ node: DependencyNode,
+): OmniPickerCollectionItemValue | undefined {
+ if (node.type !== "snippet") {
+ return;
+ }
+ return { id: node.id, model: "snippet", namespace: "snippets" };
+}
+
+export function getActionPickerItem(
+ node: DependencyNode,
+): OmniPickerCollectionItemValue | undefined {
+ if (node.type !== "action") {
+ return;
+ }
+ return {
+ id: node.id,
+ model: "action",
+ namespace: isDataStudioAction(node.data) ? "data-actions" : null,
+ };
+}
+
export function getEntryPickerItem(
node: DependencyNode,
): OmniPickerValue | undefined {
@@ -108,7 +131,9 @@ export function getEntryPickerItem(
getQuestionPickerItem(node) ??
getModelPickerItem(node) ??
getMetricPickerItem(node) ??
- getDashboardPickerItem(node)
+ getDashboardPickerItem(node) ??
+ getSnippetPickerItem(node) ??
+ getActionPickerItem(node)
);
}
@@ -123,6 +148,10 @@ export function getEntryPickerValue(
return;
}
+ if (item.model === "snippet" || item.model === "action") {
+ return { id: item.id, type: item.model };
+ }
+
// Unjustified type cast. FIXME
const groupType = SEARCH_MODEL_TO_GROUP_TYPE[item.model as SearchModel];
if (groupType != null) {
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.unit.spec.ts
new file mode 100644
index 00000000000..4ca78063210
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntryPickerModal/utils.unit.spec.ts
@@ -0,0 +1,65 @@
+import type { OmniPickerItem } from "metabase/common/components/Pickers";
+import {
+ createMockActionDependencyNode,
+ createMockActionDependencyNodeData,
+ createMockCollection,
+ createMockSnippetDependencyNode,
+} from "metabase-types/api/mocks";
+
+import { getEntryPickerItem, getEntryPickerValue } from "./utils";
+
+describe("getEntryPickerItem", () => {
+ it("should select a snippet in the snippets namespace", () => {
+ expect(
+ getEntryPickerItem(createMockSnippetDependencyNode({ id: 3 })),
+ ).toEqual({ id: 3, model: "snippet", namespace: "snippets" });
+ });
+
+ it("should select an action without a model in the data actions namespace", () => {
+ const node = createMockActionDependencyNode({
+ id: 4,
+ data: createMockActionDependencyNodeData({ model_id: null }),
+ });
+ expect(getEntryPickerItem(node)).toEqual({
+ id: 4,
+ model: "action",
+ namespace: "data-actions",
+ });
+ });
+
+ it("should select an action without a model in a regular collection in the regular namespace", () => {
+ const node = createMockActionDependencyNode({
+ id: 6,
+ data: createMockActionDependencyNodeData({
+ model_id: null,
+ collection: createMockCollection({ id: 7, namespace: null }),
+ }),
+ });
+ expect(getEntryPickerItem(node)).toEqual({
+ id: 6,
+ model: "action",
+ namespace: null,
+ });
+ });
+
+ it("should select an action of a model in the regular namespace", () => {
+ const node = createMockActionDependencyNode({
+ id: 5,
+ data: createMockActionDependencyNodeData({ model_id: 2 }),
+ });
+ expect(getEntryPickerItem(node)).toEqual({
+ id: 5,
+ model: "action",
+ namespace: null,
+ });
+ });
+});
+
+describe("getEntryPickerValue", () => {
+ it.each<{ item: OmniPickerItem; type: string }>([
+ { item: { id: 3, model: "snippet", name: "Snippet" }, type: "snippet" },
+ { item: { id: 4, model: "action", name: "Action" }, type: "action" },
+ ])("should open the graph for a picked $type", ({ item, type }) => {
+ expect(getEntryPickerValue(item)).toEqual({ id: item.id, type });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.tsx b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.tsx
index fa0d998266f..308592c785a 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.tsx
@@ -18,6 +18,8 @@ import {
getNodeLastEditedAt,
getNodeLastEditedBy,
getNodeOwner,
+ getNodeParameters,
+ getParameterIcon,
} from "../../../../utils";
import { GraphBreadcrumbs } from "../../GraphBreadcrumbs";
import { GraphExternalLink } from "../../GraphExternalLink";
@@ -37,6 +39,7 @@ export function PanelBody({ node, getGraphUrl }: PanelBodyProps) {
<DescriptionSection node={node} />
<OwnerSection node={node} />
<CreatorAndLastEditorSection node={node} />
+ <ParametersSection node={node} />
<TableSection node={node} getGraphUrl={getGraphUrl} />
<FieldsSection node={node} />
</Stack>
@@ -105,6 +108,37 @@ function CreatorAndLastEditorSection({ node }: SectionProps) {
);
}
+function ParametersSection({ node }: SectionProps) {
+ const parameters = getNodeParameters(node);
+ if (parameters == null) {
+ return null;
+ }
+
+ return (
+ <Stack gap="lg" lh="1rem">
+ <Title order={6}>{t`Parameters`}</Title>
+ {parameters.length > 0 ? (
+ parameters.map((parameter) => (
+ <Group
+ className={CS.textWrap}
+ key={parameter.id}
+ gap="sm"
+ wrap="nowrap"
+ >
+ <FixedSizeIcon
+ name={getParameterIcon(parameter)}
+ c="text-secondary"
+ />
+ {parameter.name}
+ </Group>
+ ))
+ ) : (
+ <Text lh="h4" c="text-secondary">{t`No parameters`}</Text>
+ )}
+ </Stack>
+ );
+}
+
type TableSectionProps = {
node: DependencyNode;
getGraphUrl: (entry: DependencyEntry) => string;
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.unit.spec.tsx
index 5128c7be947..5c65d5dedf5 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/PanelBody.unit.spec.tsx
@@ -3,6 +3,9 @@ import { Route } from "metabase/router";
import * as Urls from "metabase/urls";
import type { DependencyEntry, DependencyNode } from "metabase-types/api";
import {
+ createMockActionDependencyNode,
+ createMockActionDependencyNodeData,
+ createMockActionParameter,
createMockCardDependencyNode,
createMockCardDependencyNodeData,
createMockLastEditInfo,
@@ -154,4 +157,43 @@ describe("PanelBody", () => {
/Carol White/,
);
});
+
+ it("should display the parameters of an action", () => {
+ setup({
+ node: createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({
+ parameters: [
+ createMockActionParameter({
+ id: "price",
+ name: "Price",
+ type: "number/=",
+ }),
+ createMockActionParameter({
+ id: "day",
+ name: "Day",
+ type: "date/single",
+ }),
+ ],
+ }),
+ }),
+ });
+ expect(screen.getByText("Parameters")).toBeInTheDocument();
+ expect(screen.getByText("Price")).toBeInTheDocument();
+ expect(screen.getByText("Day")).toBeInTheDocument();
+ expect(screen.queryByText("No parameters")).not.toBeInTheDocument();
+ });
+
+ it("should display 'No parameters' for an action without parameters", () => {
+ setup({
+ node: createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({ parameters: [] }),
+ }),
+ });
+ expect(screen.getByText("No parameters")).toBeInTheDocument();
+ });
+
+ it("should not display parameters section for cards", () => {
+ setup({ node: createMockCardDependencyNode() });
+ expect(screen.queryByText("Parameters")).not.toBeInTheDocument();
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts
index 3424562a4ce..e60b79cd92c 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts
@@ -17,6 +17,7 @@ export function getDependentGroups(node: DependencyNode): DependentGroup[] {
sandbox = 0,
segment = 0,
measure = 0,
+ action = 0,
} = node.dependents_count ?? {};
const groups: DependentGroup[] = [
@@ -31,6 +32,7 @@ export function getDependentGroups(node: DependencyNode): DependentGroup[] {
{ type: "sandbox", count: sandbox },
{ type: "segment", count: segment },
{ type: "measure", count: measure },
+ { type: "action", count: action },
];
return groups.filter(({ count }) => count !== 0);
@@ -68,7 +70,11 @@ export function getDependentGroupLabel({
case "transform":
return ngettext(msgid`${count} transform`, `${count} transforms`, count);
case "snippet":
- return ngettext(msgid`${count} snippet`, `${count} snippet`, count);
+ return ngettext(
+ msgid`${count} SQL snippet`,
+ `${count} SQL snippets`,
+ count,
+ );
case "dashboard":
return ngettext(msgid`${count} dashboard`, `${count} dashboards`, count);
case "document":
@@ -91,5 +97,11 @@ export function getDependentGroupLabel({
`${count} measures`,
count,
);
+ case "action":
+ return c("{0} is the number of data actions").ngettext(
+ msgid`${count} data action`,
+ `${count} data actions`,
+ count,
+ );
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/utils.ts
index 36a32b9e7ac..eb352808ec1 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/utils.ts
@@ -1,12 +1,19 @@
import { c, msgid, ngettext, t } from "ttag";
+import {
+ getCollectionPathAsArray,
+ isRootCollection,
+} from "metabase/common/collections/utils";
import * as Urls from "metabase/urls";
import type { NamedUser } from "metabase/utils/user";
import { visualizations } from "metabase/viz-core";
+import { getParameterType } from "metabase-lib/v1/parameters/utils/parameter-type";
import type {
+ ActionDependencyNodeData,
AnalysisFindingError,
AnalysisFindingErrorType,
CardType,
+ Collection,
DependencyEntry,
DependencyGroupType,
DependencyId,
@@ -14,6 +21,7 @@ import type {
DependencyType,
Field,
IconName,
+ Parameter,
SourceReplacementEntry,
Transform,
VisualizationDisplay,
@@ -114,6 +122,8 @@ export function getNodeIconWithType(
return "segment";
case "measure":
return "ruler";
+ case "action":
+ return "bolt";
}
}
@@ -203,9 +213,13 @@ export function getNodeLink(node: DependencyNode): NodeLink | null {
return null;
case "snippet":
return {
- label: t`View this snippet`,
+ label: t`View this SQL snippet`,
url: Urls.dataStudioSnippet(node.id),
};
+ case "action":
+ return node.data.model_id == null
+ ? { label: t`View this action`, url: Urls.dataStudioAction(node.id) }
+ : null;
}
}
@@ -331,12 +345,50 @@ export function getNodeLocationInfo(
};
}
return null;
+ case "action":
+ return isDataStudioAction(node.data)
+ ? getDataActionLocationInfo(node.data.collection)
+ : null;
case "transform":
case "sandbox":
return null;
}
}
+export function isDataStudioAction({
+ model_id,
+ collection,
+}: Pick<ActionDependencyNodeData, "model_id" | "collection">): boolean {
+ return (
+ model_id == null &&
+ (collection == null ||
+ isRootCollection(collection) ||
+ collection.namespace === "data-actions")
+ );
+}
+
+function getDataActionLocationInfo(
+ collection: Collection | null | undefined,
+): NodeLocationInfo {
+ if (collection != null && !isRootCollection(collection)) {
+ return {
+ icon: "collection",
+ links: [
+ {
+ label: collection.name,
+ url: Urls.dataStudioActions({
+ expandedIds: getCollectionPathAsArray(collection),
+ }),
+ },
+ ],
+ };
+ }
+ return {
+ icon: "collection",
+ links: [{ label: t`Data actions`, url: Urls.dataStudioActions() }],
+ };
+}
+
export function getNodeOwner(node: DependencyNode): NamedUser | null {
switch (node.type) {
case "table":
@@ -366,6 +418,7 @@ export function getNodeCreatedAt(node: DependencyNode): string | null {
case "measure":
case "snippet":
case "transform":
+ case "action":
return node.data.created_at;
default:
return null;
@@ -381,6 +434,7 @@ export function getNodeCreatedBy(node: DependencyNode): NamedUser | null {
case "measure":
case "snippet":
case "transform":
+ case "action":
return node.data.creator ?? null;
default:
return null;
@@ -454,12 +508,37 @@ export function getNodeFields(node: DependencyNode): Field[] | null {
case "document":
case "segment":
case "measure":
+ case "action":
return null;
default:
return null;
}
}
+export function getNodeParameters(node: DependencyNode): Parameter[] | null {
+ return node.type === "action" && node.data.model_id == null
+ ? (node.data.parameters ?? [])
+ : null;
+}
+
+export function getParameterIcon(parameter: Parameter): IconName {
+ switch (getParameterType(parameter)) {
+ case "id":
+ return "label";
+ case "number":
+ return "int";
+ case "date":
+ case "temporal-unit":
+ return "calendar";
+ case "boolean":
+ return "io";
+ case "location":
+ return "location";
+ default:
+ return "string";
+ }
+}
+
export function getNodeFieldsLabel(fieldCount = 0) {
return fieldCount === 1 ? t`Field` : t`Fields`;
}
@@ -534,6 +613,8 @@ export function getDependencyGroupType(
return "measure";
case "snippet":
return "snippet";
+ case "action":
+ return "action";
}
}
@@ -552,7 +633,7 @@ export function getDependencyGroupTypeInfo(
case "transform":
return { label: t`Transform`, color: "feedback-warning" };
case "snippet":
- return { label: t`Snippet`, color: "text-secondary" };
+ return { label: t`SQL snippet`, color: "text-secondary" };
case "dashboard":
return { label: t`Dashboard`, color: "core-filter" };
case "document":
@@ -566,6 +647,8 @@ export function getDependencyGroupTypeInfo(
return { label: t`Segment`, color: "accent2" };
case "measure":
return { label: t`Measure`, color: "core-summarize" };
+ case "action":
+ return { label: t`Data action`, color: "text-secondary" };
}
}
@@ -617,6 +700,7 @@ export function getDependentGroups(node: DependencyNode): DependentGroup[] {
sandbox = 0,
segment = 0,
measure = 0,
+ action = 0,
} = node.dependents_count ?? {};
const groups: DependentGroup[] = [
@@ -631,6 +715,7 @@ export function getDependentGroups(node: DependencyNode): DependentGroup[] {
{ type: "sandbox", count: sandbox },
{ type: "segment", count: segment },
{ type: "measure", count: measure },
+ { type: "action", count: action },
];
return groups.filter(({ count }) => count !== 0);
@@ -678,7 +763,11 @@ export function getDependentGroupLabel({
case "transform":
return ngettext(msgid`${count} transform`, `${count} transforms`, count);
case "snippet":
- return ngettext(msgid`${count} snippet`, `${count} snippet`, count);
+ return ngettext(
+ msgid`${count} SQL snippet`,
+ `${count} SQL snippets`,
+ count,
+ );
case "dashboard":
return ngettext(msgid`${count} dashboard`, `${count} dashboards`, count);
case "document":
@@ -701,6 +790,12 @@ export function getDependentGroupLabel({
`${count} measures`,
count,
);
+ case "action":
+ return c("{0} is the number of data actions").ngettext(
+ msgid`${count} data action`,
+ `${count} data actions`,
+ count,
+ );
default:
return ngettext(msgid`${count} entity`, `${count} entities`, count);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/utils.unit.spec.ts
index 38268a11430..3001d102282 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/utils.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/utils.unit.spec.ts
@@ -9,6 +9,9 @@ import type {
IconName,
} from "metabase-types/api";
import {
+ createMockActionDependencyNode,
+ createMockActionDependencyNodeData,
+ createMockActionParameter,
createMockAnalysisFindingError,
createMockCardDependencyNode,
createMockCardDependencyNodeData,
@@ -19,6 +22,7 @@ import {
createMockDocumentDependencyNode,
createMockDocumentDependencyNodeData,
createMockMeasureDependencyNode,
+ createMockParameter,
createMockSandboxDependencyNode,
createMockSegmentDependencyNode,
createMockSegmentDependencyNodeData,
@@ -66,9 +70,11 @@ import {
getNodeLastEditedBy,
getNodeLink,
getNodeLocationInfo,
+ getNodeParameters,
getNodeSourceReplacementEntry,
getNodeTypeInfo,
getNodeViewCount,
+ getParameterIcon,
getSearchQuery,
isSameNode,
} from "./utils";
@@ -130,6 +136,10 @@ describe("getNodeIcon", () => {
node: createMockSnippetDependencyNode(),
expectedIcon: "snippet",
},
+ {
+ node: createMockActionDependencyNode(),
+ expectedIcon: "bolt",
+ },
])("should get the $node.type node icon", ({ node, expectedIcon }) => {
expect(getNodeIcon(node)).toBe(expectedIcon);
});
@@ -207,9 +217,26 @@ describe("getNodeLink", () => {
url: "/data-studio/data/database/1/schema/1:public/table/1/segments/1",
},
},
+ {
+ node: createMockActionDependencyNode({
+ id: 1,
+ data: createMockActionDependencyNodeData({ model_id: null }),
+ }),
+ expectedLink: {
+ label: "View this action",
+ url: "/data-studio/actions/1",
+ },
+ },
])("should get the $node.type node link", ({ node, expectedLink }) => {
expect(getNodeLink(node)).toEqual(expectedLink);
});
+
+ it("should not link an action of a model", () => {
+ const node = createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({ model_id: 2 }),
+ });
+ expect(getNodeLink(node)).toBeNull();
+ });
});
describe("getNodeTypeInfo", () => {
@@ -257,7 +284,7 @@ describe("getNodeTypeInfo", () => {
},
{
node: createMockSnippetDependencyNode(),
- expectedTypeInfo: { label: "Snippet", color: "text-secondary" },
+ expectedTypeInfo: { label: "SQL snippet", color: "text-secondary" },
},
])(
"should get the $node.type node type info",
@@ -364,6 +391,44 @@ describe("getNodeDescription", () => {
});
});
+describe("getNodeParameters", () => {
+ it("should return the parameters of a data action", () => {
+ const parameter = createMockActionParameter();
+ const node = createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({
+ model_id: null,
+ parameters: [parameter],
+ }),
+ });
+ expect(getNodeParameters(node)).toEqual([parameter]);
+ });
+
+ it("should return null for an action of a model, whose parameters come from the model", () => {
+ const node = createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({
+ model_id: 2,
+ type: "implicit",
+ parameters: [],
+ }),
+ });
+ expect(getNodeParameters(node)).toBeNull();
+ });
+});
+
+describe("getParameterIcon", () => {
+ it.each<{ type: string; expected: IconName }>([
+ { type: "id", expected: "label" },
+ { type: "number/=", expected: "int" },
+ { type: "date/single", expected: "calendar" },
+ { type: "boolean/=", expected: "io" },
+ { type: "string/=", expected: "string" },
+ { type: "category", expected: "string" },
+ { type: "unknown/type", expected: "string" },
+ ])("should map $type to $expected", ({ type, expected }) => {
+ expect(getParameterIcon(createMockParameter({ type }))).toBe(expected);
+ });
+});
+
describe("getNodeLocationInfo", () => {
it("should return dashboard location for card in dashboard", () => {
const node = createMockCardDependencyNode({
@@ -427,6 +492,75 @@ describe("getNodeLocationInfo", () => {
expect(result?.links[1].label).toBe("public");
});
+ it("should link an action in a data actions folder to that folder in Data Studio", () => {
+ const node = createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({
+ collection: createMockCollection({
+ id: 7,
+ name: "My Folder",
+ namespace: "data-actions",
+ location: "/5/",
+ }),
+ }),
+ });
+ expect(getNodeLocationInfo(node)).toEqual({
+ icon: "collection",
+ links: [
+ {
+ label: "My Folder",
+ url: "/data-studio/actions?expandedId=5&expandedId=7",
+ },
+ ],
+ });
+ });
+
+ it.each([
+ { name: "without a collection", collection: null },
+ {
+ name: "in the data actions root",
+ collection: createMockCollection({
+ id: "root",
+ name: "Data actions",
+ namespace: "data-actions",
+ location: undefined,
+ }),
+ },
+ ])(
+ "should link an action $name to the Data Studio actions root",
+ ({ collection }) => {
+ const node = createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({ collection }),
+ });
+ expect(getNodeLocationInfo(node)).toEqual({
+ icon: "collection",
+ links: [{ label: "Data actions", url: "/data-studio/actions" }],
+ });
+ },
+ );
+
+ it("should return null for an action of a model", () => {
+ const node = createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({
+ model_id: 2,
+ collection: createMockCollection({ name: "My Collection" }),
+ }),
+ });
+ expect(getNodeLocationInfo(node)).toBeNull();
+ });
+
+ it("should not link an action in a data app collection to the Data Studio actions root", () => {
+ const node = createMockActionDependencyNode({
+ data: createMockActionDependencyNodeData({
+ collection: createMockCollection({
+ id: 9,
+ name: "App collection",
+ namespace: "data-apps",
+ }),
+ }),
+ });
+ expect(getNodeLocationInfo(node)).toBeNull();
+ });
+
it("should return null for sandbox", () => {
const node = createMockSandboxDependencyNode();
expect(getNodeLocationInfo(node)).toBeNull();
@@ -633,6 +767,10 @@ describe("getDependencyGroupType", () => {
node: createMockMeasureDependencyNode(),
expected: "measure",
},
+ {
+ node: createMockActionDependencyNode(),
+ expected: "action",
+ },
])("should get group type for $node.type", ({ node, expected }) => {
expect(getDependencyGroupType(node)).toBe(expected);
});
@@ -648,6 +786,10 @@ describe("getDependencyGroupTypeInfo", () => {
expected: { label: "Question", color: "text-secondary" },
},
{ groupType: "model", expected: { label: "Model", color: "core-brand" } },
+ {
+ groupType: "action",
+ expected: { label: "Data action", color: "text-secondary" },
+ },
{
groupType: "metric",
expected: { label: "Metric", color: "core-summarize" },
diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
index e7491951919..93672fff1ac 100644
--- a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
@@ -18,6 +18,7 @@ import type {
TestBreakoutSpec,
TestColumnSpec,
TestExpressionSpec,
+ TestOperatorArgSpec,
TestQuerySpec,
TestStageSpec,
TestStageWithSourceSpec,
@@ -239,12 +240,24 @@ function toResultColumnExpressionSpec(
}
if (spec.type === "operator") {
- return { ...spec, args: spec.args?.map(toResultColumnExpressionSpec) };
+ return { ...spec, args: spec.args?.map(toResultColumnArgSpec) };
}
return spec;
}
+function toResultColumnArgSpec(spec: TestOperatorArgSpec): TestOperatorArgSpec {
+ if (
+ spec.type === "segment" ||
+ spec.type === "measure" ||
+ spec.type === "metric"
+ ) {
+ return spec;
+ }
+
+ return toResultColumnExpressionSpec(spec);
+}
+
async function loadSourceMetadata(
store: SdkStore,
input: QueryInput,
diff --git a/frontend/src/metabase-types/api/dependencies.ts b/frontend/src/metabase-types/api/dependencies.ts
index b57c91c357d..16bc15365f4 100644
--- a/frontend/src/metabase-types/api/dependencies.ts
+++ b/frontend/src/metabase-types/api/dependencies.ts
@@ -3,7 +3,9 @@
// enterprise/backend/src/metabase_enterprise/dependencies/api.clj
// (See entity-select-fields map)
+import type { WritebackActionBase, WritebackActionType } from "./actions";
import type { Card, CardType } from "./card";
+import type { Collection } from "./collection";
import type { Dashboard } from "./dashboard";
import type { Document } from "./document";
import type { Measure } from "./measure";
@@ -26,6 +28,7 @@ export const DEPENDENCY_TYPES = [
"sandbox",
"segment",
"measure",
+ "action",
] as const;
export type DependencyType = (typeof DEPENDENCY_TYPES)[number];
@@ -41,6 +44,7 @@ export const DEPENDENCY_GROUP_TYPES = [
"sandbox",
"segment",
"measure",
+ "action",
] as const;
export type DependencyGroupType = (typeof DEPENDENCY_GROUP_TYPES)[number];
@@ -197,6 +201,26 @@ export type MeasureDependencyNode = BaseDependencyNode<
MeasureDependencyNodeData
>;
+export type ActionDependencyNodeData = Pick<
+ WritebackActionBase,
+ | "name"
+ | "description"
+ | "model_id"
+ | "parameters"
+ | "created_at"
+ | "creator_id"
+ | "creator"
+ | "collection_id"
+> & {
+ type: WritebackActionType;
+ collection?: Collection | null;
+};
+
+export type ActionDependencyNode = BaseDependencyNode<
+ "action",
+ ActionDependencyNodeData
+>;
+
export type DependencyNode =
| TableDependencyNode
| TransformDependencyNode
@@ -206,7 +230,8 @@ export type DependencyNode =
| DocumentDependencyNode
| SandboxDependencyNode
| SegmentDependencyNode
- | MeasureDependencyNode;
+ | MeasureDependencyNode
+ | ActionDependencyNode;
export type AnalysisFindingErrorId = number;
diff --git a/frontend/src/metabase-types/api/mocks/dependencies.ts b/frontend/src/metabase-types/api/mocks/dependencies.ts
index 639ed8b9660..48b90194345 100644
--- a/frontend/src/metabase-types/api/mocks/dependencies.ts
+++ b/frontend/src/metabase-types/api/mocks/dependencies.ts
@@ -1,4 +1,6 @@
import type {
+ ActionDependencyNode,
+ ActionDependencyNodeData,
AnalysisFindingError,
CardDependencyNode,
CardDependencyNodeData,
@@ -27,6 +29,8 @@ import type {
TransformDependencyNodeData,
} from "metabase-types/api";
+import { createMockUserInfo } from "./user";
+
export function createMockDependencyEntry(
opts?: Partial<DependencyEntry>,
): DependencyEntry {
@@ -295,6 +299,34 @@ export function createMockMeasureDependencyNode(
};
}
+export function createMockActionDependencyNodeData(
+ opts?: Partial<ActionDependencyNodeData>,
+): ActionDependencyNodeData {
+ return {
+ name: "Action",
+ description: null,
+ type: "query",
+ model_id: null,
+ created_at: "2020-01-01T00:00:00Z",
+ creator_id: 1,
+ creator: createMockUserInfo(),
+ collection_id: null,
+ ...opts,
+ };
+}
+
+export function createMockActionDependencyNode(
+ opts?: Partial<ActionDependencyNode>,
+): ActionDependencyNode {
+ return {
+ id: 1,
+ type: "action",
+ data: createMockActionDependencyNodeData(),
+ dependents_count: {},
+ ...opts,
+ };
+}
+
export function createMockListBrokenGraphNodesRequest(
opts?: Partial<ListBreakingGraphNodesRequest>,
): ListBreakingGraphNodesRequest {
diff --git a/frontend/src/metabase-types/api/query.ts b/frontend/src/metabase-types/api/query.ts
index ac36b445479..02a98416558 100644
--- a/frontend/src/metabase-types/api/query.ts
+++ b/frontend/src/metabase-types/api/query.ts
@@ -496,6 +496,12 @@ export type TestMetricSpec = {
export type TestFilterSpec = TestExpressionSpec | TestSegmentSpec;
+export type TestOperatorArgSpec =
+ | TestExpressionSpec
+ | TestSegmentSpec
+ | TestMeasureSpec
+ | TestMetricSpec;
+
export type TestNamedAggregationSpec = {
name: string;
value: TestExpressionSpec | TestMeasureSpec | TestMetricSpec;
@@ -520,7 +526,7 @@ export type TestLiteralSpec = {
export type TestOperatorSpec = {
type: "operator";
operator: string;
- args?: readonly TestExpressionSpec[];
+ args?: readonly TestOperatorArgSpec[];
// For an aggregation: the name of its result column, which a later stage
// refers to.
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts
index 9d87aa98a73..3f410ce3345 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-path-from-value.ts
@@ -3,6 +3,7 @@ import { useDeepCompareEffect } from "react-use";
import { t } from "ttag";
import {
+ actionApi,
cardApi,
collectionApi,
dashboardApi,
@@ -604,6 +605,10 @@ function getItemByModel(value: OmniPickerValue, dispatch: DispatchFn) {
return dispatch(
transformApi.endpoints.getTransform.initiate(Number(value.id)),
).unwrap();
+ case "action":
+ return dispatch(
+ actionApi.endpoints.getAction.initiate({ id: Number(value.id) }),
+ ).unwrap();
default:
return Promise.resolve(null);
}
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-root-items.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-root-items.ts
index 9521e392362..d12c8192dd5 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-root-items.ts
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/hooks/use-get-root-items.ts
@@ -213,10 +213,10 @@ async function getRootItems({
});
}
- if (namespaces.includes("snippets")) {
+ if (namespaces.includes("transforms") && transformsEnabled) {
collectionItems.push({
...(await getRootCollectionItem({
- namespace: "snippets",
+ namespace: "transforms",
dispatch,
})),
here: ["collection"],
@@ -224,10 +224,10 @@ async function getRootItems({
});
}
- if (namespaces.includes("data-actions")) {
+ if (namespaces.includes("snippets")) {
collectionItems.push({
...(await getRootCollectionItem({
- namespace: "data-actions",
+ namespace: "snippets",
dispatch,
})),
here: ["collection"],
@@ -235,10 +235,10 @@ async function getRootItems({
});
}
- if (namespaces.includes("transforms") && transformsEnabled) {
+ if (namespaces.includes("data-actions")) {
collectionItems.push({
...(await getRootCollectionItem({
- namespace: "transforms",
+ namespace: "data-actions",
dispatch,
})),
here: ["collection"],
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.ts
index ce1d5ddf9ec..441c31867a4 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.ts
@@ -238,6 +238,7 @@ const namespaceMap: Record<string, CollectionNamespace[]> = {
normal: [null, "analytics", "shared-tenant-collection", "tenant-specific"],
snippet: ["snippets"],
transform: ["transforms"],
+ action: ["data-actions"],
};
export const getNamespacesFromModels = (
@@ -252,6 +253,10 @@ export const getNamespacesFromModels = (
modelNamespaces.push(...namespaceMap.transform);
}
+ if (models.includes("action")) {
+ modelNamespaces.push(...namespaceMap.action);
+ }
+
if (models.some((model) => model !== "snippet" && model !== "transform")) {
modelNamespaces.push(...namespaceMap.normal);
}
diff --git a/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.unit.spec.ts b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.unit.spec.ts
index 30c630b91a4..c8e783b5e75 100644
--- a/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.unit.spec.ts
+++ b/frontend/src/metabase/common/components/Pickers/EntityPicker/utils.unit.spec.ts
@@ -402,6 +402,12 @@ describe("EntityPicker utils", () => {
expect(getNamespacesFromModels(["transform"])).toContain("transforms");
});
+ it("should return data actions and normal namespaces if action model is present", () => {
+ const namespaces = getNamespacesFromModels(["action"]);
+ expect(namespaces).toContain("data-actions");
+ expect(namespaces).toContain(null);
+ });
+
it("should return normal namespaces for other models", () => {
const namespaces = getNamespacesFromModels(["card"]);
expect(namespaces).toContain(null);
diff --git a/frontend/src/metabase/common/components/Pickers/utils.ts b/frontend/src/metabase/common/components/Pickers/utils.ts
index d3db2c80166..b78ec64ae77 100644
--- a/frontend/src/metabase/common/components/Pickers/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/utils.ts
@@ -38,6 +38,7 @@ export const validCollectionModels = new Set<CollectionItemModel>([
"snippet",
"transform",
"measure",
+ "action",
]);
export const allCollectionModels = Array.from(validCollectionModels);
diff --git a/frontend/src/metabase/data-studio/actions/components/ActionHeader/ActionHeader.tsx b/frontend/src/metabase/data-studio/actions/components/ActionHeader/ActionHeader.tsx
index e0827a6ae8e..438c02e3067 100644
--- a/frontend/src/metabase/data-studio/actions/components/ActionHeader/ActionHeader.tsx
+++ b/frontend/src/metabase/data-studio/actions/components/ActionHeader/ActionHeader.tsx
@@ -15,6 +15,7 @@ import {
} from "metabase/common/data-studio/components/PaneHeader";
import { useCollectionPath } from "metabase/common/data-studio/hooks/use-collection-path/useCollectionPath";
import { useMetadataToasts } from "metabase/common/hooks";
+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
import type { StackProps } from "metabase/ui";
import * as Urls from "metabase/urls";
import type { WritebackAction, WritebackActionId } from "metabase-types/api";
@@ -114,6 +115,14 @@ function ActionTabs({ actionId }: ActionTabsProps) {
pathname.startsWith(Urls.dataStudioActionFields(actionId)),
},
{ label: t`Run`, to: Urls.dataStudioActionRun(actionId) },
+ ...(PLUGIN_DEPENDENCIES.isEnabled
+ ? [
+ {
+ label: t`Dependencies`,
+ to: Urls.dataStudioActionDependencies(actionId),
+ },
+ ]
+ : []),
{ label: t`Settings`, to: Urls.dataStudioActionSettings(actionId) },
];
return <PillTabNavigation tabs={tabs} />;
diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/ActionDependenciesPage.tsx b/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/ActionDependenciesPage.tsx
new file mode 100644
index 00000000000..4e0d3037391
--- /dev/null
+++ b/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/ActionDependenciesPage.tsx
@@ -0,0 +1,37 @@
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";
+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
+import { Outlet } from "metabase/router";
+import { Card, Center } from "metabase/ui";
+import * as Urls from "metabase/urls";
+
+import { ActionHeader } from "../../components/ActionHeader";
+import { useRouteAction } from "../../hooks/use-route-action";
+
+export function ActionDependenciesPage() {
+ const { action, isLoading, error } = useRouteAction();
+
+ if (isLoading || error != null || action == null) {
+ return (
+ <Center h="100%">
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ </Center>
+ );
+ }
+
+ return (
+ <PageContainer data-testid="action-dependencies">
+ <ActionHeader action={action} />
+ <PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider
+ value={{
+ baseUrl: Urls.dataStudioActionDependencies(action.id),
+ defaultEntry: { id: action.id, type: "action" },
+ }}
+ >
+ <Card p={0} withBorder flex={1}>
+ <Outlet />
+ </Card>
+ </PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider>
+ </PageContainer>
+ );
+}
diff --git a/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/index.ts b/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/index.ts
new file mode 100644
index 00000000000..5cc611d4e5e
--- /dev/null
+++ b/frontend/src/metabase/data-studio/actions/pages/ActionDependenciesPage/index.ts
@@ -0,0 +1 @@
+export { ActionDependenciesPage } from "./ActionDependenciesPage";
diff --git a/frontend/src/metabase/data-studio/actions/routes.tsx b/frontend/src/metabase/data-studio/actions/routes.tsx
index 8a835664e77..82e7c2cbc21 100644
--- a/frontend/src/metabase/data-studio/actions/routes.tsx
+++ b/frontend/src/metabase/data-studio/actions/routes.tsx
@@ -1,4 +1,5 @@
import { ActionsSectionLayout } from "metabase/data-studio/app/pages/ActionsSectionLayout";
+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
import { Route } from "metabase/router";
/**
@@ -41,6 +42,13 @@ const actionSettingsPage = () =>
/* webpackChunkName: "data-actions" */ "./pages/ActionSettingsPage"
).then(({ ActionSettingsPage }) => ({ Component: ActionSettingsPage }));
+const actionDependenciesPage = () =>
+ import(
+ /* webpackChunkName: "data-actions" */ "./pages/ActionDependenciesPage"
+ ).then(({ ActionDependenciesPage }) => ({
+ Component: ActionDependenciesPage,
+ }));
+
export function getDataStudioActionRoutes() {
return (
<Route path="actions" element={<ActionsSectionLayout />}>
@@ -52,6 +60,11 @@ export function getDataStudioActionRoutes() {
<Route path=":actionId/fields" lazy={actionFieldsPage} />
<Route path=":actionId/fields/:fieldId" lazy={actionFieldsPage} />
<Route path=":actionId/run" lazy={actionRunPage} />
+ {PLUGIN_DEPENDENCIES.isEnabled && (
+ <Route path=":actionId/dependencies" lazy={actionDependenciesPage}>
+ <Route index element={<PLUGIN_DEPENDENCIES.DependencyGraphPage />} />
+ </Route>
+ )}
<Route path=":actionId/settings" lazy={actionSettingsPage} />
</Route>
);
diff --git a/frontend/src/metabase/urls/data-studio.ts b/frontend/src/metabase/urls/data-studio.ts
index 51097695bcc..76062f02814 100644
--- a/frontend/src/metabase/urls/data-studio.ts
+++ b/frontend/src/metabase/urls/data-studio.ts
@@ -405,6 +405,10 @@ export function dataStudioActionFields(
: fieldsUrl;
}
+export function dataStudioActionDependencies(actionId: WritebackActionId) {
+ return `${dataStudioAction(actionId)}/dependencies`;
+}
+
export function dataStudioActionRun(actionId: WritebackActionId) {
return `${dataStudioAction(actionId)}/run`;
}
diff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.clj
index 36e1dd680a2..c771ca0f651 100644
--- a/src/metabase/actions/models.clj
+++ b/src/metabase/actions/models.clj
@@ -41,12 +41,15 @@
(derive :metabase/model)
(derive :perms/use-parent-collection-perms)
(derive :hook/entity-id)
- (derive :hook/timestamped?))
+ (derive :hook/timestamped?)
+ (derive :hook/dependencies))
(doseq [model action-sub-models]
(derive model :metabase/model))
-(derive :model/QueryAction :hook/search-index)
+(doto :model/QueryAction
+ (derive :hook/search-index)
+ (derive :hook/dependencies))
(methodical/defmethod t2/primary-keys :model/QueryAction [_model] [:action_id])
(methodical/defmethod t2/primary-keys :model/ImplicitAction [_model] [:action_id])
diff --git a/src/metabase/actions/schema.clj b/src/metabase/actions/schema.clj
index 205e6e330cf..edecc6bd43d 100644
--- a/src/metabase/actions/schema.clj
+++ b/src/metabase/actions/schema.clj
@@ -140,6 +140,7 @@
[(case schema-type
:select [[:id ::id]
[:creator {:optional true} [:maybe ::users.schema/user]]
+ [:collection {:optional true} [:maybe :metabase.collections.schema/collection-or-root]]
[:can_write {:optional true} :boolean]]
:update [[:id {:optional true} ::id]]
:insert nil)
diff --git a/src/metabase/collections/children.clj b/src/metabase/collections/children.clj
index 71437ec01a2..6b455d36f9d 100644
--- a/src/metabase/collections/children.clj
+++ b/src/metabase/collections/children.clj
@@ -155,7 +155,8 @@
(def ^:private valid-model-param-values
"Valid values for the `?model=` param accepted by the collection-items endpoints.
`no_models` is for nilling out the set because a nil model set is actually the total model set"
- #{"card" ; SavedQuestion
+ #{"action"
+ "card" ; SavedQuestion
"dataset" ; Model. TODO : update this
"document"
"exploration"
@@ -484,6 +485,27 @@
[:inline 0]
[:inline 1]])]}))
+(defmethod collection-children-query :action
+ [_model collection {:keys [archived? pinned-state]}]
+ {:select [:action.id :action.collection_id :action.name :action.description :action.entity_id
+ :action.archived :action.archived_directly [(h2x/literal "action") :model]]
+ :from [[:action :action]]
+ :where [:and
+ (poison-when-pinned-clause pinned-state)
+ [:= :action.collection_id (:id collection)]
+ [:= :action.model_id nil]
+ [:= :action.archived (boolean archived?)]]})
+
+(defmethod post-process-collection-children :action
+ [_ _options _collection rows]
+ (for [row rows]
+ (-> (dissoc row
+ :collection_position :display :authority_level :moderated_status :icon :personal_owner_id
+ :collection_preview :dataset_query :table_id :query_type :is_upload :namespace)
+ (update :archived api/bit->boolean)
+ (update :archived_directly api/bit->boolean)
+ (assoc :collection_namespace "data-actions"))))
+
(defmethod post-process-collection-children :timeline
[_ _options _collection rows]
(for [row rows]
@@ -918,6 +940,7 @@
:exploration :model/Exploration
:pulse :model/Pulse
:snippet :model/NativeQuerySnippet
+ :action :model/Action
:table :model/Table
:timeline :model/Timeline
:transform :model/Transform))
@@ -1130,7 +1153,8 @@
[collection-namespace]
(for [model-kw (cond-> [:collection :dataset :metric :card :dashboard :pulse :snippet :timeline :document :exploration :transform]
;; Tables in collections are an EE feature (library)
- (premium-features/has-feature? :library) (conj :table))
+ (premium-features/has-feature? :library) (conj :table)
+ (= "data-actions" (some-> collection-namespace name)) (conj :action))
:let [toucan-model (model-name->toucan-model model-kw)
allowed-namespaces (collection/allowed-namespaces toucan-model)]
:when (or (= model-kw :collection)
@@ -1143,7 +1167,8 @@
{:keys [models created-by-id], :as options} :- CollectionChildrenOptions]
(let [valid-models (for [model-kw (cond-> [:collection :dataset :metric :card :dashboard :pulse :snippet :timeline :document :exploration :transform]
;; Tables in collections are an EE feature (library)
- (premium-features/has-feature? :library) (conj :table))
+ (premium-features/has-feature? :library) (conj :table)
+ (= "data-actions" (some-> collection-namespace name)) (conj :action))
;; only fetch models that are specified by the `model` param; or everything if it's empty
:when (or (empty? models) (contains? models model-kw))
;; a creator filter drops models that don't index a creator
@@ -1221,4 +1246,4 @@
If you're looking in the root collection of one of these namespaces, we'll allow you to list any type of model.
Otherwise, we'll just show you collections."
- #{nil "snippets" "transforms"})
+ #{nil "snippets" "transforms" "data-actions"})
diff --git a/src/metabase/lib/fe_util.cljc b/src/metabase/lib/fe_util.cljc
index 996d6e467d6..5dfa76d78d6 100644
--- a/src/metabase/lib/fe_util.cljc
+++ b/src/metabase/lib/fe_util.cljc
@@ -46,6 +46,7 @@
:float
::lib.schema.metadata/column
::lib.schema.metadata/segment
+ ::lib.schema.metadata/measure
::lib.schema.metadata/metric])
(def ^:private ExpressionOptions
diff --git a/src/metabase/lib/query/test_spec.cljc b/src/metabase/lib/query/test_spec.cljc
index b59966dd5b1..bbe3086de19 100644
--- a/src/metabase/lib/query/test_spec.cljc
+++ b/src/metabase/lib/query/test_spec.cljc
@@ -192,11 +192,17 @@
(mu/defn- expression-spec->expression-parts
[query :- ::lib.schema/query
stage-number :- :int
- expression-spec :- [:or ::lib.schema.test-spec/test-expression-spec ::lib.schema.test-spec/test-join-source-spec]
+ expression-spec :- [:or
+ ::lib.schema.test-spec/test-expression-spec
+ ::lib.schema.test-spec/test-join-source-spec
+ ::lib.schema.test-spec/test-operator-arg-spec]
available-columns :- [:sequential ::lib.schema.metadata/column]]
(case (:type expression-spec)
:literal (:value expression-spec)
:column (find-column query stage-number available-columns expression-spec)
+ :segment (lib.metadata/segment query (:id expression-spec))
+ :measure (lib.metadata/measure query (:id expression-spec))
+ :metric (lib.metadata/metric query (:id expression-spec))
:operator {:lib/type :mbql/expression-parts
:operator (:operator expression-spec)
:options {}
diff --git a/src/metabase/lib/schema/test_spec.cljc b/src/metabase/lib/schema/test_spec.cljc
index b2464729392..c8b21cc9853 100644
--- a/src/metabase/lib/schema/test_spec.cljc
+++ b/src/metabase/lib/schema/test_spec.cljc
@@ -97,7 +97,7 @@
[:map {:closed true}
[:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :operator]]
[:operator ::test-operator-spec]
- [:args {:default []} [:sequential [:ref ::test-expression-spec]]]
+ [:args {:default []} [:sequential [:ref ::test-operator-arg-spec]]]
;; For an aggregation: the name of its result column, which a later stage refers to.
[:name {:optional true} string?]])
@@ -108,6 +108,16 @@
[:literal [:ref ::test-literal-expression-spec]]
[:operator [:ref ::test-operator-expression-spec]]])
+(mr/def ::test-operator-arg-spec
+ [:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
+ :dispatch (comp keyword :type)}
+ [:column [:ref ::test-column-spec]]
+ [:literal [:ref ::test-literal-expression-spec]]
+ [:operator [:ref ::test-operator-expression-spec]]
+ [:segment [:ref ::test-segment-spec]]
+ [:measure [:ref ::test-measure-spec]]
+ [:metric [:ref ::test-metric-spec]]])
+
(mr/def ::test-segment-spec
[:map {:closed true}
[:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :segment]]
diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.clj
index 9d7f3010399..a611d88e2ae 100644
--- a/test/metabase/collections_rest/api_test.clj
+++ b/test/metabase/collections_rest/api_test.clj
@@ -1882,6 +1882,39 @@
(map #(select-keys % [:id :name]))
(:data (mt/user-http-request :rasta :get 200 (format "collection/%d/items" (:id collection)))))))))))))
+(deftest data-action-collection-items-test
+ (testing "GET /api/collection/:id/items lists the actions without a model in data actions collections only"
+ (mt/with-temp [:model/Collection {folder-id :id} {:namespace "data-actions", :name "Data actions folder"}
+ :model/Collection {regular-id :id} {:name "Regular collection"}
+ :model/Card {model-id :id} {:type :model, :collection_id regular-id}
+ :model/Action {in-folder :id} {:type :query, :name "In folder", :collection_id folder-id}
+ :model/QueryAction _ {:action_id in-folder
+ :database_id (mt/id)
+ :dataset_query (mt/native-query {:query "DELETE FROM venues"})}
+ :model/Action {archived :id} {:type :query, :name "Archived", :collection_id folder-id, :archived true}
+ :model/QueryAction _ {:action_id archived
+ :database_id (mt/id)
+ :dataset_query (mt/native-query {:query "DELETE FROM venues"})}
+ :model/Action {at-root :id} {:type :query, :name "At data actions root"}
+ :model/QueryAction _ {:action_id at-root
+ :database_id (mt/id)
+ :dataset_query (mt/native-query {:query "DELETE FROM venues"})}
+ :model/Action {of-model :id} {:type :implicit, :name "Of a model", :model_id model-id}
+ :model/ImplicitAction _ {:action_id of-model, :kind "row/create"}]
+ (let [actions (fn [path & params]
+ (->> (apply mt/user-http-request :crowberto :get 200 path params)
+ :data
+ (filter (comp #{"action"} :model))
+ (into #{} (map :name))))]
+ (is (= #{"In folder"}
+ (actions (str "collection/" folder-id "/items") :models "action")))
+ (is (= #{"Archived"}
+ (actions (str "collection/" folder-id "/items") :models "action" :archived true)))
+ (is (contains? (actions "collection/root/items" :namespace "data-actions") "At data actions root"))
+ (is (not (contains? (actions "collection/root/items" :namespace "data-actions") "Of a model")))
+ (is (= #{}
+ (actions (str "collection/" regular-id "/items"))))))))
+
(deftest snippet-collection-items-count-only-test
(testing "The snippets namespace is unpaginated, but a count-only request still keeps its LIMIT"
(mt/with-temp [:model/NativeQuerySnippet _ {:name "UXW5016 root snippet"}]
diff --git a/test/metabase/lib/query/test_spec_test.cljc b/test/metabase/lib/query/test_spec_test.cljc
index 890a1d4ea7c..8e65e597f0f 100644
--- a/test/metabase/lib/query/test_spec_test.cljc
+++ b/test/metabase/lib/query/test_spec_test.cljc
@@ -1576,3 +1576,25 @@
meta/metadata-provider
{:stages [{:source {:type :table :id (meta/id :orders)}
:fields [column]}]})))))))
+
+(def ^:private metadata-provider-with-segment-and-measure
+ (lib.tu/mock-metadata-provider
+ metadata-provider-with-measure
+ {:segments [{:id 1
+ :name "Expensive"
+ :table-id (meta/id :venues)
+ :definition (-> (lib/query meta/metadata-provider (meta/table-metadata :venues))
+ (lib/filter (lib/> (meta/field-metadata :venues :price) 2)))}]}))
+
+(deftest ^:parallel test-query-operator-with-segment-and-measure-args-test
+ (testing "an operator's args can be segments and measures"
+ (is (=? [[:count-where {} [:segment {} 1]]
+ [:+ {} 1 [:measure {} 1]]]
+ (lib/aggregations
+ (lib.query.test-spec/test-query
+ metadata-provider-with-segment-and-measure
+ {:stages [{:source {:type :table :id (meta/id :venues)}
+ :aggregations [{:type :operator :operator :count-where
+ :args [{:type :segment :id 1}]}
+ {:type :operator :operator :+
+ :args [{:type :literal :value 1} {:type :measure :id 1}]}]}]}))))))