The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
[match] Add shorthand syntax for non-binding predicate checks (#82396)
Oleksandr Yakushevf863f6848931
diff --git a/.clj-kondo/src/hooks/metabase/util/match.clj b/.clj-kondo/src/hooks/metabase/util/match.cljindex f589742a09f..098d5a42b71 100644--- a/.clj-kondo/src/hooks/metabase/util/match.clj+++ b/.clj-kondo/src/hooks/metabase/util/match.clj@@ -9,6 +9,10 @@(and (api/keyword-node? node)(= (:k node) k)))+(defn- var-reader-node? [node]+ (and (api/node? node)+ (= (:tag node) :var)))+(defn- binding-symbol?"True when the token is a plain symbol that should be treated as a binding(not a keyword, not a boolean literal, not nil, not a number, not `_`)."@@ -29,6 +33,9 @@(binding-symbol? pattern)[[pattern opaque-node]]+ (var-reader-node? pattern)+ [[(api/token-node '_) (first (:children pattern))]]+;; Lists: (:or ...), (:and ...), (sym :guard pred ...), or a quoted symbol.(api/list-node? pattern)(let [[head & rst] (:children pattern)]diff --git a/dev/src/dev/debug_qp.clj b/dev/src/dev/debug_qp.cljindex ddb01bcbe7d..149e25354a5 100644--- a/dev/src/dev/debug_qp.clj+++ b/dev/src/dev/debug_qp.clj@@ -130,13 +130,13 @@(pos-int? (:source-field opts))(update :source-field field-id->name-form))]- (:and m {:source-table (_ :guard pos-int?)})+ (:and m {:source-table #'pos-int?})(add-names* (update m :source-table add-table-id-name))- (:and m {:metabase.query-processor.util.add-alias-info/source-table (_ :guard pos-int?)})+ (:and m {:metabase.query-processor.util.add-alias-info/source-table #'pos-int?})(add-names* (update m :metabase.query-processor.util.add-alias-info/source-table add-table-id-name))- (:and m {:fk-field-id (_ :guard pos-int?)})+ (:and m {:fk-field-id #'pos-int?})(add-names* (update m :fk-field-id field-id->name-form));; don't recursively replace the `do` lists above, other we'll get vectors.@@ -264,7 +264,7 @@(defn- can-symbolize? [x](match/match-one x- (_ :guard string?)+ #'string?(not (re-find #"\s+" x))[:field (id :guard pos-int?) nil]@@ -292,7 +292,7 @@(try(match/replace form(:and [:field (id :guard pos-int?) nil]- (_ :guard can-symbolize?))+ #'can-symbolize?)(let [[table-name field-name] (field-and-table-name id)field-name (some-> field-name u/lower-case-en)table-name (some-> table-name u/lower-case-en)]@@ -300,18 +300,18 @@[::$ field-name][::$ table-name field-name]))- (:and [:field (field-name :guard string?) (:and {:base-type base-type} (opts :guard (= (count opts) 1)))]- (_ :guard can-symbolize?))+ (:and [:field (field-name :guard string?) (:and {:base-type base-type} (opts :len 1))]+ #'can-symbolize?)[::* field-name (name base-type)](:and [:field _ {:temporal-unit temporal-unit}]- (_ :guard can-symbolize?))+ #'can-symbolize?)(let [without-unit (mbql.u/update-field-options &match dissoc :temporal-unit)expansion (expand without-unit table)][::! (name temporal-unit) (strip-$ expansion)])(:and [:field _ {:source-field source-field}]- (_ :guard can-symbolize?))+ #'can-symbolize?)(let [without-source-field (mbql.u/update-field-options &match dissoc :source-field)expansion (expand without-source-field table)source-as-field-clause [:field source-field nil]@@ -319,7 +319,7 @@[::-> source-expansion expansion])(:and [:field _ {:join-alias join-alias}]- (_ :guard can-symbolize?))+ #'can-symbolize?)(let [without-join-alias (mbql.u/update-field-options &match dissoc :join-alias)expansion (expand without-join-alias table)][::& join-alias expansion])@@ -331,12 +331,12 @@&match[:field [::% (strip-$ expansion)] opts]))- (:and m {:source-table (_ :guard pos-int?)})+ (:and m {:source-table #'pos-int?})(-> (update m :source-table (fn [table-id][::$$ (some-> (t2/select-one-fn :name :model/Table :id table-id) u/lower-case-en)]))(expand table))- (:and m {:fk-field-id (_ :guard pos-int?)})+ (:and m {:fk-field-id #'pos-int?})(-> (update m :fk-field-id (fn [fk-field-id](let [[table-name field-name] (field-and-table-name fk-field-id)field-name (some-> field-name u/lower-case-en)diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test/reconciliation_test_util.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test/reconciliation_test_util.cljindex cd4405bb85b..b88c16de1a2 100644--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test/reconciliation_test_util.clj+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test/reconciliation_test_util.clj@@ -175,7 +175,7 @@(defn- temporal-type-reconciliation-expected-value[{:keys [field temporal-type expected-value honeysql-filter-fn num-args], :as _test-case}]- (let [field-literal? (match/match-one field [:field {} (_ :guard string?)] true)+ (let [field-literal? (match/match-one field [:field {} #'string?] true)mock-field (get mock-temporal-fields temporal-type)expected-identifier (cond-> (-> (h2x/identifier :field "ABC" (name temporal-type))(vary-meta assoc ::bigquery.qp/do-not-qualify? true))diff --git a/src/metabase/agent_lib/representations.clj b/src/metabase/agent_lib/representations.cljindex d7d7bdc0b03..319d943c731 100644--- a/src/metabase/agent_lib/representations.clj+++ b/src/metabase/agent_lib/representations.clj@@ -144,22 +144,20 @@(defn- table-fk?"Portable table FK: [db-name, schema-or-null, table-name]."[x]- (match/matches? x- [(_ :guard non-blank-string?) (s :guard (or (nil? s) (string? s))) (_ :guard non-blank-string?)]))+ (match/matches? x [#'non-blank-string? (s :guard (or (nil? s) (string? s))) #'non-blank-string?]))(defn- field-fk?"Portable field FK: [db-name, schema-or-null, table-name, field-name, ...json-path-segments]."[x](match/matches? x- [(_ :guard non-blank-string?)+ [#'non-blank-string?(s :guard (or (nil? s) (string? s)))- (_ :guard non-blank-string?)+ #'non-blank-string?& (args :guard (every? non-blank-string? args))]))(defn- clause-shape?[x]- (match/matches? x- [(_ :guard non-blank-string?) (_ :guard map?) & _]))+ (match/matches? x [#'non-blank-string? #'map? & _]))(defn- numeric-id-when-allowed?"A numeric id in a source slot, valid only on a surface that accepts numeric ids (checked atdiff --git a/src/metabase/agent_lib/representations/repair.clj b/src/metabase/agent_lib/representations/repair.cljindex 575c9e46416..2c6d61c6280 100644--- a/src/metabase/agent_lib/representations/repair.clj+++ b/src/metabase/agent_lib/representations/repair.clj@@ -71,16 +71,16 @@(defn- clause-like?"Heuristic: a real clause vector (not an FK path) whose head is a non-blank operator string."[v]- (and (match/matches? v [(_ :guard non-blank-string?) & _])+ (and (match/matches? v [#'non-blank-string? & _])(not (looks-like-fk-path? v))))(defn- ensure-clause-options*"Fix a clause-like vector missing options map at position 2 in nested clause-like vectors."[form](match/replace-all form- (:and [op] (_ :guard clause-like?)) [op {}]- (:and [op nil & _] (_ :guard clause-like?)) (assoc &match 1 {})- (:and [op (non-map :guard (not (map? non-map))) & args] (_ :guard clause-like?)) (into [op {} non-map] args)))+ (:and [op] #'clause-like?) [op {}]+ (:and [op nil & _] #'clause-like?) (assoc &match 1 {})+ (:and [op (non-map :guard (not (map? non-map))) & args] #'clause-like?) (into [op {} non-map] args)));;; ============================================================;;; Pass 1.7 -- unwrap nested `[field opts [field inner-opts target]]` clauses.@@ -212,7 +212,7 @@(let [lower (u/lower-case-en op)](and (contains? operator-name-aliases lower)(not= op (operator-name-aliases lower))))))- (_ :guard map?) & _]+ #'map? & _](assoc &match 0 (operator-name-aliases (u/lower-case-en op)))));;; ============================================================@@ -241,7 +241,7 @@(defn- rewrite-temporal-bucket-aliases*[form](match/replace-all form- [(op :guard (and (string? op) (temporal-bucket-extraction-aliases op))) (_ :guard map?) & _]+ [(op :guard (and (string? op) (temporal-bucket-extraction-aliases op))) #'map? & _](assoc &match 0 (temporal-bucket-extraction-aliases (u/lower-case-en op)))));;; ============================================================@@ -271,10 +271,8 @@(defn- drop-unsupported-day-of-week-mode*[form](match/replace form- ["get-day-of-week"- (_ :guard map?)- _- (mode :guard (and (string? mode) (not= "iso" (u/lower-case-en (str/trim mode)))))]+ ["get-day-of-week" #'map? _+ (mode :guard (and (string? mode) (not= "iso" (u/lower-case-en (str/trim mode)))))](subvec &match 0 3)));;; ============================================================@@ -313,7 +311,7 @@(defn- rewrite-direction-aliases*[form](match/replace-all form- [(head :guard direction-clause-head?) (_ :guard map?) _]+ [(head :guard direction-clause-head?) #'map? _](assoc &match 0 (get direction-aliases (u/lower-case-en head)))));;; ============================================================@@ -429,8 +427,7 @@(defn- merge-trailing-options*[form](match/replace-all form- (_ :guard needs-trailing-options-merge?)- (merge-trailing-options &match)))+ #'needs-trailing-options-merge? (merge-trailing-options &match)));;; ============================================================;;; Pass 1.89 -- merge a trailing options-map into position-1 on N-ary string-search filters@@ -449,9 +446,6 @@;;; misplaced options. We merge it into position-1 (trailing keys win) and drop it. Left;;; unrepaired, `lib.normalize` cannot normalise the clause and the query explodes downstream;;; with a missing-`lib/uuid` "Invalid output" error.-;;;-;;; Runs after [[ensure-clause-options*]] so position 1 is already a map. Idempotent: the-;;; repaired clause's last element is a string arg, so the predicate fails on a second pass.;;; ============================================================(def ^:private string-search-filter-heads@@ -459,21 +453,13 @@position-1 options map. See `metabase.lib.schema.filter`."#{"contains" "does-not-contain" "starts-with" "ends-with"})-(defn- needs-string-filter-options-merge?- "True when `node` is an N-ary string-search filter whose last element is a misplaced trailing- options map (the args before it are string values, never maps). See the pass docstring above."- [node]- (and (clause-like? node)- (contains? string-search-filter-heads (nth node 0))- ;; head + opts + field + >=1 value + trailing options-map- (>= (count node) 5)- (map? (nth node 1))- (map? (peek node))))-(defn- merge-string-filter-trailing-options*[form](match/replace form- (_ :guard needs-string-filter-options-merge?)+ ;; head + opts + field + >=1 value + trailing options-map+ (:and [(op :guard (contains? string-search-filter-heads op)) #'map?+ & (args :guard (and (map? (peek args)) (>= (count args) 3)))]+ #'clause-like?)(&recur (merge-trailing-options &match))));;; ============================================================@@ -686,10 +672,10 @@clause and corrupt it by inserting `{}` between the two scalars."[form](match/replace-all form- (_ :guard in-not-in-values-list-clause)+ #'in-not-in-values-list-clause(let [[head opts lhs values] (in-not-in-values-list-clause &match)](splat-in-values-clause head opts lhs values))- (_ :guard eq-values-list-clause)+ #'eq-values-list-clause(let [[head opts lhs values] (eq-values-list-clause &match)](splat-in-values-clause (=->in-head head) opts lhs values))))@@ -710,21 +696,11 @@;;; legitimate uses of the head.;;; ============================================================-(defn- boolean-wrapper-clause?- "True when `node` is `[\"true\" {} x]` or `[\"false\" {} x]` - exactly one arg."- [node]- (and (vector? node)- (= 3 (count node))- (string? (nth node 0))- (map? (nth node 1))- (let [head (u/lower-case-en (nth node 0))]- (or (= head "true")- (= head "false")))))--(defn- unwrap-boolean-wrapper [node]- (let [head (u/lower-case-en (nth node 0))- x (nth node 2)]- (case head+(defn- unwrap-boolean-wrappers*+ [form]+ (match/replace-all form+ [(head :guard (and (string? head) (#{"true" "false"} (u/lower-case-en head)))) #'map? x]+ (case (u/lower-case-en head);; Always emit a vector so we don't expose a bare scalar (`["true" {} x]` -> `x`) that a;; sole-element parent would turn into an un-optioned clause `[x]`, which a later `repair`;; pass would then "fix" to `[x {}]` - breaking idempotency. A wrapped clause is returned@@ -732,11 +708,6 @@"true" (if (vector? x) x [x {}])"false" ["not" {} x])))-(defn- unwrap-boolean-wrappers*- [form]- (match/replace-all form- (_ :guard boolean-wrapper-clause?) (unwrap-boolean-wrapper &match)))-;;; ============================================================;;; Pass 1.87 -- swap out-of-order literal bounds in `between` clauses.;;;@@ -759,22 +730,14 @@;;; ported - the prompt is explicit about between's three-arg shape).;;; ============================================================-(defn- absolute-datetime-clause? [v]- (and (vector? v)- (>= (count v) 3)- (= "absolute-datetime" (nth v 0))- (map? (nth v 1))- (string? (nth v 2))))-(defn- between-bound-comparable"Extract a comparable value from `bound` if it's a literal we can order. Returns thevalue (a Number or String) or `nil` if the bound is not directly comparable."[bound]- (cond- (number? bound) bound- (string? bound) bound- (absolute-datetime-clause? bound) (nth bound 2)- :else nil))+ (match/match-one bound+ (:or #'number? #'string?) &match+ ["absolute-datetime" #'map? (dt :guard string?) & _] dt+ _ nil))(defn- bounds-comparable-and-swappable?"True when both bounds are extractable comparables of the same kind (both numbers, both@@ -793,15 +756,12 @@(= "between" (nth v 0))(map? (nth v 1))))-(defn- swappable-between-clause? [node]- (and (between-clause? node)- (bounds-comparable-and-swappable? (nth node 3) (nth node 4))))-(defn- swap-between-bounds*[form](match/replace-all form- (_ :guard swappable-between-clause?)- (-> &match (assoc 3 (nth &match 4)) (assoc 4 (nth &match 3)))))+ (:and ["between" #'map? _ lower upper]+ (_ :guard (bounds-comparable-and-swappable? lower upper)))+ (-> &match (assoc 3 upper) (assoc 4 lower))));;; ============================================================;;; Temporal-literal helpers, shared by the passes below.@@ -1476,7 +1436,7 @@[form](match/replace-all form{"fields" (:and single-clause- [(_ :guard string?) (_ :guard map?) & _])}+ [#'string? #'map? & _])}(assoc &match "fields" [single-clause])))(defn- normalise-aggregation-clauses*@@ -1665,7 +1625,7 @@(defn- ensure-lib-types* [form](match/replace-all form- (_ :guard needs-lib-type-marker?)+ #'needs-lib-type-marker?(assoc &match "lib/type" (cond (top-level-query-map? &match) "mbql/query"(join-like-map? &match) "mbql/join"(stage-like-map? &match) "mbql.stage/mbql"))))@@ -1705,7 +1665,7 @@non-clause vectors are left alone."[form](match/replace-all form- (:and (_ :guard clause-like?) [op (_ :guard map?) & args])+ (:and [op #'map? & args] #'clause-like?)(into [op] args)))(defn- ensure-aggregation-uuid@@ -1907,7 +1867,7 @@and no `aggregation:` block, it's a perfectly valid stage)."[stage](some? (match/match-one (dissoc stage "aggregation")- (_ :guard integer-index-agg-ref?) true)))+ #'integer-index-agg-ref? true)))(defn- resolve-integer-agg-refs-in-stage"Resolve all integer-index aggregation refs in a single stage to canonical UUID form.@@ -2731,9 +2691,10 @@"True if `v` is a string-named field ref to a previous-stage column of a stage whose joins arealiased `join-aliases`. A ref through one of those aliases names a join's column instead."[join-aliases v]- (and (not (map-entry? v))- (match/matches? v (:and ["field" (_ :guard map?) (_ :guard non-blank-string?)]))- (not (contains? join-aliases (get (nth v 1) "join-alias")))))+ (match/matches? v ["field"+ (opts :guard (and (map? opts)+ (not (contains? join-aliases (get opts "join-alias")))))+ #'non-blank-string?]))(defn- types-from-column"Pull `\"base-type\"` (and optionally `\"effective-type\"`) off a `lib/returned-columns`@@ -3284,7 +3245,7 @@`validate/operators.clj/validate-operator-specific!` `expression-ref` branch."[form](match/match-one form- ["expression" (_ :guard map?) (name-slot :guard (or (not (string? name-slot)) (str/blank? name-slot)))]+ ["expression" #'map? (name-slot :guard (or (not (string? name-slot)) (str/blank? name-slot)))](throw (ex-info(tru "`[expression, <opts>, <name>]` reference requires a non-blank string identifier in the third slot, matching an entry in some stage''s `expressions:` block."){:agent-error? true@@ -3307,7 +3268,7 @@[form](when-not resolve/*numeric-ids-allowed?*(match/match-one form- ["field" (_ :guard map?) (_ :guard integer?)]+ ["field" #'map? #'integer?](throw (ex-info(tru "`field` clause needs a portable FK in its third slot, not a numeric id. Use a vector `[<database>, <schema>, <table>, <column>]` (resolved against the metadata provider) or a string column-name (for cross-stage references)."){:agent-error? truediff --git a/src/metabase/lib/fe_util.cljc b/src/metabase/lib/fe_util.cljcindex 5dfa76d78d6..0027f06eb21 100644--- a/src/metabase/lib/fe_util.cljc+++ b/src/metabase/lib/fe_util.cljc@@ -395,7 +395,7 @@(value :guard number?)value- [:value (x :guard (= (:base-type x) :type/BigInteger)) (value :guard string?)]+ [:value {:base-type :type/BigInteger} (value :guard string?)](u.number/parse-bigint value)_ nil))@@ -799,6 +799,9 @@(or (lib.util/clause-of-type? lhs-or-rhs :field)(lib.util/clause-of-type? lhs-or-rhs :expression)))+(defn- temporal? [t]+ (lib.util/original-isa? t :type/Temporal))+(mu/defn filter-args-display-name :- :string"Provides a reasonable display name for the `filter-clause` excluding the column-name.Can be expanded as needed but only currently defined for a narrow set of date filters.@@ -809,7 +812,6 @@filter-clause :- ::lib.schema.expression/expression](let [time-config (lib.date-time/config query)->temporal-name #(u.time/format-unit time-config % nil)- temporal? #(lib.util/original-isa? % :type/Temporal)unit= (fn [maybe-clause unit-or-units](let [units (set (u/one-or-many unit-or-units))](clojure.core/and@@ -820,16 +822,16 @@:get-month :month-of-year:get-quarter :quarter-of-year}](match/match-one filter-clause- [#{:= :in} _ [:get-day-of-week _ (_ :guard temporal?) :iso] (b :guard int?)]+ [#{:= :in} _ [:get-day-of-week _ #'temporal? :iso] (b :guard int?)](inflections/plural (u.time/format-unit time-config b :day-of-week-iso))- [#{:!= :not-in} _ [:get-day-of-week _ (_ :guard temporal?) :iso] (b :guard int?)]+ [#{:!= :not-in} _ [:get-day-of-week _ #'temporal? :iso] (b :guard int?)](i18n/tru "Excludes {0}" (inflections/plural (u.time/format-unit time-config b :day-of-week-iso)))- [#{:= :in} _ [(f :guard #{:get-hour :get-month :get-quarter}) _ (_ :guard temporal?)] (b :guard int?)]+ [#{:= :in} _ [(f :guard #{:get-hour :get-month :get-quarter}) _ #'temporal?] (b :guard int?)](u.time/format-unit time-config b (->unit f))- [#{:!= :not-in} _ [(f :guard #{:get-hour :get-month :get-quarter}) _ (_ :guard temporal?)] (b :guard int?)]+ [#{:!= :not-in} _ [(f :guard #{:get-hour :get-month :get-quarter}) _ #'temporal?] (b :guard int?)](i18n/tru "Excludes {0}" (u.time/format-unit time-config b (->unit f)))[#{:= :in} _ (x :guard (unit= x lib.schema.temporal-bucketing/datetime-truncation-units)) (y :guard string?)]@@ -852,7 +854,7 @@[:> _ (x :guard temporal?) (y :guard string?)](i18n/tru "After {0}" (->temporal-name y))- [:between _ (_ :guard temporal?) (y :guard string?) (z :guard string?)]+ [:between _ #'temporal? (y :guard string?) (z :guard string?)](u.time/format-diff y z)[:is-null & _]@@ -861,10 +863,10 @@[:not-null & _](i18n/tru "Is Not Empty")- [:time-interval opts (_ :guard temporal?) n unit]+ [:time-interval opts #'temporal? n unit](lib.temporal-bucket/describe-temporal-interval n unit (select-keys opts [:include-current]))- [:relative-time-interval _ (_ :guard temporal?) n unit offset offset-unit]+ [:relative-time-interval _ #'temporal? n unit offset offset-unit](lib.temporal-bucket/describe-temporal-interval-with-offset n unit offset offset-unit)_diff --git a/src/metabase/lib/native.cljc b/src/metabase/lib/native.cljcindex eef1ac136e4..db97124e26a 100644--- a/src/metabase/lib/native.cljc+++ b/src/metabase/lib/native.cljc@@ -91,7 +91,7 @@(loop [found [][current & more] parsed](let [[found more] (match/match-one current- (_ :guard string?) [found more]+ #'string? [found more]{:type ::lib.parse/param, :name tag-name}(let [normalized-name (lib.params.parse/match-and-normalize-tag-name tag-name)]diff --git a/src/metabase/lib/remove_replace.cljc b/src/metabase/lib/remove_replace.cljcindex 7afc198cf8c..ae2a5461525 100644--- a/src/metabase/lib/remove_replace.cljc+++ b/src/metabase/lib/remove_replace.cljc@@ -459,12 +459,12 @@(let [a-conds (match/replace new-join-conditions{:join-alias (ja :guard (= ja new-join-alias))}(dissoc &match :join-alias :effective-type)- {:effective-type (_ :guard identity)}+ {:effective-type &truthy}(dissoc &match :effective-type))b-conds (match/replace join-conditions-b{:join-alias (ja :guard (= ja join-alias-b))}(dissoc &match :join-alias :effective-type)- {:effective-type (_ :guard identity)}+ {:effective-type &truthy}(dissoc &match :effective-type))](not (lib.equality/= a-conds b-conds))))diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.cljindex 44e6eadabbe..5b6b47838b1 100644--- a/src/metabase/models/serialization.clj+++ b/src/metabase/models/serialization.clj@@ -1102,7 +1102,7 @@[x :- MBQLNode](set(match/match-many x- [:aggregation (_opts :guard map?) (uuid :guard string?)]+ [:aggregation #'map? (uuid :guard string?)]uuid)))(declare export-mbql)@@ -1411,7 +1411,7 @@;; --- serialized (portable) refs, walked at load time ---;; A serialized `:field` clause has no dependencies: its Database, Table and Field are synthesized on import, and;; a field clause never nests metric/segment/card refs, so we don't descend.- [#{:field "field"} (_opts :guard map?) (_ref :guard vector?)]+ [#{:field "field"} #'map? #'vector?]nil[(tag :guard #{:metric "metric" :segment "segment" :measure "measure"})@@ -1430,7 +1430,7 @@;; --- raw (numeric) refs, walked at export time before serialization ---;; The referenced Field/Table are real appdb ids, existence-checked so a deleted row can't produce a malformed;; portable reference. `allow-int-ids?` gates these so a stray numeric in serialized data isn't mistaken for a ref.- [#{:field "field"} (_opts :guard map?) (id :guard (raw-ref-id? allow-int-ids? id))]+ [#{:field "field"} #'map? (id :guard (raw-ref-id? allow-int-ids? id))]#{[{:model "Field" :id id}]}[(tag :guard #{:metric "metric" :segment "segment" :measure "measure"})diff --git a/src/metabase/models/serialization/resolve.clj b/src/metabase/models/serialization/resolve.cljindex 1887647e164..fdcc43f966c 100644--- a/src/metabase/models/serialization/resolve.clj+++ b/src/metabase/models/serialization/resolve.clj@@ -178,12 +178,12 @@[#{:measure "measure"} (entity-id :guard content-ref?)][:measure (import-fk resolver entity-id 'Measure)]- {:source-table (_ :guard vector?)}+ {:source-table #'vector?}(-> &match(update :source-table (partial import-table-fk resolver))(->> (mbql-fully-qualified-names->ids* resolver)))- {:source_table (_ :guard vector?)}+ {:source_table #'vector?}(-> &match(update :source_table (partial import-table-fk resolver))(->> (mbql-fully-qualified-names->ids* resolver)))@@ -292,13 +292,13 @@([entity] (export-mbql *export-resolver* entity))([resolver entity](match/replace entity- (_ :guard mbql-clause-tag)+ #'mbql-clause-tag(mbql-id->fully-qualified-name resolver &match)- (_ :guard sequential?)+ #'sequential?(mapv (partial export-mbql resolver) &match)- (_ :guard map?)+ #'map?(reduce-kv(fn [entity k _v](let [f (case kdiff --git a/src/metabase/query_processor/middleware/add_implicit_joins.clj b/src/metabase/query_processor/middleware/add_implicit_joins.cljindex 1ec666faf00..91245cd0dd5 100644--- a/src/metabase/query_processor/middleware/add_implicit_joins.clj+++ b/src/metabase/query_processor/middleware/add_implicit_joins.clj@@ -130,7 +130,7 @@(let [fk-field-infos (->> field-clauses-with-source-field(keep (fn [clause](match/match-one clause- [:field (opts :guard (and (:source-field opts) (not (:join-alias opts)))) (_id :guard integer?)]+ [:field (opts :guard (and (:source-field opts) (not (:join-alias opts)))) #'integer?](field-opts->fk-field-info metadata-providerable opts))))distinctnot-empty)diff --git a/src/metabase/query_processor/middleware/expand_macros.clj b/src/metabase/query_processor/middleware/expand_macros.cljindex 2dd2a0ff5a2..bfeb6637a64 100644--- a/src/metabase/query_processor/middleware/expand_macros.clj+++ b/src/metabase/query_processor/middleware/expand_macros.clj@@ -34,15 +34,15 @@allowed, including `:filters`, join conditions, expression aggregations like `:sum-where`, etc."[macro-type :- ::macro-typequery :- ::lib.schema/query]- (let [ids (transient #{})]+ (let [ids (volatile! (transient #{}))](lib.walk/walk-stagesquery(fn [_query _path stage](match/match-many stage[#{macro-type} _opts (id :guard pos-int?)]- (conj! ids id))+ (vswap! ids conj! id))nil))- (not-empty (persistent! ids))))+ (not-empty (persistent! @ids))));;; a legacy Segment has one or more filter clauses.diff --git a/src/metabase/query_processor/middleware/optimize_temporal_filters.clj b/src/metabase/query_processor/middleware/optimize_temporal_filters.cljindex 9a764b161c4..109c83b5134 100644--- a/src/metabase/query_processor/middleware/optimize_temporal_filters.clj+++ b/src/metabase/query_processor/middleware/optimize_temporal_filters.clj@@ -49,7 +49,7 @@[:relative-datetime _opts #{0 :current}]true- [(_tag :guard #{:absolute-datetime :relative-datetime}) _opts _n _unit]+ [#{:absolute-datetime :relative-datetime} _opts _n _unit](let [unit (or (lib/raw-temporal-bucket &match) :default)](or (= unit :default)(contains? optimizable-units unit)))))@@ -153,7 +153,7 @@(defn- change-temporal-unit-to-default [field](match/replace field- [#{:field :expression} {:temporal-unit (_ :guard optimizable-units)} _id-or-name]+ [#{:field :expression} {:temporal-unit #'optimizable-units} _id-or-name](lib/update-options &match assoc :temporal-unit :default)[:absolute-datetime _opts t _unit]diff --git a/src/metabase/revisions/models/revision/diff.clj b/src/metabase/revisions/models/revision/diff.cljindex 6eb16f92b88..645bfa3deb1 100644--- a/src/metabase/revisions/models/revision/diff.clj+++ b/src/metabase/revisions/models/revision/diff.clj@@ -22,7 +22,7 @@[:description nil _](deferred-tru "added a description")- [:description (_ :guard some?) _]+ [:description #'some? _](deferred-tru "changed the description")[:document _ _]@@ -97,7 +97,7 @@(deferred-tru "modified the query");; report_card.type- [:type (_ :guard #{:question "question"}) (_ :guard #{:model "model"})]+ [:type #{:question "question"} #{:model "model"}](deferred-tru "turned this to a model")[:type old new]diff --git a/src/metabase/util/match.clj b/src/metabase/util/match.cljindex f1cb69c5ce2..3709c11a35d 100644--- a/src/metabase/util/match.clj+++ b/src/metabase/util/match.clj@@ -15,14 +15,23 @@{:type :symbol:symbol pattern}+ ;; Var pattern (var fn-name) - the result of reader processing #'fn-name syntax.+ (and (seq? pattern) (= (first pattern) 'var) (= (count pattern) 2))+ {:type :guard+ :symbol '_+ :predicate (nth pattern 1)}+;; Guard pattern(and (seq? pattern) (symbol? (first pattern)) (>= (count pattern) 3))- (let [preds (apply hash-map (rest pattern))]- (cond-> {:type :guard- :symbol (nth pattern 0)- :predicate (nth pattern 2)}- (:guard preds) (assoc :predicate (:guard preds))- (:len preds) (assoc :length (:len preds))))+ (let [m (apply hash-map (rest pattern))+ {:keys [guard len]} m]+ (doseq [k (keys m)+ :when (not (#{:guard :len} k))]+ (throw (ex-info (str "Unsupported guard pattern key: " k) {})))+ {:type :guard+ :symbol (nth pattern 0)+ :predicate guard+ :length len});; (:or ...) pattern(and (seq? pattern) (= (first pattern) :or) (>= (count pattern) 2))@@ -272,6 +281,8 @@- (sym :guard pred :len size) - bind with predicate check. The predicate should either be a symbol denoting afunction, keyword, set, or an invocation snippet (but not a lambda). Can optionallycheck for collection length.+ - #'pred - same as (_ :guard pred) - just a predicate check without binding to a symbol. Note that even though it+ looks like a var, nothing is resolved this way, and you can even use it as #'local-fn, but you shouldn't.- vector - binds positional values inside a sequence against other patterns. Can have & to bind remaining elements.- map - binds associative values inside a map against other patterns. Special symbols can be used as patterns:`&truthy` - matches if the map contains any truthy value for the keydiff --git a/test/metabase/agent_lib/representations/repair_test.clj b/test/metabase/agent_lib/representations/repair_test.cljindex 04e4a80385b..d50f5da494f 100644--- a/test/metabase/agent_lib/representations/repair_test.clj+++ b/test/metabase/agent_lib/representations/repair_test.clj@@ -2001,12 +2001,11 @@(deftest ^:parallel idempotency-unwrapped-boolean-wrapper-test(testing "unwrapping a boolean wrapper that is the sole element of a parent vector stays idempotent"- ;; Regression for a non-idempotency the generative idempotency-property-test surfaced:- ;; `["true" {} x]` unwraps to `x`. For a scalar `x`, `unwrap-boolean-wrapper` emits a clause- ;; `[x {}]` rather than the bare scalar, so a sole-element parent stays `[[x {}]]` instead of- ;; collapsing to `[x]` - which a later `repair` pass would otherwise "fix" to `[x {}]`, breaking- ;; the fixed point. Any non-blank scalar triggered it (the shrunk counterexample minimised `x`- ;; to a single NUL char).+ ;; Regression for a non-idempotency the generative idempotency-property-test surfaced: `["true" {} x]` unwraps to+ ;; `x`. For a scalar `x`, emits a clause `[x {}]` rather than the bare scalar, so a sole-element parent stays `[[x+ ;; {}]]` instead of collapsing to `[x]` - which a later `repair` pass would otherwise "fix" to `[x {}]`, breaking+ ;; the fixed point. Any non-blank scalar triggered it (the shrunk counterexample minimised `x` to a single NUL+ ;; char).(let [once (repair/repair trivial-mp [["true" {} "x"]])](is (= [["x" {}]] once)"the wrapped scalar is emitted as a clause, leaving the parent vector intact")diff --git a/test/metabase/util/match_test.cljc b/test/metabase/util/match_test.cljcindex b89bf95b89f..beb36947af4 100644--- a/test/metabase/util/match_test.cljc+++ b/test/metabase/util/match_test.cljc@@ -38,7 +38,7 @@(t/is (= [41];; return just the dest IDs of Fields in a fk-> clause(match/match-many a-query- [:field dest-id {:source-field (_ :guard integer?)}] (inc dest-id))))+ [:field dest-id {:source-field #'integer?}] (inc dest-id))))(t/is (= [10 20](match/match-many (:breakout a-query) [:field id nil] id)))))@@ -210,7 +210,7 @@(t/is (= {:fields [[:field 1 nil][:magical-field [:field 2 {:temporal-unit :day}]][:magical-field [:field 4 {:source-field 3, :temporal-unit :month}]]]}- (match/replace another-query [:field _ (_ :guard :temporal-unit)] [:magical-field &match])))))+ (match/replace another-query [:field _ {:temporal-unit &truthy}] [:magical-field &match])))))(t/deftest ^:parallel replace-&parents-test(t/testing "can we use the anaphor `&parents` to look at the parents of the match?"@@ -233,7 +233,7 @@(match/replace {:filter [:and[:= [:field 1 nil] 4000][:= [:field 2 nil] 5000]]}- (_ :guard integer?)+ #'integer?(when (= := (last &parents))(float &match)))))))@@ -245,7 +245,7 @@[:field 1 {:temporal-unit :day}][:absolute-datetime #inst "2016-11-08T00:00:00.000-00:00" :day]][:= [:field 100 nil] 20]]- [_ [:field _ (_ :guard :temporal-unit)] & _] nil)))))+ [_ [:field _ {:temporal-unit &truthy}] & _] nil)))))(t/deftest ^:parallel replace-short-circut-test(t/testing (str "can we use short-circuting patterns to do something tricky like only replace `:field-id` clauses that "@@ -320,11 +320,11 @@(t/deftest ^:parallel match-one-and-syntax(t/is (= 10 (match/match-one [1 2 3]- (:and [a b c] (_ :guard vector?)) (* a 10))))+ (:and [a b c] #'vector?) (* a 10))))(t/is (= nil (match/match-one [1 2 3]- (:and [a b c] (_ :guard map?)) (* a 10))))+ (:and [a b c] #'map?) (* a 10))))(t/is (= nil (match/match-one [1 2 3]- (:and [a b] (_ :guard vector?)) (* a 10))))+ (:and [a b] #'vector?) (* a 10))))(t/is (= 6 (match/match-one [1 2 3](:and [a b c] (v :guard vector?)) (reduce * 1 v))))(t/testing "later patterns can refer to earlier bindings"@@ -373,8 +373,8 @@[(a :guard (odd? a))] a[(b :guard (even? b))] (- b))))(t/is (= -2 (match/match-one [2]- [(_ :guard odd?)] 1- [(_ :guard even?)] -2)))+ [#'odd?] 1+ [#'even?] -2)))(t/is (= 2 (match/match-one [{:b 2}][(_ :guard :a)] 1[(_ :guard :b)] 2)))@@ -387,6 +387,14 @@(eval '(match/match-one [1][(a :guard (fn [x] (odd? x)))] a))))))+(t/deftest ^:parallel guard-option-keys-test+ #?(:clj+ (t/is (thrown-with-msg? Exception #"Syntax error macroexpanding"+ (macroexpand '(metabase.util.match/match-one 2 (x :gaurd odd?) x)))))+ (t/is (= [1 2] (match/match-one [[1 2]] [(v :len 2)] v)))+ (t/is (= :hit (match/match-one :k (:or #'string? #'keyword?) :hit)))+ (t/is (= :hit (match/match-one [1 [2]] [_ & #'vector?] :hit))))+(t/deftest ^:parallel return-nil-matches-test(t/testing "a clause can return nil and that is still considered a match"(t/is (= nil (match/match-one [:a nil]@@ -403,13 +411,13 @@(t/is (= [6 15] (match/match-many [[1 2 3] [4 5 6]][a b c] (+ a b c))))(t/is (= [1 2 3 4 5 6] (match/match-many [[1 2 3] [4 5 6]]- (_ :guard number?) &match)))+ #'number? &match)))(t/is (= [100] (match/match-many [[1 2 3] [4 5 6]]- (_ :guard keyword?) &match+ #'keyword? &match_ 100)))(t/testing "absent of matches returns nil"(t/is (= nil (match/match-many [[1 2 3] [4 5 6]]- (_ :guard keyword?) &match))))+ #'keyword? &match))))(t/testing "nils aren't recorded into the result"(t/is (= [15] (match/match-many [[1 2 3] [4 5 6]][a b c] (when (> a 1)