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
GHY-4103 Repair stale template tags on serdes import (#77897)
Ben Grabow1c2e735ab038
diff --git a/e2e/test/scenarios/native/card-tag-normalization.cy.spec.ts b/e2e/test/scenarios/native/card-tag-normalization.cy.spec.tsnew file mode 100644index 00000000000..6741228e784--- /dev/null+++ b/e2e/test/scenarios/native/card-tag-normalization.cy.spec.ts@@ -0,0 +1,59 @@+const { H } = cy;++// The frontend names card template tags `#<card-id>-<slugg(card.name)>` (see NativeQuery.ts), but any+// `#<id>-<slug>` is accepted. The backend stores tag names verbatim on save — names are only rewritten+// during serdes import, when the referenced card's id changes. These tests pin the FE->BE->FE edit+// cycle: saving never errors and never rewrites what the frontend sent.++describe("scenarios > native > card template tag normalization", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ });++ it("saves multiple differently-named references to the same card without erroring or rewriting", () => {+ H.createNativeQuestion({+ name: "Basic Aggregations",+ native: { query: 'SELECT COUNT(*) AS "count" FROM PEOPLE' },+ }).then(({ body: { id: cardId } }) => {+ H.startNewNativeQuestion({ query: "" });+ H.NativeEditor.type(+ `SELECT 1 FROM {{#${cardId}-foo}} AS a, {{#${cardId}-bar}} AS b`,+ { allowFastSet: true },+ );+ H.saveQuestion("Duplicate Card Refs", { wrapId: true });++ cy.get("@questionId").then((questionId) => {+ cy.request("GET", `/api/card/${questionId}`).then(({ body }) => {+ const query = JSON.stringify(body.dataset_query);+ expect(query).to.contain(`#${cardId}-foo`);+ expect(query).to.contain(`#${cardId}-bar`);+ });+ });+ });+ });++ it("reopens clean when the tag name matches what the frontend generated", () => {+ H.createNativeQuestion({+ name: "Bob's Café",+ native: { query: 'SELECT COUNT(*) AS "count" FROM PEOPLE' },+ }).then(({ body: { id: cardId } }) => {+ // slugg("Bob's Café") === "bobs-cafe", so this is the exact tag name the frontend generates+ const frontendTag = `#${cardId}-bobs-cafe`;++ H.startNewNativeQuestion({ query: "" });+ H.NativeEditor.type(`SELECT * FROM {{${frontendTag}}}`, {+ allowFastSet: true,+ });+ H.saveQuestion("Cafe Ref", { wrapId: true });++ cy.get("@questionId").then((questionId) => {+ H.visitQuestion(questionId);+ });+ cy.findByTestId("visibility-toggler").click();+ H.NativeEditor.get().should("contain", `{{${frontendTag}}}`);+ cy.findByTestId("qb-header").should("be.visible");+ cy.findByTestId("qb-header").button("Save").should("not.exist");+ });+ });+});diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.cljindex c09db840dc4..46a4a322917 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj@@ -18,6 +18,7 @@[metabase.search.core :as search][metabase.test :as mt][metabase.util :as u]+ [metabase.util.humanization :as u.humanization][metabase.util.json :as json][metabase.warehouses.models.database :as models.database][toucan2.core :as t2]))@@ -1423,6 +1424,81 @@:display-name "Snippet: WOOP"}}template-tags))))))))+(deftest load-native-card-template-tags-remap-test+ (testing "card template tag names, display names, and the native text follow :card-id to the local card id (#77516)"+ (let [serialized (atom nil)+ target1s (atom nil)+ target-eid (atom nil)+ native-eid (atom nil)]+ (ts/with-dbs [source-db dest-db]+ (ts/with-db source-db+ (let [db (ts/create! :model/Database :name "tag-db")+ table (ts/create! :model/Table :name "customers" :db_id (:id db))+ user (ts/create! :model/User :first_name "Tag" :last_name "User" :email "[email protected]")+ coll (ts/create! :model/Collection :name "Tag Collection")+ target (ts/create! :model/Card+ :name "BH Population Model"+ :collection_id (:id coll)+ :creator_id (:id user)+ :database_id (:id db)+ :table_id (:id table)+ :dataset_query {:type :query+ :database (:id db)+ :query {:source-table (:id table)}})+ tag-name (str "#" (:id target) "-bh-population-model")]+ (ts/create! :model/Card+ :name "Native Referencing Card"+ :collection_id (:id coll)+ :creator_id (:id user)+ :database_id (:id db)+ :query_type :native+ :entity_id "nativecardtagseid0001"+ :dataset_query {:type :native+ :database (:id db)+ :native {:query (format "SELECT * FROM {{%s}}" tag-name)+ :template-tags+ {tag-name {:id "203a5ecb-24b1-4d5b-8bee-b3520d21fa89"+ :name tag-name+ :display-name (u.humanization/name->human-readable-name :simple tag-name)+ :type "card"+ :card-id (:id target)}}}})+ (reset! target1s target)+ (reset! target-eid (:entity_id target))+ (reset! native-eid "nativecardtagseid0001")+ (reset! serialized (into [] (serdes.extract/extract {:no-settings true})))))+ (ts/with-db dest-db+ ;; pre-create some cards so the referenced card can't land on its source id+ (let [db (ts/create! :model/Database :name "other-db")+ table (ts/create! :model/Table :name "orders" :db_id (:id db))+ user (ts/create! :model/User :first_name "Tag" :last_name "User" :email "[email protected]")]+ (dotimes [i 3]+ (ts/create! :model/Card+ :name (str "Filler " i)+ :creator_id (:id user)+ :database_id (:id db)+ :table_id (:id table)+ :dataset_query {:type :query+ :database (:id db)+ :query {:source-table (:id table)}})))+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))+ (let [target-id (t2/select-one-fn :id :model/Card :entity_id @target-eid)+ new-tag-name (str "#" target-id "-bh-population-model")+ stored-query #(t2/select-one-fn :dataset_query :model/Card :entity_id @native-eid)+ query (stored-query)]+ (is (some? target-id))+ (is (not= (:id @target1s) target-id)+ "the referenced card must land on a different id for this test to prove anything")+ (is (= (format "SELECT * FROM {{%s}}" new-tag-name)+ (-> query :stages first :native)))+ (is (=? [{:type :card+ :name new-tag-name+ :display-name (u.humanization/name->human-readable-name :simple new-tag-name)+ :card-id target-id}]+ (-> query :stages first :template-tags)))+ (testing "re-importing over the existing card (the update path) repairs the same way"+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))+ (is (= query (stored-query))))))))))+(deftest load-action-test(let [serialized (atom nil)eid (u/generate-nano-id)]diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.cljindex 3acb93d70cd..ebae014236e 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.clj@@ -74,14 +74,24 @@(map (partial strip-base-path dir))(into (sorted-set))))+(def ^:private slug-id-prefix-re+ #"#\d+-")++(defn- replace-entropy+ [s]+ ;; Template tag slugs have the form `#1-my-card-name`, where `1` is the record ID. Record IDs depend on+ ;; import order which is non-deterministic. Replace them with a deterministic placeholder.+ (str/replace s slug-id-prefix-re "#<some-id>-"))+(defn read-yaml"Reads a YAML file and returns Clojure data, with ignored fields removed."[file](walk/postwalk(fn [x]- (if-not (map? x)- x- (reduce dissoc x ignored-fields)))+ (cond+ (map? x) (reduce dissoc x ignored-fields)+ (string? x) (replace-entropy x)+ :else x))(yaml/parse-string (slurp file))))(defn non-empty-diff [diff]diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljcindex bac55cb6c82..0d62729cda6 100644--- a/src/metabase/lib/core.cljc+++ b/src/metabase/lib/core.cljc@@ -1512,6 +1512,7 @@native-queryraw-native-queryrecognize-template-tags+ replace-template-tag-namesrequired-native-extrasnative-query-card-idsnative-query-snippet-idsdiff --git a/src/metabase/lib/native.cljc b/src/metabase/lib/native.cljcindex f1118799745..53b41e100d5 100644--- a/src/metabase/lib/native.cljc+++ b/src/metabase/lib/native.cljc@@ -20,6 +20,7 @@[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.lib.walk :as lib.walk][metabase.lib.walk.util :as lib.walk.util][metabase.util.humanization :as u.humanization][metabase.util.i18n :as i18n]@@ -351,6 +352,52 @@(lib.metadata/card query card-id))(native-query-card-ids query)))+(defn- regex-escape+ [s]+ (str/replace s #"[.*+?^${}()|\[\]\\]" (fn [c] (str "\\" c))))++(defn- replace-tag-in-text+ [text old-name new-name]+ (str/replace text+ (re-pattern (str "\\{\\{\\s*" (regex-escape old-name) "\\s*\\}\\}"))+ ;; function replacement so a `$` in the new name can't be misread as a match reference+ (constantly (str "{{" new-name "}}"))))++(defn- rename-tag+ "Rename a template tag, replacing its `:display-name` only if it was the humanized default for the+ old name (same rule as [[rename-template-tag]])."+ [{tag-name :name, :keys [display-name], :as tag} new-name]+ (cond-> (assoc tag :name new-name)+ (= display-name (u.humanization/name->human-readable-name :simple tag-name))+ (assoc :display-name (u.humanization/name->human-readable-name :simple new-name))))++(mu/defn replace-template-tag-names :- ::lib.schema/query+ "Apply `renames`, a map of old tag name => new tag name, across the query's native stages: each+ affected tag is renamed (a default display name follows the rename, a customized one is kept) and+ its `{{...}}` references in the raw query text are rewritten to match. Tags whose names collide+ after renaming are collapsed into one; the first occurrence wins."+ [query :- ::lib.schema/query+ renames :- [:map-of :string :string]]+ (if (empty? renames)+ query+ (lib.walk/walk-stages+ query+ (fn [_query _path {stage-tags :template-tags, sql :native, :as stage}]+ (when (and (= (:lib/type stage) :mbql.stage/native)+ (string? sql))+ (let [stage-renames (select-keys renames (map :name stage-tags))]+ (when (seq stage-renames)+ (-> stage+ (update :template-tags (fn [tags]+ (into []+ (comp (map (fn [{tag-name :name, :as tag}]+ (if-let [new-name (get stage-renames tag-name)]+ (rename-tag tag new-name)+ tag)))+ (m/distinct-by :name))+ tags)))+ (update :native #(reduce-kv replace-tag-in-text % stage-renames))))))))))+(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]diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.cljindex e648f0ba586..d7933498634 100644--- a/src/metabase/models/serialization.clj+++ b/src/metabase/models/serialization.clj@@ -1291,12 +1291,38 @@import-mbql-update-refsimport-mbql-update-maps))+(defn- stale-card-tag-rename+ "New name for a card template tag whose `#<id>-slug` name embeds a different id than its (already+ remapped) `:card-id`: the id is swapped, the slug is kept verbatim. Nil when they already agree or+ the name doesn't embed an id."+ [{tag-type :type, :keys [card-id], tag-name :name}]+ (when (and (= tag-type :card) (pos-int? card-id) (string? tag-name))+ (when-let [[_ embedded-id suffix] (re-matches #"#(\d+)(-.*)?" tag-name)]+ (when (not= (parse-long embedded-id) card-id)+ (str "#" card-id suffix)))))++(defn- repair-card-template-tag-names+ "Card template tag names (and the `{{#id-slug}}` refs in the native text) embed the referenced+ card's id, which goes stale when [[import-mbql-map]] remaps `:card-id` to the local card's id.+ Swap the embedded id for the remapped one, leaving the slug as it was exported."+ [x]+ (if (= (:lib/type x) :mbql/query)+ (lib/replace-template-tag-names+ x+ (into {}+ (keep (fn [{tag-name :name, :as tag}]+ (when-let [new-name (stale-card-tag-rename tag)]+ [tag-name new-name])))+ (lib/all-template-tags x)))+ x))+(defn import-mbql"Given an MBQL expression as an EDN structure with portable IDs embedded, convert the IDs back to raw numeric IDs."[x](-> ximport-mbql*- normalize-imported))+ normalize-imported+ repair-card-template-tag-names))(declare ^:private mbql-deps-map)diff --git a/test/metabase/lib/native_test.cljc b/test/metabase/lib/native_test.cljcindex 57bc8f492ec..ef8f2bd40c3 100644--- a/test/metabase/lib/native_test.cljc+++ b/test/metabase/lib/native_test.cljc@@ -859,3 +859,91 @@(is (= #{{:table (meta/id :orders)}}(lib.native/native-query-table-references(table-tag-query meta/metadata-provider {:table-id (meta/id :orders)}))))))++(defn- card-tag-query [sql tag]+ (lib/query meta/metadata-provider+ {:lib/type :mbql/query+ :database (meta/id)+ :stages [{:lib/type :mbql.stage/native+ :native sql+ :template-tags [tag]}]}))++(deftest ^:parallel replace-template-tag-names-test+ (testing "renamed tags get their name, default display name, and {{...}} text rewritten; other tags untouched"+ (let [query (card-tag-query "select * from {{ #133-bh-population-model }} where {{ state }}"+ {:type :card+ :name "#133-bh-population-model"+ :display-name "#133 Bh Population Model"+ :id "5ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :card-id 1206})]+ (is (=? {:stages [{:native "select * from {{#1206-bh-population-model}} where {{ state }}"+ :template-tags [{:type :card+ :name "#1206-bh-population-model"+ :display-name "#1206 Bh Population Model"+ :id "5ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :card-id 1206}]}]}+ (lib.native/replace-template-tag-names+ query+ {"#133-bh-population-model" "#1206-bh-population-model"}))))))++(deftest ^:parallel replace-template-tag-names-noop-test+ (let [query (card-tag-query "select * from {{#133-some-old-slug}}"+ {:type :card+ :name "#133-some-old-slug"+ :display-name "#133 Some Old Slug"+ :id "5ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :card-id 133})]+ (testing "an empty renames map is a no-op"+ (is (= query+ (lib.native/replace-template-tag-names query {}))))+ (testing "renames that match no tag are a no-op"+ (is (= query+ (lib.native/replace-template-tag-names query {"#999-not-here" "#1-nope"}))))))++(deftest ^:parallel replace-template-tag-names-custom-display-name-test+ (testing "a customized display name is preserved through the rename"+ (is (=? {:stages [{:template-tags [{:name "#1206-new-card"+ :display-name "My Custom Label"}]}]}+ (lib.native/replace-template-tag-names+ (card-tag-query "select * from {{#133-old-card}}"+ {:type :card+ :name "#133-old-card"+ :display-name "My Custom Label"+ :id "5ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :card-id 1206})+ {"#133-old-card" "#1206-new-card"})))))++(deftest ^:parallel replace-template-tag-names-optional-block-test+ (testing "tag refs inside [[optional]] blocks are rewritten without disturbing the rest of the text"+ (is (=? {:stages [{:native "select * from x [[ where id in (select id from {{#1206-new-card}}) ]]"}]}+ (lib.native/replace-template-tag-names+ (card-tag-query "select * from x [[ where id in (select id from {{#133-old-card}}) ]]"+ {:type :card+ :name "#133-old-card"+ :display-name "#133 Old Card"+ :id "5ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :card-id 1206})+ {"#133-old-card" "#1206-new-card"})))))++(deftest ^:parallel replace-template-tag-names-collision-test+ (testing "tags renamed onto the same name collapse into one; the first occurrence wins"+ (let [query (lib/query meta/metadata-provider+ {:lib/type :mbql/query+ :database (meta/id)+ :stages [{:lib/type :mbql.stage/native+ :native "select * from {{#133-foo}} a, {{#133-bar}} b"+ :template-tags [{:type :card+ :name "#133-foo"+ :display-name "Foo"+ :id "5ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :card-id 1206}+ {:type :card+ :name "#133-bar"+ :display-name "Bar"+ :id "6ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :card-id 1206}]}]})]+ (is (=? {:stages [{:native "select * from {{#1206-foo}} a, {{#1206-foo}} b"+ :template-tags [{:name "#1206-foo", :display-name "Foo"}]}]}+ (lib.native/replace-template-tag-names+ query+ {"#133-foo" "#1206-foo", "#133-bar" "#1206-foo"}))))))diff --git a/test/metabase/lib_be/models/transforms_test.clj b/test/metabase/lib_be/models/transforms_test.cljindex f2501259d60..deaee1a8762 100644--- a/test/metabase/lib_be/models/transforms_test.clj+++ b/test/metabase/lib_be/models/transforms_test.clj@@ -112,3 +112,52 @@(lib-be/normalize-query {:database 1:type :query:query {:source-table 2}}))))))++(defn- write-read-query [query]+ ((:out lib-be/transform-query) ((:in lib-be/transform-query) query)))++(defn- native-card-tag-query [tag-name tag]+ {:database (mt/id)+ :type :native+ :native {:query (str "SELECT * FROM {{" tag-name "}}")+ :template-tags {tag-name tag}}})++(deftest ^:parallel card-template-tag-names-preserved-on-save-test+ (testing "card tag names are stored verbatim on save, whatever id or slug they embed; the FE owns+ tag naming, and stale ids are only repaired during serdes import (#77516)"+ (let [tag-name "#999-some_arbitrary-slug"]+ (is (=? {:stages [{:native (str "SELECT * FROM {{" tag-name "}}")+ :template-tags [{:type :card+ :name tag-name+ :display-name "Anything At All"+ :card-id 123}]}]}+ (write-read-query+ (native-card-tag-query tag-name+ {:id "5ebf6c2e-d6e2-449e-97b7-7005047928e5"+ :name tag-name+ :display-name "Anything At All"+ :type :card+ :card-id 123})))))))++(deftest ^:parallel duplicate-card-template-tags-preserved-on-save-test+ (testing "two refs to the same card under different tag names save unchanged (#77516)"+ (let [tag-a "#123-foo"+ tag-b "#123-bar"+ sql (str "SELECT 1 FROM {{" tag-a "}} AS a, {{" tag-b "}} AS b")]+ (is (=? {:stages [{:native sql+ :template-tags [{:type :card, :name tag-a, :card-id 123}+ {:type :card, :name tag-b, :card-id 123}]}]}+ (write-read-query+ {:database (mt/id)+ :type :native+ :native {:query sql+ :template-tags {tag-a {:id "cc000001-0000-0000-0000-000000000001"+ :name tag-a+ :display-name "Foo"+ :type :card+ :card-id 123}+ tag-b {:id "cc000002-0000-0000-0000-000000000002"+ :name tag-b+ :display-name "Bar"+ :type :card+ :card-id 123}}}}))))))