Skip to content

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

Minor field ref resolution improvements (#62374)

Cam Saul7c979921b5e0
diff --git a/src/metabase/lib/field/resolution.cljc b/src/metabase/lib/field/resolution.cljc
index a4c7760ce3c..3a06b20d219 100644
--- a/src/metabase/lib/field/resolution.cljc
+++ b/src/metabase/lib/field/resolution.cljc
@@ -11,6 +11,7 @@
[metabase.lib.expression :as lib.expression]
[metabase.lib.field.util :as lib.field.util]
[metabase.lib.join :as lib.join]
+ [metabase.lib.join.util :as lib.join.util]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
[metabase.lib.schema :as lib.schema]
@@ -306,9 +307,12 @@
(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)]
+ (if-some [source-cols (or (when-some [previous-stage-number (lib.util/previous-stage-number query stage-number)]
+ (lib.metadata.calculation/returned-columns query previous-stage-number))
+ (when-some [source-card-id (:source-card (lib.util/query-stage query stage-number))]
+ (lib.metadata.calculation/returned-columns query (lib.metadata/card query source-card-id))))]
(let [previous-stage-cols (filter #(= (:lib/original-join-alias %) join-alias)
- (lib.metadata.calculation/returned-columns query previous-stage-number))]
+ source-cols)]
;; try to resolve by what is PROBABLY the correct name in a previous stage e.g. `Join` + `COLUMN` becomes
;; `Join__COLUMN`... if this fails then fall back to looking for matches that ignore join alias entirely
;; e.g. just `COLUMN`
@@ -319,6 +323,106 @@
(log/debug "Unable to resolve in previous stage =(")
nil))))))
+(mu/defn- resolve-in-implicit-join-previous-stage
+ "First, try to resolve the implicit join from the previous stage columns -- the join might have already been
+ performed there and `:source-field` was specified incorrectly. (You're only supposed to specify this in the stage
+ the implicit join happens; after that you should drop it and use field name refs instead e.g.
+ `CATEGORIES__via__CATEGORY_ID`.) If this did happen in a previous stage we should return `:lib/original-fk-field-id`
+ in the metadata instead of the usual `:source-field` => `:fk-field-id` mapping, otherwise we're liable to construct
+ incorrect desired column aliases. [[lib.field.util/update-keys-for-col-from-previous-stage]] should take care of the
+ renaming."
+ [query :- ::lib.schema/query
+ stage-number :- :int
+ source-field-id :- ::lib.schema.id/field
+ id-or-name :- ::id-or-name]
+ (when-some [previous-stage-number (lib.util/previous-stage-number query stage-number)]
+ ;; only look for columns from the previous stage that were originally implicitly joined using the same FK. (It is
+ ;; possible to implicitly join the same Table more than once with different FKs.)
+ (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-metadata-and-update-keys query previous-stage-cols id-or-name))))
+
+(mu/defn- find-reified-implicit-join-with-fk-field-id :- [:maybe [:tuple ::lib.schema.join/join :int]]
+ "Find the reified implicit join (i.e., a join added by
+ the [[metabase.query-processor.middleware.add-implicit-joins]] middleware) that has `:fk-field-id` if one exists;
+ returns tuple of `[join join-stage-number]`."
+ [query stage-number source-field-id]
+ (or (when-some [join (m/find-first (fn [join]
+ (= (:fk-field-id join) source-field-id))
+ (:joins (lib.util/query-stage query stage-number)))]
+ [join stage-number])
+ (when-some [previous-stage-number (lib.util/previous-stage-number query stage-number)]
+ (recur query previous-stage-number source-field-id))))
+
+(defn- resolve-name-in-implicit-join-this-stage
+ "You REALLY shouldn't be specifying `:source-field` in a field name ref, since it makes resolution 10x harder. There's
+ a 99.9% chance that using a field name ref with `:source-field` is a bad idea and broken, I even considered banning
+ it at the schema level, but decided to let it be for now since we should still be able to resolve it. we need to do
+ the lookup as follows:
+
+ Source Field (FK)
+ =>
+ Target Field (Field with `:fk-target-field-id` AKA the field the FK points to)
+ =>
+ Target Table (Table to implicitly join)
+ =>
+ Resolve in Target Table metadata"
+ [query source-field-id field-name]
+ (when-some [source-field (lib.metadata/field query source-field-id)]
+ (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))]
+ ;; 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)
+ field-name))))))
+
+(mu/defn- resolve-in-implicit-join-current-stage :- [:maybe ::lib.metadata.calculation/visible-column]
+ [query :- ::lib.schema/query
+ source-field-id :- ::lib.schema.id/field
+ id-or-name :- ::id-or-name]
+ (when-some [col (if (pos-int? id-or-name)
+ (field-metadata query id-or-name)
+ (resolve-name-in-implicit-join-this-stage query source-field-id 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)))
+
+;;; See for
+;;; example [[metabase.query-processor-test.field-ref-repro-test/model-with-implicit-join-and-external-remapping-test]],
+;;; if we have a field ref to an implicit join but the implicit join in a previous stage but that column is not
+;;; propagated to the stage we're resolving for the query almost certainly won't work, but we can at least return
+;;; somewhat more helpful metadata than the base fallback metadata that would give you a confusing error message.
+(defn- resolve-unreturned-column-in-reified-implicit-join-in-previous-stage
+ [query stage-number source-field-id id-or-name]
+ (let [[join join-stage-number] (find-reified-implicit-join-with-fk-field-id query stage-number source-field-id)]
+ (when (and join-stage-number
+ (not= join-stage-number stage-number))
+ (log/errorf (str "Field ref %s in stage %s specifies :source-field-id %s, but we found the implicit join %s in"
+ " earlier stage %s, which doesn't return this column. Query almost certainly won't work"
+ " correctly.")
+ (pr-str id-or-name)
+ (pr-str stage-number)
+ (pr-str source-field-id)
+ (pr-str (:alias join))
+ (pr-str join-stage-number))
+ (when-some [col (resolve-in-implicit-join-current-stage query source-field-id id-or-name)]
+ (-> col
+ lib.field.util/update-keys-for-col-from-previous-stage
+ (assoc :lib/original-join-name (:alias join)
+ :lib/source-column-alias (lib.join.util/joined-field-desired-alias
+ (:alias join)
+ ((some-fn :lib/source-column-alias :name) col))
+ ::fallback-metadata? true))))))
+
(mu/defn- resolve-in-implicit-join :- [:maybe ::lib.metadata.calculation/visible-column]
[query :- ::lib.schema/query
stage-number :- :int
@@ -326,60 +430,11 @@
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
- ;; performed there and `:source-field` was specified incorrectly. (You're only supposed to specify this in the stage
- ;; the implicit join happens; after that you should drop it and use field name refs instead e.g.
- ;; `CATEGORIES__via__CATEGORY_ID`.) If this did happen in a previous stage we should return
- ;; `:lib/original-fk-field-id` in the metadata instead of the usual `:source-field` => `:fk-field-id` mapping,
- ;; otherwise we're liable to construct incorrect desired column
- ;; aliases. [[lib.field.util/update-keys-for-col-from-previous-stage]] should take care of the renaming.
- (or
- (when-some [previous-stage-number (lib.util/previous-stage-number query stage-number)]
- ;; only look for columns from the previous stage that were originally implicitly joined using the same FK. (It is
- ;; possible to implicitly join the same Table more than once with different FKs.)
- (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-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)
- ;; easy enough to resolve Field ID refs.
- (field-metadata query id-or-name)
- ;;
- ;; string name ref
- ;;
- ;; You REALLY shouldn't be specifying `:source-field` in a field name ref, since it makes
- ;; resolution 10x harder. There's a 99.9% chance that using a field name ref with `:source-field`
- ;; is a bad idea and broken, I even considered banning it at the schema level, but decided to let
- ;; it be for now since we should still be able to resolve it.
- ;; we need to do the lookup as follows:
- ;;
- ;; Source Field (FK)
- ;; =>
- ;; Target Field (Field with `:fk-target-field-id` AKA the field the FK points to)
- ;; =>
- ;; Target Table (Table to implicitly join)
- ;; =>
- ;; Resolve in Target Table metadata
- (when-some [source-field (lib.metadata/field query source-field-id)]
- (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))]
- ;; 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))))
+ (or (resolve-in-implicit-join-previous-stage query stage-number source-field-id id-or-name)
+ (resolve-unreturned-column-in-reified-implicit-join-in-previous-stage query stage-number source-field-id 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.
+ (resolve-in-implicit-join-current-stage query source-field-id id-or-name)))
(mu/defn- resolve-in-previous-stage :- [:maybe ::lib.metadata.calculation/visible-column]
[query :- ::lib.schema/query
@@ -549,12 +604,14 @@
(log/debugf "Resolving %s in stage %s" (pr-str id-or-name) (pr-str stage-number))
(u/prog1 (-> (merge-metadata
{:lib/type :metadata/column}
- (or (cond
- join-alias (resolve-in-join query stage-number join-alias id-or-name)
- source-field (resolve-in-implicit-join query stage-number source-field id-or-name)
- :else (resolve-from-previous-stage-or-source query stage-number id-or-name))
+ (or (when join-alias
+ (resolve-in-join query stage-number join-alias id-or-name))
+ (when source-field
+ (resolve-in-implicit-join query stage-number source-field id-or-name))
+ (resolve-from-previous-stage-or-source query stage-number id-or-name)
(merge
- (fallback-metadata id-or-name)
+ (or (fallback-metadata-for-field-id query stage-number id-or-name)
+ (fallback-metadata id-or-name))
(when (and join-alias
(contains? (into #{}
(map :alias)
diff --git a/src/metabase/query_processor/util/add_alias_info.clj b/src/metabase/query_processor/util/add_alias_info.clj
index d732201e981..c2a56ae56e3 100644
--- a/src/metabase/query_processor/util/add_alias_info.clj
+++ b/src/metabase/query_processor/util/add_alias_info.clj
@@ -191,8 +191,12 @@
(case (:lib/source col)
:source/table-defaults (:table-id col)
(:source/joins
- :source/implicitly-joinable) (or (escaped-join-alias query stage-path (:metabase.lib.join/join-alias col))
- (throw (ex-info "Resolved metadata is missing ::escaped-join-alias" {:col col})))
+ :source/implicitly-joinable) (let [join-alias (or (:metabase.lib.join/join-alias col)
+ (throw (ex-info (format "Column with source %s is missing join alias" (:lib/source col))
+ {:col col})))]
+ (or (escaped-join-alias query stage-path join-alias)
+ (throw (ex-info (format "Resolved metadata is missing ::escaped-join-alias for %s" (pr-str (:metabase.lib.join/join-alias col)))
+ {:col col}))))
(:source/previous-stage
:source/card) ::source
(:source/expressions
diff --git a/test/metabase/lib/field/resolution_test.cljc b/test/metabase/lib/field/resolution_test.cljc
index 7d8c50bb8ec..55cb3a47233 100644
--- a/test/metabase/lib/field/resolution_test.cljc
+++ b/test/metabase/lib/field/resolution_test.cljc
@@ -766,6 +766,27 @@
:display-name "Unknown Field"}
(lib.field.resolution/resolve-field-ref query -1 field-ref))))))
+(deftest ^:parallel fallback-metadata-for-unreturned-field-id-ref-test
+ (testing "Fallback metadata for a Field ID ref that is not returned by this query should at least include the actual correct :name"
+ (let [query (lib/query meta/metadata-provider (meta/table-metadata :venues))
+ field-ref [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :orders :id)]]
+ (is (=? {:base-type :type/BigInteger
+ :display-name "ID"
+ :effective-type :type/BigInteger
+ :id (meta/id :orders :id)
+ :name "ID"
+ :semantic-type :type/PK
+ :table-id (meta/id :orders)
+ :visibility-type :normal
+ :lib/original-display-name "ID"
+ :lib/original-name "ID"
+ :lib/source :source/table-defaults
+ :lib/source-column-alias "ID"
+ :lib/source-uuid "00000000-0000-0000-0000-000000000000"
+ :lib/type :metadata/column
+ ::lib.field.resolution/fallback-metadata? true}
+ (into (sorted-map) (lib.field.resolution/resolve-field-ref query -1 field-ref)))))))
+
(deftest ^:parallel do-not-propagate-lib-expression-names-from-cards-test
(testing "Columns coming from a source card should not propagate :lib/expression-name"
(let [q1 (-> (lib/query meta/metadata-provider (meta/table-metadata :venues))
@@ -1309,3 +1330,56 @@
query
-1
[:field {:base-type :type/BigInteger, :lib/uuid "00000000-0000-0000-0000-000000000000"} "ID"]))))))
+
+;;; See also [[metabase.query-processor-test.field-ref-repro-test/model-with-implicit-join-and-external-remapping-test]]
+(deftest ^:parallel resolve-unreturned-column-from-reified-implicit-join-in-previous-stage-test
+ (let [query (lib/query
+ meta/metadata-provider
+ {:lib/type :mbql/query
+ :database (meta/id)
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table (meta/id :orders)
+ :fields [[:field {} (meta/id :orders :user-id)]
+ [:field {:join-alias "PEOPLE__via__USER_ID"} (meta/id :people :email)]]
+ :joins [{:lib/type :mbql/join
+ :qp/is-implicit-join true
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table (meta/id :people)}]
+ :alias "PEOPLE__via__USER_ID"
+ :conditions [[:= {}
+ [:field
+ {}
+ (meta/id :orders :user-id)]
+ [:field
+ {:join-alias "PEOPLE__via__USER_ID"}
+ (meta/id :people :id)]]]
+ :fk-field-id (meta/id :orders :user-id)}]}
+ {:lib/type :mbql.stage/mbql}
+ {:lib/type :mbql.stage/mbql}]})
+ field-ref [:field
+ {:base-type :type/Text
+ :join-alias "PEOPLE__via__USER_ID"
+ :source-field-name "USER_ID"
+ :source-field (meta/id :orders :user-id)
+ :lib/uuid "978082dd-2728-4053-b9cc-01bbd64f3507"
+ :effective-type :type/Text}
+ (meta/id :people :state)]]
+ (is (=? {:display-name "User → State"
+ :effective-type :type/Text
+ :fingerprint some?
+ :fk-field-name "USER_ID"
+ :id (meta/id :people :state)
+ :name "STATE"
+ :semantic-type :type/State
+ :table-id (meta/id :people)
+ :lib/breakout? false
+ :lib/original-display-name "State"
+ :lib/original-fk-field-id (meta/id :orders :user-id)
+ :lib/original-join-name "PEOPLE__via__USER_ID"
+ :lib/original-name "STATE"
+ :lib/source :source/previous-stage
+ :lib/source-column-alias "PEOPLE__via__USER_ID__STATE"
+ :lib/source-uuid "978082dd-2728-4053-b9cc-01bbd64f3507"
+ :lib/type :metadata/column
+ ::lib.field.resolution/fallback-metadata? true}
+ (into (sorted-map) (lib.field.resolution/resolve-field-ref query -1 field-ref))))))
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 bb64e00b8bd..8bf0e2f878f 100644
--- a/test/metabase/query_processor_test/field_ref_repro_test.clj
+++ b/test/metabase/query_processor_test/field_ref_repro_test.clj
@@ -37,8 +37,7 @@
query (lib/join base (-> (lib/join-clause card-meta [(lib/= lhs (lib/with-join-alias rhs "j"))])
(lib/with-join-fields :all)
(lib/with-join-alias "j")))]
- (mt/with-native-query-testing-context
- query
+ (mt/with-native-query-testing-context query
(testing "should return a single row with two columns"
(is (= {:rows [[1 1]], :columns ["_ID" "_ID_2"]}
(mt/rows+column-names
@@ -57,7 +56,7 @@
(lib/filter (lib/contains long-name-col "a"))
(lib/limit 3))]
(mt/with-native-query-testing-context query
- ;; should return 53 rows with two columns, but fails instead
+ ;; should return 53 rows with two columns
(is (= {:rows [[5 "Gadget"]
[11 "Gadget"]
[16 "Gadget"]]
@@ -66,7 +65,10 @@
(mt/rows+column-names
(qp/process-query query))))))))
-;; other than producing the metadata for the card, there is no query processing here
+;;; TODO (Cam 8/19/25) -- move these tests into Lib (probably [[metabase.lib.field-ref-repro-test]]) since marking
+;;; things `:selected?` is a pure-Lib concern.
+
+;; other than producing the metadata for the card, there is no query processing here
(deftest ^:parallel duplicate-names-selection-test
(testing "Should be able to distinguish columns with the same name from a card with self join (#27521)"
(let [mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
@@ -118,10 +120,10 @@
{:name "RATING", :display-name "Rating", :selected? true}
{:name "BODY", :display-name "Body", :selected? true}
{:name "CREATED_AT", :display-name "Created At", :selected? true}
- ;; the following two Card 1 → ID should have :selected? true
+ ;; the following two Card 1 → ID should have :selected? true
{:name "ID", :display-name "Card 1 → ID", :selected? false}
{:name "ID_2", :display-name "Card 1 → ID", :selected? false}
- ;; these are implicitly joinable fields, :selected? false is right
+ ;; these are implicitly joinable fields, :selected? false is right
{:name "ID", :display-name "ID", :selected? false}
{:name "EAN", :display-name "Ean", :selected? false}
{:name "TITLE", :display-name "Title", :selected? false}
@@ -205,11 +207,11 @@
{:name "DISCOUNT", :display-name "Discount", :selected? true}
{:name "CREATED_AT", :display-name "Created At", :selected? true}
{:name "QUANTITY", :display-name "Quantity", :selected? true}
- ;; the following two Card 1 → Created At: ... fields should have :selected? true
+ ;; the following two Card 1 → Created At: ... fields should have :selected? true
{:name "CREATED_AT", :display-name "Card 1 → Created At: Month", :selected? false}
{:name "CREATED_AT_2", :display-name "Card 1 → Created At: Year", :selected? false}
{:name "count", :display-name "Card 1 → Count", :selected? true}
- ;; these are implicitly joinable fields, :selected? false is right
+ ;; these are implicitly joinable fields, :selected? false is right
{:name "ID", :display-name "ID", :selected? false}
{:name "ADDRESS", :display-name "Address", :selected? false}
{:name "EMAIL", :display-name "Email", :selected? false}
@@ -510,17 +512,25 @@
(is (= [[1746]]
(mt/rows results))))))))
+;;; This one is a really tricky one to solve, the problem is that the implicit join happens in the first stage (Card 1)
+;;; because of the remappped column, but the parameter asks to be applied to stage 3... it's too late to add a new
+;;; filter against `PEOPLE__via__USER_ID.STATE` at that point because it doesn't come back from stage 1 or 2 (this is
+;;; why resolution trips up and falls back to `source.STATE`. I think the only way to fix this would be to make the
+;;; parameter logic apply the parameter to the correct stage (ignoring `:stage-number` when it's wrong) or add another
+;;; duplicate implicit join in stage 3 to power the filter
+;;;
+;;; See
+;;; also [[metabase.lib.field.resolution-test/resolve-unreturned-column-from-reified-implicit-join-in-previous-stage-test]]
(deftest ^:parallel model-with-implicit-join-and-external-remapping-test
(testing "Should handle models with implicit join on externally remapped field (#57596)"
- (qp.store/with-metadata-provider
- (lib.tu/remap-metadata-provider
- (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
- [(mt/mbql-query orders)
- (mt/mbql-query nil {:source-table (str "card__" 1)})])
- (mt/id :orders :user_id)
- (mt/id :people :email))
+ (qp.store/with-metadata-provider (lib.tu/remap-metadata-provider
+ (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
+ [(mt/mbql-query orders)
+ (mt/mbql-query nil {:source-table "card__1"})])
+ (mt/id :orders :user_id)
+ (mt/id :people :email))
(let [query (-> (mt/mbql-query nil
- {:source-table (str "card__" 2)})
+ {:source-table "card__2"})
(assoc :parameters [{:value ["CA"]
:type :string/=
:id "72622120"
@@ -536,5 +546,5 @@
(mt/with-native-query-testing-context query
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
- #"Column .* not found"
+ #"Column \"source\.PEOPLE__via__USER_ID__STATE\" not found"
(-> query qp/process-query mt/rows count))))))))