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
Metrics: Preserve the `:default` dimensions from before curation (#82596)
Braden Shepherdson2389bc777b0e
diff --git a/src/metabase/lib_metric/dimension.cljc b/src/metabase/lib_metric/dimension.cljcindex b71d163401a..e63715919a8 100644--- a/src/metabase/lib_metric/dimension.cljc+++ b/src/metabase/lib_metric/dimension.cljc@@ -22,12 +22,13 @@foreign table, so the same field id is reachable via different `:source-field` paths. Keying mapsby field id alone therefore collides — always key by this instead.- It drops only per-instance/derived opts (`:lib/uuid`, `:effective-type`, `:base-type`) and KEEPS+ It drops only per-instance/derived opts (`:lib/uuid`, `:effective-type`, `:base-type`, and the+ `:lib/transformation-added-base-type` bookkeeping flag that legacy-MBQL conversion stamps on a ref) and KEEPSeverything identity-relevant: the id, the `:source-field`/`:join-alias` that identifies the FK orjoin, and any `:binning`/`:temporal-unit`."[[clause-type opts id-or-name]][clause-type- (dissoc opts :lib/uuid :effective-type :base-type)+ (dissoc opts :lib/uuid :effective-type :base-type :lib/transformation-added-base-type)id-or-name])(defn targets-equal?diff --git a/src/metabase/metrics/core.clj b/src/metabase/metrics/core.cljindex a8fc888f748..81db52112d0 100644--- a/src/metabase/metrics/core.clj+++ b/src/metabase/metrics/core.clj@@ -3,6 +3,7 @@Contains persistence multimethod and orchestration logic."(:require[clojure.string :as str]+ [medley.core :as m][metabase.lib-be.core :as lib-be][metabase.lib-metric.core :as lib-metric][metabase.lib.core :as lib]@@ -132,20 +133,67 @@(or (:display-name dimension) (:name dimension))))dimension))+(defn- breakout-default-match+ "Returns `{:dimension-id ..., :breakout ...}` for the first of the `breakouts` that is mapped to a dimension.++ The matching ignores the temporal bucketing or binning of the breakouts, since the dimension mappings don't+ set those options. **However**, note that the *original* breakout is returned, so it still has its temporal unit+ and binning attached (if any)."+ [dimension-mappings breakouts]+ (let [key->dimension-id (into {} (map (juxt #(-> % :target lib-metric/field-ref->key)+ :dimension-id))+ dimension-mappings)]+ (some (fn [breakout]+ (when-let [dimension-id (-> breakout+ (lib/with-temporal-bucket nil)+ (lib/with-binning nil)+ lib-metric/field-ref->key+ key->dimension-id)]+ {:dimension-id dimension-id+ :breakout breakout}))+ breakouts)))++(defn- recover-pre-curation-default-dimension*+ "Recover the `:default` dimension for a pre-curation metric. The default used to be the dimension mapped to+ the same column as the first breakout on the query. That breakout is passed as `the-breakout`, and this function+ works backwards to figure out which dimension is mapped to that breakout column.++ Returns `dimensions` (the seq of dimensions on this metric) with the `:default` marked accordingly. Returns the+ `dimensions` unchanged if there is no breakout, or the first breakout was not mapped to a dimension.++ **Precondition:** None of the `dimensions` currently has a `:default`."+ [dimensions dimension-mappings query]+ (if-let [{:keys [dimension-id breakout]} (breakout-default-match dimension-mappings (lib/breakouts query))]+ (let [{:keys [effective-type]} (m/find-first #(= dimension-id (:id %)) dimensions)+ unit (lib/raw-temporal-bucket breakout)+ dimensions (lib-metric/set-default-dimension dimensions dimension-id)]+ (if (lib-metric/valid-temporal-unit-for-type? effective-type unit)+ (:dimensions (lib-metric/update-dimension dimensions dimension-mappings dimension-id+ {:default-temporal-unit unit}))+ dimensions))+ dimensions))+(defn compute-full-dimension-set- "Compute the FULL dimension set for a metric's `query` — its own-table columns PLUS every+ "Compute the FULL dimension set for a pre-curation metric's `query` — its own-table columns PLUS everyimplicitly-joined (FK-reachable) column — in the persisted `{:dimensions ... :dimension-mappings ...}`shape (or `nil` when `query` is blank).- Unlike the seeded default (own-table and explicitly-joined columns only), this includes every- FK-reachable column."+ **Precondition:** This is only meant to be called on a metric from before `:card_schema` 24 which has no+ `:dimensions` set at all. This treats the query as SoT and would overwrite any existing `:dimensions`.+ See [[recover-pre-curation-default-dimension]] in that case.++ A newly created post-curation metric gets its own-table and explicitly joined columns as dimensions.+ In contrast, this function preserves the pre-curation behaviour, and returns every implicitly joinable+ column."[query](when (seq query)- (let [computed-pairs (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) query)+ (let [mp (lib-metric/metadata-provider)+ computed-pairs (lib-metric/compute-dimension-pairs mp query){:keys [dimensions dimension-mappings]}- (lib-metric/reconcile-dimensions-and-mappings computed-pairs nil nil)- dimensions (mapv table-prefixed-dimension dimensions)]- {:dimensions (lib-metric/extract-persisted-dimensions dimensions)+ (lib-metric/reconcile-dimensions-and-mappings computed-pairs nil nil)]+ {:dimensions (-> (mapv table-prefixed-dimension dimensions)+ lib-metric/extract-persisted-dimensions+ (recover-pre-curation-default-dimension* dimension-mappings (lib/query mp query))):dimension-mappings dimension-mappings})))(defn modernize-pre-curation-dimensions@@ -156,6 +204,21 @@[dimensions](mapv table-prefixed-dimension dimensions))+(defn recover-pre-curation-default-dimension+ "Prior to the Metric Dimensions project that shipped in 64, the `:dimensions` were automatically populated and+ could not be edited. The *default* dimension was set implicitly as the single *breakout* on the metric card's+ `:dataset_query`.++ This function will modernize a metric card from before 64 into the 64+ style.++ **Code Health: Single-use.** This is intended to be called only from the `:card_schema` upgrade to version 24."+ [dimensions dimension-mappings query]+ (if (or (empty? query)+ (some :default dimensions))+ dimensions+ (recover-pre-curation-default-dimension* dimensions dimension-mappings+ (lib/query (lib-metric/metadata-provider) query))))+(defn- metric-seed-pairs"The computed pairs a v2 metric seeds from: the entity's own columns and explicit query joins,leaving implicitly-joinable FK columns out."diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 3bce26de00d..7b3f37719f8 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -685,24 +685,31 @@;; Curated metric dimensions. New metrics seed their own-table columns only, with joined/FK;; columns available to add on demand. But metrics created before curated dimensions shipped implicitly;; exposed EVERY breakoutable column (own-table + implicitly-joined), and existing dashboard filters may-;; be mapped to those joined columns. Modernize such a metric on read by backfilling the full-;; implicitly-joined dimension set, so every existing mapping still corresponds to a live dimension.-;; Only un-curated metrics (`:dimensions` still nil) are touched; once a metric is curated (any write),-;; its `card_schema` is bumped to current and this upgrade no longer runs, so removals stay sticky.+;; be mapped to those joined columns. The default dimension was also expressed as a breakout on the metric's+;; query, rather than the `:default` flag in the `:dimensions`.+;; This upgrade modernizes a metric card to have properly constructed `:dimensions`, preserving the legacy+;; behaviour of including all breakoutable columns, and setting the `:default` accordingly.(defmethod upgrade-card-schema-to 24- [card _schema-version]+ [{:keys [dataset_query dimensions] :as card} _schema-version](cond(not= :metric (keyword (:type card))) card ; Ignore non-:metric cards- (empty? (:dataset_query card)) card ; And those without real queries-- ;; If the `:dimensions` are populated, update their (pre-curation) representation to the current form.- (:dimensions card) (update card :dimensions metrics/modernize-pre-curation-dimensions)-- ;; If the `:dimensions` are unset, populate them with the present representation but with pre-curation semantics:- ;; all implicitly joinable columns become dimensions, not just "available" dimensions.+ (empty? dataset_query) card ; And those without real queries++ ;; Metric with `:dimensions` not populated at all, so generate them.+ ;; We generate the legacy, "full" dimensions, selecting all breakoutable columns as a dimension.+ ;; (In contrast, a newly created metric starts with only its *own* table's columns as dimensions.)+ (nil? dimensions)+ (let [{:keys [dimensions dimension-mappings]} (metrics/compute-full-dimension-set dataset_query)]+ (assoc card :dimensions dimensions :dimension_mappings dimension-mappings))++ ;; Metric with legacy `:dimensions` already set.+ ;; Update their (pre-curation) representation to the current form, then populate the `:default` flag based on+ ;; the breakout in the query.:else- (let [{:keys [dimensions dimension-mappings]} (metrics/compute-full-dimension-set (:dataset_query card))]- (assoc card :dimensions dimensions :dimension_mappings dimension-mappings))))+ (update card :dimensions #(-> %+ metrics/modernize-pre-curation-dimensions+ (metrics/recover-pre-curation-default-dimension (:dimension_mappings card)+ dataset_query)))))(defn- schema-governed-select?"Whether `card` is a Card row SELECTed with any [[card-schema/schema-governed-columns]], and therefore holds adiff --git a/test/metabase/lib_metric/dimension_test.cljc b/test/metabase/lib_metric/dimension_test.cljcindex f6e515cd4fc..4287393640b 100644--- a/test/metabase/lib_metric/dimension_test.cljc+++ b/test/metabase/lib_metric/dimension_test.cljc@@ -65,6 +65,19 @@(lib-metric.dimension/field-ref->key[:field {:lib/uuid "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" :base-type :type/BigInteger} 100])))))+(deftest ^:parallel field-ref->key-ignores-transformation-added-base-type-test+ (testing "the :lib/transformation-added-base-type flag stamped by legacy-MBQL conversion is not part of the key"+ ;; A pre-curation metric's query is stored as legacy MBQL; converting it tags every field ref with this flag,+ ;; which a mapping target built from column metadata never carries. The two must still key the same column.+ (is (= (lib-metric.dimension/field-ref->key+ [:field {:lib/uuid "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" :source-field 1} 100])+ (lib-metric.dimension/field-ref->key+ [:field {:lib/uuid "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"+ :source-field 1+ :base-type :type/Text+ :lib/transformation-added-base-type true}+ 100])))))+(deftest ^:parallel field-ref->key-distinguishes-source-field-test(testing "the SAME field id reached via different FKs (:source-field) yields DISTINCT keys";; This is the bug this function exists to prevent: field ids are not unique within a query whendiff --git a/test/metabase/metrics/core_test.clj b/test/metabase/metrics/core_test.cljindex af6f6dbdfb1..2efeb772b86 100644--- a/test/metabase/metrics/core_test.clj+++ b/test/metabase/metrics/core_test.clj@@ -7,6 +7,7 @@[metabase.lib.metadata :as lib.metadata][metabase.metrics.core :as metrics][metabase.test :as mt]+ [metabase.util.json :as json][toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -353,6 +354,192 @@;; Note: There's no test for "no-op without definition" for measures;; because measures have a NOT NULL constraint on the definition column - they must always have a definition.+(def ^:private uuid-1 "550e8400-e29b-41d4-a716-446655440001")+(def ^:private uuid-2 "550e8400-e29b-41d4-a716-446655440002")++(deftest ^:parallel recover-pre-curation-default-test+ (let [mp (mt/metadata-provider)+ products (lib.metadata/table mp (mt/id :products))+ base-query (-> (lib/query mp products)+ (lib/aggregate (lib/count)))+ get-column (m/index-by :display-name (lib/breakoutable-columns base-query))+ category (get-column "Category")+ created-at (get-column "Created At")+ rating (get-column "Rating")+ created-at-day (lib/with-temporal-bucket created-at :day)+ mappings [{:type :table+ :table-id (mt/id :products)+ :dimension-id uuid-1+ :target (lib/ref category)}+ {:type :table+ :table-id (mt/id :products)+ :dimension-id uuid-2+ :target (lib/ref created-at)}]+ dimensions [{:id uuid-1, :name "col1"}+ {:id uuid-2, :name "col2"}]]+ (testing "marks the dimension mapped to an unbucketed breakout as the sole default"+ (is (= [{:id uuid-1, :name "col1", :default true}+ {:id uuid-2, :name "col2"}]+ (->> (lib/breakout base-query category)+ (metrics/recover-pre-curation-default-dimension dimensions mappings)))))+ (testing "marks the dimension mapped to a bucketed breakout as the sole default"+ (is (= [{:id uuid-1, :name "col1"}+ {:id uuid-2, :name "col2", :default true}]+ (->> (lib/breakout base-query created-at-day)+ (metrics/recover-pre-curation-default-dimension dimensions mappings)))))+ (testing "the first mapped breakout wins when the query has several"+ (is (= [{:id uuid-1, :name "col1"}+ {:id uuid-2, :name "col2", :default true}]+ (-> base-query+ (lib/breakout created-at-day)+ (lib/breakout category)+ (->> (metrics/recover-pre-curation-default-dimension dimensions mappings)))))+ (is (= [{:id uuid-1, :name "col1", :default true}+ {:id uuid-2, :name "col2"}]+ (-> base-query+ (lib/breakout category)+ (lib/breakout created-at-day)+ (->> (metrics/recover-pre-curation-default-dimension dimensions mappings))))))+ (testing "no change to the dimensions"+ (testing "when there are no breakouts"+ (is (= dimensions+ (metrics/recover-pre-curation-default-dimension dimensions mappings base-query))))+ (testing "when no breakouts match the dimensions"+ (is (= dimensions+ (->> (lib/breakout base-query rating)+ (metrics/recover-pre-curation-default-dimension dimensions mappings)))))+ (testing "when there are no mappings"+ (is (= dimensions+ (->> (lib/breakout base-query created-at-day)+ (metrics/recover-pre-curation-default-dimension dimensions []))))))+ (testing "idempotent -- re-running over already-repaired :dimensions is a no-op"+ (let [query (-> base-query+ (lib/breakout category)+ (lib/breakout created-at-day))+ once (metrics/recover-pre-curation-default-dimension dimensions mappings query)+ twice (metrics/recover-pre-curation-default-dimension once mappings query)]+ (is (not= dimensions once))+ (is (not= dimensions twice))+ (is (= once twice))))))++(deftest ^:parallel recover-pre-curation-default-dimension-preserves-temporal-unit-test+ (let [mp (mt/metadata-provider)+ products (lib.metadata/table mp (mt/id :products))+ base-query (-> (lib/query mp products)+ (lib/aggregate (lib/count)))+ get-column (m/index-by :display-name (lib/breakoutable-columns base-query))+ created-at (get-column "Created At")+ mappings [{:type :table+ :table-id (mt/id :products)+ :dimension-id uuid-1+ :target (lib/ref created-at)}]+ dim-plain {:id uuid-1, :name "col1"}+ dim-datetime {:id uuid-1, :name "col1", :effective-type :type/DateTime}+ dim-date {:id uuid-1, :name "col1", :effective-type :type/Date}+ bucket-by (fn [dim unit]+ (let [column (cond-> created-at+ unit (lib/with-temporal-bucket unit))+ query (lib/breakout base-query column)]+ (metrics/recover-pre-curation-default-dimension [dim] mappings query)))]+ (testing "the breakout's bucket is carried over, so the metric keeps the grain it was authored at"+ (doseq [unit [:year :quarter :month :week :day :hour :minute]]+ (is (=? [(assoc dim-datetime+ :default true+ :default-temporal-unit unit)]+ (bucket-by dim-datetime unit))))+ (doseq [unit [:year :quarter :month :week :day]]+ (is (=? [(assoc dim-date+ :default true+ :default-temporal-unit unit)]+ (bucket-by dim-date unit)))))+ (testing "an unbucketed breakout recovers the dimension but sets no unit"+ (is (=? [(assoc dim-datetime :default true)]+ (bucket-by dim-datetime nil))))+ (testing "a unit the dimension's own picker would not offer is dropped rather than persisted"+ (testing "hidden from the picker"+ (is (= [(assoc dim-datetime :default true)]+ (bucket-by dim-datetime :millisecond))))+ (testing "belongs to another temporal type"+ (let [dim-date (assoc dim-plain :effective-type :type/Date)]+ (is (= [(assoc dim-date :default true)]+ (bucket-by dim-date :hour)))))+ (testing "column is not temporal at all"+ (is (= [(assoc dim-plain :default true)]+ (bucket-by dim-plain :year)))))+ (testing "idempotent -- the recovered unit survives a re-run"+ (let [once (bucket-by dim-datetime :year)]+ (is (= [(assoc dim-datetime+ :default true+ :default-temporal-unit :year)]+ once))+ (testing "even if the breakout's unit changes"+ (is (= [(assoc dim-datetime+ :default true+ :default-temporal-unit :year)]+ (bucket-by (first once) :month))))))))++(deftest ^:parallel recover-pre-curation-default-dimension-legacy-mbql-breakout-test+ ;; Pre-curation metrics were mostly authored in legacy MBQL. Converting it tags every field ref with+ ;; `:lib/transformation-added-base-type`, which the dimension mapping targets never carry.+ (let [mp (mt/metadata-provider)+ orders (lib.metadata/table mp (mt/id :orders))+ columns (lib/breakoutable-columns (lib/query mp orders))+ created-at (m/find-first #(= (mt/id :orders :created_at) (:id %)) columns)+ category (m/find-first #(and (= (mt/id :products :category) (:id %))+ (= (mt/id :orders :product_id) (:fk-field-id %)))+ columns)+ mappings [{:type :table, :table-id (mt/id :orders), :dimension-id uuid-1, :target (lib/ref created-at)}+ {:type :table, :table-id (mt/id :products), :dimension-id uuid-2, :target (lib/ref category)}]+ dimensions [{:id uuid-1, :name "col1", :effective-type :type/DateTime}+ {:id uuid-2, :name "col2", :effective-type :type/Text}]+ legacy (fn [breakout]+ (lib/query mp {:database (mt/id)+ :type :query+ :query {:source-table (mt/id :orders)+ :aggregation [[:count]]+ :breakout [breakout]}}))]+ (testing "a bucketed own-table breakout recovers the default and its unit"+ (is (= [(assoc (first dimensions) :default true, :default-temporal-unit :month)+ (second dimensions)]+ (metrics/recover-pre-curation-default-dimension+ dimensions mappings+ (legacy [:field (mt/id :orders :created_at) {:temporal-unit :month}])))))+ (testing "an implicitly-joined breakout recovers the default"+ (is (= [(first dimensions)+ (assoc (second dimensions) :default true)]+ (metrics/recover-pre-curation-default-dimension+ dimensions mappings+ (legacy [:field (mt/id :products :category) {:source-field (mt/id :orders :product_id)}])))))))++(deftest pre-curation-legacy-metric-recovers-default-dimension-on-read-test+ (testing "a pre-curation metric stored as legacy MBQL gets its breakout's dimension as the default on read"+ (mt/with-temp [:model/Card metric {:name "Legacy Metric"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :orders)+ :dataset_query (metric-query)}]+ ;; Raw UPDATE, so the row looks like it was written before curated dimensions existed.+ (t2/query-one {:update :report_card+ :set {:card_schema 23+ :dimensions nil+ :dimension_mappings nil+ :dataset_query (json/encode+ {:database (mt/id)+ :type :query+ :query {:source-table (mt/id :orders)+ :aggregation [[:count]]+ :breakout [[:field (mt/id :orders :created_at)+ {:temporal-unit :month}]]}})}+ :where [:= :id (:id metric)]})+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one :model/Card :id (:id metric))+ default (filter :default dimensions)+ target (some #(when (= (:id (first default)) (:dimension-id %)) (:target %)) dimension_mappings)]+ (is (seq dimensions)+ "The schema upgrade should have backfilled the full dimension set")+ (is (= 1 (count default)))+ (is (= :month (:default-temporal-unit (first default))))+ (is (= (mt/id :orders :created_at) (nth target 2 nil)))))))+;;; ------------------------------------------ Database-wide backfill ------------------------------------------(deftest sync-metric-dimensions-for-database-backfills-empty-test