The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Move question query runner out of services.js and into `metabase/querying` (#75016)
Romeo Van Snick8d534b519e55
diff --git a/enterprise/frontend/src/metabase-enterprise/tools/ErrorOverview.jsx b/enterprise/frontend/src/metabase-enterprise/tools/ErrorOverview.jsxindex 5f18ade679f..cee18ebf01b 100644--- a/enterprise/frontend/src/metabase-enterprise/tools/ErrorOverview.jsx+++ b/enterprise/frontend/src/metabase-enterprise/tools/ErrorOverview.jsx@@ -6,9 +6,9 @@ import {SettingsPageWrapper,SettingsSection,} from "metabase/admin/components/SettingsSection";+import { useLazyGetCardQueryQuery } from "metabase/api";import CS from "metabase/css/core/index.css";import { fetchDataOrError } from "metabase/dashboard/utils";-import { CardApi } from "metabase/services";import AuditParameters from "../audit_app/components/AuditParameters";import AuditTable from "../audit_app/containers/AuditTable";@@ -22,6 +22,7 @@ const CARD_ID_COL = 0;// eslint-disable-next-line import/no-default-export -- deprecated usageexport default function ErrorOverview(props) {+ const [runCardQuery] = useLazyGetCardQueryQuery();const reloadRef = useRef(null);// TODO: use isReloading to display a loading overlay// eslint-disable-next-line no-unused-vars@@ -59,9 +60,8 @@ export default function ErrorOverview(props) {const checkedCardIds = Object.keys(_.pick(rowChecked, _.identity));await Promise.all(- checkedCardIds.map(- async (member) =>- await fetchDataOrError(CardApi.query({ cardId: member })),+ checkedCardIds.map((member) =>+ fetchDataOrError(runCardQuery({ cardId: member }).unwrap()),),);setRowChecked({});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.tsindex 199f62f4965..2593d4d4e7b 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,10 +1,10 @@import { getGuestEmbedFilteredParameters } from "embedding-sdk-bundle/lib/get-guest-embed-filtered-parameters";import type { SdkQuestionState } from "embedding-sdk-bundle/types/question";+import { runQuestionQuery } from "metabase/querying/run-query";import type { Dispatch } from "metabase/redux/store";-import { runQuestionQuery } from "metabase/services";import { getSensibleDisplays } from "metabase/visualizations";import type Question from "metabase-lib/v1/Question";-import type { ParameterValuesMap } from "metabase-types/api";+import type { DatasetData, ParameterValuesMap } from "metabase-types/api";import type { EntityToken } from "metabase-types/api/entity";interface RunQuestionQueryParams {@@ -67,8 +67,15 @@ export async function runQuestionQuerySdk(const [{ data = isGuestEmbed ? { rows: [], cols: [] } : undefined }] =queryResults;- const sensibleDisplays = getSensibleDisplays(data);- question = question.maybeResetDisplay(data, sensibleDisplays, undefined);+ // `data` may be a partial (guest embed) or absent (error result); the+ // viz helpers tolerate it, matching the prior untyped behavior.+ const datasetData = data as DatasetData;+ const sensibleDisplays = getSensibleDisplays(datasetData);+ question = question.maybeResetDisplay(+ datasetData,+ sensibleDisplays,+ undefined,+ );}return { question, queryResults };diff --git a/frontend/src/metabase-types/api/dashboard.ts b/frontend/src/metabase-types/api/dashboard.tsindex 7d9dbee53c1..a9825a46dca 100644--- a/frontend/src/metabase-types/api/dashboard.ts+++ b/frontend/src/metabase-types/api/dashboard.ts@@ -341,6 +341,19 @@ export type GetDashboardQueryMetadataRequest = {dashboard_load_id?: string;};+export type DashboardCardQueryRequest = {+ dashboardId: DashboardId;+ dashcardId: DashCardId;+ cardId: CardId;+ collection_preview?: boolean;+ ignore_cache?: boolean;+ parameters?: unknown[];+ // Sent in the request body (in addition to the path params above) when+ // querying a saved dashcard, for query provenance/telemetry.+ dashboard_id?: DashboardId;+ dashboard_load_id?: string;+};+export type SaveDashboardRequest = Omit<UpdateDashboardRequest, "id">;export type CopyDashboardRequest = {diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.tsindex a8b134bc01b..4ff34f578be 100644--- a/frontend/src/metabase/api/card.ts+++ b/frontend/src/metabase/api/card.ts@@ -99,8 +99,13 @@ export const cardApi = Api.injectEndpoints({metadata ? provideCardQueryMetadataTags(id, metadata) : [],onQueryStarted: hydrateMetadataStore(QueryMetadataSchema),}),- getCardQuery: builder.query<Dataset, CardQueryRequest>({- query: ({ cardId, ...body }) => ({+ getCardQuery: builder.query<+ Dataset,+ CardQueryRequest & { _refetchDeps?: unknown }+ >({+ // `_refetchDeps` is part of the RTK cache key (so imperative runners can+ // force a unique key per call) but must not be sent to the server.+ query: ({ cardId, _refetchDeps, ...body }) => ({method: "POST",url: `/api/card/${cardId}/query`,body,@@ -108,8 +113,11 @@ export const cardApi = Api.injectEndpoints({providesTags: (_data, _error, { cardId }) =>provideCardQueryTags(cardId),}),- getCardQueryPivot: builder.query<Dataset, CardQueryRequest>({- query: ({ cardId, ...body }) => ({+ getCardQueryPivot: builder.query<+ Dataset,+ CardQueryRequest & { _refetchDeps?: unknown }+ >({+ query: ({ cardId, _refetchDeps, ...body }) => ({method: "POST",url: `/api/card/pivot/${cardId}/query`,body,diff --git a/frontend/src/metabase/api/dashboard.ts b/frontend/src/metabase/api/dashboard.tsindex 6ea68a2c658..e0060d1f931 100644--- a/frontend/src/metabase/api/dashboard.ts+++ b/frontend/src/metabase/api/dashboard.ts@@ -4,8 +4,10 @@ import type {CopyDashboardRequest,CreateDashboardRequest,Dashboard,+ DashboardCardQueryRequest,DashboardId,DashboardQueryMetadata,+ Dataset,FieldId,FieldValue,GetDashboardQueryMetadataRequest,@@ -28,6 +30,7 @@ import {idTag,invalidateTags,listTag,+ provideCardQueryTags,provideDashboardListTags,provideDashboardQueryMetadataTags,provideDashboardTags,@@ -95,6 +98,44 @@ export const dashboardApi = Api.injectEndpoints({metadata ? provideDashboardQueryMetadataTags(metadata) : [],onQueryStarted: hydrateMetadataStore(QueryMetadataSchema),}),+ getDashboardCardQuery: builder.query<+ Dataset,+ DashboardCardQueryRequest & { _refetchDeps?: unknown }+ >({+ // `_refetchDeps` is part of the RTK cache key (so imperative runners can+ // force a unique key per call) but must not be sent to the server.+ query: ({+ dashboardId,+ dashcardId,+ cardId,+ _refetchDeps,+ ...body+ }) => ({+ method: "POST",+ url: `/api/dashboard/${dashboardId}/dashcard/${dashcardId}/card/${cardId}/query`,+ body,+ }),+ providesTags: (_data, _error, { cardId }) =>+ provideCardQueryTags(cardId),+ }),+ getDashboardCardQueryPivot: builder.query<+ Dataset,+ DashboardCardQueryRequest & { _refetchDeps?: unknown }+ >({+ query: ({+ dashboardId,+ dashcardId,+ cardId,+ _refetchDeps,+ ...body+ }) => ({+ method: "POST",+ url: `/api/dashboard/pivot/${dashboardId}/dashcard/${dashcardId}/card/${cardId}/query`,+ body,+ }),+ providesTags: (_data, _error, { cardId }) =>+ provideCardQueryTags(cardId),+ }),getRemappedDashboardParameterValue: builder.query<FieldValue,GetRemappedDashboardParameterValueRequest@@ -263,6 +304,8 @@ export const {useGetDashboardQuery,useLazyGetDashboardQuery,useGetDashboardQueryMetadataQuery,+ useGetDashboardCardQueryQuery,+ useGetDashboardCardQueryPivotQuery,useListDashboardsQuery,useListDashboardItemsQuery,useGetRemappedDashboardParameterValueQuery,diff --git a/frontend/src/metabase/api/embed.ts b/frontend/src/metabase/api/embed.tsnew file mode 100644index 00000000000..8a10e27baa3--- /dev/null+++ b/frontend/src/metabase/api/embed.ts@@ -0,0 +1,69 @@+import { getEmbedBase } from "metabase/services";+import type { CardId, DashCardId, Dataset } from "metabase-types/api";++import { Api } from "./api";++export type EmbedCardQueryRequest = {+ token: string;+ // Embeds apply parameter values server-side; `parameters` is JSON-stringified+ // and passed through the query string.+ parameters?: string;+ ignore_cache?: boolean;+};++export type EmbedDashcardQueryRequest = {+ token: string;+ dashcardId: DashCardId;+ cardId: CardId;+ parameters?: string;+ ignore_cache?: boolean;+};++export const embedApi = Api.injectEndpoints({+ endpoints: (builder) => ({+ getEmbedCardQuery: builder.query<Dataset, EmbedCardQueryRequest>({+ // `getEmbedBase()` is resolved per request so embed previews+ // (`/api/preview_embed`) hit the preview endpoints.+ query: ({ token, ...params }) => ({+ method: "GET",+ url: `${getEmbedBase()}/card/${token}/query`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ getEmbedCardQueryPivot: builder.query<Dataset, EmbedCardQueryRequest>({+ query: ({ token, ...params }) => ({+ method: "GET",+ url: `${getEmbedBase()}/pivot/card/${token}/query`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ getEmbedDashcardQuery: builder.query<Dataset, EmbedDashcardQueryRequest>({+ query: ({ token, dashcardId, cardId, ...params }) => ({+ method: "GET",+ url: `${getEmbedBase()}/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ getEmbedDashcardQueryPivot: builder.query<+ Dataset,+ EmbedDashcardQueryRequest+ >({+ query: ({ token, dashcardId, cardId, ...params }) => ({+ method: "GET",+ url: `${getEmbedBase()}/pivot/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ }),+});++export const {+ useGetEmbedCardQueryQuery,+ useGetEmbedCardQueryPivotQuery,+ useGetEmbedDashcardQueryQuery,+ useGetEmbedDashcardQueryPivotQuery,+} = embedApi;diff --git a/frontend/src/metabase/api/index.ts b/frontend/src/metabase/api/index.tsindex 03193c34905..526cce2cdde 100644--- a/frontend/src/metabase/api/index.ts+++ b/frontend/src/metabase/api/index.ts@@ -17,6 +17,7 @@ export * from "./dashboard";export * from "./database";export * from "./dataset";export * from "./document";+export * from "./embed";export * from "./entity-id";export * from "./field";export * from "./glossary";@@ -35,6 +36,8 @@ export * from "./parameters";export * from "./permission";export * from "./persist";export * from "./premium-features";+export * from "./public";+export * from "./query-endpoints";export * from "./revision";export * from "./search";export * from "./security-center";diff --git a/frontend/src/metabase/api/public.ts b/frontend/src/metabase/api/public.tsnew file mode 100644index 00000000000..4d251b83ea8--- /dev/null+++ b/frontend/src/metabase/api/public.ts@@ -0,0 +1,69 @@+import { publicBase } from "metabase/services";+import type { CardId, DashCardId, Dataset } from "metabase-types/api";++import { Api } from "./api";++export type PublicCardQueryRequest = {+ uuid: string;+ // `parameters` is JSON-stringified because public links apply parameters+ // client-side and pass them through the query string.+ parameters?: string;+ ignore_cache?: boolean;+};++export type PublicDashcardQueryRequest = {+ uuid: string;+ dashcardId: DashCardId;+ cardId: CardId;+ parameters?: string;+ ignore_cache?: boolean;+};++const PIVOT_PREFIX = `${publicBase}/pivot`;++export const publicApi = Api.injectEndpoints({+ endpoints: (builder) => ({+ getPublicCardQuery: builder.query<Dataset, PublicCardQueryRequest>({+ query: ({ uuid, ...params }) => ({+ method: "GET",+ url: `${publicBase}/card/${uuid}/query`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ getPublicCardQueryPivot: builder.query<Dataset, PublicCardQueryRequest>({+ query: ({ uuid, ...params }) => ({+ method: "GET",+ url: `${PIVOT_PREFIX}/card/${uuid}/query`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ getPublicDashcardQuery: builder.query<Dataset, PublicDashcardQueryRequest>({+ query: ({ uuid, dashcardId, cardId, ...params }) => ({+ method: "GET",+ url: `${publicBase}/dashboard/${uuid}/dashcard/${dashcardId}/card/${cardId}`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ getPublicDashcardQueryPivot: builder.query<+ Dataset,+ PublicDashcardQueryRequest+ >({+ query: ({ uuid, dashcardId, cardId, ...params }) => ({+ method: "GET",+ url: `${PIVOT_PREFIX}/dashboard/${uuid}/dashcard/${dashcardId}/card/${cardId}`,+ params,+ }),+ keepUnusedDataFor: 0,+ }),+ }),+});++export const {+ useGetPublicCardQueryQuery,+ useGetPublicCardQueryPivotQuery,+ useGetPublicDashcardQueryQuery,+ useGetPublicDashcardQueryPivotQuery,+} = publicApi;diff --git a/frontend/src/metabase/api/query-endpoints.ts b/frontend/src/metabase/api/query-endpoints.tsnew file mode 100644index 00000000000..1f772a9d12c--- /dev/null+++ b/frontend/src/metabase/api/query-endpoints.ts@@ -0,0 +1,144 @@+import { isNative } from "metabase/common/utils/card";+import type { Dispatch } from "metabase/redux/store";+import Question from "metabase-lib/v1/Question";+import type Metadata from "metabase-lib/v1/metadata/Metadata";+import type { Card, Dataset } from "metabase-types/api";++import { cardApi } from "./card";+import { dashboardApi } from "./dashboard";+import { embedApi } from "./embed";+import { publicApi } from "./public";++// Minimal structural view of an RTK Query endpoint. We only ever dispatch+// `.initiate(...)`, so this is all the runner and pivot map need. Declared as a+// method (not an arrow property) so RTK's concrete endpoints stay assignable.+type QueryEndpoint<Arg> = {+ initiate(arg: Arg, options?: unknown): unknown;+};++// Extracts the request-argument type a query endpoint expects.+type ArgOf<Endpoint> = Endpoint extends QueryEndpoint<infer Arg> ? Arg : never;++// Pivot tables need subtotal data the regular query endpoints don't return, so+// each query route has a dedicated pivot mirror. This maps every base endpoint+// to its pivot variant; keep it as the single source of truth for that pairing.+const PIVOT_ENDPOINTS = new Map<unknown, unknown>([+ [cardApi.endpoints.getCardQuery, cardApi.endpoints.getCardQueryPivot],+ [+ dashboardApi.endpoints.getDashboardCardQuery,+ dashboardApi.endpoints.getDashboardCardQueryPivot,+ ],+ [+ publicApi.endpoints.getPublicCardQuery,+ publicApi.endpoints.getPublicCardQueryPivot,+ ],+ [+ publicApi.endpoints.getPublicDashcardQuery,+ publicApi.endpoints.getPublicDashcardQueryPivot,+ ],+ [+ embedApi.endpoints.getEmbedCardQuery,+ embedApi.endpoints.getEmbedCardQueryPivot,+ ],+ [+ embedApi.endpoints.getEmbedDashcardQuery,+ embedApi.endpoints.getEmbedDashcardQueryPivot,+ ],+]);++/**+ * Whether `card` should be queried through the pivot endpoints. Pivot tables+ * need subtotal data the regular query endpoints don't return, so they use+ * dedicated mirror endpoints that take `pivot_rows`/`pivot_cols`.+ */+export function shouldUsePivotEndpoint(+ card: Card,+ metadata: Metadata,+): boolean {+ const question = new Question(card, metadata);+ // Short-circuit on the cheap, always-safe checks first. `question.database()`+ // resolves the database via Lib, which throws for query types Lib doesn't+ // support (e.g. the `internal` queries the audit pages run), so it must not+ // be evaluated for non-pivot/native cards.+ if (question.display() !== "pivot" || isNative(card)) {+ return false;+ }+ const database = question.database();+ // if we have metadata for the db, check if it supports pivots+ return !database || database.supportsPivots();+}++/**+ * Returns the pivot variant of `endpoint` when `card` renders as a pivot table,+ * otherwise the endpoint itself. The pivot endpoint takes the same request+ * argument, so the return type matches the input.+ */+export function maybeUsePivotEndpoint<Arg>(+ endpoint: QueryEndpoint<Arg>,+ card: Card,+ metadata: Metadata,+): QueryEndpoint<Arg> {+ if (!shouldUsePivotEndpoint(card, metadata)) {+ return endpoint;+ }+ return (PIVOT_ENDPOINTS.get(endpoint) as QueryEndpoint<Arg>) ?? endpoint;+}++/**+ * Dispatches an RTK Query endpoint and wires `signal` to RTK Query's `.abort()`.+ * Aborts surface as the standard `DOMException` AbortError (matching both+ * transports and `runRtkEndpoint`), so callers can `isAbortError`-check them.+ * `forceRefetch` makes each call hit the network rather than resolving from a+ * stale cache entry, matching the legacy fetch-and-discard behavior.+ */+export function dispatchQueryEndpoint<Arg>(+ dispatch: Dispatch,+ endpoint: QueryEndpoint<Arg>,+ requestBody: Arg,+ signal?: AbortSignal,+): Promise<Dataset> {+ // RTK's initiate() returns a thunk; dispatching it yields a result that+ // carries abort/unwrap/unsubscribe.+ const action = dispatch(+ endpoint.initiate(requestBody, { forceRefetch: true }) as never,+ ) as unknown as {+ abort?: () => void;+ unsubscribe?: () => void;+ unwrap: () => Promise<Dataset>;+ };++ const onAbort = () => action.abort?.();+ // The signal may already be aborted by the time we get here (e.g. the+ // user cancelled while we were awaiting a dynamic import in the caller).+ // In that case the "abort" event already fired and a listener won't run.+ if (signal?.aborted) {+ onAbort();+ } else {+ signal?.addEventListener("abort", onAbort, { once: true });+ }++ return action.unwrap().finally(() => action.unsubscribe?.());+}++/**+ * Builds a runner that selects the pivot or non-pivot variant of a query+ * endpoint for `card` and dispatches it. `signal` is wired to RTK Query's+ * abort, and aborts surface as the standard `DOMException` AbortError.+ */+export function makePivotAwareQueryRunner(+ dispatch: Dispatch,+ signal?: AbortSignal,+) {+ return <Endpoint extends QueryEndpoint<unknown>>(+ endpoint: Endpoint,+ card: Card,+ metadata: Metadata,+ args: ArgOf<Endpoint>,+ ): Promise<Dataset> =>+ dispatchQueryEndpoint(+ dispatch,+ maybeUsePivotEndpoint(endpoint, card, metadata),+ args,+ signal,+ );+}diff --git a/frontend/src/metabase/common/components/QuestionResultLoader.tsx b/frontend/src/metabase/common/components/QuestionResultLoader.tsxindex 453b8111744..93f134d29ed 100644--- a/frontend/src/metabase/common/components/QuestionResultLoader.tsx+++ b/frontend/src/metabase/common/components/QuestionResultLoader.tsx@@ -2,8 +2,8 @@ import type { ReactNode } from "react";import { useCallback, useEffect, useRef, useState } from "react";import { useEffectOnce } from "react-use";+import { runQuestionQuery } from "metabase/querying/run-query";import { useDispatch } from "metabase/redux";-import { runQuestionQuery } from "metabase/services";import type Question from "metabase-lib/v1/Question";import type { Dataset, RawSeries } from "metabase-types/api";diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.tsindex bfa577bdfeb..694657b8526 100644--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts@@ -4,7 +4,14 @@ import { denormalize, normalize, schema } from "normalizr";import { t } from "ttag";import _ from "underscore";-import { automagicDashboardsApi, cardApi, dashboardApi } from "metabase/api";+import {+ automagicDashboardsApi,+ cardApi,+ dashboardApi,+ embedApi,+ makePivotAwareQueryRunner,+ publicApi,+} from "metabase/api";import { isAbortError } from "metabase/api/legacy-client";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { applyParameters } from "metabase/common/utils/card";@@ -28,20 +35,13 @@ import {} from "metabase/dashboard/utils";import { getSavedDashboardUiParameters } from "metabase/parameters/utils/dashboards";import { getParameterValuesByIdFromQueryParams } from "metabase/parameters/utils/parameter-parsing";+import { runAdhocDatasetQuery } from "metabase/querying/run-query";import { updateMetadata } from "metabase/redux/metadata";import type { Dispatch, GetState } from "metabase/redux/store";import { createAsyncThunk, createThunkAction } from "metabase/redux/utils";import { FieldSchema } from "metabase/schema";import { getMetadata } from "metabase/selectors/metadata";-import {- AutoApi,- DashboardApi,- EmbedApi,- PublicApi,- maybeUsePivotEndpoint,- runAdhocDatasetQuery,- shouldUsePivotEndpoint,-} from "metabase/services";+import { AutoApi, DashboardApi, EmbedApi, PublicApi } from "metabase/services";import {getDashboardType,isQuestionDashCard,@@ -330,47 +330,33 @@ export const fetchCardDataAction = createAsyncThunk<);const metadata = getMetadata(getState());- const queryOptions = {- signal: controller.signal,- };+ const runQuery = makePivotAwareQueryRunner(dispatch, controller.signal);if (dashboardType === "public") {result = (await fetchDataOrError(- maybeUsePivotEndpoint(- PublicApi.dashboardCardQuery,- card,- metadata,- )(- {- uuid: dashcard.dashboard_id,- dashcardId: dashcard.id,- cardId: card.id,- parameters: datasetQuery.parameters- ? JSON.stringify(datasetQuery.parameters)- : undefined,- ignore_cache: ignoreCache,- },- queryOptions,- ),+ runQuery(publicApi.endpoints.getPublicDashcardQuery, card, metadata, {+ // In public dashboards `dashboard_id` holds the public UUID string.+ uuid: dashcard.dashboard_id as string,+ dashcardId: dashcard.id,+ cardId: card.id,+ parameters: datasetQuery.parameters+ ? JSON.stringify(datasetQuery.parameters)+ : undefined,+ ignore_cache: ignoreCache,+ }),)) as Dataset | { error: unknown };} else if (dashboardType === "embed") {result = (await fetchDataOrError(- maybeUsePivotEndpoint(- EmbedApi.dashboardCardQuery,- card,- metadata,- )(- {- token: dashcard.dashboard_id,- dashcardId: dashcard.id,- cardId: card.id,- parameters: JSON.stringify(- getParameterValuesBySlug(dashboard.parameters, parameterValues),- ),- ignore_cache: ignoreCache,- },- queryOptions,- ),+ runQuery(embedApi.endpoints.getEmbedDashcardQuery, card, metadata, {+ // In embedded dashboards `dashboard_id` holds the embed token string.+ token: dashcard.dashboard_id as string,+ dashcardId: dashcard.id,+ cardId: card.id,+ parameters: JSON.stringify(+ getParameterValuesBySlug(dashboard.parameters, parameterValues),+ ),+ ignore_cache: ignoreCache,+ }),)) as Dataset | { error: unknown };} else if (dashboardType === "transient" || dashboardType === "inline") {result = (await fetchDataOrError(@@ -400,39 +386,28 @@ export const fetchCardDataAction = createAsyncThunk<// new dashcards and new additional series cards aren't yet saved to the dashboard, so they need to be run using the card query endpointif (shouldUseCardQueryEndpoint) {- const cardQueryEndpoint = shouldUsePivotEndpoint(card, metadata)- ? cardApi.endpoints.getCardQueryPivot- : cardApi.endpoints.getCardQuery;- const queryAction = dispatch(- cardQueryEndpoint.initiate(- { cardId: card.id, ignore_cache: ignoreCache },- { forceRefetch: true },- ),- );- controller.signal.addEventListener("abort", () => queryAction.abort());- try {- result = (await fetchDataOrError(queryAction.unwrap())) as- | Dataset- | { error: unknown };- } finally {- queryAction.unsubscribe?.();- }+ result = (await fetchDataOrError(+ runQuery(cardApi.endpoints.getCardQuery, card, metadata, {+ cardId: card.id,+ ignore_cache: ignoreCache,+ }),+ )) as Dataset | { error: unknown };} else {- const requestBody = {- dashboardId: dashcard.dashboard_id,- dashcardId: dashcard.id,- cardId: card.id,- parameters: datasetQuery.parameters,- ignore_cache: ignoreCache,- dashboard_id: dashcard.dashboard_id,- dashboard_load_id: dashboardLoadId,- };result = (await fetchDataOrError(- maybeUsePivotEndpoint(- DashboardApi.cardQuery,+ runQuery(+ dashboardApi.endpoints.getDashboardCardQuery,card,metadata,- )(requestBody, queryOptions),+ {+ dashboardId: dashcard.dashboard_id,+ dashcardId: dashcard.id,+ cardId: card.id,+ parameters: datasetQuery.parameters,+ ignore_cache: ignoreCache,+ dashboard_id: dashcard.dashboard_id,+ dashboard_load_id: dashboardLoadId,+ },+ ),)) as Dataset | { error: unknown };}}diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts b/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.tsindex ac0cc515067..d98389cbd4e 100644--- a/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts+++ b/frontend/src/metabase/dashboard/actions/data-fetching.unit.spec.ts@@ -273,18 +273,39 @@ describe("fetchDashboard", () => {});/**- * Creates a mock dispatch/getState pair that executes thunks but skips the- * Redux store, avoiding the Immer/icepick incompatibility in dashcardData- * reducer when multiple fulfilled actions arrive.+ * Creates a dispatch/getState pair that runs thunks against the mock dashboard+ * `state` but routes RTK Query lifecycle actions to a real (api-only) store, so+ * the RTK-backed dashcard query endpoints execute. The dashboard `dashcardData`+ * reducer is intentionally bypassed: it uses icepick `assocIn`, which crashes+ * under Immer when many fulfilled actions arrive at once (the case these+ * concurrency tests provoke).*/-function createMockDispatch(getState: () => Partial<State>) {- const dispatch = (action: unknown): unknown => {+function createMockDispatch(getMockState: () => Partial<State>) {+ const apiStore = getStore({ [Api.reducerPath]: Api.reducer }, {}, [+ Api.middleware,+ ]);++ const getState = (): Partial<State> => ({+ ...getMockState(),+ [Api.reducerPath]: apiStore.getState()[Api.reducerPath],+ });++ const dispatch = (action: any): any => {if (typeof action === "function") {return action(dispatch, getState);}+ // RTK Query lifecycle actions need the real api store + middleware; other+ // (dashboard) plain actions don't affect what these tests assert.+ if (+ typeof action?.type === "string" &&+ action.type.startsWith(`${Api.reducerPath}/`)+ ) {+ return apiStore.dispatch(action);+ }return Promise.resolve(action);};- return dispatch;++ return { dispatch, getState };}function setupConcurrencyTest(dashboardId: number, cardCount: number) {@@ -332,8 +353,7 @@ function setupConcurrencyTest(dashboardId: number, cardCount: number) {settings: createMockSettingsState(),};- const getState = () => state;- const dispatch = createMockDispatch(getState);+ const { dispatch, getState } = createMockDispatch(() => state);return { dispatch, getState, getMaxConcurrent: () => maxConcurrent };}@@ -422,8 +442,7 @@ describe("fetchDashboardCardData", () => {settings: createMockSettingsState(),};- const getState = () => state;- const dispatch = createMockDispatch(getState);+ const { dispatch, getState } = createMockDispatch(() => state);// Start loading Tab 1 (slow query)const tab1Fetch = fetchDashboardCardData()(diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsxindex 49992230f27..cd7e2e9dd8a 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion.tsx@@ -2,6 +2,7 @@ import type { Location } from "history";import { useCallback, useEffect, useState } from "react";import { useLatest, useMount } from "react-use";+import { embedApi, makePivotAwareQueryRunner, publicApi } from "metabase/api";import { applyParameters } from "metabase/common/utils/card";import { fetchDataOrError } from "metabase/dashboard/utils";import { LocaleProvider } from "metabase/embedding/LocaleProvider";@@ -16,7 +17,7 @@ import { updateMetadata } from "metabase/redux/metadata";import { FieldSchema } from "metabase/schema";import { getMetadata } from "metabase/selectors/metadata";import { getCanWhitelabel } from "metabase/selectors/whitelabel";-import { EmbedApi, PublicApi, maybeUsePivotEndpoint } from "metabase/services";+import { EmbedApi, PublicApi } from "metabase/services";import { getCardUiParameters } from "metabase-lib/v1/parameters/utils/cards";import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";import { getParametersFromCard } from "metabase-lib/v1/parameters/utils/template-tags";@@ -124,21 +125,22 @@ export const PublicOrEmbeddedQuestion = ({try {setResult(null);- let newResult: Dataset | { error: unknown };+ const runQuery = makePivotAwareQueryRunner(dispatch);++ let resultPromise: Promise<Dataset>;if (token) {// embeds apply parameter values server-side- newResult = (await fetchDataOrError(- maybeUsePivotEndpoint(- EmbedApi.cardQuery,- card,- metadataRef.current,- )({+ resultPromise = runQuery(+ embedApi.endpoints.getEmbedCardQuery,+ card,+ metadataRef.current,+ {token,parameters: JSON.stringify(getParameterValuesBySlug(parameters, parameterValues),),- }),- )) as Dataset | { error: unknown };+ },+ );} else if (uuid) {// public links currently apply parameters client-sideconst datasetQuery = applyParameters(@@ -148,20 +150,23 @@ export const PublicOrEmbeddedQuestion = ({[],{ sparse: true },);- newResult = (await fetchDataOrError(- maybeUsePivotEndpoint(- PublicApi.cardQuery,- card,- metadataRef.current,- )({+ resultPromise = runQuery(+ publicApi.endpoints.getPublicCardQuery,+ card,+ metadataRef.current,+ {uuid,parameters: JSON.stringify(datasetQuery.parameters),- }),- )) as Dataset | { error: unknown };+ },+ );} else {throw { status: 404 };}+ const newResult = (await fetchDataOrError(resultPromise)) as+ | Dataset+ | { error: unknown };+// If error is object it is because it was a non-query errorif (typeof newResult.error === "object") {dispatch(setErrorPage(newResult.error));diff --git a/frontend/src/metabase/query_builder/actions/querying.ts b/frontend/src/metabase/query_builder/actions/querying.tsindex ee459a37d44..3cee8bc5cf7 100644--- a/frontend/src/metabase/query_builder/actions/querying.ts+++ b/frontend/src/metabase/query_builder/actions/querying.ts@@ -2,6 +2,7 @@ import { createAction } from "redux-actions";import { t } from "ttag";import { isAbortError } from "metabase/api/legacy-client";+import { runQuestionQuery as apiRunQuestionQuery } from "metabase/querying/run-query";import { syncVizSettingsWithSeries } from "metabase/querying/viz-settings/utils/sync-viz-settings";import { createThunkAction } from "metabase/redux";import {@@ -15,7 +16,6 @@ import {} from "metabase/redux/query-builder";import type { Dispatch, GetState } from "metabase/redux/store";import { getWhiteLabeledLoadingMessageFactory } from "metabase/selectors/whitelabel";-import { runQuestionQuery as apiRunQuestionQuery } from "metabase/services";import { getSensibleDisplays } from "metabase/visualizations";import * as Lib from "metabase-lib";import type Question from "metabase-lib/v1/Question";diff --git a/frontend/src/metabase/querying/run-query.ts b/frontend/src/metabase/querying/run-query.tsnew file mode 100644index 00000000000..b15d0316378--- /dev/null+++ b/frontend/src/metabase/querying/run-query.ts@@ -0,0 +1,223 @@+import { cardApi } from "metabase/api/card";+import { dashboardApi } from "metabase/api/dashboard";+import { datasetApi } from "metabase/api/dataset";+import {+ dispatchQueryEndpoint,+ makePivotAwareQueryRunner,+ shouldUsePivotEndpoint,+} from "metabase/api/query-endpoints";+import type { Dispatch } from "metabase/redux/store";+import Question from "metabase-lib/v1/Question";+import type Metadata from "metabase-lib/v1/metadata/Metadata";+import { normalizeParameters } from "metabase-lib/v1/parameters/utils/parameter-values";+import { getPivotOptions } from "metabase-lib/v1/queries/utils/pivot";+import type {+ Card,+ CardQueryRequest,+ DashboardCardQueryRequest,+ Dataset,+ DatasetQuery,+} from "metabase-types/api";++type RunQuestionQueryOptions = {+ dispatch: Dispatch;+ signal?: AbortSignal;+ isDirty?: boolean;+ token?: string | null;+ ignoreCache?: boolean;+ collectionPreview?: boolean;+ // Ability to override or add extra query params to the request, used by Embedding SDK+ queryParamsOverride?: Record<string, unknown>;+};++type SavedCardQueryOptions = {+ parameters: unknown[];+ ignoreCache?: boolean;+ collectionPreview?: boolean;+ token?: string | null;+ queryParamsOverride?: Record<string, unknown>;+};++/**+ * Handles API errors for query endpoints. For 4xx errors from streaming query+ * endpoints, the error response body contains the actual error data that should+ * be displayed (just like the old 202-with-error-in-body behavior). This function+ * converts 4xx errors into successful responses with the error data.+ */+async function handleQueryApiError(+ apiPromise: Promise<Dataset>,+): Promise<Dataset> {+ try {+ return await apiPromise;+ } catch (error) {+ // For 4xx errors, treat the error response body as a successful response+ // (maintaining compatibility with the old 202-with-error-in-body behavior)+ if (+ error != null &&+ typeof error === "object" &&+ "status" in error &&+ typeof error.status === "number" &&+ error.status >= 400 &&+ error.status < 500 &&+ "data" in error &&+ error.data+ ) {+ // The QP returns a structured `{ error, error_type, ... }` body, but+ // plainer endpoints (e.g. `/api/embed/*` API-level checks) return a+ // plain-text body. Normalize so callers can rely on a `{ error, ... }`+ // shape and don't fall through to the empty state (EMB-1659).+ if (typeof error.data === "string") {+ return {+ error: error.data,+ status: error.status,+ } as unknown as Dataset;+ }+ return error.data as Dataset;+ }+ // For 5xx and other errors, re-throw+ throw error;+ }+}++// Dispatches the RTK `datasetApi` ad-hoc query endpoint (pivot or non-pivot).+let adhocDatasetQueryCounter = 0;+export function runAdhocDatasetQuery(+ dispatch: Dispatch,+ card: Card,+ metadata: Metadata,+ body: DatasetQuery & { parameters?: unknown[]; ignore_cache?: boolean },+ signal?: AbortSignal,+): Promise<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;++ return dispatchQueryEndpoint(dispatch, endpoint, requestBody, signal);+}++// Dispatches the RTK saved-card query endpoint, picking the card vs. dashcard+// route (and their pivot variants). Guest embeds rely on the legacy-client+// `onBeforeRequest` middleware (which RTK requests still pass through) rewriting+// the card route to `/api/embed/card/:token/query` when `token` is in the body.+let savedCardQueryCounter = 0;+function runSavedCardQuery(+ dispatch: Dispatch,+ question: Question,+ {+ parameters,+ ignoreCache,+ collectionPreview,+ token,+ queryParamsOverride,+ }: SavedCardQueryOptions,+ signal?: AbortSignal,+): Promise<Dataset> {+ const card = question.card();+ const metadata = question.metadata();+ const { dashboardId, dashcardId } = question.getDashboardProps();+ const runQuery = makePivotAwareQueryRunner(dispatch, signal);++ const body = {+ ignore_cache: ignoreCache,+ collection_preview: collectionPreview,+ parameters,+ // Disambiguate the RTK cache key so two callers running the same saved card+ // don't co-subscribe to one in-flight request — otherwise one caller+ // aborting its query (e.g. the SDK cancelling the previous run on every+ // re-run) aborts every co-subscriber's query too. Stripped from the body+ // before it hits the server. Mirrors `runAdhocDatasetQuery`.+ _refetchDeps: ++savedCardQueryCounter,+ // `token` and `cardId` identify the card in mutually exclusive ways, so we+ // send only one (mirroring the original services.js behavior). Guest and+ // embedded requests carry a `token`: the legacy `onBeforeRequest` middleware+ // rewrites the request to the matching `/api/embed/...` route, discarding+ // the `:cardId` path segment. Authenticated requests carry a `cardId`.+ // The casts below are needed because the shared request types require+ // `cardId`; we keep that contract strict for every other (authenticated)+ // caller and override it only here, on the guest-embed path.+ ...(token ? { token } : { cardId: question.id() }),+ ...queryParamsOverride,+ };++ if (dashboardId != null && dashcardId != null) {+ return runQuery(+ dashboardApi.endpoints.getDashboardCardQuery,+ card,+ metadata,+ {+ dashboardId,+ dashcardId,+ ...body,+ } as DashboardCardQueryRequest,+ );+ }++ return runQuery(+ cardApi.endpoints.getCardQuery,+ card,+ metadata,+ body as CardQueryRequest,+ );+}++export async function runQuestionQuery(+ question: Question,+ {+ dispatch,+ signal,+ isDirty = false,+ token,+ ignoreCache = false,+ collectionPreview = false,+ queryParamsOverride = {},+ }: RunQuestionQueryOptions,+): Promise<[Dataset]> {+ const canUseCardApiEndpoint = !isDirty && question.isSaved();+ const parameters = normalizeParameters(+ question.parameters({ collectionPreview }),+ );+ const card = question.card();++ if (canUseCardApiEndpoint) {+ return [+ await handleQueryApiError(+ runSavedCardQuery(+ dispatch,+ question,+ {+ parameters,+ ignoreCache,+ collectionPreview,+ token,+ queryParamsOverride,+ },+ signal,+ ),+ ),+ ];+ }++ return [+ await handleQueryApiError(+ runAdhocDatasetQuery(+ dispatch,+ card,+ question.metadata(),+ { ...question.datasetQuery(), parameters },+ signal,+ ),+ ),+ ];+}diff --git a/frontend/src/metabase/services.unit.spec.ts b/frontend/src/metabase/querying/run-query.unit.spec.tssimilarity index 76%rename from frontend/src/metabase/services.unit.spec.tsrename to frontend/src/metabase/querying/run-query.unit.spec.tsindex e41c9369ce4..c1ffacd5789 100644--- a/frontend/src/metabase/services.unit.spec.ts+++ b/frontend/src/metabase/querying/run-query.unit.spec.ts@@ -25,7 +25,7 @@ import {createSampleDatabase,} from "metabase-types/api/mocks/presets";-import { runQuestionQuery } from "./services";+import { runQuestionQuery } from "./run-query";const MOCK_QUERY = createMockStructuredDatasetQuery({database: SAMPLE_DB_ID,@@ -103,7 +103,7 @@ async function setupRunQuestionQuery(question: Question) {return { result, mockResult };}-describe("metabase/services > runQuestionQuery", () => {+describe("metabase/querying/run-query > runQuestionQuery", () => {describe("saved questions", () => {it("should use the card query endpoint", async () => {const question = createMockSavedQuestion();@@ -212,6 +212,25 @@ describe("metabase/services > runQuestionQuery", () => {const { result, mockResult } = await setupRunQuestionQuery(question);expect(result).toEqual([mockResult]);});++ it("runs `internal` queries (e.g. audit pages) without throwing in the pivot check", async () => {+ // `internal` queries aren't supported by Lib, so `question.database()`+ // throws for them. The pivot-endpoint check must not call it for a+ // non-pivot card, otherwise the query never reaches `/api/dataset` (the+ // audit "Erroring Questions" table renders nothing).+ const question = createMockAdHocQuestion({+ dataset_query: {+ type: "internal",+ fn: "metabase-enterprise.audit-app.pages.queries/bad-table",+ args: [null, null, null, "last_run_at", "desc"],+ } as unknown as UnsavedCard["dataset_query"],+ });++ const { result, mockResult } = await setupRunQuestionQuery(question);++ expect(fetchMock.callHistory.calls("path:/api/dataset")).toHaveLength(1);+ expect(result).toEqual([mockResult]);+ });});describe("error handling", () => {@@ -300,6 +319,58 @@ describe("metabase/services > runQuestionQuery", () => {await expect(runPromise).rejects.toMatchObject({ name: "AbortError" });});+ it("rejects with AbortError when the signal aborts (saved question)", async () => {+ // The saved-card path dispatches an RTK Query endpoint; aborting the+ // signal must abort the underlying `/api/card/:id/query` request and+ // reject with the standard `DOMException` AbortError that `queryErrored`+ // and other callers identify via `isAbortError`.+ const question = createMockSavedQuestion();+ fetchMock.post(+ getQueryEndpointPath(question),+ new Promise(() => undefined),+ );++ const controller = new AbortController();+ const runPromise = runQuestionQuery(question, {+ dispatch: getRtkStore().dispatch,+ signal: controller.signal,+ });++ controller.abort();++ await expect(runPromise).rejects.toMatchObject({ name: "AbortError" });+ });++ it("isolates concurrent identical saved-card queries so cancelling one doesn't abort the other", async () => {+ // Two callers running the same saved card must not co-subscribe to a+ // single RTK Query request: otherwise one caller aborting (e.g. the SDK+ // cancelling the previous run on every re-run) would abort the other's+ // query too, hanging/blanking the result. A unique `_refetchDeps` per+ // call keeps the cache keys — and therefore the requests — distinct.+ const question = createMockSavedQuestion();+ const path = getQueryEndpointPath(question);+ fetchMock.post(path, createMockDataset(), { delay: 50 });+ const { dispatch } = getRtkStore();++ const abortController = new AbortController();+ const cancelledRun = runQuestionQuery(question, {+ dispatch,+ signal: abortController.signal,+ }).catch((error) => error);+ const liveRun = runQuestionQuery(question, {+ dispatch,+ signal: new AbortController().signal,+ });++ abortController.abort();++ await expect(liveRun).resolves.toHaveLength(1);+ await cancelledRun;++ // Independent cache keys ⇒ two real requests, not one shared (deduped) one.+ expect(fetchMock.callHistory.calls(path)).toHaveLength(2);+ });+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. Withoutdiff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.jsindex 497a335b654..dd385ce6618 100644--- a/frontend/src/metabase/services.js+++ b/frontend/src/metabase/services.js@@ -1,9 +1,5 @@import { DELETE, GET, POST, PUT } from "metabase/api/legacy-client";-import { isNative } from "metabase/common/utils/card";import { isEmbedPreview } from "metabase/embedding/config";-import Question from "metabase-lib/v1/Question";-import { normalizeParameters } from "metabase-lib/v1/parameters/utils/parameter-values";-import { getPivotOptions } from "metabase-lib/v1/queries/utils/pivot";export const internalBase = "/api";export const publicBase = "/api/public";@@ -29,217 +25,11 @@ export const StoreApi = {tokenStatus: GET("/api/premium-features/token/status"),};-/**- * Handles API errors for query endpoints. For 4xx errors from streaming query- * endpoints, the error response body contains the actual error data that should- * be displayed (just like the old 202-with-error-in-body behavior). This function- * converts 4xx errors into successful responses with the error data.- *- * @param {Promise} apiPromise - The API promise to handle- * @returns {Promise} The result or error data- */-async function handleQueryApiError(apiPromise) {- try {- return await apiPromise;- } catch (error) {- // For 4xx errors, treat the error response body as a successful response- // (maintaining compatibility with the old 202-with-error-in-body behavior)- if (- error &&- typeof error === "object" &&- error.status >= 400 &&- error.status < 500 &&- error.data- ) {- // The QP returns a structured `{ error, error_type, ... }` body, but- // plainer endpoints (e.g. `/api/embed/*` API-level checks) return a- // plain-text body. Normalize so callers can rely on a `{ error, ... }`- // shape and don't fall through to the empty state (EMB-1659).- if (typeof error.data === "string") {- return { error: error.data, status: error.status };- }- return error.data;- }- // For 5xx and other errors, re-throw- throw error;- }-}--// Pivot tables need extra data beyond what's described in the MBQL query itself.-// To fetch that extra data we rely on specific APIs for pivot tables that mirrow the normal endpoints.-// Those endpoints take the query along with `pivot_rows` and `pivot_cols` to return the subtotal data.-// If we add breakout/grouping sets to MBQL in the future we can remove this API switching.-export function shouldUsePivotEndpoint(card, metadata) {- const question = new Question(card, metadata);- return (- question.display() === "pivot" &&- !isNative(card) &&- // if we have metadata for the db, check if it supports pivots- (!question.database() || question.database().supportsPivots())- );-}--export function maybeUsePivotEndpoint(api, card, metadata) {- if (!shouldUsePivotEndpoint(card, metadata)) {- return api;- }-- const mapping = [- [CardApi.query, CardApi.query_pivot],- [DashboardApi.cardQuery, DashboardApi.cardQueryPivot],- [PublicApi.cardQuery, PublicApi.cardQueryPivot],- [PublicApi.dashboardCardQuery, PublicApi.dashboardCardQueryPivot],- [EmbedApi.cardQuery, EmbedApi.cardQueryPivot],- [EmbedApi.dashboardCardQuery, EmbedApi.dashboardCardQueryPivot],- ];- for (const [from, to] of mapping) {- if (api === from) {- return to;- }- }- return api;-}--// Dispatches the RTK `datasetApi` ad-hoc query endpoint (pivot or non-pivot)-// and wires the `signal` to RTK Query's `.abort()`. On abort it surfaces the-// standard `DOMException` AbortError so existing error-handling code keeps-// working via `isAbortError(error)`.-let adhocDatasetQueryCounter = 0;-export async function runAdhocDatasetQuery(- dispatch,- card,- metadata,- body,- signal,-) {- // 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;- const onAbort = () => {- isCancelled = true;- action.abort?.();- };- // The signal may already be aborted by the time we get here (e.g. the- // user cancelled while we were awaiting the dynamic import above). In- // that case the "abort" event already fired and a listener won't run.- if (signal?.aborted) {- onAbort();- } else {- signal?.addEventListener("abort", onAbort, { once: true });- }-- return action- .unwrap()- .catch((error) => {- if (isCancelled) {- throw signal?.reason ?? new DOMException("Aborted", "AbortError");- }- throw error;- })- .finally(() => action.unsubscribe?.());-}--/**- * @param {*} question- * @param {object} param- */-export async function runQuestionQuery(- question,- {- dispatch,- signal,- isDirty = false,- token,- ignoreCache = false,- collectionPreview = false,- // Ability to override or add extra query params to the request, used by Embedding SDK- queryParamsOverride = {},- } = {},-) {- const canUseCardApiEndpoint = !isDirty && question.isSaved();- const parameters = normalizeParameters(- question.parameters({ collectionPreview }),- );- const card = question.card();-- if (canUseCardApiEndpoint) {- const { dashboardId, dashcardId } = question.getDashboardProps();-- const queryParams = {- ...(token ? { token } : { cardId: question.id() }),- dashboardId,- dashcardId,- ignore_cache: ignoreCache,- collection_preview: collectionPreview,- parameters,- ...queryParamsOverride,- };-- return [- await handleQueryApiError(- maybeUsePivotEndpoint(- dashboardId ? DashboardApi.cardQuery : CardApi.query,- card,- question.metadata(),- )(queryParams, {- signal,- }),- ),- ];- }-- return [- await handleQueryApiError(- runAdhocDatasetQuery(- dispatch,- card,- question.metadata(),- { ...question.datasetQuery(), parameters },- signal,- ),- ),- ];-}--export const CardApi = {- query: POST("/api/card/:cardId/query"),- query_pivot: POST("/api/card/pivot/:cardId/query"),-};-export const DashboardApi = {get: GET("/api/dashboard/:dashId"),parameterValues: GET("/api/dashboard/:dashId/params/:paramId/values"),parameterSearch: GET("/api/dashboard/:dashId/params/:paramId/search/:query"),validFilterFields: GET("/api/dashboard/params/valid-filter-fields"),- cardQuery: POST(- "/api/dashboard/:dashboardId/dashcard/:dashcardId/card/:cardId/query",- ),- cardQueryPivot: POST(- "/api/dashboard/pivot/:dashboardId/dashcard/:dashcardId/card/:cardId/query",- ),};export const CollectionsApi = {@@ -248,8 +38,6 @@ export const CollectionsApi = {updateGraph: PUT("/api/collection/graph?skip-graph=true"),};-const PIVOT_PUBLIC_PREFIX = `${publicBase}/pivot/`;-export const PublicApi = {action: GET(`${publicBase}/action/:uuid`),executeDashcardAction: POST(@@ -257,15 +45,7 @@ export const PublicApi = {),executeAction: POST(`${publicBase}/action/:uuid/execute`),card: GET(`${publicBase}/card/:uuid`),- cardQuery: GET(`${publicBase}/card/:uuid/query`),- cardQueryPivot: GET(PIVOT_PUBLIC_PREFIX + "card/:uuid/query"),dashboard: GET(`${publicBase}/dashboard/:uuid`),- dashboardCardQuery: GET(- `${publicBase}/dashboard/:uuid/dashcard/:dashcardId/card/:cardId`,- ),- dashboardCardQueryPivot: GET(- PIVOT_PUBLIC_PREFIX + "dashboard/:uuid/dashcard/:dashcardId/card/:cardId",- ),prefetchDashcardValues: GET(`${publicBase}/dashboard/:dashboardId/dashcard/:dashcardId/execute`,),@@ -275,16 +55,7 @@ export const PublicApi = {export const EmbedApi = {card: GET(getEmbedBase() + "/card/:token"),- cardQuery: GET(getEmbedBase() + "/card/:token/query"),- cardQueryPivot: GET(getEmbedBase() + "/pivot/card/:token/query"),dashboard: GET(getEmbedBase() + "/dashboard/:token"),- dashboardCardQuery: GET(- getEmbedBase() + "/dashboard/:token/dashcard/:dashcardId/card/:cardId",- ),- dashboardCardQueryPivot: GET(- getEmbedBase() +- "/pivot/dashboard/:token/dashcard/:dashcardId/card/:cardId",- ),};export const AutoApi = {