Skip to content

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

Keep fields when adding aggregations, and ignore them when compiling (#62539)

Williamc1a8102d17cd
diff --git a/src/metabase/lib/util.cljc b/src/metabase/lib/util.cljc
index 121c18f9153..f9f32b27d21 100644
--- a/src/metabase/lib/util.cljc
+++ b/src/metabase/lib/util.cljc
@@ -628,9 +628,7 @@
(update-query-stage
stage-number
(fn [stage]
- (-> stage
- (dissoc :order-by :fields)
- (m/update-existing :joins (fn [joins] (mapv #(dissoc % :fields) joins))))))
+ (dissoc stage :order-by)))
(update :stages #(into [] (take (inc (canonical-stage-index query stage-number))) %)))
new-query)))
diff --git a/src/metabase/query_processor/middleware/drop_fields_in_summaries.clj b/src/metabase/query_processor/middleware/drop_fields_in_summaries.clj
new file mode 100644
index 00000000000..c752bb5d153
--- /dev/null
+++ b/src/metabase/query_processor/middleware/drop_fields_in_summaries.clj
@@ -0,0 +1,12 @@
+(ns metabase.query-processor.middleware.drop-fields-in-summaries
+ (:require
+ [metabase.lib.walk :as lib.walk]))
+
+(defn drop-fields-in-summaries
+ "Drop any :fields clauses in stages that have :aggregations or :breakouts"
+ [query]
+ (letfn [(has-summary? [stage] (or (:aggregation stage)
+ (:breakout stage)))]
+ (lib.walk/walk-stages query (fn [_query _path stage]
+ (cond-> stage
+ (has-summary? stage) (dissoc :fields))))))
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index 0434c97fe87..3d035d0897c 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -21,6 +21,7 @@
[metabase.query-processor.middleware.constraints :as qp.constraints]
[metabase.query-processor.middleware.cumulative-aggregations :as qp.cumulative-aggregations]
[metabase.query-processor.middleware.desugar :as desugar]
+ [metabase.query-processor.middleware.drop-fields-in-summaries :as drop-fields-in-summaries]
[metabase.query-processor.middleware.ensure-joins-use-source-query :as ensure-joins-use-source-query]
[metabase.query-processor.middleware.enterprise :as qp.middleware.enterprise]
[metabase.query-processor.middleware.expand-aggregations :as expand-aggregations]
@@ -131,6 +132,7 @@
(ensure-mbql5 #'qp.constraints/maybe-add-default-userland-constraints)
(ensure-mbql5 #'validate/validate-query)
(ensure-mbql5 #'fetch-source-query/resolve-source-cards)
+ (ensure-mbql5 #'drop-fields-in-summaries/drop-fields-in-summaries)
(ensure-mbql5 #'expand-aggregations/expand-aggregations)
(ensure-mbql5 #'metrics/adjust)
(ensure-mbql5 #'expand-macros/expand-macros)
diff --git a/test/metabase/lib/aggregation_test.cljc b/test/metabase/lib/aggregation_test.cljc
index a93487588bc..ad94394b3b4 100644
--- a/test/metabase/lib/aggregation_test.cljc
+++ b/test/metabase/lib/aggregation_test.cljc
@@ -685,10 +685,10 @@
first-stage (lib.util/query-stage query 0)
first-join (first (lib/joins query 0))]
(is (= 1 (count (:stages query))))
- (is (not (contains? first-stage :fields)))
+ (is (contains? first-stage :fields))
(is (not (contains? first-stage :order-by)))
(is (= 1 (count (lib/joins query 0))))
- (is (not (contains? first-join :fields))))
+ (is (contains? first-join :fields)))
(testing "Already summarized query should be left alone"
(let [query (-> (lib.tu/venues-query)
(lib/breakout (meta/field-metadata :venues :category-id))
@@ -699,6 +699,19 @@
(is (= 2 (count (:stages query))))
(is (contains? first-stage :order-by)))))
+(deftest ^:parallel aggregate-should-preserve-fields
+ (testing "adding and removing an aggregation keeps original fields"
+ (let [orig-query (-> (lib.tu/venues-query)
+ (lib/with-fields [(meta/field-metadata :venues :price)])
+ (lib/join (-> (lib/join-clause (meta/table-metadata :categories)
+ [(lib/=
+ (meta/field-metadata :venues :category-id)
+ (lib/with-join-alias (meta/field-metadata :categories :id) "Cat"))])
+ (lib/with-join-fields [(meta/field-metadata :categories :id)]))))
+ agg-query (lib/aggregate orig-query (lib/count))
+ query (lib/remove-clause agg-query (first (lib/aggregations agg-query)))]
+ (is (= orig-query query)))))
+
(deftest ^:parallel aggregation-with-case-expression-metadata-test
(let [query (-> (lib.tu/venues-query)
(lib/limit 4)
diff --git a/test/metabase/lib/breakout_test.cljc b/test/metabase/lib/breakout_test.cljc
index 3bcf0dee81a..a5498e08d3f 100644
--- a/test/metabase/lib/breakout_test.cljc
+++ b/test/metabase/lib/breakout_test.cljc
@@ -53,10 +53,10 @@
first-stage (lib.util/query-stage query 0)
first-join (first (lib/joins query 0))]
(is (= 1 (count (:stages query))))
- (is (not (contains? first-stage :fields)))
+ (is (contains? first-stage :fields))
(is (not (contains? first-stage :order-by)))
(is (= 1 (count (lib/joins query 0))))
- (is (not (contains? first-join :fields))))
+ (is (contains? first-join :fields)))
(testing "Already summarized query should be left alone"
(let [query (-> (lib.tu/venues-query)
(lib/breakout (meta/field-metadata :venues :category-id))
@@ -67,6 +67,19 @@
(is (= 2 (count (:stages query))))
(is (contains? first-stage :order-by)))))
+(deftest ^:parallel breakout-should-preserve-fields
+ (testing "adding and removing an aggregation keeps original fields"
+ (let [orig-query (-> (lib.tu/venues-query)
+ (lib/with-fields [(meta/field-metadata :venues :price)])
+ (lib/join (-> (lib/join-clause (meta/table-metadata :categories)
+ [(lib/=
+ (meta/field-metadata :venues :category-id)
+ (lib/with-join-alias (meta/field-metadata :categories :id) "Cat"))])
+ (lib/with-join-fields [(meta/field-metadata :categories :id)]))))
+ breakout-query (lib/breakout orig-query (meta/field-metadata :venues :category-id))
+ query (lib/remove-clause breakout-query (first (lib/breakouts breakout-query)))]
+ (is (= orig-query query)))))
+
(deftest ^:parallel breakoutable-columns-test
(let [query (lib.tu/venues-query)]
(testing (lib.util/format "Query =\n%s" (u/pprint-to-str query))
diff --git a/test/metabase/lib/join_test.cljc b/test/metabase/lib/join_test.cljc
index 5c80c613fa0..acf60afc319 100644
--- a/test/metabase/lib/join_test.cljc
+++ b/test/metabase/lib/join_test.cljc
@@ -1570,16 +1570,6 @@
(deftest ^:parallel join-and-summary-ordering-test
(let [has-fields? #(-> % lib/joins first (contains? :fields))]
- (testing "adding an aggregation or breakout removes :fields from any joins"
- (let [base (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
- (lib/join (meta/table-metadata :products)))
- aggregated (lib/aggregate base (lib/count))
- broken-out (lib/breakout base (lib/with-temporal-bucket (meta/field-metadata :orders :created-at) :month))]
- (is (=? [{:fields :all}]
- (lib/joins base)))
- (is (has-fields? base))
- (is (not (has-fields? aggregated)))
- (is (not (has-fields? broken-out)))))
(testing "a join added with an existing breakout has no :fields clause"
(is (not (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
(lib/breakout (lib/with-temporal-bucket (meta/field-metadata :orders :created-at) :month))
diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.clj
index d8d156d6e0f..6f9a33425ea 100644
--- a/test/metabase/query_processor/api_test.clj
+++ b/test/metabase/query_processor/api_test.clj
@@ -685,43 +685,6 @@
(is (= ["MD" "Twitter" nil 4 16 62] (nth rows 1000)))
(is (= [nil nil nil 7 18760 69540] (last rows)))))))))
-;; historical test: don't do this going forward
-#_{:clj-kondo/ignore [:metabase/disallow-hardcoded-driver-names-in-tests]}
-(deftest ^:parallel pivot-dataset-with-added-expression-test
- (mt/test-drivers (qp.pivot.test-util/applicable-drivers)
- (mt/dataset test-data
- (testing "POST /api/dataset/pivot"
- ;; this only works on a handful of databases -- most of them don't allow you to ask for a Field that isn't in
- ;; the GROUP BY expression
- (when (#{:mongo :h2 :sqlite} driver/*driver*)
- (testing "with an added expression"
- ;; the added expression is coming back in this query because it is explicitly included in `:fields` -- see
- ;; comments on [[metabase.query-processor.pivot-test/pivots-should-not-return-expressions-test]].
- (let [query (-> (qp.pivot.test-util/pivot-query)
- (assoc-in [:query :fields] [[:expression "test-expr"]])
- (assoc-in [:query :expressions] {:test-expr [:ltrim "wheeee"]}))
- result (mt/user-http-request :crowberto :post 202 "dataset/pivot" query)
- rows (mt/rows result)]
- (is (= 1144 (:row_count result)))
- (is (= 1144 (count rows)))
- (let [cols (mt/cols result)]
- (is (= ["User → State"
- "User → Source"
- "Product → Category"
- "pivot-grouping"
- "Count"
- "Sum of Quantity"
- "test-expr"]
- (map :display_name cols)))
- (is (=? {:base_type "type/Integer"
- :effective_type "type/Integer"
- :name "pivot-grouping"
- :display_name "pivot-grouping"
- :field_ref ["expression" "pivot-grouping"]
- :source "breakout"}
- (nth cols 3))))
- (is (= [nil nil nil 7 18760 69540 "wheeee"] (last rows))))))))))
-
(deftest ^:parallel pivot-dataset-row-totals-disabled-test
(mt/test-drivers (qp.pivot.test-util/applicable-drivers)
(mt/dataset test-data
diff --git a/test/metabase/query_processor/pivot_test.clj b/test/metabase/query_processor/pivot_test.clj
index 5afadced365..d9806a3b73c 100644
--- a/test/metabase/query_processor/pivot_test.clj
+++ b/test/metabase/query_processor/pivot_test.clj
@@ -498,30 +498,24 @@
(deftest ^:parallel pivots-should-not-return-expressions-test-2
(mt/dataset test-data
- (let [query (assoc (mt/mbql-query orders
- {:aggregation [[:count]]
- :breakout [$user_id->people.source $product_id->products.category]})
- :pivot-rows [0]
- :pivot-cols [1])]
- (testing "If the expression is *explicitly* included in `:fields`, then return it, I guess"
- ;; I'm not sure this behavior makes sense -- it seems liable to result in a query the FE can't handle
- ;; correctly, like #14604. The difference here is that #14064 was including expressions that weren't in
- ;; `:fields` at all, which was a clear bug -- while returning expressions that are referenced in `:fields` is
- ;; how the QP normally works in non-pivot-mode.
- ;;
- ;; I do not think there are any situations where the frontend actually explicitly specifies `:fields` in a
- ;; pivot query, so we can revisit this behavior at a later date if needed.
- (let [results (qp.pivot/run-pivot-query (-> query
- (assoc-in [:query :fields] [[:expression "test-expr"]])
- (assoc-in [:query :expressions] {:test-expr [:ltrim "wheeee"]})))]
+ (let [query (->> (assoc (mt/mbql-query orders
+ {:aggregation [[:count]]
+ :breakout [$user_id->people.source $product_id->products.category]})
+ :pivot-rows [0]
+ :pivot-cols [1])
+ (lib/query (mt/metadata-provider)))]
+ (testing "If the expression is *explicitly* included in `:fields`, we still shouldn't see it"
+ ;; In general, if an aggregation has :fields set, those are "if we ever remove this aggregation, we should use
+ ;; these fields again", not "these fields should be added to the aggregation query". As a result, if fields
+ ;; are set here, we shouldn't see them.
+ (let [results (qp.pivot/run-pivot-query (lib/expression query "test-expr" (lib/ltrim "wheeee")))]
(is (= ["User → Source"
"Product → Category"
"pivot-grouping"
- "Count"
- "test-expr"]
+ "Count"]
(map :display_name (mt/cols results))))
(testing "expression value should get returned"
- (is (= ["Affiliate" "Doohickey" 0 783 "wheeee"]
+ (is (= ["Affiliate" "Doohickey" 0 783]
(mt/first-row results)))))))))
(deftest ^:parallel pivots-should-not-return-expressions-test-3
diff --git a/test/metabase/query_processor_test/aggregation_test.clj b/test/metabase/query_processor_test/aggregation_test.clj
index a48dcb2f303..183a84335dc 100644
--- a/test/metabase/query_processor_test/aggregation_test.clj
+++ b/test/metabase/query_processor_test/aggregation_test.clj
@@ -289,6 +289,34 @@
(is (= [[39]]
(mt/formatted-rows [int] (qp/process-query query)))))))))
+(deftest ^:parallel aggregation-and-fields-test
+ (mt/test-drivers (mt/normal-drivers)
+ (testing "adding an aggregation to a query with fields works"
+ (let [mp (mt/metadata-provider)]
+ (is (= [[100]]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/with-fields [(lib/ref (lib.metadata/field mp (mt/id :venues :id)))
+ (lib/ref (lib.metadata/field mp (mt/id :venues :name)))])
+ (lib/aggregate (lib/count))
+ (qp/process-query)
+ (->> (mt/formatted-rows [int])))))))))
+
+(deftest ^:parallel aggregation-and-join-fields-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join)
+ (testing "adding an aggregation to a query with fields from joins works"
+ (let [mp (mt/metadata-provider)]
+ (is (= [[18760]]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/with-fields [(lib/ref (lib.metadata/field mp (mt/id :orders :id)))
+ (lib/ref (lib.metadata/field mp (mt/id :orders :total)))])
+ (lib/join (lib/join-clause (lib.metadata/table mp (mt/id :products))
+ [(lib/= (lib.metadata/field mp (mt/id :orders :product_id))
+ (-> (lib.metadata/field mp (mt/id :products :id))
+ (lib/with-join-alias "Products")))]))
+ (lib/aggregate (lib/count))
+ (qp/process-query)
+ (->> (mt/formatted-rows [int])))))))))
+
;; !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
;; ! !
;; ! tests for named aggregations can be found in `expression-aggregations-test` !
diff --git a/test/metabase/query_processor_test/breakout_test.clj b/test/metabase/query_processor_test/breakout_test.clj
index d24a9689558..8d2de7d7955 100644
--- a/test/metabase/query_processor_test/breakout_test.clj
+++ b/test/metabase/query_processor_test/breakout_test.clj
@@ -362,3 +362,33 @@
[-100.0 11345]
[-80.0 2275]]
(mt/formatted-rows [1.0 int] (qp/process-query query)))))))))))
+
+(deftest ^:parallel breakout-and-fields-test
+ (mt/test-drivers (mt/normal-drivers)
+ (testing "adding a breakout to a query with fields works"
+ (let [mp (mt/metadata-provider)]
+ (is (= [[2] [3] [4]]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/with-fields [(lib/ref (lib.metadata/field mp (mt/id :venues :id)))
+ (lib/ref (lib.metadata/field mp (mt/id :venues :name)))])
+ (lib/breakout (lib.metadata/field mp (mt/id :venues :category_id)))
+ (lib/limit 3)
+ (qp/process-query)
+ (->> (mt/formatted-rows [int])))))))))
+
+(deftest ^:parallel breakout-and-join-fields-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join)
+ (testing "adding a breakout to a query with fields from joins works"
+ (let [mp (mt/metadata-provider)]
+ (is (= [["Doohickey"] ["Gadget"] ["Gizmo"]]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/with-fields [(lib/ref (lib.metadata/field mp (mt/id :orders :id)))
+ (lib/ref (lib.metadata/field mp (mt/id :orders :total)))])
+ (lib/join (lib/join-clause (lib.metadata/table mp (mt/id :products))
+ [(lib/= (lib.metadata/field mp (mt/id :orders :product_id))
+ (-> (lib.metadata/field mp (mt/id :products :id))
+ (lib/with-join-alias "Products")))]))
+ (lib/breakout (lib.metadata/field mp (mt/id :products :category)))
+ (lib/limit 3)
+ (qp/process-query)
+ (->> (mt/formatted-rows [str])))))))))