Skip to content

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

22.4 KB
Raw Blame
const { H } = cy;
import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { THIRD_COLLECTION_ID } from "e2e/support/cypress_sample_instance_data";

const { ORDERS_ID, PRODUCTS_ID } = SAMPLE_DATABASE;

const ORDERS_SCALAR_METRIC = {
  name: "Count of orders",
  type: "metric",
  description: "A metric",
  query: {
    "source-table": ORDERS_ID,
    aggregation: [["count"]],
  },
  display: "scalar",
};

describe("scenarios > question > native", () => {
  beforeEach(() => {
    cy.intercept("POST", "api/card").as("card");
    cy.intercept("POST", "api/dataset").as("dataset");
    cy.intercept("POST", "api/dataset/native").as("datasetNative");
    H.restore();
    cy.signInAsNormalUser();
  });

  it("lets you create and run a SQL question", () => {
    H.startNewNativeQuestion();
    H.NativeEditor.type("select count(*) from orders");

    runQuery();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains("18,760");
  });

  it("should suggest the currently viewed collection when saving question if the user has not recently visited a dashboard", () => {
    H.visitCollection(THIRD_COLLECTION_ID);
    H.startNewNativeQuestion({ collection_id: THIRD_COLLECTION_ID });

    H.NativeEditor.type("select count(*) from orders");

    cy.findByTestId("qb-header").within(() => {
      cy.findByText("Save").click();
    });
    cy.findByTestId("save-question-modal").within(() => {
      cy.findByLabelText(/Where do you want to save this/).should(
        "have.text",
        "Third collection",
      );
      cy.log("after selecting a dashboard, it should be the new suggestion");
      cy.findByLabelText(/Where do you want to save this/).click();
    });

    H.entityPickerModal().within(() => {
      cy.findByText("Orders in a dashboard").click();
      cy.button("Select this dashboard").click();
    });

    cy.findByTestId("save-question-modal")
      .findByLabelText(/Where do you want to save this/)
      .should("have.text", "Orders in a dashboard");

    cy.visit("/");

    H.startNewNativeQuestion();
    H.NativeEditor.type("select count(*) from orders");

    cy.findByTestId("qb-header").within(() => {
      cy.findByText("Save").click();
    });
    cy.findByTestId("save-question-modal").within(() => {
      cy.findByLabelText(/Where do you want to save this/).should(
        "have.text",
        "Orders in a dashboard",
      );

      cy.button("Cancel").click();
    });
  });

  it("displays an error", () => {
    H.startNewNativeQuestion();
    H.NativeEditor.type("select * from not_a_table");

    runQuery();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains('Table "NOT_A_TABLE" not found');
  });

  it("displays an error when running selected text and keeps the full query (metabase#16886)", () => {
    H.startNewNativeQuestion();
    H.NativeEditor.type("select * from orders");

    // move left three
    Cypress._.range(3).forEach(() => cy.realPress("ArrowLeft"));
    // highlight back to the front
    Cypress._.range(19).forEach(() => cy.realPress(["Shift", "ArrowLeft"]));
    runQuery();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains('Table "ORD" not found');

    cy.log(
      "shouldn't remove parts of the query when choosing 'Run selected text' (metabase#16886)",
    );
    const ORIGINAL_QUERY = "select 1 from orders";
    const SELECTED_TEXT = "select 1";
    H.NativeEditor.clear();
    H.NativeEditor.type(ORIGINAL_QUERY);
    cy.realPress("Home");
    Cypress._.range(SELECTED_TEXT.length).forEach(() =>
      cy.realPress(["Shift", "ArrowRight"]),
    );

    cy.findByTestId("native-query-editor-container").icon("play").click();

    cy.findByTestId("scalar-value").invoke("text").should("eq", "1");

    H.NativeEditor.get().contains(ORIGINAL_QUERY);
  });

  describe("template tags", () => {
    it("should save a required tag's default value as the parameter default", () => {
      H.startNewNativeQuestion();
      H.NativeEditor.type("select * from PRODUCTS where CATEGORY = {{cat}}");

      cy.findByTestId("sidebar-right")
        .findByText("Always require a value")
        .click();
      cy.get("input[placeholder*='Enter a default value']").type("Gizmo");
      runQuery();

      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.contains("Save").click();

      cy.findByTestId("save-question-modal").within(() => {
        cy.findByLabelText("Name").type("Products on Category");
        cy.findByText("Save").click();

        cy.wait("@card").should((xhr) => {
          const requestBody = xhr.request?.body;
          expect(requestBody?.parameters?.length).to.equal(1);
          const parameter = requestBody.parameters[0];
          expect(parameter.default).to.equal("Gizmo");
        });
      });
    });

    it("should recognize template tags and save them as parameters", () => {
      H.startNewNativeQuestion();
      H.NativeEditor.type(
        "select * from PRODUCTS where CATEGORY={{cat}} and RATING >= {{stars}}",
      );
      cy.get("input[placeholder*='Cat']").type("Gizmo");
      cy.get("input[placeholder*='Stars']").type("3");

      runQuery();
      H.assertQueryBuilderRowCount(45);

      // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
      cy.contains("Save").click();

      cy.findByTestId("save-question-modal").within(() => {
        cy.findByLabelText("Name").type("SQL Products");
        cy.findByText("Save").click();

        // parameters[] should reflect the template tags
        cy.wait("@card").then((xhr) => {
          const requestBody = xhr.request?.body;
          expect(requestBody?.parameters?.length).to.equal(2);
          cy.wrap(xhr.response.body.id).as("questionId");
        });
      });

      // Now load the question again and parameters[] should still be there
      cy.get("@questionId").then((questionId) => {
        cy.intercept("GET", `/api/card/${questionId}`).as("cardQuestion");
        cy.visit(`/question/${questionId}?cat=Gizmo&stars=3`);
        cy.wait("@cardQuestion").should((xhr) => {
          const responseBody = xhr.response?.body;
          expect(responseBody?.parameters?.length).to.equal(2);
        });
      });
    });

    describe("time grouping", () => {
      function setVariableType() {
        H.rightSidebar().findByTestId("variable-type-select").click();
        H.popover().findByText("Time grouping").click();
      }

      it("should create entries in variables sidebar, handle the required prop and reset the default value when options change", () => {
        H.startNewNativeQuestion();
        H.NativeEditor.type(
          "SELECT count(*), {{unit}} as unit FROM ORDERS GROUP BY unit",
        );
        setVariableType();

        cy.log("should show validation error when the field is not set");
        H.queryBuilderHeader()
          .button("Save")
          .should("have.attr", "data-disabled");

        H.popover().within(() => {
          cy.findByText("Orders").click();
          cy.findByText("Created At").click();
        });

        cy.log("should create entries in variables sidebar");
        H.rightSidebar()
          .findByLabelText("Parameter widget label")
          .type(" updated")
          .blur();
        H.filterWidget({ name: "Unit updated" }).should("exist");

        cy.log("should handle required prop for time grouping");
        H.rightSidebar()
          .findByLabelText("Always require a value")
          .parent()
          .click();
        H.runNativeQuery();
        cy.findByTestId("query-visualization-root").should(
          "contain",
          "You'll need to pick a value for 'Unit updated' before this query can run.",
        );

        H.rightSidebar().within(() => {
          cy.findByText("Enter a default value…").click();
        });
        H.popover().findByText("Year").click();
        H.runNativeQuery();
        cy.findByTestId("query-visualization-root").should(
          "contain",
          "January 1, 2025",
        );

        cy.log(
          "should reset default value when time grouping options are changed",
        );
        H.queryBuilderHeader().button("Save").click();
        cy.findByTestId("save-question-modal").within(() => {
          cy.findByLabelText("Name").type("Saved question with time grouping");
          cy.button("Save").click();
        });
        cy.wait("@card").then(({ response }) =>
          H.visitQuestion(response.body.id),
        );

        cy.log("open editor");
        cy.findByTestId("visibility-toggler").click();
        cy.findByTestId("native-query-editor-container")
          .icon("variable")
          .click();

        H.rightSidebar().should("contain", "Variables and parameters");

        H.rightSidebar()
          .findByText("Default parameter widget value")
          .next()
          .should("contain", "Year");
        H.rightSidebar().findByText("Time grouping options").next().click();
        H.popover().findByText("Year").click();

        cy.log("verify default value is empty");
        H.rightSidebar().should("contain", "Enter a default value…");
      });
    });
  });

  it("can save a question with no rows", () => {
    H.startNewNativeQuestion();
    H.NativeEditor.type("select * from people where false");
    runQuery();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains("No results");
    cy.icon("contract").click();
    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.contains("Save").click();

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

    // confirm that the question saved and url updated
    cy.location("pathname").should("match", /\/question\/\d+/);
  });

  it("should be able to add new columns after hiding some and recover them after a failed query (metabase#15393, metabase#16914)", () => {
    H.startNewNativeQuestion({ display: "table" });
    H.NativeEditor.type("select 1 as visible, 2 as hidden");
    cy.findByTestId("native-query-editor-container")
      .icon("play")
      .as("runQuery")
      .click();

    H.openVizSettingsSidebar();
    cy.findByTestId("sidebar-left")
      .as("sidebar")
      .within(() => {
        cy.findByTestId("draggable-item-HIDDEN")
          .icon("eye_outline")
          .click({ force: true });
      });
    H.NativeEditor.type("{movetoend}, 3 as added");
    cy.get("@runQuery").click();
    cy.get("@sidebar").contains(/added/i);

    cy.log(
      "should recover visualization settings after a failed query (metabase#16914)",
    );
    const FAILING_PIECE = " foo";
    cy.button("Done").click();

    H.NativeEditor.focus().type(FAILING_PIECE);
    H.runNativeQuery();

    H.NativeEditor.focus();
    cy.realPress("End");
    Cypress._.range(FAILING_PIECE.length).forEach(() =>
      cy.realPress(["Shift", "ArrowLeft"]),
    );
    cy.realPress("Backspace");
    H.runNativeQuery();

    cy.findByTestId("query-visualization-root").within(() => {
      cy.findByText("Every field is hidden right now").should("not.exist");
      cy.findByText("VISIBLE");
      cy.findByText("HIDDEN").should("not.exist");
    });
  });

  it("should not autorun ad-hoc native queries by default or native queries after updating a question (metabase#30165)", () => {
    H.visitQuestionAdhoc(
      {
        display: "scalar",
        dataset_query: {
          type: "native",
          native: {
            query: "SELECT 1",
          },
          database: SAMPLE_DB_ID,
        },
      },
      { autorun: false },
    );

    // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
    cy.findByText("Here's where your results will appear").should("be.visible");
    cy.get("@dataset.all").should("have.length", 0);

    cy.intercept("POST", "/api/card/*/query").as("cardQuery");
    cy.intercept("PUT", "/api/card/*").as("updateQuestion");

    H.startNewNativeQuestion();
    H.NativeEditor.type("SELECT * FROM ORDERS");
    H.saveQuestionToCollection("Q1");

    H.NativeEditor.focus().type(" WHERE TOTAL < 20");
    H.queryBuilderHeader().findByText("Save").click();
    cy.findByTestId("save-question-modal").within(() => {
      cy.findByText("Save").click();
    });
    cy.wait("@updateQuestion");

    H.NativeEditor.focus().type(" LIMIT 10");
    H.queryBuilderHeader().findByText("Save").click();
    cy.findByTestId("save-question-modal").within(() => {
      cy.findByText("Save").click();
    });
    cy.wait("@updateQuestion");

    cy.findByTestId("query-builder-main")
      .findByText("Here's where your results will appear")
      .should("be.visible");
    cy.get("@dataset.all").should("have.length", 0);
    cy.get("@cardQuery.all").should("have.length", 0);
  });

  it("should preview a query with missing and with set parameters", () => {
    H.startNewNativeQuestion();
    H.NativeEditor.type("select * from PRODUCTS where CATEGORY={{category}}");

    cy.log("should show errors when previewing a query");
    cy.button("Preview the query").click();
    cy.wait("@datasetNative");
    H.modal()
      .findByText(/missing required parameters/)
      .should("be.visible");
    cy.realPress("Escape");
    H.modal().should("not.exist");

    cy.log("should allow to preview a fully parameterized query");
    cy.findByPlaceholderText("Category").type("Gadget");
    cy.button("Preview the query").click();
    cy.wait("@datasetNative");
    H.modal().within(() => {
      H.codeMirrorValue().should("contain", "CATEGORY = 'Gadget'");
    });
  });

  it("should run the query when pressing meta+enter", () => {
    H.startNewNativeQuestion({
      query: "SELECT COUNT(*) FROM ORDERS",
    });
    H.NativeEditor.focus();

    cy.realPress([H.metaKey, "Enter"]);

    cy.wait("@dataset");

    cy.findByTestId("query-visualization-root").should("contain", "18,760");

    // make sure a new line was not inserted
    cy.get(".cm-lineNumbers").should("contain", "1").should("not.contain", "2");
  });

  it("should be possible to format the native query using the keyboard shortcut", () => {
    H.startNewNativeQuestion({
      query: "SELECT COUNT(*) FROM ORDERS",
    });
    H.NativeEditor.focus();

    cy.realPress(["Shift", H.metaKey, "f"]);

    H.NativeEditor.value().should(
      "contain",
      "SELECT\n  COUNT(*)\nFROM\n  ORDERS",
    );
  });

  it("should add tab at the end of the query and indent the selected line", () => {
    H.startNewNativeQuestion({
      query: "SELECT",
    });

    H.NativeEditor.focus();
    cy.realPress(["Tab"]);

    H.NativeEditor.get().should("have.text", "SELECT\t");

    cy.log("should indent the line when pressing tab while selected");
    H.NativeEditor.focus().type("{selectall}");
    cy.realPress(["Tab"]);

    H.NativeEditor.get().should("have.text", "\tSELECT\t");
  });

  it("should indent the next line to the same level when entering newline", () => {
    H.startNewNativeQuestion();

    H.NativeEditor.focus()
      .type("{tab}SELECT{enter}FOO")
      .get()
      .should("have.text", "\tSELECT\tFOO");
  });

  it("should be able to handle two sidebars on different screen sizes", () => {
    const questionDetails = {
      name: "13332",
      native: {
        query: "select * from PRODUCTS limit 5",
      },
    };

    function setViewport(width, height) {
      cy.viewport(width, height);
      cy.wait(100); // wait for UI to re-render to avoid flakiness
    }

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

    cy.log("open editor on a normal screen size");
    cy.findByTestId("visibility-toggler").click();

    dataReferenceSidebar()
      .should("be.visible")
      // means data is loaded
      .should("contain", "Sample Database");

    cy.findByTestId("visibility-toggler").click();
    dataReferenceSidebar().should("not.be.visible");

    cy.log("open editor on a small screen size");
    setViewport(1279, 800);

    cy.log("try to open data reference sidebar on a mid size screen");
    cy.findByTestId("visibility-toggler").click();
    H.NativeEditor.get().should("be.visible");
    dataReferenceSidebar().should("not.be.visible");

    cy.log("open visualization settings sidebar, order matters");
    cy.findByTestId("viz-type-button").click();

    cy.log("open data reference sidebar");
    cy.findByTestId("native-query-editor-action-buttons")
      .icon("reference")
      .click();

    cy.log("set small viewport");
    setViewport(800, 800);

    cy.findByTestId("sidebar-left").invoke("width").should("be.gt", 350);
    cy.findByTestId("sidebar-right").invoke("width").should("be.gt", 350);
  });
});

describe("scenarios > question > native > mongo", { tags: "@mongo" }, () => {
  const MONGO_DB_NAME = "QA Mongo";

  beforeEach(() => {
    H.restore("mongo-5");
    cy.signInAsAdmin();
  });

  it("should switch an SQL question to mongo and use two-space indentation (metabase#53299)", () => {
    H.startNewNativeQuestion();
    cy.findByTestId("gui-builder-data").click();
    cy.findByLabelText(MONGO_DB_NAME).click();
    H.nativeEditorDataSource().should("contain", MONGO_DB_NAME);

    cy.log("should insert two spaces when pressing tab in json-like languages");
    H.NativeEditor.type("{tab}");
    H.NativeEditor.get().should("be.visible").get(".cm-line").as("lines");
    cy.get("@lines").eq(0).should("have.text", "  ");

    cy.log("should use the correct indentation for mongo");
    H.NativeEditor.clear();
    H.NativeEditor.type('[{enter}{ {enter}"foo": "bar",{enter}"baz"');

    H.NativeEditor.get().should("be.visible").get(".cm-line").as("lines");

    cy.get("@lines").eq(0).should("have.text", "[");
    cy.get("@lines").eq(1).should("have.text", "  {");
    cy.get("@lines").eq(2).should("have.text", '    "foo": "bar",');
    cy.get("@lines").eq(3).should("have.text", '    "baz"');
    cy.get("@lines").eq(4).should("have.text", "  }");
    cy.get("@lines").eq(5).should("have.text", "]");
  });
});

describe("scenarios > native question > data reference sidebar", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  it("should show tables", () => {
    H.startNewNativeQuestion();
    sidebarHeaderTitle().should("have.text", "Sample Database");

    dataReferenceSidebar().within(() => {
      cy.findByText("ORDERS").click();
      cy.findByText(
        "Confirmed Sample Company orders for a product, from a user.",
      );
      cy.findByText("9 columns");
      cy.log("should not show metrics when they are not defined on the table");
      cy.findByText(/metric/).should("not.exist");
      cy.findByText("QUANTITY").click();
      cy.findByText("Number of products bought.");

      cy.log("clicking the title should navigate back");
      cy.findByText("QUANTITY").click();
      cy.findByText("ORDERS").click();
      sidebarHeaderTitle().findByText("Sample Database").click();
      cy.findByText("Data Reference");
    });
  });

  it("should show library tables grouped by the query's database and regroup them when the database changes", function () {
    const SECOND_DB_NAME = "Second database";

    H.activateToken("pro-self-hosted");
    H.addSqliteDatabase(SECOND_DB_NAME);
    H.createLibrary();

    cy.log("publish a table in each of two databases");
    H.publishTables({ table_ids: [ORDERS_ID, PRODUCTS_ID] });

    H.startNewNativeQuestion({ database: SAMPLE_DB_ID });

    cy.log("open the Library pane from the data reference main pane");
    dataReferenceSidebar().within(() => {
      sidebarHeaderTitle().findByText("Sample Database").click();
      cy.findByText("Library").click();
    });

    cy.log("the query's tables are grouped apart from the other database's");
    dataReferenceSidebar().within(() => {
      cy.findByText("In this database").should("be.visible");
      cy.findByText("Orders").should("be.visible");
      cy.findByText("Products").should("be.visible");

      cy.findByText("In other databases").should("not.exist");
    });

    cy.log("switching the query database regroups the tables");
    cy.findByTestId("gui-builder-data").click();
    H.popover().findByText(SECOND_DB_NAME).click();

    dataReferenceSidebar().within(() => {
      cy.findByText("In this database").should("exist");
      cy.findByText("No tables").should("exist");

      cy.findByText("In other databases").should("be.visible");
      cy.findByText("Orders").should("be.visible");
      cy.findByText("Products").should("be.visible");
      cy.findAllByText("Sample Database").should("have.length", 2);
    });
  });

  it("should show models", () => {
    H.createNativeQuestion(
      {
        name: "Native Products Model",
        description: "A model of the Products table",
        native: { query: "select id as renamed_id from products" },
        type: "model",
      },
      { visitQuestion: true },
    );
    // Move question to personal collection
    H.openQuestionActions();
    H.popover().findByTestId("move-button").click();

    H.pickEntity({
      path: ["Bobby Tables's Personal Collection"],
      select: true,
    });

    H.startNewNativeQuestion();

    dataReferenceSidebar().within(() => {
      cy.findByText("2 models in 2 collections");
      cy.findByText("Bobby Tables's Personal Collection").click(); // collection
      cy.findByText("Native Products Model").click();
      cy.findByText("A model of the Products table"); // description
      cy.findByText("1 column");
      cy.findByText("RENAMED_ID").click();
      cy.findByText("No description");
    });
  });

  describe("metrics", () => {
    it("should show metrics defined on tables", () => {
      H.createQuestion(ORDERS_SCALAR_METRIC);

      H.startNewNativeQuestion();
      sidebarHeaderTitle().should("have.text", "Sample Database");

      dataReferenceSidebar().within(() => {
        cy.findByText("ORDERS").click();
        cy.findByText("1 metric").should("be.visible");

        cy.findByText("Count of orders").should("be.visible").click();
        cy.findByText("A metric").should("be.visible");

        cy.log("clicking the title should navigate back");
        cy.findByText("Count of orders").should("be.visible").click();
        cy.findByText("1 metric").should("be.visible");
      });
    });
  });
});

function sidebarHeaderTitle() {
  return cy.findByTestId("sidebar-header-title");
}

function dataReferenceSidebar() {
  return cy.findByTestId("sidebar-right");
}

const runQuery = () => {
  cy.findByTestId("native-query-editor-container").within(() => {
    cy.button("Get Answer").click();
  });
  cy.wait("@dataset");
};