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
add-implicit-clauses middleware => Lib (#63360)
Cam Saulc1a3971ae8b6
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex 6620c247bbf..7098e56a1c9 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -228,7 +228,7 @@(clojure.core.logic/fresh)(clojure.core.logic/matcha)(clojure.core.logic/run)- (clojure.test/is [query= =? malli= qv=])+ (clojure.test/is [=? malli= qv=])(clojure.tools.macro/macrolet)instaparse.core/transform(metabase.server.streaming-response/streaming-response)@@ -713,13 +713,18 @@{:pattern "^metabase\\.lib\\..*":name metabase-lib-excluding-legacy-mbql};;- ;; QP source namespaces: `metabase.query-processor.*`, `metabase-enterprise.sandbox.query-processor.*`, and- ;; `metabase.driver.*`, excluding `-test` namespaces.+ ;; QP and driver source namespaces: `metabase.query-processor.*`, `metabase-enterprise.sandbox.query-processor.*`,+ ;; and `metabase.driver.*`, excluding `-test` namespaces.;;{:pattern "metabase(?:(?:(?:-enterprise\\.sandbox)?\\.query-processor\\.)|(?:\\.driver\\.)).*(?<!-test)$":name qp-and-driver-source-namespaces};;- ;; driver namespaces+ ;; QP source namespaces+ ;;+ {:pattern "metabase(?:(?:-enterprise\\.sandbox)?\\.query-processor\\.).*(?<!-test)$"+ :name qp-source-namespaces}+ ;;+ ;; driver namespaces, including tests;;{:pattern "metabase\\.driver.*$":name driver-namespaces}@@ -779,7 +784,7 @@clojure.string/lower-case {:level :off}clojure.string/upper-case {:level :off}}}}- ;; enable all the extra linters we haven't enabled in the core app yet in MLv2. It's all new code so we can adhere+ ;; enable all the extra linters we haven't enabled in the core app yet in Lib. It's all new code so we can adhere;; to the new stricter rules from day 1metabase-lib{:linters@@ -799,19 +804,25 @@metabase.test/with-temp {:message "Don't use application database inside Lib code"}}:discouraged-namespace- {metabase.driver {:message "MLv2 code should be independent of driver code/methods"}- metabase.test {:message "MLv2 tests should only use MLv2 test helpers"}- metabase.test.data {:message "MLv2 tests should only use MLv2 test helpers"}- metabase.util.malli.schema {:message "Prefer metabase.lib.schema schemas in MLv2 code"}- toucan.db {:message "Don't use application database inside MLv2 code"}- toucan.models {:message "Don't use application database inside MLv2 code"}- toucan.util.test {:message "Don't use application database inside MLv2 code"}- toucan2.core {:message "Don't use application database inside MLv2 code"}}}}+ {metabase.driver {:message "Lib code should be independent of driver code/methods"}+ metabase.test {:message "Lib tests should only use Lib test helpers"}+ metabase.test.data {:message "Lib tests should only use Lib test helpers"}+ metabase.util.malli.schema {:message "Prefer metabase.lib.schema schemas in Lib code"}+ toucan.db {:message "Don't use application database inside Lib code"}+ toucan.models {:message "Don't use application database inside Lib code"}+ toucan.util.test {:message "Don't use application database inside Lib code"}+ toucan2.core {:message "Don't use application database inside Lib code"}}}}metabase-lib-excluding-legacy-mbql{:linters{:discouraged-var- {metabase.legacy-mbql.util/unique-name-generator {:message "Use metabase.lib.util/unique-name-generator or non-truncating-unique-name-generator"}}}}+ {metabase.legacy-mbql.util/unique-name-generator {:message "Use metabase.lib.util/unique-name-generator or non-truncating-unique-name-generator"}}}++ :discouraged-namespace+ {metabase.legacy-mbql.js {:message "Avoid legacy MBQL utils in Lib; move things into Lib if needded."}+ metabase.legacy-mbql.jvm-util {:message "Avoid legacy MBQL utils in Lib; move things into Lib if needded."}+ metabase.legacy-mbql.predicates {:message "Avoid legacy MBQL utils in Lib; move things into Lib if needded."}+ metabase.legacy-mbql.util {:message "Avoid legacy MBQL utils in Lib; move things into Lib if needded."}}}driver-namespaces{:linters@@ -828,19 +839,31 @@{:discouraged-namespace{metabase.query-processor.store {:level :off}metabase.util.malli.schema {:message "Prefer metabase.lib.schema or metabase.legacy-mbql.schema schemas in QP/driver code"}- toucan.db {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}- toucan.models {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}- toucan.util.test {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}- toucan2.core {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}}+ toucan.db {:message "Don't use application database directly in QP code; use the MetadataProvider"}+ toucan.models {:message "Don't use application database directly in QP code; use the MetadataProvider"}+ toucan.util.test {:message "Don't use application database directly in QP code; use the MetadataProvider"}+ toucan2.core {:message "Don't use application database directly in QP code; use the MetadataProvider"}}:discouraged-var{medley.core/map-keys {:message "Use metabase.util.performance/update-keys"}medley.core/map-vals {:message "Use clojure.core/update-vals"}- metabase.app-db.core/query {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}- metabase.app-db.core/reducible-query {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}+ metabase.app-db.core/query {:message "Don't use application database directly in QP code; use the MetadataProvider"}+ metabase.app-db.core/reducible-query {:message "Don't use application database directly in QP code; use the MetadataProvider"}metabase.lib.convert/->legacy-MBQL {:level :off}metabase.lib.core/->legacy-MBQL {:level :off}}}}+ qp-source-namespaces+ {:linters+ {:discouraged-namespace+ {metabase.legacy-mbql.js {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}+ metabase.legacy-mbql.jvm-util {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}+ metabase.legacy-mbql.normalize {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}+ metabase.legacy-mbql.predicates {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}+ metabase.legacy-mbql.schema {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}+ metabase.legacy-mbql.schema.helpers {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}+ metabase.legacy-mbql.schema.macros {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}+ metabase.legacy-mbql.util {:message "Avoid legacy MBQL namespaces in the QP, use Lib instead"}}}}+general-qp-and-driver-test-namespaces{:linters{:discouraged-vardiff --git a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.jsindex 916ee71b95f..eb69d5a5e94 100644--- a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js+++ b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js@@ -115,7 +115,7 @@ describe("issue 41765", { tags: "@external" }, () => {});}- it(+ it.skip("re-syncing a database should invalidate the table cache (metabase#41765)",{ tags: "@flaky" },() => {diff --git a/e2e/test/scenarios/admin/transforms.cy.spec.ts b/e2e/test/scenarios/admin/transforms.cy.spec.tsindex 7b50bc8df72..9d9e69e60e5 100644--- a/e2e/test/scenarios/admin/transforms.cy.spec.ts+++ b/e2e/test/scenarios/admin/transforms.cy.spec.ts@@ -417,7 +417,7 @@ H.describeWithSnowplowEE("scenarios > admin > transforms", () => {});describe("tags", () => {- it("should be able to add and remove tags", () => {+ it("should be able to add and remove tags", { tags: "@flaky" }, () => {createMbqlTransform({ visitTransform: true });getTagsInput().click();@@ -1202,18 +1202,22 @@ describe("scenarios > admin > transforms > databases without :schemas", () => {cy.intercept("DELETE", "/api/ee/transform-tag/*").as("deleteTag");});- it("should be not be possible to create a new schema when updating a transform target", () => {- createMbqlTransform({- databaseId: WRITABLE_DB_ID,- sourceTable: "ORDERS",- visitTransform: true,- targetSchema: null,- });+ it(+ "should be not be possible to create a new schema when updating a transform target",+ { tags: "@flaky" },+ () => {+ createMbqlTransform({+ databaseId: WRITABLE_DB_ID,+ sourceTable: "ORDERS",+ visitTransform: true,+ targetSchema: null,+ });- getTransformPage().button("Change target").click();+ getTransformPage().button("Change target").click();- H.modal().findByLabelText("Schema").should("not.exist");- });+ H.modal().findByLabelText("Schema").should("not.exist");+ },+ );it("should be not be possible to create a new schema when the database does not support schemas", () => {cy.log("create a new transform");diff --git a/e2e/test/scenarios/models/reproductions.cy.spec.js b/e2e/test/scenarios/models/reproductions.cy.spec.jsindex c0538696440..655398c6fe5 100644--- a/e2e/test/scenarios/models/reproductions.cy.spec.js+++ b/e2e/test/scenarios/models/reproductions.cy.spec.js@@ -1442,7 +1442,7 @@ describe("issue 53604 - nested native question with multiple breakouts on same c);cy.findByTestId("qb-filters-panel").findByText(- "CREATED_AT is Jan 1 – Dec 31, 2024",+ "CREATED_AT: Year is Jan 1 – Dec 31, 2024",);H.assertQueryBuilderRowCount(520);diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/column_level_perms_check.clj b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/column_level_perms_check.cljindex b644e708e8c..c102c79d1c1 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/column_level_perms_check.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/column_level_perms_check.clj@@ -2,6 +2,9 @@(:require[medley.core :as m][metabase.api.common :refer [*current-user-id*]]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib only soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.util.match :as lib.util.match][metabase.premium-features.core :refer [defenterprise-schema]]diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.cljindex 7a45c6290c0..6bc20037f9d 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj@@ -8,6 +8,8 @@[metabase-enterprise.sandbox.api.util :as sandbox.api.util][metabase-enterprise.sandbox.models.sandbox :as sandbox][metabase.api.common :as api :refer [*current-user* *current-user-id*]]+ ;; allowed (for now) since sandboxing needs to manipulate legacy metadata+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.cljindex be8ee8683df..7acd1f09276 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj@@ -176,7 +176,10 @@(is (=? (mt/query checkins{:type :query:query {:source-query {:source-table $$checkins- :fields [$id $date $user_id $venue_id]+ :fields [[:field %id {}]+ [:field %date {}]+ [:field %user_id {}]+ [:field %venue_id {}]]:filter [:and;; This still gets :default bucketing! auto-bucket-datetimes;; puts :day bucketing on both parts of this filter, since it's@@ -196,8 +199,12 @@:query-permissions/sandboxed-table $$checkins}:joins [{:source-query{:source-table $$venues- :fields [$venues.id $venues.name $venues.category_id- $venues.latitude $venues.longitude $venues.price]+ :fields [[:field %venues.id {}]+ [:field %venues.name {}]+ [:field %venues.category_id {}]+ [:field %venues.latitude {}]+ [:field %venues.longitude {}]+ [:field %venues.price {}]]:filter [:=$venues.price[:value 1 {:base_type :type/Integer@@ -557,7 +564,7 @@:table_id (mt/id :venues));; should return a field for the original field(update :field_ref (fn [[tag _id opts]]- [tag id (or opts {})]))+ [tag id opts]))(dissoc :fk_target_field_id:lib/original-display-name:metabase.lib.query/transformation-added-base-type))))]@@ -833,7 +840,7 @@(first (mt/rows result))))))(testing "Ok, add remapping and it should still work"(qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :reviews :product_id)(mt/id :products :title))(let [result (mt/run-mbql-query reviews {:order-by [[:asc $id]]})]@@ -909,7 +916,7 @@test-preprocessing(fn []- (testing "`resolve-joined-fields` middleware should infer `:field` `:join-alias` correctly"+ (testing "`fix-bad-field-id-refs` middleware should infer `:field` `:join-alias` correctly"(is (= [:=[:field (mt/id :products :category) {:join-alias "products"}][:value "Widget" {:base_type :type/Text@@ -935,7 +942,7 @@(qp/process-query drill-thru-query)))))))](test-drill-thru)(qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :orders :product_id)(mt/id :products :title))(test-drill-thru))))))))@@ -986,7 +993,7 @@(do-tests)(testing "with remapping"(qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :orders :product_id)(mt/id :products :title))(do-tests))))))))@@ -1014,7 +1021,7 @@(mt/dataset test-data(let [remap-metadata-provider (fn [](lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :orders :product_id)(mt/id :products :title)))mbql-sandbox-results (met/with-gtaps! {:gtaps (mt/$idsdiff --git a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.cljindex 4667419e1fa..824599e69de 100644--- a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj+++ b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj@@ -45,11 +45,11 @@:source-query {:source-table 1:order-by [[:asc [:field 2 nil]]]:limit 10}}]}]- (is (query= expected- (#'sqlserver/fix-order-bys original)))+ (is (= expected+ (#'sqlserver/fix-order-bys original)))(testing "Inside `:source-query`"- (is (query= {:source-query expected}- (#'sqlserver/fix-order-bys {:source-query original})))))))+ (is (= {:source-query expected}+ (#'sqlserver/fix-order-bys {:source-query original})))))))(deftest ^:parallel fix-order-bys-test-2(testing "Add limit for :source-query order bys"@@ -57,21 +57,21 @@(let [original {:source-table 1:order-by [[:asc 2]]}](testing "Not in a source query -- don't do anything"- (is (query= original- (#'sqlserver/fix-order-bys original))))+ (is (= original+ (#'sqlserver/fix-order-bys original))))(testing "In source query -- add `:limit`"- (is (query= {:source-query (assoc original :limit limit/absolute-max-results)}- (#'sqlserver/fix-order-bys {:source-query original}))))+ (is (= {:source-query (assoc original :limit limit/absolute-max-results)}+ (#'sqlserver/fix-order-bys {:source-query original}))))(testing "In source query in source query-- add `:limit` at both levels"- (is (query= {:source-query {:source-query (assoc original :limit limit/absolute-max-results)- :order-by [[:asc [:field 1]]]- :limit limit/absolute-max-results}}- (#'sqlserver/fix-order-bys {:source-query {:source-query original- :order-by [[:asc [:field 1]]]}}))))+ (is (= {:source-query {:source-query (assoc original :limit limit/absolute-max-results)+ :order-by [[:asc [:field 1]]]+ :limit limit/absolute-max-results}}+ (#'sqlserver/fix-order-bys {:source-query {:source-query original+ :order-by [[:asc [:field 1]]]}}))))(testing "In source query inside source query for join -- add `:limit`"- (is (query= {:joins [{:source-query {:source-query (assoc original :limit limit/absolute-max-results)}}]}- (#'sqlserver/fix-order-bys- {:joins [{:source-query {:source-query original}}]}))))))))+ (is (= {:joins [{:source-query {:source-query (assoc original :limit limit/absolute-max-results)}}]}+ (#'sqlserver/fix-order-bys+ {:joins [{:source-query {:source-query original}}]}))))))));;; -------------------------------------------------- VARCHAR(MAX) --------------------------------------------------diff --git a/src/metabase/driver/common/parameters/operators.clj b/src/metabase/driver/common/parameters/operators.cljindex 7ee25b26803..ef554d6c1ba 100644--- a/src/metabase/driver/common/parameters/operators.clj+++ b/src/metabase/driver/common/parameters/operators.clj@@ -77,7 +77,7 @@(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 :- ::mbql.s/Parameter]+ [param :- ::lib.schema.parameter/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)diff --git a/src/metabase/driver/common/parameters/values.clj b/src/metabase/driver/common/parameters/values.cljindex 6af7650b490..df9a8839a2e 100644--- a/src/metabase/driver/common/parameters/values.clj+++ b/src/metabase/driver/common/parameters/values.clj@@ -18,6 +18,7 @@[metabase.lib.metadata.protocols :as lib.metadata.protocols][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.query-processor.compile :as qp.compile][metabase.query-processor.error-type :as qp.error-type]@@ -111,7 +112,7 @@(mu/defn- tag-params"Return params from the provided `params` list targeting the provided `tag`."[tag :- mbql.s/TemplateTag- params :- [:maybe [:sequential mbql.s/Parameter]]]+ params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]](let [tag-target? (tag-target-pred tag)](seq (for [param params:when (tag-target? (:target param))]@@ -132,7 +133,7 @@"Get parameter value(s) for a Field filter. Returns map if there is a normal single value, or a vector of maps formultiple values."[tag :- mbql.s/TemplateTag- params :- [:maybe [:sequential mbql.s/Parameter]]]+ params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]](let [matching-params (tag-params tag params)tag-opts (:options tag)normalize-params (fn [params]@@ -196,7 +197,7 @@(mu/defmethod parse-tag :dimension :- [:maybe FieldFilter][{:keys [dimension alias], :as tag} :- mbql.s/TemplateTag- params :- [:maybe [:sequential mbql.s/Parameter]]]+ params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]](params/map->FieldFilter{:field (let [field-id (dimension->field-id dimension)](or (lib.metadata/field (qp.store/metadata-provider) field-id)@@ -291,7 +292,7 @@(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 :- mbql.s/TemplateTag- params :- [:maybe [:sequential mbql.s/Parameter]]]+ 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)@@ -431,7 +432,7 @@"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`."[tag :- mbql.s/TemplateTag- params :- [:maybe [:sequential mbql.s/Parameter]]]+ params :- [:maybe [:sequential ::lib.schema.parameter/parameter]]](try(parse-value-for-type (:type tag) (parse-tag tag params))(catch Throwable ediff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.cljindex 4be26c9514a..77166f9fb79 100644--- a/src/metabase/driver/sql/query_processor.clj+++ b/src/metabase/driver/sql/query_processor.clj@@ -864,10 +864,10 @@(:name (driver-api/field (driver-api/metadata-provider) id-or-name)))))(defn- field-nfc-path- [[_field id-or-name opts]]- (or (get opts driver-api/qp.add.nfc-path)- (when (integer? id-or-name)- (:nfc-path (driver-api/field (driver-api/metadata-provider) id-or-name)))))+ [[_field _id-or-name opts]]+ ;; ignore nfc paths for fields that don't come from a source table+ (when (pos-int? (get opts driver-api/qp.add.source-table))+ (get opts driver-api/qp.add.nfc-path)))(defmethod ->honeysql [:sql ::nfc-path][_driver [_ _nfc-path]]diff --git a/src/metabase/legacy_mbql/normalize.cljc b/src/metabase/legacy_mbql/normalize.cljcindex ce97a634bcb..d57fd4b0b80 100644--- a/src/metabase/legacy_mbql/normalize.cljc+++ b/src/metabase/legacy_mbql/normalize.cljc@@ -395,7 +395,8 @@(mu/defn- normalize-fingerprint :- [:maybe ::lib.schema.metadata.fingerprint/fingerprint][fingerprint :- [:maybe :map]]- (lib.normalize/normalize ::lib.schema.metadata.fingerprint/fingerprint fingerprint))+ (when fingerprint+ (lib.normalize/normalize ::lib.schema.metadata.fingerprint/fingerprint fingerprint)))(mu/defn normalize-source-metadata"Normalize source/results metadata for a single column."@@ -1051,16 +1052,16 @@(defn- replace-legacy-filters"Replaces legacy filter clauses with modern alternatives."[query]- (try- (lib.util.match/replace query- (filter-clause :guard mbql.preds/Filter?)+ (lib.util.match/replace query+ (filter-clause :guard mbql.preds/Filter?)+ (try(-> filter-clausereplace-relative-date-filters- replace-exclude-date-filters))- (catch #?(:clj Throwable :cljs :default) e- (throw (ex-info (i18n/tru "Error replacing legacy filters")- {:query query}- e)))))+ replace-exclude-date-filters)+ (catch #?(:clj Throwable :cljs :default) e+ (throw (ex-info (i18n/tru "Error replacing legacy filters")+ {:filter-clause filter-clause, :query query}+ e))))));;; +----------------------------------------------------------------------------------------------------------------+;;; | REMOVING EMPTY CLAUSES |diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljcindex 46696f5efa5..b355b8ea743 100644--- a/src/metabase/legacy_mbql/schema.cljc+++ b/src/metabase/legacy_mbql/schema.cljc@@ -21,6 +21,7 @@[metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.schema.metadata.fingerprint :as lib.schema.metadata.fingerprint][metabase.lib.schema.middleware-options :as lib.schema.middleware-options]+ [metabase.lib.schema.parameter :as lib.schema.parameter][metabase.lib.schema.settings :as lib.schema.settings][metabase.lib.schema.template-tag :as lib.schema.template-tag][metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]@@ -296,6 +297,8 @@(lib.schema.common/disallowed-keys{:strategy ":binning keys like :strategy are not allowed at the top level of :field options."}))+;;; TODO (Cam 9/12/25) -- aren't these basically the same as MBQL 5, except Lib UUID isn't required? Maybe we should+;;; unify these schemas.(mr/def ::FieldOptions[:and[:map@@ -389,7 +392,7 @@(def ^{:added "0.39.0"} field"Schema for a `:field` clause."- (with-meta [:ref ::field] {:clause-name :field}))+ ^{:clause-name :field} [:ref ::field])(mr/def ::field-or-expression-ref[:schema@@ -1680,33 +1683,6 @@(defclause variabletarget template-tag)-(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)- [:or- Field- (one-of dimension variable)])--(mr/def ::Parameter- "Schema for the *value* of a parameter (e.g. a Dashboard parameter or a native query template tag) as passed in as- part of the `:parameters` list in a query."- [:merge- [:ref :metabase.lib.schema.parameter/parameter]- [:map- [:target {:optional true} [:ref ::parameter.target]]]])--(def Parameter- "Alias for ::Parameter. Prefer using that directly going forward."- [:ref ::Parameter])--(mr/def ::ParameterList- [:maybe [:sequential Parameter]])--(def ParameterList- "Schema for a list of `:parameters` as passed in to a query."- [:ref ::ParameterList])-;;; --------------------------------------------- Metabase [Outer] Query ---------------------------------------------;; To the reader: yes, this seems sort of hacky, but one of the goals of the Nested Query Initiative™ was to minimize@@ -1767,7 +1743,7 @@[:native {:optional true} NativeQuery][:query {:optional true} MBQLQuery]- [:parameters {:optional true} ParameterList]+ [:parameters {:optional true} [:maybe [:ref ::lib.schema.parameter/parameters]]];;;; OPTIONS;;diff --git a/src/metabase/lib/field.cljc b/src/metabase/lib/field.cljcindex c19c413918b..5c6b6d3cb08 100644--- a/src/metabase/lib/field.cljc+++ b/src/metabase/lib/field.cljc@@ -435,7 +435,7 @@(when-not inherited-column?(select-renamed-keys metadata field-ref-propagated-keys-for-non-inherited-columns)))id-or-name (or (lib.field.util/inherited-column-name metadata)- ((some-fn :id :lib/deduplicated-name :lib/original-name :name) metadata))]+ ((some-fn :id :lib/source-column-alias :lib/deduplicated-name :lib/original-name :name) metadata))][:field options id-or-name]))(mu/defmethod lib.ref/ref-method :metadata/column :- ::lib.schema.ref/refdiff --git a/src/metabase/lib/field/resolution.cljc b/src/metabase/lib/field/resolution.cljcindex 1b25e0e50c0..d456892007e 100644--- a/src/metabase/lib/field/resolution.cljc+++ b/src/metabase/lib/field/resolution.cljc@@ -14,6 +14,7 @@[metabase.lib.join.util :as lib.join.util][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation]+ [metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.join :as lib.schema.join]@@ -64,9 +65,18 @@(mu/defn- field-metadata :- [:maybe ::lib.metadata.calculation/visible-column]"Metadata about the field from the metadata provider."[metadata-providerable :- ::lib.schema.metadata/metadata-providerable- field-id :- ::lib.schema.id/field]- (log/debugf "Resolving Field %s from metadata provider" (pr-str field-id))- (when-some [col (lib.metadata/field metadata-providerable field-id)]+ table-id :- [:maybe ::lib.schema.id/table]+ id-or-name :- ::id-or-name]+ (log/debugf "Resolving Field %s from metadata provider" (pr-str id-or-name))+ (when-some [col (cond+ (pos-int? id-or-name)+ (lib.metadata/field metadata-providerable id-or-name)++ (and (string? id-or-name)+ (pos-int? table-id))+ (first (lib.metadata.protocols/metadatas+ (lib.metadata/->metadata-provider metadata-providerable)+ {:lib/type :metadata/column, :table-id table-id, :name #{id-or-name}})))](-> col(assoc :lib/source :source/table-defaults:lib/source-column-alias (:name col)@@ -393,9 +403,11 @@[query :- ::lib.schema/querysource-field-id :- ::lib.schema.id/fieldid-or-name :- ::id-or-name]- (when-some [col (if (pos-int? id-or-name)- (field-metadata query id-or-name)- (resolve-name-in-implicit-join-this-stage query source-field-id id-or-name))]+ ;; don't resolve name refs using [[field-metadata]] here, because it can cause us to trip up when there are multiple+ ;; fks to the same table. See+ ;; [[metabase.lib.field.resolution-test/multiple-remaps-between-tables-test]]+ (when-some [col (or (field-metadata query nil id-or-name)+ (resolve-name-in-implicit-join-this-stage query source-field-id id-or-name))];; if we managed to resolve it then update metadata appropriately.(assoc col:lib/source :source/implicitly-joinable@@ -505,23 +517,24 @@(mu/defn- resolve-from-previous-stage-or-source* :- [:maybe ::lib.metadata.calculation/visible-column][query stage-number id-or-name](b/cond- :let [stage (lib.util/query-stage query stage-number)]- (and (:source-table stage)- (pos-int? id-or-name))- (when-some [col (field-metadata query id-or-name)]+ :let [stage (lib.util/query-stage query stage-number)+ source-table-id (:source-table stage)]++ source-table-id+ (when-some [col (field-metadata query source-table-id id-or-name)];; don't return this field if it's not actually from the source table. We want some of the fallback;; resolution pathways to figure out what join this came from.- (when (= (:table-id col) (:source-table stage))+ (when (= (:table-id col) source-table-id)col));; we maybe have incorrectly used a field name ref when we should have used a field ID ref.;;;; TODO (Cam 8/15/25) -- what happpens if this field is marked inactive? It won't come back from;; `returned-columns`... we'd get fallback metadata, right?- (and (:source-table stage)+ (and source-table-id(string? id-or-name))(m/find-first #(= (:name %) id-or-name)- (lib.metadata.calculation/returned-columns query (lib.metadata/table query (:source-table stage))))+ (lib.metadata.calculation/returned-columns query (lib.metadata/table query source-table-id)))(= (:lib/type stage) :mbql.stage/native)(when-some [col (resolve-in-current-stage-metadata query stage-number id-or-name)]@@ -554,9 +567,9 @@(log/debugf "Failed to find a match in one of the query's joins in stage %s" (pr-str stage-number))nil)))-(defn- fallback-metadata-for-field-id [query stage-number id-or-name]- (when (pos-int? id-or-name)- (when-some [col (field-metadata query id-or-name)]+(defn- fallback-metadata-for-field [query stage-number id-or-name]+ (let [source-table-id (:source-table (lib.util/query-stage query stage-number))]+ (when-some [col (field-metadata query source-table-id id-or-name)](assoc col::fallback-metadata? true:lib/source (if (zero? (lib.util/canonical-stage-index query stage-number))@@ -581,12 +594,12 @@(log/debugf "Resolving %s from previous stage, source table, or source card" (pr-str id-or-name))(let [col (or (resolve-from-previous-stage-or-source* query stage-number id-or-name)(do- (log/infof "Failed to resolve Field %s in stage %s" (pr-str id-or-name) (pr-str stage-number))+ (log/debugf "Failed to resolve Field %s in stage %s. Trying other methods..." (pr-str id-or-name) (pr-str stage-number))(resolve-ref-missing-join-alias query stage-number id-or-name));; if we haven't found a match yet try getting metadata from the metadata provider if this is a;; Field ID ref. It's likely a ref that makes little or no sense (e.g. wrong table) but we can;; let QP code worry about that.- (fallback-metadata-for-field-id query stage-number id-or-name)+ (fallback-metadata-for-field query stage-number id-or-name);; try looking in the expressions in this stage to see if someone incorrectly used a field ref for an;; expression.(maybe-resolve-expression-in-current-stage query stage-number id-or-name)@@ -601,9 +614,9 @@"Resolve metadata for a `:field` ref. This is part of the implementationfor [[metabase.lib.metadata.calculation/metadata-method]] a `:field` clause. Guaranteed to have`:lib/source-column-alias` for wherever the hecc it comes from."- [query :- ::lib.schema/query- stage-number :- :int- [_tag {:keys [source-field join-alias], :as opts} id-or-name, :as field-ref] :- :mbql.clause/field]+ [query :- ::lib.schema/query+ stage-number :- :int+ [_tag {:keys [source-field join-alias], :as opts} id-or-name, :as #?(:clj field-ref :cljs _field-ref)] :- :mbql.clause/field];; this is just for easier debugging(let [stage-number (lib.util/canonical-stage-index query stage-number)](log/debugf "Resolving %s in stage %s" (pr-str id-or-name) (pr-str stage-number))@@ -615,7 +628,7 @@(resolve-in-implicit-join query stage-number source-field id-or-name))(resolve-from-previous-stage-or-source query stage-number id-or-name)(merge- (or (fallback-metadata-for-field-id query stage-number id-or-name)+ (or (fallback-metadata-for-field query stage-number id-or-name)(fallback-metadata id-or-name))(when (and join-alias(contains? (into #{}@@ -625,7 +638,9 @@{:lib/source :source/joins:metabase.lib.join/join-alias join-alias})))(options-metadata opts)- {:lib/original-ref-for-result-metadata-purposes-only field-ref})+ {:lib/original-ref-style-for-result-metadata-purposes (if (pos-int? id-or-name)+ :original-ref-style/id+ :original-ref-style/name)})(as-> $col (assoc $col :display-name (lib.metadata.calculation/display-name query stage-number $col)));; `:lib/desired-column-alias` needs to be recalculated in the context of the stage where the ref;; appears, go ahead and remove it so we don't accidentally try to use it when it may or may not be@@ -639,6 +654,11 @@#?(:clj(u/prog1(when (or config/is-dev? config/is-test?)+ (when (and (:id <>)+ (pos-int? id-or-name)+ (not= (:id <>) id-or-name))+ (throw (ex-info "Resolved column has a different :id"+ {:query query, :stage-number stage-number, :field-ref field-ref, :col <>})))(when (and (= (:lib/source <>) :source/joins)(empty? (:joins (lib.util/query-stage query stage-number))))(throw (ex-info "Stage has no joins, how can source be :source/joins??"@@ -647,8 +667,8 @@(#{:source/table-defaults :source/native} (:lib/source <>)))(throw (ex-info "A column can only come from a :source-table or native query in the first stage of a query"{:query query, :stage-number stage-number, :field-ref field-ref, :col <>})))- (when-let [source-field (:source-field opts)]- (when-let [resolved-source-field ((some-fn :fk-field-id :lib/original-fk-field-id) <>)]+ (when-some [source-field (:source-field opts)]+ (when-some [resolved-source-field ((some-fn :fk-field-id :lib/original-fk-field-id) <>)](when-not (= resolved-source-field source-field)(throw (ex-info "Resolved column has different :source-field"{:query query, :stage-number stage-number, :field-ref field-ref, :col <>})))))))))))diff --git a/src/metabase/lib/metadata.cljc b/src/metabase/lib/metadata.cljcindex 3f54a586367..47d12242bf1 100644--- a/src/metabase/lib/metadata.cljc+++ b/src/metabase/lib/metadata.cljc@@ -43,11 +43,29 @@table-id :- ::lib.schema.id/table](lib.metadata.protocols/table (->metadata-provider metadata-providerable) table-id))+(defn- fields* [metadata-providerable table-id {:keys [only-active?]}]+ (-> (lib.metadata.protocols/fields (->metadata-provider metadata-providerable) table-id)+ (cond->> only-active?+ (remove (fn [col]+ (or (false? (:active col))+ (#{:sensitive :retired} (:visibility-type col))))))+ (->> (sort-by (juxt #(:position % 0) #(u/lower-case-en (:name % "")))))))+(mu/defn fields :- [:sequential ::lib.schema.metadata/column]"Get metadata about all the Fields belonging to a specific Table."[metadata-providerable :- ::lib.schema.metadata/metadata-providerabletable-id :- ::lib.schema.id/table]- (lib.metadata.protocols/fields (->metadata-provider metadata-providerable) table-id))+ (fields* metadata-providerable table-id {:only-active? false}))++(mu/defn active-fields :- [:sequential ::lib.schema.metadata/column]+ "Like [[fields]], but filters out any Fields that are not `:active` or with `:visibility-type`s that mean they+ should not be included in queries.++ These fields are the ones we use for default `:fields`, which becomes the default `SELECT ...` (or equivalent) when+ building a query."+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable+ table-id :- ::lib.schema.id/table]+ (fields* metadata-providerable table-id {:only-active? true}))(mu/defn metadatas-for-table :- [:maybe [:sequential [:or::lib.schema.metadata/columndiff --git a/src/metabase/lib/metadata/result_metadata.cljc b/src/metabase/lib/metadata/result_metadata.cljcindex eb6a2654084..84d44e6079f 100644--- a/src/metabase/lib/metadata/result_metadata.cljc+++ b/src/metabase/lib/metadata/result_metadata.cljc@@ -282,19 +282,37 @@col :- ::kebab-cased-map](when (= (:lib/type col) :metadata/column)(let [remove-join-alias? (remove-join-alias-from-broken-field-ref? query col)]- (-> (if-let [original-ref (:lib/original-ref-for-result-metadata-purposes-only col)]- (cond-> original-ref- remove-join-alias? (lib.join/with-join-alias nil))- (binding [lib.ref/*ref-style* :ref.style/broken-legacy-qp-results]- (let [col (cond-> col- remove-join-alias? (lib.join/with-join-alias nil)- remove-join-alias? (assoc ::remove-join-alias? true))]- (->> (merge- col- (when-not remove-join-alias?- (when-let [previous-join-alias (:lib/original-join-alias col)]- {:metabase.lib.join/join-alias previous-join-alias, :lib/source :source/joins})))- lib.ref/ref))))+ (-> (binding [lib.ref/*ref-style* :ref.style/broken-legacy-qp-results]+ (let [col (cond-> col+ remove-join-alias? (-> (lib.join/with-join-alias nil)+ (assoc ::remove-join-alias? true)))+ [tag opts id-or-name, :as field-ref] (->> (merge+ col+ (when-not remove-join-alias?+ (when-let [previous-join-alias (:lib/original-join-alias col)]+ {:metabase.lib.join/join-alias previous-join-alias, :lib/source :source/joins})))+ lib.ref/ref)]+ (cond+ ;; if original ref in the query used an ID then `:field-ref` should as well for historic+ ;; reasons.+ (and (or (= (:lib/original-ref-style-for-result-metadata-purposes col) :original-ref-style/id)+ ;; for historic reasons implicit fields should also come back with ID refs...+ ;; traditionally that's what the middleware added+ (and (:id col)+ (:qp/implicit-field? col))+ (and (:id col)+ ;; don't force ID refs when it would result in duplicates (probably not+ ;; needed since [[deduplicate-field-refs]] will fix this anyway?)+ (= (:lib/deduplicated-name col) (:lib/original-name col))+ (not (= (:lib/original-ref-style-for-result-metadata-purposes col) :original-ref-style/name))))+ (string? id-or-name))+ [tag (dissoc opts :base-type) (:id col)]++ (pos-int? id-or-name)+ [tag (dissoc opts :base-type) id-or-name]++ :else+ field-ref)));; broken legacy field refs in results medtadata should never have `:effective-type`(lib.options/update-options dissoc :effective-type)lib.convert/->legacy-MBQL@@ -403,7 +421,7 @@;;; keep it around but I don't have time to update a million tests. Why do columns have `:lib/uuid` anyway? They;;; should maybe have `:lib/source-uuid` but I don't think they should have `:lib/uuid`.(defn- remove-lib-uuids [col]- (dissoc col :lib/uuid :lib/source-uuid :lib/original-ref-for-result-metadata-purposes-only))+ (dissoc col :lib/uuid :lib/source-uuid :lib/original-ref-style-for-result-metadata-purposes))(mu/defn- col->legacy-metadata :- ::kebab-cased-map"Convert Lib-style `:metadata/column` column metadata to the `snake_case` legacy format we've come to know and lovediff --git a/src/metabase/lib/schema/metadata.cljc b/src/metabase/lib/schema/metadata.cljcindex 9b61d49380d..97b682c52aa 100644--- a/src/metabase/lib/schema/metadata.cljc+++ b/src/metabase/lib/schema/metadata.cljc@@ -501,7 +501,18 @@;; in [[metabase.lib-be.metadata.jvm]]. I don't think this is really needed on the FE, at any rate the JS metadata;; provider doesn't add these keys.[:lib/external-remap {:optional true} [:maybe [:ref ::column.remapping.external]]]- [:lib/internal-remap {:optional true} [:maybe [:ref ::column.remapping.internal]]]]+ [:lib/internal-remap {:optional true} [:maybe [:ref ::column.remapping.internal]]]+ ;;+ ;; The [[metabase.query-processor.middleware.add-implicit-clauses/add-implicit-fields]] middleware adds+ ;; `:qp/added-implicit-fields?` to stages where it adds implicit fields,+ ;; then [[metabase.lib.stage/fields-columns]] adds this key to any col from such a+ ;; stage. [[metabase.lib.metadata.result-metadata/super-broken-legacy-field-ref]] uses this to know to force Field+ ;; ID refs for QP `:field_ref` in results metadata to preserve historic behavior to avoid breaking legacy viz+ ;; settings that use it as a key.+ [:qp/implicit-field? {:optional true} [:maybe :boolean]]]+ ;;+ ;; Additional constraints+ ;;;; TODO (Cam 6/13/25) -- go add this to some of the other metadata schemas as well.::kebab-cased-map[:ref ::column.validate-for-source]])diff --git a/src/metabase/lib/schema/parameter.cljc b/src/metabase/lib/schema/parameter.cljcindex cc0c7015fe9..7642f9744d2 100644--- a/src/metabase/lib/schema/parameter.cljc+++ b/src/metabase/lib/schema/parameter.cljc@@ -245,6 +245,8 @@:error/fn (fn [{:keys [value]} _](str "Invalid parameter :target, must be either :field, :dimension, or :variable; got: "(pr-str value)))}+ ;; TODO (Cam 9/12/25) -- the old legacy MBQL schema also said `:expression` refs where allowed here, but I don't+ ;; know if we actually did allow that in practice.[:field [:ref ::legacy-field-ref]][:dimension [:ref ::dimension]][:variable [:ref ::variable]]])@@ -262,6 +264,8 @@param))))(mr/def ::parameter+ "Schema for the *value* of a parameter (e.g. a Dashboard parameter or a native query template tag) as passed in as+ part of the `:parameters` list in a query."[:and[:map{:decode/normalize normalize-parameter}@@ -285,4 +289,5 @@{:dimension ":dimension is not allowed in a parameter, you probably meant to use :target [:dimension ...] instead."})])(mr/def ::parameters+ "Schema for a list of `:parameters` as passed in to a query."[:sequential [:ref ::parameter]])diff --git a/src/metabase/lib/stage.cljc b/src/metabase/lib/stage.cljcindex 054ada5a2e9..029e82fb2bd 100644--- a/src/metabase/lib/stage.cljc+++ b/src/metabase/lib/stage.cljc@@ -88,14 +88,21 @@[query :- ::lib.schema/querystage-number :- :intoptions :- [:maybe ::lib.metadata.calculation/returned-columns.options]]- (when-let [{fields :fields} (lib.util/query-stage query stage-number)]- (-> (for [[tag :as ref-clause] fields- :let [col (lib.metadata.calculation/metadata query stage-number ref-clause)]]- (cond-> col- (= tag :expression) (assoc :lib/source :source/expressions- :lib/source-column-alias (:lib/expression-name col))))- (as-> $cols (concat $cols (lib.metadata.calculation/remapped-columns query stage-number $cols options)))- not-empty)))+ (let [stage (lib.util/query-stage query stage-number)+ ;; this key is added by [[metabase.query-processor.middleware.add-implicit-clauses/add-implicit-fields]]; we+ ;; forward it as `:qp/implicit-field?`+ ;; so [[metabase.lib.metadata.result-metadata/super-broken-legacy-field-ref]] will know to force Field ID+ ;; `:field_ref`s in the QP results metadata to preserve historic behavior+ added-implicitly? (:qp/added-implicit-fields? stage)]+ (when-let [{fields :fields} stage]+ (-> (for [[tag :as ref-clause] fields+ :let [col (lib.metadata.calculation/metadata query stage-number ref-clause)]]+ (cond-> col+ (= tag :expression) (assoc :lib/source :source/expressions+ :lib/source-column-alias (:lib/expression-name col))+ added-implicitly? (assoc :qp/implicit-field? true)))+ (as-> $cols (concat $cols (lib.metadata.calculation/remapped-columns query stage-number $cols options)))+ not-empty))))(mu/defn- summary-columns :- [:maybe ::lib.metadata.calculation/visible-columns][query :- ::lib.schema/querydiff --git a/src/metabase/lib/table.cljc b/src/metabase/lib/table.cljcindex 80c1b17ba41..47c2b303840 100644--- a/src/metabase/lib/table.cljc+++ b/src/metabase/lib/table.cljc@@ -4,7 +4,6 @@[metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation][metabase.lib.util :as lib.util]- [metabase.util :as u][metabase.util.humanization :as u.humanization][metabase.util.i18n :as i18n][metabase.util.malli :as mu]))@@ -29,25 +28,9 @@(lib.metadata.calculation/display-name query stage-number table-metadata :long))(i18n/tru "Table {0}" (pr-str source-table))))))-(def ^:private ^{:arglists '([rf])} remove-hidden-default-fields-xform- "Remove Fields that shouldn't be visible from the default Fields for a source Table.- See [[metabase.query-processor.middleware.add-implicit-clauses/table->sorted-fields*]]."- (remove (fn [{:keys [visibility-type], active? :active, :as _col}]- (or (false? active?)- (#{:sensitive :retired} (some-> visibility-type keyword))))))--(defn- sort-default-fields- "Sort default Fields for a source Table. See [[metabase.warehouse-schema.models.table/field-order-rule]]."- [field-metadatas]- (sort-by (fn [{field-name :name, :keys [position], :as _field-metadata}]- [(or position 0) (u/lower-case-en (or field-name ""))])- field-metadatas))-(mu/defmethod lib.metadata.calculation/returned-columns-method :metadata/table :- ::lib.metadata.calculation/returned-columns[query _stage-number table-metadata _options]- (when-let [cols (lib.metadata/fields query (:id table-metadata))]- (into []- (comp remove-hidden-default-fields-xform- (map #(assoc % :lib/source :source/table-defaults))- (lib.field.util/add-source-and-desired-aliases-xform query))- (sort-default-fields cols))))+ (into []+ (comp (map #(assoc % :lib/source :source/table-defaults))+ (lib.field.util/add-source-and-desired-aliases-xform query))+ (lib.metadata/active-fields query (:id table-metadata))))diff --git a/src/metabase/parameters/dashboard.clj b/src/metabase/parameters/dashboard.cljindex e3c7ea2eac1..094b9964b21 100644--- a/src/metabase/parameters/dashboard.clj+++ b/src/metabase/parameters/dashboard.clj@@ -3,7 +3,6 @@[medley.core :as m][metabase.api.common :as api][metabase.legacy-mbql.normalize :as mbql.normalize]- [metabase.legacy-mbql.schema :as mbql.s][metabase.legacy-mbql.util :as mbql.u][metabase.lib.schema.parameter :as lib.schema.parameter][metabase.parameters.chain-filter :as chain-filter]@@ -32,7 +31,7 @@{:case-sensitive false}))(mu/defn- param->fields- [param :- mbql.s/Parameter]+ [param :- ::lib.schema.parameter/parameter](let [op (param-type->op (:type param))options (or (:options param) (param-type->default-options (:type param)))](for [field-id (params/dashboard-param->field-ids param)]diff --git a/src/metabase/query_processor/api.clj b/src/metabase/query_processor/api.cljindex 24ecdbf2fb1..61cfbb7880d 100644--- a/src/metabase/query_processor/api.clj+++ b/src/metabase/query_processor/api.clj@@ -6,6 +6,9 @@[metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.events.core :as events]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.info :as lib.schema.info]diff --git a/src/metabase/query_processor/card.clj b/src/metabase/query_processor/card.cljindex b7a56148fb1..2da9138c64f 100644--- a/src/metabase/query_processor/card.clj+++ b/src/metabase/query_processor/card.clj@@ -5,8 +5,11 @@[medley.core :as m][metabase.api.common :as api][metabase.cache.core :as cache]+ ;; legacy usages -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.normalize :as mbql.normalize]- [metabase.legacy-mbql.schema :as mbql.s]+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.util :as mbql.u][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.info :as lib.schema.info]@@ -216,7 +219,7 @@"Unless [[*allow-arbitrary-mbql-parameters*]] is truthy, check to make all supplied `parameters` actually match upwith template tags in the query for Card with `card-id`."[card-id :- ::lib.schema.id/card- parameters :- mbql.s/ParameterList]+ parameters :- [:maybe [:ref ::lib.schema.parameter/parameters]]](when-not *allow-arbitrary-mbql-parameters*(let [template-tags (card-template-tag-parameters card-id)](doseq [request-parameter parametersdiff --git a/src/metabase/query_processor/dashboard.clj b/src/metabase/query_processor/dashboard.cljindex 9be9f490376..1255b621cd2 100644--- a/src/metabase/query_processor/dashboard.clj+++ b/src/metabase/query_processor/dashboard.clj@@ -5,6 +5,9 @@[medley.core :as m][metabase.api.common :as api][metabase.events.core :as events]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib.schema.id :as lib.schema.id][metabase.query-processor.card :as qp.card]diff --git a/src/metabase/query_processor/metadata.clj b/src/metabase/query_processor/metadata.cljindex 0ac60ba6ded..ae57b8eeecc 100644--- a/src/metabase/query_processor/metadata.clj+++ b/src/metabase/query_processor/metadata.clj@@ -7,7 +7,11 @@[metabase.analyze.core :as analyze][metabase.driver :as driver][metabase.driver.util :as driver.u]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.normalize :as mbql.normalize]+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib-be.metadata.jvm :as lib.metadata.jvm][metabase.lib.core :as lib]diff --git a/src/metabase/query_processor/middleware/add_default_temporal_unit.clj b/src/metabase/query_processor/middleware/add_default_temporal_unit.cljindex cc187bffdb6..c96eee1204d 100644--- a/src/metabase/query_processor/middleware/add_default_temporal_unit.clj+++ b/src/metabase/query_processor/middleware/add_default_temporal_unit.clj@@ -14,7 +14,7 @@query(fn [query _path-type path clause](when (and (lib.util/clause-of-type? clause :field)- (not (:temporal-unit (lib/options clause)))+ (not (lib/raw-temporal-bucket clause))(isa? (lib.walk/apply-f-for-stage-at-path lib/type-of query path clause) :type/Temporal))(lib/with-temporal-bucket clause :default)))))diff --git a/src/metabase/query_processor/middleware/add_implicit_clauses.clj b/src/metabase/query_processor/middleware/add_implicit_clauses.cljindex 296e9587745..d8dbe42e2ff 100644--- a/src/metabase/query_processor/middleware/add_implicit_clauses.clj+++ b/src/metabase/query_processor/middleware/add_implicit_clauses.clj@@ -1,247 +1,91 @@(ns metabase.query-processor.middleware.add-implicit-clauses"Middlware for adding an implicit `:fields` and `:order-by` clauses to certain queries."(:require- [clojure.walk :as walk]- [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.result-metadata :as lib.metadata.result-metadata]- [metabase.lib.schema.id :as lib.schema.id]+ [metabase.lib.schema :as lib.schema][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.middleware.annotate.legacy-helper-fns :as annotate.legacy-helper-fns]- [metabase.query-processor.store :as qp.store]- [metabase.util :as u][metabase.util.i18n :refer [tru]]- [metabase.util.log :as log][metabase.util.malli :as mu]))-;;; +----------------------------------------------------------------------------------------------------------------+-;;; | Add Implicit Fields |-;;; +----------------------------------------------------------------------------------------------------------------+--(defn- table->sorted-fields- "Return a sequence of all Fields for table that we'd normally include in the equivalent of a `SELECT *`."- [table-id]- (->> (lib.metadata/fields (qp.store/metadata-provider) table-id)- (remove #(#{:sensitive :retired} (:visibility-type %)))- (sort-by (juxt :position (comp u/lower-case-en :name)))))--(mu/defn sorted-implicit-fields-for-table :- mbql.s/Fields- "For use when adding implicit Field IDs to a query. Return a sequence of field clauses, sorted by the rules listed- in [[metabase.query-processor.sort]], for all the Fields in a given Table."- [table-id :- ::lib.schema.id/table]- (let [fields (table->sorted-fields table-id)]- (when (empty? fields)- (throw (ex-info (tru "No fields found for table {0}." (pr-str (:name (lib.metadata/table (qp.store/metadata-provider) table-id))))- {:table-id table-id- :type qp.error-type/invalid-query})))- (mapv- (fn [field]- ;; implicit datetime Fields get bucketing of `:default`. This is so other middleware doesn't try to give it- ;; default bucketing of `:day`- [:field (u/the-id field) nil])- fields)))--(defn- multiply-bucketed-field-refs- [source-metadata]- (->> source-metadata- (map :field_ref)- (group-by #(some-> % (mbql.u/update-field-options dissoc :binning :temporal-unit :original-temporal-unit)))- (reduce-kv (fn [duplicates ref-key field-refs]- (cond-> duplicates- (and ref-key (next field-refs))- (into (filter (comp (some-fn :binning :temporal-unit) #(get % 2))) field-refs)))- #{})))--(mu/defn- source-metadata->fields :- mbql.s/Fields- "Get implicit Fields for a query with a `:source-query` that has `source-metadata`."- [source-metadata :- [:sequential {:min 1} ::mbql.s/legacy-column-metadata]]- ;; We want to allow columns to be bucketed or binned in several different ways.- ;; Such columns would be collapsed into a single column if referenced by ID,- ;; so we make sure that they get a reference by name, which is unique.- (let [multiply-bucketed-refs (multiply-bucketed-field-refs source-metadata)]- (distinct- (for [{field-name :name- base-type :base_type- field-id :id- [ref-type :as field-ref] :field_ref- unit :unit- coercion-strategy :coercion_strategy} source-metadata]- ;; return field-ref directly if it's a `:field` clause already. It might include important info such as- ;; `:join-alias` or `:source-field`. Remove binning/temporal bucketing info. The Field should already be getting- ;; bucketed in the source query; don't need to apply bucketing again in the parent query. Mark the field as- ;; `qp/ignore-coercion` here so that it doesn't happen again in the parent query.- (let [not-multiply-bracketed? (not (contains? multiply-bucketed-refs field-ref))]- (or (and not-multiply-bracketed?- (some-> (lib.util.match/match-one field-ref :field)- (mbql.u/update-field-options dissoc :binning :temporal-unit)- (cond->- (or coercion-strategy- (and (pos-int? field-id)- (some-> (qp.store/metadata-provider)- (lib.metadata/field field-id)- :coercion-strategy)))- (mbql.u/assoc-field-options :qp/ignore-coercion true)-- unit- (mbql.u/assoc-field-options :inherited-temporal-unit unit))))- ;; otherwise construct a field reference that can be used to refer to this Field.- ;; Force string id field if expression contains just field. See issue #28451.- (if (and (not= ref-type :expression)- not-multiply-bracketed?- field-id)- ;; If we have a Field ID, return a `:field` (id) clause- [:field field-id (cond-> nil- coercion-strategy (assoc :qp/ignore-coercion true)- unit (assoc :inherited-temporal-unit unit))]- ;; otherwise return a `:field` (name) clause, e.g. for a Field that's the result of an aggregation or- ;; expression. We don't need to mark as ignore-coercion here because these won't grab the field metadata- [:field field-name {:base-type base-type}])))))))-(mu/defn- should-add-implicit-fields?- "Whether we should add implicit Fields to this query. True if all of the following are true:+ "Whether we should add implicit Fields to a `stage`. True if all of the following are true:- * The query has either a `:source-table`, *or* a `:source-query` with `:source-metadata` for it- * The query has no breakouts- * The query has no aggregations"- [{:keys [fields source-table source-query source-metadata]+ * The stage is an MBQL stage+ * The stage has no breakouts+ * The stage has no aggregations+ * The stage does not already have `:fields`"+ [{:keys [fields]breakouts :breakout- aggregations :aggregation} :- mbql.s/MBQLQuery]- ;; if someone is trying to include an explicit `source-query` but isn't specifiying `source-metadata` warn that- ;; there's nothing we can do to help them- (when (and source-query- (empty? source-metadata)- (qp.store/initialized?))- ;; by 'caching' this result, this log message will only be shown once for a given QP run.- ;;- ;; deprecated usage- #_{:clj-kondo/ignore [:deprecated-var]}- (qp.store/cached [::should-add-implicit-fields-warning]- (log/warn (str "Warning: cannot determine fields for an explicit `source-query` unless you also include"- " `source-metadata`.\n"- (format "Query: %s" (u/pprint-to-str source-query))))))- ;; Determine whether we can add the implicit `:fields`- (and (or source-table- (and source-query (seq source-metadata)))+ aggregations :aggregation, :as stage} :- ::lib.schema/stage]+ (and (= (:lib/type stage) :mbql.stage/mbql)(every? empty? [aggregations breakouts fields])))-(mu/defn- add-implicit-fields- "For MBQL queries with no aggregation, add a `:fields` key containing all Fields in the source Table as well as any- expressions definied in the query."- [{source-table-id :source-table, :keys [expressions], :as inner-query}]- ;; calculate metadata if needed for MBQL source queries.- (let [inner-query (or (when (and (:source-query inner-query)- (not (:source-metadata inner-query))- (not (:native (:source-query inner-query))))- (when-let [cols (->> (annotate.legacy-helper-fns/legacy-inner-query->mlv2-query (:source-query inner-query))- lib.metadata.result-metadata/returned-columns- (mapv lib/lib-metadata-column->legacy-metadata-column)- not-empty)]- (log/infof "Calculated result metadata for source query: %s" (pr-str (mapv :lib/desired-column-alias cols)))- (assoc inner-query :source-metadata cols)))- inner-query)]- (if-not (should-add-implicit-fields? inner-query)- inner-query- (let [fields (if source-table-id- (or (not-empty (sorted-implicit-fields-for-table source-table-id))- ;; if the Table has no Fields, throw an Exception, because there is no way for us to- ;; proceed- (throw (ex-info (tru "Table ''{0}'' has no Fields associated with it."- (:name (lib.metadata/table (qp.store/metadata-provider) source-table-id)))- {:type qp.error-type/invalid-query})))- (or (not-empty (source-metadata->fields (:source-metadata inner-query)))- (throw (ex-info "source-metadata->fields unexpectedly returned zero fields"- {:inner-query inner-query, :type qp.error-type/qp}))))- ;; generate a new expression ref clause for each expression defined in the query.- expressions (for [[expression-name] expressions]- ;; TODO - we need to wrap this in `u/qualified-name` because `:expressions` uses- ;; keywords as keys. We can remove this call once we fix that.- [:expression (u/qualified-name expression-name)])]- ;; add the fields & expressions under the `:fields` clause- (assoc inner-query :fields (vec (concat fields expressions)))))))--;;; +----------------------------------------------------------------------------------------------------------------+-;;; | Add Implicit Breakout Order Bys |-;;; +----------------------------------------------------------------------------------------------------------------+--(defn- fix-order-by-field-refs- "This function transforms top level integer field refs in order by to corresponding string field refs from breakout- if present.-- ## Context- In current situation, ie. model as a source, then aggregation and breakout, and finally order by a breakout field,- [[metabase.lib.order-by/orderable-columns]] returns field ref with integer id, while reference to same field, but- with string id is present in breakout. Then, [[add-implicit-breakout-order-by]] adds the string ref to order by.-- Resulting query would contain both references, while integral is transformed differently -- it contains no casting.- As that is not part of group by, the query would fail.-- Reference: https://github.com/metabase/metabase/issues/44653."- [{:keys [breakout order-by] :as inner-query}]- (if (or (empty? breakout) (empty? order-by))- inner-query- (let [name->breakout (into {}- (keep (fn [[tag id-or-name :as clause]]- (when (and (= :field tag)- (string? id-or-name))- [id-or-name clause])))- breakout)- ref->maybe-field-name (fn [[tag id-or-name]]- (when (and (= :field tag)- (integer? id-or-name))- ((some-fn :lib/desired-column-alias :name)- (lib.metadata/field (qp.store/metadata-provider)- id-or-name))))- maybe-convert-order-by-ref (fn [[dir ref :as order-by-elm]]- (if-some [breakout (-> ref ref->maybe-field-name name->breakout)]- [dir breakout]- order-by-elm))]- (update inner-query :order-by (partial mapv maybe-convert-order-by-ref)))))--(defn- has-window-function-aggregations? [inner-query]- (or (lib.util.match/match (mapcat inner-query [:aggregation :expressions])+(mu/defn- add-implicit-fields :- [:maybe ::lib.schema/stage]+ "For stages with no aggregation, add a `:fields` key containing all Fields in the source Table as well as any+ expressions defined in the stage."+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ {source-table-id :source-table, :as stage} :- ::lib.schema/stage]+ (when (should-add-implicit-fields? stage)+ (let [cols (if source-table-id+ (lib/returned-columns query (lib.metadata/table query source-table-id))+ (for [col (lib.walk/apply-f-for-stage-at-path+ lib/returned-columns+ query+ (or (lib.walk/previous-path path)+ (throw (ex-info "Expected :source-card to be spliced into the query by now"+ {:type qp.error-type/invalid-query}))))]+ (lib/update-keys-for-col-from-previous-stage col)))+ ;; generate a new expression ref clause for each expression defined in the query.+ expressions (lib.walk/apply-f-for-stage-at-path lib/expressions-metadata query path)]+ ;; if the Table has no Fields, throw an Exception, because there is no way for us to proceed+ (when (and (empty? cols)+ source-table-id)+ (throw (ex-info (tru "Table ''{0}'' has no Fields associated with it." (:name (lib.metadata/table query source-table-id)))+ {:type qp.error-type/invalid-query})))+ ;; add the fields & expressions under the `:fields` clause+ (when (seq cols)+ (letfn [(updated-stage [query stage-number]+ (-> (lib/with-fields query stage-number (concat cols expressions))+ (lib/query-stage stage-number)+ ;; this is used+ ;; by [[metabase.lib.metadata.result-metadata/super-broken-legacy-field-ref]] (via [[metabase.lib.stage/fields-columns]])+ ;; so it knows to force Field ID `:field_ref`s in the QP results metadata to preserve historic+ ;; behavior+ (assoc :qp/added-implicit-fields? true)))]+ (lib.walk/apply-f-for-stage-at-path updated-stage (assoc-in query path stage) path))))))++(defn- has-window-function-aggregations? [stage]+ (or (lib.util.match/match (mapcat stage [:aggregation :expressions])#{:cum-sum :cum-count :offset}true)- (when-let [source-query (:source-query inner-query)]+ ;; FIXME+ (when-let [source-query (:source-query stage)](has-window-function-aggregations? source-query))))-(mu/defn- add-implicit-breakout-order-by :- mbql.s/MBQLQuery+(mu/defn- add-implicit-breakout-order-by :- [:maybe ::lib.schema/stage]"Fields specified in `breakout` should add an implicit ascending `order-by` subclause *unless* that Field is already*explicitly* referenced in `order-by`."- [inner-query :- mbql.s/MBQLQuery]- ;; Add a new [:asc <breakout-field>] clause for each breakout. The cool thing is `add-order-by-clause` will- ;; automatically ignore new ones that are reference Fields already in the order-by clause- (let [{breakouts :breakout, :as inner-query} (fix-order-by-field-refs inner-query)]- (reduce mbql.u/add-order-by-clause inner-query (when-not (has-window-function-aggregations? inner-query)- (for [breakout breakouts]- [:asc breakout])))))--;;; +----------------------------------------------------------------------------------------------------------------+-;;; | Middleware |-;;; +----------------------------------------------------------------------------------------------------------------+--(defn add-implicit-mbql-clauses- "Add implicit clauses such as `:fields` and `:order-by` to an 'inner' MBQL query as needed."- [form]- (walk/postwalk- (fn [form]- ;; add implicit clauses to any 'inner query', except for joins themselves (we should still add implicit clauses- ;; like `:fields` to source queries *inside* joins)- (if (and (map? form)- ((some-fn :source-table :source-query) form)- (not (:condition form)))- (-> form add-implicit-breakout-order-by add-implicit-fields)- form))- form))--;;; TODO (Cam 7/25/25) -- once this is converted to use Lib we can-;;; remove [[metabase.query-processor.middleware.ensure-joins-use-source-query/ensure-joins-use-source-query]]-(mu/defn add-implicit-clauses :- ::mbql.s/Query+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ stage :- ::lib.schema/stage]+ (when-not (has-window-function-aggregations? stage)+ (when-let [breakouts (not-empty (:breakout stage))]+ (letfn [(updated-stage [query stage-number]+ (-> (reduce (fn [query breakout]+ (lib/order-by query stage-number (lib/fresh-uuids breakout) :asc))+ query+ breakouts)+ (lib/query-stage stage-number)))]+ (lib.walk/apply-f-for-stage-at-path updated-stage (assoc-in query path stage) path)))))++(mu/defn add-implicit-clauses :- ::lib.schema/query"Add an implicit `fields` clause to queries with no `:aggregation`, `breakout`, or explicit `:fields` clauses.Add implicit `:order-by` clauses for fields specified in a `:breakout`."- [{query-type :type, :as query} :- ::mbql.s/Query]- (if (= query-type :native)- query- (update query :query add-implicit-mbql-clauses)))+ [query :- ::lib.schema/query]+ (-> query+ (lib.walk/walk-stages add-implicit-breakout-order-by)+ (lib.walk/walk-stages add-implicit-fields)))diff --git a/src/metabase/query_processor/middleware/add_source_metadata.clj b/src/metabase/query_processor/middleware/add_source_metadata.cljindex 049e84c80fd..7741ab5bcfc 100644--- a/src/metabase/query_processor/middleware/add_source_metadata.clj+++ b/src/metabase/query_processor/middleware/add_source_metadata.clj@@ -1,7 +1,11 @@(ns metabase.query-processor.middleware.add-source-metadata(:require[clojure.walk :as walk]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s]+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.util :as mbql.u][metabase.lib.metadata :as lib.metadata][metabase.lib.util.match :as lib.util.match]diff --git a/src/metabase/query_processor/middleware/annotate.clj b/src/metabase/query_processor/middleware/annotate.cljindex 681d6f01e91..1c2e8f3ed5b 100644--- a/src/metabase/query_processor/middleware/annotate.clj+++ b/src/metabase/query_processor/middleware/annotate.clj@@ -3,6 +3,8 @@(:require[metabase.analyze.core :as analyze][metabase.driver.common :as driver.common]+ ;; allowed because `:field_ref` is supposed to be a legacy field ref for backward compatibility purposes+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.core :as lib][metabase.lib.metadata.result-metadata :as lib.metadata.result-metadata]diff --git a/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj b/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.cljindex c7fabc59411..fdc657c7522 100644--- a/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj+++ b/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj@@ -5,6 +5,8 @@I'm keeping them around for now so drivers can continue to use them until we work on converting drivers to MLv2 (atwhich point they can use MLv2 directly)."(:require+ ;; existing legacy usage -- don't use legacy MBQL namespaces in QP going forward+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]diff --git a/src/metabase/query_processor/middleware/auto_bucket_datetimes.clj b/src/metabase/query_processor/middleware/auto_bucket_datetimes.cljindex 4d2874747f7..1fe572d8b07 100644--- a/src/metabase/query_processor/middleware/auto_bucket_datetimes.clj+++ b/src/metabase/query_processor/middleware/auto_bucket_datetimes.clj@@ -4,12 +4,12 @@`yyyy-MM-dd` format datetime strings."(:require[medley.core :as m]- [metabase.legacy-mbql.util :as mbql.u][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.util :as lib.util][metabase.lib.util.match :as lib.util.match][metabase.lib.walk :as lib.walk][metabase.util.log :as log]@@ -63,13 +63,13 @@(defn- auto-bucketable-value? [v](or (yyyy-MM-dd-date-string? v)- (mbql.u/is-clause? :relative-datetime v)))+ (lib.util/clause-of-type? v :relative-datetime)))(mu/defn- filter-clause?[query :- ::lib.schema/querystage-path :- ::lib.walk/stage-pathx]- (and (mbql.u/mbql-clause? x)+ (and (lib.util/clause? x)(when-let [expr-type (try(lib.walk/apply-f-for-stage-at-path lib/type-of query stage-path x)(catch Throwable e@@ -82,7 +82,7 @@stage-path :- ::lib.walk/stage-pathx](and (filter-clause? query stage-path x)- (not (mbql.u/is-clause? #{:and :or :not} x))))+ (not (lib.util/clause-of-type? x #{:and :or :not}))))(mr/def ::do-not-bucket-reason[:and@@ -103,7 +103,7 @@(cond;; * is not an equality or comparison filter. e.g. wouldn't make sense to bucket a field and then check if it is;; `NOT NULL`- (not (mbql.u/is-clause? #{:= :!= :< :> :<= :>= :between} x))+ (not (lib.util/clause-of-type? x #{:= :!= :< :> :<= :>= :between})):do-not-bucket-reason/not-equality-or-comparison-filter;; * has arguments that aren't `yyyy-MM-dd` date strings. The only reason we auto-bucket datetime clauses in the@@ -123,12 +123,12 @@;; do not auto-bucket clauses inside a `:time-interval` filter: it already supplies its own unit;; do not auto-bucket clauses inside a `:datetime-diff` clause: the precise timestamp is needed for the difference- (mbql.u/is-clause? #{:time-interval :datetime-diff} x)+ (lib.util/clause-of-type? x #{:time-interval :datetime-diff}):do-not-bucket-reason/bucketed-or-precise-operation;; do not autobucket clauses that already have a temporal unit, or have a binning strategy- (and (or (mbql.u/is-clause? :expression x)- (mbql.u/is-clause? :field x))+ (and (or (lib.util/clause-of-type? x :expression)+ (lib.util/clause-of-type? x :field))(let [[_tag opts _id-or-name] x]((some-fn :temporal-unit :binning) opts))):do-not-bucket-reason/field-with-bucketing-or-binning@@ -169,11 +169,11 @@;; if it's a `:field` clause and `field-id->type-info` tells us it's a `:type/Temporal` (but not;; `:type/Time`), then go ahead and replace it- [:field opts (id-or-name :guard datetime-but-not-time?)]- [:field (assoc opts :temporal-unit :day) id-or-name]+ [:field _opts (_id-or-name :guard datetime-but-not-time?)]+ (lib/with-temporal-bucket &match :day)- [:expression (opts :guard (comp date-or-datetime-clause? expression-opts->type-info)) name']- [:expression (assoc opts :temporal-unit :day) name']))+ [:expression (_opts :guard (comp date-or-datetime-clause? expression-opts->type-info)) _name]+ (lib/with-temporal-bucket &match :day)))(rewrite-clause [stage clause-to-rewrite](m/update-existing stage clause-to-rewrite wrap-clauses))](-> stagediff --git a/src/metabase/query_processor/middleware/check_features.clj b/src/metabase/query_processor/middleware/check_features.cljindex 2a8dc30cb37..d1bdc96cd4e 100644--- a/src/metabase/query_processor/middleware/check_features.clj+++ b/src/metabase/query_processor/middleware/check_features.clj@@ -2,6 +2,9 @@(:require[metabase.driver :as driver][metabase.driver.util :as driver.u]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.metadata :as lib.metadata][metabase.lib.util.match :as lib.util.match]diff --git a/src/metabase/query_processor/middleware/cumulative_aggregations.clj b/src/metabase/query_processor/middleware/cumulative_aggregations.cljindex 3864042a3bc..224ffe7ff0c 100644--- a/src/metabase/query_processor/middleware/cumulative_aggregations.clj+++ b/src/metabase/query_processor/middleware/cumulative_aggregations.clj@@ -19,6 +19,9 @@(:require[metabase.driver :as driver][metabase.driver.util :as driver.u]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.metadata :as lib.metadata][metabase.lib.util.match :as lib.util.match]diff --git a/src/metabase/query_processor/middleware/resolve_joined_fields.clj b/src/metabase/query_processor/middleware/fix_bad_field_id_refs.cljsimilarity index 80%rename from src/metabase/query_processor/middleware/resolve_joined_fields.cljrename to src/metabase/query_processor/middleware/fix_bad_field_id_refs.cljindex 1d9875f965d..f9a42f49b76 100644--- a/src/metabase/query_processor/middleware/resolve_joined_fields.clj+++ b/src/metabase/query_processor/middleware/fix_bad_field_id_refs.clj@@ -1,4 +1,4 @@-(ns metabase.query-processor.middleware.resolve-joined-fields+(ns metabase.query-processor.middleware.fix-bad-field-id-refs"Middleware that adds `:join-alias` info to `:field` clauses where needed."(:require[metabase.lib.core :as lib]@@ -9,7 +9,7 @@[metabase.lib.walk :as lib.walk][metabase.util.malli :as mu]))-(mu/defn- resolve-joined-fields-in-stage :- [:maybe ::lib.schema/stage]+(mu/defn- fix-bad-field-id-refs-in-stage :- [:maybe ::lib.schema/stage][query :- ::lib.schema/querypath :- ::lib.walk/pathstage :- ::lib.schema/stage]@@ -34,7 +34,8 @@;; normalizing the stage will remove any duplicate `:fields` or `:breakouts`(lib/normalize ::lib.schema/stage stage'))))-(mu/defn resolve-joined-fields :- ::lib.schema/query- "Add `:join-alias` info to `:field` clauses where needed."+(mu/defn fix-bad-field-id-refs :- ::lib.schema/query+ "Fix any `:field` refs using an integer Field ID that in a stage where that Field's Table is not the+ `:source-table`. Convert them to Field name refs and add info like `:join-alias` as needed."[query :- ::lib.schema/query]- (lib.walk/walk-stages query resolve-joined-fields-in-stage))+ (lib.walk/walk-stages query fix-bad-field-id-refs-in-stage))diff --git a/src/metabase/query_processor/middleware/resolve_fields.clj b/src/metabase/query_processor/middleware/resolve_fields.cljindex 01cab75db47..25470be9c30 100644--- a/src/metabase/query_processor/middleware/resolve_fields.clj+++ b/src/metabase/query_processor/middleware/resolve_fields.clj@@ -1,13 +1,11 @@(ns metabase.query-processor.middleware.resolve-fields"Middleware that resolves the Fields referenced by a query."(:require- [metabase.legacy-mbql.schema :as mbql.s][metabase.lib.metadata :as lib.metadata][metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id][metabase.lib.util.match :as lib.util.match][metabase.query-processor.error-type :as qp.error-type]- [metabase.query-processor.store :as qp.store][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]))@@ -23,12 +21,7 @@field-ids))](recur metadata-providerable parent-ids)))-(defmulti ^:private field-ids- {:arglists '([query])}- (fn [query]- (if (:lib/type query) ::pmbql ::legacy)))--(mu/defmethod field-ids ::pmbql :- [:set ::lib.schema.id/field]+(mu/defn- field-ids :- [:set ::lib.schema.id/field][query :- ::lib.schema/query](into #{}(lib.util.match/match (:stages query)@@ -39,22 +32,15 @@{:lib/type :metadata/column, :id (id :guard pos-int?)}id)))-(mu/defmethod field-ids ::legacy :- [:set ::lib.schema.id/field]- [query :- ::mbql.s/Query]- (into (set (lib.util.match/match (:query query) [:field (id :guard integer?) _] id))- (comp cat (keep :id))- (lib.util.match/match (:query query) {:source-metadata source-metadata} source-metadata)))-+;;; TODO (Cam 9/10/25) -- give this a more accurate name like `prefetch-all-fields` or+;;; `warm-metadata-provider-cache-with-all-fields` or something.(defn resolve-fields- "Resolve all field referenced in the `query`, and store them in the QP Store."+ "Resolve all field referenced in the `query`, and store them in the Metadata Provider."[query](let [ids (field-ids query)](try(u/prog1 query- (let [metadata-providerable (if (:lib/type query)- query- (qp.store/metadata-provider))]- (resolve-fields-with-ids! metadata-providerable ids)))+ (resolve-fields-with-ids! query ids))(catch Throwable e(throw (ex-info (tru "Error resolving Fields in query: {0}" (ex-message e)){:field-ids idsdiff --git a/src/metabase/query_processor/middleware/resolve_joins.clj b/src/metabase/query_processor/middleware/resolve_joins.cljindex 3dd024bcdf2..38e9d53a3e5 100644--- a/src/metabase/query_processor/middleware/resolve_joins.clj+++ b/src/metabase/query_processor/middleware/resolve_joins.clj@@ -4,11 +4,15 @@(:refer-clojure :exclude [alias])(:require[medley.core :as m]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.metadata :as lib.metadata]+ [metabase.lib.schema.id :as lib.schema.id][metabase.lib.util :as lib.util][metabase.lib.util.match :as lib.util.match]- [metabase.query-processor.middleware.add-implicit-clauses :as qp.add-implicit-clauses]+ [metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.store :as qp.store][metabase.util :as u][metabase.util.i18n :refer [tru]]@@ -90,6 +94,20 @@[:field field-id {:join-alias alias}]))[:field field-name {:base-type base-type, :join-alias alias}]))))+(mu/defn- sorted-implicit-fields-for-table :- mbql.s/Fields+ "For use when adding implicit Field IDs to a query. Return a sequence of field clauses, sorted by the rules listed+ in [[metabase.query-processor.sort]], for all the Fields in a given Table."+ [table-id :- ::lib.schema.id/table]+ (let [fields (lib.metadata/active-fields (qp.store/metadata-provider) table-id)]+ (when (empty? fields)+ (throw (ex-info (tru "No fields found for table {0}." (pr-str (:name (lib.metadata/table (qp.store/metadata-provider) table-id))))+ {:table-id table-id+ :type qp.error-type/invalid-query})))+ (mapv+ (fn [field]+ [:field (u/the-id field) nil])+ fields)))+(mu/defn- handle-all-fields :- mbql.s/Join"Replace `:fields :all` in a join with an appropriate list of Fields."[{:keys [source-table source-query alias fields source-metadata], :as join} :- mbql.s/Join]@@ -98,7 +116,7 @@(when (= fields :all){:fields (if source-query(source-metadata->fields join source-metadata)- (for [[_ id-or-name opts] (qp.add-implicit-clauses/sorted-implicit-fields-for-table source-table)]+ (for [[_ id-or-name opts] (sorted-implicit-fields-for-table source-table)][:field id-or-name (assoc opts :join-alias alias)]))})))(defn- deduplicate-aliases []@@ -215,6 +233,9 @@(seq joins) resolve-joins-in-mbql-querysource-query (update :source-query resolve-joins-in-mbql-query-all-levels)))+;; TODO (Cam 9/10/25) -- once we convert this to Lib we can remove+;; the [[metabase.query-processor.middleware.ensure-joins-use-source-query/ensure-joins-use-source-query]] middleware+;; entirely(defn resolve-joins"Add any Tables and Fields referenced by the `:joins` clause to the QP store."[{inner-query :query, :as outer-query}]diff --git a/src/metabase/query_processor/middleware/results_metadata.clj b/src/metabase/query_processor/middleware/results_metadata.cljindex 9eb8ca4f81b..93a91daf557 100644--- a/src/metabase/query_processor/middleware/results_metadata.clj+++ b/src/metabase/query_processor/middleware/results_metadata.clj@@ -8,6 +8,9 @@[metabase.analyze.core :as analyze][metabase.driver :as driver][metabase.driver.util :as driver.u]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.metadata :as lib.metadata][metabase.lib.schema.metadata :as lib.schema.metadata]diff --git a/src/metabase/query_processor/middleware/visualization_settings.clj b/src/metabase/query_processor/middleware/visualization_settings.cljindex a3b75bf0f53..89a64885538 100644--- a/src/metabase/query_processor/middleware/visualization_settings.clj+++ b/src/metabase/query_processor/middleware/visualization_settings.clj@@ -1,6 +1,9 @@(ns metabase.query-processor.middleware.visualization-settings(:require[metabase.appearance.core :as appearance]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.protocols :as lib.metadata.protocols]diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.cljindex c4a29050a36..6487000b699 100644--- a/src/metabase/query_processor/preprocess.clj+++ b/src/metabase/query_processor/preprocess.clj@@ -1,6 +1,9 @@(ns metabase.query-processor.preprocess(:require[metabase.config.core :as config]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s][metabase.lib.core :as lib][metabase.lib.schema :as lib.schema]@@ -27,6 +30,7 @@[metabase.query-processor.middleware.expand-aggregations :as expand-aggregations][metabase.query-processor.middleware.expand-macros :as expand-macros][metabase.query-processor.middleware.fetch-source-query :as fetch-source-query]+ [metabase.query-processor.middleware.fix-bad-field-id-refs :as fix-bad-field-id-refs][metabase.query-processor.middleware.limit :as limit][metabase.query-processor.middleware.metrics :as metrics][metabase.query-processor.middleware.normalize-query :as normalize]@@ -37,7 +41,6 @@[metabase.query-processor.middleware.reconcile-breakout-and-order-by-bucketing :as reconcile-bucketing][metabase.query-processor.middleware.remove-inactive-field-refs :as qp.remove-inactive-field-refs][metabase.query-processor.middleware.resolve-fields :as qp.resolve-fields]- [metabase.query-processor.middleware.resolve-joined-fields :as resolve-joined-fields][metabase.query-processor.middleware.resolve-joins :as resolve-joins][metabase.query-processor.middleware.resolve-referenced :as qp.resolve-referenced][metabase.query-processor.middleware.resolve-source-table :as qp.resolve-source-table]@@ -107,6 +110,8 @@(ensure-mbql5 #'parameters/substitute-parameters)(ensure-mbql5 #'qp.resolve-source-table/resolve-source-tables)(ensure-mbql5 #'qp.auto-bucket-datetimes/auto-bucket-datetimes)+ ;; TODO (Cam 9/10/25) -- once we convert the [[metabase.query-processor.middleware.resolve-joins/resolve-joins]]+ ;; middleware to Lib we can remove this middleware entirely(ensure-mbql5 #'ensure-joins-use-source-query/ensure-joins-use-source-query)(ensure-mbql5 #'reconcile-bucketing/reconcile-breakout-and-order-by-bucketing)(ensure-legacy #'qp.add-source-metadata/add-source-metadata-for-source-queries)@@ -114,11 +119,11 @@(ensure-mbql5 #'qp.middleware.enterprise/attach-destination-db-middleware)(ensure-mbql5 #'qp.middleware.enterprise/apply-sandboxing)(ensure-legacy #'qp.persistence/substitute-persisted-query)- (ensure-legacy #'qp.add-implicit-clauses/add-implicit-clauses) ; #61398+ (ensure-mbql5 #'qp.add-implicit-clauses/add-implicit-clauses);; this needs to be done twice, once before adding remaps (since we want to add remaps inside joins) and then again;; after adding any implicit joins. Implicit joins do not need to get remaps since we only use them for fetching;; specific columns.- (ensure-legacy #'resolve-joins/resolve-joins) ; #61398+ (ensure-legacy #'resolve-joins/resolve-joins)(ensure-mbql5 #'qp.add-remaps/add-remapped-columns)#'qp.resolve-fields/resolve-fields ; this middleware actually works with either MBQL 5 or legacy(ensure-mbql5 #'binning/update-binning-strategy)@@ -126,7 +131,7 @@(ensure-mbql5 #'qp.add-default-temporal-unit/add-default-temporal-unit)(ensure-mbql5 #'qp.add-implicit-joins/add-implicit-joins)(ensure-legacy #'resolve-joins/resolve-joins) ; #61398- (ensure-mbql5 #'resolve-joined-fields/resolve-joined-fields)+ (ensure-mbql5 #'fix-bad-field-id-refs/fix-bad-field-id-refs)(ensure-mbql5 #'qp.remove-inactive-field-refs/remove-inactive-field-refs);; yes, this is called a second time, because we need to handle any joins that got added(ensure-mbql5 #'qp.middleware.enterprise/apply-sandboxing)diff --git a/src/metabase/query_processor/streaming.clj b/src/metabase/query_processor/streaming.cljindex ca37ff79a41..881b58154c8 100644--- a/src/metabase/query_processor/streaming.clj+++ b/src/metabase/query_processor/streaming.clj@@ -3,6 +3,9 @@[clojure.string :as str][metabase.analytics.core :as analytics][metabase.driver :as driver]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.util :as mbql.u][metabase.lib.schema.common :as lib.schema.common][metabase.models.visualization-settings :as mb.viz]diff --git a/src/metabase/query_processor/util.clj b/src/metabase/query_processor/util.cljindex de91eb3b8de..16debf2617c 100644--- a/src/metabase/query_processor/util.clj+++ b/src/metabase/query_processor/util.clj@@ -7,6 +7,9 @@[clojure.walk :as walk][medley.core :as m][metabase.driver :as driver]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib only soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib-be.metadata.jvm :as lib.metadata.jvm][metabase.lib.core :as lib]diff --git a/src/metabase/query_processor/util/nest_query.clj b/src/metabase/query_processor/util/nest_query.cljindex f16dda9ca5c..19b753d0f46 100644--- a/src/metabase/query_processor/util/nest_query.clj+++ b/src/metabase/query_processor/util/nest_query.clj@@ -9,7 +9,11 @@[clojure.walk :as walk][medley.core :as m][metabase.api.common :as api]+ ;; legacy usage -- don't use Legacy MBQL utils in QP code going forward, prefer Lib. This will be updated to use+ ;; Lib only soon+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.schema :as mbql.s]+ ^{:clj-kondo/ignore [:discouraged-namespace]}[metabase.legacy-mbql.util :as mbql.u][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -27,6 +31,8 @@;; The remove line is taken from the add-implicit-clauses middleware. It shouldn't be necessary, because any;; unused fields should be dropped from the inner query. It also shouldn't hurt anything, because the outer;; query shouldn't use these fields in the first place.+ ;;+ ;; TODO (Cam 9/12/25) -- this shouldn't be necessary anymore(remove #(#{:sensitive :retired} (:visibility-type %)))(map (fn [field][:field (u/the-id field) nil]))))@@ -149,7 +155,15 @@(log/debugf "Keeping used ref:\n%s" (u/pprint-to-str a-ref))(log/debugf "Removing unused ref:\n%s" (u/pprint-to-str (keep-source+alias-props a-ref))))))(remove-unused [refs]- (filterv used?* refs))]+ (into []+ (comp (filter used?*)+ (m/distinct-by (fn [[_tag _id-or-name opts, :as _a-ref]]+ (or (::add/desired-alias opts)+ ;; if the field ref doesn't have a desired alias (probably because we+ ;; added it in this namespace and haven't generated yet, then always+ ;; keep it... just use a random UUID that should always be distinct+ (random-uuid)))))+ refs))](update source :fields remove-unused))))(defn- append-join-fieldsdiff --git a/test/metabase/analyze/query_results_test.clj b/test/metabase/analyze/query_results_test.cljindex 7f8f916b1c8..60a8a9dc76a 100644--- a/test/metabase/analyze/query_results_test.clj+++ b/test/metabase/analyze/query_results_test.clj@@ -94,7 +94,7 @@"as it's just an integer flowing through, similarly Price isn't found to be a category as we're inferring by name ""only")(qp.store/with-metadata-provider (lib.tu/mock-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){:cards [{:id 1:dataset-query {:database (mt/id):type :nativediff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.cljindex e175a347682..c1fa69ca4e3 100644--- a/test/metabase/driver/postgres_test.clj+++ b/test/metabase/driver/postgres_test.clj@@ -520,7 +520,7 @@:type :query:query {:source-table "card__123"}})](is (= ["SELECT"- " \"json_alias_test\" AS \"json_alias_test\","+ " \"source\".\"json_alias_test\" AS \"json_alias_test\","" \"source\".\"count\" AS \"count\"""FROM"" ("diff --git a/test/metabase/driver/sql/query_processor_test.clj b/test/metabase/driver/sql/query_processor_test.cljindex 17fc6f592f5..b39b78546a7 100644--- a/test/metabase/driver/sql/query_processor_test.clj+++ b/test/metabase/driver/sql/query_processor_test.clj@@ -454,14 +454,14 @@(deftest ^:parallel multiple-joins-with-expressions-test(testing "We should be able to compile a complicated query with multiple joins and expressions correctly"(is (= '{:select [source.PRODUCTS__via__PRODUCT_ID__CATEGORY AS PRODUCTS__via__PRODUCT_ID__CATEGORY- source.PEOPLE__via__USER_ID__SOURCE AS PEOPLE__via__USER_ID__SOURCE- DATE_TRUNC ("year" source.CREATED_AT) AS CREATED_AT- source.pivot-grouping AS pivot-grouping- COUNT (*) AS count]- :from [{:select [ORDERS.USER_ID AS USER_ID- ORDERS.PRODUCT_ID AS PRODUCT_ID- ORDERS.CREATED_AT AS CREATED_AT- ABS (0) AS pivot-grouping+ source.PEOPLE__via__USER_ID__SOURCE AS PEOPLE__via__USER_ID__SOURCE+ DATE_TRUNC ("year" source.CREATED_AT) AS CREATED_AT+ source.pivot-grouping AS pivot-grouping+ COUNT (*) AS count]+ :from [{:select [ORDERS.USER_ID AS USER_ID+ ORDERS.PRODUCT_ID AS PRODUCT_ID+ ORDERS.CREATED_AT AS CREATED_AT+ ABS (0) AS pivot-grouping;; TODO: The order here is not deterministic! It's coming;; from [[metabase.query-processor.util.transformations.nest-breakouts]];; or [[metabase.query-processor.util.nest-query]], which walks the query looking@@ -512,9 +512,9 @@DATE_TRUNC ("year" source.CREATED_AT)source.pivot-grouping]:order-by [source.PRODUCTS__via__PRODUCT_ID__CATEGORY ASC- source.PEOPLE__via__USER_ID__SOURCE ASC- DATE_TRUNC ("year" source.CREATED_AT) ASC- source.pivot-grouping ASC]}+ source.PEOPLE__via__USER_ID__SOURCE ASC+ DATE_TRUNC ("year" source.CREATED_AT) ASC+ source.pivot-grouping ASC]}(-> (lib.tu.macros/mbql-query orders{:aggregation [[:aggregation-options [:count] {:name "count"}]]:breakout [&PRODUCTS__via__PRODUCT_ID.products.categorydiff --git a/test/metabase/legacy_mbql/schema_test.cljc b/test/metabase/legacy_mbql/schema_test.cljcindex bad2a6859f0..2c68b81a776 100644--- a/test/metabase/legacy_mbql/schema_test.cljc+++ b/test/metabase/legacy_mbql/schema_test.cljc@@ -4,6 +4,7 @@[clojure.test :refer [are deftest is testing]][malli.error :as me][metabase.legacy-mbql.schema :as mbql.s]+ [metabase.lib.schema.parameter :as lib.schema.parameter][metabase.util.malli.humanize :as mu.humanize][metabase.util.malli.registry :as mr]))@@ -129,7 +130,7 @@:type :dimension:widget-type :date/all-options:dimension template-tag-dimension}]- (is (nil? (me/humanize (mr/explain mbql.s/Parameter parameter))))+ (is (nil? (me/humanize (mr/explain ::lib.schema.parameter/parameter parameter))))(is (nil? (me/humanize (mr/explain mbql.s/TemplateTag template-tag))))(let [query {:database 1:type :nativediff --git a/test/metabase/lib/drill_thru/underlying_records_test.cljc b/test/metabase/lib/drill_thru/underlying_records_test.cljcindex a0c5e003ad5..b34e16f4d33 100644--- a/test/metabase/lib/drill_thru/underlying_records_test.cljc+++ b/test/metabase/lib/drill_thru/underlying_records_test.cljc@@ -588,3 +588,111 @@(lib.underlying/top-level-column query (:column bucket-dim)))))(is (=? [[:= {} [:expression {} "cost bucket"] "12"]](lib/filters (lib/drill-thru query drill)))))))++(deftest ^:parallel native-query-with-multiple-breakouts-on-same-column-test+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query {:type :native+ :database (meta/id)+ :native {:query "select ID, CREATED_AT from ORDERS"}}+ :result-metadata (for [col-name [:id :created-at]]+ (-> (meta/field-metadata :orders col-name)+ (assoc :lib/source :source/native)+ (dissoc :id :table-id)))}]})+ query (lib/query+ mp+ {:database (meta/id)+ :type :query+ :query {:source-table "card__1"+ :aggregation [[:count]]+ :breakout [[:field "CREATED_AT" {:temporal-unit :month, :base-type :type/DateTime}]+ [:field "CREATED_AT" {:temporal-unit :year, :base-type :type/DateTime}]]}})+ count-col {:base-type :type/BigInteger+ :display-name "Count"+ :effective-type :type/BigInteger+ :name "count"+ :semantic-type :type/Quantity+ :lib/deduplicated-name "count"+ :lib/desired-column-alias "count"+ :lib/original-name "count"+ :lib/source :source/aggregations+ :lib/source-column-alias "count"+ :lib/source-uuid "5ae2854a-11ce-48fe-ab85-3f2bc059e452"+ :lib/type :metadata/column}+ created-at-col {:base-type :type/DateTime+ :database-type "TIMESTAMP"+ :display-name "CREATED_AT: Month"+ :effective-type :type/DateTime+ :inherited-temporal-unit :month+ :name "CREATED_AT"+ :remapped-from-index nil+ :remapping nil+ :semantic-type :type/CreationTimestamp+ :lib/breakout? true+ :lib/card-id 1+ :lib/deduplicated-name "CREATED_AT"+ :lib/desired-column-alias "CREATED_AT"+ :lib/original-name "CREATED_AT"+ :lib/source-column-alias "CREATED_AT"+ :lib/type :metadata/column+ :metabase.lib.field/temporal-unit :month}+ created-at-2-col {:base-type :type/DateTime+ :database-type "TIMESTAMP"+ :display-name "CREATED_AT: Year"+ :effective-type :type/DateTime+ :inherited-temporal-unit :year+ :name "CREATED_AT_2"+ :remapped-from-index nil+ :remapping nil+ :semantic-type :type/CreationTimestamp+ :lib/breakout? true+ :lib/card-id 1+ :lib/deduplicated-name "CREATED_AT_2"+ :lib/desired-column-alias "CREATED_AT_2"+ :lib/original-name "CREATED_AT"+ :lib/source-column-alias "CREATED_AT"+ :lib/type :metadata/column+ :metabase.lib.field/temporal-unit :year}+ context {:column count-col+ :column-ref [:aggregation {:lib/uuid "1e569eeb-049b-42a4-8bc6-678743cbfdcb"} "5ae2854a-11ce-48fe-ab85-3f2bc059e452"]+ :value 325+ :card-id 1+ :row [{:column created-at-col+ :column-ref [:field+ {:base-type :type/DateTime, :temporal-unit :month, :lib/uuid "6574ad49-7895-4f95-bbc7-6a0c9cc0338f"}+ "CREATED_AT"]+ :value "2023-07-01T00:00:00Z"}+ {:column created-at-2-col+ :column-ref [:field+ {:base-type :type/DateTime, :temporal-unit :year, :lib/uuid "289cceca-229d-42c0-9658-eb548d694269"}+ "CREATED_AT_2"]+ :value "2023"}+ {:column count-col+ :column-ref+ [:aggregation {:lib/uuid "0daafd21-4a03-4a09-a2aa-678dde6563b1"} "5ae2854a-11ce-48fe-ab85-3f2bc059e452"]+ :value 325}]+ :dimensions [{:column created-at-col+ :column-ref+ [:field+ {:base-type :type/DateTime, :temporal-unit :month, :lib/uuid "803bf31d-0a27-4c02-992f-3b550fd58db6"}+ "CREATED_AT"]+ :value "2023-07-01T00:00:00Z"}+ {:column created-at-2-col+ :column-ref [:field+ {:base-type :type/DateTime, :temporal-unit :year, :lib/uuid "5330b999-53d5-4545-9f73-61e26a6dde51"}+ "CREATED_AT_2"]+ :value "2023-01-01T00:00:00Z"}]}+ drill (m/find-first #(= (:type %) :drill-thru/underlying-records)+ (lib/available-drill-thrus query context))]+ (is (some? drill))+ (is (=? [{:source-card 1+ :filters [[:=+ {}+ [:field {:temporal-unit :month} "CREATED_AT"]+ "2023-07-01T00:00:00Z"]+ [:=+ {}+ [:field {:temporal-unit :year} "CREATED_AT"]+ "2023-01-01T00:00:00Z"]]}]+ (:stages (lib/drill-thru query drill))))))diff --git a/test/metabase/lib/field/resolution_test.cljc b/test/metabase/lib/field/resolution_test.cljcindex e16266285cc..337f01e33ef 100644--- a/test/metabase/lib/field/resolution_test.cljc+++ b/test/metabase/lib/field/resolution_test.cljc@@ -386,7 +386,7 @@:strategy :left-join:fk-field-id %category-id}]}))col (lib.field.resolution/resolve-field-ref query -1 (first (lib/fields query -1)))]- (is (=? {:lib/original-ref-for-result-metadata-purposes-only [:field {:join-alias "Category"} pos-int?]}+ (is (=? {:lib/original-ref-style-for-result-metadata-purposes :original-ref-style/id}col))(is (=? [:field{:lib/uuid string?@@ -1325,7 +1325,7 @@query-1[:field {:base-type :type/BigInteger, :lib/uuid "00000000-0000-0000-0000-000000000000"} (meta/id :products :id)])- (dissoc :lib/original-ref-for-result-metadata-purposes-only :lib/original-display-name))+ (dissoc :lib/original-ref-style-for-result-metadata-purposes :lib/original-display-name))(lib.field.resolution/resolve-field-refquery-1@@ -1416,6 +1416,22 @@query -1[:field {:lib/uuid "00000000-0000-0000-0000-000000000000", :base-type :type/Float} "TAX"]))))))+(deftest ^:parallel resolve-inactive-field-ref-by-name-test+ (testing "Should be able to resolve an INACTIVE field ref by name correctly."+ (let [mp (-> meta/metadata-provider+ (lib.tu/merged-mock-metadata-provider+ {:fields (for [field-id [(meta/id :orders :tax) (meta/id :products :vendor)]]+ {:id field-id, :active false})}))+ query (lib/query+ mp+ (lib.tu.macros/mbql-query orders))]+ (is (=? {:active false+ :id (meta/id :orders :tax)+ :name "TAX"}+ (lib.field.resolution/resolve-field-ref+ query -1+ [:field {:lib/uuid "00000000-0000-0000-0000-000000000000", :base-type :type/Float} "TAX"]))))))+(deftest ^:parallel multiple-remaps-between-tables-test(testing "Should be able to resolve multiple FK remaps via different FKs from Table A to Table B in a join"(let [mp (-> meta/metadata-providerdiff --git a/test/metabase/lib/field_test.cljc b/test/metabase/lib/field_test.cljcindex 766782eeba3..27118ff8cad 100644--- a/test/metabase/lib/field_test.cljc+++ b/test/metabase/lib/field_test.cljc@@ -1,7 +1,7 @@(ns metabase.lib.field-test(:require#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))- [clojure.test :refer [are deftest is testing use-fixtures]]+ [clojure.test :refer [are deftest is testing]][medley.core :as m][metabase.lib.binning :as lib.binning][metabase.lib.core :as lib]@@ -29,8 +29,32 @@#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))-(use-fixtures :each (fn [thunk]- (thunk)))+(deftest ^:parallel ref-test+ (is (=? [:field+ {:base-type :type/DateTime+ :effective-type :type/Integer+ :temporal-unit :year+ :lib/uuid string?}+ "CREATED_AT"]+ (lib/ref {:base-type :type/DateTime+ :database-type "TIMESTAMP"+ :display-name "CREATED_AT: Year"+ :effective-type :type/DateTime+ :inherited-temporal-unit :year+ :name "CREATED_AT_2"+ :remapped-from-index nil+ :remapping nil+ :semantic-type :type/CreationTimestamp+ :lib/breakout? true+ :lib/card-id 1+ :lib/deduplicated-name "CREATED_AT_2"+ :lib/desired-column-alias "CREATED_AT_2"+ :lib/original-name "CREATED_AT"+ :lib/source-column-alias "CREATED_AT"+ :lib/type :metadata/column+ :metabase.lib.field/original-effective-type :type/DateTime+ :metabase.lib.field/original-temporal-unit :year+ :metabase.lib.field/temporal-unit :year}))))(defn grandparent-parent-child-id [field](+ (meta/id :venues :id)diff --git a/test/metabase/lib/metadata/result_metadata_test.cljc b/test/metabase/lib/metadata/result_metadata_test.cljcindex cdf11314d97..5c78efe64a4 100644--- a/test/metabase/lib/metadata/result_metadata_test.cljc+++ b/test/metabase/lib/metadata/result_metadata_test.cljc@@ -68,7 +68,10 @@"display-name should include the display name of the FK field (for IMPLICIT JOINS)")(is (=? [{:display-name "Category → Name":source :fields- :field-ref [:field (meta/id :categories :name) {:join-alias "Category"}]}]+ ;; sort of contrived since this is not a query we could build create IRL... even tho the join is+ ;; technically explicit it matches the shape of an implicit one, so we should return field refs that+ ;; act like the join isn't here yet+ :field-ref [:field (meta/id :categories :name) {:source-field (meta/id :venues :category-id)}]}](column-info(lib/querymeta/metadata-provider@@ -201,7 +204,7 @@(lib/with-fields [(lib.metadata/field metadata-provider 3)]))](is (=? {:table-id (meta/id :venues):name "grandparent.parent.child"- :field-ref [:field 3 {:base-type :type/Text}]+ :field-ref [:field 3 nil]:parent-id 2:id 3:visibility-type :normal@@ -743,7 +746,7 @@;; the `:year` bucketing if you used this query in another subsequent query, so the field ref doesn't;; include the unit; however `:unit` is still `:year` so the frontend can use the correct formatting to;; display values of the column.- (is (=? [(assoc date-col :field-ref [:field (meta/id :checkins :date) {}], :unit :year)+ (is (=? [(assoc date-col :field-ref [:field (meta/id :checkins :date) nil], :unit :year)(assoc count-col :field-ref [:field "count" {:base-type :type/Integer}])](result-metadata/returned-columns(lib/query metadata-provider (lib.metadata/card metadata-provider 1))))))))@@ -912,8 +915,8 @@:display-name "Created At: Year":effective-type :type/Integer;; additional keys in field ref are WRONG- :field-ref (partial = [:field "CREATED_AT" {:base-type :type/DateTimeWithLocalTZ- :temporal-unit :year}])+ :field-ref [:field "CREATED_AT" (partial = {:base-type :type/DateTimeWithLocalTZ+ :temporal-unit :year})]:id (meta/id :orders :created-at):inherited-temporal-unit :year:name "CREATED_AT"diff --git a/test/metabase/lib/schema/parameter_test.cljc b/test/metabase/lib/schema/parameter_test.cljcindex 9c473f8ee01..368786583dc 100644--- a/test/metabase/lib/schema/parameter_test.cljc+++ b/test/metabase/lib/schema/parameter_test.cljc@@ -16,7 +16,11 @@(are [x] (not (me/humanize (mr/explain ::lib.schema.parameter/parameter x))){:type :category:target [:variable [:field 71725 nil]]- :value 50}))+ :value 50}+ {:type :date/range+ :name "created_at"+ :target [:dimension [:template-tag "date_range"]]+ :value "past1weeks"}))(deftest ^:parallel normalize-dimension-test(are [x expected] (= expecteddiff --git a/test/metabase/lib/table_test.cljc b/test/metabase/lib/table_test.cljcindex b52cb9940bb..413d1bf38ca 100644--- a/test/metabase/lib/table_test.cljc+++ b/test/metabase/lib/table_test.cljc@@ -3,6 +3,7 @@#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))[clojure.test :refer [deftest is testing]][metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.protocols :as metadata.protocols][metabase.lib.test-metadata :as meta][metabase.lib.test-util :as lib.tu]@@ -47,3 +48,21 @@query (lib/query metadata-provider (meta/table-metadata :venues))](mu/disable-enforcement(is (sequential? (lib/visible-columns query)))))))++(deftest ^:parallel returned-columns-ordering-test+ (testing "check we fetch Fields in the right order"+ (let [mp (lib.tu/merged-mock-metadata-provider+ meta/metadata-provider+ {:fields [{:id (meta/id :venues :price)+ :position -1}]})]+ (is (=? [;; sorted first because it has lowest position+ {:position -1, :name "PRICE", :semantic-type :type/Category}+ ;; PK+ {:position 0, :name "ID", :semantic-type :type/PK}+ ;; Name+ {:position 1, :name "NAME", :semantic-type :type/Name}+ ;; The rest are sorted by name+ {:position 2, :name "CATEGORY_ID", :semantic-type :type/FK}+ {:position 3, :name "LATITUDE", :semantic-type :type/Latitude}+ {:position 4, :name "LONGITUDE", :semantic-type :type/Longitude}]+ (lib/returned-columns (lib/native-query mp "WHATEVER") (lib.metadata/table mp (meta/id :venues))))))))diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.cljindex 6f9a33425ea..50254e1d373 100644--- a/test/metabase/query_processor/api_test.clj+++ b/test/metabase/query_processor/api_test.clj@@ -333,11 +333,11 @@encoded? json/encode)]](testing (format "encoded? %b" encoded?)(doseq [mp [(lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :venues :category_id)(mt/id :categories :name))(lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :venues :category_id)(mapv first (mt/rows (qp/process-query(mt/mbql-query categoriesdiff --git a/test/metabase/query_processor/card_test.clj b/test/metabase/query_processor/card_test.cljindex d93381060de..8915208084f 100644--- a/test/metabase/query_processor/card_test.clj+++ b/test/metabase/query_processor/card_test.clj@@ -268,7 +268,7 @@:semantic_type (base-type->semantic-type (:base_type col)))))];; use a MetadataProvider to build cards and populate metadata, but we have to use `with-temp` before;; calling [[run-query-for-card]] since the Card QP code does not currently fully support metadata providers.- (let [mp (as-> (mt/application-database-metadata-provider (mt/id)) mp+ (let [mp (as-> (mt/metadata-provider) mp(qp.test-util/metadata-provider-with-cards-with-metadata-for-queriesmp[{:database (mt/id)diff --git a/test/metabase/query_processor/middleware/add_implicit_clauses_test.clj b/test/metabase/query_processor/middleware/add_implicit_clauses_test.cljindex 4493db614a4..408233edcce 100644--- a/test/metabase/query_processor/middleware/add_implicit_clauses_test.clj+++ b/test/metabase/query_processor/middleware/add_implicit_clauses_test.clj@@ -1,181 +1,167 @@(ns ^:mb/driver-tests metabase.query-processor.middleware.add-implicit-clauses-test(:require[clojure.test :refer :all]- [metabase.legacy-mbql.util :as mbql.u]+ [metabase.driver :as driver][metabase.lib.convert :as lib.convert][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.lib.test-util.notebook-helpers :as lib.tu.notebook][metabase.lib.types.isa :as lib.types.isa][metabase.query-processor :as qp][metabase.query-processor.middleware.add-implicit-clauses :as qp.add-implicit-clauses]- [metabase.query-processor.middleware.add-source-metadata :as add-source-metadata][metabase.query-processor.preprocess :as qp.preprocess]- [metabase.query-processor.store :as qp.store]- [metabase.query-processor.test-util :as qp.test-util][metabase.test :as mt]))-(deftest ^:parallel ordering-test- (testing "check we fetch Fields in the right order"- (qp.store/with-metadata-provider (lib.tu/merged-mock-metadata-provider- meta/metadata-provider- {:fields [{:id (meta/id :venues :price)- :position -1}]})- (let [ids (map second- (#'qp.add-implicit-clauses/sorted-implicit-fields-for-table (meta/id :venues)))]- (is (=? [;; sorted first because it has lowest positon- {:position -1, :name "PRICE", :semantic-type :type/Category}- ;; PK- {:position 0, :name "ID", :semantic-type :type/PK}- ;; Name- {:position 1, :name "NAME", :semantic-type :type/Name}- ;; The rest are sorted by name- {:position 2, :name "CATEGORY_ID", :semantic-type :type/FK}- {:position 3, :name "LATITUDE", :semantic-type :type/Latitude}- {:position 4, :name "LONGITUDE", :semantic-type :type/Longitude}]- (for [id ids]- (lib.metadata/field (qp.store/metadata-provider) id))))))))+(defn- add-implicit-clauses+ ([query]+ (add-implicit-clauses meta/metadata-provider query))++ ([metadata-provider query]+ (if (= (:lib/type query) :mbql/query)+ (qp.add-implicit-clauses/add-implicit-clauses query)+ (-> (lib/query metadata-provider query)+ qp.add-implicit-clauses/add-implicit-clauses+ lib/->legacy-MBQL))))++(defn- add-implicit-clauses-to-legacy-inner-query+ ([inner-query]+ (add-implicit-clauses-to-legacy-inner-query meta/metadata-provider inner-query))++ ([metadata-provider inner-query]+ (-> (lib/query-from-legacy-inner-query metadata-provider (meta/id) inner-query)+ add-implicit-clauses+ lib/->legacy-MBQL+ :query)))(deftest ^:parallel add-order-bys-for-breakouts-test(testing "we should add order-bys for breakout clauses"- (mt/with-metadata-provider meta/metadata-provider- (is (= {:source-table 1- :breakout [[:field 1 nil]]- :order-by [[:asc [:field 1 nil]]]}- (#'qp.add-implicit-clauses/add-implicit-breakout-order-by- {:source-table 1- :breakout [[:field 1 nil]]}))))))+ (is (= {:source-table (meta/id :venues)+ :breakout [[:field (meta/id :venues :price) nil]]+ :order-by [[:asc [:field (meta/id :venues :price) nil]]]}+ (add-implicit-clauses-to-legacy-inner-query+ {:source-table (meta/id :venues)+ :breakout [[:field (meta/id :venues :price) nil]]})))))(deftest ^:parallel add-order-bys-for-breakouts-test-2(testing "we should add order-bys for breakout clauses"(testing "Add Field to existing order-by"- (mt/with-metadata-provider meta/metadata-provider- (is (=? (lib.tu.macros/mbql-query orders- {:breakout [$product-id->products.category]- :order-by [[:asc $created-at]- [:asc $product-id->products.category]]})- (update (lib.tu.macros/mbql-query orders- {:breakout [$product-id->products.category]- :order-by [[:asc $created-at]]})- :query #'qp.add-implicit-clauses/add-implicit-breakout-order-by)))))))+ (is (=? (lib.tu.macros/mbql-query orders+ {:breakout [$product-id->products.category]+ :order-by [[:asc $created-at]+ [:asc $product-id->products.category]]})+ (update (lib.tu.macros/mbql-query orders+ {:breakout [$product-id->products.category]+ :order-by [[:asc $created-at]]})+ :query add-implicit-clauses-to-legacy-inner-query))))))(deftest ^:parallel add-order-bys-for-breakouts-test-3(testing "we should add order-bys for breakout clauses"(testing "...but not if the Field is already in an order-by"- (mt/with-metadata-provider meta/metadata-provider- (let [{:keys [query]} (lib.tu.macros/mbql-query orders- {:breakout [$product-id->products.category]- :order-by [[:asc $product-id->products.category]]})]- (is (= query- (#'qp.add-implicit-clauses/add-implicit-breakout-order-by query))))))))+ (let [{:keys [query]} (lib.tu.macros/mbql-query orders+ {:breakout [$product-id->products.category]+ :order-by [[:asc $product-id->products.category]]})]+ (is (= query+ (add-implicit-clauses-to-legacy-inner-query query)))))))(deftest ^:parallel add-order-bys-for-breakouts-test-4(testing "we should add order-bys for breakout clauses"(testing "...but not if the Field is already in an order-by"- (mt/with-metadata-provider meta/metadata-provider- (let [{:keys [query]} (lib.tu.macros/mbql-query orders- {:breakout [$product-id->products.category]- :order-by [[:desc $product-id->products.category]]})]- (is (= query- (#'qp.add-implicit-clauses/add-implicit-breakout-order-by query))))))))+ (let [{:keys [query]} (lib.tu.macros/mbql-query orders+ {:breakout [$product-id->products.category]+ :order-by [[:desc $product-id->products.category]]})]+ (is (= query+ (add-implicit-clauses-to-legacy-inner-query query)))))))(deftest ^:parallel add-order-bys-for-breakouts-test-5(testing "we should add order-bys for breakout clauses"(testing "...but not if the Field is already in an order-by"(testing "With a datetime-field"- (mt/with-metadata-provider meta/metadata-provider- (let [{:keys [query]} (lib.tu.macros/mbql-query orders- {:breakout [!day.created-at]- :order-by [[:asc !day.created-at]]})]- (is (= query- (#'qp.add-implicit-clauses/add-implicit-breakout-order-by query)))))))))--(defn- add-implicit-fields [inner-query]- (if (qp.store/initialized?)- (#'qp.add-implicit-clauses/add-implicit-fields inner-query)- (qp.store/with-metadata-provider meta/metadata-provider- (#'qp.add-implicit-clauses/add-implicit-fields inner-query))))+ (let [{:keys [query]} (lib.tu.macros/mbql-query orders+ {:breakout [!day.created-at]+ :order-by [[:asc !day.created-at]]})]+ (is (= query+ (add-implicit-clauses-to-legacy-inner-query query))))))))(deftest ^:parallel add-order-bys-for-no-aggregations-test(testing "We should add sorted implicit Fields for a query with no aggregations"- (is (= (:query- (lib.tu.macros/mbql-query venues- {:fields [;; :type/PK Fields should get sorted first- $id- ;; followed by :type/Name Fields- $name- ;; followed by other Fields sorted by name- $category-id $latitude $longitude $price]}))- (add-implicit-fields (:query (lib.tu.macros/mbql-query venues)))))))+ (is (=? (:query+ (lib.tu.macros/mbql-query venues+ {:fields [[:field %id {}]+ [:field %name {}]+ [:field %category-id {}]+ [:field %latitude {}]+ [:field %longitude {}]+ [:field %price {}]]}))+ (add-implicit-clauses-to-legacy-inner-query (:query (lib.tu.macros/mbql-query venues)))))))(deftest ^:parallel sort-by-field-position-test(testing "when adding sorted implicit Fields, Field positions should be taken into account"- (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider- meta/metadata-provider- {:fields [{:id 1- :table-id (meta/id :venues)- :position 100- :name "bbbbb"- :base-type :type/Text}- {:id 2- :table-id (meta/id :venues)- :position 101- :name "aaaaa"- :base-type :type/Text}]})- (is (= (:query- (lib.tu.macros/mbql-query venues- {:fields [;; all fields with lower positions should get sorted first according to rules above- $id $name $category-id $latitude $longitude $price- ;; followed by position = 100, then position = 101- [:field 1 nil]- [:field 2 nil]]}))- (add-implicit-fields (:query (lib.tu.macros/mbql-query venues))))))))+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:fields [{:id 1+ :table-id (meta/id :venues)+ :position 100+ :name "bbbbb"+ :base-type :type/Text}+ {:id 2+ :table-id (meta/id :venues)+ :position 101+ :name "aaaaa"+ :base-type :type/Text}]})]+ (is (=? (:query+ (lib.tu.macros/mbql-query venues+ {:fields [;; all fields with lower positions should get sorted first according to rules above+ [:field %id {}]+ [:field %name {}]+ [:field %category-id {}]+ [:field %latitude {}]+ [:field %longitude {}]+ [:field %price {}]+ ;; followed by position = 100, then position = 101+ [:field 1 {}]+ [:field 2 {}]]}))+ (add-implicit-clauses-to-legacy-inner-query mp (:query (lib.tu.macros/mbql-query venues))))))))(deftest ^:parallel default-bucketing-test(testing "datetime Fields should get default bucketing of :day"- (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider- meta/metadata-provider- {:fields [{:id 1- :table-id (meta/id :venues)- :position 2- :name "aaaaa"- :base-type :type/DateTime}]})- (is (lib.types.isa/temporal? (lib.metadata/field (qp.store/metadata-provider) 1)))- (is (query= (:query- (lib.tu.macros/mbql-query venues- {:fields [$id $name- [:field 1 nil]- $category-id $latitude $longitude $price]}))- (add-implicit-fields (:query (lib.tu.macros/mbql-query venues))))))))+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:fields [{:id 1+ :table-id (meta/id :venues)+ :position 2+ :name "aaaaa"+ :base-type :type/DateTime}]})]+ (is (lib.types.isa/temporal? (lib.metadata/field mp 1)))+ (is (=? (:query+ (lib.tu.macros/mbql-query venues+ {:fields [[:field %id {}]+ [:field %name {}]+ [:field 1 {}]+ [:field %category-id {}]+ [:field %latitude {}]+ [:field %longitude {}]+ [:field %price {}]]}))+ (add-implicit-clauses-to-legacy-inner-query mp (:query (lib.tu.macros/mbql-query venues))))))))(deftest ^:parallel add-implicit-fields-for-source-queries-test- (testing "We should add implicit Fields for source queries that have source-metadata as appropriate"- (let [{{source-query :query} :dataset_query- source-metadata :result_metadata}- (qp.test-util/card-with-source-metadata-for-query- (mt/mbql-query checkins- {:aggregation [[:count]]- :breakout [!month.$date]}))]- (is (=? {:fields [[:field (mt/id :checkins :date) {:inherited-temporal-unit :month}]- [:field "count" {:base-type :type/BigInteger}]]}- (add-implicit-fields- (:query (lib.tu.macros/mbql-query checkins- {:source-query source-query- :source-metadata source-metadata}))))))))+ (testing "We should add implicit Fields when we have source queries"+ (is (=? {:fields [[:field "DATE" {:inherited-temporal-unit :month}]+ [:field "count" {:base-type :type/Integer}]]}+ (add-implicit-clauses-to-legacy-inner-query+ (:query (lib.tu.macros/mbql-query checkins+ {:source-query {:aggregation [[:count]]+ :breakout [!month.$date]}})))))))(deftest ^:parallel expression-with-only-field-in-source-query-test(testing "Field coming from expression in source query should have string id"- (let [{{source-query :query} :dataset_query- source-metadata :result_metadata}- (qp.test-util/card-with-source-metadata-for-query- (mt/mbql-query venues {:expressions {"ccprice" $price}}))]- (is (some #(when (= % [:field "ccprice" {:base-type :type/Integer}]) %)- (-> (lib.tu.macros/mbql-query nil- {:source-query source-query- :source-metadata source-metadata})- :query add-implicit-fields :fields))))))+ (is (some #(when (= % [:field "ccprice" {:base-type :type/Integer}]) %)+ (-> (lib.tu.macros/mbql-query nil+ {:source-query {:source-table $$venues+ :expressions {"ccprice" $venues.price}}})+ :query add-implicit-clauses-to-legacy-inner-query :fields)))))(deftest ^:parallel joined-field-test(testing "When adding implicit `:fields` clauses, should include `join-alias` clauses for joined fields (#14745)"@@ -211,118 +197,148 @@:id %categories.name:display_name "Category → Name":base_type :type/Text}]})]- (is (=? (lib.tu.macros/$ids [$venues.id- (mbql.u/update-field-options field-ref dissoc :temporal-unit)- $venues.category-id->categories.name])- (get-in (qp.store/with-metadata-provider meta/metadata-provider- (qp.add-implicit-clauses/add-implicit-clauses query))- [:query :fields]))))))))+ (is (= [[:field "ID" {:base-type :type/BigInteger}]+ [:field "c__NAME" {:base-type :type/Text}]+ [:field "CATEGORIES__via__CATEGORY_ID__NAME" {:base-type :type/Text}]]+ (get-in (add-implicit-clauses query)+ [:query :fields]))))))))(deftest ^:parallel add-correct-implicit-fields-for-deeply-nested-source-queries-test(testing "Make sure we add correct `:fields` from deeply-nested source queries (#14872)"- (qp.store/with-metadata-provider meta/metadata-provider- (let [expected-cols qp.preprocess/query->expected-cols- q1 (lib.tu.macros/mbql-query orders- {:filter [:= $id 1]- :aggregation [[:sum $total]]- :breakout [!day.created-at- $product-id->products.title- $product-id->products.category]})- q2 (lib.tu.macros/mbql-query nil- {:source-query (:query q1)- :filter [:> *sum/Float 100]- :aggregation [[:sum *sum/Float]]- :breakout [$orders.product-id->products.title]- :source-metadata (expected-cols q1)})- query (lib.tu.macros/mbql-query nil- {:source-query (:query q2)- :filter [:> *sum/Float 100]- :source-metadata (expected-cols q2)})]- (is (=? (lib.tu.macros/$ids orders- [$product-id->products.title- *sum/Float])- (-> (qp.add-implicit-clauses/add-implicit-clauses query)- :query- :fields)))))))--(defn- add-implicit-clauses [query]- (qp.store/with-metadata-provider meta/metadata-provider- (qp.add-implicit-clauses/add-implicit-clauses query)))+ (let [expected-cols (fn [query]+ (-> (lib/query meta/metadata-provider query)+ qp.preprocess/query->expected-cols))+ q1 (lib.tu.macros/mbql-query orders+ {:filter [:= $id 1]+ :aggregation [[:sum $total]]+ :breakout [!day.created-at+ $product-id->products.title+ $product-id->products.category]})+ q2 (lib.tu.macros/mbql-query nil+ {:source-query (:query q1)+ :filter [:> *sum/Float 100]+ :aggregation [[:sum *sum/Float]]+ :breakout [$orders.product-id->products.title]+ :source-metadata (expected-cols q1)})+ query (lib.tu.macros/mbql-query nil+ {:source-query (:query q2)+ :filter [:> *sum/Float 100]+ :source-metadata (expected-cols q2)})]+ (is (=? [[:field "PRODUCTS__via__PRODUCT_ID__TITLE" {:base-type :type/Text}]+ [:field "sum" {:base-type :type/Float}]]+ (-> (add-implicit-clauses query)+ :query+ :fields))))))(deftest ^:parallel add-implicit-fields-for-source-query-inside-join-test(testing "Should add implicit `:fields` for `:source-query` inside a join"- (is (query= (lib.tu.macros/mbql-query venues- {:joins [{:source-query {:source-table $$categories- :fields [$categories.id- $categories.name]}- :alias "cat"- :condition [:= $venues.category-id &cat.*ID/BigInteger]}]- :fields [$venues.id- $venues.name- $venues.category-id- $venues.latitude- $venues.longitude- $venues.price]- :order-by [[:asc $venues.name]]- :limit 3})- (add-implicit-clauses- (lib.tu.macros/mbql-query venues- {:joins [{:alias "cat"- :source-query {:source-table $$categories}- :condition [:= $category-id &cat.*categories.id]}]- :order-by [[:asc $name]]- :limit 3}))))))+ (is (=? (lib.tu.macros/mbql-query venues+ {:joins [{:source-query {:source-table $$categories+ :fields [[:field %categories.id {}]+ [:field %categories.name {}]]}+ :alias "cat"+ :condition [:= $venues.category-id &cat.*ID/BigInteger]}]+ :fields [[:field %venues.id {}]+ [:field %venues.name {}]+ [:field %venues.category-id {}]+ [:field %venues.latitude {}]+ [:field %venues.longitude {}]+ [:field %venues.price {}]]+ :order-by [[:asc $venues.name]]+ :limit 3})+ (add-implicit-clauses+ (lib.tu.macros/mbql-query venues+ {:joins [{:alias "cat"+ :source-query {:source-table $$categories}+ :condition [:= $category-id &cat.*categories.id]}]+ :order-by [[:asc $name]]+ :limit 3}))))))(deftest ^:parallel add-implicit-fields-skip-join-test(testing "Don't add implicit `:fields` clause to a JOIN even if we have source metadata"- (qp.store/with-metadata-provider meta/metadata-provider- (is (query= (add-source-metadata/add-source-metadata-for-source-queries- (lib.tu.macros/mbql-query venues- {:joins [{:source-query {:source-table $$categories- :fields [$categories.id- $categories.name]}- :alias "cat"- :condition [:= $venues.category-id &cat.*ID/BigInteger]}]- :fields [$venues.id- $venues.name- $venues.category-id- $venues.latitude- $venues.longitude- $venues.price]- :order-by [[:asc $venues.name]]- :limit 3}))- (qp.add-implicit-clauses/add-implicit-mbql-clauses- (add-source-metadata/add-source-metadata-for-source-queries- (lib.tu.macros/mbql-query venues- {:source-table $$venues- :joins [{:alias "cat"- :source-query {:source-table $$categories}- :condition [:= $category-id &cat.*categories.id]}]- :order-by [[:asc $name]]- :limit 3}))))))))+ (is (=? (lib.tu.macros/mbql-query venues+ {:joins [{:source-query {:source-table $$categories+ :fields [[:field %categories.id {}]+ [:field %categories.name {}]]}+ :alias "cat"+ :condition [:= $venues.category-id &cat.*ID/BigInteger]}]+ :fields [[:field %venues.id {}]+ [:field %venues.name {}]+ [:field %venues.category-id {}]+ [:field %venues.latitude {}]+ [:field %venues.longitude {}]+ [:field %venues.price {}]]+ :order-by [[:asc $venues.name]]+ :limit 3}) (add-implicit-clauses+ (lib.tu.macros/mbql-query venues+ {:source-table $$venues+ :joins [{:alias "cat"+ :source-query {:source-table $$categories}+ :condition [:= $category-id &cat.*categories.id]}]+ :order-by [[:asc $name]]+ :limit 3}))))))+;;; These are Libor's original notes about the code in the middleware that was needed to make this test pass. With+;;; various Lib and QP improvements this just works automatically, so I moved the notes here next to the test. -- Cam+;;;+;;; > In current situation, ie. model as a source, then aggregation and breakout, and finally order by a breakout field,+;;; > [[metabase.lib.order-by/orderable-columns]] returns field ref with integer id, while reference to same field, but+;;; > with string id is present in breakout. Then, [[add-implicit-breakout-order-by]] adds the string ref to order by.+;;; >+;;; > Resulting query would contain both references, while integral is transformed differently -- it contains no+;;; > casting. As that is not part of group by, the query would fail.+;;; >+;;; > Reference: https://github.com/metabase/metabase/issues/44653.(deftest ^:parallel model-breakout-sort-querying-test(mt/test-drivers (mt/normal-drivers)(testing "Query with sort, breakout and _model as a source_ works correctly (#44653)."- (let [mp (lib.tu/mock-metadata-provider- (mt/metadata-provider)- {:cards [{:id 1- :type :model- :dataset_query (mt/mbql-query orders)}]})- field-id (mt/id :products :created_at)- {:keys [base-type name]} (lib.metadata/field mp field-id)]- (is (= [1 19 37 64 79]- (->> (lib/query- mp- (mt/mbql-query nil- {:source-table "card__1"- :aggregation [[:count]]- :breakout [[:field name {:base-type base-type :temporal-unit :month}]]- :order-by [[:asc [:field field-id {:base-type base-type :temporal-unit :month}]]]- :limit 5}))- qp/process-query- mt/rows- (mapv (comp int second)))))))))+ (let [mp (lib.tu/mock-metadata-provider+ (mt/metadata-provider)+ {:cards [{:id 1+ :type :model+ :dataset_query (mt/mbql-query orders)}]})]+ (doseq [[message query] {"with a hand-rolled query that doesn't match what the FE/Lib does anymore"+ (let [field-id (mt/id :products :created_at)+ {:keys [base-type name]} (lib.metadata/field mp field-id)]+ (lib/query+ mp+ (mt/mbql-query nil+ {:source-table "card__1"+ :aggregation [[:count]]+ :breakout [[:field name {:base-type base-type :temporal-unit :month}]]+ ;; using ID here is wrong! This is what Lib did a while back. It no longer does+ ;; this (see query below), and at any rate the `fix-bad-field-id-refs`+ ;; middleware fixes the query anyway+ :order-by [[:asc [:field field-id {:base-type base-type :temporal-unit :month}]]]+ :limit 5})))++ "with a query created using Lib to mimic what we create IRL"+ (-> (lib/query mp (lib.metadata/card mp 1))+ (lib/aggregate (lib/count))+ (as-> $query (lib/breakout $query (-> (lib.tu.notebook/find-col-with-spec+ $query+ (lib/breakoutable-columns $query)+ {:display-name "Card 1"}+ {:display-name "Created At"})+ (lib/with-temporal-bucket :month))))+ (as-> $query (lib/order-by $query (lib.tu.notebook/find-col-with-spec+ $query+ (lib/orderable-columns $query)+ {:display-name "Card 1"}+ {:display-name "Created At: Month"})))+ (lib/limit 5))}]+ (testing message+ (when (= driver/*driver* :h2)+ (testing (str "After preprocessing: should not have added any new order bys. For the hand-rolled"+ " query, breakout order by should get fixed (converted to a name ref)")+ ;; this actually gets fixed by [[metabase.query-processor.middleware.fix-bad-field-id-refs]]+ (is (=? [[:asc {} [:field {:temporal-unit :month} "CREATED_AT"]]]+ (-> query qp.preprocess/preprocess :stages second :order-by)))))+ (is (= [1 19 37 64 79]+ (->> query+ qp/process-query+ mt/rows+ (mapv (comp int second)))))))))))(deftest ^:parallel changed-coercion-of-models-underlying-data-test(let [mp (mt/metadata-provider)@@ -368,7 +384,7 @@:limit 1}))](is (=? [{:source-table (meta/id :products)}{:expressions [[:+ {:lib/expression-name "CC"} 1 1]]- :fields [[:field {} (meta/id :products :category)]+ :fields [[:field {} "CATEGORY"][:field {:base-type :type/Integer} "count"][:expression {} "CC"]]}](-> querydiff --git a/test/metabase/query_processor/middleware/add_implicit_joins_test.clj b/test/metabase/query_processor/middleware/add_implicit_joins_test.cljindex fd77d45a694..9281ec464be 100644--- a/test/metabase/query_processor/middleware/add_implicit_joins_test.clj+++ b/test/metabase/query_processor/middleware/add_implicit_joins_test.clj@@ -13,7 +13,6 @@[metabase.query-processor.middleware.add-source-metadata :as qp.add-source-metadata][metabase.query-processor.middleware.fetch-source-query][metabase.query-processor.schema :as qp.schema]- [metabase.query-processor.store :as qp.store][metabase.test :as mt][metabase.util :as u][metabase.util.malli :as mu]))@@ -73,21 +72,16 @@:query)))))(mu/defn- add-implicit-joins :- ::qp.schema/any-query- [query :- ::qp.schema/any-query]- (letfn [(add-implicit-joins-legacy [query]- (-> (lib/query (qp.store/metadata-provider) query)- qp.add-implicit-joins/add-implicit-joins- lib/->legacy-MBQL))]- (cond- (:lib/type query)- (qp.add-implicit-joins/add-implicit-joins query)+ ([query]+ (add-implicit-joins meta/metadata-provider query))- (qp.store/initialized?)- (add-implicit-joins-legacy query)-- :else- (qp.store/with-metadata-provider meta/metadata-provider- (add-implicit-joins-legacy query)))))+ ([metadata-provider+ query :- ::qp.schema/any-query]+ (if (:lib/type query)+ (qp.add-implicit-joins/add-implicit-joins query)+ (-> (lib/query metadata-provider query)+ qp.add-implicit-joins/add-implicit-joins+ lib/->legacy-MBQL))))(deftest ^:parallel basic-test(testing "make sure `:joins` get added automatically for `:fk->` clauses"@@ -267,15 +261,22 @@:fields [[:field %products.category {:source-field %product-id :source-field-name "PRODUCT_ID"}][:field %products.category {:source-field %product-id :source-field-name "Orders__Product_ID"}]]}))))))+(defn- add-implicit-clauses [query]+ (if (:lib/type query)+ (qp.add-implicit-clauses/add-implicit-clauses query)+ (-> (lib/query meta/metadata-provider query)+ qp.add-implicit-clauses/add-implicit-clauses+ lib/->legacy-MBQL)))+(deftest ^:parallel source-field-name-join-alias-test(testing "make sure that implicit joins work with an explicit `:source-field-name` and `source-field-join-alias`"(is (=? (lib.tu.macros/mbql-query orders{:source-query {:source-table $$orders- :joins [{:source-table $$orders+ :joins [{:source-query {:source-table $$orders}:alias "Orders":condition [:= $product-id [:field %product-id {:join-alias "Orders"}]]:strategy :left-join}]}- :joins [{:source-query {:joins [{:source-table $$orders+ :joins [{:source-query {:joins [{:source-query {:source-table $$orders}:alias "Orders":condition [:= $product-id [:field %product-id {:join-alias "Orders"}]]:strategy :left-join@@ -326,35 +327,34 @@[:field %products.category {:join-alias "PRODUCTS__via__Orders__PRODUCT_ID__via__Card":source-field %product-id:source-field-name "Orders__PRODUCT_ID"}]]})- (qp.store/with-metadata-provider meta/metadata-provider- (add-implicit-joins- (-> (lib.tu.macros/mbql-query orders- {:source-query {:source-table $$orders- :joins [{:source-table $$orders- :alias "Orders"- :condition [:= $product-id [:field %product-id {:join-alias "Orders"}]]- :strategy :left-join}]}- :joins [{:source-query {:source-table $$orders- :joins [{:source-table $$orders- :alias "Orders"- :condition [:= $product-id [:field %product-id {:join-alias "Orders"}]]- :strategy :left-join- :fields :none}]}- :alias "Card"- :condition [:= $product-id &Card.orders.product-id]- :strategy :left-join}]- :fields [[:field %products.category {:source-field %product-id- :source-field-name "PRODUCT_ID"}]- [:field %products.category {:source-field %product-id- :source-field-name "Orders__PRODUCT_ID"}]- [:field %products.category {:source-field %product-id- :source-field-name "PRODUCT_ID"- :source-field-join-alias "Card"}]- [:field %products.category {:source-field %product-id- :source-field-name "Orders__PRODUCT_ID"- :source-field-join-alias "Card"}]]})- qp.add-source-metadata/add-source-metadata-for-source-queries- qp.add-implicit-clauses/add-implicit-clauses)))))))+ (-> (lib.tu.macros/mbql-query orders+ {:source-query {:source-table $$orders+ :joins [{:source-table $$orders+ :alias "Orders"+ :condition [:= $product-id [:field %product-id {:join-alias "Orders"}]]+ :strategy :left-join}]}+ :joins [{:source-query {:source-table $$orders+ :joins [{:source-table $$orders+ :alias "Orders"+ :condition [:= $product-id [:field %product-id {:join-alias "Orders"}]]+ :strategy :left-join+ :fields :none}]}+ :alias "Card"+ :condition [:= $product-id &Card.orders.product-id]+ :strategy :left-join}]+ :fields [[:field %products.category {:source-field %product-id+ :source-field-name "PRODUCT_ID"}]+ [:field %products.category {:source-field %product-id+ :source-field-name "Orders__PRODUCT_ID"}]+ [:field %products.category {:source-field %product-id+ :source-field-name "PRODUCT_ID"+ :source-field-join-alias "Card"}]+ [:field %products.category {:source-field %product-id+ :source-field-name "Orders__PRODUCT_ID"+ :source-field-join-alias "Card"}]]})+ qp.add-source-metadata/add-source-metadata-for-source-queries+ add-implicit-clauses+ add-implicit-joins)))))(deftest ^:parallel reuse-existing-joins-test(testing "Should reuse existing joins rather than creating new ones"@@ -385,7 +385,7 @@(deftest ^:parallel reuse-existing-joins-e2e-test(testing "Should work at arbitrary levels of nesting"- (let [mp (mt/application-database-metadata-provider (mt/id))+ (let [mp (mt/metadata-provider)base-query (lib/querymp(mt/mbql-query orders@@ -496,15 +496,15 @@(testing "If we reuse a join, make sure we add Fields to `:fields` to the source query so we can reference them in the parent level"(is (=? (lib.tu.macros/mbql-query orders{:source-query {:source-table $$orders- :fields [$id- $user-id- $product-id- $subtotal- $tax- $total- $discount- $created-at- $quantity+ :fields [[:field %id {}]+ [:field %user-id {}]+ [:field %product-id {}]+ [:field %subtotal {}]+ [:field %tax {}]+ [:field %total {}]+ [:field %discount {}]+ [:field %created-at {}]+ [:field %quantity {}][:field %products.category {:source-field %product-id:join-alias "PRODUCTS__via__PRODUCT_ID"}]]:filter [:and@@ -528,17 +528,16 @@:order-by [[:asc [:field %products.category {:source-field %product-id:join-alias "PRODUCTS__via__PRODUCT_ID"}]]]:limit 5})- (qp.store/with-metadata-provider meta/metadata-provider- (-> (lib.tu.macros/mbql-query orders- {:source-query {:source-table $$orders- :filter [:and- [:= $user-id 1]- [:= $product-id->products.category "Doohickey"]]}- :filter [:= $product-id->products.category "Doohickey"]- :order-by [[:asc $product-id->products.category]]- :limit 5})- qp.add-implicit-clauses/add-implicit-clauses- add-implicit-joins))))))+ (-> (lib.tu.macros/mbql-query orders+ {:source-query {:source-table $$orders+ :filter [:and+ [:= $user-id 1]+ [:= $product-id->products.category "Doohickey"]]}+ :filter [:= $product-id->products.category "Doohickey"]+ :order-by [[:asc $product-id->products.category]]+ :limit 5})+ add-implicit-clauses+ add-implicit-joins)))))(deftest ^:parallel add-fields-for-reused-joins-test-2(testing "don't add fields for a native source query."@@ -609,10 +608,10 @@;; TODO - I'm not sure I understand why we add the JOIN to the outer level in this case. Does it make sense?(is (=? (lib.tu.macros/mbql-query checkins{:source-query {:source-table $$checkins- :fields [$id- $date- $user-id- $venue-id]+ :fields [[:field %id {}]+ [:field %date {}]+ [:field %user-id {}]+ [:field %venue-id {}]]:filter [:> $date "2014-01-01"]}:aggregation [[:count]]:breakout [[:field %venues.price {:source-field %venue-id, :join-alias "VENUES__via__VENUE_ID"}]]@@ -625,15 +624,14 @@:strategy :left-join:fields :none:fk-field-id %venue-id}]})- (qp.store/with-metadata-provider meta/metadata-provider- (-> (lib.tu.macros/mbql-query checkins- {:source-query {:source-table $$checkins- :filter [:> $date "2014-01-01"]}- :aggregation [[:count]]- :breakout [$venue-id->venues.price]- :order-by [[:asc $venue-id->venues.price]]})- qp.add-implicit-clauses/add-implicit-clauses- add-implicit-joins))))))+ (-> (lib.tu.macros/mbql-query checkins+ {:source-query {:source-table $$checkins+ :filter [:> $date "2014-01-01"]}+ :aggregation [[:count]]+ :breakout [$venue-id->venues.price]+ :order-by [[:asc $venue-id->venues.price]]})+ add-implicit-clauses+ add-implicit-joins)))))(deftest ^:parallel topologically-sort-joins-test(let [parent (lib/normalize@@ -963,60 +961,60 @@(deftest ^:parallel test-59695(testing "Resolving an implicit join should not add field refs to incorrect places (#59695)"- (let [mp (lib.tu/mock-metadata-provider- meta/metadata-provider- {:cards [{:id 1- :dataset-query (lib.tu.macros/mbql-query orders)}]})- query (lib/query- mp- (lib.tu.macros/mbql-query nil- {:source-table "card__1"- :joins [{:source-table (meta/id :checkins)- :fields :all- :strategy :left-join- :alias "CH"- :condition [:=- [:field- "ID"- {:base-type :type/BigInteger}]- [:field- (meta/id :checkins :id)- {:base-type :type/BigInteger, :join-alias "CH"}]]}]- :filter [:=- [:field (meta/id :venues :price) {:base-type :type/Text- :source-field (meta/id :checkins :venue-id)- :source-field-join-alias "CH"}]- "Basic"]}))]- (qp.store/with-metadata-provider mp- (let [query' (-> query- metabase.query-processor.middleware.fetch-source-query/resolve-source-cards- lib/->legacy-MBQL- qp.add-implicit-clauses/add-implicit-clauses)]- (testing "sanity check: before add-implicit-joins"- (is (=? {:source-table (meta/id :orders)- :fields [[:field (meta/id :orders :id) nil]- [:field (meta/id :orders :user-id) nil]- [:field (meta/id :orders :product-id) nil]- [:field (meta/id :orders :subtotal) nil]- [:field (meta/id :orders :tax) nil]- [:field (meta/id :orders :total) nil]- [:field (meta/id :orders :discount) nil]- [:field (meta/id :orders :created-at) nil]- [:field (meta/id :orders :quantity) nil]]}- (-> query' :query :source-query))))- (testing "after add-implicit-joins"- (let [query'' (lib/->legacy-MBQL (qp.add-implicit-joins/add-implicit-joins (lib/query mp query')))]- (is (=? {:source-table (meta/id :orders)- :fields [[:field (meta/id :orders :id) nil]- [:field (meta/id :orders :user-id) nil]- [:field (meta/id :orders :product-id) nil]- [:field (meta/id :orders :subtotal) nil]- [:field (meta/id :orders :tax) nil]- [:field (meta/id :orders :total) nil]- [:field (meta/id :orders :discount) nil]- [:field (meta/id :orders :created-at) nil]- [:field (meta/id :orders :quantity) nil]]}- (-> query'' :query :source-query))))))))))+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query (lib.tu.macros/mbql-query orders)}]})+ query (lib/query+ mp+ (lib.tu.macros/mbql-query nil+ {:source-table "card__1"+ :joins [{:source-table (meta/id :checkins)+ :fields :all+ :strategy :left-join+ :alias "CH"+ :condition [:=+ [:field+ "ID"+ {:base-type :type/BigInteger}]+ [:field+ (meta/id :checkins :id)+ {:base-type :type/BigInteger, :join-alias "CH"}]]}]+ :filter [:=+ [:field (meta/id :venues :price) {:base-type :type/Text+ :source-field (meta/id :checkins :venue-id)+ :source-field-join-alias "CH"}]+ "Basic"]}))+ query' (-> query+ metabase.query-processor.middleware.fetch-source-query/resolve-source-cards+ add-implicit-clauses)]+ (testing "sanity check: before add-implicit-joins"+ (is (=? {:source-table (meta/id :orders)+ :fields [[:field (meta/id :orders :id) {}]+ [:field (meta/id :orders :user-id) {}]+ [:field (meta/id :orders :product-id) {}]+ [:field (meta/id :orders :subtotal) {}]+ [:field (meta/id :orders :tax) {}]+ [:field (meta/id :orders :total) {}]+ [:field (meta/id :orders :discount) {}]+ [:field (meta/id :orders :created-at) {}]+ [:field (meta/id :orders :quantity) {}]]}+ (-> query' lib/->legacy-MBQL :query :source-query))))+ (testing "after add-implicit-joins"+ (let [query'' (-> query'+ qp.add-implicit-joins/add-implicit-joins+ lib/->legacy-MBQL)]+ (is (=? {:source-table (meta/id :orders)+ :fields [[:field (meta/id :orders :id) {}]+ [:field (meta/id :orders :user-id) {}]+ [:field (meta/id :orders :product-id) {}]+ [:field (meta/id :orders :subtotal) {}]+ [:field (meta/id :orders :tax) {}]+ [:field (meta/id :orders :total) {}]+ [:field (meta/id :orders :discount) {}]+ [:field (meta/id :orders :created-at) {}]+ [:field (meta/id :orders :quantity) {}]]}+ (-> query'' :query :source-query))))))))(deftest ^:parallel join-against-implicit-join-test(testing "Should be able to explicitly join against an implicit join (#20519)"diff --git a/test/metabase/query_processor/middleware/add_remaps_test.clj b/test/metabase/query_processor/middleware/add_remaps_test.cljindex 746af0035eb..a3173bb00eb 100644--- a/test/metabase/query_processor/middleware/add_remaps_test.clj+++ b/test/metabase/query_processor/middleware/add_remaps_test.clj@@ -524,7 +524,7 @@(deftest ^:parallel internal-remap-e2e-test(qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :venues :category_id)(mapv first (mt/rows (qp/process-query(mt/mbql-query categories@@ -625,15 +625,15 @@"first join source query should have 10 fields (9 from orders plus one from the remap)")(is (=? {:source-table (meta/id :orders):joins [{:alias "PEOPLE__via__USER_ID"}]- :fields [[:field (meta/id :orders :id) nil]+ :fields [[:field (meta/id :orders :id) {}][:field (meta/id :orders :user-id) {::qp.add-remaps/original-field-dimension-id pos-int?}]- [:field (meta/id :orders :product-id) nil]- [:field (meta/id :orders :subtotal) nil]- [:field (meta/id :orders :tax) nil]- [:field (meta/id :orders :total) nil]- [:field (meta/id :orders :discount) nil]- [:field (meta/id :orders :created-at) nil]- [:field (meta/id :orders :quantity) nil]+ [:field (meta/id :orders :product-id) {}]+ [:field (meta/id :orders :subtotal) {}]+ [:field (meta/id :orders :tax) {}]+ [:field (meta/id :orders :total) {}]+ [:field (meta/id :orders :discount) {}]+ [:field (meta/id :orders :created-at) {}]+ [:field (meta/id :orders :quantity) {}];; 1 remap for self-joined orders.user-id => people.email[:field (meta/id :people :email) {:source-field (meta/id :orders :user-id):join-alias "PEOPLE__via__USER_ID"@@ -667,15 +667,15 @@(count (:fields preprocessed-query)))"Should have 20 fields")(is (=? {:fields [;; 9 columns from orders- [:field (meta/id :orders :id) nil]+ [:field (meta/id :orders :id) {}][:field (meta/id :orders :user-id) {::qp.add-remaps/original-field-dimension-id pos-int?}]- [:field (meta/id :orders :product-id) nil]- [:field (meta/id :orders :subtotal) nil]- [:field (meta/id :orders :tax) nil]- [:field (meta/id :orders :total) nil]- [:field (meta/id :orders :discount) nil]- [:field (meta/id :orders :created-at) nil]- [:field (meta/id :orders :quantity) nil]+ [:field (meta/id :orders :product-id) {}]+ [:field (meta/id :orders :subtotal) {}]+ [:field (meta/id :orders :tax) {}]+ [:field (meta/id :orders :total) {}]+ [:field (meta/id :orders :discount) {}]+ [:field (meta/id :orders :created-at) {}]+ [:field (meta/id :orders :quantity) {}];; 9 columns from self-join against orders[:field (meta/id :orders :id) {:join-alias "j"}][:field (meta/id :orders :user-id) {:join-alias "j", ::qp.add-remaps/original-field-dimension-id pos-int?}]diff --git a/test/metabase/query_processor/middleware/add_source_metadata_test.clj b/test/metabase/query_processor/middleware/add_source_metadata_test.cljindex 158245df7a6..2b8d2724bd7 100644--- a/test/metabase/query_processor/middleware/add_source_metadata_test.clj+++ b/test/metabase/query_processor/middleware/add_source_metadata_test.clj@@ -244,9 +244,7 @@(is (=? (lib.tu.macros/mbql-query venues{:source-query {:source-query {:native "SELECT \"ID\", \"NAME\" FROM \"VENUES\";"}:source-metadata (venues-source-metadata :id :name)}- :source-metadata (let [[id-col name-col] (venues-source-metadata :id :name)]- [(assoc id-col :field_ref [:field "ID" {:base-type :type/BigInteger}])- (assoc name-col :field_ref [:field "NAME" {:base-type :type/Text}])])})+ :source-metadata (venues-source-metadata :id :name)})(add-source-metadata(lib.tu.macros/mbql-query venues{:source-query {:source-query {:native "SELECT \"ID\", \"NAME\" FROM \"VENUES\";"}@@ -382,25 +380,3 @@(dissoc col :field_ref :id))](is (=? expected-metadata(added-metadata (assoc-in query [:query :source-metadata] legacy-metadata))))))))))--(deftest ^:parallel add-correct-metadata-fields-for-deeply-nested-source-queries-test- (testing "Make sure we add correct `:fields` from deeply-nested source queries (#14872)"- ;; this should return a field literal ref because that's what we used in the query, even if that's not technically- ;; correct.- (is (= [[:field "TITLE" {:base-type :type/Text}]- [:aggregation 0]]- (->> (lib.tu.macros/mbql-query orders- {:source-query {:source-query {:source-table $$orders- :filter [:= $id 1]- :aggregation [[:sum $total]]- :breakout [!day.created-at- $product-id->products.title- $product-id->products.category]}- :filter [:> *sum/Float 100]- :aggregation [[:sum *sum/Float]]- :breakout [*TITLE/Text]}- :filter [:> *sum/Float 100]})- add-source-metadata- :query- :source-metadata- (map :field_ref))))))diff --git a/test/metabase/query_processor/middleware/resolve_joined_fields_test.clj b/test/metabase/query_processor/middleware/fix_bad_field_id_refs_test.cljsimilarity index 96%rename from test/metabase/query_processor/middleware/resolve_joined_fields_test.cljrename to test/metabase/query_processor/middleware/fix_bad_field_id_refs_test.cljindex a09fb75e18a..8c85ae8babb 100644--- a/test/metabase/query_processor/middleware/resolve_joined_fields_test.clj+++ b/test/metabase/query_processor/middleware/fix_bad_field_id_refs_test.clj@@ -1,4 +1,4 @@-(ns metabase.query-processor.middleware.resolve-joined-fields-test+(ns metabase.query-processor.middleware.fix-bad-field-id-refs-test(:require[clojure.test :refer :all][metabase.lib.core :as lib]@@ -7,7 +7,7 @@[metabase.lib.test-util :as lib.tu][metabase.lib.test-util.macros :as lib.tu.macros][metabase.query-processor :as qp]- [metabase.query-processor.middleware.resolve-joined-fields :as resolve-joined-fields]+ [metabase.query-processor.middleware.fix-bad-field-id-refs :as fix-bad-field-id-refs][metabase.test :as mt][metabase.util :as u]))@@ -17,7 +17,7 @@([metadata-provider query](-> (lib/query metadata-provider query)- resolve-joined-fields/resolve-joined-fields+ fix-bad-field-id-refs/fix-bad-field-id-refslib/->legacy-MBQL)))(deftest ^:parallel wrap-fields-in-joined-field-test@@ -49,7 +49,7 @@:condition [:= $user-id &u.users.id]}]}}))))))(deftest ^:parallel deduplicate-fields-test- (testing "resolve-joined-fields should deduplicate :fields after resolving stuff"+ (testing "fix-bad-field-id-refs should deduplicate :fields after resolving stuff"(is (=? (lib.tu.macros/mbql-query checkins{:fields [[:field %users.name {:join-alias "u"}]]:filter [:!= [:field %users.name {:join-alias "u"}] nil]@@ -65,7 +65,7 @@:alias "u":condition [:= $user-id &u.users.id]}]}))))))-(deftest ^:parallel resolve-joined-fields-in-source-queries-test+(deftest ^:parallel fix-bad-field-id-refs-in-source-queries-test(testing "Should be able to resolve joined fields at any level of the query (#13642)"(testing "simple query"(let [query (lib.tu.macros/mbql-query nil@@ -81,7 +81,7 @@(is (=? {:query {:filter (lib.tu.macros/$ids [:= [:field %products.category {:join-alias "products"}] "Widget"])}}(wrap-joined-fields query))))))))-(deftest ^:parallel resolve-joined-fields-in-source-queries-test-2+(deftest ^:parallel fix-bad-field-id-refs-in-source-queries-test-2(testing "Should be able to resolve joined fields at any level of the query (#13642)"(testing "nested query"(let [nested-query (lib.tu.macros/mbql-query nil@@ -98,7 +98,7 @@[:= [:field %products.category {:join-alias "products"}] "Widget"])}}}(wrap-joined-fields nested-query))))))))-(deftest ^:parallel resolve-joined-fields-in-source-queries-e2e-test+(deftest ^:parallel fix-bad-field-id-refs-in-source-queries-e2e-test(testing "Should be able to resolve joined fields at any level of the query (#13642)"(testing "joins in joins query"(let [joins-in-joins-query@@ -120,12 +120,12 @@(is (= (assoc-in joins-in-joins-query[:query :joins 0 :source-query :filter](mt/$ids [:= [:field %products.category {:join-alias "products"}] "Widget"]))- (wrap-joined-fields (mt/application-database-metadata-provider (mt/id)) joins-in-joins-query)))+ (wrap-joined-fields (mt/metadata-provider) joins-in-joins-query)))(testing "Can we actually run the join-in-joins query?"(is (=? {:status :completed, :row_count 1}(qp/process-query (assoc-in joins-in-joins-query [:query :limit] 1))))))))))-(deftest ^:parallel resolve-joined-fields-in-source-queries-test-4+(deftest ^:parallel fix-bad-field-id-refs-in-source-queries-test-4(testing "Should be able to resolve joined fields at any level of the query (#13642)"(testing "multiple joins in joins query"(let [joins-in-joins-query@@ -204,7 +204,7 @@$products.title[:field %products.title {:join-alias "PRODUCTS__via__PRODUCT_ID"}]]})](testing "Middleware should handle the query"- (is (some? (wrap-joined-fields (mt/application-database-metadata-provider (mt/id)) query))))+ (is (some? (wrap-joined-fields (mt/metadata-provider) query))))(testing "Should be able tor run query end-to-end"(is (=? {:status :completed:row_count 10}@@ -328,4 +328,4 @@[:field {:join-alias "B"} 4] ; join alias should get added here[:field {:join-alias "C"}5]]]}]}]}- (resolve-joined-fields/resolve-joined-fields query))))))+ (fix-bad-field-id-refs/fix-bad-field-id-refs query))))))diff --git a/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.clj b/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.cljindex a975c6f0e18..7ad3e96fb1e 100644--- a/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.clj+++ b/test/metabase/query_processor/middleware/remove_inactive_field_refs_test.clj@@ -33,7 +33,7 @@:aggregation [[:count]]}:filter [:= *count/Integer 3976]}))](is (=? {:stages [{}- {:fields [[:field {} (meta/id :products :category)]+ {:fields [[:field {} "T__CATEGORY"][:field {} "count"]]}]}(qp.preprocess/preprocess query))))))@@ -210,23 +210,23 @@qp.preprocess/preprocesslib/->legacy-MBQL)](testing ":query => :joins => first => :source-query => :fields"- (is (=? [[:field (mt/id :orders :id) nil]- [:field (mt/id :orders :subtotal) nil]- [:field (mt/id :orders :total) nil]- [:field (mt/id :orders :created_at) nil]- [:field (mt/id :orders :quantity) nil]- [:field (mt/id :products :id) {:join-alias "Product"}]- [:field (mt/id :products :title) {:join-alias "Product"}]- [:field (mt/id :products :price) {:join-alias "Product"}]- [:field (mt/id :products :rating) {:join-alias "Product"}]]+ (is (=? [[:field "ID" {:base-type :type/BigInteger}]+ [:field "SUBTOTAL" {:base-type :type/Float}]+ [:field "TOTAL" {:base-type :type/Float}]+ [:field "CREATED_AT" {:base-type :type/DateTimeWithLocalTZ}]+ [:field "QUANTITY" {:base-type :type/Integer}]+ [:field "Product__ID" {:base-type :type/BigInteger}]+ [:field "Product__TITLE" {:base-type :type/Text}]+ [:field "Product__PRICE" {:base-type :type/Float}]+ [:field "Product__RATING" {:base-type :type/Float}]](-> preprocessed :query :joins first :source-query :fields))))(testing ":query => :fields"- (is (=? [[:field (mt/id :products :id) nil]- [:field (mt/id :products :title) nil]- [:field (mt/id :products :category) nil]- [:field (mt/id :products :price) nil]- [:field (mt/id :products :rating) nil]- [:field (mt/id :products :created_at) nil]+ (is (=? [[:field (mt/id :products :id) {}]+ [:field (mt/id :products :title) {}]+ [:field (mt/id :products :category) {}]+ [:field (mt/id :products :price) {}]+ [:field (mt/id :products :rating) {}]+ [:field (mt/id :products :created_at) {}][:field "ID_2" {:join-alias "Card", :base-type :type/BigInteger}][:field "TOTAL" {:join-alias "Card", :base-type :type/Float}]](-> preprocessed :query :fields)))))))diff --git a/test/metabase/query_processor/middleware/resolve_joins_test.clj b/test/metabase/query_processor/middleware/resolve_joins_test.cljindex e9f210c1f55..5ed2ad16aa1 100644--- a/test/metabase/query_processor/middleware/resolve_joins_test.clj+++ b/test/metabase/query_processor/middleware/resolve_joins_test.clj@@ -57,48 +57,48 @@(deftest ^:parallel fields-all-test(testing "Can we resolve some joins w/ fields = all ???"- (is (query= (mt/mbql-query venues- {:joins- [{:source-table $$categories- :alias "c"- :strategy :left-join- :condition [:= $category_id &c.categories.id]- :fields [&c.categories.id- &c.categories.name]}]- :fields [$venues.id- $venues.name- [:field %categories.id {:join-alias "c"- :qp/ignore-coercion true}]- [:field %categories.name {:join-alias "c"- :qp/ignore-coercion true}]]})- (resolve-joins- (mt/mbql-query venues- {:fields [$venues.id $venues.name]- :joins [{:source-table $$categories- :alias "c"- :condition [:= $category_id &c.categories.id]- :fields :all}]}))))))+ (is (= (mt/mbql-query venues+ {:joins+ [{:source-table $$categories+ :alias "c"+ :strategy :left-join+ :condition [:= $category_id &c.categories.id]+ :fields [&c.categories.id+ &c.categories.name]}]+ :fields [$venues.id+ $venues.name+ [:field %categories.id {:join-alias "c"+ :qp/ignore-coercion true}]+ [:field %categories.name {:join-alias "c"+ :qp/ignore-coercion true}]]})+ (resolve-joins+ (mt/mbql-query venues+ {:fields [$venues.id $venues.name]+ :joins [{:source-table $$categories+ :alias "c"+ :condition [:= $category_id &c.categories.id]+ :fields :all}]}))))))(deftest ^:parallel fields-sequence-test(testing "can we resolve joins w/ fields = <sequence>"- (is (query= (mt/mbql-query venues- {:joins- [{:source-table $$categories- :alias "c"- :strategy :left-join- :condition [:= $category_id &c.categories.id]- :fields [&c.categories.name]}]- :fields [$venues.id- $venues.name- [:field %categories.name {:join-alias "c"- :qp/ignore-coercion true}]]})- (resolve-joins- (mt/mbql-query venues- {:fields [$venues.id $venues.name]- :joins [{:source-table $$categories- :alias "c"- :condition [:= $category_id &c.categories.id]- :fields [&c.categories.name]}]}))))))+ (is (= (mt/mbql-query venues+ {:joins+ [{:source-table $$categories+ :alias "c"+ :strategy :left-join+ :condition [:= $category_id &c.categories.id]+ :fields [&c.categories.name]}]+ :fields [$venues.id+ $venues.name+ [:field %categories.name {:join-alias "c"+ :qp/ignore-coercion true}]]})+ (resolve-joins+ (mt/mbql-query venues+ {:fields [$venues.id $venues.name]+ :joins [{:source-table $$categories+ :alias "c"+ :condition [:= $category_id &c.categories.id]+ :fields [&c.categories.name]}]}))))))(deftest ^:parallel join-table-without-alias-test(testing "Does joining a table an explicit alias add a default alias?"@@ -207,41 +207,41 @@[:field "ID" {:base-type :type/BigInteger, :join-alias "cat"}]]}]:order-by [[:asc $name]]:limit 3}))]- (is (query= (mt/mbql-query venues- {:fields [[:field (mt/id :categories :id) {:join-alias "cat", :qp/ignore-coercion true}]- [:field (mt/id :categories :name) {:join-alias "cat", :qp/ignore-coercion true}]]- :joins [{:alias "cat"- :source-query {:source-table $$categories}- :source-metadata source-metadata- :strategy :left-join- :condition [:= $category_id [:field "ID" {:base-type :type/BigInteger, :join-alias "cat"}]]- :fields [&cat.categories.id- &cat.categories.name]}]- :order-by [[:asc $name]]- :limit 3})- resolved)))))+ (is (= (mt/mbql-query venues+ {:fields [[:field (mt/id :categories :id) {:join-alias "cat", :qp/ignore-coercion true}]+ [:field (mt/id :categories :name) {:join-alias "cat", :qp/ignore-coercion true}]]+ :joins [{:alias "cat"+ :source-query {:source-table $$categories}+ :source-metadata source-metadata+ :strategy :left-join+ :condition [:= $category_id [:field "ID" {:base-type :type/BigInteger, :join-alias "cat"}]]+ :fields [&cat.categories.id+ &cat.categories.name]}]+ :order-by [[:asc $name]]+ :limit 3})+ resolved)))))(deftest ^:parallel dont-append-fields-if-parent-has-breakout-or-aggregation-test(testing "if the parent level has a breakout or aggregation, we shouldn't append Join fields to the parent level"- (is (query= (mt/mbql-query users- {:joins [{:source-table $$checkins- :alias "c"- :strategy :left-join- :condition [:= $id [:field "USER_ID" {:base-type :type/Integer, :join-alias "c"}]]- :fields [&c.checkins.id- &c.checkins.date- &c.checkins.user_id- &c.checkins.venue_id]}]- :aggregation [[:sum [:field "id" {:base-type :type/Float, :join-alias "c"}]]]- :breakout [[:field %last_login {:temporal-unit :month}]]})- (resolve-joins- (mt/mbql-query users- {:joins [{:fields :all- :alias "c"- :source-table $$checkins- :condition [:= $id [:field "USER_ID" {:base-type :type/Integer, :join-alias "c"}]]}]- :aggregation [[:sum [:field "id" {:base-type :type/Float, :join-alias "c"}]]]- :breakout [[:field %last_login {:temporal-unit :month}]]}))))))+ (is (= (mt/mbql-query users+ {:joins [{:source-table $$checkins+ :alias "c"+ :strategy :left-join+ :condition [:= $id [:field "USER_ID" {:base-type :type/Integer, :join-alias "c"}]]+ :fields [&c.checkins.id+ &c.checkins.date+ &c.checkins.user_id+ &c.checkins.venue_id]}]+ :aggregation [[:sum [:field "id" {:base-type :type/Float, :join-alias "c"}]]]+ :breakout [[:field %last_login {:temporal-unit :month}]]})+ (resolve-joins+ (mt/mbql-query users+ {:joins [{:fields :all+ :alias "c"+ :source-table $$checkins+ :condition [:= $id [:field "USER_ID" {:base-type :type/Integer, :join-alias "c"}]]}]+ :aggregation [[:sum [:field "id" {:base-type :type/Float, :join-alias "c"}]]]+ :breakout [[:field %last_login {:temporal-unit :month}]]}))))))(deftest ^:parallel aggregation-field-ref-test(testing "Should correctly handle [:aggregation n] field refs"@@ -281,59 +281,59 @@:semantic_type :type/FK:field_ref [:field "_USER_ID" {:base-type :type/Integer :join-alias "alias"}]:fingerprint {:global {:distinct-count 15, :nil% 0.0}}}]]- (is (query= (mt/mbql-query users- {:fields [$id- [:field "_USER_ID" {:base-type :type/Integer- :join-alias "alias"- :qp/ignore-coercion true}]]- :joins [{:fields [[:field "_USER_ID" {:base-type :type/Integer :join-alias "alias"}]]- :alias "alias"- :strategy :left-join- :condition [:= $id [:field "_USER_ID" {:base-type :type/Integer :join-alias "alias"}]]- :source-query {:native "SELECT USER_ID AS _USER_ID FROM CHECKINS"}- :source-metadata source-metadata}]- :limit 10})- (resolve-joins- (mt/mbql-query users- {:fields [$id]- :joins [{:fields :all- :alias "alias"- :condition [:= $id [:field "_USER_ID" {:base-type :type/Integer :join-alias "alias"}]]- :source-query {:native "SELECT USER_ID AS _USER_ID FROM CHECKINS"}- :source-metadata source-metadata}]- :limit 10})))))))+ (is (= (mt/mbql-query users+ {:fields [$id+ [:field "_USER_ID" {:base-type :type/Integer+ :join-alias "alias"+ :qp/ignore-coercion true}]]+ :joins [{:fields [[:field "_USER_ID" {:base-type :type/Integer :join-alias "alias"}]]+ :alias "alias"+ :strategy :left-join+ :condition [:= $id [:field "_USER_ID" {:base-type :type/Integer :join-alias "alias"}]]+ :source-query {:native "SELECT USER_ID AS _USER_ID FROM CHECKINS"}+ :source-metadata source-metadata}]+ :limit 10})+ (resolve-joins+ (mt/mbql-query users+ {:fields [$id]+ :joins [{:fields :all+ :alias "alias"+ :condition [:= $id [:field "_USER_ID" {:base-type :type/Integer :join-alias "alias"}]]+ :source-query {:native "SELECT USER_ID AS _USER_ID FROM CHECKINS"}+ :source-metadata source-metadata}]+ :limit 10})))))))(deftest ^:parallel join-against-source-query-test- (is (query= (mt/mbql-query venues- {:joins [{:source-query {:source-table $$categories- :fields [$categories.id- $categories.name]}- :alias "cat"- :condition [:= $venues.category_id &cat.*ID/BigInteger]- :strategy :left-join}]- :fields [$venues.id- $venues.name- $venues.category_id- $venues.latitude- $venues.longitude- $venues.price]- :order-by [[:asc $venues.name]]- :limit 3})- (resolve-joins- (mt/mbql-query venues- {:joins [{:source-query {:source-table $$categories- :fields [$categories.id- $categories.name]}- :alias "cat"- :condition [:= $venues.category_id &cat.*ID/BigInteger]}]- :fields [$venues.id- $venues.name- $venues.category_id- $venues.latitude- $venues.longitude- $venues.price]- :order-by [[:asc $venues.name]]- :limit 3})))))+ (is (= (mt/mbql-query venues+ {:joins [{:source-query {:source-table $$categories+ :fields [$categories.id+ $categories.name]}+ :alias "cat"+ :condition [:= $venues.category_id &cat.*ID/BigInteger]+ :strategy :left-join}]+ :fields [$venues.id+ $venues.name+ $venues.category_id+ $venues.latitude+ $venues.longitude+ $venues.price]+ :order-by [[:asc $venues.name]]+ :limit 3})+ (resolve-joins+ (mt/mbql-query venues+ {:joins [{:source-query {:source-table $$categories+ :fields [$categories.id+ $categories.name]}+ :alias "cat"+ :condition [:= $venues.category_id &cat.*ID/BigInteger]}]+ :fields [$venues.id+ $venues.name+ $venues.category_id+ $venues.latitude+ $venues.longitude+ $venues.price]+ :order-by [[:asc $venues.name]]+ :limit 3})))))(deftest ^:parallel do-not-duplicate-columns-with-default-temporal-bucketing-test(testing "Do not add a duplicate column from a join if it uses :default temporal bucketing"@@ -383,13 +383,11 @@:fields [&Products.products.price]}]:fields [$id]})}]})query (lib/query mp (lib.metadata/card mp 1))]- (is (=? (lib.tu.macros/$ids orders- [$id- &People.people.longitude- ;; the `:default` temporal unit gets removed somewhere- &People.people.birth-date- &Products.products.price])- (-> query qp.preprocess/preprocess lib/->legacy-MBQL :query :fields))))))+ (is (= [[:field "ID" {:base-type :type/BigInteger}]+ [:field "People__LONGITUDE" {:base-type :type/Float}]+ [:field "People__BIRTH_DATE" {:inherited-temporal-unit :default, :base-type :type/Date}]+ [:field "Products__PRICE" {:base-type :type/Float}]]+ (-> query qp.preprocess/preprocess lib/->legacy-MBQL :query :fields))))));;; adapted from [[metabase.query-processor-test.explicit-joins-test/join-against-saved-question-with-sort-test]](deftest ^:parallel join-against-same-table-returned-columns-test@@ -448,12 +446,12 @@[:field "VENUE_ID" {:base-type :type/Integer, :join-alias "native_card"}]]:strategy :left-join}]:limit 10}})]- (is (=? {:query {:fields [[:field (meta/id :venues :id) nil]- [:field (meta/id :venues :name) nil]- [:field (meta/id :venues :category-id) nil]- [:field (meta/id :venues :latitude) nil]- [:field (meta/id :venues :longitude) nil]- [:field (meta/id :venues :price) nil]+ (is (=? {:query {:fields [[:field "ID" {}]+ [:field "NAME" {}]+ [:field "CATEGORY_ID" {}]+ [:field "LATITUDE" {}]+ [:field "LONGITUDE" {}]+ [:field "PRICE" {}][:field "ID" {:base-type :type/Integer, :join-alias "native_card"}]]}}(-> queryqp.preprocess/preprocessdiff --git a/test/metabase/query_processor/pivot_test.clj b/test/metabase/query_processor/pivot_test.cljindex 556b825f28e..2c8052d3ed5 100644--- a/test/metabase/query_processor/pivot_test.clj+++ b/test/metabase/query_processor/pivot_test.clj@@ -348,7 +348,7 @@(deftest ^:parallel nested-models-with-expressions-pivot-breakout-names-test(testing "#43993 again - breakouts on an expression from the inner model should pass"(qp.store/with-metadata-provider (lib.tu/mock-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){:cards [{:id 1:type :model:name "Model A"@@ -708,8 +708,8 @@{:pivot_rows [0 1]:pivot_cols []})](is (= (mt/$ids orders- [[:field %products.category {:source-field %product_id, :base-type :type/Text}]- [:field %people.source {:source-field %user_id, :base-type :type/Text}]+ [[:field %products.category {:source-field %product_id}]+ [:field %people.source {:source-field %user_id}][:expression "pivot-grouping"][:aggregation 0]])(mapv :field_ref (mt/cols (qp.pivot/run-pivot-query query))))))))diff --git a/test/metabase/query_processor/preprocess_test.clj b/test/metabase/query_processor/preprocess_test.cljindex d4bb99f7d5c..b3ea18e1ca8 100644--- a/test/metabase/query_processor/preprocess_test.clj+++ b/test/metabase/query_processor/preprocess_test.clj@@ -354,12 +354,10 @@:fields [&Products.products.price]}]:fields [$id]})}]})query (lib/query mp (lib.metadata/card mp 1))]- (is (=? {:query {:fields (lib.tu.macros/$ids orders- [$id- &People.people.longitude- ;; the `:default` temporal unit gets removed somewhere- &People.people.birth-date- &Products.products.price])}}+ (is (=? {:query {:fields [[:field "ID" {:base-type :type/BigInteger}]+ [:field "People__LONGITUDE" {:base-type :type/Float}]+ [:field "People__BIRTH_DATE" {:base-type :type/Date, :inherited-temporal-unit :default}]+ [:field "Products__PRICE" {:base-type :type/Float}]]}}(-> queryqp.preprocess/preprocesslib/->legacy-MBQL)))@@ -407,7 +405,11 @@{:name "count", :display-name "Count", :field-ref [:field "count" {}]}](lib.metadata.result-metadata/returned-columns query))))(testing `qp.preprocess/query->expected-cols- (is (=? [{:name "CREATED_AT_2", :display_name "Created At: Month", :field_ref [:field "CREATED_AT_2" {}]}+ ;; I think traditionally this field ref would have used a Field ID, and `:field_ref` should aim to preserve+ ;; the traditional response as much as possible. It only comes back as a ID ref here because the preprocessing+ ;; middleware that adds implicit columns adds the `:qp/added-implicit-fields?` key which+ ;; causes [[metabase.lib.metadata.result-metadata/super-broken-legacy-field-ref]] to force ID refs+ (is (=? [{:name "CREATED_AT_2", :display_name "Created At: Month", :field_ref [:field (meta/id :orders :created-at) nil]}{:name "count", :display_name "Count", :field_ref [:field "count" {}]}](qp.preprocess/query->expected-cols query)))))))@@ -435,15 +437,15 @@:source-field-join-alias "CH"}]"1234"]}))](is (=? {:query {:source-query {:source-table (meta/id :orders)- :fields [[:field (meta/id :orders :id) nil]- [:field (meta/id :orders :user-id) nil]- [:field (meta/id :orders :product-id) nil]- [:field (meta/id :orders :subtotal) nil]- [:field (meta/id :orders :tax) nil]- [:field (meta/id :orders :total) nil]- [:field (meta/id :orders :discount) nil]- [:field (meta/id :orders :created-at) nil]- [:field (meta/id :orders :quantity) nil]]}+ :fields [[:field (meta/id :orders :id) {}]+ [:field (meta/id :orders :user-id) {}]+ [:field (meta/id :orders :product-id) {}]+ [:field (meta/id :orders :subtotal) {}]+ [:field (meta/id :orders :tax) {}]+ [:field (meta/id :orders :total) {}]+ [:field (meta/id :orders :discount) {}]+ [:field (meta/id :orders :created-at) {}]+ [:field (meta/id :orders :quantity) {}]]}:joins [{:source-query {:source-table (meta/id :checkins)}:alias "CH":strategy :left-join@@ -464,16 +466,17 @@:condition [:=[:field (meta/id :checkins :venue-id) {:join-alias "CH"}][:field (meta/id :venues :id) {:join-alias "VENUES__via__VENUE_ID__via__CH"}]]}]- ;; TODO (Cam 7/15/25) -- these should ACTUALLY be using field name refs rather than ID refs- :fields [[:field (meta/id :orders :id) nil]- [:field (meta/id :orders :user-id) nil]- [:field (meta/id :orders :product-id) nil]- [:field (meta/id :orders :subtotal) nil]- [:field (meta/id :orders :tax) nil]- [:field (meta/id :orders :total) nil]- [:field (meta/id :orders :discount) nil]- [:field (meta/id :orders :created-at) nil]- [:field (meta/id :orders :quantity) nil]+ :fields [[:field "ID" {:base-type :type/BigInteger}]+ [:field "USER_ID" {:base-type :type/Integer}]+ [:field "PRODUCT_ID" {:base-type :type/Integer}]+ [:field "SUBTOTAL" {:base-type :type/Float}]+ [:field "TAX" {:base-type :type/Float}]+ [:field "TOTAL" {:base-type :type/Float}]+ [:field "DISCOUNT" {:base-type :type/Float}]+ [:field "CREATED_AT" {:base-type :type/DateTimeWithLocalTZ}]+ [:field "QUANTITY" {:base-type :type/Integer}]+ ;; TODO (Cam 7/15/25) -- these should ACTUALLY be using field name refs rather+ ;; than ID refs as well[:field (meta/id :checkins :id) {:join-alias "CH"}][:field (meta/id :checkins :date) {:join-alias "CH"}][:field (meta/id :checkins :user-id) {:join-alias "CH"}]@@ -506,8 +509,10 @@:limit 3}))](is (=? {:query {:joins [{:fields [[:field (meta/id :people :birth-date) {:join-alias "Q2"}][:field "count" {:base-type :type/Integer, :join-alias "Q2"}]]}]- :fields [[:field (meta/id :people :created-at) {:inherited-temporal-unit :month}]+ :fields [[:field "CREATED_AT" {:inherited-temporal-unit :month}][:field "count" {:base-type :type/Integer}]+ ;; TODO (Cam 9/11/25) -- this should use a name ref as well, once we convert the+ ;; `resolve-joins` middleware this should be fixed[:field (meta/id :people :birth-date) {:join-alias "Q2"}][:field "count" {:base-type :type/Integer, :join-alias "Q2"}]]}}(-> query@@ -578,7 +583,7 @@:stages [{:fields #(= (count %) 8)}]}{:alias "People - User":stages [{:fields #(= (count %) 13)}]}]}- {:fields [[:field {:join-alias "Products"} (meta/id :products :category)]+ {:fields [[:field {} "Products__CATEGORY"][:field {} "count"]]}{:fields [[:field {} "Products__CATEGORY"][:field {} "count"]@@ -586,7 +591,7 @@:joins [{:alias "Card 2 - Products → Category":fields [[:field {:join-alias "Card 2 - Products → Category"} (meta/id :products :category)]]:stages [{:breakout [[:field {} (meta/id :products :category)]]}- {:fields [[:field {} (meta/id :products :category)]]}]}]}]}+ {:fields [[:field {} "CATEGORY"]]}]}]}]}(qp.preprocess/preprocess query)))(is (= [["Products → Category" "Products__CATEGORY"]["Count" "count"]diff --git a/test/metabase/query_processor/streaming_test.clj b/test/metabase/query_processor/streaming_test.cljindex 5423552ee3b..a5973e51034 100644--- a/test/metabase/query_processor/streaming_test.clj+++ b/test/metabase/query_processor/streaming_test.clj@@ -479,12 +479,12 @@[1.0 "Red Medicine" "Asian" "10.06460000° N" "165.37400000° W" 3.0]](xlsx-test/parse-xlsx-results results))))}})))](qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :venues :category_id)(mt/id :categories :name))(testfn :external))(qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :venues :category_id)(mapv first (mt/rows (qp/process-query(mt/mbql-query categoriesdiff --git a/test/metabase/query_processor/test_util.clj b/test/metabase/query_processor/test_util.cljindex 785cd7135a7..3e37315d35f 100644--- a/test/metabase/query_processor/test_util.clj+++ b/test/metabase/query_processor/test_util.clj@@ -393,7 +393,13 @@(defn nest-query"Nest an MBQL/native query by `n-levels`. Useful for testing how nested queries behave.- DEPRECATED: prefer MBQL 5 queries and [[metabase.lib.core/append-stage]] going forward."+ DEPRECATED: prefer MBQL 5 queries and [[metabase.lib.core/append-stage]] going forward.++ You can do++ (nth (iterate lib/append-stage query) n-levels)++ to nest it multiple times."{:deprecated "0.57.0"}[outer-query n-levels](if-not (pos? n-levels)diff --git a/test/metabase/query_processor/util/add_alias_info_test.clj b/test/metabase/query_processor/util/add_alias_info_test.cljindex e65cd0107fb..12991c88fed 100644--- a/test/metabase/query_processor/util/add_alias_info_test.clj+++ b/test/metabase/query_processor/util/add_alias_info_test.clj@@ -362,31 +362,31 @@(deftest ^:parallel custom-escape-alias-filtering-aggregation-test(driver/with-driver ::custom-escape(is (=? (lib.tu.macros/$ids venues- (let [price [:field %price {::add/source-table $$venues- ::add/source-alias "PRICE"- ::add/desired-alias "COOL.PRICE"}]- outer-price (-> price- (assoc-in [2 ::add/source-table] ::add/source)- (update-in [2 ::add/source-alias] prefix-alias))- count-opts {::add/source-alias "strange count" ; TODO (Cam 8/7/25) -- doesn't even really make sense for an aggregation to have a source alias- ::add/desired-alias "COOL.strange count"}- outer-count-opts (-> count-opts- (assoc :base-type :type/Integer- ::add/source-table ::add/source)- (update ::add/source-alias prefix-alias))]- {:source-query {:source-table $$venues- :breakout [price]- :aggregation [[:aggregation-options [:count] count-opts]]- :order-by [[:asc price]]}- :fields [outer-price- [:field- "strange count"- outer-count-opts]]- :filter [:<- [:field- "strange count"- outer-count-opts]- [:value 10 {:base_type :type/Integer}]]}))+ (let [price [:field %price {::add/source-table $$venues+ ::add/source-alias "PRICE"+ ::add/desired-alias "COOL.PRICE"}]+ source-query {:source-table $$venues+ :breakout [price]+ :aggregation [[:aggregation-options+ [:count]+ ;; TODO (Cam 8/7/25) -- doesn't even really make sense for an aggregation to have a source alias+ {::add/source-alias "strange count"+ ::add/desired-alias "COOL.strange count"}]]+ :order-by [[:asc price]]}+ strange-count [:field+ "strange count"+ {:base-type :type/Integer+ ::add/source-table ::add/source+ ::add/source-alias "COOL.strange count"}]]+ {:source-query source-query+ :fields [[:field+ any?+ {::add/source-table ::add/source+ ::add/source-alias "COOL.PRICE"}]+ strange-count]+ :filter [:<+ strange-count+ [:value 10 {:base_type :type/Integer}]]}))(-> (lib.tu.macros/mbql-query venues{:source-query {:source-table $$venues:aggregation [[:aggregation-options@@ -415,11 +415,11 @@:condition[:=[:field- %orders.product-id+ any?{::add/source-alias "PRODUCT_ID"::add/source-table $$orders}][:field- %products.id+ any?{::add/source-alias "ID"::add/source-table "Products_Renamed":join-alias "Products Renamed"}]]@@ -427,30 +427,27 @@:expressions {"CC" [:+ 1 1]}:fields[[:field- %products.id+ any?{::add/desired-alias "Products_Renamed__ID"::add/source-alias "ID"- ::add/source-table "Products_Renamed"- :join-alias "Products Renamed"}]+ ::add/source-table "Products_Renamed"}][:expression "CC" {::add/desired-alias "CC"}]]:filter[:=[:field- %products.category+ any?{::add/source-alias "CATEGORY"- ::add/source-table "Products_Renamed"- :join-alias "Products Renamed"}]+ ::add/source-table "Products_Renamed"}][:value"Doohickey"{:base_type :type/Text:database_type "CHARACTER VARYING":semantic_type :type/Category}]]}:fields [[:field- %products.id+ any?{::add/desired-alias "Products_Renamed__ID"::add/source-alias "Products_Renamed__ID"- ::add/source-table ::add/source- :join-alias "Products Renamed"}]+ ::add/source-table ::add/source}][:field"CC"{::add/desired-alias "CC"@@ -586,12 +583,12 @@:expressions {"PRICE" [:+ $price 2]}:fields [$price[:expression "PRICE"]]}})]- (is (=? {:query {:fields [[:field (meta/id :venues :price) {::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/source-table ::add/source}]- [:field "PRICE_2" {::add/source-alias "PRICE_2"- ::add/desired-alias "PRICE_2"- ::add/source-table ::add/source}]]}}+ (is (=? {:query {:fields [[:field any? {::add/source-alias "PRICE"+ ::add/desired-alias "PRICE"+ ::add/source-table ::add/source}]+ [:field any? {::add/source-alias "PRICE_2"+ ::add/desired-alias "PRICE_2"+ ::add/source-table ::add/source}]]}}(add-alias-info source-query))))))(defn- metadata-provider-with-two-models []@@ -645,13 +642,13 @@(deftest ^:parallel models-with-joins-and-renamed-columns-test(testing "an MBQL model with an explicit join and customized field names generate correct SQL (#40252)"(qp.store/with-metadata-provider (metadata-provider-with-two-models)- (is (=? {:query {:fields [[:field "A1" {::add/source-table ::add/source+ (is (=? {:query {:fields [[:field any? {::add/source-table ::add/source::add/source-alias "A1"}]- [:field "A2" {::add/source-table ::add/source+ [:field any? {::add/source-table ::add/source::add/source-alias "A2"}]- [:field "B1" {::add/source-table ::add/source+ [:field any? {::add/source-table ::add/source::add/source-alias "Model B - A1__B1"}]- [:field "B2" {::add/source-table ::add/source+ [:field any? {::add/source-table ::add/source::add/source-alias "Model B - A1__B2"}]]}}(add-alias-info {:type :query:database (meta/id)@@ -1077,7 +1074,7 @@{::add/desired-alias "Total_number_of_people_from_each_state_separated_by_00028d48"::add/source-alias "Total_number_of_people_from_each_state_separated_by_00028d48"::add/source-table ::add/source}- "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"]]}]}+ "Total_number_of_people_from_each_state_separated_by_00028d48"]]}]}(add-alias-info query))))));;; in the future when we remove all the roundtripping that happens inside of the QP then we can remove this testdiff --git a/test/metabase/query_processor/util/nest_query_test.clj b/test/metabase/query_processor/util/nest_query_test.cljindex ea2b6471876..71eac9387c1 100644--- a/test/metabase/query_processor/util/nest_query_test.clj+++ b/test/metabase/query_processor/util/nest_query_test.clj@@ -208,9 +208,9 @@[:field %price #::add{:source-table ::add/source:source-alias "PRICE"}]4]}- :fields [[:field %id #::add{:source-table ::add/source- :source-alias "ID"- :desired-alias "ID"}]+ :fields [[:field "ID" #::add{:source-table ::add/source+ :source-alias "ID"+ :desired-alias "ID"}][:field "x" {:base-type :type/Integer::add/source-table ::add/source::add/source-alias "x"@@ -774,10 +774,8 @@[:field %rating {}][:field %created-at {}]]}:expressions {"pivot-grouping" [:abs 0]}- ;; TODO -- these should PROBABLY be nominal field literal refs (string name, not- ;; integer ID), but we can fix that later.- :fields [[:field %category {}]- [:field %created-at {}]+ :fields [[:field "CATEGORY" {}]+ [:field "CREATED_AT" {}][:expression "pivot-grouping" {}]]}:breakout [[:field "CATEGORY" {}][:field "CREATED_AT" {}]@@ -828,7 +826,7 @@(-> (lib.tu.macros/mbql-query orders{:expressions {"double_total" [:* $total 2]};; this is a broken field ref! It should use the join alias `p`. Luckily- ;; the [[metabase.query-processor.middleware.resolve-joined-fields]] middleware should fix it+ ;; the [[metabase.query-processor.middleware.fix-bad-field-id-refs]] middleware should fix it;; for us.:breakout [!hour-of-day.people.created-at[:expression "double_total"]]@@ -845,3 +843,86 @@(concat(take 3 fields)(sort-by second (drop 3 fields))))))))))))++(deftest ^:parallel wonky-breakout-test+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :type :model+ :name "Model A"+ :dataset-query (lib.tu.macros/mbql-query products+ {:source-table $$products+ :expressions {"Rating Bucket" [:floor $products.rating]}})}+ {:id 2+ :type :model+ :dataset-query (lib.tu.macros/mbql-query orders+ {:source-table $$orders+ :joins [{:source-table "card__1"+ :alias "model A - Product"+ :fields :all+ :condition [:=+ $orders.product-id+ [:field %products.id+ {:join-alias "model A - Product"}]]}]})}]})+ query (lib/query+ mp+ {:database (meta/id)+ :stages [{:lib/type :mbql.stage/mbql+ :source-card 2+ :expressions [[:abs {:lib/expression-name "pivot-grouping"} 0]]+ :aggregation [[:sum {} [:field {:base-type :type/Number} "SUBTOTAL"]]]+ :breakout [[:field {:base-type :type/Number, :join-alias "model A - Product"}+ "Rating Bucket"]+ [:expression {:base-type :type/Integer, :effective-type :type/Integer}+ "pivot-grouping"]]}]+ :lib/type :mbql/query})]+ (qp.store/with-metadata-provider mp+ (driver/with-driver :h2+ (let [stages (-> query+ qp.preprocess/preprocess+ add/add-alias-info+ lib/->legacy-MBQL+ :query+ nest-query/nest-expressions+ (->> (lib/query-from-legacy-inner-query mp (meta/id)))+ :stages+ (->> (map (fn [stage]+ (into []+ (comp (mapcat stage)+ (map lib/options)+ (map ::add/desired-alias))+ [:breakout :aggregation :fields])))))]+ (is (= 3+ (count stages)))+ (testing "first stage (Card 1)"+ (is (= ["ID"+ "USER_ID"+ "PRODUCT_ID"+ "SUBTOTAL"+ "TAX"+ "TOTAL"+ "DISCOUNT"+ "CREATED_AT"+ "QUANTITY"+ "model A - Product__ID"+ "model A - Product__EAN"+ "model A - Product__TITLE"+ "model A - Product__CATEGORY"+ "model A - Product__VENDOR"+ "model A - Product__PRICE"+ "model A - Product__RATING"+ "model A - Product__CREATED_AT"+ "model A - Product__Rating Bucket"]+ (nth stages 0))))+ (testing "second stage (Card 2)"+ (is (= ["ID"+ "SUBTOTAL"+ "CREATED_AT"+ "model A - Product__Rating Bucket"+ "pivot-grouping"]+ (nth stages 1))))+ (testing "third stage (original query)"+ (is (= ["model A - Product__Rating Bucket"+ "pivot-grouping"+ "sum"]+ (nth stages 2)))))))))diff --git a/test/metabase/query_processor_test/binning_test.clj b/test/metabase/query_processor_test/binning_test.cljindex 4b2d62493eb..28a80f24400 100644--- a/test/metabase/query_processor_test/binning_test.clj+++ b/test/metabase/query_processor_test/binning_test.clj@@ -47,7 +47,7 @@_ (is (= 2(count card-cols)))mp (lib.tu/mock-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){:cards [{:id 1:dataset-query card-query:result-metadata card-cols}]})diff --git a/test/metabase/query_processor_test/breakout_test.clj b/test/metabase/query_processor_test/breakout_test.cljindex 8d2de7d7955..69716163f07 100644--- a/test/metabase/query_processor_test/breakout_test.clj+++ b/test/metabase/query_processor_test/breakout_test.clj@@ -392,3 +392,41 @@(lib/limit 3)(qp/process-query)(->> (mt/formatted-rows [str])))))))))++(deftest ^:parallel breakout-with-expressions-test+ (let [mp (lib.tu/mock-metadata-provider+ (mt/metadata-provider)+ {:cards [{:id 1+ :type :model+ :name "Model A"+ :dataset-query (mt/mbql-query products+ {:source-table $$products+ :expressions {"Rating Bucket" [:floor $products.rating]}})}+ {:id 2+ :type :model+ :dataset-query (mt/mbql-query orders+ {:source-table $$orders+ :joins [{:source-table "card__1"+ :alias "model A - Product"+ :fields :all+ :condition [:=+ $orders.product_id+ [:field %products.id+ {:join-alias "model A - Product"}]]}]})}]})+ query (lib/query+ mp+ {:database (mt/id)+ :stages [{:lib/type :mbql.stage/mbql+ :source-card 2+ :expressions [[:abs {:lib/expression-name "pivot-grouping"} 0]]+ :aggregation [[:sum {:lib/uuid "06f3200a-519c-45fe-ab3a-35dfb44bb623"} [:field {:base-type :type/Number} "SUBTOTAL"]]]+ :breakout [[:field {:base-type :type/Number, :join-alias "model A - Product"}+ "Rating Bucket"]+ [:expression {:base-type :type/Integer, :effective-type :type/Integer}+ "pivot-grouping"]]+ :limit 3}]+ :lib/type :mbql/query})]+ (is (= [[0.0 0 172500.71]+ [2.0 0 36791.99]+ [3.0 0 454525.88]]+ (mt/formatted-rows [1.0 int 2.0] (qp/process-query query))))))diff --git a/test/metabase/query_processor_test/date_time_zone_functions_test.clj b/test/metabase/query_processor_test/date_time_zone_functions_test.cljindex a618f60e2e8..5c3a5c8fe4a 100644--- a/test/metabase/query_processor_test/date_time_zone_functions_test.clj+++ b/test/metabase/query_processor_test/date_time_zone_functions_test.clj@@ -839,7 +839,7 @@(mt/dataset times-mixed(testing "nested custom expression should works"(qp.store/with-metadata-provider (lib.tu/metadata-provider-with-cards-for-queries- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)[(mt/mbql-querytimes{:expressions {"to-07" [:convert-timezone $times.dt "Asia/Bangkok" "UTC"]diff --git a/test/metabase/query_processor_test/explicit_joins_test.clj b/test/metabase/query_processor_test/explicit_joins_test.cljindex d956cea8a3f..1d7a28cee22 100644--- a/test/metabase/query_processor_test/explicit_joins_test.clj+++ b/test/metabase/query_processor_test/explicit_joins_test.clj@@ -431,10 +431,10 @@;; that use them as keys(is (= [[:field (mt/id :people :id) nil][:field (mt/id :people :id) {:join-alias "peeps"}]- [:field "USER_ID" {:base-type :type/Integer, :join-alias "peeps"}]- [:field "count" {:base-type :type/Integer, :join-alias "peeps"}]- [:field "USER_ID_2" {:base-type :type/Integer, :join-alias "peeps"}]- [:field "count_2" {:base-type :type/Integer, :join-alias "peeps"}]]+ [:field "USER_ID" {:base-type :type/Integer, :join-alias "peeps"}]+ [:field "ord1__count" {:base-type :type/Integer, :join-alias "peeps"}]+ [:field "USER_ID_2" {:base-type :type/Integer, :join-alias "peeps"}]+ [:field "ord2__count" {:base-type :type/Integer, :join-alias "peeps"}]](map :field_ref (qp.preprocess/query->expected-cols query))))))(testing "the query runs and returns correct data"(is (= {:columns [cid cid2 cuser-id ccount cuser-id2 ccount2]@@ -1525,7 +1525,7 @@(deftest ^:parallel self-join-in-source-card-test(testing "When query uses a source card with a self-join, query should work (#27521)"- (let [mp (mt/application-database-metadata-provider (mt/id))+ (let [mp (mt/metadata-provider)q1 (-> (lib/querymp(lib.metadata/table mp (mt/id :orders)))diff --git a/test/metabase/query_processor_test/field_ref_repro_test.clj b/test/metabase/query_processor_test/field_ref_repro_test.cljindex ba79c36e949..4fdaae48e22 100644--- a/test/metabase/query_processor_test/field_ref_repro_test.clj+++ b/test/metabase/query_processor_test/field_ref_repro_test.clj@@ -153,7 +153,7 @@(testing "Should handle self joins with external remapping (#60444)";; see https://metaboat.slack.com/archives/C0645JP1W81/p1753208898063419 for further discussion(let [mp (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :orders :user_id) (mt/id :people :email))](doseq [join-base [{:source-table (mt/id :orders)}{:source-query {:source-table (mt/id :orders)@@ -247,7 +247,7 @@(deftest ^:parallel multi-stage-with-external-remapping-test(testing "Should handle multiple stages with external remapping (#60587)"- (let [mp (lib.tu/remap-metadata-provider (mt/application-database-metadata-provider (mt/id))+ (let [mp (lib.tu/remap-metadata-provider (mt/metadata-provider)(mt/id :orders :user_id)(mt/id :people :email))query (as-> (lib/query mp (lib.metadata/table mp (mt/id :orders))) $diff --git a/test/metabase/query_processor_test/filter_test.clj b/test/metabase/query_processor_test/filter_test.cljindex 53dd30879b6..99674be6f93 100644--- a/test/metabase/query_processor_test/filter_test.clj+++ b/test/metabase/query_processor_test/filter_test.clj@@ -1046,7 +1046,7 @@(deftest ^:parallel filter-on-implicitly-joined-column-test(testing "Should be able to filter on an column that was implicitly joined from a column in an explicit join (#59695)"(let [mp (lib.tu/mock-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){:cards [{:id 1:dataset-query (mt/mbql-query orders)}]})query (lib/querydiff --git a/test/metabase/query_processor_test/nested_queries_test.clj b/test/metabase/query_processor_test/nested_queries_test.cljindex be7411f9bbb..a61a2acf9a1 100644--- a/test/metabase/query_processor_test/nested_queries_test.clj+++ b/test/metabase/query_processor_test/nested_queries_test.clj@@ -665,7 +665,7 @@;; include the unit; however `:unit` is still `:year` so the frontend can use the correct formatting to;; display values of the column.(is (=? [(assoc date-col :field_ref [:field (mt/id :checkins :date) nil], :unit :year)- (assoc count-col :field_ref [:field "count" {:base-type :type/Integer}])]+ (assoc count-col :field_ref [:field "count" {:base-type keyword?}])](mt/cols(qp/process-query (query-with-source-card 1 lib.schema.id/saved-questions-virtual-database-id)))))))))))@@ -720,7 +720,7 @@(deftest ^:parallel macroexpansion-test(testing "Make sure that macro expansion works inside of a neested query, when using a compound filter clause (#5974)"(mt/test-drivers (mt/normal-drivers-with-feature :nested-queries)- (qp.store/with-metadata-provider (-> (mt/application-database-metadata-provider (mt/id))+ (qp.store/with-metadata-provider (-> (mt/metadata-provider)(lib.tu/mock-metadata-provider{:segments [{:id 1:name "Segment 1"@@ -1014,7 +1014,7 @@{:source-table "card__1"}))))(testing "if source query with expression literals is from a Model"(qp.store/with-metadata-provider (lib.tu/mock-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){:cards [{:id 1:type :model:name "Model 1"@@ -1072,30 +1072,30 @@(mt/formatted-rows[str str int]results)))- (is (= (mt/$ids venues- [{:name (mt/format-name "name")- :display_name "Name"- :id %name- :field_ref $name- :base_type :type/Text}- {:name (mt/format-name "name_2")- :display_name "c → Name"- :id %categories.name- :field_ref &c.categories.name- :base_type :type/Text}- {:name "count"- :display_name "Count"- :field_ref [:field "count" {:base-type :type/Integer}]- :base_type (:base_type (qp.test-util/aggregate-col :count))}])- (for [col (mt/cols results)]- (select-keys col [:name :display_name :id :field_ref :base_type]))))))))+ (is (=? (mt/$ids venues+ [{:name (mt/format-name "name")+ :display_name "Name"+ :id %name+ :field_ref $name+ :base_type :type/Text}+ {:name (mt/format-name "name_2")+ :display_name "c → Name"+ :id %categories.name+ :field_ref &c.categories.name+ :base_type :type/Text}+ {:name "count"+ :display_name "Count"+ :field_ref [:field "count" {:base-type keyword?}]+ :base_type (:base_type (qp.test-util/aggregate-col :count))}])+ (for [col (mt/cols results)]+ (select-keys col [:name :display_name :id :field_ref :base_type]))))))))(deftest ^:parallel remapped-fks-test(testing "Should be able to use a question with remapped FK columns as a Saved Question (#10474)"(mt/dataset test-data;; Add column remapping from Orders Product ID -> Products.Title(let [provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :orders :product_id)(mt/id :products :title))card-results-metadata (qp.store/with-metadata-provider provider@@ -1147,7 +1147,7 @@4.0 "2017-12-31T14:41:56.87Z"](first (mt/rows results))))))(qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :orders :product_id)(mt/id :products :title))(do-test@@ -1201,17 +1201,17 @@(doseq [level (range 0 4)](testing (format "with %d level(s) of nesting" level)(letfn [(run-query []- (let [query (-> (mt/mbql-query orders- {:source-table $$orders- :joins [{:fields :all- :source-table $$products- :condition [:= $product_id &Products.products.id]- :alias "Products"}]- :order-by [[:asc $id]]- :limit 2})- ;; existing usage, do not use this going forward- #_{:clj-kondo/ignore [:deprecated-var]}- (mt/nest-query level))]+ (let [query (-> (lib/query+ (mt/metadata-provider)+ (mt/mbql-query orders+ {:source-table $$orders+ :joins [{:fields :all+ :source-table $$products+ :condition [:= $product_id &Products.products.id]+ :alias "Products"}]+ :order-by [[:asc $id]]+ :limit 2}))+ (as-> $query (nth (iterate lib/append-stage $query) level)))](qp/process-query query)))](testing "with no FK remappings"(let [result (run-query)]@@ -1223,7 +1223,7 @@"2017-12-31T14:41:56.87Z"](mt/first-row result)))))(qp.store/with-metadata-provider (lib.tu/remap-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider)(mt/id :orders :product_id)(mt/id :products :title))(let [result (run-query)]@@ -1344,7 +1344,7 @@{:source-query (:query query)})metadata (assoc-in [:query :source-metadata] metadata))))(test-card-source-query [metadata]- (qp.store/with-metadata-provider (-> (mt/application-database-metadata-provider (mt/id))+ (qp.store/with-metadata-provider (-> (mt/metadata-provider)(lib.tu/metadata-provider-with-cards-for-queries [query])(lib.tu/merged-mock-metadata-provider{:cards [{:id 1, :result-metadata metadata}]}))@@ -1522,7 +1522,7 @@(mt/test-drivers (mt/normal-drivers-with-feature :nested-queries)(testing "A nested query with a Metric should work as expected (#12507)"(qp.store/with-metadata-provider (lib.tu/mock-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){:cards [{:id 1:type :metric:name "Metric 1"diff --git a/test/metabase/query_processor_test/parameters_test.clj b/test/metabase/query_processor_test/parameters_test.cljindex c5bb5e312b3..98e411a40ab 100644--- a/test/metabase/query_processor_test/parameters_test.clj+++ b/test/metabase/query_processor_test/parameters_test.clj@@ -254,7 +254,7 @@(deftest ^:parallel filter-nested-queries-test(mt/test-drivers (mt/normal-drivers-with-feature :native-parameters :nested-queries)(qp.store/with-metadata-provider (lib.tu/mock-metadata-provider- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){: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))@@ -724,7 +724,7 @@(deftest ^:parallel x-test(mt/test-drivers (mt/normal-drivers)(let [query (lib/query- (mt/application-database-metadata-provider (mt/id))+ (mt/metadata-provider){:lib/type :mbql/query:database (mt/id):stages [{:lib/type :mbql.stage/mbqldiff --git a/test/metabase/query_processor_test/remapping_test.clj b/test/metabase/query_processor_test/remapping_test.cljindex 70cc684bbad..518624d19de 100644--- a/test/metabase/query_processor_test/remapping_test.clj+++ b/test/metabase/query_processor_test/remapping_test.clj@@ -428,7 +428,7 @@(deftest ^:parallel multiple-fk-remaps-test-in-joins-e2e-test(testing "Should be able to do multiple FK remaps via different FKs from Table A to Table B in a join"- (let [mp (-> (mt/application-database-metadata-provider (mt/id))+ (let [mp (-> (mt/metadata-provider)(lib.tu/remap-metadata-provider (mt/id :venues :category_id)(mt/id :categories :name))(lib.tu/remap-metadata-provider (mt/id :venues :id)diff --git a/test/metabase/test_runner/assert_exprs.clj b/test/metabase/test_runner/assert_exprs.cljindex b0035da534a..c32b8555fe5 100644--- a/test/metabase/test_runner/assert_exprs.clj+++ b/test/metabase/test_runner/assert_exprs.clj@@ -1,16 +1,17 @@(ns metabase.test-runner.assert-exprs- "Custom implementations of a few [[clojure.test/is]] expressions (i.e., implementations of [[clojure.test/assert-expr]]):- `query=`.+ "This namespace formerly had custom implementations of a few [[clojure.test/is]] expressions, but they are no more. It+ does however pull in the implementation for `malli=`, and a handful of namespaces load THIS one, so I guess we can+ keep it around for now.Other expressions (`re=`, `=?`, and so forth) are implemented with the Hawk test-runner."(:require- [clojure.data :as data]- [clojure.test :as t][clojure.walk :as walk][metabase.test-runner.assert-exprs.malli-equals]))(comment metabase.test-runner.assert-exprs.malli-equals/keep-me)+;;; TODO (Cam 9/10/25) -- this is no longer used anywhere in the `metabase.test-runner.assert-exprs.*` world, so we+;;; should move it into a more general test util namespace.(defn derecordize"Convert all record types in `form` to plain maps, so tests won't fail."[form]@@ -20,30 +21,3 @@(into {} form)form))form))--(defn query=-report- "Impl for [[t/assert-expr]] `query=`."- [message expected actual]- (let [expected (derecordize expected)- actual (derecordize actual)- pass? (= expected actual)]- (merge- {:type (if pass? :pass :fail)- :message message- :expected expected- :actual actual}- ;; don't bother adding names unless the test actually failed- (when-not pass?- (let [add-names (requiring-resolve 'dev.debug-qp/add-names)]- {:expected (add-names expected)- :actual (add-names actual)- :diffs (let [[only-in-actual only-in-expected] (data/diff actual expected)]- [[(add-names actual) [(add-names only-in-expected) (add-names only-in-actual)]]])})))))--;; basically the same as normal `=` but will add comment forms to MBQL queries for Field clauses and source tables-;; telling you the name of the referenced Fields/Tables-(defmethod t/assert-expr 'query=- [message [_ expected & actuals]]- `(do ~@(for [actual actuals]- `(t/do-report- (query=-report ~message ~expected ~actual)))))