Skip to content

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

Warn before converting embedded dashboard questions to SQL (#74494)

Sébastien2344a40c70e9
diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.ts
index d853b123594..0f862ff1ac2 100644
--- a/frontend/src/metabase/api/card.ts
+++ b/frontend/src/metabase/api/card.ts
@@ -339,7 +339,7 @@ export const cardApi = Api.injectEndpoints({
"embedding_params" | "embedding_type"
>(),
getCardDashboards: builder.query<
- { id: DashboardId; name: string }[],
+ { id: DashboardId; name: string; enable_embedding: boolean }[],
Pick<Card, "id">
>({
query: ({ id }) => ({
diff --git a/frontend/src/metabase/query_builder/components/view/View/NotebookContainer/NotebookNativePreview.tsx b/frontend/src/metabase/query_builder/components/view/View/NotebookContainer/NotebookNativePreview.tsx
index 9c493c55feb..abc1a8769c1 100644
--- a/frontend/src/metabase/query_builder/components/view/View/NotebookContainer/NotebookNativePreview.tsx
+++ b/frontend/src/metabase/query_builder/components/view/View/NotebookContainer/NotebookNativePreview.tsx
@@ -1,5 +1,8 @@
-import { useCallback } from "react";
+import { useCallback, useMemo, useState } from "react";
+import { t } from "ttag";
+import { skipToken, useGetCardDashboardsQuery } from "metabase/api";
+import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import { updateQuestion } from "metabase/query_builder/actions";
import { getQuestion } from "metabase/query_builder/selectors";
import { NotebookNativePreview as ControlledNotebookNativePreview } from "metabase/querying/notebook/components/NotebookNativePreview";
@@ -11,8 +14,22 @@ import type Question from "metabase-lib/v1/Question";
export const NotebookNativePreview = () => {
const dispatch = useDispatch();
const question = checkNotNull(useSelector(getQuestion));
+ const cardId = question.id();
+ const isCardEmbedded = question.card().enable_embedding === true;
- const handleConvertClick = useCallback(
+ const { data: dashboards, isLoading: isLoadingDashboards } =
+ useGetCardDashboardsQuery(cardId != null ? { id: cardId } : skipToken);
+
+ const isInEmbeddedDashboard = useMemo(
+ () => (dashboards ?? []).some((dashboard) => dashboard.enable_embedding),
+ [dashboards],
+ );
+
+ const shouldWarn = isCardEmbedded || isInEmbeddedDashboard;
+
+ const [pendingQuestion, setPendingQuestion] = useState<Question | null>(null);
+
+ const performConvert = useCallback(
(newQuestion: Question) => {
dispatch(
updateQuestion(newQuestion, { shouldUpdateUrl: true, run: true }),
@@ -22,10 +39,47 @@ export const NotebookNativePreview = () => {
[dispatch],
);
+ const handleConvertClick = useCallback(
+ (newQuestion: Question) => {
+ if (shouldWarn) {
+ setPendingQuestion(newQuestion);
+ } else {
+ performConvert(newQuestion);
+ }
+ },
+ [shouldWarn, performConvert],
+ );
+
+ const handleConfirm = useCallback(() => {
+ if (pendingQuestion) {
+ performConvert(pendingQuestion);
+ setPendingQuestion(null);
+ }
+ }, [pendingQuestion, performConvert]);
+
+ const handleClose = useCallback(() => {
+ setPendingQuestion(null);
+ }, []);
+
return (
- <ControlledNotebookNativePreview
- question={question}
- onConvertClick={handleConvertClick}
- />
+ <>
+ <ControlledNotebookNativePreview
+ question={question}
+ onConvertClick={handleConvertClick}
+ disableConvert={isLoadingDashboards}
+ />
+ {pendingQuestion && (
+ <ConfirmModal
+ opened
+ data-testid="convert-to-native-warning-modal"
+ title={t`Converting this question to SQL will break any dashboard filters connected to its columns`}
+ message={t`This question is part of an embedded dashboard. Converting the query to SQL will break any dashboard filters that map to its columns, since the conversion won't include SQL variables for the filters to connect to. You can, however, manually add those variables to the converted SQL, then connect the dashboard filters to those variables.`}
+ confirmButtonText={t`Convert to SQL`}
+ confirmButtonProps={{ color: "brand", variant: "filled" }}
+ onConfirm={handleConfirm}
+ onClose={handleClose}
+ />
+ )}
+ </>
);
};
diff --git a/frontend/src/metabase/query_builder/components/view/View/NotebookContainer/NotebookNativePreview.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/View/NotebookContainer/NotebookNativePreview.unit.spec.tsx
new file mode 100644
index 00000000000..f6100779dbd
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/view/View/NotebookContainer/NotebookNativePreview.unit.spec.tsx
@@ -0,0 +1,161 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupCardDashboardsEndpoint } from "__support__/server-mocks/card";
+import { createMockEntitiesState } from "__support__/store";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import {
+ createMockQueryBuilderState,
+ createMockState,
+} from "metabase/redux/store/mocks";
+import type Question from "metabase-lib/v1/Question";
+import type { Card } from "metabase-types/api";
+import { createMockCard } from "metabase-types/api/mocks";
+import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+
+import { NotebookNativePreview } from "./NotebookNativePreview";
+
+// The inner controlled component disables its Convert button while the
+// embedded-dashboards query is loading. The mock mirrors that contract so the
+// tests exercise the wrapper's logic only after the data is in.
+jest.mock(
+ "metabase/querying/notebook/components/NotebookNativePreview",
+ () => ({
+ NotebookNativePreview: ({
+ question,
+ onConvertClick,
+ disableConvert,
+ }: {
+ question: Question;
+ onConvertClick: (q: Question) => void;
+ disableConvert?: boolean;
+ }) => (
+ <button
+ data-testid="convert-trigger"
+ onClick={() => onConvertClick(question)}
+ disabled={disableConvert}
+ >
+ convert
+ </button>
+ ),
+ }),
+);
+
+const CARD_ID = 42;
+
+interface SetupOpts {
+ cardOverrides?: Partial<Card>;
+ embeddedDashboards?: { id: number; name: string }[];
+ plainDashboards?: { id: number; name: string }[];
+}
+
+const setup = ({
+ cardOverrides,
+ embeddedDashboards = [],
+ plainDashboards = [],
+}: SetupOpts = {}) => {
+ const card = createMockCard({
+ id: CARD_ID,
+ enable_embedding: false,
+ ...cardOverrides,
+ });
+
+ setupCardDashboardsEndpoint(card.id, [
+ ...embeddedDashboards.map((d) => ({ ...d, enable_embedding: true })),
+ ...plainDashboards.map((d) => ({ ...d, enable_embedding: false })),
+ ]);
+
+ const state = createMockState({
+ qb: createMockQueryBuilderState({ card }),
+ entities: createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ questions: [card],
+ }),
+ });
+
+ return renderWithProviders(<NotebookNativePreview />, {
+ storeInitialState: state,
+ });
+};
+
+const clickConvert = async () => {
+ const button = await screen.findByTestId("convert-trigger");
+ await waitFor(() => expect(button).toBeEnabled());
+ await userEvent.click(button);
+};
+
+describe("NotebookNativePreview (controlled wrapper)", () => {
+ it("converts directly when the question is not embedded and not in any embedded dashboard", async () => {
+ setup({
+ plainDashboards: [{ id: 1, name: "Plain Dashboard" }],
+ });
+
+ await clickConvert();
+
+ expect(
+ screen.queryByText(/Converting this question to SQL will break/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("warns before converting when the question itself is embedded", async () => {
+ setup({ cardOverrides: { enable_embedding: true } });
+
+ await clickConvert();
+
+ expect(
+ await screen.findByText(/Converting this question to SQL will break/),
+ ).toBeInTheDocument();
+ expect(screen.getByText(/won't include SQL variables/)).toBeInTheDocument();
+ });
+
+ it("warns before converting when the question appears in an embedded dashboard", async () => {
+ setup({
+ embeddedDashboards: [{ id: 10, name: "Embedded Dashboard" }],
+ });
+
+ await clickConvert();
+
+ expect(
+ await screen.findByText(/Converting this question to SQL will break/),
+ ).toBeInTheDocument();
+ });
+
+ it("does not warn when the question only appears in non-embedded dashboards", async () => {
+ setup({
+ plainDashboards: [{ id: 5, name: "Some Dashboard" }],
+ });
+
+ await clickConvert();
+
+ expect(
+ screen.queryByText(/Converting this question to SQL will break/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("cancels the conversion when the user clicks Cancel in the warning modal", async () => {
+ setup({ cardOverrides: { enable_embedding: true } });
+
+ await clickConvert();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Cancel" }),
+ );
+
+ expect(
+ screen.queryByText(/Converting this question to SQL will break/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("closes the warning modal after the user confirms the conversion", async () => {
+ setup({ cardOverrides: { enable_embedding: true } });
+
+ await clickConvert();
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Convert to SQL" }),
+ );
+
+ expect(
+ screen.queryByText(/Converting this question to SQL will break/),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx b/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx
index 3334e1d0a6f..fe567dbaf99 100644
--- a/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx
+++ b/frontend/src/metabase/querying/notebook/components/NotebookNativePreview/NotebookNativePreview.tsx
@@ -37,6 +37,7 @@ type NotebookNativePreviewProps = {
onConvertClick: (newQuestion: Question) => void;
readOnly?: boolean;
disableDefaultLimit?: boolean;
+ disableConvert?: boolean;
};
export const NotebookNativePreview = ({
@@ -46,6 +47,7 @@ export const NotebookNativePreview = ({
onConvertClick,
readOnly,
disableDefaultLimit,
+ disableConvert,
}: NotebookNativePreviewProps) => {
const database = question.database();
const engine = database?.engine;
@@ -125,7 +127,7 @@ export const NotebookNativePreview = ({
variant="subtle"
p={0}
onClick={handleConvertClick}
- disabled={!showQuery}
+ disabled={!showQuery || disableConvert}
>
{buttonTitle ?? BUTTON_TITLE[engineType]}
</Button>
diff --git a/frontend/test/__support__/server-mocks/card.ts b/frontend/test/__support__/server-mocks/card.ts
index 6b20a92eadf..ccccebc411d 100644
--- a/frontend/test/__support__/server-mocks/card.ts
+++ b/frontend/test/__support__/server-mocks/card.ts
@@ -5,6 +5,7 @@ import type {
Card,
CardId,
CardQueryMetadata,
+ DashboardId,
Dataset,
GetPublicCard,
} from "metabase-types/api";
@@ -122,3 +123,12 @@ export function setupCardPublicLinkEndpoints(cardId: CardId) {
export function setupListPublicCardsEndpoint(publicCards: GetPublicCard[]) {
fetchMock.get("path:/api/card/public", publicCards);
}
+
+export function setupCardDashboardsEndpoint(
+ cardId: CardId,
+ dashboards: { id: DashboardId; name: string; enable_embedding: boolean }[],
+) {
+ fetchMock.get(`path:/api/card/${cardId}/dashboards`, dashboards, {
+ name: `card-${cardId}-dashboards`,
+ });
+}
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index 7be1ab9a3bd..ca050171b93 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -184,7 +184,8 @@
:d.collection_id
:d.description
:d.id
- :d.archived]
+ :d.archived
+ :d.enable_embedding]
:from [[:report_dashboardcard :dc]]
:join [[:report_dashboard :d] [:= :dc.dashboard_id :d.id]]
:where [:in :dc.card_id [:inline card-ids]]
@@ -196,7 +197,8 @@
:d.collection_id
:d.description
:d.id
- :d.archived]
+ :d.archived
+ :d.enable_embedding]
:from [[:dashboardcard_series :dcs]]
:join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]
[:report_dashboard :d] [:= :d.id :dc.dashboard_id]]
diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.clj
index bc7d2e6217c..45d5ce237d7 100644
--- a/test/metabase/queries_rest/api/card_test.clj
+++ b/test/metabase/queries_rest/api/card_test.clj
@@ -4411,7 +4411,8 @@
:collection_id forbidden-coll-id
:id other-dash-id
:description nil
- :archived false}]
+ :archived false
+ :enable_embedding false}]
(:in_dashboards (t2/hydrate (t2/select-one :model/Card :id card-id) :in_dashboards))))
(is (nil? (t2/select-fn-set :dashboard_id :model/DashboardCard :card_id card-id))))))))
@@ -4440,7 +4441,8 @@
:model/Card {card-id :id} {}
:model/DashboardCard _ {:dashboard_id dash-id :card_id card-id}]
(is (= [{:id dash-id
- :name "My Dashboard"}]
+ :name "My Dashboard"
+ :enable_embedding false}]
(mt/user-http-request :rasta :get 200 (str "card/" card-id "/dashboards")))))))
(deftest ^:parallel we-can-get-a-list-of-dashboards-a-card-appears-in-2
@@ -4456,8 +4458,8 @@
:model/Card {card-id :id} {}
:model/DashboardCard _ {:dashboard_id dash-id1 :card_id card-id}
:model/DashboardCard _ {:dashboard_id dash-id2 :card_id card-id}]
- (is (= [{:id dash-id1 :name "Dashboard One"}
- {:id dash-id2 :name "Dashboard Two"}]
+ (is (= [{:id dash-id1 :name "Dashboard One" :enable_embedding false}
+ {:id dash-id2 :name "Dashboard Two" :enable_embedding false}]
(mt/user-http-request :rasta :get 200 (str "card/" card-id "/dashboards")))))))
(deftest ^:parallel we-can-get-a-list-of-dashboards-a-card-appears-in-4
@@ -4466,7 +4468,7 @@
:model/Card {card-id :id} {}
:model/DashboardCard _ {:dashboard_id dash-id :card_id card-id}
:model/DashboardCard _ {:dashboard_id dash-id :card_id card-id}]
- (is (= [{:id dash-id :name "My Dashboard"}]
+ (is (= [{:id dash-id :name "My Dashboard" :enable_embedding false}]
(mt/user-http-request :rasta :get 200 (str "card/" card-id "/dashboards")))))))
(deftest ^:parallel we-can-get-a-list-of-dashboards-a-card-appears-in-5
@@ -4475,13 +4477,25 @@
:model/Card {card-id :id} {}
:model/DashboardCard {dc-id :id} {:dashboard_id dash-id}
:model/DashboardCardSeries _ {:dashboardcard_id dc-id :card_id card-id}]
- (is (= [{:id dash-id :name "My Dashboard"}]
+ (is (= [{:id dash-id :name "My Dashboard" :enable_embedding false}]
(mt/user-http-request :rasta :get 200 (str "card/" card-id "/dashboards")))))))
(deftest ^:parallel we-can-get-a-list-of-dashboards-a-card-appears-in-6
(testing "nonexistent card"
(mt/user-http-request :rasta :get 404 "card/invalid-id/dashboards")))
+(deftest ^:parallel we-can-get-a-list-of-dashboards-a-card-appears-in-includes-enable_embedding
+ (testing "Response exposes enable_embedding so the frontend can warn before converting embedded questions to SQL"
+ (mt/with-temp [:model/Dashboard {embedded-dash-id :id} {:name "Embedded Dashboard"
+ :enable_embedding true}
+ :model/Dashboard {plain-dash-id :id} {:name "Plain Dashboard"}
+ :model/Card {card-id :id} {}
+ :model/DashboardCard _ {:dashboard_id embedded-dash-id :card_id card-id}
+ :model/DashboardCard _ {:dashboard_id plain-dash-id :card_id card-id}]
+ (is (= [{:id embedded-dash-id :name "Embedded Dashboard" :enable_embedding true}
+ {:id plain-dash-id :name "Plain Dashboard" :enable_embedding false}]
+ (mt/user-http-request :rasta :get 200 (str "card/" card-id "/dashboards")))))))
+
(deftest we-can-get-a-list-of-dashboards-a-card-appears-in-7
(testing "Don't have permissions on all the dashboards involved"
(mt/with-temp [:model/Collection {allowed-coll-id :id} {:name "The allowed collection"}