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-alias-info => Lib and misc bug fixes (#60231)
Cam Saulbf85745bbb89
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 69928987cc6..a5104ebb04c 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -604,6 +604,7 @@metabase.lib.schema.infometabase.lib.schema.joinmetabase.lib.schema.literal+ metabase.lib.schema.mbql-clausemetabase.lib.schema.metadatametabase.lib.schema.metadata.fingerprintmetabase.lib.schema.order-bydiff --git a/deps.edn b/deps.ednindex 97ab5738e7c..38b445cbdde 100644--- a/deps.edn+++ b/deps.edn@@ -830,16 +830,18 @@;; run tests against MLv2. Very fast since this is almost all ^:parallel:test/lib- {:exec-args {:only ["test/metabase/lib" "test/metabase/lib_be"]}}+ {:exec-args {:only ["test/metabase/lib"+ "test/metabase/lib_be"]}};; test the Query Processor;;;; clj -X:dev:ee:ee-dev:test:test/qp:test/qp- {:exec-args {:only ["test/metabase/driver"- "test/metabase/query_processor"+ {:exec-args {:only ["test/metabase/query_processor""test/metabase/query_processor_test"+ metabase.driver.sql.query-processor-testmetabase-enterprise.advanced-permissions.models.permissions.block-permissions-test+ metabase-enterprise.advanced-permissions.query-processor.middleware.permissions-testmetabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test]}};; test the notification system@@ -852,14 +854,14 @@;;;; clj -X:dev:ee:ee-dev:test:test/mbql:test/mbql- {:exec-args {:only ["test/mbql"- "test/metabase/lib"+ {:exec-args {:only ["test/metabase/lib""test/metabase/lib_be""test/metabase/legacy_mbql"- "test/metabase/driver""test/metabase/query_processor""test/metabase/query_processor_test"+ metabase.driver.sql.query-processor-testmetabase-enterprise.advanced-permissions.models.permissions.block-permissions-test+ metabase-enterprise.advanced-permissions.query-processor.middleware.permissions-testmetabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test]}};; test search-related stuff.diff --git a/docs/developers-guide/driver-changelog.md b/docs/developers-guide/driver-changelog.mdindex 0706ffbc463..bc638e5bbbd 100644--- a/docs/developers-guide/driver-changelog.md+++ b/docs/developers-guide/driver-changelog.md@@ -4,6 +4,14 @@ title: Driver interface changelog# Driver Interface Changelog+## Metabase 0.57.0++- `driver/field-reference-mlv2` is now deprecated, and is no longer used. Please remove your implementations.++- The key `metabase.driver-api.core/qp.add.nfc-path` is now more consistently populated; other `qp.add.*` keys no+ longer include parent column names for drivers like MongoDB -- use `qp.add.nfc-path` instead to qualify the+ `qp.add.source-column-alias` with parent column names as needed.+## Metabase 0.56.0- Add the testing multi-method `tx/track-dataset` for shared cloud dbs to track loaded datasets for more efficient sharing.diff --git a/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.js b/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.jsindex 0810a3a7393..dba933a7755 100644--- a/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.js+++ b/e2e/test/scenarios/permissions/permissions-reproductions.cy.spec.js@@ -272,7 +272,7 @@ describe("issue 20436", () => {});});-describe("UI elements that make no sense for users without data permissions (metabase#22447, metabase##22449, metabase#22450)", () => {+describe("UI elements that make no sense for users without data permissions (metabase#22447, metabase#22449, metabase#22450)", () => {beforeEach(() => {H.restore();});diff --git a/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.ts b/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.tsindex 163209cba28..923c025b921 100644--- a/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.ts+++ b/e2e/test/scenarios/permissions/sandboxing/helpers/e2e-sandboxing-helpers.ts@@ -59,7 +59,6 @@ const addCustomColumnToQuestion = (customColumnType: CustomColumnType) => {};const baseQuery = {- type: "query","source-table": PRODUCTS_ID,limit: 20,};diff --git a/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-ui.cy.spec.ts b/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-ui.cy.spec.tsindex 0a7e905e0d8..0195854a100 100644--- a/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-ui.cy.spec.ts+++ b/e2e/test/scenarios/permissions/sandboxing/sandboxing-via-ui.cy.spec.ts@@ -6,12 +6,9 @@ import type { CollectionItem, Dashboard } from "metabase-types/api";import {assertAllResultsAndValuesAreSandboxed,assertNoResultsOrValuesAreSandboxed,- assertResponseFailsClosed,assignAttributeToUser,configureSandboxPolicy,createSandboxingDashboardAndQuestions,- getFieldValuesForProductCategories,- getParameterValuesForProductCategories,gizmoViewer,modelCustomView,questionCustomView,@@ -161,8 +158,8 @@ describe(});});- // Custom columns currently don't work. These tests ensure that the sandboxing policy fails closed.- describe("we expect an error - and no data to be shown - when applying a sandbox policy...", () => {+ // Custom columns currently DO work.+ describe("should work when applying a sandbox policy...", () => {([["Question", "booleanExpr", "true"],@@ -192,24 +189,20 @@ describe(filterColumn: `my_${customColumnType}`,});signInAs(gizmoViewer);- H.visitDashboard(checkNotNull(dashboard).id);- cy.log("Should not return any data, and return an error");- cy.wait(- new Array(sandboxableQuestions.length).fill("@dashcardQuery"),- ).then((interceptions) => {- interceptions.forEach(({ response }) => {- assertResponseFailsClosed(response);- });- });+ H.visitDashboard(checkNotNull(dashboard).id);- getFieldValuesForProductCategories().then((response) => {- expect(response.body.values).to.have.length(0);+ H.getDashboardCard(0).within(() => {+ cy.findByText("Question showing all products").should("be.visible");+ cy.findByText("20 rows").should("be.visible");});- getParameterValuesForProductCategories().then((response) => {- expect(response.body.values).to.have.length(0);- });+ H.getDashboardCard(1)+ .scrollIntoView()+ .within(() => {+ cy.findByText("Model showing all products").should("be.visible");+ cy.findByText("20 rows").should("be.visible");+ });});});});diff --git a/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.ts b/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.tsindex 2060628310e..2d0a69b28c1 100644--- a/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.ts+++ b/e2e/test/scenarios/question/notebook-link-to-data-source.cy.spec.ts@@ -463,7 +463,7 @@ describe("scenarios > notebook > link to data source", () => {.icon("notebook").should("not.exist");- // TODO update the following once metabase##46398 is fixed+ // TODO update the following once metabase#46398 is fixed// cy.visit(`/question/${nestedQuestion.id}/notebook`);});});diff --git a/e2e/test/scenarios/visualizations-tabular/column-shortcuts.cy.spec.ts b/e2e/test/scenarios/visualizations-tabular/column-shortcuts.cy.spec.tsindex 01c31bdc15f..75673190154 100644--- a/e2e/test/scenarios/visualizations-tabular/column-shortcuts.cy.spec.ts+++ b/e2e/test/scenarios/visualizations-tabular/column-shortcuts.cy.spec.ts@@ -472,7 +472,7 @@ H.describeWithSnowplow("scenarios > visualizations > combine shortcut", () => {["field",PRODUCTS.CATEGORY,- { "base-type": "type/text", "source-field": ORDERS.PRODUCT_ID },+ { "base-type": "type/Text", "source-field": ORDERS.PRODUCT_ID },],],},diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj b/enterprise/backend/src/metabase_enterprise/audit_app/audit.cljindex 60e48349e82..cc84c1aed5c 100644--- a/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj+++ b/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj@@ -12,6 +12,7 @@[metabase.sync.util :as sync-util][metabase.util :as u][metabase.util.files :as u.files]+ [metabase.util.json :as json][metabase.util.log :as log][toucan2.core :as t2])(:import@@ -116,7 +117,6 @@(when (seq table-ids-to-update)(t2/update! :model/Table :id [:in (map :id table-ids-to-update)]{:schema "public" :name [:lower :name]})))-(let [field-ids-to-update (t2/query {:select [:field.id]:from [[(t2/table-name :model/Field) :field]]:inner-join [[(t2/table-name :model/Table) :table]@@ -139,23 +139,44 @@{:name [:lower :name]})))(log/info "Adjusted Audit DB for loading Analytics Content"))+(defn- fix-h2-card-metadata! [audit-db-id]+ (t2/with-connection [^java.sql.Connection conn]+ (with-open [stmt (.prepareStatement conn "UPDATE \"REPORT_CARD\" SET \"RESULT_METADATA\" = ? WHERE \"ID\" = ?;")]+ (reduce+ (fn [_ card]+ (when-let [result-metadata (not-empty (some-> (:result_metadata card) (json/decode true)))]+ (let [fixed-metadata (for [col result-metadata]+ (update col :name u/upper-case-en))+ json-metadata (json/encode fixed-metadata)]+ (.setString stmt 1 json-metadata)+ (.setInt stmt 2 (:id card))+ (.addBatch stmt))))+ nil+ (t2/reducible-select [(t2/table-name :model/Card) :id :result_metadata] :database_id audit-db-id))+ (.executeBatch stmt))))+(defn- adjust-audit-db-to-host![{audit-db-id :id :keys [engine] :as audit-db}]- (when (not= engine (mdb/db-type))+ (when-not (= engine (mdb/db-type));; We need to move the loaded data back to the host db(t2/update! :model/Database audit-db-id {:engine (name (mdb/db-type))})- (when (= :mysql (mdb/db-type))- (t2/update! :model/Table {:db_id audit-db-id} {:schema nil}))- (when (= :h2 (mdb/db-type))- (t2/update! :model/Table {:db_id audit-db-id} {:schema [:upper :schema] :name [:upper :name]})- (t2/update! :model/Field- {:table_id- [:in- {:select [:id]- :from [(t2/table-name :model/Table)]- :where [:= :db_id audit-db-id]}]}- {:name [:upper :name]}))- (when (= :postgres (mdb/db-type))+ (case (mdb/db-type)+ :mysql+ (t2/update! :model/Table {:db_id audit-db-id} {:schema nil})++ :h2+ (do+ (t2/update! :model/Table {:db_id audit-db-id} {:schema [:upper :schema] :name [:upper :name]})+ (t2/update! :model/Field+ {:table_id+ [:in+ {:select [:id]+ :from [(t2/table-name :model/Table)]+ :where [:= :db_id audit-db-id]}]}+ {:name [:upper :name]})+ (fix-h2-card-metadata! audit-db-id))++ :postgres;; in postgresql the data should look just like the source(adjust-audit-db-to-source! audit-db))(log/infof "Adjusted Audit DB to match host engine: %s" (name (mdb/db-type)))))diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.cljindex 857dc360865..3d16e9cbcdc 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/common_test.clj@@ -800,9 +800,9 @@(mt/user-http-request :rasta :post 200 execute-path{:parameters {"id" 1}})))))(testing "Fails with access to the DB blocked"- (mt/with-all-users-data-perms-graph! {(u/the-id (mt/db)) {:view-data :blocked- :create-queries :no- :details :yes}}+ (mt/with-all-users-data-perms-graph! {(mt/id) {:view-data :blocked+ :create-queries :no+ :details :yes}}(mt/with-actions-enabled(is (partial= {:message "You don't have permissions to do that."}(mt/user-http-request :rasta :post 403 execute-path@@ -884,7 +884,7 @@[table-a (upload-test/create-upload-table! :schema-name schema-name)](upload-test/with-upload-table![table-b (upload-test/create-upload-table! :schema-name schema-name)]- (let [db-id (u/the-id (mt/db))+ (let [db-id (mt/id)append-csv! #(upload-test/update-csv-with-defaults!action:table-id (:id table-a)@@ -911,7 +911,7 @@action)(upload-test/with-upload-table![table-a (upload-test/create-upload-table!)]- (let [db-id (u/the-id (mt/db))+ (let [db-id (mt/id)append-csv! #(upload-test/update-csv-with-defaults!action:table-id (:id table-a)@@ -929,7 +929,7 @@(testing "GET /api/database and GET /api/database/:id responses should include can_upload depending on unrestricted data access to the upload schema"(mt/with-model-cleanup [:model/Table](let [schema-name (sql.tx/session-schema driver/*driver*)- db-id (u/the-id (mt/db))]+ db-id (mt/id)](upload-test/with-upload-table! [table (upload-test/create-upload-table! :schema-name schema-name)](mt/with-temp [:model/Table {} {:db_id db-id :schema "some_schema"}](doseq [[schema-perms can-upload?] {:query-builder truediff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.cljindex e8067f9d934..553e1e7ab21 100644--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.clj+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/query_processor/middleware/permissions_test.clj@@ -2,10 +2,10 @@(:require[clojure.data.csv :as csv][clojure.test :refer :all]- [metabase-enterprise.advanced-permissions.query-processor.middleware.permissions- :as ee.qp.perms]+ [metabase-enterprise.advanced-permissions.query-processor.middleware.permissions :as ee.qp.perms][metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions :as row-level-restrictions][metabase.legacy-mbql.normalize :as mbql.normalize]+ [metabase.lib.test-metadata :as meta][metabase.lib.util.match :as lib.util.match][metabase.permissions.core :as perms][metabase.permissions.models.data-permissions.graph :as data-perms.graph]@@ -479,42 +479,54 @@{:error "You do not have permissions to download the results of this query."}results)))}})))))))-(deftest joined-cards-with-native-query-test- (testing "Do we correctly apply the least permissive download perms when joining cards where one has a native query? (#XXXX)"+(defn- do-joined-cards-with-native-query-test! [f]+ (testing "Do we correctly apply the least permissive download perms when joining cards where one has a native query?"(mt/with-full-data-perms-for-all-users!(with-redefs [ee.qp.perms/max-rows-in-limited-downloads 3](mt/with-temp [:model/Card {mbql-card-id :id} {:dataset_query {:database (mt/id):type :query:query {:source-table (mt/id :venues)}}}- :model/Card {native-card-id :id} {:dataset_query {:database (mt/id)- :type :native- :native {:query "SELECT * FROM checkins"}}}]- (testing "When one card has native query, least permissive DB-level permission applies"- (with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :venues) :full- (mt/id :checkins) :limited- (mt/id :users) :full}}}- (streaming-test/do-test!- "Join between MBQL card (venues:full) and native card - should use limited perms due to native query"- {:query {:database (mt/id)+ :model/Card {native-card-id :id} {:dataset_query {:database (mt/id)+ :type :native+ :native {:query "SELECT * FROM checkins"}}+ :result_metadata (for [field (meta/fields :checkins)]+ (-> (meta/field-metadata :checkins field)+ (dissoc :id :table-id)))}]+ (f {:mbql-card-id mbql-card-id, :native-card-id native-card-id}))))))++(deftest joined-cards-with-native-query-test+ (do-joined-cards-with-native-query-test!+ (fn [{:keys [mbql-card-id native-card-id]}]+ (testing "When one card has native query, least permissive DB-level permission applies"+ (with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :venues) :full+ (mt/id :checkins) :limited+ (mt/id :users) :full}}}+ (streaming-test/do-test!+ "Join between MBQL card (venues:full) and native card - should use limited perms due to native query"+ {:query {:database (mt/id):type :query:query {:source-table (format "card__%d" mbql-card-id):joins [{:fields [[:field "ID" {:base-type :type/Integer}]]:source-table (format "card__%d" native-card-id):alias "native_card"- :condition [:= [:field "ID" {:base-type :type/Integer}]+ :condition [:=+ [:field "ID" {:base-type :type/Integer}][:field "VENUE_ID" {:base-type :type/Integer, :join-alias "native_card"}]]:strategy :left-join}]:limit 10}}- :endpoints [:card :dataset]- :assertions {:csv (fn [results] (is (= 3 (csv-row-count results))))}})))-- (testing "When native card references tables with no download perms, download is blocked"- (with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :venues) :full- (mt/id :checkins) :none- (mt/id :users) :limited}}}- (streaming-test/do-test!- "Join between MBQL card (venues:full) and native card - should block due to checkins:none"- {:query {:database (mt/id)+ :endpoints [:card :dataset]+ :assertions {:csv (fn [results] (is (= 3 (csv-row-count results))))}}))))))++(deftest joined-cards-with-native-query-test-2+ (do-joined-cards-with-native-query-test!+ (fn [{:keys [mbql-card-id native-card-id]}]+ (testing "When native card references tables with no download perms, download is blocked"+ (with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :venues) :full+ (mt/id :checkins) :none+ (mt/id :users) :limited}}}+ (streaming-test/do-test!+ "Join between MBQL card (venues:full) and native card - should block due to checkins:none"+ {:query {:database (mt/id):type :query:query {:source-table (format "card__%d" mbql-card-id):joins [{:fields [[:field "ID" {:base-type :type/Integer}]]@@ -524,19 +536,22 @@[:field "VENUE_ID" {:base-type :type/Integer, :join-alias "native_card"}]]:strategy :left-join}]:limit 10}}- :endpoints [:card :dataset]- :assertions {:csv (fn [results]- (is (partial=- {:error "You do not have permissions to download the results of this query."}- results)))}})))-- (testing "When all tables have full perms, download works normally"- (with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :venues) :full- (mt/id :checkins) :full- (mt/id :users) :full}}}- (streaming-test/do-test!- "Join between MBQL card and native card - should work with full perms for all tables"- {:query {:database (mt/id)+ :endpoints [:card :dataset]+ :assertions {:csv (fn [results]+ (is (partial=+ {:error "You do not have permissions to download the results of this query."}+ results)))}}))))))++(deftest joined-cards-with-native-query-test-3+ (do-joined-cards-with-native-query-test!+ (fn [{:keys [mbql-card-id native-card-id]}]+ (testing "When all tables have full perms, download works normally"+ (with-download-perms! (mt/id) {:schemas {"PUBLIC" {(mt/id :venues) :full+ (mt/id :checkins) :full+ (mt/id :users) :full}}}+ (streaming-test/do-test!+ "Join between MBQL card and native card - should work with full perms for all tables"+ {:query {:database (mt/id):type :query:query {:source-table (format "card__%d" mbql-card-id):joins [{:fields [[:field "ID" {:base-type :type/Integer}]]@@ -546,8 +561,8 @@[:field "VENUE_ID" {:base-type :type/Integer, :join-alias "native_card"}]]:strategy :left-join}]:limit 10}}- :endpoints [:card :dataset]- :assertions {:csv (fn [results] (is (= 10 (csv-row-count results))))}}))))))))+ :endpoints [:card :dataset]+ :assertions {:csv (fn [results] (is (= 10 (csv-row-count results))))}}))))))(defn- do-with-card-with-native-source-card! [f](mt/with-full-data-perms-for-all-users!diff --git a/enterprise/backend/test/metabase_enterprise/email/messages_test.clj b/enterprise/backend/test/metabase_enterprise/email/messages_test.cljindex 1c5263c11f1..b8e03df93d9 100644--- a/enterprise/backend/test/metabase_enterprise/email/messages_test.clj+++ b/enterprise/backend/test/metabase_enterprise/email/messages_test.clj@@ -10,7 +10,7 @@(use-fixtures :once (fixtures/initialize :db :test-users))(deftest admin-or-ee-monitoring-details-emails-test- (let [db-id (:id (mt/db))]+ (let [db-id (mt/id)](mt/with-user-in-groups [group {:name "New Group"}user [group]](perms/grant-application-permissions! group :monitoring)diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.cljindex ba67cdf9ded..f9dd095d75f 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/row_level_restrictions_test.clj@@ -1485,3 +1485,31 @@(mt/with-test-user :rasta(is (= [[10]](run-venues-count-query))))))))))++;;; see also [[metabase.driver.sql.query-processor-test/evil-field-ref-for-an-expression-test]]+;;; and [[metabase.query-processor.util.add-alias-info-test/resolve-incorrect-field-ref-for-expression-test]]+(deftest evil-field-ref-for-an-expression-test+ (letfn [(query []+ (mt/mbql-query products+ {:fields [$id]+ :limit 3}))+ (sandbox-query []+ (mt/mbql-query products+ {:expressions {"my_numberLiteral" [:value 1 {:base_type :type/Integer}]}+ :fields [$id+ [:expression "my_numberLiteral"]]+ :order-by [[:asc $id]]+ :limit 3}))]+ (met/with-gtaps! {:gtaps {:products {:query (sandbox-query)+ :remappings {"filter-attribute" [:dimension+ ;; PROBABLY wrong, since this should+ ;; PROBABLY be an expression ref but who+ ;; knows right+ [:field "my_numberLiteral" {:base-type :type/Integer}]+ {:stage-number 0}]}}}+ :attributes {"filter-attribute" "1"}}+ (is (= [[1]+ [2]+ [3]]+ (mt/rows+ (qp/process-query (query))))))))diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/test_util.clj b/enterprise/backend/test/metabase_enterprise/sandbox/test_util.cljindex 03fcaf0d755..92a21ac6f9e 100644--- a/enterprise/backend/test/metabase_enterprise/sandbox/test_util.clj+++ b/enterprise/backend/test/metabase_enterprise/sandbox/test_util.clj@@ -89,6 +89,7 @@[test-user-name-or-user-id gtaps-and-attributes-map & body]`(do-with-gtaps-for-user! (fn [] ~gtaps-and-attributes-map) ~test-user-name-or-user-id (fn [~'&group] ~@body)))+;;; TODO (Cam 8/13/25) -- give this a more obvious name like `with-sandboxes!` or something.(defmacro with-gtaps!"Execute `body` with `gtaps` and optionally user `attributes` in effect, for the :rasta test user. All underlyingobjects and permissions are created automatically.@@ -96,12 +97,14 @@`gtaps-and-attributes-map` is a map containing `:gtaps` and optionally `:attributes`; see the `WithGTAPsArgs` schemain this namespace.- * `:gtaps` is a map of test ID table name -> gtap def. Both `:query` and `:remappings` are optional.+ * `:gtaps` is a map of test ID table name -> gtap def. Both `:query` and `:remappings` are optional.- * If `:query` is specified, a corresponding Card is created, and the GTAP is saved with that `:card_id`.- Otherwise Card ID is nil and the GTAP uses the source table directly.+ * If `:query` is specified, a corresponding Card is created, and the GTAP is saved with that `:card_id`.+ Otherwise Card ID is nil and the GTAP uses the source table directly.- * `:remappings`, if specified, is saved as the `:attribute_remappings` property of the GTAP.+ * `:remappings`, if specified, is saved as the `:attribute_remappings` property of the GTAP.++ * `:attributes`, when specified, sets the user `:login_attributes` to the map in question.(met/with-gtaps! {:gtaps {:checkins {:query {:database (data/id), ...}:remappings {:user_category [\"variable\" ...]}}}diff --git a/frontend/src/metabase/parameters/utils/mapping-options.unit.spec.js b/frontend/src/metabase/parameters/utils/mapping-options.unit.spec.jsindex 00354f4b340..a370d40d8f0 100644--- a/frontend/src/metabase/parameters/utils/mapping-options.unit.spec.js+++ b/frontend/src/metabase/parameters/utils/mapping-options.unit.spec.js@@ -197,7 +197,6 @@ describe("parameters/utils/mapping-options", () => {joins: [{alias: "Product",- ident: "Y_wEKVMtSNd3v5I4vYs05",fields: "all","source-table": PRODUCTS_ID,condition: [diff --git a/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.tsindex ea9f81fb603..67e16de2183 100644--- a/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.ts+++ b/frontend/src/metabase/query_builder/actions/core/updateQuestion.unit.spec.ts@@ -185,7 +185,6 @@ async function setup({const REVIEW_JOIN_CLAUSE: Join = {alias: "Products",- ident: "gxyP-LOf7Zn96z8IWueoH",condition: ["=",["field", ORDERS.ID, null],diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.js b/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.jsindex 7b7572a69e4..7719aa86dd0 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.js+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/ViewTitleHeader.unit.spec.js@@ -615,7 +615,6 @@ describe("View Header | Hidden tables", () => {joins: [{alias: "Orders",- ident: "3Q-699fD5ZhmyLL1fPle2",fields: "all","source-table": ORDERS_ID,condition: [@@ -646,7 +645,6 @@ describe("View Header | Inaccessible Cards", () => {joins: [{alias: "Orders",- ident: "uAysG9UfH3RUnErkkOw77",fields: "all","source-table": ORDERS_ID,condition: [diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.js b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.jsindex 688c89454e7..4c19eb74df4 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.js+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/QuestionDataSource/QuestionDataSource.unit.spec.js@@ -106,14 +106,12 @@ const ORDERS_PEOPLE_JOIN_CONDITION = [const PRODUCTS_JOIN = {alias: "Products",- ident: "WS62Exm69R6ffcsJ-aswG",condition: ORDERS_PRODUCT_JOIN_CONDITION,"source-table": PRODUCTS_ID,};const PEOPLE_JOIN = {alias: "People",- ident: "V0nl07W2JKSFu1-w2pL_i",condition: ORDERS_PEOPLE_JOIN_CONDITION,"source-table": PEOPLE_ID,};diff --git a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/SavedQuestionLeftSide/ViewOnly.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/SavedQuestionLeftSide/ViewOnly.unit.spec.tsxindex 693d853a6c9..486afd20244 100644--- a/frontend/src/metabase/query_builder/components/view/ViewHeader/components/SavedQuestionLeftSide/ViewOnly.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewHeader/components/SavedQuestionLeftSide/ViewOnly.unit.spec.tsx@@ -159,7 +159,6 @@ describe("ViewOnlyTag", () => {joins: [{alias: "Orders Question",- ident: "Heqv_gfsCdfE95MkLLup_",fields: "all",// This card does not exist"source-table": "card__123",@@ -227,7 +226,6 @@ describe("ViewOnlyTag", () => {joins: [{alias: "Orders Question",- ident: "Heqv_gfsCdfE95MkLLup_",fields: "all","source-table": `card__${sourceCard.id}`,condition: [diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/utils.unit.spec.ts b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/utils.unit.spec.tsindex a422c88718e..b839dcf98cc 100644--- a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/utils.unit.spec.ts+++ b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionInfoSidebar/components/utils.unit.spec.ts@@ -25,7 +25,6 @@ const cardWithJoins = createMockCard({query: {joins: [{- ident: "ident",fields: "all",strategy: "left-join",alias: "joined table",diff --git a/frontend/src/metabase/query_builder/selectors.unit.spec.js b/frontend/src/metabase/query_builder/selectors.unit.spec.jsindex ddf085cfa9e..41b08ecb402 100644--- a/frontend/src/metabase/query_builder/selectors.unit.spec.js+++ b/frontend/src/metabase/query_builder/selectors.unit.spec.js@@ -169,7 +169,6 @@ describe("getIsResultDirty", () => {const filter = [">", ["field", ORDERS.TOTAL, null], 20];const join = {alias: "Products",- ident: "LUso-laB06h37QT_phn2R",fields: "all","source-table": PRODUCTS_ID,condition: [diff --git a/frontend/test/metabase-lib/lib/Question.unit.spec.js b/frontend/test/metabase-lib/lib/Question.unit.spec.jsindex 0f41540feef..dd400dc9b41 100644--- a/frontend/test/metabase-lib/lib/Question.unit.spec.js+++ b/frontend/test/metabase-lib/lib/Question.unit.spec.js@@ -187,7 +187,6 @@ const orders_join_card = {["joined-field", "Products", ["field-id", PRODUCTS.ID]],],alias: "Products",- ident: "6gujbiqQ08_bn-GTZcDFI",},],},diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test.cljindex e347e058b73..7067f39fc55 100644--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test.clj+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk/query_processor_test.clj@@ -496,8 +496,7 @@:base-type :type/Date::add/source-table ::add/source::add/source-alias "date"- ::add/desired-alias "date"- ::add/position 0}])))))))))+ ::add/desired-alias "date"}])))))))))(deftest ^:parallel between-test(testing "Make sure :between clauses reconcile the temporal types of their args"diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.cljindex 2194a758fbb..44c654b4f8f 100644--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj@@ -26,7 +26,7 @@[metabase.warehouse-schema.models.field-values :as field-values][toucan2.core :as t2])(:import- (com.google.cloud.bigquery TableResult)))+ (com.google.cloud.bigquery BigQuery TableResult)))(set! *warn-on-reflection* true)@@ -44,13 +44,13 @@[table-name](bigquery.tx/execute! (format "DROP TABLE IF EXISTS `%s`;" (fmt-table-name table-name))))-(deftest sanity-check-test+(deftest ^:parallel sanity-check-test(mt/test-driver:bigquery-cloud-sdk(mt/datasettest-data(is (seq (mt/rows- (mt/run-mbql-query orders)))))))+ (mt/run-mbql-query orders {:limit 1})))))))(deftest can-connect?-test(mt/test-driver :bigquery-cloud-sdk@@ -71,7 +71,7 @@(driver/can-connect? :bigquery-cloud-sdk(assoc db-details :dataset-filters-patterns fake-dataset-id))))))))-(deftest table-rows-sample-test+(deftest ^:parallel table-rows-sample-test(mt/test-driver :bigquery-cloud-sdk(testing "without worrying about pagination"(is (= [[1 "Red Medicine"]@@ -84,17 +84,18 @@(t2/select-one :model/Field :id (mt/id :venues :name))](constantly conj))(sort-by first)- (take 5)))))-- ;; the initial dataset isn't realized until it's used the first time. because of that,- ;; we don't care how many pages it took to load this dataset above. it will be a large- ;; number because we're just tracking the number of times `get-query-results` gets invoked.+ (take 5)))))))+(deftest ^:parallel table-rows-sample-test-2+ (mt/test-driver :bigquery-cloud-sdk+ ;; the initial dataset isn't realized until it's used the first time. because of that,+ ;; we don't care how many pages it took to load this dataset above. it will be a large+ ;; number because we're just tracking the number of times `get-query-results` gets invoked.(testing "with pagination"(let [pages-retrieved (atom 0)page-callback (fn [] (swap! pages-retrieved inc))]- (with-bindings {#'bigquery/*page-size* 25- #'bigquery/*page-callback* page-callback}+ (binding [bigquery/*page-size* 25+ bigquery/*page-callback* page-callback](let [results (->> (table-rows-sample/table-rows-sample (t2/select-one :model/Table :id (mt/id :venues))[(t2/select-one :model/Field :id (mt/id :venues :id))(t2/select-one :model/Field :id (mt/id :venues :name))]@@ -109,11 +110,11 @@(take 5 results)))(testing "results are not duplicated when pagination occurs (#45953)"(is (= (count results) (count (distinct results)))))- ;; the `(sort-by)` above will cause the entire resultset to be realized, so- ;; we want to make sure that it really did retrieve 25 rows per request- ;; this only works if the timeout has been temporarily set to 0 (see above)+ ;; the `(sort-by)` above will cause the entire resultset to be realized, so+ ;; we want to make sure that it really did retrieve 25 rows per request+ ;; this only works if the timeout has been temporarily set to 0 (see above)- ;; TODO Temporarily disabling due to flakiness (#33140)+ ;; TODO Temporarily disabling due to flakiness (#33140)#_(is (= 4 @pages-retrieved))))))));; These look like the macros from metabase.query-processor-test.expressions-test@@ -134,59 +135,77 @@(mt/$ids ~'bird-count(calculate-bird-scarcity* ~formula ~filter-clause))))-(deftest nulls-and-zeroes-test+(deftest ^:parallel nulls-and-zeroes-test(mt/test-driver :bigquery-cloud-sdk(testing (str "hey... expressions should work if they are just a Field! (Also, this lets us take a peek at the ""raw values being used to calculate the formulas below, so we can tell at a glance if they're right ""without referring to the EDN def)")(is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]]#_:clj-kondo/ignore- (calculate-bird-scarcity $count))))+ (calculate-bird-scarcity $count))))))+(deftest ^:parallel nulls-and-zeroes-test-2+ (mt/test-driver :bigquery-cloud-sdk(testing (str "do expressions automatically handle division by zero? Should return `nil` in the results for places ""where that was attempted")(is (= [[nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [9.09] [7.14]](calculate-bird-scarcity [:/ 100.0 $count]- [:!= $count nil]))))+ [:!= $count nil]))))))+(deftest ^:parallel nulls-and-zeroes-test-3+ (mt/test-driver :bigquery-cloud-sdk(testing (str "do expressions handle division by `nil`? Should return `nil` in the results for places where that ""was attempted")(is (= [[nil] [10.0] [12.5] [20.0] [20.0] [nil] [9.09] [7.14] [12.5] [7.14]](calculate-bird-scarcity [:/ 100.0 $count][:or[:= $count nil]- [:!= $count 0]]))))+ [:!= $count 0]]))))))+(deftest ^:parallel nulls-and-zeroes-test-4+ (mt/test-driver :bigquery-cloud-sdk(testing "can we handle BOTH NULLS AND ZEROES AT THE SAME TIME????"(is (= [[nil] [nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [nil]]- (calculate-bird-scarcity [:/ 100.0 $count]))))+ (calculate-bird-scarcity [:/ 100.0 $count]))))))+(deftest ^:parallel nulls-and-zeroes-test-5+ (mt/test-driver :bigquery-cloud-sdk(testing "ok, what if we use multiple args to divide, and more than one is zero?"(is (= [[nil] [nil] [nil] [1.0] [1.56] [4.0] [4.0] [nil] [nil] [nil]]- (calculate-bird-scarcity [:/ 100.0 $count $count]))))+ (calculate-bird-scarcity [:/ 100.0 $count $count]))))))+(deftest ^:parallel nulls-and-zeroes-test-6+ (mt/test-driver :bigquery-cloud-sdk(testing "are nulls/zeroes still handled appropriately when nested inside other expressions?"(is (= [[nil] [nil] [nil] [20.0] [25.0] [40.0] [40.0] [nil] [nil] [nil]]- (calculate-bird-scarcity [:* [:/ 100.0 $count] 2]))))+ (calculate-bird-scarcity [:* [:/ 100.0 $count] 2]))))))+(deftest ^:parallel nulls-and-zeroes-test-7+ (mt/test-driver :bigquery-cloud-sdk(testing (str "if a zero is present in the NUMERATOR we should return ZERO and not NULL ""(`0 / 10 = 0`; `10 / 0 = NULL`, at least as far as MBQL is concerned)")(is (= [[nil] [0.0] [0.0] [1.0] [0.8] [0.5] [0.5] [nil] [0.0] [0.0]]- (calculate-bird-scarcity [:/ $count 10]))))+ (calculate-bird-scarcity [:/ $count 10]))))))+(deftest ^:parallel nulls-and-zeroes-test-8+ (mt/test-driver :bigquery-cloud-sdk(testing "can addition handle nulls & zeroes?"(is (= [[nil] [10.0] [10.0] [20.0] [18.0] [15.0] [15.0] [nil] [10.0] [10.0]]- (calculate-bird-scarcity [:+ $count 10]))))+ (calculate-bird-scarcity [:+ $count 10]))))))+(deftest ^:parallel nulls-and-zeroes-test-9+ (mt/test-driver :bigquery-cloud-sdk(testing "can subtraction handle nulls & zeroes?"(is (= [[nil] [10.0] [10.0] [0.0] [2.0] [5.0] [5.0] [nil] [10.0] [10.0]]- (calculate-bird-scarcity [:- 10 $count]))))+ (calculate-bird-scarcity [:- 10 $count]))))))+(deftest ^:parallel nulls-and-zeroes-test-10+ (mt/test-driver :bigquery-cloud-sdk(testing "can multiplications handle nulls & zeros?"(is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]](calculate-bird-scarcity [:* 1 $count]))))))-(deftest db-default-timezone-test+(deftest ^:parallel db-default-timezone-test(mt/test-driver :bigquery-cloud-sdk(is (= "UTC"(driver/db-default-timezone :bigquery-cloud-sdk (mt/db))))))@@ -230,7 +249,7 @@(is (<= 22000 (count (into [] (driver/describe-fields :bigquery-cloud-sdk (mt/db))))))(is (<= 20 @invocation-count))))))))))-(def native-dataset+(def ^:private native-dataset(tx/native-dataset-definition"native-dataset"[["categories"@@ -489,19 +508,18 @@(into [] (filter (fn [x] (= (:table-name x) "records_o"))(driver/describe-fields :bigquery-cloud-sdk (mt/db) {:table-names ["records" "records_o"]}))))))))))-(deftest query-nested-fields-test- (mt/test-driver- :bigquery-cloud-sdk- (mt/dataset- nested-records- (is (= {:columns ["r.a" "r.b" "r.rr.aa" "r.rr"]- :rows [[1 "a" 10 {:aa 10}] [2 "b" nil nil] [3 "c" nil nil]]}- (mt/rows+column-names- (mt/run-mbql-query records- {:fields [(mt/id :records :r :a)- (mt/id :records :r :b)- (mt/id :records :r :rr :aa)- (mt/id :records :r :rr)]})))))))+(deftest ^:parallel query-nested-fields-test+ (mt/test-driver :bigquery-cloud-sdk+ (mt/dataset nested-records+ (let [query (mt/mbql-query records+ {:fields [(mt/id :records :r :a)+ (mt/id :records :r :b)+ (mt/id :records :r :rr :aa)+ (mt/id :records :r :rr)]})]+ (mt/with-native-query-testing-context query+ (is (= {:columns ["r.a" "r.b" "r.rr.aa" "r.rr"]+ :rows [[1 "a" 10 {:aa 10}] [2 "b" nil nil] [3 "c" nil nil]]}+ (mt/rows+column-names (qp/process-query query)))))))))(deftest sync-table-with-required-filter-test(mt/test-driver@@ -564,48 +582,53 @@:bigquery-cloud-sdk(mt/dataset native-dataset(testing "Partitioned tables that require a partition filter can be synced"- (let [table-names ["partition_by_range" "partition_by_time_2" "partition_by_datetime"- "partition_by_ingestion_time_2" "partition_by_ingestion_time_not_required_2"]- mv-names ["mv_partition_by_datetime" "mv_partition_by_range"]]- (let [table-ids (t2/select-pks-vec :model/Table :db_id (mt/id) :name [:in (concat mv-names table-names)])- all-field-ids (t2/select-pks-vec :model/Field :table_id [:in table-ids])]- (testing "Field values are correctly synced"- ;; Manually activate Field values since they are not created during sync (#53387)- (doseq [field (t2/select :model/Field :id [:in all-field-ids])]- (field-values/get-or-create-full-field-values! field))- (is (= {"customer_id" #{1 2 3}- "vip_customer" #{42}- "name" #{"Khuat" "Quang" "Ngoc"}- "company" #{"Metabase" "Tesla" "Apple"}- "ev_company" #{"Tesla"}- "is_awesome" #{true false}- "is_opensource" #{true false}}- (->> (t2/query {:select [[:field.name :field-name] [:fv.values :values]]- :from [[:metabase_field :field]]- :join [[:metabase_fieldvalues :fv] [:= :field.id :fv.field_id]]- :where [:and [:in :field.table_id table-ids]- [:in :field.name ["customer_id" "vip_customer" "name" "is_awesome" "is_opensource" "company" "ev_company"]]]})- (map #(update % :values (comp set json/decode)))- (map (juxt :field-name :values))- (into {}))))))-- (testing "for ingestion time partitioned tables, we should sync the pseudocolumn _PARTITIONTIME and _PARTITIONDATE"- (let [ingestion-time-partitioned-table-id (t2/select-one-pk :model/Table :db_id (mt/id)- :name "partition_by_ingestion_time_not_required_2")]- (is (=? [{:name "_PARTITIONTIME"- :database_type "TIMESTAMP"- :base_type :type/DateTimeWithLocalTZ- :database_position 1}- {:name "_PARTITIONDATE"- :database_type "DATE"- :base_type :type/Date- :database_position 2}]- (t2/select :model/Field :table_id ingestion-time-partitioned-table-id- :database_partitioned true {:order-by [[:name :desc]]}))))- (testing "and query this table should return the column pseudocolumn as well"- (is (malli=- [:tuple :boolean ms/TemporalString ms/TemporalString]- (first (mt/rows (mt/run-mbql-query partition_by_ingestion_time_not_required_2 {:limit 1}))))))))))))+ (let [table-names ["partition_by_range" "partition_by_time_2" "partition_by_datetime"+ "partition_by_ingestion_time_2" "partition_by_ingestion_time_not_required_2"]+ mv-names ["mv_partition_by_datetime" "mv_partition_by_range"]+ table-ids (t2/select-pks-vec :model/Table :db_id (mt/id) :name [:in (concat mv-names table-names)])+ all-field-ids (t2/select-pks-vec :model/Field :table_id [:in table-ids])]+ (testing "Field values are correctly synced"+ ;; Manually activate Field values since they are not created during sync (#53387)+ (doseq [field (t2/select :model/Field :id [:in all-field-ids])]+ (field-values/get-or-create-full-field-values! field))+ (is (= {"customer_id" #{1 2 3}+ "vip_customer" #{42}+ "name" #{"Khuat" "Quang" "Ngoc"}+ "company" #{"Metabase" "Tesla" "Apple"}+ "ev_company" #{"Tesla"}+ "is_awesome" #{true false}+ "is_opensource" #{true false}}+ (->> (t2/query {:select [[:field.name :field-name] [:fv.values :values]]+ :from [[:metabase_field :field]]+ :join [[:metabase_fieldvalues :fv] [:= :field.id :fv.field_id]]+ :where [:and [:in :field.table_id table-ids]+ [:in :field.name ["customer_id" "vip_customer" "name" "is_awesome" "is_opensource" "company" "ev_company"]]]})+ (map #(update % :values (comp set json/decode)))+ (map (juxt :field-name :values))+ (into {}))))))))))++(deftest full-sync-partitioned-table-test-2+ (mt/test-driver+ :bigquery-cloud-sdk+ (mt/dataset native-dataset+ (testing "Partitioned tables that require a partition filter can be synced"+ (testing "for ingestion time partitioned tables, we should sync the pseudocolumn _PARTITIONTIME and _PARTITIONDATE"+ (let [ingestion-time-partitioned-table-id (t2/select-one-pk :model/Table :db_id (mt/id)+ :name "partition_by_ingestion_time_not_required_2")]+ (is (=? [{:name "_PARTITIONTIME"+ :database_type "TIMESTAMP"+ :base_type :type/DateTimeWithLocalTZ+ :database_position 1}+ {:name "_PARTITIONDATE"+ :database_type "DATE"+ :base_type :type/Date+ :database_position 2}]+ (t2/select :model/Field :table_id ingestion-time-partitioned-table-id+ :database_partitioned true {:order-by [[:name :desc]]}))))+ (testing "and query this table should return the column pseudocolumn as well"+ (is (malli=+ [:tuple :boolean ms/TemporalString ms/TemporalString]+ (first (mt/rows (mt/run-mbql-query partition_by_ingestion_time_not_required_2 {:limit 1})))))))))))(deftest sync-update-require-partition-option-test(mt/test-driver :bigquery-cloud-sdk@@ -1271,29 +1294,29 @@(:error result)))))))(is (< (count before-names) (+ (count (future-thread-names)) 5))))))-(deftest alternate-host-test+(deftest ^:parallel alternate-host-test(mt/test-driver :bigquery-cloud-sdk(testing "Alternate BigQuery host can be configured"(mt/with-temp [:model/Database {:as temp-db}{:engine :bigquery-cloud-sdk:details (-> (:details (mt/db))(assoc :host "bigquery.example.com"))}]- (let [client (#'bigquery/database-details->client (:details temp-db))]+ (let [^BigQuery client (#'bigquery/database-details->client (:details temp-db))](is (= "bigquery.example.com"(.getHost (.getOptions client)))"BigQuery client should be configured with alternate host"))))))-(deftest user-agent-is-set-test+(deftest ^:parallel user-agent-is-set-test(mt/test-driver :bigquery-cloud-sdk(testing "User agent is set for bigquery requests"- (let [client (#'bigquery/database-details->client (:details (mt/db)))- mb-version (:tag config/mb-version-info)- run-mode (name config/run-mode)- user-agent (format "Metabase/%s (GPN:Metabase; %s)" mb-version run-mode)]+ (let [^BigQuery client (#'bigquery/database-details->client (:details (mt/db)))+ mb-version (:tag config/mb-version-info)+ run-mode (name config/run-mode)+ user-agent (format "Metabase/%s (GPN:Metabase; %s)" mb-version run-mode)](is (= user-agent(-> client .getOptions .getUserAgent)))))))-(deftest timestamp-precision-test+(deftest ^:parallel timestamp-precision-test(mt/test-driver :bigquery-cloud-sdk(let [sql (str "select"" timestamp '2024-12-11 16:23:55.123456 UTC' col_timestamp,"diff --git a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.cljindex 223e3665f07..e6db41c2396 100644--- a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj+++ b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj@@ -155,24 +155,21 @@{:arglists '([field])}driver-api/dispatch-by-clause-name-or-class)-(defn- field-name-components [{:keys [parent-id], field-name :name, :as _field}]+(defn- col->name-components [{:keys [parent-id], field-name :name, :as _col}](concat+ ;; TODO (Cam 8/11/25) -- this should be using `:nfc-path` instead of looking this up the hard way(when parent-id- (field-name-components (driver-api/field (driver-api/metadata-provider) parent-id)))+ (col->name-components (driver-api/field (driver-api/metadata-provider) parent-id)))[field-name]))(mu/defn field->name- "Return a single string name for `field`. For nested fields, this creates a combined qualified name."- ([field]- (field->name field \.))+ "Return a single string name for column metadata `col` For nested fields, this creates a combined qualified name."+ ([col]+ (field->name col \.))- ([field :- driver-api/schema.metadata.column+ ([col :- driver-api/schema.metadata.columnseparator :- [:or :string char?]]- (str/join separator (field-name-components field))))--(mu/defmethod driver-api/field-reference-mlv2 :mongo- [_driver field-inst :- driver-api/schema.metadata.column]- (field->name field-inst))+ (str/join separator (col->name-components col))))(defmacro ^:private mongo-let{:style/indent 1}@@ -210,31 +207,31 @@(def ^:private base64-decoder "function(bin) {if (!bin) return null;-+try {var base64 = bin.base64();-+// Manual base64 decode implementationvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';var result = '';var i = 0;-+// Remove any paddingbase64 = base64.replace(/=+$/, '');-+while (i < base64.length) {var a = chars.indexOf(base64.charAt(i++));var b = chars.indexOf(base64.charAt(i++));var c = chars.indexOf(base64.charAt(i++));var d = chars.indexOf(base64.charAt(i++));-+var bitmap = (a << 18) | (b << 12) | (c << 6) | d;-+result += String.fromCharCode((bitmap >> 16) & 255);if (c !== -1) result += String.fromCharCode((bitmap >> 8) & 255);if (d !== -1) result += String.fromCharCode(bitmap & 255);}-+return result;} catch(e) {return null;@@ -316,13 +313,13 @@ function(bin) {(driver-api/aggregation-name (:query *query*) (driver-api/aggregation-at-index *query* index *nesting-level*)))(defmethod ->lvalue :field- [[_ id-or-name {:keys [join-alias] :as opts} :as field]]+ [[_ id-or-name {:keys [join-alias] :as opts} :as field]](if (integer? id-or-name)(or (find-mapped-field-name field)(->lvalue (assoc (driver-api/field (driver-api/metadata-provider) id-or-name)- ::source-alias (get opts driver-api/qp.add.source-alias)+ ::source-alias (driver-api/qp.add.source-alias opts)::join-field (get-join-alias join-alias))))- (scope-with-join-field (name id-or-name) (get-join-alias join-alias) (get opts driver-api/qp.add.source-alias))))+ (scope-with-join-field (name id-or-name) (get-join-alias join-alias) (driver-api/qp.add.source-alias opts))))(defn- add-start-of-week-offset [expr offset](cond@@ -441,7 +438,7 @@ function(bin) {(defmethod ->rvalue :field[[_ id-or-name {:keys [temporal-unit join-alias] :as opts} :as field]](let [join-field (get-join-alias join-alias)- source-alias (get opts driver-api/qp.add.source-alias)]+ source-alias (driver-api/qp.add.source-alias opts)](cond-> (if (integer? id-or-name)(if-let [mapped (find-mapped-field-name field)](str \$ mapped)@@ -1158,9 +1155,9 @@ function(bin) {(recur arg)ag))-(defn- field-alias [field]- (or (get-in field [2 driver-api/qp.add.desired-alias])- (->lvalue field)))+(defn- field-alias [[_tag _id-or-name opts, :as field-ref]]+ (or (driver-api/qp.add.desired-alias opts)+ (->lvalue field-ref)))(mu/defn- breakouts-and-ags->projected-fields :- [:maybe [:sequential [:tuple driver-api/schema.common.non-blank-string :any]]]"Determine field projections for MBQL breakouts and aggregations. Returns a sequence of pairs like@@ -1643,13 +1640,13 @@ function(bin) {(reduce (fn [pipeline-ctx f](f inner-query pipeline-ctx))pipeline-ctx- [handle-joins- handle-filter- handle-breakout+aggregation- handle-order-by- handle-fields- handle-limit- handle-page])))+ [#'handle-joins+ #'handle-filter+ #'handle-breakout+aggregation+ #'handle-order-by+ #'handle-fields+ #'handle-limit+ #'handle-page])))(mu/defn- generate-aggregation-pipeline :- [:map[:projections Projections]@@ -1719,31 +1716,55 @@ function(bin) {;;; until we get around to fixing that let's just walk the query and replace all the non-add-alias-info keys with the;;; values added by add-alias-info.(defn- HACK-update-aliases [form]- (driver-api/replace form- (m :guard (every-pred map?- :alias- driver-api/qp.add.alias- #(not= (driver-api/qp.add.alias %) (:alias %))))- (HACK-update-aliases (assoc m :alias (driver-api/qp.add.alias m)))-- [:field id-or-name (opts :guard (every-pred map?- #(not= (:name %) (driver-api/qp.add.source-alias %))))]- (let [id-or-name' (if (string? id-or-name)- (driver-api/qp.add.source-alias opts)- id-or-name)]- (HACK-update-aliases [:field id-or-name' (assoc opts :name (driver-api/qp.add.source-alias opts))]))-- [:field id-or-name (opts :guard (every-pred map?- :join-alias- #(= (driver-api/qp.add.source-table %) driver-api/qp.add.source)))]- [:field id-or-name (-> opts- (dissoc :join-alias)- (assoc ::fixed true))]-- [:field id-or-name (opts :guard (every-pred map?- :join-alias- #(string? (driver-api/qp.add.source-table %))))]- [:field id-or-name (assoc opts :join-alias (driver-api/qp.add.source-table opts))]))+ (letfn [(prepend-nfc-path [{nfc-path driver-api/qp.add.nfc-path,+ source-alias driver-api/qp.add.source-alias,+ desired-alias driver-api/qp.add.desired-alias,+ :as opts}]+ (when (seq nfc-path)+ (let [nfc-path-str (str/join \. nfc-path)]+ (-> opts+ (assoc driver-api/qp.add.source-alias (str nfc-path-str \. source-alias)+ driver-api/qp.add.desired-alias (str nfc-path-str \. desired-alias))+ (dissoc driver-api/qp.add.nfc-path)))))+ (update-name [{field-name :name, source-alias driver-api/qp.add.source-alias, :as opts}]+ (when (and source-alias+ (not= field-name source-alias))+ (assoc opts :name source-alias)))+ (remove-bad-join-alias [{:keys [join-alias], source-table driver-api/qp.add.source-table, :as opts}]+ (when (and join-alias+ (= source-table driver-api/qp.add.source))+ (dissoc opts :join-alias)))+ (update-join-alias [{:keys [join-alias], source-table driver-api/qp.add.source-table, :as opts}]+ (when (and join-alias+ source-table+ (not= join-alias source-table))+ (assoc opts :join-alias source-table)))+ (update-opts [opts]+ (reduce+ (fn+ [opts f]+ (or (f opts)+ opts))+ opts+ [prepend-nfc-path+ update-join-alias+ update-name+ remove-bad-join-alias+ update-join-alias]))+ (update-field-ref [[_tag id-or-name {source-alias driver-api/qp.add.source-alias, :as opts}]]+ (let [opts (update-opts opts)]+ (if (and (string? id-or-name)+ source-alias)+ [:field source-alias opts]+ [:field id-or-name opts])))]+ (driver-api/replace form+ :field+ (update-field-ref &match)++ (join :guard (every-pred map?+ driver-api/qp.add.alias+ #(not= (driver-api/qp.add.alias %) (:alias %))))+ (recur (assoc join :alias (driver-api/qp.add.alias join))))))(defn- preprocess[inner-query]diff --git a/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.clj b/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.cljindex ce19c937f66..20921594a38 100644--- a/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.clj+++ b/modules/drivers/mongo/test/metabase/driver/mongo/query_processor_test.clj@@ -559,7 +559,7 @@{"$expr" {"$eq" ["$price" {"$add" [{"$subtract" ["$price" 5]} 100]}]}}[:= $price [:+ [:- $price 5] 100]]))))-(deftest ^:parallel uniqe-alias-index-test+(deftest ^:parallel unique-alias-index-test(mt/test-driver:mongo(testing "Field aliases have deterministic unique indices"@@ -586,7 +586,7 @@indices (reduce (fn [acc lookup-stage](let [let-var-name (-> (get-in lookup-stage ["$lookup" :let]) keys first);; Following expression ensures index is an integer.- index (Integer/parseInt (re-find #"\d+$" let-var-name))]+ index (parse-long (re-find #"\d+$" let-var-name))];; Following expression tests that index is unique.(is (not (contains? acc index)))(conj acc index)))diff --git a/modules/drivers/oracle/test/metabase/test/data/oracle.clj b/modules/drivers/oracle/test/metabase/test/data/oracle.cljindex 09d4c951f38..53caa600580 100644--- a/modules/drivers/oracle/test/metabase/test/data/oracle.clj+++ b/modules/drivers/oracle/test/metabase/test/data/oracle.clj@@ -65,7 +65,7 @@:user (tx/db-test-env-var :oracle :user):password (tx/db-test-env-var :oracle :password):sid (tx/db-test-env-var :oracle :sid)- :service-name (tx/db-test-env-var :oracle :service-name (when-not (tx/db-test-env-var :oracle :sid) "XEPDB1"))+ :service-name (tx/db-test-env-var :oracle :service-name (tx/db-test-env-var :oracle :sid "FREEPDB1")):ssl (Boolean/parseBoolean (tx/db-test-env-var :oracle :ssl "false")):schema-filters-type "inclusion":schema-filters-patterns session-schema}diff --git a/modules/drivers/sqlite/test/metabase/driver/sqlite_test.clj b/modules/drivers/sqlite/test/metabase/driver/sqlite_test.cljindex 63ac9be6eeb..7ae2d06f45b 100644--- a/modules/drivers/sqlite/test/metabase/driver/sqlite_test.clj+++ b/modules/drivers/sqlite/test/metabase/driver/sqlite_test.clj@@ -14,12 +14,12 @@(set! *warn-on-reflection* true)-(deftest timezone-id-test+(deftest ^:parallel timezone-id-test(mt/test-driver :sqlite(is (= "UTC"(driver/db-default-timezone :sqlite (mt/db))))))-(deftest filter-by-date-test+(deftest ^:parallel filter-by-date-test(testing "Make sure filtering against a LocalDate works correctly in SQLite"(mt/test-driver :sqlite(is (= [[225 "2014-03-04T00:00:00Z"]@@ -208,28 +208,27 @@{:fields [$col_timestamp $col_date $col_datetime]:filter [:= $test_case "null"]}))))))))))-(deftest duplicate-identifiers-test+(deftest ^:parallel duplicate-identifiers-test(testing "Make sure duplicate identifiers (even with different cases) get unique aliases"(mt/test-driver :sqlite- (mt/dataset test-data- (is (= '{:select [source.CATEGORY_2 AS CATEGORY- COUNT (*) AS count]- :from [{:select [products.category AS category- products.category || ? AS CATEGORY_2]- :from [products]}- AS source]- :group-by [source.CATEGORY_2]- :order-by [source.CATEGORY_2 ASC]- :limit [1]}- (sql.qp-test-util/query->sql-map- (mt/mbql-query products- {:expressions {:CATEGORY [:concat $category "2"]}- :breakout [:expression :CATEGORY]- :aggregation [:count]- :order-by [[:asc [:expression :CATEGORY]]]- :limit 1}))))))))+ (is (= '{:select [source.CATEGORY_2 AS CATEGORY_2+ COUNT (*) AS count]+ :from [{:select [products.category AS category+ products.category || ? AS CATEGORY_2]+ :from [products]}+ AS source]+ :group-by [source.CATEGORY_2]+ :order-by [source.CATEGORY_2 ASC]+ :limit [1]}+ (sql.qp-test-util/query->sql-map+ (mt/mbql-query products+ {:expressions {:CATEGORY [:concat $category "2"]}+ :breakout [:expression :CATEGORY]+ :aggregation [:count]+ :order-by [[:asc [:expression :CATEGORY]]]+ :limit 1})))))))-(deftest disallow-fdw-to-other-databases-test+(deftest ^:parallel disallow-fdw-to-other-databases-test(testing "Don't allow connections to other SQLite databases with ATTACH DATABASE (https://github.com/metabase/metaboat/issues/152)"(mt/test-driver :sqlite;; force creation of the sample dataset filediff --git a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.cljindex 5bac14d6bd4..94f5e51cf78 100644--- a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj+++ b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj@@ -542,7 +542,7 @@(update :order-by distinct))))(defmethod sql.qp/apply-top-level-clause [:sqlserver :filter]- [driver _ honeysql-form query]+ [driver _k honeysql-form query](let [parent-method (get-method sql.qp/apply-top-level-clause [:sql-jdbc :filter])](->> (update query :filter sql.qp.boolean-to-comparison/boolean->comparison)(parent-method driver :filter honeysql-form))))diff --git a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.cljindex aefb1d4e813..62024ecd50d 100644--- a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj+++ b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj@@ -8,6 +8,7 @@[medley.core :as m][metabase.config.core :as config][metabase.driver :as driver]+ [metabase.driver-api.core :as driver-api][metabase.driver.common :as driver.common][metabase.driver.sql :as driver.sql][metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]@@ -24,6 +25,7 @@[metabase.test :as mt][metabase.test.util.timezone :as test.tz][metabase.util.date-2 :as u.date]+ [metabase.util.honey-sql-2 :as h2x][next.jdbc]))(set! *warn-on-reflection* true)@@ -436,7 +438,7 @@{"year"{:expected-sql["SELECT"- " CAST(",+ " CAST("" DATEFROMPARTS(YEAR(dbo.orders.created_at), 1, 1) AS datetime2"" ) AS created_at,"" COUNT(*) AS count"@@ -721,3 +723,36 @@(testing "ignores user field and only uses role field"(let [database {:details {:user "login_user" :role "impersonation_user"}}](is (= "impersonation_user" (driver.sql/default-database-role :sqlserver database)))))))++(deftest ^:parallel wtf-test+ (driver/with-driver :sqlserver+ (qp.store/with-metadata-provider (mt/id)+ (binding [sql.qp/*inner-query* {:expressions+ {"NameEquals"+ [:=+ [:field+ "LiteralString"+ {:base-type :type/Text+ :join-alias "JoinedCategories"+ driver-api/qp.add.source-table "JoinedCategories"+ driver-api/qp.add.source-alias "LiteralString"+ driver-api/qp.add.desired-alias "JoinedCategories__LiteralString"}]+ [:field+ (mt/id :venues :name)+ {driver-api/qp.add.source-table (mt/id :venues)+ driver-api/qp.add.source-alias "name"+ driver-api/qp.add.desired-alias "name"}]]}}]++ (is (= {:where+ [:=+ [::h2x/identifier :field ["JoinedCategories" "LiteralString"]]+ [::h2x/typed+ [::h2x/identifier :field ["dbo" "venues" "name"]]+ {:database-type "varchar"}]]}+ (sql.qp/apply-top-level-clause+ :sqlserver+ :filter+ {}+ {:filter [:expression "NameEquals" {:base-type :type/Boolean+ driver-api/qp.add.source-table driver-api/qp.add.none+ driver-api/qp.add.desired-alias nil}]})))))))diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/-fFVxT-GLz6WO41bvw-Ar_dashboards_without_recent_views.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/-fFVxT-GLz6WO41bvw-Ar_dashboards_without_recent_views.yamlindex b74704f3afa..1940a5a3735 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/-fFVxT-GLz6WO41bvw-Ar_dashboards_without_recent_views.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/-fFVxT-GLz6WO41bvw-Ar_dashboards_without_recent_views.yaml@@ -94,7 +94,6 @@ dataset_query:- base-type: type/Textjoin-alias: Last content viewed at - Entity Qualifiedfields: none- ident: join_-fFVxT-GLz6WO41bvw-Ar@0__Last content viewed at - Entity Qualifiedsource-table: tKEl86EXMyTDIoO9nyFTVstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/57V11my5MYVnSlaJYM8cX_most_viewed_models.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/57V11my5MYVnSlaJYM8cX_most_viewed_models.yamlindex 07d9719ee23..62771174d94 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/57V11my5MYVnSlaJYM8cX_most_viewed_models.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/57V11my5MYVnSlaJYM8cX_most_viewed_models.yaml@@ -90,7 +90,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_57V11my5MYVnSlaJYM8cX@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -106,7 +105,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join_57V11my5MYVnSlaJYM8cX@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -125,7 +123,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_57V11my5MYVnSlaJYM8cX@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: V Databases - Question Database@@ -146,7 +143,6 @@ dataset_query:- base-type: type/Textjoin-alias: V Databases - Question Databasefields: all- ident: join_57V11my5MYVnSlaJYM8cX@0__V Databases - Question Databasesource-table:- Internal Metabase Database- publicdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5EsTAgs6Uu_xz69TsrUJ4_last_viewed_models.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5EsTAgs6Uu_xz69TsrUJ4_last_viewed_models.yamlindex 264f64225ef..b04d09d47c6 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5EsTAgs6Uu_xz69TsrUJ4_last_viewed_models.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5EsTAgs6Uu_xz69TsrUJ4_last_viewed_models.yaml@@ -88,7 +88,6 @@ dataset_query:- description- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_5EsTAgs6Uu_xz69TsrUJ4@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -106,7 +105,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Creatorfields: none- ident: join_5EsTAgs6Uu_xz69TsrUJ4@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5HQS2xXAPF4hOFudut_Tg_last_viewed_dashboards.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5HQS2xXAPF4hOFudut_Tg_last_viewed_dashboards.yamlindex 4c40dd794d6..80beae69e8a 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5HQS2xXAPF4hOFudut_Tg_last_viewed_dashboards.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5HQS2xXAPF4hOFudut_Tg_last_viewed_dashboards.yaml@@ -78,7 +78,6 @@ dataset_query:- description- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_5HQS2xXAPF4hOFudut_Tg@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -95,7 +94,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Creatorfields: none- ident: join_5HQS2xXAPF4hOFudut_Tg@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5gASJxNKdQCmkiGXb5kRP_dashboards_consuming_most_resources.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5gASJxNKdQCmkiGXb5kRP_dashboards_consuming_most_resources.yamlindex 378e822c9a0..3e94b6a18bf 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5gASJxNKdQCmkiGXb5kRP_dashboards_consuming_most_resources.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/5gASJxNKdQCmkiGXb5kRP_dashboards_consuming_most_resources.yaml@@ -89,7 +89,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Dashboard Qualifiedfields: all- ident: join_5gASJxNKdQCmkiGXb5kRP@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -109,7 +108,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Group Members - Userfields: all- ident: join_5gASJxNKdQCmkiGXb5kRP@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 300diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/613VT_7b325t9FBAJZcU8_question_views_per_month.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/613VT_7b325t9FBAJZcU8_question_views_per_month.yamlindex c7cbcced66d..92b43d9cb38 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/613VT_7b325t9FBAJZcU8_question_views_per_month.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/613VT_7b325t9FBAJZcU8_question_views_per_month.yaml@@ -59,7 +59,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_613VT_7b325t9FBAJZcU8@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -78,7 +77,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_613VT_7b325t9FBAJZcU8@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: P6Ityjj7igswKh4NgZZjzdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/7FLoE9kUELG4Ess6DsSEY_last_downloads.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/7FLoE9kUELG4Ess6DsSEY_last_downloads.yamlindex e09fa9a774a..696ef30871d 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/7FLoE9kUELG4Ess6DsSEY_last_downloads.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/7FLoE9kUELG4Ess6DsSEY_last_downloads.yaml@@ -103,7 +103,6 @@ dataset_query:- entity_id- base-type: type/Integerjoin-alias: Content - Card Qualified- ident: join_7FLoE9kUELG4Ess6DsSEY@0__Content - Card Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Content - Dashboard Qualified@@ -137,7 +136,6 @@ dataset_query:- entity_id- base-type: type/Integerjoin-alias: Content - Dashboard Qualified- ident: join_7FLoE9kUELG4Ess6DsSEY@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Databases - Database Qualified@@ -171,7 +169,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Databases - Database Qualified- ident: join_7FLoE9kUELG4Ess6DsSEY@0__Databases - Database Qualifiedsource-table: -19557ZnrWiDgG4h4cKxFstrategy: left-join- alias: People - User@@ -205,7 +202,6 @@ dataset_query:- full_name- base-type: type/Textjoin-alias: People - User- ident: join_7FLoE9kUELG4Ess6DsSEY@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/95Om4AllyfyB5wtl6TeGi_last_viewed_tables.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/95Om4AllyfyB5wtl6TeGi_last_viewed_tables.yamlindex 6f828567098..52bb07175b7 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/95Om4AllyfyB5wtl6TeGi_last_viewed_tables.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/95Om4AllyfyB5wtl6TeGi_last_viewed_tables.yaml@@ -85,7 +85,6 @@ dataset_query:- database_id- base-type: type/Integerjoin-alias: Tables - Entity Qualified- ident: join_95Om4AllyfyB5wtl6TeGi@0__Tables - Entity Qualifiedsource-table: x7GwgNdjfzrpQkKTraaqostrategy: left-join- alias: People - User@@ -105,7 +104,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Userfields: none- ident: join_95Om4AllyfyB5wtl6TeGi@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Bp2r19P5a9HjDTR4-VuZa_subscriptions_on_this_dashboard.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Bp2r19P5a9HjDTR4-VuZa_subscriptions_on_this_dashboard.yamlindex 1020b928313..c9e8ad1bcdb 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Bp2r19P5a9HjDTR4-VuZa_subscriptions_on_this_dashboard.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Bp2r19P5a9HjDTR4-VuZa_subscriptions_on_this_dashboard.yaml@@ -90,7 +90,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Dashboard Qualifiedfields: none- ident: join_Bp2r19P5a9HjDTR4-VuZa@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -110,7 +109,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Creatorfields: none- ident: join_Bp2r19P5a9HjDTR4-VuZa@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinsource-table: 5ojUtU9iE-DCggHdFPIlldiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DnNyT6EtIn-Zx8bHRFHbV_questions_created_last_week.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DnNyT6EtIn-Zx8bHRFHbV_questions_created_last_week.yamlindex f20c7ac33ff..795d8e2f2f6 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DnNyT6EtIn-Zx8bHRFHbV_questions_created_last_week.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DnNyT6EtIn-Zx8bHRFHbV_questions_created_last_week.yaml@@ -69,7 +69,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - Creator- ident: join_DnNyT6EtIn-Zx8bHRFHbV@0__Group Members - Creatorsource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: AxSackBiyXVRUzM_TyyQYdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DuL1yrlkmnqOgz4drGiG4_users_consuming_most_resources.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DuL1yrlkmnqOgz4drGiG4_users_consuming_most_resources.yamlindex 7779270b45a..d288430f6af 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DuL1yrlkmnqOgz4drGiG4_users_consuming_most_resources.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/DuL1yrlkmnqOgz4drGiG4_users_consuming_most_resources.yaml@@ -89,7 +89,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Userfields: all- ident: join_DuL1yrlkmnqOgz4drGiG4@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -109,7 +108,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Group Members - Userfields: all- ident: join_DuL1yrlkmnqOgz4drGiG4@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/FUuJSuFo7wM6EoddmNsHf_most_active_viewers.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/FUuJSuFo7wM6EoddmNsHf_most_active_viewers.yamlindex 44ae28e42e2..44ab86dd359 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/FUuJSuFo7wM6EoddmNsHf_most_active_viewers.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/FUuJSuFo7wM6EoddmNsHf_most_active_viewers.yaml@@ -65,7 +65,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - User- ident: join_FUuJSuFo7wM6EoddmNsHf@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -84,7 +83,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_FUuJSuFo7wM6EoddmNsHf@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/G7fFejjb7cgwYlUXSvf3K_dashboards_created_last_week.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/G7fFejjb7cgwYlUXSvf3K_dashboards_created_last_week.yamlindex 3ea61a18f34..5a9db309d52 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/G7fFejjb7cgwYlUXSvf3K_dashboards_created_last_week.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/G7fFejjb7cgwYlUXSvf3K_dashboards_created_last_week.yaml@@ -69,7 +69,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - Creator- ident: join_G7fFejjb7cgwYlUXSvf3K@0__Group Members - Creatorsource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: AxSackBiyXVRUzM_TyyQYdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ItdtatOMd0uUEpvx7tDAC_most_viewed_tables.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ItdtatOMd0uUEpvx7tDAC_most_viewed_tables.yamlindex d4cef991fb4..60d466756c4 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ItdtatOMd0uUEpvx7tDAC_most_viewed_tables.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ItdtatOMd0uUEpvx7tDAC_most_viewed_tables.yaml@@ -89,7 +89,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_ItdtatOMd0uUEpvx7tDAC@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: Tables - Entity Qualified@@ -109,7 +108,6 @@ dataset_query:- base-type: type/Textjoin-alias: Tables - Entity Qualifiedfields: all- ident: join_ItdtatOMd0uUEpvx7tDAC@0__Tables - Entity Qualifiedsource-table: x7GwgNdjfzrpQkKTraaqostrategy: left-join- alias: People - User@@ -130,7 +128,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Userfields: all- ident: join_ItdtatOMd0uUEpvx7tDAC@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Databases@@ -151,7 +148,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Databasesfields: all- ident: join_ItdtatOMd0uUEpvx7tDAC@0__Databasessource-table: -19557ZnrWiDgG4h4cKxFstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/JPERH6xYVcj3m2Zw0YVY1_active_alerts.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/JPERH6xYVcj3m2Zw0YVY1_active_alerts.yamlindex d9a79a45dee..d2109a37b90 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/JPERH6xYVcj3m2Zw0YVY1_active_alerts.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/JPERH6xYVcj3m2Zw0YVY1_active_alerts.yaml@@ -52,7 +52,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Creatorfields: none- ident: join_JPERH6xYVcj3m2Zw0YVY1@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinsource-table: skoPT2xiuEcUV8vFkHE6Sdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/KXNGLyYyS1pO_9wMguHIB_total_time_spent_on_sync_per_day.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/KXNGLyYyS1pO_9wMguHIB_total_time_spent_on_sync_per_day.yamlindex f62af7ba0ef..968eba7cdf7 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/KXNGLyYyS1pO_9wMguHIB_total_time_spent_on_sync_per_day.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/KXNGLyYyS1pO_9wMguHIB_total_time_spent_on_sync_per_day.yaml@@ -81,7 +81,6 @@ dataset_query:- base-type: type/Textjoin-alias: Databases - Database Qualifiedfields: all- ident: join_KXNGLyYyS1pO_9wMguHIB@0__Databases - Database Qualifiedsource-table: -19557ZnrWiDgG4h4cKxFstrategy: left-joinsource-table: PKhlEfegdbTozSMfj0aLB@@ -108,7 +107,6 @@ result_metadata:- public- v_tasks- started_at- ident: fDxH2yqCHnftKx3IkW8raname: started_atnfc_path: nullparent_id: null@@ -144,7 +142,6 @@ result_metadata:- public- v_databases- name- ident: LMqtaUMyPJJMZqYYeSRbsname: namenfc_path: nullparent_id: null@@ -163,7 +160,6 @@ result_metadata:field_ref:- aggregation- 0- ident: aggregation_KXNGLyYyS1pO_9wMguHIB@0__0name: sumsemantic_type: type/Quantitysettings: nulldiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/LN9YtKcxZk_kybyRjJx1J_total_time_looking_for_field_values_per_day.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/LN9YtKcxZk_kybyRjJx1J_total_time_looking_for_field_values_per_day.yamlindex 1c1b399eed5..b605cd71c95 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/LN9YtKcxZk_kybyRjJx1J_total_time_looking_for_field_values_per_day.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/LN9YtKcxZk_kybyRjJx1J_total_time_looking_for_field_values_per_day.yaml@@ -82,7 +82,6 @@ dataset_query:- base-type: type/Textjoin-alias: Databases - Database Qualifiedfields: all- ident: join_LN9YtKcxZk_kybyRjJx1J@0__Databases - Database Qualifiedsource-table: -19557ZnrWiDgG4h4cKxFstrategy: left-joinsource-table: PKhlEfegdbTozSMfj0aLB@@ -109,7 +108,6 @@ result_metadata:- public- v_tasks- started_at- ident: fDxH2yqCHnftKx3IkW8raname: started_atnfc_path: nullparent_id: null@@ -145,7 +143,6 @@ result_metadata:- public- v_databases- name- ident: LMqtaUMyPJJMZqYYeSRbsname: namenfc_path: nullparent_id: null@@ -164,7 +161,6 @@ result_metadata:field_ref:- aggregation- 0- ident: aggregation_LN9YtKcxZk_kybyRjJx1J@0__0name: sumsemantic_type: type/Quantitysettings: nulldiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MOAq881VSlM2BhVUv5e_K_last_activity_on_question.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MOAq881VSlM2BhVUv5e_K_last_activity_on_question.yamlindex 7e75be57e6b..1726fc2e114 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MOAq881VSlM2BhVUv5e_K_last_activity_on_question.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MOAq881VSlM2BhVUv5e_K_last_activity_on_question.yaml@@ -72,7 +72,6 @@ dataset_query:- full_name- base-type: type/Textjoin-alias: People - User- ident: join_MOAq881VSlM2BhVUv5e_K@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Content - Entity Qualified@@ -92,7 +91,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Entity Qualifiedfields: none- ident: join_MOAq881VSlM2BhVUv5e_K@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MUXrck2HHcd2TIRuPfK0v_most_viewed_dashboards.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MUXrck2HHcd2TIRuPfK0v_most_viewed_dashboards.yamlindex fe9394edbd2..602f787e077 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MUXrck2HHcd2TIRuPfK0v_most_viewed_dashboards.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/MUXrck2HHcd2TIRuPfK0v_most_viewed_dashboards.yaml@@ -66,7 +66,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_MUXrck2HHcd2TIRuPfK0v@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -82,7 +81,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join_MUXrck2HHcd2TIRuPfK0v@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -101,7 +99,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_MUXrck2HHcd2TIRuPfK0v@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/OCkxXZM5KPJ9zOjYVEnqY_slowest_questions.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/OCkxXZM5KPJ9zOjYVEnqY_slowest_questions.yamlindex 5c5f619280e..8ecd0689849 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/OCkxXZM5KPJ9zOjYVEnqY_slowest_questions.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/OCkxXZM5KPJ9zOjYVEnqY_slowest_questions.yaml@@ -90,7 +90,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Dashboard Qualifiedfields: all- ident: join_OCkxXZM5KPJ9zOjYVEnqY@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - Entity@@ -110,7 +109,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Group Members - Entityfields: all- ident: join_OCkxXZM5KPJ9zOjYVEnqY@0__Group Members - Entitysource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/PKBMfv3loa7C8ksiUmBjj_most_viewed_tables.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/PKBMfv3loa7C8ksiUmBjj_most_viewed_tables.yamlindex 1634053a8ad..0ec90a0112f 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/PKBMfv3loa7C8ksiUmBjj_most_viewed_tables.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/PKBMfv3loa7C8ksiUmBjj_most_viewed_tables.yaml@@ -89,7 +89,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_ItdtatOMd0uUEpvx7tDAC@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: Tables - Entity Qualified@@ -109,7 +108,6 @@ dataset_query:- base-type: type/Textjoin-alias: Tables - Entity Qualifiedfields: all- ident: join_ItdtatOMd0uUEpvx7tDAC@0__Tables - Entity Qualifiedsource-table: x7GwgNdjfzrpQkKTraaqostrategy: left-join- alias: People - User@@ -130,7 +128,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Userfields: all- ident: join_ItdtatOMd0uUEpvx7tDAC@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Databases@@ -151,7 +148,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Databasesfields: all- ident: join_ItdtatOMd0uUEpvx7tDAC@0__Databasessource-table: -19557ZnrWiDgG4h4cKxFstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/T1vsVJUAfg30Fqiw4Dywa_most_viewed_cards.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/T1vsVJUAfg30Fqiw4Dywa_most_viewed_cards.yamlindex cc64bc382f6..8714e1b8938 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/T1vsVJUAfg30Fqiw4Dywa_most_viewed_cards.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/T1vsVJUAfg30Fqiw4Dywa_most_viewed_cards.yaml@@ -65,7 +65,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_T1vsVJUAfg30Fqiw4Dywa@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: Content - Entity Qualified@@ -84,7 +83,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_T1vsVJUAfg30Fqiw4Dywa@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/U0oXxoLi9Ouy2V6ChvdSU_most_viewed_models.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/U0oXxoLi9Ouy2V6ChvdSU_most_viewed_models.yamlindex d307b7eb385..c891fadef90 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/U0oXxoLi9Ouy2V6ChvdSU_most_viewed_models.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/U0oXxoLi9Ouy2V6ChvdSU_most_viewed_models.yaml@@ -90,7 +90,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_57V11my5MYVnSlaJYM8cX@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -106,7 +105,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join_57V11my5MYVnSlaJYM8cX@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -125,7 +123,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_57V11my5MYVnSlaJYM8cX@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: V Databases - Question Database@@ -146,7 +143,6 @@ dataset_query:- base-type: type/Textjoin-alias: V Databases - Question Databasefields: all- ident: join_57V11my5MYVnSlaJYM8cX@0__V Databases - Question Databasesource-table:- Internal Metabase Database- publicdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/UEK1JfYa3ZBp6W7F-Ui5i_questions_without_recent_views.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/UEK1JfYa3ZBp6W7F-Ui5i_questions_without_recent_views.yamlindex 02bbc9cf728..0d4ab09babd 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/UEK1JfYa3ZBp6W7F-Ui5i_questions_without_recent_views.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/UEK1JfYa3ZBp6W7F-Ui5i_questions_without_recent_views.yaml@@ -94,7 +94,6 @@ dataset_query:- base-type: type/Textjoin-alias: Last content viewed at - Entity Qualifiedfields: none- ident: join_UEK1JfYa3ZBp6W7F-Ui5i@0__Last content viewed at - Entity Qualifiedsource-table: tKEl86EXMyTDIoO9nyFTVstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Vm-4GYORvVbGu9jHVLfg1_question_views_per_month.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Vm-4GYORvVbGu9jHVLfg1_question_views_per_month.yamlindex 0581c845593..4a64a1a2b3f 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Vm-4GYORvVbGu9jHVLfg1_question_views_per_month.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Vm-4GYORvVbGu9jHVLfg1_question_views_per_month.yaml@@ -59,7 +59,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - User- ident: join_Vm-4GYORvVbGu9jHVLfg1@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinsource-table: P6Ityjj7igswKh4NgZZjzdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/W34-Nzp-T3-SPdZwGvLeB_dashboard_metadata.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/W34-Nzp-T3-SPdZwGvLeB_dashboard_metadata.yamlindex bfd47626c70..100170df03f 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/W34-Nzp-T3-SPdZwGvLeB_dashboard_metadata.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/W34-Nzp-T3-SPdZwGvLeB_dashboard_metadata.yaml@@ -85,7 +85,10 @@ dataset_query:- archived- base-type: type/Boolean- - field- - is_verified+ - - Internal Metabase Database+ - public+ - v_content+ - is_verified- base-type: type/Booleanfilter:- =@@ -119,7 +122,6 @@ result_metadata:- public- v_content- entity_id- ident: zGxQI3k8rDbAWi4SoRBGuname: entity_idnfc_path: nullparent_id: null@@ -152,7 +154,6 @@ result_metadata:- public- v_content- entity_type- ident: o9TWAM8W0uC0FHnU3AcLoname: entity_typenfc_path: nullparent_id: null@@ -185,7 +186,6 @@ result_metadata:- public- v_content- created_at- ident: --a2aeEMqkwMXZ49EKy4qname: created_atnfc_path: nullparent_id: null@@ -218,7 +218,6 @@ result_metadata:- public- v_content- updated_at- ident: k438QMrN8DFML_jR7KnLvname: updated_atnfc_path: nullparent_id: null@@ -255,7 +254,6 @@ result_metadata:- public- v_content- creator_id- ident: f5H6w2a4ITi_hlKmuP3FPname: creator_idnfc_path: nullparent_id: null@@ -288,7 +286,6 @@ result_metadata:- public- v_content- name- ident: AnRJOSa547uepcAA8CXo7name: namenfc_path: nullparent_id: null@@ -321,7 +318,6 @@ result_metadata:- public- v_content- description- ident: fObSJJXa6tpZixX7suslCname: descriptionnfc_path: nullparent_id: null@@ -358,7 +354,6 @@ result_metadata:- public- v_content- made_public_by_user- ident: tKeCGsaHNfsvhR7TgJaTSname: made_public_by_usernfc_path: nullparent_id: null@@ -391,7 +386,6 @@ result_metadata:- public- v_content- is_embedding_enabled- ident: JxSFL9umxv4k15F_lXujQname: is_embedding_enablednfc_path: nullparent_id: null@@ -424,7 +418,6 @@ result_metadata:- public- v_content- archived- ident: hWP3d0NYZMx8Pl1f4MNrTname: archivednfc_path: nullparent_id: null@@ -444,14 +437,16 @@ result_metadata:effective_type: type/Booleanfield_ref:- field- - is_verified+ - - Internal Metabase Database+ - public+ - v_content+ - is_verified- base-type: type/Booleanid:- Internal Metabase Database- public- v_content- is_verified- ident: nMn0fuAsRSV4lDuA2NwDvname: is_verifiedposition: 11semantic_type: type/Categorydiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/WlQ-en2l-iRRCvO2-v5j1_recent_activity.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/WlQ-en2l-iRRCvO2-v5j1_recent_activity.yamlindex 855560e750b..1efe3b71d3f 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/WlQ-en2l-iRRCvO2-v5j1_recent_activity.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/WlQ-en2l-iRRCvO2-v5j1_recent_activity.yaml@@ -66,7 +66,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Userfields: none- ident: join_WlQ-en2l-iRRCvO2-v5j1@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Content - Entity Qualified@@ -107,7 +106,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_WlQ-en2l-iRRCvO2-v5j1@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XIiIsCNMk9gg-eO2hkl8S_dashboard_views_per_month.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XIiIsCNMk9gg-eO2hkl8S_dashboard_views_per_month.yamlindex 3cbcf3a05a0..c3928294d7e 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XIiIsCNMk9gg-eO2hkl8S_dashboard_views_per_month.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XIiIsCNMk9gg-eO2hkl8S_dashboard_views_per_month.yaml@@ -59,7 +59,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_XIiIsCNMk9gg-eO2hkl8S@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -78,7 +77,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_XIiIsCNMk9gg-eO2hkl8S@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: P6Ityjj7igswKh4NgZZjzdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XLzhOnMmk3DkefFAMx_Vg_question_metadata.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XLzhOnMmk3DkefFAMx_Vg_question_metadata.yamlindex 2b5bc234561..6c0cdcb3489 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XLzhOnMmk3DkefFAMx_Vg_question_metadata.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/XLzhOnMmk3DkefFAMx_Vg_question_metadata.yaml@@ -85,7 +85,10 @@ dataset_query:- archived- base-type: type/Boolean- - field- - is_verified+ - - Internal Metabase Database+ - public+ - v_content+ - is_verified- base-type: type/Booleanfilter:- =@@ -119,7 +122,6 @@ result_metadata:- public- v_content- entity_id- ident: zGxQI3k8rDbAWi4SoRBGuname: entity_idnfc_path: nullparent_id: null@@ -152,7 +154,6 @@ result_metadata:- public- v_content- entity_type- ident: o9TWAM8W0uC0FHnU3AcLoname: entity_typenfc_path: nullparent_id: null@@ -185,7 +186,6 @@ result_metadata:- public- v_content- created_at- ident: --a2aeEMqkwMXZ49EKy4qname: created_atnfc_path: nullparent_id: null@@ -218,7 +218,6 @@ result_metadata:- public- v_content- updated_at- ident: k438QMrN8DFML_jR7KnLvname: updated_atnfc_path: nullparent_id: null@@ -255,7 +254,6 @@ result_metadata:- public- v_content- creator_id- ident: f5H6w2a4ITi_hlKmuP3FPname: creator_idnfc_path: nullparent_id: null@@ -288,7 +286,6 @@ result_metadata:- public- v_content- name- ident: AnRJOSa547uepcAA8CXo7name: namenfc_path: nullparent_id: null@@ -321,7 +318,6 @@ result_metadata:- public- v_content- description- ident: fObSJJXa6tpZixX7suslCname: descriptionnfc_path: nullparent_id: null@@ -358,7 +354,6 @@ result_metadata:- public- v_content- made_public_by_user- ident: tKeCGsaHNfsvhR7TgJaTSname: made_public_by_usernfc_path: nullparent_id: null@@ -391,7 +386,6 @@ result_metadata:- public- v_content- is_embedding_enabled- ident: JxSFL9umxv4k15F_lXujQname: is_embedding_enablednfc_path: nullparent_id: null@@ -424,7 +418,6 @@ result_metadata:- public- v_content- archived- ident: hWP3d0NYZMx8Pl1f4MNrTname: archivednfc_path: nullparent_id: null@@ -444,14 +437,16 @@ result_metadata:effective_type: type/Booleanfield_ref:- field- - is_verified+ - - Internal Metabase Database+ - public+ - v_content+ - is_verified- base-type: type/Booleanid:- Internal Metabase Database- public- v_content- is_verified- ident: nMn0fuAsRSV4lDuA2NwDvname: is_verifiedposition: 11semantic_type: type/Categorydiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YiHMsA2dv3iQob11DLTIz_alerts_on_this_question.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YiHMsA2dv3iQob11DLTIz_alerts_on_this_question.yamlindex e6d812cae96..4b72810d61b 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YiHMsA2dv3iQob11DLTIz_alerts_on_this_question.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YiHMsA2dv3iQob11DLTIz_alerts_on_this_question.yaml@@ -105,7 +105,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Card Qualifiedfields: none- ident: join_YiHMsA2dv3iQob11DLTIz@0__Content - Card Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -125,7 +124,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Creatorfields: none- ident: join_YiHMsA2dv3iQob11DLTIz@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinsource-table: skoPT2xiuEcUV8vFkHE6Sdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YxCC6fQfHOPVvBtUkjFCN_questions_that_don_t_belong_to_a_dashboard.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YxCC6fQfHOPVvBtUkjFCN_questions_that_don_t_belong_to_a_dashboard.yamlindex 8196f958c4e..6dbcce1a214 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YxCC6fQfHOPVvBtUkjFCN_questions_that_don_t_belong_to_a_dashboard.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/YxCC6fQfHOPVvBtUkjFCN_questions_that_don_t_belong_to_a_dashboard.yaml@@ -100,7 +100,6 @@ dataset_query:- base-type: type/Textjoin-alias: Last content viewed at - Entity Qualifiedfields: none- ident: join_YxCC6fQfHOPVvBtUkjFCN@0__Last content viewed at - Entity Qualifiedsource-table: tKEl86EXMyTDIoO9nyFTVstrategy: left-join- alias: Dashboard cards - Entity Qualified@@ -120,7 +119,6 @@ dataset_query:- base-type: type/Textjoin-alias: Dashboard cards - Entity Qualifiedfields: none- ident: join_YxCC6fQfHOPVvBtUkjFCN@0__Dashboard cards - Entity Qualifiedsource-table: pKdvc0pwu1zDi8NqnyJktstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Z18i0B5CgOe66-YScAZdx_questions_created_per_month.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Z18i0B5CgOe66-YScAZdx_questions_created_per_month.yamlindex dbef94f3790..20a008f3605 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Z18i0B5CgOe66-YScAZdx_questions_created_per_month.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/Z18i0B5CgOe66-YScAZdx_questions_created_per_month.yaml@@ -58,7 +58,6 @@ dataset_query:- user_id- join-alias: Question 1fields: all- ident: join_Z18i0B5CgOe66-YScAZdx@0__Question 1source-table: 0wVIfjBJWclD0lKeABYYlsource-table: -lNDM3tJmuL5ltGbX0oyTtype: querydiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_lfXwss_MckZBidbcJsgk_most_viewed_questions.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_lfXwss_MckZBidbcJsgk_most_viewed_questions.yamlindex 0e33792eb7a..bd328406433 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_lfXwss_MckZBidbcJsgk_most_viewed_questions.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_lfXwss_MckZBidbcJsgk_most_viewed_questions.yaml@@ -76,7 +76,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join__lfXwss_MckZBidbcJsgk@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -92,7 +91,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join__lfXwss_MckZBidbcJsgk@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -111,7 +109,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join__lfXwss_MckZBidbcJsgk@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_p6UGMWOQn5-yf03uGsaN_most_active_people_on_this_dashboard.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_p6UGMWOQn5-yf03uGsaN_most_active_people_on_this_dashboard.yamlindex 0da91304548..e711da0d427 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_p6UGMWOQn5-yf03uGsaN_most_active_people_on_this_dashboard.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/_p6UGMWOQn5-yf03uGsaN_most_active_people_on_this_dashboard.yaml@@ -65,7 +65,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join__p6UGMWOQn5-yf03uGsaN@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -84,7 +83,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join__p6UGMWOQn5-yf03uGsaN@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: People - Creator@@ -103,7 +101,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join__p6UGMWOQn5-yf03uGsaN@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ezcT88-OmH-5HFOFNqmX7_last_viewed_questions.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ezcT88-OmH-5HFOFNqmX7_last_viewed_questions.yamlindex 9a372fbef66..893835df6f3 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ezcT88-OmH-5HFOFNqmX7_last_viewed_questions.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ezcT88-OmH-5HFOFNqmX7_last_viewed_questions.yaml@@ -88,7 +88,6 @@ dataset_query:- description- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_ezcT88-OmH-5HFOFNqmX7@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -105,7 +104,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Creatorfields: none- ident: join_ezcT88-OmH-5HFOFNqmX7@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fBr2cU-86t14YWbaS3r6-_most_viewed_dashboards.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fBr2cU-86t14YWbaS3r6-_most_viewed_dashboards.yamlindex de003540c45..f5671a32e2f 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fBr2cU-86t14YWbaS3r6-_most_viewed_dashboards.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fBr2cU-86t14YWbaS3r6-_most_viewed_dashboards.yaml@@ -65,7 +65,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_fBr2cU-86t14YWbaS3r6-@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: Content - Entity Qualified@@ -84,7 +83,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_fBr2cU-86t14YWbaS3r6-@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fwkC3nWB_uouifA5kkaBp_alerts.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fwkC3nWB_uouifA5kkaBp_alerts.yamlindex 8d9d8be1b3d..21efecf7aac 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fwkC3nWB_uouifA5kkaBp_alerts.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/fwkC3nWB_uouifA5kkaBp_alerts.yaml@@ -85,7 +85,6 @@ dataset_query:- full_name- base-type: type/Textjoin-alias: People - Creator- ident: join_fwkC3nWB_uouifA5kkaBp@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYl- alias: Content - Card Qualifiedcondition:@@ -108,7 +107,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Content - Card Qualified- ident: join_fwkC3nWB_uouifA5kkaBp@0__Content - Card Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYsource-table: skoPT2xiuEcUV8vFkHE6Stype: querydiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/g-99yx3A8bwFtrfuWdIgb_active_dashboard_subscriptions.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/g-99yx3A8bwFtrfuWdIgb_active_dashboard_subscriptions.yamlindex fc6a1eb7888..82557742ede 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/g-99yx3A8bwFtrfuWdIgb_active_dashboard_subscriptions.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/g-99yx3A8bwFtrfuWdIgb_active_dashboard_subscriptions.yaml@@ -82,7 +82,6 @@ dataset_query:- full_name- base-type: type/Textjoin-alias: People - Creator- ident: join_g-99yx3A8bwFtrfuWdIgb@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYl- alias: Content - Entity Qualifiedcondition:@@ -112,7 +111,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_g-99yx3A8bwFtrfuWdIgb@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYsource-table: 5ojUtU9iE-DCggHdFPIlltype: querydiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gTeYI2eJtQUh63sZurc3z_last_queries.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gTeYI2eJtQUh63sZurc3z_last_queries.yamlindex b588522bb4e..784219fd4fe 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gTeYI2eJtQUh63sZurc3z_last_queries.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gTeYI2eJtQUh63sZurc3z_last_queries.yaml@@ -92,7 +92,6 @@ dataset_query:- entity_id- base-type: type/Integerjoin-alias: Content - Card Qualified- ident: join_gTeYI2eJtQUh63sZurc3z@0__Content - Card Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Content - Dashboard Qualified@@ -126,7 +125,6 @@ dataset_query:- entity_id- base-type: type/Integerjoin-alias: Content - Dashboard Qualified- ident: join_gTeYI2eJtQUh63sZurc3z@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Databases - Database Qualified@@ -160,7 +158,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Databases - Database Qualified- ident: join_gTeYI2eJtQUh63sZurc3z@0__Databases - Database Qualifiedsource-table: -19557ZnrWiDgG4h4cKxFstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gYt6bo9DFKz6tSeDLxYVs_active_users_last_week.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gYt6bo9DFKz6tSeDLxYVs_active_users_last_week.yamlindex b3517f3a921..a2604415670 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gYt6bo9DFKz6tSeDLxYVs_active_users_last_week.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/gYt6bo9DFKz6tSeDLxYVs_active_users_last_week.yaml@@ -67,7 +67,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_gYt6bo9DFKz6tSeDLxYVs@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: P6Ityjj7igswKh4NgZZjzdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/j5X79-yP1N3FeZSPlbGgw_last_downloads.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/j5X79-yP1N3FeZSPlbGgw_last_downloads.yamlindex e7b0ff70e3e..c6fce40ffb4 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/j5X79-yP1N3FeZSPlbGgw_last_downloads.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/j5X79-yP1N3FeZSPlbGgw_last_downloads.yaml@@ -103,7 +103,6 @@ dataset_query:- entity_id- base-type: type/Integerjoin-alias: Content - Card Qualified- ident: join_7FLoE9kUELG4Ess6DsSEY@0__Content - Card Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Content - Dashboard Qualified@@ -137,7 +136,6 @@ dataset_query:- entity_id- base-type: type/Integerjoin-alias: Content - Dashboard Qualified- ident: join_7FLoE9kUELG4Ess6DsSEY@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Databases - Database Qualified@@ -171,7 +169,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Databases - Database Qualified- ident: join_7FLoE9kUELG4Ess6DsSEY@0__Databases - Database Qualifiedsource-table: -19557ZnrWiDgG4h4cKxFstrategy: left-join- alias: People - User@@ -205,7 +202,6 @@ dataset_query:- full_name- base-type: type/Textjoin-alias: People - User- ident: join_7FLoE9kUELG4Ess6DsSEY@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/kd1-A_wWOvlSuLDTFUpyb_question_views_per_week.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/kd1-A_wWOvlSuLDTFUpyb_question_views_per_week.yamlindex 22a458e117a..cd9877fda11 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/kd1-A_wWOvlSuLDTFUpyb_question_views_per_week.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/kd1-A_wWOvlSuLDTFUpyb_question_views_per_week.yaml@@ -66,7 +66,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_kd1-A_wWOvlSuLDTFUpyb@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: P6Ityjj7igswKh4NgZZjzdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/mm8k37Rgk7ChMNwAUdXK2_slowest_dashboards.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/mm8k37Rgk7ChMNwAUdXK2_slowest_dashboards.yamlindex 0a4db3a9a65..c1163809963 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/mm8k37Rgk7ChMNwAUdXK2_slowest_dashboards.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/mm8k37Rgk7ChMNwAUdXK2_slowest_dashboards.yaml@@ -89,7 +89,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Dashboard Qualifiedfields: all- ident: join_mm8k37Rgk7ChMNwAUdXK2@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -109,7 +108,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Group Members - Userfields: all- ident: join_mm8k37Rgk7ChMNwAUdXK2@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 300diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p-z74CSp1IOs1rXwAcwcS_most_active_creators.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p-z74CSp1IOs1rXwAcwcS_most_active_creators.yamlindex d043087a95a..4c5dbe7e692 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p-z74CSp1IOs1rXwAcwcS_most_active_creators.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p-z74CSp1IOs1rXwAcwcS_most_active_creators.yaml@@ -65,7 +65,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_p-z74CSp1IOs1rXwAcwcS@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: People - User@@ -82,7 +81,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - User- ident: join_p-z74CSp1IOs1rXwAcwcS@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p8ZML2ebd3ItzCyWsKXLa_weekly_active_users.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p8ZML2ebd3ItzCyWsKXLa_weekly_active_users.yamlindex af087a6eb7f..489b27df815 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p8ZML2ebd3ItzCyWsKXLa_weekly_active_users.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/p8ZML2ebd3ItzCyWsKXLa_weekly_active_users.yaml@@ -63,7 +63,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_p8ZML2ebd3ItzCyWsKXLa@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: P6Ityjj7igswKh4NgZZjzdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/r8r6O1VedjAjSD2MPxJs6_dashboards_with_more_questions_in_the_same_tab.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/r8r6O1VedjAjSD2MPxJs6_dashboards_with_more_questions_in_the_same_tab.yamlindex 6b59fed8337..e4dcb70ae22 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/r8r6O1VedjAjSD2MPxJs6_dashboards_with_more_questions_in_the_same_tab.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/r8r6O1VedjAjSD2MPxJs6_dashboards_with_more_questions_in_the_same_tab.yaml@@ -72,7 +72,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Dashboard Qualifiedfields: all- ident: join_r8r6O1VedjAjSD2MPxJs6@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/t-4MnpU-Nn7Ph9GQT6zYb_question_views_last_week.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/t-4MnpU-Nn7Ph9GQT6zYb_question_views_last_week.yamlindex bdcf933a0dd..3428a73d206 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/t-4MnpU-Nn7Ph9GQT6zYb_question_views_last_week.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/t-4MnpU-Nn7Ph9GQT6zYb_question_views_last_week.yaml@@ -70,7 +70,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_t-4MnpU-Nn7Ph9GQT6zYb@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: P6Ityjj7igswKh4NgZZjzdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/tKEl86EXMyTDIoO9nyFTV_last_content_viewed_at.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/tKEl86EXMyTDIoO9nyFTV_last_content_viewed_at.yamlindex 591cfab6938..060eb1096d9 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/tKEl86EXMyTDIoO9nyFTV_last_content_viewed_at.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/tKEl86EXMyTDIoO9nyFTV_last_content_viewed_at.yaml@@ -57,7 +57,6 @@ result_metadata:- public- v_view_log- entity_qualified_id- ident: field__audit_development_app_db__public__v_view_log__entity_qualified_idname: entity_qualified_idposition: 5semantic_type: type/FK@@ -72,7 +71,6 @@ result_metadata:field_ref:- aggregation- 0- ident: nullname: maxsemantic_type: type/CreationTimestampsource: aggregationdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vrez-ciNppijhELOxLJOY_dashboards_with_this_question.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vrez-ciNppijhELOxLJOY_dashboards_with_this_question.yamlindex 765d678332a..75728d1908f 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vrez-ciNppijhELOxLJOY_dashboards_with_this_question.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vrez-ciNppijhELOxLJOY_dashboards_with_this_question.yaml@@ -48,7 +48,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Card Qualifiedfields: none- ident: join_vrez-ciNppijhELOxLJOY@0__Content - Card Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Content - Dashboard Qualified@@ -82,7 +81,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Content - Dashboard Qualified- ident: join_vrez-ciNppijhELOxLJOY@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vuuqdK3FPwe4lH4SHHtM6_most_viewed_dashboards.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vuuqdK3FPwe4lH4SHHtM6_most_viewed_dashboards.yamlindex 202f4659ce8..d896f93cc80 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vuuqdK3FPwe4lH4SHHtM6_most_viewed_dashboards.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/vuuqdK3FPwe4lH4SHHtM6_most_viewed_dashboards.yaml@@ -66,7 +66,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_MUXrck2HHcd2TIRuPfK0v@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -82,7 +81,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join_MUXrck2HHcd2TIRuPfK0v@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -101,7 +99,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_MUXrck2HHcd2TIRuPfK0v@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 100diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/xrgv7nzXe_v8ORWIbq839_recent_activity_on_dashboard.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/xrgv7nzXe_v8ORWIbq839_recent_activity_on_dashboard.yamlindex 99b3834e8c7..48f84ce7e97 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/xrgv7nzXe_v8ORWIbq839_recent_activity_on_dashboard.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/xrgv7nzXe_v8ORWIbq839_recent_activity_on_dashboard.yaml@@ -73,7 +73,6 @@ dataset_query:- full_name- base-type: type/Textjoin-alias: People - User- ident: join_xrgv7nzXe_v8ORWIbq839@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Content - Entity Qualified@@ -93,7 +92,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Entity Qualifiedfields: none- ident: join_xrgv7nzXe_v8ORWIbq839@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -113,7 +111,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Group Members - Userfields: none- ident: join_xrgv7nzXe_v8ORWIbq839@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/y-_5bBl0fXY9XlEbpJkrj_most_active_people_on_this_question.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/y-_5bBl0fXY9XlEbpJkrj_most_active_people_on_this_question.yamlindex 04a355e38d4..5a17e1a225a 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/y-_5bBl0fXY9XlEbpJkrj_most_active_people_on_this_question.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/y-_5bBl0fXY9XlEbpJkrj_most_active_people_on_this_question.yaml@@ -65,7 +65,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join_y-_5bBl0fXY9XlEbpJkrj@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -84,7 +83,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join_y-_5bBl0fXY9XlEbpJkrj@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-join- alias: People - Creator@@ -103,7 +101,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join_y-_5bBl0fXY9XlEbpJkrj@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/yVr4oMzxq8BPWf5HLbdwL_questions_in_this_dashboard.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/yVr4oMzxq8BPWf5HLbdwL_questions_in_this_dashboard.yamlindex 8b7ce812704..e3f1f2f3464 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/yVr4oMzxq8BPWf5HLbdwL_questions_in_this_dashboard.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/yVr4oMzxq8BPWf5HLbdwL_questions_in_this_dashboard.yaml@@ -68,7 +68,6 @@ dataset_query:- name- base-type: type/Textjoin-alias: Content - Card Qualified- ident: join_yVr4oMzxq8BPWf5HLbdwL@0__Content - Card Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Content - Dashboard Qualified@@ -88,7 +87,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Dashboard Qualifiedfields: none- ident: join_yVr4oMzxq8BPWf5HLbdwL@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-joinorder-by:diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ybsNZp-876qEMoA1U51dc_alerts_and_subscriptions_created_last_week.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ybsNZp-876qEMoA1U51dc_alerts_and_subscriptions_created_last_week.yamlindex 9e69288e4b2..2ab01af1ee1 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ybsNZp-876qEMoA1U51dc_alerts_and_subscriptions_created_last_week.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/ybsNZp-876qEMoA1U51dc_alerts_and_subscriptions_created_last_week.yaml@@ -50,7 +50,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - Creator- ident: join_ybsNZp-876qEMoA1U51dc@0__Group Members - Creatorsource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinsource-table: 5ojUtU9iE-DCggHdFPIlldiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zdVQGoMs__No_3l_amEWV_questions_consuming_most_resources.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zdVQGoMs__No_3l_amEWV_questions_consuming_most_resources.yamlindex fa38fda1fae..82f80158b0b 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zdVQGoMs__No_3l_amEWV_questions_consuming_most_resources.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zdVQGoMs__No_3l_amEWV_questions_consuming_most_resources.yaml@@ -90,7 +90,6 @@ dataset_query:- base-type: type/Textjoin-alias: Content - Dashboard Qualifiedfields: all- ident: join_zdVQGoMs__No_3l_amEWV@0__Content - Dashboard Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: Group Members - User@@ -110,7 +109,6 @@ dataset_query:- base-type: type/Integerjoin-alias: Group Members - Userfields: all- ident: join_zdVQGoMs__No_3l_amEWV@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 200diff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zn_VtBXm5-teZmXpwGcNu_member_of.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zn_VtBXm5-teZmXpwGcNu_member_of.yamlindex 806a6636608..c6fd0032be1 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zn_VtBXm5-teZmXpwGcNu_member_of.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zn_VtBXm5-teZmXpwGcNu_member_of.yaml@@ -54,7 +54,6 @@ dataset_query:- base-type: type/Integerjoin-alias: People - Userfields: none- ident: join_zn_VtBXm5-teZmXpwGcNu@0__People - Usersource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-joinsource-table: lTp-ATFsCUFEr9I0fMEaOdiff --git a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zxl41beCP2NFbTTnc3lZt_most_viewed_questions.yaml b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zxl41beCP2NFbTTnc3lZt_most_viewed_questions.yamlindex e59887ac1a1..9ff2c8348a5 100644--- a/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zxl41beCP2NFbTTnc3lZt_most_viewed_questions.yaml+++ b/resources/instance_analytics/collections/vG58R8k-QddHWA7_47umn_usage_analytics/cards/zxl41beCP2NFbTTnc3lZt_most_viewed_questions.yaml@@ -76,7 +76,6 @@ dataset_query:- entity_qualified_id- base-type: type/Textjoin-alias: Content - Entity Qualified- ident: join__lfXwss_MckZBidbcJsgk@0__Content - Entity Qualifiedsource-table: AxSackBiyXVRUzM_TyyQYstrategy: left-join- alias: People - Creator@@ -92,7 +91,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: People - Creator- ident: join__lfXwss_MckZBidbcJsgk@0__People - Creatorsource-table: 0wVIfjBJWclD0lKeABYYlstrategy: left-join- alias: Group Members - User@@ -111,7 +109,6 @@ dataset_query:- user_id- base-type: type/Integerjoin-alias: Group Members - User- ident: join__lfXwss_MckZBidbcJsgk@0__Group Members - Usersource-table: lTp-ATFsCUFEr9I0fMEaOstrategy: left-joinlimit: 100diff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex 0b58f85509e..21874260300 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -206,7 +206,7 @@:when table-id][table-id card]))tables (when-let [table-ids (seq (keys card-by-table-id))]- (t2/hydrate (t2/select 'Table :id [:in table-ids]) :fields))]+ (t2/hydrate (t2/select :model/Table :id [:in table-ids]) :fields))](into {}(for [table tables:let [fields (:fields table)]@@ -231,6 +231,8 @@{:id (u/slugify (:name field)):display-name (:display_name field):target [:variable [:template-tag (u/slugify (:name field))]]+ ;; TODO (Cam 8/12/25) -- Field base type is NOT a valid parameter types!+ ;; See [[metabase.lib.schema.parameter/types]].:type (:base_type field):required (:database_required field):is-auto-increment (:database_is_auto_increment field)diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.cljindex d884b371317..2b4f8922d7b 100644--- a/src/metabase/driver/sql/query_processor.clj+++ b/src/metabase/driver/sql/query_processor.clj@@ -20,13 +20,7 @@[metabase.util.malli :as mu][toucan2.pipeline :as t2.pipeline])(:import- (java.time- LocalDate- LocalDateTime- LocalTime- OffsetDateTime- OffsetTime- ZonedDateTime)+ (java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)(java.util UUID)))(set! *warn-on-reflection* true)@@ -1747,7 +1741,7 @@:hierarchy #'driver/hierarchy)(defmethod join-source :sql- [driver {:keys [source-table source-query]}]+ [driver {:keys [source-table source-query], :as _join}](cond(and source-query (:native source-query))(sql-source-query (:native source-query) (:params source-query))@@ -1907,7 +1901,8 @@;; Honey SQL 2 = [expr [alias]](first (second from))from)- [raw-identifier] (format-honeysql driver table-identifier)+ [raw-identifier] (when table-identifier+ (format-honeysql driver table-identifier))expr (if (seq raw-identifier)[:raw (format "%s.*" raw-identifier)]:*)]diff --git a/src/metabase/driver/sql/query_processor/boolean_to_comparison.clj b/src/metabase/driver/sql/query_processor/boolean_to_comparison.cljindex c81dae3f7e5..a2275ebb5bb 100644--- a/src/metabase/driver/sql/query_processor/boolean_to_comparison.clj+++ b/src/metabase/driver/sql/query_processor/boolean_to_comparison.clj@@ -75,8 +75,7 @@expression refs by name, if necessary, to determine whether their value is a boolean literal."[clause](and (driver-api/is-clause? :expression clause)- (or (boolean-typed-clause? clause)- (boolean-value-clause? (driver-api/expression-with-name sql.qp/*inner-query* (second clause))))))+ (boolean-value-clause? (driver-api/expression-with-name sql.qp/*inner-query* (second clause)))))(defn boolean->comparison"Convert boolean field refs or expression literals to equivalent boolean comparison expressions.diff --git a/src/metabase/legacy_mbql/normalize.cljc b/src/metabase/legacy_mbql/normalize.cljcindex 7fb30c3a3ad..2a572037715 100644--- a/src/metabase/legacy_mbql/normalize.cljc+++ b/src/metabase/legacy_mbql/normalize.cljc@@ -112,10 +112,6 @@expression-name)]opts (->> optsnormalize-ref-opts- ;; Only keep fields required for handling binned&datetime expressions (#33528)- ;; Allowing added alias-info through here breaks- ;; [[metabase.query-processor.util.nest-query-test/nest-expressions-ignore-source-queries-test]]- (m/filter-keys #{:base-type :temporal-unit :binning})not-empty)](cond-> expressionopts (conj opts))))@@ -409,10 +405,6 @@k ((if (simple-keyword? k)u/->snake_case_enu/->kebab-case-en) k)- _ (when (= k :fingerprint)- (when-let [base-type (first (keys (:type v)))]- (assert (isa? base-type :type/*)- (str "BAD FINGERPRINT! " (pr-str v)))))v (case k(:base_type:effective_type@@ -426,6 +418,12 @@:binning_info (m/update-existing v :binning_strategy keyword)#_elsev)]+ ;; sanity check+ (when (= k :fingerprint)+ (when-let [base-type (first (keys (:type v)))]+ (assert (isa? base-type :type/*)+ (str "BAD FINGERPRINT! Invalid base-type: " (pr-str base-type) " " (pr-str v)))))+[k v]))))metadata))@@ -437,6 +435,7 @@(seq (:template-tags native-query)) (update :template-tags normalize-template-tags))))(defn- normalize-actions-row [row]+(cond-> row(map? row) (update-keys u/qualified-name)))@@ -466,7 +465,7 @@;; TODO -- when does query ever have a top-level `:context` key??:context #(some-> % maybe-normalize-token):source-metadata {::sequence normalize-source-metadata}- :viz-settings maybe-normalize-token+ :viz-settings maybe-normalize-token ; TODO (Cam 8/8/25) -- we also have [[metabase.models.interface/normalize-visualization-settings]]:create-row normalize-actions-row:update-row normalize-actions-row;;@@ -1121,7 +1120,7 @@:query {:source-query remove-empty-clauses-in-source-query:joins {::sequence remove-empty-clauses-in-join}}:parameters {::sequence remove-empty-clauses-in-parameter}- :viz-settings identity+ :viz-settings identity ; TODO (Cam 8/8/25) -- we also have [[metabase.models.interface/normalize-visualization-settings]]:create-row identity:update-row identity})diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljcindex 65621f8f1cf..06f45f4864b 100644--- a/src/metabase/legacy_mbql/schema.cljc+++ b/src/metabase/legacy_mbql/schema.cljc@@ -245,9 +245,8 @@valid-temporal-unit-for-base-type?])(mr/def ::no-binning-options-at-top-level- [:fn- {:error/message ":binning keys like :strategy are not allowed at the top level of :field options."}- (complement :strategy)])+ (lib.schema.common/disallowed-keys+ {:strategy ":binning keys like :strategy are not allowed at the top level of :field options."}))(mr/def ::FieldOptions[:and@@ -1315,10 +1314,13 @@m))]])(def ^:private NativeQuery:Common- [:map- [:template-tags {:optional true} [:ref ::TemplateTagMap]]- ;; collection (table) this query should run against. Needed for MongoDB- [:collection {:optional true} [:maybe ::lib.schema.common/non-blank-string]]])+ [:and+ [:map+ [:template-tags {:optional true} [:ref ::TemplateTagMap]]+ ;; collection (table) this query should run against. Needed for MongoDB+ [:collection {:optional true} [:maybe ::lib.schema.common/non-blank-string]]]+ (lib.schema.common/disallowed-keys+ {:type "An inner query must not include :type, this will cause us to mix it up with an outer query"})])(def NativeQuery"Schema for a valid, normalized native [inner] query."@@ -1384,9 +1386,8 @@[:source {:optional true} [:maybe [:ref ::lib.schema.metadata/column.legacy-source]]][:unit {:optional true} [:maybe [:ref ::lib.schema.temporal-bucketing/unit]]][:visibility_type {:optional true} [:maybe [:ref ::lib.schema.metadata/column.visibility-type]]]]- [:fn- {:error/message "Legacy results metadata should not have :lib/type, use :metabase.lib.schema.metadata/column for Lib metadata"}- (complement :lib/type)]+ (lib.schema.common/disallowed-keys+ {:lib/type "Legacy results metadata should not have :lib/type, use :metabase.lib.schema.metadata/column for Lib metadata"})(letfn [(disallowed-key? [k](core/or (core/not (keyword? k))(let [disallowed-char (if (qualified-keyword? k)@@ -1524,13 +1525,13 @@(every-pred(some-fn :source-table :source-query)(complement (every-pred :source-table :source-query)))]- (let [disallowed-keys #{:filter :breakout :aggreggation :expressions :joins}]- [:fn- {:error/message "Join should not have top-level 'inner' query keys like :fields or :filter -- they should go in :source-query"- :error/fn (fn [{join :value} _]- (when (map? join)- (str "join should not have top-level 'inner' query keys, found " (set/intersection (set (keys join)) disallowed-keys))))}- (complement (apply some-fn disallowed-keys))])])+ (lib.schema.common/disallowed-keys+ {:type "A join should not include :type"+ :filter "A join should not have top-level 'inner' query keys like :filter"+ :breakout "A join should not have top-level 'inner' query keys like :breakout"+ :aggreggation "A join should not have top-level 'inner' query keys like :aggreggation"+ :expressions "A join should not have top-level 'inner' query keys like :expressions"+ :joins "A join should not have top-level 'inner' query keys like :joins"})])(def Join"Alias for ::Join. Prefer that going forward."@@ -1592,7 +1593,9 @@[:fn{:error/message "Fields specified in `:breakout` should not be specified in `:fields`; this is implied."}(fn [{:keys [breakout fields]}]- (empty? (set/intersection (set breakout) (set fields))))]])+ (empty? (set/intersection (set breakout) (set fields))))]+ (lib.schema.common/disallowed-keys+ {:type "An inner query must not include :type, this will cause us to mix it up with an outer query"})]);;; ----------------------------------------------------- Params -----------------------------------------------------@@ -1786,9 +1789,8 @@This should automatically be fixed by `normalize`; if we encounter it, it means some middleware is not functioningproperly."- [:fn- {:error/message "`:source-metadata` should be added in the same level as `:source-query` (i.e., the 'inner' MBQL query.)"}- (complement :source-metadata)])+ (lib.schema.common/disallowed-keys+ {:source-metadata "`:source-metadata` should be added in the same level as `:source-query` (i.e., the 'inner' MBQL query.)"}))(def Query"Schema for an [outer] query, e.g. the sort of thing you'd pass to the query processor or save in `Card.dataset_query`."@@ -1832,7 +1834,10 @@;;;; CONSTRAINTS[:ref ::check-keys-for-query-type]- [:ref ::check-query-does-not-have-source-metadata]])+ [:ref ::check-query-does-not-have-source-metadata]+ (lib.schema.common/disallowed-keys+ {:source-table "An outer query must not include inner-query keys like :source-table; this might cause us to confuse it with an inner query"+ :source-query "An outer query must not include inner-query keys like :source-query; this might cause us to confuse it with an inner query"})])(def ^{:arglists '([query])} valid-query?"Is this a valid outer query? (Pre-compling a validator is more efficient.)"diff --git a/src/metabase/legacy_mbql/util.cljc b/src/metabase/legacy_mbql/util.cljcindex 43fc2c22982..058a9a6db99 100644--- a/src/metabase/legacy_mbql/util.cljc+++ b/src/metabase/legacy_mbql/util.cljc@@ -24,15 +24,24 @@is-clause?check-clause])-(mu/defn normalize-token :- :keyword+(mu/defn normalize-token :- [:or :keyword :string]"Convert a string or keyword in various cases (`lisp-case`, `snake_case`, or `SCREAMING_SNAKE_CASE`) to a lisp-casedkeyword."[token :- schema.helpers/KeywordOrString]- #_{:clj-kondo/ignore [:discouraged-var]}- (-> (u/qualified-name token)- str/lower-case- (str/replace \_ \-)- keyword))+ (let [s (u/qualified-name token)]+ (if (str/starts-with? s "type/")+ ;; TODO (Cam 8/12/25) -- there's tons of code using incorrect parameter types or normalizing base types+ ;; incorrectly, for example [[metabase.actions.models/implicit-action-parameters]]. We need to actually start+ ;; validating parameters against the `:metabase.lib.schema.parameter/parameter` schema. We should probably throw+ ;; an error here instead of silently correcting it... I was going to do that but it broke too many things+ (do+ (log/error "normalize-token should not be getting called on a base type! This probably means we're using a base type in the wrong place, like as a parameter type")+ (keyword s))+ #_{:clj-kondo/ignore [:discouraged-var]}+ (-> s+ #?(:clj u/lower-case-en :cljs str/lower-case)+ (str/replace \_ \-)+ keyword))));;; +----------------------------------------------------------------------------------------------------------------+;;; | Functions for manipulating queries |@@ -589,23 +598,25 @@(mu/defn expression-with-name :- ::mbql.s/FieldOrExpressionDef"Return the expression referenced by a given `expression-name`."- [inner-query expression-name :- [:or :keyword ::lib.schema.common/non-blank-string]]- (let [allowed-names [(u/qualified-name expression-name) (keyword expression-name)]]- (loop [{:keys [expressions source-query]} inner-query, found #{}]- (or- ;; look for either string or keyword version of `expression-name` in `expressions`- (some (partial get expressions) allowed-names)- ;; otherwise, if we have a source query recursively look in that (do we allow that??)- (let [found (into found (keys expressions))]- (if source-query- (recur source-query found)- ;; failing that throw an Exception with detailed info about what we tried and what the actual expressions- ;; were- (throw (ex-info (i18n/tru "No expression named ''{0}''" (u/qualified-name expression-name))- {:type :invalid-query- :expression-name expression-name- :tried allowed-names- :found found}))))))))+ [inner-query expression-name :- ::lib.schema.common/non-blank-string]+ (loop [{:keys [expressions source-query]} inner-query, found #{}]+ (when (seq expressions)+ (assert (every? string? (keys expressions))+ (str ":expressions should always use string keys, got: " (pr-str expressions))))+ (or+ ;; look for`expression-name` in `expressions`+ (get expressions expression-name)+ ;; otherwise, if we have a source query recursively look in that (do we allow that??)+ (let [found (into found (keys expressions))]+ (if source-query+ (recur source-query found)+ ;; failing that throw an Exception with detailed info about what we tried and what the actual expressions+ ;; were+ (throw (ex-info (i18n/tru "No expression named ''{0}''" (u/qualified-name expression-name))+ {:type :invalid-query+ :expression-name expression-name+ :tried expression-name+ :found found})))))))(mu/defn aggregation-at-index :- ::mbql.s/Aggregation"Fetch the aggregation at index. This is intended to power aggregate field references (e.g. [:aggregation 0]).diff --git a/src/metabase/lib/aggregation.cljc b/src/metabase/lib/aggregation.cljcindex dfab8ca17b4..28133e99083 100644--- a/src/metabase/lib/aggregation.cljc+++ b/src/metabase/lib/aggregation.cljc@@ -304,7 +304,7 @@(-> metadata(u/assoc-default :effective-type (or (:base-type metadata) :type/*))(assoc :lib/source :source/aggregations- :lib/source-uuid (lib.options/uuid aggregation))))))))))+ :lib/source-uuid (lib.options/uuid aggregation))))))))))(def ^:private OperatorWithColumns[:mergediff --git a/src/metabase/lib/card.cljc b/src/metabase/lib/card.cljcindex 8250f320939..8c2c37694b8 100644--- a/src/metabase/lib/card.cljc+++ b/src/metabase/lib/card.cljc@@ -215,7 +215,10 @@(source-model-cols metadata-providerable card))](not-empty(into []- (lib.field.util/add-source-and-desired-aliases-xform metadata-providerable)+ ;; do not truncate the desired column aliases coming back in card metadata, if the query returns a+ ;; 'crazy long' column name then we need to use that in the next stage.+ ;; See [[metabase.lib.card-test/propagate-crazy-long-identifiers-from-card-metadata-test]]+ (lib.field.util/add-source-and-desired-aliases-xform metadata-providerable (lib.util/non-truncating-unique-name-generator))(cond-> result-cols(seq model-cols) (merge-model-metadata model-cols))))))))diff --git a/src/metabase/lib/convert.cljc b/src/metabase/lib/convert.cljcindex 392eb06967b..eff076fdf84 100644--- a/src/metabase/lib/convert.cljc+++ b/src/metabase/lib/convert.cljc@@ -1,6 +1,5 @@(ns metabase.lib.convert(:require- #?@(:clj ([metabase.util.log :as log]))[clojure.data :as data][clojure.set :as set][clojure.string :as str]@@ -17,6 +16,7 @@[metabase.lib.schema.ref :as lib.schema.ref][metabase.lib.util :as lib.util][metabase.util :as u]+ [metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr])#?@(:cljs [(:require-macros [metabase.lib.convert :refer [with-aggregation-list]])]))@@ -220,16 +220,51 @@(= converted (:converted state)) (throw (ex-info "Couldn't index clauses" {:clauses clauses})):else (recur state'))))))+(defn- add-source-uuids-to-cols+ "`cols` with `:source/aggregations` and `:source/expressions` should have `:lib/source-uuid`, since it's sorta+ important for matching purposes. Add them to attached `:lib/stage-metadata` when converting from legacy MBQL to MBQL 5."+ [cols expressions]+ (try+ (loop [acc [], aggregation-index 0, [col & more] cols]+ (cond+ (not col)+ acc++ (= (:lib/source col) :source/aggregations)+ (let [ag-uuid (or (get *legacy-index->pMBQL-uuid* aggregation-index)+ (throw (ex-info (str "Missing UUID for aggregation at index " aggregation-index)+ {:legacy-index->pMBQL-uuid *legacy-index->pMBQL-uuid*+ :aggregation-index aggregation-index})))+ col' (assoc col :lib/source-uuid ag-uuid)]+ (recur (conj acc col') (inc aggregation-index) more))++ (= (:lib/source col) :source/expressions)+ (let [expression-name (or (:lib/expression-name col)+ (throw (ex-info "Column with :source/expressions is missing :lib/expression-name"+ {:col col})))+ expression (or (m/find-first #(= (:lib/expression-name (lib.options/options %)) expression-name)+ expressions)+ (throw (ex-info (str "Failed to find expression with name " (pr-str expression-name))+ {:expression-name expression-name, :expressions expressions})))+ col' (assoc col :lib/source-uuid (lib.options/uuid expression))]+ (recur (conj acc col') aggregation-index more))++ :else+ (recur (conj acc col) aggregation-index more)))+ (catch #?(:clj Throwable :cljs :default) e+ (log/error e "Error adding :lib/source-uuid to cols")+ cols)))+(defmethod ->pMBQL :mbql.stage/mbql[stage]- (let [stage (m/update-existing stage :aggregation index-ref-clauses->pMBQL)- expressions (->> stage- :expressions- (mapv (fn [[k v]]- (-> v- ->pMBQL- (lib.util/top-level-expression-clause k))))- not-empty)]+ (let [stage (m/update-existing stage :aggregation index-ref-clauses->pMBQL)+ expressions (->> stage+ :expressions+ (mapv (fn [[k v]]+ (-> v+ ->pMBQL+ (lib.util/top-level-expression-clause k))))+ not-empty)](metabase.lib.convert/with-aggregation-list (:aggregation stage)(let [stage (-> stagestage-source-card-id->pMBQL@@ -242,7 +277,8 @@stage(disj stage-keys :expressions :aggregation))](cond-> stage- (:joins stage) (update :joins deduplicate-join-aliases))))))+ (:joins stage) (update :joins deduplicate-join-aliases)+ (:lib/stage-metadata stage) (update-in [:lib/stage-metadata :columns] add-source-uuids-to-cols expressions))))))(defmethod ->pMBQL :mbql.stage/native[stage]@@ -605,6 +641,7 @@(defmethod ->legacy-MBQL :mbql/join [join](let [base (cond-> (disqualify join)(and *clean-query*+ (:alias join)(str/starts-with? (:alias join) legacy-default-join-alias);; added by [[metabase.query-processor.middleware.resolve-joins]](not (:qp/keep-default-join-alias join)))@@ -641,9 +678,9 @@(for [expression expressions:let [legacy-clause (->legacy-MBQL expression)]][(lib.util/expression-name expression)- ;; `:aggregation-options` is not allowed inside- ;; `:expressions` in legacy, we'll just have to toss the- ;; extra info.+ ;; there's no way to add an options map to arbitrary clauses like `[:abs ...]` in legacy in `:expressions`+ ;; -- in `:aggregation` we can wrap it in `:aggregation-options` but this is not allowed here. We'll just+ ;; have to toss the extra info.(if (#{:aggregation-options} (first legacy-clause))(second legacy-clause)legacy-clause)])))diff --git a/src/metabase/lib/equality.cljc b/src/metabase/lib/equality.cljcindex 0ea3b5a9856..f50ca65c8e1 100644--- a/src/metabase/lib/equality.cljc+++ b/src/metabase/lib/equality.cljc@@ -103,6 +103,47 @@(sequential? x) ((get-method = :dispatch-type/sequential) x y):else (clojure.core/= x y)))+(defn- columns-equal-by-fn-when-non-nil-in-both [f col-1 col-2]+ (let [v1 (f col-1)+ v2 (f col-2)]+ (if (and v1 v2)+ (clojure.core/= v1 v2)+ true)))++(defn- columns-equal-by-fn [f col-1 col-2]+ (clojure.core/= (f col-1) (f col-2)))++(defn- ignore-default-temporal-bucket [bucket]+ (when-not (clojure.core/= bucket :default)+ bucket))++(defmethod = :metadata/column+ [col-1 col-2]+ (and+ ;; two column metadatas with different IDs are NEVER equal.+ (columns-equal-by-fn-when-non-nil-in-both :id col-1 col-2)+ ;; from the same source.+ (columns-equal-by-fn-when-non-nil-in-both :lib/source col-1 col-2)+ ;; same join alias+ (columns-equal-by-fn lib.join.util/current-join-alias col-1 col-2)+ ;;+ ;; columns that don't have the same binning or temporal bucketing are never the same.+ ;;+ ;; same binning+ (columns-equal-by-fn :metabase.lib.field/binning col-1 col-2)+ ;; same bucketing+ (columns-equal-by-fn (comp ignore-default-temporal-bucket lib.temporal-bucket/raw-temporal-bucket) col-1 col-2)+ ;; check `:inherited-temporal-unit` as well if both columns have it.+ (columns-equal-by-fn-when-non-nil-in-both (comp ignore-default-temporal-bucket :inherited-temporal-unit) col-1 col-2)+ ;; finally make sure they have the same `:lib/source-column-alias` (if both columns have it) or `:name` (if for+ ;; some reason they do not)+ (let [k (m/find-first (fn [k]+ (and (k col-1)+ (k col-2)))+ [:lib/source-column-alias :name])]+ (assert k "No key common to both columns")+ (columns-equal-by-fn k col-1 col-2))))+(mu/defn- resolve-field-id-in-source-card :- ::lib.schema.metadata/column"Integer Field ID: get metadata from the metadata provider. If this is the first stage of the query, merge inSaved Question metadata if available.diff --git a/src/metabase/lib/expression.cljc b/src/metabase/lib/expression.cljcindex f7ec67e02f8..81d63f70f19 100644--- a/src/metabase/lib/expression.cljc+++ b/src/metabase/lib/expression.cljc@@ -89,6 +89,8 @@(mu/defmethod lib.metadata.calculation/metadata-method :expression :- ::lib.metadata.calculation/visible-column[query stage-number [_expression opts expression-name, :as expression-ref-clause]](merge {:lib/type :metadata/column+ ;; TODO (Cam 8/7/25) -- is the source UUID of an expression ref supposed to be the ID of the ref, or the ID+ ;; of the expression definition??:lib/source-uuid (:lib/uuid opts):name expression-name:lib/expression-name expression-name@@ -401,7 +403,8 @@{:base-type base-type, :effective-type base-type}(cond-> literal (u.number/bigint? literal) str)])))-(mu/defn- expression-metadata :- ::lib.schema.metadata/column+(mu/defn expression-metadata :- ::lib.schema.metadata/column+ "Return column metadata for an `expression-definition` MBQL clause."[query :- ::lib.schema/querystage-number :- :intexpression-definition :- ::lib.schema.expression/expression]@@ -415,6 +418,7 @@(select-keys [:base-type :effective-type :lib/desired-column-alias:lib/source-column-alias :lib/source-uuid :lib/type])(assoc :lib/source :source/expressions+ :lib/source-uuid (lib.options/uuid expression-definition):lib/expression-name expression-name:name expression-name:display-name expression-name))))diff --git a/src/metabase/lib/field.cljc b/src/metabase/lib/field.cljcindex f2420db106d..bfb381ca653 100644--- a/src/metabase/lib/field.cljc+++ b/src/metabase/lib/field.cljc@@ -387,7 +387,9 @@::original-effective-type::original-temporal-unit]){:metabase.lib.field/binning :binning- :metabase.lib.field/temporal-unit :temporal-unit}))+ :metabase.lib.field/temporal-unit :temporal-unit+ :lib/ref-name :name+ :lib/ref-display-name :display-name}))(def ^:private field-ref-propagated-keys-for-non-inherited-columns"Keys that should get copied into `:field` ref options from column metadata ONLY when the column is not inherited.diff --git a/src/metabase/lib/field/resolution.cljc b/src/metabase/lib/field/resolution.cljcindex 9597ceee163..a2d574be924 100644--- a/src/metabase/lib/field/resolution.cljc+++ b/src/metabase/lib/field/resolution.cljc@@ -2,10 +2,13 @@"Code for resolving field metadata from a field ref. There's a lot of code here, isn't there? This is probably morecomplicated than it needs to be!"(:require+ #?@(:clj+ ([metabase.config.core :as config]))[better-cond.core :as b][clojure.set :as set][clojure.string :as str][medley.core :as m]+ [metabase.lib.expression :as lib.expression][metabase.lib.field.util :as lib.field.util][metabase.lib.join :as lib.join][metabase.lib.metadata :as lib.metadata]@@ -39,17 +42,20 @@{:keys [parent-id], :as metadata} :- ::lib.schema.metadata/column](if-not parent-idmetadata- (let [parent-metadata (lib.metadata/field metadata-providerable parent-id)- {parent-name :name, parent-display-name :display-name} (add-parent-column-metadata metadata-providerable parent-metadata)- new-name (str parent-name- \.- ((some-fn :lib/original-name :name) metadata))- new-display-name (str parent-display-name- ": "- ((some-fn :lib/original-display-name :display-name)- metadata))]+ (let [parent-metadata (lib.metadata/field metadata-providerable parent-id)+ {parent-name :name+ parent-nfc-path :nfc-path+ parent-display-name :display-name} (add-parent-column-metadata metadata-providerable parent-metadata)+ new-name (str parent-name+ \.+ ((some-fn :lib/original-name :name) metadata))+ new-display-name (str parent-display-name+ ": "+ ((some-fn :lib/original-display-name :display-name)+ metadata))](-> metadata(assoc :name new-name+ :nfc-path (conj (vec parent-nfc-path) (:name parent-metadata)):display-name new-display-name;; this is used by the `display-name-method` for `:metadata/column` in [[metabase.lib.field]]:metabase.lib.field/simple-display-name new-display-name)))))@@ -142,7 +148,8 @@:source-field-name :fk-field-name:temporal-unit :metabase.lib.field/temporal-unit;; display-name gets copied to both display-name and lib/ref-display-name- :display-name :lib/ref-display-name})+ :display-name :lib/ref-display-name+ :name :lib/ref-name})(defn- opts-fn-inherited-temporal-unit"`:inherited-temporal-unit` is transfered from `:temporal-unit` ref option only when@@ -293,7 +300,8 @@(-> col(as-> $col (lib.join/column-from-join query stage-number $col join-alias))(merge (select-keys join [:fk-field-id]))))))- ;; a join with this alias does not exist at this stage of the query... try looking recursively in previous stage(s)+ ;; a join with this alias does not exist at this stage of the query... try looking recursively in previous+ ;; stage(s)(do(log/debugf "Join %s does not exist in stage %s, looking in previous stages"(pr-str join-alias)@@ -301,7 +309,12 @@(if-some [previous-stage-number (lib.util/previous-stage-number query stage-number)](let [previous-stage-cols (filter #(= (:lib/original-join-alias %) join-alias)(lib.metadata.calculation/returned-columns query previous-stage-number))]- (resolve-in-previous-stage-metadata-and-update-keys query previous-stage-cols id-or-name))+ ;; try to resolve by what is PROBABLY the correct name in a previous stage e.g. `Join` + `COLUMN` becomes+ ;; `Join__COLUMN`... if this fails then fall back to looking for matches that ignore join alias entirely+ ;; e.g. just `COLUMN`+ (or (when (string? id-or-name)+ (resolve-in-previous-stage-metadata-and-update-keys query previous-stage-cols (str join-alias "__" id-or-name)))+ (resolve-in-previous-stage-metadata-and-update-keys query previous-stage-cols id-or-name)))(do(log/debug "Unable to resolve in previous stage =(")nil))))))@@ -411,7 +424,10 @@(resolve-in-card-returned-columns query source-card-id id-or-name)))(defn- fallback-metadata [id-or-name]- (log/debug (u/colorize :red "Returning fallback metadata"))+ (log/warn (u/format-color :red+ (str "We tried every trick we could think of and still failed to resolve field a"+ " ref. If the query doesn't work, this is why. Returning fallback metadata for %s")+ (pr-str id-or-name)))(merge{:lib/type :metadata/column;; guess that the column came from the previous stage@@ -469,23 +485,44 @@(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)]+ (assoc col+ ::fallback-metadata? true+ :lib/source (if (zero? (lib.util/canonical-stage-index query stage-number))+ :source/table-defaults+ :source/previous-stage)))))++(defn- maybe-resolve-expression-in-current-stage [query stage-number id-or-name]+ (when (string? id-or-name)+ (when-some [expr (lib.expression/maybe-resolve-expression query stage-number id-or-name)]+ (log/warn (u/format-color :red+ (str "Resolved field %s to an expression. Please remember to use :expression references"+ " for expressions in the current stage -- using a :field ref is unsupported and may"+ " not be allowed in the future.")+ (pr-str id-or-name)))+ (-> (lib.expression/expression-metadata query stage-number expr)+ (assoc :lib/source-column-alias id-or-name)))))+(mu/defn- resolve-from-previous-stage-or-source :- ::lib.metadata.calculation/visible-column[query :- ::lib.schema/querystage-number :- :intid-or-name :- ::id-or-name](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))- (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.- (when (pos-int? id-or-name)- (when-some [col (field-metadata query id-or-name)]- (assoc col ::fallback-metadata? true)))- ;; if we STILL can't find a match, return made-up fallback metadata.- (fallback-metadata 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))+ (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)+ ;; 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)+ ;; if we STILL can't find a match, return made-up fallback metadata.+ (fallback-metadata id-or-name))](merge-metadatacol(when col@@ -501,38 +538,40 @@;; 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))- (-> (merge-metadata- {:lib/type :metadata/column}- (or (cond- join-alias (resolve-in-join query stage-number join-alias id-or-name)- source-field (resolve-in-implicit-join query stage-number source-field id-or-name)- :else (resolve-from-previous-stage-or-source query stage-number id-or-name))- (merge- (fallback-metadata id-or-name)- (when join-alias- {:lib/source :source/joins- :metabase.lib.join/join-alias join-alias})))- (options-metadata opts)- {:lib/original-ref field-ref})- (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 accurate at all.- ;;- ;; We should OTOH keep `:lib/deduplicated-name`, because this is used to calculate subsequent deduplicated- ;; names, see [[metabase.lib.stage-test/return-correct-deduplicated-names-test]] for an example.- (dissoc :lib/desired-column-alias))))--;;;-;;; Helper functions for other namespaces-;;;--(mu/defn resolve-column-in-previous-stage-metadata :- [:maybe ::lib.schema.metadata/column]- "Find the matching column metadata in `cols` for `field-ref`.-- TODO (Cam 7/28/25) -- We should probably prefer [[lib.equality/find-matching-column]] directly instead; if this- function does something that [[lib.equality]] doesn't, we should fix the code in `lib.equality` instead of having- our own bespoke way of finding matching columns here."- [metadata-providerable :- ::lib.schema.metadata/metadata-providerable- [_tag _opts id-or-name, :as _field-ref] :- :mbql.clause/field- cols :- [:sequential ::lib.schema.metadata/column]]- (resolve-in-previous-stage-metadata-without-updating-keys metadata-providerable cols id-or-name))+ (u/prog1 (-> (merge-metadata+ {:lib/type :metadata/column}+ (or (cond+ join-alias (resolve-in-join query stage-number join-alias id-or-name)+ source-field (resolve-in-implicit-join query stage-number source-field id-or-name)+ :else (resolve-from-previous-stage-or-source query stage-number id-or-name))+ (merge+ (fallback-metadata id-or-name)+ (when (and join-alias+ (contains? (into #{}+ (map :alias)+ (:joins (lib.util/query-stage query stage-number)))+ join-alias))+ {:lib/source :source/joins+ :metabase.lib.join/join-alias join-alias})))+ (options-metadata opts)+ {:lib/original-ref field-ref})+ (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+ ;; accurate at all.+ ;;+ ;; We should OTOH keep `:lib/deduplicated-name`, because this is used to calculate subsequent+ ;; deduplicated names, see [[metabase.lib.stage-test/return-correct-deduplicated-names-test]] for an+ ;; example.+ (dissoc :lib/desired-column-alias))+ ;; sanity check the metadata that we return. (Clj + dev/test only)+ #?(:clj+ (when (or config/is-dev? config/is-test?)+ (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??"+ {:query query, :stage-number stage-number, :field-ref field-ref, :col <>})))+ (when (and (pos-int? stage-number)+ (#{: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 <>}))))))))diff --git a/src/metabase/lib/field/util.cljc b/src/metabase/lib/field/util.cljcindex ce3cfa01b2a..aad2b278638 100644--- a/src/metabase/lib/field/util.cljc+++ b/src/metabase/lib/field/util.cljc@@ -68,16 +68,19 @@`:lib/deduplicated-name` to a sequence of columns.(into [] (add-unique-names-xform) cols)"- [metadata-providerable :- ::lib.metadata.protocols/metadata-providerable]- (comp (add-deduplicated-names)- (let [unique-name-fn (lib.util/unique-name-generator)]- (map (fn [col]- (let [source-alias ((some-fn :lib/source-column-alias :name) col)- desired-alias (unique-name-fn- (lib.join.util/desired-alias metadata-providerable col))]- (assoc col- :lib/source-column-alias source-alias- :lib/desired-column-alias desired-alias)))))))+ ([metadata-providerable]+ (add-source-and-desired-aliases-xform metadata-providerable (lib.util/unique-name-generator)))++ ([metadata-providerable :- ::lib.metadata.protocols/metadata-providerable+ unique-name-fn :- ::lib.util/unique-name-generator]+ (comp (add-deduplicated-names)+ (map (fn [col]+ (let [source-alias ((some-fn :lib/source-column-alias :name) col)+ desired-alias (unique-name-fn+ (lib.join.util/desired-alias metadata-providerable col))]+ (assoc col+ :lib/source-column-alias source-alias+ :lib/desired-column-alias desired-alias)))))))(mu/defn update-keys-for-col-from-previous-stage :- [:map[:lib/type [:= :metadata/column]]]diff --git a/src/metabase/lib/join.cljc b/src/metabase/lib/join.cljcindex a22fde974ce..b99a65949b6 100644--- a/src/metabase/lib/join.cljc+++ b/src/metabase/lib/join.cljc@@ -337,8 +337,8 @@"The resolved `:fields` from a join, which we automatically append to the parent stage's `:fields`."[querystage-number- {:keys [fields stages], join-alias :alias, :or {fields :none}, :as join}- options :- [:maybe ::lib.metadata.calculation/returned-columns.options]]+ {:keys [fields stages], join-alias :alias, :or {fields :none}, :as join} :- ::lib.schema.join/join+ options :- [:maybe ::lib.metadata.calculation/returned-columns.options]](when-not (= fields :none)(let [cols (join-returned-columns-relative-to-parent-stage query stage-number join options)cols' (if (= fields :all)diff --git a/src/metabase/lib/join/util.cljc b/src/metabase/lib/join/util.cljcindex 46983b9fe60..4c3c5b75705 100644--- a/src/metabase/lib/join/util.cljc+++ b/src/metabase/lib/join/util.cljc@@ -98,8 +98,9 @@You should pass the results thru a unique name function."[metadata-providerable :- ::lib.schema.metadata/metadata-providerablecol :- ::lib.schema.metadata/column]- (let [source-alias ((some-fn :lib/source-column-alias :name) col)]- (if-let [join-alias (or (current-join-alias col)- (implicit-join-name metadata-providerable col))]- (joined-field-desired-alias join-alias source-alias)- source-alias)))+ (or (:lib/ref-name col)+ (let [source-alias ((some-fn :lib/source-column-alias :name) col)]+ (if-let [join-alias (or (current-join-alias col)+ (implicit-join-name metadata-providerable col))]+ (joined-field-desired-alias join-alias source-alias)+ source-alias))))diff --git a/src/metabase/lib/metadata/calculation.cljc b/src/metabase/lib/metadata/calculation.cljcindex 23caf940dca..2180f8f596b 100644--- a/src/metabase/lib/metadata/calculation.cljc+++ b/src/metabase/lib/metadata/calculation.cljc@@ -591,7 +591,7 @@;;; TODO (Cam 8/7/25) -- historically `visible-columns` worked on a bunch of stuff besides just a stage, but Braden;;; pointed out that it really only makes any sense at all for a stage here;;; https://metaboat.slack.com/archives/C0645JP1W81/p1754587431585559 . For historic reasons the main entrypoint to-;;; the function still lives here, but it's now just a shim that calls [[metabase.lib.stage/visible-columns*]] -- we+;;; the function still lives here, but it's now just a shim that calls [[metabase.lib.stage/-visible-columns]] -- we;;; should combine these so there's no more indirection. It should probably live in [[metabase.lib.stage]] going;;; forward, but we'd need to update a lot of code that calls this version of [[visible-columns]].(mu/defn visible-columns :- ::visible-columnsdiff --git a/src/metabase/lib/metadata/result_metadata.cljc b/src/metabase/lib/metadata/result_metadata.cljcindex 49b606e7789..d53a5d12af6 100644--- a/src/metabase/lib/metadata/result_metadata.cljc+++ b/src/metabase/lib/metadata/result_metadata.cljc@@ -136,16 +136,20 @@cols :- [:sequential ::kebab-cased-map]](mapv (fn [col](let [converted-timezone (when-let [expression-name ((some-fn :lib/expression-name :lib/original-expression-name) col)]- (when-let [expr (try- (lib.expression/resolve-expression query expression-name)- (catch #?(:clj Throwable :cljs :default) e- (log/error e "Column metadata has invalid :lib/expression-name (this was probably incorrectly propagated from a previous stage) (QUE-1342)")- (log/debugf "In query:\n%s" (u/pprint-to-str query))- nil))]- (lib.util.match/match-one expr- :convert-timezone- (let [[_convert-timezone _opts _expr source-tz] &match]- source-tz))))]+ ;; don't look inside expressions that happened inside of joins,+ ;; `lib.expression/resolve-expression` is unfortunately not smart enough to+ ;; figure out how to find them and will just log a noisy error+ (when-not (:lib/original-join-alias col)+ (when-let [expr (try+ (lib.expression/resolve-expression query expression-name)+ (catch #?(:clj Throwable :cljs :default) e+ (log/error e "Column metadata has invalid :lib/expression-name (this was probably incorrectly propagated from a previous stage) (QUE-1342)")+ (log/debugf "In query:\n%s" (u/pprint-to-str query))+ nil))]+ (lib.util.match/match-one expr+ :convert-timezone+ (let [[_convert-timezone _opts _expr source-tz] &match]+ source-tz)))))](cond-> colconverted-timezone (assoc :converted-timezone converted-timezone))))cols))diff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljcindex 478fcebc5f4..539d74b1ebd 100644--- a/src/metabase/lib/schema.cljc+++ b/src/metabase/lib/schema.cljc@@ -75,15 +75,10 @@;;;; TODO -- parameters??]- [:fn- {:error/message ":source-table is not allowed in a native query stage."}- #(not (contains? % :source-table))]- [:fn- {:error/message ":source-card is not allowed in a native query stage."}- #(not (contains? % :source-card))]- [:fn- {:error/message ":query is not allowed in a native query stage, you probably meant to use :native instead."}- (complement :query)]])+ (common/disallowed-keys+ {:source-table ":source-table is not allowed in a native query stage."+ :source-card ":source-card is not allowed in a native query stage."+ :query ":query is not allowed in a native query stage, you probably meant to use :native instead."})])(mr/def ::breakout[:ref ::ref/ref])@@ -123,7 +118,9 @@(defn- expression-ref-errors-for-stage [stage](let [expression-names (into #{} (map (comp :lib/expression-name second)) (:expressions stage))pred #(bad-ref-clause? :expression expression-names %)- form (stage-with-joins-and-namespaced-keys-removed stage)]+ form (-> (stage-with-joins-and-namespaced-keys-removed stage)+ ;; also ignore expression refs inside `:parameters` since they still use legacy syntax these days.+ (dissoc :parameters))](when (mbql.u/pred-matches-form? form pred)(mbql.u/matching-locations form pred))))@@ -196,22 +193,16 @@[:source-table {:optional true} [:ref ::id/table]][:source-card {:optional true} [:ref ::id/card]][:page {:optional true} [:ref ::page]]]- [:fn- {:error/message ":source-query is not allowed in pMBQL queries."}- #(not (contains? % :source-query))]- [:fn- {:error/message ":native is not allowed in an MBQL stage."}- #(not (contains? % :native))][:fn{:error/message "A query must have exactly one of :source-table or :source-card"}(complement (comp #(= (count %) 1) #{:source-table :source-card}))][:ref ::stage.valid-refs]- (into [:and]- (map (fn [k]- [:fn- {:error/message (str k " is deprecated and should not be used")}- (complement k)]))- [:aggregation-idents :breakout-idents :expression-idents])])+ (common/disallowed-keys+ {:native ":native is not allowed in an MBQL stage."+ :aggregation-idents ":aggregation-idents is deprecated and should not be used"+ :breakout-idents ":breakout-idents is deprecated and should not be used"+ :expression-idents ":expression-idents is deprecated and should not be used"+ :filter ":filter is not allowed in an MBQL 5 stage, use :filters instead"})]);;; the schemas are constructed this way instead of using `:or` because they give better error messages(mr/def ::stage.type@@ -261,9 +252,10 @@:error/message "Invalid stage :lib/type: expected :mbql.stage/native or :mbql.stage/mbql"}[:mbql.stage/native [:ref ::stage.native]][:mbql.stage/mbql [:ref ::stage.mbql]]]- [:fn- {:error/message "A query stage should not have :source-metadata, the prior stage should have :lib/stage-metadata instead"}- (complement :source-metadata)]])+ (common/disallowed-keys+ {:source-metadata "A query stage should not have :source-metadata, the prior stage should have :lib/stage-metadata instead"+ :source-query ":source-query is not allowed in MBQL 5 queries."+ :type ":type is not allowed in a query stage in any version of MBQL"})])(mr/def ::stage.initial[:multi {:dispatch lib-typediff --git a/src/metabase/lib/schema/common.cljc b/src/metabase/lib/schema/common.cljcindex a7591562b62..bbea3ec17ca 100644--- a/src/metabase/lib/schema/common.cljc+++ b/src/metabase/lib/schema/common.cljc@@ -39,11 +39,17 @@(cond-> m(string? (:lib/type m)) (update :lib/type keyword))))-(def ^:private ^{:arglists '([k])} memoized-kebab-key+;;; TODO (Cam 8/12/25) -- this doesn't really do what I'd expect with keys like `:-` or `:-a` or `:a-` -- it strips+;;; out preceding and trailing dashes+(def ^{:arglists '([k])} memoized-kebab-key"Calculating the kebab-case version of a key every time is pretty slow (even with the LRU caching[[u/->kebab-case-en]] has), since the keys here are static and finite we can just memoize them forever andget a nice performance boost."- (u.memo/fast-memo u/->kebab-case-en))+ (u.memo/fast-memo+ (fn [k]+ ;; sanity check: make sure we're not accidentally using this on a base type+ (assert (not= k :type/Text))+ (u/->kebab-case-en k))))(defn map->kebab-case"Convert a map to kebab case, for use with `:decode/normalize`."@@ -164,6 +170,42 @@;; remove deprecated `:ident` key(dissoc :ident))))+(mu/defn disallowed-keys+ "Helper for generating a schema to disallow certain keys in a map.++ [:and+ [:map+ [:lib/type [:= :mbql.stage/mbql]]]+ (disallowed-keys {:native \":native is not allowed in an MBQL stage\"})]++ ;; =>++ [:and+ [:map [:lib/type [:= :mbql.stage/mbql]]]+ [:fn+ {:error/message \":native is not allowed in an MBQL stage\"+ :decode/normalize #(cond-> % (map? %) (dissoc :native))}+ #(not (when (map? %) (contains? :native)))]]"+ [k->message :- [:map-of :keyword :string]]+ (let [fn-schemas (map (fn [[k message]]+ [:fn+ {:error/message message+ ;; don't try to normalize something that's not a map, e.g. no `(dissoc 1 :k)` -- this is a+ ;; bad value anyway but not our problem to try and fix it+ :decode/normalize (fn -normalize [m]+ (cond-> m+ (map? m) (dissoc k)))}+ ;; we only want an error to trigger when input is a map, not if it's `nil` or+ ;; something (the `:map` schema can be the one that errors there)+ (fn -pred [m]+ (if (map? m)+ (not (contains? m k))+ true))])+ k->message)]+ (if (= (count fn-schemas) 1)+ (first fn-schemas)+ (into [:and] fn-schemas))))+(mr/def ::options[:and{:default {}}@@ -178,9 +220,8 @@[:database-type {:optional true} [:maybe ::non-blank-string]][:name {:optional true} [:maybe ::non-blank-string]][:display-name {:optional true} [:maybe ::non-blank-string]]]- [:fn- {:error/message ":ident is deprecated and should not be included in options maps"}- (complement :ident)]])+ (disallowed-keys+ {:ident ":ident is deprecated and should not be included in options maps"})])(mr/def ::external-op[:mapdiff --git a/src/metabase/lib/schema/join.cljc b/src/metabase/lib/schema/join.cljcindex 377f0708b83..85da48456a3 100644--- a/src/metabase/lib/schema/join.cljc+++ b/src/metabase/lib/schema/join.cljc@@ -102,15 +102,13 @@[:alias ::alias][:fields {:optional true} ::fields][:strategy {:optional true} ::strategy]]- [:fn- {:error/message "join should not have metadata attached directly to them; attach metadata to their last stage instead"}- (complement (some-fn :lib/stage-metadata :source-metadata))]- [:fn- {:error/message ":condition is not allowed for MBQL 5 joins, use :conditions instead"}- (complement :condition)]- [:fn- {:error/message "join should not have :source-table or :source-query; use :stages instead"}- (complement (some-fn :source-table :source-query))]])+ (common/disallowed-keys+ {:lib/stage-metadata "joins should not have metadata attached directly to them; attach metadata to their last stage instead"+ :source-metadata "joins should not have metadata attached directly to them; attach metadata to their last stage instead"+ :condition ":condition is not allowed for MBQL 5 joins, use :conditions instead"+ :source-card "join should not have :source-card; use :stages instead"+ :source-table "join should not have :source-table; use :stages instead"+ :source-query "join should not have :source-query; use :stages instead"})])(mr/def ::joins[:anddiff --git a/src/metabase/lib/schema/metadata.cljc b/src/metabase/lib/schema/metadata.cljcindex bf48d59a0fc..3fe4b3bfefd 100644--- a/src/metabase/lib/schema/metadata.cljc+++ b/src/metabase/lib/schema/metadata.cljc@@ -130,7 +130,7 @@:none})(mr/def ::column.has-field-values- (into [:enum] (sort column-has-field-values-options)))+ (into [:enum {:decode/normalize lib.schema.common/normalize-keyword}] (sort column-has-field-values-options)))(mr/def ::column.remapping.external"External remapping (Dimension) for a column. From the [[metabase.warehouse-schema.models.dimension]] with `type =@@ -199,9 +199,9 @@[;; Only allow `:lib/expression-name` when `:lib/source` is `:source/expressions`. If it's anything else, it;; probably means it's getting incorrectly propagated from a previous stage (QUE-1342).{:exclude :source/expressions- :schema [:fn- {:error/message ":lib/expression-name should only be set for expressions in the current stage (i.e., columns with :source/expressions)"}- (complement :lib/expression-name)]}+ :schema (lib.schema.common/disallowed-keys+ {:lib/expression-name+ ":lib/expression-name should only be set for expressions in the current stage (i.e., columns with :source/expressions)"})}{:include :source/expressions:schema [:fn{:error/message ":lib/expression-name is required for columns with :source/expressions"}@@ -209,10 +209,10 @@;; Current stage join alias (`:metabase.lib.join/join-alias`) should only be set for columns whose `:lib/source` is;; `:source/joins`{:exclude :source/joins- :schema [:fn- {:error/message (str "Current stage join alias (:metabase.lib.join/join-alias) should only be set for"- " columns joined in the current stage (i.e., columns with :source/joins).")}- (complement :metabase.lib.join/join-alias)]}+ :schema (lib.schema.common/disallowed-keys+ {:metabase.lib.join/join-alias+ (str "Current stage join alias (:metabase.lib.join/join-alias) should only be set for"+ " columns joined in the current stage (i.e., columns with :source/joins).")})};; If source is `:source/joins` column must specify a current stage join alias.{:include :source/joins:schema [:fn@@ -225,9 +225,9 @@;; `:source/implicitly-joinable` and `:source/joins`. For columns from `:source/previous-stage` or whatever... in;; that case we should be using `:lib/original-fk-field-id` instead.{:exclude #{:source/implicitly-joinable :source/joins}- :schema [:fn- {:error/message ":fk-field-id is only allowed for columns with :source/implicitly-joinable or :source/joins"}- (complement :fk-field-id)]}+ :schema (lib.schema.common/disallowed-keys+ {:fk-field-id+ ":fk-field-id is only allowed for columns with :source/implicitly-joinable or :source/joins"})}{:include :source/implicitly-joinable:schema [:fn{:error/message ":fk-field-id is required for columns with :source/implicitly-joinable"}@@ -236,7 +236,15 @@{:include :source/card:schema [:fn{:error/message "Columns with :source/card must have :lib/card-id"}- :lib/card-id]}])+ :lib/card-id]}+ ;; columns with `:source/aggregations` or `:source/expressions` should always have `:lib/source-uuid`, since they+ ;; by definition come from an MBQL clause with a UUID in the query itself.+ ;;+ ;; TODO (Cam 8/7/25) -- disabled for now since this breaks a surprising amount of stuff.+ #_{:include #{:source/aggregations :source/expressions}+ :schema [:fn+ {:error/message "Columns with :source/aggregations or :source/expressions must have :lib/source-uuid"}+ :lib/source-uuid]}])(defn- column-validate-for-source-schema [source](into [:and]@@ -400,6 +408,10 @@;; where this column came from. See docstring for `::column.source`.[:lib/source {:optional true} [:maybe [:ref ::column.source]]];;+ ;; if this column metadata was calculated based on MBQL clauses in the query itself, this is the UUID of the+ ;; clauses in question. Required for aggregations and expressions+ [:lib/source-uuid {:optional true} [:maybe [:ref ::lib.schema.common/uuid]]]+ ;;;; whether this column metadata occurs in the `:breakout`(s) in the CURRENT STAGE or not. Previously this was;; signified by `:lib/source = :source/breakouts` (which has been removed);;@@ -443,6 +455,11 @@;; this is that display name. `:lib/ref-display-name` should override any display names specified in the metadata.[:lib/ref-display-name {:optional true} [:maybe :string]];;+ ;; If this metadata was resolved from a ref (e.g. a `:field` ref) and that ref contained a `:name` in the options,+ ;; this is that name. If specified we should use this as the basis for the desired column alias rather than join+ ;; alias + source column alias.+ [:lib/ref-name {:optional true} [:maybe :string]]+ ;;;; when column metadata is returned by certain things;; like [[metabase.lib.aggregation/selected-aggregation-operators]] or [[metabase.lib.field/fieldable-columns]], it;; might include this key, which tells you whether or not that column is currently selected or not already, e.g.@@ -457,8 +474,21 @@;; column. The JVM provider currently does not, since the QP doesn't need it for anything.[:has-field-values {:optional true} [:maybe [:ref ::column.has-field-values]]];;+ ;; info about stuff like min and max values of the column, used for auto bucketing.[:fingerprint {:optional true} [:maybe [:ref ::lib.schema.metadata.fingerprint/fingerprint]]];;+ ;; If this is a nested column, the names of the ancestor columns used to access it. E.g. if the column is+ ;; `grandparent.parent.child` then `:nfc-path` would be `["grandparent" "parent"]`.+ ;;+ ;; This was originally added to power Postgres JSON column support; but is now used for any sort of nested column,+ ;; including BigQuery `RECORD` columns and MongoDB nested columns. See+ ;; https://metaboat.slack.com/archives/C0645JP1W81/p1754949404592539 for code archeology+ [:nfc-path {:optional true} [:maybe [:sequential :string]]]+ ;;+ ;; populated by the `metabase_field.settings` column in the application database; I'm not really sure what goes in+ ;; here and if it's actually used for anything important in Lib or the QP (I suspect it's not).+ [:settings {:optional true} [:maybe [:map-of {:decode/normalize lib.schema.common/normalize-map-no-kebab-case} :keyword :any]]]+ ;;;; Added by [[metabase.lib.metadata.result-metadata]] primarily for legacy/backward-compatibility purposes with;; legacy viz settings. This should not be used for anything other than that.[:field-ref {:optional true} [:maybe [:ref :metabase.legacy-mbql.schema/Reference]]]diff --git a/src/metabase/lib/schema/parameter.cljc b/src/metabase/lib/schema/parameter.cljcindex bcdfdb5bf0d..734a0b7cb89 100644--- a/src/metabase/lib/schema/parameter.cljc+++ b/src/metabase/lib/schema/parameter.cljc@@ -22,6 +22,8 @@`:widget-type` in some cases. In these cases, the backend is just supposed to infer the actual type of the parametervalue."(:require+ #?@(:clj+ ([flatland.ordered.map :as ordered-map]))[metabase.lib.schema.common :as lib.schema.common][metabase.util.malli.registry :as mr]))@@ -64,7 +66,8 @@Optional, specifies a function `(f clause-without-options options-map-or-nil) => clause-with-options` to be used forattaching the options. The default is to `conj` non-nil options on the end."- {;; the basic raw-value types. These can be used with [[TemplateTag:RawValue]] template tags as well as+ (#?(:clj ordered-map/ordered-map :cljs hash-map) ; for REPL-friendliness+ ;; the basic raw-value types. These can be used with [[TemplateTag:RawValue]] template tags as well as;; [[TemplateTag:FieldFilter]] template tags.:number {:type :numeric, :allowed-for #{:number :number/= :id :category :location/zip_code}}:text {:type :string, :allowed-for #{:text :string/= :id :category@@ -103,7 +106,7 @@;; time being. We'll only allow that if the widget type matches exactly, however.:location/city {:allowed-for #{:location/city}}:location/state {:allowed-for #{:location/state}}- :location/zip_code {:allowed-for #{:location/zip_code}}+ :location/zip_code {:allowed-for #{:location/zip_code}} ; TODO (Cam 8/12/25) -- should use `kebab-case` like literally every other type:location/country {:allowed-for #{:location/country}};; date range types -- these match a range of dates@@ -137,7 +140,7 @@:string/does-not-contain {:type :string, :operator :variadic, :options-fn variadic-opts-first, :allowed-for #{:string/does-not-contain}}:string/ends-with {:type :string, :operator :variadic, :options-fn variadic-opts-first, :allowed-for #{:string/ends-with}}:string/starts-with {:type :string, :operator :variadic, :options-fn variadic-opts-first, :allowed-for #{:string/starts-with}}- :boolean/= {:type :boolean, :operator :variadic, :allowed-for #{:boolean :boolean/=}}})+ :boolean/= {:type :boolean, :operator :variadic, :allowed-for #{:boolean :boolean/=}}))(mr/def ::type(into [:enum {:error/message "valid parameter type"diff --git a/src/metabase/lib/schema/template_tag.cljc b/src/metabase/lib/schema/template_tag.cljcindex 8a48b87c028..6b73eb15fe1 100644--- a/src/metabase/lib/schema/template_tag.cljc+++ b/src/metabase/lib/schema/template_tag.cljc@@ -88,10 +88,7 @@[:options {:optional true} [:maybe :map]]]])(mr/def ::disallow-dimension- [:fn- {:decode/normalize #(dissoc % :dimension)- :error/message ":dimension is only allowed for :type :dimension template tags"}- #(not (contains? % :dimension))])+ (common/disallowed-keys {:dimension ":dimension is only allowed for :type :dimension template tags"}));; Example:;;diff --git a/src/metabase/lib/stage.cljc b/src/metabase/lib/stage.cljcindex eadbef5f6d1..b03e24f2a7d 100644--- a/src/metabase/lib/stage.cljc+++ b/src/metabase/lib/stage.cljc@@ -2,10 +2,9 @@"Method implementations for a stage of a query."(:require[clojure.string :as str]- [medley.core :as m][metabase.lib.aggregation :as lib.aggregation]- [metabase.lib.binning :as lib.binning][metabase.lib.breakout :as lib.breakout]+ [metabase.lib.equality :as lib.equality][metabase.lib.expression :as lib.expression][metabase.lib.field.util :as lib.field.util][metabase.lib.hierarchy :as lib.hierarchy]@@ -17,7 +16,6 @@[metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata]- [metabase.lib.temporal-bucket :as lib.temporal-bucket][metabase.lib.util :as lib.util][metabase.lib.util.match :as lib.util.match][metabase.util :as u]@@ -49,7 +47,10 @@(not-empty(into [](comp (map #(assoc % :lib/source source-type))- (lib.field.util/add-source-and-desired-aliases-xform query))+ ;; do not truncate the desired column aliases coming back from a native query, because if a+ ;; native query returns a 'crazy long' column name then we need to use that in the next stage.+ ;; See [[metabase.lib.stage-test/propagate-crazy-long-native-identifiers-test]]+ (lib.field.util/add-source-and-desired-aliases-xform query (lib.util/non-truncating-unique-name-generator)))(:columns metadata))))))))(mu/defn- breakouts-columns :- [:maybe ::lib.metadata.calculation/visible-columns]@@ -68,9 +69,7 @@(not-empty(for [ag (lib.aggregation/aggregations-metadata query stage-number)];; TODO (Cam 8/1/25) -- why don't we just do this in [[lib.aggregation/aggregations-metadata]] instead of here?- (assoc ag- :lib/source :source/aggregations- :lib/source-column-alias ((some-fn :lib/source-column-alias :name) ag)))))+ (assoc ag :lib/source-column-alias ((some-fn :lib/source-column-alias :name) ag)))));;; TODO -- maybe the bulk of this logic should be moved into [[metabase.lib.field]], like we did for breakouts and;;; aggregations above.@@ -246,30 +245,6 @@(when include-implicitly-joinable?(lib.metadata.calculation/implicitly-joinable-columns query stage-number existing-columns)))))-(defn- add-cols-from-join-duplicate?- "Whether two columns are considered to be the same for purposes of [[add-cols-from-join]]."- [col-1 col-2]- ;; columns that don't have the same binning or temporal bucketing are never the same.- (and- ;; same binning- (= (lib.binning/binning col-1)- (lib.binning/binning col-2))- ;; same bucketing- (letfn [(bucket [col]- (when-let [bucket (lib.temporal-bucket/raw-temporal-bucket col)]- (when-not (= bucket :default)- bucket)))]- (= (bucket col-1)- (bucket col-2)))- ;; compare by something that both columns have, trying ID first falling back to column name- (let [k (m/find-first (fn [k]- (and (k col-1)- (k col-2)))- [:id :lib/source-column-alias :name])]- (assert k "No key common to both columns")- (= (k col-1)- (k col-2)))))-(defn- add-cols-from-join"The columns from `:fields` may contain columns from `:joins` -- so if the joins specify their own `:fields` we needto make sure not to include them twice! We de-duplicate them here.@@ -283,7 +258,7 @@field-cols)duplicate-col? (fn [join-col](some (fn [existing-col]- (add-cols-from-join-duplicate? join-col existing-col))+ (lib.equality/= join-col existing-col))existing-cols))](into (vec field-cols)(remove duplicate-col?)diff --git a/src/metabase/lib/util.cljc b/src/metabase/lib/util.cljcindex b5c1b3ce88f..d459916af0a 100644--- a/src/metabase/lib/util.cljc+++ b/src/metabase/lib/util.cljc@@ -23,6 +23,7 @@[metabase.lib.util.match :as lib.util.match][metabase.util :as u][metabase.util.i18n :as i18n]+ [metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]))@@ -210,16 +211,20 @@"Convert legacy `:source-metadata` to [[metabase.lib.metadata/StageMetadata]]."[source-metadata](when source-metadata- (-> (if (seqable? source-metadata)- {:columns source-metadata}- source-metadata)- (update :columns (fn [columns]- (mapv (fn [column]- (-> column- (update-keys u/->kebab-case-en)- (assoc :lib/type :metadata/column)))- columns)))- (assoc :lib/type :metadata/results))))+ (when-let [m (cond+ (seqable? source-metadata) {:columns source-metadata}+ (map? source-metadata) source-metadata+ :else (do+ (log/warnf "Ignoring invalid source metadata: expected sequence of columns, got %s" (pr-str (type source-metadata)))+ nil))]+ (-> m+ (update :columns (fn [columns]+ (mapv (fn [column]+ (-> column+ (update-keys u/->kebab-case-en)+ (assoc :lib/type :metadata/column)))+ columns)))+ (assoc :lib/type :metadata/results)))))(defn- join->pipeline [join](let [stages (inner-query->stages (or (:source-query join)@@ -584,15 +589,6 @@results metadata."(unique-name-generator-factory {::truncate? false}))-(mu/defn identity-generator :- ::unique-name-generator- "Identity unique name generator that just returns strings as-is."- ([]- identity-generator)- ([s]- s)- ([_id s]- s))-(def ^:private strip-id-regex#?(:cljs (js/RegExp. " id$" "i");; `(?i)` is JVM-specific magic to turn on the `i` case-insensitive flag.diff --git a/src/metabase/lib/walk.cljc b/src/metabase/lib/walk.cljcindex 00b6ac7ea23..d446e4d5bdc 100644--- a/src/metabase/lib/walk.cljc+++ b/src/metabase/lib/walk.cljc@@ -235,3 +235,15 @@(let [num-stages-or-joins (count (get-in query (butlast path)))](when (< (inc (last path)) num-stages-or-joins)(conj (vec (butlast path)) (inc (last path))))))++(mu/defn join-parent-stage-path :- ::path+ "Given a `join-path`, return the path to its parent stage (the stage that has this join inside its `:joins`)."+ [join-path :- ::path]+ (-> (vec join-path) pop pop))++(mu/defn join-last-stage-path :- ::path+ "Given a `join-path`, return the path to the last stage within the join."+ [join-path :- ::path+ join :- [:map+ [:lib/type [:= :mbql/join]]]]+ (into (vec join-path) [:stages (dec (count (:stages join)))]))diff --git a/src/metabase/models/interface.clj b/src/metabase/models/interface.cljindex ac7c7bd504d..e294892aa49 100644--- a/src/metabase/models/interface.clj+++ b/src/metabase/models/interface.clj@@ -193,14 +193,14 @@{:in json-in-with-eliding:out json-out-with-keywordization})-(defn- serialize-mlv2-query- "Saving MLv2 queries we can assume MLv2 queries are normalized enough already, but remove the metadata provider before- saving it, because it's not something that lends itself well to serialization."+(defn- serialize-mbql-5-query+ "Saving MBQL 5 queries we can assume MBQL 5 queries are normalized enough already, but remove the metadata provider+ before saving it, because it's not something that lends itself well to serialization."[query](dissoc query :lib/metadata))-(defn- deserialize-mlv2-query- "Reading MLv2 queries: normalize them, then attach a MetadataProvider based on their Database."+(defn- deserialize-mbql-5-query+ "Reading MBQL 5 queries: normalize them, then attach a MetadataProvider based on their Database."[query](let [metadata-provider (if (lib.metadata.protocols/metadata-provider? (:lib/metadata query));; in case someone passes in an already-normalized query to [[maybe-normalize-query]] below,@@ -216,12 +216,12 @@query](letfn [(normalize [query](let [f (if (= (lib/normalized-query-type query) :mbql/query)- ;; MLv2 queries+ ;; MBQL 5 queries(case in-or-out- :in serialize-mlv2-query- :out deserialize-mlv2-query)+ :in serialize-mbql-5-query+ :out deserialize-mbql-5-query);; legacy queries: just normalize them with the legacy normalization code for now... in the near- ;; future we'll probably convert to MLv2 before saving so everything in the app DB is MLv2+ ;; future we'll probably convert to MBQL 5 before saving so everything in the app DB is MBQL 5(case in-or-out:in mbql.normalize/normalize:out mbql.normalize/normalize))]@@ -376,7 +376,7 @@(defn normalize-visualization-settings"The frontend uses JSON-serialized versions of MBQL clauses as keys in `:column_settings`. This normalizes them- to modern MBQL clauses so things work correctly."+ to MBQL 4 clauses so things work correctly."[viz-settings](letfn [(normalize-column-settings-key [k](some-> k u/qualified-name json/decode mbql.normalize/normalize json/encode))@@ -385,29 +385,58 @@[(normalize-column-settings-key k) (walk/keywordize-keys v)])))(mbql-field-clause? [form](and (vector? form)- (#{"field-id" "fk->" "datetime-field" "joined-field" "binning-strategy" "field"- "aggregation" "expression"}+ (#{"field-id"+ "fk->"+ "datetime-field"+ "joined-field"+ "binning-strategy"+ "field"+ "aggregation"+ "expression"}(first form))))(normalize-mbql-clauses [form]- (walk/postwalk- (fn [form]- (try- (cond-> form- (mbql-field-clause? form) mbql.normalize/normalize)- (catch Exception e- (log/warnf "Unable to normalize visualization-settings part %s: %s"- (u/pprint-to-str 'red form)- (ex-message e))- form)))- form))]- (cond-> (walk/keywordize-keys (dissoc viz-settings "column_settings" "graph.metrics"))- ;; "key" is an old unused value- true (m/update-existing :table.columns (fn [cols] (mapv #(dissoc % :key) cols)))- (get viz-settings "column_settings") (assoc :column_settings (normalize-column-settings (get viz-settings "column_settings")))- true normalize-mbql-clauses- ;; exclude graph.metrics from normalization as it may start with- ;; the word "expression" but it is not MBQL (metabase#15882)- (get viz-settings "graph.metrics") (assoc :graph.metrics (get viz-settings "graph.metrics")))))+ (cond+ (mbql-field-clause? form)+ (try+ (mbql.normalize/normalize form)+ (catch Exception e+ (log/warnf "Unable to normalize visualization-settings part %s: %s"+ (u/pprint-to-str 'red form)+ (ex-message e))+ form))++ (sequential? form)+ (into (empty form) (map normalize-mbql-clauses) form)++ (map? form)+ (into (empty form)+ (map (fn [[k v]]+ ;; don't recurse into `:columns` if they are COLUMN NAMES! -- if the first column name is+ ;; something like "expression" then we don't want to accidentally treat it as an+ ;; `:expression` ref. Some `:columns` lists is viz settings do contain MBQL clauses+ ;; tho :unamused:+ (let [column-names? (and (= k :columns)+ (sequential? v)+ (every? (complement mbql-field-clause?) v))]+ [k (cond-> v+ (not column-names?) normalize-mbql-clauses)])))+ form)++ :else+ form))]+ (->+ viz-settings+ (dissoc "column_settings" "graph.metrics")+ walk/keywordize-keys+ ;; "key" is an old unused value+ (m/update-existing :table.columns (fn [cols] (mapv #(dissoc % :key) cols)))+ (cond-> (get viz-settings "column_settings")+ (assoc :column_settings (normalize-column-settings (get viz-settings "column_settings"))))+ normalize-mbql-clauses+ ;; exclude graph.metrics from normalization as it may start with the word "expression" but it is not+ ;; MBQL (metabase#15882)+ (cond-> (get viz-settings "graph.metrics")+ (assoc :graph.metrics (get viz-settings "graph.metrics"))))))(jm/def-json-migration migrate-viz-settings*)diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex eefb4ebf855..18034a329a0 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -20,6 +20,7 @@[metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib-be.metadata.jvm :as lib.metadata.jvm][metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.lib.normalize :as lib.normalize][metabase.lib.schema.metadata :as lib.schema.metadata]@@ -38,6 +39,7 @@[metabase.queries.models.parameter-card :as parameter-card][metabase.queries.models.query :as query][metabase.query-permissions.core :as query-perms]+ [metabase.query-processor.store :as qp.store][metabase.query-processor.util :as qp.util][metabase.search.core :as search][metabase.util :as u]@@ -388,7 +390,9 @@{:status-code 400})):else- (recur (or (t2/select-one-fn :dataset_query :model/Card :id source-card-id)+ (recur (or (if (qp.store/initialized?)+ (:dataset-query (lib.metadata/card (qp.store/metadata-provider) source-card-id))+ (t2/select-one-fn :dataset_query :model/Card :id source-card-id))(throw (ex-info (tru "Card {0} does not exist." source-card-id){:status-code 404})))(conj ids-already-seen source-card-id))))))diff --git a/src/metabase/queries/models/query.clj b/src/metabase/queries/models/query.cljindex 9e9b7d4f7ed..a391b8465cb 100644--- a/src/metabase/queries/models/query.clj+++ b/src/metabase/queries/models/query.clj@@ -8,6 +8,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.lib.util :as lib.util][metabase.models.interface :as mi]+ [metabase.query-processor.store :as qp.store][metabase.util.honey-sql-2 :as h2x][metabase.util.json :as json][metabase.util.malli :as mu]@@ -110,9 +111,18 @@(cond(= :native query-type) {:database-id database-id, :table-id nil}(integer? source-table) {:database-id database-id, :table-id source-table}- (string? source-table) (let [[_ card-id] (re-find #"^card__(\d+)$" source-table)]- (t2/select-one [:model/Card :card_schema [:table_id :table-id] [:database_id :database-id]]- :id (Integer/parseInt card-id)))+ (string? source-table) (let [card-id (lib.util/legacy-string-table-id->card-id source-table)]+ (if (qp.store/initialized?)+ (lib.metadata/card (qp.store/metadata-provider) card-id)+ (-> (t2/select-one [:model/Card+ ;; `card_schema` is only needed for post-processing.+ :card_schema+ [:table_id :table-id]+ [:database_id :database-id]]+ :id card-id)+ ;; remove `card_schema` so people don't try to use a key that would be `kebab-case`+ ;; if we got it from the metadata provider.+ (dissoc :card_schema))))(map? source-query) (legacy-query->database-and-table-ids {:database database-id:type query-type:query source-query})))diff --git a/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj b/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.cljindex 96d05de0627..4bd73895e35 100644--- a/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj+++ b/src/metabase/query_processor/middleware/annotate/legacy_helper_fns.clj@@ -12,6 +12,7 @@[metabase.lib.schema.common :as lib.schema.common][metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.store :as qp.store]+ [metabase.query-processor.util.add-alias-info :as-alias add][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]))@@ -36,9 +37,12 @@These names are also used directly in queries, e.g. in the equivalent of a SQL `AS` clause."[legacy-inner-query :- :maplegacy-ag-clause]- (lib/column-name- (legacy-inner-query->mlv2-query legacy-inner-query)- (lib/->pMBQL legacy-ag-clause)))+ (let [ag-clause (lib/->pMBQL legacy-ag-clause)]+ (or (::add/desired-alias (lib/options ag-clause))+ (:name (lib/options ag-clause))+ (lib/column-name+ (legacy-inner-query->mlv2-query legacy-inner-query)+ (lib/->pMBQL legacy-ag-clause)))))(mu/defn merged-column-info :- :metabase.query-processor.middleware.annotate/cols"Returns deduplicated and merged column metadata (`:cols`) for query results by combining (a) the initial resultsdiff --git a/src/metabase/query_processor/middleware/ensure_joins_use_source_query.clj b/src/metabase/query_processor/middleware/ensure_joins_use_source_query.cljindex 4290346f7b4..1dc9b9b62e8 100644--- a/src/metabase/query_processor/middleware/ensure_joins_use_source_query.clj+++ b/src/metabase/query_processor/middleware/ensure_joins_use_source_query.clj@@ -25,6 +25,6 @@[query :- ::lib.schema/query](lib.walk/walkquery- (fn [_query path-type _path stage-or-join]+ (fn [_query path-type _path join](when (= path-type :lib.walk/join)- (assoc-in stage-or-join [:stages (dec (count (:stages stage-or-join))) ::dummy-key] true)))))+ (assoc-in join [:stages (dec (count (:stages join))) ::dummy-key] true)))))diff --git a/src/metabase/query_processor/middleware/fetch_source_query.clj b/src/metabase/query_processor/middleware/fetch_source_query.cljindex 6a57d59878e..73d9f9b7821 100644--- a/src/metabase/query_processor/middleware/fetch_source_query.clj+++ b/src/metabase/query_processor/middleware/fetch_source_query.clj@@ -42,7 +42,7 @@(cons first-stage more)))(mu/defn normalize-card-query :- ::lib.schema.metadata/card- "Convert Card's query (`:datasaet-query`) to pMBQL as needed; splice in stage metadata and some extra keys."+ "Convert Card's query (`:dataset-query`) to pMBQL as needed; splice in stage metadata and some extra keys."[metadata-providerable :- ::lib.schema.metadata/metadata-providerable{card-id :id, :as card} :- ::lib.schema.metadata/card](let [persisted-info (:lib/persisted-info card)@@ -125,8 +125,7 @@;; decide whether to "flow" the Card's metadata or not (whether to use it preferentially over;; the metadata associated with Fields themselves)(assoc :qp/stage-had-source-card (:id card)- :source-query/model? (= (:type card) :model)- :source-query/entity-id (:entity-id card))+ :source-query/model? (= (:type card) :model))(dissoc :source-card))](into (vec card-stages) [stage']))))diff --git a/src/metabase/query_processor/middleware/permissions.clj b/src/metabase/query_processor/middleware/permissions.cljindex 69412e911e0..1797cef856f 100644--- a/src/metabase/query_processor/middleware/permissions.clj+++ b/src/metabase/query_processor/middleware/permissions.clj@@ -11,7 +11,6 @@[metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]][metabase.query-permissions.core :as query-perms]- [metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.store :as qp.store][metabase.util.i18n :refer [tru]][metabase.util.log :as log]@@ -22,19 +21,6 @@Card [Collection] perms checking rather than ad-hoc perms checking."nil)-(defn perms-exception- "Returns an ExceptionInfo instance containing data relevant for a permissions error."- ([required-perms]- (perms-exception (tru "You do not have permissions to run this query.") required-perms))-- ([message required-perms & [additional-ex-data]]- (ex-info message- (merge {:type qp.error-type/missing-required-permissions- :required-permissions required-perms- :actual-permissions (perms/permissions-for-user *current-user-id*)- :permissions-error? true}- additional-ex-data))))-(defenterprise check-block-permissions"OSS implementation always returns `nil` because block permissions are an EE-only feature."metabase-enterprise.advanced-permissions.models.permissions.block-permissions@@ -208,4 +194,4 @@to native.)"[{database-id :database, :as query}](when-not (current-user-has-adhoc-native-query-perms? query)- (throw (perms-exception {database-id {:perms/create-queries :query-builder-and-native}}))))+ (throw (query-perms/perms-exception {database-id {:perms/create-queries :query-builder-and-native}}))))diff --git a/src/metabase/query_processor/middleware/resolve_joins.clj b/src/metabase/query_processor/middleware/resolve_joins.cljindex 884d7b502c6..338a60b1e6d 100644--- a/src/metabase/query_processor/middleware/resolve_joins.clj+++ b/src/metabase/query_processor/middleware/resolve_joins.clj@@ -132,9 +132,13 @@"Return a flattened list of all `:fields` referenced in `joins`."[joins](into []- (comp (map :fields)- (filter sequential?)- cat)+ (mapcat (fn [{:keys [fields], :as join}]+ (when (sequential? fields)+ ;; make sure the field ref has `:join-alias`... it already SHOULD but if the query is NAUGHTY then+ ;; we better just add it in to be safe. In #61398 which is pending I actually make this happen+ ;; automatically in MBQL 5 normalization, so we can take this out eventually.+ (for [[tag id-or-name opts] fields]+ [tag id-or-name (assoc opts :join-alias (:alias join))]))))joins))(defn- should-add-join-fields?diff --git a/src/metabase/query_processor/middleware/validate.clj b/src/metabase/query_processor/middleware/validate.cljindex 22778e75403..c8d00e211de 100644--- a/src/metabase/query_processor/middleware/validate.clj+++ b/src/metabase/query_processor/middleware/validate.clj@@ -10,11 +10,10 @@(defn validate-query"Middleware that validates a query immediately after normalization."[query]- (let [explainer (mr/explainer ::lib.schema/query)]- (when-let [error (explainer query)]- (let [humanized (me/humanize error)]- (throw (ex-info (i18n/tru "Invalid query: {0}" (pr-str humanized))- {:type qp.error-type/invalid-query- :error humanized- :original error})))))+ (when-let [error (mr/explain ::lib.schema/query query)]+ (let [humanized (me/humanize error)]+ (throw (ex-info (i18n/tru "Invalid query: {0}" (pr-str humanized))+ {:type qp.error-type/invalid-query+ :error humanized+ :original error}))))query)diff --git a/src/metabase/query_processor/util/add_alias_info.clj b/src/metabase/query_processor/util/add_alias_info.cljindex d307192af58..d732201e981 100644--- a/src/metabase/query_processor/util/add_alias_info.clj+++ b/src/metabase/query_processor/util/add_alias_info.clj@@ -39,552 +39,446 @@##### `::desired-alias`If this clause is 'selected' (i.e., appears in `:fields`, `:aggregation`, or `:breakout`), select the clause `AS`- this alias. This alias is guaranteed to be unique.-- ##### `::position`-- If this clause is 'selected', this is the position the clause will appear in the results (i.e. the corresponding- column index)."+ this alias. This alias is guaranteed to be unique."+ (:refer-clojure :exclude [ref])(:require[medley.core :as m]+ [metabase.config.core :as config][metabase.driver :as driver]- [metabase.legacy-mbql.schema :as mbql.s]- [metabase.legacy-mbql.util :as mbql.u][metabase.lib.core :as lib]- [metabase.lib.field.resolution :as lib.field.resolution]- [metabase.lib.metadata :as lib.metadata]- [metabase.lib.schema.common :as lib.schema.common]- [metabase.lib.schema.id :as lib.schema.id]+ [metabase.lib.equality :as lib.equality]+ [metabase.lib.options :as lib.options]+ [metabase.lib.schema :as lib.schema]+ [metabase.lib.schema.join :as lib.schema.join][metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.util :as lib.util][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 [trs tru]][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]- [metabase.util.performance :as perf]))+ [metabase.util.malli.registry :as mr]))(def ^:private ^:dynamic ^{:arglists '([driver s])} *escape-alias-fn*#'driver/escape-alias)-(defn- prefix-field-alias- "Generate a field alias by applying `prefix` to `field-alias`. This is used for automatically-generated aliases for- columns that are the result of joins."- [prefix field-alias]- (*escape-alias-fn* driver/*driver* (str prefix "__" field-alias)))--(defn- make-unique-alias-fn- "Creates a function with the signature-- (unique-alias position original-alias)-- To return a uniquified version of `original-alias`. Memoized by `position`, so duplicate calls will result in the- same unique alias."- []- (let [unique-name-fn (lib.util/unique-name-generator)]- (fn unique-alias-fn [position original-alias]- (assert (string? original-alias)- (format "unique-alias-fn expected string, got: %s" (pr-str original-alias)))- (unique-name-fn position (*escape-alias-fn* driver/*driver* original-alias)))))--;; TODO -- this should probably limit the resulting alias, and suffix a short hash as well if it gets too long. See also-;; [[unique-alias-fn]] below.--(defn- remove-namespaced-options [options]- (not-empty- (reduce-kv (fn [m k _]- (if (qualified-keyword? k)- (dissoc m k)- m))- options options)))--(defn normalize-clause- "Normalize a `:field`/`:expression`/`:aggregation` clause by removing extra info so it can serve as a key for- `:qp/refs`. This removes `:source-field` if it is present -- don't use the output of this for anything but internal- key/distinct comparison purposes."- [clause]- (lib.util.match/match-lite clause- ;; optimization: don't need to rewrite a `:field` clause without any options- [:field _ nil]- clause-- [:field id-or-name opts]- ;; this doesn't use [[mbql.u/update-field-options]] because this gets called a lot and the overhead actually adds up- ;; a bit- [:field id-or-name (remove-namespaced-options (cond-> (dissoc opts :source-field :effective-type)- (integer? id-or-name) (dissoc :base-type)))]-- ;; for `:expression` and `:aggregation` references, remove the options map if they are empty.- [:expression expression-name opts]- (if-let [opts (remove-namespaced-options opts)]- [:expression expression-name opts]- [:expression expression-name])-- [:aggregation index opts]- (if-let [opts (-> opts- (dissoc :base-type)- (remove-namespaced-options))]- [:aggregation index opts]- [:aggregation index])-- _- clause))--(defn- selected-clauses- "Get all the clauses that are returned by this level of the query as a map of normalized-clause -> index of that- column in the results."- [{:keys [fields breakout aggregation], :as query}]- ;; this is cached for the duration of the QP run because it's a little expensive to calculate and caching this speeds- ;; up this namespace A LOT- (qp.store/cached (select-keys query [:fields :breakout :aggregation])- (into- {}- (comp cat- (map-indexed- (fn [i clause]- [(normalize-clause clause) i])))- [breakout- (map-indexed- (fn [i ag]- (lib.util.match/replace ag- ;; :offset is a special case since it doesn't NEED to get wrapped in aggregation options.- [:offset _opts _expr _n]- [:aggregation i]-- [:aggregation-options wrapped opts]- [:aggregation i]-- ;; aggregation clause should be preprocessed into an `:aggregation-options` clause by now.- _- (throw (ex-info (tru "Expected :aggregation-options clause, got {0}" (pr-str ag))- {:type qp.error-type/qp, :clause ag}))))- aggregation)- fields])))--(defn- clause->position- "Get the position (i.e., column index) `clause` is returned as, if it is returned (i.e. if it is in `:breakout`,- `:aggregation`, or `:fields`). Not all clauses are returned."- [inner-query clause]- ((selected-clauses inner-query) (normalize-clause clause)))--(defn- this-level-join-aliases [{:keys [joins]}]- (into #{} (map :alias) joins))--(defn- field-is-from-join-in-this-level? [inner-query [_field _id-or-name {:keys [join-alias]}]]- (when join-alias- ((this-level-join-aliases inner-query) join-alias)))--(mu/defn- field-instance :- [:maybe ::lib.schema.metadata/column]- [[_ id-or-name :as _field-clause] :- mbql.s/field]- (when (integer? id-or-name)- (lib.metadata/field (qp.store/metadata-provider) id-or-name)))--(defn- field-table-id [field-clause]- (:table-id (field-instance field-clause)))--(defn- resolve-field-source-table-alias-with-lib-field-resolution- "This is only an absolute last resort -- use Lib `resolve-field-ref` to resolve a field ref if the code we have here- can't do it.-- We should actually rewrite this entire namespace to just use Lib in the first place for everything, but that's a- project for another day. (See #59589)"- [inner-query field-ref]- (try- (let [lib-query (annotate.legacy-helper-fns/legacy-inner-query->mlv2-query inner-query)]- (when-let [resolved (lib.field.resolution/resolve-field-ref lib-query -1 (lib/->pMBQL field-ref))]- (cond- (= (:lib/source resolved) :source/previous-stage)- ::source-- (= (:lib/source resolved) :source/joins)- (when-let [join-alias (:metabase.lib.join/join-alias resolved)]- (get-in inner-query [::join-alias->escaped join-alias] join-alias)))))- (catch Throwable e- (log/error e "Failed to convert inner query to Lib query, unable to do fallback matching" (pr-str inner-query))- nil)))--(mu/defn- field-source-table-alias :- [:or- ::lib.schema.common/non-blank-string- ::lib.schema.id/table- [:= ::source]]- "Determine the appropriate `::source-table` alias for a `field-clause`."- [{:keys [source-table source-query], :as inner-query} [_ _id-or-name {:keys [join-alias]}, :as field-clause]]- (let [table-id (field-table-id field-clause)- join-is-this-level? (field-is-from-join-in-this-level? inner-query field-clause)]- (cond- join-is-this-level? (get-in inner-query [::join-alias->escaped join-alias] join-alias)- (and table-id (= table-id source-table)) table-id- source-query ::source- :else- (or (resolve-field-source-table-alias-with-lib-field-resolution inner-query field-clause)- (throw (ex-info (trs "Cannot determine the source table or query for Field clause {0}" (pr-str field-clause))- {:type qp.error-type/invalid-query- :clause field-clause- :query inner-query}))))))--(mr/def ::exported-clause- [:or ::mbql.s/field ::mbql.s/expression ::mbql.s/aggregation-options])--(mu/defn- exports :- [:set ::exported-clause]- [query :- ::mbql.s/SourceQuery]- (into #{} (lib.util.match/match (dissoc query :source-query :source-metadata :joins)- [(_ :guard #{:field :expression :aggregation-options}) _ (_ :guard (every-pred map? ::position))])))--(defn- join-with-alias [{:keys [joins]} join-alias]- (some (fn [join]- (when (= (:alias join) join-alias)- join))- joins))--(defn- fuzzify [clause]- (mbql.u/update-field-options clause dissoc :temporal-unit :binning))--(defn- field-signature- [field-clause]- [(second field-clause) (get-in field-clause [2 :join-alias])])--(mu/defn- field-name-match :- [:maybe ::exported-clause]- [field-name :- :string- all-exports :- [:set ::exported-clause]- source-metadata :- [:maybe [:sequential ::mbql.s/legacy-column-metadata]]- field-exports :- [:sequential ::mbql.s/field]]- ;; First, look for Expressions or fields from the source query stage whose `::desired-alias` matches the- ;; name we're searching for.- (or (m/find-first (fn [[tag _id-or-name {::keys [desired-alias], :as _opts} :as _ref]]- (when (#{:expression :field} tag)- (= desired-alias field-name)))- all-exports)- ;; Expressions by exact name.- (m/find-first (fn [[_ expression-name :as _expression-clause]]- (= expression-name field-name))- (filter (partial mbql.u/is-clause? :expression) all-exports))- ;; aggregation clauses from the previous stage based on their `::desired-alias`. If THAT doesn't work,- ;; then try to match based on their `::source-alias` (not 100% sure why we're checking `::source-alias` at- ;; all TBH -- Cam)- (when-let [ag-clauses (seq (filter (partial mbql.u/is-clause? :aggregation-options) all-exports))]- (some (fn [k]- (m/find-first (fn [[_tag _ag-clause opts :as _aggregation-options-clause]]- (= (get opts k) field-name))- ag-clauses))- [::desired-alias ::source-alias]))- ;; look for a field referenced by the name in source-metadata- (when-let [column (m/find-first #(= (:name %) field-name) source-metadata)]- (let [signature (field-signature (:field_ref column))]- (or ;; First try to match with the join alias.- (m/find-first #(= (field-signature %) signature) field-exports)- ;; Then just the names, but if the match is ambiguous, warn and return nil.- (let [matches (filter #(= (second %) field-name) field-exports)]- (when (= (count matches) 1)- (first matches))))))))--(mu/defn- matching-field-in-source-query*- [source-query :- ::mbql.s/SourceQuery- source-metadata :- [:maybe [:sequential ::mbql.s/legacy-column-metadata]]- field-clause :- ::mbql.s/field- & {:keys [normalize-fn]- :or {normalize-fn normalize-clause}}]- (let [normalized (normalize-fn field-clause)- all-exports (exports source-query)- field-exports (filter (partial mbql.u/is-clause? :field)- all-exports)]- ;; first look for an EXACT match in the `exports`- (or (m/find-first (fn [a-clause]- (= (normalize-fn a-clause) normalized))- field-exports)- ;; if there is no EXACT match, attempt a 'fuzzy' match by disregarding the `:temporal-unit` and `:binning`- (let [fuzzy-normalized (fuzzify normalized)]- (m/find-first (fn [a-clause]- (= (fuzzify (normalize-fn a-clause)) fuzzy-normalized))- field-exports))- ;; if still no match try looking based for a matching Field based on ID.- (let [[_field id-or-name _opts] field-clause]- (when (integer? id-or-name)- (or (m/find-first (fn [[_field an-id-or-name _opts]]- (= an-id-or-name id-or-name))- field-exports)- ;; look for a field referenced by the ID in source-metadata- (when-let [column (m/find-first #(= (:id %) id-or-name) source-metadata)]- (let [signature (field-signature (:field_ref column))]- (m/find-first #(= (field-signature %) signature) field-exports))))))- ;; otherwise if this is a nominal field literal ref then look for matches based on the string name used- (when-let [field-names (let [[_ id-or-name] field-clause]- (when (string? id-or-name)- [id-or-name (some-> driver/*driver* (*escape-alias-fn* id-or-name))]))]- (some #(field-name-match % all-exports source-metadata field-exports) field-names))- ;; if all of that failed then try to find a match using `:lib/deduplicated-name` (if present)- (let [[_ id-or-name] field-clause]- (when (string? id-or-name)- (when-let [col (m/find-first (fn [col]- (= (:lib/deduplicated-name col) id-or-name))- source-metadata)]- (when-let [desired-column-alias (:lib/desired-column-alias col)]- (m/find-first (fn [[_tag _id-or-name opts]]- (= (::desired-alias opts) desired-column-alias))- all-exports)))))- ;; otherwise we failed to find a match! This is expected for native queries but if the source query was MBQL- ;; there's probably something wrong.- (when-not (:native source-query)- (log/debugf "Failed to find matching field for\n\n%s\n\nin MBQL source query, query may not work! Found:\n\n%s"- (pr-str field-clause)- (u/pprint-to-str (into #{}- (map (some-fn ::desired-alias :name identity))- all-exports)))))))--(defn- matching-field-in-join-at-this-level- "If `field-clause` is the result of a join *at this level* with a `:source-query`, return the 'source' `:field` clause- from that source query."- [inner-query [_ _ {:keys [join-alias]} :as field-clause]]- (when join-alias- (let [{:keys [source-query source-metadata]} (join-with-alias inner-query join-alias)]- (when source-query- (matching-field-in-source-query*- source-query- source-metadata- field-clause- :normalize-fn #(mbql.u/update-field-options (normalize-clause %) dissoc :join-alias))))))--(defn- field-alias-in-join-at-this-level- "If `field-clause` is the result of a join at this level, return the `::desired-alias` from that join (where the Field is- introduced). This is the appropriate `::source-alias` for such a Field."- [inner-query field-clause]- (when-let [[_ _ {::keys [desired-alias]}] (matching-field-in-join-at-this-level inner-query field-clause)]- desired-alias))--(defn- matching-field-in-source-query- [{:keys [source-query source-metadata], :as inner-query} field-clause]- (when (and source-query- (= (field-source-table-alias inner-query field-clause) ::source))- (matching-field-in-source-query* source-query source-metadata field-clause)))--(defn- field-alias-in-source-query- [inner-query field-clause]- (when-let [[_tag _id-or-name {::keys [desired-alias]}] (matching-field-in-source-query inner-query field-clause)]- desired-alias))--;;; TODO (Cam 6/22/25) -- remove this method ASAP-(defmulti ^String field-reference+(defmulti ^String field-reference-mlv2"Generate a reference for the field instance `field-inst` appropriate for the driver `driver`.By default this is just the name of the field, but it can be more complicated, e.g., takeparent fields into account.- DEPRECATED: Implement [[field-reference-mlv2]] instead, which accepts a `kebab-case` Field metadata rather than- `snake_case` metadata."- {:added "0.46.0", :arglists '([driver field-inst]), :deprecated "0.48.0"}+ DEPRECATED in 0.56.0, and no longer used."+ {:added "0.48.0", :deprecated "0.57.0, " :arglists '([driver field-inst])}driver/dispatch-on-initialized-driver:hierarchy #'driver/hierarchy)-(defmulti ^String field-reference-mlv2- "Generate a reference for the field instance `field-inst` appropriate for the driver `driver`.- By default this is just the name of the field, but it can be more complicated, e.g., take- parent fields into account."- {:added "0.48.0", :arglists '([driver field-inst])}- driver/dispatch-on-initialized-driver- :hierarchy #'driver/hierarchy)+(defn- escape-fn []+ {:pre [(keyword? driver/*driver*)]}+ (let [f (lib.util/unique-name-generator)+ driver driver/*driver*]+ (fn [s]+ (->> s+ f+ (*escape-alias-fn* driver)))))++(mr/def ::desired-alias->escaped+ [:map-of ::lib.schema.metadata/desired-column-alias ::lib.schema.metadata/desired-column-alias])++;;; we add `::original` to the query so we can consistently hit the cache for things like `returned-columns` regardless+;;; of the kooky extra info we add here... none of it should affect calculated metadata++(mu/defn- returned-columns :- :metabase.lib.metadata.calculation/returned-columns+ [query :- [:merge+ ::lib.schema/query+ [:map+ [::original ::lib.schema/query]]]+ path :- ::lib.walk/path]+ (lib.walk/apply-f-for-stage-at-path lib/returned-columns (::original query) path))++(mu/defn- resolve-field-ref :- :metabase.lib.metadata.calculation/visible-column+ [query :- [:merge+ ::lib.schema/query+ [:map+ [::original ::lib.schema/query]]]+ stage-path :- ::lib.walk/path+ field-ref :- :mbql.clause/field]+ (u/prog1 (lib.walk/apply-f-for-stage-at-path lib/metadata (::original query) stage-path field-ref)+ ;; sanity check+ (when (and (or config/is-dev? config/is-test?)+ (= (:lib/source <>) :source/table-defaults)+ (pos-int? (last stage-path)))+ (throw (ex-info "Column can only come from a source table in the first stage of a query"+ {:query query, :stage-path stage-path, :col <>})))))++(mu/defn- add-escaped-desired-aliases :- [:or+ [:map+ [:lib/type [:= :mbql.stage/native]]]+ [:map+ [:lib/type [:= :mbql.stage/mbql]]+ [::desired-alias->escaped ::desired-alias->escaped]]]+ "Add a map if `::desired-alias->escaped` to each stage. This is consumed by subsequent passes and then discarded at+ the end."+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ stage :- ::lib.schema/stage]+ ;; native stages should not escape/truncate any aliases, we need to use them as-is in the next stage of the+ ;; query; see [[metabase.query-processor.util.add-alias-info-test/respect-crazy-long-native-identifiers-test]].+ ;; If a native query returns a column name we can assume it's legal in the current DB.+ (case (:lib/type stage)+ :mbql.stage/native+ stage++ (:mbql.stage/mbql :mbql/join)+ (let [returned-columns (returned-columns query path)+ escaped-aliases (into {}+ (comp+ (map :lib/desired-column-alias)+ (map (let [f (escape-fn)]+ (fn [k]+ [k (f k)]))))+ returned-columns)]+ (assoc stage ::desired-alias->escaped escaped-aliases))))++(defn- escaped-source-alias [query stage-path join-alias source-column-alias]+ (or (if join-alias+ (when-let [join (m/find-first #(= (:alias %) join-alias)+ (:joins (get-in query stage-path)))]+ (let [join-last-stage (last (:stages join))]+ (get-in join-last-stage [::desired-alias->escaped source-column-alias])))+ (when-let [previous-stage-path (lib.walk/previous-path stage-path)]+ (let [previous-stage (get-in query previous-stage-path)]+ (get-in previous-stage [::desired-alias->escaped source-column-alias]))))+ source-column-alias))++(defn- escaped-desired-alias+ "Return the escaped desired alias using the `::desired-alias->escaped` info added by [[add-escaped-desired-aliases]]+ earlier."+ [query stage-path desired-column-alias]+ (when desired-column-alias+ (case (:lib/type (get-in query stage-path))+ ;; for native stages just return desired-column-alias without escaping (see comment+ ;; in [[add-escaped-desired-aliases]] for more info)+ :mbql.stage/native+ desired-column-alias++ :mbql.stage/mbql+ (let [desired-alias->escaped (or (::desired-alias->escaped (get-in query stage-path))+ (throw (ex-info "Stage is missing ::desired-alias->escaped"+ {:stage-path stage-path})))]+ (or (get desired-alias->escaped desired-column-alias)+ (throw (ex-info (format "Missing ::desired-alias->escaped for %s" (pr-str desired-column-alias))+ {:path stage-path+ :desired-alias desired-column-alias+ :desired-alias->escaped desired-alias->escaped})))))))++(defn- escaped-join-alias [query stage-path join-alias]+ (when join-alias+ (let [stage (get-in query stage-path)+ _ (when (empty? (:joins stage))+ (throw (ex-info "Stage has no joins, are you sure this is the right path?"+ {:path stage-path, :join-alias join-alias})))+ join-alias->escaped (or (::join-alias->escaped stage)+ (throw (ex-info "Stage is missing ::join-alias->escaped"+ {:path stage-path, :join-alias join-alias})))]+ (or (get join-alias->escaped join-alias)+ (throw (ex-info (format "Missing ::join-alias->escaped entry for %s" (pr-str join-alias))+ {:path stage-path, :join-alias join-alias}))))))++(defn- source-table [query stage-path col]+ (case (:lib/source col)+ :source/table-defaults (:table-id col)+ (:source/joins+ :source/implicitly-joinable) (or (escaped-join-alias query stage-path (:metabase.lib.join/join-alias col))+ (throw (ex-info "Resolved metadata is missing ::escaped-join-alias" {:col col})))+ (:source/previous-stage+ :source/card) ::source+ (:source/expressions+ :source/aggregations+ :source/native) ::none))++(defn- add-source-to-field-ref [query path field-ref col]+ (lib/update-options+ field-ref #(-> %+ (assoc ::source-table (source-table query path col)+ ::source-alias (escaped-source-alias query path (:metabase.lib.join/join-alias col) (:lib/source-column-alias col)))+ (m/assoc-some ::nfc-path (not-empty (:nfc-path col))))))++(defn- fix-field-ref-if-it-should-actually-be-an-expression-ref+ "I feel evil about doing this, since generally this namespace otherwise just ADDs info and does not in any other way+ modify the query, but I can't think of any other way to get queries that accidentally use a `:field` ref for an+ `:expression` to work correctly."+ [field-ref col]+ (if (= (:lib/source col) :source/expressions)+ (into [:expression] (rest field-ref))+ field-ref))++(mu/defn- add-source-aliases :- ::lib.schema/stage.mbql+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ stage :- ::lib.schema/stage.mbql]+ (lib.util.match/replace stage+ ;; don't recurse into the metadata or joins -- [[lib.walk]] will take care of that recursion for us.+ (_ :guard (constantly (some (set &parents) [:lib/stage-metadata :joins])))+ &match++ :field+ (let [col (resolve-field-ref query path &match)]+ (-> (add-source-to-field-ref query path &match col)+ (fix-field-ref-if-it-should-actually-be-an-expression-ref col)+ ;; record the column we resolved it to, so we can use this when we add desired aliases in the next pass.+ (lib/update-options assoc ::resolved col)))++ :expression+ (lib/update-options &match assoc ::source-table ::none)++ :aggregation+ (lib/update-options &match assoc ::source-table ::none)))++(mu/defn- add-desired-aliases-to-aggregations :- ::lib.schema/stage.mbql+ "Update any aggregations FIRST so we can use their aliases when updating aggregation refs"+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ returned-columns :- :metabase.lib.metadata.calculation/returned-columns+ stage :- ::lib.schema/stage.mbql]+ (letfn [(resolve-aggregation [[_tag opts, :as ag-clause]]+ (or (m/find-first #(and (= (:lib/source %) :source/aggregations)+ (= (:lib/source-uuid %) (:lib/uuid opts)))+ returned-columns)+ (throw (ex-info "aggregation definition was not resolved"+ {:aggregation ag-clause}))))+ (update-aggregation [ag-clause]+ (let [col (resolve-aggregation ag-clause)+ desired-alias (escaped-desired-alias query path (or (:lib/desired-column-alias col)+ (throw (ex-info "Resolved aggregation is missing :lib/desired-column-alias"+ {:ag-clause ag-clause, :col col}))))]+ (lib/update-options ag-clause assoc+ ;; TODO (Cam 8/8/25) -- not really convinced it makes sense for an aggregation+ ;; definition to have a `::source-table` or `::source-alias` given that it comes from+ ;; the current stage, but I don't want to break something that might have been using+ ;; it for weird purposes, so I guess we can just keep including it.+ ::source-table ::none+ ::source-alias (:lib/desired-column-alias col)+ ::desired-alias desired-alias)))+ (update-aggregations [aggregations]+ (mapv update-aggregation aggregations))]+ (m/update-existing stage :aggregation update-aggregations)))++(mu/defn- add-desired-aliases-to-refs :- ::lib.schema/stage.mbql+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ returned-columns :- :metabase.lib.metadata.calculation/returned-columns+ stage :- ::lib.schema/stage.mbql]+ (lib.util.match/replace stage+ ;; don't recurse into the metadata or joins -- [[lib.walk]] will take care of that recursion for us.+ (_ :guard (constantly (some (set &parents) [:lib/stage-metadata :joins ::resolved])))+ &match++ [:field opts _id-or-name]+ (let [col (m/find-first #(lib.equality/= % (or (::resolved opts)+ (throw (ex-info "Missing ::resolved -- should have been added by add-source-aliases"+ {:field-ref &match+ :path (concat path &parents)}))))+ returned-columns)]+ (-> &match+ (lib/update-options (fn [opts]+ (-> opts+ (assoc ::desired-alias (escaped-desired-alias query path (:lib/desired-column-alias col)))+ (dissoc ::resolved))))))++ [:expression _opts expression-name]+ (let [col (m/find-first #(= (:lib/expression-name %) expression-name)+ returned-columns)]+ (lib/update-options &match assoc ::desired-alias (escaped-desired-alias query path (:lib/desired-column-alias col))))++ [:aggregation _opts uuid]+ (let [aggregation (or (m/find-first #(= (lib.options/uuid %) uuid)+ (:aggregation stage))+ (log/errorf "No aggregation matching %s" (pr-str uuid)))]+ (lib/update-options &match merge (select-keys (lib/options aggregation) [::source-table ::source-alias ::desired-alias])))))++(mu/defn- add-desired-aliases :- ::lib.schema/stage.mbql+ [query :- ::lib.schema/query+ path :- ::lib.walk/path+ stage :- ::lib.schema/stage.mbql]+ (let [returned-columns (returned-columns query path)]+ (->> stage+ (add-desired-aliases-to-aggregations query path returned-columns)+ (add-desired-aliases-to-refs query path returned-columns))))++(mu/defn- add-alias-info-to-stage :- ::lib.schema/stage+ [query :- ::lib.schema/query+ stage-path :- ::lib.walk/path+ stage :- ::lib.schema/stage]+ (case (:lib/type stage)+ :mbql.stage/native+ stage++ :mbql.stage/mbql+ (try+ (->> stage+ (add-source-aliases query stage-path)+ (add-desired-aliases query stage-path))+ (catch Throwable e+ (throw (ex-info (format "Error adding alias info to stage: %s" (ex-message e))+ {:stage-path stage-path, :stage stage}+ e))))))++(defn- update-ref-from-this-join [query+ join-path+ join+ [_tag opts _id-or-name, :as field-ref]]+ (let [parent-stage-path (lib.walk/join-parent-stage-path join-path)+ ;; the refs inside a join conditions should use the `:lib/desired-column-alias` from the columns returned by the+ ;; join's last stage. Thus the last stage of a join is effectively a 'previous stage' for purposes of field ref+ ;; resolution. Since there is no actual 'current stage' to use in this case, fake it by adding one more stage to+ ;; the join, which will let [[resolve-field-ref]] work as intended and resolve the ref relative to this extra+ ;; fake stage.+ query' (-> query+ ;; update the cached `::original` query instead of query itself, since this is+ ;; what [[resolve-field-ref]] uses.+ (update-in (into [::original] join-path)+ (fn [join]+ (update join :stages (fn [stages]+ (conj (vec stages) {:lib/type :mbql.stage/mbql}))))))+ ;; e.g. if join has one stage, `join-last-stage-path` could be something like `[:stages 0 :joins 0 :stages 0]`+ ;; and `join-extra-stage-path` would be `[:stages 0 :joins 0 :stages 1]`+ join-last-stage-path (lib.walk/join-last-stage-path join-path join)+ join-extra-stage-path (-> (vec join-last-stage-path)+ pop+ (conj (inc (last join-last-stage-path))))+ col (resolve-field-ref+ query'+ join-extra-stage-path+ ;; join alias is for use outside the join, a column doesn't have the join alias INSIDE+ ;; the join itself.+ (lib/with-join-alias field-ref nil))+ last-stage-alias (or (:lib/source-column-alias col)+ (throw (ex-info "Expected resolved column to have :lib/source-column-alias"+ {:path join-path+ :join join+ :ref field-ref+ :col col})))+ source-alias (escaped-desired-alias query (lib.walk/join-last-stage-path join-path join) last-stage-alias)+ source-table (escaped-join-alias query parent-stage-path (:join-alias opts))]+ ;; don't need to calculate `::desired-alias` because it may not be returned and even if it is it's not getting+ ;; returned in the join conditions+ (lib/update-options field-ref assoc+ ::source-alias source-alias+ ::source-table source-table)))++(mu/defn- add-alias-info-to-join-conditions :- ::lib.schema.join/join+ "Add alias info to refs in join `:conditions`. Join `:fields` do not need to be updated since they are only used to+ update parent stage `:fields` as appropriate (which will have already been done by now) and otherwise do not directly+ affect the resulting SQL (i.e., drivers should not be looking at them anyway)."+ [query :- ::lib.schema/query+ join-path :- ::lib.walk/path+ join :- ::lib.schema.join/join]+ (let [parent-stage-path (lib.walk/join-parent-stage-path join-path)+ update-other-ref (fn [field-ref]+ (let [col (resolve-field-ref query parent-stage-path field-ref)]+ (add-source-to-field-ref query parent-stage-path field-ref col)))+ update-conditions (fn [conditions]+ ;; the only kind of ref join conditions can have is a `:field` ref+ (lib.util.match/replace conditions+ ;; a field ref that comes from THIS join needs to get the desired alias returned+ ;; by the last stage of the join to use as its source alias+ [:field (_opts :guard #(= (:join-alias %) (:alias join))) _id-or-name]+ (update-ref-from-this-join query join-path join &match)++ ;; a field ref that DOES NOT come from this join should get resolved relative to+ ;; the parent stage.+ [:field (_opts :guard #(not= (:join-alias %) (:alias join))) _id-or-name]+ (update-other-ref &match)))]+ (try+ (update join :conditions update-conditions)+ (catch Throwable e+ (throw (ex-info (format "Error adding alias info to join: %s" (ex-message e))+ {:join-path join-path, :join join}+ e))))))++(defn- add-escaped-alises-to-join [query path join]+ (let [parent-stage-path (-> (vec path) pop pop)+ escaped-alias (escaped-join-alias query parent-stage-path (:alias join))]+ (assoc join+ ::original-alias (:alias join)+ ::alias escaped-alias)))++;;; the query returned by this is not necessarily valid anymore; see comments below+(mu/defn- add-alias-info** :- ::lib.schema/query+ [query :- ::lib.schema/query]+ (as-> query query+ ;; next walk all stages and for all returned columns add a map of lib/desired-column-alias => escaped-desired-alias+ (lib.walk/walk-stages query add-escaped-desired-aliases)+ ;; then walk all the stages AND joins and update the refs+ (lib.walk/walk query (fn [query path-type path stage-or-join]+ (case path-type+ :lib.walk/stage+ (add-alias-info-to-stage query path stage-or-join)++ :lib.walk/join+ (add-alias-info-to-join-conditions query path stage-or-join))))+ (lib.walk/walk query (fn [query path-type path join]+ (when (= path-type :lib.walk/join)+ (add-escaped-alises-to-join query path join))))))++(mr/def ::options+ [:map+ {:closed true}+ [:globally-unique-join-aliases? {:default false} :any]])++(mu/defn- escape-join-aliases :- ::lib.schema/query+ [query :- ::lib.schema/query+ {:keys [globally-unique-join-aliases?], :or {globally-unique-join-aliases? false}} :- [:maybe ::options]]+ (let [make-join-alias-unique-name-generator (if globally-unique-join-aliases?+ (constantly (lib.util/unique-name-generator))+ lib.util/unique-name-generator)]+ (lib.walk/walk-stages+ query+ (fn [_query _path stage]+ (if (empty? (:joins stage))+ stage+ (-> stage+ (update :joins (let [unique (comp (partial *escape-alias-fn* driver/*driver*)+ (make-join-alias-unique-name-generator))]+ (fn [joins]+ (mapv (mu/fn [join :- [:map+ [:alias ::lib.schema.join/alias]]]+ (assoc join ::alias (unique (:alias join))))+ joins))))+ (as-> $stage (assoc $stage ::join-alias->escaped (into {} (map (juxt :alias ::alias)) (:joins $stage))))))))))++(defn- clean-up-our-mess+ "Walk the query and remove the extra keys we added to stages and joins."+ [query]+ (lib.walk/walk+ query+ (fn [_query _path-type _path stage-or-join]+ (dissoc stage-or-join ::join-alias->escaped ::desired-alias->escaped))))++(mu/defn- add-alias-info* :- ::lib.schema/query+ [query :- ::lib.schema/query+ options :- [:maybe ::options]]+ (try+ (-> query+ (escape-join-aliases options)+ (assoc ::original query)+ add-alias-info**+ clean-up-our-mess+ (dissoc ::original))+ (catch Throwable e+ (throw (ex-info (format "Error adding alias info to query: %s" (ex-message e))+ {:query query, :options options}+ e)))))-(mu/defmethod field-reference-mlv2 ::driver/driver- [driver :- :keyword- field :- ::lib.schema.metadata/column]- #_{:clj-kondo/ignore [:deprecated-var]}- (if (get-method field-reference driver)- (do- ;; We should not be reaching into driver implementations- ((requiring-resolve 'metabase.driver.sql.query-processor.deprecated/log-deprecation-warning)- driver- `field-reference- "0.48.0")- (field-reference driver- #_{:clj-kondo/ignore [:deprecated-var]}- (qp.store/->legacy-metadata field)))- (:name field)))--(defn- field-nfc-path- "Nested field components path for field, so drivers can use in identifiers."- [field-clause]- (some-> field-clause field-instance :nfc-path not-empty vec))--(defn- field-requires-original-field-name- "JSON extraction fields need to be named with their outer `field-name`, not use any existing `::desired-alias`."- [field-clause]- (boolean (field-nfc-path field-clause)))--(mu/defn- field-name :- [:maybe :string]- "*Actual* name of a `:field` from the database or source query (for Field literals)."- [_inner-query [_ id-or-name :as field-clause] :- mbql.s/field]- (or (some->> field-clause- field-instance- (field-reference-mlv2 driver/*driver*))- (when (string? id-or-name)- id-or-name)))--(mu/defn- expensive-field-info- "Calculate extra stuff about `field-clause` that's a little expensive to calculate. This is done once so we can pass- it around instead of recalculating it a bunch of times."- [inner-query :- :map- field-clause :- mbql.s/field]- (merge- {:field-name (field-name inner-query field-clause)- :override-alias? (field-requires-original-field-name field-clause)- :join-is-this-level? (field-is-from-join-in-this-level? inner-query field-clause)- :alias-from-join (field-alias-in-join-at-this-level inner-query field-clause)- :alias-from-source-query (field-alias-in-source-query inner-query field-clause)}- (when-let [nfc-path (field-nfc-path field-clause)]- {:nfc-path nfc-path})))--(defn- field-source-alias- "Determine the appropriate `::source-alias` for a `field-clause`."- {:arglists '([inner-query field-clause expensive-field-info])}- [{:keys [_source-table], :as _inner-query}- [_ _id-or-name {:keys [join-alias]}, :as _field-clause]- {:keys [field-name join-is-this-level? alias-from-join alias-from-source-query]}]- (cond- ;; TODO -- this just recalculates the info instead of actually finding the Field in the join and getting its desired- ;; alias there... this seems like a clear bug since it doesn't go thru the uniquify logic. Something will- ;; potentially break by doing this. I haven't been able to reproduce it yet however.- ;;- ;; This will only be triggered if the join somehow exposes duplicate columns or columns that have the same escaped- ;; name after going thru [[*escape-alias-fn*]]. I think the only way this could happen is if we escape them- ;; aggressively but the escape logic produces duplicate columns (i.e., there is overlap between the unique hashes we- ;; suffix to escaped identifiers.)- ;;- ;; We'll have to look into this more in the future. For now, it seems to work for everything we try it with.- (and join-is-this-level? alias-from-join) alias-from-join- alias-from-source-query alias-from-source-query- (and join-alias (not join-is-this-level?)) (prefix-field-alias join-alias field-name)- :else field-name))--(defn- field-desired-alias- "Determine the appropriate `::desired-alias` for a `field-clause`."- {:arglists '([inner-query field-clause expensive-field-info])}- [_inner-query- [_ _id-or-name {:keys [join-alias], ::keys [desired-alias], explicit-name :name} :as _field-clause]- {:keys [field-name alias-from-join alias-from-source-query override-alias?], :as _expensive-field-info}]- (cond- join-alias (prefix-field-alias join-alias (or alias-from-join field-name))- ;; JSON fields and similar have to be aliased by the outer field name.- override-alias? field-name- explicit-name explicit-name- desired-alias desired-alias- alias-from-source-query alias-from-source-query- :else field-name))--(defmulti ^:private clause-alias-info- {:arglists '([inner-query unique-alias-fn clause])}- (fn [_ _ [clause-type]]- clause-type))--(mu/defmethod clause-alias-info :field- [inner-query :- :map- unique-alias-fn :- fn?- field-clause :- mbql.s/field]- (let [expensive-info (expensive-field-info inner-query field-clause)]- (merge {::source-table (field-source-table-alias inner-query field-clause)- ::source-alias (field-source-alias inner-query field-clause expensive-info)}- (when-let [nfc-path (:nfc-path expensive-info)]- {::nfc-path nfc-path})- (when-let [position (clause->position inner-query field-clause)]- {::desired-alias (unique-alias-fn position (field-desired-alias inner-query field-clause expensive-info))- ::position position}))))--(defmulti ^:private aggregation-name- {:arglists '([mbql-clause])}- (fn [x]- (when (mbql.u/mbql-clause? x)- (first x))))--;;; make sure we have an `:aggregation-options` or other fully-preprocessed aggregation clause (i.e., `:offset`) like we-;;; expect. This is mostly a precondition check since we should never be running this code on not-preprocessed queries,-;;; so it's not i18n'ed-(defmethod aggregation-name :default- [ag-clause]- (throw (ex-info (format "Expected :aggregation-options or other fully-preprocessed aggregation, got %s."- (pr-str ag-clause))- {:clause ag-clause})))--(mu/defmethod aggregation-name :aggregation-options :- :string- [[_aggregation-options _wrapped-ag opts]]- (:name opts))--(mu/defmethod aggregation-name :offset :- :string- [[_offset opts _expr _n]]- (:name opts))--(defmethod clause-alias-info :aggregation- [{aggregations :aggregation, :as inner-query} unique-alias-fn [_ index _opts :as ag-ref-clause]]- (let [position (clause->position inner-query ag-ref-clause)]- ;; an aggregation is ALWAYS returned, so it HAS to have a `position`. If it does not, the aggregation reference- ;; is busted.- (when-not position- (throw (ex-info (tru "Aggregation does not exist at index {0}" index)- {:type qp.error-type/invalid-query- :clause ag-ref-clause- :query inner-query})))- (let [ag-name (aggregation-name (nth aggregations index))]- {::desired-alias (unique-alias-fn position ag-name)- ::position position})))--(defmethod clause-alias-info :expression- [inner-query unique-alias-fn [_ expression-name :as expression-ref-clause]]- (when-let [position (clause->position inner-query expression-ref-clause)]- {::desired-alias (unique-alias-fn position expression-name)- ::position position}))--(defn- add-info-to-aggregation-definition- [inner-query unique-alias-fn ag-clause ag-index]- (lib.util.match/replace ag-clause- [:offset opts expr n]- (let [position (clause->position inner-query [:aggregation ag-index])- original-ag-name (:name opts)- unique-alias (unique-alias-fn position original-ag-name)]- [:offset (assoc opts- :name unique-alias- ::source-alias original-ag-name- ::position position- ::desired-alias unique-alias)- expr- n])-- [:aggregation-options wrapped-ag-clause opts, :as _ag-clause]- (let [position (clause->position inner-query [:aggregation ag-index])- original-ag-name (:name opts)- unique-alias (unique-alias-fn position original-ag-name)]- [:aggregation-options wrapped-ag-clause (assoc opts- :name unique-alias- ::source-alias original-ag-name- ::position position- ::desired-alias unique-alias)])))--(defn- add-info-to-aggregation-definitions [{aggregations :aggregation, :as inner-query} unique-alias-fn]- (cond-> inner-query- (seq aggregations)- (update :aggregation (fn [aggregations]- (into- []- (map-indexed (fn [i aggregation]- (add-info-to-aggregation-definition inner-query unique-alias-fn aggregation i)))- aggregations)))))--(mu/defn- add-alias-info* :- ::mbql.s/SourceQuery- [inner-query :- ::mbql.s/SourceQuery]- (assert (not (:strategy inner-query)) "add-alias-info* should not be called on a join") ; not user-facing- (let [unique-alias-fn (make-unique-alias-fn)]- (-> (lib.util.match/replace inner-query- ;; don't rewrite anything inside any source queries or source metadata.- (_ :guard (constantly (some (partial contains? (set &parents))- [:source-query :source-metadata])))- &match-- #{:field :aggregation :expression}- (mbql.u/update-field-options &match merge (clause-alias-info inner-query unique-alias-fn &match)))- (add-info-to-aggregation-definitions unique-alias-fn))))--(defn add-alias-info+(mu/defn add-alias-info :- :map"Add extra info to `:field` clauses, `:expression` references, and `:aggregation` references in `query`. `query` mustbe fully preprocessed.+ Works on MBQL 5 queries, MBQL 4 (legacy) outer queries, or MBQL 4 inner queries.+Adds some or all of the following keys:### `::source-table`@@ -605,39 +499,34 @@If this clause is 'selected' (i.e., appears in `:fields`, `:aggregation`, or `:breakout`), select the clause `AS`this alias. This alias is guaranteed to be unique.- ### `::position`-- If this clause is 'selected', this is the position the clause will appear in the results (i.e. the corresponding- column index)."- ([query-or-inner-query]- (add-alias-info query-or-inner-query nil))-- ([query-or-inner-query {:keys [globally-unique-join-aliases?], :or {globally-unique-join-aliases? false}}]- (let [make-join-alias-unique-name-generator (if globally-unique-join-aliases?- (constantly (lib.util/unique-name-generator))- lib.util/unique-name-generator)]- (as-> query-or-inner-query $q- ;; first escape all the join aliases- (perf/postwalk- (fn [form]- (if (and (map? form)- (seq (:joins form)))- (as-> form form- (update form :joins (let [unique (comp (partial *escape-alias-fn* driver/*driver*)- (make-join-alias-unique-name-generator))]- (fn [joins]- (mapv (fn [join]- (assoc join ::alias (unique (:alias join))))- joins))))- (assoc form ::join-alias->escaped (into {} (map (juxt :alias ::alias)) (:joins form))))- form))- $q)- ;; then add alias info- (perf/postwalk- (fn [form]- (if (and (map? form)- ((some-fn :source-query :source-table) form)- (not (:strategy form)))- (vary-meta (add-alias-info* form) assoc ::transformed true)- form))- $q)))))+ ### `::nfc-path`++ If this is a nested column, the path to the column, e.g. for `grandparent.parent.child` this will be `[\"grandparent\"+ \"child\"]."+ ([query]+ (add-alias-info query nil))++ ([query :- :map+ options :- [:maybe ::options]]+ (cond+ ;; MBQL 5 query+ (= (:lib/type query) :mbql/query)+ (add-alias-info* query options)++ ;; MBQL 4 outer query+ (:type query)+ (-> (lib/query (qp.store/metadata-provider) query)+ (add-alias-info* options)+ lib/->legacy-MBQL)++ ;; MBQL 4 inner MBQL query+ ((some-fn :source-table :source-query) query)+ (-> query+ annotate.legacy-helper-fns/legacy-inner-query->mlv2-query+ (add-alias-info options)+ lib/->legacy-MBQL+ :query)++ :else+ (throw (ex-info "Don't know what type of query this is, cannot add-alias-info!"+ {:query query, :type qp.error-type/qp})))))diff --git a/src/metabase/query_processor/util/nest_query.clj b/src/metabase/query_processor/util/nest_query.cljindex 495a66742ef..1b0d0a66672 100644--- a/src/metabase/query_processor/util/nest_query.clj+++ b/src/metabase/query_processor/util/nest_query.clj@@ -50,9 +50,48 @@all-fields)))outer-query))+(defn- remove-namespaced-options [options]+ (when options+ (not-empty (into {}+ (remove (fn [[k _]]+ (qualified-keyword? k)))+ options))))++;;; TODO (Cam 6/16/25) -- duplicated with [[metabase.query-processor.middleware.resolve-joins/normalize-clause]], but+;;; this doesn't matter much since we will rewrite this whole namespace in MLv2 soon.+(defn- normalize-clause+ "Normalize a `:field`/`:expression`/`:aggregation` clause by removing extra info so it can serve as a key for+ `:qp/refs`. This removes `:source-field` if it is present -- don't use the output of this for anything but internal+ key/distinct comparison purposes."+ [clause]+ (lib.util.match/match-one clause+ ;; optimization: don't need to rewrite a `:field` clause without any options+ [:field _ nil]+ &match++ [:field id-or-name opts]+ ;; this doesn't use [[mbql.u/update-field-options]] because this gets called a lot and the overhead actually adds up+ ;; a bit+ [:field id-or-name (remove-namespaced-options (cond-> (dissoc opts :source-field :effective-type)+ (integer? id-or-name) (dissoc :base-type)))]++ ;; for `:expression` and `:aggregation` references, remove the options map if they are empty.+ [:expression expression-name opts]+ (if-let [opts (remove-namespaced-options opts)]+ [:expression expression-name opts]+ [:expression expression-name])++ [:aggregation index opts]+ (if-let [opts (remove-namespaced-options opts)]+ [:aggregation index opts]+ [:aggregation index])++ _+ &match))+(defn- joined-fields [inner-query](m/distinct-by- add/normalize-clause+ normalize-clause(lib.util.match/match (walk/prewalk (fn [x](if (map? x)(dissoc x :source-query :source-metadata :temporal-unit)@@ -93,24 +132,24 @@[:field source-alias {::add/source-table ::add/source}]))(defn- remove-unused-fields [inner-query source]- (let [usages (lib.util.match/match inner-query #{:field :expression})- used-fields (into #{} (map keep-source+alias-props) usages)- nominal-fields (into #{} (keep ->nominal-ref) usages)- nfc-roots (into #{} (keep nfc-root) used-fields)]- (letfn [(used? [[_tag _id-or-name {::add/keys [source-table]}, :as field]]- (or (contains? used-fields (keep-source+alias-props field))+ (let [usages (lib.util.match/match inner-query #{:field :expression})+ used-refs (into #{} (map keep-source+alias-props) usages)+ nominal-refs (into #{} (keep ->nominal-ref) usages)+ nfc-roots (into #{} (keep nfc-root) used-refs)]+ (letfn [(used? [[_tag _id-or-name {::add/keys [source-table]}, :as a-ref]]+ (or (contains? used-refs (keep-source+alias-props a-ref));; We should also consider a Field to be used if we're referring to it with a nominal field literal;; ref in the next stage -- that's actually how you're supposed to be doing it anyway.(and (= source-table ::add/source)- (contains? nominal-fields (->nominal-ref field)))- (contains? nfc-roots (field-id-props field))))- (used?* [field]- (u/prog1 (used? field)+ (contains? nominal-refs (->nominal-ref a-ref)))+ (contains? nfc-roots (field-id-props a-ref))))+ (used?* [a-ref]+ (u/prog1 (used? a-ref)(if <>- (log/debugf "Keeping used field:\n%s" (u/pprint-to-str field))- (log/debugf "Removing unused field:\n%s" (u/pprint-to-str (keep-source+alias-props field))))))- (remove-unused [fields]- (filterv used?* fields))]+ (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))](update source :fields remove-unused))))(defn- append-join-fieldsdiff --git a/src/metabase/sync/interface.clj b/src/metabase/sync/interface.cljindex e16a1bd650a..1564db2b87b 100644--- a/src/metabase/sync/interface.clj+++ b/src/metabase/sync/interface.clj@@ -45,7 +45,8 @@[:pk? {:optional true} :boolean] ; optional for databases that don't support PKs[:nested-fields {:optional true} [:set [:ref ::TableMetadataField]]][:json-unfolding {:optional true} :boolean]- [:nfc-path {:optional true} [:any]]+ ;; TODO (Cam 8/11/25) -- this should be required to be a sequence of strings but we'll need to go fix some code+ [:nfc-path {:optional true} [:maybe [:sequential [:or :keyword :string]]]][:custom {:optional true} :map][:database-is-auto-increment {:optional true} :boolean];; nullable for databases that don't support field partitiondiff --git a/src/metabase/util/malli.cljc b/src/metabase/util/malli.cljcindex dcee4b4e802..a1ad9dd202a 100644--- a/src/metabase/util/malli.cljc+++ b/src/metabase/util/malli.cljc@@ -150,11 +150,11 @@(mc/walkschema(mc/schema-walker- (fn [schema]+ (core/fn [schema](case (mc/type schema):map(mc/-set-children schema- (mapv (fn [[k p s]]+ (mapv (core/fn [[k p s]][k (dissoc p :optional) s]) (mc/children schema))):maybe(first (mc/children schema))@@ -166,10 +166,10 @@[schema](mc/walkschema- (mc/schema-walker (fn [schema]+ (mc/schema-walker (core/fn [schema](if (= :map (mc/type schema))(mc/-set-children schema- (mapv (fn [[k p s]]+ (mapv (core/fn [[k p s]][(u/->snake_case_en k) p s]) (mc/children schema)))schema)))))diff --git a/test/metabase/driver/h2_test.clj b/test/metabase/driver/h2_test.cljindex 445ce2e601d..d09443f0bad 100644--- a/test/metabase/driver/h2_test.clj+++ b/test/metabase/driver/h2_test.clj@@ -18,7 +18,6 @@[metabase.query-processor :as qp][metabase.query-processor.compile :as qp.compile][metabase.test :as mt]- [metabase.util :as u][metabase.util.honey-sql-2 :as h2x][toucan2.core :as t2]))@@ -222,7 +221,7 @@(deftest ^:parallel check-action-commands-test(mt/test-driver :h2#_{:clj-kondo/ignore [:equals-true]}- (are [query] (= true (#'h2/every-command-allowed-for-actions? (#'h2/classify-query (u/the-id (mt/db)) query)))+ (are [query] (= true (#'h2/every-command-allowed-for-actions? (#'h2/classify-query (mt/id) query)))"select 1""update venues set name = 'bill'""delete venues"@@ -243,7 +242,7 @@"create table venues""alter table venues add column address varchar(255)")- (are [query] (= false (#'h2/every-command-allowed-for-actions? (#'h2/classify-query (u/the-id (mt/db)) query)))+ (are [query] (= false (#'h2/every-command-allowed-for-actions? (#'h2/classify-query (mt/id) query)))"select * from venues; update venues set name = 'stomp';CREATE ALIAS EXEC AS 'String shellexec(String cmd) throws java.io.IOException {Runtime.getRuntime().exec(cmd);return \"y4tacker\";}';EXEC ('open -a Calculator.app')"@@ -251,10 +250,10 @@CREATE ALIAS EXEC AS 'String shellexec(String cmd) throws java.io.IOException {Runtime.getRuntime().exec(cmd);return \"y4tacker\";}';""CREATE ALIAS EXEC AS 'String shellexec(String cmd) throws java.io.IOException {Runtime.getRuntime().exec(cmd);return \"y4tacker\";}';")- (is (= nil (#'h2/check-action-commands-allowed {:database (u/the-id (mt/db)) :native {:query nil}})))+ (is (= nil (#'h2/check-action-commands-allowed {:database (mt/id) :native {:query nil}})))(is (= nil (#'h2/check-action-commands-allowed- {:database (u/the-id (mt/db))+ {:database (mt/id):engine :h2:native {:query (str/join "; "["select 1"@@ -266,7 +265,7 @@(is (thrown? clojure.lang.ExceptionInfo#"DDL commands are not allowed to be used with h2."(#'h2/check-action-commands-allowed- {:database (u/the-id (mt/db))+ {:database (mt/id):engine :h2:native {:query trigger-creation-attempt}}))))))diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.cljindex da3c0cfaa81..5504fe4cc74 100644--- a/test/metabase/driver/postgres_test.clj+++ b/test/metabase/driver/postgres_test.clj@@ -215,9 +215,9 @@(sync/sync-database! (mt/db) {:scan :schema})(is (= [[42]](mt/rows (qp/process-query- {:database (u/the-id (mt/db))+ {:database (mt/id):type :query- :query {:source-table (t2/select-one-pk :model/Table :db_id (:id (mt/db)))}})))))))))+ :query {:source-table (t2/select-one-pk :model/Table :db_id (mt/id))}})))))))))(mt/defdataset duplicate-names[["birds"diff --git a/test/metabase/driver/sql/query_processor_test.clj b/test/metabase/driver/sql/query_processor_test.cljindex 7cad82537d7..180761c2e4d 100644--- a/test/metabase/driver/sql/query_processor_test.clj+++ b/test/metabase/driver/sql/query_processor_test.clj@@ -16,6 +16,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.compile :as qp.compile][metabase.query-processor.middleware.limit :as limit][metabase.query-processor.preprocess :as qp.preprocess][metabase.query-processor.store :as qp.store]@@ -23,7 +24,6 @@[metabase.settings.core :as setting][metabase.test :as mt][metabase.test.data.env :as tx.env]- [metabase.test.data.interface :as tx][metabase.util.date-2 :as u.date][metabase.util.honey-sql-2 :as h2x][metabase.util.malli.registry :as mr]))@@ -470,10 +470,10 @@;; order. Changing the map keys on the inner query can perturb this order; if you;; cause this test to fail based on shuffling the order of these joined fields;; just edit the expectation to match the new order. Tech debt issue: #39396- PRODUCTS__via__PRODUCT_ID.CATEGORY AS PRODUCTS__via__PRODUCT_ID__CATEGORY- PEOPLE__via__USER_ID.SOURCE AS PEOPLE__via__USER_ID__SOURCEPRODUCTS__via__PRODUCT_ID.ID AS PRODUCTS__via__PRODUCT_ID__ID- PEOPLE__via__USER_ID.ID AS PEOPLE__via__USER_ID__ID]+ PEOPLE__via__USER_ID.ID AS PEOPLE__via__USER_ID__ID+ PRODUCTS__via__PRODUCT_ID.CATEGORY AS PRODUCTS__via__PRODUCT_ID__CATEGORY+ PEOPLE__via__USER_ID.SOURCE AS PEOPLE__via__USER_ID__SOURCE]:from [ORDERS]:left-join [{:select [PRODUCTS.ID AS IDPRODUCTS.EAN AS EAN@@ -819,7 +819,7 @@(deftest ^:parallel expression-with-duplicate-column-name-test(testing "Can we use expression with same column name as table (#14267)"- (is (= '{:select [source.CATEGORY_2 AS CATEGORY+ (is (= '{:select [source.CATEGORY_2 AS CATEGORY_2COUNT (*) AS count]:from [{:select [PRODUCTS.CATEGORY AS CATEGORYCONCAT (PRODUCTS.CATEGORY ?) AS CATEGORY_2]@@ -1365,61 +1365,79 @@(sql.qp/coerce-integer :sql(h2x/with-database-type-info value type))))))))-(defmulti native-nested-array-query- {:arglists '([driver])}- tx/dispatch-on-driver-with-test-extensions- :hierarchy #'driver/hierarchy)--(defmethod native-nested-array-query :default- [_driver]- "select array[array[array['a', 'b'], array['c', 'd'] ], array[array['w', 'x'], array['y', 'z'] ]];")--(doseq [driver [:mysql :sqlite]]- (defmethod native-nested-array-query driver- [_driver]- "select json_array(json_array(json_array('a', 'b'), json_array('c', 'd')), json_array(json_array('w', 'x'), json_array('y', 'z')));"))--(doseq [driver [:redshift :databricks]]- (defmethod native-nested-array-query driver- [_driver]- "select array(array(array('a', 'b'), array('c', 'd')), array(array('w', 'x'), array('y', 'z')));"))--(defmethod native-nested-array-query :snowflake- [_driver]- "select array_construct(array_construct(array_construct('a', 'b'), array_construct('c', 'd')), array_construct(array_construct('w', 'x'), array_construct('y', 'z')));")--(defmulti native-nested-array-results- {:arglists '([driver])}- tx/dispatch-on-driver-with-test-extensions- :hierarchy #'driver/hierarchy)--(defmethod native-nested-array-results :default- [_driver]- [[["a" "b"] ["c" "d"]] [["w" "x"] ["y" "z"]]])--(doseq [driver [:sqlite :databricks :redshift]]- (defmethod native-nested-array-results driver- [_driver]- "[[[\"a\",\"b\"],[\"c\",\"d\"]],[[\"w\",\"x\"],[\"y\",\"z\"]]]"))--(defmethod native-nested-array-results :mysql- [_driver]- "[[[\"a\", \"b\"], [\"c\", \"d\"]], [[\"w\", \"x\"], [\"y\", \"z\"]]]")--(defmethod native-nested-array-results :snowflake- [_driver]- "[\n [\n [\n \"a\",\n \"b\"\n ],\n [\n \"c\",\n \"d\"\n ]\n ],\n [\n [\n \"w\",\n \"x\"\n ],\n [\n \"y\",\n \"z\"\n ]\n ]\n]")--(doseq [driver [:postgres :vertica :mysql :sqlite :redshift :databricks :snowflake]]- (defmethod driver/database-supports? [driver :test/nested-arrays]- [_driver _feature _database]- true))--(deftest ^:parallel nested-array-query-test- (testing "A nested array query should be returned in a readable format"- (mt/test-drivers (mt/normal-driver-select {:+features [:test/nested-arrays]})- (mt/dataset test-data- (is (= [[(native-nested-array-results driver/*driver*)]]- (->> (mt/native-query {:query (native-nested-array-query driver/*driver*)})- mt/process-query- mt/rows)))))))+(deftest ^:parallel multiple-counts-test+ (testing "Count of count grouping works (#15074)"+ (let [query (lib.tu.macros/mbql-query checkins+ {:aggregation [[:count]]+ :breakout [[:field "count" {:base-type :type/Integer}]]+ :source-query {:source-table (meta/id :checkins)+ :aggregation [[:count]]+ :breakout [!month.date]}+ :limit 2})]+ (qp.store/with-metadata-provider+ meta/metadata-provider+ (is (=? {:query ["SELECT"+ " \"source\".\"count\" AS \"count\","+ " COUNT(*) AS \"count_2\""+ "FROM"+ " ("+ " SELECT"+ " DATE_TRUNC('month', \"PUBLIC\".\"CHECKINS\".\"DATE\") AS \"DATE\","+ " COUNT(*) AS \"count\""+ " FROM"+ " \"PUBLIC\".\"CHECKINS\""+ " GROUP BY"+ " DATE_TRUNC('month', \"PUBLIC\".\"CHECKINS\".\"DATE\")"+ " ORDER BY"+ " DATE_TRUNC('month', \"PUBLIC\".\"CHECKINS\".\"DATE\") ASC"+ " ) AS \"source\""+ "GROUP BY"+ " \"source\".\"count\""+ "ORDER BY"+ " \"source\".\"count\" ASC"+ "LIMIT"+ " 2"]+ :params nil}+ (-> (qp.compile/compile query)+ (update :query #(str/split-lines (driver/prettify-native-form :h2 %))))))))))++;;; see also [[metabase.query-processor.util.add-alias-info-test/resolve-incorrect-field-ref-for-expression-test]]+;;; and [[metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test/evil-field-ref-for-an-expression-test]]+(deftest ^:parallel evil-field-ref-for-an-expression-test+ (testing "If we accidentally use a :field ref for an :expression, the query should still compile correctly"+ ;; (this is actually mostly checking that `add-alias-info` or someone else rewrites the `:field` ref as an+ ;; `:expression` ref, by the time the SQL QP sees the query it should be in a shape that will generate correct+ ;; output.+ (let [query {:database (meta/id)+ :type :query+ :query {:source-query {:source-table (meta/id :products)+ :expressions {"my_numberLiteral" [:value 2 {:base_type :type/Integer}]}+ :fields [[:field (meta/id :products :id) nil]+ [:expression "my_numberLiteral"]]+ :filter [:=+ ;; EVIL REF+ [:field "my_numberLiteral" {:base-type :type/Integer}]+ [:value 1 {:base_type :type/Integer}]]+ :limit 20}+ :fields [[:field (meta/id :products :id) nil]]+ :limit 20}}]+ (qp.store/with-metadata-provider meta/metadata-provider+ (is (= {:params nil+ :query ["SELECT"+ " \"source\".\"ID\" AS \"ID\""+ "FROM"+ " ("+ " SELECT"+ " \"PUBLIC\".\"PRODUCTS\".\"ID\" AS \"ID\","+ " 2 AS \"my_numberLiteral\""+ " FROM"+ " \"PUBLIC\".\"PRODUCTS\""+ " WHERE"+ " 2 = 1"+ " LIMIT"+ " 20"+ " ) AS \"source\""+ "LIMIT"+ " 20"]}+ (-> (qp.compile/compile query)+ (update :query #(str/split-lines (driver/prettify-native-form :h2 %))))))))))diff --git a/test/metabase/driver/sql_jdbc/execute/diagnostic_test.clj b/test/metabase/driver/sql_jdbc/execute/diagnostic_test.cljindex 0d34fd6961a..a86644693fc 100644--- a/test/metabase/driver/sql_jdbc/execute/diagnostic_test.clj+++ b/test/metabase/driver/sql_jdbc/execute/diagnostic_test.clj@@ -3,8 +3,7 @@[clojure.test :refer :all][metabase.driver :as driver][metabase.driver.sql-jdbc.execute.diagnostic :as sql-jdbc.execute.diagnostic]- [metabase.test :as mt]- [metabase.util :as u]))+ [metabase.test :as mt]))(deftest diagnostic-info-capture-test(mt/test-drivers (mt/driver-select {:+parent :sql-jdbc})@@ -30,6 +29,6 @@;; the diag info driver should match the current one(is (= driver/*driver* driver));; the diag info database-id should also match the current one- (is (= (u/the-id (mt/db)) database-id))+ (is (= (mt/id) database-id));; the active connections may be between 0 and total-connections (inclusive)(is (<= 0 active-connections total-connections))))))))diff --git a/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj b/test/metabase/driver/sql_jdbc/sync/describe_database_test.cljindex c0e4ca0fb54..ff624418516 100644--- a/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj+++ b/test/metabase/driver/sql_jdbc/sync/describe_database_test.clj@@ -244,7 +244,7 @@[{:field-name "citizen\\id" :base-type :type/Integer :pk? true}{:field-name "race\\id" :base-type :type/Integer :fk "human\\race"}][[1 1]]]]- (let [tables (t2/select :model/Table :db_id (:id (mt/db)))+ (let [tables (t2/select :model/Table :db_id (mt/id))field-name->field (t2/select-fn->fn :name identity :model/Field :table_id [:in (map :id tables)])](is (= #{"human\\race" "citizen"} (set (map :name tables))))(is (= #{"humanraceid" "citizen\\id" "race" "race\\id"}diff --git a/test/metabase/legacy_mbql/util_test.cljc b/test/metabase/legacy_mbql/util_test.cljcindex 729838dac3e..d2c81c81b23 100644--- a/test/metabase/legacy_mbql/util_test.cljc+++ b/test/metabase/legacy_mbql/util_test.cljc@@ -962,29 +962,19 @@(t/is (= [:+ 1 1](mbql.u/expression-with-name {:expressions {"two" [:+ 1 1]}:source-table 1}- "two")))+ "two"))))+(t/deftest ^:parallel expression-with-name-test-2(t/testing "Make sure `expression-with-name` knows how to reach into the parent query if need be"(t/is (= [:+ 1 1](mbql.u/expression-with-name {:source-query {:expressions {"two" [:+ 1 1]}:source-table 1}}- "two"))))-- (t/testing "Should work if passed in a keyword as well"- (t/is (= [:+ 1 1]- (mbql.u/expression-with-name {:source-query {:expressions {"two" [:+ 1 1]}- :source-table 1}}- :two))))-- (t/testing "Should work if the key in the expression map is a keyword in pre-Metabase 43 query maps"- (t/is (= [:+ 1 1]- (mbql.u/expression-with-name {:source-query {:expressions {:two [:+ 1 1]}- :source-table 1}}- "two"))))+ "two")))))+(t/deftest ^:parallel expression-with-name-test-3(t/testing "Should throw an Exception if expression does not exist"(t/is (thrown-with-msg?- #?(:clj clojure.lang.ExceptionInfo :cljs cljs.core.ExceptionInfo)+ #?(:clj clojure.lang.ExceptionInfo :cljs :default)#"No expression named"(mbql.u/expression-with-name {} "wow")))))@@ -1123,3 +1113,8 @@{:default ""}](mbql.u/desugar-expression [:day-name [:field 1 nil]]))"`day-name` should desugar to a `:case` clause with values for each weekday"))))++(t/deftest ^:parallel normalize-token-handle-types-test+ (t/testing "If this gets called incorrectly with a base type keyword then handle it gracefully"+ (t/is (= :type/Text+ (mbql.u/normalize-token "type/Text")))))diff --git a/test/metabase/lib/aggregation_test.cljc b/test/metabase/lib/aggregation_test.cljcindex 1d54d74f250..a93487588bc 100644--- a/test/metabase/lib/aggregation_test.cljc+++ b/test/metabase/lib/aggregation_test.cljc@@ -797,7 +797,8 @@(->> querylib/available-aggregation-operators(m/find-first #(= (:short %) :sum))- lib/aggregation-operator-columns))]+ lib/aggregation-operator-columns+ (map #(dissoc % :lib/source-uuid))))](is (= (clean built-query)(clean converted-query))))))diff --git a/test/metabase/lib/card_test.cljc b/test/metabase/lib/card_test.cljcindex b12b55a6abb..344711afa17 100644--- a/test/metabase/lib/card_test.cljc+++ b/test/metabase/lib/card_test.cljc@@ -556,3 +556,35 @@:lib/source :source/card:lib/breakout? false}](lib/returned-columns (lib.tu/query-with-source-card)))))++(deftest ^:parallel propagate-crazy-long-identifiers-from-card-metadata-test+ (testing "respect crazy-long identifiers in card metadata (we need to use these to refer to native columns in the second stage) (#47584)"+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query {:type :native+ :database (meta/id)+ :native {:query "SELECT *"}}+ :result-metadata [{:base_type :type/Text+ :database_type "CHARACTER VARYING"+ :display_name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :effective_type :type/Text+ :name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/source :source/native}]}]})+ query (-> (lib/query mp (lib.metadata/card mp 1))+ lib/append-stage)]+ (testing "card returned columns"+ (is (=? [{:lib/source :source/card+ :lib/source-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"}]+ (lib/returned-columns query (lib.metadata/card mp 1)))))+ (testing "first stage returned columns"+ (is (=? [{:lib/source :source/card+ :lib/source-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_00028d48"}]+ (lib/returned-columns query 0))))+ (testing "second stage returned columns"+ (is (=? [{:lib/source :source/previous-stage+ :lib/source-column-alias "Total_number_of_people_from_each_state_separated_by_00028d48"+ :lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_00028d48"}]+ (lib/returned-columns query 1)))))))diff --git a/test/metabase/lib/convert_test.cljc b/test/metabase/lib/convert_test.cljcindex d0936554eb0..a877989c81f 100644--- a/test/metabase/lib/convert_test.cljc+++ b/test/metabase/lib/convert_test.cljc@@ -820,7 +820,7 @@:field-ref [:field 134551 {:source-field 134534}]:fk-field-id 134534:fingerprint {:global {:distinct-count 4, :nil% 0.0}- :type {:type/text {:percent-json 0.0+ :type {:type/Text {:percent-json 0.0:percent-url 0.0:percent-email 0.0:percent-state 0.0diff --git a/test/metabase/lib/equality_test.cljc b/test/metabase/lib/equality_test.cljcindex 27ff194f01b..038f1df5c20 100644--- a/test/metabase/lib/equality_test.cljc+++ b/test/metabase/lib/equality_test.cljc@@ -1119,3 +1119,24 @@:lib/source-column-alias "ADDRESS":lib/type :metadata/column}](is (nil? (lib.equality/find-matching-ref col field-refs))))))++(deftest ^:parallel column-equality-binning-test+ (testing "Two columns with the same binning should be equal; different binning should make them unequal"+ (let [col (assoc (meta/field-metadata :orders :total)+ :metabase.lib.field/binning {:bin-width 20.0+ :max-value 160.0+ :min-value 0.0+ :num-bins 10+ :strategy :num-bins})+ same-binning (assoc col :metabase.lib.field/binning {:bin-width 20.0+ :max-value 160.0+ :min-value 0.0+ :num-bins 10+ :strategy :num-bins})+ different-binning (assoc col :metabase.lib.field/binning {:bin-width 5.0+ :max-value 160.0+ :min-value 5.0+ :num-bins 50+ :strategy :num-bins})]+ (is (lib.equality/= col same-binning))+ (is (not (lib.equality/= col different-binning))))))diff --git a/test/metabase/lib/field/resolution_test.cljc b/test/metabase/lib/field/resolution_test.cljcindex eebf88fbf96..4e7c03f4dce 100644--- a/test/metabase/lib/field/resolution_test.cljc+++ b/test/metabase/lib/field/resolution_test.cljc@@ -104,18 +104,22 @@-1a-field-clause))](testing "For fields with parents we should return them with a combined name including parent's name"- (is (=? {:table-id (meta/id :venues)- :name "grandparent.parent"- :parent-id (metabase.lib.field-test/grandparent-parent-child-id :grandparent)- :id (metabase.lib.field-test/grandparent-parent-child-id :parent)- :visibility-type :normal}+ (is (=? {:table-id (meta/id :venues)+ :name "grandparent.parent"+ :nfc-path ["grandparent"]+ :lib/source-column-alias "parent"+ :parent-id (metabase.lib.field-test/grandparent-parent-child-id :grandparent)+ :id (metabase.lib.field-test/grandparent-parent-child-id :parent)+ :visibility-type :normal}(col-info [:field {:lib/uuid (str (random-uuid))} (metabase.lib.field-test/grandparent-parent-child-id :parent)]))))(testing "nested-nested fields should include grandparent name (etc)"- (is (=? {:table-id (meta/id :venues)- :name "grandparent.parent.child"- :parent-id (metabase.lib.field-test/grandparent-parent-child-id :parent)- :id (metabase.lib.field-test/grandparent-parent-child-id :child)- :visibility-type :normal}+ (is (=? {:table-id (meta/id :venues)+ :name "grandparent.parent.child"+ :nfc-path ["grandparent" "parent"]+ :lib/source-column-alias "child"+ :parent-id (metabase.lib.field-test/grandparent-parent-child-id :parent)+ :id (metabase.lib.field-test/grandparent-parent-child-id :child)+ :visibility-type :normal}(col-info [:field {:lib/uuid (str (random-uuid))} (metabase.lib.field-test/grandparent-parent-child-id :child)]))))))(deftest ^:parallel fallback-metadata-from-saved-question-when-missing-from-metadata-provider-test@@ -748,10 +752,6 @@[:field (meta/id :venues :longitude) nil][:field (meta/id :venues :price) nil]]}})field-ref [:field {:lib/uuid (str (random-uuid))} (meta/id :venues :name)]]- (testing `lib.field.resolution/resolve-column-in-previous-stage-metadata- (let [stage-cols (get-in (lib.util/query-stage query 0) [:lib/stage-metadata :columns])]- (is (=? {:name "NAME", :description "user description", :display-name "user display name"}- (#'lib.field.resolution/resolve-column-in-previous-stage-metadata query field-ref stage-cols)))))(testing `lib.field.resolution/resolve-field-ref(is (=? {:name "NAME", :description "user description", :display-name "user display name"}(lib.field.resolution/resolve-field-ref query -1 field-ref))))))))@@ -1020,8 +1020,8 @@:name "ID":table-id (meta/id :products);; TODO (Cam 7/29/25) -- maybe we need to add a `:source/indetermiate` option or something. Because- ;; this is wrong... but nothing else is right either.- :lib/source :source/table-defaults+ ;; this is probably wrong... but nothing else is right either.+ :lib/source :source/previous-stage::lib.field.resolution/fallback-metadata? true}(lib.field.resolution/resolve-field-refquery -1@@ -1242,3 +1242,46 @@:lib/source-column-alias "Cat__NAME":lib/desired-column-alias (symbol "nil #_\"key is not present.\"")}(lib.field.resolution/resolve-field-ref query -1 bad-ref))))))++(deftest ^:parallel nested-literal-boolean-expression-with-name-collisions-test+ (testing "Don't resolve a `:field` ref to an expression if it has a conflicting name"+ (let [true-value [:value {:base-type :type/Boolean, :effective-type :type/Boolean, :lib/expression-name "T"} true]+ false-value [:value {:base-type :type/Boolean, :effective-type :type/Boolean, :lib/expression-name "F"} false]+ query (lib.tu.macros/mbql-5-query nil+ {:stages [{:source-table $$orders+ :expressions [true-value+ false-value]+ :fields [[:expression {} "T"]+ [:expression {} "F"]]}+ {:expressions [true-value+ false-value]+ :fields [[:expression {} "T"]+ [:expression {} "F"]+ [:field {:base-type :type/Boolean} "T"]+ [:field {:base-type :type/Boolean} "F"]]}]})]+ (is (=? {:lib/source :source/previous-stage+ :lib/source-column-alias "T"+ :lib/expression-name (symbol "nil #_\"key is not present.\"")+ :lib/original-expression-name "T"}+ (lib.field.resolution/resolve-field-ref query -1 [:field+ {:lib/uuid "00000000-0000-0000-0000-000000000000", :base-type :type/Boolean}+ "T"]))))))++(deftest ^:parallel resolve-incorrect-field-ref-for-expression-test+ (testing "resolve the incorrect use of a field ref correctly"+ (let [query (lib/query+ meta/metadata-provider+ (lib.tu.macros/mbql-query venues+ {:fields [[:expression "my_numberLiteral"]]+ :expressions {"my_numberLiteral" [:value 1 {:base_type :type/Integer}]}}))]+ (is (=? {:base-type :type/Integer+ :display-name "my_numberLiteral"+ :name "my_numberLiteral"+ :lib/expression-name "my_numberLiteral"+ :lib/source :source/expressions+ :lib/source-column-alias "my_numberLiteral"+ :lib/source-uuid "00000000-0000-0000-0000-000000000000"+ :lib/type :metadata/column}+ (lib.field.resolution/resolve-field-ref+ query -1+ [:field {:base-type :type/Integer, :lib/uuid "00000000-0000-0000-0000-000000000000"} "my_numberLiteral"]))))))diff --git a/test/metabase/lib/field_test.cljc b/test/metabase/lib/field_test.cljcindex 9825c5e64e3..9c5867639b6 100644--- a/test/metabase/lib/field_test.cljc+++ b/test/metabase/lib/field_test.cljc@@ -1508,7 +1508,9 @@(deftest ^:parallel expression-ref-when-metadata-has-expression-name-test(testing "column metadata with :expression-name should generate :expression refs. Prefer :expression-name over :name (#34957)"(let [metadata (-> (meta/field-metadata :venues :name)- (assoc :lib/expression-name "Custom Venue Name", :lib/source :source/expressions))]+ (assoc :lib/expression-name "Custom Venue Name"+ :lib/source :source/expressions+ :lib/source-uuid "00000000-0000-0000-0000-000000000000"))](is (=? [:expression {} "Custom Venue Name"](lib/ref metadata))))))diff --git a/test/metabase/lib/join/util_test.cljc b/test/metabase/lib/join/util_test.cljcnew file mode 100644index 00000000000..6951d6eb020--- /dev/null+++ b/test/metabase/lib/join/util_test.cljc@@ -0,0 +1,27 @@+(ns metabase.lib.join.util-test+ (:require+ #?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))+ [clojure.test :refer [deftest is testing]]+ [metabase.lib.core :as lib]+ [metabase.lib.field.resolution :as lib.field.resolution]+ [metabase.lib.join.util :as lib.join.util]+ [metabase.lib.test-metadata :as meta]+ [metabase.lib.test-util.macros :as lib.tu.macros]))++#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))++;;; see also [[metabase.query-processor.util.add-alias-info-test/preserve-field-options-name-test]]+(deftest ^:parallel desired-alias-should-respect-ref-name-test+ (testing "Respect that :name specified in a ref for desired-column-alias calculation purposes"+ (let [query (lib/query+ meta/metadata-provider+ (lib.tu.macros/mbql-5-query orders+ {:stages [{:fields [[:field {:name "__crazy__"} %id]]}]}))]+ (let [col (lib.field.resolution/resolve-field-ref query -1 (lib/normalize :mbql.clause/field [:field {:name "__crazy__"} (meta/id :orders :id)]))]+ (is (=? {:lib/ref-name "__crazy__"}+ col))+ (is (= "__crazy__"+ (lib.join.util/desired-alias query col))))+ (is (=? [{:lib/ref-name "__crazy__"+ :lib/desired-column-alias "__crazy__"}]+ (lib/returned-columns query))))))diff --git a/test/metabase/lib/metadata/calculation_test.cljc b/test/metabase/lib/metadata/calculation_test.cljcindex bb00fa904d3..eb1026131f2 100644--- a/test/metabase/lib/metadata/calculation_test.cljc+++ b/test/metabase/lib/metadata/calculation_test.cljc@@ -83,7 +83,7 @@(mu/disable-enforcement(is (=? {:name "Unknown Field":display-name "Unknown Field" #_"join → Unknown Field" ; either answer can be considered correct I guess- :long-display-name "join → Unknown Field"}+ :long-display-name "Unknown Field" #_"join → Unknown Field"}(lib/display-info query [:field {:join-alias "join"} field-id])))))))(defn- visible-columns-with-desired-aliases@@ -923,21 +923,19 @@(deftest ^:parallel return-correct-metadata-for-broken-field-refs-test(testing (str "lib/returned-columns and lib/visible-columns should not include join alias for metadatas derived from"" bad refs when join does not exist in the current stage of the query (QUE-1496)")- (let [query (lib/query- meta/metadata-provider- (lib.tu.macros/mbql-5-query venues- {:stages [{:source-table $$venues- :joins [{:strategy :left-join- :stages [{:source-table $$categories}]- :alias "Cat"- :conditions [[:= {} $category-id &Cat.categories.id]]- :fields [&Cat.categories.name]}]- :fields [$id- &Cat.categories.name]}- {;; THIS REF IS WRONG -- it should not be using `Cat` because the join is in the source- ;; query rather than in the current stage. However, we should be smart enough to try to- ;; figure out what they meant.- :breakout [&Cat.categories.name]}]}))]+ (let [query (lib.tu.macros/mbql-5-query venues+ {:stages [{:source-table $$venues+ :joins [{:strategy :left-join+ :stages [{:source-table $$categories}]+ :alias "Cat"+ :conditions [[:= {} $category-id &Cat.categories.id]]+ :fields [&Cat.categories.name]}]+ :fields [$id+ &Cat.categories.name]}+ {;; THIS REF IS WRONG -- it should not be using `Cat` because the join is in the source+ ;; query rather than in the current stage. However, we should be smart enough to try to+ ;; figure out what they meant.+ :breakout [&Cat.categories.name]}]})](testing `lib/returned-columns(testing "stage 1 of 2"(is (=? [{:id (meta/id :venues :id)@@ -992,28 +990,26 @@(deftest ^:parallel join-source-query-join-test(testing "lib/returned-columns calculates incorrect :source-column-aliases for columns coming from nested joins (QUE-1373)"- (let [query (lib/query- meta/metadata-provider- (lib.tu.macros/mbql-5-query orders- {:stages [{:joins [{:alias "Q2"- :stages [{:source-table $$reviews- :aggregation [[:avg {:name "avg"} $reviews.rating]]- :breakout [&P2.products.category]- :joins [{:alias "P2"- :strategy :left-join- :stages [{:source-table $$products}]- :conditions [[:= {}- $reviews.product-id- &P2.products.id]]}]}]- :strategy :left-join- :condition [:= {} &Q2.products.category 1]}]- ;; busted field ref, should probably be something like- ;;- ;; [:field {:join-alias "Q2", :base-type :type/Integer} "P2__CATEGORY"]- ;;- ;; but we should still be able to resolve it correctly.- :fields [[:field {:join-alias "Q2"} (meta/id :products :category)]- [:field {:base-type :type/Integer, :join-alias "Q2"} "avg"]]}]}))+ (let [query (lib.tu.macros/mbql-5-query orders+ {:stages [{:joins [{:alias "Q2"+ :stages [{:source-table $$reviews+ :aggregation [[:avg {:name "avg"} $reviews.rating]]+ :breakout [&P2.products.category]+ :joins [{:alias "P2"+ :strategy :left-join+ :stages [{:source-table $$products}]+ :conditions [[:= {}+ $reviews.product-id+ &P2.products.id]]}]}]+ :strategy :left-join+ :condition [:= {} &Q2.products.category 1]}]+ ;; busted field ref, should probably be something like+ ;;+ ;; [:field {:join-alias "Q2", :base-type :type/Integer} "P2__CATEGORY"]+ ;;+ ;; but we should still be able to resolve it correctly.+ :fields [[:field {:join-alias "Q2"} (meta/id :products :category)]+ [:field {:base-type :type/Integer, :join-alias "Q2"} "avg"]]}]})relevant-keys (fn [cols](map #(select-keys % [:name:lib/sourcediff --git a/test/metabase/lib/schema/metadata_test.cljc b/test/metabase/lib/schema/metadata_test.cljcindex 64acd305130..ec44e69d532 100644--- a/test/metabase/lib/schema/metadata_test.cljc+++ b/test/metabase/lib/schema/metadata_test.cljc@@ -1,9 +1,12 @@(ns metabase.lib.schema.metadata-test(:require[clojure.test :refer [are deftest is]]+ [clojure.walk :as walk][metabase.legacy-mbql.schema :as mbql.s]- [metabase.lib.normalize :as lib.normalize]- [metabase.lib.schema.metadata :as lib.schema.metadata]))+ [metabase.lib.core :as lib]+ [metabase.lib.schema.metadata :as lib.schema.metadata]+ [metabase.lib.test-metadata :as meta]+ [metabase.util :as u]))(deftest ^:parallel normalize-column-metadata-test(let [col {"active" true@@ -31,6 +34,7 @@"name" "CATEGORY""position" 3"semantic-type" "type/Category"+ "settings" {"is_priceless" true}"source" "breakout""table-id" 10808"visibility-type" "normal"}]@@ -51,6 +55,7 @@:name "CATEGORY":position 3:semantic-type :type/Category+ :settings {:is_priceless true}:source :breakout:table-id 10808:visibility-type :normal@@ -62,9 +67,20 @@:lib/source :source/table-defaults:lib/source-column-alias "CATEGORY":lib/type :metadata/column}- (lib.normalize/normalize ::lib.schema.metadata/column col)+ (lib/normalize ::lib.schema.metadata/column col);; should be able to detect that this is Lib metadata based on the use of `:base-type`- (lib.normalize/normalize ::lib.schema.metadata/lib-or-legacy-column (dissoc col "lib/type"))))))+ (lib/normalize ::lib.schema.metadata/lib-or-legacy-column (dissoc col "lib/type"))))))++(deftest ^:parallel normalize-column-metadata-from-json-test+ (let [cols (for [field (meta/fields :venues)]+ (meta/field-metadata :venues field))+ json-cols (walk/postwalk+ (fn [x]+ (cond-> x+ (keyword? x) u/qualified-name))+ cols)]+ (is (= cols+ (lib/normalize [:sequential ::lib.schema.metadata/column] json-cols)))))(deftest ^:parallel normalize-legacy-column-metadata-test(are [schema] (= {:base_type :type/Integer@@ -84,7 +100,7 @@:percent-state 0.0:percent-url 0.0}:type/Number {:q1 1.459}}}}- (lib.normalize/normalize+ (lib/normalizeschema{"base_type" "type/Integer":coercion_strategy nildiff --git a/test/metabase/lib/schema/parameter_test.cljc b/test/metabase/lib/schema/parameter_test.cljcindex ef741709a5c..a394208a33d 100644--- a/test/metabase/lib/schema/parameter_test.cljc+++ b/test/metabase/lib/schema/parameter_test.cljc@@ -1,8 +1,16 @@(ns metabase.lib.schema.parameter-test(:require- [clojure.test :refer [are deftest]]+ #?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))+ [clojure.test :refer [are deftest is]]+ [malli.error :as me]+ [metabase.lib.core :as lib][metabase.lib.normalize :as lib.normalize]- [metabase.lib.schema.parameter :as lib.schema.parameter]))+ [metabase.lib.schema :as lib.schema]+ [metabase.lib.schema.parameter :as lib.schema.parameter]+ [metabase.lib.test-metadata :as meta]+ [metabase.util.malli.registry :as mr]))++#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))(deftest ^:parallel normalize-dimension-test(are [x expected] (= expected@@ -14,3 +22,17 @@["dimension" ["expression" "wow"]][:dimension [:expression "wow"]]))++(deftest ^:parallel normalize-legacy-refs-inside-stage-parameters-e2e-test+ (let [query {:database 1+ :type "query"+ :query {:source-table 8+ :limit 20+ :expressions {"my_stringExpr" [:concat "Category is " [:field 69 {:base-type :type/Text}]]}+ :parameters [{:type :category+ :target [:dimension [:expression "my_stringExpr" {:base-type :type/Text}] {:stage-number 0}]+ :value "Category is Gizmo"}]}}+ query (lib/query meta/metadata-provider query)]+ (is (=? {:stages [{:parameters [{:target [:dimension [:expression "my_stringExpr" {:base-type :type/Text}] {:stage-number 0}]}]}]}+ query))+ (is (not (me/humanize (mr/explain ::lib.schema/query query))))))diff --git a/test/metabase/lib/schema/util_test.cljc b/test/metabase/lib/schema/util_test.cljcindex 40fedad3308..e091ace6028 100644--- a/test/metabase/lib/schema/util_test.cljc+++ b/test/metabase/lib/schema/util_test.cljc@@ -10,19 +10,19 @@:database 1:stages [{:lib/type :mbql.stage/mbql:source-table 2- :filter [:=- {:lib/uuid "00000000-0000-0000-0000-000000000010"}- [:field- {:lib/uuid uuid-1, :base-type :type/Text}- 3]- 4]}+ :filters [[:=+ {:lib/uuid "00000000-0000-0000-0000-000000000010"}+ [:field+ {:lib/uuid uuid-1, :base-type :type/Text}+ 3]+ 4]]}{:lib/type :mbql.stage/mbql- :filter [:=- {:lib/uuid "00000000-0000-0000-0000-000000000020"}- [:field- {:lib/uuid uuid-2, :base-type :type/Text}- "my_field"]- 4]}]})+ :filters [[:=+ {:lib/uuid "00000000-0000-0000-0000-000000000020"}+ [:field+ {:lib/uuid uuid-2, :base-type :type/Text}+ "my_field"]+ 4]]}]})(def query-with-no-duplicate-uuids(query "00000000-0000-0000-0000-000000000001"diff --git a/test/metabase/lib/schema_test.cljc b/test/metabase/lib/schema_test.cljcindex f946c6a839a..00a6df8ce14 100644--- a/test/metabase/lib/schema_test.cljc+++ b/test/metabase/lib/schema_test.cljc@@ -339,3 +339,7 @@[{:source-table 1} {"lib/type" :mbql.stage/native}][{:lib/type :mbql.stage/mbql, :source-table 1}{:lib/type :mbql.stage/native}]))++(deftest ^:parallel normalize-remove-disallowed-keys-test+ (is (= {:source-table 1, :lib/type :mbql.stage/mbql}+ (lib/normalize ::lib.schema/stage {:source-table 1, :type "query"}))))diff --git a/test/metabase/lib/stage_test.cljc b/test/metabase/lib/stage_test.cljcindex e660120cbde..9c7c2c045e3 100644--- a/test/metabase/lib/stage_test.cljc+++ b/test/metabase/lib/stage_test.cljc@@ -4,12 +4,12 @@[clojure.test :refer [are deftest is testing]][medley.core :as m][metabase.lib.core :as lib]+ [metabase.lib.equality :as lib.equality][metabase.lib.join :as lib.join][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation][metabase.lib.metadata.result-metadata :as lib.metadata.result-metadata][metabase.lib.schema :as lib.schema]- [metabase.lib.stage :as lib.stage][metabase.lib.test-metadata :as meta][metabase.lib.test-util :as lib.tu][metabase.lib.test-util.macros :as lib.tu.macros]@@ -875,9 +875,10 @@:display-name "Count"}](lib/returned-columns query)))))))+;;; TODO (Cam 8/7/25) -- move these tests that test [[lib.equality/=]] to [[metabase.lib.equality-test]](deftest ^:parallel test-QUE-1607- (testing "QUE-1607"- (is (#'lib.stage/add-cols-from-join-duplicate?+ (testing "do not add duplicate columns whne join uses name refs in :fields (QUE-1607)"+ (is (lib.equality/={:base-type :type/Integer:display-name "Sum of Quantity":effective-type :type/Integer@@ -903,7 +904,7 @@:metabase.lib.join/join-alias "Orders":name "sum"}))))-(deftest ^:parallel add-cols-from-join-duplicate?-test+(deftest ^:parallel column-equality-test(let [join-col {:active true:base-type :type/Text:caveats nil@@ -939,13 +940,13 @@:lib/source-column-alias "TITLE":lib/type :metadata/column:metabase.lib.join/join-alias "Orders"}- existing-col {:base-type :type/Integer- :display-name "Orders → Sum"- :name "sum"- :lib/source :source/previous-stage- :lib/type :metadata/column- :metabase.lib.join/join-alias "Orders"}]- (is (not (#'lib.stage/add-cols-from-join-duplicate? join-col existing-col)))))+ existing-col {:base-type :type/Integer+ :display-name "Orders → Sum"+ :name "sum"+ :lib/source :source/previous-stage+ :lib/type :metadata/column+ :lib/original-join-alias "Orders"}]+ (is (not (lib.equality/= join-col existing-col)))))(deftest ^:parallel sane-desired-column-aliases-test(testing "Do not 'double-dip' a desired-column alias and do `__via__` twice"@@ -986,3 +987,35 @@:lib/source-column-alias "count":lib/desired-column-alias "count"}](f query)))))))))++(deftest ^:parallel propagate-crazy-long-native-identifiers-test+ (testing "respect crazy-long identifiers from native query stages (we need to use these to refer to native columns in the second stage) (#47584)"+ (let [query (lib.tu.macros/mbql-5-query nil+ {:stages [{:native "SELECT *"+ :lib/stage-metadata {:columns [{:base-type :type/Text+ :database-type "CHARACTER VARYING"+ :display-name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :effective-type :type/Text+ :name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/source :source/native+ :lib/source-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/type :metadata/column}]}}+ {}+ {}]})]+ (are [stage-number expected] (=? [expected]+ (lib/returned-columns query stage-number))+ 0+ {:lib/source :source/native+ :lib/source-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"}++ 1+ {:lib/source :source/previous-stage+ :lib/source-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_00028d48"}++ 2+ {:lib/source :source/previous-stage+ :lib/source-column-alias "Total_number_of_people_from_each_state_separated_by_00028d48"+ :lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_00028d48"}))))diff --git a/test/metabase/lib/test_metadata.cljc b/test/metabase/lib/test_metadata.cljcindex 99f2eadd6f3..964ee3a898a 100644--- a/test/metabase/lib/test_metadata.cljc+++ b/test/metabase/lib/test_metadata.cljc@@ -7,6 +7,8 @@will not be reflected here, for example if we add new information to the metadata. We'll have to manually updatethese things if that happens and Metabase lib is meant to consume it."(:require+ #?@(:clj+ ([flatland.ordered.set :as ordered-set]))[metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.test-metadata.graph-provider :as meta.graph-provider][metabase.util.malli :as mu]))@@ -3029,11 +3031,15 @@[table-name :- :keyword](assert ((tables) table-name)(str "Invalid table: " table-name))- (into #{}- (keep (fn [[a-table-name a-field-name]]- (when (= a-table-name table-name)- a-field-name)))- (keys (methods field-metadata-method))))+ (let [field-names (keep (fn [[a-table-name a-field-name]]+ (when (= a-table-name table-name)+ a-field-name))+ (keys (methods field-metadata-method)))]+ (into+ #?(:clj (ordered-set/ordered-set) :cljs #{})+ (sort-by (fn [field]+ (:position (field-metadata-method table-name field)))+ field-names))))(mu/defn table-metadata :- ::lib.schema.metadata/table"Get Table metadata for a one of the `test-data` Tables in the test metadata, e.g. `:venues`. This is here so you candiff --git a/test/metabase/lib/test_util/macros.clj b/test/metabase/lib/test_util/macros.cljindex 0fe33243cc4..f061e559eab 100644--- a/test/metabase/lib/test_util/macros.clj+++ b/test/metabase/lib/test_util/macros.clj@@ -1,6 +1,8 @@(ns metabase.lib.test-util.macros(:require[clojure.test :refer [testing]]+ [metabase.lib.query :as lib.query]+ [metabase.lib.test-metadata :as meta][metabase.lib.test-util.macros.impl :as lib.tu.macros.impl][metabase.test.data.mbql-query-impl :as mbql-query-impl][metabase.util :as u]@@ -76,10 +78,14 @@(do-with-bindings(fn [](binding [mbql-query-impl/*mbql-version* 5]- (as-> query <>- (mbql-query-impl/parse-tokens table-name <>)- (u/assoc-default <> :lib/type :mbql/query, :database '(metabase.lib.test-metadata/id))- (maybe-add-source-table-mbql-5 <> table-name)))))))+ (as-> query $query+ (mbql-query-impl/parse-tokens table-name $query)+ (u/assoc-default $query+ :lib/type :mbql/query, :database '(metabase.lib.test-metadata/id))+ (maybe-add-source-table-mbql-5 $query table-name)+ `(lib.query/query+ meta/metadata-provider+ ~$query)))))))(defmacro with-testing-against-standard-queries"Tests against a number of named expressions that all produce the same columns through different methods."diff --git a/test/metabase/model_persistence/api_test.clj b/test/metabase/model_persistence/api_test.cljindex 3813dcf8a0e..5e738eb6435 100644--- a/test/metabase/model_persistence/api_test.clj+++ b/test/metabase/model_persistence/api_test.clj@@ -206,7 +206,7 @@(deftest persist-database-test(mt/test-drivers (mt/normal-drivers-with-feature :persist-models)- (let [db-id (:id (mt/db))]+ (let [db-id (mt/id)](mt/with-temp[:model/Card card {:database_id db-id:type :model}]@@ -236,7 +236,7 @@(deftest unpersist-database-test(mt/test-drivers (mt/normal-drivers-with-feature :persist-models)- (let [db-id (:id (mt/db))]+ (let [db-id (mt/id)](mt/with-temp[:model/Card _ {:database_id db-id:type :model}]diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 642cf70ec4e..27041253247 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -363,7 +363,7 @@(testing varr(varr f)))))-(deftest normalize-visualization-settings-test+(deftest ^:parallel normalize-visualization-settings-test(test-visualization-settings-normalization(fn [original expected](mt/with-temp [:model/Card card {:visualization_settings original}]diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.cljindex 557da911310..dc6fe0ee724 100644--- a/test/metabase/query_processor/api_test.clj+++ b/test/metabase/query_processor/api_test.clj@@ -230,7 +230,7 @@(do-test)))))))(deftest native-query-with-long-column-alias- (testing "nested native query with long column alias (metabase#47584)"+ (testing "nested native query with long column alias (#47584)"(let [short-col-name "coun"long-col-name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"diff --git a/test/metabase/query_processor/middleware/annotate/legacy_helper_fns_test.clj b/test/metabase/query_processor/middleware/annotate/legacy_helper_fns_test.cljnew file mode 100644index 00000000000..15b144f8a67--- /dev/null+++ b/test/metabase/query_processor/middleware/annotate/legacy_helper_fns_test.clj@@ -0,0 +1,20 @@+(ns metabase.query-processor.middleware.annotate.legacy-helper-fns-test+ (:require+ [clojure.test :refer :all]+ [clojure.walk :as walk]+ [metabase.lib.test-metadata :as meta]+ [metabase.query-processor.middleware.annotate.legacy-helper-fns :as annotate.legacy-helper-fns]+ [metabase.query-processor.store :as qp.store]+ [metabase.util :as u]))++(deftest ^:parallel aggregation-name-test+ (let [inner-query {:source-query {:source-table (meta/id :venues)}+ :source-metadata [(walk/postwalk+ (fn [form]+ (cond-> form+ (keyword? form) u/qualified-name))+ (meta/field-metadata :venues :name))]+ :aggregation [[:count]]}]+ (qp.store/with-metadata-provider meta/metadata-provider+ (is (= "count"+ (annotate.legacy-helper-fns/aggregation-name inner-query [:count]))))))diff --git a/test/metabase/query_processor/middleware/metrics_test.clj b/test/metabase/query_processor/middleware/metrics_test.cljindex 58da2a5e838..198e25c89eb 100644--- a/test/metabase/query_processor/middleware/metrics_test.clj+++ b/test/metabase/query_processor/middleware/metrics_test.clj@@ -371,8 +371,7 @@;; Empty stage added by resolved-source-cards to nest join(=?/exactly {:lib/type :mbql.stage/mbql:qp/stage-had-source-card (:id question)- :source-query/model? false- :source-query/entity-id (:entity-id question)})]}]}]}+ :source-query/model? false})]}]}]}(adjust query)))))(defn- model-based-metric-questiondiff --git a/test/metabase/query_processor/middleware/permissions_test.clj b/test/metabase/query_processor/middleware/permissions_test.cljindex cdb51190f8e..d1814aade0e 100644--- a/test/metabase/query_processor/middleware/permissions_test.clj+++ b/test/metabase/query_processor/middleware/permissions_test.clj@@ -3,6 +3,7 @@(:require[clojure.test :refer :all][metabase.api.common :as api]+ [metabase.lib.test-metadata :as meta][metabase.permissions.core :as perms][metabase.query-processor :as qp][metabase.query-processor.middleware.permissions :as qp.perms]@@ -812,14 +813,19 @@(mt/with-temp [:model/User {user-id :id} {}:model/Card {card-id :id} {:dataset_query {:database (mt/id):type :native- :native {:query "SELECT * FROM venues"}}}]+ :native {:query "SELECT * FROM venues"}}+ :result_metadata (for [field (meta/fields :venues)]+ (-> (meta/field-metadata :venues field)+ (dissoc :id :table-id)))}](mt/with-no-data-perms-for-all-users!(perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/create-queries :query-builder)(let [query (mt/mbql-query checkins- {:joins [{:fields [$id]+ {:joins [{:fields [[:field "ID" {:base-type :type/Integer, :join-alias "card"}]]:source-table (format "card__%d" card-id):alias "card"- :condition [:= $venue_id &card.venues.id]+ :condition [:=+ $venue_id+ [:field "ID" {:base-type :type/Integer, :join-alias "card"}]]:strategy :left-join}]:order-by [[:asc $id]]:limit 2})]diff --git a/test/metabase/query_processor/middleware/resolve_joins_test.clj b/test/metabase/query_processor/middleware/resolve_joins_test.cljindex 108d6b0c3b1..da75d8a68b7 100644--- a/test/metabase/query_processor/middleware/resolve_joins_test.clj+++ b/test/metabase/query_processor/middleware/resolve_joins_test.clj@@ -19,10 +19,20 @@(resolve-joins/resolve-joins query))))(deftest ^:parallel joins->fields-test- (is (= [1 2 3 4]- (#'resolve-joins/joins->fields [{:fields :all}- {:fields [1 2]}- {:fields [3 4]}]))))+ (is (= [[:field 1 {:join-alias "B"}]+ [:field 2 {:join-alias "B"}]+ [:field 3 {:join-alias "C"}]+ [:field 4 {:join-alias "C"}]]+ (#'resolve-joins/joins->fields [{:alias "A"+ :fields :all}+ {:alias "B"+ :fields [[:field 1 {:join-alias "B"}]+ ;; missing join alias+ [:field 2 nil]]}+ {:alias "C"+ :fields [[:field 3 {:join-alias "C"}]+ ;; wrong join alias+ [:field 4 {:join-alias "X"}]]}]))))(deftest ^:parallel no-op-test(testing "Does the middleware function if the query has no joins?"@@ -404,3 +414,40 @@"Q1 → Category""Q1 → Count"](map :display_name (qp.preprocess/query->expected-cols query)))))))++(deftest ^:parallel join-fields-missing-join-alias-e2e-test+ (testing "If a ref in join `:fields` is missing `:join-alias` we should add it when adding fields to the parent stage"+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query {:database (meta/id)+ :type :query+ :query {:source-table (meta/id :venues)}}}+ {:id 2+ :dataset-query {:database (meta/id)+ :type :native+ :native {:query "SELECT * FROM checkins"}}+ :result-metadata (for [field (meta/fields :checkins)]+ (-> (meta/field-metadata :checkins field)+ (dissoc :id :table-id)))}]})+ query (lib/query+ mp+ {:database (meta/id)+ :type :query+ :query {:source-table "card__1"+ :joins [{:fields [[:field "ID" {:base-type :type/Integer}]] ; busted ref, missing join-alias+ :source-table "card__2"+ :alias "native_card"+ :condition [:=+ [:field "ID" {:base-type :type/Integer}]+ [: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]+ [:field "ID" {:base-type :type/Integer, :join-alias "native_card"}]]}}+ (qp.preprocess/preprocess query))))))diff --git a/test/metabase/query_processor/streaming/csv_test.clj b/test/metabase/query_processor/streaming/csv_test.cljindex 97ea1bd0468..eea958cd75c 100644--- a/test/metabase/query_processor/streaming/csv_test.clj+++ b/test/metabase/query_processor/streaming/csv_test.clj@@ -9,8 +9,7 @@[metabase.query-processor :as qp][metabase.query-processor.streaming.interface :as qp.si][metabase.test :as mt]- [metabase.test.data.dataset-definitions :as defs]- [metabase.util :as u])+ [metabase.test.data.dataset-definitions :as defs])(:import(java.io BufferedOutputStream ByteArrayOutputStream)))@@ -57,7 +56,7 @@:notvisiblekey :notvisiblevalue}}](mt/with-no-data-perms-for-all-users!(data-perms/set-database-permission! (perms-group/all-users)- (u/the-id (mt/db))+ (mt/id):perms/create-queries :query-builder)(let [results (mt/user-http-request :rasta :post 200 (format "card/%d/query/csv" card-id))results-string (str results)diff --git a/test/metabase/query_processor/test_util.clj b/test/metabase/query_processor/test_util.cljindex be317743dbc..832f9517436 100644--- a/test/metabase/query_processor/test_util.clj+++ b/test/metabase/query_processor/test_util.clj@@ -511,6 +511,7 @@(lib.metadata.jvm/application-database-metadata-provider (data/id))queriestransforms))+([parent-metadata-provider :- ::lib.schema.metadata/metadata-providerqueries :- [:sequential {:min 1} :map]transforms :- [:maybe :map]]diff --git a/test/metabase/query_processor/util/add_alias_info_test.clj b/test/metabase/query_processor/util/add_alias_info_test.cljindex 3493b0ae343..a2ef6161291 100644--- a/test/metabase/query_processor/util/add_alias_info_test.clj+++ b/test/metabase/query_processor/util/add_alias_info_test.clj@@ -7,6 +7,7 @@[metabase.driver :as driver][metabase.driver.h2 :as h2][metabase.lib.core :as lib]+ [metabase.lib.field-test][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.calculation :as lib.metadata.calculation][metabase.lib.test-metadata :as meta]@@ -14,6 +15,8 @@[metabase.lib.test-util.macros :as lib.tu.macros][metabase.lib.test-util.metadata-providers.mock :as providers.mock][metabase.lib.test-util.uuid-dogs-metadata-provider :as lib.tu.uuid-dogs-metadata-provider]+ [metabase.lib.util :as lib.util]+ [metabase.lib.util.match :as lib.util.match][metabase.query-processor.preprocess :as qp.preprocess][metabase.query-processor.store :as qp.store][metabase.query-processor.util.add-alias-info :as add]@@ -21,32 +24,29 @@(comment h2/keep-me)-(deftest ^:parallel normalize-clause-test- (is (= [:expression "wow"]- (#'add/normalize-clause [:expression "wow"])- (#'add/normalize-clause [:expression "wow" nil])- (#'add/normalize-clause [:expression "wow" {}])- (#'add/normalize-clause [:expression "wow" {::amazing true}])))- (is (= [:field 1 nil]- (#'add/normalize-clause [:field 1 nil])- (#'add/normalize-clause [:field 1 {}])- (#'add/normalize-clause [:field 1 {::amazing true}]))))--;; TODO -- this is duplicated with [[metabase.query-processor.util.nest-query-test/remove-source-metadata]]-(defn- remove-source-metadata [x]+(defn- remove-source-metadata+ "This is mostly to make the test failure diffs sane."+ [x](walk/postwalk(fn [x]- (if ((every-pred map? :source-metadata) x)- (dissoc x :source-metadata)- x))+ (cond-> x+ (map? x) (dissoc :source-metadata :lib/stage-metadata)))x))(defn- add-alias-info [query]- (mt/with-metadata-provider (if (qp.store/initialized?)- (qp.store/metadata-provider)- meta/metadata-provider)- (driver/with-driver (or driver/*driver* :h2)- (-> query qp.preprocess/preprocess add/add-alias-info remove-source-metadata (dissoc :middleware)))))+ (driver/with-driver (or driver/*driver* :h2)+ (-> (if (:lib/type query)+ (->> query+ qp.preprocess/preprocess+ (lib/query (:lib/metadata query))+ add/add-alias-info)+ (qp.store/with-metadata-provider (if (qp.store/initialized?)+ (qp.store/metadata-provider)+ meta/metadata-provider)+ (-> query+ qp.preprocess/preprocess+ add/add-alias-info)))+ remove-source-metadata)))(deftest ^:parallel join-in-source-query-test(is (=? (lib.tu.macros/mbql-query venues@@ -60,25 +60,16 @@[:field %categories.id {:join-alias "Cat"::add/source-table "Cat"::add/source-alias "ID"}]]}]- :fields [[:field %id {::add/source-table $$venues- ::add/source-alias "ID"- ::add/desired-alias "ID"- ::add/position 0}]- [:field %categories.name {:join-alias "Cat"- ::add/source-table "Cat"- ::add/source-alias "NAME"- ::add/desired-alias "Cat__NAME"- ::add/position 1}]]}+ :fields [[:field %id {}]+ [:field %categories.name {}]]}:breakout [[:field %categories.name {:join-alias "Cat"::add/source-table ::add/source::add/source-alias "Cat__NAME"- ::add/desired-alias "Cat__NAME"- ::add/position 0}]]+ ::add/desired-alias "Cat__NAME"}]]:order-by [[:asc [:field %categories.name {:join-alias "Cat"::add/source-table ::add/source::add/source-alias "Cat__NAME"- ::add/desired-alias "Cat__NAME"- ::add/position 0}]]]+ ::add/desired-alias "Cat__NAME"}]]]:limit 1})(add-alias-info(lib.tu.macros/mbql-query venues@@ -106,7 +97,6 @@:strategy :left-join}]:fields [[:field %products.category {:join-alias "P1"::add/desired-alias "P1__CATEGORY"- ::add/position 0::add/source-alias "CATEGORY"::add/source-table "P1"}]]}:joins [{:source-query {:source-table $$reviews@@ -127,36 +117,31 @@%products.category{:join-alias "P2"::add/desired-alias "P2__CATEGORY"- ::add/position 0::add/source-alias "CATEGORY"::add/source-table "P2"}]]}:alias "Q2":condition [:=- [:field %products.category {:join-alias "P1"- ::add/desired-alias "P1__CATEGORY"- ::add/position 0- ::add/source-alias "P1__CATEGORY"+ [:field %products.category {::add/source-alias "P1__CATEGORY"::add/source-table ::add/source}][:field %products.category {:join-alias "Q2"::add/source-alias "P2__CATEGORY"::add/source-table "Q2"}]]:strategy :left-join}]- :fields [[:field %products.category {:join-alias "P1"- ::add/desired-alias "P1__CATEGORY"- ::add/position 0- ::add/source-alias "P1__CATEGORY"- ::add/source-table ::add/source}]]- :limit 1})+ :fields [[:field any? {::add/desired-alias "P1__CATEGORY"+ ::add/source-alias "P1__CATEGORY"+ ::add/source-table ::add/source}]]})(add-alias-info(lib.tu.macros/mbql-query orders- {:fields [&P1.products.category]- :source-query {:source-table $$orders+ {:source-query {:source-table $$orders:fields [&P1.products.category]:joins [{:strategy :left-join:source-table $$products:condition [:= $product-id &P1.products.id]- :alias "P1"}]}+ :alias "P1"+ :fields [&P1.products.category]}]}:joins [{:strategy :left-join+ ;; `&P1.products.category` is an INCORRECT REF because the join is at a previous stage+ ;; of the query. However, we should try to 'do the right thing'.:condition [:= &P1.products.category &Q2.products.category]:alias "Q2":source-query {:source-table $$reviews@@ -164,8 +149,9 @@:joins [{:strategy :left-join:source-table $$products:condition [:= $reviews.product-id &P2.products.id]- :alias "P2"}]}}]- :limit 1})))))+ :alias "P2"+ :fields [&P2.products.category]}]}}]+ :fields [&P1.products.category]})))))(deftest ^:parallel uniquify-aliases-test(is (=? (lib.tu.macros/mbql-query products@@ -174,15 +160,12 @@[:field %category{::add/source-table $$products::add/source-alias "CATEGORY"- ::add/desired-alias "CATEGORY"- ::add/position 0}]+ ::add/desired-alias "CATEGORY"}]"2"]}:fields [[:field %category {::add/source-table $$products::add/source-alias "CATEGORY"- ::add/desired-alias "CATEGORY"- ::add/position 0}]- [:expression "CATEGORY" {::add/desired-alias "CATEGORY_2"- ::add/position 1}]]+ ::add/desired-alias "CATEGORY"}]+ [:expression "CATEGORY" {::add/desired-alias "CATEGORY_2"}]]:limit 1})(add-alias-info(lib.tu.macros/mbql-query products@@ -197,8 +180,7 @@[:count]{:name "count"::add/source-alias "count"- ::add/desired-alias "count"- ::add/position 0}]]+ ::add/desired-alias "count"}]]:filter [:!=[:field %date {::add/source-table $$checkins::add/source-alias "DATE"}]@@ -217,35 +199,29 @@[:count]{:name "count"::add/source-alias "count"- ::add/desired-alias "count"- ::add/position 0}]+ ::add/desired-alias "count"}][:aggregation-options[:count]{:name "count_2"::add/source-alias "count_2"- ::add/desired-alias "count_2"- ::add/position 1}]+ ::add/desired-alias "count_2"}][:aggregation-options[:count]{:name "count_3"::add/source-alias "count_3"- ::add/desired-alias "count_3"- ::add/position 2}]]}+ ::add/desired-alias "count_3"}]]}:fields [[:field "count" {:base-type :type/Integer::add/source-table ::add/source::add/source-alias "count"- ::add/desired-alias "count"- ::add/position 0}]+ ::add/desired-alias "count"}][:field "count_2" {:base-type :type/Integer::add/source-table ::add/source::add/source-alias "count_2"- ::add/desired-alias "count_2"- ::add/position 1}]+ ::add/desired-alias "count_2"}][:field "count_3" {:base-type :type/Integer::add/source-table ::add/source::add/source-alias "count_3"- ::add/desired-alias "count_3"- ::add/position 2}]]+ ::add/desired-alias "count_3"}]]:limit 1})(add-alias-info(lib.tu.macros/mbql-query venues@@ -253,41 +229,22 @@:aggregation [[:aggregation-options[:count]{:name "count"- ::add/position 0::add/desired-alias "count"}][:count][:count]]}:limit 1})))))-(deftest ^:parallel multiple-expressions-test- (qp.store/with-metadata-provider meta/metadata-provider- (is (=? (lib.tu.macros/$ids venues- {$price 0- [:expression "big_price"] 1- [:expression "price_divided_by_big_price"] 2})- (#'add/selected-clauses- (lib.tu.macros/$ids venues- {:expressions {"big_price" [:+ $price 2]- "price_divided_by_big_price" [:/ $price [:expression "big_price"]]}- :fields [$price- [:expression "big_price"]- [:expression "price_divided_by_big_price"]]- :limit 1}))))))-(deftest ^:parallel multiple-expressions-test-2(is (=? (lib.tu.macros/$ids venues- (let [price [:field %price {::add/position 0- ::add/source-table $$venues+ (let [price [:field %price {::add/source-table $$venues::add/source-alias "PRICE"::add/desired-alias "PRICE"}]big-price [:expression"big_price"- {::add/position 1- ::add/desired-alias "big_price"}]+ {::add/desired-alias "big_price"}]price-divided-by-big-price [:expression"price_divided_by_big_price"- {::add/position 2- ::add/desired-alias "price_divided_by_big_price"}]]+ {::add/desired-alias "price_divided_by_big_price"}]]{:source-table $$venues:expressions {"big_price" [:+ price 2]"price_divided_by_big_price" [:/ price big-price]}@@ -305,7 +262,7 @@[:expression "price_divided_by_big_price"]]:limit 1}))))))-(deftest join-source-query-join-test+(deftest ^:parallel join-source-query-join-test(is (=? (lib.tu.macros/mbql-query orders{:joins [{:source-query {:source-table $$reviews:aggregation [[:aggregation-options@@ -313,18 +270,15 @@::add/source-alias "RATING"}]]{:name "avg"::add/source-alias "avg"- ::add/desired-alias "avg"- ::add/position 1}]]+ ::add/desired-alias "avg"}]]:breakout [[:field %products.category {:join-alias "P2"::add/source-table "P2"::add/source-alias "CATEGORY"- ::add/desired-alias "P2__CATEGORY"- ::add/position 0}]]+ ::add/desired-alias "P2__CATEGORY"}]]:order-by [[:asc [:field %products.category {:join-alias "P2"::add/source-table "P2"::add/source-alias "CATEGORY"- ::add/desired-alias "P2__CATEGORY"- ::add/position 0}]]]+ ::add/desired-alias "P2__CATEGORY"}]]]:joins [{:strategy :left-join:source-query {:source-table $$products}:condition [:=@@ -337,26 +291,22 @@:alias "Q2":strategy :left-join:condition [:=- [:field %products.category {:join-alias "Q2"- ::add/source-table "Q2"- ::add/source-alias "P2__CATEGORY"- ::add/desired-alias "Q2__P2__CATEGORY"- ::add/position 0}]- [:value 1 {:base_type :type/Text- :database_type "CHARACTER VARYING"- :name "CATEGORY"- :semantic_type :type/Category}]]}]+ [:field %products.category {:join-alias "Q2"+ ::add/source-table "Q2"+ ::add/source-alias "P2__CATEGORY"}]+ [:value 1 {:base_type :type/Text+ :database_type "CHARACTER VARYING"+ :name "CATEGORY"+ :semantic_type :type/Category}]]}]:fields [[:field %products.category {:join-alias "Q2"::add/source-table "Q2"::add/source-alias "P2__CATEGORY"- ::add/desired-alias "Q2__P2__CATEGORY"- ::add/position 0}]+ ::add/desired-alias "Q2__P2__CATEGORY"}][:field "avg" {:base-type :type/Integer:join-alias "Q2"::add/source-table "Q2"::add/source-alias "avg"- ::add/desired-alias "Q2__avg"- ::add/position 1}]]+ ::add/desired-alias "Q2__avg"}]]:limit 2})(add-alias-info(lib.tu.macros/mbql-query orders@@ -384,96 +334,75 @@(prefix-alias field-alias))(deftest ^:parallel custom-escape-alias-test- (let [db (mt/db)]- (driver/with-driver ::custom-escape- (mt/with-db db- (is (=? (lib.tu.macros/$ids venues- (merge- {:source-query (let [price [:field %price {::add/source-table $$venues- ::add/source-alias "PRICE"- ::add/desired-alias "COOL.PRICE"- ::add/position 0}]]- {:source-table $$venues- :expressions {"double_price" [:* price 2]}- :fields [price- [:expression "double_price" {::add/desired-alias "COOL.double_price"- ::add/position 1}]]- :limit 1})}- (let [double-price [:field- "double_price"- {:base-type :type/Integer- ::add/source-table ::add/source- ::add/source-alias "COOL.double_price"- ::add/desired-alias "COOL.COOL.double_price"- ::add/position 0}]]- ;; this is escaped once during preprocessing by- ;; the [[metabase.query-processor.middleware.pre-alias-aggregations]] middleware and then once- ;; more when we call [[metabase.query-processor.util.add-alias-info/add-alias-info]]- {:aggregation [[:aggregation-options [:count] {:name "COOL.COOL.count"- ::add/position 1- ::add/source-alias "COOL.count"- ::add/desired-alias "COOL.COOL.count"}]]- :breakout [double-price]- :order-by [[:asc double-price]]})))- (-> (lib.tu.macros/mbql-query venues- {:source-query {:source-table $$venues- :expressions {"double_price" [:* $price 2]}- :fields [$price- [:expression "double_price"]]- :limit 1}- :aggregation [[:count]]- :breakout [[:field "double_price" {:base-type :type/Integer}]]})- add-alias-info- :query)))))))+ (driver/with-driver ::custom-escape+ (is (=? (lib.tu.macros/$ids venues+ (merge+ {:source-query (let [price [:field %price {::add/source-table $$venues+ ::add/source-alias "PRICE"+ ::add/desired-alias "COOL.PRICE"}]]+ {:source-table $$venues+ :expressions {"double_price" [:* price 2]}+ :fields [price+ [:expression "double_price" {::add/desired-alias "COOL.double_price"}]]+ :limit 1})}+ (let [double-price [:field+ "double_price"+ {:base-type :type/Integer+ ::add/source-table ::add/source+ ::add/source-alias "COOL.double_price"+ ::add/desired-alias "COOL.double_price"}]]+ {:aggregation [[:aggregation-options [:count] {:name "COOL.count"+ ::add/desired-alias "COOL.COOL.count"}]]+ :breakout [double-price]+ :order-by [[:asc double-price]]})))+ (-> (lib.tu.macros/mbql-query venues+ {:source-query {:source-table $$venues+ :expressions {"double_price" [:* $price 2]}+ :fields [$price+ [:expression "double_price"]]+ :limit 1}+ :aggregation [[:count]]+ :breakout [[:field "double_price" {:base-type :type/Integer}]]})+ add-alias-info+ :query)))))(deftest ^:parallel custom-escape-alias-filtering-aggregation-test- (let [db (mt/db)]- (driver/with-driver ::custom-escape- (mt/with-db db- (is (=? (lib.tu.macros/$ids venues- (let [price [:field %price {::add/source-table $$venues- ::add/source-alias "PRICE"- ::add/desired-alias "COOL.PRICE"- ::add/position 0}]- outer-price (-> price- (assoc-in [2 ::add/source-table] ::add/source)- (update-in [2 ::add/source-alias] prefix-alias)- (update-in [2 ::add/desired-alias] prefix-alias))- count-opts {:name "COOL.strange count"- ::add/source-alias "strange count"- ::add/desired-alias "COOL.strange count"- ::add/position 1}- outer-count-opts (-> count-opts- (dissoc :name)- (assoc :base-type :type/Integer- ::add/source-table ::add/source)- (update ::add/source-alias prefix-alias)- (update ::add/desired-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}]]- :limit 1}))- (-> (lib.tu.macros/mbql-query venues- {:source-query {:source-table $$venues- :aggregation [[:aggregation-options- [:count]- {:name "strange count"}]]- :breakout [$price]}- :filter [:< [:field "strange count" {:base-type :type/Integer}] 10]- :limit 1})- add-alias-info- :query)))))))+ (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}]]}))+ (-> (lib.tu.macros/mbql-query venues+ {:source-query {:source-table $$venues+ :aggregation [[:aggregation-options+ [:count]+ {:name "strange count"}]]+ :breakout [$price]}+ :filter [:< [:field "strange count" {:base-type :type/Integer}] 10]})+ add-alias-info+ :query)))))(driver/register! ::custom-escape-spaces-to-underscores :parent :h2)@@ -498,17 +427,7 @@::add/source-table $$orders}][:field%products.id- {::add/desired-alias "Products_Renamed__ID"- ::add/position 0- ::add/source-alias "ID"- ::add/source-table "Products_Renamed"- :join-alias "Products Renamed"}]]- :fields- [[:field- %products.id- {::add/desired-alias "Products_Renamed__ID"- ::add/position 0- ::add/source-alias "ID"+ {::add/source-alias "ID"::add/source-table "Products_Renamed":join-alias "Products Renamed"}]]:strategy :left-join}]@@ -517,11 +436,10 @@[[:field%products.id{::add/desired-alias "Products_Renamed__ID"- ::add/position 0::add/source-alias "ID"::add/source-table "Products_Renamed":join-alias "Products Renamed"}]- [:expression "CC" {::add/desired-alias "CC", ::add/position 1}]]+ [:expression "CC" {::add/desired-alias "CC"}]]:filter[:=[:field@@ -538,14 +456,12 @@:fields [[:field%products.id{::add/desired-alias "Products_Renamed__ID"- ::add/position 0::add/source-alias "Products_Renamed__ID"::add/source-table ::add/source:join-alias "Products Renamed"}][:field"CC"{::add/desired-alias "CC"- ::add/position 1::add/source-alias "CC"::add/source-table ::add/source:base-type :type/Integer}]]@@ -620,20 +536,16 @@{:source-query {:source-table $$venues:fields [[:field name-id {::add/source-table $$venues::add/source-alias "NAME"- ::add/desired-alias "NAME"- ::add/position 0}]+ ::add/desired-alias "NAME"}][:field price-id {::add/source-table $$venues::add/source-alias "Name"- ::add/desired-alias "Name_2"- ::add/position 1}]]}+ ::add/desired-alias "Name_2"}]]}:fields [[:field name-id {::add/source-table ::add/source::add/source-alias "NAME"- ::add/desired-alias "NAME"- ::add/position 0}]+ ::add/desired-alias "NAME"}][:field price-id {::add/source-table ::add/source::add/source-alias "Name_2"- ::add/desired-alias "Name_2"- ::add/position 1}]]+ ::add/desired-alias "Name_2"}]]:limit 1})(-> (lib.tu.macros/mbql-query venues{:source-query {:source-table $$venues@@ -647,32 +559,27 @@(deftest ^:parallel aggregation-reference-test(testing "Make sure we add info to `:aggregation` reference clauses correctly"- (is (=? (lib.tu.macros/mbql-query checkins- {:aggregation [[:aggregation-options- [:sum [:field %user-id {::add/source-table $$checkins- ::add/source-alias "USER_ID"}]]- {:name "sum"- ::add/position 0- ::add/source-alias "sum"- ::add/desired-alias "sum"}]]- :order-by [[:asc [:aggregation 0 {::add/desired-alias "sum"- ::add/position 0}]]]})+ (is (=? (lib.tu.macros/$ids checkins+ {:stages [{:aggregation [[:sum+ {:name "sum"+ ::add/desired-alias "sum"}+ [:field {::add/source-table $$checkins+ ::add/source-alias "USER_ID"}+ %user-id]]]+ :order-by [[:asc+ {}+ [:aggregation {::add/desired-alias "sum"} string?]]]}]})(add-alias-info- (lib.tu.macros/mbql-query checkins- {:aggregation [[:sum $user-id]]- :order-by [[:asc [:aggregation 0]]]}))))))+ (lib.tu.macros/mbql-5-query checkins+ {:stages [{:aggregation [[:sum {:lib/uuid "00000000-0000-0000-0000-000000000001"} $user-id]]+ :order-by [[:asc {} [:aggregation {} "00000000-0000-0000-0000-000000000001"]]]}]}))))))(deftest ^:parallel uniquify-aggregation-names-text(is (=? (lib.tu.macros/mbql-query checkins{:expressions {"count" [:+ 1 1]}- :breakout [[:expression "count" {::add/desired-alias "count"- ::add/position 0}]]- :aggregation [[:aggregation-options [:count] {:name "count_2"- ::add/source-alias "count"- ::add/desired-alias "count_2"- ::add/position 1}]]- :order-by [[:asc [:expression "count" {::add/desired-alias "count"- ::add/position 0}]]]+ :breakout [[:expression "count" {::add/desired-alias "count"}]]+ :aggregation [[:aggregation-options [:count] {::add/desired-alias "count_2"}]]+ :order-by [[:asc [:expression "count" {::add/desired-alias "count"}]]]:limit 1})(add-alias-info(lib.tu.macros/mbql-query checkins@@ -681,92 +588,20 @@:aggregation [[:count]]:limit 1})))))-(deftest ^:parallel fuzzy-field-info-test- (testing "[[add/alias-from-join]] should match Fields in the Join source query even if they have temporal units"- (qp.store/with-metadata-provider meta/metadata-provider- (mt/with-driver :h2- (is (= {:field-name "CREATED_AT"- :join-is-this-level? "Q2"- :alias-from-join "Products__CREATED_AT"- :alias-from-source-query nil- :override-alias? false}- (#'add/expensive-field-info- (lib.tu.macros/$ids nil- {:source-table $$reviews- :joins [{:source-query {:source-table $$reviews- :breakout [[:field %products.created-at- {::add/desired-alias "Products__CREATED_AT"- ::add/position 0- ::add/source-alias "CREATED_AT"- ::add/source-table "Products"- :join-alias "Products"- :temporal-unit :month}]]}- :alias "Q2"}]})- [:field (meta/id :products :created-at) {:join-alias "Q2"}])))))))-(deftest ^:parallel expression-from-source-query-alias-test(testing "Make sure we use the exported alias from the source query for expressions (#21131)"- (let [source-query {:source-table 3- :expressions {"PRICE" [:+- [:field 2 {::add/source-table 3- ::add/source-alias "price"- ::add/desired-alias "price"- ::add/position 1}]- 2]}- :fields [[:field 2 {::add/source-table 3- ::add/source-alias "price"- ::add/desired-alias "price"- ::add/position 1}]- [:expression "PRICE" {::add/desired-alias "PRICE_2"- ::add/position 2}]]}]- (testing `add/exports- (is (= #{[:field 2 {::add/source-table 3- ::add/source-alias "price"- ::add/desired-alias "price"- ::add/position 1}]- [:expression "PRICE" {::add/desired-alias "PRICE_2"- ::add/position 2}]}- (#'add/exports source-query))))- (testing `add/matching-field-in-source-query- (is (= [:expression "PRICE" {::add/desired-alias "PRICE_2"- ::add/position 2}]- (#'add/matching-field-in-source-query- {:source-query source-query}- [:field "PRICE" {:base-type :type/Float}]))))- (testing `add/field-alias-in-source-query- (is (= "PRICE_2"- (#'add/field-alias-in-source-query- {:source-query source-query}- [:field "PRICE" {:base-type :type/Float}])))))))--(deftest ^:parallel find-matching-field-ignore-MLv2-extra-type-info-in-field-opts-test- (testing "MLv2 refs can include extra info like `:base-type`; make sure we ignore that when finding matching refs (#33083)"- (let [source-query {:source-table 1- :joins [{:alias "Card_2"- :source-query {:source-table 2- :breakout [[:field 78 {:join-alias "Products"- :temporal-unit :month- ::add/source-table "Products"- ::add/source-alias "CREATED_AT"- ::add/desired-alias "Products__CREATED_AT"- ::add/position 0}]]- :aggregation [[:aggregation-options- [:distinct [:field 76 {:join-alias "Products"- ::add/source-table "Products"- ::add/source-alias "ID"}]]- {:name "count"- ::add/source-alias "count"- ::add/position 1- ::add/desired-alias "count"}]]}}]}- field-clause [:field 78 {:base-type :type/DateTime, :temporal-unit :month, :join-alias "Card_2"}]]- (is (=? [:field- 78- {:join-alias "Products"- :temporal-unit :month- ::add/source-table "Products"- ::add/source-alias "CREATED_AT"- ::add/desired-alias "Products__CREATED_AT"}]- (#'add/matching-field-in-join-at-this-level source-query field-clause))))))+ (let [source-query (lib.tu.macros/mbql-query venues+ {:source-query {:source-table $$venues+ :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}]]}}+ (add-alias-info source-query))))))(defn- metadata-provider-with-two-models [](let [result-metadata-for (fn [column-name]@@ -776,9 +611,8 @@:base_type :type/Integer:effective_type :type/Integer:semantic_type nil- :fingerprint- {:global {:distinct-count 1, :nil% 0}- :type #:type{:Number {:min 1, :q1 1, :q3 1, :max 1, :sd nil, :avg 1}}}})]+ :fingerprint {:global {:distinct-count 1, :nil% 0}+ :type #:type{:Number {:min 1, :q1 1, :q3 1, :max 1, :sd nil, :avg 1}}}})](lib/composed-metadata-providermeta/metadata-provider(providers.mock/mock-metadata-provider@@ -800,22 +634,22 @@:native {:template-tags {} :query "select 1 as b1, 2 as b2;"}}:result-metadata [(result-metadata-for "B1")(result-metadata-for "B2")]}- {:name "Joined"- :id 3- :database-id (meta/id)- :type :model- :dataset-query {:database (meta/id)- :type :query- :query {:joins- [{:fields :all,- :alias "Model B - A1",- :strategy :inner-join,- :condition- [:=- [:field "A1" {:base-type :type/Integer}]- [:field "B1" {:base-type :type/Integer, :join-alias "Model B - A1"}]],- :source-table "card__2"}],- :source-table "card__1"}}}]}))))+ {:name "Joined"+ :id 3+ :database-id (meta/id)+ :type :model+ :dataset-query {:database (meta/id)+ :type :query+ :query {:joins+ [{:fields :all+ :alias "Model B - A1"+ :strategy :inner-join+ :condition+ [:=+ [:field "A1" {:base-type :type/Integer}]+ [:field "B1" {:base-type :type/Integer, :join-alias "Model B - A1"}]]+ :source-table "card__2"}]+ :source-table "card__1"}}}]}))))(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)"@@ -845,35 +679,32 @@(meta/id :orders :created-at){:temporal-unit :month::add/source-alias "CREATED_AT"- ::add/desired-alias "CREATED_AT"- ::add/position 0}]+ ::add/desired-alias "CREATED_AT"}][:field(meta/id :orders :created-at){:temporal-unit :day::add/source-alias "CREATED_AT"- ::add/desired-alias "CREATED_AT_2"- ::add/position 1}]]+ ::add/desired-alias "CREATED_AT_2"}]]:aggregation [[:aggregation-options[:count]{::add/source-alias "count"- ::add/position 2+::add/desired-alias "count"}]]:order-by [[:asc[:field(meta/id :orders :created-at){:temporal-unit :month::add/source-alias "CREATED_AT"- ::add/desired-alias "CREATED_AT"- ::add/position 0}]]+ ::add/desired-alias "CREATED_AT"}]][:asc[:field(meta/id :orders :created-at){:temporal-unit :day::add/source-alias "CREATED_AT"- ::add/desired-alias "CREATED_AT_2"- ::add/position 1}]]]}}+ ::add/desired-alias "CREATED_AT_2"}]]]}}(add/add-alias-info (qp.preprocess/preprocess query)))))))))+;;; see also [[metabase.lib.join.util-test/desired-alias-should-respect-ref-name-test]](deftest ^:parallel preserve-field-options-name-test(qp.store/with-metadata-provider meta/metadata-provider(driver/with-driver :h2@@ -894,11 +725,33 @@[:cum-sum [:field (meta/id :orders :id) nil]]{:name "sum"}]]}:breakout [[:field "id" {:base-type :type/Integer}]- [:field "sum" {:base-type :type/Integer, :name "__cumulative_sum"}]],+ [:field "sum" {:base-type :type/Integer, :name "__cumulative_sum"}]]:aggregation [[:aggregation-options[:cum-sum [:field "sum" {:base-type :type/Integer}]]{:name "sum"}]]}))))))+(deftest ^:parallel field-literals-test+ (testing "Correctly handle similar column names in nominal field literal refs (#41325)"+ (qp.store/with-metadata-provider meta/metadata-provider+ (driver/with-driver :h2+ (is (=? {:fields [[:field (meta/id :orders :created-at)+ {::add/source-alias "CREATED_AT"+ ::add/desired-alias "CREATED_AT"}]+ [:field (meta/id :orders :created-at)+ {::add/source-alias "CREATED_AT"+ ::add/desired-alias "CREATED_AT_2"}]+ [:field (meta/id :orders :total)+ {::add/source-alias "TOTAL"+ ::add/desired-alias "TOTAL"}]]}+ (-> (lib.tu.macros/mbql-query orders+ {:source-table $$orders+ :fields [!year.created-at+ !month.created-at+ $total]})+ qp.preprocess/preprocess+ add/add-alias-info+ :query)))))))+(deftest ^:parallel nested-query-field-literals-test(testing "Correctly handle similar column names in nominal field literal refs (#41325)"(qp.store/with-metadata-provider meta/metadata-provider@@ -961,8 +814,9 @@;; include the `:join-alias`) but this test is also testing that we detect this;; situation and handle it appropriately.:condition [:= !month.products.created-at !month.&Q2.products.created-at]}]})]- (is (=? {:source-query {:joins [{::add/alias "Products_2"}]}- :joins [{:source-query {:joins [{::add/alias "Products"}]}}]}+ ;; [[metabase.lib.walk]] is depth-first so the innermost queries should get first pick of aliases I guess+ (is (=? {:source-query {:joins [{::add/alias "Products"}]}+ :joins [{:source-query {:joins [{::add/alias "Products_2"}]}}]}(-> queryqp.preprocess/preprocess(add/add-alias-info {:globally-unique-join-aliases? true})@@ -971,71 +825,71 @@;;; adapted from [[metabase.query-processor-test.model-test/model-self-join-test]](deftest ^:parallel model-duplicate-joins-test(testing "Field references from model joined a second time can be resolved (#48639)"- (let [mp meta/metadata-provider- mp (lib.tu/mock-metadata-provider- mp- {:cards [{:id 1- :dataset-query- (-> (lib/query mp (lib.metadata/table mp (meta/id :products)))- (lib/join (-> (lib/join-clause (lib.metadata/table mp (meta/id :reviews))- [(lib/=- (lib.metadata/field mp (meta/id :products :id))- (lib.metadata/field mp (meta/id :reviews :product-id)))])- (lib/with-join-fields :all)))- lib/->legacy-MBQL)- :database-id (meta/id)- :name "Products+Reviews"- :type :model}]})- mp (lib.tu/mock-metadata-provider- mp- {:cards [{:id 2- :dataset-query- (binding [lib.metadata.calculation/*display-name-style* :long]- (as-> (lib/query mp (lib.metadata/card mp 1)) $q- (lib/aggregate $q (lib/sum (->> $q- lib/available-aggregation-operators- (m/find-first (comp #{:sum} :short))- :columns- (m/find-first (comp #{"Price"} :display-name)))))- (lib/breakout $q (-> (m/find-first (comp #{"Reviews → Created At"} :display-name)- (lib/breakoutable-columns $q))- (lib/with-temporal-bucket :month)))- (lib/->legacy-MBQL $q)))- :database-id (meta/id)- :name "Products+Reviews Summary"- :type :model}]})- question (binding [lib.metadata.calculation/*display-name-style* :long]- (as-> (lib/query mp (lib.metadata/card mp 1)) $q- (lib/breakout $q (-> (m/find-first (comp #{"Reviews → Created At"} :display-name)- (lib/breakoutable-columns $q))- (lib/with-temporal-bucket :month)))- (lib/aggregate $q (lib/avg (->> $q- lib/available-aggregation-operators- (m/find-first (comp #{:avg} :short))- :columns- (m/find-first (comp #{"Rating"} :display-name)))))- (lib/append-stage $q)- (letfn [(find-col [query display-name]- (or (m/find-first #(= (:display-name %) display-name)- (lib/breakoutable-columns query))- (throw (ex-info "Failed to find column with display name"- {:display-name display-name- :found (map :display-name (lib/breakoutable-columns query))}))))]- (lib/join $q (-> (lib/join-clause (lib.metadata/card mp 2)- [(lib/=- (lib/with-temporal-bucket (find-col $q "Reviews → Created At: Month")- :month)- (lib/with-temporal-bucket (find-col- (lib/query mp (lib.metadata/card mp 2))- "Reviews → Created At: Month")- :month))])- (lib/with-join-fields :all))))))]+ (let [mp meta/metadata-provider+ mp (lib.tu/mock-metadata-provider+ mp+ {:cards [{:id 1+ :dataset-query+ (-> (lib/query mp (lib.metadata/table mp (meta/id :products)))+ (lib/join (-> (lib/join-clause (lib.metadata/table mp (meta/id :reviews))+ [(lib/=+ (lib.metadata/field mp (meta/id :products :id))+ (lib.metadata/field mp (meta/id :reviews :product-id)))])+ (lib/with-join-fields :all)))+ lib/->legacy-MBQL)+ :database-id (meta/id)+ :name "Products+Reviews"+ :type :model}]})+ mp (lib.tu/mock-metadata-provider+ mp+ {:cards [{:id 2+ :dataset-query+ (binding [lib.metadata.calculation/*display-name-style* :long]+ (as-> (lib/query mp (lib.metadata/card mp 1)) $q+ (lib/aggregate $q (lib/sum (->> $q+ lib/available-aggregation-operators+ (m/find-first (comp #{:sum} :short))+ :columns+ (m/find-first (comp #{"Price"} :display-name)))))+ (lib/breakout $q (-> (m/find-first (comp #{"Reviews → Created At"} :display-name)+ (lib/breakoutable-columns $q))+ (lib/with-temporal-bucket :month)))+ (lib/->legacy-MBQL $q)))+ :database-id (meta/id)+ :name "Products+Reviews Summary"+ :type :model}]})+ query (binding [lib.metadata.calculation/*display-name-style* :long]+ (as-> (lib/query mp (lib.metadata/card mp 1)) $q+ (lib/breakout $q (-> (m/find-first (comp #{"Reviews → Created At"} :display-name)+ (lib/breakoutable-columns $q))+ (lib/with-temporal-bucket :month)))+ (lib/aggregate $q (lib/avg (->> $q+ lib/available-aggregation-operators+ (m/find-first (comp #{:avg} :short))+ :columns+ (m/find-first (comp #{"Rating"} :display-name)))))+ (lib/append-stage $q)+ (letfn [(find-col [query display-name]+ (or (m/find-first #(= (:display-name %) display-name)+ (lib/breakoutable-columns query))+ (throw (ex-info "Failed to find column with display name"+ {:display-name display-name+ :found (map :display-name (lib/breakoutable-columns query))}))))]+ (lib/join $q (-> (lib/join-clause (lib.metadata/card mp 2)+ [(lib/=+ (lib/with-temporal-bucket (find-col $q "Reviews → Created At: Month")+ :month)+ (lib/with-temporal-bucket (find-col+ (lib/query mp (lib.metadata/card mp 2))+ "Reviews → Created At: Month")+ :month))])+ (lib/with-join-fields :all))))))](qp.store/with-metadata-provider mp(driver/with-driver :h2- (let [preprocessed (-> question qp.preprocess/preprocess)+ (let [preprocessed (-> query qp.preprocess/preprocess)expected (add/add-alias-info preprocessed)](testing ":source-query -> :source-query -> :joins"- (is (=? [{:alias "Reviews"+ (is (=? [{:alias "Reviews":condition [:=[:field (meta/id :products :id){::add/source-alias "ID"}]@@ -1061,7 +915,7 @@[:field (meta/id :products :created-at){::add/source-alias "CREATED_AT", ::add/desired-alias "CREATED_AT"}][:field (meta/id :reviews :id)- {:join-alias "Reviews"+ {:join-alias "Reviews"::add/source-alias "ID", ::add/desired-alias "Reviews__ID"}][:field (meta/id :reviews :product-id){:join-alias "Reviews", ::add/source-alias "PRODUCT_ID", ::add/desired-alias "Reviews__PRODUCT_ID"}]@@ -1077,16 +931,16 @@(testing ":source-query";; we should be using `Reviews__` here for names(is (=? {:source-query/model? true- :breakout [[:field- "Reviews__CREATED_AT"- {::add/source-alias "Reviews__CREATED_AT", ::add/desired-alias "Reviews__CREATED_AT"}]]- :aggregation [[:aggregation-options- [:avg [:field "RATING" {::add/source-alias "RATING"}]]- {:name "avg", ::add/source-alias "avg", ::add/desired-alias "avg"}]]- :order-by [[:asc- [:field- "Reviews__CREATED_AT"- {::add/source-alias "Reviews__CREATED_AT", ::add/desired-alias "Reviews__CREATED_AT"}]]]}+ :breakout [[:field+ "Reviews__CREATED_AT"+ {::add/source-alias "Reviews__CREATED_AT", ::add/desired-alias "Reviews__CREATED_AT"}]]+ :aggregation [[:aggregation-options+ [:avg [:field "RATING" {::add/source-alias "RATING"}]]+ {:name "avg", ::add/desired-alias "avg"}]]+ :order-by [[:asc+ [:field+ "Reviews__CREATED_AT"+ {::add/source-alias "Reviews__CREATED_AT", ::add/desired-alias "Reviews__CREATED_AT"}]]]}(-> expected :query :source-query (dissoc :source-query)))))))))));;; adapted from [[metabase.query-processor-test.uuid-test/joined-uuid-query-test]]@@ -1098,7 +952,7 @@:query {:source-table 1 ; people:joins [{:source-table 2 ; dogs:condition [:=- [:field #_dogs.person-id 5 {:join-alias "j"}]+ [:field #_dogs.person-id 5 {:join-alias "d"}][:field #_people.id 1 nil]]:alias "d":fields :all}]@@ -1118,3 +972,325 @@qp.preprocess/preprocessadd/add-alias-info:query))))))))++(deftest ^:parallel nested-literal-boolean-expression-with-name-collisions-test+ (testing "nested literal boolean expression references with name collisions in filter and case clauses"+ ;; Test boolean->comparison conversion for drivers that need it. See boolean_to_comparison.clj. Other drivers+ ;; should support these queries without rewriting top-level booleans in conditions.+ (let [true-value [:value {:base-type :type/Boolean, :effective-type :type/Boolean, :lib/expression-name "T"} true]+ false-value [:value {:base-type :type/Boolean, :effective-type :type/Boolean, :lib/expression-name "F"} false]+ query (lib.tu.macros/mbql-5-query nil+ {:stages [{:source-table $$orders+ :expressions [true-value+ false-value]+ :fields [[:expression {} "T"]+ [:expression {} "F"]]}+ {:expressions [true-value+ false-value]+ :fields [[:expression {} "T"]+ [:expression {} "F"]+ [:field {:base-type :type/Boolean} "T"]+ [:field {:base-type :type/Boolean} "F"]]}+ {:expressions [true-value+ false-value]+ :aggregation [[:count-where {} *T/Boolean]+ [:count-where {} *F/Boolean]]+ :filters [[:or {}+ [:expression {} "T"]+ [:expression {} "F"]]+ [:or {}+ [:field {:base-type :type/Boolean} "T"]+ [:field {:base-type :type/Boolean} "F"]]]}]})]+ (testing "Sanity check: Lib should return deduplicated desired aliases for the second stage"+ (is (=? [{:lib/source-column-alias "T"+ :lib/desired-column-alias "T"+ :lib/source :source/expressions}+ {:lib/source-column-alias "F"+ :lib/desired-column-alias "F"+ :lib/source :source/expressions}+ {:lib/source-column-alias "T"+ :lib/desired-column-alias "T_2"+ :lib/source :source/previous-stage}+ {:lib/source-column-alias "F"+ :lib/desired-column-alias "F_2"+ :lib/source :source/previous-stage}]+ (lib/returned-columns+ (lib/query meta/metadata-provider query)+ 1))))+ (is (=? {:stages [{}+ {:fields [[:expression+ {::add/source-table ::add/none+ ::add/desired-alias "T"}+ "T"]+ [:expression+ {::add/source-table ::add/none+ ::add/desired-alias "F"}+ "F"]+ [:field+ {::add/source-table ::add/source+ ::add/source-alias "T"+ ::add/desired-alias "T_2"}+ "T"]+ [:field+ {::add/source-table ::add/source+ ::add/source-alias "F"+ ::add/desired-alias "F_2"}+ "F"]]}+ {:filters [[:or {}+ [:expression+ {::add/source-table ::add/none}+ "T"]+ [:expression+ {::add/source-table ::add/none}+ "F"]]+ [:or {}+ [:field+ {::add/source-table ::add/source, ::add/source-alias "T"}+ "T"]+ [:field+ {::add/source-table ::add/source, ::add/source-alias "F"}+ "F"]]]}]}+ (add-alias-info query))))))++(deftest ^:parallel respect-crazy-long-native-identifiers-test+ (testing "respect crazy-long identifiers returned by native stages (#47584)"+ (let [mp (lib.tu/mock-metadata-provider+ meta/metadata-provider+ {:cards [{:id 1+ :dataset-query {:type :native+ :database (meta/id)+ :native {:query "SELECT *"}}+ :result-metadata [{:base_type :type/Text+ :database_type "CHARACTER VARYING"+ :display_name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :effective_type :type/Text+ :name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"+ :lib/source :source/native}]}]})+ query (-> (lib/query mp (lib.metadata/card mp 1))+ lib/append-stage)]+ (is (=? {:stages [{:native "SELECT *"}+ {:fields [[:field+ {::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_state_and_then_we_do_a_count"+ ::add/source-table ::add/source}+ "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"]]}+ {:fields [[:field+ {::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"]]}]}+ (add-alias-info query))))))++;;; in the future when we remove all the roundtripping that happens inside of the QP then we can remove this test+;;; entirely.+(deftest ^:parallel additional-keys-should-survive-preprocessing-test+ (driver/with-driver :h2+ (let [query (lib/query+ meta/metadata-provider+ (lib.tu.macros/mbql-query orders+ {:aggregation [[:aggregation-options [:count] {:name "count"}]]+ :breakout [&PRODUCTS__via__PRODUCT_ID.products.category+ !year.created-at+ [:expression "pivot-grouping"]]+ :expressions {"pivot-grouping" [:abs 0]}+ :order-by [[:asc &PRODUCTS__via__PRODUCT_ID.products.category]+ [:asc !year.created-at]+ [:asc [:expression "pivot-grouping"]]]+ :joins [{:source-table $$products+ :strategy :left-join+ :alias "PRODUCTS__via__PRODUCT_ID"+ :fk-field-id %product-id+ :condition [:= $product-id &PRODUCTS__via__PRODUCT_ID.products.id]}]}))]+ (is (=? [[:expression "pivot-grouping" {::add/source-table ::add/none, ::add/desired-alias "pivot-grouping"}]+ [:expression "pivot-grouping" {::add/source-table ::add/none, ::add/desired-alias "pivot-grouping"}]]+ (lib.util.match/match (-> query+ add/add-alias-info+ qp.preprocess/preprocess)+ :expression))))))++(deftest ^:parallel remapped-columns-in-joined-source-queries-test+ (testing "Make sure remapped columns are given correct aliases and escaped correctly for drivers like Oracle"+ (let [mp (-> meta/metadata-provider+ (lib.tu/remap-metadata-provider (meta/id :orders :product-id) (meta/id :products :title)))+ query (lib/query+ mp+ (lib.tu.macros/mbql-query products+ {:joins [{:source-query {:source-table $$orders+ :breakout [$orders.product-id]+ :aggregation [[:sum $orders.quantity]]}+ :alias "Orders"+ :condition [:= $id &Orders.orders.product-id]+ ;; we can get title since product_id is remapped to title+ :fields [&Orders.title+ &Orders.*sum/Integer]}]+ :fields [$title $category]+ :order-by [[:asc $id]]+ :limit 3}))+ ;; this is a basically the same as Oracle's behavior for truncating aliases+ query (binding [add/*escape-alias-fn* (fn [_driver s]+ (let [s (str/replace s #"[\"\u0000]" "_")]+ (lib.util/truncate-alias s 30)))]+ (add-alias-info query))+ stage (-> query :stages first)+ stage-join (-> stage :joins first)+ stage-join-stage (-> stage-join :stages first)+ stage-join-stage-join (-> stage-join-stage :joins first)]+ (testing ":stages -> first -> :joins -> first -> :stages -> first -> :joins -> first"+ (is (=? {:stages [{:source-table (meta/id :products)}]+ ::add/original-alias "PRODUCTS__via__PRODUCT_ID"+ ::add/alias "PRODUCTS__via__PRODUCT_ID"+ :alias "PRODUCTS__via__PRODUCT_ID"+ :conditions [[:= {}+ [:field {::add/source-table (meta/id :orders)+ ::add/source-alias "PRODUCT_ID"}+ any?]+ [:field {:join-alias "PRODUCTS__via__PRODUCT_ID"+ ::add/source-alias "ID"+ ::add/source-table "PRODUCTS__via__PRODUCT_ID"}+ any?]]]}+ stage-join-stage-join)))+ (testing ":stages -> first -> :joins -> first -> :stages -> first"+ (is (=? {:breakout [[:field {::add/source-alias "TITLE"+ :join-alias "PRODUCTS__via__PRODUCT_ID"+ ::add/desired-alias "PRODUCTS__via__PRODUC_8b0b9fea"+ ::add/source-table "PRODUCTS__via__PRODUCT_ID"}+ any?]+ [:field {::add/source-alias "PRODUCT_ID"+ ::add/desired-alias "PRODUCT_ID"+ ::add/source-table (meta/id :orders)}+ any?]]+ :order-by [[:asc {}+ [:field {::add/source-alias "TITLE"+ :join-alias "PRODUCTS__via__PRODUCT_ID"+ ::add/desired-alias "PRODUCTS__via__PRODUC_8b0b9fea"+ ::add/source-table "PRODUCTS__via__PRODUCT_ID"}+ any?]]]+ :aggregation [[:sum {:name "sum"+ ::add/source-table ::add/none+ ::add/source-alias "sum"+ ::add/desired-alias "sum"}+ [:field {::add/source-table (meta/id :orders)+ ::add/source-alias "QUANTITY"+ ::add/desired-alias nil}+ any?]]]}+ (dissoc stage-join-stage :joins))))+ (testing ":stages -> first -> :joins -> first"+ (is (=? {:conditions [[:= {}+ [:field {::add/source-table (meta/id :products)+ ::add/source-alias "ID"}+ any?]+ [:field {:join-alias "Orders"+ ::add/source-alias "PRODUCT_ID"+ ::add/source-table "Orders"}+ any?]]]}+ (dissoc stage-join :stages))))+ (testing ":stages -> first"+ (is (=? {:fields [[:field {::add/desired-alias "TITLE"+ ::add/source-alias "TITLE"+ ::add/source-table (meta/id :products)}+ any?]+ [:field {::add/desired-alias "CATEGORY"+ ::add/source-alias "CATEGORY"+ ::add/source-table (meta/id :products)}+ any?]+ [:field {:join-alias "Orders"+ ::add/desired-alias "Orders__PRODUCTS__via_6256d0ed"+ ::add/source-alias "PRODUCTS__via__PRODUC_8b0b9fea"+ ::add/source-table "Orders"}+ any?]+ [:field {:join-alias "Orders"+ ::add/desired-alias "Orders__sum"+ ::add/source-alias "sum"+ ::add/source-table "Orders"}+ "sum"]]}+ (dissoc stage :joins)))))))++(deftest ^:parallel nested-fields-test+ (let [mp metabase.lib.field-test/grandparent-parent-child-metadata-provider+ query (lib/query+ mp+ (lib.tu.macros/mbql-query venues+ {:order-by [[:asc [:field (metabase.lib.field-test/grandparent-parent-child-id :grandparent) nil]]+ [:asc [:field (metabase.lib.field-test/grandparent-parent-child-id :parent) nil]]+ [:asc [:field (metabase.lib.field-test/grandparent-parent-child-id :child) nil]]]}))]+ (is (=? {:order-by [[:asc {}+ [:field {::add/source-table (meta/id :venues)+ ::add/source-alias "grandparent"+ ::add/desired-alias "grandparent"}+ any?]]+ [:asc {}+ [:field {::add/source-table (meta/id :venues)+ ::add/nfc-path ["grandparent"]+ ::add/source-alias "parent"+ ::add/desired-alias "parent"}+ any?]]+ [:asc {}+ [:field {::add/source-table (meta/id :venues)+ ::add/nfc-path ["grandparent" "parent"]+ ::add/source-alias "child"+ ::add/desired-alias "child"}+ any?]]]}+ (-> (add-alias-info query)+ :stages+ first)))))++(deftest ^:parallel multiple-breakouts-on-same-column-test+ (let [query (lib/query+ meta/metadata-provider+ {:database (meta/id)+ :type :query+ :query {:source-table (meta/id :orders)+ :aggregation [[:count]]+ :breakout [[:field+ (meta/id :orders :total)+ {:base-type :type/Float, :binning {:strategy :num-bins, :num-bins 10}}]+ [:field+ (meta/id :orders :total)+ {:base-type :type/Float, :binning {:strategy :num-bins, :num-bins 50}}]]}})]+ (is (=? {:aggregation [[:count+ {:name "count"+ ::add/source-table ::add/none+ ::add/source-alias "count"+ ::add/desired-alias "count"}]]+ :breakout [[:field+ {:binning {:strategy :num-bins, :num-bins 10}+ ::add/source-table (meta/id :orders)+ ::add/source-alias "TOTAL"+ ::add/desired-alias "TOTAL"}+ any?]+ [:field+ {:binning {:strategy :num-bins, :num-bins 50}+ ::add/source-table (meta/id :orders)+ ::add/source-alias "TOTAL"+ ::add/desired-alias "TOTAL_2"}+ any?]]}+ (-> (add-alias-info query)+ :stages+ first)))))++;;; see also [[metabase.driver.sql.query-processor-test/evil-field-ref-for-an-expression-test]]+;;; and [[metabase-enterprise.sandbox.query-processor.middleware.row-level-restrictions-test/evil-field-ref-for-an-expression-test]]+(deftest ^:parallel resolve-incorrect-field-ref-for-expression-test+ (testing "resolve the incorrect use of a :field ref for an expression correctly"+ (let [query (lib/query+ meta/metadata-provider+ (lib.tu.macros/mbql-query venues+ {:fields [[:expression "my_numberLiteral"]]+ :expressions {"my_numberLiteral" [:value 1 {:base_type :type/Integer}]}+ :filter [:=+ [:field "my_numberLiteral" {:base-type :type/Integer}]+ [:value 1 {:base_type :type/Integer}]]}))]+ (is (=? [:=+ {}+ ;; convert the ref to an `:expression` ref so it can get compiled correctly.+ [:expression+ {::add/desired-alias "my_numberLiteral"+ ::add/source-alias "my_numberLiteral"+ ::add/source-table ::add/none}+ "my_numberLiteral"]+ [:value {} 1]]+ (-> (add-alias-info query)+ :stages+ first+ :filters+ first))))))diff --git a/test/metabase/query_processor/util/nest_query_test.clj b/test/metabase/query_processor/util/nest_query_test.cljindex e080791642c..eb8a66a7e43 100644--- a/test/metabase/query_processor/util/nest_query_test.clj+++ b/test/metabase/query_processor/util/nest_query_test.clj@@ -43,31 +43,24 @@{:source-query {:source-table $$venues:expressions {"double_price" [:* [:field %price {::add/source-table $$venues::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]+ ::add/desired-alias "PRICE"}]2]}:fields [[:field %price {::add/source-table $$venues::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]- [:expression "double_price" {::add/desired-alias "double_price"- ::add/position 1}]]}+ ::add/desired-alias "PRICE"}]+ [:expression "double_price" {::add/desired-alias "double_price"}]]}:breakout [[:field %price {::add/source-table ::add/source::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]+ ::add/desired-alias "PRICE"}][:field "double_price" {:base-type :type/Integer::add/source-table ::add/source::add/source-alias "double_price"- ::add/desired-alias "double_price"- ::add/position 1}]]+ ::add/desired-alias "double_price"}]]:aggregation [[:aggregation-options [:count] {:name "count"- ::add/desired-alias "count"- ::add/position 2}]]+ ::add/desired-alias "count"}]]:order-by [[:asc [:field %price {::add/source-table ::add/source::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]]]})+ ::add/desired-alias "PRICE"}]]]})(-> (lib.tu.macros/mbql-query venues{:expressions {"double_price" [:* $price 2]}:breakout [$price@@ -85,15 +78,12 @@{:source-query {:source-table $$venues:expressions {"double_price" [:* [:field %price {::add/source-table $$venues::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]+ ::add/desired-alias "PRICE"}]2]}:fields [[:field %price {::add/source-table $$venues::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]- [:expression "double_price" {::add/desired-alias "double_price"- ::add/position 1}]]}+ ::add/desired-alias "PRICE"}]+ [:expression "double_price" {::add/desired-alias "double_price"}]]}:order-by [[:asc *double_price/Integer]]})(-> (lib.tu.macros/mbql-query venues{:expressions {"double_price" [:* $price 2]}@@ -113,20 +103,16 @@:expressions {"favorite" [:value "good venue" {:base_type :type/Text}]}:fields [[:field %name {::add/source-table $$venues::add/source-alias "NAME"- ::add/desired-alias "NAME"- ::add/position 0}]- [:expression "favorite" {::add/desired-alias "favorite"- ::add/position 1}]]}+ ::add/desired-alias "NAME"}]+ [:expression "favorite" {::add/desired-alias "favorite"}]]}:filter [:= [:field %name {::add/source-table ::add/source::add/source-alias "NAME"::add/desired-alias "NAME"- ::add/position 0:qp/ignore-coercion true}][:field "favorite" {:base-type :type/Text::add/source-table ::add/source::add/source-alias "favorite"- ::add/desired-alias "favorite"- ::add/position 1}]]+ ::add/desired-alias "favorite"}]]:order-by [[:asc *favorite/Text]]})(-> (lib.tu.macros/mbql-query venues{:expressions {"favorite" [:value "good venue" {:base_type :type/Text}]}@@ -146,34 +132,26 @@{:source-query {:source-table $$venues:expressions {"big_price"[:+- [:field %price {::add/position 1- ::add/source-table $$venues+ [:field %price {::add/source-table $$venues::add/source-alias "PRICE"::add/desired-alias "PRICE"}]2]"my_cool_new_field"[:/- [:field %price {::add/position 1- ::add/source-table $$venues+ [:field %price {::add/source-table $$venues::add/source-alias "PRICE"::add/desired-alias "PRICE"}]- [:expression "big_price" {::add/position 2- ::add/desired-alias "big_price"}]]}- :fields [[:field %id {::add/position 0- ::add/source-table $$venues+ [:expression "big_price" {::add/desired-alias "big_price"}]]}+ :fields [[:field %id {::add/source-table $$venues::add/source-alias "ID"::add/desired-alias "ID"}]- [:field %price {::add/position 1- ::add/source-table $$venues+ [:field %price {::add/source-table $$venues::add/source-alias "PRICE"::add/desired-alias "PRICE"}]- [:expression "big_price" {::add/position 2- ::add/desired-alias "big_price"}]- [:expression "my_cool_new_field" {::add/position 3- ::add/desired-alias "my_cool_new_field"}]]}+ [:expression "big_price" {::add/desired-alias "big_price"}]+ [:expression "my_cool_new_field" {::add/desired-alias "my_cool_new_field"}]]}:breakout [[:field "my_cool_new_field" {:base-type :type/Float- ::add/position 0::add/source-table ::add/source::add/source-alias "my_cool_new_field"::add/desired-alias "my_cool_new_field"}]]@@ -237,13 +215,11 @@[:expression "x" #::add{:desired-alias "x_2"}]]}:breakout [[:field %id #::add{:source-table ::add/source:source-alias "ID"- :desired-alias "ID"- :position 0}]+ :desired-alias "ID"}][:field "x_2" {:base-type :type/Integer::add/source-table ::add/source::add/source-alias "x_2"- ::add/desired-alias "x_2"- ::add/position 1}]]+ ::add/desired-alias "x_2"}]]:limit 1})(-> query add/add-alias-info nest-expressions)))))))))@@ -356,22 +332,17 @@{:source-query {:source-table $$venues:joins [{:strategy :left-join:condition [:=- [:field %category-id {::add/source-table $$venues- ::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CATEGORY_ID"- ::add/position 2}]- [:field %category-id {:join-alias "CategoriesStats"- ::add/source-table "CategoriesStats"- ::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CategoriesStats__CATEGORY_ID"- ::add/position 7}]]+ [:field %category-id {::add/source-table $$venues+ ::add/source-alias "CATEGORY_ID"}]+ [:field %category-id {:join-alias "CategoriesStats"+ ::add/source-table "CategoriesStats"+ ::add/source-alias "CATEGORY_ID"}]]:source-query {:source-table $$venues:aggregation [[:aggregation-options[:max [:field %price {::add/source-table $$venues::add/source-alias "PRICE"}]]{:name "MaxPrice"- ::add/desired-alias "MaxPrice"- ::add/position 1}]+ ::add/desired-alias "MaxPrice"}][:aggregation-options[:avg[:field@@ -379,158 +350,111 @@{::add/source-table $$venues::add/source-alias "PRICE"}]]{:name "AvgPrice"- ::add/desired-alias "AvgPrice"- ::add/position 2}]+ ::add/desired-alias "AvgPrice"}][:aggregation-options[:min [:field %price {::add/source-table $$venues::add/source-alias "PRICE"}]]{:name "MinPrice"- ::add/desired-alias "MinPrice"- ::add/position 3}]]+ ::add/desired-alias "MinPrice"}]]:breakout [[:field %category-id {::add/source-table $$venues::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CATEGORY_ID"- ::add/position 0}]]+ ::add/desired-alias "CATEGORY_ID"}]]:order-by [[:asc [:field %category-id {::add/source-table $$venues::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CATEGORY_ID"- ::add/position 0}]]]}+ ::add/desired-alias "CATEGORY_ID"}]]]}:alias "CategoriesStats"- :fields [[:field %category-id {:join-alias "CategoriesStats"- ::add/source-table "CategoriesStats"- ::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CategoriesStats__CATEGORY_ID"- ::add/position 7}]- [:field "MaxPrice" {:base-type :type/Integer- :join-alias "CategoriesStats"- ::add/source-table "CategoriesStats"- ::add/source-alias "MaxPrice"- ::add/desired-alias "CategoriesStats__MaxPrice"- ::add/position 8}]- [:field "AvgPrice" {:base-type :type/Float- :join-alias "CategoriesStats"- ::add/source-table "CategoriesStats"- ::add/source-alias "AvgPrice"- ::add/desired-alias "CategoriesStats__AvgPrice"- ::add/position 9}]- [:field "MinPrice" {:base-type :type/Integer- :join-alias "CategoriesStats"- ::add/source-table "CategoriesStats"- ::add/source-alias "MinPrice"- ::add/desired-alias "CategoriesStats__MinPrice"- ::add/position 10}]]}]+ :fields [[:field %category-id {:join-alias "CategoriesStats"}]+ [:field "MaxPrice" {:join-alias "CategoriesStats"}]+ [:field "AvgPrice" {:join-alias "CategoriesStats"}]+ [:field "MinPrice" {:join-alias "CategoriesStats"}]]}]:expressions {"RelativePrice" [:/[:field %price {::add/source-table $$venues::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 5}]+ ::add/desired-alias "PRICE"}][:field "AvgPrice" {:base-type :type/Integer:join-alias "CategoriesStats"::add/source-table "CategoriesStats"::add/source-alias "AvgPrice"- ::add/desired-alias "CategoriesStats__AvgPrice"- ::add/position 9}]]}+ ::add/desired-alias "CategoriesStats__AvgPrice"}]]}:fields [[:field %id {::add/source-table $$venues::add/source-alias "ID"- ::add/desired-alias "ID"- ::add/position 0}]+ ::add/desired-alias "ID"}][:field %name {::add/source-table $$venues::add/source-alias "NAME"- ::add/desired-alias "NAME"- ::add/position 1}]+ ::add/desired-alias "NAME"}][:field %category-id {::add/source-table $$venues::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CATEGORY_ID"- ::add/position 2}]+ ::add/desired-alias "CATEGORY_ID"}][:field %latitude {::add/source-table $$venues::add/source-alias "LATITUDE"- ::add/desired-alias "LATITUDE"- ::add/position 3}]+ ::add/desired-alias "LATITUDE"}][:field %longitude {::add/source-table $$venues::add/source-alias "LONGITUDE"- ::add/desired-alias "LONGITUDE"- ::add/position 4}]+ ::add/desired-alias "LONGITUDE"}][:field %price {::add/source-table $$venues::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 5}]- [:expression "RelativePrice" {::add/desired-alias "RelativePrice"- ::add/position 6}]+ ::add/desired-alias "PRICE"}]+ [:expression "RelativePrice" {::add/desired-alias "RelativePrice"}][:field %category-id {:join-alias "CategoriesStats"::add/source-table "CategoriesStats"::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CategoriesStats__CATEGORY_ID"- ::add/position 7}]+ ::add/desired-alias "CategoriesStats__CATEGORY_ID"}][:field "MaxPrice" {:base-type :type/Integer:join-alias "CategoriesStats"::add/source-table "CategoriesStats"::add/source-alias "MaxPrice"- ::add/desired-alias "CategoriesStats__MaxPrice"- ::add/position 8}]+ ::add/desired-alias "CategoriesStats__MaxPrice"}][:field "AvgPrice" {:base-type :type/Float:join-alias "CategoriesStats"::add/source-table "CategoriesStats"::add/source-alias "AvgPrice"- ::add/desired-alias "CategoriesStats__AvgPrice"- ::add/position 9}]+ ::add/desired-alias "CategoriesStats__AvgPrice"}][:field "MinPrice" {:base-type :type/Integer:join-alias "CategoriesStats"::add/source-table "CategoriesStats"::add/source-alias "MinPrice"- ::add/desired-alias "CategoriesStats__MinPrice"- ::add/position 10}]]}+ ::add/desired-alias "CategoriesStats__MinPrice"}]]}:breakout [[:field %id {::add/source-table ::add/source::add/source-alias "ID"- ::add/desired-alias "ID"- ::add/position 0}]+ ::add/desired-alias "ID"}][:field %name {::add/source-table ::add/source::add/source-alias "NAME"- ::add/desired-alias "NAME"- ::add/position 1}]+ ::add/desired-alias "NAME"}][:field %category-id {::add/source-table ::add/source::add/source-alias "CATEGORY_ID"- ::add/desired-alias "CATEGORY_ID"- ::add/position 2}]+ ::add/desired-alias "CATEGORY_ID"}][:field %latitude {::add/source-table ::add/source::add/source-alias "LATITUDE"- ::add/desired-alias "LATITUDE"- ::add/position 3}]+ ::add/desired-alias "LATITUDE"}][:field %longitude {::add/source-table ::add/source::add/source-alias "LONGITUDE"- ::add/desired-alias "LONGITUDE"- ::add/position 4}]+ ::add/desired-alias "LONGITUDE"}][:field %price {::add/source-table ::add/source::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 5}]+ ::add/desired-alias "PRICE"}][:field "RelativePrice" {:base-type :type/Float::add/source-table ::add/source::add/source-alias "RelativePrice"- ::add/desired-alias "RelativePrice"- ::add/position 6}]+ ::add/desired-alias "RelativePrice"}][:field %category-id {:join-alias "CategoriesStats"::add/source-alias "CategoriesStats__CATEGORY_ID"::add/desired-alias "CategoriesStats__CATEGORY_ID"- ::add/source-table ::add/source- ::add/position 7}]+ ::add/source-table ::add/source}][:field "MaxPrice" {:base-type :type/Integer:join-alias "CategoriesStats"::add/source-alias "CategoriesStats__MaxPrice"::add/desired-alias "CategoriesStats__MaxPrice"- ::add/source-table ::add/source- ::add/position 8}]+ ::add/source-table ::add/source}][:field "AvgPrice" {:base-type :type/Integer:join-alias "CategoriesStats"::add/source-alias "CategoriesStats__AvgPrice"::add/desired-alias "CategoriesStats__AvgPrice"- ::add/source-table ::add/source- ::add/position 9}]+ ::add/source-table ::add/source}][:field "MinPrice" {:base-type :type/Integer:join-alias "CategoriesStats"::add/source-alias "CategoriesStats__MinPrice"::add/desired-alias "CategoriesStats__MinPrice"- ::add/source-table ::add/source- ::add/position 10}]]+ ::add/source-table ::add/source}]]:limit 3})(-> (lib.tu.macros/mbql-query venues{:breakout [$id@@ -567,34 +491,30 @@{:fields [{:id (meta/id :venues :price):coercion-strategy :Coercion/UNIXSeconds->DateTime:effective-type :type/DateTime}]})- (is (partial= (lib.tu.macros/$ids venues- {:source-query {:source-table $$venues- :expressions {"test" [:* 1 1]}- :fields [[:field %price {::add/source-table $$venues- ::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]- [:expression "test" {::add/desired-alias "test"- ::add/position 1}]]}- :breakout [[:field %price {:temporal-unit :day- :qp/ignore-coercion true- ::add/source-table ::add/source- ::add/source-alias "PRICE"- ::add/desired-alias "PRICE"- ::add/position 0}]- [:field "test" {:base-type :type/Integer- ::add/source-table ::add/source- ::add/source-alias "test"- ::add/desired-alias "test"- ::add/position 1}]]- :limit 1})- (-> (lib.tu.macros/mbql-query venues- {:expressions {"test" [:* 1 1]}- :breakout [$price- [:expression "test"]]- :limit 1})- add/add-alias-info- nest-expressions)))))))+ (is (=? (lib.tu.macros/$ids venues+ {:source-query {:source-table $$venues+ :expressions {"test" [:* 1 1]}+ :fields [[:field %price {::add/source-table $$venues+ ::add/source-alias "PRICE"+ ::add/desired-alias "PRICE"}]+ [:expression "test" {::add/desired-alias "test"}]]}+ :breakout [[:field %price {:temporal-unit :day+ :qp/ignore-coercion true+ ::add/source-table ::add/source+ ::add/source-alias "PRICE"+ ::add/desired-alias "PRICE"}]+ [:field "test" {:base-type :type/Integer+ ::add/source-table ::add/source+ ::add/source-alias "test"+ ::add/desired-alias "test"}]]+ :limit 1})+ (-> (lib.tu.macros/mbql-query venues+ {:expressions {"test" [:* 1 1]}+ :breakout [$price+ [:expression "test"]]+ :limit 1})+ add/add-alias-info+ nest-expressions)))))))(deftest ^:parallel multiple-joins-with-expressions-test(testing "We should be able to compile a complicated query with multiple joins and expressions correctly"@@ -605,39 +525,32 @@[:field %products.category {:join-alias "PRODUCTS__via__PRODUCT_ID"::add/source-table ::add/source::add/source-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"- ::add/desired-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"- ::add/position 0}])+ ::add/desired-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"}])created-at (lib.tu.macros/$ids orders[:field %created-at {:temporal-unit :year:qp/ignore-coercion true::add/source-table ::add/source::add/source-alias "CREATED_AT"- ::add/desired-alias "CREATED_AT"- ::add/position 1}])+ ::add/desired-alias "CREATED_AT"}])pivot-grouping [:field "pivot-grouping" {:base-type :type/Float::add/source-table ::add/source::add/source-alias "pivot-grouping"- ::add/desired-alias "pivot-grouping"- ::add/position 2}]]+ ::add/desired-alias "pivot-grouping"}]](lib.tu.macros/mbql-query orders{:breakout [products-category created-at pivot-grouping]:aggregation [[:aggregation-options [:count] {:name "count"- ::add/desired-alias "count"- ::add/position 3}]]+ ::add/desired-alias "count"}]]:order-by [[:asc products-category][:asc created-at][:asc pivot-grouping]]}))(lib.tu.macros/mbql-query orders{:source-query (let [product-id [:field %product-id {::add/source-table $$orders::add/source-alias "PRODUCT_ID"- ::add/desired-alias "PRODUCT_ID"- ::add/position 0}]+ ::add/desired-alias "PRODUCT_ID"}]created-at [:field %created-at {::add/source-table $$orders::add/source-alias "CREATED_AT"- ::add/desired-alias "CREATED_AT"- ::add/position 1}]- pivot-grouping [:expression "pivot-grouping" {::add/desired-alias "pivot-grouping"- ::add/position 2}]+ ::add/desired-alias "CREATED_AT"}]+ pivot-grouping [:expression "pivot-grouping" {::add/desired-alias "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@@ -650,25 +563,28 @@products-id [:field %products.id {:join-alias "PRODUCTS__via__PRODUCT_ID"::add/source-table "PRODUCTS__via__PRODUCT_ID"::add/source-alias "ID"- ::add/desired-alias "PRODUCTS__via__PRODUCT_ID__ID"- ::add/position 4}]+ ::add/desired-alias "PRODUCTS__via__PRODUCT_ID__ID"}]products-category [:field %products.category {:join-alias "PRODUCTS__via__PRODUCT_ID"::add/source-table "PRODUCTS__via__PRODUCT_ID"::add/source-alias "CATEGORY"- ::add/desired-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"- ::add/position 3}]]+ ::add/desired-alias "PRODUCTS__via__PRODUCT_ID__CATEGORY"}]]{:source-table $$orders:joins [{:source-query {:source-table $$products}:alias "PRODUCTS__via__PRODUCT_ID"- :condition [:= product-id products-id]+ :condition [:=+ [:field %product-id {::add/source-table $$orders+ ::add/source-alias "PRODUCT_ID"}]+ [:field %products.id {:join-alias "PRODUCTS__via__PRODUCT_ID"+ ::add/source-table "PRODUCTS__via__PRODUCT_ID"+ ::add/source-alias "ID"}]]:strategy :left-join:fk-field-id %product-id}]:expressions {"pivot-grouping" [:abs 0]}:fields [product-idcreated-atpivot-grouping- products-category- products-id]})})))+ products-id+ products-category]})})))(-> (lib.tu.macros/mbql-query orders{:aggregation [[:aggregation-options [:count] {:name "count"}]]:breakout [&PRODUCTS__via__PRODUCT_ID.products.category@@ -683,52 +599,44 @@:alias "PRODUCTS__via__PRODUCT_ID":fk-field-id %product-id:condition [:= $product-id &PRODUCTS__via__PRODUCT_ID.products.id]}]})- qp.preprocess/preprocessadd/add-alias-infonest-expressions))))))))(deftest ^:parallel uniquify-aliases-test(driver/with-driver :h2- (mt/dataset test-data- (qp.store/with-metadata-provider meta/metadata-provider- (is (partial= (lib.tu.macros/$ids products- {:source-query {:source-table $$products- :expressions {"CATEGORY" [:concat- [:field %category {::add/source-table $$products- ::add/source-alias "CATEGORY"- ::add/desired-alias "CATEGORY"- ::add/position 0}]- "2"]}- :fields [[:field %category {::add/source-table $$products- ::add/source-alias "CATEGORY"- ::add/desired-alias "CATEGORY"- ::add/position 0}]- [:expression "CATEGORY" {::add/desired-alias "CATEGORY_2"- ::add/position 1}]]}- :breakout [[:field "CATEGORY_2" {:base-type :type/Text- ::add/source-table ::add/source- ::add/source-alias "CATEGORY_2"- ::add/desired-alias "CATEGORY"- ::add/position 0}]]- :aggregation [[:aggregation-options [:count] {:name "count"- ::add/desired-alias "count"- ::add/position 1}]]- :order-by [[:asc [:field "CATEGORY_2" {:base-type :type/Text- ::add/source-table ::add/source- ::add/source-alias "CATEGORY_2"- ::add/desired-alias "CATEGORY"- ::add/position 0}]]]- :limit 1})- (-> (lib.tu.macros/mbql-query products- {:expressions {"CATEGORY" [:concat $category "2"]}- :breakout [:expression "CATEGORY"]- :aggregation [[:count]]- :order-by [[:asc [:expression "CATEGORY"]]]- :limit 1})- qp.preprocess/preprocess- add/add-alias-info- :query- nest-query/nest-expressions)))))))+ (qp.store/with-metadata-provider meta/metadata-provider+ (is (=? (lib.tu.macros/$ids products+ {:source-query {:source-table $$products+ :expressions {"CATEGORY" [:concat+ [:field %category {::add/source-table $$products+ ::add/source-alias "CATEGORY"+ ::add/desired-alias "CATEGORY"}]+ "2"]}+ :fields [[:field %category {::add/source-table $$products+ ::add/source-alias "CATEGORY"+ ::add/desired-alias "CATEGORY"}]+ [:expression "CATEGORY" {::add/desired-alias "CATEGORY_2"}]]}+ :breakout [[:field "CATEGORY_2" {:base-type :type/Text+ ::add/source-table ::add/source+ ::add/source-alias "CATEGORY_2"+ ::add/desired-alias "CATEGORY_2"}]]+ :aggregation [[:aggregation-options [:count] {:name "count"+ ::add/desired-alias "count"}]]+ :order-by [[:asc [:field "CATEGORY_2" {:base-type :type/Text+ ::add/source-table ::add/source+ ::add/source-alias "CATEGORY_2"+ ::add/desired-alias "CATEGORY_2"}]]]+ :limit 1})+ (-> (lib.tu.macros/mbql-query products+ {:expressions {"CATEGORY" [:concat $category "2"]}+ :breakout [:expression "CATEGORY"]+ :aggregation [[:count]]+ :order-by [[:asc [:expression "CATEGORY"]]]+ :limit 1})+ qp.preprocess/preprocess+ add/add-alias-info+ :query+ nest-query/nest-expressions))))))(deftest ^:parallel uniquify-aliases-test-2(driver/with-driver :h2@@ -741,7 +649,7 @@;; Then exported as DISCOUNT from the middle layer.[:field "DISCOUNT_2" {:base-type :type/Float::add/source-alias "DISCOUNT_2"- ::add/desired-alias "DISCOUNT"}]]+ ::add/desired-alias "DISCOUNT_2"}]]:source-query {:expressions {"DISCOUNT" [:coalesce [:field %discount {}] 0]}:fields [[:field %id {::add/desired-alias "ID"}][:field %subtotal {::add/desired-alias "SUBTOTAL"}]@@ -876,38 +784,34 @@(meta/id :orders :user-id){::add/source-table (meta/id :orders)::add/source-alias "USER_ID"- ::add/desired-alias "USER_ID"- ::add/position 0}]+ ::add/desired-alias "USER_ID"}][:field(meta/id :orders :total){::add/source-table (meta/id :orders)::add/source-alias "TOTAL"- ::add/desired-alias "TOTAL"- ::add/position 1}]+ ::add/desired-alias "TOTAL"}][:expression"double_total"- {::add/desired-alias "double_total", ::add/position 2}]+ {::add/desired-alias "double_total"}];; 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 for refs in an;; arbitrary order, and returns `m/distinct-by` over that random order. Changing the map keys on the;; inner query can perturb this order; if you cause this test to fail based on shuffling the order of;; these joined fields, just edit the expectation to match the new order. Tech debt issue: #39396+ [:field+ (meta/id :people :id)+ {:join-alias "p"+ ::add/source-table "p"+ ::add/source-alias "ID"+ ::add/desired-alias "p__ID"}][:field(meta/id :people :created-at){:temporal-unit (symbol "nil #_\"key is not present.\"")::add/source-alias "CREATED_AT":join-alias "p"::add/desired-alias "p__CREATED_AT"- ::add/position 3- ::add/source-table "p"}]- [:field- (meta/id :people :id)- {:join-alias "p"- ::add/source-table "p"- ::add/source-alias "ID"- ::add/desired-alias "p__ID"- ::add/position 4}]]}}+ ::add/source-table "p"}]]}}(->> (lib.tu.macros/mbql-query orders{:expressions {"double_total" [:* $total 2]};; this is a broken field ref! It should use the join alias `p`. Luckilydiff --git a/test/metabase/query_processor_test/binning_test.clj b/test/metabase/query_processor_test/binning_test.cljindex ebc2077ea6a..be52f3d6acc 100644--- a/test/metabase/query_processor_test/binning_test.clj+++ b/test/metabase/query_processor_test/binning_test.clj@@ -39,7 +39,6 @@:data:results_metadata:columns)- _ (def %card-cols card-cols)_ (is (= 2(count card-cols)))mp (lib.tu/mock-metadata-provider@@ -74,3 +73,27 @@[125.0 13][137.5 6]](mt/formatted-rows [2.0 int] (qp/process-query query')))))))++(deftest ^:parallel multiple-bins-on-same-column-test+ (let [query (lib/query+ (mt/metadata-provider)+ {:database (mt/id)+ :type :query+ :query {:source-query {:source-table (mt/id :orders)+ :aggregation [[:count]]+ :breakout [[:field+ (mt/id :orders :total)+ {:base-type :type/Float, :binning {:strategy :num-bins, :num-bins 10}}]+ [:field+ (mt/id :orders :total)+ {:base-type :type/Float, :binning {:strategy :num-bins, :num-bins 50}}]]}+ :expressions {"Expression1" [:+ [:field "TOTAL" {:base-type :type/Float}] 100]+ "Expression2" [:+ [:field "TOTAL" {:base-type :type/Float}] 200]}+ :order-by [[:asc [:field "TOTAL" {:base-type :type/Float}]]+ [:asc [:field "TOTAL_2" {:base-type :type/Float}]]+ [:asc [:field "count" {:base-type :type/Integer}]]]+ :limit 3}})]+ (is (= [[-60.0 -50.0 1 40 140]+ [0.0 5.0 1 100 200]+ [0.0 10.0 5 100 200]]+ (mt/formatted-rows [1.0 1.0 int int int] (qp/process-query query))))))diff --git a/test/metabase/query_processor_test/date_bucketing_test.clj b/test/metabase/query_processor_test/date_bucketing_test.cljindex 10c23bfd4da..a59fe46575f 100644--- a/test/metabase/query_processor_test/date_bucketing_test.clj+++ b/test/metabase/query_processor_test/date_bucketing_test.clj@@ -1628,7 +1628,7 @@(mt/first-row(qp/process-query query))))))))))-(deftest temporal-unit-parameters-test+(deftest ^:parallel temporal-unit-parameters-test(mt/dataset test-data(let [query-months (mt/query orders{:type :query@@ -1649,23 +1649,23 @@(is (= [37019.52 32923.82 36592.60 35548.11 43556.61 39537.8242292.10 42443.71 42077.35 45708.74 44498.55 46245.48](unit-totals "month"))))-(testing "quarterly"(is (= [106535.94 118642.54 126813.16 136452.77](unit-totals "quarter"))))-(testing "annual"(is (= [488444.41] (unit-totals "year")))))))(deftest ^:parallel incompatible-temporal-unit-parameter-test(testing "Incompatible time unit parameter yields expected error"(is (thrown-with-msg?- clojure.lang.ExceptionInfo #"This chart can not be broken out by the selected unit of time: minute\."+ clojure.lang.ExceptionInfo+ #"\QThis chart can not be broken out by the selected unit of time: minute.\E"(qp.preprocess/preprocess- (mt/mbql-query- checkins- {:type :query- :query {:aggregation [[:count]]+ (mt/$ids checkins+ {:database (mt/id)+ :type :query+ :query {:source-table $$checkins+ :aggregation [[:count]]:breakout [!day.date]}:parameters [{:type :temporal-unit:target [:dimension !day.date]@@ -1709,7 +1709,7 @@(mt/formatted-rows[int int] (qp/process-query query)))))))))))-(deftest filter-by-current-quarter-test+(deftest ^:parallel filter-by-current-quarter-test(mt/test-drivers (mt/normal-drivers)(testing "Should be able to filter by current quarter (#20683)"(let [query (mt/mbql-query checkins@@ -1722,11 +1722,10 @@(mt/formatted-rows[int] (qp/process-query query)))))))))-(deftest filter-by-expression-time-interval-test+(deftest ^:parallel filter-by-expression-time-interval-test(testing "Datetime expressions can filter to a date range (#33528)"(mt/test-drivers (mt/normal-drivers-with-feature :test/dynamic-dataset-loading)- (mt/dataset- checkins:1-per-day+ (mt/dataset checkins:1-per-day(let [mp (lib.metadata.jvm/application-database-metadata-provider (mt/id))query (as-> (lib/query mp (lib.metadata/table mp (mt/id :checkins))) $q(lib/expression $q "customdate" (m/find-first (comp #{(mt/id :checkins :timestamp)} :id) (lib/visible-columns $q)))@@ -1744,7 +1743,7 @@(get-in (qp/process-query (lib.convert/->pMBQL mbql-query)) [:data :native_form])(get-in (qp/process-query query) [:data :native_form]))))))))-(deftest filter-by-expression-relative-time-interval-test+(deftest ^:parallel filter-by-expression-relative-time-interval-test(testing "Datetime expressions can filter to a date range"(mt/test-drivers(mt/normal-drivers-with-feature :date-arithmetics :test/dynamic-dataset-loading)diff --git a/test/metabase/query_processor_test/expressions_test.clj b/test/metabase/query_processor_test/expressions_test.cljindex 61b152113e5..c9a7e3d9682 100644--- a/test/metabase/query_processor_test/expressions_test.clj+++ b/test/metabase/query_processor_test/expressions_test.clj@@ -725,37 +725,37 @@(deftest ^:parallel joined-literal-expression-test(testing "joined literal expression"(mt/test-drivers (mt/normal-drivers-with-feature :expressions :expression-literals :left-join :nested-queries)- (is (= [[2 "Stout Burgers & Beers" 2 0.5 1 "Stout Burgers & Beers" "25°"]- [2 "Stout Burgers & Beers" 2 0.5 1 "Stout Burgers & Beers" "In-N-Out Burger"]- [2 "Stout Burgers & Beers" 2 0.5 1 "Stout Burgers & Beers" "The Apple Pan"]]- (mt/formatted-rows- [int str int 1.0 int str str]- (mt/run-mbql-query venues- {:fields [$id- $name- $price- [:expression "InversePrice"]- &JoinedCategories.*LiteralInt/Integer- &JoinedCategories.*LiteralString/Text- &JoinedCategories.venues.name]- :expressions {"InversePrice" [:/ &JoinedCategories.*LiteralInt/Integer $price]- "NameEquals" [:= &JoinedCategories.*LiteralString/Text $name]}- :filter [:expression "NameEquals"]- :joins [{:strategy :left-join- :condition [:= $category_id &JoinedCategories.venues.category_id]- :source-query {:source-table $$venues- :expressions {"LiteralInt" [:value 1 {:base_type :type/Integer}]- "LiteralString" [:value "Stout Burgers & Beers" {:base_type :type/Text}]}- :filter [:!= $name [:expression "LiteralString"]]- :fields [$category_id- $name- [:expression "LiteralInt"]- [:expression "LiteralString"]]- :order-by [[:asc $category_id]- [:asc $id]]}- :alias "JoinedCategories"}]- :order-by [[:asc &JoinedCategories.venues.name]]- :limit 3})))))))+ (let [query (mt/mbql-query venues+ {:fields [$id+ $name+ $price+ [:expression "InversePrice"]+ &JoinedCategories.*LiteralInt/Integer+ &JoinedCategories.*LiteralString/Text+ &JoinedCategories.venues.name]+ :expressions {"InversePrice" [:/ &JoinedCategories.*LiteralInt/Integer $price]+ "NameEquals" [:= &JoinedCategories.*LiteralString/Text $name]}+ :filter [:expression "NameEquals"]+ :joins [{:strategy :left-join+ :condition [:= $category_id &JoinedCategories.venues.category_id]+ :source-query {:source-table $$venues+ :expressions {"LiteralInt" [:value 1 {:base_type :type/Integer}]+ "LiteralString" [:value "Stout Burgers & Beers" {:base_type :type/Text}]}+ :filter [:!= $name [:expression "LiteralString"]]+ :fields [$category_id+ $name+ [:expression "LiteralInt"]+ [:expression "LiteralString"]]+ :order-by [[:asc $category_id]+ [:asc $id]]}+ :alias "JoinedCategories"}]+ :order-by [[:asc &JoinedCategories.venues.name]]+ :limit 3})]+ (mt/with-native-query-testing-context query+ (is (= [[2 "Stout Burgers & Beers" 2 0.5 1 "Stout Burgers & Beers" "25°"]+ [2 "Stout Burgers & Beers" 2 0.5 1 "Stout Burgers & Beers" "In-N-Out Burger"]+ [2 "Stout Burgers & Beers" 2 0.5 1 "Stout Burgers & Beers" "The Apple Pan"]]+ (mt/formatted-rows [int str int 1.0 int str str] (qp/process-query query)))))))))(deftest ^:parallel literal-expressions-inside-nested-and-filtered-aggregations-test(testing "nested aggregated and filtered literal expression"diff --git a/test/metabase/query_processor_test/field_ref_repro_test.clj b/test/metabase/query_processor_test/field_ref_repro_test.cljindex e70fba29332..40b764c8b24 100644--- a/test/metabase/query_processor_test/field_ref_repro_test.clj+++ b/test/metabase/query_processor_test/field_ref_repro_test.clj@@ -46,20 +46,25 @@(deftest ^:parallel long-column-name-in-card-test(testing "Should be able to handle long column names in saved questions (#35252)"- (let [mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries- [{:native {:query "SELECT ID AS \"ID\", CATEGORY as \"This is a very very long column title that makes my saved question break when I want to use it elsewhere\" FROM PRODUCTS"}- :database (mt/id)- :type :native}])- card-meta (lib.metadata/card mp 1)- base (lib/query mp card-meta)+ (let [mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries+ [{:native {:query "SELECT ID AS \"ID\", CATEGORY as \"This is a very very long column title that makes my saved question break when I want to use it elsewhere\" FROM PRODUCTS ORDER BY ID ASC"}+ :database (mt/id)+ :type :native}])+ card-meta (lib.metadata/card mp 1)+ base (lib/query mp card-meta)long-name-col (second (lib/filterable-columns base))- query (lib/filter base (lib/contains long-name-col "a"))]- (mt/with-native-query-testing-context- query- ;; should return 53 rows with two columns, but fails instead- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Column \".*very very long column title.*\" not found"- (mt/rows+column-names- (qp/process-query query))))))))+ query (-> base+ (lib/filter (lib/contains long-name-col "a"))+ (lib/limit 3))]+ (mt/with-native-query-testing-context query+ ;; should return 53 rows with two columns, but fails instead+ (is (= {:rows [[5 "Gadget"]+ [11 "Gadget"]+ [16 "Gadget"]]+ :columns ["ID"+ "This is a very very long column title that makes my saved question break when I want to use it elsewhere"]}+ (mt/rows+column-names+ (qp/process-query query))))))));; other than producing the metadata for the card, there is no query processing here(deftest ^:parallel duplicate-names-selection-test@@ -527,7 +532,9 @@:source-field (mt/id :orders :user_id):source-field-name "USER_ID"}]{:stage-number -1}]}]))]- ;; should return 613 rows+ ;; should return 613 rows(mt/with-native-query-testing-context query- (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Column .*STATE.* not found"- (-> query qp/process-query mt/rows count))))))))+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Column .* not found"+ (-> query qp/process-query mt/rows count))))))))diff --git a/test/metabase/query_processor_test/native_test.clj b/test/metabase/query_processor_test/native_test.cljindex 4e8ed75d362..7d5157793e4 100644--- a/test/metabase/query_processor_test/native_test.clj+++ b/test/metabase/query_processor_test/native_test.clj@@ -2,7 +2,9 @@(:require[clojure.test :refer :all][metabase.driver.sql.query-processor-test-util :as sql.qp-test-util]+ [metabase.lib.test-util :as lib.tu][metabase.query-processor :as qp]+ [metabase.query-processor.store :as qp.store][metabase.query-processor.test-util :as qp.test-util][metabase.test :as mt][metabase.util :as u]))@@ -38,46 +40,53 @@(deftest ^:parallel native-with-duplicate-column-names(testing "Should be able to run native query referring a question referring a question (#25988)"(mt/with-test-drivers (sql.qp-test-util/sql-drivers)- (mt/with-temp [:model/Card card {:dataset_query {:native {:query "select id, id from orders"}- :database (mt/id)- :type :native}- :result_metadata [{:base_type :type/BigInteger,- :display_name "ID",- :effective_type :type/BigInteger,- :field_ref [:field "ID" {:base-type :type/BigInteger}],- :fingerprint nil,- :name "ID",- :semantic_type :type/PK}- {:base_type :type/BigInteger,- :display_name "ID",- :effective_type :type/BigInteger,- :field_ref [:field "ID_2" {:base-type :type/BigInteger}],- :fingerprint nil,- :name "ID",- :semantic_type :type/PK}]}]+ (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider+ (mt/metadata-provider)+ {:cards [{:id 1+ :dataset-query {:native {:query "select id, id from orders"}+ :database (mt/id)+ :type :native}+ :result-metadata [{:base_type :type/BigInteger+ :display_name "ID"+ :effective_type :type/BigInteger+ :field_ref [:field "ID" {:base-type :type/BigInteger}]+ :fingerprint nil+ :name "ID"+ :semantic_type :type/PK}+ {:base_type :type/BigInteger+ :display_name "ID"+ :effective_type :type/BigInteger+ :field_ref [:field "ID_2" {:base-type :type/BigInteger}]+ :fingerprint nil+ :name "ID"+ :semantic_type :type/PK}]}]})(is (=? {:columns ["ID" "ID_2"]}(mt/rows+column-names(qp/process-query- {:query {:source-table (str "card__" (:id card))- :fields [[:field "ID" {:base-type :type/Integer}] [:field "ID_2" {:base-type :type/Integer}]]}+ {:query {:source-table "card__1"+ :fields [[:field "ID" {:base-type :type/Integer}]+ [:field "ID_2" {:base-type :type/Integer}]]}:database (mt/id)- :type :query}))))))))+ :type :query}))))))))(deftest ^:parallel native-referring-question-referring-question-test(testing "Should be able to run native query referring a question referring a question (#25988)"(mt/with-driver :h2- (mt/dataset test-data- (mt/with-temp [:model/Card card1 {:dataset_query (mt/mbql-query products)}- :model/Card card2 {:dataset_query {:query {:source-table (str "card__" (u/the-id card1))}- :database (u/the-id (mt/db))- :type :query}}]- (let [card-tag (str "#" (u/the-id card2))- query {:query (format "SELECT CATEGORY, VENDOR FROM {{%s}} ORDER BY ID LIMIT 1" card-tag)- :template-tags {card-tag- {:id "afd1bf85-61d0-258c-99a7-a5b448728308"- :name card-tag- :display-name card-tag- :type :card- :card-id (u/the-id card2)}}}]- (is (= [["Gizmo" "Swaniawski, Casper and Hilll"]]- (mt/rows (qp/process-query (mt/native-query query)))))))))))+ (qp.store/with-metadata-provider (lib.tu/mock-metadata-provider+ (mt/metadata-provider)+ {:cards [{:id 1+ :dataset-query (mt/mbql-query products)}+ {:id 2+ :dataset-query {:query {:source-table "card__1"}+ :database (u/the-id (mt/db))+ :type :query}}]})+ (let [card-tag "#2"+ query {:query (format "SELECT CATEGORY, VENDOR FROM {{%s}} ORDER BY ID LIMIT 1" card-tag)+ :template-tags {card-tag+ {:id "afd1bf85-61d0-258c-99a7-a5b448728308"+ :name card-tag+ :display-name card-tag+ :type :card+ :card-id 2}}}]+ (is (= [["Gizmo" "Swaniawski, Casper and Hilll"]]+ (mt/rows (qp/process-query (mt/native-query query))))))))))diff --git a/test/metabase/query_processor_test/nested_array_test.clj b/test/metabase/query_processor_test/nested_array_test.cljnew file mode 100644index 00000000000..2855bb549ee--- /dev/null+++ b/test/metabase/query_processor_test/nested_array_test.clj@@ -0,0 +1,65 @@+(ns ^:mb/driver-tests metabase.query-processor-test.nested-array-test+ (:require+ [clojure.test :refer :all]+ [metabase.driver :as driver]+ [metabase.test :as mt]+ [metabase.test.data.interface :as tx]))++(defmulti native-nested-array-query+ {:arglists '([driver])}+ tx/dispatch-on-driver-with-test-extensions+ :hierarchy #'driver/hierarchy)++(defmethod native-nested-array-query :default+ [_driver]+ "select array[array[array['a', 'b'], array['c', 'd'] ], array[array['w', 'x'], array['y', 'z'] ]];")++(doseq [driver [:mysql :sqlite]]+ (defmethod native-nested-array-query driver+ [_driver]+ "select json_array(json_array(json_array('a', 'b'), json_array('c', 'd')), json_array(json_array('w', 'x'), json_array('y', 'z')));"))++(doseq [driver [:redshift :databricks]]+ (defmethod native-nested-array-query driver+ [_driver]+ "select array(array(array('a', 'b'), array('c', 'd')), array(array('w', 'x'), array('y', 'z')));"))++(defmethod native-nested-array-query :snowflake+ [_driver]+ "select array_construct(array_construct(array_construct('a', 'b'), array_construct('c', 'd')), array_construct(array_construct('w', 'x'), array_construct('y', 'z')));")++(defmulti native-nested-array-results+ {:arglists '([driver])}+ tx/dispatch-on-driver-with-test-extensions+ :hierarchy #'driver/hierarchy)++(defmethod native-nested-array-results :default+ [_driver]+ [[["a" "b"] ["c" "d"]] [["w" "x"] ["y" "z"]]])++(doseq [driver [:sqlite :databricks :redshift]]+ (defmethod native-nested-array-results driver+ [_driver]+ "[[[\"a\",\"b\"],[\"c\",\"d\"]],[[\"w\",\"x\"],[\"y\",\"z\"]]]"))++(defmethod native-nested-array-results :mysql+ [_driver]+ "[[[\"a\", \"b\"], [\"c\", \"d\"]], [[\"w\", \"x\"], [\"y\", \"z\"]]]")++(defmethod native-nested-array-results :snowflake+ [_driver]+ "[\n [\n [\n \"a\",\n \"b\"\n ],\n [\n \"c\",\n \"d\"\n ]\n ],\n [\n [\n \"w\",\n \"x\"\n ],\n [\n \"y\",\n \"z\"\n ]\n ]\n]")++(doseq [driver [:postgres :vertica :mysql :sqlite :redshift :databricks :snowflake]]+ (defmethod driver/database-supports? [driver :test/nested-arrays]+ [_driver _feature _database]+ true))++(deftest ^:parallel nested-array-query-test+ (testing "A nested array query should be returned in a readable format"+ (mt/test-drivers (mt/normal-driver-select {:+features [:test/nested-arrays]})+ (mt/dataset test-data+ (is (= [[(native-nested-array-results driver/*driver*)]]+ (->> (mt/native-query {:query (native-nested-array-query driver/*driver*)})+ mt/process-query+ mt/rows)))))))diff --git a/test/metabase/query_processor_test/nested_field_test.clj b/test/metabase/query_processor_test/nested_field_test.cljindex 88bb3aa8a7b..6aaa438d929 100644--- a/test/metabase/query_processor_test/nested_field_test.clj+++ b/test/metabase/query_processor_test/nested_field_test.clj@@ -2,6 +2,7 @@"Tests for nested field access."(:require[clojure.test :refer :all]+ [metabase.query-processor :as qp][metabase.test :as mt]))(deftest ^:parallel filter-test@@ -9,22 +10,22 @@(testing "Nested Field in FILTER"(mt/dataset geographical-tips;; Get the first 10 tips where tip.venue.name == "Kyle's Low-Carb Grill"- (is (= [[8 "Kyle's Low-Carb Grill"]- [67 "Kyle's Low-Carb Grill"]- [80 "Kyle's Low-Carb Grill"]- [83 "Kyle's Low-Carb Grill"]- [295 "Kyle's Low-Carb Grill"]- [342 "Kyle's Low-Carb Grill"]- [417 "Kyle's Low-Carb Grill"]- [426 "Kyle's Low-Carb Grill"]- [470 "Kyle's Low-Carb Grill"]]- (mt/formatted-rows- [int str]- (mt/run-mbql-query tips- {:fields [$tips.id $tips.venue.name]- :filter [:= $tips.venue.name "Kyle's Low-Carb Grill"]- :order-by [[:asc $id]]- :limit 10}))))))))+ (let [query (mt/mbql-query tips+ {:fields [$tips.id $tips.venue.name]+ :filter [:= $tips.venue.name "Kyle's Low-Carb Grill"]+ :order-by [[:asc $id]]+ :limit 10})]+ (mt/with-native-query-testing-context query+ (is (= [[8 "Kyle's Low-Carb Grill"]+ [67 "Kyle's Low-Carb Grill"]+ [80 "Kyle's Low-Carb Grill"]+ [83 "Kyle's Low-Carb Grill"]+ [295 "Kyle's Low-Carb Grill"]+ [342 "Kyle's Low-Carb Grill"]+ [417 "Kyle's Low-Carb Grill"]+ [426 "Kyle's Low-Carb Grill"]+ [470 "Kyle's Low-Carb Grill"]]+ (mt/formatted-rows [int str] (qp/process-query query))))))))))(deftest ^:parallel order-by-test(mt/test-drivers (mt/normal-drivers-with-feature :nested-fields)@@ -90,17 +91,21 @@(testing "Nested Field in BREAKOUT";; Let's see how many tips we have by source.service(mt/dataset geographical-tips- (is (= [["facebook" 107]- ["flare" 105]- ["foursquare" 100]- ["twitter" 98]- ["yelp" 90]]- (mt/formatted-rows- [str int]- (mt/run-mbql-query tips- {:aggregation [[:count]]- :breakout [$tips.source.service]}))))+ (let [query (mt/mbql-query tips+ {:aggregation [[:count]]+ :breakout [$tips.source.service]})]+ (mt/with-native-query-testing-context query+ (is (= [["facebook" 107]+ ["flare" 105]+ ["foursquare" 100]+ ["twitter" 98]+ ["yelp" 90]]+ (mt/formatted-rows [str int] (qp/process-query query))))))))))+(deftest ^:parallel breakout-test-2+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-fields)+ (testing "Nested Field in BREAKOUT"+ (mt/dataset geographical-tips(is (= [[nil 297]["amy" 20]["biggie" 11]diff --git a/test/metabase/query_processor_test/nested_queries_test.clj b/test/metabase/query_processor_test/nested_queries_test.cljindex 8843e565b57..a8fdb327e61 100644--- a/test/metabase/query_processor_test/nested_queries_test.clj+++ b/test/metabase/query_processor_test/nested_queries_test.clj@@ -350,19 +350,17 @@(catch Exception _ nil)))(deftest card-id-native-source-query-with-long-alias-test- (testing "nested card with native query and long column alias (metabase##47584)"+ (testing "nested card with native query and long column alias (#47584)"(mt/test-drivers (set/intersection (mt/normal-drivers-with-feature :nested-queries)(descendants driver/hierarchy :sql))(let [coun-col-name "coun"long-col-full-name "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count"-;; Truncate the long column to something the driver can actually execute.long-col-name (subs long-col-full-name0(if-let [col-max (col-max-for-driver driver/*driver*)](min col-max (count long-col-full-name))(count long-col-full-name)))-;; Disable truncate-alias when compiling the native query to ensure we don't further truncate the column.;; We want to simulate a user-defined query where the column name is long, but valid for the driver.native-sub-query (with-redefs [lib.util/truncate-alias@@ -376,7 +374,6 @@:limit 5})qp.compile/compile:query))-query (query-with-source-card 1)](qp.store/with-metadata-provider (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries[(mt/native-query {:query native-sub-query})])@@ -1565,7 +1562,8 @@:condition [:= *products.id &Reviews.reviews.product_id]:alias "Reviews"}]:order-by [[:asc $product_id->products.id]- [:asc &Reviews.products.id]]+ [:asc &Reviews.reviews.product_id]+ [:asc &Reviews.reviews.id]]:limit 1})](sql.qp-test-util/with-native-query-testing-context query(testing "results"diff --git a/test/metabase/query_processor_test/remapping_test.clj b/test/metabase/query_processor_test/remapping_test.cljindex f1e91b58898..de62422dba5 100644--- a/test/metabase/query_processor_test/remapping_test.clj+++ b/test/metabase/query_processor_test/remapping_test.clj@@ -378,8 +378,7 @@:joins [{:source-table $$products:alias "Products":condition [:= $product_id &Products.products.id]- :fields [$id- &Products.products.title]}]+ :fields [&Products.products.title]}]:order-by [[:asc $id]]:limit 3})(mt/mbql-query nil {:source-table "card__1"})diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.cljindex cca3fc2e8c2..b8f47574399 100644--- a/test/metabase/search/api_test.clj+++ b/test/metabase/search/api_test.clj@@ -100,7 +100,7 @@(defn- query-action[action-id]{:action_id action-id- :database_id (u/the-id (mt/db))+ :database_id (mt/id):dataset_query (mt/query venues)})(def ^:private test-collection (make-result "collection test collection"diff --git a/test/metabase/sync/analyze/fingerprint_test.clj b/test/metabase/sync/analyze/fingerprint_test.cljindex 5fed2661357..145b7163faf 100644--- a/test/metabase/sync/analyze/fingerprint_test.clj+++ b/test/metabase/sync/analyze/fingerprint_test.clj@@ -334,7 +334,7 @@(:count (t2/query-one {:select [[:%count.* :count]]:from :metabase_field:join [[:metabase_table :table] [:= :table.id :table_id]]- :where [:= :table.db_id (:id (mt/db))]+ :where [:= :table.db_id (mt/id)]:group-by [:table_id]:order-by [[:count :desc]]:limit 1}))))))))))diff --git a/test/metabase/sync/api/notify_test.clj b/test/metabase/sync/api/notify_test.cljindex c9af60fb998..c661b0580a0 100644--- a/test/metabase/sync/api/notify_test.clj+++ b/test/metabase/sync/api/notify_test.clj@@ -13,7 +13,6 @@[metabase.test.data.interface :as tx][metabase.test.fixtures :as fixtures][metabase.test.http-client :as client]- [metabase.util :as u][metabase.warehouses.models.database :as database][toucan2.core :as t2]))@@ -46,7 +45,7 @@(testing "table ID must exist or we get a 404"(is (= {:status 404:body "Not found."}- (try (http/post (client/build-url (format "notify/db/%d" (:id (mt/db))) {})+ (try (http/post (client/build-url (format "notify/db/%d" (mt/id)) {})(merge {:accept :json:content-type :json:form-params {:table_id Integer/MAX_VALUE}}@@ -56,7 +55,7 @@(testing "table name must exist or we get a 404"(is (= {:status 404:body "Not found."}- (try (http/post (client/build-url (format "notify/db/%d" (:id (mt/db))) {})+ (try (http/post (client/build-url (format "notify/db/%d" (mt/id)) {})(merge {:accept :json:content-type :json:form-params {:table_name "IncorrectToucanFact"}}@@ -71,7 +70,7 @@([payload] (post-api payload 200))([payload expected-code](mt/with-temporary-setting-values [api-key "test-api-key"]- (mt/client :post expected-code (format "notify/db/%d" (u/the-id (mt/db)))+ (mt/client :post expected-code (format "notify/db/%d" (mt/id)){:request-options api-headers}(merge {:synchronous? true}payload)))))]diff --git a/test/metabase/sync/sync_metadata/comments_test.clj b/test/metabase/sync/sync_metadata/comments_test.cljindex a7adc8f290f..e658553f9d5 100644--- a/test/metabase/sync/sync_metadata/comments_test.clj+++ b/test/metabase/sync/sync_metadata/comments_test.clj@@ -125,4 +125,4 @@(tx/map->TableDefinition {:table-name table-name:table-comment added-comment}))])(sync-tables/sync-tables-and-database! (mt/db))- (is (true? (t2/exists? :model/Table :db_id (u/the-id (mt/db)) :description added-comment))))))))+ (is (true? (t2/exists? :model/Table :db_id (mt/id) :description added-comment))))))))diff --git a/test/metabase/sync/sync_metadata/fields_test.clj b/test/metabase/sync/sync_metadata/fields_test.cljindex 33b1842120a..6ed8014389e 100644--- a/test/metabase/sync/sync_metadata/fields_test.clj+++ b/test/metabase/sync/sync_metadata/fields_test.clj@@ -116,7 +116,7 @@"(3, 'Colin Fowl');")]](jdbc/execute! one-off-dbs/*conn* [statement]))(sync/sync-database! (mt/db))- (let [tables (t2/select-pks-set :model/Table :db_id (u/the-id (mt/db)))+ (let [tables (t2/select-pks-set :model/Table :db_id (mt/id))get-field-to-update (fn [](t2/select-one:model/Fielddiff --git a/test/metabase/sync/sync_metadata/indexes_test.clj b/test/metabase/sync/sync_metadata/indexes_test.cljindex 33adff55856..68863526f7d 100644--- a/test/metabase/sync/sync_metadata/indexes_test.clj+++ b/test/metabase/sync/sync_metadata/indexes_test.clj@@ -60,7 +60,7 @@many-indexes (into indexes (repeat 100000 {:table-schema "public",:table-name "fake_table",:field-name "id"}))- field-ids (#'sync.indexes/all-indexes->field-ids (:id (mt/db)) many-indexes)]+ field-ids (#'sync.indexes/all-indexes->field-ids (mt/id) many-indexes)](is (seq field-ids))))))(deftest sync-all-indexes!-testdiff --git a/test/metabase/sync/util_test.clj b/test/metabase/sync/util_test.cljindex 660746cd477..33fb5408492 100644--- a/test/metabase/sync/util_test.clj+++ b/test/metabase/sync/util_test.clj@@ -287,29 +287,29 @@(deftest initial-sync-status-test(mt/dataset test-data(testing "If `initial-sync-status` on a DB is `incomplete`, it is marked as `complete` when sync-metadata has finished"- (let [_ (t2/update! :model/Database (:id (mt/db)) {:initial_sync_status "incomplete"})- db (t2/select-one :model/Database :id (:id (mt/db)))]+ (let [_ (t2/update! :model/Database (mt/id) {:initial_sync_status "incomplete"})+ db (t2/select-one :model/Database :id (mt/id))](sync/sync-database! db)(is (= "complete" (t2/select-one-fn :initial_sync_status :model/Database :id (:id db))))))(testing "If `initial-sync-status` on a DB is `complete`, it remains `complete` when sync is run again"- (let [_ (t2/update! :model/Database (:id (mt/db)) {:initial_sync_status "complete"})- db (t2/select-one :model/Database :id (:id (mt/db)))]+ (let [_ (t2/update! :model/Database (mt/id) {:initial_sync_status "complete"})+ db (t2/select-one :model/Database :id (mt/id))](sync/sync-database! db)(is (= "complete" (t2/select-one-fn :initial_sync_status :model/Database :id (:id db))))))(testing "If `initial-sync-status` on a table is `incomplete`, it is marked as `complete` after the sync-fks stephas finished"- (let [table-id (t2/select-one-fn :id :model/Table :db_id (:id (mt/db)))+ (let [table-id (t2/select-one-fn :id :model/Table :db_id (mt/id))_ (t2/update! :model/Table table-id {:initial_sync_status "incomplete"})_table (t2/select-one :model/Table :id table-id)](sync/sync-database! (mt/db))(is (= "complete" (t2/select-one-fn :initial_sync_status :model/Table :id table-id)))))(testing "Database and table syncs are marked as complete even if the initial scan is :schema only"- (let [_ (t2/update! :model/Database (:id (mt/db)) {:initial_sync_status "incomplete"})- db (t2/select-one :model/Database :id (:id (mt/db)))- table-id (t2/select-one-fn :id :model/Table :db_id (:id (mt/db)))+ (let [_ (t2/update! :model/Database (mt/id) {:initial_sync_status "incomplete"})+ db (t2/select-one :model/Database :id (mt/id))+ table-id (t2/select-one-fn :id :model/Table :db_id (mt/id))_ (t2/update! :model/Table table-id {:initial_sync_status "incomplete"})_table (t2/select-one :model/Table :id table-id)](sync/sync-database! db {:scan :schema})@@ -317,8 +317,8 @@(is (= "complete" (t2/select-one-fn :initial_sync_status :model/Table :id table-id)))))(testing "If a non-recoverable error occurs during sync, `initial-sync-status` on the database is set to `aborted`"- (let [_ (t2/update! :model/Database (:id (mt/db)) {:initial_sync_status "incomplete"})- db (t2/select-one :model/Database :id (:id (mt/db)))]+ (let [_ (t2/update! :model/Database (mt/id) {:initial_sync_status "incomplete"})+ db (t2/select-one :model/Database :id (mt/id))](with-redefs [sync-metadata/make-sync-steps (fn [_][(sync-util/create-sync-step"fake-step"@@ -328,8 +328,8 @@(testing "If `initial-sync-status` is `aborted` for a database, it is set to `complete` the next time sync finisheswithout error"- (let [_ (t2/update! :model/Database (:id (mt/db)) {:initial_sync_status "complete"})- db (t2/select-one :model/Database :id (:id (mt/db)))]+ (let [_ (t2/update! :model/Database (mt/id) {:initial_sync_status "complete"})+ db (t2/select-one :model/Database :id (mt/id))](sync/sync-database! db)(is (= "complete" (t2/select-one-fn :initial_sync_status :model/Database :id (:id db))))))))diff --git a/test/metabase/test/generate.clj b/test/metabase/test/generate.cljindex 41b495daa92..8aeae265d41 100644--- a/test/metabase/test/generate.clj+++ b/test/metabase/test/generate.clj@@ -120,7 +120,7 @@(s/def ::content ::not-empty-string)(s/def :parameter/id ::not-empty-string)-(s/def :parameter/type ::base_type)+(s/def :parameter/type #{:text})(s/def ::parameter (s/keys :req-un [:parameter/id :parameter/type]))(s/def ::parameters (s/coll-of ::parameter))diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.cljindex 0ff02e2bdc9..44a5bc0bc84 100644--- a/test/metabase/test/util.clj+++ b/test/metabase/test/util.clj@@ -1067,11 +1067,11 @@is granted the permission specified by `permission-path`.For most use cases see the macro [[with-all-users-permission]]."- [permission-path f]+ [permission-path thunk]#_{:clj-kondo/ignore [:discouraged-var]}(t2.with-temp/with-temp [:model/Permissions _ {:group_id (:id (perms/all-users-group)):object permission-path}]- (f)))+ (thunk)))(defn do-with-all-user-data-perms-graph!"Implementation for [[with-all-users-data-perms]]"