Skip to content

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

19.2 KB
Raw Blame
const { H } = cy;
import { SAMPLE_DB_ID, USER_GROUPS } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";

import { getRunQueryButton, runQuery } from "./helpers/e2e-sql-filter-helpers";

const { PRODUCTS, ORDERS_ID } = SAMPLE_DATABASE;

describe("issue 12439", () => {
  const nativeQuery = `
  SELECT "PRODUCTS__via__PRODUCT_ID"."CATEGORY" AS "CATEGORY",
         date_trunc('month', "ORDERS"."CREATED_AT") AS "CREATED_AT",
         count(*) AS "count"
  FROM "ORDERS"
  LEFT JOIN "PRODUCTS" "PRODUCTS__via__PRODUCT_ID"
         ON "ORDERS"."PRODUCT_ID" = "PRODUCTS__via__PRODUCT_ID"."ID"
  GROUP BY "PRODUCTS__via__PRODUCT_ID"."CATEGORY",
           date_trunc('month', "ORDERS"."CREATED_AT")
  ORDER BY "PRODUCTS__via__PRODUCT_ID"."CATEGORY" ASC,
           date_trunc('month', "ORDERS"."CREATED_AT") ASC
  `;

  const questionDetails = {
    dataset_query: {
      database: SAMPLE_DB_ID,
      native: {
        query: nativeQuery,
      },
      type: "native",
    },
    display: "line",
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

    H.visitQuestionAdhoc(questionDetails);
  });

  it("should allow clicking on a legend in a native question without breaking the UI (metabase#12439)", () => {
    cy.findByTestId("query-visualization-root").within(() => {
      cy.findByText("Gizmo").click();

      // Make sure the legends and the graph are still there
      cy.findByText("Gizmo").should("be.visible");
      cy.findByText("Doohickey").should("be.visible");

      H.cartesianChartCircle();
    });

    // Make sure buttons are clickable
    H.openVizSettingsSidebar();

    H.sidebar().contains("X-axis");
    H.sidebar().contains("Y-axis");
  });
});
describe("issue 17060", () => {
  const ORIGINAL_QUERY =
    'select ID as "num", CATEGORY as "text" from PRODUCTS limit 1';
  const SECTION = "select ";
  const SELECTED_TEXT = "ID";

  function rearrangeColumns() {
    cy.findAllByTestId(/draggable-item/)
      .first()
      .trigger("mousedown", 0, 0, { force: true })
      .trigger("mousemove", 5, 5, { force: true })
      .trigger("mousemove", 0, 100, { force: true })
      .trigger("mouseup", 0, 100, { force: true });
  }

  beforeEach(() => {
    cy.intercept("POST", "/api/dataset").as("dataset");

    H.restore();
    cy.signInAsAdmin();
    H.visitQuestionAdhoc({
      display: "table",
      dataset_query: {
        database: SAMPLE_DB_ID,
        type: "native",
        native: {
          query: ORIGINAL_QUERY,
        },
      },
      visualization_settings: {},
    });

    H.openVizSettingsSidebar();
    cy.findByTestId("sidebar-left").within(() => {
      rearrangeColumns();
    });
  });

  it("should not render duplicated columns (metabase#17060)", () => {
    H.NativeEditor.focus();
    cy.realPress("Home");
    Cypress._.range(SECTION.length).forEach(() => cy.realPress("ArrowRight"));
    Cypress._.range(SELECTED_TEXT.length).forEach(() =>
      cy.realPress(["Shift", "ArrowRight"]),
    );
    H.NativeEditor.type("RATING", { focus: false });
    runQuery();

    H.tableInteractiveBody().findByText("4.6").should("be.visible");
    cy.findByTestId("query-visualization-root").within(() => {
      cy.findAllByTestId("header-cell").should("have.length", 2);
      cy.findByText("num").should("be.visible");
    });
  });
});

describe("issue 18148", () => {
  const dbName = "sqlite";

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

    cy.addSQLiteDatabase({
      name: dbName,
    });
  });

  it("should not offer to save the question before it is actually possible to save it (metabase#18148)", () => {
    cy.visit("/");
    cy.findByTestId("app-bar").findByLabelText("New").click();
    H.popover().findByText("SQL query").click();

    cy.findByTestId("qb-save-button").should(
      "have.attr",
      "aria-disabled",
      "true",
    );

    cy.findByTestId("gui-builder-data").should("contain", "Select a database");
    H.popover().should("contain", "Sample Database").and("contain", dbName);
    H.popover().findByText(dbName).click();

    H.NativeEditor.focus().type("select foo");

    cy.findByTestId("qb-save-button").click();
    cy.findByTestId("save-question-modal").findByText("Save").should("exist");
  });
});

describe("issue 19451", () => {
  const question = {
    name: "19451",
    native: {
      query: "select count(*) from products where {{filter}}",
      "template-tags": {
        filter: {
          id: "1b33304a-18ea-cc77-083a-b5225954f200",
          name: "filter",
          "display-name": "Filter",
          type: "dimension",
          dimension: ["field", PRODUCTS.ID, null],
          "widget-type": "id",
          default: null,
        },
      },
    },
    display: "scalar",
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();

    H.createNativeQuestion(question, { visitQuestion: true });
  });

  it("question field filter shows all tables from a selected database (metabase#19451, metabase#23510)", () => {
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Open Editor").click();

    cy.log("The data reference loads uncached metadata (metabase#23510)");
    cy.findByTestId("sidebar-content").within(() => {
      cy.findByText("ORDERS");
      cy.findByText("PRODUCTS");
      cy.findByText("REVIEWS");
      cy.findByText("PEOPLE");
      cy.findByText("Sample Database");
    });

    cy.icon("variable").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Products").click();
    cy.icon("chevronleft").click();

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Products");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Orders");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("People");
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Reviews");
  });
});

describe("issue 20044", () => {
  const questionDetails = {
    name: "20044",
    native: {
      query: "select 1",
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("nodata user should not see 'Explore results' (metabase#20044)", () => {
    H.createNativeQuestion(questionDetails).then(({ body: { id } }) => {
      H.visitQuestion(id);
      cy.findByTestId("qb-header-action-panel")
        .findByText("Explore results")
        .should("be.visible");

      cy.signIn("nodata");

      H.visitQuestion(id);

      cy.get("[data-testid=cell-data]").contains("1");
      cy.findByTestId("qb-header-action-panel")
        .findByText("Explore results")
        .should("not.exist");
    });
  });
});

describe("issue 31926", { tags: "@external" }, () => {
  const databaseName = "Sample Database";
  const databaseCopyName = `${databaseName} copy`;

  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should disable running and saving after switching a field filter query to another database (metabase#31926)", () => {
    // Second DB (copy)
    H.addPostgresDatabase(databaseCopyName);

    // Create a native query and run it
    H.startNewNativeQuestion();
    H.NativeEditor.type("SELECT COUNT(*) FROM PRODUCTS WHERE {{FILTER}}");

    cy.findByTestId("variable-type-select").click();
    H.popover().within(() => {
      cy.findByText("Field Filter").click();
    });
    H.popover().within(() => {
      cy.findByText("Products").click();
    });
    H.popover().within(() => {
      cy.findByText("Category").click();
    });

    cy.findByTestId("native-query-editor-container").icon("play").click();
    cy.findByTestId("scalar-value").should("have.text", "200");
    cy.findByTestId("qb-save-button").should("not.have.attr", "data-disabled");

    // Change DB
    // and re-run the native query
    cy.findByTestId("native-query-editor-container")
      .findByText("Sample Database")
      .click();
    H.popover().within(() => {
      cy.findByText(databaseCopyName).click();
    });
    // run button disabled
    cy.findAllByTestId("run-button").filter(":visible").should("be.disabled");

    // Try to save the native query
    // save button disabled
    cy.findByTestId("qb-save-button").should(
      "have.attr",
      "data-disabled",
      "true",
    );
  });
});

describe("issue 21597", () => {
  // The save request is stubbed with an error to check that its message
  // shows in the save modal.
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("display the relevant error message in save question modal (metabase#21597)", () => {
    const message =
      'Invalid Field Filter: Field 164574 "PRODUCTS"."CATEGORY" belongs to Database 2276 "sample-dataset", but the query is against Database 2275 "test-data"';
    cy.intercept({ method: "POST", url: "/api/card" }, (request) => {
      request.reply({
        body: {
          message: message,
          _status: 400,
        },
        statusCode: 400,
      });
    }).as("saveNativeQuestion");

    // Create a native query and run it
    H.startNewNativeQuestion();
    H.NativeEditor.type("SELECT 1");

    // Try to save the native query
    cy.findByTestId("qb-header-action-panel").findByText("Save").click();
    H.modal().within(() => {
      cy.findByPlaceholderText("What is the name of your question?").type(
        "The question name",
      );
      cy.findByText("Save").click();
      cy.wait("@saveNativeQuestion");
      cy.findByText(message);
    });
  });
});

describe("issue 30680", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should not render native editor buttons when 'Columns' tab is open (metabase#30680, metabase#53649)", () => {
    H.startNewNativeModel();

    cy.log("The native editor does not freeze (metabase#53649)");
    H.NativeEditor.type("select 1");
    H.NativeEditor.get().should("contain", "select 1");

    cy.findByTestId("editor-tabs-columns").should("be.disabled");

    H.runNativeQuery();
    cy.findByTestId("editor-tabs-columns").should("not.be.disabled");
    cy.findByTestId("native-query-editor-action-buttons").should("be.visible");
    cy.findByTestId("editor-tabs-columns-name").click();

    cy.findByTestId("sidebar-content").should("exist");
    cy.findByTestId("native-query-editor-action-buttons").should("not.exist");
  });
});

describe("issue 34330", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
    H.startNewNativeQuestion();

    cy.intercept({
      method: "GET",
      pathname: `/api/database/${SAMPLE_DB_ID}/autocomplete_suggestions`,
    }).as("autocomplete");

    H.clearBrowserCache();
  });

  it("should only call the autocompleter with all text typed (metabase#34330)", () => {
    cy.findByTestId("query-visualization-root")
      .findByText("Here's where your results will appear")
      .should("be.visible");

    H.NativeEditor.type("SEAT", { delay: 10 });
    H.NativeEditor.completion("SEATS").should("be.visible");

    cy.wait("@autocomplete").then(({ request }) => {
      const url = new URL(request.url);
      expect(url.searchParams.get("substring")).to.equal("SEAT");
    });

    // only one call to the autocompleter should have been made
    cy.get("@autocomplete.all").should("have.length", 1);
  });

  it("should call the autocompleter eventually and only once, even when only 1 character was typed (metabase#34330, metabase#21034)", () => {
    H.NativeEditor.type("S", { delay: 10 });
    H.NativeEditor.completion("SEATS").should("be.visible");

    cy.wait("@autocomplete").then(({ request }) => {
      const url = new URL(request.url);
      expect(url.searchParams.get("substring")).to.equal("S");
    });

    // only one call to the autocompleter should have been made
    cy.get("@autocomplete.all").should("have.length", 1);

    cy.log(
      "should not invoke API calls for autocomplete twice in a row (metabase#21034)",
    );
    // Wait until another explicit autocomplete could be triggered
    // (slightly longer than AUTOCOMPLETE_DEBOUNCE_DURATION)
    // See https://github.com/metabase/metabase/pull/20970
    cy.wait(1000);
    cy.get("@autocomplete.all").should("have.length", 1);
  });

  it("should call the autocompleter when backspacing to a 1-character prefix (metabase#34330)", () => {
    H.NativeEditor.type("SEAT{backspace}", { delay: 10 });
    H.NativeEditor.completion("SEATS").should("be.visible");

    cy.wait("@autocomplete").should(({ request }) => {
      const url = new URL(request.url);
      expect(url.searchParams.get("substring")).to.equal("SEA");
    });

    // only one call to the autocompleter should have been made
    cy.get("@autocomplete.all").should("have.length", 1);
  });
});

describe("issue 35344", () => {
  const questionDetails = {
    name: "REVIEWS SQL",
    native: { query: "select REVIEWER from REVIEWS" },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
  });

  it("should not allow the user to undo to the empty editor (metabase#35344)", () => {
    H.createNativeQuestion(questionDetails, { visitQuestion: true });

    cy.findByTestId("query-builder-main").findByText("Open Editor").click();

    // make sure normal undo still works
    H.NativeEditor.type("--");
    expect(H.NativeEditor.get().findByText("--")).to.exist;

    H.NativeEditor.focus();
    cy.realPress(["Meta", "z"]);
    H.NativeEditor.get().findByText("--").should("not.exist");

    // more undoing does not change to empty editor
    H.NativeEditor.focus();
    cy.realPress(["Meta", "z"]);
    expect(H.NativeEditor.get().findByText("select")).to.exist;
  });
});

describe("issue 35785", () => {
  const nativeQuery =
    "select * from products where created_at < {{max_date}} and created_at > {{from}} limit 5";

  const questionDetails = {
    native: {
      query: nativeQuery,
      "template-tags": {
        max_date: {
          id: "32b7654f-38b1-2dfd-ded6-ed23c45ef5f6",
          name: "max_date",
          "display-name": "Max date",
          type: "date",
          default: "2030-01-01",
          required: true,
        },
        from: {
          id: "ddf7c404-38db-8b65-f90d-c6f4bd8127ec",
          name: "from",
          "display-name": "From",
          type: "date",
          default: "2025-10-02",
          required: true,
        },
      },
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();

    H.createNativeQuestion(questionDetails, { visitQuestion: true });

    cy.intercept("GET", "/api/search?*").as("getSearchResults");
    cy.intercept("PUT", "/api/card/*").as("updateCard");
  });

  it("should not redirect to the value of 'from' URL parameter after saving (metabase#35785)", () => {
    cy.findByTestId("native-query-editor-container")
      .findByTestId("visibility-toggler")
      .click();
    H.NativeEditor.type("{backspace}4");

    cy.findByTestId("qb-header").findByRole("button", { name: "Save" }).click();

    cy.findByTestId("save-question-modal").within((modal) => {
      cy.findByText("Save").click();
    });

    cy.wait("@updateCard");
    cy.wait("@getSearchResults");

    cy.findByTestId("save-question-modal").should("not.exist");
    cy.location("pathname").should("match", /^\/question\/\d+/);
  });
});

describe("issue 22991", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should not show 'no permissions' screen when question with no access is referenced (metabase#22991)", () => {
    const questionDetails = {
      name: "question 22991",
      query: {
        "source-table": ORDERS_ID,
        limit: 5,
      },
    };

    H.createCollection({ name: "Restricted Collection" }).then(
      ({ body: restrictedCollection }) => {
        cy.updateCollectionGraph({
          [USER_GROUPS.COLLECTION_GROUP]: {
            [restrictedCollection.id]: "none",
          },
        });

        H.createQuestion(
          {
            ...questionDetails,
            collection_id: restrictedCollection.id,
          },
          { wrapId: true },
        );
      },
    );

    cy.signOut();
    cy.signInAsNormalUser();

    H.startNewNativeQuestion();
    cy.get("@questionId").then((questionId) => {
      // can't use cy.type because it does not simulate the bug
      H.NativeEditor.type(`select * from {{#${questionId}`);
      H.NativeEditor.get()
        .should("be.visible")
        .and("contain.text", `#${questionId}`);
    });

    cy.get("main").should(
      "not.contain",
      "Sorry, you don’t have permission to see that",
    );
  });
});

describe("issue 46308", () => {
  const nativeQuery =
    "select category, count(*) from products where category != {{exclude}} group by category";

  const questionDetails = {
    native: {
      query: nativeQuery,
      "template-tags": {
        exclude: {
          id: "ddf7c404-38db-8b65-f90d-c6f4bd8127ec",
          name: "exclude",
          "display-name": "Exclude",
          type: "text",
        },
      },
    },
    display: "line",
    visualization_settings: {
      "graph.metrics": ["category"],
      "graph.dimensions": ["count"],
    },
  };

  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
    H.createNativeQuestion(questionDetails, { visitQuestion: true });
  });

  it("should persist viz settings when saving a question without a required filter selected (metabase#46308)", () => {
    cy.findByTestId("native-query-editor-container")
      .findByTestId("visibility-toggler")
      .click();

    cy.icon("variable").click();
    cy.get("input[value=Exclude]").eq(0).type(" Category").blur();

    cy.findByTestId("qb-save-button").click();
    cy.findByTestId("save-question-modal").findByText("Save").click();

    cy.findByPlaceholderText("Exclude Category").type("Doohickey");
    getRunQueryButton().click();

    H.cartesianChartCircle().should("have.length", 3);
  });
});

describe("issue 38176", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsNormalUser();
    cy.intercept("PUT", "/api/card/**").as("updateQuestion");
  });

  it("restoring a question to a previous version should preserve the variables (metabase#38176)", () => {
    H.createNativeQuestion(
      {
        name: "38176",
        native: {
          query:
            'SELECT "COUNTRY" from "ACCOUNTS" WHERE country = {{ country }} LIMIT 5',
          "template-tags": {
            country: {
              type: "text",
              id: "dd06cd10-596b-41d0-9d6e-94e98ceaf989",
              name: "country",
              "display-name": "Country",
            },
          },
        },
      },
      { visitQuestion: true },
    );

    cy.findByPlaceholderText("Country").type("NL");

    cy.findByTestId("qb-header").icon("play").click();

    H.questionInfoButton().click();
    H.sidesheet().within(() => {
      cy.findByPlaceholderText("Add description")
        .type("This is a question")
        .blur();

      cy.wait("@updateQuestion");
      cy.wait("@cardQuery");
      cy.findByRole("tab", { name: "History" }).click();
      cy.findByText(/added a description/i);
      cy.findByTestId("question-revert-button").click();
      cy.wait("@cardQuery");

      cy.findByRole("tab", { name: "History" }).click();
      cy.findByText(/reverted to an earlier version/i, {
        timeout: 10000,
      }).should("be.visible");
    });

    cy.findByLabelText("Close").click();
    H.tableInteractive().should("contain", "NL");
  });
});