Skip to content

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

Build parameter fields from param_fields, not the metadata store (#81935)

Romeo Van Snick6ed9837a03bc
diff --git a/frontend/src/metabase-lib/v1/parameters/types.ts b/frontend/src/metabase-lib/v1/parameters/types.ts
index af183f714a4..18482d1ae3c 100644
--- a/frontend/src/metabase-lib/v1/parameters/types.ts
+++ b/frontend/src/metabase-lib/v1/parameters/types.ts
@@ -1,16 +1,37 @@
-import type Field from "metabase-lib/v1/metadata/Field";
+import type { RemappableField } from "metabase-lib/v1/metadata/utils/remapping";
import type {
+ FieldFormattingSettings,
+ FieldValue,
+ FieldValuesType,
Parameter,
ParameterTarget,
ParameterValueOrArray,
+ TableId,
} from "metabase-types/api";
+/**
+ * What a parameter widget reads off a field it filters on.
+ *
+ * The API field and the v1 `Field` wrapper both match it. They are not
+ * assignable to each other, because the wrapper hydrates `table` into a v1
+ * `Table`, so the parameter pipeline names the fields it reads instead.
+ */
+export interface ParameterField extends RemappableField<ParameterField> {
+ name: string;
+ display_name: string;
+ table_id: TableId;
+ has_field_values: FieldValuesType;
+ has_more_values?: boolean;
+ values?: FieldValue[];
+ settings?: FieldFormattingSettings;
+}
+
interface ValuePopulatedParameter extends ParameterWithTemplateTagTarget {
value?: ParameterValueOrArray | null;
}
export interface FieldFilterUiParameter extends ValuePopulatedParameter {
- fields: Field[];
+ fields: ParameterField[];
}
export type UiParameter = (FieldFilterUiParameter | ValuePopulatedParameter) & {
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/cards.ts b/frontend/src/metabase-lib/v1/parameters/utils/cards.ts
index d7a39f1225d..c44ee4a33f2 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/cards.ts
+++ b/frontend/src/metabase-lib/v1/parameters/utils/cards.ts
@@ -1,6 +1,5 @@
import _ from "underscore";
-import { isNotNull } from "metabase/utils/types";
import Question from "metabase-lib/v1/Question";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import type {
@@ -35,7 +34,7 @@ export function getCardUiParameters(
});
return hasParamFields(card)
- ? getSavedCardUiParameters(card, metadata, valuePopulatedParameters)
+ ? getSavedCardUiParameters(card, valuePopulatedParameters)
: getUnsavedCardUiParameters(card, metadata, valuePopulatedParameters);
}
@@ -55,15 +54,14 @@ function hasParamFields(card: SeriesCard) {
*/
function getSavedCardUiParameters(
card: SeriesCard,
- metadata: Metadata,
parameters: Parameter[] | ParameterWithTarget[],
): UiParameter[] {
return parameters.map((parameter) => {
const target = getParameterTarget(parameter);
- const parameterFields = (card.param_fields?.[parameter.id] ?? [])
- .map((field) => metadata.field(field.id))
- .filter(isNotNull);
- const fields = _.uniq(parameterFields, (field) => field.id);
+ const fields = _.uniq(
+ card.param_fields?.[parameter.id] ?? [],
+ (field) => field.id,
+ );
if (fields.length > 0) {
return {
...parameter,
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/cards.unit.spec.ts b/frontend/src/metabase-lib/v1/parameters/utils/cards.unit.spec.ts
index f17f8a8623f..ce7c88dd529 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/cards.unit.spec.ts
+++ b/frontend/src/metabase-lib/v1/parameters/utils/cards.unit.spec.ts
@@ -39,30 +39,25 @@ describe("parameters/utils/cards", () => {
});
describe("saved cards", () => {
- it("should get parameter fields from param_fields via metadata", () => {
- const metadata = createMockMetadata({
- fields: [createMockField({ id: 1 }), createMockField({ id: 2 })],
- });
+ it("should get parameter fields from param_fields, without duplicates", () => {
+ const firstField = createMockField({ id: 1 });
+ const secondField = createMockField({ id: 2 });
const card = createMockCard({
id: 1,
parameters: [dateParameter, variableParameter],
param_fields: {
- [dateParameter.id]: [
- createMockField({ id: 1 }),
- createMockField({ id: 2 }),
- createMockField({ id: 1 }),
- ],
+ [dateParameter.id]: [firstField, secondField, firstField],
},
});
const [dateUiParameter, variableUiParameter] = getCardUiParameters(
card,
- metadata,
+ createMockMetadata({}),
);
expect(dateUiParameter).toMatchObject({
id: dateParameter.id,
- fields: [metadata.field(1), metadata.field(2)],
+ fields: [firstField, secondField],
hasVariableTemplateTagTarget: false,
});
expect(variableUiParameter).toMatchObject({
@@ -72,23 +67,26 @@ describe("parameters/utils/cards", () => {
expect(variableUiParameter).not.toHaveProperty("fields");
});
- it("should ignore fields missing from metadata", () => {
- const metadata = createMockMetadata({ fields: [] });
+ it("should use a param_fields field the metadata store never loaded", () => {
+ // the backend hydrates param_fields for this card, so a field is
+ // there to be used whether or not another request put it in the store
+ const field = createMockField({ id: 1 });
const card = createMockCard({
id: 1,
parameters: [dateParameter],
- param_fields: {
- [dateParameter.id]: [createMockField({ id: 1 })],
- },
+ param_fields: { [dateParameter.id]: [field] },
});
- const [dateUiParameter] = getCardUiParameters(card, metadata);
+ const [dateUiParameter] = getCardUiParameters(
+ card,
+ createMockMetadata({ fields: [] }),
+ );
expect(dateUiParameter).toMatchObject({
id: dateParameter.id,
+ fields: [field],
hasVariableTemplateTagTarget: false,
});
- expect(dateUiParameter).not.toHaveProperty("fields");
});
it("should not resolve parameter fields from the query", () => {
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/parameter-fields.ts b/frontend/src/metabase-lib/v1/parameters/utils/parameter-fields.ts
index 07ce50d9e9a..3a2d52aa1b4 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/parameter-fields.ts
+++ b/frontend/src/metabase-lib/v1/parameters/utils/parameter-fields.ts
@@ -1,6 +1,6 @@
-import type Field from "metabase-lib/v1/metadata/Field";
import type {
FieldFilterUiParameter,
+ ParameterField,
UiParameter,
} from "metabase-lib/v1/parameters/types";
@@ -14,7 +14,7 @@ export const hasFields = (parameter: UiParameter) => {
return isFieldFilterUiParameter(parameter) && parameter.fields.length > 0;
};
-export const getFields = (parameter: UiParameter): Field[] => {
+export const getFields = (parameter: UiParameter): ParameterField[] => {
if (isFieldFilterUiParameter(parameter) && hasFields(parameter)) {
return parameter.fields;
} else {
@@ -23,5 +23,5 @@ export const getFields = (parameter: UiParameter): Field[] => {
};
export const getNonVirtualFields = (parameter: UiParameter) => {
- return getFields(parameter).filter((field) => !field.isVirtual());
+ return getFields(parameter).filter((field) => typeof field.id === "number");
};
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.ts b/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.ts
index e9da076bc23..20c4db3fe63 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.ts
+++ b/frontend/src/metabase-lib/v1/parameters/utils/parameter-source.ts
@@ -1,5 +1,12 @@
-import Field from "metabase-lib/v1/metadata/Field";
+import {
+ getSearchField,
+ getSharedRemappedField,
+} from "metabase-lib/v1/metadata/utils/remapping";
import { isFuzzyOperator } from "metabase-lib/v1/operators/utils";
+import type {
+ ParameterField,
+ ParameterWithTemplateTagTarget,
+} from "metabase-lib/v1/parameters/types";
import type {
Parameter,
ValuesQueryType,
@@ -7,8 +14,6 @@ import type {
ValuesSourceType,
} from "metabase-types/api";
-import type { ParameterWithTemplateTagTarget } from "../types";
-
import { deriveFieldOperatorFromParameter } from "./operators";
import { getFields } from "./parameter-fields";
import { getParameterType } from "./parameter-type";
@@ -46,9 +51,9 @@ export const getSourceConfig = (parameter: Parameter): ValuesSourceConfig => {
*/
export const hasRemappedParameterValues = (
parameter: Parameter | null | undefined,
- fields: Field[],
+ fields: ParameterField[],
): boolean => {
- if (Field.remappedField(fields) != null) {
+ if (getSharedRemappedField(fields) != null) {
return true;
}
@@ -122,10 +127,10 @@ export const canListParameterValues = (parameter: Parameter) => {
: queryType !== "none" && canListFields;
};
-export const canListFieldValues = (fields: Field[]) => {
+export const canListFieldValues = (fields: ParameterField[]) => {
const hasFields = fields.length > 0;
const hasFieldValues = fields
- .filter((field) => !field.isVirtual())
+ .filter((field) => typeof field.id === "number")
.every((field) => field.has_field_values === "list");
return hasFields && hasFieldValues;
@@ -151,12 +156,12 @@ export const canSearchParameterValues = (
};
export const canSearchFieldValues = (
- fields: Field[],
+ fields: ParameterField[],
disablePKRemapping = false,
) => {
const hasFields = fields.length > 0;
const canSearch = fields.every((field) =>
- field.searchField(disablePKRemapping),
+ getSearchField(field, disablePKRemapping),
);
const hasFieldValues = fields.some(
(field) =>
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index f5aa027dbaa..806c2c898cd 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -896,12 +896,10 @@ export const fetchDashboard = createAsyncThunk(
const lastUsedParametersValues = result["last_used_param_values"] ?? {};
- const metadata = getMetadata(getState());
const parameters = getSavedDashboardUiParameters(
result.dashcards,
result.parameters,
result.param_fields,
- metadata,
);
const parameterValuesById = preserveParameters
diff --git a/frontend/src/metabase/dashboard/selectors.ts b/frontend/src/metabase/dashboard/selectors.ts
index b50dbe897c8..b5aa5d13514 100644
--- a/frontend/src/metabase/dashboard/selectors.ts
+++ b/frontend/src/metabase/dashboard/selectors.ts
@@ -432,7 +432,6 @@ export const getParameters = createSelector(
dashboard.dashcards,
dashboard.parameters,
dashboard.param_fields,
- metadata,
);
},
);
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts
index c7cde68e3ec..0135f72a7de 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-available-parameters.ts
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef } from "react";
-import { useLatest, usePrevious } from "react-use";
+import { usePrevious } from "react-use";
import type { SdkIframeEmbedSetupExperience } from "metabase/embedding/embedding-iframe-sdk-setup/types";
import { getMetadata, paramFieldsFetched } from "metabase/metadata-store";
@@ -25,11 +25,6 @@ export const useAvailableParameters = ({
const initialAvailableParametersRef = useRef<Parameter[] | null>(null);
const prevResourceId = usePrevious(resource?.id);
- // This prevents `availableParameters` from being updated on every metadata change,
- // which would cause unnecessary re-renders in the component using this hook.
- // See [PublicOrEmbeddedQuestion.tsx] for reference.
- const metadataRef = useLatest(metadata);
-
// Extract parameters from the loaded dashboard/card
const availableParameters = useMemo((): Parameter[] => {
if (!resource) {
@@ -43,16 +38,15 @@ export const useAvailableParameters = ({
dashboard.dashcards,
dashboard.parameters,
dashboard.param_fields,
- metadata,
);
} else if (experience === "chart") {
// Unjustified type cast. FIXME
const card = resource as Card;
- return getCardUiParameters(card, metadataRef.current) || [];
+ return getCardUiParameters(card, metadata) || [];
}
return [];
- }, [resource, experience, metadata, metadataRef]);
+ }, [resource, experience, metadata]);
// Reset initial parameters when the resource changes
if (resource?.id !== prevResourceId) {
diff --git a/frontend/src/metabase/hoc/Remapped.tsx b/frontend/src/metabase/hoc/Remapped.tsx
index a5fdd92a965..51b92c59c5d 100644
--- a/frontend/src/metabase/hoc/Remapped.tsx
+++ b/frontend/src/metabase/hoc/Remapped.tsx
@@ -1,16 +1,16 @@
import { Component, type ComponentType } from "react";
-import { fetchRemapping, getMetadata } from "metabase/metadata-store";
+import { fetchRemapping, getRemappedFieldValue } from "metabase/metadata-store";
import { connect } from "metabase/redux";
import type { State } from "metabase/redux/store";
-import type Field from "metabase-lib/v1/metadata/Field";
-import type Metadata from "metabase-lib/v1/metadata/Metadata";
+import { getRemappedField } from "metabase-lib/v1/metadata/utils/remapping";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
type Remapping = [value: unknown, label: unknown];
interface RemappedOwnProps {
value?: unknown;
- column?: Field;
+ column?: ParameterField;
parameter?: { id?: unknown };
cardId?: unknown;
dashboardId?: unknown;
@@ -19,7 +19,8 @@ interface RemappedOwnProps {
}
interface RemappedStateProps {
- metadata: Metadata;
+ // the label the store already holds for this value, if any
+ remappedValue: string | undefined;
}
interface RemappedDispatchProps {
@@ -27,7 +28,7 @@ interface RemappedDispatchProps {
fetchRemapping: (args: {
parameter?: { id?: unknown };
value?: unknown;
- field?: Field;
+ field?: ParameterField;
cardId?: unknown;
dashboardId?: unknown;
uuid?: unknown;
@@ -39,8 +40,12 @@ type RemappedClassProps = RemappedOwnProps &
RemappedStateProps &
RemappedDispatchProps;
-const mapStateToProps = (state: State): RemappedStateProps => ({
- metadata: getMetadata(state),
+const mapStateToProps = (
+ state: State,
+ { column, value }: RemappedOwnProps,
+): RemappedStateProps => ({
+ remappedValue:
+ column == null ? undefined : getRemappedFieldValue(state, column, value),
});
const mapDispatchToProps = {
@@ -99,10 +104,9 @@ export default (ComposedComponent: ComponentType<any>) => {
}
}
- getDisplayValue(field: Field | null | undefined, value: unknown) {
- const fieldDisplayValue = field && field.remappedValue(value);
- if (fieldDisplayValue != null) {
- return fieldDisplayValue;
+ getDisplayValue() {
+ if (this.props.remappedValue != null) {
+ return this.props.remappedValue;
}
const [, remappedLabel] = this.state.remapping ?? [];
@@ -114,16 +118,17 @@ export default (ComposedComponent: ComponentType<any>) => {
}
render() {
- const { metadata, fetchRemapping, ...props } = this.props;
- // Read the field from metadata so we pick up remappings stored
- // asynchronously by fetchRemapping (e.g. card/question label columns);
- // the column passed in props can be a stale instance.
- const field =
- (props.column?.id != null && metadata?.field(props.column.id)) ||
- props.column;
- const displayValue = this.getDisplayValue(field, props.value);
+ const {
+ remappedValue: _remappedValue,
+ fetchRemapping,
+ ...props
+ } = this.props;
+ const displayValue = this.getDisplayValue();
const displayColumn =
- (displayValue != null && field && field.remappedField()) || null;
+ (displayValue != null &&
+ props.column != null &&
+ getRemappedField(props.column)) ||
+ null;
return (
<ComposedComponent
diff --git a/frontend/src/metabase/metadata-store/index.ts b/frontend/src/metabase/metadata-store/index.ts
index 11236acf67e..56f56022cff 100644
--- a/frontend/src/metabase/metadata-store/index.ts
+++ b/frontend/src/metabase/metadata-store/index.ts
@@ -3,6 +3,7 @@ export {
getMetadata,
getMetadataUnfiltered,
getMetadataWithHiddenTables,
+ getRemappedFieldValue,
getShallowDatabases,
getShallowFields,
getShallowSegments,
diff --git a/frontend/src/metabase/metadata-store/remappings.ts b/frontend/src/metabase/metadata-store/remappings.ts
index a9a046a41bb..1aba6d276a4 100644
--- a/frontend/src/metabase/metadata-store/remappings.ts
+++ b/frontend/src/metabase/metadata-store/remappings.ts
@@ -2,7 +2,7 @@ import { cardApi, dashboardApi, datasetApi } from "metabase/api";
import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
import { createThunkAction } from "metabase/redux";
import type { Dispatch, GetState } from "metabase/redux/store";
-import type Field from "metabase-lib/v1/metadata/Field";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";
import { normalizeParameter } from "metabase-lib/v1/parameters/utils/parameter-values";
import type {
@@ -15,7 +15,7 @@ import type {
} from "metabase-types/api";
import { fieldRemappingsUpdated } from "./actions";
-import { getFieldRemappings } from "./selectors";
+import { getFieldRemappings, getRemappedFieldValue } from "./selectors";
export const addRemappings =
(fieldId: FieldId, remappings: FieldValue[]) =>
@@ -37,7 +37,7 @@ export const addRemappings =
type FetchRemappingOptions = {
parameter?: Parameter | null;
value: RowValue;
- field?: Field | null;
+ field?: ParameterField | null;
cardId?: CardId | null;
dashboardId?: DashboardId | null;
uuid?: string | null;
@@ -56,8 +56,11 @@ export const fetchRemapping = createThunkAction(
uuid,
token,
}: FetchRemappingOptions) =>
- async (dispatch: Dispatch) => {
- if (field != null && field.hasRemappedValue(value)) {
+ async (dispatch: Dispatch, getState: GetState) => {
+ if (
+ field != null &&
+ getRemappedFieldValue(getState(), field, value) !== undefined
+ ) {
return;
}
diff --git a/frontend/src/metabase/metadata-store/remappings.unit.spec.ts b/frontend/src/metabase/metadata-store/remappings.unit.spec.ts
new file mode 100644
index 00000000000..447e53db952
--- /dev/null
+++ b/frontend/src/metabase/metadata-store/remappings.unit.spec.ts
@@ -0,0 +1,87 @@
+import fetchMock from "fetch-mock";
+
+import { getMainStore } from "__support__/entities-store";
+import { createMockState } from "__support__/state";
+import { createMockEntitiesState } from "__support__/store";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
+import { createMockField, createMockParameter } from "metabase-types/api/mocks";
+import {
+ PEOPLE,
+ PEOPLE_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
+
+import { addRemappings, fetchRemapping } from "./remappings";
+import { getFieldRemappings } from "./selectors";
+
+// the shape the backend hydrates into `param_fields`: a plain object with the
+// remap target nested, and none of the v1 wrapper's methods
+const idField: ParameterField = createMockField({
+ id: PEOPLE.ID,
+ table_id: PEOPLE_ID,
+ name: "ID",
+ display_name: "ID",
+ base_type: "type/BigInteger",
+ semantic_type: "type/PK",
+ has_field_values: "none",
+ name_field: createMockField({
+ id: PEOPLE.NAME,
+ table_id: PEOPLE_ID,
+ name: "NAME",
+ display_name: "Name",
+ base_type: "type/Text",
+ semantic_type: "type/Name",
+ has_field_values: "list",
+ }),
+});
+
+const parameter = createMockParameter({
+ id: "p1",
+ type: "id",
+ sectionId: "id",
+});
+
+const setup = () =>
+ getMainStore(
+ createMockState({
+ entities: createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ }),
+ }),
+ );
+
+describe("fetchRemapping", () => {
+ it("stores the label a plain param_fields field has no method to report", async () => {
+ fetchMock.post("path:/api/dataset/parameter/remapping", [
+ 2,
+ "Domenica Williamson",
+ ]);
+
+ const store = setup();
+ await store.dispatch(
+ fetchRemapping({ parameter, value: 2, field: idField }),
+ );
+
+ expect(getFieldRemappings(store.getState(), PEOPLE.ID)).toEqual([
+ [2, "Domenica Williamson"],
+ ]);
+ });
+
+ it("does not fetch a label the store already holds", async () => {
+ fetchMock.post("path:/api/dataset/parameter/remapping", [
+ 2,
+ "Domenica Williamson",
+ ]);
+
+ const store = setup();
+ store.dispatch(addRemappings(PEOPLE.ID, [[2, "Domenica Williamson"]]));
+
+ await store.dispatch(
+ fetchRemapping({ parameter, value: 2, field: idField }),
+ );
+
+ expect(
+ fetchMock.callHistory.calls("path:/api/dataset/parameter/remapping"),
+ ).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/metabase/metadata-store/selectors.ts b/frontend/src/metabase/metadata-store/selectors.ts
index bccc595168d..39c403543b9 100644
--- a/frontend/src/metabase/metadata-store/selectors.ts
+++ b/frontend/src/metabase/metadata-store/selectors.ts
@@ -13,10 +13,12 @@ import Metadata from "metabase-lib/v1/metadata/Metadata";
import type Schema from "metabase-lib/v1/metadata/Schema";
import Table from "metabase-lib/v1/metadata/Table";
import { isVirtualCardId } from "metabase-lib/v1/metadata/utils/saved-questions";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
import {
getFieldValues,
getRemappings,
} from "metabase-lib/v1/queries/utils/field";
+import { isNumeric } from "metabase-lib/v1/types/utils/isa";
import type {
Table as ApiTable,
Card,
@@ -508,5 +510,44 @@ export function getFieldRemappings(
state: MetadataState,
fieldId: FieldId,
): FieldValue[] {
- return state.entities.fields[fieldId]?.remappings ?? [];
+ return state.entities.fields[fieldId]?.remappings ?? NO_REMAPPINGS;
+}
+
+// a shared empty array, so a field with no remappings keeps its identity
+// between calls and a `useSelector` on it does not re-render
+const NO_REMAPPINGS: FieldValue[] = [];
+
+/**
+ * The label a field carries for `value`.
+ *
+ * It merges the values a values endpoint fetched with the remappings the
+ * client accumulated as other widgets fetched values. The store holds both, so
+ * a field a caller holds cannot answer this on its own.
+ */
+export function getRemappedFieldValue(
+ state: State,
+ field: ParameterField,
+ value: unknown,
+): string | undefined {
+ const fieldId = typeof field.id === "number" ? field.id : null;
+ const storeField =
+ fieldId == null ? undefined : state.entities.fields[fieldId];
+ const remappings =
+ fieldId == null ? NO_REMAPPINGS : getFieldRemappings(state, fieldId);
+
+ // parameter values arrive from the URL as strings
+ const key =
+ isNumeric(field) && typeof value !== "number"
+ ? parseFloat(String(value))
+ : value;
+
+ // a later entry wins, so the accumulated remappings override the field's
+ // own values
+ const labels = new Map<unknown, string | undefined>(
+ // the store's copy carries the values a values endpoint fetched, which the
+ // field a caller holds does not
+ getRemappings({ ...field, values: storeField?.values, remappings }),
+ );
+
+ return labels.get(key);
}
diff --git a/frontend/src/metabase/parameters/components/ParameterValueWidget.unit.spec.tsx b/frontend/src/metabase/parameters/components/ParameterValueWidget.unit.spec.tsx
index 5732f062425..3aeb296b4dd 100644
--- a/frontend/src/metabase/parameters/components/ParameterValueWidget.unit.spec.tsx
+++ b/frontend/src/metabase/parameters/components/ParameterValueWidget.unit.spec.tsx
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
import { renderWithProviders, screen } from "__support__/ui";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
import { createMockParameter } from "metabase-types/api/mocks";
+import { createProductsRatingField } from "metabase-types/api/mocks/presets";
import { ParameterValueWidget } from "./ParameterValueWidget";
@@ -33,6 +34,27 @@ function setup({ parameter }: { parameter?: Partial<UiParameter> } = {}) {
}
describe("ParameterValueWidget", () => {
+ it("should let a number filter be typed into when its field has no values to list", async () => {
+ setup({
+ parameter: {
+ ...createMockParameter({
+ id: "number-param",
+ type: "number/=",
+ sectionId: "number",
+ slug: "number",
+ name: "Number Equals",
+ }),
+ fields: [createProductsRatingField({ has_field_values: "none" })],
+ },
+ });
+
+ await userEvent.click(screen.getByTestId("parameter-value-widget-target"));
+
+ expect(
+ await screen.findByPlaceholderText("Enter a number"),
+ ).toBeInTheDocument();
+ });
+
it("should apply aria-expanded=true on the trigger button element (#70543)", async () => {
setup();
diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx
index 34b70a875a1..7558683dea9 100644
--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx
+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx
@@ -39,7 +39,11 @@ import {
} from "metabase/ui";
import { parseNumber } from "metabase/utils/number";
import { isNotNull } from "metabase/utils/types";
-import Field from "metabase-lib/v1/metadata/Field";
+import {
+ getSearchField,
+ getSharedRemappedField,
+} from "metabase-lib/v1/metadata/utils/remapping";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";
import { normalizeParameter } from "metabase-lib/v1/parameters/utils/parameter-values";
import type {
@@ -76,7 +80,10 @@ const MAX_SEARCH_RESULTS = 100;
const COMBOBOX_WIDTH = 364;
const DROPDOWN_WIDTH = 314;
-function mapStateToProps(state: State, { fields = [] }: { fields: Field[] }) {
+function mapStateToProps(
+ state: State,
+ { fields = [] }: { fields: ParameterField[] },
+) {
const metadata = getMetadata(state);
return {
fields: fields.map((field) => metadata.field(field.id) || field),
@@ -99,7 +106,7 @@ export interface IFieldValuesWidgetProps {
parameter: Parameter;
parameters?: Parameter[]; // linked parameters with values
- fields: Field[];
+ fields: ParameterField[];
dashboardId?: DashboardId;
cardId?: CardId;
@@ -257,7 +264,7 @@ export const FieldValuesWidgetInner = forwardRef<
// ? this may rely on field mutations
const updateRemappings = (options: FieldValue[]) => {
- if (Field.remappedField(fields) != null) {
+ if (getSharedRemappedField(fields) != null) {
fields.forEach((field) => {
if (typeof field.id === "number") {
dispatch(addRemappings(field.id, options));
@@ -486,7 +493,7 @@ function getNothingFoundMessage({
loadingState,
lastValue,
}: {
- fields: (Field | null)[];
+ fields: (ParameterField | null)[];
loadingState: LoadingStateType;
lastValue: string;
}) {
@@ -495,7 +502,7 @@ function getNothingFoundMessage({
}
if (fields.length === 1 && fields[0] != null) {
const [field] = fields;
- const searchField = field.searchField();
+ const searchField = getSearchField(field);
return t`No matching ${searchField?.display_name} found.`;
} else {
return t`No matching result`;
@@ -513,7 +520,7 @@ function renderValue({
compact,
displayValue,
}: {
- fields: Field[];
+ fields: ParameterField[];
formatOptions: Record<string, any>;
value: RowValue;
parameter?: Parameter;
@@ -531,7 +538,7 @@ function renderValue({
cardId={cardId}
dashboardId={dashboardId}
maximumFractionDigits={20}
- remap={displayValue || Field.remappedField(fields) != null}
+ remap={displayValue || getSharedRemappedField(fields) != null}
displayValue={displayValue}
{...formatOptions}
autoLoad={autoLoad}
@@ -542,7 +549,7 @@ function renderValue({
type RemappedValueProps = {
parameter: Parameter;
- fields: Field[];
+ fields: ParameterField[];
value: ParameterValueOrArray | null;
dashboardId?: DashboardId;
cardId?: CardId;
@@ -615,12 +622,12 @@ function RemappedValue({
type RemappedOptionProps = {
option: { value: string; label?: string };
- fields: Field[];
+ fields: ParameterField[];
tc: ContentTranslationFunction;
};
function RemappedOption({ option, fields, tc }: RemappedOptionProps) {
- const isRemapped = Field.remappedField(fields) != null;
+ const isRemapped = getSharedRemappedField(fields) != null;
const label = tc(option.label ?? option.value);
if (!isRemapped) {
diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.ts b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.ts
index 403afdf198a..672873831b1 100644
--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.ts
+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/utils.ts
@@ -4,7 +4,8 @@ import _ from "underscore";
import type { ComboboxItem } from "metabase/ui";
import { isTransientId } from "metabase/utils/dashboard";
import { stripId } from "metabase/utils/formatting";
-import type Field from "metabase-lib/v1/metadata/Field";
+import { getSearchField } from "metabase-lib/v1/metadata/utils/remapping";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
import {
canListFieldValues,
canListParameterValues,
@@ -17,6 +18,11 @@ import {
isNumberParameter,
isStringParameter,
} from "metabase-lib/v1/parameters/utils/parameter-type";
+import {
+ isID,
+ isNumeric as isNumericField,
+ isString,
+} from "metabase-lib/v1/types/utils/isa";
import type {
CardId,
DashboardId,
@@ -45,7 +51,7 @@ export function shouldList({
disableSearch,
}: {
parameter?: Parameter;
- fields: Field[];
+ fields: ParameterField[];
disableSearch?: boolean;
}) {
if (disableSearch) {
@@ -58,7 +64,7 @@ export function shouldList({
}
function getNonSearchableTokenFieldPlaceholder(
- firstField: Field,
+ firstField: ParameterField,
parameter?: Parameter,
) {
if (parameter) {
@@ -73,11 +79,11 @@ function getNonSearchableTokenFieldPlaceholder(
// fallback
return t`Enter some text`;
} else if (firstField) {
- if (firstField.isID()) {
+ if (isID(firstField)) {
return t`Enter an ID`;
- } else if (firstField.isString()) {
+ } else if (isString(firstField)) {
return t`Enter some text`;
- } else if (firstField.isNumeric()) {
+ } else if (isNumericField(firstField)) {
return t`Enter a number`;
}
@@ -90,24 +96,24 @@ function getNonSearchableTokenFieldPlaceholder(
}
export function searchField(
- field: Field | null,
+ field: ParameterField | null,
disablePKRemappingForSearch?: boolean,
) {
- return field?.searchField(disablePKRemappingForSearch) ?? null;
+ return field ? getSearchField(field, disablePKRemappingForSearch) : null;
}
function getSearchableTokenFieldPlaceholder(
parameter: Parameter | undefined,
- fields: Field[],
- firstField: Field,
+ fields: ParameterField[],
+ firstField: ParameterField,
disablePKRemappingForSearch?: boolean,
) {
let placeholder;
const names = new Set(
- fields.map((field: Field) =>
+ fields.map((field) =>
stripId(
- field?.searchField?.(disablePKRemappingForSearch)?.display_name ?? "",
+ getSearchField(field, disablePKRemappingForSearch)?.display_name ?? "",
),
),
);
@@ -123,8 +129,8 @@ function getSearchableTokenFieldPlaceholder(
placeholder = t`Search by ${name}`;
if (
firstField &&
- firstField.isID() &&
- firstField !== firstField.searchField(disablePKRemappingForSearch)
+ isID(firstField) &&
+ firstField !== getSearchField(firstField, disablePKRemappingForSearch)
) {
placeholder += t` or enter an ID`;
}
@@ -139,7 +145,7 @@ export function hasList({
options,
}: {
parameter?: Parameter;
- fields: Field[];
+ fields: ParameterField[];
disableSearch: boolean;
options: FieldValue[];
}) {
@@ -172,7 +178,7 @@ export function isSearchable({
valuesMode,
}: {
parameter?: Parameter;
- fields?: Field[];
+ fields?: ParameterField[];
disableSearch?: boolean;
disablePKRemappingForSearch?: boolean;
valuesMode?: ValuesMode;
@@ -199,7 +205,7 @@ export function getTokenFieldPlaceholder({
options,
valuesMode,
}: {
- fields: Field[];
+ fields: ParameterField[];
parameter?: Parameter;
disableSearch: boolean;
placeholder?: string;
@@ -249,7 +255,7 @@ export function getValuesMode({
disablePKRemappingForSearch,
}: {
parameter?: Parameter;
- fields: Field[];
+ fields: ParameterField[];
disableSearch?: boolean;
disablePKRemappingForSearch?: boolean;
}): ValuesMode {
@@ -272,10 +278,10 @@ export function getValuesMode({
return "none";
}
-export function isNumeric(parameter: Parameter, fields: Field[]) {
+export function isNumeric(parameter: Parameter, fields: ParameterField[]) {
return (
isNumberParameter(parameter) ||
- (fields.length > 0 && fields.every((field) => field.isNumeric()))
+ (fields.length > 0 && fields.every(isNumericField))
);
}
diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx
index 764dd0fa8a9..c834716696b 100644
--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx
+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidget.tsx
@@ -6,12 +6,14 @@ import _ from "underscore";
import CS from "metabase/css/core/index.css";
import { UpdateFilterButton } from "metabase/parameters/components/UpdateFilterButton";
import { Box } from "metabase/ui";
-import type Field from "metabase-lib/v1/metadata/Field";
import {
getFilterArgumentFormatOptions,
isEqualsOperator,
} from "metabase-lib/v1/operators/utils";
-import type { UiParameter } from "metabase-lib/v1/parameters/types";
+import type {
+ ParameterField,
+ UiParameter,
+} from "metabase-lib/v1/parameters/types";
import { deriveFieldOperatorFromParameter } from "metabase-lib/v1/parameters/utils/operators";
import {
getIsMultiSelect,
@@ -26,7 +28,7 @@ import FieldValuesWidget from "./FieldValuesWidget";
import { normalizeValue } from "./normalizeValue";
interface ParameterFieldWidgetProps {
- fields: Field[];
+ fields: ParameterField[];
isEditing?: boolean;
parameter: UiParameter;
parameters?: UiParameter[];
diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx
index a841a891b49..099c6058ed2 100644
--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx
+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.tsx
@@ -1,5 +1,6 @@
import { renderNumberOfSelections } from "metabase/parameters/utils/formatting";
-import Field from "metabase-lib/v1/metadata/Field";
+import { getSharedRemappedField } from "metabase-lib/v1/metadata/utils/remapping";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
import { hasRemappedParameterValues } from "metabase-lib/v1/parameters/utils/parameter-source";
import type { CardId, DashboardId, Parameter } from "metabase-types/api";
@@ -8,7 +9,7 @@ import { normalizeValue } from "../normalizeValue";
type ParameterFieldWidgetValueProps = {
value: unknown;
- fields: Field[];
+ fields: ParameterField[];
parameter?: Parameter;
cardId?: CardId;
dashboardId?: DashboardId;
@@ -28,7 +29,7 @@ export function ParameterFieldWidgetValue({
const shouldRemap =
(parameter != null
? hasRemappedParameterValues(parameter, fields)
- : Field.remappedField(fields) != null) || displayValue != null;
+ : getSharedRemappedField(fields) != null) || displayValue != null;
return numberOfValues > 1 ? (
<>{renderNumberOfSelections(numberOfValues)}</>
diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.unit.spec.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.unit.spec.tsx
index d43794fd2fb..4044392c5d9 100644
--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.unit.spec.tsx
+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/ParameterFieldWidgetValue/ParameterFieldWidgetValue.unit.spec.tsx
@@ -1,4 +1,8 @@
-import { render, screen } from "__support__/ui";
+import { createMockState } from "__support__/state";
+import { createMockEntitiesState } from "__support__/store";
+import { render, renderWithProviders, screen } from "__support__/ui";
+import { createMockField } from "metabase-types/api/mocks";
+import { ORDERS, createSampleDatabase } from "metabase-types/api/mocks/presets";
import { ParameterFieldWidgetValue } from "./ParameterFieldWidgetValue";
@@ -15,3 +19,50 @@ describe("when fields is empty array", () => {
expect(screen.getByText("2 selections")).toBeInTheDocument();
});
});
+
+describe("when a field remaps its values", () => {
+ const PEOPLE_ID = 10;
+ const PEOPLE_NAME_ID = 11;
+
+ // the shape the backend hydrates into `param_fields`: a PK carries the
+ // `type/Name` field of its table, which is what its values remap to
+ const nameField = createMockField({
+ id: PEOPLE_NAME_ID,
+ name: "NAME",
+ display_name: "Name",
+ base_type: "type/Text",
+ semantic_type: "type/Name",
+ has_field_values: "list",
+ });
+
+ const idField = createMockField({
+ id: PEOPLE_ID,
+ name: "ID",
+ display_name: "ID",
+ base_type: "type/BigInteger",
+ semantic_type: "type/PK",
+ has_field_values: "none",
+ name_field: nameField,
+ });
+
+ it("renders the remapped label the store accumulated for the value", () => {
+ const state = createMockState({
+ entities: createMockEntitiesState({
+ databases: [createSampleDatabase()],
+ }),
+ });
+ state.entities.fields[PEOPLE_ID] = {
+ ...state.entities.fields[ORDERS.ID],
+ id: PEOPLE_ID,
+ uniqueId: String(PEOPLE_ID),
+ remappings: [[2, "Domenica Williamson"]],
+ };
+
+ renderWithProviders(
+ <ParameterFieldWidgetValue value={[2]} fields={[idField]} />,
+ { storeInitialState: state },
+ );
+
+ expect(screen.getByText("Domenica Williamson")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsx
index 2634755a816..1da073ac7de 100644
--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsx
+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/Value/RemappedValue.tsx
@@ -3,22 +3,28 @@ import type { ReactNode } from "react";
import { useTranslateContent } from "metabase/content-translation/hooks";
import CS from "metabase/css/core/index.css";
import AutoLoadRemapped from "metabase/hoc/Remapped";
+import { getRemappedFieldValue } from "metabase/metadata-store";
+import { useSelector } from "metabase/redux";
import { formatValue } from "metabase/value-formatting";
-import type Field from "metabase-lib/v1/metadata/Field";
+import type { ParameterField } from "metabase-lib/v1/parameters/types";
+import { isID } from "metabase-lib/v1/types/utils/isa";
-type RenderNormal = (opts: { value?: unknown; column?: Field }) => ReactNode;
+type RenderNormal = (opts: {
+ value?: unknown;
+ column?: ParameterField;
+}) => ReactNode;
type RenderRemapped = (opts: {
value: unknown;
- column?: Field;
+ column?: ParameterField;
displayValue?: unknown;
- displayColumn?: Field;
+ displayColumn?: ParameterField;
}) => ReactNode;
export type RemappedValueProps = {
value: unknown;
- column?: Field;
+ column?: ParameterField;
displayValue?: unknown;
- displayColumn?: Field;
+ displayColumn?: ParameterField;
renderNormal?: RenderNormal;
renderRemapped?: RenderRemapped;
autoLoad?: boolean;
@@ -38,7 +44,7 @@ const defaultRenderRemapped: RenderRemapped = ({
{/* Unjustified type cast. FIXME */}
<span className={CS.textBold}>{displayValue as ReactNode}</span>
{/* Show the underlying ID for PK/FK */}
- {column?.isID() && <span style={{ opacity: 0.5 }}>{" - " + value}</span>}
+ {isID(column) && <span style={{ opacity: 0.5 }}>{" - " + value}</span>}
</span>
);
@@ -72,7 +78,7 @@ const RemappedValueContent = ({
const getEffectiveValue = (
value: unknown,
- column: Field | undefined,
+ column: ParameterField | undefined,
props: object,
) =>
column != null
@@ -81,7 +87,7 @@ const getEffectiveValue = (
const getEffectiveDisplayValue = (
displayValue: unknown,
- displayColumn: Field | undefined,
+ displayColumn: ParameterField | undefined,
props: object,
) =>
displayColumn != null
@@ -95,14 +101,22 @@ const getEffectiveDisplayValue = (
export const AutoLoadRemappedValue = AutoLoadRemapped(RemappedValueContent);
-export const FieldRemappedValue = (props: RemappedValueProps) => (
- <RemappedValueContent
- {...props}
- displayValue={
- props.displayValue ?? props.column?.remappedValue(props.value)
- }
- />
-);
+export const FieldRemappedValue = (props: RemappedValueProps) => {
+ const remappedValue = useRemappedValue(props.column, props.value);
+
+ return (
+ <RemappedValueContent
+ {...props}
+ displayValue={props.displayValue ?? remappedValue}
+ />
+ );
+};
+
+function useRemappedValue(column: ParameterField | undefined, value: unknown) {
+ return useSelector((state) =>
+ column == null ? undefined : getRemappedFieldValue(state, column, value),
+ );
+}
const RemappedValue = ({ autoLoad = true, ...props }: RemappedValueProps) =>
autoLoad && !props.displayValue ? (
diff --git a/frontend/src/metabase/parameters/utils/dashboards.ts b/frontend/src/metabase/parameters/utils/dashboards.ts
index f72e6afb665..901aee78596 100644
--- a/frontend/src/metabase/parameters/utils/dashboards.ts
+++ b/frontend/src/metabase/parameters/utils/dashboards.ts
@@ -134,18 +134,12 @@ export function getSavedDashboardUiParameters(
dashcards: Dashboard["dashcards"],
parameters: Dashboard["parameters"],
parameterFields: Dashboard["param_fields"],
- metadata: Metadata,
): UiParameter[] {
const mappableDashcards = dashcards.filter(isQuestionDashCard);
const mappings = getMappings(mappableDashcards);
const uiParameters: UiParameter[] = (parameters || []).map((parameter) => {
if (isFieldFilterParameter(parameter)) {
- return buildSavedDashboardParameter(
- parameter,
- mappings,
- parameterFields,
- metadata,
- );
+ return buildSavedDashboardParameter(parameter, mappings, parameterFields);
}
return {
@@ -208,7 +202,6 @@ function buildSavedDashboardParameter(
parameter: Parameter,
mappings: ExtendedMapping[],
fields: Dashboard["param_fields"],
- metadata: Metadata,
) {
const parameterMappings = mappings.filter(
(mapping) => mapping.parameter_id === parameter.id,
@@ -216,10 +209,10 @@ function buildSavedDashboardParameter(
const hasVariableTemplateTagTarget = parameterMappings.some((mapping) =>
isParameterVariableTarget(mapping.target),
);
- const parameterFields = (fields?.[parameter.id] ?? [])
- .map((field) => metadata.field(field.id))
- .filter(isNotNull);
- const uniqueParameterFields = _.uniq(parameterFields, (field) => field.id);
+ const uniqueParameterFields = _.uniq(
+ fields?.[parameter.id] ?? [],
+ (field) => field.id,
+ );
return {
...parameter,
diff --git a/frontend/src/metabase/parameters/utils/formatting.ts b/frontend/src/metabase/parameters/utils/formatting.ts
index 7d38c7f3c85..1200b827536 100644
--- a/frontend/src/metabase/parameters/utils/formatting.ts
+++ b/frontend/src/metabase/parameters/utils/formatting.ts
@@ -2,7 +2,7 @@ import { msgid, ngettext } from "ttag";
import { formatValue } from "metabase/value-formatting";
import * as Lib from "metabase-lib";
-import Field from "metabase-lib/v1/metadata/Field";
+import { getSharedRemappedField } from "metabase-lib/v1/metadata/utils/remapping";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
import {
getFields,
@@ -78,7 +78,7 @@ export function formatParameterValue(
// when a parameter targets multiple fields we won't know
// which parameter the value is associated with, so we take
// the first field for remapping
- const remap = Field.remappedField(fields) != null;
+ const remap = getSharedRemappedField(fields) != null;
return formatValue(value, {
column: firstField,
maximumFractionDigits: 20,
diff --git a/frontend/src/metabase/parameters/utils/parameter-parsing.ts b/frontend/src/metabase/parameters/utils/parameter-parsing.ts
index 7f0409c4b76..dde15a6c333 100644
--- a/frontend/src/metabase/parameters/utils/parameter-parsing.ts
+++ b/frontend/src/metabase/parameters/utils/parameter-parsing.ts
@@ -6,10 +6,19 @@ import {
normalizeTemporalUnitParameterValue,
} from "metabase/querying/parameters/utils/parsing";
import * as Lib from "metabase-lib";
-import type Field from "metabase-lib/v1/metadata/Field";
-import type { FieldFilterUiParameter } from "metabase-lib/v1/parameters/types";
+import type {
+ FieldFilterUiParameter,
+ ParameterField,
+} from "metabase-lib/v1/parameters/types";
import { getParameterType } from "metabase-lib/v1/parameters/utils/parameter-type";
import { getIsMultiSelect } from "metabase-lib/v1/parameters/utils/parameter-values";
+import {
+ isBoolean,
+ isDate,
+ isNumeric,
+ isString,
+ isStringLike,
+} from "metabase-lib/v1/types/utils/isa";
import type {
Parameter,
ParameterType,
@@ -116,18 +125,18 @@ function parseParameterValueForNumber(
function parseParameterValueForFields(
type: ParameterType,
value: ParameterValueOrArray,
- fields: Field[],
+ fields: ParameterField[],
): ParameterValueOrArray {
// unix dates fields are numeric but query params shouldn't be parsed as numbers
- if (fields.every((f) => f.isNumeric() && !f.isDate())) {
+ if (fields.every((field) => isNumeric(field) && !isDate(field))) {
return normalizeNumberParameterValue(type, value);
}
- if (fields.every((f) => f.isBoolean())) {
+ if (fields.every(isBoolean)) {
return normalizeBooleanParameterValue(value);
}
- if (fields.every((f) => f.isString() || f.isStringLike())) {
+ if (fields.every((field) => isString(field) || isStringLike(field))) {
return normalizeStringParameterValue(value);
}
diff --git a/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.ts b/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.ts
index 4081e2c934a..1c546c5cfb4 100644
--- a/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.ts
+++ b/frontend/src/metabase/parameters/utils/parameter-parsing.unit.spec.ts
@@ -1,23 +1,19 @@
-import Field from "metabase-lib/v1/metadata/Field";
import type { FieldFilterUiParameter } from "metabase-lib/v1/parameters/types";
import type {
+ Field,
Parameter,
ParameterValueOrArray,
ParameterValuesMap,
} from "metabase-types/api";
-import {
- createMockNormalizedField,
- createMockParameter,
-} from "metabase-types/api/mocks";
+import { createMockField, createMockParameter } from "metabase-types/api/mocks";
import {
getParameterValueFromQueryParams,
getParameterValuesByIdFromQueryParams,
} from "./parameter-parsing";
-function createMockField(mocks: Partial<Field>): Field {
- return Object.assign(new Field(createMockNormalizedField({})), mocks);
-}
+// the root type, so every type predicate is false until a test sets a type
+const UNTYPED = "type/*";
// bypasses the strict signature to pin the runtime `|| {}` guard
const UNDEFINED_QUERY_PARAMS = undefined as unknown as ParameterValuesMap;
@@ -38,38 +34,22 @@ describe("parameters/utils/parameter-values", () => {
field1 = createMockField({
id: 1,
table_id: 1,
- isString: () => false,
- isStringLike: () => false,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
+ base_type: UNTYPED,
});
field2 = createMockField({
id: 2,
table_id: 1,
- isString: () => false,
- isStringLike: () => false,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
+ base_type: UNTYPED,
});
field3 = createMockField({
id: 3,
table_id: 1,
- isString: () => false,
- isStringLike: () => false,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
+ base_type: UNTYPED,
});
field4 = createMockField({
id: 4,
table_id: 1,
- isString: () => false,
- isStringLike: () => false,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
+ base_type: UNTYPED,
});
// found in queryParams and not defaulted
@@ -181,11 +161,8 @@ describe("parameters/utils/parameter-values", () => {
});
it("should parse the parameter value as a float if all associated fields are numeric and not dates", () => {
- field1.isNumeric = () => true;
- field1.isDate = () => false;
-
- field4.isNumeric = () => true;
- field4.isDate = () => false;
+ field1.base_type = "type/Integer";
+ field4.base_type = "type/Integer";
expect(
getParameterValueFromQueryParams(parameter1, {
@@ -201,11 +178,11 @@ describe("parameters/utils/parameter-values", () => {
});
it("should not parse numeric values that are dates as floats", () => {
- field1.isNumeric = () => true;
- field1.isDate = () => true;
-
- field4.isNumeric = () => true;
- field4.isDate = () => false;
+ // a unix timestamp is stored as a number and coerced to a date
+ field1.base_type = "type/BigInteger";
+ field1.effective_type = "type/DateTime";
+ field1.coercion_strategy = "Coercion/UNIXSeconds->DateTime";
+ field4.base_type = "type/Integer";
expect(
getParameterValueFromQueryParams(parameter1, {
@@ -215,8 +192,8 @@ describe("parameters/utils/parameter-values", () => {
});
it("should convert boolean arguments to strings if all mapped fields are strings", () => {
- field1.isString = () => true;
- field4.isStringLike = () => true;
+ field1.base_type = "type/Text";
+ field4.base_type = "type/TextLike";
expect(
getParameterValueFromQueryParams(parameter1, {
@@ -226,8 +203,8 @@ describe("parameters/utils/parameter-values", () => {
});
it("should parse a value of 'true' or 'false' as a boolean if all associated fields are booleans", () => {
- field1.isBoolean = () => true;
- field4.isBoolean = () => true;
+ field1.base_type = "type/Boolean";
+ field4.base_type = "type/Boolean";
expect(
getParameterValueFromQueryParams(parameter1, {
@@ -305,7 +282,7 @@ describe("parameters/utils/parameter-values", () => {
});
it("should be able to get the underlying field of a parameter tied to a dimension", () => {
- field3.isBoolean = () => true;
+ field3.base_type = "type/Boolean";
expect(
getParameterValueFromQueryParams(parameter3, {
@@ -338,8 +315,7 @@ describe("parameters/utils/parameter-values", () => {
});
it("should not try to parse default values", () => {
- field2.isNumeric = () => true;
- field2.isDate = () => false;
+ field2.base_type = "type/Integer";
expect(
getParameterValueFromQueryParams(parameter2, {
@@ -516,9 +492,9 @@ describe("parameters/utils/parameter-values", () => {
});
it("should not filter out falsy non-nil values", () => {
- field1.isNumeric = () => true;
- field4.isNumeric = () => true;
- field3.isBoolean = () => true;
+ field1.base_type = "type/Integer";
+ field4.base_type = "type/Integer";
+ field3.base_type = "type/Boolean";
expect(
getParameterValuesByIdFromQueryParams(parameters, {
@@ -555,9 +531,9 @@ describe("parameters/utils/parameter-values", () => {
});
it("should not filter out falsy non-nil, non-empty-string values", () => {
- field1.isNumeric = () => true;
- field4.isNumeric = () => true;
- field3.isBoolean = () => true;
+ field1.base_type = "type/Integer";
+ field4.base_type = "type/Integer";
+ field3.base_type = "type/Boolean";
expect(
getParameterValuesByIdFromQueryParams(
diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView-filters.stories.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView-filters.stories.tsx
index a725bc7df64..ea0cdd75256 100644
--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView-filters.stories.tsx
+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView-filters.stories.tsx
@@ -264,7 +264,11 @@ function createDashboard({
[CATEGORY_DROPDOWN_FILTER.id]: [createProductsCategoryField()],
[DATE_FILTER_ID]: [createProductsCreatedAtField()],
[UNIT_OF_TIME_FILTER_ID]: [createProductsCreatedAtField()],
- [NUMBER_FILTER_ID]: [createProductsRatingField()],
+ // the story types a value into this filter, so its field must not offer
+ // a list to pick from
+ [NUMBER_FILTER_ID]: [
+ createProductsRatingField({ has_field_values: "none" }),
+ ],
},
dashcards: [
createMockDashboardCard({
diff --git a/src/metabase/parameters/params.clj b/src/metabase/parameters/params.clj
index e15a5fa959c..646dda69120 100644
--- a/src/metabase/parameters/params.clj
+++ b/src/metabase/parameters/params.clj
@@ -183,6 +183,20 @@
[card-or-dashboard]
(m/update-existing card-or-dashboard :param_fields update-vals #(mapv remove-param-field-non-public-columns %)))
+(defn- hydrate-param-field-targets
+ "Attach each FK Field's `:target`, with the `:name_field` that labels the target's
+ values. The usual `:target` hydration reads the target Field through permissions,
+ which an anonymous public or embedded request does not have, so it is selected
+ directly here. Without the target a public parameter widget cannot label an FK's
+ values."
+ [fields]
+ (let [target-ids (into #{} (keep :fk_target_field_id) fields)
+ id->target (when (seq target-ids)
+ (m/index-by :id (-> (parameters.db/fields-with-columns param-field-columns target-ids)
+ (t2/hydrate :has_field_values :name_field))))]
+ (for [field fields]
+ (assoc field :target (some-> (:fk_target_field_id field) id->target)))))
+
(mu/defn- param-field-ids->fields
"Get the Fields (as a map of Parameter ID -> Fields) that should be returned for hydrated `:param_fields` for a Card
or Dashboard. These only contain the minimal amount of information necessary needed to power public or embedded
@@ -191,7 +205,8 @@
(let [field-ids (into #{} cat (vals param-id->field-ids))
field-id->field (when (seq field-ids)
(m/index-by :id (-> (parameters.db/fields-with-columns param-field-columns field-ids)
- (t2/hydrate :has_field_values :name_field [:target :has_field_values :name_field] [:dimensions [:human_readable_field :has_field_values]])
+ (t2/hydrate :has_field_values :name_field [:dimensions [:human_readable_field :has_field_values]])
+ hydrate-param-field-targets
remove-dimensions-nonpublic-columns)))]
(->> param-id->field-ids
(m/map-vals #(into [] (keep field-id->field) %)))))
diff --git a/test/metabase/embedding_rest/api/embed_test.clj b/test/metabase/embedding_rest/api/embed_test.clj
index 7288c68adaa..e502ab7861e 100644
--- a/test/metabase/embedding_rest/api/embed_test.clj
+++ b/test/metabase/embedding_rest/api/embed_test.clj
@@ -49,6 +49,28 @@
(defmacro with-new-secret-key! {:style/indent 0} [& body]
`(do-with-new-secret-key! (fn [] ~@body)))
+(defn- categories-id-target
+ "The `:target` a `:param_fields` entry for `venues.category_id` carries: the
+ Categories primary key in public columns, with the `:name_field` that labels its
+ values. A public parameter widget cannot remap an FK's values without it."
+ []
+ {:id (mt/id :categories :id)
+ :table_id (mt/id :categories)
+ :display_name "ID"
+ :base_type "type/BigInteger"
+ :name "ID"
+ :semantic_type "type/PK"
+ :has_field_values "none"
+ :fk_target_field_id nil
+ :name_field {:id (mt/id :categories :name)
+ :table_id (mt/id :categories)
+ :display_name "Name"
+ :base_type "type/Text"
+ :name "NAME"
+ :semantic_type "type/Name"
+ :has_field_values "list"
+ :fk_target_field_id nil}})
+
(defn- the-id-or-entity-id
"u/the-id doesn't work on entity-ids, so we should just pass them through."
[id-or-entity-id]
@@ -697,6 +719,7 @@
:semantic_type "type/FK"
:has_field_values "none"
:fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)
:dimensions []}]}
(:param_fields (client/client :get 200 (card-url card))))))))))
@@ -719,6 +742,7 @@
:semantic_type "type/FK"
:has_field_values "none"
:fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)
:dimensions []}]}
(:param_fields (client/client :get 200 (dashboard-url (:dashboard_id dashcard))))))))))
@@ -762,6 +786,7 @@
:semantic_type "type/FK"
:has_field_values "none"
:fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)
:dimensions []}]}
(:param_fields (client/client :get 200 (card-url card {:params {:id 1}}))))))))))
@@ -790,6 +815,7 @@
:semantic_type "type/FK"
:has_field_values "none"
:fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)
:dimensions []}]}
(:param_fields (client/client :get 200 (dashboard-url (:dashboard_id dashcard) {:params {:id 1}})))))))))
@@ -827,6 +853,7 @@
:semantic_type "type/FK"
:has_field_values "none"
:fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)
:dimensions []}]}
(:param_fields (client/client :get 200 (dashboard-url (:dashboard_id dashcard))))))))))))
diff --git a/test/metabase/public_sharing_rest/api_test.clj b/test/metabase/public_sharing_rest/api_test.clj
index 260298f7ddf..018ac07be09 100644
--- a/test/metabase/public_sharing_rest/api_test.clj
+++ b/test/metabase/public_sharing_rest/api_test.clj
@@ -42,6 +42,28 @@
;;; --------------------------------------------------- Helper Fns ---------------------------------------------------
+(defn- categories-id-target
+ "The `:target` a `:param_fields` entry for `venues.category_id` carries: the
+ Categories primary key in public columns, with the `:name_field` that labels its
+ values. A public parameter widget cannot remap an FK's values without it."
+ []
+ {:id (mt/id :categories :id)
+ :table_id (mt/id :categories)
+ :display_name "ID"
+ :base_type "type/BigInteger"
+ :name "ID"
+ :semantic_type "type/PK"
+ :has_field_values "none"
+ :fk_target_field_id nil
+ :name_field {:id (mt/id :categories :name)
+ :table_id (mt/id :categories)
+ :display_name "Name"
+ :base_type "type/Text"
+ :name "NAME"
+ :semantic_type "type/Name"
+ :has_field_values "list"
+ :fk_target_field_id nil}})
+
(defn- shared-obj []
{:public_uuid (str (random-uuid))
:made_public_by_id (mt/user->id :crowberto)})
@@ -1515,9 +1537,23 @@
:semantic_type "type/FK"
:has_field_values "none"
:fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)
:dimensions []}]}
(:param_fields (client/client :get 200 (str "public/card/" (:public_uuid card)))))))))))
+(deftest dashboard-param-fields-anonymous-fk-target-test
+ (testing "GET /api/public/dashboard/:uuid :param_fields carry an FK's target without a session"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (with-sharing-enabled-and-temp-dashcard-referencing! :orders :user_id [dashboard]
+ (testing "the target labels the FK's values, so a public widget cannot remap them without it"
+ (is (=? {:id (mt/id :people :id)
+ :name_field {:id (mt/id :people :name)}}
+ (-> (client/client :get 200 (str "public/dashboard/" (:public_uuid dashboard)))
+ :param_fields
+ vals
+ ffirst
+ :target))))))))
+
(deftest dashboard-param-fields-public-columns-test
(testing "GET /api/public/dashboard/:uuid :param_fields only carry the public Field columns"
(mt/with-temporary-setting-values [enable-public-sharing true]
@@ -1541,6 +1577,7 @@
:semantic_type "type/FK"
:has_field_values "none"
:fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)
:dimensions []}]}
(:param_fields (client/client :get 200 (str "public/dashboard/" (:public_uuid dashboard)))))))))))
@@ -1571,7 +1608,8 @@
:name "CATEGORY_ID"
:semantic_type "type/FK"
:has_field_values "none"
- :fk_target_field_id (mt/id :categories :id)}
+ :fk_target_field_id (mt/id :categories :id)
+ :target (categories-id-target)}
categories-name {:id (mt/id :categories :name)
:table_id (mt/id :categories)
:display_name "Name"