Skip to content

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

Move `MetabaseApi` onto `metabase/api` hooks (#74331)

Romeo Van Snickd373b6aae55e
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx
index b58b7455d15..4856011d5cf 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx
@@ -1,6 +1,6 @@
import userEvent from "@testing-library/user-event";
-import { act, screen, within } from "__support__/ui";
+import { act, screen, waitFor, within } from "__support__/ui";
import type { SetupOpts } from "metabase/admin/performance/components/test-utils";
import {
setupStrategyEditorForDatabases as baseSetup,
@@ -120,9 +120,11 @@ describe("StrategyEditorForDatabases", () => {
await screen.findByTestId("strategy-form-submit-button"),
);
- expect(
- await screen.findByTestId("strategy-form-submit-button"),
- ).toHaveTextContent(/Saved/i);
+ await waitFor(() =>
+ expect(
+ screen.getByTestId("strategy-form-submit-button"),
+ ).toHaveTextContent(/Saved/i),
+ );
expect(await screen.findByLabelText(/Edit default policy/)).toHaveAttribute(
"aria-label",
@@ -189,9 +191,11 @@ describe("StrategyEditorForDatabases", () => {
await userEvent.click(
await screen.findByTestId("strategy-form-submit-button"),
);
- expect(
- await screen.findByTestId("strategy-form-submit-button"),
- ).toHaveTextContent(/Saved/i);
+ await waitFor(() =>
+ expect(
+ screen.getByTestId("strategy-form-submit-button"),
+ ).toHaveTextContent(/Saved/i),
+ );
expect(
await screen.findByLabelText(/Edit policy for database 'Database 1'/),
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts
index 9a08bc45d22..f672cf035e9 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts
@@ -142,6 +142,7 @@ export function useLoadQuestion({
originalQuestion: questionState.originalQuestion,
parameterValues: questionState.parameterValues,
cancelDeferred: deferred(),
+ dispatch,
});
mergeQuestionState(results);
@@ -199,6 +200,7 @@ export function useLoadQuestion({
originalQuestion,
parameterValues,
cancelDeferred: deferred(),
+ dispatch,
});
mergeQuestionState(state);
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts
index eafa66a8f0f..3ea3c951ae3 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts
@@ -68,6 +68,7 @@ export const runQuestionOnNavigateSdk =
cancelDeferred,
isGuestEmbed,
token,
+ dispatch,
});
return state as SdkQuestionState;
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
index a0cbba417bc..f1930c0b609 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
@@ -1,5 +1,6 @@
import { getGuestEmbedFilteredParameters } from "embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters";
import type { SdkQuestionState } from "embedding-sdk-bundle/types/question";
+import type { Dispatch } from "metabase/redux/store";
import { runQuestionQuery } from "metabase/services";
import type { Deferred } from "metabase/utils/promise";
import { getSensibleDisplays } from "metabase/visualizations";
@@ -14,6 +15,7 @@ interface RunQuestionQueryParams {
originalQuestion?: Question;
parameterValues?: ParameterValuesMap;
cancelDeferred?: Deferred;
+ dispatch: Dispatch;
}
export async function runQuestionQuerySdk(
@@ -26,6 +28,7 @@ export async function runQuestionQuerySdk(
originalQuestion,
parameterValues,
cancelDeferred,
+ dispatch,
} = params;
if (question.isSaved()) {
@@ -49,6 +52,7 @@ export async function runQuestionQuerySdk(
);
queryResults = await runQuestionQuery(question, {
+ dispatch,
cancelDeferred,
ignoreCache: false,
isDirty: isQueryDirty,
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.ts
index 5e422c401f0..841b86e9db0 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/update-question.ts
@@ -132,6 +132,7 @@ export const updateQuestionSdk =
originalQuestion,
parameterValues: nextParameterValues,
cancelDeferred,
+ dispatch,
});
}
diff --git a/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx b/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx
index 4149131ff88..3f2b6b00209 100644
--- a/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx
+++ b/frontend/src/metabase/admin/databases/components/DeleteDatabaseModel/DeleteDatabaseModal.tsx
@@ -1,12 +1,11 @@
import type { FormEvent, MouseEventHandler } from "react";
import { useEffect, useRef, useState } from "react";
import { push } from "react-router-redux";
-import { useAsync } from "react-use";
import { jt, t } from "ttag";
+import { useGetDatabaseUsageInfoQuery } from "metabase/api";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { useDispatch } from "metabase/redux";
-import { MetabaseApi } from "metabase/services";
import {
Alert,
Box,
@@ -68,8 +67,8 @@ export const DeleteDatabaseModal = ({
}: DeleteDatabaseModalProps) => {
const dispatch = useDispatch();
- const { value: usageInfo, loading } = useAsync(
- async () => await MetabaseApi.db_usage_info({ dbId: database.id }),
+ const { data: usageInfo, isLoading: loading } = useGetDatabaseUsageInfoQuery(
+ database.id,
);
const [isContentRemovalConfirmed, setIsContentRemovalConfirmed] =
diff --git a/frontend/src/metabase/api/database.ts b/frontend/src/metabase/api/database.ts
index cd13edd8d7b..d294e8f67bb 100644
--- a/frontend/src/metabase/api/database.ts
+++ b/frontend/src/metabase/api/database.ts
@@ -14,6 +14,7 @@ import type {
CreateDatabaseRequest,
Database,
DatabaseId,
+ DatabaseUsageInfo,
Field,
GetDatabaseHealthRequest,
GetDatabaseHealthResponse,
@@ -106,6 +107,13 @@ export const databaseApi = Api.injectEndpoints({
dispatch(updateMetadata(data, DatabaseSchema)),
),
}),
+ getDatabaseUsageInfo: builder.query<DatabaseUsageInfo, DatabaseId>({
+ query: (id) => ({
+ method: "GET",
+ url: `/api/database/${id}/usage_info`,
+ }),
+ providesTags: (_response, _error, id) => [idTag("database", id)],
+ }),
getDatabaseSettingsAvailable: builder.query<
GetDatabaseSettingsAvailableResponse,
DatabaseId
@@ -343,6 +351,7 @@ export const {
useGetDatabaseQuery,
useGetDatabaseHealthQuery,
useGetDatabaseMetadataQuery,
+ useGetDatabaseUsageInfoQuery,
useGetDatabaseSettingsAvailableQuery,
useListDatabaseSchemasQuery,
useLazyListDatabaseSchemasQuery,
diff --git a/frontend/src/metabase/api/dataset.ts b/frontend/src/metabase/api/dataset.ts
index a4aa8326368..e5482b7f68f 100644
--- a/frontend/src/metabase/api/dataset.ts
+++ b/frontend/src/metabase/api/dataset.ts
@@ -74,8 +74,17 @@ export const datasetApi = Api.injectEndpoints({
url: "/api/dataset",
body,
noEvent: ignore_error,
+ // Use fetch so RTK Query's AbortSignal actually cancels the
+ // request. The XHR path only honors a `cancelled` promise, which
+ // we can't thread through `endpoint.initiate(...).abort()`.
+ fetch: true,
}),
providesTags: () => provideAdhocDatasetTags(),
+ // Dataset results can be large and the cache key is the full
+ // DatasetQuery, so cross-caller cache hits are rare. Evict
+ // immediately on unsubscribe to match the legacy fetch-and-discard
+ // behavior used by the imperative `runAdhocDatasetQuery` runner.
+ keepUnusedDataFor: 0,
}),
getAdhocPivotQuery: builder.query<
Dataset,
@@ -92,8 +101,10 @@ export const datasetApi = Api.injectEndpoints({
url: "/api/dataset/pivot",
body,
noEvent: ignore_error,
+ fetch: true,
}),
providesTags: () => provideAdhocDatasetTags(),
+ keepUnusedDataFor: 0,
}),
getAdhocQueryMetadata: builder.query<CardQueryMetadata, DatasetQuery>({
query: (body) => ({
diff --git a/frontend/src/metabase/api/legacy-client.ts b/frontend/src/metabase/api/legacy-client.ts
index 53b6069497d..2cdf3523201 100644
--- a/frontend/src/metabase/api/legacy-client.ts
+++ b/frontend/src/metabase/api/legacy-client.ts
@@ -88,6 +88,19 @@ type ResponseErrorInfo = {
metabaseVersion: string | null;
};
+/**
+ * Thrown when the transport itself fails before a response is received —
+ * e.g. the server dropped the connection, DNS lookup failed, or the user is
+ * offline. Callers can `instanceof`-check this to render a connectivity
+ * error message instead of treating it as a generic JS exception.
+ */
+export class NetworkError extends Error {
+ constructor(message = "Network error") {
+ super(message);
+ this.name = "NetworkError";
+ }
+}
+
export class LegacyApi extends EventEmitter {
basename = "";
apiKey = "";
@@ -421,7 +434,7 @@ export class LegacyApi extends EventEmitter {
options: RequestOptions,
): Promise<unknown> {
const controller = options.controller || new AbortController();
- const signal = options.signal ?? controller.signal;
+ const signal = controller.signal;
options.cancelled?.then(() => controller.abort());
const requestUrl = new URL(this.basename + url, location.origin);
@@ -432,6 +445,20 @@ export class LegacyApi extends EventEmitter {
signal,
});
+ // Propagate aborts from an externally-supplied signal. If the signal is
+ // already aborted (e.g. cancelled while we were awaiting auth-refresh
+ // middleware), defer the propagation to the next microtask so the request
+ // still gets dispatched first — matching XHR's `send()` then-`abort()`
+ // semantics, where `xhr.send()` runs before the cancel handler is wired
+ // up. Otherwise the network never sees the request at all.
+ if (options.signal) {
+ if (options.signal.aborted) {
+ queueMicrotask(() => controller.abort());
+ } else {
+ options.signal.addEventListener("abort", () => controller.abort());
+ }
+ }
+
return fetch(request)
.then((response) => {
const unreadResponse = response.clone();
@@ -488,9 +515,16 @@ export class LegacyApi extends EventEmitter {
.catch((error: unknown) => {
if (signal.aborted) {
throw { isCancelled: true };
- } else {
- throw error;
}
+ // A raw `fetch` rejection (e.g. the server dropped the connection)
+ // surfaces as a plain Error here, indistinguishable from JS
+ // exceptions thrown elsewhere. Wrap it so downstream renderers can
+ // `instanceof NetworkError`-check and route it to the connectivity
+ // error message.
+ if (error instanceof Error) {
+ throw new NetworkError(error.message);
+ }
+ throw error;
});
}
diff --git a/frontend/src/metabase/api/table.ts b/frontend/src/metabase/api/table.ts
index 37da3b50108..3f05b926b32 100644
--- a/frontend/src/metabase/api/table.ts
+++ b/frontend/src/metabase/api/table.ts
@@ -162,6 +162,42 @@ export const tableApi = Api.injectEndpoints({
invalidatesTags: (_, error) =>
invalidateTags(error, [tag("field-values"), tag("parameter-values")]),
}),
+ appendTableCsv: builder.mutation<
+ void,
+ { tableId: TableId; formData: FormData }
+ >({
+ query: ({ tableId, formData }) => ({
+ method: "POST",
+ url: `/api/table/${tableId}/append-csv`,
+ body: { formData },
+ formData: true,
+ fetch: true,
+ }),
+ invalidatesTags: (_, error, { tableId }) =>
+ invalidateTags(error, [
+ idTag("table", tableId),
+ listTag("field"),
+ listTag("field-values"),
+ ]),
+ }),
+ replaceTableCsv: builder.mutation<
+ void,
+ { tableId: TableId; formData: FormData }
+ >({
+ query: ({ tableId, formData }) => ({
+ method: "POST",
+ url: `/api/table/${tableId}/replace-csv`,
+ body: { formData },
+ formData: true,
+ fetch: true,
+ }),
+ invalidatesTags: (_, error, { tableId }) =>
+ invalidateTags(error, [
+ idTag("table", tableId),
+ listTag("field"),
+ listTag("field-values"),
+ ]),
+ }),
/// DATA STUDIO
getTableSelectionInfo: builder.query<
@@ -238,6 +274,8 @@ export const {
useRescanTableFieldValuesMutation,
useSyncTableSchemaMutation,
useDiscardTableFieldValuesMutation,
+ useAppendTableCsvMutation,
+ useReplaceTableCsvMutation,
useGetTableSelectionInfoQuery,
useLazyGetTableSelectionInfoQuery,
diff --git a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts b/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
index 4b3891959de..0bf4ea2b3ae 100644
--- a/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
+++ b/frontend/src/metabase/common/components/ErrorPages/use-error-info.ts
@@ -1,11 +1,12 @@
import { useAsync } from "react-use";
import { t } from "ttag";
+import { datasetApi } from "metabase/api";
import { useLazyGetBugReportDetailsQuery } from "metabase/api/bug-report";
import { useLazyListLogsQuery } from "metabase/api/logger";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import { useDispatch, useSelector } from "metabase/redux";
import { getUser, getUserIsAdmin } from "metabase/selectors/user";
-import { MetabaseApi } from "metabase/services";
import type { ErrorPayload, ReportableEntityName } from "./types";
import { getBrowserInfo, getEntityDetails, hasQueryData } from "./utils";
@@ -81,7 +82,11 @@ export const useErrorInfo = (
const queryResults =
hasQueryData(entity) &&
entityInfo?.dataset_query &&
- (await MetabaseApi.dataset(entityInfo.dataset_query).catch(nullOnCatch));
+ (await entityCompatibleQuery(
+ entityInfo.dataset_query,
+ dispatch,
+ datasetApi.endpoints.getAdhocQuery,
+ ).catch(nullOnCatch));
// if this is an ad-hoc exploration on top of a saved question, fetch the original card
if (hasQueryData(entity) && entityInfo?.original_card_id) {
diff --git a/frontend/src/metabase/common/components/QuestionResultLoader.tsx b/frontend/src/metabase/common/components/QuestionResultLoader.tsx
index 1772421e7a0..6a9bac67f24 100644
--- a/frontend/src/metabase/common/components/QuestionResultLoader.tsx
+++ b/frontend/src/metabase/common/components/QuestionResultLoader.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useEffectOnce } from "react-use";
+import { useDispatch } from "metabase/redux";
import { runQuestionQuery } from "metabase/services";
import type { Deferred } from "metabase/utils/promise";
import { defer } from "metabase/utils/promise";
@@ -51,6 +52,7 @@ export function QuestionResultLoader({
collectionPreview,
children,
}: QuestionResultLoaderProps) {
+ const dispatch = useDispatch();
const [results, setResults] = useState<Dataset[] | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<unknown>(null);
@@ -79,6 +81,7 @@ export function QuestionResultLoader({
setError(null);
const queryResults = await runQuestionQuery(questionToLoad, {
+ dispatch,
cancelDeferred: cancelDeferredRef.current,
collectionPreview,
});
@@ -94,7 +97,7 @@ export function QuestionResultLoader({
setError(err);
}
},
- [collectionPreview],
+ [dispatch, collectionPreview],
);
// A function to pass to the child to allow the component to call `loadResult` again
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index 4d4b8596126..70a16b8fce2 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -36,9 +36,9 @@ import {
AutoApi,
DashboardApi,
EmbedApi,
- MetabaseApi,
PublicApi,
maybeUsePivotEndpoint,
+ runAdhocDatasetQuery,
shouldUsePivotEndpoint,
} from "metabase/services";
import {
@@ -380,11 +380,13 @@ export const fetchCardDataAction = createAsyncThunk<
)) as Dataset | { error: unknown };
} else if (dashboardType === "transient" || dashboardType === "inline") {
result = (await fetchDataOrError(
- maybeUsePivotEndpoint(
- MetabaseApi.dataset,
+ runAdhocDatasetQuery(
+ dispatch,
card,
metadata,
- )({ ...datasetQuery, ignore_cache: ignoreCache }, queryOptions),
+ { ...datasetQuery, ignore_cache: ignoreCache },
+ deferred,
+ ),
)) as Dataset | { error: unknown };
} else {
const dashcardBeforeEditing = getDashCardBeforeEditing(
diff --git a/frontend/src/metabase/query_builder/actions/object-detail.ts b/frontend/src/metabase/query_builder/actions/object-detail.ts
index fcb4c84eb61..b5543617c20 100644
--- a/frontend/src/metabase/query_builder/actions/object-detail.ts
+++ b/frontend/src/metabase/query_builder/actions/object-detail.ts
@@ -1,10 +1,11 @@
import _ from "underscore";
+import { datasetApi } from "metabase/api";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import { createThunkAction } from "metabase/redux";
import { RESET_ROW_ZOOM } from "metabase/redux/query-builder";
import type { Dispatch, GetState } from "metabase/redux/store";
import { getMetadata } from "metabase/selectors/metadata";
-import { MetabaseApi } from "metabase/services";
import type { ObjectId } from "metabase/visualizations/components/ObjectDetail/types";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
@@ -155,7 +156,11 @@ export const loadObjectDetailFKReferences = createThunkAction(
};
try {
- const result = await MetabaseApi.dataset(finalCard);
+ const result = await entityCompatibleQuery(
+ finalCard,
+ dispatch,
+ datasetApi.endpoints.getAdhocQuery,
+ );
if (
result &&
result.status === "completed" &&
diff --git a/frontend/src/metabase/query_builder/actions/querying.ts b/frontend/src/metabase/query_builder/actions/querying.ts
index 97ca81b30fc..00fe9eeda76 100644
--- a/frontend/src/metabase/query_builder/actions/querying.ts
+++ b/frontend/src/metabase/query_builder/actions/querying.ts
@@ -161,6 +161,7 @@ export const runQuestionQuery = ({
const cancelQueryDeferred = defer();
apiRunQuestionQuery(question, {
+ dispatch,
cancelDeferred: cancelQueryDeferred,
ignoreCache: ignoreCache,
isDirty: isQueryDirty,
diff --git a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsx b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsx
index ff98648a36d..5420d658a05 100644
--- a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsx
+++ b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/VisualizationError.tsx
@@ -2,6 +2,7 @@ import cx from "classnames";
import { getIn } from "icepick";
import { t } from "ttag";
+import { NetworkError } from "metabase/api/legacy-client";
import { EmptyState } from "metabase/common/components/EmptyState";
import { ErrorDetails } from "metabase/common/components/ErrorDetails/ErrorDetails";
import { ErrorMessage } from "metabase/common/components/ErrorMessage";
@@ -47,7 +48,13 @@ export function VisualizationError({
const showMetabaseLinks = useSelector(getShowMetabaseLinks);
const isNative = question && Lib.queryDisplayInfo(query).isNative;
- if (typeof error === "object" && error.status != null) {
+ // Treat transport-level failures (server dropped connection, offline, etc.)
+ // the same as an HTTP error with a status — the user just needs to know the
+ // server isn't reachable, not see a stack trace.
+ if (
+ error instanceof NetworkError ||
+ (typeof error === "object" && error.status != null)
+ ) {
// Assume if the request took more than 15 seconds it was due to a timeout
// Some platforms like Heroku return a 503 for numerous types of errors so we can't use the status code to distinguish between timeouts and other failures.
if (duration > VISUALIZATION_SLOW_TIMEOUT) {
diff --git a/frontend/src/metabase/redux/uploads.ts b/frontend/src/metabase/redux/uploads.ts
index 8205b57a6b7..ebd4b2cf532 100644
--- a/frontend/src/metabase/redux/uploads.ts
+++ b/frontend/src/metabase/redux/uploads.ts
@@ -1,7 +1,7 @@
import { assocIn, dissocIn, updateIn } from "icepick";
import { t } from "ttag";
-import { Api, cardApi } from "metabase/api";
+import { Api, cardApi, tableApi } from "metabase/api";
import { listTag } from "metabase/api/tags";
import { entityCompatibleQuery } from "metabase/entities/utils";
import type { Dispatch, State } from "metabase/redux/store";
@@ -12,7 +12,6 @@ import {
createThunkAction,
handleActions,
} from "metabase/redux/utils";
-import { MetabaseApi } from "metabase/services";
import type { CardId, CollectionId, TableId } from "metabase-types/api";
export const UPLOAD_DATA_FILE_TYPES = [".csv", ".tsv"];
@@ -98,9 +97,17 @@ export const uploadFile = createThunkAction(
const response = await (() => {
switch (uploadMode) {
case UploadMode.append:
- return MetabaseApi.tableAppendCSV({ tableId, formData });
+ return entityCompatibleQuery(
+ { tableId, formData },
+ dispatch,
+ tableApi.endpoints.appendTableCsv,
+ );
case UploadMode.replace:
- return MetabaseApi.tableReplaceCSV({ tableId, formData });
+ return entityCompatibleQuery(
+ { tableId, formData },
+ dispatch,
+ tableApi.endpoints.replaceTableCsv,
+ );
case UploadMode.create:
default:
return entityCompatibleQuery(
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index 29e07e35b7c..ce179cb0cf3 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -80,33 +80,11 @@ export function shouldUsePivotEndpoint(card, metadata) {
}
export function maybeUsePivotEndpoint(api, card, metadata) {
- const question = new Question(card, metadata);
-
- // we need to pass pivot_rows, pivot_cols, and totals settings only for ad-hoc queries endpoints
- // in other cases the BE extracts these options from the viz settings
- function wrap(api) {
- return (params, ...rest) => {
- const { pivot_rows, pivot_cols, show_row_totals, show_column_totals } =
- getPivotOptions(question);
- return api(
- {
- ...params,
- pivot_rows,
- pivot_cols,
- show_row_totals,
- show_column_totals,
- },
- ...rest,
- );
- };
- }
-
if (!shouldUsePivotEndpoint(card, metadata)) {
return api;
}
const mapping = [
- [MetabaseApi.dataset, MetabaseApi.dataset_pivot, { wrap: true }],
[CardApi.query, CardApi.query_pivot],
[DashboardApi.cardQuery, DashboardApi.cardQueryPivot],
[PublicApi.cardQuery, PublicApi.cardQueryPivot],
@@ -114,14 +92,68 @@ export function maybeUsePivotEndpoint(api, card, metadata) {
[EmbedApi.cardQuery, EmbedApi.cardQueryPivot],
[EmbedApi.dashboardCardQuery, EmbedApi.dashboardCardQueryPivot],
];
- for (const [from, to, options = {}] of mapping) {
+ for (const [from, to] of mapping) {
if (api === from) {
- return options.wrap ? wrap(to) : to;
+ return to;
}
}
return api;
}
+// Dispatches the RTK `datasetApi` ad-hoc query endpoint (pivot or non-pivot)
+// and wires the `cancelDeferred` to RTK Query's `.abort()`. Translates aborts
+// into the `{ isCancelled: true }` shape that the legacy fetch helper threw,
+// so existing error-handling code (e.g. queryErrored) keeps working.
+let adhocDatasetQueryCounter = 0;
+export async function runAdhocDatasetQuery(
+ dispatch,
+ card,
+ metadata,
+ body,
+ cancelDeferred,
+) {
+ // Dynamic import to avoid a module-init cycle: `metabase/api/dataset` pulls
+ // in `metabase/api` → `metabase/redux/user` → `metabase/redux/query-builder`
+ // → `metabase/services` (this module). Deferring resolution until call time
+ // means the cycle closes only after every module has finished initializing.
+ const { datasetApi } = await import("metabase/api/dataset");
+ const isPivot = shouldUsePivotEndpoint(card, metadata);
+ // Disambiguate the RTK cache key so two callers running the same MBQL
+ // query get independent cache entries and abort signals. Without this,
+ // one caller cancelling would abort the shared in-flight request for
+ // every co-subscribed caller. `_refetchDeps` is stripped from the body
+ // before it hits the server.
+ const requestBody = {
+ ...(isPivot
+ ? { ...body, ...getPivotOptions(new Question(card, metadata)) }
+ : body),
+ _refetchDeps: ++adhocDatasetQueryCounter,
+ };
+ const endpoint = isPivot
+ ? datasetApi.endpoints.getAdhocPivotQuery
+ : datasetApi.endpoints.getAdhocQuery;
+
+ const action = dispatch(
+ endpoint.initiate(requestBody, { forceRefetch: true }),
+ );
+
+ let isCancelled = false;
+ cancelDeferred?.promise.then(() => {
+ isCancelled = true;
+ action.abort?.();
+ });
+
+ return action
+ .unwrap()
+ .catch((error) => {
+ if (isCancelled) {
+ throw { isCancelled: true };
+ }
+ throw error;
+ })
+ .finally(() => action.unsubscribe?.());
+}
+
/**
* @param {*} question
* @param {object} param
@@ -129,6 +161,7 @@ export function maybeUsePivotEndpoint(api, card, metadata) {
export async function runQuestionQuery(
question,
{
+ dispatch,
cancelDeferred,
isDirty = false,
token,
@@ -170,27 +203,17 @@ export async function runQuestionQuery(
];
}
- const getDatasetQueryResult = (datasetQuery) => {
- const datasetQueryWithParameters = { ...datasetQuery, parameters };
- return handleQueryApiError(
- maybeUsePivotEndpoint(
- MetabaseApi.dataset,
+ return [
+ await handleQueryApiError(
+ runAdhocDatasetQuery(
+ dispatch,
card,
question.metadata(),
- )(
- datasetQueryWithParameters,
- cancelDeferred
- ? {
- cancelled: cancelDeferred.promise,
- }
- : {},
+ { ...question.datasetQuery(), parameters },
+ cancelDeferred,
),
- );
- };
-
- const datasetQueries = [question.datasetQuery()];
-
- return Promise.all(datasetQueries.map(getDatasetQueryResult));
+ ),
+ ];
}
export const CardApi = {
@@ -263,26 +286,6 @@ export const AutoApi = {
}),
};
-export const MetabaseApi = {
- db_usage_info: GET("/api/database/:dbId/usage_info"),
- tableAppendCSV: POST("/api/table/:tableId/append-csv", {
- formData: true,
- fetch: true,
- }),
- tableReplaceCSV: POST("/api/table/:tableId/replace-csv", {
- formData: true,
- fetch: true,
- }),
- dataset: POST("/api/dataset"),
- dataset_pivot: POST("/api/dataset/pivot"),
-
- // to support audit app allow the endpoint to be provided in the query
- datasetEndpoint: POST("/api/:endpoint", {
- // this prevents the `endpoint` parameter from being URL encoded
- raw: { endpoint: true },
- }),
-};
-
export const ParameterApi = {
parameterValues: POST("/api/dataset/parameter/values"),
parameterSearch: POST("/api/dataset/parameter/search/:query"),
diff --git a/frontend/src/metabase/services.unit.spec.ts b/frontend/src/metabase/services.unit.spec.ts
index 3165ca8d85c..b2eb362de3c 100644
--- a/frontend/src/metabase/services.unit.spec.ts
+++ b/frontend/src/metabase/services.unit.spec.ts
@@ -1,6 +1,9 @@
import fetchMock from "fetch-mock";
+import { getStore } from "__support__/entities-store";
import { createMockEntitiesState } from "__support__/store";
+import { Api } from "metabase/api";
+import { mainReducers } from "metabase/reducers-main";
import { createMockState } from "metabase/redux/store/mocks";
import { getMetadata } from "metabase/selectors/metadata";
import { defer } from "metabase/utils/promise";
@@ -83,10 +86,21 @@ function getQueryEndpointPath(question: Question) {
: `path:/api/card/${question.id()}/query`;
}
+function getRtkStore() {
+ return getStore(
+ { ...mainReducers, [Api.reducerPath]: Api.reducer },
+ createMockState(),
+ [Api.middleware],
+ );
+}
+
async function setupRunQuestionQuery(question: Question) {
const mockResult = createMockDataset();
fetchMock.post(getQueryEndpointPath(question), mockResult);
- const result = await runQuestionQuery(question, { cancelDeferred: defer() });
+ const result = await runQuestionQuery(question, {
+ dispatch: getRtkStore().dispatch,
+ cancelDeferred: defer(),
+ });
return { result, mockResult };
}
@@ -216,6 +230,7 @@ describe("metabase/services > runQuestionQuery", () => {
});
const result = await runQuestionQuery(question, {
+ dispatch: getRtkStore().dispatch,
cancelDeferred: defer(),
});
@@ -237,6 +252,7 @@ describe("metabase/services > runQuestionQuery", () => {
});
const result = await runQuestionQuery(question, {
+ dispatch: getRtkStore().dispatch,
cancelDeferred: defer(),
});
@@ -254,12 +270,37 @@ describe("metabase/services > runQuestionQuery", () => {
// 5xx errors should still throw
await expect(
- runQuestionQuery(question, { cancelDeferred: defer() }),
+ runQuestionQuery(question, {
+ dispatch: getRtkStore().dispatch,
+ cancelDeferred: defer(),
+ }),
).rejects.toMatchObject({
status: 500,
});
});
+ it("rejects with { isCancelled: true } when cancelDeferred resolves (ad-hoc question)", async () => {
+ // Guards the RTK Query cancellation path: resolving `cancelDeferred`
+ // must abort the underlying `/api/dataset` request and reject with
+ // the legacy `{ isCancelled: true }` shape that `queryErrored` and
+ // other callers rely on.
+ const question = createMockAdHocQuestion();
+ fetchMock.post(
+ getQueryEndpointPath(question),
+ new Promise(() => undefined),
+ );
+
+ const cancelDeferred = defer();
+ const runPromise = runQuestionQuery(question, {
+ dispatch: getRtkStore().dispatch,
+ cancelDeferred,
+ });
+
+ cancelDeferred.resolve();
+
+ await expect(runPromise).rejects.toEqual({ isCancelled: true });
+ });
+
it("normalizes plain-text 4xx error bodies into a structured error result (EMB-1659)", async () => {
// Embed API checks (e.g. `/api/embed/card/:token/query`) reject with a
// plain-text body when a locked param is missing from the JWT. Without
@@ -275,6 +316,7 @@ describe("metabase/services > runQuestionQuery", () => {
});
const result = await runQuestionQuery(question, {
+ dispatch: getRtkStore().dispatch,
cancelDeferred: defer(),
});
diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailView.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailView.tsx
index 6c23883e343..e691a534b6f 100644
--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailView.tsx
+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailView.tsx
@@ -4,13 +4,14 @@ import { t } from "ttag";
import _ from "underscore";
import { ActionExecuteModal } from "metabase/actions/containers/ActionExecuteModal";
-import { skipToken, useListActionsQuery } from "metabase/api";
+import { datasetApi, skipToken, useListActionsQuery } from "metabase/api";
import { NotFound } from "metabase/common/components/ErrorPages";
import { LoadingSpinner } from "metabase/common/components/LoadingSpinner";
import { useDatabaseListQuery } from "metabase/common/hooks";
+import { entityCompatibleQuery } from "metabase/entities/utils";
import { runQuestionQuery } from "metabase/query_builder/actions";
import { useDispatch } from "metabase/redux";
-import { ActionsApi, MetabaseApi } from "metabase/services";
+import { ActionsApi } from "metabase/services";
import { Modal } from "metabase/ui";
import * as Lib from "metabase-lib";
import { isVirtualCardId } from "metabase-lib/v1/metadata/utils/saved-questions";
@@ -90,6 +91,7 @@ export function ObjectDetailView({
className,
isDashboard,
}: ObjectDetailProps): JSX.Element | null {
+ const dispatch = useDispatch();
const [hasNotFoundError, setHasNotFoundError] = useState(false);
const [maybeLoading, setMaybeLoading] = useState(false);
const prevZoomedRowId = usePrevious(zoomedRowID);
@@ -199,7 +201,11 @@ export function ObjectDetailView({
? Lib.toJsQuery(filterByPk(query, pkField, zoomedRowID))
: undefined;
- MetabaseApi.dataset(datasetQuery)
+ entityCompatibleQuery(
+ datasetQuery,
+ dispatch,
+ datasetApi.endpoints.getAdhocQuery,
+ )
.then((result) => {
if (result?.data?.rows?.length > 0) {
const newRow = result.data.rows[0];
@@ -217,7 +223,7 @@ export function ObjectDetailView({
setMaybeLoading(false);
});
}
- }, [maybeLoading, passedData, question, zoomedRowID, pkIndex]);
+ }, [dispatch, maybeLoading, passedData, question, zoomedRowID, pkIndex]);
useEffect(() => {
const hadPrevZoomedRow = prevZoomedRowId != null;
@@ -289,8 +295,6 @@ export function ObjectDetailView({
[zoomedRowID],
);
- const dispatch = useDispatch();
-
const handleActionSuccess = useCallback(() => {
dispatch(runQuestionQuery());
}, [dispatch]);