Skip to content

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

Finish untangling the metadata knot (#61767)

Cam Saul5edd511b5b97
diff --git a/modules/drivers/mongo/test/metabase/test/data/mongo.clj b/modules/drivers/mongo/test/metabase/test/data/mongo.clj
index e6fe6ce5ecd..3706fb79149 100644
--- a/modules/drivers/mongo/test/metabase/test/data/mongo.clj
+++ b/modules/drivers/mongo/test/metabase/test/data/mongo.clj
@@ -95,7 +95,7 @@
(defmethod ddl.i/format-name :mongo
[_ table-or-field-name]
- (if (re-matches #"id(?:_\d+)?" table-or-field-name)
+ (if (re-matches #"id(?:_\d+)*" table-or-field-name)
(str "_" table-or-field-name)
table-or-field-name))
diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljc
index b6ae8149ce3..65621f8f1cf 100644
--- a/src/metabase/legacy_mbql/schema.cljc
+++ b/src/metabase/legacy_mbql/schema.cljc
@@ -42,11 +42,6 @@
;; the future we will likely add middleware that uses this metadata to automatically validate that a driver has the
;; features needed to run the query in question.
-(def ^:private PositiveInt
- [:schema
- {:description "Must be a positive integer."}
- pos-int?])
-
;; `:day-of-week` depends on the [[metabase.lib-be.core/start-of-week]] Setting, by default Sunday.
;; 1 = first day of the week (e.g. Sunday)
;; 7 = last day of the week (e.g. Saturday)
@@ -550,7 +545,7 @@
(if (number? x)
:number
:else))}
- [:number PositiveInt]
+ [:number pos-int?]
[:else NumericExpression]])
(def ^:private IntGreaterThanZeroOrNumericExpression
@@ -1168,9 +1163,9 @@
[:map
[:type [:= :snippet]]
[:snippet-name ::lib.schema.common/non-blank-string]
- [:snippet-id PositiveInt]
+ [:snippet-id ::lib.schema.id/snippet]
;; database to which this Snippet belongs. Doesn't always seen to be specified.
- [:database {:optional true} PositiveInt]]])
+ [:database {:optional true} ::lib.schema.id/database]]])
;; Example:
;;
@@ -1185,7 +1180,7 @@
TemplateTag:Common
[:map
[:type [:= :card]]
- [:card-id PositiveInt]]])
+ [:card-id ::lib.schema.id/card]]])
(def ^:private TemplateTag:Value:Common
"Stuff shared between the Field filter and raw value template tag schemas."
@@ -1564,8 +1559,8 @@
{:page 1, :items 10} = items 1-10
{:page 2, :items 10} = items 11-20"
[:map
- [:page PositiveInt]
- [:items PositiveInt]])
+ [:page pos-int?]
+ [:items pos-int?]])
(mr/def ::MBQLQuery
[:and
diff --git a/src/metabase/lib/aggregation.cljc b/src/metabase/lib/aggregation.cljc
index 9a00da0b279..1cd23f27312 100644
--- a/src/metabase/lib/aggregation.cljc
+++ b/src/metabase/lib/aggregation.cljc
@@ -13,6 +13,7 @@
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.aggregation :as lib.schema.aggregation]
[metabase.lib.schema.common :as lib.schema.common]
+ [metabase.lib.schema.mbql-clause :as lib.schema.mbql-clause]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.lib.temporal-bucket :as lib.temporal-bucket]
[metabase.lib.types.isa :as lib.types.isa]
@@ -159,8 +160,11 @@
:sum "sum"
:var "var"))
-(defmethod lib.metadata.calculation/display-name-method ::unary-aggregation
- [query stage-number [tag _opts arg] style]
+(mu/defmethod lib.metadata.calculation/display-name-method ::unary-aggregation
+ [query
+ stage-number
+ [tag _opts arg] :- [:ref ::lib.schema.mbql-clause/clause]
+ style]
(let [arg (lib.metadata.calculation/display-name query stage-number arg style)]
(case tag
:avg (i18n/tru "Average of {0}" arg)
diff --git a/src/metabase/lib/breakout.cljc b/src/metabase/lib/breakout.cljc
index 7e2f0003f97..84e140c91f1 100644
--- a/src/metabase/lib/breakout.cljc
+++ b/src/metabase/lib/breakout.cljc
@@ -32,15 +32,15 @@
stage-number :- :int]
(not-empty (:breakout (lib.util/query-stage query stage-number)))))
-(mu/defn breakouts-metadata :- [:maybe [:sequential ::lib.metadata.calculation/column-metadata-with-source]]
+(mu/defn breakouts-metadata :- [:maybe ::lib.metadata.calculation/visible-columns]
"Get metadata about the breakouts in a given stage of a `query`."
([query]
(breakouts-metadata query -1))
([query :- ::lib.schema/query
stage-number :- :int]
(some->> (breakouts query stage-number)
- (mapv (fn [field-ref]
- (-> (lib.metadata.calculation/metadata query stage-number field-ref)
+ (mapv (mu/fn [a-ref :- [:or :mbql.clause/field :mbql.clause/expression]]
+ (-> (lib.metadata.calculation/metadata query stage-number a-ref)
(assoc :lib/breakout? true)))))))
(mu/defn breakout :- ::lib.schema/query
diff --git a/src/metabase/lib/card.cljc b/src/metabase/lib/card.cljc
index 9f16ab05ec8..4947c553471 100644
--- a/src/metabase/lib/card.cljc
+++ b/src/metabase/lib/card.cljc
@@ -90,16 +90,13 @@
(when-some [card (lib.metadata/card metadata-providerable card-id)]
(= (:type card) :model))))
(assoc :lib/model-display-name (:display-name source-metadata-col)))
- col (cond-> (merge
- {:base-type :type/*, :lib/type :metadata/column}
- field-metadata
- (m/filter-vals some? source-metadata-col)
- {:lib/type :metadata/column
- :lib/source :source/card
- :lib/source-column-alias ((some-fn :lib/source-column-alias :name) source-metadata-col)})
- card-id
- (assoc :lib/card-id card-id)
-
+ col (merge
+ {:base-type :type/*, :lib/type :metadata/column}
+ field-metadata
+ (m/filter-vals some? source-metadata-col)
+ {:lib/type :metadata/column
+ :lib/source-column-alias ((some-fn :lib/source-column-alias :name) source-metadata-col)})
+ col (cond-> col
(:metabase.lib.field/temporal-unit source-metadata-col)
(assoc :inherited-temporal-unit (keyword (:metabase.lib.field/temporal-unit source-metadata-col)))
@@ -111,6 +108,8 @@
(assoc :fk-target-field-id nil))]
(-> col
lib.field.util/update-keys-for-col-from-previous-stage
+ (merge (when card-id
+ {:lib/source :source/card, :lib/card-id card-id}))
;; :effective-type is required, but not always set, see e.g.,
;; [[metabase.warehouse-schema.api.table/card-result-metadata->virtual-fields]]
(u/assoc-default :effective-type (:base-type col))
@@ -245,15 +244,15 @@
card :- ::lib.schema.metadata/card
options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
(mapv (fn [col]
- (assoc col :lib/source :source/card))
+ (assoc col :lib/source :source/card, :lib/card-id (:id card)))
(if (= (:type card) :metric)
(let [metric-query (-> card :dataset-query mbql.normalize/normalize lib.convert/->pMBQL
(lib.util/update-query-stage -1 dissoc :aggregation :breakout))]
- (not-empty (lib.metadata.calculation/returned-columns
- (assoc metric-query :lib/metadata (:lib/metadata query))
- -1
- (lib.util/query-stage metric-query -1)
- options)))
+ (lib.metadata.calculation/returned-columns
+ (assoc metric-query :lib/metadata (:lib/metadata query))
+ -1
+ (lib.util/query-stage metric-query -1)
+ options))
(card-metadata-columns query card))))
(mu/defn source-card-type :- [:maybe ::lib.schema.metadata/card.type]
diff --git a/src/metabase/lib/column_group.cljc b/src/metabase/lib/column_group.cljc
index 2948d5bd68f..5b1272e238d 100644
--- a/src/metabase/lib/column_group.cljc
+++ b/src/metabase/lib/column_group.cljc
@@ -141,7 +141,7 @@
:fk-join-alias (:fk-join-alias column-metadata)})
(defmethod column-group-info-method :source/joins
- [{:keys [table-id], card-id :lib/card-id, :as column-metadata}]
+ [{:keys [table-id], card-id :lib/card-id, :as col}]
(merge
{::group-type :group-type/join.explicit}
;; if we're in the process of BUILDING a join and using this in combination
@@ -149,7 +149,7 @@
;; joinable -- either the Card we're joining, or the Table we're joining. Prefer `:lib/card-id` because when we
;; join a Card the Fields might have `:table-id` but we want the entire Card to appear as one group. See #32493
(or
- (when-let [join-alias (lib.join.util/current-join-alias column-metadata)]
+ (when-let [join-alias (lib.join.util/current-join-alias col)]
{:join-alias join-alias})
(when card-id
{:card-id card-id})
diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljc
index ebfef6ecc94..b6b62d85cbc 100644
--- a/src/metabase/lib/core.cljc
+++ b/src/metabase/lib/core.cljc
@@ -21,6 +21,7 @@
[metabase.lib.extraction :as lib.extraction]
[metabase.lib.fe-util :as lib.fe-util]
[metabase.lib.field :as lib.field]
+ [metabase.lib.field.util]
[metabase.lib.filter :as lib.filter]
[metabase.lib.filter.update :as lib.filter.update]
[metabase.lib.join :as lib.join]
@@ -63,6 +64,7 @@
lib.extraction/keep-me
lib.fe-util/keep-me
lib.field/keep-me
+ metabase.lib.field.util/keep-me
lib.filter.update/keep-me
lib.filter/keep-me
lib.join/keep-me
@@ -241,6 +243,8 @@
find-visible-column-for-ref
remove-field
with-fields]
+ [metabase.lib.field.util
+ update-keys-for-col-from-previous-stage]
[lib.filter
filter
filters
@@ -328,6 +332,7 @@
with-native-query
with-template-tags]
[metabase.lib.options
+ ensure-uuid
options
update-options]
[lib.order-by
diff --git a/src/metabase/lib/equality.cljc b/src/metabase/lib/equality.cljc
index f3489fc304d..0ea3b5a9856 100644
--- a/src/metabase/lib/equality.cljc
+++ b/src/metabase/lib/equality.cljc
@@ -20,8 +20,7 @@
[metabase.lib.temporal-bucket :as lib.temporal-bucket]
[metabase.lib.util :as lib.util]
[metabase.util.log :as log]
- [metabase.util.malli :as mu]
- [metabase.util.malli.registry :as mr]))
+ [metabase.util.malli :as mu]))
(defmulti =
"Determine whether two already-normalized pMBQL maps, clauses, or other sorts of expressions are equal. The basic rule
@@ -427,72 +426,39 @@
(defn- ref-id-or-name [[_ref-kind _opts id-or-name]]
id-or-name)
-(mr/def ::match-type
- [:enum ::match-type.same-stage ::match-type.unknown])
-
-(mr/def ::match-options
- [:map
- {:closed true}
- [:match-type {:optional true} [:maybe ::match-type]]])
-
(mu/defn find-matching-ref :- [:maybe ::lib.schema.ref/ref]
"Given `column` and a list of `refs`, finds the ref that best matches this column.
Throws if there are multiple, ambiguous matches.
- Returns the matching ref, or nil if no plausible matches are found."
- ([column refs]
- (find-matching-ref column refs nil))
-
- ([column :- ::lib.schema.metadata/column
- refs :- [:sequential ::lib.schema.ref/ref]
- ;; `same-stage?` = refs and columns are known to be from the same stage (or join), so they should have matching
- ;; join aliases AND any string name refs should match `:lib/source-column-alias` (the string name in a field name
- ;; ref should be the SOURCE COLUMN ALIAS in the current stage; this is derived from the DESIRED COLUMN ALIAS from
- ;; the previous stage).
- {:keys [match-type], :or {match-type ::match-type.unknown}} :- [:maybe ::match-options]]
- (let [ref-tails (group-by ref-id-or-name refs)
- matches (or (when-let [source-uuid (:lib/source-uuid column)]
- (some (fn [a-ref]
- (when (= (lib.options/uuid a-ref) source-uuid)
- [a-ref]))
- refs))
- (case match-type
- ::match-type.same-stage
- ;; same stage match, use SOURCE COLUMN ALIAS!!!! IF YOU ARE NOT CLEAR ON WHY, TALK
- ;; TO YOUR BOY CAM!!!!
- (let [matches (let [col-join-alias (lib.join.util/current-join-alias column)
- source-column-alias ((some-fn :lib/source-column-alias :name) column)]
- (filter (fn [a-ref]
- (and (clojure.core/= (:join-alias (lib.options/options a-ref)) col-join-alias)
- (some #(clojure.core/= (ref-id-or-name a-ref) %)
- [(:id column) source-column-alias])))
- refs))]
- ;; if we fail to match with join alias then try to match by `:source-field`/`:fk-field-id`
- (if (= (count matches) 1)
- matches
- (when-let [fk-field-id (:fk-field-id column)]
- (filter (fn [a-ref]
- (= (:source-field (lib.options/options a-ref)) fk-field-id))
- refs))))
- ;; otherwise they're not the same stage, maybe the column is from an earlier stage
- ;; or maybe the refs are. WHO KNOWS!!!
- ::match-type.unknown
- (do
- (log/debug "Are refs from a previous stage that the column or the other way around? Who knows! Implement better match logic.")
- (or
- (not-empty (get ref-tails (:id column)))
- ;; columns from the previous stage have unique `:lib/desired-column-alias`
- ;; but not `:name`. we cannot fallback to `:name` when
- ;; `:lib/desired-column-alias` is set
- (get ref-tails ((some-fn :lib/desired-column-alias :name) column)))))
- [])]
- (case (count matches)
- 0 nil
- 1 (first matches)
- (throw (ex-info "Ambiguous match: given column matches multiple refs"
- {:column column
- :matching-refs matches}))))))
+ Returns the matching ref, or nil if no plausible matches are found.
+
+ `column` AND `refs` MUST BOTH BE RELATIVE TO THE SAME STAGE FOR THIS TO WORK CORRECTLY!!!!!!"
+ [column :- ::lib.schema.metadata/column
+ refs :- [:sequential ::lib.schema.ref/ref]]
+ (let [matches (or (when-let [source-uuid (:lib/source-uuid column)]
+ (some (fn [a-ref]
+ (when (= (lib.options/uuid a-ref) source-uuid)
+ [a-ref]))
+ refs))
+ ;; same stage match, use SOURCE COLUMN ALIAS!!!! IF YOU ARE NOT CLEAR ON WHY, TALK TO YOUR BOY
+ ;; CAM!!!!
+ (let [col-join-alias (lib.join.util/current-join-alias column)
+ col-source-field (:fk-field-id column)
+ source-column-alias ((some-fn :lib/source-column-alias :name) column)]
+ (filter (fn [a-ref]
+ (and (clojure.core/= (:join-alias (lib.options/options a-ref)) col-join-alias)
+ (clojure.core/= (:source-field (lib.options/options a-ref)) col-source-field)
+ (some #(clojure.core/= (ref-id-or-name a-ref) %)
+ [(:id column) source-column-alias])))
+ refs))
+ [])]
+ (case (count matches)
+ 0 nil
+ 1 (first matches)
+ (throw (ex-info "Ambiguous match: given column matches multiple refs"
+ {:column column
+ :matching-refs matches})))))
(mu/defn find-column-indexes-for-refs :- [:sequential :int]
"Given a list `haystack` of columns or refs, and a list `needles` of refs to searc for, this returns a list parallel
diff --git a/src/metabase/lib/expression.cljc b/src/metabase/lib/expression.cljc
index 9d86dc77818..a253ea86373 100644
--- a/src/metabase/lib/expression.cljc
+++ b/src/metabase/lib/expression.cljc
@@ -86,15 +86,16 @@
(let [expression (resolve-expression query stage-number expression-name)]
(lib.metadata.calculation/type-of query stage-number expression)))
-(defmethod lib.metadata.calculation/metadata-method :expression
+(mu/defmethod lib.metadata.calculation/metadata-method :expression :- ::lib.metadata.calculation/visible-column
[query stage-number [_expression opts expression-name, :as expression-ref-clause]]
- (merge {:lib/type :metadata/column
- :lib/source-uuid (:lib/uuid opts)
- :name expression-name
- :lib/expression-name expression-name
- :display-name (lib.metadata.calculation/display-name query stage-number expression-ref-clause)
- :base-type (lib.metadata.calculation/type-of query stage-number expression-ref-clause)
- :lib/source :source/expressions}
+ (merge {:lib/type :metadata/column
+ :lib/source-uuid (:lib/uuid opts)
+ :name expression-name
+ :lib/expression-name expression-name
+ :lib/source-column-alias expression-name
+ :display-name (lib.metadata.calculation/display-name query stage-number expression-ref-clause)
+ :base-type (lib.metadata.calculation/type-of query stage-number expression-ref-clause)
+ :lib/source :source/expressions}
(when-let [unit (lib.temporal-bucket/raw-temporal-bucket expression-ref-clause)]
{:metabase.lib.field/temporal-unit unit})
(when lib.metadata.calculation/*propagate-binning-and-bucketing*
@@ -414,9 +415,10 @@
;; not the properties of the expression.
(select-keys [:base-type :effective-type :lib/desired-column-alias
:lib/source-column-alias :lib/source-uuid :lib/type])
- (assoc :lib/source :source/expressions
- :name expression-name
- :display-name expression-name))))
+ (assoc :lib/source :source/expressions
+ :lib/expression-name expression-name
+ :name expression-name
+ :display-name expression-name))))
(mu/defn expressions-metadata :- [:maybe [:sequential ::lib.schema.metadata/column]]
"Get metadata about the expressions in a given stage of a `query`."
diff --git a/src/metabase/lib/field.cljc b/src/metabase/lib/field.cljc
index d8212964847..5c4c899c8ca 100644
--- a/src/metabase/lib/field.cljc
+++ b/src/metabase/lib/field.cljc
@@ -57,7 +57,7 @@
[_query _stage-number {field-name :name, :as field-metadata}]
(assoc field-metadata :name field-name))
-(mu/defmethod lib.metadata.calculation/metadata-method :field :- ::lib.schema.metadata/column
+(mu/defmethod lib.metadata.calculation/metadata-method :field :- ::lib.metadata.calculation/visible-column
[query stage-number field-ref]
(lib.field.resolution/resolve-field-ref query stage-number field-ref))
@@ -239,20 +239,20 @@
"unknown_field"))
(defmethod lib.metadata.calculation/display-info-method :metadata/column
- [query stage-number field-metadata]
+ [query stage-number col]
(merge
- ((get-method lib.metadata.calculation/display-info-method :default) query stage-number field-metadata)
+ ((get-method lib.metadata.calculation/display-info-method :default) query stage-number col)
;; These have to be calculated even if the metadata has display-name to support nested fields
;; because the query processor doesn't produce nested display-names.
- {:display-name (lib.metadata.calculation/display-name query stage-number field-metadata)
- :long-display-name (lib.metadata.calculation/display-name query stage-number field-metadata :long)}
+ {:display-name (lib.metadata.calculation/display-name query stage-number col)
+ :long-display-name (lib.metadata.calculation/display-name query stage-number col :long)}
;; Include description and fingerprint if they're present on the column. Only proper fields or columns from a model
;; have these, not aggregations or expressions.
- (u/select-non-nil-keys field-metadata [:description :fingerprint])
+ (u/select-non-nil-keys col [:description :fingerprint])
;; if this column comes from a source Card (Saved Question/Model/etc.) use the name of the Card as the 'table' name
;; rather than the ACTUAL table name.
- (when (= (:lib/source field-metadata) :source/card)
- (when-let [card-id (:lib/card-id field-metadata)]
+ (when (= (:lib/source col) :source/card)
+ (when-let [card-id (:lib/card-id col)]
(when-let [card (lib.metadata/card query card-id)]
{:table {:name (:name card), :display-name (:name card)}})))))
@@ -534,14 +534,15 @@
(defn- include-field [query stage-number column]
(let [populated (query-with-fields query stage-number)
field-refs (fields populated stage-number)
- match-ref (lib.equality/find-matching-ref column field-refs)
- column-ref (lib.ref/ref column)]
- (if (and match-ref
- (or (string? (last column-ref))
- (integer? (last match-ref))))
- ;; If the column is already found, do nothing and return the original query.
- query
- (lib.util/update-query-stage populated stage-number update :fields conj column-ref))))
+ matching-ref (lib.equality/find-matching-ref column field-refs)]
+ (if matching-ref
+ (do
+ (log/debugf "Column %s already included by ref %s, doing nothing and returning the original query"
+ (pr-str (select-keys column [:id :metabase.lib.join/join-alias :lib/source-column-alias]))
+ (pr-str matching-ref))
+ query)
+ (let [column-ref (lib.ref/ref column)]
+ (lib.util/update-query-stage populated stage-number update :fields conj column-ref)))))
(defn- add-field-to-join [query stage-number column]
(let [column-ref (lib.ref/ref column)
@@ -588,7 +589,7 @@
(let [stage (lib.util/query-stage query stage-number)
source (:lib/source column)]
(when (and (empty? (:fields stage))
- (not= source :source/joins))
+ (not (#{:source/implicitly-joinable :source/joins} source)))
(log/warnf "[add-field] stage :fields is empty, which means everything will already be included; attempt to add %s will no-op"
(pr-str ((some-fn :display-name :name) column))))
(-> (case source
@@ -610,8 +611,8 @@
lib.remove-replace/normalize-fields-clauses)))
(defn- remove-matching-ref [column refs]
- (let [match (or (lib.equality/find-matching-ref column refs {:match-type ::lib.equality/match-type.same-stage})
- (log/warnf "Failed to find match for column\n%s\nin refs:\n%s"
+ (let [match (or (lib.equality/find-matching-ref column refs)
+ (log/warnf "[remove-matching-ref] Failed to find match for column\n%s\nin refs:\n%s"
(u/pprint-to-str column)
(u/pprint-to-str refs)))]
(remove #(= % match) refs)))
@@ -639,7 +640,7 @@
;; Nothing to do if there's already no join fields.
query
(let [resolved-join-fields (if (= join-fields :all)
- (map lib.ref/ref (lib.metadata.calculation/returned-columns query stage-number join))
+ (map lib.ref/ref (lib.join/join-returned-columns-relative-to-parent-stage query stage-number join))
join-fields)
removed (remove-matching-ref column resolved-join-fields)]
(cond-> query
diff --git a/src/metabase/lib/field/resolution.cljc b/src/metabase/lib/field/resolution.cljc
index cca8dbd9a7b..9597ceee163 100644
--- a/src/metabase/lib/field/resolution.cljc
+++ b/src/metabase/lib/field/resolution.cljc
@@ -18,7 +18,11 @@
[metabase.lib.util :as lib.util]
[metabase.util :as u]
[metabase.util.log :as log]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]))
+
+(mr/def ::id-or-name
+ [:or :string ::lib.schema.id/field])
(defn- merge-metadata
[m & more]
@@ -50,7 +54,7 @@
;; this is used by the `display-name-method` for `:metadata/column` in [[metabase.lib.field]]
:metabase.lib.field/simple-display-name new-display-name)))))
-(mu/defn- field-metadata :- [:maybe ::lib.metadata.calculation/column-metadata-with-source]
+(mu/defn- field-metadata :- [:maybe ::lib.metadata.calculation/visible-column]
"Metadata about the field from the metadata provider."
[metadata-providerable :- ::lib.schema.metadata/metadata-providerable
field-id :- ::lib.schema.id/field]
@@ -58,6 +62,7 @@
(when-some [col (lib.metadata/field metadata-providerable field-id)]
(-> col
(assoc :lib/source :source/table-defaults
+ :lib/source-column-alias (:name col)
:lib/original-name (:name col)
:lib/original-display-name (:display-name col))
(->> (add-parent-column-metadata metadata-providerable)))))
@@ -73,11 +78,14 @@
[:lib/desired-column-alias
:lib/deduplicated-name]))
-(mu/defn- resolve-in-metadata :- [:maybe ::lib.schema.metadata/column]
- "Find the matching column metadata in `cols` for `id-or-name`."
+(mu/defn- resolve-in-previous-stage-metadata-without-updating-keys :- [:maybe ::lib.schema.metadata/column]
+ "Find the matching column metadata in `cols` for `id-or-name`.
+
+ This metadata should be relative to the previous stage, or join, or whatever!!!! It should not be relative to the
+ current stage."
[metadata-providerable :- ::lib.schema.metadata/metadata-providerable
cols :- [:sequential ::lib.schema.metadata/column]
- id-or-name :- [:or :string ::lib.schema.id/field]]
+ id-or-name :- ::id-or-name]
(letfn [(resolve* [id-or-name]
(if (string? id-or-name)
(column-with-name cols id-or-name)
@@ -97,7 +105,8 @@
(if <>
(log/debugf "Found match %s"
(pr-str (select-keys <> [:id :lib/desired-column-alias :lib/deduplicated-name])))
- (log/debugf "Failed to find match. Found:\n%s"
+ (log/debugf "Failed to find match for %s. Found:\n%s"
+ (pr-str id-or-name)
(u/pprint-to-str (map #(select-keys % [:id :lib/desired-column-alias :lib/deduplicated-name])
cols)))))))
@@ -222,8 +231,11 @@
#{:lib/card-id
:fingerprint})
-(defn- additional-metadata-from-source-card
- [query stage-number id-or-name]
+(mu/defn- additional-metadata-from-source-card :- [:maybe :map]
+ "Calculate additional metadata to include from a source model or Card for an already-resolved column."
+ [query :- ::lib.schema/query
+ stage-number :- :int
+ col :- ::lib.metadata.calculation/visible-column]
(let [stage (lib.util/query-stage query stage-number)]
(cond
(:qp/stage-had-source-card stage)
@@ -231,25 +243,40 @@
(when-some [card (lib.metadata/card query card-id)]
;; card returned columns should be the same regardless of which stage number we pass in, so always use the
;; last stage so we can hit the cache more often
- (when-some [card-cols (not-empty (lib.metadata.calculation/returned-columns query 0 card))]
- (when-some [col (resolve-in-metadata query card-cols id-or-name)]
- (let [propagated-keys (if (= (:type card) :model)
- model-propagated-keys
- regular-card-propagated-keys)]
- (-> col
- lib.field.util/update-keys-for-col-from-previous-stage
- (assoc :lib/card-id card-id)
- (select-keys propagated-keys)))))))
+ (when-some [card-cols (not-empty (cond->> (lib.metadata.calculation/returned-columns query 0 card)
+ ;; if we have `id` then filter out anything that is definitely not a
+ ;; match
+ (:id col) (filter #(= (:id %) (:id col)))))]
+ (let [card-cols (for [col card-cols]
+ (-> col
+ lib.field.util/update-keys-for-col-from-previous-stage
+ (assoc :lib/source :source/card, :lib/card-id card-id)))]
+ ;; prefer resolution with `:lib/source-column-alias` over `:id` if we have it because it will be
+ ;; unique/unambiguous if multiple versions of the column (e.g. with different bucketing units) are
+ ;; returned
+ (when-some [col (resolve-in-previous-stage-metadata-without-updating-keys query card-cols (:lib/source-column-alias col))]
+ (let [propagated-keys (if (= (:type card) :model)
+ model-propagated-keys
+ regular-card-propagated-keys)]
+ (select-keys col propagated-keys)))))))
(:qp/stage-is-from-source-card stage)
(let [card-id (:qp/stage-is-from-source-card stage)]
{:lib/card-id card-id}))))
-(mu/defn- resolve-in-join :- [:maybe ::lib.metadata.calculation/column-metadata-with-source]
+(mu/defn- resolve-in-previous-stage-metadata-and-update-keys :- [:maybe ::lib.metadata.calculation/visible-column]
+ [query :- ::lib.schema/query
+ previous-stage-columns :- [:sequential ::lib.schema.metadata/column]
+ id-or-name :- [:or ::lib.schema.id/field :string]]
+ (log/tracef "Previous stage columns: %s" (pr-str (map (juxt :id :lib/desired-column-alias) previous-stage-columns)))
+ (when-some [col (resolve-in-previous-stage-metadata-without-updating-keys query previous-stage-columns id-or-name)]
+ (lib.field.util/update-keys-for-col-from-previous-stage col)))
+
+(mu/defn- resolve-in-join :- [:maybe ::lib.metadata.calculation/visible-column]
[query :- ::lib.schema/query
stage-number :- :int
join-alias :- ::lib.schema.join/alias
- id-or-name :- [:or :string ::lib.schema.id/field]]
+ id-or-name :- ::id-or-name]
(log/debugf "Resolving %s (join alias = %s) in joins in stage %s" (pr-str id-or-name) (pr-str join-alias) (pr-str stage-number))
;; find the matching join.
(let [stage (lib.util/query-stage query stage-number)]
@@ -262,46 +289,28 @@
(pr-str join-alias)
(pr-str stage-number))
(let [join-cols (lib.metadata.calculation/returned-columns query stage-number join)]
- (when-some [col (resolve-in-metadata query join-cols id-or-name)]
- (-> (merge
- ;; run this thru `update-keys-for-col-from-previous-stage` so things like binning or bucketing in the
- ;; last stage of the join don't get propagated incorrectly. Don't update source or desired aliases
- ;; tho since those should already be calculated correctly and running thru
- ;; `lib.field.util/update-keys-for-col-from-previous-stage` will mess them up.
- (-> (lib.field.util/update-keys-for-col-from-previous-stage col)
- (dissoc :lib/source-column-alias :lib/desired-column-alias))
- (select-keys col [:lib/source-column-alias :lib/desired-column-alias])
- ;; include the `fk-field-id` specified in the join
- (when-some [fk-field-id (:fk-field-id join)]
- {:fk-field-id fk-field-id}))
- ;; now make sure join alias and what not is still set correctly for a column coming directly from a join
- (as-> $col (lib.join/column-from-join query stage-number $col join-alias))))))
+ (when-some [col (resolve-in-previous-stage-metadata-and-update-keys query join-cols id-or-name)]
+ (-> col
+ (as-> $col (lib.join/column-from-join query stage-number $col join-alias))
+ (merge (select-keys join [:fk-field-id]))))))
;; a join with this alias does not exist at this stage of the query... try looking recursively in previous stage(s)
(do
(log/debugf "Join %s does not exist in stage %s, looking in previous stages"
(pr-str join-alias)
(pr-str stage-number))
(if-some [previous-stage-number (lib.util/previous-stage-number query stage-number)]
- (when-some [col (resolve-in-join query previous-stage-number join-alias id-or-name)]
- (-> col
- lib.field.util/update-keys-for-col-from-previous-stage
- (assoc :lib/source :source/previous-stage)))
+ (let [previous-stage-cols (filter #(= (:lib/original-join-alias %) join-alias)
+ (lib.metadata.calculation/returned-columns query previous-stage-number))]
+ (resolve-in-previous-stage-metadata-and-update-keys query previous-stage-cols id-or-name))
(do
- (log/debug "No more previous stages =(")
+ (log/debug "Unable to resolve in previous stage =(")
nil))))))
-(defn- resolve-in-previous-stage-cols [query previous-stage-columns id-or-name]
- (log/tracef "Previous stage columns: %s" (pr-str (map (juxt :id :lib/desired-column-alias) previous-stage-columns)))
- (when-some [col (resolve-in-metadata query previous-stage-columns id-or-name)]
- (-> col
- lib.field.util/update-keys-for-col-from-previous-stage
- (assoc :lib/source :source/previous-stage))))
-
-(mu/defn- resolve-in-implicit-join
+(mu/defn- resolve-in-implicit-join :- [:maybe ::lib.metadata.calculation/visible-column]
[query :- ::lib.schema/query
stage-number :- :int
source-field-id :- ::lib.schema.id/field
- id-or-name :- [:or :string ::lib.schema.id/field]]
+ id-or-name :- ::id-or-name]
(log/debugf "Resolving implicitly joined %s (source Field ID = %s) in stage %s"
(pr-str id-or-name) (pr-str source-field-id) (pr-str stage-number))
;; first, try to resolve the implicit join from the previous stage columns -- the join might have already been
@@ -318,7 +327,7 @@
(let [previous-stage-cols (filter #(= ((some-fn :fk-field-id :lib/original-fk-field-id) %)
source-field-id)
(lib.metadata.calculation/returned-columns query previous-stage-number))]
- (resolve-in-previous-stage-cols query previous-stage-cols id-or-name)))
+ (resolve-in-previous-stage-metadata-and-update-keys query previous-stage-cols id-or-name)))
;; if there is no previous stage or we were unable to find the column in a previous stage then that means the
;; implicit join is happening in the current stage.
(when-some [col (if (pos-int? id-or-name)
@@ -344,51 +353,62 @@
(when-some [fk-target-field-id (:fk-target-field-id source-field)]
(when-some [target-field (lib.metadata/field query fk-target-field-id)]
(when-some [target-table (lib.metadata/table query (:table-id target-field))]
- (resolve-in-metadata query
- (lib.metadata.calculation/returned-columns query target-table)
- id-or-name))))))]
+ ;; TODO (Cam 8/7/25) -- seems sorta weird to be
+ ;; using [[resolve-in-previous-stage-metadata-without-updating-keys]] here since the
+ ;; source table is technically in the same stage, alto if you think about it you can sort
+ ;; of think of a table as being the Ur-source of the entire query... either way this
+ ;; actually still works since `returned-columns` for a table includes desired column
+ ;; aliases.
+ (resolve-in-previous-stage-metadata-without-updating-keys
+ query
+ (lib.metadata.calculation/returned-columns query target-table)
+ id-or-name))))))]
;; if we managed to resolve it then update metadata appropriately.
(assoc col
:lib/source :source/implicitly-joinable
:fk-field-id source-field-id))))
-(mu/defn- resolve-in-previous-stage :- [:maybe ::lib.metadata.calculation/column-metadata-with-source]
+(mu/defn- resolve-in-previous-stage :- [:maybe ::lib.metadata.calculation/visible-column]
[query :- ::lib.schema/query
previous-stage-number :- :int
- id-or-name :- [:or :string ::lib.schema.id/field]]
+ id-or-name :- ::id-or-name]
(log/debugf "Resolving %s in previous stage returned columns" (pr-str id-or-name))
(when-some [previous-stage-columns (lib.metadata.calculation/returned-columns query previous-stage-number)]
- (resolve-in-previous-stage-cols query previous-stage-columns id-or-name)))
+ (resolve-in-previous-stage-metadata-and-update-keys query previous-stage-columns id-or-name)))
-(mu/defn- resolve-in-card-returned-columns :- [:maybe ::lib.metadata.calculation/column-metadata-with-source]
+(mu/defn- resolve-in-card-returned-columns :- [:maybe ::lib.metadata.calculation/visible-column]
[query :- ::lib.schema/query
source-card-id :- ::lib.schema.id/card
- id-or-name :- [:or :string ::lib.schema.id/field]]
+ id-or-name :- ::id-or-name]
(log/debugf "Resolving %s in source Card %s metadata" (pr-str id-or-name) (pr-str source-card-id))
(when-some [card (lib.metadata/card query source-card-id)]
- (let [card-metadata-columns (lib.metadata.calculation/returned-columns query 0 card)]
- (when-some [col (resolve-in-metadata query card-metadata-columns id-or-name)]
+ (let [card-metadata-columns (lib.metadata.calculation/returned-columns query card)]
+ (when-some [col (resolve-in-previous-stage-metadata-and-update-keys query card-metadata-columns id-or-name)]
(-> col
- lib.field.util/update-keys-for-col-from-previous-stage
(assoc :lib/source :source/card, :lib/card-id source-card-id))))))
-(mu/defn- resolve-in-card-or-stage-metadata :- [:maybe ::lib.metadata.calculation/column-metadata-with-source]
+(mu/defn- resolve-in-current-stage-metadata :- [:maybe ::lib.schema.metadata/column]
[query :- ::lib.schema/query
stage-number :- :int
- id-or-name :- [:or :string ::lib.schema.id/field]]
- (let [{source-card-id :source-card, :as stage} (lib.util/query-stage query stage-number)]
- ;; This must be the first stage. See if this stage has a `:source-card`; if so, look at its columns.
- (if source-card-id
- (resolve-in-card-returned-columns query source-card-id id-or-name)
- ;; otherwise look in `:lib/stage-metadata` -- this will be the only way we can resolve things for native stages.
+ id-or-name :- ::id-or-name]
+ (log/debugf "Resolving %s in current stage metadata" (pr-str id-or-name))
+ (let [stage (lib.util/query-stage query stage-number)]
+ (if-some [current-stage-metadata-columns (not-empty (get-in stage [:lib/stage-metadata :columns]))]
+ ;; TODO (Cam 8/7/25) -- sort of a hacc to add deduplicated names here just so we can properly
+ ;; use [[resolve-in-previous-stage-metadata-without-updating-keys]], but we don't have any sort of
+ ;; `resolve-in-current-stage-metadata` function now. I guess it works tho
+ (let [current-stage-metadata-columns (lib.field.util/add-deduplicated-names current-stage-metadata-columns)]
+ (resolve-in-previous-stage-metadata-without-updating-keys query current-stage-metadata-columns id-or-name))
(do
- (log/debugf "Resolving %s in stage metadata" (pr-str id-or-name))
- (if-some [stage-metadata-columns (not-empty (get-in stage [:lib/stage-metadata :columns]))]
- (let [stage-metadata-columns (lib.field.util/add-deduplicated-names stage-metadata-columns)]
- (resolve-in-metadata query stage-metadata-columns id-or-name))
- (do
- (log/debug "stage has no attached metadata")
- nil))))))
+ (log/debug "stage has no attached metadata")
+ nil))))
+
+(mu/defn- resolve-in-source-card-metadata :- [:maybe ::lib.metadata.calculation/visible-column]
+ [query :- ::lib.schema/query
+ stage-number :- :int
+ id-or-name :- ::id-or-name]
+ (when-some [source-card-id (:source-card (lib.util/query-stage query stage-number))]
+ (resolve-in-card-returned-columns query source-card-id id-or-name)))
(defn- fallback-metadata [id-or-name]
(log/debug (u/colorize :red "Returning fallback metadata"))
@@ -399,12 +419,15 @@
:base-type :type/*
::fallback-metadata? true}
(if (pos-int? id-or-name)
- {:id id-or-name
- :name "Unknown Field"
- :display-name "Unknown Field"}
- {:name id-or-name})))
-
-(defn- resolve-from-previous-stage-or-source* [query stage-number id-or-name]
+ {:id id-or-name
+ :name "Unknown Field"
+ :lib/source-column-alias "Unknown Field"
+ :display-name "Unknown Field"}
+ {:name id-or-name
+ :lib/source-column-alias id-or-name})))
+
+(mu/defn- resolve-from-previous-stage-or-source* :- [:maybe ::lib.metadata.calculation/visible-column]
+ [query stage-number id-or-name]
(b/cond
:let [stage (lib.util/query-stage query stage-number)]
(and (pos-int? id-or-name)
@@ -416,21 +439,19 @@
col))
(= (:lib/type stage) :mbql.stage/native)
- (do
- (log/debugf "Resolving %s in native stage metadata" (pr-str id-or-name))
- (when-some [cols (get-in stage [:lib/stage-metadata :columns])]
- (let [cols (lib.field.util/add-deduplicated-names cols)]
- (when-some [col (resolve-in-metadata query cols id-or-name)]
- (assoc col :lib/source :source/native)))))
+ (when-some [col (resolve-in-current-stage-metadata query stage-number id-or-name)]
+ (-> col
+ (assoc :lib/source :source/native)
+ (u/assoc-default :lib/source-column-alias (:name col))))
(:source-card stage)
- (when-some [col (resolve-in-card-or-stage-metadata query stage-number id-or-name)]
- (assoc col :lib/source :source/card))
+ (when-some [col (resolve-in-source-card-metadata query stage-number id-or-name)]
+ (u/assoc-default col :lib/source-column-alias (:name col)))
(lib.util/previous-stage-number query stage-number)
(resolve-in-previous-stage query (lib.util/previous-stage-number query stage-number) id-or-name)))
-(defn- resolve-ref-missing-join-alias
+(mu/defn- resolve-ref-missing-join-alias :- [:maybe ::lib.metadata.calculation/visible-column]
"Try finding a match in joins (field ref is missing `:join-alias`)."
[query stage-number id-or-name]
(log/debugf "Assuming %s is from a join, and missing :join-alias" (pr-str id-or-name))
@@ -448,28 +469,32 @@
(log/debugf "Failed to find a match in one of the query's joins in stage %s" (pr-str stage-number))
nil)))
-(mu/defn- resolve-from-previous-stage-or-source :- ::lib.metadata.calculation/column-metadata-with-source
+(mu/defn- resolve-from-previous-stage-or-source :- ::lib.metadata.calculation/visible-column
[query :- ::lib.schema/query
stage-number :- :int
- id-or-name :- [:or :string ::lib.schema.id/field]]
+ id-or-name :- ::id-or-name]
(log/debugf "Resolving %s from previous stage, source table, or source card" (pr-str id-or-name))
- (merge-metadata
- (or (resolve-from-previous-stage-or-source* query stage-number id-or-name)
- (do
- (log/infof "Failed to resolve Field %s in stage %s" (pr-str id-or-name) (pr-str stage-number))
- (resolve-ref-missing-join-alias query stage-number id-or-name))
- ;; if we haven't found a match yet try getting metadata from the metadata provider if this is a Field ID ref.
- ;; It's likely a ref that makes little or no sense (e.g. wrong table) but we can let QP code worry about that.
- (when (pos-int? id-or-name)
- (when-some [col (field-metadata query id-or-name)]
- (assoc col ::fallback-metadata? true)))
- ;; if we STILL can't find a match, return made-up fallback metadata.
- (fallback-metadata id-or-name))
- (additional-metadata-from-source-card query stage-number id-or-name)))
-
-(mu/defn resolve-field-ref :- ::lib.metadata.calculation/column-metadata-with-source
+ (let [col (or (resolve-from-previous-stage-or-source* query stage-number id-or-name)
+ (do
+ (log/infof "Failed to resolve Field %s in stage %s" (pr-str id-or-name) (pr-str stage-number))
+ (resolve-ref-missing-join-alias query stage-number id-or-name))
+ ;; if we haven't found a match yet try getting metadata from the metadata provider if this is a
+ ;; Field ID ref. It's likely a ref that makes little or no sense (e.g. wrong table) but we can
+ ;; let QP code worry about that.
+ (when (pos-int? id-or-name)
+ (when-some [col (field-metadata query id-or-name)]
+ (assoc col ::fallback-metadata? true)))
+ ;; if we STILL can't find a match, return made-up fallback metadata.
+ (fallback-metadata id-or-name))]
+ (merge-metadata
+ col
+ (when col
+ (additional-metadata-from-source-card query stage-number col)))))
+
+(mu/defn resolve-field-ref :- ::lib.metadata.calculation/visible-column
"Resolve metadata for a `:field` ref. This is part of the implementation
- for [[metabase.lib.metadata.calculation/metadata-method]] a `:field` clause."
+ for [[metabase.lib.metadata.calculation/metadata-method]] a `:field` clause. Guaranteed to have
+ `:lib/source-column-alias` for wherever the hecc it comes from."
[query :- ::lib.schema/query
stage-number :- :int
[_tag {:keys [source-field join-alias], :as opts} id-or-name, :as field-ref] :- :mbql.clause/field]
@@ -485,16 +510,23 @@
(merge
(fallback-metadata id-or-name)
(when join-alias
- {:metabase.lib.join/join-alias join-alias})))
+ {:lib/source :source/joins
+ :metabase.lib.join/join-alias join-alias})))
(options-metadata opts)
{:lib/original-ref field-ref})
- (as-> $col (assoc $col :display-name (lib.metadata.calculation/display-name query stage-number $col))))))
+ (as-> $col (assoc $col :display-name (lib.metadata.calculation/display-name query stage-number $col)))
+ ;; `:lib/desired-column-alias` needs to be recalculated in the context of the stage where the ref appears, go
+ ;; ahead and remove it so we don't accidentally try to use it when it may or may not be accurate at all.
+ ;;
+ ;; We should OTOH keep `:lib/deduplicated-name`, because this is used to calculate subsequent deduplicated
+ ;; names, see [[metabase.lib.stage-test/return-correct-deduplicated-names-test]] for an example.
+ (dissoc :lib/desired-column-alias))))
;;;
;;; Helper functions for other namespaces
;;;
-(mu/defn resolve-column-in-metadata :- [:maybe ::lib.schema.metadata/column]
+(mu/defn resolve-column-in-previous-stage-metadata :- [:maybe ::lib.schema.metadata/column]
"Find the matching column metadata in `cols` for `field-ref`.
TODO (Cam 7/28/25) -- We should probably prefer [[lib.equality/find-matching-column]] directly instead; if this
@@ -503,4 +535,4 @@
[metadata-providerable :- ::lib.schema.metadata/metadata-providerable
[_tag _opts id-or-name, :as _field-ref] :- :mbql.clause/field
cols :- [:sequential ::lib.schema.metadata/column]]
- (resolve-in-metadata metadata-providerable cols id-or-name))
+ (resolve-in-previous-stage-metadata-without-updating-keys metadata-providerable cols id-or-name))
diff --git a/src/metabase/lib/field/util.cljc b/src/metabase/lib/field/util.cljc
index 5300ab3c07d..ce3cfa01b2a 100644
--- a/src/metabase/lib/field/util.cljc
+++ b/src/metabase/lib/field/util.cljc
@@ -17,16 +17,25 @@
(some? (#{:source/card :source/native :source/previous-stage} (:lib/source column))))
(mu/defn inherited-column-name :- [:maybe :string]
- "If the field ref for this `column` should be name-based, returns the name used in the field ref."
+ "If the field ref for this `column` should be name-based, returns the name used in the field ref.
+
+ `column` SHOULD BE METADATA RELATIVE TO THE CURRENT STAGE WHERE YOU ARE ADDING THE REF!!!!!!
+
+ Field name refs should use the `:lib/source-column-alias`, e.g.
+
+ [:field {} \"WHATEVER\"]
+
+ which should be the same as the `:lib/desired-column-alias` the previous stage or (last stage of the) join that it
+ came from."
[column :- ::lib.schema.metadata/column]
(when (inherited-column? column)
((some-fn
- ;; broken field refs never use `:lib/desired-column-alias`.
+ ;; broken field refs never use `:lib/source-column-alias`.
(case lib.ref/*ref-style*
- :ref.style/default :lib/desired-column-alias
+ :ref.style/default :lib/source-column-alias
:ref.style/broken-legacy-qp-results (constantly nil))
- :lib/deduplicated-name
- :lib/original-name
+ ;; if this is missing for some reason then fall back to `:name` -- probably wrong, but maybe not and it might
+ ;; still work.
:name)
column)))
@@ -45,10 +54,9 @@
([]
(let [deduplicated-name-fn (lib.util/non-truncating-unique-name-generator)]
(map (fn [col]
- (let [original-name ((some-fn :lib/original-name :name) col)]
- (assoc col
- :lib/original-name original-name
- :lib/deduplicated-name (deduplicated-name-fn ((some-fn :lib/deduplicated-name :name) col))))))))
+ (assoc col
+ :lib/original-name ((some-fn :lib/original-name :name) col)
+ :lib/deduplicated-name (deduplicated-name-fn ((some-fn :lib/deduplicated-name :name) col)))))))
([cols :- [:sequential ::lib.schema.metadata/column]]
(into []
@@ -71,12 +79,14 @@
:lib/source-column-alias source-alias
:lib/desired-column-alias desired-alias)))))))
-(mu/defn update-keys-for-col-from-previous-stage :- :map
+(mu/defn update-keys-for-col-from-previous-stage :- [:map
+ [:lib/type [:= :metadata/column]]]
"For a column that came from a previous stage, change the keys for things that mean 'this happened in the current
stage' to the equivalent keys that mean 'this happened at some stage in the past' e.g.
`:metabase.lib.join/join-alias` and `:lib/expression-name` become `:lib/original-join-alias` and
`:lib/original-expression-name` respectively."
- [col :- :map]
+ [col :- [:map
+ [:lib/type [:= :metadata/column]]]]
(-> col
(set/rename-keys {:fk-field-id :lib/original-fk-field-id
:fk-field-name :lib/original-fk-field-name
@@ -85,9 +95,18 @@
:metabase.lib.field/binning :lib/original-binning
:metabase.lib.field/temporal-unit :inherited-temporal-unit
:metabase.lib.join/join-alias :lib/original-join-alias})
- ;; TODO (Cam 7/25/25) -- shouldn't this set `:lib/source` as well?
(assoc :lib/breakout? false
;; TODO (Cam 6/26/25) -- should we set `:lib/original-display-name` here too?
:lib/original-name ((some-fn :lib/original-name :name) col)
;; desired-column-alias is previous stage => source column alias in next stage
- :lib/source-column-alias ((some-fn :lib/desired-column-alias :lib/source-column-alias :name) col))))
+ :lib/source-column-alias ((some-fn :lib/desired-column-alias :lib/source-column-alias :name) col)
+ :lib/source :source/previous-stage)
+ ;;
+ ;; Remove `:lib/desired-column-alias`, which needs to be recalculated in the context
+ ;; of what is returned by the current stage, to prevent any confusion; its value is likely wrong now and we
+ ;; don't want people to get confused by them. `visible-columns` is not supposed to return it, since we can't
+ ;; know their value without knowing what is actually returned.
+ ;;
+ ;; we should OTOH keep `:lib/deduplicated-name`, because this is used to calculate subsequent deduplicated
+ ;; names, see [[metabase.lib.stage-test/return-correct-deduplicated-names-test]] for an example.
+ (dissoc :lib/desired-column-alias)))
diff --git a/src/metabase/lib/join.cljc b/src/metabase/lib/join.cljc
index 174162d5c67..c65a743d779 100644
--- a/src/metabase/lib/join.cljc
+++ b/src/metabase/lib/join.cljc
@@ -102,7 +102,7 @@
(let [[operator opts lhs rhs] condition]
[operator opts lhs (apply f rhs args)])))
-(mu/defn- with-join-alias-update-join-conditions :- lib.join.util/PartialJoin
+(mu/defn- with-join-alias-update-join-conditions :- ::lib.join.util/partial-join
"Impl for [[with-join-alias]] for a join: recursively update the `:join-alias` for inside the `:conditions` of the
join.
@@ -113,7 +113,7 @@
[[join-condition-operators]], the LHS expression with columns from [[join-condition-lhs-columns]], the RHS expression
with columns from [[join-condition-rhs-columns]]). This currently doesn't handle more complex filter clauses that
were created without the 'normal' MLv2 functions used by the frontend; we can add this in the future if we need it."
- [join :- lib.join.util/PartialJoin
+ [join :- ::lib.join.util/partial-join
old-alias :- [:maybe ::lib.schema.join/alias]
new-alias :- [:maybe ::lib.schema.join/alias]]
(cond
@@ -140,6 +140,7 @@
(defn- with-join-alias-update-join
"Impl for [[with-join-alias]] for a join."
+ {:style/indent [:form]}
[join new-alias]
(let [old-alias (lib.join.util/current-join-alias join)]
(-> join
@@ -147,11 +148,17 @@
(with-join-alias-update-join-fields new-alias)
(with-join-alias-update-join-conditions old-alias new-alias))))
-(mu/defn with-join-alias :- lib.join.util/FieldOrPartialJoin
+(mu/defn with-join-alias :- [:or
+ [:map
+ [:lib/type [:enum :metadata/column :mbql/join]]]
+ [:ref :mbql.clause/field]]
"Add OR REMOVE a specific `join-alias` to `field-or-join`, which is either a `:field`/Field metadata, or a join map.
Does not recursively update other references (yet; we can add this in the future)."
{:style/indent [:form]}
- [field-or-join :- lib.join.util/FieldOrPartialJoin
+ [field-or-join :- [:or
+ [:map
+ [:lib/type [:enum :metadata/column :mbql/join]]]
+ [:ref :mbql.clause/field]]
join-alias :- [:maybe ::lib.schema.common/non-blank-string]]
(case (lib.dispatch/dispatch-value field-or-join)
:field
@@ -234,11 +241,13 @@
(throw (ex-info "You can't calculate a metadata map for a join! Use lib.metadata.calculation/returned-columns-method instead."
{})))
-(mu/defn column-from-join :- ::lib.metadata.calculation/column-metadata-with-source
+(mu/defn column-from-join :- [:map
+ [:lib/type [:= :metadata/column]]]
"For a column that comes from a join, add or update metadata as needed, e.g. include join name in the display name."
[query :- ::lib.schema/query
stage-number :- :int
- col :- ::lib.schema.metadata/column
+ col :- [:map
+ [:lib/type [:= :metadata/column]]]
join-alias :- ::lib.schema.join/alias]
(-> col
(assoc
@@ -254,6 +263,19 @@
(set/rename-keys {:lib/expression-name :lib/original-expression-name})
(as-> $col (assoc $col :display-name (lib.metadata.calculation/display-name query stage-number $col)))))
+(defn- HACK-column-from-incomplete-join
+ "Hack until I can figure out a better way to fix this. Once I made `::join-alias` required for columns with
+ `:source/join`, [[metabase.lib.column-group/column-group-info-method]] in combination
+ with [[join-condition-rhs-columns]] when joining Cards stopped working, because it relies on columns coming back
+ with `:source/joins` even tho the join does not yet have an alias.
+
+ `::HACK-from-incomplete-join?` is used to disable the requirement that this column have a join alias."
+ [col]
+ (-> col
+ (assoc :lib/source :source/joins
+ ::HACK-from-incomplete-join? true)
+ (set/rename-keys {:lib/expression-name :lib/original-expression-name})))
+
(defmethod lib.metadata.calculation/display-name-method :option/join.strategy
[_query _stage-number {:keys [strategy]} _style]
(case strategy
@@ -268,38 +290,48 @@
:display-name (lib.metadata.calculation/display-name query stage-number option)}
default (assoc :default true)))
-;;; this returns ALL the columns 'visible' within the join, regardless of `:fields` ! `:fields` is only the list of
+;;; this returns ALL the columns made 'visible' by the join, regardless of `:fields` ! `:fields` is only the list of
;;; things to get added to the parent stage `:fields`! See QUE-1380
;;;
;;; If you want just the stuff in `:fields`, use [[join-fields-to-add-to-parent-stage]] instead.
;;;
-;;; returned columns for a join == returned columns from the previous stage
-(mu/defmethod lib.metadata.calculation/returned-columns-method :mbql/join :- [:maybe ::lib.metadata.calculation/returned-columns]
- [query :- ::lib.schema/query
- stage-number :- :int
- {:keys [stages], join-alias :alias, :as _join} :- ::lib.schema.join/join
- options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
- (let [join-query (assoc query :stages stages)
- cols (lib.metadata.calculation/returned-columns
- join-query -1 (lib.util/query-stage join-query -1)
- options)]
- (into []
- (comp (map #(column-from-join query stage-number % join-alias))
- (lib.field.util/add-source-and-desired-aliases-xform query))
- cols)))
-
-(defn- update-keys-for-join-returned-column
- "Things like bucketing that happened in the last stage of the join they should NOT get propagated (QUE-1621) to the
- parent stage, otherwise we'd be performing the bucketing twice.
- Use [[lib.field.util/update-keys-for-col-from-previous-stage]] to update all these keys so we make sure stuff like
- binning and bucketing that should not get propagated are updated appropriately."
- [col]
- (-> col
- lib.field.util/update-keys-for-col-from-previous-stage
- ;; these columns aren't TRULY from a previous stage so we don't want to update `:lib/desired-column-alias` =>
- ;; `:lib/source-column-alias`; we'll keep the ones we already have. Throw out the
- ;; changes [[lib.field.util/update-keys-for-col-from-previous-stage]] made to these.
- (merge (select-keys col [:lib/source-column-alias :lib/desired-column-alias]))))
+;;; returned columns for a join == returned columns from the join's last stage.
+;;;
+;;; THIS METADATA IS RELATIVE TO THE JOIN! IT DOES NOT INCLUDE THE JOIN ALIAS OR UPDATED SOURCE/DESIRED ALIASES AS
+;;; THEY WOULD APPEAR IN THE PARENT STAGE!!! USE [[join-returned-columns-relative-to-parent-stage]] if that's what you
+;;; want instead.
+(mu/defmethod lib.metadata.calculation/returned-columns-method :mbql/join :- ::lib.metadata.calculation/returned-columns
+ [query :- ::lib.schema/query
+ _stage-number :- :int
+ {:keys [stages], :as _join} :- ::lib.schema.join/join
+ options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
+ (let [join-query (assoc query :stages stages)]
+ (lib.metadata.calculation/returned-columns join-query -1 (lib.util/query-stage join-query -1) options)))
+
+(mu/defn join-returned-columns-relative-to-parent-stage :- ::lib.metadata.calculation/visible-columns
+ "All columns made 'visible' by the join (regardless of `:fields`) -- i.e., the columns returned by the last stage of
+ the join -- updated so their metadata is relative to the parent stage.
+
+ E.g. the desired column alias from the last stage of the join needs to become the new source column alias in the
+ join's parent stage e.g. if the last stage of the join `Q2` returns `P2__CATEGORY` then the ultimate source alias in
+ the parent stage of this join should be `P2__CATEGORY`, and the desired alias should be `Q2__P2__CATEGORY`.
+ See [[metabase.lib.metadata.calculation-test/join-source-query-join-test]] for a concrete example of this.
+
+ Note that a join's `:fields` is effectively relative to the parent stage of the join, rather than the join's last
+ stage, since they include `:join-alias`; if you want to resolve these refs, you should use this function as opposed
+ to `returned-columns`."
+ ([query stage-number join]
+ (join-returned-columns-relative-to-parent-stage query stage-number join nil))
+
+ ([query :- ::lib.schema/query
+ stage-number :- :int
+ {join-alias :alias, :as join} :- ::lib.schema.join/join
+ options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
+ (into []
+ (comp
+ (map lib.field.util/update-keys-for-col-from-previous-stage)
+ (map #(column-from-join query stage-number % join-alias)))
+ (lib.metadata.calculation/returned-columns query stage-number join options))))
(mu/defn join-fields-to-add-to-parent-stage :- [:maybe [:sequential ::lib.metadata.calculation/column-metadata-with-source]]
"The resolved `:fields` from a join, which we automatically append to the parent stage's `:fields`."
@@ -308,27 +340,26 @@
{:keys [fields stages], join-alias :alias, :or {fields :none}, :as join}
options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
(when-not (= fields :none)
- (let [cols (lib.metadata.calculation/returned-columns query stage-number join options)
- cols' (if (= fields :all)
- (map update-keys-for-join-returned-column cols)
- (for [field-ref fields
- :let [match (or (lib.equality/find-matching-column field-ref cols)
- (log/warnf "Failed to find matching column in join %s for ref %s, found:\n%s"
- (pr-str join-alias)
- (pr-str field-ref)
- (u/pprint-to-str (map :lib/desired-column-alias cols))))]
- :when match]
- (-> match
- update-keys-for-join-returned-column
- (assoc :lib/source-uuid (lib.options/uuid field-ref))
- ;; if the ref in join `:fields` is bucketed then we need to propagate this, since the
- ;; bucketing will actually take place in the parent stage. Note that this unit can differ
- ;; from bucketing done in the last stage of the join --
- ;; see [[metabase.lib.join-test/do-not-incorrectly-propagate-temporal-unit-in-returned-columns-test-2]]
- (m/assoc-some :metabase.lib.field/temporal-unit (lib.temporal-bucket/raw-temporal-bucket field-ref)))))
+ (let [cols (join-returned-columns-relative-to-parent-stage query stage-number join options)
+ cols' (if (= fields :all)
+ cols
+ (for [field-ref fields
+ :let [match (or (lib.equality/find-matching-column field-ref cols)
+ (log/warnf "Failed to find matching column in join %s for ref %s, found:\n%s"
+ (pr-str join-alias)
+ (pr-str field-ref)
+ (pr-str (map (juxt :id :lib/source-column-alias) cols))))]
+ :when match]
+ (-> match
+ (assoc :lib/source-uuid (lib.options/uuid field-ref))
+ ;; if the ref in join `:fields` is bucketed then we need to propagate this, since the
+ ;; bucketing will actually take place in the parent stage. Note that this unit can differ
+ ;; from bucketing done in the last stage of the join --
+ ;; see [[metabase.lib.join-test/do-not-incorrectly-propagate-temporal-unit-in-returned-columns-test-2]]
+ (m/assoc-some :metabase.lib.field/temporal-unit (lib.temporal-bucket/raw-temporal-bucket field-ref)))))
;; If there was a `:fields` clause but none of them matched the `join-cols` then pretend it was `:fields :all`
;; instead. That can happen if a model gets reworked and an old join clause remembers the old fields.
- cols' (if (empty? cols') cols cols')
+ cols' (if (empty? cols') cols cols')
;; add any remaps for the fields as needed.
cols' (concat
cols'
@@ -337,29 +368,37 @@
0
cols'
options))]
+ ;; TODO (Cam 8/1/25) -- doesn't [[join-returned-columns-relative-to-parent-stage]] already
+ ;; call [[column-from-join]] ???
(mapv #(column-from-join query stage-number % join-alias)
cols'))))
-(defmethod lib.metadata.calculation/visible-columns-method :mbql/join
- [query stage-number join options]
- (lib.metadata.calculation/returned-columns query stage-number (assoc join :fields :all) options))
+;;; VISIBLE COLUMNS FOR A JOIN ARE RELATIVE TO THE LAST STAGE OF A JOIN!!!! IF YOU WANT THEM WITH APPROPRIATE METADATA
+;;; RELATIVE TO THE PARENT STAGE OF A QUERY, USE [[join-visible-columns-relative-to-parent-stage]] INSTEAD!!!
+
+(mu/defn- join-visible-columns-relative-to-parent-stage :- ::lib.metadata.calculation/visible-columns
+ "Convenience for calling [[lib.metadata.calculation/visible-columns]] on all of the joins in a query stage."
+ [query :- ::lib.schema/query
+ stage-number :- :int
+ {join-alias :alias, :as join} :- ::lib.schema.join/join
+ options :- ::lib.metadata.calculation/visible-columns.options]
+ (into []
+ (comp (map lib.field.util/update-keys-for-col-from-previous-stage)
+ (map #(column-from-join query stage-number % join-alias)))
+ (lib.metadata.calculation/visible-columns query stage-number join options)))
-(mu/defn all-joins-visible-columns :- ::lib.metadata.calculation/visible-columns
+(mu/defn all-joins-visible-columns-relative-to-parent-stage :- ::lib.metadata.calculation/visible-columns
"Convenience for calling [[lib.metadata.calculation/visible-columns]] on all of the joins in a query stage."
[query :- ::lib.schema/query
stage-number :- :int
options :- ::lib.metadata.calculation/visible-columns.options]
(into []
(mapcat (fn [join]
- (lib.metadata.calculation/visible-columns
- query stage-number join
- (-> options
- (select-keys [:include-remaps?]) ; WHY
- (assoc :include-implicitly-joinable? false)))))
+ (join-visible-columns-relative-to-parent-stage query stage-number join options)))
(:joins (lib.util/query-stage query stage-number))))
-(mu/defn all-joins-fields-to-add-to-parent-stage :- ::lib.metadata.calculation/returned-columns
- "Convenience for calling [[lib.metadata.calculation/returned-columns-method]] on all the joins in a query stage."
+(mu/defn all-joins-fields-to-add-to-parent-stage :- ::lib.metadata.calculation/visible-columns
+ "Convenience for calling [[join-fields-to-add-to-parent-stage]] on all the joins in a query stage."
[query :- ::lib.schema/query
stage-number :- :int
options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
@@ -425,19 +464,19 @@
(with-join-alias field join-alias)))))
conditions)))
-(mu/defn with-join-conditions :- lib.join.util/PartialJoin
+(mu/defn with-join-conditions :- ::lib.join.util/partial-join
"Update the `:conditions` (filters) for a Join clause."
{:style/indent [:form]}
- [a-join :- lib.join.util/PartialJoin
+ [a-join :- ::lib.join.util/partial-join
conditions :- [:maybe [:sequential [:or ::lib.schema.expression/boolean ::lib.schema.common/external-op]]]]
(let [conditions (-> (mapv lib.common/->op-arg conditions)
(with-join-conditions-add-alias-to-rhses (lib.join.util/current-join-alias a-join)))]
(u/assoc-dissoc a-join :conditions (not-empty conditions))))
-(mu/defn with-join-fields :- lib.join.util/PartialJoin
+(mu/defn with-join-fields :- ::lib.join.util/partial-join
"Update a join (or a function that will return a join) to include `:fields`, either `:all`, `:none`, or a sequence of
references."
- [joinable :- lib.join.util/PartialJoin
+ [joinable :- ::lib.join.util/partial-join
fields :- [:maybe [:or [:enum :all :none] [:sequential some?]]]]
(let [fields (cond
(keyword? fields) fields
@@ -574,7 +613,7 @@
new one."
[query :- ::lib.schema/query
stage-number :- :int
- a-join :- lib.join.util/JoinWithOptionalAlias]
+ a-join :- ::lib.join.util/join-with-optional-alias]
(if (and (contains? a-join :alias) (not (contains? a-join ::replace-alias)))
;; if the join clause comes with an alias and doesn't need a new one, keep it and assume that the condition fields
;; have the right join-aliases too
@@ -613,12 +652,12 @@
(mu/defn join-conditions :- [:maybe ::lib.schema.join/conditions]
"Get all join conditions for the given join"
- [a-join :- lib.join.util/PartialJoin]
+ [a-join :- ::lib.join.util/partial-join]
(:conditions a-join))
(mu/defn join-fields :- [:maybe ::lib.schema.join/fields]
"Get all join conditions for the given join"
- [a-join :- lib.join.util/PartialJoin]
+ [a-join :- ::lib.join.util/partial-join]
(:fields a-join))
(defn- raw-join-strategy->strategy-option [raw-strategy]
@@ -631,18 +670,18 @@
(mu/defn raw-join-strategy :- ::lib.schema.join/strategy
"Get the raw keyword strategy (type) of a given join, e.g. `:left-join` or `:right-join`. This is either the value
of the optional `:strategy` key or the default, `:left-join`, if `:strategy` is not specified."
- [a-join :- lib.join.util/PartialJoin]
+ [a-join :- ::lib.join.util/partial-join]
(get a-join :strategy :left-join))
(mu/defn join-strategy :- ::lib.schema.join/strategy.option
"Get the strategy (type) of a given join, as a `:option/join.strategy` map. If `:stategy` is unspecified, returns
the default, left join."
- [a-join :- lib.join.util/PartialJoin]
+ [a-join :- ::lib.join.util/partial-join]
(raw-join-strategy->strategy-option (raw-join-strategy a-join)))
-(mu/defn with-join-strategy :- lib.join.util/PartialJoin
+(mu/defn with-join-strategy :- ::lib.join.util/partial-join
"Return a copy of `a-join` with its `:strategy` set to `strategy`."
- [a-join :- lib.join.util/PartialJoin
+ [a-join :- ::lib.join.util/partial-join
strategy :- [:or ::lib.schema.join/strategy ::lib.schema.join/strategy.option]]
;; unwrap the strategy to a raw keyword if needed.
(assoc a-join :strategy (cond-> strategy
@@ -663,7 +702,7 @@
(map raw-join-strategy->strategy-option))
[:left-join :right-join :inner-join :full-join])))
-(mu/defn join-clause :- lib.join.util/PartialJoin
+(mu/defn join-clause :- ::lib.join.util/partial-join
"Create an MBQL join map from something that can conceptually be joined against. A `Table`? An MBQL or native query? A
Saved Question? You should be able to join anything, and this should return a sensible MBQL join map. Uses a left join
by default."
@@ -691,7 +730,7 @@
([query :- ::lib.schema/query
stage-number :- :int
- a-join :- [:or lib.join.util/PartialJoin Joinable]]
+ a-join :- [:or ::lib.join.util/partial-join Joinable]]
(let [a-join (join-clause a-join)
suggested-conditions (when (empty? (join-conditions a-join))
(suggested-join-conditions query stage-number (joined-thing query a-join)))
@@ -707,7 +746,7 @@
(mu/defn joined-thing :- [:maybe Joinable]
"Return metadata about the origin of `a-join` using `metadata-providerable` as the source of information."
[metadata-providerable :- ::lib.schema.metadata/metadata-providerable
- a-join :- lib.join.util/PartialJoin]
+ a-join :- ::lib.join.util/partial-join]
(let [origin (-> a-join :stages first)]
(cond
(:source-card origin) (lib.metadata/card metadata-providerable (:source-card origin))
@@ -825,8 +864,8 @@
(mu/defn join-condition-rhs-columns :- [:sequential ::lib.schema.metadata/column]
"Get a sequence of columns that can be used as the right-hand-side (target column) in a join condition. This column
is the one that belongs to the thing being joined, `join-or-joinable`, which can be something like a
- Table ([[metabase.lib.metadata/TableMetadata]]), Saved Question/Model ([[metabase.lib.metadata/CardMetadata]]),
- another query, etc. -- anything you can pass to [[join-clause]]. You can also pass in an existing join.
+ Table (`:metabase.lib.schema.metadata/table`), Saved Question/Model (`:metabase.lib.schema.metadata/card`), another
+ query, etc. -- anything you can pass to [[join-clause]]. You can also pass in an existing join.
If the left-hand-side column has already been chosen (they can be chosen in any order in the Query Builder UI),
pass in the chosen LHS column. In the future, this may be used to restrict results to compatible columns. (See #31174)
@@ -849,16 +888,18 @@
(let [joinable (if (join? join-or-joinable)
(joined-thing query join-or-joinable)
join-or-joinable)
- join-alias (when (join? join-or-joinable)
- (lib.join.util/current-join-alias join-or-joinable))
+ join-alias (if (join? join-or-joinable)
+ (lib.join.util/current-join-alias join-or-joinable)
+ (::join-alias join-or-joinable))
rhs-column-or-nil (when (lib.util/field-clause? rhs-expression-or-nil)
(cond-> rhs-expression-or-nil
;; Drop the :join-alias from the RHS if the joinable doesn't have one either.
(not join-alias) (lib.options/update-options dissoc :join-alias)))]
(->> (lib.metadata.calculation/visible-columns query stage-number joinable {:include-implicitly-joinable? false})
(map (fn [col]
- (cond-> (assoc col :lib/source :source/joins)
- join-alias (with-join-alias join-alias))))
+ (if join-alias
+ (column-from-join query stage-number col join-alias)
+ (HACK-column-from-incomplete-join col))))
(mark-selected-column query stage-number rhs-column-or-nil)
sort-join-condition-columns))))
diff --git a/src/metabase/lib/join/util.cljc b/src/metabase/lib/join/util.cljc
index 956f6bd003a..46983b9fe60 100644
--- a/src/metabase/lib/join/util.cljc
+++ b/src/metabase/lib/join/util.cljc
@@ -8,9 +8,10 @@
[metabase.lib.schema.join :as lib.schema.join]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.lib.util :as lib.util]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]))
-(def JoinWithOptionalAlias
+(mr/def ::join-with-optional-alias
"A Join that may not yet have an `:alias`, which is normally required; [[join]] accepts this and will add a default
alias if one is not present."
[:merge
@@ -18,33 +19,38 @@
[:map
[:alias {:optional true} [:ref ::lib.schema.join/alias]]]])
-(def PartialJoin
+(mr/def ::partial-join
"A join that may not yet have an `:alias` or `:conditions`."
[:merge
- JoinWithOptionalAlias
+ [:ref ::join-with-optional-alias]
[:map
[:conditions {:optional true} [:ref ::lib.schema.join/conditions]]]])
-(def Field
+(mr/def ::column-or-field-ref
"A field in a join, either `:metabase.lib.schema.metadata/column` or a `:field` ref."
- [:or
- [:ref ::lib.schema.metadata/column]
- [:ref :mbql.clause/field]])
-
-(def FieldOrPartialJoin
+ [:multi {:dispatch lib.dispatch/dispatch-value}
+ [:field [:ref :mbql.clause/field]]
+ [:metadata/column [:ref ::lib.schema.metadata/column]]
+ [:malli.core/default [:fn
+ {:error/message "Should be a :field ref or column metadata"}
+ (constantly false)]]])
+
+(mr/def ::column-or-field-ref-or-partial-join
"A field or a partial join."
- [:or Field PartialJoin])
+ [:multi {:dispatch lib.dispatch/dispatch-value}
+ [:mbql/join [:ref ::partial-join]]
+ [:malli.core/default [:ref ::column-or-field-ref]]])
-(mu/defn current-join-alias :- [:maybe ::lib.schema.common/non-blank-string]
+(mu/defn current-join-alias :- [:maybe ::lib.schema.join/alias]
"Get the current join alias associated with something, if it has one."
- [field-or-join :- [:maybe FieldOrPartialJoin]]
+ [field-or-join :- [:maybe ::column-or-field-ref-or-partial-join]]
(case (lib.dispatch/dispatch-value field-or-join)
:dispatch-type/nil nil
:field (:join-alias (lib.options/options field-or-join))
:metadata/column (:metabase.lib.join/join-alias field-or-join)
:mbql/join (:alias field-or-join)))
-(mu/defn joined-field-desired-alias :- ::lib.schema.common/non-blank-string
+(mu/defn joined-field-desired-alias :- ::lib.schema.metadata/desired-column-alias
"Desired alias for a Field that comes from a join, e.g.
MyJoin__my_field
@@ -55,7 +61,7 @@
field-name :- ::lib.schema.common/non-blank-string]
(lib.util/format "%s__%s" join-alias field-name))
-(mu/defn format-implicit-join-name :- ::lib.schema.common/non-blank-string
+(mu/defn format-implicit-join-name :- ::lib.schema.join/alias
"Name for an implicit join against `table-name` via an FK field, e.g.
CATEGORIES__via__CATEGORY_ID
@@ -80,7 +86,7 @@
fk-field-name (or fk-field-name (:name (lib.metadata/field metadata-providerable fk-field-id)))]
(format-implicit-join-name table-name fk-field-name fk-join-alias)))))
-(mu/defn desired-alias :- :string
+(mu/defn desired-alias :- ::lib.schema.metadata/desired-column-alias
"Desired alias for a Field e.g.
my_field
diff --git a/src/metabase/lib/metadata/calculation.cljc b/src/metabase/lib/metadata/calculation.cljc
index 46c0288ba4b..d3a3d84ade4 100644
--- a/src/metabase/lib/metadata/calculation.cljc
+++ b/src/metabase/lib/metadata/calculation.cljc
@@ -445,7 +445,8 @@
:visibility-type (:visibility-type table)}))
(mr/def ::column-metadata-with-source
- "Schema for the column metadata that should be returned by [[metadata]]."
+ "Schema for the column metadata that should be returned by [[metadata]]. A column metadata that is also required to
+ have `:lib/source`."
[:merge
[:ref ::lib.schema.metadata/column]
[:map
@@ -503,9 +504,22 @@
(mu/defn returned-columns :- [:maybe ::returned-columns]
"Return a sequence of metadata maps for all the columns expected to be 'returned' at a query, stage of the query, or
join, and include the `:lib/source` of where they came from. This should only include columns that will be present
- in the results; DOES NOT include 'expected' columns that are not 'exported' to subsequent stages.
+ in the results; DOES NOT include 'visible' columns that are not 'exported' to subsequent stages.
- See [[::returned-columns.options]] for allowed options."
+ See [[::returned-columns.options]] for allowed options.
+
+ `returned-columns` always returns metadata relative to the source `x`, not subsequent stages or parent stages (for
+ joins)!!!! Take a moment and make sure you understand this concept clearly, it's SUPER IMPORTANT <3
+
+ Examples:
+
+ * `returned-columns` for a join is the same as `returned-columns` for the last stage of the join -- the columns have
+ source and desired aliases appropriate for the join's `:stages` if they were an entirely independent query, and do
+ not include join aliases!
+
+ * `returned-columns` for a stage have source and desired aliases relative to that stage!
+
+ * `returned-columns` for a Card has the same source and desired aliases you'd see in that Card's `:result-metadata`!!"
([query]
(returned-columns query (lib.util/query-stage query -1)))
@@ -524,6 +538,13 @@
(returned-columns-method query stage-number x options)))))
(mr/def ::visible-column
+ "Schema for a column that should be returned by [[visible-columns]]. A visible column is a column metadata that is
+ required to also have `:lib/source` and `:lib/source-column-alias`.
+
+ `:lib/desired-column-alias` should not be returned by [[visible-columns]] since it needs to be calculated in the
+ context of the columns RETURNED by the stage! Do not expect it to be present. You should probably be using
+ `:lib/source-column-alias` for whatever purpose you think you need `:lib/desired-column-alias` for (field refs,
+ etc.)"
[:merge
[:ref ::column-metadata-with-source]
[:map
@@ -540,10 +561,10 @@
[:ref ::returned-columns.options]
[:map
;; these all default to true
- [:include-joined? {:optional true} :boolean]
- [:include-expressions? {:optional true} :boolean]
- [:include-implicitly-joinable? {:optional true} :boolean]
- [:include-implicitly-joinable-for-source-card? {:optional true} :boolean]]])
+ [:include-joined? {:optional true, :default true} :boolean]
+ [:include-expressions? {:optional true, :default true} :boolean]
+ [:include-implicitly-joinable? {:optional true, :default true} :boolean]
+ [:include-implicitly-joinable-for-source-card? {:optional true, :default true} :boolean]]])
(mu/defn- default-visible-columns-options :- ::visible-columns.options
[]
@@ -573,6 +594,9 @@
[query _stage-number stage-number options]
(visible-columns-method query stage-number (lib.util/query-stage query stage-number) options))
+;; TODO (Cam 8/7/25) -- Braden and I are in agreement that `visible-columns` fundamentally does not make sense for
+;; anything other than a specific query stage, and we should probably remove it entirely in the near future and leave
+;; just the stage implementation. See https://github.com/metabase/metabase/pull/61767#discussion_r2260558780
(mu/defn visible-columns :- ::visible-columns
"Return a sequence of columns that should be visible *within* a given stage of something, e.g. a query stage or a
join query. This includes not just the columns that get returned (ones present in [[metadata]], but other columns
@@ -617,9 +641,13 @@
:let [remapped (lib.metadata/remapped-field query column)]
:when (and remapped
(not (existing-ids (:id remapped))))]
- (assoc remapped
- :lib/source (:lib/source column) ; TODO: What's the right source for a remap?
- :lib/source-column-alias ((some-fn :lib/source-column-alias :name) remapped))))))
+ (merge
+ remapped
+ {:lib/source (:lib/source column) ; TODO: What's the right source for a remap?
+ :lib/source-column-alias ((some-fn :lib/source-column-alias :name) remapped)}
+ ;; if a remap is of a joined column then we should do the remap in the join itself; columns with
+ ;; `:lib/source` `:source/joins` need to have a join alias.
+ (select-keys column [:metabase.lib.join/join-alias]))))))
(mu/defn primary-keys :- [:sequential ::lib.schema.metadata/column]
"Returns a list of primary keys for the source table of this query."
@@ -689,4 +717,4 @@
(let [no-fields (lib.util/update-query-stage query stage-number dissoc :fields)]
(into [] (remove (comp #{:source/joins :source/implicitly-joinable}
:lib/source))
- (returned-columns no-fields stage-number (lib.util/query-stage no-fields stage-number)))))
+ (returned-columns no-fields stage-number))))
diff --git a/src/metabase/lib/metadata/result_metadata.cljc b/src/metabase/lib/metadata/result_metadata.cljc
index b6d127284f8..49b606e7789 100644
--- a/src/metabase/lib/metadata/result_metadata.cljc
+++ b/src/metabase/lib/metadata/result_metadata.cljc
@@ -178,19 +178,25 @@
(set/union aliases (implicit-join-aliases query previous-stage-number))
aliases)))
-;;; TODO (Cam 7/30/25) -- I have no real idea why we're doing this. It seems dumb and broken; a column from a reified
-;;; explicit join that gets `:source/joins` should always have a join aliases -- see my notes on
-;;; `:metabase.lib.metadata.result-metadata/column.validate-join-alias`. Can we just remove `:source-alias` (which is
-;;; used by the FE for mysterious/unknown purposes) and leave the Lib keys in the correct shape?
(defn- remove-implicit-join-aliases
+ "If an implicit join was reified by the QP preprocessor, we need to remove traces of that reification from result
+ metadata, so anyone using it in combination with the un-preprocessed query doesn't accidentally introduce field refs
+ that include generated join aliases for joins that don't exist yet."
[query cols]
- (let [implicit-aliases (implicit-join-aliases query -1)]
- (map (fn [col]
- (cond-> col
- (when-let [join-alias (any-join-alias col)]
- (contains? implicit-aliases join-alias))
- (dissoc :metabase.lib.join/join-alias :lib/original-join-alias :source-alias)))
- cols)))
+ (let [implicit-aliases (implicit-join-aliases query -1)
+ maybe-update-source (fn [col]
+ (cond-> col
+ (= (:lib/source col) :source/joins)
+ (assoc :lib/source :source/implicitly-joinable)))
+ remove-aliases (fn [col]
+ (dissoc col :metabase.lib.join/join-alias :lib/original-join-alias :source-alias))
+ implicitly-joined? (fn [col]
+ (when-let [join-alias (any-join-alias col)]
+ (contains? implicit-aliases join-alias)))
+ maybe-update-col (fn [col]
+ (cond-> col
+ (implicitly-joined? col) (-> remove-aliases maybe-update-source)))]
+ (map maybe-update-col cols)))
(mu/defn- add-legacy-source :- [:sequential
[:merge
diff --git a/src/metabase/lib/metric.cljc b/src/metabase/lib/metric.cljc
index 6a3b33d4282..146fba8d018 100644
--- a/src/metabase/lib/metric.cljc
+++ b/src/metabase/lib/metric.cljc
@@ -145,9 +145,8 @@
inner-aggregation (first (lib.aggregation/aggregations metric-query))
inner-meta (lib.metadata.calculation/metadata metric-query -1 inner-aggregation)]
(-> inner-meta
- (assoc :display-name (:name metric-meta) ; Metric card's name
- :lib/hack-original-name (:name metric-meta) ; Metric card's name
- :name (:name inner-meta)) ; Name of the inner aggregation column
+ (assoc :display-name (:name metric-meta) ; Metric card's name
+ :name (:name inner-meta)) ; Name of the inner aggregation column
;; If the :metric ref has a :name option, that overrides the metric card's name.
(cond-> (:name opts) (assoc :name (:name opts)))))
{:lib/type :metadata/metric
diff --git a/src/metabase/lib/query.cljc b/src/metabase/lib/query.cljc
index 6de5178a715..bed72302b71 100644
--- a/src/metabase/lib/query.cljc
+++ b/src/metabase/lib/query.cljc
@@ -491,8 +491,8 @@
(cond-> graph
card-id (dep/depend [:card from-id] [:card card-id])
table-id (dep/depend [:card from-id] [:table table-id]))
- (catch #?(:clj Exception :cljs :default) _e
- (throw (ex-info (i18n/tru "Cannot save card with cycles.") {}))))))
+ (catch #?(:clj Exception :cljs :default) e
+ (throw (ex-info (i18n/tru "Cannot save card with cycles.") {} e))))))
(defn- build-graph [source-id metadata-provider a-query]
(loop [graph (dep/graph)
diff --git a/src/metabase/lib/remove_replace.cljc b/src/metabase/lib/remove_replace.cljc
index 39fc22e31c8..c80ae660058 100644
--- a/src/metabase/lib/remove_replace.cljc
+++ b/src/metabase/lib/remove_replace.cljc
@@ -89,10 +89,10 @@
query-modified stage-number
#(lib.util.match/replace
%
- #{:field}
+ :field
(let [old-matching-column (lib.equality/find-matching-column &match old-columns)]
(if-let [new-column (some-> old-matching-column :lib/source-uuid source-uuid->new-column)]
- (assoc &match 2 ((some-fn :lib/desired-column-alias :name) new-column))
+ (assoc &match 2 ((some-fn :lib/source-column-alias :name) new-column))
(do
(log/warnf "Failed to match downstream ref %s against visible columns, ref is on stage %d at %s"
&match stage-number &parents)
@@ -112,7 +112,7 @@
in stage 1.
These aggregation columns have same `:name`. Field refs, intended for use in stage 1, generated out of those
- columns, are then identified by `:lib/desired-column-alias`. Stage 1 will be using ref
+ columns, are then identified by `:lib/source-column-alias`. Stage 1 will be using ref
`[:field <opts> \"sum_2\"]` for the second aggregation.
Removing the first from the stage 0, will remove clauses refeencing it in further stages. So far so good.
@@ -209,7 +209,7 @@
target-ref-id (->> (lib.metadata.calculation/visible-columns unmodified-query-for-stage stage-number stage)
(some (fn [{:keys [lib/source lib/source-uuid] :as column}]
(when (and (= :source/previous-stage source) (= target-uuid source-uuid))
- (:lib/desired-column-alias column)))))]
+ (:lib/source-column-alias column)))))]
(cond-> query
;; We are moving to the next stage, so pass the current query as the unmodified-query-for-stage
target-ref-id
@@ -572,19 +572,22 @@
removed-cols)))
(defn- remove-invalidated-refs
+ "Remove refs that are now invalid because a join has been removed."
[query-after query-before stage-number]
(let [query-without-local-refs (remove-matching-missing-columns
query-after
query-before
stage-number
(fn [column] [:field {:join-alias (::lib.join/join-alias column)} (:id column)]))]
- ;; Because joins can use :all or :none, we cannot just use `remove-local-references` we have to manually look at the next stage as well
- (if-let [stage-number (lib.util/next-stage-number query-without-local-refs stage-number)]
+ ;; Because joins can use :all or :none, we cannot just use `remove-local-references` we have to manually look at
+ ;; the next stage as well
+ (if-let [next-stage-number (lib.util/next-stage-number query-without-local-refs stage-number)]
(remove-matching-missing-columns
query-without-local-refs
query-before
- stage-number
- (fn [column] [:field {} (:lib/desired-column-alias column)]))
+ next-stage-number
+ (fn [column]
+ [:field {} (:lib/source-column-alias column)]))
query-without-local-refs)))
(defn- join-spec->alias
diff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljc
index 0ba1141e7ef..478fcebc5f4 100644
--- a/src/metabase/lib/schema.cljc
+++ b/src/metabase/lib/schema.cljc
@@ -251,8 +251,9 @@
:params
:parameters
:lib/stage-metadata
- ;; wait a minute, `:middleware` is not supposed to be added here, it's supposed to be
- ;; added to the top level.
+ ;; TODO (Cam 8/7/25) -- wait a minute, `:middleware` is not supposed to be added here,
+ ;; it's supposed to be added to the top level. Investigate whether this was just a
+ ;; mistake or what.
:middleware)}
[:map
[:lib/type [:ref ::stage.type]]]
diff --git a/src/metabase/lib/schema/aggregation.cljc b/src/metabase/lib/schema/aggregation.cljc
index a5468f4c248..9fe8c46345c 100644
--- a/src/metabase/lib/schema/aggregation.cljc
+++ b/src/metabase/lib/schema/aggregation.cljc
@@ -17,12 +17,19 @@
(mbql-clause/define-tuple-mbql-clause :avg :- :type/Float
[:schema [:ref ::expression/number]])
+(mr/def ::distinct.arg
+ [:and
+ [:ref ::expression/expression]
+ ;; you're not allowed to do distinct values of nil
+ [:some
+ {:error/message "You're not allowed to do distinct values of nil"}]])
+
;;; number of distinct values of something.
(mbql-clause/define-tuple-mbql-clause :distinct :- :type/Integer
- [:schema [:ref ::expression/expression]])
+ [:schema [:ref ::distinct.arg]])
(mbql-clause/define-tuple-mbql-clause :distinct-where :- :type/Integer
- [:schema [:ref ::expression/expression]]
+ [:schema [:ref ::distinct.arg]]
[:schema [:ref ::expression/boolean]])
(mbql-clause/define-tuple-mbql-clause :count-where :- :type/Integer
diff --git a/src/metabase/lib/schema/metadata.cljc b/src/metabase/lib/schema/metadata.cljc
index 092dbc4c026..bf48d59a0fc 100644
--- a/src/metabase/lib/schema/metadata.cljc
+++ b/src/metabase/lib/schema/metadata.cljc
@@ -192,72 +192,90 @@
;; remove deprecated `:ident` and `:model/inner_ident` keys (normalized to `:model/inner-ident`)
(dissoc :ident :model/inner-ident))))
-(mr/def ::column.validate-expression-source
- "Only allow `:lib/expression-name` when `:lib/source` is `:source/expressions`. If it's anything else, it probably
- means it's getting incorrectly propagated from a previous stage (QUE-1342)."
- [:fn
- {:error/message ":lib/expression-name should only be set for expressions in the current stage (:lib/source = :source/expressions)"}
- (fn [m]
- (if (:lib/expression-name m)
- (= (:lib/source m) :source/expressions)
- true))])
-
-(mr/def ::column.validate-native-column
- "Certain keys cannot possibly be set when a column comes from directly from native query results, for example
- `:lib/breakout?` or join aliases"
- (let [disallowed-keys [:metabase.lib.join/join-alias ; only things that come from a JOIN should have a join alias.
- :lib/expression-name]] ; if it comes from a native query then it can't come from an expression.
- [:fn
- {:error/message "Invalid column metadata for a column with :lib/source :source/native"
- :error/fn (fn [{m :value} _]
- (some (fn [k]
- (when (k m)
- (str "Column has :lib/source :source/native but also " k "; this is impossible")))
- disallowed-keys))}
- (fn [m]
- (if (= (:lib/source m) :source/native)
- (every? (fn [k]
- (not (k m)))
- disallowed-keys)
- true))]))
-
-(mr/def ::column.validate-table-defaults-column
- "A column with :lib/source :source/table-defaults cannot possibly have a join alias."
- [:fn
- {:error/message "A column with :lib/source :source/table-defaults cannot possibly have a join alias"}
- (fn [m]
- (if (= (:lib/source m) :source/table-defaults)
- (not (:metabase.lib.join/join-alias m))
- true))])
-
-;;; TODO (Cam 7/1/25) -- disabled for now because of bugs like QUE-1496; once that's fixed we should re-enable this.
-;;; Note we probably also need to remove [[metabase.lib.metadata.result-metadata/remove-implicit-join-aliases]]
-#_(mr/def ::column.validate-join-alias
- "* Current stage join alias (`:metabase.lib.join/join-alias`) should only be set for columns whose `:lib/source` is
- `:source/joins`
-
- * If source is `:source/joins` column must specify a current stage join alias."
- [:and
- [:fn
- {:error/message (str "Current stage join alias (:metabase.lib.join/join-alias) should only be set for columns"
- " whose :lib/source is :source/joins.")}
- (fn [m]
- (if (:metabase.lib.join/join-alias m)
- (= (:lib/source m) :source/joins)
- true))]
- [:fn
- {:error/message (str "If source is :source/joins the column must specify current stage join"
- " alias (:metabase.lib.join/join-alias).")}
- (fn [m]
- (if (= (:lib/source m) :source/joins)
- (:metabase.lib.join/join-alias m)
- true))]])
-
-;;; TODO (Cam 7/30/25) -- we should also validate that if `:lib/source` is `:source/implicitly-joinable` it includes
-;;; `:fk-field-id`, and vice-versa (actually this is also allowed if source is `:source/joins` as well.) The implicit
-;;; join could have only happened if the was a `:field` ref with `:source-field` (the mapped key in this case).
-;;; `:fk-field-id` should not be allowed for columns from `:source/previous-stage` or whatever... in that case we
-;;; should be using `:lib/original-fk-field-id` instead.
+(def ^:private column-validate-for-source-specs
+ "Schemas to use to validate columns with a given `:lib/source`. Since a lot of these schemas are applicable to
+ everything BUT one specific source it made more sense to write them out like this and use a bit of glue to build the
+ schemas in [[column-validate-for-source-schema]]."
+ [;; Only allow `:lib/expression-name` when `:lib/source` is `:source/expressions`. If it's anything else, it
+ ;; probably means it's getting incorrectly propagated from a previous stage (QUE-1342).
+ {:exclude :source/expressions
+ :schema [:fn
+ {:error/message ":lib/expression-name should only be set for expressions in the current stage (i.e., columns with :source/expressions)"}
+ (complement :lib/expression-name)]}
+ {:include :source/expressions
+ :schema [:fn
+ {:error/message ":lib/expression-name is required for columns with :source/expressions"}
+ :lib/expression-name]}
+ ;; Current stage join alias (`:metabase.lib.join/join-alias`) should only be set for columns whose `:lib/source` is
+ ;; `:source/joins`
+ {:exclude :source/joins
+ :schema [:fn
+ {:error/message (str "Current stage join alias (:metabase.lib.join/join-alias) should only be set for"
+ " columns joined in the current stage (i.e., columns with :source/joins).")}
+ (complement :metabase.lib.join/join-alias)]}
+ ;; If source is `:source/joins` column must specify a current stage join alias.
+ {:include :source/joins
+ :schema [:fn
+ {:error/message (str "Columns joined in the current stage (i.e., columns with :source/joins) must specify"
+ " current stage join alias (:metabase.lib.join/join-alias).")}
+ (some-fn :metabase.lib.join/join-alias
+ ;; see [[metabase.lib.join/HACK-column-from-incomplete-join]]
+ :metabase.lib.join/HACK-from-incomplete-join?)]}
+ ;; `:lib/source` `:source/implicitly-joinable` must have `:fk-field-id`; `:fk-field-id` is only allowed for
+ ;; `:source/implicitly-joinable` and `:source/joins`. For columns from `:source/previous-stage` or whatever... in
+ ;; that case we should be using `:lib/original-fk-field-id` instead.
+ {:exclude #{:source/implicitly-joinable :source/joins}
+ :schema [:fn
+ {:error/message ":fk-field-id is only allowed for columns with :source/implicitly-joinable or :source/joins"}
+ (complement :fk-field-id)]}
+ {:include :source/implicitly-joinable
+ :schema [:fn
+ {:error/message ":fk-field-id is required for columns with :source/implicitly-joinable"}
+ :fk-field-id]}
+ ;; columns with `:source/card` should have `:lib/card-id`. Doesn't matter if it gets propagated elsewhere
+ {:include :source/card
+ :schema [:fn
+ {:error/message "Columns with :source/card must have :lib/card-id"}
+ :lib/card-id]}])
+
+(defn- column-validate-for-source-schema [source]
+ (into [:and]
+ (comp (remove (fn [validator]
+ (when-let [exclude (:exclude validator)]
+ (if (set? exclude)
+ (contains? exclude source)
+ (= exclude source)))))
+ (filter (fn [validator]
+ (let [include (:include validator)]
+ (cond
+ (not include) true
+ (set? include) (contains? include source)
+ :else (= include source)))))
+ (map :schema))
+ column-validate-for-source-specs))
+
+(mr/def ::column.validate-for-source-card (column-validate-for-source-schema :source/card))
+(mr/def ::column.validate-for-source-native (column-validate-for-source-schema :source/native))
+(mr/def ::column.validate-for-source-previous-stage (column-validate-for-source-schema :source/previous-stage))
+(mr/def ::column.validate-for-source-table-defaults (column-validate-for-source-schema :source/table-defaults))
+(mr/def ::column.validate-for-source-aggregations (column-validate-for-source-schema :source/aggregations))
+(mr/def ::column.validate-for-source-joins (column-validate-for-source-schema :source/joins))
+(mr/def ::column.validate-for-source-expressions (column-validate-for-source-schema :source/expressions))
+(mr/def ::column.validate-for-source-implicitly-joinable (column-validate-for-source-schema :source/implicitly-joinable))
+
+(mr/def ::column.validate-for-source
+ "Do additional validation for column metadata based on `:lib/source`."
+ [:multi
+ {:dispatch :lib/source}
+ [:source/card [:ref ::column.validate-for-source-card]]
+ [:source/native [:ref ::column.validate-for-source-native]]
+ [:source/previous-stage [:ref ::column.validate-for-source-previous-stage]]
+ [:source/table-defaults [:ref ::column.validate-for-source-table-defaults]]
+ [:source/aggregations [:ref ::column.validate-for-source-aggregations]]
+ [:source/joins [:ref ::column.validate-for-source-joins]]
+ [:source/expressions [:ref ::column.validate-for-source-expressions]]
+ [:source/implicitly-joinable [:ref ::column.validate-for-source-implicitly-joinable]]
+ [nil :any]])
(def column-visibility-types
"Possible values for column `:visibility-type`."
@@ -323,9 +341,9 @@
;; if this is a field from another table (implicit join), this is the name of the source field. It can be either a
;; `:lib/desired-column-alias` or `:name`, depending on the `:lib/source`. It's set only when the field can be
;; referenced by a name, normally when it's coming from a card or a previous query stage.
- [:fk-field-name {:optional true} [:maybe ::lib.schema.common/non-blank-string]]
+ [:fk-field-name {:optional true} [:maybe :string]]
;; if this is a field from another table (implicit join), this is the join alias of the source field.
- [:fk-join-alias {:optional true} [:maybe ::lib.schema.common/non-blank-string]]
+ [:fk-join-alias {:optional true} [:maybe ::lib.schema.join/alias]]
;; `metabase_field.fk_target_field_id` in the application database; recorded during the sync process. This Field is
;; an foreign key, and points to this Field ID. This is mostly used to determine how to add implicit joins by
;; the [[metabase.query-processor.middleware.add-implicit-joins]] middleware.
@@ -358,6 +376,10 @@
;; original join alias = X
;; column => [join X => join Y]
;;
+ ;; It is not currently well-defined whether this appears when the join was the current stage or not, i.e. if it's
+ ;; equal to `:metabase.lib.join/join-alias` when it is set or if it is only set if the join happened in a previous
+ ;; stage, i.e. if it's `nil` when `:metabase.lib.join/join-alias` is set. It seems like current behavior is the
+ ;; former but you should NOT rely on this behavior.
[:lib/original-join-alias {:optional true} [:maybe ::lib.schema.join/alias]]
;; these should only be present if temporal bucketing or binning is done in the current stage of the query; if
;; this happened in a previous stage they should get propagated as the keys below instead.
@@ -401,11 +423,6 @@
;;
[:lib/original-name {:optional true} ::original-name]
[:lib/deduplicated-name {:optional true} ::deduplicated-name]
- ;; appears to serve the same purpose as `:lib/original-name` but it's unclear where or why it is
- ;; used. https://metaboat.slack.com/archives/C0645JP1W81/p1749168183509589
- ;;
- ;; TODO (Cam 6/19/25) -- can we remove this entirely?
- [:lib/hack-original-name {:optional true} ::original-name]
;;
;; the original display name of this column before adding join/temporal bucketing/binning stuff to it. `Join ->
;; <whatever>` or `<whatever>: Month` or `<whatever>: Auto-binned`. Should be equal to the very first
@@ -457,10 +474,7 @@
[:lib/internal-remap {:optional true} [:maybe [:ref ::column.remapping.internal]]]]
;; TODO (Cam 6/13/25) -- go add this to some of the other metadata schemas as well.
::kebab-cased-map
- ::column.validate-expression-source
- ::column.validate-native-column
- ::column.validate-table-defaults-column
- #_::column.validate-join-alias])
+ [:ref ::column.validate-for-source]])
(mr/def ::persisted-info.definition
"Definition spec for a cached table."
@@ -575,10 +589,17 @@
;;
[:lib/persisted-info {:optional true} [:maybe [:ref ::persisted-info]]]])
+(defn- mock-segment [segment]
+ (cond-> segment
+ (and (not (:name segment))
+ (:id segment))
+ (assoc :name (str "Segment " (:id segment)))))
+
(mr/def ::segment
"More or less the same as a [[metabase.segments.models.segment]], but with kebab-case keys."
[:map
- {:error/message "Valid Segment metadata"}
+ {:error/message "Valid Segment metadata"
+ :decode/mock mock-segment}
[:lib/type [:= :metadata/segment]]
[:id ::lib.schema.id/segment]
[:name ::lib.schema.common/non-blank-string]
diff --git a/src/metabase/lib/stage.cljc b/src/metabase/lib/stage.cljc
index b764b019b5c..ae94f00349d 100644
--- a/src/metabase/lib/stage.cljc
+++ b/src/metabase/lib/stage.cljc
@@ -2,11 +2,10 @@
"Method implementations for a stage of a query."
(:require
[clojure.string :as str]
- [metabase.legacy-mbql.normalize :as mbql.normalize]
+ [medley.core :as m]
[metabase.lib.aggregation :as lib.aggregation]
[metabase.lib.binning :as lib.binning]
[metabase.lib.breakout :as lib.breakout]
- [metabase.lib.convert :as lib.convert]
[metabase.lib.expression :as lib.expression]
[metabase.lib.field.util :as lib.field.util]
[metabase.lib.hierarchy :as lib.hierarchy]
@@ -14,6 +13,7 @@
[metabase.lib.join.util :as lib.join.util]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
+ [metabase.lib.query :as lib.query]
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.metadata :as lib.schema.metadata]
@@ -52,7 +52,7 @@
(lib.field.util/add-source-and-desired-aliases-xform query))
(:columns metadata))))))))
-(mu/defn- breakouts-columns :- [:maybe [:sequential ::lib.metadata.calculation/column-metadata-with-source]]
+(mu/defn- breakouts-columns :- [:maybe ::lib.metadata.calculation/visible-columns]
[query :- ::lib.schema/query
stage-number :- :int
options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
@@ -62,16 +62,19 @@
cols
(lib.metadata.calculation/remapped-columns query stage-number cols options)))))
-(mu/defn- aggregations-columns :- [:maybe [:sequential ::lib.metadata.calculation/column-metadata-with-source]]
+(mu/defn- aggregations-columns :- [:maybe ::lib.metadata.calculation/visible-columns]
[query :- ::lib.schema/query
stage-number :- :int]
(not-empty
(for [ag (lib.aggregation/aggregations-metadata query stage-number)]
- (assoc ag :lib/source :source/aggregations))))
+ ;; TODO (Cam 8/1/25) -- why don't we just do this in [[lib.aggregation/aggregations-metadata]] instead of here?
+ (assoc ag
+ :lib/source :source/aggregations
+ :lib/source-column-alias ((some-fn :lib/source-column-alias :name) ag)))))
;;; TODO -- maybe the bulk of this logic should be moved into [[metabase.lib.field]], like we did for breakouts and
;;; aggregations above.
-(mu/defn- fields-columns :- [:maybe [:sequential ::lib.metadata.calculation/column-metadata-with-source]]
+(mu/defn- fields-columns :- [:maybe ::lib.metadata.calculation/visible-columns]
[query :- ::lib.schema/query
stage-number :- :int
options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
@@ -79,11 +82,12 @@
(-> (for [[tag :as ref-clause] fields
:let [col (lib.metadata.calculation/metadata query stage-number ref-clause)]]
(cond-> col
- (= tag :expression) (assoc :lib/source :source/expressions)))
+ (= tag :expression) (assoc :lib/source :source/expressions
+ :lib/source-column-alias (:lib/expression-name col))))
(as-> $cols (concat $cols (lib.metadata.calculation/remapped-columns query stage-number $cols options)))
not-empty)))
-(mu/defn- summary-columns :- [:maybe [:sequential ::lib.metadata.calculation/column-metadata-with-source]]
+(mu/defn- summary-columns :- [:maybe ::lib.metadata.calculation/visible-columns]
[query :- ::lib.schema/query
stage-number :- :int
options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
@@ -92,17 +96,17 @@
(breakouts-columns query stage-number options)
(aggregations-columns query stage-number))))
-(mu/defn- previous-stage-metadata :- [:maybe ::lib.metadata.calculation/returned-columns]
- "Metadata for the previous stage, if there is one."
+(mu/defn- visible-columns-from-previous-stage-returned-columns :- [:maybe ::lib.metadata.calculation/visible-columns]
+ "Columns that are visible in the current stage because they were returned by the previous stage, if there is one.
+ These are updated to use correct aliases and other info for the current stage
+ with [[lib.field.util/update-keys-for-col-from-previous-stage]]."
[query :- ::lib.schema/query
stage-number :- :int
options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]
(when-let [previous-stage-number (lib.util/previous-stage-number query stage-number)]
(not-empty
(into []
- (comp (map lib.field.util/update-keys-for-col-from-previous-stage)
- (map #(assoc % :lib/source :source/previous-stage))
- (lib.field.util/add-source-and-desired-aliases-xform query))
+ (map lib.field.util/update-keys-for-col-from-previous-stage)
(lib.metadata.calculation/returned-columns query
previous-stage-number
(lib.util/query-stage query previous-stage-number)
@@ -118,12 +122,13 @@
(when-let [card (lib.metadata/card query card-id)]
(not-empty (lib.metadata.calculation/visible-columns query stage-number card options)))))
-(mu/defn- metric-metadata :- [:maybe ::lib.metadata.calculation/returned-columns]
+;;; TODO (Cam 8/6/25) -- this should probably live in [[metabase.lib.metric]]
+(mu/defn- metric-visible-columns :- [:maybe ::lib.metadata.calculation/visible-columns]
[query :- ::lib.schema/query
_stage-number :- :int
card :- ::lib.schema.metadata/card
options :- ::lib.metadata.calculation/visible-columns.options]
- (let [metric-query (-> card :dataset-query mbql.normalize/normalize lib.convert/->pMBQL
+ (let [metric-query (-> (lib.query/query (lib.metadata/->metadata-provider query) (:dataset-query card))
(lib.util/update-query-stage -1 dissoc :aggregation :breakout))]
(not-empty (lib.metadata.calculation/visible-columns
(assoc metric-query :lib/metadata (:lib/metadata query))
@@ -177,30 +182,34 @@
(let [{:keys [source-table source-card], :as this-stage} (lib.util/query-stage query stage-number)
card (some->> source-card (lib.metadata/card query))
metric-based? (= (:type card) :metric)]
- (into []
- (if metric-based?
- identity
- (map lib.field.util/update-keys-for-col-from-previous-stage))
- (or
- ;; 1a. columns returned by previous stage
- (previous-stage-metadata query stage-number options)
- ;; 1b: default visible Fields for the source Table
- (when source-table
- (assert (integer? source-table))
- (let [table-metadata (lib.metadata/table query source-table)]
- (lib.metadata.calculation/visible-columns query stage-number table-metadata options)))
- ;; 1e. Metadata associated with a Metric
- (when metric-based?
- (metric-metadata query stage-number card options))
- ;; 1c. Metadata associated with a saved Question
- (when source-card
- (saved-question-visible-columns query stage-number source-card (assoc options :include-implicitly-joinable? false)))
- ;; 1d: `:lib/stage-metadata` for the (presumably native) query
- (for [col (get-in this-stage [:lib/stage-metadata :columns])
- :let [source-column-alias ((some-fn :lib/source-column-alias :name) col)]]
- (assoc col
- :lib/source :source/native
- :lib/source-column-alias source-column-alias))))))
+ (vec
+ (or
+ ;; 1a. columns returned by previous stage
+ (visible-columns-from-previous-stage-returned-columns query stage-number options)
+ ;; 1b: default visible Fields for the source Table
+ (when source-table
+ (assert (integer? source-table))
+ (let [table-metadata (lib.metadata/table query source-table)]
+ (lib.metadata.calculation/visible-columns query stage-number table-metadata options)))
+ ;; 1e. Metadata associated with a Metric
+ (when metric-based?
+ (metric-visible-columns query stage-number card options))
+ ;; 1c. Metadata associated with a saved Question
+ (when source-card
+ (when-let [cols (not-empty (saved-question-visible-columns query stage-number source-card
+ (assoc options :include-implicitly-joinable? false)))]
+ (into []
+ (comp (map lib.field.util/update-keys-for-col-from-previous-stage)
+ (map (fn [col]
+ (assoc col :lib/source :source/card))))
+ cols)))
+ ;; 1d: `:lib/stage-metadata` for the (presumably native) query
+ (mapv (fn [col]
+ (let [source-column-alias ((some-fn :lib/source-column-alias :name) col)]
+ (assoc col
+ :lib/source :source/native
+ :lib/source-column-alias source-column-alias)))
+ (get-in this-stage [:lib/stage-metadata :columns]))))))
(mu/defn- existing-visible-columns :- ::lib.metadata.calculation/visible-columns
[query :- ::lib.schema/query
@@ -218,7 +227,7 @@
(lib.metadata.calculation/remapped-columns query stage-number source-columns options)
;; 4: columns added by joins at this stage
(when include-joined?
- (lib.join/all-joins-visible-columns query stage-number options)))))
+ (lib.join/all-joins-visible-columns-relative-to-parent-stage query stage-number options)))))
(mu/defmethod lib.metadata.calculation/visible-columns-method ::stage :- ::lib.metadata.calculation/visible-columns
[query :- ::lib.schema/query
@@ -226,12 +235,10 @@
_stage :- ::lib.schema/stage
{:keys [include-implicitly-joinable?], :as options} :- ::lib.metadata.calculation/visible-columns.options]
(let [existing-columns (existing-visible-columns query stage-number options)]
- (->> (concat
- existing-columns
- ;; add implicitly joinable columns if desired
+ (into (vec existing-columns)
+ ;; add implicitly joinable columns if desired
(when include-implicitly-joinable?
- (lib.metadata.calculation/implicitly-joinable-columns query stage-number existing-columns)))
- vec)))
+ (lib.metadata.calculation/implicitly-joinable-columns query stage-number existing-columns)))))
(defn- add-cols-from-join-duplicate?
"Whether two columns are considered to be the same for purposes of [[add-cols-from-join]]."
@@ -248,15 +255,14 @@
bucket)))]
(= (bucket col-1)
(bucket col-2)))
- ;; compare by IDs if we have ID info for both.
- (if (every? :id [col-1 col-2])
- ;; same IDs
- (= (:id col-1) (:id col-2))
- ;; same names
- (some (fn [f]
- (= (f col-2)
- (f col-1)))
- [:lib/desired-column-alias :lib/source-column-alias :lib/deduplicated-name :name]))))
+ ;; compare by something that both columns have, trying ID first falling back to column name
+ (let [k (m/find-first (fn [k]
+ (and (k col-1)
+ (k col-2)))
+ [:id :lib/source-column-alias :name])]
+ (assert k "No key common to both columns")
+ (= (k col-1)
+ (k col-2)))))
(defn- add-cols-from-join
"The columns from `:fields` may contain columns from `:joins` -- so if the joins specify their own `:fields` we need
diff --git a/src/metabase/lib/table.cljc b/src/metabase/lib/table.cljc
index 1cf576a7c05..80c1b17ba41 100644
--- a/src/metabase/lib/table.cljc
+++ b/src/metabase/lib/table.cljc
@@ -45,9 +45,9 @@
(mu/defmethod lib.metadata.calculation/returned-columns-method :metadata/table :- ::lib.metadata.calculation/returned-columns
[query _stage-number table-metadata _options]
- (when-let [field-metadatas (lib.metadata/fields query (:id table-metadata))]
+ (when-let [cols (lib.metadata/fields query (:id table-metadata))]
(into []
(comp remove-hidden-default-fields-xform
(map #(assoc % :lib/source :source/table-defaults))
(lib.field.util/add-source-and-desired-aliases-xform query))
- (sort-default-fields field-metadatas))))
+ (sort-default-fields cols))))
diff --git a/src/metabase/query_processor/middleware/add_implicit_joins.clj b/src/metabase/query_processor/middleware/add_implicit_joins.clj
index f127d864c30..18fb70c726f 100644
--- a/src/metabase/query_processor/middleware/add_implicit_joins.clj
+++ b/src/metabase/query_processor/middleware/add_implicit_joins.clj
@@ -44,7 +44,7 @@
[:map
{:closed true} ; closed because it is used as a map key
[:fk-field-id ::lib.schema.id/field]
- [:fk-field-name {:optional true} ::lib.schema.common/non-blank-string]
+ [:fk-field-name {:optional true} :string]
[:fk-join-alias {:optional true} ::lib.schema.join/alias]])
(mr/def ::join
@@ -55,7 +55,7 @@
[:strategy [:= :left-join]]
[:conditions [:tuple :mbql.clause/=]] ; exactly one condition
[:fk-field-id ::lib.schema.id/field]
- [:fk-field-name {:optional true} [:maybe ::lib.schema.common/non-blank-string]]
+ [:fk-field-name {:optional true} [:maybe :string]]
[:fk-join-alias {:optional true} [:maybe ::lib.schema.join/alias]]]])
(mu/defn- fk-field-infos->joins :- [:maybe [:sequential ::join]]
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index f027da2a3ac..6a89a74b84f 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -210,7 +210,7 @@
{:fn (middleware-fn-name middleware-fn), :query query, :result <>, :type qp.error-type/qp})))))
(catch Throwable e
(let [middleware-fn (middleware-fn-name middleware-fn)]
- (throw (ex-info (i18n/tru "Error preprocessing query in {0}: {1}" middleware-fn (ex-message e))
+ (throw (ex-info (i18n/tru "Error preprocessing query in {0}: {1}" middleware-fn ((some-fn ex-message class) e))
{:fn middleware-fn, :query query, :type qp.error-type/qp}
e)))))))
query
diff --git a/src/metabase/query_processor/store.clj b/src/metabase/query_processor/store.clj
index bce5bb7d182..7f3f225bbc4 100644
--- a/src/metabase/query_processor/store.clj
+++ b/src/metabase/query_processor/store.clj
@@ -9,9 +9,9 @@
(qp.store/field 10) ;; get Field 10
- Of course, it would be entirely possible to call `(t2/select-one Field :id 10)` every time you needed information about that Field,
- but fetching all Fields in a single pass and storing them for reuse is dramatically more efficient than fetching
- those Fields potentially dozens of times in a single query execution."
+ Of course, it would be entirely possible to call `(t2/select-one Field :id 10)` every time you needed information
+ about that Field, but fetching all Fields in a single pass and storing them for reuse is dramatically more efficient
+ than fetching those Fields potentially dozens of times in a single query execution."
(:require
[metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
[metabase.lib.core :as lib]
diff --git a/src/metabase/query_processor/util/add_alias_info.clj b/src/metabase/query_processor/util/add_alias_info.clj
index 45b38d15ce7..d307192af58 100644
--- a/src/metabase/query_processor/util/add_alias_info.clj
+++ b/src/metabase/query_processor/util/add_alias_info.clj
@@ -68,11 +68,14 @@
[metabase.util.malli.registry :as mr]
[metabase.util.performance :as perf]))
+(def ^:private ^:dynamic ^{:arglists '([driver s])} *escape-alias-fn*
+ #'driver/escape-alias)
+
(defn- prefix-field-alias
"Generate a field alias by applying `prefix` to `field-alias`. This is used for automatically-generated aliases for
columns that are the result of joins."
[prefix field-alias]
- (driver/escape-alias driver/*driver* (str prefix "__" field-alias)))
+ (*escape-alias-fn* driver/*driver* (str prefix "__" field-alias)))
(defn- make-unique-alias-fn
"Creates a function with the signature
@@ -86,7 +89,7 @@
(fn unique-alias-fn [position original-alias]
(assert (string? original-alias)
(format "unique-alias-fn expected string, got: %s" (pr-str original-alias)))
- (unique-name-fn position (driver/escape-alias driver/*driver* original-alias)))))
+ (unique-name-fn position (*escape-alias-fn* driver/*driver* original-alias)))))
;; TODO -- this should probably limit the resulting alias, and suffix a short hash as well if it gets too long. See also
;; [[unique-alias-fn]] below.
@@ -310,7 +313,7 @@
;; otherwise if this is a nominal field literal ref then look for matches based on the string name used
(when-let [field-names (let [[_ id-or-name] field-clause]
(when (string? id-or-name)
- [id-or-name (some-> driver/*driver* (driver/escape-alias id-or-name))]))]
+ [id-or-name (some-> driver/*driver* (*escape-alias-fn* id-or-name))]))]
(some #(field-name-match % all-exports source-metadata field-exports) field-names))
;; if all of that failed then try to find a match using `:lib/deduplicated-name` (if present)
(let [[_ id-or-name] field-clause]
@@ -443,7 +446,7 @@
;; potentially break by doing this. I haven't been able to reproduce it yet however.
;;
;; This will only be triggered if the join somehow exposes duplicate columns or columns that have the same escaped
- ;; name after going thru [[driver/escape-alias]]. I think the only way this could happen is if we escape them
+ ;; name after going thru [[*escape-alias-fn*]]. I think the only way this could happen is if we escape them
;; aggressively but the escape logic produces duplicate columns (i.e., there is overlap between the unique hashes we
;; suffix to escaped identifiers.)
;;
@@ -620,7 +623,7 @@
(if (and (map? form)
(seq (:joins form)))
(as-> form form
- (update form :joins (let [unique (comp (partial driver/escape-alias driver/*driver*)
+ (update form :joins (let [unique (comp (partial *escape-alias-fn* driver/*driver*)
(make-join-alias-unique-name-generator))]
(fn [joins]
(mapv (fn [join]
diff --git a/src/metabase/query_processor/util/transformations/nest_breakouts.clj b/src/metabase/query_processor/util/transformations/nest_breakouts.clj
index 7555b275159..0962cc0e400 100644
--- a/src/metabase/query_processor/util/transformations/nest_breakouts.clj
+++ b/src/metabase/query_processor/util/transformations/nest_breakouts.clj
@@ -1,11 +1,11 @@
(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 Lib
+ rather than in QP -- we should move it there."
(:require
[flatland.ordered.set :as ordered-set]
[medley.core :as m]
- [metabase.driver :as driver]
[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.metadata :as lib.schema.metadata]
[metabase.lib.schema.util :as lib.schema.util]
@@ -43,25 +43,15 @@
lib.util/fresh-uuids
(fields-used-in-breakouts-aggregations-or-expressions stage)))))
-;;; TODO (Cam 7/7/25) -- update this to use [[metabase.lib.field.util/update-keys-for-col-from-previous-stage]] instead
-;;; of its own weird bespoke version of the same thing.
-(mu/defn- update-metadata-from-previous-stage-to-produce-correct-ref-in-current-stage :- ::lib.schema.metadata/column
- "Force a `[:field {} <name>]` ref. Must manually escape field refs here, since `escape-join-aliases` mw is already run."
- [col :- ::lib.schema.metadata/column]
- (-> col
- (update :lib/desired-column-alias #(driver/escape-alias driver/*driver* %))
- (assoc :lib/source :source/previous-stage
- :lib/source-column-alias (driver/escape-alias driver/*driver* (:lib/desired-column-alias col)))
- (lib/with-temporal-bucket (if (isa? ((some-fn :effective-type :base-type) col) :type/Temporal)
- ;; for temporal columns: set temporal type to `:default` to
- ;; prevent [[metabase.query-processor.middleware.auto-bucket-datetimes]] from
- ;; trying to mess with it.
+(defn- update-temporal-bucket
+ "For temporal columns: set temporal type to `:default` to
+ prevent [[metabase.query-processor.middleware.auto-bucket-datetimes]] from trying to mess with it.
+
+ For other columns: remove temporal type, it should be nil anyway but remove it to be safe."
+ [col]
+ (lib/with-temporal-bucket col (if (isa? ((some-fn :effective-type :base-type) col) :type/Temporal)
:default
- ;; for other columns: remove temporal type, it should be nil anyway but remove it to
- ;; be safe.
- nil))
- (lib/with-binning nil)
- (dissoc :lib/expression-name)))
+ nil)))
(mu/defn- update-second-stage-refs :- ::lib.schema/stage
[stage :- ::lib.schema/stage
@@ -71,9 +61,10 @@
(if-let [col (when-not (some #{:expressions} &parents)
(lib.equality/find-matching-column &match first-stage-cols))]
(-> col
- update-metadata-from-previous-stage-to-produce-correct-ref-in-current-stage
+ lib/update-keys-for-col-from-previous-stage
+ update-temporal-bucket
lib/ref
- (cond-> (:lib/external-remap col) (lib.options/update-options assoc ::externally-remapped-field true)))
+ (cond-> (:lib/external-remap col) (lib/update-options assoc ::externally-remapped-field true)))
(lib.util/fresh-uuids &match))))
(def ^:private granularity
@@ -102,6 +93,7 @@
(if (and (some? temporal-unit) (not= temporal-unit :default))
temporal-unit
(or (:original-temporal-unit temporal-attributes)
+ (:inherited-temporal-unit temporal-attributes)
(:metabase.lib.field/original-temporal-unit temporal-attributes)
temporal-unit))))
@@ -134,7 +126,7 @@
(recur (next bs) (inc i) granularity i)
(recur (next bs) (inc i) min-granularity finest-index))))))
-(defn- add-implicit-breakouts
+(defn- add-implicit-breakout-order-bys
[stage]
(if-let [breakouts (not-empty (:breakout stage))]
(let [finest-temp-breakout (finest-temporal-breakout-index breakouts 1)
@@ -149,7 +141,7 @@
(comp (map lib.schema.util/remove-lib-uuids)
(remove explicit-order-by-exprs)
(map (fn [expr]
- (lib.options/ensure-uuid [:asc (lib.options/ensure-uuid expr)]))))
+ (lib/ensure-uuid [:asc (lib/ensure-uuid expr)]))))
breakout-exprs)]
(assoc stage :order-by order-bys))
stage))
@@ -167,7 +159,7 @@
(dissoc :joins :source-table :source-card :lib/stage-metadata :filters)
(update-second-stage-refs first-stage-cols)
(dissoc :expressions)
- add-implicit-breakouts)))
+ add-implicit-breakout-order-bys)))
(mu/defn- nest-breakouts-in-stage :- [:maybe [:sequential {:min 2, :max 2} ::lib.schema/stage]]
[query :- ::lib.schema/query
diff --git a/test/metabase/lib/aggregation_test.cljc b/test/metabase/lib/aggregation_test.cljc
index 7b164d2f799..1d54d74f250 100644
--- a/test/metabase/lib/aggregation_test.cljc
+++ b/test/metabase/lib/aggregation_test.cljc
@@ -46,8 +46,9 @@
(deftest ^:parallel aggregation-names-test
(are [aggregation-clause expected] (= expected
- {:column-name (aggregation-column-name aggregation-clause)
- :display-name (aggregation-display-name aggregation-clause)})
+ (let [clause (lib/normalize aggregation-clause)]
+ {:column-name (aggregation-column-name clause)
+ :display-name (aggregation-display-name clause)}))
[:count {}]
{:column-name "count", :display-name "Count"}
@@ -141,7 +142,7 @@
(col-info-for-aggregation-clause query -1 clause))
([query stage clause]
- (lib/metadata query stage clause)))
+ (lib/metadata query stage (lib/normalize clause))))
(deftest ^:parallel col-info-for-aggregation-clause-test
(are [clause expected] (=? expected
diff --git a/test/metabase/lib/breakout_test.cljc b/test/metabase/lib/breakout_test.cljc
index c3bb31ffde6..3bcf0dee81a 100644
--- a/test/metabase/lib/breakout_test.cljc
+++ b/test/metabase/lib/breakout_test.cljc
@@ -537,15 +537,15 @@
(deftest ^:parallel breakoutable-columns-include-all-visible-columns-test
(testing "Include all visible columns, not just projected ones (#31233)"
- (is (= ["ID"
- "NAME"
- "CATEGORY_ID"
- "LATITUDE"
- "LONGITUDE"
- "PRICE"
- "Categories__ID" ; this column is not projected, but should still be returned.
- "Categories__NAME"]
- (map :lib/desired-column-alias
+ (is (= [[nil "ID"]
+ [nil "NAME"]
+ [nil "CATEGORY_ID"]
+ [nil "LATITUDE"]
+ [nil "LONGITUDE"]
+ [nil "PRICE"]
+ ["Categories" "ID"] ; this column is not projected, but should still be returned.
+ ["Categories" "NAME"]]
+ (map (juxt :metabase.lib.join/join-alias :lib/source-column-alias)
(-> (lib.tu/venues-query)
(lib/join (-> (lib/join-clause
(meta/table-metadata :categories)
diff --git a/test/metabase/lib/card_test.cljc b/test/metabase/lib/card_test.cljc
index 6e2c3982951..583714826c5 100644
--- a/test/metabase/lib/card_test.cljc
+++ b/test/metabase/lib/card_test.cljc
@@ -119,7 +119,6 @@
(is (=? (->> (cols-of :orders)
sort-cols)
(sort-cols (get-in (lib.tu/mock-cards) [:orders :result-metadata]))))
-
(is (=? (->> (concat (from :source/card (cols-of :orders))
(implicitly-joined (cols-of :people))
(implicitly-joined (cols-of :products)))
@@ -234,8 +233,10 @@
rhs (m/find-first (comp #{"ID"} :name) (lib/join-condition-rhs-columns query 0 people-card nil nil))
join-clause (lib/join-clause people-card [(lib/= lhs rhs)])
query (lib/join query join-clause)
- filter-col (m/find-first (comp #{"Mock people card__ID"} :lib/desired-column-alias)
+ filter-col (m/find-first #(and (= (:metabase.lib.join/join-alias %) "Mock people card")
+ (= (:lib/source-column-alias %) "ID"))
(lib/filterable-columns query))
+ _ (assert (some? filter-col) "Failed to find filter column")
query (-> query
(lib/filter (lib/= filter-col 1))
(lib/aggregate (lib/distinct filter-col))
diff --git a/test/metabase/lib/drill_thru/column_filter_test.cljc b/test/metabase/lib/drill_thru/column_filter_test.cljc
index 34c964ec946..ff40c0fb8fc 100644
--- a/test/metabase/lib/drill_thru/column_filter_test.cljc
+++ b/test/metabase/lib/drill_thru/column_filter_test.cljc
@@ -210,7 +210,7 @@
:type :drill-thru/column-filter
:query query
:stage-number 1
- :column (-> query lib/returned-columns second)}
+ :column (-> query lib/returned-columns second (dissoc :lib/desired-column-alias :lib/deduplicated-name))}
(->> {:column count-col
:column-ref (lib/ref count-col)
:value nil}
diff --git a/test/metabase/lib/drill_thru/underlying_records_test.cljc b/test/metabase/lib/drill_thru/underlying_records_test.cljc
index 5ccc3cd019c..a0c5e003ad5 100644
--- a/test/metabase/lib/drill_thru/underlying_records_test.cljc
+++ b/test/metabase/lib/drill_thru/underlying_records_test.cljc
@@ -569,7 +569,7 @@
bucket-expr (m/find-first #(= (:name %) "cost bucket") cols)
query (lib/breakout base bucket-expr)
[bucket count-col] (lib/returned-columns query)
- bucket-dim {:column (dissoc bucket :lib/expression-name)
+ bucket-dim {:column (dissoc bucket :lib/expression-name :lib/source)
:column-ref (lib/ref bucket)
:value "12"}
count-dim {:column count-col
diff --git a/test/metabase/lib/drill_thru_test.cljc b/test/metabase/lib/drill_thru_test.cljc
index 6298c4855e8..1c2632b48d0 100644
--- a/test/metabase/lib/drill_thru_test.cljc
+++ b/test/metabase/lib/drill_thru_test.cljc
@@ -865,7 +865,7 @@
metadata-provider (lib.tu/metadata-provider-with-mock-card card)
query (lib/query metadata-provider card)
lib-col (-> (m/find-first #(= (:name %) "CREATED_AT") (lib/returned-columns query))
- (dissoc :lib/deduplicated-name :lib/original-name))
+ (dissoc :lib/deduplicated-name :lib/original-name :lib/desired-column-alias))
card-col (m/find-first #(= (:name %) "CREATED_AT") (:result-metadata card))
context {:column card-col
:column-ref (lib/ref card-col)
diff --git a/test/metabase/lib/equality_test.cljc b/test/metabase/lib/equality_test.cljc
index 5f1845810ce..27ff194f01b 100644
--- a/test/metabase/lib/equality_test.cljc
+++ b/test/metabase/lib/equality_test.cljc
@@ -357,8 +357,7 @@
table-col #(assoc % :lib/source :source/table-defaults)
join-col #(-> %
(merge {:lib/source :source/joins
- :metabase.lib.join/join-alias "Orders"
- :lib/desired-column-alias (str "Orders__" (:name %))}))
+ :metabase.lib.join/join-alias "Orders"}))
sorted #(sort-by (juxt :position :source-alias) %)
visible (lib/visible-columns query)]
(is (=? (->> (sorted (concat (map table-col cols)
@@ -409,7 +408,7 @@
{:lib/desired-column-alias "Orders__ID"}]
(lib/returned-columns just-3)))
(testing "matching the four fields against"
- (let [hr-own-id {:lib/type :metadata/column
+ (let [hr-own-id {:lib/type :metadata/column
:description "Own ID"
:base-type :type/BigInteger
:semantic-type :type/PK
@@ -422,7 +421,7 @@
:parent-id nil
:display-name "ID"
:position 0}
- hr-own-tax {:lib/type :metadata/column
+ hr-own-tax {:lib/type :metadata/column
:description "Own Tax"
:base-type :type/Float
:semantic-type nil
@@ -435,49 +434,49 @@
:parent-id nil
:display-name "Tax"
:position 4}
- hr-join-id {:lib/type :metadata/column
- :description "Join ID"
- :base-type :type/BigInteger
- :semantic-type :type/PK
- :effective-type :type/BigInteger
- :table-id (meta/id :orders)
- :id (meta/id :orders :id)
- :name "ID_2"
- :source-alias "Orders"
- :lib/source :source/joins
- :fk-target-field-id nil
- :parent-id nil
- :display-name "Orders → ID"
- :position 0}
- hr-join-tax {:lib/type :metadata/column
- :description "Join Tax"
- :base-type :type/Float
- :semantic-type nil
- :effective-type :type/Float
- :table-id (meta/id :orders)
- :id (meta/id :orders :tax)
- :name "TAX_2"
- :source-alias "Orders"
- :lib/source :source/joins
- :fk-target-field-id nil
- :parent-id nil
- :display-name "Orders → Tax"
- :position 4}
- ret-4 [hr-own-id hr-own-tax hr-join-id hr-join-tax]
- ret-3 [hr-own-id hr-own-tax hr-join-id]
- refs (for [join-alias [nil "Orders"]
- [column coltype] [[:id :type/Integer] [:tax :type/Float]]]
- [:field (merge {:lib/uuid (str (random-uuid))
- :base-type coltype
- :effective-type coltype}
- (when join-alias
- {:join-alias join-alias}))
- (meta/id :orders column)])
- exp-4 [{:display-name "ID"}
- {:display-name "Tax"}
- {:display-name "Orders → ID"}
- {:display-name "Orders → Tax"}]
- exp-3 (update exp-4 3 (constantly nil))]
+ hr-join-id {:lib/type :metadata/column
+ :description "Join ID"
+ :base-type :type/BigInteger
+ :semantic-type :type/PK
+ :effective-type :type/BigInteger
+ :table-id (meta/id :orders)
+ :id (meta/id :orders :id)
+ :name "ID_2"
+ :metabase.lib.join/join-alias "Orders"
+ :lib/source :source/joins
+ :fk-target-field-id nil
+ :parent-id nil
+ :display-name "Orders → ID"
+ :position 0}
+ hr-join-tax {:lib/type :metadata/column
+ :description "Join Tax"
+ :base-type :type/Float
+ :semantic-type nil
+ :effective-type :type/Float
+ :table-id (meta/id :orders)
+ :id (meta/id :orders :tax)
+ :name "TAX_2"
+ :metabase.lib.join/join-alias "Orders"
+ :lib/source :source/joins
+ :fk-target-field-id nil
+ :parent-id nil
+ :display-name "Orders → Tax"
+ :position 4}
+ ret-4 [hr-own-id hr-own-tax hr-join-id hr-join-tax]
+ ret-3 [hr-own-id hr-own-tax hr-join-id]
+ refs (for [join-alias [nil "Orders"]
+ [column coltype] [[:id :type/Integer] [:tax :type/Float]]]
+ [:field (merge {:lib/uuid (str (random-uuid))
+ :base-type coltype
+ :effective-type coltype}
+ (when join-alias
+ {:join-alias join-alias}))
+ (meta/id :orders column)])
+ exp-4 [{:display-name "ID"}
+ {:display-name "Tax"}
+ {:display-name "Orders → ID"}
+ {:display-name "Orders → Tax"}]
+ exp-3 (update exp-4 3 (constantly nil))]
(testing "all-4 matches everything"
(is (=? exp-4
(->> refs
@@ -693,6 +692,16 @@
(lib/append-stage))
columns (lib/fieldable-columns query)
column-refs (mapv lib.ref/ref columns)]
+ (is (=? [{:lib/source-column-alias "CREATED_AT"
+ :inherited-temporal-unit :year}
+ {:lib/source-column-alias "CREATED_AT_2"
+ :inherited-temporal-unit :month}
+ {:lib/source-column-alias "count"}]
+ columns))
+ (is (=? [[:field {:inherited-temporal-unit :year} "CREATED_AT"]
+ [:field {:inherited-temporal-unit :month} "CREATED_AT_2"]
+ [:field {} "count"]]
+ column-refs))
(is (=? [:field {} "CREATED_AT"]
(lib.equality/find-matching-ref (first columns) column-refs)))
(is (=? [:field {} "CREATED_AT_2"]
@@ -738,7 +747,7 @@
{:base-type :type/BigInteger, :lib/uuid "00000000-0000-0000-0000-000000000001"}
"Products__ID"]]))
cols (lib/visible-columns query)]
- (is (=? {:name "ID_2", :lib/desired-column-alias "Products__ID"}
+ (is (=? {:name "ID_2", :lib/source-column-alias "Products__ID"}
(lib.equality/find-matching-column
[:field
{:base-type :type/BigInteger, :lib/uuid "00000000-0000-0000-0000-000000000002"}
@@ -760,7 +769,6 @@
:last-analyzed "2025-06-24T20:58:41.088313-07:00"
:lib/deduplicated-name "CREATED_AT"
:lib/desired-column-alias "CREATED_AT"
- :lib/hack-original-name "CREATED_AT"
:lib/original-display-name "Created At"
:lib/original-name "CREATED_AT"
:lib/original-ref [:field {:base-type :type/DateTime, :temporal-unit :year, :lib/uuid "aa4324c7-12d2-46fe-ba8d-8f1fe54b61af", :effective-type :type/DateTime} 39]
@@ -782,7 +790,6 @@
:last-analyzed "2025-06-24T20:58:41.088313-07:00"
:lib/deduplicated-name "CREATED_AT_2"
:lib/desired-column-alias "CREATED_AT_2"
- :lib/hack-original-name "CREATED_AT"
:lib/original-display-name "Created At"
:lib/original-name "CREATED_AT"
:lib/original-ref [:field {:base-type :type/DateTime, :temporal-unit :month, :lib/uuid "1f16a57a-2afd-4c92-8d6c-b41062235a49", :effective-type :type/DateTime} 39]
@@ -941,15 +948,14 @@
:base-type :type/Text
:join-alias "question b - Product"}
"TITLE"]
- (lib.equality/find-matching-ref col refs {:match-type ::lib.equality/match-type.same-stage}))))))
+ (lib.equality/find-matching-ref col refs))))))
(deftest ^:parallel same-stage-matching-do-not-barf-when-trying-to-find-a-match-for-an-expression-ref-test
(let [[col] (lib/returned-columns (lib/query meta/metadata-provider (meta/table-metadata :venues)))]
;; just make sure this doesn't barf.
(is (nil? (lib.equality/find-matching-ref
col
- [[:expression {:lib/uuid (str (random-uuid)), :base-type :type/Integer} "bad_expression"]]
- {:match-type ::lib.equality/match-type.same-stage})))))
+ [[:expression {:lib/uuid (str (random-uuid)), :base-type :type/Integer} "bad_expression"]])))))
(deftest ^:parallel pick-correct-column-when-one-is-from-join-and-on-is-not-test
(testing "If we have two cols and one has a join alias and one doesn't, and our ref has no alias, then pick the col with no alias"
@@ -1019,7 +1025,7 @@
:join-alias "Orders"}
55603]]]
(is (= (first refs)
- (lib.equality/find-matching-ref col refs {:match-type ::lib.equality/match-type.same-stage})))))
+ (lib.equality/find-matching-ref col refs)))))
(deftest ^:parallel match-by-source-field-test
(let [col {:base-type :type/BigInteger
@@ -1040,4 +1046,76 @@
refs [[:field {:base-type :type/BigInteger, :lib/uuid "b10907ef-d71b-4ddc-b3b9-ff0fda706b6d"} "ID"]
[:field {:base-type :type/BigInteger, :source-field 35, :source-field-name "USER_ID", :lib/uuid "1cb6708d-754d-48b9-b44f-660a7c91561d", :effective-type :type/BigInteger} 24]]]
(is (= (second refs)
- (lib.equality/find-matching-ref col refs {:match-type ::lib.equality/match-type.same-stage})))))
+ (lib.equality/find-matching-ref col refs)))))
+
+(deftest ^:parallel find-matching-column-prefer-exact-matches-test
+ (testing `lib.equality/find-matching-column
+ (testing "For field name refs, prefer matches that have the same [lack of] join alias and same source-column-alias"
+ (let [a-ref [:field
+ {:lib/uuid "00000000-0000-0000-0000-000000000000"
+ :effective-type :type/Text
+ :base-type :type/Text}
+ "Cat__NAME"]
+ ;; here we have TWO potential matches with `:lib/source-uuid` -- this happens
+ ;; in [[metabase.query-processor.util.add-alias-info]] when we search thru the concatenation of
+ ;; `returned-columns` and `visible-columns`. The first potential match has the wrong join alias and source
+ ;; column alias; the second is an exact match. We should return the second.
+ col-1 (merge
+ (meta/field-metadata :categories :name)
+ {:lib/deduplicated-name "NAME"
+ :lib/desired-column-alias "Cat__NAME"
+ :lib/original-join-alias "Cat"
+ :lib/original-name "NAME"
+ :lib/source :source/joins
+ :lib/source-column-alias "NAME"
+ :lib/source-uuid "00000000-0000-0000-0000-000000000000"
+ :metabase.lib.join/join-alias "Cat"
+ :name "NAME"})
+ col-2 (merge
+ (meta/field-metadata :categories :name)
+ {:lib/deduplicated-name "NAME"
+ :lib/desired-column-alias "Cat__NAME"
+ :lib/original-display-name "Name"
+ :lib/original-join-alias "Cat"
+ :lib/original-name "NAME"
+ :lib/source :source/previous-stage
+ :lib/source-column-alias "Cat__NAME"
+ :lib/source-uuid "00000000-0000-0000-0000-000000000000"
+ :lib/type :metadata/column
+ :name "NAME"})]
+ (doseq [cols [[col-1 col-2]
+ [col-2 col-1]]]
+ (is (= col-2
+ (lib.equality/find-matching-column a-ref cols))))))))
+
+(deftest ^:parallel never-return-match-with-different-id-test
+ (testing "find-matching-ref should never return a match with a different :id"
+ (let [field-refs (mapv #(lib/normalize :mbql.clause/field %)
+ [[:field {} 10]
+ [:field {} 8]
+ [:field {} 7]
+ [:field {} 1]
+ [:field {} 3]
+ [:field {} 2]
+ [:field {} 4]
+ [:field {} 6]
+ [:field {} 5]
+ [:field {:source-field 8} 20]])
+ col {:base-type :type/Text
+ :display-name "Address"
+ :effective-type :type/Text
+ :fk-field-id 8
+ :fk-target-field-id nil
+ :id 23
+ :name "ADDRESS"
+ :position 1
+ :preview-display true
+ :table-id 10
+ :visibility-type :normal
+ :lib/deduplicated-name "ADDRESS"
+ :lib/desired-column-alias "ADDRESS"
+ :lib/original-name "ADDRESS"
+ :lib/source :source/implicitly-joinable
+ :lib/source-column-alias "ADDRESS"
+ :lib/type :metadata/column}]
+ (is (nil? (lib.equality/find-matching-ref col field-refs))))))
diff --git a/test/metabase/lib/field/resolution_test.cljc b/test/metabase/lib/field/resolution_test.cljc
index 493200bbaca..eebf88fbf96 100644
--- a/test/metabase/lib/field/resolution_test.cljc
+++ b/test/metabase/lib/field/resolution_test.cljc
@@ -460,7 +460,6 @@
:visibility-type :normal
:lib/original-binning {:strategy :default}
:lib/card-id 1
- :lib/desired-column-alias "C__NAME"
:lib/original-display-name "Name"
:lib/original-join-alias "C"
:lib/original-name "NAME"
@@ -474,7 +473,6 @@
(binding [lib.metadata.calculation/*display-name-style* :long]
(testing "with model as :source-card (current-stage-source-card-metadata pathway)"
(is (=? (assoc expected
- :lib/deduplicated-name "NAME"
:name "NAME"
:lib/source-column-alias "C__NAME")
(lib.field.resolution/resolve-field-ref query -1 field-ref))))
@@ -522,14 +520,16 @@
(deftest ^:parallel column-filter-join-alias-test
(testing "We should be able to resolve a ref missing join alias and add that to the metadata (#36861)"
- (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
- (lib/join (lib/join-clause (meta/table-metadata :products)
- [(lib/= (meta/field-metadata :orders :product-id)
- (meta/field-metadata :products :id))])))
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/join (lib/join-clause (meta/table-metadata :products)
+ [(lib/= (meta/field-metadata :orders :product-id)
+ (meta/field-metadata :products :id))])))
broken-ref [:field {:lib/uuid "00000000-0000-0000-0000-000000000000", :base-type :type/Text} "CATEGORY"]]
(is (=? {:id (meta/id :products :category)
:table-id (meta/id :products)
:name "CATEGORY"
+ :lib/source :source/joins
+ :lib/source-column-alias "CATEGORY"
:lib/original-join-alias "Products"
:metabase.lib.join/join-alias "Products"}
(lib.field.resolution/resolve-field-ref query -1 broken-ref))))))
@@ -748,10 +748,10 @@
[:field (meta/id :venues :longitude) nil]
[:field (meta/id :venues :price) nil]]}})
field-ref [:field {:lib/uuid (str (random-uuid))} (meta/id :venues :name)]]
- (testing `lib.field.resolution/resolve-column-in-metadata
+ (testing `lib.field.resolution/resolve-column-in-previous-stage-metadata
(let [stage-cols (get-in (lib.util/query-stage query 0) [:lib/stage-metadata :columns])]
(is (=? {:name "NAME", :description "user description", :display-name "user display name"}
- (#'lib.field.resolution/resolve-column-in-metadata query field-ref stage-cols)))))
+ (#'lib.field.resolution/resolve-column-in-previous-stage-metadata query field-ref stage-cols)))))
(testing `lib.field.resolution/resolve-field-ref
(is (=? {:name "NAME", :description "user description", :display-name "user display name"}
(lib.field.resolution/resolve-field-ref query -1 field-ref))))))))
@@ -836,7 +836,6 @@
(map #(select-keys % [:name :lib/source-column-alias])
(lib/visible-columns q3))))
(is (=? {:lib/source-column-alias "Reviews__CREATED_AT"
- :lib/desired-column-alias "Reviews__CREATED_AT"
:lib/original-join-alias "Reviews"
:display-name "Reviews → Created At"}
(lib.field.resolution/resolve-field-ref
@@ -1099,7 +1098,6 @@
:display-name "Product → Category"
:lib/source :source/previous-stage
:lib/source-column-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"
- :lib/desired-column-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"
:fk-field-id (symbol "nil #_\"key is not present.\"")
:lib/original-fk-field-id (meta/id :orders :product-id)}
(lib.field.resolution/resolve-field-ref query 1 field-ref))))
@@ -1108,7 +1106,6 @@
:display-name "Product → Category"
:lib/source :source/previous-stage
:lib/source-column-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"
- :lib/desired-column-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"
:fk-field-id (symbol "nil #_\"key is not present.\"")
:lib/original-fk-field-id (meta/id :orders :product-id)}
(lib.field.resolution/resolve-field-ref query 2 field-ref)))))))))
@@ -1131,7 +1128,6 @@
:display-name "ID → Category"
:lib/source :source/previous-stage
:lib/source-column-alias "PRODUCTS__via__ID__CATEGORY"
- :lib/desired-column-alias "PRODUCTS__via__ID__CATEGORY"
:fk-field-id (symbol "nil #_\"key is not present.\"")
:lib/original-fk-field-id (meta/id :orders :id)}
(lib.field.resolution/resolve-field-ref query 1 field-ref))))
@@ -1140,7 +1136,6 @@
:display-name "ID → Category"
:lib/source :source/previous-stage
:lib/source-column-alias "PRODUCTS__via__ID__CATEGORY"
- :lib/desired-column-alias "PRODUCTS__via__ID__CATEGORY"
:fk-field-id (symbol "nil #_\"key is not present.\"")
:lib/original-fk-field-id (meta/id :orders :id)}
(lib.field.resolution/resolve-field-ref query 2 field-ref)))))))))
@@ -1150,7 +1145,7 @@
(let [query (-> (lib/query
meta/metadata-provider
(lib.tu.macros/mbql-query venues
- {:fields [&Category.categories.name]
+ {:fields [&Category.categories.id]
:joins [{:alias "Category"
:source-table $$categories
:condition [:= $category-id &Category.categories.id]
@@ -1216,3 +1211,34 @@
(lib.field.resolution/resolve-field-ref
query -1
[:field {:lib/uuid "00000000-0000-0000-0000-000000000000", :base-type :type/Float} "avg"]))))))
+
+(deftest ^:parallel return-correct-metadata-for-broken-field-refs-test
+ (testing "Do not propagate join alias in metadata for busted field refs that incorrectly use it (QUE-1496)"
+ (let [query (lib/query
+ meta/metadata-provider
+ (lib.tu.macros/mbql-query venues
+ {:source-query {:source-table $$venues
+ :joins [{:strategy :left-join
+ :source-table $$categories
+ :alias "Cat"
+ :condition [:= $category-id &Cat.categories.id]
+ :fields [&Cat.categories.name]}]
+ :fields [$id
+ &Cat.categories.name]}
+ ;; THIS REF IS WRONG -- it should not be using `Cat` because the join is in the source query
+ ;; rather than in the current stage. However, we should be smart enough to try to figure out
+ ;; what they meant.
+ :breakout [&Cat.categories.name]}))
+ [bad-ref] (lib/breakouts query -1)]
+ ;; maybe one day `lib/query` will automatically fix bad refs like these. If that happens, we probably don't even
+ ;; need this test anymore? Or we should update it so it's still testing with a bad ref rather than a fixed ref.
+ (is (=? [:field {:join-alias "Cat"} (meta/id :categories :name)]
+ bad-ref))
+ (is (=? {:table-id (meta/id :categories)
+ :id (meta/id :categories :name)
+ :name "NAME"
+ :lib/original-join-alias "Cat"
+ :metabase.lib.join/join-alias (symbol "nil #_\"key is not present.\"")
+ :lib/source-column-alias "Cat__NAME"
+ :lib/desired-column-alias (symbol "nil #_\"key is not present.\"")}
+ (lib.field.resolution/resolve-field-ref query -1 bad-ref))))))
diff --git a/test/metabase/lib/field_test.cljc b/test/metabase/lib/field_test.cljc
index 7d1580c6ee9..8aed15c77de 100644
--- a/test/metabase/lib/field_test.cljc
+++ b/test/metabase/lib/field_test.cljc
@@ -558,22 +558,22 @@
(deftest ^:parallel fieldable-columns-test
(testing "query with no :fields"
- (is (=? [{:lib/desired-column-alias "ID", :selected? true}
- {:lib/desired-column-alias "NAME", :selected? true}
- {:lib/desired-column-alias "CATEGORY_ID", :selected? true}
- {:lib/desired-column-alias "LATITUDE", :selected? true}
- {:lib/desired-column-alias "LONGITUDE", :selected? true}
- {:lib/desired-column-alias "PRICE", :selected? true}]
+ (is (=? [{:lib/source-column-alias "ID", :selected? true}
+ {:lib/source-column-alias "NAME", :selected? true}
+ {:lib/source-column-alias "CATEGORY_ID", :selected? true}
+ {:lib/source-column-alias "LATITUDE", :selected? true}
+ {:lib/source-column-alias "LONGITUDE", :selected? true}
+ {:lib/source-column-alias "PRICE", :selected? true}]
(lib/fieldable-columns (lib.tu/venues-query))))))
(deftest ^:parallel fieldable-columns-query-with-fields-test
(testing "query with :fields"
- (is (=? [{:lib/desired-column-alias "ID", :selected? true}
- {:lib/desired-column-alias "NAME", :selected? true}
- {:lib/desired-column-alias "CATEGORY_ID", :selected? false}
- {:lib/desired-column-alias "LATITUDE", :selected? false}
- {:lib/desired-column-alias "LONGITUDE", :selected? false}
- {:lib/desired-column-alias "PRICE", :selected? false}]
+ (is (=? [{:lib/source-column-alias "ID", :selected? true}
+ {:lib/source-column-alias "NAME", :selected? true}
+ {:lib/source-column-alias "CATEGORY_ID", :selected? false}
+ {:lib/source-column-alias "LATITUDE", :selected? false}
+ {:lib/source-column-alias "LONGITUDE", :selected? false}
+ {:lib/source-column-alias "PRICE", :selected? false}]
(-> (lib.tu/venues-query)
(lib/with-fields [(meta/field-metadata :venues :id)
(meta/field-metadata :venues :name)])
@@ -598,7 +598,7 @@
:semantic-type :type/Name
:lib/source :source/previous-stage
:effective-type :type/Text
- :lib/desired-column-alias "Categories__NAME"}
+ :lib/source-column-alias "Categories__NAME"}
joined-col))
(testing "Metadata should not contain inherited join information"
(is (not-any? :metabase.lib.join/join-alias (lib/returned-columns query))))
@@ -844,7 +844,6 @@
(-> query
(lib/add-field -1 (nth implicit-columns 6))
fields-of)))))
-
(testing "with explicit :fields list"
(let [field-query (->> table-columns
(take 4)
@@ -872,6 +871,17 @@
(lib/breakout (lib/with-temporal-bucket (meta/field-metadata :orders :created-at) :month))
(lib/append-stage))
columns (lib/fieldable-columns query)]
+ (is (=? [{:name "CREATED_AT"
+ :lib/source-column-alias "CREATED_AT"
+ :inherited-temporal-unit :year}
+ {:name "CREATED_AT"
+ :lib/source-column-alias "CREATED_AT_2"
+ :inherited-temporal-unit :month}
+ {:name "count"}]
+ columns))
+ (testing (str "Sanity check: initial query should have no `:fields` in the last stage (i.e., it should return"
+ " everything from the stage before that)")
+ (is (nil? (fields-of query))))
(testing "removing the column coming from the first breakout"
(is (=? [[:field {} "CREATED_AT_2"] [:field {} "count"]]
(-> query
@@ -1009,9 +1019,14 @@
viz-columns (lib/visible-columns query)
table-columns (lib/fieldable-columns query -1)
implicit-columns (filter #(= (:lib/source %) :source/implicitly-joinable) viz-columns)
+ _ (is (>= (count implicit-columns) 2)
+ "Not sure how many it should have but it should have at least the two we use")
implied-query (-> query
(lib/add-field -1 (first implicit-columns))
(lib/add-field -1 (second implicit-columns)))
+ _ (is (= 11
+ (count (get-in implied-query [:stages 0 :fields])))
+ "Sanity check: implied-query should now have 11 :fields")
table-fields (map clean-ref table-columns)
implied1 (clean-ref (first implicit-columns))
implied2 (clean-ref (second implicit-columns))]
@@ -1290,7 +1305,6 @@
:lib/source-column-alias "USER_ID"
:effective-type :type/Integer
:id (meta/id :checkins :user-id)
- :lib/desired-column-alias "USER_ID"
:display-name "User ID"}
(lib/find-visible-column-for-ref query col-ref))))))
@@ -1315,14 +1329,12 @@
:table-id (meta/id :orders)
:id (meta/id :orders :id)
:lib/source :source/table-defaults
- :lib/desired-column-alias "ID"
:display-name "ID"}
exp-src-tax {:lib/type :metadata/column
:lib/source-column-alias "TAX"
:table-id (meta/id :orders)
:id (meta/id :orders :tax)
:lib/source :source/table-defaults
- :lib/desired-column-alias "TAX"
:display-name "Tax"}
exp-join-id {:lib/type :metadata/column
:lib/source-column-alias "ID"
@@ -1330,7 +1342,6 @@
:table-id (meta/id :orders)
:id (meta/id :orders :id)
:lib/source :source/joins
- :lib/desired-column-alias "Orders__ID"
:metabase.lib.join/join-alias "Orders"
:display-name "ID"}
exp-join-tax {:lib/type :metadata/column
@@ -1338,18 +1349,18 @@
:table-id (meta/id :orders)
:id (meta/id :orders :tax)
:lib/source :source/joins
- :lib/desired-column-alias "Orders__TAX"
:metabase.lib.join/join-alias "Orders"
:display-name "Tax"}
columns (lib.metadata.calculation/returned-columns query)]
(is (=? [exp-src-id exp-src-tax exp-join-id exp-join-tax]
(lib.metadata.calculation/returned-columns query)))
- (doseq [[label column-alias] [["original ID column" "ID"]
- ["original TAX column" "TAX"]
- ["joined ID column" "Orders__ID"]
- ["joined TAX column" "Orders__TAX"]]]
+ (doseq [[label join-alias column-alias] [["original ID column" nil "ID"]
+ ["original TAX column" nil "TAX"]
+ ["joined ID column" "Orders" "ID"]
+ ["joined TAX column" "Orders" "TAX"]]]
(testing (str "when hiding the " label)
- (let [col-pred #(= (:lib/desired-column-alias %) column-alias)
+ (let [col-pred #(and (= (:metabase.lib.join/join-alias %) join-alias)
+ (= (:lib/source-column-alias %) column-alias))
to-hide (first (filter col-pred columns))
;_ (prn "to hide" to-hide)
;_ (prn "query" query)
@@ -1907,10 +1918,10 @@
:fields [$title $category]
:order-by [[:asc $id]]
:limit 3}))]
- (is (= [["TITLE" "Title"] ; products.title
- ["CATEGORY" "Category"] ; products.category
- ["TITLE_2" "Orders → Title"] ; orders.title
- ["sum" "Orders → Sum of Quantity"]] ; sum(orders.quantity)
+ (is (= [["TITLE" "Title"] ; products.title
+ ["CATEGORY" "Category"] ; products.category
+ ["TITLE_2" "Orders → Title"] ; orders.title
+ ["sum" "Orders → Sum of Quantity"]] ; sum(orders.quantity)
(map (juxt :lib/deduplicated-name :display-name)
(lib.metadata.result-metadata/returned-columns query)))))))
@@ -1925,7 +1936,7 @@
:aggregation [[:sum $orders.quantity]]}
:alias "Orders"
:condition [:= $id &Orders.orders.product-id]
- ;; we can get title since product-id is remapped to title
+ ;; we can get products.title since orders.product-id is remapped to title
:fields [&Orders.title
&Orders.*sum/Integer]}]
:fields [$title
@@ -1933,11 +1944,11 @@
[:field "sum" {:base-type :type/Integer, :join-alias "Orders"}]]
:order-by [[:asc $id]]
:limit 3}))]
- (is (= [["TITLE" "Title"] ; products.title
- ["CATEGORY" "Category"] ; products.category
- ["sum" "Orders → Sum of Quantity"] ; sum(orders.quantity)
- ["TITLE_2" "Orders → Title"]] ; orders.title
- (map (juxt :lib/deduplicated-name :display-name)
+ (is (= [[nil "TITLE" "Title"] ; products.title
+ [nil "CATEGORY" "Category"] ; products.category
+ ["Orders" "sum" "Orders → Sum of Quantity"] ; sum(orders.quantity)
+ ["Orders" "TITLE" "Orders → Title"]] ; orders.product-id remap to products.title
+ (map (juxt :metabase.lib.join/join-alias :lib/source-column-alias :display-name)
(lib.metadata.result-metadata/returned-columns query)))))))
(deftest ^:parallel propagate-binning-display-names-test
@@ -2152,7 +2163,7 @@
refs))
"expected ref should be present")
(is (=? [:field {:join-alias "question b - Product"} "TITLE"]
- (lib.equality/find-matching-ref b-title refs {:match-type ::lib.equality/match-type.same-stage}))
+ (lib.equality/find-matching-ref b-title refs))
"should find match"))))
(is (=? {:stages [{:joins [{:alias "question b - Product"
:fields (for [col (map :name b-cols)
diff --git a/test/metabase/lib/filter_test.cljc b/test/metabase/lib/filter_test.cljc
index ddc875ecaa3..04e5ef51168 100644
--- a/test/metabase/lib/filter_test.cljc
+++ b/test/metabase/lib/filter_test.cljc
@@ -239,7 +239,9 @@
(meta/field-metadata :checkins :venue-id)
(meta/field-metadata :venues :id))])
(lib/with-join-fields :all))))
- columns (lib/filterable-columns query)
+ columns (into []
+ (lib.field.util/add-source-and-desired-aliases-xform query)
+ (lib/filterable-columns query))
pk-operators [:= :!= :> :< :between :>= :<= :is-null :not-null]
temporal-operators [:!= := :< :> :between :is-null :not-null]
coordinate-operators [:= :!= :inside :> :< :between :>= :<=]
@@ -259,10 +261,7 @@
"Venues__PRICE"
"CATEGORIES__via__CATEGORY_ID__via__Venues__ID"
"CATEGORIES__via__CATEGORY_ID__via__Venues__NAME"]
- (into []
- (comp (lib.field.util/add-source-and-desired-aliases-xform query)
- (map :lib/desired-column-alias))
- columns)))
+ (map :lib/desired-column-alias columns)))
(testing "Operators are attached to proper columns"
(is (=? {"ID" pk-operators,
"NAME" text-operators,
diff --git a/test/metabase/lib/join_test.cljc b/test/metabase/lib/join_test.cljc
index cf33c04367a..5c80c613fa0 100644
--- a/test/metabase/lib/join_test.cljc
+++ b/test/metabase/lib/join_test.cljc
@@ -264,8 +264,8 @@
(let [metadata-provider (lib.tu/metadata-provider-with-cards-for-queries
meta/metadata-provider
[(lib.tu.macros/mbql-query checkins
- {:aggregation [[:count]]
- :breakout [$user-id]})])
+ {:aggregation [[:count]]
+ :breakout [$user-id]})])
join {:lib/type :mbql/join
:lib/options {:lib/uuid "d7ebb6bd-e7ac-411a-9d09-d8b18329ad46"}
:stages [{:lib/type :mbql.stage/mbql
@@ -288,16 +288,16 @@
:stages [{:lib/type :mbql.stage/mbql
:source-table (meta/id :checkins)
:joins [join]}]}]
- (is (=? [{:id (meta/id :checkins :user-id)
- :name "USER_ID"
- :lib/source :source/joins
- :lib/source-column-alias "USER_ID"
- :lib/desired-column-alias "checkins_by_user__USER_ID"}
- {:name "count"
- :lib/source :source/joins
- :lib/source-column-alias "count"
- :lib/desired-column-alias "checkins_by_user__count"}]
- (lib/returned-columns query -1 join)))
+ (is (=? [{:id (meta/id :checkins :user-id)
+ :name "USER_ID"
+ :lib/source :source/joins
+ :lib/source-column-alias "USER_ID"
+ ::lib.join/join-alias "checkins_by_user"}
+ {:name "count"
+ :lib/source :source/joins
+ :lib/source-column-alias "count"
+ ::lib.join/join-alias "checkins_by_user"}]
+ (lib.join/join-returned-columns-relative-to-parent-stage query -1 join)))
(is (= (lib.metadata/card metadata-provider 1)
(lib.join/joined-thing query join)))))
@@ -721,15 +721,16 @@
(lib/with-join-alias "User")
lib/ref)]]
(testing (str "rhs = " (pr-str rhs))
- (is (=? [{:lib/desired-column-alias "ID"}
- {:lib/desired-column-alias "Cat__ID"}
- {:lib/desired-column-alias "CATEGORY_ID"}
- {:lib/desired-column-alias "NAME"}
- {:lib/desired-column-alias "LATITUDE"}
- {:lib/desired-column-alias "LONGITUDE"}
- {:lib/desired-column-alias "PRICE"}
- {:lib/desired-column-alias "Cat__NAME"}]
- (lib/join-condition-lhs-columns query nil nil rhs)))
+ (is (=? [[nil "ID"]
+ ["Cat" "ID"]
+ [nil "CATEGORY_ID"]
+ [nil "NAME"]
+ [nil "LATITUDE"]
+ [nil "LONGITUDE"]
+ [nil "PRICE"]
+ ["Cat" "NAME"]]
+ (map (juxt :metabase.lib.join/join-alias :lib/source-column-alias)
+ (lib/join-condition-lhs-columns query nil nil rhs))))
(is (= (lib/join-condition-lhs-columns query nil nil rhs)
(lib/join-condition-lhs-columns query -1 nil nil rhs))))))))
@@ -748,18 +749,22 @@
:alias "C3"}
join-3))
(are [join expected] (= expected
- (map :lib/desired-column-alias (lib/join-condition-lhs-columns query join nil nil)))
+ (map (fn [col]
+ (if-let [join-alias (::lib.join/join-alias col)]
+ [join-alias (:lib/source-column-alias col)]
+ (:lib/source-column-alias col)))
+ (lib/join-condition-lhs-columns query join nil nil)))
nil
- ["ID" "Cat__ID" "C2__ID" "C3__ID" "CATEGORY_ID" "NAME" "LATITUDE" "LONGITUDE" "PRICE" "Cat__NAME" "C2__NAME" "C3__NAME"]
+ ["ID" ["Cat" "ID"] ["C2" "ID"] ["C3" "ID"] "CATEGORY_ID" "NAME" "LATITUDE" "LONGITUDE" "PRICE" ["Cat" "NAME"] ["C2" "NAME"] ["C3" "NAME"]]
join-1
["ID" "CATEGORY_ID" "NAME" "LATITUDE" "LONGITUDE" "PRICE"]
join-2
- ["ID" "Cat__ID" "CATEGORY_ID" "NAME" "LATITUDE" "LONGITUDE" "PRICE" "Cat__NAME"]
+ ["ID" ["Cat" "ID"] "CATEGORY_ID" "NAME" "LATITUDE" "LONGITUDE" "PRICE" ["Cat" "NAME"]]
join-3
- ["ID" "Cat__ID" "C2__ID" "CATEGORY_ID" "NAME" "LATITUDE" "LONGITUDE" "PRICE" "Cat__NAME" "C2__NAME"]))))
+ ["ID" ["Cat" "ID"] ["C2" "ID"] "CATEGORY_ID" "NAME" "LATITUDE" "LONGITUDE" "PRICE" ["Cat" "NAME"] ["C2" "NAME"]]))))
(def ^:private join-for-query-with-join
(first (lib/joins (lib.tu/query-with-join))))
@@ -1729,9 +1734,9 @@
:fields [$title $category]}))
join (first (lib/joins query -1))]
(binding [lib.metadata.calculation/*display-name-style* :long]
- (is (= [["TITLE" "Orders__TITLE" "TITLE" "Orders → Title"]
- ["sum" "Orders__sum" "sum" "Orders → Sum of Quantity"]]
- (map (juxt :name :lib/desired-column-alias :lib/source-column-alias :display-name)
+ (is (= [["TITLE" "Orders" "TITLE" "Orders → Title"]
+ ["sum" "Orders" "sum" "Orders → Sum of Quantity"]]
+ (map (juxt :name :metabase.lib.join/join-alias :lib/source-column-alias :display-name)
(lib.join/join-fields-to-add-to-parent-stage
query -1 join {:include-remaps? true}))))))))
@@ -1776,9 +1781,9 @@
:fields [$title $category]}))
join (first (lib/joins query -1))]
(binding [lib.metadata.calculation/*display-name-style* :long]
- (is (= [["PRODUCT_ID" "Orders__PRODUCT_ID" "PRODUCT_ID" "Orders → Product ID"]
- ["TITLE" "Orders__TITLE" "TITLE" "Orders → Title"]]
- (map (juxt :name :lib/desired-column-alias :lib/source-column-alias :display-name)
+ (is (= [["PRODUCT_ID" "Orders" "PRODUCT_ID" "Orders → Product ID"]
+ ["TITLE" "Orders" "TITLE" "Orders → Title"]]
+ (map (juxt :name ::lib.join/join-alias :lib/source-column-alias :display-name)
(lib.join/join-fields-to-add-to-parent-stage
query -1 join {:include-remaps? true}))))))))
@@ -1867,22 +1872,18 @@
:condition [:= !month.created-at !month.&Q2.birth-date]
:fields fields}]}))]
;; these SHOULD NOT include `:metabase.lib.field/temporal-unit`, so don't change this to `=?`.
- (is (= [{:lib/source-column-alias "BIRTH_DATE"
- ::lib.join/join-alias "Q2"
- :lib/desired-column-alias "Q2__BIRTH_DATE"
- :lib/original-name "BIRTH_DATE"
- :inherited-temporal-unit :month}
- {:lib/source-column-alias "count"
- ::lib.join/join-alias "Q2"
- :lib/desired-column-alias "Q2__count"
- :lib/original-name "count"}]
- (map #(select-keys % [:lib/source-column-alias
- ::lib.join/join-alias
- :lib/desired-column-alias
- :lib/original-name
- :metabase.lib.field/temporal-unit
- :inherited-temporal-unit])
- (lib.join/join-fields-to-add-to-parent-stage query -1 (first (lib/joins query -1)) {})))))))))
+ (is (=? [{:lib/source :source/joins
+ :lib/source-column-alias "BIRTH_DATE"
+ ::lib.join/join-alias "Q2"
+ :lib/original-name "BIRTH_DATE"
+ :metabase.lib.field/temporal-unit (symbol "nil #_\"key is not present.\"")
+ :inherited-temporal-unit :month}
+ {:lib/source :source/joins
+ :lib/source-column-alias "count"
+ ::lib.join/join-alias "Q2"
+ :metabase.lib.field/temporal-unit (symbol "nil #_\"key is not present.\"")
+ :lib/original-name "count"}]
+ (lib.join/join-fields-to-add-to-parent-stage query -1 (first (lib/joins query -1)) {}))))))))
(deftest ^:parallel do-not-incorrectly-propagate-temporal-unit-in-returned-columns-test-2
(testing "DO propagate temporal unit if it is included in join :fields"
@@ -1900,9 +1901,10 @@
:condition [:= !month.created-at !month.&Q2.birth-date]
:fields [[:field (meta/id :people :birth-date) {:join-alias "Q2", :temporal-unit :month}]
[:field "count" {:base-type :type/Integer, :join-alias "Q2"}]]}]}))]
- (is (= [{:lib/desired-column-alias "Q2__BIRTH_DATE"
- :metabase.lib.field/temporal-unit :month
- :inherited-temporal-unit :year}
- {:lib/desired-column-alias "Q2__count"}]
- (map #(select-keys % [:lib/desired-column-alias :metabase.lib.field/temporal-unit :inherited-temporal-unit])
- (lib.join/join-fields-to-add-to-parent-stage query -1 (first (lib/joins query -1)) {})))))))
+ (is (=? [{::lib.join/join-alias "Q2"
+ :lib/source-column-alias "BIRTH_DATE"
+ :metabase.lib.field/temporal-unit :month
+ :inherited-temporal-unit :year}
+ {::lib.join/join-alias "Q2"
+ :lib/source-column-alias "count"}]
+ (lib.join/join-fields-to-add-to-parent-stage query -1 (first (lib/joins query -1)) {}))))))
diff --git a/test/metabase/lib/metadata/calculation_test.cljc b/test/metabase/lib/metadata/calculation_test.cljc
index 597024a2414..30f57f3fd4f 100644
--- a/test/metabase/lib/metadata/calculation_test.cljc
+++ b/test/metabase/lib/metadata/calculation_test.cljc
@@ -5,6 +5,7 @@
[medley.core :as m]
[metabase.lib.core :as lib]
[metabase.lib.field.util :as lib.field.util]
+ [metabase.lib.join :as lib.join]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.metadata.cache :as lib.metadata.cache]
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
@@ -12,6 +13,7 @@
[metabase.lib.test-util :as lib.tu]
[metabase.lib.test-util.macros :as lib.tu.macros]
[metabase.lib.util :as lib.util]
+ [metabase.lib.walk :as lib.walk]
[metabase.util :as u]
[metabase.util.malli :as mu]))
@@ -80,7 +82,7 @@
field-id (inc (apply max (map :id (lib/visible-columns query))))]
(mu/disable-enforcement
(is (=? {:name "Unknown Field"
- :display-name "join → Unknown Field" #_"Unknown Field" ; either answer can be considered correct I guess
+ :display-name "Unknown Field" #_"join → Unknown Field" ; either answer can be considered correct I guess
:long-display-name "join → Unknown Field"}
(lib/display-info query [:field {:join-alias "join"} field-id])))))))
@@ -221,25 +223,26 @@
(sort-by :position)))
(deftest ^:parallel self-join-visible-columns-test
- (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
- (lib/with-fields (for [field [:id :tax]]
- (lib/ref (meta/field-metadata :orders field))))
- (lib/join (-> (lib/join-clause (meta/table-metadata :orders)
- [(lib/= (meta/field-metadata :orders :id)
- (meta/field-metadata :orders :id))])
- (lib/with-join-fields (for [field [:id :tax]]
- (lib/ref (meta/field-metadata :orders field)))))))
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/with-fields (for [field [:id :tax]]
+ (lib/ref (meta/field-metadata :orders field))))
+ (lib/join (-> (lib/join-clause (meta/table-metadata :orders)
+ [(lib/= (meta/field-metadata :orders :id)
+ (meta/field-metadata :orders :id))])
+ (lib/with-join-fields (for [field [:id :tax]]
+ (lib/ref (meta/field-metadata :orders field)))))))
orders-cols (for [field-name ["ID" "USER_ID" "PRODUCT_ID" "SUBTOTAL" "TAX"
"TOTAL" "DISCOUNT" "CREATED_AT" "QUANTITY"]]
- {:name field-name
- :lib/desired-column-alias field-name
- :lib/source :source/table-defaults})
+ {:name field-name
+ :lib/source-column-alias field-name
+ :lib/source :source/table-defaults})
joined-cols (for [field-key [:id :user-id :product-id :subtotal :tax
:total :discount :created-at :quantity]
- :let [field (meta/field-metadata :orders field-key)]]
- {:name (:name field)
- :lib/desired-column-alias (str "Orders__" (:name field))
- :lib/source :source/joins})]
+ :let [field (meta/field-metadata :orders field-key)]]
+ {:name (:name field)
+ :metabase.lib.join/join-alias "Orders"
+ :lib/source-column-alias (:name field)
+ :lib/source :source/joins})]
(testing "just own columns"
(is (=? (concat orders-cols joined-cols)
(lib/visible-columns query -1 (lib.util/query-stage query -1) {:include-implicitly-joinable? false}))))
@@ -916,3 +919,139 @@
"Q2__BIRTH_DATE"
"Q2__count"]
(mapv :lib/desired-column-alias cols))))))
+
+(deftest ^:parallel return-correct-metadata-for-broken-field-refs-test
+ (testing (str "lib/returned-columns and lib/visible-columns should not include join alias for metadatas derived from"
+ " bad refs when join does not exist in the current stage of the query (QUE-1496)")
+ (let [query (lib/query
+ meta/metadata-provider
+ (lib.tu.macros/mbql-5-query venues
+ {:stages [{:source-table $$venues
+ :joins [{:strategy :left-join
+ :stages [{:source-table $$categories}]
+ :alias "Cat"
+ :conditions [[:= {} $category-id &Cat.categories.id]]
+ :fields [&Cat.categories.name]}]
+ :fields [$id
+ &Cat.categories.name]}
+ {;; THIS REF IS WRONG -- it should not be using `Cat` because the join is in the source
+ ;; query rather than in the current stage. However, we should be smart enough to try to
+ ;; figure out what they meant.
+ :breakout [&Cat.categories.name]}]}))]
+ (testing `lib/returned-columns
+ (testing "stage 1 of 2"
+ (is (=? [{:id (meta/id :venues :id)
+ :table-id (meta/id :venues)
+ :name "ID"
+ :lib/source :source/table-defaults
+ :lib/original-join-alias (symbol "nil #_\"key is not present.\"")
+ :metabase.lib.join/join-alias (symbol "nil #_\"key is not present.\"")
+ :lib/source-column-alias "ID"
+ :lib/desired-column-alias "ID"}
+ {:id (meta/id :categories :name)
+ :table-id (meta/id :categories)
+ :name "NAME"
+ :lib/source :source/joins
+ :metabase.lib.join/join-alias "Cat"
+ :lib/source-column-alias "NAME"
+ :lib/desired-column-alias "Cat__NAME"}]
+ (lib/returned-columns query 0 (lib/query-stage query 0)))))
+ (testing "stage 2 of 2"
+ (is (=? [{:id (meta/id :categories :name)
+ :table-id (meta/id :categories)
+ :name "NAME"
+ :lib/source :source/previous-stage
+ :lib/breakout? true
+ :lib/original-join-alias "Cat"
+ :metabase.lib.join/join-alias (symbol "nil #_\"key is not present.\"")
+ :lib/source-column-alias "Cat__NAME"
+ :lib/desired-column-alias "Cat__NAME"}]
+ (lib/returned-columns query)))))
+ (testing `lib/visible-columns
+ (is (=? [{:id (meta/id :venues :id)
+ :table-id (meta/id :venues)
+ :name "ID"
+ :lib/source :source/previous-stage
+ :lib/original-join-alias (symbol "nil #_\"key is not present.\"")
+ :metabase.lib.join/join-alias (symbol "nil #_\"key is not present.\"")
+ :lib/source-column-alias "ID"}
+ {:id (meta/id :categories :name)
+ :table-id (meta/id :categories)
+ :name "NAME"
+ :lib/source :source/previous-stage
+ :lib/original-join-alias "Cat"
+ :metabase.lib.join/join-alias (symbol "nil #_\"key is not present.\"")
+ :lib/source-column-alias "Cat__NAME"
+ ;; should not be returned by `visible-columns` since it needs to be recalculated in the context of
+ ;; everything that gets returned.
+ :lib/desired-column-alias (symbol "nil #_\"key is not present.\"")}]
+ (lib/visible-columns query -1 (lib/query-stage query -1) {:include-joined? false
+ :include-expressions? false
+ :include-implicitly-joinable? false
+ :include-implicitly-joinable-for-source-card? false})))))))
+
+(deftest ^:parallel join-source-query-join-test
+ (testing "lib/returned-columns calculates incorrect :source-column-aliases for columns coming from nested joins (QUE-1373)"
+ (let [query (lib/query
+ meta/metadata-provider
+ (lib.tu.macros/mbql-5-query orders
+ {:stages [{:joins [{:alias "Q2"
+ :stages [{:source-table $$reviews
+ :aggregation [[:avg {:name "avg"} $reviews.rating]]
+ :breakout [&P2.products.category]
+ :joins [{:alias "P2"
+ :strategy :left-join
+ :stages [{:source-table $$products}]
+ :conditions [[:= {}
+ $reviews.product-id
+ &P2.products.id]]}]}]
+ :strategy :left-join
+ :condition [:= {} &Q2.products.category 1]}]
+ ;; busted field ref, should probably be something like
+ ;;
+ ;; [:field {:join-alias "Q2", :base-type :type/Integer} "P2__CATEGORY"]
+ ;;
+ ;; but we should still be able to resolve it correctly.
+ :fields [[:field {:join-alias "Q2"} (meta/id :products :category)]
+ [:field {:base-type :type/Integer, :join-alias "Q2"} "avg"]]}]}))
+ relevant-keys (fn [cols]
+ (map #(select-keys % [:name
+ :lib/source
+ :metabase.lib.join/join-alias
+ :lib/source-column-alias
+ :lib/desired-column-alias])
+ cols))]
+ (testing "join last stage returned columns == join returned columns"
+ (is (= [{:name "CATEGORY"
+ :lib/source :source/joins
+ :lib/desired-column-alias "P2__CATEGORY"
+ :lib/source-column-alias "CATEGORY"
+ :metabase.lib.join/join-alias "P2"}
+ {:name "avg"
+ :lib/source :source/aggregations
+ :lib/desired-column-alias "avg"
+ :lib/source-column-alias "avg"}]
+ (relevant-keys (lib.walk/apply-f-for-stage-at-path lib/returned-columns query [:stages 0 :joins 0 :stages 0]))
+ (relevant-keys (lib/returned-columns query (first (lib/joins query)))))))
+ (testing "join returned columns relative to parent stage"
+ (is (= [{:name "CATEGORY"
+ :lib/source :source/joins
+ :metabase.lib.join/join-alias "Q2"
+ :lib/source-column-alias "P2__CATEGORY"}
+ {:name "avg"
+ :lib/source :source/joins
+ :metabase.lib.join/join-alias "Q2"
+ :lib/source-column-alias "avg"}]
+ (relevant-keys (#'lib.join/join-returned-columns-relative-to-parent-stage query -1 (first (lib/joins query)))))))
+ (testing "query (last stage) returned columns"
+ (is (= [{:name "CATEGORY"
+ :lib/source :source/joins
+ :metabase.lib.join/join-alias "Q2"
+ :lib/source-column-alias "P2__CATEGORY"
+ :lib/desired-column-alias "Q2__P2__CATEGORY"}
+ {:name "avg"
+ :lib/source :source/joins
+ :metabase.lib.join/join-alias "Q2"
+ :lib/source-column-alias "avg"
+ :lib/desired-column-alias "Q2__avg"}]
+ (relevant-keys (lib/returned-columns query))))))))
diff --git a/test/metabase/lib/order_by_test.cljc b/test/metabase/lib/order_by_test.cljc
index f1d475eaafe..d0ada2160e4 100644
--- a/test/metabase/lib/order_by_test.cljc
+++ b/test/metabase/lib/order_by_test.cljc
@@ -477,38 +477,32 @@
(lib/display-name query' order-by))))))))))
(deftest ^:parallel orderable-columns-with-join-test
- (is (=? [{:name "ID"
- :lib/source-column-alias "ID"
- :lib/desired-column-alias "ID"
- :lib/source :source/table-defaults}
- {:name "NAME"
- :lib/source-column-alias "NAME"
- :lib/desired-column-alias "NAME"
- :lib/source :source/table-defaults}
- {:name "CATEGORY_ID"
- :lib/source-column-alias "CATEGORY_ID"
- :lib/desired-column-alias "CATEGORY_ID"
- :lib/source :source/table-defaults}
- {:name "LATITUDE"
- :lib/source-column-alias "LATITUDE"
- :lib/desired-column-alias "LATITUDE"
- :lib/source :source/table-defaults}
- {:name "LONGITUDE"
- :lib/source-column-alias "LONGITUDE"
- :lib/desired-column-alias "LONGITUDE"
- :lib/source :source/table-defaults}
- {:name "PRICE"
- :lib/source-column-alias "PRICE"
- :lib/desired-column-alias "PRICE"
- :lib/source :source/table-defaults}
- {:name "ID"
- :lib/source-column-alias "ID"
- :lib/desired-column-alias "Cat__ID"
- :lib/source :source/joins}
- {:name "NAME"
- :lib/source-column-alias "NAME"
- :lib/desired-column-alias "Cat__NAME"
- :lib/source :source/joins}]
+ (is (=? [{:name "ID"
+ :lib/source-column-alias "ID"
+ :lib/source :source/table-defaults}
+ {:name "NAME"
+ :lib/source-column-alias "NAME"
+ :lib/source :source/table-defaults}
+ {:name "CATEGORY_ID"
+ :lib/source-column-alias "CATEGORY_ID"
+ :lib/source :source/table-defaults}
+ {:name "LATITUDE"
+ :lib/source-column-alias "LATITUDE"
+ :lib/source :source/table-defaults}
+ {:name "LONGITUDE"
+ :lib/source-column-alias "LONGITUDE"
+ :lib/source :source/table-defaults}
+ {:name "PRICE"
+ :lib/source-column-alias "PRICE"
+ :lib/source :source/table-defaults}
+ {:name "ID"
+ :lib/source-column-alias "ID"
+ :metabase.lib.join/join-alias "Cat"
+ :lib/source :source/joins}
+ {:name "NAME"
+ :lib/source-column-alias "NAME"
+ :metabase.lib.join/join-alias "Cat"
+ :lib/source :source/joins}]
(-> (lib.tu/venues-query)
(lib/join (-> (lib/join-clause
(meta/table-metadata :categories)
@@ -523,36 +517,33 @@
(deftest ^:parallel order-bys-with-duplicate-column-names-test
(testing "Order by stuff should work with two different columns named ID (#29702)"
- (is (=? [{:id (meta/id :venues :id)
- :name "ID"
- :lib/source :source/previous-stage
- :lib/type :metadata/column
- :base-type :type/BigInteger
- :effective-type :type/BigInteger
- :display-name "ID"
- :table-id (meta/id :venues)
- :lib/source-column-alias "ID"
- :lib/desired-column-alias "ID"}
- {:id (meta/id :categories :id)
- :name "ID"
- :lib/source :source/previous-stage
- :lib/type :metadata/column
- :base-type :type/BigInteger
- :effective-type :type/BigInteger
- :display-name "ID"
- :table-id (meta/id :categories)
- :lib/source-column-alias "Cat__ID"
- :lib/desired-column-alias "Cat__ID"}
- {:id (meta/id :categories :name)
- :name "NAME"
- :lib/source :source/previous-stage
- :lib/type :metadata/column
- :base-type :type/Text
- :effective-type :type/Text
- :display-name "Name"
- :table-id (meta/id :categories)
- :lib/source-column-alias "Cat__NAME"
- :lib/desired-column-alias "Cat__NAME"}]
+ (is (=? [{:id (meta/id :venues :id)
+ :name "ID"
+ :lib/source :source/previous-stage
+ :lib/type :metadata/column
+ :base-type :type/BigInteger
+ :effective-type :type/BigInteger
+ :display-name "ID"
+ :table-id (meta/id :venues)
+ :lib/source-column-alias "ID"}
+ {:id (meta/id :categories :id)
+ :name "ID"
+ :lib/source :source/previous-stage
+ :lib/type :metadata/column
+ :base-type :type/BigInteger
+ :effective-type :type/BigInteger
+ :display-name "ID"
+ :table-id (meta/id :categories)
+ :lib/source-column-alias "Cat__ID"}
+ {:id (meta/id :categories :name)
+ :name "NAME"
+ :lib/source :source/previous-stage
+ :lib/type :metadata/column
+ :base-type :type/Text
+ :effective-type :type/Text
+ :display-name "Name"
+ :table-id (meta/id :categories)
+ :lib/source-column-alias "Cat__NAME"}]
(-> (lib.tu/venues-query)
(lib/join (-> (lib/join-clause
(meta/table-metadata :categories)
@@ -718,15 +709,15 @@
(deftest ^:parallel orderable-columns-include-all-visible-columns-test
(testing "Include all visible columns, not just projected ones (#31233)"
- (is (= ["ID"
- "NAME"
- "CATEGORY_ID"
- "LATITUDE"
- "LONGITUDE"
- "PRICE"
- "Categories__ID" ; this column is not projected, but should still be returned.
- "Categories__NAME"]
- (map :lib/desired-column-alias
+ (is (= [[nil "ID"]
+ [nil "NAME"]
+ [nil "CATEGORY_ID"]
+ [nil "LATITUDE"]
+ [nil "LONGITUDE"]
+ [nil "PRICE"]
+ ["Categories" "ID"] ; this column is not projected, but should still be returned.
+ ["Categories" "NAME"]]
+ (map (juxt :metabase.lib.join/join-alias :lib/source-column-alias)
(-> (lib.tu/venues-query)
(lib/join (-> (lib/join-clause
(meta/table-metadata :categories)
diff --git a/test/metabase/lib/remove_replace_test.cljc b/test/metabase/lib/remove_replace_test.cljc
index 4dfd40271a8..12b5bcf3e3b 100644
--- a/test/metabase/lib/remove_replace_test.cljc
+++ b/test/metabase/lib/remove_replace_test.cljc
@@ -261,7 +261,10 @@
(defn- by-desired-alias
[columns desired-alias]
- (m/find-first (comp #{desired-alias} :lib/desired-column-alias) columns))
+ (let [columns (into []
+ (lib.field.util/add-source-and-desired-aliases-xform meta/metadata-provider)
+ columns)]
+ (m/find-first (comp #{desired-alias} :lib/desired-column-alias) columns)))
(deftest ^:parallel remove-clause-aggregation-with-ref-test
(testing "removing an aggregation removes references in order-by (#12625)"
@@ -288,7 +291,11 @@
lib/append-stage)
[a0-column a1-column] (-> query
lib/visible-columns
- (->> (filter #(= "sum" (:name %)))))
+ (->> (filter #(= (:name %) "sum"))))
+ _ (is (=? {:name "sum", :lib/source-column-alias "sum"}
+ a0-column))
+ _ (is (=? {:name "sum", :lib/source-column-alias "sum_2"}
+ a1-column))
query (-> query
(lib/expression "xix" (lib/ref a0-column))
(lib/expression "yiy" (lib/ref a1-column)))
@@ -1287,20 +1294,26 @@
(are [query-fn] (let [q (query-fn)] (= q (lib.remove-replace/normalize-fields-clauses q)))
lib.tu/query-with-join
lib.tu/query-with-self-join
- lib.tu/venues-query))
+ lib.tu/venues-query)))
+
+(deftest ^:parallel normalize-fields-clauses-test-2
(testing "a :fields clause with extras is retained"
(let [base (lib/query meta/metadata-provider (meta/table-metadata :orders))
viz (lib/visible-columns base)
category (m/find-first #(= (:name %) "CATEGORY") viz)
query (lib/add-field base 0 category)]
(is (= base (lib.remove-replace/normalize-fields-clauses base)))
- (is (= query (lib.remove-replace/normalize-fields-clauses query)))))
+ (is (= query (lib.remove-replace/normalize-fields-clauses query))))))
+
+(deftest ^:parallel normalize-fields-clauses-test-3
(testing "a :fields clause with a default field removed is retained"
(let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
(lib/remove-field 0 (assoc (meta/field-metadata :orders :tax)
:lib/source :source/table-defaults)))]
(is (= 8 (-> query :stages first :fields count)))
- (is (= query (lib.remove-replace/normalize-fields-clauses query)))))
+ (is (= query (lib.remove-replace/normalize-fields-clauses query))))))
+
+(deftest ^:parallel normalize-fields-clauses-test-4a
(testing "if :fields clause matches the defaults it is dropped"
(testing "removing then restoring a field"
(let [tax (assoc (meta/field-metadata :orders :tax)
@@ -1315,10 +1328,14 @@
lib.remove-replace/normalize-fields-clauses
:stages
first
- :fields)))))
+ :fields)))))))
+
+(deftest ^:parallel normalize-fields-clauses-test-4b
+ (testing "if :fields clause matches the defaults it is dropped"
(testing "adding and dropping and implicit join field"
(let [category (assoc (meta/field-metadata :products :category)
- :lib/source :source/implicitly-joinable)
+ :lib/source :source/implicitly-joinable
+ :fk-field-id 1337) ; just make something up
query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
(lib/add-field 0 category)
;; Can't use remove-field itself; it will normalize the fields clause.
@@ -1328,7 +1345,9 @@
lib.remove-replace/normalize-fields-clauses
:stages
first
- :fields))))))
+ :fields)))))))
+
+(deftest ^:parallel normalize-fields-clauses-test-5a
(testing ":fields clauses on joins"
(testing "are preserved if :none or :all"
(let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
@@ -1338,7 +1357,10 @@
none (assoc-in query [:stages 0 :joins 0 :fields] :none)]
(is (= :all (-> query :stages first :joins first :fields)))
(is (= query (lib.remove-replace/normalize-fields-clauses query)))
- (is (= none (lib.remove-replace/normalize-fields-clauses none)))))
+ (is (= none (lib.remove-replace/normalize-fields-clauses none)))))))
+
+(deftest ^:parallel normalize-fields-clauses-test-5b
+ (testing ":fields clauses on joins"
(testing "are preserved if they do not match the defaults"
(let [join (-> (lib/join-clause (meta/table-metadata :products)
[(lib/= (meta/field-metadata :orders :product-id)
@@ -1348,7 +1370,10 @@
query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
(lib/join join))]
(is (= 4 (-> query :stages first :joins first :fields count)))
- (is (= query (lib.remove-replace/normalize-fields-clauses query)))))
+ (is (= query (lib.remove-replace/normalize-fields-clauses query)))))))
+
+(deftest ^:parallel normalize-fields-clauses-test-5c
+ (testing ":fields clauses on joins"
(testing "are replaced with :all if they include all the defaults"
(let [join (-> (lib/join-clause (meta/table-metadata :products)
[(lib/= (meta/field-metadata :orders :product-id)
diff --git a/test/metabase/lib/schema/join_test.cljc b/test/metabase/lib/schema/join_test.cljc
index 469520bdfcb..b191cabef6d 100644
--- a/test/metabase/lib/schema/join_test.cljc
+++ b/test/metabase/lib/schema/join_test.cljc
@@ -1,7 +1,7 @@
(ns metabase.lib.schema.join-test
(:require
#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
- [clojure.test :refer [deftest is]]
+ [clojure.test :refer [deftest is testing]]
[malli.error :as me]
[metabase.lib.core :as lib]
[metabase.lib.schema :as lib.schema]
@@ -60,3 +60,19 @@
{:name "NAME", :base_type :type/Name, :display_name "Name"}]
:alias "Question 54"
:condition [:= 1 1]}]})))))
+
+(deftest ^:parallel normalize-join-condition->conditions-test
+ (testing "normalize should fix condition => conditions and normalize things inside it"
+ (is (=? {:strategy :left-join
+ :stages [{:source-table 1}]
+ :alias "Cat"
+ :conditions [[:= {} [:field {} 2] [:field {:join-alias "Cat"} 3]]]
+ :conditon (symbol "nil #_\"key is not present.\"")
+ :fields [[:field {} 4]]}
+ (lib/normalize
+ ::lib.schema.join/join
+ {:strategy :left-join
+ :stages [{:source-table 1}]
+ :alias "Cat"
+ :condition [:= [:field {} 2] [:field {:join-alias "Cat"} 3]]
+ :fields [[:field {} 4]]})))))
diff --git a/test/metabase/lib/schema_test.cljc b/test/metabase/lib/schema_test.cljc
index 791f797f17e..f946c6a839a 100644
--- a/test/metabase/lib/schema_test.cljc
+++ b/test/metabase/lib/schema_test.cljc
@@ -301,3 +301,41 @@
;; ok because it has a different temporal unit
[:field {:lib/uuid "00000000-0000-0000-0000-000000000003", :base-type :type/Integer, :temporal-unit :month} 101]]
(lib/normalize schema fields)))))))
+
+(deftest ^:parallel normalize-stage-infer-type-test
+ (are [stage expected] (= expected
+ (lib/normalize ::lib.schema/stage stage))
+ {:source-table 10}
+ {:lib/type :mbql.stage/mbql, :source-table 10}
+
+ {:source-card 10}
+ {:lib/type :mbql.stage/mbql, :source-card 10}
+
+ {:native "SELECT *"}
+ {:lib/type :mbql.stage/native, :native "SELECT *"}
+
+ ;; if we can't infer the type, return the stage as-is
+ {:breakout [[:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} 1]]}
+ {:breakout [[:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} 1]]}))
+
+(deftest ^:parallel normalize-stages-add-subsequent-stage-types-test
+ (are [stages expected] (= expected
+ (lib/normalize ::lib.schema/stages stages))
+ ;; add `:lib/type` to subsequent stages automatically
+ [{:source-table 1} {}]
+ [{:lib/type :mbql.stage/mbql, :source-table 1}
+ {:lib/type :mbql.stage/mbql}]
+
+ [{:source-table 1}
+ {:breakout [[:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} 1]]}]
+ [{:lib/type :mbql.stage/mbql, :source-table 1}
+ {:lib/type :mbql.stage/mbql, :breakout [[:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} 1]]}]
+
+ ;; don't stomp on existing `:lib/type` even if it's wrong
+ [{:source-table 1} {:lib/type :mbql.stage/native}]
+ [{:lib/type :mbql.stage/mbql, :source-table 1}
+ {:lib/type :mbql.stage/native}]
+
+ [{:source-table 1} {"lib/type" :mbql.stage/native}]
+ [{:lib/type :mbql.stage/mbql, :source-table 1}
+ {:lib/type :mbql.stage/native}]))
diff --git a/test/metabase/lib/stage_test.cljc b/test/metabase/lib/stage_test.cljc
index 38ebc0458fa..e660120cbde 100644
--- a/test/metabase/lib/stage_test.cljc
+++ b/test/metabase/lib/stage_test.cljc
@@ -260,28 +260,28 @@
:name "ID"
:lib/source :source/previous-stage
:effective-type :type/BigInteger
- :lib/desired-column-alias "ID"
+ :lib/source-column-alias "ID"
:display-name "ID"}
{:base-type :type/Text
:semantic-type :type/Name
:name "NAME"
:lib/source :source/previous-stage
:effective-type :type/Text
- :lib/desired-column-alias "NAME"
+ :lib/source-column-alias "NAME"
:display-name "Name"}
{:base-type :type/BigInteger
:semantic-type :type/PK
:name "ID"
:lib/source :source/previous-stage
:effective-type :type/BigInteger
- :lib/desired-column-alias "Cat__ID"
+ :lib/source-column-alias "Cat__ID"
:display-name "ID"}
{:base-type :type/Text
:semantic-type :type/Name
:name "NAME"
:lib/source :source/previous-stage
:effective-type :type/Text
- :lib/desired-column-alias "Cat__NAME"
+ :lib/source-column-alias "Cat__NAME"
:display-name "Name"}]
(lib/visible-columns query)))))
@@ -805,7 +805,7 @@
(deftest ^:parallel return-correct-deduplicated-names-test
(testing "Deduplicated names from previous stage should be preserved even when excluding certain fields"
- ;; e.g. a field called CREATED_AT_2 in the previous stage should continue to be called that. See ;; see
+ ;; e.g. a field called CREATED_AT_2 in the previous stage should continue to be called that. See
;; https://metaboat.slack.com/archives/C0645JP1W81/p1750961267171999
(let [query (-> (lib/query
meta/metadata-provider
@@ -820,19 +820,60 @@
lib/append-stage
lib/append-stage
(as-> query (lib/remove-field query -1 (first (lib/fieldable-columns query -1)))))]
- (is (=? [{:name "CREATED_AT_2"
- :lib/original-name "CREATED_AT"
- :lib/deduplicated-name "CREATED_AT_2"
- :lib/source-column-alias "CREATED_AT_2"
- :lib/desired-column-alias "CREATED_AT_2"
- :display-name "Created At: Month"}
- {:name "count"
- :lib/original-name "count"
- :lib/deduplicated-name "count"
- :lib/source-column-alias "count"
- :lib/desired-column-alias "count"
- :display-name "Count"}]
- (lib/returned-columns query))))))
+ (testing "Stage 1 of 3"
+ (is (=? [{:name "CREATED_AT"
+ :lib/original-name "CREATED_AT"
+ :lib/deduplicated-name "CREATED_AT"
+ :lib/source-column-alias "CREATED_AT"
+ :lib/desired-column-alias "CREATED_AT"
+ :display-name "Created At: Year"}
+ {:name "CREATED_AT"
+ :lib/original-name "CREATED_AT"
+ :lib/deduplicated-name "CREATED_AT_2"
+ :lib/source-column-alias "CREATED_AT"
+ :lib/desired-column-alias "CREATED_AT_2"
+ :display-name "Created At: Month"}
+ {:name "count"
+ :lib/original-name "count"
+ :lib/deduplicated-name "count"
+ :lib/source-column-alias "count"
+ :lib/desired-column-alias "count"
+ :display-name "Count"}]
+ (lib/returned-columns query 0))))
+ (testing "Stage 2 of 3"
+ (is (=? [{:name "CREATED_AT"
+ :lib/original-name "CREATED_AT"
+ :lib/deduplicated-name "CREATED_AT"
+ :lib/source-column-alias "CREATED_AT"
+ :lib/desired-column-alias "CREATED_AT"
+ :display-name "Created At: Year"}
+ {:name "CREATED_AT"
+ :lib/original-name "CREATED_AT"
+ :lib/deduplicated-name "CREATED_AT_2"
+ :lib/source-column-alias "CREATED_AT_2"
+ :lib/desired-column-alias "CREATED_AT_2"
+ :display-name "Created At: Month"}
+ {:name "count"
+ :lib/original-name "count"
+ :lib/deduplicated-name "count"
+ :lib/source-column-alias "count"
+ :lib/desired-column-alias "count"
+ :display-name "Count"}]
+ (lib/returned-columns query 1))))
+ (testing "Stage 3 of 3"
+ (is (=? [{:name "CREATED_AT_2" ; name should get deduplicated in the last stage for historical reasons
+ :lib/original-name "CREATED_AT"
+ :lib/deduplicated-name "CREATED_AT_2"
+ :lib/source-column-alias "CREATED_AT_2"
+ :lib/desired-column-alias "CREATED_AT_2"
+ :display-name "Created At: Month"}
+ {:name "count"
+ :lib/original-name "count"
+ :lib/deduplicated-name "count"
+ :lib/source-column-alias "count"
+ :lib/desired-column-alias "count"
+ :display-name "Count"}]
+ (lib/returned-columns query)))))))
(deftest ^:parallel test-QUE-1607
(testing "QUE-1607"
@@ -862,6 +903,50 @@
:metabase.lib.join/join-alias "Orders"
:name "sum"}))))
+(deftest ^:parallel add-cols-from-join-duplicate?-test
+ (let [join-col {:active true
+ :base-type :type/Text
+ :caveats nil
+ :coercion-strategy nil
+ :custom-position 0
+ :database-is-auto-increment false
+ :database-position 2
+ :database-required false
+ :database-type "CHARACTER VARYING"
+ :description nil
+ :display-name "Orders → Title"
+ :effective-type :type/Text,
+ :fingerprint-version 5
+ :fk-target-field-id nil
+ :has-field-values :auto-list
+ :id 24504
+ :name "TITLE"
+ :nfc-path nil
+ :parent-id nil
+ :points-of-interest nil
+ :position 2
+ :preview-display true
+ :semantic-type :type/Title
+ :settings nil
+ :source-alias "Orders"
+ :table-id 24050
+ :visibility-type :normal
+ :lib/breakout? false
+ :lib/original-display-name "Title"
+ :lib/original-join-alias "Orders"
+ :lib/original-name "TITLE"
+ :lib/source :source/joins
+ :lib/source-column-alias "TITLE"
+ :lib/type :metadata/column
+ :metabase.lib.join/join-alias "Orders"}
+ existing-col {:base-type :type/Integer
+ :display-name "Orders → Sum"
+ :name "sum"
+ :lib/source :source/previous-stage
+ :lib/type :metadata/column
+ :metabase.lib.join/join-alias "Orders"}]
+ (is (not (#'lib.stage/add-cols-from-join-duplicate? join-col existing-col)))))
+
(deftest ^:parallel sane-desired-column-aliases-test
(testing "Do not 'double-dip' a desired-column alias and do `__via__` twice"
(let [query (lib/query
diff --git a/test/metabase/lib/swap_test.cljc b/test/metabase/lib/swap_test.cljc
index c317b385416..2af1d731c7a 100644
--- a/test/metabase/lib/swap_test.cljc
+++ b/test/metabase/lib/swap_test.cljc
@@ -156,15 +156,15 @@
(is (=? (map :lib/source-uuid cols-before)
(map :lib/source-uuid cols-after)))
(testing "even though the names have changed where they were swapped"
- (let [dcas-before (mapv :lib/desired-column-alias cols-before)
- dcas-after (mapv :lib/desired-column-alias cols-after)]
- (is (not= (nth dcas-before i1)
- (nth dcas-after i1)))
- (is (not= (nth dcas-before i2)
- (nth dcas-after i2)))
+ (let [aliases-before (mapv (juxt :metabase.lib.join/join-alias :lib/source-column-alias) cols-before)
+ aliases-after (mapv (juxt :metabase.lib.join/join-alias :lib/source-column-alias) cols-after)]
+ (is (not= (nth aliases-before i1)
+ (nth aliases-after i1)))
+ (is (not= (nth aliases-before i2)
+ (nth aliases-after i2)))
(for [i-unchanged (remove #{i1 i2} (range (count aggs-by-id)))]
- (is (= (nth dcas-before i-unchanged)
- (nth dcas-after i-unchanged))))))))))))
+ (is (= (nth aliases-before i-unchanged)
+ (nth aliases-after i-unchanged))))))))))))
(deftest ^:parallel swap-clauses-breakouts-on-same-column-test
(testing "swapping two breakouts of the same column with different time granularity maintains downstream refs"
@@ -180,12 +180,10 @@
after (lib/swap-clauses before 0 brk1 brk2)
cols-after (lib/visible-columns after)
days-after (-> (assoc days
- :lib/source-column-alias "CREATED_AT"
- :lib/desired-column-alias "CREATED_AT")
+ :lib/source-column-alias "CREATED_AT")
(dissoc :lib/deduplicated-name))
months-after (-> (assoc months
- :lib/source-column-alias "CREATED_AT_2"
- :lib/desired-column-alias "CREATED_AT_2")
+ :lib/source-column-alias "CREATED_AT_2")
(dissoc :lib/deduplicated-name))]
(testing "\nthe columns have swapped places and their names have changed"
(is (=? [days-after months-after {:name "days-ago"}]
diff --git a/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.clj b/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.clj
index 2e6c9ea27f4..126aabcb01e 100644
--- a/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.clj
+++ b/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.clj
@@ -78,8 +78,9 @@
(defn- summary-query []
(mt/mbql-query orders
{:source-table "card__4"
- :aggregation [[:sum [:field "TOTAL" {:base-type :type/Float}]]]
- :breakout [[:field "RATING" {:base-type :type/Float}]]}))
+ :aggregation [[:sum [:field "TOTAL" {:base-type :type/Float}]]]
+ :breakout [[:field "RATING" {:base-type :type/Float}]]
+ :limit 1}))
(defn- join-query []
(mt/mbql-query orders
@@ -98,7 +99,8 @@
[:field "TAX" {:join-alias "Card"
:base-type :type/Float}]
[:field "VENDOR" {:join-alias "Card"
- :base-type :type/Text}]]}]}))
+ :base-type :type/Text}]]}]
+ :limit 1}))
(deftest ^:parallel deleted-columns-before-test
(qp.store/with-metadata-provider @metadata-provider
diff --git a/test/metabase/query_processor/pivot_test.clj b/test/metabase/query_processor/pivot_test.clj
index fa867654b83..cf19a578143 100644
--- a/test/metabase/query_processor/pivot_test.clj
+++ b/test/metabase/query_processor/pivot_test.clj
@@ -10,11 +10,13 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.query-processor :as qp]
[metabase.query-processor.pivot :as qp.pivot]
[metabase.query-processor.pivot.test-util :as qp.pivot.test-util]
+ [metabase.query-processor.store :as qp.store]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
@@ -338,26 +340,30 @@
(assoc :info {:visualization-settings viz-settings})
qp.pivot/run-pivot-query))))))))))
-(deftest nested-models-with-expressions-pivot-breakout-names-test
+(deftest ^:parallel nested-models-with-expressions-pivot-breakout-names-test
(testing "#43993 again - breakouts on an expression from the inner model should pass"
- (mt/with-temp [:model/Card model1 {:type :model
- :dataset_query
- (mt/mbql-query products
- {:source-table $$products
- :expressions {"Rating Bucket" [:floor $products.rating]}})}
- :model/Card model2 {:type :model
- :dataset_query
- (mt/mbql-query orders
- {:source-table $$orders
- :joins [{:source-table (str "card__" (u/the-id model1))
- :alias "model A - Product"
- :fields :all
- :condition [:= $orders.product_id
- [:field %products.id
- {:join-alias "model A - Product"}]]}]})}]
+ (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider
+ (mt/application-database-metadata-provider (mt/id))
+ {:cards [{:id 1
+ :type :model
+ :name "Model A"
+ :dataset-query (mt/mbql-query products
+ {:source-table $$products
+ :expressions {"Rating Bucket" [:floor $products.rating]}})}
+ {:id 2
+ :type :model
+ :dataset-query (mt/mbql-query orders
+ {:source-table $$orders
+ :joins [{:source-table "card__1"
+ :alias "model A - Product"
+ :fields :all
+ :condition [:=
+ $orders.product_id
+ [:field %products.id
+ {:join-alias "model A - Product"}]]}]})}]})
(testing "Column aliasing works when joining an expression in an inner model"
(let [query (mt/mbql-query
- orders {:source-table (str "card__" (u/the-id model2))
+ orders {:source-table "card__2"
:aggregation [[:sum [:field "SUBTOTAL" {:base-type :type/Number}]]]
:breakout [[:field "Rating Bucket" {:base-type :type/Number
:join-alias "model A - Product"}]]})
diff --git a/test/metabase/query_processor/preprocess_test.clj b/test/metabase/query_processor/preprocess_test.clj
index 6e6f2c94939..5e240703d63 100644
--- a/test/metabase/query_processor/preprocess_test.clj
+++ b/test/metabase/query_processor/preprocess_test.clj
@@ -314,9 +314,11 @@
{:aggregation [[:count]]
:breakout [[:field %products.created-at {:source-field %product-id, :temporal-unit :month}]
[:field %products.category {:source-field %product-id}]]}))]
+ ;; actually, ok just to not return `:source-alias`, which is used for mysterious FE legacy historical purposes. We
+ ;; can go ahead and return various Lib keys for Lib purposes.
(doseq [col (qp.preprocess/query->expected-cols query)]
(testing (pr-str (:name col))
- (is (empty? (m/filter-vals #(= % "PRODUCTS__via__PRODUCT_ID") col)))))
+ (is (not (contains? col :source-alias)))))
(testing "result metadata should still contain fk_field_id"
(is (=? [{:fk_field_id (meta/id :orders :product-id)}
{:fk_field_id (meta/id :orders :product-id)}
@@ -599,17 +601,20 @@
(meta/id :products :category)
{:source-field (meta/id :orders :product-id)}]]}})]
(testing "one stage"
- (is (=? [{:name "CATEGORY"
- :display_name "Product → Category"
- ;; technically this should probably be `:source/implicitly-joinable` but we reify the join during
- ;; preprocessing so it comes from joins now I guess. Probably fine. Note that join alias doesn't come
- ;; back in this case because [[metabase.lib.metadata.result-metadata/remove-implicit-join-aliases]]
- ;; strips it out. We should probably leave it in, but we were doing it for some sort of reason.
- :lib/source :source/joins
- :lib/breakout? true
- :lib/source-column-alias "CATEGORY"
- :lib/desired-column-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"
- :fk_field_id (meta/id :orders :product-id)}
+ (is (=? [{:name "CATEGORY"
+ :display_name "Product → Category"
+ ;; This should be `:source/implicitly-joinable` because we reify the join during preprocessing, and
+ ;; join doesn't exist in the original version of the query. Note that join alias doesn't come back in
+ ;; this case because [[metabase.lib.metadata.result-metadata/remove-implicit-join-aliases]] strips it
+ ;; out.
+ :lib/source :source/implicitly-joinable
+ :lib/breakout? true
+ :lib/source-column-alias "CATEGORY"
+ :lib/desired-column-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"
+ :metabase.lib.join/join-alias (symbol "nil #_\"key is not present.\"")
+ :lib/original-join-alias (symbol "nil #_\"key is not present.\"")
+ :source_alias (symbol "nil #_\"key is not present.\"")
+ :fk_field_id (meta/id :orders :product-id)}
{:name "count"
:display_name "Count"
:lib/source :source/aggregations
diff --git a/test/metabase/query_processor/util/transformations/nest_breakouts_test.clj b/test/metabase/query_processor/util/transformations/nest_breakouts_test.clj
index cd31159301f..34b94146c52 100644
--- a/test/metabase/query_processor/util/transformations/nest_breakouts_test.clj
+++ b/test/metabase/query_processor/util/transformations/nest_breakouts_test.clj
@@ -14,8 +14,8 @@
[metabase.query-processor.util.add-alias-info :as add]
[metabase.query-processor.util.transformations.nest-breakouts :as nest-breakouts]))
-(deftest cumulative-aggregation-with-filter-and-temporal-bucketed-breakout-test
- (with-redefs [driver/escape-alias (fn [_ s] (driver.impl/truncate-alias s 30))]
+(deftest ^:parallel cumulative-aggregation-with-filter-and-temporal-bucketed-breakout-test
+ (binding [add/*escape-alias-fn* (fn [_ s] (driver.impl/truncate-alias s 30))]
(testing "Query with a filter and a temporally bucketed breakout should work (#41791)"
(let [orders (meta/table-metadata :orders)
orders-quantity (meta/field-metadata :orders :quantity)
@@ -36,8 +36,8 @@
:limit 5}]}
(nest-breakouts/nest-breakouts-in-stages-with-window-aggregation query)))))))
-(deftest nest-breakouts-test
- (with-redefs [driver/escape-alias (fn [_ s] (driver.impl/truncate-alias s 30))]
+(deftest ^:parallel nest-breakouts-test
+ (binding [add/*escape-alias-fn* (fn [_ s] (driver.impl/truncate-alias s 30))]
(let [metadata-provider meta/metadata-provider
orders (lib.metadata/table metadata-provider (meta/id :orders))
orders-created-at (lib.metadata/field metadata-provider (meta/id :orders :created-at))
@@ -83,10 +83,10 @@
:limit 3}]}
(nest-breakouts/nest-breakouts-in-stages-with-window-aggregation query))))))
-(deftest escape-identifiers-correctly-test
- (testing (str "Refs in the second stage need to get escaped using [[metabase.driver/escape-alias]]."
+(deftest ^:parallel escape-identifiers-correctly-test
+ (testing (str "Refs in the second stage should get escaped correctly when running results thru `add-alias-info`."
" Simulate Oracle behavior here, which truncates all identifiers to 30 characters.")
- (with-redefs [driver/escape-alias (fn [_ s] (driver.impl/truncate-alias s 30))]
+ (binding [add/*escape-alias-fn* (fn [_ s] (driver.impl/truncate-alias s 30))]
(let [metadata-provider (lib.tu/merged-mock-metadata-provider
meta/metadata-provider
{:database {}
@@ -99,9 +99,9 @@
:schema "mb_test"
:name "test_data_products"}]
:fields [{:id (meta/id :orders :created-at), :name "created_at"}
- {:id (meta/id :orders :id), :name "id"}
+ {:id (meta/id :orders :id), :name "id"}
{:id (meta/id :orders :product-id), :name "product_id"}
- {:id (meta/id :products :id), :name "id"}
+ {:id (meta/id :products :id), :name "id"}
{:id (meta/id :products :category), :name "category"}]})
orders (lib.metadata/table metadata-provider (meta/id :orders))
orders-created-at (lib.metadata/field metadata-provider (meta/id :orders :created-at))
@@ -116,39 +116,63 @@
(lib/aggregate (lib/cum-count))
(lib/breakout (lib/with-temporal-bucket orders-created-at :year))
(lib/breakout products-category))
- preprocessed (qp.store/with-metadata-provider metadata-provider
- (lib.query/query metadata-provider (driver/with-driver :h2
- (add/add-alias-info (qp.preprocess/preprocess query)))))
- actual (nest-breakouts/nest-breakouts-in-stages-with-window-aggregation
- preprocessed)]
+ preprocessed (qp.store/with-metadata-provider metadata-provider
+ (lib.query/query metadata-provider (driver/with-driver :h2
+ (add/add-alias-info (qp.preprocess/preprocess query)))))
+ actual (qp.store/with-metadata-provider metadata-provider
+ (driver/with-driver :h2
+ (-> (nest-breakouts/nest-breakouts-in-stages-with-window-aggregation preprocessed)
+ lib/->legacy-MBQL
+ add/add-alias-info
+ lib/->pMBQL)))]
(is (=? {:stages [{;; join alias is escaped:
;;
;; (metabase.driver/escape-alias :oracle "test_data_products__via__product_id")
;; =>
;; "test_data_products__v_af2712b9"
- :joins [{::add/alias "test_data_products__v_af2712b9"
- :stages [{:lib/type :mbql.stage/mbql, :source-table pos-int?}]
- :conditions [[:=
- {}
- [:field {} pos-int?]
- [:field
- {::add/source-table "test_data_products__v_af2712b9"}
- pos-int?]]]}]
- :fields [[:field {} pos-int?]
- [:field {::add/source-table "test_data_products__v_af2712b9"} pos-int?]]
+ :joins [{::add/alias "test_data_products__v_af2712b9"
+ :stages [{:lib/type :mbql.stage/mbql, :source-table pos-int?}]
+ :conditions [[:=
+ {}
+ [:field {} pos-int?]
+ [:field
+ {::add/source-table "test_data_products__v_af2712b9"}
+ pos-int?]]]}]
+ :fields [[:field {} pos-int?]
+ [:field {::add/source-table "test_data_products__v_af2712b9"} pos-int?]]
:filters [[:>
{}
[:field {} pos-int?]
[:value {} 5000]]]}
- ;; new second stage. Source column names are escaped:
+ ;; new second stage. Source column names ONLY GET ESCAPED WHEN RAN THRU `add-alias-info`,
+ ;; which should always be done after using this transformation:
;;
;; (metabase.driver/escape-alias :oracle "test_data_products__v_af2712b9__category")
;; =>
;; "test_data_products__v_f48e965c"
- {:breakout [[:field {} "created_at"]
- [:field {:join-alias (symbol "nil #_\"key is not present.\"")
- :source-field (symbol "nil #_\"key is not present.\"")}
- "test_data_products__v_d795ff70"]]
+ {:breakout [[:field {} "created_at"]
+ [:field {:join-alias (symbol "nil #_\"key is not present.\"")
+ :source-field (symbol "nil #_\"key is not present.\"")
+ ::add/source-alias "test_data_products__v_d795ff70"
+ ::add/desired-alias "test_data_products__v_d795ff70"}
+ "test_data_products__via__product_id__category"]]
:aggregation [[:count {:name "count"}]
[:cum-count {:name "count_2"}]]}]}
actual))))))
+
+(deftest ^:parallel cumulative-count-offset-day-of-year-test
+ (testing "day is finer than day-of-year (GROUP BY should preserve breakout order; add ORDER BY day-of-year, day)"
+ (let [mp meta/metadata-provider
+ created-at (meta/field-metadata :orders :created-at)]
+ (is (=? {:breakout [[:field {:inherited-temporal-unit :day} "CREATED_AT"]
+ [:field {:inherited-temporal-unit :day-of-year} "CREATED_AT_2"]]
+ :order-by [[:asc {} [:field {:inherited-temporal-unit :day-of-year} "CREATED_AT_2"]]
+ [:asc {} [:field {:inherited-temporal-unit :day} "CREATED_AT"]]]}
+ (-> (lib/query mp (meta/table-metadata :orders))
+ (lib/breakout (lib/with-temporal-bucket created-at :day))
+ (lib/breakout (lib/with-temporal-bucket created-at :day-of-year))
+ (lib/aggregate (lib/count))
+ (lib/aggregate (lib/offset (lib/count) -1))
+ nest-breakouts/nest-breakouts-in-stages-with-window-aggregation
+ :stages
+ second))))))
diff --git a/test/metabase/query_processor_test/breakout_test.clj b/test/metabase/query_processor_test/breakout_test.clj
index e55aa8a0743..60d75e1cb2c 100644
--- a/test/metabase/query_processor_test/breakout_test.clj
+++ b/test/metabase/query_processor_test/breakout_test.clj
@@ -3,6 +3,7 @@
(:require
[clojure.test :refer :all]
[medley.core :as m]
+ [metabase.driver :as driver]
[metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
@@ -319,6 +320,7 @@
{:breakout [$price]
:fields [$price]})))))))
+;;; TODO (Cam 8/6/25) -- move this and other binning-related tests to `binning-test`
(deftest ^:parallel binning-with-source-card-with-explicit-joins-test
(testing "Make sure binning works with a source card that contains explicit joins"
(mt/test-drivers (mt/normal-drivers-with-feature :binning :nested-queries :left-join)
@@ -346,4 +348,18 @@
_ (is (some? binning-strategy))
query (-> query
(lib/breakout (lib/with-binning people-longitude binning-strategy)))]
- (mt/rows (qp/process-query query)))))))))
+ ;; only check the query for H2; other databases might name `LONGITUDE` differently
+ (when (= driver/*driver* :h2)
+ (is (=? {:stages [{:source-card 1
+ :aggregation [[:count {}]]
+ :breakout [[:field
+ {:binning {:strategy :bin-width, :bin-width 20.0}}
+ "People__LONGITUDE"]]}]}
+ query)))
+ (is (= [[-180.0 75]
+ [-160.0 383]
+ [-140.0 879]
+ [-120.0 3803]
+ [-100.0 11345]
+ [-80.0 2275]]
+ (mt/formatted-rows [1.0 int] (qp/process-query query)))))))))))
diff --git a/test/metabase/query_processor_test/count_where_test.clj b/test/metabase/query_processor_test/count_where_test.clj
index e9b88a9fa50..31201ce585b 100644
--- a/test/metabase/query_processor_test/count_where_test.clj
+++ b/test/metabase/query_processor_test/count_where_test.clj
@@ -1,7 +1,9 @@
(ns ^:mb/driver-tests metabase.query-processor-test.count-where-test
(:require
[clojure.test :refer :all]
+ [metabase.lib.test-util :as lib.tu]
[metabase.query-processor :as qp]
+ [metabase.query-processor.store :as qp.store]
[metabase.test :as mt]))
(deftest ^:parallel basic-test
@@ -76,11 +78,14 @@
(deftest ^:parallel segment-test
(mt/test-drivers (mt/normal-drivers-with-feature :basic-aggregations)
- (mt/with-temp [:model/Segment {segment-id :id} {:table_id (mt/id :venues)
- :definition {:source-table (mt/id :venues)
- :filter [:< [:field (mt/id :venues :price) nil] 4]}}]
+ (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider
+ (mt/metadata-provider)
+ {:segments [{:id 1
+ :table-id (mt/id :venues)
+ :definition {:source-table (mt/id :venues)
+ :filter [:< [:field (mt/id :venues :price) nil] 4]}}]})
(is (= 94
- (->> {:aggregation [[:count-where [:segment segment-id]]]}
+ (->> {:aggregation [[:count-where [:segment 1]]]}
(mt/run-mbql-query venues)
mt/rows
ffirst
@@ -88,14 +93,17 @@
(deftest ^:parallel metric-test
(mt/test-drivers (mt/normal-drivers-with-feature :basic-aggregations)
- (mt/with-temp [:model/Card {metric-id :id} {:dataset_query (mt/mbql-query venues
- {:aggregation [:count-where
- [:< $price 4]]
+ (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider
+ (mt/metadata-provider)
+ {:cards [{:id 1
+ :dataset-query (mt/mbql-query venues
+ {:aggregation [:count-where
+ [:< $price 4]]
:source-table $$venues})
- :type :metric}]
+ :type :metric}]})
(is (= 94
- (->> {:aggregation [[:metric metric-id]]
- :source-table (str "card__" metric-id)}
+ (->> {:aggregation [[:metric 1]]
+ :source-table "card__1"}
(mt/run-mbql-query venues)
mt/rows
ffirst
diff --git a/test/metabase/query_processor_test/cumulative_aggregation_test.clj b/test/metabase/query_processor_test/cumulative_aggregation_test.clj
index 740740c0668..e8003abe9a6 100644
--- a/test/metabase/query_processor_test/cumulative_aggregation_test.clj
+++ b/test/metabase/query_processor_test/cumulative_aggregation_test.clj
@@ -491,7 +491,7 @@
(qp/process-query query)))))))))
(deftest ^:parallel cumulative-count-different-temporal-fields-test
- (testing "day is finer than day-of-year"
+ (testing "month-of-year is finer than year (GROUP BY should preserve breakout order; add ORDER BY year, month-of-year)"
(mt/test-drivers (mt/normal-drivers-with-feature :window-functions/cumulative)
(let [metadata-provider (lib.metadata.jvm/application-database-metadata-provider (mt/id))
orders (lib.metadata/table metadata-provider (mt/id :orders))
@@ -521,7 +521,7 @@
(qp/process-query query)))))))))
(deftest ^:parallel cumulative-count-offset-day-of-year-test
- (testing "day is finer than day-of-year"
+ (testing "day is finer than day-of-year (GROUP BY should preserve breakout order; add ORDER BY day-of-year, day)"
(mt/test-drivers (mt/normal-drivers-with-feature :window-functions/cumulative :window-functions/offset)
(let [metadata-provider (lib.metadata.jvm/application-database-metadata-provider (mt/id))
orders (lib.metadata/table metadata-provider (mt/id :orders))
diff --git a/test/metabase/query_processor_test/explicit_joins_test.clj b/test/metabase/query_processor_test/explicit_joins_test.clj
index 72e3b5ea398..dfe8a907c51 100644
--- a/test/metabase/query_processor_test/explicit_joins_test.clj
+++ b/test/metabase/query_processor_test/explicit_joins_test.clj
@@ -582,9 +582,9 @@
:limit 2})))]
(is (= (mapv
mt/format-name
- ["id" "date" "user_id" "venue_id" ; checkins
- "id_2" "name" "last_login" ; users
- "id_3" "name_2" "category_id" "latitude" "longitude" "price"]) ; venues
+ ["id" "date" "user_id" "venue_id" ; checkins
+ "id_2" "name" "last_login" ; users
+ #_"id_3" "id_2_2" "name_2" "category_id" "latitude" "longitude" "price"]) ; venues
columns))
(is (= [[1 "2014-04-07T00:00:00Z" 5 12
5 "Quentin Sören" "2014-10-03T17:30:00Z"
diff --git a/test/metabase/query_processor_test/field_ref_repro_test.clj b/test/metabase/query_processor_test/field_ref_repro_test.clj
index ad3c2005691..bc68ca18ab4 100644
--- a/test/metabase/query_processor_test/field_ref_repro_test.clj
+++ b/test/metabase/query_processor_test/field_ref_repro_test.clj
@@ -446,7 +446,7 @@
;; The order of these columns seems to be 'flexible' (I would consider either to be correct), and
;; I've seen both in two different branches of mine attempting to fix this bug. The order doesn't
;; matter at all to the FE, so if this changes in the future it's ok. -- Cam
- "j__EMAIL"
+ "j__PEOPLE__via__USER_ID__EMAIL" #_"j__EMAIL"
"PEOPLE__via__USER_ID__EMAIL"]
(map :lib/desired-column-alias (mt/cols results))))
(is (= [[1 ; <= orders.id
diff --git a/test/metabase/query_processor_test/remapping_test.clj b/test/metabase/query_processor_test/remapping_test.clj
index 7c660971ac9..f1e91b58898 100644
--- a/test/metabase/query_processor_test/remapping_test.clj
+++ b/test/metabase/query_processor_test/remapping_test.clj
@@ -469,19 +469,19 @@
;; The order of remaps is not important to the FE. If it changes in the future that is ok.
;;
;; 2 remaps from the join against `VENUES`
- "J__NAME_2"
- "J__NAME_3"
+ "J__CATEGORIES__via__ID__NAME"
+ "J__CATEGORIES__via__CATEGORY_ID__NAME"
;; 2 remaps for the top-level query
"CATEGORIES__via__CATEGORY_ID__NAME"
"CATEGORIES__via__ID__NAME"
;; BROKEN! This is a duplicate and should not be returned. Interestingly enough, both Lib and QP
;; incorrectly calculate the set of returned columns and both include this. (Probably because Lib and QP
;; use mostly the same code these days.)
- "J__NAME_4"]
+ "J__CATEGORIES__via__ID__NAME_2"]
(map :lib/desired-column-alias (mt/cols results))))
;; The extra incorrect duplicate column seems to be sorta indetermiate? I've seen it match the value of
- ;; `J__NAME_2` and `J__NAME_3` in different test runs and I'm not sure why. Not bothering to debug since it's not
- ;; even supposed to be returned anyway.
+ ;; `J__CATEGORIES__via__ID__NAME` and `J__CATEGORIES__via__CATEGORY_ID__NAME` in different test runs and I'm not
+ ;; sure why. Not bothering to debug since it's not even supposed to be returned anyway.
;;
;; <top-level :fields> <join> <join remaps> <fields remaps> <incorrect duplicate>
(is (=? [[11 2 "Stout Burgers & Beers" 1 "Red Medicine" 4 10.0646 -165.374 3 "African" "Asian" "Burger" "American" string?]