The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
QP parameters code => Lib (#61114)
Cam Saul03c268b8409e
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 31c59af3d07..8e090a1464f 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -947,6 +947,7 @@metabase.query-processor.middleware.limitmetabase.query-processor.middleware.permissionsmetabase.query-processor.middleware.wrap-value-literals+ metabase.query-processor.parameters.operatorsmetabase.query-processor.pipelinemetabase.query-processor.pivotmetabase.query-processor.preprocessdiff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.cljindex 65492f3d01e..833739b07d8 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/field_test.clj@@ -27,7 +27,7 @@(doseq [[query-type gtap-rule][["MBQL"{:gtaps {:venues {:query (mt.tu/restricted-column-query (mt/id))- :remappings {:cat [:dimension (mt/id :venues :category_id)]}}}+ :remappings {:cat [:dimension [:field (mt/id :venues :category_id) nil]]}}}:attributes {:cat 50}}]["native"{:gtaps {:venues {:query@@ -88,7 +88,7 @@(met/with-gtaps-for-user! another-user {:gtaps {:venues{:remappings{:cat- [:dimension (mt/id :venues :category_id)]}}}+ [:dimension [:field (mt/id :venues :category_id) nil]]}}}:attributes {:cat 5 #_BBQ}}(is (= {:field_id (mt/id :venues :name):values [["Baby Blues BBQ"]diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.cljindex 54fa4408d7e..43a86bf580b 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj@@ -132,7 +132,10 @@{:database (mt/id):query {:source-table (str "card__" (u/the-id card))}:type :query}))- "metabase_cache")))))+ "metabase_cache")))))))++(deftest persistence-and-permissions-2+ (mt/with-model-cleanup [:model/PersistedInfo](testing "Queries from source if sandboxed"(met/with-gtaps!{:gtaps {:venues {:query (mt/mbql-query venues)diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.cljindex 6baa0955391..b1ee8002dcd 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj@@ -848,7 +848,7 @@:database_id db-id:type :model:query_type :native- :dataset_query (mt/native-query {:native "select 1"})+ :dataset_query (mt/native-query {:query "select 1"}):creator_id ann-id}{:keys [action-id]}@@ -886,7 +886,7 @@:database_id db-id:type :model:query_type :native- :dataset_query (mt/native-query {:native "select 1"})+ :dataset_query (mt/native-query {:query "select 1"}):creator_id ann-id}{:keys [action-id]}@@ -924,13 +924,13 @@:database_id db-id:type :model:query_type :native- :dataset_query (mt/native-query {:native "select 1"})+ :dataset_query (mt/native-query {:query "select 1"}):creator_id ann-id}{:keys [action-id]}{:name "My Action":type :query- :dataset_query {:type "native", :native {:native "select 1"}, :database db-id}+ :dataset_query {:type "native", :native {:query "select 1"}, :database db-id}:database_id db-id:creator_id ann-id:model_id card-id-1}]@@ -944,8 +944,8 @@:creator_id "[email protected]":created_at string?:query [{:dataset_query {:database "My Database"- :type "native"- :native {:native "select 1"}}}]+ :type :native+ :native {:query "select 1"}}}]:model_id card-eid-1}ser))(is (not (contains? ser :id)))diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.cljindex 6c21b7ae38a..523e7659938 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj@@ -8,6 +8,7 @@[metabase.driver-api.core :as driver-api][metabase.driver.bigquery-cloud-sdk.common :as bigquery.common][metabase.driver.common :as driver.common]+ [metabase.driver.common.parameters][metabase.driver.sql.parameters.substitution :as sql.params.substitution][metabase.driver.sql.query-processor :as sql.qp][metabase.driver.sql.util :as sql.u]@@ -35,6 +36,8 @@(set! *warn-on-reflection* true)+(comment metabase.driver.common.parameters/keep-me)+(defn- valid-project-identifier?"Is String `s` a valid BigQuery project identifier (a.k.a. project-id)? Identifiers are only allowed to containletters, numbers, and underscores, cannot start with a number, and for project-id, can be at most 30 characters long."diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.cljindex 44c654b4f8f..2fe382680f2 100644--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj@@ -874,10 +874,10 @@"`describe-fields` should see the fields in the table")(sync/sync-database! (mt/db) {:scan :schema})(testing "We should be able to run queries against the table"- (doseq [[col-nm param-v] [[:numeric_col (bigdec numeric-val)]- [:decimal_col (bigdec decimal-val)]- [:bignumeric_col (bigdec bignumeric-val)]- [:bigdecimal_col (bigdec bigdecimal-val)]]]+ (doseq [[col-nm param-v] {"numeric_col" (bigdec numeric-val)+ "decimal_col" (bigdec decimal-val)+ "bignumeric_col" (bigdec bignumeric-val)+ "bigdecimal_col" (bigdec bigdecimal-val)}](testing (format "filtering against %s" col-nm))(is (= 1(-> (mt/first-rowdiff --git a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.cljindex 1cebc18b9c0..8125b0b1620 100644--- a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj+++ b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj@@ -131,7 +131,7 @@(let [param (:value v)compiled-clause (-> (assoc param:target- [:template-tag+ [:dimension[:field (field->name (:field v) false){:base-type (get-in v [:field :base-type])}]])params.ops/to-clausediff --git a/src/metabase/actions/execution.clj b/src/metabase/actions/execution.cljindex cb749eeb167..cd047c46041 100644--- a/src/metabase/actions/execution.clj+++ b/src/metabase/actions/execution.clj@@ -23,21 +23,27 @@[metabase.util.malli :as mu][toucan2.core :as t2]))-(defn- execute-query-action!+(mu/defn- execute-query-action!"Execute a `QueryAction` with parameters as passed in from anendpoint of shape `{<parameter-id> <value>}`.`action` should already be hydrated with its `:card`."- [{:keys [dataset_query model_id] :as action} request-parameters]+ [{query :dataset_query, model-id :model_id, :as action} :- [:map+ [:model_id ::lib.schema.id/card]+ [:dataset_query [:map+ [:type [:= :native]]+ [:native [:map+ [:query :string]]]]]]+ request-parameters](log/tracef "Executing action\n\n%s" (u/pprint-to-str action))(try(let [parameters (for [parameter (:parameters action)](assoc parameter :value (get request-parameters (:id parameter))))- query (-> dataset_query+ query (-> query(update :type keyword)(assoc :parameters parameters))](log/debugf "Query (before preprocessing):\n\n%s" (u/pprint-to-str query))- (binding [qp.perms/*card-id* model_id]+ (binding [qp.perms/*card-id* model-id](qp.writeback/execute-write-query! query)))(catch Throwable e(if (= (:type (u/all-ex-data e)) qp.error-type/missing-required-permissions)diff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex 21874260300..87b984a115e 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -55,8 +55,7 @@:visualization_settings transform-action-visualization-settings})(t2/deftransforms :model/QueryAction- ;; shouldn't this be mi/transform-metabase-query?- {:dataset_query mi/transform-json})+ {:dataset_query mi/transform-metabase-query})(def ^:private transform-json-with-nested-parameters{:in (comp mi/json-indiff --git a/src/metabase/driver.clj b/src/metabase/driver.cljindex df0ca194d70..eab1e80404b 100644--- a/src/metabase/driver.clj+++ b/src/metabase/driver.clj@@ -993,7 +993,7 @@(defmulti substitute-native-parameters"For drivers that support `:native-parameters`. Substitute parameters in a normalized 'inner' native query.- {:query \"SELECT count(*) FROM table WHERE id = {{param}}\"+ {:query \"SELECT count(*) FROM table WHERE id = {{param}}\":template-tags {:param {:name \"param\", :display-name \"Param\", :type :number}}:parameters [{:type :number:target [:variable [:template-tag \"param\"]]@@ -1005,7 +1005,7 @@`metabase.driver.common.parameters.*` namespaces. See the `:sql` and `:mongo` drivers for sample implementations ofthis method.`Driver-agnostic end-to-end native parameter tests live in[[metabase.query-processor-test.parameters-test]] and other namespaces."- {:added "0.34.0" :arglists '([driver inner-query])}+ {:added "0.34.0" :arglists '([driver inner-native-query])}dispatch-on-initialized-driver:hierarchy #'hierarchy)diff --git a/src/metabase/driver/common/parameters/operators.clj b/src/metabase/driver/common/parameters/operators.cljindex 5fb247e2438..7ee25b26803 100644--- a/src/metabase/driver/common/parameters/operators.clj+++ b/src/metabase/driver/common/parameters/operators.clj@@ -74,10 +74,10 @@(nil? l) (assoc :type :number/<=, :value [u])))param))-(mu/defn to-clause :- mbql.s/Filter+(mu/defn to-clause :- ::mbql.s/Filter"Convert an operator style parameter into an mbql clause. Will also do arity checks and throws an ex-info with`:type qp.error-type/invalid-parameter` if arity is incorrect."- [param]+ [param :- ::mbql.s/Parameter](let [{param-type :type, [a b :as param-value] :value, [_ field] :target, options :options} (normalize-param param)](verify-type-and-arity field param-type param-value)(let [field' (mbql.u/wrap-field-id-if-needed field)@@ -86,9 +86,9 @@:binary (opts-fn [(keyword (name param-type)) field' a b] options):unary (opts-fn [(keyword (name param-type)) field' a] options):variadic (opts-fn (into [(keyword (name param-type)) field'] param-value) options)-+ #_else(throw (ex-info (format "Unrecognized operator: %s" param-type)- {:param-type param-type+ {:param-type param-type:param-value param-value:field-id (second field):type qp.error-type/invalid-parameter}))))))diff --git a/src/metabase/driver/common/parameters/values.clj b/src/metabase/driver/common/parameters/values.cljindex 38dcecab76d..6af7650b490 100644--- a/src/metabase/driver/common/parameters/values.clj+++ b/src/metabase/driver/common/parameters/values.clj@@ -27,9 +27,7 @@[metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.log :as log]- [metabase.util.malli :as mu]- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(clojure.lang ExceptionInfo)(java.util UUID)))@@ -157,12 +155,16 @@(first params)params)))nil-value? (and (seq matching-params)- (every? (fn [param]- (nil? (:value param)))+ (every? (fn [{:keys [value], :as _param}]+ (or (nil? value)+ (and (sequential? value)+ (every? nil? value))))matching-params))](cond;; if we have matching parameter(s) with at least one actual value, return them.- (and (seq matching-params) (some :value matching-params))+ (and (seq matching-params)+ (some :value matching-params)+ (not nil-value?))(normalize-params (filter :value matching-params));; If a FieldFilter has value=nil, return a [[params/no-value]];; so that this filter can be substituted with "1 = 1" regardless of whether or not this tag has default value@@ -240,7 +242,7 @@(let [snippet-id (or snippet-id(throw (ex-info (tru "Unable to resolve Snippet: missing `:snippet-id`"){:tag tag, :type qp.error-type/invalid-parameter})))- snippet (or (t2/select-one :model/NativeQuerySnippet :id snippet-id)+ snippet (or (lib.metadata/native-query-snippet (qp.store/metadata-provider) snippet-id)(throw (ex-info (tru "Snippet {0} {1} not found." snippet-id (pr-str snippet-name)){:snippet-id snippet-id:snippet-name snippet-namediff --git a/src/metabase/driver/h2.clj b/src/metabase/driver/h2.cljindex ca4e1f91d02..527f405e973 100644--- a/src/metabase/driver/h2.clj+++ b/src/metabase/driver/h2.clj@@ -266,8 +266,12 @@(check-read-only-statements query)((get-method driver/execute-reducible-query :sql-jdbc) driver query chans respond))-(defmethod driver/execute-write-query! :h2- [driver query]+(mu/defmethod driver/execute-write-query! :h2+ [driver :- :keyword+ query :- [:map+ [:type [:= :native]]+ [:native [:map+ [:query :string]]]]](check-native-query-not-using-default-user query)(check-action-commands-allowed query)((get-method driver/execute-write-query! :sql-jdbc) driver query))diff --git a/src/metabase/driver/sql/parameters/substitute.clj b/src/metabase/driver/sql/parameters/substitute.cljindex 6e9a0c5a5cc..d4e59e47699 100644--- a/src/metabase/driver/sql/parameters/substitute.clj+++ b/src/metabase/driver/sql/parameters/substitute.clj@@ -4,8 +4,7 @@[metabase.driver :as driver][metabase.driver-api.core :as driver-api][metabase.driver.common.parameters :as params]- [metabase.driver.sql.parameters.substitution- :as sql.params.substitution]+ [metabase.driver.sql.parameters.substitution :as sql.params.substitution][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.log :as log]))diff --git a/src/metabase/driver/sql/parameters/substitution.clj b/src/metabase/driver/sql/parameters/substitution.cljindex e4eb4e02ec6..67bf5672704 100644--- a/src/metabase/driver/sql/parameters/substitution.clj+++ b/src/metabase/driver/sql/parameters/substitution.clj@@ -315,7 +315,7 @@(sql.qp/->honeysql driver form))](cond(params.ops/operator? param-type)- (->> (assoc params :target [:template-tag (field->field-filter-clause driver field param-type value)])+ (->> (assoc params :target [:dimension (field->field-filter-clause driver field param-type value)])params.ops/to-clausedriver-api/desugar-filter-clausedriver-api/wrap-value-literals-in-mbqldiff --git a/src/metabase/driver/sql_jdbc/execute.clj b/src/metabase/driver/sql_jdbc/execute.cljindex 8f8dbb644df..e48f0f96c67 100644--- a/src/metabase/driver/sql_jdbc/execute.clj+++ b/src/metabase/driver/sql_jdbc/execute.clj@@ -832,8 +832,12 @@;;; | Actions Stuff |;;; +----------------------------------------------------------------------------------------------------------------+-(defmethod driver/execute-write-query! :sql-jdbc- [driver {{sql :query, :keys [params]} :native}]+(mu/defmethod driver/execute-write-query! :sql-jdbc+ [driver :- :keyword+ {{sql :query, :keys [params]} :native} :- [:map+ [:type [:= :native]]+ [:native [:map+ [:query :string]]]]]{:pre [(string? sql)]}(try(do-with-connection-with-optionsdiff --git a/src/metabase/embedding/api/common.clj b/src/metabase/embedding/api/common.cljindex 05fa45d672f..1324a2f0884 100644--- a/src/metabase/embedding/api/common.clj+++ b/src/metabase/embedding/api/common.clj@@ -4,7 +4,6 @@[clojure.string :as str][medley.core :as m][metabase.api.common :as api]- [metabase.driver.common.parameters.operators :as params.ops][metabase.eid-translation.core :as eid-translation][metabase.embedding.jwt :as embed][metabase.embedding.validation :as embedding.validation]@@ -16,6 +15,7 @@[metabase.queries.core :as queries][metabase.query-processor.card :as qp.card][metabase.query-processor.middleware.constraints :as qp.constraints]+ [metabase.query-processor.parameters.operators :as params.ops][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.json :as json]diff --git a/src/metabase/legacy_mbql/normalize.cljc b/src/metabase/legacy_mbql/normalize.cljcindex 32176f9aac0..fdc4f4c9c7f 100644--- a/src/metabase/legacy_mbql/normalize.cljc+++ b/src/metabase/legacy_mbql/normalize.cljc@@ -427,9 +427,9 @@[k v]))))metadata))-(defn- normalize-native-query+(mu/defn- normalize-native-query :- [:maybe :map]"For native queries, normalize the top-level keys, and template tags, but nothing else."- [native-query]+ [native-query :- [:maybe :map]](let [native-query (update-keys native-query maybe-normalize-token)](cond-> native-query(seq (:template-tags native-query)) (update :template-tags normalize-template-tags))))diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljcindex 225b64e0c72..c9fa681d879 100644--- a/src/metabase/legacy_mbql/schema.cljc+++ b/src/metabase/legacy_mbql/schema.cljc@@ -1329,13 +1329,13 @@[:mergeNativeQuery:Common[:map- [:query :any]]])+ [:query :some]]])(mr/def ::NativeSourceQuery[:mergeNativeQuery:Common[:map- [:native :any]]])+ [:native :some]]]);;; ----------------------------------------------- MBQL [Inner] Query -----------------------------------------------@@ -1629,7 +1629,7 @@(defclause variabletarget template-tag)-(def ^:private ParameterTarget+(mr/def ::parameter.target"Schema for the value of `:target` in a [[Parameter]].";; not 100% sure about this but `field` on its own comes from a Dashboard parameter and when it's wrapped in;; `dimension` it comes from a Field filter template tag parameter (don't quote me on this -- working theory)@@ -1643,7 +1643,7 @@[:merge[:ref :metabase.lib.schema.parameter/parameter][:map- [:target {:optional true} ParameterTarget]]])+ [:target {:optional true} [:ref ::parameter.target]]]])(def Parameter"Alias for ::Parameter. Prefer using that directly going forward."diff --git a/src/metabase/legacy_mbql/util.cljc b/src/metabase/legacy_mbql/util.cljcindex 058a9a6db99..34783e77f9b 100644--- a/src/metabase/legacy_mbql/util.cljc+++ b/src/metabase/legacy_mbql/util.cljc@@ -111,7 +111,8 @@[filter-clause & more-filter-clauses](simplify-compound-filter (cons :and (cons filter-clause more-filter-clauses))))-(defn legacy-last-stage-number+;;; TODO (Cam 7/16/25) -- why does the LEGACY MBQL UTILS have STAGE STUFF IN IT!+(defn ^:deprecated legacy-last-stage-number"Returns the canonical stage number of the last stage of the legacy `inner-query`."[inner-query](loop [{:keys [source-query qp/stage-had-source-card]} inner-query, n 0]@@ -120,42 +121,6 @@n(recur source-query (inc n)))))-(defn stage-path- "Returns a vector consisting of :source-query elements that address the stage of `inner-query`- specified by `stage-number`.-- Stage numbers are used as described in [[add-filter-clause]]."- [inner-query stage-number]- (if-not stage-number- []- (let [elements (if (neg? stage-number)- (dec (- stage-number))- (- (legacy-last-stage-number inner-query) stage-number))]- (into [] (repeat elements :source-query)))))--(mu/defn add-filter-clause-to-inner-query :- mbql.s/MBQLQuery- "Add a additional filter clause to an *inner* MBQL query, merging with the existing filter clause with `:and` if- needed.-- Stage numbers work as in [[add-filter-clause]]."- [inner-query :- mbql.s/MBQLQuery- stage-number :- [:maybe number?]- new-clause :- [:maybe mbql.s/Filter]]- (if (not new-clause)- inner-query- (let [path (stage-path inner-query stage-number)]- (update-in inner-query (conj path :filter) combine-filter-clauses new-clause))))--(mu/defn add-filter-clause :- mbql.s/Query- "Add an additional filter clause to an `outer-query` at stage `stage-number`- or at the last stage if `stage-number` is `nil`. If `new-clause` is `nil` this is a no-op.-- Stage numbers can be negative: `-1` refers to the last stage, `-2` to the penultimate stage, etc."- [outer-query :- mbql.s/Query- stage-number :- [:maybe number?]- new-clause :- [:maybe mbql.s/Filter]]- (update outer-query :query add-filter-clause-to-inner-query stage-number new-clause))-(defn- map-stages*"Helper for [[map-stages]]; call that instead."[f {:keys [source-query] :as inner-query}]diff --git a/src/metabase/lib/convert.cljc b/src/metabase/lib/convert.cljcindex eff076fdf84..dd797696d3e 100644--- a/src/metabase/lib/convert.cljc+++ b/src/metabase/lib/convert.cljc@@ -294,7 +294,19 @@(if (sequential? fields)(mapv ->pMBQL fields)(keyword fields))))- (not (:alias join)) (assoc :alias legacy-default-join-alias))))+ (not (:alias join)) (assoc :alias legacy-default-join-alias)+ ;; MBQL 5 does not support `:parameters` at the top level of a join, so move them to the join's first stage.+ ;;+ ;; TODO (Cam 8/8/25) -- this is not really a 100% correct transformation, parameters that specify+ ;; `:stage-number` should get moved to the corresponding stage. (The first stage is the default tho so this is+ ;; correct if `:stage-number` is unspecified.) We do this in the QP+ ;; in [[metabase.query-processor.middleware.parameters/move-top-level-params-to-stage*]].+ ;;+ ;; IRL parameters are never actually attached to joins at all, and the only reason we're even pretending+ ;; to "support them" (in air quotes) even this much is because we had a few tests that act like this is ok and I+ ;; don't want to fix them. But we don't really need to be serious about actually supporting this.+ (:parameters join) (-> (update-in [:stages 0 :parameters] #(into (vec %) (:parameters join)))+ (dissoc :parameters)))))(defmethod ->pMBQL :dispatch-type/sequential[xs]@@ -701,7 +713,15 @@(defmethod ->legacy-MBQL :mbql.stage/native [stage](-> stagedisqualify- (update-vals ->legacy-MBQL)))+ (update-vals ->legacy-MBQL)+ ;; a native stage becomes+ ;;+ ;; {:native "SELECT ..."}+ ;;+ ;; IF it is used as a source query. If it's a top-level inner query it's+ ;;+ ;; {:database 1, :type :native, :native {:query "SELECT ..."}}+ (set/rename-keys {:query :native})))(defmethod ->legacy-MBQL :mbql/query [query](trydiff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljcindex b6b62d85cbc..dcc9b13475e 100644--- a/src/metabase/lib/core.cljc+++ b/src/metabase/lib/core.cljc@@ -246,6 +246,7 @@[metabase.lib.field.utilupdate-keys-for-col-from-previous-stage][lib.filter+ add-filter-to-stagefilterfiltersfilterable-columns@@ -390,6 +391,7 @@with-temporal-bucket][lib.utilfresh-uuids+ native-stage?normalized-query-typeprevious-stageprevious-stage-numberdiff --git a/src/metabase/lib/field.cljc b/src/metabase/lib/field.cljcindex bfb381ca653..ac79f8b85e5 100644--- a/src/metabase/lib/field.cljc+++ b/src/metabase/lib/field.cljc@@ -280,9 +280,9 @@original-temporal-unit ((some-fn ::original-temporal-unit ::temporal-unit) metadata)](if unit(-> metadata- (assoc ::temporal-unit unit- ::original-effective-type original-effective-type)- (m/assoc-some ::original-temporal-unit original-temporal-unit))+ (assoc ::temporal-unit unit)+ (m/assoc-some ::original-effective-type original-effective-type+ ::original-temporal-unit original-temporal-unit))(cond-> (dissoc metadata ::temporal-unit ::original-effective-type)original-effective-type (assoc :effective-type original-effective-type)original-temporal-unit (assoc ::original-temporal-unit original-temporal-unit)))))diff --git a/src/metabase/lib/filter.cljc b/src/metabase/lib/filter.cljcindex 322f98325eb..250b5331dd5 100644--- a/src/metabase/lib/filter.cljc+++ b/src/metabase/lib/filter.cljc@@ -348,7 +348,7 @@(lib.common/defop during [t v unit])(lib.common/defop segment [segment-id])-(mu/defn- add-filter-to-stage+(mu/defn add-filter-to-stage"Add a new filter clause to a `stage`, ignoring it if it is a duplicate clause (ignoring :lib/uuid)."[stage :- ::lib.schema/stagenew-filter :- [:maybe ::lib.schema.expression/boolean]]diff --git a/src/metabase/lib/native.cljc b/src/metabase/lib/native.cljcindex cd83a1b93a9..12a858da025 100644--- a/src/metabase/lib/native.cljc+++ b/src/metabase/lib/native.cljc@@ -125,7 +125,7 @@;; Otherwise just an empty map, no tags.{}))))-(defn- assert-native-query! [stage]+(defn- assert-native-query [stage](assert (= (:lib/type stage) :mbql.stage/native) (i18n/tru "Must be a native query")))(def ^:private all-native-extra-keys@@ -156,7 +156,7 @@stage-without-old-extras (apply dissoc stage extras-to-remove)result (merge stage-without-old-extras (select-keys native-extras required-extras))missing-keys (set/difference required-extras (set (keys native-extras)))]- (assert-native-query! (lib.util/query-stage query 0))+ (assert-native-query (lib.util/query-stage query 0))(assert (empty? missing-keys)(i18n/tru "Missing extra, required keys for native query: {0}"(pr-str missing-keys)))@@ -187,7 +187,7 @@Native extras must be provided if the new database requires it."[query :- ::lib.schema/querymetadata-provider :- ::lib.schema.metadata/metadata-providerable]- (assert-native-query! (lib.util/query-stage query 0))+ (assert-native-query (lib.util/query-stage query 0))(let [stages-without-fields (->> (:stages query)(mapv (fn [stage](update stage :template-tags update-vals #(dissoc % :dimension)))))]@@ -206,19 +206,21 @@(lib.util/update-query-stagequery 0(fn [{existing-tags :template-tags :as stage}]- (assert-native-query! stage)+ (assert-native-query stage)(assoc stage:native inner-query:template-tags (extract-template-tags inner-query existing-tags)))))+;;; TODO (Cam 7/16/25) -- this really doesn't seem to do what I'd expect, maybe we should rename it something like+;;; `with-replaced-template-tags`(mu/defn with-template-tags :- ::lib.schema/query"Updates the native query's template tags."[query :- ::lib.schema/query- tags :- ::lib.schema.template-tag/template-tag-map]+ tags :- ::lib.schema.template-tag/template-tag-map](lib.util/update-query-stagequery 0(fn [{existing-tags :template-tags :as stage}]- (assert-native-query! stage)+ (assert-native-query stage)(let [valid-tags (keys existing-tags)](assoc stage :template-tags(merge existing-tags (select-keys tags valid-tags)))))))@@ -260,7 +262,7 @@This is only filled in by [[metabase.warehouses.api/add-native-perms-info]]and added to metadata when pulling a database from the list of dbs in js."[query :- ::lib.schema/query]- (assert-native-query! (lib.util/query-stage query 0))+ (assert-native-query (lib.util/query-stage query 0))(= :write (:native-permissions (lib.metadata/database query))))(defmethod lib.query/can-run-method :mbql.stage/native@@ -278,5 +280,5 @@"Returns the database engine.Must be a native query"[query :- ::lib.schema/query]- (assert-native-query! (lib.util/query-stage query 0))+ (assert-native-query (lib.util/query-stage query 0))(:engine (lib.metadata/database query)))diff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljcindex 49126439d6f..a7514197d6e 100644--- a/src/metabase/lib/schema.cljc+++ b/src/metabase/lib/schema.cljc@@ -26,7 +26,7 @@[metabase.lib.schema.literal :as literal][metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.schema.order-by :as order-by]- [metabase.lib.schema.parameter :as parameter]+ [metabase.lib.schema.parameter :as lib.schema.parameter][metabase.lib.schema.ref :as ref][metabase.lib.schema.template-tag :as template-tag][metabase.lib.schema.util :as lib.schema.util]@@ -40,41 +40,44 @@metabase.lib.schema.expression.window/keep-memetabase.lib.schema.filter/keep-me)+(mr/def ::stage.common+ [:map+ [:parameters {:optional true} [:ref ::lib.schema.parameter/parameters]]])+(mr/def ::stage.native[:and- [:map- {:decode/normalize #(->> %- common/normalize-map- ;; filter out null :collection keys -- see #59675- (m/filter-kv (fn [k v]- (not (and (= k :collection)- (nil? v))))))}- [:lib/type [:= {:decode/normalize common/normalize-keyword} :mbql.stage/native]]- [:lib/stage-metadata {:optional true} [:maybe [:ref ::lib.schema.metadata/stage]]]- ;; the actual native query, depends on the underlying database. Could be a raw SQL string or something like that.- ;; Only restriction is that, if present, it is non-nil.- ;; It is valid to have a blank query like `{:type :native}` in legacy.- [:native {:optional true} some?]- ;; any parameters that should be passed in along with the query to the underlying query engine, e.g. for JDBC these- ;; are the parameters we pass in for a `PreparedStatement` for `?` placeholders. These can be anything, including- ;; nil.- ;;- ;; TODO -- pretty sure this is supposed to be `:params`, not `:args`, and this is allowed to be anything rather- ;; than just `literal`... I think we're using the `literal` schema tho for either normalization or serialization- [:args {:optional true} [:sequential ::literal/literal]]- ;; the Table/Collection/etc. that this query should be executed against; currently only used for MongoDB, where it- ;; is required.- [:collection {:optional true} ::common/non-blank-string]- ;; optional template tag declarations. Template tags are things like `{{x}}` in the query (the value of the- ;; `:native` key), but their definition lives under this key.- [:template-tags {:optional true} [:ref ::template-tag/template-tag-map]]- ;; optional, set of Card IDs referenced by this query in `:card` template tags like `{{card}}`. This is added- ;; automatically during parameter expansion. To run a native query you must have native query permissions as well- ;; as permissions for any Cards' parent Collections used in `:card` template tag parameters.- [:query-permissions/referenced-card-ids {:optional true} [:maybe [:set ::id/card]]]- ;;- ;; TODO -- parameters??- ]+ [:merge+ ::stage.common+ [:map+ {:decode/normalize #(->> %+ common/normalize-map+ ;; filter out null :collection keys -- see #59675+ (m/filter-kv (fn [k v]+ (not (and (= k :collection)+ (nil? v))))))}+ [:lib/type [:= {:decode/normalize common/normalize-keyword} :mbql.stage/native]]+ [:lib/stage-metadata {:optional true} [:maybe [:ref ::lib.schema.metadata/stage]]]+ ;; the actual native query, depends on the underlying database. Could be a raw SQL string or something like that.+ ;; Only restriction is that, if present, it is non-nil.+ ;; It is valid to have a blank query like `{:type :native}` in legacy.+ [:native {:optional true} some?]+ ;; any parameters that should be passed in along with the query to the underlying query engine, e.g. for JDBC these+ ;; are the parameters we pass in for a `PreparedStatement` for `?` placeholders. These can be anything, including+ ;; nil.+ ;;+ ;; TODO -- pretty sure this is supposed to be `:params`, not `:args`, and this is allowed to be anything rather+ ;; than just `literal`... I think we're using the `literal` schema tho for either normalization or serialization+ [:args {:optional true} [:sequential ::literal/literal]]+ ;; the Table/Collection/etc. that this query should be executed against; currently only used for MongoDB, where it+ ;; is required.+ [:collection {:optional true} ::common/non-blank-string]+ ;; optional template tag declarations. Template tags are things like `{{x}}` in the query (the value of the+ ;; `:native` key), but their definition lives under this key.+ [:template-tags {:optional true} [:ref ::template-tag/template-tag-map]]+ ;; optional, set of Card IDs referenced by this query in `:card` template tags like `{{card}}`. This is added+ ;; automatically during parameter expansion. To run a native query you must have native query permissions as well+ ;; as permissions for any Cards' parent Collections used in `:card` template tag parameters.+ [:query-permissions/referenced-card-ids {:optional true} [:maybe [:set ::id/card]]]]](common/disallowed-keys{:query ":query is not allowed in a native query stage, you probably meant to use :native instead.":source-table "MBQL stage keys like :source-table are not allowed in a native query stage."@@ -122,7 +125,8 @@stage stage))(defn- expression-ref-errors-for-stage [stage]- (let [expression-names (into #{} (map (comp :lib/expression-name second)) (:expressions 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))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.@@ -185,20 +189,22 @@(mr/def ::stage.mbql[:and- [:map- {:decode/normalize normalize-mbql-stage}- [:lib/type [:= {:decode/normalize common/normalize-keyword} :mbql.stage/mbql]]- [:lib/stage-metadata {:optional true} [:maybe [:ref ::lib.schema.metadata/stage]]]- [:joins {:optional true} [:ref ::join/joins]]- [:expressions {:optional true} [:ref ::expression/expressions]]- [:breakout {:optional true} [:ref ::breakouts]]- [:aggregation {:optional true} [:ref ::aggregation/aggregations]]- [:fields {:optional true} [:ref ::fields]]- [:filters {:optional true} [:ref ::filters]]- [:order-by {:optional true} [:ref ::order-by/order-bys]]- [:source-table {:optional true} [:ref ::id/table]]- [:source-card {:optional true} [:ref ::id/card]]- [:page {:optional true} [:ref ::page]]]+ [:merge+ ::stage.common+ [:map+ {:decode/normalize normalize-mbql-stage}+ [:lib/type [:= {:decode/normalize common/normalize-keyword} :mbql.stage/mbql]]+ [:lib/stage-metadata {:optional true} [:maybe [:ref ::lib.schema.metadata/stage]]]+ [:joins {:optional true} [:ref ::join/joins]]+ [:expressions {:optional true} [:ref ::expression/expressions]]+ [:breakout {:optional true} [:ref ::breakouts]]+ [:aggregation {:optional true} [:ref ::aggregation/aggregations]]+ [:fields {:optional true} [:ref ::fields]]+ [:filters {:optional true} [:ref ::filters]]+ [:order-by {:optional true} [:ref ::order-by/order-bys]]+ [:source-table {:optional true} [:ref ::id/table]]+ [:source-card {:optional true} [:ref ::id/card]]+ [:page {:optional true} [:ref ::page]]]][:fn{:error/message "A query must have exactly one of :source-table or :source-card"}(complement (comp #(= (count %) 1) #{:source-table :source-card}))]@@ -405,7 +411,7 @@[true ::id/saved-questions-virtual-database][false ::id/database]]][:stages [:ref ::stages]]- [:parameters {:optional true} [:maybe [:ref ::parameter/parameters]]]+ [:parameters {:optional true} [:maybe [:ref ::lib.schema.parameter/parameters]]];;;; OPTIONS;;diff --git a/src/metabase/lib/schema/join.cljc b/src/metabase/lib/schema/join.cljcindex 84f2b6f9ea4..c3b57b34e24 100644--- a/src/metabase/lib/schema/join.cljc+++ b/src/metabase/lib/schema/join.cljc@@ -129,7 +129,8 @@:source-table "join should not have :source-table; use :stages instead":source-query "join should not have :source-query; use :stages instead":filter "join should not have top-level :filters; these should belong to one of the join :stages"- :filters "join should not have top-level :filters; these should belong to one of the join :stages"})+ :filters "join should not have top-level :filters; these should belong to one of the join :stages"+ :parameters "join should not have top-level :parameters; these should belong to one of the join :stages"})[:ref ::validate-field-aliases-match-join-alias]])(mr/def ::joinsdiff --git a/src/metabase/lib/schema/metadata.cljc b/src/metabase/lib/schema/metadata.cljcindex ec3f530b9ae..8ecbedd685d 100644--- a/src/metabase/lib/schema/metadata.cljc+++ b/src/metabase/lib/schema/metadata.cljc@@ -655,6 +655,8 @@[:id ::lib.schema.id/native-query-snippet]]);;; TODO (Cam 8/8/25) -- description, content, archived, collection-id+;;; TODO (Cam 8/8/25) -- description, content, archived, collection-id+(mr/def ::table"Schema for metadata about a specific [[metabase.warehouse-schema.models.table]]. More or less the same but withkebab-case keys."diff --git a/src/metabase/lib/schema/parameter.cljc b/src/metabase/lib/schema/parameter.cljcindex 734a0b7cb89..cc0c7015fe9 100644--- a/src/metabase/lib/schema/parameter.cljc+++ b/src/metabase/lib/schema/parameter.cljc@@ -50,7 +50,7 @@Signifies this is one of the new 'operator' parameter types added in 0.39.0 or so. These parameters can only be usedfor [[TemplateTag:FieldFilter]]s or for Dashboard parameters mapped to MBQL queries. The value of this key is thearity for the parameter, either `:unary`, `:binary`, or `:variadic`. See- the [[metabase.driver.common.parameters.operators]] namespace for more information.+ the [[metabase.query-processor.parameters.operators]] namespace for more information.### `:allowed-for`@@ -196,25 +196,30 @@(mr/def ::dimension.target[:multi {:dispatch lib.schema.common/mbql-clause-tag:error/fn (fn [{:keys [value]} _]- (str "Invalid :dimension target: must be either a :field or a :template-tag, got: "+ (str "Invalid :dimension target: must be a :field, :template-tag, or :expression, got: "(pr-str value)))}[:field [:ref ::legacy-field-ref]][:expression [:ref ::legacy-expression-ref]][:template-tag [:ref ::template-tag]]])-(mr/def ::DimensionOptions+;;; TODO (Cam 8/8/25) -- is options supposed to be non-empty? It it supposed to be removed from `:dimension` if it's+;;; empty? Unclear. I don't think it matters tho.+(mr/def ::dimension.options[:map{:error/message "dimension options"}[:stage-number {:optional true} :int]])+;;; TODO (Cam 8/8/25) -- seems really WACK to have dimension use MBQL 4 clause order even in Lib... I guess it's not a+;;; real MBQL clause tho.(mr/def ::dimension[:catn[:tag [:= {:decode/normalize lib.schema.common/normalize-keyword} :dimension]][:target ::dimension.target]- [:options [:? [:maybe ::DimensionOptions]]]])-;;; this is the reference like [:template-tag <whatever>], not the schema for native query template tags -- that lives-;;; in [[metabase.lib.schema.template-tag]]+ [:options [:? [:maybe ::dimension.options]]]])+(mr/def ::template-tag+ "This is the reference like [:template-tag <whatever>], not the schema for native query template tags -- that lives+ in [[metabase.lib.schema.template-tag]]."[:tuple#_tag [:= {:decode/normalize lib.schema.common/normalize-keyword} :template-tag]#_tag-name [:multi {:dispatch map?}@@ -222,10 +227,18 @@[:id ::lib.schema.common/non-blank-string]]][false ::lib.schema.common/non-blank-string]]])+(mr/def ::variable.target+ [:multi {:dispatch lib.schema.common/mbql-clause-tag+ :error/message "A :variable target must be a (legacy) :field or :template-tag"+ :error/fn (fn [{:keys [value]} _]+ (str "Invalid :variable target: must be a :field or :template-tag, got: " (pr-str value)))}+ [:field [:ref ::legacy-field-ref]]+ [:template-tag [:ref ::template-tag]]])+(mr/def ::variable[:tuple#_tag [:= {:decode/normalize lib.schema.common/normalize-keyword} :variable]- #_target [:ref ::template-tag]])+ #_target [:ref ::variable.target]])(mr/def ::target[:multi {:dispatch lib.schema.common/mbql-clause-tag@@ -236,24 +249,40 @@[:dimension [:ref ::dimension]][:variable [:ref ::variable]]])+(defn- normalize-parameter+ [param]+ (when (map? param)+ (let [param (lib.schema.common/normalize-map param)]+ (case (keyword (:type param))+ :number/between+ (let [[l u] (:value param)]+ (cond-> param+ (nil? u) (assoc :type :number/>=, :value [l])+ (nil? l) (assoc :type :number/<=, :value [u])))+ param))))+(mr/def ::parameter- [:map- [:type [:ref ::type]]- ;; TODO -- these definitely SHOULD NOT be optional but a ton of tests aren't passing them in like they should be.- ;; At some point we need to go fix those tests and then make these keys required- [:id {:optional true} ::lib.schema.common/non-blank-string]- [:target {:optional true} [:ref ::target]]- ;; not specified if the param has no value. TODO - make this stricter; type of `:value` should be validated based- ;; on the [[ParameterType]]- [:value {:optional true} :any]- ;; the name of the parameter we're trying to set -- this is actually required now I think, or at least needs to get- ;; merged in appropriately- [:name {:optional true} ::lib.schema.common/non-blank-string]- ;; The following are not used by the code in this namespace but may or may not be specified depending on what the- ;; code that constructs the query params is doing. We can go ahead and ignore these when present.- [:slug {:optional true} ::lib.schema.common/non-blank-string]- [:default {:optional true} :any]- [:required {:optional true} :any]])+ [:and+ [:map+ {:decode/normalize normalize-parameter}+ [:type [:ref ::type]]+ ;; TODO -- these definitely SHOULD NOT be optional but a ton of tests aren't passing them in like they should be.+ ;; At some point we need to go fix those tests and then make these keys required+ [:id {:optional true} ::lib.schema.common/non-blank-string]+ [:target {:optional true} [:ref ::target]]+ ;; not specified if the param has no value. TODO - make this stricter; type of `:value` should be validated based+ ;; on the [[ParameterType]]+ [:value {:optional true} :any]+ ;; the name of the parameter we're trying to set -- this is actually required now I think, or at least needs to get+ ;; merged in appropriately+ [:name {:optional true} ::lib.schema.common/non-blank-string]+ ;; The following are not used by the code in this namespace but may or may not be specified depending on what the+ ;; code that constructs the query params is doing. We can go ahead and ignore these when present.+ [:slug {:optional true} ::lib.schema.common/non-blank-string]+ [:default {:optional true} :any]+ [:required {:optional true} :any]]+ (lib.schema.common/disallowed-keys+ {:dimension ":dimension is not allowed in a parameter, you probably meant to use :target [:dimension ...] instead."})])(mr/def ::parameters[:sequential [:ref ::parameter]])diff --git a/src/metabase/lib/temporal_bucket.cljc b/src/metabase/lib/temporal_bucket.cljcindex d6166e13e49..58fa8e47b02 100644--- a/src/metabase/lib/temporal_bucket.cljc+++ b/src/metabase/lib/temporal_bucket.cljc@@ -468,9 +468,9 @@original-effective-type)options (-> options(assoc :temporal-unit unit- :effective-type new-effective-type- :metabase.lib.field/original-effective-type original-effective-type)- (m/assoc-some :metabase.lib.field/original-temporal-unit original-temporal-unit))]+ :effective-type new-effective-type)+ (m/assoc-some :metabase.lib.field/original-effective-type original-effective-type+ :metabase.lib.field/original-temporal-unit original-temporal-unit))][tag options id-or-name]);; `unit` is `nil`: remove the temporal bucket and remember it :metabase.lib.field/original-temporal-unit.(let [original-effective-type (:metabase.lib.field/original-effective-type options)diff --git a/src/metabase/lib/util/match.clj b/src/metabase/lib/util/match.cljindex 91383549cce..74e2e7e6080 100644--- a/src/metabase/lib/util/match.clj+++ b/src/metabase/lib/util/match.clj@@ -381,7 +381,7 @@(some? default) (conj default))))))(defmacro match-lite- "Pattern matching macro, simplified version of `clojure.core.match`.+ "Pattern matching macro, simplified version of [[clojure.core.match]].Usage:(match-lite value@@ -400,7 +400,7 @@(match-lite* value clauses false))(defmacro match-lite-recursive- "Like `match-lite`, but tries to match children recursively if the top-level match failed."+ "Like [[match-lite]], but tries to match children recursively if the top-level match failed."{:style/indent :defn}[value & clauses](match-lite* value clauses true))diff --git a/src/metabase/lib_be/metadata/jvm.clj b/src/metabase/lib_be/metadata/jvm.cljindex 100835ba7e8..b3eb99a9ec2 100644--- a/src/metabase/lib_be/metadata/jvm.clj+++ b/src/metabase/lib_be/metadata/jvm.clj@@ -30,6 +30,8 @@(or (qualified-keyword? k)(str/includes? k ".")))+;;; TODO (Cam 8/8/25) -- this is duplicated with [[metabase.lib.schema.common/memoized-kebab-key]]... should we use that+;;; here too? Or is it better if this keeps its own cache, which presumably has a smaller set of keys to deal with?(def ^{:private true:arglists '([k])} memoized-kebab-key"Calculating the kebab-case version of a key every time is pretty slow (even with the LRU caching@@ -320,6 +322,28 @@[segment](instance->metadata segment :metadata/segment))+;;;+;;; Native Query Snippet+;;;++(derive :metadata/native-query-snippet :model/NativeQuerySnippet)++(methodical/defmethod t2.model/resolve-model :metadata/native-query-snippet+ [model]+ (t2/resolve-model :model/NativeQuerySnippet) ; for side-effects+ model)++(methodical/defmethod t2.pipeline/build [#_query-type :toucan.query-type/select.*+ #_model :metadata/native-query-snippet+ #_resolved-query clojure.lang.IPersistentMap]+ [query-type model parsed-args honeysql]+ (merge (next-method query-type model parsed-args honeysql)+ {:select [:id :name :description :content :archived :collection_id]}))++(t2/define-after-select :metadata/native-query-snippet+ [snippet]+ (instance->metadata snippet :metadata/native-query-snippet))+;;;;;; MetadataProvider;;;@@ -334,13 +358,16 @@(defn- metadatas [database-id metadata-type ids](let [database-id-key (case metadata-type- :metadata/table :db_id- :metadata/card :database_id+ :metadata/table :db_id+ :metadata/card :card/database_id+ :metadata/native-query-snippet nil:table/db_id)](when (seq ids)(t2/select metadata-type- database-id-key database-id- :id [:in (set ids)]))))+ :id [:in (set ids)]+ (if database-id-key+ {:where [:= database-id-key database-id]}+ {})))))(defn- tables [database-id](t2/select :metadata/tablediff --git a/src/metabase/query_processor/card.clj b/src/metabase/query_processor/card.cljindex cfda8ef77ae..e2e090f4c70 100644--- a/src/metabase/query_processor/card.clj+++ b/src/metabase/query_processor/card.clj@@ -71,6 +71,7 @@(defn- last-stage-number[outer-query]+ #_{:clj-kondo/ignore [:deprecated-var]}(mbql.u/legacy-last-stage-number (:query outer-query)))(defn- nest-querydiff --git a/src/metabase/query_processor/dashboard.clj b/src/metabase/query_processor/dashboard.cljindex aca882eca22..9be9f490376 100644--- a/src/metabase/query_processor/dashboard.clj+++ b/src/metabase/query_processor/dashboard.clj@@ -4,13 +4,13 @@[clojure.string :as str][medley.core :as m][metabase.api.common :as api]- [metabase.driver.common.parameters.operators :as params.ops][metabase.events.core :as events][metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib.schema.id :as lib.schema.id][metabase.query-processor.card :as qp.card][metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.middleware.constraints :as qp.constraints]+ [metabase.query-processor.parameters.operators :as params.ops][metabase.users.models.user-parameter-value :as user-parameter-value][metabase.util :as u][metabase.util.i18n :refer [tru]]diff --git a/src/metabase/query_processor/middleware/parameters.clj b/src/metabase/query_processor/middleware/parameters.cljindex 73ec6621b5a..2503bc8f1a1 100644--- a/src/metabase/query_processor/middleware/parameters.clj+++ b/src/metabase/query_processor/middleware/parameters.clj@@ -3,127 +3,131 @@(:require[clojure.data :as data][clojure.set :as set]- [medley.core :as m]- [metabase.legacy-mbql.normalize :as mbql.normalize]- [metabase.legacy-mbql.schema :as mbql.s]- [metabase.legacy-mbql.util :as mbql.u]- [metabase.lib.util.match :as lib.util.match]+ [metabase.lib.core :as lib]+ [metabase.lib.schema :as lib.schema]+ [metabase.lib.schema.common :as lib.schema.common]+ [metabase.lib.schema.id :as lib.schema.id]+ [metabase.lib.schema.parameter :as lib.schema.parameter]+ [metabase.lib.schema.template-tag :as lib.schema.template-tag]+ [metabase.lib.walk :as lib.walk][metabase.query-processor.middleware.parameters.mbql :as qp.mbql][metabase.query-processor.middleware.parameters.native :as qp.native][metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]))-(defn- join? [m]- (:condition m))+(mu/defn- expand-stage :- ::lib.schema/stage+ "Expand `:parameters` in one stage map that contains them."+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ stage :- ::lib.schema/stage]+ (if-not ((some-fn :parameters :template-tags) stage)+ stage+ (let [f (case (:lib/type stage)+ :mbql.stage/mbql qp.mbql/expand+ :mbql.stage/native (fn [query _path stage]+ (qp.native/expand-stage query stage)))+ expanded (f query path stage)]+ (dissoc expanded :parameters :template-tags))))-(defn- nested-native? [m]- (and (:source-query m)- (:native (:source-query m))))--(mu/defn- move-join-condition-to-source-query :- mbql.s/Join- "Joins aren't allowed to have `:filter` clauses, generated by the `expand-mbql-params` function below. Move the filter- clause into the `:source-query`, converting `:source-table` to a source query if needed."- [{:keys [source-table], filter-clause :filter, :as join}]- (if-not filter-clause- join- (if source-table- (-> (assoc join :source-query {:source-table source-table, :filter filter-clause})- (dissoc :source-table :filter))- ;; putting parameters in a join that has a `:source-query` is a little wacky (just add them to `:parameters` in- ;; the source query itself), but we'll allow it for now- (-> (update-in join [:source-query :filter] mbql.u/combine-filter-clauses filter-clause)- (dissoc :filter)))))--(mu/defn- move-native-filter-to-parent-stage :- mbql.s/MBQLQuery- "Native stages aren't allowed to have `:filter` clauses, generated by the `expand-mbql-params` function below. Move the filter- clause into the parent stage, if needed."- [{{native-query :native, filter-clause :filter} :source-query, :as parent-stage}]- (if-not (and native-query filter-clause)- parent-stage- (-> parent-stage- (update :source-query dissoc :filter)- (update :filter mbql.u/combine-filter-clauses filter-clause))))+(mu/defn- expand-all :- ::lib.schema/query+ "Expand all `:parameters` anywhere in the query."+ [query :- ::lib.schema/query]+ (lib.walk/walk-stages query expand-stage))-(defn- expand-mbql-params [outer-query {:keys [parameters], :as m}]- ;; HACK `qp.mbql/expand` assumes it's operating on an outer query so wrap `m` to look like an outer query. TODO- ;; - fix `qp.mbql` to operate on abitrary maps instead of only on top-level queries.- (let [wrapped (assoc outer-query :query m)- {expanded :query} (qp.mbql/expand (dissoc wrapped :parameters) parameters)]- (cond-> expanded- (join? m) move-join-condition-to-source-query- (nested-native? m) move-native-filter-to-parent-stage)))+;;; if parameters specify `:stage-number`, it means the original stage number before we started preprocessing the+;;; query (i.e., before we expanded source cards and what not)-(defn- expand-one- "Expand `:parameters` in one inner-query-style map that contains them."- [outer-query {:keys [source-table source-query parameters], :as m}]- ;; HACK - normalization does not yet operate on `:parameters` that aren't at the top level, so double-check that- ;; they're normalized properly before proceeding.- (let [m (cond-> m- (seq parameters) (update :parameters (partial mbql.normalize/normalize-fragment [:parameters])))- expanded (if (or source-table source-query)- (expand-mbql-params outer-query m)- (qp.native/expand-inner m))]- (dissoc expanded :parameters :template-tags)))+(mu/defn- num-stages-prepended-by-preprocessing :- ::lib.schema.common/int-greater-than-or-equal-to-zero+ "Parameters can specify the `:stage-number` they should be applied to, but this is relative to the stage number of the+ query as it was originally passed in. The preprocessing middleware that expands source cards can introduce additional+ stages at the beginning of the query, so to get the actual stage number a parameter should affect we have to offset it+ by the number of stages added by preprocessing."+ [{:keys [stages], :as _query} :- ::lib.schema/query]+ (count (take-while :qp/stage-is-from-source-card stages)))-(defn- expand-all- "Expand all `:parameters` anywhere in the query."- ([outer-query]- (expand-all outer-query outer-query))+(mu/defn- parameter->stage-number :- :int+ "The stage number that this parameter should be applied to. This is derived from the `:stage-number` specified in the+ parameter `:target`, defaulting to `0`. Note that this `:stage-number` is relative to the stages in the query BEFORE+ stages were appended by preprocessing, so if a parameter specifies `:stage-number` 1 and the the first stage (stage 0)+ has a `:source-card` that gets expanded to three replacement stages (i.e., 2 additional stages prepended to `:stages`+ before the original first stage) then the actual stage number we need to apply the parameter is `3` (1 offset by+ the [[num-stages-prepended-by-preprocessing]])."+ [query :- ::lib.schema/query+ parameter :- ::lib.schema.parameter/parameter]+ (let [stage-number (or (-> parameter+ :target+ lib/->pMBQL+ lib/options+ :stage-number)+ 0)]+ (if (not (neg? stage-number))+ ;; for a non-negative stage number add the offset to it as mentioned above+ (+ stage-number (num-stages-prepended-by-preprocessing query))+ ;; for a NEGATIVE stage number we can leave it NEGATIVE because it applies to a stage relative to the end, and all+ ;; the `:source-card` stages get added to the front, e.g. `-1` applies to the same last stage and `-2` applies to+ ;; the same second-to-last stage either way.+ stage-number)))- ([outer-query m]- (lib.util.match/replace m- (_ :guard (every-pred map? (some-fn :parameters :template-tags)))- (let [expanded (expand-one outer-query &match)]- ;; now recursively expand any remaining maps that contain `:parameters`- (expand-all outer-query expanded)))))+(defn- move-top-level-params-to-stage* [query parameters]+ (reduce+ (fn [query parameter]+ (let [param-stage-number (parameter->stage-number query parameter)]+ (lib/update-query-stage query param-stage-number+ update :parameters+ (fn [parameters]+ (conj (vec parameters) parameter)))))+ query+ parameters))-(mu/defn- move-top-level-params-to-inner-query- "Move any top-level parameters to the same level (i.e., 'inner query') as the query they affect."- [{:keys [info parameters], query-type :type, :as outer-query} :- [:map [:type [:enum :query :native]]]]- (cond-> (set/rename-keys outer-query {:parameters :user-parameters})+(mu/defn- move-top-level-params-to-stage :- ::lib.schema/query+ "Move any top-level parameters to the stage they affect."+ [{:keys [info parameters], :as query} :- ::lib.schema/query]+ ;; TODO (Cam 8/8/25) -- as far as I can tell the only reason why we keep parameters around is that `:user-parameters`+ ;; is used in one single place, by [[metabase.driver.redshift/field->parameter-value]] for some nefarious purposes.+ ;; Seems icky to have a driver be digging into the query like that. Maybe we can fix that usage and remove this.+ (cond-> (set/rename-keys query {:parameters :user-parameters});; TODO: Native models should be within scope of dashboard filters, by applying the filter on an outer stage.;; That doesn't work, so the logic below requires MBQL queries only to fix the regression.;; Native models don't actual get filtered even when linked to dashboard filters, but that's not a regression.;; This can be fixed properly once this middleware is powered by MLv2. See #40011.(and (seq parameters)(:metadata/model-metadata info)- (= query-type :query)) (update query-type (fn [inner-query] {:source-query inner-query}))- (seq parameters) (assoc-in [query-type :parameters] parameters)))+ (not (lib/native-stage? (lib/query-stage query -1))))+ lib/append-stage-(defn- expand-parameters- "Expand parameters in the `outer-query`, and if the query is using a native source query, expand params in that as- well."- [outer-query]- (let [pivot-original-query (get-in outer-query [:info :pivot/original-query])]- (cond-> outer-query- pivot-original-query (m/dissoc-in [:info :pivot/original-query])- true move-top-level-params-to-inner-query- true expand-all- pivot-original-query (assoc-in [:info :pivot/original-query] pivot-original-query))))+ (seq parameters)+ (move-top-level-params-to-stage* parameters)))-(mu/defn- substitute-parameters* :- :map+(mu/defn- expand-parameters :- ::lib.schema/query"If any parameters were supplied then substitute them into the query."- [query]- (u/prog1 (expand-parameters query)+ [query :- ::lib.schema/query]+ (u/prog1 (-> query+ move-top-level-params-to-stage+ expand-all)(when (not= <> query)(when-let [diff (second (data/diff query <>))](log/tracef "\n\nSubstituted params:\n%s\n" (u/pprint-to-str 'cyan diff))))))-(defn- assoc-db-in-snippet-tag- [db template-tags]+(mu/defn- assoc-database-id-in-snippet-tag :- ::lib.schema.template-tag/template-tag-map+ [template-tags :- ::lib.schema.template-tag/template-tag-map+ database-id :- ::lib.schema.id/database](update-valstemplate-tags(fn [v](cond-> v- (= (:type v) :snippet) (assoc :database db)))))+ (= (:type v) :snippet) (assoc :database database-id)))))-(defn- hoist-database-for-snippet-tags+(mu/defn- hoist-database-for-snippet-tags :- ::lib.schema/query"Assocs the `:database` ID from `query` in all snippet template tags."- [query]- (u/update-in-if-exists query [:native :template-tags] (partial assoc-db-in-snippet-tag (:database query))))+ [query :- ::lib.schema/query]+ (lib.walk/walk-stages+ query+ (fn [_query _path stage]+ (when (lib/native-stage? stage)+ (u/update-if-exists stage :template-tags assoc-database-id-in-snippet-tag (:database query))))))-(defn substitute-parameters+(mu/defn substitute-parameters :- ::lib.schema/query"Substitute Dashboard or Card-supplied parameters in a query, replacing the param placeholers with appropriate valuesand/or modifiying the query as appropriate. This looks for maps that have the key `:parameters` and/or`:template-tags` and removes those keys, splicing appropriate conditions into the queries they affect.@@ -131,7 +135,7 @@A SQL query with a param like `{{param}}` will have that part of the query replaced with an appropriate snippet aswell as any prepared statement args needed. MBQL queries will have additional filter clauses added. (Or in a specialcase, the temporal bucketing on a breakout altered by a `:temporal-unit` parameter.)"- [query]+ [query :- ::lib.schema/query](-> queryhoist-database-for-snippet-tags- substitute-parameters*))+ expand-parameters))diff --git a/src/metabase/query_processor/middleware/parameters/mbql.clj b/src/metabase/query_processor/middleware/parameters/mbql.cljindex 87a8816ae9f..57d653e17e6 100644--- a/src/metabase/query_processor/middleware/parameters/mbql.clj+++ b/src/metabase/query_processor/middleware/parameters/mbql.clj@@ -1,18 +1,23 @@(ns metabase.query-processor.middleware.parameters.mbql"Code for handling parameter substitution in MBQL queries."(:require- [metabase.driver.common.parameters.dates :as params.dates]- [metabase.driver.common.parameters.operators :as params.ops]- [metabase.legacy-mbql.schema :as mbql.s]- [metabase.legacy-mbql.util :as mbql.u][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]- [metabase.lib.metadata.protocols :as lib.metadata.protocols]+ [metabase.lib.schema :as lib.schema]+ [metabase.lib.schema.common :as lib.schema.common]+ [metabase.lib.schema.expression :as lib.schema.expression]+ [metabase.lib.schema.id :as lib.schema.id]+ [metabase.lib.schema.metadata :as lib.schema.metadata]+ [metabase.lib.schema.parameter :as lib.schema.parameter]+ [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing][metabase.lib.util.match :as lib.util.match]+ [metabase.lib.walk :as lib.walk][metabase.query-processor.error-type :as qp.error-type]- [metabase.query-processor.store :as qp.store]+ [metabase.query-processor.parameters.dates :as params.dates]+ [metabase.query-processor.parameters.operators :as params.ops][metabase.query-processor.util.temporal-bucket :as qp.u.temporal-bucket][metabase.util.i18n :refer [tru]]+ [metabase.util.log :as log][metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -21,44 +26,40 @@"Returns long, biginteger, or double. Possible to use the edn reader but we would then have to worry about arbitrarymaps/stuff being read. Error messages would be more confusing EOF while reading instead of a more sensical numberformat exception."- [s]+ [s :- string?](if (re-find #"\." s)- (Double/parseDouble s)+ (parse-double s)(or (parse-long s) (biginteger s))))-(defn- field-type- [field-clause]- (lib.util.match/match-one field-clause- [:field (id :guard integer?) _] ((some-fn :effective-type :base-type)- (lib.metadata.protocols/field (qp.store/metadata-provider) id))- [:field (_ :guard string?) opts] (:base-type opts)))--(defn- expression-type- [query expression-clause]- (lib.util.match/match-one expression-clause- [:expression (expression-name :guard string?)]- (let [query (lib/query (qp.store/metadata-provider) query)]- (if-let [expr-clause (try- (lib/resolve-expression query expression-name)- (catch clojure.lang.ExceptionInfo e- (when-not (:expression-name e)- (throw e))))]- (lib/type-of query expr-clause)- :type/*))))+(mu/defn- field-type :- ::lib.schema.common/base-type+ [query :- ::lib.schema/query+ stage-path :- ::lib.walk/path+ a-ref :- [:or :mbql.clause/field :mbql.clause/expression]]+ (lib.walk/apply-f-for-stage-at-path lib/type-of query stage-path a-ref))++(mu/defn- expression-type :- ::lib.schema.common/base-type+ [query :- ::lib.schema/query+ expression-ref :- :mbql.clause/expression]+ (or (lib/type-of query expression-ref)+ :type/*))(mu/defn- parse-param-value-for-type"Convert `param-value` to a type appropriate for `param-type`.The frontend always passes parameters in as strings, which is what we want in most cases; for numbers, insteadconvert the parameters to integers or floating-point numbers."- [query param-type param-value field-clause :- mbql.s/Field]+ [query :- ::lib.schema/query+ stage-path :- ::lib.walk/path+ param-type :- ::lib.schema.parameter/type+ param-value+ a-ref :- [:or :mbql.clause/field :mbql.clause/expression]](cond;; for `id` or `category` type params look up the base-type of the Field and see if it's a number or not.;; If it *is* a number then recursively call this function and parse the param value as a number as appropriate.(and (#{:id :category} param-type)- (let [base-type (or (field-type field-clause)- (expression-type query field-clause))]+ (let [base-type (or (field-type query stage-path a-ref)+ (expression-type query a-ref))](isa? base-type :type/Number)))- (recur query :number param-value field-clause)+ (recur query stage-path :number param-value a-ref);; no conversion needed if PARAM-TYPE isn't :number or PARAM-VALUE isn't a string(or (not= param-type :number)@@ -68,52 +69,64 @@:else(to-numeric param-value)))-(mu/defn- build-filter-clause :- [:maybe mbql.s/Filter]- [query {param-type :type, param-value :value, [_ field :as target] :target, :as param}]- (cond- (params.ops/operator? param-type)- (params.ops/to-clause param)- ;; multipe values. Recursively handle them all and glue them all together with an OR clause- (sequential? param-value)- (mbql.u/simplify-compound-filter- (vec (cons :or (for [value param-value]- (build-filter-clause query {:type param-type, :value value, :target target})))))-- ;; single value, date range. Generate appropriate MBQL clause based on date string- (params.dates/date-type? param-type)- (params.dates/date-string->filter- (parse-param-value-for-type query param-type param-value (mbql.u/unwrap-field-or-expression-clause field))- field)-- ;; TODO - We can't tell the difference between a dashboard parameter (convert to an MBQL filter) and a native- ;; query template tag parameter without this. There's should be a better, less fragile way to do this. (Not 100%- ;; sure why, but this is needed for GTAPs to work.)- (mbql.u/is-clause? :template-tag field)- nil-- ;; single-value, non-date param. Generate MBQL [= [field <field> nil] <value>] clause- :else- [:=- (mbql.u/wrap-field-id-if-needed field)- (parse-param-value-for-type query param-type param-value (mbql.u/unwrap-field-or-expression-clause field))]))--(defn- update-breakout-unit-in [query path target-field-id temporal-unit new-unit]- (lib.util.match/replace-in- query path+(mu/defn- build-filter-clause :- [:maybe ::lib.schema.expression/boolean]+ [query :- ::lib.schema/query+ stage-path :- ::lib.walk/path+ {param-type :type, param-value :value, target :target, :as param} :- ::lib.schema.parameter/parameter]+ (let [a-ref (lib.util.match/match-one target+ #{:field :expression}+ (lib/->pMBQL &match))]+ (cond+ (params.ops/operator? param-type)+ (params.ops/to-clause param)++ ;; multiple values. Recursively handle them all and glue them all together with an OR clause+ (sequential? param-value)+ (let [clauses (for [value param-value]+ (build-filter-clause query stage-path {:type param-type, :value value, :target target}))]+ (if (= (count clauses) 1)+ (first clauses)+ (apply lib/or clauses)))++ ;; single value, date range. Generate appropriate MBQL clause based on date string+ (and (params.dates/date-type? param-type)+ a-ref)+ (params.dates/date-string->filter+ (parse-param-value-for-type query stage-path param-type param-value a-ref)+ a-ref)++ ;; TODO - We can't tell the difference between a dashboard parameter (convert to an MBQL filter) and a native+ ;; query template tag parameter without this. There's should be a better, less fragile way to do this. (Not 100%+ ;; sure why, but this is needed for GTAPs to work.)+ (= (first target) :template-tag)+ nil++ ;; single-value, non-date param. Generate MBQL [= [field <field> nil] <value>] clause+ a-ref+ (lib/=+ a-ref+ (parse-param-value-for-type query stage-path param-type param-value a-ref)))))++(mu/defn- update-breakout-unit* :- ::lib.schema/stage+ [stage :- ::lib.schema/stage+ target-column :- [:or ::lib.schema.id/field :string]+ temporal-unit :- ::lib.schema.temporal-bucketing/unit+ new-unit :- ::lib.schema.temporal-bucketing/unit]+ (lib.util.match/replace stage[(tag :guard #{:field :expression})- (_ :guard #(= target-field-id %))- (opts :guard #(= temporal-unit (:temporal-unit %)))]- [tag target-field-id (assoc opts :temporal-unit new-unit)]))--(defn- update-breakout-unit- [query- {[_dimension [_field target-field-id {:keys [base-type temporal-unit]}] dim-opts] :target- :keys [value] :as _param}]+ (opts :guard #(= temporal-unit (:temporal-unit %)))+ (_id-or-name :guard #(= target-column %))]+ (lib/with-temporal-bucket &match new-unit)))++(mu/defn- update-breakout-unit :- ::lib.schema/stage+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ stage :- ::lib.schema/stage+ {[_dimension [_ref target-column {:keys [base-type temporal-unit]}] _dim-opts] :target+ :keys [value] :as _param} :- ::lib.schema.parameter/parameter](let [new-unit (keyword value)base-type (or base-type- (when (integer? target-field-id)- (:base-type (lib.metadata/field (qp.store/metadata-provider) target-field-id))))- stage-path (into [:query] (mbql.u/stage-path (:query query) (:stage-number dim-opts)))]+ (when (integer? target-column)+ (:base-type (lib.metadata/field metadata-providerable target-column))))](assert (some? base-type) "`base-type` is not set.")(when-not (qp.u.temporal-bucket/compatible-temporal-unit? base-type new-unit)(throw (ex-info (tru "This chart can not be broken out by the selected unit of time: {0}." value)@@ -121,29 +134,47 @@:is-curated true:base-type base-type:unit new-unit})))- (-> query- (update-breakout-unit-in (conj stage-path :breakout) target-field-id temporal-unit new-unit)- (update-breakout-unit-in (conj stage-path :order-by) target-field-id temporal-unit new-unit))))+ (update-breakout-unit* stage target-column temporal-unit new-unit)))-(defn expand- "Expand parameters for MBQL queries in `query` (replacing Dashboard or Card-supplied params with the appropriate+(mu/defn expand :- ::lib.schema/stage.mbql+ "Expand parameters for MBQL queries in a query stage (replacing Dashboard or Card-supplied params with the appropriatevalues in the queries themselves)."- [query [{:keys [target value default], :as param} & rest]]- (let [param-value (or value default)]- (cond- (not param)- query-- (or (not target)- (not param-value))- (recur query rest)-- (= (:type param) :temporal-unit)- (let [query (update-breakout-unit query (assoc param :value param-value))]- (recur query rest))-- :else- (let [filter-clause (build-filter-clause query (assoc param :value param-value))- [_ _ opts] target- query (mbql.u/add-filter-clause query (:stage-number opts) filter-clause)]- (recur query rest)))))+ [query :- ::lib.schema/query+ stage-path :- ::lib.walk/path+ stage :- ::lib.schema/stage.mbql]+ (loop [stage stage, [{:keys [target value default], :as param} & more-params] (:parameters stage)]+ (let [param-value (or value default)]+ (cond+ (not param)+ stage++ ;; ignore `:template-tag` parameters... these may be lying around if we had a source card that was native and+ ;; then replaced it with an MBQL source card.+ (lib.util.match/match-one target :template-tag &match)+ (do+ (log/warnf "Ignoring :template-tag parameter %s because this is an MBQL stage (path = %s)"+ (pr-str target)+ (pr-str stage-path))+ (recur stage more-params))++ (not target)+ (do+ (log/infof "Ignoring parameter %s because it has no target" (pr-str param))+ (recur stage more-params))++ (or (nil? param-value)+ (and (sequential? param-value)+ (every? nil? param-value)))+ (do+ (log/infof "Ignoring parameter %s because it has no value" (pr-str param-value))+ (recur stage more-params))++ (= (:type param) :temporal-unit)+ (let [stage' (update-breakout-unit query stage (assoc param :value param-value))]+ (recur stage' more-params))++ :else+ (let [filter-clause (or (build-filter-clause query stage-path (assoc param :value param-value))+ (log/warnf "build-filter-clause did not return a valid clause for param %s" (pr-str param)))+ stage' (lib/add-filter-to-stage stage filter-clause)]+ (recur stage' more-params))))))diff --git a/src/metabase/query_processor/middleware/parameters/native.clj b/src/metabase/query_processor/middleware/parameters/native.cljindex fd4983f268a..0e481d25ac2 100644--- a/src/metabase/query_processor/middleware/parameters/native.clj+++ b/src/metabase/query_processor/middleware/parameters/native.clj@@ -12,8 +12,9 @@replaced as usual and the rest of the clause (`AND ...`) is included in the query as-isNative parameter parsing and substution logic shared by multiple drivers lives in- `metabase.driver.common.parameters.*`. Driver-specific parsing/substitution logic is implemented in- `metabase.driver.sql.parameters.*` (for SQL drivers) or similar namespaces for others.+ `metabase.driver.common.parameters.*` (for legacy MBQL) and `metabase.query-processor.parameters.*` (for MBQL 5).+ Driver-specific parsing/substitution logic is implemented in `metabase.driver.sql.parameters.*` (for SQL drivers) or+ similar namespaces for others.The different steps of this process, are similar between existing driver implementations, and are as follows:@@ -26,21 +27,34 @@snippets and prepared statement args, and combine the sequence of fragments back into a single SQL string."(:require[clojure.set :as set]+ [medley.core :as m][metabase.driver :as driver][metabase.driver.util :as driver.u]+ [metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]- [metabase.query-processor.store :as qp.store]))--(defn expand-inner+ [metabase.lib.schema :as lib.schema]+ [metabase.lib.schema.metadata :as lib.schema.metadata]+ [metabase.query-processor.store :as qp.store]+ [metabase.util.malli :as mu]))++(defn- substitute-native-parameters* [stage]+ (-> stage+ (set/rename-keys {:native :query})+ (m/update-existing :parameters (fn [parameters]+ (mapv lib/->legacy-MBQL parameters)))+ (m/update-existing :template-tags update-vals lib/->legacy-MBQL)+ (->> (driver/substitute-native-parameters driver/*driver*))+ (set/rename-keys {:query :native})))++(mu/defn expand-stage :- ::lib.schema/stage.native"Expand parameters inside an *inner* native `query`. Not recursive -- recursive transformations are handled inthe `middleware.parameters` functions that invoke this function."- [inner-query]- (if-not (driver.u/supports? driver/*driver* :native-parameters (lib.metadata/database (qp.store/metadata-provider)))- inner-query- ;; Totally ridiculous, but top-level native queries use the key `:query` for SQL or equivalent, while native- ;; source queries use `:native`. So we need to handle either case.- (let [source-query? (:native inner-query)- substituted-inner-query (driver/substitute-native-parameters driver/*driver*- (set/rename-keys inner-query {:native :query}))]- (cond-> (dissoc substituted-inner-query :parameters :template-tags)- source-query? (set/rename-keys {:query :native})))))+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ stage :- ::lib.schema/stage.native]+ (if-not (driver.u/supports? driver/*driver* :native-parameters (lib.metadata/database metadata-providerable))+ stage+ (let [substituted-stage (qp.store/with-metadata-provider (lib.metadata/->metadata-provider metadata-providerable)+ (substitute-native-parameters* stage))]+ (->+ substituted-stage+ (dissoc :parameters :template-tags)))))diff --git a/src/metabase/query_processor/parameters.clj b/src/metabase/query_processor/parameters.cljdeleted file mode 100644index de8c58d4696..00000000000--- a/src/metabase/query_processor/parameters.clj+++ /dev/null@@ -1,222 +0,0 @@-(ns metabase.query-processor.parameters- "Schemas and helper functions for various PARSED parameter maps. These are created from the `:parameters` passed in- with a query."- (:require- [metabase.lib.schema.common :as lib.schema.common]- [metabase.lib.schema.id :as lib.schema.id]- [metabase.lib.schema.literal :as lib.schema.literal]- [metabase.lib.schema.metadata :as lib.schema.metadata]- [metabase.lib.schema.parameter :as lib.schema.parameter]- [metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]))--(def no-value- "Convenience for representing an *optional* parameter present in a query but whose value is unspecified in the param- values."- ::no-value)--(mr/def ::no-value- [:= ::no-value])--(mr/def ::field-filter.value.map- [:map- [:type ::lib.schema.parameter/type]- [:value :any]])--(mr/def ::field-filter.value- [:or- ::no-value- ::field-filter.value.map- [:sequential [:ref ::field-filter.value]]])--(mr/def ::field-filter- "'FieldFilter' is something that expands to a clause like 'some_field BETWEEN 1 AND 10'-- `field` is a `:metadata/column`-- `value` is either:-- * [[no-value]]-- * A map contianing the value and type info for the value, e.g.-- {:type :date/single- :value #t \"2019-09-20T19:52:00.000-07:00\"}-- * A vector of maps like the one above (for multiple values)"- [:map- [:lib/type [:= ::field-filter]]- [:field ::lib.schema.metadata/column]- [:value ::field-filter.value]])--(mu/defn field-filter :- ::field-filter- "Create a parsed `field-filter` parameter from map `m`."- [m]- (assoc m :lib/type ::field-filter))--(defn field-filter?- "Whether `x` is a map representing a parsed [[field-filter]] parameter."- [x]- (= (:lib/type x) ::field-filter))--(mr/def ::temporal-unit- [:map- [:lib/type [:= ::temporal-unit]]- [:name ::lib.schema.common/non-blank-string]- ;; TODO (Cam 7/16/25) -- constrain `:value`- [:value some?]])--(mu/defn temporal-unit :- ::temporal-unit- "Create a parsed `temporal-unit` parameter from map `m`."- [m :- :map]- (assoc m :lib/type ::temporal-unit))--(defn temporal-unit?- "Whether `x` is a map representing a parsed [[temporal-unit]] parameter."- [x]- (= (:lib/type x) ::temporal-unit))--(mr/def ::referenced-card-query- "A ReferencedCardQuery parameter expands to the native query of the referenced card.-- `card-id` is the ID of the Card instance whose query is the value for this parameter.-- `query` is the native query as stored in the Card-- `parameters` are positional parameters for a parameterized native query e.g. the JDBC parameters corresponding to- `?` placeholders"- [:map- [:lib/type [:= ::referenced-card-query]]- [:card-id ::lib.schema.id/card]- [:query :string]- [:parameters {:optional true} [:maybe [:sequential :any]]]])--(mu/defn referenced-card-query :- ::referenced-card-query- "Create a parsed `referenced-card-query` parameter from map `m`."- [m :- :map]- (assoc m :lib/type ::referenced-card-query))--(defn referenced-card-query?- "Whether `x` is a map representing a parsed [[referenced-card-query]] parameter."- [x]- (= (:lib/type x) ::referenced-card-query))--(mr/def ::referenced-query-snippet- "A `ReferencedQuerySnippet` expands to the partial query snippet stored in the `NativeQuerySnippet` table in the- application DB.-- `snippet-id` is the integer ID of the row in the application DB from where the snippet content is loaded.-- `content` is the raw query snippet which will be replaced, verbatim, for this template tag."- [:map- [:lib/type [:= ::referenced-query-snippet]]- [:snippet-id ::lib.schema.id/snippet]- [:content :string]])--(mu/defn referenced-query-snippet :- ::referenced-query-snippet- "Create a parsed `referenced-query-snippet` parameter from map `m`."- [m :- :map]- (assoc m :lib/type ::referenced-query-snippet))--(defn referenced-query-snippet?- "Whether `x` is a map representing a parsed [[referenced-query-snippet]]."- [x]- (= (:lib/type x) ::referenced-query-snippet))--(mr/def ::date- "As in a literal date, defined by date-string `s`."- [:map- [:lib/type [:= ::date]]- [:s ::lib.schema.literal/string.date]])--(mu/defn date :- ::date- "Create a parsed `date` parameter from map `m`."- [m :- :map]- (assoc m :lib/type ::date))--(defn date?- "Whether `x` is a map representing a parsed [[date]] parameter."- [x]- (= (:lib/type x) ::date))--(mr/def ::date-range- [:map- [:lib/type [:= ::date-range]]- ;; TODO (Cam 7/16/25) -- constrain `:start` and `:end` values- [:start :any]- [:end :any]])--(mu/defn date-range :- ::date-range- "Create a new parsed `date-range` parameter from map `m`."- [m :- :map]- (assoc m :lib/type ::date-range))--(defn date-range?- "Whether `x` is a map representing a parsed [[date-range]] parameter."- [x]- (= (:lib/type x) ::date-range))--(mr/def ::date-time-range- [:map- [:lib/type [:= ::date-time-range]]- ;; TODO (Cam 7/16/25) -- constrain `:start` and `:end` values- [:start :any]- [:end :any]])--(mu/defn date-time-range :- ::date-time-range- "Create a new parsed `date-time-range` parameter from map `m`."- [m :- :map]- (assoc m :lib/type ::date-time-range))--(defn date-time-range?- "Whether `x` is a map representing a parsed [[date-time-range]] parameter."- [x]- (= (:lib/type x) ::date-time-range))--(mr/def ::param- [:map- [:lib/type [:= ::param]]- [:k :string]])--(mu/defn param :- ::param- "Create a new parsed `param` parameter from map `m`."- [m :- :map]- (assoc m :lib/type ::param))--(defn param?- "Whether `x` is a map that represents a parsed [[param]] parameter."- [x]- (= (:lib/type x) ::param))--(mr/def ::function-param- [:map- [:lib/type [:= ::function-param]]- [:function-name :string]- ;; TODO (Cam 7/16/25) -- constrain further; I think these have to be valid parameters- [:args [:sequential :any]]])--(mu/defn function-param :- ::function-param- "Create a new parsed `function-param` from map `m`."- [m :- :map]- (assoc m :lib/type ::function-param))--(defn function-param?- "Whether `x` is a map that represents a parsed [[function-param]]."- [x]- (= (:lib/type x) ::function-param))--(mr/def ::optional- [:map- [:lib/type [:= ::optional]]- ;; TODO (Cam 7/16/25) -- constrain further- [:args [:sequential :any]]])--(mu/defn optional :- ::optional- "Create a new parsed `optional` param from map `m`."- [m :- :map]- (assoc m :lib/type ::optional))--(defn optional?- "Whether `x` is a map that represents a parsed [[optional]] parameter."- [x]- (= (:lib/type x) ::optional))diff --git a/src/metabase/query_processor/parameters/operators.clj b/src/metabase/query_processor/parameters/operators.cljindex a30903e3af7..f1b4c5173c5 100644--- a/src/metabase/query_processor/parameters/operators.clj+++ b/src/metabase/query_processor/parameters/operators.clj@@ -6,7 +6,10 @@[:field26{:source-field 5}]]- :value [3 5]}"+ :value [3 5]}++ TODO (Cam 8/8/25) -- move this into `lib` since there's nothing particularly QP about it except+ for [[qp.error-type]], which maybe belongs in Lib too!"(:require[metabase.lib.core :as lib][metabase.lib.schema.expression :as lib.schema.expression]@@ -26,7 +29,7 @@(boolean (operator-arity param-type)))(mu/defn- verify-type-and-arity- [field :- :mbql.clause/field+ [field :- [:or :mbql.clause/field :mbql.clause/expression]param-typeparam-value](letfn [(maybe-arity-error [n]@@ -76,7 +79,7 @@[param](let [{param-type :type, [a b :as param-value] :value, target :target, options :options} (normalize-param param)field-ref (or (lib.util.match/match-one target- :field+ #{:field :expression}(lib/->pMBQL &match))(throw (ex-info (format "Invalid target: expected :field ref, got: %s" (pr-str target)){:target target, :type qp.error-type/invalid-parameter})))diff --git a/src/metabase/query_processor/parameters/parse.clj b/src/metabase/query_processor/parameters/parse.cljdeleted file mode 100644index 4d865e4231b..00000000000--- a/src/metabase/query_processor/parameters/parse.clj+++ /dev/null@@ -1,48 +0,0 @@-(ns metabase.query-processor.parameters.parse- (:require- [clojure.core.match :refer [match]]- [clojure.string :as str]- [metabase.lib.parse :as lib.parse]- [metabase.query-processor.parameters :as params]- [metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]))--(mr/def ::parsed-token- [:or- :string- ::params/param- ::params/function-param- ::params/optional])--(defn- ->param [value]- (match [value]- [s :guard string?]- s-- [{:type :metabase.lib.parse/param- :name param-name}]- (params/param {:k (str/trim param-name)})-- [{:type :metabase.lib.parse/function-param- :name param-name- :args args}]- (params/function-param {:function-name param-name, :args (mapv ->param args)})-- [{:type :metabase.lib.parse/optional- :contents contents}]- (params/optional {:args (mapv ->param contents)})))--(mu/defn parse :- [:sequential ::parsed-token]- "Attempts to parse parameters in string `s`. Parses any optional clauses or parameters found, and returns a sequence- of non-parameter string fragments (possibly) interposed with `Param` or `Optional` instances.-- If `handle-sql-comments` is true (default) then we make a best effort to ignore params in SQL comments."- ([s :- :string]- (parse s true))-- ([s :- :string- handle-sql-comments :- :boolean]- (->> (lib.parse/parse {:parse-error-type :invalid-query}- s- handle-sql-comments)- (mapv ->param))))diff --git a/src/metabase/query_processor/parameters/values.clj b/src/metabase/query_processor/parameters/values.cljdeleted file mode 100644index 3f3b655854d..00000000000--- a/src/metabase/query_processor/parameters/values.clj+++ /dev/null@@ -1,468 +0,0 @@-(ns metabase.query-processor.parameters.values- "These functions build a map of information about the types and values of the params used in a query. (These functions- don't parse the query itself, but instead look at the values of `:template-tags` and `:parameters` passed along with- the query.)-- (query->params-map some-inner-query)- ;; -> {\"checkin_date\" {:field {:name \"date\", :parent_id nil, :table_id 1375}- :param {:type \"date/range\"- :target [\"dimension\" [\"template-tag\" \"checkin_date\"]]- :value \"2015-01-01~2016-09-01\"}}}"- (:require- [clojure.string :as str]- [metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata]- [metabase.lib.schema :as lib.schema]- [metabase.lib.schema.common :as lib.schema.common]- [metabase.lib.schema.id :as lib.schema.id]- [metabase.lib.schema.metadata :as lib.schema.metadata]- [metabase.lib.schema.parameter :as lib.schema.parameter]- [metabase.lib.schema.template-tag :as lib.schema.template-tag]- [metabase.query-processor.compile :as qp.compile]- [metabase.query-processor.error-type :as qp.error-type]- [metabase.query-processor.middleware.limit :as limit]- [metabase.query-processor.parameters :as params]- [metabase.query-processor.util.persisted-cache :as qp.persistence]- [metabase.util :as u]- [metabase.util.i18n :refer [tru]]- [metabase.util.log :as log]- [metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]))--(set! *warn-on-reflection* true)--(defmulti ^:private parse-tag- "Parse a tag by its `:type`, returning an appropriate [[metabase.query-processor.parameters]] map."- {:arglists '([metadata-providerable tag params])}- (fn [_metadata-providerable {tag-type :type, :as _tag} _params]- (keyword tag-type)))--(defmethod parse-tag :default- [_metadata-providerable- {tag-type :type, :as tag}- _params]- (throw (ex-info (tru "Don''t know how to parse parameter of type {0}" (pr-str tag-type))- {:tag tag})))--;; various schemas are used to check that various functions return things in expected formats--;; TAGS in this case are simple params like {{x}} that get replaced with a single value ("ABC" or 1) as opposed to a-;; "FieldFilter" clause like FieldFilters-;;-;; Since 'FieldFilter' are considered their own `:type` (confusingly enough, called `:dimension`), to *actually* store-;; the type of a FieldFilter look at the key `:widget-type`. This applies to things like the default value for a-;; FieldFilter as well.--(mr/def ::single-value- "Schema for a valid *single* value for a param."- [:or ::params/field-filter ::params/date number? :string :boolean])--(mr/def ::parsed-param-value- "Schema for valid param value(s). Params can have one or more values."- [:maybe- [:or {:error/message "Valid param value(s)"}- ::params/no-value- ::single-value- [:sequential ::single-value]- :map]])--(mu/defn- tag-targets- "Given a template tag, returns a set of `target` structures that can be used to target the tag.- Potential targets look something like:-- [:dimension [:template-tag {:id <param-id>}]- [:dimension [:template-tag <param-name>]] ; for Field Filters-- [:variable [:template-tag {:id <param-id>}]]- [:variable [:template-tag <param-name>]] ; for other types of params-- Targeting template tags by ID is preferable (as of version 44) but targeting by name is supported for backwards- compatibility."- [tag :- ::lib.schema.template-tag/template-tag]- (let [target-type (case (:type tag)- :dimension :dimension- :variable)]- #{[target-type [:template-tag (:name tag)]]- [target-type [:template-tag {:id (:id tag)}]]}))--(defn- tag-target-pred- "Returns a predicate recognizing parameter targets pointing to `tag`."- [tag]- (let [targets (tag-targets tag)]- (fn tag-target? [param-target]- (and (vector? param-target)- (> (count param-target) 1)- (targets (subvec param-target 0 2))- ;; legacy dimension params come without stage-number, 0 is the default- (= (get-in param-target [2 :stage-number] 0)- ;; Currently, we have no multi-stage native queries, so the stage-number is always 0.- ;; If in the future we introduce such queries, we can specify the stage-number of tags- ;; and they should match the stage-number of the parameter target.- (get tag :stage-number 0))))))--(mu/defn- tag-params- "Return params from the provided `params` list targeting the provided `tag`."- [tag :- ::lib.schema.template-tag/template-tag- params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]]- (let [tag-target? (tag-target-pred tag)]- (seq (for [param params- :when (tag-target? (:target param))]- param))))--;;; FieldFilter Params (Field Filters) (e.g. WHERE {{x}})--(defn- missing-required-param-exception [param-display-name]- (ex-info (tru "You''ll need to pick a value for ''{0}'' before this query can run."- param-display-name)- {:type qp.error-type/missing-required-parameter}))--(mu/defn- field-ref->field-id :- ::lib.schema.id/field- [field-ref :- :mbql.clause/field]- (last field-ref))--(mu/defn- field-filter-value- "Get parameter value(s) for a Field filter. Returns map if there is a normal single value, or a vector of maps for- multiple values."- [tag :- ::lib.schema.template-tag/template-tag- params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]]- (let [matching-params (tag-params tag params)- tag-opts (:options tag)- normalize-params (fn [params]- ;; remove `:target` which is no longer needed after this point- ;; and add any tag options that are compatible with the new type- (let [params (map (fn [param]- (let [tag-opts (if (and (contains? tag-opts :case-sensitive)- (not (contains? #{:string/contains- :string/does-not-contain- :string/ends-with- :string/starts-with}- (:type param))))- (dissoc tag-opts :case-sensitive)- tag-opts)]- (cond-> (dissoc param :target)- (seq tag-opts)- (assoc :options tag-opts))))- params)]- (if (= (count params) 1)- (first params)- params)))- nil-value? (and (seq matching-params)- (every? (fn [param]- (nil? (:value param)))- matching-params))]- (cond- ;; if we have matching parameter(s) with at least one actual value, return them.- (and (seq matching-params) (some :value matching-params))- (normalize-params (filter :value matching-params))- ;; If a FieldFilter has value=nil, return a [[params/no-value]]- ;; so that this filter can be substituted with "1 = 1" regardless of whether or not this tag has default value- (and (not (:required tag)) nil-value?)- params/no-value- ;; When a FieldFilter has value=nil and is required, use the default value or throw an exception- (and (:required tag) nil-value?)- (if-let [tag-default (:default tag)]- (cond-> {:type (:widget-type tag :dimension) ; widget-type is the actual type of the default value if set- :value tag-default}- tag-opts (assoc :options tag-opts))- (throw (missing-required-param-exception (:display-name tag))))- ;; otherwise, attempt to fall back to the default value specified as part of the template tag.- (some? (:default tag))- (cond-> {:type (:widget-type tag :dimension) ; widget-type is the actual type of the default value if set- :value (:default tag)}- tag-opts (assoc :options tag-opts))- ;; if that doesn't exist, see if the matching parameters specified default values This can be the case if the- ;; parameters came from a Dashboard -- Dashboard parameter mappings can specify their own defaults -- but we want- ;; the defaults specified in the template tag to take precedence if both are specified- (and (seq matching-params) (every? :default matching-params))- (normalize-params matching-params)- ;; otherwise there is no value for this Field filter ("dimension"), throw Exception if this param is required,- (:required tag)- (throw (missing-required-param-exception (:display-name tag)))- ;; otherwise return [[params/no-value]] to signify that this filter can be substituted with "1 = 1"- :else- params/no-value)))--(mu/defmethod parse-tag :dimension :- [:maybe ::params/field-filter]- [metadata-providerable :- ::lib.schema.metadata/metadata-providerable- {field-ref :dimension, :as tag} :- ::lib.schema.template-tag/template-tag- params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]]- (params/field-filter- {:field (let [field-id (field-ref->field-id field-ref)]- (or (lib.metadata/field metadata-providerable field-id)- (throw (ex-info (tru "Can''t find field with ID: {0}" field-id)- {:field-id field-id, :type qp.error-type/invalid-parameter}))))- :value (field-filter-value tag params)}))--(mu/defmethod parse-tag :card :- ::params/referenced-card-query- [metadata-providerable :- ::lib.schema.metadata/metadata-providerable- {:keys [card-id], :as tag} :- ::lib.schema.template-tag/template-tag- _params]- (when-not card-id- (throw (ex-info (tru "Invalid :card parameter: missing `:card-id`")- {:tag tag, :type qp.error-type/invalid-parameter})))- (let [card (lib.metadata/card metadata-providerable card-id)- persisted-info (when (= (:type card) :model)- (:lib/persisted-info card))- query (or (:dataset-query card)- (throw (ex-info (tru "Card {0} not found." card-id)- {:card-id card-id, :tag tag, :type qp.error-type/invalid-parameter})))]- (try- (params/referenced-card-query- (let [query (assoc query :info {:card-id card-id})]- (log/tracef "Compiling referenced query for Card %d\n%s" card-id (u/pprint-to-str query))- (merge {:card-id card-id}- (or (when (qp.persistence/can-substitute? card persisted-info)- {:query (qp.persistence/persisted-info-native-query- (u/the-id (lib.metadata/database metadata-providerable))- persisted-info)})- (qp.compile/compile (lib/query- (lib.metadata/->metadata-provider metadata-providerable)- (limit/disable-max-results query)))))))- (catch clojure.lang.ExceptionInfo e- (throw (ex-info- (tru "The sub-query from referenced question #{0} failed with the following error: {1}"- (str card-id) (pr-str (.getMessage e)))- {:card-query-error? true- :card-id card-id- :tag tag- :type qp.error-type/invalid-parameter}- e))))))--(mu/defmethod parse-tag :snippet :- ::params/referenced-query-snippet- [metadata-providerable :- ::lib.schema.metadata/metadata-providerable- {:keys [snippet-name snippet-id], :as tag} :- ::lib.schema.template-tag/template-tag- _params]- (let [snippet-id (or snippet-id- (throw (ex-info (tru "Unable to resolve Snippet: missing `:snippet-id`")- {:tag tag, :type qp.error-type/invalid-parameter})))- snippet (or (lib.metadata/native-query-snippet metadata-providerable snippet-id)- (throw (ex-info (tru "Snippet {0} {1} not found." snippet-id (pr-str snippet-name))- {:snippet-id snippet-id- :snippet-name snippet-name- :tag tag- :type qp.error-type/invalid-parameter})))]- (params/referenced-query-snippet- {:snippet-id snippet-id- :content (:content snippet)})))--(mu/defmethod parse-tag :temporal-unit- [_metadata-providerable :- ::lib.schema.metadata/metadata-providerable- {:keys [required] tag-name :name :as tag}- params]- (let [matching-param (when-let [matching-params (not-empty (tag-params tag params))]- (when (> (count matching-params) 1)- (throw (ex-info (tru "Error: multiple values specified for parameter; non-Field Filter parameters can only have one value.")- {:type- qp.error-type/invalid-parameter- :template-tag tag- :matching-parameters params})))- (first matching-params))- param-value (:value matching-param)- nil-value? (and matching-param- (nil? param-value))- valid-temporal-units (into #{}- (map name)- (lib/available-temporal-units))]- (when-not (or (nil? param-value) (valid-temporal-units param-value))- (throw (ex-info (tru "Error: invalid value specified for temporal-unit parameter.")- {:value param-value- :expected valid-temporal-units})))- (params/temporal-unit- {:name tag-name- :value (or (:value matching-param)- (when (and nil-value? (not required))- params/no-value)- (:default tag)- (if required- (throw (missing-required-param-exception (:display-name tag)))- params/no-value))})))--;;; Non-FieldFilter Params (e.g. WHERE x = {{x}})--(mu/defn- param-value-for-raw-value-tag- "Get the value that should be used for a raw value (i.e., non-Field filter) template tag from `params`."- [tag :- ::lib.schema.template-tag/template-tag- params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]]- (let [matching-param (when-let [matching-params (not-empty (tag-params tag params))]- ;; double-check and make sure we didn't end up with multiple mappings or something crazy like that.- (when (> (count matching-params) 1)- (throw (ex-info (tru "Error: multiple values specified for parameter; non-Field Filter parameters can only have one value.")- {:type qp.error-type/invalid-parameter- :template-tag tag- :matching-parameters params})))- (first matching-params))- nil-value? (and matching-param- (nil? (:value matching-param)))]- ;; But if the param is present in `params` and its value is nil, don't use the default.- ;; If the param is not present in `params` use a default from either the tag or the Dashboard parameter.- ;; If both the tag and Dashboard parameter specify a default value, prefer the default value from the tag.- (or (:value matching-param)- (when (and nil-value? (not (:required tag)))- params/no-value)- (:default tag)- (:default matching-param)- (if (:required tag)- (throw (missing-required-param-exception (:display-name tag)))- params/no-value))))--(defmethod parse-tag :number- [_metadata-providerable tag params]- (param-value-for-raw-value-tag tag params))--(defmethod parse-tag :text- [_metadata-providerable tag params]- (param-value-for-raw-value-tag tag params))--(defmethod parse-tag :date- [_metadata-providerable tag params]- (param-value-for-raw-value-tag tag params))--;;; Parsing Values--(mu/defn- parse-number :- number?- "Parse a string like `1` or `2.0` into a valid number. Done mostly to keep people from passing in- things that aren't numbers, like SQL identifiers. When the value is an integer outside the Long range, BigInteger- is returned."- [s :- :string]- (if (re-find #"\." s)- (parse-double s)- (or (parse-long s) (biginteger s))))--(mu/defn- value->number :- [:or number? [:sequential {:min 1} number?]]- "Parse a 'numeric' param value. Normally this returns an integer or floating-point number, but as a somewhat- undocumented feature it also accepts comma-separated lists of numbers. This was a side-effect of the old parameter- code that unquestioningly substituted any parameter passed in as a number directly into the SQL. This has long been- changed for security purposes (avoiding SQL injection), but since users have come to expect comma-separated numeric- values to work we'll allow that (with validation) and return a vector to be converted to a list in the native query."- [value]- (cond- ;; already parsed- (number? value)- value- ;; newer operators use vectors as their arguments even if there's only one- (vector? value)- (u/many-or-one (mapv value->number value))- ;; if the value is a string, then split it by commas in the string. Usually there should be none.- ;; Parse each part as a number.- (string? value)- (u/many-or-one (mapv parse-number (str/split value #",")))))--(mu/defn- parse-value-for-field-type :- :any- "Do special parsing for value for a (presumably textual) FieldFilter (`:type` = `:dimension`) param (i.e., attempt- to parse it as appropriate based on the base type and semantic type of the Field associated with it). These are- special cases for handling types that do not have an associated parameter type (such as `date` or `number`), such as- UUID fields."- [effective-type :- ::lib.schema.common/base-type value]- (cond- (isa? effective-type :type/UUID)- (java.util.UUID/fromString value)-- (isa? effective-type :type/Number)- (value->number value)-- :else- value))--(mu/defn- update-filter-for-field-type :- ::parsed-param-value- "Update a Field Filter with a textual, or sequence of textual, values. The base type and semantic type of the field- are used to determine what 'semantic' type interpretation is required (e.g. for UUID fields)."- [{field :field, {value :value} :value, :as field-filter} :- ::params/field-filter]- (let [effective-type ((some-fn :effective-type :base-type) field)- new-value (cond- (string? value)- (parse-value-for-field-type effective-type value)-- (and (sequential? value)- (every? string? value))- (mapv (partial parse-value-for-field-type effective-type) value))]- (when (not= value new-value)- (log/tracef "update filter for base-type: %s value: %s -> %s"- (pr-str effective-type) (pr-str value) (pr-str new-value)))- (cond-> field-filter- new-value (assoc-in [:value :value] new-value))))--(mu/defn- parse-value-for-type :- ::parsed-param-value- "Parse a `value` based on the type chosen for the param, such as `text` or `number`. (Depending on the type of param- created, `value` here might be a raw value or a map including information about the Field it references as well as a- value.) For numbers, dates, and the like, this will parse the string appropriately; for `text` parameters, this will- additionally attempt handle special cases based on the base type of the Field, for example, parsing params for UUID- base type Fields as UUIDs."- [param-type :- ::lib.schema.template-tag/type value]- (cond- (= value params/no-value)- value-- (= param-type :number)- (value->number value)-- (= param-type :date)- (params/date {:s value})-- ;; Field Filters- (and (= param-type :dimension)- (= (get-in value [:value :type]) :number))- (update-in value [:value :value] value->number)-- (sequential? value)- (mapv (partial parse-value-for-type param-type) value)-- ;; Field Filters with "special" base types- (and (= param-type :dimension)- (get-in value [:field :base-type]))- (update-filter-for-field-type value)-- :else- value))--(mu/defn- value-for-tag :- ::parsed-param-value- "Given a map `tag` (a value in the `:template-tags` dictionary) return the corresponding value from the `params`- sequence. The `value` is something that can be compiled to SQL via `->replacement-snippet-info`."- [metadata-providerable :- ::lib.schema.metadata/metadata-providerable- tag :- ::lib.schema.template-tag/template-tag- params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]]- (try- (parse-value-for-type (:type tag) (parse-tag metadata-providerable tag params))- (catch Throwable e- (throw (ex-info (tru "Error determining value for parameter {0}: {1}"- (pr-str (:name tag))- (ex-message e))- {:tag tag- :type (or (:type (ex-data e)) qp.error-type/invalid-parameter)- :params params}- e)))))--(mu/defn stage->params-map :- [:map-of ::lib.schema.common/non-blank-string ::parsed-param-value]- "Extract parameters info from `query`. Return a map of parameter name -> value.-- (stage->params-map query -1)- ->- {:checkin_date #t \"2019-09-19T23:30:42.233-07:00\"}"- ([query]- (stage->params-map query 0))-- ([query :- ::lib.schema/query- stage-number :- :int]- (let [{tags :template-tags, params :parameters} (lib/query-stage query stage-number)]- (log/tracef "Building params map out of tags\n%s\nand params\n%s\n" (u/pprint-to-str tags) (u/pprint-to-str params))- (try- (into {} (for [[k tag] tags- :let [v (value-for-tag query tag params)]]- (do- (log/tracef "Value for tag %s\n%s\n->\n%s" (pr-str k) (u/pprint-to-str tag) (u/pprint-to-str v))- [k v])))- (catch Throwable e- (throw (ex-info (tru "Error building query parameter map: {0}" (ex-message e))- {:type (or (:type (ex-data e)) qp.error-type/invalid-parameter)- :tags tags- :params params}- e)))))))--(mu/defn referenced-card-ids :- [:set ::lib.schema.id/card]- "Return a set of all Card IDs referenced in the parameters in `params-map`. This should be added to the (inner) query- under the `:query-permissions/referenced-card-ids` key when doing parameter expansion."- [params-map :- [:map-of ::lib.schema.common/non-blank-string ::parsed-param-value]]- (into #{}- (keep (fn [param]- (when (params/referenced-card-query? param)- (:card-id param))))- (vals params-map)))diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.cljindex 8d7725ebe53..534a457c2b1 100644--- a/src/metabase/query_processor/preprocess.clj+++ b/src/metabase/query_processor/preprocess.clj@@ -136,7 +136,7 @@(ensure-pmbql #'metrics/adjust)(ensure-pmbql #'expand-macros/expand-macros)(ensure-pmbql #'qp.resolve-referenced/resolve-referenced-card-resources)- (ensure-legacy #'parameters/substitute-parameters)+ (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)diff --git a/src/metabase/query_processor/writeback.clj b/src/metabase/query_processor/writeback.cljindex 8ab80f4a2a5..2830f29cb26 100644--- a/src/metabase/query_processor/writeback.clj+++ b/src/metabase/query_processor/writeback.clj@@ -2,6 +2,7 @@"Code for executing writeback queries."(:require[metabase.driver :as driver]+ [metabase.lib.core :as lib][metabase.query-processor :as qp][metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.middleware.enterprise :as qp.enterprise]@@ -9,9 +10,12 @@[metabase.query-processor.middleware.permissions :as qp.perms][metabase.query-processor.preprocess :as qp.preprocess][metabase.query-processor.setup :as qp.setup]+ [metabase.query-processor.store :as qp.store][metabase.util :as u][metabase.util.i18n :refer [tru]]- [metabase.util.log :as log]))+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr]))(def ^:private execution-middleware"Middleware that happens after compilation, AROUND query execution itself. Has the form@@ -29,19 +33,32 @@qpmiddleware-fns))+(mr/def ::native-mbql-4-query+ [:map+ [:type [:= :native]]+ [:native [:map+ [:query :string]]]])++(mu/defn- substitute-params :- ::native-mbql-4-query+ [query :- ::native-mbql-4-query]+ (->> query+ (lib/query (qp.store/metadata-provider))+ parameters/substitute-parameters+ lib/->legacy-MBQL))+(defn- writeback-qp [];; `rff` and `context` are not currently used by the writeback QP stuff, so these parameters can be ignored; we pass;; in `nil` for these below.(letfn [(qp* [query _rff]- (let [query (parameters/substitute-parameters query)]+ (let [query (substitute-params query)];; ok, now execute the query.(log/debugf "Executing query\n\n%s" (u/pprint-to-str query))(driver/execute-write-query! driver/*driver* query)))](apply-middleware qp* (concat execution-middleware qp/around-middleware))))-(defn execute-write-query!- "Execute an writeback query from an action."- [query]+(mu/defn execute-write-query!+ "Execute an writeback query (which currently has to be an MBQL 4 native query) from an action."+ [query :- ::native-mbql-4-query](qp.setup/with-qp-setup [query query](let [{query-type :type, :as query} (qp.preprocess/preprocess query)];; make sure this is a native query.diff --git a/src/metabase/util/malli.cljc b/src/metabase/util/malli.cljcindex a1ad9dd202a..751b179dd02 100644--- a/src/metabase/util/malli.cljc+++ b/src/metabase/util/malli.cljc@@ -131,19 +131,6 @@{:error (explain schema-or-validator value)})))value))))-(core/defn map-schema-assoc- "Returns a new schema that is the same as map-schema, but with the key k associated with the value v.- If kvs are provided, they are also associated with the schema."- [map-schema & kvs]- (if kvs- (if (next kvs)- (let [key (first kvs)- val (first (next kvs))- ret (mut/assoc map-schema key val)]- (recur ret (nnext kvs)))- (throw (ex-info "map-schema-assoc expects even number of arguments after schema-map, found odd number" {})))- map-schema))-(core/defn require-all-keys"Ensure maps has no optional keys, maybe is required."[schema]diff --git a/test/metabase/driver/common/parameters/values_test.clj b/test/metabase/driver/common/parameters/values_test.cljindex 9d3a090c171..b319fb8b180 100644--- a/test/metabase/driver/common/parameters/values_test.clj+++ b/test/metabase/driver/common/parameters/values_test.clj@@ -8,7 +8,6 @@[metabase.driver.common.parameters.values :as params.values][metabase.driver.ddl.interface :as ddl.i][metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]- [metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.test-metadata :as meta][metabase.lib.test-util :as lib.tu]@@ -329,7 +328,7 @@(deftest ^:parallel field-filter-errors-test(testing "error conditions for field filter (:dimension) parameters"(testing "Should throw an Exception if Field does not exist"- (let [query (assoc (mt/native-query "SELECT * FROM table WHERE {{x}}")+ (let [query (assoc (mt/native-query {:query "SELECT * FROM table WHERE {{x}}"}):template-tags {"x" {:name "x":display-name "X":type :dimension@@ -506,7 +505,7 @@(deftest ^:parallel card-query-errors-test(testing "error conditions for :card parameters"(testing "should throw an Exception if Card does not exist"- (let [query (assoc (mt/native-query "SELECT * FROM table WHERE {{x}}")+ (let [query (assoc (mt/native-query {:query "SELECT * FROM table WHERE {{x}}"}):template-tags {"x" {:name "x":display-name "X":type :card@@ -516,7 +515,7 @@(query->params-map query)))))))(defn- query-with-snippet [& {:as snippet-properties}]- (assoc (mt/native-query "SELECT * FROM {{expensive-venues}}")+ (assoc (mt/native-query {:query "SELECT * FROM {{expensive-venues}}"}):template-tags {"expensive-venues" (merge{:type :snippet:name "expensive-venues"@@ -534,7 +533,7 @@clojure.lang.ExceptionInfo(query->params-map (query-with-snippet :snippet-id Integer/MAX_VALUE))))))-(deftest snippet-happy-path-test+(deftest ^:parallel snippet-happy-path-test(testing "Snippet parsing should work correctly for a valid Snippet"(mt/with-temp [:model/NativeQuerySnippet {snippet-id :id} {:name "expensive-venues":content "venues WHERE price = 4"}]@@ -542,14 +541,27 @@:content "venues WHERE price = 4"})}](is (= expected(query->params-map (query-with-snippet :snippet-id snippet-id))))-(testing "`:snippet-name` property in query shouldn't have to match `:name` of Snippet in DB"(is (= expected(query->params-map (query-with-snippet :snippet-id snippet-id, :snippet-name "Old Name")))))))))+(deftest ^:parallel snippet-happy-path-mock-metadata-provider-test+ (testing "Snippet parsing should work correctly for a valid Snippet"+ (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:native-query-snippets [{:id 1+ :content "venues WHERE price = 4"}]})+ (let [expected {"expensive-venues" (params/map->ReferencedQuerySnippet {:snippet-id 1+ :content "venues WHERE price = 4"})}]+ (is (= expected+ (query->params-map (query-with-snippet :snippet-id 1))))+ (testing "`:snippet-name` property in query shouldn't have to match `:name` of Snippet in DB"+ (is (= expected+ (query->params-map (query-with-snippet :snippet-id 1, :snippet-name "Old Name")))))))))+(deftest ^:parallel invalid-param-test(testing "Should throw an Exception if we try to pass with a `:type` we don't understand"- (let [query (assoc (mt/native-query "SELECT * FROM table WHERE {{x}}")+ (let [query (assoc (mt/native-query {:query "SELECT * FROM table WHERE {{x}}"}):template-tags {"x" {:name "x":type :writer}})](is (thrown?@@ -767,20 +779,7 @@(deftest ^:parallel handle-dashboard-parameters-without-values-test(testing "dash params for a template tag may have no :value or :default (#38012)"(mt/dataset test-data- (qp.store/with-metadata-provider (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [(lib.tu.macros/mbql-query orders)- (lib/with-template-tags- (lib/native-query meta/metadata-provider- "SELECT * FROM Orders WHERE {{createdAt}}")- {"createdAt"- {:type :dimension- :dimension #_[:field (meta/id :orders :created-at)]- (lib/ref (meta/field-metadata :orders :created-at))- :name "createdAt"- :id "4636d745-1467-4a70-ba20-2a08069d77ff"- :display-name "CreatedAt"- :widget-type :date/all-options}})])+ (qp.store/with-metadata-provider meta/metadata-provider(let [template-tags {"createdAt" {:type :dimension:dimension [:field (meta/id :orders :created-at) {}]:name "createdAt"diff --git a/test/metabase/driver/sql/parameters/substitute_test.clj b/test/metabase/driver/sql/parameters/substitute_test.cljindex ed4095621b7..89638c1f298 100644--- a/test/metabase/driver/sql/parameters/substitute_test.clj+++ b/test/metabase/driver/sql/parameters/substitute_test.clj@@ -8,13 +8,15 @@[metabase.driver.common.parameters.parse :as params.parse][metabase.driver.sql.parameters.substitute :as sql.params.substitute][metabase.legacy-mbql.normalize :as mbql.normalize]+ [metabase.lib.core :as lib][metabase.lib.test-metadata :as meta][metabase.query-processor :as qp][metabase.query-processor.compile :as qp.compile][metabase.query-processor.middleware.parameters.native :as qp.native][metabase.query-processor.test-util :as qp.test-util][metabase.test :as mt]- [metabase.test.data.interface :as tx]))+ [metabase.test.data.interface :as tx]+ [metabase.util.malli :as mu]))(defn- optional [& args] (params/->Optional args))(defn- param [param-name] (params/->Param param-name))@@ -473,13 +475,23 @@;;; ------------------------------------------- expansion tests: variables --------------------------------------------(defn- expand**+(mu/defn- expand**"Expand parameters inside a top-level native `query`. Not recursive."- [{:keys [parameters], inner :native, :as query}]+ [{:keys [parameters], :as query} :- [:map+ [:native [:map+ [:query some?]]]]](driver/with-driver :h2- (mt/with-metadata-provider meta/metadata-provider- (let [inner' (qp.native/expand-inner (update inner :parameters #(concat parameters %)))]- (assoc query :native inner')))))+ (let [mp meta/metadata-provider]+ (-> (lib/query+ mp+ (merge {:database (meta/id)+ :type :native}+ query))+ (lib/update-query-stage 0 (fn [stage]+ (-> stage+ (update :parameters concat parameters)+ (->> (qp.native/expand-stage mp)))))+ lib/->legacy-MBQL))))(defn- expand* [query](-> (expand** (mbql.normalize/normalize query))@@ -493,36 +505,41 @@:params []}(expand* {:native {:query "SELECT * FROM orders [[WHERE id = {{id}}]];":template-tags {"id" {:name "id", :display-name "ID", :type :number}}}- :parameters []})))+ :parameters []}))))+(deftest ^:parallel expand-variables-test-2(testing "unspecified *required* param"(is (thrown?Exception(expand** {:native {:query "SELECT * FROM orders [[WHERE id = {{id}}]];":template-tags {"id" {:name "id", :display-name "ID", :type :number, :required true}}}- :parameters []}))))+ :parameters []})))))+(deftest ^:parallel expand-variables-test-3(testing "default value"(is (= {:query "SELECT * FROM orders WHERE id = 100;":params []}(expand* {:native {:query "SELECT * FROM orders WHERE id = {{id}};":template-tags {"id" {:name "id", :display-name "ID", :type :number, :required true, :default "100"}}}- :parameters []}))))+ :parameters []})))))+(deftest ^:parallel expand-variables-test-4(testing "specified param (numbers)"(is (= {:query "SELECT * FROM orders WHERE id = 2;":params []}(expand* {:native {:query "SELECT * FROM orders WHERE id = {{id}};":template-tags {"id" {:name "id", :display-name "ID", :type :number, :required true, :default "100"}}}- :parameters [{:type "category", :target [:variable [:template-tag "id"]], :value "2"}]}))))+ :parameters [{:type "category", :target [:variable [:template-tag "id"]], :value "2"}]})))))+(deftest ^:parallel expand-variables-test-5(testing "specified param (date/single)"(is (= {:query "SELECT * FROM orders WHERE created_at > ?;":params [#t "2016-07-19"]}(expand* {:native {:query "SELECT * FROM orders WHERE created_at > {{created_at}};":template-tags {"created_at" {:name "created_at", :display-name "Created At", :type "date"}}}- :parameters [{:type :date/single, :target [:variable [:template-tag "created_at"]], :value "2016-07-19"}]}))))+ :parameters [{:type :date/single, :target [:variable [:template-tag "created_at"]], :value "2016-07-19"}]})))))+(deftest ^:parallel expand-variables-test-6(testing "specified param (text)"(is (= {:query "SELECT * FROM products WHERE category = ?;":params ["Gizmo"]}@@ -539,8 +556,7 @@([sql field-filter-param];; TIMEZONE FIXME(mt/with-clock (t/mock-clock #t "2016-06-07T12:00-00:00" (t/zone-id "UTC"))- (-> {:native {:query- sql+ (-> {:native {:query sql:template-tags {"date" {:name "date":display-name "Checkin Date":type :dimension@@ -903,7 +919,7 @@(defn- process-native [& {:as query}](qp/process-query(merge- (mt/native-query nil)+ {:database (mt/id), :type :native}query)))(deftest ^:parallel e2e-basic-testdiff --git a/test/metabase/driver/sql/parameters/substitution_test.clj b/test/metabase/driver/sql/parameters/substitution_test.cljindex 507e4ff4310..d75e3860fe1 100644--- a/test/metabase/driver/sql/parameters/substitution_test.clj+++ b/test/metabase/driver/sql/parameters/substitution_test.clj@@ -6,8 +6,7 @@[java-time.api :as t][metabase.driver :as driver][metabase.driver.common.parameters :as params]- [metabase.driver.sql.parameters.substitution- :as sql.params.substitution]+ [metabase.driver.sql.parameters.substitution :as sql.params.substitution][metabase.driver.sql.query-processor :as sql.qp][metabase.lib.metadata :as lib.metadata][metabase.lib.test-metadata :as meta]diff --git a/test/metabase/legacy_mbql/util_test.cljc b/test/metabase/legacy_mbql/util_test.cljcindex d2c81c81b23..4912c4228be 100644--- a/test/metabase/legacy_mbql/util_test.cljc+++ b/test/metabase/legacy_mbql/util_test.cljc@@ -182,58 +182,6 @@[:= [:field 4 nil] 300]]))"Should be able to combine multiple compound clauses"))-(t/deftest ^:parallel add-filter-clause-test-1-single-stage- (t/is (= {:database 1- :type :query- :query {:source-table 1- :filter [:and [:= [:field 1 nil] 100] [:= [:field 2 nil] 200]]}}- (mbql.u/add-filter-clause- {:database 1- :type :query- :query {:source-table 1- :filter [:= [:field 1 nil] 100]}}- 0- [:= [:field 2 nil] 200]))- "Should be able to add a filter clause to a query"))--(t/deftest ^:parallel add-filter-clause-test-2-earlier-stage- (doseq [stage-number [0 -2]]- (t/is (= {:database 1- :type :query- :query {:source-query {:source-table 1- :filter [:and [:= [:field 1 nil] 100] [:= [:field 2 nil] 200]]- :aggregation [[:count]]}- :expressions {"negated" [:* [:field 1 nil] -1]}}}- (mbql.u/add-filter-clause- {:database 1- :type :query- :query {:source-query {:source-table 1- :filter [:= [:field 1 nil] 100]- :aggregation [[:count]]}- :expressions {"negated" [:* [:field 1 nil] -1]}}}- stage-number- [:= [:field 2 nil] 200]))- "Should be able to add a filter clause to an earlier stage of a query")))--(t/deftest ^:parallel add-filter-clause-test-3-later-stage- (doseq [stage-number [-1 1]]- (t/is (= {:database 1- :type :query- :query {:source-query {:source-table 1- :filter [:= [:field 1 nil] 100]- :aggregation [[:count]]}- :expressions {"negated" [:* [:field 1 nil] -1]}- :filter [:= [:field 2 nil] 200]}}- (mbql.u/add-filter-clause- {:database 1- :type :query- :query {:source-query {:source-table 1- :filter [:= [:field 1 nil] 100]- :aggregation [[:count]]}- :expressions {"negated" [:* [:field 1 nil] -1]}}}- stage-number- [:= [:field 2 nil] 200])))))-(t/deftest ^:parallel map-stages-test(let [test-fn (fn [inner-query stage-number](assoc inner-query ::stage-number stage-number))]diff --git a/test/metabase/lib/convert_test.cljc b/test/metabase/lib/convert_test.cljcindex a877989c81f..0a5e29f08e7 100644--- a/test/metabase/lib/convert_test.cljc+++ b/test/metabase/lib/convert_test.cljc@@ -1237,6 +1237,122 @@(is (= legacy-query(-> legacy-query lib.convert/->pMBQL lib.convert/->legacy-MBQL)))))+(deftest ^:parallel join-native-source-query->legacy-test+ (testing "join :source-query should rename :query to :native for native stages"+ (let [query {:lib/type :mbql/query+ :stages [{:lib/type :mbql.stage/mbql+ :joins [{:lib/type :mbql/join+ :alias "c"+ :conditions [[:=+ {:lib/uuid "43813e7b-ebf7-4278-8ab4-af23be9ffc0d"}+ [:field+ {:lib/uuid "b8ad483b-1ff8-4979-bb3e-c006fe5caf46"}+ 61325]+ [:field+ {:base-type :type/BigInteger, :join-alias "c", :lib/uuid "3000ef3f-a190-4f47-88df-404150748352"}+ "ID"]]]+ :stages [{:lib/type :mbql.stage/native+ :query "SELECT * FROM categories WHERE name = ?;"+ :params ["BBQ"]}+ {:lib/type :mbql.stage/mbql}]}]}]}]+ (is (=? {:type :query+ :query {:joins [{:alias "c"+ :condition [:= [:field 61325 nil] [:field "ID" {:base-type :type/BigInteger, :join-alias "c"}]]+ :source-query {:native "SELECT * FROM categories WHERE name = ?;"+ :params ["BBQ"]}}]}}+ (lib.convert/->legacy-MBQL query))))))++(deftest ^:parallel do-not-do-nasty-stuff-to-parameters-test+ (let [query {:database 33001+ :type :query+ :query {:source-query {:source-table 33030+ :expressions {"date-column" [:field 33302 nil]+ "number-column" [:field 33300 nil]}+ :parameters [{:type :date/range+ :value "2019-09-29~2023-09-29"+ :target [:dimension [:expression "date-column"]]}+ {:type :category+ :value 1+ :target [:dimension [:expression "number-column"]]}]}}}]+ (is (=? {:lib/type :mbql/query+ :stages [{:lib/type :mbql.stage/mbql+ :expressions [[:field+ {:lib/uuid string?+ :lib/expression-name "date-column"}+ pos-int?]+ [:field+ {:lib/uuid string?+ :lib/expression-name "number-column"}+ pos-int?]]+ :parameters [{:type :date/range, :value "2019-09-29~2023-09-29", :target [:dimension [:expression "date-column"]]}+ {:type :category, :value 1, :target [:dimension [:expression "number-column"]]}]}+ {:lib/type :mbql.stage/mbql}]}+ (lib/->pMBQL query)))+ (is (=? query+ (-> query lib/->pMBQL lib/->legacy-MBQL)))))++;;; TODO (Cam 8/8/25) -- mentioned in `->pMBQL` for `:mbql/join` but we don't even actually ever attach `:parameters`+;;; to a join's top-level IRL, so this not something we ACTUALLY need to support.+(deftest ^:parallel join-parameters-test+ (let [query {:database 33001+ :type :query+ :query {:source-query {:source-table 33040}+ :aggregation [[:count]]+ :joins [{:source-table 33010+ :alias "c"+ :condition [:=+ [:field 33402 nil]+ [:field 33100 {:join-alias "c"}]]+ :parameters [{:type :category+ :target [:field 33101 nil]+ :value "BBQ"}]}]}}]+ (is (=? {:stages [{:source-table 33040}+ {:joins [{:alias "c"+ :parameters (symbol "nil #_\"key is not present.\"")+ :conditions [[:=+ {}+ [:field {} 33402]+ [:field {:join-alias "c"} 33100]]]+ :lib/type :mbql/join+ :stages [{:lib/type :mbql.stage/mbql+ :source-table 33010+ :parameters [{:type :category+ :target [:field 33101 nil]+ :value "BBQ"}]}]}]}]+ :database 33001}+ (lib/->pMBQL query)))+ (testing "round-trip to legacy should leave join parameters in the :source-query"+ (is (=? {:database 33001+ :type :query+ :query {:source-query {:source-table 33040}+ :aggregation [[:count]]+ :joins [{:source-query {:source-table 33010+ :parameters [{:type :category+ :target [:field 33101 nil]+ :value "BBQ"}]}+ :alias "c"+ :condition [:=+ [:field 33402 nil]+ [:field 33100 {:join-alias "c"}]]}]}}+ (-> query lib/->pMBQL lib/->legacy-MBQL))))))++(deftest ^:parallel join-parameters-test-2+ (testing "If join has top-level :parameters and its source query has :parameters, splice them together"+ (let [query {:database 33001+ :type :query+ :query {:aggregation [[:count]]+ :joins [{:source-query {:source-table 33010+ :parameters [{:name "id", :type :category, :target [:field 33100 nil], :value 5}]}+ :alias "c"+ :condition [:= [:field 33402 nil] [:field 33100 {:join-alias "c"}]]+ :parameters [{:type "category", :target [:field 33101 nil], :value "BBQ"}]}]+ :source-table 33040}}]+ (is (=? {:stages [{:joins [{:alias "c"+ :stages [{:parameters [{:name "id", :type :category, :target [:field 33100 nil], :value 5}+ {:type :category, :target [:field 33101 nil], :value "BBQ"}]}]+ :parameters (symbol "nil #_\"key is not present.\"")}]}]}+ (lib/->pMBQL query))))))+(deftest ^:parallel convert-join-with-filters-test(testing "A join whose sole stage has :filters should get converted to a join with a :source-query (QUE-1566)"(let [query {:lib/type :mbql/query@@ -1307,7 +1423,7 @@:source-table 33040}}(lib/->legacy-MBQL query)))))-(deftest ^:parallel join-native-source-query->legacy-test+(deftest ^:parallel join-native-source-query->legacy-test-2(testing "join :source-query should rename :query to :native for native stages"(let [query {:lib/type :mbql/query:stages [{:lib/type :mbql.stage/mbqldiff --git a/test/metabase/lib/schema/parameter_test.cljc b/test/metabase/lib/schema/parameter_test.cljcindex a394208a33d..9c473f8ee01 100644--- a/test/metabase/lib/schema/parameter_test.cljc+++ b/test/metabase/lib/schema/parameter_test.cljc@@ -12,6 +12,12 @@#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))+(deftest ^:parallel parameter-schema-test+ (are [x] (not (me/humanize (mr/explain ::lib.schema.parameter/parameter x)))+ {:type :category+ :target [:variable [:field 71725 nil]]+ :value 50}))+(deftest ^:parallel normalize-dimension-test(are [x expected] (= expected(lib.normalize/normalizediff --git a/test/metabase/lib/util_test.cljc b/test/metabase/lib/util_test.cljcindex adcb696fcea..0077b3e99f2 100644--- a/test/metabase/lib/util_test.cljc+++ b/test/metabase/lib/util_test.cljc@@ -82,6 +82,20 @@:strategy :left-join:fk-field-id (meta/id :venues :category-id)}]}}))))+(deftest ^:parallel pipeline-joins-test-2+ (testing "Make sure we don't add unnecessary stages to joins when pipelining"+ (let [query {:database 33001+ :type :query+ :query {:aggregation [[:count]]+ :joins [{:source-query {:source-table 33010+ :parameters [{:name "id", :type :category, :target [:field 33100 nil], :value 5}]}+ :alias "c"+ :condition [:= [:field 33402 nil] [:field 33100 {:join-alias "c"}]]+ :parameters [{:type "category", :target [:field 33101 nil], :value "BBQ"}]}]+ :source-table 33040}}]+ (is (=? {:stages [{:joins [{:stages [{}]}]}]}+ (lib.util/pipeline query))))))+(deftest ^:parallel pipeline-source-metadata-test(testing "`:source-metadata` should get moved to the previous stage as `:lib/stage-metadata`"(is (=? {:lib/type :mbql/querydiff --git a/test/metabase/parameters/params_test.clj b/test/metabase/parameters/params_test.cljindex 703cb0e493f..35c41a819f7 100644--- a/test/metabase/parameters/params_test.clj+++ b/test/metabase/parameters/params_test.clj@@ -180,7 +180,8 @@(is (not (contains? param-fields "p7"))))))))(deftest ^:parallel card->template-tag-test- (let [card {:dataset_query (mt/native-query {:template-tags {"id" {:name "id"+ (let [card {:dataset_query (mt/native-query {:query "SELECT *"+ :template-tags {"id" {:name "id":display_name "ID":id "11111111":type :dimension@@ -239,7 +240,8 @@(deftest ^:parallel duplicate-column-names-test(testing "columns with duplicated names get mapped correctly to parameters"(testing "native queries"- (let [card {:dataset_query (mt/native-query {:template-tags+ (let [card {:dataset_query (mt/native-query {:query "SELECT *"+ :template-tags{"tag1" {:name "tag1":display_name "Tag 1":id "11111111"diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 27041253247..1b63c390e20 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -260,7 +260,6 @@:result_metadata (qp.preprocess/query->expected-cols (mt/mbql-query checkins))}](t2/update! :model/Card card-id changes)(f (t2/select-one-fn :result_metadata :model/Card :id card-id))))}]-(testing (format "When %s a Card\n" creating-or-updating)(testing "If result_metadata is empty, we should attempt to populate it"(f {:dataset_query (mt/mbql-query venues)}@@ -275,7 +274,7 @@(is (= (mt/derecordize metadata)(mt/derecordize new-metadata)))))))(testing "Shouldn't barf if query can't be run (e.g. if query is a SQL query); set metadata to nil"- (f {:dataset_query (mt/native-query {:native "SELECT * FROM VENUES"})}+ (f {:dataset_query (mt/native-query {:query "SELECT * FROM VENUES"})}(fn [metadata](is (= nilmetadata)))))@@ -284,7 +283,7 @@metadata (-> (mt/mbql-query checkins)qp.preprocess/query->expected-colsmt/metadata->native-form)]- (f (cond-> {:dataset_query (mt/native-query {:native "SELECT * FROM CHECKINS"})+ (f (cond-> {:dataset_query (mt/native-query {:query "SELECT * FROM CHECKINS"}):result_metadata metadata:entity_id card-eid}(= creating-or-updating "updating")diff --git a/test/metabase/query_processor/middleware/parameters/mbql_test.clj b/test/metabase/query_processor/middleware/parameters/mbql_test.cljindex 2bda5798507..90e709f0422 100644--- a/test/metabase/query_processor/middleware/parameters/mbql_test.clj+++ b/test/metabase/query_processor/middleware/parameters/mbql_test.clj@@ -6,148 +6,176 @@[metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.legacy-mbql.normalize :as mbql.normalize]+ [metabase.lib.core :as lib]+ [metabase.lib.test-metadata :as meta]+ [metabase.lib.test-util.macros :as lib.tu.macros][metabase.query-processor :as qp][metabase.query-processor.compile :as qp.compile][metabase.query-processor.middleware.parameters.mbql :as qp.mbql]- [metabase.query-processor.store :as qp.store][metabase.test :as mt][metabase.test.data.interface :as tx]))-(defn- expand-parameters [query]- (let [query (mbql.normalize/normalize query)]- (qp.store/with-metadata-provider (mt/id)- (qp.mbql/expand (dissoc query :parameters) (:parameters query)))))+(defn- expand-parameters+ [query]+ (if (:lib/type query)+ ;; MBQL 5 query: return an MBQL 5 query+ (let [params (:parameters query)]+ (reduce+ (fn [query stage-number]+ (lib/update-query-stage+ query+ stage-number+ (fn [stage]+ (qp.mbql/expand query+ [:stages stage-number]+ (cond-> stage+ (not-empty params) (assoc :parameters params))))))+ (dissoc query :parameters)+ (range (count (:stages query)))))+ ;; legacy input: return a legacy query+ (-> (lib/query meta/metadata-provider (mbql.normalize/normalize query))+ expand-parameters+ lib/->legacy-MBQL)))(defn- expanded-query-with-filter [filter-clause]- {:database 1+ {:database (meta/id):type :query- :query {:source-table 1000+ :query {:source-table (meta/id :venues):filter filter-clause- :breakout [[:field 17 nil]]}})+ :breakout [[:field (meta/id :venues :price) nil]]}})(defn- query-with-parameters [& parameters]- {:database 1+ {:database (meta/id):type :query- :query {:source-table 1000- :breakout [[:field 17 nil]]}+ :query {:source-table (meta/id :venues)+ :breakout [[:field (meta/id :venues :price) nil]]}:parameters (vec parameters)})(deftest ^:parallel basic-test(testing "adding a simple parameter"- (is (= (expanded-query-with-filter- [:= [:field (mt/id :venues :name) nil] "Cam's Toucannery"])- (expand-parameters- (query-with-parameters- {:hash "abc123"- :name "foo"- :type "id"- :target [:dimension [:field (mt/id :venues :name) nil]]- :value "Cam's Toucannery"}))))))+ (is (=? (expanded-query-with-filter+ [:= [:field (meta/id :venues :name) nil] "Cam's Toucannery"])+ (expand-parameters+ (query-with-parameters+ {:hash "abc123"+ :name "foo"+ :type "id"+ :target [:dimension [:field (meta/id :venues :name) nil]]+ :value "Cam's Toucannery"}))))))(deftest ^:parallel biginteger-test(testing "adding an id parameter with a biginteger value"- (is (= (expanded-query-with-filter- [:= [:field (mt/id :orders :id) nil] 9223372036854775808])- (expand-parameters- (query-with-parameters- {:hash "abc123"- :name "foo"- :type "id"- :target [:dimension [:field (mt/id :orders :id) nil]]- :value "9223372036854775808"}))))))+ (is (=? (expanded-query-with-filter+ [:= [:field (meta/id :orders :id) nil] 9223372036854775808])+ (expand-parameters+ (query-with-parameters+ {:hash "abc123"+ :name "foo"+ :type "id"+ :target [:dimension [:field (meta/id :orders :id) nil]]+ :value "9223372036854775808"}))))))(deftest ^:parallel multiple-filters-test(testing "multiple filters are conjoined by an :and"- (is (= (expanded-query-with-filter- [:and- [:= [:field (mt/id :venues :id) nil] 12]- [:= [:field (mt/id :venues :name) nil] "Cam's Toucannery"]- [:= [:field (mt/id :venues :id) nil] 999]])- (expand-parameters- (-> (query-with-parameters- {:hash "abc123"- :name "foo"- :type :id- :target [:dimension [:field (mt/id :venues :name) nil] nil]- :value "Cam's Toucannery"}- {:hash "def456"- :name "bar"- :type :category- :target [:dimension [:field (mt/id :venues :id) nil] {}]- :value 999})- (assoc-in [:query :filter] [:and [:= [:field (mt/id :venues :id) nil] 12]])))))))+ (is (=? (expanded-query-with-filter+ [:and+ [:= [:field (meta/id :venues :id) nil] 12]+ [:= [:field (meta/id :venues :name) nil] "Cam's Toucannery"]+ [:= [:field (meta/id :venues :id) nil] 999]])+ (expand-parameters+ (-> (query-with-parameters+ {:hash "abc123"+ :name "foo"+ :type :id+ :target [:dimension [:field (meta/id :venues :name) nil] nil]+ :value "Cam's Toucannery"}+ {:hash "def456"+ :name "bar"+ :type :category+ :target [:dimension [:field (meta/id :venues :id) nil] {}]+ :value 999})+ (assoc-in [:query :filter] [:and [:= [:field (meta/id :venues :id) nil] 12]])))))))(deftest ^:parallel multi-stage-test(testing "adding parameters to different stages"- (is (= {:database 1,- :type :query,- :query {:source-query {:source-table 1000,- :aggregation [[:count]],- :breakout [[:field 17 {:temporal-unit :year}]],- :filter [:= [:field 809 nil] "Cam's Toucannery"]},- :filter [:and- [:> [:field "count" {:base-type :type/Integer}] 0]- [:<= [:field "count" {:base-type :type/Integer}] 30]]}}- (expand-parameters- {:database 1- :type :query- :query {:source-query {:source-table 1000- :aggregation [[:count]]- :breakout [[:field 17 {:temporal-unit :day}]]}- :filter [:> [:field "count" {:base-type :type/Integer}] 0]}- :parameters [{:hash "abc123"- :name "foo"- :type "id"- :target [:dimension [:field 809 nil] {:stage-number -2}]- :value "Cam's Toucannery"}- {:hash "def456"- :name "bar"- :type :number/<=- :target [:dimension [:field "count" {:base-type :type/Integer}] {:stage-number 1}]- :value [30]}- {:value "year"- :type :temporal-unit- :id "66cf9285"- :target [:dimension- [:field 17 {:base-type :type/DateTime, :temporal-unit :day}]- {:stage-number -2}]}]})))))+ (is (=? {:stages [{:aggregation [[:count {}]]+ :breakout [[:field {:temporal-unit :year} (meta/id :venues :price)]]+ :filters [[:=+ {}+ [:field {} (meta/id :venues :name)]+ "Cam's Toucannery"]]}+ {:filters [[:> {}+ [:field {:base-type :type/Integer} "count"]+ 0]+ [:<= {}+ [:field {:base-type :type/Integer} "count"]+ 30]]}]}+ (expand-parameters+ (lib/query+ meta/metadata-provider+ (lib.tu.macros/mbql-5-query venues+ {:stages [{:aggregation [[:count {}]]+ :breakout [[:field {:temporal-unit :day} %price]]+ :parameters [{:hash "abc123"+ :name "foo"+ :type "id"+ ;; stage-number should get ignored by this+ ;; namespace; [[metabase.query-processor.middleware.parameters]] should decide+ ;; what to do with it.+ :target [:dimension [:field %name nil] {:stage-number 1000}]+ :value "Cam's Toucannery"}+ {:value "year"+ :type :temporal-unit+ :id "66cf9285"+ :target [:dimension+ [:field %price {:base-type :type/DateTime, :temporal-unit :day}]+ {:stage-number 1000}]}]}+ {:filters [[:>+ {}+ [:field {:base-type :type/Integer} "count"]+ 0]]+ :parameters [{:hash "def456"+ :name "bar"+ :type :number/<=+ :target [:dimension [:field "count" {:base-type :type/Integer}] {:stage-number 1}]+ :value [30]}]}]})))))))(deftest ^:parallel date-range-parameters-test(testing "date range parameters"(doseq [[value expected-filter-clause]- {"past30days" [:time-interval [:field (mt/id :users :last_login) nil] -30 :day {:include-current false}]- "past30days~" [:time-interval [:field (mt/id :users :last_login) nil] -30 :day {:include-current true}]+ {"past30days" [:time-interval [:field (meta/id :users :last-login) nil] -30 :day {:include-current false}]+ "past30days~" [:time-interval [:field (meta/id :users :last-login) nil] -30 :day {:include-current true}]"yesterday" [:=- [:field (mt/id :users :last_login) {:temporal-unit :day}]+ [:field (meta/id :users :last-login) {:temporal-unit :day}][:relative-datetime -1 :day]]- "2014-05-10~2014-05-16" [:between [:field (mt/id :users :last_login) {:temporal-unit :day}]+ "2014-05-10~2014-05-16" [:between [:field (meta/id :users :last-login) {:temporal-unit :day}]"2014-05-10""2014-05-16"]}](testing (format "value = %s" (pr-str value))- (is (= (expanded-query-with-filter expected-filter-clause)- (expand-parameters- (query-with-parameters- {:hash "abc123"- :name "foo"- :type :date- :target [:dimension [:field (mt/id :users :last_login) nil]]- :value value}))))))))+ (is (=? (expanded-query-with-filter expected-filter-clause)+ (expand-parameters+ (query-with-parameters+ {:hash "abc123"+ :name "foo"+ :type :date+ :target [:dimension [:field (meta/id :users :last-login) nil]]+ :value value}))))))))(deftest ^:parallel single-date-parameters-test(testing "absolute date parameters"(doseq [[value expected-filter-clause]- {"2014-05-10" [:= [:field (mt/id :users :last_login) {:temporal-unit :day}] "2014-05-10"]- "2014-05-10T09:30:00" [:= [:field (mt/id :users :last_login) {:temporal-unit :minute}]+ {"2014-05-10" [:= [:field (meta/id :users :last-login) {:temporal-unit :day}] "2014-05-10"]+ "2014-05-10T09:30:00" [:= [:field (meta/id :users :last-login) {:temporal-unit :minute}]"2014-05-10T09:30:00"]}](testing (format "value = %s" (pr-str value))- (is (= (expanded-query-with-filter expected-filter-clause)- (expand-parameters- (query-with-parameters- {:hash "abc123"- :name "foo"- :type :date/single- :target [:dimension [:field (mt/id :users :last_login) nil]]- :value value}))))))))+ (is (=? (expanded-query-with-filter expected-filter-clause)+ (expand-parameters+ (query-with-parameters+ {:hash "abc123"+ :name "foo"+ :type :date/single+ :target [:dimension [:field (meta/id :users :last-login) nil]]+ :value value}))))))));;; +----------------------------------------------------------------------------------------------------------------+;;; | END-TO-END TESTS |@@ -166,17 +194,17 @@#_{:clj-kondo/ignore [:metabase/disallow-hardcoded-driver-names-in-tests]}(when (= :snowflake driver/*driver*)(driver/notify-database-updated driver/*driver* (mt/id)))- (is (= [[29]]- (mt/formatted-rows- [int]- (qp/process-query- (mt/query checkins- {:query {:aggregation [[:count]]}- :parameters [{:hash "abc123"- :name "foo"- :type "date"- :target [:dimension $date]- :value "2015-04-01~2015-05-01"}]}))))))))+ (is (=? [[29]]+ (mt/formatted-rows+ [int]+ (qp/process-query+ (mt/query checkins+ {:query {:aggregation [[:count]]}+ :parameters [{:hash "abc123"+ :name "foo"+ :type "date"+ :target [:dimension $date]+ :value "2015-04-01~2015-05-01"}]}))))))))(deftest ^:parallel ids-e2e-test(mt/test-drivers (params-test-drivers)@@ -184,31 +212,31 @@(doseq [[message value] {"passed in as numbers" 100"passed in as strings" "100"}](testing message- (is (= [[1]]- (mt/formatted-rows- [int]- (qp/process-query- (mt/query checkins- {:query {:aggregation [[:count]]}- :parameters [{:hash "abc123"- :name "foo"- :type :number- :target [:dimension $id]- :value value}]}))))))))))+ (is (=? [[1]]+ (mt/formatted-rows+ [int]+ (qp/process-query+ (mt/query checkins+ {:query {:aggregation [[:count]]}+ :parameters [{:hash "abc123"+ :name "foo"+ :type :number+ :target [:dimension $id]+ :value value}]}))))))))))(deftest ^:parallel categories-e2e-test(mt/test-drivers (params-test-drivers)(testing "check that Categories work correctly (passed in as strings, as the frontend is wont to do; should get converted)"- (is (= [[6]]- (mt/formatted-rows- [int]- (qp/process-query- (mt/query venues- {:query {:aggregation [[:count]]}- :parameters [{:name "price"- :type :category- :target $price- :value "4"}]}))))))))+ (is (=? [[6]]+ (mt/formatted-rows+ [int]+ (qp/process-query+ (mt/query venues+ {:query {:aggregation [[:count]]}+ :parameters [{:name "price"+ :type :category+ :target $price+ :value "4"}]}))))))))(deftest ^:parallel operations-e2e-test(mt/test-drivers (params-test-drivers)@@ -217,13 +245,13 @@[int](qp/process-query %))](testing "binary numeric"- (is (= [[78]]- (f (mt/query venues- {:query {:aggregation [[:count]]}- :parameters [{:name "price"- :type :number/between- :target $price- :value [2 5]}]})))))))))+ (is (=? [[78]]+ (f (mt/query venues+ {:query {:aggregation [[:count]]}+ :parameters [{:name "price"+ :type :number/between+ :target $price+ :value [2 5]}]})))))))))(defmulti operations-e2e-test-2-expected-rows{:arglists '([driver])}@@ -247,57 +275,57 @@[int](qp/process-query %))](testing "unary string"- (is (= (operations-e2e-test-2-expected-rows driver/*driver*)- (f (mt/query venues- {:query {:aggregation [[:count]]}- :parameters [{:name "name"- :type :string/starts-with- :target $name- :value ["B"]}]})))))))))+ (is (=? (operations-e2e-test-2-expected-rows driver/*driver*)+ (f (mt/query venues+ {:query {:aggregation [[:count]]}+ :parameters [{:name "name"+ :type :string/starts-with+ :target $name+ :value ["B"]}]})))))))))(deftest ^:parallel basic-where-test(mt/test-drivers (params-test-drivers)(testing "test that we can inject a basic `WHERE field = value` type param"(testing "`:id` param type"- (is (= [[9 "Nils Gotam"]]- (mt/formatted-rows- [int str]- (qp/process-query- (mt/query users- {:parameters [{:name "id"- :type "id"- :target $id- :value 9}]})))))))))+ (is (=? [[9 "Nils Gotam"]]+ (mt/formatted-rows+ [int str]+ (qp/process-query+ (mt/query users+ {:parameters [{:name "id"+ :type "id"+ :target $id+ :value 9}]})))))))))(deftest ^:parallel basic-where-test-2(mt/test-drivers (params-test-drivers)(testing "test that we can inject a basic `WHERE field = value` type param"(testing "`:category` param type"- (is (= [[6]]- (mt/formatted-rows- [int]- (qp/process-query- (mt/query venues- {:query {:aggregation [[:count]]}- :parameters [{:name "price"- :type :category- :target $price- :value 4}]})))))))))+ (is (=? [[6]]+ (mt/formatted-rows+ [int]+ (qp/process-query+ (mt/query venues+ {:query {:aggregation [[:count]]}+ :parameters [{:name "price"+ :type :category+ :target $price+ :value 4}]})))))))))(deftest ^:parallel basic-where-test-3(mt/test-drivers (params-test-drivers)(testing "test that we can inject a basic `WHERE field = value` type param"(testing "`:number/>=` param type"- (is (= [[78]]- (mt/formatted-rows- [int]- (qp/process-query- (mt/query venues- {:query {:aggregation [[:count]]}- :parameters [{:name "price"- :type :number/>=- :target $price- :value [2]}]})))))))))+ (is (=? [[78]]+ (mt/formatted-rows+ [int]+ (qp/process-query+ (mt/query venues+ {:query {:aggregation [[:count]]}+ :parameters [{:name "price"+ :type :number/>=+ :target $price+ :value [2]}]})))))))));; Make sure that *multiple* values work. This feature was added in 0.28.0. You are now allowed to pass in an array of;; parameter values instead of a single value, which should stick them together in a single MBQL `:=` clause, which@@ -311,10 +339,10 @@:type :category:target $price:value [3 4]}]})]- (is (= [[19]]- (mt/formatted-rows- [int]- (qp/process-query query))))))))+ (is (=? [[19]]+ (mt/formatted-rows+ [int]+ (qp/process-query query))))))))(deftest ^:parallel multiple-values-test-2(testing "Make sure that *multiple* values work."@@ -323,17 +351,17 @@;; know the features are still working correctly because we're actually checking that we get the right result;; from running the query above these tests are more of a sanity check to make sure the SQL generated is sane.)(testing "Make sure correct query is generated"- (is (= {:query (str "SELECT COUNT(*) AS \"count\" "- "FROM \"PUBLIC\".\"VENUES\" "- "WHERE (\"PUBLIC\".\"VENUES\".\"PRICE\" = 3) OR (\"PUBLIC\".\"VENUES\".\"PRICE\" = 4)")- :params nil}- (qp.compile/compile- (mt/query venues- {:query {:aggregation [[:count]]}- :parameters [{:name "price"- :type :category- :target $price- :value [3 4]}]})))))))+ (is (=? {:query (str "SELECT COUNT(*) AS \"count\" "+ "FROM \"PUBLIC\".\"VENUES\" "+ "WHERE (\"PUBLIC\".\"VENUES\".\"PRICE\" = 3) OR (\"PUBLIC\".\"VENUES\".\"PRICE\" = 4)")+ :params nil}+ (qp.compile/compile+ (mt/query venues+ {:query {:aggregation [[:count]]}+ :parameters [{:name "price"+ :type :category+ :target $price+ :value [3 4]}]})))))))(deftest ^:parallel multiple-values-test-3(testing "Make sure multiple values with operators works"@@ -344,102 +372,105 @@:type :number/between:target $price:value [3 4]}]})]- (is (= [[19]]- (mt/formatted-rows- [int]- (qp/process-query query))))))))+ (is (=? [[19]]+ (mt/formatted-rows+ [int]+ (qp/process-query query))))))))(deftest ^:parallel multiple-values-test-4(testing "Make sure multiple values with operators works"(testing "Make sure correct query is generated"- (is (= {:query (str "SELECT COUNT(*) AS \"count\" "- "FROM \"PUBLIC\".\"VENUES\" "- "WHERE \"PUBLIC\".\"VENUES\".\"PRICE\" BETWEEN 3 AND 4")- :params nil}- (qp.compile/compile- (mt/query venues- {:query {:aggregation [[:count]]}- :parameters [{:name "price"- :type :number/between- :target $price- :value [3 4]}]})))))))+ (is (=? {:query (str "SELECT COUNT(*) AS \"count\" "+ "FROM \"PUBLIC\".\"VENUES\" "+ "WHERE \"PUBLIC\".\"VENUES\".\"PRICE\" BETWEEN 3 AND 4")+ :params nil}+ (qp.compile/compile+ (mt/query venues+ {:query {:aggregation [[:count]]}+ :parameters [{:name "price"+ :type :number/between+ :target $price+ :value [3 4]}]})))))));; try it with date params as well. Even though there's no way to do this in the frontend AFAIK there's no reason we;; can't handle it on the backend(deftest ^:parallel date-params-test- (is (= {:query ["SELECT"- " COUNT(*) AS \"count\""- "FROM"- " \"PUBLIC\".\"CHECKINS\""- "WHERE"- " \"PUBLIC\".\"CHECKINS\".\"DATE\" BETWEEN ? AND ?"- " OR \"PUBLIC\".\"CHECKINS\".\"DATE\" BETWEEN ? AND ?"]- :params [#t "2014-06-01"- #t "2014-06-30"- #t "2015-06-01"- #t "2015-06-30"]}- (-> (qp.compile/compile- (mt/query checkins- {:query {:aggregation [[:count]]}- :parameters [{:name "date"- :type "date/month-year"- :target $date- :value ["2014-06" "2015-06"]}]}))- (update :query #(str/split-lines (driver/prettify-native-form :h2 %)))))))+ (is (=? {:query ["SELECT"+ " COUNT(*) AS \"count\""+ "FROM"+ " \"PUBLIC\".\"CHECKINS\""+ "WHERE"+ " \"PUBLIC\".\"CHECKINS\".\"DATE\" BETWEEN ? AND ?"+ " OR \"PUBLIC\".\"CHECKINS\".\"DATE\" BETWEEN ? AND ?"]+ :params [#t "2014-06-01"+ #t "2014-06-30"+ #t "2015-06-01"+ #t "2015-06-30"]}+ (-> (qp.compile/compile+ (mt/query checkins+ {:query {:aggregation [[:count]]}+ :parameters [{:name "date"+ :type "date/month-year"+ :target $date+ :value ["2014-06" "2015-06"]}]}))+ (update :query #(str/split-lines (driver/prettify-native-form :h2 %)))))))(defn- build-filter-clause [query param]- (qp.store/with-metadata-provider (mt/id)- (#'qp.mbql/build-filter-clause query param)))+ (let [stage-path [:stages (dec (count (:stages query)))]]+ (#'qp.mbql/build-filter-clause query stage-path param)))(deftest ^:parallel convert-ids-to-numbers-test- (is (= (mt/$ids venues- [:= $id 1])- (build-filter-clause- nil- (mt/$ids venues- {:type :id- :target [:dimension $id]- :slug "venue_id"- :value "1"- :name "Venue ID"})))+ (is (=? (lib.tu.macros/$ids venues+ [:= {} [:field {} %id] 1])+ (build-filter-clause+ (lib/query meta/metadata-provider (meta/table-metadata :venues))+ (lib.tu.macros/$ids venues+ {:type :id+ :target [:dimension $id]+ :slug "venue_id"+ :value "1"+ :name "Venue ID"})))"make sure that :id type params get converted to numbers when appropriate"))(deftest ^:parallel handle-fk-forms-test(mt/test-drivers (params-test-drivers)- (qp.store/with-metadata-provider (mt/id)- (when (driver.u/supports? driver/*driver* :left-join (mt/db))- (testing "Make sure we properly handle paramters that have `fk->` forms in `:dimension` targets (#9017)"- (is (= [[31 "Bludso's BBQ" 5 33.8894 -118.207 2]- [32 "Boneyard Bistro" 5 34.1477 -118.428 3]- [33 "My Brother's Bar-B-Q" 5 34.167 -118.595 2]- [35 "Smoke City Market" 5 34.1661 -118.448 1]- [37 "bigmista's barbecue" 5 34.118 -118.26 2]- [38 "Zeke's Smokehouse" 5 34.2053 -118.226 2]- [39 "Baby Blues BBQ" 5 34.0003 -118.465 2]]- (mt/formatted-rows- :venues- (qp/process-query- (mt/query venues- {:query {:order-by [[:asc $id]]}- :parameters [{:type :id- :target [:dimension $category_id->categories.name]- :value ["BBQ"]}]}))))))- (testing "Operators work on fk"- (is (= [[31 "Bludso's BBQ" 5 33.8894 -118.207 2]- [32 "Boneyard Bistro" 5 34.1477 -118.428 3]- [33 "My Brother's Bar-B-Q" 5 34.167 -118.595 2]- [35 "Smoke City Market" 5 34.1661 -118.448 1]- [37 "bigmista's barbecue" 5 34.118 -118.26 2]- [38 "Zeke's Smokehouse" 5 34.2053 -118.226 2]- [39 "Baby Blues BBQ" 5 34.0003 -118.465 2]]- (mt/formatted-rows- :venues- (qp/process-query- (mt/query venues- {:query {:order-by [[:asc $id]]}- :parameters [{:type :string/starts-with- :target [:dimension $category_id->categories.name]- :value ["BB"]}]}))))))))))+ (when (driver.u/supports? driver/*driver* :left-join (mt/db))+ (testing "Make sure we properly handle paramters that have `fk->` forms in `:dimension` targets (#9017)"+ (is (=? [[31 "Bludso's BBQ" 5 33.8894 -118.207 2]+ [32 "Boneyard Bistro" 5 34.1477 -118.428 3]+ [33 "My Brother's Bar-B-Q" 5 34.167 -118.595 2]+ [35 "Smoke City Market" 5 34.1661 -118.448 1]+ [37 "bigmista's barbecue" 5 34.118 -118.26 2]+ [38 "Zeke's Smokehouse" 5 34.2053 -118.226 2]+ [39 "Baby Blues BBQ" 5 34.0003 -118.465 2]]+ (mt/formatted-rows+ :venues+ (qp/process-query+ (mt/query venues+ {:query {:order-by [[:asc $id]]}+ :parameters [{:type :id+ :target [:dimension $category_id->categories.name]+ :value ["BBQ"]}]})))))))))++(deftest ^:parallel handle-fk-forms-test-2+ (mt/test-drivers (params-test-drivers)+ (when (driver.u/supports? driver/*driver* :left-join (mt/db))+ (testing "Operators work on fk"+ (is (=? [[31 "Bludso's BBQ" 5 33.8894 -118.207 2]+ [32 "Boneyard Bistro" 5 34.1477 -118.428 3]+ [33 "My Brother's Bar-B-Q" 5 34.167 -118.595 2]+ [35 "Smoke City Market" 5 34.1661 -118.448 1]+ [37 "bigmista's barbecue" 5 34.118 -118.26 2]+ [38 "Zeke's Smokehouse" 5 34.2053 -118.226 2]+ [39 "Baby Blues BBQ" 5 34.0003 -118.465 2]]+ (mt/formatted-rows+ :venues+ (qp/process-query+ (mt/query venues+ {:query {:order-by [[:asc $id]]}+ :parameters [{:type :string/starts-with+ :target [:dimension $category_id->categories.name]+ :value ["BB"]}]})))))))))(deftest ^:parallel test-mbql-parameters(testing "Should be able to pass parameters in to an MBQL query"@@ -456,14 +487,14 @@(doseq [[price expected] {1 222 59}](testing (format ":value = %d" price)- (is (= expected- (venues-with-price {:value price})))))+ (is (=? expected+ (venues-with-price {:value price})))))(testing "Should use :default if :value is not specified"- (is (= 22- (venues-with-price {:default 1}))))+ (is (=? 22+ (venues-with-price {:default 1}))))(testing "Should prefer :value over :default"- (is (= 59- (venues-with-price {:default 1, :value 2})))))))+ (is (=? 59+ (venues-with-price {:default 1, :value 2})))))))(deftest ^:parallel time-granularity-parameters-test(testing "time granularity parameters should update the matching clause in the breakouts and order-by clauses"@@ -479,5 +510,5 @@{:parameters [{:type :temporal-unit:target [:dimension (by-unit :month)]:value :week}]})]- (is (= ["2016-04-30T00:00:00Z" "2016-04-24T00:00:00Z" 1]- (first (mt/rows (mt/process-query query))))))))+ (is (=? ["2016-04-30T00:00:00Z" "2016-04-24T00:00:00Z" 1]+ (first (mt/rows (mt/process-query query))))))))diff --git a/test/metabase/query_processor/middleware/parameters/native_test.clj b/test/metabase/query_processor/middleware/parameters/native_test.cljindex a72a95c791e..ac5d7adab45 100644--- a/test/metabase/query_processor/middleware/parameters/native_test.clj+++ b/test/metabase/query_processor/middleware/parameters/native_test.clj@@ -2,56 +2,67 @@(:require[clojure.test :refer :all][metabase.driver :as driver]+ [metabase.lib.core :as lib]+ [metabase.lib.test-metadata :as meta]+ [metabase.lib.test-util :as lib.tu]+ [metabase.lib.test-util.macros :as lib.tu.macros][metabase.query-processor.middleware.parameters.native :as qp.native][metabase.test :as mt]- [metabase.util :as u][metabase.util.malli.schema :as ms]))(deftest ^:parallel include-card-parameters-test(testing "Expanding a Card reference in a native query should include its parameters (#12236)"- (mt/dataset test-data- (mt/with-temp [:model/Card card {:dataset_query (mt/mbql-query orders- {:filter [:between $total 30 60]- :aggregation [[:aggregation-options- [:count-where [:starts-with $product_id->products.category "G"]]- {:name "G Monies", :display-name "G Monies"}]]- :breakout [!month.created_at]})}]- (let [card-tag (str "#" (u/the-id card))- query {:native (format "SELECT * FROM {{%s}}" card-tag)- :template-tags {card-tag- {:id "5aa37572-058f-14f6-179d-a158ad6c029d"- :name card-tag- :display-name card-tag- :type :card- :card-id (u/the-id card)}}}]- (mt/with-driver :h2- (mt/with-metadata-provider (mt/id)- (is (malli= [:map- [:native ms/NonBlankString]- [:params [:= ["G%"]]]]- (qp.native/expand-inner query))))))))))+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query (lib.tu.macros/mbql-query orders+ {:filter [:between $total 30 60]+ :aggregation [[:aggregation-options+ [:count-where [:starts-with $product-id->products.category "G"]]+ {:name "G Monies", :display-name "G Monies"}]]+ :breakout [!month.created-at]})}]})+ query (lib/query+ mp+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM {{#1}}"+ :template-tags {"#1" {:id "5aa37572-058f-14f6-179d-a158ad6c029d"+ :name "#1"+ :display-name "#1"+ :type :card+ :card-id 1}}}})]+ (mt/with-driver :h2+ (is (malli= [:map+ [:native ms/NonBlankString]+ [:params [:= ["G%"]]]]+ (qp.native/expand-stage mp (lib/query-stage query 0))))))))(deftest ^:parallel native-query-with-card-template-tag-include-referenced-card-ids-test(mt/test-drivers (mt/normal-drivers-with-feature :native-parameters :nested-queries :native-parameter-card-reference)(testing (str "Expanding a Card template tag should add the card ID(s) to"" `:query-permissions/referenced-card-ids`")- (mt/with-temp [:model/Card {card-1-id :id} {:collection_id nil- :dataset_query (mt/mbql-query venues {:limit 2})}- :model/Card {card-2-id :id} {:collection_id nil- :dataset_query (mt/native-query- {:query (mt/native-query-with-card-template-tag driver/*driver* "card")- :template-tags {"card" {:name "card"- :display-name "card"- :type :card- :card-id card-1-id}}})}]- (testing (format "Card 1 ID = %d, Card 2 ID = %d" card-1-id card-2-id)- ;; this SHOULD NOT include `card-1-id`, because Card 1 is only referenced indirectly; if you have permissions- ;; to run Card 2 that should be sufficient to run it even if it references Card 1 (see #15131)- (mt/with-metadata-provider (mt/id)- (is (=? {:query-permissions/referenced-card-ids #{Integer/MAX_VALUE card-2-id}}- (qp.native/expand-inner {:query (mt/native-query-with-card-template-tag driver/*driver* "card")- :template-tags {"card" {:name "card"- :display-name "card"- :type :card- :card-id card-2-id}}- :query-permissions/referenced-card-ids #{Integer/MAX_VALUE}})))))))))+ (let [mp (lib.tu/mock-metadata-provider+ (mt/metadata-provider)+ {:cards [{:id 1+ :collection-id nil+ :dataset-query (mt/mbql-query venues {:limit 2})}+ {:id 2+ :collection-id nil+ :dataset-query (mt/native-query+ {:query (mt/native-query-with-card-template-tag driver/*driver* "card")+ :template-tags {"card" {:name "card"+ :display-name "card"+ :type :card+ :card-id 1}}})}]})+ query (lib/query+ mp+ (mt/native-query {:query (mt/native-query-with-card-template-tag driver/*driver* "card")+ :template-tags {"card" {:name "card"+ :display-name "card"+ :type :card+ :card-id 2}}+ :query-permissions/referenced-card-ids #{Integer/MAX_VALUE}}))]+ ;; this SHOULD NOT include `1`, because Card 1 is only referenced indirectly; if you have permissions to run+ ;; Card 2 that should be sufficient to run it even if it references Card 1 (see #15131)+ (is (=? {:query-permissions/referenced-card-ids #{Integer/MAX_VALUE 2}}+ (qp.native/expand-stage mp (lib/query-stage query 0))))))))diff --git a/test/metabase/query_processor/middleware/parameters_test.clj b/test/metabase/query_processor/middleware/parameters_test.cljindex 0393a515dc9..561fb9c9ff4 100644--- a/test/metabase/query_processor/middleware/parameters_test.clj+++ b/test/metabase/query_processor/middleware/parameters_test.clj@@ -2,95 +2,71 @@"Testings to make sure the parameter substitution middleware works as expected. Even though the below tests areSQL-specific, they still confirm that the middleware itself is working correctly."(:require+ [clojure.string :as str][clojure.test :refer :all][metabase.driver :as driver][metabase.legacy-mbql.normalize :as mbql.normalize]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.lib.schema.common :as lib.schema.common][metabase.lib.test-metadata :as meta][metabase.lib.test-util :as lib.tu][metabase.lib.test-util.macros :as lib.tu.macros][metabase.query-processor.middleware.parameters :as parameters]- [metabase.query-processor.store :as qp.store]- [metabase.test :as mt])- (:import- (clojure.lang ExceptionInfo)))+ [metabase.query-processor.preprocess :as qp.preprocess]+ [metabase.test :as mt]))-(deftest ^:parallel move-top-level-params-to-inner-query-test- (is (= {:type :native- :native {:query "WOW", :parameters ["My Param"]}- :user-parameters ["My Param"]}- (#'parameters/move-top-level-params-to-inner-query- {:type :native, :native {:query "WOW"}, :parameters ["My Param"]})))- (testing "when top-level query is a model"- (testing "and there are parameters, wrap it up as a :source-query"- (is (= {:type :query- :query {:source-query {:source-table 5}- :parameters ["My Param"]}- :info {:metadata/model-metadata []}- :user-parameters ["My Param"]}- (#'parameters/move-top-level-params-to-inner-query- {:type :query- :query {:source-table 5}- :parameters ["My Param"]- :info {:metadata/model-metadata []}}))))- (testing "without parameters, leave the model at the top level"- (is (= {:type :query- :query {:source-table 5- :parameters ["My Param"]}- :user-parameters ["My Param"]}- (#'parameters/move-top-level-params-to-inner-query- {:type :query- :query {:source-table 5}- :parameters ["My Param"]}))))))+(defn- substitute-params+ ([query]+ (let [mp (or (:lib/metadata query)+ meta/metadata-provider)]+ (substitute-params mp query)))-(defn- substitute-params [query]- (letfn [(thunk []- (driver/with-driver :h2- (parameters/substitute-parameters (mbql.normalize/normalize query))))]- (driver/with-driver :h2- (if (qp.store/initialized?)- (thunk)- (qp.store/with-metadata-provider meta/metadata-provider- (thunk))))))+ ([metadata-provider query]+ (driver/with-driver :h2+ (if (:lib/type query)+ (parameters/substitute-parameters query)+ (-> (lib/query metadata-provider (mbql.normalize/normalize query))+ parameters/substitute-parameters+ lib/->legacy-MBQL)))))(deftest ^:parallel expand-mbql-top-level-params-test(testing "can we expand MBQL params if they are specified at the top level?"- (is (=? (mt/mbql-query venues+ (is (=? (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:filter [:= $price 1]})(substitute-params- (mt/mbql-query venues+ (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:parameters [{:name "price", :type :category, :target $price, :value 1}]}))))))(deftest ^:parallel expand-native-top-level-params-test(testing "can we expand native params if they are specified at the top level?"- (is (= (mt/query nil- {:type :native- :native {:query "SELECT * FROM venues WHERE price = 1;", :params []}- :user-parameters [{:type :category, :target [:variable [:template-tag "price"]], :value "1"}]})- (substitute-params- (mt/query nil- {:type :native- :native {:query "SELECT * FROM venues WHERE price = {{price}};"- :template-tags {"price" {:name "price", :display-name "Price", :type :number}}}- :parameters [{:type "category", :target [:variable [:template-tag "price"]], :value "1"}]}))))))+ (is (=? {:type :native+ :native {:query "SELECT * FROM venues WHERE price = 1;", :params []}+ :user-parameters [{:type :category, :target [:variable [:template-tag "price"]], :value "1"}]}+ (substitute-params+ {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM venues WHERE price = {{price}};"+ :template-tags {"price" {:name "price", :display-name "Price", :type :number}}}+ :parameters [{:type "category", :target [:variable [:template-tag "price"]], :value "1"}]})))))(deftest ^:parallel expand-mbql-source-query-params-test(testing "can we expand MBQL params in a source query?"- (is (=? (mt/mbql-query venues+ (is (=? (lib.tu.macros/mbql-query venues{:source-query {:source-table $$venues:filter [:= $price 1]}:aggregation [[:count]]})(substitute-params- (mt/mbql-query venues+ (lib.tu.macros/mbql-query venues{:source-query {:source-table $$venues:parameters [{:name "price", :type :category, :target $price, :value 1}]}:aggregation [[:count]]}))))))(deftest ^:parallel expand-mbql-source-query-date-expression-param-test(testing "can we expand MBQL number and date expression params in a source query?"- (is (=? (mt/mbql-query users+ (is (=? (lib.tu.macros/mbql-query users{:source-query {:source-table (meta/id :users):expressions {"date-column" [:field (meta/id :users :last-login) nil]"number-column" [:field (meta/id :users :id) nil]}@@ -98,7 +74,7 @@[:between [:expression "date-column"] "2019-09-29" "2023-09-29"][:= [:expression "number-column"] 1]]}})(substitute-params- (mt/mbql-query users+ (lib.tu.macros/mbql-query users{:source-query {:source-table (meta/id :users):expressions {"date-column" [:field (meta/id :users :last-login) nil]"number-column" [:field (meta/id :users :id) nil]}@@ -111,88 +87,88 @@(deftest ^:parallel expand-native-source-query-params-test(testing "can we expand native params if in a source query?"- (is (= (mt/mbql-query nil+ (is (= (lib.tu.macros/mbql-query nil{:source-query {:native "SELECT * FROM categories WHERE name = ?;":params ["BBQ"]}})(substitute-params- (mt/mbql-query nil+ (lib.tu.macros/mbql-query nil{:source-query {:native "SELECT * FROM categories WHERE name = {{cat}};":template-tags {"cat" {:name "cat", :display-name "Category", :type :text}}:parameters [{:type "category", :target [:variable [:template-tag "cat"]], :value "BBQ"}]}}))))))(deftest ^:parallel expand-mbql-join-params-test(testing "can we expand MBQL params in a JOIN?"- (is (=? (mt/mbql-query venues+ (is (=? (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:joins [{:source-query {:source-table $$categories:filter [:= $categories.name "BBQ"]}:alias "c"- :condition [:= $category_id &c.categories.id]}]})+ :condition [:= $category-id &c.categories.id]}]})(substitute-params- (mt/mbql-query venues+ (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:joins [{:source-table $$categories:alias "c"- :condition [:= $category_id &c.categories.id]+ :condition [:= $category-id &c.categories.id]:parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]}))))))(deftest ^:parallel expand-native-join-params-test(testing "can we expand native params in a JOIN?"- (is (=? (mt/mbql-query venues+ (is (=? (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:joins [{:source-query {:native "SELECT * FROM categories WHERE name = ?;":params ["BBQ"]}:alias "c"- :condition [:= $category_id &c.*categories.id]}]})+ :condition [:= $category-id &c.*categories.id]}]})(substitute-params- (mt/mbql-query venues+ (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:joins [{:source-query {:native "SELECT * FROM categories WHERE name = {{cat}};":template-tags {"cat" {:name "cat", :display-name "Category", :type :text}}:parameters [{:type "category", :target [:variable [:template-tag "cat"]], :value "BBQ"}]}:alias "c"- :condition [:= $category_id &c.*categories.id]}]}))))))+ :condition [:= $category-id &c.*categories.id]}]}))))))(deftest ^:parallel expand-multiple-mbql-params-test(testing "can we expand multiple sets of MBQL params?"(is (=?- (mt/mbql-query venues+ (lib.tu.macros/mbql-query venues{:source-query {:source-table $$venues:filter [:= $price 1]}:aggregation [[:count]]:joins [{:source-query {:source-table $$categories:filter [:= $categories.name "BBQ"]}:alias "c"- :condition [:= $category_id &c.categories.id]}]})+ :condition [:= $category-id &c.categories.id]}]})(substitute-params- (mt/mbql-query venues+ (lib.tu.macros/mbql-query venues{:source-query {:source-table $$venues:parameters [{:name "price", :type :category, :target $price, :value 1}]}:aggregation [[:count]]:joins [{:source-table $$categories:alias "c"- :condition [:= $category_id &c.categories.id]+ :condition [:= $category-id &c.categories.id]:parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]}))))))(deftest ^:parallel expand-multiple-mbql-params-in-joins-test;; (This is dumb. Hopefully no one is creating queries like this. The `:parameters` should go in the source query;; instead of in the join.)(testing "can we expand multiple sets of MBQL params with params in a join and the join's source query?"- (is (=? (mt/mbql-query venues+ (is (=? (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:joins [{:source-query {:source-table $$categories:filter [:and- [:= $categories.name "BBQ"]- [:= $categories.id 5]]}+ [:= $categories.id 5]+ [:= $categories.name "BBQ"]]}:alias "c"- :condition [:= $category_id &c.categories.id]}]})+ :condition [:= $category-id &c.categories.id]}]})(substitute-params- (mt/mbql-query venues+ (lib.tu.macros/mbql-query venues{:aggregation [[:count]]:joins [{:source-query {:source-table $$categories:parameters [{:name "id", :type :category, :target $categories.id, :value 5}]}:alias "c"- :condition [:= $category_id &c.categories.id]+ :condition [:= $category-id &c.categories.id]:parameters [{:type "category", :target $categories.name, :value "BBQ"}]}]}))))))(defn- card-template-tag@@ -222,93 +198,97 @@(deftest ^:parallel expand-multiple-referenced-cards-in-template-tags(testing "multiple sub-queries, referenced in template tags, are correctly substituted"- (qp.store/with-metadata-provider mock-native-query-cards-metadata-provider- (is (=? (native-query- {:query "SELECT COUNT(*) FROM (SELECT 1) AS c1, (SELECT 2) AS c2", :params []})- (substitute-params- (native-query- {:query (str "SELECT COUNT(*) FROM {{#" 1 "}} AS c1, {{#" 2 "}} AS c2")- :template-tags (card-template-tags [1 2])})))))))++ (is (=? (native-query+ {:query "SELECT COUNT(*) FROM (SELECT 1) AS c1, (SELECT 2) AS c2", :params []})+ (substitute-params+ mock-native-query-cards-metadata-provider+ (native-query+ {:query (str "SELECT COUNT(*) FROM {{#" 1 "}} AS c1, {{#" 2 "}} AS c2")+ :template-tags (card-template-tags [1 2])}))))))(deftest ^:parallel expand-multiple-referenced-cards-in-template-tags-2(testing "multiple CTE queries, referenced in template tags, are correctly substituted"- (qp.store/with-metadata-provider mock-native-query-cards-metadata-provider- (is (=? (native-query- {:query "WITH c1 AS (SELECT 1), c2 AS (SELECT 2) SELECT COUNT(*) FROM c1, c2", :params []})- (substitute-params- (native-query- {:query "WITH c1 AS {{#1}}, c2 AS {{#2}} SELECT COUNT(*) FROM c1, c2"- :template-tags (card-template-tags [1 2])})))))))+ (is (=? (native-query+ {:query "WITH c1 AS (SELECT 1), c2 AS (SELECT 2) SELECT COUNT(*) FROM c1, c2", :params []})+ (substitute-params+ mock-native-query-cards-metadata-provider+ (native-query+ {:query "WITH c1 AS {{#1}}, c2 AS {{#2}} SELECT COUNT(*) FROM c1, c2"+ :template-tags (card-template-tags [1 2])}))))))(deftest ^:parallel expand-multiple-referenced-cards-in-template-tags-3(testing "recursive native queries, referenced in template tags, are correctly substituted"- (qp.store/with-metadata-provider mock-native-query-cards-metadata-provider- (is (=? (native-query- {:query "SELECT COUNT(*) FROM (SELECT * FROM (SELECT 1) AS c1) AS c2", :params []})- (substitute-params- (native-query- {:query "SELECT COUNT(*) FROM {{#3}} AS c2"- :template-tags (card-template-tags [3])})))))))+ (is (=? (native-query+ {:query "SELECT COUNT(*) FROM (SELECT * FROM (SELECT 1) AS c1) AS c2", :params []})+ (substitute-params+ mock-native-query-cards-metadata-provider+ (native-query+ {:query "SELECT COUNT(*) FROM {{#3}} AS c2"+ :template-tags (card-template-tags [3])}))))))(deftest ^:parallel expand-multiple-referenced-cards-in-template-tags-4(testing "recursive native/MBQL queries, referenced in template tags, are correctly substituted"- (qp.store/with-metadata-provider (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [(lib.tu.macros/mbql-query venues)- (native-query- {:query "SELECT * FROM {{#1}} AS c1"- :template-tags (card-template-tags [1])})])- (let [card-1-subquery (str "SELECT "- "\"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\", "- "\"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\", "- "\"PUBLIC\".\"VENUES\".\"CATEGORY_ID\" AS \"CATEGORY_ID\", "- "\"PUBLIC\".\"VENUES\".\"LATITUDE\" AS \"LATITUDE\", "- "\"PUBLIC\".\"VENUES\".\"LONGITUDE\" AS \"LONGITUDE\", "- "\"PUBLIC\".\"VENUES\".\"PRICE\" AS \"PRICE\" "- "FROM \"PUBLIC\".\"VENUES\"")]- (is (=? (native-query- {:query (str "SELECT COUNT(*) FROM (SELECT * FROM (" card-1-subquery ") AS c1) AS c2") :params []})- (substitute-params- (native-query- {:query "SELECT COUNT(*) FROM {{#2}} AS c2"- :template-tags (card-template-tags [2])}))))))))+ (let [mp (lib.tu/metadata-provider-with-cards-for-queries+ meta/metadata-provider+ [(lib.tu.macros/mbql-query venues)+ (native-query+ {:query "SELECT * FROM {{#1}} AS c1"+ :template-tags (card-template-tags [1])})])+ card-1-subquery (str "SELECT "+ "\"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\", "+ "\"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\", "+ "\"PUBLIC\".\"VENUES\".\"CATEGORY_ID\" AS \"CATEGORY_ID\", "+ "\"PUBLIC\".\"VENUES\".\"LATITUDE\" AS \"LATITUDE\", "+ "\"PUBLIC\".\"VENUES\".\"LONGITUDE\" AS \"LONGITUDE\", "+ "\"PUBLIC\".\"VENUES\".\"PRICE\" AS \"PRICE\" "+ "FROM \"PUBLIC\".\"VENUES\"")]+ (is (=? (native-query+ {:query (str "SELECT COUNT(*) FROM (SELECT * FROM (" card-1-subquery ") AS c1) AS c2") :params []})+ (substitute-params+ mp+ (native-query+ {:query "SELECT COUNT(*) FROM {{#2}} AS c2"+ :template-tags (card-template-tags [2])})))))))(deftest ^:parallel referencing-cards-with-parameters-test(testing "referencing card with parameter and default value substitutes correctly"- (qp.store/with-metadata-provider (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [(native-query- {:query "SELECT {{x}}"- :template-tags {"x"- {:id "x"- :name "x"- :display-name "Number x"- :type :number- :default "1"- :required true}}})])+ (let [mp (lib.tu/metadata-provider-with-cards-for-queries+ meta/metadata-provider+ [(native-query+ {:query "SELECT {{x}}"+ :template-tags {"x"+ {:id "x"+ :name "x"+ :display-name "Number x"+ :type :number+ :default "1"+ :required true}}})])](is (=? (native-query{:query "SELECT * FROM (SELECT 1) AS x", :params []})(substitute-params+ mp(native-query{:query "SELECT * FROM {{#1}} AS x":template-tags (card-template-tags [1])})))))))(deftest ^:parallel referencing-cards-with-parameters-test-2(testing "referencing card with parameter and NO default value, fails substitution"- (qp.store/with-metadata-provider (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [(native-query- {:query "SELECT {{x}}"- :template-tags {"x"- {:id "x"- :name "x"- :display-name "Number x"- :type :number- :required true}}})])+ (let [mp (lib.tu/metadata-provider-with-cards-for-queries+ meta/metadata-provider+ [(native-query+ {:query "SELECT {{x}}"+ :template-tags {"x"+ {:id "x"+ :name "x"+ :display-name "Number x"+ :type :number+ :required true}}})])](is (thrown-with-msg?- ExceptionInfo+ clojure.lang.ExceptionInfo#"\QYou'll need to pick a value for 'Number x' before this query can run.\E"(substitute-params+ mp(native-query{:query "SELECT * FROM {{#1}} AS x":template-tags (card-template-tags [1])})))))))@@ -322,59 +302,207 @@:snippet-name snippet-name:snippet-id snippet-id}])))-(deftest expand-multiple-snippets-test- (mt/with-temp [:model/NativeQuerySnippet select-snippet {:content "name, price"- :creator_id (mt/user->id :rasta)- :description "Fields to SELECT"- :name "Venue fields"}- :model/NativeQuerySnippet where-snippet {:content "price > 2"- :creator_id (mt/user->id :rasta)- :description "Meant for use in WHERE clause"- :name "Filter: expensive venues"}- :model/Card card {:dataset_query- (mt/native-query- {:query (str "SELECT {{ Venue fields }} "- "FROM venues "- "WHERE {{ Filter: expensive venues }}")- :template-tags (snippet-template-tags- {"Venue fields" (:id select-snippet)- "Filter: expensive venues" (:id where-snippet)})})}]- (qp.store/with-metadata-provider (mt/id)- (testing "multiple snippets are correctly expanded in parent query"- (is (= (mt/native-query- {:query "SELECT name, price FROM venues WHERE price > 2", :params nil})- (substitute-params (:dataset_query card)))))- (testing "multiple snippets are expanded from saved sub-query"- (is (=? (mt/native-query- {:query "SELECT * FROM (SELECT name, price FROM venues WHERE price > 2) AS x", :params []})- (substitute-params- (mt/native-query- {:query (str "SELECT * FROM {{#" (:id card) "}} AS x")- :template-tags (card-template-tags [(:id card)])}))))))))+(deftest ^:parallel expand-multiple-snippets-test+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:native-query-snippets [{:id 1+ :content "name, price"+ :creator-id (mt/user->id :rasta)+ :description "Fields to SELECT"+ :name "Venue fields"}+ {:id 2+ :content "price > 2"+ :creator-id (mt/user->id :rasta)+ :description "Meant for use in WHERE clause"+ :name "Filter: expensive venues"}]+ :cards [{:id 1+ :dataset-query (mt/native-query+ {:query (str "SELECT {{ Venue fields }} "+ "FROM venues "+ "WHERE {{ Filter: expensive venues }}")+ :template-tags (snippet-template-tags+ {"Venue fields" 1+ "Filter: expensive venues" 2})})}]})]+ (testing "multiple snippets are correctly expanded in parent query"+ (is (=? {:native {:query "SELECT name, price FROM venues WHERE price > 2", :params nil}}+ (substitute-params mp (:dataset-query (lib.metadata/card mp 1))))))+ (testing "multiple snippets are expanded from saved sub-query"+ (is (=? {:native {:query "SELECT * FROM (SELECT name, price FROM venues WHERE price > 2) AS x", :params []}}+ (substitute-params+ mp+ (mt/native-query+ {:query "SELECT * FROM {{#1}} AS x"+ :template-tags (card-template-tags [1])})))))))(deftest ^:parallel include-card-parameters-test(testing "Expanding a Card reference should include its parameters (#12236)"- (qp.store/with-metadata-provider (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [(lib.tu.macros/mbql-query orders- {:filter [:between $total 30 60]- :aggregation [[:aggregation-options- [:count-where- [:starts-with $product-id->products.category "G"]]- {:name "G Monies", :display-name "G Monies"}]]- :breakout [!month.created-at]})])- (let [card-tag "#1"- query (native-query- {:query (format "SELECT * FROM {{%s}}" card-tag)- :template-tags {card-tag- {:id "5aa37572-058f-14f6-179d-a158ad6c029d"- :name card-tag- :display-name card-tag- :type :card- :card-id 1}}})]- (is (malli= [:map- [:native- [:map- [:query ::lib.schema.common/non-blank-string]- [:params [:= ["G%"]]]]]]- (substitute-params query)))))))+ (let [mp (lib.tu/metadata-provider-with-cards-for-queries+ meta/metadata-provider+ [(lib.tu.macros/mbql-query orders+ {:filter [:between $total 30 60]+ :aggregation [[:aggregation-options+ [:count-where+ [:starts-with $product-id->products.category "G"]]+ {:name "G Monies", :display-name "G Monies"}]]+ :breakout [!month.created-at]})])+ card-tag "#1"+ query (native-query+ {:query (format "SELECT * FROM {{%s}}" card-tag)+ :template-tags {card-tag+ {:id "5aa37572-058f-14f6-179d-a158ad6c029d"+ :name card-tag+ :display-name card-tag+ :type :card+ :card-id 1}}})]+ (is (malli= [:map+ [:native+ [:map+ [:query ::lib.schema.common/non-blank-string]+ [:params [:= ["G%"]]]]]]+ (substitute-params mp query))))))++;;; see also [[metabase.query-processor-test.parameters-test/filter-nested-queries-test]]+(deftest ^:parallel filter-nested-queries-test+ (testing "We should be able to apply filters explicitly targeting nested native stages (#48258)"+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query {:database (meta/id), :type :native, :native {:query "SELECT *"}}}]})+ query (assoc (mt/mbql-query nil+ {:source-table "card__1", :limit 5})+ :parameters [{:type :date/all-options+ :target [:dimension [:field "DATE" {:base-type :type/Date}]]+ :value "2014-01-06"}])+ query (assoc-in query [:parameters 0 :target 2 :stage-number] 0)]+ (is (=? {:parameters [{:target [:dimension [:field "DATE" {:base-type :type/Date}] {:stage-number 0}]+ :value "2014-01-06"}]}+ query))+ (is (=? {:query {:filter [:=+ [:field "DATE" {:base-type :type/Date, :temporal-unit :day}]+ "2014-01-06"]}}+ (substitute-params mp query))))))++(deftest ^:parallel stage-number-in-parameters-e2e-test+ (testing "We should be able to apply filters explicitly targeting nested native stages (#48258)"+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM checkins;"}}}]})+ query (lib/query+ mp+ (lib.tu.macros/mbql-5-query nil+ {:stages [{:source-card 1}]+ :parameters [{:type :date/all-options+ :target [:dimension [:field "DATE" {:base-type :type/Date}] {:stage-number 0}]+ :value "2014-01-06"}]}))]+ (is (=? {:stages [{:native "SELECT * FROM checkins;"}+ {:filters [[:=+ {}+ [:field {:temporal-unit :default} "DATE"]+ [:absolute-datetime {} #t "2014-01-06" :default]]]}]}+ (-> query+ qp.preprocess/preprocess+ lib/->pMBQL))))))++(deftest ^:parallel nil-values-test+ (let [mp meta/metadata-provider+ query (lib/query+ mp+ {:constraints {:max-results 10000, :max-results-bare-rows 2000}+ :lib/type :mbql/query+ :stages [{:lib/type :mbql.stage/native+ :template-tags {"equal" {:id "197c0532-e2f8-24be-8d71-757369d3a75f"+ :name "equal"+ :display-name "Equal to"+ :type :dimension+ :dimension [:field+ {:lib/uuid "1b435d67-0cb2-4f4d-bac5-d06b60be4eca"+ :base-type :type/Float+ :effective-type :type/Float}+ (meta/id :products :rating)]+ :widget-type :number/=+ :default nil}+ "notEqual" {:id "827ca517-e493-397f-971c-1a2d2f12d5f1"+ :name "notEqual"+ :display-name "Not equal to"+ :type :dimension+ :dimension [:field+ {:lib/uuid "c0ff814c-e0df-4e50-9e29-0c61f0bd2b3b"+ :base-type :type/Float+ :effective-type :type/Float}+ (meta/id :products :rating)]+ :widget-type :number/!=+ :default nil}+ "between" {:id "6a3d9a46-671b-dee3-2971-fc180d27adfd"+ :name "between"+ :display-name "Between"+ :type :dimension+ :dimension [:field+ {:lib/uuid "c752de3e-e528-45ee-a8cc-687ce9329019"+ :base-type :type/Float+ :effective-type :type/Float}+ (meta/id :products :rating)]+ :widget-type :number/between+ :default nil}}+ :native (str/join \space ["select PRODUCTS.TITLE, PRODUCTS.RATING from PRODUCTS where true"+ "[[AND {{equal}}]]"+ "[[AND {{notEqual}}]]"+ "[[AND {{between}}]]"])}]+ :database (meta/id)+ :parameters [{:value [3.8], :type :number/=, :id "a57c8ec6", :target [:dimension [:template-tag "equal"] {"stage-number" 0}]}+ {:value nil, :type :number/!=, :id "5da85a8c", :target [:dimension [:template-tag "notEqual"] {"stage-number" 0}]}+ {:value [nil], :type :number/<=, :id "6b9e7189", :target [:dimension [:template-tag "between"] {"stage-number" 0}]}]})]+ (is (=? {:stages [{:lib/type :mbql.stage/native+ :params []+ :native (str "select PRODUCTS.TITLE, PRODUCTS.RATING"+ " from PRODUCTS"+ " where true AND (\"PUBLIC\".\"PRODUCTS\".\"RATING\" = 3.8)")}]}+ (-> query+ qp.preprocess/preprocess+ lib/->pMBQL)))))++(deftest ^:parallel ignore-template-tag-parameters-in-mbql-stages-test+ (let [query {:lib/type :mbql/query+ :lib/metadata meta/metadata-provider+ :database (meta/id)+ :stages [{:lib/type :mbql.stage/mbql+ :source-table (meta/id :venues)+ :qp/stage-is-from-source-card 1}+ {:lib/type :mbql.stage/mbql+ :qp/stage-had-source-card 1}]+ ;; dangling `template-tag` parameters can happen if you replace a source card that had a native query+ ;; with an MBQL one... we should just ignore these.+ :parameters [{:id "13ebc3b6"+ :target [:dimension [:template-tag "RATING"] {:stage-number 0}]+ :type :number/=+ :value [3]}]}]+ (is (=? {:stages [{:parameters (symbol "nil #_\"key is not present.\"")}+ {:parameters (symbol "nil #_\"key is not present.\"")}]}+ (substitute-params query)))))++(deftest ^:parallel expression-parameter-test+ (let [query {:lib/metadata meta/metadata-provider+ :lib/type :mbql/query+ :database (meta/id)+ :stages [{:lib/type :mbql.stage/mbql+ :source-table (meta/id :orders)+ :expressions [[:field+ {:base-type :type/Integer+ :effective-type :type/Integer+ :lib/expression-name "Quantity_2"+ :lib/uuid "a9212400-3b5f-4034-b7a0-f8848579af30"+ :metabase.lib.query/transformation-added-base-type true}+ (meta/id :orders :quantity)]]}]+ :parameters [{:id "c77842b9"+ :target [:dimension+ [:expression "Quantity_2" {:base-type :type/Integer}]+ {:stage-number 0}]+ :type :number/=+ :value [14]}]}]+ (is (=? {:stages [{:filters [[:=+ {}+ [:expression {} "Quantity_2"]+ 14]]}]}+ (substitute-params query)))))diff --git a/test/metabase/query_processor/parameters/parse_test.clj b/test/metabase/query_processor/parameters/parse_test.cljdeleted file mode 100644index 9bb063ea777..00000000000--- a/test/metabase/query_processor/parameters/parse_test.clj+++ /dev/null@@ -1,154 +0,0 @@-(ns metabase.query-processor.parameters.parse-test- (:require- [clojure.test :refer :all]- [metabase.lib.parse :as lib.parse]- [metabase.query-processor.parameters :as params]- [metabase.query-processor.parameters.parse :as params.parse]))--(defn- param [field-name] (params/param {:k field-name}))-(defn- optional [& args] (params/optional {:args (vec args)}))--(defn- normalize-tokens- [tokens]- (for [token tokens]- (or (:token token) token)))--(deftest ^:parallel tokenize-test- (doseq [[query expected]- {"{{num_toucans}}"- [:param-begin "num_toucans" :param-end]-- "[[AND num_toucans > {{num_toucans}}]]"- [:optional-begin "AND num_toucans > " :param-begin "num_toucans" :param-end :optional-end]-- "}}{{]][["- [:param-end :param-begin :optional-end :optional-begin]-- "SELECT * FROM toucanneries WHERE TRUE [[AND num_toucans > {{num_toucans}}]]"- ["SELECT * FROM toucanneries WHERE TRUE " :optional-begin "AND num_toucans > " :param-begin "num_toucans" :param-end :optional-end]-- "SELECT * FROM toucanneries WHERE TRUE [[AND num_toucans > {{num_toucans}}]] [[AND total_birds > {{total_birds}}]]"- ["SELECT * FROM toucanneries WHERE TRUE " :optional-begin "AND num_toucans > " :param-begin "num_toucans" :param-end :optional-end- " " :optional-begin "AND total_birds > " :param-begin "total_birds" :param-end :optional-end]-- "SELECT * FROM -- {{foo}}\n" ["SELECT * FROM " :line-comment-begin " " :param-begin "foo" :param-end :newline]-- "/*SELECT {{foo}}*/" [:block-comment-begin "SELECT " :param-begin "foo" :param-end :block-comment-end]}]- (is (= expected- (normalize-tokens (#'lib.parse/tokenize query true)))- (format "%s should get tokenized to %s" (pr-str query) (pr-str expected)))))--(deftest ^:parallel tokenize-no-sql-comments-test- (doseq [[query expected]- {"-- {{num_toucans}}"- ["-- " :param-begin "num_toucans" :param-end]-- "/* [[AND num_toucans > {{num_toucans}} --]] */"- ["/* " :optional-begin "AND num_toucans > " :param-begin "num_toucans" :param-end " --" :optional-end " */"]}]- (is (= expected- (normalize-tokens (#'lib.parse/tokenize query false)))- (format "%s should get tokenized to %s" (pr-str query) (pr-str expected)))))--(deftest ^:parallel parse-test- (doseq [[group s->expected]- {"queries with one param"- {"select * from foo where bar=1" ["select * from foo where bar=1"]- "select * from foo where bar={{baz}}" ["select * from foo where bar=" (param "baz")]- "select * from foo [[where bar = {{baz}} ]]" ["select * from foo " (optional "where bar = " (param "baz") " ")]}-- "multiple params"- {"SELECT * FROM bird_facts WHERE toucans_are_cool = {{toucans_are_cool}} AND bird_type = {{bird_type}}"- ["SELECT * FROM bird_facts WHERE toucans_are_cool = " (param "toucans_are_cool")- " AND bird_type = " (param "bird_type")]}-- "Multiple optional clauses"- {(str "select * from foo where bar1 = {{baz}} "- "[[and bar2 = {{baz}}]] "- "[[and bar3 = {{baz}}]] "- "[[and bar4 = {{baz}}]]")- ["select * from foo where bar1 = " (param "baz") " "- (optional "and bar2 = " (param "baz")) " "- (optional "and bar3 = " (param "baz")) " "- (optional "and bar4 = " (param "baz"))]-- "SELECT * FROM toucanneries WHERE TRUE [[AND num_toucans > {{num_toucans}}]] [[AND total_birds > {{total_birds}}]]"- ["SELECT * FROM toucanneries WHERE TRUE "- (optional "AND num_toucans > " (param "num_toucans"))- " "- (optional "AND total_birds > " (param "total_birds"))]-- "select * from foobars [[ where foobars.id in (string_to_array({{foobar_id}}, ',')::integer[]) ]]"- ["select * from foobars "- (optional " where foobars.id in (string_to_array(" (param "foobar_id") ", ',')::integer[]) ")]}-- "single square brackets shouldn't get parsed"- (let [query (str "SELECT [test_data.checkins.venue_id] AS [venue_id], "- " [test_data.checkins.user_id] AS [user_id], "- " [test_data.checkins.id] AS [checkins_id] "- "FROM [test_data.checkins] "- "LIMIT 2")]- {query [query]})-- "Valid syntax in PG -- shouldn't get parsed"- (let [query "SELECT array_dims(1 || '[0:1]={2,3}'::int[])"]- {query [query]})-- "Queries with newlines (#11526)"- {"SELECT count(*)\nFROM products\nWHERE category = {{category}}"- ["SELECT count(*)\nFROM products\nWHERE category = " (param "category")]}-- "Queries with params in SQL comments (#7742)"- {"SELECT -- {{foo}}" ["SELECT -- {{foo}}"]- "[[{{this}} -- and]] that" [(optional (param "this") " -- and") " that"]- "SELECT /* \n --{{foo}} */ {{bar}}" ["SELECT /* \n --{{foo}} */ " (param "bar")]}-- "JSON queries that contain non-param fragments like '}}'"- {"{x: {y: \"{{param}}\"}}" ["{x: {y: \"" (param "param") "\"}}"]- "{$match: {{{date}}, field: 1}}}" ["{$match: {" (param "date") ", field: 1}}}"]}-- "Queries that contain non-param fragments like '}}'"- {"select ']]' from t [[where x = {{foo}}]]" ["select ']]' from t " (optional "where x = " (param "foo"))]- "select '}}' from t [[where x = {{foo}}]]" ["select '}}' from t " (optional "where x = " (param "foo"))]}}]- (testing group- (doseq [[s expected] s->expected]- (is (= expected- (normalize-tokens (params.parse/parse s)))- (format "%s should get parsed to %s" (pr-str s) (pr-str expected))))))-- (testing "Testing that invalid/unterminated template params/clauses throw an exception"- (doseq [invalid ["select * from foo [[where bar = {{baz}} "- "select * from foo [[where bar = {{baz]]"- "select * from foo {{bar}} {{baz"- "select * from foo [[clause 1 {{bar}}]] [[clause 2"- "select * from foo where bar = {{baz]]"- "select * from foo [[where bar = {{baz}}}}"]]- (is (thrown? clojure.lang.ExceptionInfo- (params.parse/parse invalid))- (format "Parsing %s should throw an exception" (pr-str invalid))))))--(deftest ^:parallel disable-comment-handling-test- (testing "SQL comments are ignored when handle-sql-comments = false, e.g. in Mongo driver queries"- (doseq [[query result] [["{{{foo}}: -- {{bar}}}"- ["{" (param "foo") ": -- " (param "bar") "}"]]-- ["{{{foo}}: \"/* {{bar}} */\"}"- ["{" (param "foo") ": \"/* " (param "bar") " */\"}"]]]]- (is (= result (normalize-tokens (params.parse/parse query false)))))))--(deftest ^:parallel tokens-in-strings-test- (testing "skip malformed parameter tokens in strings"- (is (= ["'{{'"] (params.parse/parse "'{{'")))- (is (= ["'{{"] (params.parse/parse "'{{")))- (is (= ["'{{}}'"] (params.parse/parse "'{{}}'")))- (is (= ["'[['"] (params.parse/parse "'[['")))- (is (= ["'[[]]'"] (params.parse/parse "'[[]]'")))- (is (= ["'[[{{]]'"] (params.parse/parse "'[[{{]]'"))))- (testing "Parse well-formed tokens in strings"- (is (= ["'" (param "x") "'"] (params.parse/parse "'{{x}}'")))- (is (= ["'" (param "snippet: 'test'") "'"] (params.parse/parse "'{{snippet: 'test'}}'")))- (is (= ["'{{" (param "x") "'"] (params.parse/parse "'{{{{x}}'")))- (is (= ["'[[" (param "x") "'"] (params.parse/parse "'[[{{x}}'")))- (is (= ["'" (optional (param "x")) "'"] (params.parse/parse "'[[{{x}}]]'"))))- (testing "skip comment start in strings"- (is (= ["concat('--'," (param "x") ")"] (params.parse/parse "concat('--',{{x}})")))- (is (= ["concat('/*'," (param "x") ")"] (params.parse/parse "concat('/*',{{x}})")))))diff --git a/test/metabase/query_processor/parameters/values_test.clj b/test/metabase/query_processor/parameters/values_test.cljdeleted file mode 100644index 8a3e70690a0..00000000000--- a/test/metabase/query_processor/parameters/values_test.clj+++ /dev/null@@ -1,887 +0,0 @@-(ns metabase.query-processor.parameters.values-test- (:require- [clojure.java.jdbc :as jdbc]- [clojure.string :as str]- [clojure.test :refer :all]- [metabase.driver :as driver]- [metabase.driver.ddl.interface :as ddl.i]- [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]- [metabase.lib.core :as lib]- [metabase.lib.metadata :as lib.metadata]- [metabase.lib.test-metadata :as meta]- [metabase.lib.test-util :as lib.tu]- [metabase.lib.test-util.macros :as lib.tu.macros]- [metabase.permissions.models.data-permissions :as data-perms]- [metabase.permissions.models.permissions :as perms]- [metabase.permissions.models.permissions-group :as perms-group]- [metabase.query-processor :as qp]- [metabase.query-processor.middleware.permissions :as qp.perms]- [metabase.query-processor.parameters :as params]- [metabase.query-processor.parameters.values :as params.values]- [metabase.system.core :as system]- [metabase.test :as mt]- [metabase.util :as u]- [toucan2.core :as t2]))--(def ^:private test-uuid "00000000-0000-0000-0000-000000000000")--(defn- value-for-tag- "Call the private function and de-recordize the field"- ([field-info info]- (value-for-tag meta/metadata-provider field-info info))-- ([metadata-providerable field-info info]- (#'params.values/value-for-tag metadata-providerable field-info info)))--(deftest ^:parallel variable-value-test- (testing "Specified value, targeted by name"- (is (= "2"- (value-for-tag- {:name "id", :display-name "ID", :type :text, :required true, :default "100"}- [{:type :category, :target [:variable [:template-tag "id"]], :value "2"}])))))--(deftest ^:parallel variable-value-test-2- (testing "Specified value, targeted by ID"- (is (= "2"- (value-for-tag- {:name "id", :id test-uuid, :display-name "ID", :type :text, :required true, :default "100"}- [{:type :category, :target [:variable [:template-tag {:id test-uuid}]], :value "2"}])))))--(deftest ^:parallel variable-value-test-3- (testing "Multiple values with new operators"- (is (= 20- (value-for-tag- {:name "number_filter", :display-name "ID", :type :number, :required true, :default "100"}- [{:type :number/=, :value ["20"], :target [:variable [:template-tag "number_filter"]]}])))- (is (= [20 40]- (value-for-tag- {:name "number_filter", :display-name "ID", :type :number, :required true, :default "100"}- [{:type :number/=, :value ["20" "40"], :target [:variable [:template-tag "number_filter"]]}])))))--(deftest ^:parallel variable-value-test-4- (testing "Unspecified value"- (is (= params/no-value- (value-for-tag {:name "id", :display-name "ID", :type :text} nil)))))--(deftest ^:parallel variable-value-test-5- (testing "Unspecified value when required"- (is (thrown?- Exception- (value-for-tag {:name "id", :display-name "ID", :required true, :type :text} nil)))))--(deftest ^:parallel variable-value-test-6- (testing "Empty value when required"- (is (thrown?- Exception- (value-for-tag- {:name "id", :id test-uuid, :display-name "ID", :required true, :type :text}- [{:type :category, :target [:variable [:template-tag {:id test-uuid}]], :value nil}])))))--(deftest ^:parallel variable-value-test-7- (testing "Default used with unspecified value"- (is (= "100"- (value-for-tag- {:name "id", :display-name "ID", :type :text, :required true, :default "100"} nil)))))--(deftest ^:parallel variable-value-test-8- (testing "Default not used with empty value"- (is (= params/no-value- (value-for-tag- {:name "id", :id test-uuid, :display-name "ID", :type :text, :default "100"}- [{:type :category, :target [:variable [:template-tag {:id test-uuid}]], :value nil}])))))--(deftest ^:parallel variable-value-test-9- (testing "Default used with empty value when required"- (is (= "100"- (value-for-tag- {:name "id", :id test-uuid, :display-name "ID", :type :text, :required true, :default "100"}- [{:type :category, :target [:variable [:template-tag {:id test-uuid}]], :value nil}])))))--(deftest ^:parallel variable-value-test-10- (testing "BigInteger value"- (is (= 9223372036854775808- (value-for-tag- {:name "id", :id test-uuid, :display-name "ID", :type :number}- [{:type :category, :target [:variable [:template-tag {:id test-uuid}]], :value "9223372036854775808"}])))))--(defn- extra-field-info- "Add extra field information like `:coercion-strategy`, `:semantic-type`, and `:effective-type`."- ([field]- (extra-field-info meta/metadata-provider field))-- ([metadata-providerable field]- (merge (lib.metadata/field metadata-providerable (u/the-id field)) field)))--(defn- parse-tag- ([field-info info]- (parse-tag meta/metadata-provider field-info info))-- ([metadata-providerable field-info info]- (#'params.values/parse-tag metadata-providerable field-info info)))--(deftest ^:parallel field-filter-date-range-targeted-by-name-test- (testing "date range for a normal :type/Temporal field, targeted by name"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :date)- :name "DATE"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/Date- :semantic-type nil})- :value {:type :date/range- :value "2015-04-01~2015-05-01"}}- (value-for-tag- {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]- :widget-type :date/all-options}- [{:type :date/range- :target [:dimension [:template-tag "checkin_date"]]- :value "2015-04-01~2015-05-01"}])))))--(deftest ^:parallel field-filter-date-range-targeted-by-id-test- (testing "date range for a normal :type/Temporal field, targeted by id"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :date)- :name "DATE"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/Date- :semantic-type nil})- :value {:type :date/range- :value "2015-04-01~2015-05-01"}}- (value-for-tag- {:name "checkin_date"- :id test-uuid- :display-name "Checkin Date"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]- :widget-type :date/all-options}- [{:type :date/range- :target [:dimension [:template-tag {:id test-uuid}]]- :value "2015-04-01~2015-05-01"}])))))--(deftest ^:parallel field-filter-date-range-for-unix-timestamp-test- (testing "date range for a UNIX timestamp field should work just like a :type/Temporal field (#11934)"- (mt/dataset tupac-sightings- (mt/$ids sightings- (is (=? {:field (extra-field-info- (mt/application-database-metadata-provider (mt/id))- {:id %timestamp- :name "TIMESTAMP"- :parent-id nil- :table-id $$sightings- :base-type :type/BigInteger- :effective-type :type/Instant- :coercion-strategy :Coercion/UNIXSeconds->DateTime})- :value {:type :date/range- :value "2020-02-01~2020-02-29"}}- (value-for-tag- (mt/application-database-metadata-provider (mt/id))- {:name "timestamp"- :display-name "Sighting Timestamp"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} %timestamp]- :widget-type :date/range}- [{:type :date/range- :target [:dimension [:template-tag "timestamp"]]- :value "2020-02-01~2020-02-29"}])))))))--(deftest ^:parallel field-filter-with-unspecified-value-test- (testing "unspecified"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :date)- :name "DATE"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/Date- :semantic-type nil})- :value params/no-value}- (value-for-tag- {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :widget-type :date/all-options- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]}- nil)))))--(deftest ^:parallel field-filter-id-requiring-parsing-test- (testing "id requiring parsing"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :id)- :name "ID"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/BigInteger- :semantic-type :type/PK})- :value {:type :id- :value 5}}- (value-for-tag- {:name "id"- :display-name "ID"- :type :dimension- :widget-type :number- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :id)]}- [{:type :id, :target [:dimension [:template-tag "id"]], :value "5"}])))))--(deftest ^:parallel field-filter-with-required-but-no-value-test- (testing "required but unspecified"- (is (thrown?- Exception- (value-for-tag- {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :widget-type :date/all-options- :required true- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]}- nil)))))--(deftest ^:parallel field-filter-with-required-and-default-test- (testing "required and default specified"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :date)- :name "DATE"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/Date- :semantic-type nil})- :value {:type :date/range- :value "2015-04-01~2015-05-01"}}- (value-for-tag- {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :widget-type :date/range- :required true- :default "2015-04-01~2015-05-01"- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]}- nil)))))--(deftest ^:parallel field-filter-multiple-values-for-same-tag-test- (testing "multiple values for the same tag should return a vector with multiple params instead of a single param"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :date)- :name "DATE"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/Date- :semantic-type nil})- :value [{:type :date/range- :value "2015-01-01~2016-09-01"}- {:type :date/single- :value "2015-07-01"}]}- (value-for-tag- {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :widget-type :date/all-options- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]}- [{:type :date/range- :target [:dimension [:template-tag "checkin_date"]]- :value "2015-01-01~2016-09-01"}- {:type :date/single- :target [:dimension [:template-tag "checkin_date"]]- :value "2015-07-01"}])))))--(deftest ^:parallel field-filter-default-values-test- (testing "Make sure defaults values get picked up for field filter clauses"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :date)- :name "DATE"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/Date- :semantic-type nil})- :value {:type :date/all-options- :value "past5days"}}- (parse-tag- {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]- :default "past5days"- :widget-type :date/all-options}- nil)))))--(deftest ^:parallel field-filter-nil-values-test- (testing "Make sure nil values result in no value"- (is (=? {:field (extra-field-info- {:id (meta/id :checkins :date)- :name "DATE"- :parent-id nil- :table-id (meta/id :checkins)- :base-type :type/Date- :effective-type :type/Date})- :value params/no-value}- (parse-tag- {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]- :widget-type :date/all-options}- nil)))))--(deftest ^:parallel field-filter-errors-test- (testing "error conditions for field filter (:dimension) parameters"- (testing "Should throw an exception if Field does not exist"- (let [query (-> (lib/native-query meta/metadata-provider "SELECT * FROM table WHERE {{x}}")- (lib/update-query-stage- 0 assoc :template-tags- {"x" {:name "x"- :display-name "X"- :type :dimension- :widget-type :date/all-options- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} Integer/MAX_VALUE]}}))]- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"\QCan't find field with ID\E"- (params.values/stage->params-map query -1)))))))--(deftest ^:parallel card-query-test- (mt/with-test-user :rasta- (testing "Card query template tag gets card's native query"- (let [test-query "SELECT 1"- mp (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [{:database (meta/id)- :type "native"- :native {:query test-query}}])]- (is (=? {:card-id 1, :query test-query}- (value-for-tag- mp- {:name "card-template-tag-test"- :display-name "Card template tag test"- :type :card- :card-id 1}- [])))))))--(deftest ^:parallel card-query-test-2- (mt/with-test-user :rasta- (testing "Card query template tag generates native query for MBQL query"- (driver/with-driver :h2- (let [mbql-query (lib.tu.macros/mbql-query venues- {:database (meta/id)- :filter [:< [:field $price nil] 3]})- expected-sql (str "SELECT "- "\"PUBLIC\".\"VENUES\".\"ID\" AS \"ID\", "- "\"PUBLIC\".\"VENUES\".\"NAME\" AS \"NAME\", "- "\"PUBLIC\".\"VENUES\".\"CATEGORY_ID\" AS \"CATEGORY_ID\", "- "\"PUBLIC\".\"VENUES\".\"LATITUDE\" AS \"LATITUDE\", "- "\"PUBLIC\".\"VENUES\".\"LONGITUDE\" AS \"LONGITUDE\", "- "\"PUBLIC\".\"VENUES\".\"PRICE\" AS \"PRICE\" "- "FROM \"PUBLIC\".\"VENUES\" "- "WHERE \"PUBLIC\".\"VENUES\".\"PRICE\" < 3")- mp (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [mbql-query])]- (is (=? {:card-id 1, :query expected-sql, :params nil}- (value-for-tag- mp- {:name "card-template-tag-test"- :display-name "Card template tag test"- :type :card- :card-id 1}- []))))))))--(deftest card-query-test-3- (mt/with-test-user :rasta- (testing "Persisted Models are substituted"- ;; legacy test -- don't hardcode driver names in new tests going forward.- #_{:clj-kondo/ignore [:metabase/disallow-hardcoded-driver-names-in-tests]}- (mt/test-driver :postgres- ;; TODO (Cam 7/16/25) -- rework this to use metadata providers -- we support model persisted info directly from- ;; the metadata provider- (mt/with-persistence-enabled! [persist-models!]- (let [mbql-query (mt/mbql-query categories)]- (mt/with-temp [:model/Card model {:name "model"- :type :model- :dataset_query mbql-query- :database_id (mt/id)}]- (persist-models!)- (testing "tag uses persisted table"- (let [pi (t2/select-one :model/PersistedInfo :card_id (u/the-id model))]- (is (= "persisted" (:state pi)))- (is (re-matches #"select \* from \"metabase_cache_[a-z0-9]+_[0-9]+\".\"model_[0-9]+_model\""- (:query- (value-for-tag- (mt/application-database-metadata-provider (mt/id))- {:name "card-template-tag-test"- :display-name "Card template tag test"- :type :card- :card-id (:id model)}- []))))- (testing "query hits persisted table"- (let [persisted-schema (ddl.i/schema-name {:id (mt/id)}- (system/site-uuid))- update-query (format "update %s.%s set name = name || ' from cached table'"- persisted-schema (:table_name pi))- model-query (format "select c_orig.name, c_cached.name- from categories c_orig- left join {{#%d}} c_cached- on c_orig.id = c_cached.id- order by c_orig.id desc limit 3"- (u/the-id model))- tag-name (format "#%d" (u/the-id model))]- (jdbc/execute! (sql-jdbc.conn/db->pooled-connection-spec (mt/db))- [update-query])- (is (= [["Winery" "Winery from cached table"]- ["Wine Bar" "Wine Bar from cached table"]- ["Vegetarian / Vegan" "Vegetarian / Vegan from cached table"]]- (mt/rows (qp/process-query- {:database (mt/id)- :type :native- :native {:query model-query- :template-tags- {(keyword tag-name)- {:id "c6558da4-95b0-d829-edb6-45be1ee10d3c"- :name tag-name- :display-name tag-name- :type "card"- :card-id (u/the-id model)}}}})))))))))))))))--(deftest ^:parallel card-query-test-4- (mt/with-test-user :rasta- (testing "Card query template tag wraps error in tag details"- (let [mp (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [{:type :native- :native {:query "SELECT {{x}}"- :template-tags {"x" {:id "x-tag"- :name "x"- :display-name "Number x"- :type :number- :required false}}}- :database (meta/id)}- {:type :native- :native {:query "SELECT * FROM {{#1}} AS y"- :template-tags {"#1" {:id "#1"- :name "#1"- :display-name "#1"- :type "card"- :card-id 1}}}- :database (meta/id)}])- tag {:name "card-template-tag-test"- :display-name "Card template tag test"- :type :card- :card-id 1}- e (try- (value-for-tag mp tag [])- (catch clojure.lang.ExceptionInfo e- e))- exc-data (some (fn [e]- (when (:card-query-error? (ex-data e))- (ex-data e)))- (take-while some? (iterate ex-cause e)))]- (testing "should be a card Query error"- (is (true?- (boolean (:card-query-error? exc-data)))))- (testing "card-id"- (is (= 1- (:card-id exc-data))))- (testing "tag"- (is (= tag- (:tag exc-data))))))))--(deftest card-query-permissions-test- (testing "We should be able to run a query referenced via a template tag if we have perms for the Card in question (#12354)"- (mt/with-non-admin-groups-no-root-collection-perms- (mt/with-temp-copy-of-db- (mt/with-no-data-perms-for-all-users!- (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)- (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/create-queries :no)- (mt/with-temp [:model/Collection collection {}- :model/Card {card-1-id :id} {:collection_id (u/the-id collection)- :dataset_query (mt/mbql-query venues- {:order-by [[:asc $id]] :limit 2})}- :model/Card card-2 {:collection_id (u/the-id collection)- :dataset_query (mt/native-query- {:query "SELECT * FROM {{card}}"- :template-tags {"card" {:name "card"- :display-name "card"- :type :card- :card-id card-1-id}}})}]- (perms/grant-collection-read-permissions! (perms-group/all-users) collection)- (mt/with-test-user :rasta- (binding [qp.perms/*card-id* (u/the-id card-2)]- (is (= [[1 "Red Medicine" 4 10.0646 -165.374 3]- [2 "Stout Burgers & Beers" 11 34.0996 -118.329 2]]- (mt/rows- (qp/process-query (:dataset_query card-2)))))))))))))--(deftest ^:parallel card-query-errors-test- (testing "error conditions for :card parameters"- (testing "should throw and exception if Card does not exist"- (let [query {:database (meta/id)- :type :native- :native {:query "SELECT * FROM table WHERE {{x}}"}- :template-tags {"x" {:name "x"- :display-name "X"- :type :card- :card-id Integer/MAX_VALUE}}}]- (is (thrown?- clojure.lang.ExceptionInfo- (params.values/stage->params-map query)))))))--(defn- query-with-snippet [metadata-provider & {:as snippet-properties}]- (-> (lib/native-query metadata-provider "SELECT * FROM {{expensive-venues}}")- (lib/update-query-stage 0 assoc :template-tags {"expensive-venues" (merge- {:type :snippet- :name "expensive-venues"- :display-name "Expensive Venues"- :snippet-name "expensive-venues"}- snippet-properties)})))--(deftest ^:parallel snippet-validation-test- (testing "`:snippet-id` should be required"- (is (thrown?- clojure.lang.ExceptionInfo- (params.values/stage->params-map (query-with-snippet meta/metadata-provider)))))- (testing "If no such Snippet exists, it should throw an #?(:clj Exception :cljs :default"- (is (thrown?- clojure.lang.ExceptionInfo- (params.values/stage->params-map (query-with-snippet meta/metadata-provider :snippet-id Integer/MAX_VALUE))))))--(deftest ^:parallel snippet-happy-path-test- (testing "Snippet parsing should work correctly for a valid Snippet"- (let [mp (lib.tu/mock-metadata-provider- meta/metadata-provider- {:native-query-snippets [{:id 1- :name "expensive-venues"- :content "venues WHERE price = 4"}]})- expected {"expensive-venues" (params/referenced-query-snippet {:snippet-id 1- :content "venues WHERE price = 4"})}]- (is (= expected- (params.values/stage->params-map (query-with-snippet mp :snippet-id 1))))- (testing "`:snippet-name` property in query shouldn't have to match `:name` of Snippet in DB"- (is (= expected- (params.values/stage->params-map (query-with-snippet mp :snippet-id 1, :snippet-name "Old Name"))))))))--(deftest ^:parallel invalid-param-test- (testing "Should throw an exception if we try to pass with a `:type` we don't understand"- (let [query {:database (meta/id)- :type :native- :native {:query "SELECT * FROM table WHERE {{x}}"}- :template-tags {"x" {:name "x"- :type :writer}}}]- (is (thrown?- clojure.lang.ExceptionInfo- (params.values/stage->params-map query))))))--(deftest ^:parallel dont-be-too-strict-test- (testing "values-for-tag should allow unknown keys (used only by FE) (#13868)"- (testing "\nUnknown key 'filteringParameters'"- (testing "in tag"- (is (= "2"- (value-for-tag- {:name "id"- :display-name "ID"- :type :text- :required true- :default "100"- :filteringParameters "222b245f"}- [{:type :category- :target [:variable [:template-tag "id"]]- :value "2"}])))))))--(deftest ^:parallel dont-be-too-strict-test-2- (testing "values-for-tag should allow unknown keys (used only by FE) (#13868)"- (testing "\nUnknown key 'filteringParameters'"- (testing "in params"- (is (= "2"- (value-for-tag- {:name "id"- :display-name "ID"- :type :text- :required true- :default "100"}- [{:type :category- :target [:variable [:template-tag "id"]]- :value "2"- :filteringParameters "222b245f"}])))))))--(deftest ^:parallel parse-card-include-parameters-test- (testing "Parsing a Card reference should return a `ReferencedCardQuery` record that includes its parameters (#12236)"- (let [mp (lib.tu/mock-metadata-provider- meta/metadata-provider- {:cards [(assoc (:orders (lib.tu/mock-cards))- :id 1- :dataset-query (lib.tu.macros/mbql-query orders- {:filter [:between $total 30 60]- :aggregation [[:aggregation-options- [:count-where [:starts-with $product-id->products.category "G"]]- {:name "G Monies", :display-name "G Monies"}]]- :breakout [!month.created-at]}))]})]- (is (=? {:card-id 1- :query (every-pred string? (complement str/blank?))- :params ["G%"]}- (#'params.values/parse-tag- mp- {:id "5aa37572-058f-14f6-179d-a158ad6c029d"- :name "#1"- :display-name "#1"- :type :card- :card-id 1}- nil))))))--(defn- query-with-native-stage-with-keys [m]- (-> (lib/native-query meta/metadata-provider "SELECT * FROM whatever;")- (lib/update-query-stage 0 merge m)))--(deftest ^:parallel no-value-template-tag-defaults-test- (testing "should not throw and exception if no :value is specified for a required parameter when defaults are provided"- (testing "Field filters"- (is (=? {"filter" {:value {:value ["Gizmo" "Gadget"]}}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags {"filter"- {:id "xyz456"- :name "filter"- :display-name "Filter"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :products :category)]- :widget-type :category- :default ["Gizmo" "Gadget"]- :required true}}- :parameters [{:type :string/=- :id "abc123"- :default ["Widget"]- :target [:dimension [:template-tag "filter"]]}]})))))))--(deftest ^:parallel no-value-template-tag-defaults-raw-value-test- (testing "should not throw and exception if no :value is specified for a required parameter when defaults are provided"- (testing "Raw value template tags"- (is (= {"filter" "Foo"}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags {"filter"- {:id "f0774ef5-a14a-e181-f557-2d4bb1fc94ae"- :name "filter"- :display-name "Filter"- :type :text- :required true- :default "Foo"}}- :parameters [{:type :string/=- :id "5791ff38"- :default "Bar"- :target [:variable [:template-tag "filter"]]}]})))))))--(deftest ^:parallel nil-value-parameter-template-tag-default-test- (testing "Default values passed in as part of the request should not apply when the value is nil"- (testing "Field filters"- (is (=? {"filter" {:value ::params/no-value}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags {"filter"- {:id "xyz456"- :name "filter"- :display-name "Filter"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :products :category)]- :widget-type :category- :default ["Gizmo" "Gadget"]}}- :parameters [{:type :string/=- :id "abc123"- :default ["Widget"]- :value nil- :target [:dimension [:template-tag "filter"]]}]})))))))--(deftest ^:parallel nil-value-parameter-template-tag-default-raw-value-test- (testing "Raw value template tags"- (is (= {"filter" ::params/no-value}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags {"filter"- {:id "f0774ef5-a14a-e181-f557-2d4bb1fc94ae"- :name "filter"- :display-name "Filter"- :type :text- :default "Foo"}}- :parameters [{:type :string/=- :id "5791ff38"- :default "Bar"- :target [:variable [:template-tag "filter"]]}]}))))))--(deftest ^:parallel field-filter-multiple-values-test- (testing "Make sure multiple values get returned the way we'd expect"- (is (=? {"checkin_date" {:value [{:type :date/range, :value "2015-01-01~2016-09-01"}- {:type :date/single, :value "2015-07-01"}]}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags {"checkin_date" {:name "checkin_date"- :display-name "Checkin Date"- :type :dimension- :widget-type :date/all-options- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :checkins :date)]}}- :parameters [{:type :date/range- :target [:dimension [:template-tag "checkin_date"]]- :value "2015-01-01~2016-09-01"}- {:type :date/single- :target [:dimension [:template-tag "checkin_date"]]- :value "2015-07-01"}]}))))))--(deftest ^:parallel use-parameter-defaults-test- (testing "If parameter specifies a default value (but tag does not), don't use the default when the value is nil"- (testing "Field filters"- (is (=? {"filter" {:value ::params/no-value}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags {"filter"- {:id "xyz456"- :name "filter"- :display-name "Filter"- :type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :products :category)]- :widget-type :category}}- :parameters [{:type :string/=- :id "abc123"- :default ["Widget"]- :value nil- :target [:dimension [:template-tag "filter"]]}]})))))))--(deftest ^:parallel use-parameter-defaults-raw-value-template-tags-test- (testing "If parameter specifies a default value (but tag does not), don't use the default when the value is nil"- (testing "Raw value template tags"- (is (= {"filter" ::params/no-value}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags {"filter"- {:id "f0774ef5-a14a-e181-f557-2d4bb1fc94ae"- :name "filter"- :display-name "Filter"- :type :text}}- :parameters [{:type :string/=- :id "5791ff38"- :default "Bar"- :value nil- :target [:variable [:template-tag "filter"]]}]})))))))--(deftest ^:parallel value->number-test- (testing `params.values/value->number- (testing "should handle a vector"- (testing "of strings"- (is (= 1- (#'params.values/value->number ["1"]))))- (testing "of numbers (#20845)"- (is (= 1- (#'params.values/value->number [1])))))))--(deftest ^:parallel handle-referenced-card-parameter-mixed-with-other-parameters-test- (testing "Should be able to handle for Card ref params regardless of whether other params are passed in (#21246)\n"- (let [mp (lib.tu/metadata-provider-with-cards-for-queries- meta/metadata-provider- [(lib.tu.macros/mbql-query products)])- param-name "#1"- template-tags {param-name {:type :card- :card-id 1- :display-name param-name- :id "__source__"- :name param-name}}]- (testing "With no parameters passed in"- (is (=? {param-name params/referenced-card-query?}- (params.values/stage->params-map (-> (lib/native-query mp "SELECT *")- (lib/update-query-stage 0 assoc :template-tags template-tags))))))- (testing "WITH parameters passed in"- (let [parameters [{:type :date/all-options- :value "2022-04-20"- :target [:dimension [:template-tag "created_at"]]}]]- (is (=? {param-name params/referenced-card-query?}- (params.values/stage->params-map (-> (lib/native-query mp "SELECT *")- (lib/update-query-stage 0 merge {:template-tags template-tags- :parameters parameters}))))))))))--(deftest ^:parallel handle-dashboard-parameters-without-values-test- (testing "dash params for a template tag may have no :value or :default (#38012)"- (let [template-tags {"createdAt" {:type :dimension- :dimension [:field {:lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :orders :created-at)]- :name "createdAt"- :id "4636d745-1467-4a70-ba20-2a08069d77ff"- :display-name "CreatedAt"- :widget-type :date/all-options}}]- (testing "with no parameters given, no value"- (is (=? {"createdAt" {:field {:lib/type :metadata/column}- :value params/no-value}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags template-tags})))))- (testing "with parameters given but blank, no value"- (is (=? {"createdAt" {:field {:lib/type :metadata/column}- :value params/no-value}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags template-tags- :parameters [{:type :date/relative- :value nil- :target [:dimension [:template-tag "createdAt"]]}- {:type :date/month-year- :value nil- :target [:dimension [:template-tag "createdAt"]]}]})))))- (testing "with only the relative date parameter set, use it"- (is (=? {"createdAt" {:field {:lib/type :metadata/column}- :value {:type :date/relative- :value "past30days"}}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags template-tags- :parameters [{:type :date/relative- :value "past30days"- :target [:dimension [:template-tag "createdAt"]]}- {:type :date/month-year- :value nil- :target [:dimension [:template-tag "createdAt"]]}]})))))- (testing "with only the month-year parameter set, use it"- (is (=? {"createdAt" {:field {:lib/type :metadata/column}- :value {:type :date/month-year- :value "2023-01"}}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags template-tags- :parameters [{:type :date/relative- :value nil- :target [:dimension [:template-tag "createdAt"]]}- {:type :date/month-year- :value "2023-01"- :target [:dimension [:template-tag "createdAt"]]}]})))))- (testing "with both parameters set, use both"- (is (=? {"createdAt" {:field {:lib/type :metadata/column}- :value [{:type :date/relative- :value "past30days"}- {:type :date/month-year- :value "2023-01"}]}}- (params.values/stage->params-map- (query-with-native-stage-with-keys- {:template-tags template-tags- :parameters [{:type :date/relative- :value "past30days"- :target [:dimension [:template-tag "createdAt"]]}- {:type :date/month-year- :value "2023-01"- :target [:dimension [:template-tag "createdAt"]]}]}))))))))--(deftest ^:parallel referenced-card-ids-test- (let [mp (lib.tu/mock-metadata-provider- meta/metadata-provider- {:cards [{:id 1- :dataset-query (lib.tu.macros/mbql-query venues {:limit 2})}- {:id 2- :dataset-query {:database (meta/id)- :type :native- :native {:query "SELECT * FROM {{card}}"- :template-tags {"card" {:name "card"- :display-name "card"- :type :card- :card-id 1}}}}}]})]- ;; even tho Card 2 references Card 1, we don't want to include it in the set of referenced Card IDs, since you- ;; should only need permissions for Card 2 to be able to run the query (see #15131)- (is (=? #{2}- (params.values/referenced-card-ids- (params.values/stage->params-map- (lib/query- mp- {:type :native- :native {:query "SELECT * FROM {{card}}"- :template-tags {"card" {:name "card"- :display-name "card"- :type :card- :card-id 2}}}})))))))diff --git a/test/metabase/query_processor_test/field_ref_repro_test.clj b/test/metabase/query_processor_test/field_ref_repro_test.cljindex 40b764c8b24..bb64e00b8bd 100644--- a/test/metabase/query_processor_test/field_ref_repro_test.clj+++ b/test/metabase/query_processor_test/field_ref_repro_test.clj@@ -510,7 +510,7 @@(is (= [[1746]](mt/rows results))))))))-(deftest model-with-implicit-join-and-external-remapping-test+(deftest ^:parallel model-with-implicit-join-and-external-remapping-test(testing "Should handle models with implicit join on externally remapped field (#57596)"(qp.store/with-metadata-provider(lib.tu/remap-metadata-providerdiff --git a/test/metabase/query_processor_test/parameters_test.clj b/test/metabase/query_processor_test/parameters_test.cljindex 2e2c1967be7..3f1f94fee11 100644--- a/test/metabase/query_processor_test/parameters_test.clj+++ b/test/metabase/query_processor_test/parameters_test.clj@@ -8,11 +8,15 @@[java-time.api :as t][medley.core :as m][metabase.driver :as driver]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.lib.native :as lib-native]+ [metabase.lib.test-util :as lib.tu][metabase.permissions.models.permissions :as perms][metabase.permissions.models.permissions-group :as perms-group][metabase.query-processor :as qp][metabase.query-processor.compile :as qp.compile]+ [metabase.query-processor.store :as qp.store][metabase.test :as mt][metabase.util :as u][metabase.util.date-2 :as u.date]))@@ -245,11 +249,15 @@(deftest ^:parallel filter-nested-queries-test(mt/test-drivers (mt/normal-drivers-with-feature :native-parameters :nested-queries)- (mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/native-query (qp.compile/compile (mt/mbql-query checkins)))}]- (let [query (assoc (mt/mbql-query nil- {:source-table (format "card__%d" card-id)})+ (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider+ (mt/application-database-metadata-provider (mt/id))+ {:cards [{:id 1+ :dataset-query (mt/native-query (qp.compile/compile (mt/mbql-query checkins)))}]})+ (let [date (lib.metadata/field (qp.store/metadata-provider) (mt/id :checkins :date))+ query (assoc (mt/mbql-query nil+ {:source-table "card__1", :limit 5}):parameters [{:type :date/all-options- :target [:dimension (mt/$ids *checkins.date)] ; expands to appropriate field-literal form+ :target [:dimension [:field (:name date) {:base-type :type/Date}]]:value "2014-01-06"}])](testing "We should be able to apply filters to queries that use native queries with parameters as their source (#9802)"(is (= [[182 "2014-01-06T00:00:00Z" 5 31]]@@ -257,10 +265,14 @@:checkins(qp/process-query query)))))(testing "We should be able to apply filters explicitly targeting nested native stages (#48258)"- (is (= [[182 "2014-01-06T00:00:00Z" 5 31]]- (mt/formatted-rows- :checkins- (qp/process-query (assoc-in query [:parameters 0 :target 2] {:stage-number 0}))))))))))+ (let [query' (assoc-in query [:parameters 0 :target 2 :stage-number] 0)]+ (is (=? {:parameters [{:target [:dimension [:field (:name date) {:base-type :type/Date}] {:stage-number 0}]+ :value "2014-01-06"}]}+ query'))+ (is (= [[182 "2014-01-06T00:00:00Z" 5 31]]+ (mt/formatted-rows+ :checkins+ (qp/process-query query'))))))))))(deftest ^:parallel string-escape-test;; test `:sql` drivers that support native parameters@@ -696,3 +708,44 @@(mt/formatted-rows[int str](qp/process-query query))))))))))))))++(deftest ^:parallel x-test+ (mt/test-drivers (mt/normal-drivers)+ (let [query (lib/query+ (mt/application-database-metadata-provider (mt/id))+ {:lib/type :mbql/query+ :database (mt/id)+ :stages [{:lib/type :mbql.stage/mbql+ :source-table (mt/id :orders)+ :fields [[:field {:lib/uuid "00000000-0000-0000-0000-000000000000"}+ (mt/id :orders :id)]+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000001"}+ (mt/id :orders :tax)]]+ :order-by [[:asc {:lib/uuid "00000000-0000-0000-0000-000000000002"}+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000003"}+ (mt/id :orders :id)]]]+ :limit 2}]+ :parameters [{:value [2.07]+ :type :number/=+ :target [:dimension [:field (mt/id :orders :tax) {:base-type :type/Float}] {:stage-number 0}]}+ {:value nil+ :type :number/=+ :target [:dimension [:field (mt/id :orders :tax) {:base-type :type/Float}] {:stage-number 0}]}+ {:value nil+ :type :number/!=+ :target [:dimension [:field (mt/id :orders :tax) {:base-type :type/Float}] {:stage-number 0}]}+ {:value nil+ :type :number/!=+ :target [:dimension [:field (mt/id :orders :tax) {:base-type :type/Float}] {:stage-number 0}]}+ {:value [nil]+ :type :number/<=+ :target [:dimension [:field (mt/id :orders :tax) {:base-type :type/Float}] {:stage-number 0}]}+ {:value nil+ :type :number/>=+ :target [:dimension [:field (mt/id :orders :tax) {:base-type :type/Float}] {:stage-number 0}]}+ {:value nil+ :type :number/<=+ :target [:dimension [:field (mt/id :orders :tax) {:base-type :type/Float}] {:stage-number 0}]}]})]+ (is (= [[1 2.07]+ [212 2.07]]+ (mt/formatted-rows [int 2.0] (qp/process-query query)))))))diff --git a/test/metabase/search/appdb/index_test.clj b/test/metabase/search/appdb/index_test.cljindex 89ef47eb934..65e0baa1b52 100644--- a/test/metabase/search/appdb/index_test.clj+++ b/test/metabase/search/appdb/index_test.clj@@ -365,7 +365,7 @@:updated_at yesterday;; :archived = true:archived true}- :model/QueryAction _ {:dataset_query (mt/native-query "select * from metabase")+ :model/QueryAction _ {:dataset_query (mt/native-query {:query "select * from metabase"});; :database_id = db-id:database_id db-id:action_id action-id}]diff --git a/test/metabase/session/models/session_test.clj b/test/metabase/session/models/session_test.cljindex 4466798e515..bbadfa01faf 100644--- a/test/metabase/session/models/session_test.clj+++ b/test/metabase/session/models/session_test.clj@@ -8,12 +8,15 @@[metabase.session.models.session :as session][metabase.system.core :as system][metabase.test :as mt]+ [metabase.test.fixtures :as fixtures][metabase.util :as u][metabase.util.date-2 :as u.date][metabase.util.malli.schema :as ms][metabase.util.string :as string][toucan2.core :as t2]))+(use-fixtures :once (fixtures/initialize :db :test-users))+(def ^:private test-uuid #uuid "092797dd-a82a-4748-b393-697d7bb9ab65")(def ^:private test-id "abcde12345")diff --git a/test/metabase/test/data.clj b/test/metabase/test/data.cljindex ecc2ff674a8..f3fe19907a3 100644--- a/test/metabase/test/data.clj+++ b/test/metabase/test/data.clj@@ -177,9 +177,10 @@(declare id)-(defn native-query+(mu/defn native-query"Like `mbql-query`, but for native queries."- [inner-native-query]+ [inner-native-query :- [:map+ [:query some?]]]{:database (id):type :native:native inner-native-query})