Skip to content

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

Add `mbql-5-query` macro (#61898)

Cam Saulf6d3a73bb3d4
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 33afa616571..b98ffb07188 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -543,6 +543,7 @@
metabase.lib.schema.mbql-clause/define-tuple-mbql-clause hooks.metabase.lib.schema.mbql-clause/define-mbql-clause
metabase.lib.test-util.macros/$ids hooks.metabase.test.data/$ids
metabase.lib.test-util.macros/mbql-query hooks.metabase.test.data/mbql-query
+ metabase.lib.test-util.macros/mbql-5-query hooks.metabase.test.data/mbql-query
metabase.lib.test-util.macros/with-testing-against-standard-queries hooks.metabase.lib.test-util.macros/with-testing-against-standard-queries
metabase.model-persistence.api-test/with-persistence-setup! hooks.common/with-one-top-level-binding
metabase.model-persistence.api-test/with-setup! hooks.common/with-one-top-level-binding
diff --git a/.cljfmt.edn b/.cljfmt.edn
index 83bcaefeb6a..c3c53fa34cd 100644
--- a/.cljfmt.edn
+++ b/.cljfmt.edn
@@ -152,6 +152,7 @@
metabase.lib.join/with-join-alias [[:default]]
metabase.lib.join/with-join-conditions [[:default]]
metabase.lib.test-util.macros/$ids [[:inner 0]]
+ metabase.lib.test-util.macros/mbql-5-query [[:inner 0]]
metabase.lib.test-util.macros/mbql-query [[:inner 0]]
metabase.lib.util.match/match [[:inner 0]]
metabase.lib.util.match/match-one [[:inner 0]]
diff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljc
index 931943633ea..0ba1141e7ef 100644
--- a/src/metabase/lib/schema.cljc
+++ b/src/metabase/lib/schema.cljc
@@ -224,16 +224,35 @@
(when (map? x)
(keyword (some #(get x %) [:lib/type "lib/type"]))))
+(defn- normalize-stage [stage]
+ (when (map? stage)
+ (let [stage (common/normalize-map stage)]
+ ;; infer stage type
+ (cond
+ (:lib/type stage)
+ stage
+
+ ((some-fn :source-table :source-card) stage)
+ (assoc stage :lib/type :mbql.stage/mbql)
+
+ (:native stage)
+ (assoc stage :lib/type :mbql.stage/native)
+
+ :else
+ stage))))
+
;;; TODO -- enforce all kebab-case keys
(mr/def ::stage
[:and
- {:default {}
- :decode/normalize common/normalize-map
+ {:default {:lib/type :mbql.stage/mbql}
+ :decode/normalize normalize-stage
:encode/serialize #(dissoc %
;; this stuff is all added at runtime by QP middleware.
:params
:parameters
:lib/stage-metadata
+ ;; wait a minute, `:middleware` is not supposed to be added here, it's supposed to be
+ ;; added to the top level.
:middleware)}
[:map
[:lib/type [:ref ::stage.type]]]
@@ -316,9 +335,26 @@
(ref-error-for-stages stages))}
(complement ref-error-for-stages)])
+(defn- normalize-stages [stages]
+ (when (sequential? stages)
+ (if (every? :lib/type stages)
+ stages
+ (into [(first stages)]
+ (comp
+ ;; make sure stage has keywordized keys so we can check `:lib/type`
+ (map normalize-stage)
+ ;; subsequent stages have to be MBQL, so add `:lib/type` if it is missing.
+ (map (fn [subsequent-stage]
+ (cond-> subsequent-stage
+ (not (:lib/type subsequent-stage)) (assoc :lib/type :mbql.stage/mbql)))))
+ (rest stages)))))
+
(mr/def ::stages
[:and
- [:sequential {:min 1} [:ref ::stage]]
+ [:sequential {:min 1
+ :decode/normalize normalize-stages
+ :default []}
+ [:ref ::stage]]
[:cat
[:schema [:ref ::stage.initial]]
[:* [:schema [:ref ::stage.additional]]]]
@@ -397,4 +433,5 @@
[:ref ::lib.schema.util/unique-uuids]
[:fn
{:error/message ":expressions is not allowed in the top level of a query -- it is only allowed in MBQL stages"}
- #(not (contains? % :expressions))]])
+ #(not (when (map? %)
+ (contains? % :expressions)))]])
diff --git a/src/metabase/lib/schema/join.cljc b/src/metabase/lib/schema/join.cljc
index a7d23569287..377f0708b83 100644
--- a/src/metabase/lib/schema/join.cljc
+++ b/src/metabase/lib/schema/join.cljc
@@ -80,7 +80,14 @@
(seq (:source-metadata join))
(-> (assoc-in [:stages (dec (count (:stages join))) :lib/stage-metadata] {:lib/type :metadata/results
:columns (:source-metadata join)})
- (dissoc :source-metadata))))))
+ (dissoc :source-metadata))
+
+ ;; automatically fix :condition => :conditions if we run into it. Kinda overlapping responsibility
+ ;; with [[metabase.lib.convert]] but this lets us write busted stuff in tests more easily
+ ;; using [[metabase.lib.test-util.macros/mbql-5-query]]
+ (:condition join)
+ (-> (dissoc :condition)
+ (assoc :conditions [(:condition join)]))))))
(mr/def ::join
[:and
@@ -97,7 +104,13 @@
[:strategy {:optional true} ::strategy]]
[:fn
{:error/message "join should not have metadata attached directly to them; attach metadata to their last stage instead"}
- (complement (some-fn :lib/stage-metadata :source-metadata))]])
+ (complement (some-fn :lib/stage-metadata :source-metadata))]
+ [:fn
+ {:error/message ":condition is not allowed for MBQL 5 joins, use :conditions instead"}
+ (complement :condition)]
+ [:fn
+ {:error/message "join should not have :source-table or :source-query; use :stages instead"}
+ (complement (some-fn :source-table :source-query))]])
(mr/def ::joins
[:and
diff --git a/test/metabase/lib/test_util/macros.clj b/test/metabase/lib/test_util/macros.clj
index f7b774b9542..0fe33243cc4 100644
--- a/test/metabase/lib/test_util/macros.clj
+++ b/test/metabase/lib/test_util/macros.clj
@@ -2,7 +2,9 @@
(:require
[clojure.test :refer [testing]]
[metabase.lib.test-util.macros.impl :as lib.tu.macros.impl]
- [metabase.test.data.mbql-query-impl :as mbql-query-impl]))
+ [metabase.test.data.mbql-query-impl :as mbql-query-impl]
+ [metabase.util :as u]
+ [metabase.util.malli :as mu]))
(defn- do-with-bindings [thunk]
(binding [mbql-query-impl/*id-fn-symb* 'metabase.lib.test-metadata/id
@@ -37,6 +39,48 @@
(mbql-query-impl/maybe-add-source-table <> table-name)
(mbql-query-impl/wrap-inner-query <>)))))
+(mu/defn- maybe-add-source-table-mbql-5 :- :map
+ [query :- :map
+ table-name]
+ (cond
+ ;; `table-name` is not specified: return query as is
+ (not table-name)
+ query
+
+ ;; already has source table/card in the first stage: return query as is
+ ((some-fn :source-table :source-card) (get-in query [:stages 0]))
+ query
+
+ ;; query is missing `:stages`: add empty vector and recur
+ (not (:stages query))
+ (recur (assoc query :stages [])
+ table-name)
+
+ ;; query is missing first stage: add empty first stage and recur
+ (not (first (:stages query)))
+ (recur (update query :stages #(conj (vec %) {:lib/type :mbql.stage/mbql}))
+ table-name)
+
+ ;; otherwise we're good to go. Add `(meta/id ...)` form for `:source-table` to the first stage
+ :else
+ (assoc-in query [:stages 0 :source-table] (list 'metabase.lib.test-metadata/id (keyword table-name)))))
+
+(defmacro mbql-5-query
+ "Like [[mbql-query]] but for use with MBQL 5 queries. Currently experimental, and maybe need bugfixes!"
+ {:style/indent :defn}
+ ([table-name]
+ `(mbql-5-query ~table-name {}))
+
+ ([table-name query]
+ {:pre [(map? query)]}
+ (do-with-bindings
+ (fn []
+ (binding [mbql-query-impl/*mbql-version* 5]
+ (as-> query <>
+ (mbql-query-impl/parse-tokens table-name <>)
+ (u/assoc-default <> :lib/type :mbql/query, :database '(metabase.lib.test-metadata/id))
+ (maybe-add-source-table-mbql-5 <> table-name)))))))
+
(defmacro with-testing-against-standard-queries
"Tests against a number of named expressions that all produce the same columns through different methods."
[sym & body]
diff --git a/test/metabase/test/data/mbql_query_impl.cljc b/test/metabase/test/data/mbql_query_impl.cljc
index cab1facb2a7..ffbf318623a 100644
--- a/test/metabase/test/data/mbql_query_impl.cljc
+++ b/test/metabase/test/data/mbql_query_impl.cljc
@@ -1,9 +1,12 @@
(ns metabase.test.data.mbql-query-impl
"Internal implementation of [[metabase.test.data/$ids]] and [[metabase.test.data/$ids]] and related macros."
(:require
- #?@(:clj ([toucan2.core :as t2]))
+ #?@(:clj ([metabase.query-processor.store :as qp.store]
+ [metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
+ [metabase.lib.metadata :as lib.metadata]))
[clojure.string :as str]
- [clojure.walk :as walk]))
+ [clojure.walk :as walk]
+ [metabase.util.malli :as mu]))
#?(:clj (set! *warn-on-reflection* true))
@@ -22,6 +25,7 @@
(def ^:dynamic *id-fn-symb* `druid-id-fn #_'metabase.test.data/id)
(def ^:dynamic *field-name-fn-symb* `field-name)
(def ^:dynamic *field-base-type-fn-symb* `field-base-type)
+(def ^:dynamic ^Long *mbql-version* 4)
(defn- token->sigil [token]
(when-let [[_ sigil] (re-matches #"^([$%*!&]{1,2}).*[\w/]$" (str token))]
@@ -59,9 +63,32 @@
{:arglists '([strategy token-type source-table-symb & tokens])}
(fn [strategy token-type & _] [strategy token-type]))
+(mu/defn- field-ref
+ [id-or-name ; can be integer, string, or a s-expression evaluating to one of these.
+ options :- [:maybe :map]] ; options should already be a map.
+ (case (long *mbql-version*)
+ 4 [:field id-or-name (not-empty options)]
+ 5 [:field (or options {}) id-or-name]))
+
+(mu/defn- field-ref->opts :- [:maybe :map]
+ [[_tag x y] :- vector?]
+ (case (long *mbql-version*)
+ 4 y
+ 5 x))
+
+(mu/defn- field-ref->id-or-name
+ [[_tag x y] :- vector?]
+ (case (long *mbql-version*)
+ 4 x
+ 5 y))
+
+(mu/defn- field-ref-update-options [a-ref f & args]
+ (field-ref (field-ref->id-or-name a-ref)
+ (apply f (field-ref->opts a-ref) args)))
+
(defmethod mbql-field [:id :normal]
[_ _ source-table-symb token-str]
- [:field (field-id-call source-table-symb token-str) nil])
+ (field-ref (field-id-call source-table-symb token-str) nil))
(defmethod mbql-field [:id :->]
[_ _ source-table-symb source-token-str dest-token-str]
@@ -69,7 +96,7 @@
(let [[_ id-form options] (parse-token-by-sigil source-table-symb (symbol (if (token->sigil dest-token-str)
dest-token-str
(str \$ dest-token-str))))]
- [:field id-form (assoc options :source-field (field-id-call source-table-symb source-token-str))]))
+ (field-ref id-form (assoc options :source-field (field-id-call source-table-symb source-token-str)))))
(defmethod mbql-field [:raw :normal]
[_ _ source-table-symb token-str]
@@ -82,21 +109,27 @@
:source-token-str source-token-str
:dest-token-str dest-token-str})))
+#?(:clj
+ (defn- metadata-provider []
+ (if (qp.store/initialized?)
+ (qp.store/metadata-provider)
+ (lib.metadata.jvm/application-database-metadata-provider ((requiring-resolve 'metabase.test.data/id))))))
+
#?(:clj
(defn field-name [field-id]
- (t2/select-one-fn :name :model/Field :id field-id)))
+ (:name (lib.metadata/field (metadata-provider) field-id))))
#?(:clj
(defn field-base-type [field-id]
- (t2/select-one-fn :base_type :model/Field :id field-id)))
+ (:base-type (lib.metadata/field (metadata-provider) field-id))))
(defn- field-literal [source-table-symb token-str]
(if (str/includes? token-str "/")
(let [[field-name field-type] (str/split token-str #"/")]
- [:field field-name {:base-type (keyword "type" field-type)}])
- [:field
+ (field-ref field-name {:base-type (keyword "type" field-type)}))
+ (field-ref
(list *field-name-fn-symb* (field-id-call source-table-symb token-str))
- {:base-type (list *field-base-type-fn-symb* (field-id-call source-table-symb token-str))}]))
+ {:base-type (list *field-base-type-fn-symb* (field-id-call source-table-symb token-str))})))
(defmethod mbql-field [:literal :normal]
[_ _ source-table-symb token-str]
@@ -133,10 +166,10 @@
(defmethod parse-token-by-sigil "&"
[source-table-symb token]
(if-let [[_ alias-name token] (re-matches #"^&([^.]+)\.(.+$)" (str token))]
- (let [[_ id-or-name opts] (parse-token-by-sigil source-table-symb (if (token->sigil token)
- (symbol token)
- (symbol (str \$ token))))]
- [:field id-or-name (assoc opts :join-alias alias-name)])
+ (-> (parse-token-by-sigil source-table-symb (if (token->sigil token)
+ (symbol token)
+ (symbol (str \$ token))))
+ (field-ref-update-options assoc :join-alias alias-name))
(throw (ex-info "Error parsing token starting with '&'"
{:token token}))))
@@ -147,7 +180,7 @@
(let [[_ id-or-name opts] (parse-token-by-sigil source-table-symb (if (token->sigil token)
(symbol token)
(symbol (str \$ token))))]
- [:field id-or-name (assoc opts :temporal-unit (keyword unit))])
+ (field-ref id-or-name (assoc opts :temporal-unit (keyword unit))))
(throw (ex-info "Error parsing token starting with '!'" {:token token}))))
;; $$ = table ID.