Skip to content

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

Omit `pivot-grouping` from window function `OVER` `PARTITION BY` and `ORDER BY` expressions (#70273)

Cam Saulab7e4712b12e
diff --git a/modules/drivers/redshift/test/metabase/test/data/redshift.clj b/modules/drivers/redshift/test/metabase/test/data/redshift.clj
index 4148ea49b17..1ac8de4d28e 100644
--- a/modules/drivers/redshift/test/metabase/test/data/redshift.clj
+++ b/modules/drivers/redshift/test/metabase/test/data/redshift.clj
@@ -72,7 +72,7 @@
(def db-connection-details
(delay {:host (tx/db-test-env-var-or-throw :redshift :host)
- :port (Integer/parseInt (tx/db-test-env-var-or-throw :redshift :port "5439"))
+ :port (parse-long (tx/db-test-env-var :redshift :port "5439"))
:db (tx/db-test-env-var-or-throw :redshift :db)
:user (tx/db-test-env-var-or-throw :redshift :user)
:password (tx/db-test-env-var-or-throw :redshift :password)
@@ -81,8 +81,8 @@
(def db-routing-connection-details
(delay {:host (tx/db-test-env-var-or-throw :redshift :host)
- :port (Integer/parseInt (tx/db-test-env-var-or-throw :redshift :port "5439"))
- :db (tx/db-test-env-var-or-throw :redshift :db-routing)
+ :port (parse-long (tx/db-test-env-var :redshift :port "5439"))
+ :db (tx/db-test-env-var :redshift :db-routing "dev")
:user (tx/db-test-env-var-or-throw :redshift :user)
:password (tx/db-test-env-var-or-throw :redshift :password)
:schema-filters-type "inclusion"
@@ -195,7 +195,7 @@
result)))]
(group-by (fn [schema-name]
(if-let [oldest (get schema->time schema-name)]
- (if (t/before? (.toInstant oldest) threshold)
+ (if (t/before? (t/instant oldest) threshold)
:expired
:recent)
;; Schema not in pg_class_info means no objects - treat as expired
diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.clj
index 3705775aba7..fc7540ad1b1 100644
--- a/src/metabase/driver/sql/query_processor.clj
+++ b/src/metabase/driver/sql/query_processor.clj
@@ -13,13 +13,14 @@
[metabase.driver-api.core :as driver-api]
[metabase.driver.common :as driver.common]
[metabase.driver.sql.query-processor.deprecated :as sql.qp.deprecated]
+ [metabase.lib.util.match :as lib.util.match]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
- [metabase.util.performance :as perf :refer [some mapv every? select-keys empty? not-empty]]
+ [metabase.util.performance :as perf :refer [empty? every? mapv not-empty select-keys some]]
[toucan2.pipeline :as t2.pipeline])
(:import
(java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)
@@ -989,47 +990,72 @@
(or (clause-pred (first form))
(m/find-first (partial contains-clause? clause-pred) (rest form))))))
+(defn- pivot-query-group-constant-expression?
+ "Whether this is a reference to the `pivot-group` constant expression added
+ by [[metabase.query-processor.pivot/add-pivot-group-breakout]]; if it is, we can safely exclude it from `GROUP BY`
+ and `ORDER BY` when generating an `OVER` window expression, since it is a constant value. (Some databases like
+ Redshift aren't happy if they include constant expressions in `OVER`).
+
+ See [[metabase.query-processor.pivot-test/offset-pivot-test]] for a test that fails if this is removed."
+ [expr]
+ (lib.util.match/match-lite expr
+ [(_ :guard #{:field :expression}) (_name :guard string?) (_opts :guard :qp.pivot/pivot-grouping?)]
+ true))
+
(defn- over-order-bys
"Returns a vector containing the `aggregations` specified by `order-bys` compiled to
honeysql expressions for `driver` suitable for ordering in the over clause of a window function."
[driver aggregations order-bys]
(let [aggregations (vec aggregations)]
(into []
- (keep (fn [[direction expr]]
- (if (aggregation? expr)
- (let [[_aggregation index] expr
- agg (unwrap-aggregation-option (aggregations index))]
- (when-not (contains-clause? #{:cum-count :cum-sum :offset} agg)
- [(->honeysql driver agg) direction]))
- [(->honeysql driver expr) direction])))
+ (comp (remove (fn [[_direction expr]]
+ (when (pivot-query-group-constant-expression? expr)
+ (log/debugf "Excluding %s from ORDER BY in OVER expression since it is a constant" (pr-str expr))
+ true)))
+ (keep (fn [[direction expr]]
+ (if (aggregation? expr)
+ (let [[_aggregation index] expr
+ agg (unwrap-aggregation-option (aggregations index))]
+ (when-not (contains-clause? #{:cum-count :cum-sum :offset} agg)
+ [(->honeysql driver agg) direction]))
+ [(->honeysql driver expr) direction]))))
order-bys)))
(defn- window-aggregation-over-expr-for-query-with-breakouts
"Order by the first breakout, then partition by all the other ones. See #42003 and
https://metaboat.slack.com/archives/C05MPF0TM3L/p1714084449574689 for more info."
[driver inner-query]
- (let [breakouts (remove
- (comp driver-api/qp.util.transformations.nest-breakouts.externally-remapped-field
- #(nth % 2))
- (:breakout inner-query))
- group-bys (:group-by (apply-top-level-clause driver :breakout {} inner-query))
+ (let [breakouts (into []
+ (comp (remove
+ (comp driver-api/qp.util.transformations.nest-breakouts.externally-remapped-field
+ #(nth % 2)))
+ (remove (fn [expr]
+ (when (pivot-query-group-constant-expression? expr)
+ (log/debugf "Excluding %s from GROUP BY in OVER expression since it is a constant"
+ (pr-str expr))
+ true))))
+ (:breakout inner-query))
+ group-bys (:group-by (apply-top-level-clause driver :breakout {} inner-query))
finest-temp-breakout (driver-api/finest-temporal-breakout-index breakouts 2)
- partition-exprs (when (> (count breakouts) 1)
- (if finest-temp-breakout
- (m/remove-nth finest-temp-breakout group-bys)
- (butlast group-bys)))
- order-bys (over-order-bys driver (:aggregation inner-query)
- (remove
- (comp driver-api/qp.util.transformations.nest-breakouts.externally-remapped-field
- #(nth % 2)
- second)
- (:order-by inner-query)))]
+ partition-exprs (when (> (count breakouts) 1)
+ (if finest-temp-breakout
+ (m/remove-nth finest-temp-breakout group-bys)
+ (butlast group-bys)))
+ order-bys (remove
+ (comp driver-api/qp.util.transformations.nest-breakouts.externally-remapped-field
+ #(nth % 2)
+ second)
+ (:order-by inner-query))
+ order-bys (over-order-bys driver
+ (:aggregation inner-query)
+ order-bys)]
(merge
(when (seq partition-exprs)
{:partition-by (mapv (fn [expr]
[expr])
partition-exprs)})
- {:order-by order-bys})))
+ (when (seq order-bys)
+ {:order-by order-bys}))))
(defn- window-aggregation-over-expr-for-query-without-breakouts [driver inner-query]
(when-let [order-bys (not-empty (:order-by (apply-top-level-clause driver :order-by {} inner-query)))]
@@ -1052,8 +1078,13 @@
(throw (ex-info (tru "Window function requires either breakouts or order by in the query")
{:type driver-api/qp.error-type.invalid-query
:query *inner-query*})))
- m (f driver *inner-query*)]
- (-> [:over [expr (merge m additional-hsql)]]
+ m (-> (f driver *inner-query*)
+ (merge additional-hsql))]
+ (-> (if (seq m)
+ [:over [expr m]]
+ (do
+ (log/debug "OVER contains no GROUP BYs or ORDER BYs, falling back to returning NULL")
+ [:inline nil]))
(h2x/with-database-type-info (h2x/database-type expr))))))
(defn- format-rows-unbounded-preceding [_clause _args]
diff --git a/src/metabase/lib/expression.cljc b/src/metabase/lib/expression.cljc
index 6dde4e6b756..9da1307daef 100644
--- a/src/metabase/lib/expression.cljc
+++ b/src/metabase/lib/expression.cljc
@@ -94,8 +94,8 @@
(fn []
(let [base-type (lib.metadata.calculation/type-of query stage-number expression-ref-clause)]
(merge {:lib/type :metadata/column
- ;; TODO (Cam 8/7/25) -- is the source UUID of an expression ref supposed to be the ID of the ref, or the ID
- ;; of the expression definition??
+ ;; TODO (Cam 8/7/25) -- is the source UUID of an expression ref supposed to be the ID of the ref, or the ID
+ ;; of the expression definition??
:lib/source-uuid (:lib/uuid opts)
:name expression-name
:lib/expression-name expression-name
@@ -108,7 +108,9 @@
{:lib/temporal-unit unit})
(when lib.metadata.calculation/*propagate-binning-and-bucketing*
(when-let [unit (lib.temporal-bucket/raw-temporal-bucket expression-ref-clause)]
- {:inherited-temporal-unit unit})))))))
+ {:inherited-temporal-unit unit}))
+ (when-some [pivot-grouping? (:qp.pivot/pivot-grouping? opts)]
+ {:qp.pivot/pivot-grouping? pivot-grouping?}))))))
(defmethod lib.temporal-bucket/available-temporal-buckets-method :expression
[query stage-number [_expression opts _expr-name, :as expr-clause]]
diff --git a/src/metabase/lib/field.cljc b/src/metabase/lib/field.cljc
index 8114d2638bc..bafb48b92b5 100644
--- a/src/metabase/lib/field.cljc
+++ b/src/metabase/lib/field.cljc
@@ -427,11 +427,12 @@
[:base-type
:inherited-temporal-unit
:lib/original-binning
- :lib/original-effective-type])
- {:lib/binning :binning
- :lib/temporal-unit :temporal-unit
- :lib/ref-name :name
- :lib/ref-display-name :display-name}))
+ :lib/original-effective-type
+ :qp.pivot/pivot-grouping?])
+ {:lib/binning :binning
+ :lib/temporal-unit :temporal-unit
+ :lib/ref-name :name
+ :lib/ref-display-name :display-name}))
(def ^:private field-ref-propagated-keys-for-non-inherited-columns
"Keys that should get copied into `:field` ref options from column metadata ONLY when the column is not inherited.
@@ -447,9 +448,9 @@
;; types -- they're required for field name refs.
[:lib/transformation-added-base-type])
{:lib/join-alias :join-alias
- :fk-field-id :source-field
- :fk-join-alias :source-field-join-alias
- :fk-field-name :source-field-name}))
+ :fk-field-id :source-field
+ :fk-join-alias :source-field-join-alias
+ :fk-field-name :source-field-name}))
(defn- select-renamed-keys [m old->new]
(-> m
@@ -609,7 +610,7 @@
"hidden in the UI.")))
(mu/defn add-field :- ::lib.schema/query
- "Adds a given field (`ColumnMetadata`, as returned from eg. [[visible-columns]]) to the fields returned by the query.
+ "Adds a given field (column metadata), as returned from eg. [[visible-columns]]) to the fields returned by the query.
Exactly what this means depends on the source of the field:
- Source table/card, previous stage of the query, custom expression, aggregation or breakout:
- Add it to the `:fields` list
diff --git a/src/metabase/lib/field/resolution.cljc b/src/metabase/lib/field/resolution.cljc
index 9cbec0bf9b9..114968d78f1 100644
--- a/src/metabase/lib/field/resolution.cljc
+++ b/src/metabase/lib/field/resolution.cljc
@@ -136,7 +136,8 @@
:effective-type
:display-name
:lib/transformation-added-base-type
- :lib/original-effective-type})
+ :lib/original-effective-type
+ :qp.pivot/pivot-grouping?})
(def ^:private opts-propagated-renamed-keys
"Keys in `:field` opts that get copied into column metadata with different keys when they have non-nil values.
diff --git a/src/metabase/lib/schema/metadata.cljc b/src/metabase/lib/schema/metadata.cljc
index 2b4bcab8894..dae0edb98e5 100644
--- a/src/metabase/lib/schema/metadata.cljc
+++ b/src/metabase/lib/schema/metadata.cljc
@@ -516,7 +516,18 @@
;; stage. [[metabase.lib.metadata.result-metadata/super-broken-legacy-field-ref]] uses this to know to force Field
;; ID refs for QP `:field_ref` in results metadata to preserve historic behavior to avoid breaking legacy viz
;; settings that use it as a key.
- [:qp/implicit-field? {:optional true} [:maybe :boolean]]]
+ [:qp/implicit-field? {:optional true} [:maybe :boolean]]
+ ;;
+ ;; Whether this is the special `pivot-grouping` column added by the Pivot QP
+ ;; in [[metabase.query-processor.pivot/add-pivot-group-breakout]]. In `OVER` window function `GROUP BY` and `ORDER
+ ;; BY` this should be "optimized out" since some databases like Redshift don't allow constant expressions there.
+ ;; See also [[metabase.driver.sql.query-processor/pivot-query-group-constant-expression?]] (where this is used by
+ ;; the SQL QP) and [[metabase.query-processor.pivot-test/offset-pivot-test]] (a test that will fail if this key is
+ ;; removed)
+ ;;
+ ;; This should be propagated as-is to subsequent stages and copied into ref option maps, and from ref option maps
+ ;; into calculated metadata.
+ [:qp.pivot/pivot-grouping? {:optional true} [:maybe :boolean]]]
;;
;; Additional constraints
;;
diff --git a/src/metabase/lib/schema/ref.cljc b/src/metabase/lib/schema/ref.cljc
index 377db07a601..3405ad4342b 100644
--- a/src/metabase/lib/schema/ref.cljc
+++ b/src/metabase/lib/schema/ref.cljc
@@ -56,7 +56,7 @@
[:and
[:merge
{:encode/serialize (fn [opts]
- (let [;; These keys were previously in metabase.lib.* namespaces and stripped
+ (let [ ;; These keys were previously in metabase.lib.* namespaces and stripped
;; by the (= namespace "lib") check. After renaming to :lib/* they'd
;; survive serialization, so exclude them explicitly.
exclude (set (vals common/deprecated-lib-key-renames))]
@@ -144,7 +144,10 @@
;; Produced by older queries and the `reconcile-breakout-and-order-by-bucketing` QP middleware. Used as a
;; fallback in `nest-breakouts` to determine column granularity when `:temporal-unit` is nil or `:default`.
;; Not produced by MLv2 code; new queries will not contain this key.
- [:original-temporal-unit {:optional true} [:ref ::temporal-bucketing/unit]]]]
+ [:original-temporal-unit {:optional true} [:ref ::temporal-bucketing/unit]]
+ ;;
+ ;; Propagated from `:metabase.lib.schema.metadata/column` metadata; see description there.
+ [:qp.pivot/pivot-grouping? {:optional true} [:maybe :boolean]]]]
(common/disallowed-keys
(into {:strategy ":binning keys like :strategy are not allowed at the top level of :field options."}
(map (fn [[old-key new-key]]
diff --git a/src/metabase/query_processor/pivot.clj b/src/metabase/query_processor/pivot.clj
index e0dcc9c10a2..99de9d5cfc8 100644
--- a/src/metabase/query_processor/pivot.clj
+++ b/src/metabase/query_processor/pivot.clj
@@ -171,7 +171,13 @@
(lib/expression query -1 "pivot-grouping" (lib/abs bitmask) {:add-to-fields? false})
;; in PostgreSQL and most other databases, all the expressions must be present in the breakouts. Add a pivot
;; grouping expression ref to the breakouts
- (lib/breakout query (lib/expression-ref query "pivot-grouping"))
+ (lib/breakout query (-> (lib/expression-ref query "pivot-grouping")
+ ;; mark this expression ref as a special constant so it can get removed from window
+ ;; function `OVER` `ORDER BY` or `GROUP BY` expressions since constants aren't allowed in
+ ;; all DBs (e.g. Redshift) --
+ ;; see [[metabase.query-processor.pivot-test/offset-pivot-test]]
+ ;; and [[metabase.driver.sql.query-processor/pivot-query-group-constant-expression?]]
+ (lib/update-options assoc :qp.pivot/pivot-grouping? true)))
(do
(log/tracef "Added pivot-grouping expression to query\n%s" (u/pprint-to-str 'yellow query))
query)))
diff --git a/test/metabase/query_processor/pivot_test.clj b/test/metabase/query_processor/pivot_test.clj
index f5e66be19f0..b8cde36981a 100644
--- a/test/metabase/query_processor/pivot_test.clj
+++ b/test/metabase/query_processor/pivot_test.clj
@@ -802,3 +802,24 @@
[nil 1 3]]
(mt/rows
(qp.pivot/run-pivot-query query))))))))
+
+(deftest ^:parallel offset-pivot-test
+ (testing "Window functions like OFFSET (... OVER ...) should work correctly with the pivot QP (#70088)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/cumulative :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/aggregate (-> (lib/offset (lib/count) -1)
+ (lib/update-options assoc :display-name "Previous Count")))
+ (lib/breakout (-> (lib.metadata/field mp (mt/id :orders :created_at))
+ (lib/with-temporal-bucket :year))))]
+ ;; Created At | Pivot Group | Count | Previous Count
+ (is (=? [[#"2016-01-01(?:T00:00:00Z)?" 0 744 nil]
+ [#"2017-01-01(?:T00:00:00Z)?" 0 3610 744]
+ [#"2018-01-01(?:T00:00:00Z)?" 0 5834 3610]
+ [#"2019-01-01(?:T00:00:00Z)?" 0 6578 5834]
+ [#"2020-01-01(?:T00:00:00Z)?" 0 1994 6578]
+ [nil 1 18760 nil]]
+ (mt/formatted-rows
+ [str int int int]
+ (qp.pivot/run-pivot-query query))))))))