Skip to content

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

Remove Question entity (#74652)

Romeo Van Snick5325f240e9f7
diff --git a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx
index 4b1b5cd861a..2ae59f53fbd 100644
--- a/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx
+++ b/enterprise/frontend/src/embedding/data-picker/DataSelector/DataSelector.jsx
@@ -5,6 +5,7 @@ import { t } from "ttag";
import _ from "underscore";
import {
+ cardApi,
databaseApi,
useLazyListDatabaseSchemaTablesQuery,
useLazyListDatabaseSchemasQuery,
@@ -14,7 +15,6 @@ import {
import { EmptyState } from "metabase/common/components/EmptyState";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import CS from "metabase/css/core/index.css";
-import { Questions } from "metabase/entities/questions";
import { entityCompatibleQuery } from "metabase/entities/utils";
import { connect } from "metabase/redux";
import { fetchTableMetadata } from "metabase/redux/tables";
@@ -957,9 +957,9 @@ const DataSelector = _.compose(
}),
hasDataAccess: canUserCreateQueries(state),
hasNestedQueriesEnabled: getSetting(state, "enable-nested-queries"),
- selectedQuestion: Questions.selectors.getObject(state, {
- entityId: getQuestionIdFromVirtualTableId(ownProps.selectedTableId),
- }),
+ selectedQuestion: getMetadata(state).question(
+ getQuestionIdFromVirtualTableId(ownProps.selectedTableId),
+ ),
};
},
(dispatch) => ({
@@ -972,10 +972,10 @@ const DataSelector = _.compose(
),
fetchFields: (tableId) => dispatch(fetchTableMetadata({ id: tableId })),
fetchQuestion: (id) =>
- dispatch(
- Questions.actions.fetch({
- id: getQuestionIdFromVirtualTableId(id),
- }),
+ entityCompatibleQuery(
+ { id: getQuestionIdFromVirtualTableId(id) },
+ dispatch,
+ cardApi.endpoints.getCard,
),
}),
),
diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx
index 5e83f57462a..98d027fbd12 100644
--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx
@@ -16,10 +16,10 @@ import {
getQuestionPickerValue,
} from "metabase/common/components/Pickers/QuestionPicker";
import { QuestionLoader } from "metabase/common/components/QuestionLoader";
+import { QuestionName } from "metabase/common/components/QuestionName";
import { Radio } from "metabase/common/components/Radio";
import { useToggle } from "metabase/common/hooks/use-toggle";
import CS from "metabase/css/core/index.css";
-import { EntityName } from "metabase/entities/containers/EntityName";
import { useTranslateContent } from "metabase/i18n/hooks";
import { GTAPApi } from "metabase/services";
import { Button, Center, Icon, Loader } from "metabase/ui";
@@ -353,10 +353,7 @@ const PolicySummary = ({ policy, policyTable }: PolicySummaryProps) => {
policy.card_id
? jt`rows in the ${(
<strong key="question-name">
- <EntityName
- entityType="questions"
- entityId={policy.card_id}
- />
+ <QuestionName id={policy.card_id} />
</strong>
)} question`
: jt`rows in the ${(
diff --git a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
index af1af57bafb..2da7237a35b 100644
--- a/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreator/ActionCreator.tsx
@@ -1,12 +1,12 @@
import { useState } from "react";
import type { Route } from "react-router";
import { t } from "ttag";
-import _ from "underscore";
import {
skipToken,
useCreateActionMutation,
useGetActionQuery,
+ useGetCardQuery,
useListDatabasesQuery,
useUpdateActionMutation,
} from "metabase/api";
@@ -15,8 +15,7 @@ import { Modal } from "metabase/common/components/Modal";
import { useBeforeUnload } from "metabase/common/hooks/use-before-unload";
import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";
import { useToast } from "metabase/common/hooks/use-toast";
-import { Questions } from "metabase/entities/questions";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import type { State } from "metabase/redux/store";
import { getMetadata } from "metabase/selectors/metadata";
import type Question from "metabase-lib/v1/Question";
@@ -42,7 +41,7 @@ interface OwnProps {
databaseId?: DatabaseId;
action?: WritebackAction;
- route: Route;
+ route?: Route;
onSubmit?: (action: WritebackAction) => void;
onClose?: () => void;
@@ -201,8 +200,14 @@ function ActionCreatorWithContext({
databaseId,
action,
...props
-}: Props) {
+}: OwnProps & StateProps) {
useListDatabasesQuery();
+ useGetCardQuery(props.modelId != null ? { id: props.modelId } : skipToken);
+ const model = useSelector((state) =>
+ props.modelId != null
+ ? (getMetadata(state).question(props.modelId) ?? undefined)
+ : undefined,
+ );
const { data: initialAction } = useGetActionQuery(
props.actionId != null ? { id: props.actionId } : skipToken,
);
@@ -215,16 +220,15 @@ function ActionCreatorWithContext({
databaseId={databaseId}
metadata={metadata}
>
- <ActionCreator {...props} databaseId={databaseId} metadata={metadata} />
+ <ActionCreator
+ {...props}
+ model={model}
+ databaseId={databaseId}
+ metadata={metadata}
+ />
</ActionContext>
);
}
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default _.compose(
- Questions.load({
- id: (state: State, props: OwnProps) => props?.modelId,
- entityAlias: "model",
- }),
- connect(mapStateToProps),
-)(ActionCreatorWithContext);
+export default connect(mapStateToProps)(ActionCreatorWithContext);
diff --git a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
index ca8dd438a83..12e23f5e6a5 100644
--- a/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
+++ b/frontend/src/metabase/actions/containers/ActionCreatorModal/ActionCreatorModal.tsx
@@ -2,13 +2,14 @@ import type { LocationDescriptor } from "history";
import { useEffect } from "react";
import type { Route } from "react-router";
import { replace } from "react-router-redux";
-import _ from "underscore";
-import { skipToken, useGetActionQuery } from "metabase/api";
-import { Questions } from "metabase/entities/questions";
-import { connect } from "metabase/redux";
+import { skipToken, useGetActionQuery, useGetCardQuery } from "metabase/api";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import type { ModalComponentProps } from "metabase/hoc/ModalRoute";
+import { connect, useSelector } from "metabase/redux";
import { setErrorPage } from "metabase/redux/app";
-import type { AppErrorDescriptor, State } from "metabase/redux/store";
+import type { AppErrorDescriptor } from "metabase/redux/store";
+import { getMetadata } from "metabase/selectors/metadata";
import * as Urls from "metabase/urls";
import type Question from "metabase-lib/v1/Question";
import type { WritebackAction } from "metabase-types/api";
@@ -17,11 +18,10 @@ import ActionCreator from "../ActionCreator";
interface OwnProps {
params: {
- slug: string;
+ slug?: string;
actionId?: string;
};
onClose: () => void;
- onChangeLocation: (location: LocationDescriptor) => void;
}
interface EntityLoaderProps {
@@ -31,7 +31,7 @@ interface EntityLoaderProps {
}
interface RouteProps {
- route: Route;
+ route?: Route;
}
interface DispatchProps {
@@ -60,7 +60,7 @@ function ActionCreatorModal({
}: ActionCreatorModalProps) {
const actionId = Urls.extractEntityId(params.actionId);
const modelId = Urls.extractEntityId(params.slug);
- const databaseId = model.databaseId();
+ const databaseId = model.databaseId() ?? undefined;
const { isLoading: isActionLoading, data: action } = useGetActionQuery(
actionId === undefined ? skipToken : { id: actionId },
@@ -99,15 +99,33 @@ function ActionCreatorModal({
);
}
-function getModelId(state: State, props: OwnProps) {
- return Urls.extractEntityId(props.params.slug);
+function ActionCreatorModalLoader({
+ params,
+ onClose,
+ ...dispatchProps
+}: ModalComponentProps & DispatchProps) {
+ const modelId = Urls.extractEntityId(params.slug);
+ const { isLoading, error } = useGetCardQuery(
+ modelId != null ? { id: modelId } : skipToken,
+ );
+ const model = useSelector((state) =>
+ modelId != null ? getMetadata(state).question(modelId) : undefined,
+ );
+
+ if (isLoading || error != null || !model) {
+ return <LoadingAndErrorWrapper loading={isLoading} error={error} />;
+ }
+
+ return (
+ <ActionCreatorModal
+ params={params}
+ onClose={onClose}
+ model={model}
+ loading={isLoading}
+ {...dispatchProps}
+ />
+ );
}
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default _.compose(
- Questions.load({
- id: getModelId,
- entityAlias: "model",
- }),
- connect(null, mapDispatchToProps),
-)(ActionCreatorModal);
+export default connect(null, mapDispatchToProps)(ActionCreatorModalLoader);
diff --git a/frontend/src/metabase/common/components/QuestionName.tsx b/frontend/src/metabase/common/components/QuestionName.tsx
new file mode 100644
index 00000000000..3bba98f65a7
--- /dev/null
+++ b/frontend/src/metabase/common/components/QuestionName.tsx
@@ -0,0 +1,24 @@
+import { useGetCardQuery } from "metabase/api";
+import { useTranslateContent } from "metabase/i18n/hooks";
+import { getName } from "metabase/utils/name";
+import type { CardId } from "metabase-types/api";
+
+interface QuestionNameProps {
+ id: CardId | null | undefined;
+}
+
+export const QuestionName = ({ id }: QuestionNameProps) => {
+ if (id == null || (typeof id === "number" && isNaN(id))) {
+ return null;
+ }
+ return <FetchedQuestionName id={id} />;
+};
+
+const FetchedQuestionName = ({ id }: { id: CardId }) => {
+ const tc = useTranslateContent();
+ const { currentData: card } = useGetCardQuery({ id });
+ if (!card) {
+ return null;
+ }
+ return <span>{tc(getName(card))}</span>;
+};
diff --git a/frontend/src/metabase/common/components/QuestionName.unit.spec.tsx b/frontend/src/metabase/common/components/QuestionName.unit.spec.tsx
new file mode 100644
index 00000000000..26351f762ba
--- /dev/null
+++ b/frontend/src/metabase/common/components/QuestionName.unit.spec.tsx
@@ -0,0 +1,65 @@
+import fetchMock from "fetch-mock";
+
+import { setupCardEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockCard } from "metabase-types/api/mocks";
+
+import { QuestionName } from "./QuestionName";
+
+const TEST_CARD = createMockCard({ name: "Sales overview" });
+
+const renderName = (id: Parameters<typeof QuestionName>[0]["id"]) =>
+ renderWithProviders(
+ <div data-testid="wrapper">
+ <QuestionName id={id} />
+ </div>,
+ );
+
+describe("QuestionName", () => {
+ it("renders the question name returned from the API", async () => {
+ setupCardEndpoints(TEST_CARD);
+
+ renderName(TEST_CARD.id);
+
+ expect(await screen.findByText("Sales overview")).toBeInTheDocument();
+ });
+
+ it("renders nothing while the question is loading", () => {
+ setupCardEndpoints(TEST_CARD);
+
+ renderName(TEST_CARD.id);
+
+ expect(screen.getByTestId("wrapper")).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing when the question cannot be found", async () => {
+ fetchMock.get(`path:/api/card/${TEST_CARD.id}`, 404);
+
+ renderName(TEST_CARD.id);
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD.id}`),
+ ).toHaveLength(1);
+ });
+ expect(screen.getByTestId("wrapper")).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing when the id is null", () => {
+ renderName(null);
+
+ expect(screen.getByTestId("wrapper")).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing when the id is undefined", () => {
+ renderName(undefined);
+
+ expect(screen.getByTestId("wrapper")).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing when the id is NaN", () => {
+ renderName(NaN);
+
+ expect(screen.getByTestId("wrapper")).toBeEmptyDOMElement();
+ });
+});
diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-entity-list-query/use-entity-list-query.unit.spec.tsx b/frontend/src/metabase/common/hooks/entity-framework/use-entity-list-query/use-entity-list-query.unit.spec.tsx
deleted file mode 100644
index ef3b4c5b0de..00000000000
--- a/frontend/src/metabase/common/hooks/entity-framework/use-entity-list-query/use-entity-list-query.unit.spec.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import userEvent from "@testing-library/user-event";
-import fetchMock from "fetch-mock";
-
-import { setupCardsEndpoints } from "__support__/server-mocks";
-import {
- renderWithProviders,
- screen,
- waitFor,
- waitForLoaderToBeRemoved,
- within,
-} from "__support__/ui";
-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import { Questions } from "metabase/entities/questions";
-import { useDispatch } from "metabase/redux";
-import { delay } from "metabase/utils/promise";
-import type Question from "metabase-lib/v1/Question";
-import { createMockCard } from "metabase-types/api/mocks";
-
-import { useEntityListQuery } from "./use-entity-list-query";
-
-const TEST_CARD = createMockCard();
-
-const TestComponent = ({
- reload,
- testId,
-}: {
- reload?: boolean;
- testId?: string;
-}) => {
- const {
- data = [],
- isLoading,
- error,
- } = useEntityListQuery<Question>(
- { reload },
- {
- fetchList: Questions.actions.fetchList,
- getList: Questions.selectors.getList,
- getLoading: Questions.selectors.getLoading,
- getLoaded: Questions.selectors.getLoaded,
- getError: Questions.selectors.getError,
- getListMetadata: Questions.selectors.getListMetadata,
- },
- );
-
- const dispatch = useDispatch();
- const handleInvalidate = () => dispatch(Questions.actions.invalidateLists());
-
- if (isLoading || error) {
- return (
- <LoadingAndErrorWrapper
- loading={isLoading}
- error={error}
- data-testid={testId}
- />
- );
- }
-
- return (
- <div data-testid={testId}>
- <button onClick={handleInvalidate}>Invalidate questions</button>
- {data.map((question) => (
- <div key={question.id()}>{question.displayName()}</div>
- ))}
- </div>
- );
-};
-
-const setup = ({ reload }: { reload?: boolean } = {}) => {
- setupCardsEndpoints([TEST_CARD]);
- return renderWithProviders(<TestComponent reload={reload} />);
-};
-
-describe("useEntityListQuery", () => {
- it("should be initially loading", async () => {
- setup();
-
- expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
-
- // Let the pending list requests settle so their state updates stay
- // wrapped in act instead of leaking into the next test.
- await waitForLoaderToBeRemoved();
- });
-
- it("should load data only once", async () => {
- setup();
-
- await waitForLoaderToBeRemoved();
-
- expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);
- });
-
- it("should not reload data when re-rendered", async () => {
- const { rerender } = setup();
-
- await waitForLoaderToBeRemoved();
- rerender(<TestComponent />);
-
- expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);
- });
-
- it("should not reload data when re-mounted without the reload flag", async () => {
- const { rerender } = setup();
-
- await waitForLoaderToBeRemoved();
- rerender(<div />);
- rerender(<TestComponent />);
- await waitForLoaderToBeRemoved();
-
- expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);
- });
-
- it("should reload data when re-mounted with the reload flag", async () => {
- const { rerender } = setup({ reload: true });
-
- await waitForLoaderToBeRemoved();
- rerender(<div />);
- rerender(<TestComponent reload />);
- await waitForLoaderToBeRemoved();
-
- expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(2);
- });
-
- it("should reload data when explicitly invalidated", async () => {
- setup();
-
- await waitForLoaderToBeRemoved();
- await userEvent.click(screen.getByText("Invalidate questions"));
-
- await waitFor(() => {
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(2);
- });
- expect(await screen.findByText(TEST_CARD.name)).toBeInTheDocument();
- });
-
- it("should not remove loader in case second api call is cached", async () => {
- const { rerender } = setup();
- fetchMock.modifyRoute("cards-list", {
- response: async () => {
- await delay(100);
- return [TEST_CARD];
- },
- });
- await waitFor(() => {
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);
- });
-
- rerender(
- <>
- <TestComponent />
- <TestComponent testId="test2" />
- </>,
- );
-
- // second component should not create extra request, make sure that caching works as expected
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);
-
- expect(
- within(screen.getByTestId("test2")).getByTestId("loading-indicator"),
- ).toBeInTheDocument();
-
- // Wait for the delayed (cached) request to resolve. Using waitFor keeps the
- // resulting state updates wrapped in act, unlike a bare delay.
- await waitForLoaderToBeRemoved();
-
- expect(fetchMock.callHistory.calls("path:/api/card")).toHaveLength(1);
- expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();
- });
-});
diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-entity-query/use-entity-query.unit.spec.tsx b/frontend/src/metabase/common/hooks/entity-framework/use-entity-query/use-entity-query.unit.spec.tsx
deleted file mode 100644
index 3cb8063f67b..00000000000
--- a/frontend/src/metabase/common/hooks/entity-framework/use-entity-query/use-entity-query.unit.spec.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-import fetchMock from "fetch-mock";
-
-import { setupCardEndpoints } from "__support__/server-mocks";
-import {
- renderWithProviders,
- screen,
- waitForLoaderToBeRemoved,
-} from "__support__/ui";
-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import { Questions } from "metabase/entities/questions";
-import type Question from "metabase-lib/v1/Question";
-import type { CardId } from "metabase-types/api";
-import { createMockCard } from "metabase-types/api/mocks";
-
-import { useEntityQuery } from "./use-entity-query";
-
-const TEST_CARD = createMockCard({ id: 1, name: "Card One" });
-const TEST_CARD_RELOAD = createMockCard({ id: 2, name: "Card Two" });
-
-const TestComponent = () => {
- const {
- data: question,
- isLoading,
- error,
- } = useEntityQuery<CardId, Question>(
- {
- id: TEST_CARD.id,
- },
- {
- fetch: Questions.actions.fetch,
- getObject: Questions.selectors.getObject,
- getLoading: Questions.selectors.getLoading,
- getError: Questions.selectors.getError,
- },
- );
-
- if (isLoading || error || !question) {
- return <LoadingAndErrorWrapper loading={isLoading} error={error} />;
- }
-
- return (
- <div>
- <div>{question.displayName()}</div>
- <TestInnerComponent />
- </div>
- );
-};
-
-const TestInnerComponent = () => {
- const {
- data: question,
- isLoading,
- error,
- } = useEntityQuery<CardId, Question>(
- {
- id: TEST_CARD_RELOAD.id,
- reload: true,
- },
- {
- fetch: Questions.actions.fetch,
- getObject: Questions.selectors.getObject,
- getLoading: Questions.selectors.getLoading,
- getError: Questions.selectors.getError,
- },
- );
-
- if (isLoading || error || !question) {
- return <LoadingAndErrorWrapper loading={isLoading} error={error} />;
- }
-
- return <div>{question.displayName()}</div>;
-};
-
-const setup = () => {
- setupCardEndpoints(TEST_CARD);
- setupCardEndpoints(TEST_CARD_RELOAD);
- return renderWithProviders(<TestComponent />);
-};
-
-describe("useEntityQuery", () => {
- it("should be initially loading", () => {
- setup();
-
- expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
- });
-
- it("should initially load data only once the reload flag", async () => {
- setup();
-
- await waitForLoaderToBeRemoved();
-
- expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();
- expect(screen.getByText(TEST_CARD_RELOAD.name)).toBeInTheDocument();
- expect(
- fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD.id}`),
- ).toHaveLength(1);
- expect(
- fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD_RELOAD.id}`),
- ).toHaveLength(1);
- });
-
- it("should not reload data when re-rendered", async () => {
- const { rerender } = setup();
-
- await waitForLoaderToBeRemoved();
- rerender(<TestComponent />);
-
- expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();
- expect(screen.getByText(TEST_CARD_RELOAD.name)).toBeInTheDocument();
- expect(
- fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD.id}`),
- ).toHaveLength(1);
- expect(
- fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD_RELOAD.id}`),
- ).toHaveLength(1);
- });
-
- it("should reload data only for calls with the reload flag when re-mounted", async () => {
- const { rerender } = setup();
-
- await waitForLoaderToBeRemoved();
- rerender(<div />);
- rerender(<TestComponent />);
- await waitForLoaderToBeRemoved();
-
- expect(screen.getByText(TEST_CARD.name)).toBeInTheDocument();
- expect(screen.getByText(TEST_CARD_RELOAD.name)).toBeInTheDocument();
- expect(
- fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD.id}`),
- ).toHaveLength(1);
- expect(
- fetchMock.callHistory.calls(`path:/api/card/${TEST_CARD_RELOAD.id}`),
- ).toHaveLength(2);
- });
-});
diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.ts b/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.ts
index 3c45c2f4651..f56306994fd 100644
--- a/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.ts
+++ b/frontend/src/metabase/common/hooks/entity-framework/use-question-list-query/use-question-list-query.ts
@@ -1,24 +1,42 @@
+import { skipToken, useListCardsQuery } from "metabase/api";
import type {
UseEntityListQueryProps,
UseEntityListQueryResult,
} from "metabase/common/hooks/entity-framework/use-entity-list-query";
-import { useEntityListQuery } from "metabase/common/hooks/entity-framework/use-entity-list-query";
-import { Questions } from "metabase/entities/questions";
+import { useSelector } from "metabase/redux";
+import { getMetadata } from "metabase/selectors/metadata";
import type Question from "metabase-lib/v1/Question";
import type { ListCardsRequest } from "metabase-types/api";
/**
* @deprecated use "metabase/api" instead
*/
-export const useQuestionListQuery = (
- props: UseEntityListQueryProps<ListCardsRequest> = {},
-): UseEntityListQueryResult<Question> => {
- return useEntityListQuery<Question, ListCardsRequest>(props, {
- fetchList: Questions.actions.fetchList,
- getList: Questions.selectors.getList,
- getLoading: Questions.selectors.getLoading,
- getLoaded: Questions.selectors.getLoaded,
- getError: Questions.selectors.getError,
- getListMetadata: Questions.selectors.getListMetadata,
+export const useQuestionListQuery = ({
+ query,
+ reload = false,
+ enabled = true,
+}: UseEntityListQueryProps<ListCardsRequest> = {}): UseEntityListQueryResult<Question> => {
+ const {
+ data: response,
+ isFetching,
+ isSuccess,
+ error,
+ } = useListCardsQuery(enabled ? (query ?? undefined) : skipToken, {
+ refetchOnMountOrArgChange: reload,
});
+ const data = useSelector((state) => {
+ if (!response) {
+ return undefined;
+ }
+ const metadata = getMetadata(state);
+ return response
+ .map(({ id }) => metadata.question(id))
+ .filter((question): question is Question => question != null);
+ });
+ return {
+ data,
+ isLoading: isFetching,
+ isLoaded: isSuccess,
+ error,
+ };
};
diff --git a/frontend/src/metabase/common/hooks/entity-framework/use-question-query/use-question-query.ts b/frontend/src/metabase/common/hooks/entity-framework/use-question-query/use-question-query.ts
index 655fcd1f2d2..64284401ea4 100644
--- a/frontend/src/metabase/common/hooks/entity-framework/use-question-query/use-question-query.ts
+++ b/frontend/src/metabase/common/hooks/entity-framework/use-question-query/use-question-query.ts
@@ -1,22 +1,36 @@
+import { skipToken, useGetCardQuery } from "metabase/api";
import type {
UseEntityQueryProps,
UseEntityQueryResult,
} from "metabase/common/hooks/entity-framework/use-entity-query";
-import { useEntityQuery } from "metabase/common/hooks/entity-framework/use-entity-query";
-import { Questions } from "metabase/entities/questions";
+import { useSelector } from "metabase/redux";
+import { getMetadata } from "metabase/selectors/metadata";
import type Question from "metabase-lib/v1/Question";
import type { CardId, GetCardRequest } from "metabase-types/api";
/**
* @deprecated use "metabase/api" instead
*/
-export const useQuestionQuery = (
- props: UseEntityQueryProps<CardId, Omit<GetCardRequest, "id">>,
-): UseEntityQueryResult<Question> => {
- return useEntityQuery(props, {
- fetch: Questions.actions.fetch,
- getObject: Questions.selectors.getObject,
- getLoading: Questions.selectors.getLoading,
- getError: Questions.selectors.getError,
- });
+export const useQuestionQuery = ({
+ id,
+ query,
+ reload = false,
+ enabled = true,
+}: UseEntityQueryProps<
+ CardId,
+ Omit<GetCardRequest, "id">
+>): UseEntityQueryResult<Question> => {
+ const isActive = enabled && id != null;
+ const { isFetching, error } = useGetCardQuery(
+ isActive ? { id, ...query } : skipToken,
+ { refetchOnMountOrArgChange: reload },
+ );
+ const data = useSelector((state) =>
+ id != null ? (getMetadata(state).question(id) ?? undefined) : undefined,
+ );
+ return {
+ data,
+ isLoading: isFetching || (isActive && data == null),
+ error,
+ };
};
diff --git a/frontend/src/metabase/dashboard/actions/cards-typed.ts b/frontend/src/metabase/dashboard/actions/cards-typed.ts
index 0f2fe59444a..ccd702d3156 100644
--- a/frontend/src/metabase/dashboard/actions/cards-typed.ts
+++ b/frontend/src/metabase/dashboard/actions/cards-typed.ts
@@ -3,7 +3,7 @@ import { t } from "ttag";
import _ from "underscore";
import { cardApi } from "metabase/api";
-import { Questions } from "metabase/entities/questions";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import { loadMetadataForCard } from "metabase/questions/actions";
import { createThunkAction } from "metabase/redux";
import type { Dispatch, GetState } from "metabase/redux/store";
@@ -172,11 +172,12 @@ export type AddCardToDashboardOpts = NewDashCardOpts & {
export const addCardToDashboard =
({ dashId, tabId, cardId }: AddCardToDashboardOpts) =>
- async (dispatch: Dispatch, getState: GetState) => {
- await dispatch(Questions.actions.fetch({ id: cardId }));
- const card = Questions.selectors
- .getObject(getState(), { entityId: cardId })
- .card();
+ async (dispatch: Dispatch) => {
+ const card = await entityCompatibleQuery(
+ { id: cardId },
+ dispatch,
+ cardApi.endpoints.getCard,
+ );
const dashcardId = generateTemporaryDashcardId();
const dashcard = dispatch(
@@ -252,10 +253,11 @@ export const replaceCard =
async (dispatch: Dispatch, getState: GetState) => {
const dashboardId = getDashboardId(getState());
- await dispatch(Questions.actions.fetch({ id: nextCardId }));
- const card = Questions.selectors
- .getObject(getState(), { entityId: nextCardId })
- .card();
+ const card = await entityCompatibleQuery(
+ { id: nextCardId },
+ dispatch,
+ cardApi.endpoints.getCard,
+ );
await dispatch(
setDashCardAttributes({
@@ -296,10 +298,11 @@ export const addCardWithVisualization =
const cards: Card[] = [];
for (const cardId of cardIds) {
- await dispatch(Questions.actions.fetch({ id: cardId }));
- const card: Card = Questions.selectors
- .getObject(getState(), { entityId: cardId })
- .card();
+ const card: Card = await entityCompatibleQuery(
+ { id: cardId },
+ dispatch,
+ cardApi.endpoints.getCard,
+ );
cards.push(card);
}
@@ -345,10 +348,11 @@ export const replaceCardWithVisualization =
const cards: Card[] = [];
for (const cardId of cardIds) {
- await dispatch(Questions.actions.fetch({ id: cardId }));
- const card: Card = Questions.selectors
- .getObject(getState(), { entityId: cardId })
- .card();
+ const card: Card = await entityCompatibleQuery(
+ { id: cardId },
+ dispatch,
+ cardApi.endpoints.getCard,
+ );
cards.push(card);
}
diff --git a/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts b/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
index 4e38aff40d5..6a166aa52dd 100644
--- a/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/actions/cards.unit.spec.ts
@@ -360,7 +360,7 @@ async function runAddCardToDashboard({
dashId,
tabId,
cardId,
- })(store.dispatch, store.getState);
+ })(store.dispatch);
const nextState = store.getState();
const tempDashCardId =
diff --git a/frontend/src/metabase/dashboard/actions/trash.ts b/frontend/src/metabase/dashboard/actions/trash.ts
index 0c0934e8005..6bc96e1b2b8 100644
--- a/frontend/src/metabase/dashboard/actions/trash.ts
+++ b/frontend/src/metabase/dashboard/actions/trash.ts
@@ -1,11 +1,10 @@
import { t } from "ttag";
import _ from "underscore";
-import { dashboardApi } from "metabase/api";
+import { cardApi, dashboardApi } from "metabase/api";
import { getTrashUndoMessage } from "metabase/archive/utils";
import { canonicalCollectionId } from "metabase/collections/utils";
import { fetchDashboard } from "metabase/dashboard/actions";
-import { Questions } from "metabase/entities/questions";
import { entityCompatibleQuery } from "metabase/entities/utils";
import { createThunkAction } from "metabase/redux";
import { addUndo } from "metabase/redux/undo";
@@ -59,7 +58,7 @@ export const setArchivedDashboard = createThunkAction(
try {
await Promise.all(
_.uniq(dashboardQuestionIds).map((id) =>
- dispatch(Questions.actions.fetch({ id }, { reload: true })),
+ entityCompatibleQuery({ id }, dispatch, cardApi.endpoints.getCard),
),
);
} catch (err) {
diff --git a/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsx b/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsx
index 117cd209004..4d286a50942 100644
--- a/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsx
+++ b/frontend/src/metabase/dashboard/components/ActionViz/ActionVizForm.tsx
@@ -156,7 +156,6 @@ function ActionVizForm({
onClose={closeEditModal}
>
<ActionCreator
- initialAction={action}
action={action}
modelId={action.model_id}
databaseId={action.database_id}
diff --git a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsx b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsx
index ceb3e508e05..ae8b039f1c8 100644
--- a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsx
+++ b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/LinkOptions/LinkedEntityPicker/LinkedEntityPicker.tsx
@@ -10,13 +10,13 @@ import {
DashboardPickerModal,
QuestionPickerModal,
} from "metabase/common/components/Pickers";
+import { QuestionName } from "metabase/common/components/QuestionName";
import CS from "metabase/css/core/index.css";
import {
ClickMappings,
clickTargetObjectType,
} from "metabase/dashboard/components/ClickMappings";
import { getDashboard } from "metabase/dashboard/selectors";
-import { Questions } from "metabase/entities/questions";
import { useSelector } from "metabase/redux";
import { getMetadata } from "metabase/selectors/metadata";
import { Button, Icon, Select } from "metabase/ui";
@@ -40,7 +40,7 @@ const LINK_TARGETS = {
// TODO: we can probably just have one picker to pick either a question or a dashboard
question: {
Name: ({ id }: { id: CardId | DashboardId | undefined }) => (
- <Questions.Name id={id} />
+ <QuestionName id={id as CardId | undefined} />
),
PickerComponent: QuestionPickerModal,
pickerIcon: "bar" as const,
diff --git a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/TableClickBehaviorView/Column.tsx b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/TableClickBehaviorView/Column.tsx
index 9c9bd42f6ea..f99dec341e6 100644
--- a/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/TableClickBehaviorView/Column.tsx
+++ b/frontend/src/metabase/dashboard/components/ClickBehaviorSidebar/TableClickBehaviorView/Column.tsx
@@ -1,9 +1,10 @@
import { jt, msgid, ngettext, t } from "ttag";
import { DashboardName } from "metabase/common/components/DashboardName";
-import { Questions } from "metabase/entities/questions";
+import { QuestionName } from "metabase/common/components/QuestionName";
import { getIconForField } from "metabase-lib/v1/metadata/utils/fields";
import type {
+ CardId,
ClickBehavior,
CustomDestinationClickBehavior,
DatasetColumn,
@@ -31,7 +32,7 @@ const getLinkTargetName = (clickBehavior: CustomDestinationClickBehavior) => {
if (clickBehavior.linkType === "question") {
return (
<Quoted key="link-question">
- <Questions.Name id={targetId} />
+ <QuestionName id={targetId as CardId} />
</Quoted>
);
}
diff --git a/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.ts b/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.ts
index ea274234a0f..bdbacb93a3d 100644
--- a/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.ts
+++ b/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.ts
@@ -11,9 +11,9 @@ import {
getParameterValuesBySlugMap,
getParameters,
} from "metabase/dashboard/selectors";
-import { Questions } from "metabase/entities/questions";
import { useStore } from "metabase/redux";
import type { State } from "metabase/redux/store";
+import { getMetadata } from "metabase/selectors/metadata";
import { getUserAttributes } from "metabase/selectors/user";
import type { ClickObject } from "metabase/visualizations/types";
import Question from "metabase-lib/v1/Question";
@@ -39,9 +39,10 @@ function isEntityObject(value: unknown): value is EntityObject {
function resolveLinkedObject(target: LinkedEntityTarget, state: State) {
if (target.entityType === "question") {
- const object = Questions.selectors.getObject(state, {
- entityId: target.entityId,
- });
+ const object =
+ target.entityId != null
+ ? getMetadata(state).question(target.entityId)
+ : null;
if (object instanceof Question) {
const card = object.card();
return isEntityObject(card) ? card : null;
diff --git a/frontend/src/metabase/dashboard/reducers-typed.ts b/frontend/src/metabase/dashboard/reducers-typed.ts
index ae072aa7db0..3af794a2dfc 100644
--- a/frontend/src/metabase/dashboard/reducers-typed.ts
+++ b/frontend/src/metabase/dashboard/reducers-typed.ts
@@ -9,8 +9,8 @@ import {
updateDashboardEmbeddingParams,
updateDashboardEnableEmbedding,
} from "metabase/api";
-import { Questions } from "metabase/entities/questions";
import { handleActions } from "metabase/redux";
+import { CARD_UPDATED } from "metabase/redux/cards";
import {
INITIALIZE,
RESET,
@@ -432,7 +432,7 @@ export const dashcardData = createReducer(
return dissocIn(state, [dashcardId, cardId]);
})
.addCase<string, { type: string; payload: { object?: Card } }>(
- Questions.actionTypes.UPDATE,
+ CARD_UPDATED,
(state, { payload: { object: card } }) => {
if (card) {
const { id } = card;
diff --git a/frontend/src/metabase/dashboard/reducers.ts b/frontend/src/metabase/dashboard/reducers.ts
index ec7b593b414..904eae94722 100644
--- a/frontend/src/metabase/dashboard/reducers.ts
+++ b/frontend/src/metabase/dashboard/reducers.ts
@@ -2,8 +2,8 @@ import { type UnknownAction, createReducer } from "@reduxjs/toolkit";
import { assoc, chain, merge, updateIn } from "icepick";
import { actionApi } from "metabase/api";
-import { Questions } from "metabase/entities/questions";
import { combineReducers } from "metabase/redux";
+import { CARD_UPDATED } from "metabase/redux/cards";
import { SET_PARAMETER_VALUES, initialize } from "metabase/redux/dashboard";
import type { Card } from "metabase-types/api";
@@ -181,19 +181,16 @@ const dashcards = createReducer(
.addCase<
string,
{ type: string; payload: { object: Card | null | undefined } }
- >(
- Questions.actionTypes.UPDATE,
- (state, { payload: { object: card } }) => {
- if (!card) {
- return;
+ >(CARD_UPDATED, (state, { payload: { object: card } }) => {
+ if (!card) {
+ return;
+ }
+ Object.values(state).forEach((dashcard) => {
+ if (dashcard.card?.id === card.id) {
+ Object.assign(dashcard.card, card);
}
- Object.values(state).forEach((dashcard) => {
- if (dashcard.card?.id === card.id) {
- Object.assign(dashcard.card, card);
- }
- });
- },
- )
+ });
+ })
.addMatcher(
actionApi.endpoints.updateAction.matchFulfilled,
(state, { payload: action }) => {
diff --git a/frontend/src/metabase/entities/containers/EntityName.unit.spec.tsx b/frontend/src/metabase/entities/containers/EntityName.unit.spec.tsx
deleted file mode 100644
index b015d01efc4..00000000000
--- a/frontend/src/metabase/entities/containers/EntityName.unit.spec.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { setupCardEndpoints } from "__support__/server-mocks";
-import { createMockEntitiesState } from "__support__/store";
-import { renderWithProviders, screen } from "__support__/ui";
-import { createMockCard } from "metabase-types/api/mocks";
-
-import { EntityName } from "./EntityName";
-
-describe("EntityName", () => {
- describe("questions", () => {
- test("question with name (metabase#33192)", async () => {
- const expectedQuestionName = "Mock Products question";
- const mockCard = createMockCard({ name: expectedQuestionName });
- setupCardEndpoints(mockCard);
-
- renderWithProviders(
- <EntityName entityType="questions" entityId={mockCard.id} />,
- {
- storeInitialState: {
- entities: createMockEntitiesState({
- questions: [mockCard],
- }),
- },
- },
- );
- expect(await screen.findByText(expectedQuestionName)).toBeInTheDocument();
- });
- });
-});
diff --git a/frontend/src/metabase/entities/index.ts b/frontend/src/metabase/entities/index.ts
index 9e0dfe2b71e..c72c40d91be 100644
--- a/frontend/src/metabase/entities/index.ts
+++ b/frontend/src/metabase/entities/index.ts
@@ -68,4 +68,7 @@
* )(BookContainer);
*/
-export { Questions as questions } from "./questions";
+// All entities have been migrated to "metabase/api"; this barrel intentionally
+// exports nothing. Keep the empty export so the file stays a module, not a
+// script.
+export {};
diff --git a/frontend/src/metabase/entities/questions-reducer.ts b/frontend/src/metabase/entities/questions-reducer.ts
new file mode 100644
index 00000000000..a8357874d7e
--- /dev/null
+++ b/frontend/src/metabase/entities/questions-reducer.ts
@@ -0,0 +1,53 @@
+import { updateIn } from "icepick";
+
+import { SOFT_RELOAD_CARD } from "metabase/redux/query-builder";
+
+/**
+ * Dispatched (with a card payload) to merge freshly-fetched RTK Query card data
+ * into the normalized `state.entities.questions` slice, so `getMetadata` sees it.
+ */
+export const INJECT_RTK_QUERY_QUESTION_VALUE =
+ "metabase/entities/questions/FETCH_ADHOC_METADATA";
+
+type QuestionState = Record<string, any>;
+type ReducerAction = { type: string; payload?: any };
+
+/**
+ * Reducer for the `state.entities.questions` slice.
+ *
+ * The `questions` entity has been removed from the entity framework (its CRUD
+ * now lives in `metabase/api/card`), but the normalized slice still needs to:
+ *
+ * - reflect the latest moderation status when a card is soft-reloaded, and
+ * - absorb ad-hoc card values injected by RTK Query consumers.
+ *
+ * It is registered as the retired-entity reducer for `questions` in
+ * `metabase/redux/entities`, where it runs after `handleEntities` has merged any
+ * `payload.entities.questions`.
+ */
+export function questionsReducer(
+ state: QuestionState = {},
+ { type, payload }: ReducerAction,
+): QuestionState {
+ if (type === SOFT_RELOAD_CARD) {
+ const { id } = payload;
+ const latestReview = payload.moderation_reviews?.find(
+ (review: { most_recent?: boolean }) => review.most_recent,
+ );
+
+ if (latestReview) {
+ return updateIn(state, [id], (question) => ({
+ ...question,
+ moderated_status: latestReview.status,
+ }));
+ }
+ }
+
+ if (type === INJECT_RTK_QUERY_QUESTION_VALUE) {
+ const { id } = payload;
+
+ return updateIn(state, [id], (question) => ({ ...question, ...payload }));
+ }
+
+ return state;
+}
diff --git a/frontend/src/metabase/entities/questions-reducer.unit.spec.ts b/frontend/src/metabase/entities/questions-reducer.unit.spec.ts
new file mode 100644
index 00000000000..6ca55f7afef
--- /dev/null
+++ b/frontend/src/metabase/entities/questions-reducer.unit.spec.ts
@@ -0,0 +1,56 @@
+import {
+ INJECT_RTK_QUERY_QUESTION_VALUE,
+ questionsReducer,
+} from "metabase/entities/questions-reducer";
+import { SOFT_RELOAD_CARD } from "metabase/redux/query-builder";
+
+describe("questionsReducer", () => {
+ describe(SOFT_RELOAD_CARD, () => {
+ it("updates moderated_status from the most recent review", () => {
+ const state = { 1: { id: 1, moderated_status: null } };
+
+ const nextState = questionsReducer(state, {
+ type: SOFT_RELOAD_CARD,
+ payload: {
+ id: 1,
+ moderation_reviews: [
+ { status: "verified", most_recent: true },
+ { status: null, most_recent: false },
+ ],
+ },
+ });
+
+ expect(nextState[1].moderated_status).toBe("verified");
+ });
+
+ it("leaves state untouched when there is no most-recent review", () => {
+ const state = { 1: { id: 1, moderated_status: "verified" } };
+
+ const nextState = questionsReducer(state, {
+ type: SOFT_RELOAD_CARD,
+ payload: { id: 1, moderation_reviews: [] },
+ });
+
+ expect(nextState).toBe(state);
+ });
+ });
+
+ describe(INJECT_RTK_QUERY_QUESTION_VALUE, () => {
+ it("merges the payload into the existing question", () => {
+ const state = { 1: { id: 1, name: "Old", display: "table" } };
+
+ const nextState = questionsReducer(state, {
+ type: INJECT_RTK_QUERY_QUESTION_VALUE,
+ payload: { id: 1, name: "New" },
+ });
+
+ expect(nextState[1]).toEqual({ id: 1, name: "New", display: "table" });
+ });
+ });
+
+ it("ignores unrelated actions", () => {
+ const state = { 1: { id: 1 } };
+
+ expect(questionsReducer(state, { type: "metabase/unrelated" })).toBe(state);
+ });
+});
diff --git a/frontend/src/metabase/entities/questions.js b/frontend/src/metabase/entities/questions.js
deleted file mode 100644
index 73b501a70ff..00000000000
--- a/frontend/src/metabase/entities/questions.js
+++ /dev/null
@@ -1,129 +0,0 @@
-import { updateIn } from "icepick";
-
-import { cardApi, useGetCardQuery, useListCardsQuery } from "metabase/api";
-import { getCollectionType } from "metabase/collections/utils";
-import { SOFT_RELOAD_CARD } from "metabase/redux/query-builder";
-import {
- getMetadata,
- getMetadataUnfiltered,
-} from "metabase/selectors/metadata";
-
-import { createEntity, entityCompatibleQuery } from "./utils";
-
-export const INJECT_RTK_QUERY_QUESTION_VALUE =
- "metabase/entities/questions/FETCH_ADHOC_METADATA";
-
-/**
- * @deprecated use "metabase/api" instead
- */
-export const Questions = createEntity({
- name: "questions",
- nameOne: "question",
- path: "/api/card",
-
- rtk: () => ({
- getUseGetQuery: () => ({
- useGetQuery: useGetCardQuery,
- }),
- useListQuery: useListCardsQuery,
- }),
-
- api: {
- list: (entityQuery, dispatch) =>
- entityCompatibleQuery(entityQuery, dispatch, cardApi.endpoints.listCards),
- get: (entityQuery, options, dispatch) =>
- entityCompatibleQuery(
- { ...entityQuery, ignore_error: options?.noEvent },
- dispatch,
- cardApi.endpoints.getCard,
- ),
- create: (entityQuery, dispatch) => {
- const { collection_id, dashboard_id, dashboard_tab_id, ...rest } =
- entityQuery;
-
- const destination = dashboard_id
- ? { dashboard_id, dashboard_tab_id }
- : { collection_id };
-
- return entityCompatibleQuery(
- { ...rest, ...destination },
- dispatch,
- cardApi.endpoints.createCard,
- );
- },
- update: (entityQuery, dispatch) => {
- return entityCompatibleQuery(
- entityQuery,
- dispatch,
- cardApi.endpoints.updateCard,
- );
- },
- delete: ({ id }, dispatch) =>
- entityCompatibleQuery(id, dispatch, cardApi.endpoints.deleteCard),
- },
-
- selectors: {
- getObject: (state, { entityId }) => getMetadata(state).question(entityId),
- getObjectUnfiltered: (state, { entityId }) =>
- getMetadataUnfiltered(state).question(entityId),
- getListUnfiltered: (state, { entityQuery }) => {
- const entityIds =
- Questions.selectors.getEntityIds(state, { entityQuery }) ?? [];
- return entityIds.map((entityId) =>
- Questions.selectors.getObjectUnfiltered(state, { entityId }),
- );
- },
- },
-
- reducer: (state = {}, { type, payload, error }) => {
- if (type === SOFT_RELOAD_CARD) {
- const { id } = payload;
- const latestReview = payload.moderation_reviews?.find(
- (x) => x.most_recent,
- );
-
- if (latestReview) {
- return updateIn(state, [id], (question) => ({
- ...question,
- moderated_status: latestReview.status,
- }));
- }
- }
-
- if (type === INJECT_RTK_QUERY_QUESTION_VALUE) {
- const { id } = payload;
-
- return updateIn(state, [id], (question) => ({ ...question, ...payload }));
- }
- return state;
- },
-
- // NOTE: keep in sync with src/metabase/queries_rest/api/card.clj
- writableProperties: [
- "name",
- "cache_ttl",
- "type",
- "dataset_query",
- "display",
- "description",
- "visualization_settings",
- "parameters",
- "parameter_mappings",
- "archived",
- "enable_embedding",
- "embedding_params",
- "collection_id",
- "dashboard_id",
- "dashboard_tab_id",
- "collection_position",
- "collection_preview",
- "result_metadata",
- "delete_old_dashcards",
- "size",
- ],
-
- getAnalyticsMetadata([object], { action }, getState) {
- const type = object && getCollectionType(object.collection_id, getState());
- return type && `collection=${type}`;
- },
-});
diff --git a/frontend/src/metabase/entities/tables-reducer.ts b/frontend/src/metabase/entities/tables-reducer.ts
index 65f0ec91069..2b64eef641d 100644
--- a/frontend/src/metabase/entities/tables-reducer.ts
+++ b/frontend/src/metabase/entities/tables-reducer.ts
@@ -1,6 +1,6 @@
import { updateIn } from "icepick";
-import { Questions } from "metabase/entities/questions";
+import { CARD_CREATED, CARD_UPDATED } from "metabase/redux/cards";
import {
convertSavedQuestionToVirtualTable,
getCollectionVirtualSchemaId,
@@ -29,7 +29,7 @@ export function tablesReducer(
state: TableState = {},
{ type, payload, error }: ReducerAction,
): TableState {
- if (type === Questions.actionTypes.CREATE && !error) {
+ if (type === CARD_CREATED && !error) {
const card = payload.question;
const virtualQuestionTable = convertSavedQuestionToVirtualTable(card);
@@ -43,7 +43,7 @@ export function tablesReducer(
};
}
- if (type === Questions.actionTypes.UPDATE && !error) {
+ if (type === CARD_UPDATED && !error) {
const card = payload.question;
const virtualTableId = getQuestionVirtualTableId(card.id);
diff --git a/frontend/src/metabase/entities/tables-reducer.unit.spec.ts b/frontend/src/metabase/entities/tables-reducer.unit.spec.ts
index 7ec0fa3d980..f6ec2423fd4 100644
--- a/frontend/src/metabase/entities/tables-reducer.unit.spec.ts
+++ b/frontend/src/metabase/entities/tables-reducer.unit.spec.ts
@@ -1,6 +1,7 @@
-import { Questions } from "metabase/entities/questions";
import { tablesReducer } from "metabase/entities/tables-reducer";
+import { cardCreated, cardUpdated } from "metabase/redux/cards";
import { convertSavedQuestionToVirtualTable } from "metabase-lib/v1/metadata/utils/saved-questions";
+import type { Card } from "metabase-types/api";
describe("tablesReducer", () => {
describe("saved questions virtual table sync", () => {
@@ -25,23 +26,11 @@ describe("tablesReducer", () => {
}
function getCreateAction(question: unknown) {
- return {
- type: Questions.actionTypes.CREATE,
- payload: {
- question,
- object: question,
- },
- };
+ return cardCreated(question as Card);
}
function getUpdateAction(question: unknown) {
- return {
- type: Questions.actionTypes.UPDATE,
- payload: {
- question,
- object: question,
- },
- };
+ return cardUpdated(question as Card);
}
it("should add saved question to tables state on CREATE", () => {
diff --git a/frontend/src/metabase/entities/utils.ts b/frontend/src/metabase/entities/utils.ts
index 04e3afd9a82..0a4ab3a198a 100644
--- a/frontend/src/metabase/entities/utils.ts
+++ b/frontend/src/metabase/entities/utils.ts
@@ -979,6 +979,7 @@ const RETIRED_ENTITY_NAMES = [
"fields",
"measures",
"metrics",
+ "questions",
"schemas",
"segments",
"snippets",
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
index bf8e5703e75..bf5a65e9b80 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.tsx
@@ -2,17 +2,22 @@ import type { LocationDescriptor } from "history";
import { useEffect, useMemo, useState } from "react";
import { replace } from "react-router-redux";
import { useMount } from "react-use";
-import _ from "underscore";
-import { useListActionsQuery, useListDatabasesQuery } from "metabase/api";
+import {
+ skipToken,
+ useGetCardQuery,
+ useListActionsQuery,
+ useListDatabasesQuery,
+} from "metabase/api";
import { NotFound } from "metabase/common/components/ErrorPages";
-import { Questions } from "metabase/entities/questions";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { usePageTitle } from "metabase/hooks/use-page-title";
import ModelActionsView from "metabase/models/components/ModelActions";
import { loadMetadataForCard } from "metabase/questions/actions";
-import { connect } from "metabase/redux";
+import { connect, useSelector } from "metabase/redux";
import type { State } from "metabase/redux/store";
import { fetchTableForeignKeys } from "metabase/redux/tables";
+import { getMetadata } from "metabase/selectors/metadata";
import * as Urls from "metabase/urls";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
@@ -112,15 +117,32 @@ function ModelActions({
);
}
-function getModelId(state: State, props: OwnProps) {
- return Urls.extractEntityId(props.params.slug);
+function ModelActionsLoader({
+ params,
+ children,
+ ...dispatchProps
+}: OwnProps & DispatchProps) {
+ const modelId = Urls.extractEntityId(params.slug);
+ const { isLoading, error } = useGetCardQuery(
+ modelId != null ? { id: modelId } : skipToken,
+ );
+ const model = useSelector((state) =>
+ modelId != null ? getMetadata(state).question(modelId) : undefined,
+ );
+
+ if (!model) {
+ return <LoadingAndErrorWrapper loading={isLoading} error={error} />;
+ }
+
+ return (
+ <ModelActions model={model} params={params} {...dispatchProps}>
+ {children}
+ </ModelActions>
+ );
}
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default _.compose(
- Questions.load({ id: getModelId, entityAlias: "model" }),
- connect<null, DispatchProps, OwnProps & EntityLoadersProps, State>(
- null,
- mapDispatchToProps,
- ),
-)(ModelActions);
+export default connect<null, DispatchProps, OwnProps, State>(
+ null,
+ mapDispatchToProps,
+)(ModelActionsLoader);
diff --git a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
index e0176c322fe..41c81ba53a8 100644
--- a/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
+++ b/frontend/src/metabase/models/containers/ModelActions/ModelActions.unit.spec.tsx
@@ -19,7 +19,6 @@ import {
within,
} from "__support__/ui";
import ActionCreator from "metabase/actions/containers/ActionCreatorModal";
-import { Questions as Models } from "metabase/entities/questions";
import { ModalRoute } from "metabase/hoc/ModalRoute";
import {
createMockSettingsState,
@@ -197,8 +196,6 @@ async function setup({
checkNotNull(metadata.question(q.id)),
);
- const modelUpdateSpy = jest.spyOn(Models.actions, "update");
-
setupDatabasesEndpoints(databases);
setupCardsUsingModelEndpoint(card, usedBy);
setupCardsEndpoints([card]);
@@ -246,7 +243,7 @@ async function setup({
await waitForLoaderToBeRemoved();
- return { model, history, baseUrl, metadata, usedByQuestions, modelUpdateSpy };
+ return { model, history, baseUrl, metadata, usedByQuestions };
}
async function setupActions({
diff --git a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx
index 597e5cc9a06..f5f959ca94e 100644
--- a/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx
+++ b/frontend/src/metabase/parameters/components/ValuesSourceModal/ValuesSourceTypeModal.tsx
@@ -2,9 +2,12 @@ import type { ChangeEvent, ReactNode } from "react";
import { useCallback, useLayoutEffect, useMemo } from "react";
import { useAsyncFn } from "react-use";
import { jt, t } from "ttag";
-import _ from "underscore";
-import { skipToken, useGetTableQueryMetadataQuery } from "metabase/api";
+import {
+ skipToken,
+ useGetCardQuery,
+ useGetTableQueryMetadataQuery,
+} from "metabase/api";
import { Button } from "metabase/common/components/Button";
import { ExternalLink } from "metabase/common/components/ExternalLink";
import { ModalContent } from "metabase/common/components/ModalContent";
@@ -13,9 +16,8 @@ import { Radio } from "metabase/common/components/Radio";
import type { SelectChangeEvent } from "metabase/common/components/Select";
import { Option, Select } from "metabase/common/components/Select";
import { SelectButton } from "metabase/common/components/SelectButton";
-import { Questions } from "metabase/entities/questions";
import { connect, useSelector } from "metabase/redux";
-import type { State } from "metabase/redux/store";
+import { getMetadata } from "metabase/selectors/metadata";
import { getLearnUrl } from "metabase/selectors/settings";
import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
import { Box, Flex, Icon } from "metabase/ui";
@@ -668,28 +670,38 @@ const mapDispatchToProps = {
onFetchParameterValues: fetchParameterValues,
};
-const ValuesSourceTypeModalConnected = _.compose(
- Questions.load({
- id: (state: State, { sourceConfig: { card_id } }: ModalOwnProps) => card_id,
- LoadingAndErrorWrapper: ModalLoadingAndErrorWrapper,
- }),
- connect(null, mapDispatchToProps),
+const ValuesSourceTypeModalConnected = connect(
+ null,
+ mapDispatchToProps,
)(ValuesSourceTypeModal);
-// Loads the source card's virtual-table query metadata into the store (so the
-// connected fields are available) before rendering, replacing the former
-// Tables.load HOC.
+// Loads the source card and its virtual-table query metadata into the store (so
+// the question and its connected fields are available) before rendering,
+// replacing the former Questions.load / Tables.load HOCs.
function ValuesSourceTypeModalLoader(props: ModalOwnProps) {
const { card_id } = props.sourceConfig;
const virtualTableId =
card_id != null ? getQuestionVirtualTableId(card_id) : undefined;
- const { isLoading, error } = useGetTableQueryMetadataQuery(
- virtualTableId != null ? { id: virtualTableId } : skipToken,
+ const { isLoading: isMetadataLoading, error: metadataError } =
+ useGetTableQueryMetadataQuery(
+ virtualTableId != null ? { id: virtualTableId } : skipToken,
+ );
+ const { isLoading: isCardLoading, error: cardError } = useGetCardQuery(
+ card_id != null ? { id: card_id } : skipToken,
+ );
+ const question = useSelector((state) =>
+ card_id != null
+ ? (getMetadata(state).question(card_id) ?? undefined)
+ : undefined,
);
return (
- <ModalLoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
- <ValuesSourceTypeModalConnected {...props} />
+ <ModalLoadingAndErrorWrapper
+ loading={isMetadataLoading || isCardLoading}
+ error={metadataError ?? cardError}
+ noWrapper
+ >
+ <ValuesSourceTypeModalConnected {...props} question={question} />
</ModalLoadingAndErrorWrapper>
);
}
diff --git a/frontend/src/metabase/query_builder/actions/core/core.ts b/frontend/src/metabase/query_builder/actions/core/core.ts
index 65d4ae7e4bb..033ba918b83 100644
--- a/frontend/src/metabase/query_builder/actions/core/core.ts
+++ b/frontend/src/metabase/query_builder/actions/core/core.ts
@@ -1,6 +1,7 @@
import _ from "underscore";
import {
+ cardApi,
databaseApi,
invalidateNotificationsApiCache,
revisionApi,
@@ -10,11 +11,11 @@ import {
cardIsEquivalent,
cardQueryIsEquivalent,
} from "metabase/common/utils/card";
-import { Questions } from "metabase/entities/questions";
import { entityCompatibleQuery } from "metabase/entities/utils";
import { loadMetadataForCard } from "metabase/questions/actions";
import { createThunkAction } from "metabase/redux";
import { openUrl } from "metabase/redux/app";
+import { createQuestionCard, updateQuestionCard } from "metabase/redux/cards";
import {
API_UPDATE_QUESTION,
REVERT_CARD_TO_REVISION,
@@ -62,11 +63,11 @@ export const softReloadCard = createThunkAction(SOFT_RELOAD_CARD, () => {
return async (dispatch, getState) => {
const outdatedCard = getCard(getState());
- const action = await dispatch(
- Questions.actions.fetch({ id: outdatedCard?.id }, { reload: true }),
+ return entityCompatibleQuery(
+ { id: outdatedCard?.id },
+ dispatch,
+ cardApi.endpoints.getCard,
);
-
- return Questions.HACK_getObjectFromAction(action);
};
});
@@ -81,10 +82,11 @@ export const reloadCard = createThunkAction(RELOAD_CARD, () => {
return;
}
- const action = await dispatch(
- Questions.actions.fetch({ id: outdatedQuestion.id() }, { reload: true }),
+ const card = await entityCompatibleQuery(
+ { id: outdatedQuestion.id() },
+ dispatch,
+ cardApi.endpoints.getCard,
);
- const card = Questions.HACK_getObjectFromAction(action);
dispatch(loadMetadataForCard(card));
@@ -377,14 +379,14 @@ async function reduxCreateQuestion(
) {
const display = question.display();
const size = getDefaultSize(display);
- const action = await dispatch(
- Questions.actions.create({
+ const card = (await dispatch(
+ createQuestionCard({
...question.card(),
dashboard_tab_id: options?.dashboardTabId,
- ...(size && { size_x: size.width, size_y: size.height }),
+ ...(size && { size: { size_x: size.width, size_y: size.height } }),
}),
- );
- return question.setCard(Questions.HACK_getObjectFromAction(action));
+ )) as Card;
+ return question.setCard(card);
}
async function reduxUpdateQuestion(
@@ -401,8 +403,8 @@ async function reduxUpdateQuestion(
const card = _.omit(fullCard, ...keysToOmit);
- const action = await dispatch(
- Questions.actions.update({ id: question.id() }, card),
- );
- return question.setCard(Questions.HACK_getObjectFromAction(action));
+ const updatedCard = (await dispatch(
+ updateQuestionCard({ id: question.id(), ...card }),
+ )) as Card;
+ return question.setCard(updatedCard);
}
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index f0319b0c654..e497b4ce017 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -1,13 +1,13 @@
import type { LocationDescriptorObject } from "history";
import { replace } from "react-router-redux";
-import { snippetApi } from "metabase/api";
+import { cardApi, snippetApi } from "metabase/api";
import {
cardIsEquivalent,
deserializeCard,
parseHash,
} from "metabase/common/utils/card";
-import { Questions } from "metabase/entities/questions";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import {
getIsEditingInDashboard,
getNotebookNativePreviewSidebarWidth,
@@ -235,10 +235,11 @@ export async function updateTemplateTagNames(
await Promise.all(
query.referencedQuestionIds().map(async (id) => {
try {
- const actionResult = await dispatch(
- Questions.actions.fetch({ id }, { noEvent: true }),
+ return await entityCompatibleQuery(
+ { id, ignore_error: true },
+ dispatch,
+ cardApi.endpoints.getCard,
);
- return Questions.HACK_getObjectFromAction(actionResult);
} catch {
return null;
}
diff --git a/frontend/src/metabase/query_builder/actions/native.ts b/frontend/src/metabase/query_builder/actions/native.ts
index 880165357c2..dcda07e0279 100644
--- a/frontend/src/metabase/query_builder/actions/native.ts
+++ b/frontend/src/metabase/query_builder/actions/native.ts
@@ -1,6 +1,7 @@
import { createAction } from "redux-actions";
-import { Questions } from "metabase/entities/questions";
+import { cardApi } from "metabase/api";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import { createThunkAction } from "metabase/redux";
import { updateUserSetting } from "metabase/redux/settings";
import type { Dispatch, GetState } from "metabase/redux/store";
@@ -53,17 +54,19 @@ export const OPEN_DATA_REFERENCE_AT_QUESTION =
export const openDataReferenceAtQuestion = createThunkAction(
OPEN_DATA_REFERENCE_AT_QUESTION,
(id: CardId) => async (dispatch: Dispatch) => {
- const action = await dispatch(
- Questions.actions.fetch(
- { id },
- { noEvent: true, useCachedForbiddenError: true },
- ),
+ // forceRefetch: false so a permanently-forbidden card (403) is served from
+ // RTK Query's cache instead of re-hitting /api/card/:id on every open, matching
+ // the former `useCachedForbiddenError` behavior.
+ const card = await entityCompatibleQuery(
+ { id, ignore_error: true },
+ dispatch,
+ cardApi.endpoints.getCard,
+ { forceRefetch: false },
);
- const question = Questions.HACK_getObjectFromAction(action);
- if (question) {
+ if (card) {
return [
- { type: "database", id: question.database_id },
- { type: "question", id: question.id },
+ { type: "database", id: card.database_id },
+ { type: "question", id: card.id },
];
}
},
diff --git a/frontend/src/metabase/query_builder/components/view/View/View/View.jsx b/frontend/src/metabase/query_builder/components/view/View/View/View.jsx
index d587ae77cfe..a3bdd8a534c 100644
--- a/frontend/src/metabase/query_builder/components/view/View/View/View.jsx
+++ b/frontend/src/metabase/query_builder/components/view/View/View/View.jsx
@@ -6,7 +6,7 @@ import { match } from "ts-pattern";
import { t } from "ttag";
import _ from "underscore";
-import { Api } from "metabase/api";
+import { Api, cardApi } from "metabase/api";
import { listTag } from "metabase/api/tags";
import { deletePermanently } from "metabase/archive/actions";
import { getEntityTypeFromCardType } from "metabase/collections/utils";
@@ -16,7 +16,7 @@ import { Toaster } from "metabase/common/components/Toaster";
import { useSetCollection } from "metabase/common/hooks";
import CS from "metabase/css/core/index.css";
import QueryBuilderS from "metabase/css/query_builder.module.css";
-import { Questions } from "metabase/entities/questions";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import {
rememberLastUsedDatabase,
runOrCancelQuestionOrSelectedQuery,
@@ -25,6 +25,7 @@ import {
import { SIDEBAR_SIZES } from "metabase/query_builder/constants";
import { MetricEditor } from "metabase/querying/metrics/components/MetricEditor";
import { connect, useDispatch } from "metabase/redux";
+import { updateQuestionCard } from "metabase/redux/cards";
import { API_UPDATE_QUESTION } from "metabase/redux/query-builder";
import { Flex } from "metabase/ui";
import * as Lib from "metabase-lib";
@@ -297,14 +298,13 @@ const ViewInner = forwardRef(function ViewInnerImpl(propsIn, ref) {
const mapDispatchToProps = (dispatch) => ({
onSetDatabaseId: (id) => dispatch(rememberLastUsedDatabase(id)),
onUnarchive: async (question) => {
- await dispatch(
- Questions.actions.update({ id: question.id() }, { archived: false }),
- );
+ await dispatch(updateQuestionCard({ id: question.id(), archived: false }));
await dispatch(setArchivedQuestion(question, false));
dispatch(Api.util.invalidateTags([listTag("bookmark")]));
},
onDeletePermanently: (id) => {
- const deleteAction = Questions.actions.delete({ id });
+ const deleteAction = (dispatch) =>
+ entityCompatibleQuery(id, dispatch, cardApi.endpoints.deleteCard);
dispatch(deletePermanently(deleteAction));
},
runQuery: () => {
diff --git a/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx b/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx
index b5b4726cb28..7b5c6761210 100644
--- a/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx
+++ b/frontend/src/metabase/querying/common/components/DataSelector/DataSelector.jsx
@@ -6,6 +6,7 @@ import { t } from "ttag";
import _ from "underscore";
import {
+ cardApi,
databaseApi,
useLazyListDatabaseSchemaTablesQuery,
useLazyListDatabaseSchemasQuery,
@@ -15,7 +16,6 @@ import {
import { EmptyState } from "metabase/common/components/EmptyState";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import CS from "metabase/css/core/index.css";
-import { Questions } from "metabase/entities/questions";
import { entityCompatibleQuery } from "metabase/entities/utils";
import { connect } from "metabase/redux";
import { fetchTableMetadata } from "metabase/redux/tables";
@@ -1172,9 +1172,9 @@ const DataSelector = _.compose(
}),
hasDataAccess: canUserCreateQueries(state),
hasNestedQueriesEnabled: getSetting(state, "enable-nested-queries"),
- selectedQuestion: Questions.selectors.getObject(state, {
- entityId: getQuestionIdFromVirtualTableId(ownProps.selectedTableId),
- }),
+ selectedQuestion: getMetadata(state).question(
+ getQuestionIdFromVirtualTableId(ownProps.selectedTableId),
+ ),
};
},
(dispatch) => ({
@@ -1187,10 +1187,10 @@ const DataSelector = _.compose(
),
fetchFields: (tableId) => dispatch(fetchTableMetadata({ id: tableId })),
fetchQuestion: (id) =>
- dispatch(
- Questions.actions.fetch({
- id: getQuestionIdFromVirtualTableId(id),
- }),
+ entityCompatibleQuery(
+ { id: getQuestionIdFromVirtualTableId(id) },
+ dispatch,
+ cardApi.endpoints.getCard,
),
}),
),
diff --git a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx
index ebdc54a51a4..c8a0d863422 100644
--- a/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx
+++ b/frontend/src/metabase/questions/components/MoveCardModal/MoveCardModal.tsx
@@ -15,7 +15,7 @@ import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import { DashboardName } from "metabase/common/components/DashboardName";
import type { OmniPickerCollectionItem } from "metabase/common/components/Pickers";
import { MoveModal } from "metabase/common/components/Pickers";
-import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/entities/questions";
+import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/entities/questions-reducer";
import { useDispatch } from "metabase/redux";
import { API_UPDATE_QUESTION } from "metabase/redux/query-builder";
import { addUndo } from "metabase/redux/undo";
diff --git a/frontend/src/metabase/redux/cards.ts b/frontend/src/metabase/redux/cards.ts
new file mode 100644
index 00000000000..05a0d3c7eb7
--- /dev/null
+++ b/frontend/src/metabase/redux/cards.ts
@@ -0,0 +1,113 @@
+import _ from "underscore";
+
+import { cardApi } from "metabase/api";
+import { INJECT_RTK_QUERY_QUESTION_VALUE } from "metabase/entities/questions-reducer";
+import { entityCompatibleQuery } from "metabase/entities/utils";
+import type { Dispatch } from "metabase/redux/store";
+import type { Card } from "metabase-types/api";
+
+/**
+ * Card lifecycle events dispatched by the create/update thunks below. They let
+ * the retired-entity reducers stay in sync after a card is written — the
+ * `tables` slice keeps the `card__<id>` virtual tables current, and the
+ * dashboard `dashcards` / `dashcardData` slices drop stale data for the updated
+ * card. The payload mirrors the former `Questions` entity action shape
+ * (`object` / `question`) so the reducers that consumed those actions keep
+ * working unchanged.
+ *
+ * Annotated as `string` (not the inferred string literal) on purpose: reducers
+ * pass these to `builder.addCase(type, reducer)`, and a literal type makes
+ * TypeScript resolve the createReducer overloads deeply enough to trip the
+ * instantiation-depth limit on the large dashboard reducer chains. (The former
+ * entity action types sidestepped this by being typed `any`.)
+ */
+export const CARD_CREATED: string = "metabase/cards/CREATED";
+export const CARD_UPDATED: string = "metabase/cards/UPDATED";
+
+export const cardCreated = (card: Card) => ({
+ type: CARD_CREATED,
+ payload: { object: card, question: card },
+});
+
+export const cardUpdated = (card: Card) => ({
+ type: CARD_UPDATED,
+ payload: { object: card, question: card },
+});
+
+// The properties the card endpoints accept on write. Mirrors the former
+// Questions entity `writableProperties`.
+// NOTE: keep in sync with src/metabase/queries_rest/api/card.clj
+const WRITABLE_CARD_PROPERTIES = [
+ "name",
+ "cache_ttl",
+ "type",
+ "dataset_query",
+ "display",
+ "description",
+ "visualization_settings",
+ "parameters",
+ "parameter_mappings",
+ "archived",
+ "enable_embedding",
+ "embedding_params",
+ "collection_id",
+ "dashboard_id",
+ "dashboard_tab_id",
+ "collection_position",
+ "collection_preview",
+ "result_metadata",
+ "delete_old_dashcards",
+ "size",
+] as const;
+
+const pickWritable = (card: object) =>
+ _.pick(card, "id", ...WRITABLE_CARD_PROPERTIES) as Record<string, unknown>;
+
+/**
+ * Creates a card and notifies the retired-entity reducers. Replaces
+ * `Questions.actions.create`, preserving its request shaping: only writable
+ * properties are sent, and the card is filed into either a dashboard or a
+ * collection.
+ */
+export const createQuestionCard =
+ (request: object) =>
+ async (dispatch: Dispatch): Promise<Card> => {
+ const { collection_id, dashboard_id, dashboard_tab_id, ...rest } =
+ pickWritable(request);
+
+ const destination = dashboard_id
+ ? { dashboard_id, dashboard_tab_id }
+ : { collection_id };
+
+ const card: Card = await entityCompatibleQuery(
+ { ...rest, ...destination },
+ dispatch,
+ cardApi.endpoints.createCard,
+ );
+ dispatch(cardCreated(card));
+ // Hydrate the normalized `questions` slice so `getMetadata(state).question(id)`
+ // reflects the write immediately, instead of waiting for a later GET — the
+ // entity framework used to do this when normalizing the create response.
+ dispatch({ type: INJECT_RTK_QUERY_QUESTION_VALUE, payload: card });
+ return card;
+ };
+
+/**
+ * Updates a card and notifies the retired-entity reducers. Replaces
+ * `Questions.actions.update`, sending only writable properties.
+ */
+export const updateQuestionCard =
+ (request: object) =>
+ async (dispatch: Dispatch): Promise<Card> => {
+ const card: Card = await entityCompatibleQuery(
+ pickWritable(request),
+ dispatch,
+ cardApi.endpoints.updateCard,
+ );
+ dispatch(cardUpdated(card));
+ // Hydrate the normalized `questions` slice so `getMetadata(state).question(id)`
+ // reflects the write immediately, instead of waiting for a later GET — the
+ // entity framework used to do this when normalizing the update response.
+ dispatch({ type: INJECT_RTK_QUERY_QUESTION_VALUE, payload: card });
+ return card;
+ };
diff --git a/frontend/src/metabase/redux/entities.js b/frontend/src/metabase/redux/entities.js
index 77c3d311dd6..0ac55f884f8 100644
--- a/frontend/src/metabase/redux/entities.js
+++ b/frontend/src/metabase/redux/entities.js
@@ -1,16 +1,20 @@
import * as entitiesMap from "metabase/entities";
+import { questionsReducer } from "metabase/entities/questions-reducer";
import { tablesReducer } from "metabase/entities/tables-reducer";
import { combineEntities } from "metabase/entities/utils";
import { PLUGIN_ENTITIES } from "metabase/plugins";
+// `metabase/entities` no longer exports any entities, so guard against
+// non-entity values (e.g. interop artifacts from the empty barrel) reaching
+// combineEntities.
const entitiesArray = Object.values({
...entitiesMap,
...PLUGIN_ENTITIES.entities,
-});
+}).filter((entity) => entity?.reducers != null);
export const { entities, reducer, requestsReducer } = combineEntities(
entitiesArray,
- { tables: tablesReducer },
+ { questions: questionsReducer, tables: tablesReducer },
);
// eslint-disable-next-line import/no-default-export -- deprecated usage
export default reducer;
diff --git a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
index 1cfb1ef457f..2f17f75f59e 100644
--- a/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
+++ b/frontend/src/metabase/reference/databases/TableQuestionsContainer.tsx
@@ -2,11 +2,13 @@ import cx from "classnames";
import type { Location } from "history";
import { Component } from "react";
+import { cardApi } from "metabase/api";
import { SidebarLayout } from "metabase/common/components/SidebarLayout";
import CS from "metabase/css/core/index.css";
-import { Questions } from "metabase/entities/questions";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import { connect } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
+import type { Dispatch } from "metabase/redux/store";
import TableQuestions from "metabase/reference/databases/TableQuestions";
import * as actions from "metabase/reference/reference";
@@ -37,7 +39,8 @@ const mapStateToProps = (
});
const mapDispatchToProps = {
- fetchQuestions: Questions.actions.fetchList,
+ fetchQuestions: () => (dispatch: Dispatch) =>
+ entityCompatibleQuery({}, dispatch, cardApi.endpoints.listCards),
...metadataActions,
...actions,
};
diff --git a/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx
index d47bafdb9f7..73565030c87 100644
--- a/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx
+++ b/frontend/src/metabase/reference/segments/SegmentQuestionsContainer.tsx
@@ -2,11 +2,13 @@ import cx from "classnames";
import type { Location } from "history";
import { Component } from "react";
+import { cardApi } from "metabase/api";
import { SidebarLayout } from "metabase/common/components/SidebarLayout";
import CS from "metabase/css/core/index.css";
-import { Questions } from "metabase/entities/questions";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import { connect } from "metabase/redux";
import * as metadataActions from "metabase/redux/metadata";
+import type { Dispatch } from "metabase/redux/store";
import * as actions from "metabase/reference/reference";
import { SegmentQuestions } from "metabase/reference/segments/SegmentQuestions";
import type { User } from "metabase-types/api";
@@ -33,7 +35,8 @@ const mapStateToProps = (
});
const mapDispatchToProps = {
- fetchQuestions: Questions.actions.fetchList,
+ fetchQuestions: () => (dispatch: Dispatch) =>
+ entityCompatibleQuery({}, dispatch, cardApi.endpoints.listCards),
...metadataActions,
...actions,
};