Skip to content

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

Clean table urls (#75079)

Romeo Van Snick1d04c71315d0
diff --git a/e2e/test/scenarios/detail-view/detail-view.cy.spec.ts b/e2e/test/scenarios/detail-view/detail-view.cy.spec.ts
index b51f6d4a85f..93c198a0618 100644
--- a/e2e/test/scenarios/detail-view/detail-view.cy.spec.ts
+++ b/e2e/test/scenarios/detail-view/detail-view.cy.spec.ts
@@ -35,11 +35,7 @@ describe("detail view", () => {
.and("have.attr", "href", `/browse/databases/${SAMPLE_DB_ID}`);
cy.findByRole("link", { name: "Products" })
.should("be.visible")
- .and(
- "have.attr",
- "href",
- `/question#?db=${SAMPLE_DB_ID}&table=${PRODUCTS_ID}`,
- );
+ .and("have.attr", "href", `/table/${PRODUCTS_ID}-products`);
cy.findByText("Rustic Paper Wallet").should("be.visible");
});
diff --git a/e2e/test/scenarios/onboarding/home/browse.cy.spec.ts b/e2e/test/scenarios/onboarding/home/browse.cy.spec.ts
index f74e20f12b1..4b117e5aff3 100644
--- a/e2e/test/scenarios/onboarding/home/browse.cy.spec.ts
+++ b/e2e/test/scenarios/onboarding/home/browse.cy.spec.ts
@@ -98,6 +98,30 @@ describe("scenarios > browse", () => {
});
});
+ it("opens a table at a clean /table/:slug URL that falls back to /question on edit", () => {
+ cy.visit("/");
+ H.browseDatabases().click();
+ cy.findByRole("heading", { name: "Sample Database" }).click();
+ cy.findByRole("heading", { name: "Products" }).click();
+
+ cy.log("a pristine table view keeps the canonical /table/:slug URL");
+ cy.findByRole("button", { name: /Summarize/ }).should("be.visible");
+ cy.location("pathname").should("eq", `/table/${PRODUCTS_ID}-products`);
+
+ cy.log("the clean URL survives a reload");
+ cy.reload();
+ cy.findByRole("button", { name: /Summarize/ }).should("be.visible");
+ cy.location("pathname").should("eq", `/table/${PRODUCTS_ID}-products`);
+
+ cy.log("editing the question falls back to the ad-hoc /question#hash form");
+ H.tableHeaderClick("Category");
+ H.popover()
+ .findByTestId("click-actions-sort-control-sort.ascending")
+ .click();
+ cy.location("pathname").should("eq", "/question");
+ cy.location("hash").should("not.be.empty");
+ });
+
it("can generate x-ray dashboard from a browse page", () => {
cy.visit(`/browse/databases/${SAMPLE_DB_ID}`);
diff --git a/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsx b/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsx
index 3138c9c1486..b3da0bc4f23 100644
--- a/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsx
+++ b/frontend/src/metabase/browse/tables/TableBrowser/TableBrowser.tsx
@@ -13,7 +13,11 @@ import * as Urls from "metabase/urls";
import { isSyncInProgress } from "metabase/utils/syncing";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import { SAVED_QUESTIONS_VIRTUAL_DB_ID } from "metabase-lib/v1/metadata/utils/saved-questions";
-import type { DatabaseId, Table } from "metabase-types/api";
+import {
+ type DatabaseId,
+ type Table,
+ isConcreteTableId,
+} from "metabase-types/api";
import { RELOAD_INTERVAL } from "../../constants";
@@ -57,9 +61,14 @@ const getSchemaName = (props: TableBrowserContainerProps): string | undefined =>
props.schemaName || props.params?.schemaName || undefined;
export const getTableUrl = (table: Table, metadata?: Metadata): string => {
- const metadataTable = metadata?.table(table.id);
- const question = metadataTable?.newQuestion();
- return question ? Urls.question(question) : "";
+ // The Saved Questions virtual database exposes cards as "tables" with virtual
+ // ids (e.g. card__17). Those have no /table/:slug route, so fall back to the
+ // ad-hoc question URL for them.
+ if (!isConcreteTableId(table.id)) {
+ const question = metadata?.table(table.id)?.newQuestion();
+ return question ? Urls.question(question) : "";
+ }
+ return Urls.table({ id: table.id, name: table.display_name });
};
export const TableBrowser = (props: TableBrowserContainerProps) => {
diff --git a/frontend/src/metabase/detail-view/components/Nav/TableNav.tsx b/frontend/src/metabase/detail-view/components/Nav/TableNav.tsx
index 6e5d47ce07b..cddc7902989 100644
--- a/frontend/src/metabase/detail-view/components/Nav/TableNav.tsx
+++ b/frontend/src/metabase/detail-view/components/Nav/TableNav.tsx
@@ -3,7 +3,7 @@ import type { ReactNode } from "react";
import { skipToken, useListDatabaseSchemasQuery } from "metabase/api";
import { Group, type GroupProps } from "metabase/ui";
import * as Urls from "metabase/urls";
-import type { Table } from "metabase-types/api";
+import { type Table, isConcreteTableId } from "metabase-types/api";
import { Breadcrumb } from "./Breadcrumb";
import { Separator } from "./Separator";
@@ -43,7 +43,13 @@ export const TableNav = ({ rowName, table, ...props }: Props) => {
<Separator />
- <Breadcrumb href={Urls.tableRowsQuery(table.db_id, table.id)}>
+ <Breadcrumb
+ href={
+ isConcreteTableId(table.id)
+ ? Urls.table({ id: table.id, name: table.display_name })
+ : Urls.tableRowsQuery(table.db_id, table.id)
+ }
+ >
{table.display_name}
</Breadcrumb>
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
index d3c914e4b13..370ce810c4e 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
@@ -379,7 +379,7 @@ const TableSourceRow = ({
location={location}
messageId={messageId}
source={{ source_id: id, source_type: "table" }}
- to={Urls.tableRowsQuery(table.db_id, id)}
+ to={Urls.table({ id, name: table.display_name })}
/>
);
};
@@ -595,7 +595,7 @@ const NativeSourcesRow = ({
location={location}
messageId={messageId}
source={{ source_id: table.id, source_type: "table" }}
- to={Urls.tableRowsQuery(databaseId, table.id)}
+ to={Urls.table({ id: table.id, name: label })}
/>
);
})}
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx
index 0e1223959e0..88dde596c41 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx
@@ -380,7 +380,7 @@ describe("MetabotAgentDataSourcePills", () => {
const sourceLink = await screen.findByRole("link", { name: "Orders" });
- expect(sourceLink).toHaveAttribute("href", "/question#?db=1&table=2");
+ expect(sourceLink).toHaveAttribute("href", "/table/2-orders");
expect(
screen.queryByLabelText("Source is correct"),
).not.toBeInTheDocument();
diff --git a/frontend/src/metabase/metrics/urls.ts b/frontend/src/metabase/metrics/urls.ts
index 55e6da391c8..9649ab03d9d 100644
--- a/frontend/src/metabase/metrics/urls.ts
+++ b/frontend/src/metabase/metrics/urls.ts
@@ -1,4 +1,5 @@
import * as Urls from "metabase/urls";
+import { isConcreteTableId } from "metabase-types/api";
import type { MetricUrls } from "./types";
@@ -9,5 +10,8 @@ export const metricUrls: MetricUrls = {
dependencies: Urls.metricDependencies,
history: Urls.metricHistory,
database: (id) => Urls.browseDatabase({ id }),
- table: (databaseId, tableId) => Urls.tableRowsQuery(databaseId, tableId),
+ table: (databaseId, tableId) =>
+ isConcreteTableId(tableId)
+ ? Urls.table({ id: tableId })
+ : Urls.tableRowsQuery(databaseId, tableId),
};
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index a461acdf57a..2c08f06c6ef 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -15,7 +15,7 @@ import {
import { loadMetadataForCard } from "metabase/questions/actions";
import { setErrorPage } from "metabase/redux/app";
import type { DispatchFn } from "metabase/redux/hooks";
-import { updateMetadata } from "metabase/redux/metadata";
+import { fetchTableMetadata, updateMetadata } from "metabase/redux/metadata";
import { INITIALIZE_QB, resetQB } from "metabase/redux/query-builder";
import type {
Dispatch,
@@ -287,12 +287,35 @@ async function handleQBInit(
dispatch(cancelQuery());
const queryParams = location.query;
- const cardId = Urls.extractEntityId(params.slug);
+ const isTableRoute = location.pathname?.startsWith("/table");
+ const slugEntityId = Urls.extractEntityId(params.slug);
+ // On the /table/:slug route the slug identifies a table, not a saved card.
+ const cardId = isTableRoute ? undefined : slugEntityId;
const uiControls: UIControls = getQueryBuilderModeFromLocation(location);
- const { options, serializedCard } = parseHash(location.hash);
- const hasCard = cardId || serializedCard;
+ let { options, serializedCard } = parseHash(location.hash);
const currentUser = getUser(getState());
+ if (isTableRoute && slugEntityId != null) {
+ await dispatch(fetchTableMetadata(slugEntityId));
+ if (isStale()) {
+ return;
+ }
+ const table = getMetadata(getState()).table(slugEntityId);
+ if (!table) {
+ dispatch(setErrorPage(NOT_FOUND_ERROR));
+ return;
+ }
+ // The /table URL only carries the table id; resolve its db so the QB can
+ // build the table's default ad-hoc question, just like `?db=&table=`.
+ options = {
+ ...options,
+ db: String(table.db_id),
+ table: String(slugEntityId),
+ };
+ }
+
+ const hasCard = cardId || serializedCard;
+
if (uiControls.queryBuilderMode === "notebook") {
if (!canUserCreateQueries(getState())) {
dispatch(replace(Urls.unauthorized()));
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
index b5cdf0d24ab..425cfd7ccaa 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
@@ -915,4 +915,55 @@ describe("QB Actions > initializeQB", () => {
expect(result.uiControls.isShowingNewbModal).toBeFalsy();
});
});
+
+ describe("table route (/table/:slug)", () => {
+ function setupTableRoute(
+ tableId: TableId,
+ opts: Omit<BaseSetupOpts, "location" | "params"> = {},
+ ) {
+ const slug = `${tableId}-orders`;
+ const location: LocationDescriptorObject = {
+ pathname: `/table/${slug}`,
+ hash: "",
+ query: {},
+ };
+ return baseSetup({ location, params: { slug }, ...opts });
+ }
+
+ it("builds the table's default ad-hoc question from the slug", async () => {
+ const { result, metadata } = await setupTableRoute(ORDERS_ID);
+ const expectedCard = checkNotNull(
+ metadata.table(ORDERS_ID)?.question().card(),
+ );
+
+ expect(
+ Lib.areLegacyQueriesEqual(
+ result.card.dataset_query,
+ expectedCard.dataset_query,
+ ),
+ ).toBe(true);
+ expect(result.originalCard).toBeUndefined();
+ });
+
+ it("treats the slug as a table, not a saved card (does not load a card)", async () => {
+ const loadCardSpy = jest.spyOn(cardActions, "loadCard");
+ await setupTableRoute(ORDERS_ID);
+ expect(loadCardSpy).not.toHaveBeenCalled();
+ });
+
+ it("renders an unsaved (ad-hoc) question", async () => {
+ const { result } = await setupTableRoute(ORDERS_ID);
+ expect(result.card.id).toBeUndefined();
+ expect(result.card.displayIsLocked).toBeFalsy();
+ });
+
+ it("shows a not-found error for an unknown table", async () => {
+ const { dispatch } = await setupTableRoute(999999);
+ expect(dispatch).toHaveBeenCalledWith(
+ setErrorPage(
+ expect.objectContaining({ data: { error_code: "not-found" } }),
+ ),
+ );
+ });
+ });
});
diff --git a/frontend/src/metabase/query_builder/actions/url.ts b/frontend/src/metabase/query_builder/actions/url.ts
index 26c33e02210..443adc95188 100644
--- a/frontend/src/metabase/query_builder/actions/url.ts
+++ b/frontend/src/metabase/query_builder/actions/url.ts
@@ -3,6 +3,7 @@ import { parse as parseUrl } from "url";
import type { LocationDescriptor } from "history";
import { push, replace } from "react-router-redux";
+import api from "metabase/api/legacy-client";
import { isEqualCard } from "metabase/common/utils/card";
import { createThunkAction } from "metabase/redux";
import * as Lib from "metabase-lib";
@@ -21,6 +22,7 @@ import { getQueryBuilderModeFromLocation } from "../typed-utils";
import {
getCurrentQueryParams,
getPathNameFromQueryBuilderMode,
+ getTableUrlForPristineQuestion,
getURLForCardState,
} from "../utils";
@@ -90,7 +92,21 @@ export const updateUrl = createThunkAction(
const { currentState } = getState().qb;
const queryParams = preserveParameters ? getCurrentQueryParams() : {};
- const url = getURLForCardState(newState, dirty, queryParams, objectId);
+ // While we're on the /table/:slug route and the question is still the
+ // pristine default view of that table, keep the canonical /table URL.
+ // Any edit falls through to /question#hash and stays there — we don't
+ // convert a /question entry point into /table.
+ // Compare against the basename-aware path so this still works under
+ // subpath deployments (e.g. /mb/table/...).
+ const isOnTableRoute = window.location.pathname.startsWith(
+ `${api.basename}/table/`,
+ );
+ const tableUrl =
+ isOnTableRoute && objectId == null && queryBuilderMode === "view"
+ ? getTableUrlForPristineQuestion(question)
+ : null;
+ const url =
+ tableUrl ?? getURLForCardState(newState, dirty, queryParams, objectId);
const urlParsed = parseUrl(url);
const locationDescriptor: LocationDescriptor = {
diff --git a/frontend/src/metabase/query_builder/utils/index.ts b/frontend/src/metabase/query_builder/utils/index.ts
index 5a6c38bc104..7342f7ce31a 100644
--- a/frontend/src/metabase/query_builder/utils/index.ts
+++ b/frontend/src/metabase/query_builder/utils/index.ts
@@ -66,6 +66,51 @@ export function getURLForCardState(
return Urls.card(card, options);
}
+/**
+ * The clean `/table/:slug` URL (e.g. /table/2-orders) for a question that is
+ * still the pristine, unmodified default view of a table — otherwise `null`.
+ *
+ * This is what lets the QB show the canonical table URL on entry and fall back
+ * to the `/question#<hash>` form (via {@link getURLForCardState}) the moment the
+ * question is edited away from the table's default.
+ */
+export function getTableUrlForPristineQuestion(
+ question: Question,
+): string | null {
+ if (question.isSaved()) {
+ return null;
+ }
+
+ const query = question.query();
+ const { isNative } = Lib.queryDisplayInfo(query);
+ if (isNative || Lib.stageCount(query) !== 1) {
+ return null;
+ }
+
+ // A card source (`card__123`) is a string id; only a real table qualifies.
+ const sourceTableId = Lib.sourceTableOrCardId(query);
+ if (typeof sourceTableId !== "number") {
+ return null;
+ }
+
+ const table = question.metadata().table(sourceTableId);
+ if (!table) {
+ return null;
+ }
+
+ const card = question.card();
+ const defaultCard = table.newQuestion().card();
+ const isPristine =
+ Lib.areLegacyQueriesEqual(card.dataset_query, defaultCard.dataset_query) &&
+ card.display === defaultCard.display &&
+ _.isEmpty(card.visualization_settings) &&
+ question.parameters().length === 0;
+
+ return isPristine
+ ? Urls.table({ id: sourceTableId, name: table.display_name })
+ : null;
+}
+
export const isNavigationAllowed = ({
destination,
question,
diff --git a/frontend/src/metabase/query_builder/utils/utils.unit.spec.ts b/frontend/src/metabase/query_builder/utils/utils.unit.spec.ts
index 0e6ca43ee39..da59ae727c1 100644
--- a/frontend/src/metabase/query_builder/utils/utils.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/utils/utils.unit.spec.ts
@@ -3,14 +3,20 @@ import { getNextId } from "__support__/utils";
import { serializeCardForUrl } from "metabase/common/utils/card";
import { createMockLocation } from "metabase/redux/store/mocks";
import { checkNotNull } from "metabase/utils/types";
+import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
import type { Card } from "metabase-types/api";
import {
createMockCard,
createMockNativeDatasetQuery,
} from "metabase-types/api/mocks";
+import {
+ ORDERS_ID,
+ PRODUCTS_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
-import { isNavigationAllowed } from ".";
+import { getTableUrlForPristineQuestion, isNavigationAllowed } from ".";
const structuredCard = createMockCard({
id: getNextId(),
@@ -656,3 +662,57 @@ describe("isNavigationAllowed", () => {
});
});
});
+
+describe("getTableUrlForPristineQuestion", () => {
+ const tableMetadata = createMockMetadata({
+ databases: [createSampleDatabase()],
+ });
+
+ const pristineOrders = checkNotNull(
+ tableMetadata.table(ORDERS_ID),
+ ).newQuestion();
+
+ it("returns the /table/:slug URL for a table's pristine default question", () => {
+ expect(getTableUrlForPristineQuestion(pristineOrders)).toBe(
+ "/table/2-orders",
+ );
+ expect(
+ getTableUrlForPristineQuestion(
+ checkNotNull(tableMetadata.table(PRODUCTS_ID)).newQuestion(),
+ ),
+ ).toBe("/table/1-products");
+ });
+
+ it("returns null once the query is modified", () => {
+ const withLimit = pristineOrders.setQuery(
+ Lib.limit(pristineOrders.query(), -1, 10),
+ );
+ expect(getTableUrlForPristineQuestion(withLimit)).toBeNull();
+ });
+
+ it("returns null when the display is changed", () => {
+ expect(
+ getTableUrlForPristineQuestion(pristineOrders.setDisplay("bar")),
+ ).toBeNull();
+ });
+
+ it("returns null when visualization settings are set", () => {
+ const withSettings = pristineOrders.setCard({
+ ...pristineOrders.card(),
+ visualization_settings: { "table.pivot": true },
+ });
+ expect(getTableUrlForPristineQuestion(withSettings)).toBeNull();
+ });
+
+ it("returns null for a saved question", () => {
+ expect(getTableUrlForPristineQuestion(pristineOrders.setId(1))).toBeNull();
+ });
+
+ it("returns null for a native question", () => {
+ const native = pristineOrders.setCard({
+ ...pristineOrders.card(),
+ dataset_query: createMockNativeDatasetQuery(),
+ });
+ expect(getTableUrlForPristineQuestion(native)).toBeNull();
+ });
+});
diff --git a/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/utils.ts b/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/utils.ts
index 86aa26a77ab..ec8db7a51bd 100644
--- a/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/utils.ts
+++ b/frontend/src/metabase/querying/notebook/components/NotebookDataPicker/utils.ts
@@ -1,5 +1,6 @@
import * as Urls from "metabase/urls";
import * as Lib from "metabase-lib";
+import { isConcreteTableId } from "metabase-types/api";
type Props = {
query: Lib.Query;
@@ -32,6 +33,8 @@ export const getUrl = ({
};
return isModel ? Urls.model(payload) : Urls.card(payload);
+ } else if (isConcreteTableId(tableId)) {
+ return Urls.table({ id: tableId, name: tableInfo.displayName });
} else {
return Urls.tableRowsQuery(databaseId, tableId);
}
diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsx
index 0dde55cc732..494f919c614 100644
--- a/frontend/src/metabase/routes.jsx
+++ b/frontend/src/metabase/routes.jsx
@@ -323,6 +323,7 @@ export const getRoutes = (store) => {
<Route path="explore" component={MetricsViewerPage} />
<Route path="table">
+ <Route path=":slug" component={QueryBuilder} />
<Route path=":tableId/detail/:rowId" component={TableDetailPage} />
</Route>
diff --git a/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx b/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx
index 99cb78100a5..3b8103a904d 100644
--- a/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx
+++ b/frontend/src/metabase/search/components/InfoText/InfoText.unit.spec.tsx
@@ -144,7 +144,7 @@ describe("InfoText", () => {
const tableLink = screen.getByText(MOCK_TABLE.display_name);
expect(tableLink).toHaveAttribute(
"href",
- `/question#?db=${MOCK_DATABASE.id}&table=${MOCK_TABLE.id}`,
+ `/table/${MOCK_TABLE.id}-table-name`,
);
expect(screen.getByTestId("revision-history-text")).toHaveTextContent(
diff --git a/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx b/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx
index 97651bdb5fa..84d77c4df51 100644
--- a/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx
+++ b/frontend/src/metabase/search/components/InfoText/InfoTextAssetLink.tsx
@@ -3,9 +3,14 @@ import { t } from "ttag";
import { useDatabaseQuery, useTableQuery } from "metabase/common/hooks";
import { SearchResultLink } from "metabase/search/components/SearchResultLink";
import { Box, Icon, Text } from "metabase/ui";
-import { browseDatabase, browseSchema, tableRowsQuery } from "metabase/urls";
+import {
+ browseDatabase,
+ browseSchema,
+ tableRowsQuery,
+ table as tableUrl,
+} from "metabase/urls";
import type Database from "metabase-lib/v1/metadata/Database";
-import type { SearchResult } from "metabase-types/api";
+import { type SearchResult, isConcreteTableId } from "metabase-types/api";
import type { InfoTextData } from "./get-info-text";
import { getInfoText } from "./get-info-text";
@@ -51,7 +56,9 @@ export const InfoTextTableLink = ({
return <LoadingText />;
}
- const link = tableRowsQuery(result.database_id, result.table_id);
+ const link = isConcreteTableId(result.table_id)
+ ? tableUrl({ id: result.table_id, name: table?.display_name })
+ : tableRowsQuery(result.database_id, result.table_id);
const label = table?.display_name ?? null;
return (
diff --git a/frontend/src/metabase/urls/modelToUrl.ts b/frontend/src/metabase/urls/modelToUrl.ts
index 9b5a1696439..165381aac82 100644
--- a/frontend/src/metabase/urls/modelToUrl.ts
+++ b/frontend/src/metabase/urls/modelToUrl.ts
@@ -58,6 +58,10 @@ export function modelToUrl(item: UrlableModel): string {
return dashboard(item);
case "table":
if (databaseId != null) {
+ // modelToUrl serves collection/search/library contexts where a user may
+ // only have indirect (published-table) access. The /table/:slug route
+ // needs direct table metadata, which 403s for those users, so keep the
+ // ad-hoc question URL here.
return tableRowsQuery(databaseId, item.id);
}
return NOT_FOUND_URL;
diff --git a/frontend/src/metabase/urls/questions.ts b/frontend/src/metabase/urls/questions.ts
index d86f69a8e6b..3fc63858dee 100644
--- a/frontend/src/metabase/urls/questions.ts
+++ b/frontend/src/metabase/urls/questions.ts
@@ -1,14 +1,18 @@
+import slugg from "slugg";
+
import MetabaseSettings from "metabase/utils/settings";
import type { QuestionCreatorOpts } from "metabase-lib/v1/Question";
import Question from "metabase-lib/v1/Question";
import type {
CardId,
+ ConcreteTableId,
Card as SavedCard,
UnsavedCard,
} from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";
import { card as urlForCard } from "./cards";
+import { appendSlug } from "./utils";
type QuestionUrlBuilderOpts = {
originalQuestion?: Question;
@@ -112,6 +116,27 @@ export function tableRowsQuery(
return `/question#${query}`;
}
+/**
+ * Canonical, human-readable URL for viewing a table as an ad-hoc question,
+ * e.g. `/table/2-orders`. This is the entry URL only: the QB falls back to the
+ * `/question#<hash>` form (see {@link question}) as soon as the question is
+ * edited away from the table's pristine default.
+ *
+ * Only concrete (numeric) table ids are supported — the `/table/:slug` route
+ * parses ids via {@link extractEntityId}. Callers holding a possibly-virtual id
+ * (e.g. `card__17` from the Saved Questions virtual database) must fall back to
+ * {@link tableRowsQuery} or the ad-hoc {@link question} URL.
+ */
+export function table({
+ id,
+ name,
+}: {
+ id: ConcreteTableId;
+ name?: string | null;
+}) {
+ return appendSlug(`/table/${id}`, name ? slugg(name) : undefined);
+}
+
export function xrayModel(id: CardId) {
return `/auto/dashboard/model/${id}`;
}
diff --git a/frontend/src/metabase/urls/questions.unit.spec.ts b/frontend/src/metabase/urls/questions.unit.spec.ts
index edbc3d84320..c34b9b0e9b2 100644
--- a/frontend/src/metabase/urls/questions.unit.spec.ts
+++ b/frontend/src/metabase/urls/questions.unit.spec.ts
@@ -8,7 +8,7 @@ import {
createSampleDatabase,
} from "metabase-types/api/mocks/presets";
-import { newQuestion, question } from "./questions";
+import { newQuestion, question, table } from "./questions";
const metadata = createMockMetadata({
databases: [createSampleDatabase()],
@@ -58,6 +58,23 @@ describe("urls > questions", () => {
});
});
+ describe("table", () => {
+ it("builds a slugged URL from id and name", () => {
+ expect(table({ id: 2, name: "Orders" })).toBe("/table/2-orders");
+ });
+
+ it("slugifies multi-word and special-character names", () => {
+ expect(table({ id: 10, name: "People & Places!" })).toBe(
+ "/table/10-people-places",
+ );
+ });
+
+ it("omits the slug when no name is given", () => {
+ expect(table({ id: 2 })).toBe("/table/2");
+ expect(table({ id: 2, name: null })).toBe("/table/2");
+ });
+ });
+
describe("newQuestion", () => {
it("should return the correct url", () => {
const hash =