Skip to content

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

e2e2unit: Joins (#85687)

Nemanja Glumacd34ef2f9069e
diff --git a/e2e/support/helpers/e2e-notebook-helpers.ts b/e2e/support/helpers/e2e-notebook-helpers.ts
index 0b8f5687156..792fdb26f42 100644
--- a/e2e/support/helpers/e2e-notebook-helpers.ts
+++ b/e2e/support/helpers/e2e-notebook-helpers.ts
@@ -1,9 +1,7 @@
import type { CyHttpMessages } from "cypress/types/net-stubbing";
import {
- entityPickerModal,
miniPicker,
- miniPickerBrowseAll,
popover,
} from "e2e/support/helpers/e2e-ui-elements-helpers";
import type { NotebookStepType } from "metabase/querying/notebook/types";
@@ -187,40 +185,6 @@ export function joinTable(
}
}
-/**
- * Open a saved question and join it with another saved question.
- *
- * Depends on a `startNewQuestion()` helper to work properly!
- *
- * @todo Either decouple this dependency or use `startNewQuestion()` directly here.
- *
- * @example
- * startNewQuestion();
- * selectSavedQuestionsToJoin("Q1", "Q2");
- */
-export function selectSavedQuestionsToJoin(
- firstQuestionName: string,
- secondQuestionName: string,
-) {
- cy.intercept("GET", "/api/table/*/query_metadata").as("joinedTableMetadata");
- miniPickerBrowseAll().click();
- entityPickerModal().within(() => {
- cy.findByText("Our analytics").click();
- cy.findByText(firstQuestionName).click();
- });
-
- cy.wait("@joinedTableMetadata");
-
- // join to question b
- cy.icon("join_left_outer").click();
-
- miniPickerBrowseAll().click();
- entityPickerModal().within(() => {
- cy.findByText("Our analytics").click();
- cy.findByText(secondQuestionName).click();
- });
-}
-
export function selectFilterOperator(operatorName: string) {
cy.findByLabelText("Filter operator").click();
cy.findByRole("menu").findByText(operatorName).click();
diff --git a/e2e/test/scenarios/joins/joins-custom-expressions.cy.spec.ts b/e2e/test/scenarios/joins/joins-custom-expressions.cy.spec.ts
deleted file mode 100644
index cdbb2a64cf0..00000000000
--- a/e2e/test/scenarios/joins/joins-custom-expressions.cy.spec.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { ORDERS_MODEL_ID } from "e2e/support/cypress_sample_instance_data";
-
-const { H } = cy;
-
-describe("scenarios > joins > custom expressions", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("should support expressions in join conditions referencing model columns", () => {
- H.visitModel(ORDERS_MODEL_ID);
- H.openNotebook();
-
- H.join();
- H.miniPicker().within(() => {
- cy.findByText("Our analytics").click();
- cy.findByText("Orders Model").click();
- });
- H.popover().within(() => {
- cy.findByText("Custom Expression").click();
- H.enterCustomColumnDetails({ formula: "[ID] + [User ID]" });
- cy.button("Done").click();
- });
- H.popover().within(() => {
- cy.findByText("Custom Expression").click();
- H.enterCustomColumnDetails({ formula: "[ID] + [Product ID]" });
- cy.button("Done").click();
- });
-
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("ID").click();
- cy.findByPlaceholderText("Enter an ID").type("1");
- cy.button("Add filter").click();
- });
-
- H.visualize();
- H.assertQueryBuilderRowCount(9);
- });
-
- it("should allow to update a join with a join condition with custom expressions", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.join();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Reviews").click();
- });
- H.popover().within(() => {
- cy.findByText("Custom Expression").click();
- H.enterCustomColumnDetails({ formula: "1" });
- cy.button("Done").click();
- });
- H.popover().within(() => {
- cy.findByText("Custom Expression").click();
- H.enterCustomColumnDetails({ formula: "1" });
- cy.button("Done").click();
- });
-
- H.getNotebookStep("join").findByLabelText("Change operator").click();
- H.popover().findByText("=").click();
- H.getNotebookStep("join").findByLabelText("Change join type").click();
- H.popover().findByText("Inner join").click();
- H.getNotebookStep("join")
- .findByLabelText("Left column")
- .findByText("1")
- .click();
- H.enterCustomColumnDetails({ formula: "[ID] + 1" });
- H.popover().button("Update").click();
- H.getNotebookStep("join")
- .findByLabelText("Right column")
- .findByText("1")
- .click();
- H.enterCustomColumnDetails({ formula: "[Reviews → ID] + 1" });
- H.popover().button("Update").click();
-
- H.visualize();
- H.assertTableRowsCount(1112);
- });
-});
diff --git a/e2e/test/scenarios/joins/joins-reproductions.cy.spec.js b/e2e/test/scenarios/joins/joins-reproductions.cy.spec.js
deleted file mode 100644
index 706d00e80f2..00000000000
--- a/e2e/test/scenarios/joins/joins-reproductions.cy.spec.js
+++ /dev/null
@@ -1,962 +0,0 @@
-const { H } = cy;
-import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-
-const {
- ORDERS,
- ORDERS_ID,
- PRODUCTS,
- PRODUCTS_ID,
- PEOPLE,
- PEOPLE_ID,
- REVIEWS,
- REVIEWS_ID,
-} = SAMPLE_DATABASE;
-describe("issue 14793", () => {
- const XRAY_DATASETS = 11; // enough to load most questions
-
- const QUESTION_DETAILS = {
- dataset_query: {
- type: "query",
- query: {
- "source-table": REVIEWS_ID,
- joins: [
- {
- fields: "all",
- "source-table": PRODUCTS_ID,
- condition: [
- "=",
- ["field", REVIEWS.PRODUCT_ID, null],
- ["field", PRODUCTS.ID, { "join-alias": "Products" }],
- ],
- alias: "Products",
- },
- ],
- aggregation: [
- ["sum", ["field", PRODUCTS.PRICE, { "join-alias": "Products" }]],
- ],
- breakout: [["field", REVIEWS.CREATED_AT, { "temporal-unit": "year" }]],
- },
- database: SAMPLE_DB_ID,
- },
- display: "line",
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- cy.intercept("GET", "/api/automagic-dashboards/adhoc/**").as("xray");
- cy.intercept("POST", "/api/dataset").as("postDataset");
- });
-
- it("x-rays should work on explicit joins when metric is for the joined table (metabase#14793)", () => {
- H.visitQuestionAdhoc(QUESTION_DETAILS);
-
- H.cartesianChartCircle().eq(2).click({ force: true });
-
- H.popover().findByText("Automatic insights…").click();
- H.popover().findByText("X-ray").click();
-
- cy.wait("@xray").then((xhr) => {
- for (let i = 0; i < XRAY_DATASETS; ++i) {
- cy.wait("@postDataset");
- }
- expect(xhr.response.statusCode).not.to.eq(500);
- expect(xhr.response.body.cause).not.to.exist;
- });
-
- H.dashboardGrid()
- .findByText("How this metric is distributed across different numbers")
- .should("exist");
-
- cy.findByTestId("automatic-dashboard-header")
- .findByText(/^A closer look at/)
- .should("be.visible");
-
- H.getDashboardCards().should("have.length", 35);
- });
-});
-
-describe("issue 15342", { tags: "@external" }, () => {
- const MYSQL_DB_NAME = "QA MySQL8";
-
- beforeEach(() => {
- H.restore("mysql-8");
- cy.signInAsAdmin();
-
- cy.viewport(4000, 1200); // huge width required so three joined tables can fit
- });
-
- it("should correctly order joins for MySQL queries (metabase#15342)", () => {
- H.startNewQuestion();
- H.miniPicker().within(() => {
- cy.findByText(MYSQL_DB_NAME).click();
- cy.findByText("People").click();
- });
-
- cy.icon("join_left_outer").click();
- H.miniPicker().within(() => {
- cy.findByText(MYSQL_DB_NAME).click();
- cy.findByText("Orders").click();
- });
- H.getNotebookStep("join").findByLabelText("Right column").click();
- H.popover().findByText("Product ID").click();
-
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.icon("join_left_outer").last().click();
- H.miniPicker().within(() => {
- cy.findByText(MYSQL_DB_NAME).click();
- cy.findByText("Products").click();
- });
- H.getNotebookStep("join").icon("join_left_outer").click();
- H.popover().findByText("Inner join").click();
-
- H.visualize();
-
- cy.findByTestId("query-visualization-root").within(() => {
- cy.findByText("Email"); // from People table
- cy.findByText("Orders → ID"); // joined Orders table columns
- cy.findByText("Products → ID"); // joined Products table columns
- });
- });
-});
-
-describe("issue 15578", () => {
- const JOINED_QUESTION_NAME = "15578";
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- // Remap display value
- cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
- name: "Product ID",
- type: "external",
- human_readable_field_id: PRODUCTS.TITLE,
- });
-
- H.createQuestion({
- name: JOINED_QUESTION_NAME,
- query: { "source-table": ORDERS_ID },
- });
- });
-
- it("joining on a question with remapped values should work (metabase#15578)", () => {
- H.openProductsTable({ mode: "notebook" });
-
- cy.button("Join data").click();
- H.miniPicker().within(() => {
- cy.findByText("Our analytics").click();
- cy.findByText(JOINED_QUESTION_NAME).click();
- });
-
- H.visualize();
-
- H.queryBuilderHeader()
- .findByTestId("question-table-badges")
- .within(() => {
- cy.findByText("Products").should("be.visible");
- cy.findByText(JOINED_QUESTION_NAME).should("be.visible");
- });
-
- H.queryBuilderMain().within(() => {
- cy.findByText("Category").should("be.visible");
- cy.findByText(`${JOINED_QUESTION_NAME} → ID`).should("be.visible");
- });
- });
-});
-
-describe("issue 17710, 39448", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("should suggest join conditions and remove only invalid join clauses (metabase#17710, metabase#39448)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- cy.button("Join data").click();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Products").click();
- });
-
- cy.log(
- "should load joined table metadata for suggested join conditions (metabase#39448)",
- );
- H.getNotebookStep("join").within(() => {
- cy.findByLabelText("Right table").should("have.text", "Products");
- cy.findByLabelText("Left column")
- .findByText("Product ID")
- .should("be.visible");
- cy.findByLabelText("Right column").findByText("ID").should("be.visible");
- cy.findByLabelText("Change operator").should("have.text", "=");
- });
-
- cy.log("should remove only invalid join clauses (metabase#17710)");
- H.getNotebookStep("join").icon("add").click();
-
- // Close the LHS column popover that opens automatically
- H.getNotebookStep("join").parent().click();
-
- H.visualize();
-
- H.openNotebook();
-
- cy.findByTestId("step-join-0-0").within(() => {
- cy.findByLabelText("Left column").findByText("Product ID");
- cy.findByLabelText("Right column").findByText("ID");
- cy.findAllByLabelText("Left column").should("have.length", 1);
- cy.findAllByLabelText("Right column").should("have.length", 1);
- });
- });
-});
-describe("issue 17968", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should show 'Previous results' instead of a table name for non-field dimensions (metabase#17968)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.summarize({ mode: "notebook" });
- H.popover().findByText("Count of rows").click();
-
- H.getNotebookStep("summarize")
- .findByText("Pick a column to group by")
- .click();
- H.popover().findByText("Created At").click();
-
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.findAllByTestId("action-buttons").last().button("Join data").click();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Products").click();
- });
- H.popover().findByText("Count").click();
-
- H.getNotebookStep("join", { stage: 1 })
- .findByLabelText("Left column")
- .findByText("Previous results");
- });
-});
-
-describe("issue 18502", () => {
- const { PEOPLE, PEOPLE_ID } = SAMPLE_DATABASE;
-
- const question1 = getQuestionDetails("18502#1", PEOPLE.CREATED_AT);
- const question2 = getQuestionDetails("18502#2", PEOPLE.BIRTH_DATE);
-
- function getQuestionDetails(name, breakoutColumn) {
- return {
- name,
- query: {
- "source-table": PEOPLE_ID,
- aggregation: [["count"]],
- breakout: [["field", breakoutColumn, { "temporal-unit": "month" }]],
- },
- };
- }
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should be able to join two saved questions based on the same table (metabase#18502)", () => {
- H.createQuestion(question1);
- H.createQuestion(question2);
-
- H.startNewQuestion();
- H.selectSavedQuestionsToJoin("18502#1", "18502#2");
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Created At: Month").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Birth Date: Month").click();
-
- H.visualize((response) => {
- expect(response.body.error).to.not.exist;
- });
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("April 2025");
- });
-});
-describe("issue 18818", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should normally open notebook editor for queries joining on custom columns (metabase#18818)", () => {
- H.createQuestion(
- {
- query: {
- "source-table": REVIEWS_ID,
- expressions: {
- "CC Rating": ["field", REVIEWS.RATING],
- },
- joins: [
- {
- fields: "all",
- "source-table": ORDERS_ID,
- condition: [
- "=",
- ["expression", "CC Rating"],
- ["field", ORDERS.QUANTITY, { "join-alias": "Orders" }],
- ],
- },
- ],
- },
- },
- { visitQuestion: true },
- );
-
- H.openNotebook();
- H.getNotebookStep("join").within(() => {
- cy.findByLabelText("Left column").findByText("CC Rating");
- cy.findByLabelText("Right column").findByText("Quantity");
- });
- });
-});
-
-describe("issue 20519", () => {
- const questionDetails = {
- name: "20519",
- query: {
- "source-query": {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- breakout: [
- ["field", PRODUCTS.CATEGORY, { "source-field": ORDERS.PRODUCT_ID }],
- ],
- },
- joins: [
- {
- fields: "all",
- "source-table": PRODUCTS_ID,
- condition: [
- "=",
- ["field", "CATEGORY", { "base-type": "type/Text" }],
- ["field", PRODUCTS.CATEGORY, { "join-alias": "Products" }],
- ],
- alias: "Products",
- },
- ],
- limit: 2,
- },
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- H.createQuestion(questionDetails, { visitQuestion: true });
- H.openNotebook();
- });
-
- // Tightly related issue: metabase#17767
- it("should allow subsequent joins and nested query after summarizing on the implicit joins (metabase#20519)", () => {
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.findAllByLabelText("Custom column").last().click();
-
- H.enterCustomColumnDetails({
- formula: "1 + 1",
- name: "Two",
- });
-
- cy.button("Done").click();
-
- H.getNotebookStep("expression", { stage: 1 })
- .contains("Two")
- .should("exist");
-
- H.visualize((response) => {
- expect(response.body.error).not.to.exist;
- });
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Doohickey");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Two");
- });
-});
-
-describe("issue 22859 - multiple levels of nesting", () => {
- const questionDetails = {
- name: "22859-Q1",
- query: {
- "source-table": REVIEWS_ID,
- joins: [
- {
- fields: "all",
- "source-table": PRODUCTS_ID,
- condition: [
- "=",
- ["field", REVIEWS.PRODUCT_ID, null],
- ["field", PRODUCTS.ID, { "join-alias": "Products" }],
- ],
- alias: "Products",
- },
- ],
- },
- };
-
- function getJoinedTableColumnHeader() {
- cy.get("@q1Id").then((id) => {
- cy.findByText(`Question ${id} → ID`);
- });
- }
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- H.createQuestion(questionDetails, { wrapId: true, idAlias: "q1Id" });
-
- // Join Orders table with the previously saved question and save it again
- cy.get("@q1Id").then((id) => {
- const nestedQuestionDetails = {
- name: "22859-Q2",
- query: {
- "source-table": ORDERS_ID,
- joins: [
- {
- fields: "all",
- alias: `Question ${id}`,
- condition: [
- "=",
- ["field", ORDERS.PRODUCT_ID, { "base-type": "type/Integer" }],
- [
- "field",
- REVIEWS.PRODUCT_ID,
- {
- "base-type": "type/Integer",
- "join-alias": `Question ${id}`,
- },
- ],
- ],
- "source-table": `card__${id}`,
- },
- ],
- limit: 5,
- },
- };
-
- H.createQuestion(nestedQuestionDetails, {
- wrapId: true,
- idAlias: "q2Id",
- });
- });
- });
-
- it("model based on multi-level nested saved question should work (metabase#22859-1)", () => {
- cy.get("@q2Id").then((id) => {
- // Convert the second question to a model
- cy.request("PUT", `/api/card/${id}`, { type: "model" });
-
- cy.intercept("POST", "/api/dataset").as("dataset");
- cy.visit(`/model/${id}`);
- cy.wait("@dataset");
- });
-
- getJoinedTableColumnHeader();
- });
-});
-
-describe("issue 23293", () => {
- /**
- * @param {string} columnName
- * @param {("add"|"remove")} action
- */
- function modifyColumn(columnName, action) {
- cy.findByTestId("sidebar-left").within(() => {
- cy.findByRole("button", { name: "Add or remove columns" }).click();
- if (action === "add") {
- cy.findByLabelText(columnName).should("not.be.checked").click();
- } else {
- cy.findByLabelText(columnName).should("be.checked").click();
- }
-
- cy.findByRole("button", { name: "Done picking columns" }).click();
- });
- }
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- cy.intercept("POST", "/api/card").as("saveQuestion");
- });
-
- it("should retain the filter when drilling through the dashboard card with implicitly added column (metabase#23293)", () => {
- H.openOrdersTable();
-
- H.openVizSettingsSidebar();
- modifyColumn("Product ID", "remove");
- modifyColumn("Category", "add");
- cy.wait("@dataset");
-
- H.queryBuilderHeader().button("Save").click();
- cy.findByTestId("save-question-modal")
- .findByLabelText(/Where do you want to save this/)
- .click();
- H.pickEntity({
- path: ["Our analytics"],
- });
- H.entityPickerModal().findByText("Select this collection").click();
- cy.findByTestId("save-question-modal").button("Save").click();
-
- cy.wait("@saveQuestion").then(({ response }) => {
- const id = response.body.id;
- const questionDetails = {
- query: {
- "source-table": `card__${id}`,
- aggregation: [["count"]],
- breakout: [
- [
- "field",
- PRODUCTS.CATEGORY,
- {
- "source-field": ORDERS.PRODUCT_ID,
- },
- ],
- ],
- },
- display: "bar",
- };
-
- H.createQuestionAndDashboard({ questionDetails }).then(
- ({ body: { dashboard_id } }) => {
- H.visitDashboard(dashboard_id);
- },
- );
-
- // Click on the first bar
- H.chartPathWithFillColor("#509EE3").first().realClick();
- H.popover()
- .findByText(/^See these/)
- .click();
-
- cy.findByTestId("qb-filters-panel").should(
- "contain",
- "Orders → Category is Doohickey",
- );
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.findAllByTestId("header-cell")
- .last()
- .should("have.text", "Product → Category");
-
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.findAllByRole("grid")
- .last()
- .should("contain", "Doohickey")
- .and("not.contain", "Gizmo");
- });
- });
-});
-
-describe("issue 27380", () => {
- beforeEach(() => {
- cy.intercept("POST", "/api/dataset").as("dataset");
-
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should not drop fields from joined table on dashboard 'zoom-in' (metabase#27380)", () => {
- const questionDetails = {
- query: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- breakout: [
- [
- "field",
- PRODUCTS.CREATED_AT,
- { "source-field": ORDERS.PRODUCT_ID, "temporal-unit": "month" },
- ],
- ],
- },
- display: "line",
- };
- H.createQuestionAndDashboard({ questionDetails }).then(
- ({ body: { dashboard_id } }) => {
- H.visitDashboard(dashboard_id);
- },
- );
-
- // Doesn't really matter which 'circle" we click on the graph
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- H.cartesianChartCircle().last().click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("See this month by week").click();
- cy.wait("@dataset");
-
- // Graph should still exist
- // Checks the y-axis label
- H.echartsContainer().findByText("Count");
-
- H.openNotebook();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Pick a column to group by").should("not.exist");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Product → Created At: Week");
- });
-});
-describe("issue 31769", () => {
- const Q1 = {
- "source-table": ORDERS_ID,
- joins: [
- {
- fields: "all",
- alias: "Products",
- "source-table": PRODUCTS_ID,
- condition: [
- "=",
- ["field", ORDERS.PRODUCT_ID, null],
- ["field", PRODUCTS.ID, { "join-alias": "Products" }],
- ],
- },
- {
- fields: "all",
- alias: "People — User",
- "source-table": PEOPLE_ID,
- condition: [
- "=",
- ["field", ORDERS.USER_ID, null],
- ["field", PEOPLE.ID, { "join-alias": "People — User" }],
- ],
- },
- ],
- aggregation: [["count"]],
- breakout: [
- [
- "field",
- PRODUCTS.CATEGORY,
- { "base-type": "type/Text", "join-alias": "Products" },
- ],
- ],
- };
-
- const Q2 = {
- "source-table": PRODUCTS_ID,
- aggregation: [["count"]],
- breakout: [["field", PRODUCTS.CATEGORY, { "base-type": "type/Text" }]],
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
-
- H.createQuestion({ name: "Q1", query: Q1 }).then(() => {
- H.createQuestion({ name: "Q2", query: Q2 }).then(() => {
- H.startNewQuestion();
- });
- });
- });
-
- it("shouldn't drop joins using Lib/MBQL 5 (metabase#31769)", () => {
- H.selectSavedQuestionsToJoin("Q1", "Q2");
-
- H.popover().findByText("Products → Category").click();
- H.popover().findByText("Category").click();
-
- H.visualize();
-
- // Asserting there're two columns from Q1 and two columns from Q2
- cy.findAllByTestId("header-cell").should("have.length", 4);
-
- H.tableInteractive()
- .findByText("Q2 - Products → Category → Category")
- .should("exist");
-
- H.tableInteractive().findByText("Products → Category").should("exist");
- });
-});
-
-// See TODO inside this test when unskipping
-describe("issue 27521", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("correctly displays joined question's column names (metabase#27521)", () => {
- cy.visit("/");
-
- cy.log("Create Q1");
- H.openOrdersTable({ mode: "notebook" });
-
- H.getNotebookStep("data").button("Pick columns").click();
- H.popover().findByText("Select all").click();
-
- cy.log("close popover");
- H.getNotebookStep("data").click();
-
- H.join();
-
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Orders").click();
- });
-
- H.popover().findByText("ID").click();
- H.popover().findByText("ID").click();
-
- H.getNotebookStep("join", { stage: 0, index: 0 })
- .button("Pick columns")
- .click();
- H.popover().within(() => {
- cy.findByText("Select all").click();
- cy.findByText("ID").click();
- });
-
- H.visualize();
- assertTableHeader(0, "ID");
- assertTableHeader(1, "Orders_2 → ID");
-
- H.saveQuestion("Q1");
-
- assertTableHeader(0, "ID");
- assertTableHeader(1, "Orders_2 → ID");
-
- cy.log("Create second question (Products + Q1)");
- H.newButton("Question").click();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("People").click();
- });
-
- H.getNotebookStep("data").button("Pick columns").click();
- H.popover().findByText("Select all").click();
-
- H.join();
-
- H.miniPicker().within(() => {
- cy.findByText("Our analytics").click();
- cy.findByText("Q1").click();
- });
-
- H.popover().findByText("ID").click();
- H.popover().findByText("Orders_2 → ID").should("be.visible").click();
- H.getNotebookStep("join")
- .findByLabelText("Right column")
- .findByText("Q1 → ID")
- .should("be.visible")
- .click();
- H.popover()
- .findAllByText("Q1 → ID")
- .should("have.length", 2)
- .first()
- .click();
-
- H.visualize();
-
- assertTableHeader(0, "ID");
- assertTableHeader(1, "Q1 → ID");
- assertTableHeader(2, "Q1 → ID");
-
- H.openVizSettingsSidebar();
- cy.findByTestId("chartsettings-sidebar").within(() => {
- cy.findAllByText("ID").should("have.length", 1);
- cy.findAllByText("Q1 → ID").should("have.length", 2);
-
- cy.findByRole("button", { name: "Add or remove columns" }).click();
- cy.findAllByText("ID").should("have.length", 1);
- cy.findAllByText("Q1 → ID").should("have.length", 2);
-
- // TODO: add assertions for what happens when toggling all the columns here
- // See https://github.com/metabase/metabase/issues/27521#issuecomment-1948658757
- });
- });
-
- function assertTableHeader(index, name) {
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.findAllByTestId("header-cell").eq(index).should("have.text", name);
- }
-});
-
-describe("issue 42385", { tags: "@external" }, () => {
- beforeEach(() => {
- H.restore("postgres-12");
- cy.signInAsAdmin();
- });
-
- it("should remove invalid draft join clause when query database changes (metabase#42385)", () => {
- H.openOrdersTable({ mode: "notebook" });
- H.join();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Reviews").click();
- });
-
- H.getNotebookStep("data").findByTestId("data-step-cell").click();
- H.miniPickerHeader().click();
- H.miniPicker().within(() => {
- cy.findByText("QA Postgres12").click();
- cy.findByText("Reviews").click();
- });
-
- H.getNotebookStep("join").within(() => {
- cy.findByPlaceholderText("Search for tables and more...").should(
- "be.visible",
- );
- cy.findByLabelText("Left column").should("not.exist");
- cy.findByLabelText("Right column").should("not.exist");
- });
- });
-
- it("should remove invalid join clause in incomplete draft state when query database changes (metabase#42385)", () => {
- H.openOrdersTable({ mode: "notebook" });
- H.join();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Products").click();
- });
-
- H.getNotebookStep("join")
- .findByLabelText("Right table")
- .findByText("Products")
- .click();
-
- H.miniPicker().findByText("Reviews").click();
-
- H.getNotebookStep("data").findByTestId("data-step-cell").click();
- H.miniPickerHeader().click();
- H.miniPicker().within(() => {
- cy.findByText("QA Postgres12").click();
- cy.findByText("Reviews").click();
- });
-
- H.getNotebookStep("join").should("not.exist");
- });
-});
-
-describe("issue 45300", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("joins using the foreign key only should not break the filter picker (metabase#45300)", () => {
- H.visitQuestionAdhoc({
- dataset_query: {
- database: SAMPLE_DB_ID,
- type: "query",
- query: {
- "source-table": REVIEWS_ID,
- joins: [
- {
- fields: "all",
- strategy: "left-join",
- alias: "Orders - Product",
- condition: [
- "=",
- ["field", REVIEWS.PRODUCT_ID, { "base-type": "type/Integer" }],
- [
- "field",
- ORDERS.PRODUCT_ID,
- {
- "base-type": "type/Integer",
- "join-alias": "Orders - Product",
- },
- ],
- ],
- "source-table": ORDERS_ID,
- },
- ],
- },
- parameters: [],
- },
- });
-
- H.filter();
- H.popover().within(() => {
- cy.findAllByText("Product").should("have.length", 2).first().click();
- cy.findByText("Category").click();
- cy.findByText("Doohickey").click();
- cy.button("Apply filter").click();
- });
- cy.wait("@dataset");
-
- cy.findByTestId("filter-pill").should(
- "have.text",
- "Product → Category is Doohickey",
- );
- });
-});
-
-describe("issue 46675", () => {
- const questionDetails = {
- query: {
- "source-table": ORDERS_ID,
- },
- };
-
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
-
- cy.log("create draft state with a rhs table and a lhs column");
- H.createQuestion(questionDetails, { visitQuestion: true });
- H.openNotebook();
- H.getNotebookStep("data").findByLabelText("Join data").click();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Reviews").click();
- });
- H.popover().findByText("ID").click();
- });
-
- it("should reset the draft join state when the source table changes (metabase#46675)", () => {
- cy.log("change the source table and verify that the state was reset");
- H.getNotebookStep("data").findByText("Orders").click();
- H.miniPicker().within(() => {
- cy.findByText("Products").click();
- });
- H.getNotebookStep("join").within(() => {
- cy.findByLabelText("Left table").should("have.text", "Products");
- cy.findByPlaceholderText("Search for tables and more...").should(
- "be.visible",
- );
- });
-
- cy.log("complete the join and make sure the query can be executed");
- H.getNotebookStep("join")
- .findByPlaceholderText("Search for tables and more...")
- .click();
- H.miniPicker().within(() => {
- cy.findByText("Sample Database").click();
- cy.findByText("Orders").click();
- });
- H.visualize();
- H.tableInteractive().should("be.visible");
- });
-
- it("should reset the draft join state when the rhs table changes (metabase#46675)", () => {
- cy.log("change the rhs table and verify that the state was reset");
- H.getNotebookStep("join")
- .findByLabelText("Right table")
- .findByText("Reviews")
- .click();
- H.miniPicker().within(() => {
- cy.findByText("Orders").click();
- });
- H.getNotebookStep("join").within(() => {
- cy.findByLabelText("Left table").should("have.text", "Orders");
- cy.findByLabelText("Right table").should("have.text", "Orders");
- cy.findByLabelText("Left column").should(
- "contain.text",
- "Pick a column…",
- );
- });
-
- cy.log("complete the join and make sure the query can be executed");
- H.popover().findByText("ID").click();
- H.popover().findByText("ID").click();
- H.visualize();
- H.tableInteractive().should("be.visible");
- });
-});
diff --git a/e2e/test/scenarios/joins/joins.cy.spec.js b/e2e/test/scenarios/joins/joins.cy.spec.js
deleted file mode 100644
index 275686f2a01..00000000000
--- a/e2e/test/scenarios/joins/joins.cy.spec.js
+++ /dev/null
@@ -1,361 +0,0 @@
-const { H } = cy;
-import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-
-const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID } = SAMPLE_DATABASE;
-
-describe("scenarios > question > joined questions", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should join raw tables (metabase#11452, metabase#12221, metabase#13468, metabase#15570)", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.join();
- H.joinTable("Reviews", "Product ID", "Product ID");
-
- H.visualize();
- H.assertJoinValid({
- lhsTable: "Orders",
- rhsTable: "Reviews",
- lhsSampleColumn: "Product ID",
- rhsSampleColumn: "Reviews - Product → ID",
- });
-
- H.openNotebook();
- H.getNotebookStep("join").icon("chevrondown").click();
- H.popover().within(() => {
- cy.findByText("Product ID").click();
- cy.findByText("Body").click();
- cy.findByText("Created At").click();
- });
- H.visualize();
-
- H.assertJoinValid({
- lhsTable: "Orders",
- rhsTable: "Reviews",
- lhsSampleColumn: "Product ID",
- rhsSampleColumn: "Reviews - Product → Reviewer",
- });
- H.queryBuilderMain()
- .findByText("Reviews - Product → Body")
- .should("not.exist");
-
- // Post-join filters on the joined table (metabase#12221, metabase#15570)
- H.openNotebook();
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Reviews").click();
- cy.findByText("Rating").click();
- });
- H.selectFilterOperator("Equal to");
- H.popover().within(() => {
- cy.findByLabelText("2").click();
- cy.button("Add filter").click();
- });
-
- // Post-join aggregation (metabase#11452):
- H.summarize({ mode: "notebook" });
- H.addSummaryField({
- metric: "Average of ...",
- table: "Reviews",
- field: "Rating",
- });
- H.addSummaryGroupingField({ table: "Reviews", field: "Reviewer" });
-
- H.visualize();
-
- cy.findByTestId("qb-filters-panel").findByText(
- "Reviews - Product → Rating is equal to 2",
- );
- H.assertQueryBuilderRowCount(89);
-
- // Make sure UI overlay doesn't obstruct viewing results after we save this question (metabase#13468)
- cy.findByTestId("qb-header").button("Save").click();
- cy.findByTestId("save-question-modal")
- .findByLabelText(/Where do you want to save this/)
- .click();
- H.pickEntity({
- path: ["Our analytics"],
- });
- H.entityPickerModal().button("Select this collection").click();
- cy.findByTestId("save-question-modal").button("Save").click();
-
- cy.findByTestId("qb-filters-panel").findByText(
- "Reviews - Product → Rating is equal to 2",
- );
- H.assertQueryBuilderRowCount(89);
- });
-
- it("should join a native question (metabase#37100)", () => {
- H.createNativeQuestion({
- name: "question a",
- native: { query: "select ID, PRODUCT_ID, TOTAL from orders" },
- });
-
- H.createNativeQuestion({
- name: "question b",
- native: { query: "select * from products" },
- });
-
- H.startNewQuestion();
- H.selectSavedQuestionsToJoin("question a", "question b");
- H.popover().findByText("PRODUCT_ID").click();
- H.popover().findByText("ID").click();
- cy.realPress("Escape");
- H.visualize();
- H.assertJoinValid({
- lhsTable: "question a",
- rhsTable: "question b",
- lhsSampleColumn: "TOTAL",
- rhsSampleColumn: "question b - PRODUCT_ID → ID",
- });
-
- H.openNotebook();
- H.getNotebookStep("join").icon("chevrondown").click();
- H.popover().within(() => {
- cy.findByText("question b - PRODUCT_ID → EAN").click();
- cy.findByText("question b - PRODUCT_ID → VENDOR").click();
- cy.findByText("question b - PRODUCT_ID → PRICE").click();
- cy.findByText("question b - PRODUCT_ID → CATEGORY").click();
- cy.findByText("question b - PRODUCT_ID → CREATED_AT").click();
- });
- cy.realPress("Escape");
- H.visualize();
- H.assertJoinValid({
- lhsTable: "question a",
- rhsTable: "question b",
- lhsSampleColumn: "TOTAL",
- rhsSampleColumn: "question b - PRODUCT_ID → RATING",
- });
- H.queryBuilderMain()
- .findByText("question b - PRODUCT_ID → EAN")
- .should("not.exist");
-
- H.openNotebook();
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("question b").click();
- cy.findByText("question b - PRODUCT_ID → CATEGORY").click();
- });
- H.selectFilterOperator("Is");
- H.popover().within(() => {
- cy.findByPlaceholderText("Enter some text").type("Gadget");
- cy.button("Add filter").click();
- });
-
- H.summarize({ mode: "notebook" });
- H.addSummaryGroupingField({
- table: "question b",
- field: "question b - PRODUCT_ID → CATEGORY",
- });
- H.visualize();
-
- cy.findByTestId("qb-filters-panel")
- .findByText("question b - PRODUCT_ID → CATEGORY is Gadget")
- .should("be.visible");
- cy.findByTestId("scalar-value").contains("Gadget").should("be.visible");
- });
-
- it("should join structured questions (metabase#13000, metabase#13649, metabase#13744)", () => {
- H.createQuestion({
- name: "Q1",
- query: {
- aggregation: ["sum", ["field", ORDERS.TOTAL, null]],
- breakout: [["field", ORDERS.PRODUCT_ID, null]],
- // Make sure it works if a question has sorted metric (metabase#13744)
- "order-by": [["asc", ["aggregation", 0]]],
- "source-table": ORDERS_ID,
- },
- });
-
- H.createQuestion({
- name: "Q2",
- query: {
- aggregation: ["sum", ["field", PRODUCTS.RATING, null]],
- breakout: [["field", PRODUCTS.ID, null]],
- "source-table": PRODUCTS_ID,
- },
- });
-
- H.startNewQuestion();
- H.selectSavedQuestionsToJoin("Q1", "Q2");
- H.visualize();
-
- H.assertJoinValid({
- lhsTable: "Q1",
- rhsTable: "Q2",
- lhsSampleColumn: "Product ID",
- rhsSampleColumn: "Q2 - Product → ID",
- });
-
- H.openNotebook();
- H.getNotebookStep("join").icon("chevrondown").click();
- H.popover().findByText("Q2 - Product → ID").click();
- H.visualize();
-
- H.assertJoinValid({
- lhsTable: "Q1",
- rhsTable: "Q2",
- lhsSampleColumn: "Product ID",
- rhsSampleColumn: "Q2 - Product → Sum of Rating",
- });
- H.queryBuilderMain().findByText("Q2 - Product → ID").should("not.exist");
-
- H.openNotebook();
- // add a custom column on top of the steps from the #13000 repro which was simply asserting
- // that a question could be made by joining two previously saved questions
- H.addCustomColumn();
- H.enterCustomColumnDetails({
- formula: "[Q2 - Product → Sum of Rating] / [Sum of Total]",
- name: "Sum Divide",
- });
- H.popover().button("Done").click();
-
- H.filter({ mode: "notebook" });
- H.popover().within(() => {
- cy.findByText("Q2").click();
- cy.findByText("Q2 - Product → ID").click();
- cy.findByPlaceholderText("Enter an ID").type("12");
- cy.button("Add filter").click();
- });
-
- H.visualize();
- H.queryBuilderMain().findByText("Sum Divide");
-
- cy.findByTestId("qb-filters-panel")
- .findByText("Q2 - Product → ID is 12")
- .should("be.visible");
- });
-
- it("should handle joins on different stages", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.join();
- H.joinTable("Products");
-
- H.summarize({ mode: "notebook" });
- H.addSummaryField({ metric: "Count of rows" });
- H.addSummaryGroupingField({ table: "Products", field: "ID" });
-
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.findAllByTestId("action-buttons").last().button("Join data").click();
- H.joinTable("Reviews");
- H.visualize();
-
- H.assertJoinValid({
- lhsSampleColumn: "Count",
- rhsSampleColumn: "Reviews → ID",
- });
- H.assertQueryBuilderRowCount(1136);
- });
-
- it("should allow joins with multiple conditions", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.join();
- H.joinTable("Products");
- selectJoinStrategy("Inner join");
-
- H.getNotebookStep("join").icon("add").click();
- H.popover().findByText("Created At").click();
- H.popover().findByText("Created At").click();
-
- H.visualize();
-
- H.assertJoinValid({
- lhsTable: "Orders",
- rhsTable: "Products",
- lhsSampleColumn: "Product ID",
- rhsSampleColumn: "Products → ID",
- });
- H.assertQueryBuilderRowCount(415);
- });
-
- it("should sync join condition's date-time column units", () => {
- H.openOrdersTable({ mode: "notebook" });
-
- H.join();
- H.joinTable("Products");
- selectJoinStrategy("Inner join");
-
- // Test LHS column infers RHS column's temporal unit
-
- cy.findByLabelText("Left column").click();
- H.popover().findByText("Created At").click();
-
- cy.findByLabelText("Right column").click();
- H.popover().findByText("by month").click({ force: true });
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- H.popover().last().findByText("Week").click();
-
- assertJoinColumnName("left", "Created At: Week");
- assertJoinColumnName("right", "Created At: Week");
-
- // Test changing a temporal unit on one column would update a second one
-
- cy.findByLabelText("Right column").click();
- H.popover().findByText("by week").click({ force: true });
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- H.popover().last().findByText("Day").click();
-
- assertJoinColumnName("left", "Created At: Day");
- assertJoinColumnName("right", "Created At: Day");
-
- H.summarize({ mode: "notebook" });
- H.addSummaryField({ metric: "Count of rows" });
-
- H.visualize();
-
- cy.findByTestId("scalar-value").contains("2,087");
- });
-
- it("should remove a join when changing the source table", () => {
- H.visitQuestionAdhoc(
- {
- dataset_query: {
- type: "query",
- database: SAMPLE_DB_ID,
- query: {
- "source-table": ORDERS_ID,
- joins: [
- {
- alias: "Products",
- condition: [
- "=",
- ["field", ORDERS.PRODUCT_ID, null],
- ["field", PRODUCTS.ID, { "join-alias": "Products" }],
- ],
- fields: "all",
- "source-table": PRODUCTS_ID,
- },
- ],
- },
- },
- },
- { mode: "notebook" },
- );
-
- H.getNotebookStep("data").findByTestId("data-step-cell").click();
- H.miniPicker().findByText("People").click();
-
- H.getNotebookStep("join").should("not.exist");
-
- H.visualize();
- H.queryBuilderMain()
- .findAllByText(/Product/)
- .should("have.length", 0);
- });
-});
-
-function selectJoinStrategy(strategy) {
- cy.findByLabelText("Change join type").click();
- H.popover().findByText(strategy).click();
-}
-
-function assertJoinColumnName(side, name) {
- const label = side === "left" ? "Left column" : "Right column";
- cy.findByLabelText(label).findByText(name).should("exist");
-}
diff --git a/e2e/test/scenarios/joins/joins.cy.spec.ts b/e2e/test/scenarios/joins/joins.cy.spec.ts
new file mode 100644
index 00000000000..96d6c16541b
--- /dev/null
+++ b/e2e/test/scenarios/joins/joins.cy.spec.ts
@@ -0,0 +1,486 @@
+const { H } = cy;
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+
+const { ORDERS, ORDERS_ID, PRODUCTS, PRODUCTS_ID, REVIEWS, REVIEWS_ID } =
+ SAMPLE_DATABASE;
+
+describe("scenarios > joins", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ describe("notebook", () => {
+ it("should join raw tables (metabase#11452, metabase#12221, metabase#13468, metabase#15570)", () => {
+ H.openOrdersTable({ mode: "notebook" });
+
+ H.join();
+ H.joinTable("Reviews", "Product ID", "Product ID");
+
+ H.visualize();
+ H.assertJoinValid({
+ lhsTable: "Orders",
+ rhsTable: "Reviews",
+ lhsSampleColumn: "Product ID",
+ rhsSampleColumn: "Reviews - Product → ID",
+ });
+
+ H.openNotebook();
+ H.getNotebookStep("join").icon("chevrondown").click();
+ H.popover().within(() => {
+ cy.findByText("Product ID").click();
+ cy.findByText("Body").click();
+ cy.findByText("Created At").click();
+ });
+ H.visualize();
+
+ H.assertJoinValid({
+ lhsTable: "Orders",
+ rhsTable: "Reviews",
+ lhsSampleColumn: "Product ID",
+ rhsSampleColumn: "Reviews - Product → Reviewer",
+ });
+ H.queryBuilderMain()
+ .findByText("Reviews - Product → Body")
+ .should("not.exist");
+
+ // Post-join filters on the joined table (metabase#12221, metabase#15570)
+ H.openNotebook();
+ H.filter({ mode: "notebook" });
+ H.popover().within(() => {
+ cy.findByText("Reviews").click();
+ cy.findByText("Rating").click();
+ });
+ H.selectFilterOperator("Equal to");
+ H.popover().within(() => {
+ cy.findByLabelText("2").click();
+ cy.button("Add filter").click();
+ });
+
+ // Post-join aggregation (metabase#11452):
+ H.summarize({ mode: "notebook" });
+ H.addSummaryField({
+ metric: "Average of ...",
+ table: "Reviews",
+ field: "Rating",
+ });
+ H.addSummaryGroupingField({ table: "Reviews", field: "Reviewer" });
+
+ H.visualize();
+
+ cy.findByTestId("qb-filters-panel").findByText(
+ "Reviews - Product → Rating is equal to 2",
+ );
+ H.assertQueryBuilderRowCount(89);
+
+ // Make sure UI overlay doesn't obstruct viewing results after we save this question (metabase#13468)
+ cy.findByTestId("qb-header").button("Save").click();
+ cy.findByTestId("save-question-modal")
+ .findByLabelText(/Where do you want to save this/)
+ .click();
+ H.pickEntity({
+ path: ["Our analytics"],
+ });
+ H.entityPickerModal().button("Select this collection").click();
+ cy.findByTestId("save-question-modal").button("Save").click();
+
+ cy.findByTestId("qb-filters-panel").findByText(
+ "Reviews - Product → Rating is equal to 2",
+ );
+ H.assertQueryBuilderRowCount(89);
+ });
+
+ it("joining on a question with remapped values should work (metabase#15578)", () => {
+ const JOINED_QUESTION_NAME = "15578";
+
+ // Remap display value
+ cy.request("POST", `/api/field/${ORDERS.PRODUCT_ID}/dimension`, {
+ name: "Product ID",
+ type: "external",
+ human_readable_field_id: PRODUCTS.TITLE,
+ });
+
+ H.createQuestion({
+ name: JOINED_QUESTION_NAME,
+ query: { "source-table": ORDERS_ID },
+ });
+
+ H.openProductsTable({ mode: "notebook" });
+
+ cy.button("Join data").click();
+ H.miniPicker().within(() => {
+ cy.findByText("Our analytics").click();
+ cy.findByText(JOINED_QUESTION_NAME).click();
+ });
+
+ H.visualize();
+
+ H.queryBuilderHeader()
+ .findByTestId("question-table-badges")
+ .within(() => {
+ cy.findByText("Products").should("be.visible");
+ cy.findByText(JOINED_QUESTION_NAME).should("be.visible");
+ });
+
+ H.queryBuilderMain().within(() => {
+ cy.findByText("Category").should("be.visible");
+ cy.findByText(`${JOINED_QUESTION_NAME} → ID`).should("be.visible");
+ });
+ });
+
+ it("correctly displays joined question's column names (metabase#27521)", () => {
+ cy.signInAsNormalUser();
+ cy.visit("/");
+
+ cy.log("Create Q1");
+ H.openOrdersTable({ mode: "notebook" });
+
+ H.getNotebookStep("data").button("Pick columns").click();
+ H.popover().findByText("Select all").click();
+
+ cy.log("close popover");
+ H.getNotebookStep("data").click();
+
+ H.join();
+
+ H.miniPicker().within(() => {
+ cy.findByText("Sample Database").click();
+ cy.findByText("Orders").click();
+ });
+
+ H.popover().findByText("ID").click();
+ H.popover().findByText("ID").click();
+
+ H.getNotebookStep("join", { stage: 0, index: 0 })
+ .button("Pick columns")
+ .click();
+ H.popover().within(() => {
+ cy.findByText("Select all").click();
+ cy.findByText("ID").click();
+ });
+
+ H.visualize();
+ assertTableHeader(0, "ID");
+ assertTableHeader(1, "Orders_2 → ID");
+
+ H.saveQuestion("Q1");
+
+ assertTableHeader(0, "ID");
+ assertTableHeader(1, "Orders_2 → ID");
+
+ cy.log("Create second question (Products + Q1)");
+ H.newButton("Question").click();
+ H.miniPicker().within(() => {
+ cy.findByText("Sample Database").click();
+ cy.findByText("People").click();
+ });
+
+ H.getNotebookStep("data").button("Pick columns").click();
+ H.popover().findByText("Select all").click();
+
+ H.join();
+
+ H.miniPicker().within(() => {
+ cy.findByText("Our analytics").click();
+ cy.findByText("Q1").click();
+ });
+
+ H.popover().findByText("ID").click();
+ H.popover().findByText("Orders_2 → ID").should("be.visible").click();
+ H.getNotebookStep("join")
+ .findByLabelText("Right column")
+ .findByText("Q1 → ID")
+ .should("be.visible")
+ .click();
+ H.popover()
+ .findAllByText("Q1 → ID")
+ .should("have.length", 2)
+ .first()
+ .click();
+
+ H.visualize();
+
+ assertTableHeader(0, "ID");
+ assertTableHeader(1, "Q1 → ID");
+ assertTableHeader(2, "Q1 → ID");
+
+ H.openVizSettingsSidebar();
+ cy.findByTestId("chartsettings-sidebar").within(() => {
+ cy.findAllByText("ID").should("have.length", 1);
+ cy.findAllByText("Q1 → ID").should("have.length", 2);
+
+ cy.findByRole("button", { name: "Add or remove columns" }).click();
+ cy.findAllByText("ID").should("have.length", 1);
+ cy.findAllByText("Q1 → ID").should("have.length", 2);
+
+ // TODO: add assertions for what happens when toggling all the columns here
+ // See https://github.com/metabase/metabase/issues/27521#issuecomment-1948658757
+ });
+ });
+ });
+
+ describe("drills", () => {
+ it("x-rays should work on explicit joins when metric is for the joined table (metabase#14793)", () => {
+ const XRAY_DATASETS = 11; // enough to load most questions
+
+ cy.intercept("GET", "/api/automagic-dashboards/adhoc/**").as("xray");
+ cy.intercept("POST", "/api/dataset").as("postDataset");
+
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ type: "query",
+ query: {
+ "source-table": REVIEWS_ID,
+ joins: [
+ {
+ fields: "all",
+ "source-table": PRODUCTS_ID,
+ condition: [
+ "=",
+ ["field", REVIEWS.PRODUCT_ID, null],
+ ["field", PRODUCTS.ID, { "join-alias": "Products" }],
+ ],
+ alias: "Products",
+ },
+ ],
+ aggregation: [
+ ["sum", ["field", PRODUCTS.PRICE, { "join-alias": "Products" }]],
+ ],
+ breakout: [
+ ["field", REVIEWS.CREATED_AT, { "temporal-unit": "year" }],
+ ],
+ },
+ database: SAMPLE_DB_ID,
+ },
+ display: "line",
+ });
+
+ H.cartesianChartCircle().eq(2).click({ force: true });
+
+ H.popover().findByText("Automatic insights…").click();
+ H.popover().findByText("X-ray").click();
+
+ cy.wait("@xray").then((xhr) => {
+ for (let i = 0; i < XRAY_DATASETS; ++i) {
+ cy.wait("@postDataset");
+ }
+ expect(xhr.response.statusCode).not.to.eq(500);
+ expect(xhr.response.body.cause).not.to.exist;
+ });
+
+ H.dashboardGrid()
+ .findByText("How this metric is distributed across different numbers")
+ .should("exist");
+
+ cy.findByTestId("automatic-dashboard-header")
+ .findByText(/^A closer look at/)
+ .should("be.visible");
+
+ H.getDashboardCards().should("have.length", 35);
+ });
+
+ it("should retain the filter when drilling through the dashboard card with implicitly added column (metabase#23293)", () => {
+ cy.intercept("POST", "/api/card").as("saveQuestion");
+
+ H.openOrdersTable();
+
+ H.openVizSettingsSidebar();
+ modifyColumn("Product ID", "remove");
+ modifyColumn("Category", "add");
+ cy.wait("@dataset");
+
+ H.queryBuilderHeader().button("Save").click();
+ cy.findByTestId("save-question-modal")
+ .findByLabelText(/Where do you want to save this/)
+ .click();
+ H.pickEntity({
+ path: ["Our analytics"],
+ });
+ H.entityPickerModal().findByText("Select this collection").click();
+ cy.findByTestId("save-question-modal").button("Save").click();
+
+ cy.wait("@saveQuestion").then(({ response }) => {
+ const id = response.body.id;
+ const questionDetails = {
+ query: {
+ "source-table": `card__${id}`,
+ aggregation: [["count"]],
+ breakout: [
+ [
+ "field",
+ PRODUCTS.CATEGORY,
+ {
+ "source-field": ORDERS.PRODUCT_ID,
+ },
+ ],
+ ],
+ },
+ display: "bar",
+ };
+
+ H.createQuestionAndDashboard({ questionDetails }).then(
+ ({ body: { dashboard_id } }) => {
+ H.visitDashboard(dashboard_id);
+ },
+ );
+
+ // Click on the first bar
+ H.chartPathWithFillColor("#509EE3").first().realClick();
+ H.popover()
+ .findByText(/^See these/)
+ .click();
+
+ cy.findByTestId("qb-filters-panel").should(
+ "contain",
+ "Orders → Category is Doohickey",
+ );
+ // eslint-disable-next-line metabase/no-unsafe-element-filtering
+ cy.findAllByTestId("header-cell")
+ .last()
+ .should("have.text", "Product → Category");
+
+ // eslint-disable-next-line metabase/no-unsafe-element-filtering
+ cy.findAllByRole("grid")
+ .last()
+ .should("contain", "Doohickey")
+ .and("not.contain", "Gizmo");
+ });
+ });
+
+ it("should not drop fields from joined table on dashboard 'zoom-in' (metabase#27380)", () => {
+ cy.intercept("POST", "/api/dataset").as("dataset");
+
+ const questionDetails = {
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ [
+ "field",
+ PRODUCTS.CREATED_AT,
+ { "source-field": ORDERS.PRODUCT_ID, "temporal-unit": "month" },
+ ],
+ ],
+ },
+ display: "line",
+ };
+ H.createQuestionAndDashboard({ questionDetails }).then(
+ ({ body: { dashboard_id } }) => {
+ H.visitDashboard(dashboard_id);
+ },
+ );
+
+ // Doesn't really matter which 'circle" we click on the graph
+ // eslint-disable-next-line metabase/no-unsafe-element-filtering
+ H.cartesianChartCircle().last().click();
+ // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
+ cy.findByText("See this month by week").click();
+ cy.wait("@dataset");
+
+ // Graph should still exist
+ // Checks the y-axis label
+ H.echartsContainer().findByText("Count");
+
+ H.openNotebook();
+ // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
+ cy.findByText("Pick a column to group by").should("not.exist");
+ // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
+ cy.findByText("Product → Created At: Week");
+ });
+ });
+
+ describe("models", () => {
+ it("model based on multi-level nested saved question should work (metabase#22859-1)", () => {
+ H.createQuestion(
+ {
+ name: "22859-Q1",
+ query: {
+ "source-table": REVIEWS_ID,
+ joins: [
+ {
+ fields: "all",
+ "source-table": PRODUCTS_ID,
+ condition: [
+ "=",
+ ["field", REVIEWS.PRODUCT_ID, null],
+ ["field", PRODUCTS.ID, { "join-alias": "Products" }],
+ ],
+ alias: "Products",
+ },
+ ],
+ },
+ },
+ { wrapId: true, idAlias: "q1Id" },
+ );
+
+ // Join Orders table with the previously saved question and save it again
+ cy.get("@q1Id").then((id) => {
+ H.createQuestion(
+ {
+ name: "22859-Q2",
+ query: {
+ "source-table": ORDERS_ID,
+ joins: [
+ {
+ fields: "all",
+ alias: `Question ${id}`,
+ condition: [
+ "=",
+ [
+ "field",
+ ORDERS.PRODUCT_ID,
+ { "base-type": "type/Integer" },
+ ],
+ [
+ "field",
+ REVIEWS.PRODUCT_ID,
+ {
+ "base-type": "type/Integer",
+ "join-alias": `Question ${id}`,
+ },
+ ],
+ ],
+ "source-table": `card__${id}`,
+ },
+ ],
+ limit: 5,
+ },
+ },
+ { wrapId: true, idAlias: "q2Id" },
+ );
+ });
+
+ cy.get("@q2Id").then((id) => {
+ // Convert the second question to a model
+ cy.request("PUT", `/api/card/${id}`, { type: "model" });
+
+ cy.intercept("POST", "/api/dataset").as("dataset");
+ cy.visit(`/model/${id}`);
+ cy.wait("@dataset");
+ });
+
+ cy.get("@q1Id").then((id) => {
+ cy.findByText(`Question ${id} → ID`);
+ });
+ });
+ });
+});
+
+function assertTableHeader(index: number, name: string) {
+ // eslint-disable-next-line metabase/no-unsafe-element-filtering
+ cy.findAllByTestId("header-cell").eq(index).should("have.text", name);
+}
+
+function modifyColumn(columnName: string, action: "add" | "remove") {
+ cy.findByTestId("sidebar-left").within(() => {
+ cy.findByRole("button", { name: "Add or remove columns" }).click();
+ if (action === "add") {
+ cy.findByLabelText(columnName).should("not.be.checked").click();
+ } else {
+ cy.findByLabelText(columnName).should("be.checked").click();
+ }
+
+ cy.findByRole("button", { name: "Done picking columns" }).click();
+ });
+}
diff --git a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx
index 545a19597e4..8eab70728d8 100644
--- a/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/filters/components/FilterPicker/FilterColumnPicker/FilterColumnPicker.unit.spec.tsx
@@ -1,10 +1,16 @@
import userEvent from "@testing-library/user-event";
import { setupFieldsValuesEndpoints } from "__support__/server-mocks";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, within } from "__support__/ui";
import * as Lib from "metabase-lib";
import { DEFAULT_TEST_QUERY, SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
-import { SAMPLE_DB_FIELD_VALUES } from "metabase-types/api/mocks/presets";
+import {
+ ORDERS_ID,
+ REVIEWS_ID,
+ SAMPLE_DB_FIELD_VALUES,
+} from "metabase-types/api/mocks/presets";
+
+import type { ColumnListItem } from "../types";
import { FilterColumnPicker } from "./FilterColumnPicker";
@@ -14,17 +20,19 @@ interface SetupOpts {
}
function setup({ query, stageIndexes }: SetupOpts) {
+ const onColumnSelect = jest.fn<void, [ColumnListItem]>();
setupFieldsValuesEndpoints(SAMPLE_DB_FIELD_VALUES);
renderWithProviders(
<FilterColumnPicker
query={query}
stageIndexes={stageIndexes}
checkItemIsSelected={() => false}
- onColumnSelect={jest.fn()}
+ onColumnSelect={onColumnSelect}
onSegmentSelect={jest.fn()}
onExpressionSelect={jest.fn()}
/>,
);
+ return { onColumnSelect };
}
describe("FilterColumnPicker", () => {
@@ -49,4 +57,62 @@ describe("FilterColumnPicker", () => {
await screen.findByRole("option", { name: "Birth Date" }),
).toBeInTheDocument();
});
+
+ it("should keep column groups with the same name apart (metabase#45300)", async () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: REVIEWS_ID },
+ joins: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ strategy: "left-join",
+ conditions: [
+ {
+ operator: "=",
+ left: { type: "column", name: "PRODUCT_ID" },
+ right: { type: "column", name: "PRODUCT_ID" },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ const { onColumnSelect } = setup({ query, stageIndexes: [0] });
+
+ expect(screen.getAllByText("Product")).toHaveLength(2);
+
+ await userEvent.click(screen.getAllByText("Product")[0]);
+ await userEvent.click(
+ within(await screen.findByRole("option", { name: "Category" })).getByText(
+ "Category",
+ ),
+ );
+ await userEvent.click(screen.getAllByText("Product")[1]);
+ await userEvent.click(
+ within(await screen.findByRole("option", { name: "Category" })).getByText(
+ "Category",
+ ),
+ );
+
+ const getColumnRef = (column: Lib.ColumnMetadata) =>
+ Lib.legacyRef(query, 0, column);
+ const expectedColumnRefs = Lib.groupColumns(Lib.filterableColumns(query, 0))
+ .filter(
+ (group) => Lib.displayInfo(query, 0, group).displayName === "Product",
+ )
+ .map((group) =>
+ Lib.getColumnsFromColumnGroup(group).find(
+ (column) => Lib.displayInfo(query, 0, column).name === "CATEGORY",
+ ),
+ )
+ .map((column) => column && getColumnRef(column));
+
+ expect(expectedColumnRefs).toHaveLength(2);
+ expect(expectedColumnRefs[0]).not.toEqual(expectedColumnRefs[1]);
+ expect(
+ onColumnSelect.mock.calls.map(([item]) => getColumnRef(item.column)),
+ ).toEqual(expectedColumnRefs);
+ });
});
diff --git a/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsx
index 5d61666f314..f1ba8a2521b 100644
--- a/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsx
@@ -17,6 +17,7 @@ import type { CardType, IconName } from "metabase-types/api";
import { createMockSearchResult } from "metabase-types/api/mocks";
import {
ORDERS_ID,
+ PRODUCTS_ID,
SAMPLE_DB_ID,
createSampleDatabase,
createSavedStructuredCard,
@@ -181,6 +182,38 @@ describe("DataStep", () => {
expect(getNextTableName()).toBe("Products");
});
+ it("should remove joins when changing a table", async () => {
+ const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ joins: [
+ {
+ source: { type: "table", id: PRODUCTS_ID },
+ strategy: "left-join",
+ conditions: [
+ {
+ operator: "=",
+ left: { type: "column", name: "PRODUCT_ID" },
+ right: { type: "column", name: "ID" },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ const { getNextQuery, getNextTableName } = await setup({
+ step: createMockNotebookStep({ query }),
+ });
+
+ await userEvent.click(screen.getByText("Orders"));
+ await userEvent.click(await screen.findByText("People"));
+
+ expect(getNextTableName()).toBe("People");
+ expect(Lib.joins(getNextQuery(), 0)).toHaveLength(0);
+ });
+
describe("fields selection", () => {
it("should render with all columns selected", async () => {
await setup();
diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx
index 29fd9cda4d1..842ddf163cf 100644
--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx
+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx
@@ -1,5 +1,5 @@
import _userEvent from "@testing-library/user-event";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { createMockMetadata } from "__support__/metadata";
import {
@@ -21,8 +21,12 @@ import {
within,
} from "__support__/ui";
import { METAKEY } from "metabase/utils/browser";
+import { checkNotNull } from "metabase/utils/types";
import * as Lib from "metabase-lib";
-import { createMetadataProvider } from "metabase-lib/test-helpers";
+import {
+ columnFinder,
+ createMetadataProvider,
+} from "metabase-lib/test-helpers";
import type {
CollectionItem,
RecentItem,
@@ -33,12 +37,15 @@ import {
createMockCollection,
createMockCollectionItem,
createMockDatabase,
+ createMockField,
createMockRecentCollectionItem,
+ createMockTable,
} from "metabase-types/api/mocks";
import {
ORDERS_ID,
PEOPLE_ID,
PRODUCTS_ID,
+ REVIEWS_ID,
createSampleDatabase,
createSavedStructuredCard,
createStructuredModelCard,
@@ -48,12 +55,34 @@ import { createMockNotebookStep, getColumnNames } from "../../test-utils";
import type { NotebookStep } from "../../types";
import { NotebookProvider } from "../Notebook/context";
+import { getDefaultJoinStrategy } from "./JoinDraft/utils";
import { JoinStep } from "./JoinStep";
const SAMPLE_DATABASE = createSampleDatabase();
+const ANOTHER_DATABASE_ID = 2;
+const ANOTHER_DATABASE_TABLE_ID = 100;
const ANOTHER_DATABASE = createMockDatabase({
- id: 2,
+ id: ANOTHER_DATABASE_ID,
name: "Another Database",
+ tables: [
+ createMockTable({
+ id: ANOTHER_DATABASE_TABLE_ID,
+ db_id: ANOTHER_DATABASE_ID,
+ name: "ACCOUNTS",
+ display_name: "Accounts",
+ fields: [
+ createMockField({
+ id: 1000,
+ table_id: ANOTHER_DATABASE_TABLE_ID,
+ name: "ID",
+ display_name: "ID",
+ base_type: "type/BigInteger",
+ effective_type: "type/BigInteger",
+ semantic_type: "type/PK",
+ }),
+ ],
+ }),
+ ],
});
const DATABASES = [SAMPLE_DATABASE, ANOTHER_DATABASE];
const MODEL = createStructuredModelCard({ name: "my cool model" });
@@ -82,6 +111,10 @@ const metadata = createMockMetadata({
});
const provider = createMetadataProvider({ metadata });
+const anotherDatabaseProvider = createMetadataProvider({
+ databaseId: ANOTHER_DATABASE_ID,
+ metadata,
+});
const userEvent = _userEvent.setup();
@@ -203,8 +236,10 @@ function setup({
collectionItems: [],
});
- function Wrapper() {
- const [query, setQuery] = useState(step.query);
+ function Wrapper({ sourceQuery }: { sourceQuery: Lib.Query }) {
+ const [query, setQuery] = useState(sourceQuery);
+
+ useEffect(() => setQuery(sourceQuery), [sourceQuery]);
const onChange = async (nextQuery: Lib.Query) => {
setQuery(nextQuery);
@@ -227,9 +262,16 @@ function setup({
);
}
- renderWithProviders(<Wrapper />, {
- storeInitialState: STATE,
- });
+ const { rerender } = renderWithProviders(
+ <Wrapper sourceQuery={step.query} />,
+ {
+ storeInitialState: STATE,
+ },
+ );
+
+ function changeQuery(nextQuery: Lib.Query) {
+ rerender(<Wrapper sourceQuery={nextQuery} />);
+ }
function getNextQuery(): Lib.Query {
const [lastCall] = updateQuery.mock.calls.slice(-1);
@@ -262,7 +304,7 @@ function setup({
};
}
- return { getRecentJoin, mockWindowOpen };
+ return { getRecentJoin, changeQuery, updateQuery, mockWindowOpen };
}
async function enterCustomExpression(expression: string) {
@@ -684,6 +726,144 @@ describe("Notebook Editor > Join Step", () => {
expect(within(lhsColumn).queryByText("ID")).not.toBeInTheDocument();
});
+ it.each([
+ {
+ description: "a table in the same database",
+ sourceQuery: () =>
+ Lib.createTestQuery(provider, {
+ stages: [{ source: { type: "table", id: PRODUCTS_ID } }],
+ }),
+ sourceTableName: "Products",
+ },
+ {
+ description: "a table in another database",
+ sourceQuery: () =>
+ Lib.createTestQuery(anotherDatabaseProvider, {
+ stages: [
+ { source: { type: "table", id: ANOTHER_DATABASE_TABLE_ID } },
+ ],
+ }),
+ sourceTableName: "Accounts",
+ },
+ ])(
+ "should reset the draft join when the source changes to $description (metabase#42385, metabase#46675)",
+ async ({ sourceQuery, sourceTableName }) => {
+ const { changeQuery } = setup();
+ await userEvent.click(
+ within(screen.getByLabelText("Right table")).getByRole("textbox"),
+ );
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: /Browse all/ }),
+ );
+ const modal = await screen.findByTestId("entity-picker-modal");
+ await waitForLoaderToBeRemoved();
+ await userEvent.click(await within(modal).findByText("Databases"));
+ await userEvent.click(await screen.findByText(/Sample Database/));
+ await userEvent.click(await within(modal).findByText("Reviews"));
+ const lhsColumnPicker = await screen.findByTestId("lhs-column-picker");
+ await userEvent.click(await within(lhsColumnPicker).findByText("ID"));
+
+ expect(screen.getByLabelText("Right table")).toHaveTextContent("Reviews");
+ expect(screen.getByTestId("new-join-condition")).toBeInTheDocument();
+
+ changeQuery(sourceQuery());
+
+ expect(await screen.findByLabelText("Left table")).toHaveTextContent(
+ sourceTableName,
+ );
+ expect(screen.getByLabelText("Right table")).not.toHaveTextContent(
+ "Reviews",
+ );
+ expect(
+ screen.queryByTestId("new-join-condition"),
+ ).not.toBeInTheDocument();
+ },
+ );
+
+ describe("post-aggregation stage", () => {
+ it("should show 'Previous results' for a LHS aggregation column (metabase#17968)", async () => {
+ const query = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [{ type: "column", name: "CREATED_AT" }],
+ },
+ {},
+ ],
+ });
+ setup({ step: createMockNotebookStep({ query, stageIndex: 1 }) });
+
+ await userEvent.click(
+ within(screen.getByLabelText("Right table")).getByRole("textbox"),
+ );
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: /Browse all/ }),
+ );
+ const modal = await screen.findByTestId("entity-picker-modal");
+ await waitForLoaderToBeRemoved();
+ await userEvent.click(await within(modal).findByText("Databases"));
+ await userEvent.click(await screen.findByText(/Sample Database/));
+ await userEvent.click(await within(modal).findByText("Products"));
+ const lhsColumnPicker = await screen.findByTestId("lhs-column-picker");
+ await userEvent.click(within(lhsColumnPicker).getByText("Count"));
+
+ const lhsColumn = screen.getByLabelText("Left column");
+ await waitFor(() => expect(lhsColumn).toHaveTextContent("Count"));
+ expect(lhsColumn).toHaveTextContent("Previous results");
+ });
+
+ it("should suggest a condition from a previous-stage breakout on a joined column", async () => {
+ const query = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: { type: "table", id: ORDERS_ID },
+ joins: [
+ {
+ source: { type: "table", id: PRODUCTS_ID },
+ strategy: "left-join",
+ conditions: [
+ {
+ operator: "=",
+ left: { type: "column", name: "PRODUCT_ID" },
+ right: { type: "column", name: "ID" },
+ },
+ ],
+ },
+ ],
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ breakouts: [{ type: "column", name: "ID", joinAlias: "Products" }],
+ },
+ {},
+ ],
+ });
+ const { getRecentJoin } = setup({
+ step: createMockNotebookStep({ query, stageIndex: 1 }),
+ });
+
+ await userEvent.click(
+ within(screen.getByLabelText("Right table")).getByRole("textbox"),
+ );
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: /Browse all/ }),
+ );
+ const modal = await screen.findByTestId("entity-picker-modal");
+ await waitForLoaderToBeRemoved();
+ await userEvent.click(await within(modal).findByText("Databases"));
+ await userEvent.click(await screen.findByText(/Sample Database/));
+ await userEvent.click(await within(modal).findByText("Reviews"));
+
+ const { conditions } = getRecentJoin();
+ const [condition] = conditions;
+ expect(conditions).toHaveLength(1);
+ expect(condition.operator).toBe("=");
+ expect(condition.lhsExpression.longDisplayName).toBe("Products → ID");
+ expect(condition.rhsExpression.longDisplayName).toBe(
+ "Reviews → Product ID",
+ );
+ });
+ });
+
describe("join strategies", () => {
it("should be able to change the join strategy for a new join clause", async () => {
const { getRecentJoin } = setup();
@@ -1169,6 +1349,31 @@ describe("Notebook Editor > Join Step", () => {
).not.toBeInTheDocument();
});
+ it("should not add an incomplete condition to the query (metabase#17710)", async () => {
+ const { updateQuery } = setup({
+ step: createMockNotebookStep({ query: getJoinedQuery() }),
+ });
+
+ await userEvent.click(screen.getByLabelText("Add condition"));
+ const conditionContainer = screen.getByTestId("new-join-condition");
+ const lhsColumnPicker = await screen.findByTestId("lhs-column-picker");
+ await userEvent.click(within(lhsColumnPicker).getByText("Created At"));
+ await waitFor(() =>
+ expect(
+ within(conditionContainer).getByLabelText("Left column"),
+ ).toHaveTextContent("Created At"),
+ );
+
+ const completeCondition = screen.getByTestId("join-condition-0");
+ expect(
+ within(completeCondition).getByLabelText("Left column"),
+ ).toHaveTextContent("Product ID");
+ expect(
+ within(completeCondition).getByLabelText("Right column"),
+ ).toHaveTextContent("ID");
+ expect(updateQuery).not.toHaveBeenCalled();
+ });
+
it("should remove a complete condition", async () => {
const { getRecentJoin } = setup({
step: createMockNotebookStep({
@@ -1427,6 +1632,145 @@ describe("Notebook Editor > Join Step", () => {
expect(condition.rhsExpression.longDisplayName).toBe("ID + 1");
});
+ it("should update an existing join with custom expressions on both sides", async () => {
+ const { getRecentJoin } = setup({
+ step: createMockNotebookStep({
+ query: getJoinedQueryWithCustomExpressions(
+ { type: "literal", value: 1 },
+ { type: "literal", value: 1 },
+ ),
+ }),
+ });
+
+ await userEvent.click(screen.getByLabelText("Change operator"));
+ await userEvent.click(
+ within(await screen.findByTestId("select-list")).getByLabelText("!="),
+ );
+ await userEvent.click(screen.getByLabelText("Change join type"));
+ await userEvent.click(
+ within(await screen.findByTestId("select-list")).getByLabelText(
+ "Inner join",
+ ),
+ );
+
+ await userEvent.click(screen.getByLabelText("Left column"));
+ expect(
+ await screen.findByTestId("custom-expression-query-editor"),
+ ).toHaveValue("1");
+ await enterCustomExpression("[[Product ID] + 1");
+ await submitCustomExpression();
+
+ await userEvent.click(screen.getByLabelText("Right column"));
+ expect(
+ await screen.findByTestId("custom-expression-query-editor"),
+ ).toHaveValue("1");
+ await enterCustomExpression("[[Products → ID] + 1");
+ await submitCustomExpression();
+
+ const { strategy, conditions } = getRecentJoin();
+ const [condition] = conditions;
+ expect(strategy.shortName).toBe("inner-join");
+ expect(conditions).toHaveLength(1);
+ expect(condition.operator).toBe("!=");
+ expect(condition.lhsExpression.longDisplayName).toBe("Product ID + 1");
+ expect(condition.rhsExpression.longDisplayName).toBe("ID + 1");
+ });
+
+ it("should allow custom expressions referencing model columns on both sides", async () => {
+ const query = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: { type: "card", id: MODEL.id },
+ joins: [
+ {
+ source: { type: "card", id: MODEL.id },
+ strategy: "left-join",
+ conditions: [
+ {
+ operator: "=",
+ left: { type: "column", name: "ID" },
+ right: { type: "column", name: "ID" },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ const { getRecentJoin } = setup({
+ step: createMockNotebookStep({ query }),
+ });
+
+ await userEvent.click(screen.getByLabelText("Left column"));
+ const lhsPicker = await screen.findByTestId("lhs-column-picker");
+ await userEvent.click(within(lhsPicker).getByText("Custom Expression"));
+ await enterCustomExpression("[[ID] + [[User ID]");
+ await submitCustomExpression();
+
+ await userEvent.click(screen.getByLabelText("Right column"));
+ const rhsPicker = await screen.findByTestId("rhs-column-picker");
+ await userEvent.click(within(rhsPicker).getByText("Custom Expression"));
+ await enterCustomExpression(
+ `[[${MODEL.name}_2 → ID] + [[${MODEL.name}_2 → Product ID]`,
+ );
+ await submitCustomExpression();
+
+ const [condition] = getRecentJoin().conditions;
+ expect(condition.lhsExpression.longDisplayName).toBe("ID + User ID");
+ expect(condition.rhsExpression.longDisplayName).toBe(
+ `${MODEL.name}_2 → ID + ${MODEL.name}_2 → Product ID`,
+ );
+ });
+
+ it("should display a custom column used as a join column (metabase#18818)", () => {
+ const queryWithExpression = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: { type: "table", id: REVIEWS_ID },
+ expressions: [
+ {
+ name: "CC Rating",
+ value: { type: "column", name: "RATING" },
+ },
+ ],
+ },
+ ],
+ });
+ const orders = checkNotNull(
+ Lib.tableOrCardMetadata(queryWithExpression, ORDERS_ID),
+ );
+ const findLhsColumn = columnFinder(
+ queryWithExpression,
+ Lib.joinConditionLHSColumns(queryWithExpression, 0, orders),
+ );
+ const findRhsColumn = columnFinder(
+ queryWithExpression,
+ Lib.joinConditionRHSColumns(queryWithExpression, 0, orders),
+ );
+ const condition = Lib.joinConditionClause(
+ "=",
+ findLhsColumn(null, "CC Rating"),
+ findRhsColumn("ORDERS", "QUANTITY"),
+ );
+ const query = Lib.join(
+ queryWithExpression,
+ 0,
+ Lib.joinClause(
+ orders,
+ [condition],
+ getDefaultJoinStrategy(queryWithExpression, 0),
+ ),
+ );
+ setup({ step: createMockNotebookStep({ query }) });
+
+ expect(screen.getByLabelText("Left column")).toHaveTextContent(
+ "CC Rating",
+ );
+ expect(screen.getByLabelText("Right column")).toHaveTextContent(
+ "Quantity",
+ );
+ });
+
it("should display the literal value for a LHS literal", () => {
setup({
step: createMockNotebookStep({