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
Refactor match-lite and introduce :or clause (#67345)
Oleksandr Yakushev52f48e2400c7
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex b56f31f573a..4fee2430bd9 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -220,7 +220,8 @@;; misc config for built-in linters;;- :invalid-arity {:skip-args [metabase.lib.util.match/match]} ; TODO (cam): can we fix these?+ :invalid-arity {:skip-args [metabase.lib.util.match/match+ metabase.lib.util.match/match-lite]} ; TODO (cam): can we fix these?:refer-all {:level :warning, :exclude [clojure.test]}:unused-referred-var {:exclude {compojure.core [GET DELETE POST PUT]}}diff --git a/src/metabase/lib/fe_util.cljc b/src/metabase/lib/fe_util.cljcindex 7fc2a06218d..9edd307fff7 100644--- a/src/metabase/lib/fe_util.cljc+++ b/src/metabase/lib/fe_util.cljc@@ -372,31 +372,26 @@filter-clause :- ::lib.schema.expression/expression](let [ref->col #(column-metadata-from-ref query stage-number %)number-col? #(ref-clause-with-type? % [:type/Number])- number-arg? #(some? (expression-arg->number %))- result (fn [op col-ref values]- {:operator ({:in :=, :not-in :!=} op op)- :column (ref->col col-ref)- :values (mapv expression-arg->number values)})]+ number-arg? #(some? (expression-arg->number %))](lib.util.match/match-lite filter-clause- ;; no arguments- [(op :guard #{:is-null :not-null}) _ (col-ref :guard number-col?) & (args :len 0 :guard (every? number-arg? args))]- (result op col-ref args)+ (:or+ ;; no arguments+ [(op :guard #{:is-null :not-null}) _ (col-ref :guard number-col?) & (args :len 0 :guard (every? number-arg? args))]- ;; multiple arguments, `:=`- [(op :guard #{:= :in}) _ (col-ref :guard number-col?) & (args :guard (every? number-arg? args))]- (result op col-ref args)+ ;; multiple arguments, `:=`+ [(op :guard #{:= :in}) _ (col-ref :guard number-col?) & (args :guard (every? number-arg? args))]- ;; multiple arguments, `:!=`- [(op :guard #{:!= :not-in}) _ (col-ref :guard number-col?) & (args :guard (every? number-arg? args))]- (result op col-ref args)+ ;; multiple arguments, `:!=`+ [(op :guard #{:!= :not-in}) _ (col-ref :guard number-col?) & (args :guard (every? number-arg? args))]- ;; exactly 1 argument- [(op :guard #{:> :>= :< :<=}) _ (col-ref :guard number-col?) & (args :len 1 :guard (every? number-arg? args))]- (result op col-ref args)+ ;; exactly 1 argument+ [(op :guard #{:> :>= :< :<=}) _ (col-ref :guard number-col?) & (args :len 1 :guard (every? number-arg? args))]- ;; exactly 2 arguments- [(op :guard #{:between}) _ (col-ref :guard number-col?) & (args :len 2 :guard (every? number-arg? args))]- (result op col-ref args))))+ ;; exactly 2 arguments+ [(op :guard #{:between}) _ (col-ref :guard number-col?) & (args :len 2 :guard (every? number-arg? args))])+ {:operator ({:in :=, :not-in :!=} op op)+ :column (ref->col col-ref)+ :values (mapv expression-arg->number args)})))(def ^:private CoordinateFilterParts[:map@@ -433,30 +428,25 @@:values (mapv expression-arg->number args)}lon-col-ref (assoc :longitude-column (ref->col lon-col-ref))))];; Separated into two match calls to allow `match-lite` macro to better group things.- (or (lib.util.match/match-lite filter-clause- ;; multiple arguments, `:=`- [(op :guard #{:= :in}) _ (col-ref :guard coordinate-col?) & (args :guard (every? number-arg? args))]- (result op col-ref nil args)-- ;; multiple arguments, `:!=`- [(op :guard #{:!= :not-in}) _ (col-ref :guard coordinate-col?) & (args :guard (every? number-arg? args))]- (result op col-ref nil args)-- ;; exactly 1 argument- [(op :guard #{:> :>= :< :<=}) _ (col-ref :guard coordinate-col?) & (args :len 1 :guard (every? number-arg? args))]- (result op col-ref nil args)-- ;; exactly 2 arguments- [(op :guard #{:between}) _ (col-ref :guard coordinate-col?) & (args :len 2 :guard (every? number-arg? args))]- (result op col-ref nil args))- (lib.util.match/match-lite filter-clause- ;; exactly 4 arguments- [(op :guard #{:inside})- _- (lat-col-ref :guard coordinate-col?)- (lon-col-ref :guard coordinate-col?)- & (args :len 4 :guard (every? number-arg? args))]- (result op lat-col-ref lon-col-ref args)))))+ (lib.util.match/match-lite filter-clause+ (:or+ ;; multiple arguments, `:=`+ [(op :guard #{:= :in}) _ (col-ref :guard coordinate-col?) & (args :guard (every? number-arg? args))]+ ;; multiple arguments, `:!=`+ [(op :guard #{:!= :not-in}) _ (col-ref :guard coordinate-col?) & (args :guard (every? number-arg? args))]+ ;; exactly 1 argument+ [(op :guard #{:> :>= :< :<=}) _ (col-ref :guard coordinate-col?) & (args :len 1 :guard (every? number-arg? args))]+ ;; exactly 2 arguments+ [(op :guard #{:between}) _ (col-ref :guard coordinate-col?) & (args :len 2 :guard (every? number-arg? args))])+ (result op col-ref nil args)++ ;; exactly 4 arguments+ [(op :guard #{:inside})+ _+ (lat-col-ref :guard coordinate-col?)+ (lon-col-ref :guard coordinate-col?)+ & (args :len 4 :guard (every? number-arg? args))]+ (result op lat-col-ref lon-col-ref args))))(def ^:private BooleanFilterParts[:map@@ -481,12 +471,11 @@(let [ref->col #(column-metadata-from-ref query stage-number %)boolean-col? #(ref-clause-with-type? % [:type/Boolean])](lib.util.match/match-lite filter-clause- ;; no arguments- [(op :guard #{:is-null :not-null}) _ (col-ref :guard boolean-col?) & (args :len 0 :guard (every? boolean? args))]- {:operator op, :column (ref->col col-ref), :values (vec args)}-- ;; exactly 1 argument- [(op :guard #{:=}) _ (col-ref :guard boolean-col?) & (args :len 1 :guard (every? boolean? args))]+ (:or+ ;; no arguments+ [(op :guard #{:is-null :not-null}) _ (col-ref :guard boolean-col?) & (args :len 0 :guard (every? boolean? args))]+ ;; exactly 1 argument+ [(op :guard #{:=}) _ (col-ref :guard boolean-col?) & (args :len 1 :guard (every? boolean? args))]){:operator op, :column (ref->col col-ref), :values (vec args)})))(def ^:private SpecificDateFilterParts@@ -522,12 +511,12 @@(when (every? u.time/valid? values){:operator op, :column (ref->col col-ref), :values values, :with-time? (not date?)})))](lib.util.match/match-lite filter-clause- ;; exactly 1 argument- [(op :guard #{:= :> :<}) _ (col-ref :guard date-col?) & (args :len 1 :guard (every? string? args))]- (result op col-ref args)+ (:or+ ;; exactly 1 argument+ [(op :guard #{:= :> :<}) _ (col-ref :guard date-col?) & (args :len 1 :guard (every? string? args))]- ;; exactly 2 arguments- [(op :guard #{:between}) _ (col-ref :guard date-col?) & (args :len 2 :guard (every? string? args))]+ ;; exactly 2 arguments+ [(op :guard #{:between}) _ (col-ref :guard date-col?) & (args :len 2 :guard (every? string? args))])(result op col-ref args))))(def ^:private RelativeDateFilterParts@@ -663,23 +652,18 @@stage-number :- :intfilter-clause :- ::lib.schema.expression/expression](let [ref->col #(column-metadata-from-ref query stage-number %)- time-col? #(ref-clause-with-type? % [:type/Time])- result (fn [op col-ref args]- (let [values (mapv u.time/coerce-to-time args)]- (when (every? u.time/valid? values)- {:operator op, :column (ref->col col-ref), :values values})))]+ time-col? #(ref-clause-with-type? % [:type/Time])](lib.util.match/match-lite filter-clause- ;; no arguments- [(op :guard #{:is-null :not-null}) _ (col-ref :guard time-col?) & (args :len 0 :guard (every? string? args))]- (result op col-ref args)-- ;; exactly 1 argument- [(op :guard #{:> :<}) _ (col-ref :guard time-col?) & (args :len 1 :guard (every? string? args))]- (result op col-ref args)-- ;; exactly 2 arguments- [(op :guard #{:between}) _ (col-ref :guard time-col?) & (args :len 2 :guard (every? string? args))]- (result op col-ref args))))+ (:or+ ;; no arguments+ [(op :guard #{:is-null :not-null}) _ (col-ref :guard time-col?) & (args :len 0 :guard (every? string? args))]+ ;; exactly 1 argument+ [(op :guard #{:> :<}) _ (col-ref :guard time-col?) & (args :len 1 :guard (every? string? args))]+ ;; exactly 2 arguments+ [(op :guard #{:between}) _ (col-ref :guard time-col?) & (args :len 2 :guard (every? string? args))])+ (let [values (mapv u.time/coerce-to-time args)]+ (when (every? u.time/valid? values)+ {:operator op, :column (ref->col col-ref), :values values})))))(def ^:private DefaultFilterParts[:mapdiff --git a/src/metabase/lib/remove_replace.cljc b/src/metabase/lib/remove_replace.cljcindex a0592765ea4..50ad40f026c 100644--- a/src/metabase/lib/remove_replace.cljc+++ b/src/metabase/lib/remove_replace.cljc@@ -163,10 +163,7 @@(remove-stage-references stage-number unmodified-query-for-stage target-uuid)(update-stale-references stage-number unmodified-query-for-stage))- (q :guard (and (vector? q)- (or (= q [:breakout])- (= q [:fields])- (and (= (nth q 0) :joins) (= (nth q 2) :fields) (= (count q) 3)))))+ (:or [:breakout] [:fields] [:joins _ :fields])(-> (remove-stage-references result stage-number unmodified-query-for-stage target-uuid)(update-stale-references stage-number unmodified-query-for-stage))diff --git a/src/metabase/lib/util/match.clj b/src/metabase/lib/util/match.cljindex fa47e1688f2..52220b55f65 100644--- a/src/metabase/lib/util/match.clj+++ b/src/metabase/lib/util/match.clj@@ -221,7 +221,7 @@:symbol pattern};; Guard pattern- (and (list? pattern) (>= (count pattern) 3))+ (and (list? pattern) (symbol? (first pattern)) (>= (count pattern) 3))(let [preds (apply hash-map (rest pattern))](cond-> {:type :guard:symbol (nth pattern 0)@@ -229,14 +229,18 @@(:guard preds) (assoc :predicate (:guard preds))(:len preds) (assoc :length (:len preds))))+ ;; (:or ...) pattern+ (and (list? pattern) (= (first pattern) :or) (>= (count pattern) 2))+ {:type :or+ :clauses (rest pattern)}+;; Vector pattern(vector? pattern)(let [[main-parts rest-parts] (vec (split-with (complement #{'&}) pattern))rest-part (second rest-parts)]{:type :vector:parts main-parts- :rest-part rest-part- :has-rest (some? rest-part)})+ :rest-part rest-part});; Map pattern(map? pattern)@@ -254,73 +258,77 @@:else(throw (ex-info "Invalid pattern" {:pattern pattern}))))-(defn- process-pattern- ([pattern value dont-ensure-vectors?]- (let [bindings (volatile! []), conditions (volatile! [])]- (process-pattern pattern value bindings conditions dont-ensure-vectors?)- {:bindings @bindings- :conditions @conditions}))- ([pattern value bindings conditions dont-ensure-vectors?]- (let [{:keys [parts rest-part predicate] :as parsed} (parse-pattern pattern)]- (case (:type parsed)- :symbol (when-not (= (:symbol parsed) '_)- (vswap! bindings conj [(:symbol parsed) value]))- :vector (let [s (if (symbol? value) value (gensym "vec"))- cnt (count parts)]- (when-not dont-ensure-vectors?- (vswap! bindings conj [s `(metabase.lib.util.match.impl/vector! ~value)]))- (dorun (map-indexed #(process-pattern %2 (list `nth s %1 nil) bindings conditions false) parts))- (if rest-part- (process-pattern rest-part (list `drop cnt value) bindings conditions false)- (vswap! conditions conj (list `metabase.lib.util.match.impl/count= s cnt))))- :map (let [s (if (symbol? value) value (gensym "map"))]- (vswap! bindings conj [s `(metabase.lib.util.match.impl/map! ~value)])- (run! (fn [[k v]] (process-pattern v (list `get s k) bindings conditions false)) (:map parsed)))- :guard (let [s (:symbol parsed)- bind (when-not (= s '_) s)- ;; Treat symbol, keyword, or set predicates as functions to be called, and thus transform them- ;; into invocation snippets. Be careful that if user doesn't want to bind the value in the- ;; guard (signified by `_`), we should pass the directly extracted value to the predicate,- ;; otherwise the binding.- predicate (if (or (symbol? predicate) (keyword? predicate) (set? predicate))- (list predicate (or bind value))- predicate)]- (when bind (vswap! bindings conj [bind value]))- (when predicate- ;; Make sure that the predicate is an invocation snippet, not a lambda as in regular `match` syntax.- (when (and (seq? predicate) ('#{fn fn*} (first predicate)))- (throw (ex-info "match-lite :guard predicate must be an invocation form or a symbol, not a lambda" {:predicate predicate})))- (vswap! conditions conj (with-meta (if (and (seq? predicate) (not= (first predicate) 'fn*))- predicate- (list predicate (or bind value)))- {:depends-on s})))- (when (:length parsed)- (vswap! conditions conj (with-meta (list `metabase.lib.util.match.impl/count= (or bind value) (:length parsed))+(declare process-clauses)++(defn- process-pattern [pattern value bindings conditions return]+ (let [{:keys [parts rest-part predicate] :as parsed} (parse-pattern pattern)]+ (case (:type parsed)+ :symbol (when-not (= (:symbol parsed) '_)+ (vswap! bindings conj [(:symbol parsed) value]))+ :vector (let [s (if (symbol? value) value (gensym "vec"))+ cnt (count parts)]+ (vswap! bindings conj (with-meta [s `(metabase.lib.util.match.impl/vector! ~value)]+ {:vector-check true}))+ (dorun (map-indexed #(process-pattern %2 (list `nth s %1 nil) bindings conditions return) parts))+ (if rest-part+ (process-pattern rest-part (list `drop cnt s) bindings conditions false)+ (vswap! conditions conj (with-meta (list `metabase.lib.util.match.impl/count= s cnt){:depends-on s}))))- :equality (vswap! conditions conj (list `= value (:value parsed)))- :set (vswap! conditions conj (list (:value parsed) value))))))+ :map (let [s (if (symbol? value) value (gensym "map"))]+ (vswap! bindings conj [s `(metabase.lib.util.match.impl/map! ~value)])+ (run! (fn [[k v]] (process-pattern v (list `get s k) bindings conditions false)) (:map parsed)))+ :or (let [or-clauses (:clauses parsed)+ new-body (process-clauses (mapv vector (:clauses parsed) (repeat (count or-clauses) @return)) value nil)]+ (vreset! return new-body))+ :guard (let [s (:symbol parsed)+ s (if (= s '_) (gensym "_") s)+ ;; Treat symbol, keyword, or set predicates as functions to be called, and thus transform them+ ;; into invocation snippets. Be careful that if user doesn't want to bind the value in the+ ;; guard (signified by `_`), we should pass the directly extracted value to the predicate,+ ;; otherwise the binding.+ predicate (if (or (symbol? predicate) (keyword? predicate) (set? predicate))+ (list predicate s)+ predicate)]+ (vswap! bindings conj [s value])+ (when predicate+ ;; Make sure that the predicate is an invocation snippet, not a lambda as in regular `match` syntax.+ (when (and (seq? predicate) ('#{fn fn*} (first predicate)))+ (throw (ex-info "match-lite :guard predicate must be an invocation form or a symbol, not a lambda" {:predicate predicate})))+ (vswap! conditions conj (with-meta (if (and (seq? predicate) (not= (first predicate) 'fn*))+ predicate+ (list predicate s))+ {:depends-on s})))+ (when (:length parsed)+ (vswap! conditions conj (with-meta (list `metabase.lib.util.match.impl/count= s (:length parsed))+ {:depends-on s}))))+ :equality (vswap! conditions conj (list `= value (:value parsed)))+ :set (vswap! conditions conj (list (:value parsed) value)))))++(defn- process-clause [[pattern ret] value-sym]+ (let [bindings (volatile! []), conditions (volatile! []) return (volatile! ret)]+ (process-pattern pattern value-sym bindings conditions return)+ {:bindings @bindings+ :conditions @conditions+ :return @return}))(defn- seq-contains? [coll item](some #(= % item) coll))-(defn- collect-common [processed-patterns]- (let [all-bindings (mapv :bindings processed-patterns)- common-bindings (filter (fn [bind] (every? #(seq-contains? % bind) all-bindings))- (first all-bindings))-- all-conditions (mapv :conditions processed-patterns)- common-conditions (filter (fn [condition] (and (every? #(seq-contains? % condition) all-conditions)+(defn- collect-common [bindings conditions]+ (let [common-bindings (filter (fn [bind] (every? #(seq-contains? % bind) bindings))+ (first bindings))+ common-conditions (filter (fn [condition] (and (every? #(seq-contains? % condition) conditions);; Ensure that variable for common condition is already bound.(seq-contains? (map first common-bindings)(:depends-on (meta condition)))))- (first all-conditions))]+ (first conditions))]{:common-bindings common-bindings:common-conditions (->> common-conditions(mapv #(vary-meta % dissoc :depends-on))):all-bindings (mapv (fn [bindings](remove #(seq-contains? common-bindings %) bindings))- all-bindings)- :all-conditions (->> all-conditions+ bindings)+ :all-conditions (->> conditions(mapv (fn [conditions](->> conditions(remove #(seq-contains? common-conditions %))@@ -346,6 +354,37 @@1 (first args)`(if-some [a# ~(first args)] a# ~(expand-or-some (rest args)))))+(defn- emit-clause [{:keys [common-bindings common-conditions all-bindings all-conditions]}+ returns value-sym value-binding]+ (let [same-return? (and (apply = returns)+ ;; Only allow extracting same result if there are no individual bindings in branches.+ (every? empty? all-bindings))+ ;; If all clauses check for vector, hoist the check into the let binding.+ common-vector-check? (some #(:vector-check (meta %)) common-bindings)+ common-bindings (remove #(:vector-check (meta %)) common-bindings)+ value-binding (if common-vector-check?+ `(metabase.lib.util.match.impl/vector! ~(or value-binding value-sym))+ value-binding)]+ `(let [~@(when (some? value-binding)+ [value-sym value-binding])+ ~@(mapcat identity common-bindings)]+ ~(expand-conditions+ `and common-conditions+ (if (and same-return? (> (count returns) 1))+ `(when (or ~@(mapv (fn [bindings conditions]+ (expand-bindings bindings (expand-conditions `and conditions true true)))+ all-bindings all-conditions))+ ~(first returns))+ (expand-or-some+ (mapv (fn [bindings conditions return-expr]+ (expand-bindings bindings (expand-conditions `and conditions return-expr)))+ all-bindings all-conditions returns)))))))++(defn- process-clauses [clauses value-sym value-binding]+ (let [processed (mapv #(process-clause % value-sym) clauses)+ collected (collect-common (map :bindings processed) (map :conditions processed))]+ (emit-clause collected (mapv :return processed) value-sym value-binding)))+(defn- match-lite* [value clauses recursive?](when (odd? (count clauses))(throw (ex-info "match-lite requires even number of clauses" {})))@@ -353,34 +392,12 @@[pairs default] (if (= (first (last pairs)) '_)[(butlast pairs) (second (last pairs))][pairs nil])- all-vectors? (every? vector? (map first pairs))- value-sym (if (and (symbol? value) (not recursive?))- value- (gensym "value"))- processed-patterns (for [[pattern _] pairs]- (process-pattern pattern value-sym all-vectors?))- {:keys [common-bindings common-conditions all-bindings all-conditions]}- (collect-common processed-patterns)- same-result? (and (apply = (map second pairs))- ;; Only allow extracting same result if there are no individual bindings in branches.- (every? empty? all-bindings))- value-binding (if (or (= value-sym value) recursive?)- [] [value-sym value])- body `(let [~@value-binding- ~@(when all-vectors?- [value-sym `(metabase.lib.util.match.impl/vector! ~value-sym)])- ~@(vec (mapcat identity common-bindings))]- ~(expand-conditions- `and common-conditions- (if (and same-result? (> (count pairs) 1))- `(when (or ~@(mapv (fn [bindings conditions]- (expand-bindings bindings (expand-conditions `and conditions true true)))- all-bindings all-conditions))- ~(second (first pairs)))- (expand-or-some- (mapv (fn [bindings conditions [_ return-expr]]- (expand-bindings bindings (expand-conditions `and conditions return-expr)))- all-bindings all-conditions pairs)))))]+ ;; Wrap explicit nil values.+ value (if (nil? value) `(identity nil) value)+ [value-sym value-binding] (cond recursive? [(gensym "value") nil]+ (symbol? value) [value nil]+ :else [(gensym "value") value])+ body (process-clauses pairs value-sym value-binding)](if recursive?(let [f (gensym "f")]`((fn ~f [~value-sym]@@ -409,7 +426,9 @@- keyword - must match exactly- set - must be one of the set items- (sym :guard pred :len size) - bind with predicate check. The predicate should either be a symbol denoting a function, keyword, set, or an invocation snippet (but not a lambda). Can optionally check for collection length.- - vector - binds positional values inside a sequence against other patterns. Can have & to bind remaining elements."+ - 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.+ - (:or clause1 clause2 ...) - special syntax for grouping several alternative conditions that share the same returned value."{:style/indent :defn}[value & clauses](match-lite* value clauses false))diff --git a/test/metabase/lib/util/match_test.cljc b/test/metabase/lib/util/match_test.cljcindex 275e24be74f..1105d83b035 100644--- a/test/metabase/lib/util/match_test.cljc+++ b/test/metabase/lib/util/match_test.cljc@@ -356,6 +356,22 @@true :true-valuefalse :false-value))))))+(t/deftest ^:parallel match-lite-or-syntax+ (t/is (= 10 (lib.util.match/match-lite [1 2 3]+ (:or [a] [a b] [a b c]) (* a 10))))+ (t/is (= nil (lib.util.match/match-lite [1 2 3]+ (:or [(a :guard even?) b] [a (b :guard odd?)]) [* a b])))+ (t/testing ":or can mix with other patterns"+ (t/is (= 20 (lib.util.match/match-lite [1 2 3]+ [a b c d] 10+ (:or [a b] [a b c]) 20+ _ 30))))+ (t/testing "doesn't break if same symbols are used for different bindings"+ (t/is (= 1 (lib.util.match/match-lite [1 2]+ (:or [(a :guard even?) b]+ [b a])+ b)))))+(t/deftest ^:parallel same-result-with-different-bindings-test(t/testing "result here should not be treated as a common because it refers to different bindings in branches"(t/is (= 1 (lib.util.match/match-lite [1 2]