The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
const { H } = cy;
import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
import { FIRST_COLLECTION_ID } from "e2e/support/cypress_sample_instance_data";
import { FIXTURE_PATH, VALID_CSV_FILES } from "e2e/support/helpers";
describe("CSV Uploading", { tags: ["@external", "@actions"] }, () => {
beforeEach(() => {
cy.intercept("POST", "/api/dataset").as("dataset");
});
it("Can upload a CSV file to an empty postgres schema", () => {
const testFile = VALID_CSV_FILES[0];
const EMPTY_SCHEMA_NAME = "empty_uploads";
cy.intercept("PUT", "/api/setting/*").as("saveSettings");
cy.intercept("GET", "/api/database").as("databaseList");
H.restore("postgres-writable");
cy.signInAsAdmin();
H.queryWritableDB(
"DROP SCHEMA IF EXISTS empty_uploads CASCADE;",
"postgres",
);
H.queryWritableDB("CREATE SCHEMA IF NOT EXISTS empty_uploads;", "postgres");
// create a table because H.resyncDatabase has a check relying on tables count > 0
H.queryWritableDB("CREATE TABLE empty_uploads.empty_table ();", "postgres");
// Make sure to resync the db because otherwise "public" schema sometimes is there but sometimes is not
H.resyncDatabase({ dbId: WRITABLE_DB_ID });
cy.request("POST", "/api/collection", {
name: "Uploads Collection",
parent_id: null,
}).then(({ body: { id: collectionId } }) => {
cy.wrap(collectionId).as("collectionId");
});
cy.visit("/admin/settings/uploads");
cy.findByTestId("loading-indicator").should("not.exist");
cy.findByLabelText("Upload Settings Form")
.findByPlaceholderText("Select a database")
.click();
H.popover().findByText("Writable Postgres12").click();
cy.findByLabelText("Upload Settings Form")
.findByPlaceholderText("Select a schema")
.click();
H.popover().findByText(EMPTY_SCHEMA_NAME).click();
cy.findByLabelText("Upload Settings Form").button("Enable uploads").click();
cy.wait(["@saveSettings", "@databaseList"]);
uploadFileToCollection(testFile);
const tableQuery = `SELECT * FROM information_schema.tables WHERE table_name LIKE '%${testFile.tableName}_%' ORDER BY table_name DESC LIMIT 1;`;
H.queryWritableDB(tableQuery, "postgres").then((result) => {
expect(result.rows.length).to.equal(1);
const tableName = result.rows[0].table_name;
H.queryWritableDB(
`SELECT count(*) FROM ${EMPTY_SCHEMA_NAME}.${tableName};`,
"postgres",
).then((result) => {
expect(Number(result.rows[0].count)).to.equal(testFile.rowCount);
});
});
cy.log(
"Ensure that table is visible in admin without refreshing (metabase#38041)",
);
H.goToAdmin();
cy.findByRole("link", { name: "Table Metadata" }).click();
H.DataModel.TablePicker.getDatabase("Writable Postgres12").click();
H.DataModel.TablePicker.getTables().should("have.length", 2);
H.DataModel.TablePicker.getTable("Dog Breeds").should("be.visible");
});
["postgres", "mysql"].forEach((dialect) => {
describe(`CSV Uploading (${dialect})`, () => {
beforeEach(() => {
H.restore(`${dialect}-writable`);
H.resetSnowplow();
cy.signInAsAdmin();
H.enableTracking();
cy.request("POST", "/api/collection", {
name: "Uploads Collection",
parent_id: null,
}).then(({ body: { id: collectionId } }) => {
cy.wrap(collectionId).as("collectionId");
});
H.enableUploads(dialect);
});
afterEach(() => {
H.expectNoBadSnowplowEvents();
});
// VALID_CSV_FILES[0] is uploaded and checked by the append/replace test below
VALID_CSV_FILES.slice(1).forEach((testFile) => {
it(`Can upload ${testFile.fileName} to a collection`, () => {
uploadFileToCollection(testFile);
H.expectUnstructuredSnowplowEvent({
event: "csv_upload_successful",
});
assertUploadedRowCount({
dialect,
testFile,
rowCount: testFile.rowCount,
});
});
});
H.INVALID_CSV_FILES.forEach((testFile) => {
it(`Cannot upload ${testFile.fileName} to a collection`, () => {
uploadFileToCollection(testFile);
H.expectUnstructuredSnowplowEvent({
event: "csv_upload_failed",
});
const tableQuery = `SELECT * FROM information_schema.tables WHERE table_name LIKE '%${testFile.tableName}_%' ORDER BY table_name DESC LIMIT 1;`;
H.queryWritableDB(tableQuery, dialect).then((result) => {
expect(result.rows.length).to.equal(0);
});
cy.log("metabase#55382");
closeUploadErrorDetails();
cy.intercept("PUT", "/api/collection/*").as("trashCollection");
H.openCollectionMenu();
H.popover().findByText("Move to trash").click();
H.modal().button("Move to trash").click();
cy.wait("@trashCollection");
cy.findByTestId("toast-undo").should("contain", "Trashed collection");
cy.findByRole("dialog", { name: "Upload error details" }).should(
"not.exist",
);
});
});
it("Can upload a CSV to a collection, then append and replace data in the table, but not with a different schema", () => {
const { rowCount } = VALID_CSV_FILES[0];
uploadFileToCollection(VALID_CSV_FILES[0]);
H.expectUnstructuredSnowplowEvent({
event: "csv_upload_successful",
});
assertUploadedRowCount({
dialect,
testFile: VALID_CSV_FILES[0],
rowCount,
});
cy.findByTestId("view-footer").findByText(`Showing ${rowCount} rows`);
cy.log("append with an identical schema");
uploadToExisting({
testFile: VALID_CSV_FILES[0],
uploadMode: "append",
});
cy.findByTestId("view-footer").findByText(
`Showing ${rowCount * 2} rows`,
);
cy.log("replace with an identical schema");
uploadToExisting({
testFile: VALID_CSV_FILES[0],
uploadMode: "replace",
});
cy.findByTestId("view-footer").findByText(`Showing ${rowCount} rows`);
cy.log("append with a different schema");
uploadToExisting({
testFile: VALID_CSV_FILES[1],
identicalSchema: false,
uploadMode: "append",
});
closeUploadErrorDetails();
cy.log("replace with a different schema");
uploadToExisting({
testFile: VALID_CSV_FILES[1],
identicalSchema: false,
uploadMode: "replace",
});
closeUploadErrorDetails();
cy.log("rejected uploads leave the table unchanged");
assertUploadedRowCount({
dialect,
testFile: VALID_CSV_FILES[0],
rowCount,
});
});
});
});
it("should allow you to choose a model to append to if there are multiple (metabase#53824)", () => {
H.restore("postgres-writable");
cy.signInAsAdmin();
H.enableUploads("postgres");
H.headlessUpload(FIRST_COLLECTION_ID, VALID_CSV_FILES[0]);
H.headlessUpload(FIRST_COLLECTION_ID, VALID_CSV_FILES[1]);
H.visitCollection(FIRST_COLLECTION_ID);
cy.fixture(`${FIXTURE_PATH}/${VALID_CSV_FILES[2].fileName}`).then(
(file) => {
cy.get("#upload-input").selectFile(
{
contents: Cypress.Buffer.from(file),
fileName: VALID_CSV_FILES[2].fileName,
mimeType: "text/csv",
},
{ force: true },
);
},
);
cy.findByRole("radio", { name: /Append to a model/ }).click();
cy.findByRole("textbox", { name: "Select a model" })
.should("contain.value", VALID_CSV_FILES[1].humanName)
.click();
H.popover().findByText(VALID_CSV_FILES[0].humanName).click();
cy.findByRole("textbox", { name: "Select a model" }).should(
"have.value",
VALID_CSV_FILES[0].humanName,
);
});
});
describe("Upload Table Cleanup/Management", { tags: "@external" }, () => {
beforeEach(() => {
cy.intercept("GET", "/api/ee/upload-management/tables").as(
"getUploadTables",
);
H.restore("postgres-12");
cy.signInAsAdmin();
H.enableUploads("postgres");
H.activateToken("pro-self-hosted");
});
it("should allow a user to delete an upload table", () => {
H.headlessUpload(FIRST_COLLECTION_ID, VALID_CSV_FILES[0]);
H.headlessUpload(FIRST_COLLECTION_ID, VALID_CSV_FILES[0]);
H.headlessUpload(FIRST_COLLECTION_ID, VALID_CSV_FILES[0]);
H.headlessUpload(FIRST_COLLECTION_ID, VALID_CSV_FILES[1]);
H.headlessUpload(FIRST_COLLECTION_ID, VALID_CSV_FILES[1]);
waitForActiveUploadTables(5);
cy.visit("/admin/settings/uploads");
cy.wait("@getUploadTables");
// Re-query the container fresh on each assertion instead of caching it via
// `within`: the table re-renders when `getUploadTables` resolves, detaching
// the captured node, and a retrying query against a detached subtree gets
// stuck on the intermediate render.
cy.findByTestId("upload-tables-table")
.findAllByText(/dog_breeds/i)
.should("have.length", 3);
cy.findByTestId("upload-tables-table")
.findAllByText(/star_wars_characters/i)
.should("have.length", 2);
// single delete
cy.findByTestId("upload-tables-table")
.findAllByLabelText("trash icon")
.first()
.click();
H.modal().button("Delete").click();
cy.wait("@getUploadTables");
cy.findByTestId("undo-list").findByText(/1 table deleted/i);
cy.findByTestId("upload-tables-table")
.findAllByText(/dog_breeds/i)
.should("have.length", 2);
cy.findByTestId("upload-tables-table")
.findAllByText(/star_wars_characters/i)
.should("have.length", 2);
// multiple delete: pick one row of each table so the counts below follow
// from the selection rather than from row order
cy.findByTestId("upload-tables-table")
.contains("tr", /dog_breeds/i)
.findByRole("checkbox")
.click();
cy.findByTestId("upload-tables-table")
.contains("tr", /star_wars_characters/i)
.findByRole("checkbox")
.click();
cy.findByTestId("toast-card").button("Delete").click();
H.modal().button("Delete").click();
cy.wait("@getUploadTables");
cy.findByTestId("undo-list").findByText(/2 tables deleted/i);
cy.findByTestId("upload-tables-table")
.findAllByText(/dog_breeds/i)
.should("have.length", 1);
cy.findByTestId("upload-tables-table")
.findAllByText(/star_wars_characters/i)
.should("have.length", 1);
});
});
/**
* The sync `H.restore` kicks off can still be running when the first upload creates its table: the
* sync listed the warehouse's tables before that table existed, so it retires the table it does not
* recognise (`active=false`), and `/tables` — which only returns active tables — never lists it
* (flake: found 2 dog_breeds rows, expected 3). A later sync does see the table in the warehouse and
* reactivates it, so sync again until every uploaded table is back.
*/
function waitForActiveUploadTables(expectedCount, iteration = 0) {
if (iteration === 10) {
throw new Error(
`Fewer than ${expectedCount} upload tables are active. Something is wrong.`,
);
}
cy.request("GET", "/api/ee/upload-management/tables").then(({ body }) => {
if (body.length >= expectedCount) {
return;
}
cy.request("POST", `/api/database/${WRITABLE_DB_ID}/sync_schema`);
cy.wait(1000);
waitForActiveUploadTables(expectedCount, iteration + 1);
});
}
function uploadFileToCollection(testFile, viewModel = true) {
cy.get("@collectionId").then((collectionId) =>
cy.visit(`/collection/${collectionId}`),
);
H.uploadFile("#upload-input", "Uploads Collection", testFile);
if (testFile.valid && viewModel) {
cy.get("main").within(() => cy.findByText("Uploads Collection"));
cy.findByTestId("collection-table").within(() => {
cy.findByText(testFile.humanName);
});
cy.findByTestId("status-root-container")
.findByText("Start exploring")
.click();
cy.wait("@dataset");
cy.url().should("include", "/model/");
H.tableInteractive();
}
}
function closeUploadErrorDetails() {
cy.findByRole("dialog", { name: "Upload error details" })
.findByRole("button", { name: "Close" })
.click();
cy.findByRole("dialog", { name: "Upload error details" }).should("not.exist");
}
function assertUploadedRowCount({ dialect, testFile, rowCount }) {
const tableQuery = `SELECT * FROM information_schema.tables WHERE table_name LIKE '%${testFile.tableName}_%' ORDER BY table_name DESC LIMIT 1;`;
H.queryWritableDB(tableQuery, dialect).then((result) => {
expect(result.rows.length).to.equal(1);
const tableName = result.rows[0].table_name ?? result.rows[0].TABLE_NAME;
H.queryWritableDB(
`SELECT count(*) as count FROM ${tableName};`,
dialect,
).then((result) => {
expect(Number(result.rows[0].count)).to.equal(rowCount);
});
});
}
function uploadToExisting({
testFile,
identicalSchema = true,
uploadMode = "append",
}) {
cy.intercept("POST", "/api/table/*/append-csv").as("appendCSV");
cy.intercept("POST", "/api/table/*/replace-csv").as("replaceCSV");
// assumes we're already looking at an uploadable model page
cy.findByTestId("qb-header").icon("upload").click();
const uploadOptions = {
append: "Append data to this model",
replace: "Replace all data in this model",
};
const uploadEndpoints = {
append: "@appendCSV",
replace: "@replaceCSV",
};
H.popover().findByText(uploadOptions[uploadMode]).click();
cy.fixture(`${FIXTURE_PATH}/${testFile.fileName}`).then((file) => {
cy.get("#upload-file-input").selectFile(
{
contents: Cypress.Buffer.from(file),
fileName: testFile.fileName,
mimeType: "text/csv",
},
{ force: true },
);
});
if (identicalSchema) {
cy.findByTestId("status-root-container")
.should("contain", "Uploading data to")
.and("contain", testFile.fileName);
cy.wait(uploadEndpoints[uploadMode]);
// eslint-disable-next-line metabase/no-unsafe-element-filtering
cy.findAllByRole("status")
.last()
.findByText(/Data (added|replaced)/i, {
timeout: 10 * 1000,
});
} else {
cy.wait(uploadEndpoints[uploadMode]);
cy.findByTestId("status-root-container").findByText(
"Error uploading your file",
);
H.modal().findByText("Upload error details");
}
}