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
Native Query Snippet Params (#62283)
Williamc80fea158712
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 431080279b6..09cd70521b7 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -718,6 +718,7 @@metabase.native-query-snippets.core}:uses #{apicollections+ libmodelspermissionspremium-featuresdiff --git a/e2e/support/helpers/api/createSnippet.ts b/e2e/support/helpers/api/createSnippet.tsindex c78123a5316..7a8ff1936fa 100644--- a/e2e/support/helpers/api/createSnippet.ts+++ b/e2e/support/helpers/api/createSnippet.ts@@ -1,12 +1,27 @@+import type {+ NativeQuerySnippet,+ RegularCollectionId,+} from "metabase-types/api";++export type NativeQuerySnippetDetails = {+ name?: string;+ description?: string | null;+ content: string;+ collection_id?: RegularCollectionId | null;+};+export function createSnippet({- name,+ name = "Test snippet",+ description = null,content,-}: {- name: string;- content: string;-}): Cypress.Chainable<Cypress.Response<NativeQuerySnippet>> {- cy.request("POST", "/api/native-query-snippet", {+ collection_id = null,+}: NativeQuerySnippetDetails): Cypress.Chainable<+ Cypress.Response<NativeQuerySnippet>+> {+ return cy.request("POST", "/api/native-query-snippet", {name,+ description,content,+ collection_id,});}diff --git a/e2e/support/helpers/e2e-misc-helpers.js b/e2e/support/helpers/e2e-misc-helpers.jsindex c89d1868682..758f4f37c25 100644--- a/e2e/support/helpers/e2e-misc-helpers.js+++ b/e2e/support/helpers/e2e-misc-helpers.js@@ -281,6 +281,7 @@ export function interceptIfNotPreviouslyDefined({ method, url, alias } = {}) {* @param {boolean=} [options.addToDashboard]* @param {boolean=} [options.wrapId]* @param {string=} [options.idAlias]+ * @param {Object=} [pickEntityOptions]*/export function saveQuestion(name,diff --git a/e2e/test/scenarios/native/snippet-tags.cy.spec.ts b/e2e/test/scenarios/native/snippet-tags.cy.spec.tsnew file mode 100644index 00000000000..d2073288288--- /dev/null+++ b/e2e/test/scenarios/native/snippet-tags.cy.spec.ts@@ -0,0 +1,404 @@+const { H } = cy;++import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";++describe("scenarios > native > snippet tags", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ });++ it("should be able to create a snippet with variable tags", () => {+ H.startNewNativeQuestion();+ H.NativeEditor.type("select id from products where ");++ cy.log("create a snippet");+ getEditorTopBar().icon("snippet").click();+ getEditorSidebar().findByText("Create snippet").click();+ H.modal().within(() => {+ getSnippetContentInput().type("category = {{category}}", {+ parseSpecialCharSequences: false,+ });+ getSnippetNameInput().type("variable-snippet");+ cy.button("Save").click();+ });++ cy.log("verify that the snippet was inserted");+ H.NativeEditor.get().should(+ "contain",+ "select id from products where {{snippet: variable-snippet}}",+ );++ cy.log("verify that the query can be run");+ getEditorTopBar().findByPlaceholderText("Category").type("Widget");+ H.runNativeQuery();+ H.assertQueryBuilderRowCount(54);+ });++ it("should be able to create a snippet with card tags", () => {+ H.startNewNativeQuestion();+ H.NativeEditor.type("select * from ");++ cy.log("create a snippet");+ getEditorTopBar().icon("snippet").click();+ getEditorSidebar().findByText("Create snippet").click();+ H.modal().within(() => {+ getSnippetContentInput().type(`{{#${ORDERS_QUESTION_ID}}}`, {+ parseSpecialCharSequences: false,+ });+ getSnippetNameInput().type("card-snippet");+ cy.button("Save").click();+ });++ cy.log("verify that the snippet was inserted");+ H.NativeEditor.get().should(+ "contain",+ "select * from {{snippet: card-snippet}}",+ );++ cy.log("verify that the query can be run");+ H.runNativeQuery();+ H.tableInteractive().should("be.visible");+ });++ it("should be able to create a snippet with snippet tags", () => {+ H.startNewNativeQuestion();+ H.NativeEditor.type("select * from ");++ cy.log("create a snippet");+ getEditorTopBar().icon("snippet").click();+ getEditorSidebar().findByText("Create snippet").click();+ H.modal().within(() => {+ getSnippetContentInput().type("category = {{category}}", {+ parseSpecialCharSequences: false,+ });+ getSnippetNameInput().type("snippet1");+ cy.button("Save").click();+ });++ cy.log("create a snippet that uses the previous snippet");+ getEditorTopBar().icon("snippet").click();+ getEditorSidebar().icon("add").click();+ H.popover().findByText("New snippet").click();+ H.modal().within(() => {+ getSnippetContentInput().type("{{snippet: snippet1}}", {+ parseSpecialCharSequences: false,+ });+ getSnippetNameInput().type("snippet2");+ cy.button("Save").click();+ });++ cy.log("verify that the snippet can used");+ H.NativeEditor.clear();+ H.NativeEditor.type("select id from products where {{snippet: snippet2}}");+ getEditorTopBar().findByLabelText("Category").type("Gizmo");+ H.runNativeQuery();+ H.tableInteractive().should("be.visible");+ });++ it("should be able to create a tag with the same name as the inner snippet tag", () => {+ createQuestionAndSnippet().then(({ card }) => {+ H.visitQuestion(card.id);+ });++ cy.log("add a local tag with the same name");+ getEditorVisibilityToggler().click();+ H.NativeEditor.type(" and category = {{filter}}");++ cy.log("verify that the query can be run");+ getEditorTopBar().findByPlaceholderText("Filter").type("Widget");+ H.runNativeQuery();+ H.assertQueryBuilderRowCount(54);+ });++ it("should be able to use snippets where tags overlap", () => {+ cy.log("create snippets with overlapping tags");+ H.createSnippet({+ name: "snippet1",+ content: "category = {{category1}} or category = {{category2}}",+ });+ H.createSnippet({+ name: "snippet2",+ content: "category = {{category2}}",+ });++ cy.log("use both snippets in a query");+ H.startNewNativeQuestion();+ H.NativeEditor.type(+ "select id from products where {{snippet: snippet1}} or {{snippet: snippet2}}",+ );++ cy.log("verify that the query can be run");+ getEditorTopBar().findByPlaceholderText("Category1").type("Widget");+ getEditorTopBar().findByPlaceholderText("Category2").type("Gadget");+ H.runNativeQuery();+ H.assertQueryBuilderRowCount(107);+ });++ it("should be able to update a snippet and change tags", () => {+ createQuestionAndSnippet().then(({ card }) => {+ H.visitQuestion(card.id);+ });++ cy.log("update the snippet");+ getEditorVisibilityToggler().click();+ getEditorTopBar().icon("snippet").click();+ getEditorSidebar().within(() => {+ cy.icon("chevrondown").click({ force: true });+ cy.button(/Edit/).click();+ });+ H.modal().within(() => {+ getSnippetContentInput()+ .clear()+ .type("ean = {{ean}} or vendor = {{vendor}}", {+ parseSpecialCharSequences: false,+ });+ cy.button("Save").click();+ });++ cy.log("verify that the tags in the query were updated");+ getEditorTopBar().within(() => {+ cy.findByPlaceholderText("Filter").should("not.exist");+ cy.findByPlaceholderText("Ean").type("1018947080336");+ cy.findByPlaceholderText("Vendor").type("Balistreri-Ankunding");+ });+ H.runNativeQuery();+ H.assertTableRowsCount(2);+ });++ it("should be able to change the inner tag type to Number", () => {+ createQuestionAndSnippet({ snippetContent: "ID = {{filter}}" }).then(+ ({ card }) => {+ H.visitQuestion(card.id);+ },+ );++ cy.log("change the type");+ getEditorVisibilityToggler().click();+ getEditorTopBar().icon("variable").click();+ getVariableTypeSelect().click();+ H.popover().findByText("Number").click();++ cy.log("verify that the parameter can be used");+ getEditorTopBar().findByPlaceholderText("Filter").type("10");+ H.runNativeQuery();+ H.assertQueryBuilderRowCount(1);+ });++ it("should be able to change the inner tag type to Field Filter", () => {+ createQuestionAndSnippet({ snippetContent: "{{filter}}" }).then(+ ({ card }) => {+ H.visitQuestion(card.id);+ },+ );++ cy.log("change the type");+ getEditorVisibilityToggler().click();+ getEditorTopBar().icon("variable").click();+ getVariableTypeSelect().click();+ H.popover().findByText("Field Filter").click();+ H.popover().findByText("Products").click();+ H.popover().findByText("Category").click();++ cy.log("verify that the parameter can be used");+ H.filterWidget().click();+ H.popover().within(() => {+ cy.findByText("Gadget").click();+ cy.button("Add filter").click();+ });+ H.runNativeQuery();+ H.assertQueryBuilderRowCount(53);+ });++ it("should be able to open a question with an old snippet name", () => {+ createQuestionAndSnippet().then(({ card, snippet }) => {+ cy.request("PUT", `/api/native-query-snippet/${snippet.id}`, {+ name: "category-snippet",+ });+ cy.visit(`/question/${card.id}`);+ });++ cy.log("verify that the parameter can be used");+ getEditorTopBar().findByPlaceholderText("Filter").type("Widget");+ H.queryBuilderHeader().icon("play").click();+ H.assertQueryBuilderRowCount(54);+ });++ it("should not be able to create card cycles via snippets", () => {+ cy.log("create a card and a snippet referencing this card");+ H.createNativeQuestion({+ native: {+ query: "select 1",+ },+ }).then(({ body: card }) => {+ H.createSnippet({+ name: "cycle-snippet",+ content: `{{#${card.id}}}`,+ });+ H.visitQuestion(card.id);+ });++ cy.log("create a cycle and try to save the card");+ getEditorVisibilityToggler().click();+ H.NativeEditor.clear();+ H.NativeEditor.type("select * from {{snippet: cycle-snippet}}");+ H.queryBuilderHeader().button("Save").click();+ H.modal().within(() => {+ cy.button("Save").click();+ cy.findByText("Cannot save card with cycles.").should("be.visible");+ });+ });++ it("should not be able to create snippet cycles via snippets", () => {+ cy.log("create two snippets, one using another");+ H.createSnippet({+ name: "snippet1",+ content: "1",+ });+ H.createSnippet({+ name: "snippet2",+ content: "{{snippet: snippet1}}",+ });++ cy.log("open the modal for the first snippet");+ H.startNewNativeQuestion();+ getEditorTopBar().icon("snippet").click();+ getEditorSidebar().within(() => {+ cy.icon("chevrondown")+ .should("have.length", 2)+ .first()+ .click({ force: true });+ cy.button(/Edit/).click();+ });++ cy.log("create a cycle and save the first snippet");+ H.modal().within(() => {+ getSnippetContentInput()+ .clear()+ .type("{{snippet: snippet2}}", { parseSpecialCharSequences: false })+ .click();+ cy.button("Save").click();+ });++ cy.log("run the query and verify that we detect a cycle");+ H.NativeEditor.type("select {{snippet: snippet1}}");+ H.runNativeQuery();+ H.queryBuilderMain()+ .findByText(+ 'This query has circular referencing sub-queries. The snippet "snippet2" and the snippet "snippet1" seem to be part of the problem.',+ )+ .should("be.visible");++ cy.log(+ "try to save a question with a snippet cycle and verify we detect it",+ );+ H.queryBuilderHeader().findByText("Save").click();+ H.modal().within(() => {+ cy.findByLabelText("Name").type("SQL");+ cy.button("Save").click();+ cy.findByText("Cannot save card with cycles.").should("be.visible");+ cy.button("Cancel").click();+ });++ cy.log(+ "remove a cycle, save the card, add a cycle again and verify that we detect it on update",+ );+ H.NativeEditor.clear().type("select 1");+ H.saveQuestion("SQL", undefined, {+ tab: "Browse",+ path: ["Our analytics"],+ });+ H.NativeEditor.clear().type("select {{snippet: snippet1}}");+ H.queryBuilderHeader().button("Save").click();+ H.modal().within(() => {+ cy.button("Save").click();+ cy.findByText("Cannot save card with cycles.").should("be.visible");+ });+ });++ it("should work for a public or embedded question", () => {+ createQuestionAndSnippet().then(({ card }) => {+ cy.log("public question - no parameter value");+ H.visitPublicQuestion(card.id);+ H.assertTableRowsCount(200);++ cy.log("public question - with parameter value");+ H.filterWidget().findByLabelText("Filter").type("Gadget{enter}");+ H.assertTableRowsCount(53);++ cy.log("embedded question - no parameter value");+ H.visitEmbeddedPage({+ resource: { question: card.id },+ params: {},+ });+ H.assertTableRowsCount(200);++ cy.log("embedded question - with parameter value");+ H.filterWidget().findByLabelText("Filter").type("Gadget{enter}");+ H.assertTableRowsCount(53);+ });+ });+});++function getEditorSidebar() {+ return cy.findByTestId("sidebar-right");+}++function getEditorTopBar() {+ return cy.findByTestId("native-query-top-bar");+}++function getEditorVisibilityToggler() {+ return cy.findByTestId("visibility-toggler");+}++function getVariableTypeSelect() {+ return cy.findByTestId("variable-type-select");+}++function getSnippetNameInput() {+ return cy.findByLabelText("Give your snippet a name");+}++function getSnippetContentInput() {+ return cy.findByLabelText("Enter some SQL here so you can reuse it later");+}++function createQuestionAndSnippet({+ snippetContent = "category = {{filter}}",+}: {+ snippetContent?: string;+} = {}) {+ return H.createSnippet({+ name: "filter-snippet",+ content: snippetContent,+ }).then(({ body: snippet }) => {+ return H.createNativeQuestion({+ native: {+ query: "select id from products [[where {{snippet: filter-snippet}}]]",+ "template-tags": {+ "snippet: filter-snippet": {+ id: "4b77cc1f-ea70-4ef6-84db-58432fce6928",+ name: "snippet: filter-snippet",+ "display-name": "snippet: filter-snippet",+ type: "snippet",+ "snippet-id": snippet.id,+ "snippet-name": snippet.name,+ },+ filter: {+ id: "4b77cc1f-ea70-4ef6-84db-58432fce6929",+ name: "filter",+ "display-name": "Filter",+ type: "text",+ },+ },+ },+ enable_embedding: true,+ embedding_params: {+ filter: "enabled",+ },+ }).then(({ body: card }) => {+ return { card, snippet };+ });+ });+}diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.cljindex a770c5a766b..ee57a112f39 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj@@ -963,6 +963,64 @@:content "11 = 11"}(t2/select-one :model/NativeQuerySnippet :entity_id (:entity_id snippet)))))))))+(deftest snippet-template-tags-import-test+ (testing "Template tags import preserves nil, empty, and populated values"++ (testing "Missing template_tags field -> {} when selected"+ (mt/with-empty-h2-app-db!+ (let [snippet-data {:serdes/meta [{:model "NativeQuerySnippet"+ :id "test-entity-1"+ :label "test_snippet_1"}]+ :name "no-tags-field"+ :content "WHERE id = {{id}}"+ :creator_id "[email protected]"+ :entity_id "test-entity-1"}+ ingestion (ingestion-in-memory [snippet-data])]+ (serdes.load/load-metabase! ingestion)+ (let [template-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :entity_id "test-entity-1")]+ ;; Toucan hooks compute the template-tags:+ (is (=? {"id" {:type :text+ :display-name "ID"+ :name "id"}}+ template-tags))))))++ (testing "Empty map template_tags -> preserved as empty map"+ (mt/with-empty-h2-app-db!+ (let [snippet-data {:serdes/meta [{:model "NativeQuerySnippet"+ :id "test-entity-2"+ :label "test_snippet_2"}]+ :name "empty-tags"+ :content "SELECT 1"+ :template_tags {}+ :creator_id "[email protected]"+ :entity_id "test-entity-2"}+ ingestion (ingestion-in-memory [snippet-data])]+ (serdes.load/load-metabase! ingestion)+ (let [template-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :entity_id "test-entity-2")]+ (is (= {} template-tags))))))++ (testing "Snippet template tags get preserved rather than recalculated"+ (mt/with-empty-h2-app-db!+ (let [snippet-data {:serdes/meta [{:model "NativeQuerySnippet"+ :id "test-entity-3"+ :label "test_snippet_3"}]+ :name "with-tags"+ :content "WHERE id = {{snippet: id}}"+ :template_tags {"id" {:type :snippet+ :name "snippet: id"+ :snippet-name "id"+ ;; Definitely not calculated that way:+ :display-name "Snippet: WOOP"}}+ :creator_id "[email protected]"+ :entity_id "test-entity-3"}+ ingestion (ingestion-in-memory [snippet-data])]+ (serdes.load/load-metabase! ingestion)+ (let [template-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :entity_id "test-entity-3")]+ (is (=? {"snippet: id" {:type :snippet+ :name "snippet: id"+ :display-name "Snippet: WOOP"}}+ template-tags))))))))+(deftest load-action-test(let [serialized (atom nil)eid (u/generate-nano-id)]diff --git a/frontend/src/metabase-lib/v1/metadata/Metadata.ts b/frontend/src/metabase-lib/v1/metadata/Metadata.tsindex 3cda43ad6d2..16750f1b3a0 100644--- a/frontend/src/metabase-lib/v1/metadata/Metadata.ts+++ b/frontend/src/metabase-lib/v1/metadata/Metadata.ts@@ -5,6 +5,7 @@ import type {DatabaseId,FieldId,FieldReference,+ NativeQuerySnippet,SchemaId,SegmentId,SettingKey,@@ -45,6 +46,7 @@ class Metadata {fields: Record<string, Field> = {};segments: Record<string, Segment> = {};questions: Record<string, Question> = {};+ snippets: Record<string, NativeQuerySnippet> = {};settings?: Settings;constructor(opts?: MetadataOpts) {diff --git a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.ts b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.tsindex 32ba791a30f..ade224875f8 100644--- a/frontend/src/metabase-lib/v1/parameters/utils/template-tags.ts+++ b/frontend/src/metabase-lib/v1/parameters/utils/template-tags.ts@@ -47,7 +47,7 @@ function getParameterTarget(tag: TemplateTag): ParameterTarget {export function getTemplateTagParameter(tag: TemplateTag,- oldParameter?: Parameter,+ oldParameter?: Partial<Parameter>,): ParameterWithTarget {return {id: tag.id,diff --git a/frontend/src/metabase-lib/v1/queries/NativeQuery.ts b/frontend/src/metabase-lib/v1/queries/NativeQuery.tsindex 8ba18403ad6..a128ff77f4b 100644--- a/frontend/src/metabase-lib/v1/queries/NativeQuery.ts+++ b/frontend/src/metabase-lib/v1/queries/NativeQuery.ts@@ -1,10 +1,9 @@-// eslint-disable-next-line @typescript-eslint/ban-ts-comment-// @ts-nocheckimport { updateIn } from "icepick";import slugg from "slugg";import { t } from "ttag";import _ from "underscore";+import { checkNotNull } from "metabase/lib/types";import * as Lib from "metabase-lib";import type Question from "metabase-lib/v1/Question";import ValidationError from "metabase-lib/v1/ValidationError";@@ -18,6 +17,7 @@ import type {DatabaseId,DatasetQuery,NativeDatasetQuery,+ NativeQuerySnippet,ParameterValuesConfig,TemplateTag,TemplateTags,@@ -51,10 +51,12 @@ function replaceTagName(oldTagName: string,newTagName: string,): NativeQuery {- const queryText = query- .queryText()- .replace(tagRegex(oldTagName), `{{${newTagName}}}`);- return query.setQueryText(queryText);+ const queryText = query.queryText();+ const newQueryText = queryText.replace(+ tagRegex(oldTagName),+ `{{${newTagName}}}`,+ );+ return newQueryText !== queryText ? query.setQueryText(newQueryText) : query;}export function updateCardTemplateTagNames(@@ -67,10 +69,10 @@ export function updateCardTemplateTagNames(// only tags for cards.filter((tag) => tag.type === "card")// only tags for given cards- .filter((tag) => cardById[tag["card-id"]]);+ .filter((tag) => tag["card-id"] != null && cardById[tag["card-id"]]);// reduce over each tag, updating query text with the new tag namereturn tags.reduce((query, tag) => {- const card = cardById[tag["card-id"]];+ const card = cardById[Number(tag["card-id"])];const newTagName = `#${card.id}-${slugg(card.name)}`;return replaceTagName(query, tag.name, newTagName);}, query);@@ -101,7 +103,7 @@ export default class NativeQuery {}private _setQuery(query: Lib.Query): NativeQuery {- return this.question().setQuery(query).legacyNativeQuery();+ return checkNotNull(this.question().setQuery(query).legacyNativeQuery());}/**@@ -203,7 +205,9 @@ export default class NativeQuery {supportsNativeParameters() {const database = this._database();return (- database != null && _.contains(database.features, "native-parameters")+ database != null &&+ database.features != null &&+ _.contains(database.features, "native-parameters"));}@@ -238,11 +242,11 @@ export default class NativeQuery {// NOTE 2: currently cannot be ported to MBQL lib because maps with keys in// different order are considered equal.return new NativeQuery(- this._originalQuestion,+ this._question,updateIn(this._datasetQuery,["native", "template-tags"],- (templateTags) => {+ (templateTags: TemplateTags) => {const entries = Array.from(Object.entries(templateTags));const oldIndex = _.findIndex(entries, (entry) => entry[1].id === id);@@ -298,7 +302,8 @@ export default class NativeQuery {referencedQuestionIds(): number[] {return this.templateTags().filter((tag) => tag.type === "card")- .map((tag) => tag["card-id"]);+ .map((tag) => tag["card-id"])+ .filter((cardId): cardId is number => cardId != null);}private _validateTemplateTags() {@@ -346,26 +351,28 @@ export default class NativeQuery {...oldParameter,...config,});- return this.question()- .setParameter(tag.id, newParameter)- .legacyNativeQuery();+ return checkNotNull(+ this.question().setParameter(tag.id, newParameter).legacyNativeQuery(),+ );}setDatasetQuery(datasetQuery: DatasetQuery): NativeQuery {- return this.question().setDatasetQuery(datasetQuery).legacyNativeQuery();+ return checkNotNull(+ this.question().setDatasetQuery(datasetQuery).legacyNativeQuery(),+ );}dimensionOptions(- dimensionFilter: DimensionFilter = _.identity,- operatorFilter = _.identity,+ dimensionFilter: DimensionFilter = _.constant(true),): DimensionOptions {const dimensions = this.templateTags()- .filter((tag) => tag.type === "dimension" && operatorFilter(tag))+ .filter((tag) => tag.type === "dimension").map((tag) => new TemplateTagDimension(tag.name, this.metadata(), this)).filter((dimension) => dimensionFilter(dimension));return new DimensionOptions({dimensions: dimensions,+ fks: [],count: dimensions.length,});}@@ -379,35 +386,27 @@ export default class NativeQuery {.filter(variableFilter);}- updateSnippetsWithIds(snippets): NativeQuery {- const tagsBySnippetName = _.chain(this.templateTags())- .filter((tag) => tag.type === "snippet" && tag["snippet-id"] == null)- .groupBy((tag) => tag["snippet-name"])- .value();-- if (Object.keys(tagsBySnippetName).length === 0) {- // no need to check if there are no tags- return this;- }-- let query = this;-- for (const snippet of snippets) {- for (const tag of tagsBySnippetName[snippet.name] || []) {- query = query.setTemplateTag(tag.name, {- ...tag,- "snippet-id": snippet.id,- });- }- }+ updateSnippet(+ oldSnippet: NativeQuerySnippet,+ newSnippet: NativeQuerySnippet,+ ) {+ // if the snippet name has changed, we need to update it in the query+ const newQuery =+ newSnippet.name !== oldSnippet.name+ ? this.updateSnippetNames([newSnippet])+ : this;- return query;+ // if the query has changed, it was already parsed; otherwise do the parsing+ // to expand snippet tags into the query tags+ return newQuery === this+ ? newQuery.setQueryText(newQuery.queryText())+ : newQuery;}- updateSnippetNames(snippets): NativeQuery {+ updateSnippetNames(snippets: NativeQuerySnippet[]): NativeQuery {const tagsBySnippetId = _.chain(this.templateTags())- .filter((tag) => tag.type === "snippet")- .groupBy((tag) => tag["snippet-id"])+ .filter((tag) => tag.type === "snippet" && tag["snippet-id"] != null)+ .groupBy((tag) => Number(tag["snippet-id"])).value();if (Object.keys(tagsBySnippetId).length === 0) {@@ -429,7 +428,7 @@ export default class NativeQuery {}if (queryText !== this.queryText()) {- return this.setQueryText(queryText).updateSnippetsWithIds(snippets);+ return this.setQueryText(queryText);}return this;diff --git a/frontend/src/metabase-types/api/mocks/snippets.ts b/frontend/src/metabase-types/api/mocks/snippets.tsindex 0dde70117f6..ba9246beb24 100644--- a/frontend/src/metabase-types/api/mocks/snippets.ts+++ b/frontend/src/metabase-types/api/mocks/snippets.ts@@ -12,6 +12,7 @@ export const createMockNativeQuerySnippet = ({name: "My Snippet",description: null,content: "SELECT * FROM my_table",+ template_tags: null,collection_id: null,creator,creator_id,diff --git a/frontend/src/metabase-types/api/snippets.ts b/frontend/src/metabase-types/api/snippets.tsindex 2c513649bff..1733a0a174d 100644--- a/frontend/src/metabase-types/api/snippets.ts+++ b/frontend/src/metabase-types/api/snippets.ts@@ -1,4 +1,5 @@import type { RegularCollectionId } from "./collection";+import type { TemplateTags } from "./dataset";import type { BaseEntityId } from "./entity-id";import type { UserId, UserInfo } from "./user";@@ -9,6 +10,7 @@ export interface NativeQuerySnippet {name: string;description: string | null;content: string;+ template_tags: TemplateTags | null;collection_id: RegularCollectionId | null;creator_id: UserId;creator: UserInfo;diff --git a/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.ts b/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.tsindex c747c614cb8..4b574b9de4a 100644--- a/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.ts+++ b/frontend/src/metabase/admin/permissions/selectors/data-permissions/data-permissions.unit.spec.fixtures.ts@@ -118,6 +118,7 @@ export const normalizedMetadata = {fields: {/* stripped out */},+ snippets: {},revisions: {},databasesList: [2, 3],diff --git a/frontend/src/metabase/entities/dashboards.js b/frontend/src/metabase/entities/dashboards.jsindex 7423d623cc4..8646677590b 100644--- a/frontend/src/metabase/entities/dashboards.js+++ b/frontend/src/metabase/entities/dashboards.js@@ -28,13 +28,7 @@ import {} from "metabase/lib/redux";import * as Urls from "metabase/lib/urls/dashboards";import { addUndo } from "metabase/redux/undo";-import {- DashboardSchema,- DatabaseSchema,- FieldSchema,- QuestionSchema,- TableSchema,-} from "metabase/schema";+import { QueryMetadataSchema } from "metabase/schema";const COPY_ACTION = `metabase/entities/dashboards/COPY`;const FETCH_METADATA = "metabase/entities/dashboards/FETCH_METADATA";@@ -181,13 +175,7 @@ const Dashboards = createEntity({fetchMetadata: compose(withAction(FETCH_METADATA),- withNormalize({- databases: [DatabaseSchema],- tables: [TableSchema],- fields: [FieldSchema],- cards: [QuestionSchema],- dashboards: [DashboardSchema],- }),+ withNormalize(QueryMetadataSchema),)(({ id, ...params }) =>(dispatch) =>@@ -201,13 +189,7 @@ const Dashboards = createEntity({fetchXrayMetadata: compose(withAction(FETCH_METADATA),- withNormalize({- databases: [DatabaseSchema],- tables: [TableSchema],- fields: [FieldSchema],- cards: [QuestionSchema],- dashboards: [DashboardSchema],- }),+ withNormalize(QueryMetadataSchema),)(({ entity, entityId, dashboard_load_id }) =>(dispatch) =>diff --git a/frontend/src/metabase/entities/questions.js b/frontend/src/metabase/entities/questions.jsindex af2d0ee019a..5766c0d8311 100644--- a/frontend/src/metabase/entities/questions.js+++ b/frontend/src/metabase/entities/questions.js@@ -28,7 +28,7 @@ import {API_UPDATE_QUESTION,SOFT_RELOAD_CARD,} from "metabase/query_builder/actions/core/types";-import { DatabaseSchema, FieldSchema, TableSchema } from "metabase/schema";+import { QueryMetadataSchema } from "metabase/schema";import {getMetadata,getMetadataUnfiltered,@@ -91,11 +91,7 @@ const Questions = createEntity({actions: {fetchMetadata: compose(withAction(FETCH_METADATA),- withNormalize({- databases: [DatabaseSchema],- tables: [TableSchema],- fields: [FieldSchema],- }),+ withNormalize(QueryMetadataSchema),)(({ id } = {}) =>(dispatch) =>@@ -108,11 +104,7 @@ const Questions = createEntity({),fetchAdhocMetadata: compose(withAction(FETCH_ADHOC_METADATA),- withNormalize({- databases: [DatabaseSchema],- tables: [TableSchema],- fields: [FieldSchema],- }),+ withNormalize(QueryMetadataSchema),)((query) => (dispatch) =>entityCompatibleQuery(diff --git a/frontend/src/metabase/query_builder/actions/native.ts b/frontend/src/metabase/query_builder/actions/native.tsindex c28d2f37109..3423a73b7e5 100644--- a/frontend/src/metabase/query_builder/actions/native.ts+++ b/frontend/src/metabase/query_builder/actions/native.ts@@ -137,10 +137,7 @@ export const insertSnippet =query.queryText().slice(0, selectionStart) +`{{snippet: ${name}}}` +query.queryText().slice(nativeEditorCursorOffset);- const datasetQuery = query- .setQueryText(newText)- .updateSnippetsWithIds([snippet])- .datasetQuery();+ const datasetQuery = query.setQueryText(newText).datasetQuery();dispatch(updateQuestion(question.setDatasetQuery(datasetQuery)));};diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsxindex a5c23df0011..3918c12e131 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx@@ -181,10 +181,7 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {onChange = (queryText: string) => {const { query, setDatasetQuery } = this.props;if (query.queryText() !== queryText) {- const updatedQuery = query- .setQueryText(queryText)- .updateSnippetsWithIds(this.props.snippets);-+ const updatedQuery = query.setQueryText(queryText);setDatasetQuery(updatedQuery);}};@@ -382,9 +379,12 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {snippet={this.props.modalSnippet}onCreate={this.props.insertSnippet}onUpdate={(newSnippet, oldSnippet) => {- if (newSnippet.name !== oldSnippet.name) {- setDatasetQuery(query.updateSnippetNames([newSnippet]));- }+ // get the query instance with the latest Metadata that has the updated snippet+ const newQuery = this.props.query.updateSnippet(+ oldSnippet,+ newSnippet,+ );+ setDatasetQuery(newQuery);}}onClose={this.props.closeSnippetModal}/>diff --git a/frontend/src/metabase/schema.js b/frontend/src/metabase/schema.jsindex d1aed84e996..ef8707c9351 100644--- a/frontend/src/metabase/schema.js+++ b/frontend/src/metabase/schema.js@@ -135,3 +135,12 @@ export const ObjectUnionSchema = new schema.Union(CollectionSchema.define({items: [ObjectUnionSchema],});++export const QueryMetadataSchema = {+ databases: [DatabaseSchema],+ tables: [TableSchema],+ fields: [FieldSchema],+ snippets: [SnippetSchema],+ cards: [QuestionSchema],+ dashboards: [DashboardSchema],+};diff --git a/frontend/src/metabase/selectors/metadata.ts b/frontend/src/metabase/selectors/metadata.tsindex 5d963a1b013..8a20358650a 100644--- a/frontend/src/metabase/selectors/metadata.ts+++ b/frontend/src/metabase/selectors/metadata.ts@@ -87,6 +87,7 @@ const getNormalizedFields = createSelector(const getNormalizedSegments = (state: State) => state.entities.segments;const getNormalizedQuestions = (state: State) => state.entities.questions;+const getNormalizedSnippets = (state: State) => state.entities.snippets;export const getShallowDatabases = getNormalizedDatabases;export const getShallowTables = getNormalizedTables;@@ -104,9 +105,19 @@ export const getMetadata: (getNormalizedFields,getNormalizedSegments,getNormalizedQuestions,+ getNormalizedSnippets,getSettings,],- (databases, schemas, tables, fields, segments, questions, settings) => {+ (+ databases,+ schemas,+ tables,+ fields,+ segments,+ questions,+ snippets,+ settings,+ ) => {const metadata = new Metadata({ settings });metadata.databases = Object.fromEntries(@@ -129,6 +140,9 @@ export const getMetadata: (metadata.questions = Object.fromEntries(Object.values(questions).map((c) => [c.id, createQuestion(c, metadata)]),);+ metadata.snippets = Object.fromEntries(+ Object.values(snippets).map((snippet) => [snippet.id, snippet]),+ );Object.values(metadata.databases).forEach((database) => {database.tables = hydrateDatabaseTables(database, metadata);diff --git a/frontend/test/metabase-lib/lib/queries/NativeQuery.unit.spec.js b/frontend/test/metabase-lib/lib/queries/NativeQuery.unit.spec.jsindex 79de5dcb85b..6b2e9c1adcc 100644--- a/frontend/test/metabase-lib/lib/queries/NativeQuery.unit.spec.js+++ b/frontend/test/metabase-lib/lib/queries/NativeQuery.unit.spec.js@@ -5,7 +5,11 @@ import Question from "metabase-lib/v1/Question";import NativeQuery, {updateCardTemplateTagNames,} from "metabase-lib/v1/queries/NativeQuery";-import { createMockDatabase } from "metabase-types/api/mocks";+import {+ createMockDatabase,+ createMockNativeQuerySnippet,+ createMockTemplateTag,+} from "metabase-types/api/mocks";import {PRODUCTS,SAMPLE_DB_ID,@@ -13,8 +17,9 @@ import {} from "metabase-types/api/mocks/presets";const MONGO_DB_ID = SAMPLE_DB_ID + 1;+const SNIPPET_ID = 1;-const metadata = createMockMetadata({+const METADATA = createMockMetadata({databases: [createSampleDatabase(),createMockDatabase({@@ -28,6 +33,13 @@ const metadata = createMockMetadata({],}),],+ snippets: [+ createMockNativeQuerySnippet({+ id: SNIPPET_ID,+ name: "bar",+ content: "WHERE",+ }),+ ],});function makeDatasetQuery(queryText, templateTags, databaseId) {@@ -41,14 +53,14 @@ function makeDatasetQuery(queryText, templateTags, databaseId) {};}-function makeQuery(query, templateTags) {+function makeQuery(query, templateTags, metadata = METADATA) {return new NativeQuery(Question.create({ type: "native", metadata }),makeDatasetQuery(query, templateTags, SAMPLE_DB_ID),);}-function makeMongoQuery(query, templateTags) {+function makeMongoQuery(query, templateTags, metadata = METADATA) {return new NativeQuery(Question.create({ type: "native", metadata }),makeDatasetQuery(query, templateTags, MONGO_DB_ID),@@ -262,19 +274,79 @@ describe("NativeQuery", () => {expect(type).toEqual("snippet");});+ it.each([+ { oldName: "snippet1", newName: "snippet1" },+ { oldName: "snippet1", newName: "snippet2" },+ ])("should update a snippet with inner tags", ({ oldName, newName }) => {+ const oldSnippet = createMockNativeQuerySnippet({+ name: oldName,+ content: "SELECT",+ });+ const oldMetadata = createMockMetadata({+ snippets: [oldSnippet],+ });+ const oldQuery = makeQuery("SELECT", {}, oldMetadata).setQueryText(+ `{{snippet: ${oldName}}}`,+ );++ const newSnippet = createMockNativeQuerySnippet({+ id: oldSnippet.id,+ name: newName,+ content: "{{var}}",+ template_tags: {+ var: createMockTemplateTag({+ id: "1",+ name: "var",+ type: "text",+ }),+ },+ });+ const newMetadata = createMockMetadata({+ snippets: [newSnippet],+ });+ const queryWithNewMetadata = makeQuery(+ oldQuery.queryText(),+ oldQuery.templateTagsMap(),+ newMetadata,+ );+ const queryWithNewSnippet = queryWithNewMetadata.updateSnippet(+ oldSnippet,+ newSnippet,+ );++ expect(queryWithNewSnippet.templateTags()).toMatchObject([+ { name: `snippet: ${newName}`, type: "snippet" },+ { name: "var", type: "text" },+ ]);+ });+it("should update query text with new snippet names", () => {- const q = makeQuery()- .setQueryText("{{ snippet: foo }}")- .updateSnippetsWithIds([{ id: 123, name: "foo" }])- .updateSnippetNames([{ id: 123, name: "bar" }]);+ const q = makeQuery("{{ snippet: foo }}", {+ "snippet: foo": createMockTemplateTag({+ name: " snippet: foo ",+ type: "snippet",+ "snippet-id": SNIPPET_ID,+ "snippet-name": "foo",+ }),+ }).updateSnippetNames([{ id: SNIPPET_ID, name: "bar" }]);expect(q.queryText()).toEqual("{{snippet: bar}}");});it("should update snippet names that differ on spacing", () => {- const q = makeQuery()- .setQueryText("{{ snippet: foo }} {{snippet: foo }}")- .updateSnippetsWithIds([{ id: 123, name: "foo" }])- .updateSnippetNames([{ id: 123, name: "bar" }]);+ const q = makeQuery("{{ snippet: foo }} {{snippet: foo }}", {+ " snippet: foo ": createMockTemplateTag({+ name: " snippet: foo ",+ type: "snippet",+ "snippet-id": SNIPPET_ID,+ "snippet-name": "foo",+ }),+ "snippet: foo ": createMockTemplateTag({+ name: "snippet: foo ",+ type: "snippet",+ "snippet-id": SNIPPET_ID,+ "snippet-name": "foo",+ }),+ }).updateSnippetNames([{ id: SNIPPET_ID, name: "bar" }]);expect(q.queryText()).toEqual("{{snippet: bar}} {{snippet: bar}}");});});diff --git a/resources/migrations/057_update_migrations.yaml b/resources/migrations/057_update_migrations.yamlindex ce38f9a648e..6514e793a84 100644--- a/resources/migrations/057_update_migrations.yaml+++ b/resources/migrations/057_update_migrations.yaml@@ -1043,6 +1043,20 @@ databaseChangeLog:job_id IN (SELECT id FROM transform_job WHERE built_in_type IS NOT NULL) ANDtag_id IN (SELECT id FROM transform_tag WHERE built_in_type IS NOT NULL);+ - changeSet:+ id: v57.2025-08-22T00:15:01+ author: william+ comment: Add template tag data to snippets+ changes:+ - addColumn:+ tableName: native_query_snippet+ columns:+ - column:+ name: template_tags+ remarks: Template tags for the snippet+ type: ${text.type}+ constraints:+ nullable: true- changeSet:id: v57.2025-08-23T10:00:00author: chodorowiczdiff --git a/resources/serialization-order.edn b/resources/serialization-order.ednindex b61fb8058f4..5464f66328c 100644--- a/resources/serialization-order.edn+++ b/resources/serialization-order.edn@@ -141,6 +141,8 @@:description:entity_id:created_at]+ [:NativeQuerySnippet+ :template_tags] []:Table [:name:display_name:descriptiondiff --git a/src/metabase/driver/sql/parameters/substitute.clj b/src/metabase/driver/sql/parameters/substitute.cljindex d4e59e47699..12843aca42f 100644--- a/src/metabase/driver/sql/parameters/substitute.clj+++ b/src/metabase/driver/sql/parameters/substitute.clj@@ -4,11 +4,14 @@[metabase.driver :as driver][metabase.driver-api.core :as driver-api][metabase.driver.common.parameters :as params]+ [metabase.driver.common.parameters.parse :as params.parse][metabase.driver.sql.parameters.substitution :as sql.params.substitution][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.log :as log]))+(declare #^:private substitute*)+(defn- substitute-field-param [[sql args missing] in-optional? k {:keys [_field value], :as v}](if (and (= params/no-value value) in-optional?);; no-value field filters inside optional clauses are ignored, and eventually emitted entirely@@ -23,9 +26,12 @@(sql.params.substitution/->replacement-snippet-info driver/*driver* v)][(str sql replacement-snippet) (concat args prepared-statement-args) missing]))-(defn- substitute-native-query-snippet [[sql args missing] v]- (let [{:keys [replacement-snippet]} (sql.params.substitution/->replacement-snippet-info driver/*driver* v)]- [(str sql replacement-snippet) args missing]))+(defn- substitute-native-query-snippet [param->value [sql args missing] in-optional? v]+ (let [{:keys [replacement-snippet]} (sql.params.substitution/->replacement-snippet-info driver/*driver* v)+ [processed-snippet snippet-args snippet-missing] (substitute* param->value (params.parse/parse replacement-snippet) in-optional?)]+ [(str sql processed-snippet)+ (not-empty (concat args snippet-args))+ (not-empty (concat missing snippet-missing))]))(defn- substitute-param [param->value [sql args missing] in-optional? {:keys [k]}](if-not (contains? param->value k)@@ -40,7 +46,7 @@(substitute-card-query [sql args missing] v)(params/ReferencedQuerySnippet? v)- (substitute-native-query-snippet [sql args missing] v)+ (substitute-native-query-snippet param->value [sql args missing] in-optional? v)(= params/no-value v)[sql args (conj missing k)]diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljcindex 12840df2306..0cfe1e44097 100644--- a/src/metabase/lib/core.cljc+++ b/src/metabase/lib/core.cljc@@ -44,6 +44,7 @@[metabase.lib.stage :as lib.stage][metabase.lib.swap :as lib.swap][metabase.lib.table :as lib.table]+ [metabase.lib.template-tags :as lib.template-tags][metabase.lib.temporal-bucket :as lib.temporal-bucket][metabase.lib.util :as lib.util][metabase.util.namespaces :as shared.ns]))@@ -87,6 +88,7 @@lib.stage/keep-melib.swap/keep-melib.table/keep-me+ lib.template-tags/keep-melib.temporal-bucket/keep-melib.util/keep-me)@@ -327,8 +329,10 @@native-extrasnative-queryraw-native-query+ recognize-template-tagsrequired-native-extras- template-tag-card-ids+ native-query-card-ids+ native-query-snippet-idstemplate-tags-referenced-cardstemplate-tagswith-different-database@@ -357,7 +361,7 @@can-previewcan-runcan-save- check-overwrite+ check-card-overwritepreview-queryqueryquery-from-legacy-inner-query@@ -386,6 +390,9 @@has-clauses?][lib.swapswap-clauses]+ [lib.template-tags+ template-tags->card-ids+ template-tags->snippet-ids][lib.temporal-bucketdescribe-temporal-unitdescribe-temporal-intervaldiff --git a/src/metabase/lib/fe_util.cljc b/src/metabase/lib/fe_util.cljcindex 2c361d920a5..1b8fb881222 100644--- a/src/metabase/lib/fe_util.cljc+++ b/src/metabase/lib/fe_util.cljc@@ -13,6 +13,7 @@[metabase.lib.hierarchy :as lib.hierarchy][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation]+ [metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.lib.normalize :as lib.normalize][metabase.lib.options :as lib.options][metabase.lib.query :as lib.query]@@ -799,6 +800,26 @@_(lib.metadata.calculation/display-name query stage-number filter-clause))))+(defn- query-dependents-snippets+ "Recursively extract snippet dependencies from snippet template tags.+ Returns a sequence of dependent items including the snippet and any nested snippets."+ [metadata-providerable snippet-id visited-ids]+ (if-let [snippet (lib.metadata/native-query-snippet metadata-providerable snippet-id)]+ (let [visited-ids' (conj visited-ids snippet-id)]+ (cons {:type :native-query-snippet, :id snippet-id}+ ;; Recursively get dependencies from the snippet's own template tags+ (for [{nested-type :type,+ nested-snippet-id :snippet-id} (vals (:template-tags snippet))+ :when (and (= nested-type :snippet)+ (integer? nested-snippet-id)+ (not (contains? visited-ids' nested-snippet-id)))+ dependency (query-dependents-snippets metadata-providerable+ nested-snippet-id+ visited-ids')]+ dependency)))+ ;; Return just the ID if we can't fetch the snippet:+ [{:type :native-query-snippet, :id snippet-id}]))+(defn- query-dependents-foreign-keys[metadata-providerable columns](for [column columns@@ -810,20 +831,34 @@(defn- query-dependents[metadata-providerable query-or-join]- (let [base-stage (first (:stages query-or-join))+ (let [base-stage (first (:stages query-or-join))database-id (or (:database query-or-join) -1)](concat(when (pos? database-id)[{:type :database, :id database-id}- {:type :schema, :id database-id}])+ {:type :schema, :id database-id}])(when (= (:lib/type base-stage) :mbql.stage/native)- (for [{tag-type :type, [dim-tag _opts id] :dimension} (vals (:template-tags base-stage))- :when (and (= tag-type :dimension)- (= dim-tag :field)- (integer? id))]- {:type :field, :id id}))+ (concat+ ;; Extract field dependencies from dimension template tags+ (for [{tag-type :type, [dim-tag _opts id] :dimension} (vals (:template-tags base-stage))+ :when (and (= tag-type :dimension)+ (= dim-tag :field)+ (integer? id))]+ {:type :field, :id id})+ ;; Extract snippet dependencies from snippet template tags (with recursion)+ (mapcat+ (fn [{tag-type :type, snippet-id :snippet-id}]+ (when (and (= tag-type :snippet)+ (some? snippet-id)+ (integer? snippet-id))+ ;; Only try to recurse if we have a real metadata provider+ (if (lib.metadata.protocols/metadata-providerable? metadata-providerable)+ (query-dependents-snippets metadata-providerable snippet-id #{})+ ;; If we don't have a real metadata provider, just return the direct dependency+ [{:type :native-query-snippet, :id snippet-id}])))+ (vals (:template-tags base-stage)))))(when-let [card-id (:source-card base-stage)]- (let [card (lib.metadata/card metadata-providerable card-id)+ (let [card (lib.metadata/card metadata-providerable card-id)definition (:dataset-query card)](concat [{:type :table, :id (str "card__" card-id)}](when-let [card-columns (lib.card/saved-question-metadata metadata-providerable card-id)]@@ -835,20 +870,21 @@(cons {:type :table, :id table-id}(query-dependents-foreign-keys metadata-providerable(lib.metadata/fields metadata-providerable table-id))))- (for [stage (:stages query-or-join)- join (:joins stage)+ (for [stage (:stages query-or-join)+ join (:joins stage)dependent (query-dependents metadata-providerable join)]dependent))))(def ^:private DependentItem[:and[:map- [:type [:enum :database :schema :table :card :field]]]+ [:type [:enum :database :schema :table :card :field :native-query-snippet]]][:multi {:dispatch :type}[:database [:map [:id ::lib.schema.id/database]]][:schema [:map [:id ::lib.schema.id/database]]][:table [:map [:id [:or ::lib.schema.id/table :string]]]]- [:field [:map [:id ::lib.schema.id/field]]]]])+ [:field [:map [:id ::lib.schema.id/field]]]+ [:native-query-snippet [:map [:id ::lib.schema.id/native-query-snippet]]]]])(mu/defn dependent-metadata :- [:sequential DependentItem]"Return the IDs and types of entities the metadata about is requireddiff --git a/src/metabase/lib/js/metadata.cljs b/src/metabase/lib/js/metadata.cljsindex 62488ee2633..aaa134f7513 100644--- a/src/metabase/lib/js/metadata.cljs+++ b/src/metabase/lib/js/metadata.cljs@@ -8,6 +8,7 @@[medley.core :as m][metabase.lib.cache :as lib.cache][metabase.lib.metadata.protocols :as lib.metadata.protocols]+ [metabase.lib.normalize :as lib.normalize][metabase.lib.util :as lib.util][metabase.util :as u][metabase.util.log :as log]))@@ -452,6 +453,21 @@[_object-type]"segments")+(defmethod lib-type :snippet+ [_object-type]+ :metadata/native-query-snippet)++(defmethod parse-objects-default-key :snippet+ [_object-type]+ "snippets")++(defmethod parse-field-fn :snippet+ [_object-type]+ (fn [k v]+ (case k+ :template-tags (lib.normalize/normalize :metabase.lib.schema.template-tag/template-tag-map (js->clj v))+ v)))+(defn- parse-objects-delay [object-type metadata](delay(try@@ -476,30 +492,62 @@[id (-> card card->metric-card delay)]))))cards)))+(defn- metadata-property [metadata-type]+ (case metadata-type+ :metadata/table :tables+ :metadata/column :fields+ :metadata/card :cards+ :metadata/segment :segments+ :metadata/native-query-snippet :snippets))++(defn- by-name-field [field]+ (keyword (str (name field) "-by-name")))++(defn- by-name-delay [objects-delay]+ (delay+ (let [objects @objects-delay]+ (into {}+ (map (fn [[_id object-delay]]+ (let [object @object-delay]+ [(:name object) object])))+ objects))))++(defn- add-by-names [metadata-map]+ (into metadata-map+ (map (fn [[field objects-delay]]+ [(by-name-field field)+ (by-name-delay objects-delay)]))+ metadata-map))+(defn- parse-metadata [metadata](let [delayed-cards (parse-objects-delay :card metadata)]- {:databases (parse-objects-delay :database metadata)- :tables (parse-objects-delay :table metadata)- :fields (parse-objects-delay :field metadata)- :cards delayed-cards- :metrics (delay (metric-cards delayed-cards))- :segments (parse-objects-delay :segment metadata)}))+ (add-by-names+ {:databases (parse-objects-delay :database metadata)+ :tables (parse-objects-delay :table metadata)+ :fields (parse-objects-delay :field metadata)+ :snippets (parse-objects-delay :snippet metadata)+ :cards delayed-cards+ :metrics (delay (metric-cards delayed-cards))+ :segments (parse-objects-delay :segment metadata)})))(defn- database [metadata database-id](some-> metadata :databases deref (get database-id) deref))(defn- metadatas [metadata metadata-type ids]- (let [k (case metadata-type- :metadata/table :tables- :metadata/column :fields- :metadata/card :cards- :metadata/segment :segments)+ (let [k (metadata-property metadata-type)metadatas* (some-> metadata k deref)](into [](keep (fn [id](some-> metadatas* (get id) deref)))ids)))+(defn- metadatas-by-name [metadata metadata-type names]+ (let [k (-> metadata-type metadata-property by-name-field)+ metadatas* (some-> metadata k deref)]+ (into [] (comp (distinct)+ (keep #(get metadatas* %)))+ names)))+(defn- tables [metadata database-id](into [](keep (fn [[_id dlay]]@@ -549,6 +597,8 @@(database metadata database-id))(metadatas [_this metadata-type ids](metadatas metadata metadata-type ids))+ (metadatas-by-name [_this metadata-type names]+ (metadatas-by-name metadata metadata-type names))(tables [_this](tables metadata database-id))(metadatas-for-table [_this metadata-type table-id]diff --git a/src/metabase/lib/metadata.cljc b/src/metabase/lib/metadata.cljcindex 6f6e3a4abd2..6f24e1dccb5 100644--- a/src/metabase/lib/metadata.cljc+++ b/src/metabase/lib/metadata.cljc@@ -101,6 +101,12 @@snippet-id :- ::lib.schema.id/native-query-snippet](lib.metadata.protocols/native-query-snippet (->metadata-provider metadata-providerable) snippet-id))+(mu/defn native-query-snippet-by-name :- [:maybe ::lib.schema.metadata/native-query-snippet]+ "Get metadata for a NativeQuerySnippet with `snippet-name` if it can be found."+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ snippet-name :- :string]+ (lib.metadata.protocols/native-query-snippet-by-name (->metadata-provider metadata-providerable) snippet-name))+(mu/defn segment :- [:maybe ::lib.schema.metadata/segment]"Get metadata for the Segment with `segment-id`, if it can be found."[metadata-providerable :- ::lib.schema.metadata/metadata-providerablediff --git a/src/metabase/lib/metadata/cached_provider.cljc b/src/metabase/lib/metadata/cached_provider.cljcindex 8d6bac2256f..63a77457364 100644--- a/src/metabase/lib/metadata/cached_provider.cljc+++ b/src/metabase/lib/metadata/cached_provider.cljc@@ -56,31 +56,31 @@(defn- database [cache metadata-provider](get-in-cache-or-fetch cache [:metadata/database] #(lib.metadata.protocols/database metadata-provider)))-(defn- metadatas [cache uncached-provider metadata-type ids]- (when (seq ids)- (log/tracef "Getting %s metadata with IDs %s" metadata-type (pr-str (sort ids)))+(defn- metadatas [inner-fn k cache uncached-provider metadata-type values]+ (when (seq values)+ (log/tracef "Getting %s metadata with Values %s" metadata-type (pr-str (sort values)))(let [metadata-cache (get @cache metadata-type)]- (when-not (every? #(contains? metadata-cache %) ids)- (let [existing-ids (set (keys metadata-cache))- missing-ids (set/difference (set ids) existing-ids)]- (log/tracef "Already fetched %s: %s" metadata-type (pr-str (sort (set/intersection (set ids) existing-ids))))- (when (seq missing-ids)- (log/tracef "Need to fetch %s: %s" metadata-type (pr-str (sort missing-ids)))- (let [fetched-metadatas (lib.metadata.protocols/metadatas uncached-provider metadata-type missing-ids)- fetched-ids (map :id fetched-metadatas)- unfetched-ids (set/difference (set missing-ids) (set fetched-ids))]- (when (seq fetched-ids)- (log/tracef "Fetched %s: %s" metadata-type (pr-str (sort fetched-ids)))+ (when-not (every? #(contains? metadata-cache %) values)+ (let [existing-values (set (keys metadata-cache))+ missing-values (set/difference (set values) existing-values)]+ (log/tracef "Already fetched %s: %s" metadata-type (pr-str (sort (set/intersection (set values) existing-values))))+ (when (seq missing-values)+ (log/tracef "Need to fetch %s: %s" metadata-type (pr-str (sort missing-values)))+ (let [fetched-metadatas (inner-fn uncached-provider metadata-type missing-values)+ fetched-values (map k fetched-metadatas)+ unfetched-values (set/difference (set missing-values) (set fetched-values))]+ (when (seq fetched-values)+ (log/tracef "Fetched %s: %s" metadata-type (pr-str (sort fetched-values)))(doseq [instance fetched-metadatas]- (store-in-cache! cache [metadata-type (:id instance)] instance)))- (when (seq unfetched-ids)- (log/tracef "Failed to fetch %s: %s" metadata-type (pr-str (sort unfetched-ids)))- (doseq [unfetched-id unfetched-ids]+ (store-in-cache! cache [metadata-type (k instance)] instance)))+ (when (seq unfetched-values)+ (log/tracef "Failed to fetch %s: %s" metadata-type (pr-str (sort unfetched-values)))+ (doseq [unfetched-id unfetched-values](store-in-cache! cache [metadata-type unfetched-id] ::nil))))))))(into []- (keep (fn [id]- (get-in-cache cache [metadata-type id])))- ids)))+ (keep (fn [value]+ (get-in-cache cache [metadata-type value])))+ values)))(defn- cached-metadatas [cache metadata-type metadata-ids](into []@@ -125,7 +125,9 @@(database [_this](database cache metadata-provider))(metadatas [_this metadata-type ids]- (metadatas cache metadata-provider metadata-type ids))+ (metadatas lib.metadata.protocols/metadatas :id cache metadata-provider metadata-type ids))+ (metadatas-by-name [_this metadata-type names]+ (metadatas lib.metadata.protocols/metadatas-by-name :name cache metadata-provider metadata-type names))(tables [_this](get-in-cache-or-fetch cache [::database-tables] #(tables metadata-provider cache)))(metadatas-for-table [_this metadata-type table-id]diff --git a/src/metabase/lib/metadata/composed_provider.cljc b/src/metabase/lib/metadata/composed_provider.cljcindex 651881b2353..6a3c92fbcf5 100644--- a/src/metabase/lib/metadata/composed_provider.cljc+++ b/src/metabase/lib/metadata/composed_provider.cljc@@ -43,6 +43,9 @@metadata-typeids))+(defn- metadatas-by-name [providers metadata-type names]+ (metadatas-for-f metadata.protocols/metadatas-by-name providers metadata-type names))+(defn- cached-value [metadata-providers k not-found](loop [[cached-provider & more] (cached-providers metadata-providers)](b/cond@@ -99,6 +102,8 @@(some metadata.protocols/database metadata-providers))(metadatas [_this metadata-type ids](metadatas metadata-providers metadata-type ids))+ (metadatas-by-name [_this metadata-type names]+ (metadatas-by-name metadata-providers metadata-type names))(tables [_this](tables metadata-providers))(metadatas-for-table [_this metadata-type table-id]diff --git a/src/metabase/lib/metadata/invocation_tracker.cljc b/src/metabase/lib/metadata/invocation_tracker.cljcindex b7a6a0fa714..c963bc09af4 100644--- a/src/metabase/lib/metadata/invocation_tracker.cljc+++ b/src/metabase/lib/metadata/invocation_tracker.cljc@@ -49,6 +49,8 @@(lib.metadata.protocols/database metadata-provider))(metadatas [_this metadata-type ids](metadatas tracker metadata-provider metadata-type ids))+ (metadatas-by-name [_this metadata-type names]+ (lib.metadata.protocols/metadatas-by-name metadata-provider metadata-type names))(tables [_this](lib.metadata.protocols/tables metadata-provider))(metadatas-for-table [_this metadata-type table-id]diff --git a/src/metabase/lib/metadata/protocols.cljc b/src/metabase/lib/metadata/protocols.cljcindex b2a98542cd8..8fe1a0106b8 100644--- a/src/metabase/lib/metadata/protocols.cljc+++ b/src/metabase/lib/metadata/protocols.cljc@@ -41,6 +41,14 @@not matter. For MetadataProviders that have a cache, calling this method can be done for side-effects (to warm thecache).")+ (metadatas-by-name [metadata-provider metadata-type names]+ "Return a sequence of non-nil metadata objects of `metadata-type` associated with `names`, which is either+ a sequence or a set of string names. Objects should be fetched as needed, but if this MetadataProvider has an+ internal cache (i.e., if it is a [[CachedMetadataProvider]]), it should return any cached objects and only fetch+ ones not present in the cache. This should not error if any objects were not found. The order objects are returned+ in does not matter. For MetadataProviders that have a cache, calling this method can be done for side-effects (to+ warm the cache).")+(tables [metadata-provider]"Return a sequence of Tables in this Database. Tables should satisfy the `:metabase.lib.schema.metadata/table`schema. This should also include things that serve as 'virtual' tables, e.g. Saved Questions or Models. But users of@@ -102,6 +110,14 @@(= (:id object) metadata-id))(metadatas metadata-provider metadata-type [metadata-id])))+(mu/defn- metadata-by-name :- [:maybe ::metadata]+ [metadata-provider :- ::metadata-provider+ metadata-type :- ::metadata-type-excluding-database+ metadata-name :- :string]+ (m/find-first (fn [object]+ (= (:name object) metadata-name))+ (metadatas-by-name metadata-provider metadata-type [metadata-name])))+(mu/defn table :- [:maybe ::lib.schema.metadata/table]"Return metadata for a specific Table. Metadata should satisfy `:metabase.lib.schema.metadata/table`."[metadata-provider :- ::metadata-provider@@ -128,6 +144,12 @@snippet-id :- ::lib.schema.id/native-query-snippet](metadata metadata-provider :metadata/native-query-snippet snippet-id))+(mu/defn native-query-snippet-by-name :- [:maybe ::lib.schema.metadata/native-query-snippet]+ "Get metadata for a NativeQuerySnippet with `snippet-name` if it can be found."+ [metadata-provider :- ::metadata-provider+ snippet-name :- :string]+ (metadata-by-name metadata-provider :metadata/native-query-snippet snippet-name))+(mu/defn segment :- [:maybe ::lib.schema.metadata/segment]"Return metadata for a particular captial-S Segment, i.e. something from the `segment` table in the applicationdatabase. Metadata should match `:metabase.lib.schema.metadata/segment`."diff --git a/src/metabase/lib/native.cljc b/src/metabase/lib/native.cljcindex 7364c78f853..2772dd30d5a 100644--- a/src/metabase/lib/native.cljc+++ b/src/metabase/lib/native.cljc@@ -13,6 +13,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.schema.template-tag :as lib.schema.template-tag]+ [metabase.lib.template-tags :as lib.template-tags][metabase.lib.util :as lib.util][metabase.util.humanization :as u.humanization][metabase.util.i18n :as i18n]@@ -31,27 +32,6 @@(def ^:private tag-regexes[variable-tag-regex snippet-tag-regex card-tag-regex])-(defn- fresh-tag [tag-name]- {:type :text- :name tag-name- :id (str (random-uuid))})--(defn- recognize-template-tags [query-text]- (let [parsed (lib.parse/parse {} query-text)]- (loop [found {}- [current & more] (vec parsed)]- (match [current]- [nil] found- [_ :guard string?] (recur found more)- [{:type ::lib.parse/param- :name tag-name}] (let [full-tag (str "{{" tag-name "}}")- [_ matched-name] (some #(re-matches % full-tag) tag-regexes)]- (recur (cond-> found- (and matched-name (not (found matched-name))) (assoc matched-name (fresh-tag matched-name)))- more))- [{:type ::lib.parse/optional- :contents contents}] (recur found (apply conj more contents))))))-(defn- tag-name->card-id [tag-name](when-let [[_ id-str] (re-matches #"^#(\d+)(-[a-z0-9-]*)?$" tag-name)](parse-long id-str)))@@ -71,6 +51,33 @@(when-not (:display-name tag){:display-name (u.humanization/name->human-readable-name :simple tag-name)})))+(defn- fresh-tag [tag-name]+ (finish-tag+ {:type :text+ :name tag-name+ :id (str (random-uuid))}))++(defn recognize-template-tags+ "Finds and returns all template tags in query-text."+ [query-text]+ (let [parsed (lib.parse/parse {} query-text)]+ (loop [found {}+ [current & more] parsed]+ (match [current]+ [nil] found+ [_ :guard string?] (recur found more)++ [{:type ::lib.parse/param, :name tag-name}]+ (let [full-tag (str "{{" tag-name "}}")+ [_ matched-name] (some #(re-matches % full-tag) tag-regexes)]+ (recur (cond-> found+ (and matched-name (not (found matched-name))) (assoc matched-name (fresh-tag matched-name)))+ more))++ [{:type ::lib.parse/optional+ :contents contents}]+ (recur found (into more contents))))))+(defn- rename-template-tag[existing-tags old-name new-name](let [old-tag (get existing-tags old-name)@@ -99,6 +106,32 @@(m/filter-keys new-tags query-tags)))](update-vals tags finish-tag)))+(defn- snippet-names [template-tags]+ (keep #(when (= (:type %) :snippet)+ (:snippet-name %))+ (vals template-tags)))++(defn- extract-snippet-tags [metadata-providerable template-tags]+ (loop [[snippet-name & more-snippet-names] (snippet-names template-tags)+ seen #{}+ tags {}]+ (cond+ (nil? snippet-name) tags+ (seen snippet-name) (recur more-snippet-names seen tags)+ :else (let [snippet-tags (->> (lib.metadata/native-query-snippet-by-name metadata-providerable snippet-name)+ :template-tags)]+ (recur (into more-snippet-names (snippet-names snippet-tags))+ (conj seen snippet-name)+ (merge tags snippet-tags))))))++(defn- add-snippet-ids [metadata-providerable template-tags]+ (update-vals template-tags+ (fn [{tag-type :type, :keys [snippet-name], :as tag}]+ (cond-> tag+ ;; A snippet can be referenced by a previous name. If it cannot be found, preserve the previous `snippet-id`.+ (= tag-type :snippet) (m/assoc-some :snippet-id+ (:id (lib.metadata/native-query-snippet-by-name metadata-providerable snippet-name)))))))+(mu/defn extract-template-tags :- ::lib.schema.template-tag/template-tag-map"Extract the template tags from a native query's text.@@ -111,17 +144,23 @@For snippets they start with `snippet:`, eg. `{{ snippet: arbitrary text here }}`.And for card references either `{{ #123 }}` or with the optional human label `{{ #123-card-title-slug }}`.- Invalid patterns are simply ignored, so something like `{{&foo!}}` is just disregarded."- ([query-text :- ::common/non-blank-string]- (extract-template-tags query-text nil))- ([query-text :- ::common/non-blank-string- existing-tags :- [:maybe ::lib.schema.template-tag/template-tag-map]]- (let [query-tags (recognize-template-tags query-text)+ Invalid patterns are simply ignored, so something like `{{&foo!}}` is just disregarded.++ This finds in tags from snippets and assigns snippet-ids."+ ([metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ query-text :- ::common/non-blank-string]+ (extract-template-tags metadata-providerable query-text nil))+ ([metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ query-text :- ::common/non-blank-string+ existing-tags :- [:maybe ::lib.schema.template-tag/template-tag-map]]+ (let [direct-tags (recognize-template-tags query-text)+ query-tags (merge direct-tags (extract-snippet-tags metadata-providerable direct-tags))query-tag-names (not-empty (set (keys query-tags)))existing-tag-names (not-empty (set (keys existing-tags)))](if (or query-tag-names existing-tag-names);; If there's at least some tags, unify them.- (unify-template-tags query-tags query-tag-names existing-tags existing-tag-names)+ (->> (unify-template-tags query-tags query-tag-names existing-tags existing-tag-names)+ (add-snippet-ids metadata-providerable));; Otherwise just an empty map, no tags.{}))))@@ -174,7 +213,7 @@sql-or-other-native-query :- ::common/non-blank-stringresults-metadata :- [:maybe ::lib.schema.metadata/stage]native-extras :- [:maybe ::native-extras]]- (let [tags (extract-template-tags sql-or-other-native-query)]+ (let [tags (extract-template-tags metadata-providerable sql-or-other-native-query)](cond-> (lib.query/query-with-stages metadata-providerable[{:lib/type :mbql.stage/native:lib/stage-metadata results-metadata@@ -209,7 +248,7 @@(assert-native-query stage)(assoc stage:native inner-query- :template-tags (extract-template-tags inner-query existing-tags)))))+ :template-tags (extract-template-tags query inner-query existing-tags)))));;; TODO (Cam 7/16/25) -- this really doesn't seem to do what I'd expect, maybe we should rename it something like;;; `with-replaced-template-tags`@@ -235,10 +274,10 @@[query :- ::lib.schema/query](:template-tags (lib.util/query-stage query 0)))-(mu/defn template-tag-card-ids :- [:maybe [:set {:min 1} ::lib.schema.id/card]]+(mu/defn native-query-card-ids :- [:maybe [:set {:min 1} ::lib.schema.id/card]]"Returns the card IDs from the template tags of the native query of `query`."[query :- ::lib.schema/query]- (not-empty (into #{} (keep (fn [[_k m]] (:card-id m))) (template-tags query))))+ (lib.template-tags/template-tags->card-ids (template-tags query)))(mu/defn template-tags-referenced-cards :- [:maybe [:sequential ::lib.schema.metadata/card]]"Returns Card instances referenced by the given native `query`."@@ -246,7 +285,12 @@(mapv(fn [card-id](lib.metadata/card query card-id))- (template-tag-card-ids query)))+ (native-query-card-ids query)))++(mu/defn native-query-snippet-ids :- [:maybe [:set {:min 1} ::lib.schema.id/native-query-snippet]]+ "Returns the card IDs from the template tags of the native query of `query`."+ [query :- ::lib.schema/query]+ (lib.template-tags/template-tags->snippet-ids (template-tags query)))(mu/defn has-template-tag-variables? :- :boolean"Tests whether `query` has any template-tag variables.diff --git a/src/metabase/lib/query.cljc b/src/metabase/lib/query.cljcindex 147bc0f9c4a..5287b2a003a 100644--- a/src/metabase/lib/query.cljc+++ b/src/metabase/lib/query.cljc@@ -451,10 +451,13 @@[a-query](dissoc a-query :lib/metadata))-(defn- get-native-stages [native-stage]- (for [{:keys [card-id] tag-type :type} (-> native-stage :template-tags vals)- :when (= tag-type :card)]- {:source-card card-id}))+(defn- template-tag-stages+ [template-tags]+ (for [{:keys [card-id snippet-id] tag-type :type} (vals template-tags)+ :when (#{:card :snippet} tag-type)]+ (case tag-type+ :card {:source-card card-id}+ :snippet {:source-snippet-id snippet-id})))(defn- stage-seq* [query-fragment](cond@@ -467,38 +470,53 @@(map? query-fragment)(if (= (:lib/type query-fragment) :mbql.stage/native)- (get-native-stages query-fragment)+ (-> query-fragment :template-tags template-tag-stages)(concat (:stages query-fragment) (mapcat stage-seq* (vals query-fragment)))):else[]))-(defn- stage-seq [card-id a-query]- (map #(assoc % ::from-card card-id) (stage-seq* a-query)))+(defn- stage-seq [from-entity a-query]+ ;; from-entity is [entity-type entity-id] like [:card 123] or [:snippet 456]+ (map #(assoc % ::from-entity from-entity) (stage-seq* a-query)))++(defn- snippet-seq [from-entity snippet]+ (map #(assoc % ::from-entity from-entity) (template-tag-stages (:template-tags snippet))))(defn- expand-stage [metadata-provider stage]- (let [card-id (:source-card stage)- expanded-query (some->> card-id- (lib.metadata/card metadata-provider)- :dataset-query- (query metadata-provider))]- (stage-seq card-id expanded-query)))+ (let [{card-id :source-card+ snippet-id :source-snippet-id} stage]+ (cond+ card-id+ (let [expanded-query (some->> card-id+ (lib.metadata/card metadata-provider)+ :dataset-query+ (query metadata-provider))]+ (stage-seq [:card card-id] expanded-query))++ snippet-id+ (when-let [snippet (lib.metadata/native-query-snippet metadata-provider snippet-id)]+ (snippet-seq [:snippet snippet-id] snippet))++ :else [])))(defn- add-stage-dep [graph stage]- (let [card-id (:source-card stage)- table-id (:source-table stage)- from-id (::from-card stage)]+ (let [{card-id :source-card+ snippet-id :source-snippet-id+ table-id :source-table+ from-entity ::from-entity} stage](try(cond-> graph- card-id (dep/depend [:card from-id] [:card card-id])- table-id (dep/depend [:card from-id] [:table table-id]))+ card-id (dep/depend from-entity [:card card-id])+ snippet-id (dep/depend from-entity [:snippet snippet-id])+ table-id (dep/depend from-entity [:table table-id]))(catch #?(:clj Exception :cljs :default) e(throw (ex-info (i18n/tru "Cannot save card with cycles.") {} e))))))-(defn- build-graph [source-id metadata-provider a-query]+(defn- build-card-snippet-graph [source-entity metadata-provider a-query](loop [graph (dep/graph)stages-visited 0- stages (stage-seq source-id a-query)]+ stages (stage-seq source-entity a-query)](cond(empty? stages)graph@@ -512,12 +530,12 @@(inc stages-visited)(concat stages (expand-stage metadata-provider stage)))))))-(defn check-overwrite+(defn check-card-overwrite"Returns nil if the card with given `card-id` can be overwritten with `query`.Throws `ExceptionInfo` with a user-facing message otherwise.Currently checks for cycles (self-referencing queries)."[card-id new-query]- (build-graph card-id new-query new-query)+ (build-card-snippet-graph [:card card-id] new-query new-query);; return nil if nothing throwsnil)diff --git a/src/metabase/lib/template_tags.cljc b/src/metabase/lib/template_tags.cljcnew file mode 100644index 00000000000..6ddc7f838db--- /dev/null+++ b/src/metabase/lib/template_tags.cljc@@ -0,0 +1,19 @@+(ns metabase.lib.template-tags+ (:require+ [metabase.lib.schema.id :as lib.schema.id]+ [metabase.lib.schema.template-tag :as lib.schema.template-tag]+ [metabase.util.malli :as mu]))++(mu/defn template-tags->card-ids :- [:maybe [:set {:min 1} ::lib.schema.id/card]]+ "Returns the card IDs from the template tags map."+ [template-tags :- [:maybe ::lib.schema.template-tag/template-tag-map]]+ (->> (vals template-tags)+ (into #{} (keep :card-id))+ not-empty))++(mu/defn template-tags->snippet-ids :- [:maybe [:set {:min 1} ::lib.schema.id/native-query-snippet]]+ "Returns the snippet IDs from the template tags map."+ [template-tags :- [:maybe ::lib.schema.template-tag/template-tag-map]]+ (->> (vals template-tags)+ (into #{} (keep :snippet-id))+ not-empty))diff --git a/src/metabase/lib_be/metadata/jvm.clj b/src/metabase/lib_be/metadata/jvm.cljindex 681a806dd76..a16529a950a 100644--- a/src/metabase/lib_be/metadata/jvm.clj+++ b/src/metabase/lib_be/metadata/jvm.clj@@ -340,7 +340,7 @@#_resolved-query clojure.lang.IPersistentMap][query-type model parsed-args honeysql](merge (next-method query-type model parsed-args honeysql)- {:select [:id :name :description :content :archived :collection_id]}))+ {:select [:id :name :description :content :archived :collection_id :template_tags]}))(t2/define-after-select :metadata/native-query-snippet[snippet]@@ -358,12 +358,15 @@{})))(t2/select-one :metadata/database database-id))+(defn- db-id-key [metadata-type]+ (case metadata-type+ :metadata/table :db_id+ :metadata/card :card/database_id+ :metadata/native-query-snippet nil+ :table/db_id))+(defn- metadatas [database-id metadata-type ids]- (let [database-id-key (case metadata-type- :metadata/table :db_id- :metadata/card :card/database_id- :metadata/native-query-snippet nil- :table/db_id)]+ (let [database-id-key (db-id-key metadata-type)](when (seq ids)(t2/select metadata-type:id [:in (set ids)]@@ -371,6 +374,15 @@{:where [:= database-id-key database-id]}{})))))+(defn- metadatas-by-name [database-id metadata-type names]+ (let [database-id-key (db-id-key metadata-type)]+ (when (seq names)+ (t2/select metadata-type+ :name [:in (set names)]+ (if database-id-key+ {:where [:= database-id-key database-id]}+ {})))))+(defn- tables [database-id](t2/select :metadata/table{:where [:and@@ -405,6 +417,8 @@(database database-id))(metadatas [_this metadata-type ids](metadatas database-id metadata-type ids))+ (metadatas-by-name [_this metadata-type names]+ (metadatas-by-name database-id metadata-type names))(tables [_this](tables database-id))(metadatas-for-table [_this metadata-type table-id]diff --git a/src/metabase/native_query_snippets/models/native_query_snippet.clj b/src/metabase/native_query_snippets/models/native_query_snippet.cljindex 5441ad8f0da..69c5c136cf6 100644--- a/src/metabase/native_query_snippets/models/native_query_snippet.clj+++ b/src/metabase/native_query_snippets/models/native_query_snippet.clj@@ -1,6 +1,8 @@(ns metabase.native-query-snippets.models.native-query-snippet(:require[metabase.collections.models.collection :as collection]+ [metabase.lib.core :as lib]+ [metabase.lib.normalize :as lib.normalize][metabase.models.interface :as mi][metabase.models.serialization :as serdes][metabase.native-query-snippets.models.native-query-snippet.permissions :as snippet.perms]@@ -19,17 +21,55 @@(derive :hook/timestamped?)(derive :hook/entity-id))+(t2/deftransforms :model/NativeQuerySnippet+ {:template_tags {:in mi/json-in+ :out (comp (mi/catch-normalization-exceptions+ #(lib.normalize/normalize :metabase.lib.schema.template-tag/template-tag-map %))+ mi/json-out-without-keywordization)}})+(defmethod collection/allowed-namespaces :model/NativeQuerySnippet[_]#{:snippets})+(defn- add-template-tags [{old-tags :template_tags :as snippet}]+ ;; Parse the snippet content to identify all template tags (like {{snippet: FilterA}} or {{var}}).+ ;; For snippet references, we need to resolve them to snippet IDs while preserving reference stability.+ ;;+ ;; Key behavior for snippet references:+ ;; 1. If a snippet with the exact referenced name exists in the DB, use its ID+ ;; 2. Otherwise, preserve the existing snippet-id from old tags if available+ ;; (this maintains references even when the target snippet has been renamed)+ ;; 3. If neither exists, keep the tag without a snippet-id (reference to non-existent snippet)+ ;;+ ;; This approach ensures that:+ ;; - References remain stable when target snippets are renamed+ ;; - References update to exact matches when the content is re-saved+ ;; - Creating a new snippet with a referenced name will cause queries to switch to it on next save+ (let [snippet-tag? (fn [tag] (= (:type tag) :snippet))+ name->old-tag (into {} (comp (map val)+ (filter snippet-tag?)+ (map (juxt :snippet-name identity)))+ old-tags)+ new-tags (lib/recognize-template-tags (:content snippet))+ set-snippet-id (fn [{:keys [snippet-name] :as tag}]+ ;; Check for exact match in database:+ (if-let [snippet-id (t2/select-one-fn :id :model/NativeQuerySnippet+ :name snippet-name)]+ (assoc tag :snippet-id snippet-id)+ ;; Use previous reference if possible:+ (or (name->old-tag snippet-name) tag)))]+ (->> (update-vals new-tags (fn [tag]+ (cond-> tag (snippet-tag? tag) (set-snippet-id))))+ (assoc snippet :template_tags))))+(t2/define-before-insert :model/NativeQuerySnippet [snippet]- (u/prog1 snippet+ (u/prog1 (add-template-tags snippet)(collection/check-collection-namespace :model/NativeQuerySnippet (:collection_id snippet))))(t2/define-before-update :model/NativeQuerySnippet[snippet]- (u/prog1 snippet+ (u/prog1 (cond-> snippet+ (:content snippet) add-template-tags);; throw an Exception if someone tries to update creator_id(when (contains? (t2/changes <>) :creator_id)(throw (UnsupportedOperationException. (tru "You cannot update the creator_id of a NativeQuerySnippet."))))@@ -74,10 +114,10 @@(serdes/extract-query-collections :model/NativeQuerySnippet opts))(defmethod serdes/make-spec "NativeQuerySnippet" [_model-name _opts]- {:copy [:archived :content :description :entity_id :name]- :transform {:created_at (serdes/date)+ {:copy [:archived :content :description :entity_id :name :template_tags]+ :transform {:created_at (serdes/date):collection_id (serdes/fk :model/Collection)- :creator_id (serdes/fk :model/User)}})+ :creator_id (serdes/fk :model/User)}})(defmethod serdes/dependencies "NativeQuerySnippet"[{:keys [collection_id]}]@@ -89,9 +129,9 @@;; Intended path here is ["snippets" "<nested ... collections>" "<snippet_eid_and_slug>"];; We just the default path, then pull it apart.;; The default is ["collections" "<nested ... collections>" "nativequerysnippets" "<base_name>"]- (let [basis (serdes/storage-default-collection-path snippet ctx)- file (last basis)- colls (->> basis rest (drop-last 2))] ; Drops the "collections" at the start, and the last two.+ (let [basis (serdes/storage-default-collection-path snippet ctx)+ file (last basis)+ colls (->> basis rest (drop-last 2))] ; Drops the "collections" at the start, and the last two.(concat ["snippets"] colls [file])))(defmethod serdes/load-one! "NativeQuerySnippet" [ingested maybe-local]diff --git a/src/metabase/queries/api/card.clj b/src/metabase/queries/api/card.cljindex 73fb1bbfc8b..4f420a0e580 100644--- a/src/metabase/queries/api/card.clj+++ b/src/metabase/queries/api/card.clj@@ -522,6 +522,10 @@;; if a `dashboard-id` is specified, check permissions on the *dashboard's* collection ID.(collection/check-write-perms-for-collection(actual-collection-id body))+ (try+ (lib/check-card-overwrite ::no-id (dataset-query->query query))+ (catch clojure.lang.ExceptionInfo e+ (throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 400)))))(let [body (cond-> body(string? (:type body)) (update :type keyword))](-> (card/create-card! body @api/*current-user*)@@ -612,7 +616,7 @@(check-if-card-can-be-saved dataset_query type)(when-some [query (dataset-query->query dataset_query)](try- (lib/check-overwrite id query)+ (lib/check-card-overwrite id query)(catch clojure.lang.ExceptionInfo e(throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 400))))))(let [card-before-update (t2/hydrate (api/write-check :model/Card id)diff --git a/src/metabase/queries/metadata.clj b/src/metabase/queries/metadata.cljindex 1cf2647a75c..5b018422ece 100644--- a/src/metabase/queries/metadata.clj+++ b/src/metabase/queries/metadata.clj@@ -1,5 +1,6 @@(ns metabase.queries.metadata(:require+ [clojure.set :as set][metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib.schema.id :as lib.schema.id][metabase.lib.util :as lib.util]@@ -32,14 +33,68 @@source-ids)(update-vals persistent!)))+(defn- query->template-tags+ [query]+ (-> query :native :template-tags vals))+(defn- query->template-tag-field-ids [query]- (when-let [template-tags (some-> query :native :template-tags vals seq)]+ (when-let [template-tags (query->template-tags query)](for [{tag-type :type, [dim-tag id _opts] :dimension} template-tags:when (and (#{:dimension :temporal-unit} tag-type)(= dim-tag :field)(integer? id))]id)))+(defn- query->template-tag-snippet-ids+ "Extract snippet IDs from template tags in a native query."+ [query]+ (some->> (query->template-tags query)+ (into #{}+ (comp (filter #(= :snippet (:type %)))+ (keep :snippet-id)))))++(defn- collect-recursive-snippets+ ([initial-snippet-ids]+ (when (seq initial-snippet-ids)+ (let [snippets (t2/select :model/NativeQuerySnippet :id [:in initial-snippet-ids])]+ (collect-recursive-snippets (set snippets) snippets (set initial-snippet-ids)))))+ ([all-snippets snippets-to-recurse seen-ids]+ (let [->nested-snippet-ids (fn [snippet]+ (when snippet+ (for [tag (vals (:template_tags snippet))+ :when (= "snippet" (:type tag))+ :let [snippet-id (:snippet-id tag)]+ :when (and snippet-id+ (not (contains? seen-ids snippet-id)))]+ snippet-id)))+ nested-snippet-ids (into #{} (mapcat ->nested-snippet-ids) snippets-to-recurse)+ nested-snippets (when (seq nested-snippet-ids)+ (t2/select :model/NativeQuerySnippet :id [:in nested-snippet-ids]))]+ (if-not (seq nested-snippet-ids)+ all-snippets+ (recur (into all-snippets nested-snippets)+ nested-snippets+ (set/union seen-ids nested-snippet-ids))))))++(defn- collect-snippet-field-ids+ [snippets]+ (set+ (for [snippet snippets+ :when (:template_tags snippet)+ tag (vals (:template_tags snippet))+ :when (#{:dimension :temporal-unit} (:type tag))+ :let [dimension (:dimension tag)+ ;; Handle both keyword and string field references+ [dim-type field-id] (cond+ (vector? dimension) dimension+ (string? dimension) (try+ (read-string dimension)+ (catch Exception _ nil))+ :else nil)]+ :when (and (#{:field "field"} dim-type)+ (integer? field-id))]+ field-id)))+(defn- batch-fetch-query-metadata*"Fetch dependent metadata for ad-hoc queries."[queries]@@ -58,6 +113,11 @@fk-target-tables (schema.table/batch-fetch-table-query-metadatas fk-target-table-ids)tables (concat source-tables fk-target-tables)template-tag-field-ids (into #{} (mapcat query->template-tag-field-ids) queries)+ direct-snippet-ids (into #{} (mapcat query->template-tag-snippet-ids) queries)+ snippets (collect-recursive-snippets direct-snippet-ids)+ snippet-field-ids (collect-snippet-field-ids snippets)+ ;; Combine all field IDs+ all-field-ids (set/union template-tag-field-ids snippet-field-ids)query-database-ids (into #{} (keep :database) queries)database-ids (into query-database-ids(keep :db_id)@@ -75,7 +135,9 @@[id ""][Integer/MAX_VALUE (str id)]))tables)- :fields (sort-by :id (schema.field/get-fields template-tag-field-ids))}))+ :fields (sort-by :id (schema.field/get-fields all-field-ids))+ ;; Add snippets to the response+ :snippets (sort-by :id snippets)}))(defn batch-fetch-query-metadata"Fetch dependent metadata for ad-hoc queries."diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 5f29393727d..c7cf03c9a96 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -20,7 +20,6 @@[metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib-be.metadata.jvm :as lib.metadata.jvm][metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.lib.normalize :as lib.normalize][metabase.lib.schema.metadata :as lib.schema.metadata]@@ -39,8 +38,6 @@[metabase.queries.models.parameter-card :as parameter-card][metabase.queries.models.query :as query][metabase.query-permissions.core :as query-perms]- ;; legacy usage -- don't do things like this going forward- ^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.query-processor.store :as qp.store][metabase.query-processor.util :as qp.util][metabase.search.core :as search][metabase.util :as u]@@ -374,30 +371,6 @@(when table-id{:table_id table-id})))))))-(defn- check-for-circular-source-query-references- "Check that a `card`, if it is using another Card as its source, does not have circular references between source- Cards. (e.g. Card A cannot use itself as a source, or if A uses Card B as a source, Card B cannot use Card A, and so- forth.)"- [{query :dataset_query, id :id}] ; don't use `u/the-id` here so that we can use this with `pre-insert` too- (loop [query query, ids-already-seen #{id}]- (let [source-card-id (qp.util/query->source-card-id query)]- (cond- (not source-card-id)- :ok-- (ids-already-seen source-card-id)- (throw- (ex-info (tru "Cannot save Question: source query has circular references.")- {:status-code 400}))-- :else- (recur (or (if (qp.store/initialized?)- (:dataset-query (lib.metadata/card (qp.store/metadata-provider) source-card-id))- (t2/select-one-fn :dataset_query :model/Card :id source-card-id))- (throw (ex-info (tru "Card {0} does not exist." source-card-id)- {:status-code 404})))- (conj ids-already-seen source-card-id))))))-(defn- maybe-normalize-query [card](cond-> card(seq (:dataset_query card)) (update :dataset_query #(mi/maybe-normalize-query :in %))))@@ -545,8 +518,6 @@card (maybe-check-dashboard-internal-card(merge defaults card))](u/prog1 card- ;; make sure this Card doesn't have circular source query references- (check-for-circular-source-query-references card)(check-field-filter-fields-are-from-correct-database card);; TODO: add a check to see if all id in :parameter_mappings are in :parameters (#40013)(assert-valid-type card)@@ -648,9 +619,6 @@"Newly Added:" newly-added-param-field-ids);; Now update the FieldValues for the Fields referenced by this Card.(field-values/update-field-values-for-on-demand-dbs! newly-added-param-field-ids)))))- ;; make sure this Card doesn't have circular source query references if we're updating the query- (when (:dataset_query changes)- (check-for-circular-source-query-references card));; updating a model dataset query to not support implicit actions will disable implicit actions if they exist(when (and (:dataset_query changes)(= (:type old-card-info) :model)diff --git a/src/metabase/query_processor/middleware/resolve_referenced.clj b/src/metabase/query_processor/middleware/resolve_referenced.cljindex 10b41760453..7ef3eae601a 100644--- a/src/metabase/query_processor/middleware/resolve_referenced.clj+++ b/src/metabase/query_processor/middleware/resolve_referenced.clj@@ -27,51 +27,97 @@(qp.resolve-source-table/resolve-source-tables resolved-query)(qp.resolve-fields/resolve-fields resolved-query)))-(mu/defn- card-subquery-graph+(mu/defn- fetch-card-query[metadata-providerable :- ::lib.schema.metadata/metadata-providerable- graph :- :map- card-id :- ::lib.schema.id/card]- (let [card-query (->> (or (lib.metadata/card metadata-providerable card-id)- (throw (ex-info (tru "Card {0} does not exist, or is from a different Database." (pr-str card-id))- {:type qp.error-type/invalid-query, :card-id card-id})))- (qp.fetch-source-query/normalize-card-query metadata-providerable)- :dataset-query)]- (reduce- (fn [g sub-card-id]- (card-subquery-graph metadata-providerable- (dep/depend g card-id sub-card-id)- sub-card-id))- graph- (lib/template-tag-card-ids card-query))))+ card-id :- ::lib.schema.id/card]+ (->> (or (lib.metadata/card metadata-providerable card-id)+ (throw (ex-info (tru "Card {0} does not exist, or is from a different Database." (pr-str card-id))+ {:type qp.error-type/invalid-query, :card-id card-id})))+ (qp.fetch-source-query/normalize-card-query metadata-providerable)+ :dataset-query))++(mu/defn- fetch-snippet+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ snippet-id :- ::lib.schema.id/snippet]+ (or (lib.metadata/native-query-snippet metadata-providerable snippet-id)+ (throw (ex-info (tru "Snippet {0} does not exist." (pr-str snippet-id))+ {:type qp.error-type/invalid-query, :snippet-id snippet-id}))))++(mu/defn- subquery-graph+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ graph :- :map+ init-query :- ::lib.schema/query]+ (letfn [(card-subquery-graph [mp graph card-id]+ (let [card-query (fetch-card-query mp card-id)+ card-ids (lib/native-query-card-ids card-query)+ snippet-ids (lib/native-query-snippet-ids card-query)]+ (subquery-graph* mp graph ::card card-id card-ids snippet-ids)))+ (snippet-subquery-graph [mp graph snippet-id]+ (let [snippet (fetch-snippet mp snippet-id)+ snippet-template-tags (:template-tags snippet)+ card-ids (lib/template-tags->card-ids snippet-template-tags)+ snippet-ids (lib/template-tags->snippet-ids snippet-template-tags)]+ (subquery-graph* mp graph ::snippet snippet-id card-ids snippet-ids)))+ (subquery-graph* [mp graph node-type node-id card-ids snippet-ids]+ (as-> graph <>+ (reduce (card-recurse mp node-type node-id) <> card-ids)+ (reduce (snippet-recurse mp node-type node-id) <> snippet-ids)))+ (card-recurse [mp node-type id]+ (fn [graph nested-card-id]+ (card-subquery-graph mp+ (dep/depend graph [node-type id] [::card nested-card-id])+ nested-card-id)))+ (snippet-recurse [mp node-type id]+ (fn [graph nested-snippet-id]+ (snippet-subquery-graph mp+ (dep/depend graph [node-type id] [::snippet nested-snippet-id])+ nested-snippet-id)))]+ (let [card-ids (lib/native-query-card-ids init-query)+ snippet-ids (lib/native-query-snippet-ids init-query)]+ (subquery-graph* metadata-providerable+ graph+ ::card+ ::init-id+ card-ids+ snippet-ids))))(mu/defn- circular-ref-error :- ::lib.schema.common/non-blank-string[metadata-providerable :- ::lib.schema.metadata/metadata-providerable- from-card :- ::lib.schema.id/card- to-card :- ::lib.schema.id/card]- (let [cards (into {}- (map (juxt :id :name))- (lib.metadata/bulk-metadata metadata-providerable :metadata/card #{from-card to-card}))- from-name (or (get cards from-card)- (throw (ex-info (tru "Referenced query is from a different database")- {:type qp.error-type/invalid-query, :card-id from-card})))- to-name (or (get cards to-card)- (throw (ex-info (tru "Referenced query is from a different database")- {:type qp.error-type/invalid-query, :card-id to-card})))]- (str- (tru "This query has circular referencing sub-queries. ")- (tru "These questions seem to be part of the problem: \"{0}\" and \"{1}\"." from-name to-name))))+ from-type :- :keyword+ from-id :- [:or ::lib.schema.id/card ::lib.schema.id/snippet]+ to-type :- :keyword+ to-id :- [:or ::lib.schema.id/card ::lib.schema.id/snippet]]+ (let [get-card-name (fn [card-id]+ (if-let [card (lib.metadata/card metadata-providerable card-id)]+ (:name card)+ (throw (ex-info (tru "Referenced query is from a different database")+ {:type qp.error-type/invalid-query, :card-id card-id}))))+ get-snippet-name (fn [snippet-id]+ (if-let [snippet (lib.metadata/native-query-snippet metadata-providerable snippet-id)]+ (:name snippet)+ (throw (ex-info (tru "Referenced snippet not found")+ {:type qp.error-type/invalid-query, :snippet-id snippet-id}))))+ [from-name from-label] (case from-type+ ::card [(get-card-name from-id) "question"]+ ::snippet [(get-snippet-name from-id) "snippet"])+ [to-name to-label] (case to-type+ ::card [(get-card-name to-id) "question"]+ ::snippet [(get-snippet-name to-id) "snippet"])]+ (str (tru "This query has circular referencing sub-queries. ")+ (tru "The {0} \"{1}\" and the {2} \"{3}\" seem to be part of the problem."+ from-label from-name to-label to-name))))(mu/defn- check-for-circular-references- "Done for side effects; [[card-subquery-graph]] will throw if there are circular references."+ "Done for side effects; [[subquery-graph]] will throw if there are circular references."[query :- ::lib.schema/query](try- (reduce (partial card-subquery-graph query)- (dep/graph)- (lib/template-tag-card-ids query))+ (subquery-graph query (dep/graph) query)(catch ExceptionInfo e- (let [{:keys [reason node dependency]} (ex-data e)]+ (let [{:keys [reason node dependency]} (ex-data e)+ [node-type node-id] node+ [dependency-type dependency-id] dependency](if (= reason :weavejester.dependency/circular-dependency)- (throw (ex-info (circular-ref-error query node dependency) {:original-exception e}))+ (throw (ex-info (circular-ref-error query node-type node-id dependency-type dependency-id) {:original-exception e}))(throw e))))))(mu/defn resolve-referenced-card-resources :- ::lib.schema/querydiff --git a/src/metabase/query_processor/setup.clj b/src/metabase/query_processor/setup.cljindex cf3541912ba..20cc868bd98 100644--- a/src/metabase/query_processor/setup.clj+++ b/src/metabase/query_processor/setup.clj@@ -59,6 +59,8 @@nil)(metadatas [_this metadata-type ids](bootstrap-metadatas metadata-type ids))+ (metadatas-by-name [_this _metadata-type _names]+ nil)(tables [_this]nil)(metadatas-for-table [_this _metadata-type _table-id]diff --git a/test/metabase/driver/sql/parameters/substitute_test.clj b/test/metabase/driver/sql/parameters/substitute_test.cljindex 89638c1f298..f4339a1bbca 100644--- a/test/metabase/driver/sql/parameters/substitute_test.clj+++ b/test/metabase/driver/sql/parameters/substitute_test.clj@@ -319,8 +319,15 @@(deftest ^:parallel substitute-native-query-snippets-test(testing "Native query snippet substitution"(let [query ["SELECT * FROM test_scores WHERE " (param "snippet:symbol_is_A")]]- (is (= ["SELECT * FROM test_scores WHERE symbol = 'A'" nil]- (substitute query {"snippet:symbol_is_A" (params/->ReferencedQuerySnippet 123 "symbol = 'A'")}))))))+ (is (=? ["SELECT * FROM test_scores WHERE symbol = 'A'" nil]+ (substitute query {"snippet:symbol_is_A" (params/->ReferencedQuerySnippet 123 "symbol = 'A'")}))))))++(deftest ^:parallel substitute-recursive-native-query-snippets-test+ (testing "Recursive native query snippet substitution"+ (let [query ["SELECT * FROM test_scores WHERE " (param "snippet:outer")]]+ (is (=? ["SELECT * FROM test_scores WHERE symbol = 'A'" nil]+ (substitute query {"snippet:outer" (params/->ReferencedQuerySnippet 123 "{{snippet:symbol_is_A}}")+ "snippet:symbol_is_A" (params/->ReferencedQuerySnippet 124 "symbol = 'A'")}))))));;; ------------------------------------------ simple substitution — {{x}} ------------------------------------------diff --git a/test/metabase/lib/fe_util_test.cljc b/test/metabase/lib/fe_util_test.cljcindex d79c228485a..a78b8733407 100644--- a/test/metabase/lib/fe_util_test.cljc+++ b/test/metabase/lib/fe_util_test.cljc@@ -1051,7 +1051,85 @@{:type :table, :id "card__1"}](lib/dependent-metadata query 1 :metric))query- (lib/append-stage query)))))+ (lib/append-stage query))))+ (testing "Native query snippets should be included in dependent metadata"+ (let [;; lib/native-query would try to look up the snippets:+ query {:lib/type :mbql/query+ :database 1+ :stages [{:lib/type :mbql.stage/native+ :native "SELECT * WHERE {{snippet: filter1}} AND {{snippet: filter2}}"+ :template-tags {"snippet: filter1" {:type :snippet+ :snippet-id 10+ :snippet-name "filter1"+ :name "snippet: filter1"+ :display-name "Filter 1"+ :id "def456"}+ "snippet: filter2" {:type :snippet+ :snippet-id 20+ :snippet-name "filter2"+ :name "snippet: filter2"+ :display-name "Filter 2"+ :id "ghi789"}}}]}]+ (is (=? [{:type :database}+ {:type :schema}+ {:type :native-query-snippet :id 10}+ {:type :native-query-snippet :id 20}]+ (lib/dependent-metadata query nil :question))))))++(deftest ^:parallel recursive-snippet-dependencies-test+ (testing "Recursive snippet dependencies should be resolved"+ (let [metadata-provider (lib.tu/mock-metadata-provider+ {:native-query-snippets+ [{:lib/type :metadata/native-query-snippet+ :id 10+ :name "filter1"+ :template-tags {"snippet: nested1" {:type :snippet+ :snippet-id 30+ :snippet-name "nested1"+ :name "snippet: nested1"+ :display-name "Nested 1"+ :id "test-id-30"}+ "snippet: nested2" {:type :snippet+ :snippet-id 40+ :snippet-name "nested2"+ :name "snippet: nested2"+ :display-name "Nested 2"+ :id "test-id-40"}}}+ {:lib/type :metadata/native-query-snippet+ :id 30+ :name "nested1"+ :template-tags {"snippet: deeply-nested" {:type :snippet+ :snippet-id 50+ :snippet-name "deeply-nested"+ :name "snippet: deeply-nested"+ :display-name "Deeply Nested"+ :id "test-id-50"}}}+ {:lib/type :metadata/native-query-snippet+ :id 40+ :name "nested2"+ :template-tags {}}+ {:lib/type :metadata/native-query-snippet+ :id 50+ :name "deeply-nested"+ :template-tags {}}]})+ query (lib/query metadata-provider+ {:lib/type :mbql/query+ :database 1+ :stages [{:lib/type :mbql.stage/native+ :native "SELECT * WHERE {{snippet: filter1}}"+ :template-tags {"snippet: filter1" {:type :snippet+ :snippet-id 10+ :snippet-name "filter1"+ :name "snippet: filter1"+ :display-name "Filter 1"+ :id "test-id-1"}}}]})]+ (is (=? [{:type :database}+ {:type :schema}+ {:type :native-query-snippet :id 10}+ {:type :native-query-snippet :id 30}+ {:type :native-query-snippet :id 50}+ {:type :native-query-snippet :id 40}]+ (lib/dependent-metadata query nil :question))))))(deftest ^:parallel table-or-card-dependent-metadata-test(testing "start from table"diff --git a/test/metabase/lib/native_test.cljc b/test/metabase/lib/native_test.cljcindex be20eefe699..4026e199b82 100644--- a/test/metabase/lib/native_test.cljc+++ b/test/metabase/lib/native_test.cljc@@ -13,7 +13,7 @@#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))(deftest ^:parallel variable-tag-test- (are [exp input] (= exp (set (keys (lib.native/extract-template-tags input))))+ (are [exp input] (= exp (set (keys (lib.native/extract-template-tags meta/metadata-provider input))))#{"foo"} "SELECT * FROM table WHERE {{foo}} AND some_field IS NOT NULL"#{"foo" "bar"} "SELECT * FROM table WHERE {{foo}} AND some_field = {{bar}}";; Duplicates are flattened.@@ -22,7 +22,7 @@#{} "SELECT * FROM table WHERE {{&foo}}"))(deftest ^:parallel snippet-tag-test- (are [exp input] (= exp (set (keys (lib.native/extract-template-tags input))))+ (are [exp input] (= exp (set (keys (lib.native/extract-template-tags meta/metadata-provider input))))#{"snippet: foo "} "SELECT * FROM table WHERE {{snippet: foo }} AND some_field IS NOT NULL"#{"snippet: foo *#&@"} "SELECT * FROM table WHERE {{snippet: foo *#&@}}";; TODO: This logic should trim the whitespace and unify these two snippet names.@@ -31,7 +31,7 @@#{"snippet: foo" "snippet:foo"} "SELECT * FROM table WHERE {{snippet: foo}} AND {{snippet:foo}}"))(deftest ^:parallel card-tag-test- (are [exp input] (= exp (set (keys (lib.native/extract-template-tags input))))+ (are [exp input] (= exp (set (keys (lib.native/extract-template-tags meta/metadata-provider input))))#{"#123"} "SELECT * FROM table WHERE {{ #123 }} AND some_field IS NOT NULL";; TODO: This logic should trim the whitespace and unify these two card tags.;; I think this is a bug in the original code but am aiming to reproduce it exactly for now.@@ -42,22 +42,30 @@(deftest ^:parallel template-tags-test(testing "snippet tags"- (is (=? {"snippet:foo" {:type :snippet- :name "snippet:foo"- :snippet-name "foo"- :id string?}}- (lib.native/extract-template-tags "SELECT * FROM table WHERE {{snippet:foo}}")))- (is (=? {"snippet:foo" {:type :snippet- :name "snippet:foo"- :snippet-name "foo"- :id string?}- "snippet: foo" {:type :snippet- :name "snippet: foo"- :snippet-name "foo"- :id string?}}- ;; TODO: This should probably be considered a bug - whitespace matters for the name.- ;; Tech debt issue: #39378- (lib.native/extract-template-tags "SELECT * FROM {{snippet: foo}} WHERE {{snippet:foo}}"))))+ (let [snippet {:type :snippet+ :name "foo"+ :id 1}+ metadata-provider (lib.tu/mock-metadata-provider+ {:native-query-snippets [snippet]})]+ (is (=? {"snippet:foo" {:type :snippet+ :name "snippet:foo"+ :snippet-name "foo"+ :snippet-id 1+ :id string?}}+ (lib.native/extract-template-tags metadata-provider "SELECT * FROM table WHERE {{snippet:foo}}")))+ (is (=? {"snippet:foo" {:type :snippet+ :name "snippet:foo"+ :snippet-name "foo"+ :snippet-id 1+ :id string?}+ "snippet: foo" {:type :snippet+ :name "snippet: foo"+ :snippet-name "foo"+ :snippet-id 1+ :id string?}}+ ;; TODO: This should probably be considered a bug - whitespace matters for the name.+ ;; Tech debt issue: #39378+ (lib.native/extract-template-tags metadata-provider "SELECT * FROM {{snippet: foo}} WHERE {{snippet:foo}}")))))(testing "renaming a variable"(let [old-tag {:type :text@@ -69,14 +77,14 @@:name "bar":display-name "Bar":id (:id old-tag)}}- (lib.native/extract-template-tags "SELECT * FROM {{bar}}"+ (lib.native/extract-template-tags meta/metadata-provider "SELECT * FROM {{bar}}"{"foo" old-tag}))))(testing "keeps display-name if it's customized"(is (=? {"bar" {:type :text:name "bar":display-name "Custom Name":id (:id old-tag)}}- (lib.native/extract-template-tags "SELECT * FROM {{bar}}"+ (lib.native/extract-template-tags meta/metadata-provider "SELECT * FROM {{bar}}"{"foo" (assoc old-tag :display-name "Custom Name")}))))(testing "works with other variables present, if they don't change"@@ -89,7 +97,7 @@:name "bar":display-name "Bar":id (:id old-tag)}}- (lib.native/extract-template-tags "SELECT * FROM {{bar}} AND field = {{other}}"+ (lib.native/extract-template-tags meta/metadata-provider "SELECT * FROM {{bar}} AND field = {{other}}"{"foo" old-tag"other" other})))))))@@ -108,6 +116,7 @@:type :snippet})s2 (mktag {:name "snippet:another snippet":snippet-name "another snippet"+ :snippet-id 124:type :snippet})c1 (mktag {:name "#123-card-1"@@ -115,24 +124,32 @@:card-id 123})c2 (mktag {:name "#321":type :card- :card-id 321})]+ :card-id 321})+ metadata-provider (lib.tu/mock-metadata-provider+ {:native-query-snippets [{:name "first snippet"+ :id 123}+ {:name "another snippet"+ :id 124}]})](is (=? {"foo" v1"#123-card-1" c1- "snippet:first snippet" (dissoc s1 :snippet-id)}+ "snippet:first snippet" s1}(lib.native/extract-template-tags+ metadata-provider"SELECT * FROM {{#123-card-1}} WHERE {{foo}} AND {{ snippet:first snippet}}")))(is (=? {"bar" v2"baz" v3"snippet:another snippet" s2"#321" c2}(lib.native/extract-template-tags+ metadata-provider"SELECT * FROM {{#321}} WHERE {{baz}} AND {{bar}} AND {{snippet:another snippet}}"{"foo" (assoc v1 :id (str (random-uuid)))"#123-card-1" (assoc c1 :id (str (random-uuid)))"snippet:first snippet" (assoc s1 :id (str (random-uuid)))})))(let [s1-uuid (str (random-uuid))]- (is (= {"snippet:another snippet" (assoc (dissoc s2 :snippet-id) :id s1-uuid)}+ (is (= {"snippet:another snippet" (assoc s2 :id s1-uuid)}(lib.native/extract-template-tags+ metadata-provider"SELECT * FROM {{snippet:another snippet}}"{"snippet:first snippet" (assoc s1 :id s1-uuid)})))))))@@ -327,7 +344,7 @@(deftest ^:parallel engine-test(is (= :h2 (lib/engine (lib.tu/native-query)))))-(deftest ^:parallel template-tag-card-ids-test+(deftest ^:parallel native-query-card-ids-test(let [query (lib/query (lib.tu/metadata-provider-with-mock-cards){:database (meta/id):type :native@@ -339,7 +356,7 @@:display-name "Y":card-id 2}}}})](is (= #{1 2}- (lib/template-tag-card-ids query)))))+ (lib/native-query-card-ids query)))))(deftest ^:parallel template-tags-referenced-cards-test(testing "returns Card instances from raw query"diff --git a/test/metabase/lib/test_metadata/graph_provider.cljc b/test/metabase/lib/test_metadata/graph_provider.cljcindex 36a971050e2..2b02ddc0418 100644--- a/test/metabase/lib/test_metadata/graph_provider.cljc+++ b/test/metabase/lib/test_metadata/graph_provider.cljc@@ -69,6 +69,9 @@(graph-database metadata-graph))(metadatas [_this metadata-type ids](graph-metadatas metadata-graph metadata-type ids))+ (metadatas-by-name [_this _metadata-type _names]+ ;; Not implemented+ [])(tables [_this](graph-tables metadata-graph))(metadatas-for-table [_this metadata-type table-id]diff --git a/test/metabase/lib/test_util/metadata_providers/mock.cljc b/test/metabase/lib/test_util/metadata_providers/mock.cljcindex 29c50f335d9..943d0194861 100644--- a/test/metabase/lib/test_util/metadata_providers/mock.cljc+++ b/test/metabase/lib/test_util/metadata_providers/mock.cljc@@ -62,6 +62,21 @@(= metadata-type :metadata/table) (dissoc :fields)))))(get metadata k))))+(defn- mock-metadatas-by-name [metadata metadata-type names]+ (let [k (case metadata-type+ :metadata/table :tables+ :metadata/column :fields+ :metadata/card :cards+ :metadata/segment :segments+ :metadata/native-query-snippet :native-query-snippets)+ names (set names)]+ (into []+ (keep (fn [object]+ (when (contains? names (:name object))+ (cond-> (assoc object :lib/type metadata-type)+ (= metadata-type :metadata/table) (dissoc :fields)))))+ (get metadata k))))+(defn- mock-tables [metadata](for [table (:tables metadata)](-> (assoc table :lib/type :metadata/table)@@ -104,6 +119,8 @@(mock-database metadata))(metadatas [_this metadata-type ids](mock-metadatas metadata metadata-type ids))+ (metadatas-by-name [_this metadata-type ids]+ (mock-metadatas-by-name metadata metadata-type ids))(tables [_this](mock-tables metadata))(metadatas-for-table [_this metadata-type table-id]diff --git a/test/metabase/native_query_snippets/models/native_query_snippet_test.clj b/test/metabase/native_query_snippets/models/native_query_snippet_test.cljindex bf91d403d49..97c2d2bc0e0 100644--- a/test/metabase/native_query_snippets/models/native_query_snippet_test.clj+++ b/test/metabase/native_query_snippets/models/native_query_snippet_test.clj@@ -68,3 +68,80 @@(is (= "7ac51ad0"(serdes/raw-hash ["my snippet" (serdes/identity-hash coll) (:created_at snippet)])(serdes/identity-hash snippet)))))))++(deftest basic-param-finding-test+ (testing "Can find params in a snippet"+ (mt/with-temp [:model/NativeQuerySnippet {snippet-id :id} {:name "my snippet" :content "{{id}}"}]+ (is (=? {"id" {:type :text,+ :name "id",+ :display-name "ID"}}+ (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-id))))))++(deftest update-param-finding-test+ (testing "Can find params on update"+ (mt/with-temp [:model/NativeQuerySnippet {snippet-id :id} {:name "my snippet" :content "id"}]+ (is (= {} (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-id)))+ (t2/update! :model/NativeQuerySnippet :id snippet-id {:content "{{id}}"})+ (is (=? {"id" {:type :text,+ :name "id",+ :display-name "ID"}}+ (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-id))))))++(deftest recursive-snippets-test+ (testing "Does not find params in child snippets"+ (mt/with-temp [:model/NativeQuerySnippet {inner-id :id} {:name "inner" :content "id"}+ :model/NativeQuerySnippet {snippet-id :id} {:name "my snippet" :content "{{snippet: inner}}"}]+ (is (=? {"snippet: inner"+ {:type :snippet,+ :name "snippet: inner",+ :snippet-name "inner",+ :display-name "Snippet: Inner",+ :snippet-id inner-id}}+ (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-id))))))++(deftest not-parse-recursive-snippets-test+ (testing "Does not find params in child snippets"+ (mt/with-temp [:model/NativeQuerySnippet {inner-id :id} {:name "inner" :content "{{id}}"}+ :model/NativeQuerySnippet {snippet-id :id} {:name "my snippet" :content "{{snippet: inner}}"}]+ (is (=? {"snippet: inner"+ {:type :snippet,+ :name "snippet: inner",+ :snippet-name "inner",+ :display-name "Snippet: Inner",+ :snippet-id inner-id}}+ (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-id))))))++(deftest template-tags-serialization-test+ (testing "Template tags serialization preserves nil, empty, and populated states"+ (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}]++ (testing "nil in -> {} out"+ (let [snippet (t2/insert-returning-instance! :model/NativeQuerySnippet+ {:name "nil-tags"+ :content "SELECT 1"+ :creator_id user-id+ :template_tags nil})+ extracted (serdes/extract-one "NativeQuerySnippet" {} snippet)]+ ;; toucan hooks populate it:+ (is (= {} (:template_tags extracted)))+ (t2/delete! :model/NativeQuerySnippet :id (:id snippet))))++ (testing "empty map in -> empty map out"+ (mt/with-temp [:model/NativeQuerySnippet snippet+ {:name "empty-tags"+ :content "SELECT 1"+ :creator_id user-id+ :template_tags {}}]+ (let [extracted (serdes/extract-one "NativeQuerySnippet" {} snippet)]+ (is (= {} (:template_tags extracted))))))++ (testing "tags in -> tags out"+ (mt/with-temp [:model/NativeQuerySnippet snippet+ {:name "with-tags"+ :content "WHERE id = {{id}}"+ :creator_id user-id}]+ (let [extracted (serdes/extract-one "NativeQuerySnippet" {} snippet)]+ (is (=? {"id" {:type :text+ :name "id"+ :display-name "ID"}}+ (:template_tags extracted)))))))))diff --git a/test/metabase/native_query_snippets/models/snippet_persistence_test.clj b/test/metabase/native_query_snippets/models/snippet_persistence_test.cljnew file mode 100644index 00000000000..8323608aecf--- /dev/null+++ b/test/metabase/native_query_snippets/models/snippet_persistence_test.clj@@ -0,0 +1,132 @@+(ns metabase.native-query-snippets.models.snippet-persistence-test+ (:require+ [clojure.test :refer :all]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db :test-users))++(deftest snippet-reference-persistence-test+ (testing "Snippet references should persist when referenced snippets are renamed"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :namespace :snippets}+ ;; Step 1: Create Snippet A+ :model/NativeQuerySnippet {snippet-a-id :id} {:name "Snippet A"+ :content "WHERE price > 100"+ :collection_id coll-id}+ ;; Step 2: Create Snippet B that refers to Snippet A+ :model/NativeQuerySnippet {snippet-b-id :id} {:name "Snippet B"+ :content "SELECT * FROM orders {{snippet: Snippet A}}"+ :collection_id coll-id}]+ (testing "Initial reference should point to Snippet A"+ (let [template-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-b-id)]+ (is (contains? template-tags "snippet: Snippet A"))+ (is (= snippet-a-id (get-in template-tags ["snippet: Snippet A" :snippet-id])))))+ (testing "with Snippet A renamed to Snippet C"+ (t2/update! :model/NativeQuerySnippet snippet-a-id {:name "Snippet C"})+ (testing "Snippet B should still refer to snippet-a-id"+ (let [updated-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-b-id)]+ ;; The template tag key is still "snippet: Snippet A" because we haven't edited Snippet B+ (is (contains? updated-tags "snippet: Snippet A"))+ ;; But it still points to the same snippet (now named Snippet C)+ (is (= snippet-a-id (get-in updated-tags ["snippet: Snippet A" :snippet-id])))))+ (testing "with Snippet B edited but preserving reference to Snippet A"+ (t2/update! :model/NativeQuerySnippet snippet-b-id+ {:content "SELECT id, name FROM orders {{snippet: Snippet A}} LIMIT 10"})+ (let [edited-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-b-id)]+ ;; The reference text is still "snippet: Snippet A"+ (is (contains? edited-tags "snippet: Snippet A"))+ ;; And it STILL points to the same snippet ID (now Snippet C)+ (is (= snippet-a-id (get-in edited-tags ["snippet: Snippet A" :snippet-id]))+ "The snippet-id should persist even after editing the referring snippet")))))))++(deftest snippet-reference-update-on-name-change-test+ (testing "Snippet references should update when the parsed snippet name changes"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :namespace :snippets}+ :model/NativeQuerySnippet {snippet-x-id :id} {:name "Snippet X"+ :content "WHERE status = 'active'"+ :collection_id coll-id}+ :model/NativeQuerySnippet {snippet-y-id :id} {:name "Snippet Y"+ :content "WHERE status = 'inactive'"+ :collection_id coll-id}+ :model/NativeQuerySnippet {snippet-ref-id :id} {:name "Reference Snippet"+ :content "SELECT * FROM users {{snippet: Snippet X}}"+ :collection_id coll-id}]+ (testing "Initial reference should point to Snippet X"+ (let [template-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-ref-id)]+ (is (= snippet-x-id (get-in template-tags ["snippet: Snippet X" :snippet-id])))+ (testing "Changing the referenced snippet name should update the reference"+ (t2/update! :model/NativeQuerySnippet snippet-ref-id+ {:content "SELECT * FROM users {{snippet: Snippet Y}}"})+ (let [updated-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-ref-id)]+ (is (not (contains? updated-tags "snippet: Snippet X")))+ (is (contains? updated-tags "snippet: Snippet Y"))+ (is (= snippet-y-id (get-in updated-tags ["snippet: Snippet Y" :snippet-id]))))))))))++(deftest snippet-reference-handles-missing-snippet-test+ (testing "Template tags should handle references to non-existent snippets"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :namespace :snippets}+ :model/NativeQuerySnippet {snippet-id :id} {:name "Reference Missing"+ :content "SELECT * FROM products {{snippet: NonExistent}}"+ :collection_id coll-id}]+ (let [template-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id snippet-id)]+ (is (contains? template-tags "snippet: NonExistent"))+ (is (nil? (get-in template-tags ["snippet: NonExistent" :snippet-id])))))))++(deftest multiple-snippet-references-test+ (testing "A snippet can reference multiple other snippets and maintain all references"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :namespace :snippets}+ :model/NativeQuerySnippet {filter1-id :id} {:name "Filter One"+ :content "price > 100"+ :collection_id coll-id}+ :model/NativeQuerySnippet {filter2-id :id} {:name "Filter Two"+ :content "quantity > 5"+ :collection_id coll-id}+ :model/NativeQuerySnippet {combined-id :id} {:name "Combined"+ :content "SELECT * FROM orders WHERE {{snippet: Filter One}} AND {{snippet: Filter Two}}"+ :collection_id coll-id}]+ (let [template-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id combined-id)]+ (is (= filter1-id (get-in template-tags ["snippet: Filter One" :snippet-id])))+ (is (= filter2-id (get-in template-tags ["snippet: Filter Two" :snippet-id])))+ (testing "After renaming referenced snippets, references should persist"+ (t2/update! :model/NativeQuerySnippet filter1-id {:name "Renamed Filter One"})+ (t2/update! :model/NativeQuerySnippet filter2-id {:name "Renamed Filter Two"})+ (let [updated-tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id combined-id)]+ (is (= filter1-id (get-in updated-tags ["snippet: Filter One" :snippet-id])))+ (is (= filter2-id (get-in updated-tags ["snippet: Filter Two" :snippet-id])))))))))++(deftest snippet-reference-prefers-exact-name-match-test+ (testing "When a new snippet is created matching an old reference name, the reference should switch to the new snippet"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :namespace :snippets}+ ;; Step 1: Create "expensive" snippet (with intentional typo on `<`!)+ :model/NativeQuerySnippet {expensive-wrong-id :id} {:name "expensive"+ :content "WHERE total < 100" ; Oops, wrong!+ :collection_id coll-id}+ ;; Step 2: Create a query that references "expensive"+ :model/NativeQuerySnippet {query-id :id} {:name "Expensive Orders Query"+ :content "SELECT * FROM orders {{snippet: expensive}}"+ :collection_id coll-id}]+ (testing "Initial reference points to the \"wrong\" 'expensive' snippet"+ (let [tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id query-id)]+ (is (= expensive-wrong-id (get-in tags ["snippet: expensive" :snippet-id])))))+ ;; Step 3: Rename the wrong snippet to "affordable" (fixing the mistake)+ (t2/update! :model/NativeQuerySnippet expensive-wrong-id {:name "affordable"})+ (testing "After renaming, reference still points to same snippet (now 'affordable')"+ (let [tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id query-id)]+ (is (= expensive-wrong-id (get-in tags ["snippet: expensive" :snippet-id]))+ "Reference persists even though snippet name changed")))+ ;; Step 4: Create a new "expensive" snippet with correct logic+ (mt/with-temp [:model/NativeQuerySnippet {expensive-correct-id :id} {:name "expensive"+ :content "WHERE total > 100"+ :collection_id coll-id}]+ (testing "With a new snippet matching the reference name, existing queries keep old reference"+ (let [tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id query-id)]+ (is (= expensive-wrong-id (get-in tags ["snippet: expensive" :snippet-id]))+ "Without re-saving, query still points to the old (now 'affordable') snippet")))+ ;; Step 5: Re-save the query (simulating user editing and saving)+ (t2/update! :model/NativeQuerySnippet query-id+ {:content "SELECT * FROM orders {{snippet: expensive}}"})+ (testing "After re-saving the query, reference switches to the new exact-match snippet"+ (let [tags (t2/select-one-fn :template_tags :model/NativeQuerySnippet :id query-id)]+ (is (= expensive-correct-id (get-in tags ["snippet: expensive" :snippet-id]))+ "Reference now points to the new 'expensive' snippet with correct logic")))))))diff --git a/test/metabase/queries/api/card_test.clj b/test/metabase/queries/api/card_test.cljindex 514083055e1..30ff14ed7fc 100644--- a/test/metabase/queries/api/card_test.clj+++ b/test/metabase/queries/api/card_test.clj@@ -4367,6 +4367,130 @@{:dataset_query (lib/->legacy-MBQL query-cycle):type :question}))))))))))+(deftest cannot-create-card-snippet-cycle-test+ (testing "Cannot create card → snippet → card cycle"+ (mt/with-temp [:model/NativeQuerySnippet snippet {:name "test-snippet"+ :content "WHERE true"+ :template_tags {}}+ :model/Card card {:dataset_query+ {:database (mt/id)+ :type :native+ :native {:query "SELECT * FROM products"}}}]+ ;; Update snippet to reference card (creates snippet → card)+ (t2/update! :model/NativeQuerySnippet (:id snippet)+ {:content (str "WHERE id IN ({{#" (:id card) "}})")+ :template_tags {(str "card-" (:id card)) {:type :card+ :card-id (:id card)+ :name (str "card-" (:id card))+ :display-name "Card Reference"}}})++ ;; Try to update card to reference snippet (would create card → snippet → card cycle)+ (is (= "Cannot save card with cycles."+ (mt/user-http-request :crowberto :put 400 (str "card/" (:id card))+ {:dataset_query+ {:database (mt/id)+ :type :native+ :native {:query (str "SELECT * FROM products {{snippet:" (:name snippet) "}}")+ :template-tags {(str "snippet: " (:name snippet))+ {:type :snippet+ :snippet-id (:id snippet)+ :snippet-name (:name snippet)+ :name (str "snippet:" (:name snippet))+ :display-name "Test Snippet"}}}}}))))))++(deftest cannot-create-multi-hop-card-snippet-cycle-test+ (testing "Cannot create cycles through multiple cards and snippets"+ (mt/with-temp [:model/NativeQuerySnippet snippet-1 {:name "snippet-1"+ :content "WHERE category = 'Electronics'"+ :template_tags {}}+ :model/NativeQuerySnippet snippet-2 {:name "snippet-2"+ :content "AND price > 100"+ :template_tags {}}+ :model/Card card-1 {:dataset_query+ {:database (mt/id)+ :type :native+ :native {:query (str "SELECT * FROM products {{snippet:" "snippet-1" "}}")+ :template-tags {"snippet:snippet-1"+ {:type :snippet+ :snippet-id (:id snippet-1)+ :snippet-name "snippet-1"+ :name (str "snippet:" "snippet-1")+ :display-name "Snippet 1"}}}}}+ :model/Card card-2 {:dataset_query+ {:database (mt/id)+ :type :native+ :native {:query (format "SELECT * FROM {{#%d}}" (:id card-1))+ :template-tags {(str "#" (:id card-1))+ {:type :card+ :card-id (:id card-1)+ :name (str "#" (:id card-1))+ :display-name "Card 1"}}}}}]+ ;; Update snippet-2 to reference card-2 (creates snippet-2 → card-2 → card-1 → snippet-1)+ (t2/update! :model/NativeQuerySnippet (:id snippet-2)+ {:content (str "AND id IN ({{#" (:id card-2) "}})")+ :template_tags {(str "card-" (:id card-2)) {:type :card+ :card-id (:id card-2)+ :name (str "card-" (:id card-2))+ :display-name "Card 2"}}})++ ;; Try to update card-1 to also reference snippet-2+ ;; (would create card-1 → snippet-2 → card-2 → card-1 cycle)+ (is (= "Cannot save card with cycles."+ (mt/user-http-request :crowberto :put 400 (str "card/" (:id card-1))+ {:dataset_query+ {:database (mt/id)+ :type :native+ :native {:query (str "SELECT * FROM products {{snippet:" "snippet-1" "}} {{snippet:" "snippet-2" "}}")+ :template-tags {(str "snippet:" "snippet-1")+ {:type :snippet+ :snippet-id (:id snippet-1)+ :snippet-name "snippet-1"+ :name "snippet:snippet-1"+ :display-name "Snippet 1"}+ (str "snippet:" "snippet-2")+ {:type :snippet+ :snippet-id (:id snippet-2)+ :snippet-name "snippet-2"+ :name (str "snippet:" "snippet-2")+ :display-name "Snippet 2"}}}}}))))))++(deftest cannot-create-new-card-with-cyclic-snippets-test+ (testing "Cannot create a new card that references snippets with existing cycles"+ ;; Create two snippets that reference each other in a cycle+ (mt/with-temp [:model/NativeQuerySnippet snippet-1 {:name "snippet-1"+ :content "WHERE category = 'Electronics'"+ :template_tags {"snippet:snippet-2"+ {:type :snippet+ :snippet-name "snippet-2"+ :name "snippet:snippet-2"+ :display-name "Snippet 2"}}}+ :model/NativeQuerySnippet _snippet-2 {:name "snippet-2"+ :content "AND price > 100 {{snippet: snippet-1}}"+ :template_tags {"snippet: snippet-1"+ {:type :snippet+ :snippet-name "snippet-1"+ :name "snippet:snippet-1"+ :display-name "Snippet 1"}}}]+ (t2/update! :model/NativeQuerySnippet (:id snippet-1)+ {:content "WHERE category = 'Electronics' {{snippet: snippet-2}}"})+ ;; Now try to create a NEW card that references snippet-1 (which has a cycle with snippet-2)+ ;; This should fail even though the card doesn't exist yet+ (is (= "Cannot save card with cycles."+ (mt/user-http-request :crowberto :post 400 "card"+ {:name "New Card with Cyclic Snippets"+ :dataset_query+ {:database (mt/id)+ :type :native+ :native {:query "SELECT * FROM products {{snippet:snippet-1}}"+ :template-tags {"snippet:snippet-1"+ {:type :snippet+ :snippet-id (:id snippet-1)+ :snippet-name "snippet-1"+ :name "snippet:snippet-1"+ :display-name "Snippet 1"}}}}+ :display "table"+ :visualization_settings {}}))))))+(deftest e2e-card-update-invalidates-cache-test(testing "Card update invalidates card's cache (#55955)"(let [existing-config (t2/select-one :model/CacheConfig :model_id 0 :model "root")]diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex dd60932cc56..e7e83c4654b 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -182,44 +182,6 @@(is (= 2 (t2/count :model/Action :id [:in [action-id-1 action-id-2]])))(is (= 2 (t2/count :model/ImplicitAction :action_id [:in [action-id-1 action-id-2]]))))))))-;;; ------------------------------------------ Circular Reference Detection --------------------------------------------(defn- card-with-source-table- "Generate values for a Card with `source-table` for use with `with-temp`."- [source-table & {:as kvs}]- (merge {:dataset_query {:database (mt/id)- :type :query- :query {:source-table source-table}}}- kvs))--(deftest circular-reference-test- (testing "Should throw an Exception if saving a Card that references itself"- (mt/with-temp [:model/Card card (card-with-source-table (mt/id :venues))]- ;; now try to make the Card reference itself. Should throw Exception- (is (thrown?- Exception- (t2/update! :model/Card (u/the-id card)- (card-with-source-table (str "card__" (u/the-id card)))))))))--(deftest circular-reference-test-2- (testing "Do the same stuff with circular reference between two Cards... (A -> B -> A)"- (mt/with-temp [:model/Card card-a (card-with-source-table (mt/id :venues))- :model/Card card-b (card-with-source-table (str "card__" (u/the-id card-a)))]- (is (thrown?- Exception- (t2/update! :model/Card (u/the-id card-a)- (card-with-source-table (str "card__" (u/the-id card-b)))))))))--(deftest circular-reference-test-3- (testing "ok now try it with A -> C -> B -> A"- (mt/with-temp [:model/Card card-a (card-with-source-table (mt/id :venues))- :model/Card card-b (card-with-source-table (str "card__" (u/the-id card-a)))- :model/Card card-c (card-with-source-table (str "card__" (u/the-id card-b)))]- (is (thrown?- Exception- (t2/update! :model/Card (u/the-id card-a)- (card-with-source-table (str "card__" (u/the-id card-c)))))))))-(deftest validate-collection-namespace-test(mt/with-temp [:model/Collection {collection-id :id} {:namespace "currency"}](testing "Shouldn't be able to create a Card in a non-normal Collection"diff --git a/test/metabase/query_processor/middleware/resolve_referenced_test.clj b/test/metabase/query_processor/middleware/resolve_referenced_test.cljindex 16a23b71b55..5e16ecd1077 100644--- a/test/metabase/query_processor/middleware/resolve_referenced_test.clj+++ b/test/metabase/query_processor/middleware/resolve_referenced_test.clj@@ -43,17 +43,17 @@(deftest ^:parallel referenced-query-from-different-db-test(testing "fails on query that references a native query from a different database"(let [metadata-provider meta/metadata-provider- tag-name "#1"- query (lib/query- (lib.tu/mock-metadata-provider- metadata-provider- {:database (assoc (lib.metadata/database metadata-provider) :id 1234)})- {:database 1234- :type :native- :native {:query (format "SELECT * FROM {{%s}} AS x" tag-name)- :template-tags {tag-name ; This tag's query is from the test db- {:id tag-name, :name tag-name, :display-name tag-name,- :type "card", :card-id 1}}}})]+ tag-name "#1"+ query (lib/query+ (lib.tu/mock-metadata-provider+ metadata-provider+ {:database (assoc (lib.metadata/database metadata-provider) :id 1234)})+ {:database 1234+ :type :native+ :native {:query (format "SELECT * FROM {{%s}} AS x" tag-name)+ :template-tags {tag-name ; This tag's query is from the test db+ {:id tag-name, :name tag-name, :display-name tag-name,+ :type "card", :card-id 1}}}})](is (thrown-with-msg?clojure.lang.ExceptionInfo#"\QCard 1 does not exist, or is from a different Database.\E"@@ -84,5 +84,229 @@(#'qp.resolve-referenced/check-for-circular-references entrypoint-query)(catch ExceptionInfo e(testing e- (is (= (#'qp.resolve-referenced/circular-ref-error entrypoint-query 2 1)+ (is (= (#'qp.resolve-referenced/circular-ref-error entrypoint-query+ ::qp.resolve-referenced/card 2+ ::qp.resolve-referenced/card 1)(ex-message e)))))))))++(defn- make-card-template-tag+ "Helper to create a card template tag with proper display-name"+ [card-id & [tag-name]]+ (let [name (or tag-name (str "#" card-id))]+ {name {:name name+ :display-name (str "Card " card-id)+ :type :card+ :card-id card-id}}))++(defn- make-snippet-template-tag+ "Helper to create a snippet template tag with proper display-name"+ [snippet-id snippet-name & [tag-name]]+ (let [name (or tag-name (str "snippet: " snippet-name))]+ {name {:name name+ :display-name snippet-name+ :type :snippet+ :snippet-name snippet-name+ :snippet-id snippet-id}}))++(defn- make-snippet+ "Helper to create a snippet with properly formatted template tags"+ [{:keys [id name content card-refs snippet-refs]}]+ (let [card-tags (reduce merge {} (map make-card-template-tag card-refs))+ snippet-tags (reduce merge {} (map (fn [[snippet-id snippet-name]]+ (make-snippet-template-tag snippet-id snippet-name))+ snippet-refs))]+ {:id id+ :name name+ :content content+ :template-tags (merge card-tags snippet-tags)}))++(deftest ^:parallel card-snippet-card-circular-reference-test+ (testing "Detects card→snippet→card circular references"+ (testing "Card 1 → Snippet A → Card 1 (direct cycle)"+ (let [metadata-provider (lib.tu/metadata-provider-with-cards-for-queries+ meta/metadata-provider+ [{:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{snippet: snippet-a}}"+ :template-tags (make-snippet-template-tag 100 "snippet-a")}}])+ ;; Add snippet to metadata provider+ metadata-provider-with-snippet+ (lib.tu/mock-metadata-provider+ metadata-provider+ {:native-query-snippets [(make-snippet {:id 100+ :name "snippet-a"+ :content "WHERE id IN (SELECT id FROM {{#1}})"+ :card-refs [1]+ :snippet-refs []})]})++ ;; Create the query that starts the cycle+ entrypoint-query (lib/query+ metadata-provider-with-snippet+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{#1}}"+ :template-tags (card-template-tags [1])}})]++ (testing "Should throw an exception for circular reference"+ (is (thrown-with-msg?+ ExceptionInfo+ #"circular|cycle"+ (#'qp.resolve-referenced/check-for-circular-references entrypoint-query))))))))++(deftest ^:parallel complex-card-snippet-cycle-test+ (testing "Detects complex card→snippet→snippet→card→snippet→card circular references"+ (testing "Card A → Snippet 1 → Snippet 2 → Card B → Snippet 3 → Card A"+ (let [;; Set up the metadata provider with both cards+ metadata-provider (lib.tu/metadata-provider-with-cards-for-queries+ meta/metadata-provider+ [;; Card A (id 1) references snippet-1+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{snippet: snippet-1}}"+ :template-tags (make-snippet-template-tag 101 "snippet-1")}}+ ;; Card B (id 2) references snippet-3+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{snippet: snippet-3}}"+ :template-tags (make-snippet-template-tag 103 "snippet-3")}}])+ ;; Add all three snippets to the metadata provider+ metadata-provider-with-snippets+ (lib.tu/mock-metadata-provider+ metadata-provider+ {:native-query-snippets [;; Snippet 1 references snippet-2+ (make-snippet {:id 101+ :name "snippet-1"+ :content "WHERE x IN ({{snippet: snippet-2}})"+ :card-refs []+ :snippet-refs [[102 "snippet-2"]]})+ ;; Snippet 2 references Card B (id 2)+ (make-snippet {:id 102+ :name "snippet-2"+ :content "SELECT y FROM {{#2}}"+ :card-refs [2]+ :snippet-refs []})+ ;; Snippet 3 references Card A (id 1), completing the cycle+ (make-snippet {:id 103+ :name "snippet-3"+ :content "SELECT z FROM {{#1}}"+ :card-refs [1]+ :snippet-refs []})]})++ ;; Create the query that starts with Card A+ entrypoint-query (lib/query+ metadata-provider-with-snippets+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{#1}}"+ :template-tags (card-template-tags [1])}})]++ (testing "Should throw an exception for circular reference"+ (is (thrown-with-msg?+ ExceptionInfo+ #"circular|cycle"+ (#'qp.resolve-referenced/check-for-circular-references entrypoint-query))))++ (testing "The cycle detection should work from any entry point"+ ;; Starting from Card B should also detect the cycle+ (let [card-b-query (lib/query+ metadata-provider-with-snippets+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{#2}}"+ :template-tags (card-template-tags [2])}})]+ (is (thrown-with-msg?+ ExceptionInfo+ #"circular|cycle"+ (#'qp.resolve-referenced/check-for-circular-references card-b-query)))))))))++(deftest ^:parallel snippet-to-snippet-cycle-test+ (testing "Detects direct snippet→snippet cycles"+ (testing "Snippet A → Snippet B → Snippet A"+ (let [;; Create snippets that reference each other+ metadata-provider-with-snippets+ (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:native-query-snippets [(make-snippet {:id 201+ :name "snippet-a"+ :content "WHERE x IN ({{snippet: snippet-b}})"+ :card-refs []+ :snippet-refs [[202 "snippet-b"]]})+ (make-snippet {:id 202+ :name "snippet-b"+ :content "SELECT y FROM ({{snippet: snippet-a}})"+ :card-refs []+ :snippet-refs [[201 "snippet-a"]]})]})+ entrypoint-query (lib/query+ metadata-provider-with-snippets+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM orders {{snippet: snippet-a}}"+ :template-tags (make-snippet-template-tag 201 "snippet-a")}})]+ (testing "Should throw an exception specifically mentioning snippet cycle"+ (is (thrown-with-msg?+ ExceptionInfo+ #"circular|cycle"+ (#'qp.resolve-referenced/check-for-circular-references entrypoint-query))))))++ (testing "Self-referencing snippet"+ (let [metadata-provider-with-snippet+ (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:native-query-snippets [;; Snippet that references itself+ (make-snippet {:id 301+ :name "recursive-snippet"+ :content "WHERE id IN (SELECT id FROM ({{snippet: recursive-snippet}}))"+ :card-refs []+ :snippet-refs [[301 "recursive-snippet"]]})]})+ entrypoint-query (lib/query+ metadata-provider-with-snippet+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM venues {{snippet: recursive-snippet}}"+ :template-tags (make-snippet-template-tag 301 "recursive-snippet")}})]+ (testing "Should throw an exception for self-referencing snippet"+ (is (thrown-with-msg?+ ExceptionInfo+ #"circular|cycle"+ (#'qp.resolve-referenced/check-for-circular-references entrypoint-query))))))))++(deftest ^:parallel valid-card-snippet-chain-test+ (testing "Allows valid non-cyclic card→snippet→snippet chains"+ (testing "Card → Snippet 1 → Snippet 2 (no cycle)"+ (let [;; Set up the metadata provider with one card+ metadata-provider (lib.tu/metadata-provider-with-cards-for-queries+ meta/metadata-provider+ [;; Card (id 1) references both snippet-1 and snippet-2+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM products {{snippet: snippet-1}} {{snippet: snippet-2}}"+ :template-tags (merge (make-snippet-template-tag 101 "snippet-1")+ (make-snippet-template-tag 102 "snippet-2"))}}])+ ;; Add two snippets where snippet-1 references snippet-2 (but no cycle)+ metadata-provider-with-snippets+ (lib.tu/mock-metadata-provider+ metadata-provider+ {:native-query-snippets [;; Snippet 1 references snippet-2+ (make-snippet {:id 101+ :name "snippet-1"+ :content "WHERE category IN ({{snippet: snippet-2}})"+ :card-refs []+ :snippet-refs [[102 "snippet-2"]]})+ ;; Snippet 2 does not reference anything else+ (make-snippet {:id 102+ :name "snippet-2"+ :content "SELECT DISTINCT category FROM categories WHERE active = true"+ :card-refs []+ :snippet-refs []})]})++ ;; Create the query that references Card 1+ entrypoint-query (lib/query+ metadata-provider-with-snippets+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{#1}}"+ :template-tags (card-template-tags [1])}})]++ (testing "Should NOT throw an exception for valid non-cyclic chain"+ ;; This should complete, without throwing an exception, and return a dependency graph+ (is (some? (#'qp.resolve-referenced/check-for-circular-references entrypoint-query))))))))diff --git a/test/metabase/query_processor_test/nested_queries_test.clj b/test/metabase/query_processor_test/nested_queries_test.cljindex af3f6c22962..be7411f9bbb 100644--- a/test/metabase/query_processor_test/nested_queries_test.clj+++ b/test/metabase/query_processor_test/nested_queries_test.clj@@ -242,16 +242,16 @@:breakout [*price]}))))))))(defn- query-with-source-card- ([card]- {:database lib.schema.id/saved-questions-virtual-database-id+ ([card db-id]+ {:database db-id:type :query:query {:source-table (str "card__" (u/the-id card))}})- ([card m]- (update (query-with-source-card card) :query #(merge (get m :query m) %)))+ ([card db-id m]+ (update (query-with-source-card card db-id) :query #(merge (get m :query m) %)))- ([card k v & {:as more}]- (query-with-source-card card (merge {k v} more))))+ ([card db-id k v & {:as more}]+ (query-with-source-card card db-id (merge {k v} more))))(deftest ^:parallel multilevel-nested-questions-with-joins(testing "Multilevel nested questions with joins work (#22859)"@@ -271,7 +271,7 @@:fields [&RP.reviews.id &RP.products.id &RP.products.ean]:condition [:= $product_id &RP.products.id]}]})])(is (=? {:status :completed}- (qp/process-query (query-with-source-card 2 :limit 1)))))))))+ (qp/process-query (query-with-source-card 2 lib.schema.id/saved-questions-virtual-database-id :limit 1)))))))))(deftest ^:parallel source-card-id-test(testing "Make sure we can run queries using source table `card__id` format."@@ -286,6 +286,7 @@[int int](qp/process-query(query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id(mt/mbql-query venues{:aggregation [:count]:breakout [$price]})))))))))))@@ -309,7 +310,7 @@:breakout [[:expression "Price level"]]:expressions {"Price level" [:case [[[:> $price 2] "expensive"]] {:default "budget"}]}:limit 2})])- (let [query (query-with-source-card 1)]+ (let [query (query-with-source-card 1 lib.schema.id/saved-questions-virtual-database-id)](mt/with-native-query-testing-context query(is (= [["budget" 81]["expensive" 19]]@@ -329,9 +330,10 @@(mt/format-rows-by[int int](qp/process-query- (query-with-source-card 1 (mt/mbql-query venues- {:aggregation [:count]- :breakout [*price]})))))))]+ (query-with-source-card 1 lib.schema.id/saved-questions-virtual-database-id+ (mt/mbql-query venues+ {:aggregation [:count]+ :breakout [*price]})))))))](is (=? (breakout-results :has-source-metadata? false :native-source? true)(run-native-query native-sub-query))"make sure `card__id`-style queries work with native source queries as well")@@ -373,7 +375,7 @@:limit 5})qp.compile/compile:query))- query (query-with-source-card 1)]+ query (query-with-source-card 1 lib.schema.id/saved-questions-virtual-database-id)](qp.store/with-metadata-provider (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries[(mt/native-query {:query native-sub-query})])(mt/with-native-query-testing-context query@@ -595,7 +597,7 @@[:id :name :category_id :latitude :longitude :price]);; todo: i don't know why the results don't have the information(mt/cols- (qp/process-query (query-with-source-card 1)))))))))+ (qp/process-query (query-with-source-card 1 lib.schema.id/saved-questions-virtual-database-id)))))))))(deftest ^:parallel correct-column-metadata-test-2(mt/test-drivers (mt/normal-drivers-with-feature :nested-queries)@@ -607,6 +609,7 @@(mt/cols(qp/process-query(query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id(mt/mbql-query venues{:aggregation [[:count]]:breakout [$price]}))))))))))@@ -626,9 +629,10 @@(qp.test-util/aggregate-col :count)](mt/cols(qp/process-query- (query-with-source-card 1 (mt/mbql-query checkins- {:aggregation [[:count]]- :breakout [!day.*date]})))))))))+ (query-with-source-card 1 lib.schema.id/saved-questions-virtual-database-id+ (mt/mbql-query checkins+ {:aggregation [[:count]]+ :breakout [!day.*date]})))))))))(defmethod driver/database-supports? [::driver/driver ::breakout-year-test][_driver _feature _database]@@ -663,7 +667,7 @@(is (=? [(assoc date-col :field_ref [:field (mt/id :checkins :date) nil], :unit :year)(assoc count-col :field_ref [:field "count" {:base-type :type/Integer}])](mt/cols- (qp/process-query (query-with-source-card 1)))))))))))+ (qp/process-query (query-with-source-card 1 lib.schema.id/saved-questions-virtual-database-id)))))))))))(defn- completed-status [{:keys [status], :as results}](if (= status :completed)@@ -676,6 +680,7 @@(qp.store/with-metadata-provider (qp.test-util/metadata-provider-with-cards-for-queries[(mt/mbql-query checkins)])(let [query (query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id(mt/$ids checkins{:filter [:time-interval *date -30 :day]}))](mt/with-native-query-testing-context query@@ -689,6 +694,7 @@[(mt/mbql-query checkins)])(is (= :completed(-> (query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id(mt/mbql-query checkins{:aggregation [[:count]]:filter [:= !quarter.*date "2014-01-01T08:00:00.000Z"]@@ -703,6 +709,7 @@[(mt/mbql-query checkins)])(is (= :completed(-> (query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id(mt/mbql-query checkins{:aggregation [[:count]]:breakout [!week.*date]@@ -727,6 +734,7 @@[int](qp/process-query(query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id{:aggregation [:count]})))))))))(deftest ^:parallel card-perms-test@@ -736,7 +744,9 @@(lib.tu/metadata-provider-with-cards-for-queries [{}])(lib.tu/merged-mock-metadata-provider {:cards [{:id 1, :collection-id 1000}]}))(is (= {:paths #{(perms/collection-read-path (t2/instance :model/Collection {:id 1000}))}}- (query-perms/required-perms-for-query (query-with-source-card 1 :aggregation [:count]))))))))+ (query-perms/required-perms-for-query (query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id+ :aggregation [:count]))))))))(deftest ^:parallel card-perms-test-2(testing "perms for a Card with a SQL source query\n"@@ -745,7 +755,9 @@(qp.store/with-metadata-provider (qp.test-util/metadata-provider-with-cards-for-queries[(mt/native-query {:query "SELECT * FROM VENUES"})])(is (= {:paths #{(perms/collection-read-path collection/root-collection)}}- (query-perms/required-perms-for-query (query-with-source-card 1 :aggregation [:count]))))))))+ (query-perms/required-perms-for-query (query-with-source-card 1+ lib.schema.id/saved-questions-virtual-database-id+ :aggregation [:count]))))))))(deftest card-perms-test-3(testing "perms for Card -> Card -> MBQL Source query\n"@@ -812,7 +824,7 @@:collection_id (some-> dest-collection-or-id-or-nil u/the-id):display "scalar":visualization_settings {}- :dataset_query (query-with-source-card card+ :dataset_query (query-with-source-card card (u/the-id db-or-id):aggregation [:count])})))(deftest save-card-with-source-query-via-api-testdiff --git a/test/metabase/query_processor_test/parameters_test.clj b/test/metabase/query_processor_test/parameters_test.cljindex c2f91dffbd6..54ef46e6c54 100644--- a/test/metabase/query_processor_test/parameters_test.clj+++ b/test/metabase/query_processor_test/parameters_test.clj@@ -111,7 +111,7 @@:type :model:dataset-query (mt/native-query {:query "select * from checkins"})}]})q "SELECT * FROM {{#1}} LIMIT 2"- tt (lib-native/extract-template-tags q)+ tt (lib-native/extract-template-tags mp q)res (qp/process-query(lib/querympdiff --git a/test_resources/serialization_baseline/snippets/WyQWnT23PF-SfbYLROllJ_snippet_2.yaml b/test_resources/serialization_baseline/snippets/WyQWnT23PF-SfbYLROllJ_snippet_2.yamlindex 14604ef6b1c..32034a0a16a 100644--- a/test_resources/serialization_baseline/snippets/WyQWnT23PF-SfbYLROllJ_snippet_2.yaml+++ b/test_resources/serialization_baseline/snippets/WyQWnT23PF-SfbYLROllJ_snippet_2.yaml@@ -5,6 +5,7 @@ created_at: '2024-08-28T14:36:15.328717Z'archived: falsecollection_id: nullcontent: 1 = 1+template_tags: {}creator_id: [email protected]serdes/meta:- id: WyQWnT23PF-SfbYLROllJdiff --git a/test_resources/serialization_baseline/snippets/Y6d4QwJgGKw-X1tRh3ir2_shared_collection/hcSr4xgVEd8AyElRRLu9w_snippet_1.yaml b/test_resources/serialization_baseline/snippets/Y6d4QwJgGKw-X1tRh3ir2_shared_collection/hcSr4xgVEd8AyElRRLu9w_snippet_1.yamlindex 5c86b90cd0d..541b45dd911 100644--- a/test_resources/serialization_baseline/snippets/Y6d4QwJgGKw-X1tRh3ir2_shared_collection/hcSr4xgVEd8AyElRRLu9w_snippet_1.yaml+++ b/test_resources/serialization_baseline/snippets/Y6d4QwJgGKw-X1tRh3ir2_shared_collection/hcSr4xgVEd8AyElRRLu9w_snippet_1.yaml@@ -5,6 +5,7 @@ created_at: '2024-08-28T14:36:15.324887Z'archived: falsecollection_id: Y6d4QwJgGKw-X1tRh3ir2content: 1 = 1+template_tags: {}creator_id: [email protected]serdes/meta:- id: hcSr4xgVEd8AyElRRLu9w