Skip to content

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

Fix data apps schema query and skill issues (#82978)

Timofey Kachalovbbf64b92ca0a
diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-query-runtime-clauses.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-query-runtime-clauses.cy.spec.tsx
new file mode 100644
index 00000000000..0c35c3c556d
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-query-runtime-clauses.cy.spec.tsx
@@ -0,0 +1,309 @@
+import { MetabaseProvider } from "@metabase/embedding-sdk-react";
+import {
+ type DefinedQuery,
+ aggregations,
+ breakout,
+ defineQuery,
+ filter,
+ orderBy,
+ useMetabaseQuery,
+} from "@metabase/embedding-sdk-react/data-app";
+
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { createQuestion } from "e2e/support/helpers";
+import {
+ DEFAULT_SDK_AUTH_PROVIDER_CONFIG,
+ mountSdk,
+} from "e2e/support/helpers/embedding-sdk-component-testing";
+import {
+ mockAuthProviderAndJwtSignIn,
+ signInAsAdminAndEnableEmbeddingSdk,
+} from "e2e/support/helpers/embedding-sdk-testing";
+import type { StructuredQuery } from "metabase-types/api";
+
+const { ORDERS, ORDERS_ID, PEOPLE, PRODUCTS } = SAMPLE_DATABASE;
+
+const tableSource = { type: "table" as const, id: ORDERS_ID };
+
+const createdAtField = {
+ type: "column" as const,
+ fieldId: ORDERS.CREATED_AT,
+ tableId: ORDERS_ID,
+ name: "CREATED_AT",
+ jsType: "Date" as const,
+};
+const userIdField = {
+ type: "column" as const,
+ fieldId: ORDERS.USER_ID,
+ tableId: ORDERS_ID,
+ name: "USER_ID",
+ jsType: "number" as const,
+};
+const productIdField = {
+ type: "column" as const,
+ fieldId: ORDERS.PRODUCT_ID,
+ tableId: ORDERS_ID,
+ name: "PRODUCT_ID",
+ jsType: "number" as const,
+};
+const totalField = {
+ type: "column" as const,
+ fieldId: ORDERS.TOTAL,
+ tableId: ORDERS_ID,
+ name: "TOTAL",
+ jsType: "number" as const,
+};
+const subtotalField = {
+ type: "column" as const,
+ fieldId: ORDERS.SUBTOTAL,
+ tableId: ORDERS_ID,
+ name: "SUBTOTAL",
+ jsType: "number" as const,
+};
+const productsIdField = {
+ type: "column" as const,
+ fieldId: PRODUCTS.ID,
+ sourceFieldId: ORDERS.PRODUCT_ID,
+ name: "ID",
+ jsType: "number" as const,
+};
+const peopleIdField = {
+ type: "column" as const,
+ fieldId: PEOPLE.ID,
+ sourceFieldId: ORDERS.USER_ID,
+ name: "ID",
+ jsType: "number" as const,
+};
+
+type QueryResult = { columns: { name: string }[]; rawRows: unknown[][] };
+type QueryState = { data: QueryResult | null; error: unknown };
+
+type RowCheck = (data: QueryResult) => string | null;
+
+type UseQueryStates = (cardId: number) => {
+ fromTable: QueryState;
+ fromCard: QueryState;
+};
+
+const asCardQuery = <TQuery extends DefinedQuery>(cardId: number) =>
+ // Public types admit only table sources; the card holds `TQuery`, so its
+ // result columns match.
+ ({ source: { type: "card", id: cardId } }) as unknown as TQuery;
+
+const describeState = ({ data, error }: QueryState, check: RowCheck) =>
+ error
+ ? `error: ${String(error)}`
+ : data === null
+ ? "loading"
+ : data.rawRows.length === 0
+ ? "empty"
+ : (check(data) ?? "ok");
+
+function RuntimeClauses({
+ cardId,
+ useQueryStates,
+ check,
+}: {
+ cardId: number;
+ useQueryStates: UseQueryStates;
+ check: RowCheck;
+}) {
+ const { fromTable, fromCard } = useQueryStates(cardId);
+
+ return (
+ <>
+ <div data-testid="from-table">{describeState(fromTable, check)}</div>
+ <div data-testid="from-card">{describeState(fromCard, check)}</div>
+ </>
+ );
+}
+
+const isSortedDescending = (values: unknown[]) =>
+ values.every(
+ (value, index) => index === 0 || Number(values[index - 1]) >= Number(value),
+ );
+
+describe("scenarios > embedding-sdk > query runtime clauses", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+ });
+
+ const expectRuntimeClauses = ({
+ cardQuery,
+ useQueryStates,
+ check,
+ }: {
+ cardQuery: StructuredQuery;
+ useQueryStates: UseQueryStates;
+ check: RowCheck;
+ }) => {
+ createQuestion({ name: "Runtime clauses source", query: cardQuery }).then(
+ ({ body: card }) => {
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+
+ mountSdk(
+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>
+ <RuntimeClauses
+ cardId={card.id}
+ useQueryStates={useQueryStates}
+ check={check}
+ />
+ </MetabaseProvider>,
+ );
+
+ cy.findByTestId("from-table", { timeout: 30000 }).should(
+ "have.text",
+ "ok",
+ );
+ cy.findByTestId("from-card", { timeout: 30000 }).should(
+ "have.text",
+ "ok",
+ );
+ },
+ );
+ };
+
+ it("filters on a result column that a foreign key also makes joinable", () => {
+ const staticQuery = defineQuery({
+ source: tableSource,
+ aggregations: [aggregations.count()],
+ breakouts: [
+ breakout(createdAtField, { unit: "month" }),
+ breakout(userIdField),
+ ],
+ });
+ const dynamicQuery = {
+ filters: [filter(createdAtField, ">=", "2024-01-01")],
+ };
+
+ expectRuntimeClauses({
+ cardQuery: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ["field", ORDERS.USER_ID, null],
+ ],
+ },
+ useQueryStates: (cardId) => ({
+ fromTable: useMetabaseQuery(staticQuery, dynamicQuery),
+ fromCard: useMetabaseQuery(
+ asCardQuery<typeof staticQuery>(cardId),
+ dynamicQuery,
+ ),
+ }),
+ check: ({ rawRows }) => {
+ const earlier = rawRows.find(
+ ([createdAt]) => String(createdAt) < "2024-01-01",
+ );
+ return earlier ? `row before 2024: ${JSON.stringify(earlier)}` : null;
+ },
+ });
+ });
+
+ it("filters on one of two result columns with the same name", () => {
+ // Generated joined fields are metric dimensions, and the skill requires
+ // their metric in the same query. The metric is what loads the metadata of
+ // the tables its foreign keys point to.
+ createQuestion({
+ name: "Orders count",
+ type: "metric",
+ query: { "source-table": ORDERS_ID, aggregation: [["count"]] },
+ }).then(({ body: metric }) => {
+ const ordersCount = {
+ type: "metric" as const,
+ id: metric.id,
+ sourceTableId: ORDERS_ID,
+ mappedTableIds: [ORDERS_ID],
+ columns: [{ name: "count", jsType: "number" as const }],
+ };
+ const staticQuery = defineQuery({
+ source: tableSource,
+ aggregations: [ordersCount],
+ breakouts: [breakout(productsIdField), breakout(peopleIdField)],
+ });
+ const dynamicQuery = { filters: [filter(peopleIdField, "<", 10)] };
+
+ expectRuntimeClauses({
+ cardQuery: {
+ "source-table": ORDERS_ID,
+ aggregation: [["metric", metric.id]],
+ breakout: [
+ ["field", PRODUCTS.ID, { "source-field": ORDERS.PRODUCT_ID }],
+ ["field", PEOPLE.ID, { "source-field": ORDERS.USER_ID }],
+ ],
+ },
+ useQueryStates: (cardId) => ({
+ fromTable: useMetabaseQuery(staticQuery, dynamicQuery),
+ fromCard: useMetabaseQuery(
+ asCardQuery<typeof staticQuery>(cardId),
+ dynamicQuery,
+ ),
+ }),
+ check: ({ rawRows }) => {
+ const outside = rawRows.find(
+ ([, peopleId]) => Number(peopleId) >= 10,
+ );
+ return outside
+ ? `row with people ID >= 10: ${JSON.stringify(outside)}`
+ : null;
+ },
+ });
+ });
+ });
+
+ describe("two aggregations of the same kind", () => {
+ // Unnamed, both return a column named `sum`, which a later stage cannot
+ // tell apart.
+ const totalSum = aggregations.sum(totalField, { name: "total" });
+ const subtotalSum = aggregations.sum(subtotalField, { name: "subtotal" });
+ const staticQuery = defineQuery({
+ source: tableSource,
+ aggregations: [totalSum, subtotalSum],
+ breakouts: [breakout(productIdField)],
+ });
+ const cardQuery: StructuredQuery = {
+ "source-table": ORDERS_ID,
+ aggregation: [
+ [
+ "aggregation-options",
+ ["sum", ["field", ORDERS.TOTAL, null]],
+ { name: "total", "display-name": "Sum of Total" },
+ ],
+ [
+ "aggregation-options",
+ ["sum", ["field", ORDERS.SUBTOTAL, null]],
+ { name: "subtotal", "display-name": "Sum of Subtotal" },
+ ],
+ ],
+ breakout: [["field", ORDERS.PRODUCT_ID, null]],
+ };
+
+ [
+ { aggregation: totalSum, name: "total", index: 1 },
+ { aggregation: subtotalSum, name: "subtotal", index: 2 },
+ ].forEach(({ aggregation, name, index }) => {
+ it(`orders by ${name}, by its name`, () => {
+ const dynamicQuery = { orderBys: [orderBy(aggregation, "desc")] };
+
+ expectRuntimeClauses({
+ cardQuery,
+ useQueryStates: (cardId) => ({
+ fromTable: useMetabaseQuery(staticQuery, dynamicQuery),
+ fromCard: useMetabaseQuery(
+ asCardQuery<typeof staticQuery>(cardId),
+ dynamicQuery,
+ ),
+ }),
+ check: ({ columns, rawRows }) =>
+ columns[index]?.name !== name
+ ? `column ${index} is reported as ${columns[index]?.name}`
+ : isSortedDescending(rawRows.map((row) => row[index]))
+ ? null
+ : `rows are not sorted by ${name}`,
+ });
+ });
+ });
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/semantic-schema.cy.spec.ts b/e2e/test/scenarios/data-apps/semantic-schema.cy.spec.ts
new file mode 100644
index 00000000000..ae28c894c9c
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/semantic-schema.cy.spec.ts
@@ -0,0 +1,77 @@
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { Collection } from "metabase-types/api";
+
+const { H } = cy;
+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+
+type LibraryResponse = Collection & {
+ effective_children?: Collection[];
+};
+
+const METRIC_DESCRIPTION = "Revenue from completed orders";
+
+describe("scenarios > data apps > semantic schema", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ H.createLibrary().then(
+ ({ body: library }: Cypress.Response<LibraryResponse>) => {
+ const metricsCollection = library.effective_children?.find(
+ ({ type }) => type === "library-metrics",
+ );
+
+ H.publishTables({ table_ids: [ORDERS_ID] });
+ H.createQuestion({
+ name: "Revenue",
+ description: METRIC_DESCRIPTION,
+ type: "metric",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["sum", ["field", ORDERS.TOTAL, null]]],
+ filter: [">=", ["field", ORDERS.CREATED_AT, null], "2025-01-01"],
+ },
+ }).then(({ body: metric }) => {
+ // `createQuestion` saves a question and only then sets the metric
+ // type, and the Metrics collection accepts nothing but metrics.
+ cy.request("PUT", `/api/card/${metric.id}`, {
+ collection_id: metricsCollection?.id,
+ });
+ });
+ },
+ );
+ });
+
+ it("tells the author about the filter a metric applies", () => {
+ cy.request<string>(
+ "GET",
+ "/api/typed-schemas/v1/typescript?include-metric-library=true",
+ ).then(({ body }) => {
+ const comments = commentsAbove(body, "revenue: {");
+
+ expect(comments).to.include(`// Description: ${METRIC_DESCRIPTION}`);
+ expect(comments).to.include("// Filters:");
+ expect(
+ comments.some(
+ (line) => line.startsWith("// - ") && line.includes("Created At"),
+ ),
+ ).to.eq(true);
+ });
+ });
+});
+
+/** The comment lines directly above the schema entry that opens with `entry`. */
+function commentsAbove(body: string, entry: string) {
+ const lines = body.split("\n").map((line) => line.trim());
+ const comments: string[] = [];
+
+ for (let index = lines.indexOf(entry) - 1; index >= 0; index--) {
+ if (!lines[index].startsWith("//")) {
+ break;
+ }
+ comments.unshift(lines[index]);
+ }
+
+ return comments;
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/aggregation-helpers.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/aggregation-helpers.ts
index 55c33e48f44..f71a591bfd3 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/aggregation-helpers.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/aggregation-helpers.ts
@@ -8,66 +8,119 @@ import type {
OrderableAggregationDimension,
} from "./types";
-export const count = (): CountAggregationSchema => ({
- type: "operator",
- operator: "count",
- args: [],
- columns: [{ name: "count", displayName: "Count", jsType: "number" }],
-});
-
-export const sum = <TDimension>(
- dimension: NumericAggregationDimension<TDimension>,
-): FieldAggregationSchema<"sum", NumericAggregationDimension<TDimension>> =>
- fieldAggregation("sum", "Sum", dimension);
+type AggregationOptions<TName extends string> = {
+ name: TName;
+};
+
+export function count(): CountAggregationSchema;
+export function count<const TName extends string>(
+ options: AggregationOptions<TName>,
+): CountAggregationSchema<TName>;
+export function count(
+ options?: AggregationOptions<string>,
+): CountAggregationSchema<string> {
+ return {
+ type: "operator",
+ operator: "count",
+ args: [],
+ ...(options && { name: options.name }),
+ columns: [
+ {
+ name: options?.name ?? "count",
+ displayName: "Count",
+ jsType: "number",
+ },
+ ],
+ };
+}
-export const avg = <TDimension>(
+export const sum = <TDimension, const TName extends string = "sum">(
dimension: NumericAggregationDimension<TDimension>,
-): FieldAggregationSchema<"avg", NumericAggregationDimension<TDimension>> =>
- fieldAggregation("avg", "Average", dimension);
-
-export const median = <TDimension>(
+ options?: AggregationOptions<TName>,
+): FieldAggregationSchema<
+ "sum",
+ NumericAggregationDimension<TDimension>,
+ "number",
+ NoInfer<TName>
+> => fieldAggregation("sum", "Sum", dimension, options);
+
+export const avg = <TDimension, const TName extends string = "avg">(
dimension: NumericAggregationDimension<TDimension>,
-): FieldAggregationSchema<"median", NumericAggregationDimension<TDimension>> =>
- fieldAggregation("median", "Median", dimension);
-
-export const distinct = <TDimension>(
+ options?: AggregationOptions<TName>,
+): FieldAggregationSchema<
+ "avg",
+ NumericAggregationDimension<TDimension>,
+ "number",
+ NoInfer<TName>
+> => fieldAggregation("avg", "Average", dimension, options);
+
+export const median = <TDimension, const TName extends string = "median">(
+ dimension: NumericAggregationDimension<TDimension>,
+ options?: AggregationOptions<TName>,
+): FieldAggregationSchema<
+ "median",
+ NumericAggregationDimension<TDimension>,
+ "number",
+ NoInfer<TName>
+> => fieldAggregation("median", "Median", dimension, options);
+
+export const distinct = <TDimension, const TName extends string = "count">(
dimension: TDimension,
-): FieldAggregationSchema<"distinct", TDimension> =>
- fieldAggregation("distinct", "Distinct values", dimension);
+ options?: AggregationOptions<TName>,
+): FieldAggregationSchema<"distinct", TDimension, "number", NoInfer<TName>> =>
+ fieldAggregation("distinct", "Distinct values", dimension, options);
-export const min = <TDimension>(
+export const min = <TDimension, const TName extends string = "min">(
dimension: OrderableAggregationDimension<TDimension>,
-): FieldAggregationSchema<"min", OrderableAggregationDimension<TDimension>> =>
- fieldAggregation("min", "Minimum", dimension);
-
-export const max = <TDimension>(
+ options?: AggregationOptions<TName>,
+): FieldAggregationSchema<
+ "min",
+ OrderableAggregationDimension<TDimension>,
+ "number",
+ NoInfer<TName>
+> => fieldAggregation("min", "Minimum", dimension, options);
+
+export const max = <TDimension, const TName extends string = "max">(
dimension: OrderableAggregationDimension<TDimension>,
-): FieldAggregationSchema<"max", OrderableAggregationDimension<TDimension>> =>
- fieldAggregation("max", "Maximum", dimension);
+ options?: AggregationOptions<TName>,
+): FieldAggregationSchema<
+ "max",
+ OrderableAggregationDimension<TDimension>,
+ "number",
+ NoInfer<TName>
+> => fieldAggregation("max", "Maximum", dimension, options);
const fieldAggregation = <
TOperator extends FieldAggregationOperator,
TDimension,
+ TName extends string,
>(
type: TOperator,
displayName: string,
dimension: TDimension,
-): FieldAggregationSchema<TOperator, TDimension> =>
+ options: AggregationOptions<TName> | undefined,
+): FieldAggregationSchema<TOperator, TDimension, "number", TName> =>
// The column's `name`/`jsType` are computed at runtime (`string` /
- // `SchemaJavaScriptType`), while the schema type states them as the conditional
- // literals derived from `TOperator` — TS can't connect the two.
+ // `SchemaJavaScriptType`), while the schema type states them as the literals
+ // derived from `TName` and `TOperator` — TS can't connect the two.
({
type: "operator",
operator: type,
args: [dimension],
+ ...(options && { name: options.name }),
columns: [
{
- name: getFieldAggregationColumnName(type),
+ name: options?.name ?? getFieldAggregationColumnName(type),
displayName,
jsType: getFieldAggregationColumnJavaScriptType(type, dimension),
},
],
- }) as unknown as FieldAggregationSchema<TOperator, TDimension>;
+ }) as unknown as FieldAggregationSchema<
+ TOperator,
+ TDimension,
+ "number",
+ TName
+ >;
const getFieldAggregationColumnName = (
type: FieldAggregationOperator,
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx
index c2728bf554a..1844799d8a3 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/dynamic-query.unit.spec.tsx
@@ -6,7 +6,7 @@ import { TEST_SCHEMA } from "./fixtures";
import { resolveDatasetQuery as resolveDatasetQueryInBundle } from "embedding-sdk-bundle/lib/create-metabase-query";
import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
-import { count, filter, orderBy } from "..";
+import { count, filter, orderBy, sum } from "..";
beforeEach(resetTestState);
afterEach(() => {
@@ -186,6 +186,78 @@ describe("dynamic query clauses", () => {
});
});
+ // Products' ID is reachable through PRODUCT_ID under the same name.
+ it.each([
+ ["the published card", false],
+ ["the dev preview table", true],
+ ])(
+ "tells a result column from a same-named implicitly joinable column on %s",
+ async (_source, isDataAppDev) => {
+ EMBEDDING_SDK_CONFIG.isDataAppDev = isDataAppDev;
+
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(
+ STATIC_QUERY,
+ {
+ orderBys: [orderBy(TEST_SCHEMA.tables.orders.fields.id, "desc")],
+ },
+ );
+
+ expect(stagesOf(datasetQuery)[1]).toMatchObject({
+ "order-by": [
+ ["desc", expect.anything(), ["field", expect.anything(), "ID"]],
+ ],
+ });
+ },
+ );
+
+ // Unnamed, both sums return a column named `sum`, and the later stage cannot
+ // tell them apart.
+ it("orders the dynamic stage by one of two sums, by its name", async () => {
+ EMBEDDING_SDK_CONFIG.isDataAppDev = true;
+
+ const totalAmount = sum(TEST_SCHEMA.tables.orders.fields.amount, {
+ name: "total amount",
+ });
+ const totalIds = sum(TEST_SCHEMA.tables.orders.fields.id, {
+ name: "total ids",
+ });
+
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())(
+ {
+ ...STATIC_QUERY,
+ aggregations: [totalAmount, totalIds],
+ breakouts: [TEST_SCHEMA.tables.orders.fields.status],
+ },
+ { orderBys: [orderBy(totalIds, "desc")] },
+ );
+
+ expect(stagesOf(datasetQuery)).toMatchObject([
+ {
+ aggregation: [
+ [
+ "sum",
+ expect.objectContaining({ name: "total amount" }),
+ expect.anything(),
+ ],
+ [
+ "sum",
+ expect.objectContaining({ name: "total ids" }),
+ expect.anything(),
+ ],
+ ],
+ },
+ {
+ "order-by": [
+ [
+ "desc",
+ expect.anything(),
+ ["field", expect.anything(), "total ids"],
+ ],
+ ],
+ },
+ ]);
+ });
+
it("rejects table-scoped references in the dynamic part", async () => {
await expect(
resolveDatasetQueryInBundle(createMockStore())(STATIC_QUERY, {
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.ts
index 7c9cc19e876..21fe0563edc 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/fixtures.ts
@@ -105,6 +105,7 @@ export const TEST_SCHEMA = {
type: "measure" as const,
id: 21,
tableId: 1,
+ name: "Revenue",
columns: [{ name: "sum", displayName: "Sum", jsType: "number" }],
},
},
@@ -132,6 +133,7 @@ export const TEST_SCHEMA = {
revenue: {
type: "metric" as const,
id: 31,
+ name: "Revenue",
sourceTableId: 1,
mappedTableIds: [1, 2],
columns: [{ name: "sum", displayName: "Revenue", jsType: "number" }],
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsx
index 5a61c8f8e30..1b6378672a1 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/resolve-dataset-query.unit.spec.tsx
@@ -400,8 +400,8 @@ describe("resolveDatasetQuery", () => {
filters: [filter(TEST_SCHEMA.tables.orders.fields.status, "=", "paid")],
});
- // The generated field's `tableId`/`sourceName` scope it to the orders table;
- // keeping them would stop it matching the question's own STATUS column.
+ // The question's STATUS column comes from the orders table, so the table
+ // field's `tableId` still matches it.
expect(stagesOf(datasetQuery)[0].filters).toEqual([
["=", expect.anything(), ["field", expect.anything(), "STATUS"], "paid"],
]);
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts
index ea01a750079..20df24f0f09 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-invalid.ts
@@ -188,6 +188,18 @@ function InvalidTypeFixtures() {
// @ts-expect-error aggregation result rows should not include source fields
void scalarAggregationResult.data?.rows[0]?.amount;
+ const namedAggregationResult = useMetabaseQuery(
+ defineQuery({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [
+ sum(TEST_SCHEMA.tables.orders.fields.amount, { name: "total amount" }),
+ ],
+ }),
+ );
+
+ // @ts-expect-error a named aggregation's column takes its name, not `sum`
+ void namedAggregationResult.data?.rows[0]?.sum;
+
const metricResult = useMetabaseQuery(
defineQuery({
source: TEST_SCHEMA.tables.orders,
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts
index d4e6eca0d7c..c3c4cd1b3c6 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/tests/type-contract-valid.ts
@@ -139,6 +139,24 @@ function ValidTypeFixtures() {
void scalarAggregationValue;
+ const namedAggregationResult = useMetabaseQuery(
+ defineQuery({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [
+ count({ name: "orders" }),
+ sum(TEST_SCHEMA.tables.orders.fields.amount, { name: "total amount" }),
+ ],
+ }),
+ );
+
+ const namedCountValue: number | null | undefined =
+ namedAggregationResult.data?.rows[0]?.orders;
+ const namedSumValue: RowValue | undefined =
+ namedAggregationResult.data?.rows[0]?.["total amount"];
+
+ void namedCountValue;
+ void namedSumValue;
+
const groupedMetricResult = useMetabaseQuery(
defineQuery<OrdersTable>({
source: TEST_SCHEMA.tables.orders,
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
index de14fcaad60..279bcf8b18b 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
@@ -133,21 +133,25 @@ export type FieldReference<TTable = unknown> =
| LocalFieldReference<TTable>
| JoinedFieldReference;
+// `name` names the result column, which is how a later stage refers to it. A
+// query with two aggregations of the same kind needs it to tell them apart.
export type CountAggregation = {
type: "operator";
operator: "count";
args: [];
+ name?: string;
};
-export type CountAggregationSchema = CountAggregation & {
- columns: readonly [
- {
- name: "count";
- displayName: "Count";
- jsType: "number";
- },
- ];
-};
+export type CountAggregationSchema<TName extends string = "count"> =
+ CountAggregation & {
+ columns: readonly [
+ {
+ name: TName;
+ displayName: "Count";
+ jsType: "number";
+ },
+ ];
+ };
type CountAggregationColumn = CountAggregationSchema["columns"][number];
@@ -166,16 +170,18 @@ export type FieldAggregation<
type: "operator";
operator: TOperator;
args: readonly [TDimension];
+ name?: string;
};
export type FieldAggregationSchema<
TOperator extends FieldAggregationOperator = FieldAggregationOperator,
TDimension = unknown,
TJavaScriptType extends SchemaJavaScriptType = "number",
+ TName extends string = TOperator extends "distinct" ? "count" : TOperator,
> = FieldAggregation<TOperator, TDimension> & {
columns: readonly [
{
- name: TOperator extends "distinct" ? "count" : TOperator;
+ name: TName;
displayName: string;
jsType: TJavaScriptType;
},
diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
index f86c0929372..6ef3842fe5f 100644
--- a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
@@ -149,13 +149,13 @@ function toResultColumnStageSpec({
}
// A card stage exposes the saved question's result columns, so they are looked
-// up by name. Keys that scope a column to a table narrow that lookup and stop
-// it matching, so drop them from generated table fields used as result columns.
+// up by name. `sourceName` and `displayName` describe the table field rather
+// than the result column and stop it matching, so they are dropped. `tableId`
+// and `sourceFieldId` stay: a result column keeps both, and they tell it apart
+// from a same-named column reachable through an FK.
function toResultColumnSpec<TSpec extends TestColumnSpec>(spec: TSpec) {
const {
- tableId: _tableId,
sourceName: _sourceName,
- sourceFieldId: _sourceFieldId,
displayName: _displayName,
...resultColumn
} = spec;
diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts
index 45f551b2bf0..53ada02d604 100644
--- a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts
@@ -344,6 +344,16 @@ function getAggregationResultColumnNames(
aggregations: readonly unknown[] | undefined,
) {
return (aggregations ?? []).flatMap((aggregation) => {
+ // Metrics and Measures also carry a `name`, but it is their title, not a
+ // result column name.
+ if (
+ isObject(aggregation) &&
+ aggregation.type === "operator" &&
+ typeof aggregation.name === "string"
+ ) {
+ return [aggregation.name];
+ }
+
if (isCountAggregation(aggregation)) {
return ["count"];
}
diff --git a/frontend/src/metabase-types/api/query.ts b/frontend/src/metabase-types/api/query.ts
index 5996bd9d0b4..4f0e30ad4ea 100644
--- a/frontend/src/metabase-types/api/query.ts
+++ b/frontend/src/metabase-types/api/query.ts
@@ -521,6 +521,10 @@ export type TestOperatorSpec = {
type: "operator";
operator: string;
args?: readonly TestExpressionSpec[];
+
+ // For an aggregation: the name of its result column, which a later stage
+ // refers to.
+ name?: string;
};
export type TestTemporalBucketSpec = {
diff --git a/skills/metabase-data-app-semantic-layer/SKILL.md b/skills/metabase-data-app-semantic-layer/SKILL.md
index a83dd361d9e..458e5fa372d 100644
--- a/skills/metabase-data-app-semantic-layer/SKILL.md
+++ b/skills/metabase-data-app-semantic-layer/SKILL.md
@@ -292,7 +292,24 @@ export const AmountByCategory = defineQuery({
});
```
-When using the same helper more than once, Metabase may return numbered runtime keys such as `sum`, `sum_2`, and `sum_3`. TypeScript only models the base helper key today. For custom KPI code that intentionally uses repeated same-kind aggregations, read through `data.columns` or cast the row to `Record<string, unknown>` before accessing numbered keys. Prefer curated measures or separate queries when that is clearer.
+When a query uses the same helper more than once, give each one a `name`. The name becomes the result column's name and the row key, it is typed, and it is how `orderBy(...)` and runtime clauses refer to that aggregation. Without names, the columns come back as `sum`, `sum_2`, and so on, and sorting or filtering by one of them fails:
+
+```ts
+const totalAmount = aggregations.sum(recordsTable.fields.amount, {
+ name: "total_amount",
+});
+const totalTax = aggregations.sum(recordsTable.fields.tax, {
+ name: "total_tax",
+});
+
+export const TaxByCategory = defineQuery({
+ source: recordsTable,
+ aggregations: [totalAmount, totalTax],
+ breakouts: [breakout(recordsTable.fields.category)],
+ orderBys: [orderBy(totalTax, "desc")],
+});
+// Rows are keyed `total_amount` and `total_tax`.
+```
Table fields, segments, measures, filters, breakouts, and orderBys must come from the queried table. Use `defineQuery<RecordsTable>({ ... })` when you want TypeScript to validate that ownership at the definition.
@@ -630,7 +647,7 @@ const orderFilters = useMemo(
- Treat row values as nullable. Guard before calling number/string methods such as `toFixed`, `toLocaleString`, or string transforms.
- Use `rawRows` only for known positional shapes.
- Aggregation columns may be named `count`, `sum`, or `avg`; match metadata when needed.
-- If a custom visualization needs several helper aggregations with the same output name, such as multiple `aggregations.sum(...)` calls, prefer separate single-aggregation queries so each typed row has the known `sum` key. If one multi-aggregation query is necessary, read `rawRows` by column position after checking `data.columns`; do not depend on generated names like `sum_2` unless they are explicitly typed or narrowed in the app code.
+- If a query has several helper aggregations of the same kind, such as multiple `aggregations.sum(...)` calls, name each one (`{ name: "..." }`) and read the rows by those names. Never depend on generated names like `sum_2`.
- Grouped queries can include a `null` breakout bucket. Render it as `"Unknown"` or filter it out deliberately.
- Time-series charts need multiple ordered buckets. Do not fake sparklines for scalar or one-point results.
- Multi-series charts with different units or magnitudes need separate axes or normalization.
diff --git a/skills/metabase-data-app-setup/.gitignore b/skills/metabase-data-app-setup/.gitignore
new file mode 100644
index 00000000000..4487a70e91b
--- /dev/null
+++ b/skills/metabase-data-app-setup/.gitignore
@@ -0,0 +1,6 @@
+template/dist
+template/package-lock.json
+template/yarn.lock
+template/pnpm-lock.yaml
+template/bun.lock
+template/bun.lockb
diff --git a/skills/metabase-data-app-setup/SKILL.md b/skills/metabase-data-app-setup/SKILL.md
index fc19a98cc78..9d8900b439d 100644
--- a/skills/metabase-data-app-setup/SKILL.md
+++ b/skills/metabase-data-app-setup/SKILL.md
@@ -128,10 +128,7 @@ Once the template is in `<repo>/data_apps/<slug>/` (run everything below from th
> **Never ask the user to paste the API key into the chat, and never `cat` / `echo` / print `.env.local` or its variables.** It's git-ignored and may hold *other* secrets — the file's contents and the key must never enter the conversation or your context. Every command that needs the key `source`s the file (as above) so the shell uses the value directly; you only ever see the `creds present` / `MISSING` signal, never the secret itself. (`creds present` only means both vars are filled and not the default `mb_replace_me` placeholder — not that the URL or key are valid; a bad key surfaces later when a request fails.)
5. `npm install` (or whichever package manager the user prefers — the template ships with no lockfile, so `npm` / `yarn` / `pnpm` / `bun` all work; use the project's existing lockfile if one appears post-clone).
-6. **Fix the app's `.gitignore` so the lockfile *and* the built bundle get committed.** Two things must end up tracked in the remote-sync repo:
- - **Lockfile** — strip the lockfile-ignoring block (the chunk between `# Lockfiles —` and `bun.lockb`, covering `package-lock.json` / `yarn.lock` / `pnpm-lock.yaml` / `bun.lock` / `bun.lockb`) so the project commits its lockfile for reproducible installs.
- - **The built bundle** — Metabase serves the file at the `path` declared in `data_app.yaml` (the template builds to `dist/index.js`, the default `path`) straight from the committed Git tree, so **that file must be committed**. If the template's `.gitignore` ignores `dist/` (or wherever your build outputs), remove that line.
- **Verify with `git status`** — after `npm install` + a build, both the generated lockfile and the built bundle (the file `path` points at) must appear as untracked/committable files. If either doesn't, the relevant `.gitignore` line is still there; remove it and re-check. Do **not** skip this — agents have repeatedly shipped projects with no committed lockfile or an un-synced bundle.
+6. **The lockfile and the built bundle must both be committed.** Metabase serves the file at the `path` declared in `data_app.yaml` (the template builds to `dist/index.js`) straight from the committed Git tree, and the lockfile keeps installs reproducible. **Verify with `git status`** after `npm install` and a build: both must appear as committable files.
7. `npm run dev` and confirm the preview at http://localhost:5174 renders the starter "Hello, data app" message.
8. If the preview hits CORS, add `http://localhost:5174` under Admin → Embedding → Embedded analytics SDK → CORS.
9. **Edit `data_app.yaml`** (it ships with the template, in the app directory). This is the per-app config Metabase reads on sync — one file per app. Fill in its fields for this app:
diff --git a/skills/metabase-data-app-setup/template/.gitignore b/skills/metabase-data-app-setup/template/.gitignore
index 1da42fddcc3..38028ade26b 100644
--- a/skills/metabase-data-app-setup/template/.gitignore
+++ b/skills/metabase-data-app-setup/template/.gitignore
@@ -1,16 +1,4 @@
node_modules
.env.local
.vite
-dist
.idea
-
-# Lockfiles — the template is package-manager agnostic; don't commit any
-# generated lockfile from `npm install` / `yarn` / `pnpm install` / `bun install`.
-# Downstream projects scaffolded from this template should DELETE these lines
-# from their own .gitignore once they pick a package manager — they'll want
-# their lockfile committed for reproducible installs.
-package-lock.json
-yarn.lock
-pnpm-lock.yaml
-bun.lock
-bun.lockb
\ No newline at end of file
diff --git a/src/metabase/lib/query/test_spec.cljc b/src/metabase/lib/query/test_spec.cljc
index 86d348212ce..43e97a24b50 100644
--- a/src/metabase/lib/query/test_spec.cljc
+++ b/src/metabase/lib/query/test_spec.cljc
@@ -1,5 +1,5 @@
(ns metabase.lib.query.test-spec
- (:refer-clojure :exclude [mapv name])
+ (:refer-clojure :exclude [mapv name not-empty])
(:require
[malli.core :as mc]
[malli.transform :as mtx]
@@ -16,6 +16,7 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
[metabase.lib.native :as lib.native]
+ [metabase.lib.options :as lib.options]
[metabase.lib.order-by :as lib.order-by]
[metabase.lib.query :as lib.query]
[metabase.lib.ref :as lib.ref]
@@ -33,7 +34,7 @@
[metabase.util :as u]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
- [metabase.util.performance :refer [mapv]]))
+ [metabase.util.performance :refer [mapv not-empty]]))
(mu/defn- find-source :- [:or ::lib.schema.metadata/table ::lib.schema.metadata/card]
[metadata-providerable :- ::lib.schema.metadata/metadata-providerable
@@ -45,9 +46,10 @@
(mu/defn- matches-column? :- :boolean
[query :- ::lib.schema/query
_stage-number :- :int
+ name-key :- :keyword
{:keys [name table-id source-name source-field-id display-name]} :- ::lib.schema.test-spec/test-order-by-spec
column :- ::lib.schema.metadata/column]
- (cond-> (= name (:name column))
+ (cond-> (= name (name-key column))
(some? table-id) (and (= table-id (:table-id column)))
(some? source-name) (and (= source-name (some->> column :table-id (lib.metadata/table query) :name)))
(some? source-field-id) (and (= source-field-id ((some-fn :fk-field-id :lib/original-fk-field-id) column)))
@@ -58,7 +60,12 @@
stage-number :- :int
available-columns :- [:sequential ::lib.schema.metadata/column]
column-spec :- ::lib.schema.test-spec/test-order-by-spec]
- (let [columns (filterv (partial matches-column? query stage-number column-spec) available-columns)]
+ (let [matching (fn [name-key]
+ (filterv (partial matches-column? query stage-number name-key column-spec) available-columns))
+ ;; A saved card stores repeated names deduplicated (`ID`, `ID_2`), so a spec naming the column as its table
+ ;; does matches nothing; the name it had before deduplication still finds it.
+ columns (or (not-empty (matching :name))
+ (matching :lib/original-name))]
(case (count columns)
0 (throw (ex-info "No column found" {:columns available-columns, :column-spec column-spec}))
1 (first columns)
@@ -305,9 +312,12 @@
(if-let [aggregation (saved-aggregation query aggregation-spec)]
(lib.aggregation/aggregate query stage-number aggregation)
(throw (ex-info "No saved aggregation found" {:aggregation-spec aggregation-spec})))
- (->> (lib.aggregation/aggregable-columns query stage-number)
- (expression-spec->expression-clause query stage-number aggregation-spec)
- (lib.aggregation/aggregate query stage-number))))
+ (let [clause (->> (lib.aggregation/aggregable-columns query stage-number)
+ (expression-spec->expression-clause query stage-number aggregation-spec))]
+ (lib.aggregation/aggregate query stage-number
+ (cond-> clause
+ ;; Only the name a later stage refers to; the display name stays derived.
+ (:name aggregation-spec) (lib.options/update-options assoc :name (:name aggregation-spec)))))))
(mu/defn- append-aggregations :- ::lib.schema/query
[query :- ::lib.schema/query
diff --git a/src/metabase/lib/schema/test_spec.cljc b/src/metabase/lib/schema/test_spec.cljc
index ca8cb487e5e..9d49bd513c9 100644
--- a/src/metabase/lib/schema/test_spec.cljc
+++ b/src/metabase/lib/schema/test_spec.cljc
@@ -82,7 +82,9 @@
[:map {:closed true}
[:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :operator]]
[:operator ::test-operator-spec]
- [:args {:default []} [:sequential [:ref ::test-expression-spec]]]])
+ [:args {:default []} [:sequential [:ref ::test-expression-spec]]]
+ ;; For an aggregation: the name of its result column, which a later stage refers to.
+ [:name {:optional true} string?]])
(mr/def ::test-expression-spec
[:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case
diff --git a/src/metabase/typed_schemas/render.clj b/src/metabase/typed_schemas/render.clj
index e59c83ebfbd..d5bc50a0408 100644
--- a/src/metabase/typed_schemas/render.clj
+++ b/src/metabase/typed_schemas/render.clj
@@ -38,7 +38,7 @@
:comment [:entityId :description]}
:metric {:runtime [:type :id :name :databaseId :sourceTableId :sourceCardId
:mappedTableIds :columns :dimensions]
- :comment [:entityId :description :verified :sourceTable]}
+ :comment [:entityId :description :filters :verified :sourceTable]}
:metric-dimension {:runtime [:type :id :fieldId :metricId :tableId :sourceName :sourceFieldId
:name :jsType :baseType :effectiveType :defaultTemporalBucket]
:comment [:displayName :description :semanticType :unit]}
@@ -62,6 +62,7 @@
:displayName "Display name"
:effectiveType "Effective type"
:entityId "Entity ID"
+ :filters "Filters"
:schemaName "Schema"
:semanticType "Semantic type"
:sourceTable "Source table"
@@ -108,12 +109,18 @@
for humans and coding agents, but are intentionally omitted from runtime
objects consumed by the Lib.createTestQuery DSL."
[kind value entry-key]
- (seq (for [comment-key (policy-comment-keys kind value entry-key)
- :let [comment-text (comment-value (get value comment-key))]
- :when (not (str/blank? comment-text))]
- (str (get comment-labels comment-key (name comment-key))
- ": "
- (str/replace comment-text #"\R+" " ")))))
+ (let [single-line #(str/replace % #"\R+" " ")]
+ (seq (mapcat (fn [comment-key]
+ (let [label (get comment-labels comment-key (name comment-key))
+ value (get value comment-key)]
+ ;; A list gets a line per item, so a long one stays readable instead of being truncated.
+ (if (sequential? value)
+ (when (seq value)
+ (cons (str label ":") (map #(str "- " (single-line (str %))) value)))
+ (let [comment-text (comment-value value)]
+ (when-not (str/blank? comment-text)
+ [(str label ": " (single-line comment-text))])))))
+ (policy-comment-keys kind value entry-key)))))
(defn- generic->node
"Converts a schema value without render policy into an AST expression.
diff --git a/src/metabase/typed_schemas/schema/metric.clj b/src/metabase/typed_schemas/schema/metric.clj
index 49cccb72b48..a3b9e35ab6c 100644
--- a/src/metabase/typed_schemas/schema/metric.clj
+++ b/src/metabase/typed_schemas/schema/metric.clj
@@ -2,6 +2,7 @@
"Typed schema generation for metrics and metric dimensions."
(:require
[medley.core :as m]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.metabot.core :as metabot]
[metabase.metrics.core :as metrics]
@@ -11,7 +12,8 @@
[metabase.typed-schemas.db :as typed-schemas.db]
[metabase.typed-schemas.schema.common :as schema.common]
[metabase.typed-schemas.schema.table :as schema.table]
- [metabase.util :as u]))
+ [metabase.util :as u]
+ [metabase.util.log :as log]))
(set! *warn-on-reflection* true)
@@ -20,6 +22,21 @@
[card]
(schema.common/aggregation-result-column (:database_id card) (:dataset_query card)))
+(defn- metric-filters
+ "Returns the display names of the filters `card`'s query applies. The schema exposes a metric only as an
+ aggregation, so they are the only hint that it counts a subset of the rows."
+ [card]
+ (when-let [query-definition (not-empty (:dataset_query card))]
+ (try
+ (let [query (lib/query (lib-be/application-database-metadata-provider (:database_id card))
+ query-definition)]
+ (not-empty (vec (for [stage-number (range (lib/stage-count query))
+ filter-clause (lib/filters query stage-number)]
+ (lib/display-name query stage-number filter-clause)))))
+ (catch Exception e
+ (log/warnf e "Could not describe the filters of metric %s" (:id card))
+ nil))))
+
(defn- metric-details-error-message
[card error-message]
(format "Failed to build schema details for metric \"%s\" (card %s): %s"
@@ -267,6 +284,7 @@
:sourceCardId source-card-id-value
:entityId portable_entity_id
:description description
+ :filters (metric-filters card)
:verified (when verified true)
:sourceTable (source-table-schema base_table_portable_fk)
:mappedTableIds (not-empty mapped-table-ids)
diff --git a/test/metabase/lib/query/test_spec_test.cljc b/test/metabase/lib/query/test_spec_test.cljc
index 74970513094..8ced5e9f890 100644
--- a/test/metabase/lib/query/test_spec_test.cljc
+++ b/test/metabase/lib/query/test_spec_test.cljc
@@ -1244,3 +1244,92 @@
:widget-type :string/contains
:id string?}]
(lib/template-tags query))))))
+
+(defn- orders-column
+ [column-name]
+ {:type :column :name column-name :table-id (meta/id :orders)})
+
+(defn- orders-then
+ [first-stage second-stage]
+ (lib.query.test-spec/test-query
+ meta/metadata-provider
+ {:stages [(assoc first-stage :source {:type :table :id (meta/id :orders)})
+ second-stage]}))
+
+(deftest ^:parallel test-query-later-stage-column-with-table-id-test
+ (testing "USER_ID in the result makes PEOPLE.CREATED_AT joinable next to the CREATED_AT result column; the table
+ tells them apart"
+ (is (=? [[:> {} [:field {:inherited-temporal-unit :month} "CREATED_AT"] "2024-01-01"]]
+ (lib/filters
+ (orders-then {:aggregations [{:type :operator :operator :count :args []}]
+ :breakouts [(assoc (orders-column "CREATED_AT") :unit :month)
+ (orders-column "USER_ID")]}
+ {:filters [{:type :operator
+ :operator :>
+ :args [(orders-column "CREATED_AT")
+ {:type :literal :value "2024-01-01"}]}]})
+ 1)))))
+
+(def ^:private named-sums
+ {:aggregations [{:type :operator :operator :sum :name "sum A" :args [(orders-column "TOTAL")]}
+ {:type :operator :operator :sum :name "sum B" :args [(orders-column "SUBTOTAL")]}]
+ :breakouts [(orders-column "PRODUCT_ID")]})
+
+(deftest ^:parallel test-query-aggregation-result-name-test
+ (let [query (orders-then named-sums {:order-bys [{:type :column :name "sum B" :direction :desc}]})]
+ (testing "an aggregation's :name names its result column, and keeps the display name"
+ (is (=? [{:name "PRODUCT_ID"}
+ {:name "sum A" :display-name "Sum of Total"}
+ {:name "sum B" :display-name "Sum of Subtotal"}]
+ (lib/returned-columns query 0))))
+ (testing "a later stage refers to it by that name"
+ (is (=? [[:desc {} [:field {} "sum B"]]]
+ (lib/order-bys query 1))))))
+
+(deftest ^:parallel test-query-aggregation-result-name-through-card-test
+ (testing "a stage on a saved question refers to the question's named aggregation by that name"
+ (let [card-query (lib.query.test-spec/test-query
+ meta/metadata-provider
+ {:stages [(assoc named-sums :source {:type :table :id (meta/id :orders)})]})
+ query (lib.query.test-spec/test-query
+ (lib.tu/metadata-provider-with-card-from-query 1 card-query)
+ {:stages [{:source {:type :card :id 1}}
+ {:order-bys [{:type :column :name "sum B" :direction :desc}]}]})]
+ (is (=? [[:desc {} [:field {} "sum B"]]]
+ (lib/order-bys query 1))))))
+
+(deftest ^:parallel test-query-later-stage-tells-joined-result-columns-apart-by-fk-test
+ (testing "PRODUCTS.ID and PEOPLE.ID are both named ID; the FK they were reached through picks one"
+ (is (=? [[:< {} [:field {} "PEOPLE__via__USER_ID__ID"] 10]]
+ (lib/filters
+ (orders-then {:aggregations [{:type :operator :operator :count :args []}]
+ :breakouts [{:type :column :name "ID" :source-field-id (meta/id :orders :product-id)}
+ {:type :column :name "ID" :source-field-id (meta/id :orders :user-id)}]}
+ {:filters [{:type :operator
+ :operator :<
+ :args [{:type :column :name "ID" :source-field-id (meta/id :orders :user-id)}
+ {:type :literal :value 10}]}]})
+ 1)))))
+
+(deftest ^:parallel test-query-joined-result-column-through-card-test
+ (testing "a saved card stores the second joined ID as ID_2; its original name and FK still pick it"
+ (let [card-query (lib.query.test-spec/test-query
+ meta/metadata-provider
+ {:stages [{:source {:type :table :id (meta/id :orders)}
+ :aggregations [{:type :operator :operator :count :args []}]
+ :breakouts [{:type :column :name "ID" :source-field-id (meta/id :orders :product-id)}
+ {:type :column :name "ID" :source-field-id (meta/id :orders :user-id)}]}]})
+ ;; Saved result metadata carries the deduplicated names, as the query processor returns them.
+ mp (lib.tu/metadata-provider-with-card-from-query
+ meta/metadata-provider 1 card-query
+ {:result-metadata (mapv #(assoc % :name (:lib/deduplicated-name %))
+ (lib/returned-columns card-query))})
+ query (lib.query.test-spec/test-query
+ mp
+ {:stages [{:source {:type :card :id 1}}
+ {:filters [{:type :operator
+ :operator :<
+ :args [{:type :column :name "ID" :source-field-id (meta/id :orders :user-id)}
+ {:type :literal :value 10}]}]}]})]
+ (is (=? [[:< {} [:field {} "PEOPLE__via__USER_ID__ID"] 10]]
+ (lib/filters query 1))))))
diff --git a/test/metabase/typed_schemas/render_test.clj b/test/metabase/typed_schemas/render_test.clj
index 929d650b118..bf553b03296 100644
--- a/test/metabase/typed_schemas/render_test.clj
+++ b/test/metabase/typed_schemas/render_test.clj
@@ -52,6 +52,7 @@
:databaseId 1
:sourceTableId 10
:description "Total order revenue"
+ :filters ["Status is paid" "Created At is in the previous 30 days"]
:mappedTableIds [10 20]
:dimensions {"paymentMethod" payment-method-dimension
"franchiseName" franchise-name-dimension}})
@@ -78,6 +79,7 @@
;; Emit comments to provide context for agents
(is (str/includes? body "// Description: Saved orders"))
(is (str/includes? body "// Description: Total order revenue"))
+ (is (re-find #"// Filters:\n\s*// - Status is paid\n\s*// - Created At is in the previous 30 days\n" body))
(is (str/includes? body "// Display name: Payment Method"))
(is (str/includes? body "// Semantic type: type/Category"))
;; Emit metadata needed for the Lib.createTestQuery DSL
@@ -87,7 +89,8 @@
(is (str/includes? body "sourceTableId: 10"))
(is (str/includes? body "mappedTableIds: [ 10, 20 ]"))
;; Comment-only metadata should not become runtime fields.
- (is (not (str/includes? body "displayName: \"Payment Method\"")))))
+ (is (not (str/includes? body "displayName: \"Payment Method\"")))
+ (is (not (str/includes? body "filters:")))))
(deftest typescript-renderer-compacts-metric-dimensions-test
(let [body (typed-schemas/render-typescript compacting-schema)]
diff --git a/test/metabase/typed_schemas/schema/metric_test.clj b/test/metabase/typed_schemas/schema/metric_test.clj
index 48075ec5b34..08181085594 100644
--- a/test/metabase/typed_schemas/schema/metric_test.clj
+++ b/test/metabase/typed_schemas/schema/metric_test.clj
@@ -1,6 +1,7 @@
(ns metabase.typed-schemas.schema.metric-test
(:require
[clojure.test :refer :all]
+ [metabase.lib.core :as lib]
[metabase.metabot.core :as metabot]
[metabase.models.interface :as mi]
[metabase.permissions.core :as perms]
@@ -55,6 +56,37 @@
(is (= 42 (#'schema.metric/source-card-id
{:dataset_query {:stages [{:source-card 42}]}})))))
+(defn- orders-metric-query
+ [filters]
+ (lib/test-query
+ (mt/metadata-provider)
+ {:stages [{:source {:type :table :id (mt/id :orders)}
+ :filters filters
+ :aggregations [{:type :operator :operator :sum
+ :args [{:type :column :name "TOTAL" :table-id (mt/id :orders)}]}]}]}))
+
+(deftest metric-filters-test
+ (testing "a metric's filters are described the way the query builder names them"
+ (mt/with-temp [:model/Card card {:type :metric
+ :database_id (mt/id)
+ :dataset_query (orders-metric-query
+ [{:type :operator :operator :>=
+ :args [{:type :column :name "CREATED_AT" :table-id (mt/id :orders)}
+ {:type :literal :value "2025-01-01"}]}
+ {:type :operator :operator :=
+ :args [{:type :column :name "CATEGORY"
+ :source-field-id (mt/id :orders :product_id)}
+ {:type :literal :value "Widget"}]}])}]
+ (is (= ["Created At is greater than or equal to \"2025-01-01\"" "Category is Widget"]
+ (#'schema.metric/metric-filters card)))))
+ (testing "a metric without filters has none"
+ (mt/with-temp [:model/Card card {:type :metric
+ :database_id (mt/id)
+ :dataset_query (orders-metric-query [])}]
+ (is (nil? (#'schema.metric/metric-filters card)))))
+ (testing "a card without a query has none"
+ (is (nil? (#'schema.metric/metric-filters {:id 247 :dataset_query {}})))))
+
(deftest metric-details-skips-default-temporal-breakout-test
(let [requested (atom nil)]
(mt/with-dynamic-fn-redefs [metabot/get-metric-details