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
Get rid of `category` and `id` parameter types (#70196)
metambenbfb0b42b42c3
diff --git a/e2e/test/scenarios/dashboard-filters/dashboard-filters-management.cy.spec.js b/e2e/test/scenarios/dashboard-filters/dashboard-filters-management.cy.spec.jsindex e9585bd3cc9..b7818d2e028 100644--- a/e2e/test/scenarios/dashboard-filters/dashboard-filters-management.cy.spec.js+++ b/e2e/test/scenarios/dashboard-filters/dashboard-filters-management.cy.spec.js@@ -153,8 +153,8 @@ describe("scenarios > dashboard > filters > management", () => {changeFilterType("ID");- cy.log("verify ID doesn't render operator select");- H.sidebar().findByText("Filter operator").should("not.exist");+ cy.log("verify ID default value: Numeric ID");+ verifyOperatorValue("Numeric ID");changeFilterType("Date picker");diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.cljindex f0a1d1872b6..58e4c8d2de9 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj@@ -120,9 +120,12 @@(when (not attr-value)(throw (ex-info (tru "Query requires user attribute `{0}`" (name attr-name)){:type qp.error-type/missing-required-parameter})))- {:type :category+ {:type (if (and field-base-type (isa? field-base-type :type/Number))+ :number/=+ :string/=):target target- :value (attr-value->param-value field-base-type attr-value)}))+ ;; :number/= and :string/= are variadic operators that require a sequential value+ :value [(attr-value->param-value field-base-type attr-value)]}))(mu/defn- sandbox->parameters :- [:maybe [:sequential ::lib.schema.parameter/parameter]][metadata-providerable :- ::lib.schema.metadata/metadata-providerablediff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.cljindex 2ad81eff453..083bc5f06a8 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj@@ -1813,3 +1813,14 @@(lib/aggregate (lib/sum (lib.metadata/field mp (mt/id :orders :quantity)))))](is (= [[44]](mt/rows (mt/user-http-request :rasta :post 202 "dataset" query))))))))++(deftest ^:parallel attr-remapping-parameter-type-test+ (testing "attr-remapping->parameter uses explicit parameter types instead of :category (QUE2-326)"+ (let [attr-remapping->parameter #'sandboxing/attr-remapping->parameter+ mp (mt/metadata-provider)]+ (testing "numeric field → :number/="+ (is (= :number/=+ (:type (attr-remapping->parameter mp {"cat" "50"} ["cat" [:variable [:field (mt/id :venues :price) nil]]])))))+ (testing "text field → :string/="+ (is (= :string/=+ (:type (attr-remapping->parameter mp {"cat" "foo"} ["cat" [:variable [:field (mt/id :venues :name) nil]]]))))))))diff --git a/frontend/src/metabase-lib/v1/parameters/constants.ts b/frontend/src/metabase-lib/v1/parameters/constants.tsindex da26b2f38df..ccc9cde5752 100644--- a/frontend/src/metabase-lib/v1/parameters/constants.ts+++ b/frontend/src/metabase-lib/v1/parameters/constants.ts@@ -168,6 +168,28 @@ export const PARAMETER_OPERATOR_TYPES = {},},],+ id: [+ {+ type: "number/=",+ operator: "=",+ get name() {+ return t`ID`;+ },+ get menuName() {+ return t`Numeric ID`;+ },+ },+ {+ type: "string/=",+ operator: "=",+ get name() {+ return t`ID`;+ },+ get menuName() {+ return t`Text ID`;+ },+ },+ ],} as const;export const OPTIONS_WITH_OPERATOR_SUBTYPES = [@@ -191,6 +213,10 @@ export const OPTIONS_WITH_OPERATOR_SUBTYPES = [},] as const;+// LEGACY: "id" is a widget-type misused as a parameter type (QUE2-326).+// New ID parameters start with type "id" as a placeholder; the type should be+// updated to a concrete type (e.g., "number/=") when the parameter is mapped+// to a field. Frontend UI behavior uses sectionId "id" instead of the type.export const ID_OPTION = {type: "id",get name() {@@ -205,6 +231,7 @@ export const BOOLEAN_OPTION = {},} as const;+// LEGACY: "category" and "id" entries handle legacy stored parameters (QUE2-326).export const TYPE_SUPPORTS_LINKED_FILTERS = ["string","category",@@ -212,6 +239,7 @@ export const TYPE_SUPPORTS_LINKED_FILTERS = ["location",] as const;+// LEGACY: "category" and "id" entries handle legacy stored parameters (QUE2-326).export const SINGLE_OR_MULTI_SELECTABLE_TYPES: Record<string,string | string[]@@ -230,6 +258,7 @@ export const SINGLE_OR_MULTI_SELECTABLE_TYPES: Record<number: ["=", "!="],};+// LEGACY: "category" and "id" entries handle legacy stored parameters (QUE2-326).export const FIELD_FILTER_PARAMETER_TYPES = ["date","string",diff --git a/frontend/src/metabase-lib/v1/parameters/utils/operators.ts b/frontend/src/metabase-lib/v1/parameters/utils/operators.tsindex 5b9c5b320b1..836bff0fcc8 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/operators.ts+++ b/frontend/src/metabase-lib/v1/parameters/utils/operators.ts@@ -12,7 +12,7 @@ import type { Parameter, ParameterMappingOptions } from "metabase-types/api";import { getIsMultiSelect } from "./parameter-values";-type OperatorType = "date" | "number" | "string";+type OperatorType = "date" | "number" | "string" | "id";export type ParameterSectionId =| "date"| "temporal-unit"@@ -27,7 +27,11 @@ export function getOperatorDisplayName(operatorType: OperatorType,sectionName?: string,) {- if (operatorType === "date" || operatorType === "number") {+ if (+ operatorType === "date" ||+ operatorType === "number" ||+ operatorType === "id"+ ) {return option.name;} else if (operatorType === "string" && option.operator === "=") {return sectionName;diff --git a/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.js b/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.jsindex ace816604b0..f7e98f68694 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.js+++ b/frontend/src/metabase-lib/v1/parameters/utils/parameter-type.unit.spec.js@@ -1,6 +1,7 @@import {getParameterSubType,getParameterType,+ isIdParameter,} from "metabase-lib/v1/parameters/utils/parameter-type";describe("parameters/utils/parameter-type", () => {@@ -22,6 +23,27 @@ describe("parameters/utils/parameter-type", () => {});});+ describe("isIdParameter (QUE2-326)", () => {+ it("should return true for sectionId 'id' with concrete type", () => {+ expect(isIdParameter({ sectionId: "id", type: "number/=" })).toBe(true);+ });++ it("should return true for sectionId 'id' with string type", () => {+ expect(isIdParameter({ sectionId: "id", type: "string/=" })).toBe(true);+ });++ it("should return true for legacy type 'id' (backward compat)", () => {+ expect(isIdParameter({ type: "id" })).toBe(true);+ });++ it("should return false for non-id parameters", () => {+ expect(isIdParameter({ type: "number/=" })).toBe(false);+ expect(isIdParameter({ sectionId: "number", type: "number/=" })).toBe(+ false,+ );+ });+ });+describe("getParameterSubType", () => {it("should return the string before the slash in a parameter type", () => {expect(getParameterSubType("string/foo")).toEqual("foo");diff --git a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.ts b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.tsindex 4d54ec1e092..bc19cc65ad2 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.ts+++ b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.ts@@ -23,8 +23,7 @@ function getParameterType(tag: TemplateTag) {if (type === "date") {return "date/single";}- // @ts-expect-error -- preserving preexisting incorrect types (for now)- if (type === "string" || type === "text") {+ if (type === "text") {return "string/=";}if (type === "number") {@@ -37,7 +36,7 @@ function getParameterType(tag: TemplateTag) {return "temporal-unit";}- return "category";+ return "string/=";}function getParameterTarget(tag: TemplateTag): ParameterTarget {diff --git a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.js b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.jsindex f407780e7a0..3fc82a2ec87 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.js+++ b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.unit.spec.js@@ -182,6 +182,72 @@ describe("parameters/utils/cards", () => {);});+ it("should produce string/= for text tags without widget-type (QUE2-326)", () => {+ const tags = [+ createMockTemplateTag({+ type: "text",+ id: "1",+ name: "name",+ "display-name": "Name",+ }),+ ];+ expect(getTemplateTagParameters(tags)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: "1",+ name: "Name",+ slug: "name",+ target: ["variable", ["template-tag", "name"]],+ type: "string/=",+ }),+ ]),+ );+ });++ it("should produce boolean/= for boolean tags without widget-type (QUE2-326)", () => {+ const tags = [+ createMockTemplateTag({+ type: "boolean",+ id: "1",+ name: "active",+ "display-name": "Is Active",+ }),+ ];+ expect(getTemplateTagParameters(tags)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: "1",+ name: "Is Active",+ slug: "active",+ target: ["variable", ["template-tag", "active"]],+ type: "boolean/=",+ }),+ ]),+ );+ });++ it("should produce string/= for unknown tag types (QUE2-326)", () => {+ const tags = [+ createMockTemplateTag({+ type: "unknown-type",+ id: "1",+ name: "x",+ "display-name": "X",+ }),+ ];+ expect(getTemplateTagParameters(tags)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: "1",+ name: "X",+ slug: "x",+ target: ["variable", ["template-tag", "x"]],+ type: "string/=",+ }),+ ]),+ );+ });+it("should exclude tags that are not parameters", () => {const tags = [createMockTemplateTag({diff --git a/frontend/src/metabase/dashboard/actions/parameters.tsx b/frontend/src/metabase/dashboard/actions/parameters.tsxindex 8c8380ee78d..9e73658b28f 100644--- a/frontend/src/metabase/dashboard/actions/parameters.tsx+++ b/frontend/src/metabase/dashboard/actions/parameters.tsx@@ -22,6 +22,7 @@ import {setParameterType as setParamType,} from "metabase/parameters/utils/dashboards";import { addUndo, dismissUndo } from "metabase/redux/undo";+import { getMetadata } from "metabase/selectors/metadata";import { Text } from "metabase/ui";import * as Lib from "metabase-lib";import { getParameterValuesByIdFromQueryParams } from "metabase-lib/v1/parameters/utils/parameter-parsing";@@ -29,6 +30,8 @@ import {PULSE_PARAM_EMPTY,isParameterValueEmpty,} from "metabase-lib/v1/parameters/utils/parameter-values";+import { TYPE } from "metabase-lib/v1/types/constants";+import { isNumericBaseType, isa } from "metabase-lib/v1/types/utils/isa";import type {ActionDashboardCard,CardId,@@ -43,6 +46,7 @@ import type {VisualizationDisplay,WritebackAction,} from "metabase-types/api";+import { isDimensionTarget } from "metabase-types/guards";import type { Dispatch, GetState } from "metabase-types/store";import {@@ -445,10 +449,64 @@ export const setParameterMapping = createThunkAction(},}),);++ // QUE2-326: when an ID parameter is mapped to a field, replace the+ // placeholder "id" type with a concrete type based on the field.+ if (target !== null && isDimensionTarget(target)) {+ const parameter = getParameters(getState()).find(+ (p) => p.id === parameterId,+ );+ if (parameter?.type === "id") {+ updateParameter(dispatch, getState, parameterId, (p) => ({+ ...p,+ type: resolveIdParameterType(getState, target),+ // Preserve sectionId so getParameterType() still returns "id" for+ // UI purposes (column compatibility, widget rendering) even though+ // the QP-facing type is now concrete.+ sectionId: p.sectionId ?? "id",+ }));+ }+ }};},);+/**+ * QUE2-326: Determine the concrete parameter type for an ID parameter based on+ * the mapped field. Handles both by-ID refs (looks up metadata) and by-name+ * refs (reads base-type from the field ref options). Falls back to "number/="+ * since most PKs are numeric.+ */+function resolveIdParameterType(+ getState: GetState,+ target: ParameterTarget,+): string {+ const fieldRef = target[1];+ if (!Array.isArray(fieldRef) || fieldRef[0] !== "field") {+ return "number/=";+ }++ const fieldIdOrName = fieldRef[1];++ // By-ID: look up the field from the metadata store+ if (typeof fieldIdOrName === "number") {+ const field = getMetadata(getState()).field(fieldIdOrName);+ if (field) {+ return isNumericBaseType(field) ? "number/=" : "string/=";+ }+ return "number/=";+ }++ // By-name: read the base-type from the field ref options+ const opts = fieldRef[2];+ const baseType = opts?.["base-type"];+ if (typeof baseType === "string") {+ return isa(baseType, TYPE.Number) ? "number/=" : "string/=";+ }++ return "number/=";+}+export const UPDATE_PARAMETER_MAPPINGS_FOR_DASHCARD_TEXT ="metabase/dashboard/UPDATE_PARAMETER_MAPPINGS_FOR_DASHCARD_TEXT";export const updateParameterMappingsForDashcardText = createThunkAction(diff --git a/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts b/frontend/src/metabase/dashboard/actions/parameters.unit.spec.tsindex 70b8d96abee..ac44b4a4ae5 100644--- a/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts+++ b/frontend/src/metabase/dashboard/actions/parameters.unit.spec.ts@@ -8,6 +8,7 @@ import {createMockParameter,createMockStructuredDatasetQuery,} from "metabase-types/api/mocks";+import { createMockNormalizedField } from "metabase-types/api/mocks/schema";import type { State } from "metabase-types/store";import {createMockDashboardState,@@ -20,6 +21,7 @@ import {removeParameter,setOrUnsetParameterValues,setParameterIsMultiSelect,+ setParameterMapping,setParameterType,} from "./parameters";@@ -215,6 +217,197 @@ describe("removeParameter", () => {});});+describe("setParameterMapping", () => {+ describe("QUE2-326: updates ID parameter type when mapped to a field", () => {+ function setupIdMapping({+ fieldId,+ fieldBaseType,+ }: {+ fieldId: number | undefined;+ fieldBaseType: string;+ }) {+ const state = createMockState({+ dashboard: createMockDashboardState({+ dashboardId: 1,+ dashboards: {+ "1": createMockStoreDashboard({+ id: 1,+ dashcards: [1],+ parameters: [+ createMockParameter({+ id: "id-param",+ type: "id",+ sectionId: "id",+ }),+ ],+ }),+ },+ dashcards: {+ "1": createMockDashboardCard({+ id: 1,+ card_id: 1,+ card: createMockCard({+ id: 1,+ dataset_query: createMockStructuredDatasetQuery(),+ }),+ }),+ },+ }),+ entities: {+ actions: {},+ collections: {},+ dashboards: {},+ databases: {},+ documents: {},+ schemas: {},+ tables: {},+ fields:+ fieldId != null+ ? {+ [String(fieldId)]: createMockNormalizedField({+ id: fieldId,+ uniqueId: String(fieldId),+ base_type: fieldBaseType,+ }),+ }+ : {},+ segments: {},+ measures: {},+ snippets: {},+ questions: {},+ indexedEntities: {},+ groups: {},+ },+ });+ const store = setup(state);+ return { store };+ }++ it("should update type to number/= when mapped to a numeric field by ID", async () => {+ const { store } = setupIdMapping({+ fieldId: 42,+ fieldBaseType: "type/Integer",+ });+ await store.dispatch(+ setParameterMapping("id-param", 1, 1, [+ "dimension",+ ["field", 42, null],+ ]),+ );+ const [param] = getParameters(store.getState());+ expect(param.type).toBe("number/=");+ expect(param.sectionId).toBe("id");+ });++ it("should update type to string/= when mapped to a text field by ID", async () => {+ const { store } = setupIdMapping({+ fieldId: 43,+ fieldBaseType: "type/Text",+ });+ await store.dispatch(+ setParameterMapping("id-param", 1, 1, [+ "dimension",+ ["field", 43, null],+ ]),+ );+ const [param] = getParameters(store.getState());+ expect(param.type).toBe("string/=");+ });++ it("should update type to number/= when mapped to a numeric field by name", async () => {+ const { store } = setupIdMapping({+ fieldId: undefined,+ fieldBaseType: "type/Integer",+ });+ await store.dispatch(+ setParameterMapping("id-param", 1, 1, [+ "dimension",+ ["field", "USER_ID", { "base-type": "type/Integer" }],+ ]),+ );+ const [param] = getParameters(store.getState());+ expect(param.type).toBe("number/=");+ });++ it("should update type to string/= when mapped to a text field by name", async () => {+ const { store } = setupIdMapping({+ fieldId: undefined,+ fieldBaseType: "type/Text",+ });+ await store.dispatch(+ setParameterMapping("id-param", 1, 1, [+ "dimension",+ ["field", "EMAIL", { "base-type": "type/Text" }],+ ]),+ );+ const [param] = getParameters(store.getState());+ expect(param.type).toBe("string/=");+ });++ it("should not change type for non-id parameters", async () => {+ const state = createMockState({+ dashboard: createMockDashboardState({+ dashboardId: 1,+ dashboards: {+ "1": createMockStoreDashboard({+ id: 1,+ dashcards: [1],+ parameters: [+ createMockParameter({+ id: "str-param",+ type: "string/=",+ sectionId: "string",+ }),+ ],+ }),+ },+ dashcards: {+ "1": createMockDashboardCard({+ id: 1,+ card_id: 1,+ card: createMockCard({+ id: 1,+ dataset_query: createMockStructuredDatasetQuery(),+ }),+ }),+ },+ }),+ entities: {+ actions: {},+ collections: {},+ dashboards: {},+ databases: {},+ documents: {},+ schemas: {},+ tables: {},+ fields: {+ "42": createMockNormalizedField({+ id: 42,+ uniqueId: "42",+ base_type: "type/Integer",+ }),+ },+ segments: {},+ measures: {},+ snippets: {},+ questions: {},+ indexedEntities: {},+ groups: {},+ },+ });+ const store = setup(state);+ await store.dispatch(+ setParameterMapping("str-param", 1, 1, [+ "dimension",+ ["field", 42, null],+ ]),+ );+ const [param] = getParameters(store.getState());+ expect(param.type).toBe("string/=");+ });+ });+});+describe("setOrUnsetParameterValues", () => {it("should set parameter value to default when parameter is required and has a default value", async () => {const store = setup(diff --git a/frontend/src/metabase/parameters/components/ParameterSettings/ParameterSettings.unit.spec.tsx b/frontend/src/metabase/parameters/components/ParameterSettings/ParameterSettings.unit.spec.tsxindex 4b7804e210e..5e8516ded42 100644--- a/frontend/src/metabase/parameters/components/ParameterSettings/ParameterSettings.unit.spec.tsx+++ b/frontend/src/metabase/parameters/components/ParameterSettings/ParameterSettings.unit.spec.tsx@@ -129,7 +129,7 @@ describe("ParameterSidebar", () => {beforeEach(() => {setup({parameter: createMockUiParameter({- type: "id",+ type: "number/=",sectionId: "id",}),});@@ -139,8 +139,8 @@ describe("ParameterSidebar", () => {expect(screen.getByDisplayValue("ID")).toBeInTheDocument();});- it("should not render operator", () => {- expect(screen.getAllByDisplayValue("id").length).toBe(1);+ it("should render operator", () => {+ expect(screen.getByDisplayValue("Numeric ID")).toBeInTheDocument();});});diff --git a/frontend/src/metabase/parameters/utils/dashboard-options.ts b/frontend/src/metabase/parameters/utils/dashboard-options.tsindex d0ab37155a1..f13b1a3aabb 100644--- a/frontend/src/metabase/parameters/utils/dashboard-options.ts+++ b/frontend/src/metabase/parameters/utils/dashboard-options.ts@@ -1,9 +1,6 @@import { t } from "ttag";-import {- BOOLEAN_OPTION,- ID_OPTION,-} from "metabase-lib/v1/parameters/constants";+import { BOOLEAN_OPTION } from "metabase-lib/v1/parameters/constants";import type { ParameterSectionId } from "metabase-lib/v1/parameters/utils/operators";import { buildTypedOperatorOptions } from "metabase-lib/v1/parameters/utils/operators";import type { ParameterMappingOptions } from "metabase-types/api";@@ -63,12 +60,7 @@ export function getDashboardParameterSections(): ParameterSection[] {id: "id",name: t`ID`,description: t`Primary key, User ID…`,- options: [- {- ...ID_OPTION,- sectionId: "id",- },- ],+ options: buildTypedOperatorOptions("id", "id", t`ID`),},];}@@ -79,6 +71,7 @@ const defaultSectionToParameter = {string: "string/=",date: "date/all-options",boolean: "boolean/=",+ id: "number/=",};export function getDefaultOptionForParameterSectionMap(): Record<@@ -91,7 +84,7 @@ export function getDefaultOptionForParameterSectionMap(): Record<for (const section of sections) {const { id: sectionId, options } = section;- if (sectionId === "id" || sectionId === "temporal-unit") {+ if (sectionId === "temporal-unit") {map[sectionId] = options[0];continue;}diff --git a/frontend/src/metabase/parameters/utils/dashboard-options.unit.spec.tsx b/frontend/src/metabase/parameters/utils/dashboard-options.unit.spec.tsxindex 1e73ebe0fa0..4896239a6a2 100644--- a/frontend/src/metabase/parameters/utils/dashboard-options.unit.spec.tsx+++ b/frontend/src/metabase/parameters/utils/dashboard-options.unit.spec.tsx@@ -2,7 +2,10 @@ import _ from "underscore";import type { ParameterSectionId } from "metabase-lib/v1/parameters/utils/operators";-import { getDashboardParameterSections } from "./dashboard-options";+import {+ getDashboardParameterSections,+ getDefaultOptionForParameterSectionMap,+} from "./dashboard-options";describe("parameters/utils/dashboard-options", () => {describe("getDashboardParameterSections", () => {@@ -34,5 +37,24 @@ describe("parameters/utils/dashboard-options", () => {_.findWhere(getDashboardParameterSections(), { id: "string" }),).toBeDefined();});++ it("should have an id section with numeric and text subtypes", () => {+ const idSection = _.findWhere(getDashboardParameterSections(), {+ id: "id",+ });+ expect(idSection).toBeDefined();+ expect(idSection?.options).toHaveLength(2);+ expect(idSection?.options.map((o) => o.type)).toEqual([+ "number/=",+ "string/=",+ ]);+ });+ });++ describe("getDefaultOptionForParameterSectionMap", () => {+ it("should default id section to number/=", () => {+ const map = getDefaultOptionForParameterSectionMap();+ expect(map.id.type).toBe("number/=");+ });});});diff --git a/src/metabase/actions/execution.clj b/src/metabase/actions/execution.cljindex 54a458eba5f..6edda95a63f 100644--- a/src/metabase/actions/execution.clj+++ b/src/metabase/actions/execution.clj@@ -160,7 +160,10 @@;; consistent rather than random to make this easier to test:id "metabase.actions.execution/prefetch-parameters-pk":target [:dimension [:field (:id pk-field) nil]]- :type :id+ ;; :type/UUID derives from :type/Text, so UUIDs are handled as strings+ :type (if (isa? (:base_type pk-field) :type/Number)+ :number/=+ :string/=):value [(get simple-parameters pk-field-name)]}]))))(defn- parse-implicit-action [action-instance]diff --git a/src/metabase/lib/schema/parameter.cljc b/src/metabase/lib/schema/parameter.cljcindex b43cedab157..ac456f938df 100644--- a/src/metabase/lib/schema/parameter.cljc+++ b/src/metabase/lib/schema/parameter.cljc@@ -86,20 +86,17 @@;; everything else can't be used with raw value template tags -- they can only be used with Dashboard parameters;; for MBQL queries or Field filters in native queries- ;; `:id` and `:category` conceptually aren't types in a "the parameter value is of this type" sense, but they are- ;; widget types. They have something to do with telling the frontend to show FieldValues list/search widgets or- ;; something like that.+ ;; LEGACY PARAMETER TYPES -- do not create new parameters with these types.+ ;; Use :number/=, :string/=, :boolean/=, etc. instead.;;- ;; Apparently the frontend might still pass in parameters with these types, in which case we're supposed to infer- ;; the actual type of the parameter based on the Field we're filtering on. Or something like that. Parameters with- ;; these types are only allowed if the widget type matches exactly, but you can also pass in something like a- ;; `:number/=` for a parameter with widget type `:category`.+ ;; :id and :category are widget-types that were historically misused as parameter types.+ ;; As parameter types they mean "infer the value type from the target field." The QP+ ;; handles this in parse-param-value-for-type (mbql.clj).;;- ;; TODO FIXME -- actually, it turns out the the FE client passes parameter type `:category` for parameters in- ;; public Cards. Who knows why! For now, we'll continue allowing it. But we should fix it soon. See- ;; [[metabase.public-sharing-rest.api-test/execute-public-card-with-parameters-test]]+ ;; These remain valid for backward compatibility (dashboard/card parameters already in the app DB).+ ;; See QUE2-326 for history.:id {:allowed-for #{:id}}- :category {:allowed-for #{:category #_FIXME :number :text :date :boolean}}+ :category {:allowed-for #{:category :number :text :date :boolean}};; Like `:id` and `:category`, the `:location/*` types are primarily widget types. They don't really have a meaning;; as a parameter type, so in an ideal world they wouldn't be allowed; however it seems like the FE still passeddiff --git a/src/metabase/parameters/dashboard.clj b/src/metabase/parameters/dashboard.cljindex d64c0e0d381..a6ab42f9ae2 100644--- a/src/metabase/parameters/dashboard.clj+++ b/src/metabase/parameters/dashboard.clj@@ -31,8 +31,8 @@{:case-sensitive false}))(mu/defn- param->fields- [param :- ::parameters.schema/parameter]- (let [op (param-type->op (:type param))+ [param :- ::parameters.schema/parameter & {:keys [op-override]}]+ (let [op (or op-override (param-type->op (:type param)))options (or (:options param) (param-type->default-options (:type param)))](for [field-id (params/dashboard-param->field-ids param)]{:field-id field-id@@ -162,37 +162,37 @@([dashboard param-key value](dashboard-param-remapped-value dashboard param-key value nil))([dashboard param-key value constraint-param-key->value]- (when (contains? constraint-param-key->value param-key)- (throw (ex-info (tru "Getting the remapped value for a constrained parameter is not supported")- {:status-code 400- :parameter param-key})))- (let [dashboard (-> dashboard- (t2/hydrate :resolved-params)- ;; whatever the param's type, we want an equality constraint- (m/update-existing-in [:resolved-params param-key] assoc :type :id))- param (get-in dashboard [:resolved-params param-key])- field-ids (into #{} (map :field-id (param->fields param)))- ;; Default case when we have just a single field-id:- get-direct-remapping #(chain-filter/chain-filter- (first field-ids)- (chain-filter-constraints dashboard- (assoc constraint-param-key->value- param-key- value))- :relax-fk-requirement? true- :limit 1)- ;; Default case when we have multiple field-ids:- get-common-remapping #(when-let [common-display-field (find-common-remapping-target field-ids)]- (when-let [pk-field-id (custom-values/pk-of-fk-pk-field-ids field-ids)]- (chain-filter/chain-filter pk-field-id- [{:field-id pk-field-id, :op :=, :value value}]- :limit 1- :remapping-field common-display-field)))- default-case-fn (fn dashboard-param-remapped-default-case []- (-> (if (= (count field-ids) 1)- (get-direct-remapping) ; only one field id- (get-common-remapping)) ; more than one- :values- first))]- (or (custom-values/parameter-remapped-value param value default-case-fn)- [value]))))+ (let [constraint-param-key->value (or constraint-param-key->value {})]+ (when (contains? constraint-param-key->value param-key)+ (throw (ex-info (tru "Getting the remapped value for a constrained parameter is not supported")+ {:status-code 400+ :parameter param-key})))+ (let [dashboard (t2/hydrate dashboard :resolved-params)+ param (get-in dashboard [:resolved-params param-key])+ ;; Whatever the param's type, we want an equality constraint for the remapped value+ ;; lookup. Use op-override := instead of mutating the param type to :id (QUE2-326).+ field-ids (into #{} (map :field-id (param->fields param :op-override :=)))+ ;; Default case when we have just a single field-id:+ get-direct-remapping #(chain-filter/chain-filter+ (first field-ids)+ (into (chain-filter-constraints dashboard+ constraint-param-key->value)+ (for [field (param->fields param :op-override :=)]+ (assoc field :value value)))+ :relax-fk-requirement? true+ :limit 1)+ ;; Default case when we have multiple field-ids:+ get-common-remapping #(when-let [common-display-field (find-common-remapping-target field-ids)]+ (when-let [pk-field-id (custom-values/pk-of-fk-pk-field-ids field-ids)]+ (chain-filter/chain-filter pk-field-id+ [{:field-id pk-field-id, :op :=, :value value}]+ :limit 1+ :remapping-field common-display-field)))+ default-case-fn (fn dashboard-param-remapped-default-case []+ (-> (if (= (count field-ids) 1)+ (get-direct-remapping) ; only one field id+ (get-common-remapping)) ; more than one+ :values+ first))]+ (or (custom-values/parameter-remapped-value param value default-case-fn)+ [value])))))diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex bcfa2402599..2fdbe7080d0 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -389,10 +389,14 @@(or (contains? lib.schema.template-tag/raw-value-template-tag-types tag-type)(and (= tag-type :dimension) widget-type (not= widget-type :none))))]{:id (:id tag)- :type (or widget-type (cond (= tag-type :date) :date/single- (= tag-type :string) :string/=- (= tag-type :number) :number/=- :else :category))+ :type (or widget-type (case tag-type+ :date :date/single+ :text :string/=+ :number :number/=+ :boolean :boolean/=+ ;; fallback; should be unreachable since :when filters+ ;; to raw-value-template-tag-types+ :string/=)):target (if (= tag-type :dimension)[:dimension [:template-tag (:name tag)]][:variable [:template-tag (:name tag)]])diff --git a/src/metabase/query_processor/middleware/parameters/mbql.clj b/src/metabase/query_processor/middleware/parameters/mbql.cljindex ae751c3010c..09f21940a47 100644--- a/src/metabase/query_processor/middleware/parameters/mbql.clj+++ b/src/metabase/query_processor/middleware/parameters/mbql.clj@@ -55,8 +55,9 @@param-valuea-ref :- [:or :mbql.clause/field :mbql.clause/expression]](cond- ;; for `id` or `category` type params look up the base-type of the Field and see if it's a number or not.- ;; If it *is* a number then recursively call this function and parse the param value as a number as appropriate.+ ;; LEGACY: :id and :category are widget-types misused as parameter types.+ ;; New code uses explicit types, but stored parameters may still have these.+ ;; Infer numeric vs string from the target field. See QUE2-326.(and (#{:id :category} param-type)(let [base-type (or (field-type query stage-path a-ref)(expression-type query a-ref))]diff --git a/test/metabase/actions/execution_test.clj b/test/metabase/actions/execution_test.cljindex 090b7c3c128..f1c29f651dc 100644--- a/test/metabase/actions/execution_test.clj+++ b/test/metabase/actions/execution_test.clj@@ -21,7 +21,7 @@:query:fieldsfirst)]- :type :id+ :type :number/=:value [1]}]:constraints nil:middleware nil@@ -33,3 +33,16 @@(actions.execution/fetch-values (action/select-action :id action-id) {"id" 1})))(is (=? {:action_id action-id}(qe))))))))))++(deftest implicit-action-prefetch-parameter-type-test+ (testing "implicit action prefetch uses explicit parameter type instead of :id (QUE2-326)"+ (mt/test-helpers-set-global-values!+ (mt/with-actions-enabled+ (mt/with-actions [_ {:type :model :dataset_query (mt/mbql-query venues {:fields [$id $name]})}+ {:keys [action-id]} {:type :implicit :kind "row/update"}]+ (let [action (action/select-action :id action-id)+ build-implicit-query #'actions.execution/build-implicit-query+ {:keys [prefetch-parameters]} (build-implicit-query action :model.row/update {"id" 1})]+ (testing "numeric PK → :number/="+ (is (= :number/=+ (:type (first prefetch-parameters)))))))))))diff --git a/test/metabase/parameters/dashboard_test.clj b/test/metabase/parameters/dashboard_test.cljindex a128c85e262..8a6efc4f231 100644--- a/test/metabase/parameters/dashboard_test.clj+++ b/test/metabase/parameters/dashboard_test.clj@@ -23,7 +23,12 @@(is (=? [{:op := :options nil}](#'parameters.dashboard/param->fields (get-in dashboard [:resolved-params "_CATEGORY_NAME_"]))))(is (=? [{:op :contains :options {:case-sensitive false}}]- (#'parameters.dashboard/param->fields (get-in dashboard [:resolved-params "_CATEGORY_CONTAINS_"])))))))))+ (#'parameters.dashboard/param->fields (get-in dashboard [:resolved-params "_CATEGORY_CONTAINS_"])))))+ (testing "op-override forces the op regardless of param type (QUE2-326)"+ (is (=? [{:op := :options {:case-sensitive false}}]+ (#'parameters.dashboard/param->fields+ (get-in dashboard [:resolved-params "_CATEGORY_CONTAINS_"])+ :op-override :=))))))))(deftest ^:parallel chain-filter-constraints-test(testing "chain-filter-constraints"diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 7bb6d42d104..e24c7b766a4 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -8,6 +8,7 @@[metabase.lib.convert :as lib.convert][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.lib.test-metadata :as meta][metabase.lib.test-util.notebook-helpers :as notebook-helpers][metabase.models.interface :as mi][metabase.models.serialization :as serdes]@@ -373,6 +374,71 @@:required true}](card/template-tag-parameters card))))))+(defn- native-query-card+ "Build a card map with a native query containing the given template tags.+ Uses lib to construct a properly normalized pMBQL query."+ [sql template-tags]+ {:dataset_query (lib/with-template-tags+ (lib/native-query meta/metadata-provider sql)+ template-tags)})++(deftest ^:parallel template-tag-parameters-text-tag-test+ (testing ":text template tag without widget-type produces :string/= parameter type (QUE2-326)"+ (let [card (native-query-card+ "SELECT * FROM PEOPLE WHERE NAME = {{name}}"+ {"name" {:id "_NAME_"+ :name "name"+ :display-name "Name"+ :type :text+ :required false+ :default "Alice"}})]+ (is (= [{:id "_NAME_"+ :type :string/=+ :target [:variable [:template-tag "name"]]+ :name "Name"+ :slug "name"+ :default "Alice"+ :required false}]+ (card/template-tag-parameters card))))))++(deftest ^:parallel template-tag-parameters-boolean-tag-test+ (testing ":boolean template tag without widget-type produces :boolean/= parameter type (QUE2-326)"+ (let [card (native-query-card+ "SELECT 1 WHERE 1 = {{active}}"+ {"active" {:id "_ACTIVE_"+ :name "active"+ :display-name "Is Active"+ :type :boolean+ :required false}})]+ (is (= [{:id "_ACTIVE_"+ :type :boolean/=+ :target [:variable [:template-tag "active"]]+ :name "Is Active"+ :slug "active"+ :default nil+ :required false}]+ (card/template-tag-parameters card))))))++(deftest ^:parallel template-tag-parameters-dimension-category-widget-test+ (testing ":dimension template tag with :category widget-type passes through widget-type (QUE2-326)"+ (let [card (native-query-card+ "SELECT * FROM PRODUCTS WHERE {{cat}}"+ {"cat" {:id "_CAT_"+ :name "cat"+ :display-name "Category"+ :type :dimension+ :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"}+ (meta/id :products :category)]+ :widget-type :category}})]+ (is (= [{:id "_CAT_"+ :type :category+ :target [:dimension [:template-tag "cat"]]+ :name "Category"+ :slug "cat"+ :default nil+ :required false}]+ (card/template-tag-parameters card))))))+(deftest validate-template-tag-field-ids-test(testing "Disallow saving a Card with native query Field filter template tags referencing a different Database (#14145)"(let [test-data-db-id (mt/id)