Skip to content

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

QP desugar middleware => Lib (#62319)

Cam Saul6f77396704bb
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index ac3ff0e5705..90c478b3459 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -589,6 +589,8 @@
metabase.lib.field
metabase.lib.field.resolution
metabase.lib.filter
+ metabase.lib.filter.desugar
+ metabase.lib.filter.desugar.jvm
metabase.lib.init
metabase.lib.join.util
metabase.lib.metadata
diff --git a/bin/cljfmt-updated.sh b/bin/cljfmt-updated.sh
deleted file mode 100755
index fe8e74870ff..00000000000
--- a/bin/cljfmt-updated.sh
+++ /dev/null
@@ -1,43 +0,0 @@
-#! /usr/bin/env bash
-
-# Reformat files that have changed since the last commit. See also `cljfmt_staged.sh` which is meant to be used as a
-# commit hook, or `kondo-updated.sh` for doing the same thing
-#
-# By default, reformats uncommitted changes i.e. files that are different compared to HEAD. You can choose a different
-# target to diff against e.g. `master` as follows:
-#
-# ./bin/cljfmt-updated.sh master
-
-set -euo pipefail
-
-echo "This script is deprecated. Please use mage instead."
-echo "see:"
-echo "./bin/mage"
-
-# make sure we're in the root dir of the metabase repo i.e. the parent dir of the dir this script lives in
-script_dir=`dirname "${BASH_SOURCE[0]}"`
-cd "$script_dir/.."
-
-if [ -n "${1:-}" ]; then
- diff_target="$1"
-else
- diff_target="HEAD"
-fi
-
-echo "Formatting Clojure source files that have changes compared to $diff_target..."
-
-UPDATED_FILES=$(git diff --name-only "$diff_target" -- '*.clj' '*.cljc' '*.cljs')
-
-if [ -z "$UPDATED_FILES" ]; then
- echo 'No updated Clojure source files.'
- exit 0
-fi
-
-args=()
-for file in $UPDATED_FILES; do
- args+=("\"$file\"")
-done
-
-set -x
-
-clojure -T:cljfmt fix "{:paths [${args[*]}]}"
diff --git a/bin/cljfmt_staged.sh b/bin/cljfmt_staged.sh
deleted file mode 100755
index 25c3891ebfe..00000000000
--- a/bin/cljfmt_staged.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-#! /usr/bin/env bash
-
-# Reformat staged clj, cljc, and cljs files
-# Will print the results of the call. Will return an error (stopping the commit stage) if any files are reformatted.
-#
-# This is not a custom reformatter.
-# In the event that do you want to do some manual reformatting, you can do this:
-# clojure -T:cljfmt fix ;; Reformat everything
-
-set -euo pipefail
-
-echo "This script is deprecated. Please use mage instead."
-echo "see:"
-echo "./bin/mage"
-
-STAGED_FILES=$(git diff --name-status --cached -- "*.clj" "*.cljc" "*.cljs" | grep -E '[AM]' | cut -f2 || true)
-
-if [ "${#STAGED_FILES}" -gt 0 ]; then
- args=()
- for file in $STAGED_FILES; do
- args+=("\"$file\"")
- done
-
- output=$(clojure -T:cljfmt fix "{:paths [${args[*]}]}" 2>&1)
-
- if [ -n "$output" ]; then
- echo $output
- else
- echo "All staged clj, cljc, or cljs formatted correctly"
- fi
-else
- echo "No staged clj, cljc, or cljs files to format"
-fi
diff --git a/bin/kondo-updated.sh b/bin/kondo-updated.sh
deleted file mode 100755
index aac3720f8dd..00000000000
--- a/bin/kondo-updated.sh
+++ /dev/null
@@ -1,42 +0,0 @@
-#! /usr/bin/env bash
-
-# Run Kondo against files that have changed since the last commit. See also `cljfmt-updated.sh`
-#
-# By default, lints uncommitted changes i.e. files that are different compared to HEAD. You can choose a different
-# target to diff against e.g. `master` as follows:
-#
-# ./bin/kondo-updated.sh master
-
-echo "This script is deprecated. Please use mage instead."
-echo "see:"
-echo "./bin/mage"
-
-set -euo pipefail
-
-# make sure we're in the root dir of the metabase repo i.e. the parent dir of the dir this script lives in
-script_dir=`dirname "${BASH_SOURCE[0]}"`
-cd "$script_dir/.."
-
-if [ -n "${1:-}" ]; then
- diff_target="$1"
-else
- diff_target="HEAD"
-fi
-
-echo "Linting Clojure source files that have changes compared to $diff_target..."
-
-# ignore files in the Kondo config directory and dev directory
-UPDATED_FILES=$(git diff --name-only "$diff_target" -- '*.clj' '*.cljc' '*.cljs' ':!/.clj-kondo' ':!/dev')
-
-if [ -z "$UPDATED_FILES" ]; then
- echo 'No updated Clojure source files.'
- exit 0
-fi
-
-command="clojure -M:kondo --lint ${UPDATED_FILES[*]}"
-
-set -x
-
-
-
-$command
diff --git a/bin/kondo.sh b/bin/kondo.sh
deleted file mode 100755
index 265031c6c92..00000000000
--- a/bin/kondo.sh
+++ /dev/null
@@ -1,63 +0,0 @@
-#! /usr/bin/env bash
-
-# Convenience for running clj-kondo.
-#
-# You can also run with specific arguments like
-#
-# ./bin/kondo.sh --lint src
-#
-# If no arguments are passed, it uses the `:kondo/all` alias which runs Kondo against all directories.
-
-set -euo pipefail
-
-echo "This script is deprecated. Please use mage instead."
-echo "see:"
-echo "./bin/mage"
-echo "and"
-echo "./bin/mage kondo -h"
-
-# make sure we're in the root dir of the metabase repo i.e. the parent dir of the dir this script lives in
-script_dir=`dirname "${BASH_SOURCE[0]}"`
-cd "$script_dir/.."
-
-if [ -n "${1:-}" ]; then
- init_cache="false"
- command="clojure -M:kondo $@"
-else
- init_cache="true"
- command="clojure -M:kondo:kondo/all"
-fi
-
-# Copy over Kondo configs from libraries we use.
-
-DEPS_EDN_CHECKSUM_FILE=".clj-kondo/.deps.edn.md5sum"
-
-if [ -f $DEPS_EDN_CHECKSUM_FILE ]; then
- previous_deps_edn_checksum=$(cat $DEPS_EDN_CHECKSUM_FILE)
-else
- previous_deps_edn_checksum=""
-fi
-
-current_deps_edn_checksum=$(md5sum deps.edn)
-
-if [ "$previous_deps_edn_checksum" != "$current_deps_edn_checksum" ]; then
- clojure -M:kondo --copy-configs --dependencies --lint "$(clojure -A:dev -Spath)" --skip-lint --parallel
- echo "$current_deps_edn_checksum" > $DEPS_EDN_CHECKSUM_FILE
-fi
-
-# Clear cache and delete the broken type signatures automatically generated by Malli.
-#
-# TODO -- it's only really important to clear the cache when we switch branches; maybe we can keep track of what
-# branch we last ran on and only clear the cache when it changes.
-
-rm -rf .clj-kondo/metosin/malli-types-clj/
-rm -rf .clj-kondo/.cache
-
-# Initialize cache required for `hooks.metabase.test.data/dataset` hook. Only when running the full set of things
-if [ "$init_cache" = "true" ]; then
- clojure -M:kondo --dependencies --lint "test/metabase/test/data/dataset_definitions.clj"
-fi
-
-set -x
-
-$command
diff --git a/modules/drivers/druid/src/metabase/driver/druid/query_processor.clj b/modules/drivers/druid/src/metabase/driver/druid/query_processor.clj
index 67e08793028..169b468bb21 100644
--- a/modules/drivers/druid/src/metabase/driver/druid/query_processor.clj
+++ b/modules/drivers/druid/src/metabase/driver/druid/query_processor.clj
@@ -307,6 +307,8 @@
(-> (driver-api/replace filter-clause
[_ [:field _ (_ :guard :temporal-unit)] & _]
nil)
+ ;; TODO (Cam 8/18/25) -- I am 90% sure this is serving no useful purpose.
+ #_{:clj-kondo/ignore [:deprecated-var]}
driver-api/simplify-compound-filter
parse-filter*))
diff --git a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
index 8125b0b1620..54e7e1a11fe 100644
--- a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
+++ b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
@@ -138,6 +138,7 @@
;; 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/src/metabase/driver/sql/parameters/substitution.clj b/src/metabase/driver/sql/parameters/substitution.clj
index 67bf5672704..a766ef5ac32 100644
--- a/src/metabase/driver/sql/parameters/substitution.clj
+++ b/src/metabase/driver/sql/parameters/substitution.clj
@@ -317,6 +317,7 @@
(params.ops/operator? param-type)
(->> (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,6 +326,7 @@
(params.dates/exclusion-date-type param-type value)
(let [field-clause (field->field-filter-clause driver field param-type value)]
(->> (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/legacy_mbql/jvm_util.clj b/src/metabase/legacy_mbql/jvm_util.clj
index 9a198dc106d..5a51bbd87e4 100644
--- a/src/metabase/legacy_mbql/jvm_util.clj
+++ b/src/metabase/legacy_mbql/jvm_util.clj
@@ -2,104 +2,20 @@
"This namespace contains functionality that is not compatible with js, hence can not be stored in correspoding
cljc ns, ie. [[metabase.legacy-mbql.util]]."
(:require
+ [metabase.lib.filter.desugar.jvm :as lib.filter.desugar.jvm]
[metabase.lib.util.match :as lib.util.match]))
-;;;; Following regex definitions are incompatible with Safari browser. Code is unused on FE.
-
-(def ^:private host-regex
- ;; Extracts the "host" from a URL or an email.
- ;; By host we mean the main domain name and the TLD, eg. metabase.com, amazon.co.jp, bbc.co.uk.
- ;; For a URL, this is not the RFC3986 "host", which would include any subdomains and the optional `:3000` port number.
- ;;
- ;; For an email, this is generally the part after the @, but it will skip any subdomains:
- ;; [email protected] -> mycompany.net
- ;;
- ;; Referencing the indexes below:
- ;; 1. Positive lookbehind:
- ;; Just past one of:
- ;; 2. @ from an email or URL userinfo@ prefix
- ;; 3. // from a URL scheme
- ;; 4. . from a previous subdomain segment
- ;; 5. Start of string
- ;; 6. Negative lookahead: don't capture www as part of the domain
- ;; 7. Main domain segment
- ;; 8. Ending in a dot
- ;; 9. Optional short final segment (eg. co in .co.uk)
- ;; 10. Top-level domain
- ;; 11. Optional :port, /path, ?query or #hash
- ;; 12. Anchor to the end
- ;;1 2 3 4 5 6 7 8 9 10 11 12
- #"(?<=@|//|\.|^)(?!www\.)[^@\.:/?#]+\.(?:[^@\.:/?#]{1,3}\.)?[^@\.:/?#]+(?=[:/?#].*$|$)")
-
-(def ^:private domain-regex
- ;; Deliberately no ^ at the start; there might be several subdomains before this spot.
- ;; By "short tail" below, I mean a pseudo-TLD nested under a proper TLD. For example, mycompany.co.uk.
- ;; This can accidentally capture a short domain name, eg. "subdomain.aol.com" -> "subdomain", oops.
- ;; But there's a load of these, not a short list we can include here, so it's either preprocess the (huge) master list
- ;; from Mozilla or accept that this regex is a bit best-effort.
- ;; Referencing the indexes below:
- ;; 1. Positive lookbehind:
- ;; Just past one of:
- ;; 2. @ from an email or URL userinfo@ prefix
- ;; 3. // from a URL scheme
- ;; 4. . from a previous subdomain segment
- ;; 5. Start of string
- ;; 6. Negative lookahead: don't capture www as the domain
- ;; 7. One domain segment
- ;; 8. Positive lookahead:
- ;; Either:
- ;; 9. Short final segment (eg. .co.uk)
- ;; 10. Top-level domain
- ;; 11. Optional :port, /path, ?query or #hash
- ;; 12. Anchor to end
- ;; Or:
- ;; 13. Top-level domain
- ;; 14. Optional :port, /path, ?query or #hash
- ;; 15. Anchor to end
- ;;1 2 3 4 5 6 7 (8 9 10 11 12| 13 14 15)
- #"(?<=@|//|\.|^)(?!www\.)[^@\.:/?#]+(?=\.[^@\.:/?#]{1,3}\.[^@\.:/?#]+(?:[:/?#].*)?$|\.[^@\.:/?#]+(?:[:/?#].*)?$)")
-
-(def ^:private subdomain-regex
- ;; This grabs the first segment that isn't "www", AND excludes the main domain name.
- ;; See [[domain-regex]] for more details about how those are matched.
- ;; Referencing the indexes below:
- ;; 1. Positive lookbehind:
- ;; Just past one of:
- ;; 2. @ from an email or URL userinfo@ prefix
- ;; 3. // from a URL scheme
- ;; 4. . from a previous subdomain segment
- ;; 5. Start of string
- ;; 6. Negative lookahead: don't capture www as the domain
- ;; 7. Negative lookahead: don't capture the main domain name or part of the TLD
- ;; That would look like:
- ;; 8. The next segment we *would* capture as the subdomain
- ;; 9. Optional short segment, like "co" in .co.uk
- ;; 10. Top-level domain
- ;; 11. Optionally more URL things: :port or /path or ?query or #fragment
- ;; 12. End of string
- ;; 13. Match the actual subdomain
- ;; 14. Positive lookahead: the . after the subdomain, which we want to detect but not capture.
- ;;1 2 3 4 5 6 7 8 9 10 11 12 13 14
- #"(?<=@|//|\.|^)(?!www\.)(?![^\.:/?#]+\.(?:[^\.:/?#]{1,3}\.)?[^\.:/?#]+(?:[:/?#].*)?$)[^\.:/?#]+(?=\.)")
-
-(def ^:private path-regex
- ;; this regex is just a hack. It's actually really hard to just match the path with a regex.
- ;; This will match
- ;; google.com/
- ;; google.com/abc
- ;; google.com/abc?hjfds
- #"(?<=\.[^/]{1,10})/[^#?]*")
-
(defn desugar-host-and-domain
"Unwrap host and domain."
+ {:deprecated "0.57.0"}
[expression]
(lib.util.match/replace
expression
[:host column]
- (recur [:regex-match-first column (str host-regex)])
+ (recur [:regex-match-first column (str lib.filter.desugar.jvm/host-regex)])
[:domain column]
- (recur [:regex-match-first column (str domain-regex)])
+ (recur [:regex-match-first column (str lib.filter.desugar.jvm/domain-regex)])
[:subdomain column]
- (recur [:regex-match-first column (str subdomain-regex)])
+ (recur [:regex-match-first column (str lib.filter.desugar.jvm/subdomain-regex)])
[:path column]
- (recur [:regex-match-first column (str path-regex)])))
+ (recur [:regex-match-first column (str lib.filter.desugar.jvm/path-regex)])))
diff --git a/src/metabase/legacy_mbql/normalize.cljc b/src/metabase/legacy_mbql/normalize.cljc
index 826648aa872..7ba3dd5864b 100644
--- a/src/metabase/legacy_mbql/normalize.cljc
+++ b/src/metabase/legacy_mbql/normalize.cljc
@@ -627,6 +627,7 @@
;; For `and`/`or`/`not` compound filters, recurse on the arg(s), then simplify the whole thing.
(defn- canonicalize-compound-filter-clause [[filter-name & args]]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(mbql.u/simplify-compound-filter
(into [filter-name]
;; we need to canonicalize any other mbql clauses that might show up in args here because
diff --git a/src/metabase/legacy_mbql/predicates.cljc b/src/metabase/legacy_mbql/predicates.cljc
index ee4d22c7d55..86e6819622f 100644
--- a/src/metabase/legacy_mbql/predicates.cljc
+++ b/src/metabase/legacy_mbql/predicates.cljc
@@ -2,13 +2,8 @@
"Predicate functions for checking whether something is a valid instance of a given MBQL clause."
(:require
[metabase.legacy-mbql.schema :as mbql.s]
- [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
[metabase.util.malli.registry :as mr]))
-(def ^{:arglists '([unit])} DateTimeUnit?
- "Is `unit` a valid datetime bucketing unit?"
- (mr/validator ::lib.schema.temporal-bucketing/unit))
-
(def ^{:arglists '([field-clause])} Field?
"Is this a valid Field clause?"
(mr/validator mbql.s/Field))
diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljc
index 685c676305b..a92f7be4fd7 100644
--- a/src/metabase/legacy_mbql/schema.cljc
+++ b/src/metabase/legacy_mbql/schema.cljc
@@ -26,6 +26,7 @@
[metabase.lib.schema.template-tag :as lib.schema.template-tag]
[metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
[metabase.util.i18n :as i18n]
+ [metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]))
;; A NOTE ABOUT METADATA:
@@ -45,6 +46,48 @@
;; the future we will likely add middleware that uses this metadata to automatically validate that a driver has the
;; features needed to run the query in question.
+(mr/def ::options-style
+ "For convenience of converting back and forth between MBQL 5, from now on we can record info about the options style
+ of a given clause you can do:
+
+ (defmethod options-style-method :field [_tag] ::options-style.last-always)"
+ [:enum
+ {:default ::options-style.none}
+ ;;
+ ;; this is the default style (options is unsupported)
+ ::options-style.none
+ ;;
+ ;; same style as MBQL 5; options map is always the first arg after the tag and we should use `{}` instead of `nil`
+ ;; for empty options. `:lib/uuid` should be preserved here I think.
+ ::options-style.mbql-5
+ ;;
+ ;; like a `:field` ref, options are ALWAYS the last arg, but should be `nil` if the options map is empty.
+ ::options-style.last-always
+ ;;
+ ;; The same as but keys should be `snake_case` (`:value` uses this)
+ ::options-style.last-always.snake_case
+ ;;
+ ;; like a `:expression` ref, options is optional but should only be present if non-nil.
+ ::options-style.last-unless-empty
+ ;;
+ ;; for `:contains` and other string filters: style is `::options-style.last-unless-empty` if the clause has two
+ ;; args, otherwise it's basically the same as `::options-style.mbql-5` if it has > 3 args, altho `:lib/uuid`
+ ;; should not be kept on conversion to legacy
+ ::options-style.𝕨𝕚𝕝𝕕])
+
+(defmulti ^:private options-style-method
+ {:arglists '([tag])}
+ keyword)
+
+(defmethod options-style-method :default
+ [_tag]
+ ::options-style.none)
+
+(mu/defn options-style :- ::options-style
+ "The style of options a legacy MBQL clause supports."
+ [tag :- simple-keyword?]
+ (options-style-method tag))
+
;; `:day-of-week` depends on the [[metabase.lib-be.core/start-of-week]] Setting, by default Sunday.
;; 1 = first day of the week (e.g. Sunday)
;; 7 = last day of the week (e.g. Saturday)
@@ -213,6 +256,8 @@
value :any
type-info [:maybe ::ValueTypeInfo])
+(defmethod options-style-method :value [_tag] ::options-style.last-always.snake_case)
+
;;; ----------------------------------------------------- Fields -----------------------------------------------------
;; Expression *references* refer to a something in the `:expressions` clause, e.g. something like
@@ -224,6 +269,8 @@
expression-name ::lib.schema.common/non-blank-string
options (optional :map))
+(defmethod options-style-method :expression [_tag] ::options-style.last-unless-empty)
+
(defn valid-temporal-unit-for-base-type?
"Whether `temporal-unit` (e.g. `:day`) is valid for the given `base-type` (e.g. `:type/Date`). If either is `nil` this
will return truthy. Accepts either map of `field-options` or `base-type` and `temporal-unit` passed separately."
@@ -329,6 +376,8 @@
base-type
true))])
+(defmethod options-style-method :field [_tag] ::options-style.last-always)
+
(mr/def ::field
[:and
{:doc/title [:span [:code ":field"] " clause"]}
@@ -384,6 +433,8 @@
aggregation-clause-index :int
options (optional :map))
+(defmethod options-style-method :aggregation [_tag] ::options-style.last-unless-empty)
+
(mr/def ::Reference
[:schema
;; this is provided for the convenience of Lib which uses this schema for `:field-ref` in results metadata
@@ -400,6 +451,8 @@
expr [:or [:ref ::FieldOrExpressionDef] [:ref ::Aggregation]]
n ::lib.schema.expression.window/offset.n)
+(defmethod options-style-method :offset [_tag] ::options-style.mbql-5)
+
;;; -------------------------------------------------- Expressions ---------------------------------------------------
;; Expressions are "calculated column" definitions, defined once and then used elsewhere in the MBQL query.
@@ -738,6 +791,8 @@
value :any ;; normally a string, number, or bytes
options (optional [:map [:mode {:optional true} LiteralDatetimeModeString]]))
+(defmethod options-style-method :datetime [_tag] ::options-style.last-unless-empty)
+
(mr/def ::DatetimeExpression
(one-of + datetime-add datetime-subtract convert-timezone now date datetime today))
@@ -861,6 +916,7 @@
[:case-sensitive {:optional true} :boolean]])
(doseq [clause-keyword [::starts-with ::ends-with ::contains ::does-not-contain]]
+ (defmethod options-style-method (keyword (name clause-keyword)) [_tag] ::options-style.𝕨𝕚𝕝𝕕)
(mr/def clause-keyword
[:or
;; Binary form
@@ -879,9 +935,11 @@
(def starts-with
"Schema for a valid :starts-with clause."
(with-meta [:ref ::starts-with] {:clause-name :starts-with}))
+
(def ends-with
"Schema for a valid :ends-with clause."
(with-meta [:ref ::ends-with] {:clause-name :ends-with}))
+
(def contains
"Schema for a valid :contains clause."
(with-meta [:ref ::contains] {:clause-name :contains}))
@@ -918,6 +976,8 @@
unit [:ref ::RelativeDatetimeUnit]
options (optional TimeIntervalOptions))
+(defmethod options-style-method :time-interval [_tag] ::options-style.last-unless-empty)
+
(defclause ^:sugar during
field Field
value [:or ::lib.schema.literal/date ::lib.schema.literal/datetime]
@@ -982,9 +1042,13 @@
(defclause ^{:requires-features #{:basic-aggregations}} case
clauses CaseClauses, options (optional CaseOptions))
+(defmethod options-style-method :case [_tag] ::options-style.last-unless-empty)
+
(defclause ^:sugar ^{:requires-features #{:basic-aggregations}} [case:if if]
clauses CaseClauses, options (optional CaseOptions))
+(defmethod options-style-method :if [_tag] ::options-style.last-unless-empty)
+
(mr/def ::NumericExpression
(one-of + - / * coalesce length floor ceil round abs power sqrt exp log case case:if datetime-diff integer float
temporal-extract get-year get-quarter get-month get-week get-day get-day-of-week
@@ -1105,6 +1169,8 @@
aggregation UnnamedAggregation
options AggregationOptions)
+(defmethod options-style-method :aggregation-options [_tag] ::options-style.last-always)
+
(mr/def ::Aggregation
[:multi
{:error/message "aggregation clause or numeric expression"
diff --git a/src/metabase/legacy_mbql/schema/helpers.cljc b/src/metabase/legacy_mbql/schema/helpers.cljc
index 22228bc0424..6daf38a0571 100644
--- a/src/metabase/legacy_mbql/schema/helpers.cljc
+++ b/src/metabase/legacy_mbql/schema/helpers.cljc
@@ -57,7 +57,7 @@
"Impl of [[metabase.legacy-mbql.schema.macros/defclause]] macro. Creates a Malli schema."
[tag & arg-schemas]
[:and
- {:doc/title [:span [:code (pr-str tag)] " clause"]}
+ {:description (str "schema for a valid legacy MBQL " :tag " clause")}
[:fn
{:error/message (str "must be a `" tag "` clause")}
(partial is-clause? tag)]
diff --git a/src/metabase/legacy_mbql/schema/macros.clj b/src/metabase/legacy_mbql/schema/macros.clj
index 0613c004a25..4b81d9b24a7 100644
--- a/src/metabase/legacy_mbql/schema/macros.clj
+++ b/src/metabase/legacy_mbql/schema/macros.clj
@@ -34,7 +34,7 @@
clause-name
[clause-name clause-name])
clause-name-kw (keyword clause-name)
- clause-registry-name (keyword "metabase.legacy-mbql.schema" (name symb-name))]
+ clause-registry-name (keyword "metabase.legacy-mbql.schema" (name clause-name))]
`(do
(mr/register! ~clause-registry-name
(metabase.legacy-mbql.schema.helpers/clause ~clause-name-kw ~@(stringify-names arg-names-and-schemas)))
diff --git a/src/metabase/legacy_mbql/util.cljc b/src/metabase/legacy_mbql/util.cljc
index ffaa0cf88c8..c0cf4e28d14 100644
--- a/src/metabase/legacy_mbql/util.cljc
+++ b/src/metabase/legacy_mbql/util.cljc
@@ -47,7 +47,9 @@
;;; | Functions for manipulating queries |
;;; +----------------------------------------------------------------------------------------------------------------+
-(defn- combine-compound-filters-of-type [compound-type subclauses]
+(defn- combine-compound-filters-of-type
+ {:deprecated "0.57.0"}
+ [compound-type subclauses]
(mapcat #(lib.util.match/match-lite %
[(t :guard (= t compound-type)) & args]
args
@@ -58,7 +60,9 @@
(declare simplify-compound-filter)
(defn- simplify-and-or-filter
+ {:deprecated "0.57.0"}
[op args]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(let [args (distinct (filter some? args))]
(case (count args)
;; an empty filter, toss it
@@ -79,8 +83,13 @@
(defn simplify-compound-filter
"Simplify compound `:and`, `:or`, and `:not` compound filters, combining or eliminating them where possible. This
also fixes theoretically disallowed compound filters like `:and` with only a single subclause, and eliminates `nils`
- and duplicate subclauses from the clauses."
+ and duplicate subclauses from the clauses.
+
+ DEPRECATED: This will be removed in the near future.
+ Use [[metabase.lib.filter.simplify-compound/simplify-compound-filter]] going forward."
+ {:deprecated "0.57.0"}
[x]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(cond
;; look for filters in the values
(map? x) (update-vals x simplify-compound-filter)
@@ -107,13 +116,18 @@
(mu/defn combine-filter-clauses :- mbql.s/Filter
"Combine two filter clauses into a single clause in a way that minimizes slapping a bunch of `:and`s together if
- possible."
+ possible.
+
+ DEPRECATED: This will be removed in the near future. Use lib utils going forward."
+ {:deprecated "0.57.0"}
[filter-clause & more-filter-clauses]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(simplify-compound-filter (cons :and (cons filter-clause more-filter-clauses))))
;;; TODO (Cam 7/16/25) -- why does the LEGACY MBQL UTILS have STAGE STUFF IN IT!
-(defn ^:deprecated legacy-last-stage-number
+(defn legacy-last-stage-number
"Returns the canonical stage number of the last stage of the legacy `inner-query`."
+ {:deprecated "0.57.0"}
[inner-query]
(loop [{:keys [source-query qp/stage-had-source-card]} inner-query, n 0]
(if (or (nil? source-query)
@@ -146,6 +160,7 @@
(defn desugar-inside
"Rewrite `:inside` filter clauses as a pair of `:between` clauses."
+ {:deprecated "0.57.0"}
[m]
(lib.util.match/replace m
[:inside lat-field lon-field lat-max lon-min lat-min lon-max]
@@ -155,6 +170,7 @@
(defn desugar-is-null-and-not-null
"Rewrite `:is-null` and `:not-null` filter clauses as simpler `:=` and `:!=`, respectively."
+ {:deprecated "0.57.0"}
[m]
(lib.util.match/replace m
[:is-null field] [:= field nil]
@@ -163,6 +179,7 @@
(declare field-options)
(defn- emptyable?
+ {:deprecated "0.57.0"}
[clause]
(if (is-clause? #{:field :expression :aggregation} clause)
(-> clause
@@ -171,12 +188,14 @@
(isa? :metabase.lib.schema.expression/emptyable))
(mbql.preds/Emptyable? clause)))
-(defn desugar-is-empty-and-not-empty
+(defn- desugar-is-empty-and-not-empty
"Rewrite `:is-empty` and `:not-empty` filter clauses as simpler `:=` and `:!=`, respectively.
If `:not-empty` is called on `:metabase.lib.schema.expression/emptyable` type, expand check for empty string. For
non-`emptyable` types act as `:is-null`. If field has nil base type it is considered not emptyable expansion wise."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[:is-empty clause]
(if (emptyable? clause)
@@ -190,7 +209,9 @@
(defn- replace-field-or-expression
"Replace a field or expression inside :time-interval"
+ {:deprecated "0.57.0"}
[m unit]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[:field id-or-name opts]
[:field id-or-name (assoc opts :temporal-unit unit)]
@@ -199,9 +220,11 @@
(let [[_expression expression-name opts] &match]
[:expression expression-name (assoc opts :temporal-unit unit)])))
-(defn desugar-time-interval
+(defn- desugar-time-interval
"Rewrite `:time-interval` filter clauses as simpler ones like `:=` or `:between`."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[:time-interval field-or-expression n unit] (recur [:time-interval field-or-expression n unit nil])
@@ -251,7 +274,9 @@
(defn desugar-relative-time-interval
"Transform `:relative-time-interval` to `:and` expression."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace
m
[:relative-time-interval col value bucket offset-value offset-bucket]
@@ -272,7 +297,9 @@
(defn desugar-during
"Transform a `:during` expression to an `:and` expression."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace
m
[:during col value unit]
@@ -287,7 +314,9 @@
(defn desugar-if
"Transform a `:if` expression to an `:case` expression."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace
m
[:if & args]
@@ -295,7 +324,9 @@
(defn desugar-in
"Transform `:in` and `:not-in` expressions to `:=` and `:!=` expressions."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[:in & args]
(into [:=] args)
@@ -303,18 +334,20 @@
[:not-in & args]
(into [:!=] args)))
-(defn desugar-does-not-contain
+(defn- desugar-does-not-contain
"Rewrite `:does-not-contain` filter clauses as simpler `[:not [:contains ...]]` clauses.
Note that [[desugar-multi-argument-comparisons]] will have already desugared any 3+ argument `:does-not-contain` to
several `[:and [:does-not-contain ...] [:does-not-contain ...] ...]` clauses, which then get rewritten here into
`[:and [:not [:contains ...]] [:not [:contains ...]]]`."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[:does-not-contain & args]
[:not (into [:contains] args)]))
-(defn desugar-multi-argument-comparisons
+(defn- desugar-multi-argument-comparisons
"`:=`, `!=`, `:contains`, `:does-not-contain`, `:starts-with` and `:ends-with` clauses with more than 2 args
automatically get rewritten as compound filters.
@@ -326,7 +359,9 @@
`:ends-with` depending on the number of arguments. 2-argument forms use the legacy style `[:contains field x opts]`.
Multi-argument forms use pMBQL style with the options at index 1, **even if there are no options**:
`[:contains {} field x y z]`."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[:= field x y & more]
(apply vector :or (for [x (concat [x y] more)]
@@ -348,7 +383,9 @@
(defn desugar-current-relative-datetime
"Replace `relative-datetime` clauses like `[:relative-datetime :current]` with `[:relative-datetime 0 <unit>]`.
`<unit>` is inferred from the `:field` the clause is being compared to (if any), otherwise falls back to `default.`"
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[clause field & (args :guard (partial some (partial = [:relative-datetime :current])))]
(let [temporal-unit (or (lib.util.match/match-lite-recursive field
@@ -358,7 +395,7 @@
[:relative-datetime :current]
[:relative-datetime 0 temporal-unit])))))
-(def temporal-extract-ops->unit
+(def ^{:deprecated "0.57.0"} temporal-extract-ops->unit
"Mapping from the sugar syntax to extract datetime to the unit."
{[:get-year nil] :year-of-era
[:get-quarter nil] :quarter-of-year
@@ -375,25 +412,31 @@
[:get-minute nil] :minute-of-hour
[:get-second nil] :second-of-minute})
-(def ^:private temporal-extract-ops
+(def ^:private ^{:deprecated "0.57.0"} temporal-extract-ops
+ #_{:clj-kondo/ignore [:deprecated-var]}
(->> (keys temporal-extract-ops->unit)
(map first)
set))
-(defn desugar-temporal-extract
+(defn- desugar-temporal-extract
"Replace datetime extractions clauses like `[:get-year field]` with `[:temporal-extract field :year]`."
+ {:deprecated "0.57.0"}
[m]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace m
[(op :guard temporal-extract-ops) field & args]
[:temporal-extract field (temporal-extract-ops->unit [op (first args)])]))
-(defn- desugar-divide-with-extra-args [expression]
+(defn- desugar-divide-with-extra-args
+ {:deprecated "0.57.0"}
+ [expression]
(lib.util.match/replace expression
[:/ x y z & more]
(recur (into [:/ [:/ x y]] (cons z more)))))
(defn- temporal-case-expression
"Creates a `:case` expression with a condition for each value of the given unit."
+ {:deprecated "0.57.0"}
[column unit n]
(let [user-locale #?(:clj (i18n/user-locale)
:cljs nil)]
@@ -408,7 +451,9 @@
Uses the user's locale rather than the site locale, so the results will depend on the runner of the query, not just
the query itself. Filtering should be done based on the number, rather than the name."
+ {:deprecated "0.57.0"}
[expression]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(lib.util.match/replace expression
[:month-name column]
(recur (temporal-case-expression column :month-of-year 12))
@@ -420,7 +465,9 @@
(mu/defn desugar-expression :- ::mbql.s/FieldOrExpressionDef
"Rewrite various 'syntactic sugar' expressions like `:/` with more than two args into something simpler for drivers
to compile."
+ {:deprecated "0.57.0"}
[expression :- ::mbql.s/FieldOrExpressionDef]
+ #_{:clj-kondo/ignore [:deprecated-var]}
;; The `mbql.jvm-u/desugar-host-and-domain` is implemented only for jvm because regexes are not compatible with
;; Safari.
(let [desugar-host-and-domain* #?(:clj mbql.jvm-u/desugar-host-and-domain
@@ -432,7 +479,10 @@
desugar-host-and-domain*
desugar-temporal-names)))
-(defn- maybe-desugar-expression [clause]
+(defn- maybe-desugar-expression
+ {:deprecated "0.57.0"}
+ [clause]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(cond-> clause
(mbql.preds/FieldOrExpressionDef? clause) desugar-expression))
@@ -440,8 +490,13 @@
"Rewrite various 'syntatic sugar' filter clauses like `:time-interval` and `:inside` as simpler, logically
equivalent clauses. This can be used to simplify the number of filter clauses that need to be supported by anything
that needs to enumerate all the possible filter types (such as driver query processor implementations, or the
- implementation [[negate-filter-clause]] below.)"
+ implementation [[negate-filter-clause]] below.)
+
+ DEPRECATED: This will be removed in a future release. Use [[metabase.lib.core/desugar-filter-clause]] instead going
+ forward."
+ {:deprecated "0.57.0"}
[filter-clause :- mbql.s/Filter]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(-> filter-clause
desugar-current-relative-datetime
desugar-in
@@ -485,6 +540,7 @@
filter clause types). Useful for generating highly optimized filter clauses and for drivers that do not support
top-level `:not` filter clauses."
[filter-clause :- mbql.s/Filter]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(-> filter-clause desugar-filter-clause negate* simplify-compound-filter))
(mu/defn query->source-table-id :- [:maybe pos-int?]
diff --git a/src/metabase/lib/convert.cljc b/src/metabase/lib/convert.cljc
index 9295c0dabc2..b3cd3046b09 100644
--- a/src/metabase/lib/convert.cljc
+++ b/src/metabase/lib/convert.cljc
@@ -6,6 +6,7 @@
[malli.error :as me]
[medley.core :as m]
[metabase.legacy-mbql.normalize :as mbql.normalize]
+ [metabase.legacy-mbql.schema :as mbql.s]
[metabase.lib.convert.metadata-to-legacy :as lib.convert.metadata-to-legacy]
[metabase.lib.dispatch :as lib.dispatch]
[metabase.lib.hierarchy :as lib.hierarchy]
@@ -500,12 +501,33 @@
[clause]
(->legacy-MBQL clause))
-(defn- clause-with-options->legacy-MBQL [[k options & args]]
- (if (map? options)
- (into [k] (concat (map ->legacy-MBQL args)
- (when-let [options (not-empty (options->legacy-MBQL options))]
- [options])))
- (into [k] (map ->legacy-MBQL (cons options args)))))
+(defn- clause-with-options->legacy-MBQL
+ [[tag & args :as clause]]
+ (if-not ((some-fn nil? map?) (first args))
+ ;; probably something like `:dimension` which is not a 'real' MBQL clause
+ clause
+ (let [[options & args] args
+ args (map ->legacy-MBQL args)]
+ (loop [style (mbql.s/options-style tag), options options]
+ (case style
+ ::mbql.s/options-style.none (into [tag] args)
+ ::mbql.s/options-style.mbql-5 (into [tag (or options {})] args)
+ ::mbql.s/options-style.last-always (-> (into [tag] args)
+ (conj (not-empty (options->legacy-MBQL options))))
+ ::mbql.s/options-style.last-always.snake_case (recur ::mbql.s/options-style.last-always
+ (into (empty options)
+ (map (fn [[k v]]
+ [(cond-> k
+ (simple-keyword? k) u/->snake_case_en)
+ v]))
+ options))
+ ::mbql.s/options-style.last-unless-empty (let [options (options->legacy-MBQL options)]
+ (cond-> (into [tag] args)
+ (seq options)
+ (conj options)))
+ ::mbql.s/options-style.𝕨𝕚𝕝𝕕 (if (> (count args) 2)
+ (recur ::mbql.s/options-style.mbql-5 (options->legacy-MBQL options))
+ (recur ::mbql.s/options-style.last-unless-empty options)))))))
(defmethod ->legacy-MBQL :default
[x]
@@ -607,42 +629,17 @@
(defmethod ->legacy-MBQL :field [[_ opts id]]
;; Fields are not like the normal clauses - they need that options field even if it's null.
;; TODO: Sometimes the given field is in the legacy order - that seems wrong.
- (let [[opts id] (if (or (nil? opts) (map? opts))
+ (let [[opts id] (if ((some-fn nil? map?) opts)
[opts id]
[id opts])]
- [:field
- (->legacy-MBQL id)
- (options->legacy-MBQL 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)
- ;; as mentioned above, `:value` in legacy MBQL expects `snake_case` keys for type info keys.
- (set/rename-keys {:base-type :base_type
- :semantic-type :semantic_type
- :database-type :database_type
- :effective-type :effective_type})
- options->legacy-MBQL)]
- ;; in legacy MBQL, `:value` has to be three args; `opts` has to be present, but it should can be `nil` if it is
- ;; empty.
- [:value value opts]))
-
-;; `:offset` is the same in legacy and pMBQL, but we need to update the expr it wraps.
-(defmethod ->legacy-MBQL :offset
- [[tag opts expr n, :as clause]]
- {:pre [(= (count clause) 4)]}
- [tag opts (->legacy-MBQL expr) n])
-
-(defmethod ->legacy-MBQL ::string-comparison
- [[tag opts & args]]
- (if (> (count args) 2)
- (into [tag (disqualify opts)] (map ->legacy-MBQL args)) ; Multi-arg, pMBQL style: [tag {opts...} x y z ...]
- ;; Two-arg, legacy style: [tag x y] or [tag x y opts].
- (let [opts (disqualify opts)]
- (cond-> (into [tag] (map ->legacy-MBQL args))
- (seq opts) (conj opts)))))
+ (dissoc :effective-type))]
+ (clause-with-options->legacy-MBQL [:value opts value])))
(defn- update-list->legacy-boolean-expression
[m pMBQL-key legacy-key]
diff --git a/src/metabase/lib/expression.cljc b/src/metabase/lib/expression.cljc
index 47f09ae84e8..8ff085fb365 100644
--- a/src/metabase/lib/expression.cljc
+++ b/src/metabase/lib/expression.cljc
@@ -392,7 +392,7 @@
[:relative-datetime {:lib/uuid (str (random-uuid))} t])
([t :- ::lib.schema.expression.temporal/relative-datetime.amount
- unit :- ::lib.schema.temporal-bucketing/unit.date-time.interval]
+ unit :- ::lib.schema.expression.temporal/relative-datetime.unit]
[:relative-datetime {:lib/uuid (str (random-uuid))} t unit]))
(mu/defn value :- ::lib.schema.expression/expression
diff --git a/src/metabase/lib/filter/desugar.cljc b/src/metabase/lib/filter/desugar.cljc
new file mode 100644
index 00000000000..0d7d51dc666
--- /dev/null
+++ b/src/metabase/lib/filter/desugar.cljc
@@ -0,0 +1,360 @@
+(ns metabase.lib.filter.desugar
+ (:require
+ #?@(:clj ([metabase.lib.filter.desugar.jvm :as lib.filter.desugar.jvm]
+ [metabase.util.i18n :as i18n])
+ :cljs ([metabase.util.log :as log]))
+ [metabase.lib.expression :as lib.expression]
+ [metabase.lib.filter :as lib.filter]
+ [metabase.lib.filter.simplify-compound :as lib.filter.simplify-compound]
+ [metabase.lib.options :as lib.options]
+ [metabase.lib.schema.expression :as lib.schema.expression]
+ [metabase.lib.schema.mbql-clause :as lib.schema.mbql-clause]
+ [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
+ [metabase.lib.schema.util :as lib.schema.util]
+ [metabase.lib.util :as lib.util]
+ [metabase.lib.util.match :as lib.util.match]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.time :as u.time]))
+
+(mr/def ::clause
+ [:and
+ [:ref ::lib.schema.mbql-clause/clause]
+ [:ref ::lib.schema.util/unique-uuids]])
+
+(defn- merge-options [clause opts]
+ (lib.options/update-options clause merge opts))
+
+(mu/defn- desugar-inside :- ::clause
+ "Rewrite `:inside` filter clauses as a pair of `:between` clauses."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:inside opts lat-field lon-field lat-max lon-min lat-min lon-max]
+ (-> (lib.filter/and
+ (lib.filter/between lat-field lat-min lat-max)
+ (lib.filter/between lon-field lon-min lon-max))
+ (merge-options opts))))
+
+(mu/defn- desugar-is-null-and-not-null :- ::clause
+ "Rewrite `:is-null` and `:not-null` filter clauses as simpler `:=` and `:!=`, respectively."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:is-null opts x] [:= opts x nil]
+ [:not-null opts x] [:!= opts x nil]))
+
+(defn- emptyable?
+ [expr]
+ (isa? (lib.schema.expression/type-of expr) ::lib.schema.expression/emptyable))
+
+(mu/defn- desugar-is-empty-and-not-empty :- ::clause
+ "Rewrite `:is-empty` and `:not-empty` filter clauses as simpler `:=` and `:!=`, respectively.
+
+ If `:not-empty` is called on `::lib.schema.expression/emptyable` type, expand check for empty string. For
+ non-`emptyable` types act as `:is-null`. If field has nil base type it is considered not emptyable expansion wise."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:is-empty opts arg]
+ (-> (if (emptyable? arg)
+ (lib.filter/or
+ (lib.filter/= (lib.util/fresh-uuids arg) nil)
+ (lib.filter/= (lib.util/fresh-uuids arg) ""))
+ (lib.filter/= arg nil))
+ (merge-options opts))
+
+ [:not-empty opts arg]
+ (-> (if (emptyable? arg)
+ (lib.filter/and
+ (lib.filter/!= (lib.util/fresh-uuids arg) nil)
+ (lib.filter/!= (lib.util/fresh-uuids arg) ""))
+ (lib.filter/!= (lib.util/fresh-uuids arg) nil))
+ (merge-options opts))))
+
+(mu/defn- update-temporal-unit-in-refs :- ::clause
+ "Replace a field or expression inside :time-interval"
+ [expr :- ::clause
+ unit :- ::lib.schema.temporal-bucketing/unit]
+ (lib.util.match/replace expr
+ #{:field :expression}
+ (lib.options/update-options &match assoc :temporal-unit unit)))
+
+(mu/defn- desugar-time-interval :- ::clause
+ "Rewrite `:time-interval` filter clauses as simpler ones like `:=` or `:between`."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ ;; replace current/last/next with corresponding value of n and recur
+ [:time-interval opts field-or-expression :current unit] (recur [:time-interval opts field-or-expression 0 unit])
+ [:time-interval opts field-or-expression :last unit] (recur [:time-interval opts field-or-expression -1 unit])
+ [:time-interval opts field-or-expression :next unit] (recur [:time-interval opts field-or-expression 1 unit])
+
+ [:time-interval (opts :guard :include-current) field-or-expression (n :guard neg?) unit]
+ (-> (lib.filter/between
+ (update-temporal-unit-in-refs field-or-expression unit)
+ (lib.expression/relative-datetime n unit)
+ (lib.expression/relative-datetime 0 unit))
+ (merge-options opts))
+
+ [:time-interval (opts :guard :include-current) field-or-expression n unit]
+ (-> (lib.filter/between
+ (update-temporal-unit-in-refs field-or-expression unit)
+ (lib.expression/relative-datetime 0 unit)
+ (lib.expression/relative-datetime n unit))
+ (merge-options opts))
+
+ [:time-interval opts field-or-expression (n :guard #{-1 0 1}) unit]
+ (-> (lib.filter/= (update-temporal-unit-in-refs field-or-expression unit)
+ (lib.expression/relative-datetime n unit))
+ (merge-options opts))
+
+ [:time-interval opts field-or-expression (n :guard neg?) unit]
+ (-> (lib.filter/between
+ (update-temporal-unit-in-refs field-or-expression unit)
+ (lib.expression/relative-datetime n unit)
+ (lib.expression/relative-datetime -1 unit))
+ (merge-options opts))
+
+ [:time-interval opts field-or-expression n unit]
+ (-> (update-temporal-unit-in-refs field-or-expression unit)
+ (lib.filter/between
+ (lib.expression/relative-datetime 1 unit)
+ (lib.expression/relative-datetime n unit))
+ (merge-options opts))))
+
+(defn- with-default-temporal-bucket-in-refs [arg]
+ (lib.util/fresh-uuids (update-temporal-unit-in-refs arg :default)))
+
+(mu/defn- desugar-relative-time-interval :- ::clause
+ "Transform `:relative-time-interval` to `:and` expression."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:relative-time-interval opts arg (value :guard int?) bucket offset-value offset-bucket]
+ (let [bucket #(lib.util/fresh-uuids bucket)
+ offset-value #(lib.util/fresh-uuids offset-value)
+ offset-bucket #(lib.util/fresh-uuids offset-bucket)
+ offset #(lib.expression/interval (offset-value) (offset-bucket))
+ lower-bound (if (neg? value)
+ (lib.expression/relative-datetime value (bucket))
+ (lib.expression/relative-datetime 1 (bucket)))
+ upper-bound (if (neg? value)
+ (lib.expression/relative-datetime 0 (bucket))
+ (lib.expression/relative-datetime (inc value) (bucket)))
+ lower-with-offset (lib.expression/+ lower-bound (offset))
+ upper-with-offset (lib.expression/+ upper-bound (offset))]
+ (-> (lib.filter/and
+ (lib.filter/>= (with-default-temporal-bucket-in-refs arg) lower-with-offset)
+ (lib.filter/< (with-default-temporal-bucket-in-refs arg) upper-with-offset))
+ (merge-options opts)))))
+
+(mu/defn- desugar-during :- ::clause
+ "Transform a `:during` expression to an `:and` expression."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:during opts arg value unit]
+ (let [lower-bound (u.time/truncate value unit)
+ upper-bound (u.time/add lower-bound unit 1)]
+ (-> (lib.filter/and
+ (lib.filter/>= (with-default-temporal-bucket-in-refs arg) lower-bound)
+ (lib.filter/< (with-default-temporal-bucket-in-refs arg) upper-bound))
+ (merge-options opts)))))
+
+(mu/defn- desugar-if :- ::clause
+ "Transform a `:if` expression to an `:case` expression."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:if opts & args]
+ (-> (apply lib.expression/case args)
+ (merge-options opts))))
+
+(mu/defn- desugar-in :- ::clause
+ "Transform `:in` and `:not-in` expressions to `:=` and `:!=` expressions."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:in opts & args]
+ (-> (apply lib.filter/= args)
+ (merge-options opts))
+
+ [:not-in opts & args]
+ (-> (apply lib.filter/!= args)
+ (merge-options opts))))
+
+(mu/defn- desugar-does-not-contain :- ::clause
+ "Rewrite `:does-not-contain` filter clauses as simpler `[:not [:contains ...]]` clauses.
+
+ Note that [[desugar-multi-argument-comparisons]] will have already desugared any 3+ argument `:does-not-contain` to
+ several `[:and [:does-not-contain ...] [:does-not-contain ...] ...]` clauses, which then get rewritten here into
+ `[:and [:not [:contains ...]] [:not [:contains ...]]]`."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:does-not-contain opts whole & parts]
+ (-> (lib.filter/not (-> (apply lib.filter/contains whole parts)
+ ;; need to preserve stuff like `:case-sensitve`. Prefer values in each clause over `opts`
+ ;; so we don't get duplicate UUIDs
+ (lib.options/update-options #(merge opts %))))
+ (merge-options opts))))
+
+(mu/defn- desugar-multi-argument-comparisons :- ::clause
+ "`:=`, `!=`, `:contains`, `:does-not-contain`, `:starts-with` and `:ends-with` clauses with more than 2 args
+ automatically get rewritten as compound filters.
+
+ [:= field x y] -> [:or [:= field x] [:= field y]]
+ [:!= field x y] -> [:and [:!= field x] [:!= field y]]
+ [:does-not-contain field x y] -> [:and [:does-not-contain field x] [:does-not-contain field y]]
+
+ Note that the optional options map is in different positions for `:contains`, `:does-not-contain`, `:starts-with` and
+ `:ends-with` depending on the number of arguments. 2-argument forms use the legacy style `[:contains field x opts]`.
+ Multi-argument forms use pMBQL style with the options at index 1, **even if there are no options**:
+ `[:contains {} field x y z]`."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [:= opts field a b & more]
+ (-> (apply lib.filter/or (map (fn [expr]
+ (lib.filter/= (lib.util/fresh-uuids field) expr))
+ (list* a b more)))
+ (merge-options opts))
+
+ [:!= opts field a b & more]
+ (-> (apply lib.filter/and (map (fn [expr]
+ (lib.filter/!= (lib.util/fresh-uuids field) expr))
+ (list* a b more)))
+ (merge-options opts))
+
+ [(op :guard #{:contains :does-not-contain :starts-with :ends-with})
+ (opts :guard map?)
+ field a b & more]
+ (let [f (case op
+ :contains lib.filter/contains
+ :does-not-contain lib.filter/does-not-contain
+ :starts-with lib.filter/starts-with
+ :ends-with lib.filter/ends-with)]
+ (-> (apply (if (= op :does-not-contain) lib.filter/and lib.filter/or)
+ (map (fn [expr]
+ (-> (f (lib.util/fresh-uuids field) expr)
+ (lib.options/update-options #(merge opts %))))
+ (list* a b more)))
+ (merge-options opts)))))
+
+(mu/defn- desugar-current-relative-datetime :- ::clause
+ "Replace `relative-datetime` clauses like `[:relative-datetime :current]` with `[:relative-datetime 0 <unit>]`.
+ `<unit>` is inferred from the `:field` the clause is being compared to (if any), otherwise falls back to `default.`"
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [tag opts field & (args :guard (fn [args]
+ (some (fn [arg]
+ (lib.util.match/match-one arg [:relative-datetime _opts :current]))
+ args)))]
+ (let [temporal-unit (or (lib.util.match/match-lite-recursive field
+ [:field {:temporal-unit temporal-unit} _]
+ temporal-unit)
+ :default)]
+ (into [tag opts field]
+ (map (fn [arg]
+ (lib.util.match/replace arg
+ [:relative-datetime relative-datetime-opts :current]
+ (-> (lib.expression/relative-datetime 0 temporal-unit)
+ (merge-options relative-datetime-opts)))))
+ args))))
+
+(def ^:private temporal-extract-ops->unit
+ "Mapping from the sugar syntax to extract datetime to the unit."
+ {[:get-year nil] :year-of-era
+ [:get-quarter nil] :quarter-of-year
+ [:get-month nil] :month-of-year
+ ;; default get-week mode is iso
+ [:get-week nil] :week-of-year-iso
+ [:get-week :iso] :week-of-year-iso
+ [:get-week :us] :week-of-year-us
+ [:get-week :instance] :week-of-year-instance
+ [:get-day nil] :day-of-month
+ [:get-day-of-week nil] :day-of-week
+ [:get-day-of-week :iso] :day-of-week-iso
+ [:get-hour nil] :hour-of-day
+ [:get-minute nil] :minute-of-hour
+ [:get-second nil] :second-of-minute})
+
+(def ^:private temporal-extract-ops
+ (->> (keys temporal-extract-ops->unit)
+ (map first)
+ set))
+
+(mu/defn- desugar-temporal-extract :- ::clause
+ "Replace datetime extractions clauses like `[:get-year field]` with `[:temporal-extract field :year]`."
+ [expr :- ::clause]
+ (lib.util.match/replace expr
+ [(tag :guard temporal-extract-ops) opts field & args]
+ [:temporal-extract opts field (temporal-extract-ops->unit [tag (first args)])]))
+
+(mu/defn- desugar-divide-with-extra-args :- ::clause
+ [expression :- ::clause]
+ (lib.util.match/replace expression
+ [:/ opts x y z & more]
+ (recur (-> (apply lib.expression// (lib.expression// x y) z more)
+ (merge-options opts)))))
+
+(mu/defn- temporal-case-expression :- :mbql.clause/case
+ "Creates a `:case` expression with a condition for each value of the given unit."
+ [expr :- ::clause
+ opts :- :map
+ unit :- :keyword
+ n :- :int]
+ (let [user-locale #?(:clj (i18n/user-locale)
+ :cljs nil)]
+ (-> (lib.expression/case
+ (mapv (fn [raw-value]
+ [(lib.filter/= (lib.util/fresh-uuids expr) raw-value)
+ (u.time/format-unit raw-value unit user-locale)])
+ (range 1 (inc n))))
+ (lib.options/update-options merge opts {:default ""}))))
+
+(mu/defn- desugar-temporal-names :- ::clause
+ "Given an expression like `[:month-name column]`, transforms this into a `:case` expression, which matches the input
+ numbers and transforms them into names.
+
+ Uses the user's locale rather than the site locale, so the results will depend on the runner of the query, not just
+ the query itself. Filtering should be done based on the number, rather than the name."
+ [expression :- ::clause]
+ (lib.util.match/replace expression
+ [:month-name opts expr] (recur (temporal-case-expression expr opts :month-of-year 12))
+ [:quarter-name opts expr] (recur (temporal-case-expression expr opts :quarter-of-year 4))
+ [:day-name opts expr] (recur (temporal-case-expression expr opts :day-of-week 7))))
+
+(mu/defn- desugar-expression :- ::clause
+ "Rewrite various 'syntactic sugar' expressions like `:/` with more than two args into something simpler for drivers
+ to compile."
+ [expression :- ::clause]
+ ;; The `mbql.jvm-u/desugar-host-and-domain` is implemented only for jvm because regexes are not compatible with
+ ;; Safari.
+ (let [desugar-host-and-domain* #?(:clj lib.filter.desugar.jvm/desugar-host-and-domain
+ :cljs (fn [x]
+ (log/warn "`desugar-host-and-domain` implemented only on JVM.")
+ x))]
+ (-> expression
+ desugar-divide-with-extra-args
+ desugar-host-and-domain*
+ desugar-temporal-names)))
+
+(mu/defn- maybe-desugar-expression :- ::clause
+ [clause :- ::clause]
+ (cond-> clause
+ (or (lib.util/clause-of-type? clause :field)
+ (mr/validate ::lib.schema.expression/expression clause))
+ desugar-expression))
+
+(mu/defn desugar-filter-clause :- ::clause
+ "Rewrite various 'syntatic sugar' filter clauses like `:time-interval` and `:inside` as simpler, logically
+ equivalent clauses. This can be used to simplify the number of filter clauses that need to be supported by anything
+ that needs to enumerate all the possible filter types."
+ [filter-clause :- ::clause]
+ (-> filter-clause
+ desugar-current-relative-datetime
+ desugar-in
+ desugar-multi-argument-comparisons
+ desugar-does-not-contain
+ desugar-time-interval
+ desugar-relative-time-interval
+ desugar-is-null-and-not-null
+ desugar-is-empty-and-not-empty
+ desugar-inside
+ lib.filter.simplify-compound/simplify-compound-filter
+ desugar-temporal-extract
+ desugar-during
+ desugar-if
+ maybe-desugar-expression))
diff --git a/src/metabase/lib/filter/desugar/jvm.clj b/src/metabase/lib/filter/desugar/jvm.clj
new file mode 100644
index 00000000000..c4fe43427cb
--- /dev/null
+++ b/src/metabase/lib/filter/desugar/jvm.clj
@@ -0,0 +1,156 @@
+(ns metabase.lib.filter.desugar.jvm
+ "This namespace contains functionality that is not compatible with js."
+ (:require
+ [metabase.lib.schema.mbql-clause :as lib.schema.mbql-clause]
+ [metabase.lib.util.match :as lib.util.match]
+ [metabase.util.malli :as mu]))
+
+;;;; Following regex definitions are incompatible with Safari browser. Code is unused on FE.
+
+;;; TODO (Cam 8/18/25) -- we should rewrite these with [[metabase.util.regex]] to make them actually readable
+
+(def host-regex
+ "Extracts the \"host\" from a URL or an email. By host we mean the main domain name and the TLD, eg. `metabase.com`,
+ `amazon.co.jp`, `bbc.co.uk`. For a URL, this is not the RFC3986 \"host\", which would include any subdomains and the
+ optional `:3000` port number.
+
+ For an email, this is generally the part after the @, but it will skip any subdomains:
+
+ [email protected] -> mycompany.net
+
+ Referencing the indexes below:
+
+ 1. Positive lookbehind: Just past one of:
+
+ 2. `@` from an email or URL userinfo@ prefix
+
+ 3. `//` from a URL scheme
+
+ 4. `.` from a previous subdomain segment
+
+ 5. Start of string
+
+ 6. Negative lookahead: don't capture `www` as part of the domain
+
+ 7. Main domain segment
+
+ 8. Ending in a dot
+
+ 9. Optional short final segment (eg. `co` in `.co.uk`)
+
+ 10. Top-level domain
+
+ 11. Optional `:port`, `/path`, `?query` or `#hash`
+
+ 12. Anchor to the end"
+
+ ;;1 2 3 4 5 6 7 8 9 10 11 12
+ #"(?<=@|//|\.|^)(?!www\.)[^@\.:/?#]+\.(?:[^@\.:/?#]{1,3}\.)?[^@\.:/?#]+(?=[:/?#].*$|$)")
+
+(def domain-regex
+ "Deliberately no ^ at the start; there might be several subdomains before this spot. By \"short tail\" below, I mean a
+ pseudo-TLD nested under a proper TLD. For example, `mycompany.co.uk`.
+
+ This can accidentally capture a short domain name, eg.
+
+ \"subdomain.aol.com\" -> \"subdomain\"
+
+ , oops. But there's a load of these, not a short list we can include here, so it's either preprocess the (huge)
+ master list from Mozilla or accept that this regex is a bit best-effort. Referencing the indexes below:
+
+ 1. Positive lookbehind: Just past one of:
+
+ 2. `@` from an email or URL userinfo@ prefix
+
+ 3. `//` from a URL scheme
+
+ 4. `.` from a previous subdomain segment
+
+ 5. Start of string
+
+ 6. Negative lookahead: don't capture `www` as the domain
+
+ 7. One domain segment
+
+ 8. Positive lookahead: Either:
+
+ 9. Short final segment (eg. `.co.uk`)
+
+ 10. Top-level domain
+
+ 11. Optional `:port`, `/path`, `?query` or `#hash`
+
+ 12. Anchor to end Or:
+
+ 13. Top-level domain
+
+ 14. Optional `:port`, `/path`, `?query` or `#hash`
+
+ 15. Anchor to end"
+ ;;1 2 3 4 5 6 7 (8 9 10 11 12| 13 14 15)
+ #"(?<=@|//|\.|^)(?!www\.)[^@\.:/?#]+(?=\.[^@\.:/?#]{1,3}\.[^@\.:/?#]+(?:[:/?#].*)?$|\.[^@\.:/?#]+(?:[:/?#].*)?$)")
+
+(def subdomain-regex
+ "This grabs the first segment that isn't `www`, AND excludes the main domain name. See [[domain-regex]] for more
+ details about how those are matched.
+
+ Referencing the indexes below:
+
+ 1. Positive lookbehind: Just past one of:
+
+ 2. `@` from an email or URL `userinfo@` prefix
+
+ 3. `//` from a URL scheme
+
+ 4. `.` from a previous subdomain segment
+
+ 5. Start of string
+
+ 6. Negative lookahead: don't capture `www` as the domain
+
+ 7. Negative lookahead: don't capture the main domain name or part of the TLD That would look like:
+
+ 8. The next segment we *would* capture as the subdomain
+
+ 9. Optional short segment, like `co` in `.co.uk`
+
+ 10. Top-level domain
+
+ 11. Optionally more URL things: `:port` or `/path` or `?query` or `#fragment`
+
+ 12. End of string
+
+ 13. Match the actual subdomain
+
+ 14. Positive lookahead: the . after the subdomain, which we want to detect but not capture."
+ ;;1 2 3 4 5 6 7 8 9 10 11 12 13 14
+ #"(?<=@|//|\.|^)(?!www\.)(?![^\.:/?#]+\.(?:[^\.:/?#]{1,3}\.)?[^\.:/?#]+(?:[:/?#].*)?$)[^\.:/?#]+(?=\.)")
+
+(def path-regex
+ "This regex is just a hack. It's actually really hard to just match the path with a regex.
+
+ This will match:
+
+ - `google.com/`
+
+ - `google.com/abc`
+
+ - `google.com/abc?hjfds`"
+ #"(?<=\.[^/]{1,10})/[^#?]*")
+
+(mu/defn desugar-host-and-domain :- ::lib.schema.mbql-clause/clause
+ "Unwrap host and domain."
+ [expression :- ::lib.schema.mbql-clause/clause]
+ (lib.util.match/replace expression
+ [:host opts expr]
+ ;; TODO (Cam 8/18/25) -- seems weird that we don't support Regex literals in the regex clauses and have to call (str ...)
+ (recur [:regex-match-first opts expr (str host-regex)])
+
+ [:domain opts expr]
+ (recur [:regex-match-first opts expr (str domain-regex)])
+
+ [:subdomain opts expr]
+ (recur [:regex-match-first opts expr (str subdomain-regex)])
+
+ [:path opts expr]
+ (recur [:regex-match-first opts expr (str path-regex)])))
diff --git a/src/metabase/lib/filter/simplify_compound.cljc b/src/metabase/lib/filter/simplify_compound.cljc
new file mode 100644
index 00000000000..ebebf882551
--- /dev/null
+++ b/src/metabase/lib/filter/simplify_compound.cljc
@@ -0,0 +1,87 @@
+(ns metabase.lib.filter.simplify-compound
+ (:require
+ [medley.core :as m]
+ [metabase.lib.filter :as lib.filter]
+ [metabase.lib.options :as lib.options]
+ [metabase.lib.schema.mbql-clause :as lib.schema.mbql-clause]
+ [metabase.lib.schema.util :as lib.schema.util]
+ [metabase.lib.util :as lib.util]
+ [metabase.lib.util.match :as lib.util.match]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.registry :as mr]))
+
+(mr/def ::mbql-clause
+ "An MBQL clause that may not be well-formed, e.g. an `:and` clause with only one arg."
+ [:schema
+ [:cat
+ keyword?
+ map?
+ [:+ any?]]])
+
+(mu/defn- combine-compound-filters-of-type :- [:sequential [:maybe ::mbql-clause]]
+ [tag :- [:enum :and :or]
+ clauses :- [:sequential ::mbql-clause]]
+ (loop [acc [], [clause & more] clauses]
+ (cond
+ (and (not clause)
+ (seq more))
+ (recur acc more)
+
+ (and (not clause)
+ (empty? more))
+ acc
+
+ (lib.util/clause-of-type? clause tag)
+ (recur acc (concat (drop 2 clause) more))
+
+ :else
+ (recur (conj acc clause) more))))
+
+(declare simplify-compound-filter)
+
+(mu/defn- simplify-and-or-filter :- [:maybe ::lib.schema.mbql-clause/clause]
+ [tag :- [:enum :and :or]
+ opts :- :map
+ args]
+ (let [args (m/distinct-by lib.schema.util/mbql-clause-distinct-key (filter some? args))]
+ (case (count args)
+ ;; an empty filter, toss it
+ 0 nil
+ ;; single arg, unwrap it
+ 1 (simplify-compound-filter (first args))
+ ;; else
+ (if (some #(lib.util/clause-of-type? % tag) args)
+ ;; clause of the same type embedded, flatten it
+ (recur tag opts (combine-compound-filters-of-type tag args))
+ ;; simplify the arguments
+ (let [simplified (map simplify-compound-filter args)]
+ (if (= simplified args)
+ ;; no change
+ (into [tag opts] args)
+ ;; there is a change, we might be able to simplify even further
+ (recur tag opts simplified)))))))
+
+(mu/defn simplify-compound-filter :- ::lib.schema.util/unique-uuids
+ "Simplify compound `:and`, `:or`, and `:not` compound filters, combining or eliminating them where possible. This
+ also fixes theoretically disallowed compound filters like `:and` with only a single subclause, and eliminates `nils`
+ and duplicate subclauses from the clauses."
+ [x]
+ (lib.util.match/replace x
+ ;; double negation, eliminate both
+ [:not opts [:not arg-opts arg-arg]]
+ (recur
+ ;; preserve options from the collapsed clauses.
+ (lib.options/update-options arg-arg merge arg-opts opts))
+
+ ;; use de Morgan's law to push the negation down
+ [:not opts [:and arg-opts & arg-args]]
+ (simplify-and-or-filter :or (merge arg-opts opts) (map lib.filter/not arg-args))
+
+ [:not opts [:or arg-opts & arg-args]]
+ (simplify-and-or-filter :and (merge arg-opts opts) (map lib.filter/not arg-args))
+
+ [:and opts & args]
+ (simplify-and-or-filter :and opts args)
+
+ [:or opts & args]
+ (simplify-and-or-filter :or opts args)))
diff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljc
index 853dc2fd11e..40059c1c6f0 100644
--- a/src/metabase/lib/schema.cljc
+++ b/src/metabase/lib/schema.cljc
@@ -129,7 +129,10 @@
(defn- expression-ref-errors-for-stage [stage]
(let [stage (dissoc stage :parameters) ; don't validate [:dimension [:expression ...]] refs since they might not be moved to the correct place yet.
- expression-names (into #{} (map (comp :lib/expression-name second)) (:expressions stage))
+ expression-names (when-let [expressions (:expressions stage)]
+ (when (and (sequential? expressions)
+ (every? sequential? expressions))
+ (into #{} (map (comp :lib/expression-name second)) expressions)))
pred #(bad-ref-clause? :expression expression-names %)
form (-> (stage-with-joins-and-namespaced-keys-removed stage)
;; also ignore expression refs inside `:parameters` since they still use legacy syntax these days.
diff --git a/src/metabase/lib/schema/expression/temporal.cljc b/src/metabase/lib/schema/expression/temporal.cljc
index 85e1a8f1167..b8ad539ff4b 100644
--- a/src/metabase/lib/schema/expression/temporal.cljc
+++ b/src/metabase/lib/schema/expression/temporal.cljc
@@ -273,10 +273,15 @@
[true [:= {:decode/normalize common/normalize-keyword-lower} :current]]
[false :int]])
+(mr/def ::relative-datetime.unit
+ [:or
+ [:= :default]
+ [:ref ::temporal-bucketing/unit.date-time.interval]])
+
;;; TODO (Cam 7/16/25) -- I think unit is rewuired unless `n` is `:current`
(mbql-clause/define-catn-mbql-clause :relative-datetime :- :type/DateTime
[:n [:schema [:ref ::relative-datetime.amount]]]
- [:unit [:? [:schema [:ref ::temporal-bucketing/unit.date-time.interval]]]])
+ [:unit [:? [:schema [:ref ::relative-datetime.unit]]]])
(mbql-clause/define-tuple-mbql-clause :time :- :type/Time
#_:timestr [:schema [:ref ::expression/string]]
diff --git a/src/metabase/lib/schema/mbql_clause.cljc b/src/metabase/lib/schema/mbql_clause.cljc
index 31ca0148ded..6915494a0b3 100644
--- a/src/metabase/lib/schema/mbql_clause.cljc
+++ b/src/metabase/lib/schema/mbql_clause.cljc
@@ -10,7 +10,7 @@
(comment metabase.types.core/keep-me)
(defonce ^:private ^{:doc "Set of all registered MBQL clause tags e.g. #{:starts-with}"} tag-registry
- (atom #{}))
+ (atom (sorted-set)))
(defn tag->registered-schema-name
"Given an MBQL clause tag like `:starts-with`, return the name of the schema we'll register for it, e.g.
diff --git a/src/metabase/lib/util.cljc b/src/metabase/lib/util.cljc
index 19e6a5e5df7..121c18f9153 100644
--- a/src/metabase/lib/util.cljc
+++ b/src/metabase/lib/util.cljc
@@ -47,7 +47,7 @@
[clause]
(and (vector? clause)
(keyword? (first clause))
- (let [opts (get clause 1)]
+ (let [opts (second clause)]
(and (map? opts)
(contains? opts :lib/uuid)))))
@@ -55,7 +55,9 @@
"Returns true if this is a clause."
[clause clause-type]
(and (clause? clause)
- (= (first clause) clause-type)))
+ (if (set? clause-type)
+ (clause-type (first clause))
+ (= (first clause) clause-type))))
(defn field-clause?
"Returns true if this is a field clause."
diff --git a/src/metabase/parameters/chain_filter.clj b/src/metabase/parameters/chain_filter.clj
index 2536a71dcbe..b1695b91be2 100644
--- a/src/metabase/parameters/chain_filter.clj
+++ b/src/metabase/parameters/chain_filter.clj
@@ -182,6 +182,7 @@
(name-for-logging :model/Table field-table-id)
(name-for-logging :model/Field field-id)
clause)
+ #_{:clj-kondo/ignore [:deprecated-var]}
(update query :filter mbql.u/combine-filter-clauses clause))
(do
(log/tracef "Not adding filter clause for %s %s because we did not join against its Table"
diff --git a/src/metabase/query_processor/middleware/desugar.clj b/src/metabase/query_processor/middleware/desugar.clj
index ea12439a012..01e9402d82c 100644
--- a/src/metabase/query_processor/middleware/desugar.clj
+++ b/src/metabase/query_processor/middleware/desugar.clj
@@ -1,59 +1,26 @@
(ns metabase.query-processor.middleware.desugar
(:require
- [medley.core :as m]
- [metabase.legacy-mbql.predicates :as mbql.preds]
- [metabase.legacy-mbql.schema :as mbql.s]
- [metabase.legacy-mbql.util :as mbql.u]
- [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.filter.desugar :as lib.filter.desugar]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.util :as lib.util]
[metabase.lib.util.match :as lib.util.match]
- [metabase.query-processor.store :as qp.store]
+ [metabase.lib.walk :as lib.walk]
[metabase.util.malli :as mu]))
-(defn- add-missing-field-base-types
- "Add base type to fields with id that are missing it. It is necessary for correct function
- of [[metabase.legacy-mbql.util/desugar-is-empty-and-not-empty]]."
- [query]
- (lib.util.match/replace query
- (field-clause :guard (fn [clause]
- (and (mbql.preds/Field? clause)
- (integer? (second clause))
- (not (contains? (get clause 2) :base-type)))))
- (let [id (second field-clause)
- metadata (lib.metadata/field (qp.store/metadata-provider) id)
- {:keys [base-type]} metadata]
- (update field-clause 2 assoc
- :base-type base-type
- ::desugar-added-base-type true))))
-
-(defn- remove-desugar-added-base-types
- [query]
- (lib.util.match/replace query
- (field-clause :guard (fn [clause]
- (and (mbql.preds/Field? clause)
- (integer? (second clause))
- (get-in clause [2 ::desugar-added-base-type]))))
- (update field-clause 2 (comp not-empty
- #(dissoc % :base-type ::desugar-added-base-type)))))
-
(defn- desugar*
- [query]
- (lib.util.match/replace query
- (filter-clause :guard mbql.preds/Filter?)
- (mbql.u/desugar-filter-clause filter-clause)
-
- (temporal-extract-clause :guard mbql.preds/DatetimeExpression?)
- (mbql.u/desugar-temporal-extract temporal-extract-clause)
-
- (expression :guard mbql.preds/FieldOrExpressionDef?)
- (mbql.u/desugar-expression expression)))
+ [stage-or-join]
+ (letfn [(desugar** [x]
+ (lib.util.match/replace x
+ (clause :guard lib.util/clause?)
+ (lib.filter.desugar/desugar-filter-clause clause)))]
+ (merge
+ (desugar** (dissoc stage-or-join :joins :stages :lib/stage-metadata :parameters))
+ (select-keys stage-or-join [:joins :stages :lib/stage-metadata :parameters]))))
-(mu/defn desugar :- mbql.s/Query
+(mu/defn desugar :- ::lib.schema/query
"Middleware that uses MBQL lib functions to replace high-level 'syntactic sugar' clauses like `time-interval` and
`inside` with lower-level clauses like `between`. This is done to minimize the number of MBQL clauses individual
drivers need to support. Clauses replaced by this middleware are marked `^:sugar` in the MBQL schema."
- [query]
- ;; Base types are added to field options for integer id fields that are missing those. Then original desugar
- ;; is performed. Later those base types (added for desugaring purposes [expanding is-empty, not-empty]) are removed.
- (m/update-existing query :query (comp remove-desugar-added-base-types
- desugar*
- add-missing-field-base-types)))
+ [query :- ::lib.schema/query]
+ (lib.walk/walk query (fn [_query _path-type _path stage-or-join]
+ (desugar* stage-or-join))))
diff --git a/src/metabase/query_processor/middleware/optimize_temporal_filters.clj b/src/metabase/query_processor/middleware/optimize_temporal_filters.clj
index 07e0741df6a..29707a962d5 100644
--- a/src/metabase/query_processor/middleware/optimize_temporal_filters.clj
+++ b/src/metabase/query_processor/middleware/optimize_temporal_filters.clj
@@ -353,6 +353,7 @@
;; optimize the filters in this inner-query form.
(let [optimized (optimize-temporal-filters* form)]
;; if we did some optimizations, we should flatten/deduplicate the filter clauses afterwards.
+ #_{:clj-kondo/ignore [:deprecated-var]}
(cond-> optimized
(not= optimized form) (update :filter mbql.u/combine-filter-clauses)))))
query)))
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index c4540b72c0b..b3c28cbac4a 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -54,7 +54,7 @@
(set! *warn-on-reflection* true)
;;; the following helper functions are temporary, to aid in the transition from a legacy MBQL QP to a pMBQL QP. Each
-;;; individual middleware function is wrapped in either [[ensure-legacy]] or [[ensure-pmbql]], and will then see the
+;;; individual middleware function is wrapped in either [[ensure-legacy]] or [[ensure-mbql-5]], and will then see the
;;; flavor of MBQL it is written for.
(mu/defn- ->legacy :- mbql.s/Query
@@ -79,7 +79,7 @@
(cond->> query
(not (:lib/type query)) (lib/query (qp.store/metadata-provider))))
-(defn- ensure-pmbql [middleware-fn]
+(defn- ensure-mbql-5 [middleware-fn]
(-> (fn [query]
(let [query (->mbql-5 query)]
(vary-meta (middleware-fn query)
@@ -98,7 +98,7 @@
from))
;;; TODO -- this is broken and disables enforcement inside the middleware itself -- see QUE-1346
-(defn- ensure-pmbql-for-unclean-query
+(defn- ensure-mbql-5-for-unclean-query
[middleware-fn]
(-> (fn [query]
(as-> query query
@@ -126,24 +126,24 @@
;; ↓↓↓ PRE-PROCESSING ↓↓↓ happens from TOP TO BOTTOM
#_{:clj-kondo/ignore [:deprecated-var]}
[#'normalize/normalize-preprocessing-middleware
- (ensure-pmbql #'qp.perms/remove-permissions-key)
- (ensure-pmbql #'qp.perms/remove-source-card-keys)
- (ensure-pmbql #'qp.perms/remove-gtapped-table-keys)
- (ensure-pmbql #'qp.constraints/maybe-add-default-userland-constraints)
- (ensure-pmbql #'validate/validate-query)
- (ensure-pmbql #'fetch-source-query/resolve-source-cards)
- (ensure-pmbql #'expand-aggregations/expand-aggregations)
- (ensure-pmbql #'metrics/adjust)
- (ensure-pmbql #'expand-macros/expand-macros)
- (ensure-pmbql #'qp.resolve-referenced/resolve-referenced-card-resources)
- (ensure-pmbql #'parameters/substitute-parameters)
- (ensure-pmbql #'qp.resolve-source-table/resolve-source-tables)
- (ensure-pmbql #'qp.auto-bucket-datetimes/auto-bucket-datetimes)
- (ensure-pmbql #'ensure-joins-use-source-query/ensure-joins-use-source-query)
+ (ensure-mbql-5 #'qp.perms/remove-permissions-key)
+ (ensure-mbql-5 #'qp.perms/remove-source-card-keys)
+ (ensure-mbql-5 #'qp.perms/remove-gtapped-table-keys)
+ (ensure-mbql-5 #'qp.constraints/maybe-add-default-userland-constraints)
+ (ensure-mbql-5 #'validate/validate-query)
+ (ensure-mbql-5 #'fetch-source-query/resolve-source-cards)
+ (ensure-mbql-5 #'expand-aggregations/expand-aggregations)
+ (ensure-mbql-5 #'metrics/adjust)
+ (ensure-mbql-5 #'expand-macros/expand-macros)
+ (ensure-mbql-5 #'qp.resolve-referenced/resolve-referenced-card-resources)
+ (ensure-mbql-5 #'parameters/substitute-parameters)
+ (ensure-mbql-5 #'qp.resolve-source-table/resolve-source-tables)
+ (ensure-mbql-5 #'qp.auto-bucket-datetimes/auto-bucket-datetimes)
+ (ensure-mbql-5 #'ensure-joins-use-source-query/ensure-joins-use-source-query)
(ensure-legacy #'reconcile-bucketing/reconcile-breakout-and-order-by-bucketing)
(ensure-legacy #'qp.add-source-metadata/add-source-metadata-for-source-queries)
- (ensure-pmbql #'qp.middleware.enterprise/apply-impersonation)
- (ensure-pmbql #'qp.middleware.enterprise/attach-destination-db-middleware)
+ (ensure-mbql-5 #'qp.middleware.enterprise/apply-impersonation)
+ (ensure-mbql-5 #'qp.middleware.enterprise/attach-destination-db-middleware)
(ensure-legacy #'qp.middleware.enterprise/apply-sandboxing)
(ensure-legacy #'qp.persistence/substitute-persisted-query)
(ensure-legacy #'qp.add-implicit-clauses/add-implicit-clauses) ; #61398
@@ -151,24 +151,24 @@
;; after adding any implicit joins. Implicit joins do not need to get remaps since we only use them for fetching
;; specific columns.
(ensure-legacy #'resolve-joins/resolve-joins) ; #61398
- (ensure-pmbql #'qp.add-remaps/add-remapped-columns)
+ (ensure-mbql-5 #'qp.add-remaps/add-remapped-columns)
#'qp.resolve-fields/resolve-fields ; this middleware actually works with either MBQL 5 or legacy
- (ensure-pmbql #'binning/update-binning-strategy)
- (ensure-legacy #'desugar/desugar) ; #62319
+ (ensure-mbql-5 #'binning/update-binning-strategy)
+ (ensure-mbql-5 #'desugar/desugar)
(ensure-legacy #'qp.add-default-temporal-unit/add-default-temporal-unit)
- (ensure-pmbql #'qp.add-implicit-joins/add-implicit-joins)
+ (ensure-mbql-5 #'qp.add-implicit-joins/add-implicit-joins)
(ensure-legacy #'resolve-joins/resolve-joins) ; #61398
- (ensure-pmbql #'resolve-joined-fields/resolve-joined-fields)
- (ensure-pmbql #'qp.remove-inactive-field-refs/remove-inactive-field-refs)
+ (ensure-mbql-5 #'resolve-joined-fields/resolve-joined-fields)
+ (ensure-mbql-5 #'qp.remove-inactive-field-refs/remove-inactive-field-refs)
;; 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.pre-alias-aggregations/pre-alias-aggregations)
(ensure-legacy #'qp.wrap-value-literals/wrap-value-literals)
- (ensure-pmbql-for-unclean-query #'auto-parse-filter-values/auto-parse-filter-values)
+ (ensure-mbql-5-for-unclean-query #'auto-parse-filter-values/auto-parse-filter-values)
(ensure-legacy #'validate-temporal-bucketing/validate-temporal-bucketing)
(ensure-legacy #'optimize-temporal-filters/optimize-temporal-filters)
- (ensure-pmbql #'limit/add-default-limit)
+ (ensure-mbql-5 #'limit/add-default-limit)
(ensure-legacy #'qp.middleware.enterprise/apply-download-limit)
(ensure-legacy #'check-features/check-features)])
diff --git a/src/metabase/tiles/api.clj b/src/metabase/tiles/api.clj
index b340beb1d14..0435383436e 100644
--- a/src/metabase/tiles/api.clj
+++ b/src/metabase/tiles/api.clj
@@ -70,6 +70,7 @@
(top-left :lon)
(bottom-right :lat)
(bottom-right :lon)]]
+ #_{:clj-kondo/ignore [:deprecated-var]}
(update details :filter mbql.u/combine-filter-clauses inside-filter)))
;;; --------------------------------------------------- RENDERING ----------------------------------------------------
diff --git a/src/metabase/xrays/automagic_dashboards/filters.clj b/src/metabase/xrays/automagic_dashboards/filters.clj
index 55573730ff2..ec104e35ed0 100644
--- a/src/metabase/xrays/automagic_dashboards/filters.clj
+++ b/src/metabase/xrays/automagic_dashboards/filters.clj
@@ -158,6 +158,7 @@
[[clause-name, :as filter-clause]]
(when (seq filter-clause)
(if (= clause-name :and)
+ #_{:clj-kondo/ignore [:deprecated-var]}
(rest (mbql.u/simplify-compound-filter filter-clause))
[filter-clause])))
@@ -181,6 +182,7 @@
(if (seq existing-filters)
;; since the filters are programatically generated they won't have passed thru normalization, so make sure we
;; normalize them before passing them to `combine-filter-clauses`, which validates its input
+ #_{:clj-kondo/ignore [:deprecated-var]}
(apply mbql.u/combine-filter-clauses (map (partial mbql.normalize/normalize-fragment [:query :filter])
(cons refinement existing-filters)))
refinement)))
diff --git a/test/metabase/legacy_mbql/jvm_util_test.clj b/test/metabase/legacy_mbql/jvm_util_test.clj
index fcd825efb70..ccdbdb7b080 100644
--- a/test/metabase/legacy_mbql/jvm_util_test.clj
+++ b/test/metabase/legacy_mbql/jvm_util_test.clj
@@ -1,116 +1,20 @@
(ns metabase.legacy-mbql.jvm-util-test
+ {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}
(:require
[clojure.test :as t]
- [metabase.legacy-mbql.jvm-util :as mbql.jvm-u]
- [metabase.legacy-mbql.util :as mbql.u]))
-
-(t/deftest ^:parallel host-regex-on-urls-test
- (t/are [host url] (= host (re-find @#'mbql.jvm-u/host-regex url))
- "cdbaby.com" "https://cdbaby.com/some.txt"
- "fema.gov" "https://fema.gov/some/path/Vatini?search=foo"
- "geocities.jp" "https://www.geocities.jp/some/path/Turbitt?search=foo"
- "jalbum.net" "https://jalbum.net/some/path/Kirsz?search=foo"
- "usa.gov" "https://usa.gov/some/path/Curdell?search=foo"
- ;; Oops, this one captures a subdomain because it can't tell va.gov is supposed to be that short.
- "taxes.va.gov" "http://taxes.va.gov/some/path/Marritt?search=foo"
- "gmpg.org" "http://log.stuff.gmpg.org/some/path/Cambden?search=foo"
- "hatena.ne.jp" "http://hatena.ne.jp/"
- "telegraph.co.uk" "//telegraph.co.uk?foo=bar#tail"
- "bbc.co.uk" "bbc.co.uk/some/path?search=foo"
- "bbc.co.uk" "news.bbc.co.uk:port"))
-
-(t/deftest ^:parallel host-regex-on-emails-test
- (t/are [host email] (= host (re-find @#'mbql.jvm-u/host-regex email))
- "metabase.com" "[email protected]"
- "homeoffice.gov.uk" "[email protected]"
- "someisp.com" "[email protected]"
- "amazon.co.uk" "[email protected]"
- "hatena.ne.jp" "[email protected]"
- "hatena.ne.jp" "[email protected]"
- "ne.jp" "[email protected]"))
-
-(t/deftest ^:parallel domain-regex-on-urls-test
- (t/are [domain url] (= domain (re-find @#'mbql.jvm-u/domain-regex url))
- "cdbaby" "https://cdbaby.com/some.txt"
- "fema" "https://fema.gov/some/path/Vatini?search=foo"
- "geocities" "https://www.geocities.jp/some/path/Turbitt?search=foo"
- "jalbum" "https://jalbum.net/some/path/Kirsz?search=foo"
- "usa" "https://usa.gov/some/path/Curdell?search=foo"
- "taxes" "http://taxes.va.gov/some/path/Marritt?search=foo"
- "gmpg" "http://log.stuff.gmpg.org/some/path/Cambden?search=foo"
- "hatena" "http://hatena.ne.jp/"
- "telegraph" "//telegraph.co.uk?foo=bar#tail"
- "bbc" "bbc.co.uk/some/path?search=foo"))
-
-(t/deftest ^:parallel domain-regex-on-emails-test
- (t/are [domain email] (= domain (re-find @#'mbql.jvm-u/domain-regex email))
- "metabase" "[email protected]"
- "homeoffice" "[email protected]"
- "someisp" "[email protected]"
- "amazon" "[email protected]"
- "hatena" "[email protected]"
-
-(t/deftest ^:parallel subdomain-regex-on-urls-test
- (t/are [subdomain url] (= subdomain (re-find @#'mbql.jvm-u/subdomain-regex url))
- ;; Blanks. "www" doesn't count.
- nil "cdbaby.com"
- nil "https://fema.gov"
- nil "http://www.geocities.jp"
- nil "usa.gov/some/page.cgi.htm"
- nil "va.gov"
-
- ;; Basics - taking the first segment that isn't "www", IF it isn't the domain.
- "sub" "sub.jalbum.net"
- "subdomains" "subdomains.go.here.jalbum.net"
- "log" "log.stuff.gmpg.org"
- "log" "https://log.stuff.gmpg.org"
- "log" "log.stuff.gmpg.org/some/path"
- "log" "log.stuff.gmpg.org?search=yes"
-
- ;; Oops, we miss these! This is the reverse of the problem when picking the domain.
- ;; We can't tell without maintaining a huge list that va and ne are the real domains, and not the trailing
- ;; fragments like .co.uk - see below.
- nil "taxes.va.gov" ; True domain is va, subdomain is taxes.
- nil "hatena.ne.jp" ; True domain is ne, subdomain is hatena.
-
- ;; Sometimes the second-last part is a short suffix.
- ;; Mozilla maintains a huge list of these, but since this has to go into a regex and get passed to the database,
- ;; we use a best-effort matcher that gets the domain right most of the time.
- nil "telegraph.co.uk"
- nil "https://telegraph.co.uk"
- nil "telegraph.co.uk/some/article.php"
- "local" "local.news.telegraph.co.uk"
- nil "bbc.co.uk#fragment"
- "video" "video.bbc.co.uk"
- ;; "www" is disregarded as a possible subdomain.
- nil "www.usa.gov"
- nil "www.dot.va.gov"
- "licensing" "www.licensing.dot.va.gov"))
-
-(t/deftest ^:parallel path-regex-on-urls-test
- (t/are [path url] (= path (re-find @#'mbql.jvm-u/path-regex url))
- "/some.txt" "https://cdbaby.com/some.txt"
- "/some/path/Vatini" "https://fema.gov/some/path/Vatini?search=foo"
- "/some/path/Turbitt" "https://www.geocities.jp/some/path/Turbitt?search=foo"
- "/some/path/Kirsz" "https://jalbum.net/some/path/Kirsz?search=foo"
- "/some/path/Curdell" "https://usa.gov/some/path/Curdell?search=foo"
- "/some/path/Marritt" "http://taxes.va.gov/some/path/Marritt?search=foo"
- "/some/path/Cambden" "http://log.stuff.gmpg.org/some/path/Cambden?search=foo"
- "/" "http://hatena.ne.jp/"
- nil "//telegraph.co.uk?foo=bar#tail"
- "/some/path" "bbc.co.uk/some/path?search=foo"))
+ [metabase.legacy-mbql.util :as mbql.u]
+ [metabase.lib.filter.desugar.jvm :as lib.filter.desugar.jvm]))
(t/deftest ^:parallel desugar-host-and-domain-test
- (t/is (= [:regex-match-first [:field 1 nil] (str @#'mbql.jvm-u/host-regex)]
+ (t/is (= [:regex-match-first [:field 1 nil] (str @#'lib.filter.desugar.jvm/host-regex)]
(mbql.u/desugar-expression [:host [:field 1 nil]]))
"`host` should desugar to a `regex-match-first` clause with the host regex")
- (t/is (= [:regex-match-first [:field 1 nil] (str @#'mbql.jvm-u/domain-regex)]
+ (t/is (= [:regex-match-first [:field 1 nil] (str @#'lib.filter.desugar.jvm/domain-regex)]
(mbql.u/desugar-expression [:domain [:field 1 nil]]))
"`domain` should desugar to a `regex-match-first` clause with the domain regex")
- (t/is (= [:regex-match-first [:field 1 nil] (str @#'mbql.jvm-u/subdomain-regex)]
+ (t/is (= [:regex-match-first [:field 1 nil] (str @#'lib.filter.desugar.jvm/subdomain-regex)]
(mbql.u/desugar-expression [:subdomain [:field 1 nil]]))
"`subdomain` should desugar to a `regex-match-first` clause with the subdomain regex")
- (t/is (= [:regex-match-first [:field 1 nil] (str @#'mbql.jvm-u/path-regex)]
+ (t/is (= [:regex-match-first [:field 1 nil] (str @#'lib.filter.desugar.jvm/path-regex)]
(mbql.u/desugar-expression [:path [:field 1 nil]]))
"`path` should desugar to a `regex-match-first` clause with the path regex"))
diff --git a/test/metabase/legacy_mbql/util_test.cljc b/test/metabase/legacy_mbql/util_test.cljc
index 196c2746b94..48e586d8aa7 100644
--- a/test/metabase/legacy_mbql/util_test.cljc
+++ b/test/metabase/legacy_mbql/util_test.cljc
@@ -1,6 +1,7 @@
(ns metabase.legacy-mbql.util-test
+ {:clj-kondo/config '{:linters {:deprecated-var {:level :off}}}}
(:require
- #?@(:clj (^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.test :as mt])
+ #?@(:clj ([metabase.test.util.i18n])
:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
[clojure.string :as str]
[clojure.test :as t]
@@ -534,12 +535,12 @@
(t/deftest ^:parallel desugar-temporal-extract-test
(t/testing "desugaring :get-year, :get-month, etc"
- (doseq [[[op mode] unit] mbql.u/temporal-extract-ops->unit]
+ (doseq [[[op mode] unit] @#'mbql.u/temporal-extract-ops->unit]
(t/is (= [:temporal-extract [:field 1 nil] unit]
- (mbql.u/desugar-temporal-extract [op [:field 1 nil] mode])))
+ (#'mbql.u/desugar-temporal-extract [op [:field 1 nil] mode])))
(t/is (= [:+ [:temporal-extract [:field 1 nil] unit] 1]
- (mbql.u/desugar-temporal-extract [:+ [op [:field 1 nil] mode] 1]))))))
+ (#'mbql.u/desugar-temporal-extract [:+ [op [:field 1 nil] mode] 1]))))))
(t/deftest ^:parallel desugar-divide-with-extra-args-test
(t/testing `mbql.u/desugar-expression
@@ -988,7 +989,7 @@
(t/is (= [:=
[:expression "Date" {:temporal-unit :quarter}]
[:relative-datetime 0 :quarter]]
- (mbql.u/desugar-time-interval [:time-interval [:expression "Date"] :current :quarter]))))
+ (#'mbql.u/desugar-time-interval [:time-interval [:expression "Date"] :current :quarter]))))
(t/deftest ^:parallel desugar-month-quarter-day-name-test
(t/is (= [:case [[[:= [:field 1 nil] 1] "Jan"]
@@ -1026,7 +1027,7 @@
#?(:clj
(t/deftest ^:synchronized desugar-month-quarter-day-name-i18n-test
- (mt/with-user-locale "es"
+ (metabase.test.util.i18n/with-user-locale "es"
;; JVM versions 17 and older for some languages (including Spanish) use eg. "oct.", while in JVMs 18+ they
;; use "oct". I wish I were joking, but I'm not. These tests were passing on 21 and failing on 17 and 11
;; before I made them flexible about the dot.
diff --git a/test/metabase/lib/convert_test.cljc b/test/metabase/lib/convert_test.cljc
index 0a5e29f08e7..8ac8eec3bf0 100644
--- a/test/metabase/lib/convert_test.cljc
+++ b/test/metabase/lib/convert_test.cljc
@@ -1581,3 +1581,41 @@
:lib/metadata meta/metadata-provider}]
(is (=? {:native {:projections [:count]}}
(lib.convert/->legacy-MBQL query))))))
+
+(deftest ^:parallel between-with-options->legacy-test
+ (is (= [:between
+ [:field 72922 {:base-type :type/Text}]
+ [:relative-datetime -15 :day]
+ [:relative-datetime 0 :day]]
+ (lib.convert/->legacy-MBQL [:between
+ {:include-current true,
+ :lib/uuid "b8991b40-d452-4922-8768-b07f6f2b1918"}
+ [:field
+ {:base-type :type/Text
+ :lib/uuid "408cebeb-4511-4e3f-87c4-bc9d9cb84eca"}
+ 72922]
+ [:relative-datetime
+ {:lib/uuid "4eeca5bb-1614-48d1-8bfd-30c91dd4f546"}
+ -15
+ :day]
+ [:relative-datetime
+ {:lib/uuid "85a69d68-a2df-4c22-8a45-2203c837d3bf"}
+ 0
+ :day]]))))
+
+(deftest ^:parallel and-or-with-options->legacy-test
+ (doseq [tag [:and :or]]
+ (is (= [tag
+ [:starts-with [:field 243 {:base-type :type/Text}] "B" {:case-sensitive false}]
+ [:starts-with [:field 243 {:base-type :type/Text}] "C" {:case-sensitive false}]]
+ (lib.convert/->legacy-MBQL
+ [tag
+ {:lib/uuid "fd823910-ffc9-4508-a6af-fa37fe29514d", :case-sensitive false}
+ [:starts-with
+ {:case-sensitive false, :lib/uuid "dc413cb8-429d-4103-aaa4-06e3d3bf0a4d"}
+ [:field {:base-type :type/Text, :lib/uuid "b94a285d-32a5-45ad-a261-d4c67f1af8db", :effective-type :type/Text} 243]
+ "B"]
+ [:starts-with
+ {:case-sensitive false, :lib/uuid "92c8ee03-6bc6-45c9-865c-57d0c5d53e23"}
+ [:field {:base-type :type/Text, :lib/uuid "044811f6-9e30-4c42-b5b6-6afde5031675", :effective-type :type/Text} 243]
+ "C"]])))))
diff --git a/test/metabase/lib/filter/desugar/jvm_test.clj b/test/metabase/lib/filter/desugar/jvm_test.clj
new file mode 100644
index 00000000000..c93c3264e02
--- /dev/null
+++ b/test/metabase/lib/filter/desugar/jvm_test.clj
@@ -0,0 +1,125 @@
+(ns metabase.lib.filter.desugar.jvm-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.lib.filter.desugar :as lib.filter.desugar]
+ [metabase.lib.filter.desugar.jvm :as lib.filter.desugar.jvm]))
+
+(defn- opts [& {:as kvs}]
+ (merge {:lib/uuid (str (random-uuid))} kvs))
+
+(deftest ^:parallel host-regex-on-urls-test
+ (are [host url] (= host (re-find @#'lib.filter.desugar.jvm/host-regex url))
+ "cdbaby.com" "https://cdbaby.com/some.txt"
+ "fema.gov" "https://fema.gov/some/path/Vatini?search=foo"
+ "geocities.jp" "https://www.geocities.jp/some/path/Turbitt?search=foo"
+ "jalbum.net" "https://jalbum.net/some/path/Kirsz?search=foo"
+ "usa.gov" "https://usa.gov/some/path/Curdell?search=foo"
+ ;; Oops, this one captures a subdomain because it can't tell va.gov is supposed to be that short.
+ "taxes.va.gov" "http://taxes.va.gov/some/path/Marritt?search=foo"
+ "gmpg.org" "http://log.stuff.gmpg.org/some/path/Cambden?search=foo"
+ "hatena.ne.jp" "http://hatena.ne.jp/"
+ "telegraph.co.uk" "//telegraph.co.uk?foo=bar#tail"
+ "bbc.co.uk" "bbc.co.uk/some/path?search=foo"
+ "bbc.co.uk" "news.bbc.co.uk:port"))
+
+(deftest ^:parallel host-regex-on-emails-test
+ (are [host email] (= host (re-find @#'lib.filter.desugar.jvm/host-regex email))
+ "metabase.com" "[email protected]"
+ "homeoffice.gov.uk" "[email protected]"
+ "someisp.com" "[email protected]"
+ "amazon.co.uk" "[email protected]"
+ "hatena.ne.jp" "[email protected]"
+ "hatena.ne.jp" "[email protected]"
+ "ne.jp" "[email protected]"))
+
+(deftest ^:parallel domain-regex-on-urls-test
+ (are [domain url] (= domain (re-find @#'lib.filter.desugar.jvm/domain-regex url))
+ "cdbaby" "https://cdbaby.com/some.txt"
+ "fema" "https://fema.gov/some/path/Vatini?search=foo"
+ "geocities" "https://www.geocities.jp/some/path/Turbitt?search=foo"
+ "jalbum" "https://jalbum.net/some/path/Kirsz?search=foo"
+ "usa" "https://usa.gov/some/path/Curdell?search=foo"
+ "taxes" "http://taxes.va.gov/some/path/Marritt?search=foo"
+ "gmpg" "http://log.stuff.gmpg.org/some/path/Cambden?search=foo"
+ "hatena" "http://hatena.ne.jp/"
+ "telegraph" "//telegraph.co.uk?foo=bar#tail"
+ "bbc" "bbc.co.uk/some/path?search=foo"))
+
+(deftest ^:parallel domain-regex-on-emails-test
+ (are [domain email] (= domain (re-find @#'lib.filter.desugar.jvm/domain-regex email))
+ "metabase" "[email protected]"
+ "homeoffice" "[email protected]"
+ "someisp" "[email protected]"
+ "amazon" "[email protected]"
+ "hatena" "[email protected]"
+
+(deftest ^:parallel subdomain-regex-on-urls-test
+ (are [subdomain url] (= subdomain (re-find @#'lib.filter.desugar.jvm/subdomain-regex url))
+ ;; Blanks. "www" doesn't count.
+ nil "cdbaby.com"
+ nil "https://fema.gov"
+ nil "http://www.geocities.jp"
+ nil "usa.gov/some/page.cgi.htm"
+ nil "va.gov"
+
+ ;; Basics - taking the first segment that isn't "www", IF it isn't the domain.
+ "sub" "sub.jalbum.net"
+ "subdomains" "subdomains.go.here.jalbum.net"
+ "log" "log.stuff.gmpg.org"
+ "log" "https://log.stuff.gmpg.org"
+ "log" "log.stuff.gmpg.org/some/path"
+ "log" "log.stuff.gmpg.org?search=yes"
+
+ ;; Oops, we miss these! This is the reverse of the problem when picking the domain.
+ ;; We can't tell without maintaining a huge list that va and ne are the real domains, and not the trailing
+ ;; fragments like .co.uk - see below.
+ nil "taxes.va.gov" ; True domain is va, subdomain is taxes.
+ nil "hatena.ne.jp" ; True domain is ne, subdomain is hatena.
+
+ ;; Sometimes the second-last part is a short suffix.
+ ;; Mozilla maintains a huge list of these, but since this has to go into a regex and get passed to the database,
+ ;; we use a best-effort matcher that gets the domain right most of the time.
+ nil "telegraph.co.uk"
+ nil "https://telegraph.co.uk"
+ nil "telegraph.co.uk/some/article.php"
+ "local" "local.news.telegraph.co.uk"
+ nil "bbc.co.uk#fragment"
+ "video" "video.bbc.co.uk"
+ ;; "www" is disregarded as a possible subdomain.
+ nil "www.usa.gov"
+ nil "www.dot.va.gov"
+ "licensing" "www.licensing.dot.va.gov"))
+
+(deftest ^:parallel path-regex-on-urls-test
+ (are [path url] (= path (re-find @#'lib.filter.desugar.jvm/path-regex url))
+ "/some.txt" "https://cdbaby.com/some.txt"
+ "/some/path/Vatini" "https://fema.gov/some/path/Vatini?search=foo"
+ "/some/path/Turbitt" "https://www.geocities.jp/some/path/Turbitt?search=foo"
+ "/some/path/Kirsz" "https://jalbum.net/some/path/Kirsz?search=foo"
+ "/some/path/Curdell" "https://usa.gov/some/path/Curdell?search=foo"
+ "/some/path/Marritt" "http://taxes.va.gov/some/path/Marritt?search=foo"
+ "/some/path/Cambden" "http://log.stuff.gmpg.org/some/path/Cambden?search=foo"
+ "/" "http://hatena.ne.jp/"
+ nil "//telegraph.co.uk?foo=bar#tail"
+ "/some/path" "bbc.co.uk/some/path?search=foo"))
+
+(deftest ^:parallel desugar-host-and-domain-test-1
+ (testing "`host` should desugar to a `regex-match-first` clause with the host regex"
+ (is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/host-regex)]
+ (#'lib.filter.desugar/desugar-expression [:host (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-host-and-domain-test-2
+ (testing "`domain` should desugar to a `regex-match-first` clause with the domain regex"
+ (is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/domain-regex)]
+ (#'lib.filter.desugar/desugar-expression [:domain (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-host-and-domain-test-3
+ (testing "`subdomain` should desugar to a `regex-match-first` clause with the subdomain regex"
+ (is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/subdomain-regex)]
+ (#'lib.filter.desugar/desugar-expression [:subdomain (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-host-and-domain-test-4
+ (testing "`path` should desugar to a `regex-match-first` clause with the path regex"
+ (is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/path-regex)]
+ (#'lib.filter.desugar/desugar-expression [:path (opts) [:field (opts) 1]])))))
diff --git a/test/metabase/lib/filter/desugar_test.cljc b/test/metabase/lib/filter/desugar_test.cljc
new file mode 100644
index 00000000000..ca288457fc1
--- /dev/null
+++ b/test/metabase/lib/filter/desugar_test.cljc
@@ -0,0 +1,621 @@
+(ns metabase.lib.filter.desugar-test
+ (:require
+ #?@(:clj ([metabase.lib-be.settings] ; for the start-of-week setting
+ [metabase.test.util.i18n])
+ :cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
+ [clojure.test :refer [are deftest is testing]]
+ [metabase.lib.filter.desugar :as lib.filter.desugar]))
+
+#?(:clj (comment metabase.lib-be.settings/keep-me)
+ :cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))
+
+(defn- opts [& {:as kvs}]
+ (merge {:lib/uuid (str (random-uuid))} kvs))
+
+(deftest ^:parallel desugar-time-interval-test-1
+ (testing "`time-interval` with value > 1 or < -1 should generate a `between` clause"
+ (is (=? [:between {}
+ [:expression {:temporal-unit :month} "CC"]
+ [:relative-datetime {} 1 :month]
+ [:relative-datetime {} 2 :month]]
+ (lib.filter.desugar/desugar-filter-clause [:time-interval (opts) [:expression (opts) "CC"] 2 :month])))))
+
+(deftest ^:parallel desugar-time-interval-test-2
+ (testing "test the `include-current` option -- interval should start or end at `0` instead of `1`"
+ (is (=? [:between {}
+ [:expression {:temporal-unit :month} "CC"]
+ [:relative-datetime {} 0 :month]
+ [:relative-datetime {} 2 :month]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:time-interval (opts :include-current true) [:expression (opts) "CC"] 2 :month])))))
+
+(deftest ^:parallel desugar-time-interval-test-3
+ (testing "`time-interval` with value = 1 should generate an `=` clause"
+ (is (=? [:= {}
+ [:expression {:temporal-unit :month} "CC"]
+ [:relative-datetime {} 1 :month]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:time-interval (opts) [:expression (opts) "CC"] 1 :month])))))
+
+(deftest ^:parallel desugar-time-interval-test-4
+ (testing "`time-interval` with value = -1 should generate an `=` clause"
+ (is (=? [:= {}
+ [:expression {:temporal-unit :week} "CC"]
+ [:relative-datetime {} -1 :week]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:time-interval (opts) [:expression (opts) "CC"] -1 :week])))))
+
+(deftest ^:parallel desugar-time-interval-test-5
+ (testing "`include-current` option"
+ (testing "interval with value = 1 should generate a `between` clause"
+ (is (=? [:between {}
+ [:expression {:temporal-unit :month} "CC"]
+ [:relative-datetime {} 0 :month]
+ [:relative-datetime {} 1 :month]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:time-interval (opts :include-current true)
+ [:expression (opts) "CC"]
+ 1 :month]))))))
+
+(deftest ^:parallel desugar-time-interval-test-6
+ (testing "`include-current` option"
+ (testing "`include-current` option -- interval with value = 1 should generate a `between` clause"
+ (is (=? [:between {}
+ [:expression {:temporal-unit :day} "CC"]
+ [:relative-datetime {} -1 :day]
+ [:relative-datetime {} 0 :day]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:time-interval (opts :include-current true)
+ [:expression (opts) "CC"]
+ -1 :day]))))))
+
+(deftest ^:parallel desugar-time-interval-test-7
+ (testing "keywords like `:current` should work correctly"
+ (is (=? [:= {}
+ [:expression {:temporal-unit :week} "CC"]
+ [:relative-datetime {} 0 :week]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:time-interval (opts)
+ [:expression (opts) "CC"]
+ :current :week])))))
+
+(deftest ^:parallel desugar-relative-time-interval-negative-test
+ (testing "Desugaring relative-date-time produces expected [:and (opts) [:>=..] [:<..]] expression"
+ (let [value -10
+ bucket :day
+ offset-value -8
+ offset-bucket :week]
+ (testing "expression reference is transformed correctly"
+ (is (=? [:and {}
+ [:>= {}
+ [:expression {} "cc"]
+ [:+ {}
+ [:relative-datetime {} value bucket]
+ [:interval {} offset-value offset-bucket]]]
+ [:< {}
+ [:expression {} "cc"]
+ [:+ {}
+ [:relative-datetime {} 0 bucket]
+ [:interval {} offset-value offset-bucket]]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:relative-time-interval (opts) [:expression (opts) "cc"] value bucket offset-value offset-bucket]))))
+ (testing "field reference is transformed correctly"
+ (is (=? [:and {}
+ [:>= {}
+ [:field {:temporal-unit :default} 100]
+ [:+ {}
+ [:relative-datetime {} value bucket]
+ [:interval {} offset-value offset-bucket]]]
+ [:< {}
+ [:field {:temporal-unit :default} 100]
+ [:+ {}
+ [:relative-datetime {} 0 bucket]
+ [:interval {} offset-value offset-bucket]]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:relative-time-interval (opts)
+ [:field (opts :temporal-unit :default) 100]
+ value
+ bucket
+ offset-value
+ offset-bucket])))))))
+
+(deftest ^:parallel desugar-relative-time-interval-positive-test
+ (testing "Desugaring relative-date-time produces expected [:and (opts) [:>=..] [:<..]] expression"
+ (let [value 10
+ bucket :day
+ offset-value 8
+ offset-bucket :week]
+ (testing "expression reference is transformed correctly"
+ (is (=? [:and {}
+ [:>= {} [:expression {} "cc"] [:+ {} [:relative-datetime {} 1 bucket] [:interval {} offset-value offset-bucket]]]
+ [:< {} [:expression {} "cc"] [:+ {} [:relative-datetime {} (inc value) bucket] [:interval {} offset-value offset-bucket]]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:relative-time-interval (opts)
+ [:expression (opts) "cc"]
+ value bucket offset-value offset-bucket]))))
+ (testing "field reference is transformed correctly"
+ (is (=? [:and {}
+ [:>= {} [:field {:temporal-unit :default} 100] [:+ {} [:relative-datetime {} 1 bucket] [:interval {} offset-value offset-bucket]]]
+ [:< {} [:field {:temporal-unit :default} 100] [:+ {} [:relative-datetime {} (inc value) bucket] [:interval {} offset-value offset-bucket]]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:relative-time-interval (opts)
+ [:field (opts :temporal-unit :default) 100]
+ value bucket offset-value offset-bucket])))))))
+
+(deftest ^:parallel desugar-during-test
+ (testing "Desugaring during filter produces expected [:and (opts) [:>=..] [:<..]] expression"
+ (let [value "2020-01-01T13:24:32"]
+ (doseq [{:keys [unit expected-lower expected-upper]}
+ [{:unit :second
+ :expected-lower "2020-01-01T13:24:32"
+ :expected-upper "2020-01-01T13:24:33"}
+ {:unit :minute
+ :expected-lower "2020-01-01T13:24"
+ :expected-upper "2020-01-01T13:25"}
+ {:unit :hour
+ :expected-lower "2020-01-01T13:00"
+ :expected-upper "2020-01-01T14:00"}
+ {:unit :day
+ :expected-lower "2020-01-01T00:00"
+ :expected-upper "2020-01-02T00:00"}
+ {:unit :month
+ :expected-lower "2020-01-01T00:00"
+ :expected-upper "2020-02-01T00:00"}
+ {:unit :year
+ :expected-lower "2020-01-01T00:00"
+ :expected-upper "2021-01-01T00:00"}]]
+ (testing (str "expression reference is transformed correctly for unit " unit)
+ (is (=? [:and {}
+ [:>= {} [:expression {} "cc"] expected-lower]
+ [:< {} [:expression {} "cc"] expected-upper]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:during (opts) [:expression (opts) "cc"] value unit]))))
+ (testing (str "field reference is transformed correctly for unit " unit)
+ (is (=? [:and {}
+ [:>= {} [:field {:temporal-unit :default} 100] expected-lower]
+ [:< {} [:field {:temporal-unit :default} 100] expected-upper]]
+ (lib.filter.desugar/desugar-filter-clause [:during (opts) [:field (opts) 100] value unit]))))))))
+
+(deftest ^:parallel desugar-if-test-1
+ (testing "Desugaring if produces expected [:case ..] expression"
+ (is (=? [:case {}
+ [[[:< {} [:field {} 1] 1] 2]
+ [[:< {} [:field {} 3] 4] 5]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:if (opts)
+ [[[:< (opts) [:field (opts) 1] 1] 2]
+ [[:< (opts) [:field (opts) 3] 4] 5]]])))))
+
+(deftest ^:parallel desugar-if-test-2
+ (testing "Desugaring if produces expected [:case ..] expression"
+ (is (=? [:case {:default 3}
+ [[[:< {} [:field {} 1] 1] 2]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:if (opts :default 3)
+ [[[:< (opts) [:field (opts) 1] 1] 2]]])))))
+
+(deftest ^:parallel desugar-if-with-default-value-test
+ (is (= [:case {:lib/uuid "00000000-0000-0000-0000-000000000000", :lib/expression-name "If"}
+ [[[:= {:lib/uuid "00000000-0000-0000-0000-000000000001"}
+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000002"} 255] 1]
+ "First"]
+ [[:= {:lib/uuid "00000000-0000-0000-0000-000000000003"}
+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000004"} 255] 2]
+ "Second"]]
+ "Other"]
+ (lib.filter.desugar/desugar-filter-clause
+ [:if {:lib/uuid "00000000-0000-0000-0000-000000000000", :lib/expression-name "If"}
+ [[[:= {:lib/uuid "00000000-0000-0000-0000-000000000001"}
+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000002"} 255] 1]
+ "First"]
+ [[:= {:lib/uuid "00000000-0000-0000-0000-000000000003"}
+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000004"} 255] 2]
+ "Second"]]
+ "Other"]))))
+
+(deftest ^:parallel desugar-in-test
+ (testing "Desugaring in and not-in produces expected [:= ..] and [:!= ..] expressions"
+ (are [clause expected] (=? expected
+ (lib.filter.desugar/desugar-filter-clause clause))
+ [:in (opts) [:field (opts) 1] 2]
+ [:= {} [:field {} 1] 2]
+
+ [:in (opts) [:field (opts) 1] [:field (opts) 2]]
+ [:= {} [:field {} 1] [:field {} 2]]
+
+ [:in (opts) [:field (opts) 1] 2 3]
+ [:or {}
+ [:= {}
+ [:field {} 1]
+ 2]
+ [:= {} [:field {} 1] 3]]
+
+ [:not-in (opts)
+ [:field (opts) 1]
+ 2]
+ [:!= {} [:field {} 1] 2]
+
+ [:not-in (opts)
+ [:field (opts) 1]
+ [:field (opts) 2]]
+ [:!= {}
+ [:field {} 1]
+ [:field {} 2]]
+
+ [:not-in (opts)
+ [:field (opts) 1]
+ 2
+ 3]
+ [:and {}
+ [:!= {} [:field {} 1] 2]
+ [:!= {} [:field {} 1] 3]])))
+
+(deftest ^:parallel desugar-relative-datetime-with-current-test-1
+ (testing "when comparing `:relative-datetime`to `:field`, it should take the temporal unit of the `:field`"
+ (is (=? [:= {}
+ [:field {:temporal-unit :minute} 1]
+ [:relative-datetime {} 0 :minute]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:= (opts)
+ [:field (opts :temporal-unit :minute) 1]
+ [:relative-datetime (opts) :current]])))))
+
+(deftest ^:parallel desugar-relative-datetime-with-current-test-2
+ (testing "otherwise it should just get a unit of `:default`"
+ (is (=? [:= {}
+ [:field {} 1]
+ [:relative-datetime {} 0 :default]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:= (opts)
+ [:field (opts) 1]
+ [:relative-datetime (opts) :current]])))))
+
+(deftest ^:parallel desugar-relative-datetime-with-current-test-3
+ (testing "we should be able to handle datetime fields even if they are nested inside another clause"
+ (is (=? [:= {}
+ [:field {:temporal-unit :week, :binning {:strategy :default}} 1]
+ [:relative-datetime {} 0 :week]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:= (opts)
+ [:field (opts :temporal-unit :week, :binning {:strategy :default}) 1]
+ [:relative-datetime (opts) :current]])))))
+
+(deftest ^:parallel relative-datetime-current-inside-between-test
+ (testing ":relative-datetime should work inside a :between clause (#19606)\n"
+ (let [absolute "2022-03-11T15:48:00-08:00"
+ relative (fn []
+ [:relative-datetime (opts) :current])
+ expected (fn [v unit]
+ (cond
+ (string? v) absolute
+ (= (first v) :relative-datetime) [:relative-datetime {} 0 unit]))]
+ (doseq [x [(relative) absolute]
+ y [(relative) absolute]
+ unit [:week :default]]
+ (testing (pr-str [:between (opts) [:field {:temporal-unit unit} 1] x y])
+ (is (=? [:between {}
+ [:field {:temporal-unit unit} 1]
+ (expected x unit)
+ (expected y unit)]
+ (lib.filter.desugar/desugar-filter-clause
+ [:between
+ (opts)
+ [:field (opts :temporal-unit unit) 1]
+ x
+ y]))))))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-1
+ (testing "desugaring := and :!= with extra args"
+ (testing "= with extra args should get converted to or"
+ (is (=? [:or {}
+ [:= {} [:field {} 1] 2]
+ [:= {} [:field {} 1] 3]
+ [:= {} [:field {} 1] 4]
+ [:= {} [:field {} 1] 5]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:= (opts)
+ [:field (opts) 1] 2 3 4 5]))))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-2
+ (testing "desugaring := and :!= with extra args"
+ (testing "!= with extra args should get converted to or"
+ (is (=? [:and {}
+ [:!= {} [:field {} 1] 2]
+ [:!= {} [:field {} 1] 3]
+ [:!= {} [:field {} 1] 4]
+ [:!= {} [:field {} 1] 5]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:!= (opts) [:field (opts) 1] 2 3 4 5]))))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-3
+ (testing "desugaring :inside"
+ (is (=? [:and {}
+ [:between {} [:field {} 1] -10.0 10.0]
+ [:between {} [:field {} 2] -20.0 20.0]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:inside (opts) [:field (opts) 1] [:field (opts) 2] 10.0 -20.0 -10.0 20.0])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-4
+ (testing "desugaring :is-null"
+ (is (=? [:= {} [:field {} 1] nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:is-null (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-5
+ (testing "desugaring :not-null"
+ (is (=? [:!= {} [:field {} 1] nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:not-null (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-6
+ (testing "desugaring :is-empty of nil base-type"
+ (is (=? [:= {} [:field {} 1] nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:is-empty (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-7
+ (testing "desugaring :is-empty of emptyable base-type :type/Text"
+ (is (=? [:or {}
+ [:= {} [:field {:base-type :type/Text} 1] nil]
+ [:= {} [:field {:base-type :type/Text} 1] ""]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:is-empty (opts) [:field (opts :base-type :type/Text) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-8
+ (testing "desugaring :is-empty of string expression #41265"
+ (is (=? [:or {}
+ [:= {}
+ [:regex-match-first {} "foo" "bar"]
+ nil]
+ [:= {}
+ [:regex-match-first {} "foo" "bar"]
+ ""]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:is-empty (opts) [:regex-match-first (opts) "foo" "bar"]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-9
+ (testing "desugaring :is-empty of not emptyable base-type :type/DateTime"
+ (is (=? [:= {}
+ [:field {:base-type :type/DateTime} 1]
+ nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:is-empty (opts) [:field (opts :base-type :type/DateTime) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-10
+ (testing "desugaring :is-empty of :type/PostgresEnum #48022"
+ (is (=? [:= {}
+ [:field {:base-type :type/PostgresEnum} 1]
+ nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:is-empty (opts) [:field (opts :base-type :type/PostgresEnum) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-11
+ (testing "desugaring :not-empty of nil base-type"
+ (is (=? [:!= {}
+ [:field {} 1]
+ nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:not-empty (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-12
+ (testing "desugaring :not-empty of emptyable base-type :type/Text"
+ (is (=? [:and {}
+ [:!= {} [:field {:base-type :type/Text} 1] nil]
+ [:!= {} [:field {:base-type :type/Text} 1] ""]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:not-empty (opts) [:field (opts :base-type :type/Text) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-13
+ (testing "desugaring :not-empty of string expression #41265"
+ (is (=? [:and {}
+ [:!= {} [:regex-match-first {} "foo" "bar"] nil]
+ [:!= {} [:regex-match-first {} "foo" "bar"] ""]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:not-empty (opts) [:regex-match-first (opts) "foo" "bar"]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-14
+ (testing "desugaring :not-empty of not emptyable base-type"
+ (is (=? [:!= {}
+ [:field {:base-type :type/DateTime} 1]
+ nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:not-empty (opts) [:field (opts :base-type :type/DateTime) 1]])))))
+
+(deftest ^:parallel desugar-other-filter-clauses-test-15
+ (testing "desugaring :not-empty of :type/PostgresEnum #48022"
+ (is (=? [:!= {}
+ [:field {:base-type :type/PostgresEnum} 1]
+ nil]
+ (lib.filter.desugar/desugar-filter-clause
+ [:not-empty (opts) [:field (opts :base-type :type/PostgresEnum) 1]])))))
+
+(deftest ^:parallel desugar-does-not-contain-test-1
+ (testing "desugaring does-not-contain"
+ (testing "without options"
+ (is (=? [:not {}
+ [:contains {} [:field {} 1] "ABC"]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:does-not-contain (opts) [:field (opts) 1] "ABC"]))))))
+
+(deftest ^:parallel desugar-does-not-contain-test-2
+ (testing "desugaring does-not-contain"
+ (testing "*with* options"
+ (is (=? [:not {}
+ [:contains {:case-sensitive false} [:field {} 1] "ABC"]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:does-not-contain (opts :case-sensitive false)
+ [:field (opts) 1]
+ "ABC"]))))))
+
+(deftest ^:parallel desugar-does-not-contain-test-3
+ (testing "desugaring does-not-contain"
+ (testing "desugaring does-not-contain with multiple arguments"
+ (testing "without options"
+ (is (=? [:and {}
+ [:not {}
+ [:contains {} [:field {} 1] "ABC"]]
+ [:not {}
+ [:contains {} [:field {} 1] "XYZ"]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:does-not-contain (opts) [:field (opts) 1] "ABC" "XYZ"])))))))
+
+(deftest ^:parallel desugar-does-not-contain-test-4
+ (testing "desugaring does-not-contain"
+ (testing "desugaring does-not-contain with multiple arguments"
+ (testing "without options"
+ (is (=? [:and {}
+ [:not {} [:contains {} [:field {} 1] "ABC"]]
+ [:not {} [:contains {} [:field {} 1] "XYZ"]]
+ [:not {} [:contains {} [:field {} 1] "LMN"]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:does-not-contain (opts) [:field (opts) 1] "ABC" "XYZ" "LMN"])))))))
+
+(deftest ^:parallel desugar-does-not-contain-test-5
+ (testing "desugaring does-not-contain"
+ (testing "desugaring does-not-contain with multiple arguments"
+ (testing "*with* options"
+ (is (=? [:and {}
+ [:not {} [:contains {:case-sensitive false} [:field {} 1] "ABC"]]
+ [:not {} [:contains {:case-sensitive false} [:field {} 1] "XYZ"]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:does-not-contain (opts :case-sensitive false) [:field (opts) 1] "ABC" "XYZ"])))))))
+
+(deftest ^:parallel desugar-does-not-contain-test-6
+ (testing "desugaring does-not-contain"
+ (testing "desugaring does-not-contain with multiple arguments"
+ (testing "*with* options"
+ (is (=? [:and {}
+ [:not {:case-sensitive false} [:contains {} [:field {} 1] "ABC"]]
+ [:not {:case-sensitive false} [:contains {} [:field {} 1] "XYZ"]]
+ [:not {:case-sensitive false} [:contains {} [:field {} 1] "LMN"]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:does-not-contain (opts :case-sensitive false) [:field (opts) 1] "ABC" "XYZ" "LMN"])))))))
+
+(deftest ^:parallel desugar-temporal-extract-test
+ (testing "desugaring :get-year, :get-month, etc"
+ (doseq [[[op mode] unit] @#'lib.filter.desugar/temporal-extract-ops->unit
+ :let [clause (if mode
+ [op (opts) [:field (opts) 1] mode]
+ [op (opts) [:field (opts) 1]])]]
+ (is (=? [:temporal-extract {} [:field {} 1] unit]
+ (#'lib.filter.desugar/desugar-temporal-extract
+ clause)))
+ (is (=? [:+ {} [:temporal-extract {} [:field {} 1] unit] 1]
+ (#'lib.filter.desugar/desugar-temporal-extract
+ [:+ (opts) clause 1]))))))
+
+(deftest ^:parallel desugar-divide-with-extra-args-test-1
+ (testing '#'lib.filter.desugar/desugar-expression
+ (are [expression expected] (=? expected (#'lib.filter.desugar/desugar-expression expression))
+ [:/ (opts) 1 2]
+ [:/ {} 1 2]
+
+ [:/ (opts) 1 2 3]
+ [:/ {} [:/ {} 1 2] 3]
+
+ [:/ (opts) 1 2 3 4]
+ [:/ {} [:/ {} [:/ {} 1 2] 3] 4])))
+
+(deftest ^:parallel desugar-divide-with-extra-args-test-2
+ (testing 'lib.filter.desugar/desugar-filter-clause
+ (are [expression expected] (=? expected (lib.filter.desugar/desugar-filter-clause expression))
+ [:= (opts) 1 [:/ (opts) 1 2]]
+ [:= {} 1 [:/ {} 1 2]]
+
+ [:= (opts) 1 [:/ (opts) 1 2 3]]
+ [:= {} 1 [:/ {} [:/ {} 1 2] 3]]
+
+ [:= (opts) 1 [:/ (opts) 1 2 3 4]]
+ [:= {} 1 [:/ {} [:/ {} [:/ {} 1 2] 3] 4]])))
+
+(deftest ^:parallel desugar-time-interval-expression-test
+ (is (=? [:= {}
+ [:expression {:temporal-unit :quarter} "Date"]
+ [:relative-datetime {} 0 :quarter]]
+ (#'lib.filter.desugar/desugar-time-interval
+ [:time-interval (opts) [:expression (opts) "Date"] :current :quarter]))))
+
+(deftest ^:parallel desugar-month-quarter-day-name-test-1
+ (testing "`month-name` should desugar to a `:case` clause with values for each month"
+ (is (=? [:case
+ {:default ""}
+ [[[:= {} [:field {} 1] 1] "Jan"]
+ [[:= {} [:field {} 1] 2] "Feb"]
+ [[:= {} [:field {} 1] 3] "Mar"]
+ [[:= {} [:field {} 1] 4] "Apr"]
+ [[:= {} [:field {} 1] 5] "May"]
+ [[:= {} [:field {} 1] 6] "Jun"]
+ [[:= {} [:field {} 1] 7] "Jul"]
+ [[:= {} [:field {} 1] 8] "Aug"]
+ [[:= {} [:field {} 1] 9] "Sep"]
+ [[:= {} [:field {} 1] 10] "Oct"]
+ [[:= {} [:field {} 1] 11] "Nov"]
+ [[:= {} [:field {} 1] 12] "Dec"]]]
+ (#'lib.filter.desugar/desugar-expression [:month-name (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-month-quarter-day-name-test-2
+ (testing "`quarter-name` should desugar to a `:case` clause with values for each quarter"
+ (is (=? [:case {:default ""}
+ [[[:= {} [:field {} 1] 1] "Q1"]
+ [[:= {} [:field {} 1] 2] "Q2"]
+ [[:= {} [:field {} 1] 3] "Q3"]
+ [[:= {} [:field {} 1] 4] "Q4"]]]
+ (#'lib.filter.desugar/desugar-expression [:quarter-name (opts) [:field (opts) 1]])))))
+
+(deftest ^:parallel desugar-month-quarter-day-name-test-3
+ (testing "`day-name` should desugar to a `:case` clause with values for each weekday"
+ (is (=? [:case {:default ""}
+ [[[:= {} [:field {} 1] 1] "Sunday"]
+ [[:= {} [:field {} 1] 2] "Monday"]
+ [[:= {} [:field {} 1] 3] "Tuesday"]
+ [[:= {} [:field {} 1] 4] "Wednesday"]
+ [[:= {} [:field {} 1] 5] "Thursday"]
+ [[:= {} [:field {} 1] 6] "Friday"]
+ [[:= {} [:field {} 1] 7] "Saturday"]]]
+ (#'lib.filter.desugar/desugar-expression [:day-name (opts) [:field (opts) 1]])))))
+#?(:clj
+ (deftest ^:synchronized desugar-month-quarter-day-name-i18n-test
+ (metabase.test.util.i18n/with-user-locale "es"
+ ;; JVM versions 17 and older for some languages (including Spanish) use eg. "oct.", while in JVMs 18+ they
+ ;; use "oct". I wish I were joking, but I'm not. These tests were passing on 21 and failing on 17 and 11
+ ;; before I made them flexible about the dot.
+ (testing "`month-name` should desugar to a `:case` clause with values for each month"
+ (is (=? [:case {:default ""}
+ [[[:= {} [:field {} 1] 1] #(#{"ene" "ene."} %)]
+ [[:= {} [:field {} 1] 2] #(#{"feb" "feb."} %)]
+ [[:= {} [:field {} 1] 3] #(#{"mar" "mar."} %)]
+ [[:= {} [:field {} 1] 4] #(#{"abr" "abr."} %)]
+ [[:= {} [:field {} 1] 5] #(#{"may" "may."} %)]
+ [[:= {} [:field {} 1] 6] #(#{"jun" "jun."} %)]
+ [[:= {} [:field {} 1] 7] #(#{"jul" "jul."} %)]
+ [[:= {} [:field {} 1] 8] #(#{"ago" "ago."} %)]
+ [[:= {} [:field {} 1] 9] #(#{"sept" "sept."} %)]
+ [[:= {} [:field {} 1] 10] #(#{"oct" "oct."} %)]
+ [[:= {} [:field {} 1] 11] #(#{"nov" "nov."} %)]
+ [[:= {} [:field {} 1] 12] #(#{"dic" "dic."} %)]]]
+ (#'lib.filter.desugar/desugar-expression [:month-name (opts) [:field (opts) 1]])))))))
+
+#?(:clj
+ (deftest ^:synchronized desugar-month-quarter-day-name-i18n-test-2
+ (metabase.test.util.i18n/with-user-locale "es"
+ (testing "`quarter-name` should desugar to a `:case` clause with values for each quarter"
+ (is (=? [:case {:default ""}
+ [[[:= {} [:field {} 1] 1] "Q1"]
+ [[:= {} [:field {} 1] 2] "Q2"]
+ [[:= {} [:field {} 1] 3] "Q3"]
+ [[:= {} [:field {} 1] 4] "Q4"]]]
+ (#'lib.filter.desugar/desugar-expression [:quarter-name (opts) [:field (opts) 1]])))))))
+
+#?(:clj
+ (deftest ^:synchronized desugar-month-quarter-day-name-i18n-test-3
+ (metabase.test.util.i18n/with-user-locale "es"
+ (testing "`day-name` should desugar to a `:case` clause with values for each weekday"
+ (is (=? [:case {:default ""}
+ [[[:= {} [:field {} 1] 1] "domingo"]
+ [[:= {} [:field {} 1] 2] "lunes"]
+ [[:= {} [:field {} 1] 3] "martes"]
+ [[:= {} [:field {} 1] 4] "miércoles"]
+ [[:= {} [:field {} 1] 5] "jueves"]
+ [[:= {} [:field {} 1] 6] "viernes"]
+ [[:= {} [:field {} 1] 7] "sábado"]]]
+ (#'lib.filter.desugar/desugar-expression [:day-name (opts) [:field (opts) 1]])))))))
diff --git a/test/metabase/lib/filter/simplify_compound_test.cljc b/test/metabase/lib/filter/simplify_compound_test.cljc
new file mode 100644
index 00000000000..d5a65ed4b1f
--- /dev/null
+++ b/test/metabase/lib/filter/simplify_compound_test.cljc
@@ -0,0 +1,164 @@
+(ns metabase.lib.filter.simplify-compound-test
+ (:require
+ #?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
+ [clojure.test :refer [are deftest is testing]]
+ [metabase.lib.filter.simplify-compound :as lib.filter.simplify-compound]))
+
+#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))
+
+(defn- simplify-compound-filter [x]
+ (lib.filter.simplify-compound/simplify-compound-filter x))
+
+(defn- opts [& {:as kvs}]
+ (merge {:lib/uuid (str (random-uuid))} kvs))
+
+(deftest ^:parallel simplify-compound-filter-test
+ (testing "can `simplify-compound-filter` fix `and` or `or` with only one arg?"
+ (is (=? [:= {} [:field {} 1] 2]
+ (simplify-compound-filter [:and (opts) [:= (opts) [:field (opts) 1] 2]])))))
+
+(deftest ^:parallel simplify-compound-filter-test-2
+ (testing "can `simplify-compound-filter` unnest nested `and`s or `or`s?"
+ (is (=? [:and {}
+ [:= {} [:field {} 1] 2]
+ [:= {} [:field {} 3] 4]
+ [:= {} [:field {} 5] 6]]
+ (simplify-compound-filter
+ [:and (opts)
+ [:= (opts) [:field (opts) 1] 2]
+ [:and (opts)
+ [:= (opts) [:field (opts) 3] 4]
+ [:and (opts)
+ [:= (opts) [:field (opts) 5] 6]]]])))))
+
+(deftest ^:parallel simplify-compound-filter-test-3
+ (testing "can `simplify-compound-filter` remove duplicates?"
+ (is (=? [:and {}
+ [:= {}
+ [:field {} 1]
+ 2]
+ [:= {}
+ [:field {} 3]
+ 4]]
+ (simplify-compound-filter
+ [:and (opts)
+ [:= (opts)
+ [:field (opts) 1]
+ 2]
+ [:= (opts)
+ [:field (opts) 3]
+ 4]
+ [:= (opts)
+ [:field (opts) 1]
+ 2]])))))
+
+(deftest ^:parallel simplify-compound-filter-test-4
+ (testing "can `simplify-compound-filter` eliminate `not` inside a `not`?"
+ (is (=? [:= {} [:field {} 1] 2]
+ (simplify-compound-filter [:not (opts) [:not (opts) [:= (opts) [:field (opts) 1] 2]]])))))
+
+(deftest ^:parallel simplify-compound-filter-test-5a
+ (testing "removing empty/nil filter clauses"
+ (testing "does `simplify-compound-filter` return `nil` for empty filter clauses?"
+ (is (=? nil
+ (simplify-compound-filter nil))))))
+
+(deftest ^:parallel simplify-compound-filter-test-5b
+ (testing "removing empty/nil filter clauses"
+ (are [x] (nil? (simplify-compound-filter x))
+ [:and (opts) nil nil]
+ [:and (opts) nil [:and (opts) nil nil nil] nil])))
+
+(deftest ^:parallel simplify-compound-filter-test-5c
+ (testing "removing empty/nil filter clauses"
+ (is (=? [:= {} [:field {} 1] 2]
+ (simplify-compound-filter [:and (opts) nil [:and (opts) nil [:= (opts) [:field (opts) 1] 2] nil] nil])))))
+
+(deftest ^:parallel simplify-compound-filter-test-5d
+ (testing "removing empty/nil filter clauses"
+ (is (=? [:and {}
+ [:= {} [:field {} 1] 2]
+ [:= {} [:field {} 3] 4]
+ [:= {} [:field {} 5] 6]
+ [:= {} [:field {} 7] 8]
+ [:= {} [:field {} 9] 10]]
+ (simplify-compound-filter
+ [:and (opts)
+ nil
+ [:= (opts) [:field (opts) 1] 2]
+ [:and (opts)
+ [:= (opts) [:field (opts) 3] 4]]
+ nil
+ [:and (opts)
+ [:and (opts)
+ [:and (opts)
+ [:= (opts) [:field (opts) 5] 6]
+ nil
+ nil]
+ [:= (opts) [:field (opts) 7] 8]
+ [:= (opts) [:field (opts) 9] 10]]]])))))
+
+(deftest ^:parallel simplify-compound-filter-test-6
+ (testing "`simplify-compound-filter` should also work with more complex structures"
+ (is (=? {:aggregation [[:share {}
+ [:and {}
+ [:= {} [:field {} 1] 2]
+ [:= {} [:field {} 3] 4]
+ [:= {} [:field {} 5] 6]
+ [:= {} [:field {} 7] 8]
+ [:= {} [:field {} 9] 10]]]]}
+ (simplify-compound-filter
+ {:aggregation [[:share (opts)
+ [:and (opts)
+ nil
+ [:= (opts) [:field (opts) 1] 2]
+ [:and (opts)
+ [:= (opts) [:field (opts) 3] 4]]
+ nil
+ [:and (opts)
+ [:and (opts)
+ [:and (opts)
+ [:= (opts) [:field (opts) 5] 6]
+ nil
+ nil]
+ [:= (opts) [:field (opts) 7] 8]
+ [:= (opts) [:field (opts) 9] 10]]]]]]})))))
+
+(deftest ^:parallel simplify-compound-filter-test-7a
+ (testing "Check that `simplify-compound-filter` can apply de Morgan's law on `:not`"
+ (testing ":and clauses"
+ (is (=? [:or {}
+ [:not {} [:= {} [:field {} 1] 2]]
+ [:not {} [:= {} [:field {} 2] 3]]]
+ (simplify-compound-filter
+ [:not (opts)
+ [:and (opts)
+ [:= (opts) [:field (opts) 1] 2]
+ [:= (opts) [:field (opts) 2] 3]]]))))))
+
+(deftest ^:parallel simplify-compound-filter-test-7b
+ (testing "Check that `simplify-compound-filter` can apply de Morgan's law on `:not`"
+ (testing ":or clauses"
+ (testing "Check that `simplify-compound-filter` can apply de Morgan's law on `:not` over `:or`"
+ (is (=? [:and {}
+ [:not {} [:= {} [:field {} 1] 2]]
+ [:not {} [:= {} [:field {} 2] 3]]]
+ (simplify-compound-filter
+ [:not (opts)
+ [:or (opts)
+ [:= (opts) [:field (opts) 1] 2]
+ [:= (opts) [:field (opts) 2] 3]]])))))))
+
+(deftest ^:parallel simplify-compound-filter-test-8a
+ (testing "check that `simplify-compound-filter` doesn't remove `nil` from filters where it's being used as the value"
+ (is (=? [:= {}
+ [:field {} 1]
+ nil]
+ (simplify-compound-filter [:= (opts) [:field (opts) 1] nil])))))
+
+(deftest ^:parallel simplify-compound-filter-test-8b
+ (testing "check that `simplify-compound-filter` doesn't remove `nil` from filters where it's being used as the value"
+ (is (=? [:= {}
+ [:field {} 1]
+ nil]
+ (simplify-compound-filter [:and (opts) nil [:= (opts) [:field (opts) 1] nil]])))))
diff --git a/test/metabase/query_processor/middleware/desugar_test.clj b/test/metabase/query_processor/middleware/desugar_test.clj
index 6c1a13d10ca..9b44f56bdfc 100644
--- a/test/metabase/query_processor/middleware/desugar_test.clj
+++ b/test/metabase/query_processor/middleware/desugar_test.clj
@@ -1,53 +1,123 @@
(ns metabase.query-processor.middleware.desugar-test
+ "Sctual desugaring logic and tests are in [[metabase.lib.filter.desugar]]."
(:require
[clojure.test :refer :all]
+ [metabase.lib.core :as lib]
[metabase.lib.test-metadata :as meta]
- [metabase.lib.test-util.macros :as lib.tu.macros]
- [metabase.query-processor.middleware.desugar :as desugar]
- [metabase.test :as mt]))
+ [metabase.query-processor.middleware.desugar :as desugar]))
-;; actual desugaring logic and tests are in [[metabase.legacy-mbql.util-test]]
-(deftest ^:parallel e2e-test
- (is (=? (lib.tu.macros/mbql-query orders
- {:filter [:and
- [:= $user-id->people.name "Run Query"]
- [:between
- !day.created-at
- [:relative-datetime -30 :day]
- [:relative-datetime -1 :day]]
- [:>=
- !default.created-at
- [:+ [:relative-datetime -30 :day] [:interval -30 :day]]]
- [:<
- !default.created-at
- [:+ [:relative-datetime 0 :day] [:interval -30 :day]]]
- [:!= $user-id->people.source "(not set)"]
- [:!= $user-id->people.source "Twitter"]
- [:> [:temporal-extract $user-id->people.birth-date :year-of-era] [:/ [:/ 1 2] 3]]]
- :expressions {"year" [:+
- [:temporal-extract $user-id->people.birth-date :year-of-era]
- [:/ [:/ [:/ 1 2] 3] 4]]}
- :aggregation [[:share [:and
- [:= $user-id->people.name "Run Query"]
- [:between
- !day.created-at
- [:relative-datetime -30 :day]
- [:relative-datetime -1 :day]]
- [:!= $user-id->people.source "(not set)"]
- [:!= $user-id->people.source "Twitter"]]]]})
- (mt/with-metadata-provider meta/metadata-provider
- (desugar/desugar
- (lib.tu.macros/mbql-query orders
- {:filter [:and
- [:= $user-id->people.name "Run Query"]
- [:time-interval !day.created-at -30 :day]
- [:relative-time-interval $created-at -30 :day -30 :day]
- [:!= $user-id->people.source "(not set)" "Twitter"]
- [:> [:get-year $user-id->people.birth-date] [:/ 1 2 3]]]
- :expressions {"year" [:+
- [:get-year $user-id->people.birth-date]
- [:/ 1 2 3 4]]}
- :aggregation [[:share [:and
- [:= $user-id->people.name "Run Query"]
- [:time-interval $created-at -30 :day]
- [:!= $user-id->people.source "(not set)" "Twitter"]]]]}))))))
+(defn- opts [& {:as kvs}]
+ (merge {:lib/uuid (str (random-uuid))} kvs))
+
+(deftest ^:parallel e2e-filters-test
+ (is (=? [[:and {}
+ [:= {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :name)]
+ "Run Query"]
+ [:between {}
+ [:field {:temporal-unit :day} (meta/id :orders :created-at)]
+ [:relative-datetime {} -30 :day]
+ [:relative-datetime {} -1 :day]]
+ [:>= {}
+ [:field {:temporal-unit :default} (meta/id :orders :created-at)]
+ [:+ {} [:relative-datetime {} -30 :day] [:interval {} -30 :day]]]
+ [:< {}
+ [:field {:temporal-unit :default} (meta/id :orders :created-at)]
+ [:+ {}
+ [:relative-datetime {} 0 :day]
+ [:interval {} -30 :day]]]
+ [:!= {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :source)]
+ "(not set)"]
+ [:!= {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :source)]
+ "Twitter"]
+ [:> {}
+ [:temporal-extract {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :birth-date)]
+ :year-of-era]
+ [:/ {} [:/ {} 1 2] 3]]]]
+ (-> (lib/query
+ meta/metadata-provider
+ {:lib/type :mbql/query
+ :stages [{:source-table (meta/id :orders)
+ :filters [[:and (opts)
+ [:= (opts)
+ [:field (opts :source-field (meta/id :orders :user-id)) (meta/id :people :name)]
+ "Run Query"]
+ [:time-interval (opts)
+ [:field (opts :temporal-unit :day) (meta/id :orders :created-at)]
+ -30 :day]
+ [:relative-time-interval (opts)
+ [:field (opts) (meta/id :orders :created-at)]
+ -30 :day
+ -30 :day]
+ [:!=
+ [:field (opts :source-field (meta/id :orders :user-id)) (meta/id :people :source)]
+ "(not set)"
+ "Twitter"]
+ [:>
+ [:get-year [:field (opts :source-field (meta/id :orders :user-id)) (meta/id :people :birth-date)]]
+ [:/ 1 2 3]]]]}]})
+ desugar/desugar
+ :stages
+ first
+ :filters))))
+
+(deftest ^:parallel e2e-expressions-test
+ (is (=? [[:+
+ {:lib/expression-name "year"}
+ [:temporal-extract {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :birth-date)]
+ :year-of-era]
+ [:/ {} [:/ {} [:/ {} 1 2] 3] 4]]]
+ (-> (lib/query
+ meta/metadata-provider
+ {:lib/type :mbql/query
+ :stages [{:source-table (meta/id :orders)
+ :expressions [[:+ (opts :lib/expression-name "year")
+ [:get-year (opts)
+ [:field (opts :source-field (meta/id :orders :user-id)) (meta/id :people :birth-date)]]
+ [:/ (opts) 1 2 3 4]]]}]})
+ desugar/desugar
+ :stages
+ first
+ :expressions))))
+
+(deftest ^:parallel e2e-aggregations-test
+ (is (=? [[:share {}
+ [:and {}
+ [:= {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :name)]
+ "Run Query"]
+ [:between {}
+ [:field {:temporal-unit :day} (meta/id :orders :created-at)]
+ [:relative-datetime {} -30 :day]
+ [:relative-datetime {} -1 :day]]
+ [:!= {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :source)]
+ "(not set)"]
+ [:!= {}
+ [:field {:source-field (meta/id :orders :user-id)} (meta/id :people :source)]
+ "Twitter"]]]]
+ (-> (lib/query
+ meta/metadata-provider
+ {:lib/type :mbql/query
+ :stages [{:source-table (meta/id :orders)
+ :aggregation [[:share (opts)
+ [:and (opts)
+ [:= (opts)
+ [:field (opts :source-field (meta/id :orders :user-id)) (meta/id :people :name)]
+ "Run Query"]
+ [:time-interval (opts)
+ [:field (opts) (meta/id :orders :created-at)]
+ -30
+ :day]
+ [:!= (opts)
+ [:field (opts :source-field (meta/id :orders :user-id)) (meta/id :people :source)]
+ "(not set)"
+ "Twitter"]]]]}]})
+ desugar/desugar
+ :stages
+ first
+ :aggregation))))
diff --git a/test/metabase/query_processor/util/nest_query_test.clj b/test/metabase/query_processor/util/nest_query_test.clj
index eb8a66a7e43..92f9e24d684 100644
--- a/test/metabase/query_processor/util/nest_query_test.clj
+++ b/test/metabase/query_processor/util/nest_query_test.clj
@@ -600,7 +600,13 @@
:fk-field-id %product-id
:condition [:= $product-id &PRODUCTS__via__PRODUCT_ID.products.id]}]})
add/add-alias-info
- nest-expressions))))))))
+ nest-expressions
+ ;; I'm tired of dealing with the nondeterministic order mentioned above, so just sort them by ID
+ ;; and call it a day for now.
+ (update-in [:source-query :fields] (fn [fields]
+ (concat
+ (take 3 fields)
+ (sort-by second (drop 3 fields)))))))))))))
(deftest ^:parallel uniquify-aliases-test
(driver/with-driver :h2
@@ -812,17 +818,23 @@
:join-alias "p"
::add/desired-alias "p__CREATED_AT"
::add/source-table "p"}]]}}
- (->> (lib.tu.macros/mbql-query orders
- {:expressions {"double_total" [:* $total 2]}
- ;; this is a broken field ref! It should use the join alias `p`. Luckily
- ;; the [[metabase.query-processor.middleware.resolve-joined-fields]] middleware should fix it
- ;; for us.
- :breakout [!hour-of-day.people.created-at
- [:expression "double_total"]]
- :aggregation [[:count]]
- :joins [{:source-table $$people
- :alias "p"
- :condition [:= $user-id &p.people.id]}]})
- qp.preprocess/preprocess
- add/add-alias-info
- nest-expressions)))))))
+ (-> (lib.tu.macros/mbql-query orders
+ {:expressions {"double_total" [:* $total 2]}
+ ;; this is a broken field ref! It should use the join alias `p`. Luckily
+ ;; the [[metabase.query-processor.middleware.resolve-joined-fields]] middleware should fix it
+ ;; for us.
+ :breakout [!hour-of-day.people.created-at
+ [:expression "double_total"]]
+ :aggregation [[:count]]
+ :joins [{:source-table $$people
+ :alias "p"
+ :condition [:= $user-id &p.people.id]}]})
+ qp.preprocess/preprocess
+ add/add-alias-info
+ nest-expressions
+ ;; I'm tired of dealing with the nondeterministic order mentioned above, so just sort them by ID and
+ ;; call it a day for now.
+ (update-in [:source-query :fields] (fn [fields]
+ (concat
+ (take 3 fields)
+ (sort-by second (drop 3 fields))))))))))))
diff --git a/test/metabase/query_processor/util/relative_datetime_test.clj b/test/metabase/query_processor/util/relative_datetime_test.clj
index 3700d5ab3dd..238dd52f347 100644
--- a/test/metabase/query_processor/util/relative_datetime_test.clj
+++ b/test/metabase/query_processor/util/relative_datetime_test.clj
@@ -102,7 +102,7 @@
:order-by [[:asc $last_login]]})
(mt/formatted-rows [int str str]))))))))))
-(deftest text-to-date-coercion-relative-time-filter-test
+(deftest ^:parallel text-to-date-coercion-relative-time-filter-test
(testing "text fields that have been casted to dates can be filtered by relative time"
(mt/with-clock #t "2025-01-30T12:00:00-00:00[UTC]"
(mt/test-drivers (mt/normal-drivers-with-feature ::server-side-relative-datetime)
diff --git a/test/metabase/query_processor_test/case_test.clj b/test/metabase/query_processor_test/case_test.clj
index 6a8daa17d67..8d62769fdcd 100644
--- a/test/metabase/query_processor_test/case_test.clj
+++ b/test/metabase/query_processor_test/case_test.clj
@@ -1,6 +1,7 @@
(ns ^:mb/driver-tests metabase.query-processor-test.case-test
(:require
[clojure.test :refer :all]
+ [metabase.query-processor :as qp]
[metabase.test :as mt]))
(defn- test-case
@@ -123,3 +124,20 @@
[:case [[[:> $rating 4] 1]] {:default 0}]]}
:limit 2
:order-by [[:asc $id]]})))))))
+
+(deftest ^:parallel if-test
+ (testing "If should work as syntactic sugar for case"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions)
+ (let [query (mt/mbql-query products
+ {:expressions {"If"
+ [:if [[[:= $id 1] "First"]
+ [[:= $id 2] "Second"]]
+ {:default "Other"}]}
+ :fields [$id
+ [:expression "If"]]
+ :filter [:= [:expression "If" {:base-type :type/Text}] "Other"]
+ :order-by [[:asc $id]]
+ :limit 2})]
+ (is (= [[3 "Other"]
+ [4 "Other"]]
+ (mt/formatted-rows [int str] (qp/process-query query))))))))
diff --git a/test/metabase/query_processor_test/filter_test.clj b/test/metabase/query_processor_test/filter_test.clj
index 37cfc15a730..f55c11e2663 100644
--- a/test/metabase/query_processor_test/filter_test.clj
+++ b/test/metabase/query_processor_test/filter_test.clj
@@ -7,6 +7,7 @@
[metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.options :as lib.options]
[metabase.lib.test-util :as lib.tu]
[metabase.query-processor :as qp]
[metabase.query-processor-test.timezones-test :as timezones-test]
@@ -1070,3 +1071,59 @@
(is (= [[3 1 105 52.72 2.9 49.2 6.42 "2019-12-06T22:22:48.544Z" 2 3 "2014-09-15T00:00:00Z" 8 56]
[6 1 60 29.8 1.64 31.44 nil "2019-11-06T16:38:50.134Z" 3 6 "2015-07-04T00:00:00Z" 3 35]]
(mt/rows (qp/process-query query)))))))
+
+(deftest ^:parallel starts-with-multiple-args-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :case-sensitivity-string-filter-options)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :categories)))
+ (lib/filter (-> (lib/starts-with
+ (lib.metadata/field mp (mt/id :categories :name))
+ "b"
+ "c")
+ (lib.options/update-options assoc :case-sensitive false)))
+ (lib/order-by (lib.metadata/field mp (mt/id :categories :id)))
+ (lib/limit 2))]
+ (is (= [[5 "BBQ"] [6 "Bakery"]]
+ (mt/formatted-rows [int str] (qp/process-query query)))))))
+
+(deftest ^:parallel ends-with-multiple-args-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :case-sensitivity-string-filter-options)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :categories)))
+ (lib/filter (-> (lib/ends-with
+ (lib.metadata/field mp (mt/id :categories :name))
+ "B"
+ "C")
+ (lib.options/update-options assoc :case-sensitive false)))
+ (lib/order-by (lib.metadata/field mp (mt/id :categories :id)))
+ (lib/limit 2))]
+ (is (= [[17 "Comedy Club"] [55 "Nightclub"]]
+ (mt/formatted-rows [int str] (qp/process-query query)))))))
+
+(deftest ^:parallel contains-multiple-args-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :case-sensitivity-string-filter-options)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :categories)))
+ (lib/filter (-> (lib/contains
+ (lib.metadata/field mp (mt/id :categories :name))
+ "B"
+ "E")
+ (lib.options/update-options assoc :case-sensitive false)))
+ (lib/order-by (lib.metadata/field mp (mt/id :categories :id)))
+ (lib/limit 2))]
+ (is (= [[2 "American"] [5 "BBQ"]]
+ (mt/formatted-rows [int str] (qp/process-query query)))))))
+
+(deftest ^:parallel does-not-contain-multiple-args-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :case-sensitivity-string-filter-options)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :categories)))
+ (lib/filter (-> (lib/does-not-contain
+ (lib.metadata/field mp (mt/id :categories :name))
+ "B"
+ "C")
+ (lib.options/update-options assoc :case-sensitive false)))
+ (lib/order-by (lib.metadata/field mp (mt/id :categories :id)))
+ (lib/limit 2))]
+ (is (= [[3 "Artisan"] [4 "Asian"]]
+ (mt/formatted-rows [int str] (qp/process-query query)))))))