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
Implement the UNION ALL approach for running pivot queries (#81406)
metamben8d5db3195d21
diff --git a/.clj-kondo/ratchets.edn b/.clj-kondo/ratchets.ednindex b180942c4d9..cc0e92a23db 100644--- a/.clj-kondo/ratchets.edn+++ b/.clj-kondo/ratchets.edn@@ -21,11 +21,11 @@:consistent-alias 2:def-fn 1:deprecated-namespace 29- :deprecated-var 53+ :deprecated-var 61:discouraged-java-method 4:duplicate-require 1:main-without-gen-class 1- :metabase/discourage-dynamic-vars 324+ :metabase/discourage-dynamic-vars 323:metabase/discourage-millis-duration 1:metabase/modules 23:metabase/namespace-name 3@@ -108,8 +108,7 @@:unresolved-symbol 15:unresolved-var 1:unused-referred-var 4}- :comment-exempt #{:deprecated-namespace- :discouraged-namespace+ :comment-exempt #{:discouraged-namespace:discouraged-var:metabase/discourage-dynamic-vars:metabase/modulesdiff --git a/docs/developers-guide/driver-changelog.md b/docs/developers-guide/driver-changelog.mdindex e50847321bf..826a93dcc43 100644--- a/docs/developers-guide/driver-changelog.md+++ b/docs/developers-guide/driver-changelog.md@@ -83,6 +83,18 @@ title: Driver interface changelogform for the pivot-grouping bitmask. The default emits `GROUPING(exprs...)` (the Postgres/Oracle/Snowflakemulti-arg extension); drivers whose SQL dialect uses a different function or shape override this method.+- `metabase.driver.sql.pivot/null-pad-breakout-hsql` `[driver breakout breakout-expr]` -- produces the HoneySQL form+ used to null-pad a dropped-breakout column in a `UNION ALL` branch of the pivot compiler's UNION ALL path (the+ fallback used when the driver lacks `:native-pivot-tables` or the query has window-function+ aggregations). `breakout` is the MBQL breakout clause (with `:base-type` in its options); `breakout-expr` is its+ compiled HoneySQL form. Default is bare `NULL`, which most dialects infer from sibling `UNION ALL` branches.+ Dialects that don't coerce untyped `NULL` across branches override to emit `CAST(NULL AS <type>)`, typically by+ mapping the breakout `:base-type` to a driver-specific SQL type name.++- `metabase.driver.sql.query-processor/apply-cte-hoist?` `[driver]` -- whether a `UNION ALL` pivot compiled for `driver`+ should hoist the shared pre-pivot subquery into a `WITH` binding that every branch references by alias, rather+ than inlining it once per branch. Defaults to `true`.+- `:native-pivot-tables` is now enabled for `:hive-like` drivers.Hive-family dialects synthesise the pivot-grouping bitmask from single-arg `GROUPING(x)` calls.diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.cljindex eb207445c58..f9bf40b43cd 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj@@ -344,32 +344,9 @@"BIGNUMERIC" :type/Decimal:type/*))-(defmulti ^:private type->database-type- "Internal type->database-type multimethod for BigQuery that dispatches on type."- {:arglists '([type])}- identity)--;; we can't recover the parameterized types-(defmethod type->database-type :type/Array [_] [[:raw "JSON"]])-(defmethod type->database-type :type/Dictionary [_] [[:raw "JSON"]])--(defmethod type->database-type :type/Boolean [_] [[:raw "BOOL"]])-(defmethod type->database-type :type/Float [_] [[:raw "FLOAT64"]])-(defmethod type->database-type :type/Integer [_] [[:raw "INT"]])-(defmethod type->database-type :type/Number [_] [[:raw "INT"]])-(defmethod type->database-type :type/Text [_] [[:raw "STRING"]])-(defmethod type->database-type :type/TextLike [_] [[:raw "STRING"]])-(defmethod type->database-type :type/Date [_] [[:raw "DATE"]])-(defmethod type->database-type :type/DateTime [_] [[:raw "DATETIME"]])-(defmethod type->database-type :type/DateTimeWithTZ [_] [[:raw "TIMESTAMP"]])-(defmethod type->database-type :type/Time [_] [[:raw "TIME"]])-(defmethod type->database-type :type/JSON [_] [[:raw "JSON"]])-(defmethod type->database-type :type/SerializedJSON [_] [[:raw "JSON"]])-(defmethod type->database-type :type/Decimal [_] [[:raw "BIGDECIMAL"]])-(defmethod driver/type->database-type :bigquery-cloud-sdk[_driver base-type]- (type->database-type base-type))+ [[:raw (bigquery.common/base-type->bigquery-type base-type)]])(defn- field->database+base-type"Returns a normalized `database-type` and its `base-type` for a type from BigQuery Field type.diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.cljindex 0ef77eceb2c..9e967a8b1ea 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.clj@@ -56,6 +56,31 @@[{:keys [project-id billing-project-id] :as details}](or project-id billing-project-id (database-details->credential-project-id details)))+(defmulti base-type->bigquery-type+ "Return the BigQuery SQL type name for a Metabase `:type/*` base-type as a plain string. Throws+ `IllegalArgumentException` when the type has no BigQuery analogue."+ {:arglists '([base-type])+ :changelog-test/ignore true}+ identity)++;; We can't recover the parameterized types for ARRAY / DICTIONARY — flatten to JSON.+(defmethod base-type->bigquery-type :type/Array [_] "JSON")+(defmethod base-type->bigquery-type :type/Dictionary [_] "JSON")++(defmethod base-type->bigquery-type :type/Boolean [_] "BOOL")+(defmethod base-type->bigquery-type :type/Integer [_] "INT")+(defmethod base-type->bigquery-type :type/Number [_] "INT")+(defmethod base-type->bigquery-type :type/Float [_] "FLOAT64")+(defmethod base-type->bigquery-type :type/Decimal [_] "BIGDECIMAL")+(defmethod base-type->bigquery-type :type/Text [_] "STRING")+(defmethod base-type->bigquery-type :type/TextLike [_] "STRING")+(defmethod base-type->bigquery-type :type/Date [_] "DATE")+(defmethod base-type->bigquery-type :type/DateTime [_] "DATETIME")+(defmethod base-type->bigquery-type :type/DateTimeWithTZ [_] "TIMESTAMP")+(defmethod base-type->bigquery-type :type/Time [_] "TIME")+(defmethod base-type->bigquery-type :type/JSON [_] "JSON")+(defmethod base-type->bigquery-type :type/SerializedJSON [_] "JSON")+(mu/defn populate-project-id-from-credentials!"Update the given `database` details blob to include the credentials' project-id as a separate entry (under a`project-id-from-credentials` key). This is basically an inferred/calculated key (not something the user will everdiff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.cljindex 70207986b3c..30354320a17 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj@@ -11,6 +11,7 @@[metabase.driver.common :as driver.common][metabase.driver.connection :as driver.conn][metabase.driver.sql.parameters.substitution :as sql.params.substitution]+ [metabase.driver.sql.pivot :as sql.pivot][metabase.driver.sql.query-processor :as sql.qp][metabase.driver.sql.query-processor.util :as sql.qp.u][metabase.driver.sql.util :as sql.u]@@ -1100,3 +1101,13 @@(defmethod sql.qp/cast-temporal-string [:bigquery-cloud-sdk :Coercion/ISO8601->Time][_driver _semantic_type expr](h2x/->time expr))++;; BigQuery infers untyped `NULL` in `UNION ALL` as `INT64` and then rejects the union against+;; sibling `TIMESTAMP` / `STRING` columns. Emit `CAST(NULL AS <type>)` so the branch's null-padded+;; column carries the same type as its counterpart in the full-breakout branch.+(defmethod sql.pivot/null-pad-breakout-hsql :bigquery-cloud-sdk+ [_driver [_tag opts _id-or-name] _breakout-expr]+ (when-let [base-type (or (:effective-type opts) (:base-type opts))]+ (try+ (h2x/cast (bigquery.common/base-type->bigquery-type base-type) nil)+ (catch IllegalArgumentException _ nil))))diff --git a/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj b/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.cljindex 8bfe6b4e899..732eb196e41 100644--- a/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj+++ b/modules/drivers/presto-jdbc/src/metabase/driver/presto_jdbc.clj@@ -19,6 +19,7 @@[metabase.driver.sql-jdbc.sync :as sql-jdbc.sync][metabase.driver.sql-jdbc.sync.describe-database :as sql-jdbc.describe-database][metabase.driver.sql.parameters.substitution :as sql.params.substitution]+ [metabase.driver.sql.pivot :as sql.pivot][metabase.driver.sql.query-processor :as sql.qp][metabase.driver.sql.util :as sql.u][metabase.util :as u]@@ -115,6 +116,28 @@[_driver expr amount unit](date-add unit amount expr))+;; Presto/Trino doesn't coerce untyped `NULL` across `UNION ALL` branches, so the UA pivot+;; compiler's default bare-`NULL` pad fails preparation. Map the MBQL breakout `:base-type` to a+;; Presto cast target so the branch's null-padded column carries the same type as its+;; counterpart in the full-breakout branch.+(defn- base-type->presto-cast-type+ [base-type]+ (cond+ (isa? base-type :type/Text) "varchar"+ (isa? base-type :type/Integer) "bigint"+ (isa? base-type :type/Float) "double"+ (isa? base-type :type/Decimal) "decimal"+ (isa? base-type :type/Boolean) "boolean"+ (isa? base-type :type/Date) "date"+ (isa? base-type :type/Time) "time"+ (isa? base-type :type/DateTimeWithTZ) "timestamp with time zone"+ (isa? base-type :type/DateTime) "timestamp"))++(defmethod sql.pivot/null-pad-breakout-hsql :presto-jdbc+ [_driver [_tag opts _id-or-name] _breakout-expr]+ (when-let [presto-type (base-type->presto-cast-type (or (:effective-type opts) (:base-type opts)))]+ (h2x/cast presto-type nil)))+(defn- describe-catalog-sql"The SHOW SCHEMAS statement that will list all schemas for the given `catalog`."{:added "0.39.0"}diff --git a/src/metabase/driver/h2.clj b/src/metabase/driver/h2.cljindex 5cb0d9e23b7..4fc81705e4a 100644--- a/src/metabase/driver/h2.clj+++ b/src/metabase/driver/h2.clj@@ -113,6 +113,13 @@[driver [_ _opts arg pattern]][:regexp_substr (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver pattern)])+;; H2 loses a CTE's prepared-statement parameters under the outer `SELECT * FROM (<UNION ALL>)` wrap+;; the pivot compiler emits — every branch counts zero rows. Opt out so the compiler inlines the+;; pre-pivot subquery in each branch instead.+(defmethod sql.qp/apply-cte-hoist? :h2+ [_driver]+ false)+(defmethod driver/connection-properties :h2[_](->>diff --git a/src/metabase/driver/sql/pivot.clj b/src/metabase/driver/sql/pivot.cljindex b648a3f17d5..7d01f3714fb 100644--- a/src/metabase/driver/sql/pivot.clj+++ b/src/metabase/driver/sql/pivot.clj@@ -1,19 +1,42 @@(ns metabase.driver.sql.pivot"HoneySQL formatters and SQL compilation hooks for the MBQL 5 native pivot path. Used by any driver that derives from`:sql` and opts into `:native-pivot-tables`."- (:refer-clojure :exclude [mapv])+ (:refer-clojure :exclude [mapv not-empty some])(:require[clojure.string :as str][honey.sql :as sql][metabase.driver :as driver]+ [metabase.driver-api.core :as driver-api][metabase.driver.sql.query-processor :as sql.qp]+ [metabase.driver.util :as driver.u][metabase.lib.options :as lib.options][metabase.lib.pivot :as lib.pivot]+ [metabase.lib.schema.aggregation :as lib.schema.aggregation]+ [metabase.lib.util :as lib.util];; :as-alias only, for ::add-remaps keywords; no runtime dependency on QP internals^{:clj-kondo/ignore [:metabase/modules]}[metabase.query-processor.middleware.add-remaps :as-alias add-remaps][metabase.query-processor.pivot :as qp.pivot]- [metabase.util.performance :refer [mapv]]))+ [metabase.util :as u]+ [metabase.util.performance :refer [mapv not-empty some]]))++(set! *warn-on-reflection* true)++(defn- stage-has-window-fn-aggregation?+ "True iff any aggregation on the compiled `stage` is a window-function aggregation, or transitively contains one."+ [stage]+ (some? (some lib.schema.aggregation/window-aggregation-expression?+ (:aggregation stage))))++(defn- use-grouping-sets?+ "True iff `database`'s driver supports `:native-pivot-tables` and the compiled `stage` has no window aggregation.+ Short-circuits when the stage carries `:qp.pivot/forced-shape` `:native-pivot-query` or `:union-all`."+ [database stage]+ (case (:qp.pivot/forced-shape stage)+ :native-pivot-query true+ :union-all false+ (and (driver.u/supports? (driver.u/database->driver database) :native-pivot-tables database)+ (not (stage-has-window-fn-aggregation? stage)))))(defn- format-exprs"Format each expression in `exprs` via [[honey.sql/format-expr]] and return `[[sql-strings] [args]]`."@@ -139,8 +162,10 @@(conj pivot-grouping-select)(into rest-cols))))-(defmethod sql.qp/apply-top-level-clause [:sql :pivot]- [driver _ honeysql-form {:keys [breakout pivot]}]+(defn- compile-grouping-sets-pivot+ "Compile the `:pivot` clause into a single-query `GROUP BY GROUPING SETS ((...), (...), ...)` shape.+ Assumes `driver` supports the `GROUPING SETS` extension via `:native-pivot-tables`."+ [driver honeysql-form {:keys [breakout pivot]}](let [breakout-hsql (mapv #(sql.qp/->honeysql driver %) breakout)non-remap-poss (non-remap-positions breakout)non-remap-bos (mapv breakout non-remap-poss)@@ -168,3 +193,202 @@(update :select splice-pivot-grouping-select (count breakout) [grouping-fn lib.pivot/pivot-grouping-column-name])(assoc :group-by [grouping-sets]:order-by (into prefix-order-by (:order-by honeysql-form))))))++(defn- select-entry-alias+ "Return the alias of a HoneySQL `:select` `entry` — either the second element of an `[expr alias]` pair, or the+ entry itself (HoneySQL treats a bare identifier as its own alias)."+ [entry]+ (cond-> entry (vector? entry) second))++(defmulti null-pad-breakout-hsql+ "Return a HoneySQL form used to null-pad a dropped-breakout column in a UNION ALL branch of the+ UA pivot compiler. `breakout` is the MBQL breakout clause (drivers can read `:base-type` /+ `:effective-type` from its options); `breakout-expr` is its compiled HoneySQL form (drivers can+ read database-type metadata attached during compilation).++ Default is a bare `NULL`, which most dialects infer from sibling `UNION ALL` branches. Dialects+ that leave untyped `NULL` untyped and reject the union (BigQuery, Presto/Trino) override this+ to emit `CAST(NULL AS <type>)`, typically by mapping `:base-type` to a driver-specific SQL type+ name."+ {:added "0.64.0", :arglists '([driver breakout breakout-expr])}+ driver/dispatch-on-initialized-driver+ :hierarchy #'driver/hierarchy)++(defmethod null-pad-breakout-hsql :sql+ [_driver _breakout _breakout-expr]+ nil)++(defn- hoist-shared-source-to-cte+ "When every UA branch shares the same single-entry subquery `:from`, lift it into a `WITH`+ binding and rewrite each branch to reference the CTE by its original alias. Returns+ `{:cte-binding [<name> <src>] :branches <rewritten>}` on hoist, or `nil` when hoisting doesn't+ apply — driver opts out via [[sql.qp/apply-cte-hoist?]], branches diverge, or the shared entry+ isn't a subquery."+ [driver branches]+ (let [cte-name :__mb_pivot_source+ froms (mapv :from branches)+ [shared-src src-alias]+ (when (and (sql.qp/apply-cte-hoist? driver)+ (apply = froms)+ ;; single from-entry only: multi-source `:from` (implicit+ ;; cross joins) would need every entry hoisted separately.+ (= 1 (count (first froms))))+ (let [entry (ffirst froms)]+ (cond+ ;; unaliased subquery: `<map>`+ (map? entry)+ [entry nil]+ ;; aliased subquery: `[<map> <alias>]`+ (and (vector? entry) (= 2 (count entry)) (map? (first entry)))+ [(first entry) (second entry)])))]+ (when shared-src+ (let [cte-from (if src-alias+ [[cte-name src-alias]]+ [[cte-name]])]+ {:cte-binding [cte-name shared-src]+ :branches (mapv #(assoc % :from cte-from) branches)}))))++(defn- compile-union-all-pivot+ "Compile the `:pivot` clause into a `UNION ALL` over one branch per grouping-set combination, wrapped in an outer+ `SELECT * FROM (...) AS __mb_pivot_result`. Used for drivers that lack `:native-pivot-tables` and for queries whose+ window aggregations GROUPING SETS can't compose meaningfully.++ For each combo we recompile `:breakout` + `:aggregation` against a stage variant carrying only the kept+ breakouts, so the SQL compiler produces branch-appropriate `GROUP BY` and window-fn `OVER` shapes (matching+ what the multi-query path emits per subquery). Missing breakout columns are null-padded so all branches+ share a UNION-ALL-compatible column layout."+ [driver honeysql-form {:keys [breakout pivot] :as stage}]+ (let [breakout (vec breakout)+ breakout-hsql (mapv #(sql.qp/->honeysql driver %) breakout)+ non-remap-poss (non-remap-positions breakout)+ non-remap-bos (mapv breakout non-remap-poss)+ orig->new (remap-original->new-field-positions breakout)+ nr-idx-by-uuid (into {} (map-indexed (fn [i b] [(lib.options/uuid b) i])) non-remap-bos)+ rows-idx (mapv nr-idx-by-uuid (:rows pivot))+ cols-idx (mapv nr-idx-by-uuid (:columns pivot))+ combos (qp.pivot/breakout-combinations (count non-remap-bos)+ rows-idx+ cols-idx+ (get pivot :show-row-totals true)+ (get pivot :show-column-totals true))+ n-breakouts (count breakout)+ orig-breakout-select (subvec (:select honeysql-form) 0 n-breakouts)+ orig-agg-select (subvec (:select honeysql-form) n-breakouts)+ ;; Only take aggregation-referencing order-bys from the stage — implicit breakout-based order-bys+ ;; added by middleware are re-derived below (canonicalized), so keeping them would double-insert.+ user-order-bys (into []+ (filter (fn [[_ _ ref]]+ (lib.util/clause-of-type? ref :aggregation)))+ (:order-by stage))+ ;; HoneySQL form used to null-pad a dropped breakout in a UA branch — dispatched to+ ;; [[null-pad-breakout-hsql]]. Default is bare `NULL`; drivers with strict `UNION ALL`+ ;; type coercion (BigQuery, Presto) override to emit `CAST(NULL AS <type>)`.+ typed-null (fn [i]+ (null-pad-breakout-hsql driver (breakout i) (breakout-hsql i)))+ ;; Shared prefix (source, joins, filter, CTEs) — everything except the per-branch shape.+ shared-base (dissoc honeysql-form :select :select-distinct :group-by :order-by :limit)+ alias-of select-entry-alias+ ;; Reorder `bos` so any temporal breakout with the finest granularity comes last — matches the sort+ ;; ordering the multi-query path emits per subquery.+ canonicalize-breakouts (fn [bos]+ (if-let [fti (driver-api/finest-temporal-breakout-index bos 1)]+ (-> (subvec bos 0 fti)+ (into (subvec bos (inc fti)))+ (conj (bos fti)))+ bos))+ compile-branch (fn [combo]+ (let [kept-full-idx (vec (expand-grouping-combo combo non-remap-poss orig->new))+ kept-breakout (mapv breakout kept-full-idx)+ bitmask (qp.pivot/group-bitmask (count non-remap-bos) combo)+ ;; Strip :pivot to avoid recursing into this method. Set :order-by to+ ;; the user's explicit order-bys followed by canonical breakouts+ ;; (finest-temporal last) — window-fn aggregations read this from+ ;; `*inner-query*` to build their `OVER (ORDER BY ...)`, and multi-query's+ ;; subqueries sort the same way so branch row ordering lines up. Strip+ ;; :limit — the outer wrapper owns any row caps.+ canonical-bo (canonicalize-breakouts kept-breakout)+ branch-obs (into user-order-bys+ (map (fn [b] (lib.options/ensure-uuid [:asc {} b])))+ canonical-bo)+ branch-stage (-> stage+ (dissoc :pivot :limit)+ (assoc :breakout kept-breakout)+ (u/assoc-dissoc :order-by (not-empty branch-obs)))+ branch-form (binding [sql.qp/*inner-query* branch-stage]+ (cond-> shared-base+ (seq kept-breakout)+ (as-> $ (sql.qp/apply-top-level-clause+ driver :breakout $ branch-stage))+ :always+ (as-> $ (sql.qp/apply-top-level-clause+ driver :aggregation $ branch-stage))))+ n-kept (count kept-breakout)+ branch-select (:select branch-form)+ kept-sel (subvec branch-select 0 n-kept)+ aggs-sel (subvec branch-select n-kept)+ kept-by-alias (u/index-by alias-of kept-sel)+ padded-bo-sel (into []+ (map-indexed (fn [i orig-entry]+ (let [alias (alias-of orig-entry)]+ (or (kept-by-alias alias)+ [(typed-null i) alias]))))+ orig-breakout-select)+ full-select (-> padded-bo-sel+ (conj [[:inline bitmask]+ lib.pivot/pivot-grouping-column-name])+ (into aggs-sel))]+ (assoc branch-form :select full-select)))+ branches (mapv compile-branch combos)+ ;; Outer sort: pivot-grouping first (so branches stay grouped), then user's explicit order-bys+ ;; (referenced by their aggregation aliases so each pivot-grouping's rows are ordered like a+ ;; multi-query subquery would order them), then canonical breakouts as a final tiebreak.+ ;; HoneySQL wraps `[<alias>]` (the SELECT-alias shape) around the identifier form; strip that+ ;; wrapper for ORDER-BY use so HoneySQL emits `"alias" ASC` rather than `("alias") ASC` (which+ ;; Presto/Trino rejects).+ alias-ident (fn [a]+ (cond-> a+ (and (vector? a) (= 1 (count a)))+ first))+ canonical-orig-bo-aliases (mapv (fn [b]+ (-> (.indexOf ^java.util.List breakout b)+ orig-breakout-select+ alias-of+ alias-ident))+ (canonicalize-breakouts breakout))+ ;; Map aggregation UUID → position, so we can resolve MBQL 5 `[:aggregation opts <uuid-str>]`+ ;; references from the user's :order-by to the corresponding aggregation alias in+ ;; `orig-agg-select`.+ agg-uuid->idx (into {}+ (map-indexed (fn [i agg] [(lib.options/uuid agg) i]))+ (:aggregation stage))+ user-order-by-outer (into []+ (keep (fn [[dir _opts ref]]+ (when (lib.util/clause-of-type? ref :aggregation)+ (let [target (nth ref 2 nil)+ agg-idx (get agg-uuid->idx target)]+ (when-let [entry (and agg-idx (nth orig-agg-select agg-idx nil))]+ [(alias-ident (alias-of entry)) dir])))))+ user-order-bys)+ ;; `[:pivot-grouping :asc]` sorts combos so grand totals sort last; only meaningful when >1 combo.+ ;; User `:order-by` and the breakout tiebreakers apply in every case, so they're always included+ ;; when non-empty — dropping them for the single-combo case silently discarded the user's sort.+ outer-order-by (not-empty+ (into (if (> (count combos) 1)+ [[(keyword lib.pivot/pivot-grouping-column-name) :asc]]+ [])+ cat+ [user-order-by-outer+ (map (fn [alias] [alias :asc]) canonical-orig-bo-aliases)]))+ hoist (hoist-shared-source-to-cte driver branches)+ branches (:branches hoist branches)]+ (cond-> {:select [:*]+ :from [[{:union-all branches} :__mb_pivot_result]]}+ hoist (assoc :with [(:cte-binding hoist)])+ outer-order-by (assoc :order-by outer-order-by))))++(defmethod sql.qp/apply-top-level-clause [:sql :pivot]+ [driver _ honeysql-form stage]+ (let [database (driver-api/database (driver-api/metadata-provider))]+ (if (use-grouping-sets? database stage)+ (compile-grouping-sets-pivot driver honeysql-form stage)+ (compile-union-all-pivot driver honeysql-form stage))))diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.cljindex f079d189c4a..9ba8deae3a0 100644--- a/src/metabase/driver/sql/query_processor.clj+++ b/src/metabase/driver/sql/query_processor.clj@@ -2204,6 +2204,18 @@(remove (partial = :source-query)))(apply-top-level-clauses driver honeysql-form inner-query))))+(defmulti apply-cte-hoist?+ "True iff a UNION ALL pivot compiled for `driver` should hoist the shared pre-pivot subquery into a+ `WITH` binding that every branch references by alias, rather than inlining it once per branch. On+ by default; drivers whose planner doesn't support the resulting shape override to false."+ {:added "0.64.0", :arglists '([driver])}+ driver/dispatch-on-initialized-driver+ :hierarchy #'driver/hierarchy)++(defmethod apply-cte-hoist? :sql+ [_driver]+ true)+(defmulti preprocess"Do miscellaneous transformations to the MBQL before compiling the query. These changes are idempotent, so it is safeto use this function in your own implementations of [[driver/mbql->native]], if you want to apply changes to the@@ -2215,9 +2227,14 @@:hierarchy #'driver/hierarchy)(defmethod preprocess :sql- [_driver mbql5-query]+ [driver mbql5-query]+ ;; Nest a pivot stage's joins into a prior stage only for drivers that opt into the UA CTE hoist —+ ;; the nesting exists so [[metabase.driver.sql.pivot/compile-union-all-pivot]] can lift the shared+ ;; subquery into a `WITH` binding. Drivers that don't hoist would just carry an unnecessary+ ;; subquery layer on their GS / multi-query paths.(-> mbql5-querydriver-api/nest-breakouts-in-stages-with-window-aggregation+ (cond-> (apply-cte-hoist? driver) driver-api/nest-pivot-joins)driver-api/nest-expressionsdriver-api/add-alias-info:stages))diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.cljindex 551f0644f0e..7625e8f7026 100644--- a/src/metabase/driver_api/core.clj+++ b/src/metabase/driver_api/core.clj@@ -166,6 +166,7 @@qp.timezone/system-timezone-idqp.util.transformations.nest-breakouts/finest-temporal-breakout-indexqp.util.transformations.nest-breakouts/nest-breakouts-in-stages-with-window-aggregation+ qp.util.transformations.nest-breakouts/nest-pivot-joinsqp.util/default-query->remarkqp.util/query->remarkqp.wrap-value-literals/wrap-value-literals-in-mbql5diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljcindex 53a4c12cc16..aa595ee9f5d 100644--- a/src/metabase/legacy_mbql/schema.cljc+++ b/src/metabase/legacy_mbql/schema.cljc@@ -1787,6 +1787,7 @@[:qp/stage-is-from-source-card {:optional true} [:ref ::lib.schema.id/card]][:qp/stage-had-source-card {:optional true} [:ref ::lib.schema.id/card]][:qp/skip-persisted-cache {:optional true} :boolean]+ [:qp.pivot/forced-shape {:optional true} [:enum :native-pivot-query :union-all]][:persisted-info/native {:optional true} ::lib.schema.common/non-blank-string][:source-query/model? {:optional true} :boolean][:source-query/native-model? {:optional true} [:maybe :boolean]]diff --git a/src/metabase/lib/metadata/result_metadata.cljc b/src/metabase/lib/metadata/result_metadata.cljcindex 4ec21258910..d782800ec7e 100644--- a/src/metabase/lib/metadata/result_metadata.cljc+++ b/src/metabase/lib/metadata/result_metadata.cljc@@ -306,10 +306,15 @@;;; TODO (Cam 6/12/25) -- all this stuff should be moved into the main [[metabase.lib.field]] namespace as and done;;; automatically when [[lib.ref/*ref-style*]] is `:ref.style/broken-legacy-qp-results`(mu/defn- super-broken-legacy-field-ref :- [:maybe ::mbql.s/Reference]- "Generate a SUPER BROKEN legacy field ref for backward-compatibility purposes for frontend viz settings usage."+ "Generate a SUPER BROKEN legacy field ref for backward-compatibility purposes for frontend viz settings usage.++ The synthetic pivot-grouping column is skipped — the multi-query pivot path splices it in fresh (no+ `:field_ref`) via `metabase.query-processor.pivot.middleware/add-pivot-grouping`, so the SQL native path+ emits nothing here for parity with what the FE contract already sees for that column."[query :- ::lib.schema/querycol :- ::kebab-cased-map]- (when (= (:lib/type col) :metadata/column)+ (when (and (= (:lib/type col) :metadata/column)+ (not= (:lib/source col) :source/pivot-grouping))(let [remove-join-alias? (remove-join-alias-from-broken-field-ref? query col)](-> (binding [lib.ref/*ref-style* :ref.style/broken-legacy-qp-results](let [col (cond-> coldiff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljcindex b145f853d5a..43249dc4bd9 100644--- a/src/metabase/lib/schema.cljc+++ b/src/metabase/lib/schema.cljc@@ -88,6 +88,7 @@[:qp/stage-had-source-card {:optional true} [:ref ::id/card]][:qp/added-implicit-fields? {:optional true} :boolean][:qp/skip-persisted-cache {:optional true} :boolean]+ [:qp.pivot/forced-shape {:optional true} [:enum :native-pivot-query :union-all]][:persisted-info/native {:optional true} ::common/non-blank-string][:source-query/model? {:optional true} :boolean][:source-query/native-model? {:optional true} [:maybe :boolean]]diff --git a/src/metabase/query_processor/middleware/check_features.clj b/src/metabase/query_processor/middleware/check_features.cljindex b1bcde200ea..21bef9825e8 100644--- a/src/metabase/query_processor/middleware/check_features.clj+++ b/src/metabase/query_processor/middleware/check_features.clj@@ -1,5 +1,4 @@(ns metabase.query-processor.middleware.check-features- (:refer-clojure :exclude [some])(:require[metabase.driver :as driver][metabase.driver.util :as driver.u]@@ -10,8 +9,7 @@[metabase.query-processor.error-type :as qp.error-type][metabase.util :as u][metabase.util.i18n :refer [tru]]- [metabase.util.malli :as mu]- [metabase.util.performance :refer [some]]))+ [metabase.util.malli :as mu]))(defn- assert-driver-supports"Assert that the driver/database supports keyword `feature`."@@ -40,8 +38,6 @@(when (= path-type :lib.walk/join)(vswap! required-features conj! (:strategy join)))nil))- (when (some :pivot (:stages query))- (vswap! required-features conj! :native-pivot-tables))(persistent! @required-features)))(defn check-featuresdiff --git a/src/metabase/query_processor/middleware/fix_bad_field_id_refs.clj b/src/metabase/query_processor/middleware/fix_bad_field_id_refs.cljindex c4f07a75865..410bb25da4d 100644--- a/src/metabase/query_processor/middleware/fix_bad_field_id_refs.clj+++ b/src/metabase/query_processor/middleware/fix_bad_field_id_refs.clj@@ -32,7 +32,8 @@query path &match)](lib/update-options (lib/ref resolved)merge- (select-keys opts [:lib/expression-name+ (select-keys opts [:lib/uuid+ :lib/expression-name::qp.add-remaps/original-field-dimension-id::qp.add-remaps/new-field-dimension-id])))))&match)))diff --git a/src/metabase/query_processor/pivot.clj b/src/metabase/query_processor/pivot.cljindex ad85bf39289..dd3c95a5fa9 100644--- a/src/metabase/query_processor/pivot.clj+++ b/src/metabase/query_processor/pivot.clj@@ -12,6 +12,7 @@(:refer-clojure :exclude [every? mapv some select-keys update-keys empty? not-empty get-in])(:require[medley.core :as m]+ [metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]@@ -35,7 +36,6 @@[metabase.query-processor.middleware.normalize-query :as qp.middleware.normalize][metabase.query-processor.pipeline :as qp.pipeline][metabase.query-processor.pivot.common :as pivot.common]- [metabase.query-processor.preprocess :as qp.preprocess][metabase.query-processor.reducible :as qp.reducible][metabase.query-processor.schema :as qp.schema][metabase.query-processor.settings :as qp.settings]@@ -50,6 +50,10 @@(set! *warn-on-reflection* true)+(def group-bitmask+ "Re-export of [[metabase.query-processor.pivot.common/group-bitmask]]."+ pivot.common/group-bitmask)+(defn- powerset"Generate a powerset while maintaining the original ordering as much as possible"[xs]@@ -81,6 +85,32 @@#(or (empty? %)(apply distinct? %))]])+(defn- validate-pivot-indices!+ "Throw an `:invalid-query` error if any index in `pivot-rows` or `pivot-cols` falls outside+ `[0, num-breakouts)`."+ [num-breakouts pivot-rows pivot-cols]+ (doseq [[k pivots] [[:pivot-rows pivot-rows]+ [:pivot-cols pivot-cols]]+ i pivots]+ (when (or (neg? i) (>= i num-breakouts))+ (throw (ex-info (tru "Invalid {0}: specified breakout at index {1}, but we only have {2} breakouts"+ (name k) i num-breakouts)+ {:type qp.error-type/invalid-query+ :num-breakouts num-breakouts+ :pivot-rows pivot-rows+ :pivot-cols pivot-cols})))))++(defmacro ^:private wrapping-pivot-generation-errors+ "Rewrap any throw from `body` as `\"Error generating pivot queries\"` of type `:qp`, matching the+ outer error shape every pivot path presents to the QP's error handling."+ [query & body]+ `(try+ ~@body+ (catch Throwable e#+ (throw (ex-info (tru "Error generating pivot queries")+ {:type qp.error-type/qp, :query ~query}+ e#)))))+(mu/defn breakout-combinations :- ::pivot.common/breakout-combinations"Return a sequence of all breakout combinations (by index) we should generate queries for.@@ -92,17 +122,7 @@show-column-totals :- [:maybe :boolean]](let [row-totals (if (nil? show-row-totals) true show-row-totals)col-totals (if (nil? show-column-totals) true show-column-totals)]- ;; validate pivot-rows/pivot-cols- (doseq [[k pivots] [[:pivot-rows pivot-rows]- [:pivot-cols pivot-cols]]- i pivots]- (when (>= i num-breakouts)- (throw (ex-info (tru "Invalid {0}: specified breakout at index {1}, but we only have {2} breakouts"- (name k) i num-breakouts)- {:type qp.error-type/invalid-query- :num-breakouts num-breakouts- :pivot-rows pivot-rows- :pivot-cols pivot-cols}))))+ (validate-pivot-indices! num-breakouts pivot-rows pivot-cols)(sort-by(partial pivot.common/group-bitmask num-breakouts)(m/distinct-by@@ -160,26 +180,28 @@"Generate the additional queries to perform a generic pivot table"[query :- ::lib.schema/query{:keys [pivot-rows pivot-cols show-row-totals show-column-totals] :as _pivot-options} :- ::pivot-opts]- (try- (let [all-breakouts (lib/breakouts query)- all-queries (for [breakout-indexes (u/prog1 (breakout-combinations (count all-breakouts)- pivot-rows- pivot-cols- show-row-totals- show-column-totals)- (log/tracef "Using breakout combinations: %s" (pr-str <>)))]- (-> query- (assoc :qp.pivot/unremapped-breakout-combination breakout-indexes)- qp.nest-for-pivot/remove-non-aggregation-order-bys- (keep-breakouts-at-indexes breakout-indexes)))]- (conj (rest (map #(assoc-in % [:info :pivot/result-metadata] :none) all-queries))- (->- (assoc-in (first all-queries) [:info :pivot/original-query] query)- (assoc-in [:info :pivot/result-metadata] (qp.metadata/result-metadata query)))))- (catch Throwable e- (throw (ex-info (tru "Error generating pivot queries")- {:type qp.error-type/qp, :query query}- e)))))+ (wrapping-pivot-generation-errors query+ (let [all-breakouts (lib/breakouts query)+ all-queries (for [breakout-indexes (u/prog1 (breakout-combinations (count all-breakouts)+ pivot-rows+ pivot-cols+ show-row-totals+ show-column-totals)+ (log/tracef "Using breakout combinations: %s" (pr-str <>)))]+ (-> query+ (assoc :qp.pivot/unremapped-breakout-combination breakout-indexes)+ qp.nest-for-pivot/remove-non-aggregation-order-bys+ (keep-breakouts-at-indexes breakout-indexes)))]+ (conj (rest (map #(assoc-in % [:info :pivot/result-metadata] :none) all-queries))+ (->+ (assoc-in (first all-queries) [:info :pivot/original-query] query)+ (assoc-in [:info :pivot/result-metadata] (qp.metadata/result-metadata query)))))))++(defn- maybe-userland+ "Wrap `query` as a userland query when it carries a non-empty `:info` map."+ [query]+ (cond-> query+ (seq (:info query)) qp/userland-query))(mu/defn- process-query-append-results"Reduce the results of a single (sub)`query` using `rf` and initial value `init`."@@ -304,13 +326,10 @@pivot-limit :- [:maybe nat-int?]](if (empty? more-queries);; Single query - use normal QP pipeline to preserve userland metadata- (qp/process-query (cond-> first-query- (seq info) qp/userland-query)- rff)+ (qp/process-query (maybe-userland first-query) rff);; Multiple queries - use custom pivot pipeline(let [{:keys [rff execute reduce]} (append-queries-rff-and-fns info rff more-queries pivot-limit)- first-query (cond-> first-query- (seq info) qp/userland-query)]+ first-query (maybe-userland first-query)](binding [qp.pipeline/*execute* (or execute qp.pipeline/*execute*)qp.pipeline/*reduce* (or reduce qp.pipeline/*reduce*)](qp/process-query first-query rff)))))@@ -483,8 +502,8 @@legacy keys.Reads positional-index keys (`:pivot-rows` / `:pivot_rows`, `:pivot-cols` / `:pivot_cols`) and the- `show-*-totals` flags. Indices that fall outside the last stage's breakout vector are silently dropped.- `:pivot-measures` is presentation-only and is discarded.+ `show-*-totals` flags. Throws `:invalid-query` when any index falls outside the last stage's+ breakout vector. `:pivot-measures` is presentation-only and is discarded.If `query` already has a `:pivot` clause, only strips the legacy keys."[query :- ::lib.schema/query]@@ -495,9 +514,9 @@(and (nil? rows-idxs) (nil? cols-idxs)))stripped(let [breakouts (vec (:breakout (lib.util/query-stage query -1)))- n (count breakouts)+ _ (validate-pivot-indices! (count breakouts) rows-idxs cols-idxs)index->uuid (fn [i]- (when (and (nat-int? i) (< i n))+ (when (nat-int? i)(lib.options/uuid (nth breakouts i))))row-uuids (into [] (keep index->uuid) (or rows-idxs []))col-uuids (into [] (keep index->uuid) (or cols-idxs []))]@@ -509,28 +528,6 @@:show-row-totals (lib.pivot/read-show-flag query :show-row-totals :show_row_totals):show-column-totals (lib.pivot/read-show-flag query :show-column-totals :show_column_totals)}))))))-(defn- has-window-fn-aggregation?- "True iff any aggregation in the last stage of `query` contains a window-function aggregation clause at any depth."- [query]- (boolean (some lib.schema.aggregation/window-aggregation-expression?- (lib/aggregations query))))--(defn native-pivot-compatible?- "True iff the native MBQL5 pivot path can handle `query` end-to-end.-- Preprocesses the query first so the check sees the fully-expanded form — after metric/measure/segment- expansion and source-card inlining — and then rejects only when a known incompatibility remains."- [query]- ;; The set of incompatibility reasons is intentionally small: each entry must point at a specific demonstrated- ;; problem, never "just in case." Add new conditions by combining the existing predicates with `or` inside the- ;; `not`.- ;;- ;; Window-function aggregations: a running total over `GROUPING SETS` results would span detail rows AND- ;; subtotal rows, which is meaningless. The multi-query path runs one query per breakout combination, where- ;; these aggregations behave as expected. Importantly, this check has to see the EXPANDED query — a metric- ;; that resolves to `:cum-sum` is just as problematic as a `:cum-sum` written inline.- (not (has-window-fn-aggregation? (qp.preprocess/preprocess query))))-(defn- remapped-field[breakout](when (and (vector? breakout)@@ -660,21 +657,58 @@(get-in result [:cache/details :updated_at])))(defn- pivot-rows-equivalent?- "Compare pivot result maps from the two pivot paths. The candidate always uses `default-rff` and so carries- `(:data :rows)` and `:row_count`; the control uses the caller's rff and may carry anything.-- When comparing rows, each cell is normalised via [[round-numeric]] to tolerate float-associativity noise- between multi-`SUM` per-subquery and native `SUM` over `GROUPING SETS`.-- On mismatch — when at least one side was served from the QP cache — logs each side's cache `updated_at` so- that mismatches caused by asymmetric cache freshness (control served from a stale multi-path cache while- candidate ran fresh, or vice versa) can be distinguished from true code regressions."+ "Row-frequency equivalence for pivot results. Each cell is normalised via [[round-numeric]] to tolerate+ float-associativity noise between multi-`SUM` per-subquery and native `SUM` over `GROUPING SETS`. Falls+ back to `:row_count` when a caller-supplied rff didn't carry rows through, and to `true` when neither+ side exposes rows or a row count — the caller's rff (e.g. a bare-count reducer or a streaming HTTP+ writer) has reduced past what the parity checker can meaningfully compare."+ [r1 r2]+ (cond+ (and (map? r1) (-> r1 :data :rows)+ (map? r2) (-> r2 :data :rows))+ (= (frequencies (mapv #(mapv round-numeric %) (-> r1 :data :rows)))+ (frequencies (mapv #(mapv round-numeric %) (-> r2 :data :rows))))++ (and (map? r1) (:row_count r1)+ (map? r2) (:row_count r2))+ (= (:row_count r1) (:row_count r2))++ :else+ true))++(defn- ->cols-fingerprint+ "Extract the field-shape signature the FE contract cares about — `:name`, `:field_ref`, `:source`, and+ `:base_type` — for each column in `result`'s metadata. Ignores incidental fields (`:fingerprint`,+ `:lib/*`, `:table_id`, `:id`, `:display_name`, etc.) that legitimately differ between pivot paths, and+ drops the synthetic `pivot-grouping` column, which the multi-query post-processing middleware splices in+ fresh (no `:field_ref`) but the SQL native path emits as a real `SELECT` column (with a `:field_ref`)."+ [result]+ (into []+ (comp (remove #(= (:name %) lib.pivot/pivot-grouping-column-name))+ (map (fn [col] (select-keys col [:name :field_ref :source :base_type]))))+ (or (get-in result [:data :cols])+ (get-in result [:data :results_metadata :columns]))))++(defn pivot-cols-equivalent?+ "Column-metadata equivalence for pivot results — compares the [[->cols-fingerprint]] projection so pivot+ paths agree on the FE-visible shape (name/field_ref/source/base_type) even when rows legitimately differ+ (e.g. `:limit N` under multi-query applies per subquery)."+ [r1 r2]+ (= (->cols-fingerprint r1) (->cols-fingerprint r2)))++(def pivot-outcome-comparator+ "Predicate `(fn [r1 r2])` the parity checker uses to decide whether two pivot-flow outcomes agree. Defaults+ to [[pivot-rows-equivalent?]] (row-frequency compare). Tests whose paths legitimately diverge on rows but+ should agree on column metadata can override this via+ [[metabase.query-processor.pivot.test-util/with-metadata-only-parity]]."+ pivot-rows-equivalent?)++(defn- outcomes-data-equivalent?+ "Delegates to [[pivot-outcome-comparator]], then logs an asymmetric-cache warning when a mismatch shows+ the cache freshness diverged between the two sides (helps distinguish stale-cache flakes from real+ regressions)."[r1 r2]- (let [equivalent? (cond- (-> r1 :data :rows) (= (frequencies (mapv #(mapv round-numeric %) (-> r1 :data :rows)))- (frequencies (mapv #(mapv round-numeric %) (-> r2 :data :rows))))- (:row_count r1) (= (:row_count r1) (:row_count r2))- :else true)+ (let [equivalent? (pivot-outcome-comparator r1 r2)control-cached-at (cache-updated-at r1)candidate-cached-at (cache-updated-at r2)](when (and (not equivalent?)@@ -683,28 +717,32 @@control-cached-at candidate-cached-at))equivalent?))-(defn- ensure-pivot-clause- "Return `query` unchanged when its last stage already carries `:pivot`; otherwise attach a default `:pivot`- clause so the SQL compiler emits every subset of breakouts as its own grouping set (the powerset)."+(defn- maybe-add-default-pivot-clause+ "Attach a default `:pivot` clause to the last stage so the SQL compiler emits every subset of breakouts+ as its own grouping set (the powerset). Returns `query` unchanged when the last stage already carries+ `:pivot`, isn't an MBQL stage, or has no breakouts to pivot over."[query](cond-> query- (not (lib.pivot/has-pivot? query))+ (and (= :mbql.stage/mbql (:lib/type (lib.util/query-stage query -1)))+ (seq (:breakout (lib.util/query-stage query -1)))+ (not (lib.pivot/has-pivot? query)))(lib.pivot/with-pivot {:rows [] :columns [] :show-row-totals true :show-column-totals true})))-(defn- run-native-pivot-query+(defn- run-sql-pivot-query"Translate `query`'s pivot intent (legacy top-level keys and/or viz-settings) into an MBQL5 `:pivot` clauseon the last stage and submit to the standard QP through `rff`."[query rff](let [viz-settings (or (:viz-settings query)(get-in query [:info :visualization-settings]))- pivot-opts (pivot-opts-from-query query)]- (-> query- apply-legacy-pivot-keys- (apply-pivot-viz-settings viz-settings)- ensure-pivot-clause- (assoc-in [:middleware :pivot-options] pivot-opts)- (cond-> (seq (:info query)) qp/userland-query)- (qp/process-query rff))))+ pivot-opts (pivot-opts-from-query query)+ prepared (wrapping-pivot-generation-errors query+ (-> query+ apply-legacy-pivot-keys+ (apply-pivot-viz-settings viz-settings)+ maybe-add-default-pivot-clause+ (assoc-in [:middleware :pivot-options] pivot-opts)+ maybe-userland))]+ (qp/process-query prepared rff)))(defn- running-in-clojure-test?"True when a `clojure.test` test is currently on the stack — the presence of `*testing-vars*` is the@@ -716,7 +754,7 @@#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}(def ^:dynamic *check-pivot-parity?*"Controls whether [[run-pivot-query]] runs both the native and multi-query pivot paths whenever both are- applicable and reports disagreement via [[*on-parity-mismatch*]]. Left at the default sentinel+ applicable and reports disagreement via [[on-parity-mismatch]]. Left at the default sentinel`::default`, parity is on whenever a `clojure.test` test is currently running. Bind to `true` or`false` to override; the [[without-pivot-parity-check]] helper does exactly that for tests whosequeries intentionally diverge between the two paths."@@ -730,105 +768,189 @@::default (running-in-clojure-test?)(boolean *check-pivot-parity?*)))-(defn- default-on-parity-mismatch!- "Default handler for pivot parity mismatches: reports a `clojure.test` failure when a test is on the- stack — the two outcomes are handed to the reporter as `:expected` (multi-query) and `:actual` (native)- so the test runner prints the diff — and logs otherwise."- [{:keys [native-outcome multi-outcome] :as ctx}]- (if (running-in-clojure-test?)- ((requiring-resolve 'clojure.test/do-report)- {:type :fail- :message "Pivot parity mismatch — native and multi-query paths disagree"- :expected multi-outcome- :actual native-outcome})- (log/warnf "Pivot parity mismatch — native and multi-query paths disagree: %s" (pr-str ctx))))--#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}-(def ^:dynamic *on-parity-mismatch*- "Called with `{:native-outcome ..., :multi-outcome ...}` when the two pivot paths disagree under- [[*check-pivot-parity?*]]. Each outcome is either the result map returned by the path, or the- `Throwable` it threw. Defaults to [[default-on-parity-mismatch!]]."- default-on-parity-mismatch!)--(defn- native-path-applicable?- "True when `query` can be served by the native pivot path on `db`'s driver."- [db query]- (and (driver.u/supports? (:engine db) :native-pivot-tables db)- (native-pivot-compatible? query)))--(defn- run-secondary-for-parity- "Run the non-primary pivot path with the default rff and result handler purely to capture its outcome- for comparison. Returns `{:outcome ...}` on success or `{:throwable ...}` on failure."- [runner query]- (binding [qp.pipeline/*result* qp.pipeline/default-result-handler]- (try- {:outcome (runner query qp.reducible/default-rff)}- (catch Throwable t- {:throwable t}))))--(def ^:private throwable-signature- (juxt class ex-message ex-data))+(def ^:private pivot-flow-comparison-pairs+ "Pivot flow pairs the parity checker compares, in order. `:multi-query` is placed first in each pair that+ includes it so `do-report` renders it as `:expected` (the reference)."+ [[:multi-query :native-pivot-query]+ [:multi-query :union-all]+ [:native-pivot-query :union-all]])++(defn- failure-signature+ "Comparable `[class-name message]` for a failure's deepest cause. Accepts a `Throwable` (walks+ `ex-cause`) or a `catch-exceptions`-formatted `:status :failed` map (whose outer `:class` /+ `:error` are already the deepest cause's)."+ [failure]+ (letfn [(->class-name [c]+ (cond+ (nil? c) nil+ (instance? Class c) (.getName ^Class c)+ :else (name c)))]+ (cond+ (instance? Throwable failure)+ (let [root (loop [t failure] (if-let [c (ex-cause t)] (recur c) t))]+ [(->class-name (class root)) (ex-message root)])++ (and (map? failure) (= (:status failure) :failed))+ [(->class-name (:class failure)) (:error failure)])))(defn- outcomes-match?- "True when two `{:outcome ...}`/`{:throwable ...}` maps represent equivalent behavior — both threw- throwables with the same signature (see [[throwable-signature]]), or both succeeded with row-equivalent results."- [{primary-outcome :outcome primary-t :throwable}- {secondary-outcome :outcome secondary-t :throwable}]- (cond- (and primary-t secondary-t) (= (throwable-signature primary-t) (throwable-signature secondary-t))- (or primary-t secondary-t) false- :else (pivot-rows-equivalent? primary-outcome secondary-outcome)))+ "True when two pivot-flow outcome maps -- `{:outcome ...}` or `{:throwable ...}` -- agree: both+ failed with the same root-cause signature, or both succeeded on `pivot-outcome-comparator`."+ [{a-outcome :outcome a-throwable :throwable}+ {b-outcome :outcome b-throwable :throwable}]+ (let [a-failure (or a-throwable (when (= (:status a-outcome) :failed) a-outcome))+ b-failure (or b-throwable (when (= (:status b-outcome) :failed) b-outcome))]+ (cond+ (and a-failure b-failure) (= (failure-signature a-failure) (failure-signature b-failure))+ (or a-failure b-failure) false+ :else (outcomes-data-equivalent? a-outcome b-outcome))))++(defn- divergent-pivot-pairs+ "Vector of `[flow-a flow-b]` pairs (drawn in [[pivot-flow-comparison-pairs]] order) whose outcomes in+ `outcomes` disagree. Pairs where either side is missing (flow didn't run) are skipped."+ [outcomes]+ (into []+ (filter (fn [[a b]]+ (when-let [oa (get outcomes a)]+ (when-let [ob (get outcomes b)]+ (not (outcomes-match? oa ob))))))+ pivot-flow-comparison-pairs))(defn- outcome->reportable"The value inside an outcome map, whether success or failure."[{:keys [outcome throwable]}](or outcome throwable))+(defn- default-on-parity-mismatch!+ "Default handler for pivot parity mismatches: emits one `clojure.test/do-report` `:fail` per divergent pair+ when a test is on the stack (each pair's outcomes fed as `:expected` / `:actual` so the runner prints a+ diff), and logs otherwise."+ [{:keys [outcomes divergent-pairs]}]+ (if (running-in-clojure-test?)+ (doseq [[a b] divergent-pairs]+ ((requiring-resolve 'clojure.test/do-report)+ {:type :fail+ :message (str "Pivot parity mismatch — " (name a) " and " (name b) " paths disagree")+ :expected (outcome->reportable (get outcomes a))+ :actual (outcome->reportable (get outcomes b))}))+ (log/warnf "Pivot parity mismatch — divergent pairs %s; outcomes %s"+ (pr-str divergent-pairs)+ (pr-str (update-vals outcomes outcome->reportable)))))++(def on-parity-mismatch+ "Called with `{:outcomes {<flow> <outcome-map> ...} :divergent-pairs [[<flow-a> <flow-b>] ...]}` when the+ parity checker sees any divergence across the pivot flows it ran (a subset of `:native-pivot-query`,+ `:union-all`, `:multi-query`). Each outcome is a `{:outcome ...}` on success or `{:throwable ...}` on+ failure. `:divergent-pairs` preserves the order of [[pivot-flow-comparison-pairs]]. Defaults to+ [[default-on-parity-mismatch!]]; override via+ [[metabase.test.util.dynamic-redefs/with-dynamic-fn-redefs]] in tests."+ default-on-parity-mismatch!)++(defn- query-has-window-fn-aggregation?+ "True iff any aggregation in the last stage of the preprocessed `query` is a window-function aggregation."+ [query]+ (some? (some lib.schema.aggregation/window-aggregation-expression?+ (lib/aggregations query))))++(defn- run-pivot-flow+ "Run one pivot `flow` (`:multi-query`, `:native-pivot-query`, or `:union-all`) against `query`. The primary+ flow uses the caller's `rff` and lets `qp.pipeline/*result*` pass through; the others use the default rff+ and result handler purely to collect an outcome for comparison. Returns `{:outcome ...}` on success or+ `{:throwable ...}` on failure — annotated with `:elapsed-ms` and `:flow` so the parity checker (and CI+ log inspection) can see per-flow timings without extra plumbing."+ [flow query rff primary-flow]+ (let [primary? (= flow primary-flow)+ runner (if (= flow :multi-query) run-pivot-query-multi run-sql-pivot-query)+ force-shape (case flow+ :multi-query nil+ :native-pivot-query :native-pivot-query+ :union-all :union-all)+ scoped-query (cond-> query+ force-shape (lib.util/update-query-stage -1 assoc :qp.pivot/forced-shape force-shape))+ do-run (fn [rff]+ (let [t0 (System/nanoTime)+ result (try {:outcome (runner scoped-query rff)}+ (catch Throwable t {:throwable t}))]+ (assoc result :flow flow, :elapsed-ms (long (/ (- (System/nanoTime) t0) 1e6)))))]+ (if primary?+ (do-run rff)+ (binding [qp.pipeline/*result* qp.pipeline/default-result-handler]+ (do-run qp.reducible/default-rff)))))++(defn- driver-supports-grouping-sets?+ "True iff `query`'s driver supports the `:native-pivot-tables` feature — i.e. forcing the+ `:native-pivot-query` compilation shape would produce valid SQL."+ [query]+ (let [db (query-database query)]+ (driver.u/supports? (driver.u/database->driver db) :native-pivot-tables db)))+(defn- run-with-parity-check- "Run `primary` with the caller's `rff` (this is what the caller receives) and `secondary` with the- default rff purely to compare outcomes; report a mismatch via [[*on-parity-mismatch*]]. Returns- primary's success value or rethrows its exception."- [primary secondary query rff use-native?]- (let [primary-outcome (try {:outcome (primary query rff)}- (catch Throwable t {:throwable t}))- secondary-outcome (run-secondary-for-parity secondary query)- native-outcome (if use-native? primary-outcome secondary-outcome)- multi-outcome (if use-native? secondary-outcome primary-outcome)]- (when-not (outcomes-match? primary-outcome secondary-outcome)- (*on-parity-mismatch* {:native-outcome (outcome->reportable native-outcome)- :multi-outcome (outcome->reportable multi-outcome)}))- (if-let [t (:throwable primary-outcome)]- (throw t)- (:outcome primary-outcome))))+ "Run every applicable pivot flow — `:multi-query` always, `:union-all` on every SQL driver, and+ `:native-pivot-query` when the driver supports `:native-pivot-tables` and the query has no window-function+ aggregation — and report any pairwise divergence via [[on-parity-mismatch]]. The primary flow (per+ `sql-primary?` + GS applicability) uses the caller's `rff`; other flows use the default rff for+ comparison only. Returns the primary flow's success value or rethrows its exception.++ Logs a per-flow timing summary at WARN so CI logs surface which flow was slow and by how much when a+ mismatch or timeout occurs on some environment (e.g. Presto CI). Format: `pivot-parity {:driver ..+ :primary .. :outcomes {<flow> {:elapsed-ms .. :ok? .. :cause [..]}}}`. `:cause` is the ex-message chain+ (root cause first) — populated only for failing flows so a Presto `Socket closed` after the JDBC+ polling budget shows up plainly instead of the QP's wrapping `Error preparing statement` text."+ [query rff sql-primary?]+ (let [skip-gs? (or (query-has-window-fn-aggregation? query)+ (not (driver-supports-grouping-sets? query)))+ primary-flow (cond+ (not sql-primary?) :multi-query+ skip-gs? :union-all+ :else :native-pivot-query)+ flows (cond-> [:multi-query :union-all]+ (not skip-gs?) (conj :native-pivot-query))+ outcomes (into {} (map (fn [flow] [flow (run-pivot-flow flow query rff primary-flow)])) flows)+ divergent-pairs (divergent-pivot-pairs outcomes)+ cause-chain (fn [^Throwable t]+ (loop [t t, acc []]+ (if t (recur (.getCause t) (conj acc (.getMessage t))) acc)))]+ (log/warnf "pivot-parity %s"+ (pr-str {:driver (:engine (query-database query))+ :primary primary-flow+ :flows (update-vals outcomes+ (fn [{:keys [throwable elapsed-ms]}]+ (cond-> {:elapsed-ms elapsed-ms+ :ok? (nil? throwable)}+ throwable (assoc :cause (cause-chain throwable)))))+ :divergent-pairs divergent-pairs}))+ (when (seq divergent-pairs)+ (on-parity-mismatch {:outcomes outcomes, :divergent-pairs divergent-pairs}))+ (let [{:keys [outcome throwable]} (get outcomes primary-flow)]+ (if throwable (throw throwable) outcome))))(mu/defn- run-pivot-query*"Impl for [[run-pivot-query]]: pick the pivot implementation for `query` and run it through `rff`."[query :- ::qp.schema/any-queryrff :- ::qp.schema/rff]- (let [query (-> query- qp.middleware.normalize/normalize-preprocessing-middleware- lib/prepare-after-deserialization)- db (query-database query)- nativable? (native-path-applicable? db query)- use-native? (and nativable? (qp.settings/use-native-pivot-tables))- primary (if use-native? run-native-pivot-query run-pivot-query-multi)- secondary (if use-native? run-pivot-query-multi run-native-pivot-query)]+ (let [query (-> query+ qp.middleware.normalize/normalize-preprocessing-middleware+ lib/prepare-after-deserialization)+ db (query-database query)+ sql-driver? (isa? driver/hierarchy (:engine db) :sql)+ use-single-query? (and sql-driver? (qp.settings/use-native-pivot-tables))+ primary (if use-single-query? run-sql-pivot-query run-pivot-query-multi)](binding [qp.pipeline/*pivot?* true]- (if (and nativable? (pivot-parity-enabled?))- (run-with-parity-check primary secondary query rff use-native?)+ (if (and sql-driver? (pivot-parity-enabled?))+ (run-with-parity-check query rff use-single-query?)(primary query rff)))))(mu/defn run-pivot-query"Run the pivot `query` through `rff`.Dispatches between two implementations:- * **Native** — a single `GROUPING SETS` query, chosen when [[qp.settings/use-native-pivot-tables]] is on,- the driver supports `:native-pivot-tables`, and `query` is [[native-pivot-compatible?]].+ * **SQL** — a single query (GROUPING SETS or UNION ALL, per the SQL pivot compiler's dispatch), chosen when+ [[qp.settings/use-native-pivot-tables]] is on and the driver derives from `:sql`.* **Multi-query** — one query per breakout combination, results concatenated. Used otherwise.- When [[*check-pivot-parity?*]] is on and both paths are applicable, both run (primary via the caller's+ When [[*check-pivot-parity?*]] is on and the SQL path is applicable, both run (primary via the caller'srff, secondary via the default rff for comparison) and disagreement is reported via- [[*on-parity-mismatch*]]. Parity checking is on by default in clojure.test tests.+ [[on-parity-mismatch]]. Parity checking is on by default in clojure.test tests.A query with `:info` is run as a userland query, so any error iscaught and returned as a formatted error response rather than thrown.diff --git a/src/metabase/query_processor/util/transformations/nest_breakouts.clj b/src/metabase/query_processor/util/transformations/nest_breakouts.cljindex 854d010845a..88f684112a9 100644--- a/src/metabase/query_processor/util/transformations/nest_breakouts.clj+++ b/src/metabase/query_processor/util/transformations/nest_breakouts.clj@@ -1,20 +1,22 @@(ns metabase.query-processor.util.transformations.nest-breakouts"TODO (Cam 8/7/25) -- this is a pure-MBQL-5 high-level query transformation, and almost certainly belongs in Librather than in QP -- we should move it there. (This also applies to [[metabase.query-processor.util.nest-query]])."- (:refer-clojure :exclude [mapv select-keys some not-empty])+ (:refer-clojure :exclude [get-in mapv select-keys some not-empty])(:require[flatland.ordered.set :as ordered-set][medley.core :as m][metabase.lib.core :as lib][metabase.lib.equality :as lib.equality]+ [metabase.lib.options :as lib.options][metabase.lib.schema :as lib.schema][metabase.lib.schema.expression :as lib.schema.expression][metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.schema.util :as lib.schema.util][metabase.lib.walk :as lib.walk]+ [metabase.query-processor.middleware.add-remaps :as-alias add-remaps][metabase.util.malli :as mu][metabase.util.match :as match]- [metabase.util.performance :refer [mapv select-keys some not-empty]]))+ [metabase.util.performance :refer [get-in mapv select-keys some not-empty]]))(defn- stage-has-window-aggregation? [stage](match/match-one (:aggregation stage)@@ -37,10 +39,11 @@[#{:field :expression} & _] &match)))(mu/defn- new-first-stage :- ::lib.schema/stage- "Remove breakouts, aggregations, order bys, and limit. Add `:fields` to return the things needed by the second stage."+ "Remove breakouts, aggregations, order bys, limit, and pivot. Add `:fields` to return the things needed by the+ second stage."[stage :- ::lib.schema/stage](-> stage- (dissoc :breakout :aggregation :order-by :limit :lib/stage-metadata)+ (dissoc :breakout :aggregation :order-by :limit :lib/stage-metadata :pivot)(assoc :fields (mapvlib/fresh-uuids(fields-used-in-breakouts-aggregations-or-expressions stage)))))@@ -193,3 +196,50 @@(when (and (stage-has-window-aggregation? stage)(stage-has-breakout? stage))(nest-breakouts-in-stage query path stage)))))++(def ^:private remap-keep-opts+ "Add-remap option keys that must be preserved on breakout refs so the pivot compiler can still detect+ remap pairs after nesting rewrites the refs."+ [::add-remaps/original-field-dimension-id+ ::add-remaps/new-field-dimension-id])++(defn- reattach-remap-keys+ "Positionally copy `remap-keep-opts` from `old-breakouts` onto `new-breakouts` so a nested pivot stage's+ rewritten breakout refs still expose the `::add-remaps/*` dimension IDs the pivot compiler pairs on."+ [new-breakouts old-breakouts]+ (mapv (fn [new-b old-b]+ (let [carried (select-keys (lib.options/options old-b) remap-keep-opts)]+ (cond-> new-b+ (seq carried) (lib.options/update-options merge carried))))+ new-breakouts+ old-breakouts))++(mu/defn nest-pivot-joins :- ::lib.schema/query+ "Split `query`'s last stage into two via [[nest-breakouts-in-stage]] when it carries `:pivot`, joins, and+ breakouts; the first stage takes the source/joins/filters and projects the fields the second needs, and+ the second keeps `:pivot`/`:breakout`/`:aggregation` with refs rewritten. Positionally rewrites the+ `:pivot` clause's row/column UUIDs to match the second stage's regenerated breakout UUIDs, and copies+ add-remap dimension-id options ([[remap-keep-opts]]) forward so the pivot compiler still pairs remapped+ columns correctly. Returns `query` unchanged when the last stage has no `:pivot`, no joins, or no+ breakouts."+ {:added "0.64.0"}+ [query :- ::lib.schema/query]+ (let [path [:stages (dec (count (:stages query)))]+ last-stage (get-in query path)]+ (if (and (some? (:pivot last-stage))+ (seq (:joins last-stage))+ (stage-has-breakout? last-stage))+ (let [[first-stage second-stage] (nest-breakouts-in-stage query path last-stage)+ second-breakouts (reattach-remap-keys (:breakout second-stage) (:breakout last-stage))+ uuid-map (zipmap (mapv lib.options/uuid (:breakout last-stage))+ (mapv lib.options/uuid second-breakouts))+ rekey (fn [uuids] (mapv #(get uuid-map % %) uuids))+ second-stage' (-> second-stage+ (assoc :breakout second-breakouts)+ (update-in [:pivot :rows] rekey)+ (update-in [:pivot :columns] rekey))]+ (update query :stages+ (fn [stages]+ (-> (subvec stages 0 (dec (count stages)))+ (conj first-stage second-stage')))))+ query)))diff --git a/test/metabase/driver/sql/pivot_test.clj b/test/metabase/driver/sql/pivot_test.cljindex ca2b787d26b..981bbbf4c41 100644--- a/test/metabase/driver/sql/pivot_test.clj+++ b/test/metabase/driver/sql/pivot_test.clj@@ -1,12 +1,21 @@(ns metabase.driver.sql.pivot-test(:require- [clojure.test :refer [deftest is testing]]+ [clojure.test :refer [are deftest is testing]][honey.sql :as sql]+ [metabase.driver :as driver][metabase.driver.sql.pivot :as sql.pivot][metabase.driver.sql.query-processor :as sql.qp]+ [metabase.lib.core :as lib][metabase.lib.test-metadata :as meta]+ [metabase.lib.util :as lib.util][metabase.query-processor.store :as qp.store]))+(driver/register! ::sql-with-native-pivot, :parent :sql, :abstract? true)+(driver/register! ::sql-without-native-pivot, :parent :sql, :abstract? true)++(defmethod driver/database-supports? [::sql-with-native-pivot :native-pivot-tables]+ [_driver _feature _db] true)+;;; ----- HoneySQL formatters -----(deftest ^:parallel grouping-fn-formatter-test@@ -38,14 +47,59 @@(is (= ["GROUPING SETS ((col_a, col_b), (col_a), ())"](sql/format-expr [::sql.pivot/grouping-sets [:col-a :col-b] [:col-a] []])))))+;;; ----- stage-has-window-fn-aggregation? -----++(defn- orders-stage-with-aggs [& agg-clauses]+ (lib.util/query-stage+ (reduce lib/aggregate+ (lib/query meta/metadata-provider (meta/table-metadata :orders))+ agg-clauses)+ -1))++(deftest ^:parallel stage-has-window-fn-aggregation?-test+ (testing "false when the stage has no aggregations"+ (is (false? (#'sql.pivot/stage-has-window-fn-aggregation?+ (orders-stage-with-aggs)))))+ (testing "false when the stage has only non-window aggregations"+ (is (false? (#'sql.pivot/stage-has-window-fn-aggregation?+ (orders-stage-with-aggs+ (lib/count)+ (lib/sum (meta/field-metadata :orders :total)))))))+ (testing "true when a :cum-sum aggregation is present"+ (is (true? (#'sql.pivot/stage-has-window-fn-aggregation?+ (orders-stage-with-aggs+ (lib/count)+ (lib/cum-sum (meta/field-metadata :orders :total)))))))+ (testing "true when a window aggregation is nested inside an expression"+ (is (true? (#'sql.pivot/stage-has-window-fn-aggregation?+ (orders-stage-with-aggs+ (lib/- (lib/count) (lib/offset (lib/count) -1))))))))++;;; ----- use-grouping-sets? -----++(defn- lib-database [engine]+ {:lib/type :metadata/database, :id 1, :name "test-db", :engine engine})++(deftest ^:parallel use-grouping-sets?-test+ (testing "true only when the driver supports :native-pivot-tables AND there is no window aggregation"+ (let [db-with (lib-database ::sql-with-native-pivot)+ db-without (lib-database ::sql-without-native-pivot)+ plain-stage (orders-stage-with-aggs (lib/count))+ window-stage (orders-stage-with-aggs (lib/cum-count))]+ (are [database stage expected] (= expected (#'sql.pivot/use-grouping-sets? database stage))+ db-with plain-stage true+ db-with window-stage false+ db-without plain-stage false+ db-without window-stage false))))+;;; ----- apply-top-level-clause [:sql :pivot] -----(defn- field-clause [uuid alias field-id][:field {:lib/uuid uuid:metabase.query-processor.util.add-alias-info/source-alias alias} field-id])-(defn- lower-pivot- "Run the `[:sql :pivot]` dispatch and return its HoneySQL form result (not formatted SQL)."+(defn- compile-grouping-sets+ "Invoke `compile-grouping-sets-pivot` on a stage built from `breakouts` and `pivot`, returning its HoneySQL form."[breakouts pivot](qp.store/with-metadata-provider meta/metadata-provider(let [stage {:lib/type :mbql.stage/mbql@@ -55,7 +109,7 @@:pivot pivot}starting {:select [:b1] :group-by [:b1]}](binding [sql.qp/*inner-query* stage]- (sql.qp/apply-top-level-clause :sql :pivot starting stage)))))+ (#'sql.pivot/compile-grouping-sets-pivot :sql starting stage)))))(def ^:private b1-uuid "11111111-1111-1111-1111-111111111111")(def ^:private b2-uuid "22222222-2222-2222-2222-222222222222")@@ -70,14 +124,14 @@[[::sql.pivot/grouping-fn some?] "pivot-grouping"]]:group-by [[::sql.pivot/grouping-sets [some?] []]]:order-by [[[::sql.pivot/grouping-fn some?] :asc]]}- (lower-pivot [(b1)] {:rows [b1-uuid] :columns []- :show-row-totals true :show-column-totals true})))))+ (compile-grouping-sets [(b1)] {:rows [b1-uuid] :columns []+ :show-row-totals true :show-column-totals true})))))(deftest ^:parallel grouping-args-reversed-test(testing "GROUPING() args appear in reverse breakout order so bit 0 = first breakout"- (let [out (lower-pivot [(b1) (b2)]- {:rows [b1-uuid] :columns [b2-uuid]- :show-row-totals true :show-column-totals true})+ (let [out (compile-grouping-sets [(b1) (b2)]+ {:rows [b1-uuid] :columns [b2-uuid]+ :show-row-totals true :show-column-totals true})[tag a1 a2] (-> out :select last first)](testing "tag is ::grouping-fn and we have two args"(is (= ::sql.pivot/grouping-fn tag))@@ -92,21 +146,21 @@(deftest ^:parallel grouping-sets-shape-test(testing "2-breakout rows+cols pivot with both totals → 4 grouping sets including grand-total ()"- (let [out (lower-pivot [(b1) (b2)]- {:rows [b1-uuid] :columns [b2-uuid]- :show-row-totals true :show-column-totals true})+ (let [out (compile-grouping-sets [(b1) (b2)]+ {:rows [b1-uuid] :columns [b2-uuid]+ :show-row-totals true :show-column-totals true})[_tag & sets] (-> out :group-by first)](is (= 4 (count sets)))(is (some empty? sets) "one of the sets is the empty grand-total ()")))(testing "both totals off → only the detail grouping set"- (let [out (lower-pivot [(b1) (b2)]- {:rows [b1-uuid] :columns [b2-uuid]- :show-row-totals false :show-column-totals false})+ (let [out (compile-grouping-sets [(b1) (b2)]+ {:rows [b1-uuid] :columns [b2-uuid]+ :show-row-totals false :show-column-totals false})[_tag & sets] (-> out :group-by first)](is (= 1 (count sets)))(is (= 2 (count (first sets))) "the single set has both breakouts"))))-(defn- lower-pivot-with-order-by [breakouts pivot order-by]+(defn- compile-grouping-sets-with-order-by [breakouts pivot order-by](qp.store/with-metadata-provider meta/metadata-provider(let [stage {:lib/type :mbql.stage/mbql:source-table (meta/id :orders)@@ -115,12 +169,12 @@:pivot pivot}starting {:select [:b1] :group-by [:b1] :order-by order-by}](binding [sql.qp/*inner-query* stage]- (sql.qp/apply-top-level-clause :sql :pivot starting stage)))))+ (#'sql.pivot/compile-grouping-sets-pivot :sql starting stage)))))(deftest ^:parallel order-by-prepends-grouping-test(testing "GROUPING(...) ASC is prepended as the primary sort; existing :order-by entries pass through untouched(callers are expected to have already stripped non-aggregation order-bys upstream)"- (let [out (lower-pivot-with-order-by+ (let [out (compile-grouping-sets-with-order-by[(b1)]{:rows [b1-uuid] :columns [] :show-row-totals true :show-column-totals true}[[:count :desc]])]@@ -130,7 +184,7 @@(deftest ^:parallel order-by-skips-grouping-when-single-set-test(testing "When there is only one grouping set, the grouping bitmask is constant and the ORDER BY prefix is omitted"- (let [out (lower-pivot-with-order-by+ (let [out (compile-grouping-sets-with-order-by[(b1) (b2)]{:rows [b1-uuid] :columns [b2-uuid] :show-row-totals false :show-column-totals false}[[:count :desc]])]diff --git a/test/metabase/embedding_rest/api/embed_test.clj b/test/metabase/embedding_rest/api/embed_test.cljindex 565ac690c9e..a4e8e887156 100644--- a/test/metabase/embedding_rest/api/embed_test.clj+++ b/test/metabase/embedding_rest/api/embed_test.clj@@ -1683,13 +1683,18 @@:dataset_query {:database (mt/id):type :native:native {:query "SELECT * FROM no_such_table -- EMBED_ERROR_LEAK_SQL_CANARY"}}}]- (let [{:keys [status body]} (client/client-full-response :get (pivot-card-query-url card ""))- body-str (pr-str body)]- (is (= 500 status))- (is (= {:status "failed", :error "An error occurred while running the query.", :error_type "qp"}- body))- (is (not (str/includes? body-str "CANARY")))- (is (not (str/includes? body-str ":trace")))))))))+ ;; Both pivot flows fail with the same H2 "table not found" root cause, but H2 embeds the+ ;; compiled SQL in its error message and the compiled SQL has different Metabase-added+ ;; comments per path. The parity signature compares message text, so it flags this as a+ ;; divergence even though the user-visible outcome is identical.+ (api.pivots/without-pivot-parity-check+ (let [{:keys [status body]} (client/client-full-response :get (pivot-card-query-url card ""))+ body-str (pr-str body)]+ (is (= 500 status))+ (is (= {:status "failed", :error "An error occurred while running the query.", :error_type "qp"}+ body))+ (is (not (str/includes? body-str "CANARY")))+ (is (not (str/includes? body-str ":trace"))))))))))(deftest embed-card-query-exception-outside-qp-does-not-leak-test(testing "GET /api/embed/card/:token/query"diff --git a/test/metabase/lib/serialize_test.cljc b/test/metabase/lib/serialize_test.cljcindex 1275548bc9f..a91bcdda93a 100644--- a/test/metabase/lib/serialize_test.cljc+++ b/test/metabase/lib/serialize_test.cljc@@ -194,6 +194,7 @@:qp/stage-had-source-card 1:qp/added-implicit-fields? true:qp/skip-persisted-cache true+ :qp.pivot/forced-shape :union-all:persisted-info/native "SELECT * FROM cache_1":source-query/model? true:source-query/native-model? falsediff --git a/test/metabase/mcp/v2/tools/run_saved_question_test.clj b/test/metabase/mcp/v2/tools/run_saved_question_test.cljindex a6f7954a9fd..c5d585769ac 100644--- a/test/metabase/mcp/v2/tools/run_saved_question_test.clj+++ b/test/metabase/mcp/v2/tools/run_saved_question_test.clj@@ -17,6 +17,7 @@;; direct unit test of the private `check-parameter-value!`[metabase.mcp.v2.tools.query :as tools.query][metabase.permissions.core :as perms]+ [metabase.query-processor.pivot.test-util :as qp.pivot.tu][metabase.test :as mt][metabase.test.fixtures :as fixtures][metabase.util.json :as json]))@@ -386,11 +387,15 @@:columns ["VENDOR"]:values ["count"]}}}](mt/with-current-user (mt/user->id :rasta)- (let [payload (tool-result (call-run-saved-question {:id card-id :row_limit 5}))]- (is (= 5 (:returned payload)))- (is (= 5 (count (:rows payload))))- (is (true? (:truncated payload)))- (is (some? (::steering payload))))))))+ ;; Multi-query caps each subquery at row_limit → sum across combos; UA caps the total once.+ ;; Both flows produce the same column shape and the tool layer truncates to `row_limit`+ ;; downstream; don't compare row bags.+ (qp.pivot.tu/with-metadata-only-parity+ (let [payload (tool-result (call-run-saved-question {:id card-id :row_limit 5}))]+ (is (= 5 (:returned payload)))+ (is (= 5 (count (:rows payload))))+ (is (true? (:truncated payload)))+ (is (some? (::steering payload)))))))))(deftest ^:parallel numeric-string-id-parity-test(testing "GHY-4498: Claude Desktop sends every value of an int-or-string param as a JSON string,diff --git a/test/metabase/public_sharing_rest/api_test.clj b/test/metabase/public_sharing_rest/api_test.cljindex 5f66c691dc3..fdbbd5aeeee 100644--- a/test/metabase/public_sharing_rest/api_test.clj+++ b/test/metabase/public_sharing_rest/api_test.clj@@ -2142,9 +2142,15 @@:native {:query (str "SELECT * FROM no_such_table -- "error-leak-sql-canary)}}}](let [dashcard (add-card-to-dashboard! card dash)]- (is (nil? (:public_uuid card)))- (assert-generic-query-error- (client/client-full-response :get (pivot-dashcard-url dash card dashcard))))))))))+ ;; Both pivot flows fail with the same H2 "table not found" root cause, but H2 embeds the+ ;; compiled SQL in its error message and the compiled SQL has different Metabase-added+ ;; comments per path. The parity signature compares message text, so it flags this as a+ ;; divergence even though the user-visible outcome is identical. Disable parity for this+ ;; test rather than loosen the signature across the board.+ (api.pivots/without-pivot-parity-check+ (is (nil? (:public_uuid card)))+ (assert-generic-query-error+ (client/client-full-response :get (pivot-dashcard-url dash card dashcard)))))))))))(deftest public-card-query-exception-outside-qp-does-not-leak-test(testing "GET /api/public/card/:uuid/query"diff --git a/test/metabase/query_processor/middleware/fix_bad_field_id_refs_test.clj b/test/metabase/query_processor/middleware/fix_bad_field_id_refs_test.cljindex 026f9d4a074..21f4a9f0e15 100644--- a/test/metabase/query_processor/middleware/fix_bad_field_id_refs_test.clj+++ b/test/metabase/query_processor/middleware/fix_bad_field_id_refs_test.clj@@ -342,6 +342,20 @@qp.add-remaps/add-remapped-columnsfix-bad-field-id-refs/fix-bad-field-id-refs))))))+(deftest ^:parallel preserve-lib-uuid-when-fixing-field-id-ref-test+ (testing "rewriting bad ID refs preserves :lib/uuid so other clauses that reference the ref by uuid stay resolvable"+ (let [mp (-> meta/metadata-provider+ (lib.tu/metadata-provider-with-cards-for-queries+ [(lib/query meta/metadata-provider (meta/table-metadata :venues))]))+ card1 (lib.metadata/card mp 1)+ fk-id (meta/id :venues :category-id)+ pre-uuid (str (random-uuid))+ bad-ref [:field {:lib/uuid pre-uuid :base-type :type/Integer} fk-id]+ query (-> (lib/query mp card1)+ (assoc-in [:stages 0 :fields] [bad-ref]))]+ (is (=? {:stages [{:fields [[:field {:lib/uuid pre-uuid} "CATEGORY_ID"]]}]}+ (fix-bad-field-id-refs/fix-bad-field-id-refs query))))))+(deftest ^:parallel resolve-join-conditions-test(testing "Resolve fields in join :conditions"(let [mp (lib.tu/mock-metadata-providerdiff --git a/test/metabase/query_processor/pivot/test_util.clj b/test/metabase/query_processor/pivot/test_util.cljindex f1149cf596e..bc578b2a0e4 100644--- a/test/metabase/query_processor/pivot/test_util.clj+++ b/test/metabase/query_processor/pivot/test_util.clj@@ -108,3 +108,25 @@[& body]`(binding [qp.pivot/*check-pivot-parity?* false]~@body))++(defmacro with-metadata-only-parity+ "Compare pivot flows on column metadata (name/field_ref/source/base_type) only inside `body`, skipping the+ row-frequency check. Use for tests whose query intentionally diverges on rows between the multi-query+ and native paths (e.g. `:limit N` applied per-subquery) but should still agree on the FE-visible column+ shape."+ [& body]+ `(mt/with-dynamic-fn-redefs [qp.pivot/pivot-outcome-comparator qp.pivot/pivot-cols-equivalent?]+ ~@body))++(defmacro with-multi-query-pivot!+ "Force `run-pivot-query` to use the multi-query path inside `body` (by toggling+ `use-native-pivot-tables` off), and disable parity checking. Use for tests that assert multi-query-+ specific behavior (per-subquery row cap, subquery skipping, etc.) whose semantics don't translate to+ the single-query paths.++ Not thread-safe — do not use inside `^:parallel` tests; the site-wide setting toggle races other+ fixtures. The trailing `!` marks this side effect."+ [& body]+ `(mt/with-temporary-setting-values [use-native-pivot-tables false]+ (binding [qp.pivot/*check-pivot-parity?* false]+ ~@body)))diff --git a/test/metabase/query_processor/pivot_test.clj b/test/metabase/query_processor/pivot_test.cljindex 0bee9e11807..8a58d7675f4 100644--- a/test/metabase/query_processor/pivot_test.clj+++ b/test/metabase/query_processor/pivot_test.clj@@ -35,7 +35,9 @@[metabase.test.data :as data][metabase.util :as u][metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]))+ [metabase.util.malli.registry :as mr])+ (:import+ (clojure.lang ExceptionInfo)))(set! *warn-on-reflection* true)@@ -389,15 +391,15 @@(is (=? {:show-row-totals false :show-column-totals false} (pivot-of (qp.pivot/apply-legacy-pivot-keys q-kebab))))(is (=? {:show-row-totals false :show-column-totals false} (pivot-of (qp.pivot/apply-legacy-pivot-keys q-snake)))))))-(deftest ^:parallel apply-legacy-pivot-keys-drops-out-of-range-indices-test- (testing "out-of-range indices are silently dropped (matching legacy)"+(deftest ^:parallel apply-legacy-pivot-keys-throws-on-out-of-range-indices-test+ (testing "an out-of-range :pivot-rows index throws :invalid-query"(let [q (two-breakout-query-with-legacy-pivot-keys {:pivot-rows [0 5] :pivot-cols [99]})]- (is (=? {:rows [(breakout-uuid q 0)] :columns []}- (pivot-of (qp.pivot/apply-legacy-pivot-keys q))))))- (testing "no :pivot attached when every index is out of range"- (let [q (two-breakout-query-with-legacy-pivot-keys {:pivot-rows [5] :pivot-cols [99]})- out (qp.pivot/apply-legacy-pivot-keys q)]- (is (nil? (:pivot out))))))+ (is (thrown-with-msg? ExceptionInfo #"Invalid pivot-rows"+ (qp.pivot/apply-legacy-pivot-keys q)))))+ (testing "an out-of-range :pivot-cols index throws :invalid-query"+ (let [q (two-breakout-query-with-legacy-pivot-keys {:pivot-cols [99]})]+ (is (thrown-with-msg? ExceptionInfo #"Invalid pivot-cols"+ (qp.pivot/apply-legacy-pivot-keys q))))))(deftest ^:parallel apply-legacy-pivot-keys-strips-all-legacy-keys-test(testing "all 10 legacy key variants are stripped, including :pivot-measures"@@ -431,72 +433,6 @@(let [q (two-breakout-query)](is (= q (qp.pivot/apply-legacy-pivot-keys q))))))-;;; ---- native-pivot-compatible? ------(deftest ^:parallel native-pivot-compatible?-test- (let [base (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))- (lib/breakout (meta/field-metadata :orders :created-at)))]- (testing "queries without window-function aggregations are compatible"- (is (qp.pivot/native-pivot-compatible? (lib/aggregate base (lib/count)))))- (testing ":cum-count aggregation is not compatible"- (is (not (qp.pivot/native-pivot-compatible? (lib/aggregate base (lib/cum-count))))))- (testing ":cum-sum aggregation is not compatible"- (is (not (qp.pivot/native-pivot-compatible?- (lib/aggregate base (lib/cum-sum (meta/field-metadata :orders :total)))))))- (testing ":offset aggregation is not compatible"- (is (not (qp.pivot/native-pivot-compatible?- (lib/aggregate base (lib/offset (lib/count) -1))))))- (testing "window-function aggregation nested inside an arithmetic clause is not compatible"- (let [total (meta/field-metadata :orders :total)- diff (lib/expression-clause :- [(lib/sum total) (lib/offset (lib/sum total) -1)] nil)]- (is (not (qp.pivot/native-pivot-compatible? (lib/aggregate base diff)))))))- (testing "nested-field (e.g. JSON-unfolded) breakouts are compatible"- (let [json-mp (lib.tu/mock-metadata-provider- {:database (assoc meta/database :id 1)- :tables [(merge (meta/table-metadata :venues)- {:id 1 :db-id 1 :name "json_table"})]- :fields [(merge (meta/field-metadata :venues :id)- {:id 1- :table-id 1- :name "category"- :nfc-path ["payload" "category"]- :database-type "text"})]})- query (-> (lib/query json-mp (lib.metadata/table json-mp 1))- (lib/aggregate (lib/count))- (lib/breakout (lib.metadata/field json-mp 1)))]- (is (qp.pivot/native-pivot-compatible? query))))- (testing "metric whose definition is a window-function aggregation is incompatible"- (let [metric-query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))- (lib/aggregate (lib/cum-sum (meta/field-metadata :orders :total))))- metric-card {:lib/type :metadata/card- :id 10000- :entity-id (apply str (repeat 21 "X"))- :database-id (meta/id)- :name "Cumulative Total"- :type :metric- :dataset-query metric-query}- mp (lib.tu/mock-metadata-provider meta/metadata-provider {:cards [metric-card]})- query (-> (lib/query mp (lib.metadata/table mp (meta/id :orders)))- (lib/aggregate (lib.options/ensure-uuid [:metric {} (:id metric-card)]))- (lib/breakout (lib.metadata/field mp (meta/id :orders :created-at))))]- (is (not (qp.pivot/native-pivot-compatible? query)))))- (testing "source card with a window-function aggregation"- (let [card-query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))- (lib/breakout (meta/field-metadata :orders :created-at))- (lib/aggregate (lib/cum-sum (meta/field-metadata :orders :total))))- card {:lib/type :metadata/card- :id 10001- :entity-id (apply str (repeat 21 "Y"))- :database-id (meta/id)- :name "Cumulative by Day"- :type :question- :dataset-query card-query}- mp (lib.tu/mock-metadata-provider meta/metadata-provider {:cards [card]})- query (-> (lib/query mp (lib.metadata/card mp (:id card)))- (lib/aggregate (lib/count)))]- (testing "outer aggregations don't inherit the card's window-fn, so the pivot is compatible"- (is (qp.pivot/native-pivot-compatible? query))))))-(defn- capture-first-query"Return `[p stub]` where `stub` is a `qp/process-query` replacement that delivers its first-received query tothe promise `p` and returns a benign completed result."@@ -521,21 +457,21 @@(qp.pivot/run-pivot-query (qp.pivot.test-util/pivot-query)))(is (= 1 @invocations)))))))-(deftest ^:parallel native-and-multi-pivot-paths-stash-same-pivot-options-test+(deftest ^:parallel sql-and-multi-pivot-paths-stash-same-pivot-options-test(testing "the two pivot paths stash the same [:middleware :pivot-options] on the query given to qp/process-query"(mt/dataset test-data(qp.store/with-metadata-provider (mt/id)- (let [query (-> (qp.pivot.test-util/pivot-query)- qp.middleware.normalize/normalize-preprocessing-middleware)- [multi-p multi-stub] (capture-first-query)- [native-p native-stub] (capture-first-query)]+ (let [query (-> (qp.pivot.test-util/pivot-query)+ qp.middleware.normalize/normalize-preprocessing-middleware)+ [multi-p multi-stub] (capture-first-query)+ [sql-p sql-stub] (capture-first-query)](mt/with-dynamic-fn-redefs [qp.core/process-query multi-stub](#'qp.pivot/run-pivot-query-multi query nil))- (mt/with-dynamic-fn-redefs [qp.core/process-query native-stub]- (#'qp.pivot/run-native-pivot-query query nil))+ (mt/with-dynamic-fn-redefs [qp.core/process-query sql-stub]+ (#'qp.pivot/run-sql-pivot-query query nil))(is (some? (get-in @multi-p [:middleware :pivot-options])))- (is (= (get-in @multi-p [:middleware :pivot-options])- (get-in @native-p [:middleware :pivot-options]))))))))+ (is (= (get-in @multi-p [:middleware :pivot-options])+ (get-in @sql-p [:middleware :pivot-options]))))))))(deftest ^:mb/driver-tests pivot-with-expression-referencing-breakout-e2e-test(testing "pivot with a breakout that references an expression"@@ -1263,28 +1199,51 @@(mt/rows(qp.pivot/run-pivot-query query))))))))+(deftest ^:parallel single-combo-ua-preserves-user-order-by-test+ (testing "UA compilation must honor user :order-by when there's only one grouping-set combo"+ (let [mp (mt/metadata-provider)+ orders (lib.metadata/table mp (mt/id :orders))+ prod-id (lib.metadata/field mp (mt/id :orders :product_id))+ query (-> (lib/query mp orders)+ (lib/breakout prod-id)+ (lib/aggregate (lib/count))+ (as-> q (lib/order-by q (lib/aggregation-ref q 0) :desc))+ (merge {:pivot-rows [0]+ :pivot-cols []+ :show-row-totals false+ :show-column-totals false}))+ forced (lib.util/update-query-stage query -1 assoc :qp.pivot/forced-shape :union-all)+ counts (mapv last (mt/rows (qp.pivot/run-pivot-query forced)))]+ (is (apply >= counts)+ (str "Expected counts DESC; got: " counts)))))+(deftest ^:parallel fe-friendly-legacy-field-refs-test(testing "field_refs in the result metadata should match the 'traditional' legacy shape the FE expects, or it will break";; (This is calculated by [[metabase.lib.metadata.result-metadata/super-broken-legacy-field-ref]]);;;; `e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js` will break if the `field_ref`s don't come;; back in this EXACT shape =(, see [[metabase.query-processor.middleware.annotate/fe-friendly-legacy-ref]]- (let [query (merge- (mt/mbql-query orders- {:aggregation [[:count]]- :breakout [!year.created_at- $product_id->products.category- $user_id->people.source]- :limit 1})- {:pivot_rows [0 1 2]- :pivot_cols []})]- (is (= (mt/$ids orders- [[:field %created_at {:temporal-unit :year}]- [:field %products.category {:source-field %product_id}]- [:field %people.source {:source-field %user_id}]- nil ; pivot-grouping does not have a field ref- [:aggregation 0]])- (mapv :field_ref (mt/cols (qp.pivot/run-pivot-query query))))))))+ ;;+ ;; `:limit 1` applies per subquery under multi-query but only once under the single-query paths, so row+ ;; counts legitimately diverge. This assertion only cares about column metadata, so restrict the parity+ ;; check accordingly.+ (qp.pivot.test-util/with-metadata-only-parity+ (let [query (merge+ (mt/mbql-query orders+ {:aggregation [[:count]]+ :breakout [!year.created_at+ $product_id->products.category+ $user_id->people.source]+ :limit 1})+ {:pivot_rows [0 1 2]+ :pivot_cols []})]+ (is (= (mt/$ids orders+ [[:field %created_at {:temporal-unit :year}]+ [:field %products.category {:source-field %product_id}]+ [:field %people.source {:source-field %user_id}]+ nil ; pivot-grouping does not have a field ref+ [:aggregation 0]])+ (mapv :field_ref (mt/cols (qp.pivot/run-pivot-query query)))))))))(deftest ^:parallel fe-friendly-legacy-field-refs-test-2(testing "field_refs in the result metadata should preserve :base-type if it was specified for some reason, otherwise FE will break"@@ -1442,74 +1401,74 @@[str str int int int](qp.pivot/run-pivot-query query))))))))-(deftest ^:parallel pivot-query-uses-custom-limit-test+(deftest pivot-query-uses-custom-limit-test(testing "Pivot queries use a custom higher limit instead of the caller's constraints, so data stays consistent";; The multi-query path overrides the caller's `:constraints :max-results` with `pivot-query-max-rows`; the native;; single-query path doesn't, so results legitimately diverge — this test is multi-query-only.- (qp.pivot.test-util/without-pivot-parity-check- (mt/test-drivers (qp.pivot.test-util/applicable-drivers)- ;; The pivot-query has 2 aggregations (count, sum-of-quantity), so the pivot limit is 200k/2 = 100k.- ;; Even though we pass max-results=50, the pivot limit overrides it, so all rows come through.- (let [query (qp.pivot.test-util/pivot-query)- query (assoc query :constraints {:max-results 50})- results (qp.pivot/run-pivot-query query)- rows (mt/formatted-rows [str str str int int int] results)- ;; pivot-grouping is column index 3 (state, source, category, pivot-grouping, count, sum)- ;; Group 0 = all breakouts (detail rows)- ;; Group 7 = grand total (no breakouts)- detail-rows (filter #(zero? (nth % 3)) rows)- grand-total-row (first (filter #(= 7 (nth % 3)) rows))- detail-count-sum (reduce + (map #(nth % 4) detail-rows))- grand-total-count (nth grand-total-row 4)]- (testing "All detail rows are returned (not truncated to caller's max-results)"- (is (> (count detail-rows) 50)- "Detail rows should exceed the caller's max-results=50 because the pivot limit overrides it"))- (testing "The grand total row exists"- (is (some? grand-total-row)))- (testing "Detail rows sum to the grand total — data is consistent"- (is (= detail-count-sum grand-total-count)- (str "Detail count sum (" detail-count-sum ") should equal grand total ("- grand-total-count ") because pivot uses its own higher limit"))))))))--(deftest ^:parallel pivot-query-short-circuits-when-master-hits-limit-test+ (qp.pivot.test-util/with-multi-query-pivot!+ (mt/test-drivers (qp.pivot.test-util/applicable-drivers)+ ;; The pivot-query has 2 aggregations (count, sum-of-quantity), so the pivot limit is 200k/2 = 100k.+ ;; Even though we pass max-results=50, the pivot limit overrides it, so all rows come through.+ (let [query (qp.pivot.test-util/pivot-query)+ query (assoc query :constraints {:max-results 50})+ results (qp.pivot/run-pivot-query query)+ rows (mt/formatted-rows [str str str int int int] results)+ ;; pivot-grouping is column index 3 (state, source, category, pivot-grouping, count, sum)+ ;; Group 0 = all breakouts (detail rows)+ ;; Group 7 = grand total (no breakouts)+ detail-rows (filter #(zero? (nth % 3)) rows)+ grand-total-row (first (filter #(= 7 (nth % 3)) rows))+ detail-count-sum (reduce + (map #(nth % 4) detail-rows))+ grand-total-count (nth grand-total-row 4)]+ (testing "All detail rows are returned (not truncated to caller's max-results)"+ (is (> (count detail-rows) 50)+ "Detail rows should exceed the caller's max-results=50 because the pivot limit overrides it"))+ (testing "The grand total row exists"+ (is (some? grand-total-row)))+ (testing "Detail rows sum to the grand total — data is consistent"+ (is (= detail-count-sum grand-total-count)+ (str "Detail count sum (" detail-count-sum ") should equal grand total ("+ grand-total-count ") because pivot uses its own higher limit"))))))))++(deftest pivot-query-short-circuits-when-master-hits-limit-test(testing "When the master pivot query hits the row limit, remaining sub-queries are skipped and truncation is signaled";; The native pivot path is a single GROUPING SETS query, so the per-sub-query row cap doesn't apply — this test;; intentionally exercises multi-query-only behavior.- (qp.pivot.test-util/without-pivot-parity-check- (mt/test-drivers (qp.pivot.test-util/applicable-drivers)- ;; Use the standard pivot-query but override the pivot limit to be very small.- ;; The master query (state × source × category) produces ~200+ rows.- ;; With *pivot-max-result-rows* 20, the limit is 20/2=10 per sub-query.- (binding [qp.pivot/*pivot-max-result-rows* 20]- (let [query (qp.pivot.test-util/pivot-query)- results (qp.pivot/run-pivot-query query)- rows (mt/rows results)]- (testing "Only master query rows are returned (no subtotals/totals since sub-queries were skipped)"- ;; All rows should be pivot-grouping=0 (the master query's group)- (is (every? #(zero? (nth % 3)) rows)- "All rows should be from the master query (pivot-grouping=0)"))- (testing "The result includes pivot_rows_truncated flag"- (is (= 10 (get-in results [:data :pivot_rows_truncated]))- "Should signal truncation with the row count"))))))))+ (qp.pivot.test-util/with-multi-query-pivot!+ (mt/test-drivers (qp.pivot.test-util/applicable-drivers)+ ;; Use the standard pivot-query but override the pivot limit to be very small.+ ;; The master query (state × source × category) produces ~200+ rows.+ ;; With *pivot-max-result-rows* 20, the limit is 20/2=10 per sub-query.+ (binding [qp.pivot/*pivot-max-result-rows* 20]+ (let [query (qp.pivot.test-util/pivot-query)+ results (qp.pivot/run-pivot-query query)+ rows (mt/rows results)]+ (testing "Only master query rows are returned (no subtotals/totals since sub-queries were skipped)"+ ;; All rows should be pivot-grouping=0 (the master query's group)+ (is (every? #(zero? (nth % 3)) rows)+ "All rows should be from the master query (pivot-grouping=0)"))+ (testing "The result includes pivot_rows_truncated flag"+ (is (= 10 (get-in results [:data :pivot_rows_truncated]))+ "Should signal truncation with the row count"))))))))(deftest pivot-query-with-high-unaggregated-row-limit-test(testing "Pivot queries don't fail when MB_UNAGGREGATED_QUERY_ROW_LIMIT exceeds the pivot row limit (#72157)";; This exercises the multi-query path's per-sub-query constraint plumbing; the native path doesn't use it.- (qp.pivot.test-util/without-pivot-parity-check- (mt/test-drivers (qp.pivot.test-util/applicable-drivers)- ;; pivot-query has 2 aggregations, so pivot-limit = 20/2 = 10.- ;; Setting unaggregated-query-row-limit to 15 means max-results-bare-rows (15) > max-results (10),- ;; which violates the constraint schema without the fix.- ;; Pre-set :constraints like the API layer does (see qp.api/run-query-async+pivot).- (binding [qp.pivot/*pivot-max-result-rows* 20]- (mt/with-temporary-setting-values [qp.settings/unaggregated-query-row-limit 15]- (let [query (-> (qp.pivot.test-util/pivot-query)- (assoc :constraints (qp.constraints/default-query-constraints)))- results (qp.pivot/run-pivot-query query)]- (is (<= 2 (count (get-in query [:query :aggregation])))- "Sanity check: pivot-query should have at least 2 aggregations")- (is (not= :failed (:status results))- "Pivot query should not fail with a constraint violation"))))))))+ (qp.pivot.test-util/with-multi-query-pivot!+ (mt/test-drivers (qp.pivot.test-util/applicable-drivers)+ ;; pivot-query has 2 aggregations, so pivot-limit = 20/2 = 10.+ ;; Setting unaggregated-query-row-limit to 15 means max-results-bare-rows (15) > max-results (10),+ ;; which violates the constraint schema without the fix.+ ;; Pre-set :constraints like the API layer does (see qp.api/run-query-async+pivot).+ (binding [qp.pivot/*pivot-max-result-rows* 20]+ (mt/with-temporary-setting-values [qp.settings/unaggregated-query-row-limit 15]+ (let [query (-> (qp.pivot.test-util/pivot-query)+ (assoc :constraints (qp.constraints/default-query-constraints)))+ results (qp.pivot/run-pivot-query query)]+ (is (<= 2 (count (get-in query [:query :aggregation])))+ "Sanity check: pivot-query should have at least 2 aggregations")+ (is (not= :failed (:status results))+ "Pivot query should not fail with a constraint violation"))))))))(deftest ^:parallel native-pivot-honors-max-results-constraint-test(testing "Native pivot path honors the caller's :constraints :max-results — no special pivot-only cap"@@ -1527,7 +1486,7 @@:pivot_rows [0]:pivot_cols [1]})qp.middleware.normalize/normalize-preprocessing-middleware)- results (#'qp.pivot/run-native-pivot-query query nil)]+ results (#'qp.pivot/run-sql-pivot-query query nil)](testing "row count matches the requested cap"(is (= max-results (count (mt/rows results)))))(testing "result emits :pivot_rows_truncated (not :rows_truncated) so the FE pivot truncation warning fires"diff --git a/test_config/log4j2-test.xml b/test_config/log4j2-test.xmlindex 8698f4a62cf..247c40e080c 100644--- a/test_config/log4j2-test.xml+++ b/test_config/log4j2-test.xml@@ -40,6 +40,14 @@<AppenderRef ref="File"/></Logger>+ <!-- Pivot parity check emits per-flow timing + failure cause at WARN so a Presto (or other driver) CI+ failure surfaces which flow was slow and what root exception hit each flow, without needing the+ JSON log file (which CI doesn't publish). Diagnostic; safe to drop once UA is stable. -->+ <Logger name="metabase.query-processor.pivot" level="WARN" additivity="false">+ <AppenderRef ref="WarnConsole"/>+ <AppenderRef ref="File"/>+ </Logger>+<Root level="INFO"><AppenderRef ref="Console"/><AppenderRef ref="File"/>