Skip to content

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

`wrap-value-literals` => Lib (#62619)

Cam Sauleb8aad0e2cd7
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 696179e74bb..6620c247bbf 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -249,16 +249,15 @@
(taoensso.nippy/extend-freeze)
(taoensso.nippy/extend-thaw)]}
+ ;; TODO (Cam 8/22/25) -- what's the point of marking stuff deprecated if we don't have Kondo enforce it? We should
+ ;; remove all of these and add individual ignores as needed.
:deprecated-var
{:exclude
- {metabase.cmd.core/dump {:namespaces ["metabase\\.cmd-test" "metabase-enterprise\\.serialization\\.cmd-test"]}
- metabase.cmd.core/load {:namespaces ["metabase\\.cmd-test" "metabase-enterprise\\.serialization\\.cmd-test"]}
- metabase.driver.sql-jdbc.execute.old-impl/set-timezone-sql {:namespaces ["metabase\\.driver.*"]}
- metabase.driver.sql-jdbc.execute/set-time-zone-if-supported! {:namespaces ["metabase\\.driver.*"]}
- metabase.driver/current-db-time {:namespaces ["metabase.*"]}
- metabase.driver/supports? {:namespaces ["metabase.*"]}
- metabase.query-processor.middleware.resolve-joins/maybe-resolve-source-table {:namespaces ["metabase.*"]}
- metabase.query-processor.util/normalize-token {:namespaces ["metabase.*"]}}}
+ {metabase.driver.sql-jdbc.execute.old-impl/set-timezone-sql {:namespaces ["metabase\\.driver.*"]}
+ metabase.driver.sql-jdbc.execute/set-time-zone-if-supported! {:namespaces ["metabase\\.driver.*"]}
+ metabase.driver/current-db-time {:namespaces ["metabase.*"]}
+ metabase.driver/supports? {:namespaces ["metabase.*"]}
+ metabase.query-processor.util/normalize-token {:namespaces ["metabase.*"]}}}
:discouraged-var
{clojure.core/print {:message "Use metabase.util.log instead of clojure.core/print"}
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj
index 6fe4c785ac1..e89dac080e5 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj
@@ -200,8 +200,7 @@
$user_id
[:value 5 {:base_type :type/Integer
:semantic_type :type/FK
- :database_type "INTEGER"
- :name "USER_ID"}]]]
+ :database_type "INTEGER"}]]]
::row-level-restrictions/gtap? true
:query-permissions/gtapped-table $$checkins}
:joins [{:source-query
@@ -212,8 +211,7 @@
$venues.price
[:value 1 {:base_type :type/Integer
:semantic_type :type/Category
- :database_type "INTEGER"
- :name "PRICE"}]]
+ :database_type "INTEGER"}]]
::row-level-restrictions/gtap? true
:query-permissions/gtapped-table $$venues}
:alias "v"
@@ -900,8 +898,7 @@
[:value "Widget" {:base_type :type/Text
:semantic_type (t2/select-one-fn :semantic_type :model/Field
:id (mt/id :products :category))
- :database_type "CHARACTER VARYING"
- :name "CATEGORY"}]]
+ :database_type "CHARACTER VARYING"}]]
(get-in (-> drill-thru-query
qp.preprocess/preprocess
;; legacy usage -- don't do things like this going forward
diff --git a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
index 54e7e1a11fe..b6cd17ca369 100644
--- a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
+++ b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
@@ -128,6 +128,7 @@
(let [no-value? (= (:value v) params/no-value)]
(cond
(params.ops/operator? (get-in v [:value :type]))
+ #_{:clj-kondo/ignore [:deprecated-var]}
(let [param (:value v)
compiled-clause (-> (assoc param
:target
@@ -138,7 +139,6 @@
;; desugar only impacts :does-not-contain -> [:not [:contains ... but it prevents
;; an optimization of [:= 'field 1 2 3] -> [:in 'field [1 2 3]] since that
;; desugars to [:or [:= 'field 1] ...].
- #_{:clj-kondo/ignore [:deprecated-var]}
driver-api/desugar-filter-clause
driver-api/wrap-value-literals-in-mbql
mongo.qp/compile-filter
diff --git a/modules/drivers/oracle/test/metabase/driver/oracle_test.clj b/modules/drivers/oracle/test/metabase/driver/oracle_test.clj
index 5faaf7ea69e..c4566a1c21f 100644
--- a/modules/drivers/oracle/test/metabase/driver/oracle_test.clj
+++ b/modules/drivers/oracle/test/metabase/driver/oracle_test.clj
@@ -522,32 +522,39 @@
[[(t/offset-date-time 2024 11 5 12 12 12)]
[(t/offset-date-time 2024 11 6 13 13 13)]]]])
-(deftest date-column-filtering-test
- (mt/test-driver
- :oracle
- (mt/dataset
- date-cols-with-datetime-values
+(deftest ^:parallel date-column-filtering-test
+ (mt/test-driver :oracle
+ (mt/dataset date-cols-with-datetime-values
(testing "Oracle's DATE columns are mapped to type/DateTime (#49440)"
(testing "Synced field is correctly mapped"
(let [date-field (t2/select-one :model/Field
- {:where [:and
- [:= :table_id (t2/select-one-fn :id :model/Table :db_id (mt/id))]
- [:= :name "date_with_time"]]})]
- (are [key* expected-type] (= expected-type (key* date-field))
- :base_type :type/DateTime
- :database_type "DATE")))
+ :table_id (t2/select-one-fn :id :model/Table :db_id (mt/id))
+ :name "date_with_time")]
+ (is (=? {:base_type :type/DateTime
+ :database_type "DATE"}
+ date-field))))))))
+
+(deftest ^:parallel date-column-filtering-test-2
+ (mt/test-driver :oracle
+ (mt/dataset date-cols-with-datetime-values
+ (testing "Oracle's DATE columns are mapped to type/DateTime (#49440)"
(testing "Filtering with day temporal unit returns expected resutls"
- (is (= [[2M "2024-11-06T13:13:13Z"]]
- (mt/rows
- (mt/run-mbql-query
- dates_with_time
- {:filter [:= [:field %date_with_time {:base-type :type/Date :temporal-unit :day}] "2024-11-06"]})))))
+ (let [query (mt/mbql-query dates_with_time
+ {:filter [:= [:field %date_with_time {:base-type :type/Date :temporal-unit :day}] "2024-11-06"]})]
+ (mt/with-native-query-testing-context query
+ (is (= [[2M "2024-11-06T13:13:13Z"]]
+ (mt/rows (qp/process-query query)))))))))))
+
+(deftest ^:parallel date-column-filtering-test-3
+ (mt/test-driver :oracle
+ (mt/dataset date-cols-with-datetime-values
+ (testing "Oracle's DATE columns are mapped to type/DateTime (#49440)"
(testing "Filtering by datetime retuns expected results"
- (is (= [[1M "2024-11-05T12:12:12Z"]]
- (mt/rows
- (mt/run-mbql-query
- dates_with_time
- {:filter [:= [:field %date_with_time {:base-type :type/Date}] "2024-11-05T12:12:12"]})))))))))
+ (let [query (mt/mbql-query dates_with_time
+ {:filter [:= [:field %date_with_time {:base-type :type/DateTime}] "2024-11-05T12:12:12"]})]
+ (mt/with-native-query-testing-context query
+ (is (= [[1M "2024-11-05T12:12:12Z"]]
+ (mt/rows (qp/process-query query)))))))))))
(deftest ^:parallel repro-49433-test
(mt/test-driver
diff --git a/src/metabase/channel/render/body.clj b/src/metabase/channel/render/body.clj
index aa50899752d..0d28cd855bf 100644
--- a/src/metabase/channel/render/body.clj
+++ b/src/metabase/channel/render/body.clj
@@ -74,6 +74,8 @@
(mu/defn- format-scalar-value
[timezone-id :- [:maybe :string] value col visualization-settings]
(cond
+ ;; legacy usage -- do not use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(types/temporal-field? col)
((formatter/make-temporal-str-formatter timezone-id col {}) value)
diff --git a/src/metabase/driver/sql/parameters/substitution.clj b/src/metabase/driver/sql/parameters/substitution.clj
index a766ef5ac32..2f050af0053 100644
--- a/src/metabase/driver/sql/parameters/substitution.clj
+++ b/src/metabase/driver/sql/parameters/substitution.clj
@@ -315,9 +315,9 @@
(sql.qp/->honeysql driver form))]
(cond
(params.ops/operator? param-type)
+ #_{:clj-kondo/ignore [:deprecated-var]}
(->> (assoc params :target [:dimension (field->field-filter-clause driver field param-type value)])
params.ops/to-clause
- #_{:clj-kondo/ignore [:deprecated-var]}
driver-api/desugar-filter-clause
driver-api/wrap-value-literals-in-mbql
->honeysql
@@ -325,8 +325,8 @@
(params.dates/exclusion-date-type param-type value)
(let [field-clause (field->field-filter-clause driver field param-type value)]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(->> (params.dates/date-string->filter value field-clause)
- #_{:clj-kondo/ignore [:deprecated-var]}
driver-api/desugar-filter-clause
driver-api/wrap-value-literals-in-mbql
->honeysql
diff --git a/src/metabase/formatter/impl.clj b/src/metabase/formatter/impl.clj
index ae7879a4221..e850397a6b2 100644
--- a/src/metabase/formatter/impl.clj
+++ b/src/metabase/formatter/impl.clj
@@ -295,7 +295,8 @@
(cond
;; for numbers, return a format function that has already computed the differences.
;; todo: do the same for temporal strings
- (and apply-formatting? (types/temporal-field? col))
+ (and apply-formatting?
+ #_{:clj-kondo/ignore [:deprecated-var]} (types/temporal-field? col)) ; legacy usage -- do not use going forward
(datetime/make-temporal-str-formatter timezone-id col visualization-settings)
(and apply-formatting? (isa? (:semantic_type col) :type/Coordinate))
diff --git a/src/metabase/lib/convert.cljc b/src/metabase/lib/convert.cljc
index 60c09667dc2..0bef613b58d 100644
--- a/src/metabase/lib/convert.cljc
+++ b/src/metabase/lib/convert.cljc
@@ -472,8 +472,13 @@
;; Removing the namespaces from a few
true (perf/update-keys #(get options-preserved-in-legacy % %)))
(into {} (comp (disqualify)
- (remove (fn [[k _v]]
- (#{:effective-type :ident} k)))))
+ ;; remove `:effective-type` if `:base-type` is not present OR if it's the same as `:base-type`.
+ (remove (let [keys-to-remove (if (or (nil? (:base-type m))
+ (= (:effective-type m) (:base-type m)))
+ #{:effective-type :ident}
+ #{:ident})]
+ (fn [[k _v]]
+ (keys-to-remove k))))))
not-empty))
(defmulti ^:private aggregation->legacy-MBQL
@@ -520,7 +525,7 @@
[(cond-> k
(simple-keyword? k) u/->snake_case_en)
v]))
- options))
+ (options->legacy-MBQL options)))
::mbql.s/options-style.last-unless-empty (let [options (options->legacy-MBQL options)]
(cond-> (into [tag] args)
(seq options)
@@ -634,13 +639,6 @@
[id opts])]
(clause-with-options->legacy-MBQL [:field opts id])))
-(defmethod ->legacy-MBQL :value
- [[_tag opts value]]
- (let [opts (-> opts
- ;; remove effective type since it's not used/allowed in legacy MBQL
- (dissoc :effective-type))]
- (clause-with-options->legacy-MBQL [:value opts value])))
-
(defn- update-list->legacy-boolean-expression
[m pMBQL-key legacy-key]
(cond-> m
diff --git a/src/metabase/lib/field/resolution.cljc b/src/metabase/lib/field/resolution.cljc
index 3a06b20d219..7a174d32c53 100644
--- a/src/metabase/lib/field/resolution.cljc
+++ b/src/metabase/lib/field/resolution.cljc
@@ -620,7 +620,7 @@
{:lib/source :source/joins
:metabase.lib.join/join-alias join-alias})))
(options-metadata opts)
- {:lib/original-ref field-ref})
+ {:lib/original-ref-for-result-metadata-purposes-only field-ref})
(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
diff --git a/src/metabase/lib/metadata/result_metadata.cljc b/src/metabase/lib/metadata/result_metadata.cljc
index 0471a04a4fd..260fb7ab2cb 100644
--- a/src/metabase/lib/metadata/result_metadata.cljc
+++ b/src/metabase/lib/metadata/result_metadata.cljc
@@ -20,6 +20,7 @@
[metabase.lib.join :as lib.join]
[metabase.lib.join.util :as lib.join.util]
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
+ [metabase.lib.options :as lib.options]
[metabase.lib.ref :as lib.ref]
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.metadata :as lib.schema.metadata]
@@ -268,21 +269,23 @@
col :- ::kebab-cased-map]
(when (= (:lib/type col) :metadata/column)
(let [remove-join-alias? (remove-join-alias-from-broken-field-ref? query col)]
- (->> (if-let [original-ref (:lib/original-ref col)]
- (cond-> original-ref
- remove-join-alias? (lib.join/with-join-alias nil))
- (binding [lib.ref/*ref-style* :ref.style/broken-legacy-qp-results]
- (let [col (cond-> col
- remove-join-alias? (lib.join/with-join-alias nil)
- remove-join-alias? (assoc ::remove-join-alias? true))]
- (->> (merge
- col
- (when-not remove-join-alias?
- (when-let [previous-join-alias (:lib/original-join-alias col)]
- {:metabase.lib.join/join-alias previous-join-alias})))
- lib.ref/ref))))
- lib.convert/->legacy-MBQL
- (fe-friendly-expression-ref col)))))
+ (-> (if-let [original-ref (:lib/original-ref-for-result-metadata-purposes-only col)]
+ (cond-> original-ref
+ remove-join-alias? (lib.join/with-join-alias nil))
+ (binding [lib.ref/*ref-style* :ref.style/broken-legacy-qp-results]
+ (let [col (cond-> col
+ remove-join-alias? (lib.join/with-join-alias nil)
+ remove-join-alias? (assoc ::remove-join-alias? true))]
+ (->> (merge
+ col
+ (when-not remove-join-alias?
+ (when-let [previous-join-alias (:lib/original-join-alias col)]
+ {:metabase.lib.join/join-alias previous-join-alias})))
+ lib.ref/ref))))
+ ;; legacy field refs should never have `:effective-type`
+ (lib.options/update-options dissoc :effective-type)
+ lib.convert/->legacy-MBQL
+ (->> (fe-friendly-expression-ref col))))))
;; For unambiguous columns we should use broken legacy refs to maintain backward compatibility with legacy viz
;; settings, which use them as keys. Since ambiguous refs have never worked correctly it is ok to return
@@ -387,7 +390,7 @@
;;; keep it around but I don't have time to update a million tests. Why do columns have `:lib/uuid` anyway? They
;;; should maybe have `:lib/source-uuid` but I don't think they should have `:lib/uuid`.
(defn- remove-lib-uuids [col]
- (dissoc col :lib/uuid :lib/source-uuid :lib/original-ref))
+ (dissoc col :lib/uuid :lib/source-uuid :lib/original-ref-for-result-metadata-purposes-only))
(mu/defn- col->legacy-metadata :- ::kebab-cased-map
"Convert MLv2-style `:metadata/column` column metadata to the `snake_case` legacy format we've come to know and love
diff --git a/src/metabase/lib/util.cljc b/src/metabase/lib/util.cljc
index f9f32b27d21..180a23c6de9 100644
--- a/src/metabase/lib/util.cljc
+++ b/src/metabase/lib/util.cljc
@@ -82,13 +82,15 @@
(and (clause? clause)
(lib.hierarchy/isa? (first clause) ::lib.schema.ref/metric)))
+;;; TODO (Cam 8/28/25) -- base type is the original effective type!!! We shouldn't need a separate
+;;; `:metabase.lib.field/original-effective-type` key.
(defn original-isa?
"Returns whether the type of `expression` isa? `typ`.
If the expression has an original-effective-type due to bucketing, check that."
[expression typ]
(isa?
(or (and (clause? expression)
- (:metabase.lib.field/original-effective-type (second expression)))
+ ((some-fn :metabase.lib.field/original-effective-type :base-type) (lib.options/options expression)))
(lib.schema.expression/type-of expression))
typ))
diff --git a/src/metabase/lib/walk.cljc b/src/metabase/lib/walk.cljc
index 271422376c3..e39867b8eec 100644
--- a/src/metabase/lib/walk.cljc
+++ b/src/metabase/lib/walk.cljc
@@ -2,6 +2,8 @@
"Tools for walking and transforming a query."
(:require
[medley.core :as m]
+ [metabase.lib.dispatch :as lib.dispatch]
+ [metabase.lib.hierarchy :as lib.hierarchy]
[metabase.lib.join :as lib.join]
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.common :as lib.schema.common]
@@ -251,30 +253,88 @@
[:lib/type [:= :mbql/join]]]]
(into (vec join-path) [:stages (dec (count (:stages join)))]))
-(declare walk-clauses*)
+(declare walk-clause* walk-clauses*)
;;; [[clojure.core.walk]] functions generally have the form `(walk f x)` but reversing the args is more natural and
;;; lets you use these functions in `->` or with things like [[update]]. I went back and forth on this but decided
;;; this is better -- your BFF Cam
+(defmulti ^:private walk-subclauses-method
+ "Impl for [[walk-clause]]; walk the subclauses of an MBQL clause calling `f` on each one."
+ {:arglists '([clause f])}
+ (fn [clause _f]
+ (lib.dispatch/dispatch-value clause))
+ :hierarchy lib.hierarchy/hierarchy)
+
+(mu/defmethod walk-subclauses-method :default
+ [clause f]
+ (let [[tag opts & subclauses] clause
+ subclauses' (walk-clauses* subclauses f)]
+ (when-not (= subclauses' subclauses)
+ (into [tag opts] subclauses'))))
+
+;; `:case` and `:if` have the same (messed up/weird) syntax.
+(lib.hierarchy/derive :case ::case)
+(lib.hierarchy/derive :if ::case)
+
+(mu/defmethod walk-subclauses-method ::case
+ [[tag opts if-then-pairs default :as clause] f]
+ (let [if-then-pairs' (mapv (fn [[if-expr then-expr]]
+ [(walk-clause* if-expr f) (walk-clause* then-expr f)])
+ if-then-pairs)]
+ (case (count clause)
+ ;; no default value
+ 3
+ [tag opts if-then-pairs']
+ ;; has default value
+ 4
+ (let [default' (walk-clause* default f)]
+ [tag opts if-then-pairs' default']))))
+
+(defn- walk-subclauses [clause f]
+ (let [clause' (walk-subclauses-method clause f)]
+ (cond
+ (nil? clause') clause
+ (= clause' clause) clause
+ :else clause')))
+
+(defn- walk-clause-wrap-f
+ "Wrap `f` so it
+
+ 1. Returns the original value if the wrapped function returns `nil`
+
+ 2. Returns the original value if the wrapped function returns a value that is `=` to it (this is so we can return
+ an [[identical?]] clause if `f` does not make any changes)."
+ [f]
+ (fn f* [clause]
+ (let [clause' (f clause)]
+ (cond
+ (nil? clause') clause
+ (= clause' clause) clause
+ :else clause'))))
+
+(defn- walk-clause* [clause f]
+ (if-not (lib.util/clause? clause)
+ ;; not a clause -- an atomic value like a number or string literal. Call `f` but do not recurse.
+ (f clause)
+ ;; MBQL clause -- recurse into subclauses first then call `f` on the result.
+ (let [clause' (walk-subclauses clause f)]
+ (f clause'))))
+
(mu/defn walk-clause
"Impl for [[walk-clauses]]. You can call this directly if you are a psycho who needs to walk some clauses but don't
have `query` for some
reason (e.g. [[metabase.query-processor.middleware.wrap-value-literals/wrap-value-literals-in-mbql]]).
- Walks `clause` in a depth-first manner and calls
+ Walks `clause` in a depth-first postorder manner and calls
(f clause)
- on every MBQL clause. (Also includes non-clause arguments like the `1` and `2` in `[:= {} [:field {} 1] 2]`.)"
+ on every MBQL subclause of `clause`, then on `clause` itself. (Also includes non-clause arguments like the `1` and
+ `2` in `[:= {} [:field {} 1] 2]`.)"
[clause :- :any
f :- [:=> [:cat :any] :any]]
- (or (when (lib.util/clause? clause)
- (let [[tag opts & subclauses] clause
- subclauses' (walk-clauses* subclauses f)]
- (when-not (= subclauses' subclauses)
- (into [tag opts] subclauses'))))
- clause))
+ (walk-clause* clause (walk-clause-wrap-f f)))
(mu/defn walk-clauses*
"Impl for [[walk-clauses]].
@@ -291,13 +351,11 @@
(when clauses
(reduce
(fn [clauses i]
- (let [clause (nth clauses i)
- clause' (walk-clause clause f)
- clause'' (or (f clause')
- clause')]
- (if (= clause'' clause)
+ (let [clause (nth clauses i)
+ clause' (walk-clause clause f)]
+ (if (= clause' clause)
clauses
- (assoc (vec clauses) i clause''))))
+ (assoc (vec clauses) i clause'))))
clauses
(range (count clauses)))))
diff --git a/src/metabase/parameters/chain_filter.clj b/src/metabase/parameters/chain_filter.clj
index b1695b91be2..8bef8d2da48 100644
--- a/src/metabase/parameters/chain_filter.clj
+++ b/src/metabase/parameters/chain_filter.clj
@@ -138,7 +138,7 @@
{:base-type base_type})
(when-not (= this-field-table-id source-table-id)
{:join-alias (joined-table-alias this-field-table-id)}))])]
- (if (and (types/temporal-field? field-metadata)
+ (if (and #_{:clj-kondo/ignore [:deprecated-var]} (types/temporal-field? field-metadata) ; legacy usage -- do not use going forward
(string? value))
(u/ignore-exceptions
(params.dates/date-string->filter value field-id))
diff --git a/src/metabase/query_processor/middleware/auto_parse_filter_values.clj b/src/metabase/query_processor/middleware/auto_parse_filter_values.clj
index c91b8454c0d..d878cdba89d 100644
--- a/src/metabase/query_processor/middleware/auto_parse_filter_values.clj
+++ b/src/metabase/query_processor/middleware/auto_parse_filter_values.clj
@@ -2,9 +2,10 @@
"Middleware that parses filter clause values that come in as strings (e.g. from the API) to the appropriate type. E.g.
a String value in a filter clause against a `:type/Integer` Field should get parsed into an integer.
- Note that logic for automatically parsing temporal values lives in the `wrap-values-literals` middleware for
- historic reasons. When time permits it should be moved into this middleware since it's really a separate
- transformation from wrapping the value literals themselves."
+ Note that logic for automatically parsing temporal values lives in
+ the [[metabase.query-processor.middleware.wrap-value-literals]] middleware for historic reasons. When time permits
+ it should be moved into this middleware since it's really a separate transformation from wrapping the value literals
+ themselves."
(:require
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.common :as lib.schema.common]
@@ -37,17 +38,17 @@
e)))))
;;; I guess we probably want this to work on join conditions as well as normal stage filters.
-(defn- auto-parse-filter-values-this-stage-or-join
- [_query _path-type _path stage-or-join]
- (lib.util.match/replace stage-or-join
+(defn- auto-parse-filter-values-in-clause
+ [_query _path-type _path clause]
+ (lib.util.match/match-lite clause
[:value
- (info :guard (fn [{:keys [effective-type], :as _value-options}]
+ (opts :guard (fn [{:keys [effective-type], :as _value-options}]
(and effective-type
(not (isa? effective-type :type/Text)))))
(v :guard string?)]
- [:value info (parse-value-for-base-type v (:effective-type info))]))
+ [:value opts (parse-value-for-base-type v (:effective-type opts))]))
(mu/defn auto-parse-filter-values :- ::lib.schema/query
"Automatically parse String filter clause values to the appropriate type."
[query :- ::lib.schema/query]
- (lib.walk/walk query auto-parse-filter-values-this-stage-or-join))
+ (lib.walk/walk-clauses query auto-parse-filter-values-in-clause))
diff --git a/src/metabase/query_processor/middleware/wrap_value_literals.clj b/src/metabase/query_processor/middleware/wrap_value_literals.clj
index cd9f2e1153f..a7f17420987 100644
--- a/src/metabase/query_processor/middleware/wrap_value_literals.clj
+++ b/src/metabase/query_processor/middleware/wrap_value_literals.clj
@@ -4,87 +4,47 @@
(:require
[clojure.string :as str]
[java-time.api :as t]
- [metabase.legacy-mbql.schema :as mbql.s]
- [metabase.legacy-mbql.util :as mbql.u]
+ [metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.schema.expression :as lib.schema.expression]
+ [metabase.lib.types.isa :as lib.types.isa]
+ [metabase.lib.util :as lib.util]
[metabase.lib.util.match :as lib.util.match]
+ [metabase.lib.walk :as lib.walk]
[metabase.query-processor.error-type :as qp.error-type]
[metabase.query-processor.store :as qp.store]
[metabase.query-processor.timezone :as qp.timezone]
- [metabase.types.core :as types]
- [metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.i18n :as i18n]
- [metabase.util.malli :as mu]
- [metabase.util.performance :as perf])
+ [metabase.util.malli :as mu])
(:import
(java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)))
-;;; --------------------------------------------------- Type Info ----------------------------------------------------
-
-(def ^:private ^:dynamic *inner-query*
- "To be bound in [[metabase.query-processor.middleware.wrap-value-literals/wrap-value-literals-in-mbql-query]].
- Original motivation is to provide metadata required for computation of _type info_. See the
- [[metabase.query-processor.middleware.wrap-value-literals/str-id-field->type-info]] docstring for details."
- nil)
-
-(defmulti ^:private type-info
- "Get information about database, base, and semantic types for an object. This is passed to along to various
- `->honeysql` method implementations so drivers have the information they need to handle raw values like Strings,
- which may need to be parsed as a certain type."
- {:arglists '([field-clause])}
- mbql.u/dispatch-by-clause-name-or-class)
-
-(defmethod type-info :default [_] nil)
-
-(defmethod type-info :metadata/column
- [field]
- ;; Opts should probably override all of these
- (-> (select-keys field [:base-type :effective-type :coercion-strategy :semantic-type :database-type :name])
- (perf/update-keys u/->snake_case_en)))
-
-(defn- str-id-field->type-info
- "Return _type info_ for `_field` with string `field-name`, coming from the source query or joins."
- [[_tag field-name {:keys [join-alias] :as _opts} :as _field] inner-query]
- (when (string? field-name)
- ;; Use corresponding source-metadata from joins or `inner-query`.
- (let [source-metadatas (if join-alias
- (some #(when (= join-alias (:alias %))
- (:source-metadata %))
- (:joins inner-query))
- (:source-metadata inner-query))
- [{[_ field-name :as field-ref] :field_ref :as field-metadata}] (filter #(= (:name %) field-name)
- source-metadatas)]
- (-> (if (and field-ref (integer? field-name))
- (type-info field-ref)
- {})
- (merge field-metadata)
- (select-keys [:base_type :effective_type :database_type])))))
-
-(defmethod type-info :field [[_ id-or-name opts :as field]]
- (merge
- ;; With Mlv2 queries, this could be combined with `:expression` below and use the column from the
- ;; query rather than metadata/field
- (if (integer? id-or-name)
- (type-info (lib.metadata/field (qp.store/metadata-provider) id-or-name))
- (str-id-field->type-info field *inner-query*))
- (when (:temporal-unit opts)
- {:unit (:temporal-unit opts)})
- (when (:base-type opts)
- {:base_type (:base-type opts)})
- (when (:effective-type opts)
- {:effective_type (:effective-type opts)})))
-
-(defmethod type-info :expression [[_ _name opts]]
- (merge
- (when (:temporal-unit opts)
- {:unit (:temporal-unit opts)})
- (when (:base-type opts)
- {:base_type (:base-type opts)})
- (when (:effective-type opts)
- {:effective_type (:effective-type opts)})))
+(mu/defn- value :- :mbql.clause/value
+ [info :- :map v]
+ [:value (assoc info :lib/uuid (str (random-uuid))) v])
+
+(defn- type-info-from-col [col]
+ (when col
+ (merge
+ (select-keys col [:coercion-strategy :semantic-type :database-type])
+ (when-let [unit (lib/raw-temporal-bucket col)]
+ {:unit unit}))))
+
+(defn- ^:dynamic *type-info*
+ "This is the type info for the LHS in something like
-;;; ------------------------------------------------- add-type-info --------------------------------------------------
+ [:= {} <lhs> <rhs>]
+
+ usually a `:field` clause; we use this info to wrap `rhs` if it's a raw value e.g. `1`."
+ [query path clause]
+ (merge
+ (when (lib.util/clause-of-type? clause :field)
+ (type-info-from-col (lib.walk/apply-f-for-stage-at-path lib/metadata query path clause)))
+ (let [expr-type (lib.walk/apply-f-for-stage-at-path lib/type-of query path clause)]
+ {:base-type expr-type
+ :effective-type expr-type})))
;; TODO -- parsing the temporal string literals should be moved into `auto-parse-filter-values`, it's really a
;; separate transformation from just wrapping the value
@@ -97,35 +57,31 @@
(defmethod add-type-info nil
[_ info & _]
- [:value nil info])
+ (value info nil))
(defmethod add-type-info Object
[this info & _]
- [:value this info])
+ (value info this))
-(defmethod add-type-info LocalDate
- [this info & _]
- [:absolute-datetime this (get info :unit :default)])
+(derive LocalDate ::->absolute-datetime)
+(derive LocalDateTime ::->absolute-datetime)
+(derive OffsetDateTime ::->absolute-datetime)
+(derive ZonedDateTime ::->absolute-datetime)
-(defmethod add-type-info LocalDateTime
- [this info & _]
- [:absolute-datetime this (get info :unit :default)])
+(prefer-method add-type-info ::->absolute-datetime Object)
-(defmethod add-type-info LocalTime
+(defmethod add-type-info ::->absolute-datetime
[this info & _]
- [:time this (get info :unit :default)])
+ (lib/absolute-datetime this (get info :unit :default)))
-(defmethod add-type-info OffsetDateTime
- [this info & _]
- [:absolute-datetime this (get info :unit :default)])
+(derive LocalTime ::->time)
+(derive OffsetTime ::->time)
-(defmethod add-type-info OffsetTime
- [this info & _]
- [:time this (get info :unit :default)])
+(prefer-method add-type-info ::->time Object)
-(defmethod add-type-info ZonedDateTime
+(defmethod add-type-info ::->time
[this info & _]
- [:absolute-datetime this (get info :unit :default)])
+ (lib/time this (get info :unit :default)))
(defmulti ^:private coerce-temporal
"Coerce temporal value `t` to `target-class`, or throw an Exception if it is an invalid conversion."
@@ -210,27 +166,27 @@
(defmethod parse-temporal-string-literal :default
[_effective-type s target-unit]
(let [t (u.date/parse s (qp.timezone/results-timezone-id))]
- [:absolute-datetime t target-unit]))
+ (lib/absolute-datetime t target-unit)))
(defmethod parse-temporal-string-literal :type/Date
[_effective-type s target-unit]
(let [t (parse-temporal-string-literal-to-class s LocalDate)]
- [:absolute-datetime t target-unit]))
+ (lib/absolute-datetime t target-unit)))
(defmethod parse-temporal-string-literal :type/Time
[_effective-type s target-unit]
(let [t (parse-temporal-string-literal-to-class s LocalTime)]
- [:time t target-unit]))
+ (lib/time t target-unit)))
(defmethod parse-temporal-string-literal :type/TimeWithTZ
[_effective-type s target-unit]
(let [t (parse-temporal-string-literal-to-class s OffsetTime)]
- [:time t target-unit]))
+ (lib/time t target-unit)))
(defmethod parse-temporal-string-literal :type/DateTime
[_effective-type s target-unit]
(let [t (parse-temporal-string-literal-to-class s LocalDateTime)]
- [:absolute-datetime t target-unit]))
+ (lib/absolute-datetime t target-unit)))
(defn- date-literal-string? [s]
(not (str/includes? s "T")))
@@ -242,7 +198,7 @@
(date-literal-string? s))
:day
target-unit)]
- [:absolute-datetime t target-unit]))
+ (lib/absolute-datetime t target-unit)))
(defmethod parse-temporal-string-literal :type/DateTimeWithZoneID
[_effective-type s target-unit]
@@ -251,56 +207,60 @@
:day
target-unit)
t (parse-temporal-string-literal-to-class s ZonedDateTime)]
- [:absolute-datetime t target-unit]))
+ (lib/absolute-datetime t target-unit)))
(defmethod add-type-info String
[s {:keys [unit], :as info} & {:keys [parse-datetime-strings?]
:or {parse-datetime-strings? true}}]
- (if (and (or unit (when info (types/temporal-field? info)))
+ (if (and (or unit (when info (lib.types.isa/temporal? info)))
parse-datetime-strings?
(seq s))
- (let [effective-type ((some-fn :effective_type :base_type) info)]
+ (let [effective-type ((some-fn :effective-type :base-type) info)]
(parse-temporal-string-literal effective-type s (or unit :default)))
- [:value s info]))
+ (value info s)))
;;; -------------------------------------------- wrap-literals-in-clause ---------------------------------------------
-(def ^:private raw-value? (complement mbql.u/mbql-clause?))
+(def ^:private raw-value? (complement lib.util/clause?))
-(defn wrap-value-literals-in-mbql
- "Given a normalized mbql query (important to desugar forms like `[:does-not-contain ...]` -> `[:not [:contains
- ...]]`), walks over the clause and annotates literals with type information.
+(defn- wrap-value-literals-in-clause
+ [query path clause]
+ (lib.util.match/match-lite clause
+ [(tag :guard #{:= :!= :< :> :<= :>=}) opts field (x :guard raw-value?)]
+ [tag opts field (add-type-info x (*type-info* query path field))]
- eg:
+ [:datetime-diff opts (x :guard string?) (y :guard string?) unit]
+ [:datetime-diff opts (add-type-info (u.date/parse x) nil) (add-type-info (u.date/parse y) nil) unit]
- [:not [:contains [:field 13 {:base_type :type/Text}] \"foo\"]]
- ->
- [:not [:contains [:field 13 {:base_type :type/Text}]
- [:value \"foo\" {:base_type :type/Text,
- :semantic_type nil,
- :database_type \"VARCHAR\",
- :name \"description\"}]]]"
- [mbql]
- (lib.util.match/replace mbql
- [(clause :guard #{:= :!= :< :> :<= :>=}) field (x :guard raw-value?)]
- [clause field (add-type-info x (type-info field))]
-
- [:datetime-diff (x :guard string?) (y :guard string?) unit]
- [:datetime-diff (add-type-info (u.date/parse x) nil) (add-type-info (u.date/parse y) nil) unit]
-
- [(clause :guard #{:datetime-add :datetime-subtract :convert-timezone :temporal-extract}) (field :guard string?) & args]
- (into [clause (add-type-info (u.date/parse field) nil)] args)
-
- [:between field (min-val :guard raw-value?) (max-val :guard raw-value?)]
+ [(tag :guard #{:datetime-add :datetime-subtract :convert-timezone :temporal-extract}) opts (field :guard string?) & args]
+ (into [tag opts (add-type-info (u.date/parse field) nil)] args)
+
+ [:between opts field (min-val :guard raw-value?) (max-val :guard raw-value?)]
[:between
+ opts
field
- (add-type-info min-val (type-info field))
- (add-type-info max-val (type-info field))]
+ (add-type-info min-val (*type-info* query path field))
+ (add-type-info max-val (*type-info* query path field))]
- [(clause :guard #{:starts-with :ends-with :contains}) field (s :guard string?) & more]
- (let [s (add-type-info s (type-info field), :parse-datetime-strings? false)]
- (into [clause field s] more))))
+ [(tag :guard #{:starts-with :ends-with :contains}) opts field (s :guard string?) & more]
+ (let [s (add-type-info s (*type-info* query path field), :parse-datetime-strings? false)]
+ (into [tag opts field s] more))))
+(mu/defn wrap-value-literals :- ::lib.schema/query
+ "Middleware that wraps ran value literals in `:value` (for integers, strings, etc.) or `:absolute-datetime` (for
+ datetime strings, etc.) clauses which include info about the Field they are being compared to. This is done mostly
+ to make it easier for drivers to write implementations that rely on multimethod dispatch (by clause name) -- they
+ can dispatch directly off of these clauses."
+ [query :- ::lib.schema/query]
+ (lib.walk/walk-clauses query (fn [query _path-type path clause]
+ (wrap-value-literals-in-clause query path clause))))
+
+;;;
+;;; Tangentially-related nonsense not used by the middleware
+;;;
+
+;;; TODO (Cam 8/22/25) FIXME: This is used in exactly one place: the SQL QP... so why does it live in a QP middleware
+;;; namespace? Nobody knows.
(defn unwrap-value-literal
"Extract value literal from `:value` form or returns form as is if not a `:value` form."
[maybe-value-form]
@@ -308,19 +268,48 @@
[:value x & _] x
_ &match))
-(defn ^:private wrap-value-literals-in-mbql-query
- [{:keys [source-query], :as inner-query} options]
- (let [inner-query (cond-> inner-query
- source-query (update :source-query wrap-value-literals-in-mbql-query options))]
- (binding [*inner-query* inner-query]
- (wrap-value-literals-in-mbql inner-query))))
+(defn- type-info-no-query
+ "This is like [[type-info*]] but specifically for supporting the legacy/deprecated [[wrap-value-literals-in-mbql]]
+ function."
+ {:deprecated "0.57.0"}
+ [clause]
+ (let [expr-type (lib.schema.expression/type-of clause)]
+ (merge
+ (when (and (lib.util/clause-of-type? clause :field)
+ (qp.store/initialized?))
+ (let [[_tag _opts id-or-name] clause]
+ (when (pos-int? id-or-name)
+ (type-info-from-col (lib.metadata/field (qp.store/metadata-provider) id-or-name)))))
+ (when-let [unit (lib/raw-temporal-bucket clause)]
+ {:unit unit})
+ {:base-type expr-type
+ :effective-type expr-type})))
+
+(mu/defn wrap-value-literals-in-mbql :- [:cat :keyword [:* :any]]
+ "Given a normalized legacy MBQL query (important to desugar forms like `[:does-not-contain ...]` -> `[:not [:contains
+ ...]]`), walks over the clause and annotates literals with type information.
-(mu/defn wrap-value-literals :- mbql.s/Query
- "Middleware that wraps ran value literals in `:value` (for integers, strings, etc.) or `:absolute-datetime` (for
- datetime strings, etc.) clauses which include info about the Field they are being compared to. This is done mostly
- to make it easier for drivers to write implementations that rely on multimethod dispatch (by clause name) -- they
- can dispatch directly off of these clauses."
- [{query-type :type, :as query}]
- (if-not (= query-type :query)
- query
- (update query :query wrap-value-literals-in-mbql-query nil)))
+ eg:
+
+ [:not [:contains [:field 13 {:base_type :type/Text}] \"foo\"]]
+ ->
+ [:not [:contains [:field 13 {:base_type :type/Text}]
+ [:value {:base_type :type/Text, \"foo\"
+ :semantic_type nil,
+ :database_type \"VARCHAR\",
+ :name \"description\"}]]]
+
+ DEPRECATED: This is for legacy compatibility and should not be used in new code."
+ {:deprecated "0.57.0"}
+ [mbql :- [:cat :keyword [:* :any]]]
+ (-> mbql
+ lib/->pMBQL
+ (as-> $mbql (binding [*type-info* (fn [_query _path clause]
+ #_{:clj-kondo/ignore [:deprecated-var]}
+ (type-info-no-query clause))]
+ (-> (lib.walk/walk-clauses*
+ [$mbql]
+ (fn [clause]
+ (wrap-value-literals-in-clause nil nil clause)))
+ first)))
+ lib/->legacy-MBQL))
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index ccaa32ef532..482e7322982 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -131,14 +131,14 @@
;; yes, this is called a second time, because we need to handle any joins that got added
(ensure-legacy #'qp.middleware.enterprise/apply-sandboxing)
(ensure-legacy #'qp.cumulative-aggregations/rewrite-cumulative-aggregations)
- (ensure-legacy #'qp.wrap-value-literals/wrap-value-literals)
+ (ensure-mbql5 #'qp.wrap-value-literals/wrap-value-literals)
(ensure-mbql5 #'auto-parse-filter-values/auto-parse-filter-values)
(ensure-mbql5 #'validate-temporal-bucketing/validate-temporal-bucketing)
(ensure-legacy #'optimize-temporal-filters/optimize-temporal-filters)
(ensure-mbql5 #'limit/add-default-limit)
(ensure-legacy #'qp.middleware.enterprise/apply-download-limit)
(ensure-legacy #'check-features/check-features)
- ;; return pMBQL at the end
+ ;; return MBQL 5 at the end
(ensure-mbql5 identity)])
(defn- middleware-fn-name [middleware-fn]
diff --git a/src/metabase/types/core.cljc b/src/metabase/types/core.cljc
index 7aad9a7d9dd..5c6ced78637 100644
--- a/src/metabase/types/core.cljc
+++ b/src/metabase/types/core.cljc
@@ -54,7 +54,8 @@
[[metabase.util :as u]])
[clojure.set :as set]
[metabase.types.coercion-hierarchies :as coercion-hierarchies]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]))
;;; Table (entity) Types
@@ -373,7 +374,7 @@
;;; ---------------------------------------------------- Util Fns ----------------------------------------------------
-(def ^:private SnakeCasedField
+(mr/def ::snake-cased-type-info
"E.g. the version coming back from the app DB as opposed to MLv2 metadata. This should eventually be considered
deprecated."
[:map
@@ -381,15 +382,23 @@
(mu/defn field-is-type?
"True if a Metabase `Field` instance has a temporal base or semantic type, i.e. if this Field represents a value
- relating to a moment in time."
+ relating to a moment in time.
+
+ DEPRECATED: Prefer MBQL 5 + [[metabase.lib.schema.expression/type-of]] (if you only have the clause)
+ or [[metabase.lib.metadata.calculation/type-of]] (if you have the query and stage number as well) going forward."
+ {:deprecated "0.57.0"}
[tyype :- :keyword
- {base-type :base_type, effective-type :effective_type} :- SnakeCasedField]
+ {base-type :base_type, effective-type :effective_type} :- ::snake-cased-type-info]
(some #(isa? % tyype) [base-type effective-type]))
(mu/defn temporal-field?
"True if a Metabase `Field` instance has a temporal base or semantic type, i.e. if this Field represents a value
- relating to a moment in time."
- [field :- SnakeCasedField]
+ relating to a moment in time.
+
+ DEPRECATED: Prefer using MBQL 5 + [[metabase.lib.types.isa/temporal?]] going forward."
+ {:deprecated "0.57.0"}
+ [field :- ::snake-cased-type-info]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(field-is-type? :type/Temporal field))
(def ^:private assignable-hierarchy
diff --git a/test/metabase/driver/sql/query_processor_test_util.clj b/test/metabase/driver/sql/query_processor_test_util.clj
index 3f675936e1f..a40bf7e2cb1 100644
--- a/test/metabase/driver/sql/query_processor_test_util.clj
+++ b/test/metabase/driver/sql/query_processor_test_util.clj
@@ -7,7 +7,8 @@
[metabase.query-processor.compile :as qp.compile]
[metabase.test.data.env :as tx.env]
[metabase.test.data.interface :as tx]
- [metabase.util :as u]))
+ [metabase.util :as u]
+ [metabase.util.malli :as mu]))
(set! *warn-on-reflection* true)
@@ -101,7 +102,9 @@
query))
([_driver query]
- (qp.compile/compile query)))
+ ;; for performance in tests: disable Malli validation.
+ (mu/disable-enforcement
+ (qp.compile/compile query))))
(def ^{:arglists '([query] [driver query])} query->sql
"Compile an MBQL query to 'pretty' SQL (i.e., remove quote marks and `public.` qualifiers)."
diff --git a/test/metabase/lib/convert_test.cljc b/test/metabase/lib/convert_test.cljc
index 8ac8eec3bf0..e21163fd41a 100644
--- a/test/metabase/lib/convert_test.cljc
+++ b/test/metabase/lib/convert_test.cljc
@@ -268,11 +268,11 @@
(is (= original
(lib.convert/->legacy-MBQL (lib.convert/->pMBQL original))))))
-(defn- test-round-trip [query]
- (testing (str "original =\n" (u/pprint-to-str query))
- (let [converted (lib.convert/->pMBQL query)]
- (testing (str "\npMBQL =\n" (u/pprint-to-str converted))
- (is (= query
+(defn- test-round-trip [x]
+ (testing (str "original =\n" (u/pprint-to-str x))
+ (let [converted (lib.convert/->pMBQL x)]
+ (testing (str "\nMBQL 5 =\n" (u/pprint-to-str converted))
+ (is (= x
(lib.convert/->legacy-MBQL converted)))))))
(deftest ^:parallel round-trip-test
@@ -414,7 +414,7 @@
(deftest ^:parallel round-trip-literal-expression-test
;; Some cases of literal expressions are already covered in round-trip-test, above.
- (are [query] (test-round-trip query)
+ (are [x] (test-round-trip x)
[:value false {:base_type :type/Boolean}]
[:value true nil]
diff --git a/test/metabase/lib/equality_test.cljc b/test/metabase/lib/equality_test.cljc
index b7c8a2d2f97..44e5b594abc 100644
--- a/test/metabase/lib/equality_test.cljc
+++ b/test/metabase/lib/equality_test.cljc
@@ -772,7 +772,6 @@
:lib/desired-column-alias "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]
:lib/source :source/previous-stage
:lib/source-column-alias "CREATED_AT"
:lib/source-uuid "aa4324c7-12d2-46fe-ba8d-8f1fe54b61af"
@@ -793,7 +792,6 @@
:lib/desired-column-alias "CREATED_AT_2"
: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]
:lib/source :source/previous-stage
:lib/source-column-alias "CREATED_AT_2"
:lib/source-uuid "1f16a57a-2afd-4c92-8d6c-b41062235a49"
diff --git a/test/metabase/lib/field/resolution_test.cljc b/test/metabase/lib/field/resolution_test.cljc
index f4b08bf8d3d..46e6455b561 100644
--- a/test/metabase/lib/field/resolution_test.cljc
+++ b/test/metabase/lib/field/resolution_test.cljc
@@ -386,7 +386,7 @@
:strategy :left-join
:fk-field-id %category-id}]}))
col (lib.field.resolution/resolve-field-ref query -1 (first (lib/fields query -1)))]
- (is (=? {:lib/original-ref [:field {:join-alias "Category"} pos-int?]}
+ (is (=? {:lib/original-ref-for-result-metadata-purposes-only [:field {:join-alias "Category"} pos-int?]}
col))
(is (=? [:field
{:lib/uuid string?
@@ -1325,7 +1325,7 @@
query
-1
[:field {:base-type :type/BigInteger, :lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :products :id)])
- (dissoc :lib/original-ref :lib/original-display-name))
+ (dissoc :lib/original-ref-for-result-metadata-purposes-only :lib/original-display-name))
(lib.field.resolution/resolve-field-ref
query
-1
diff --git a/test/metabase/lib/field_test.cljc b/test/metabase/lib/field_test.cljc
index 9c5867639b6..1a5ae0d3a8d 100644
--- a/test/metabase/lib/field_test.cljc
+++ b/test/metabase/lib/field_test.cljc
@@ -1284,8 +1284,10 @@
col (lib/visible-columns query)
:let [col-ref (lib/ref col)]]
(testing (str "ref " col-ref " of " (symbol query-var))
- (is (= (dissoc col :lib/source-uuid :lib/original-ref)
- (dissoc (lib/find-visible-column-for-ref query col-ref) :lib/source-uuid :lib/original-ref)))))))
+ (is (= (-> col
+ (dissoc :lib/source-uuid :lib/original-ref-for-result-metadata-purposes-only))
+ (-> (lib/find-visible-column-for-ref query col-ref)
+ (dissoc :lib/source-uuid :lib/original-ref-for-result-metadata-purposes-only))))))))
(deftest ^:parallel find-visible-column-for-ref-test-2
(testing "reference by ID instead of name"
diff --git a/test/metabase/lib/filter_test.cljc b/test/metabase/lib/filter_test.cljc
index 04e5ef51168..cdc9e42797a 100644
--- a/test/metabase/lib/filter_test.cljc
+++ b/test/metabase/lib/filter_test.cljc
@@ -973,3 +973,14 @@
{:lib/uuid "00000000-0000-0000-0000-000000000004"}
[:= {:lib/uuid "00000000-0000-0000-0000-000000000005"} 7 8]
[:= {:lib/uuid "00000000-0000-0000-0000-000000000006"} 9 10]]]]}))))
+
+(deftest ^:parallel filter-display-name-for-year-bucketing-test
+ (let [query (lib/native-query meta/metadata-provider "SELECT * FROM ORDERS;")]
+ (is (= "Created At is Jan 1 – Dec 31, 2023"
+ (lib/display-name query [:= {:lib/uuid "79e513f8-af80-4c15-96b6-e72eff7f37cc"}
+ [:field {:effective-type :type/Integer
+ :base-type :type/DateTime
+ :temporal-unit :year
+ :lib/uuid "1fe5dc66-54af-4368-9e4a-1e64a1fbe484"}
+ "CREATED_AT"]
+ "2023-01-01T00:00:00Z"])))))
diff --git a/test/metabase/lib/walk_test.cljc b/test/metabase/lib/walk_test.cljc
index 085468beb89..ea6732f5577 100644
--- a/test/metabase/lib/walk_test.cljc
+++ b/test/metabase/lib/walk_test.cljc
@@ -6,6 +6,7 @@
[metabase.lib.core :as lib]
[metabase.lib.test-metadata :as meta]
[metabase.lib.walk :as lib.walk]
+ [metabase.util :as u]
[metabase.util.malli.registry :as mr]))
#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))
@@ -233,3 +234,65 @@
;; check that we support `f` returning no clause (treat this the same as returning the original clause)
(constantly nil)]]
(is (identical? query (lib.walk/walk-clauses query f)))))))
+
+(deftest ^:parallel walk-clauses-case-test
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :checkins))
+ (lib/aggregate (lib/sum (lib/case [[(lib/between
+ (meta/field-metadata :checkins :date)
+ "2018-09-01"
+ "2018-09-30")
+ false]]
+ false))))]
+ (testing "No changes should return the original query (same object)"
+ (is (identical? query
+ (lib.walk/walk-clauses query (constantly nil)))))
+ (let [calls (atom [])]
+ (is (=? [:SUM {}
+ [:CASE {}
+ [[[:BETWEEN {}
+ [:FIELD {} pos-int?]
+ "2018-09-01"
+ "2018-09-30"]
+ false]]
+ false]]
+ (-> query
+ (lib.walk/walk-clauses
+ (fn [_query _path-type _stage-or-join-path clause]
+ (swap! calls conj clause)
+ (when (vector? clause)
+ (update clause 0 (comp keyword u/upper-case-en name)))))
+ :stages
+ first
+ :aggregation
+ first)))
+ (is (=? [;; sum => case => if-then-pairs => if expr (between) => field => arg
+ (meta/id :checkins :date)
+ ;; sum => case => if-then-pairs => if expr (between) => field
+ [:field {} (meta/id :checkins :date)]
+ ;; sum => case => if-then-pairs => if expr (between) => other args
+ "2018-09-01"
+ "2018-09-30"
+ ;; sum => case => if-then-pairs => if expr (between)
+ [:between {} [:FIELD {} (meta/id :checkins :date)] "2018-09-01" "2018-09-30"]
+ ;; sum => case => if-then-pairs => then expr (false)
+ false
+ ;; sum => case => default
+ false
+ ;; sum => case
+ [:case {}
+ [[[:BETWEEN {}
+ [:FIELD {} pos-int?]
+ "2018-09-01"
+ "2018-09-30"]
+ false]]
+ false]
+ ;; sum
+ [:sum {}
+ [:CASE {}
+ [[[:BETWEEN {}
+ [:FIELD {} pos-int?]
+ "2018-09-01"
+ "2018-09-30"]
+ false]]
+ false]]]
+ @calls)))))
diff --git a/test/metabase/query_processor/middleware/auto_bucket_datetimes_test.clj b/test/metabase/query_processor/middleware/auto_bucket_datetimes_test.clj
index 15bdf43a024..d59733fb522 100644
--- a/test/metabase/query_processor/middleware/auto_bucket_datetimes_test.clj
+++ b/test/metabase/query_processor/middleware/auto_bucket_datetimes_test.clj
@@ -216,11 +216,11 @@
(deftest ^:parallel auto-bucket-by-effective-type-test
(testing "UNIX timestamps should be considered to be :type/DateTime based on effective type"
(qp.store/with-metadata-provider unix-timestamp-metadata-provider
- (is (= {:source-table 1
- :breakout [[:field 1 {:temporal-unit :day}]]}
- (auto-bucket-mbql
- {:source-table 1
- :breakout [[:field 1 nil]]}))))))
+ (is (=? {:source-table 1
+ :breakout [[:field 1 {:temporal-unit :day}]]}
+ (auto-bucket-mbql
+ {:source-table 1
+ :breakout [[:field 1 nil]]}))))))
(deftest ^:parallel ignore-native-queries-test
(testing "do native queries pass thru unchanged?"
diff --git a/test/metabase/query_processor/middleware/wrap_value_literals_test.clj b/test/metabase/query_processor/middleware/wrap_value_literals_test.clj
index 2916e5781a2..78aea2688ae 100644
--- a/test/metabase/query_processor/middleware/wrap_value_literals_test.clj
+++ b/test/metabase/query_processor/middleware/wrap_value_literals_test.clj
@@ -23,24 +23,23 @@
(wrap-value-literals query "UTC"))
([query ^String timezone-id]
- (letfn [(thunk []
+ (letfn [(f [query]
(mt/with-results-timezone-id timezone-id
(qp.wrap-value-literals/wrap-value-literals query)))]
- (if (qp.store/initialized?)
- (thunk)
- (qp.store/with-metadata-provider meta/metadata-provider
- (thunk))))))
+ (if (:lib/type query)
+ (f query)
+ (let [mp meta/metadata-provider]
+ (-> (lib/query mp query)
+ f
+ lib/->legacy-MBQL))))))
(deftest ^:parallel wrap-integers-test
(is (= (lib.tu.macros/mbql-query venues
{:filter [:>
$id
- [:value 50 {:base_type :type/BigInteger
- :effective_type :type/BigInteger
- :coercion_strategy nil
- :semantic_type :type/PK
- :database_type "BIGINT"
- :name "ID"}]]})
+ [:value 50 {:base_type :type/BigInteger
+ :semantic_type :type/PK
+ :database_type "BIGINT"}]]})
(wrap-value-literals
(lib.tu.macros/mbql-query venues
{:filter [:> $id 50]})))))
@@ -48,18 +47,12 @@
(deftest ^:parallel wrap-integers-test-2
(is (= (lib.tu.macros/mbql-query venues
{:filter [:and
- [:> $id [:value 50 {:base_type :type/BigInteger
- :effective_type :type/BigInteger
- :coercion_strategy nil
- :semantic_type :type/PK
- :database_type "BIGINT"
- :name "ID"}]]
- [:< $price [:value 5 {:base_type :type/Integer
- :effective_type :type/Integer
- :coercion_strategy nil
- :semantic_type :type/Category
- :database_type "INTEGER"
- :name "PRICE"}]]]})
+ [:> $id [:value 50 {:base_type :type/BigInteger
+ :semantic_type :type/PK
+ :database_type "BIGINT"}]]
+ [:< $price [:value 5 {:base_type :type/Integer
+ :semantic_type :type/Category
+ :database_type "INTEGER"}]]]})
(wrap-value-literals
(lib.tu.macros/mbql-query venues
{:filter [:and
@@ -72,8 +65,8 @@
(is (= (qp.timezone/results-timezone-id)
timezone-id)
"Make sure `results-timezone-id` is returning the bound value")
- (second (#'qp.wrap-value-literals/add-type-info datetime-str
- {:unit :day})))))
+ (-> (#'qp.wrap-value-literals/add-type-info datetime-str {:unit :day})
+ (nth 2)))))
(deftest parse-datetime-literal-strings-test
(doseq [[timezone expected] {"UTC" (t/zoned-date-time "2018-10-01T00:00:00Z[UTC]")
@@ -131,41 +124,44 @@
:coercion-strategy :Coercion/UNIXSeconds->DateTime}]}))
(deftest ^:parallel wrap-datetime-literal-strings-test-4
- (qp.store/with-metadata-provider unix-timestamp-metadata-provider
- (is (= (:query
- (lib.tu.macros/mbql-query checkins
- {:filter [:and
- [:>
- !day.date
- [:absolute-datetime (t/offset-date-time "2015-06-01T00:00Z") :day]]
- [:<
- !day.date
- [:absolute-datetime (t/offset-date-time "2015-06-03T00:00:00Z") :day]]]}))
- (:query
- (wrap-value-literals
- (lib.tu.macros/mbql-query checkins
- {:filter [:and
- [:> !day.date "2015-06-01"]
- [:< !day.date "2015-06-03"]]}))))
- "should also apply if the Fields are UNIX timestamps or other things with semantic type of :type/DateTime")))
+ (is (=? {:filters [[:>
+ {}
+ [:field {:temporal-unit :day} (meta/id :checkins :date)]
+ [:absolute-datetime {} (t/offset-date-time "2015-06-01T00:00Z") :day]]
+ [:<
+ {}
+ [:field {:temporal-unit :day} (meta/id :checkins :date)]
+ [:absolute-datetime {} (t/offset-date-time "2015-06-03T00:00:00Z") :day]]]}
+ (-> (lib/query
+ unix-timestamp-metadata-provider
+ (lib.tu.macros/mbql-query checkins
+ {:filter [:and
+ [:> !day.date "2015-06-01"]
+ [:< !day.date "2015-06-03"]]}))
+ wrap-value-literals
+ :stages
+ first))
+ "should also apply if the Fields are UNIX timestamps or other things with semantic type of :type/DateTime"))
(deftest ^:parallel wrap-datetime-literal-strings-test-5
(qp.store/with-metadata-provider unix-timestamp-metadata-provider
- (is (= (:query
- (lib.tu.macros/mbql-query checkins
- {:filter [:and
- [:>
- !day.date
- [:absolute-datetime (t/offset-date-time "2015-06-01T00:00Z") :day]]
- [:<
- !day.date
- [:absolute-datetime (t/offset-date-time "2015-06-03T00:00:00Z") :day]]]}))
- (:query
- (wrap-value-literals
- (lib.tu.macros/mbql-query checkins
- {:filter [:and
- [:> !day.date "2015-06-01"]
- [:< !day.date "2015-06-03"]]}))))
+ (is (=? {:filters [[:>
+ {}
+ [:field {:temporal-unit :day} (meta/id :checkins :date)]
+ [:absolute-datetime {} (t/offset-date-time "2015-06-01T00:00Z") :day]]
+ [:<
+ {}
+ [:field {:temporal-unit :day} (meta/id :checkins :date)]
+ [:absolute-datetime {} (t/offset-date-time "2015-06-03T00:00:00Z") :day]]]}
+ (-> (lib/query
+ unix-timestamp-metadata-provider
+ (lib.tu.macros/mbql-query checkins
+ {:filter [:and
+ [:> !day.date "2015-06-01"]
+ [:< !day.date "2015-06-03"]]}))
+ wrap-value-literals
+ :stages
+ first))
"should also apply if the Fields are UNIX timestamps or other things with semantic type of :type/DateTime")))
(deftest wrap-datetime-literal-strings-test-6
@@ -189,13 +185,9 @@
(is (= (lib.tu.macros/mbql-query checkins
{:filter [:starts-with
!month.date
- [:value "2018-10-01" {:base_type :type/Date
- :effective_type :type/Date
- :coercion_strategy nil
- :semantic_type nil
- :database_type "DATE"
- :unit :month
- :name "DATE"}]]})
+ [:value "2018-10-01" {:base_type :type/Date
+ :database_type "DATE"
+ :unit :month}]]})
(wrap-value-literals
(lib.tu.macros/mbql-query checkins
{:filter [:starts-with !month.date "2018-10-01"]}))))))
@@ -235,16 +227,12 @@
(deftest ^:parallel base-type-test
(testing "Make sure base-type from `:field` w/ name is picked up correctly"
- (is (= {:order-by [[:asc [:field "A" {:base-type :type/Text}]]]
- :filter [:not [:starts-with
- [:field "A" {:base-type :type/Text}]
- [:value "f" {:base_type :type/Text}]]]
- :source-query {:native "select 'foo' as a union select null as a union select 'bar' as a"}}
- (#'qp.wrap-value-literals/wrap-value-literals-in-mbql-query
- {:order-by [[:asc [:field "A" {:base-type :type/Text}]]],
- :filter [:not [:starts-with [:field "A" {:base-type :type/Text}] "f"]],
- :source-query {:native "select 'foo' as a union select null as a union select 'bar' as a"}}
- nil)))))
+ (is (= [:not [:starts-with
+ [:field "A" {:base-type :type/Text}]
+ [:value "f" {:base_type :type/Text}]]]
+ #_{:clj-kondo/ignore [:deprecated-var]}
+ (qp.wrap-value-literals/wrap-value-literals-in-mbql
+ [:not [:starts-with [:field "A" {:base-type :type/Text}] "f"]])))))
(deftest ^:parallel parse-temporal-string-literals-based-on-column-effective-type-test
(testing "Temporal string literals should be parsed to different things based on the effective type of the target column (#39769)"
@@ -265,14 +253,14 @@
:base-type :type/Text
:coercion-strategy :Coercion/UNIXSeconds->DateTime
:effective-type column-type}]})
- (is (= {:filter [:=
- [:field (meta/id :checkins :date) {:base-type :type/Text, :effective-type column-type}]
- expected]}
- (#'qp.wrap-value-literals/wrap-value-literals-in-mbql-query
- {:filter [:=
- [:field (meta/id :checkins :date) {:base-type :type/Text, :effective-type column-type}]
- "2024-03-20T15:24:00-07:00[US/Pacific]"]}
- nil)))))))))
+ (is (= [:=
+ [:field (meta/id :checkins :date) {:base-type :type/Text, :effective-type column-type}]
+ expected]
+ #_{:clj-kondo/ignore [:deprecated-var]}
+ (qp.wrap-value-literals/wrap-value-literals-in-mbql
+ [:=
+ [:field (meta/id :checkins :date) {:base-type :type/Text, :effective-type column-type}]
+ "2024-03-20T15:24:00-07:00[US/Pacific]"])))))))))
(deftest ^:parallel expression-test
(testing "Value literals compared to :expression refs should get wrapped. Should give date literal strings :day bucketing (#17807)"
@@ -365,3 +353,13 @@
qp.preprocess/preprocess
lib/->legacy-MBQL
wrap-value-literals)))))
+
+(deftest ^:parallel wrap-value-literals-in-mbql-test
+ (is (= [:!=
+ [:field 1 {:base-type :type/Date, :temporal-unit :month-of-year}]
+ [:absolute-datetime #t "2016-01-01" :month-of-year]]
+ #_{:clj-kondo/ignore [:deprecated-var]}
+ (#'qp.wrap-value-literals/wrap-value-literals-in-mbql
+ [:!=
+ [:field 1 {:base-type :type/Date, :temporal-unit :month-of-year}]
+ "2016-01-01"]))))
diff --git a/test/metabase/query_processor/preprocess_test.clj b/test/metabase/query_processor/preprocess_test.clj
index 2dbae0ee178..d4bb99f7d5c 100644
--- a/test/metabase/query_processor/preprocess_test.clj
+++ b/test/metabase/query_processor/preprocess_test.clj
@@ -430,7 +430,7 @@
[:field (meta/id :checkins :id)
{:base-type :type/BigInteger, :join-alias "CH"}]]}]
:filter [:=
- [:field (meta/id :venues :price) {:base-type :type/Text
+ [:field (meta/id :venues :price) {:base-type :type/Integer
:source-field (meta/id :checkins :venue-id)
:source-field-join-alias "CH"}]
"1234"]}))]
diff --git a/test/metabase/query_processor/util/add_alias_info_test.clj b/test/metabase/query_processor/util/add_alias_info_test.clj
index d8a281febf2..3e619e5db18 100644
--- a/test/metabase/query_processor/util/add_alias_info_test.clj
+++ b/test/metabase/query_processor/util/add_alias_info_test.clj
@@ -183,9 +183,8 @@
:filter [:!=
[:field %date {::add/source-table $$checkins
::add/source-alias "DATE"}]
- [:value nil {:base_type :type/Date
- :database_type "DATE"
- :name "DATE"}]]})
+ [:value nil {:base_type :type/Date
+ :database_type "DATE"}]]})
(add-alias-info
(lib.tu.macros/mbql-query checkins
{:aggregation [[:count]]
@@ -292,7 +291,6 @@
::add/source-alias "P2__CATEGORY"}]
[:value 1 {:base_type :type/Text
:database_type "CHARACTER VARYING"
- :name "CATEGORY"
:semantic_type :type/Category}]]}]
:fields [[:field %products.category {:join-alias "Q2"
::add/source-table "Q2"
@@ -422,9 +420,9 @@
::add/source-table $$orders}]
[:field
%products.id
- {::add/source-alias "ID"
- ::add/source-table "Products_Renamed"
- :join-alias "Products Renamed"}]]
+ {::add/source-alias "ID"
+ ::add/source-table "Products_Renamed"
+ :join-alias "Products Renamed"}]]
:strategy :left-join}]
:expressions {"CC" [:+ 1 1]}
:fields
@@ -440,14 +438,13 @@
[:field
%products.category
{::add/source-alias "CATEGORY"
- ::add/source-table "Products_Renamed"
+ ::add/source-table "Products_Renamed"
:join-alias "Products Renamed"}]
[:value
"Doohickey"
- {:base_type :type/Text
- :database_type "CHARACTER VARYING"
- :name "CATEGORY"
- :semantic_type :type/Category}]]}
+ {:base_type :type/Text
+ :database_type "CHARACTER VARYING"
+ :semantic_type :type/Category}]]}
:fields [[:field
%products.id
{::add/desired-alias "Products_Renamed__ID"
diff --git a/test/metabase/query_processor_test/cast_test.clj b/test/metabase/query_processor_test/cast_test.clj
index ee9071c1371..f698d149edb 100644
--- a/test/metabase/query_processor_test/cast_test.clj
+++ b/test/metabase/query_processor_test/cast_test.clj
@@ -1,4 +1,13 @@
(ns ^:mb/driver-tests metabase.query-processor-test.cast-test
+ {:clj-kondo/config '{:linters
+ ;; this is actually ok here since this is a drivers namespace
+ {:discouraged-namespace {metabase.query-processor.store {:level :off}}
+ ;; there are several legacy usages of `field-is-type?` here, and I don't really want to add
+ ;; clj-kondo/ignores to all of them... so this will take care of it. We do still want to remove
+ ;; them soon.
+ :deprecated-var {:exclude {metabase.types.core/field-is-type? {:namespaces ["metabase\\.query-processor-test\\.cast-test"]}}}
+ ;; this is also ok here since this is a drivers namespace
+ :discouraged-var {metabase.lib.core/->legacy-MBQL {:level :off}}}}}
(:require
[clojure.string :as str]
[clojure.test :refer :all]
diff --git a/test/metabase/query_processor_test/coercion_test.clj b/test/metabase/query_processor_test/coercion_test.clj
index 2175fdb3de4..e80c32bf1d1 100644
--- a/test/metabase/query_processor_test/coercion_test.clj
+++ b/test/metabase/query_processor_test/coercion_test.clj
@@ -75,6 +75,8 @@
(biginteger coerced-number))))))))))
(defn- date-type? [col]
+ ;; legacy usage -- do not use going forward
+ #_{:clj-kondo/ignore [:deprecated-var]}
(some #(types/field-is-type? % col) [:type/DateTime ;; some databases return datetimes for date (e.g., Oracle)
:type/Text ;; sqlite uses text :(
:type/Date]))