Skip to content

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

Tables in collections (#66262)

Alexander Polyankin7e31d3b57940
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 5432b50ca69..d2842c2ea27 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1852,9 +1852,9 @@
database-routing
driver
events
- lib
- lib-be
- queries
+ models
+ permissions
+ premium-features
request
sync
util
diff --git a/.loki/reference/chrome_laptop_viz_BarChart_Watermark.png b/.loki/reference/chrome_laptop_viz_BarChart_Watermark.png
deleted file mode 100644
index 9f9a62a5c9c..00000000000
Binary files a/.loki/reference/chrome_laptop_viz_BarChart_Watermark.png and /dev/null differ
diff --git a/e2e/support/commands/permissions/sandboxTable.js b/e2e/support/commands/permissions/sandboxTable.js
deleted file mode 100644
index 589386cc6e3..00000000000
--- a/e2e/support/commands/permissions/sandboxTable.js
+++ /dev/null
@@ -1,43 +0,0 @@
-import { SAMPLE_DB_TABLES, USER_GROUPS } from "e2e/support/cypress_data";
-
-const { STATIC_ORDERS_ID } = SAMPLE_DB_TABLES;
-
-const { COLLECTION_GROUP } = USER_GROUPS;
-
-Cypress.Commands.add(
- "sandboxTable",
- ({
- attribute_remappings = {},
- card_id = null,
- group_id = COLLECTION_GROUP,
- table_id = STATIC_ORDERS_ID,
- } = {}) => {
- // Extract the name of the table, as well as `schema` and `db_id` that we'll need later on for `cy.updatePermissionsGraph()`
- cy.request("GET", "/api/table").then(({ body: tables }) => {
- const { name, schema, db_id } = tables.find(
- (table) => table.id === table_id,
- );
- const attr = Object.keys(attribute_remappings).join(", "); // Account for the possiblity of passing multiple user attributes
-
- cy.log(`Sandbox "${name}" table on "${attr}"`);
- cy.updatePermissionsGraph({
- [group_id]: {
- [db_id]: {
- "view-data": {
- [schema]: {
- [table_id]: "sandboxed",
- },
- },
- "create-queries": "query-builder",
- },
- },
- });
- cy.request("POST", "/api/mt/gtap", {
- attribute_remappings,
- card_id,
- group_id,
- table_id,
- });
- });
- },
-);
diff --git a/e2e/support/commands/permissions/sandboxTable.ts b/e2e/support/commands/permissions/sandboxTable.ts
new file mode 100644
index 00000000000..3b40d3ac0b1
--- /dev/null
+++ b/e2e/support/commands/permissions/sandboxTable.ts
@@ -0,0 +1,69 @@
+import { SAMPLE_DB_TABLES, USER_GROUPS } from "e2e/support/cypress_data";
+import type {
+ CardId,
+ GroupId,
+ ParameterTarget,
+ Table,
+ TableId,
+} from "metabase-types/api";
+
+const { STATIC_ORDERS_ID } = SAMPLE_DB_TABLES;
+
+const { COLLECTION_GROUP } = USER_GROUPS;
+
+type SandboxTableOptions = {
+ card_id?: CardId | null;
+ group_id?: GroupId;
+ table_id?: TableId;
+ attribute_remappings?: Record<string, ParameterTarget>;
+};
+
+declare global {
+ namespace Cypress {
+ interface Chainable {
+ sandboxTable(props: SandboxTableOptions): void;
+ }
+ }
+}
+
+Cypress.Commands.add(
+ "sandboxTable",
+ ({
+ attribute_remappings = {},
+ card_id = null,
+ group_id = COLLECTION_GROUP,
+ table_id = STATIC_ORDERS_ID,
+ } = {}) => {
+ // Extract the name of the table, as well as `schema` and `db_id` that we'll need later on for `cy.updatePermissionsGraph()`
+ cy.request("GET", "/api/table").then(
+ ({ body: tables }: { body: Table[] }) => {
+ const { name, schema, db_id } = tables.find(
+ (table) => table.id === table_id,
+ )!;
+ const attr = Object.keys(attribute_remappings).join(", "); // Account for the possiblity of passing multiple user attributes
+
+ cy.log(`Sandbox "${name}" table on "${attr}"`);
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-expect-error
+ cy.updatePermissionsGraph({
+ [group_id]: {
+ [db_id]: {
+ "view-data": {
+ [schema]: {
+ [table_id]: "sandboxed",
+ },
+ },
+ "create-queries": "query-builder",
+ },
+ },
+ });
+ cy.request("POST", "/api/mt/gtap", {
+ attribute_remappings,
+ card_id,
+ group_id,
+ table_id,
+ });
+ },
+ );
+ },
+);
diff --git a/e2e/support/helpers/api/index.ts b/e2e/support/helpers/api/index.ts
index 27b2fba12e5..63d6ed09561 100644
--- a/e2e/support/helpers/api/index.ts
+++ b/e2e/support/helpers/api/index.ts
@@ -37,7 +37,9 @@ export { createTransformTag } from "./createTransformTag";
export { deleteComment } from "./deleteComment";
export { editDashboardCard } from "./editDashboardCard";
export { getCurrentUser } from "./getCurrentUser";
+export { publishTables } from "./publishTables";
export { remapDisplayValueToFK } from "./remapDisplayValueToFK";
+export { unpublishTables } from "./unpublishTables";
export { updateComment } from "./updateComment";
export { updateDashboardCards } from "./updateDashboardCards";
export { updateSetting, updateEnterpriseSetting } from "./updateSetting";
diff --git a/e2e/support/helpers/api/publishTables.ts b/e2e/support/helpers/api/publishTables.ts
new file mode 100644
index 00000000000..544c664258c
--- /dev/null
+++ b/e2e/support/helpers/api/publishTables.ts
@@ -0,0 +1,9 @@
+import type { BulkTableSelection } from "metabase-types/api";
+
+export const publishTables = (request: BulkTableSelection) => {
+ return cy.request(
+ "POST",
+ "/api/ee/data-studio/table/publish-tables",
+ request,
+ );
+};
diff --git a/e2e/support/helpers/api/unpublishTables.ts b/e2e/support/helpers/api/unpublishTables.ts
new file mode 100644
index 00000000000..dec2352d049
--- /dev/null
+++ b/e2e/support/helpers/api/unpublishTables.ts
@@ -0,0 +1,9 @@
+import type { BulkTableSelection } from "metabase-types/api";
+
+export const unpublishTables = (request: BulkTableSelection) => {
+ return cy.request(
+ "POST",
+ "/api/ee/data-studio/table/unpublish-tables",
+ request,
+ );
+};
diff --git a/e2e/support/helpers/e2e-data-studio-helpers.ts b/e2e/support/helpers/e2e-data-studio-helpers.ts
index a88a4fe862f..8d77b338b52 100644
--- a/e2e/support/helpers/e2e-data-studio-helpers.ts
+++ b/e2e/support/helpers/e2e-data-studio-helpers.ts
@@ -1,4 +1,7 @@
+import type { TableId } from "metabase-types/api";
+
import { codeMirrorHelpers } from "./e2e-codemirror-helpers";
+import { popover } from "./e2e-ui-elements-helpers";
const modelingSidebar = () => cy.findByTestId("modeling-sidebar");
const collectionsSection = () => cy.findByTestId("collections-section");
@@ -12,11 +15,10 @@ const modelOverviewPage = () => cy.findByTestId("model-overview-page");
const modelQueryEditor = () => cy.findByTestId("model-query-editor");
const modelFieldsPage = () => cy.findByTestId("model-fields-page");
const collectionPage = () => cy.findByTestId("collection-page");
-const modelingEmptyPage = () =>
- cy.findByText("Pick a collection or create a new model or metric");
export const DataStudio = {
header: () => cy.findByTestId("data-studio-header"),
+ nav: () => cy.findByTestId("data-studio-nav"),
transformsButton: () => DataStudio.header().findByText("Transforms"),
jobsButton: () => DataStudio.header().findByText("Jobs"),
runsButton: () => DataStudio.header().findByText("Runs"),
@@ -100,11 +102,45 @@ export const DataStudio = {
dependenciesTab: () =>
DataStudio.Models.header().findByText("Dependencies"),
},
+ Tables: {
+ overviewPage: () => cy.findByTestId("table-overview-page"),
+ fieldsPage: () => cy.findByTestId("table-fields-page"),
+ dependenciesPage: () => cy.findByTestId("table-dependencies-page"),
+ header: () => cy.findByTestId("table-pane-header"),
+ nameInput: () => cy.findByTestId("table-name-input"),
+ moreMenu: () => DataStudio.Tables.header().icon("ellipsis"),
+ overviewTab: () => DataStudio.Tables.header().findByText("Overview"),
+ fieldsTab: () => DataStudio.Tables.header().findByText("Fields"),
+ dependenciesTab: () =>
+ DataStudio.Tables.header().findByText("Dependencies"),
+ visitOverviewPage: (tableId: TableId) =>
+ cy.visit(`/data-studio/modeling/tables/${tableId}`),
+ moreMenuViewTable: () =>
+ popover()
+ .findByRole("menuitem", { name: /View/ })
+ .invoke("removeAttr", "target")
+ .click(),
+
+ Overview: {
+ descriptionText: () =>
+ cy
+ .findByTestId("table-description-section")
+ .findByTestId("editable-text"),
+ descriptionInput: () =>
+ cy
+ .findByTestId("table-description-section")
+ .findByPlaceholderText("No description"),
+ },
+ },
Modeling: {
- emptyPage: modelingEmptyPage,
+ emptyPage: () => cy.findByTestId("modeling-empty-page"),
collectionPage: collectionPage,
collectionTitle: () => collectionPage().findByRole("heading"),
- metricItem: (name: string) => cy.findByTestId("metric-name").contains(name),
- modelItem: (name: string) => cy.findByTestId("dataset-name").contains(name),
+ metricItem: (name: string) =>
+ cy.findAllByTestId("metric-name").contains(name),
+ modelItem: (name: string) =>
+ cy.findAllByTestId("dataset-name").contains(name),
+ tableItem: (name: string) =>
+ cy.findAllByTestId("table-name").contains(name),
},
};
diff --git a/e2e/support/helpers/e2e-ui-elements-helpers.js b/e2e/support/helpers/e2e-ui-elements-helpers.js
index d670ec87e4d..da328570f4e 100644
--- a/e2e/support/helpers/e2e-ui-elements-helpers.js
+++ b/e2e/support/helpers/e2e-ui-elements-helpers.js
@@ -270,6 +270,10 @@ export const queryBuilderFooterDisplayToggle = () => {
return cy.findByTestId("query-display-tabular-toggle");
};
+export const queryVisualizationRoot = () => {
+ return cy.findByTestId("query-visualization-root");
+};
+
export const closeQuestionActions = () => {
queryBuilderHeader().click();
};
@@ -579,7 +583,7 @@ export function assertTableData({ columns, firstRows = [] }) {
* @param {*} menuItem optional, if provided, will click the New button and return the menu item with the text provided
* @returns
*/
-export function newButton(menuItem) {
+export function newButton(menuItem = undefined) {
if (menuItem) {
cy.findByTestId("app-bar").button("New").click();
return popover().findByText(menuItem);
diff --git a/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts b/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts
index 71108753148..2c2075e7470 100644
--- a/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts
+++ b/e2e/test/scenarios/admin/database-routing/database-routing-usage.cy.spec.ts
@@ -264,7 +264,6 @@ describe("admin > database > database routing", { tags: ["@external"] }, () => {
}).then(({ body: { id: questionId } }) => {
cy.log("Sandboxing a destination db should have no effect");
H.blockUserGroupPermissions(ALL_USERS_GROUP, this.destinationOneDbId);
- // @ts-expect-error - this isn't typed yet
cy.sandboxTable({
table_id: this.destinationOneDb_db_identifier_table_ID,
group_id: COLLECTION_GROUP,
@@ -281,7 +280,6 @@ describe("admin > database > database routing", { tags: ["@external"] }, () => {
cy.signInAsAdmin();
H.blockUserGroupPermissions(ALL_USERS_GROUP, this.leadDbId);
- // @ts-expect-error - this isn't typed yet
cy.sandboxTable({
table_id: this.leadDb_db_identifier_table_ID,
group_id: COLLECTION_GROUP,
@@ -317,7 +315,6 @@ describe("admin > database > database routing", { tags: ["@external"] }, () => {
},
}).then(({ body: { id: redColorQuestionId } }) => {
H.blockUserGroupPermissions(COLLECTION_GROUP, this.leadDbId);
- // @ts-expect-error - this isn't typed yet
cy.sandboxTable({
table_id: this.leadDb_db_identifier_table_ID,
group_id: COLLECTION_GROUP,
diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
index dc81d8cbe1c..4951372e7da 100644
--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
@@ -92,7 +92,10 @@ describe("scenarios > dashboard", () => {
H.miniPickerBrowseAll().click();
H.entityPickerModal().within(() => {
- cy.findByPlaceholderText("Search…").type("Pro");
+ cy.findByText("Databases").click();
+ cy.findByPlaceholderText("Search this database or everywhere…").type(
+ "Pro",
+ );
cy.findByText("Products").click();
});
diff --git a/e2e/test/scenarios/data-studio/data-model/data-studio-bulk-table.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/data-studio-bulk-table.cy.spec.ts
index e32a1689df7..a1fb543b23d 100644
--- a/e2e/test/scenarios/data-studio/data-model/data-studio-bulk-table.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-model/data-studio-bulk-table.cy.spec.ts
@@ -19,12 +19,6 @@ interface Table {
id: number;
}
-interface PublishModelResponse {
- models: {
- id: number;
- }[];
-}
-
describe("bulk table operations", () => {
beforeEach(() => {
H.restore();
@@ -43,8 +37,11 @@ describe("bulk table operations", () => {
"GET",
`/api/database/${WRITABLE_DB_ID}/schema/public?include_hidden=true&include_editable_data_model=true`,
).as("getSchema");
- cy.intercept("POST", "/api/ee/data-studio/table/publish-model").as(
- "publishModel",
+ cy.intercept("POST", "/api/ee/data-studio/table/publish-tables").as(
+ "publishTables",
+ );
+ cy.intercept("POST", "/api/ee/data-studio/table/unpublish-tables").as(
+ "unpublishTables",
);
});
@@ -55,14 +52,14 @@ describe("bulk table operations", () => {
TablePicker.getDatabase("Writable Postgres12").click();
cy.wait("@getSchema").then(({ response }) => {
const tables = response?.body ?? [];
- const accountTableId = getTableId(tables, "Accounts");
- const feedbackTableId = getTableId(tables, "Feedback");
+ const accountTableId = getTableId(tables, "Orders");
+ const feedbackTableId = getTableId(tables, "Products");
cy.wrap([accountTableId, feedbackTableId]).as("tableIds");
});
- TablePicker.getTable("Accounts").find('input[type="checkbox"]').check();
- TablePicker.getTable("Feedback").find('input[type="checkbox"]').check();
+ TablePicker.getTable("Orders").find('input[type="checkbox"]').check();
+ TablePicker.getTable("Products").find('input[type="checkbox"]').check();
cy.findByRole("heading", { name: /2 tables selected/ });
cy.findByRole("button", { name: /Sync settings/ }).click();
@@ -72,7 +69,7 @@ describe("bulk table operations", () => {
cy.wait<TablesActionRequest, TablesActionsResponse>("@syncSchema").then(
({ request, response }) => {
expect(request.body.table_ids).to.deep.eq(tableIds);
- expect(response?.body.status).to.eq("ok");
+ expect(response?.statusCode).to.eq(204);
},
);
});
@@ -84,7 +81,7 @@ describe("bulk table operations", () => {
cy.wait<TablesActionRequest, TablesActionsResponse>("@rescanValues").then(
({ request, response }) => {
expect(request.body.table_ids).to.deep.eq(tableIds);
- expect(response?.body.status).to.eq("ok");
+ expect(response?.statusCode).to.eq(204);
},
);
});
@@ -98,42 +95,54 @@ describe("bulk table operations", () => {
"@discardValues",
).then(({ request, response }) => {
expect(request.body.table_ids).to.deep.eq(tableIds);
- expect(response?.body.status).to.eq("ok");
+ expect(response?.statusCode).to.eq(204);
});
});
});
- it("allows publishing multiple tables", { tags: ["@external"] }, () => {
- H.restore("postgres-writable");
- H.activateToken("bleeding-edge");
- cy.signInAsAdmin();
- H.DataModel.visitDataStudio();
- TablePicker.getDatabase("Writable Postgres12").click();
- TablePicker.getTable("Accounts").find('input[type="checkbox"]').check();
- TablePicker.getTable("Feedback").find('input[type="checkbox"]').check();
- cy.findByRole("button", { name: /Publish/ }).click();
- cy.findByLabelText("Don’t show this to me again").check();
- cy.findByRole("button", { name: /Got it/ }).click();
-
- H.pickEntity({
- tab: "Collections",
- path: ["Our analytics"],
- });
- cy.findByRole("button", { name: /Publish here/ }).click();
-
- cy.wait<PublishModelResponse>("@publishModel").then(({ response }) => {
- expect(response?.body.created_count).to.eq(2);
- });
-
- H.undoToast().within(() => {
- cy.findByText("Published").should("be.visible");
- cy.findByRole("button", { name: /See it/ }).click();
- });
-
- cy.findByTestId("collection-caption").within(() => {
- cy.findByText("Our analytics").should("be.visible");
- });
- });
+ it(
+ "allows publishing and unpublishing multiple tables",
+ { tags: ["@external"] },
+ () => {
+ H.restore("postgres-writable");
+ H.activateToken("bleeding-edge");
+ cy.signInAsAdmin();
+ H.DataModel.visitDataStudio();
+
+ cy.log("select multiple tables");
+ TablePicker.getDatabase("Writable Postgres12").click();
+ TablePicker.getTable("Orders").findByRole("checkbox").check();
+ TablePicker.getTable("Products").findByRole("checkbox").check();
+ TablePicker.getTable("Reviews").findByRole("checkbox").check();
+
+ cy.log("publish the tables and verify they are published");
+ cy.findByRole("button", { name: /Publish/ }).click();
+ H.modal().findByText("Create my Library").click();
+ H.modal().findByText("Publish these tables").click();
+ cy.wait("@publishTables");
+ H.undoToastListContainer().within(() => {
+ cy.findByText("Published").should("be.visible");
+ cy.findByRole("button", { name: /Go to Data/ }).click();
+ });
+ H.DataStudio.Modeling.tableItem("Orders").should("be.visible");
+ H.DataStudio.Modeling.tableItem("Products").should("be.visible");
+ cy.go("back");
+
+ cy.log("unpublish some tables and verify they are unpublished");
+ TablePicker.getTable("Orders").findByRole("checkbox").check();
+ TablePicker.getTable("Products").findByRole("checkbox").check();
+ cy.findByRole("button", { name: /Unpublish/ }).click();
+ H.modal().findByText("Unpublish these tables").click();
+ cy.wait("@unpublishTables");
+ H.DataStudio.nav().findByLabelText("Modeling").click();
+ H.DataStudio.ModelingSidebar.collectionsTree().findByText("Data").click();
+ H.DataStudio.Modeling.collectionPage().within(() => {
+ cy.findByText("Reviews").should("be.visible");
+ cy.findByText("Orders").should("not.exist");
+ cy.findByText("Products").should("not.exist");
+ });
+ },
+ );
it("allows to edit attributes for tables", { tags: ["@external"] }, () => {
H.restore("postgres-writable");
@@ -141,8 +150,8 @@ describe("bulk table operations", () => {
cy.signInAsAdmin();
H.DataModel.visitDataStudio();
TablePicker.getDatabase("Writable Postgres12").click();
- TablePicker.getTable("Accounts").find('input[type="checkbox"]').check();
- TablePicker.getTable("Feedback").find('input[type="checkbox"]').check();
+ TablePicker.getTable("Orders").find('input[type="checkbox"]').check();
+ TablePicker.getTable("Products").find('input[type="checkbox"]').check();
H.selectHasValue("Owner", "").click();
H.selectDropdown().contains("Bobby Tables").click();
@@ -156,10 +165,10 @@ describe("bulk table operations", () => {
H.selectHasValue("Source", "").click();
H.selectDropdown().contains("Ingested").click();
H.undoToastList().should("have.length", 4);
- TablePicker.getTable("Accounts")
+ TablePicker.getTable("Orders")
.findByTestId("table-owner")
.should("have.text", "Bobby Tables");
- TablePicker.getTable("Feedback")
+ TablePicker.getTable("Products")
.findByTestId("table-owner")
.should("have.text", "Bobby Tables");
});
@@ -167,6 +176,7 @@ describe("bulk table operations", () => {
it("allows to edit attributes for db", { tags: ["@external"] }, () => {
H.restore("postgres-writable");
H.activateToken("bleeding-edge");
+ H.createLibrary();
cy.signInAsAdmin();
H.DataModel.visitDataStudio();
TablePicker.getDatabase("Writable Postgres12")
@@ -186,12 +196,8 @@ describe("bulk table operations", () => {
H.selectDropdown().contains("Ingested").click();
cy.findByRole("button", { name: /Publish/ }).click();
- cy.findByRole("button", { name: /Got it/ }).click();
- H.pickEntity({
- tab: "Collections",
- path: ["Our analytics"],
- });
- cy.findByRole("button", { name: /Publish here/ }).click();
+ H.modal().findByText("Publish these tables").click();
+ cy.wait("@publishTables");
TablePicker.getDatabase("Writable Postgres12").click();
diff --git a/e2e/test/scenarios/data-studio/data-model/data-studio-single-table.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/data-studio-single-table.cy.spec.ts
index f84153969d6..e41daa7cd8c 100644
--- a/e2e/test/scenarios/data-studio/data-model/data-studio-single-table.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-model/data-studio-single-table.cy.spec.ts
@@ -9,12 +9,6 @@ interface MetadataResponse {
view_count: number;
}
-interface PublishModelResponse {
- models: {
- id: number;
- }[];
-}
-
describe("Table editing", () => {
beforeEach(() => {
H.resetSnowplow();
@@ -35,8 +29,11 @@ describe("Table editing", () => {
cy.intercept("POST", "/api/field/*/dimension").as("updateFieldDimension");
cy.intercept("PUT", "/api/table").as("updateTables");
cy.intercept("PUT", "/api/table/*").as("updateTable");
- cy.intercept("POST", "/api/ee/data-studio/table/publish-model").as(
- "publishModel",
+ cy.intercept("POST", "/api/ee/data-studio/table/publish-tables").as(
+ "publishTables",
+ );
+ cy.intercept("POST", "/api/ee/data-studio/table/unpublish-tables").as(
+ "unpublishTables",
);
});
@@ -59,7 +56,9 @@ describe("Table editing", () => {
cy.findByLabelText("Dependencies").should("have.text", "0");
cy.findByLabelText("Dependents").should("have.text", "0");
- cy.findByRole("link", { name: "Dependency graph" }).click();
+ H.DataModel.TableSection.get()
+ .findByRole("link", { name: "Dependency graph" })
+ .click();
cy.findByRole("heading", { name: "Dependency graph" }).should(
"be.visible",
);
@@ -67,7 +66,7 @@ describe("Table editing", () => {
});
it(
- "should publish single table to a collection",
+ "should publish a single table to a collection and unpublish",
{ tags: ["@external"] },
() => {
H.restore("mysql-8");
@@ -76,52 +75,30 @@ describe("Table editing", () => {
TablePicker.getDatabase("QA MySQL8").click();
TablePicker.getTable("Orders").click();
- // Shows publish model information modal
- cy.findByRole("button", { name: /Publish/ }).click();
- cy.findByRole("button", { name: /Got it/ }).click();
- H.modal().within(() => {
- cy.findByRole("button", { name: /Cancel/ }).click();
- });
-
- // Don't show this again, info should not be shown later
- cy.findByRole("button", { name: /Publish/ }).click();
- cy.findByLabelText("Don’t show this to me again").check();
- cy.findByRole("button", { name: /Got it/ }).click();
- H.modal().within(() => {
- cy.findByRole("button", { name: /Cancel/ }).click();
- });
-
+ cy.log("publish the table and verify it's published");
cy.findByRole("button", { name: /Publish/ }).click();
- H.pickEntity({
- tab: "Collections",
- path: ["Our analytics"],
- });
- cy.findByRole("button", { name: /Publish here/ }).click();
-
- cy.wait<PublishModelResponse>("@publishModel").then(() => {
- H.undoToast().within(() => {
- cy.findByText("Published").should("be.visible");
- cy.findByRole("button", { name: /See it/ }).click();
- });
- cy.findByTestId("head-crumbs-container").within(() => {
- cy.findByText("Our analytics").should("be.visible");
- cy.findByText("Model based on ORDERS").should("be.visible");
- });
+ H.modal().findByText("Create my Library").click();
+ H.modal().findByText("Publish this table").click();
+ cy.wait("@publishTables");
+ H.undoToastListContainer().within(() => {
+ cy.findByText("Published").should("be.visible");
+ cy.findByRole("button", { name: /Go to Data/ }).click();
});
-
H.expectUnstructuredSnowplowEvent({
event: "data_studio_table_published",
});
-
- // Should not show info modal again
+ H.DataStudio.Modeling.tableItem("Orders").should("be.visible");
cy.go("back");
- cy.findByRole("button", { name: /Publish/ }).click();
- H.modal().within(() => {
- cy.findByText("Pick the collection to publish this table in").should(
- "be.visible",
- );
- });
+ cy.log("unpublish the table and verify it's unpublished");
+ cy.findByRole("button", { name: /Unpublish/ }).click();
+ H.modal().findByText("Unpublish this table").click();
+ cy.wait("@unpublishTables");
+ H.DataStudio.nav().findByLabelText("Modeling").click();
+ H.DataStudio.ModelingSidebar.collectionsTree().findByText("Data").click();
+ H.DataStudio.Modeling.collectionPage()
+ .findByText("No tables or models yet")
+ .should("be.visible");
},
);
diff --git a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
index 809a4e026ee..36d5ed23d1e 100644
--- a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio.cy.spec.ts
@@ -545,7 +545,8 @@ describe("scenarios > data studio > datamodel", () => {
it("should indicate published tables", () => {
getTableId({ databaseId: WRITABLE_DB_ID, name: domesticAnimalsTable })
.then((tableId) => {
- return publishTables([tableId]);
+ H.createLibrary();
+ publishTables([tableId]);
})
.as("publishedTableId");
@@ -4012,9 +4013,8 @@ function updateTableAttributes({
}
function publishTables(tableIds: TableId[]) {
- return cy.request("POST", "/api/ee/data-studio/table/publish-model", {
+ return cy.request("POST", "/api/ee/data-studio/table/publish-tables", {
table_ids: tableIds,
- target_collection_id: null,
});
}
diff --git a/e2e/test/scenarios/data-studio/data-model/segments-data-studio.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/segments-data-studio.cy.spec.ts
new file mode 100644
index 00000000000..81c33882350
--- /dev/null
+++ b/e2e/test/scenarios/data-studio/data-model/segments-data-studio.cy.spec.ts
@@ -0,0 +1,340 @@
+import { SAMPLE_DB_ID, SAMPLE_DB_SCHEMA_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+
+const { H } = cy;
+const { ORDERS, ORDERS_ID, PRODUCTS_ID } = SAMPLE_DATABASE;
+
+describe("scenarios > data studio > data model > segments", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ cy.intercept("POST", "/api/segment").as("createSegment");
+ cy.intercept("PUT", "/api/segment/*").as("updateSegment");
+ cy.intercept("DELETE", "/api/segment/*").as("deleteSegment");
+ cy.intercept("GET", "/api/table/*/query_metadata*").as("metadata");
+ });
+
+ describe("Segment list", () => {
+ it("should show empty state and navigation when no segments exist", () => {
+ visitDataStudioTableSegmentsTab(ORDERS_ID);
+
+ cy.log("verify empty state");
+ H.main()
+ .findByText("No segments yet")
+ .scrollIntoView()
+ .should("be.visible");
+ H.main()
+ .findByText("Create a segment to filter rows in this table.")
+ .should("be.visible");
+
+ cy.log("verify new segment link and navigation");
+ H.main()
+ .findByRole("link", { name: /New segment/i })
+ .scrollIntoView()
+ .click();
+
+ cy.url().should(
+ "include",
+ `/data-studio/modeling/segments/new?tableId=${ORDERS_ID}`,
+ );
+ });
+
+ it("should display segments and allow navigation to edit page", () => {
+ createTestSegment({
+ name: "High Value Orders",
+ filter: [">", ["field", ORDERS.TOTAL, null], 100],
+ });
+ visitDataStudioTableSegmentsTab(ORDERS_ID);
+
+ cy.log("verify segment in list with filter description");
+ H.main()
+ .findByRole("listitem", { name: "High Value Orders" })
+ .scrollIntoView()
+ .should("be.visible");
+ H.main()
+ .findByTestId("list-item-description")
+ .should("contain", "Filtered by Total is greater than 100");
+
+ cy.log("navigate to edit page");
+ H.main().findByRole("listitem", { name: "High Value Orders" }).click();
+ cy.get<number>("@segmentId").then((segmentId) => {
+ cy.url().should(
+ "include",
+ `/data-studio/modeling/segments/${segmentId}`,
+ );
+ });
+ });
+
+ it("should navigate between Fields and Segments tabs", () => {
+ visitDataStudioTable(ORDERS_ID);
+
+ cy.log("verify both tabs visible");
+ cy.findByRole("tab", { name: /Fields/i }).scrollIntoView();
+ cy.findByRole("tab", { name: /Segments/i }).should("be.visible");
+
+ cy.log("navigate to segments tab");
+ cy.findByRole("tab", { name: /Segments/i }).click();
+ cy.url().should(
+ "include",
+ `/data-studio/data/database/${SAMPLE_DB_ID}/schema/${SAMPLE_DB_SCHEMA_ID}/table/${ORDERS_ID}/segments`,
+ );
+ H.main()
+ .findByText("No segments yet")
+ .scrollIntoView()
+ .should("be.visible");
+
+ cy.log("verify tab selection preserved on refresh");
+ cy.reload();
+ cy.wait("@metadata");
+ cy.findByRole("tab", { name: /Segments/i })
+ .scrollIntoView()
+ .should("have.attr", "aria-selected", "true");
+
+ cy.log("navigate back to fields tab");
+ cy.findByRole("tab", { name: /Fields/i }).click();
+ cy.url().should("include", "/field");
+ });
+ });
+
+ describe("Segment creation", () => {
+ it("should create a segment with filters and verify across features", () => {
+ visitDataStudioTableSegmentsTab(ORDERS_ID);
+
+ cy.log("navigate to new segment page");
+ H.main()
+ .findByRole("link", { name: /New segment/i })
+ .scrollIntoView()
+ .click();
+
+ cy.log("fill in segment name");
+ cy.findByPlaceholderText("New segment").type("Premium Orders");
+
+ cy.log("add filter");
+ H.main()
+ .findByText("Add filters to narrow your answer")
+ .scrollIntoView()
+ .click();
+ H.popover().findByText("Total").click();
+ H.selectFilterOperator("Greater than");
+ H.popover().within(() => {
+ cy.findByLabelText("Filter value").type("100");
+ cy.button("Add filter").click();
+ });
+
+ cy.log("verify row count preview");
+ H.main()
+ .findByText(/\d+ rows/)
+ .scrollIntoView()
+ .should("be.visible");
+
+ cy.log("verify preview link");
+ H.main()
+ .findByRole("link", { name: /Preview/i })
+ .should("be.visible");
+
+ cy.log("save segment");
+ H.main().button("Save").scrollIntoView().click();
+ cy.wait("@createSegment");
+
+ cy.log("verify redirect to edit page and toast");
+ H.undoToast().should("contain.text", "Segment created");
+ cy.url().should("match", /\/data-studio\/modeling\/segments\/\d+$/);
+
+ cy.log("verify segment in query builder");
+ verifySegmentInQueryBuilder("Premium Orders");
+ });
+
+ it("should show row count when filters are added", () => {
+ visitDataStudioTableSegmentsTab(PRODUCTS_ID);
+
+ H.main()
+ .findByRole("link", { name: /New segment/i })
+ .scrollIntoView()
+ .click();
+
+ H.main()
+ .findByText("Add filters to narrow your answer")
+ .scrollIntoView()
+ .click();
+ H.popover().findByText("Price").click();
+ H.selectFilterOperator("Less than");
+ H.popover().within(() => {
+ cy.findByLabelText("Filter value").type("50");
+ cy.button("Add filter").click();
+ });
+
+ H.main()
+ .findByText(/\d+ rows/)
+ .scrollIntoView()
+ .should("be.visible");
+ });
+ });
+
+ describe("Segment editing", () => {
+ it("should display and update existing segment", () => {
+ createTestSegment({
+ name: "Test Segment",
+ description: "Test description",
+ });
+ cy.get<number>("@segmentId").then((segmentId) => {
+ cy.visit(`/data-studio/modeling/segments/${segmentId}`);
+ });
+
+ cy.log("verify existing data displayed");
+ H.main().findByText("Test Segment").scrollIntoView().should("be.visible");
+ H.main()
+ .findByLabelText("Description")
+ .scrollIntoView()
+ .should("have.value", "Test description");
+
+ cy.log("update segment name");
+ H.main().findByText("Test Segment").click().type(" Updated{enter}");
+ H.main().button("Save").scrollIntoView().click();
+ cy.wait("@updateSegment");
+
+ cy.log("verify toast (stays on edit page)");
+ H.undoToast().should("contain.text", "Segment updated");
+
+ cy.log("verify updated segment in query builder");
+ verifySegmentInQueryBuilder("Test Segment Updated");
+ });
+
+ it("should navigate back to segments tab via breadcrumb", () => {
+ createTestSegment({ name: "Breadcrumb Test Segment" });
+ cy.get<number>("@segmentId").then((segmentId) => {
+ cy.visit(`/data-studio/modeling/segments/${segmentId}`);
+ });
+
+ H.main().findByText("Orders segments").scrollIntoView().click();
+
+ cy.url().should(
+ "include",
+ `/data-studio/data/database/${SAMPLE_DB_ID}/schema/${SAMPLE_DB_SCHEMA_ID}/table/${ORDERS_ID}/segments`,
+ );
+ cy.findByRole("tab", { name: /Segments/i })
+ .scrollIntoView()
+ .should("have.attr", "aria-selected", "true");
+ });
+ });
+
+ describe("Segment deletion", () => {
+ it("should remove segment via more menu", () => {
+ createTestSegment({ name: "Segment to Delete" });
+ cy.get<number>("@segmentId").then((segmentId) => {
+ cy.visit(`/data-studio/modeling/segments/${segmentId}`);
+ });
+
+ cy.log("delete via more menu");
+ cy.findByLabelText("Segment actions").click();
+ H.popover().findByText("Remove segment").click();
+ H.modal().button("Remove").click();
+ cy.wait("@deleteSegment");
+
+ cy.log("verify redirect to list and removal");
+ H.undoToast().should("contain.text", "Segment removed");
+ cy.url().should(
+ "include",
+ `/data-studio/data/database/${SAMPLE_DB_ID}/schema/${SAMPLE_DB_SCHEMA_ID}/table/${ORDERS_ID}/segments`,
+ );
+ H.main()
+ .findByText("Segment to Delete", { timeout: 1000 })
+ .should("not.exist");
+
+ cy.log("verify segment removed from query builder");
+ verifySegmentNotInQueryBuilder("Segment to Delete");
+ });
+ });
+
+ describe("Unsaved changes", () => {
+ it("should show leave confirmation with unsaved changes", () => {
+ visitDataStudioTableSegmentsTab(ORDERS_ID);
+
+ H.main()
+ .findByRole("link", { name: /New segment/i })
+ .scrollIntoView()
+ .click();
+ cy.findByPlaceholderText("New segment").type("Unsaved Segment");
+
+ cy.log("attempt to navigate away");
+ H.main().findByText("Orders segments").scrollIntoView().click();
+
+ cy.log("verify confirmation modal");
+ H.modal().within(() => {
+ cy.findByText("Discard your changes?").should("be.visible");
+ cy.button("Cancel").click();
+ });
+
+ cy.log("verify still on editor");
+ H.main().findByText("Unsaved Segment").should("be.visible");
+ });
+ });
+});
+
+function visitDataStudioTable(tableId: number) {
+ H.DataModel.visitDataStudio({
+ databaseId: SAMPLE_DB_ID,
+ schemaId: SAMPLE_DB_SCHEMA_ID,
+ tableId,
+ });
+}
+
+function visitDataStudioTableSegmentsTab(tableId: number) {
+ cy.visit(
+ `/data-studio/data/database/${SAMPLE_DB_ID}/schema/${SAMPLE_DB_SCHEMA_ID}/table/${tableId}/segments`,
+ );
+ cy.wait("@metadata");
+}
+
+function createTestSegment(
+ opts: {
+ name?: string;
+ description?: string;
+ tableId?: number;
+ filter?: unknown[];
+ } = {},
+) {
+ const {
+ name = "Test Segment",
+ description,
+ tableId = ORDERS_ID,
+ filter = ["<", ["field", ORDERS.TOTAL, null], 100],
+ } = opts;
+
+ H.createSegment({
+ name,
+ description,
+ table_id: tableId,
+ definition: {
+ type: "query",
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": tableId,
+ filter,
+ },
+ },
+ }).then(({ body }) => {
+ cy.wrap(body.id).as("segmentId");
+ });
+}
+
+function verifySegmentInQueryBuilder(
+ segmentName: string,
+ tableId: number = ORDERS_ID,
+) {
+ H.openTable({ table: tableId, mode: "notebook" });
+
+ H.getNotebookStep("data").button("Filter").click();
+ H.popover().findByText(segmentName).should("be.visible");
+}
+
+function verifySegmentNotInQueryBuilder(
+ segmentName: string,
+ tableId: number = ORDERS_ID,
+) {
+ H.openTable({ table: tableId, mode: "notebook" });
+
+ H.getNotebookStep("data").button("Filter").click();
+ H.popover().findByText(segmentName).should("not.exist");
+}
diff --git a/e2e/test/scenarios/data-studio/modeling-library.cy.spec.ts b/e2e/test/scenarios/data-studio/modeling-library.cy.spec.ts
index 2d0401868bd..79314310ae4 100644
--- a/e2e/test/scenarios/data-studio/modeling-library.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/modeling-library.cy.spec.ts
@@ -35,7 +35,7 @@ describe("scenarios > data studio > modeling > library", () => {
cy.log("Create library via modal");
H.modal().within(() => {
cy.findByText("Create your Library").should("be.visible");
- cy.button("Create my Library").click();
+ cy.findByText("Create my Library").click();
});
cy.wait("@createLibrary");
@@ -54,18 +54,18 @@ describe("scenarios > data studio > modeling > library", () => {
cy.log("Verify empty state shows on library root");
H.DataStudio.Modeling.collectionPage().within(() => {
- cy.findByText("No models or metrics yet").should("be.visible");
+ cy.findByText("No tables or metrics yet").should("be.visible");
cy.findByText(
- "Models and metrics in this collection will appear here.",
+ "Tables and metrics in this collection will appear here.",
).should("be.visible");
});
cy.log("Select Data collection and verify it's empty");
H.DataStudio.ModelingSidebar.collectionsTree().findByText("Data").click();
- cy.log("Verify no models yet message");
+ cy.log("Verify no tables or models yet message");
H.DataStudio.Modeling.collectionPage().within(() => {
- cy.findByText("No models yet").should("be.visible");
+ cy.findByText("No tables or models yet").should("be.visible");
});
});
diff --git a/e2e/test/scenarios/data-studio/modeling-models.cy.spec.ts b/e2e/test/scenarios/data-studio/modeling-models.cy.spec.ts
index d064e601f02..8c739730d79 100644
--- a/e2e/test/scenarios/data-studio/modeling-models.cy.spec.ts
+++ b/e2e/test/scenarios/data-studio/modeling-models.cy.spec.ts
@@ -132,7 +132,7 @@ describe("scenarios > data studio > modeling > models", () => {
H.DataStudio.ModelingSidebar.collectionsTree().findByText("Data").click();
H.DataStudio.Modeling.collectionPage().should("be.visible");
H.DataStudio.Modeling.collectionPage()
- .findByText("No models yet")
+ .findByText("No tables or models yet")
.should("be.visible");
cy.log("Navigate to trash");
@@ -275,7 +275,7 @@ describe("scenarios > data studio > modeling > models", () => {
H.DataStudio.ModelingSidebar.collectionsTree().findByText("Data").click();
H.DataStudio.Modeling.collectionPage().should("be.visible");
H.DataStudio.Modeling.collectionPage()
- .findByText("No models yet")
+ .findByText("No tables or models yet")
.should("be.visible");
});
});
diff --git a/e2e/test/scenarios/data-studio/modeling-tables.cy.spec.ts b/e2e/test/scenarios/data-studio/modeling-tables.cy.spec.ts
new file mode 100644
index 00000000000..e34e60d8dfe
--- /dev/null
+++ b/e2e/test/scenarios/data-studio/modeling-tables.cy.spec.ts
@@ -0,0 +1,127 @@
+const { H } = cy;
+
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+describe("scenarios > data studio > modeling > tables", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ });
+
+ describe("header", () => {
+ it("should be able to change the name", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ H.DataStudio.Tables.visitOverviewPage(ORDERS_ID);
+ H.DataStudio.Tables.nameInput().should("have.value", "Orders");
+ H.DataStudio.Tables.nameInput().clear().type("Orders changed").blur();
+ H.undoToastList().contains("Table name updated").should("be.visible");
+ });
+
+ it("should be able to view the table in the query builder", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ H.DataStudio.Tables.visitOverviewPage(ORDERS_ID);
+ H.DataStudio.Tables.moreMenu().click();
+ H.DataStudio.Tables.moreMenuViewTable();
+
+ H.queryBuilderHeader().within(() => {
+ cy.icon("repository").should("be.visible");
+ cy.findByText("Data").should("be.visible");
+ cy.findByText("Orders").should("be.visible");
+ });
+ });
+
+ it("should be able to unpublish a table", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ H.DataStudio.Tables.visitOverviewPage(ORDERS_ID);
+ H.DataStudio.Tables.moreMenu().click();
+ H.popover().findByText("Unpublish").click();
+ H.modal().findByText("Unpublish this table").click();
+ H.DataStudio.Modeling.emptyPage().should("be.visible");
+ H.DataStudio.ModelingSidebar.collectionsTree().findByText("Data").click();
+ H.DataStudio.Modeling.collectionPage()
+ .findByText("No tables or models yet")
+ .should("be.visible");
+ });
+ });
+
+ describe("overview", () => {
+ it("should be able to view the table data", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ H.DataStudio.Tables.visitOverviewPage(ORDERS_ID);
+ H.queryVisualizationRoot().within(() => {
+ cy.findByText("Subtotal").should("be.visible");
+ cy.findByText("109.22").should("be.visible");
+ });
+ });
+
+ it("should be able to change the description", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ H.DataStudio.Tables.visitOverviewPage(ORDERS_ID);
+ H.DataStudio.Tables.Overview.descriptionText()
+ .should("contain.text", "orders for a product")
+ .click();
+ H.DataStudio.Tables.Overview.descriptionInput()
+ .clear()
+ .type("Description changed")
+ .blur();
+ H.undoToastList()
+ .contains("Table description updated")
+ .should("be.visible");
+ });
+ });
+
+ describe("fields", () => {
+ it("should be able to rename fields", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ H.DataStudio.Tables.visitOverviewPage(ORDERS_ID);
+ H.tableHeaderColumn("Total").should("be.visible");
+
+ H.DataStudio.Tables.fieldsTab().click();
+ H.DataModel.TableSection.clickField("Total");
+ H.DataModel.FieldSection.getNameInput()
+ .clear()
+ .type("Total changed")
+ .blur();
+ H.undoToast().findByText("Name of Total updated").should("be.visible");
+
+ H.DataStudio.Tables.overviewTab().click();
+ H.tableHeaderColumn("Total changed").should("be.visible");
+ });
+ });
+
+ describe("dependencies", () => {
+ it("should be able to view dependencies for a table", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+ H.createQuestion({
+ name: "Test question",
+ query: { "source-table": ORDERS_ID },
+ });
+
+ H.DataStudio.Tables.visitOverviewPage(ORDERS_ID);
+ H.DataStudio.Tables.dependenciesTab().click();
+ H.DependencyGraph.graph().within(() => {
+ cy.findByText("Orders").should("be.visible");
+ cy.findByText(/question/).click();
+ });
+ H.DependencyGraph.dependencyPanel()
+ .findByText("Test question")
+ .should("be.visible");
+ });
+ });
+});
diff --git a/e2e/test/scenarios/data-studio/table-collection-permissions.cy.spec.ts b/e2e/test/scenarios/data-studio/table-collection-permissions.cy.spec.ts
new file mode 100644
index 00000000000..2e2321db013
--- /dev/null
+++ b/e2e/test/scenarios/data-studio/table-collection-permissions.cy.spec.ts
@@ -0,0 +1,556 @@
+const { H } = cy;
+
+import { SAMPLE_DB_ID, USER_GROUPS } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { QuestionDetails } from "e2e/support/helpers";
+
+const { ORDERS_ID, ORDERS, PRODUCTS_ID, PRODUCTS, PEOPLE_ID, REVIEWS } =
+ SAMPLE_DATABASE;
+
+const productsQuestionDetails: QuestionDetails = {
+ dataset_query: {
+ type: "query",
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": PRODUCTS_ID,
+ },
+ },
+};
+
+const productsByTimeQuestionDetails: QuestionDetails = {
+ dataset_query: {
+ type: "query",
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": PRODUCTS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", PRODUCTS.CREATED_AT, { "temporal-unit": "year" }]],
+ },
+ },
+};
+
+const peopleQuestionDetails: QuestionDetails = {
+ dataset_query: {
+ type: "query",
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": PEOPLE_ID,
+ },
+ },
+};
+
+const ordersQuestionDetails: QuestionDetails = {
+ dataset_query: {
+ type: "query",
+ database: SAMPLE_DB_ID,
+ query: {
+ "source-table": ORDERS_ID,
+ },
+ },
+};
+
+describe("scenarios > data studio > table collection permissions", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ H.createLibrary();
+ });
+
+ describe("queries", () => {
+ it("should create a question based on a published table", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ cy.visit("/");
+ H.newButton().click();
+ H.popover().within(() => {
+ cy.findByText("Question").should("be.visible");
+ cy.findByText("SQL query").should("not.exist");
+ cy.findByText("Question").click();
+ });
+ H.popover().within(() => {
+ cy.findByText("Products").should("be.visible");
+ cy.findByText("Orders").should("not.exist");
+ cy.findByText("Products").click();
+ });
+ H.visualize();
+ H.assertQueryBuilderRowCount(200);
+
+ H.saveQuestion("Test question", { wrapId: true });
+ H.visitQuestion("@questionId");
+ H.assertQueryBuilderRowCount(200);
+ });
+
+ it("should create a question with explicit joins when not all FK tables are published", () => {
+ H.publishTables({ table_ids: [ORDERS_ID, PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(ordersQuestionDetails, { mode: "notebook" });
+ H.getNotebookStep("data").button("Join data").click();
+ H.popover().within(() => {
+ cy.findByText("Products").should("be.visible");
+ cy.findByText("People").should("not.exist");
+ cy.findByText("Products").click();
+ });
+ H.getNotebookStep("join").button("Summarize").click();
+ H.popover().findByText("Count of rows").click();
+ H.visualize();
+ H.assertQueryBuilderRowCount(1);
+
+ H.saveQuestion("Test question", { wrapId: true });
+ H.visitQuestion("@questionId");
+ H.assertQueryBuilderRowCount(1);
+ });
+
+ it("should create a question with implicit joins when not all FK tables are published", () => {
+ H.publishTables({ table_ids: [ORDERS_ID, PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(ordersQuestionDetails, { mode: "notebook" });
+ H.getNotebookStep("data").button("Filter").click();
+ H.popover().within(() => {
+ cy.findByText("Product").should("exist");
+ cy.findByText("User").should("not.exist");
+ cy.findByText("Product").click();
+ cy.findByText("Category").click();
+ cy.findByText("Gadget").click();
+ cy.button("Add filter").click();
+ });
+ H.getNotebookStep("filter").button("Summarize").click();
+ H.popover().findByText("Count of rows").click();
+ H.visualize();
+ H.assertQueryBuilderRowCount(1);
+
+ H.saveQuestion("Test question", { wrapId: true });
+ H.visitQuestion("@questionId");
+ H.assertQueryBuilderRowCount(1);
+ });
+
+ it("should create a question with a table segment", () => {
+ H.createSegment({
+ name: "ID segment",
+ table_id: PRODUCTS_ID,
+ definition: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": PRODUCTS_ID,
+ filter: ["=", ["field", PRODUCTS.ID, null], 1],
+ },
+ },
+ });
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails, { mode: "notebook" });
+ H.getNotebookStep("data").button("Filter").click();
+ H.popover().findByText("ID segment").click();
+ H.visualize();
+ H.assertQueryBuilderRowCount(1);
+
+ H.saveQuestion("Test question", { wrapId: true });
+ H.visitQuestion("@questionId");
+ H.assertQueryBuilderRowCount(1);
+ });
+
+ it("should create a question with a table metric", () => {
+ H.createQuestion({
+ name: "Count metric",
+ type: "metric",
+ query: {
+ "source-table": PRODUCTS_ID,
+ aggregation: [["count"]],
+ },
+ });
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails, { mode: "notebook" });
+ H.getNotebookStep("data").button("Summarize").click();
+ H.popover().within(() => {
+ cy.findByText("Metrics").click();
+ cy.findByText("Count metric").click();
+ });
+ H.visualize();
+ H.assertQueryBuilderRowCount(1);
+
+ H.saveQuestion("Test question", { wrapId: true });
+ H.visitQuestion("@questionId");
+ H.assertQueryBuilderRowCount(1);
+ });
+
+ it("should create a question with table and question sources", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails, { mode: "notebook" });
+ H.getNotebookStep("data").button("Join data").click();
+ H.popover().findByText("Browse all").click();
+ H.entityPickerModal().within(() => {
+ cy.findByText("Orders").click();
+ });
+ H.getNotebookStep("join").button("Summarize").click();
+ H.popover().findByText("Count of rows").click();
+ H.visualize();
+ H.assertQueryBuilderRowCount(1);
+
+ H.saveQuestion("Test question", { wrapId: true });
+ H.visitQuestion("@questionId");
+ H.assertQueryBuilderRowCount(1);
+ });
+
+ it("should be able to drill-thru", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ H.tableInteractive().findByText("82.75").click();
+ H.popover().findByText("=").click();
+ H.assertQueryBuilderRowCount(1);
+ });
+ });
+
+ describe("x-rays", () => {
+ it("should be able to x-ray a table", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsByTimeQuestionDetails);
+ H.cartesianChartCircle().first().click();
+ H.popover().findByText("Automatic insights…").click();
+ H.popover().findByText("X-ray").click();
+ H.main()
+ .findByText(/A closer look at number of Products/)
+ .should("be.visible");
+ });
+ });
+
+ describe("field values", () => {
+ it("should be able to use list field values", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ H.tableHeaderClick("Category");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByText("Gadget").click();
+ cy.button("Add filter").click();
+ });
+ H.assertQueryBuilderRowCount(53);
+ });
+
+ it("should be able to use search field values", () => {
+ H.publishTables({ table_ids: [PEOPLE_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(peopleQuestionDetails);
+ H.tableHeaderClick("Name");
+ H.popover().findByText("Filter by this column").click();
+ popoverByIndex(1).findByText("Aaron Hand").click();
+ popoverByIndex(0).findByPlaceholderText("Search by Name").type("Myrtle");
+ popoverByIndex(1).findByText("Myrtle Johns").click();
+ popoverByIndex(0).findByPlaceholderText("Search by Name").type("{esc}");
+ H.popover().within(() => {
+ cy.findByText("Aaron Hand").should("be.visible");
+ cy.findByText("Myrtle Johns").should("be.visible");
+ cy.button("Add filter").click();
+ });
+ H.assertQueryBuilderRowCount(2);
+ });
+ });
+
+ describe("remapping", () => {
+ it("should automatically publish all tables referenced by FK remapping, recursively", () => {
+ cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
+ name: "Product ID",
+ type: "external",
+ human_readable_field_id: PRODUCTS.TITLE,
+ });
+ cy.request("PUT", `/api/field/${PRODUCTS.RATING}`, {
+ semantic_type: "type/FK",
+ fk_target_field_id: REVIEWS.ID,
+ });
+ cy.request("POST", `/api/field/${PRODUCTS.RATING}/dimension`, {
+ name: "Rating",
+ type: "external",
+ human_readable_field_id: REVIEWS.REVIEWER,
+ });
+ H.DataModel.visitDataStudio();
+ H.DataModel.TablePicker.getTable("Orders").click();
+ cy.findByRole("button", { name: /Publish/ }).click();
+ H.modal().within(() => {
+ cy.findByText("Products").should("be.visible");
+ cy.findByText("Reviews").should("be.visible");
+ cy.findByText("People").should("not.exist");
+ cy.findByText("Publish these tables").click();
+ });
+ H.undoToast().findByText("Published").should("be.visible");
+
+ cy.signIn("nodata");
+ cy.visit("/");
+ librarySidebarSection().findByText("Data").click();
+ H.collectionTable().within(() => {
+ cy.findByText("Products").should("be.visible");
+ cy.findByText("Reviews").should("be.visible");
+ cy.findByText("Orders").click();
+ });
+ H.tableInteractive().should("be.visible");
+ H.tableHeaderColumn("Product ID").should("be.visible");
+ });
+
+ it("should automatically unpublish all tables referenced by FK remapping, recursively", () => {
+ cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
+ name: "Product ID",
+ type: "external",
+ human_readable_field_id: PRODUCTS.TITLE,
+ });
+ cy.request("PUT", `/api/field/${PRODUCTS.RATING}`, {
+ semantic_type: "type/FK",
+ fk_target_field_id: REVIEWS.ID,
+ });
+ cy.request("POST", `/api/field/${PRODUCTS.RATING}/dimension`, {
+ name: "Rating",
+ type: "external",
+ human_readable_field_id: REVIEWS.REVIEWER,
+ });
+ H.publishTables({ table_ids: [ORDERS_ID, PEOPLE_ID] });
+ H.DataModel.visitDataStudio();
+ H.DataModel.TablePicker.getTable("Reviews").click();
+ cy.findByRole("button", { name: /Unpublish/ }).click();
+ H.modal().within(() => {
+ cy.findByText("Products").should("be.visible");
+ cy.findByText("Orders").should("be.visible");
+ cy.findByText("People").should("not.exist");
+ cy.findByText("Unpublish these tables").click();
+ });
+ H.undoToast().findByText("Unpublished").should("be.visible");
+
+ cy.signIn("nodata");
+ cy.visit("/");
+ librarySidebarSection().findByText("Data").click();
+ H.collectionTable().within(() => {
+ cy.findByText("People").should("be.visible");
+ cy.findByText("Products").should("not.exist");
+ cy.findByText("Orders").should("not.exist");
+ cy.findByText("Reviews").should("not.exist");
+ });
+ });
+
+ it("should be able to use list field values with FK remapping", () => {
+ cy.request("PUT", `/api/field/${ORDERS.PRODUCT_ID}`, {
+ has_field_values: "list",
+ });
+ cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
+ name: "Product ID",
+ type: "external",
+ human_readable_field_id: PRODUCTS.TITLE,
+ });
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(ordersQuestionDetails);
+ H.tableInteractive()
+ .findByText("Awesome Concrete Shoes")
+ .should("be.visible");
+ H.tableHeaderClick("Product ID");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByText("Rustic Paper Wallet").click();
+ cy.button("Add filter").click();
+ });
+ H.assertQueryBuilderRowCount(93);
+ });
+
+ it("should be able to use search field values with FK remapping", () => {
+ cy.request("PUT", `/api/field/${ORDERS.PRODUCT_ID}`, {
+ has_field_values: "search",
+ });
+ cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
+ name: "Product ID",
+ type: "external",
+ human_readable_field_id: PRODUCTS.TITLE,
+ });
+ H.publishTables({ table_ids: [ORDERS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(ordersQuestionDetails);
+ H.tableInteractive()
+ .findByText("Awesome Concrete Shoes")
+ .should("be.visible");
+ H.tableHeaderClick("Product ID");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByPlaceholderText("Search by Title or enter an ID").type(
+ "Rustic Paper",
+ );
+ cy.findByText("Rustic Paper Wallet").click();
+ cy.button("Add filter").click();
+ });
+ H.assertQueryBuilderRowCount(93);
+ });
+
+ it("should show a permission error when accessing a published table when some columns are remapped to unpublished tables", () => {
+ H.publishTables({ table_ids: [ORDERS_ID] });
+ cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
+ name: "Product ID",
+ type: "external",
+ human_readable_field_id: PRODUCTS.TITLE,
+ });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(ordersQuestionDetails);
+ assertQueryPermissionError();
+ });
+ });
+
+ describe("sandboxing", () => {
+ it("should be able to access a published sandboxed table", () => {
+ H.blockUserGroupPermissions(USER_GROUPS.ALL_USERS_GROUP);
+ sandboxProductsOnCategory();
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("sandboxed");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ H.assertQueryBuilderRowCount(54);
+ });
+
+ it("should be able to use list field values with sandboxing", () => {
+ H.blockUserGroupPermissions(USER_GROUPS.ALL_USERS_GROUP);
+ sandboxProductsOnCategory();
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("sandboxed");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ H.tableHeaderClick("Category");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByText("Widget").should("be.visible");
+ cy.findByText("Gadget").should("not.exist");
+ cy.findByText("Widget").click();
+ cy.button("Add filter").click();
+ });
+ H.assertQueryBuilderRowCount(54);
+ });
+
+ it("should be able to use search field values with sandboxing", () => {
+ cy.request("PUT", `/api/field/${PRODUCTS.CATEGORY}`, {
+ has_field_values: "search",
+ });
+ H.blockUserGroupPermissions(USER_GROUPS.ALL_USERS_GROUP);
+ sandboxProductsOnCategory();
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("sandboxed");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ H.tableHeaderClick("Category");
+ H.popover().within(() => {
+ cy.findByText("Filter by this column").click();
+ cy.findByPlaceholderText("Search by Category").type("get");
+ cy.findByText("Widget").should("be.visible");
+ cy.findByText("Gadget").should("not.exist");
+ cy.findByText("Widget").click();
+ cy.button("Add filter").click();
+ });
+ H.assertQueryBuilderRowCount(54);
+ });
+ });
+
+ describe("block permission", () => {
+ it("should not be able to access a published table data when blocked", () => {
+ H.blockUserGroupPermissions(USER_GROUPS.ALL_USERS_GROUP);
+ H.blockUserGroupPermissions(USER_GROUPS.COLLECTION_GROUP);
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ assertQueryPermissionError();
+ });
+ });
+
+ describe("unpublishing", () => {
+ it("should not be able to access a previously published table when it is unpublished", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+ H.DataModel.visitDataStudio();
+ H.DataModel.TablePicker.getTable("Products").click();
+ cy.findByRole("button", { name: /Unpublish/ }).click();
+ H.modal().findByText("Unpublish this table").click();
+ H.undoToast().findByText("Unpublished").should("be.visible");
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ assertPermissionError();
+ });
+
+ it("should not be able to create questions when all published tables are unpublished", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+ H.DataModel.visitDataStudio();
+ H.DataModel.TablePicker.getTable("Products").click();
+ cy.findByRole("button", { name: /Unpublish/ }).click();
+ H.modal().findByText("Unpublish this table").click();
+ H.undoToast().findByText("Unpublished").should("be.visible");
+
+ cy.signIn("nodata");
+ cy.visit("/");
+ H.newButton().click();
+ H.popover().within(() => {
+ cy.findByText("Dashboard").should("be.visible");
+ cy.findByText("Question").should("not.exist");
+ });
+ });
+ });
+
+ describe("losing token features", () => {
+ it("should not be able to query previously published tables", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+ H.deleteToken();
+
+ cy.signIn("nodata");
+ H.visitQuestionAdhoc(productsQuestionDetails);
+ assertPermissionError();
+ });
+
+ it("should not be able to create questions even if there are published tables", () => {
+ H.publishTables({ table_ids: [PRODUCTS_ID] });
+ H.deleteToken();
+
+ cy.signIn("nodata");
+ cy.visit("/");
+ H.newButton().click();
+ H.popover().within(() => {
+ cy.findByText("Dashboard").should("be.visible");
+ cy.findByText("Question").should("not.exist");
+ });
+ });
+ });
+});
+
+function sandboxProductsOnCategory() {
+ cy.sandboxTable({
+ table_id: PRODUCTS_ID,
+ attribute_remappings: {
+ attr_cat: ["dimension", ["field", PRODUCTS.CATEGORY, null]],
+ },
+ });
+}
+
+function popoverByIndex(index: number) {
+ return H.popover().should("have.length", 2).eq(index);
+}
+
+function librarySidebarSection() {
+ return H.navigationSidebar().findByRole("section", { name: "Library" });
+}
+
+function assertPermissionError() {
+ H.main()
+ .findByText("Sorry, you don’t have permission to see that.")
+ .should("be.visible");
+}
+
+function assertQueryPermissionError() {
+ H.main()
+ .findByText("Sorry, you don't have permission to run this query.")
+ .should("be.visible");
+}
diff --git a/e2e/test/scenarios/navigation/navbar.cy.spec.js b/e2e/test/scenarios/navigation/navbar.cy.spec.js
index 9ed0431fc12..c7ff8996592 100644
--- a/e2e/test/scenarios/navigation/navbar.cy.spec.js
+++ b/e2e/test/scenarios/navigation/navbar.cy.spec.js
@@ -148,4 +148,24 @@ describe("scenarios > navigation > navbar", () => {
H.navigationSidebar().should("not.be.visible");
});
});
+
+ describe("library", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ });
+
+ it("should show the library when a table is published", () => {
+ H.createLibrary();
+ H.publishTables({ table_ids: [ORDERS_ID] });
+ cy.visit("/");
+ H.navigationSidebar()
+ .findByRole("section", { name: "Library" })
+ .findByText("Data")
+ .click();
+ H.collectionTable().findByText("Orders").click();
+ H.queryBuilderHeader().findByText("Orders").should("be.visible");
+ });
+ });
});
diff --git a/e2e/test/scenarios/question/notebook-data-source.cy.spec.ts b/e2e/test/scenarios/question/notebook-data-source.cy.spec.ts
index bef6c453b74..d09fe3468d7 100644
--- a/e2e/test/scenarios/question/notebook-data-source.cy.spec.ts
+++ b/e2e/test/scenarios/question/notebook-data-source.cy.spec.ts
@@ -9,7 +9,7 @@ import {
import type { StructuredQuestionDetails } from "e2e/support/helpers";
import { checkNotNull } from "metabase/lib/types";
-const { ORDERS_ID, REVIEWS_ID } = SAMPLE_DATABASE;
+const { ORDERS_ID, PRODUCTS_ID, REVIEWS_ID } = SAMPLE_DATABASE;
describe("scenarios > notebook > data source", () => {
describe("empty app db", () => {
@@ -195,6 +195,85 @@ describe("scenarios > notebook > data source", () => {
});
});
+ describe("library table as a source", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ H.createLibrary();
+ });
+
+ it("should allow to pick a published table from the mini picker", () => {
+ H.publishTables({ table_ids: [ORDERS_ID, PRODUCTS_ID] });
+ H.startNewQuestion();
+
+ cy.log("verify the picker when nothing is selected");
+ H.popover().findByText("Orders").click();
+ H.join();
+ H.popover().findByText("Products").click();
+ H.visualize();
+ H.tableHeaderColumn("User ID").should("be.visible");
+ H.tableHeaderColumn("Products → ID").should("be.visible");
+
+ cy.log("verify the picker when there is a selected item");
+ H.openNotebook();
+ H.getNotebookStep("data").findByText("Orders").click();
+ H.popover().findByText("Products").click();
+ H.getNotebookStep("data").findByText("Products").should("be.visible");
+ });
+
+ it("should allow to pick a publish table from the data picker", () => {
+ H.publishTables({ table_ids: [ORDERS_ID, PRODUCTS_ID] });
+ H.startNewQuestion();
+
+ cy.log("verify the picker when nothing is selected");
+ H.popover().findByText("Browse all").click();
+ H.entityPickerModal().within(() => {
+ H.entityPickerModalLevel(0).findByText("Library").click();
+ H.entityPickerModalLevel(1).findByText("Data").click();
+ cy.findByText("Orders").click();
+ });
+
+ H.join();
+ H.popover().findByText("Browse all").click();
+ H.entityPickerModal().within(() => {
+ H.entityPickerModalTab("Data").click();
+ H.entityPickerModalLevel(0).findByText("Library").click();
+ H.entityPickerModalLevel(1).findByText("Data").click();
+ cy.findByText("Products").click();
+ });
+
+ H.visualize();
+ H.tableHeaderColumn("User ID").should("be.visible");
+ H.tableHeaderColumn("Products → ID").should("be.visible");
+
+ H.openNotebook();
+ H.getNotebookStep("data").findByText("Orders").click();
+ H.popover().within(() => {
+ cy.findByText("Data").click();
+ cy.findByText("Browse all").click();
+ });
+
+ H.entityPickerModal().within(() => {
+ H.entityPickerModalItem(0, "Library").should(
+ "have.attr",
+ "data-active",
+ "true",
+ );
+ H.entityPickerModalItem(1, "Data").should(
+ "have.attr",
+ "data-active",
+ "true",
+ );
+ H.entityPickerModalItem(2, "Orders").should(
+ "have.attr",
+ "data-active",
+ "true",
+ );
+ });
+ });
+ });
+
describe("saved entity as a source (aka the virtual table)", () => {
const modelDetails: StructuredQuestionDetails = {
name: "GUI Model",
diff --git a/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.ts b/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.ts
index b60e16486e8..7849d511443 100644
--- a/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.ts
+++ b/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.ts
@@ -478,7 +478,6 @@ describe("scenarios > notebook > link to data source", () => {
},
});
- // @ts-expect-error - Non-trivial types in `sandboxTable` that should be addressed separately
cy.sandboxTable({
table_id: ORDERS_ID,
attribute_remappings: {
diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj
index d34407fdff0..03d4faf201c 100644
--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj
+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj
@@ -54,17 +54,20 @@
(:id table)))
(defn with-advanced-permissions
- "Adds to `user` a set of boolean flag indiciate whether or not current user has access to an advanced permissions.
- This function is meant to be used for GET /api/user/current "
+ "Adds to `user` a set of boolean flags indicating whether or not current user has access to advanced permissions.
+ This function is meant to be used for GET /api/user/current.
+ Note: `:can_create_queries` and `:can_create_native_queries` are set by `add-query-permissions` before this
+ function is called, so we don't need to set them here."
[user]
- (let [permissions-set @api/*current-user-permissions-set*]
- (assoc user :permissions
- {:can_access_setting (perms/set-has-application-permission-of-type? permissions-set :setting)
+ (let [permissions-set @api/*current-user-permissions-set*
+ user-id api/*current-user-id*]
+ (update user :permissions assoc
+ :can_access_setting (perms/set-has-application-permission-of-type? permissions-set :setting)
:can_access_subscription (perms/set-has-application-permission-of-type? permissions-set :subscription)
:can_access_monitoring (perms/set-has-application-permission-of-type? permissions-set :monitoring)
- :can_access_data_model (perms/user-has-any-perms-of-type? api/*current-user-id* :perms/manage-table-metadata)
- :can_access_db_details (perms/user-has-any-perms-of-type? api/*current-user-id* :perms/manage-database)
- :is_group_manager api/*is-group-manager?*})))
+ :can_access_data_model (perms/user-has-any-perms-of-type? user-id :perms/manage-table-metadata)
+ :can_access_db_details (perms/user-has-any-perms-of-type? user-id :perms/manage-database)
+ :is_group_manager api/*is-group-manager?*)))
(defenterprise current-user-has-application-permissions?
"Check if `*current-user*` has permissions for a application permissions of type `perm-type`."
diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj b/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj
index cb70a6134aa..ef18f476e7c 100644
--- a/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj
+++ b/enterprise/backend/src/metabase_enterprise/audit_app/pages/queries.clj
@@ -49,7 +49,7 @@
:select [[:card.id :card_id]
[:card.name :card_name]
[error-substr :error_substr]
- :collection_id
+ [:card.collection_id :collection_id]
[coll-name :collection_name]
:card.database_id
[:db.name :database_name]
diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
index 571a7b0e39f..49f8a81fac2 100644
--- a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
+++ b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj
@@ -1,22 +1,20 @@
(ns metabase-enterprise.data-studio.api.table
"/api/ee/data-studio/table endpoints for bulk table operations."
(:require
+ [clojure.set :as set]
[clojure.string :as str]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
- [metabase.collections.core :as collections]
+ [metabase.collections.core :as collection]
[metabase.database-routing.core :as database-routing]
[metabase.driver.settings :as driver.settings]
[metabase.driver.util :as driver.u]
[metabase.events.core :as events]
- [metabase.lib-be.core :as lib-be]
- [metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
- [metabase.queries.core :as queries]
[metabase.request.core :as request]
[metabase.sync.core :as sync]
[metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.jvm :as u.jvm]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
@@ -24,8 +22,7 @@
[metabase.util.malli.schema :as ms]
[metabase.util.quick-task :as quick-task]
[metabase.warehouse-schema.models.table :as table]
- [toucan2.core :as t2]
- [toucan2.realize :as t2.realize]))
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -49,12 +46,109 @@
(mr/def ::data-layers
(into [:enum {:decode/string keyword}] table/data-layers))
+;;; ------------------------------------------------ Remapping Graph Traversal ------------------------------------------------
+
+(defn- remapped-table-ids
+ "Find tables connected via FK remapping (Dimensions).
+ `input-field` and `output-field` are field aliases (:source_field or :target_field).
+ Returns table IDs from `output-field` that are connected to `tables` via `input-field`.
+ `tables` can be a set of table IDs or a HoneySQL subquery map."
+ [input-field output-field tables]
+ (if (empty? tables)
+ #{}
+ (let [input-table-id (keyword (name input-field) "table_id")
+ output-table-id (keyword (name output-field) "table_id")]
+ (into #{} (map :table_id)
+ (t2/reducible-query {:select [[output-table-id :table_id]]
+ :from [[(t2/table-name :model/Dimension) :dim]]
+ :join [[(t2/table-name :model/Field) :source_field]
+ [:= :dim.field_id :source_field.id]
+ [(t2/table-name :model/Field) :target_field]
+ [:= :dim.human_readable_field_id :target_field.id]]
+ :where [:and
+ [:= :dim.type "external"]
+ [:in input-table-id tables]
+ [:not [:in output-table-id tables]]]})))))
+
+(defn- upstream-table-ids
+ "Given a table selector (set of IDs or subquery), find all tables that these tables depend on
+ via FK remapping (Dimensions)."
+ [source-tables]
+ (remapped-table-ids :source_field :target_field source-tables))
+
+(defn- downstream-table-ids
+ "Given a table selector (set of IDs or subquery), find all tables that depend on these tables
+ via FK remapping (Dimensions)."
+ [target-tables]
+ (remapped-table-ids :target_field :source_field target-tables))
+
+(defn- table-subquery
+ "Create a subquery that selects table IDs matching the given WHERE clause."
+ [where]
+ {:select [:id] :from [(t2/table-name :model/Table)] :where where})
+
+(defn- traverse-graph
+ "Recursively traverse the remapping graph starting from initial-ids.
+ Returns all reachable table IDs (including initial-ids)."
+ [neighbors-fn initial-ids]
+ (loop [visited initial-ids
+ frontier initial-ids]
+ (let [new-neighbors (set/difference (neighbors-fn frontier) visited)]
+ (if (empty? new-neighbors)
+ visited
+ (recur (set/union visited new-neighbors)
+ new-neighbors)))))
+
+(defn- all-upstream-table-ids
+ "Get all upstream table IDs recursively for tables matching the given WHERE clause.
+ The first hop uses a subquery to avoid materializing potentially millions of IDs;
+ subsequent hops use IDs since remappings are rare."
+ [source-table-where]
+ (let [initial-ids (upstream-table-ids (table-subquery source-table-where))]
+ (if (empty? initial-ids)
+ #{}
+ (traverse-graph upstream-table-ids initial-ids))))
+
+(defn- all-downstream-table-ids
+ "Get all downstream table IDs recursively for tables matching the given WHERE clause.
+ The first hop uses a subquery to avoid materializing potentially millions of IDs;
+ subsequent hops use IDs since remappings are rare."
+ [target-table-where]
+ (let [initial-ids (downstream-table-ids (table-subquery target-table-where))]
+ (if (empty? initial-ids)
+ #{}
+ (traverse-graph downstream-table-ids initial-ids))))
+
(mr/def ::data-sources
(into [:enum {:decode/string keyword}] table/data-sources))
(mr/def ::data-authorities
(into [:enum {:decode/string keyword}] table/writable-data-authority-types))
+;;; ------------------------------------------------ Response Schemas ------------------------------------------------
+
+(mr/def ::bulk-table-info
+ "Schema for table info in bulk operations. Matches frontend BulkTableInfo type."
+ [:map
+ [:id ms/PositiveInt]
+ [:db_id ms/PositiveInt]
+ [:name :string]
+ [:display_name :string]
+ [:schema [:maybe :string]]
+ [:is_published :boolean]])
+
+(mr/def ::bulk-table-selection-info
+ "Schema for /selection endpoint response. Matches frontend BulkTableSelectionInfo type."
+ [:map
+ [:selected_table [:maybe ::bulk-table-info]]
+ [:published_downstream_tables [:sequential ::bulk-table-info]]
+ [:unpublished_upstream_tables [:sequential ::bulk-table-info]]])
+
+(mr/def ::publish-tables-response
+ "Schema for /publish-tables endpoint response. Matches frontend PublishTablesResponse type."
+ [:map
+ [:target_collection [:maybe (ms/InstanceOf :model/Collection)]]])
+
(defn- sync-unhidden-tables
"Function to call on newly unhidden tables. Starts a thread to sync all tables. Groups tables by database to
efficiently sync tables from different databases."
@@ -80,11 +174,7 @@
(sync-unhidden-tables (when (and (contains? body :data_layer) (not= :copper data_layer))
(filter #(= :copper (:data_layer %)) existing-tables))))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/edit"
+(api.macros/defendpoint :post "/edit" :- [:map {:closed true}]
"Bulk updating tables."
[_route-params
_query-params
@@ -114,63 +204,74 @@
(maybe-sync-unhidden-tables! existing-tables set-map))
{}))
-(defn- table->published-model
- [{:keys [id name db_id] :as _table} creator-id collection-id]
- {:name (format "Model based on %s" name)
- :description (format "Base model for table %s " name)
- :dataset_query (let [mp (lib-be/application-database-metadata-provider db_id)]
- (lib/query mp (lib.metadata/table mp id)))
- :type :model
- :display :table
- :visualization_settings {}
- :creator_id creator-id
- :collection_id collection-id
- :published_table_id id})
-
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/publish-model"
- "Create a model for each of selected tables"
+(api.macros/defendpoint :post "/selection" :- ::bulk-table-selection-info
+ "Gets information about selected tables"
[_route-params
_query-params
- {:keys [target_collection_id]
- :as body}
- :- [:merge
- ::table-selectors
- [:map
- [:target_collection_id [:maybe [:or pos-int? [:= "library"]]]]]]]
+ body :- ::table-selectors]
+ (api/check-superuser)
+ (let [fields [:model/Table :id :db_id :name :display_name :schema :is_published]
+ where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))
+ selected-tables (t2/select fields {:where where :limit 2})
+ selected-table (when-not (next selected-tables)
+ (first selected-tables))
+ upstream-ids (all-upstream-table-ids where)
+ downstream-ids (all-downstream-table-ids where)
+ upstream-tables (when (seq upstream-ids)
+ (t2/select fields :id [:in upstream-ids]))
+ downstream-tables (when (seq downstream-ids)
+ (t2/select fields :id [:in downstream-ids]))]
+ {:selected_table selected-table
+ :published_downstream_tables (filterv :is_published downstream-tables)
+ :unpublished_upstream_tables (filterv (complement :is_published) upstream-tables)}))
+
+(api.macros/defendpoint :post "/publish-tables" :- ::publish-tables-response
+ "Set collection for each of selected tables and all upstream dependencies recursively."
+ [_route-params
+ _query-params
+ body :- ::table-selectors]
(api/check-superuser)
- (let [target-collection (cond
- (= "library" target_collection_id) (api/check-403 (collections/remote-synced-collection))
- (nil? target_collection_id) nil
- :else (api/check-404 (t2/select-one :model/Collection target_collection_id)))
+ (let [target-collection (api/let-404 [colls (seq (t2/select :model/Collection
+ :type collection/library-models-collection-type
+ {:limit 2}))]
+ (if (next colls)
+ (throw (ex-info (tru "Multiple library-models collections found.")
+ {:status-code 409}))
+ (first colls)))
where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))
- created-models (t2/with-transaction [_conn]
- (into []
- (comp
- (map t2.realize/realize)
- (partition-all 20)
- (mapcat (fn [batch]
- (mapv (fn [table]
- (queries/create-card! (table->published-model table api/*current-user-id* (:id target-collection)) @api/*current-user*))
- batch))))
- (t2/reducible-select :model/Table :active true {:where where})))]
- {:created_count (count created-models)
- :models created-models
- :target_collection target-collection}))
+ upstream-ids (all-upstream-table-ids where)
+ update-where (if (seq upstream-ids)
+ [:or where [:in :id upstream-ids]]
+ where)]
+ (t2/query {:update (t2/table-name :model/Table)
+ :set {:collection_id (:id target-collection)
+ :is_published true}
+ :where update-where})
+ {:target_collection target-collection}))
+
+(api.macros/defendpoint :post "/unpublish-tables" :- :nil
+ "Unset collection for each of selected tables and all downstream dependents recursively."
+ [_route-params
+ _query-params
+ body :- ::table-selectors]
+ (api/check-superuser)
+ (let [where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))
+ downstream-ids (all-downstream-table-ids where)
+ update-where (if (seq downstream-ids)
+ [:or where [:in :id downstream-ids]]
+ where)]
+ (t2/query {:update (t2/table-name :model/Table)
+ :set {:collection_id nil
+ :is_published false}
+ :where update-where})
+ nil))
(defn- sync-schema-async!
[table user-id]
(events/publish-event! :event/table-manual-sync {:object table :user-id user-id})
(quick-task/submit-task! #(database-routing/with-database-routing-off (sync/sync-table! table))))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/sync-schema"
+(api.macros/defendpoint :post "/sync-schema" :- :nil
"Batch version of /table/:id/sync_schema. Takes an abstract table selection as /table/edit does.
- Currently checks policy before returning (so you might receive a 4xx on e.g. AuthZ policy failure)
- The sync itself is however, asyncronous. This call may return before all tables synced."
@@ -189,14 +290,9 @@
(log/warn (u/format-color :red "Cannot connect to database '%s' in order to sync tables" (:name database)))
(throw (ex-info (ex-message e) {:status-code 422})))))
(doseq [table tables]
- (sync-schema-async! table api/*current-user-id*))
- {:status :ok}))
-
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/rescan-values"
+ (sync-schema-async! table api/*current-user-id*))))
+
+(api.macros/defendpoint :post "/rescan-values" :- :nil
"Batch version of /table/:id/rescan_values. Takes an abstract table selection as /table/edit does."
[_
_
@@ -207,14 +303,9 @@
(doseq [table tables]
(events/publish-event! :event/table-manual-scan {:object table :user-id api/*current-user-id*})
(request/as-admin
- (quick-task/submit-task! #(sync/update-field-values-for-table! table))))
- {:status :ok}))
-
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/discard-values"
+ (quick-task/submit-task! #(sync/update-field-values-for-table! table))))))
+
+(api.macros/defendpoint :post "/discard-values" :- :nil
"Batch version of /table/:id/discard_values. Takes an abstract table selection as /table/edit does."
[_
_
@@ -225,7 +316,7 @@
:from [(t2/table-name :model/Field)]
:where [:in :table_id (map :id tables)]}]
(t2/delete! (t2/table-name :model/FieldValues) :field_id [:in field-ids-to-delete-q]))
- {:status :ok}))
+ nil))
(def ^{:arglists '([request respond raise])} routes
"`/api/ee/data-studio/table` routes."
diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj
new file mode 100644
index 00000000000..09116074442
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj
@@ -0,0 +1,48 @@
+(ns metabase-enterprise.data-studio.permissions.published-tables
+ "Enterprise implementation of published table permissions.
+ Provides query access to published tables via collection permissions."
+ (:require
+ [metabase.collections.models.collection :as collection]
+ [metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [toucan2.core :as t2]))
+
+(defenterprise user-published-table-permission
+ "Returns :query-builder permission if table is published and user has collection access.
+ Tables published into the root collection (collection_id=nil) are accessible to all users."
+ :feature :data-studio
+ [perm-type table-id]
+ (when (and (= perm-type :perms/create-queries)
+ (t2/exists? :model/Table
+ {:where [:and
+ [:= :id table-id]
+ [:= :is_published true]
+ (collection/visible-collection-filter-clause :collection_id)]}))
+ :query-builder))
+
+(defenterprise user-has-any-published-table-permission?
+ "Returns true if user has access to any published table via collection permissions."
+ :feature :data-studio
+ []
+ (t2/exists? :model/Table
+ {:where [:and
+ [:= :is_published true]
+ (collection/visible-collection-filter-clause :collection_id)]}))
+
+(defenterprise user-has-published-table-permission-for-database?
+ "Returns true if user has access to any published table in the given database via collection permissions."
+ :feature :data-studio
+ [database-id]
+ (t2/exists? :model/Table
+ {:where [:and
+ [:= :db_id database-id]
+ [:= :is_published true]
+ (collection/visible-collection-filter-clause :collection_id)]}))
+
+(defenterprise can-access-via-collection?
+ "Returns true if the user can access this published table via collection read permissions."
+ :feature :data-studio
+ [table]
+ (when (:is_published table)
+ (mi/current-user-has-full-permissions? (perms/perms-objects-set-for-parent-collection table :read))))
diff --git a/enterprise/backend/src/metabase_enterprise/library/api.clj b/enterprise/backend/src/metabase_enterprise/library/api.clj
index 190de66c75b..63e33bb2d13 100644
--- a/enterprise/backend/src/metabase_enterprise/library/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/library/api.clj
@@ -26,14 +26,15 @@
(defn- add-here-and-below [collection]
(let [descendent-ids (map :id (collection/descendants-flat collection))
- below (t2/select-fn-set :type [:model/Card :type] :collection_id [:in descendent-ids])]
+ below-card-types (t2/select-fn-set :type [:model/Card :type] :collection_id [:in descendent-ids])
+ below-tables? (t2/exists? :model/Table :is_published true :collection_id [:in descendent-ids])]
;; This function is only used on the root Library which cannot have items directly in it
;; So can assume :here is only collection, and all descendants are :below
(assoc collection :here #{:collection}
- :below (cond-> below
- (contains? below :model)
+ :below (cond-> below-card-types
+ (contains? below-card-types :model)
(-> (disj :model) (conj :dataset))
-
+ below-tables? (conj :table)
true sort))))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
index f7c6995fef3..41e14abe5ff 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj
@@ -27,22 +27,22 @@
(-> (mt/user-http-request user :get 200 "user/current")
:permissions))]
(testing "admins should have full advanced permisions"
- (is (= {:can_access_setting true
- :can_access_subscription true
- :can_access_monitoring true
- :can_access_data_model true
- :is_group_manager false
- :can_access_db_details true}
- (user-permissions :crowberto))))
+ (is (=? {:can_access_setting true
+ :can_access_subscription true
+ :can_access_monitoring true
+ :can_access_data_model true
+ :is_group_manager false
+ :can_access_db_details true}
+ (user-permissions :crowberto))))
(testing "non-admin users should only have subscriptions enabled by default"
- (is (= {:can_access_setting false
- :can_access_subscription true
- :can_access_monitoring false
- :can_access_data_model false
- :is_group_manager false
- :can_access_db_details false}
- (user-permissions :rasta))))
+ (is (=? {:can_access_setting false
+ :can_access_subscription true
+ :can_access_monitoring false
+ :can_access_data_model false
+ :is_group_manager false
+ :can_access_db_details false}
+ (user-permissions :rasta))))
(testing "can_access_data_model is true if a user has any data model perms"
(let [[id-1 id-2 id-3 id-4] (map u/the-id (database/tables (mt/db)))]
@@ -60,6 +60,23 @@
(is (partial= {:can_access_db_details true}
(user-permissions :rasta)))))))))
+(deftest current-user-query-permissions-published-table-test
+ (testing "GET /api/user/current can_create_queries respects published tables"
+ (mt/with-premium-features #{:data-studio}
+ (letfn [(user-permissions [user]
+ (-> (mt/user-http-request user :get 200 "user/current")
+ :permissions))]
+ (testing "user with collection permission on published table should have can_create_queries true"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Table _table {:db_id (mt/id)
+ :is_published true
+ :collection_id (:id collection)}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) (:id collection))
+ (mt/with-no-data-perms-for-all-users!
+ (is (partial= {:can_create_queries true
+ :can_create_native_queries false}
+ (user-permissions :rasta))))))))))
+
(deftest new-database-view-data-permission-level-test
(mt/with-additional-premium-features #{:sandboxes :advanced-permissions}
(mt/with-temp [:model/Database {db-id :id} {}
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
new file mode 100644
index 00000000000..7c9cd852f4c
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/collection_test.clj
@@ -0,0 +1,129 @@
+(ns metabase-enterprise.data-studio.api.collection-test
+ "Tests for published tables appearing in collection items API."
+ (:require
+ [clojure.test :refer :all]
+ [metabase.permissions.core :as perms]
+ [metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(deftest collection-items-table-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "GET /api/collection/:id/items"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card _ {:collection_id (u/the-id collection)
+ :name "a-card"}
+ :model/Table {table-id :id :as table} {:collection_id (u/the-id collection)
+ :is_published true}
+ :model/Table {root-table-id :id :as root-table} {:is_published true}]
+ (testing "table items appear in collection items"
+ (let [items (:data (mt/user-http-request :crowberto :get 200
+ (str "collection/" (u/the-id collection) "/items")))]
+ (is (=? [{:id table-id
+ :name (:display_name table)
+ :model "table"
+ :database_id (mt/id)
+ :archived false}]
+ (filter #(= "table" (:model %)) items)))))
+ (testing "table items appear in root collection items"
+ (let [items (:data (mt/user-http-request :crowberto :get 200 "collection/root/items"))]
+ (is (=? [{:id root-table-id
+ :name (:display_name root-table)
+ :model "table"
+ :database_id (mt/id)
+ :archived false}]
+ (filter #(= "table" (:model %)) items)))))
+ (testing "tables don't appear when archived=true"
+ (let [items (mt/user-http-request :crowberto :get 200
+ (str "collection/" (u/the-id collection) "/items")
+ :archived true)]
+ (is (empty? (filter #(= "table" (:model %)) (:data items))))))
+ (testing "tables don't appear when pinned_state=is_pinned"
+ (let [items (mt/user-http-request :crowberto :get 200
+ (str "collection/" (u/the-id collection) "/items")
+ :pinned_state "is_pinned")]
+ (is (empty? (filter #(= "table" (:model %)) (:data items))))))
+ (testing "tables appear when pinned_state=is_not_pinned"
+ (let [items (mt/user-http-request :crowberto :get 200
+ (str "collection/" (u/the-id collection) "/items")
+ :pinned_state "is_not_pinned")]
+ (is (= 1 (count (filter #(= "table" (:model %)) (:data items)))))))))))
+
+(deftest collection-items-table-permissions-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "GET /api/collection/:id/items - published tables only require collection read permissions"
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/Collection collection {}
+ :model/Table {table-id :id :as table} {:collection_id (u/the-id collection)
+ :is_published true}
+ :model/PermissionsGroup {group-id :id} {}]
+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)
+ (t2/delete! :model/DataPermissions :db_id (mt/id))
+ (perms/grant-collection-read-permissions! (perms/all-users-group) collection)
+ (testing "with collection read but NO data permissions, user should see published table"
+ (data-perms/set-database-permission! group-id (mt/id) :perms/view-data :blocked)
+ (data-perms/set-database-permission! group-id (mt/id) :perms/create-queries :no)
+ (let [items (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" (u/the-id collection) "/items")))]
+ (is (=? [{:id table-id
+ :name (:display_name table)
+ :model "table"
+ :database_id (mt/id)
+ :archived false}]
+ (filter #(= "table" (:model %)) items))
+ "User with collection read permissions should see published tables (even without data permissions)")))
+ (testing "with collection read AND data permissions, user should still see published table"
+ (data-perms/set-table-permission! group-id table :perms/view-data :unrestricted)
+ (data-perms/set-table-permission! group-id table :perms/create-queries :query-builder)
+ (let [items (:data (mt/user-http-request :rasta :get 200
+ (str "collection/" (u/the-id collection) "/items")))]
+ (is (=? [{:id table-id
+ :name (:display_name table)
+ :model "table"
+ :database_id (mt/id)
+ :archived false}]
+ (filter #(= "table" (:model %)) items))
+ "User with both collection and data permissions should see published tables"))))))
+ (testing "GET /api/collection/:id/items - without collection read permission, user should NOT see published table"
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/Collection collection {}
+ :model/Table table {:collection_id (u/the-id collection)
+ :is_published true}
+ :model/PermissionsGroup {group-id :id} {}]
+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)
+ (t2/delete! :model/DataPermissions :db_id (mt/id))
+ (perms/revoke-collection-permissions! (perms/all-users-group) collection)
+ (data-perms/set-table-permission! group-id table :perms/view-data :unrestricted)
+ (data-perms/set-table-permission! group-id table :perms/create-queries :query-builder)
+ (testing "user cannot access collection at all without collection permissions"
+ (mt/user-http-request :rasta :get 403 (str "collection/" (u/the-id collection) "/items"))))))
+ (testing "GET /api/collection/root/items - published tables in root do NOT require data permissions"
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/Table {table-id :id :as table} {:collection_id nil
+ :is_published true}
+ :model/PermissionsGroup {group-id :id} {}]
+ (perms/add-user-to-group! (mt/user->id :rasta) group-id)
+ (t2/delete! :model/DataPermissions :db_id (mt/id))
+ (testing "with NO data permissions, user should see published table in root"
+ (data-perms/set-database-permission! group-id (mt/id) :perms/view-data :blocked)
+ (data-perms/set-database-permission! group-id (mt/id) :perms/create-queries :no)
+ (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items"))]
+ (is (=? [{:id table-id
+ :name (:display_name table)
+ :model "table"
+ :database_id (mt/id)
+ :archived false}]
+ (filter #(= table-id (:id %)) (filter #(= "table" (:model %)) items)))
+ "Users should see published tables in root collection (even without data permissions)")))
+ (testing "with data permissions, user should still see published table in root"
+ (data-perms/set-table-permission! group-id table :perms/view-data :unrestricted)
+ (data-perms/set-table-permission! group-id table :perms/create-queries :query-builder)
+ (let [items (:data (mt/user-http-request :rasta :get 200 "collection/root/items"))]
+ (is (=? [{:id table-id
+ :name (:display_name table)
+ :model "table"
+ :database_id (mt/id)
+ :archived false}]
+ (filter #(= table-id (:id %)) (filter #(= "table" (:model %)) items)))
+ "User with data permissions should see published tables in root"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/query_metadata_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/query_metadata_test.clj
new file mode 100644
index 00000000000..fa06de24d1c
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/query_metadata_test.clj
@@ -0,0 +1,144 @@
+(ns metabase-enterprise.data-studio.api.query-metadata-test
+ "Tests for published table query_metadata API access via collection permissions."
+ (:require
+ [clojure.test :refer :all]
+ [metabase.permissions.core :as perms]
+ [metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.test :as mt]
+ [metabase.util :as u]))
+
+(deftest table-query-metadata-collection-permissions-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "GET /api/table/:id/query_metadata"
+ (testing "Published tables in collections should be accessible with collection read permission (no data permissions)"
+ (mt/with-temp [:model/Collection coll {}
+ :model/Database db {}
+ :model/Table table {:db_id (u/the-id db) :is_published true :collection_id (u/the-id coll)}
+ :model/Field _field-1 {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
+ :model/Field _field-2 {:table_id (u/the-id table) :name "name" :base_type :type/Text}
+ :model/PermissionsGroup {group-id :id} {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id group-id}]
+ (mt/with-no-data-perms-for-all-users!
+ (perms/grant-collection-read-permissions! group-id (u/the-id coll))
+ (let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (u/the-id table)))]
+ (is (some? response))
+ (is (= (u/the-id table) (:id response)))
+ (is (= 2 (count (:fields response))))))))
+
+ (testing "Published tables in root collection should be accessible with root collection read permission"
+ (mt/with-temp [:model/Database db {}
+ :model/Table table {:db_id (u/the-id db) :is_published true :collection_id nil}
+ :model/Field _field-1 {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
+ :model/PermissionsGroup {group-id :id} {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id group-id}]
+ (mt/with-no-data-perms-for-all-users!
+ (let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (u/the-id table)))]
+ (is (some? response))
+ (is (= (u/the-id table) (:id response)))))))
+
+ (testing "Unpublished tables require data permissions"
+ (mt/with-temp [:model/Database db {}
+ :model/Table table {:db_id (u/the-id db) :is_published false}
+ :model/Field _field-1 {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
+ :model/PermissionsGroup {group-id :id} {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id group-id}]
+ (mt/with-no-data-perms-for-all-users!
+ (testing "User without data permissions cannot access unpublished tables"
+ (data-perms/set-database-permission! group-id db :perms/view-data :blocked)
+ (data-perms/set-database-permission! group-id db :perms/create-queries :no)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 (format "table/%d/query_metadata" (u/the-id table))))))
+
+ (testing "Data permissions ARE required for unpublished tables"
+ (data-perms/set-database-permission! group-id db :perms/view-data :unrestricted)
+ (data-perms/set-database-permission! group-id db :perms/create-queries :query-builder)
+ (let [response (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (u/the-id table)))]
+ (is (some? response))
+ (is (= (u/the-id table) (:id response)))))))))))
+
+(deftest table-card-query-metadata-published-table-collection-perms-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "GET /api/table/card__:id/query_metadata"
+ (testing "Should include Field metadata for published tables accessible via collection permissions"
+ (mt/with-temp [:model/Collection table-coll {}
+ :model/Table table {:is_published true :collection_id (u/the-id table-coll)}
+ :model/Field field {:table_id (u/the-id table) :name "test-field"}
+ :model/Card card {:dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (u/the-id table)}}
+ :result_metadata [{:id (u/the-id field) :name "test-field"}]}
+ :model/PermissionsGroup custom-group {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta)
+ :group_id (u/the-id custom-group)}]
+ (data-perms/set-database-permission! custom-group (mt/id) :perms/view-data :blocked)
+ (perms/grant-collection-read-permissions! custom-group (u/the-id table-coll))
+ (is (=? {:fields [{:id (u/the-id field) :name "test-field"}]}
+ (mt/user-http-request :rasta :get 200 (format "table/card__%d/query_metadata" (u/the-id card))))))))))
+
+(deftest card-query-metadata-published-table-collection-perms-test
+ (testing "GET /api/card/:id/query_metadata should include published tables accessible via collection permissions"
+ (mt/with-premium-features #{:data-studio}
+ (mt/with-temp [:model/Collection table-coll {}
+ :model/Database db {}
+ :model/Table table {:db_id (u/the-id db) :is_published true :collection_id (u/the-id table-coll)}
+ :model/Field _field {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
+ :model/Collection card-coll {}
+ :model/Card card {:collection_id (u/the-id card-coll)
+ :dataset_query {:database (u/the-id db)
+ :type :query
+ :query {:source-table (u/the-id table)}}}
+ :model/PermissionsGroup {group-id :id} {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id group-id}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! group-id db :perms/view-data :blocked)
+ (data-perms/set-database-permission! group-id db :perms/create-queries :no)
+ (perms/grant-collection-read-permissions! group-id (u/the-id table-coll))
+ (perms/grant-collection-read-permissions! group-id (u/the-id card-coll))
+ (testing "User with collection read (no data perms) can access card query_metadata with published table"
+ (let [metadata (mt/user-http-request :rasta :get 200 (str "card/" (u/the-id card) "/query_metadata"))]
+ (is (map? metadata))
+ (is (seq (:tables metadata)) "Should include tables")
+ (is (some #(= (u/the-id table) (:id %)) (:tables metadata))
+ "Should include the published table"))))))))
+
+(deftest dashboard-query-metadata-published-table-collection-perms-test
+ (testing "GET /api/dashboard/:id/query_metadata should include published tables accessible via collection permissions"
+ (mt/with-premium-features #{:data-studio}
+ (mt/with-temp [:model/Collection table-coll {}
+ :model/Database db {}
+ :model/Table table {:db_id (u/the-id db) :is_published true :collection_id (u/the-id table-coll)}
+ :model/Field _field {:table_id (u/the-id table) :name "id" :base_type :type/Integer :semantic_type :type/PK}
+ :model/Collection card-coll {}
+ :model/Card card {:collection_id (u/the-id card-coll)
+ :dataset_query {:database (u/the-id db)
+ :type :query
+ :query {:source-table (u/the-id table)}}}
+ :model/Dashboard dash {:collection_id (u/the-id card-coll)}
+ :model/DashboardCard _ {:dashboard_id (u/the-id dash) :card_id (u/the-id card)}
+ :model/PermissionsGroup {group-id :id} {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta) :group_id group-id}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! group-id db :perms/view-data :blocked)
+ (data-perms/set-database-permission! group-id db :perms/create-queries :no)
+ (perms/grant-collection-read-permissions! group-id (u/the-id table-coll))
+ (perms/grant-collection-read-permissions! group-id (u/the-id card-coll))
+ (testing "User with collection read (no data perms) can access dashboard query_metadata with published table"
+ (let [metadata (mt/user-http-request :rasta :get 200 (str "dashboard/" (u/the-id dash) "/query_metadata"))]
+ (is (map? metadata))
+ (is (seq (:tables metadata)) "Should include tables")
+ (is (some #(= (u/the-id table) (:id %)) (:tables metadata))
+ "Should include the published table"))))))))
+
+(deftest automagic-dashboards-query-metadata-published-table-collection-perms-test
+ (testing "GET /api/automagic-dashboards/:entity/:entity-id-or-query/query_metadata"
+ (testing "Should include published tables accessible via collection permissions"
+ (mt/with-premium-features #{:data-studio}
+ (mt/with-temp [:model/Collection table-coll {}
+ :model/Table table {:is_published true :collection_id (u/the-id table-coll)}
+ :model/PermissionsGroup custom-group {}
+ :model/PermissionsGroupMembership _ {:user_id (mt/user->id :rasta)
+ :group_id (u/the-id custom-group)}]
+ (perms/set-database-permission! custom-group (mt/id) :perms/view-data :blocked)
+ (perms/grant-collection-read-permissions! custom-group (u/the-id table-coll))
+ (is (=? {:tables [{:id (u/the-id table)}]}
+ (mt/user-http-request :rasta :get 200 (str "automagic-dashboards/table/" (u/the-id table) "/query_metadata")))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
index b98d0c116cb..dc6b2959bba 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
@@ -3,86 +3,63 @@
(:require
[clojure.test :refer :all]
[metabase-enterprise.data-studio.api.table :as api.table]
+ [metabase.collections.models.collection :as collection]
+ [metabase.collections.test-helpers :refer [without-library]]
[metabase.sync.core :as sync]
[metabase.test :as mt]
- [metabase.util :as u]
+ [metabase.test.fixtures :as fixtures]
[toucan2.core :as t2])
(:import (java.util.concurrent CountDownLatch TimeUnit)))
(set! *warn-on-reflection* true)
-(deftest publish-model-test
- (mt/with-premium-features #{:data-studio}
- (testing "POST /api/ee/data-studio/table/publish-model"
- (testing "creates models for selected tables"
- (mt/with-model-cleanup [:model/Card]
- (mt/with-temp [:model/Collection {collection-id :id} {}]
- (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-model"
- {:table_ids [(mt/id :users) (mt/id :venues)]
- :target_collection_id collection-id})]
- (is (= 2 (:created_count response)))
- (is (= 2 (count (:models response))))
- (testing "models have correct attributes"
- (doseq [model (:models response)]
- (is (= "model" (:type model)))
- (is (= collection-id (:collection_id model)))
- (is (int? (:published_table_id model)))))
- (testing "the query should works"
- (is (some? (mt/process-query (-> response :models first :dataset_query)))))
- (testing "models are persisted in database"
- (is (= 2 (t2/count :model/Card :collection_id collection-id :type :model)))))))))))
-;: TODO (Ngoc 31/10/2025): test publish model to library mark the library as dirty
-
-(deftest published-as-model-test
- (mt/with-premium-features #{:data-studio}
- (mt/with-model-cleanup [:model/Card]
- (mt/with-temp [:model/Collection {collection-id :id} {}]
- (let [{:keys [models]} (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-model"
- {:table_ids [(mt/id :venues)]
- :target_collection_id collection-id})
- [model] models
- venues-schema (t2/select-one-fn :schema [:model/Table :schema] (mt/id :venues))
- schema-url (format "database/%d/schema/%s" (mt/id) venues-schema)
- list-tables-via-table-api (fn [] (->> (mt/user-http-request :crowberto :get 200 "table" :db-id (mt/id))
- (filter #(= (mt/id) (:db_id %)))))
- list-tables-via-schema-api #(mt/user-http-request :crowberto :get 200 schema-url)]
- (testing "list tables"
- (let [list-response (list-tables-via-table-api)
- published-as-model (u/index-by :id :published_as_model list-response)]
- (is (true? (published-as-model (mt/id :venues))))
- (is (false? (published-as-model (mt/id :users))))))
- (testing "list tables via schema"
- (let [list-response (list-tables-via-schema-api)
- published-as-model (u/index-by :id :published_as_model list-response)]
- (is (true? (published-as-model (mt/id :venues))))
- (is (false? (published-as-model (mt/id :users))))))
- (testing "archived tables are not returned"
- (t2/update! :model/Card (:id model) {:archived true, :archived_directly false})
- (is (not-any? :published_as_model (list-tables-via-table-api)))))))))
-
-(deftest published-models-perm-test
+(use-fixtures :once (fixtures/initialize :db))
+
+(deftest publish-table-test
(mt/with-premium-features #{:data-studio}
- ;; what I think would be reasonable permissions behaviour:
- ;; > if no permissions on model or its collection, model is filtered out
- ;; what I have done:
- ;; > if not super-user we never give you the published models
- (mt/with-model-cleanup [:model/Card]
- (mt/with-temp [:model/Collection {collection1 :id} {}
- :model/Collection {collection2 :id} {}]
- (let [publish-venues #(mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-model"
- {:table_ids [(mt/id :venues)]
- :target_collection_id %})
- {[{model1 :id}] :models} (publish-venues collection1)
- {[{model2 :id}] :models} (publish-venues collection2)
- query-meta-url #(format "table/%d/query_metadata" %)
- list-published-models #(:published_models (mt/user-http-request %1 :get 200 (query-meta-url %2)))]
- (testing "admin sees both models"
- (is (= #{model1 model2} (set (map :id (list-published-models :crowberto (mt/id :venues)))))))
- (testing "no published models"
- (is (nil? (list-published-models :crowberto (mt/id :users)))))
- (testing "non admin does not see published models"
- (is (nil? (list-published-models :rasta (mt/id :venues))))
- (is (nil? (list-published-models :rasta (mt/id :users))))))))))
+ (without-library
+ (testing "POST /api/ee/data-studio/table/(un)publish-table"
+ (testing "publishes tables into the library-models collection"
+ (mt/with-temp [:model/Collection {collection-id :id} {:type collection/library-models-collection-type}]
+ (testing "normal users are not allowed to publish"
+ (mt/user-http-request :rasta :post 403 "ee/data-studio/table/publish-tables"
+ {:table_ids [(mt/id :users) (mt/id :venues)]}))
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"
+ {:table_ids [(mt/id :users) (mt/id :venues)]})]
+ (is (=? {:id collection-id} (:target_collection response)))
+ (testing "collection_id and is_published are set"
+ (is (=? [{:display_name "Users"
+ :collection_id collection-id
+ :is_published true}
+ {:display_name "Venues"
+ :collection_id collection-id
+ :is_published true}]
+ (t2/select :model/Table :id [:in [(mt/id :users) (mt/id :venues)]] {:order-by [:display_name]}))))
+ (testing "unpublishing"
+ (testing "normal users are not allowed"
+ (mt/user-http-request :rasta :post 403 "ee/data-studio/table/unpublish-tables"
+ {:table_ids [(mt/id :venues)]}))
+ (mt/user-http-request :crowberto :post 204 "ee/data-studio/table/unpublish-tables"
+ {:table_ids [(mt/id :venues)]})
+ (is (=? {:display_name "Venues"
+ :collection_id nil
+ :is_published false}
+ (t2/select-one :model/Table (mt/id :venues)))))))
+ (testing "deleting the collection unpublishes"
+ (is (=? {:display_name "Users"
+ :collection_id nil
+ :is_published false}
+ (t2/select-one :model/Table (mt/id :users))))))
+ (testing "returns 404 when no library-models collection exists"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :post 404 "ee/data-studio/table/publish-tables"
+ {:table_ids [(mt/id :users)]}))))
+ (testing "returns 409 when multiple library-models collections exist"
+ (mt/with-temp [:model/Collection _ {:type collection/library-models-collection-type}
+ :model/Collection _ {:type collection/library-models-collection-type}]
+ (is (= "Multiple library-models collections found."
+ (mt/user-http-request :crowberto :post 409 "ee/data-studio/table/publish-tables"
+ {:table_ids [(mt/id :users)]})))))))))
(deftest bulk-edit-visibility-sync-test
(mt/with-premium-features #{:data-studio}
@@ -145,7 +122,7 @@
(swap! tables conj table)
(.countDown latch)
nil)]
- (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/sync-schema" {:database_ids [d1],
+ (mt/user-http-request :crowberto :post 204 "ee/data-studio/table/sync-schema" {:database_ids [d1],
:schema_ids [(format "%d:FOO" d2)]
:table_ids [t4]}))
(testing "sync called?"
@@ -175,7 +152,7 @@
(swap! tables conj table)
(.countDown latch)
nil)]
- (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/rescan-values" {:database_ids [d1],
+ (mt/user-http-request :crowberto :post 204 "ee/data-studio/table/rescan-values" {:database_ids [d1],
:schema_ids [(format "%d:FOO" d2)]
:table_ids [t4]}))
(testing "rescanned?"
@@ -226,9 +203,9 @@
(testing "FieldValues should still exist"
(is (= [v1 v2 v3 v4 v5 v6 v7] (get-field-values)))))
(testing "Admins should be able to successfully delete them"
- (is (= {:status "ok"} (mt/user-http-request :crowberto :post 200 url {:database_ids [d1],
- :schema_ids [(format "%d:FOO" d2)]
- :table_ids [t4]})))
+ (is (nil? (mt/user-http-request :crowberto :post 204 url {:database_ids [d1],
+ :schema_ids [(format "%d:FOO" d2)]
+ :table_ids [t4]})))
(testing "Selected FieldValues should be gone"
(is (= [v3] (get-field-values))))))))))
@@ -394,3 +371,356 @@
gc nil
jit nil}
(t2/select-pk->fn :owner_user_id :model/Table :db_id [:in [clojure jvm]]))))))))
+
+;;; ------------------------------------------------- Selection Tests -------------------------------------------------
+
+(deftest selection-basic-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/selection"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {t1 :id} {:db_id db-id :name "orders" :schema "PUBLIC" :is_published false}
+ :model/Table {t2 :id} {:db_id db-id :name "products" :schema "PUBLIC" :is_published true}
+ :model/Table _ {:db_id db-id :name "people" :schema "PUBLIC" :is_published false}]
+ (testing "returns a published table in selection with all required fields"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [t2]})]
+ (is (=? {:selected_table {:id t2
+ :db_id db-id
+ :name "products"
+ :display_name "Products"
+ :schema "PUBLIC"
+ :is_published true}}
+ response))))
+ (testing "returns an unpublished table in selection with all required fields"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [t1]})]
+ (is (=? {:selected_table {:id t1
+ :db_id db-id
+ :name "orders"
+ :display_name "Orders"
+ :schema "PUBLIC"
+ :is_published false}}
+ response))))
+ (testing "returns nil for :selected_table when there are multiple selected tables"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [t1 t2]})]
+ (is (=? {:selected_table nil}
+ response))))
+ (testing "tables with no remapping should have empty upstream/downstream"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [t2]})]
+ (is (=? {:published_downstream_tables []
+ :unpublished_upstream_tables []}
+ response))))))))
+
+(deftest selection-with-remapping-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/selection with remapping dependencies"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ ;; Orders table with FK to Products
+ :model/Table {orders-id :id} {:db_id db-id :name "orders" :schema "PUBLIC" :is_published false}
+ :model/Field _ {:table_id orders-id :name "id" :semantic_type :type/PK
+ :base_type :type/Integer}
+ :model/Field {product-fk :id} {:table_id orders-id :name "product_id" :semantic_type :type/FK
+ :base_type :type/Integer}
+ ;; Products table
+ :model/Table {products-id :id} {:db_id db-id :name "products" :schema "PUBLIC" :is_published false}
+ :model/Field _ {:table_id products-id :name "id" :semantic_type :type/PK
+ :base_type :type/Integer}
+ :model/Field {prod-name-f :id} {:table_id products-id :name "name" :semantic_type :type/Name
+ :base_type :type/Text}
+ ;; Dimension for FK remapping: product_id -> products.name
+ :model/Dimension _ {:field_id product-fk
+ :human_readable_field_id prod-name-f
+ :type :external}]
+ (testing "selecting orders returns products as upstream dependency"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [orders-id]})]
+ (is (=? {:selected_table {:id orders-id
+ :db_id db-id
+ :name "orders"
+ :display_name "Orders"
+ :schema "PUBLIC"}
+ :unpublished_upstream_tables [{:id products-id
+ :db_id db-id
+ :name "products"
+ :display_name "Products"
+ :schema "PUBLIC"}]}
+ response))))
+
+ (testing "if products is already published, it appears in published_downstream when selecting it"
+ (t2/update! :model/Table products-id {:is_published true})
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [products-id]})]
+ (is (=? {:selected_table {:id products-id
+ :db_id db-id
+ :name "products"
+ :display_name "Products"
+ :schema "PUBLIC"}
+ :unpublished_upstream_tables []}
+ response))
+ ;; orders is unpublished and depends on products
+ ;; when we want to unpublish products, orders would need to be unpublished too
+ ;; but orders is already unpublished, so published_downstream_tables should be empty
+ (is (= [] (:published_downstream_tables response)))))
+
+ (testing "when orders is published and we select products, orders appears in published_downstream"
+ (t2/update! :model/Table orders-id {:is_published true})
+ (t2/update! :model/Table products-id {:is_published true})
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [products-id]})]
+ (is (=? {:selected_table {:id products-id
+ :db_id db-id
+ :name "products"
+ :display_name "Products"
+ :schema "PUBLIC"}
+ :published_downstream_tables [{:id orders-id
+ :db_id db-id
+ :name "orders"
+ :display_name "Orders"
+ :schema "PUBLIC"}]}
+ response))))))))
+
+(deftest selection-recursive-upstream-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/selection with recursive upstream dependencies"
+ ;; Chain: order_items -> orders -> customers
+ ;; order_items.order_id remaps to orders.name
+ ;; orders.customer_id remaps to customers.name
+ (mt/with-temp [:model/Database {db-id :id} {}
+ ;; Customers table
+ :model/Table {customers-id :id} {:db_id db-id :name "customers" :schema "PUBLIC"
+ :is_published false}
+ :model/Field _ {:table_id customers-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ ;; Orders table
+ :model/Table {orders-id :id} {:db_id db-id :name "orders" :schema "PUBLIC"
+ :is_published false}
+ :model/Field _ {:table_id orders-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-name-f :id} {:table_id orders-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Order items table
+ :model/Table {items-id :id} {:db_id db-id :name "order_items" :schema "PUBLIC"
+ :is_published false}
+ :model/Field _ {:table_id items-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-fk :id} {:table_id items-id :name "order_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Dimensions for FK remapping
+ :model/Dimension _ {:field_id customer-fk
+ :human_readable_field_id cust-name-f
+ :type :external}
+ :model/Dimension _ {:field_id order-fk
+ :human_readable_field_id order-name-f
+ :type :external}]
+ (testing "selecting order_items returns orders and customers as upstream (recursive)"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [items-id]})]
+ (is (=? {:selected_table {:id items-id
+ :db_id db-id
+ :name "order_items"
+ :display_name "Order Items"
+ :schema "PUBLIC"}
+ :unpublished_upstream_tables (mt/malli=? [:sequential {:min 2 :max 2} :map])}
+ response))
+ (is (= #{orders-id customers-id}
+ (set (map :id (:unpublished_upstream_tables response)))))
+ ;; Verify upstream tables have all required fields
+ (doseq [table (:unpublished_upstream_tables response)]
+ (are [k] (contains? table k)
+ :id :db_id :name :display_name :schema))))))))
+
+(deftest selection-recursive-downstream-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/selection with recursive downstream dependencies"
+ ;; Same chain: order_items -> orders -> customers
+ ;; If we unpublish customers, we need to unpublish orders and order_items too
+ (mt/with-temp [:model/Database {db-id :id} {}
+ ;; Customers table (published)
+ :model/Table {customers-id :id} {:db_id db-id :name "customers" :schema "PUBLIC"
+ :is_published true}
+ :model/Field _ {:table_id customers-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ ;; Orders table (published)
+ :model/Table {orders-id :id} {:db_id db-id :name "orders" :schema "PUBLIC"
+ :is_published true}
+ :model/Field _ {:table_id orders-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-name-f :id} {:table_id orders-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Order items table (published)
+ :model/Table {items-id :id} {:db_id db-id :name "order_items" :schema "PUBLIC"
+ :is_published true}
+ :model/Field _ {:table_id items-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-fk :id} {:table_id items-id :name "order_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Dimensions for FK remapping
+ :model/Dimension _ {:field_id customer-fk
+ :human_readable_field_id cust-name-f
+ :type :external}
+ :model/Dimension _ {:field_id order-fk
+ :human_readable_field_id order-name-f
+ :type :external}]
+ (testing "selecting customers returns orders and order_items as downstream (recursive)"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/selection"
+ {:table_ids [customers-id]})]
+ (is (=? {:selected_table {:id customers-id
+ :db_id db-id
+ :name "customers"
+ :display_name "Customers"
+ :schema "PUBLIC"}
+ :published_downstream_tables (mt/malli=? [:sequential {:min 2 :max 2} :map])}
+ response))
+ (is (= #{orders-id items-id}
+ (set (map :id (:published_downstream_tables response)))))
+ ;; Verify downstream tables have all required fields
+ (doseq [table (:published_downstream_tables response)]
+ (are [k] (contains? table k)
+ :id :db_id :name :display_name :schema))))))))
+
+;;; ------------------------------------------ Publish/Unpublish with Dependencies ------------------------------------------
+
+(deftest publish-tables-with-upstream-dependencies-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/publish-tables publishes upstream dependencies"
+ (mt/with-temp [:model/Collection _ {:type collection/library-models-collection-type}
+ :model/Database {db-id :id} {}
+ ;; Products table (upstream)
+ :model/Table {products-id :id} {:db_id db-id :name "products" :is_published false}
+ :model/Field _ {:table_id products-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {prod-name-f :id} {:table_id products-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ ;; Orders table (depends on products)
+ :model/Table {orders-id :id} {:db_id db-id :name "orders" :is_published false}
+ :model/Field _ {:table_id orders-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {product-fk :id} {:table_id orders-id :name "product_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Dimension for FK remapping
+ :model/Dimension _ {:field_id product-fk
+ :human_readable_field_id prod-name-f
+ :type :external}]
+ (testing "publishing orders also publishes products (upstream dependency)"
+ (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"
+ {:table_ids [orders-id]})
+ (are [table-id] (true? (t2/select-one-fn :is_published :model/Table table-id))
+ orders-id products-id))))))
+
+(deftest publish-tables-recursive-upstream-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/publish-tables publishes recursive upstream dependencies"
+ (mt/with-temp [:model/Collection _ {:type collection/library-models-collection-type}
+ :model/Database {db-id :id} {}
+ ;; Customers table (upstream of orders)
+ :model/Table {customers-id :id} {:db_id db-id :name "customers" :is_published false}
+ :model/Field _ {:table_id customers-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ ;; Orders table (upstream of order_items, downstream of customers)
+ :model/Table {orders-id :id} {:db_id db-id :name "orders" :is_published false}
+ :model/Field _ {:table_id orders-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-name-f :id} {:table_id orders-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Order items table (downstream of orders)
+ :model/Table {items-id :id} {:db_id db-id :name "order_items" :is_published false}
+ :model/Field _ {:table_id items-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-fk :id} {:table_id items-id :name "order_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Dimensions for FK remapping
+ :model/Dimension _ {:field_id customer-fk
+ :human_readable_field_id cust-name-f
+ :type :external}
+ :model/Dimension _ {:field_id order-fk
+ :human_readable_field_id order-name-f
+ :type :external}]
+ (testing "publishing order_items also publishes orders and customers (recursive upstream)"
+ (mt/user-http-request :crowberto :post 200 "ee/data-studio/table/publish-tables"
+ {:table_ids [items-id]})
+ (are [table-id] (true? (t2/select-one-fn :is_published :model/Table table-id))
+ items-id orders-id customers-id))))))
+
+(deftest unpublish-tables-with-downstream-dependents-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/unpublish-tables unpublishes downstream dependents"
+ (mt/with-temp [:model/Collection {coll-id :id} {:type collection/library-models-collection-type}
+ :model/Database {db-id :id} {}
+ ;; Products table (upstream, published)
+ :model/Table {products-id :id} {:db_id db-id :name "products" :is_published true
+ :collection_id coll-id}
+ :model/Field _ {:table_id products-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {prod-name-f :id} {:table_id products-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ ;; Orders table (depends on products, published)
+ :model/Table {orders-id :id} {:db_id db-id :name "orders" :is_published true
+ :collection_id coll-id}
+ :model/Field _ {:table_id orders-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {product-fk :id} {:table_id orders-id :name "product_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Dimension for FK remapping
+ :model/Dimension _ {:field_id product-fk
+ :human_readable_field_id prod-name-f
+ :type :external}]
+ (testing "unpublishing products also unpublishes orders (downstream dependent)"
+ (mt/user-http-request :crowberto :post 204 "ee/data-studio/table/unpublish-tables"
+ {:table_ids [products-id]})
+ (are [table-id] (false? (t2/select-one-fn :is_published :model/Table table-id))
+ products-id orders-id))))))
+
+(deftest unpublish-tables-recursive-downstream-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/ee/data-studio/table/unpublish-tables unpublishes recursive downstream dependents"
+ (mt/with-temp [:model/Collection {coll-id :id} {:type collection/library-models-collection-type}
+ :model/Database {db-id :id} {}
+ ;; Customers table (upstream of orders, published)
+ :model/Table {customers-id :id} {:db_id db-id :name "customers" :is_published true
+ :collection_id coll-id}
+ :model/Field _ {:table_id customers-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ ;; Orders table (downstream of customers, upstream of items, published)
+ :model/Table {orders-id :id} {:db_id db-id :name "orders" :is_published true
+ :collection_id coll-id}
+ :model/Field _ {:table_id orders-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-name-f :id} {:table_id orders-id :name "name"
+ :semantic_type :type/Name :base_type :type/Text}
+ :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Order items table (downstream of orders, published)
+ :model/Table {items-id :id} {:db_id db-id :name "order_items" :is_published true
+ :collection_id coll-id}
+ :model/Field _ {:table_id items-id :name "id"
+ :semantic_type :type/PK :base_type :type/Integer}
+ :model/Field {order-fk :id} {:table_id items-id :name "order_id"
+ :semantic_type :type/FK :base_type :type/Integer}
+ ;; Dimensions for FK remapping
+ :model/Dimension _ {:field_id customer-fk
+ :human_readable_field_id cust-name-f
+ :type :external}
+ :model/Dimension _ {:field_id order-fk
+ :human_readable_field_id order-name-f
+ :type :external}]
+ (testing "unpublishing customers also unpublishes orders and order_items (recursive downstream)"
+ (mt/user-http-request :crowberto :post 204 "ee/data-studio/table/unpublish-tables"
+ {:table_ids [customers-id]})
+ (are [table-id] (false? (t2/select-one-fn :is_published :model/Table table-id))
+ customers-id orders-id items-id))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
new file mode 100644
index 00000000000..4982fa5519e
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
@@ -0,0 +1,137 @@
+(ns metabase-enterprise.data-studio.permissions.query-test
+ "Tests for published table query permissions.
+ Published tables can be queried via collection permissions instead of data permissions."
+ (:require
+ [clojure.test :refer :all]
+ [metabase.api.common :refer [*current-user-id* *current-user-permissions-set* *is-superuser?*]]
+ [metabase.permissions.core :as perms]
+ [metabase.query-permissions.core :as query-perms]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once (fixtures/initialize :db))
+
+(deftest published-table-test
+ (testing "Published tables grant query access via collection permissions only with data-studio enabled"
+ (doseq [features [#{} #{:data-studio}]
+ collection-readable? [false true]
+ view-data [:unrestricted :blocked]]
+ (mt/with-premium-features features
+ (let [mbql-query (mt/mbql-query venues)]
+ (mt/with-restored-data-perms-for-group! (u/the-id (perms/all-users-group))
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}
+ :model/User {user-id :id} {}
+ :model/PermissionsGroupMembership _ {:user_id user-id :group_id group-id}
+ :model/Collection {collection-id :id} {}]
+ ;; Ensure All Users group has no create-queries permission and matching view-data
+ ;; (user is automatically in this group)
+ (perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data view-data)
+ (perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/create-queries :no)
+ (perms/set-table-permission! (perms/all-users-group) (mt/id :venues) :perms/create-queries :no)
+ ;; Set up permissions on custom group: user cannot create queries, view-data varies
+ (perms/set-database-permission! group-id (mt/id) :perms/view-data view-data)
+ (perms/set-database-permission! group-id (mt/id) :perms/create-queries :no)
+ ;; Publish the table and grant/revoke collection read permissions
+ (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id collection-id})
+ (if collection-readable?
+ (perms/grant-collection-read-permissions! group-id collection-id)
+ (do
+ ;; Revoke from both groups since user is in All Users automatically
+ (perms/revoke-collection-permissions! group-id collection-id)
+ (perms/revoke-collection-permissions! (perms/all-users-group) collection-id)))
+ (binding [*current-user-id* user-id
+ *current-user-permissions-set* (atom (if collection-readable?
+ #{(perms/collection-read-path collection-id)}
+ #{}))]
+ (testing (str "with features " (pr-str features)
+ ", collection-readable? " collection-readable?
+ ", view-data " view-data)
+ (perms/disable-perms-cache
+ ;; Query is only runnable when: data-studio enabled AND collection readable AND view-data unrestricted
+ (is (= (and (contains? features :data-studio)
+ collection-readable?
+ (not= view-data :blocked))
+ (query-perms/can-run-query? mbql-query))))))))))))))
+
+(deftest published-table-does-not-grant-view-data-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "Published tables with collection permissions should NOT grant view-data permissions"
+ (mt/with-restored-data-perms-for-group! (u/the-id (perms/all-users-group))
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ ;; Create a test user that only belongs to all-users group (no extra permissions)
+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
+ :model/Collection collection {}]
+ ;; Publish the venues table into this collection
+ (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
+ (let [all-users (perms/all-users-group)]
+ ;; Set database-level permissions first to establish baseline
+ (perms/set-database-permission! all-users (mt/id) :perms/view-data :blocked)
+ (perms/set-database-permission! all-users (mt/id) :perms/create-queries :no)
+ ;; Grant collection read permission
+ (perms/grant-collection-read-permissions! all-users (u/the-id collection))
+ ;; Set table-level permissions
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/create-queries :no)
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/view-data :blocked)
+
+ (perms/disable-perms-cache
+ (binding [*current-user-id* user-id
+ *current-user-permissions-set* (delay (perms/user-permissions-set user-id))
+ *is-superuser?* false]
+ (testing "Should grant create-queries via collection permissions"
+ (is (= :query-builder
+ (perms/table-permission-for-user user-id :perms/create-queries (mt/id) (mt/id :venues)))
+ "Collection permissions should grant query-builder permission"))
+ (testing "Should NOT grant view-data via collection permissions"
+ (is (= :blocked
+ (perms/table-permission-for-user user-id :perms/view-data (mt/id) (mt/id :venues)))
+ "Collection permissions should NOT grant view-data permission")))))))))))
+
+(deftest published-table-grants-database-access-test
+ (mt/with-restored-data-perms-for-group! (u/the-id (perms/all-users-group))
+ (mt/with-premium-features #{:data-studio}
+ (testing "POST /api/dataset in EE: published table access GRANTS database access"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
+ :model/Collection collection {}]
+ ;; Publish the venues table into this collection
+ (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
+ (let [all-users (perms/all-users-group)]
+ ;; Set database-level permissions first to establish baseline
+ (perms/set-database-permission! all-users (mt/id) :perms/view-data :unrestricted)
+ (perms/set-database-permission! all-users (mt/id) :perms/create-queries :no)
+ ;; Grant collection read permission - this gives create-queries via published table mechanism
+ (perms/grant-collection-read-permissions! all-users (u/the-id collection))
+ ;; Set table-level permissions
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/view-data :unrestricted)
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/create-queries :no)
+ ;; With collection permission on published table, query should succeed
+ (testing "Query should succeed because EE grants create-queries via published table mechanism"
+ (is (=? {:status "completed"
+ :row_count pos-int?}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 202 "dataset"
+ (mt/mbql-query venues {:limit 1}))))))))))
+ (testing "POST /api/dataset in EE: without collection permission, published table does NOT grant access"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
+ :model/Collection collection {}]
+ ;; Publish the venues table into this collection
+ (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
+ (let [all-users (perms/all-users-group)]
+ ;; Set database-level permissions first to establish baseline
+ (perms/set-database-permission! all-users (mt/id) :perms/view-data :unrestricted)
+ (perms/set-database-permission! all-users (mt/id) :perms/create-queries :no)
+ ;; DON'T grant collection read permission - revoke it explicitly
+ (perms/revoke-collection-permissions! all-users collection)
+ ;; Set table-level permissions
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/view-data :unrestricted)
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/create-queries :no)
+ ;; Without collection permission, query should fail at database check (403)
+ (testing "Query should fail because user has no collection permission on published table"
+ (is (= "You don't have permissions to do that."
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 403 "dataset"
+ (mt/mbql-query venues {:limit 1})))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj
new file mode 100644
index 00000000000..243918751a4
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/search_test.clj
@@ -0,0 +1,116 @@
+(ns metabase-enterprise.data-studio.search-test
+ "Tests for published tables in search."
+ (:require
+ [clojure.test :refer :all]
+ [medley.core :as m]
+ [metabase.collections.models.collection :as collection]
+ [metabase.search.core :as search]
+ [metabase.test :as mt]))
+
+(deftest published-table-collection-filter-test
+ (mt/with-premium-features #{:data-studio}
+ (testing "Published tables are included in collection-filtered search"
+ (mt/with-temp
+ [:model/Collection {parent-coll :id} {:name "Parent Collection" :location "/"}
+ :model/Collection {child-coll :id} {:name "Child Collection"
+ :location (collection/location-path parent-coll)}
+ :model/Card {card-1 :id} {:collection_id parent-coll :name "Parent Card"}
+ :model/Table {table-1 :id} {:name "Published Table" :is_published true :collection_id parent-coll}
+ :model/Table {table-2 :id} {:name "Child Published Table" :is_published true :collection_id child-coll}
+ :model/Table {table-3 :id} {:name "Unpublished Table" :is_published false}
+ :model/Table {table-4 :id} {:name "Root Published Table" :is_published true :collection_id nil}]
+ ;; Initialize search index for appdb engine
+ (search/reindex! {:async? false :in-place? true})
+ (doseq [engine ["in-place" "appdb"]]
+ (testing (str "with engine " engine)
+ (testing "Global search"
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :search_engine engine)]
+ (is (=? [{:collection {:authority_level nil, :id parent-coll, :name "Parent Collection", :type nil}
+ :database_id (mt/id)
+ :id table-1
+ :model "table"
+ :name "Published Table"
+ :table_id table-1
+ :table_name "Published Table"}
+ {:collection {:authority_level nil, :id child-coll, :name "Child Collection", :type nil}
+ :database_id (mt/id)
+ :id table-2
+ :model "table"
+ :name "Child Published Table"
+ :table_id table-2
+ :table_name "Child Published Table"}
+ {:database_id (mt/id)
+ :id table-3
+ :model "table"
+ :name "Unpublished Table"
+ :table_id table-3
+ :table_name "Unpublished Table"}
+ {:collection {:authority_level nil, :id "root", :name "Our analytics", :type nil}
+ :database_id (mt/id)
+ :id table-4
+ :model "table"
+ :name "Root Published Table"
+ :table_id table-4
+ :table_name "Root Published Table"}]
+ (->> (:data results)
+ (filter (comp #{table-1 table-2 table-3 table-4} :id))
+ (sort-by :id))))))
+ (testing "Filter by parent collection returns published tables in that collection and descendants"
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :collection parent-coll :search_engine engine)]
+ (is (=? {:collection {:authority_level nil, :id parent-coll, :name "Parent Collection", :type nil}
+ :database_id (mt/id)
+ :id table-1
+ :model "table"
+ :name "Published Table"
+ :table_id table-1
+ :table_name "Published Table"}
+ (m/find-first (comp #{table-1} :id) (:data results))))
+ (is (contains? (set (map :id (:data results))) table-1)
+ "Published table in parent collection should be included")
+ (is (contains? (set (map :id (:data results))) table-2)
+ "Published table in child collection should be included")
+ (is (contains? (set (map :id (:data results))) card-1)
+ "Card in parent collection should be included")))
+ (testing "Unpublished tables are not included in collection filter results"
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :collection parent-coll :search_engine engine)]
+ (is (not (contains? (set (map :id (:data results))) table-3))
+ "Unpublished table should not be in results")))))))
+ (testing "Published tables in root collection (collection_id=nil) appear in unfiltered search"
+ (mt/with-temp
+ [:model/Table {root-table :id} {:name "Root Published Searchable" :is_published true :collection_id nil}]
+ (search/reindex! {:async? false :in-place? true})
+ (doseq [engine ["in-place" "appdb"]]
+ (testing (str "with engine " engine)
+ (let [results (mt/user-http-request :crowberto :get 200 "search" :q "Root Published Searchable" :search_engine engine)]
+ (is (some #(= root-table (:id %)) (:data results))
+ "Root published table should appear in search results"))))))
+ (testing "Published tables appear as collection items, unpublished as database items"
+ (mt/with-temp
+ [:model/Database {db-id :id} {:name "Context Test DB"}
+ :model/Collection {coll-id :id} {:name "Context Test Collection" :location "/"}
+ :model/Table {pub-table :id} {:name "ContextTestTablePub"
+ :db_id db-id
+ :is_published true
+ :collection_id coll-id}
+ :model/Table {unpub-table :id} {:name "ContextTestTableUnpub"
+ :db_id db-id
+ :is_published false}]
+ (search/reindex! {:async? false :in-place? true})
+ (doseq [engine ["in-place" "appdb"]]
+ (testing (str "with engine " engine)
+ (let [results (mt/user-http-request :crowberto :get 200 "search"
+ :q "Context" :models "table" :search_engine engine)
+ our-result (->> (filter (comp #{pub-table unpub-table} :id) (:data results))
+ (sort-by :id))]
+ (testing "each table appears once"
+ (is (=? [{:id pub-table
+ :model "table"
+ :name "ContextTestTablePub"
+ :collection {:id coll-id}
+ :database_name "Context Test DB"}
+ {:id unpub-table
+ :model "table"
+ :name "ContextTestTableUnpub"
+ :collection {:id nil}
+ :database_name "Context Test DB"}]
+ our-result))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
index a8809a90fcf..b07edf89150 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
@@ -912,6 +912,45 @@
{:model "Field" :id "Some Field"}]}
(set (serdes/dependencies ser))))))))))
+(deftest table-publishing-serdes-test
+ (mt/with-empty-h2-app-db!
+ (ts/with-temp-dpc [:model/Database {db-id :id} {:name "My Database"}
+ :model/Table {table-id :id} {:name "Schemaless Table" :db_id db-id}
+ :model/Collection {coll-id :id
+ coll-eid :entity_id} {:name "Publishing Collection"}
+ :model/Table {pub-table-id :id} {:name "Published Table"
+ :db_id db-id
+ :is_published true
+ :collection_id coll-id}
+ :model/Table {unpub-table-id :id} {:name "Unpublished Table"
+ :db_id db-id
+ :is_published false}]
+ (testing "published table with collection_id"
+ (let [ser (ts/extract-one "Table" pub-table-id)]
+ (testing "is_published is included in extraction"
+ (is (true? (:is_published ser))))
+ (testing "collection_id is transformed to entity_id"
+ (is (= coll-eid (:collection_id ser))))
+ (testing "depends on the collection"
+ (is (contains? (set (serdes/dependencies ser))
+ [{:model "Collection" :id coll-eid}])))))
+ (testing "unpublished table without collection_id"
+ (let [ser (ts/extract-one "Table" unpub-table-id)]
+ (testing "is_published defaults to false"
+ (is (false? (:is_published ser))))
+ (testing "collection_id is nil"
+ (is (nil? (:collection_id ser))))
+ (testing "does not depend on any collection"
+ (is (not (some #(= "Collection" (:model (first %)))
+ (serdes/dependencies ser)))))))
+ (testing "regular table without publishing fields set"
+ (let [ser (ts/extract-one "Table" table-id)]
+ (testing "is_published defaults to false"
+ (is (false? (:is_published ser))))
+
+ (testing "collection_id is nil"
+ (is (nil? (:collection_id ser)))))))))
+
(deftest implicit-action-test
(mt/with-empty-h2-app-db!
(ts/with-temp-dpc [:model/User {ann-id :id} {:first_name "Ann"
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
index 5b857a560e0..75ade58dbdb 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
@@ -846,6 +846,59 @@
(is (= (dissoc @fv2s :id :field_id :created_at :updated_at)
(dissoc @fv2d :id :field_id :created_at :updated_at)))))))))
+(deftest table-publishing-round-trip-test
+ ;; Tests that is_published and collection_id survive a round-trip through serialization.
+ ;; The collection_id FK transform converts DB id to entity_id and back.
+ (testing "published table with collection_id survives round-trip"
+ (let [serialized (atom nil)
+ db1s (atom nil)
+ table1s (atom nil)
+ coll1s (atom nil)
+ table2s (atom nil)
+
+ db1d (atom nil)
+ table1d (atom nil)
+ coll1d (atom nil)
+ table2d (atom nil)]
+
+ (ts/with-dbs [source-db dest-db]
+ (testing "serializing published tables"
+ (ts/with-db source-db
+ (reset! db1s (ts/create! :model/Database :name "my-db"))
+ (reset! coll1s (ts/create! :model/Collection :name "Publishing Collection"))
+ (reset! table1s (ts/create! :model/Table :name "published_table" :db_id (:id @db1s)
+ :is_published true :collection_id (:id @coll1s)))
+ (reset! table2s (ts/create! :model/Table :name "unpublished_table" :db_id (:id @db1s)
+ :is_published false))
+ (reset! serialized (into [] (serdes.extract/extract {})))))
+
+ (testing "serialized form has collection entity_id, not DB id"
+ (let [pub-table (->> @serialized
+ (filter #(and (-> % :serdes/meta last :model (= "Table"))
+ (= (:name %) "published_table")))
+ first)]
+ (is (true? (:is_published pub-table)))
+ (is (= (:entity_id @coll1s) (:collection_id pub-table)))))
+
+ (testing "deserializing restores collection_id correctly"
+ (ts/with-db dest-db
+ ;; Load the serialized content
+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))
+
+ ;; Fetch the relevant bits
+ (reset! db1d (t2/select-one :model/Database :name "my-db"))
+ (reset! coll1d (t2/select-one :model/Collection :name "Publishing Collection"))
+ (reset! table1d (t2/select-one :model/Table :name "published_table" :db_id (:id @db1d)))
+ (reset! table2d (t2/select-one :model/Table :name "unpublished_table" :db_id (:id @db1d)))
+
+ (testing "published table has correct is_published and collection_id"
+ (is (true? (:is_published @table1d)))
+ (is (= (:id @coll1d) (:collection_id @table1d))))
+
+ (testing "unpublished table has is_published=false and no collection"
+ (is (false? (:is_published @table2d)))
+ (is (nil? (:collection_id @table2d))))))))))
+
(deftest bare-import-test
;; If the dependencies of an entity exist in the receiving database, they don't need to be in the export.
;; This tests that such an import will succeed, and that it still fails when the dependency is not found in
diff --git a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx
index a0d0cd30e49..d3728b5123d 100644
--- a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx
+++ b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx
@@ -13,9 +13,9 @@ import Schemas from "metabase/entities/schemas";
import Search from "metabase/entities/search";
import Tables from "metabase/entities/tables";
import { connect } from "metabase/lib/redux";
-import { getHasDataAccess } from "metabase/selectors/data";
import { getMetadata } from "metabase/selectors/metadata";
import { getSetting } from "metabase/selectors/settings";
+import { canUserCreateQueries } from "metabase/selectors/user";
import { Box, Popover } from "metabase/ui";
import {
SAVED_QUESTIONS_VIRTUAL_DB_ID,
@@ -889,7 +889,7 @@ const DataSelector = _.compose(
hasLoadedDatabasesWithTables: Databases.selectors.getLoaded(state, {
entityQuery: { include: "tables" },
}),
- hasDataAccess: getHasDataAccess(ownProps.databases ?? []),
+ hasDataAccess: canUserCreateQueries(state),
hasNestedQueriesEnabled: getSetting(state, "enable-nested-queries"),
selectedQuestion: Questions.selectors.getObject(state, {
entityId: getQuestionIdFromVirtualTableId(ownProps.selectedTableId),
diff --git a/enterprise/frontend/src/metabase-enterprise/api/library.ts b/enterprise/frontend/src/metabase-enterprise/api/library.ts
index 8cbcd90d97f..393c4544e38 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/library.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/library.ts
@@ -1,7 +1,7 @@
import type { Collection, CollectionItem } from "metabase-types/api";
import { EnterpriseApi } from "./api";
-import { listTag, tag } from "./tags";
+import { idTag, listTag, tag } from "./tags";
export const libraryApi = EnterpriseApi.injectEndpoints({
endpoints: (builder) => ({
@@ -10,14 +10,20 @@ export const libraryApi = EnterpriseApi.injectEndpoints({
method: "POST",
url: "/api/ee/library",
}),
- invalidatesTags: [listTag("collection")],
+ invalidatesTags: [listTag("collection"), tag("library-collection")],
}),
getLibraryCollection: builder.query<CollectionItem | { data: null }, void>({
query: () => ({
url: `/api/ee/library`,
method: "GET",
}),
- providesTags: () => [tag("library-collection")],
+ providesTags: (collection) => [
+ // TODO Alex P 12/05/2025 Fix the endpoint to return sensible data
+ ...(collection != null && "name" in collection
+ ? [idTag("collection", collection.id)]
+ : []),
+ tag("library-collection"),
+ ],
}),
}),
});
diff --git a/enterprise/frontend/src/metabase-enterprise/api/table.ts b/enterprise/frontend/src/metabase-enterprise/api/table.ts
index 49d7bf6daa1..fbd78f46ab6 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/table.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/table.ts
@@ -1,17 +1,35 @@
import type {
+ BulkTableSelection,
+ BulkTableSelectionInfo,
DiscardTablesValuesRequest,
EditTablesRequest,
- PublishModelsRequest,
- PublishModelsResponse,
+ PublishTablesResponse,
RescanTablesValuesRequest,
SyncTablesSchemaRequest as SyncTablesSchemasRequest,
} from "metabase-types/api";
import { EnterpriseApi } from "./api";
-import { invalidateTags, listTag, tag } from "./tags";
+import {
+ invalidateTags,
+ listTag,
+ provideBulkTableSelectionInfoTags,
+ tag,
+} from "./tags";
export const tableApi = EnterpriseApi.injectEndpoints({
endpoints: (builder) => ({
+ getTableSelectionInfo: builder.query<
+ BulkTableSelectionInfo,
+ BulkTableSelection
+ >({
+ query: (body) => ({
+ method: "POST",
+ url: "/api/ee/data-studio/table/selection",
+ body,
+ }),
+ providesTags: (response) =>
+ response ? provideBulkTableSelectionInfoTags(response) : [],
+ }),
editTables: builder.mutation<Record<string, never>, EditTablesRequest>({
query: (body) => ({
method: "POST",
@@ -57,13 +75,19 @@ export const tableApi = EnterpriseApi.injectEndpoints({
invalidatesTags: (_, error) =>
invalidateTags(error, [tag("field-values"), tag("parameter-values")]),
}),
- publishModels: builder.mutation<
- PublishModelsResponse,
- PublishModelsRequest
- >({
+ publishTables: builder.mutation<PublishTablesResponse, BulkTableSelection>({
+ query: (body) => ({
+ method: "POST",
+ url: "/api/ee/data-studio/table/publish-tables",
+ body,
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [tag("table"), tag("card"), tag("collection")]),
+ }),
+ unpublishTables: builder.mutation<void, BulkTableSelection>({
query: (body) => ({
method: "POST",
- url: "/api/ee/data-studio/table/publish-model",
+ url: "/api/ee/data-studio/table/unpublish-tables",
body,
}),
invalidatesTags: (_, error) =>
@@ -73,9 +97,12 @@ export const tableApi = EnterpriseApi.injectEndpoints({
});
export const {
+ useGetTableSelectionInfoQuery,
+ useLazyGetTableSelectionInfoQuery,
useEditTablesMutation,
useRescanTablesFieldValuesMutation,
useSyncTablesSchemasMutation,
useDiscardTablesFieldValuesMutation,
- usePublishModelsMutation,
+ usePublishTablesMutation,
+ useUnpublishTablesMutation,
} = tableApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index c5930ecd3cc..7d86357713f 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -9,6 +9,8 @@ import {
provideUserTags,
} from "metabase/api/tags";
import type {
+ BulkTableInfo,
+ BulkTableSelectionInfo,
CardDependencyNode,
Comment,
DashboardDependencyNode,
@@ -305,3 +307,22 @@ export function provideSupportAccessGrantListTags(
...grants.flatMap(provideSupportAccessGrantTags),
];
}
+
+export function provideBulkTableInfoTags(
+ table: BulkTableInfo,
+): TagDescription<EnterpriseTagType>[] {
+ return [idTag("table", table.id)];
+}
+
+export function provideBulkTableSelectionInfoTags({
+ selected_table,
+ published_downstream_tables,
+ unpublished_upstream_tables,
+}: BulkTableSelectionInfo): TagDescription<EnterpriseTagType>[] {
+ return [
+ listTag("table"),
+ ...(selected_table != null ? provideBulkTableInfoTags(selected_table) : []),
+ ...published_downstream_tables.flatMap(provideBulkTableInfoTags),
+ ...unpublished_upstream_tables.flatMap(provideBulkTableInfoTags),
+ ];
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/types/state.ts b/enterprise/frontend/src/metabase-enterprise/application_permissions/types/state.ts
index 1a4cad55a87..cffc0591703 100644
--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/types/state.ts
+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/types/state.ts
@@ -1,10 +1,8 @@
import type { State } from "metabase-types/store";
import type { ApplicationPermissions } from "./permissions";
-import type { UserWithApplicationPermissions } from "./user";
export interface ApplicationPermissionsState extends State {
- currentUser: UserWithApplicationPermissions | null;
plugins: {
applicationPermissionsPlugin: {
applicationPermissions: ApplicationPermissions;
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/types/user.ts b/enterprise/frontend/src/metabase-enterprise/application_permissions/types/user.ts
deleted file mode 100644
index 5469cca35fd..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/types/user.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type { UserWithApplicationPermissions } from "metabase/plugins";
diff --git a/enterprise/frontend/src/metabase-enterprise/application_permissions/utils.ts b/enterprise/frontend/src/metabase-enterprise/application_permissions/utils.ts
index a794694bc33..b0f9cdb472f 100644
--- a/enterprise/frontend/src/metabase-enterprise/application_permissions/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/application_permissions/utils.ts
@@ -1,17 +1,16 @@
+import type { User } from "metabase-types/api";
import type { AdminPathKey } from "metabase-types/store";
-import type { UserWithApplicationPermissions } from "./types/user";
-
-const canAccessMonitoringItems = (user?: UserWithApplicationPermissions) =>
+const canAccessMonitoringItems = (user?: User) =>
user?.permissions?.can_access_monitoring ?? false;
-const canAccessSettings = (user?: UserWithApplicationPermissions) =>
+const canAccessSettings = (user?: User) =>
user?.permissions?.can_access_setting ?? false;
export const monitoringPermissionAllowedPathGetter = (
- user?: UserWithApplicationPermissions,
+ user?: User,
): AdminPathKey[] => (canAccessMonitoringItems(user) ? ["tools"] : []);
export const settingsPermissionAllowedPathGetter = (
- user?: UserWithApplicationPermissions,
+ user?: User,
): AdminPathKey[] => (canAccessSettings(user) ? ["settings"] : []);
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/analytics.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/analytics.ts
index 36f2373ef10..7e67d9a6508 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/analytics.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/analytics.ts
@@ -1,5 +1,5 @@
import { trackSimpleEvent } from "metabase/lib/analytics";
-import type { CollectionId } from "metabase-types/api";
+import type { CollectionId, TableId } from "metabase-types/api";
export const trackDataStudioLibraryCreated = (id: CollectionId) => {
trackSimpleEvent({
@@ -8,10 +8,10 @@ export const trackDataStudioLibraryCreated = (id: CollectionId) => {
});
};
-export const trackDataStudioTablePublished = (id: number | null) => {
+export const trackDataStudioTablePublished = (id: TableId | null) => {
trackSimpleEvent({
event: "data_studio_table_published",
- target_id: id,
+ target_id: id != null ? Number(id) : null,
});
};
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataSectionLayout/DataSectionLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataSectionLayout/DataSectionLayout.tsx
index c43667b896b..9320232aad3 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataSectionLayout/DataSectionLayout.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataSectionLayout/DataSectionLayout.tsx
@@ -2,8 +2,6 @@ import type { ReactNode } from "react";
import { t } from "ttag";
import { usePageTitle } from "metabase/hooks/use-page-title";
-import * as Urls from "metabase/lib/urls";
-import { DataModelContext } from "metabase/metadata/pages/shared";
import { SectionLayout, SectionTitle } from "../../components/SectionLayout";
@@ -16,9 +14,7 @@ export function DataSectionLayout({ children }: DataSectionLayoutProps) {
return (
<SectionLayout title={<SectionTitle title={t`Data`} />}>
- <DataModelContext.Provider value={{ baseUrl: Urls.dataStudioData() }}>
- {children}
- </DataModelContext.Provider>
+ {children}
</SectionLayout>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
index 575751ea024..0d6800de373 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
@@ -81,7 +81,13 @@ function DataStudioNav({
const isDependenciesTab = pathname.startsWith(Urls.dependencyGraph());
return (
- <Stack className={S.nav} h="100%" p="0.75rem" justify="space-between">
+ <Stack
+ className={S.nav}
+ h="100%"
+ p="0.75rem"
+ justify="space-between"
+ data-testid="data-studio-nav"
+ >
<Stack gap="0.75rem">
{canAccessDataModel && (
<DataStudioTab
@@ -142,6 +148,7 @@ function DataStudioTab({ label, icon, to, isSelected }: DataStudioTabProps) {
to={to}
p="0.75rem"
bdrs="md"
+ aria-label={label}
>
<FixedSizeIcon name={icon} display="block" />
</Box>
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/CreateLibraryModal/CreateLibraryModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/CreateLibraryModal/CreateLibraryModal.tsx
deleted file mode 100644
index c0ba57a8587..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/CreateLibraryModal/CreateLibraryModal.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { t } from "ttag";
-
-import { Form, FormErrorMessage, FormProvider } from "metabase/forms";
-import {
- Box,
- Button,
- Center,
- FixedSizeIcon,
- FocusTrap,
- Group,
- List,
- Modal,
- Text,
- Title,
-} from "metabase/ui";
-import { useCreateLibraryMutation } from "metabase-enterprise/api";
-import type { Collection } from "metabase-types/api";
-
-type CreateLibraryModalProps = {
- onCreate: (collection: Collection) => void;
- onClose: () => void;
-};
-
-export function CreateLibraryModal({
- onCreate,
- onClose,
-}: CreateLibraryModalProps) {
- const [createLibrary] = useCreateLibraryMutation();
-
- const handleSubmit = async () => {
- const collection = await createLibrary().unwrap();
- onCreate(collection);
- };
-
- return (
- <Modal
- title={
- <Group gap="sm">
- <Center w="2rem" h="2rem" c="brand" bg="brand-light" bdrs="md">
- <FixedSizeIcon name="repository" />
- </Center>
- <Title order={3}>{t`Create your Library`}</Title>
- </Group>
- }
- opened
- onClose={onClose}
- >
- <FormProvider initialValues={{}} onSubmit={handleSubmit}>
- <Form>
- <FocusTrap.InitialFocus />
- <Text>
- {t`The Library helps you create a source of truth for analytics by providing a centrally managed set of curated content. It separates authoritative, reusable components from ad-hoc analyses.`}
- </Text>
- <List mt="sm" spacing="sm">
- <ListItem
- title={t`Models`}
- description={t`Cleaned, pre-transformed data sources ready for exploring`}
- />
- <ListItem
- title={t`Metrics`}
- description={t`Standardized calculations with known dimensions`}
- />
- <ListItem
- title={t`Version control`}
- description={t`Sync your library to Git for governance`}
- />
- <ListItem
- title={t`High trust`}
- description={t`Default to reliable sources your data team prescribes`}
- />
- </List>
- <Group mt="xl" gap="sm">
- <Box flex={1}>
- <FormErrorMessage />
- </Box>
- <Button variant="subtle" onClick={onClose}>{t`Cancel`}</Button>
- <Button variant="filled" type="submit">
- {t`Create my Library`}
- </Button>
- </Group>
- </Form>
- </FormProvider>
- </Modal>
- );
-}
-
-type ListItemProps = {
- title: string;
- description: string;
-};
-
-function ListItem({ title, description }: ListItemProps) {
- return (
- <List.Item>
- <strong>{title}</strong>
- {": "}
- {description}
- </List.Item>
- );
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/LibrarySection.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/LibrarySection.tsx
index 0376c07dae6..187a843cf05 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/LibrarySection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/LibrarySection.tsx
@@ -7,12 +7,11 @@ import { isLibraryCollection } from "metabase/collections/utils";
import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { getUserIsAdmin } from "metabase/selectors/user";
-import { trackDataStudioLibraryCreated } from "metabase-enterprise/data-studio/analytics";
+import { CreateLibraryModal } from "metabase-enterprise/data-studio/common/components/CreateLibraryModal";
import type { Collection, CollectionId } from "metabase-types/api";
import { ModelingSidebarSection } from "../ModelingSidebarSection";
-import { CreateLibraryModal } from "./CreateLibraryModal";
import { LibraryCollectionTree } from "./LibraryCollectionTree";
export type LibrarySectionProps = {
@@ -40,7 +39,6 @@ export function LibrarySection({
const handleCreate = (collection: Collection) => {
closeModal();
- trackDataStudioLibraryCreated(collection.id);
dispatch(push(Urls.dataStudioCollection(collection.id)));
};
@@ -63,9 +61,11 @@ export function LibrarySection({
icon="repository"
onClick={openModal}
/>
- {isModalOpened && (
- <CreateLibraryModal onCreate={handleCreate} onClose={closeModal} />
- )}
+ <CreateLibraryModal
+ isOpened={isModalOpened}
+ onCreate={handleCreate}
+ onClose={closeModal}
+ />
</>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/ModelingSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/ModelingSidebar.tsx
index b1ffa8bf7ca..a5a847c52b9 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/ModelingSidebar.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/ModelingSidebar.tsx
@@ -1,10 +1,9 @@
-import { useMemo } from "react";
-
+import { useListCollectionsTreeQuery } from "metabase/api";
+import { useSelector } from "metabase/lib/redux";
import {
- useListCollectionsTreeQuery,
- useListDatabasesQuery,
-} from "metabase/api";
-import { getHasDataAccess, getHasNativeWrite } from "metabase/selectors/data";
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+} from "metabase/selectors/user";
import type { CollectionId, NativeQuerySnippetId } from "metabase-types/api";
import { ModelingSidebarView } from "./ModelingSidebarView";
@@ -20,24 +19,13 @@ export function ModelingSidebar({
selectedSnippetId,
isGlossaryActive,
}: ModelingSidebarProps) {
- const { data: databaseData, isLoading: isLoadingDatabases } =
- useListDatabasesQuery();
- const { data: collections = [], isLoading: isLoadingCollections } =
- useListCollectionsTreeQuery({
- "exclude-other-user-collections": true,
- "exclude-archived": true,
- "include-library": true,
- });
-
- const { hasDataAccess, hasNativeWrite } = useMemo(() => {
- const databases = databaseData?.data ?? [];
- return {
- hasDataAccess: getHasDataAccess(databases),
- hasNativeWrite: getHasNativeWrite(databases),
- };
- }, [databaseData]);
-
- const isLoading = isLoadingDatabases || isLoadingCollections;
+ const { data: collections = [], isLoading } = useListCollectionsTreeQuery({
+ "exclude-other-user-collections": true,
+ "exclude-archived": true,
+ "include-library": true,
+ });
+ const hasDataAccess = useSelector(canUserCreateQueries);
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
if (isLoading) {
return null;
diff --git a/frontend/src/metabase/questions/components/CardMoreMenu/CardMoreMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardMoreMenu/CardMoreMenu.tsx
similarity index 93%
rename from frontend/src/metabase/questions/components/CardMoreMenu/CardMoreMenu.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardMoreMenu/CardMoreMenu.tsx
index 3ee38d4a044..0352585367d 100644
--- a/frontend/src/metabase/questions/components/CardMoreMenu/CardMoreMenu.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardMoreMenu/CardMoreMenu.tsx
@@ -4,15 +4,14 @@ import { c, t } from "ttag";
import { ForwardRefLink } from "metabase/common/components/Link";
import { useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
+import { ArchiveCardModal } from "metabase/questions/components/ArchiveCardModal";
+import { CardCopyModal } from "metabase/questions/components/CardCopyModal";
+import { MoveCardModal } from "metabase/questions/components/MoveCardModal";
import { getMetadata } from "metabase/selectors/metadata";
import { ActionIcon, Icon, Menu } from "metabase/ui";
import * as Lib from "metabase-lib";
import type { Card } from "metabase-types/api";
-import { ArchiveCardModal } from "../ArchiveCardModal";
-import { CardCopyModal } from "../CardCopyModal";
-import { MoveCardModal } from "../MoveCardModal";
-
type CardModalType = "move" | "copy" | "archive";
type CardMoreMenuProps = {
diff --git a/frontend/src/metabase/questions/components/CardMoreMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardMoreMenu/index.ts
similarity index 100%
rename from frontend/src/metabase/questions/components/CardMoreMenu/index.ts
rename to enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardMoreMenu/index.ts
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.module.css
index 215750900ee..0c93fdb0ca8 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.module.css
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.module.css
@@ -2,14 +2,6 @@
overflow: auto;
}
-.visualization {
- background-color: var(--mb-color-bg-white);
- border: 1px solid var(--mb-color-border);
- border-radius: var(--default-border-radius);
- overflow: hidden;
- flex: 1;
-}
-
.sidebar {
flex-shrink: 0;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.tsx
index 385ff4dce1a..aeaa65addc5 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverview.tsx
@@ -2,8 +2,9 @@ import { EntityCreationInfo } from "metabase/common/components/EntityCreationInf
import { Flex, Stack } from "metabase/ui";
import type { Card } from "metabase-types/api";
+import { OverviewVisualization } from "../OverviewVisualization";
+
import S from "./CardOverview.module.css";
-import { CardOverviewVisualization } from "./CardOverviewVisualization";
import { DescriptionSection } from "./DescriptionSection";
import { QuerySourceSection } from "./QuerySourceSection";
@@ -15,7 +16,7 @@ export function CardOverview({ card }: CardOverviewProps) {
return (
<Flex className={S.root} p="lg" flex={1} bg="bg-light">
<Flex direction="column" flex={1} mah={700}>
- <CardOverviewVisualization className={S.visualization} card={card} />
+ <OverviewVisualization card={card} />
</Flex>
<Stack maw={300} ml="lg" gap="lg" className={S.sidebar}>
<DescriptionSection card={card} />
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/VisualizationSection.css b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/VisualizationSection.css
deleted file mode 100644
index 9c5f5ebe751..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/VisualizationSection.css
+++ /dev/null
@@ -1,3 +0,0 @@
-.root {
- flex: 1 0 auto;
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/index.ts
deleted file mode 100644
index 2ee9962e31b..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./CardOverviewVisualization";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/QuerySourceSection/QuerySourceSection.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/QuerySourceSection/QuerySourceSection.tsx
index 66ad5169825..b44d7c6cd75 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/QuerySourceSection/QuerySourceSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/QuerySourceSection/QuerySourceSection.tsx
@@ -64,7 +64,9 @@ function TableSourcePath({ tableId }: TableSourcePathProps) {
const pathParts: SourcePathPart[] = [];
pathParts.push({
name: table.db.name,
- url: table.db.is_audit ? undefined : Urls.dataModelDatabase(table.db_id),
+ url: table.db.is_audit
+ ? undefined
+ : Urls.dataModel({ databaseId: table.db_id }),
});
if (table.schema) {
@@ -72,7 +74,10 @@ function TableSourcePath({ tableId }: TableSourcePathProps) {
name: table.schema,
url: table.db.is_audit
? undefined
- : Urls.dataModelSchema(table.db_id, table.schema),
+ : Urls.dataModel({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ }),
});
}
@@ -80,7 +85,11 @@ function TableSourcePath({ tableId }: TableSourcePathProps) {
name: table.display_name,
url: table.db.is_audit
? undefined
- : Urls.dataModelTable(table.db_id, table.schema, table.id),
+ : Urls.dataModel({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ tableId: table.id,
+ }),
});
return pathParts;
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/CreateLibraryModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/CreateLibraryModal.tsx
new file mode 100644
index 00000000000..cc59e477072
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/CreateLibraryModal.tsx
@@ -0,0 +1,143 @@
+import { t } from "ttag";
+
+import {
+ Form,
+ FormErrorMessage,
+ FormProvider,
+ FormSubmitButton,
+} from "metabase/forms";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ Box,
+ Button,
+ Center,
+ FixedSizeIcon,
+ FocusTrap,
+ Group,
+ List,
+ Modal,
+ Stack,
+ Text,
+ Title,
+} from "metabase/ui";
+import { useCreateLibraryMutation } from "metabase-enterprise/api";
+import { trackDataStudioLibraryCreated } from "metabase-enterprise/data-studio/analytics";
+import type { Collection } from "metabase-types/api";
+
+type CreateLibraryModalProps = {
+ title?: string;
+ explanatorySentence?: string;
+ isOpened: boolean;
+ onCreate: (collection: Collection) => void;
+ onClose: () => void;
+};
+
+export function CreateLibraryModal({
+ title = t`Create your Library`,
+ explanatorySentence,
+ isOpened,
+ onCreate,
+ onClose,
+}: CreateLibraryModalProps) {
+ return (
+ <Modal
+ title={<ModalTitle title={title} />}
+ opened={isOpened}
+ onClose={onClose}
+ >
+ <FocusTrap.InitialFocus />
+ <ModalBody
+ explanatorySentence={explanatorySentence}
+ onCreate={onCreate}
+ onClose={onClose}
+ />
+ </Modal>
+ );
+}
+
+type ModalTitleProps = {
+ title: string;
+};
+
+function ModalTitle({ title }: ModalTitleProps) {
+ return (
+ <Group gap="sm">
+ <Center w="2rem" h="2rem" c="brand" bg="brand-light" bdrs="md">
+ <FixedSizeIcon name="repository" />
+ </Center>
+ <Title order={3}>{title}</Title>
+ </Group>
+ );
+}
+
+type ModalBodyProps = {
+ explanatorySentence?: string;
+ onCreate: (collection: Collection) => void;
+ onClose: () => void;
+};
+
+function ModalBody({ explanatorySentence, onCreate, onClose }: ModalBodyProps) {
+ const [createLibrary] = useCreateLibraryMutation();
+ const { sendSuccessToast } = useMetadataToasts();
+
+ const handleSubmit = async () => {
+ const collection = await createLibrary().unwrap();
+ sendSuccessToast(t`Library created`);
+ trackDataStudioLibraryCreated(collection.id);
+ onCreate(collection);
+ };
+
+ return (
+ <FormProvider initialValues={{}} onSubmit={handleSubmit}>
+ <Form>
+ <FocusTrap.InitialFocus />
+ <Stack gap="sm">
+ {explanatorySentence && <Text>{explanatorySentence}</Text>}
+ <Text>
+ {t`The Library helps you create a source of truth for analytics by providing a centrally managed set of curated content. It separates authoritative, reusable components from ad-hoc analyses.`}
+ </Text>
+ <List spacing="sm">
+ <ListItem
+ title={t`Tables`}
+ description={t`Cleaned, pre-transformed data sources ready for exploring`}
+ />
+ <ListItem
+ title={t`Metrics`}
+ description={t`Standardized calculations with known dimensions`}
+ />
+ <ListItem
+ title={t`Version control`}
+ description={t`Sync your Library to Git`}
+ />
+ <ListItem
+ title={t`High trust`}
+ description={t`Default to reliable sources your data team prescribes`}
+ />
+ </List>
+ </Stack>
+ <Group mt="xl" gap="sm">
+ <Box flex={1}>
+ <FormErrorMessage />
+ </Box>
+ <Button variant="subtle" onClick={onClose}>{t`Cancel`}</Button>
+ <FormSubmitButton label={t`Create my Library`} variant="filled" />
+ </Group>
+ </Form>
+ </FormProvider>
+ );
+}
+
+type ListItemProps = {
+ title: string;
+ description: string;
+};
+
+function ListItem({ title, description }: ListItemProps) {
+ return (
+ <List.Item>
+ <strong>{title}</strong>
+ {": "}
+ {description}
+ </List.Item>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/CreateLibraryModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/CreateLibraryModal.unit.spec.tsx
new file mode 100644
index 00000000000..06066f0074f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/CreateLibraryModal.unit.spec.tsx
@@ -0,0 +1,45 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupCreateLibraryEndpoint,
+ setupCreateLibraryEndpointError,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+
+import { CreateLibraryModal } from "./CreateLibraryModal";
+
+type SetupOpts = {
+ hasCreateError?: boolean;
+};
+
+function setup({ hasCreateError }: SetupOpts = {}) {
+ const onCreate = jest.fn();
+ const onClose = jest.fn();
+
+ if (hasCreateError) {
+ setupCreateLibraryEndpointError();
+ } else {
+ setupCreateLibraryEndpoint();
+ }
+
+ renderWithProviders(
+ <CreateLibraryModal isOpened onCreate={onCreate} onClose={onClose} />,
+ );
+
+ return { onCreate, onClose };
+}
+
+describe("CreateLibraryModal", () => {
+ it("should be able to create the library", async () => {
+ const { onCreate } = setup();
+ await userEvent.click(screen.getByText("Create my Library"));
+ await waitFor(() => expect(onCreate).toHaveBeenCalled());
+ });
+
+ it("should show a library creation error", async () => {
+ const { onCreate } = setup({ hasCreateError: true });
+ await userEvent.click(screen.getByText("Create my Library"));
+ expect(await screen.findByText("An error occurred")).toBeInTheDocument();
+ expect(onCreate).not.toHaveBeenCalled();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/CreateLibraryModal/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/index.ts
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/ModelingSectionLayout/ModelingSidebar/LibrarySection/CreateLibraryModal/index.ts
rename to enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CreateLibraryModal/index.ts
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/OverviewVisualization.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/OverviewVisualization.module.css
new file mode 100644
index 00000000000..ff393eb57d5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/OverviewVisualization.module.css
@@ -0,0 +1,11 @@
+.root {
+ flex: 1 0 auto;
+}
+
+.visualization {
+ background-color: var(--mb-color-bg-white);
+ border: 1px solid var(--mb-color-border);
+ border-radius: var(--default-border-radius);
+ overflow: hidden;
+ flex: 1;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/CardOverviewVisualization.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/OverviewVisualization.tsx
similarity index 56%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/CardOverviewVisualization.tsx
rename to enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/OverviewVisualization.tsx
index 15a59e849e8..caa312267dc 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/CardOverview/CardOverviewVisualization/CardOverviewVisualization.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/OverviewVisualization.tsx
@@ -1,6 +1,10 @@
import { useMemo } from "react";
-import { useGetCardQueryQuery } from "metabase/api";
+import {
+ skipToken,
+ useGetAdhocQueryQuery,
+ useGetCardQueryQuery,
+} from "metabase/api";
import DebouncedFrame from "metabase/common/components/DebouncedFrame";
import { useSelector } from "metabase/lib/redux";
import QueryVisualization from "metabase/query_builder/components/QueryVisualization";
@@ -8,24 +12,27 @@ import { getMetadata } from "metabase/selectors/metadata";
import Question from "metabase-lib/v1/Question";
import type { Card } from "metabase-types/api";
-import S from "./VisualizationSection.css";
+import S from "./OverviewVisualization.module.css";
-type CardOverviewVisualizationProps = {
- className?: string;
+type OverviewVisualizationProps = {
card: Card;
};
-export function CardOverviewVisualization({
- className,
- card,
-}: CardOverviewVisualizationProps) {
+export function OverviewVisualization({ card }: OverviewVisualizationProps) {
const metadata = useSelector(getMetadata);
const question = useMemo(
() => new Question(card, metadata),
[card, metadata],
);
- const { data, isLoading } = useGetCardQueryQuery({ cardId: card.id });
+ const { data: cardData, isLoading: isLoadingCardData } = useGetCardQueryQuery(
+ card.id != null ? { cardId: card.id } : skipToken,
+ );
+ const { data: adhocData, isLoading: isLoadingAdhocData } =
+ useGetAdhocQueryQuery(card.id == null ? card.dataset_query : skipToken);
+ const data = cardData || adhocData;
+ const isLoading = isLoadingCardData || isLoadingAdhocData;
+
const rawSeries = useMemo(
() => (data ? [{ card, data: data.data }] : null),
[card, data],
@@ -34,10 +41,11 @@ export function CardOverviewVisualization({
return (
<DebouncedFrame className={S.root}>
<QueryVisualization
- className={className}
+ className={S.visualization}
question={question}
result={data}
rawSeries={rawSeries}
+ queryBuilderMode="dataset" // disable the object details column
isRunnable={false}
isRunning={isLoading}
isDirty
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/index.ts
new file mode 100644
index 00000000000..c288e9366cc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/OverviewVisualization/index.ts
@@ -0,0 +1 @@
+export * from "./OverviewVisualization";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PaneHeader/PaneHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PaneHeader/PaneHeader.tsx
index 2074827e26c..11594b70a3e 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PaneHeader/PaneHeader.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PaneHeader/PaneHeader.tsx
@@ -69,6 +69,7 @@ type PaneHeaderInputProps = {
placeholder?: string;
maxLength?: number;
isOptional?: boolean;
+ "data-testid"?: string;
onChange?: (value: string) => void;
onContentChange?: (value: string) => void;
};
@@ -77,6 +78,7 @@ export function PaneHeaderInput({
initialValue,
placeholder = t`Name`,
maxLength,
+ "data-testid": dataTestId,
isOptional,
onChange,
onContentChange,
@@ -93,6 +95,7 @@ export function PaneHeaderInput({
px={isOptional ? "xs" : undefined}
bd={isOptional ? "1px solid var(--mb-color-border)" : undefined}
isOptional={isOptional}
+ data-testid={dataTestId}
onChange={onChange}
onContentChange={onContentChange}
/>
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/PublishTablesModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/PublishTablesModal.tsx
new file mode 100644
index 00000000000..19f14929970
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/PublishTablesModal.tsx
@@ -0,0 +1,217 @@
+import { push } from "react-router-redux";
+import { jt, t } from "ttag";
+
+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
+import {
+ Form,
+ FormErrorMessage,
+ FormProvider,
+ FormSubmitButton,
+} from "metabase/forms";
+import { useDispatch } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ Box,
+ Button,
+ FocusTrap,
+ Group,
+ List,
+ Modal,
+ Stack,
+ Text,
+} from "metabase/ui";
+import {
+ useGetTableSelectionInfoQuery,
+ usePublishTablesMutation,
+} from "metabase-enterprise/api";
+import { trackDataStudioTablePublished } from "metabase-enterprise/data-studio/analytics";
+import type {
+ BulkTableInfo,
+ DatabaseId,
+ SchemaId,
+ TableId,
+} from "metabase-types/api";
+
+type PublishTablesModalProps = {
+ databaseIds?: DatabaseId[];
+ schemaIds?: SchemaId[];
+ tableIds?: TableId[];
+ isOpened: boolean;
+ onPublish: () => void;
+ onClose: () => void;
+};
+
+export function PublishTablesModal({
+ databaseIds,
+ schemaIds,
+ tableIds,
+ isOpened,
+ onPublish,
+ onClose,
+}: PublishTablesModalProps) {
+ return (
+ <Modal
+ title={
+ <ModalTitle
+ databaseIds={databaseIds}
+ schemaIds={schemaIds}
+ tableIds={tableIds}
+ />
+ }
+ opened={isOpened}
+ onClose={onClose}
+ >
+ <FocusTrap.InitialFocus />
+ <ModalBody
+ databaseIds={databaseIds}
+ schemaIds={schemaIds}
+ tableIds={tableIds}
+ onPublish={onPublish}
+ onClose={onClose}
+ />
+ </Modal>
+ );
+}
+
+type ModalTitleProps = {
+ databaseIds: DatabaseId[] | undefined;
+ schemaIds: SchemaId[] | undefined;
+ tableIds: TableId[] | undefined;
+};
+
+function ModalTitle({ databaseIds, schemaIds, tableIds }: ModalTitleProps) {
+ const { data } = useGetTableSelectionInfoQuery({
+ database_ids: databaseIds,
+ schema_ids: schemaIds,
+ table_ids: tableIds,
+ });
+ if (!data) {
+ return null;
+ }
+
+ const { selected_table, unpublished_upstream_tables } = data;
+ return <>{getTitle(selected_table, unpublished_upstream_tables)}</>;
+}
+
+type ModalBodyProps = {
+ databaseIds: DatabaseId[] | undefined;
+ schemaIds: SchemaId[] | undefined;
+ tableIds: TableId[] | undefined;
+ onPublish: () => void;
+ onClose: () => void;
+};
+
+function ModalBody({
+ databaseIds,
+ schemaIds,
+ tableIds,
+ onPublish,
+ onClose,
+}: ModalBodyProps) {
+ const { data, isLoading, error } = useGetTableSelectionInfoQuery({
+ database_ids: databaseIds,
+ schema_ids: schemaIds,
+ table_ids: tableIds,
+ });
+ const [publishTables] = usePublishTablesMutation();
+ const { sendSuccessToast } = useMetadataToasts();
+ const dispatch = useDispatch();
+
+ if (isLoading || error != null || data == null) {
+ return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;
+ }
+
+ const { selected_table, unpublished_upstream_tables } = data;
+
+ const handleSubmit = async () => {
+ const { target_collection: collection } = await publishTables({
+ database_ids: databaseIds,
+ schema_ids: schemaIds,
+ table_ids: tableIds,
+ }).unwrap();
+
+ if (collection != null) {
+ sendSuccessToast(
+ t`Published`,
+ () => dispatch(push(Urls.dataStudioCollection(collection.id))),
+ t`Go to ${collection.name}`,
+ );
+ } else {
+ sendSuccessToast(t`Published`);
+ }
+
+ trackDataStudioTablePublished(
+ selected_table != null ? selected_table.id : null,
+ );
+
+ onPublish();
+ };
+
+ return (
+ <FormProvider initialValues={{}} onSubmit={handleSubmit}>
+ <Form>
+ <Stack gap="sm">
+ <Text>{t`Publishing a table saves it to the Library.`}</Text>
+ {unpublished_upstream_tables.length > 0 && (
+ <>
+ <Text>{getForeignKeyMessage(selected_table)}</Text>
+ <List spacing="sm">
+ {unpublished_upstream_tables.map((table) => (
+ <List.Item key={table.id} fw="bold">
+ {table.display_name}
+ </List.Item>
+ ))}
+ </List>
+ </>
+ )}
+ </Stack>
+ <Group mt="xl" gap="sm" wrap="nowrap">
+ <Box flex={1}>
+ <FormErrorMessage />
+ </Box>
+ <Button variant="subtle" onClick={onClose}>{t`Cancel`}</Button>
+ <FormSubmitButton
+ label={getSubmitButtonLabel(
+ selected_table,
+ unpublished_upstream_tables,
+ )}
+ variant="filled"
+ />
+ </Group>
+ </Form>
+ </FormProvider>
+ );
+}
+
+function getTitle(
+ selectedTable: BulkTableInfo | null,
+ unpublishedRemappedTables: BulkTableInfo[],
+) {
+ if (selectedTable != null) {
+ return unpublishedRemappedTables.length > 0
+ ? t`Publish ${selectedTable.display_name} and the tables it depends on?`
+ : t`Publish ${selectedTable.display_name}?`;
+ }
+
+ return unpublishedRemappedTables.length > 0
+ ? t`Publish these tables and the tables they depend on?`
+ : t`Publish these tables?`;
+}
+
+function getForeignKeyMessage(selectedTable: BulkTableInfo | null) {
+ return selectedTable != null
+ ? jt`Because ${(
+ <strong key="table">{selectedTable.display_name}</strong>
+ )} uses foreign keys to display values from other tables, you'll need to publish these, too:`
+ : t`Because some of the tables you've selected use foreign keys to display values from other tables, you'll need to publish the tables below, too:`;
+}
+
+function getSubmitButtonLabel(
+ selectedTable: BulkTableInfo | null,
+ unpublishedRemappedTables: BulkTableInfo[],
+) {
+ return selectedTable != null && unpublishedRemappedTables.length === 0
+ ? t`Publish this table`
+ : t`Publish these tables`;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/PublishTablesModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/PublishTablesModal.unit.spec.tsx
new file mode 100644
index 00000000000..f7e7af1faf2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/PublishTablesModal.unit.spec.tsx
@@ -0,0 +1,159 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupPublishTablesEndpoint,
+ setupPublishTablesEndpointError,
+ setupTableSelectionInfoEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type {
+ BulkTableSelectionInfo,
+ DatabaseId,
+ SchemaId,
+ TableId,
+} from "metabase-types/api";
+import {
+ createMockBulkTableInfo,
+ createMockBulkTableSelectionInfo,
+} from "metabase-types/api/mocks";
+
+import { PublishTablesModal } from "./PublishTablesModal";
+
+type SetupOpts = {
+ databaseIds?: DatabaseId[];
+ schemaIds?: SchemaId[];
+ tableIds?: TableId[];
+ selectionInfo?: BulkTableSelectionInfo;
+ hasPublishError?: boolean;
+};
+
+function setup({
+ databaseIds,
+ schemaIds,
+ tableIds,
+ selectionInfo = createMockBulkTableSelectionInfo(),
+ hasPublishError,
+}: SetupOpts = {}) {
+ const onPublish = jest.fn();
+ const onClose = jest.fn();
+
+ setupTableSelectionInfoEndpoint(selectionInfo);
+ if (hasPublishError) {
+ setupPublishTablesEndpointError();
+ } else {
+ setupPublishTablesEndpoint();
+ }
+
+ renderWithProviders(
+ <PublishTablesModal
+ databaseIds={databaseIds}
+ schemaIds={schemaIds}
+ tableIds={tableIds}
+ isOpened
+ onPublish={onPublish}
+ onClose={onClose}
+ />,
+ );
+
+ return { onPublish, onClose };
+}
+
+describe("PublishTablesModal", () => {
+ it("should be able to publish a single table", async () => {
+ const { onPublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: createMockBulkTableInfo({
+ id: 1,
+ display_name: "Orders",
+ }),
+ }),
+ });
+ expect(await screen.findByText("Publish Orders?")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Publish this table"));
+ await waitFor(() => expect(onPublish).toHaveBeenCalled());
+ });
+
+ it("should be able to publish a single table with remapped tables", async () => {
+ const { onPublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: createMockBulkTableInfo({
+ id: 1,
+ display_name: "Orders",
+ }),
+ unpublished_upstream_tables: [
+ createMockBulkTableInfo({
+ id: 2,
+ display_name: "Products",
+ }),
+ createMockBulkTableInfo({
+ id: 3,
+ display_name: "People",
+ }),
+ ],
+ }),
+ });
+ expect(
+ await screen.findByText("Publish Orders and the tables it depends on?"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Products")).toBeInTheDocument();
+ expect(screen.getByText("People")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Publish these tables"));
+ await waitFor(() => expect(onPublish).toHaveBeenCalled());
+ });
+
+ it("should be able to publish multiple tables", async () => {
+ const { onPublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: null,
+ }),
+ });
+ expect(
+ await screen.findByText("Publish these tables?"),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Publish these tables"));
+ await waitFor(() => expect(onPublish).toHaveBeenCalled());
+ });
+
+ it("should be able to publish multiple tables with remapped tables", async () => {
+ const { onPublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: null,
+ unpublished_upstream_tables: [
+ createMockBulkTableInfo({
+ id: 2,
+ display_name: "Products",
+ }),
+ createMockBulkTableInfo({
+ id: 3,
+ display_name: "People",
+ }),
+ ],
+ }),
+ });
+ expect(
+ await screen.findByText(
+ "Publish these tables and the tables they depend on?",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Products")).toBeInTheDocument();
+ expect(screen.getByText("People")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Publish these tables"));
+ await waitFor(() => expect(onPublish).toHaveBeenCalled());
+ });
+
+ it("should show a publish error", async () => {
+ const { onPublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: createMockBulkTableInfo({
+ id: 1,
+ display_name: "Orders",
+ }),
+ }),
+ hasPublishError: true,
+ });
+ expect(await screen.findByText("Publish Orders?")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Publish this table"));
+ expect(await screen.findByText("An error occurred")).toBeInTheDocument();
+ expect(onPublish).not.toHaveBeenCalled();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/index.ts
new file mode 100644
index 00000000000..2cf04a18c90
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/PublishTablesModal/index.ts
@@ -0,0 +1 @@
+export * from "./PublishTablesModal";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/UnpublishTablesModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/UnpublishTablesModal.tsx
new file mode 100644
index 00000000000..ed48d2e4033
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/UnpublishTablesModal.tsx
@@ -0,0 +1,210 @@
+import { jt, t } from "ttag";
+
+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
+import {
+ Form,
+ FormErrorMessage,
+ FormProvider,
+ FormSubmitButton,
+} from "metabase/forms";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import {
+ Box,
+ Button,
+ FocusTrap,
+ Group,
+ List,
+ Modal,
+ Stack,
+ Text,
+} from "metabase/ui";
+import {
+ useGetTableSelectionInfoQuery,
+ useUnpublishTablesMutation,
+} from "metabase-enterprise/api";
+import type {
+ BulkTableInfo,
+ DatabaseId,
+ SchemaId,
+ TableId,
+} from "metabase-types/api";
+
+type UnpublishTablesModalProps = {
+ databaseIds?: DatabaseId[];
+ schemaIds?: SchemaId[];
+ tableIds?: TableId[];
+ isOpened: boolean;
+ onUnpublish: () => void;
+ onClose: () => void;
+};
+
+export function UnpublishTablesModal({
+ databaseIds,
+ schemaIds,
+ tableIds,
+ isOpened,
+ onUnpublish,
+ onClose,
+}: UnpublishTablesModalProps) {
+ return (
+ <Modal
+ title={
+ <ModalTitle
+ databaseIds={databaseIds}
+ schemaIds={schemaIds}
+ tableIds={tableIds}
+ />
+ }
+ opened={isOpened}
+ onClose={onClose}
+ >
+ <FocusTrap.InitialFocus />
+ <ModalBody
+ databaseIds={databaseIds}
+ schemaIds={schemaIds}
+ tableIds={tableIds}
+ onUnpublish={onUnpublish}
+ onClose={onClose}
+ />
+ </Modal>
+ );
+}
+
+type ModalTitleProps = {
+ databaseIds: DatabaseId[] | undefined;
+ schemaIds: SchemaId[] | undefined;
+ tableIds: TableId[] | undefined;
+};
+
+function ModalTitle({ databaseIds, schemaIds, tableIds }: ModalTitleProps) {
+ const { data } = useGetTableSelectionInfoQuery({
+ database_ids: databaseIds,
+ schema_ids: schemaIds,
+ table_ids: tableIds,
+ });
+ if (!data) {
+ return null;
+ }
+
+ const { selected_table, published_downstream_tables } = data;
+ return <>{getTitle(selected_table, published_downstream_tables)}</>;
+}
+
+type ModalBodyProps = {
+ databaseIds: DatabaseId[] | undefined;
+ schemaIds: SchemaId[] | undefined;
+ tableIds: TableId[] | undefined;
+ onUnpublish: () => void;
+ onClose: () => void;
+};
+
+function ModalBody({
+ databaseIds,
+ schemaIds,
+ tableIds,
+ onUnpublish,
+ onClose,
+}: ModalBodyProps) {
+ const { data, isLoading, error } = useGetTableSelectionInfoQuery({
+ database_ids: databaseIds,
+ schema_ids: schemaIds,
+ table_ids: tableIds,
+ });
+ const [unpublishTables] = useUnpublishTablesMutation();
+ const { sendSuccessToast } = useMetadataToasts();
+
+ if (isLoading || error != null || data == null) {
+ return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;
+ }
+
+ const { selected_table, published_downstream_tables } = data;
+
+ const handleSubmit = async () => {
+ await unpublishTables({
+ database_ids: databaseIds,
+ schema_ids: schemaIds,
+ table_ids: tableIds,
+ }).unwrap();
+ sendSuccessToast(t`Unpublished`);
+ onUnpublish();
+ };
+
+ return (
+ <FormProvider initialValues={{}} onSubmit={handleSubmit}>
+ <Form>
+ <Stack gap="sm">
+ <Text>
+ {getInfoMessage(selected_table, published_downstream_tables)}
+ </Text>
+ {published_downstream_tables.length > 0 && (
+ <>
+ <Text>{getForeignKeyMessage(selected_table)}</Text>
+ <List spacing="sm">
+ {published_downstream_tables.map((table) => (
+ <List.Item key={table.id} fw="bold">
+ {table.display_name}
+ </List.Item>
+ ))}
+ </List>
+ </>
+ )}
+ </Stack>
+ <Group mt="xl" gap="sm" wrap="nowrap">
+ <Box flex={1}>
+ <FormErrorMessage />
+ </Box>
+ <Button variant="subtle" onClick={onClose}>{t`Cancel`}</Button>
+ <FormSubmitButton
+ label={getSubmitButtonLabel(
+ selected_table,
+ published_downstream_tables,
+ )}
+ variant="filled"
+ color="error"
+ />
+ </Group>
+ </Form>
+ </FormProvider>
+ );
+}
+
+function getTitle(
+ selectedTable: BulkTableInfo | null,
+ publishedRemappedTables: BulkTableInfo[],
+) {
+ if (selectedTable != null) {
+ return publishedRemappedTables.length > 0
+ ? t`Unpublish ${selectedTable.display_name} and the tables that depend on it?`
+ : t`Unpublish ${selectedTable.display_name}?`;
+ }
+
+ return publishedRemappedTables.length > 0
+ ? t`Unpublish these tables and the tables that depend on them?`
+ : t`Unpublish these tables?`;
+}
+
+function getInfoMessage(
+ selectedTable: BulkTableInfo | null,
+ publishedRemappedTables: BulkTableInfo[],
+) {
+ return selectedTable != null && publishedRemappedTables.length === 0
+ ? t`This will remove this table from the Library.`
+ : t`This will remove these tables from the Library.`;
+}
+
+function getForeignKeyMessage(selectedTable: BulkTableInfo | null) {
+ return selectedTable != null
+ ? jt`Because values in ${(
+ <strong key="table">{selectedTable.display_name}</strong>
+ )} are used as display values in other published tables, you'll need to unpublish these, too:`
+ : t`Because values in some of the tables you've selected are used as display values in other published tables, you'll need to unpublish the tables below, too:`;
+}
+
+function getSubmitButtonLabel(
+ selectedTable: BulkTableInfo | null,
+ publishedRemappedTables: BulkTableInfo[],
+) {
+ return selectedTable != null && publishedRemappedTables.length === 0
+ ? t`Unpublish this table`
+ : t`Unpublish these tables`;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/UnpublishTablesModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/UnpublishTablesModal.unit.spec.tsx
new file mode 100644
index 00000000000..c7c07f31ac0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/UnpublishTablesModal.unit.spec.tsx
@@ -0,0 +1,151 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupTableSelectionInfoEndpoint,
+ setupUnpublishTablesEndpoint,
+ setupUnpublishTablesEndpointError,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type {
+ BulkTableSelectionInfo,
+ DatabaseId,
+ SchemaId,
+ TableId,
+} from "metabase-types/api";
+import {
+ createMockBulkTableInfo,
+ createMockBulkTableSelectionInfo,
+} from "metabase-types/api/mocks";
+
+import { UnpublishTablesModal } from "./UnpublishTablesModal";
+
+type SetupOpts = {
+ databaseIds?: DatabaseId[];
+ schemaIds?: SchemaId[];
+ tableIds?: TableId[];
+ selectionInfo?: BulkTableSelectionInfo;
+ hasUnpublishError?: boolean;
+};
+
+function setup({
+ databaseIds,
+ schemaIds,
+ tableIds,
+ selectionInfo = createMockBulkTableSelectionInfo(),
+ hasUnpublishError,
+}: SetupOpts = {}) {
+ const onUnpublish = jest.fn();
+ const onClose = jest.fn();
+
+ setupTableSelectionInfoEndpoint(selectionInfo);
+ if (hasUnpublishError) {
+ setupUnpublishTablesEndpointError();
+ } else {
+ setupUnpublishTablesEndpoint();
+ }
+
+ renderWithProviders(
+ <UnpublishTablesModal
+ databaseIds={databaseIds}
+ schemaIds={schemaIds}
+ tableIds={tableIds}
+ isOpened
+ onUnpublish={onUnpublish}
+ onClose={onClose}
+ />,
+ );
+
+ return { onUnpublish, onClose };
+}
+
+describe("UnpublishTablesModal", () => {
+ it("should be able to unpublish a single table", async () => {
+ const { onUnpublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: createMockBulkTableInfo({
+ id: 1,
+ display_name: "Orders",
+ }),
+ }),
+ });
+ expect(await screen.findByText("Unpublish Orders?")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Unpublish this table"));
+ await waitFor(() => expect(onUnpublish).toHaveBeenCalled());
+ });
+
+ it("should be able to unpublish a single table with remapped tables", async () => {
+ const { onUnpublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: createMockBulkTableInfo({
+ id: 1,
+ display_name: "Products",
+ }),
+ published_downstream_tables: [
+ createMockBulkTableInfo({
+ id: 2,
+ display_name: "Orders",
+ }),
+ ],
+ }),
+ });
+ expect(
+ await screen.findByText(
+ "Unpublish Products and the tables that depend on it?",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Orders")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Unpublish these tables"));
+ await waitFor(() => expect(onUnpublish).toHaveBeenCalled());
+ });
+
+ it("should be able to unpublish multiple tables", async () => {
+ const { onUnpublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: null,
+ }),
+ });
+ expect(
+ await screen.findByText("Unpublish these tables?"),
+ ).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Unpublish these tables"));
+ await waitFor(() => expect(onUnpublish).toHaveBeenCalled());
+ });
+
+ it("should be able to unpublish multiple tables with remapped tables", async () => {
+ const { onUnpublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: null,
+ published_downstream_tables: [
+ createMockBulkTableInfo({
+ id: 2,
+ display_name: "Orders",
+ }),
+ ],
+ }),
+ });
+ expect(
+ await screen.findByText(
+ "Unpublish these tables and the tables that depend on them?",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Orders")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Unpublish these tables"));
+ await waitFor(() => expect(onUnpublish).toHaveBeenCalled());
+ });
+
+ it("should show a unpublish error", async () => {
+ const { onUnpublish } = setup({
+ selectionInfo: createMockBulkTableSelectionInfo({
+ selected_table: createMockBulkTableInfo({
+ id: 1,
+ display_name: "Orders",
+ }),
+ }),
+ hasUnpublishError: true,
+ });
+ expect(await screen.findByText("Unpublish Orders?")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Unpublish this table"));
+ expect(await screen.findByText("An error occurred")).toBeInTheDocument();
+ expect(onUnpublish).not.toHaveBeenCalled();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/index.ts
new file mode 100644
index 00000000000..791e4800183
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/components/UnpublishTablesModal/index.ts
@@ -0,0 +1 @@
+export * from "./UnpublishTablesModal";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata/index.ts
new file mode 100644
index 00000000000..0b1deeb0d18
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata/index.ts
@@ -0,0 +1 @@
+export * from "./use-load-table-with-metadata";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata/use-load-table-with-metadata.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata/use-load-table-with-metadata.ts
new file mode 100644
index 00000000000..f310bd33db7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata/use-load-table-with-metadata.ts
@@ -0,0 +1,20 @@
+import { skipToken, useGetTableQueryMetadataQuery } from "metabase/api";
+import type { TableId } from "metabase-types/api";
+
+export function useLoadTableWithMetadata(tableId: TableId | undefined) {
+ const {
+ data: table,
+ isLoading,
+ error,
+ } = useGetTableQueryMetadataQuery(
+ tableId != null
+ ? { id: tableId, include_editable_data_model: true }
+ : skipToken,
+ );
+
+ return {
+ table,
+ isLoading,
+ error,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/analytics.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/analytics.ts
new file mode 100644
index 00000000000..efbc96eb608
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/analytics.ts
@@ -0,0 +1,10 @@
+import { trackSimpleEvent } from "metabase/lib/analytics";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
+
+export function trackMetadataChange(detail: MetadataEditEventDetail) {
+ trackSimpleEvent({
+ event: "metadata_edited",
+ event_detail: detail,
+ triggered_from: "data_studio",
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/PublishModelsModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/PublishModelsModal.tsx
deleted file mode 100644
index 05d9b4999bf..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/PublishModelsModal.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import { useState } from "react";
-import { push } from "react-router-redux";
-import { t } from "ttag";
-
-import {
- CollectionPickerModal,
- type CollectionPickerValueItem,
-} from "metabase/common/components/Pickers/CollectionPicker";
-import { useUserAcknowledgement } from "metabase/common/hooks/use-user-acknowledgement";
-import { useDispatch } from "metabase/lib/redux";
-import { useMetadataToasts } from "metabase/metadata/hooks";
-import { PLUGIN_DATA_STUDIO } from "metabase/plugins";
-import { Box, Button, Checkbox, Group, Modal, Text, rem } from "metabase/ui";
-import { usePublishModelsMutation } from "metabase-enterprise/api";
-import { trackDataStudioTablePublished } from "metabase-enterprise/data-studio/analytics";
-import type { DatabaseId, SchemaId, TableId } from "metabase-types/api";
-
-import { getPublishSeeItLink } from "../utils";
-
-interface Props {
- tables?: Set<TableId>;
- schemas?: Set<SchemaId>;
- databases?: Set<DatabaseId>;
- isOpen: boolean;
- onClose?: () => void;
- onSuccess?: () => void;
-}
-
-export function PublishModelsModal({
- tables = new Set(),
- schemas = new Set(),
- databases = new Set(),
- isOpen,
- onClose,
- onSuccess,
-}: Props) {
- const dispatch = useDispatch();
- const [seenPublishModelsInfo, { ack: ackSeenPublishModelsInfo }] =
- useUserAcknowledgement("seen-publish-models-info");
- const [showPublishInfo, setShowPublishInfo] = useState(
- !seenPublishModelsInfo,
- );
- const [publishModels] = usePublishModelsMutation();
- const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
-
- const defaultPublishCollection =
- PLUGIN_DATA_STUDIO.useGetLibraryChildCollectionByType({
- type: "library-models",
- });
-
- const handleSubmit = async (collection: CollectionPickerValueItem) => {
- if (!collection) {
- sendErrorToast(t`Please select a collection`);
- return;
- }
-
- const collectionId =
- collection.id === "root" ? null : Number(collection.id);
-
- const { error, data } = await publishModels({
- table_ids: Array.from(tables),
- schema_ids: Array.from(schemas),
- database_ids: Array.from(databases),
- target_collection_id: collectionId,
- });
-
- if (error) {
- sendErrorToast(t`Failed to publish models`);
- } else if (data) {
- trackDataStudioTablePublished(collectionId);
- sendSuccessToast(
- t`Published`,
- () => {
- dispatch(push(getPublishSeeItLink(data)));
- },
- t`See it`,
- );
- onSuccess?.();
- handleClose();
- }
- };
-
- const handleClose = () => {
- setShowPublishInfo(!seenPublishModelsInfo);
- onClose?.();
- };
-
- if (!isOpen) {
- return null;
- }
-
- if (showPublishInfo && !seenPublishModelsInfo) {
- return (
- <AcknowledgePublishModelsModal
- isOpen={true}
- handleSubmit={({ acknowledged }) => {
- if (acknowledged) {
- ackSeenPublishModelsInfo();
- }
- setShowPublishInfo(false);
- }}
- handleClose={() => {
- handleClose();
- }}
- />
- );
- }
-
- return (
- <CollectionPickerModal
- value={{
- id: defaultPublishCollection?.id || "root",
- model: "collection",
- }}
- options={{
- showSearch: true,
- hasConfirmButtons: true,
- showRootCollection: true,
- showPersonalCollections: true,
- confirmButtonText: t`Publish here`,
- }}
- title={t`Pick the collection to publish this table in`}
- onClose={() => {
- handleClose();
- }}
- onChange={(collection) => {
- handleSubmit(collection);
- }}
- />
- );
-}
-
-function AcknowledgePublishModelsModal({
- isOpen,
- handleSubmit,
- handleClose,
-}: {
- isOpen: boolean;
- handleSubmit: ({ acknowledged }: { acknowledged: boolean }) => void;
- handleClose: () => void;
-}) {
- const [isAcknowledged, setIsAcknowledged] = useState(false);
-
- return (
- <Modal
- opened={isOpen}
- padding="xl"
- size={rem(512)}
- title={t`What publishing a table does`}
- onClose={() => handleClose()}
- >
- <Text pt="sm">
- {t`Publishing a table means we'll create a model based on it and save it in the collection you choose so that it’s easy for your end users to find it.`}
- </Text>
-
- <Group pt="xl" justify="space-between">
- <Box>
- <Checkbox
- label={t`Don’t show this to me again`}
- checked={isAcknowledged}
- onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
- setIsAcknowledged(event.target.checked)
- }
- />
- </Box>
- <Button
- onClick={() => handleSubmit({ acknowledged: isAcknowledged })}
- variant="filled"
- >{t`Got it`}</Button>
- </Group>
- </Modal>
- );
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/PublishModelsModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/PublishModelsModal.unit.spec.tsx
deleted file mode 100644
index 4629ecf5a4d..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/PublishModelsModal.unit.spec.tsx
+++ /dev/null
@@ -1,319 +0,0 @@
-import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
-
-import {
- setupCollectionByIdEndpoint,
- setupCollectionItemsEndpoint,
- setupCollectionsEndpoints,
- setupRecentViewsAndSelectionsEndpoints,
- setupRecentViewsEndpoints,
- setupUserAcknowledgementEndpoints,
-} from "__support__/server-mocks";
-import {
- mockGetBoundingClientRect,
- renderWithProviders,
- screen,
- waitFor,
-} from "__support__/ui";
-import { UndoListing } from "metabase/common/components/UndoListing";
-import type { PublishModelsResponse } from "metabase-types/api";
-import { createMockCard, createMockCollection } from "metabase-types/api/mocks";
-
-import { PublishModelsModal } from "./PublishModelsModal";
-
-function setup(
- args: {
- isOpen?: boolean;
- tables?: Set<number | string>;
- schemas?: Set<string>;
- databases?: Set<number>;
- seenPublishModelsInfo?: boolean;
- publishResponse?: PublishModelsResponse;
- publishError?: boolean;
- } = {},
-) {
- const {
- isOpen = true,
- tables = new Set([1]),
- schemas = new Set<string>(),
- databases = new Set<number>(),
- seenPublishModelsInfo = true,
- publishResponse,
- publishError = false,
- } = args;
-
- const onClose = jest.fn();
- const onSuccess = jest.fn();
-
- setupUserAcknowledgementEndpoints({
- key: "seen-publish-models-info",
- value: seenPublishModelsInfo,
- });
- setupRecentViewsEndpoints([]);
- const testCollection = createMockCollection({
- id: 1,
- name: "Test Collection",
- });
- setupCollectionsEndpoints({
- collections: [testCollection],
- });
- setupRecentViewsAndSelectionsEndpoints([]);
- setupCollectionByIdEndpoint({ collections: [testCollection] });
- setupCollectionItemsEndpoint({
- collection: createMockCollection({ id: "root" }),
- collectionItems: [],
- });
- setupCollectionItemsEndpoint({
- collection: testCollection,
- collectionItems: [],
- });
-
- // Setup publish models API endpoint
- if (publishError) {
- fetchMock.post("path:/api/ee/data-studio/table/publish-model", {
- status: 500,
- body: { message: "Failed to publish" },
- });
- } else if (publishResponse) {
- fetchMock.post(
- "path:/api/ee/data-studio/table/publish-model",
- publishResponse,
- );
- } else {
- fetchMock.post("path:/api/ee/data-studio/table/publish-model", {
- created_count: 1,
- models: [createMockCard({ id: 1 })],
- target_collection: testCollection,
- });
- }
-
- mockGetBoundingClientRect();
-
- renderWithProviders(
- <>
- <PublishModelsModal
- isOpen={isOpen}
- tables={tables}
- schemas={schemas}
- databases={databases}
- onClose={onClose}
- onSuccess={onSuccess}
- />
- <UndoListing />
- </>,
- {
- withRouter: false,
- },
- );
-
- return {
- onClose,
- onSuccess,
- };
-}
-
-function getCheckbox() {
- return screen.getByRole("checkbox", {
- name: "Don’t show this to me again",
- });
-}
-
-describe("PublishModelsModal", () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it("renders nothing when isOpen is false", () => {
- setup({ isOpen: false });
-
- expect(
- screen.queryByText("Pick the collection to publish this table in"),
- ).not.toBeInTheDocument();
- expect(
- screen.queryByText("What publishing a table does"),
- ).not.toBeInTheDocument();
- });
-
- it("renders collection picker when user has seen publish models info", async () => {
- setup({ seenPublishModelsInfo: true });
-
- await waitFor(() => {
- expect(
- screen.getByText("Pick the collection to publish this table in"),
- ).toBeInTheDocument();
- });
- });
-
- it("calls onClose when closing info modal", async () => {
- const { onClose } = setup({ seenPublishModelsInfo: false });
-
- const closeButton = screen.getByRole("button", { name: /close/i });
- await userEvent.click(closeButton);
-
- await waitFor(() => {
- expect(onClose).toHaveBeenCalled();
- });
- });
-
- it("calls onClose when closing collection picker", async () => {
- const { onClose } = setup({ seenPublishModelsInfo: true });
-
- await waitFor(() => {
- expect(
- screen.getByText("Pick the collection to publish this table in"),
- ).toBeInTheDocument();
- });
-
- const closeButton = screen.getByRole("button", { name: /close/i });
- await userEvent.click(closeButton);
-
- await waitFor(() => {
- expect(onClose).toHaveBeenCalled();
- });
- });
-
- it("handles success flow correctly", async () => {
- const publishResponse: PublishModelsResponse = {
- created_count: 1,
- models: [createMockCard({ id: 1 })],
- target_collection: createMockCollection({ id: 1 }),
- };
-
- const { onSuccess } = setup({
- seenPublishModelsInfo: false,
- tables: new Set([1, 2]),
- schemas: new Set<string>(["10"]),
- databases: new Set([100]),
- publishResponse,
- });
-
- const checkbox = getCheckbox();
- await userEvent.click(checkbox);
-
- const gotItButton = screen.getByRole("button", { name: "Got it" });
- await userEvent.click(gotItButton);
-
- await waitFor(() => {
- expect(
- fetchMock.callHistory.called(
- "path:/api/user-key-value/namespace/user_acknowledgement/key/seen-publish-models-info",
- { method: "PUT" },
- ),
- ).toBe(true);
- });
-
- await waitFor(() => {
- expect(
- screen.getByText("Pick the collection to publish this table in"),
- ).toBeInTheDocument();
- });
-
- // Select a collection and confirm
- const collectionLink = await screen.findByText("Test Collection");
- await userEvent.click(collectionLink);
-
- const publishButton = await screen.findByRole("button", {
- name: "Publish here",
- });
- await userEvent.click(publishButton);
-
- await waitFor(() => {
- expect(
- fetchMock.callHistory.called(
- "path:/api/ee/data-studio/table/publish-model",
- ),
- ).toBe(true);
- });
-
- const lastCall = fetchMock.callHistory.lastCall(
- "path:/api/ee/data-studio/table/publish-model",
- );
- expect(lastCall).toBeTruthy();
- const body = lastCall?.options?.body;
- expect(body).toBeTruthy();
- const parsedBody = typeof body === "string" ? JSON.parse(body) : body;
- expect(parsedBody.table_ids).toEqual([1, 2]);
- expect(parsedBody.schema_ids).toEqual(["10"]);
- expect(parsedBody.database_ids).toEqual([100]);
- expect(parsedBody.target_collection_id).toBe(1);
-
- // make sure we call onSuccess
- await waitFor(() => {
- expect(onSuccess).toHaveBeenCalled();
- });
-
- // make sure we show the success toast
- await waitFor(() => {
- expect(screen.getByText(/Published/i)).toBeInTheDocument();
- });
- });
-
- it("shows error toast when publishModels API fails", async () => {
- setup({
- seenPublishModelsInfo: true,
- publishError: true,
- });
-
- await waitFor(() => {
- expect(
- screen.getByText("Pick the collection to publish this table in"),
- ).toBeInTheDocument();
- });
-
- const collectionLink = await screen.findByText("Test Collection");
- await userEvent.click(collectionLink);
-
- const publishButton = await screen.findByRole("button", {
- name: "Publish here",
- });
- await userEvent.click(publishButton);
-
- await waitFor(() => {
- expect(screen.getByText(/Failed to publish models/i)).toBeInTheDocument();
- });
- });
-
- it("handles root collection selection correctly", async () => {
- const publishResponse: PublishModelsResponse = {
- created_count: 1,
- models: [createMockCard({ id: 1 })],
- target_collection: createMockCollection({ id: "root" }),
- };
-
- setup({
- seenPublishModelsInfo: true,
- publishResponse,
- });
-
- await waitFor(() => {
- expect(
- screen.getByText("Pick the collection to publish this table in"),
- ).toBeInTheDocument();
- });
-
- const rootCollectionLink = await screen.findByText(/Our Analytics/i);
- await userEvent.click(rootCollectionLink);
-
- const publishButton = await screen.findByRole("button", {
- name: "Publish here",
- });
- await userEvent.click(publishButton);
-
- await waitFor(() => {
- expect(
- fetchMock.callHistory.called(
- "path:/api/ee/data-studio/table/publish-model",
- ),
- ).toBe(true);
- });
-
- const lastCall = fetchMock.callHistory.lastCall(
- "path:/api/ee/data-studio/table/publish-model",
- );
- expect(lastCall).toBeTruthy();
- const body = lastCall?.options?.body;
- expect(body).toBeTruthy();
- const parsedBody = typeof body === "string" ? JSON.parse(body) : body;
- expect(parsedBody.target_collection_id).toBeNull();
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Results.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Results.tsx
index 86093422b3c..c7d0fdad69f 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Results.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Results.tsx
@@ -1,12 +1,6 @@
import { useVirtualizer } from "@tanstack/react-virtual";
import cx from "classnames";
-import {
- type KeyboardEvent,
- useContext,
- useEffect,
- useMemo,
- useRef,
-} from "react";
+import { type KeyboardEvent, useEffect, useMemo, useRef } from "react";
import { Link } from "react-router";
import { useLatest } from "react-use";
import { t } from "ttag";
@@ -16,8 +10,7 @@ import {
type NumberFormatter,
useNumberFormatter,
} from "metabase/common/hooks/use-number-formatter";
-import { DataModelContext } from "metabase/metadata/pages/shared/DataModelContext";
-import { getUrl } from "metabase/metadata/pages/shared/utils";
+import * as Urls from "metabase/lib/urls";
import { Box, Checkbox, Flex, Icon, Skeleton, Stack, rem } from "metabase/ui";
import type { UserId } from "metabase-types/api";
@@ -365,7 +358,6 @@ const ResultsItem = ({
ownerNameById,
}: ResultsItemProps) => {
const { selectedItemsCount } = useSelection();
- const { baseUrl } = useContext(DataModelContext);
const { value, label, type, isExpanded, isLoading, key, level, disabled } =
item;
const formatNumber = useNumberFormatter({ maximumFractionDigits: 0 });
@@ -504,7 +496,7 @@ const ResultsItem = ({
transform: `translateY(${start}px)`,
pointerEvents: disabled ? "none" : undefined,
}}
- to={getUrl(baseUrl, {
+ to={Urls.dataStudioData({
databaseId: value?.databaseId,
schemaName:
type === "schema" || isTableNode(item)
@@ -642,7 +634,7 @@ function getPublishedDisplay(item: FlatItem): React.ReactNode {
return null;
}
- return item.table.published_as_model ? (
+ return item.table.is_published ? (
<Icon name="verified_round" aria-label={t`Published`} />
) : null;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/SearchNew.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/SearchNew.tsx
index 676898d8cf5..a40213fac76 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/SearchNew.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/SearchNew.tsx
@@ -31,7 +31,6 @@ interface SearchNewProps {
query: string;
params: RouteParams;
filters: FilterState;
- setOnUpdateCallback: (callback: (() => void) | null) => void;
}
function buildResultTree(tables: Table[]): RootNode {
@@ -95,12 +94,7 @@ function buildResultTree(tables: Table[]): RootNode {
return root;
}
-export function SearchNew({
- query,
- params,
- filters,
- setOnUpdateCallback,
-}: SearchNewProps) {
+export function SearchNew({ query, params, filters }: SearchNewProps) {
const {
selectedTables,
setSelectedTables,
@@ -109,11 +103,7 @@ export function SearchNew({
resetSelection,
} = useSelection();
const routeParams = parseRouteParams(params);
- const {
- data: tables,
- isLoading: isLoadingTables,
- refetch,
- } = useListTablesQuery({
+ const { data: tables, isLoading: isLoadingTables } = useListTablesQuery({
term: query,
"data-layer": filters.dataLayer ?? undefined,
"data-source":
@@ -152,11 +142,6 @@ export function SearchNew({
const isLoading = isLoadingTables || isLoadingDatabases;
- useEffect(() => {
- setOnUpdateCallback(() => refetch);
- return () => setOnUpdateCallback(null);
- }, [refetch, setOnUpdateCallback]);
-
const resultTree = useMemo(
() => buildResultTree(filteredTables),
[filteredTables],
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.tsx
index 84bd6de2ecd..904a849128b 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.tsx
@@ -22,7 +22,6 @@ import type { ChangeOptions, FilterState, TreePath } from "../types";
import { getFiltersCount } from "../utils";
import { FilterPopover } from "./FilterPopover";
-import { PublishModelsModal } from "./PublishModelsModal";
import { SearchNew } from "./SearchNew";
import { Tree } from "./Tree";
@@ -39,9 +38,7 @@ export function TablePicker({
className,
onChange,
}: TablePickerProps) {
- const { selectedTables, selectedSchemas, selectedDatabases, resetSelection } =
- useSelection();
-
+ const { resetSelection } = useSelection();
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query);
const previousDeferredQuery = usePrevious(deferredQuery);
@@ -55,18 +52,6 @@ export function TablePicker({
const [isOpen, { toggle, close }] = useDisclosure();
const filtersCount = getFiltersCount(filters);
- const [isCreateModelsModalOpen, setIsCreateModelsModalOpen] = useState(false);
- const [onUpdateCallback, setOnUpdateCallback] = useState<(() => void) | null>(
- null,
- );
-
- function handlePublishSuccess() {
- if (onUpdateCallback) {
- onUpdateCallback();
- }
- resetSelection();
- }
-
useEffect(() => {
const togglingBetweenSearchAndTree =
(previousDeferredQuery === "" && deferredQuery !== "") ||
@@ -145,29 +130,11 @@ export function TablePicker({
<Box mih={0} flex="1 1 auto">
{deferredQuery === "" && filtersCount === 0 ? (
- <Tree
- path={path}
- onChange={onChange}
- setOnUpdateCallback={setOnUpdateCallback}
- />
+ <Tree path={path} onChange={onChange} />
) : (
- <SearchNew
- query={deferredQuery}
- params={params}
- filters={filters}
- setOnUpdateCallback={setOnUpdateCallback}
- />
+ <SearchNew query={deferredQuery} params={params} filters={filters} />
)}
</Box>
-
- <PublishModelsModal
- tables={selectedTables}
- schemas={selectedSchemas}
- databases={selectedDatabases}
- isOpen={isCreateModelsModalOpen}
- onClose={() => setIsCreateModelsModalOpen(false)}
- onSuccess={handlePublishSuccess}
- />
</Stack>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsx
index 3aeaeaaabb6..9478bb8c4e2 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsx
@@ -161,7 +161,7 @@ function setup({
setupUsersEndpoints([currentUser]);
setupUserKeyValueEndpoints({
namespace: "user_acknowledgement",
- key: "seen-publish-models-info",
+ key: "seen-publish-tables-info",
value: false,
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Tree.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Tree.tsx
index 06d1b30b30b..38a538c8b4f 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Tree.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/components/Tree.tsx
@@ -41,10 +41,9 @@ import { TablePickerResults } from "./Results";
interface Props {
path: TreePath;
onChange: (path: TreePath, options?: ChangeOptions) => void;
- setOnUpdateCallback: (callback: (() => void) | null) => void;
}
-export function Tree({ path, onChange, setOnUpdateCallback }: Props) {
+export function Tree({ path, onChange }: Props) {
const {
selectedTables,
setSelectedTables,
@@ -57,11 +56,6 @@ export function Tree({ path, onChange, setOnUpdateCallback }: Props) {
const { isExpanded, toggle } = useExpandedState(path);
const { tree, reload } = useTableLoader(path);
- useEffect(() => {
- setOnUpdateCallback(() => () => reload(path));
- return () => setOnUpdateCallback(null);
- }, [path, reload, setOnUpdateCallback]);
-
const items = flatten(tree, {
isExpanded,
addLoadingNodes: true,
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/utils.ts
index ef382c0d174..725ccc241ce 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/utils.ts
@@ -1,7 +1,3 @@
-import * as Urls from "metabase/lib/urls";
-import { getUrl as getUrl_ } from "metabase/metadata/pages/shared/utils";
-import type { PublishModelsResponse } from "metabase-types/api";
-
import { type NodeSelection, isItemSelected } from "./bulk-selection.utils";
import { CHILD_TYPES, UNNAMED_SCHEMA_NAME } from "./constants";
import type {
@@ -20,16 +16,6 @@ export function hasChildren(type: ItemType): boolean {
return type !== "table";
}
-export function getUrl(baseUrl: string, value: TreePath) {
- return getUrl_(baseUrl, {
- fieldId: undefined,
- tableId: undefined,
- databaseId: undefined,
- schemaName: undefined,
- ...value,
- });
-}
-
// Returns a new state object with all the nodes along the path expanded.
// Note: This only expands parent containers (database, schema) but NOT tables,
// to prevent unwanted expansion when navigating via checkbox selection.
@@ -250,21 +236,3 @@ export function getFiltersCount(filters: FilterState): number {
return count;
}
-
-export function getPublishSeeItLink(response: PublishModelsResponse) {
- if (response.target_collection?.type === "library-models") {
- if (response.created_count === 1) {
- return Urls.dataStudioModel(response.models[0].id);
- } else {
- return Urls.dataStudioCollection(
- response.target_collection?.id ?? "root",
- );
- }
- } else {
- if (response.created_count === 1) {
- return Urls.model(response.models[0]);
- } else {
- return Urls.collection(response.target_collection);
- }
- }
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/wrappers.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/wrappers.tsx
index 99fe10a5fe2..5c0b5e00ff3 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/wrappers.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TablePicker/wrappers.tsx
@@ -1,15 +1,13 @@
-import { useCallback, useContext, useEffect, useState } from "react";
-import { push, replace } from "react-router-redux";
+import { useCallback, useEffect, useState } from "react";
+import { replace } from "react-router-redux";
-import { useDispatch, useSelector } from "metabase/lib/redux";
-import { DataModelContext } from "metabase/metadata/pages/shared/DataModelContext";
-import { getLocation } from "metabase/selectors/routing";
+import { useDispatch } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
import type { RouteParams } from "../../pages/DataModel/types";
import { TablePicker } from "./components";
-import type { ChangeOptions, TreePath } from "./types";
-import { getUrl } from "./utils";
+import type { TreePath } from "./types";
type Props = TreePath & {
params: RouteParams;
@@ -18,9 +16,6 @@ type Props = TreePath & {
export function RouterTablePicker({ params, ...props }: Props) {
const dispatch = useDispatch();
const [value, setValue] = useState(props);
- const location = useSelector(getLocation);
- const { baseUrl } = useContext(DataModelContext);
- const isSegments = location.pathname?.startsWith(`${baseUrl}/segment`);
const {
databaseId: propDatabaseId,
schemaName: propSchemaName,
@@ -28,7 +23,7 @@ export function RouterTablePicker({ params, ...props }: Props) {
} = props;
const onChange = useCallback(
- (value: TreePath, options?: ChangeOptions) => {
+ (value: TreePath) => {
setValue(value);
// Update URL only when either opening a table or no table has been opened yet.
@@ -36,17 +31,10 @@ export function RouterTablePicker({ params, ...props }: Props) {
const canUpdateUrl = value.tableId != null || propTableId == null;
if (canUpdateUrl) {
- if (options?.isAutomatic) {
- // prevent auto-navigation from table-picker when Segments tab is open
- if (!isSegments) {
- dispatch(replace(getUrl(baseUrl, value)));
- }
- } else {
- dispatch(push(getUrl(baseUrl, value)));
- }
+ dispatch(replace(Urls.dataStudioData(value)));
}
},
- [dispatch, baseUrl, isSegments, propTableId],
+ [dispatch, propTableId],
);
useEffect(() => {
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.module.css
new file mode 100644
index 00000000000..c099e1f0102
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.module.css
@@ -0,0 +1,7 @@
+.card {
+ box-shadow: 0 2px 4px 0 hsla(0, 0%, 0%, 0.05);
+
+ &:hover {
+ background-color: var(--mb-color-brand-lighter);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.tsx
new file mode 100644
index 00000000000..5dbf677e3f3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.tsx
@@ -0,0 +1,42 @@
+import { Link } from "react-router";
+
+import { Ellipsified } from "metabase/common/components/Ellipsified";
+import { Card, Flex, Icon, Stack, Text } from "metabase/ui";
+import type { Segment } from "metabase-types/api";
+
+import S from "./SegmentItem.module.css";
+
+type SegmentItemProps = {
+ segment: Segment;
+ href: string;
+};
+
+export function SegmentItem({ segment, href }: SegmentItemProps) {
+ return (
+ <Card
+ className={S.card}
+ component={Link}
+ to={href}
+ aria-label={segment.name}
+ role="listitem"
+ px="md"
+ py="0.75rem"
+ withBorder
+ >
+ <Stack gap="xs">
+ <Flex align="center" gap="sm">
+ <Icon name="segment2" c="brand" />
+ <Ellipsified lines={1} tooltip={segment.name}>
+ <Text fw="bold">{segment.name}</Text>
+ </Ellipsified>
+ </Flex>
+
+ {segment.definition_description && (
+ <Text data-testid="list-item-description">
+ {segment.definition_description}
+ </Text>
+ )}
+ </Stack>
+ </Card>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.unit.spec.tsx
new file mode 100644
index 00000000000..b9e7a171875
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentItem.unit.spec.tsx
@@ -0,0 +1,55 @@
+import { Route } from "react-router";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockSegment } from "metabase-types/api/mocks";
+
+import { SegmentItem } from "./SegmentItem";
+
+describe("SegmentItem", () => {
+ it("should render segment with name, description, link, and list role", () => {
+ const segment = createMockSegment({
+ name: "Premium Customers",
+ definition_description: "Total > $1000",
+ });
+
+ renderWithProviders(
+ <Route
+ path="/"
+ component={() => (
+ <SegmentItem
+ segment={segment}
+ href="/data-studio/modeling/segments/42"
+ />
+ )}
+ />,
+ { withRouter: true },
+ );
+
+ expect(screen.getByText("Premium Customers")).toBeInTheDocument();
+ expect(screen.getByText("Total > $1000")).toBeInTheDocument();
+
+ const item = screen.getByRole("listitem");
+ expect(item).toBeInTheDocument();
+ expect(item).toHaveAttribute("href", "/data-studio/modeling/segments/42");
+ expect(item).toHaveAttribute("aria-label", "Premium Customers");
+ });
+
+ it("should not render definition description when empty", () => {
+ const segment = createMockSegment({
+ name: "Premium",
+ definition_description: "",
+ });
+
+ renderWithProviders(
+ <Route
+ path="/"
+ component={() => <SegmentItem segment={segment} href="/test" />}
+ />,
+ { withRouter: true },
+ );
+
+ expect(
+ screen.queryByTestId("list-item-description"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentList.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentList.tsx
new file mode 100644
index 00000000000..8c8d23fb05a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentList.tsx
@@ -0,0 +1,52 @@
+import { t } from "ttag";
+
+import EmptyState from "metabase/common/components/EmptyState";
+import { ForwardRefLink } from "metabase/common/components/Link";
+import * as Urls from "metabase/lib/urls";
+import { Button, Group, Icon, Stack } from "metabase/ui";
+import type { Segment, TableId } from "metabase-types/api";
+
+import { SegmentItem } from "./SegmentItem";
+
+type SegmentListProps = {
+ segments: Segment[];
+ tableId: TableId;
+};
+
+export function SegmentList({ segments, tableId }: SegmentListProps) {
+ return (
+ <Stack gap="md">
+ <Group gap="md" justify="flex-start" wrap="nowrap">
+ <Button
+ component={ForwardRefLink}
+ to={Urls.newDataStudioSegment(tableId)}
+ h={32}
+ px="sm"
+ py="xs"
+ size="xs"
+ leftSection={<Icon name="add" />}
+ >{t`New segment`}</Button>
+ </Group>
+
+ {segments.length === 0 ? (
+ <EmptyState
+ illustrationElement={
+ <Icon name="segment2" size={32} c="text-secondary" />
+ }
+ title={t`No segments yet`}
+ message={t`Create a segment to filter rows in this table.`}
+ />
+ ) : (
+ <Stack gap="sm" role="list">
+ {segments.map((segment) => (
+ <SegmentItem
+ key={segment.id}
+ segment={segment}
+ href={Urls.dataStudioSegment(segment.id)}
+ />
+ ))}
+ </Stack>
+ )}
+ </Stack>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentList.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentList.unit.spec.tsx
new file mode 100644
index 00000000000..38f75a24e18
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/SegmentList.unit.spec.tsx
@@ -0,0 +1,56 @@
+import { Route } from "react-router";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import type { Segment, TableId } from "metabase-types/api";
+import { createMockSegment } from "metabase-types/api/mocks";
+
+import { SegmentList } from "./SegmentList";
+
+type SetupOpts = {
+ segments?: Segment[];
+ tableId?: TableId;
+};
+
+function setup({ segments = [], tableId = 1 }: SetupOpts = {}) {
+ renderWithProviders(
+ <Route
+ path="/"
+ component={() => <SegmentList segments={segments} tableId={tableId} />}
+ />,
+ { withRouter: true },
+ );
+}
+
+describe("SegmentList", () => {
+ it("should render empty state when no segments", () => {
+ setup({ segments: [] });
+
+ expect(screen.getByText("No segments yet")).toBeInTheDocument();
+ expect(
+ screen.getByText("Create a segment to filter rows in this table."),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: /New segment/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("should render segment items", () => {
+ const segments = [
+ createMockSegment({
+ id: 1,
+ name: "High Value",
+ definition_description: "Price > 100",
+ }),
+ createMockSegment({ id: 2, name: "Active Users" }),
+ ];
+ setup({ segments });
+
+ expect(screen.getByRole("list")).toBeInTheDocument();
+ expect(screen.getByText("High Value")).toBeInTheDocument();
+ expect(screen.getByText("Price > 100")).toBeInTheDocument();
+ expect(screen.getByText("Active Users")).toBeInTheDocument();
+ expect(
+ screen.getByRole("listitem", { name: "High Value" }),
+ ).toHaveAttribute("href", "/data-studio/modeling/segments/1");
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.tsx
index fb512ea9715..9cf4b80fba0 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.tsx
@@ -1,4 +1,3 @@
-import { useDisclosure } from "@mantine/hooks";
import { useEffect, useState } from "react";
import { t } from "ttag";
@@ -11,6 +10,9 @@ import {
import { useMetadataToasts } from "metabase/metadata/hooks";
import { Box, Button, Group, Icon, Stack, Title } from "metabase/ui";
import { useEditTablesMutation } from "metabase-enterprise/api";
+import { CreateLibraryModal } from "metabase-enterprise/data-studio/common/components/CreateLibraryModal";
+import { PublishTablesModal } from "metabase-enterprise/data-studio/common/components/PublishTablesModal";
+import { UnpublishTablesModal } from "metabase-enterprise/data-studio/common/components/UnpublishTablesModal";
import type {
TableDataLayer,
TableDataSource,
@@ -19,19 +21,25 @@ import type {
import { useSelection } from "../../pages/DataModel/contexts/SelectionContext";
import { SyncOptionsModal } from "../SyncOptionsModal";
-import { PublishModelsModal } from "../TablePicker/components/PublishModelsModal";
import S from "./TableAttributes.module.css";
import { TableSectionGroup } from "./TableSectionGroup";
-export function TableAttributesEditBulk() {
+type TableAttributesEditBulkProps = {
+ hasLibrary: boolean;
+};
+
+type TableModalType = "library" | "publish" | "unpublish" | "sync";
+
+export function TableAttributesEditBulk({
+ hasLibrary,
+}: TableAttributesEditBulkProps) {
const {
- selectedTables,
- selectedSchemas,
selectedDatabases,
+ selectedSchemas,
+ selectedTables,
selectedItemsCount,
} = useSelection();
- const [isCreateModelsModalOpen, setIsCreateModelsModalOpen] = useState(false);
const { sendErrorToast, sendSuccessToast } = useMetadataToasts();
const [editTables] = useEditTablesMutation();
const [dataLayer, setDataLayer] = useState<TableDataLayer | null>(null);
@@ -41,8 +49,7 @@ export function TableAttributesEditBulk() {
const [email, setEmail] = useState<string | null>(null);
const [entityType, setEntityType] = useState<string | null>(null);
const [userId, setUserId] = useState<UserId | "unknown" | null>(null);
- const [isSyncModalOpen, { close: closeSyncModal, open: openSyncModal }] =
- useDisclosure();
+ const [modalType, setModalType] = useState<TableModalType>();
const hasOnlyTablesSelected =
selectedTables.size > 0 &&
@@ -99,6 +106,10 @@ export function TableAttributesEditBulk() {
}
};
+ const handleCloseModal = () => {
+ setModalType(undefined);
+ };
+
useEffect(() => {
setDataLayer(null);
setDataSource(null);
@@ -136,27 +147,31 @@ export function TableAttributesEditBulk() {
<Box px="lg">
<Group gap="sm">
- <Box flex={1}>
+ <Button
+ flex={1}
+ p="sm"
+ leftSection={<Icon name="publish" />}
+ onClick={() => setModalType(hasLibrary ? "publish" : "library")}
+ >
+ {t`Publish`}
+ </Button>
+ {hasLibrary && (
<Button
- leftSection={<Icon name="settings" />}
- onClick={openSyncModal}
- style={{
- width: "100%",
- }}
+ flex={1}
+ p="sm"
+ leftSection={<Icon name="unpublish" />}
+ onClick={() => setModalType("unpublish")}
>
- {t`Sync settings`}
+ {t`Unpublish`}
</Button>
- </Box>
- <Box flex={1}>
- <Button
- onClick={() => setIsCreateModelsModalOpen(true)}
- p="sm"
- leftSection={<Icon name="add_folder" />}
- style={{
- width: "100%",
- }}
- >{t`Publish`}</Button>
- </Box>
+ )}
+ <Button
+ flex={1}
+ leftSection={<Icon name="settings" />}
+ onClick={() => setModalType("sync")}
+ >
+ {t`Sync settings`}
+ </Button>
</Group>
</Box>
@@ -235,20 +250,38 @@ export function TableAttributesEditBulk() {
</Box>
</Stack>
- <PublishModelsModal
- tables={selectedTables}
- schemas={selectedSchemas}
- databases={selectedDatabases}
- isOpen={isCreateModelsModalOpen}
- onClose={() => setIsCreateModelsModalOpen(false)}
+ <CreateLibraryModal
+ title={t`First, let's create your Library`}
+ explanatorySentence={t`This is where published tables will go.`}
+ isOpened={modalType === "library"}
+ onCreate={() => setModalType("publish")}
+ onClose={handleCloseModal}
+ />
+
+ <PublishTablesModal
+ isOpened={modalType === "publish"}
+ databaseIds={Array.from(selectedDatabases)}
+ schemaIds={Array.from(selectedSchemas)}
+ tableIds={Array.from(selectedTables)}
+ onPublish={handleCloseModal}
+ onClose={handleCloseModal}
+ />
+
+ <UnpublishTablesModal
+ isOpened={modalType === "unpublish"}
+ databaseIds={Array.from(selectedDatabases)}
+ schemaIds={Array.from(selectedSchemas)}
+ tableIds={Array.from(selectedTables)}
+ onUnpublish={handleCloseModal}
+ onClose={handleCloseModal}
/>
<SyncOptionsModal
- isOpen={isSyncModalOpen}
+ isOpen={modalType === "sync"}
databaseIds={Array.from(selectedDatabases)}
schemaIds={Array.from(selectedSchemas)}
tableIds={Array.from(selectedTables)}
- onClose={closeSyncModal}
+ onClose={handleCloseModal}
/>
</>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.unit.spec.tsx
index 89f8d855d05..b60d059cca7 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableAttributesEditBulk.unit.spec.tsx
@@ -55,7 +55,7 @@ function TestWrapper({
return (
<SelectionProvider>
- <TableAttributesEditBulk />
+ <TableAttributesEditBulk hasLibrary />
<SelectionController
initialTables={initialTables}
onSelectionChange={() => setSelectionChanged(true)}
@@ -70,7 +70,7 @@ function setup({
setupUsersEndpoints([createMockUser()]);
setupUserKeyValueEndpoints({
namespace: "user_acknowledgement",
- key: "seen-publish-models-info",
+ key: "seen-publish-tables-info",
value: true,
});
setupTableEndpoints(createMockTable());
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableCollection.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableCollection.module.css
new file mode 100644
index 00000000000..35d5ac3e5d7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableCollection.module.css
@@ -0,0 +1,5 @@
+.link {
+ &:hover {
+ color: var(--mb-color-brand);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableCollection.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableCollection.tsx
new file mode 100644
index 00000000000..f9aa4425c77
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableCollection.tsx
@@ -0,0 +1,36 @@
+import { Link } from "react-router";
+import { t } from "ttag";
+
+import * as Urls from "metabase/lib/urls";
+import { Box } from "metabase/ui";
+import type { Table } from "metabase-types/api";
+
+import S from "./TableCollection.module.css";
+import { TableSectionGroup } from "./TableSectionGroup";
+
+type TableCollectionProps = {
+ table: Table;
+};
+
+export function TableCollection({ table }: TableCollectionProps) {
+ const { collection } = table;
+
+ return (
+ <>
+ <TableSectionGroup title={t`This table has been published`}>
+ {collection != null ? (
+ <Box
+ className={S.link}
+ component={Link}
+ to={Urls.dataStudioCollection(collection.id)}
+ fw="bold"
+ >
+ {collection.name}
+ </Box>
+ ) : (
+ <Box>{t`You don't have access to this collection`}</Box>
+ )}
+ </TableSectionGroup>
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableModels.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableModels.module.css
deleted file mode 100644
index 0e9d60d92a2..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableModels.module.css
+++ /dev/null
@@ -1,22 +0,0 @@
-.modelItem {
- padding: 8px;
- border-radius: 8px;
- transition: background-color 0.2s ease;
- cursor: pointer;
-}
-
-.modelItem:hover {
- background-color: var(--mb-color-bg-light);
-}
-
-.modelName {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.collectionName {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableModels.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableModels.tsx
deleted file mode 100644
index 1088620721f..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableModels.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { Link } from "react-router";
-import { t } from "ttag";
-
-import * as Urls from "metabase/lib/urls";
-import { Box, Group, Icon, Stack, Text } from "metabase/ui";
-import type { Table } from "metabase-types/api";
-
-import S from "./TableModels.module.css";
-import { TableSectionGroup } from "./TableSectionGroup";
-
-interface Props {
- table: Table;
-}
-
-export function TableModels({ table }: Props) {
- if (table.published_models == null || table.published_models.length === 0) {
- return null;
- }
-
- return (
- <Box px="lg">
- <TableSectionGroup title={t`This table has been published as a model`}>
- <Stack gap={8}>
- {table.published_models.map((model) => {
- return (
- <Box
- key={model.id}
- className={S.modelItem}
- component={Link}
- to={Urls.dataStudioModel(model.id)}
- >
- <Group gap={8} wrap="nowrap" align="flex-start">
- <Icon name="model" size={16} c="brand" />
- <Stack gap={4} style={{ flex: 1, minWidth: 0 }}>
- <Text fw="bold" size="md" lh="md" className={S.modelName}>
- {model.name}
- </Text>
- {model.collection && (
- <Text
- c="text-medium"
- size="xs"
- lh="16px"
- className={S.collectionName}
- >
- {model.collection.name}
- </Text>
- )}
- </Stack>
- </Group>
- </Box>
- );
- })}
- </Stack>
- </TableSectionGroup>
- </Box>
- );
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.tsx
index 7c5c6bedab1..fb2d34bb0bb 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.tsx
@@ -1,5 +1,5 @@
-import { memo, useContext, useState } from "react";
-import { Link } from "react-router";
+import { memo, useCallback, useState } from "react";
+import { push } from "react-router-redux";
import { t } from "ttag";
import {
@@ -7,16 +7,19 @@ import {
useUpdateTableMutation,
} from "metabase/api";
import EmptyState from "metabase/common/components/EmptyState";
+import { ForwardRefLink } from "metabase/common/components/Link";
+import { useDispatch } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
+import type { DataStudioTableMetadataTab } from "metabase/lib/urls/data-studio";
import { dependencyGraph } from "metabase/lib/urls/dependencies";
import {
FieldOrderPicker,
NameDescriptionInput,
} from "metabase/metadata/components";
+import { ResponsiveButton } from "metabase/metadata/components/ResponsiveButton";
+import { TableFieldList } from "metabase/metadata/components/TableFieldList";
+import { TableSortableFieldList } from "metabase/metadata/components/TableSortableFieldList";
import { useMetadataToasts } from "metabase/metadata/hooks";
-import { DataModelContext } from "metabase/metadata/pages/shared/DataModelContext";
-import { ResponsiveButton } from "metabase/metadata/pages/shared/ResponsiveButton";
-import { getUrl } from "metabase/metadata/pages/shared/utils";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import {
Box,
@@ -25,52 +28,80 @@ import {
Icon,
Loader,
Stack,
- Text,
+ Tabs,
Tooltip,
} from "metabase/ui";
+import { CreateLibraryModal } from "metabase-enterprise/data-studio/common/components/CreateLibraryModal";
+import { PublishTablesModal } from "metabase-enterprise/data-studio/common/components/PublishTablesModal";
+import { UnpublishTablesModal } from "metabase-enterprise/data-studio/common/components/UnpublishTablesModal";
import type { FieldId, Table, TableFieldOrder } from "metabase-types/api";
-import { PublishModelsModal } from "../TablePicker/components/PublishModelsModal";
-
+import { SegmentList } from "./SegmentList";
import { TableAttributesEditSingle } from "./TableAttributesEditSingle";
-import { TableFieldList } from "./TableFieldList";
+import { TableCollection } from "./TableCollection";
import { TableMetadata } from "./TableMetadata";
-import { TableModels } from "./TableModels";
import S from "./TableSection.module.css";
import { TableSectionGroup } from "./TableSectionGroup";
-import { TableSortableFieldList } from "./TableSortableFieldList";
interface Props {
table: Table;
activeFieldId?: FieldId;
+ activeTab: DataStudioTableMetadataTab;
+ hasLibrary: boolean;
onSyncOptionsClick: () => void;
}
+type TableModalType = "library" | "publish" | "unpublish";
+
const TableSectionBase = ({
table,
activeFieldId,
+ activeTab,
+ hasLibrary,
onSyncOptionsClick,
}: Props) => {
const [updateTable] = useUpdateTableMutation();
const [updateTableSorting, { isLoading: isUpdatingSorting }] =
useUpdateTableMutation();
const [updateTableFieldsOrder] = useUpdateTableFieldsOrderMutation();
+ const [modalType, setModalType] = useState<TableModalType>();
const { sendErrorToast, sendSuccessToast, sendUndoToast } =
useMetadataToasts();
- const { baseUrl } = useContext(DataModelContext);
const [isSorting, setIsSorting] = useState(false);
const hasFields = Boolean(table.fields && table.fields.length > 0);
- const [isCreateModelsModalOpen, setIsCreateModelsModalOpen] = useState(false);
const getFieldHref = (fieldId: FieldId) => {
- return getUrl(baseUrl, {
+ return Urls.dataStudioData({
databaseId: table.db_id,
schemaName: table.schema,
tableId: table.id,
+ tab: "field",
fieldId,
});
};
+ const dispatch = useDispatch();
+
+ const handleTabChange = useCallback(
+ (tab: string | null) => {
+ if (!Urls.isDataStudioTableMetadataTab(tab)) {
+ return;
+ }
+
+ dispatch(
+ push(
+ Urls.dataStudioData({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ tableId: table.id,
+ tab,
+ }),
+ ),
+ );
+ },
+ [dispatch, table.db_id, table.schema, table.id],
+ );
+
const handleNameChange = async (name: string) => {
const { error } = await updateTable({
id: table.id,
@@ -153,6 +184,18 @@ const TableSectionBase = ({
}
};
+ const handlePublishToggle = () => {
+ if (!hasLibrary) {
+ setModalType("library");
+ } else {
+ setModalType(table.is_published ? "unpublish" : "publish");
+ }
+ };
+
+ const handleCloseModal = () => {
+ setModalType(undefined);
+ };
+
return (
<Stack data-testid="table-section" gap="md" pb="xl">
<Box className={S.header} bg="accent-gray-light" px="lg" mt="lg">
@@ -170,42 +213,37 @@ const TableSectionBase = ({
<Box px="lg">
<Group justify="stretch" gap="sm">
+ <Button
+ flex="1"
+ p="sm"
+ leftSection={
+ <Icon name={table.is_published ? "unpublish" : "publish"} />
+ }
+ onClick={handlePublishToggle}
+ >
+ {table.is_published ? t`Unpublish` : t`Publish`}
+ </Button>
<Button
flex="1"
leftSection={<Icon name="settings" />}
onClick={onSyncOptionsClick}
- style={{
- width: "100%",
- }}
>
{t`Sync settings`}
</Button>
- <Button
- flex="1"
- onClick={() => setIsCreateModelsModalOpen(true)}
- p="sm"
- leftSection={<Icon name="add_folder" />}
- style={{
- width: "100%",
- }}
- >{t`Publish`}</Button>
<Tooltip label={t`Dependency graph`}>
- <Box /* wrapping with a Box because Tooltip does not work for <Button component={Link} /> */
- >
- <Button
- component={Link}
- to={dependencyGraph({
- entry: { id: Number(table.id), type: "table" },
- })}
- p="sm"
- leftSection={<Icon name="network" />}
- style={{
- flexGrow: 0,
- width: 40,
- }}
- aria-label={t`Dependency graph`}
- />
- </Box>
+ <Button
+ component={ForwardRefLink}
+ to={dependencyGraph({
+ entry: { id: Number(table.id), type: "table" },
+ })}
+ p="sm"
+ leftSection={<Icon name="network" />}
+ style={{
+ flexGrow: 0,
+ width: 40,
+ }}
+ aria-label={t`Dependency graph`}
+ />
</Tooltip>
<Box style={{ flexGrow: 0, width: 40 }}>
<TableLink table={table} />
@@ -223,98 +261,115 @@ const TableSectionBase = ({
</TableSectionGroup>
</Box>
- {table.published_models != null && table.published_models.length > 0 && (
- <TableModels table={table} />
+ {table.is_published && (
+ <Box px="lg">
+ <TableCollection table={table} />
+ </Box>
)}
<Box px="lg">
- <Stack gap={12}>
- <Group
- align="center"
- gap="md"
- justify="space-between"
- miw={0}
- wrap="nowrap"
- h={36}
- >
- <Text flex="0 0 auto" fw="bold">{t`Fields`}</Text>
-
- <Group
- flex="1"
- gap="md"
- justify="flex-end"
- miw={0}
- wrap="nowrap"
- h="100%"
- >
- {isUpdatingSorting && (
- <Loader data-testid="loading-indicator" size="xs" />
- )}
-
- {!isSorting && hasFields && (
- <ResponsiveButton
- icon="sort_arrows"
- showLabel
- onClick={() => setIsSorting(true)}
- >{t`Sorting`}</ResponsiveButton>
+ <Tabs value={activeTab} onChange={handleTabChange}>
+ <Tabs.List mb="md">
+ <Tabs.Tab
+ value="field"
+ leftSection={<Icon name="list" />}
+ >{t`Fields`}</Tabs.Tab>
+ <Tabs.Tab
+ value="segments"
+ leftSection={<Icon name="segment2" />}
+ >{t`Segments`}</Tabs.Tab>
+ </Tabs.List>
+
+ <Tabs.Panel value="field">
+ <Stack gap="md">
+ <Group gap="md" justify="flex-start" wrap="nowrap">
+ {isUpdatingSorting && (
+ <Loader data-testid="loading-indicator" size="xs" />
+ )}
+
+ {!isSorting && hasFields && (
+ <ResponsiveButton
+ icon="sort_arrows"
+ showLabel
+ onClick={() => setIsSorting(true)}
+ >{t`Sorting`}</ResponsiveButton>
+ )}
+
+ {isSorting && (
+ <FieldOrderPicker
+ value={table.field_order}
+ onChange={handleFieldOrderTypeChange}
+ />
+ )}
+
+ {isSorting && (
+ <ResponsiveButton
+ icon="check"
+ showLabel
+ onClick={() => setIsSorting(false)}
+ >{t`Done`}</ResponsiveButton>
+ )}
+ </Group>
+
+ {!hasFields && (
+ <EmptyState message={t`This table has no fields`} />
)}
- {isSorting && (
- <FieldOrderPicker
- value={table.field_order}
- onChange={handleFieldOrderTypeChange}
- />
+ {hasFields && (
+ <>
+ <Box
+ style={{
+ display: isSorting ? "block" : "none",
+ }}
+ aria-hidden={!isSorting}
+ >
+ <TableSortableFieldList
+ activeFieldId={activeFieldId}
+ table={table}
+ onChange={handleCustomFieldOrderChange}
+ />
+ </Box>
+
+ <Box
+ style={{
+ display: isSorting ? "none" : "block",
+ }}
+ aria-hidden={isSorting}
+ >
+ <TableFieldList
+ table={table}
+ activeFieldId={activeFieldId}
+ getFieldHref={getFieldHref}
+ />
+ </Box>
+ </>
)}
+ </Stack>
+ </Tabs.Panel>
- {isSorting && (
- <ResponsiveButton
- icon="check"
- showLabel
- onClick={() => setIsSorting(false)}
- >{t`Done`}</ResponsiveButton>
- )}
- </Group>
- </Group>
-
- {!hasFields && <EmptyState message={t`This table has no fields`} />}
-
- {/* NOTE: We're using here CSS display property to avoid scroll jump when toggling sorting mode. */}
- {hasFields && (
- <>
- <Box
- style={{
- display: isSorting ? "block" : "none",
- }}
- aria-hidden={!isSorting}
- >
- <TableSortableFieldList
- activeFieldId={activeFieldId}
- table={table}
- onChange={handleCustomFieldOrderChange}
- />
- </Box>
-
- <Box
- style={{
- display: isSorting ? "none" : "block",
- }}
- aria-hidden={isSorting}
- >
- <TableFieldList
- table={table}
- activeFieldId={activeFieldId}
- getFieldHref={getFieldHref}
- />
- </Box>
- </>
- )}
- </Stack>
+ <Tabs.Panel value="segments">
+ <SegmentList segments={table.segments ?? []} tableId={table.id} />
+ </Tabs.Panel>
+ </Tabs>
</Box>
-
- <PublishModelsModal
- tables={new Set([table.id])}
- isOpen={isCreateModelsModalOpen}
- onClose={() => setIsCreateModelsModalOpen(false)}
+ <CreateLibraryModal
+ title={t`First, let's create your Library`}
+ explanatorySentence={t`This is where published tables will go.`}
+ isOpened={modalType === "library"}
+ onCreate={() => setModalType("publish")}
+ onClose={handleCloseModal}
+ />
+ <PublishTablesModal
+ isOpened={modalType === "publish"}
+ tableIds={[table.id]}
+ onPublish={handleCloseModal}
+ onClose={handleCloseModal}
+ />
+ <UnpublishTablesModal
+ isOpened={modalType === "unpublish"}
+ tableIds={[table.id]}
+ onUnpublish={handleCloseModal}
+ onClose={handleCloseModal}
/>
</Stack>
);
@@ -331,18 +386,15 @@ function TableLink({ table }: { table: Table }) {
return (
<Tooltip label={t`Go to this table`} position="top">
- <Box>
- {/* wrapping with a Box because Tooltip does not work for <Button component={Link} /> */}
- <Button
- component={Link}
- to={url}
- aria-label={t`Go to this table`}
- leftSection={<Icon name="external" size={16} />}
- style={{
- width: "100%",
- }}
- />
- </Box>
+ <Button
+ component={ForwardRefLink}
+ to={url}
+ aria-label={t`Go to this table`}
+ leftSection={<Icon name="external" size={16} />}
+ style={{
+ width: "100%",
+ }}
+ />
</Tooltip>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.unit.spec.tsx
index e2ce5c8c16a..ec285e89f0d 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSection.unit.spec.tsx
@@ -5,8 +5,13 @@ import {
setupUsersEndpoints,
} from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
-import type { Table } from "metabase-types/api";
-import { createMockTable, createMockUser } from "metabase-types/api/mocks";
+import type { DataStudioTableMetadataTab } from "metabase/lib/urls/data-studio";
+import type { Segment, Table } from "metabase-types/api";
+import {
+ createMockSegment,
+ createMockTable,
+ createMockUser,
+} from "metabase-types/api/mocks";
import type { RouteParams } from "../../pages/DataModel/types";
@@ -15,15 +20,23 @@ import { TableSection } from "./TableSection";
type SetupOpts = {
table?: Table;
params?: RouteParams;
+ activeTab?: DataStudioTableMetadataTab;
+ segments?: Segment[];
};
-function setup({ table = createMockTable() }: SetupOpts = {}) {
+function setup({
+ table = createMockTable(),
+ activeTab = "field",
+ segments,
+}: SetupOpts = {}) {
const onSyncOptionsClick = jest.fn();
+ const tableWithSegments = segments ? { ...table, segments } : table;
+
setupUsersEndpoints([createMockUser()]);
setupUserKeyValueEndpoints({
namespace: "user_acknowledgement",
- key: "seen-publish-models-info",
+ key: "seen-publish-tables-info",
value: true,
});
@@ -31,7 +44,12 @@ function setup({ table = createMockTable() }: SetupOpts = {}) {
<Route
path="/"
component={() => (
- <TableSection table={table} onSyncOptionsClick={onSyncOptionsClick} />
+ <TableSection
+ table={tableWithSegments}
+ activeTab={activeTab}
+ hasLibrary
+ onSyncOptionsClick={onSyncOptionsClick}
+ />
)}
/>,
{ withRouter: true },
@@ -52,4 +70,54 @@ describe("TableSection", () => {
`/question#?db=${table.db_id}&table=${table.id}`,
);
});
+
+ describe("tabs", () => {
+ it("should render Fields and Segments tabs", () => {
+ setup({ activeTab: "field" });
+
+ expect(screen.getByRole("tab", { name: /Fields/i })).toBeInTheDocument();
+ expect(
+ screen.getByRole("tab", { name: /Segments/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("should show Fields tab as selected when activeTab is field", () => {
+ setup({ activeTab: "field" });
+
+ expect(screen.getByRole("tab", { name: /Fields/i })).toHaveAttribute(
+ "aria-selected",
+ "true",
+ );
+ expect(screen.getByRole("tab", { name: /Segments/i })).toHaveAttribute(
+ "aria-selected",
+ "false",
+ );
+ });
+
+ it("should show Segments tab as selected when activeTab is segments", () => {
+ setup({ activeTab: "segments" });
+
+ expect(screen.getByRole("tab", { name: /Segments/i })).toHaveAttribute(
+ "aria-selected",
+ "true",
+ );
+ expect(screen.getByRole("tab", { name: /Fields/i })).toHaveAttribute(
+ "aria-selected",
+ "false",
+ );
+ });
+
+ it("should show segment list content in segments tab", () => {
+ const segments = [createMockSegment({ id: 1, name: "Test Segment" })];
+ setup({ activeTab: "segments", segments });
+
+ expect(screen.getByText("Test Segment")).toBeInTheDocument();
+ });
+
+ it("should show empty state when no segments exist in segments tab", () => {
+ setup({ activeTab: "segments", segments: [] });
+
+ expect(screen.getByText("No segments yet")).toBeInTheDocument();
+ });
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/index.ts
index fdd6e055fa0..b6dcb1dd72a 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/index.ts
@@ -1,9 +1,3 @@
-export * from "metabase/metadata/pages/shared/FieldSection";
-export * from "metabase/metadata/pages/shared/FieldValuesModal";
-export * from "metabase/metadata/pages/shared/NoDatabasesEmptyState";
-export * from "metabase/metadata/pages/shared/PreviewSection";
-export * from "metabase/metadata/pages/shared/ResponsiveButton";
-export * from "metabase/metadata/pages/shared/SegmentsLink";
export * from "./SyncOptionsModal";
export * from "./TablePicker";
export * from "./TableSection";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.tsx
index 5b4ba9dee9f..d5f710333cf 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.tsx
@@ -1,5 +1,4 @@
import { useDisclosure, useWindowEvent } from "@mantine/hooks";
-import type { Location } from "history";
import { type ReactNode, useMemo, useState } from "react";
import { t } from "ttag";
import _ from "underscore";
@@ -9,19 +8,21 @@ import {
useListDatabasesQuery,
} from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import {
- getTableMetadataQuery,
- parseRouteParams,
-} from "metabase/metadata/pages/shared/utils";
-import { getRawTableFieldId } from "metabase/metadata/utils/field";
-import { Box, Flex, Stack, rem } from "metabase/ui";
-
+import * as Urls from "metabase/lib/urls";
import {
FieldSection,
FieldValuesModal,
NoDatabasesEmptyState,
PreviewSection,
type PreviewType,
+} from "metabase/metadata/components";
+import { getTableMetadataQuery } from "metabase/metadata/pages/shared/utils";
+import { getRawTableFieldId } from "metabase/metadata/utils/field";
+import { Box, Flex, Stack, rem } from "metabase/ui";
+import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";
+
+import { trackMetadataChange } from "../../analytics";
+import {
RouterTablePicker,
SyncOptionsModal,
TableSection,
@@ -32,19 +33,17 @@ import S from "./DataModel.module.css";
import { COLUMN_CONFIG } from "./constants";
import { SelectionProvider, useSelection } from "./contexts/SelectionContext";
import type { RouteParams } from "./types";
+import { parseRouteParams } from "./utils";
interface Props {
children?: ReactNode;
- location: Location;
params: RouteParams;
}
-export const DataModel = ({ children, location, params }: Props) => {
+export const DataModel = ({ children, params }: Props) => {
return (
<SelectionProvider>
- <DataModelContent location={location} params={params}>
- {children}
- </DataModelContent>
+ <DataModelContent params={params}>{children}</DataModelContent>
</SelectionProvider>
);
};
@@ -56,14 +55,19 @@ function DataModelContent({ params }: Props) {
selectedTables,
hasSelectedMoreThanOneTable,
} = useSelection();
+ const parsedParams = parseRouteParams(params);
const {
databaseId,
fieldId,
schemaName,
+ tab: activeTab,
tableId: queryTableId,
- } = parseRouteParams(params);
- const { data: databasesData, isLoading: isLoadingDatabases } =
- useListDatabasesQuery({ include_editable_data_model: true });
+ } = parsedParams;
+ const {
+ data: databasesData,
+ error: databasesError,
+ isLoading: isLoadingDatabases,
+ } = useListDatabasesQuery({ include_editable_data_model: true });
const databaseExists = databasesData?.data?.some(
(database) => database.id === databaseId,
);
@@ -82,7 +86,7 @@ function DataModelContent({ params }: Props) {
const {
data: table,
- error,
+ error: tableError,
isLoading: isLoadingTables,
} = useGetTableQueryMetadataQuery(getTableMetadataQuery(metadataTableId));
const fieldsByName = useMemo(() => {
@@ -91,8 +95,18 @@ function DataModelContent({ params }: Props) {
const field = table?.fields?.find((field) => field.id === fieldId);
const parentName = field?.nfc_path?.[0] ?? "";
const parentField = fieldsByName[parentName];
+
+ const {
+ data: libraryCollection,
+ isLoading: isLoadingLibrary,
+ error: libraryError,
+ } = useGetLibraryCollectionQuery();
+
const [previewType, setPreviewType] = useState<PreviewType>("table");
- const isLoading = isLoadingTables || isLoadingDatabases;
+ const isLoading = isLoadingDatabases || isLoadingTables || isLoadingLibrary;
+ const error = databasesError ?? tableError ?? libraryError;
+ // TODO Alex P 12/05/2025 Fix the endpoint to return sensible data
+ const hasLibrary = libraryCollection != null && "name" in libraryCollection;
useWindowEvent(
"keydown",
@@ -180,7 +194,7 @@ function DataModelContent({ params }: Props) {
maw={COLUMN_CONFIG.table.max}
miw={COLUMN_CONFIG.table.min}
>
- <TableAttributesEditBulk />
+ <TableAttributesEditBulk hasLibrary={hasLibrary} />
</Stack>
)}
@@ -203,6 +217,8 @@ function DataModelContent({ params }: Props) {
key={table.id}
table={table}
activeFieldId={fieldId}
+ activeTab={activeTab}
+ hasLibrary={hasLibrary}
onSyncOptionsClick={openSyncModal}
/>
)}
@@ -226,16 +242,18 @@ function DataModelContent({ params }: Props) {
{field && table && databaseId != null && (
<Box flex="1" h="100%" maw={COLUMN_CONFIG.field.max}>
<FieldSection
- databaseId={databaseId}
- field={field}
/**
* Make sure internal component state is reset when changing fields.
* This is to avoid state mix-up with optimistic updates.
*/
key={getRawTableFieldId(field)}
+ field={field}
parent={parentField}
table={table}
- eventSource="data_studio"
+ getFieldHref={(fieldId) =>
+ Urls.dataStudioData({ ...parsedParams, fieldId })
+ }
+ onTrackMetadataChange={trackMetadataChange}
onFieldValuesClick={openFieldValuesModal}
onPreviewClick={togglePreview}
/>
@@ -260,14 +278,11 @@ function DataModelContent({ params }: Props) {
>
<PreviewSection
className={S.preview}
- databaseId={databaseId}
field={field}
- fieldId={fieldId}
- previewType={previewType}
table={table}
- tableId={metadataTableId}
- onClose={closePreview}
+ previewType={previewType}
onPreviewTypeChange={setPreviewType}
+ onClose={closePreview}
/>
</Box>
)}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx
index c2a083fc5c8..8baea55b90f 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx
@@ -1,12 +1,13 @@
import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
-import { IndexRedirect, Link, Route } from "react-router";
+import { IndexRedirect, Link, Redirect, Route } from "react-router";
import {
setupCardDataset,
setupDatabaseIdFieldsEndpoints,
setupDatabasesEndpoints,
setupFieldsValuesEndpoints,
+ setupLibraryEndpoints,
setupTableEndpoints,
setupTableSearchEndpoint,
setupTablesBulkEndpoints,
@@ -24,7 +25,7 @@ import {
within,
} from "__support__/ui";
import { checkNotNull } from "metabase/lib/types";
-import { getUrl } from "metabase/metadata/pages/shared/utils";
+import * as Urls from "metabase/lib/urls";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import registerVisualizations from "metabase/visualizations/register";
import type {
@@ -37,6 +38,7 @@ import {
createMockField,
createMockFieldDimension,
createMockFieldValues,
+ createMockSegment,
createMockTable,
createMockUserListResult,
} from "metabase-types/api/mocks";
@@ -64,6 +66,7 @@ const DEFAULT_ROUTE_PARAMS: ParsedRouteParams = {
databaseId: undefined,
schemaName: undefined,
tableId: undefined,
+ tab: "field",
fieldId: undefined,
};
@@ -166,6 +169,37 @@ const JSON_DB = createMockDatabase({
features: ["nested-field-columns"],
});
+const TEST_SEGMENT_1 = createMockSegment({
+ id: 1,
+ name: "High Value Orders",
+ description: "Orders with total over 100",
+ table_id: ORDERS_TABLE.id,
+ definition_description: "Filtered by Total is greater than 100",
+});
+
+const TEST_SEGMENT_2 = createMockSegment({
+ id: 2,
+ name: "Recent Orders",
+ description: "Orders from the last 30 days",
+ table_id: ORDERS_TABLE.id,
+ definition_description: "Filtered by Created At is in the previous 30 days",
+});
+
+const ORDERS_TABLE_WITH_SEGMENTS = createOrdersTable({
+ fields: [
+ ORDERS_ID_FIELD,
+ ORDERS_PRODUCT_ID_FIELD,
+ ORDERS_USER_ID_FIELD,
+ ORDERS_DISCOUNT_FIELD,
+ ORDERS_QUANTITY_FIELD,
+ ],
+ segments: [TEST_SEGMENT_1, TEST_SEGMENT_2],
+});
+
+const SAMPLE_DB_WITH_SEGMENTS = createSampleDatabase({
+ tables: [ORDERS_TABLE_WITH_SEGMENTS, PRODUCTS_TABLE],
+});
+
interface SetupOpts {
databases?: Database[];
fieldValues?: GetFieldValuesResponse[];
@@ -181,13 +215,11 @@ const OtherComponent = () => {
return (
<>
<span>Another route</span>
- <Link to="admin/datamodel">Link to Data Model</Link>
+ <Link to="data-studio/data">Link to Data Model</Link>
</>
);
};
-const BASE_URL = "/admin/datamodel";
-
async function setup({
databases = [SAMPLE_DB],
fieldValues = SAMPLE_DB_FIELD_VALUES,
@@ -203,9 +235,10 @@ async function setup({
setupTablesBulkEndpoints();
setupUsersEndpoints([createMockUserListResult()]);
setupUserAcknowledgementEndpoints({
- key: "seen-publish-models-info",
+ key: "seen-publish-tables-info",
value: false,
});
+ setupLibraryEndpoints();
if (hasFieldValuesAccess) {
setupFieldsValuesEndpoints(fieldValues);
@@ -220,8 +253,8 @@ async function setup({
const { history } = renderWithProviders(
<>
- <Route path="notAdmin" component={OtherComponent} />
- <Route path="admin/datamodel">
+ <Route path="notData" component={OtherComponent} />
+ <Route path="data-studio/data">
<IndexRedirect to="database" />
<Route path="database" component={DataModel} />
<Route path="database/:databaseId" component={DataModel} />
@@ -229,19 +262,24 @@ async function setup({
path="database/:databaseId/schema/:schemaId"
component={DataModel}
/>
+ <Redirect
+ from="database/:databaseId/schema/:schemaId/table/:tableId"
+ to="database/:databaseId/schema/:schemaId/table/:tableId/field"
+ />
<Route
- path="database/:databaseId/schema/:schemaId/table/:tableId"
+ path="database/:databaseId/schema/:schemaId/table/:tableId/:tab"
component={DataModel}
/>
<Route
- path="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId"
+ path="database/:databaseId/schema/:schemaId/table/:tableId/:tab/:fieldId"
component={DataModel}
/>
</Route>
+ <Route path="data-studio/modeling/segments/new" />
</>,
{
withRouter: true,
- initialRoute: initialRoute ?? getUrl(BASE_URL, params),
+ initialRoute: initialRoute ?? Urls.dataStudioData(params),
},
);
@@ -647,7 +685,7 @@ describe("DataModel", () => {
describe("navigation", () => {
it("should replace locations in history stack when being routed automatically", async () => {
const { history } = await setup({
- initialRoute: "notAdmin",
+ initialRoute: "notData",
waitForDatabase: false,
waitForTable: false,
});
@@ -744,6 +782,7 @@ describe("DataModel", () => {
databaseId: JSON_DB.id,
schemaName: JSON_TABLE.schema,
tableId: JSON_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(JSON_FIELD_ROOT),
},
});
@@ -757,6 +796,7 @@ describe("DataModel", () => {
databaseId: SAMPLE_DB.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_DISCOUNT_FIELD),
},
});
@@ -770,6 +810,7 @@ describe("DataModel", () => {
databaseId: SAMPLE_DB.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_ID_FIELD),
},
});
@@ -789,6 +830,7 @@ describe("DataModel", () => {
databaseId: SAMPLE_DB.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_DISCOUNT_FIELD),
},
});
@@ -817,6 +859,7 @@ describe("DataModel", () => {
databaseId: database.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_PRODUCT_ID_FIELD),
},
unauthorizedField: PRODUCTS_ID_FIELD,
@@ -843,6 +886,7 @@ describe("DataModel", () => {
databaseId: SAMPLE_DB.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_QUANTITY_FIELD),
},
});
@@ -869,6 +913,7 @@ describe("DataModel", () => {
databaseId: SAMPLE_DB.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_QUANTITY_FIELD),
},
hasFieldValuesAccess: false,
@@ -892,6 +937,7 @@ describe("DataModel", () => {
databaseId: SAMPLE_DB.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_ID_FIELD),
},
});
@@ -917,6 +963,7 @@ describe("DataModel", () => {
databaseId: SAMPLE_DB.id,
schemaName: ORDERS_TABLE.schema,
tableId: ORDERS_TABLE.id,
+ tab: "field",
fieldId: getRawTableFieldId(ORDERS_ID_FIELD),
},
});
@@ -936,6 +983,70 @@ describe("DataModel", () => {
});
});
});
+
+ describe("segments tab", () => {
+ it("should show empty state when no segments exist", async () => {
+ await setup();
+
+ await userEvent.click(
+ await findTablePickerTable(ORDERS_TABLE.display_name),
+ );
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(screen.getByRole("tab", { name: /Segments/i }));
+
+ expect(screen.getByText("No segments yet")).toBeInTheDocument();
+ expect(
+ screen.getByText("Create a segment to filter rows in this table."),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: /New segment/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("should display segments when they exist", async () => {
+ await setup({ databases: [SAMPLE_DB_WITH_SEGMENTS] });
+
+ await userEvent.click(
+ await findTablePickerTable(ORDERS_TABLE_WITH_SEGMENTS.display_name),
+ );
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(screen.getByRole("tab", { name: /Segments/i }));
+
+ expect(
+ screen.getByRole("listitem", { name: TEST_SEGMENT_1.name }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("listitem", { name: TEST_SEGMENT_2.name }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(TEST_SEGMENT_1.definition_description),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(TEST_SEGMENT_2.definition_description),
+ ).toBeInTheDocument();
+ });
+
+ it("should navigate to new segment page when clicking New segment", async () => {
+ const { history } = await setup();
+
+ await userEvent.click(
+ await findTablePickerTable(ORDERS_TABLE.display_name),
+ );
+ await waitForLoaderToBeRemoved();
+
+ await userEvent.click(screen.getByRole("tab", { name: /Segments/i }));
+ await userEvent.click(screen.getByRole("link", { name: /New segment/i }));
+
+ expect(history?.getCurrentLocation().pathname).toBe(
+ "/data-studio/modeling/segments/new",
+ );
+ expect(history?.getCurrentLocation().search).toContain(
+ `tableId=${ORDERS_TABLE.id}`,
+ );
+ });
+ });
});
function getTableSearchInput() {
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/types.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/types.ts
index 194bf9fcb3e..be7b27ccab5 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/types.ts
@@ -1,3 +1,4 @@
+import type { DataStudioTableMetadataTab } from "metabase/lib/urls/data-studio";
import type {
DatabaseId,
FieldId,
@@ -10,6 +11,7 @@ export type RouteParams = {
databaseId?: string;
schemaId?: SchemaId;
tableId?: string;
+ tab?: string;
fieldId?: string;
};
@@ -17,6 +19,7 @@ export type ParsedRouteParams = {
databaseId: DatabaseId | undefined;
schemaName: SchemaName | undefined;
tableId: TableId | undefined;
+ tab: DataStudioTableMetadataTab;
fieldId?: FieldId;
};
@@ -27,12 +30,3 @@ export interface ColumnSizeConfig {
min: number;
max: number | string;
}
-
-export type MetadataEditAnalyticsDetail =
- | "type_casting"
- | "semantic_type_change"
- | "visibility_change"
- | "filtering_change"
- | "display_values"
- | "json_unfolding"
- | "formatting";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/utils.ts
new file mode 100644
index 00000000000..d233900ce79
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/utils.ts
@@ -0,0 +1,17 @@
+import * as Urls from "metabase/lib/urls";
+import { isDataStudioTableMetadataTab } from "metabase/lib/urls/data-studio";
+import { getSchemaName } from "metabase-lib/v1/metadata/utils/schema";
+
+import type { ParsedRouteParams, RouteParams } from "./types";
+
+export function parseRouteParams(params: RouteParams): ParsedRouteParams {
+ return {
+ databaseId: Urls.extractEntityId(params.databaseId),
+ schemaName: params.schemaId
+ ? getSchemaName(params.schemaId)
+ : params.schemaId,
+ tableId: Urls.extractEntityId(params.tableId),
+ tab: isDataStudioTableMetadataTab(params.tab) ? params.tab : "field",
+ fieldId: Urls.extractEntityId(params.fieldId),
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/utils.unit.spec.ts
index f44e3136dbb..e4ec212ea75 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/utils.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/pages/DataModel/utils.unit.spec.ts
@@ -1,6 +1,6 @@
-import { getUrl, parseRouteParams } from "metabase/metadata/pages/shared/utils";
+import { parseRouteParams } from "metabase/metadata/pages/shared/utils";
-import type { ParsedRouteParams, RouteParams } from "./types";
+import type { RouteParams } from "./types";
describe("parseRouteParams", () => {
it("should parse all route parameters correctly", () => {
@@ -49,92 +49,3 @@ describe("parseRouteParams", () => {
});
});
});
-
-const BASE_URL = "/admin/datamodel";
-
-describe("getUrl", () => {
- it("should generate URL with all params", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: 2,
- fieldId: 3,
- };
-
- expect(getUrl(BASE_URL, params)).toBe(
- `${BASE_URL}/database/1/schema/1:public/table/2/field/3`,
- );
- });
-
- it("should generate URL with database, schema, and table", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: 2,
- fieldId: undefined,
- };
-
- expect(getUrl(BASE_URL, params)).toBe(
- `${BASE_URL}/database/1/schema/1:public/table/2`,
- );
- });
-
- it("should generate URL with database and schema", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: undefined,
- fieldId: undefined,
- };
-
- expect(getUrl(BASE_URL, params)).toBe(
- `${BASE_URL}/database/1/schema/1:public`,
- );
- });
-
- it("should generate URL with database", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: undefined,
- tableId: undefined,
- fieldId: undefined,
- };
-
- expect(getUrl(BASE_URL, params)).toBe(`${BASE_URL}/database/1`);
- });
-
- it("should generate base URL when no params are provided", () => {
- const params: ParsedRouteParams = {
- databaseId: undefined,
- schemaName: undefined,
- tableId: undefined,
- fieldId: undefined,
- };
-
- expect(getUrl(BASE_URL, params)).toBe(BASE_URL);
- });
-
- it("should not include field param when there is no table param", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: undefined,
- fieldId: 3,
- };
-
- expect(getUrl(BASE_URL, params)).toBe(
- `${BASE_URL}/database/1/schema/1:public`,
- );
- });
-
- it("should not include schema, table, and field params when there is no database param", () => {
- const params: ParsedRouteParams = {
- databaseId: undefined,
- schemaName: "public",
- tableId: 2,
- fieldId: 3,
- };
-
- expect(getUrl(BASE_URL, params)).toBe(BASE_URL);
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/routes.tsx
index 92d2bfdc23d..8654f8ed701 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/routes.tsx
@@ -21,31 +21,35 @@ export function getDataStudioMetadataRoutes() {
component={DataModel}
/>
<Route
- path="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId"
+ path="database/:databaseId/schema/:schemaId/table/:tableId/:tab"
+ component={DataModel}
+ />
+ <Route
+ path="database/:databaseId/schema/:schemaId/table/:tableId/:tab/:fieldId"
component={DataModel}
/>
<Redirect
from="database/:databaseId/schema/:schemaId/table/:tableId/settings"
- to="database/:databaseId/schema/:schemaId/table/:tableId"
+ to="database/:databaseId/schema/:schemaId/table/:tableId/field"
/>
<Redirect
from="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId/:section"
to="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId"
/>
- <Route component={DataModel}>
- <Route path="segments" component={SegmentListApp} />
- <Route path="segment/create" component={SegmentApp} />
- <Route path="segment/:id" component={SegmentApp} />
- <Route path="segment/:id/revisions" component={RevisionHistoryApp} />
- </Route>
<Redirect
from="database/:databaseId/schema/:schemaId/table/:tableId/settings"
- to="database/:databaseId/schema/:schemaId/table/:tableId"
+ to="database/:databaseId/schema/:schemaId/table/:tableId/field"
/>
<Redirect
from="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId/:section"
to="database/:databaseId/schema/:schemaId/table/:tableId/field/:fieldId"
/>
+ <Route component={DataModel}>
+ <Route path="segments" component={SegmentListApp} />
+ <Route path="segment/create" component={SegmentApp} />
+ <Route path="segment/:id" component={SegmentApp} />
+ <Route path="segment/:id/revisions" component={RevisionHistoryApp} />
+ </Route>
</>
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/utils.unit.spec.ts
deleted file mode 100644
index 0995e95112b..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/utils.unit.spec.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { createMockCard, createMockCollection } from "metabase-types/api/mocks";
-
-import { getPublishSeeItLink } from "./components/TablePicker/utils";
-
-const createMockPublishModelsResponse = ({
- target_collection = createMockCollection({ type: "library-models" }),
- models = [createMockCard({ type: "model" })],
- created_count = 1,
-} = {}) => {
- return { target_collection, models, created_count };
-};
-
-describe("getPublishSeeItLink", () => {
- describe("published inside data studio", () => {
- it("1 model created", () => {
- const response = createMockPublishModelsResponse();
- const link = getPublishSeeItLink(response);
-
- expect(link).toContain(
- `data-studio/modeling/models/${response.models[0].id}`,
- );
- });
-
- it("> 1 model created", () => {
- const response = createMockPublishModelsResponse({ created_count: 2 });
- const link = getPublishSeeItLink(response);
-
- expect(link).toContain(
- `data-studio/modeling/collections/${response.target_collection.id}`,
- );
- });
- });
-
- describe("published outside data studio", () => {
- it("1 model created", () => {
- const response = createMockPublishModelsResponse({
- target_collection: createMockCollection(),
- });
- const link = getPublishSeeItLink(response);
-
- expect(link).toContain(`model/${response.models[0].id}`);
- });
-
- it("> 1 model created", () => {
- const response = createMockPublishModelsResponse({
- target_collection: createMockCollection(),
- created_count: 2,
- });
- const link = getPublishSeeItLink(response);
-
- expect(link).toContain(`collection/${response.target_collection.id}`);
- });
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/metrics/components/MetricHeader/MetricHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/metrics/components/MetricHeader/MetricHeader.tsx
index f499ea8fff2..bc8b293236c 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/metrics/components/MetricHeader/MetricHeader.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/metrics/components/MetricHeader/MetricHeader.tsx
@@ -7,8 +7,8 @@ import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { useMetadataToasts } from "metabase/metadata/hooks";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
-import { CardMoreMenu } from "metabase/questions/components/CardMoreMenu";
import { getMetadata } from "metabase/selectors/metadata";
+import { CardMoreMenu } from "metabase-enterprise/data-studio/common/components/CardMoreMenu";
import * as Lib from "metabase-lib";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import type { Card } from "metabase-types/api";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionEmptyState/CollectionEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionEmptyState/CollectionEmptyState.tsx
index 1b5c0962230..71c7dea831c 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionEmptyState/CollectionEmptyState.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionEmptyState/CollectionEmptyState.tsx
@@ -30,8 +30,8 @@ function getMessages(collection: Collection) {
switch (PLUGIN_DATA_STUDIO.getLibraryCollectionType(collection.type)) {
case "models":
return {
- title: t`No models yet`,
- message: t`Put models in the Library to see them here.`,
+ title: t`No tables or models yet`,
+ message: t`Publish tables in the Library to see them here.`,
};
case "metrics":
return {
@@ -40,8 +40,8 @@ function getMessages(collection: Collection) {
};
default:
return {
- title: t`No models or metrics yet`,
- message: t`Models and metrics in this collection will appear here.`,
+ title: t`No tables or metrics yet`,
+ message: t`Tables and metrics in this collection will appear here.`,
};
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/CollectionItemsTable.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/CollectionItemsTable.tsx
index 458656061ce..492659482ed 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/CollectionItemsTable.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/CollectionItemsTable.tsx
@@ -11,9 +11,9 @@ import {
TableColumn,
} from "metabase/common/components/ItemsTable/BaseItemsTable.styled";
import { Columns } from "metabase/common/components/ItemsTable/Columns";
+import type { CollectionItem } from "metabase-types/api";
import { ItemRow } from "./ItemRow";
-import type { ModelingItem } from "./types";
import { DEFAULT_SORTING_OPTIONS, sortItems } from "./utils";
const CONTAINER_NAME = "ItemsTableContainer";
@@ -32,7 +32,7 @@ const menuProps = {
};
interface CollectionItemsTableProps {
- items: ModelingItem[];
+ items: CollectionItem[];
skeleton?: boolean;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/DescriptionCell/DescriptionCell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/DescriptionCell/DescriptionCell.tsx
index bf00f0bf38c..2a908c8a67c 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/DescriptionCell/DescriptionCell.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/DescriptionCell/DescriptionCell.tsx
@@ -1,12 +1,12 @@
import { Cell } from "metabase/browse/components/BrowseTable.styled";
import { MarkdownPreview } from "metabase/common/components/MarkdownPreview";
import { Skeleton } from "metabase/ui";
+import type { CollectionItem } from "metabase-types/api";
-import type { ModelingItem } from "../types";
import { getItemDescription } from "../utils";
interface DescriptionCellProps {
- item?: ModelingItem;
+ item?: CollectionItem;
}
const CONTAINER_NAME = "ItemsTableContainer";
@@ -24,7 +24,7 @@ export function DescriptionCell({ item }: DescriptionCellProps) {
allowedElements={["strong", "em"]}
oneLine
>
- {getItemDescription(item) || ""}
+ {getItemDescription(item)}
</MarkdownPreview>
) : (
<Skeleton natural h="16.8px" />
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/ItemRow/ItemRow.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/ItemRow/ItemRow.tsx
index af38e21aa4d..ff97a251d89 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/ItemRow/ItemRow.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/ItemRow/ItemRow.tsx
@@ -6,14 +6,15 @@ import { TableRow } from "metabase/browse/components/BrowseTable.styled";
import { Columns } from "metabase/common/components/ItemsTable/Columns";
import { useDispatch } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
+import type { CollectionItem } from "metabase-types/api";
+import { getItemUrl } from "../../../../utils";
import { DescriptionCell } from "../DescriptionCell";
import { MenuCell } from "../MenuCell";
import { NameCell } from "../NameCell";
-import type { ModelingItem } from "../types";
interface ItemRowProps {
- item?: ModelingItem;
+ item?: CollectionItem;
}
export function ItemRow({ item }: ItemRowProps) {
@@ -31,11 +32,7 @@ export function ItemRow({ item }: ItemRowProps) {
return;
}
- const { id, model } = item;
- const url =
- model === "metric"
- ? Urls.dataStudioMetric(id)
- : Urls.dataStudioModel(id);
+ const url = getItemUrl(item);
const subpathSafeUrl = Urls.getSubpathSafeUrl(url);
event.preventDefault();
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/MenuCell/MenuCell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/MenuCell/MenuCell.tsx
index 2d3c964ff6d..d849250b9f6 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/MenuCell/MenuCell.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/MenuCell/MenuCell.tsx
@@ -6,13 +6,12 @@ import { Cell } from "metabase/browse/components/BrowseTable.styled";
import Questions from "metabase/entities/questions";
import { useDispatch } from "metabase/lib/redux";
import { Button, FixedSizeIcon, Menu } from "metabase/ui";
-
-import type { ModelingItem } from "../types";
+import type { CollectionItem } from "metabase-types/api";
import S from "./MenuCell.module.css";
interface MenuCellProps {
- item?: ModelingItem;
+ item?: CollectionItem;
}
function stopPropagation(event: MouseEvent) {
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/NameCell/NameCell.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/NameCell/NameCell.tsx
index b537e20a7d0..abe7297bd32 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/NameCell/NameCell.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/NameCell/NameCell.tsx
@@ -6,15 +6,15 @@ import {
MaybeItemLink,
} from "metabase/common/components/ItemsTable/BaseItemsTable.styled";
import { getIcon } from "metabase/lib/icon";
-import * as Urls from "metabase/lib/urls";
import { FixedSizeIcon, type IconName, Skeleton } from "metabase/ui";
+import type { CollectionItem } from "metabase-types/api";
-import type { ModelingItem } from "../types";
+import { getItemUrl } from "../../../../utils";
import S from "./NameCell.module.css";
interface NameCellProps {
- item?: ModelingItem;
+ item?: CollectionItem;
}
const CONTAINER_NAME = "ItemsTableContainer";
@@ -29,14 +29,8 @@ function preventDefault(event: MouseEvent) {
export function NameCell({ item }: NameCellProps) {
const headingId = item ? `${item.model}-${item.id}-heading` : "dummy-heading";
-
const icon = item ? getIcon(item) : { name: "folder" as IconName };
-
- const itemUrl = item
- ? item.model === "metric"
- ? Urls.metric({ id: item.id, name: item.name, type: "metric" })
- : Urls.dataStudioModel(item.id)
- : undefined;
+ const itemUrl = item ? getItemUrl(item) : undefined;
return (
<ItemNameCell
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/index.ts
index e82c57d53ba..063cfe01b95 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/index.ts
@@ -1,2 +1 @@
export * from "./CollectionItemsTable";
-export type { ModelingItem } from "./types";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/types.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/types.ts
index aa2bbf7455c..9acea0ad8fa 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/types.ts
@@ -1,9 +1,4 @@
import type { IconName } from "metabase/ui";
-import type { CollectionItem } from "metabase-types/api";
-
-export type ModelingItem = CollectionItem & {
- model: "metric" | "model";
-};
export type SortColumn = "name" | "description";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/utils.ts
index 6eac94ebf1a..ade6b707f13 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionItemsTable/utils.ts
@@ -1,25 +1,21 @@
-import { t } from "ttag";
-
+import type { CollectionItem } from "metabase-types/api";
import { SortDirection, type SortingOptions } from "metabase-types/api/sorting";
-import type { ModelingItem, SortColumn } from "./types";
+import type { SortColumn } from "./types";
export const DEFAULT_SORTING_OPTIONS: SortingOptions<SortColumn> = {
sort_column: "name",
sort_direction: SortDirection.Asc,
};
-export function getItemDescription(item: ModelingItem): string {
- if (!item.description?.trim()) {
- return item.model === "metric" ? t`A metric` : t`A model`;
- }
- return item.description;
+export function getItemDescription(item: CollectionItem): string {
+ return item.description ?? "";
}
export function sortItems(
- items: ModelingItem[],
+ items: CollectionItem[],
sortingOptions: SortingOptions<SortColumn>,
-): ModelingItem[] {
+): CollectionItem[] {
const { sort_column, sort_direction } = sortingOptions;
return [...items].sort((a, b) => {
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.tsx
index 759e31e3908..089bbf14ed8 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.tsx
@@ -1,5 +1,3 @@
-import { useMemo } from "react";
-
import {
useGetCollectionQuery,
useListCollectionItemsQuery,
@@ -13,10 +11,7 @@ import {
} from "../../../common/components/PaneHeader";
import { CollectionEmptyState } from "./CollectionEmptyState";
-import {
- CollectionItemsTable,
- type ModelingItem,
-} from "./CollectionItemsTable";
+import { CollectionItemsTable } from "./CollectionItemsTable";
import S from "./CollectionPage.module.css";
type CollectionPageParams = {
@@ -41,21 +36,12 @@ export function CollectionPage({ params }: CollectionPageProps) {
error: itemsError,
} = useListCollectionItemsQuery({
id: params.collectionId,
- models: ["dataset", "metric"],
+ models: ["dataset", "metric", "table"],
});
+ const items = data?.data ?? [];
const isLoading = isLoadingCollection || isLoadingItems;
const error = collectionError ?? itemsError;
- const items = useMemo(() => {
- if (!data?.data) {
- return [];
- }
- return data.data.filter(
- (item): item is ModelingItem =>
- item.model === "dataset" || item.model === "metric",
- );
- }, [data]);
-
if (isLoading || error != null || collection == null) {
return (
<Center h="100%">
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.unit.spec.tsx
index 4d568f575d0..245f6699585 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/CollectionPage/CollectionPage.unit.spec.tsx
@@ -102,7 +102,7 @@ describe("CollectionPage", () => {
await waitForLoaderToBeRemoved();
expect(
- await screen.findByText("No models or metrics yet"),
+ await screen.findByText("No tables or metrics yet"),
).toBeInTheDocument();
});
@@ -179,7 +179,7 @@ describe("CollectionPage", () => {
expect(screen.getByText(errorMessage)).toBeInTheDocument();
});
- it("should request only models and metrics from API", async () => {
+ it("should request only tables, models, and metrics from API", async () => {
await setup({
collectionItems: [TEST_MODEL_ITEM, TEST_METRIC_ITEM],
});
@@ -194,7 +194,7 @@ describe("CollectionPage", () => {
const url = new URL(itemsCall.url);
const models = url.searchParams.getAll("models");
- expect(models).toEqual(["dataset", "metric"]);
+ expect(models).toEqual(["dataset", "metric", "table"]);
});
it("should show collection name in page header", async () => {
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/ModelingEmptyPage/ModelingEmptyPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/ModelingEmptyPage/ModelingEmptyPage.tsx
index 352cff02f71..597a2f63c1c 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/ModelingEmptyPage/ModelingEmptyPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/pages/ModelingEmptyPage/ModelingEmptyPage.tsx
@@ -6,7 +6,7 @@ import { Center } from "metabase/ui";
export function ModelingEmptyPage() {
return (
- <Center h="100%" bg="bg-light">
+ <Center h="100%" bg="bg-light" data-testid="modeling-empty-page">
<EmptyState
illustrationElement={<img src={EmptyDashboardBot} />}
title={t`Pick a collection or create a new model or metric`}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/utils.ts
new file mode 100644
index 00000000000..1364fcc7344
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/modeling/utils.ts
@@ -0,0 +1,15 @@
+import * as Urls from "metabase/lib/urls";
+import type { CollectionItem } from "metabase-types/api";
+
+export function getItemUrl(item: CollectionItem) {
+ switch (item.model) {
+ case "table":
+ return Urls.dataStudioTable(item.id);
+ case "dataset":
+ return Urls.dataStudioModel(item.id);
+ case "metric":
+ return Urls.dataStudioMetric(item.id);
+ default:
+ throw new TypeError(`Unsupported item: ${item.model}`);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/models/components/ModelHeader/ModelHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/models/components/ModelHeader/ModelHeader.tsx
index bdac4e9cf63..36f2c1ed497 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/models/components/ModelHeader/ModelHeader.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/models/components/ModelHeader/ModelHeader.tsx
@@ -7,8 +7,8 @@ import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { useMetadataToasts } from "metabase/metadata/hooks";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
-import { CardMoreMenu } from "metabase/questions/components/CardMoreMenu";
import { getMetadata } from "metabase/selectors/metadata";
+import { CardMoreMenu } from "metabase-enterprise/data-studio/common/components/CardMoreMenu";
import * as Lib from "metabase-lib";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import type { Card } from "metabase-types/api";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldList/ModelFieldList.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldList/ModelFieldList.tsx
index 248f6ceca6b..d600f7cc2f5 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldList/ModelFieldList.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldList/ModelFieldList.tsx
@@ -1,8 +1,5 @@
-import { t } from "ttag";
-
-import { SortableFieldList } from "metabase/metadata/components";
import { FieldList } from "metabase/metadata/components/FieldList";
-import { Box, Button, Flex, Group, Icon } from "metabase/ui";
+import { Box, Flex } from "metabase/ui";
import type { Field } from "metabase-types/api";
import type { FieldOverrides } from "../../../types";
@@ -12,23 +9,17 @@ import S from "./ModelFieldList.module.css";
type ModelFieldListProps = {
fields: Field[];
activeFieldName?: string;
- isSorting: boolean;
isReadOnly: boolean;
onSelectField: (field: Field) => void;
onChangeField: (field: Field, overrides: FieldOverrides) => void;
- onChangeSorting: (fields: Field[]) => void;
- onToggleSorting: (isSorting: boolean) => void;
};
export function ModelFieldList({
fields,
activeFieldName,
- isSorting,
isReadOnly,
onSelectField,
onChangeField,
- onChangeSorting,
- onToggleSorting,
}: ModelFieldListProps) {
const handleNameChange = (field: Field, name: string) => {
onChangeField(field, { display_name: name });
@@ -41,55 +32,22 @@ export function ModelFieldList({
onChangeField(field, { description });
};
- const handleSortingClick = () => {
- onToggleSorting(!isSorting);
- };
-
- const handleSortingChange = (fieldNames: string[]) => {
- const fieldByName = Object.fromEntries(
- fields.map((field) => [field.name, field]),
- );
- const fieldsInOrder = fieldNames.map((fieldName) => fieldByName[fieldName]);
- onChangeSorting(fieldsInOrder);
- };
-
return (
<Flex
className={S.section}
flex={activeFieldName ? "0 0 33%" : 1}
direction="column"
>
- {!isReadOnly && (
- <Group className={S.header} p="md" pb="sm">
- <Button
- px="sm"
- py="0.85rem"
- size="compact-md"
- leftSection={<Icon name={isSorting ? "check" : "sort_arrows"} />}
- onClick={handleSortingClick}
- >
- {isSorting ? t`Done` : t`Sorting`}
- </Button>
- </Group>
- )}
<Box px="md" pb="md" pt={isReadOnly ? "md" : undefined}>
- {isSorting ? (
- <SortableFieldList
- fields={fields}
- getFieldKey={getFieldKey}
- onChange={handleSortingChange}
- />
- ) : (
- <FieldList
- fields={fields}
- activeFieldKey={activeFieldName}
- readOnly={isReadOnly}
- getFieldKey={getFieldKey}
- onSelect={onSelectField}
- onNameChange={handleNameChange}
- onDescriptionChange={handleDescriptionChange}
- />
- )}
+ <FieldList
+ fields={fields}
+ activeFieldKey={activeFieldName}
+ readOnly={isReadOnly}
+ getFieldKey={getFieldKey}
+ onSelect={onSelectField}
+ onNameChange={handleNameChange}
+ onDescriptionChange={handleDescriptionChange}
+ />
</Box>
</Flex>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldsPage.tsx
index 1d0c7e68a75..2c72a084676 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldsPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/models/pages/ModelFieldsPage/ModelFieldsPage.tsx
@@ -81,7 +81,6 @@ function ModelFieldsPageBody({
}: ModelFieldsPageBodyProps) {
const [fields, setFields] = useState(card.result_metadata ?? []);
const [activeFieldName, setActiveFieldName] = useState<string>();
- const [isSorting, setIsSorting] = useState(false);
const [updateCard, { isLoading: isSaving }] = useUpdateCardMutation();
const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
const isReadOnly = !card.can_write;
@@ -107,7 +106,6 @@ function ModelFieldsPageBody({
};
const handleSave = async () => {
- setIsSorting(false);
const { error } = await updateCard({
id: card.id,
result_metadata: fields,
@@ -122,7 +120,6 @@ function ModelFieldsPageBody({
const handleCancel = () => {
setFields(card.result_metadata ?? []);
setActiveFieldName(undefined);
- setIsSorting(false);
};
const resetRef = useLatest(handleCancel);
@@ -150,12 +147,9 @@ function ModelFieldsPageBody({
<ModelFieldList
fields={fields}
activeFieldName={activeFieldName}
- isSorting={isSorting}
isReadOnly={isReadOnly}
onSelectField={handleSelectField}
onChangeField={handleChangeField}
- onChangeSorting={setFields}
- onToggleSorting={setIsSorting}
/>
{activeField != null ? (
<ModelFieldDetails
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/routes.tsx
index a8392ec795b..fe1dba13c9a 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/routes.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/routes.tsx
@@ -20,7 +20,9 @@ import { getDataStudioGlossaryRoutes } from "./glossary/routes";
import { getDataStudioMetricRoutes } from "./metrics/routes";
import { getDataStudioModelingRoutes } from "./modeling/routes";
import { getDataStudioModelRoutes } from "./models/routes";
+import { getDataStudioSegmentRoutes } from "./segments/routes";
import { getDataStudioSnippetRoutes } from "./snippets/routes";
+import { getDataStudioTableRoutes } from "./tables/routes";
export function getDataStudioRoutes(
store: Store<State>,
@@ -50,8 +52,10 @@ export function getDataStudioRoutes(
)}
<Route path="modeling" component={ModelingSectionLayout}>
{getDataStudioModelingRoutes()}
+ {getDataStudioTableRoutes()}
{getDataStudioModelRoutes()}
{getDataStudioMetricRoutes()}
+ {getDataStudioSegmentRoutes()}
{getDataStudioSnippetRoutes()}
{getDataStudioGlossaryRoutes()}
</Route>
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentEditorPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentEditorPage.tsx
new file mode 100644
index 00000000000..b7ecfe9e366
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentEditorPage.tsx
@@ -0,0 +1,220 @@
+import { useEffect, useMemo, useState } from "react";
+import type { Route } from "react-router";
+import { Link } from "react-router";
+import { t } from "ttag";
+
+import EditableText from "metabase/common/components/EditableText";
+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";
+import { useSelector } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
+import { SegmentEditorV2 } from "metabase/querying/segments";
+import { getMetadata } from "metabase/selectors/metadata";
+import {
+ Anchor,
+ Button,
+ FixedSizeIcon,
+ Group,
+ Stack,
+ Textarea,
+} from "metabase/ui";
+import * as Lib from "metabase-lib";
+import type { DatasetQuery, Segment, Table } from "metabase-types/api";
+
+import { SegmentMoreMenu } from "./SegmentMoreMenu";
+import { SegmentPreview } from "./SegmentPreview";
+
+const SEGMENT_NAME_MAX_LENGTH = 254;
+
+type SegmentFormData = {
+ name: string;
+ description: string;
+ definition: DatasetQuery;
+};
+
+type SegmentEditorPageProps = {
+ segment?: Segment;
+ table: Table;
+ route: Route;
+ isSaving: boolean;
+ isRemoving?: boolean;
+ onSave: (data: SegmentFormData) => void;
+ onCancel?: () => void;
+ onRemove?: () => void;
+ testId?: string;
+};
+
+export function SegmentEditorPage({
+ segment,
+ table,
+ route,
+ isSaving,
+ isRemoving,
+ onSave,
+ onCancel,
+ onRemove,
+ testId,
+}: SegmentEditorPageProps) {
+ const metadata = useSelector(getMetadata);
+
+ const [name, setName] = useState("");
+ const [description, setDescription] = useState("");
+ const [datasetQuery, setDatasetQuery] = useState<DatasetQuery | null>(null);
+
+ const query = useMemo(() => {
+ if (!datasetQuery?.database) {
+ return undefined;
+ }
+ const metadataProvider = Lib.metadataProvider(
+ datasetQuery.database,
+ metadata,
+ );
+ return Lib.fromJsQuery(metadataProvider, datasetQuery);
+ }, [metadata, datasetQuery]);
+
+ const filters = useMemo(() => (query ? Lib.filters(query, -1) : []), [query]);
+
+ useEffect(() => {
+ if (segment) {
+ setName(segment.name);
+ setDescription(segment.description ?? "");
+ setDatasetQuery(segment.definition);
+ } else {
+ const metadataProvider = Lib.metadataProvider(table.db_id, metadata);
+ const tableMetadata = Lib.tableOrCardMetadata(metadataProvider, table.id);
+ if (tableMetadata) {
+ const initialQuery = Lib.queryFromTableOrCardMetadata(
+ metadataProvider,
+ tableMetadata,
+ );
+ setDatasetQuery(Lib.toJsQuery(initialQuery));
+ }
+ }
+ }, [segment, table, metadata]);
+
+ const isDirty = useMemo(() => {
+ if (segment) {
+ if (!datasetQuery) {
+ return false;
+ }
+ const nameChanged = name !== segment.name;
+ const descriptionChanged = description !== (segment.description ?? "");
+ const queryChanged = !Lib.areLegacyQueriesEqual(
+ datasetQuery,
+ segment.definition,
+ );
+ return nameChanged || descriptionChanged || queryChanged;
+ }
+ return (
+ name.trim().length > 0 || description.length > 0 || filters.length > 0
+ );
+ }, [segment, name, description, datasetQuery, filters]);
+
+ const isNew = !segment;
+ const hasName = name.trim().length > 0;
+ const hasFilters = filters.length > 0;
+ const isValid = hasName && hasFilters;
+ const showButtons = isNew || isDirty;
+ const canSave = showButtons && isValid && !isSaving;
+
+ const handleChangeQuery = (newQuery: Lib.Query) => {
+ setDatasetQuery(Lib.toJsQuery(newQuery));
+ };
+
+ const handleSave = () => {
+ if (!datasetQuery || !isValid) {
+ return;
+ }
+ onSave({
+ name: name.trim(),
+ description: description.trim(),
+ definition: datasetQuery,
+ });
+ };
+
+ const handleCancel = () => {
+ if (segment) {
+ setName(segment.name);
+ setDescription(segment.description ?? "");
+ setDatasetQuery(segment.definition);
+ }
+ onCancel?.();
+ };
+
+ const backUrl = Urls.dataStudioData({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ tableId: table.id,
+ tab: "segments",
+ });
+
+ return (
+ <>
+ <Stack
+ pos="relative"
+ w="100%"
+ h="100%"
+ bg="bg-white"
+ px="xl"
+ py="lg"
+ gap="lg"
+ data-testid={testId}
+ >
+ <Stack gap="sm" align="flex-start">
+ <Anchor component={Link} to={backUrl} c="text-medium" fz="sm">
+ <Group gap="xs">
+ <FixedSizeIcon name="chevronleft" size={12} />
+ {t`${table.display_name} segments`}
+ </Group>
+ </Anchor>
+ <Group gap="xs" align="center">
+ <EditableText
+ initialValue={name}
+ placeholder={t`New segment`}
+ maxLength={SEGMENT_NAME_MAX_LENGTH}
+ p={0}
+ fw="bold"
+ fz="h3"
+ lh="h3"
+ onContentChange={setName}
+ />
+ {segment && onRemove && <SegmentMoreMenu onRemove={onRemove} />}
+ </Group>
+ </Stack>
+ <Stack flex={1} gap="lg">
+ {query && (
+ <SegmentEditorV2 query={query} onChange={handleChangeQuery} />
+ )}
+ <Group gap="lg" align="flex-start">
+ <Textarea
+ label={t`Description`}
+ placeholder={t`Give it a description`}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ maw={400}
+ flex={1}
+ />
+ {query && hasFilters && <SegmentPreview query={query} />}
+ </Group>
+ {showButtons && (
+ <Group>
+ <Button onClick={handleCancel}>{t`Cancel`}</Button>
+ <Button
+ variant="filled"
+ disabled={!canSave}
+ loading={isSaving}
+ onClick={handleSave}
+ >
+ {t`Save`}
+ </Button>
+ </Group>
+ )}
+ </Stack>
+ </Stack>
+ <LeaveRouteConfirmModal
+ key={segment?.id}
+ route={route}
+ isEnabled={isDirty && !isSaving && !isRemoving}
+ />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentEditorPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentEditorPage.unit.spec.tsx
new file mode 100644
index 00000000000..5ab5f687219
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentEditorPage.unit.spec.tsx
@@ -0,0 +1,98 @@
+import { Route } from "react-router";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import type { Segment, Table } from "metabase-types/api";
+import { createMockSegment, createMockTable } from "metabase-types/api/mocks";
+
+import { SegmentEditorPage } from "./SegmentEditorPage";
+
+const mockRoute = {
+ path: "/",
+};
+
+type SetupOpts = {
+ segment?: Segment;
+ table?: Table;
+ isSaving?: boolean;
+ isRemoving?: boolean;
+ onRemove?: () => void;
+};
+
+function setup({
+ segment,
+ table = createMockTable({
+ id: 42,
+ db_id: 1,
+ display_name: "Orders",
+ schema: "PUBLIC",
+ }),
+ isSaving = false,
+ isRemoving = false,
+ onRemove,
+}: SetupOpts = {}) {
+ const onSave = jest.fn();
+ const onCancel = jest.fn();
+ const onRemoveFn = onRemove ?? jest.fn();
+
+ renderWithProviders(
+ <Route
+ path="/"
+ component={() => (
+ <SegmentEditorPage
+ segment={segment}
+ table={table}
+ route={mockRoute as any}
+ isSaving={isSaving}
+ isRemoving={isRemoving}
+ onSave={onSave}
+ onCancel={onCancel}
+ onRemove={segment ? onRemoveFn : undefined}
+ testId="segment-editor"
+ />
+ )}
+ />,
+ { withRouter: true },
+ );
+
+ return { onSave, onCancel, onRemove: onRemoveFn };
+}
+
+describe("SegmentEditorPage", () => {
+ it("renders new segment form with name placeholder, description, back link, and no menu", () => {
+ setup({ segment: undefined });
+
+ expect(screen.getByPlaceholderText("New segment")).toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText("Give it a description"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Orders segments")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /segment actions/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders existing segment with name, description, and more menu", () => {
+ const segment = createMockSegment({
+ id: 1,
+ name: "High Value",
+ description: "Premium customers",
+ });
+ setup({ segment, onRemove: jest.fn() });
+
+ expect(screen.getByDisplayValue("High Value")).toBeInTheDocument();
+ expect(screen.getByDisplayValue("Premium customers")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /segment actions/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("links back to segments tab with correct URL", () => {
+ setup({ segment: undefined });
+
+ const backLink = screen.getByText("Orders segments").closest("a");
+ expect(backLink).toHaveAttribute(
+ "href",
+ "/data-studio/data/database/1/schema/1:PUBLIC/table/42/segments",
+ );
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentMoreMenu/SegmentMoreMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentMoreMenu/SegmentMoreMenu.tsx
new file mode 100644
index 00000000000..10ffa12a2a2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentMoreMenu/SegmentMoreMenu.tsx
@@ -0,0 +1,48 @@
+import { useDisclosure } from "@mantine/hooks";
+import { t } from "ttag";
+
+import { ConfirmModal } from "metabase/common/components/ConfirmModal";
+import { ActionIcon, Icon, Menu } from "metabase/ui";
+
+type SegmentMoreMenuProps = {
+ onRemove: () => void;
+};
+
+export function SegmentMoreMenu({ onRemove }: SegmentMoreMenuProps) {
+ const [isConfirmOpen, { open: openConfirm, close: closeConfirm }] =
+ useDisclosure();
+
+ const handleConfirm = () => {
+ closeConfirm();
+ onRemove();
+ };
+
+ return (
+ <>
+ <Menu>
+ <Menu.Target>
+ <ActionIcon aria-label={t`Segment actions`}>
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ c="danger"
+ leftSection={<Icon name="trash" />}
+ onClick={openConfirm}
+ >
+ {t`Remove segment`}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ <ConfirmModal
+ title={t`Remove this segment?`}
+ message={t`This segment will be permanently removed.`}
+ opened={isConfirmOpen}
+ onClose={closeConfirm}
+ onConfirm={handleConfirm}
+ confirmButtonText={t`Remove`}
+ />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentMoreMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentMoreMenu/index.ts
new file mode 100644
index 00000000000..cbf657c4758
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentMoreMenu/index.ts
@@ -0,0 +1 @@
+export { SegmentMoreMenu } from "./SegmentMoreMenu";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentPreview/SegmentPreview.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentPreview/SegmentPreview.tsx
new file mode 100644
index 00000000000..9212d6b95b8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentPreview/SegmentPreview.tsx
@@ -0,0 +1,43 @@
+import { useMemo } from "react";
+import { Link } from "react-router";
+import { P, match } from "ts-pattern";
+import { t } from "ttag";
+
+import { useGetAdhocQueryQuery } from "metabase/api";
+import * as Urls from "metabase/lib/urls";
+import { Button, Group, Icon, Loader, Text } from "metabase/ui";
+import * as Lib from "metabase-lib";
+
+type SegmentPreviewProps = {
+ query: Lib.Query;
+};
+
+export function SegmentPreview({ query }: SegmentPreviewProps) {
+ const countQuery = useMemo(() => Lib.aggregateByCount(query, -1), [query]);
+
+ const { data, isFetching } = useGetAdhocQueryQuery(Lib.toJsQuery(countQuery));
+ const count = data?.data?.rows?.[0]?.[0];
+
+ const previewUrl = Urls.newQuestion({
+ dataset_query: Lib.toJsQuery(query),
+ });
+
+ return (
+ <Group gap="md" ml="auto">
+ {match({ isFetching, count })
+ .with({ isFetching: true }, () => <Loader size="xs" />)
+ .with({ isFetching: false, count: P.nonNullable }, ({ count }) => (
+ <Text>{t`${count} rows`}</Text>
+ ))
+ .otherwise(() => null)}
+ <Button
+ component={Link}
+ to={previewUrl}
+ target="_blank"
+ leftSection={<Icon name="share" size={16} />}
+ variant="filled"
+ size="compact-sm"
+ >{t`Preview`}</Button>
+ </Group>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentPreview/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentPreview/index.ts
new file mode 100644
index 00000000000..f5e3eba92f8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/SegmentPreview/index.ts
@@ -0,0 +1 @@
+export { SegmentPreview } from "./SegmentPreview";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/index.ts
new file mode 100644
index 00000000000..83faa216f8c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/components/SegmentEditorPage/index.ts
@@ -0,0 +1 @@
+export { SegmentEditorPage } from "./SegmentEditorPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/EditSegmentPage/EditSegmentPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/EditSegmentPage/EditSegmentPage.tsx
new file mode 100644
index 00000000000..dbe9a13af98
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/EditSegmentPage/EditSegmentPage.tsx
@@ -0,0 +1,129 @@
+import { skipToken } from "@reduxjs/toolkit/query";
+import { useCallback } from "react";
+import type { Route } from "react-router";
+import { push } from "react-router-redux";
+import { t } from "ttag";
+
+import {
+ useDeleteSegmentMutation,
+ useGetSegmentQuery,
+ useUpdateSegmentMutation,
+} from "metabase/api";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useDispatch } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { Center } from "metabase/ui";
+import { useLoadTableWithMetadata } from "metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata";
+import type { DatasetQuery } from "metabase-types/api";
+
+import { SegmentEditorPage } from "../../components/SegmentEditorPage";
+
+type EditSegmentPageProps = {
+ params: { segmentId: string };
+ route: Route;
+};
+
+export function EditSegmentPage({ params, route }: EditSegmentPageProps) {
+ const dispatch = useDispatch();
+ const segmentId = Urls.extractEntityId(params.segmentId);
+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
+
+ const {
+ data: segment,
+ isLoading: isLoadingSegment,
+ error: segmentError,
+ } = useGetSegmentQuery(segmentId ?? skipToken);
+
+ const {
+ table,
+ isLoading: isLoadingTable,
+ error: tableError,
+ } = useLoadTableWithMetadata(segment?.table_id);
+
+ const [updateSegment, { isLoading: isSaving }] = useUpdateSegmentMutation();
+ const [deleteSegment, { isLoading: isRemoving }] = useDeleteSegmentMutation();
+
+ const handleSave = useCallback(
+ async (data: {
+ name: string;
+ description: string;
+ definition: DatasetQuery;
+ }) => {
+ if (!segment) {
+ return;
+ }
+ const { error } = await updateSegment({
+ id: segment.id,
+ name: data.name,
+ description: data.description || undefined,
+ definition: data.definition,
+ revision_message: t`Updated from Data Studio`,
+ });
+
+ if (error) {
+ sendErrorToast(t`Failed to update segment`);
+ } else {
+ sendSuccessToast(t`Segment updated`);
+ }
+ },
+ [segment, updateSegment, sendSuccessToast, sendErrorToast],
+ );
+
+ const handleRemove = useCallback(async () => {
+ if (!segment || !table) {
+ return;
+ }
+ const { error } = await deleteSegment({
+ id: segment.id,
+ revision_message: t`Removed from Data Studio`,
+ });
+
+ if (error) {
+ sendErrorToast(t`Failed to remove segment`);
+ } else {
+ sendSuccessToast(t`Segment removed`);
+ dispatch(
+ push(
+ Urls.dataStudioData({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ tableId: table.id,
+ tab: "segments",
+ }),
+ ),
+ );
+ }
+ }, [
+ segment,
+ table,
+ deleteSegment,
+ dispatch,
+ sendSuccessToast,
+ sendErrorToast,
+ ]);
+
+ const isLoading = isLoadingSegment || isLoadingTable;
+ const error = segmentError || tableError;
+
+ if (isLoading || error || !segment || !table) {
+ return (
+ <Center h="100%">
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ </Center>
+ );
+ }
+
+ return (
+ <SegmentEditorPage
+ segment={segment}
+ table={table}
+ route={route}
+ isSaving={isSaving}
+ isRemoving={isRemoving}
+ onSave={handleSave}
+ onRemove={handleRemove}
+ testId="edit-segment-page"
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/EditSegmentPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/EditSegmentPage/index.ts
new file mode 100644
index 00000000000..a1225453f8c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/EditSegmentPage/index.ts
@@ -0,0 +1 @@
+export { EditSegmentPage } from "./EditSegmentPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/NewSegmentPage/NewSegmentPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/NewSegmentPage/NewSegmentPage.tsx
new file mode 100644
index 00000000000..dd242dd7de6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/NewSegmentPage/NewSegmentPage.tsx
@@ -0,0 +1,93 @@
+import type { Location } from "history";
+import { useCallback } from "react";
+import type { Route } from "react-router";
+import { push } from "react-router-redux";
+import { t } from "ttag";
+
+import { useCreateSegmentMutation } from "metabase/api";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useDispatch } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { Center } from "metabase/ui";
+import { useLoadTableWithMetadata } from "metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata";
+import type { DatasetQuery } from "metabase-types/api";
+
+import { SegmentEditorPage } from "../../components/SegmentEditorPage";
+
+type NewSegmentPageProps = {
+ route: Route;
+ location: Location;
+};
+
+export function NewSegmentPage({ route, location }: NewSegmentPageProps) {
+ const dispatch = useDispatch();
+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
+
+ const tableIdParam = new URLSearchParams(location.search).get("tableId");
+ const tableId = tableIdParam ? Number(tableIdParam) : undefined;
+
+ const { table, isLoading, error } = useLoadTableWithMetadata(tableId);
+
+ const [createSegment, { isLoading: isSaving }] = useCreateSegmentMutation();
+
+ const handleSave = useCallback(
+ async (data: {
+ name: string;
+ description: string;
+ definition: DatasetQuery;
+ }) => {
+ if (!table) {
+ return;
+ }
+ const { data: segment, error } = await createSegment({
+ name: data.name,
+ table_id: table.id,
+ definition: data.definition,
+ description: data.description || undefined,
+ });
+
+ if (error) {
+ sendErrorToast(t`Failed to create segment`);
+ } else if (segment) {
+ sendSuccessToast(t`Segment created`);
+ dispatch(push(Urls.dataStudioSegment(segment.id)));
+ }
+ },
+ [table, createSegment, dispatch, sendSuccessToast, sendErrorToast],
+ );
+
+ const handleCancel = useCallback(() => {
+ if (table) {
+ dispatch(
+ push(
+ Urls.dataStudioData({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ tableId: table.id,
+ tab: "segments",
+ }),
+ ),
+ );
+ }
+ }, [table, dispatch]);
+
+ if (isLoading || error || !table) {
+ return (
+ <Center h="100%">
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ </Center>
+ );
+ }
+
+ return (
+ <SegmentEditorPage
+ table={table}
+ route={route}
+ isSaving={isSaving}
+ onSave={handleSave}
+ onCancel={handleCancel}
+ testId="new-segment-page"
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/NewSegmentPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/NewSegmentPage/index.ts
new file mode 100644
index 00000000000..968adcfc26a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/pages/NewSegmentPage/index.ts
@@ -0,0 +1 @@
+export { NewSegmentPage } from "./NewSegmentPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/segments/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/routes.tsx
new file mode 100644
index 00000000000..f29551181ba
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/segments/routes.tsx
@@ -0,0 +1,13 @@
+import { Route } from "react-router";
+
+import { EditSegmentPage } from "./pages/EditSegmentPage";
+import { NewSegmentPage } from "./pages/NewSegmentPage";
+
+export function getDataStudioSegmentRoutes() {
+ return (
+ <>
+ <Route path="segments/new" component={NewSegmentPage} />
+ <Route path="segments/:segmentId" component={EditSegmentPage} />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/analytics.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/analytics.ts
new file mode 100644
index 00000000000..efbc96eb608
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/analytics.ts
@@ -0,0 +1,10 @@
+import { trackSimpleEvent } from "metabase/lib/analytics";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
+
+export function trackMetadataChange(detail: MetadataEditEventDetail) {
+ trackSimpleEvent({
+ event: "metadata_edited",
+ event_detail: detail,
+ triggered_from: "data_studio",
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableHeader.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableHeader.tsx
new file mode 100644
index 00000000000..c5a068ecf90
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableHeader.tsx
@@ -0,0 +1,23 @@
+import type { Table } from "metabase-types/api";
+
+import { PaneHeader } from "../../../common/components/PaneHeader";
+
+import { TableMoreMenu } from "./TableMoreMenu";
+import { TableNameInput } from "./TableNameInput";
+import { TableTabs } from "./TableTabs";
+
+type TableHeaderProps = {
+ table: Table;
+};
+
+export function TableHeader({ table }: TableHeaderProps) {
+ return (
+ <PaneHeader
+ data-testid="table-pane-header"
+ title={<TableNameInput table={table} />}
+ icon="table"
+ menu={<TableMoreMenu table={table} />}
+ tabs={<TableTabs table={table} />}
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx
new file mode 100644
index 00000000000..c9820395748
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableMoreMenu/TableMoreMenu.tsx
@@ -0,0 +1,60 @@
+import { useState } from "react";
+import { push } from "react-router-redux";
+import { c, t } from "ttag";
+
+import { ForwardRefLink } from "metabase/common/components/Link";
+import { useDispatch } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
+import { ActionIcon, Icon, Menu } from "metabase/ui";
+import { UnpublishTablesModal } from "metabase-enterprise/data-studio/common/components/UnpublishTablesModal";
+import type { Table } from "metabase-types/api";
+
+type TableModalType = "unpublish";
+
+type TableMoreMenuProps = {
+ table: Table;
+};
+
+export function TableMoreMenu({ table }: TableMoreMenuProps) {
+ const dispatch = useDispatch();
+ const [modalType, setModalType] = useState<TableModalType>();
+
+ const handleUnpublish = () => {
+ setModalType(undefined);
+ dispatch(push(Urls.dataStudioModeling()));
+ };
+
+ return (
+ <>
+ <Menu>
+ <Menu.Target>
+ <ActionIcon>
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ leftSection={<Icon name="external" />}
+ component={ForwardRefLink}
+ to={Urls.queryBuilderTable(table.id, table.db_id)}
+ target="_blank"
+ >
+ {c("A verb, not a noun").t`View`}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="unpublish" />}
+ onClick={() => setModalType("unpublish")}
+ >
+ {t`Unpublish`}
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ <UnpublishTablesModal
+ isOpened={modalType === "unpublish"}
+ tableIds={[table.id]}
+ onUnpublish={handleUnpublish}
+ onClose={() => setModalType(undefined)}
+ />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableMoreMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableMoreMenu/index.ts
new file mode 100644
index 00000000000..2593038f2a3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableMoreMenu/index.ts
@@ -0,0 +1 @@
+export * from "./TableMoreMenu";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableNameInput/TableNameInput.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableNameInput/TableNameInput.tsx
new file mode 100644
index 00000000000..6ef04fcef42
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableNameInput/TableNameInput.tsx
@@ -0,0 +1,40 @@
+import { t } from "ttag";
+
+import { useUpdateTableMutation } from "metabase/api";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { PaneHeaderInput } from "metabase-enterprise/data-studio/common/components/PaneHeader";
+import type { Table } from "metabase-types/api";
+
+import { NAME_MAX_LENGTH } from "../../../constants";
+
+type TableNameInputProps = {
+ table: Table;
+ onChangeName?: (name: string) => void;
+};
+
+export function TableNameInput({ table }: TableNameInputProps) {
+ const [updateTable] = useUpdateTableMutation();
+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
+
+ const handleChangeName = async (newName: string) => {
+ const { error } = await updateTable({
+ id: table.id,
+ display_name: newName,
+ });
+
+ if (error) {
+ sendErrorToast(t`Failed to update table name`);
+ } else {
+ sendSuccessToast(t`Table name updated`);
+ }
+ };
+
+ return (
+ <PaneHeaderInput
+ initialValue={table.display_name}
+ maxLength={NAME_MAX_LENGTH}
+ data-testid="table-name-input"
+ onChange={handleChangeName}
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableNameInput/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableNameInput/index.ts
new file mode 100644
index 00000000000..5b4179e6bde
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableNameInput/index.ts
@@ -0,0 +1 @@
+export * from "./TableNameInput";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableTabs/TableTabs.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableTabs/TableTabs.tsx
new file mode 100644
index 00000000000..c549fb7ba2c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableTabs/TableTabs.tsx
@@ -0,0 +1,48 @@
+import type { Location } from "history";
+import { t } from "ttag";
+
+import { useSelector } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
+import { getLocation } from "metabase/selectors/routing";
+import {
+ type PaneHeaderTab,
+ PaneHeaderTabs,
+} from "metabase-enterprise/data-studio/common/components/PaneHeader";
+import type { Table } from "metabase-types/api";
+
+type TableTabsProps = {
+ table: Table;
+};
+
+export function TableTabs({ table }: TableTabsProps) {
+ const location = useSelector(getLocation);
+ const tabs = getTabs(table, location);
+ return <PaneHeaderTabs tabs={tabs} />;
+}
+
+function getTabs(table: Table, location: Location): PaneHeaderTab[] {
+ const tabs: PaneHeaderTab[] = [];
+
+ tabs.push({
+ label: t`Overview`,
+ to: Urls.dataStudioTable(table.id),
+ });
+
+ tabs.push({
+ label: t`Fields`,
+ to: Urls.dataStudioTableFields(table.id),
+ isSelected: location.pathname.startsWith(
+ Urls.dataStudioTableFields(table.id),
+ ),
+ });
+
+ if (PLUGIN_DEPENDENCIES.isEnabled) {
+ tabs.push({
+ label: t`Dependencies`,
+ to: Urls.dataStudioTableDependencies(table.id),
+ });
+ }
+
+ return tabs;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableTabs/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableTabs/index.ts
new file mode 100644
index 00000000000..5145c4a0f5c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/TableTabs/index.ts
@@ -0,0 +1 @@
+export * from "./TableTabs";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/index.ts
new file mode 100644
index 00000000000..f192eceeea9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/components/TableHeader/index.ts
@@ -0,0 +1 @@
+export * from "./TableHeader";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/constants.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/constants.ts
new file mode 100644
index 00000000000..1c40320a871
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/constants.ts
@@ -0,0 +1 @@
+export const NAME_MAX_LENGTH = 255;
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableDependenciesPage/TableDependenciesPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableDependenciesPage/TableDependenciesPage.tsx
new file mode 100644
index 00000000000..3619b6aaed0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableDependenciesPage/TableDependenciesPage.tsx
@@ -0,0 +1,48 @@
+import type { ReactNode } from "react";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import * as Urls from "metabase/lib/urls";
+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
+import { Center, Flex } from "metabase/ui";
+import { useLoadTableWithMetadata } from "metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata";
+
+import { TableHeader } from "../../components/TableHeader";
+
+type TableDependenciesPageParams = {
+ tableId: string;
+};
+
+type TableDependenciesPageProps = {
+ params: TableDependenciesPageParams;
+ children?: ReactNode;
+};
+
+export function TableDependenciesPage({
+ params,
+ children,
+}: TableDependenciesPageProps) {
+ const tableId = Urls.extractEntityId(params.tableId);
+ const { table, isLoading, error } = useLoadTableWithMetadata(tableId);
+
+ if (isLoading || error != null || table == null) {
+ return (
+ <Center h="100%">
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ </Center>
+ );
+ }
+
+ return (
+ <Flex direction="column" h="100%" data-testid="table-dependencies-page">
+ <TableHeader table={table} />
+ <PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider
+ value={{
+ baseUrl: Urls.dataStudioTableDependencies(table.id),
+ defaultEntry: { id: table.id, type: "table" },
+ }}
+ >
+ {children}
+ </PLUGIN_DEPENDENCIES.DependencyGraphPageContext.Provider>
+ </Flex>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableDependenciesPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableDependenciesPage/index.ts
new file mode 100644
index 00000000000..5f40499032d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableDependenciesPage/index.ts
@@ -0,0 +1 @@
+export * from "./TableDependenciesPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/TableFieldsPage.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/TableFieldsPage.module.css
new file mode 100644
index 00000000000..cf41c9d7ba4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/TableFieldsPage.module.css
@@ -0,0 +1,12 @@
+.body {
+ overflow-x: auto;
+}
+
+.column {
+ overflow-y: auto;
+ border-right: 1px solid var(--mb-color-border);
+}
+
+.preview {
+ box-shadow: 0 10px 30px 0 hsla(0, 0%, 0%, 0.1);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/TableFieldsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/TableFieldsPage.tsx
new file mode 100644
index 00000000000..6382c96d901
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/TableFieldsPage.tsx
@@ -0,0 +1,126 @@
+import { useDisclosure } from "@mantine/hooks";
+import { useState } from "react";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import * as Urls from "metabase/lib/urls";
+import {
+ FieldEmptyState,
+ FieldSection,
+ FieldValuesModal,
+ PreviewSection,
+ type PreviewType,
+ SyncOptionsModal,
+ TableSection,
+} from "metabase/metadata/components";
+import { Box, Center, Flex, Stack } from "metabase/ui";
+import { useLoadTableWithMetadata } from "metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata";
+
+import { trackMetadataChange } from "../../analytics";
+import { TableHeader } from "../../components/TableHeader";
+
+import S from "./TableFieldsPage.module.css";
+
+type TableFieldsPageParams = {
+ tableId: string;
+ fieldId?: string;
+};
+
+type TableFieldsPageProps = {
+ params: TableFieldsPageParams;
+};
+
+export function TableFieldsPage({ params }: TableFieldsPageProps) {
+ const tableId = Urls.extractEntityId(params.tableId);
+ const fieldId = Urls.extractEntityId(params.fieldId);
+ const { table, isLoading, error } = useLoadTableWithMetadata(tableId);
+ const field = table?.fields?.find((field) => field.id === fieldId);
+ const [previewType, setPreviewType] = useState<PreviewType>("table");
+ const [isPreviewOpen, { close: closePreview, toggle: togglePreview }] =
+ useDisclosure();
+ const [isSyncModalOpen, { close: closeSyncModal, open: openSyncModal }] =
+ useDisclosure();
+ const [
+ isFieldValuesModalOpen,
+ { close: closeFieldValuesModal, open: openFieldValuesModal },
+ ] = useDisclosure();
+
+ if (isLoading || error != null || table == null || tableId == null) {
+ return (
+ <Center h="100%">
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ </Center>
+ );
+ }
+
+ return (
+ <Flex direction="column" h="100%" data-testid="table-fields-page">
+ <TableHeader table={table} />
+ <Flex className={S.body} flex={1} bg="accent-gray-light">
+ <Stack className={S.column} flex="8 1 0" miw={320} maw={640} mih={0}>
+ <TableSection
+ /**
+ * Make sure internal component state is reset when changing tables.
+ * This is to avoid state mix-up with optimistic updates.
+ */
+ key={tableId}
+ table={table}
+ fieldId={fieldId}
+ getFieldHref={(fieldId) =>
+ Urls.dataStudioTableFields(tableId, fieldId)
+ }
+ onSyncOptionsClick={openSyncModal}
+ />
+ </Stack>
+ {field != null && (
+ <Stack className={S.column} flex="9 1 0" miw={320} maw={680} mih={0}>
+ <FieldSection
+ /**
+ * Make sure internal component state is reset when changing tables.
+ * This is to avoid state mix-up with optimistic updates.
+ */
+ key={fieldId}
+ field={field}
+ table={table}
+ getFieldHref={(fieldId) =>
+ Urls.dataStudioTableFields(tableId, fieldId)
+ }
+ onPreviewClick={togglePreview}
+ onFieldValuesClick={openFieldValuesModal}
+ onTrackMetadataChange={trackMetadataChange}
+ />
+ </Stack>
+ )}
+ {isPreviewOpen && field != null && (
+ <Box flex="10 1 0" miw={504} maw={734} p="lg">
+ <PreviewSection
+ className={S.preview}
+ field={field}
+ table={table}
+ previewType={previewType}
+ onPreviewTypeChange={setPreviewType}
+ onClose={closePreview}
+ />
+ </Box>
+ )}
+ {field == null && (
+ <Flex align="center" flex="1" justify="center" miw={240}>
+ <FieldEmptyState hasTable />
+ </Flex>
+ )}
+ </Flex>
+ <SyncOptionsModal
+ isOpen={isSyncModalOpen}
+ tableId={table.id}
+ onClose={closeSyncModal}
+ />
+
+ {fieldId != null && (
+ <FieldValuesModal
+ fieldId={fieldId}
+ isOpen={isFieldValuesModalOpen}
+ onClose={closeFieldValuesModal}
+ />
+ )}
+ </Flex>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/index.ts
new file mode 100644
index 00000000000..0ab4de334e3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableFieldsPage/index.ts
@@ -0,0 +1 @@
+export * from "./TableFieldsPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/DescriptionSection/DescriptionSection.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/DescriptionSection/DescriptionSection.tsx
new file mode 100644
index 00000000000..14f7489b0e9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/DescriptionSection/DescriptionSection.tsx
@@ -0,0 +1,40 @@
+import { t } from "ttag";
+
+import { useUpdateTableMutation } from "metabase/api";
+import EditableText from "metabase/common/components/EditableText";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { Box } from "metabase/ui";
+import type { Table } from "metabase-types/api";
+
+type DescriptionSectionProps = {
+ table: Table;
+};
+
+export function DescriptionSection({ table }: DescriptionSectionProps) {
+ const [updateTable] = useUpdateTableMutation();
+ const { sendSuccessToast, sendErrorToast } = useMetadataToasts();
+
+ const handleChange = async (newValue: string) => {
+ const newDescription = newValue.trim();
+ const { error } = await updateTable({
+ id: table.id,
+ description: newDescription.length > 0 ? newDescription : null,
+ });
+ if (error) {
+ sendErrorToast(t`Failed to update table description`);
+ } else {
+ sendSuccessToast(t`Table description updated`);
+ }
+ };
+
+ return (
+ <Box mx="-5px" data-testid="table-description-section">
+ <EditableText
+ initialValue={table.description ?? ""}
+ placeholder={t`No description`}
+ isMarkdown
+ onChange={handleChange}
+ />
+ </Box>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/DescriptionSection/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/DescriptionSection/index.ts
new file mode 100644
index 00000000000..64c023fdf2f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/DescriptionSection/index.ts
@@ -0,0 +1 @@
+export * from "./DescriptionSection";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/TableOverview.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/TableOverview.module.css
new file mode 100644
index 00000000000..0c93fdb0ca8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/TableOverview.module.css
@@ -0,0 +1,7 @@
+.root {
+ overflow: auto;
+}
+
+.sidebar {
+ flex-shrink: 0;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/TableOverview.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/TableOverview.tsx
new file mode 100644
index 00000000000..2dbdb6607ad
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/TableOverview.tsx
@@ -0,0 +1,51 @@
+import { useMemo } from "react";
+
+import { useSelector } from "metabase/lib/redux";
+import { getMetadata } from "metabase/selectors/metadata";
+import { Flex, Stack } from "metabase/ui";
+import { OverviewVisualization } from "metabase-enterprise/data-studio/common/components/OverviewVisualization";
+import * as Lib from "metabase-lib";
+import Question from "metabase-lib/v1/Question";
+import type Metadata from "metabase-lib/v1/metadata/Metadata";
+import type { Table } from "metabase-types/api";
+
+import { DescriptionSection } from "./DescriptionSection";
+import S from "./TableOverview.module.css";
+
+type TableOverviewProps = {
+ table: Table;
+};
+
+export function TableOverview({ table }: TableOverviewProps) {
+ const metadata = useSelector(getMetadata);
+ const card = useMemo(() => getCard(table, metadata), [table, metadata]);
+
+ return (
+ <Flex className={S.root} p="lg" flex={1} bg="bg-light">
+ <Flex direction="column" flex={1} mah={700}>
+ {card && <OverviewVisualization card={card} />}
+ </Flex>
+ <Stack maw={300} ml="lg" gap="lg" className={S.sidebar}>
+ <DescriptionSection table={table} />
+ </Stack>
+ </Flex>
+ );
+}
+
+function getCard(table: Table, metadata: Metadata) {
+ const metadataProvider = Lib.metadataProvider(table.db_id, metadata);
+ const tableMetadata = Lib.tableOrCardMetadata(metadataProvider, table.id);
+ if (tableMetadata == null) {
+ return;
+ }
+
+ const query = Lib.queryFromTableOrCardMetadata(
+ metadataProvider,
+ tableMetadata,
+ );
+ const question = Question.create({
+ dataset_query: Lib.toJsQuery(query),
+ metadata,
+ });
+ return question.card();
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/index.ts
new file mode 100644
index 00000000000..62268f6af65
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverview/index.ts
@@ -0,0 +1 @@
+export * from "./TableOverview";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverviewPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverviewPage.tsx
new file mode 100644
index 00000000000..d58e3ce19d4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/TableOverviewPage.tsx
@@ -0,0 +1,36 @@
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import * as Urls from "metabase/lib/urls";
+import { Center, Flex } from "metabase/ui";
+import { useLoadTableWithMetadata } from "metabase-enterprise/data-studio/common/hooks/use-load-table-with-metadata";
+
+import { TableHeader } from "../../components/TableHeader";
+
+import { TableOverview } from "./TableOverview";
+
+type TableOverviewPageParams = {
+ tableId: string;
+};
+
+type TableOverviewPageProps = {
+ params: TableOverviewPageParams;
+};
+
+export function TableOverviewPage({ params }: TableOverviewPageProps) {
+ const tableId = Urls.extractEntityId(params.tableId);
+ const { table, isLoading, error } = useLoadTableWithMetadata(tableId);
+
+ if (isLoading || error != null || table == null) {
+ return (
+ <Center h="100%">
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ </Center>
+ );
+ }
+
+ return (
+ <Flex direction="column" h="100%" data-testid="table-overview-page">
+ <TableHeader table={table} />
+ <TableOverview table={table} />
+ </Flex>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/index.ts
new file mode 100644
index 00000000000..fa6efc05654
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/pages/TableOverviewPage/index.ts
@@ -0,0 +1 @@
+export * from "./TableOverviewPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/tables/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/routes.tsx
new file mode 100644
index 00000000000..6376598a866
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/tables/routes.tsx
@@ -0,0 +1,21 @@
+import { IndexRoute, Route } from "react-router";
+
+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
+
+import { TableDependenciesPage } from "./pages/TableDependenciesPage";
+import { TableFieldsPage } from "./pages/TableFieldsPage";
+import { TableOverviewPage } from "./pages/TableOverviewPage";
+export function getDataStudioTableRoutes() {
+ return (
+ <Route path="tables">
+ <Route path=":tableId" component={TableOverviewPage} />
+ <Route path=":tableId/fields" component={TableFieldsPage} />
+ <Route path=":tableId/fields/:fieldId" component={TableFieldsPage} />
+ {PLUGIN_DEPENDENCIES.isEnabled && (
+ <Route path=":tableId/dependencies" component={TableDependenciesPage}>
+ <IndexRoute component={PLUGIN_DEPENDENCIES.DependencyGraphPage} />
+ </Route>
+ )}
+ </Route>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts
index cebc10cd4be..2dafe40245e 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts
@@ -92,17 +92,24 @@ export function getNodeTableInfo(
},
metadata: {
label: t`View metadata`,
- url: Urls.dataModelTable(table.db_id, table.schema, table.id),
+ url: Urls.dataModel({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ tableId: table.id,
+ }),
},
location: table.db
? [
{
label: table.db.name,
- url: Urls.dataModelDatabase(table.db.id),
+ url: Urls.dataModel({ databaseId: table.db.id }),
},
{
label: table.schema,
- url: Urls.dataModelSchema(table.db.id, table.schema),
+ url: Urls.dataModel({
+ databaseId: table.db.id,
+ schemaName: table.schema,
+ }),
},
]
: null,
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts
index e80052b6cbe..84a30a38187 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts
@@ -176,7 +176,11 @@ export function getNodeLink(node: DependencyNode): NodeLink | null {
case "table":
return {
label: t`View metadata`,
- url: Urls.dataModelTable(node.data.db_id, node.data.schema, node.id),
+ url: Urls.dataModel({
+ databaseId: node.data.db_id,
+ schemaName: node.data.schema,
+ tableId: node.id,
+ }),
};
case "transform":
return {
@@ -208,7 +212,7 @@ export function getNodeLink(node: DependencyNode): NodeLink | null {
case "segment":
return {
label: t`View this segment`,
- url: Urls.dataStudioSegment(node.id),
+ url: Urls.dataModelSegment(node.id),
};
case "snippet":
return null;
@@ -240,11 +244,14 @@ export function getNodeLocationInfo(node: DependencyNode): NodeLink[] | null {
return [
{
label: node.data.db.name,
- url: Urls.dataModelDatabase(node.data.db_id),
+ url: Urls.dataModel({ databaseId: node.data.db_id }),
},
{
label: node.data.schema,
- url: Urls.dataModelSchema(node.data.db_id, node.data.schema),
+ url: Urls.dataModel({
+ databaseId: node.data.db_id,
+ schemaName: node.data.schema,
+ }),
},
];
}
@@ -265,11 +272,11 @@ export function getNodeLocationInfo(node: DependencyNode): NodeLink[] | null {
return [
{
label: node.data.table.display_name,
- url: Urls.dataModelTable(
- node.data.table.db_id,
- node.data.table.schema,
- node.data.table.id,
- ),
+ url: Urls.dataModel({
+ databaseId: node.data.table.db_id,
+ schemaName: node.data.table.schema,
+ tableId: node.data.table.id,
+ }),
},
];
}
diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/types/user.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/types/user.ts
deleted file mode 100644
index 53740b5ca56..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/types/user.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { User } from "metabase-types/api";
-
-export interface UserWithFeaturePermissions extends User {
- permissions?: {
- can_access_data_model: boolean;
- can_access_db_details: boolean;
- };
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.ts b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.ts
index 96b1c22c154..f45fe7ce858 100644
--- a/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/feature_level_permissions/utils.ts
@@ -2,14 +2,13 @@ import { t } from "ttag";
import type { PermissionSubject } from "metabase/admin/permissions/types";
import { getUser } from "metabase/selectors/user";
+import type { User } from "metabase-types/api";
import type { AdminPathKey, State } from "metabase-types/store";
-import type { UserWithFeaturePermissions } from "./types/user";
-
-const canUserAccessDataModel = (user?: UserWithFeaturePermissions) =>
+const canUserAccessDataModel = (user?: User) =>
user?.permissions?.can_access_data_model ?? false;
-const canUserAccessDatabaseManagement = (user?: UserWithFeaturePermissions) =>
+const canUserAccessDatabaseManagement = (user?: User) =>
user?.permissions?.can_access_db_details ?? false;
export const canAccessDataModel = (state: State): boolean => {
@@ -18,13 +17,13 @@ export const canAccessDataModel = (state: State): boolean => {
};
export const dataModelPermissionAllowedPathGetter = (
- user?: UserWithFeaturePermissions,
+ user?: User,
): AdminPathKey[] => {
return canUserAccessDataModel(user) ? ["data-model"] : [];
};
export const databaseManagementPermissionAllowedPathGetter = (
- user?: UserWithFeaturePermissions,
+ user?: User,
): AdminPathKey[] => {
return canUserAccessDatabaseManagement(user) ? ["databases"] : [];
};
diff --git a/enterprise/frontend/src/metabase-enterprise/group_managers/types/user.ts b/enterprise/frontend/src/metabase-enterprise/group_managers/types/user.ts
deleted file mode 100644
index fd5eda12d02..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/group_managers/types/user.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type { User } from "metabase-types/api";
-
-export interface UserWithGroupManagerPermission extends User {
- permissions?: {
- is_group_manager: boolean;
- };
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/group_managers/utils.ts b/enterprise/frontend/src/metabase-enterprise/group_managers/utils.ts
index b2456786389..dcd08a49ea8 100644
--- a/enterprise/frontend/src/metabase-enterprise/group_managers/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/group_managers/utils.ts
@@ -1,12 +1,9 @@
import { t } from "ttag";
import type { ConfirmationState } from "metabase/common/hooks/use-confirmation";
-import type { Member, Membership } from "metabase-types/api";
-import type { User } from "metabase-types/api/user";
+import type { Member, Membership, User } from "metabase-types/api";
import type { AdminPath, AdminPathKey } from "metabase-types/store";
-import type { UserWithGroupManagerPermission } from "./types/user";
-
const REVOKE_MANAGING_CONFIRMATION = {
// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045
title: t`Are you sure?`,
@@ -14,12 +11,10 @@ const REVOKE_MANAGING_CONFIRMATION = {
message: t`You will not be able to manage users of this group anymore.`,
};
-const canAccessPeople = (user?: UserWithGroupManagerPermission) =>
+const canAccessPeople = (user?: User) =>
user?.permissions?.is_group_manager ?? false;
-export const groupManagerAllowedPathGetter = (
- user?: UserWithGroupManagerPermission,
-): AdminPathKey[] => {
+export const groupManagerAllowedPathGetter = (user?: User): AdminPathKey[] => {
return canAccessPeople(user) ? ["people"] : [];
};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx
index e6744de46fd..ffc4bdbac36 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/context.tsx
@@ -3,15 +3,17 @@ import type React from "react";
import { createContext, useCallback, useRef, useState } from "react";
import _ from "underscore";
-import { useLazyListDatabasesQuery } from "metabase/api";
import { useStore } from "metabase/lib/redux";
import type {
ChatContextProviderFn,
MetabotChatInputRef,
MetabotContext as MetabotCtx,
} from "metabase/metabot";
-import { getHasDataAccess, getHasNativeWrite } from "metabase/selectors/data";
-import { getUserIsAdmin } from "metabase/selectors/user";
+import {
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+ getUserIsAdmin,
+} from "metabase/selectors/user";
export const defaultContext = {
prompt: "",
@@ -43,17 +45,13 @@ export const MetabotProvider = ({
const providerFnsRef = useRef<Set<ChatContextProviderFn>>(new Set());
const store = useStore();
- const [listDbs] = useLazyListDatabasesQuery();
-
const getChatContext = useCallback(async () => {
const state = store.getState();
const providerFns = [...providerFnsRef.current];
- const { data: dbData } = await listDbs(undefined, true);
- const databases = dbData?.data ?? [];
- const hasDataAccess = getHasDataAccess(databases);
- const hasNativeWrite = getHasNativeWrite(databases);
const isAdmin = getUserIsAdmin(state);
+ const hasDataAccess = canUserCreateQueries(state);
+ const hasNativeWrite = canUserCreateNativeQueries(state);
const ctx = {
user_is_viewing: [],
@@ -76,7 +74,7 @@ export const MetabotProvider = ({
}
return ctx;
- }, [store, listDbs]);
+ }, [store]);
const registerChatContextProvider = useCallback(
(providerFn: ChatContextProviderFn) => {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
index 13d55cf330e..db205b45b96 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/metabot.unit.spec.tsx
@@ -30,6 +30,7 @@ import {
createMockDatabase,
createMockTokenFeatures,
createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import { createMockState } from "metabase-types/store/mocks";
@@ -851,7 +852,11 @@ describe("metabot-streaming", () => {
});
it("should send along available actions in context", async () => {
- setup();
+ setup({
+ currentUser: createMockUser({
+ permissions: createMockUserPermissions({ can_create_queries: true }),
+ }),
+ });
fetchMock.removeRoutes({ names: ["database-list"] });
setupDatabaseListEndpoint([
createMockDatabase({
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
index 544384a59bb..48131b47268 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
@@ -21,6 +21,8 @@ import {
createMockRecentTableItem,
createMockSearchResult,
createMockTokenFeatures,
+ createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import type { SettingsState } from "metabase-types/store";
import { createMockState } from "metabase-types/store/mocks";
@@ -407,7 +409,16 @@ describe("CommandSuggestion", () => {
items={[]}
range={{ from: 0, to: 0 }}
/>,
- { storeInitialState: createMockState({ settings: mockSettings({}) }) },
+ {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({
+ permissions: createMockUserPermissions({
+ can_create_queries: true,
+ }),
+ }),
+ settings: mockSettings({}),
+ }),
+ },
);
await userEvent.click(await screen.findByRole("option", { name: "Chart" }));
diff --git a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/use-create-questions-menu-items.ts b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/use-create-questions-menu-items.ts
index 7294d64d951..d1b2dba0306 100644
--- a/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/use-create-questions-menu-items.ts
+++ b/enterprise/frontend/src/metabase-enterprise/rich_text_editing/tiptap/extensions/Command/use-create-questions-menu-items.ts
@@ -2,11 +2,12 @@ import { useMemo } from "react";
import { t } from "ttag";
import { useListDatabasesQuery } from "metabase/api";
+import { useSelector } from "metabase/lib/redux";
+import { getHasDatabaseWithJsonEngine } from "metabase/selectors/data";
import {
- getHasDataAccess,
- getHasDatabaseWithJsonEngine,
- getHasNativeWrite,
-} from "metabase/selectors/data";
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+} from "metabase/selectors/user";
import type { NewQuestionMenuItem } from "./types";
@@ -17,13 +18,9 @@ export const useCreateQuestionsMenuItems = ({
}) => {
const { data } = useListDatabasesQuery();
const databases = useMemo(() => data?.data ?? [], [data]);
- const hasDataAccess = useMemo(() => getHasDataAccess(databases), [databases]);
- const hasNativeWrite = useMemo(
- () => getHasNativeWrite(databases),
- [databases],
- );
-
const hasDatabaseWithJsonEngine = getHasDatabaseWithJsonEngine(databases);
+ const hasDataAccess = useSelector(canUserCreateQueries);
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
const items = useMemo(() => {
const result: NewQuestionMenuItem[] = [];
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsx
index 6f0a01d3960..716d1293844 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonDataPicker/TableSelector/TableSelector.tsx
@@ -109,7 +109,7 @@ export function TableSelector({
{isOpened && (
<DataPickerModal
title={t`Pick a table`}
- value={getDataPickerValue(table) as TablePickerValue}
+ value={getDataPickerValue(table)}
databaseId={database}
onChange={handleChange}
onClose={close}
@@ -126,12 +126,14 @@ export function TableSelector({
);
}
-function getDataPickerValue(table: Table | undefined) {
+function getDataPickerValue(
+ table: Table | undefined,
+): TablePickerValue | undefined {
if (!table) {
- return { model: "table", id: null };
+ return;
}
return {
- model: "table" as const,
+ model: "table",
id: table.id,
name: table.display_name,
db_id: table.db_id,
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformTargetPage/TargetSection/TargetSection.tsx b/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformTargetPage/TargetSection/TargetSection.tsx
index 1469687aa4e..246979db6a8 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformTargetPage/TargetSection/TargetSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms/pages/TransformTargetPage/TargetSection/TargetSection.tsx
@@ -91,7 +91,7 @@ function TargetInfo({ transform }: TargetInfoProps) {
<TargetItemLink
label={database.name}
icon="database"
- to={Urls.dataModelDatabase(database.id)}
+ to={Urls.dataModel({ databaseId: database.id })}
data-testid="database-link"
/>
<TargetItemDivider />
@@ -104,7 +104,10 @@ function TargetInfo({ transform }: TargetInfoProps) {
icon="folder"
to={
table || targetSchemaExists
- ? Urls.dataModelSchema(database.id, target.schema)
+ ? Urls.dataModel({
+ databaseId: database.id,
+ schemaName: target.schema,
+ })
: undefined
}
tooltip={
@@ -249,7 +252,11 @@ function EditMetadataButton({ transform }: EditMetadataButtonProps) {
return (
<Button
component={Link}
- to={Urls.dataModelTable(table.db_id, table.schema, table.id)}
+ to={Urls.dataModel({
+ databaseId: table.db_id,
+ schemaName: table.schema,
+ tableId: table.id,
+ })}
leftSection={<Icon name="label" aria-hidden />}
data-testid="table-metadata-link"
>
diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx
index 22b5336ff23..58e9462923d 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/tests/setup.tsx
@@ -40,6 +40,7 @@ import {
createMockStructuredDatasetQuery,
createMockTextDashboardCard,
createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import {
ORDERS_ID,
@@ -198,7 +199,11 @@ export const setupSdkDashboard = async ({
setupBookmarksEndpoints([]);
- const user = createMockUser();
+ const user = createMockUser({
+ permissions: createMockUserPermissions({
+ can_create_queries: true,
+ }),
+ });
const state = setupSdkState({
currentUser: user,
diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.ts
index c70ebed8bef..31924482bc6 100644
--- a/frontend/src/metabase-types/analytics/event.ts
+++ b/frontend/src/metabase-types/analytics/event.ts
@@ -3,10 +3,6 @@ import type {
ChecklistItemCTA,
ChecklistItemValue,
} from "metabase/home/components/Onboarding/types";
-import type {
- MetadataEditAnalyticsDetail,
- MetadataEventSource,
-} from "metabase/metadata/pages/DataModelV1/types";
import type { KeyboardShortcutId } from "metabase/palette/shortcuts";
import type { ClickActionSection } from "metabase/visualizations/types";
import type {
@@ -98,7 +94,8 @@ export type MoveToTrashEvent = ValidateEvent<{
| "dataset"
| "indexed-entity"
| "snippet"
- | "document";
+ | "document"
+ | "table";
}>;
export type ErrorDiagnosticModalOpenedEvent = ValidateEvent<{
@@ -410,10 +407,27 @@ export type LearnAboutDataClickedEvent = ValidateEvent<{
event: "learn_about_our_data_clicked";
}>;
+export type MetadataEditEventDetail =
+ | "type_casting"
+ | "semantic_type_change"
+ | "visibility_change"
+ | "filtering_change"
+ | "display_values"
+ | "json_unfolding"
+ | "formatting";
+
+export type MetadataEditEventTriggeredFrom = "admin" | "data_studio";
+
export type MetadataEditEvent = ValidateEvent<{
event: "metadata_edited";
- event_detail: MetadataEditAnalyticsDetail;
- triggered_from: MetadataEventSource;
+ event_detail: MetadataEditEventDetail;
+ triggered_from: MetadataEditEventTriggeredFrom;
+}>;
+
+export type BookmarkTableEvent = ValidateEvent<{
+ event: "bookmark_added";
+ event_detail: "table";
+ triggered_from: "collection_list";
}>;
export type BookmarkQuestionEvent = ValidateEvent<{
@@ -498,6 +512,7 @@ export type RemoteSyncEvent =
| RemoteSyncDeactivatedEvent;
export type BookmarkEvent =
+ | BookmarkTableEvent
| BookmarkQuestionEvent
| BookmarkModelEvent
| BookmarkMetricEvent
diff --git a/frontend/src/metabase-types/api/bookmark.ts b/frontend/src/metabase-types/api/bookmark.ts
index bc2f4c762c3..dee42f6b0a6 100644
--- a/frontend/src/metabase-types/api/bookmark.ts
+++ b/frontend/src/metabase-types/api/bookmark.ts
@@ -11,6 +11,7 @@ export const BOOKMARK_TYPES = [
"snippet",
"indexed-entity",
"document",
+ "table",
] as const;
export type BookmarkType = (typeof BOOKMARK_TYPES)[number];
export type BookmarkId = string;
diff --git a/frontend/src/metabase-types/api/collection.ts b/frontend/src/metabase-types/api/collection.ts
index 2226f812da9..e132d03d4db 100644
--- a/frontend/src/metabase-types/api/collection.ts
+++ b/frontend/src/metabase-types/api/collection.ts
@@ -106,6 +106,7 @@ export const COLLECTION_ITEM_MODELS = [
"collection",
"indexed-entity",
"document",
+ "table",
] as const;
export type CollectionItemModel = (typeof COLLECTION_ITEM_MODELS)[number];
diff --git a/frontend/src/metabase-types/api/mocks/table.ts b/frontend/src/metabase-types/api/mocks/table.ts
index 1c33c31df56..e44138fa98c 100644
--- a/frontend/src/metabase-types/api/mocks/table.ts
+++ b/frontend/src/metabase-types/api/mocks/table.ts
@@ -1,4 +1,12 @@
-import type { ForeignKey, Schema, Table } from "metabase-types/api";
+import type {
+ BulkTableInfo,
+ BulkTableSelection,
+ BulkTableSelectionInfo,
+ ForeignKey,
+ PublishTablesResponse,
+ Schema,
+ Table,
+} from "metabase-types/api";
export const createMockTable = (opts?: Partial<Table>): Table => {
return {
@@ -22,6 +30,8 @@ export const createMockTable = (opts?: Partial<Table>): Table => {
owner_user_id: null,
transform_id: null,
view_count: 0,
+ collection_id: null,
+ is_published: false,
...opts,
};
};
@@ -40,3 +50,45 @@ export const createMockForeignKey = (
relationship: "Mt1",
...opts,
});
+
+export const createMockBulkTableInfo = (
+ opts?: Partial<BulkTableInfo>,
+): BulkTableInfo => {
+ return {
+ id: 1,
+ db_id: 1,
+ name: "TABLE",
+ display_name: "Table",
+ schema: "public",
+ is_published: false,
+ ...opts,
+ };
+};
+
+export const createMockBulkTableSelection = (
+ opts?: Partial<BulkTableSelection>,
+): BulkTableSelection => {
+ return {
+ ...opts,
+ };
+};
+
+export const createMockBulkTableSelectionInfo = (
+ opts?: Partial<BulkTableSelectionInfo>,
+): BulkTableSelectionInfo => {
+ return {
+ selected_table: null,
+ published_downstream_tables: [],
+ unpublished_upstream_tables: [],
+ ...opts,
+ };
+};
+
+export const createMockPublishTablesResponse = (
+ opts?: Partial<PublishTablesResponse>,
+): PublishTablesResponse => {
+ return {
+ target_collection: null,
+ ...opts,
+ };
+};
diff --git a/frontend/src/metabase-types/api/mocks/user.ts b/frontend/src/metabase-types/api/mocks/user.ts
index fbd07ed7d56..6119bfb640a 100644
--- a/frontend/src/metabase-types/api/mocks/user.ts
+++ b/frontend/src/metabase-types/api/mocks/user.ts
@@ -1,4 +1,9 @@
-import type { User, UserInfo, UserListResult } from "metabase-types/api";
+import type {
+ User,
+ UserInfo,
+ UserListResult,
+ UserPermissions,
+} from "metabase-types/api";
export const createMockUser = (opts?: Partial<User>): User => {
const firstName = opts?.first_name ?? "Testy";
@@ -25,10 +30,17 @@ export const createMockUser = (opts?: Partial<User>): User => {
last_login: new Date().toISOString(),
updated_at: new Date().toISOString(),
sso_source: null,
+ permissions: createMockUserPermissions(),
...opts,
};
};
+export const createMockUserPermissions = (
+ opts?: Partial<UserPermissions>,
+): UserPermissions => {
+ return { ...opts };
+};
+
export const createMockUserListResult = (
opts?: Partial<UserListResult>,
): UserListResult => ({
diff --git a/frontend/src/metabase-types/api/table.ts b/frontend/src/metabase-types/api/table.ts
index 4949fcb7fc5..4a975fe6438 100644
--- a/frontend/src/metabase-types/api/table.ts
+++ b/frontend/src/metabase-types/api/table.ts
@@ -1,5 +1,5 @@
import type { Card, CardType } from "./card";
-import type { Collection } from "./collection";
+import type { Collection, CollectionId } from "./collection";
import type { Database, DatabaseId, InitialSyncStatus } from "./database";
import type { DatasetData } from "./dataset";
import type { Field, FieldId } from "./field";
@@ -71,8 +71,9 @@ export type Table = {
view_count: number;
transform?: Transform;
- published_models?: Card[] | null; // present in /api/table/:id/query_metadata
- published_as_model?: boolean; // present in /api/database/:id/schemas/:schemaId
+ collection_id: CollectionId | null;
+ is_published: boolean;
+ collection?: Collection;
};
export type SchemaName = string;
@@ -135,7 +136,7 @@ export interface UpdateTableRequest {
id: TableId;
display_name?: string;
visibility_type?: TableVisibilityType;
- description?: string;
+ description?: string | null;
caveats?: string;
points_of_interest?: string;
show_in_getting_started?: boolean;
@@ -211,19 +212,6 @@ export interface GetTableDataRequest {
tableId: TableId;
}
-export interface PublishModelsRequest {
- database_ids?: DatabaseId[];
- schema_ids?: SchemaId[];
- table_ids?: TableId[];
- target_collection_id: number | "library" | null;
-}
-
-export interface PublishModelsResponse {
- created_count: number;
- models: Card[];
- target_collection: Collection | null;
-}
-
export type TableData = {
data: DatasetData;
database_id: DatabaseId;
@@ -244,3 +232,31 @@ export type TableData = {
/** A date in ISO 8601 format */
started_at?: string;
};
+
+export interface BulkTableInfo {
+ id: TableId;
+ db_id: DatabaseId;
+ name: string;
+ display_name: string;
+ schema: string | null;
+ is_published: boolean;
+}
+
+export interface BulkTableSelection {
+ database_ids?: DatabaseId[];
+ schema_ids?: SchemaId[];
+ table_ids?: TableId[];
+}
+
+export interface BulkTableSelectionInfo {
+ // if only one table was selected, returns this table, otherwise null
+ selected_table: BulkTableInfo | null;
+ // tables outside the selection that use selected tables for remapping
+ published_downstream_tables: BulkTableInfo[];
+ // tables outside the selection that are used for remapping by selected tables
+ unpublished_upstream_tables: BulkTableInfo[];
+}
+
+export interface PublishTablesResponse {
+ target_collection: Collection | null;
+}
diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.ts
index 20ffd955392..9ff6cdb93a3 100644
--- a/frontend/src/metabase-types/api/user.ts
+++ b/frontend/src/metabase-types/api/user.ts
@@ -41,6 +41,20 @@ export interface BaseUser {
updated_at: string;
}
+export interface UserPermissions {
+ can_create_queries?: boolean;
+ can_create_native_queries?: boolean;
+
+ // requires advanced_permissions feature
+ is_group_manager?: boolean;
+ can_access_data_model?: boolean;
+ can_access_db_details?: boolean;
+ can_access_monitoring?: boolean;
+ can_access_setting?: boolean;
+ can_access_subscription?: boolean;
+ can_access_data_studio?: boolean;
+}
+
export interface User extends BaseUser {
attributes: UserAttributeMap | null;
login_attributes: UserAttributeMap | null;
@@ -54,6 +68,7 @@ export interface User extends BaseUser {
custom_homepage: {
dashboard_id: DashboardId;
} | null;
+ permissions?: UserPermissions;
}
export interface UserListResult {
diff --git a/frontend/src/metabase/admin/datamodel/components/SegmentActionSelect.tsx b/frontend/src/metabase/admin/datamodel/components/SegmentActionSelect.tsx
index 36e2e0a4e29..2c9c01598f4 100644
--- a/frontend/src/metabase/admin/datamodel/components/SegmentActionSelect.tsx
+++ b/frontend/src/metabase/admin/datamodel/components/SegmentActionSelect.tsx
@@ -2,6 +2,7 @@ import { useDisclosure } from "@mantine/hooks";
import { Link } from "react-router";
import { t } from "ttag";
+import * as Urls from "metabase/lib/urls";
import { ActionIcon, Icon, Menu } from "metabase/ui";
import type { Segment } from "metabase-types/api";
@@ -29,15 +30,12 @@ export function SegmentActionSelect({
</ActionIcon>
</Menu.Target>
<Menu.Dropdown p="sm">
- <Menu.Item
- component={Link}
- to={`/admin/datamodel/segment/${object.id}`}
- >
+ <Menu.Item component={Link} to={Urls.dataModelSegment(object.id)}>
{t`Edit Segment`}
</Menu.Item>
<Menu.Item
component={Link}
- to={`/admin/datamodel/segment/${object.id}/revisions`}
+ to={Urls.dataModelSegmentRevisions(object.id)}
>
{t`Revision History`}
</Menu.Item>
diff --git a/frontend/src/metabase/admin/datamodel/components/SegmentItem.tsx b/frontend/src/metabase/admin/datamodel/components/SegmentItem.tsx
index 72ab9863fec..b8bb8bb16e3 100644
--- a/frontend/src/metabase/admin/datamodel/components/SegmentItem.tsx
+++ b/frontend/src/metabase/admin/datamodel/components/SegmentItem.tsx
@@ -1,5 +1,6 @@
import { Link } from "react-router";
+import * as Urls from "metabase/lib/urls";
import { TableBreadcrumbs } from "metabase/metadata/components";
import { Box, Flex, Group, Icon } from "metabase/ui";
import type { Segment } from "metabase-types/api";
@@ -16,7 +17,7 @@ export const SegmentItem = ({ segment, onRetire }: Props) => {
return (
<tr>
<Box component="td" className={S.cell} p="sm">
- <Link to={`/admin/datamodel/segment/${segment.id}`}>
+ <Link to={Urls.dataModelSegment(segment.id)}>
<Group display="inline-flex" gap="sm" wrap="nowrap">
<Box
color="text-medium"
diff --git a/frontend/src/metabase/admin/datamodel/components/revisions/RevisionHistory.jsx b/frontend/src/metabase/admin/datamodel/components/revisions/RevisionHistory.jsx
index eba5154432f..99e8cffe014 100644
--- a/frontend/src/metabase/admin/datamodel/components/revisions/RevisionHistory.jsx
+++ b/frontend/src/metabase/admin/datamodel/components/revisions/RevisionHistory.jsx
@@ -8,6 +8,7 @@ import Breadcrumbs from "metabase/common/components/Breadcrumbs";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import CS from "metabase/css/core/index.css";
import { assignUserColors } from "metabase/lib/formatting";
+import * as Urls from "metabase/lib/urls";
import Revision from "./Revision";
@@ -40,7 +41,7 @@ export default class RevisionHistory extends Component {
crumbs={[
[
t`Segments`,
- `/admin/datamodel/segments?table=${segment.table_id}`,
+ Urls.dataModelSegments({ tableId: segment.table_id }),
],
[t`Segment History`],
]}
diff --git a/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.jsx b/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.jsx
index 163ea077ebf..9b4c4007186 100644
--- a/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.jsx
+++ b/frontend/src/metabase/admin/datamodel/containers/SegmentListApp.jsx
@@ -12,6 +12,7 @@ import AdminS from "metabase/css/admin.module.css";
import CS from "metabase/css/core/index.css";
import Segments from "metabase/entities/segments";
import { connect } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
class SegmentListAppInner extends Component {
render() {
@@ -24,7 +25,7 @@ class SegmentListAppInner extends Component {
>
<div className={cx(CS.flex, CS.py2)}>
{tableSelector}
- <Link to="/admin/datamodel/segment/create" className={CS.mlAuto}>
+ <Link to={Urls.newDataModelSegment()} className={CS.mlAuto}>
<Button primary>{t`New segment`}</Button>
</Link>
</div>
diff --git a/frontend/src/metabase/api/dataset.ts b/frontend/src/metabase/api/dataset.ts
index 45eb7378a50..59c4a590615 100644
--- a/frontend/src/metabase/api/dataset.ts
+++ b/frontend/src/metabase/api/dataset.ts
@@ -11,6 +11,7 @@ import type {
import { Api } from "./api";
import {
+ provideAdhocDatasetTags,
provideAdhocQueryMetadataTags,
provideParameterValuesTags,
} from "./tags";
@@ -40,6 +41,7 @@ export const datasetApi = Api.injectEndpoints({
body,
noEvent: ignore_error,
}),
+ providesTags: () => provideAdhocDatasetTags(),
}),
getAdhocPivotQuery: builder.query<
Dataset,
@@ -57,6 +59,7 @@ export const datasetApi = Api.injectEndpoints({
body,
noEvent: ignore_error,
}),
+ providesTags: () => provideAdhocDatasetTags(),
}),
getAdhocQueryMetadata: builder.query<CardQueryMetadata, DatasetQuery>({
query: (body) => ({
diff --git a/frontend/src/metabase/api/field.ts b/frontend/src/metabase/api/field.ts
index 8ae2f71af2e..4538e817d3c 100644
--- a/frontend/src/metabase/api/field.ts
+++ b/frontend/src/metabase/api/field.ts
@@ -81,6 +81,7 @@ export const fieldApi = Api.injectEndpoints({
idTag("field-values", id),
tag("parameter-values"),
tag("card"),
+ tag("dataset"),
]),
}),
updateFieldValues: builder.mutation<void, UpdateFieldValuesRequest>({
@@ -109,6 +110,7 @@ export const fieldApi = Api.injectEndpoints({
idTag("field", id),
idTag("field-values", id),
tag("parameter-values"),
+ tag("dataset"),
]),
}),
deleteFieldDimension: builder.mutation<void, FieldId>({
@@ -121,6 +123,7 @@ export const fieldApi = Api.injectEndpoints({
idTag("field", id),
idTag("field-values", id),
tag("parameter-values"),
+ tag("dataset"),
]),
}),
rescanFieldValues: builder.mutation<void, FieldId>({
diff --git a/frontend/src/metabase/api/table.ts b/frontend/src/metabase/api/table.ts
index 328789d526f..370100215b3 100644
--- a/frontend/src/metabase/api/table.ts
+++ b/frontend/src/metabase/api/table.ts
@@ -90,6 +90,7 @@ export const tableApi = Api.injectEndpoints({
idTag("table", id),
tag("database"),
tag("card"),
+ tag("dataset"),
]),
}),
updateTableList: builder.mutation<Table[], UpdateTableListRequest>({
@@ -99,7 +100,12 @@ export const tableApi = Api.injectEndpoints({
body,
}),
invalidatesTags: (_, error) =>
- invalidateTags(error, [tag("table"), tag("database"), tag("card")]),
+ invalidateTags(error, [
+ tag("table"),
+ tag("database"),
+ tag("card"),
+ tag("dataset"),
+ ]),
}),
updateTableFieldsOrder: builder.mutation<
Table,
@@ -116,6 +122,7 @@ export const tableApi = Api.injectEndpoints({
idTag("table", id),
listTag("field"),
tag("card"),
+ tag("dataset"),
]),
}),
rescanTableFieldValues: builder.mutation<void, TableId>({
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index ab5f61ad5c0..7f6be88a44b 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -14,6 +14,7 @@ export const TAG_TYPES = [
"dashboard",
"dashboard-question-candidates",
"database",
+ "dataset",
"document",
"embedding-hub-checklist",
"field",
diff --git a/frontend/src/metabase/api/tags/utils.ts b/frontend/src/metabase/api/tags/utils.ts
index a50640a6dae..ef74a034ad4 100644
--- a/frontend/src/metabase/api/tags/utils.ts
+++ b/frontend/src/metabase/api/tags/utils.ts
@@ -106,10 +106,15 @@ export function provideActivityItemTags(
return [idTag(TAG_TYPE_MAPPING[item.model], item.id)];
}
+export function provideAdhocDatasetTags(): TagDescription<TagType>[] {
+ return [tag("dataset")];
+}
+
export function provideAdhocQueryMetadataTags(
metadata: CardQueryMetadata,
): TagDescription<TagType>[] {
return [
+ ...provideAdhocDatasetTags(),
...provideDatabaseListTags(metadata.databases),
...provideTableListTags(metadata.tables),
...provideFieldListTags(metadata.fields),
diff --git a/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx b/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx
index 90ad33451c6..d03088a7cd2 100644
--- a/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx
+++ b/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx
@@ -3,7 +3,7 @@ import { t } from "ttag";
import _ from "underscore";
import NoResults from "assets/img/metrics_bot.svg";
-import { skipToken, useListDatabasesQuery } from "metabase/api";
+import { skipToken } from "metabase/api";
import EmptyState from "metabase/common/components/EmptyState";
import Link, { ForwardRefLink } from "metabase/common/components/Link";
import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
@@ -15,8 +15,8 @@ import {
PLUGIN_CONTENT_VERIFICATION,
PLUGIN_DATA_STUDIO,
} from "metabase/plugins";
-import { getHasDataAccess } from "metabase/selectors/data";
import { getIsEmbeddingIframe } from "metabase/selectors/embed";
+import { canUserCreateQueries } from "metabase/selectors/user";
import {
ActionIcon,
Box,
@@ -48,7 +48,6 @@ const {
} = PLUGIN_CONTENT_VERIFICATION;
export function BrowseMetrics() {
- const { data } = useListDatabasesQuery();
const [metricFilters, setMetricFilters] = useMetricFilterSettings();
const { isLoading, error, metrics, hasVerifiedMetrics } =
useFilteredMetrics(metricFilters);
@@ -67,8 +66,7 @@ export function BrowseMetrics() {
collectionId: libraryMetricCollection?.id,
});
- const databases = data?.data ?? [];
- const hasDataAccess = getHasDataAccess(databases);
+ const hasDataAccess = useSelector(canUserCreateQueries);
const isEmbeddingIframe = useSelector(getIsEmbeddingIframe);
const canCreateMetric = !isEmbeddingIframe && hasDataAccess;
diff --git a/frontend/src/metabase/browse/metrics/tests/common.unit.spec.tsx b/frontend/src/metabase/browse/metrics/tests/common.unit.spec.tsx
index 4c70d344f56..e1caf053ec4 100644
--- a/frontend/src/metabase/browse/metrics/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/browse/metrics/tests/common.unit.spec.tsx
@@ -25,7 +25,7 @@ describe("BrowseMetrics (OSS)", () => {
});
it("should not show the Create metric button in an empty state if the user does not have data access", async () => {
- setup({ metricCount: 0, databases: [] });
+ setup({ metricCount: 0, canCreateQueries: false });
expect(
await screen.findByText(
"Create Metrics to define the official way to calculate important numbers for your team",
@@ -35,7 +35,7 @@ describe("BrowseMetrics (OSS)", () => {
});
it("should not show the new metric header button if the user does not have data access", async () => {
- setup({ metricCount: 0, databases: [] });
+ setup({ metricCount: 0, canCreateQueries: false });
const header = await screen.findByTestId("browse-metrics-header");
expect(
within(header).queryByLabelText("Create a new metric"),
diff --git a/frontend/src/metabase/browse/metrics/tests/setup.tsx b/frontend/src/metabase/browse/metrics/tests/setup.tsx
index 25f4790d738..69b61e27352 100644
--- a/frontend/src/metabase/browse/metrics/tests/setup.tsx
+++ b/frontend/src/metabase/browse/metrics/tests/setup.tsx
@@ -4,22 +4,21 @@ import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupCardEndpoints,
setupCardQueryEndpoints,
- setupDatabasesEndpoints,
setupRecentViewsEndpoints,
setupSearchEndpoints,
setupSettingsEndpoints,
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
-import type { Database, TokenFeatures } from "metabase-types/api";
+import type { TokenFeatures } from "metabase-types/api";
import {
createMockCard,
createMockCollection,
- createMockDatabase,
createMockDataset,
createMockSearchResult,
createMockTokenFeatures,
createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import {
createMockSetupState,
@@ -211,18 +210,16 @@ export type SetupOpts = {
showMetabaseLinks?: boolean;
hasEnterprisePlugins?: boolean;
tokenFeatures?: Partial<TokenFeatures>;
- databases?: Database[];
+ canCreateQueries?: boolean;
};
-const MOCK_DATABASE = createMockDatabase({ id: 1, name: "Database Name" });
-
export function setup({
metricCount = Infinity,
recentMetricCount = 5,
showMetabaseLinks = true,
hasEnterprisePlugins,
tokenFeatures = {},
- databases = [MOCK_DATABASE],
+ canCreateQueries = true,
}: SetupOpts = {}) {
const state = createMockState({
setup: createMockSetupState({
@@ -232,7 +229,12 @@ export function setup({
"show-metabase-links": showMetabaseLinks,
"token-features": createMockTokenFeatures(tokenFeatures),
}),
- currentUser: createMockUser({ id: 1 }),
+ currentUser: createMockUser({
+ id: 1,
+ permissions: createMockUserPermissions({
+ can_create_queries: canCreateQueries,
+ }),
+ }),
});
if (hasEnterprisePlugins) {
@@ -247,7 +249,6 @@ export function setup({
const metrics = mockMetricResults.slice(0, metricCount);
const recentMetrics = mockRecentMetrics.slice(0, recentMetricCount);
- setupDatabasesEndpoints(databases);
setupSettingsEndpoints([]);
setupSearchEndpoints(metrics.map(createMockSearchResult));
setupRecentViewsEndpoints(recentMetrics);
diff --git a/frontend/src/metabase/browse/models/BrowseModels.tsx b/frontend/src/metabase/browse/models/BrowseModels.tsx
index a2c892f1a8f..94500d849be 100644
--- a/frontend/src/metabase/browse/models/BrowseModels.tsx
+++ b/frontend/src/metabase/browse/models/BrowseModels.tsx
@@ -2,11 +2,7 @@ import { useMemo, useState } from "react";
import { t } from "ttag";
import _ from "underscore";
-import {
- skipToken,
- useListDatabasesQuery,
- useListRecentsQuery,
-} from "metabase/api";
+import { skipToken, useListRecentsQuery } from "metabase/api";
import ExternalLink from "metabase/common/components/ExternalLink";
import { ForwardRefLink } from "metabase/common/components/Link";
import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
@@ -17,8 +13,11 @@ import {
PLUGIN_COLLECTIONS,
PLUGIN_CONTENT_VERIFICATION,
} from "metabase/plugins";
-import { getHasDataAccess, getHasNativeWrite } from "metabase/selectors/data";
import { getIsEmbeddingIframe } from "metabase/selectors/embed";
+import {
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+} from "metabase/selectors/user";
import {
ActionIcon,
Box,
@@ -54,7 +53,6 @@ const {
} = PLUGIN_CONTENT_VERIFICATION;
export const BrowseModels = () => {
- const { data } = useListDatabasesQuery();
const [modelFilters, setModelFilters] = useModelFilterSettings();
const { isLoading, error, models, recentModels, hasVerifiedModels } =
useFilteredModels(modelFilters);
@@ -64,9 +62,8 @@ export const BrowseModels = () => {
const isEmpty = !isLoading && !error && models.length === 0;
const titleId = useMemo(() => _.uniqueId("browse-models"), []);
- const databases = data?.data ?? [];
- const hasDataAccess = getHasDataAccess(databases);
- const hasNativeWrite = getHasNativeWrite(databases);
+ const hasDataAccess = useSelector(canUserCreateQueries);
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
const isEmbeddingIframe = useSelector(getIsEmbeddingIframe);
const canCreateNewModel =
diff --git a/frontend/src/metabase/browse/models/BrowseModels.unit.spec.tsx b/frontend/src/metabase/browse/models/BrowseModels.unit.spec.tsx
index 8ca032b231d..a437e9a6d49 100644
--- a/frontend/src/metabase/browse/models/BrowseModels.unit.spec.tsx
+++ b/frontend/src/metabase/browse/models/BrowseModels.unit.spec.tsx
@@ -2,7 +2,6 @@ import userEvent from "@testing-library/user-event";
import { Route } from "react-router";
import {
- setupDatabasesEndpoints,
setupRecentViewsEndpoints,
setupSearchEndpoints,
setupSettingsEndpoints,
@@ -10,8 +9,9 @@ import {
import { renderWithProviders, screen, within } from "__support__/ui";
import {
createMockCollection,
- createMockDatabase,
createMockSearchResult,
+ createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import { createMockSetupState } from "metabase-types/store/mocks";
@@ -34,7 +34,6 @@ const setup = ({
recentModelCount = 5,
hasDataPermissions = true,
}: SetupOptions) => {
- const databases = hasDataPermissions ? [createMockDatabase()] : [];
const mockModelResults = mockModels.map((model) =>
createMockModelResult(model),
);
@@ -42,7 +41,6 @@ const setup = ({
.slice(0, recentModelCount)
.map((model) => createMockRecentModel(model));
const models = mockModelResults.slice(0, modelCount);
- setupDatabasesEndpoints(databases);
setupSearchEndpoints(models.map((model) => createMockSearchResult(model)));
setupSettingsEndpoints([]);
setupRecentViewsEndpoints(mockRecentModels);
@@ -56,6 +54,12 @@ const setup = ({
</>,
{
storeInitialState: {
+ currentUser: createMockUser({
+ permissions: createMockUserPermissions({
+ can_create_queries: hasDataPermissions,
+ can_create_native_queries: hasDataPermissions,
+ }),
+ }),
setup: createMockSetupState({
locale: { name: "English", code: "en" },
}),
diff --git a/frontend/src/metabase/collections/analytics.ts b/frontend/src/metabase/collections/analytics.ts
index 7fc04461c46..44fc2390d64 100644
--- a/frontend/src/metabase/collections/analytics.ts
+++ b/frontend/src/metabase/collections/analytics.ts
@@ -29,7 +29,8 @@ export const trackCollectionItemBookmarked = (item: CollectionItem) => {
| "collection"
| "dataset"
| "document"
- | "card",
+ | "card"
+ | "table",
) => {
switch (analyticsModel) {
case "card":
diff --git a/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.unit.spec.tsx b/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.unit.spec.tsx
index 91f898f63f9..44293cd5f99 100644
--- a/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/ActionMenu/ActionMenu.unit.spec.tsx
@@ -2,7 +2,7 @@ import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { createMockEntitiesState } from "__support__/store";
-import { getIcon, renderWithProviders } from "__support__/ui";
+import { getIcon, queryIcon, renderWithProviders } from "__support__/ui";
import Collections from "metabase/entities/collections";
import Dashboards from "metabase/entities/dashboards";
import Questions from "metabase/entities/questions";
@@ -268,4 +268,17 @@ describe("ActionMenu", () => {
expect(screen.queryByText("X-ray this")).not.toBeInTheDocument();
});
});
+
+ describe("tables", () => {
+ it("should not allow actions on a table", () => {
+ const item = createMockCollectionItem({
+ id: 1,
+ model: "table",
+ });
+
+ setup({ item });
+
+ expect(queryIcon("ellipsis")).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/metabase/collections/components/CollectionContent/constants.ts b/frontend/src/metabase/collections/components/CollectionContent/constants.ts
index 7c5674af0e2..1685a12213e 100644
--- a/frontend/src/metabase/collections/components/CollectionContent/constants.ts
+++ b/frontend/src/metabase/collections/components/CollectionContent/constants.ts
@@ -34,4 +34,5 @@ export const ALL_MODELS: CollectionItemModel[] = [
"snippet",
"collection",
"document",
+ "table",
];
diff --git a/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx b/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx
index 0a6db255ece..738e15ae84e 100644
--- a/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx
+++ b/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.tsx
@@ -87,8 +87,8 @@ function getDefaultEmptyStateMessages(collection: Collection | undefined) {
switch (PLUGIN_DATA_STUDIO.getLibraryCollectionType(collection?.type)) {
case "models":
return {
- title: t`No models yet`,
- description: t`Put models in the Library to see them here.`,
+ title: t`No tables or models yet`,
+ description: t`Publish tables in the Library to see them here.`,
};
case "metrics":
return {
diff --git a/frontend/src/metabase/collections/utils.ts b/frontend/src/metabase/collections/utils.ts
index 9010dc8c388..0603e38e112 100644
--- a/frontend/src/metabase/collections/utils.ts
+++ b/frontend/src/metabase/collections/utils.ts
@@ -175,10 +175,23 @@ export function isReadOnlyCollection(collection: CollectionItem) {
return isItemCollection(collection) && !collection.can_write;
}
-export function canBookmarkItem(item: CollectionItem) {
- return (
- !isLibraryCollection(item as Pick<Collection, "type">) && !item.archived
- );
+export function canBookmarkItem({ model, type, archived }: CollectionItem) {
+ if (archived) {
+ return false;
+ }
+
+ if (type === "question" || type === "model" || type === "metric") {
+ return true;
+ }
+
+ switch (model) {
+ case "table":
+ return false;
+ case "collection":
+ return !isLibraryCollection({ type });
+ default:
+ return true;
+ }
}
export function canPinItem(item: CollectionItem, collection?: Collection) {
@@ -210,6 +223,7 @@ export function canArchiveItem(item: CollectionItem, collection?: Collection) {
!isReadOnlyCollection(item) &&
!(isItemCollection(item) && isRootPersonalCollection(item)) &&
!isLibraryCollection(item as Pick<Collection, "type">) &&
+ item.model !== "table" &&
!item.archived
);
}
diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.tsx
index 9aab3ad69bd..b0acae588a2 100644
--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.tsx
+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.tsx
@@ -4,11 +4,11 @@ import _ from "underscore";
import Databases from "metabase/entities/databases";
import { connect } from "metabase/lib/redux";
import { closeNavbar } from "metabase/redux/app";
+import { getHasDatabaseWithJsonEngine } from "metabase/selectors/data";
import {
- getHasDataAccess,
- getHasDatabaseWithJsonEngine,
- getHasNativeWrite,
-} from "metabase/selectors/data";
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+} from "metabase/selectors/user";
import type Database from "metabase-lib/v1/metadata/Database";
import type { State } from "metabase-types/store";
@@ -22,8 +22,8 @@ const mapStateToProps = (
state: State,
{ databases = [] }: MenuDatabaseProps,
) => ({
- hasDataAccess: getHasDataAccess(databases),
- hasNativeWrite: getHasNativeWrite(databases),
+ hasDataAccess: canUserCreateQueries(state),
+ hasNativeWrite: canUserCreateNativeQueries(state),
hasDatabaseWithJsonEngine: getHasDatabaseWithJsonEngine(databases),
});
diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx
index f0fe37da5bb..199b45ba0db 100644
--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx
@@ -7,8 +7,13 @@ import {
import { renderWithProviders, screen } from "__support__/ui";
import { NewModals } from "metabase/new/components/NewModals/NewModals";
import type { Database } from "metabase-types/api";
-import { createMockCollection } from "metabase-types/api/mocks";
+import {
+ createMockCollection,
+ createMockUser,
+ createMockUserPermissions,
+} from "metabase-types/api/mocks";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+import { createMockState } from "metabase-types/store/mocks";
import NewItemMenu from "./NewItemMenu";
@@ -34,6 +39,16 @@ async function setup({ databases = [SAMPLE_DATABASE] }: SetupOpts = {}) {
<NewItemMenu trigger={<button>New</button>} />
<NewModals />
</>,
+ {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({
+ permissions: createMockUserPermissions({
+ can_create_queries: true,
+ can_create_native_queries: true,
+ }),
+ }),
+ }),
+ },
);
await userEvent.click(screen.getByText("New"));
}
diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemList.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemList.tsx
index 6d8ee5053b5..2f9c2c4965c 100644
--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemList.tsx
+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionItemList.tsx
@@ -11,6 +11,7 @@ const validModels: CollectionItemModel[] = [
"card",
"dataset",
"metric",
+ "table",
];
const getValidCollectionItemModels = (models?: CollectionItemModel[]) =>
diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.unit.spec.tsx
index 87b348231dd..d1f2f13102c 100644
--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/components/CollectionPicker.unit.spec.tsx
@@ -2,7 +2,10 @@ import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { useState } from "react";
-import { setupCollectionItemsEndpoint } from "__support__/server-mocks";
+import {
+ setupCollectionItemsEndpoint,
+ setupDatabasesEndpoints,
+} from "__support__/server-mocks";
import {
act,
mockGetBoundingClientRect,
@@ -148,6 +151,7 @@ const setup = ({
});
setupCollectionTreeMocks(collectionTree);
+ setupDatabasesEndpoints([]);
function TestComponent() {
const [path, setPath] = useState<CollectionPickerStatePath>();
diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts
index e8482259424..7c1cca09af3 100644
--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts
+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/hooks.ts
@@ -5,17 +5,14 @@ import {
skipToken,
useGetCollectionQuery,
useListCollectionItemsQuery,
+ useListDatabasesQuery,
} from "metabase/api";
import { isRootCollection } from "metabase/collections/utils";
import { PERSONAL_COLLECTIONS } from "metabase/entities/collections/constants";
import { useSelector } from "metabase/lib/redux";
import { PLUGIN_DATA_STUDIO } from "metabase/plugins";
import { getUser, getUserIsAdmin } from "metabase/selectors/user";
-import type {
- Collection,
- CollectionItemModel,
- Dashboard,
-} from "metabase-types/api";
+import type { Collection, Dashboard } from "metabase-types/api";
import type { CollectionItemListProps, CollectionPickerItem } from "./types";
@@ -38,8 +35,12 @@ const personalCollectionsRoot: CollectionPickerItem = {
export const useRootCollectionPickerItems = (
options: CollectionItemListProps["options"],
) => {
- const isAdmin = useSelector(getUserIsAdmin);
const currentUser = useSelector(getUser);
+ const isAdmin = useSelector(getUserIsAdmin);
+
+ const { data: databaseData, isLoading: isLoadingDatabases } =
+ useListDatabasesQuery(undefined, { skip: !options.showDatabases });
+ const databases = databaseData?.data ?? [];
const { data: personalCollection, isLoading: isLoadingPersonalCollecton } =
useGetCollectionQuery(
@@ -84,7 +85,7 @@ export const useRootCollectionPickerItems = (
});
}
- if (options.showDatabases) {
+ if (options.showDatabases && databases.length > 0) {
collectionItems.push({
id: "databases",
name: t`Databases`,
@@ -92,7 +93,7 @@ export const useRootCollectionPickerItems = (
can_write: true,
location: "/",
here: ["collection"],
- below: ["table" as CollectionItemModel],
+ below: ["table"],
});
}
@@ -146,12 +147,14 @@ export const useRootCollectionPickerItems = (
rootCollection,
isAdmin,
options,
+ databases.length,
rootCollectionError,
totalPersonalCollectionItems,
libraryCollection,
]);
const isLoading =
+ isLoadingDatabases ||
isLoadingRootCollecton ||
isLoadingPersonalCollecton ||
isLoadingPersonalCollectionItems;
diff --git a/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts b/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts
index b718086b57f..2971f502ca5 100644
--- a/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts
+++ b/frontend/src/metabase/common/components/Pickers/CollectionPicker/types.ts
@@ -21,7 +21,7 @@ export type CollectionItemId = CollectionId | CardId | DashboardId;
// so that we can use its components for picking all of them
export type CollectionPickerModel = Extract<
CollectionItemModel,
- "collection" | "card" | "dataset" | "metric" | "dashboard"
+ "collection" | "card" | "dataset" | "metric" | "dashboard" | "table"
>;
// we can enforce type safety at the boundary of a collection-only picker with this type
diff --git a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.unit.spec.tsx
index b172eda0215..ccc057593ce 100644
--- a/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/DashboardPicker/components/DashboardPicker.unit.spec.tsx
@@ -4,6 +4,7 @@ import { useState } from "react";
import {
setupCollectionItemsEndpoint,
+ setupDatabasesEndpoints,
setupRecentViewsAndSelectionsEndpoints,
setupSearchEndpoints,
} from "__support__/server-mocks";
@@ -172,6 +173,7 @@ const commonSetup = () => {
setupRecentViewsAndSelectionsEndpoints([]);
mockGetBoundingClientRect();
setupSearchEndpoints([]);
+ setupDatabasesEndpoints([]);
const allItems = flattenCollectionTree(collectionTree).map(
createMockCollectionItem,
diff --git a/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.tsx b/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.tsx
index 81823435ea1..82a81819968 100644
--- a/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.tsx
+++ b/frontend/src/metabase/common/components/Pickers/DataPicker/components/DataPickerModal.tsx
@@ -59,7 +59,7 @@ const QUESTION_PICKER_MODELS: QuestionPickerModel[] = [
"dataset",
"metric",
"dashboard",
- "table", // yes, tables are in the question picker now, I'm sorry
+ "table",
];
const RECENTS_CONTEXT: RecentContexts[] = ["selections"];
@@ -195,7 +195,9 @@ export const DataPickerModal = ({
DataPickerItem
>[] = [];
- if (!hasNestedQueriesEnabled) {
+ const hasOnlyTableModels =
+ models != null && models.length === 1 && models[0] === "table";
+ if (hasOnlyTableModels || !hasNestedQueriesEnabled) {
computedTabs.push({
id: "tables-tab",
displayName: t`Tables`,
diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsx
index 96fcdfca646..5463e212119 100644
--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/components/MiniPicker/test/oss.unit.spec.tsx
@@ -185,6 +185,7 @@ describe("MiniPicker", () => {
name: "Rosings",
collection_id: 101,
collection: createMockCollection({
+ id: 101,
effective_location: "/",
}),
}),
diff --git a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts
index f253ef8f56f..58f19283adc 100644
--- a/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/MiniPicker/utils.ts
@@ -2,7 +2,7 @@ import { useState } from "react";
import { useDeepCompareEffect } from "react-use";
import { t } from "ttag";
-import { cardApi, collectionApi, databaseApi } from "metabase/api";
+import { cardApi, collectionApi, databaseApi, tableApi } from "metabase/api";
import type { DispatchFn } from "metabase/lib/redux";
import { useDispatch } from "metabase/lib/redux";
import type { SchemaName } from "metabase-types/api";
@@ -59,7 +59,14 @@ async function getPathFromValue(
dispatch: DispatchFn,
libraryCollection?: MiniPickerCollectionItem,
): Promise<MiniPickerFolderItem[]> {
- return value?.model === "table"
+ if (value.model !== "table") {
+ return getCollectionPathFromValue(value, dispatch, libraryCollection);
+ }
+
+ const table = await dispatch(
+ tableApi.endpoints.getTable.initiate({ id: value.id }),
+ ).unwrap();
+ return table.collection == null
? getTablePathFromValue(value, dispatch)
: getCollectionPathFromValue(value, dispatch, libraryCollection);
}
@@ -93,16 +100,26 @@ async function getTablePathFromValue(
}
async function getCollectionPathFromValue(
- value: Exclude<DataPickerValue, TablePickerValue>,
+ value: DataPickerValue,
dispatch: DispatchFn,
libraryCollection?: MiniPickerCollectionItem,
): Promise<MiniPickerFolderItem[]> {
- const card = await dispatch(
- cardApi.endpoints.getCard.initiate({ id: value.id }),
- ).unwrap();
-
- const location =
- card.collection?.effective_location ?? card.collection?.location;
+ const table =
+ value.model === "table"
+ ? await dispatch(
+ tableApi.endpoints.getTable.initiate({ id: value.id }),
+ ).unwrap()
+ : null;
+ const card =
+ value.model !== "table"
+ ? await dispatch(
+ cardApi.endpoints.getCard.initiate({ id: value.id }),
+ ).unwrap()
+ : null;
+
+ const collection = table?.collection ?? card?.collection;
+
+ const location = collection?.effective_location ?? collection?.location;
if (!location) {
return [getOurAnalytics()];
@@ -112,11 +129,11 @@ async function getCollectionPathFromValue(
const collectionIds = [
"root",
- ...(location?.split("/") ?? []),
- card?.collection_id,
+ ...(location?.split("/") ?? []).map((id) => parseInt(id, 10)),
+ collection?.id,
].filter(Boolean);
- if (collectionIds.includes(String(libraryCollection?.id))) {
+ if (collectionIds.includes(libraryCollection?.id)) {
collectionIds.shift(); // pretend the library is at the top level
locationPath.shift();
}
@@ -139,9 +156,7 @@ async function getCollectionPathFromValue(
}
const nextItem = collectionItems.data.find(
- (item) =>
- item.model === "collection" &&
- String(item.id) === String(collectionIds[i + 1]),
+ (item) => item.model === "collection" && item.id === collectionIds[i + 1],
);
if (!nextItem) {
diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.tsx
index a6949118430..403bd7b6cac 100644
--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.tsx
+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.tsx
@@ -5,11 +5,7 @@ import { useSelector } from "metabase/lib/redux";
import { getUserPersonalCollectionId } from "metabase/selectors/user";
import { DelayedLoadingSpinner, NestedItemPicker } from "../../../EntityPicker";
-import {
- type CollectionPickerItem,
- type CollectionPickerModel,
- useEnsureCollectionSelected,
-} from "../../CollectionPicker";
+import { useEnsureCollectionSelected } from "../../CollectionPicker";
import { CollectionItemPickerResolver } from "../../CollectionPicker/components/CollectionItemPickerResolver";
import { getPathLevelForItem } from "../../CollectionPicker/utils";
import {
@@ -71,13 +67,18 @@ export const QuestionPicker = ({
const defaultPath = useMemo(() => {
return getStateFromIdPath({
idPath: ["root"],
- models: models as CollectionPickerModel[],
+ models,
});
}, [models]);
const path = pathProp ?? defaultPath;
- const { currentDashboard, currentCollection, currentQuestion, isLoading } =
- useGetInitialContainer(initialValue);
+ const {
+ currentTable,
+ currentQuestion,
+ currentCollection,
+ currentDashboard,
+ isLoading,
+ } = useGetInitialContainer(initialValue);
const userPersonalCollectionId = useSelector(getUserPersonalCollectionId);
@@ -86,13 +87,10 @@ export const QuestionPicker = ({
onItemSelect(folder);
//if it's actually a folder
- if (isFolder(folder, models as QuestionPickerModel[])) {
+ if (isFolder(folder, models)) {
const newPath = getStateFromIdPath({
- idPath: getCollectionIdPath(
- folder as CollectionPickerItem,
- userPersonalCollectionId,
- ),
- models: models as CollectionPickerModel[],
+ idPath: getCollectionIdPath(folder, userPersonalCollectionId),
+ models: models,
});
onPathChange(newPath);
@@ -137,7 +135,7 @@ export const QuestionPicker = ({
const newPath = getStateFromIdPath({
idPath,
- models: models as CollectionPickerModel[],
+ models,
});
// start with the current item selected if we can
@@ -160,21 +158,27 @@ export const QuestionPicker = ({
{ ...currentCollection, model: "collection" },
userPersonalCollectionId,
),
- models: models as CollectionPickerModel[],
+ models,
});
// start with the current item selected if we can
- const newSelectedItem: QuestionPickerItem = currentQuestion
+ const newSelectedItem: QuestionPickerItem = currentTable
? {
- id: currentQuestion.id,
- name: currentQuestion.name,
- model: getQuestionPickerValueModel(currentQuestion.type),
+ id: currentTable.id,
+ name: currentTable.display_name,
+ model: "table",
}
- : {
- id: currentCollection.id,
- name: currentCollection.name,
- model: "collection",
- };
+ : currentQuestion
+ ? {
+ id: currentQuestion.id,
+ name: currentQuestion.name,
+ model: getQuestionPickerValueModel(currentQuestion.type),
+ }
+ : {
+ id: currentCollection.id,
+ name: currentCollection.name,
+ model: "collection",
+ };
newPath[newPath.length - 1].selectedItem = newSelectedItem;
@@ -207,15 +211,11 @@ export const QuestionPicker = ({
<NestedItemPicker
initialValue={isTablePickerValue(initialValue) ? initialValue : undefined}
isFolder={(item: QuestionPickerItem | TablePickerItem) =>
- isTablePickerFolderOrQuestionPickerFolder(
- item,
- models as QuestionPickerModel[],
- )
+ isTablePickerFolderOrQuestionPickerFolder(item, models)
}
options={options}
onFolderSelect={onFolderSelect}
onItemSelect={handleItemSelect}
- // @ts-expect-error - CollectionPickerItem and QuestionPickerItem don't mix 😢
path={path}
listResolver={CollectionItemPickerResolver}
shouldShowItem={shouldShowItem}
diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx
index cd2cbe17220..cc78047e157 100644
--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/components/QuestionPicker.unit.spec.tsx
@@ -6,6 +6,7 @@ import { setupEnterprisePlugins } from "__support__/enterprise";
import {
setupCollectionItemsEndpoint,
setupDashboardItemsEndpoint,
+ setupDatabasesEndpoints,
setupRecentViewsAndSelectionsEndpoints,
setupSearchEndpoints,
} from "__support__/server-mocks";
@@ -253,6 +254,7 @@ interface SetupOpts {
const commonSetup = () => {
mockGetBoundingClientRect();
setupRecentViewsAndSelectionsEndpoints([]);
+ setupDatabasesEndpoints([]);
const allItems = flattenCollectionTree(collectionTree).map(
createMockCollectionItem,
diff --git a/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.ts b/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.ts
index 25fccf25241..68e6d734a54 100644
--- a/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.ts
+++ b/frontend/src/metabase/common/components/Pickers/QuestionPicker/utils.ts
@@ -7,7 +7,6 @@ import {
type TablePickerFolderItem,
type TablePickerItem,
isTablePickerFolder,
- isTablePickerItem,
} from "../TablePicker";
import type {
@@ -34,10 +33,7 @@ export const isTablePickerFolderOrQuestionPickerFolder = (
item: QuestionPickerItem | TablePickerItem,
models: QuestionPickerModel[],
): item is TablePickerFolderItem | QuestionPickerItem => {
- if (isTablePickerItem(item)) {
- return isTablePickerFolder(item);
- }
- return isFolder(item, models);
+ return isTablePickerFolder(item) || isFolder(item, models);
};
export const getQuestionPickerValue = ({
diff --git a/frontend/src/metabase/common/components/Pickers/TablePicker/types.ts b/frontend/src/metabase/common/components/Pickers/TablePicker/types.ts
index 590f1c0446c..c3f422aaf47 100644
--- a/frontend/src/metabase/common/components/Pickers/TablePicker/types.ts
+++ b/frontend/src/metabase/common/components/Pickers/TablePicker/types.ts
@@ -53,10 +53,3 @@ export const isTablePickerFolder = (
input?: TablePickerItem | CollectionPickerItem,
): input is TablePickerFolderItem =>
input?.model === "database" || input?.model === "schema";
-
-export const isTablePickerItem = (
- input?: TablePickerItem | CollectionPickerItem,
-): input is TablePickerItem =>
- input?.model === "database" ||
- input?.model === "schema" ||
- input?.model === "table";
diff --git a/frontend/src/metabase/common/components/Pickers/hooks.ts b/frontend/src/metabase/common/components/Pickers/hooks.ts
index a6821a83e4f..b0cd4d9fb87 100644
--- a/frontend/src/metabase/common/components/Pickers/hooks.ts
+++ b/frontend/src/metabase/common/components/Pickers/hooks.ts
@@ -3,6 +3,7 @@ import {
useGetCardQuery,
useGetCollectionQuery,
useGetDashboardQuery,
+ useGetTableQuery,
} from "metabase/api";
import { isValidCollectionId } from "metabase/collections/utils";
import { DATABASES_COLLECTION } from "metabase/entities/collections";
@@ -30,10 +31,6 @@ export const useGetInitialContainer = (
: "root"
: undefined;
- const databasesCollection = isTable
- ? (DATABASES_COLLECTION as Collection)
- : undefined;
-
// Fetch the initial value's entity
const {
data: currentCollection,
@@ -86,10 +83,24 @@ export const useGetInitialContainer = (
: skipToken,
);
+ const {
+ data: currentTable,
+ isLoading: isCurrentTableLoading,
+ error: currentTableError,
+ } = useGetTableQuery(
+ initialValue != null && isTable ? { id: initialValue.id } : skipToken,
+ );
+
+ const currentTableCollection =
+ currentTable != null
+ ? (currentTable.collection ?? (DATABASES_COLLECTION as Collection))
+ : undefined;
+
return {
- currentQuestion: currentQuestion,
+ currentTable,
+ currentQuestion,
currentCollection:
- databasesCollection ??
+ currentTableCollection ??
currentQuestionCollection ??
currentDashboardCollection ??
currentCollection,
@@ -98,10 +109,12 @@ export const useGetInitialContainer = (
isCollectionLoading ||
isQuestionLoading ||
isDashboardLoading ||
+ isCurrentTableLoading ||
isCurrentQuestionCollectionLoading ||
isCurrentQuestionDashboardLoading ||
isCurrentDashboardCollectionLoading,
error:
+ currentTableError ??
currentCollectionError ??
currentDashboardError ??
currentQuestionError ??
diff --git a/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsx b/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsx
index f90e197fb40..8f40f9c65a1 100644
--- a/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/SaveQuestionModal/SaveQuestionModal.unit.spec.tsx
@@ -2,12 +2,13 @@ import userEvent from "@testing-library/user-event";
import { setupEnterpriseTest } from "__support__/enterprise";
import { createMockMetadata } from "__support__/metadata";
-import type { CollectionEndpoints } from "__support__/server-mocks";
import {
+ type CollectionEndpoints,
setupCollectionByIdEndpoint,
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
setupDashboardEndpoints,
+ setupDatabasesEndpoints,
setupLibraryEndpoints,
setupRecentViewsAndSelectionsEndpoints,
} from "__support__/server-mocks";
@@ -121,6 +122,7 @@ const setup = async (
setupDashboardEndpoints(FOO_DASH);
setupDashboardEndpoints(BAR_DASH);
setupLibraryEndpoints();
+ setupDatabasesEndpoints([]);
setupRecentViewsAndSelectionsEndpoints([], ["selections"]);
setupRecentViewsAndSelectionsEndpoints(
diff --git a/frontend/src/metabase/dashboard/components/AddCardSidebar/AddCardSidebar.unit.spec.tsx b/frontend/src/metabase/dashboard/components/AddCardSidebar/AddCardSidebar.unit.spec.tsx
index d734d2edc1a..02d26bf15b9 100644
--- a/frontend/src/metabase/dashboard/components/AddCardSidebar/AddCardSidebar.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/AddCardSidebar/AddCardSidebar.unit.spec.tsx
@@ -4,7 +4,6 @@ import fetchMock from "fetch-mock";
import {
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
- setupDatabasesEndpoints,
} from "__support__/server-mocks";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { getNextId } from "__support__/utils";
@@ -12,19 +11,14 @@ import { ROOT_COLLECTION as ROOT } from "metabase/entities/collections";
import { checkNotNull } from "metabase/lib/types";
// TODO: Move this to a more suitable location for sharing.
import { MockDashboardContext } from "metabase/public/containers/PublicOrEmbeddedDashboard/mock-context";
-import type {
- Collection,
- CollectionItem,
- Dashboard,
- Database,
-} from "metabase-types/api";
+import type { Collection, CollectionItem, Dashboard } from "metabase-types/api";
import {
createMockCollection,
createMockCollectionItem,
createMockDashboard,
- createMockDatabase,
createMockSearchResult,
createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import {
createMockDashboardState,
@@ -33,27 +27,8 @@ import {
import { AddCardSidebar } from "./AddCardSidebar";
-const CURRENT_USER = createMockUser({
- id: 1,
- personal_collection_id: 100,
- is_superuser: true,
-});
-
-const DB_WITH_ONLY_DATA_ACCESS = createMockDatabase({
- id: 1,
- native_permissions: "none",
-});
-
-const DB_WITH_NATIVE_WRITE_ACCESS = createMockDatabase({
- id: 1,
- native_permissions: "write",
-});
-
-const DB_WITH_NO_WRITE_ACCESS = createMockDatabase({
- id: 1,
- is_saved_questions: true,
- native_permissions: "none",
-});
+const CURRENT_USER_ID = 1;
+const PERSONAL_COLLECTION_ID = 100;
const COLLECTION = createMockCollection({
id: 1,
@@ -72,16 +47,16 @@ const SUBCOLLECTION = createMockCollection({
});
const PERSONAL_COLLECTION = createMockCollection({
- id: CURRENT_USER.personal_collection_id,
+ id: PERSONAL_COLLECTION_ID,
name: "My personal collection",
- personal_owner_id: CURRENT_USER.id,
+ personal_owner_id: CURRENT_USER_ID,
can_write: true,
is_personal: true,
location: "/",
});
const PERSONAL_SUBCOLLECTION = createMockCollection({
- id: (CURRENT_USER.personal_collection_id as number) + 1,
+ id: PERSONAL_COLLECTION_ID + 1,
name: "Nested personal collection",
can_write: true,
is_personal: true,
@@ -102,21 +77,22 @@ const COLLECTIONS = [
];
interface SetupOpts {
- databases?: Database[];
collections: Collection[];
collectionItems?: CollectionItem[];
dashboard?: Dashboard;
+ canCreateQueries?: boolean;
+ canCreateNativeQueries?: boolean;
}
async function setup({
- databases = [],
collections,
collectionItems = [],
dashboard = createMockDashboard({
collection: ROOT_COLLECTION,
}),
+ canCreateQueries,
+ canCreateNativeQueries,
}: SetupOpts) {
- setupDatabasesEndpoints(databases);
setupCollectionsEndpoints({
collections,
});
@@ -134,7 +110,14 @@ async function setup({
</MockDashboardContext>,
{
storeInitialState: createMockState({
- currentUser: CURRENT_USER,
+ currentUser: createMockUser({
+ id: CURRENT_USER_ID,
+ personal_collection_id: PERSONAL_COLLECTION_ID,
+ permissions: createMockUserPermissions({
+ can_create_queries: canCreateQueries,
+ can_create_native_queries: canCreateNativeQueries,
+ }),
+ }),
dashboard: createMockDashboardState({
dashboards: {
[dashboard.id]: { ...dashboard, dashcards: [] },
@@ -430,7 +413,7 @@ describe("AddCardSideBar", () => {
it("displays the 'New Question' button if the user has data access", async () => {
await setup({
collections: COLLECTIONS,
- databases: [DB_WITH_ONLY_DATA_ACCESS],
+ canCreateQueries: true,
});
expect(await screen.findByText("New Question")).toBeInTheDocument();
expect(screen.queryByText("New SQL query")).not.toBeInTheDocument();
@@ -439,7 +422,8 @@ describe("AddCardSideBar", () => {
it("displays the 'New Question' and 'New SQL query' button if the user has native write access", async () => {
await setup({
collections: COLLECTIONS,
- databases: [DB_WITH_NATIVE_WRITE_ACCESS],
+ canCreateQueries: true,
+ canCreateNativeQueries: true,
});
expect(await screen.findByTestId("new-button-bar")).toBeInTheDocument();
expect(await screen.findByText("New Question")).toBeInTheDocument();
@@ -449,7 +433,8 @@ describe("AddCardSideBar", () => {
it("does not display any buttons if the user has no access to either", async () => {
await setup({
collections: COLLECTIONS,
- databases: [DB_WITH_NO_WRITE_ACCESS],
+ canCreateQueries: false,
+ canCreateNativeQueries: false,
});
expect(await screen.findByPlaceholderText(/Search/)).toBeInTheDocument();
expect(screen.queryByText("New Question")).not.toBeInTheDocument();
diff --git a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx
index b335e1a4676..236e4460bcc 100644
--- a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.unit.spec.tsx
@@ -5,6 +5,7 @@ import {
setupCollectionByIdEndpoint,
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
+ setupDatabasesEndpoints,
setupRecentViewsAndSelectionsEndpoints,
setupSearchEndpoints,
} from "__support__/server-mocks";
@@ -88,7 +89,6 @@ function setup({
}: SetupOpts) {
mockGetBoundingClientRect();
setupCollectionsEndpoints({ collections: COLLECTIONS });
-
setupCollectionByIdEndpoint({ collections: COLLECTIONS });
setupSearchEndpoints(searchResults);
setupCollectionItemsEndpoint({
@@ -104,6 +104,7 @@ function setup({
collectionItems: [],
});
setupRecentViewsAndSelectionsEndpoints([]);
+ setupDatabasesEndpoints([]);
fetchMock.get("path:/api/user/recipients", { data: [] });
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx b/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx
index a08a550699a..f407e60457e 100644
--- a/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx
+++ b/frontend/src/metabase/dashboard/components/Dashboard/components/Grid.tsx
@@ -1,11 +1,12 @@
import { useCallback, useMemo } from "react";
import { t } from "ttag";
-import { skipToken, useListDatabasesQuery } from "metabase/api";
import { useDashboardContext } from "metabase/dashboard/context";
import { useSelector } from "metabase/lib/redux";
-import { getHasDataAccess, getHasNativeWrite } from "metabase/selectors/data";
-import { getUser } from "metabase/selectors/user";
+import {
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+} from "metabase/selectors/user";
import { Loader, Stack, Text } from "metabase/ui";
import type { DashboardCard } from "metabase-types/api";
@@ -53,20 +54,9 @@ export const Grid = ({
* on `GET /api/database`. After the consolidation every dashboard uses the same component, so we probably
* missed this case.
*/
- const isLoggedIn = useSelector((state) => !!getUser(state));
- const { data: databasesResponse, isError } = useListDatabasesQuery(
- isLoggedIn ? undefined : skipToken,
- );
- const databases = useMemo(
- () => databasesResponse?.data ?? [],
- [databasesResponse],
- );
- const hasDataAccess = useMemo(() => getHasDataAccess(databases), [databases]);
- const hasNativeWrite = useMemo(
- () => getHasNativeWrite(databases),
- [databases],
- );
- const canCreateQuestions = !isError && (hasDataAccess || hasNativeWrite);
+ const hasDataAccess = useSelector(canUserCreateQueries);
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
+ const canCreateQuestions = hasDataAccess || hasNativeWrite;
const handleSetEditing = useCallback(() => {
if (!isEditing) {
diff --git a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx
index c267daa342c..3b47938c3ce 100644
--- a/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx
+++ b/frontend/src/metabase/dashboard/components/QuestionPicker/QuestionPicker.tsx
@@ -1,8 +1,7 @@
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { t } from "ttag";
import _ from "underscore";
-import { useListDatabasesQuery } from "metabase/api";
import { isPublicCollection } from "metabase/collections/utils";
import Breadcrumbs from "metabase/common/components/Breadcrumbs";
import Input from "metabase/common/components/Input";
@@ -17,7 +16,10 @@ import { getCrumbs } from "metabase/lib/collections";
import { SEARCH_DEBOUNCE_DURATION } from "metabase/lib/constants";
import { connect, useDispatch, useSelector } from "metabase/lib/redux";
import { PLUGIN_COLLECTIONS } from "metabase/plugins";
-import { getHasDataAccess, getHasNativeWrite } from "metabase/selectors/data";
+import {
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+} from "metabase/selectors/user";
import { Button, Flex, Icon, type IconProps } from "metabase/ui";
import type { Collection, CollectionId } from "metabase-types/api";
@@ -61,13 +63,8 @@ function QuestionPickerInner({
? allCollections.filter(isPublicCollection)
: allCollections;
- const { data } = useListDatabasesQuery();
- const databases = useMemo(() => data?.data ?? [], [data]);
- const hasDataAccess = useMemo(() => getHasDataAccess(databases), [databases]);
- const hasNativeWrite = useMemo(
- () => getHasNativeWrite(databases),
- [databases],
- );
+ const hasDataAccess = useSelector(canUserCreateQueries);
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
const { onNewQuestion } = useDashboardContext();
const onNewNativeQuestion = () => dispatch(addDashboardQuestion("native"));
diff --git a/frontend/src/metabase/dashboard/containers/CreateDashboardModal.unit.spec.tsx b/frontend/src/metabase/dashboard/containers/CreateDashboardModal.unit.spec.tsx
index 03ca2be4ca6..69aac395546 100644
--- a/frontend/src/metabase/dashboard/containers/CreateDashboardModal.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/containers/CreateDashboardModal.unit.spec.tsx
@@ -5,6 +5,7 @@ import { setupEnterpriseTest } from "__support__/enterprise";
import {
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
+ setupDatabasesEndpoints,
setupLibraryEndpoints,
setupRecentViewsAndSelectionsEndpoints,
} from "__support__/server-mocks";
@@ -54,6 +55,7 @@ function setup({ mockCreateDashboardResponse = true } = {}) {
mockGetBoundingClientRect();
setupRecentViewsAndSelectionsEndpoints([]);
setupLibraryEndpoints();
+ setupDatabasesEndpoints([]);
const onClose = jest.fn();
const settings = mockSettings({});
diff --git a/frontend/src/metabase/entities/collections/utils.ts b/frontend/src/metabase/entities/collections/utils.ts
index db56f51a826..b7687c0a036 100644
--- a/frontend/src/metabase/entities/collections/utils.ts
+++ b/frontend/src/metabase/entities/collections/utils.ts
@@ -45,7 +45,7 @@ export function getCollectionIcon(
case "root":
return { name: "repository" };
case "models":
- return { name: "model" };
+ return { name: "table" };
case "metrics":
return { name: "metric" };
}
diff --git a/frontend/src/metabase/lib/icon.ts b/frontend/src/metabase/lib/icon.ts
index df6c240ed13..de0e935b65e 100644
--- a/frontend/src/metabase/lib/icon.ts
+++ b/frontend/src/metabase/lib/icon.ts
@@ -85,7 +85,7 @@ export const getIconBase = (item: ObjectWithModel): IconData => {
case "root":
return { name: "repository" };
case "models":
- return { name: "model" };
+ return { name: "table" };
case "metrics":
return { name: "metric" };
}
diff --git a/frontend/src/metabase/lib/urls/admin.ts b/frontend/src/metabase/lib/urls/admin.ts
index 0b2680a65be..3b134e6563a 100644
--- a/frontend/src/metabase/lib/urls/admin.ts
+++ b/frontend/src/metabase/lib/urls/admin.ts
@@ -1,6 +1,8 @@
import type {
DatabaseId,
+ FieldId,
SchemaName,
+ SegmentId,
TableId,
UserId,
} from "metabase-types/api";
@@ -45,27 +47,66 @@ export function editDatabase(databaseId: DatabaseId) {
return `/admin/databases/${databaseId}/edit`;
}
-export function dataModel() {
- return `/admin/datamodel`;
+type DataModelParams = {
+ databaseId?: DatabaseId;
+ schemaName?: SchemaName | null;
+ tableId?: TableId;
+ fieldId?: FieldId;
+};
+
+export function dataModel({
+ databaseId,
+ schemaName,
+ tableId,
+ fieldId,
+}: DataModelParams = {}) {
+ const parts = ["/admin/datamodel"];
+
+ if (databaseId != null) {
+ parts.push("database", String(databaseId));
+
+ if (schemaName != null) {
+ const schemaId = `${databaseId}:${encodeURIComponent(schemaName)}`;
+ parts.push("schema", schemaId);
+
+ if (tableId != null) {
+ parts.push("table", String(tableId));
+
+ if (fieldId != null) {
+ parts.push("field", String(fieldId));
+ }
+ }
+ }
+ }
+
+ return parts.join("/");
+}
+
+export type DataModelSegmentsParams = {
+ tableId?: TableId;
+};
+
+export function dataModelSegments({ tableId }: DataModelSegmentsParams = {}) {
+ const params = new URLSearchParams();
+ if (tableId != null) {
+ params.set("table", String(tableId));
+ }
+
+ const baseUrl = "/admin/datamodel/segments";
+ const queryString = params.toString();
+ return queryString.length > 0 ? `${baseUrl}?${queryString}` : baseUrl;
}
-export function dataModelDatabase(databaseId: DatabaseId) {
- return `${dataModel()}/database/${databaseId}`;
+export function newDataModelSegment() {
+ return "/admin/datamodel/segment/create";
}
-export function dataModelSchema(
- databaseId: DatabaseId,
- schema: SchemaName | null,
-) {
- return `${dataModelDatabase(databaseId)}/schema/${databaseId}:${encodeURIComponent(schema ?? "")}`;
+export function dataModelSegment(segmentId: SegmentId) {
+ return `/admin/datamodel/segment/${segmentId}`;
}
-export function dataModelTable(
- databaseId: DatabaseId,
- schema: SchemaName | null,
- tableId: TableId,
-) {
- return `${dataModelSchema(databaseId, schema)}/table/${tableId}`;
+export function dataModelSegmentRevisions(segmentId: SegmentId) {
+ return `${dataModelSegment(segmentId)}/revisions`;
}
export function uploadsSettings() {
diff --git a/frontend/src/metabase/lib/urls/data-studio.ts b/frontend/src/metabase/lib/urls/data-studio.ts
index 80193e1a209..eac8f46b408 100644
--- a/frontend/src/metabase/lib/urls/data-studio.ts
+++ b/frontend/src/metabase/lib/urls/data-studio.ts
@@ -1,8 +1,12 @@
import type {
CardId,
CollectionId,
+ DatabaseId,
+ FieldId,
NativeQuerySnippetId,
+ SchemaName,
SegmentId,
+ TableId,
} from "metabase-types/api";
const ROOT_URL = "/data-studio";
@@ -20,18 +24,92 @@ function getQueryString({ collectionId }: OptionalParams) {
return queryString.length > 0 ? `?${queryString}` : "";
}
+export const DATA_STUDIO_TABLE_METADATA_TABS = ["field", "segments"] as const;
+export type DataStudioTableMetadataTab =
+ (typeof DATA_STUDIO_TABLE_METADATA_TABS)[number];
+
+export function isDataStudioTableMetadataTab(
+ tab: unknown,
+): tab is DataStudioTableMetadataTab {
+ return DATA_STUDIO_TABLE_METADATA_TABS.includes(
+ tab as DataStudioTableMetadataTab,
+ );
+}
+
+type DataStudioDataParams = {
+ databaseId?: DatabaseId;
+ schemaName?: SchemaName | null;
+ tableId?: TableId;
+ tab?: DataStudioTableMetadataTab;
+ fieldId?: FieldId;
+};
+
export function dataStudio() {
return ROOT_URL;
}
-export function dataStudioData() {
- return `${ROOT_URL}/data`;
+export function dataStudioData({
+ databaseId,
+ schemaName,
+ tableId,
+ tab,
+ fieldId,
+}: DataStudioDataParams = {}) {
+ const parts = [ROOT_URL, "data"];
+
+ if (databaseId != null) {
+ parts.push("database", String(databaseId));
+
+ if (schemaName != null) {
+ const schemaId = `${databaseId}:${encodeURIComponent(schemaName)}`;
+ parts.push("schema", schemaId);
+
+ if (tableId != null) {
+ parts.push("table", String(tableId));
+
+ if (tab != null) {
+ parts.push(tab);
+
+ if (fieldId != null && tab === "field") {
+ parts.push(String(fieldId));
+ }
+ }
+ }
+ }
+ }
+
+ return parts.join("/");
}
export function dataStudioModeling() {
return `${ROOT_URL}/modeling`;
}
+export function dataStudioTable(tableId: TableId) {
+ return `${dataStudioModeling()}/tables/${tableId}`;
+}
+
+export function dataStudioTableFields(tableId: TableId, fieldId?: FieldId) {
+ const baseUrl = `${dataStudioModeling()}/tables/${tableId}/fields`;
+ return fieldId != null ? `${baseUrl}/${fieldId}` : baseUrl;
+}
+
+export function dataStudioTableDependencies(tableId: TableId) {
+ return `${dataStudioTable(tableId)}/dependencies`;
+}
+
+export function dataStudioTableSegments(tableId: TableId) {
+ return `${dataStudioTable(tableId)}/segments`;
+}
+
+export function dataStudioSegment(segmentId: SegmentId) {
+ return `${dataStudioModeling()}/segments/${segmentId}`;
+}
+
+export function newDataStudioSegment(tableId: TableId) {
+ return `${dataStudioModeling()}/segments/new?tableId=${tableId}`;
+}
+
export type NewDataStudioQueryModelParams = {
collectionId?: CollectionId;
};
@@ -107,11 +185,3 @@ export function dataStudioSnippetDependencies(snippetId: NativeQuerySnippetId) {
export function newDataStudioSnippet() {
return `${dataStudioModeling()}/snippets/new`;
}
-
-export function dataStudioSegment(segmentId: SegmentId) {
- return `/admin/datamodel/segment/${segmentId}`;
-}
-
-export function dataStudioSegmentDependencies(segmentId: SegmentId) {
- return `${dataStudioSegment(segmentId)}/dependencies`;
-}
diff --git a/frontend/src/metabase/lib/urls/data-studio.unit.spec.ts b/frontend/src/metabase/lib/urls/data-studio.unit.spec.ts
new file mode 100644
index 00000000000..315e9a1065d
--- /dev/null
+++ b/frontend/src/metabase/lib/urls/data-studio.unit.spec.ts
@@ -0,0 +1,142 @@
+import {
+ dataStudio,
+ dataStudioData,
+ dataStudioModeling,
+ dataStudioSegment,
+ dataStudioTable,
+ dataStudioTableFields,
+ dataStudioTableSegments,
+ newDataStudioSegment,
+} from "./data-studio";
+
+describe("urls > data-studio", () => {
+ describe("dataStudio", () => {
+ it("should return root URL", () => {
+ expect(dataStudio()).toBe("/data-studio");
+ });
+ });
+
+ describe("dataStudioData", () => {
+ it("should return base data URL when no params", () => {
+ expect(dataStudioData()).toBe("/data-studio/data");
+ });
+
+ it("should include database", () => {
+ expect(dataStudioData({ databaseId: 1 })).toBe(
+ "/data-studio/data/database/1",
+ );
+ });
+
+ it("should include database and schema", () => {
+ expect(dataStudioData({ databaseId: 1, schemaName: "public" })).toBe(
+ "/data-studio/data/database/1/schema/1:public",
+ );
+ });
+
+ it("should encode schema name with special characters", () => {
+ expect(
+ dataStudioData({ databaseId: 1, schemaName: "My Schema/Test" }),
+ ).toBe("/data-studio/data/database/1/schema/1:My%20Schema%2FTest");
+ });
+
+ it("should include table", () => {
+ expect(
+ dataStudioData({ databaseId: 1, schemaName: "public", tableId: 42 }),
+ ).toBe("/data-studio/data/database/1/schema/1:public/table/42");
+ });
+
+ it("should generate URL with field tab", () => {
+ expect(
+ dataStudioData({
+ databaseId: 1,
+ schemaName: "public",
+ tableId: 42,
+ tab: "field",
+ }),
+ ).toBe("/data-studio/data/database/1/schema/1:public/table/42/field");
+ });
+
+ it("should generate URL with segments tab", () => {
+ expect(
+ dataStudioData({
+ databaseId: 1,
+ schemaName: "public",
+ tableId: 42,
+ tab: "segments",
+ }),
+ ).toBe("/data-studio/data/database/1/schema/1:public/table/42/segments");
+ });
+
+ it("should generate URL with field tab and fieldId", () => {
+ expect(
+ dataStudioData({
+ databaseId: 1,
+ schemaName: "public",
+ tableId: 42,
+ tab: "field",
+ fieldId: 100,
+ }),
+ ).toBe("/data-studio/data/database/1/schema/1:public/table/42/field/100");
+ });
+
+ it("should not include fieldId when tab is segments", () => {
+ expect(
+ dataStudioData({
+ databaseId: 1,
+ schemaName: "public",
+ tableId: 42,
+ tab: "segments",
+ fieldId: 100,
+ }),
+ ).toBe("/data-studio/data/database/1/schema/1:public/table/42/segments");
+ });
+ });
+
+ describe("dataStudioModeling", () => {
+ it("should return modeling URL", () => {
+ expect(dataStudioModeling()).toBe("/data-studio/modeling");
+ });
+ });
+
+ describe("dataStudioTable", () => {
+ it("should return table URL", () => {
+ expect(dataStudioTable(42)).toBe("/data-studio/modeling/tables/42");
+ });
+ });
+
+ describe("dataStudioTableFields", () => {
+ it("should return table fields URL without fieldId", () => {
+ expect(dataStudioTableFields(42)).toBe(
+ "/data-studio/modeling/tables/42/fields",
+ );
+ });
+
+ it("should return table fields URL with fieldId", () => {
+ expect(dataStudioTableFields(42, 100)).toBe(
+ "/data-studio/modeling/tables/42/fields/100",
+ );
+ });
+ });
+
+ describe("dataStudioTableSegments", () => {
+ it("should return table segments URL", () => {
+ expect(dataStudioTableSegments(42)).toBe(
+ "/data-studio/modeling/tables/42/segments",
+ );
+ });
+ });
+
+ describe("dataStudioSegment", () => {
+ it("should return segment edit URL", () => {
+ expect(dataStudioSegment(123)).toBe("/data-studio/modeling/segments/123");
+ });
+ });
+
+ describe("newDataStudioSegment", () => {
+ it("should return new segment URL with tableId", () => {
+ expect(newDataStudioSegment(42)).toBe(
+ "/data-studio/modeling/segments/new?tableId=42",
+ );
+ });
+ });
+});
diff --git a/frontend/src/metabase/metadata/components/FieldEmptyState/FieldEmptyState.tsx b/frontend/src/metabase/metadata/components/FieldEmptyState/FieldEmptyState.tsx
new file mode 100644
index 00000000000..0d10d1d234a
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/FieldEmptyState/FieldEmptyState.tsx
@@ -0,0 +1,29 @@
+import { t } from "ttag";
+
+import EmptyDashboardBot from "assets/img/dashboard-empty.svg";
+import EmptyState from "metabase/common/components/EmptyState";
+import { Box, rem } from "metabase/ui";
+
+type FieldEmptyStateProps = {
+ hasTable: boolean;
+};
+
+export function FieldEmptyState({ hasTable }: FieldEmptyStateProps) {
+ return (
+ <Box maw={rem(320)} p="xl">
+ <EmptyState
+ illustrationElement={<img src={EmptyDashboardBot} />}
+ title={
+ hasTable
+ ? t`Edit the table and fields`
+ : t`Start by selecting data to model`
+ }
+ message={
+ hasTable
+ ? t`Select a field to edit its name, description, formatting, and more.`
+ : t`Browse your databases to find the table you’d like to edit.`
+ }
+ />
+ </Box>
+ );
+}
diff --git a/frontend/src/metabase/metadata/components/FieldEmptyState/index.ts b/frontend/src/metabase/metadata/components/FieldEmptyState/index.ts
new file mode 100644
index 00000000000..8d439819384
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/FieldEmptyState/index.ts
@@ -0,0 +1 @@
+export * from "./FieldEmptyState";
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/BehaviorSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/BehaviorSection.tsx
similarity index 84%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/BehaviorSection.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/BehaviorSection.tsx
index fb7b69d9374..9e186ed1a26 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/BehaviorSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/BehaviorSection.tsx
@@ -2,20 +2,14 @@ import { memo } from "react";
import { t } from "ttag";
import { useGetDatabaseQuery, useUpdateFieldMutation } from "metabase/api";
-import {
- FieldValuesTypePicker,
- FieldVisibilityPicker,
- UnfoldJsonPicker,
-} from "metabase/metadata/components";
-import { TitledSection } from "metabase/metadata/components/TitledSection";
import { useMetadataToasts } from "metabase/metadata/hooks";
-import type { MetadataEventSource } from "metabase/metadata/pages/DataModelV1/types";
import {
canFieldUnfoldJson,
getRawTableFieldId,
isFieldJsonUnfolded,
} from "metabase/metadata/utils/field";
import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
import type {
DatabaseId,
Field,
@@ -23,17 +17,24 @@ import type {
FieldVisibilityType,
} from "metabase-types/api";
-import { trackMetadataChange } from "../../analytics";
+import { FieldValuesTypePicker } from "../../FieldValuesTypePicker";
+import { FieldVisibilityPicker } from "../../FieldVisibilityPicker";
+import { TitledSection } from "../../TitledSection";
+import { UnfoldJsonPicker } from "../../UnfoldJsonPicker";
import { RemappingPicker } from "./RemappingPicker";
-interface Props {
- databaseId: DatabaseId;
+type BehaviorSectionBaseProps = {
field: Field;
- eventSource: MetadataEventSource;
-}
+ databaseId: DatabaseId;
+ onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
+};
-const BehaviorSectionBase = ({ databaseId, field, eventSource }: Props) => {
+const BehaviorSectionBase = ({
+ field,
+ databaseId,
+ onTrackMetadataChange,
+}: BehaviorSectionBaseProps) => {
const id = getRawTableFieldId(field);
const { data: database } = useGetDatabaseQuery({
id: databaseId,
@@ -51,7 +52,7 @@ const BehaviorSectionBase = ({ databaseId, field, eventSource }: Props) => {
visibility_type: visibilityType,
});
- trackMetadataChange("visibility_change", eventSource);
+ onTrackMetadataChange("visibility_change");
if (error) {
sendErrorToast(t`Failed to update visibility of ${field.display_name}`);
@@ -75,7 +76,7 @@ const BehaviorSectionBase = ({ databaseId, field, eventSource }: Props) => {
has_field_values: hasFieldValues,
});
- trackMetadataChange("filtering_change", eventSource);
+ onTrackMetadataChange("filtering_change");
if (error) {
sendErrorToast(t`Failed to update filtering of ${field.display_name}`);
@@ -108,7 +109,7 @@ const BehaviorSectionBase = ({ databaseId, field, eventSource }: Props) => {
: t`Failed to disable JSON unfolding for ${field.display_name}`,
);
} else {
- trackMetadataChange("json_unfolding", eventSource);
+ onTrackMetadataChange("json_unfolding");
sendSuccessToast(
jsonUnfolding
@@ -147,7 +148,7 @@ const BehaviorSectionBase = ({ databaseId, field, eventSource }: Props) => {
description={t`Choose to show the original value from the database, or have this field display associated or custom information.`}
field={field}
label={t`Display values`}
- eventSource={eventSource}
+ onTrackMetadataChange={onTrackMetadataChange}
/>
)}
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.module.css b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.module.css
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.module.css
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.module.css
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.unit.spec.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.unit.spec.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/CustomMappingModal.unit.spec.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/index.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/index.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/types.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/types.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/types.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/types.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/utils.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/utils.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/utils.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/CustomMappingModal/utils.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.module.css b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.module.css
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.module.css
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.module.css
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.unit.spec.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.unit.spec.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/DisplayValuesPicker.unit.spec.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/index.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/index.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/types.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/types.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/types.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/DisplayValuesPicker/types.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/NamingTip.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/NamingTip/NamingTip.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/NamingTip.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/NamingTip/NamingTip.tsx
diff --git a/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/NamingTip/index.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/NamingTip/index.ts
new file mode 100644
index 00000000000..b4791b307d2
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/NamingTip/index.ts
@@ -0,0 +1 @@
+export * from "./NamingTip";
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
similarity index 96%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
index 2e07a3d0cac..567560e38e5 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/RemappingPicker.tsx
@@ -11,7 +11,6 @@ import {
useUpdateFieldValuesMutation,
} from "metabase/api";
import { useMetadataToasts } from "metabase/metadata/hooks";
-import type { MetadataEventSource } from "metabase/metadata/pages/DataModelV1/types";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";
import { FieldDataSelector } from "metabase/query_builder/components/DataSelector";
@@ -25,10 +24,9 @@ import {
Stack,
rem,
} from "metabase/ui";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
import type { Database, Field, FieldId } from "metabase-types/api";
-import { trackMetadataChange } from "../../../analytics";
-
import {
type ChangeOptions,
CustomMappingModal,
@@ -49,19 +47,19 @@ import {
is403Error,
} from "./utils";
-interface Props extends Omit<SelectProps, "data" | "value" | "onChange"> {
+type RemappingPicker = Omit<SelectProps, "data" | "value" | "onChange"> & {
database: Database;
field: Field;
- eventSource: MetadataEventSource;
-}
+ onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
+};
export const RemappingPicker = ({
- comboboxProps,
database,
field,
- eventSource,
+ comboboxProps,
+ onTrackMetadataChange,
...props
-}: Props) => {
+}: RemappingPicker) => {
const { sendErrorToast, sendSuccessToast, sendUndoToast } =
useMetadataToasts();
const [hasChanged, setHasChanged] = useState(false);
@@ -134,7 +132,7 @@ export const RemappingPicker = ({
t`Failed to update display values of ${field.display_name}`,
);
} else {
- trackMetadataChange("display_values", eventSource);
+ onTrackMetadataChange("display_values");
sendSuccessToast(
t`Display values of ${field.display_name} updated`,
async () => {
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/illustrations/sub-input.svg b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/illustrations/sub-input.svg
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/illustrations/sub-input.svg
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/illustrations/sub-input.svg
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/index.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/index.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/utils.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/utils.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/RemappingPicker/utils.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/RemappingPicker/utils.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/index.ts b/frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/BehaviorSection/index.ts
rename to frontend/src/metabase/metadata/components/FieldSection/BehaviorSection/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/DataSection.module.css b/frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.module.css
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/DataSection.module.css
rename to frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.module.css
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/DataSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.tsx
similarity index 90%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/DataSection.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.tsx
index 8f2208e5bea..a29fd94a99f 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/DataSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/DataSection/DataSection.tsx
@@ -2,33 +2,33 @@ import { type ChangeEvent, memo, useEffect, useState } from "react";
import { t } from "ttag";
import { useUpdateFieldMutation } from "metabase/api";
-import {
- CoercionStrategyPicker,
- LabeledValue,
- TitledSection,
-} from "metabase/metadata/components";
import { useMetadataToasts } from "metabase/metadata/hooks";
-import type { MetadataEventSource } from "metabase/metadata/pages/DataModelV1/types";
import {
canCoerceFieldType,
getFieldRawName,
getRawTableFieldId,
} from "metabase/metadata/utils/field";
import { Box, Flex, Group, Stack, Switch, rem } from "metabase/ui";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
import type { Field } from "metabase-types/api";
-import { trackMetadataChange } from "../../analytics";
+import { CoercionStrategyPicker } from "../../CoercionStrategyPicker";
+import { LabeledValue } from "../../LabeledValue";
+import { TitledSection } from "../../TitledSection";
import S from "./DataSection.module.css";
import SubInputFollowIllustration from "./illustrations/sub-input-follow.svg?component";
import SubInputIllustration from "./illustrations/sub-input.svg?component";
-interface Props {
+type DataSectionBaseProps = {
field: Field;
- eventSource: MetadataEventSource;
-}
+ onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
+};
-const DataSectionBase = ({ field, eventSource }: Props) => {
+const DataSectionBase = ({
+ field,
+ onTrackMetadataChange,
+}: DataSectionBaseProps) => {
const id = getRawTableFieldId(field);
const [isCasting, setIsCasting] = useState(
field ? field.coercion_strategy != null : false,
@@ -92,7 +92,7 @@ const DataSectionBase = ({ field, eventSource }: Props) => {
: t`Failed to update casting for ${field.display_name}`,
);
} else {
- trackMetadataChange("type_casting", eventSource);
+ onTrackMetadataChange("type_casting");
sendSuccessToast(
field.coercion_strategy == null
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/illustrations/sub-input-follow.svg b/frontend/src/metabase/metadata/components/FieldSection/DataSection/illustrations/sub-input-follow.svg
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/illustrations/sub-input-follow.svg
rename to frontend/src/metabase/metadata/components/FieldSection/DataSection/illustrations/sub-input-follow.svg
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/illustrations/sub-input.svg b/frontend/src/metabase/metadata/components/FieldSection/DataSection/illustrations/sub-input.svg
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/illustrations/sub-input.svg
rename to frontend/src/metabase/metadata/components/FieldSection/DataSection/illustrations/sub-input.svg
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/index.ts b/frontend/src/metabase/metadata/components/FieldSection/DataSection/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/DataSection/index.ts
rename to frontend/src/metabase/metadata/components/FieldSection/DataSection/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/FieldSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.tsx
similarity index 80%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/FieldSection.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/FieldSection.tsx
index 51dc34b4356..d9e810d419b 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldSection/FieldSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/FieldSection.tsx
@@ -3,41 +3,41 @@ import { t } from "ttag";
import { useUpdateFieldMutation } from "metabase/api";
import { getColumnIcon } from "metabase/common/utils/columns";
-import { NameDescriptionInput } from "metabase/metadata/components";
import { useMetadataToasts } from "metabase/metadata/hooks";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import { Group, Stack, Text } from "metabase/ui";
import * as Lib from "metabase-lib";
-import type { DatabaseId, Field, Table } from "metabase-types/api";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
+import type { Field, FieldId, Table } from "metabase-types/api";
-import type { MetadataEventSource } from "../../DataModelV1/types";
+import { NameDescriptionInput } from "../NameDescriptionInput";
import { ResponsiveButton } from "../ResponsiveButton";
import { BehaviorSection } from "./BehaviorSection";
import { DataSection } from "./DataSection";
-import { FormattingSection } from "./FormattingSection";
-import { MetadataSection } from "./MetadataSection";
+import { FormattingSection } from "./FormattingSection/FormattingSection";
+import { MetadataSection } from "./MetadataSection/MetadataSection";
import { useResponsiveButtons } from "./hooks";
-interface Props {
- databaseId: DatabaseId;
+type FieldSectionBaseProps = {
field: Field;
table: Table;
parent?: Field;
- eventSource: MetadataEventSource;
+ getFieldHref: (fieldId: FieldId) => string;
onFieldValuesClick: () => void;
onPreviewClick: () => void;
-}
+ onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
+};
const FieldSectionBase = ({
- databaseId,
field,
parent,
table,
- eventSource,
+ getFieldHref,
onFieldValuesClick,
onPreviewClick,
-}: Props) => {
+ onTrackMetadataChange,
+}: FieldSectionBaseProps) => {
const id = getRawTableFieldId(field);
const [updateField] = useUpdateFieldMutation();
const { sendErrorToast, sendSuccessToast, sendUndoToast } =
@@ -140,19 +140,25 @@ const FieldSectionBase = ({
</Stack>
<Stack gap="xl" px="lg">
- <DataSection field={field} eventSource={eventSource} />
+ <DataSection
+ field={field}
+ onTrackMetadataChange={onTrackMetadataChange}
+ />
<MetadataSection
- databaseId={databaseId}
field={field}
table={table}
- eventSource={eventSource}
+ getFieldHref={getFieldHref}
+ onTrackMetadataChange={onTrackMetadataChange}
/>
<BehaviorSection
- databaseId={databaseId}
field={field}
- eventSource={eventSource}
+ databaseId={table.db_id}
+ onTrackMetadataChange={onTrackMetadataChange}
+ />
+ <FormattingSection
+ field={field}
+ onTrackMetadataChange={onTrackMetadataChange}
/>
- <FormattingSection field={field} eventSource={eventSource} />
</Stack>
</Stack>
);
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/FormattingSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/FormattingSection.tsx
similarity index 84%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/FormattingSection.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/FormattingSection/FormattingSection.tsx
index ade581638f7..430dba16c9b 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldSection/FormattingSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/FormattingSection.tsx
@@ -2,26 +2,25 @@ import { memo, useMemo } from "react";
import { t } from "ttag";
import { useUpdateFieldMutation } from "metabase/api";
-import { TitledSection } from "metabase/metadata/components/TitledSection";
import { useMetadataToasts } from "metabase/metadata/hooks";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import ColumnSettings from "metabase/visualizations/components/ColumnSettings";
import { getGlobalSettingsForColumn } from "metabase/visualizations/lib/settings/column";
import { isCurrency } from "metabase-lib/v1/types/utils/isa";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
import type {
Field,
FieldFormattingSettings as FieldSettings,
} from "metabase-types/api";
-import type { MetadataEventSource } from "../../DataModelV1/types";
-import { trackMetadataChange } from "../analytics";
+import { TitledSection } from "../../TitledSection";
interface Props {
field: Field;
- eventSource: MetadataEventSource;
+ onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
}
-const FormattingSectionBase = ({ field, eventSource }: Props) => {
+const FormattingSectionBase = ({ field, onTrackMetadataChange }: Props) => {
const id = getRawTableFieldId(field);
const [updateField] = useUpdateFieldMutation();
const { sendErrorToast, sendSuccessToast, sendUndoToast } =
@@ -39,7 +38,7 @@ const FormattingSectionBase = ({ field, eventSource }: Props) => {
if (error) {
sendErrorToast(t`Failed to update formatting of ${field.display_name}`);
} else {
- trackMetadataChange("formatting", eventSource);
+ onTrackMetadataChange("formatting");
sendSuccessToast(
t`Formatting of ${field.display_name} updated`,
diff --git a/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/index.ts b/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/index.ts
new file mode 100644
index 00000000000..6e85c85efce
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/FieldSection/FormattingSection/index.ts
@@ -0,0 +1 @@
+export * from "./FormattingSection";
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/MetadataSection.tsx b/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/MetadataSection.tsx
similarity index 68%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/MetadataSection.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/MetadataSection/MetadataSection.tsx
index 5def9859ca1..63606c32a25 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldSection/MetadataSection.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/MetadataSection.tsx
@@ -1,50 +1,46 @@
-import { memo, useContext, useMemo } from "react";
+import { memo, useMemo } from "react";
import { t } from "ttag";
import {
useListDatabaseIdFieldsQuery,
useUpdateFieldMutation,
} from "metabase/api";
-import { SemanticTypeAndTargetPicker } from "metabase/metadata/components";
-import { TitledSection } from "metabase/metadata/components/TitledSection";
import { useMetadataToasts } from "metabase/metadata/hooks";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import { PLUGIN_FEATURE_LEVEL_PERMISSIONS } from "metabase/plugins";
-import type { DatabaseId, Field, Table } from "metabase-types/api";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
+import type { Field, FieldId, Table } from "metabase-types/api";
-import type { MetadataEventSource } from "../../DataModelV1/types";
-import { DataModelContext } from "../DataModelContext";
-import { trackMetadataChange } from "../analytics";
-
-import { getSemanticTypeError } from "./utils";
+import { SemanticTypeAndTargetPicker } from "../../SemanticTypeAndTargetPicker";
+import { TitledSection } from "../../TitledSection";
+import { getSemanticTypeError } from "../utils";
type Patch = Partial<
Pick<Field, "settings" | "semantic_type" | "fk_target_field_id">
>;
-interface Props {
- databaseId: DatabaseId;
+type MetadataSectionBaseProps = {
field: Field;
table: Table;
- eventSource: MetadataEventSource;
-}
+ getFieldHref: (fieldId: FieldId) => string;
+ onTrackMetadataChange: (detail: MetadataEditEventDetail) => void;
+};
const MetadataSectionBase = ({
- databaseId,
field,
table,
- eventSource,
-}: Props) => {
+ getFieldHref,
+ onTrackMetadataChange,
+}: MetadataSectionBaseProps) => {
const id = getRawTableFieldId(field);
const { data: idFields = [] } = useListDatabaseIdFieldsQuery({
- id: databaseId,
+ id: table.db_id,
...PLUGIN_FEATURE_LEVEL_PERMISSIONS.dataModelQueryProps,
});
const [updateField] = useUpdateFieldMutation();
- const { baseUrl } = useContext(DataModelContext);
const semanticTypeError = useMemo(() => {
- return getSemanticTypeError(table, field, baseUrl);
- }, [table, field, baseUrl]);
+ return getSemanticTypeError(table, field, getFieldHref);
+ }, [table, field, getFieldHref]);
const { sendErrorToast, sendSuccessToast, sendUndoToast } =
useMetadataToasts();
@@ -56,7 +52,7 @@ const MetadataSectionBase = ({
t`Failed to update semantic type of ${field.display_name}`,
);
} else {
- trackMetadataChange("semantic_type_change", eventSource);
+ onTrackMetadataChange("semantic_type_change");
sendSuccessToast(
t`Semantic type of ${field.display_name} updated`,
diff --git a/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/index.ts b/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/index.ts
new file mode 100644
index 00000000000..bb37ba4269a
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/FieldSection/MetadataSection/index.ts
@@ -0,0 +1 @@
+export * from "./MetadataSection";
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/hooks.ts b/frontend/src/metabase/metadata/components/FieldSection/hooks.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/hooks.ts
rename to frontend/src/metabase/metadata/components/FieldSection/hooks.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/index.ts b/frontend/src/metabase/metadata/components/FieldSection/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/index.ts
rename to frontend/src/metabase/metadata/components/FieldSection/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldSection/utils.tsx b/frontend/src/metabase/metadata/components/FieldSection/utils.tsx
similarity index 82%
rename from frontend/src/metabase/metadata/pages/shared/FieldSection/utils.tsx
rename to frontend/src/metabase/metadata/components/FieldSection/utils.tsx
index c9e69b233a8..6394de78a62 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldSection/utils.tsx
+++ b/frontend/src/metabase/metadata/components/FieldSection/utils.tsx
@@ -5,14 +5,12 @@ import _ from "underscore";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import { isEntityName } from "metabase-lib/v1/types/utils/isa";
-import type { Field, Table } from "metabase-types/api";
-
-import { getUrl } from "../utils";
+import type { Field, FieldId, Table } from "metabase-types/api";
export function getSemanticTypeError(
table: Table,
field: Field,
- baseUrl: string,
+ getFieldHref: (fieldId: FieldId) => string,
): ReactNode | undefined {
if (!isEntityName(field)) {
return undefined;
@@ -38,12 +36,7 @@ export function getSemanticTypeError(
{entityNameFields.map((field, index) => {
const parentName = field.nfc_path?.[0] ?? "";
const parentField = fieldsByName[parentName];
- const href = getUrl(baseUrl, {
- databaseId: table.db_id,
- schemaName: table.schema,
- tableId: table.id,
- fieldId: getRawTableFieldId(field),
- });
+ const href = getFieldHref(getRawTableFieldId(field));
return (
<Fragment key={index}>
diff --git a/frontend/src/metabase/metadata/pages/shared/FieldValuesModal.tsx b/frontend/src/metabase/metadata/components/FieldValuesModal/FieldValuesModal.tsx
similarity index 50%
rename from frontend/src/metabase/metadata/pages/shared/FieldValuesModal.tsx
rename to frontend/src/metabase/metadata/components/FieldValuesModal/FieldValuesModal.tsx
index 03dcfc047de..15181529cd0 100644
--- a/frontend/src/metabase/metadata/pages/shared/FieldValuesModal.tsx
+++ b/frontend/src/metabase/metadata/components/FieldValuesModal/FieldValuesModal.tsx
@@ -1,19 +1,26 @@
import { t } from "ttag";
-import {
- DiscardFieldValuesButton,
- RescanFieldButton,
-} from "metabase/metadata/components";
+import { useSelector } from "metabase/lib/redux";
+import { getApplicationName } from "metabase/selectors/whitelabel";
import { Modal, Stack, Text, rem } from "metabase/ui";
import type { FieldId } from "metabase-types/api";
-interface Props {
+import { DiscardFieldValuesButton } from "../DiscardFieldValuesButton";
+import { RescanFieldButton } from "../RescanFieldButton";
+
+type FieldValuesModalProps = {
fieldId: FieldId;
isOpen: boolean;
onClose: () => void;
-}
+};
+
+export const FieldValuesModal = ({
+ fieldId,
+ isOpen,
+ onClose,
+}: FieldValuesModalProps) => {
+ const applicationName = useSelector(getApplicationName);
-export const FieldValuesModal = ({ fieldId, isOpen, onClose }: Props) => {
return (
<Modal
opened={isOpen}
@@ -24,8 +31,7 @@ export const FieldValuesModal = ({ fieldId, isOpen, onClose }: Props) => {
>
<Stack gap="md" pt="sm">
<Text c="text-secondary" size="sm">
- {/* eslint-disable-next-line no-literal-metabase-strings -- Admin settings */}
- {t`Metabase can scan the values in this table to enable checkbox filters in dashboards and questions.`}
+ {t`${applicationName} can scan the values in this table to enable checkbox filters in dashboards and questions.`}
</Text>
<RescanFieldButton fieldId={fieldId} />
diff --git a/frontend/src/metabase/metadata/components/FieldValuesModal/index.ts b/frontend/src/metabase/metadata/components/FieldValuesModal/index.ts
new file mode 100644
index 00000000000..77de4f58633
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/FieldValuesModal/index.ts
@@ -0,0 +1 @@
+export * from "./FieldValuesModal";
diff --git a/frontend/src/metabase/metadata/pages/shared/NoDatabasesEmptyState.tsx b/frontend/src/metabase/metadata/components/NoDatabasesEmptyState/NoDatabasesEmptyState.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/NoDatabasesEmptyState.tsx
rename to frontend/src/metabase/metadata/components/NoDatabasesEmptyState/NoDatabasesEmptyState.tsx
diff --git a/frontend/src/metabase/metadata/components/NoDatabasesEmptyState/index.ts b/frontend/src/metabase/metadata/components/NoDatabasesEmptyState/index.ts
new file mode 100644
index 00000000000..bb0e66463ac
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/NoDatabasesEmptyState/index.ts
@@ -0,0 +1 @@
+export * from "./NoDatabasesEmptyState";
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/EmptyStateBlock.tsx b/frontend/src/metabase/metadata/components/PreviewSection/EmptyStateBlock.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/EmptyStateBlock.tsx
rename to frontend/src/metabase/metadata/components/PreviewSection/EmptyStateBlock.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/Error/Error.module.css b/frontend/src/metabase/metadata/components/PreviewSection/Error/Error.module.css
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/Error/Error.module.css
rename to frontend/src/metabase/metadata/components/PreviewSection/Error/Error.module.css
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/Error/Error.tsx b/frontend/src/metabase/metadata/components/PreviewSection/Error/Error.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/Error/Error.tsx
rename to frontend/src/metabase/metadata/components/PreviewSection/Error/Error.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/Error/index.ts b/frontend/src/metabase/metadata/components/PreviewSection/Error/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/Error/index.ts
rename to frontend/src/metabase/metadata/components/PreviewSection/Error/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/FilteringPreview.tsx b/frontend/src/metabase/metadata/components/PreviewSection/FilteringPreview.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/FilteringPreview.tsx
rename to frontend/src/metabase/metadata/components/PreviewSection/FilteringPreview.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/ObjectDetailPreview.tsx b/frontend/src/metabase/metadata/components/PreviewSection/ObjectDetailPreview.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/ObjectDetailPreview.tsx
rename to frontend/src/metabase/metadata/components/PreviewSection/ObjectDetailPreview.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.module.css b/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.module.css
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.module.css
rename to frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.module.css
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.tsx b/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.tsx
similarity index 90%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.tsx
rename to frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.tsx
index c87d986ca14..413b686bd7d 100644
--- a/frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.tsx
+++ b/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.tsx
@@ -1,6 +1,7 @@
import { memo, useMemo } from "react";
import { t } from "ttag";
+import { getRawTableFieldId } from "metabase/metadata/utils/field";
import {
ActionIcon,
Box,
@@ -12,13 +13,7 @@ import {
Text,
} from "metabase/ui";
import { isPK } from "metabase-lib/v1/types/utils/isa";
-import type {
- DatabaseId,
- Field,
- FieldId,
- Table,
- TableId,
-} from "metabase-types/api";
+import type { Field, Table } from "metabase-types/api";
import { FilteringPreview } from "./FilteringPreview";
import { ObjectDetailPreview } from "./ObjectDetailPreview";
@@ -27,29 +22,26 @@ import { TablePreview } from "./TablePreview";
import type { PreviewType } from "./types";
import { getPreviewTypeData } from "./utils";
-interface Props {
+type PreviewSectionBaseProps = {
className?: string;
- databaseId: DatabaseId;
field: Field;
- fieldId: FieldId;
- previewType: PreviewType;
table: Table;
- tableId: TableId;
- onClose: () => void;
+ previewType: PreviewType;
onPreviewTypeChange: (value: PreviewType) => void;
-}
+ onClose: () => void;
+};
const PreviewSectionBase = ({
className,
- databaseId,
field,
- fieldId,
- previewType,
table,
- tableId,
- onClose,
+ previewType,
onPreviewTypeChange,
-}: Props) => {
+ onClose,
+}: PreviewSectionBaseProps) => {
+ const fieldId = getRawTableFieldId(field);
+ const tableId = table.id;
+ const databaseId = table.db_id;
const data = useMemo(() => getPreviewTypeData(), []);
const pkFields = useMemo(
() => table.fields?.filter((field) => isPK(field)) ?? [],
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.unit.spec.tsx b/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.unit.spec.tsx
similarity index 91%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.unit.spec.tsx
rename to frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.unit.spec.tsx
index 9d0fe990563..070b841a20d 100644
--- a/frontend/src/metabase/metadata/pages/shared/PreviewSection/PreviewSection.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/components/PreviewSection/PreviewSection.unit.spec.tsx
@@ -3,7 +3,6 @@ import { useState } from "react";
import { setupCardDataset } from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
-import { getRawTableFieldId } from "metabase/metadata/utils/field";
import registerVisualizations from "metabase/visualizations/register";
import {
createOrdersTable,
@@ -32,14 +31,11 @@ function TestComponent({
return (
<PreviewSection
- databaseId={table.db_id}
field={field}
- fieldId={getRawTableFieldId(field)}
- previewType={previewType}
table={table}
- tableId={field.table_id}
- onClose={jest.fn()}
+ previewType={previewType}
onPreviewTypeChange={handlePreviewTypeChange}
+ onClose={jest.fn()}
/>
);
}
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/TablePreview.tsx b/frontend/src/metabase/metadata/components/PreviewSection/TablePreview.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/TablePreview.tsx
rename to frontend/src/metabase/metadata/components/PreviewSection/TablePreview.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/index.ts b/frontend/src/metabase/metadata/components/PreviewSection/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/index.ts
rename to frontend/src/metabase/metadata/components/PreviewSection/index.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/types.ts b/frontend/src/metabase/metadata/components/PreviewSection/types.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/types.ts
rename to frontend/src/metabase/metadata/components/PreviewSection/types.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/PreviewSection/utils.ts b/frontend/src/metabase/metadata/components/PreviewSection/utils.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/PreviewSection/utils.ts
rename to frontend/src/metabase/metadata/components/PreviewSection/utils.ts
diff --git a/frontend/src/metabase/metadata/pages/shared/ResponsiveButton.tsx b/frontend/src/metabase/metadata/components/ResponsiveButton/ResponsiveButton.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/ResponsiveButton.tsx
rename to frontend/src/metabase/metadata/components/ResponsiveButton/ResponsiveButton.tsx
diff --git a/frontend/src/metabase/metadata/components/ResponsiveButton/index.ts b/frontend/src/metabase/metadata/components/ResponsiveButton/index.ts
new file mode 100644
index 00000000000..cd074bba03a
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/ResponsiveButton/index.ts
@@ -0,0 +1 @@
+export * from "./ResponsiveButton";
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/SyncOptionsModal.tsx b/frontend/src/metabase/metadata/components/SyncOptionsModal/SyncOptionsModal.tsx
similarity index 80%
rename from frontend/src/metabase/metadata/pages/DataModelV1/components/SyncOptionsModal.tsx
rename to frontend/src/metabase/metadata/components/SyncOptionsModal/SyncOptionsModal.tsx
index 2177178fc46..1be034097cc 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/SyncOptionsModal.tsx
+++ b/frontend/src/metabase/metadata/components/SyncOptionsModal/SyncOptionsModal.tsx
@@ -1,20 +1,23 @@
import { t } from "ttag";
-import {
- DiscardTableFieldValuesButton,
- RescanTableFieldsButton,
- SyncTableSchemaButton,
-} from "metabase/metadata/components";
import { Modal, Stack, Text, rem } from "metabase/ui";
import type { TableId } from "metabase-types/api";
-interface Props {
+import { DiscardTableFieldValuesButton } from "../DiscardTableFieldValuesButton";
+import { RescanTableFieldsButton } from "../RescanTableFieldsButton";
+import { SyncTableSchemaButton } from "../SyncTableSchemaButton";
+
+type SyncOptionsModalProps = {
isOpen: boolean;
tableId: TableId;
onClose: () => void;
-}
+};
-export const SyncOptionsModal = ({ isOpen, tableId, onClose }: Props) => {
+export const SyncOptionsModal = ({
+ isOpen,
+ tableId,
+ onClose,
+}: SyncOptionsModalProps) => {
return (
<Modal
opened={isOpen}
diff --git a/frontend/src/metabase/metadata/components/SyncOptionsModal/index.ts b/frontend/src/metabase/metadata/components/SyncOptionsModal/index.ts
new file mode 100644
index 00000000000..103a059c002
--- /dev/null
+++ b/frontend/src/metabase/metadata/components/SyncOptionsModal/index.ts
@@ -0,0 +1 @@
+export * from "./SyncOptionsModal";
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableFieldList/TableFieldList.tsx b/frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.tsx
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableFieldList/TableFieldList.tsx
rename to frontend/src/metabase/metadata/components/TableFieldList/TableFieldList.tsx
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableFieldList/index.ts b/frontend/src/metabase/metadata/components/TableFieldList/index.ts
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableFieldList/index.ts
rename to frontend/src/metabase/metadata/components/TableFieldList/index.ts
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.module.css b/frontend/src/metabase/metadata/components/TableSection/TableSection.module.css
similarity index 100%
rename from frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.module.css
rename to frontend/src/metabase/metadata/components/TableSection/TableSection.module.css
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.tsx b/frontend/src/metabase/metadata/components/TableSection/TableSection.tsx
similarity index 77%
rename from frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.tsx
rename to frontend/src/metabase/metadata/components/TableSection/TableSection.tsx
index a8d22545406..33f15a116f7 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.tsx
+++ b/frontend/src/metabase/metadata/components/TableSection/TableSection.tsx
@@ -8,13 +8,7 @@ import {
} from "metabase/api";
import EmptyState from "metabase/common/components/EmptyState";
import * as Urls from "metabase/lib/urls";
-import {
- FieldOrderPicker,
- NameDescriptionInput,
- SortableFieldList,
-} from "metabase/metadata/components";
import { useMetadataToasts } from "metabase/metadata/hooks";
-import { ResponsiveButton } from "metabase/metadata/pages/shared/ResponsiveButton";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import {
ActionIcon,
@@ -27,21 +21,30 @@ import {
} from "metabase/ui";
import type { FieldId, Table, TableFieldOrder } from "metabase-types/api";
-import type { RouteParams } from "../../types";
-import { getUrl, parseRouteParams } from "../../utils";
+import { FieldOrderPicker } from "../FieldOrderPicker";
+import { NameDescriptionInput } from "../NameDescriptionInput";
+import { ResponsiveButton } from "../ResponsiveButton";
+import { TableFieldList } from "../TableFieldList";
+import { TableSortableFieldList } from "../TableSortableFieldList";
-import { FieldList } from "./FieldList";
import S from "./TableSection.module.css";
import { useResponsiveButtons } from "./hooks";
-interface Props {
- params: RouteParams;
+type TableSectionBaseProps = {
table: Table;
+ fieldId: FieldId | undefined;
+ withName?: boolean;
+ getFieldHref: (fieldId: FieldId) => string;
onSyncOptionsClick: () => void;
-}
+};
-const TableSectionBase = ({ params, table, onSyncOptionsClick }: Props) => {
- const { fieldId, ...parsedParams } = parseRouteParams(params);
+const TableSectionBase = ({
+ table,
+ fieldId,
+ withName,
+ getFieldHref,
+ onSyncOptionsClick,
+}: TableSectionBaseProps) => {
const [updateTable] = useUpdateTableMutation();
const [updateTableSorting, { isLoading: isUpdatingSorting }] =
useUpdateTableMutation();
@@ -156,31 +159,33 @@ const TableSectionBase = ({ params, table, onSyncOptionsClick }: Props) => {
px="lg"
top={0}
>
- <NameDescriptionInput
- description={table.description ?? ""}
- descriptionPlaceholder={t`Give this table a description`}
- name={table.display_name}
- nameIcon="table2"
- nameMaxLength={254}
- namePlaceholder={t`Give this table a name`}
- nameRightSection={
- <Tooltip label={t`Go to this table`} position="top">
- <ActionIcon
- component={Link}
- to={Urls.queryBuilderTable(table.id, table.db_id)}
- variant="subtle"
- color="text-light"
- size="sm"
- mr="sm"
- aria-label={t`Go to this table`}
- >
- <Icon name="external" size={16} />
- </ActionIcon>
- </Tooltip>
- }
- onNameChange={handleNameChange}
- onDescriptionChange={handleDescriptionChange}
- />
+ {withName && (
+ <NameDescriptionInput
+ description={table.description ?? ""}
+ descriptionPlaceholder={t`Give this table a description`}
+ name={table.display_name}
+ nameIcon="table2"
+ nameMaxLength={254}
+ namePlaceholder={t`Give this table a name`}
+ nameRightSection={
+ <Tooltip label={t`Go to this table`} position="top">
+ <ActionIcon
+ component={Link}
+ to={Urls.queryBuilderTable(table.id, table.db_id)}
+ variant="subtle"
+ color="text-light"
+ size="sm"
+ mr="sm"
+ aria-label={t`Go to this table`}
+ >
+ <Icon name="external" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ }
+ onNameChange={handleNameChange}
+ onDescriptionChange={handleDescriptionChange}
+ />
+ )}
<Group
align="center"
@@ -237,7 +242,9 @@ const TableSectionBase = ({ params, table, onSyncOptionsClick }: Props) => {
showIconWithLabel={false}
onClick={() => setIsSorting(false)}
onRequestWidth={setDoneButtonWidth}
- >{t`Done`}</ResponsiveButton>
+ >
+ {t`Done`}
+ </ResponsiveButton>
)}
</Group>
</Group>
@@ -248,19 +255,18 @@ const TableSectionBase = ({ params, table, onSyncOptionsClick }: Props) => {
{!hasFields && <EmptyState message={t`This table has no fields`} />}
{isSorting && hasFields && (
- <SortableFieldList
- activeFieldKey={fieldId}
- fields={table.fields ?? []}
- getFieldKey={getRawTableFieldId}
+ <TableSortableFieldList
+ table={table}
+ activeFieldId={fieldId}
onChange={handleCustomFieldOrderChange}
/>
)}
{!isSorting && hasFields && (
- <FieldList
- activeFieldId={fieldId}
- getFieldHref={(fieldId) => getUrl({ ...parsedParams, fieldId })}
+ <TableFieldList
table={table}
+ activeFieldId={fieldId}
+ getFieldHref={getFieldHref}
/>
)}
</Stack>
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.unit.spec.tsx b/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
similarity index 68%
rename from frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.unit.spec.tsx
rename to frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
index 08c681ca3ae..45fc8e82b2b 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/TableSection.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/components/TableSection/TableSection.unit.spec.tsx
@@ -1,22 +1,17 @@
import { Route } from "react-router";
import { renderWithProviders, screen } from "__support__/ui";
-import type { Table } from "metabase-types/api";
+import type { FieldId, Table } from "metabase-types/api";
import { createMockTable } from "metabase-types/api/mocks";
-import type { RouteParams } from "../../types";
-
import { TableSection } from "./TableSection";
type SetupOpts = {
table?: Table;
- params?: RouteParams;
+ fieldId?: FieldId;
};
-function setup({
- table = createMockTable(),
- params = createMockRouteParams(),
-}: SetupOpts = {}) {
+function setup({ table = createMockTable(), fieldId }: SetupOpts = {}) {
const onSyncOptionsClick = jest.fn();
renderWithProviders(
@@ -25,7 +20,9 @@ function setup({
component={() => (
<TableSection
table={table}
- params={params}
+ fieldId={fieldId}
+ withName
+ getFieldHref={(fieldId) => `/field/${fieldId}`}
onSyncOptionsClick={onSyncOptionsClick}
/>
)}
@@ -36,16 +33,6 @@ function setup({
return { onSyncOptionsClick };
}
-function createMockRouteParams(opts?: Partial<RouteParams>): RouteParams {
- return {
- databaseId: "1",
- schemaId: "1:public",
- tableId: "1",
- fieldId: "1",
- ...opts,
- };
-}
-
describe("TableSection", () => {
it("should render the link to explore this table in the query builder", () => {
const table = createMockTable();
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/hooks.ts b/frontend/src/metabase/metadata/components/TableSection/hooks.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/hooks.ts
rename to frontend/src/metabase/metadata/components/TableSection/hooks.ts
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/index.ts b/frontend/src/metabase/metadata/components/TableSection/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/index.ts
rename to frontend/src/metabase/metadata/components/TableSection/index.ts
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSortableFieldList/TableSortableFieldList.tsx b/frontend/src/metabase/metadata/components/TableSortableFieldList/TableSortableFieldList.tsx
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSortableFieldList/TableSortableFieldList.tsx
rename to frontend/src/metabase/metadata/components/TableSortableFieldList/TableSortableFieldList.tsx
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSortableFieldList/index.ts b/frontend/src/metabase/metadata/components/TableSortableFieldList/index.ts
similarity index 100%
rename from enterprise/frontend/src/metabase-enterprise/data-studio/data-model/components/TableSection/TableSortableFieldList/index.ts
rename to frontend/src/metabase/metadata/components/TableSortableFieldList/index.ts
diff --git a/frontend/src/metabase/metadata/components/index.ts b/frontend/src/metabase/metadata/components/index.ts
index 1eb68df165f..6e5a77e0e0a 100644
--- a/frontend/src/metabase/metadata/components/index.ts
+++ b/frontend/src/metabase/metadata/components/index.ts
@@ -3,22 +3,32 @@ export * from "./CurrencyPicker";
export * from "./DataSourceInput";
export * from "./DiscardFieldValuesButton";
export * from "./DiscardTableFieldValuesButton";
+export * from "./FieldEmptyState";
export * from "./EntityTypeInput";
export * from "./FieldOrderPicker";
export * from "./FieldValuesTypePicker";
export * from "./FieldVisibilityPicker";
+export * from "./FieldSection";
+export * from "./FieldValuesModal";
export * from "./FkTargetPicker";
export * from "./LabeledValue";
export * from "./LayerInput";
export * from "./NameDescriptionInput";
+export * from "./NoDatabasesEmptyState";
+export * from "./PreviewSection";
export * from "./RescanFieldButton";
+export * from "./ResponsiveButton";
export * from "./RescanTableFieldsButton";
export * from "./SemanticTypeAndTargetPicker";
export * from "./SemanticTypePicker";
export * from "./SortableFieldItem";
export * from "./SortableFieldList";
+export * from "./SyncOptionsModal";
export * from "./SyncTableSchemaButton";
export * from "./TableBreadcrumbs";
+export * from "./TableFieldList";
+export * from "./TableSortableFieldList";
+export * from "./TableSection";
export * from "./TitledSection";
export * from "./UnfoldJsonPicker";
export * from "./UserInput";
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsx
index 60212a7bfaa..c9ec9950b1f 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsx
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.tsx
@@ -4,31 +4,29 @@ import { type ReactNode, useMemo, useState } from "react";
import { t } from "ttag";
import _ from "underscore";
-import EmptyDashboardBot from "assets/img/dashboard-empty.svg";
import {
useGetTableQueryMetadataQuery,
useListDatabasesQuery,
} from "metabase/api";
-import EmptyState from "metabase/common/components/EmptyState";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import * as Urls from "metabase/lib/urls";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import { Box, Flex, Stack, rem } from "metabase/ui";
import {
+ FieldEmptyState,
FieldSection,
FieldValuesModal,
NoDatabasesEmptyState,
PreviewSection,
type PreviewType,
-} from "../shared";
-
-import S from "./DataModel.module.css";
-import {
- RouterTablePicker,
- SegmentsLink,
SyncOptionsModal,
TableSection,
-} from "./components";
+} from "../../components";
+import { trackMetadataChange } from "../shared";
+
+import S from "./DataModel.module.css";
+import { RouterTablePicker, SegmentsLink } from "./components";
import { COLUMN_CONFIG, EMPTY_STATE_MIN_WIDTH } from "./constants";
import type { RouteParams } from "./types";
import { getTableMetadataQuery, parseRouteParams } from "./utils";
@@ -40,7 +38,8 @@ interface Props {
}
export const DataModelV1 = ({ children, location, params }: Props) => {
- const { databaseId, fieldId, schemaName, tableId } = parseRouteParams(params);
+ const parsedParams = parseRouteParams(params);
+ const { databaseId, fieldId, schemaName, tableId } = parsedParams;
const { data: databasesData, isLoading: isLoadingDatabases } =
useListDatabasesQuery({ include_editable_data_model: true });
const databaseExists = databasesData?.data?.some(
@@ -153,8 +152,12 @@ export const DataModelV1 = ({ children, location, params }: Props) => {
* This is to avoid state mix-up with optimistic updates.
*/
key={table.id}
- params={params}
table={table}
+ fieldId={fieldId}
+ withName
+ getFieldHref={(fieldId) =>
+ Urls.dataModel({ ...parsedParams, fieldId })
+ }
onSyncOptionsClick={openSyncModal}
/>
)}
@@ -177,18 +180,20 @@ export const DataModelV1 = ({ children, location, params }: Props) => {
{field && table && (
<Box flex="1" h="100%" maw={COLUMN_CONFIG.field.max}>
<FieldSection
- databaseId={databaseId}
- field={field}
/**
* Make sure internal component state is reset when changing fields.
* This is to avoid state mix-up with optimistic updates.
*/
key={getRawTableFieldId(field)}
- parent={parentField}
+ field={field}
table={table}
- eventSource="admin"
- onFieldValuesClick={openFieldValuesModal}
+ parent={parentField}
+ getFieldHref={(fieldId) =>
+ Urls.dataModel({ ...parsedParams, fieldId })
+ }
onPreviewClick={togglePreview}
+ onFieldValuesClick={openFieldValuesModal}
+ onTrackMetadataChange={trackMetadataChange}
/>
</Box>
)}
@@ -211,14 +216,11 @@ export const DataModelV1 = ({ children, location, params }: Props) => {
>
<PreviewSection
className={S.preview}
- databaseId={databaseId}
field={field}
- fieldId={fieldId}
- previewType={previewType}
table={table}
- tableId={tableId}
- onClose={closePreview}
+ previewType={previewType}
onPreviewTypeChange={setPreviewType}
+ onClose={closePreview}
/>
</Box>
)}
@@ -230,21 +232,7 @@ export const DataModelV1 = ({ children, location, params }: Props) => {
justify="center"
miw={rem(EMPTY_STATE_MIN_WIDTH)}
>
- <Box maw={rem(320)} p="xl">
- <EmptyState
- illustrationElement={<img src={EmptyDashboardBot} />}
- title={
- table
- ? t`Edit the table and fields`
- : t`Start by selecting data to model`
- }
- message={
- table
- ? t`Select a field to edit its name, description, formatting, and more.`
- : t`Browse your databases to find the table you’d like to edit.`
- }
- />
- </Box>
+ <FieldEmptyState hasTable={table != null} />
</Flex>
)}
</>
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx
index bb0d6bd5c6c..e0eddcbd335 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/DataModelV1.unit.spec.tsx
@@ -22,6 +22,7 @@ import {
} from "__support__/ui";
import { getNextId } from "__support__/utils";
import { checkNotNull } from "metabase/lib/types";
+import * as Urls from "metabase/lib/urls";
import { getRawTableFieldId } from "metabase/metadata/utils/field";
import registerVisualizations from "metabase/visualizations/register";
import type {
@@ -54,7 +55,6 @@ import {
import { DataModelV1 } from "./DataModelV1";
import type { ParsedRouteParams } from "./types";
-import { getUrl } from "./utils";
registerVisualizations();
@@ -237,7 +237,7 @@ async function setup({
</>,
{
withRouter: true,
- initialRoute: initialRoute ?? getUrl(params),
+ initialRoute: initialRoute ?? Urls.dataModel(params),
},
);
diff --git a/frontend/src/metabase/metadata/pages/shared/SegmentsLink/SegmentsLink.module.css b/frontend/src/metabase/metadata/pages/DataModelV1/components/SegmentsLink/SegmentsLink.module.css
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/SegmentsLink/SegmentsLink.module.css
rename to frontend/src/metabase/metadata/pages/DataModelV1/components/SegmentsLink/SegmentsLink.module.css
diff --git a/frontend/src/metabase/metadata/pages/shared/SegmentsLink/SegmentsLink.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/components/SegmentsLink/SegmentsLink.tsx
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/SegmentsLink/SegmentsLink.tsx
rename to frontend/src/metabase/metadata/pages/DataModelV1/components/SegmentsLink/SegmentsLink.tsx
diff --git a/frontend/src/metabase/metadata/pages/shared/SegmentsLink/index.ts b/frontend/src/metabase/metadata/pages/DataModelV1/components/SegmentsLink/index.ts
similarity index 100%
rename from frontend/src/metabase/metadata/pages/shared/SegmentsLink/index.ts
rename to frontend/src/metabase/metadata/pages/DataModelV1/components/SegmentsLink/index.ts
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/components/Results.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/components/Results.tsx
index 1f02e06d04f..51b2850bbae 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/components/Results.tsx
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/components/Results.tsx
@@ -9,9 +9,9 @@ import {
} from "react";
import { Link } from "react-router";
+import * as Urls from "metabase/lib/urls";
import { Box, Flex, Icon, Skeleton, rem } from "metabase/ui";
-import { getUrl } from "../../../utils";
import { TYPE_ICONS } from "../constants";
import type { FlatItem, TreePath } from "../types";
import { hasChildren } from "../utils";
@@ -212,7 +212,7 @@ export function Results({
marginLeft: level * INDENT_OFFSET,
pointerEvents: disabled ? "none" : undefined,
}}
- to={getUrl({
+ to={Urls.dataModel({
databaseId: value?.databaseId,
schemaName:
type === "schema" || type === "table"
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/utils.ts b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/utils.ts
index 2d5be4dfd47..476987786f1 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/utils.ts
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/utils.ts
@@ -1,5 +1,3 @@
-import { getUrl as getUrl_ } from "../../utils";
-
import { CHILD_TYPES, UNNAMED_SCHEMA_NAME } from "./constants";
import type {
DatabaseNode,
@@ -16,16 +14,6 @@ export function hasChildren(type: ItemType): boolean {
return type !== "table";
}
-export function getUrl(value: TreePath) {
- return getUrl_({
- fieldId: undefined,
- tableId: undefined,
- databaseId: undefined,
- schemaName: undefined,
- ...value,
- });
-}
-
// Returns a new state object with all the nodes along the path expanded.
export function expandPath(
state: ExpandedState,
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx
index 950f19237f3..aee5bb33d9c 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/components/TablePicker/wrappers.tsx
@@ -2,11 +2,11 @@ import { useCallback, useEffect, useState } from "react";
import { push, replace } from "react-router-redux";
import { useDispatch, useSelector } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
import { getLocation } from "metabase/selectors/routing";
import { TablePicker } from "./components";
import type { ChangeOptions, TreePath } from "./types";
-import { getUrl } from "./utils";
export function RouterTablePicker(props: TreePath) {
const dispatch = useDispatch();
@@ -26,10 +26,10 @@ export function RouterTablePicker(props: TreePath) {
if (options?.isAutomatic) {
// prevent auto-navigation from table-picker when Segments tab is open
if (!isSegments) {
- dispatch(replace(getUrl(value)));
+ dispatch(replace(Urls.dataModel(value)));
}
} else {
- dispatch(push(getUrl(value)));
+ dispatch(push(Urls.dataModel(value)));
}
}
},
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/FieldItem.module.css b/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/FieldItem.module.css
deleted file mode 100644
index e9e36ead8cf..00000000000
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/FieldItem.module.css
+++ /dev/null
@@ -1,62 +0,0 @@
-.card {
- box-shadow: 0 2px 4px 0 hsla(0, 0%, 0%, 0.05) !important;
- overflow: visible; /* so that outline from focus state of inner <a /> is not cut off */
-
- &:hover {
- &:not(.active) {
- background-color: var(--mb-color-brand-lighter) !important;
- }
- }
-}
-
-.active {
- border-color: var(--mb-color-brand) !important;
-}
-
-.link {
- border-radius: inherit;
-}
-
-.icon {
- color: var(--mb-color-brand);
-}
-
-.input {
- overflow: hidden;
- line-height: var(--mantine-line-height) !important;
-
- &:focus-within {
- border-color: var(--mb-color-brand) !important;
- }
-
- textarea {
- cursor: text;
-
- &:focus {
- color: var(--mb-color-text-secondary);
- background-color: var(--mb-color-brand-lighter);
- }
- }
-
- .active & {
- textarea {
- &:focus,
- &:hover {
- background-color: var(--mb-color-bg-white);
- }
- }
- }
-}
-
-.description {
- line-height: var(--mantine-line-height-lg) !important;
-}
-
-.name {
- line-clamp: 1;
- -webkit-line-clamp: 1;
-
- textarea {
- white-space: nowrap;
- }
-}
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/FieldItem.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/FieldItem.tsx
deleted file mode 100644
index 7f0e5dce00d..00000000000
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/FieldItem.tsx
+++ /dev/null
@@ -1,204 +0,0 @@
-import cx from "classnames";
-import type { MouseEvent } from "react";
-import { Link } from "react-router";
-import { t } from "ttag";
-
-import { useUpdateFieldMutation } from "metabase/api";
-import EditableText from "metabase/common/components/EditableText";
-import { Ellipsified } from "metabase/common/components/Ellipsified";
-import { getColumnIcon } from "metabase/common/utils/columns";
-import { useMetadataToasts } from "metabase/metadata/hooks";
-import { getRawTableFieldId } from "metabase/metadata/utils/field";
-import { Box, Card, Flex, Group, Icon, rem } from "metabase/ui";
-import * as Lib from "metabase-lib";
-import type { Field } from "metabase-types/api";
-
-import S from "./FieldItem.module.css";
-
-interface Props {
- active?: boolean;
- field: Field;
- href: string;
- parent?: Field;
-}
-
-export const FieldItem = ({ active, field, href, parent }: Props) => {
- const id = getRawTableFieldId(field);
- const [updateField] = useUpdateFieldMutation();
- const { sendErrorToast, sendSuccessToast, sendUndoToast } =
- useMetadataToasts();
- const icon = getColumnIcon(Lib.legacyColumnTypeInfo(field));
-
- const handleNameChange = async (name: string) => {
- const newName = name.trim();
-
- if (field.display_name === newName) {
- return;
- }
-
- const { error } = await updateField({ id, display_name: name });
-
- if (error) {
- sendErrorToast(t`Failed to update name of ${field.display_name}`);
- } else {
- sendSuccessToast(t`Name of ${field.display_name} updated`, async () => {
- const { error } = await updateField({
- id,
- display_name: field.display_name,
- });
- sendUndoToast(error);
- });
- }
- };
-
- const handleDescriptionChange = async (description: string) => {
- const newDescription = description.trim();
-
- if ((field.description ?? "") === newDescription) {
- return;
- }
-
- const { error } = await updateField({
- id,
- // API does not accept empty strings
- description: description.length === 0 ? null : description,
- });
-
- if (error) {
- sendErrorToast(t`Failed to update description of ${field.display_name}`);
- } else {
- sendSuccessToast(
- t`Description of ${field.display_name} updated`,
- async () => {
- const { error } = await updateField({
- id,
- description: field.description ?? "",
- });
- sendUndoToast(error);
- },
- );
- }
- };
-
- const handleInputClick = (event: MouseEvent) => {
- // EditableText component breaks a11y with the programmatic
- // event.currentTarget.click() call. The click event bubbles
- // to this Link component. This is problematic e.g. when tabbing
- // out of the EditableText component, as the link gets clicked.
- if (!event.isTrusted) {
- event.stopPropagation();
- event.preventDefault();
- }
- };
-
- const handleClick = (event: MouseEvent) => {
- // prevent navigation when focusing textareas with mouse
- if (
- event.target instanceof HTMLElement &&
- event.target.tagName === "TEXTAREA"
- ) {
- event.preventDefault();
- }
- };
-
- return (
- <Card
- aria-label={field.display_name}
- bg={active ? "brand-light" : "bg-white"}
- c="text-medium"
- className={cx(S.card, {
- [S.active]: active,
- })}
- role="listitem"
- p={0}
- pb={1}
- withBorder
- >
- <Flex
- align="flex-start"
- className={S.link}
- component={Link}
- direction="column"
- draggable={false} // this + onClick handler is required, otherwise interaction is broken on macOS
- gap={rem(12)}
- justify="space-between"
- mih={rem(40)}
- pos="relative"
- px="md"
- py={rem(12)}
- to={href}
- w="100%"
- wrap="nowrap"
- onClick={handleClick} // this + draggable={false} is required, otherwise interaction is broken on macOS
- >
- <Group
- align="center"
- c="text-light"
- flex="0 0 auto"
- gap={0}
- maw="100%"
- w="100%"
- wrap="nowrap"
- >
- <Icon className={S.icon} flex="0 0 auto" mr="sm" name={icon} />
-
- {parent && (
- <Box
- data-testid="name-prefix"
- flex="0 0 auto"
- lh="normal"
- maw="50%"
- mb={rem(-4)}
- mr="xs"
- mt={rem(-3)}
- >
- <Ellipsified lines={1} tooltip={parent.display_name}>
- {parent.display_name}
- {":"}
- </Ellipsified>
- </Box>
- )}
-
- <Box
- className={cx(S.input, S.name)}
- // TODO: fix EditableText or use something else
- // https://linear.app/metabase/issue/SEM-429/data-model-inline-field-namedescription-inputs
- component={EditableText}
- fw="bold"
- initialValue={field.display_name}
- maxLength={254}
- mb={rem(-4)}
- ml={rem(-2)}
- mt={rem(-3)}
- placeholder={t`Give this field a name`}
- px={rem(1)}
- py={rem(2)}
- tabIndex={undefined} // override the default 0 which breaks a11y
- onChange={handleNameChange}
- onClick={handleInputClick}
- />
- </Group>
-
- <Box
- className={cx(S.input, S.description)}
- // TODO: fix EditableText or use something else
- // https://linear.app/metabase/issue/SEM-429/data-model-inline-field-namedescription-inputs
- component={EditableText}
- initialValue={field.description ?? ""}
- isMultiline
- isOptional
- maw="100%"
- mb={rem(-4)}
- mt={rem(-3)}
- mx={rem(-2)}
- px={rem(1)}
- py={0}
- placeholder={t`No description yet`}
- tabIndex={undefined} // override the default 0 which breaks a11y
- onChange={handleDescriptionChange}
- onClick={handleInputClick}
- />
- </Flex>
- </Card>
- );
-};
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/index.ts b/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/index.ts
deleted file mode 100644
index 8432734e678..00000000000
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldItem/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./FieldItem";
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldList.tsx b/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldList.tsx
deleted file mode 100644
index b0982c62bf9..00000000000
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/FieldList.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useMemo } from "react";
-import _ from "underscore";
-
-import { getRawTableFieldId } from "metabase/metadata/utils/field";
-import { Stack, rem } from "metabase/ui";
-import type { FieldId, Table } from "metabase-types/api";
-
-import { FieldItem } from "./FieldItem";
-
-interface Props {
- activeFieldId?: FieldId;
- getFieldHref: (fieldId: FieldId) => string;
- table: Table;
-}
-
-export const FieldList = ({ activeFieldId, getFieldHref, table }: Props) => {
- const fields = useMemo(() => {
- return _.sortBy(table.fields ?? [], (item) => item.position);
- }, [table.fields]);
- const fieldsByName = useMemo(() => {
- return _.indexBy(fields, (field) => field.name);
- }, [fields]);
-
- return (
- <Stack gap={rem(12)}>
- {fields.map((field) => {
- const id = getRawTableFieldId(field);
- const parentName = field.nfc_path?.[0] ?? "";
- const parent = fieldsByName[parentName];
-
- return (
- <FieldItem
- active={id === activeFieldId}
- field={field}
- parent={parent}
- href={getFieldHref(id)}
- key={id}
- />
- );
- })}
- </Stack>
- );
-};
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/index.ts b/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/index.ts
deleted file mode 100644
index cd5026f9b2c..00000000000
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/TableSection/FieldList/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./FieldList";
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/components/index.ts b/frontend/src/metabase/metadata/pages/DataModelV1/components/index.ts
index 8a8f3b5bc44..dc991067f92 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/components/index.ts
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/components/index.ts
@@ -1,4 +1,2 @@
-export * from "../../shared/SegmentsLink";
-export * from "./SyncOptionsModal";
+export * from "./SegmentsLink";
export * from "./TablePicker";
-export * from "./TableSection";
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/types.ts b/frontend/src/metabase/metadata/pages/DataModelV1/types.ts
index bbf5774e49b..643981120de 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/types.ts
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/types.ts
@@ -27,14 +27,3 @@ export interface ColumnSizeConfig {
min: number;
max: number;
}
-
-export type MetadataEditAnalyticsDetail =
- | "type_casting"
- | "semantic_type_change"
- | "visibility_change"
- | "filtering_change"
- | "display_values"
- | "json_unfolding"
- | "formatting";
-
-export type MetadataEventSource = "admin" | "data_studio";
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/utils.ts b/frontend/src/metabase/metadata/pages/DataModelV1/utils.ts
index 55a47d08a26..7647db7e6a3 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/utils.ts
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/utils.ts
@@ -17,34 +17,6 @@ export function parseRouteParams(params: RouteParams): ParsedRouteParams {
};
}
-export function getUrl(params: ParsedRouteParams): string {
- const { databaseId, schemaName, tableId, fieldId } = params;
- const schemaId = `${databaseId}:${schemaName}`;
-
- if (
- databaseId != null &&
- schemaName != null &&
- tableId != null &&
- fieldId != null
- ) {
- return `/admin/datamodel/database/${databaseId}/schema/${schemaId}/table/${tableId}/field/${fieldId}`;
- }
-
- if (databaseId != null && schemaName != null && tableId != null) {
- return `/admin/datamodel/database/${databaseId}/schema/${schemaId}/table/${tableId}`;
- }
-
- if (databaseId != null && schemaName != null) {
- return `/admin/datamodel/database/${databaseId}/schema/${schemaId}`;
- }
-
- if (databaseId != null) {
- return `/admin/datamodel/database/${databaseId}`;
- }
-
- return `/admin/datamodel`;
-}
-
export function getTableMetadataQuery(
tableId: TableId | undefined,
): GetTableQueryMetadataRequest | typeof skipToken {
diff --git a/frontend/src/metabase/metadata/pages/DataModelV1/utils.unit.spec.ts b/frontend/src/metabase/metadata/pages/DataModelV1/utils.unit.spec.ts
index c92aa51d4cf..fc717325c11 100644
--- a/frontend/src/metabase/metadata/pages/DataModelV1/utils.unit.spec.ts
+++ b/frontend/src/metabase/metadata/pages/DataModelV1/utils.unit.spec.ts
@@ -1,5 +1,5 @@
-import type { ParsedRouteParams, RouteParams } from "./types";
-import { getUrl, parseRouteParams } from "./utils";
+import type { RouteParams } from "./types";
+import { parseRouteParams } from "./utils";
describe("parseRouteParams", () => {
it("should parse all route parameters correctly", () => {
@@ -48,86 +48,3 @@ describe("parseRouteParams", () => {
});
});
});
-
-describe("getUrl", () => {
- it("should generate URL with all params", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: 2,
- fieldId: 3,
- };
-
- expect(getUrl(params)).toBe(
- "/admin/datamodel/database/1/schema/1:public/table/2/field/3",
- );
- });
-
- it("should generate URL with database, schema, and table", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: 2,
- fieldId: undefined,
- };
-
- expect(getUrl(params)).toBe(
- "/admin/datamodel/database/1/schema/1:public/table/2",
- );
- });
-
- it("should generate URL with database and schema", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: undefined,
- fieldId: undefined,
- };
-
- expect(getUrl(params)).toBe("/admin/datamodel/database/1/schema/1:public");
- });
-
- it("should generate URL with database", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: undefined,
- tableId: undefined,
- fieldId: undefined,
- };
-
- expect(getUrl(params)).toBe("/admin/datamodel/database/1");
- });
-
- it("should generate base URL when no params are provided", () => {
- const params: ParsedRouteParams = {
- databaseId: undefined,
- schemaName: undefined,
- tableId: undefined,
- fieldId: undefined,
- };
-
- expect(getUrl(params)).toBe("/admin/datamodel");
- });
-
- it("should not include field param when there is no table param", () => {
- const params: ParsedRouteParams = {
- databaseId: 1,
- schemaName: "public",
- tableId: undefined,
- fieldId: 3,
- };
-
- expect(getUrl(params)).toBe("/admin/datamodel/database/1/schema/1:public");
- });
-
- it("should not include schema, table, and field params when there is no database param", () => {
- const params: ParsedRouteParams = {
- databaseId: undefined,
- schemaName: "public",
- tableId: 2,
- fieldId: 3,
- };
-
- expect(getUrl(params)).toBe("/admin/datamodel");
- });
-});
diff --git a/frontend/src/metabase/metadata/pages/shared/DataModelContext.tsx b/frontend/src/metabase/metadata/pages/shared/DataModelContext.tsx
deleted file mode 100644
index e81f3f451bc..00000000000
--- a/frontend/src/metabase/metadata/pages/shared/DataModelContext.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { createContext } from "react";
-
-export type DataModelContextType = {
- baseUrl: string;
-};
-
-// should be removed once we don't need to render the page in two different places
-export const DataModelContext = createContext<DataModelContextType>({
- baseUrl: "/admin/datamodel",
-});
diff --git a/frontend/src/metabase/metadata/pages/shared/analytics.ts b/frontend/src/metabase/metadata/pages/shared/analytics.ts
index f7225f45b06..60bbbbfa735 100644
--- a/frontend/src/metabase/metadata/pages/shared/analytics.ts
+++ b/frontend/src/metabase/metadata/pages/shared/analytics.ts
@@ -1,17 +1,10 @@
import { trackSimpleEvent } from "metabase/lib/analytics";
+import type { MetadataEditEventDetail } from "metabase-types/analytics";
-import type {
- MetadataEditAnalyticsDetail,
- MetadataEventSource,
-} from "../DataModelV1/types";
-
-export const trackMetadataChange = (
- detail: MetadataEditAnalyticsDetail,
- triggered_from: MetadataEventSource,
-) => {
+export const trackMetadataChange = (detail: MetadataEditEventDetail) => {
trackSimpleEvent({
event: "metadata_edited",
event_detail: detail,
- triggered_from,
+ triggered_from: "admin",
});
};
diff --git a/frontend/src/metabase/metadata/pages/shared/index.ts b/frontend/src/metabase/metadata/pages/shared/index.ts
index 447ce2a34ab..1cda355301a 100644
--- a/frontend/src/metabase/metadata/pages/shared/index.ts
+++ b/frontend/src/metabase/metadata/pages/shared/index.ts
@@ -1,9 +1,2 @@
export * from "./analytics";
-export * from "./DataModelContext";
-export * from "./FieldSection";
-export * from "./FieldValuesModal";
-export * from "./NoDatabasesEmptyState";
-export * from "./PreviewSection";
-export * from "./ResponsiveButton";
-export * from "./SegmentsLink";
export * from "./utils";
diff --git a/frontend/src/metabase/metadata/pages/shared/utils.ts b/frontend/src/metabase/metadata/pages/shared/utils.ts
index 7fcc8c2fc26..5a16fe18200 100644
--- a/frontend/src/metabase/metadata/pages/shared/utils.ts
+++ b/frontend/src/metabase/metadata/pages/shared/utils.ts
@@ -17,34 +17,6 @@ export function parseRouteParams(params: RouteParams): ParsedRouteParams {
};
}
-export function getUrl(baseUrl: string, params: ParsedRouteParams): string {
- const { databaseId, schemaName, tableId, fieldId } = params;
- const schemaId = `${databaseId}:${schemaName}`;
-
- if (
- databaseId != null &&
- schemaName != null &&
- tableId != null &&
- fieldId != null
- ) {
- return `${baseUrl}/database/${databaseId}/schema/${schemaId}/table/${tableId}/field/${fieldId}`;
- }
-
- if (databaseId != null && schemaName != null && tableId != null) {
- return `${baseUrl}/database/${databaseId}/schema/${schemaId}/table/${tableId}`;
- }
-
- if (databaseId != null && schemaName != null) {
- return `${baseUrl}/database/${databaseId}/schema/${schemaId}`;
- }
-
- if (databaseId != null) {
- return `${baseUrl}/database/${databaseId}`;
- }
-
- return baseUrl;
-}
-
export function getTableMetadataQuery(
tableId: TableId | undefined,
): GetTableQueryMetadataRequest | typeof skipToken {
diff --git a/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx b/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
index 9bf1e874107..96597858410 100644
--- a/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
+++ b/frontend/src/metabase/models/containers/NewModelOptions/NewModelOptions.tsx
@@ -1,20 +1,19 @@
import cx from "classnames";
import type { Location } from "history";
import { t } from "ttag";
-import _ from "underscore";
-import { useListDatabasesQuery } from "metabase/api";
-import { DelayedLoadingSpinner } from "metabase/common/components/EntityPicker/components/LoadingSpinner";
import { Grid } from "metabase/common/components/Grid";
import CS from "metabase/css/core/index.css";
-import Databases from "metabase/entities/databases";
import { useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import NewModelOption from "metabase/models/components/NewModelOption";
import { PLUGIN_DATA_STUDIO } from "metabase/plugins";
import { NoDatabasesEmptyState } from "metabase/reference/databases/NoDatabasesEmptyState";
-import { getHasDataAccess, getHasNativeWrite } from "metabase/selectors/data";
import { getLearnUrl, getSetting } from "metabase/selectors/settings";
+import {
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
+} from "metabase/selectors/user";
import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
import {
@@ -30,10 +29,8 @@ interface NewModelOptionsProps {
}
const NewModelOptions = ({ location }: NewModelOptionsProps) => {
- const { data, isFetching } = useListDatabasesQuery();
- const databases = data?.data ?? [];
- const hasDataAccess = getHasDataAccess(databases);
- const hasNativeWrite = getHasNativeWrite(databases);
+ const hasDataAccess = useSelector(canUserCreateQueries);
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
const lastUsedDatabaseId = useSelector((state) =>
getSetting(state, "last-used-native-database-id"),
@@ -52,10 +49,6 @@ const NewModelOptions = ({ location }: NewModelOptionsProps) => {
const showMetabaseLinks = useSelector(getShowMetabaseLinks);
- if (isFetching) {
- return <DelayedLoadingSpinner />;
- }
-
if (!hasDataAccess && !hasNativeWrite) {
return (
<div
@@ -121,8 +114,4 @@ const NewModelOptions = ({ location }: NewModelOptionsProps) => {
);
};
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default _.compose(
- Databases.loadList({
- loadingAndErrorWrapper: false,
- }),
-)(NewModelOptions);
+export default NewModelOptions;
diff --git a/frontend/src/metabase/models/containers/NewModelOptions/tests/common.unit.spec.tsx b/frontend/src/metabase/models/containers/NewModelOptions/tests/common.unit.spec.tsx
index 2d9c5139aae..198345b1d61 100644
--- a/frontend/src/metabase/models/containers/NewModelOptions/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/models/containers/NewModelOptions/tests/common.unit.spec.tsx
@@ -1,14 +1,10 @@
-import fetchMock from "fetch-mock";
-
import { screen } from "__support__/ui";
-import { delay } from "metabase/lib/promise";
-import { createMockDatabase } from "metabase-types/api/mocks";
import { setup } from "./setup";
describe("NewModelOptions (OSS)", () => {
it("should render no data access notice when instance have no database access", async () => {
- setup({ databases: [] });
+ setup({ canCreateQueries: false });
expect(
await screen.findByText("Metabase is no fun without any data"),
@@ -16,24 +12,8 @@ describe("NewModelOptions (OSS)", () => {
});
describe("has data access", () => {
- it("should render loading indicator when fetching databases (metabase#44813)", async () => {
- setup({ databases: [createMockDatabase()] });
-
- fetchMock.get(
- "path:/api/database",
- delay(2000).then(() => {
- return [createMockDatabase()];
- }),
- );
-
- expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
- expect(
- screen.queryByText("Metabase is no fun without any data"),
- ).not.toBeInTheDocument();
- });
-
it("should render options for creating a model", async () => {
- setup({ databases: [createMockDatabase()] });
+ setup({ canCreateQueries: true, canCreateNativeQueries: true });
expect(
await screen.findByText("Use the notebook editor"),
@@ -43,13 +23,13 @@ describe("NewModelOptions (OSS)", () => {
describe("whitelabel feature", () => {
it("should render help link when `show-metabase-links: false`", async () => {
- setup({ databases: [createMockDatabase()], showMetabaseLinks: false });
+ setup({ canCreateQueries: true, showMetabaseLinks: false });
expect(await screen.findByText("What's a model?")).toBeInTheDocument();
});
it("should render help link when `show-metabase-links: true`", async () => {
- setup({ databases: [createMockDatabase()], showMetabaseLinks: true });
+ setup({ canCreateQueries: true, showMetabaseLinks: true });
expect(await screen.findByText("What's a model?")).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/models/containers/NewModelOptions/tests/enterprise.unit.spec.tsx b/frontend/src/metabase/models/containers/NewModelOptions/tests/enterprise.unit.spec.tsx
index 79d59d2a2b5..a94d261fd18 100644
--- a/frontend/src/metabase/models/containers/NewModelOptions/tests/enterprise.unit.spec.tsx
+++ b/frontend/src/metabase/models/containers/NewModelOptions/tests/enterprise.unit.spec.tsx
@@ -1,5 +1,4 @@
import { screen } from "__support__/ui";
-import { createMockDatabase } from "metabase-types/api/mocks";
import type { SetupOpts } from "./setup";
import { setup as baseSetup } from "./setup";
@@ -10,7 +9,7 @@ function setup(opts: SetupOpts) {
describe("NewModelOptions (EE without token)", () => {
it("should render no data access notice when instance have no database access", async () => {
- setup({ databases: [] });
+ setup({ canCreateQueries: false });
expect(
await screen.findByText("Metabase is no fun without any data"),
@@ -19,7 +18,7 @@ describe("NewModelOptions (EE without token)", () => {
describe("has data access", () => {
it("should render options for creating a model", async () => {
- setup({ databases: [createMockDatabase()] });
+ setup({ canCreateQueries: true, canCreateNativeQueries: true });
expect(
await screen.findByText("Use the notebook editor"),
@@ -29,13 +28,13 @@ describe("NewModelOptions (EE without token)", () => {
describe("whitelabel feature", () => {
it("should render help link when `show-metabase-links: false`", async () => {
- setup({ databases: [createMockDatabase()], showMetabaseLinks: false });
+ setup({ canCreateQueries: true, showMetabaseLinks: false });
expect(await screen.findByText("What's a model?")).toBeInTheDocument();
});
it("should render help link when `show-metabase-links: true`", async () => {
- setup({ databases: [createMockDatabase()], showMetabaseLinks: true });
+ setup({ canCreateQueries: true, showMetabaseLinks: true });
expect(await screen.findByText("What's a model?")).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/models/containers/NewModelOptions/tests/premium.unit.spec.tsx b/frontend/src/metabase/models/containers/NewModelOptions/tests/premium.unit.spec.tsx
index 2f3f59e5508..a46df254f7c 100644
--- a/frontend/src/metabase/models/containers/NewModelOptions/tests/premium.unit.spec.tsx
+++ b/frontend/src/metabase/models/containers/NewModelOptions/tests/premium.unit.spec.tsx
@@ -1,5 +1,4 @@
import { screen } from "__support__/ui";
-import { createMockDatabase } from "metabase-types/api/mocks";
import type { SetupOpts } from "./setup";
import { setup as baseSetup } from "./setup";
@@ -14,7 +13,7 @@ function setup(opts: SetupOpts) {
describe("NewModelOptions (EE with token)", () => {
it("should render no data access notice when instance have no database access", async () => {
- setup({ databases: [] });
+ setup({ canCreateQueries: false });
expect(
await screen.findByText("Metabase is no fun without any data"),
@@ -23,7 +22,7 @@ describe("NewModelOptions (EE with token)", () => {
describe("has data access", () => {
it("should render options for creating a model", async () => {
- setup({ databases: [createMockDatabase()] });
+ setup({ canCreateQueries: true, canCreateNativeQueries: true });
expect(
await screen.findByText("Use the notebook editor"),
@@ -33,7 +32,11 @@ describe("NewModelOptions (EE with token)", () => {
describe("whitelabel feature", () => {
it("should not render help link when `show-metabase-links: false`", async () => {
- setup({ databases: [createMockDatabase()], showMetabaseLinks: false });
+ setup({
+ canCreateQueries: true,
+ canCreateNativeQueries: true,
+ showMetabaseLinks: false,
+ });
expect(
await screen.findByText("Use the notebook editor"),
@@ -42,7 +45,11 @@ describe("NewModelOptions (EE with token)", () => {
});
it("should render help link when `show-metabase-links: true`", async () => {
- setup({ databases: [createMockDatabase()], showMetabaseLinks: true });
+ setup({
+ canCreateQueries: true,
+ canCreateNativeQueries: true,
+ showMetabaseLinks: true,
+ });
expect(await screen.findByText("What's a model?")).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/models/containers/NewModelOptions/tests/setup.tsx b/frontend/src/metabase/models/containers/NewModelOptions/tests/setup.tsx
index cdd6ac64f9b..6bd0706c7aa 100644
--- a/frontend/src/metabase/models/containers/NewModelOptions/tests/setup.tsx
+++ b/frontend/src/metabase/models/containers/NewModelOptions/tests/setup.tsx
@@ -1,31 +1,40 @@
import { Route } from "react-router";
import { setupEnterprisePlugins } from "__support__/enterprise";
-import { setupDatabasesEndpoints } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
-import type { Database, TokenFeatures } from "metabase-types/api";
-import { createMockTokenFeatures } from "metabase-types/api/mocks";
+import type { TokenFeatures } from "metabase-types/api";
+import {
+ createMockTokenFeatures,
+ createMockUser,
+ createMockUserPermissions,
+} from "metabase-types/api/mocks";
import { createMockState } from "metabase-types/store/mocks";
import NewModelOptions from "../NewModelOptions";
export interface SetupOpts {
- databases: Database[];
+ canCreateQueries?: boolean;
+ canCreateNativeQueries?: boolean;
showMetabaseLinks?: boolean;
hasEnterprisePlugins?: boolean;
tokenFeatures?: Partial<TokenFeatures>;
}
export function setup({
- databases = [],
+ canCreateQueries = false,
+ canCreateNativeQueries = false,
showMetabaseLinks = true,
hasEnterprisePlugins,
tokenFeatures = {},
}: SetupOpts) {
- setupDatabasesEndpoints(databases);
-
const state = createMockState({
+ currentUser: createMockUser({
+ permissions: createMockUserPermissions({
+ can_create_queries: canCreateQueries,
+ can_create_native_queries: canCreateNativeQueries,
+ }),
+ }),
settings: mockSettings({
"show-metabase-links": showMetabaseLinks,
"token-features": createMockTokenFeatures(tokenFeatures),
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx
index 89811424185..21f7a43e9e9 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx
@@ -10,7 +10,6 @@ import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders } from "__support__/ui";
import { ROOT_COLLECTION } from "metabase/entities/collections";
-import type { UserWithApplicationPermissions } from "metabase/plugins";
import type { GdrivePayload, TokenFeatures } from "metabase-types/api";
import {
createMockCollection,
@@ -49,12 +48,12 @@ export const setup = ({
status,
adminEmail = "[email protected]",
}: SetupOpts = {}) => {
- const user = {
+ const user = createMockUser({
is_superuser: isAdmin,
- };
+ });
if (canManageSettings) {
- (user as UserWithApplicationPermissions).permissions = {
+ user.permissions = {
can_access_setting: true,
can_access_monitoring: false,
can_access_subscription: false,
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.unit.spec.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.unit.spec.ts
index 3180869a53c..4adc5c02026 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.unit.spec.ts
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.unit.spec.ts
@@ -6,7 +6,6 @@ import {
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
import { renderHookWithProviders, waitFor } from "__support__/ui";
-import type { UserWithApplicationPermissions } from "metabase/plugins";
import {
createMockDatabase,
createMockTokenFeatures,
@@ -30,7 +29,7 @@ function setup({
});
if (canAccessSettings) {
- (currentUser as UserWithApplicationPermissions).permissions = {
+ currentUser.permissions = {
can_access_setting: true,
can_access_monitoring: false,
can_access_subscription: false,
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
index 08e1d2d0456..3c30636f484 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarContainer.tsx
@@ -23,7 +23,6 @@ import Collections, {
import Databases from "metabase/entities/databases";
import { connect } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
-import { getHasDataAccess } from "metabase/selectors/data";
import { getUser, getUserIsAdmin } from "metabase/selectors/user";
import type Database from "metabase-lib/v1/metadata/Database";
import type { Bookmark, Collection, User } from "metabase-types/api";
@@ -41,7 +40,7 @@ function mapStateToProps(state: State, { databases = [] }: DatabaseProps) {
return {
currentUser: getUser(state),
isAdmin: getUserIsAdmin(state),
- hasDataAccess: getHasDataAccess(databases),
+ hasDataAccess: databases.length > 0,
bookmarks: getOrderedBookmarks(state),
};
}
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
index cf3c185b0cc..736bfd77dd5 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
@@ -11,7 +11,6 @@ import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { CreateOrEditQuestionAlertModal } from "metabase/notifications/modals";
-import type { UserWithApplicationPermissions } from "metabase/plugins";
import type {
ChannelApiResponse,
Notification,
@@ -432,7 +431,7 @@ function setup({
);
if (userCanAccessSettings) {
- (currentUser as UserWithApplicationPermissions).permissions = {
+ currentUser.permissions = {
can_access_setting: true,
can_access_monitoring: false,
can_access_subscription: false,
diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
index ab6b96f9914..c5d847b4af2 100644
--- a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
+++ b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
@@ -22,6 +22,7 @@ import {
createMockRecentCollectionItem,
createMockTokenFeatures,
createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import {
createMockAdminAppState,
@@ -142,6 +143,10 @@ export const commonSetup = ({
settings: mockSettings({ ...settings, "token-features": TOKEN_FEATURES }),
currentUser: createMockUser({
is_superuser: isAdmin,
+ permissions: createMockUserPermissions({
+ can_create_queries: true,
+ can_create_native_queries: true,
+ }),
}),
});
diff --git a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
index ee2fcf305b7..95d5ede3215 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
@@ -352,7 +352,9 @@ export const getSearchResultSubtext = (wrappedSearchResult: any) => {
)} ${wrappedSearchResult.model_name}`}</SubtitleText>
);
} else if (wrappedSearchResult.model === "table") {
- return (
+ return wrappedSearchResult.collection?.name ? (
+ <SubtitleText>{wrappedSearchResult.collection.name}</SubtitleText>
+ ) : (
<SubtitleText>
{wrappedSearchResult.table_schema
? `${wrappedSearchResult.database_name} (${wrappedSearchResult.table_schema})`
diff --git a/frontend/src/metabase/palette/hooks/useCommandPalette.unit.spec.tsx b/frontend/src/metabase/palette/hooks/useCommandPalette.unit.spec.tsx
index 31e3956a171..daab0cbae64 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPalette.unit.spec.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPalette.unit.spec.tsx
@@ -80,6 +80,20 @@ describe("useCommandPalette", () => {
await screen.findByText("Bar Database (My Schema)"),
).toBeInTheDocument();
});
+
+ it("should should include the collection name in table search results when the table is published to a collection", async () => {
+ const mockSearchResult = Search.wrapEntity(
+ createMockSearchResult({
+ model: "table",
+ collection: createMockCollection({ id: 1, name: "Data" }),
+ database_name: "Bar Database",
+ table_schema: "My Schema",
+ }),
+ );
+ setup(getSearchResultSubtext(mockSearchResult));
+
+ expect(await screen.findByText("Data")).toBeInTheDocument();
+ });
});
describe("getRecentItemSubtext", () => {
diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
index 1b83e978716..cb6409e5873 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
@@ -23,12 +23,10 @@ import {
setOpenModal,
setOpenModalWithProps,
} from "metabase/redux/ui";
+import { getHasDatabaseWithActionsEnabled } from "metabase/selectors/data";
import {
- getHasDataAccess,
- getHasDatabaseWithActionsEnabled,
- getHasNativeWrite,
-} from "metabase/selectors/data";
-import {
+ canUserCreateNativeQueries,
+ canUserCreateQueries,
getUserIsAdmin,
getUserPersonalCollectionId,
} from "metabase/selectors/user";
@@ -60,8 +58,8 @@ export const useCommandPaletteBasicActions = ({
const personalCollectionId = useSelector(getUserPersonalCollectionId);
const isAdmin = useSelector(getUserIsAdmin);
- const hasDataAccess = getHasDataAccess(databases);
- const hasNativeWrite = getHasNativeWrite(databases);
+ const hasDataAccess = useSelector(canUserCreateQueries);
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
const hasDatabaseWithActionsEnabled =
getHasDatabaseWithActionsEnabled(databases);
const hasModels = models.length > 0;
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 97b1d9508e0..29a580c673d 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -105,7 +105,6 @@ export {
PLUGIN_FEATURE_LEVEL_PERMISSIONS,
PLUGIN_APPLICATION_PERMISSIONS,
PLUGIN_GROUP_MANAGERS,
- type UserWithApplicationPermissions,
} from "./oss/permissions";
export { PLUGIN_PUBLIC_SHARING } from "./oss/public-sharing";
export { PLUGIN_REMOTE_SYNC } from "./oss/remote-sync";
diff --git a/frontend/src/metabase/plugins/oss/permissions.ts b/frontend/src/metabase/plugins/oss/permissions.ts
index fb1eddb9ab2..d6204ac000d 100644
--- a/frontend/src/metabase/plugins/oss/permissions.ts
+++ b/frontend/src/metabase/plugins/oss/permissions.ts
@@ -20,15 +20,6 @@ import type { State } from "metabase-types/store";
import type { PluginGroupManagersType } from "../types";
-// Types
-export interface UserWithApplicationPermissions extends User {
- permissions?: {
- can_access_monitoring: boolean;
- can_access_setting: boolean;
- can_access_subscription: boolean;
- };
-}
-
const getDefaultAdminPermissionsDatabaseRoutes = () => [];
const getDefaultAdminPermissionsDatabaseGroupRoutes = () => [];
const getDefaultAdminPermissionsDatabasePostActions = () => ({
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index 40e963bacec..cb547da76e7 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -2,7 +2,6 @@ import type { LocationDescriptorObject } from "history";
import querystring from "querystring";
import { replace } from "react-router-redux";
-import { databaseApi } from "metabase/api";
import Questions from "metabase/entities/questions";
import Snippets from "metabase/entities/snippets";
import { deserializeCardFromUrl } from "metabase/lib/card";
@@ -15,9 +14,8 @@ import {
} from "metabase/query_builder/selectors";
import { loadMetadataForCard } from "metabase/questions/actions";
import { setErrorPage } from "metabase/redux/app";
-import { getHasDataAccess } from "metabase/selectors/data";
import { getMetadata } from "metabase/selectors/metadata";
-import { getUser } from "metabase/selectors/user";
+import { canUserCreateQueries, getUser } from "metabase/selectors/user";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
@@ -204,17 +202,6 @@ export async function resolveCards({
);
}
-async function loadDatabases(dispatch: any) {
- const action = databaseApi.endpoints.listDatabases.initiate();
- try {
- const { data } = await dispatch(action).unwrap();
- return data;
- } catch (error) {
- console.error("error loading databases", error);
- return [];
- }
-}
-
export function parseHash(hash?: string) {
let options: BlankQueryOptions = {};
let serializedCard;
@@ -287,8 +274,7 @@ async function handleQBInit(
const currentUser = getUser(getState());
if (uiControls.queryBuilderMode === "notebook") {
- const databases = await loadDatabases(dispatch);
- if (!getHasDataAccess(databases)) {
+ if (!canUserCreateQueries(getState())) {
dispatch(replace(Urls.unauthorized()));
return;
}
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
index 77ec7a1982f..152a2d54028 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
@@ -22,7 +22,11 @@ import type {
UnsavedCard,
User,
} from "metabase-types/api";
-import { createMockSegment, createMockUser } from "metabase-types/api/mocks";
+import {
+ createMockSegment,
+ createMockUser,
+ createMockUserPermissions,
+} from "metabase-types/api/mocks";
import {
ORDERS_ID,
SAMPLE_DB_ID,
@@ -61,23 +65,25 @@ async function baseSetup({
hasDataPermissions = true,
}: BaseSetupOpts) {
jest.useFakeTimers();
-
- const databases = hasDataPermissions ? [createSampleDatabase()] : [];
- const dispatch = jest
- .fn()
- .mockReturnValue({ unwrap: () => ({ data: databases }) });
-
const state = createMockState({
entities: createMockEntitiesState({
- databases,
+ databases: hasDataPermissions ? [createSampleDatabase()] : [],
segments: [SEGMENT],
}),
- currentUser: user === undefined ? createMockUser() : user,
+ currentUser:
+ user === undefined
+ ? createMockUser({
+ permissions: createMockUserPermissions({
+ can_create_queries: hasDataPermissions,
+ }),
+ })
+ : user,
});
const metadata = getMetadata(state);
const getState = () => state;
+ const dispatch = jest.fn();
await initializeQB(location, params)(dispatch, getState);
jest.runAllTimers();
diff --git a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx
index 849cfa5226b..be5664c62fd 100644
--- a/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx
@@ -6,6 +6,7 @@ import {
setupCollectionByIdEndpoint,
setupCollectionItemsEndpoint,
setupCollectionsEndpoints,
+ setupDatabasesEndpoints,
setupMostRecentlyViewedDashboard,
setupRecentViewsAndSelectionsEndpoints,
setupSearchEndpoints,
@@ -235,6 +236,7 @@ const setup = async ({
setupRecentViewsAndSelectionsEndpoints([]);
setupMostRecentlyViewedDashboard(mostRecentlyViewedDashboard);
setupSearchEndpoints(searchResults);
+ setupDatabasesEndpoints([]);
collections.forEach((collection) => {
setupCollectionItemsEndpoint({
diff --git a/frontend/src/metabase/query_builder/components/DataSelector/DataSelector.jsx b/frontend/src/metabase/query_builder/components/DataSelector/DataSelector.jsx
index 1117282fe90..b89ff6a91b4 100644
--- a/frontend/src/metabase/query_builder/components/DataSelector/DataSelector.jsx
+++ b/frontend/src/metabase/query_builder/components/DataSelector/DataSelector.jsx
@@ -14,9 +14,9 @@ import Schemas from "metabase/entities/schemas";
import Search from "metabase/entities/search";
import Tables from "metabase/entities/tables";
import { connect } from "metabase/lib/redux";
-import { getHasDataAccess } from "metabase/selectors/data";
import { getMetadata } from "metabase/selectors/metadata";
import { getSetting } from "metabase/selectors/settings";
+import { canUserCreateQueries } from "metabase/selectors/user";
import { Box, Popover } from "metabase/ui";
import {
SAVED_QUESTIONS_VIRTUAL_DB_ID,
@@ -1083,7 +1083,7 @@ const DataSelector = _.compose(
hasLoadedDatabasesWithTables: Databases.selectors.getLoaded(state, {
entityQuery: { include: "tables" },
}),
- hasDataAccess: getHasDataAccess(ownProps.allDatabases ?? []),
+ hasDataAccess: canUserCreateQueries(state),
hasNestedQueriesEnabled: getSetting(state, "enable-nested-queries"),
selectedQuestion: Questions.selectors.getObject(state, {
entityId: getQuestionIdFromVirtualTableId(ownProps.selectedTableId),
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.js b/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.js
index 7719aa86dd0..306d4638633 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.js
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.js
@@ -3,6 +3,7 @@ import fetchMock from "fetch-mock";
import { Route } from "react-router";
import _ from "underscore";
+import { setupTableEndpoints } from "__support__/server-mocks";
import { setupGetUserKeyValueEndpoint } from "__support__/server-mocks/user-key-value";
import { createMockEntitiesState } from "__support__/store";
import { fireEvent, renderWithProviders, screen } from "__support__/ui";
@@ -27,6 +28,7 @@ import { ViewTitleHeader } from "./ViewTitleHeader";
console.warn = jest.fn();
console.error = jest.fn();
+const ORDERS_TABLE = createOrdersTable();
const PRODUCTS_TABLE = createProductsTable();
const HIDDEN_ORDERS_TABLE = createOrdersTable({
visibility_type: "hidden",
@@ -121,6 +123,8 @@ function setup({
} = {}) {
mockSettings(settings);
+ setupTableEndpoints(ORDERS_TABLE);
+ setupTableEndpoints(PRODUCTS_TABLE);
setupGetUserKeyValueEndpoint({
namespace: "user_acknowledgement",
key: "turn_into_model_modal",
@@ -297,11 +301,13 @@ describe("ViewTitleHeader", () => {
const { card, questionType } = testCase;
describe(questionType, () => {
- it("displays database and table names", () => {
+ it("displays database and table names", async () => {
setup({ card });
- expect(screen.getByText("Sample Database")).toBeInTheDocument();
- expect(screen.getByText("Orders")).toBeInTheDocument();
+ expect(
+ await screen.findByText("Sample Database"),
+ ).toBeInTheDocument();
+ expect(await screen.findByText("Orders")).toBeInTheDocument();
});
it("offers to filter query results", () => {
@@ -422,11 +428,11 @@ describe("ViewTitleHeader", () => {
});
describe("ViewHeader | Ad-hoc GUI question", () => {
- it("does not open details sidebar on table name click", () => {
+ it("does not open details sidebar on table name click", async () => {
const { question, onOpenModal } = setupAdHoc();
const tableName = question.legacyQueryTable().displayName();
- fireEvent.click(screen.getByText(tableName));
+ fireEvent.click(await screen.findByText(tableName));
expect(onOpenModal).not.toHaveBeenCalled();
});
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/HeaderBreadcrumbs/HeaderBreadcrumbs.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/HeaderBreadcrumbs/HeaderBreadcrumbs.tsx
index 998a0e0bc55..c6d977a1807 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/HeaderBreadcrumbs/HeaderBreadcrumbs.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/HeaderBreadcrumbs/HeaderBreadcrumbs.tsx
@@ -35,6 +35,7 @@ function getBadgeInactiveColor({
}
interface HeadBreadcrumbsProps {
+ className?: string;
variant?: "head" | "subhead";
parts: DataSourcePart[];
divider?: string | ReactElement;
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/DataSourceCrumbs.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/DataSourceCrumbs.tsx
index 11b8b18122b..9ce00004e93 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/DataSourceCrumbs.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/DataSourceCrumbs.tsx
@@ -7,6 +7,7 @@ import { HeadBreadcrumbs } from "../HeaderBreadcrumbs/HeaderBreadcrumbs";
import { getDataSourceParts } from "./utils";
interface Props {
+ className?: string;
divider?: ReactElement | string;
question: Question;
variant: "head" | "subhead";
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.tsx
index e827751d7e9..469dfe2f72f 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.tsx
@@ -6,16 +6,17 @@ import {
} from "metabase-lib/v1/metadata/utils/saved-questions";
import { DataSourceCrumbs } from "./DataSourceCrumbs";
-import { SourceDatasetBreadcrumbs } from "./SourceDatasetBreadcrumbs";
+import { SourceModelBreadcrumbs } from "./SourceModelBreadcrumbs";
import { SourceQuestionBreadcrumbs } from "./SourceQuestionBreadcrumbs";
+import { SourceTableBreadcrumbs } from "./SourceTableBreadcrumbs";
import { getDataSourceParts } from "./utils";
interface QuestionDataSourceProps {
+ className?: string;
question: Question;
originalQuestion?: Question;
subHead?: boolean;
isObjectDetail?: boolean;
- className?: string;
}
export function QuestionDataSource({
@@ -36,15 +37,25 @@ export function QuestionDataSource({
const variant = subHead ? "subhead" : "head";
- if (isNative || !isVirtualCardId(sourceTableId)) {
+ if (isNative) {
return (
<DataSourceCrumbs question={question} variant={variant} {...props} />
);
}
+ if (!isVirtualCardId(sourceTableId)) {
+ return (
+ <SourceTableBreadcrumbs
+ question={question}
+ variant={variant}
+ {...props}
+ />
+ );
+ }
+
if (originalQuestion?.id() === sourceQuestionId) {
return (
- <SourceDatasetBreadcrumbs
+ <SourceModelBreadcrumbs
question={originalQuestion}
variant={variant}
{...props}
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.js b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.js
index 4c19eb74df4..1c632528849 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.js
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.js
@@ -2,7 +2,10 @@
import { Component } from "react";
import { createMockMetadata } from "__support__/metadata";
-import { setupCardEndpoints } from "__support__/server-mocks/card";
+import {
+ setupCardEndpoints,
+ setupTableEndpoints,
+} from "__support__/server-mocks";
import { getIcon, renderWithProviders, screen } from "__support__/ui";
import { deserializeCardFromUrl } from "metabase/lib/card";
import * as Urls from "metabase/lib/urls";
@@ -24,6 +27,9 @@ import {
PRODUCTS,
PRODUCTS_ID,
SAMPLE_DB_ID,
+ createOrdersTable,
+ createPeopleTable,
+ createProductsTable,
createSampleDatabase,
} from "metabase-types/api/mocks/presets";
@@ -156,24 +162,29 @@ const SOURCE_QUESTION_COLLECTION_SCHEMA_NAME = "Everything else";
// Factories
+const ORDERS_TABLE = createOrdersTable();
+const PRODUCTS_TABLE = createProductsTable();
+const PEOPLE_TABLE = createPeopleTable();
+
+const MULTI_SCHEMA_TABLE1 = createMockTable({
+ id: MULTI_SCHEMA_TABLE1_ID,
+ db_id: MULTI_SCHEMA_DB_ID,
+ schema: "first_schema",
+});
+
+const MULTI_SCHEMA_TABLE2 = createMockTable({
+ id: MULTI_SCHEMA_TABLE2_ID,
+ db_id: MULTI_SCHEMA_DB_ID,
+ schema: "second_schema",
+});
+
function getMetadata() {
return createMockMetadata({
databases: [
createSampleDatabase(),
createMockDatabase({
id: MULTI_SCHEMA_DB_ID,
- tables: [
- createMockTable({
- id: MULTI_SCHEMA_TABLE1_ID,
- db_id: MULTI_SCHEMA_DB_ID,
- schema: "first_schema",
- }),
- createMockTable({
- id: MULTI_SCHEMA_TABLE2_ID,
- db_id: MULTI_SCHEMA_DB_ID,
- schema: "second_schema",
- }),
- ],
+ tables: [MULTI_SCHEMA_TABLE1, MULTI_SCHEMA_TABLE2],
}),
],
});
@@ -223,6 +234,11 @@ function setup({
const originalQuestion = originalCard && new Question(originalCard, metadata);
setupCardEndpoints(SOURCE_CARD);
+ setupTableEndpoints(ORDERS_TABLE);
+ setupTableEndpoints(PRODUCTS_TABLE);
+ setupTableEndpoints(PEOPLE_TABLE);
+ setupTableEndpoints(MULTI_SCHEMA_TABLE1);
+ setupTableEndpoints(MULTI_SCHEMA_TABLE2);
const onError = jest.fn();
renderWithProviders(
@@ -345,9 +361,11 @@ describe("QuestionDataSource", () => {
const { card, questionType } = testCase;
describe(questionType, () => {
- it("displays database name", () => {
+ it("displays database name", async () => {
const { question } = setup({ card });
- const node = screen.queryByText(question.database().displayName());
+ const node = await screen.findByText(
+ question.database().displayName(),
+ );
expect(node).toBeInTheDocument();
expect(node.closest("a")).toHaveAttribute(
"href",
@@ -355,10 +373,10 @@ describe("QuestionDataSource", () => {
);
});
- it("shows nothing if a user doesn't have data permissions", () => {
+ it("shows nothing if a user doesn't have data permissions", async () => {
setup({ card, hasPermissions: false });
expect(
- screen.getByTestId("head-crumbs-container"),
+ await screen.findByTestId("head-crumbs-container"),
).toBeEmptyDOMElement();
});
});
@@ -370,18 +388,18 @@ describe("QuestionDataSource", () => {
const { card, questionType } = testCase;
describe(questionType, () => {
- it("displays table name", () => {
+ it("displays table name", async () => {
const { question } = setup({ card });
- const node = screen.queryByText(
+ const node = await screen.findByText(
new RegExp(question.legacyQueryTable().displayName()),
);
expect(node).toBeInTheDocument();
expect(node.closest("a")).not.toBeInTheDocument();
});
- it("displays table link in subhead variant", () => {
+ it("displays table link in subhead variant", async () => {
const { question } = setup({ card, subHead: true });
- const node = screen.queryByText(
+ const node = await screen.findByText(
new RegExp(question.legacyQueryTable().displayName()),
);
expect(
@@ -392,9 +410,9 @@ describe("QuestionDataSource", () => {
).toBe(true);
});
- it("displays table link in object detail view", () => {
+ it("displays table link in object detail view", async () => {
const { question } = setup({ card, isObjectDetail: true });
- const node = screen.queryByText(
+ const node = await screen.findByText(
new RegExp(question.legacyQueryTable().displayName()),
);
expect(
@@ -416,9 +434,9 @@ describe("QuestionDataSource", () => {
const { card, questionType } = testCase;
describe(questionType, () => {
- it("displays schema name", () => {
+ it("displays schema name", async () => {
const { question } = setup({ card });
- const node = screen.queryByText(
+ const node = await screen.findByText(
question.legacyQueryTable().schema_name,
);
expect(node).toBeInTheDocument();
@@ -439,11 +457,11 @@ describe("QuestionDataSource", () => {
const { card, questionType } = testCase;
describe(questionType, () => {
- it("displays 2 joined tables (metabase#17961)", () => {
+ it("displays 2 joined tables (metabase#17961)", async () => {
setup({ card, subHead: true });
- const orders = screen.queryByText(/Orders/);
- const products = screen.queryByText(/Products/);
+ const orders = await screen.findByText(/Orders/);
+ const products = await screen.findByText(/Products/);
expect(orders).toBeInTheDocument();
expect(
@@ -470,12 +488,12 @@ describe("QuestionDataSource", () => {
const { card, questionType } = testCase;
describe(questionType, () => {
- it("displays > 2 joined tables (metabase#17961)", () => {
+ it("displays > 2 joined tables (metabase#17961)", async () => {
setup({ card, subHead: true });
- const orders = screen.queryByText(/Orders/);
- const products = screen.queryByText(/Products/);
- const people = screen.queryByText(/People/);
+ const orders = await screen.findByText(/Orders/);
+ const products = await screen.findByText(/Products/);
+ const people = await screen.findByText(/People/);
expect(orders).toBeInTheDocument();
expect(
@@ -566,12 +584,12 @@ describe("QuestionDataSource", () => {
});
});
- it("should show info icon on an ad-hoc question header", () => {
+ it("should show info icon on an ad-hoc question header", async () => {
setup({ card: SOURCE_CARD });
- expect(screen.getByLabelText("More info")).toBeInTheDocument();
+ expect(await screen.findByLabelText("More info")).toBeInTheDocument();
});
- it("should show info icon on a subheader", () => {
+ it("should show info icon on a subheader", async () => {
setup({ card: SOURCE_CARD, subHead: true });
expect(screen.queryByLabelText("More info")).not.toBeInTheDocument();
});
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceDatasetBreadcrumbs.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceModelBreadcrumbs.tsx
similarity index 86%
rename from frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceDatasetBreadcrumbs.tsx
rename to frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceModelBreadcrumbs.tsx
index bd5feddd122..0a6582ee129 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceDatasetBreadcrumbs.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceModelBreadcrumbs.tsx
@@ -10,23 +10,23 @@ import { HeadBreadcrumbs } from "../HeaderBreadcrumbs/HeaderBreadcrumbs";
import { getQuestionIcon } from "./utils";
-interface SourceDatasetBreadcrumbsProps {
+interface SourceModelBreadcrumbsProps {
divider?: ReactElement | string;
question: Question;
variant: "head" | "subhead";
}
-export function SourceDatasetBreadcrumbs({
+export function SourceModelBreadcrumbs({
question,
...props
-}: SourceDatasetBreadcrumbsProps) {
+}: SourceModelBreadcrumbsProps) {
const collectionId = question.collectionId();
- const { data: collection, isFetching } = useGetCollectionQuery(
+ const { data: collection, isLoading } = useGetCollectionQuery(
collectionId ? { id: collectionId } : skipToken,
);
- if (isFetching) {
+ if (isLoading) {
return null;
}
@@ -35,7 +35,7 @@ export function SourceDatasetBreadcrumbs({
{...props}
parts={[
<HeadBreadcrumbs.Badge
- key="dataset-collection"
+ key="collection"
to={Urls.collection(collection)}
icon={getQuestionIcon(question)}
inactiveColor="text-light"
@@ -44,7 +44,7 @@ export function SourceDatasetBreadcrumbs({
</HeadBreadcrumbs.Badge>,
question.isArchived() ? (
<Tooltip
- key="dataset-name"
+ key="name"
label={t`This model is archived and shouldn't be used.`}
maw="auto"
position="bottom"
@@ -62,6 +62,7 @@ export function SourceDatasetBreadcrumbs({
</Tooltip>
) : (
<HeadBreadcrumbs.Badge
+ key="name"
to={Urls.question(question.card())}
inactiveColor="text-light"
>
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceQuestionBreadcrumbs.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceQuestionBreadcrumbs.tsx
index c4f052d1e84..fb204a46913 100644
--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceQuestionBreadcrumbs.tsx
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceQuestionBreadcrumbs.tsx
@@ -8,7 +8,7 @@ import Question from "metabase-lib/v1/Question";
import { getQuestionIdFromVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";
import { DataSourceCrumbs } from "./DataSourceCrumbs";
-import { SourceDatasetBreadcrumbs } from "./SourceDatasetBreadcrumbs";
+import { SourceModelBreadcrumbs } from "./SourceModelBreadcrumbs";
interface Props {
divider?: ReactElement | string;
@@ -39,7 +39,7 @@ export function SourceQuestionBreadcrumbs({
if (sourceQuestion.type() === "model" || sourceQuestion.type() === "metric") {
return (
- <SourceDatasetBreadcrumbs
+ <SourceModelBreadcrumbs
question={sourceQuestion}
variant={variant}
{...props}
diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceTableBreadcrumbs.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceTableBreadcrumbs.tsx
new file mode 100644
index 00000000000..18c1036ced7
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/SourceTableBreadcrumbs.tsx
@@ -0,0 +1,97 @@
+import type { ReactElement } from "react";
+
+import { skipToken, useGetTableQuery } from "metabase/api";
+import { TableInfoIcon } from "metabase/common/components/MetadataInfo/TableInfoIcon/TableInfoIcon";
+import * as Urls from "metabase/lib/urls";
+import * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
+
+import { HeadBreadcrumbs } from "../HeaderBreadcrumbs/HeaderBreadcrumbs";
+import HeaderS from "../HeaderBreadcrumbs/HeaderBreadcrumbs.module.css";
+
+import { DataSourceCrumbs } from "./DataSourceCrumbs";
+import S from "./QuestionDataSource.module.css";
+
+type SourceTableBreadcrumbsProps = {
+ className?: string;
+ question: Question;
+ variant: "head" | "subhead";
+ divider?: ReactElement | string;
+ isObjectDetail?: boolean;
+};
+
+export function SourceTableBreadcrumbs({
+ className,
+ question,
+ variant,
+ divider,
+ isObjectDetail,
+}: SourceTableBreadcrumbsProps) {
+ const query = question.query();
+ const tableId = Lib.sourceTableOrCardId(query);
+ const isSubhead = variant === "subhead";
+ const hasTableLink = isSubhead || isObjectDetail;
+
+ const { data: table, isLoading } = useGetTableQuery(
+ tableId != null ? { id: tableId } : skipToken,
+ );
+
+ if (table == null || isLoading) {
+ return null;
+ }
+
+ const collection = table.collection;
+ if (collection == null) {
+ return (
+ <DataSourceCrumbs
+ className={className}
+ question={question}
+ variant={variant}
+ divider={divider}
+ isObjectDetail={isObjectDetail}
+ />
+ );
+ }
+
+ return (
+ <HeadBreadcrumbs
+ className={className}
+ variant={variant}
+ divider={divider}
+ parts={[
+ <HeadBreadcrumbs.Badge
+ key="collection"
+ to={Urls.collection(collection)}
+ icon="repository"
+ inactiveColor="text-light"
+ >
+ {collection.name}
+ </HeadBreadcrumbs.Badge>,
+ <HeadBreadcrumbs.Badge
+ key="name"
+ to={
+ hasTableLink
+ ? Urls.queryBuilderTable(table.id, table.db_id)
+ : undefined
+ }
+ inactiveColor={isSubhead ? "text-light" : "text-dark"}
+ >
+ <span>
+ {table.display_name}
+ {!isSubhead && (
+ <span className={S.IconWrapper}>
+ <TableInfoIcon
+ table={table}
+ icon="info"
+ size={16}
+ position="bottom"
+ className={HeaderS.HeaderBadgeIcon}
+ />
+ </span>
+ )}
+ </span>
+ </HeadBreadcrumbs.Badge>,
+ ]}
+ />
+ );
+}
diff --git a/frontend/src/metabase/query_builder/containers/test-utils.tsx b/frontend/src/metabase/query_builder/containers/test-utils.tsx
index 5356648fa7e..1a9173a19fc 100644
--- a/frontend/src/metabase/query_builder/containers/test-utils.tsx
+++ b/frontend/src/metabase/query_builder/containers/test-utils.tsx
@@ -52,6 +52,8 @@ import {
createMockStructuredDatasetQuery,
createMockStructuredQuery,
createMockUnsavedCard,
+ createMockUser,
+ createMockUserPermissions,
} from "metabase-types/api/mocks";
import {
ORDERS,
@@ -60,6 +62,7 @@ import {
createSampleDatabase,
} from "metabase-types/api/mocks/presets";
import type { RequestState, State } from "metabase-types/store";
+import { createMockState } from "metabase-types/store/mocks";
import { QueryBuilder } from "./QueryBuilder";
@@ -305,6 +308,14 @@ export const setup = async ({
{
withRouter: true,
initialRoute,
+ storeInitialState: createMockState({
+ currentUser: createMockUser({
+ permissions: createMockUserPermissions({
+ can_create_queries: true,
+ can_create_native_queries: true,
+ }),
+ }),
+ }),
},
);
diff --git a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx
index f222a1d71fd..7165766796e 100644
--- a/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx
+++ b/frontend/src/metabase/querying/notebook/components/Notebook/Notebook.unit.spec.tsx
@@ -33,11 +33,7 @@ import {
createQueryWithClauses,
} from "metabase-lib/test-helpers";
import Question from "metabase-lib/v1/Question";
-import type {
- CardType,
- CollectionItemModel,
- RecentItem,
-} from "metabase-types/api";
+import type { CardType, RecentItem } from "metabase-types/api";
import {
createMockCard,
createMockCollection,
@@ -160,7 +156,7 @@ function setup({
const collectionItems = TEST_ENTITY_TYPES.map((entityType) =>
createMockCollectionItem({
- model: entityType as CollectionItemModel,
+ model: entityType,
collection: TEST_COLLECTION,
collection_id: TEST_COLLECTION.id,
name: entityType,
@@ -350,7 +346,7 @@ describe("Notebook", () => {
});
});
- describe.each<DataPickerValue["model"]>(TEST_ENTITY_TYPES)(
+ describe.each<DataPickerValue["model"]>(["metric", "card", "dataset"])(
"when filtering with %s",
(entityType) => {
it(`should show the Collection item picker when modelsFilterList=[${entityType}]`, async () => {
diff --git a/frontend/src/metabase/querying/segments/components/SegmentEditorV2/SegmentEditorV2.tsx b/frontend/src/metabase/querying/segments/components/SegmentEditorV2/SegmentEditorV2.tsx
new file mode 100644
index 00000000000..5276729a692
--- /dev/null
+++ b/frontend/src/metabase/querying/segments/components/SegmentEditorV2/SegmentEditorV2.tsx
@@ -0,0 +1,87 @@
+import { useCallback, useMemo } from "react";
+import { t } from "ttag";
+
+import ErrorBoundary from "metabase/ErrorBoundary";
+import { FilterPicker } from "metabase/querying/filters/components/FilterPicker";
+import { ClauseStep } from "metabase/querying/notebook/components/ClauseStep";
+import { color } from "metabase/ui/utils/colors";
+import * as Lib from "metabase-lib";
+
+const STAGE_INDEX = -1;
+
+type SegmentEditorV2Props = {
+ query: Lib.Query;
+ onChange: (query: Lib.Query) => void;
+ readOnly?: boolean;
+};
+
+export function SegmentEditorV2({
+ query,
+ onChange,
+ readOnly = false,
+}: SegmentEditorV2Props) {
+ const filters = useMemo(() => Lib.filters(query, STAGE_INDEX), [query]);
+
+ const renderFilterName = useCallback(
+ (filter: Lib.FilterClause) =>
+ Lib.displayInfo(query, STAGE_INDEX, filter).longDisplayName,
+ [query],
+ );
+
+ const handleSelectFilter = useCallback(
+ (filter: Lib.FilterClause | undefined, newFilter: Lib.Filterable) => {
+ const nextQuery = filter
+ ? Lib.replaceClause(query, STAGE_INDEX, filter, newFilter)
+ : Lib.filter(query, STAGE_INDEX, newFilter);
+ onChange(nextQuery);
+ },
+ [query, onChange],
+ );
+
+ const handleReorderFilter = useCallback(
+ (sourceClause: Lib.FilterClause, targetClause: Lib.FilterClause) => {
+ const nextQuery = Lib.swapClauses(
+ query,
+ STAGE_INDEX,
+ sourceClause,
+ targetClause,
+ );
+ onChange(nextQuery);
+ },
+ [query, onChange],
+ );
+
+ const handleRemoveFilter = useCallback(
+ (clause: Lib.FilterClause) => {
+ const nextQuery = Lib.removeClause(query, STAGE_INDEX, clause);
+ onChange(nextQuery);
+ },
+ [query, onChange],
+ );
+
+ return (
+ <ErrorBoundary>
+ <ClauseStep
+ items={filters}
+ initialAddText={t`Add filters to narrow your answer`}
+ readOnly={readOnly}
+ color={color("filter")}
+ isLastOpened={false}
+ renderName={renderFilterName}
+ renderPopover={({ item: filter, index, onClose }) => (
+ <FilterPicker
+ query={query}
+ stageIndex={STAGE_INDEX}
+ filter={filter}
+ filterIndex={index}
+ onSelect={(newFilter) => handleSelectFilter(filter, newFilter)}
+ onClose={onClose}
+ readOnly={readOnly}
+ />
+ )}
+ onReorder={handleReorderFilter}
+ onRemove={handleRemoveFilter}
+ />
+ </ErrorBoundary>
+ );
+}
diff --git a/frontend/src/metabase/querying/segments/components/SegmentEditorV2/index.ts b/frontend/src/metabase/querying/segments/components/SegmentEditorV2/index.ts
new file mode 100644
index 00000000000..7a65b053ccb
--- /dev/null
+++ b/frontend/src/metabase/querying/segments/components/SegmentEditorV2/index.ts
@@ -0,0 +1 @@
+export { SegmentEditorV2 } from "./SegmentEditorV2";
diff --git a/frontend/src/metabase/querying/segments/index.ts b/frontend/src/metabase/querying/segments/index.ts
new file mode 100644
index 00000000000..507335839d4
--- /dev/null
+++ b/frontend/src/metabase/querying/segments/index.ts
@@ -0,0 +1 @@
+export { SegmentEditorV2 } from "./components/SegmentEditorV2";
diff --git a/frontend/src/metabase/schema.js b/frontend/src/metabase/schema.js
index 75aee106a17..77c8f645dfa 100644
--- a/frontend/src/metabase/schema.js
+++ b/frontend/src/metabase/schema.js
@@ -94,6 +94,7 @@ TableSchema.define({
metrics: [QuestionSchema],
segments: [SegmentSchema],
schema: SchemaSchema,
+ collection: CollectionSchema,
});
FieldSchema.define({
diff --git a/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx b/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx
index aa2b5f0398f..3b84d81f323 100644
--- a/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx
+++ b/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx
@@ -164,11 +164,27 @@ describe("InfoText", () => {
);
});
- it("shows table's schema", async () => {
+ it("shows table's collection when the table is in a collection", async () => {
await setup({
model: "table",
});
+ const collectionLink = screen.getByText("Collection Name");
+ expect(collectionLink).toBeInTheDocument();
+ expect(collectionLink).toHaveAttribute(
+ "href",
+ `/collection/${MOCK_COLLECTION.id}-collection-name`,
+ );
+ });
+
+ it("shows table's schema when the table is not in a collection", async () => {
+ await setup({
+ model: "table",
+ resultProps: {
+ collection: createMockCollection({ id: undefined, name: undefined }),
+ },
+ });
+
const databaseLink = screen.getByText("Database Name");
expect(databaseLink).toBeInTheDocument();
expect(databaseLink).toHaveAttribute(
diff --git a/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx b/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx
index a9cb679d1cd..c6edfdb9295 100644
--- a/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx
+++ b/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx
@@ -132,7 +132,7 @@ export const InfoTextAssetLink = ({
result,
showLinks = true,
}: InfoTextAssetLinkProps) => {
- if (result.model === "table") {
+ if (result.model === "table" && result.collection?.name == null) {
return <InfoTextTablePath showLinks={showLinks} result={result} />;
}
diff --git a/frontend/src/metabase/search/components/filters/NativeQueryFilter/NativeQueryLabel.tsx b/frontend/src/metabase/search/components/filters/NativeQueryFilter/NativeQueryLabel.tsx
index b205388ba40..6a9e8cd008b 100644
--- a/frontend/src/metabase/search/components/filters/NativeQueryFilter/NativeQueryLabel.tsx
+++ b/frontend/src/metabase/search/components/filters/NativeQueryFilter/NativeQueryLabel.tsx
@@ -1,14 +1,10 @@
import { t } from "ttag";
-import { useDatabaseListQuery } from "metabase/common/hooks";
-import { getHasNativeWrite } from "metabase/selectors/data";
+import { useSelector } from "metabase/lib/redux";
+import { canUserCreateNativeQueries } from "metabase/selectors/user";
export const NativeQueryLabel = () => {
- const { data: databases = [] } = useDatabaseListQuery();
-
- const hasNativeWrite = getHasNativeWrite(databases);
-
+ const hasNativeWrite = useSelector(canUserCreateNativeQueries);
const filterLabel = hasNativeWrite ? t`native` : `SQL`;
-
return `Search the contents of ${filterLabel} queries`;
};
diff --git a/frontend/src/metabase/selectors/data.ts b/frontend/src/metabase/selectors/data.ts
index 26a49923328..fe92409d755 100644
--- a/frontend/src/metabase/selectors/data.ts
+++ b/frontend/src/metabase/selectors/data.ts
@@ -2,22 +2,10 @@ import { getEngineNativeType } from "metabase/lib/engine";
import type DatabaseEntity from "metabase-lib/v1/metadata/Database";
import type { Database } from "metabase-types/api";
-export const getHasDataAccess = (
- databases: Pick<Database | DatabaseEntity, "is_saved_questions">[],
-) => {
- return databases.some((d) => !d.is_saved_questions);
-};
-
export const getHasOwnDatabase = (databases: (Database | DatabaseEntity)[]) => {
return databases.some((d) => !d.is_sample && !d.is_saved_questions);
};
-export const getHasNativeWrite = (
- databases: Pick<Database | DatabaseEntity, "native_permissions">[],
-) => {
- return databases.some((d) => d.native_permissions === "write");
-};
-
export const getHasDatabaseWithJsonEngine = (
databases: (Database | DatabaseEntity)[],
) => {
diff --git a/frontend/src/metabase/selectors/data.unit.spec.ts b/frontend/src/metabase/selectors/data.unit.spec.ts
index 0ed9a7e482c..ca819927c3d 100644
--- a/frontend/src/metabase/selectors/data.unit.spec.ts
+++ b/frontend/src/metabase/selectors/data.unit.spec.ts
@@ -3,12 +3,7 @@ import { checkNotNull } from "metabase/lib/types";
import type { Database } from "metabase-types/api";
import { createMockDatabase } from "metabase-types/api/mocks";
-import {
- getHasDataAccess,
- getHasDatabaseWithJsonEngine,
- getHasNativeWrite,
- getHasOwnDatabase,
-} from "./data";
+import { getHasDatabaseWithJsonEngine, getHasOwnDatabase } from "./data";
const setup = (databases: Database[]) => {
const metadata = createMockMetadata({ databases });
@@ -16,28 +11,6 @@ const setup = (databases: Database[]) => {
};
describe("metabase/selectors/data", () => {
- describe("getHasDataAccess", () => {
- it("should return true if user has access to at least one database, even if it's the one with sample data", () => {
- const databases = setup([
- createMockDatabase({
- is_saved_questions: false,
- }),
- ]);
-
- expect(getHasDataAccess(databases)).toBe(true);
- });
-
- it("should return false if user does not have access to at least one real database", () => {
- const databases = setup([
- createMockDatabase({
- is_saved_questions: true,
- }),
- ]);
-
- expect(getHasDataAccess(databases)).toBe(false);
- });
- });
-
describe("getHasOwnDatabase", () => {
it("user has at least one database, and the one with sample data does not count", () => {
const databases = setup([
@@ -62,28 +35,6 @@ describe("metabase/selectors/data", () => {
});
});
- describe("getHasNativeWrite", () => {
- it("user has permissions to write to at least one database", () => {
- const databases = setup([
- createMockDatabase({
- native_permissions: "write",
- }),
- ]);
-
- expect(getHasNativeWrite(databases)).toBe(true);
- });
-
- it("user does not have permissions to write to at least one database", () => {
- const databases = setup([
- createMockDatabase({
- native_permissions: "none",
- }),
- ]);
-
- expect(getHasNativeWrite(databases)).toBe(false);
- });
- });
-
describe("getHasDatabaseWithJsonEngine", () => {
it("user has a json database", () => {
const databases = setup([
diff --git a/frontend/src/metabase/selectors/user.ts b/frontend/src/metabase/selectors/user.ts
index 666ade3c3df..bd9fc84ed37 100644
--- a/frontend/src/metabase/selectors/user.ts
+++ b/frontend/src/metabase/selectors/user.ts
@@ -39,3 +39,13 @@ export const getUserPersonalCollectionId = createSelector(
[getUser],
(user) => user?.personal_collection_id,
);
+
+export const canUserCreateQueries = createSelector(
+ [getUser],
+ (user) => user?.permissions?.can_create_queries ?? false,
+);
+
+export const canUserCreateNativeQueries = createSelector(
+ [getUser],
+ (user) => user?.permissions?.can_create_native_queries ?? false,
+);
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
index dbb1a7cec6f..7b370a185ef 100644
--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
@@ -352,6 +352,8 @@ import popular_component from "./popular.svg?component";
import popular_source from "./popular.svg?source";
import progress_component from "./progress.svg?component";
import progress_source from "./progress.svg?source";
+import publish_component from "./publish.svg?component";
+import publish_source from "./publish.svg?source";
import pulse_component from "./pulse.svg?component";
import pulse_source from "./pulse.svg?source";
import question_component from "./question.svg?component";
@@ -390,6 +392,8 @@ import section_component from "./section.svg?component";
import section_source from "./section.svg?source";
import segment_component from "./segment.svg?component";
import segment_source from "./segment.svg?source";
+import segment2_component from "./segment2.svg?component";
+import segment2_source from "./segment2.svg?source";
import send_component from "./send.svg?component";
import send_source from "./send.svg?source";
import settings_component from "./settings.svg?component";
@@ -492,6 +496,8 @@ import unknown_component from "./unknown.svg?component";
import unknown_source from "./unknown.svg?source";
import unpin_component from "./unpin.svg?component";
import unpin_source from "./unpin.svg?source";
+import unpublish_component from "./unpublish.svg?component";
+import unpublish_source from "./unpublish.svg?source";
import unsubscribe_component from "./unsubscribe.svg?component";
import unsubscribe_source from "./unsubscribe.svg?source";
import upload_component from "./upload.svg?component";
@@ -1209,6 +1215,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: embed_static_component,
source: embed_static_source,
},
+ publish: {
+ component: publish_component,
+ source: publish_source,
+ },
pulse: {
component: pulse_component,
source: pulse_source,
@@ -1337,6 +1347,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: segment_component,
source: segment_source,
},
+ segment2: {
+ component: segment2_component,
+ source: segment2_source,
+ },
send: {
component: send_component,
source: send_source,
@@ -1487,6 +1501,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: unpin_component,
source: unpin_source,
},
+ unpublish: {
+ component: unpublish_component,
+ source: unpublish_source,
+ },
unsubscribe: {
component: unsubscribe_component,
source: unsubscribe_source,
@@ -1761,6 +1779,7 @@ export type IconName =
| "popover"
| "popular"
| "progress"
+ | "publish"
| "pulse"
| "receipt"
| "recents"
@@ -1796,6 +1815,7 @@ export type IconName =
| "search"
| "section"
| "segment"
+ | "segment2"
| "shield"
| "shield_outline"
| "sidebar_closed"
@@ -1830,6 +1850,7 @@ export type IconName =
| "undo"
| "unknown"
| "unpin"
+ | "unpublish"
| "unsubscribe"
| "upload"
| "variable"
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/publish.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/publish.svg
new file mode 100644
index 00000000000..c49b9f75864
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/publish.svg
@@ -0,0 +1,2 @@
+<svg viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg"> <path d="M12.293 1.25a1.229 1.229 0 0 1 1.228 1.229v11.044a1.227 1.227 0 0 1-1.228 1.227h-7.67a2.149 2.149 0 0 1-2.136-1.935l-.012-.213V3.398A2.149 2.149 0 0 1 4.624 1.25h7.67zm-7.67 10.433a.92.92 0 0 0-.92.92l.005.09a.923.923 0 0 0 .916.83h7.67v-1.84h-7.67zm0-9.204a.92.92 0 0 0-.92.92v7.265c.286-.135.6-.209.92-.209h7.67V2.48h-7.67zM8 3.859c.338 0 .614.275.614.614v1.226h1.226a.615.615 0 0 1 0 1.228H8.613v1.227a.615.615 0 0 1-1.229 0V6.927H6.158a.614.614 0 1 1 0-1.228h1.226V4.473c0-.34.276-.615.615-.615z" />
+</svg>
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/segment2.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/segment2.svg
new file mode 100644
index 00000000000..239163a46b7
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/segment2.svg
@@ -0,0 +1,6 @@
+<svg viewBox="0 0 16 16" fill="none" stroke="currentcolor" xmlns="http://www.w3.org/2000/svg">
+ <path d="M10.3573 7.52888C10.2323 7.6539 10.1621 7.82344 10.1621 8.00021C10.1621 8.17699 10.2323 8.34653 10.3573 8.47155L11.9413 10.0562C12.0663 10.1812 12.2359 10.2514 12.4126 10.2514C12.5894 10.2514 12.7589 10.1812 12.884 10.0562L14.4686 8.47155C14.5936 8.34653 14.6638 8.17699 14.6638 8.00021C14.6638 7.82344 14.5936 7.6539 14.4686 7.52888L12.884 5.94421C12.7589 5.81923 12.5894 5.74902 12.4126 5.74902C12.2359 5.74902 12.0663 5.81923 11.9413 5.94421L10.3573 7.52888Z" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
+ <path d="M1.53113 7.52888C1.40615 7.6539 1.33594 7.82344 1.33594 8.00021C1.33594 8.17699 1.40615 8.34653 1.53113 8.47155L3.1158 10.0562C3.24081 10.1812 3.41035 10.2514 3.58713 10.2514C3.7639 10.2514 3.93344 10.1812 4.05846 10.0562L5.64313 8.47155C5.76811 8.34653 5.83832 8.17699 5.83832 8.00021C5.83832 7.82344 5.76811 7.6539 5.64313 7.52888L4.05846 5.94421C3.93344 5.81923 3.7639 5.74902 3.58713 5.74902C3.41035 5.74902 3.24081 5.81923 3.1158 5.94421L1.53113 7.52888Z" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
+ <path d="M5.94357 11.9413C5.88159 12.0032 5.83241 12.0767 5.79887 12.1577C5.76532 12.2386 5.74805 12.3254 5.74805 12.413C5.74805 12.5006 5.76532 12.5873 5.79887 12.6683C5.83241 12.7492 5.88159 12.8227 5.94357 12.8846L7.52824 14.4686C7.65326 14.5936 7.8228 14.6638 7.99957 14.6638C8.17635 14.6638 8.34589 14.5936 8.4709 14.4686L10.0556 12.8846C10.1176 12.8227 10.1667 12.7492 10.2003 12.6683C10.2338 12.5873 10.2511 12.5006 10.2511 12.413C10.2511 12.3254 10.2338 12.2386 10.2003 12.1577C10.1667 12.0767 10.1176 12.0032 10.0556 11.9413L8.4709 10.3573C8.34589 10.2323 8.17635 10.1621 7.99957 10.1621C7.8228 10.1621 7.65326 10.2323 7.52824 10.3573L5.94357 11.9413Z" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
+ <path d="M5.94421 3.1158C5.81923 3.24081 5.74902 3.41035 5.74902 3.58713C5.74902 3.7639 5.81923 3.93344 5.94421 4.05846L7.52888 5.64246C7.6539 5.76744 7.82344 5.83765 8.00021 5.83765C8.17699 5.83765 8.34653 5.76744 8.47155 5.64246L10.0562 4.05846C10.1812 3.93344 10.2514 3.7639 10.2514 3.58713C10.2514 3.41035 10.1812 3.24081 10.0562 3.1158L8.47155 1.53113C8.34653 1.40615 8.17699 1.33594 8.00021 1.33594C7.82344 1.33594 7.6539 1.40615 7.52888 1.53113L5.94421 3.1158Z" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>
+</svg>
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/unpublish.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/unpublish.svg
new file mode 100644
index 00000000000..bc3de73f656
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/unpublish.svg
@@ -0,0 +1,2 @@
+<svg viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg"> <path d="M12.298 1.25a1.23 1.23 0 0 1 1.228 1.229v11.044a1.227 1.227 0 0 1-1.228 1.227h-7.67a2.149 2.149 0 0 1-2.136-1.935l-.011-.213V3.398A2.148 2.148 0 0 1 4.628 1.25h7.67zm-7.67 10.433a.92.92 0 0 0-.92.92l.004.09a.923.923 0 0 0 .916.83h7.67v-1.84h-7.67zm0-9.204a.92.92 0 0 0-.92.92v7.265c.285-.135.599-.209.92-.209h7.67V2.48h-7.67zm5.216 3.68a.615.615 0 0 1 0 1.228H6.163a.614.614 0 1 1 0-1.228h3.681z" />
+</svg>
diff --git a/frontend/test/__support__/server-mocks/data-studio.ts b/frontend/test/__support__/server-mocks/data-studio.ts
new file mode 100644
index 00000000000..f954cf03ae0
--- /dev/null
+++ b/frontend/test/__support__/server-mocks/data-studio.ts
@@ -0,0 +1,36 @@
+import fetchMock from "fetch-mock";
+
+import {
+ createMockBulkTableSelectionInfo,
+ createMockPublishTablesResponse,
+} from "metabase-types/api/mocks";
+
+export function setupTableSelectionInfoEndpoint(
+ response = createMockBulkTableSelectionInfo(),
+) {
+ fetchMock.post("path:/api/ee/data-studio/table/selection", response);
+}
+
+export function setupPublishTablesEndpoint(
+ response = createMockPublishTablesResponse(),
+) {
+ fetchMock.post("path:/api/ee/data-studio/table/publish-tables", response);
+}
+
+export function setupPublishTablesEndpointError() {
+ fetchMock.post("path:/api/ee/data-studio/table/publish-tables", {
+ status: 500,
+ });
+}
+
+export function setupUnpublishTablesEndpoint() {
+ fetchMock.post("path:/api/ee/data-studio/table/unpublish-tables", {
+ status: 204,
+ });
+}
+
+export function setupUnpublishTablesEndpointError() {
+ fetchMock.post("path:/api/ee/data-studio/table/unpublish-tables", {
+ status: 500,
+ });
+}
diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.ts
index 6a9144091be..b0d10fd932c 100644
--- a/frontend/test/__support__/server-mocks/index.ts
+++ b/frontend/test/__support__/server-mocks/index.ts
@@ -13,6 +13,7 @@ export * from "./collection";
export * from "./comment";
export * from "./constants";
export * from "./dashboard";
+export * from "./data-studio";
export * from "./database";
export * from "./dataset";
export * from "./document";
diff --git a/frontend/test/__support__/server-mocks/library.ts b/frontend/test/__support__/server-mocks/library.ts
index 818b4beda49..1b4161d1f9d 100644
--- a/frontend/test/__support__/server-mocks/library.ts
+++ b/frontend/test/__support__/server-mocks/library.ts
@@ -1,6 +1,9 @@
import fetchMock from "fetch-mock";
-import { createMockCollectionItem } from "metabase-types/api/mocks";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+} from "metabase-types/api/mocks";
export const setupLibraryEndpoints = (hasLibrary?: boolean) => {
if (hasLibrary) {
@@ -23,3 +26,13 @@ export const setupLibraryEndpoints = (hasLibrary?: boolean) => {
});
}
};
+
+export function setupCreateLibraryEndpoint(
+ collection = createMockCollection(),
+) {
+ fetchMock.post("path:/api/ee/library", collection);
+}
+
+export function setupCreateLibraryEndpointError() {
+ fetchMock.post("path:/api/ee/library", { status: 500 });
+}
diff --git a/mage/test/mage/core_test.clj b/mage/test/mage/core_test.clj
index 1dfb80f48ed..b1ceef3e175 100644
--- a/mage/test/mage/core_test.clj
+++ b/mage/test/mage/core_test.clj
@@ -3,8 +3,8 @@
[babashka.tasks :as bt]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]
- [mage.merge-yaml-migrations-test :as merge-yaml-migrations-test]
[mage.alias-test]
+ [mage.merge-yaml-migrations-test :as merge-yaml-migrations-test]
[mage.token-scan-test]
[mage.util :as u]
[mage.util-test]))
diff --git a/resources/migrations/058_update_migrations.yaml b/resources/migrations/058_update_migrations.yaml
index 656a7f15c9c..7f5499c1248 100644
--- a/resources/migrations/058_update_migrations.yaml
+++ b/resources/migrations/058_update_migrations.yaml
@@ -835,6 +835,61 @@ databaseChangeLog:
tableName: segment
columnName: dependency_analysis_version
+ - changeSet:
+ id: v58.2025-11-25T17:41:50
+ author: metamben
+ comment: Add collection_id column to metabase_table for publishing tables to collections
+ changes:
+ - addColumn:
+ tableName: metabase_table
+ columns:
+ - column:
+ name: collection_id
+ type: int
+ remarks: The collection this table is published to (null if not published or published to root)
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v58.2025-11-25T17:41:51
+ author: metamben
+ comment: Add index on metabase_table.collection_id
+ changes:
+ - createIndex:
+ tableName: metabase_table
+ indexName: idx_metabase_table_collection_id
+ columns:
+ - column:
+ name: collection_id
+
+ - changeSet:
+ id: v58.2025-11-25T17:41:52
+ author: metamben
+ comment: Add foreign key constraint from metabase_table.collection_id to collection.id
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: metabase_table
+ baseColumnNames: collection_id
+ constraintName: fk_metabase_table_collection_id
+ referencedTableName: collection
+ referencedColumnNames: id
+
+ - changeSet:
+ id: v58.2025-11-25T17:41:53
+ author: metamben
+ comment: Add is_published column to metabase_table
+ changes:
+ - addColumn:
+ tableName: metabase_table
+ columns:
+ - column:
+ name: is_published
+ type: ${boolean.type}
+ remarks: Whether this table is published
+ defaultValueBoolean: false
+ constraints:
+ nullable: false
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
diff --git a/src/metabase/api/common.clj b/src/metabase/api/common.clj
index 6249985c555..385fa58fe1d 100644
--- a/src/metabase/api/common.clj
+++ b/src/metabase/api/common.clj
@@ -491,11 +491,16 @@
;;; ------------------------------------------ PARAM PARSING FNS ----------------------------------------
(defn bit->boolean
- "Coerce a bit returned by some MySQL/MariaDB versions in some situations to Boolean."
+ "Coerce a bit returned by some MySQL/MariaDB versions in some situations to Boolean.
+
+ MariaDB is especially strange: https://stackoverflow.com/questions/78466426/bit1-in-view-using-conditionals-in-mariadb-returns-48-49"
[v]
- (if (number? v)
- (not (zero? v))
- v))
+ (cond
+ (number? v) (not (zero? v))
+ (and (bytes? v) (= (count v) 1)) (case (char (first v))
+ \0 false
+ \1 true)
+ :else v))
(defn parse-multi-values-param
"Parse a param that could have a single value or multiple values using `parse-fn`.
diff --git a/src/metabase/collections/core.clj b/src/metabase/collections/core.clj
index 4824db8ac86..5446e84d168 100644
--- a/src/metabase/collections/core.clj
+++ b/src/metabase/collections/core.clj
@@ -15,6 +15,7 @@
check-non-remote-synced-dependencies
check-remote-synced-dependents
library-collection
+ library-models-collection-type
create-library-collection!
moving-into-remote-synced?
moving-from-remote-synced?
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index 6e22c788514..a9d48fd367a 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -1744,6 +1744,8 @@
;; delete all collection children
(t2/delete! :model/Collection :location (children-location collection))
(let [affected-collection-ids (cons (u/the-id collection) (collection->descendant-ids collection))]
+ (t2/update! :model/Table :collection_id [:in affected-collection-ids] {:collection_id nil
+ :is_published false})
(doseq [model [:model/Card
:model/Dashboard
:model/NativeQuerySnippet
diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.clj
index 65170402a73..a73a0ade618 100644
--- a/src/metabase/collections_rest/api.clj
+++ b/src/metabase/collections_rest/api.clj
@@ -230,17 +230,26 @@
(t2/hydrate :can_write))]
(if shallow
(shallow-tree-from-collection-id collections)
- (let [collection-type-ids (reduce (fn [acc {collection-id :collection_id, card-type :type, :as _card}]
- (update acc (case (keyword card-type)
- :model :dataset
- :metric :metric
- :card) conj collection-id))
- {:dataset #{}
- :metric #{}
- :card #{}}
- (t2/reducible-query {:select-distinct [:collection_id :type]
- :from [:report_card]
- :where [:= :archived false]}))
+ (let [collection-type-ids (merge (reduce (fn [acc {collection-id :collection_id, card-type :type, :as _card}]
+ (update acc (case (keyword card-type)
+ :model :dataset
+ :metric :metric
+ :card) conj collection-id))
+ {:dataset #{}
+ :metric #{}
+ :card #{}}
+ (t2/reducible-query {:select-distinct [:collection_id :type]
+ :from [:report_card]
+ :where [:= :archived false]}))
+ ;; Tables in collections are an EE feature (data-studio)
+ (when (premium-features/has-feature? :data-studio)
+ {:table (->> (t2/query {:select-distinct [:collection_id]
+ :from :metabase_table
+ :where [:and
+ [:= :is_published true]
+ [:= :archived_at nil]]})
+ (map :collection_id)
+ (into #{}))}))
collections-with-details (map collection/personal-collection-with-ui-details collections)]
(collection/collections->tree collection-type-ids collections-with-details)))))
@@ -258,7 +267,8 @@
"pulse" ; I think the only kinds of Pulses we still have are Alerts?
"snippet"
"no_models"
- "timeline"})
+ "timeline"
+ "table"})
(def ^:private ModelString
(into [:enum] valid-model-param-values))
@@ -388,7 +398,7 @@
(if (collection/is-trash? collection)
[:= :document.archived_directly true]
[:and
- [:= :collection_id (:id collection)]
+ [:= :document.collection_id (:id collection)]
[:= :document.archived_directly false]])
[:= :document.archived (boolean archived?)]]}
(sql.helpers/where (pinned-state->clause pinned-state :document.collection_position))))
@@ -489,11 +499,11 @@
[:= :mr.moderated_item_type (h2x/literal "card")]]
[:core_user :u] [:= :u.id :r.user_id]]
:where [:and
- (collection/visible-collection-filter-clause :collection_id {:cte-name :visible_collection_ids})
+ (collection/visible-collection-filter-clause :c.collection_id {:cte-name :visible_collection_ids})
(if (collection/is-trash? collection)
[:= :c.archived_directly true]
[:and
- [:= :collection_id (:id collection)]
+ [:= :c.collection_id (:id collection)]
[:= :c.archived_directly false]])
(when-not show-dashboard-questions?
[:= :c.dashboard_id nil])
@@ -587,11 +597,11 @@
[:= :r.model (h2x/literal "Dashboard")]]
[:core_user :u] [:= :u.id :r.user_id]]
:where [:and
- (collection/visible-collection-filter-clause :collection_id {:cte-name :visible_collection_ids})
+ (collection/visible-collection-filter-clause :d.collection_id {:cte-name :visible_collection_ids})
(if (collection/is-trash? collection)
[:= :d.archived_directly true]
[:and
- [:= :collection_id (:id collection)]
+ [:= :d.collection_id (:id collection)]
[:not= :d.archived_directly true]])
[:= :archived (boolean archived?)]]}
(sql.helpers/where (pinned-state->clause pinned-state))))
@@ -692,6 +702,26 @@
[_ collection options]
(collection-query collection options))
+(defmethod collection-children-query :table
+ [_ collection {:keys [archived? pinned-state]}]
+ {:select [:t.id
+ [:t.id :table_id]
+ [:t.display_name :name]
+ :t.description
+ :t.collection_id
+ [:t.db_id :database_id]
+ [[:!= :t.archived_at nil] :archived]
+ [(h2x/literal "table") :model]]
+ :from [[:metabase_table :t]]
+ :where [:and
+ [:= :t.is_published true]
+ (poison-when-pinned-clause pinned-state)
+ (collection/visible-collection-filter-clause :t.collection_id {:cte-name :visible_collection_ids})
+ [:= :t.collection_id (:id collection)]
+ (if archived?
+ [:!= :t.archived_at nil]
+ [:= :t.archived_at nil])]})
+
(defn- annotate-collections
[parent-coll colls {:keys [show-dashboard-questions?]}]
(let [descendant-collections (collection/descendants-flat parent-coll (collection/visible-collection-filter-clause
@@ -718,6 +748,20 @@
[:= :archived false]
[:in :collection_id descendant-collection-ids]]})))
+ ;; Tables in collections are an EE feature (data-studio)
+ collections-containing-tables
+ (if (premium-features/has-feature? :data-studio)
+ (->> (when (seq descendant-collection-ids)
+ (t2/query {:select-distinct [:collection_id]
+ :from :metabase_table
+ :where [:and
+ [:= :is_published true]
+ [:= :archived_at nil]
+ [:in :collection_id descendant-collection-ids]]}))
+ (map :collection_id)
+ (into #{}))
+ #{})
+
collections-containing-dashboards
(->> (when (seq descendant-collection-ids)
(t2/query {:select-distinct [:collection_id]
@@ -738,7 +782,8 @@
child-type->coll-id-set
(merge child-type->coll-id-set
- {:collection collections-containing-collections
+ {:table collections-containing-tables
+ :collection collections-containing-collections
:dashboard collections-containing-dashboards})
;; why are we calling `annotate-collections` on all descendants, when we only need the collections in `colls`
@@ -769,6 +814,10 @@
(assoc :type type-value)
update-personal-collection)))))
+(defmethod post-process-collection-children :table
+ [_ _ _collection rows]
+ (map #(update % :archived api/bit->boolean) rows))
+
;;; TODO -- consider whether this function belongs here or in [[metabase.revisions.models.revision.last-edit]]
(mu/defn- coalesce-edit-info :- revisions/MaybeAnnotated
"Hoist all of the last edit information into a map under the key :last-edit-info. Considers this information present
@@ -801,6 +850,7 @@
:document :model/Document
:pulse :model/Pulse
:snippet :model/NativeQuerySnippet
+ :table :model/Table
:timeline :model/Timeline))
(defn post-process-rows
@@ -988,6 +1038,8 @@
[{collection-namespace :namespace, :as collection} :- collection/CollectionWithLocationAndIDOrRoot
{:keys [models], :as options} :- CollectionChildrenOptions]
(let [valid-models (for [model-kw (cond-> [:collection :dataset :metric :card :dashboard :pulse :snippet :timeline]
+ ;; Tables in collections are an EE feature (data-studio)
+ (premium-features/has-feature? :data-studio) (conj :table)
(premium-features/enable-documents?) (conj :document))
;; only fetch models that are specified by the `model` param; or everything if it's empty
:when (or (empty? models) (contains? models model-kw))
diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.clj
index bdc19aa1760..305d4e26fa2 100644
--- a/src/metabase/permissions/core.clj
+++ b/src/metabase/permissions/core.clj
@@ -12,6 +12,7 @@
[metabase.permissions.models.permissions-group-membership]
[metabase.permissions.models.permissions-revision]
[metabase.permissions.path]
+ [metabase.permissions.published-tables]
[metabase.permissions.user]
[metabase.permissions.util]
[metabase.permissions.validation]
@@ -28,6 +29,7 @@
metabase.permissions.models.permissions-group-membership/keep-me
metabase.permissions.models.permissions-revision/keep-me
metabase.permissions.path/keep-me
+ metabase.permissions.published-tables/keep-me
metabase.permissions.user/keep-me
metabase.permissions.util/keep-me
metabase.permissions.validation/keep-me)
@@ -114,7 +116,11 @@
check-manager-of-group]
[metabase.permissions.models.collection.graph
graph
- update-graph!])
+ update-graph!]
+ [metabase.permissions.published-tables
+ user-published-table-permission
+ user-has-any-published-table-permission?
+ user-has-published-table-permission-for-database?])
;;; import these vars with different names to make their purpose more obvious.
diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.clj
index 462843a7137..6ab336e9b70 100644
--- a/src/metabase/permissions/models/data_permissions.clj
+++ b/src/metabase/permissions/models/data_permissions.clj
@@ -6,6 +6,7 @@
[metabase.api.common :as api]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.models.interface :as mi]
+ [metabase.permissions.published-tables :as published-tables]
[metabase.permissions.schema :as permissions.schema]
[metabase.premium-features.core :refer [defenterprise]]
[metabase.util :as u]
@@ -299,13 +300,17 @@
{perm-type (permissions.schema/data-permissions perm-type)})))
(if (is-superuser? user-id)
(most-permissive-value perm-type)
- (let [perm-values (->> (get-permissions user-id perm-type database-id)
- (filter #(or (= (:table_id %) table-id)
- (nil? (:table_id %))))
- (map :perm_value)
- (into #{}))]
- (or (coalesce perm-type (conj perm-values (get-additional-table-permission! {:db-id database-id :table-id table-id}
- perm-type)))
+ (let [perm-values (into #{}
+ (comp (filter #(or (= (:table_id %) table-id)
+ (nil? (:table_id %))))
+ (map :perm_value))
+ (get-permissions user-id perm-type database-id))
+ table-perm (coalesce perm-type (conj perm-values (get-additional-table-permission! {:db-id database-id :table-id table-id}
+ perm-type)))]
+ (or (when-not (= table-perm (least-permissive-value perm-type))
+ table-perm)
+ (when (pos-int? table-id)
+ (published-tables/user-published-table-permission perm-type table-id))
(least-permissive-value perm-type)))))
(mu/defn user-has-permission-for-table? :- :boolean
diff --git a/src/metabase/permissions/published_tables.clj b/src/metabase/permissions/published_tables.clj
new file mode 100644
index 00000000000..4cab7dd8ab5
--- /dev/null
+++ b/src/metabase/permissions/published_tables.clj
@@ -0,0 +1,32 @@
+(ns metabase.permissions.published-tables
+ "Published tables permission functions.
+ Published tables are an EE feature (data-studio) that allows tables to be placed in collections
+ and accessed via collection permissions instead of data permissions.
+
+ This namespace contains OSS stubs that return false/nil. The EE implementations in
+ `metabase-enterprise.data-studio.permissions.published-tables` provide the actual functionality."
+ (:require
+ [metabase.premium-features.core :refer [defenterprise]]))
+
+;;; ---------------------------------------- Permission Check Functions ------------------------------------------------
+
+(defenterprise user-published-table-permission
+ "Returns `:query-builder` permission if table is published and user has collection access.
+ OSS implementation always returns nil - published tables only grant access in EE."
+ metabase-enterprise.data-studio.permissions.published-tables
+ [_perm-type _table-id]
+ nil)
+
+(defenterprise user-has-any-published-table-permission?
+ "Returns true if user has access to any published table via collection permissions.
+ OSS implementation always returns false - published tables only grant access in EE."
+ metabase-enterprise.data-studio.permissions.published-tables
+ []
+ false)
+
+(defenterprise user-has-published-table-permission-for-database?
+ "Returns true if user has access to any published table in the given database via collection permissions.
+ OSS implementation always returns false - published tables only grant access in EE."
+ metabase-enterprise.data-studio.permissions.published-tables
+ [_database-id]
+ false)
diff --git a/src/metabase/query_processor/api.clj b/src/metabase/query_processor/api.clj
index 706c133c7e5..9966b7ea7c0 100644
--- a/src/metabase/query_processor/api.clj
+++ b/src/metabase/query_processor/api.clj
@@ -18,6 +18,7 @@
[metabase.parameters.custom-values :as custom-values]
[metabase.parameters.field :as parameters.field]
[metabase.parameters.schema :as parameters.schema]
+ [metabase.permissions.core :as perms]
[metabase.queries.core :as queries]
[metabase.query-processor :as qp]
[metabase.query-processor.compile :as qp.compile]
@@ -62,7 +63,9 @@
(when-not database
(throw (ex-info (tru "`database` is required for all queries whose type is not `internal`.")
{:status-code 400, :query query})))
- (api/read-check :model/Database database))
+ (when-not (or (mi/can-read? :model/Database database)
+ (perms/user-has-published-table-permission-for-database? database))
+ (api/throw-403)))
;; store table id trivially iff we get a query with simple source-table
(let [table-id (get-in query [:query :source-table])]
(when (int? table-id)
diff --git a/src/metabase/search/filter.clj b/src/metabase/search/filter.clj
index db3d7353807..9ea03b6f51f 100644
--- a/src/metabase/search/filter.clj
+++ b/src/metabase/search/filter.clj
@@ -91,9 +91,15 @@
(defmethod where-clause* ::collection-hierarchy [_ k v]
;; Filter by collection and all descendants
;; Match items directly in the collection OR in descendant collections
- [:or
- [:= k v]
- [:like :collection.location (str "%" (collection/location-path v) "%")]])
+ ;; Tables in collections are an EE feature (data-studio), so exclude them in OSS
+ (let [collection-filter [:or
+ [:= k v]
+ [:like :collection.location (str "%" (collection/location-path v) "%")]]]
+ (if (premium-features/has-feature? :data-studio)
+ collection-filter
+ [:and
+ [:not= :search_index.model [:inline "table"]]
+ collection-filter])))
(defn personal-collections-where-clause
"Build a clause limiting the entries to those (not) within or within personal collections, if relevant.
diff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.clj
index 256f5d0ffb4..808ca920fbe 100644
--- a/src/metabase/search/impl.clj
+++ b/src/metabase/search/impl.clj
@@ -184,7 +184,9 @@
:collection (if (and archived_directly (not= "collection" model))
(select-keys (collection/trash-collection)
[:id :name :authority_level :type])
- (merge {:id collection_id
+ (merge {:id (if (and (nil? collection_id) (some? collection_name))
+ "root"
+ collection_id)
:name collection_name
:authority_level collection_authority_level
:type collection_type}
diff --git a/src/metabase/search/in_place/filter.clj b/src/metabase/search/in_place/filter.clj
index 480ae3c95f1..85793a0c7b6 100644
--- a/src/metabase/search/in_place/filter.clj
+++ b/src/metabase/search/in_place/filter.clj
@@ -284,8 +284,22 @@
[:= :collection.id collection-id]
[:like :collection.location (str "%" (collection/location-path collection-id) "%")]])))))
+(defmethod build-optional-filter-query [:collection "table"]
+ [_filter model query collection-id]
+ ;; Tables in collections are an EE feature (data-studio)
+ (if (premium-features/has-feature? :data-studio)
+ (let [collection-col (search.config/column-with-model-alias model :collection_id)
+ published-col (search.config/column-with-model-alias model :is_published)]
+ (sql.helpers/where query [:and
+ [:= published-col true]
+ [:or
+ [:= collection-col collection-id]
+ [:like :collection.location (str "%" (collection/location-path collection-id) "%")]]]))
+ ;; OSS: tables don't belong to collections
+ (sql.helpers/where query false-clause)))
+
;; Things that don't belong to collections
-(doseq [model ["table" "database" "action" "indexed-entity"]]
+(doseq [model ["database" "action" "indexed-entity"]]
(defmethod build-optional-filter-query [:collection model]
[_filter _model query _collection-id]
;; These models don't have collection_id, so they never match
@@ -311,7 +325,7 @@
(reduce (fn [acc [filter model]]
(update acc filter set/union #{model}))
{})))
- (update :collection disj "table" "database")
+ (update :collection disj "database")
(update :collection conj "indexed-entity")))
;; ------------------------------------------------------------------------------------------------;;
diff --git a/src/metabase/search/in_place/legacy.clj b/src/metabase/search/in_place/legacy.clj
index 442a5dd6f3e..5def86e04cb 100644
--- a/src/metabase/search/in_place/legacy.clj
+++ b/src/metabase/search/in_place/legacy.clj
@@ -443,6 +443,13 @@
[:table.schema :table_schema]
[:table.name :table_name]
[:table.description :table_description]
+ [:table.collection_id :collection_id]
+ [[:case [:and [:= :table.collection_id nil] [:= :table.is_published true]]
+ [:inline "Our analytics"]
+ :else
+ :collection.name] :collection_name]
+ [:collection.authority_level :collection_authority_level]
+ [:collection.type :collection_type]
[:metabase_database.name :database_name]])
(defmethod columns-for-model "transform"
@@ -599,6 +606,7 @@
(-> (base-query-for-model model search-ctx)
(add-table-db-id-clause table-db-id)
(add-table-where-clauses model search-ctx)
+ (sql.helpers/left-join [:collection :collection] [:and :table.is_published [:= :table.collection_id :collection.id]])
(sql.helpers/left-join :metabase_database [:= :table.db_id :metabase_database.id]))))
(defmethod search.engine/model-set :search.engine/in-place
diff --git a/src/metabase/segments/api.clj b/src/metabase/segments/api.clj
index 87d1ace699d..3ea90e5e9fd 100644
--- a/src/metabase/segments/api.clj
+++ b/src/metabase/segments/api.clj
@@ -61,7 +61,9 @@
(api.macros/defendpoint :get "/"
"Fetch *all* `Segments`."
[]
- (as-> (t2/select :model/Segment, :archived false, {:order-by [[:%lower.name :asc]]}) segments
+ (as-> (t2/select :model/Segment
+ :archived false
+ {:order-by [[:%lower.name :asc]]}) segments
(filter mi/can-read? segments)
(t2/hydrate segments :creator :definition_description)))
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index df1020ed19a..c924c67ab0d 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -8,7 +8,8 @@
[metabase.api.macros :as api.macros]
[metabase.appearance.core :as appearance]
[metabase.auth-identity.core :as auth-identity]
- [metabase.collections.models.collection :as collection] [metabase.config.core :as config]
+ [metabase.collections.models.collection :as collection]
+ [metabase.config.core :as config]
[metabase.events.core :as events]
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
@@ -301,6 +302,26 @@
:group (within-group)
:all (all)))))
+(defn- add-query-permissions
+ "Add `:can_create_queries` and `:can_create_native_queries` flags to user based on their create-queries
+ permissions across non-sample databases."
+ [user]
+ (let [db-ids (t2/select-pks-set :model/Database)
+ _ (perms/prime-db-cache db-ids)
+ create-query-perms (into #{}
+ (map (fn [db-id]
+ (perms/most-permissive-database-permission-for-user
+ api/*current-user-id* :perms/create-queries db-id)))
+ db-ids)
+ can-create-queries? (or (some #(perms/at-least-as-permissive?
+ :perms/create-queries % :query-builder)
+ create-query-perms)
+ (perms/user-has-any-published-table-permission?))
+ can-create-native? (contains? create-query-perms :query-builder-and-native)]
+ (update user :permissions assoc
+ :can_create_queries (boolean can-create-queries?)
+ :can_create_native_queries can-create-native?)))
+
(defn- maybe-add-advanced-permissions
"If `advanced-permissions` is enabled, add to `user` a permissions map."
[user]
@@ -365,6 +386,7 @@
(t2/hydrate :personal_collection_id :group_ids :is_installer :has_invited_second_user)
add-has-question-and-dashboard
add-first-login
+ add-query-permissions
maybe-add-advanced-permissions
maybe-add-sso-source
add-custom-homepage-info))
diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.clj
index 315943da642..820d20bfb9c 100644
--- a/src/metabase/warehouse_schema/models/table.clj
+++ b/src/metabase/warehouse_schema/models/table.clj
@@ -462,8 +462,9 @@
(t2/select-one :model/Database :id (:db_id table)))
;;; ------------------------------------------------- Serialization -------------------------------------------------
-(defmethod serdes/dependencies "Table" [table]
- [[{:model "Database" :id (:db_id table)}]])
+(defmethod serdes/dependencies "Table" [{:keys [db_id collection_id]}]
+ (cond-> [[{:model "Database" :id db_id}]]
+ collection_id (conj [{:model "Collection" :id collection_id}])))
(defmethod serdes/generate-path "Table" [_ table]
(let [db-name (t2/select-one-fn :name :model/Database :id (:db_id table))]
@@ -488,13 +489,14 @@
{:copy [:name :description :entity_type :active :display_name :visibility_type :schema
:points_of_interest :caveats :show_in_getting_started :field_order :initial_sync_status :is_upload
:database_require_filter :is_defective_duplicate :unique_table_helper :is_writable :data_authority
- :data_source :owner_email :owner_user_id]
+ :data_source :owner_email :owner_user_id :is_published]
:skip [:estimated_row_count :view_count]
- :transform {:created_at (serdes/date)
- :archived_at (serdes/date)
+ :transform {:created_at (serdes/date)
+ :archived_at (serdes/date)
:deactivated_at (serdes/date)
- :data_layer (serdes/optional-kw)
- :db_id (serdes/fk :model/Database :name)}})
+ :data_layer (serdes/optional-kw)
+ :db_id (serdes/fk :model/Database :name)
+ :collection_id (serdes/fk :model/Collection)}})
(defmethod serdes/storage-path "Table" [table _ctx]
(concat (serdes/storage-path-prefixes (serdes/path table))
@@ -507,7 +509,8 @@
:attrs {;; legacy search uses :active for this, but then has a rule to only ever show active tables
;; so we moved that to the where clause
:archived false
- :collection-id false
+ ;; For published tables with no collection, we want to show "root" as the collection id
+ :collection-id true
:creator-id false
:database-id :db_id
:view-count true
@@ -516,15 +519,25 @@
:search-terms {:name search.spec/explode-camel-case
:display_name true
:description true}
- :render-terms {:initial-sync-status true
- :table-id :id
- :table-description :description
- :table-name :name
- :table-schema :schema
- :database-name :db.name}
+ :render-terms {:initial-sync-status true
+ :table-id :id
+ :table-description :description
+ :table-name :name
+ :table-schema :schema
+ :database-name :db.name
+ :collection-authority_level :collection.authority_level
+ :collection-location :collection.location
+ ;; For published tables with no collection, show "Our analytics" as the collection name
+ :collection-name [:coalesce :collection.name
+ [:case
+ [:and :this.is_published
+ [:= :this.collection_id nil]] [:inline "Our analytics"]
+ :else nil]]
+ :collection-type :collection.type}
:where [:and
:active
[:= :visibility_type nil]
[:= :db.router_database_id nil]
[:not= :db_id [:inline audit/audit-db-id]]]
- :joins {:db [:model/Database [:= :db.id :this.db_id]]}})
+ :joins {:db [:model/Database [:= :db.id :this.db_id]]
+ :collection [:model/Collection [:and [:= :this.is_published true] [:= :collection.id :this.collection_id]]]}})
diff --git a/src/metabase/warehouse_schema/table.clj b/src/metabase/warehouse_schema/table.clj
index d9c497934eb..d817f8461c0 100644
--- a/src/metabase/warehouse_schema/table.clj
+++ b/src/metabase/warehouse_schema/table.clj
@@ -10,11 +10,17 @@
(set! *warn-on-reflection* true)
+(defn- nil-if-unreadable
+ [instance]
+ (when (and instance (mi/can-read? instance))
+ instance))
+
(defn present-table
"Given a table, shape it for the API."
[table]
(-> table
(update :db dissoc :router_database_id)
+ (m/update-existing :collection nil-if-unreadable)
(update :schema str)))
(defn- format-fields-for-response [resp]
@@ -25,17 +31,35 @@
(update field :values field-values/field-values->pairs)
field)))))
+(defenterprise can-access-via-collection?
+ "Returns true if the user can access this published table via collection read permissions.
+ OSS returns false (published tables don't grant access).
+ Enterprise checks collection permissions for published tables."
+ metabase-enterprise.data-studio.permissions.published-tables
+ [_table]
+ false)
+
+(defn- can-access-table-for-query-metadata?
+ "Returns true if the current user can access this table for query metadata.
+ Checks collection permissions for published tables, data permissions for unpublished tables."
+ [table]
+ (or (can-access-via-collection? table)
+ (mi/can-read? table)))
+
(defn fetch-query-metadata*
"Returns the query metadata used to power the Query Builder for the given `table`. `include-sensitive-fields?`,
`include-hidden-fields?` and `include-editable-data-model?` can be either booleans or boolean strings."
[table {:keys [include-sensitive-fields? include-hidden-fields? include-editable-data-model?]}]
+ (api/check-404 table)
(if include-editable-data-model?
(api/write-check table)
- (api/read-check table))
- (let [hydration-keys (cond-> [:db [:fields [:target :has_field_values] :has_field_values :dimensions :name_field] :segments :metrics]
+ (api/check-403 (can-access-table-for-query-metadata? table)))
+ (let [hydration-keys (cond-> [:db [:fields [:target :has_field_values] :has_field_values :dimensions :name_field]
+ [:segments :definition_description] :metrics :collection]
(premium-features/has-feature? :transforms) (conj :transform)
api/*is-superuser?* (conj :published_models))]
(-> table
+ (update :collection nil-if-unreadable)
(#(apply t2/hydrate % hydration-keys))
(m/dissoc-in [:db :details])
format-fields-for-response
@@ -51,7 +75,7 @@
[ids]
(when (seq ids)
(let [tables (->> (t2/select :model/Table :id [:in ids])
- (filter mi/can-read?))
+ (filter can-access-table-for-query-metadata?))
tables (t2/hydrate tables
[:fields [:target :has_field_values] :has_field_values :dimensions :name_field]
:segments
diff --git a/src/metabase/warehouse_schema_rest/api/table.clj b/src/metabase/warehouse_schema_rest/api/table.clj
index 9e9b89f6d75..4d8ed42153a 100644
--- a/src/metabase/warehouse_schema_rest/api/table.clj
+++ b/src/metabase/warehouse_schema_rest/api/table.clj
@@ -137,7 +137,7 @@
api/write-check
api/read-check)]
(-> (api-perm-check-fn :model/Table id)
- (t2/hydrate :db :pk_field)
+ (t2/hydrate :db :pk_field :collection)
schema.table/present-table)))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.clj
index dea648921da..2f01c765338 100644
--- a/test/metabase/collections_rest/api_test.clj
+++ b/test/metabase/collections_rest/api_test.clj
@@ -3202,3 +3202,28 @@
(mt/with-temp [:model/Collection {a-id :id} {:archived true}]
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :delete 403 (str "/collection/" a-id))))))
+
+(deftest published-tables-not-in-collection-items-oss-test
+ (testing "In OSS (without :data-studio feature), published tables should NOT appear in collection items"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Card {card-id :id} {:collection_id coll-id :name "Test Card"}
+ :model/Table {table-id :id} {:collection_id coll-id
+ :is_published true
+ :name "Published Table"}]
+ (let [items (:data (mt/user-http-request :crowberto :get 200
+ (str "collection/" coll-id "/items")))]
+ (testing "Card should appear"
+ (is (some #(= card-id (:id %)) items)
+ "Card should be in collection items"))
+ (testing "Published table should NOT appear"
+ (is (not (some #(= table-id (:id %)) items))
+ "Published table should NOT be in collection items in OSS"))))))
+ (testing "In OSS (without :data-studio feature), published tables should NOT appear in root collection items"
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Table {table-id :id} {:collection_id nil
+ :is_published true
+ :name "Root Published Table"}]
+ (let [items (:data (mt/user-http-request :crowberto :get 200 "collection/root/items"))]
+ (is (not (some #(= table-id (:id %)) items))
+ "Published table should NOT be in root collection items in OSS"))))))
diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.clj
index 9f5fd1575a2..aabb4f74eed 100644
--- a/test/metabase/query_processor/api_test.clj
+++ b/test/metabase/query_processor/api_test.clj
@@ -1048,3 +1048,28 @@
:tables empty?
:databases [{:id (mt/id) :engine string?}]}
(query-metadata 200 card-id))))))))))
+
+(deftest published-table-does-not-grant-database-access-oss-test
+ (testing "POST /api/dataset in OSS: published table access does NOT grant database access"
+ (mt/with-premium-features #{}
+ (mt/with-restored-data-perms-for-group! (u/the-id (perms/all-users-group))
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
+ :model/Collection collection {}]
+ ;; Publish the venues table into this collection
+ (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
+ (let [all-users (perms/all-users-group)]
+ ;; Set database-level permissions first to establish baseline
+ (perms/set-database-permission! all-users (mt/id) :perms/view-data :unrestricted)
+ (perms/set-database-permission! all-users (mt/id) :perms/create-queries :no)
+ ;; Grant collection read permission - gives create-queries via published table mechanism in EE
+ (perms/grant-collection-read-permissions! all-users (u/the-id collection))
+ ;; Set table-level permissions
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/view-data :unrestricted)
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/create-queries :no)
+ ;; In OSS: published tables don't grant database access, so user gets 403 at database check
+ (testing "Query should be blocked because OSS doesn't grant database access via published tables"
+ (is (= "You don't have permissions to do that."
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 403 "dataset"
+ (mt/mbql-query venues {:limit 1})))))))))))))
diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.clj
index 66302f12b41..f707b620fba 100644
--- a/test/metabase/search/api_test.clj
+++ b/test/metabase/search/api_test.clj
@@ -1930,3 +1930,17 @@
:collection coll-1)]
(is (= #{card-1}
(set (map :id (:data results)))))))))
+
+(deftest published-table-not-in-collection-search-oss-test
+ (testing "In OSS, published tables should NOT appear in collection-filtered search"
+ (mt/with-premium-features #{}
+ (mt/with-temp
+ [:model/Collection {parent-coll :id} {:name "OSS Test Collection" :location "/"}
+ :model/Card {card-id :id} {:collection_id parent-coll :name "OSS Test Card"}
+ :model/Table {table-id :id} {:name "OSS Published Table" :is_published true :collection_id parent-coll}]
+ (testing "Collection-filtered search should NOT include published tables in OSS"
+ (let [result-ids (into #{} (map :id) (:data (mt/user-http-request :crowberto :get 200 "search" :collection parent-coll)))]
+ (is (contains? result-ids card-id)
+ "Card in collection should be included")
+ (is (not (contains? result-ids table-id))
+ "Published table should NOT be included in collection search in OSS")))))))
diff --git a/test/metabase/search/filter_test.clj b/test/metabase/search/filter_test.clj
index dc5487213f5..36bac613653 100644
--- a/test/metabase/search/filter_test.clj
+++ b/test/metabase/search/filter_test.clj
@@ -8,7 +8,10 @@
[metabase.search.filter :as search.filter]
[metabase.search.in-place.filter :as search.in-place.filter]
[metabase.search.ingestion :as search.ingestion]
- [metabase.search.test-util :as search.tu]))
+ [metabase.search.test-util :as search.tu]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :db))
(use-fixtures :each (fn [thunk] (binding [search.ingestion/*force-sync* true]
(search.tu/with-new-search-if-available-otherwise-legacy (thunk)))))
@@ -141,6 +144,7 @@
[:= :search_index.non_temporal_dim_ids "[1]"]
[:= :search_index.has_temporal_dim true]
[:in :search_index.display_type ["line"]]
- [:or [:= :search_index.collection_id 5] [:like :collection.location "%/5/%"]]}}
+ [:or [:= :search_index.collection_id 5] [:like :collection.location "%/5/%"]]
+ [:not= :search_index.model [:inline "table"]]}}
(-> (search.filter/with-filters kitchen-sink-filter-context {:select [:some :stuff], :from :somewhere})
(update :where set))))))
diff --git a/test/metabase/search/spec_test.clj b/test/metabase/search/spec_test.clj
index 8f0b0bff33a..b39566a0936 100644
--- a/test/metabase/search/spec_test.clj
+++ b/test/metabase/search/spec_test.clj
@@ -100,16 +100,22 @@
{:search-model "table",
:fields
#{:active :description :schema :name :id :db_id :initial_sync_status :display_name
- :visibility_type :view_count :created_at :updated_at}
+ :visibility_type :view_count :created_at :updated_at :collection_id :is_published}
:where [:= :updated.id :this.id]}},
- :Database #{{:search-model "table", :fields #{:name :router_database_id}, :where [:= :updated.id :this.db_id]}}
+ :Database #{{:search-model "table"
+ :fields #{:name :router_database_id}
+ :where [:= :updated.id :this.db_id]}}
:Segment #{{:search-model "segment"
:fields #{:description :archived :table_id :name :id :updated_at}
:where [:= :updated.id :this.id]}}
:Collection #{{:search-model "collection"
:fields #{:authority_level :archived :description :name :type :id
+
:archived_directly :location :namespace :created_at}
- :where [:= :updated.id :this.id]}}}
+ :where [:= :updated.id :this.id]}
+ {:search-model "table"
+ :fields #{:authority_level :name :type :location}
+ :where [:and [:= :this.is_published true] [:= :updated.id :this.collection_id]]}}}
(#'search.spec/merge-hooks
[(#'search.spec/search-model-hooks (search.spec/spec "table"))
(#'search.spec/search-model-hooks (search.spec/spec "segment"))
diff --git a/test/metabase/segments/api_test.clj b/test/metabase/segments/api_test.clj
index b10e5ca1449..8ddfea45ade 100644
--- a/test/metabase/segments/api_test.clj
+++ b/test/metabase/segments/api_test.clj
@@ -29,8 +29,9 @@
(defn- mbql4-segment-definition
"Create a legacy MBQL4 segment definition"
- [field-id value]
- {:filter [:= [:field field-id nil] value]})
+ [table-id field-id value]
+ {:source-table table-id
+ :filter [:= [:field field-id nil] value]})
(defn- pmbql-segment-definition
"Create an MBQL5 segment definition"
@@ -59,7 +60,7 @@
(testing "Test security. Requires superuser perms."
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 "segment" {:name "abc"
- :table_id 123
+ :table_id (mt/id :users)
:definition {}}))))))
(deftest create-segment-input-validation-test
@@ -84,32 +85,30 @@
:definition "foobar"})))))
(deftest create-segment-test
- (mt/with-temp [:model/Database {database-id :id} {}
- :model/Table {:keys [id]} {:db_id database-id}]
- (doseq [[format-name definition-fn] {"MBQL4" mbql4-segment-definition
- "pMBQL" (partial pmbql-segment-definition id)}]
- (testing format-name
- (is (= {:name "A Segment"
- :description "I did it!"
- :show_in_getting_started false
- :caveats nil
- :points_of_interest nil
- :creator_id (mt/user->id :crowberto)
- :creator (user-details (mt/fetch-user :crowberto))
- :entity_id true
- :created_at true
- :updated_at true
- :archived false
- :definition true}
- (-> (mt/user-http-request :crowberto :post 200 "segment"
- {:name "A Segment"
- :description "I did it!"
- :show_in_getting_started false
- :caveats nil
- :points_of_interest nil
- :table_id id
- :definition (definition-fn 10 20)})
- segment-response)))))))
+ (doseq [[format-name definition-fn] {"MBQL4" (partial mbql4-segment-definition (mt/id :users))
+ "pMBQL" (partial pmbql-segment-definition (mt/id :users))}]
+ (testing format-name
+ (is (= {:name "A Segment"
+ :description "I did it!"
+ :show_in_getting_started false
+ :caveats nil
+ :points_of_interest nil
+ :creator_id (mt/user->id :crowberto)
+ :creator (user-details (mt/fetch-user :crowberto))
+ :entity_id true
+ :created_at true
+ :updated_at true
+ :archived false
+ :definition true}
+ (-> (mt/user-http-request :crowberto :post 200 "segment"
+ {:name "A Segment"
+ :description "I did it!"
+ :show_in_getting_started false
+ :caveats nil
+ :points_of_interest nil
+ :table_id (mt/id :users)
+ :definition (definition-fn (mt/id :users :id) 20)})
+ segment-response))))))
;; ## PUT /api/segment
@@ -142,12 +141,10 @@
(deftest update-test
(testing "PUT /api/segment/:id"
- (mt/with-temp [:model/Database {database-id :id} {}
- :model/Table {table-id :id} {:db_id database-id}
- :model/Segment {:keys [id]} {:table_id table-id
- :definition (mbql4-segment-definition 2 "cans")}]
- (doseq [[format-name eq-fn] [["MBQL4" mbql4-segment-definition]
- ["pMBQL" (partial pmbql-segment-definition table-id)]]]
+ (mt/with-temp [:model/Segment {:keys [id]} {:table_id (mt/id :users)
+ :definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
+ (doseq [[format-name eq-fn] [["MBQL4" (partial mbql4-segment-definition (mt/id :users))]
+ ["pMBQL" (partial pmbql-segment-definition (mt/id :users))]]]
(testing format-name
(is (= {:name "Costa Rica"
:description nil
@@ -160,7 +157,7 @@
:created_at true
:updated_at true
:archived false
- :definition true}
+ :definition true}
(-> (mt/user-http-request
:crowberto :put 200 (format "segment/%d" id)
{:id id
@@ -169,15 +166,15 @@
:show_in_getting_started false
:caveats nil
:points_of_interest nil
- :table_id 456
+ :table_id (mt/id :users)
:revision_message "I got me some revisions"
- :definition (eq-fn 2 "cans")})
+ :definition (eq-fn (mt/id :users :name) "cans")})
segment-response))))))))
(deftest partial-update-test
(testing "PUT /api/segment/:id"
(testing "Can I update a segment's name without specifying `:points_of_interest` and `:show_in_getting_started`?"
- (mt/with-temp [:model/Segment segment {:definition (mbql4-segment-definition 2 "cans")}]
+ (mt/with-temp [:model/Segment segment {:definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
;; just make sure API call doesn't barf
(is (some? (mt/user-http-request :crowberto :put 200 (str "segment/" (u/the-id segment))
{:name "Cool name"
@@ -187,7 +184,7 @@
(deftest archive-test
(testing "PUT /api/segment/:id"
(testing "Can we archive a Segment with the PUT endpoint?"
- (mt/with-temp [:model/Segment {:keys [id]} {:definition (mbql4-segment-definition 2 "cans")}]
+ (mt/with-temp [:model/Segment {:keys [id]} {:definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
(is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id)
{:archived true, :revision_message "Archive the Segment"})))
(is (true?
@@ -197,7 +194,7 @@
(testing "PUT /api/segment/:id"
(testing "Can we unarchive a Segment with the PUT endpoint?"
(mt/with-temp [:model/Segment {:keys [id]} {:archived true
- :definition (mbql4-segment-definition 2 "cans")}]
+ :definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
(is (map? (mt/user-http-request :crowberto :put 200 (str "segment/" id)
{:archived false, :revision_message "Unarchive the Segment"})))
(is (= false
@@ -208,7 +205,7 @@
(deftest delete-permissions-test
(testing "DELETE /api/segment/:id"
(testing "test security. requires superuser perms"
- (mt/with-temp [:model/Segment {:keys [id]} {:definition (mbql4-segment-definition 2 "cans")}]
+ (mt/with-temp [:model/Segment {:keys [id]} {:definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :delete 403 (str "segment/" id)
:revision_message "yeeeehaw!")))))))
@@ -223,10 +220,8 @@
(deftest delete-test
(testing "DELETE /api/segment/:id"
- (mt/with-temp [:model/Database {database-id :id} {}
- :model/Table {table-id :id} {:db_id database-id}
- :model/Segment {:keys [id]} {:table_id table-id
- :definition (mbql4-segment-definition 2 "cans")}]
+ (mt/with-temp [:model/Segment {:keys [id]} {:table_id (mt/id :users)
+ :definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
(is (= nil
(mt/user-http-request :crowberto :delete 204 (format "segment/%d" id) :revision_message "carryon")))
(testing "should still be able to fetch the archived segment"
@@ -250,47 +245,44 @@
(deftest fetch-segment-permissions-test
(testing "GET /api/segment/:id"
(testing "test security. Requires read perms for the Table it references"
- (mt/with-temp [:model/Database db {}
- :model/Table table {:db_id (u/the-id db)}
- :model/Segment segment {:table_id (u/the-id table)
- :definition (mbql4-segment-definition 2 "cans")}]
+ (mt/with-temp [:model/Segment segment {:table_id (mt/id :users)
+ :definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
(mt/with-no-data-perms-for-all-users!
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "segment/" (u/the-id segment))))))))))
(deftest fetch-segment-test
(testing "GET /api/segment/:id"
- (mt/with-temp [:model/Database {database-id :id} {}
- :model/Table {table-id :id} {:db_id database-id}]
- (doseq [[format-name definition-fn] {"MBQL4" mbql4-segment-definition
- "pMBQL" (partial pmbql-segment-definition table-id)}]
- (testing format-name
- (mt/with-temp [:model/Segment {:keys [id]} {:creator_id (mt/user->id :crowberto)
- :table_id table-id
- :definition (definition-fn 2 "cans")}]
- (mt/with-full-data-perms-for-all-users!
- (is (= {:name "Toucans in the rainforest"
- :description "Lookin' for a blueberry"
- :show_in_getting_started false
- :caveats nil
- :points_of_interest nil
- :creator_id (mt/user->id :crowberto)
- :creator (user-details (mt/fetch-user :crowberto))
- :created_at true
- :updated_at true
- :entity_id true
- :archived false
- :definition true}
- (-> (mt/user-http-request :rasta :get 200 (format "segment/%d" id))
- segment-response
- (dissoc :query_description)))))))))))
+ (doseq [[format-name definition-fn] {"MBQL4" (partial mbql4-segment-definition (mt/id :users))
+ "pMBQL" (partial pmbql-segment-definition (mt/id :users))}]
+ (testing format-name
+ (mt/with-temp [:model/Segment {:keys [id]} {:creator_id (mt/user->id :crowberto)
+ :table_id (mt/id :users)
+ :definition (definition-fn (mt/id :users :name) "cans")}]
+ (mt/with-full-data-perms-for-all-users!
+ (is (= {:name "Toucans in the rainforest"
+ :description "Lookin' for a blueberry"
+ :show_in_getting_started false
+ :caveats nil
+ :points_of_interest nil
+ :creator_id (mt/user->id :crowberto)
+ :creator (user-details (mt/fetch-user :crowberto))
+ :created_at true
+ :updated_at true
+ :entity_id true
+ :archived false
+ :definition true}
+ (-> (mt/user-http-request :rasta :get 200 (format "segment/%d" id))
+ segment-response
+ (dissoc :query_description))))))))))
(deftest list-test
(testing "GET /api/segment/"
- (mt/with-temp [:model/Segment {id-1 :id} {:name "Segment 1"
- :table_id (mt/id :users)
- :definition (mbql4-segment-definition (mt/id :users :name) "cans")}
+ (mt/with-temp [:model/Segment {id-1 :id} {:name "Segment 1"
+ :table_id (mt/id :users)
+ :definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}
:model/Segment {id-2 :id} {:name "Segment 2"
+ :table_id (mt/id :venues)
:definition (:query (mt/mbql-query venues
{:filter
[:and
@@ -298,7 +290,7 @@
[:= $category_id->categories.name "BBQ"]]}))}
;; inactive segments shouldn't show up
:model/Segment {id-3 :id} {:archived true
- :definition (mbql4-segment-definition 2 "cans")}]
+ :definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
(mt/with-full-data-perms-for-all-users!
(is (=? [{:id id-1
:name "Segment 1"
@@ -316,7 +308,7 @@
(deftest related-entities-test
(testing "GET /api/segment/:id/related"
(testing "related/recommended entities"
- (mt/with-temp [:model/Segment {segment-id :id} {:definition (mbql4-segment-definition 2 "cans")}]
+ (mt/with-temp [:model/Segment {segment-id :id} {:definition (mbql4-segment-definition (mt/id :users) (mt/id :users :name) "cans")}]
(is (= #{:table :metrics :segments :linked-from}
(-> (mt/user-http-request :crowberto :get 200 (format "segment/%s/related" segment-id))
keys
diff --git a/test/metabase/sync/sync_test.clj b/test/metabase/sync/sync_test.clj
index 7a34994214a..33d450f66f4 100644
--- a/test/metabase/sync/sync_test.clj
+++ b/test/metabase/sync/sync_test.clj
@@ -222,7 +222,8 @@
:display_name "Movie"
:initial_sync_status "complete"
:fields [(field:movie-id) (field:movie-studio) (field:movie-title)]
- :description nil}))
+ :description nil
+ :collection_id false}))
(defn- expected-studio-table []
(merge (table-defaults)
@@ -231,7 +232,8 @@
:display_name "Studio"
:initial_sync_status "complete"
:fields [(field:studio-name) (field:studio-studio)]
- :description ""}))
+ :description ""
+ :collection_id false}))
(deftest sync-database-test
(doseq [supports-schemas? [true false]]
diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.clj
index ca3cb22a99b..93086ba202b 100644
--- a/test/metabase/users_rest/api_test.clj
+++ b/test/metabase/users_rest/api_test.clj
@@ -6,6 +6,7 @@
[metabase.collections.models.collection :as collection]
[metabase.config.core :as config]
[metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.permissions.util :as perms-util]
[metabase.test :as mt]
@@ -503,6 +504,70 @@
custom-homepage-dashboard -3]
(is (nil? (:custom_homepage (mt/user-http-request :rasta :get 200 "user/current")))))))))
+(deftest get-current-user-query-permissions-test
+ (testing "GET /api/user/current includes can_create_queries and can_create_native_queries"
+ (mt/with-premium-features #{}
+ (letfn [(user-permissions [user]
+ (-> (mt/user-http-request user :get 200 "user/current")
+ :permissions))]
+ (testing "admins should have both permissions true"
+ (is (partial= {:can_create_queries true
+ :can_create_native_queries true}
+ (user-permissions :crowberto))))
+
+ (testing "user with query-builder-and-native on a non-sample DB"
+ (mt/with-temp [:model/Database {db-id :id} {:is_sample false}]
+ (mt/with-all-users-data-perms-graph! {db-id {:view-data :unrestricted
+ :create-queries :query-builder-and-native}}
+ (is (partial= {:can_create_queries true
+ :can_create_native_queries true}
+ (user-permissions :rasta))))))
+
+ (testing "user with only query-builder (no native) on a non-sample DB"
+ (mt/with-temp [:model/Database {db-id :id} {:is_sample false}]
+ (mt/with-all-users-data-perms-graph! {db-id {:view-data :unrestricted
+ :create-queries :query-builder}}
+ (is (partial= {:can_create_queries true
+ :can_create_native_queries false}
+ (user-permissions :rasta))))))
+
+ (testing "user with no query permissions on non-sample DBs"
+ (mt/with-temp [:model/Database {db-id :id} {:is_sample false}]
+ (mt/with-all-users-data-perms-graph! {db-id {:view-data :unrestricted
+ :create-queries :no}}
+ (is (partial= {:can_create_queries false
+ :can_create_native_queries false}
+ (user-permissions :rasta))))))
+
+ (testing "at least one non-sample DB with native permission is enough"
+ (mt/with-temp [:model/Database {db1-id :id} {:is_sample false}
+ :model/Database {db2-id :id} {:is_sample false}]
+ (mt/with-all-users-data-perms-graph! {db1-id {:view-data :unrestricted
+ :create-queries :no}
+ db2-id {:view-data :unrestricted
+ :create-queries :query-builder-and-native}}
+ (is (partial= {:can_create_queries true
+ :can_create_native_queries true}
+ (user-permissions :rasta))))))))))
+
+(deftest can-create-queries-ignores-published-tables-oss-test
+ (testing "In OSS, can_create_queries should NOT consider published tables"
+ (mt/with-premium-features #{}
+ (letfn [(user-permissions [user]
+ (-> (mt/user-http-request user :get 200 "user/current")
+ :permissions))]
+ (testing "user with collection permission on published table should still have can_create_queries false"
+ (mt/with-temp [:model/Collection {collection-id :id} {}
+ :model/Table _table {:db_id (mt/id)
+ :is_published true
+ :collection_id collection-id}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) collection-id)
+ (mt/with-no-data-perms-for-all-users!
+ (is (partial= {:can_create_queries false
+ :can_create_native_queries false}
+ (user-permissions :rasta))
+ "Published tables should NOT grant can_create_queries in OSS"))))))))
+
(deftest ^:parallel get-user-test
(mt/with-premium-features #{}
(testing "GET /api/user/:id"
diff --git a/test/metabase/warehouse_schema/models/table_test.clj b/test/metabase/warehouse_schema/models/table_test.clj
index f26f3d74b20..f3213a62c43 100644
--- a/test/metabase/warehouse_schema/models/table_test.clj
+++ b/test/metabase/warehouse_schema/models/table_test.clj
@@ -419,3 +419,47 @@
(is (= {t1 [c1 c3], t2 []}
(->> (t2/hydrate [table1 table2] :published_models)
(u/index-by :id (comp sort (partial mapv :id) :published_models))))))))
+
+(deftest is-published-and-collection-id-test
+ (testing "is_published defaults to false"
+ (mt/with-temp [:model/Table {table-id :id} {}]
+ (is (false? (t2/select-one-fn :is_published :model/Table :id table-id)))))
+ (testing "can create a table with is_published=true and collection_id"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Table {table-id :id} {:is_published true :collection_id coll-id}]
+ (let [table (t2/select-one :model/Table :id table-id)]
+ (is (true? (:is_published table)))
+ (is (= coll-id (:collection_id table))))))
+ (testing "collection_id FK constraint prevents referencing non-existent collection"
+ (is (thrown?
+ Exception
+ (mt/with-temp [:model/Table _ {:collection_id Integer/MAX_VALUE}]))))
+ (testing "deleting a collection unpublishes the tables in it"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Table {table-1-id :id} {:is_published true :collection_id coll-id}
+ :model/Table {table-2-id :id} {:is_published true :collection_id coll-id}]
+ (t2/delete! :model/Collection :id coll-id)
+ (is (= #{[false nil]} (t2/select-fn-set (juxt :is_published :collection_id) :model/Table
+ :id [:in [table-1-id table-2-id]]))))))
+
+(deftest collection-hydration-test
+ (testing "hydrating :collection on a table"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}
+ :model/Table table {:is_published true :collection_id coll-id}]
+ (let [hydrated (t2/hydrate table :collection)]
+ (is (= coll-id (-> hydrated :collection :id)))
+ (is (= "Test Collection" (-> hydrated :collection :name))))))
+ (testing "hydrating :collection on a table with no collection_id returns nil"
+ (mt/with-temp [:model/Table table {}]
+ (let [hydrated (t2/hydrate table :collection)]
+ (is (nil? (:collection hydrated))))))
+ (testing "batched hydration works for multiple tables"
+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1"}
+ :model/Collection {coll2-id :id} {:name "Collection 2"}
+ :model/Table table1 {:is_published true :collection_id coll1-id}
+ :model/Table table2 {:is_published true :collection_id coll2-id}
+ :model/Table table3 {}]
+ (let [hydrated (t2/hydrate [table1 table2 table3] :collection)]
+ (is (= coll1-id (-> hydrated first :collection :id)))
+ (is (= coll2-id (-> hydrated second :collection :id)))
+ (is (nil? (-> hydrated (nth 2) :collection)))))))
diff --git a/test/metabase/warehouse_schema_rest/api/table_test.clj b/test/metabase/warehouse_schema_rest/api/table_test.clj
index 93c68c8f20a..d365e5c9c97 100644
--- a/test/metabase/warehouse_schema_rest/api/table_test.clj
+++ b/test/metabase/warehouse_schema_rest/api/table_test.clj
@@ -161,7 +161,7 @@
(t2/hydrate (t2/select-one [:model/Table :id :created_at :updated_at :initial_sync_status
:view_count]
:id (mt/id :venues))
- :pk_field)
+ :pk_field :collection)
{:schema "PUBLIC"
:name "VENUES"
:display_name "Venues"
@@ -182,7 +182,7 @@
(t2/hydrate (t2/select-one [:model/Table :id :created_at :updated_at :initial_sync_status
:view_count]
:id table-id)
- :pk_field)
+ :pk_field :collection)
{:schema ""
:name "schemaless_table"
:display_name "Schemaless"
@@ -243,8 +243,9 @@
(testing "Sensitive fields are included"
(is (= (merge
(query-metadata-defaults)
- (t2/select-one [:model/Table :created_at :updated_at :initial_sync_status :view_count]
- :id (mt/id :users))
+ (t2/hydrate (t2/select-one [:model/Table :created_at :updated_at :initial_sync_status :view_count]
+ :id (mt/id :users))
+ :collection)
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
@@ -324,8 +325,9 @@
(testing "Sensitive fields should not be included"
(is (= (merge
(query-metadata-defaults)
- (t2/select-one [:model/Table :created_at :updated_at :initial_sync_status :view_count]
- :id (mt/id :users))
+ (t2/hydrate (t2/select-one [:model/Table :created_at :updated_at :initial_sync_status :view_count]
+ :id (mt/id :users))
+ :collection)
{:schema "PUBLIC"
:name "USERS"
:display_name "Users"
@@ -418,7 +420,8 @@
(-> (table-defaults)
(dissoc :segments :field_values :metrics :updated_at)
(update :db merge (select-keys (mt/db) [:details])))
- (t2/hydrate (t2/select-one [:model/Table :id :schema :name :created_at :initial_sync_status] :id (u/the-id table)) :pk_field)
+ (t2/hydrate (t2/select-one [:model/Table :id :schema :name :created_at :initial_sync_status] :id (u/the-id table))
+ :pk_field :collection)
{:description "What a nice table!"
:entity_type nil
:schema ""
@@ -643,7 +646,8 @@
(testing "GET /api/table/:id/query_metadata"
(is (= (merge
(query-metadata-defaults)
- (t2/select-one [:model/Table :created_at :updated_at :initial_sync_status] :id (mt/id :categories))
+ (t2/hydrate (t2/select-one [:model/Table :created_at :updated_at :initial_sync_status] :id (mt/id :categories))
+ :collection)
{:schema "PUBLIC"
:name "CATEGORIES"
:display_name "Categories"
@@ -709,6 +713,14 @@
(is (=? {:metrics [(assoc metric :type "metric" :display "table")]}
(mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :categories))))))))
+(deftest ^:parallel table-segment-query-metadata-test
+ (testing "GET /api/table/:id/query_metadata"
+ (testing "segments include :definition_description"
+ (mt/with-temp [:model/Segment _ {:table_id (mt/id :venues)
+ :definition (:query (mt/mbql-query venues {:filter [:= $price 4]}))}]
+ (is (=? {:segments [{:definition_description "Filtered by Price is equal to 4"}]}
+ (mt/user-http-request :rasta :get 200 (format "table/%d/query_metadata" (mt/id :venues)))))))))
+
(defn- with-field-literal-id [{field-name :name, base-type :base_type :as field}]
(assoc field :id ["field" field-name {:base-type base-type}]))
diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.clj
index 4f4803e2008..43cf2865cd5 100644
--- a/test/metabase/warehouses_rest/api_test.clj
+++ b/test/metabase/warehouses_rest/api_test.clj
@@ -1945,6 +1945,16 @@
(is (= ["t1" "t2"]
(map :name (mt/user-http-request :lucky :get 200 (format "database/%d/schema/" db-id)))))))))
+(deftest ^:parallel get-schema-tables-publishing-test
+ (testing "GET /api/database/:id/schema/:schema"
+ (testing "should return is_published as true for published tables"
+ (mt/with-temp [:model/Database {database-id :id} {}
+ :model/Table _ {:db_id database-id :schema "public" :name "published-table" :is_published true}
+ :model/Table _ {:db_id database-id :schema "public" :name "unpublished-table" :is_published false}]
+ (let [tables (mt/user-http-request :rasta :get 200 (format "database/%s/schema/%s" database-id "public"))]
+ (is (true? (:is_published (m/find-first #(= "published-table" (:name %)) tables))))
+ (is (false? (:is_published (m/find-first #(= "unpublished-table" (:name %)) tables)))))))))
+
(deftest get-schema-tables-unreadable-metrics-are-not-returned-test
(mt/with-temp [:model/Collection model-coll {:name "Model Collection"}
:model/Card card (card-with-native-query
diff --git a/test/metabase/xrays/api/automagic_dashboards_test.clj b/test/metabase/xrays/api/automagic_dashboards_test.clj
index 8a89ae8f19b..c83ded1756e 100644
--- a/test/metabase/xrays/api/automagic_dashboards_test.clj
+++ b/test/metabase/xrays/api/automagic_dashboards_test.clj
@@ -4,7 +4,7 @@
[clojure.test :refer :all]
[malli.core :as mc]
[metabase.indexed-entities.models.model-index :as model-index]
- [metabase.permissions.models.permissions :as perms]
+ [metabase.permissions.core :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.permissions.test-util :as perms.test-util]
[metabase.query-processor :as qp]
diff --git a/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml b/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml
index ce28cd2100e..fbb7740515e 100644
--- a/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml
+++ b/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml
@@ -19,11 +19,13 @@ serdes/meta:
- id: Schemaless Table
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml
index 729d106ed21..ac332054ec8 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: CATEGORIES
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml
index 4f5d0b2b5fc..8db321a7d6e 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: CHECKINS
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml
index 3d830d18f4e..da7cb68fd55 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: ORDERS
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml
index 1f80f12972e..9d757511302 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: PEOPLE
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml
index 28e534e3f0b..f1a73db23f6 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: PRODUCTS
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml
index 641f15d2a1e..06ce03a1c32 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: REVIEWS
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml
index 0c009f6f0d6..85e1abbe330 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: USERS
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml
index 9fd12de75bc..24f14b9552d 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml
@@ -21,11 +21,13 @@ serdes/meta:
- id: VENUES
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/tables/linked_table/linked_table.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/tables/linked_table/linked_table.yaml
index 74015a1fa34..9933feb7aa2 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/tables/linked_table/linked_table.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/tables/linked_table/linked_table.yaml
@@ -19,11 +19,13 @@ serdes/meta:
- id: linked_table
model: Table
archived_at: null
+collection_id: null
data_authority: unconfigured
data_layer: null
data_source: null
database_require_filter: null
deactivated_at: null
+is_published: false
is_writable: null
owner_email: null
owner_user_id: null