From c15a5799876efed84dd016b46553c1bba680129e Mon Sep 17 00:00:00 2001
From: Case Nelson <case@metabase.com>
Date: Fri, 28 Jul 2023 12:08:07 -0600
Subject: [PATCH] [MLv2] Add field-id method (#32537)

* [MLv2] Add field-id method

* Update PR feedback
---
 src/metabase/lib/core.cljc        |  1 +
 src/metabase/lib/field.cljc       |  5 +++++
 src/metabase/lib/js.cljs          |  5 +++++
 test/metabase/lib/field_test.cljc | 12 ++++++++++++
 4 files changed, 23 insertions(+)

diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljc
index 725ed46f31c..74c58448a56 100644
--- a/src/metabase/lib/core.cljc
+++ b/src/metabase/lib/core.cljc
@@ -142,6 +142,7 @@
    upper
    lower]
   [lib.field
+   field-id
    fields
    with-fields
    fieldable-columns]
diff --git a/src/metabase/lib/field.cljc b/src/metabase/lib/field.cljc
index 1147e4ad87b..a9c4e5b86e9 100644
--- a/src/metabase/lib/field.cljc
+++ b/src/metabase/lib/field.cljc
@@ -529,3 +529,8 @@
                (assoc col :selected? true))
              visible-columns)
        (lib.equality/mark-selected-columns visible-columns selected-fields)))))
+
+(mu/defn field-id :- [:maybe ::lib.schema.common/int-greater-than-or-equal-to-zero]
+  "Find the field id for something or nil."
+  [field-metadata :- lib.metadata/ColumnMetadata]
+  (:id field-metadata))
diff --git a/src/metabase/lib/js.cljs b/src/metabase/lib/js.cljs
index ca91fe8d897..8951f93b745 100644
--- a/src/metabase/lib/js.cljs
+++ b/src/metabase/lib/js.cljs
@@ -124,6 +124,11 @@
       (update :table update-keys u/->camelCaseEn)
       (clj->js :keyword-fn u/qualified-name)))
 
+(defn ^:export field-id
+  "Find the field id for something or nil."
+  [field-metadata]
+  (lib.core/field-id field-metadata))
+
 (defn ^:export order-by-clause
   "Create an order-by clause independently of a query, e.g. for `replace` or whatever."
   ([orderable]
diff --git a/test/metabase/lib/field_test.cljc b/test/metabase/lib/field_test.cljc
index 9fd9da2b90b..9ca7d6233b8 100644
--- a/test/metabase/lib/field_test.cljc
+++ b/test/metabase/lib/field_test.cljc
@@ -735,3 +735,15 @@
                query
                (lib/with-binning (m/find-first (comp #{"PRICE"} :name) breakoutables)
                  (first (lib.binning/numeric-binning-strategies)))))))))
+
+(deftest ^:parallel field-id-test
+  (let [id-meta (meta/field-metadata :venues :id)
+        query (-> (lib/query meta/metadata-provider (meta/table-metadata :venues))
+                  (lib/with-fields [id-meta])
+                  (lib/expression "foo" (lib/+ id-meta 10)))
+        venues-id (:id id-meta)
+        cols (lib/orderable-columns query)]
+    (is (= venues-id (lib/field-id id-meta)))
+    (is (=? {"foo" nil
+             "ID" venues-id}
+           (into {} (map (juxt :lib/desired-column-alias lib/field-id)) cols)))))
-- 
GitLab