Skip to content

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

validate-temporal-bucketing middleware => Lib (#62632)

Cam Saula941f1d9c2f6
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index c1c1ec590b7..63fecf1f7a8 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -173,7 +173,6 @@
metabase.driver.sql-jdbc.execute/execute-prepared-statement!
metabase.notification.models/create-notification!
metabase.pulse.send/send-pulse!
- metabase.query-processor.store/store-database!
;; Safe in tests, where we typically use a private, temporary index per thread.
metabase.search.core/reindex!
metabase.util/run-count!
diff --git a/src/metabase/lib/schema/temporal_bucketing.cljc b/src/metabase/lib/schema/temporal_bucketing.cljc
index 4ab966cac95..795e16b3583 100644
--- a/src/metabase/lib/schema/temporal_bucketing.cljc
+++ b/src/metabase/lib/schema/temporal_bucketing.cljc
@@ -19,7 +19,7 @@
(def date-extraction-units
"Units that you can EXTRACT from a date or datetime. These return integers in temporal bucketing expressions."
- (set ordered-date-extraction-units))
+ (into (sorted-set) ordered-date-extraction-units))
(mr/def ::unit.date.extract
(into [:enum {:error/message "Valid date extraction unit"
@@ -33,7 +33,7 @@
(def date-truncation-units
"Units that you can TRUNCATE a date or datetime to. In temporal bucketing expressions these return a `:type/Date`."
- (set ordered-date-truncation-units))
+ (into (sorted-set) ordered-date-truncation-units))
(mr/def ::unit.date.truncate
(into [:enum {:error/message "Valid date truncation unit"
@@ -47,7 +47,7 @@
(def date-bucketing-units
"Valid date or datetime bucketing units for either truncation or extraction operations."
- (set ordered-date-bucketing-units))
+ (into (sorted-set) ordered-date-bucketing-units))
(mr/def ::unit.date
(into [:enum {:error/message "Valid date bucketing unit"
@@ -63,7 +63,7 @@
(def time-extraction-units
"Units that you can EXTRACT from a time or datetime. These return integers in temporal bucketing expressions."
- (set ordered-time-extraction-units))
+ (into (sorted-set) ordered-time-extraction-units))
(mr/def ::unit.time.extract
(into [:enum {:error/message "Valid time extraction unit"}] time-extraction-units))
@@ -76,7 +76,7 @@
(def time-truncation-units
"Units you can TRUNCATE a time or datetime to. These return the same type as the expression being bucketed in temporal
bucketing expressions."
- (set ordered-time-truncation-units))
+ (into (sorted-set) ordered-time-truncation-units))
(mr/def ::unit.time.truncate
(into [:enum {:error/message "Valid time truncation unit"
@@ -92,7 +92,7 @@
(def time-bucketing-units
"Valid time bucketing units for either truncation or extraction operations."
- (set ordered-time-bucketing-units))
+ (into (sorted-set) ordered-time-bucketing-units))
(mr/def ::unit.time
(into [:enum {:error/message "Valid time bucketing unit"
@@ -116,7 +116,7 @@
(def datetime-bucketing-units
"Valid datetime bucketing units for either truncation or extraction operations."
- (set ordered-datetime-bucketing-units))
+ (into (sorted-set) ordered-datetime-bucketing-units))
(mr/def ::unit.date-time
(into [:enum {:error/message "Valid datetime bucketing unit"
diff --git a/src/metabase/lib/temporal_bucket.cljc b/src/metabase/lib/temporal_bucket.cljc
index 58fa8e47b02..fe546c66bef 100644
--- a/src/metabase/lib/temporal_bucket.cljc
+++ b/src/metabase/lib/temporal_bucket.cljc
@@ -510,3 +510,25 @@
(if-some [temporal-unit (:unit column-metadata)]
(update column-metadata :display_name ensure-ends-with-temporal-unit temporal-unit)
column-metadata))
+
+(def ^:private valid-units-for-date (conj lib.schema.temporal-bucketing/date-bucketing-units :default))
+(def ^:private valid-units-for-time (conj lib.schema.temporal-bucketing/time-bucketing-units :default))
+(def ^:private valid-units-for-datetime lib.schema.temporal-bucketing/temporal-bucketing-units)
+
+(defmulti valid-units-for-type
+ "Returns valid temporal units for `a-type`."
+ {:arglists '([a-type])}
+ keyword)
+
+(defmethod valid-units-for-type :type/* [_] valid-units-for-datetime)
+(defmethod valid-units-for-type :type/Date [_] valid-units-for-date)
+(defmethod valid-units-for-type :type/Time [_] valid-units-for-time)
+(defmethod valid-units-for-type :type/DateTime [_] valid-units-for-datetime)
+
+(mu/defn compatible-temporal-unit?
+ "Check whether some column of `a-type` can be bucketted by the`temporal-unit`. Any column can be bucketed by `nil`
+ temporal unit."
+ [a-type :- ::lib.schema.common/base-type
+ temporal-unit :- [:maybe ::lib.schema.temporal-bucketing/unit]]
+ (or (nil? temporal-unit)
+ (contains? (valid-units-for-type a-type) temporal-unit)))
diff --git a/src/metabase/lib/walk.cljc b/src/metabase/lib/walk.cljc
index d446e4d5bdc..271422376c3 100644
--- a/src/metabase/lib/walk.cljc
+++ b/src/metabase/lib/walk.cljc
@@ -1,10 +1,13 @@
(ns metabase.lib.walk
"Tools for walking and transforming a query."
(:require
+ [medley.core :as m]
[metabase.lib.join :as lib.join]
[metabase.lib.schema :as lib.schema]
[metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.schema.join :as lib.schema.join]
+ [metabase.lib.schema.mbql-clause :as lib.schema.mbql-clause]
+ [metabase.lib.util :as lib.util]
[metabase.util :as u]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]))
@@ -247,3 +250,95 @@
join :- [:map
[:lib/type [:= :mbql/join]]]]
(into (vec join-path) [:stages (dec (count (:stages join)))]))
+
+(declare 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
+
+(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
+
+ (f clause)
+
+ on every MBQL clause. (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))
+
+(mu/defn walk-clauses*
+ "Impl for [[walk-clauses]].
+
+ Calls
+
+ (f clause)
+
+ on every clause in the normal places clauses live in a query."
+ [clauses :- [:maybe [:sequential :any]]
+ f :- [:=> [:cat :any] :any]]
+ ;; we're doing this the hard way instead of using `mapv` to avoid allocating new objects/creating a new query map
+ ;; if we don't actually change anything
+ (when clauses
+ (reduce
+ (fn [clauses i]
+ (let [clause (nth clauses i)
+ clause' (walk-clause clause f)
+ clause'' (or (f clause')
+ clause')]
+ (if (= clause'' clause)
+ clauses
+ (assoc (vec clauses) i clause''))))
+ clauses
+ (range (count clauses)))))
+
+(mu/defn walk-clauses :- ::lib.schema/query
+ "Walk all the MBQL clauses in a query in a depth-first manner.
+
+ `f` is of the form
+
+ (f query path-type stage-or-join-path clause) => replacement-clause-or-nil
+
+ `clause` in this case includes any MBQL clause in the normal places they live in a query as well as other args
+ inside MBQL clauses, e.g.
+
+ [:> {} [:field {} 1] 2]
+
+ will call `f` with `1` and `2` as well as the `:field` and `:>` clauses.
+
+ If `f` returns `nil` the clause will be left as-is. Use this to your advantage.
+
+ Avoids creating new objects except for when `f` actually returns something different."
+ [query :- ::lib.schema/query
+ f :- [:=>
+ [:cat :map ::path-type ::path ::lib.schema.mbql-clause/clause]
+ [:maybe ::lib.schema.mbql-clause/clause]]]
+ (walk
+ query
+ (fn [query path-type path stage-or-join]
+ (let [f (partial f query path-type path)]
+ (case path-type
+ :lib.walk/join
+ (-> stage-or-join
+ (m/update-existing :conditions walk-clauses* f)
+ (m/update-existing :fields (fn [fields]
+ (cond-> fields
+ (sequential? fields)
+ (walk-clauses* f)))))
+
+ :lib.walk/stage
+ (when (= (:lib/type stage-or-join) :mbql.stage/mbql)
+ (reduce
+ (fn [stage k]
+ (m/update-existing stage k walk-clauses* f))
+ stage-or-join
+ [:aggregation :breakout :expressions :fields :filters :order-by])))))))
diff --git a/src/metabase/query_processor/middleware/parameters/mbql.clj b/src/metabase/query_processor/middleware/parameters/mbql.clj
index 57d653e17e6..4ae9977ec61 100644
--- a/src/metabase/query_processor/middleware/parameters/mbql.clj
+++ b/src/metabase/query_processor/middleware/parameters/mbql.clj
@@ -10,12 +10,12 @@
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
+ [metabase.lib.temporal-bucket :as lib.temporal-bucket]
[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.parameters.dates :as params.dates]
[metabase.query-processor.parameters.operators :as params.ops]
- [metabase.query-processor.util.temporal-bucket :as qp.u.temporal-bucket]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
@@ -128,7 +128,7 @@
(when (integer? target-column)
(:base-type (lib.metadata/field metadata-providerable target-column))))]
(assert (some? base-type) "`base-type` is not set.")
- (when-not (qp.u.temporal-bucket/compatible-temporal-unit? base-type new-unit)
+ (when-not (lib.temporal-bucket/compatible-temporal-unit? base-type new-unit)
(throw (ex-info (tru "This chart can not be broken out by the selected unit of time: {0}." value)
{:type qp.error-type/invalid-query
:is-curated true
diff --git a/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj b/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj
index 5c4c66d3c13..16135494bf8 100644
--- a/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj
+++ b/src/metabase/query_processor/middleware/validate_temporal_bucketing.clj
@@ -1,27 +1,33 @@
(ns metabase.query-processor.middleware.validate-temporal-bucketing
(:require
- [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.core :as lib]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.temporal-bucket :as lib.temporal-bucket]
[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.util.temporal-bucket :as qp.u.temporal-bucket]
- [metabase.util.i18n :refer [tru]]))
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.malli :as mu]))
-(defn validate-temporal-bucketing
+(mu/defn validate-temporal-bucketing
"Make sure temporal bucketing of Fields (i.e., `:datetime-field` clauses) in this query is valid given the combination
of Field base-type and unit. For example, you should not be allowed to bucket a `:type/Date` Field by `:minute`."
- [query]
- (doseq [[_ id-or-name {:keys [temporal-unit base-type]} :as clause] (lib.util.match/match (:query query) [:field _ (_ :guard :temporal-unit)])]
- (let [base-type (if (integer? id-or-name)
- (:base-type (lib.metadata/field (qp.store/metadata-provider) id-or-name))
- base-type)
- valid-units (qp.u.temporal-bucket/valid-units-for-base-type base-type)]
- (when-not (valid-units temporal-unit)
- (throw (ex-info (tru "Unsupported temporal bucketing: You can''t bucket a {0} Field by {1}."
- base-type temporal-unit)
- {:type qp.error-type/invalid-query
- :field clause
- :base-type base-type
- :unit temporal-unit
- :valid-units valid-units})))))
- query)
+ [query :- ::lib.schema/query]
+ (u/prog1 query
+ (lib.walk/walk-clauses
+ query
+ (fn [query _path-type path clause]
+ (lib.util.match/match-lite clause
+ [:field (opts :guard :temporal-unit) _id-or-name]
+ (let [temporal-unit (:temporal-unit opts)
+ effective-type (lib.walk/apply-f-for-stage-at-path lib/type-of query path clause)
+ valid-units (lib.temporal-bucket/valid-units-for-type effective-type)]
+ (when-not (valid-units temporal-unit)
+ (throw (ex-info (tru "Unsupported temporal bucketing: You can''t bucket a {0} Field by {1}."
+ effective-type temporal-unit)
+ {:type qp.error-type/invalid-query
+ :field clause
+ :effective-type effective-type
+ :unit temporal-unit
+ :valid-units valid-units})))))))))
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index 3d035d0897c..ccaa32ef532 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -86,39 +86,6 @@
assoc :converted-form query)))
(with-meta (meta middleware-fn))))
-(def ^:private unconverted-property?
- (some-fn #{:info} qualified-keyword?))
-
-(defn- copy-unconverted-properties
- [to from]
- (reduce-kv (fn [m k v]
- (cond-> m
- (unconverted-property? k) (assoc k v)))
- to
- from))
-
-;;; TODO -- this is broken and disables enforcement inside the middleware itself -- see QUE-1346
-(defn- ensure-mbql5-for-unclean-query
- [middleware-fn]
- (-> (fn [query]
- (as-> query query
- ;; convert to MBQL 5 as needed
- (letfn [(convert [query]
- (lib/without-cleaning
- (^:once fn* []
- (mu/disable-enforcement
- (lib/query (qp.store/metadata-provider) query)))))]
- (-> (cond->> query
- (not (:lib/type query)) convert)
- (copy-unconverted-properties query)))
- ;; apply the middleware WITH MALLI ENFORCEMENT ENABLED!
- (middleware-fn query)
- ;; now convert back to legacy without cleaning
- (mu/disable-enforcement
- (lib/without-cleaning
- (^:once fn* [] (->legacy query))))))
- (with-meta (meta middleware-fn))))
-
(def ^:private middleware
"Pre-processing middleware. Has the form
@@ -165,8 +132,8 @@
(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-for-unclean-query #'auto-parse-filter-values/auto-parse-filter-values)
- (ensure-legacy #'validate-temporal-bucketing/validate-temporal-bucketing)
+ (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)
diff --git a/src/metabase/query_processor/util/temporal_bucket.clj b/src/metabase/query_processor/util/temporal_bucket.clj
deleted file mode 100644
index 68b5042ba75..00000000000
--- a/src/metabase/query_processor/util/temporal_bucket.clj
+++ /dev/null
@@ -1,27 +0,0 @@
-(ns metabase.query-processor.util.temporal-bucket
- (:require
- [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]))
-
-(def ^:private valid-date-units (into #{:default} lib.schema.temporal-bucketing/date-bucketing-units))
-(def ^:private valid-time-units (into #{:default} lib.schema.temporal-bucketing/time-bucketing-units))
-(def ^:private valid-datetime-units lib.schema.temporal-bucketing/temporal-bucketing-units)
-
-;; TODO -- this should be changed to `:effective-type` once we finish the metadata changes.
-(defmulti valid-units-for-base-type
- "Returns valid temrpoal units for the `base-type`."
- {:arglists '([base-type])}
- keyword)
-
-;; for stuff like UNIX timestamps -- skip validation for now. (UNIX timestamp should be bucketable with any unit
-;; anyway). Once `:effective-type` is in place, we can actually check those Fields here.
-(defmethod valid-units-for-base-type :type/* [_] valid-datetime-units)
-(defmethod valid-units-for-base-type :type/Date [_] valid-date-units)
-(defmethod valid-units-for-base-type :type/Time [_] valid-time-units)
-(defmethod valid-units-for-base-type :type/DateTime [_] valid-datetime-units)
-
-(defn compatible-temporal-unit?
- "Check whether some column of `a-type` can be bucketted by the`temporal-unit`. Any column can be bucketed by `nil`
- temporal unit."
- [a-type temporal-unit]
- (or (nil? temporal-unit)
- (contains? (valid-units-for-base-type a-type) temporal-unit)))
diff --git a/test/metabase/lib/test_util/attempted_murders_metadata_provider.cljc b/test/metabase/lib/test_util/attempted_murders_metadata_provider.cljc
new file mode 100644
index 00000000000..7a8a235a021
--- /dev/null
+++ b/test/metabase/lib/test_util/attempted_murders_metadata_provider.cljc
@@ -0,0 +1,233 @@
+(ns metabase.lib.test-util.attempted-murders-metadata-provider
+ (:require
+ [metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]))
+
+(defonce ^:private table-id-offset (rand-int 100))
+(defonce ^:private field-id-offset (* table-id-offset 10))
+
+(defn id
+ "Like [[metabase.lib.test-metadata/id]] but specifically for this test dataset."
+ ([]
+ 1)
+ ([table-name]
+ (+ (case table-name
+ :attempts 1)
+ table-id-offset))
+ ([table-name field-name]
+ (+ (case table-name
+ :attempts (case field-name
+ :id 1
+ :date 2
+ :datetime 3
+ :datetime-ltz 4
+ :datetime-tz 5
+ :datetime-tz-id 6
+ :time 7
+ :time-ltz 8
+ :time-tz 9
+ :num-crows 10))
+ field-id-offset)))
+
+(def metadata-provider
+ "A metadata provider that simulates the `attempted-murders` test dataset."
+ (lib.tu/mock-metadata-provider
+ {:database meta/database
+ :tables [{:active true
+ :db-id 1
+ :display-name "Attempts"
+ :id (id :attempts)
+ :name "ATTEMPTS"
+ :schema "PUBLIC"
+ :visibility-type nil
+ :lib/type :metadata/table}]
+ :fields [{:active true
+ :base-type :type/BigInteger
+ :coercion-strategy nil
+ :database-type "BIGINT"
+ :description nil
+ :display-name "ID"
+ :effective-type :type/BigInteger
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :id)
+ :name "ID"
+ :nfc-path nil
+ :parent-id nil
+ :position 0
+ :semantic-type :type/PK
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/Date
+ :coercion-strategy nil
+ :database-type "DATE"
+ :description nil
+ :display-name "Date"
+ :effective-type :type/Date
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :date)
+ :name "DATE"
+ :nfc-path nil
+ :parent-id nil
+ :position 1
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/DateTime
+ :coercion-strategy nil
+ :database-type "TIMESTAMP"
+ :description nil
+ :display-name "Datetime"
+ :effective-type :type/DateTime
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :datetime)
+ :name "DATETIME"
+ :nfc-path nil
+ :parent-id nil
+ :position 2
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/DateTimeWithLocalTZ
+ :coercion-strategy nil
+ :database-type "TIMESTAMP WITH TIME ZONE"
+ :description nil
+ :display-name "Datetime Ltz"
+ :effective-type :type/DateTimeWithLocalTZ
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :datetime-ltz)
+ :name "DATETIME_LTZ"
+ :nfc-path nil
+ :parent-id nil
+ :position 3
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/DateTimeWithLocalTZ
+ :coercion-strategy nil
+ :database-type "TIMESTAMP WITH TIME ZONE"
+ :description nil
+ :display-name "Datetime Tz"
+ :effective-type :type/DateTimeWithLocalTZ
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :datetime-tz)
+ :name "DATETIME_TZ"
+ :nfc-path nil
+ :parent-id nil
+ :position 4
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/DateTimeWithLocalTZ
+ :coercion-strategy nil
+ :database-type "TIMESTAMP WITH TIME ZONE"
+ :description nil
+ :display-name "Datetime Tz ID"
+ :effective-type :type/DateTimeWithLocalTZ
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :datetime-tz-id)
+ :name "DATETIME_TZ_ID"
+ :nfc-path nil
+ :parent-id nil
+ :position 5
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/Time
+ :coercion-strategy nil
+ :database-type "TIME"
+ :description nil
+ :display-name "Time"
+ :effective-type :type/Time
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :time)
+ :name "TIME"
+ :nfc-path nil
+ :parent-id nil
+ :position 6
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/Time
+ :coercion-strategy nil
+ :database-type "TIME"
+ :description nil
+ :display-name "Time Ltz"
+ :effective-type :type/Time
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :time-ltz)
+ :name "TIME_LTZ"
+ :nfc-path nil
+ :parent-id nil
+ :position 7
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/Time
+ :coercion-strategy nil
+ :database-type "TIME"
+ :description nil
+ :display-name "Time Tz"
+ :effective-type :type/Time
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :time-tz)
+ :name "TIME_TZ"
+ :nfc-path nil
+ :parent-id nil
+ :position 8
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/Integer
+ :coercion-strategy nil
+ :database-type "INTEGER"
+ :description nil
+ :display-name "Num Crows"
+ :effective-type :type/Integer
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :attempts :num-crows)
+ :name "NUM_CROWS"
+ :nfc-path nil
+ :parent-id nil
+ :position 9
+ :semantic-type nil
+ :settings nil
+ :table-id (id :attempts)
+ :visibility-type :normal
+ :lib/type :metadata/column}]}))
diff --git a/test/metabase/lib/test_util/sad_toucan_incidents_metadata_provider.cljc b/test/metabase/lib/test_util/sad_toucan_incidents_metadata_provider.cljc
new file mode 100644
index 00000000000..594e7bf79d7
--- /dev/null
+++ b/test/metabase/lib/test_util/sad_toucan_incidents_metadata_provider.cljc
@@ -0,0 +1,93 @@
+(ns metabase.lib.test-util.sad-toucan-incidents-metadata-provider
+ (:require
+ [metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]))
+
+(defonce ^:private table-id-offset (rand-int 100))
+(defonce ^:private field-id-offset (* table-id-offset 10))
+
+(defn id
+ "Like [[metabase.lib.test-metadata/id]] but specifically for this test dataset."
+ ([]
+ 1)
+ ([table-name]
+ (+ (case table-name
+ :incidents 1)
+ table-id-offset))
+ ([table-name field-name]
+ (+ (case table-name
+ :incidents (case field-name
+ :id 1
+ :severity 2
+ :timestamp 3))
+ field-id-offset)))
+
+(def metadata-provider
+ "A metadata provider that simulates the `sad-toucan-incidents` test dataset."
+ (lib.tu/mock-metadata-provider
+ {:database meta/database
+ :tables [{:active true
+ :db-id 1
+ :display-name "Incidents"
+ :id (id :incidents)
+ :name "INCIDENTS"
+ :schema "PUBLIC"
+ :visibility-type nil
+ :lib/type :metadata/table}]
+ :fields [{:active true
+ :base-type :type/BigInteger
+ :coercion-strategy nil
+ :database-type "BIGINT"
+ :description nil
+ :display-name "ID"
+ :effective-type :type/BigInteger
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :incidents :id)
+ :name "ID"
+ :nfc-path nil
+ :parent-id nil
+ :position 0
+ :semantic-type :type/PK
+ :settings nil
+ :table-id (id :incidents)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/Integer
+ :coercion-strategy nil
+ :database-type "INTEGER"
+ :description nil
+ :display-name "Severity"
+ :effective-type :type/Integer
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :incidents :severity)
+ :name "SEVERITY"
+ :nfc-path nil
+ :parent-id nil
+ :position 1
+ :semantic-type nil
+ :settings nil
+ :table-id (id :incidents)
+ :visibility-type :normal
+ :lib/type :metadata/column}
+ {:active true
+ :base-type :type/BigInteger
+ :coercion-strategy :Coercion/UNIXMilliSeconds->DateTime
+ :database-type "BIGINT"
+ :description nil
+ :display-name "Timestamp"
+ :effective-type :type/Instant
+ :fingerprint nil
+ :fk-target-field-id nil
+ :id (id :incidents :timestamp)
+ :name "TIMESTAMP"
+ :nfc-path nil
+ :parent-id nil
+ :position 2
+ :semantic-type nil
+ :settings nil
+ :table-id (id :incidents)
+ :visibility-type :normal
+ :lib/type :metadata/column}]}))
diff --git a/test/metabase/lib/walk_test.cljc b/test/metabase/lib/walk_test.cljc
index baf77248e09..085468beb89 100644
--- a/test/metabase/lib/walk_test.cljc
+++ b/test/metabase/lib/walk_test.cljc
@@ -1,10 +1,15 @@
(ns metabase.lib.walk-test
(:require
- #?(:clj [metabase.util.malli.fn :as mu.fn])
+ #?@(:clj ([metabase.util.malli.fn :as mu.fn])
+ :cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
[clojure.test :refer [are deftest is testing use-fixtures]]
+ [metabase.lib.core :as lib]
+ [metabase.lib.test-metadata :as meta]
[metabase.lib.walk :as lib.walk]
[metabase.util.malli.registry :as mr]))
+#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))
+
(use-fixtures :each (fn [thunk]
;;; disable schema enforcement so we don't need mega queries to test stuff here.
#?(:clj (binding [mu.fn/*enforce* false]
@@ -168,3 +173,63 @@
[:stages 0 :joins 0 :joins 0]
[:joins]
[:joins 0]))
+
+(deftest ^:parallel walk-clauses-test
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :venues))
+ (lib/filter (lib/and
+ (lib/> (meta/field-metadata :venues :id) 50)
+ (lib/< (meta/field-metadata :venues :id) 60))))
+ calls (atom [])]
+ (is (=? {:stages [{:filters [[:and {}
+ [:> {}
+ [:field {} (meta/id :venues :id)]
+ [:value {:lib/uuid "00000000-0000-0000-0000-000000000000"} 50]]
+ [:< {}
+ [:field {} (meta/id :venues :id)]
+ 60]]]}]}
+ (lib.walk/walk-clauses
+ query
+ (fn [_query _path-type _stage-or-join-path clause]
+ (swap! calls conj clause)
+ (if (= clause 50)
+ [:value {:lib/uuid "00000000-0000-0000-0000-000000000000"} 50]
+ clause)))))
+ (is (=? [;; recursing into `>`
+ (meta/id :venues :id)
+ [:field {} (meta/id :venues :id)]
+ 50
+ [:> {}
+ [:field {} (meta/id :venues :id)]
+ [:value {:lib/uuid "00000000-0000-0000-0000-000000000000"} 50]]
+ ;; recursing into `<`
+ (meta/id :venues :id)
+ [:field
+ {}
+ (meta/id :venues :id)]
+ 60
+ [:< {}
+ [:field
+ {}
+ (meta/id :venues :id)]
+ 60]
+ ;; `:filters`
+ [:and {}
+ [:> {}
+ [:field {} (meta/id :venues :id)]
+ [:value {:lib/uuid "00000000-0000-0000-0000-000000000000"} 50]]
+ [:< {}
+ [:field {} (meta/id :venues :id)]
+ 60]]]
+ @calls))))
+
+(deftest ^:parallel walk-clauses-identity-test
+ (testing "If we don't update any clauses then we should return the original query"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :venues))
+ (lib/filter (lib/and
+ (lib/> (meta/field-metadata :venues :id) 50)
+ (lib/< (meta/field-metadata :venues :id) 60))))]
+ (doseq [f [(fn [_query _path-type _stage-or-join-path clause]
+ clause)
+ ;; 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)))))))
diff --git a/test/metabase/query_processor/middleware/validate_temporal_bucketing_test.clj b/test/metabase/query_processor/middleware/validate_temporal_bucketing_test.clj
index 22e0a4ce748..ca35d206101 100644
--- a/test/metabase/query_processor/middleware/validate_temporal_bucketing_test.clj
+++ b/test/metabase/query_processor/middleware/validate_temporal_bucketing_test.clj
@@ -1,67 +1,72 @@
(ns metabase.query-processor.middleware.validate-temporal-bucketing-test
(:require
[clojure.test :refer :all]
- [metabase.query-processor.middleware.validate-temporal-bucketing
- :as validate-temporal-bucketing]
- [metabase.test :as mt]
- [toucan2.core :as t2]))
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.schema.util :as lib.schema.util]
+ [metabase.lib.test-util.attempted-murders-metadata-provider :as lib.tu.attempted-murders-metadata-provider]
+ [metabase.lib.test-util.sad-toucan-incidents-metadata-provider :as lib.tu.sad-toucan-incidents-metadata-provider]
+ [metabase.query-processor.middleware.validate-temporal-bucketing :as validate-temporal-bucketing]
+ [metabase.test :as mt]))
(defn- validate [query]
(validate-temporal-bucketing/validate-temporal-bucketing query))
-(deftest validate-temporal-bucketing-test
- (mt/dataset attempted-murders
- (mt/with-metadata-provider (mt/id)
- (doseq [field-clause-type [:id :name]]
- (testing (format "With %s clauses" field-clause-type)
- (letfn [(query [field unit]
- (mt/mbql-query attempts
- {:filter [:=
- [:field
- (case field-clause-type
- :id (mt/id :attempts field)
- :name (t2/select-one-fn :name :model/Field :id (mt/id :attempts field)))
- (merge
- {:temporal-unit unit}
- (when (= field-clause-type :name)
- {:base-type (t2/select-one-fn :base_type :model/Field :id (mt/id :attempts field))}))]
- [:relative-datetime -1 unit]]}))]
- ;; I don't think we need to test every possible combination in the world here -- that will get tested by
- ;; other stuff
- (doseq [[field unit valid?] [[:date :day true]
- [:date :default true]
- [:time :day false]
- [:datetime :day true]
- [:datetime_tz :month true]
- [:date :minute false]
- [:time_tz :minute true]
- [:datetime_tz :minute true]]]
- (if valid?
- (testing (format "Valid combinations (%s × %s) should return query as-is" field unit)
- (is (= (query field unit)
- (validate (query field unit)))))
- (testing (format "We should throw an Exception if you try to do something that makes no sense (bucketing %s by %s)"
- field unit)
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"Unsupported temporal bucketing: You can't bucket"
- (validate (query field unit)))))))))))))
+(deftest ^:parallel validate-temporal-bucketing-test
+ (let [mp lib.tu.attempted-murders-metadata-provider/metadata-provider]
+ (doseq [field-clause-type [:id :name]]
+ (testing (format "With %s clauses" field-clause-type)
+ (letfn [(query [field unit]
+ (-> (lib/query mp (lib.metadata/table mp (lib.tu.attempted-murders-metadata-provider/id :attempts)))
+ (lib/filter (lib/=
+ [:field
+ (merge
+ {:lib/uuid (str (random-uuid))
+ :temporal-unit unit}
+ (select-keys (lib.metadata/field mp (lib.tu.attempted-murders-metadata-provider/id :attempts field))
+ [:base-type :effective-type]))
+ (case field-clause-type
+ :id (lib.tu.attempted-murders-metadata-provider/id :attempts field)
+ :name (:name (lib.metadata/field mp (lib.tu.attempted-murders-metadata-provider/id :attempts field))))]
+ (lib/relative-datetime -1 unit)))))]
+ ;; I don't think we need to test every possible combination in the world here -- that will get tested by
+ ;; other stuff
+ (doseq [[field unit valid?] [[:date :day true]
+ [:date :default true]
+ [:time :day false]
+ [:datetime :day true]
+ [:datetime-tz :month true]
+ [:date :minute false]
+ [:time-tz :minute true]
+ [:datetime-tz :minute true]]]
+ (if valid?
+ (testing (format "Valid combinations (%s × %s) should return query as-is" field unit)
+ (is (=? (lib.schema.util/remove-lib-uuids (query field unit))
+ (validate (query field unit)))))
+ (testing (format "We should throw an Exception if you try to do something that makes no sense (bucketing %s by %s)"
+ field unit)
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Unsupported temporal bucketing: You can't bucket"
+ (validate (query field unit))))))))))))
-(deftest unix-timestamp-test
+(deftest ^:parallel unix-timestamp-test
(testing "UNIX Timestamps should be bucketable by anything"
- (mt/dataset sad-toucan-incidents
- (mt/with-metadata-provider (mt/id)
- (doseq [unit [:default :hour :day]]
- (testing (format "Unit = %s" unit)
- (is (some? (validate (mt/mbql-query incidents
- {:filter [:= [:field %timestamp {:temporal-unit unit}]]}))))))))))
+ (let [mp lib.tu.sad-toucan-incidents-metadata-provider/metadata-provider]
+ (doseq [unit [:default :hour :day]]
+ (testing (format "Unit = %s" unit)
+ (is (some? (validate
+ (-> (lib/query mp (lib.metadata/table mp (lib.tu.sad-toucan-incidents-metadata-provider/id :incidents)))
+ (lib/filter (lib/= (-> (lib.metadata/field mp (lib.tu.sad-toucan-incidents-metadata-provider/id :incidents :timestamp))
+ (lib/with-temporal-bucket unit))
+ #t "2025-08-22T16:26:00")))))))))))
-(deftest e2e-test
+(deftest ^:parallel e2e-test
(testing "We should throw an Exception if you try to do something that makes no sense, e.g. bucketing a DATE by MINUTE"
(mt/dataset attempted-murders
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
- #"Unsupported temporal bucketing: You can't bucket a :type/Date Field by :minute|Invalid output:.*should be a.*got"
+ #"Unsupported temporal bucketing: You can't bucket a :type/Date Field by :minute"
(mt/run-mbql-query attempts
{:aggregation [[:count]]
:filter [:time-interval $date :last :minute]}))))))