The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Trim redundant Data Studio TablePicker end-to-end tests (#81848)
Anderson0a30b63176fc
diff --git a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio-search.cy.spec.ts b/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio-search.cy.spec.tsdeleted file mode 100644index 90ec3ad6cd9..00000000000--- a/e2e/test/scenarios/data-studio/data-model/datamodel-data-studio-search.cy.spec.ts+++ /dev/null@@ -1,211 +0,0 @@-import { WRITABLE_DB_ID } from "e2e/support/cypress_data";--const { H } = cy;-const { TablePicker } = H.DataModel;--describe("Search", () => {- beforeEach(() => {- cy.signInAsAdmin();- H.restore("postgres-writable");- H.resetSnowplow();- H.activateToken("pro-self-hosted");- H.resetTestTable({ type: "postgres", table: "multi_schema" });- H.resyncDatabase({ dbId: WRITABLE_DB_ID });- cy.intercept("GET", "/api/table?*").as("listTables");- });-- it("should support prefix-based search", () => {- H.DataModel.visitDataStudio();-- TablePicker.getSearchInput().type("an");- TablePicker.getTables().should("have.length", 3);- TablePicker.getTable("Analytic Events").should("be.visible");- TablePicker.getTable("Animals").should("be.visible");- H.expectUnstructuredSnowplowEvent({- event: "data_studio_table_picker_search_performed",- });- });-- it("should support wildcard search with *", () => {- H.DataModel.visitDataStudio();-- TablePicker.getSearchInput().type("irds");- TablePicker.get().findByText("No tables found").should("be.visible");- H.expectUnstructuredSnowplowEvent({- event: "data_studio_table_picker_search_performed",- });-- TablePicker.getSearchInput().clear().type("*irds");- TablePicker.getTables().should("have.length", 1);- TablePicker.getTable("Birds").should("be.visible");- H.expectUnstructuredSnowplowEvent(- {- event: "data_studio_table_picker_search_performed",- },- 2,- );- });-- it("should allow using shift key to select multiple tables", () => {- H.DataModel.visitDataStudio();- TablePicker.getSearchInput().type("a");-- TablePicker.getTables().should("have.length", 4);- TablePicker.getTable("Accounts").find('input[type="checkbox"]').click();- TablePicker.getTable("Animals")- .eq(0)- .find('input[type="checkbox"]')- .click({ shiftKey: true });-- cy.findByRole("heading", { name: /3 tables selected/i }).should(- "be.visible",- );- });-- it("should remove the active highlight once tables are selected", () => {- H.DataModel.visitDataStudio();-- TablePicker.getSearchInput().type("an");- TablePicker.getTable("Animals").eq(0).should("be.visible").click();- TablePicker.getTable("Animals")- .eq(0)- .should("have.attr", "aria-selected", "true");-- TablePicker.getTable("Animals")- .eq(0)- .find('input[type="checkbox"]')- .check();- TablePicker.getTable("Animals").eq(1).should("be.visible").click();-- TablePicker.getTable("Animals")- .eq(0)- .should("not.have.attr", "aria-selected", "true");- TablePicker.getTable("Animals")- .eq(1)- .should("not.have.attr", "aria-selected", "true");- });-- it("should select/deselect tables with clicking checkboxes", () => {- H.DataModel.visitDataStudio();- TablePicker.getSearchInput().type("a");- TablePicker.getTables().should("have.length", 4);- TablePicker.getTable("Accounts")- .find('input[type="checkbox"]')- .as("accountsCheckbox");- TablePicker.getTable("Analytic Events")- .find('input[type="checkbox"]')- .as("analyticEventsCheckbox");- cy.get("@accountsCheckbox").check();- cy.get("@analyticEventsCheckbox").check();- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "be.visible",- );- cy.get("@accountsCheckbox").uncheck();- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "not.exist",- );-- // clear selection when changing search query- cy.get("@accountsCheckbox").check();- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "be.visible",- );- TablePicker.getSearchInput().type("c");- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "not.exist",- );- });-- it("should select/deselect databases and schemas", () => {- H.DataModel.visitDataStudio();- TablePicker.getSearchInput().type("a");- // wait for the tables to be loaded- TablePicker.getTables().should("have.length", 4);- const postgres = "Writable Postgres12";- const sampleDatabaseName = "Sample Database";- const domesticSchema = "Domestic";-- TablePicker.getDatabaseCheckbox(sampleDatabaseName).click();- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "be.visible",- );- TablePicker.getDatabaseCheckbox(postgres).click();- cy.findByRole("heading", { name: /4 tables selected/i }).should(- "be.visible",- );- TablePicker.getSchemaCheckbox(domesticSchema).click();- cy.findByRole("heading", { name: /3 tables selected/i }).should(- "be.visible",- );- TablePicker.getDatabaseCheckbox(postgres).click();- cy.findByRole("heading", { name: /4 tables selected/i }).should(- "be.visible",- );- });-- it("should allow to hide/show table and schemas", () => {- H.DataModel.visitDataStudio();- TablePicker.getSearchInput().type("a");- const postgres = "Writable Postgres12";- const sampleDatabaseName = "Sample Database";- const domesticSchema = "Domestic";- const sampleDbTables = ["Accounts", "Analytic Events"];-- sampleDbTables.forEach((table) => {- TablePicker.getTable(table).should("be.visible");- });-- TablePicker.getDatabaseToggle(sampleDatabaseName).click();- sampleDbTables.forEach((table) => {- TablePicker.getTable(table).should("not.exist");- });-- TablePicker.getTable("Animals").should("have.length", 2);- TablePicker.getSchemaToggle(domesticSchema).click();- TablePicker.getTable("Animals").should("have.length", 1);-- TablePicker.getDatabaseToggle(postgres).click();- TablePicker.getTables().should("have.length", 0);- TablePicker.getDatabases().should("have.length", 2);- });-- it("should deselect and hide tables that are not in the search results", () => {- H.DataModel.visitDataStudio();-- TablePicker.getTables().should("have.length", 0);- TablePicker.getSearchInput().type("a");- TablePicker.getTables().should("have.length", 4);-- ["Writable Postgres12", "Sample Database"].forEach((database) => {- TablePicker.getDatabaseCheckbox(database).click();- });- cy.findByRole("heading", { name: /4 tables selected/i }).should(- "be.visible",- );- TablePicker.getTables()- .find('input[type="checkbox"]:checked')- .should("have.length", 4);-- TablePicker.openFilterPopover();- cy.findByTestId("table-picker-filter").within(() => {- TablePicker.selectFilterOption("Visibility layer", "Internal");- TablePicker.applyFilters();- });-- TablePicker.getTables()- .find('input[type="checkbox"]:checked')- .should("have.length", 0);-- TablePicker.getDatabaseCheckbox("Writable Postgres12").click();-- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "be.visible",- );-- TablePicker.selectFilterOption("Visibility layer", "Final");- TablePicker.get().findByText("No tables found").should("be.visible");- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "not.exist",- );- });-});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.tsindex c2d11252e8c..3ff7ca4bc38 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@@ -37,223 +37,7 @@ describe("scenarios > data studio > datamodel", () => {});describe("Table picker", () => {- describe("1 database, 1 schema", () => {- it("should allow to search for tables", () => {- H.DataModel.visitDataStudio();-- TablePicker.getSearchInput().type("or");- TablePicker.getTables().should("have.length", 1);- TablePicker.getTable("Orders").should("be.visible").click();- cy.location("pathname").should(- "eq",- `/data-studio/data/database/${SAMPLE_DB_ID}/schema/${SAMPLE_DB_SCHEMA_ID}/table/${ORDERS_ID}`,- );- TableSection.getNameInput().should("have.value", "Orders");-- cy.log("no results");- TablePicker.getSearchInput().clear().type("xyz");- TablePicker.get().findByText("No tables found").should("be.visible");-- cy.log("go back to browsing");- TablePicker.getSearchInput().clear();- TablePicker.getTables().should("have.length", 8);- });- });-- describe(- "mutliple databases, with single and multiple schemas",- { tags: "@external" },- () => {- beforeEach(() => {- H.restore("postgres-writable");- H.activateToken("pro-self-hosted");- cy.signInAsAdmin();-- H.resetTestTable({ type: "postgres", table: "multi_schema" });- H.resyncDatabase({ dbId: WRITABLE_DB_ID });- });-- it("should allow to search for tables", () => {- H.DataModel.visitDataStudio();-- TablePicker.getSearchInput().type("an");- TablePicker.getTables().should("have.length", 3);- TablePicker.getTable("Animals").should("have.length", 2);- TablePicker.getTable("Analytic Events").should("be.visible");-- TablePicker.getSearchInput().clear().type("ani");- TablePicker.getTables().should("have.length", 2);- TablePicker.getTable("Animals").eq(1).should("be.visible").click();-- cy.location("pathname").should((pathname) => {- return pathname.startsWith(- `/data-studio/data/database/${WRITABLE_DB_ID}/schema/${WRITABLE_DB_ID}:Wild/table/`,- );- });- TableSection.getNameInput().should("have.value", "Animals");-- cy.log("go back to browsing");- TablePicker.getSearchInput().clear();- TablePicker.getTables().should("have.length", 2);- });-- it("should restore previously selected table when expanding the tree", () => {- H.DataModel.visitDataStudio();-- TablePicker.getDatabase("Writable Postgres12").click();- TablePicker.getSchema("Domestic").click();- TablePicker.getTable("Animals").click();- TablePicker.getSchema("Wild").click();- TablePicker.getTable("Birds").click();- TablePicker.getTable("Birds").should(- "have.attr",- "aria-selected",- "true",- );-- TablePicker.getTable("Birds").find('input[type="checkbox"]').check();- TablePicker.getTable("Birds").should(- "not.have.attr",- "aria-selected",- "true",- );-- TablePicker.getDatabase("Writable Postgres12").click();- TablePicker.getDatabase("Writable Postgres12").click();-- TableSection.getNameInput().should("have.value", "Birds");- });- },- );-- describe("Extra info about tables", () => {- const databaseName = "Writable Postgres12";- const domesticSchema = "Domestic";- const wildSchema = "Wild";- const domesticAnimalsTable = "Animals";- const wildBirdsTable = "Birds";-- beforeEach(() => {- H.restore("postgres-writable");- H.activateToken("pro-self-hosted");- H.resetTestTable({ type: "postgres", table: "multi_schema" });- H.resyncDatabase({ dbId: WRITABLE_DB_ID });- });-- it("should show the table owner", () => {- cy.request("GET", "/api/user/current")- .its("body")- .then(({ id, common_name }) => {- cy.wrap(common_name).as("tableOwnerName");- return updateTableAttributes({- databaseId: WRITABLE_DB_ID,- displayName: domesticAnimalsTable,- attributes: { owner_user_id: id },- });- })- .as("ownerTableId");-- openWritableDomesticSchema(databaseName, domesticSchema);-- cy.get<string>("@tableOwnerName").then((ownerName) => {- TablePicker.getTable(domesticAnimalsTable)- .findByTestId("table-owner")- .should("contain", ownerName);- });- });-- it("should display the estimated row count", () => {- const EXPECTED_ROWS = 3210;-- cy.intercept(- "GET",- `/api/database/${WRITABLE_DB_ID}/schema/${domesticSchema}*`,- (req) => {- req.continue((res) => {- if (Array.isArray(res.body)) {- res.body = res.body.map((table) => {- if (- table.display_name === domesticAnimalsTable ||- table.name === domesticAnimalsTable- ) {- return {- ...table,- estimated_row_count: EXPECTED_ROWS,- };- }- return table;- });- }- });- },- );-- openWritableDomesticSchema(databaseName, domesticSchema);-- TablePicker.getTable(domesticAnimalsTable)- .findByTestId("table-expected-rows")- .should("contain", "3,210");- });-- it("should indicate published tables", () => {- getTableId({ databaseId: WRITABLE_DB_ID, name: domesticAnimalsTable })- .then((tableId) => {- H.createLibrary();- publishTables([tableId]);- })- .as("publishedTableId");-- openWritableDomesticSchema(databaseName, domesticSchema);-- TablePicker.getTable(domesticAnimalsTable)- .findByTestId("table-published")- .findByLabelText("Published")- .should("be.visible");-- TablePicker.getSchema(wildSchema).click();-- TablePicker.getTable(wildBirdsTable)- .icon("verified_round")- .should("not.exist");- });- });-describe("Filtering", () => {- it("should filter tables by visibility layer", () => {- updateTableAttributes({- databaseId: SAMPLE_DB_ID,- displayName: "Orders",- attributes: { data_layer: "final" },- }).as("finalTableId");-- updateTableAttributes({- databaseId: SAMPLE_DB_ID,- displayName: "Products",- attributes: { data_layer: "hidden" },- }).as("hiddenTableId");-- H.DataModel.visitDataStudio();-- TablePicker.openFilterPopover();-- cy.log("Filter popover should close on click outside");- H.DataModel.TablePicker.getSearchInput().click();- H.DataModel.TablePicker.getFilterForm().should("not.exist");-- TablePicker.openFilterPopover();- TablePicker.selectFilterOption("Visibility layer", "Final");- TablePicker.applyFilters();- H.expectUnstructuredSnowplowEvent({- event: "data_studio_table_picker_filters_applied",- });- H.expectUnstructuredSnowplowEvent({- event: "data_studio_table_picker_search_performed",- });-- cy.get<TableId>("@finalTableId").then(expectTableVisible);- cy.get<TableId>("@hiddenTableId").then(expectTableNotVisible);- });-it("should filter tables owned by unspecified", () => {cy.request("GET", "/api/user/current").its("body")@@ -355,218 +139,6 @@ describe("scenarios > data studio > datamodel", () => {cy.get<TableId>("@uploadedTableId").then(expectTableVisible);cy.get<TableId>("@ingestedTableId").then(expectTableNotVisible);});-- it("should filter unused tables only", () => {- H.restore("postgres-writable");- H.activateToken("pro-self-hosted");- H.resetTestTable({ type: "postgres", table: "multi_schema" });- H.resyncDatabase({ dbId: WRITABLE_DB_ID });- const usedTableName = "Animals";- const unusedTableName = "Birds";-- getTableId({- databaseId: WRITABLE_DB_ID,- displayName: usedTableName,- }).then((tableId) => {- cy.wrap(tableId).as("usedTableId");- return H.createQuestion({- database: WRITABLE_DB_ID,- name: "filter used question",- query: { "source-table": tableId },- });- });-- getTableId({- databaseId: WRITABLE_DB_ID,- name: unusedTableName,- }).as("unusedTableId");-- H.DataModel.visitDataStudio();-- TablePicker.openFilterPopover();- toggleUnusedFilter(true);- TablePicker.applyFilters();-- cy.get<TableId>("@unusedTableId").then(expectTableVisible);- cy.get<TableId>("@usedTableId").then(expectTableNotVisible);- });- });-- it("select/deselect functionality", { tags: ["@external"] }, () => {- H.restore("postgres-writable");- H.activateToken("pro-self-hosted");- H.resetTestTable({ type: "postgres", table: "multi_schema" });- H.resyncDatabase({ dbId: WRITABLE_DB_ID });-- H.DataModel.visitDataStudio();-- const databaseName = "Writable Postgres12";- const sampleDatabaseName = "Sample Database";- const domesticSchema = "Domestic";- const wildSchema = "Wild";- const domesticTables = ["Animals"];- const wildTables = ["Animals", "Birds"];- const tablesInDatabase = [- ...domesticTables.map((table) => ({- schema: domesticSchema,- table,- })),- ...wildTables.map((table) => ({- schema: wildSchema,- table,- })),- ];-- const getDatabaseCheckbox = () =>- TablePicker.getDatabase(databaseName).find('input[type="checkbox"]');- const getSchemaCheckbox = (schemaName: string) =>- TablePicker.getSchema(schemaName).find('input[type="checkbox"]');- const getWpTableCheckbox = (schemaName: string, tableName: string) =>- getTableCheckbox(WRITABLE_DB_ID, schemaName, tableName);- const getSampleTableCheckbox = (tableName: string) =>- getTableCheckbox(SAMPLE_DB_ID, "PUBLIC", tableName);-- function getTableCheckbox(- databaseId: number,- schemaName: string,- tableName: string,- ) {- return TablePicker.getTables()- .filter(- `[data-database-id="${databaseId}"][data-schema-name="${schemaName}"]`,- )- .filter(`:contains("${tableName}")`)- .find('input[type="checkbox"]');- }-- TablePicker.getDatabase(databaseName).click();- TablePicker.getSchema(domesticSchema).click();- TablePicker.getSchema(wildSchema).click();- TablePicker.getTables().should("have.length", 3);-- cy.log("selecting a db selects all schemas and tables in it");- getDatabaseCheckbox().check();- for (const schemaName of [domesticSchema, wildSchema]) {- getSchemaCheckbox(schemaName).should("be.checked");- }- for (const tableName of domesticTables) {- getWpTableCheckbox(domesticSchema, tableName).should("be.checked");- }-- for (const tableName of wildTables) {- getWpTableCheckbox(wildSchema, tableName).should("be.checked");- }- getDatabaseCheckbox().uncheck();- for (const schemaName of [domesticSchema, wildSchema]) {- getSchemaCheckbox(schemaName).should("not.be.checked");- }- for (const { schema, table } of tablesInDatabase) {- getWpTableCheckbox(schema, table).should("not.be.checked");- }-- cy.log("selecting a schema selects all tables in it");- getSchemaCheckbox(domesticSchema).check();- for (const tableName of domesticTables) {- getWpTableCheckbox(domesticSchema, tableName).should("be.checked");- }- getSchemaCheckbox(domesticSchema).uncheck();- for (const tableName of domesticTables) {- getWpTableCheckbox(domesticSchema, tableName).should("not.be.checked");- }-- cy.log("selecting all tables in a schema selects the schema");- getSchemaCheckbox(wildSchema).should("not.be.checked");- getWpTableCheckbox(wildSchema, "Animals").check();- getSchemaCheckbox(wildSchema).should("not.be.checked");- getWpTableCheckbox(wildSchema, "Birds").check();- getSchemaCheckbox(wildSchema).should("be.checked");- getSchemaCheckbox(wildSchema).uncheck();- for (const tableName of wildTables) {- getWpTableCheckbox(wildSchema, tableName).should("not.be.checked");- }-- cy.log("selecting all schemas in a db selects the db");- getSchemaCheckbox(domesticSchema).check();- getSchemaCheckbox(wildSchema).check();- getDatabaseCheckbox().should("be.checked");- getSchemaCheckbox(domesticSchema).uncheck();- getSchemaCheckbox(wildSchema).uncheck();- getDatabaseCheckbox().should("not.be.checked");-- cy.log("selecting all tables in a db selects the db");- cy.then(() => {- tablesInDatabase.forEach(({ schema, table }, index) => {- getWpTableCheckbox(schema, table).check();- if (index < tablesInDatabase.length - 1) {- getDatabaseCheckbox().should("not.be.checked");- }- });- });- getDatabaseCheckbox().should("be.checked");- getDatabaseCheckbox().uncheck();- for (const { schema, table } of tablesInDatabase) {- getWpTableCheckbox(schema, table).should("not.be.checked");- }-- cy.log("deselecting a table updates parent state");- getDatabaseCheckbox().check();- getWpTableCheckbox(wildSchema, "Birds").uncheck();- getSchemaCheckbox(wildSchema).should("not.be.checked");- // partially selected now, so clicking twice to make it unchecked- getDatabaseCheckbox().should("not.be.checked");- getDatabaseCheckbox().check();- getDatabaseCheckbox().uncheck();- for (const { schema, table } of tablesInDatabase) {- getWpTableCheckbox(schema, table).should("not.be.checked");- }-- cy.log("deselecting a schema clears its tables");- getSchemaCheckbox(domesticSchema).check();- cy.findByPlaceholderText("Give this table a name")- .should("have.value", domesticTables[0])- .should("be.visible");- getSchemaCheckbox(domesticSchema).uncheck();-- cy.log("schema toggle handles partially selected state");- getSchemaCheckbox(wildSchema).check();- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "be.visible",- );- getWpTableCheckbox(wildSchema, "Birds").uncheck();- cy.findByPlaceholderText("Give this table a name")- .should("have.value", domesticTables[0])- .should("be.visible");-- cy.log("first click selects all tables");- getSchemaCheckbox(wildSchema).click();- cy.findByRole("heading", { name: /2 tables selected/i }).should(- "be.visible",- );- cy.log("second click deselects all tables");- getSchemaCheckbox(wildSchema).click();- cy.findAllByRole("heading", { name: /table[s]? selected/i }).should(- "have.length",- 0,- );- for (const tableName of wildTables) {- getWpTableCheckbox(wildSchema, tableName).should("not.be.checked");- }-- cy.log("shift + click selects a range of tables");- TablePicker.getDatabase(databaseName).click();- TablePicker.getDatabase(sampleDatabaseName).click();-- getSampleTableCheckbox("Orders").should("not.be.checked");- getSampleTableCheckbox("People").should("not.be.checked");- getSampleTableCheckbox("Products").should("not.be.checked");-- getSampleTableCheckbox("Orders").click();- getSampleTableCheckbox("Products").click({ shiftKey: true });-- getSampleTableCheckbox("Orders").should("be.checked");- getSampleTableCheckbox("People").should("be.checked");- getSampleTableCheckbox("Products").should("be.checked");- getSampleTableCheckbox("Feedback").should("not.be.checked");});});@@ -1413,14 +985,6 @@ function selectOwnerByEmail(email: string) {H.popover().contains(email).click();}-function toggleUnusedFilter(checked: boolean) {- if (checked) {- cy.findByLabelText("Table isn’t referenced by anything").check();- } else {- cy.findByLabelText("Table isn’t referenced by anything").uncheck();- }-}-function expectTableVisible(tableId: TableId) {findSearchResultByTableId(tableId).should("exist");}@@ -1433,12 +997,6 @@ function findSearchResultByTableId(tableId: TableId) {return cy.findAllByTestId("tree-item").filter(`[data-table-id="${tableId}"]`);}-function openWritableDomesticSchema(databaseName: string, schemaName: string) {- H.DataModel.visitDataStudio();- TablePicker.getDatabase(databaseName).click();- TablePicker.getSchema(schemaName).click();-}-function getTableId({databaseId,displayName,@@ -1493,19 +1051,6 @@ function updateTableAttributes({});}-function publishTables(tableIds: TableId[]) {- return cy.request("GET", "/api/ee/library").then(({ body }) => {- const dataCollection = body.effective_children?.find(- (collection: { type?: string }) => collection.type === "library-data",- );-- return cy.request("POST", "/api/ee/data-studio/table/publish-tables", {- table_ids: tableIds,- collection_id: dataCollection.id,- });- });-}-function verifyAndCloseToast(message: string) {H.undoToast().should("contain.text", message);H.undoToast().icon("close").click({ force: true });diff --git a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/FilterPopover.tsx b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/FilterPopover.tsxindex b8f4212b473..b779adfe03f 100644--- a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/FilterPopover.tsx+++ b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/FilterPopover.tsx@@ -78,6 +78,7 @@ export function FilterPopover({ filters, isLibraryEnabled, onSubmit }: Props) {<DataSourceInputclearableshowMetabaseTransform+ showUnknown={false}value={form.dataSource}onChange={(dataSource) => {setForm((form) => ({ ...form, dataSource }));diff --git a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/SearchNew.tsx b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/SearchNew.tsxindex b55873c1364..a2c3ae51305 100644--- a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/SearchNew.tsx+++ b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/SearchNew.tsx@@ -145,7 +145,7 @@ export function SearchNew({return tables.filter((table) => allowedDatabaseIds.has(table.db_id));}, [allowedDatabaseIds, tables]);- const isLoading = isLoadingTables || isLoadingDatabases;+ const isLoading = isLoadingTables || isFetchingTables || isLoadingDatabases;const resultTree = useMemo(() => buildResultTree(filteredTables),diff --git a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsxindex 4ad0819843a..499de221d44 100644--- a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePicker.unit.spec.tsx@@ -11,14 +11,18 @@ import {import { mockSettings } from "__support__/settings";import { createMockState } from "__support__/state";import {+ fireEvent,mockGetBoundingClientRect,renderWithProviders,screen,waitFor,+ within,} from "__support__/ui";+import * as Analytics from "metabase/analytics";import { SelectionProvider } from "metabase/data-studio/data-model/pages/DataModel/contexts/SelectionContext";+import { reinitialize } from "metabase/plugins";import { Route } from "metabase/router";-import type { Database, TokenFeatures, User } from "metabase-types/api";+import type { Database, Table, TokenFeatures, User } from "metabase-types/api";import {createMockDatabase,createMockSchema,@@ -41,6 +45,7 @@ beforeEach(() => {afterEach(() => {jest.restoreAllMocks();+ reinitialize();});const PUBLIC_SCHEMA = createMockSchema({@@ -137,6 +142,38 @@ const DATABASE_WITH_UNNAMED_SCHEMA = createMockDatabase({tables: [CORGE, GRAULT, GLORP],});+const BIRDS_TABLE = createMockTable({+ id: nextId(),+ name: "BIRDS",+ display_name: "Birds",+ schema: PUBLIC_SCHEMA.name,+});++const ORDER_ITEM_DISCOUNT_TABLE = createMockTable({+ id: nextId(),+ name: "ORDER_ITEM_DISCOUNT",+ display_name: "Order Item Discount",+ schema: PUBLIC_SCHEMA.name,+});++const LITERAL_SEARCH_TABLE = createMockTable({+ id: nextId(),+ name: "what-a_cool%table\\name",+ display_name: "Literal Search Table",+ schema: PUBLIC_SCHEMA.name,+});++const SEARCH_SEMANTICS_DATABASE = createMockDatabase({+ id: nextId(),+ name: "SEARCH_SEMANTICS_DATABASE",+ tables: [+ FOO_TABLE,+ BIRDS_TABLE,+ ORDER_ITEM_DISCOUNT_TABLE,+ LITERAL_SEARCH_TABLE,+ ],+});+const MOCK_DATABASES = [DATABASE_WITH_MULTIPLE_SCHEMAS,DATABASE_WITH_SINGLE_SCHEMA,@@ -149,6 +186,56 @@ const currentUser: User = createMockUser({is_superuser: true,});+interface FilterRequestCase {+ name: string;+ selectFilter: () => Promise<void>;+ expectedParams: Record<string, string>;+ tokenFeatures?: Partial<TokenFeatures>;+}++const FILTER_REQUEST_CASES: FilterRequestCase[] = [+ {+ name: "data-layer",+ selectFilter: () => selectFilterOption("Visibility layer", "Final"),+ expectedParams: { "data-layer": "final" },+ },+ {+ name: "data-source",+ selectFilter: () => selectFilterOption("Source", "Uploaded data"),+ expectedParams: { "data-source": "upload" },+ },+ {+ name: "owner-user-id",+ selectFilter: () => selectFilterOption("Owner", currentUser.common_name),+ expectedParams: { "owner-user-id": String(currentUser.id) },+ },+ {+ name: "owner-email",+ selectFilter: selectOwnerEmail,+ expectedParams: { "owner-email": "[email protected]" },+ },+ {+ name: "orphan-only",+ selectFilter: () => selectFilterOption("Owner", "Unspecified"),+ expectedParams: { "orphan-only": "true" },+ },+ {+ name: "unused-only",+ selectFilter: () =>+ userEvent.click(+ screen.getByLabelText("Table isn’t referenced by anything"),+ ),+ expectedParams: { "unused-only": "true" },+ },+ {+ name: "published-only",+ selectFilter: () =>+ userEvent.click(screen.getByLabelText("Published tables only")),+ expectedParams: { "published-only": "true" },+ tokenFeatures: { library: true },+ },+];+function setup({path = {},databases = MOCK_DATABASES,@@ -437,6 +524,121 @@ describe("TablePicker", () => {expect(labels).toContain("Hidden");expect(labels).toContain("Final");});++ it("keeps the active table while its database is collapsed and restored", async () => {+ setup({+ path: {+ databaseId: DATABASE_WITH_MULTIPLE_SCHEMAS.id,+ schemaName: FOO_TABLE.schema,+ tableId: FOO_TABLE.id,+ },+ });+ await waitLoading();++ const initialTableRow = tableItem(FOO_TABLE.id);+ expect(initialTableRow).toHaveAttribute("aria-selected", "true");+ if (!initialTableRow) {+ return;+ }++ await userEvent.click(within(initialTableRow).getByRole("checkbox"));+ expect(tableItem(FOO_TABLE.id)).toHaveAttribute("aria-selected", "false");++ await clickItem(DATABASE_WITH_MULTIPLE_SCHEMAS);+ expect(tableItem(FOO_TABLE.id)).not.toBeInTheDocument();+ await clickItem(DATABASE_WITH_MULTIPLE_SCHEMAS);++ await waitFor(() => {+ expect(tableItem(FOO_TABLE.id)).toBeInTheDocument();+ });+ const restoredTableRow = tableItem(FOO_TABLE.id);+ expect(restoredTableRow).toBeInTheDocument();+ if (!restoredTableRow) {+ return;+ }++ const restoredCheckbox = within(restoredTableRow).getByRole("checkbox");+ expect(restoredCheckbox).toBeChecked();+ await userEvent.click(restoredCheckbox);+ expect(tableItem(FOO_TABLE.id)).toHaveAttribute("aria-selected", "true");+ });++ it("renders a user owner, formatted row count, and published state", async () => {+ const table = createMockTable({+ id: nextId(),+ name: "KNOWN_OWNER",+ display_name: "Known Owner",+ schema: PUBLIC_SCHEMA.name,+ owner_user_id: currentUser.id,+ estimated_row_count: 3210,+ is_published: true,+ });++ const row = await setupMetadataTable(table);+ expect(row).toBeInTheDocument();+ if (!row) {+ return;+ }++ expect(within(row).getByTestId("table-owner")).toHaveTextContent(+ currentUser.common_name,+ );+ expect(within(row).getByTestId("table-expected-rows")).toHaveTextContent(+ "3,210",+ );+ expect(within(row).getByLabelText("Published")).toBeVisible();+ });++ it("renders an email owner and a zero row count", async () => {+ const table = createMockTable({+ id: nextId(),+ name: "EMAIL_OWNER",+ display_name: "Email Owner",+ schema: PUBLIC_SCHEMA.name,+ owner_user_id: null,+ owner_email: "[email protected]",+ estimated_row_count: 0,+ is_published: false,+ });++ const row = await setupMetadataTable(table);+ expect(row).toBeInTheDocument();+ if (!row) {+ return;+ }++ expect(within(row).getByTestId("table-owner")).toHaveTextContent(+ "[email protected]",+ );+ expect(within(row).getByTestId("table-expected-rows")).toHaveTextContent(+ "0",+ );+ expect(within(row).queryByLabelText("Published")).not.toBeInTheDocument();+ });++ it("omits empty owner and row count cells", async () => {+ const table = createMockTable({+ id: nextId(),+ name: "EMPTY_METADATA",+ display_name: "Empty Metadata",+ schema: PUBLIC_SCHEMA.name,+ owner_user_id: null,+ owner_email: null,+ estimated_row_count: null,+ is_published: false,+ });++ const row = await setupMetadataTable(table);+ expect(row).toBeInTheDocument();+ if (!row) {+ return;+ }++ expect(within(row).queryByTestId("table-owner")).not.toBeInTheDocument();+ expect(+ within(row).queryByTestId("table-expected-rows"),+ ).not.toBeInTheDocument();+ });});describe("Search view", () => {@@ -460,108 +662,153 @@ describe("TablePicker", () => {expect(item(BAR_TABLE)).not.toBeInTheDocument();});- it("should render a message when no results are found", async () => {+ it("selects a range of table checkboxes with shift+click", async () => {setup();-- await waitLoading();- await userEvent.type(searchInput(), "nonexistent");await waitLoading();+ await userEvent.type(searchInput(), "Q");await waitFor(() => {- expect(screen.getByText("No tables found")).toBeInTheDocument();+ expect(tableItem(QUU.id)).toBeInTheDocument();+ expect(tableItem(QUX.id)).toBeInTheDocument();});+ const firstRow = tableItem(QUU.id);+ const secondRow = tableItem(QUX.id);+ if (!firstRow || !secondRow) {+ return;+ }++ const firstCheckbox = within(firstRow).getByRole("checkbox");+ const secondCheckbox = within(secondRow).getByRole("checkbox");+ await userEvent.click(firstCheckbox);+ fireEvent.click(secondCheckbox, { shiftKey: true });++ expect(firstCheckbox).toBeChecked();+ expect(secondCheckbox).toBeChecked();});- it("should clear search and return to tree view", async () => {+ it("clears selected tables when filters or search terms change", async () => {setup();-await waitLoading();- await userEvent.type(searchInput(), "foo");- await waitLoading();+ const quuCheckbox = () =>+ within(screen.getByRole("row", { name: /Quu$/ })).getByRole("checkbox");- await waitFor(() => {- expect(item(FOO_TABLE)).toBeInTheDocument();- });+ await userEvent.type(searchInput(), "Q");+ expect(await screen.findByText(QUU.display_name)).toBeInTheDocument();- await userEvent.clear(searchInput());- await waitLoading();+ await userEvent.click(quuCheckbox());+ expect(quuCheckbox()).toBeChecked();- // Should return to tree view with databases- await waitFor(() => {- expect(item(DATABASE_WITH_MULTIPLE_SCHEMAS)).toBeInTheDocument();- });- expect(item(DATABASE_WITH_SINGLE_SCHEMA)).toBeInTheDocument();+ await openFilters();+ await selectFilterOption("Visibility layer", "Final");+ await userEvent.click(screen.getByRole("button", { name: "Apply" }));+ await waitFor(() => expect(quuCheckbox()).not.toBeChecked());++ await userEvent.click(quuCheckbox());+ expect(quuCheckbox()).toBeChecked();++ await userEvent.type(searchInput(), "u");+ await waitFor(() => expect(quuCheckbox()).not.toBeChecked());});- it("should search case-insensitively", async () => {+ it("should render a message when no results are found", async () => {setup();await waitLoading();-- // Search with uppercase- await userEvent.type(searchInput(), "BAR");+ await userEvent.type(searchInput(), "nonexistent");await waitLoading();- // Should find "Bar" tableawait waitFor(() => {- expect(item(BAR_TABLE)).toBeInTheDocument();+ expect(screen.getByText("No tables found")).toBeInTheDocument();});- expect(item(FOO_TABLE)).not.toBeInTheDocument();});- it("should support partial matching", async () => {+ it("should clear search and return to tree view", async () => {setup();await waitLoading();- // Search for partial string "oo" should match "Foo"- await userEvent.type(searchInput(), "oo");+ await userEvent.type(searchInput(), "foo");await waitLoading();await waitFor(() => {expect(item(FOO_TABLE)).toBeInTheDocument();});- expect(item(BAR_TABLE)).not.toBeInTheDocument();- // Clear and search for "ar" should match "Bar"await userEvent.clear(searchInput());await waitLoading();- await userEvent.type(searchInput(), "ar");- await waitLoading();-+ // Should return to tree view with databasesawait waitFor(() => {- expect(item(BAR_TABLE)).toBeInTheDocument();+ expect(item(DATABASE_WITH_MULTIPLE_SCHEMAS)).toBeInTheDocument();});- expect(item(FOO_TABLE)).not.toBeInTheDocument();+ expect(item(DATABASE_WITH_SINGLE_SCHEMA)).toBeInTheDocument();});- it("should support wildcard search with *", async () => {+ it("should search case-insensitively", async () => {setup();await waitLoading();- // Search with wildcard pattern- await userEvent.type(searchInput(), "Q*");+ // Search with uppercase+ await userEvent.type(searchInput(), "BAR");await waitLoading();- // Should match both QUU and QUX+ // Should find "Bar" tableawait waitFor(() => {- expect(item(QUU)).toBeInTheDocument();+ expect(item(BAR_TABLE)).toBeInTheDocument();});- expect(item(QUX)).toBeInTheDocument();expect(item(FOO_TABLE)).not.toBeInTheDocument();- expect(item(BAR_TABLE)).not.toBeInTheDocument();});+ it.each([+ { term: "oo", expectedText: "No tables found", expectedTableCount: 0 },+ {+ term: "Ite",+ expectedText: ORDER_ITEM_DISCOUNT_TABLE.display_name,+ expectedTableCount: 1,+ },+ {+ term: "irds",+ expectedText: "No tables found",+ expectedTableCount: 0,+ },+ {+ term: "*irds",+ expectedText: BIRDS_TABLE.display_name,+ expectedTableCount: 1,+ },+ {+ term: "what-a_cool%table\\name",+ expectedText: LITERAL_SEARCH_TABLE.display_name,+ expectedTableCount: 1,+ },+ {+ term: "what%a%cool%table%name",+ expectedText: "No tables found",+ expectedTableCount: 0,+ },+ ])(+ "matches '$term' with backend-equivalent semantics (UXW-5189)",+ async ({ term, expectedText, expectedTableCount }) => {+ setup({ databases: [SEARCH_SEMANTICS_DATABASE] });++ await waitLoading();+ await userEvent.type(searchInput(), term);+ await waitLoading();++ expect(await screen.findByText(expectedText)).toBeInTheDocument();+ expect(tableItems()).toHaveLength(expectedTableCount);+ },+ );+it("should match tables from all databases in search", async () => {setup();await waitLoading();// Search for a pattern that matches tables in different databases- await userEvent.type(searchInput(), "o");+ await userEvent.type(searchInput(), "*o*");await waitLoading();// Should find FOO (from DATABASE_WITH_MULTIPLE_SCHEMAS)@@ -578,9 +825,49 @@ describe("TablePicker", () => {expect(item(QUX)).not.toBeInTheDocument();expect(item(GRAULT)).not.toBeInTheDocument();});++ it("routes to the selected result when table names are duplicated", async () => {+ const domesticAnimals = createMockTable({+ id: nextId(),+ name: "DOMESTIC_ANIMALS",+ display_name: "Animals",+ schema: "Domestic",+ });+ const wildAnimals = createMockTable({+ id: nextId(),+ name: "WILD_ANIMALS",+ display_name: "Animals",+ schema: "Wild",+ });+ const database = createMockDatabase({+ id: nextId(),+ name: "Duplicate tables",+ tables: [domesticAnimals, wildAnimals],+ });+ const { onChange } = setup({ databases: [database] });++ await waitLoading();+ await userEvent.type(searchInput(), "Ani");+ await waitLoading();++ await waitFor(() => {+ expect(screen.getAllByText("Animals")).toHaveLength(2);+ });+ const wildRow = tableItem(wildAnimals.id);+ expect(wildRow).toBeInTheDocument();+ if (wildRow) {+ await userEvent.click(wildRow);+ }++ expect(onChange).toHaveBeenCalledWith({+ databaseId: database.id,+ schemaName: wildAnimals.schema,+ tableId: wildAnimals.id,+ });+ });});- describe("Published tables filter", () => {+ describe("Filters", () => {it("is hidden when the Library is not enabled", async () => {setup();await waitLoading();@@ -595,34 +882,197 @@ describe("TablePicker", () => {).not.toBeInTheDocument();});- it("sends published-only=true when enabled, checked, and applied", async () => {- setup({ tokenFeatures: { library: true } });+ it.each(FILTER_REQUEST_CASES)(+ "maps $name to the table search request",+ async ({ selectFilter, expectedParams, tokenFeatures }) => {+ const trackSimpleEvent = jest.spyOn(Analytics, "trackSimpleEvent");+ trackSimpleEvent.mockClear();+ setup({ tokenFeatures });+ await waitLoading();++ await openFilters();+ await selectFilter();+ await userEvent.click(screen.getByRole("button", { name: "Apply" }));++ await expectTableSearchParams(expectedParams);+ expect(trackSimpleEvent).toHaveBeenCalledWith({+ event: "data_studio_table_picker_filters_applied",+ });+ expect(trackSimpleEvent).toHaveBeenCalledWith({+ event: "data_studio_table_picker_search_performed",+ });+ },+ );++ it("does not offer an unsupported unspecified source filter (UXW-5189)", async () => {+ setup();await waitLoading();- // Enter search mode first so the table-search endpoint matches the request- await userEvent.type(searchInput(), "o");+ await openFilters();+ await userEvent.click(screen.getByRole("textbox", { name: "Source" }));++ expect(+ screen.getByRole("option", { name: "Uploaded data" }),+ ).toBeVisible();+ expect(+ screen.queryByRole("option", { name: "Unspecified" }),+ ).not.toBeInTheDocument();+ });++ it("closes the filter popover when clicking outside", async () => {+ setup();await waitLoading();- await userEvent.click(screen.getByRole("button", { name: "Filter" }));- await userEvent.click(- await screen.findByLabelText("Published tables only"),- );+ await openFilters();+ await userEvent.click(searchInput());++ expect(+ screen.queryByTestId("table-picker-filter"),+ ).not.toBeInTheDocument();+ });++ it("hides stale results while a filter request is in flight (UXW-5189)", async () => {+ const initialTables = [+ { ...FOO_TABLE, db_id: DATABASE_WITH_MULTIPLE_SCHEMAS.id },+ ];+ const filteredTables = [+ { ...BAR_TABLE, db_id: DATABASE_WITH_MULTIPLE_SCHEMAS.id },+ ];+ let resolveFilteredTables: (tables: Table[]) => void = () => {};+ const filteredTablesRequest = new Promise<Table[]>((resolve) => {+ resolveFilteredTables = resolve;+ });+ setup();+ fetchMock.modifyRoute("table-search", {+ response: (call) => {+ const dataLayer = new URL(call.url).searchParams.get("data-layer");+ return dataLayer === "final" ? filteredTablesRequest : initialTables;+ },+ });+ await waitLoading();++ await userEvent.type(searchInput(), "*");+ expect(+ await screen.findByText(FOO_TABLE.display_name),+ ).toBeInTheDocument();++ await openFilters();+ await selectFilterOption("Visibility layer", "Final");await userEvent.click(screen.getByRole("button", { name: "Apply" }));++ await waitFor(() => {+ expect(fetchMock.callHistory.calls("table-search")).toHaveLength(2);+ });+ expect(screen.getByTestId("loading-indicator")).toBeVisible();+ expect(tableItem(FOO_TABLE.id)).not.toBeInTheDocument();+ resolveFilteredTables(filteredTables);++ expect(+ await screen.findByText(BAR_TABLE.display_name),+ ).toBeInTheDocument();+ });+ });++ describe("Analytics", () => {+ it("tracks a table search request", async () => {+ const trackSimpleEvent = jest.spyOn(Analytics, "trackSimpleEvent");+ trackSimpleEvent.mockClear();+ setup();await waitLoading();+ await userEvent.type(searchInput(), "foo");+await waitFor(() => {- const calls = fetchMock.callHistory.calls("path:/api/table");- const lastCall = calls.at(-1);- expect(lastCall).toBeDefined();- const url = new URL(lastCall!.url);- expect(url.searchParams.get("published-only")).toBe("true");+ expect(trackSimpleEvent).toHaveBeenCalledWith({+ event: "data_studio_table_picker_search_performed",+ });+ });++ await userEvent.type(searchInput(), "d");+ expect(await screen.findByText("No tables found")).toBeInTheDocument();+ await waitFor(() => {+ const searchEvents = trackSimpleEvent.mock.calls.filter(+ ([event]) =>+ event.event === "data_studio_table_picker_search_performed",+ );+ expect(searchEvents).toHaveLength(2);});});});});function searchInput() {- return screen.getByRole("textbox");+ return screen.getByPlaceholderText("Search tables");+}++function tableItem(tableId: Table["id"]) {+ return (+ tableItems().find(+ (row) => row.getAttribute("data-table-id") === String(tableId),+ ) ?? null+ );+}++function tableItems() {+ return screen+ .queryAllByTestId("tree-item")+ .filter((row) => row.hasAttribute("data-table-id"));+}++async function setupMetadataTable(table: Table) {+ const database = createMockDatabase({+ id: nextId(),+ name: "Metadata database",+ tables: [table],+ });+ setup({ databases: [database], tokenFeatures: { library: true } });+ await waitLoading();+ await waitFor(() => {+ expect(tableItem(table.id)).toBeInTheDocument();+ });+ return tableItem(table.id);+}++async function openFilters() {+ await userEvent.click(screen.getByRole("button", { name: "Filter" }));+ expect(await screen.findByTestId("table-picker-filter")).toBeInTheDocument();+}++async function selectFilterOption(label: string, option: string) {+ const filterForm = screen.getByTestId("table-picker-filter");+ await userEvent.click(+ within(filterForm).getByRole("textbox", { name: label }),+ );+ const listbox = await within(filterForm).findByRole("listbox", {+ name: label,+ });+ await userEvent.click(within(listbox).getByText(option));+}++async function selectOwnerEmail() {+ const email = "[email protected]";+ const filterForm = screen.getByTestId("table-picker-filter");+ await userEvent.type(+ within(filterForm).getByRole("textbox", { name: "Owner" }),+ email,+ );+ await userEvent.click(await within(filterForm).findByText(email));+}++async function expectTableSearchParams(expectedParams: Record<string, string>) {+ await waitFor(() => {+ expect(fetchMock.callHistory.calls("table-search")).toHaveLength(1);+ });+ const lastCall = fetchMock.callHistory.calls("table-search").at(-1);+ expect(lastCall).toBeDefined();+ if (!lastCall) {+ return;+ }++ expect(Object.fromEntries(new URL(lastCall.url).searchParams)).toEqual({+ term: "",+ ...expectedParams,+ });}async function waitLoading() {diff --git a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePickerTreeTable.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePickerTreeTable.unit.spec.tsxindex fb39ae93cb7..eea55cc5905 100644--- a/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePickerTreeTable.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/data-model/components/TablePicker/components/TablePickerTreeTable.unit.spec.tsx@@ -268,6 +268,66 @@ describe("handleCheckboxToggle", () => {expect(result.lastSelectedRowIndex).toBe(0);});+ it("should select all missing children when parents are partially selected", () => {+ const table1 = createMockTableNode(1, "public", 101);+ const table2 = createMockTableNode(1, "public", 102);+ const table3 = createMockTableNode(1, "private", 103);+ const schema1 = createMockSchemaNode(1, "public", [table1, table2]);+ const schema2 = createMockSchemaNode(1, "private", [table3]);+ const database = createMockDatabaseNode(1, [schema1, schema2]);+ const schemaRow = createCheckboxRow({+ type: "schema",+ nodeKey: schema1.key,+ databaseId: 1,+ });+ const databaseRow = createCheckboxRow({+ type: "database",+ nodeKey: database.key,+ databaseId: 1,+ });+ const selection: NodeSelection = {+ tables: new Set([101]),+ schemas: new Set(),+ databases: new Set(),+ };+ const nodeKeyToOriginal = new Map<string, TreeNode>([+ [schema1.key, schema1],+ [database.key, database],+ ]);++ const schemaResult = changeCheckboxSelection({+ row: schemaRow,+ index: 0,+ isShiftPressed: false,+ selection,+ lastSelectedRowIndex: null,+ rows: [schemaRow, databaseRow],+ nodeKeyToOriginal,+ });++ expect(schemaResult.selection.tables).toEqual(new Set([101, 102]));+ expect(schemaResult.selection.schemas).toEqual(new Set());+ expect(schemaResult.selection.databases).toEqual(new Set());+ expect(schemaResult.lastSelectedRowIndex).toBe(0);++ const databaseResult = changeCheckboxSelection({+ row: databaseRow,+ index: 1,+ isShiftPressed: false,+ selection: schemaResult.selection,+ lastSelectedRowIndex: schemaResult.lastSelectedRowIndex,+ rows: [schemaRow, databaseRow],+ nodeKeyToOriginal,+ });++ expect(databaseResult.selection.tables).toEqual(+ new Set([101, 102, 103]),+ );+ expect(databaseResult.selection.schemas).toEqual(new Set());+ expect(databaseResult.selection.databases).toEqual(new Set());+ expect(databaseResult.lastSelectedRowIndex).toBe(1);+ });+it("should select empty database without children", () => {const database = createMockDatabaseNode(1, []);const row = createCheckboxRow({diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsxindex 8ef0bd3acc9..39147071534 100644--- a/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/DataModel.unit.spec.tsx@@ -611,6 +611,70 @@ describe("DataModel", () => {});describe("multi schema database", () => {+ it("switches between single-table and bulk editing as selection changes", async () => {+ await setup({+ databases: [SAMPLE_DB_MULTI_SCHEMA],+ waitForTable: false,+ });++ await userEvent.click(+ await findTablePickerSchema(PEOPLE_TABLE_MULTI_SCHEMA.schema),+ );+ expect(+ await findTablePickerTable(PEOPLE_TABLE_MULTI_SCHEMA.display_name),+ ).toBeInTheDocument();+ await userEvent.click(+ await findTablePickerSchemaCheckbox(PEOPLE_TABLE_MULTI_SCHEMA.schema),+ );++ expect(+ await screen.findByPlaceholderText("Give this table a name"),+ ).toHaveValue(PEOPLE_TABLE_MULTI_SCHEMA.display_name);+ expect(+ await findTablePickerSchemaCheckbox(PEOPLE_TABLE_MULTI_SCHEMA.schema),+ ).toBeChecked();++ await userEvent.click(+ await findTablePickerSchema(REVIEWS_TABLE_MULTI_SCHEMA.schema),+ );+ expect(+ await findTablePickerTable(REVIEWS_TABLE_MULTI_SCHEMA.display_name),+ ).toBeInTheDocument();+ await userEvent.click(+ await findTablePickerSchemaCheckbox(REVIEWS_TABLE_MULTI_SCHEMA.schema),+ );++ expect(+ await findTablePickerSchemaCheckbox(PEOPLE_TABLE_MULTI_SCHEMA.schema),+ ).toBeChecked();+ expect(+ await findTablePickerSchemaCheckbox(REVIEWS_TABLE_MULTI_SCHEMA.schema),+ ).toBeChecked();+ expect(+ await screen.findByRole("heading", { name: /2 tables selected/i }),+ ).toBeInTheDocument();+ expect(+ screen.queryByPlaceholderText("Give this table a name"),+ ).not.toBeInTheDocument();++ await userEvent.click(+ await findTablePickerSchemaCheckbox(REVIEWS_TABLE_MULTI_SCHEMA.schema),+ );++ expect(+ await screen.findByPlaceholderText("Give this table a name"),+ ).toHaveValue(PEOPLE_TABLE_MULTI_SCHEMA.display_name);+ expect(+ screen.queryByRole("heading", { name: /tables selected/i }),+ ).not.toBeInTheDocument();+ expect(+ await findTablePickerSchemaCheckbox(PEOPLE_TABLE_MULTI_SCHEMA.schema),+ ).toBeChecked();+ expect(+ await findTablePickerSchemaCheckbox(REVIEWS_TABLE_MULTI_SCHEMA.schema),+ ).not.toBeChecked();+ });+it("should not select the first schema if there are multiple schemas", async () => {await setup({ databases: [SAMPLE_DB_MULTI_SCHEMA], waitForTable: false });@@ -1091,6 +1155,10 @@ async function findTablePickerTable(name: string) {return await findTablePickerItem("table", name);}+async function findTablePickerSchemaCheckbox(name: string) {+ return within(await findTablePickerSchema(name)).getByRole("checkbox");+}+async function findTablePickerItem(type: "table" | "schema" | "database",name: string,diff --git a/frontend/src/metabase/data-studio/data-model/pages/DataModel/contexts/SelectionContext.unit.spec.tsx b/frontend/src/metabase/data-studio/data-model/pages/DataModel/contexts/SelectionContext.unit.spec.tsxnew file mode 100644index 00000000000..80894bc906d--- /dev/null+++ b/frontend/src/metabase/data-studio/data-model/pages/DataModel/contexts/SelectionContext.unit.spec.tsx@@ -0,0 +1,116 @@+import userEvent from "@testing-library/user-event";++import { render, screen } from "__support__/ui";+import type { DatabaseId, TableId } from "metabase-types/api";++import { SelectionProvider, useSelection } from "./SelectionContext";++const FIRST_TABLE_ID: TableId = 10;+const SECOND_TABLE_ID: TableId = 20;+const DATABASE_ID: DatabaseId = 30;+const SCHEMA_ID = `${DATABASE_ID}:PUBLIC`;++function SelectionHarness() {+ const {+ selectedTables,+ setSelectedTables,+ selectedSchemas,+ setSelectedSchemas,+ selectedDatabases,+ setSelectedDatabases,+ resetSelection,+ filterSelectedTables,+ hasSelectedItems,+ selectedItemsCount,+ hasOnlyOneTableSelected,+ hasSelectedMoreThanOneTable,+ } = useSelection();++ const selectItems = () => {+ setSelectedTables(new Set([FIRST_TABLE_ID, SECOND_TABLE_ID]));+ setSelectedSchemas(new Set([SCHEMA_ID]));+ setSelectedDatabases(new Set([DATABASE_ID]));+ };++ return (+ <>+ <button onClick={selectItems}>Select items</button>+ <button onClick={resetSelection}>Reset selection</button>+ <button onClick={() => filterSelectedTables([SECOND_TABLE_ID])}>+ Filter tables+ </button>+ <output data-testid="selected-tables">+ {Array.from(selectedTables).join(",")}+ </output>+ <output data-testid="selected-schemas">+ {Array.from(selectedSchemas).join(",")}+ </output>+ <output data-testid="selected-databases">+ {Array.from(selectedDatabases).join(",")}+ </output>+ <output data-testid="has-selected-items">+ {String(hasSelectedItems)}+ </output>+ <output data-testid="selected-items-count">{selectedItemsCount}</output>+ <output data-testid="has-only-one-table">+ {String(hasOnlyOneTableSelected)}+ </output>+ <output data-testid="has-more-than-one-table">+ {String(hasSelectedMoreThanOneTable)}+ </output>+ </>+ );+}++function setup() {+ render(+ <SelectionProvider>+ <SelectionHarness />+ </SelectionProvider>,+ );+}++describe("SelectionContext", () => {+ it("resets table, schema, and database selection", async () => {+ setup();++ await userEvent.click(screen.getByRole("button", { name: "Select items" }));+ expect(screen.getByTestId("selected-tables")).toHaveTextContent("10,20");+ expect(screen.getByTestId("selected-schemas")).toHaveTextContent(SCHEMA_ID);+ expect(screen.getByTestId("selected-databases")).toHaveTextContent("30");+ expect(screen.getByTestId("has-selected-items")).toHaveTextContent("true");+ expect(screen.getByTestId("selected-items-count")).toHaveTextContent("4");+ expect(screen.getByTestId("has-only-one-table")).toHaveTextContent("false");+ expect(screen.getByTestId("has-more-than-one-table")).toHaveTextContent(+ "true",+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Reset selection" }),+ );++ expect(screen.getByTestId("selected-tables")).toBeEmptyDOMElement();+ expect(screen.getByTestId("selected-schemas")).toBeEmptyDOMElement();+ expect(screen.getByTestId("selected-databases")).toBeEmptyDOMElement();+ expect(screen.getByTestId("has-selected-items")).toHaveTextContent("false");+ expect(screen.getByTestId("selected-items-count")).toHaveTextContent("0");+ expect(screen.getByTestId("has-only-one-table")).toHaveTextContent("false");+ expect(screen.getByTestId("has-more-than-one-table")).toHaveTextContent(+ "false",+ );+ });++ it("filters selected tables without changing schema or database selection", async () => {+ setup();++ await userEvent.click(screen.getByRole("button", { name: "Select items" }));+ await userEvent.click(+ screen.getByRole("button", { name: "Filter tables" }),+ );++ expect(screen.getByTestId("selected-tables")).toHaveTextContent("20");+ expect(screen.getByTestId("selected-tables")).not.toHaveTextContent("10");+ expect(screen.getByTestId("selected-schemas")).toHaveTextContent(SCHEMA_ID);+ expect(screen.getByTestId("selected-databases")).toHaveTextContent("30");+ });+});diff --git a/frontend/test/__support__/server-mocks/table.ts b/frontend/test/__support__/server-mocks/table.tsindex 147fdf8fa50..e24b8195240 100644--- a/frontend/test/__support__/server-mocks/table.ts+++ b/frontend/test/__support__/server-mocks/table.ts@@ -4,6 +4,10 @@ import type { ForeignKey, Table, TableId } from "metabase-types/api";import { setupFieldEndpoints } from "./field";+function escapeRegExp(value: string) {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}+export function setupTableEndpoints(table: Table,foreignKeys: ForeignKey[] = [],@@ -62,17 +66,15 @@ export function setupTableSearchEndpoint(tables: Table[]) {name,response: (call) => {const url = new URL(call.url);- const term = url.searchParams.get("term");-- // Convert wildcard pattern to regex (support * as wildcard)- const searchPattern = term?.toLowerCase().replace(/\*/g, ".*"); // Convert \* back to .* for wildcard matching-- const regex = new RegExp(searchPattern ?? "");+ const term = url.searchParams.get("term") ?? "";+ const searchPattern = term.split("*").map(escapeRegExp).join(".*");+ const namePattern = new RegExp(`^${searchPattern}`, "i");+ const displayNamePattern = new RegExp(`(?:^| )${searchPattern}`, "i");return tables.filter((table) =>- regex.test(table.name.toLowerCase()) ||- regex.test(table.display_name?.toLowerCase() ?? ""),+ namePattern.test(table.name) ||+ displayNamePattern.test(table.display_name ?? ""),);},});