Skip to content

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

respect default time dimensions from list of dimensions (#79167)

John Swansoncfd6896c177c
diff --git a/src/metabase/explorations/query_plan/context.clj b/src/metabase/explorations/query_plan/context.clj
index 38b291b997b..cbccfa6c279 100644
--- a/src/metabase/explorations/query_plan/context.clj
+++ b/src/metabase/explorations/query_plan/context.clj
@@ -91,14 +91,14 @@
(let [base-query (try (lib/query mp (:dataset_query card)) (catch Exception _ nil))
appl (applicability dim-by-id tm base-query)
default-temp (when base-query
- (qp.mbql/default-temporal-breakout-col base-query))]
+ (qp.mbql/default-time-dimension-col base-query card))]
{:metric-id (:card_id tm)
:card card
:mp mp
:applicability appl
:default-temporal-breakout-summary (when-let [[_col unit display-name] default-temp]
{:column display-name
- :unit (some-> unit name)})
+ :unit (name unit)})
:segments (segment-blurbs base-query)
:name (:name card)
:description (some-> (:description card) str/trim not-empty)
@@ -187,14 +187,14 @@
...]}
The underlying Card is hydrated with the columns the variant builders need
- (`:id :name :description :database_id :dataset_query :card_schema`), once per Card even
- when it appears in several blocks."
+ (`:id :name :description :database_id :dataset_query :card_schema :dimensions
+ :dimension_mappings`), once per Card even when it appears in several blocks."
[blocks]
(let [card-ids (distinct (mapcat #(map :card_id (:metrics %)) blocks))
cards (when (seq card-ids)
(t2/select-pk->fn identity
[:model/Card :id :name :description :database_id
- :dataset_query :card_schema]
+ :dataset_query :card_schema :dimensions :dimension_mappings]
:id [:in card-ids]))
mp-by-db (memoize (fn [db-id] (lib-be/application-database-metadata-provider db-id)))]
{:blocks (mapv #(block-context % cards mp-by-db) blocks)}))
diff --git a/src/metabase/explorations/query_plan/mbql.clj b/src/metabase/explorations/query_plan/mbql.clj
index 6e2a918f858..d2a0ceba811 100644
--- a/src/metabase/explorations/query_plan/mbql.clj
+++ b/src/metabase/explorations/query_plan/mbql.clj
@@ -4,7 +4,6 @@
(:require
[metabase.lib-metric.core :as lib-metric]
[metabase.lib.core :as lib]
- [metabase.lib.types.isa :as lib.types.isa]
[metabase.metrics.core :as metrics]
[metabase.util.malli.registry :as mr]))
@@ -122,31 +121,28 @@
(when (mr/validate :mbql.clause/field ref-clause)
(lib/field-ref-id ref-clause))))
-(defn default-temporal-breakout-col
- "If `base-query` carries a temporal breakout (the metric's default temporal
- dimension, e.g. `created_at` bucketed by `:month`), resolve the breakout against
- the query's visible columns and return `[col raw-unit display-name]`. Returns
- `nil` if no temporal breakout exists, the column can't be resolved, or column
- resolution throws. The raw unit may be `nil` if the metric breakout was unbucketed.
-
- Prefer this over [[extract-default-temporal-breakout-col]] when the caller already
- holds the Lib query — building one is expensive."
- [base-query]
- (try
- (let [cols (lib/visible-columns base-query)]
- (some (fn [bo]
- (when-let [col (lib/find-matching-column bo cols)]
- (when (lib.types.isa/temporal? col)
- [col (lib/raw-temporal-bucket bo) (lib/display-name base-query col)])))
- (lib/breakouts base-query)))
- (catch Exception _ nil)))
-
-(defn extract-default-temporal-breakout-col
- "[[default-temporal-breakout-col]] for callers holding a metric Card's `dataset_query`
- rather than a built Lib query. Returns `nil` when the query can't be normalized."
- [mp card-dataset-query]
+(defn default-time-dimension-col
+ "Resolve the metric `card`'s curated default dimension to `[col unit display-name]`,
+ where `col` is the dimension's target resolved against `base-query`'s visible
+ columns, `unit` is the dimension's `:default-temporal-unit` (`:month` when unset),
+ and `display-name` is the dimension's curated display name.
+
+ The default dimension is used only when it is active (not orphaned) and its type
+ carries a date component (`:type/HasDate` — covers `:type/Date` and `:type/DateTime`;
+ bare `:type/Time` dims don't qualify). Curation is authoritative: when the
+ default dimension is missing or doesn't qualify, returns `nil` rather than
+ falling back to the card's `dataset_query` breakouts."
+ [base-query card]
(try
- (default-temporal-breakout-col (lib/query mp card-dataset-query))
+ (when-let [dim (some #(when (:default %) %) (:dimensions card))]
+ (when (and (not= :status/orphaned (:status dim))
+ (dim-type-isa? dim :type/HasDate))
+ (when-let [target (find-dimension-target (:id dim) (:dimension_mappings card))]
+ (when-let [col (lib/find-matching-column (normalize-target-ref target)
+ (lib/visible-columns base-query))]
+ [col
+ (or (:default-temporal-unit dim) :month)
+ (or (:display-name dim) (lib/display-name base-query col))]))))
(catch Exception _ nil)))
(defn dim-fingerprint-distinct-count
diff --git a/src/metabase/explorations/query_plan/mechanical.clj b/src/metabase/explorations/query_plan/mechanical.clj
index 63056f1418c..05c1ae4ea17 100644
--- a/src/metabase/explorations/query_plan/mechanical.clj
+++ b/src/metabase/explorations/query_plan/mechanical.clj
@@ -55,7 +55,7 @@
"Eligibility for the `time-facet` variant on this (metric, dim) pair:
1. Dim is non-temporal (temporal dims belong to the `temporal-pattern-*`
variants, not stacked-by-category line series).
- 2. Metric Card carries a temporal breakout in its dataset_query
+ 2. Metric Card's curated default dimension is temporal with a date component
(`metric :default-temporal-breakout-summary` set by `metric-and-dim-context`).
3. The dim's *effective* cardinality — bin count for auto-binned numerics,
raw distinct-count otherwise — is known and ≤ `time-facet-max-cardinality`.
diff --git a/src/metabase/explorations/query_plan/variants.clj b/src/metabase/explorations/query_plan/variants.clj
index 83e59383207..e9f1dcc381d 100644
--- a/src/metabase/explorations/query_plan/variants.clj
+++ b/src/metabase/explorations/query_plan/variants.clj
@@ -335,11 +335,10 @@
;; per-bin line series (e.g. 8 lines for an auto-binned `Subtotal`)
;; rather than one line per raw value.
dim-breakout (qp.mbql/apply-default-bucket base-query ref-clause dim)]
- (when-let [[temporal-col raw-unit] (qp.mbql/extract-default-temporal-breakout-col
- mp (:dataset_query card))]
+ (when-let [[temporal-col unit] (qp.mbql/default-time-dimension-col base-query card)]
;; Row cap is defense-in-depth: the planner's `:max-cardinality 20` gate
;; is fingerprint-based and can be stale (claims low, reality high).
- (let [temporal-breakout (lib/with-temporal-bucket temporal-col (or raw-unit :month))]
+ (let [temporal-breakout (lib/with-temporal-bucket temporal-col unit)]
(-> base-query
(lib/breakout dim-breakout)
(lib/breakout temporal-breakout)
@@ -383,16 +382,15 @@
[_ {:keys [mp card target segment params] :as ctx}]
(let [v (nth (cached-discovery ctx) (:value_index params) nil)]
(when (some? v)
- (when-let [[temporal-col raw-unit] (qp.mbql/extract-default-temporal-breakout-col
- mp (:dataset_query card))]
- (let [base-query (-> (lib/query mp (:dataset_query card)) lib/remove-all-breakouts)
- [ref-clause field-ref] (resolve-target base-query target)
- temporal-breakout (lib/with-temporal-bucket temporal-col (or raw-unit :month))]
- (-> base-query
- (lib/filter (lib/= (or field-ref ref-clause) v))
- (lib/breakout temporal-breakout)
- (maybe-segment-filtered segment)
- (order-by-temporal-and-limit temporal-breakout default-max-rows)))))))
+ (let [base-query (-> (lib/query mp (:dataset_query card)) lib/remove-all-breakouts)]
+ (when-let [[temporal-col unit] (qp.mbql/default-time-dimension-col base-query card)]
+ (let [[ref-clause field-ref] (resolve-target base-query target)
+ temporal-breakout (lib/with-temporal-bucket temporal-col unit)]
+ (-> base-query
+ (lib/filter (lib/= (or field-ref ref-clause) v))
+ (lib/breakout temporal-breakout)
+ (maybe-segment-filtered segment)
+ (order-by-temporal-and-limit temporal-breakout default-max-rows))))))))
;; ---------------------------------------------------------------------------
;; pin-other-last — runner-side result post-processing.
diff --git a/test/metabase/explorations/api_test.clj b/test/metabase/explorations/api_test.clj
index cf4aa694a32..6fd8ae4abc4 100644
--- a/test/metabase/explorations/api_test.clj
+++ b/test/metabase/explorations/api_test.clj
@@ -688,12 +688,24 @@
"the users-table segment doesn't apply, so no segment fan-out")))))
(defn- products-monthly-metric-card
- "Metric Card with a default `:month` temporal breakout on `products.created_at`. Used to
- exercise the time-facet variant, which fires only when the metric carries a temporal breakout."
+ "Metric Card with a curated default `:month` time dimension on `products.created_at` (and the
+ matching temporal breakout in its query). Used to exercise the time-facet variant, which fires
+ only when the metric's curated default dimension is temporal — the query breakout alone is not
+ enough."
[user-id]
- {:type :metric
- :creator_id user-id
- :dataset_query (lib/->legacy-MBQL (let [mp (mt/metadata-provider)] (-> (lib/query mp (lib.metadata/table mp (mt/id :products))) (lib/aggregate (lib/count)) (lib/breakout (lib/with-temporal-bucket (lib.metadata/field mp (mt/id :products :created_at)) :month)))))})
+ {:type :metric
+ :creator_id user-id
+ :dataset_query (lib/->legacy-MBQL (let [mp (mt/metadata-provider)] (-> (lib/query mp (lib.metadata/table mp (mt/id :products))) (lib/aggregate (lib/count)) (lib/breakout (lib/with-temporal-bucket (lib.metadata/field mp (mt/id :products :created_at)) :month)))))
+ :dimensions [{:id (duid "prod-created")
+ :display-name "Created At"
+ :effective-type :type/DateTime
+ :status :status/active
+ :default true
+ :default-temporal-unit :month}]
+ :dimension_mappings [{:type :table
+ :table-id (mt/id :products)
+ :dimension-id (duid "prod-created")
+ :target [:field {} (mt/id :products :created_at)]}]})
(defn- query-types
[queries]
diff --git a/test/metabase/explorations/query_plan/context_test.clj b/test/metabase/explorations/query_plan/context_test.clj
index d740e7f03a1..86a4cac5473 100644
--- a/test/metabase/explorations/query_plan/context_test.clj
+++ b/test/metabase/explorations/query_plan/context_test.clj
@@ -134,6 +134,57 @@
(is (= [] (:segments m)))
(is (= #{"d1"} (set (keys (:applicability m)))))))))
+(deftest metric-context-default-time-dimension-summary-test
+ (testing ":default-temporal-breakout-summary reflects the curated default dimension —
+ its display name and :default-temporal-unit"
+ (let [dim-id (str (random-uuid))]
+ (mt/with-temp [:model/Card metric {:type :metric
+ :name "Orders"
+ :dataset_query (orders-count-metric-query)
+ :dimensions [{:id dim-id
+ :display-name "Order Date"
+ :effective-type :type/DateTimeWithLocalTZ
+ :status :status/active
+ :default true
+ :default-temporal-unit :week}]
+ :dimension_mappings [{:type :table
+ :table-id (mt/id :orders)
+ :dimension-id dim-id
+ :target [:field {} (mt/id :orders :created_at)]}]}]
+ (let [m (-> (qp.context/metric-and-dim-context
+ [{:id 1 :metrics [{:card_id (:id metric)}] :dimensions []}])
+ :blocks first :metrics first)]
+ (is (= {:column "Order Date" :unit "week"}
+ (:default-temporal-breakout-summary m))))))))
+
+(deftest metric-context-no-fallback-to-query-breakout-test
+ (testing "a curated non-temporal default dimension yields no temporal summary,
+ even when the metric's dataset_query still carries a temporal breakout"
+ (let [mp (mt/metadata-provider)
+ query (lib/->legacy-MBQL
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket
+ (lib.metadata/field mp (mt/id :orders :created_at))
+ :month))))
+ dim-id (str (random-uuid))]
+ (mt/with-temp [:model/Card metric {:type :metric
+ :name "Orders"
+ :dataset_query query
+ :dimensions [{:id dim-id
+ :display-name "Quantity"
+ :effective-type :type/Integer
+ :status :status/active
+ :default true}]
+ :dimension_mappings [{:type :table
+ :table-id (mt/id :orders)
+ :dimension-id dim-id
+ :target [:field {} (mt/id :orders :quantity)]}]}]
+ (let [m (-> (qp.context/metric-and-dim-context
+ [{:id 1 :metrics [{:card_id (:id metric)}] :dimensions []}])
+ :blocks first :metrics first)]
+ (is (nil? (:default-temporal-breakout-summary m))))))))
+
(deftest build-row-context-resolves-from-block-test
(testing "build-row-context resolves the dim target + snapshot from the row's page's block (not per-thread tables)"
(mt/with-temp [:model/Card metric {:type :metric :dataset_query (count-metric-query)}
diff --git a/test/metabase/explorations/query_plan/mbql_test.clj b/test/metabase/explorations/query_plan/mbql_test.clj
index a1b601eaf9a..cfe0cdda6fd 100644
--- a/test/metabase/explorations/query_plan/mbql_test.clj
+++ b/test/metabase/explorations/query_plan/mbql_test.clj
@@ -1,7 +1,9 @@
(ns metabase.explorations.query-plan.mbql-test
(:require
[clojure.test :refer [are deftest is testing]]
- [metabase.explorations.query-plan.mbql :as qp.mbql]))
+ [metabase.explorations.query-plan.mbql :as qp.mbql]
+ [metabase.lib.core :as lib]
+ [metabase.lib.test-metadata :as meta]))
(deftest ^:parallel target-field-id-test
(testing "an id-based :field ref yields its Field id"
@@ -25,3 +27,84 @@
(is (= [:expression "Foo"]
(let [[tag _opts nm] (qp.mbql/normalize-target-ref ["expression" "Foo"])]
[tag nm])))))
+
+(def ^:private default-created-at-dim
+ {:id "d-created-at"
+ :display-name "Order Date"
+ :effective-type :type/DateTimeWithLocalTZ
+ :status :status/active
+ :default true})
+
+(defn- card-with-default-dim
+ [dim & {:keys [mappings]}]
+ {:dimensions [dim]
+ :dimension_mappings (or mappings
+ [{:dimension-id (:id dim)
+ :target [:field {} (meta/id :orders :created-at)]}])})
+
+(defn- orders-count-query []
+ (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (lib/count))))
+
+(deftest ^:parallel default-time-dimension-col-test
+ (let [q (orders-count-query)]
+ (testing "the curated default temporal dim resolves to [col unit display-name]"
+ (let [[col unit display-name]
+ (qp.mbql/default-time-dimension-col q (card-with-default-dim default-created-at-dim))]
+ (is (= (meta/id :orders :created-at) (:id col)))
+ (is (= :month unit))
+ (is (= "Order Date" display-name))))
+ (testing "the dim's curated :default-temporal-unit wins over the :month fallback"
+ (let [[_col unit] (qp.mbql/default-time-dimension-col
+ q
+ (card-with-default-dim
+ (assoc default-created-at-dim :default-temporal-unit :week)))]
+ (is (= :week unit))))
+ (testing "a pure :type/Date dim qualifies — a date component is what matters"
+ (let [[col unit] (qp.mbql/default-time-dimension-col
+ q
+ (card-with-default-dim
+ (assoc default-created-at-dim :effective-type :type/Date)))]
+ (is (some? col))
+ (is (= :month unit))))))
+
+(deftest ^:parallel default-time-dimension-col-disqualified-test
+ (let [q (orders-count-query)]
+ (testing "a non-temporal default dim yields nil"
+ (is (nil? (qp.mbql/default-time-dimension-col
+ q
+ (card-with-default-dim
+ {:id "d-category"
+ :display-name "Category"
+ :effective-type :type/Text
+ :status :status/active
+ :default true}
+ :mappings [{:dimension-id "d-category"
+ :target [:field
+ {:source-field (meta/id :orders :product-id)}
+ (meta/id :products :category)]}])))))
+ (testing "a bare :type/Time default dim yields nil — no date component"
+ (is (nil? (qp.mbql/default-time-dimension-col
+ q
+ (card-with-default-dim
+ (assoc default-created-at-dim :effective-type :type/Time))))))
+ (testing "an orphaned default dim yields nil"
+ (is (nil? (qp.mbql/default-time-dimension-col
+ q
+ (card-with-default-dim
+ (assoc default-created-at-dim :status :status/orphaned))))))
+ (testing "no dim marked default yields nil"
+ (is (nil? (qp.mbql/default-time-dimension-col
+ q
+ (card-with-default-dim (dissoc default-created-at-dim :default))))))
+ (testing "a default dim with no mapping yields nil"
+ (is (nil? (qp.mbql/default-time-dimension-col
+ q
+ (assoc (card-with-default-dim default-created-at-dim)
+ :dimension_mappings [])))))
+ (testing "no fallback to dataset_query breakouts: a temporal breakout alone is ignored"
+ (is (nil? (qp.mbql/default-time-dimension-col
+ (lib/breakout q (lib/with-temporal-bucket
+ (meta/field-metadata :orders :created-at)
+ :month))
+ {:dimensions [] :dimension_mappings []}))))))
diff --git a/test/metabase/explorations/query_plan/variants_test.clj b/test/metabase/explorations/query_plan/variants_test.clj
index 896a0bd7ae4..a801162aaed 100644
--- a/test/metabase/explorations/query_plan/variants_test.clj
+++ b/test/metabase/explorations/query_plan/variants_test.clj
@@ -60,19 +60,19 @@
(lib.metadata/table (mt/metadata-provider) (mt/id :orders)))
(lib/aggregate (lib/count))))})
-(defn- orders-count-by-month-card
- "Count metric on ORDERS broken out by CREATED_AT month — carries the temporal
- breakout that `time-facet` and `per-value-time-series` resolve their time
- axis from."
+(defn- orders-count-with-default-time-dim-card
+ "Count metric on ORDERS with a curated default CREATED_AT dimension — the
+ curated default that `time-facet` and `per-value-time-series` resolve their
+ time axis from."
[card-id]
- (let [mp (mt/metadata-provider)]
- {:id card-id
- :dataset_query (lib/->legacy-MBQL
- (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
- (lib/aggregate (lib/count))
- (lib/breakout (lib/with-temporal-bucket
- (lib.metadata/field mp (mt/id :orders :created_at))
- :month))))}))
+ (-> (orders-count-card card-id)
+ (assoc :dimensions [{:id "d-created-at"
+ :display-name "Created At"
+ :effective-type :type/DateTimeWithLocalTZ
+ :status :status/active
+ :default true}]
+ :dimension_mappings [{:dimension-id "d-created-at"
+ :target [:field (mt/id :orders :created_at) nil]}])))
(def ^:private created-at-dim
{:dimension-id "d-created-at"
@@ -145,7 +145,7 @@
(testing "time-facet orders by date desc then metric desc,
so a fired cap keeps the most recent months across all dim values"
(let [ctx {:mp (mt/metadata-provider)
- :card (orders-count-by-month-card 9000005)
+ :card (orders-count-with-default-time-dim-card 9000005)
:target (orders-category-target)
:dim category-dim
:segment nil
@@ -171,7 +171,7 @@
(deftest per-value-time-series-cap-test
(testing "per-value-time-series carries a date-desc row cap (it previously had none)"
(let [ctx {:mp (mt/metadata-provider)
- :card (orders-count-by-month-card 9000006)
+ :card (orders-count-with-default-time-dim-card 9000006)
:target (orders-category-target)
:dim category-dim
:segment nil