Skip to content

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

Add backend test parity for MBQL lib / QP behaviors covered only by e2e tests (#77062)

Alexander Polyankinc109d4fbc6e0
diff --git a/.github/workflows/cross-branch-migrations.yml b/.github/workflows/cross-branch-migrations.yml
index 72e4a506eef..3641881439a 100644
--- a/.github/workflows/cross-branch-migrations.yml
+++ b/.github/workflows/cross-branch-migrations.yml
@@ -26,7 +26,7 @@ concurrency:
jobs:
migrations-h2-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
- timeout-minutes: 10
+ timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: h2
@@ -40,7 +40,7 @@ jobs:
migrations-postgres-14-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
- timeout-minutes: 10
+ timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: postgres
@@ -66,7 +66,7 @@ jobs:
migrations-postgres-latest-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
- timeout-minutes: 10
+ timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: postgres
@@ -92,7 +92,7 @@ jobs:
migrations-mysql-8-0-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
- timeout-minutes: 10
+ timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql
@@ -117,7 +117,7 @@ jobs:
migrations-mysql-latest-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
- timeout-minutes: 10
+ timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql
@@ -143,7 +143,7 @@ jobs:
migrations-mariadb-10-6-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
- timeout-minutes: 10
+ timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql
@@ -168,7 +168,7 @@ jobs:
migrations-mariadb-latest-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
- timeout-minutes: 10
+ timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql
diff --git a/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj b/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj
index ca549ea82b8..cec14d0622a 100644
--- a/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/action_v2/api_test.clj
@@ -493,6 +493,32 @@
(check-coercion-fn-coverage @#'coerce/unimplemented-coercion-functions)
(run! #(apply do-test %)))))))
+(deftest native-temporal-columns-output-roundtrip-test
+ (testing "execute-bulk echoes native date/timestamp columns in the same format the QP returns"
+ (mt/with-premium-features #{actions-feature-flag}
+ (mt/test-drivers (mt/normal-drivers-with-feature :actions/data-editing)
+ (action-v2.tu/with-test-tables! [table-id [{:id 'auto-inc-type
+ :d [:date]
+ :dt [:timestamp]}
+ {:primary-key [:id]}]]
+ (let [qp-state (fn [] (map #(zipmap [:id :d :dt] %) (table-rows table-id)))]
+ (testing "create returns the same coerced output that the QP would return"
+ (let [{:keys [outputs]} (action-v2.tu/create-rows! table-id [{:d "2020-02-15" :dt "2020-02-15T11:35:00"}])]
+ (is (= 1 (count outputs)))
+ (is (= (qp-state) (map :row outputs)))
+ (is (=? {:d #(re-find #"2020-02-15" (str %))
+ :dt #(re-find #"2020-02-15T11:35:00" (str %))}
+ (first (qp-state))))))
+ (testing "update returns the same coerced output that the QP would return"
+ (let [[{id :id}] (map :row (:outputs (action-v2.tu/create-rows! table-id [{:d nil :dt nil}])))
+ _ (is (some? id))
+ {:keys [outputs]} (action-v2.tu/update-rows! table-id [{:id id :d "2021-06-20" :dt "2021-06-20T08:15:00"}])
+ updated-qp-row (first (filter (comp #{id} :id) (qp-state)))]
+ (is (= [updated-qp-row] (map :row outputs)))
+ (is (=? {:d #(re-find #"2021-06-20" (str %))
+ :dt #(re-find #"2021-06-20T08:15:00" (str %))}
+ updated-qp-row))))))))))
+
(deftest field-values-invalidated-test
(mt/with-premium-features #{actions-feature-flag}
(mt/test-drivers (mt/normal-drivers-with-feature :actions/data-editing)
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
index 9163fc1180f..dcf459b3ff3 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
@@ -307,3 +307,15 @@
(set-interval! :crowberto 204)
(set-interval! user 204)
(set-interval! :rasta 403))))))))
+
+(deftest generic-setting-write-test
+ (testing "PUT /api/setting/:key -- granting the :setting application permission lets a non-admin write a settings-manager-visible setting"
+ (mt/with-user-in-groups
+ [group {:name "New Group"}
+ user [group]]
+ (mt/with-premium-features #{:advanced-permissions}
+ (mt/with-temporary-setting-values [site-name "Metabase"]
+ (mt/user-http-request user :put 403 "setting/site-name" {:value "Nope"})
+ (perms/grant-application-permissions! group :setting)
+ (mt/user-http-request user :put 204 "setting/site-name" {:value "NewName"})
+ (is (= "NewName" (mt/user-http-request :crowberto :get 200 "setting/site-name"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/audit_app/api/database_test.clj b/enterprise/backend/test/metabase_enterprise/audit_app/api/database_test.clj
index 8b36d0d0c92..bc29494147d 100644
--- a/enterprise/backend/test/metabase_enterprise/audit_app/api/database_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/audit_app/api/database_test.clj
@@ -3,7 +3,10 @@
[clojure.test :refer :all]
[metabase-enterprise.audit-app.audit-test :as audit-test]
[metabase.audit-app.core :as audit]
- [metabase.test :as mt]))
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :db :plugins))
(deftest audit-db-unmodifiable-test
(mt/with-premium-features #{:audit-app}
@@ -16,3 +19,13 @@
user [:crowberto :lucky]]
(is (= "You don't have permissions to do that."
(mt/user-http-request user verb 403 (format path audit/audit-db-id)))))))))
+
+(deftest audit-db-excluded-from-database-list-test
+ (mt/with-premium-features #{:audit-app}
+ (audit-test/with-audit-db-restoration!
+ (testing "GET /api/database excludes the audit DB by default"
+ (is (not (contains? (set (map :id (:data (mt/user-http-request :crowberto :get 200 "database"))))
+ audit/audit-db-id))))
+ (testing "GET /api/database?include_analytics=true includes the audit DB"
+ (is (contains? (set (map :id (:data (mt/user-http-request :crowberto :get 200 "database" :include_analytics true))))
+ audit/audit-db-id))))))
diff --git a/enterprise/backend/test/metabase_enterprise/audit_app/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/audit_app/permissions_test.clj
index 8b8fef24e90..4df92716def 100644
--- a/enterprise/backend/test/metabase_enterprise/audit_app/permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/audit_app/permissions_test.clj
@@ -8,6 +8,9 @@
[metabase.api.common :as api]
[metabase.audit-app.core :as audit]
[metabase.core.core :as mbc]
+ [metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.models.interface :as mi]
[metabase.permissions.models.collection.graph :refer [update-graph!]]
[metabase.permissions.models.collection.graph-test :refer [graph]]
@@ -178,3 +181,28 @@
(let [dashboard (t2/select-one :model/Dashboard :collection_id (:id (audit/default-audit-collection)))]
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "dashboard/" (u/the-id dashboard)) {:name "My new title"})))))
+
+(deftest audit-db-adhoc-query-and-collection-write-perms-test
+ (audit-test/with-audit-db-restoration!
+ (mt/with-premium-features #{:audit-app}
+ (testing "An ad-hoc aggregation query on top of a saved audit model runs successfully (#43088)"
+ (mt/with-test-user :crowberto
+ (let [audit-card (t2/select-one :model/Card :database_id audit/audit-db-id :type :model :name "People")]
+ (is (some? audit-card)
+ "Expected the audit DB's 'People' model card to exist after installation")
+ (let [mp (lib.metadata.jvm/application-database-metadata-provider audit/audit-db-id)
+ query (-> (lib/query mp (lib.metadata/card mp (u/the-id audit-card)))
+ (lib/aggregate (lib/count)))]
+ (is (partial= {:status :completed}
+ (qp/process-query query)))))))
+ (testing "the analytics collection is read-only via the API"
+ (let [audit-coll-id (:id (audit/default-audit-collection))
+ items (:data (mt/user-http-request :crowberto :get 200 "collection/root/items"))
+ analytics (first (filter #(and (= (:model %) "collection") (= (:id %) audit-coll-id)) items))]
+ (is (some? analytics)
+ "the analytics collection is listed under the root collection")
+ (is (false? (:can_write analytics)))))
+ (testing "GET /api/permissions/graph does not include the audit DB"
+ (let [resp (mt/user-http-request :crowberto :get 200 "permissions/graph")]
+ (is (every? #(not (contains? % audit/audit-db-id))
+ (vals (:groups resp)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/cache/cache_test.clj b/enterprise/backend/test/metabase_enterprise/cache/cache_test.clj
index c9f552b93f9..3515d99570d 100644
--- a/enterprise/backend/test/metabase_enterprise/cache/cache_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/cache/cache_test.clj
@@ -109,6 +109,29 @@
:strategy {:type "schedule"
:schedule "0/2 * * * * ?"}}))))))))
+(deftest preemptive-refresh-automatically-roundtrip-test
+ (testing "PUT /api/cache serializes refresh_automatically to its own column and GET re-nests it"
+ (mt/with-model-cleanup [:model/CacheConfig]
+ (mt/with-premium-features #{:cache-granular-controls :cache-preemptive}
+ (mt/with-temp [:model/Database db {}
+ :model/Card card {:name "card"
+ :database_id (:id db)
+ :dataset_query (lib/native-query (lib-be/application-database-metadata-provider (:id db)) "SELECT 1;")}]
+ (is (mt/user-http-request :crowberto :put 200 "cache/"
+ {:model "question"
+ :model_id (:id card)
+ :strategy {:type "duration" :duration 24 :unit "hours" :refresh_automatically true}}))
+ (testing "flag is persisted to the top-level CacheConfig column"
+ (is (true? (t2/select-one-fn :refresh_automatically :model/CacheConfig
+ :model "question" :model_id (:id card)))))
+ (testing "GET re-nests the flag under strategy"
+ (is (=? {:data [{:model "question"
+ :model_id (:id card)
+ :strategy {:type "duration"
+ :refresh_automatically true}}]}
+ (mt/user-http-request :crowberto :get 200 "cache/"
+ :model "question" :id (:id card))))))))))
+
(deftest cache-config-permissions-test
(mt/with-model-cleanup [:model/CacheConfig]
(mt/with-premium-features #{:cache-granular-controls :audit-app}
diff --git a/enterprise/backend/test/metabase_enterprise/content_translation/dictionary_test.clj b/enterprise/backend/test/metabase_enterprise/content_translation/dictionary_test.clj
index 9b56e899a1a..6d29a288265 100644
--- a/enterprise/backend/test/metabase_enterprise/content_translation/dictionary_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/content_translation/dictionary_test.clj
@@ -314,6 +314,21 @@
(is (not (some #(= (:msgstr %) " ") translations)))
(is (not (some #(= (:msgstr %) ",,,") translations)))))))))
+(deftest import-translations-failure-leaves-existing-untouched-test
+ (ct-utils/with-clean-translations!
+ (testing "A failed import leaves previously stored translations intact"
+ (mt/with-premium-features #{:content-translation}
+ (#'dictionary/import-translations! [["de" "Cat" "Katze"]])
+ (is (= 1 (count-translations)))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"The file could not be uploaded due to the following error"
+ (#'dictionary/import-translations! [["invalidlocale" "Dog" "Hund"]])))
+ (is (= 1 (count-translations)) "original row survives the failed import")
+ (let [translations (get-translations)]
+ (is (some #(and (= (:locale %) "de") (= (:msgid %) "Cat") (= (:msgstr %) "Katze")) translations))
+ (is (not (some #(= (:msgid %) "Dog") translations))))))))
+
(deftest import-translations-error-test
(ct-utils/with-clean-translations!
(testing "Import fails with validation errors"
diff --git a/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.clj b/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.clj
index 6b4a48018b5..b6444033bf1 100644
--- a/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/content_translation/routes_test.clj
@@ -116,7 +116,17 @@
(is (=? {:errors ["Row 4: Invalid locale: xx"]}
(mt/user-http-request :crowberto :post 422 "ee/content-translation/upload-dictionary"
{:request-options {:headers {"content-type" "multipart/form-data"}}}
- {:file csv-with-invalid-locale}))))))))
+ {:file csv-with-invalid-locale}))))))
+ (testing "admin can upload a file with non-ASCII characters"
+ (ct-utils/with-clean-translations!
+ (mt/with-premium-features #{:content-translation}
+ (let [csv (.getBytes "Language,String,Translation\nar,Cat,قطة" "UTF-8")]
+ (is (=? {:success true}
+ (mt/user-http-request :crowberto :post 200 "ee/content-translation/upload-dictionary"
+ {:request-options {:headers {"content-type" "multipart/form-data"}}}
+ {:file csv})))
+ (is (=? [{:locale "ar" :msgid "Cat" :msgstr "قطة"}]
+ (t2/select :model/ContentTranslation)))))))))
(defn random-embedding-secret-key [] (u.random/secure-hex 32))
diff --git a/enterprise/backend/test/metabase_enterprise/content_verification/api/collection_test.clj b/enterprise/backend/test/metabase_enterprise/content_verification/api/collection_test.clj
index 1f94b14165f..fe1421fa855 100644
--- a/enterprise/backend/test/metabase_enterprise/content_verification/api/collection_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/content_verification/api/collection_test.clj
@@ -109,3 +109,19 @@
{:moderated_item_id model-id
:moderated_item_type :card
:status :verified}))))))))
+
+(deftest remove-official-badge-test
+ (testing "PUT /api/collection/:id can remove the official badge when :official-collections is enabled"
+ (mt/with-premium-features #{:official-collections}
+ (mt/with-temp [:model/Collection {id :id} {:authority_level "official"}]
+ (is (nil? (:authority_level (mt/user-http-request :crowberto :put 200 (format "collection/%d" id)
+ {:authority_level nil}))))
+ (is (nil? (t2/select-one-fn :authority_level :model/Collection id)))))))
+
+(deftest non-admin-cannot-set-authority-level-test
+ (testing "PUT /api/collection/:id with :authority_level is rejected (403) for a non-admin"
+ (mt/with-premium-features #{:official-collections}
+ (mt/with-temp [:model/Collection {id :id} {:authority_level nil}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "collection/%d" id)
+ {:authority_level "official"})))))))
diff --git a/enterprise/backend/test/metabase_enterprise/content_verification/api/moderation_review_test.clj b/enterprise/backend/test/metabase_enterprise/content_verification/api/moderation_review_test.clj
index c2c290c3157..a60d21fa3f7 100644
--- a/enterprise/backend/test/metabase_enterprise/content_verification/api/moderation_review_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/content_verification/api/moderation_review_test.clj
@@ -91,3 +91,18 @@
:status "verified"
:moderated_item_id Integer/MAX_VALUE
:moderated_item_type "card"}))))))))))
+
+(deftest create-dashboard-review-test
+ (testing "POST /api/moderation-review can verify a dashboard"
+ (mt/with-premium-features #{:content-verification}
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}]
+ (mt/with-model-cleanup [:model/ModerationReview]
+ (is (=? {:status "verified"
+ :moderated_item_type "dashboard"
+ :moderated_item_id dashboard-id
+ :moderator_id (mt/user->id :crowberto)
+ :most_recent true}
+ (mt/user-http-request :crowberto :post 200 "moderation-review"
+ {:status "verified"
+ :moderated_item_id dashboard-id
+ :moderated_item_type "dashboard"}))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
index 610fb9f4062..abbacea3136 100644
--- a/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/custom_viz_plugin/api_test.clj
@@ -1,5 +1,6 @@
(ns ^:synchronous metabase-enterprise.custom-viz-plugin.api-test
(:require
+ [clj-http.client :as http]
[clojure.string :as str]
[clojure.test :refer :all]
[metabase-enterprise.custom-viz-plugin.cache :as cache]
@@ -650,6 +651,29 @@
{:dev_bundle_url "http://localhost:5174"})]
(is (= "gated-dev" (:identifier resp))))))))))
+(deftest dev-sse-proxy-test
+ (mt/with-premium-features #{:custom-viz}
+ (with-dev-mode-enabled
+ (mt/with-temp [:model/CustomVizPlugin {id :id} {:identifier "dev-sse-proxy"
+ :display_name "dev-sse-proxy"
+ :status :active
+ :dev_bundle_url "http://localhost:5199"}]
+ (testing "GET /:id/dev-sse returns 404 when no dev server URL is configured"
+ (mt/with-dynamic-fn-redefs [cache/resolve-dev-bundle (constantly nil)]
+ (is (re-find #"No dev server URL configured"
+ (str (mt/user-http-request :crowberto :get 404 (str "ee/custom-viz-plugin/" id "/dev-sse")))))))
+ (testing "GET /:id/dev-sse forwards Server-Sent Events from the dev server"
+ (mt/with-dynamic-fn-redefs [cache/resolve-dev-bundle (constantly "http://localhost:5199")
+ http/get (fn [_url _opts]
+ {:body (java.io.ByteArrayInputStream.
+ (.getBytes "data: hello\n\n" "UTF-8"))})]
+ (let [resp (mt/user-http-request-full-response
+ :crowberto :get 200 (str "ee/custom-viz-plugin/" id "/dev-sse"))]
+ (testing "response is served as an event stream"
+ (is (str/starts-with? (get-in resp [:headers "Content-Type"]) "text/event-stream")))
+ (testing "the dev server's event is forwarded to the browser"
+ (is (str/includes? (str (:body resp)) "data: hello"))))))))))
+
(deftest list-excludes-dev-plugins-when-dev-mode-disabled-test
(mt/with-premium-features #{:custom-viz}
(mt/with-temp [:model/CustomVizPlugin _ {:identifier "upload-viz-list"
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
index 213d7d6aa69..e8a9e8b7c2d 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/api/table_test.clj
@@ -2,6 +2,7 @@
"Tests for /api/ee/data-studio/table endpoints (enterprise-only: publish-tables, unpublish-tables)."
(:require
[clojure.test :refer :all]
+ [medley.core :as m]
[metabase.collections.models.collection :as collection]
[metabase.collections.test-utils :refer [without-library]]
[metabase.permissions.core :as perms]
@@ -15,6 +16,20 @@
(use-fixtures :once (fixtures/initialize :db))
+(deftest table-metadata-survives-deleted-transform-test
+ (testing "a table whose creating transform has since been deleted (metabase#69904)"
+ (mt/with-premium-features #{:transforms-basic}
+ (mt/with-temp [:model/Transform transform {}
+ :model/Table {table-id :id} {:transform_id (:id transform)}]
+ (t2/delete! :model/Transform (:id transform))
+ (testing "metabase_table.transform_id -> transform.id is ON DELETE SET NULL, not left dangling"
+ (is (nil? (t2/select-one-fn :transform_id :model/Table :id table-id))))
+ (testing "GET /api/table/:id does not crash"
+ (is (=? {:id table-id} (mt/user-http-request :crowberto :get 200 (str "table/" table-id)))))
+ (testing "GET /api/table (list, which hydrates :transform when transforms are enabled) does not crash"
+ (is (=? {:id table-id :transform nil}
+ (m/find-first #(= table-id (:id %)) (mt/user-http-request :crowberto :get 200 "table")))))))))
+
(deftest publish-table-test
(mt/with-premium-features #{:library :audit-app}
(without-library
@@ -200,11 +215,11 @@
(testing "POST /api/ee/data-studio/table/publish-tables publishes recursive upstream dependencies"
(mt/with-temp [:model/Collection {collection-id :id} {:type collection/library-data-collection-type}
:model/Database {db-id :id} {}
- ;; Customers table (upstream of orders)
- :model/Table {customers-id :id} {:db_id db-id :name "customers" :is_published false}
- :model/Field _ {:table_id customers-id :name "id"
+ ;; Purchasers table (upstream of orders)
+ :model/Table {purchasers-id :id} {:db_id db-id :name "purchasers" :is_published false}
+ :model/Field _ {:table_id purchasers-id :name "id"
:semantic_type :type/PK :base_type :type/Integer}
- :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :model/Field {cust-name-f :id} {:table_id purchasers-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
;; Orders table (upstream of order_items, downstream of customers)
:model/Table {orders-id :id} {:db_id db-id :name "orders" :is_published false}
@@ -212,8 +227,8 @@
:semantic_type :type/PK :base_type :type/Integer}
:model/Field {order-name-f :id} {:table_id orders-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
- :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
- :semantic_type :type/FK :base_type :type/Integer}
+ :model/Field {purchaser-fk :id} {:table_id orders-id :name "purchaser_id"
+ :semantic_type :type/FK :base_type :type/Integer}
;; Order items table (downstream of orders)
:model/Table {items-id :id} {:db_id db-id :name "order_items" :is_published false}
:model/Field _ {:table_id items-id :name "id"
@@ -221,7 +236,7 @@
:model/Field {order-fk :id} {:table_id items-id :name "order_id"
:semantic_type :type/FK :base_type :type/Integer}
;; Dimensions for FK remapping
- :model/Dimension _ {:field_id customer-fk
+ :model/Dimension _ {:field_id purchaser-fk
:human_readable_field_id cust-name-f
:type :external}
:model/Dimension _ {:field_id order-fk
@@ -232,7 +247,7 @@
{:table_ids [items-id]
:collection_id collection-id})
(are [table-id] (true? (t2/select-one-fn :is_published :model/Table table-id))
- items-id orders-id customers-id))))))
+ items-id orders-id purchasers-id))))))
(deftest unpublish-tables-with-downstream-dependents-test
(mt/with-premium-features #{:library}
@@ -268,12 +283,12 @@
(testing "POST /api/ee/data-studio/table/unpublish-tables unpublishes recursive downstream dependents"
(mt/with-temp [:model/Collection {coll-id :id} {:type collection/library-data-collection-type}
:model/Database {db-id :id} {}
- ;; Customers table (upstream of orders, published)
- :model/Table {customers-id :id} {:db_id db-id :name "customers" :is_published true
- :collection_id coll-id}
- :model/Field _ {:table_id customers-id :name "id"
+ ;; Purchasers table (upstream of orders, published)
+ :model/Table {purchasers-id :id} {:db_id db-id :name "purchasers" :is_published true
+ :collection_id coll-id}
+ :model/Field _ {:table_id purchasers-id :name "id"
:semantic_type :type/PK :base_type :type/Integer}
- :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :model/Field {cust-name-f :id} {:table_id purchasers-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
;; Orders table (downstream of customers, upstream of items, published)
:model/Table {orders-id :id} {:db_id db-id :name "orders" :is_published true
@@ -282,8 +297,8 @@
:semantic_type :type/PK :base_type :type/Integer}
:model/Field {order-name-f :id} {:table_id orders-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
- :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
- :semantic_type :type/FK :base_type :type/Integer}
+ :model/Field {purchaser-fk :id} {:table_id orders-id :name "purchaser_id"
+ :semantic_type :type/FK :base_type :type/Integer}
;; Order items table (downstream of orders, published)
:model/Table {items-id :id} {:db_id db-id :name "order_items" :is_published true
:collection_id coll-id}
@@ -292,7 +307,7 @@
:model/Field {order-fk :id} {:table_id items-id :name "order_id"
:semantic_type :type/FK :base_type :type/Integer}
;; Dimensions for FK remapping
- :model/Dimension _ {:field_id customer-fk
+ :model/Dimension _ {:field_id purchaser-fk
:human_readable_field_id cust-name-f
:type :external}
:model/Dimension _ {:field_id order-fk
@@ -300,9 +315,9 @@
:type :external}]
(testing "unpublishing customers also unpublishes orders and order_items (recursive downstream)"
(mt/user-http-request :crowberto :post 204 "ee/data-studio/table/unpublish-tables"
- {:table_ids [customers-id]})
+ {:table_ids [purchasers-id]})
(are [table-id] (false? (t2/select-one-fn :is_published :model/Table table-id))
- customers-id orders-id items-id))))))
+ purchasers-id orders-id items-id))))))
(defn- with-fk-linked-published-tables
"Sets up two Library/Data collections A and B, with published Table X in A and published Table Y in B, where Y has an
diff --git a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
index cc4aec5e88c..549df73f932 100644
--- a/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/data_studio/permissions/query_test.clj
@@ -4,6 +4,7 @@
{:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase-enterprise.data-studio.permissions.query-test]}}}}}}
(:require
[clojure.test :refer :all]
+ [metabase-enterprise.sandbox.test-util :as sandbox.tu]
[metabase.api.common :refer [*current-user-id* *current-user-permissions-set* *is-superuser?*]]
[metabase.permissions.core :as perms]
[metabase.query-permissions.core :as query-perms]
@@ -14,6 +15,43 @@
(use-fixtures :once (fixtures/initialize :db))
+(defn- do-with-published-venues!
+ "Publishes the venues table into a fresh `library-data` collection and configures the All Users
+ group (which every fresh user joins automatically) so the ONLY route to querying venues is the
+ collection-read grant on the published table: db/table `create-queries` are `:no`, table
+ `view-data` is `:unrestricted`, and db `view-data` is `db-view-data`.
+
+ Every row and permission here is COMMITTED, so the API server observes the intended permission
+ state. (Wrapping this in a `:rollback-only` transaction made the assertions vacuous: the request
+ thread never sees the uncommitted rows, so queries succeeded on the committed *default* full
+ access instead of the published-table mechanism under test.) `mt/with-restored-data-perms-for-group!`
+ restores the All Users data perms, the temp user/collection are cleaned up by `mt/with-temp`, and
+ the venues table's published state is restored in a `finally` before the collection is torn down.
+
+ Options:
+ :db-view-data - db-level view-data perm for All Users (default :unrestricted)
+ :grant? - grant collection-read to All Users on the published collection (default true)
+
+ Invokes `(f user-id collection-id)`."
+ [{:keys [db-view-data grant?] :or {db-view-data :unrestricted grant? true}} f]
+ (mt/with-restored-data-perms-for-group! (u/the-id (perms/all-users-group))
+ (mt/with-premium-features #{:library}
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/Collection {collection-id :id} {:type "library-data"}]
+ (try
+ (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id collection-id})
+ (let [all-users (perms/all-users-group)]
+ (perms/set-database-permission! all-users (mt/id) :perms/view-data db-view-data)
+ (perms/set-database-permission! all-users (mt/id) :perms/create-queries :no)
+ (if grant?
+ (perms/grant-collection-read-permissions! all-users collection-id)
+ (perms/revoke-collection-permissions! all-users collection-id))
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/view-data :unrestricted)
+ (perms/set-table-permission! all-users (mt/id :venues) :perms/create-queries :no))
+ (f user-id collection-id)
+ (finally
+ (t2/update! :model/Table (mt/id :venues) {:is_published false :collection_id nil})))))))
+
(deftest published-table-test
(testing "Published tables grant query access via collection permissions only with library enabled\n"
(doseq [features [#{} #{:library}]
@@ -91,49 +129,104 @@
"Collection permissions should NOT grant view-data permission")))))))))))
(deftest published-table-grants-database-access-test
- (mt/with-restored-data-perms-for-group! (u/the-id (perms/all-users-group))
- (mt/with-premium-features #{:library}
- (testing "POST /api/dataset in EE: published table access GRANTS database access"
- (t2/with-transaction [_conn nil {:rollback-only true}]
- (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
- :model/Collection collection {:type "library-data"}]
- ;; Publish the venues table into this collection
- (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
- (let [all-users (perms/all-users-group)]
- ;; Set database-level permissions first to establish baseline
- (perms/set-database-permission! all-users (mt/id) :perms/view-data :unrestricted)
- (perms/set-database-permission! all-users (mt/id) :perms/create-queries :no)
- ;; Grant collection read permission - this gives create-queries via published table mechanism
- (perms/grant-collection-read-permissions! all-users (u/the-id collection))
- ;; Set table-level permissions
- (perms/set-table-permission! all-users (mt/id :venues) :perms/view-data :unrestricted)
- (perms/set-table-permission! all-users (mt/id :venues) :perms/create-queries :no)
- ;; With collection permission on published table, query should succeed
- (testing "Query should succeed because EE grants create-queries via published table mechanism"
- (is (=? {:status "completed"
- :row_count pos-int?}
- (mt/with-current-user user-id
- (mt/user-http-request user-id :post 202 "dataset"
- (mt/mbql-query venues {:limit 1}))))))))))
- (testing "POST /api/dataset in EE: without collection permission, published table does NOT grant access"
- (t2/with-transaction [_conn nil {:rollback-only true}]
- (mt/with-temp [:model/User {user-id :id} {:email "[email protected]"}
- :model/Collection collection {:type "library-data"}]
- ;; Publish the venues table into this collection
- (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id (u/the-id collection)})
- (let [all-users (perms/all-users-group)]
- ;; Set database-level permissions first to establish baseline
- (perms/set-database-permission! all-users (mt/id) :perms/view-data :unrestricted)
- (perms/set-database-permission! all-users (mt/id) :perms/create-queries :no)
- ;; DON'T grant collection read permission - revoke it explicitly
- (perms/revoke-collection-permissions! all-users collection)
- ;; Set table-level permissions
- (perms/set-table-permission! all-users (mt/id :venues) :perms/view-data :unrestricted)
- (perms/set-table-permission! all-users (mt/id :venues) :perms/create-queries :no)
- ;; Without collection permission, query should fail at database check (403)
- (testing "Query should fail because user has no collection permission on published table"
- (is (=? {:status "failed"
- :error "You do not have permissions to run this query."}
- (mt/with-current-user user-id
- (mt/user-http-request user-id :post 403 "dataset"
- (mt/mbql-query venues {:limit 1})))))))))))))
+ (testing "POST /api/dataset in EE: published table access GRANTS database access"
+ (do-with-published-venues! {:grant? true}
+ (fn [user-id _collection-id]
+ (testing "Query should succeed because EE grants create-queries via published table mechanism"
+ (is (=? {:status "completed"
+ :row_count pos-int?}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 202 "dataset"
+ (mt/mbql-query venues {:limit 1})))))))))
+ (testing "POST /api/dataset in EE: without collection permission, published table does NOT grant access"
+ (do-with-published-venues! {:grant? false}
+ (fn [user-id _collection-id]
+ (testing "Query should fail because user has no collection permission on published table"
+ (is (=? {:status "failed"
+ :error "You do not have permissions to run this query."}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 403 "dataset"
+ (mt/mbql-query venues {:limit 1}))))))))))
+
+(deftest published-table-query-blocks-join-to-unpublished-table-test
+ (testing "POST /api/dataset: a published table's entity-picker visibility is not itself a security boundary --
+ a hand-crafted query joining an unpublished table must still be rejected"
+ (do-with-published-venues! {:db-view-data :blocked}
+ (fn [user-id _collection-id]
+ ;; categories is left blocked/unpublished -- no grant of any kind
+ (is (=? {:status "failed"}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 403 "dataset"
+ (mt/mbql-query venues
+ {:joins [{:source-table $$categories
+ :alias "Cat"
+ :condition [:= $category_id &Cat.$categories.id]}]
+ :limit 1})))))))))
+
+(deftest published-table-segment-and-metric-resolve-under-collection-only-perms-test
+ (do-with-published-venues! {}
+ (fn [user-id _collection-id]
+ (mt/with-temp [:model/Segment {segment-id :id} {:table_id (mt/id :venues)
+ :definition (:query (mt/mbql-query venues {:filter [:> $price 2]}))}
+ :model/Card {metric-id :id} {:type :metric
+ :dataset_query (mt/mbql-query venues {:aggregation [[:count]]})}]
+ (testing "a query referencing a :segment on the published table resolves"
+ (is (=? {:status "completed"}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 202 "dataset"
+ (mt/mbql-query venues {:filter [:segment segment-id]}))))))
+ (testing "a :metric card built on the published table resolves"
+ (is (=? {:status "completed"}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 202 (format "card/%d/query" metric-id))))))))))
+
+(deftest published-table-field-values-resolve-under-collection-only-perms-test
+ (do-with-published-venues! {}
+ (fn [user-id _collection-id]
+ (testing "GET /api/field/:id/values resolves via the collection grant"
+ (is (=? {:field_id (mt/id :venues :price)}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :get 200 (format "field/%d/values" (mt/id :venues :price)))))))
+ (testing "GET /api/field/:id/search/:search-id resolves via the collection grant"
+ (is (some? (mt/with-current-user user-id
+ (mt/user-http-request user-id :get 200
+ (format "field/%d/search/%d?limit=3" (mt/id :venues :name) (mt/id :venues :name))))))))))
+
+(deftest published-table-remap-to-unpublished-target-permission-error-test
+ ;; venues is published; categories (the FK-remap target) is deliberately left unpublished/blocked
+ (do-with-published-venues! {:db-view-data :blocked}
+ (fn [user-id _collection-id]
+ (mt/with-temp [:model/Dimension _ {:field_id (mt/id :venues :category_id)
+ :human_readable_field_id (mt/id :categories :name)
+ :type :external}]
+ (testing "querying venues (whose FK-remap target is unpublished) surfaces a permission error"
+ (is (=? {:status "failed"}
+ (mt/with-current-user user-id
+ (mt/user-http-request user-id :post 403 "dataset"
+ (mt/mbql-query venues {:limit 1}))))))))))
+
+(deftest published-sandboxed-table-query-reflects-sandbox-not-full-access-test
+ (mt/with-additional-premium-features #{:library}
+ (testing "a table that is both published (collection-grant) and GTAP-sandboxed applies row-level sandboxing,
+ not broader access, via the published-table path"
+ (sandbox.tu/with-gtaps-for-user! :rasta
+ {:gtaps {:venues {:query (mt/mbql-query venues {:filter [:= $venues.price 4]})}}}
+ (mt/with-temp [:model/Collection {collection-id :id} {:type "library-data"}]
+ (try
+ (t2/update! :model/Table (mt/id :venues) {:is_published true :collection_id collection-id})
+ (perms/grant-collection-read-permissions! &group collection-id)
+ (testing "POST /api/dataset row count reflects the sandbox filter, not the full table"
+ (let [full-count (mt/with-test-user :crowberto
+ (first (first (mt/formatted-rows [int]
+ (mt/process-query
+ (mt/mbql-query venues {:aggregation [[:count]]}))))))
+ result (mt/user-http-request :rasta :post 202 "dataset" (mt/mbql-query venues))
+ price-index (->> result :data :cols
+ (keep-indexed (fn [i col] (when (= "PRICE" (u/upper-case-en (:name col))) i)))
+ first)]
+ (is (=? {:status "completed" :row_count pos-int?} result))
+ (is (< (:row_count result) full-count) "sanity: some rows filtered")
+ (is (every? #(= 4 (nth % price-index)) (mt/rows result))
+ "every returned row has price = 4, per the sandbox filter")))
+ (finally
+ (t2/update! :model/Table (mt/id :venues) {:is_published false :collection_id nil}))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj
index f88ab6dec51..b97051c6869 100644
--- a/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/database_routing/api_test.clj
@@ -229,3 +229,32 @@
(is (t2/exists? :model/DataPermissions :group_id group-id :db_id db-id)))
(testing "New group should NOT have permissions for the destination database"
(is (not (t2/exists? :model/DataPermissions :group_id group-id :db_id destination-db-id)))))))
+
+(deftest manage-db-user-cannot-delete-destination-database-test
+ (testing "DELETE /api/database/:id is rejected (403) for a non-superuser with manage-database perms on a routed destination"
+ ;; NOTE: `DELETE /api/database/:id` calls `api/check-superuser` unconditionally before it ever looks at the
+ ;; database being deleted (see `metabase.warehouses-rest.api`), so this endpoint is admin-only full stop -- it
+ ;; doesn't have any destination-specific carve-out to disprove. To show that manage-database perms are actually
+ ;; being exercised here (and not just trivially irrelevant), we also enable `:advanced-permissions` -- without it,
+ ;; `current-user-can-write-db?` falls back to the OSS `superuser?` check and the manage-database grant below would
+ ;; be a no-op -- and we assert the *same* grant is refused identically for a regular database, proving there's no
+ ;; accidental carve-out that would let a manage-database non-admin delete regular databases while destinations
+ ;; stay protected (or vice versa).
+ (mt/with-additional-premium-features #{:advanced-permissions}
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/DatabaseRouter _ {:database_id db-id :user_attribute "foo"}
+ :model/Database {dest :id} {:router_database_id db-id}
+ :model/Database {regular-db-id :id} {}]
+ (mt/with-no-data-perms-for-all-users!
+ (perms/set-database-permission! (perms/all-users-group) db-id :perms/manage-database :yes)
+ (perms/set-database-permission! (perms/all-users-group) db-id :perms/create-queries :query-builder-and-native)
+ (perms/set-database-permission! (perms/all-users-group) regular-db-id :perms/manage-database :yes)
+ (perms/set-database-permission! (perms/all-users-group) regular-db-id :perms/create-queries :query-builder-and-native)
+ (testing "manage-database perms don't allow deleting a regular database either"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 (str "database/" regular-db-id)))))
+ (testing "manage-database perms on the router database don't allow deleting its destination database"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 (str "database/" dest)))))
+ (is (t2/exists? :model/Database :id regular-db-id))
+ (is (t2/exists? :model/Database :id dest)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/sandboxing_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/sandboxing_test.clj
new file mode 100644
index 00000000000..79c6cbbb998
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/database_routing/sandboxing_test.clj
@@ -0,0 +1,48 @@
+(ns ^:mb/driver-tests metabase-enterprise.database-routing.sandboxing-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase-enterprise.database-routing.e2e-test :as e2e]
+ [metabase-enterprise.test :as met]
+ [metabase.driver.settings :as driver.settings]
+ [metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.permissions.core :as perms]
+ [metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.sync.core :as sync]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(deftest sandboxing-applies-to-routed-destination-test
+ (testing "a row sandbox defined on a router table filters rows in the per-user routed destination database"
+ (mt/with-premium-features #{:database-routing :sandboxes :advanced-permissions}
+ (binding [driver.settings/*allow-testing-h2-connections* true]
+ (met/with-user-attributes! :rasta {"db_name" "destination-db" "filter_val" "keep"}
+ (e2e/with-temp-dbs! [router-db destination-db]
+ (t2/update! :model/Database (u/the-id destination-db)
+ {:name "destination-db" :router_database_id (u/the-id router-db)})
+ (sync/sync-database! router-db)
+ (e2e/execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('keep')")
+ (e2e/execute-statement! destination-db "INSERT INTO \"my_database_name\" (str) VALUES ('drop')")
+ (e2e/execute-statement! router-db "INSERT INTO \"my_database_name\" (str) VALUES ('router-only')")
+ (let [router-table (t2/select-one :model/Table :db_id (u/the-id router-db))
+ str-field (t2/select-one :model/Field :table_id (u/the-id router-table))
+ all-users (perms/all-users-group)]
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router-db)
+ :user_attribute "db_name"}
+ :model/Sandbox _ {:group_id (u/the-id all-users)
+ :table_id (u/the-id router-table)
+ :card_id nil
+ :attribute_remappings {"filter_val" [:dimension [:field (u/the-id str-field) nil]]}}]
+ (data-perms/set-database-permission! all-users (u/the-id router-db) :perms/view-data :unrestricted)
+ (data-perms/set-table-permission! all-users (u/the-id router-table) :perms/create-queries :query-builder)
+ (let [mp (lib.metadata.jvm/application-database-metadata-provider (u/the-id router-db))
+ query (lib/query mp (lib.metadata/table mp (u/the-id router-table)))]
+ (mt/with-temp [:model/Card card {:name "Router question"
+ :database_id (u/the-id router-db)
+ :dataset_query query}]
+ (testing "the sandboxed user only sees the destination row matching their attribute"
+ (let [response (mt/user-http-request :rasta :post 202 (str "card/" (u/the-id card) "/query"))]
+ (is (= [["keep"]] (mt/rows response))))))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
index 5245c0694d8..a7c32277e65 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/api_test.clj
@@ -225,6 +225,56 @@
:edges #{}}
(update response :edges set)))))))))))
+(deftest ^:sequential table-dependents-all-types-test
+ (testing "GET /api/ee/dependencies/graph dependents_count types every non-card dependent kind for a table root"
+ (mt/with-premium-features #{:dependencies :transforms-basic}
+ (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus
+ :model/Transform :model/Segment :model/Measure]
+ (mt/with-test-user :crowberto
+ (let [mp (mt/metadata-provider)
+ products-id (mt/id :products)
+ products (lib.metadata/table mp products-id)
+ price (lib.metadata/field mp (mt/id :products :price))
+ user (mt/fetch-user :crowberto)]
+ (card/create-card! (assoc (card-with-query "Question on products" (lib/query mp products))
+ :type :question)
+ user)
+ (card/create-card! (assoc (card-with-query "Model on products" (lib/query mp products))
+ :type :model)
+ user)
+ (card/create-card! (assoc (card-with-query "Metric on products"
+ (-> (lib/query mp products)
+ (lib/aggregate (lib/count))))
+ :type :metric)
+ user)
+ (mt/with-temp [:model/Segment {:as segment} {:name "Segment on products"
+ :table_id products-id
+ :definition (-> (lib/query mp products)
+ (lib/filter (lib/> price 50))
+ lib/->legacy-MBQL
+ :query)}
+ :model/Measure {:as measure} {:name "Measure on products"
+ :table_id products-id
+ :definition (-> (lib/query mp products)
+ (lib/aggregate (lib/sum price)))}
+ :model/Transform _ {:name "Transform on products"
+ :source {:type "query" :query (lib/query mp products)}
+ :target {:type "table" :name (mt/random-name)}}]
+ (events/publish-event! :event/segment-create {:object segment :user-id (mt/user->id :crowberto)})
+ (events/publish-event! :event/measure-create {:object measure :user-id (mt/user->id :crowberto)})
+ (deps.test/synchronously-run-backfill!)
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/dependencies/graph"
+ :id products-id :type "table")
+ table-node (first (filter #(= (:id %) products-id) (:nodes response)))]
+ (testing "the table's dependents_count includes every dependent kind, correctly typed"
+ (is (=? {:question pos-int?
+ :model pos-int?
+ :metric pos-int?
+ :segment pos-int?
+ :measure pos-int?
+ :transform pos-int?}
+ (:dependents_count table-node))))))))))))
+
(deftest dependents-test
(testing "GET /api/ee/dependencies/graph/dependents"
(mt/with-premium-features #{:dependencies}
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
index 6b25e030965..25fa25ea724 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
@@ -131,6 +131,42 @@
:from_entity_type :card :from_entity_id card-id
:to_entity_type :snippet :to_entity_id snippet-id)))))))
+(deftest ^:sequential backfill-snippet-in-snippet-test
+ (testing "A snippet referencing another snippet produces a snippet->snippet dependency"
+ (backfill-all-existing-entities!)
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/NativeQuerySnippet {inner-id :id} {:name "inner_snip" :content "1 = 1"}
+ :model/NativeQuerySnippet {outer-id :id} {:name "outer_snip" :content "SELECT * WHERE {{snippet: inner_snip}}"}]
+ (mark-stale! :snippet inner-id)
+ (mark-stale! :snippet outer-id)
+ (is (false? (t2/exists? :model/Dependency
+ :from_entity_type :snippet :from_entity_id outer-id
+ :to_entity_type :snippet :to_entity_id inner-id)))
+ (backfill-dependencies-single-trigger!)
+ (assert-processed :snippet inner-id)
+ (assert-processed :snippet outer-id)
+ (is (t2/exists? :model/Dependency
+ :from_entity_type :snippet :from_entity_id outer-id
+ :to_entity_type :snippet :to_entity_id inner-id))))))
+
+(deftest ^:sequential backfill-snippet-referencing-card-test
+ (testing "A snippet referencing a card produces a snippet->card dependency"
+ (backfill-all-existing-entities!)
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query orders)}
+ :model/NativeQuerySnippet {snippet-id :id} {:name "card_ref_snip"
+ :content (format "SELECT * FROM {{#%d}}" card-id)}]
+ (mark-stale! :card card-id)
+ (mark-stale! :snippet snippet-id)
+ (is (false? (t2/exists? :model/Dependency
+ :from_entity_type :snippet :from_entity_id snippet-id
+ :to_entity_type :card :to_entity_id card-id)))
+ (backfill-dependencies-single-trigger!)
+ (assert-processed :snippet snippet-id)
+ (is (t2/exists? :model/Dependency
+ :from_entity_type :snippet :from_entity_id snippet-id
+ :to_entity_type :card :to_entity_id card-id))))))
+
(deftest ^:sequential backfill-idempotency-test
(testing "Running the backfill multiple times should be idempotent"
(backfill-all-existing-entities!)
diff --git a/enterprise/backend/test/metabase_enterprise/embedding_hub/api_test.clj b/enterprise/backend/test/metabase_enterprise/embedding_hub/api_test.clj
index 281478378e4..f6295c97234 100644
--- a/enterprise/backend/test/metabase_enterprise/embedding_hub/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/embedding_hub/api_test.clj
@@ -130,6 +130,44 @@
(let [response (mt/user-http-request :crowberto :get 200 "/ee/embedding-hub/checklist")]
(is (false? (get-in response [:checklist :data-permissions-and-enable-tenants])))))))))
+(deftest move-dashboard-to-shared-checklist-test
+ (mt/id) ;; force the app-db's own database row to exist so add-data resolves deterministically
+ (mt/with-premium-features #{:embedding :tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (let [ck (fn [k] (get-in (mt/user-http-request :crowberto :get 200 "/ee/embedding-hub/checklist") [:checklist k]))]
+ (is (false? (ck :move-dashboard-to-shared)))
+ (mt/with-temp [:model/Collection {sc :id} {:namespace "shared-tenant-collection"}]
+ (is (false? (ck :move-dashboard-to-shared)))
+ (mt/with-temp [:model/Dashboard _ {:collection_id sc :archived false}]
+ (is (true? (ck :move-dashboard-to-shared)))))))))
+
+(deftest setting-and-sso-checklist-test
+ (mt/id) ;; force the app-db's own database row to exist so add-data resolves deterministically
+ (testing "402 without :embedding feature"
+ (mt/with-premium-features #{}
+ (mt/user-http-request :crowberto :get 402 "/ee/embedding-hub/checklist")))
+ (mt/with-premium-features #{:embedding}
+ (let [ck (fn [k] (get-in (mt/user-http-request :crowberto :get 200 "/ee/embedding-hub/checklist") [:checklist k]))]
+ (testing "create-test-embed reflects a published guest embed"
+ (mt/with-temp [:model/Card _ {:enable_embedding true}]
+ (is (true? (ck :create-test-embed)))))
+ (testing "create-test-embed reflects the test-embed-snippet-created setting"
+ (mt/with-temporary-setting-values [embedding-hub-test-embed-snippet-created true]
+ (is (true? (ck :create-test-embed)))))
+ (testing "embed-production reflects the production-embed-snippet-created setting"
+ (mt/with-temporary-setting-values [embedding-hub-production-embed-snippet-created true]
+ (is (true? (ck :embed-production)))))))
+ (mt/with-premium-features #{:embedding :sso-jwt}
+ (mt/with-temporary-setting-values [jwt-shared-secret "0123456789abcdef0123456789abcdef"
+ jwt-identity-provider-uri "https://idp.example.com"
+ jwt-enabled true]
+ (is (true? (get-in (mt/user-http-request :crowberto :get 200 "/ee/embedding-hub/checklist")
+ [:checklist :sso-configured])))))
+ (mt/with-premium-features #{:embedding}
+ (mt/with-temporary-setting-values [embedding-hub-sso-auth-manual-tested true]
+ (is (true? (get-in (mt/user-http-request :crowberto :get 200 "/ee/embedding-hub/checklist")
+ [:checklist :sso-auth-manual-tested]))))))
+
(deftest data-isolation-strategy-test
(testing "data-isolation-strategy is nil when no strategy is configured"
(mt/with-premium-features #{:embedding}
diff --git a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
index 536b47a1778..359882e4b6b 100644
--- a/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/impersonation/driver_test.clj
@@ -1085,6 +1085,51 @@
(format "INSERT INTO %s (name) VALUES ('x'); SELECT 1;" venues-table)
(format "SET ROLE NONE; DELETE FROM %s WHERE id = -1;" venues-table)))))))))))))))
+(deftest impersonated-action-write-permission-denied-test
+ (testing "An impersonated custom action whose role lacks write grants surfaces the DB permission error and leaves the row unchanged"
+ (mt/test-drivers (mt/normal-driver-select {:+features [:connection-impersonation :actions/custom]})
+ (mt/with-premium-features #{:advanced-permissions}
+ (let [venues-table (sql.tx/qualify-and-quote driver/*driver* "test-data" "venues")
+ role-a (u/lower-case-en (mt/random-name))]
+ (tx/with-temp-roles! driver/*driver*
+ (impersonation-granting-details driver/*driver* (mt/db))
+ ;; role-a is granted SELECT only (no INSERT/UPDATE/DELETE)
+ {role-a {venues-table {}}}
+ (impersonation-default-user driver/*driver*)
+ (impersonation-default-role driver/*driver*)
+ (let [granting-details (impersonation-granting-details driver/*driver* (mt/db))
+ spec (sql-jdbc.conn/connection-details->spec driver/*driver* granting-details)
+ read-name (fn [] (-> (jdbc/query spec [(format "SELECT name FROM %s WHERE id = 1" venues-table)])
+ first :name))]
+ (mt/with-temp [:model/Database database {:engine driver/*driver*,
+ :details (impersonation-details driver/*driver* (mt/db))}]
+ (mt/with-db database
+ (when (driver/database-supports? driver/*driver* :connection-impersonation-requires-role nil)
+ (t2/update! :model/Database :id (mt/id) (assoc-in (mt/db) [:details :role] (impersonation-default-role driver/*driver*))))
+ (sync/sync-database! database {:scan :schema})
+ (mt/with-actions-enabled
+ (impersonation.util-test/with-impersonations! {:impersonations [{:db-id (mt/id) :attribute "impersonation_attr"}]
+ :attributes {"impersonation_attr" role-a}}
+ (let [original-name (read-name)
+ execute-action-with-sql
+ (fn [sql]
+ (mt/with-actions [{_card-id :id} {:type :model :dataset_query (mt/mbql-query venues)}
+ {action-id :action-id} {:type :query
+ :name "Test action"
+ :dataset_query (update (mt/native-query {:query sql})
+ :type name)
+ :database_id (mt/id)
+ :parameters []}]
+ (actions.execution/execute-action! (action/select-action :id action-id) {})))]
+ (testing "write is denied for a role with only SELECT"
+ (is (thrown-with-msg?
+ java.lang.Exception
+ #"(?i)permission denied|denied to user|not authorized"
+ (execute-action-with-sql
+ (format "UPDATE %s SET name = 'hacked' WHERE id = 1" venues-table)))))
+ (testing "the row is unchanged"
+ (is (= original-name (read-name))))))))))))))))
+
(deftest admins-can-run-show-timezone-statement-test
(mt/test-drivers (mt/normal-driver-select {:+parent :postgres})
(mt/with-premium-features #{:advanced-permissions}
diff --git a/enterprise/backend/test/metabase_enterprise/library/api_test.clj b/enterprise/backend/test/metabase_enterprise/library/api_test.clj
index 7936c713615..56831ef88b7 100644
--- a/enterprise/backend/test/metabase_enterprise/library/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/library/api_test.clj
@@ -6,6 +6,21 @@
[metabase.test :as mt]
[toucan2.core :as t2]))
+(deftest create-library-endpoint-test
+ (mt/with-premium-features #{:library}
+ (mt/with-discard-model-updates! [:model/Collection]
+ (without-library
+ (testing "non-data-analysts cannot create the library"
+ (mt/user-http-request :rasta :post 403 "ee/library"))
+ (testing "POST /ee/library creates the Library root + Data/Metrics subcollections"
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/library")]
+ (is (= "Library" (:name response)))
+ (is (some? (t2/select-one-pk :model/Collection :type collection/library-data-collection-type)))
+ (is (some? (t2/select-one-pk :model/Collection :type collection/library-metrics-collection-type)))))
+ (testing "a second call rejects with 400 'Library already exists'"
+ (is (= "Library already exists"
+ (mt/user-http-request :crowberto :post 400 "ee/library"))))))))
+
(deftest get-library-test
(mt/with-premium-features #{:library}
(mt/with-discard-model-updates! [:model/Collection]
diff --git a/enterprise/backend/test/metabase_enterprise/metabot/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/api_test.clj
index 047becdf75b..af3af53194a 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot/api_test.clj
@@ -1,11 +1,55 @@
(ns metabase-enterprise.metabot.api-test
(:require
+ [clojure.string :as str]
[clojure.test :refer :all]
+ [metabase-enterprise.metabot.settings :as ee.metabot.settings]
+ [metabase-enterprise.metabot.usage :as ee.metabot.usage]
+ [metabase.config.core :as config]
+ [metabase.metabot.scope :as scope]
+ [metabase.metabot.self.openrouter :as openrouter]
+ [metabase.metabot.settings :as metabot.settings]
+ [metabase.metabot.test-util :as mut]
[metabase.premium-features.core :as premium-features]
[metabase.test :as mt]))
(set! *warn-on-reflection* true)
+(def ^:private test-provider "openrouter/anthropic/claude-haiku-4-5")
+
+(deftest agent-streaming-quota-exceeded-test
+ (testing "POST /api/metabot/agent-streaming short-circuits with the quota message once an instance usage limit is exceeded"
+ (mt/with-premium-features #{:ai-controls}
+ (mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider test-provider]
+ (binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
+ (with-redefs [config/is-dev? true]
+ (try
+ (mt/with-temp [:model/MetabotInstanceLimit _ {:tenant_id nil :max_usage 0}]
+ (ee.metabot.usage/clear-limit-cache!)
+ (let [llm-called? (atom false)]
+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]
+ (reset! llm-called? true)
+ (mut/mock-llm-response
+ [{:type :text :text "should not be reached"}]))]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:message "Hi"
+ :context {}
+ :conversation_id (str (random-uuid))
+ :history []
+ :state {}})
+ lines (str/split-lines response)
+ error-line (first (filter #(str/starts-with? % "3:") lines))]
+ (is (false? @llm-called?)
+ "the LLM must never be called once the instance limit is exceeded")
+ (is (some? error-line))
+ (is (str/includes? error-line "ai_usage_limit_reached"))
+ (is (str/includes? error-line (ee.metabot.settings/metabot-quota-reached-message))))))))
+ ;; the limit check is TTL-memoized process-wide; bust it so the now-removed temp limit
+ ;; doesn't leak a stale "exceeded" verdict into other tests
+ (finally
+ (ee.metabot.usage/clear-limit-cache!)))))))))
+
(deftest usage-get-returns-token-status-usage-test
(mt/with-premium-features #{:metabot-v3}
(with-redefs [premium-features/token-status (constantly {:meters {:anthropic:claude-sonnet-4-6:tokens {:meter-value 12345
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
index eb1ed0a9b15..0ebb0a8e83f 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
@@ -954,6 +954,17 @@
{:remote-sync-url "asdf://invalid-url"})]
(is (= "Invalid repository URL: only HTTPS URLs are supported (e.g., https://git-host.example.com/yourcompany/repo.git)" (:error response))))))
+(deftest settings-surfaces-clone-failure-message-test
+ (testing "PUT /api/ee/remote-sync/settings surfaces a JGit clone-failure as a 400 error message"
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings!
+ (fn [_] (throw (ex-info "Failed to clone git repository: URI not supported: file://bad" {})))]
+ (mt/with-temporary-setting-values [remote-sync-url nil
+ remote-sync-type :read-only]
+ (let [response (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"
+ {:remote-sync-url "https://github.com/does/not-exist.git"
+ :remote-sync-type :read-only})]
+ (is (re-find #"Failed to clone git repository" (:error response))))))))
+
(deftest settings-cannot-change-with-dirty-data
(testing "PUT /api/ee/remote-sync/settings doesn't allow losing dirty data"
(mt/with-dynamic-fn-redefs [remote-sync.object/dirty? (constantly true)
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj
index 053ab0ebdca..ac3229765a4 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/permissions_test.clj
@@ -4,6 +4,7 @@
[clojure.test :refer :all]
[metabase-enterprise.remote-sync.settings :as settings]
[metabase.collections.models.collection :as collections]
+ [metabase.lib.core :as lib]
[metabase.models.interface :as mi]
[metabase.test :as mt]
[toucan2.core :as t2]))
@@ -712,6 +713,30 @@
(is (false? (mi/can-write? (t2/select-one :model/Transform :id transform-id)))
"Non-superuser should not be able to write transforms even when remote-sync-type is read-write")))))))
+(deftest transform-write-endpoints-return-403-in-read-only-remote-sync-test
+ (testing "PUT/DELETE /api/transform/:id reject with 403 when remote-sync is enabled and read-only"
+ (mt/with-premium-features #{:transforms-basic}
+ (mt/with-temporary-setting-values [settings/remote-sync-url "https://github.com/test/repo.git"
+ settings/remote-sync-type :read-only]
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Transforms Collection"
+ :namespace :transforms}
+ :model/Transform {transform-id :id} {:name "Read-only Transform"
+ :collection_id coll-id
+ :source {:type "query"
+ :query (lib/native-query (mt/metadata-provider) "SELECT 1")}
+ :target {:database (mt/id)
+ :type "table"
+ :schema "public"
+ :name "target_table"}}]
+ (testing "PUT is rejected"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :crowberto :put 403 (str "transform/" transform-id) {:name "renamed"}))))
+ (testing "DELETE is rejected"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :crowberto :delete 403 (str "transform/" transform-id)))))
+ (testing "transform is untouched"
+ (is (= "Read-only Transform" (t2/select-one-fn :name :model/Transform :id transform-id)))))))))
+
(deftest transform-non-superuser-cannot-create-test
(testing "can_create should be false for non-superusers even when remote-sync-type is read-write"
(mt/with-premium-features #{:transforms-basic}
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
index 6b31ae68b6a..91cf7b96119 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/settings_test.clj
@@ -134,6 +134,20 @@
(mt/with-temporary-setting-values [:remote-sync-url "file://my/repo.git"]
(is (true? (settings/remote-sync-enabled)))))
+(deftest deactivate-clears-remote-sync-with-blank-url-test
+ (testing "Setting a blank remote-sync-url clears all git settings and disables remote sync"
+ (mt/with-dynamic-fn-redefs [settings/check-git-settings! (constantly true)]
+ (mt/with-temporary-setting-values [:remote-sync-url "file://my/repo.git"
+ :remote-sync-token "secret-token"
+ :remote-sync-branch "main"
+ :remote-sync-type :read-write]
+ (is (true? (settings/remote-sync-enabled)))
+ (settings/check-and-update-remote-settings! {:remote-sync-url ""})
+ (is (false? (settings/remote-sync-enabled)))
+ (is (nil? (settings/remote-sync-url)))
+ (is (nil? (settings/remote-sync-token)))
+ (is (nil? (settings/remote-sync-branch)))))))
+
;;; ------------------------------------------------- Root Collection Remote Sync -------------------------------------------------
(deftest check-and-update-remote-settings-env-var-aware-test
diff --git a/enterprise/backend/test/metabase_enterprise/replacement/api_test.clj b/enterprise/backend/test/metabase_enterprise/replacement/api_test.clj
index 8f7174e8b53..e9ea4ca5050 100644
--- a/enterprise/backend/test/metabase_enterprise/replacement/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/replacement/api_test.clj
@@ -10,6 +10,7 @@
[metabase.events.core :as events]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.query-processor.test :as qp]
[metabase.test :as mt]
[metabase.transforms.core :as transforms]
[metabase.transforms.test-util :refer [with-transform-cleanup!]]
@@ -451,6 +452,111 @@
(is (contains? events "model_to_transforms_migration_failure"))
(is (not (contains? events "model_to_transforms_migration_success"))))))))))))))
+(deftest replace-model-with-transform-dependent-shapes-test
+ (testing "POST /replace-model-with-transform correctly handles every dependent shape"
+ ;; one of the dependent shapes is a question that joins the model (rather than sourcing from it), so drivers
+ ;; also need :left-join support
+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table :left-join)
+ (mt/with-premium-features #{:dependencies}
+ (let [mp (mt/metadata-provider)
+ schema (t2/select-one-fn :schema :model/Table (mt/id :orders))]
+ (with-transform-cleanup! [target {:type "table"
+ :schema schema
+ :name "model_transform_shapes"}]
+ (mt/with-temp [:model/Card {model-id :id :as model-card}
+ {:database_id (mt/id)
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ :type :model
+ :name "Model"}
+
+ :model/Card {direct-id :id :as direct-card}
+ {:database_id (mt/id)
+ :dataset_query (lib/query mp (lib.metadata/card mp model-id))
+ :type :question
+ :name "Direct Child"}
+
+ :model/Card {nested-id :id :as nested-card}
+ {:database_id (mt/id)
+ :dataset_query (lib/query mp (lib.metadata/card mp direct-id))
+ :type :question
+ :name "Nested Grandchild"}
+
+ :model/Card {metric-id :id :as metric-card}
+ {:database_id (mt/id)
+ :dataset_query (lib/aggregate (lib/query mp (lib.metadata/card mp model-id)) (lib/count))
+ :type :metric
+ :name "Row Count Metric"}
+
+ :model/Card {join-id :id :as join-card}
+ {:database_id (mt/id)
+ :dataset_query (lib/join (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib.metadata/card mp model-id))
+ :type :question
+ :name "Joins The Model"}
+
+ :model/Dashboard {dashboard-id :id}
+ {:name "Model Dashboard"}
+
+ :model/DashboardCard {dashcard-id :id}
+ {:dashboard_id dashboard-id
+ :card_id model-id
+ :parameter_mappings [{:parameter_id "model-id-param"
+ :card_id model-id
+ :target [:dimension
+ (lib/->legacy-MBQL
+ (lib/ref (lib.metadata/field mp (mt/id :orders :id))))
+ {:stage-number 0}]}]}]
+ (mt/with-model-cleanup [:model/ReplacementRun]
+ (doseq [card [model-card direct-card nested-card metric-card join-card]]
+ (events/publish-event! :event/card-create {:object card :user-id (mt/user->id :crowberto)}))
+ (deps.test/synchronously-run-backfill!)
+ (let [response (mt/user-http-request :crowberto :post 202
+ "ee/replacement/replace-model-with-transform"
+ {:card_id model-id
+ :transform_name "Shapes Transform"
+ :transform_target {:type "table"
+ :schema schema
+ :name (:name target)
+ :database (mt/id)}
+ :target_collection_id nil})
+ run-id (:run_id response)
+ final (poll-run run-id :timeout-ms 30000)
+ transform (t2/select-one :model/Transform :name "Shapes Transform")
+ output-table (transforms/output-table transform)]
+ (is (= "succeeded" (:status final)))
+ (testing "direct dependent's source is swapped to the transform output table"
+ (let [q (t2/select-one-fn :dataset_query :model/Card :id direct-id)]
+ (is (= (:id output-table) (lib/primary-source-table-id q)))))
+ (testing "nested grandchild's own ref stays untouched (card__direct-id), yet still resolves transitively"
+ (let [q (t2/select-one-fn :dataset_query :model/Card :id nested-id)]
+ (is (= direct-id (lib/primary-source-card-id q)))
+ (is (=? {:status "completed"}
+ (mt/user-http-request :crowberto :post 202 (format "card/%d/query" nested-id))))))
+ (testing "metric aggregating the model is swapped and produces the same result"
+ (let [q (t2/select-one-fn :dataset_query :model/Card :id metric-id)
+ expected-count (->> (lib/aggregate (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/count))
+ qp/process-query
+ (mt/formatted-rows [int])
+ ffirst)
+ result (mt/user-http-request :crowberto :post 202 (format "card/%d/query" metric-id))]
+ (is (= (:id output-table) (lib/primary-source-table-id q)))
+ (is (=? {:status "completed" :row_count 1} result))
+ (is (= [[expected-count]] (mt/formatted-rows [int] result)))))
+ (testing "question joining (not sourcing from) the model has its join arm swapped"
+ (let [q (t2/select-one-fn :dataset_query :model/Card :id join-id)
+ joins (lib/joins q)]
+ (is (= 1 (count joins)))
+ (is (= (:id output-table) (-> joins first :stages first :source-table)))
+ (is (=? {:status "completed"}
+ (mt/user-http-request :crowberto :post 202 (format "card/%d/query" join-id))))))
+ (testing "dashboard displaying the model directly keeps working (model's own query is untouched)"
+ (is (= model-id (t2/select-one-fn :card_id :model/DashboardCard :id dashcard-id)))
+ (is (=? {:status "completed"}
+ (mt/user-http-request :crowberto :post 202
+ (format "dashboard/%d/dashcard/%d/card/%d/query"
+ dashboard-id dashcard-id model-id))))))))))))))
+
(deftest all-endpoints-require-superuser-test
(testing "All /ee/replacement/ endpoints return 403 for non-admin users"
(mt/with-premium-features #{:dependencies}
diff --git a/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj b/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj
index c15ff6b2a31..45771c8a5db 100644
--- a/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/replacement/field_refs_test.clj
@@ -247,6 +247,32 @@
:value_field [:field 1 nil]}}]}
(t2/select-one :model/Card card-id)))))))
+(deftest card-upgrade-field-refs!-join-alias-suffix-test
+ (testing "should correctly resolve a name ref disambiguated by a join-alias-derived numeric suffix (e.g. ID_2)"
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/join (lib.metadata/table mp (mt/id :products)))
+ lib/append-stage
+ (lib/filter (lib/not-null (lib/ensure-uuid [:field {:base-type :type/BigInteger} "ID_2"]))))]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query query}]
+ (replacement.field-refs/upgrade-field-refs! [:card card-id])
+ (is (=? {:dataset_query {:stages [{:source-table (mt/id :orders)}
+ {:filters [[:not-null {} [:field {} "Products__ID"]]]}]}}
+ (t2/select-one :model/Card card-id)))))))
+
+(deftest card-upgrade-field-refs!-nested-card-source-test
+ (testing "should upgrade a numeric field-id ref in a card sourced from another card (nested indirection)"
+ (let [mp (mt/metadata-provider)
+ parent-query (lib/query mp (lib.metadata/table mp (mt/id :orders)))]
+ (mt/with-temp [:model/Card {parent-id :id} {:dataset_query parent-query}]
+ (let [child-query (-> (lib/query mp (lib.metadata/card mp parent-id))
+ (lib/filter (lib/= (lib.metadata/field mp (mt/id :orders :id)) 1)))]
+ (mt/with-temp [:model/Card {child-id :id} {:dataset_query child-query}]
+ (replacement.field-refs/upgrade-field-refs! [:card child-id])
+ (is (=? {:dataset_query {:stages [{:source-card parent-id
+ :filters [[:= {} [:field {} "ID"] 1]]}]}}
+ (t2/select-one :model/Card child-id)))))))))
+
(deftest card-upgrade-field-refs!-no-changes-test
(testing "should not update a card when there are no changes"
(let [mp (mt/metadata-provider)
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
index a2aa4fa2784..8ad76ea8ba7 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/gtap_test.clj
@@ -5,6 +5,7 @@
[metabase.api.response :as api.response]
[metabase.driver.util :as driver.util]
[metabase.permissions-rest.data-permissions.graph :as data-perms.graph]
+ [metabase.permissions.models.data-permissions :as data-perms]
[metabase.premium-features.core :as premium-features]
[metabase.test :as mt]
[metabase.test.http-client :as client]
@@ -294,6 +295,25 @@
:table_id table-id-2
:group_id group-id))))))))))
+(deftest sandbox-and-create-queries-persist-together-test
+ (testing "PUT /api/permissions/graph with a sandbox view-data change and a create-queries change persists both (#46450)"
+ (mt/with-premium-features #{:sandboxes :advanced-permissions}
+ (mt/with-temp [:model/PermissionsGroup {gid :id} {}
+ :model/Card {cid :id} {}]
+ (with-gtap-cleanup!
+ (let [tid (mt/id :orders)
+ graph (-> (data-perms.graph/api-graph)
+ (assoc-in [:groups gid (mt/id) :view-data] {"PUBLIC" {tid :sandboxed}})
+ (assoc-in [:groups gid (mt/id) :create-queries] {"PUBLIC" {tid :query-builder}})
+ (assoc :sandboxes [{:table_id tid
+ :group_id gid
+ :card_id cid
+ :attribute_remappings {"foo" 1}}]))]
+ (mt/user-http-request :crowberto :put 200 "permissions/graph" graph)
+ (is (t2/exists? :model/Sandbox :table_id tid :group_id gid))
+ (is (= :query-builder
+ (data-perms/table-permission-for-groups #{gid} :perms/create-queries (mt/id) tid)))))))))
+
(deftest bulk-upsert-sandboxes-error-test
(testing "PUT /api/permissions/graph"
(testing "make sure an error is thrown if the :sandboxes key is included in the request, but the :sandboxes feature
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj
index 44afa700ca8..17011a53ccd 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/permissions_test.clj
@@ -5,6 +5,7 @@
[clojure.test :refer :all]
[metabase-enterprise.test :as met]
[metabase.model-persistence.models.persisted-info :as persisted-info]
+ [metabase.permissions-rest.data-permissions.graph :as data-perms.graph]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.query-processor.compile :as qp.compile]
[metabase.test :as mt]
@@ -152,3 +153,33 @@
:query {:source-table (str "card__" (u/the-id card))}
:type :query}))
"metabase_cache"))))))))
+
+(deftest oss-preserves-sandboxed-view-data-test
+ (testing "PUT /api/permissions/graph in OSS preserves stored EE sandbox config on rows it never surfaces"
+ (mt/with-model-cleanup [:model/Sandbox]
+ (mt/with-temp [:model/PermissionsGroup {gid :id} {}
+ :model/Card {cid1 :id} {}
+ :model/Card {cid2 :id} {}]
+ (mt/with-premium-features #{:advanced-permissions :sandboxes}
+ (mt/user-http-request
+ :crowberto :put 200 "permissions/graph"
+ (-> (data-perms.graph/api-graph)
+ (assoc-in [:groups gid (mt/id) :view-data]
+ {"PUBLIC" {(mt/id :orders) :sandboxed (mt/id :people) :sandboxed}})
+ (assoc :sandboxes [{:table_id (mt/id :orders) :group_id gid :card_id cid1 :attribute_remappings {"foo" 1}}
+ {:table_id (mt/id :people) :group_id gid :card_id cid2 :attribute_remappings {"foo" 1}}]))))
+ (mt/with-premium-features #{}
+ (mt/user-http-request
+ :crowberto :put 200 "permissions/graph"
+ (assoc-in (data-perms.graph/api-graph)
+ [:groups gid (mt/id) :create-queries]
+ {"PUBLIC" {(mt/id :orders) :query-builder}})))
+ (testing "both sandbox rows survive the OSS create-queries edit"
+ (is (t2/exists? :model/Sandbox :table_id (mt/id :orders) :group_id gid))
+ (is (t2/exists? :model/Sandbox :table_id (mt/id :people) :group_id gid)))
+ (testing "the graph still surfaces :sandboxed view-data under EE"
+ (mt/with-premium-features #{:advanced-permissions :sandboxes}
+ (is (=? {(mt/id :orders) :sandboxed
+ (mt/id :people) :sandboxed}
+ (get-in (data-perms.graph/api-graph)
+ [:groups gid (mt/id) :view-data "PUBLIC"])))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj
index df506169aea..2f9cf98ce48 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/query_processor/middleware/sandboxing_test.clj
@@ -4,6 +4,7 @@
metabase.test.data/run-mbql-query {:namespaces [metabase-enterprise.sandbox.query-processor.middleware.sandboxing-test]}}}}}}
(:require
[clojure.core.async :as a]
+ [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[medley.core :as m]
@@ -11,8 +12,10 @@
[metabase-enterprise.test :as met]
[metabase.api.common :as api]
[metabase.driver :as driver]
+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.util :as driver.u]
+ [metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-util :as lib.tu]
@@ -2001,3 +2004,92 @@
"Price column should be coerced to a timestamp string")
(is (str/starts-with? (last row) "1970-01-01")
"Price should be coerced exactly once, producing a date near the Unix epoch"))))))))
+
+(deftest regex-expression-over-sandboxed-table-test
+ (testing "a regex-match-first custom column over a sandboxed table compiles over the sandbox subquery and returns only the user's row (#14873)"
+ (mt/dataset test-data
+ ;; `with-gtaps!` runs both the remapping form and the body against a temp copy of the DB, so the metadata
+ ;; provider and field ids must be resolved *inside* that copy context (not captured beforehand).
+ (met/with-gtaps! {:gtaps {:people {:remappings {:id [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :people :id))))]}}}
+ :attributes {"id" "1"}}
+ (let [mp (mt/metadata-provider)
+ q (as-> (lib/query mp (lib.metadata/table mp (mt/id :people))) q
+ (lib/expression q "first" (lib/regex-match-first (lib.metadata/field mp (mt/id :people :name)) "^[A-Za-z]+"))
+ (lib/with-fields q [(lib/expression-ref q "first")]))]
+ (is (= [["Hudson"]] (mt/rows (qp/process-query q)))))))))
+
+(deftest case-expression-else-branch-table-substitution-test
+ (testing "a :case custom column whose :default references the sandboxed table has that table-ref rewritten to the sandbox subquery (#14859)"
+ (mt/dataset test-data
+ ;; Full, unsandboxed row count of orders, computed as admin *outside* the sandbox below. The sandboxed
+ ;; queries must return strictly fewer rows than this, otherwise a global sandbox bypass would go undetected.
+ (let [full-count (let [omp (mt/metadata-provider)]
+ (-> (lib/query omp (lib.metadata/table omp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ qp/process-query mt/rows ffirst))]
+ ;; `with-gtaps!` runs both the remapping form and the body against a temp copy of the DB, so the metadata
+ ;; provider and field ids must be resolved *inside* that copy context (not captured beforehand).
+ (met/with-gtaps! {:gtaps {:orders {:remappings {"uid" [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :orders :user_id))))]}}}
+ :attributes {"uid" "1"}}
+ (let [mp (mt/metadata-provider)
+ total (lib.metadata/field mp (mt/id :orders :total))
+ discount (lib.metadata/field mp (mt/id :orders :discount))
+ baseline (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/with-fields [(lib/ref total)]))
+ with-case (as-> (lib/query mp (lib.metadata/table mp (mt/id :orders))) with-case
+ (lib/expression with-case "cc" (lib/case [[(lib/> discount 0) discount]] total))
+ (lib/with-fields with-case [(lib/expression-ref with-case "cc")]))
+ baseline-count (count (mt/rows (qp/process-query baseline)))
+ with-case-count (count (mt/rows (qp/process-query with-case)))]
+ ;; `with-case` adds only a :case column whose :default references the sandboxed orders table.
+ ;; A missing table-ref rewrite (#14859) would make it throw or return a different row set than
+ ;; `baseline`. Equal counts prove the rewrite, not the sandbox filter (a global bypass would
+ ;; inflate both equally).
+ (is (= baseline-count with-case-count))
+ ;; Leak discriminator: the sandbox filters orders down to user 1's rows, so both queries must
+ ;; return strictly fewer rows than the full table. A global sandbox bypass would inflate them to
+ ;; `full-count` and fail here even though the equal-counts check above would still pass.
+ (is (< with-case-count full-count))))))))
+
+(deftest sandbox-fails-closed-when-filter-column-dropped-test
+ (testing "a column-based sandbox fails closed (errors, returns no unfiltered rows) when its filter column is dropped from the DB"
+ ;; Run against a throwaway physical copy of the warehouse (products table only). The DROP COLUMN
+ ;; below is destructive DDL; `met/with-gtaps!` copies only app-DB metadata (reusing the same
+ ;; physical `:details`), so without an isolated copy this would permanently drop products.category
+ ;; from the shared test-data DB and break every later test in the JVM. `with-actions-test-data`
+ ;; loads a freshly created copy and destroys it afterwards, so the DDL can't leak.
+ (mt/with-actions-test-data-tables #{"products"}
+ (mt/with-actions-test-data
+ ;; `with-gtaps!` runs the remapping form and body against a temp copy of the DB, so the metadata provider
+ ;; and field ids must be resolved *inside* that copy context (not captured beforehand).
+ (met/with-gtaps! {:gtaps {:products {:remappings {"category" [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :products :category))))]}}}
+ :attributes {"category" "Gizmo"}}
+ (testing "sanity check: the sandbox filters rows to the user's category"
+ (let [mp (mt/metadata-provider)
+ q (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/with-fields [(lib/ref (lib.metadata/field mp (mt/id :products :category)))])
+ (lib/limit 20))
+ rows (mt/rows (qp/process-query q))]
+ (is (seq rows))
+ (is (every? #(= "Gizmo" (first %)) rows))))
+ (testing "after the sandbox filter column is dropped, the query fails closed rather than returning unfiltered rows"
+ (let [db-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))]
+ (jdbc/execute! db-spec ["ALTER TABLE \"PUBLIC\".\"PRODUCTS\" DROP COLUMN \"CATEGORY\";"]))
+ ;; The consumer query selects only ID (a column that still exists). This is what makes the
+ ;; assertion distinguish fail-CLOSED from fail-OPEN: if the sandbox were silently dropped
+ ;; (fail-open), `SELECT ID FROM products` would SUCCEED and leak unfiltered rows, so the
+ ;; `thrown?` below would NOT hold and the test would fail. Because the sandbox is still
+ ;; enforced (fail-closed), its subquery references the now-missing CATEGORY column in its
+ ;; WHERE clause and the query throws. (If ID were replaced with an implicit `SELECT *`, the
+ ;; dropped CATEGORY would be selected either way and the throw would no longer prove
+ ;; enforcement.)
+ (is (thrown?
+ Throwable
+ (mt/rows (qp/process-query
+ (let [mp (mt/metadata-provider)]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/with-fields [(lib/ref (lib.metadata/field mp (mt/id :products :id)))])
+ (lib/limit 20)))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/schema_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/schema_test.clj
index dfa05ddde0a..e7605ad39b3 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/schema_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/schema_test.clj
@@ -23,3 +23,15 @@
:attribute_remappings {"user" ["variable" ["field" (mt/id :venues :id) nil]]}}]
(is (= {"user" [:variable [:field (mt/id :venues :id) nil]]}
(t2/select-one-fn :attribute_remappings :model/Sandbox :id (u/the-id gtap))))))))
+
+(deftest ^:parallel normalize-attribute-remappings-dimension-targets-test
+ (testing "dimension targets (bare, with stage-number, and with field-ref options) round-trip through the normalization transform"
+ (doseq [target [[:dimension [:field (mt/id :venues :category_id) nil]]
+ [:dimension [:field (mt/id :venues :category_id) nil] {"stage-number" 0}]
+ [:dimension [:field (mt/id :venues :category_id) {:base-type :type/Integer}] {"stage-number" 0}]]]
+ (mt/with-temp [:model/PermissionsGroup group {}
+ :model/Sandbox g {:table_id (mt/id :venues)
+ :group_id (u/the-id group)
+ :attribute_remappings {"cat" target}}]
+ (is (= {"cat" target}
+ (t2/select-one-fn :attribute_remappings :model/Sandbox :id (u/the-id g))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/snippet_collections/api/native_query_snippet_test.clj b/enterprise/backend/test/metabase_enterprise/snippet_collections/api/native_query_snippet_test.clj
index e3ae51e170e..72540faf691 100644
--- a/enterprise/backend/test/metabase_enterprise/snippet_collections/api/native_query_snippet_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/snippet_collections/api/native_query_snippet_test.clj
@@ -1,7 +1,9 @@
(ns metabase-enterprise.snippet-collections.api.native-query-snippet-test
(:require
[clojure.test :refer :all]
+ [metabase-enterprise.remote-sync.settings :as remote-sync.settings]
[metabase.collections.models.collection :as collection]
+ [metabase.models.interface :as mi]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.models.permissions :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
@@ -181,6 +183,22 @@
{:id (:id sub-collection) :name "Nested Snippet Collection"}]
(:data (mt/user-http-request :rasta :get 200 (format "collection/%d/items" (:id collection)))))))))))
+(deftest snippet-folder-read-only-remote-sync-test
+ (testing "A snippet folder (Collection in the snippets namespace) in a remote-synced collection cannot be edited under read-only remote sync"
+ (mt/with-premium-features #{:snippet-collections}
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Collection folder {:name "Snippet Folder"
+ :namespace "snippets"
+ :is_remote_synced true}]
+ (testing "read-only remote sync blocks writes to the snippet folder"
+ (mt/with-temporary-setting-values [remote-sync.settings/remote-sync-type :read-only]
+ (is (false? (mi/can-write? (t2/select-one :model/Collection :id (:id folder))))
+ "snippet folder in a remote-synced collection should not be writable when remote-sync-type is read-only")))
+ (testing "read-write remote sync allows writes to the snippet folder"
+ (mt/with-temporary-setting-values [remote-sync.settings/remote-sync-type :read-write]
+ (is (true? (mi/can-write? (t2/select-one :model/Collection :id (:id folder))))
+ "snippet folder should be writable when remote-sync-type is read-write"))))))))
+
(deftest ee-disabled-snippets-graph-test
(testing "GET /api/collection/root/items?namespace=snippets"
(mt/with-non-admin-groups-no-root-collection-for-namespace-perms "snippets"
diff --git a/enterprise/backend/test/metabase_enterprise/sso/settings_test.clj b/enterprise/backend/test/metabase_enterprise/sso/settings_test.clj
index 20d7ff2ee8c..f394b8655c2 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/settings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/settings_test.clj
@@ -328,3 +328,17 @@
"sso-enabled? should be true when OIDC is the only provider")
(is (false? (session/enable-password-login))
"enable-password-login should be honored when OIDC is enabled")))))
+
+(deftest saml-settings-clear-flips-configured-flag-test
+ (testing "clearing the SAML idp settings bundle flips saml-configured and saml-enabled back to false"
+ (mt/with-premium-features #{:sso-saml}
+ (tu/with-temporary-setting-values [saml-identity-provider-uri default-idp-uri
+ saml-identity-provider-certificate default-idp-cert
+ saml-enabled true]
+ (is (true? (sso-settings/saml-configured)))
+ (is (true? (sso-settings/saml-enabled))))
+ (tu/with-temporary-setting-values [saml-identity-provider-uri nil
+ saml-identity-provider-certificate nil
+ saml-enabled true]
+ (is (false? (sso-settings/saml-configured)))
+ (is (false? (sso-settings/saml-enabled)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/stale/api_test.clj b/enterprise/backend/test/metabase_enterprise/stale/api_test.clj
index 9c70c9551ec..35dffcc2ce3 100644
--- a/enterprise/backend/test/metabase_enterprise/stale/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/stale/api_test.clj
@@ -4,6 +4,8 @@
[metabase.analytics.snowplow-test :as snowplow-test]
[metabase.collections.models.collection :as collection]
[metabase.collections.models.collection-test :refer [with-collection-hierarchy!]]
+ [metabase.permissions.models.permissions :as perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.stale-test :as stale.test]
[metabase.test :as mt]
[metabase.util :as u]))
@@ -234,3 +236,23 @@
"cutoff_date" "1988-01-21T00:00:00Z"}
:user-id (str (mt/user->id :crowberto))}
(last (snowplow-test/pop-event-data-and-user-id!))))))))
+
+(deftest stale-candidates-respects-permissions-test
+ (mt/with-premium-features #{:collection-cleanup}
+ (testing "GET /api/ee/stale/:id read-checks the target collection"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection collection {}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 (stale-url collection)))))))
+ (testing "is_recursive traversal excludes descendants the user cannot write to"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection parent {}
+ :model/Collection child {:location (collection/children-location parent)}]
+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) parent)
+ (perms/grant-collection-read-permissions! (perms-group/all-users) child)
+ (stale.test/with-stale-items [:model/Card parent-card {:collection_id (:id parent)}
+ :model/Card child-card {:collection_id (:id child)}]
+ (let [result (mt/user-http-request :rasta :get 200 (stale-url parent) :is_recursive true)
+ ids (->> result :data (map (juxt :model :id)) set)]
+ (is (contains? ids ["card" (u/the-id parent-card)]))
+ (is (not (contains? ids ["card" (u/the-id child-card)]))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/api_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/api_test.clj
index 04aa78b1702..a81e075ce22 100644
--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/api_test.clj
@@ -203,3 +203,12 @@
(deftest get-current-grant-fails-for-non-admin-test
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 "ee/support-access-grant/current"))))
+
+(deftest create-grant-persists-notes-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-777"
+ :grant_duration_minutes 2880
+ :notes "Custom notes"})]
+ (is (= "Custom notes" (:notes response)))
+ (is (= "Custom notes" (:notes (t2/select-one :model/SupportAccessGrantLog :id (:id response))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj
index 17fdf23e490..c57199b716e 100644
--- a/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/tenants/api_test.clj
@@ -3,6 +3,8 @@
(:require
[clojure.test :refer [deftest testing is use-fixtures]]
[metabase.collections.models.collection :as collection]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.permissions.core :as perms]
[metabase.test :as mt]
[toucan2.core :as t2]))
@@ -775,3 +777,48 @@
:attributes {:department "engineering"
:region "us-west"}}
(:details audit-entry))))))))
+
+(deftest cannot-move-regular-collection-into-shared-tenant-collection-test
+ (testing "PUT /api/collection/:id cannot move a regular collection into a shared-tenant-namespace parent"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Collection {shared-id :id} {:namespace collection/shared-tenant-ns}
+ :model/Collection {regular-id :id} {}]
+ (mt/user-http-request :crowberto :put 400 (str "collection/" regular-id) {:parent_id shared-id}))))))
+
+(deftest can-create-dashboards-in-shared-tenant-collections-test
+ (testing "POST /api/dashboard can save a dashboard to a shared-tenant-namespace collection"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Collection {coll-id :id} {:namespace collection/shared-tenant-ns}]
+ (is (= coll-id
+ (:collection_id (mt/user-http-request :crowberto :post 200 "dashboard"
+ {:name "Tenant Dash" :collection_id coll-id})))))))))
+
+(deftest can-create-cards-in-shared-tenant-collections-test
+ (testing "POST /api/card can save a question to a shared-tenant-namespace collection"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Collection {coll-id :id} {:namespace collection/shared-tenant-ns}]
+ (let [query (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :venues)))]
+ (is (= coll-id
+ (:collection_id (mt/user-http-request :crowberto :post 200 "card"
+ {:name "Tenant Card"
+ :collection_id coll-id
+ :display "table"
+ :visualization_settings {}
+ :dataset_query query}))))))))))
+
+(deftest official-authority-level-in-shared-tenant-namespace-not-enforced-test
+ (testing "the backend does not block :authority_level \"official\" for shared-tenant-namespace collections (enforcement is FE-only)"
+ (mt/with-premium-features #{:tenants :official-collections}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Collection {shared-id :id} {:namespace collection/shared-tenant-ns}]
+ (mt/with-model-cleanup [:model/Collection]
+ (is (=? {:authority_level "official"
+ :namespace (name collection/shared-tenant-ns)}
+ (mt/user-http-request :crowberto :post 200 "collection/"
+ {:name (mt/random-name)
+ :parent_id shared-id
+ :authority_level "official"})))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj b/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj
index 5132f71d4f3..eedd21852d8 100644
--- a/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/tenants/user_api_test.clj
@@ -1,12 +1,16 @@
(ns metabase-enterprise.tenants.user-api-test
(:require
[clojure.test :refer :all]
+ [metabase.notification.test-util :as notification.tu]
[metabase.permissions.core :as perms]
[metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
[metabase.users.models.user-test :as user-test]
[metabase.util :as u]
[toucan2.core :as t2]))
+(use-fixtures :once (fixtures/initialize :notifications))
+
(defn- group-or-ids->user-group-memberships
[group-or-ids]
(map (fn [group-or-id] {:id (u/the-id group-or-id)}) group-or-ids))
@@ -202,3 +206,29 @@
(mt/user-http-request :crowberto :put 200 (str "user/" user-id) {:tenant_id tenant-id})
(is (= #{(u/the-id (perms/all-external-users-group))}
(t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id))))))))
+
+(deftest tenant-user-creation-sends-no-invite-email-test
+ (testing "POST /api/user creating a tenant user does not send an invite email even when SMTP is configured"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tid :id} {:name "T" :slug "t"}]
+ (notification.tu/with-send-notification-sync
+ (mt/with-fake-inbox
+ (mt/with-model-cleanup [:model/User]
+ (mt/user-http-request :crowberto :post 200 "user"
+ {:first_name "A" :last_name "B" :email (mt/random-email) :tenant_id tid})
+ (is (empty? @mt/inbox))))))))))
+
+(deftest tenant-user-can-join-custom-tenant-group-test
+ (testing "POST /api/user with a custom tenant group persists exactly two memberships (All tenant users + the custom group)"
+ (mt/with-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tid :id} {:name "T" :slug "t"}
+ :model/PermissionsGroup {gid :id} {:name "Fav" :is_tenant_group true}]
+ (mt/with-model-cleanup [:model/User]
+ (let [resp (mt/user-http-request :crowberto :post 200 "user"
+ {:first_name "M" :last_name "C" :email (mt/random-email) :tenant_id tid
+ :user_group_memberships [{:id (u/the-id (perms/all-external-users-group))}
+ {:id gid}]})]
+ (is (= #{(u/the-id (perms/all-external-users-group)) gid}
+ (set (map :id (:user_group_memberships resp))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.clj b/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.clj
index 0d907830a96..46212a2e59a 100644
--- a/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.clj
@@ -309,6 +309,31 @@
(is (compare-checkpoint-values checkpoint-type expected-second-checkpoint checkpoint)
(format "Checkpoint should be MAX(%s) from all 17 rows" (:field-name checkpoint-config)))))))))))))))))))
+(deftest reset-checkpoint-endpoint-test
+ (testing "POST /api/transform/:id/reset-checkpoint clears the checkpoint and forces a full reprocess"
+ (mt/test-drivers (test-drivers)
+ (mt/with-premium-features #{:transforms-basic}
+ (mt/dataset transforms-dataset/transforms-test
+ (with-transform-cleanup! [target-table (target-table-gen "reset_checkpoint")]
+ (let [checkpoint-config (get checkpoint-configs :integer)
+ transform-payload (make-incremental-transform-payload "Reset Checkpoint Transform" target-table :mbql checkpoint-config)]
+ (mt/with-temp [:model/Transform transform transform-payload]
+ (testing "first run processes all 16 rows and sets a checkpoint"
+ (execute-transform-with-ordering! transform :mbql (:field-name checkpoint-config) {:run-method :manual})
+ (transforms.tu/wait-for-table (:name target-table) 10000)
+ (is (= 16 (get-table-row-count target-table)))
+ (is (some? (get-checkpoint-value (:id transform)))))
+ (with-insert-test-products!
+ [{:name "Reset Checkpoint Extra" :category "Gadget" :price 379.99 :created-at "2024-01-20T10:00:00"}]
+ (testing "resetting the checkpoint clears the persisted value"
+ (is (nil? (mt/user-http-request :crowberto :post 204 (format "transform/%s/reset-checkpoint" (:id transform)))))
+ (is (nil? (get-checkpoint-value (:id transform)))))
+ (testing "the next run reprocesses the full source table, not just the tail"
+ (let [transform (t2/select-one :model/Transform (:id transform))]
+ (execute-transform-with-ordering! transform :mbql (:field-name checkpoint-config) {:run-method :manual})
+ (is (= 17 (get-table-row-count target-table))
+ "full reload replaces the target with all 17 source rows"))))))))))))
+
(deftest switch-incremental-to-non-incremental-test
(testing "Switching an incremental transform to non-incremental overwrites data"
(doseq [checkpoint-type [:integer :float :temporal]
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_manager_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_manager_test.clj
index 842fab8bdca..ea8ae331315 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_manager_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/api/workspace_manager_test.clj
@@ -124,6 +124,37 @@
:with-tables true
:with-fields true))))))
+(deftest rename-workspace-test
+ (testing "PUT /:id renames a workspace and returns the updated WorkspaceResponse"
+ (mt/with-temp [:model/Workspace {ws-id :id} {:name "Before"}]
+ (is (=? {:id ws-id :name "After"}
+ (mt/user-http-request :crowberto :put 200 (str "ee/workspace-manager/" ws-id) {:name "After"})))
+ (is (= "After" (t2/select-one-fn :name :model/Workspace :id ws-id)))
+ (testing "404 for a missing id"
+ (mt/user-http-request :crowberto :put 404 "ee/workspace-manager/13371337" {:name "X"})))))
+
+(deftest download-config-endpoint-test
+ (testing "GET /:id/config"
+ (mt/with-temp [:model/Database {db-id :id} {:engine :postgres :details {}}
+ :model/Workspace {ws-id :id} {:name "Cfg WS"}
+ :model/WorkspaceDatabase _ {:workspace_id ws-id
+ :database_id db-id
+ :database_details {}
+ :output_namespace ""
+ :input_schemas ["public"]
+ :status :provisioned}]
+ (testing "returns application/x-yaml with an attachment Content-Disposition"
+ (is (=? {:status 200
+ :headers {"Content-Type" "application/x-yaml"
+ "Content-Disposition" "attachment; filename=\"config.yml\""}}
+ (mt/user-http-request-full-response
+ :crowberto :get 200 (str "ee/workspace-manager/" ws-id "/config")))))
+ (testing "409 when a database is not :provisioned"
+ (t2/update! :model/WorkspaceDatabase :workspace_id ws-id {:status :unprovisioned})
+ (mt/user-http-request :crowberto :get 409 (str "ee/workspace-manager/" ws-id "/config")))
+ (testing "404 for a missing workspace"
+ (mt/user-http-request :crowberto :get 404 "ee/workspace-manager/13371337/config")))))
+
(defmacro ^:private with-data-analyst [& body]
`(perms.test-util/with-data-analyst-role! (mt/user->id :rasta) ~@body))
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj
index c8114f7722a..885e650729a 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/config_test.clj
@@ -4,7 +4,8 @@
[metabase-enterprise.workspaces.config :as config]
[metabase-enterprise.workspaces.test-util :as workspaces.tu]
[metabase.test :as mt]
- [metabase.test.fixtures :as fixtures]))
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util :as u]))
(use-fixtures :once (fixtures/initialize :db))
@@ -219,6 +220,30 @@
first)]
(is (false? (get-in own-db [:details :let-user-control-scheduling])))))))
+(deftest build-workspace-config-schemaless-engine-omits-filters-test
+ (testing "MySQL (no schemas) omits schema-filters-*/dataset-filters-* entirely (the :else {} branch)"
+ (mt/with-temp [:model/Database {db-id :id}
+ {:name "MySQL DW" :engine :mysql :details {:dbname "dw"}}
+ :model/Workspace {ws-id :id} {:name "mysql-ws"
+ :creator_id (mt/user->id :crowberto)}
+ :model/WorkspaceDatabase _
+ {:workspace_id ws-id
+ :database_id db-id
+ :database_details {:user "u" :password "p"}
+ :output_namespace "ws_alice"
+ :input_schemas ["public"]
+ :status :provisioned}]
+ ;; Select the MySQL entry explicitly rather than relying on `first` -- `:databases` also carries
+ ;; stub/sample entries (e.g. a pre-existing Sample Database), so its ordering isn't something this
+ ;; test should depend on.
+ (let [details (->> (config/build-workspace-config ws-id) :config :databases
+ (u/seek #(= :mysql (:engine %)))
+ :details)]
+ (is (nil? (:schema-filters-type details)))
+ (is (nil? (:schema-filters-patterns details)))
+ (is (nil? (:dataset-filters-type details)))
+ (is (nil? (:dataset-filters-patterns details)))))))
+
(deftest build-workspace-config-emits-sample-database-test
(testing "When a Sample Database exists in the instance, /config emits an entry with
standardized name/engine, empty :details, and :is_sample true. The entry is
diff --git a/modules/drivers/mongo/test/metabase/driver/mongo/parameters_test.clj b/modules/drivers/mongo/test/metabase/driver/mongo/parameters_test.clj
index 446e94c7583..a612a7f7153 100644
--- a/modules/drivers/mongo/test/metabase/driver/mongo/parameters_test.clj
+++ b/modules/drivers/mongo/test/metabase/driver/mongo/parameters_test.clj
@@ -9,7 +9,9 @@
[java-time.api :as t]
[metabase.driver.mongo.parameters :as mongo.params]
[metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]
[metabase.query-processor.test :as qp]
[metabase.test :as mt]
[metabase.util.json :as json]
@@ -312,6 +314,24 @@
{:$sort {:_id 1}}])}
(mongo.params/substitute-native-parameters :mongo mp stage)))))
+(deftest ^:parallel variable-default-value-substitution-test
+ (testing "previewing a Mongo native query substitutes a plain variable tag's :default when no runtime param is supplied (#47793)"
+ (let [mp (lib.tu/merged-mock-metadata-provider
+ meta/metadata-provider
+ {:database {:features (conj (:features (lib.metadata/database meta/metadata-provider))
+ :native-requires-specified-collection)}})
+ query (-> (lib/native-query mp (to-bson [{:$match {"quantity" (bson-literal "{{quantity}}")}}]))
+ (lib/with-native-extras {:collection "orders"})
+ (lib/with-template-tags {"quantity" {:name "quantity"
+ :display-name "Quantity"
+ :type :number
+ :default "10"
+ :required false}}))
+ stage (-> (lib/query-stage query 0)
+ (assoc :parameters (or (:parameters query) [])))]
+ (is (=? {:native (to-bson [{:$match {"quantity" 10}}])}
+ (mongo.params/substitute-native-parameters :mongo mp stage))))))
+
(deftest e2e-field-filter-test
(mt/test-driver :mongo
(mt/with-temporary-setting-values [report-timezone "UTC"]
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.clj
index fd8534be0a8..ab37834d5fa 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
@@ -796,3 +796,21 @@
:effective_type :type/Integer}]
:rows [[14 37.65 0 1] [nil 37.65 1 1] [14 nil 2 1] [nil nil 3 1]]}}
(qp.pivot/run-pivot-query pivot-query)))))))
+
+(deftest ^:parallel nested-native-card-recompile-no-bson-wrappers-test
+ (mt/test-driver :mongo
+ (testing "a nested query over a converted-to-native Mongo card compiles to a Bson-wrapper-free pipeline (#38181, #40557)"
+ (let [mp (mt/metadata-provider)
+ ;; compiled mongo pipelines are vectors; a real saved native mongo query stores the JSON text
+ native (json/encode
+ (:query (qp.compile/compile
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/with-fields [(lib.metadata/field mp (mt/id :venues :price))])))))]
+ (mt/with-temp [:model/Card {card-id :id}
+ {:dataset_query (-> (lib/native-query mp native)
+ (lib/with-native-extras {:collection "venues"}))}]
+ (let [compiled (qp.compile/compile (lib/query (mt/metadata-provider)
+ (lib.metadata/card (mt/metadata-provider) card-id)))]
+ ;; match the entire `BsonXxx` wrapper-class family, not just a hand-picked subset.
+ (is (not (re-find #"Bson[A-Z]\w*"
+ (pr-str (:query compiled)))))))))))
diff --git a/resources/migrations/063/20260706_comment_reaction_emoji_collation.yaml b/resources/migrations/063/20260706_comment_reaction_emoji_collation.yaml
new file mode 100644
index 00000000000..7495900fd25
--- /dev/null
+++ b/resources/migrations/063/20260706_comment_reaction_emoji_collation.yaml
@@ -0,0 +1,29 @@
+## Fix MySQL/MariaDB collation collapse of distinct emoji in comment_reaction.emoji
+
+databaseChangeLog:
+
+ - changeSet:
+ id: v63.2026-07-06T00:00:00
+ author: ranquild
+ dbms: mysql,mariadb
+ comment: >-
+ comment_reaction tables were created with the default utf8mb4_unicode_ci collation, which -- because its
+ Unicode Collation Algorithm weight table predates most emoji -- treats distinct supplementary-plane (4-byte)
+ emoji such as 👍 and 🎉 as equal. That collapsed the unique_user_comment_emoji constraint and every
+ exists?/delete equality check in metabase.comments.models.comment-reaction, silently deleting an existing
+ reaction instead of adding a second, different one. Switch the column to utf8mb4_bin so comparisons are
+ exact (byte-for-byte), matching the fix already applied to metabase_field.name in v49.2024-06-27T00:00:00.
+ changes:
+ - sql:
+ sql: >-
+ ALTER TABLE comment_reaction MODIFY
+ emoji VARCHAR(10)
+ CHARACTER SET utf8mb4
+ COLLATE utf8mb4_bin;
+ rollback:
+ - sql:
+ sql: >-
+ ALTER TABLE comment_reaction MODIFY
+ emoji VARCHAR(10)
+ CHARACTER SET utf8mb4
+ COLLATE utf8mb4_unicode_ci;
diff --git a/test/metabase/actions/models_test.clj b/test/metabase/actions/models_test.clj
index b57f8b33b44..49e6e7b2351 100644
--- a/test/metabase/actions/models_test.clj
+++ b/test/metabase/actions/models_test.clj
@@ -120,6 +120,25 @@
(->> (action/select-action :id action-id)
:parameters (map :id) set)))))))))))
+(deftest hydrate-implicit-action-test-3
+ (testing "Implicit actions do not map parameters to binary fields, the same way JSON fields are excluded"
+ (mt/test-driver :postgres
+ (mt/dataset (mt/dataset-definition
+ "binary-field-dataset"
+ [["binary_table"
+ [{:field-name "name", :base-type :type/Text}
+ {:field-name "bytea_col", :base-type {:native "bytea"}, :effective-type :type/*}]
+ [["Row One" (byte-array [0 1])]
+ ["Row Two" (byte-array [2 3])]]]])
+ (mt/with-actions-enabled
+ (mt/with-actions [_ {:type :model :dataset_query (mt/mbql-query binary_table)}
+ {action-id :action-id} {:type :implicit}]
+ (let [parameter-ids (->> (action/select-action :id action-id) :parameters (map :id) set)]
+ (testing "the non-binary column is still a valid parameter"
+ (is (contains? parameter-ids "name")))
+ (testing "the binary column is excluded"
+ (is (not (contains? parameter-ids "bytea_col")))))))))))
+
(deftest hydrate-creator-test
(mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)
(mt/with-actions-test-data-and-actions-enabled
diff --git a/test/metabase/actions_rest/api_test.clj b/test/metabase/actions_rest/api_test.clj
index d868a013441..d1ed7fb1511 100644
--- a/test/metabase/actions_rest/api_test.clj
+++ b/test/metabase/actions_rest/api_test.clj
@@ -683,6 +683,23 @@
(mt/user-http-request :crowberto :post 400 (format "action/%s/execute" action-id)
{:parameters {:name "Darth Vader"}})))))))))
+(deftest implicit-update-timestamp-round-trip-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :actions)
+ (mt/with-actions-test-data-tables #{"users"}
+ (mt/with-actions-test-data-and-actions-enabled
+ (mt/with-actions [_ {:type :model :dataset_query (mt/mbql-query users)}
+ {action-id :action-id} {:type :implicit :kind "row/update"}]
+ (testing "a prefetched temporal value round-trips unchanged through an update execution (#32840)"
+ (let [fetch! #(mt/user-http-request :crowberto :get 200 (format "action/%d/execute" action-id)
+ :parameters (json/encode {:id 1}))
+ {:keys [last_login] :as fetched} (fetch!)
+ local-value (.format ^java.time.OffsetDateTime last_login
+ (java.time.format.DateTimeFormatter/ofPattern "yyyy-MM-dd'T'HH:mm:ss"))]
+ (is (some? last_login))
+ (mt/user-http-request :crowberto :post 200 (format "action/%d/execute" action-id)
+ {:parameters (assoc fetched :last_login local-value)})
+ (is (= last_login (:last_login (fetch!)))))))))))
+
(deftest fetch-implicit-action-default-values-test
(mt/test-drivers (mt/normal-drivers-with-feature :actions)
(mt/with-actions-enabled
diff --git a/test/metabase/activity_feed/api_test.clj b/test/metabase/activity_feed/api_test.clj
index 66981499955..3c8b7eb5046 100644
--- a/test/metabase/activity_feed/api_test.clj
+++ b/test/metabase/activity_feed/api_test.clj
@@ -3,7 +3,9 @@
(:require
[clojure.test :refer :all]
[java-time.api :as t]
+ [metabase.content-verification.models.moderation-review :as moderation-review]
[metabase.events.core :as events]
+ [metabase.permissions.core :as perms]
[metabase.query-processor.util :as qp.util]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -402,3 +404,41 @@
(testing "Context query param controls return values: selections"
(is (= {:recents []}
(mt/user-http-request :crowberto :get 200 "activity/recents?context=selections")))))
+
+(deftest post-recents-selection-permission-test
+ (testing "POST /api/activity/recents read-checks the target before recording a selection"
+ (mt/with-model-cleanup [:model/RecentViews]
+ (mt/with-temp [:model/Collection c {} :model/Dashboard d {:collection_id (:id c)}]
+ (perms/revoke-collection-permissions! (perms/all-users-group) (:id c))
+ (mt/user-http-request :rasta :post 403 "activity/recents"
+ {:model "dashboard" :model_id (:id d) :context "selection"})
+ (perms/grant-collection-read-permissions! (perms/all-users-group) (:id c))
+ (mt/user-http-request :rasta :post 204 "activity/recents"
+ {:model "dashboard" :model_id (:id d) :context "selection"})))))
+
+(deftest card-query-collection-context-excluded-from-recents-test
+ (testing "A card-query event with a non-question context is not recorded as a recent view (#45003)"
+ (mt/with-test-user :crowberto
+ (mt/with-model-cleanup [:model/RecentViews]
+ (mt/with-temp [:model/Card {card-id :id} {:creator_id (mt/user->id :crowberto)}]
+ (doseq [ctx [:collection :dashboard :dashboard-subscription]]
+ (events/publish-event! :event/card-query {:user-id (mt/user->id :crowberto) :card-id card-id :context ctx}))
+ (is (empty? (filter (comp #{card-id} :id)
+ (:recents (mt/user-http-request :crowberto :get 200 "activity/recents?context=views"))))))))))
+
+(deftest recent-views-verified-status-test
+ (testing "moderated_status reflects a verified moderation review (metabase#18021)"
+ (mt/with-premium-features #{:content-verification}
+ (clear-recent-views-for-user :crowberto)
+ (mt/with-model-cleanup [:model/RecentViews :model/ModerationReview]
+ (mt/with-temp [:model/Card card {:name "verified card"}]
+ (moderation-review/create-review! {:moderated_item_id (:id card)
+ :moderated_item_type "card"
+ :moderator_id (mt/user->id :crowberto)
+ :status "verified"})
+ (events/publish-event! :event/card-query {:user-id (mt/user->id :crowberto) :card-id (:id card)})
+ (is (=? {:model "card" :moderated_status "verified"}
+ (->> (mt/user-http-request :crowberto :get 200 "activity/recents?context=views")
+ :recents
+ (filter (comp #{(:id card)} :id))
+ first))))))))
diff --git a/test/metabase/activity_feed/models/recent_views_test.clj b/test/metabase/activity_feed/models/recent_views_test.clj
index bb21b8f605a..4baff6a0625 100644
--- a/test/metabase/activity_feed/models/recent_views_test.clj
+++ b/test/metabase/activity_feed/models/recent_views_test.clj
@@ -6,6 +6,7 @@
[metabase.activity-feed.models.recent-views :as recent-views]
[metabase.collections.models.collection :as collection]
[metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.test :as mt]
[metabase.util.log :as log]
@@ -566,6 +567,25 @@
(mt/with-test-user :rasta
(:recents (recent-views/get-recents (mt/user->id :rasta) [:selections :views]))))))))
+(deftest context-exclusion-test
+ (mt/with-model-cleanup [:model/RecentViews]
+ (mt/with-temp
+ [:model/Card {card-id :id} {:type "question"}]
+ (recent-views/update-users-recent-views! (mt/user->id :rasta) :model/Card card-id :view)
+ (is (= 0 (count (mt/with-test-user :rasta (recent-views (mt/user->id :rasta) [:selections])))))
+ (recent-views/update-users-recent-views! (mt/user->id :rasta) :model/Card card-id :selection)
+ (is (= 1 (count (mt/with-test-user :rasta (recent-views (mt/user->id :rasta) [:selections]))))))))
+
+(deftest dashboard-can-write-reflects-real-permission-graph-test
+ (mt/with-model-cleanup [:model/RecentViews]
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Dashboard {dash-id :id} {:collection_id coll-id}]
+ (perms/grant-collection-read-permissions! (perms/all-users-group) coll-id)
+ (recent-views/update-users-recent-views! (mt/user->id :rasta) :model/Dashboard dash-id :view)
+ (is (= false
+ (:can_write (first (mt/with-test-user :rasta (recent-views (mt/user->id :rasta)))))))))))
+
(deftest special-collections-are-treated-specially
(mt/with-temp
[:model/Collection {instance-analytics-id :id} {:type collection/instance-analytics-collection-type}
diff --git a/test/metabase/api/timeline_event_test.clj b/test/metabase/api/timeline_event_test.clj
index 3801ce343d4..fc4afa3940b 100644
--- a/test/metabase/api/timeline_event_test.clj
+++ b/test/metabase/api/timeline_event_test.clj
@@ -2,7 +2,11 @@
"Tests for /api/timeline-event endpoints"
(:require
[clojure.test :refer :all]
+ [mb.hawk.assert-exprs.approximately-equal :as hawk.approx]
+ [metabase.analytics.snowplow-test :as snowplow-test]
[metabase.api.response :as api.response]
+ [metabase.permissions.models.permissions :as perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.test :as mt]
[metabase.test.http-client :as client]
[metabase.util :as u]
@@ -64,6 +68,41 @@
(->> (mt/user-http-request :rasta :put 200 (str "timeline-event/" (u/the-id event)) {:archived true})
:archived))))))))
+(deftest move-timeline-event-test
+ (testing "PUT /api/timeline-event/:id can move an event to another timeline"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Important Data"}
+ :model/Timeline {tl-a :id} {:name "Timeline A" :collection_id coll-id}
+ :model/Timeline {tl-b :id} {:name "Timeline B" :collection_id coll-id}
+ :model/TimelineEvent {ev-id :id} {:name "Event" :timeline_id tl-a}]
+ (is (= tl-b
+ (:timeline_id (mt/user-http-request :rasta :put 200 (str "timeline-event/" ev-id)
+ {:timeline_id tl-b}))))
+ (is (= tl-b (t2/select-one-fn :timeline_id :model/TimelineEvent :id ev-id))))))
+
+(deftest timeline-event-permissions-test
+ (testing "read-only users cannot create or edit timeline events"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Timeline {tl-id :id} {:collection_id coll-id}
+ :model/TimelineEvent {ev-id :id} {:timeline_id tl-id}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) coll-id)
+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll-id)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "timeline-event"
+ {:name "nope" :timestamp "2027-10-20" :timezone "UTC" :timeline_id tl-id})))
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (str "timeline-event/" ev-id) {:name "nope"}))))))
+
+(deftest create-timeline-event-tracks-snowplow-test
+ (testing "POST /api/timeline-event fires a snowplow new_event_created event"
+ (snowplow-test/with-fake-snowplow-collector
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Timeline {tl-id :id} {:collection_id coll-id}]
+ (mt/user-http-request :crowberto :post 200 "timeline-event"
+ {:name "RC1" :timestamp "2027-10-20" :timezone "UTC"
+ :time_matters false :timeline_id tl-id})
+ (is (some #(nil? (hawk.approx/=?-diff* {:data {"event" "new_event_created"}} %))
+ (snowplow-test/pop-event-data-and-user-id!)))))))
+
(deftest delete-timeline-event-test
(testing "DELETE /api/timeline-event/:id"
(mt/with-temp [:model/Collection {collection-id :id} {:name "Example Data"}
diff --git a/test/metabase/api/timeline_test.clj b/test/metabase/api/timeline_test.clj
index addb5c93cd5..2e7df91521b 100644
--- a/test/metabase/api/timeline_test.clj
+++ b/test/metabase/api/timeline_test.clj
@@ -189,6 +189,41 @@
(map :archived)
(every? false?))))))))
+(deftest rename-timeline-test
+ (testing "PUT /api/timeline/:id can rename a timeline"
+ (mt/with-temp [:model/Timeline {tl-id :id} {:name "Timeline A"}]
+ (is (= "Launches"
+ (:name (mt/user-http-request :rasta :put 200 (str "timeline/" tl-id) {:name "Launches"}))))
+ (is (= "Launches" (t2/select-one-fn :name :model/Timeline :id tl-id))))))
+
+(deftest move-timeline-test
+ (testing "PUT /api/timeline/:id can move a timeline to another collection"
+ (mt/with-temp [:model/Collection {coll-a :id} {}
+ :model/Collection {coll-b :id} {}
+ :model/Timeline {tl-id :id} {:collection_id coll-a}]
+ (is (= coll-b (:collection_id (mt/user-http-request :crowberto :put 200 (str "timeline/" tl-id)
+ {:collection_id coll-b}))))
+ (testing "a user without write permission on the destination collection is denied"
+ (perms/revoke-collection-permissions! (perms-group/all-users) coll-a)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (str "timeline/" tl-id) {:collection_id coll-a})))))))
+
+(deftest delete-timeline-test
+ (testing "DELETE /api/timeline/:id cascades to its events"
+ (mt/with-temp [:model/Timeline {tl-id :id} {:name "Releases"}
+ :model/TimelineEvent {ev-id :id} {:timeline_id tl-id :name "RC1"}]
+ (is (nil? (mt/user-http-request :crowberto :delete 204 (str "timeline/" tl-id))))
+ (is (nil? (t2/select-one :model/Timeline :id tl-id)))
+ (is (nil? (t2/select-one :model/TimelineEvent :id ev-id))))))
+
+(deftest create-timeline-permissions-test
+ (testing "POST /api/timeline is denied to a user with only read permission on the collection"
+ (mt/with-temp [:model/Collection {coll-id :id} {}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) coll-id)
+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll-id)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "timeline" {:name "nope" :collection_id coll-id}))))))
+
(defn- include-events-request
[timeline archived?]
(mt/user-http-request :rasta :get 200 (str "timeline/" (u/the-id timeline))
diff --git a/test/metabase/api_keys/api_test.clj b/test/metabase/api_keys/api_test.clj
index 1856e0b7eb0..bd3355731e8 100644
--- a/test/metabase/api_keys/api_test.clj
+++ b/test/metabase/api_keys/api_test.clj
@@ -389,3 +389,30 @@
:updated_by_id (mt/user->id :crowberto)}]
(is (nil? (mt/user-http-request :crowberto :delete 204 (format "api-key/%d" api-key-id))))
(is (true? (t2/select-one-fn :is_active :model/User :id (mt/user->id :crowberto))))))
+
+(deftest api-key-endpoints-are-admin-only-test
+ (testing "every /api/api-key endpoint rejects non-admins with a 403"
+ (doseq [[method path body] [[:get "api-key" nil]
+ [:get "api-key/count" nil]
+ [:post "api-key" {:group_id 1 :name "x"}]
+ [:put "api-key/1" {:name "x"}]
+ [:put "api-key/1/regenerate" nil]
+ [:delete "api-key/1" nil]]]
+ (testing (format "%s /%s" method path)
+ (is (= "You don't have permissions to do that."
+ (if body
+ (mt/user-http-request :rasta method 403 path body)
+ (mt/user-http-request :rasta method 403 path))))))))
+
+(deftest api-key-attributes-revisions-test
+ (testing "content created via an API key attributes the revision to the API key's backing user"
+ (mt/with-model-cleanup [:model/ApiKey :model/Dashboard :model/User]
+ (let [{k :unmasked_key, api-key-id :id} (mt/user-http-request :crowberto :post 200 "api-key"
+ {:group_id (:id (perms-group/admin))
+ :name (str (random-uuid))})
+ api-user-id (t2/select-one-fn :user_id :model/ApiKey :id api-key-id)
+ dashboard (client/client :post 200 "dashboard"
+ {:request-options {:headers {"x-api-key" k}}}
+ {:name "API key dashboard"})]
+ (is (= api-user-id
+ (t2/select-one-fn :user_id :model/Revision :model "Dashboard" :model_id (:id dashboard))))))))
diff --git a/test/metabase/appearance/settings_test.clj b/test/metabase/appearance/settings_test.clj
index 2b31922627c..92bd6c2a91f 100644
--- a/test/metabase/appearance/settings_test.clj
+++ b/test/metabase/appearance/settings_test.clj
@@ -29,6 +29,23 @@
(appearance.settings/help-link! :hidden)))
(is (= :metabase (appearance.settings/help-link)))))))
+(deftest application-font-validation-test
+ (mt/discard-setting-changes [application-font]
+ (mt/with-premium-features #{:whitelabel}
+ (testing "application-font accepts a valid font"
+ (appearance.settings/application-font! "Open Sans")
+ (is (= "Open Sans" (appearance.settings/application-font))))
+ (testing "application-font rejects an unknown font"
+ (is (thrown-with-msg?
+ Exception #"Invalid font"
+ (appearance.settings/application-font! "Comic Sans")))))
+ (mt/with-premium-features #{}
+ (testing "application-font cannot be set when whitelabeling is not enabled"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Setting application-font is not enabled because feature :whitelabel is not available"
+ (appearance.settings/application-font! "Open Sans")))))))
+
(deftest validate-help-url-test
(testing "validate-help-url accepts valid URLs with HTTP or HTTPS protocols"
(is (nil? (#'appearance.settings/validate-help-url "http://www.metabase.com")))
diff --git a/test/metabase/bookmarks/api_test.clj b/test/metabase/bookmarks/api_test.clj
index 4842b04f0cd..f78903abb60 100644
--- a/test/metabase/bookmarks/api_test.clj
+++ b/test/metabase/bookmarks/api_test.clj
@@ -3,6 +3,7 @@
(:require
[clojure.test :refer :all]
[metabase.models.interface :as mi]
+ [metabase.permissions.core :as perms]
[metabase.test :as mt]
[metabase.util :as u]
[toucan2.core :as t2]))
@@ -49,6 +50,41 @@
(map :type)
set)))))))
+(deftest bookmark-survives-card-dashboard-move-test
+ (testing "A CardBookmark survives moving the card to a Dashboard (metabase#dashboard-questions)"
+ (mt/with-temp [:model/Card card {}
+ :model/Dashboard d {}]
+ (mt/user-http-request :rasta :post 200 (str "bookmark/card/" (u/the-id card)))
+ (mt/user-http-request :rasta :put 200 (str "card/" (u/the-id card)) {:dashboard_id (u/the-id d)})
+ (is (some #(= (u/the-id card) (:item_id %))
+ (mt/user-http-request :rasta :get 200 "bookmark"))))))
+
+(deftest bookmark-requires-only-read-perms-test
+ (testing "POST /api/bookmark/card/:id succeeds for a read-only (collection-read) user"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card card {:collection_id (u/the-id collection)}]
+ (perms/grant-collection-read-permissions! (perms/all-users-group) collection)
+ (is (some? (mt/user-http-request :rasta :post 200 (str "bookmark/card/" (u/the-id card)))))))))
+
+(deftest bookmark-hidden-when-parent-collection-trashed-test
+ (testing "GET /api/bookmark hides a bookmark whose parent collection was trashed, and shows it again on restore (metabase#44499)"
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card {card-id :id} {:collection_id coll-id}]
+ (mt/user-http-request :rasta :post 200 (str "bookmark/card/" card-id))
+ (mt/user-http-request :crowberto :put 200 (str "collection/" coll-id) {:archived true})
+ (is (empty? (mt/user-http-request :rasta :get 200 "bookmark")))
+ (mt/user-http-request :crowberto :put 200 (str "collection/" coll-id) {:archived false})
+ (is (= [card-id] (map :item_id (mt/user-http-request :rasta :get 200 "bookmark")))))))
+
+(deftest bookmark-card-type-tracks-current-card-type-test
+ (testing "GET /api/bookmark's card_type reflects the card's current type after it changes (e.g. Turn into a model)"
+ (mt/with-temp [:model/Card {card-id :id} {:name "My Card"}]
+ (mt/user-http-request :rasta :post 200 (str "bookmark/card/" card-id))
+ (is (= "question" (:card_type (first (mt/user-http-request :rasta :get 200 "bookmark")))))
+ (t2/update! :model/Card card-id {:type :model})
+ (is (= "model" (:card_type (first (mt/user-http-request :rasta :get 200 "bookmark"))))))))
+
(defn bookmark-models [user-id & models]
(doseq [model models]
(cond
diff --git a/test/metabase/channel/impl/email_test.clj b/test/metabase/channel/impl/email_test.clj
index 6a9c99b647c..7f94761d345 100644
--- a/test/metabase/channel/impl/email_test.clj
+++ b/test/metabase/channel/impl/email_test.clj
@@ -7,6 +7,10 @@
[metabase.channel.impl.email :as email.impl]
[metabase.channel.render.util :as render.util]
[metabase.channel.urls :as urls]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.notification.send :as notification.send]
+ [metabase.notification.test-util :as notification.tu]
[metabase.test :as mt]))
(deftest bcc-enabled-test
@@ -186,3 +190,31 @@
(and (re-find #"Rendering user-provided template" message)
(re-find #"Hello" message)))
(messages)))))))
+
+(deftest email-branding-hidden-when-whitelabel-test
+ (testing "the 'Made with Metabase' footer respects the :whitelabel premium feature"
+ (notification.tu/with-notification-testing-setup!
+ (notification.tu/with-card-notification
+ [notification {:card {:name "Orders question"
+ :dataset_query (let [mp (mt/metadata-provider)]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/limit 1)))}
+ :subscriptions [{:type :notification-subscription/cron
+ :cron_schedule "0 0 0 * * ? *"}]
+ :handlers [{:channel_type :channel/email
+ :recipients [{:type :notification-recipient/user
+ :user_id (mt/user->id :crowberto)}]}]}]
+ (let [render! (fn []
+ (-> (notification.tu/with-captured-channel-send!
+ (#'notification.send/send-notification-sync! notification))
+ :channel/email first :message first :content))]
+ (testing "branding link is present without whitelabel"
+ (mt/with-premium-features #{}
+ (is (str/includes? (render!) "Made with"))))
+ ;; Whitelabeling is only wired up in EE builds (`enable-whitelabeling?` is gated on
+ ;; `config/ee-available?`), so `:whitelabel` can never hide the footer on OSS builds.
+ ;; The EE app-db jobs run this same file with EE on the classpath and cover the hidden case.
+ (mt/when-ee-evailable
+ (testing "branding link is hidden with whitelabel"
+ (mt/with-premium-features #{:whitelabel}
+ (is (not (str/includes? (render!) "Made with")))))))))))
diff --git a/test/metabase/channel/render/card_test.clj b/test/metabase/channel/render/card_test.clj
index c210022cda6..99cbfe225c5 100644
--- a/test/metabase/channel/render/card_test.clj
+++ b/test/metabase/channel/render/card_test.clj
@@ -482,6 +482,18 @@
expected-href (format "https://mb.com/dashboard/%d#scrollTo=%d" (:dashboard_id dc1) (:id dc1))]
(is (every? #(= % expected-href) (match/match-many rendered-card-content {:href href} href))))))))
+(deftest dashcard-title-override-wins-over-card-name-test
+ (testing "a dashcard's card.title override wins over the underlying card's own name in rendered emails (#18344)"
+ (mt/with-temp [:model/Card card {:name "Orders" :dataset_query (mt/mbql-query orders {:limit 1})}
+ :model/Dashboard dashboard {}
+ :model/DashboardCard dc {:dashboard_id (:id dashboard) :card_id (:id card)
+ :visualization_settings {:card.title "OrdersFoo"}}]
+ (let [rendered (:content (channel.render/render-pulse-card :inline "UTC" card dc
+ (qp/process-query (:dataset_query card))
+ {:channel.render/include-title? true}))]
+ (is (match/match-one rendered [:a _ "OrdersFoo"] true))
+ (is (not (match/match-one rendered [:a _ "Orders"] true)))))))
+
(deftest render-card-with-abbreviated-dates-test
(testing "Static-viz should render without error when date formatting is abbreviated (metabase#27020)"
(mt/with-temporary-setting-values [custom-formatting {:type/Temporal {:date_style "MMMM D, YYYY"}}]
diff --git a/test/metabase/channel/render/maps_test.clj b/test/metabase/channel/render/maps_test.clj
index e40ba193f2e..4136bde0912 100644
--- a/test/metabase/channel/render/maps_test.clj
+++ b/test/metabase/channel/render/maps_test.clj
@@ -2,8 +2,11 @@
(:require
[clj-http.fake :as fake]
[clojure.test :refer :all]
+ [metabase.channel.render.body :as body]
[metabase.channel.render.maps :as maps]
- [metabase.pulse.render.test-util :as render.tu])
+ [metabase.pulse.render.test-util :as render.tu]
+ [metabase.test :as mt]
+ [metabase.util.match :as match])
(:import
(java.awt Color)
(java.io ByteArrayInputStream)
@@ -50,6 +53,15 @@
(assoc test-sizing-opts
:tile-url "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"))))))
+(deftest render-region-map-test
+ (mt/id) ;; force the app-db test dataset to exist; the render pipeline queries it for timeline annotations
+ (testing "A region (choropleth) map card renders to an image, not a leaked-data table"
+ (let [card {:display :map :visualization_settings {"map.type" "region" "map.region" "us_states"}}
+ data {:cols [{:name "STATE" :base_type :type/Text} {:name "METRIC" :base_type :type/Number}]
+ :rows [["CA" 99999] ["NY" 11111]]}
+ rendered (body/render :region_map :inline "UTC" card nil data)]
+ (is (match/match-one (:content rendered) [:img _] true)))))
+
(deftest ^:parallel pin-marker-icon-loads-test
(testing "the teardrop pin marker icon is present on the classpath (markers pin type depends on it)"
(is (some? (deref @#'maps/pin-marker-icon)))))
diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.clj
index 02335e27b51..994aaf1132e 100644
--- a/test/metabase/collections_rest/api_test.clj
+++ b/test/metabase/collections_rest/api_test.clj
@@ -1136,6 +1136,18 @@
:data
(map (juxt :model :name))))))))))
+(deftest collection-items-order-by-model-with-subcollection-test
+ (testing "GET /api/collection/:id/items"
+ (testing "Results ordered by model include sub-collections, not just cards/dashboards/pulses"
+ (mt/with-temp [:model/Collection parent {:name "Parent"}
+ :model/Collection _ {:name "AA Sub" :location (collection/children-location parent)}
+ :model/Card _ {:name "ZZ" :collection_id (u/the-id parent)}
+ :model/Dashboard _ {:name "ZZ" :collection_id (u/the-id parent)}]
+ (is (= "collection"
+ (-> (mt/user-http-request :rasta :get 200
+ (str "collection/" (u/the-id parent) "/items?sort_column=model&sort_direction=desc"))
+ :data first :model)))))))
+
(deftest collection-items-include-latest-revision-test
(testing "GET /api/collection/:id/items"
(testing "Results have the lastest revision timestamp"
@@ -1722,6 +1734,13 @@
(with-some-children-of-collection! nil
(mt/user-http-request :crowberto :get 200 "collection/root")))))))
+(deftest fetch-root-collection-permissions-test
+ (testing "GET /api/collection/root"
+ (testing "403s (not silently filters) for a user without root read perms"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "collection/root")))))))
+
(defn results-matching [collection-items parameters]
(-> collection-items
(set/index (keys parameters))
@@ -2696,6 +2715,17 @@
(update :id integer?)
(update :entity_id string?)))))))))
+(deftest create-child-collection-of-other-users-personal-collection-test
+ (testing "POST /api/collection"
+ (testing "an admin can create a sub-collection inside another user's personal collection, a non-admin cannot"
+ (mt/with-model-cleanup [:model/Collection]
+ (let [lucky-collection (collection/user->personal-collection (mt/user->id :lucky))]
+ (is (=? {:name "Foo"} (mt/user-http-request :crowberto :post 200 "collection"
+ {:name "Foo" :parent_id (u/the-id lucky-collection)})))
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "collection"
+ {:name "Bar" :parent_id (u/the-id lucky-collection)}))))))))
+
(deftest create-collection-different-namespace-test
(testing "POST /api/collection"
(testing "\nShould be able to create a Collection in a different namespace"
@@ -2831,6 +2861,16 @@
(mt/user-http-request :rasta :put 403 (str "collection/" (u/the-id collection))
{:name "My Beautiful Collection"}))))))))
+(deftest set-authority-level-after-move-out-of-personal-collection-test
+ (testing "PUT /api/collection/:id allows setting authority_level after moving out of a personal-collection subtree (metabase#30235)"
+ (mt/with-premium-features #{:official-collections}
+ (mt/with-temp [:model/Collection sub {:location (collection/children-location
+ (collection/user->personal-collection (mt/user->id :crowberto)))}]
+ (mt/user-http-request :crowberto :put 200 (str "collection/" (u/the-id sub)) {:parent_id nil})
+ (is (= "official"
+ (:authority_level (mt/user-http-request :crowberto :put 200 (str "collection/" (u/the-id sub))
+ {:authority_level "official"}))))))))
+
(deftest archive-collection-test
(testing "PUT /api/collection/:id"
(testing "Archiving a collection should delete any alerts associated with questions in the collection"
@@ -2892,6 +2932,13 @@
(is (some? (mt/user-http-request :rasta :put 200 (str "collection/" (u/the-id collection-a))
{:archived true}))))))))
+(deftest archive-collection-inside-own-personal-collection-test
+ (testing "PUT /api/collection/:id can archive a collection nested inside the caller's own personal collection (metabase#15343)"
+ (mt/with-temp [:model/Collection child {:location (collection/children-location
+ (collection/user->personal-collection (mt/user->id :rasta)))}]
+ (is (=? {:archived true}
+ (mt/user-http-request :rasta :put 200 (str "collection/" (u/the-id child)) {:archived true}))))))
+
(deftest move-collection-test
(testing "PUT /api/collection/:id"
(testing "Can I *change* the `location` of a Collection? (i.e. move it into a different parent Collection)"
@@ -2975,6 +3022,15 @@
(is (some? (mt/user-http-request :rasta :put 200 (str "collection/" (u/the-id collection-a))
{:parent_id (u/the-id collection-d)}))))))))
+(deftest move-collection-into-own-descendant-rejected-test
+ (testing "PUT /api/collection/:id rejects moving a collection into its own descendant, without actually moving it"
+ ;; Pinning current (dubious) behavior: this returns a 500 today; a 4xx status would be the correct response.
+ (with-collection-hierarchy! [a b]
+ (let [location-before (t2/select-one-fn :location :model/Collection :id (u/the-id a))]
+ (mt/user-http-request :crowberto :put 500 (str "collection/" (u/the-id a)) {:parent_id (u/the-id b)})
+ (is (= location-before
+ (t2/select-one-fn :location :model/Collection :id (u/the-id a))))))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/collection/graph and PUT /api/collection/graph |
;;; +----------------------------------------------------------------------------------------------------------------+
@@ -3233,6 +3289,26 @@
ids (set (map :id (filter #(= model-name (:model %)) (:data items))))]
(is (contains? ids item-id)))))))))
+(deftest can-write-false-for-view-only-user-on-trashed-item-test
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Dashboard {dash-id :id} {:collection_id coll-id}]
+ (perms/revoke-collection-permissions! (perms/all-users-group) coll-id)
+ (perms/grant-collection-read-permissions! (perms/all-users-group) coll-id)
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" dash-id) {:archived true})
+ (testing "GET /api/collection/<trash-id>/items does not list the item for a view-only user"
+ ;; Browsing the trash listing requires *write* access to the item's original collection (see
+ ;; `:permission-level (if archived? :write :read)` in `collections-rest.api/collection-children*`), so a
+ ;; view-only user won't see it there at all.
+ (is (empty? (->> (mt/user-http-request :rasta :get 200
+ (format "collection/%d/items" (collection/trash-collection-id)))
+ :data
+ (filter #(= dash-id (:id %)))))))
+ (testing "GET /api/dashboard/:id reflects can_write:false for the trashed item"
+ ;; Unlike the trash listing, fetching the item directly only requires *read* access, so a view-only user can
+ ;; still load it -- and the response should honestly report that they can't write it.
+ (is (=? {:id dash-id :can_write false}
+ (mt/user-http-request :rasta :get 200 (str "dashboard/" dash-id)))))))
+
(deftest skip-graph-skips-graph-on-graph-PUT
(is (malli= [:map [:revision :int] [:groups :map]]
(mt/user-http-request :crowberto
diff --git a/test/metabase/comments/api_test.clj b/test/metabase/comments/api_test.clj
index e7fe58256ff..721063e1783 100644
--- a/test/metabase/comments/api_test.clj
+++ b/test/metabase/comments/api_test.clj
@@ -227,6 +227,70 @@
(mt/user-http-request :rasta :put 200 (str "comment/" comment-id)
{:is_resolved true})))))))
+(deftest update-delete-non-creator-non-admin-test
+ (testing "PUT/DELETE /api/comment/:comment-id - a user with document access who isn't the creator or an admin cannot edit or delete another user's comment"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {c-id :id} {:target_id doc-id :creator_id (mt/user->id :rasta)}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :lucky :put 403 (str "comment/" c-id) {:content {:text "hi"}})))
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :lucky :delete 403 (str "comment/" c-id)))))))
+
+(deftest unresolve-comment-test
+ (testing "PUT /api/comment/:comment-id can flip is_resolved back off after being set"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {comment-id :id} {:target_id doc-id}]
+ (mt/user-http-request :rasta :put 200 (str "comment/" comment-id) {:is_resolved true})
+ (is (=? {:is_resolved false}
+ (mt/user-http-request :rasta :put 200 (str "comment/" comment-id) {:is_resolved false}))))))
+
+(deftest resolve-reply-comment-test
+ (testing "PUT /api/comment/:comment-id allows resolving a non-root reply comment (no server-side root-only restriction)"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {root :id} {:target_id doc-id}
+ :model/Comment {reply :id} {:target_id doc-id :parent_comment_id root}]
+ (is (=? {:is_resolved true}
+ (mt/user-http-request :rasta :put 200 (str "comment/" reply) {:is_resolved true}))))))
+
+(deftest resolve-deleted-comment-test
+ (testing "PUT /api/comment/:comment-id can set is_resolved on a comment whose content has been soft-deleted"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {comment-id :id} {:target_id doc-id}]
+ (mt/user-http-request :rasta :delete 204 (str "comment/" comment-id))
+ (is (=? {:is_resolved true}
+ (mt/user-http-request :rasta :put 200 (str "comment/" comment-id) {:is_resolved true}))))))
+
+(deftest resolve-other-users-thread-test
+ (testing "PUT /api/comment/:comment-id - any user with document write access can resolve a thread they didn't create"
+ (mt/with-temp [:model/Document {doc-id :id} {:creator_id (mt/user->id :crowberto)}
+ :model/Comment {c-id :id} {:target_id doc-id :creator_id (mt/user->id :crowberto)}]
+ (is (=? {:is_resolved true}
+ (mt/user-http-request :rasta :put 200 (str "comment/" c-id) {:is_resolved true}))))))
+
+(deftest reply-to-resolved-comment-test
+ (testing "POST /api/comment/ allows replying to a resolved parent thread (no server-side restriction)"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {root :id} {:target_id doc-id}]
+ (mt/with-model-cleanup [:model/Comment]
+ (mt/user-http-request :rasta :put 200 (str "comment/" root) {:is_resolved true})
+ (is (=? {:parent_comment_id root}
+ (mt/user-http-request :rasta :post 200 "comment/"
+ {:target_type "document"
+ :target_id doc-id
+ :parent_comment_id root
+ :content (tiptap [:p "reply"])})))))))
+
+(deftest deleted-comment-without-replies-omitted-test
+ (testing "a deleted comment with no replies is omitted entirely from GET"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {c1 :id} {:target_id doc-id}
+ :model/Comment {c2 :id} {:target_id doc-id}]
+ (mt/user-http-request :rasta :delete 204 (str "comment/" c1))
+ (is (=? {:comments [{:id c2}]}
+ (mt/user-http-request :rasta :get 200 "comment/"
+ :target_type "document"
+ :target_id doc-id))))))
+
(deftest delete-comment-test
(testing "DELETE /api/comment/:comment-id"
(mt/with-temp [:model/Document {doc-id :id} {}
@@ -280,6 +344,50 @@
:target_type "document"
:target_id doc-id)))))))
+(deftest multiple-emoji-reactions-test
+ ;; Relies on comment_reaction.emoji using an exact (not linguistic) collation on MySQL/MariaDB -- see
+ ;; migration v63.2026-07-06T00:00:00. Under the table's original utf8mb4_unicode_ci collation, distinct
+ ;; supplementary-plane emoji like 👍 and 🎉 compared as equal, so the second POST below looked like a
+ ;; toggle-off of the first reaction instead of a new one.
+ (testing "POST /api/comment/:comment-id/reaction supports multiple distinct emoji on the same comment"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {comment-id :id} {:target_id doc-id}]
+ (mt/with-model-cleanup [:model/CommentReaction]
+ (mt/user-http-request :rasta :post 200 (str "comment/" comment-id "/reaction") {:emoji "👍"})
+ (mt/user-http-request :rasta :post 200 (str "comment/" comment-id "/reaction") {:emoji "🎉"})
+ (let [{:keys [comments]} (mt/user-http-request :rasta :get 200 "comment/"
+ :target_type "document" :target_id doc-id)
+ reactions (->> comments (filter #(= comment-id (:id %))) first :reactions
+ (map #(select-keys % [:emoji :count])) set)]
+ (is (= #{{:emoji "👍" :count 1} {:emoji "🎉" :count 1}} reactions)))))))
+
+(deftest multi-user-reaction-aggregation-test
+ (testing "reactions from different users on the same emoji aggregate, and one user removing theirs doesn't affect the other's"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {comment-id :id} {:target_id doc-id}]
+ (mt/with-model-cleanup [:model/CommentReaction]
+ (mt/user-http-request :rasta :post 200 (str "comment/" comment-id "/reaction") {:emoji "👍"})
+ (mt/user-http-request :crowberto :post 200 (str "comment/" comment-id "/reaction") {:emoji "👍"})
+ (is (=? {:comments [{:id comment-id
+ :reactions [{:emoji "👍" :count 2}]}]}
+ (mt/user-http-request :rasta :get 200 "comment/"
+ :target_type "document"
+ :target_id doc-id)))
+ (mt/user-http-request :crowberto :post 200 (str "comment/" comment-id "/reaction") {:emoji "👍"})
+ (is (=? {:comments [{:id comment-id
+ :reactions [{:emoji "👍" :count 1 :users [{:id (mt/user->id :rasta)}]}]}]}
+ (mt/user-http-request :rasta :get 200 "comment/"
+ :target_type "document"
+ :target_id doc-id)))))))
+
+(deftest cannot-react-to-deleted-comment-test
+ (testing "POST /api/comment/:comment-id/reaction 400s on a soft-deleted comment"
+ (mt/with-temp [:model/Document {doc-id :id} {}
+ :model/Comment {comment-id :id} {:target_id doc-id}]
+ (mt/user-http-request :rasta :delete 204 (str "comment/" comment-id))
+ (is (= "Cannot react to deleted comments"
+ (mt/user-http-request :rasta :post 400 (str "comment/" comment-id "/reaction") {:emoji "👍"}))))))
+
(deftest comments-permissions-test
(testing "Comment permissions - users without document access cannot read or write comments"
(mt/with-non-admin-groups-no-root-collection-perms
@@ -311,6 +419,30 @@
(mt/user-http-request :lucky :post 403 (str "comment/" restricted-comment-id "/reaction")
{:emoji "👍"})))))))))
+(deftest mention-notification-content-test
+ (testing "@mention notifications pin heading text and comment link, not just the subject"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (mt/with-temp [:model/Document {doc-id :id} {:name "Mentions Doc"
+ :creator_id (mt/user->id :lucky)}]
+ (mt/with-model-cleanup [:model/Comment :model/Notification]
+ (mt/with-fake-inbox
+ (notification.seed/seed-notification!)
+ (let [created (mt/user-http-request :rasta :post 200 "comment/"
+ {:target_type "document"
+ :target_id doc-id
+ :content (tiptap
+ [:smartLink {:model "user"
+ :entityId (mt/user->id :crowberto)}])})
+ expected [{:subject "Comment on Mentions Doc"
+ :body [{:content (relaxed-re
+ (str (:common_name (mt/fetch-user :rasta)) " left a comment on a document")
+ (format "http://localhost:\\d+/document/%s#comment-%s"
+ doc-id
+ (:id created)))}]}]]
+ (is (=? {(:email (mt/fetch-user :lucky)) expected
+ (:email (mt/fetch-user :crowberto)) expected}
+ (first (swap-vals! mt/inbox empty)))))))))))
+
(deftest mention-entities-test
(testing "We can get users to mention"
(is (=? {:data [{:id int? :common_name "Crowberto Corv" :model "user"}
diff --git a/test/metabase/dashboards/models/dashboard_card_test.clj b/test/metabase/dashboards/models/dashboard_card_test.clj
index 95a324cb06b..c12a131e1ab 100644
--- a/test/metabase/dashboards/models/dashboard_card_test.clj
+++ b/test/metabase/dashboards/models/dashboard_card_test.clj
@@ -325,6 +325,21 @@
(is (= dashcard
transformed))))))
+(deftest ^:parallel visualizer-settings-no-extra-keys-test
+ (testing "visualization_settings.visualization.settings persists exactly as written (VIZ-905)"
+ (mt/with-temp [:model/Dashboard dash {}
+ :model/Card card {}
+ :model/DashboardCard dashcard {:dashboard_id (:id dash)
+ :card_id (:id card)
+ :visualization_settings
+ {:visualization {:display "line"
+ :columnValuesMapping {}
+ :settings {"graph.dimensions" ["A"]
+ "graph.metrics" ["B"]}}}}]
+ (is (= {:graph.dimensions ["A"] :graph.metrics ["B"]}
+ (-> (t2/select-one :model/DashboardCard :id (:id dashcard))
+ :visualization_settings :visualization :settings))))))
+
(deftest ^:parallel after-select-tolerates-dangling-visualizer-ref-test
(testing "A DashboardCard whose visualizer settings reference a deleted Card is returned unmodified on read,
rather than throwing and making the dashcard unloadable."
diff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.clj
index 96b5fafc170..7ff5dfd0df4 100644
--- a/test/metabase/dashboards_rest/api_test.clj
+++ b/test/metabase/dashboards_rest/api_test.clj
@@ -42,6 +42,7 @@
[metabase.query-processor.pivot.test-util :as api.pivots]
[metabase.query-processor.streaming.test-util :as streaming.test-util]
[metabase.query-processor.test :as qp]
+ [metabase.query-processor.test-util :as qp.test-util]
[metabase.revisions.models.revision :as revision]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -140,6 +141,14 @@
(defmacro ^:private with-dashboards-in-writeable-collection! [dashboards-or-ids & body]
`(do-with-dashboards-in-a-collection! perms/grant-collection-readwrite-permissions! ~dashboards-or-ids (fn [] ~@body)))
+(defn- implicit-fk-column-ref
+ "The legacy `[:field id {:source-field fk-id}]` ref for the column with `target-field-id`, as reached implicitly via
+ an FK from `from-table-key` (e.g. `products.category` reached via `orders.product_id`)."
+ [mp from-table-key target-field-id]
+ (let [query (lib/query mp (lib.metadata/table mp (mt/id from-table-key)))
+ col (m/find-first #(= (:id %) target-field-id) (lib/filterable-columns query))]
+ (lib.convert/->legacy-MBQL (lib/ref col))))
+
(defn do-with-simple-dashboard-with-tabs
[f]
(mt/with-temp
@@ -5692,3 +5701,672 @@
{:parameters [{:id "_DASH_PRODUCT_ID_" :value "1"}]})
(is (some? (t2/select-one-fn :result_metadata :model/Card :id card-id))
"result_metadata should be persisted when native dashcard runs with default parameter values")))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Additional parameter/permission coverage |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(deftest dashboard-chain-filter-search-missing-data-perms-test
+ (testing "GET /api/dashboard/:id/params/:param-key/search/:query"
+ (testing "missing data perms should not affect search endpoint when users have collection access (#8472)"
+ (mt/with-temp-copy-of-db
+ (with-chain-filter-fixtures [{:keys [dashboard param-keys]}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :venues) :perms/create-queries :no)
+ (is (= {:values [["African"]] :has_more_values false}
+ (mt/user-http-request :rasta :get 200
+ (chain-filter-search-url (:id dashboard) (:category-name param-keys) "afr"))))))))))
+
+(deftest add-card-parameter-mapping-fk-target-permissions-test
+ (testing "PUT /api/dashboard/:id checks perms on the *joined* table for an FK-qualified dimension target"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:parameters [{:id "_ID_" :type :id :name "ID" :slug "id"}]}
+ :model/Card {card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}]
+ (let [mapping [{:parameter_id "_ID_"
+ :target [:dimension (implicit-fk-column-ref mp :orders (mt/id :products :id))]}]
+ put! (fn [status]
+ (mt/user-http-request :rasta :put status (format "dashboard/%d" dash-id)
+ {:dashcards [{:id -1 :card_id card-id :row 0 :col 0 :size_x 4 :size_y 4
+ :parameter_mappings mapping}]
+ :tabs []}))]
+ (is (=? {:message #"(?i).*data permissions.*PRODUCTS.*"} (put! 403)))
+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :products) :perms/view-data :unrestricted)
+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :products) :perms/create-queries :query-builder)
+ (is (=? [{:parameter_mappings [{:parameter_id "_ID_"
+ :target ["dimension" ["field" (mt/id :products :id)
+ {:source-field (mt/id :orders :product_id)}]]}]}]
+ (:dashcards (put! 200))))))))))
+
+(deftest required-parameter-without-default-test
+ (testing "PUT /api/dashboard/:id currently accepts a :required parameter with no :default (FE-only enforced)"
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}]
+ (with-dashboards-in-writeable-collection! [dashboard-id]
+ (is (=? {:parameters [{:required true}]}
+ (mt/user-http-request :rasta :put 200 (str "dashboard/" dashboard-id)
+ {:parameters [{:name "Month" :slug "month" :id "a" :type :date/month-year :required true}]})))))))
+
+(deftest remove-one-parameter-mapping-across-multiple-dashcards-test
+ (testing "PUT /api/dashboard/:id selectively removes one parameter_id's mappings from multiple dashcards while preserving another"
+ (let [mp (mt/metadata-provider)
+ p1-target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :venues :name))))]
+ p2-target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :venues :price))))]]
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:parameters [{:id "p1" :type :string/= :name "P1" :slug "p1"}
+ {:id "p2" :type :string/= :name "P2" :slug "p2"}]}
+ :model/Card c1 {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Card c2 {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/DashboardCard {dc1 :id} {:dashboard_id dash-id :card_id (:id c1)
+ :parameter_mappings [{:parameter_id "p1" :card_id (:id c1) :target p1-target}
+ {:parameter_id "p2" :card_id (:id c1) :target p2-target}]}
+ :model/DashboardCard {dc2 :id} {:dashboard_id dash-id :card_id (:id c2)
+ :parameter_mappings [{:parameter_id "p1" :card_id (:id c2) :target p1-target}
+ {:parameter_id "p2" :card_id (:id c2) :target p2-target}]}]
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" dash-id)
+ {:dashcards [(assoc (dashboard-card/retrieve-dashboard-card dc1) :id dc1
+ :parameter_mappings [{:parameter_id "p2" :card_id (:id c1) :target p2-target}])
+ (assoc (dashboard-card/retrieve-dashboard-card dc2) :id dc2
+ :parameter_mappings [{:parameter_id "p2" :card_id (:id c2) :target p2-target}])]
+ :tabs []})
+ (is (every? #(= 1 (count %)) (t2/select-fn-vec :parameter_mappings :model/DashboardCard :dashboard_id dash-id)))))))
+
+(deftest param-search-no-field-ids-test
+ (testing "GET .../params/:param-key/search/:query for field-ref-only (nested-native) params currently returns the same unfiltered set as /values"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card {native-id :id} (qp.test-util/card-with-source-metadata-for-query
+ (lib/native-query mp "select * from people"))
+ :model/Card {final-id :id} {:dataset_query (lib/query mp (lib.metadata/card mp native-id))}
+ :model/Dashboard {dashboard-id :id}
+ {:parameters [{:name "User Source" :slug "user_source" :id "_US_" :type :string/=}]}
+ :model/DashboardCard _ {:dashboard_id dashboard-id :card_id final-id
+ :parameter_mappings [{:card_id final-id :parameter_id "_US_"
+ :target [:dimension [:field "SOURCE" {:base-type :type/Text}]]}]}]
+ (is (= {:values [["Affiliate"] ["Facebook"] ["Google"] ["Organic"] ["Twitter"]] :has_more_values false}
+ (mt/user-http-request :rasta :get 200
+ (str "dashboard/" dashboard-id "/params/_US_/search/Goog"))))))))
+
+(deftest add-card-parameter-mapping-nested-name-ref-permissions-test
+ (testing "PUT /api/dashboard/:id with a mapping targeting a nested/native card's field-name ref is exempt from data-permission checks"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/Dashboard {dash-id :id} {}
+ :model/Card {native-id :id} {:dataset_query (lib/native-query mp "select * from people")}
+ :model/Card {final-id :id} {:dataset_query (lib/query mp (lib.metadata/card mp native-id))}]
+ (is (=? {:dashcards [{:card_id final-id}]}
+ (mt/user-http-request :rasta :put 200 (format "dashboard/%d" dash-id)
+ {:dashcards [{:id -1 :card_id final-id :row 0 :col 0 :size_x 4 :size_y 4
+ :parameter_mappings [{:card_id final-id :parameter_id "abc"
+ :target [:dimension [:field "SOURCE" {:base-type :type/Text}]]}]}]
+ :tabs []}))))))))
+
+(deftest number-static-list-mixed-shape-values-and-search-test
+ (mt/with-temp [:model/Dashboard {id :id}
+ {:parameters [{:name "Number" :slug "number" :id "_NUM_" :type :number/=
+ :values_source_type "static-list"
+ :values_source_config {:values [["10" "Ten"] ["20" "Twenty"] "30"]}}]}]
+ (testing "GET /api/dashboard/:id/params/:param-key/values handles a static-list source with mixed labeled/bare entries"
+ (is (= {:values [["10" "Ten"] ["20" "Twenty"] ["30"]] :has_more_values false}
+ (mt/user-http-request :rasta :get 200 (chain-filter-values-url id "_NUM_")))))
+ (testing "GET /api/dashboard/:id/params/:param-key/search/:query matches both labeled and unlabeled static-list entries"
+ (is (= {:values [["10" "Ten"] ["20" "Twenty"]] :has_more_values false}
+ (mt/user-http-request :rasta :get 200 (chain-filter-search-url id "_NUM_" "t")))))))
+
+(deftest numeric-card-source-values-and-search-test
+ (testing "GET /api/dashboard/:id/params/:param-key/values and /search/:query for a numeric card-source parameter"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card {source-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}
+ :model/Dashboard {id :id}
+ {:parameters [{:name "Number" :slug "number" :id "_NUM_" :type :number/<=
+ :values_source_type "card"
+ :values_source_config
+ {:card_id source-id
+ :value_field (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :orders :id))))}}]}]
+ (let [values (:values (mt/user-http-request :rasta :get 200 (format "dashboard/%d/params/_NUM_/values" id)))]
+ (is (seq values))
+ (is (every? #(= 1 (count %)) values)))
+ (let [values (:values (mt/user-http-request :rasta :get 200 (format "dashboard/%d/params/_NUM_/search/225" id)))]
+ (is (seq values))
+ (is (every? (fn [[v]] (str/includes? (str v) "225")) values)
+ "every result actually matches the search query")
+ (is (not-any? #{[5]} values)
+ "an unrelated id that doesn't contain the search query is excluded"))))))
+
+(deftest param-value-remapping-internal-remap-test
+ (testing "GET /api/dashboard/:id/params/:param-key/remapping works for human-readable-values (internal) remaps"
+ (chain-filter-test/with-human-readable-values-remapping!
+ (with-chain-filter-fixtures [{:keys [dashboard]}]
+ (is (= [40 "Japanese"]
+ (mt/user-http-request :rasta :get 200
+ (format "dashboard/%d/params/_CATEGORY_ID_/remapping?value=40" (:id dashboard)))))))))
+
+(deftest card-source-param-with-label-field-values-endpoint-test
+ (testing "GET /api/dashboard/:id/params/:key/values returns [value label] pairs for a card-source param with label_field"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card native-card (qp.test-util/card-with-source-metadata-for-query
+ (lib/native-query mp "select id, name from venues limit 5"))
+ :model/Dashboard dashboard
+ {:parameters [{:id "abc" :name "abc" :slug "abc" :type "category"
+ :values_source_type "card"
+ :values_source_config {:card_id (:id native-card)
+ :value_field [:field "ID" {:base-type :type/Integer}]
+ :label_field [:field "NAME" {:base-type :type/Text}]}}]}]
+ (let [{:keys [values]} (mt/user-http-request :rasta :get 200
+ (format "dashboard/%d/params/abc/values" (:id dashboard)))]
+ (is (seq values))
+ (is (every? (fn [[value label]] (and (int? value) (string? label))) values)))))))
+
+(deftest chain-filter-template-tags-search-test
+ (testing "GET /api/dashboard/:id/params/:param-key/search/:query works for a native template-tag dimension param"
+ (with-chain-filter-fixtures [{:keys [dashboard]}]
+ (mt/let-url [url (chain-filter-search-url dashboard "_name_" "am")]
+ (is (= {:values [["American"] ["Latin American"] ["Ramen"]] :has_more_values false}
+ (chain-filter-test/take-n-values 3 (mt/user-http-request :rasta :get 200 url))))))))
+
+(deftest can-filter-on-multi-database-params-test
+ (testing "GET /api/dashboard/:id/params/:param-key/values merges/dedupes results across databases (#68998)"
+ (let [orig-db-id (mt/id)
+ orig-category-field-id (mt/id :products :category)
+ mp-orig (lib.metadata.jvm/application-database-metadata-provider orig-db-id)
+ card-a-query (lib/query mp-orig (lib.metadata/table mp-orig (mt/id :products)))
+ card-a-target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp-orig orig-category-field-id)))]]
+ (mt/with-temp-copy-of-db
+ (let [other-db-id (mt/id)
+ other-category-field-id (mt/id :products :category)
+ mp-other (lib.metadata.jvm/application-database-metadata-provider other-db-id)
+ card-b-query (lib/query mp-other (lib.metadata/table mp-other (mt/id :products)))
+ card-b-target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp-other other-category-field-id)))]]
+ (mt/with-temp
+ [:model/Dashboard dashboard {:parameters [{:name "Category" :slug "category" :id "_CAT_" :type "category"}]}
+ :model/Card card-a {:database_id orig-db-id :dataset_query card-a-query}
+ :model/Card card-b {:database_id other-db-id :dataset_query card-b-query}
+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :card_id (:id card-a)
+ :parameter_mappings [{:parameter_id "_CAT_" :card_id (:id card-a) :target card-a-target}]}
+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :card_id (:id card-b)
+ :parameter_mappings [{:parameter_id "_CAT_" :card_id (:id card-b) :target card-b-target}]}]
+ (is (= #{"Doohickey" "Gadget" "Gizmo" "Widget"}
+ (into #{} (map first) (:values (mt/user-http-request :rasta :get 200
+ (chain-filter-values-url (:id dashboard) "_CAT_"))))))))))))
+
+(deftest ^:parallel legacy-location-city-parameter-search-test
+ (testing "GET /api/dashboard/:id/params/:param-key/search/:query works for the legacy location/city parameter type"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {:parameters [{:name "City" :slug "city" :id "_CITY_" :type "location/city"}]}
+ :model/Card {card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :people)))}
+ :model/DashboardCard {} {:dashboard_id dashboard-id :card_id card-id
+ :parameter_mappings [{:parameter_id "_CITY_" :card_id card-id
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :people :city))))]}]}]
+ (is (=? {:values [["Flagstaff"]]}
+ (mt/user-http-request :rasta :get 200 (chain-filter-search-url dashboard-id "_CITY_" "Flag"))))))))
+
+(deftest chain-filter-search-unions-values-across-multiple-mapped-fields-test
+ (testing "GET /api/dashboard/:id/params/:param-key/search/:query unions results across every mapped field, even with disjoint value domains"
+ (let [mp (mt/metadata-provider)
+ people-target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :people :name))))]
+ products-target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :products :category))))]]
+ (mt/with-temp [:model/Dashboard dashboard {:parameters [{:id "abc" :type :string/= :name "abc" :slug "abc"}]}
+ :model/Card people-card {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :people)))}
+ :model/Card products-card {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :products)))}
+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :card_id (:id people-card)
+ :parameter_mappings [{:parameter_id "abc" :card_id (:id people-card) :target people-target}]}
+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :card_id (:id products-card)
+ :parameter_mappings [{:parameter_id "abc" :card_id (:id products-card) :target products-target}]}]
+ (let [{:keys [values]} (mt/user-http-request :rasta :get 200
+ (format "dashboard/%d/params/abc/search/Ga" (:id dashboard)))]
+ (is (some #(= % ["Gadget"]) values)))))))
+
+(deftest stale-parameter-mapping-target-is-silently-ignored-test
+ (testing "a stale parameter_mappings target (from a query edit) is silently ignored, not erroring"
+ (let [mp (mt/metadata-provider)
+ cat-tag (-> (lib/native-query mp "select count(*) from products where {{cat}}")
+ (lib/with-template-tags {"cat" {:id "_CAT_TAG_" :name "cat" :display-name "Cat" :type :dimension
+ :dimension (lib/ref (lib.metadata/field mp (mt/id :products :category)))
+ :widget-type :string/=}}))]
+ (mt/with-temp [:model/Card card {:dataset_query cat-tag}
+ :model/Dashboard dashboard {:parameters [{:id "p" :type :string/= :name "p" :slug "p"}]}
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard) :card_id (:id card)
+ :parameter_mappings [{:parameter_id "p" :card_id (:id card)
+ :target [:dimension [:template-tag "cat"]]}]}]
+ (mt/user-http-request :rasta :put 200 (str "card/" (:id card))
+ {:dataset_query (lib/->legacy-MBQL (lib/native-query mp "select 1"))})
+ (is (= [[1]] (mt/rows (mt/user-http-request :rasta :post 202
+ (format "dashboard/%d/dashcard/%d/card/%d/query" (:id dashboard) (:id dashcard) (:id card))
+ {:parameters [{:id "p" :type :string/= :value ["Gadget"]}]}))))))))
+
+(deftest put-dashboard-does-not-clean-orphaned-parameter-mappings-test
+ (testing "PUT /api/dashboard/:id removing a parameter does not prune dashcard parameter_mappings that reference it (#17933)"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Dashboard dashboard {:parameters [{:id "p" :type :string/= :name "p" :slug "p"}]}
+ :model/Card card {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard) :card_id (:id card)
+ :parameter_mappings [{:parameter_id "p" :card_id (:id card)
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :orders :total))))]}]}]
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" (:id dashboard)) {:parameters []})
+ (is (seq (t2/select-one-fn :parameter_mappings :model/DashboardCard :id (:id dashcard)))
+ "backend does not clean up dashcard parameter_mappings that reference a removed parameter_id")))))
+
+(deftest values-endpoint-does-not-gate-by-operator-type-test
+ (testing "GET /api/dashboard/:id/params/:param-key/values has no operator-type gating"
+ (with-chain-filter-fixtures [{:keys [dashboard param-keys]}]
+ (mt/user-http-request :rasta :put 200 (str "dashboard/" (:id dashboard))
+ {:parameters (mapv (fn [p] (cond-> p (= (:id p) (:category-name param-keys)) (assoc :type :string/starts-with)))
+ (:parameters dashboard))})
+ (is (seq (:values (mt/user-http-request :rasta :get 200
+ (chain-filter-values-url (:id dashboard) (:category-name param-keys)))))))))
+
+(deftest temporal-unit-param-rejects-invalid-unit-in-allowlist-test
+ (testing "PUT /api/dashboard/:id rejects a temporal_units allow-list containing a non-unit string"
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}]
+ (mt/user-http-request :crowberto :put 400 (str "dashboard/" dashboard-id)
+ {:parameters [{:id "p" :type :temporal-unit :name "p" :slug "p" :temporal_units ["not-a-real-unit"]}]}))))
+
+(deftest temporal-unit-param-mapping-to-text-template-tag-not-rejected-test
+ (testing "PUT /api/dashboard/:id accepts a temporal-unit param mapped onto a non-dimension (text) template tag"
+ (let [mp (mt/metadata-provider)
+ native-q (-> (lib/native-query mp "select count(*) from products where category = {{cat}}")
+ (lib/with-template-tags {"cat" {:id "_CAT_TAG_" :name "cat" :display-name "Cat" :type :text}}))]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query native-q}
+ :model/Dashboard {dashboard-id :id} {:parameters [{:id "p" :type :temporal-unit :name "p" :slug "p"}]}
+ :model/DashboardCard {dashcard-id :id} {:dashboard_id dashboard-id :card_id card-id}]
+ (is (=? [{:parameter_id "p"}]
+ (:parameter_mappings
+ (first (:dashcards
+ (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" dashboard-id)
+ {:dashcards [{:id dashcard-id :card_id card-id :row 0 :col 0 :size_x 4 :size_y 4
+ :parameter_mappings [{:parameter_id "p" :card_id card-id
+ :target [:dimension [:template-tag "cat"]]}]}]
+ :tabs []}))))))))))
+
+(deftest dashboard-mixed-permission-dashcards-query-isolation-test
+ (testing "GET /api/dashboard/:id redacts an unreadable dashcard; querying it 403s while a sibling dashcard still succeeds"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Collection {accessible-coll-id :id} {}
+ :model/Collection {restricted-coll-id :id} {}
+ :model/Card {ok-card-id :id} {:collection_id accessible-coll-id
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Card {bad-card-id :id} {:collection_id restricted-coll-id
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Dashboard {dashboard-id :id} {:collection_id accessible-coll-id}
+ :model/DashboardCard {ok-dc-id :id} {:dashboard_id dashboard-id :card_id ok-card-id}
+ :model/DashboardCard {bad-dc-id :id} {:dashboard_id dashboard-id :card_id bad-card-id}]
+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) accessible-coll-id)
+ (let [dashcards (:dashcards (mt/user-http-request :rasta :get 200 (str "dashboard/" dashboard-id)))
+ bad-dc (m/find-first #(= (:id %) bad-dc-id) dashcards)]
+ (is (=? {:id bad-card-id} (:card bad-dc)))
+ (is (not (contains? (:card bad-dc) :dataset_query))))
+ (mt/user-http-request :rasta :post 202 (dashboard-card-query-url dashboard-id ok-card-id ok-dc-id))
+ (mt/user-http-request :rasta :post 403 (dashboard-card-query-url dashboard-id bad-card-id bad-dc-id)))))))
+
+(deftest update-dashboard-creates-revision-test
+ (testing "PUT /api/dashboard/:id updating name/description creates a Revision row"
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {:name "Test Dashboard"}]
+ (with-dashboards-in-writeable-collection! [dashboard-id]
+ (let [before (t2/count :model/Revision :model_id dashboard-id :model "Dashboard")]
+ (mt/user-http-request :rasta :put 200 (str "dashboard/" dashboard-id) {:name "Updated Name"})
+ (is (= (inc before) (t2/count :model/Revision :model_id dashboard-id :model "Dashboard"))))))))
+
+(deftest archive-unarchive-round-trip-preserves-collection-id-test
+ (testing "PUT /api/dashboard/:id archived true/false round trip preserves the real collection_id"
+ (mt/with-temp [:model/Collection {collection-id :id} {}
+ :model/Dashboard {dashboard-id :id} {:collection_id collection-id}]
+ (is (=? {:archived true :archived_directly true}
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" dashboard-id) {:archived true})))
+ (is (= collection-id (t2/select-one-fn :collection_id :model/Dashboard :id dashboard-id)))
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" dashboard-id) {:archived false})
+ (is (=? {:archived false :collection_id collection-id}
+ (t2/select-one :model/Dashboard :id dashboard-id))))))
+
+(deftest copy-dashboard-permission-model-test
+ (testing "POST /api/dashboard/:id/copy needs only read-on-source + create-on-destination"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {src-id :id} {}
+ :model/Dashboard {dash-id :id} {:collection_id src-id}
+ :model/Collection {dest-id :id} {}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) src-id)
+ (testing "read-only on source + create on personal collection succeeds"
+ (let [personal-id (u/the-id (collection/user->personal-collection (mt/user->id :rasta)))]
+ (is (= personal-id
+ (:collection_id (mt/user-http-request :rasta :post 200 (str "dashboard/" dash-id "/copy")
+ {:collection_id personal-id}))))))
+ (testing "no create perms on destination collection is rejected"
+ (mt/user-http-request :rasta :post 403 (str "dashboard/" dash-id "/copy") {:collection_id dest-id}))))))
+
+(deftest dq-not-archived-while-other-dashcard-remains-test
+ (testing "PUT /api/dashboard/:id removing one of two dashcards for the same Dashboard Question does not archive it"
+ (mt/with-temp [:model/Dashboard d {}
+ :model/Card dq {:dashboard_id (:id d)}
+ :model/DashboardCard _dc1 {:dashboard_id (:id d) :card_id (:id dq)}
+ :model/DashboardCard dc2 {:dashboard_id (:id d) :card_id (:id dq)}]
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" (:id d)) {:dashcards [dc2] :tabs []})
+ (is (false? (t2/select-one-fn :archived :model/Card (:id dq))))
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" (:id d)) {:dashcards [] :tabs []})
+ (is (true? (t2/select-one-fn :archived :model/Card (:id dq)))))))
+
+(deftest removing-one-dq-does-not-affect-sibling-dq-test
+ (testing "PUT /api/dashboard/:id removing one Dashboard Question's dashcard leaves an unrelated Dashboard Question untouched"
+ (mt/with-temp [:model/Dashboard d {}
+ :model/Card dq-a {:dashboard_id (:id d)} :model/Card dq-b {:dashboard_id (:id d)}
+ :model/DashboardCard _dc-a {:dashboard_id (:id d) :card_id (:id dq-a)}
+ :model/DashboardCard dc-b {:dashboard_id (:id d) :card_id (:id dq-b)}]
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" (:id d)) {:dashcards [dc-b] :tabs []})
+ (is (true? (t2/select-one-fn :archived :model/Card (:id dq-a))))
+ (is (false? (t2/select-one-fn :archived :model/Card (:id dq-b)))))))
+
+(deftest create-dashboard-blank-name-test
+ (testing "POST /api/dashboard with a whitespace-only name is rejected (#63176)"
+ (is (contains? (:errors (mt/user-http-request :rasta :post 400 "dashboard" {:name " "}))
+ :name))))
+
+(deftest move-dashcard-between-tabs-without-card-read-perms-test
+ (testing "PUT /api/dashboard/:id moving a dashcard between tabs needs only dashboard write, not card read"
+ (mt/with-temp [:model/Collection {no-access-id :id} {}
+ :model/Card {card-id :id} {:collection_id no-access-id}
+ :model/Dashboard {dash-id :id} {}
+ :model/DashboardTab {t1-id :id} {:dashboard_id dash-id :name "Tab 1" :position 0}
+ :model/DashboardTab {t2-id :id} {:dashboard_id dash-id :name "Tab 2" :position 1}
+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id :dashboard_tab_id t1-id}]
+ (with-dashboards-in-writeable-collection! [dash-id]
+ (is (=? [{:dashboard_tab_id t2-id}]
+ (:dashcards
+ (mt/user-http-request :rasta :put 200 (str "dashboard/" dash-id)
+ {:tabs [{:id t1-id :name "Tab 1"} {:id t2-id :name "Tab 2"}]
+ :dashcards [{:id dc-id :dashboard_tab_id t2-id :card_id card-id :row 0 :col 0 :size_x 4 :size_y 4}]}))))))))
+
+(deftest add-text-tag-parameter-mapping-test
+ (testing "PUT /api/dashboard/:id creates a virtual dashcard with a :text-tag parameter mapping (#11927)"
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:parameters [{:id "_a" :slug "a" :name "a" :type :string/contains}]}]
+ (is (=? [{:parameter_mappings [{:target ["text-tag" "foo"]}]}]
+ (:dashcards
+ (mt/user-http-request :rasta :put 200 (str "dashboard/" dash-id)
+ {:tabs [] :dashcards [{:id -1 :row 0 :col 0 :size_x 4 :size_y 4 :card_id nil
+ :visualization_settings {:virtual_card {:display "text"} :text "{{foo}}"}
+ :parameter_mappings [{:parameter_id "_a" :target [:text-tag "foo"]}]}]})))))))
+
+(deftest update-text-tag-mapping-shared-across-dashcards-test
+ (testing "PUT /api/dashboard/:id updates an existing :text-tag mapping shared by two virtual dashcards"
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:parameters [{:id "_a" :slug "a" :name "a" :type :string/contains}]}]
+ (let [mk (fn [id] {:id id :row 0 :col 0 :size_x 4 :size_y 4 :card_id nil
+ :visualization_settings {:virtual_card {:display "text"} :text "{{foo}}"}
+ :parameter_mappings [{:parameter_id "_a" :target [:text-tag "foo"]}]})
+ resp (mt/user-http-request :rasta :put 200 (str "dashboard/" dash-id) {:tabs [] :dashcards [(mk -1) (mk -2)]})
+ updated (mt/user-http-request :rasta :put 200 (str "dashboard/" dash-id)
+ {:tabs [] :dashcards (mapv #(assoc % :parameter_mappings [{:parameter_id "_a" :target [:text-tag "bar"]}])
+ (:dashcards resp))})]
+ (is (every? #(= [{:parameter_id "_a" :target ["text-tag" "bar"]}] (:parameter_mappings %))
+ (:dashcards updated)))))))
+
+(deftest update-cards-parameter-mapping-joined-field-test
+ (testing "PUT /api/dashboard/:id persists parameter_mappings targeting a joined (source-field) column"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Dashboard {dash-id :id} {}
+ :model/Card {card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}
+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id}]
+ (let [target [:dimension (implicit-fk-column-ref mp :orders (mt/id :products :category))]]
+ (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" dash-id)
+ {:dashcards [{:id dc-id :card_id card-id :size_x 4 :size_y 4 :row 0 :col 0
+ :parameter_mappings [{:parameter_id "abc" :card_id card-id :target target}]}]
+ :tabs []})
+ (is (=? [{:target target}]
+ (t2/select-one-fn :parameter_mappings :model/DashboardCard :id dc-id))))))))
+
+(deftest swap-dashcard-card-id-requires-no-card-permission-test
+ (testing "PUT /api/dashboard/:id swapping a dashcard's card_id needs no data/read perms on the new card"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Dashboard {dash-id :id} {:collection_id coll-id}
+ :model/Card {c1-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Card {c2-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id c1-id}]
+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) coll-id)
+ (mt/with-no-data-perms-for-all-users!
+ (is (=? [{:card_id c2-id}]
+ (:dashcards (mt/user-http-request :rasta :put 200 (format "dashboard/%d" dash-id)
+ {:dashcards [{:id dc-id :card_id c2-id :row 0 :col 0 :size_x 4 :size_y 4}]
+ :tabs []}))))))))))
+
+(deftest update-card-id-preserves-mismatched-stale-parameter-mappings-test
+ (testing "PUT /api/dashboard/:id changing a dashcard's card_id does not validate/prune stale parameter_mappings"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Dashboard {dash-id :id} {}
+ :model/Card {c1-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/Card {c2-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :checkins)))}
+ :model/DashboardCard {dc-id :id}
+ {:dashboard_id dash-id :card_id c1-id
+ :parameter_mappings [{:parameter_id "abc"
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :venues :category_id))))]}]}]
+ (let [stale [{:parameter_id "abc"
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :venues :category_id))))]}]]
+ (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" dash-id)
+ {:dashcards [{:id dc-id :card_id c2-id :parameter_mappings stale :row 0 :col 0 :size_x 4 :size_y 4}] :tabs []})
+ (is (= stale (t2/select-one-fn :parameter_mappings :model/DashboardCard :id dc-id))))))))
+
+(deftest duplicate-dashcard-same-card-and-mappings-test
+ (testing "PUT /api/dashboard/:id allows two dashcards sharing card_id and identical parameter_mappings"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:parameters [{:id "cat" :name "Category" :type :string/= :slug "cat"}]}
+ :model/Card {card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/DashboardCard {dc-id :id}
+ {:dashboard_id dash-id :card_id card-id
+ :parameter_mappings [{:parameter_id "cat" :card_id card-id
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :venues :category_id))))]}]}]
+ (let [orig (select-keys (t2/select-one :model/DashboardCard :id dc-id) [:id :card_id :row :col :size_x :size_y :parameter_mappings])
+ resp (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" dash-id)
+ {:dashcards [orig (-> orig (dissoc :id) (assoc :id -1 :row 10))] :tabs []})]
+ (is (= 2 (count (:dashcards resp)))))))))
+
+(deftest duplicate-tab-with-mapped-dashcard-test
+ (testing "PUT /api/dashboard/:id resolves a new tab (negative id) together with a new mapped dashcard in one request"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:parameters [{:id "cat" :name "Category" :type :string/= :slug "cat"}]}
+ :model/Card {card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}
+ :model/DashboardTab {tab-id :id} {:dashboard_id dash-id :name "Tab 1" :position 0}]
+ (let [resp (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" dash-id)
+ {:tabs [{:id tab-id :name "Tab 1"} {:id -1 :name "Tab 1 - Duplicate"}]
+ :dashcards [{:id -1 :dashboard_tab_id -1 :card_id card-id :row 0 :col 0 :size_x 4 :size_y 4
+ :parameter_mappings [{:parameter_id "cat" :card_id card-id
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref (lib.metadata/field mp (mt/id :venues :category_id))))]}]}]})]
+ (is (seq (-> resp :dashcards first :parameter_mappings))))))))
+
+(deftest visualizer-dashcard-series-and-settings-round-trip-test
+ (testing "PUT /api/dashboard/:id persists a new DashboardCardSeries and visualizer columnValuesMapping blob together"
+ (mt/with-temp [:model/Dashboard {d-id :id} {}
+ :model/Card {c1-id :id} {} :model/Card {c2-id :id} {}
+ :model/DashboardCard {dc-id :id} {:dashboard_id d-id :card_id c1-id}]
+ (let [resp (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" d-id)
+ {:dashcards [{:id dc-id :card_id c1-id :series [{:id c2-id}]
+ :visualization_settings {:visualization {:columnValuesMapping {:COLUMN_1 [{:sourceId (str "card:" c2-id)}]}
+ :settings {}}}
+ :row 0 :col 0 :size_x 4 :size_y 4}]
+ :tabs []})]
+ (is (=? [{:id c2-id}] (-> resp :dashcards first :series)))))))
+
+(deftest visualizer-multi-source-entity-id-resolution-test
+ (testing "PUT /api/dashboard/:id resolves >2 dataset columnValuesMapping entity ids on the subsequent GET"
+ (mt/with-temp [:model/Dashboard {d-id :id} {}
+ :model/Card {a-id :id} {} :model/Card b {} :model/Card c {}]
+ (let [resp (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" d-id)
+ {:dashcards [{:id -1 :card_id a-id :row 0 :col 0 :size_x 4 :size_y 4
+ :visualization_settings
+ {:visualization {:columnValuesMapping
+ {:COLUMN_1 [{:sourceId (str "card:" (:entity_id b))}
+ {:sourceId (str "card:" (:entity_id c))}]}}}}]
+ :tabs []})]
+ (is (=? [{:sourceId (str "card:" (:id b))} {:sourceId (str "card:" (:id c))}]
+ (get-in (first (:dashcards resp)) [:visualization_settings :visualization :columnValuesMapping :COLUMN_1])))))))
+
+(deftest cant-archive-dashboard-without-collection-write-perms-test
+ (testing "PUT /api/dashboard/:id {:archived true} requires collection write perms"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}]
+ (mt/user-http-request :rasta :put 403 (str "dashboard/" dashboard-id) {:archived true})))))
+
+(deftest move-archived-dashboard-to-collection-unarchives-test
+ (testing "PUT /api/dashboard/:id moving an archived dashboard into a regular collection unarchives it"
+ (mt/with-temp [:model/Collection {collection-id :id} {}
+ :model/Dashboard {dashboard-id :id} {:archived true}]
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" dashboard-id)
+ {:collection_id collection-id :archived false})
+ (is (=? {:archived false :collection_id collection-id}
+ (t2/select-one :model/Dashboard :id dashboard-id))))))
+
+(deftest two-temporal-unit-params-same-field-different-breakouts-test
+ (testing "dashboard/public/embed persistence for two parameter_mappings on the same field, disambiguated by :temporal-unit (#46536, #46776)"
+ (let [mp (mt/metadata-provider)
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ year-ref (lib.convert/->legacy-MBQL (lib/ref (lib/with-temporal-bucket created-at :year)))
+ month-ref (lib.convert/->legacy-MBQL (lib/ref (lib/with-temporal-bucket created-at :month)))
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created-at :year))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query query}
+ :model/Dashboard {dashboard-id :id}
+ {:parameters [{:name "Unit1" :slug "unit1" :id "u1" :type :temporal-unit}
+ {:name "Unit2" :slug "unit2" :id "u2" :type :temporal-unit}]}
+ :model/DashboardCard {dashcard-id :id}
+ {:card_id card-id :dashboard_id dashboard-id
+ :parameter_mappings [{:parameter_id "u1" :card_id card-id :target [:dimension year-ref]}
+ {:parameter_id "u2" :card_id card-id :target [:dimension month-ref]}]}]
+ (let [cols (->> (mt/user-http-request :crowberto :post 202
+ (format "dashboard/%d/dashcard/%d/card/%d/query" dashboard-id dashcard-id card-id)
+ {:parameters [{:id "u1" :type "temporal-unit" :value "quarter"}
+ {:id "u2" :type "temporal-unit" :value "week"}]})
+ :data :cols
+ (map :display_name))]
+ (is (some #(= % "Created At: Quarter") cols))
+ (is (some #(= % "Created At: Week") cols)))))))
+
+(deftest fetch-dashboard-with-nested-source-card-in-restricted-collection-test
+ (testing "GET /api/dashboard/:id does not require collection-read on a card's *nested* source reference"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Collection {readable-coll :id} {}
+ :model/Collection {restricted-coll :id} {}
+ :model/Card {model-id :id} {:type :model :collection_id restricted-coll
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}
+ :model/Card {metric-id :id} {:type :metric :collection_id readable-coll
+ :dataset_query (-> (lib/query mp (lib.metadata/card mp model-id))
+ (lib/aggregate (lib/count)))}
+ :model/Dashboard {dash-id :id} {:collection_id readable-coll}
+ :model/DashboardCard _ {:dashboard_id dash-id :card_id metric-id}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) readable-coll)
+ (is (=? {:dashcards [{:card {:id metric-id}}]}
+ (mt/user-http-request :rasta :get 200 (format "dashboard/%d" dash-id)))))))))
+
+(deftest dashcard-includes-card-collection-authority-level-test
+ (testing "GET /api/dashboard/:id dashcards carry collection_authority_level from their own card's collection"
+ (mt/with-temp [:model/Collection {official-coll :id} {:authority_level "official"}
+ :model/Dashboard {dashboard-id :id} {}
+ :model/Card {card-id :id} {:collection_id official-coll}
+ :model/DashboardCard _ {:dashboard_id dashboard-id :card_id card-id}]
+ (is (= ["official"]
+ (map :collection_authority_level
+ (:dashcards (mt/user-http-request :crowberto :get 200 (str "dashboard/" dashboard-id)))))))))
+
+(deftest dashboard-card-query-export-format-no-self-service-test
+ (testing "metabase#20868: CSV export works for a GUI card with a dimension param and no create-queries perms"
+ (mt/test-helpers-set-global-values!
+ (mt/with-temp-copy-of-db
+ (with-chain-filter-fixtures [{{dashboard-id :id} :dashboard {card-id :id} :card {dashcard-id :id} :dashcard}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/create-queries :no)
+ (is (some? (mt/user-real-request :rasta :post 200
+ (format "%s/csv" (dashboard-card-query-url dashboard-id card-id dashcard-id))
+ {:request-options {:as :byte-array}}
+ {:parameters [{:id "_PRICE_" :value 4}]})))))))))
+
+(deftest non-admin-can-read-existing-public-dashboard-link-test
+ (testing "GET /api/dashboard/:id exposes public_uuid to non-admin viewers for an already-shared dashboard"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Dashboard dashboard {:public_uuid (str (random-uuid))
+ :made_public_by_id (mt/user->id :crowberto)}]
+ (with-dashboards-in-readable-collection! [dashboard]
+ (is (= (str (:public_uuid dashboard))
+ (:public_uuid (mt/user-http-request :rasta :get 200 (str "dashboard/" (u/the-id dashboard)))))))))))
+
+(deftest update-embedding-type-to-guest-embed-and-static-legacy-test
+ (testing "PUT /api/dashboard/:id sets/echoes/persists embedding_type for guest-embed and static-legacy"
+ (mt/with-temporary-setting-values [enable-embedding-static true]
+ (mt/with-temp [:model/Dashboard dashboard {}]
+ (doseq [embedding-type ["guest-embed" "static-legacy"]]
+ (let [resp (mt/user-http-request :crowberto :put 200 (str "dashboard/" (u/the-id dashboard))
+ {:enable_embedding true :embedding_type embedding-type})]
+ (is (=? {:enable_embedding true :embedding_type embedding-type} resp))
+ (is (= embedding-type (t2/select-one-fn :embedding_type :model/Dashboard :id (u/the-id dashboard)))))))
+ (testing "embedding_params persists alongside embedding_type guest-embed (EMB-1884)"
+ (mt/with-temp [:model/Dashboard dashboard {}]
+ (let [resp (mt/user-http-request :crowberto :put 200 (str "dashboard/" (u/the-id dashboard))
+ {:enable_embedding true :embedding_type "guest-embed"
+ :embedding_params {:downloads "enabled"}})]
+ (is (=? {:embedding_type "guest-embed" :embedding_params {:downloads "enabled"}} resp))))))))
+
+(deftest dashcard-action-execution-additional-types-test
+ (testing "implicit actions correctly coerce/persist additional column types, including on MySQL"
+ (mt/test-drivers (mt/normal-drivers-with-feature :actions)
+ (let [types [{:field-name "adate" :base-type :type/Date ::good "2020-02-02"}
+ {:field-name "adecimal" :base-type :type/Decimal ::good 3.14}
+ {:field-name "abigint" :base-type :type/BigInteger ::good 9000000000}]]
+ (mt/with-temp-test-data
+ [["types"
+ (map #(dissoc % ::good) types)
+ [[nil nil nil]]]]
+ (mt/with-actions-enabled
+ (mt/with-actions [{card-id :id} {:type :model :dataset_query (mt/mbql-query types)}
+ {:keys [action-id]} {:type :implicit :kind "row/create"}]
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}
+ :model/DashboardCard {dashcard-id :id} {:dashboard_id dashboard-id
+ :action_id action-id
+ :card_id card-id}]
+ (doseq [{:keys [field-name base-type] value ::good} types]
+ (testing (str "Attempting to implicitly insert " field-name)
+ (let [created-row (-> (mt/user-http-request :crowberto :post 200
+ (format "dashboard/%s/dashcard/%s/execute" dashboard-id dashcard-id)
+ {:parameters {field-name value}})
+ :created-row
+ (update-keys (comp keyword u/lower-case-en name)))
+ actual (get created-row (keyword field-name))]
+ (is (condp = base-type
+ ;; some drivers return the date with a (midnight) time component attached, so only
+ ;; compare the date portion
+ :type/Date (str/starts-with? (str actual) value)
+ ;; this DECIMAL column has no explicit scale, so per the SQL standard it's
+ ;; driver-dependent whether it's cast/rounded to a whole number (scale 0, e.g.
+ ;; MySQL) or persisted at full precision (e.g. Postgres NUMERIC) -- accept either
+ ;; driver-faithful outcome
+ :type/Decimal (or (== (Math/round (double value)) actual)
+ (< (Math/abs (- (double value) (double actual))) 1e-6))
+ (== value actual))
+ (format "%s was persisted with the correct coerced value (expected %s, got %s)"
+ field-name (pr-str value) (pr-str actual))))))))))))))
+
+(deftest dashcard-query-action-optional-hidden-param-test
+ (testing "a query action's optional/hidden template-tag parameter can be omitted, and is not a valid explicit destination"
+ (mt/test-drivers (mt/normal-drivers-with-feature :actions)
+ (mt/with-actions-test-data-and-actions-enabled
+ (let [mp (mt/metadata-provider)
+ dataset-query (-> (lib/native-query mp "UPDATE categories SET name = {{name}} WHERE id = {{id}} [[AND name = {{old_name}}]]")
+ (lib/with-template-tags
+ {"id" {:name "id" :display-name "ID" :type :number :required true}
+ "name" {:name "name" :display-name "Name" :type :text :required true}
+ "old_name" {:name "old_name" :display-name "Old Name" :type :text :required false}}))]
+ (mt/with-actions [{:keys [action-id model-id]}
+ {:dataset_query dataset-query
+ :parameters [{:id "id" :slug "id" :type "number" :target [:variable [:template-tag "id"]]}
+ {:id "name" :slug "name" :type "text" :target [:variable [:template-tag "name"]]}
+ {:id "old_name" :slug "old_name" :type "text" :required false :target [:variable [:template-tag "old_name"]]}]
+ :visualization_settings {:fields {"old_name" {:id "old_name" :hidden true :required false}}}}]
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}
+ :model/DashboardCard {dashcard-id :id} {:dashboard_id dashboard-id
+ :action_id action-id
+ :card_id model-id}]
+ (let [execute-path (format "dashboard/%s/dashcard/%s/execute" dashboard-id dashcard-id)]
+ (testing "runs successfully when the hidden/optional parameter is omitted"
+ (is (partial= {:rows-affected 1}
+ (mt/user-http-request :crowberto :post 200 execute-path
+ {:parameters {"id" 1 "name" "Store"}}))))
+ (testing "explicitly supplying the hidden parameter is rejected as an unrecognized destination"
+ (is (=? {:message #"(?i).*No destination parameter found.*"}
+ (mt/user-http-request :crowberto :post 400 execute-path
+ {:parameters {"id" 1 "name" "Store" "old_name" "Shop"}}))))))))))))
diff --git a/test/metabase/data_studio/api/table_test.clj b/test/metabase/data_studio/api/table_test.clj
index 3468caa7459..0f2096024cf 100644
--- a/test/metabase/data_studio/api/table_test.clj
+++ b/test/metabase/data_studio/api/table_test.clj
@@ -41,6 +41,15 @@
:visibility_type "hidden"
:data_layer "hidden"})))))
+(deftest bulk-edit-does-not-allow-changing-data-source-away-from-transform-test
+ (testing "POST /api/data-studio/table/edit cannot change a transform-created table's data_source"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {table-id :id} {:db_id db-id :data_source :metabase-transform}]
+ (mt/user-http-request :crowberto :post 400 "data-studio/table/edit"
+ {:table_ids [table-id]
+ :data_source "ingested"})
+ (is (= :metabase-transform (t2/select-one-fn :data_source :model/Table :id table-id))))))
+
(deftest data-analyst-can-access-endpoints-test
(testing "Data analysts (members of Data Analysts group) can access data studio endpoints"
(let [data-analyst-group-id (:id (perms-group/data-analyst))]
@@ -426,12 +435,12 @@
;; order_items.order_id remaps to orders.name
;; orders.customer_id remaps to customers.name
(mt/with-temp [:model/Database {db-id :id} {}
- ;; Customers table
- :model/Table {customers-id :id} {:db_id db-id :name "customers" :schema "PUBLIC"
- :is_published false}
- :model/Field _ {:table_id customers-id :name "id"
+ ;; Purchasers table
+ :model/Table {purchasers-id :id} {:db_id db-id :name "purchasers" :schema "PUBLIC"
+ :is_published false}
+ :model/Field _ {:table_id purchasers-id :name "id"
:semantic_type :type/PK :base_type :type/Integer}
- :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :model/Field {cust-name-f :id} {:table_id purchasers-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
;; Orders table
:model/Table {orders-id :id} {:db_id db-id :name "orders" :schema "PUBLIC"
@@ -440,8 +449,8 @@
:semantic_type :type/PK :base_type :type/Integer}
:model/Field {order-name-f :id} {:table_id orders-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
- :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
- :semantic_type :type/FK :base_type :type/Integer}
+ :model/Field {purchaser-fk :id} {:table_id orders-id :name "purchaser_id"
+ :semantic_type :type/FK :base_type :type/Integer}
;; Order items table
:model/Table {items-id :id} {:db_id db-id :name "order_items" :schema "PUBLIC"
:is_published false}
@@ -450,7 +459,7 @@
:model/Field {order-fk :id} {:table_id items-id :name "order_id"
:semantic_type :type/FK :base_type :type/Integer}
;; Dimensions for FK remapping
- :model/Dimension _ {:field_id customer-fk
+ :model/Dimension _ {:field_id purchaser-fk
:human_readable_field_id cust-name-f
:type :external}
:model/Dimension _ {:field_id order-fk
@@ -466,7 +475,7 @@
:schema "PUBLIC"}
:unpublished_upstream_tables (mt/malli=? [:sequential {:min 2 :max 2} :map])}
response))
- (is (= #{orders-id customers-id}
+ (is (= #{orders-id purchasers-id}
(set (map :id (:unpublished_upstream_tables response)))))
;; Verify upstream tables have all required fields
(doseq [table (:unpublished_upstream_tables response)]
@@ -478,12 +487,12 @@
;; Same chain: order_items -> orders -> customers
;; If we unpublish customers, we need to unpublish orders and order_items too
(mt/with-temp [:model/Database {db-id :id} {}
- ;; Customers table (published)
- :model/Table {customers-id :id} {:db_id db-id :name "customers" :schema "PUBLIC"
- :is_published true}
- :model/Field _ {:table_id customers-id :name "id"
+ ;; Purchasers table (published)
+ :model/Table {purchasers-id :id} {:db_id db-id :name "purchasers" :schema "PUBLIC"
+ :is_published true}
+ :model/Field _ {:table_id purchasers-id :name "id"
:semantic_type :type/PK :base_type :type/Integer}
- :model/Field {cust-name-f :id} {:table_id customers-id :name "name"
+ :model/Field {cust-name-f :id} {:table_id purchasers-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
;; Orders table (published)
:model/Table {orders-id :id} {:db_id db-id :name "orders" :schema "PUBLIC"
@@ -492,8 +501,8 @@
:semantic_type :type/PK :base_type :type/Integer}
:model/Field {order-name-f :id} {:table_id orders-id :name "name"
:semantic_type :type/Name :base_type :type/Text}
- :model/Field {customer-fk :id} {:table_id orders-id :name "customer_id"
- :semantic_type :type/FK :base_type :type/Integer}
+ :model/Field {purchaser-fk :id} {:table_id orders-id :name "purchaser_id"
+ :semantic_type :type/FK :base_type :type/Integer}
;; Order items table (published)
:model/Table {items-id :id} {:db_id db-id :name "order_items" :schema "PUBLIC"
:is_published true}
@@ -502,7 +511,7 @@
:model/Field {order-fk :id} {:table_id items-id :name "order_id"
:semantic_type :type/FK :base_type :type/Integer}
;; Dimensions for FK remapping
- :model/Dimension _ {:field_id customer-fk
+ :model/Dimension _ {:field_id purchaser-fk
:human_readable_field_id cust-name-f
:type :external}
:model/Dimension _ {:field_id order-fk
@@ -510,11 +519,11 @@
:type :external}]
(testing "selecting customers returns orders and order_items as downstream (recursive)"
(let [response (mt/user-http-request :crowberto :post 200 "data-studio/table/selection"
- {:table_ids [customers-id]})]
- (is (=? {:selected_table {:id customers-id
+ {:table_ids [purchasers-id]})]
+ (is (=? {:selected_table {:id purchasers-id
:db_id db-id
- :name "customers"
- :display_name "Customers"
+ :name "purchasers"
+ :display_name "Purchasers"
:schema "PUBLIC"}
:published_downstream_tables (mt/malli=? [:sequential {:min 2 :max 2} :map])}
response))
diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.clj
index 6bb3d63ff87..c9db2cea410 100644
--- a/test/metabase/driver/postgres_test.clj
+++ b/test/metabase/driver/postgres_test.clj
@@ -32,6 +32,7 @@
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.sql.query-processor-test-util :as sql.qp-test-util]
[metabase.driver.sql.util :as sql.u]
+ [metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
[metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
@@ -1009,6 +1010,37 @@
:data
(select-keys [:rows :native_form]))))))))))
+(deftest enum-field-filter-test
+ (mt/test-driver :postgres
+ (do-with-enums-db!
+ (fn [db]
+ (let [mp (lib.metadata.jvm/application-database-metadata-provider (u/the-id db))
+ table-id (t2/select-one-pk :model/Table :db_id (u/the-id db) :name "birds")
+ type-field-id (t2/select-one-pk :model/Field :table_id table-id :name "type")
+ type-field (lib.metadata/field mp type-field-id)]
+ (testing "an MBQL string/= param on a postgres enum column filters correctly (#40396)"
+ (is (= [["Rasta" "good bird" "sad bird" "toucan"]]
+ (mt/rows
+ (qp/process-query
+ (assoc (lib/query mp (lib.metadata/table mp table-id))
+ :parameters [{:type :string/=
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref type-field))]
+ :value ["toucan"]}]))))))
+ (testing "a native field filter over a postgres enum column filters correctly (#63537)"
+ (is (= [["Rasta" "good bird" "sad bird" "toucan"]]
+ (mt/rows
+ (qp/process-query
+ (assoc (-> (lib/native-query mp "SELECT * FROM birds WHERE {{type}}")
+ (lib/with-template-tags
+ {"type" {:name "type"
+ :display-name "Type"
+ :type :dimension
+ :dimension (lib/ref type-field)
+ :widget-type :string/=}}))
+ :parameters [{:type :string/=
+ :target [:dimension [:template-tag "type"]]
+ :value ["toucan"]}])))))))))))
+
(deftest enums-test-3
(mt/test-driver :postgres
(do-with-enums-db!
diff --git a/test/metabase/driver/sql/parameters/substitute_test.clj b/test/metabase/driver/sql/parameters/substitute_test.clj
index 258b9b01527..d867c22b48c 100644
--- a/test/metabase/driver/sql/parameters/substitute_test.clj
+++ b/test/metabase/driver/sql/parameters/substitute_test.clj
@@ -10,6 +10,7 @@
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.legacy-mbql.normalize :as mbql.normalize]
[metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]
[metabase.query-processor.compile :as qp.compile]
@@ -514,28 +515,44 @@
;;; ------------------------------------------- expansion tests: variables -------------------------------------------
(mu/defn- expand**
- "Expand parameters inside a top-level native `query`. Not recursive."
- [{:keys [parameters], :as query} :- [:map
- [:native [:map
- [:query some?]]]]]
- (driver/with-driver :h2
- (let [mp meta/metadata-provider]
- (-> (lib/query
- mp
- (merge {:database (meta/id)
- :type :native}
- query))
- (lib/update-query-stage 0 (fn [stage]
- (-> stage
- (update :parameters concat parameters)
- (->> (qp.native/expand-stage mp)))))
- lib/->legacy-MBQL))))
-
-(defn- expand* [query]
- (-> (expand** (mbql.normalize/normalize query))
- :native
- (select-keys [:query :params :template-tags])
- (update :params vec)))
+ "Expand parameters inside a top-level native `query`. Not recursive. Expands against `meta/metadata-provider` unless
+ an explicit metadata provider `mp` is supplied (handy for overriding field metadata)."
+ ([query]
+ (expand** meta/metadata-provider query))
+ ([mp
+ {:keys [parameters], :as query} :- [:or
+ [:map
+ [:lib/type [:= :mbql/query]]]
+ [:map
+ [:native [:map
+ [:query some?]]]]]]
+ (driver/with-driver :h2
+ (-> (if (:lib/type query)
+ (lib/query mp (dissoc query :parameters))
+ (lib/query
+ mp
+ (merge {:database (meta/id)
+ :type :native}
+ query)))
+ (lib/update-query-stage 0 (fn [stage]
+ (-> stage
+ (update :parameters concat parameters)
+ (->> (qp.native/expand-stage mp)))))
+ lib/->legacy-MBQL))))
+
+(defn- expand*
+ "Expand parameters inside native `query`, returning the resulting native query map. Expands against
+ `meta/metadata-provider` unless an explicit metadata provider `mp` is supplied (handy for overriding field
+ metadata)."
+ ([query]
+ (expand* meta/metadata-provider query))
+ ([mp query]
+ (-> (expand** mp (if (:lib/type query)
+ query
+ (mbql.normalize/normalize query)))
+ :native
+ (select-keys [:query :params :template-tags])
+ (update :params vec))))
(deftest ^:parallel expand-variables-test
;; unspecified optional param
@@ -1217,6 +1234,41 @@
:default "2017-11-14"
:widget-type :date/all-options}}}})))))
+(deftest ^:parallel field-filter-date-broken-semantic-type-test
+ (testing "a date field filter over a temporal field whose semantic_type was forced non-temporal still parses the date value (#58061)"
+ (mt/with-clock (t/mock-clock #t "2016-06-07T12:00-00:00" (t/zone-id "UTC"))
+ (let [mp (lib.tu/merged-mock-metadata-provider
+ meta/metadata-provider
+ {:fields [{:id (meta/id :checkins :date) :semantic-type :type/Category}]})]
+ (is (= {:query "SELECT * FROM checkins WHERE \"PUBLIC\".\"CHECKINS\".\"DATE\" = ?;"
+ :params [#t "2016-07-01"]}
+ (expand*
+ mp
+ (-> (lib/native-query mp "SELECT * FROM checkins WHERE {{date}};")
+ (lib/with-template-tags
+ {"date" {:name "date"
+ :display-name "Checkin Date"
+ :type :dimension
+ :widget-type :date/all-options
+ :dimension (lib/ref (lib.metadata/field mp (meta/id :checkins :date)))}})
+ (assoc :parameters [{:type :date/single
+ :target [:dimension [:template-tag "date"]]
+ :value "2016-07-01"}])))))))))
+
+(deftest ^:parallel field-filter-string-default-test
+ (testing "a required category field filter with a string default (no user input) filters on the default value (#15444)"
+ (is (= {:query "SELECT count(*) FROM PRODUCTS WHERE (\"PUBLIC\".\"PRODUCTS\".\"CATEGORY\" = ?)"
+ :params ["Doohickey"]}
+ (expand* (-> (lib/native-query meta/metadata-provider "SELECT count(*) FROM PRODUCTS WHERE {{cat}}")
+ (lib/with-template-tags
+ {"cat" {:name "cat"
+ :display-name "Cat"
+ :type :dimension
+ :dimension (lib/ref (meta/field-metadata :products :category))
+ :widget-type :string/=
+ :required true
+ :default ["Doohickey"]}})))))))
+
(deftest ^:parallel newlines-test
(testing "Make sure queries with newlines are parsed correctly (#11526)"
(is (= [[1]]
diff --git a/test/metabase/driver/sql/parameters/substitution_test.clj b/test/metabase/driver/sql/parameters/substitution_test.clj
index 800ef34b02c..ca7017cffaf 100644
--- a/test/metabase/driver/sql/parameters/substitution_test.clj
+++ b/test/metabase/driver/sql/parameters/substitution_test.clj
@@ -10,6 +10,7 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]
^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]
[metabase.test :as mt]
[metabase.util.honey-sql-2 :as h2x]))
@@ -46,6 +47,20 @@
:value {:type :string/=
:value ["Doohickey"]}}))))))
+(deftest ^:parallel field-filter-nil-schema-snippet-test
+ (testing "field-filter snippet omits schema when the field's table has no schema (#29786)"
+ (let [mp (lib.tu/merged-mock-metadata-provider
+ meta/metadata-provider
+ {:tables [{:id (meta/id :venues) :schema nil}]})]
+ (mt/with-metadata-provider mp
+ (is (= {:replacement-snippet "(\"VENUES\".\"NAME\" = ?)"
+ :prepared-statement-args ["Doohickey"]}
+ (#'sql.params.substitution/field-filter->replacement-snippet-info
+ :h2
+ {:field (lib.metadata/field (qp.store/metadata-provider) (meta/id :venues :name))
+ :value {:type :string/=
+ :value ["Doohickey"]}})))))))
+
(deftest ^:parallel field-filter->replacement-snippet-info-test-2
(testing "Compound filters should be wrapped in parens"
(mt/dataset test-data
diff --git a/test/metabase/embedding/settings_test.clj b/test/metabase/embedding/settings_test.clj
index 2d98706af98..40fd9c06ca1 100644
--- a/test/metabase/embedding/settings_test.clj
+++ b/test/metabase/embedding/settings_test.clj
@@ -55,6 +55,20 @@
:user-id (str (mt/user->id :crowberto))}]
(filter embedding-event? (snowplow-test/pop-event-data-and-user-id!))))))))))))
+(deftest enabling-embedding-generates-secret-key-test
+ (testing "Enabling embedding auto-generates embedding-secret-key when blank, and preserves an existing key"
+ (mt/with-test-user :crowberto
+ (mt/with-premium-features #{:embedding}
+ (snowplow-test/with-fake-snowplow-collector
+ (mt/with-temporary-setting-values [enable-embedding-simple false enable-embedding-static false embedding-secret-key nil]
+ (embed.settings/enable-embedding-simple! true)
+ (is (true? (embed.settings/enable-embedding-simple)))
+ (is (not (str/blank? (embed.settings/embedding-secret-key))))
+ (let [generated-key (embed.settings/embedding-secret-key)]
+ (embed.settings/enable-embedding-static! true)
+ (is (= generated-key (embed.settings/embedding-secret-key))
+ "an existing secret key is preserved, not regenerated"))))))))
+
(def ^:private other-ip "1.2.3.4:5555")
(deftest enable-embedding-SDK-true-ignores-localhosts
diff --git a/test/metabase/embedding_rest/api/embed_test.clj b/test/metabase/embedding_rest/api/embed_test.clj
index 3c55015adb7..5dab5b8e412 100644
--- a/test/metabase/embedding_rest/api/embed_test.clj
+++ b/test/metabase/embedding_rest/api/embed_test.clj
@@ -13,6 +13,8 @@
[metabase.api.common :as api]
[metabase.dashboards-rest.api-test :as api.dashboard-test]
[metabase.embedding-rest.api.common :as api.embed.common]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.parameters.chain-filter-test :as chain-filer-test]
[metabase.parameters.custom-values :as custom-values]
[metabase.public-sharing-rest.api-test :as public-test]
@@ -992,6 +994,35 @@
(is (= "completed"
(:status (client/client :get 202 (dashcard-url (assoc dashcard :card_id (u/the-id series-card)))))))))))))
+(deftest embed-dashboard-visualizer-series-card-test
+ (testing "GET /api/embed/dashboard/:token exposes visualizer viz-settings, and dashcard-query authorizes series-card queries"
+ (with-embedding-enabled-and-new-secret-key!
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card series-card {:dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/aggregate (lib/count)))}]
+ (with-temp-dashcard
+ [dashcard {:dash {:enable_embedding true}
+ :dashcard {:visualization_settings
+ {:visualization {:columnValuesMapping {:COLUMN_1 [{:sourceId (str "card:" (u/the-id series-card))}]}}}}}]
+ (mt/with-temp [:model/DashboardCardSeries _ {:dashboardcard_id (u/the-id dashcard) :card_id (u/the-id series-card)}]
+ (testing "embed dashboard response exposes the visualizer viz-settings unchanged"
+ (is (=? {:columnValuesMapping {:COLUMN_1 [{:sourceId (str "card:" (u/the-id series-card))}]}}
+ (-> (client/client :get 200 (str "embed/dashboard/" (dash-token (:dashboard_id dashcard))))
+ :dashcards first :visualization_settings :visualization))))
+ (testing "dashcard-query endpoint authorizes the series card via a real DashboardCardSeries row"
+ (is (= "completed"
+ (:status (client/client :get 202 (dashcard-url (assoc dashcard :card_id (u/the-id series-card)))))))))))))))
+
+(deftest non-map-token-params-are-handled-test
+ (testing "GET /api/embed/dashboard/:token/dashcard/:id/card/:id whose signed :params is a non-map yields a clean 4xx, not a 500 (#14474)"
+ (with-embedding-enabled-and-new-secret-key!
+ (with-temp-dashcard [dashcard {:dash {:enable_embedding true}}]
+ (let [url (str "embed/dashboard/" (sign {:resource {:dashboard (:dashboard_id dashcard)} :params []})
+ "/dashcard/" (u/the-id dashcard)
+ "/card/" (:card_id dashcard))]
+ (is (some? (client/client-full-response :get url)))
+ (is (<= 400 (:status (client/client-full-response :get url)) 499)))))))
+
;;; ------------------------------- GET /api/embed/card/:token/params/:param/values --------------------------------
(deftest card-param-values
@@ -1130,6 +1161,15 @@
:has_more_values false}
(client/client :get 200 (search-url {} "_STATIC_CATEGORY_LABEL_" "AF")))))))))
+(deftest embed-dashboard-card-source-param-values-test
+ (testing "GET /api/embed/dashboard/:token/params/:key/values works for a card-source parameter"
+ (with-chain-filter-fixtures! [{:keys [dashboard values-url]}]
+ (t2/update! :model/Dashboard (u/the-id dashboard)
+ {:parameters (mapv (fn [p] (cond-> p (= (:id p) "_CARD_") (assoc :slug "card")))
+ (:parameters dashboard))
+ :embedding_params {"card" "enabled"}})
+ (is (seq (:values (client/client :get 200 (values-url {} "_CARD_"))))))))
+
(deftest chain-filter-enabled-params-test
(with-chain-filter-fixtures! [{:keys [dashboard values-url search-url]}]
(t2/update! :model/Dashboard (:id dashboard)
diff --git a/test/metabase/embedding_rest/api/preview_embed_test.clj b/test/metabase/embedding_rest/api/preview_embed_test.clj
index 3232b898184..7747ace173e 100644
--- a/test/metabase/embedding_rest/api/preview_embed_test.clj
+++ b/test/metabase/embedding_rest/api/preview_embed_test.clj
@@ -571,6 +571,19 @@
:has_more_values false}
(mt/user-http-request :rasta :get 200 url))))))))))
+(deftest preview-locked-linked-chain-filter-values-test
+ (testing "GET /api/preview_embed/dashboard/:token/params/:key/values constrains a linked enabled param by a locked param (#41635)"
+ (with-embedding-enabled-and-new-secret-key!
+ (api.dashboard-test/with-chain-filter-fixtures [{:keys [dashboard]}]
+ (let [signed-token (dash-token dashboard {:_embedding_params {:category_id "enabled"
+ :category_name "enabled"
+ :price "locked"}
+ :params {:price 4}})
+ url (format "preview_embed/dashboard/%s/params/%s/values" signed-token "_CATEGORY_ID_")]
+ (is (= {:values [[40 "Japanese"] [67 "Steakhouse"]]
+ :has_more_values false}
+ (mt/user-http-request :crowberto :get 200 url))))))))
+
(deftest dashboard-params-search-test
(testing "GET /api/preview_embed/dashboard/:token/params/:param-key/search/:prefix"
(with-embedding-enabled-and-new-secret-key!
diff --git a/test/metabase/lib/aggregation_test.cljc b/test/metabase/lib/aggregation_test.cljc
index 14c60f18e3f..a17bc826e7c 100644
--- a/test/metabase/lib/aggregation_test.cljc
+++ b/test/metabase/lib/aggregation_test.cljc
@@ -1030,3 +1030,82 @@
(when (and sum-where-idx sum-idx)
(is (< sum-where-idx sum-idx)
"Sum-where pattern should come before plain Sum pattern")))))
+
+(deftest ^:parallel aggregable-columns-from-nested-aggregating-source-test
+ (testing "#24839 a nested question on an aggregating card offers its aggregation columns as aggregable columns"
+ (let [source (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (lib/sum (meta/field-metadata :orders :quantity)))
+ (lib/aggregate (lib/avg (meta/field-metadata :orders :total)))
+ (lib/breakout (-> (meta/field-metadata :orders :created-at)
+ (lib/with-temporal-bucket :month))))
+ mp (lib.tu/metadata-provider-with-card-from-query 1 source)
+ query (lib/query mp (lib.metadata/card mp 1))]
+ (is (set/subset? #{"Sum of Quantity" "Average of Total"}
+ (set (map :display-name (lib/aggregable-columns query nil))))))))
+
+(deftest ^:parallel expression-references-named-aggregation-test
+ (testing "an expression can reference a named aggregation column from the previous stage"
+ (let [q (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (-> (lib/sum (meta/field-metadata :orders :total))
+ (lib/with-expression-name "Custom Sum")))
+ (lib/breakout (meta/field-metadata :orders :user-id))
+ lib/append-stage)
+ agg-col (m/find-first #(= "Custom Sum" (:display-name %)) (lib/visible-columns q))]
+ (is (some? agg-col))
+ (let [q' (lib/expression q "Custom Sum + 1" (lib/+ agg-col 1))
+ new-col (m/find-first #(= "Custom Sum + 1" (:display-name %)) (lib/returned-columns q'))]
+ (is (some? new-col))
+ (is (lib.types.isa/numeric? new-col))))))
+
+(deftest ^:parallel aggregations-over-native-card-survive-normalize-test
+ (testing "#15725 aggregations built over a native card survive a convert round-trip and are not dropped"
+ (let [mp (lib.tu/metadata-provider-with-mock-cards)
+ card (:orders/native (lib.tu/mock-cards))
+ query (lib/query mp card)
+ total (m/find-first #(= "TOTAL" (:name %)) (lib/visible-columns query))
+ pid (m/find-first #(= "PRODUCT_ID" (:name %)) (lib/visible-columns query))
+ q (-> query
+ (lib/aggregate (lib/count))
+ (lib/aggregate (lib/sum total))
+ (lib/breakout pid))
+ q' (lib/query mp (lib.convert/->legacy-MBQL q))]
+ (is (= 2 (count (lib/aggregations q'))))
+ (is (= 1 (count (lib/breakouts q')))))))
+
+(deftest ^:parallel aggregation-named-same-as-aggregated-column-test
+ (testing "#44567 an aggregation named the same as the column it aggregates still resolves the inner field"
+ (let [total (meta/field-metadata :orders :total)
+ q (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (-> (lib/sum total) (lib/with-expression-name "Total"))))
+ agg (first (lib/aggregations q))]
+ (testing "the aggregation display name is the custom name"
+ (is (= "Total" (:display-name (lib/display-info q agg)))))
+ (testing "the inner field ref still resolves to the Total column (not Unknown Field)"
+ (is (= "Total" (lib/display-name q (last agg)))))
+ (testing "Sum([Total]) + 1 still validates as an aggregation"
+ (is (= 2 (count (lib/aggregations (lib/aggregate q (lib/+ (lib/sum total) 1))))))))))
+
+(deftest ^:parallel aggregate-over-joined-card-aggregation-column-test
+ (testing "#32020 aggregation columns from source and joined cards can feed a new aggregation"
+ (let [card1 (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
+ (lib/breakout (meta/field-metadata :orders :user-id)))
+ card2 (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
+ (lib/aggregate (lib/max (meta/field-metadata :people :longitude)))
+ (lib/breakout (meta/field-metadata :people :id)))
+ mp (lib.tu/metadata-provider-with-cards-for-queries meta/metadata-provider [card1 card2])
+ base (lib/query mp (lib.metadata/card mp 1))
+ c2 (lib.metadata/card mp 2)
+ lhs (m/find-first #(= "USER_ID" (:name %))
+ (lib/join-condition-lhs-columns base c2 nil nil))
+ rhs (m/find-first #(= "ID" (:name %))
+ (lib/join-condition-rhs-columns base c2 (lib/ref lhs) nil))
+ joined (lib/join base (lib/join-clause c2 [(lib/= lhs rhs)]))
+ sum-op (m/find-first #(= :sum (:short %)) (lib/available-aggregation-operators joined))
+ cols (lib/aggregation-operator-columns sum-op)
+ maxcol (m/find-first #(and (= "max" (:name %)) (= :source/joins (:lib/source %))) cols)]
+ (testing "the source card's aggregation column is offered as an aggregation input"
+ (is (some #(and (= "sum" (:name %)) (= :source/card (:lib/source %))) cols)))
+ (testing "the joined card's aggregation column is offered as an aggregation input"
+ (is (some? maxcol)))
+ (is (= 1 (count (lib/aggregations (lib/aggregate joined (lib/sum maxcol)))))))))
diff --git a/test/metabase/lib/breakout_test.cljc b/test/metabase/lib/breakout_test.cljc
index f8cf83c1ce0..1a8117c5a3c 100644
--- a/test/metabase/lib/breakout_test.cljc
+++ b/test/metabase/lib/breakout_test.cljc
@@ -803,3 +803,38 @@
(juxt #(get-in % [:table :long-display-name]) :long-display-name)
#(lib/display-info query %))
(lib/breakoutable-columns query)))))))
+
+(deftest ^:parallel available-binning-strategies-through-joins-test
+ (testing "#16674 binning strategies / temporal buckets offered on a joined column match the direct-column list"
+ (let [query (lib/query meta/metadata-provider (meta/table-metadata :orders))]
+ (testing "coordinate binning on an implicitly-joined column"
+ (let [lat (m/find-first #(and (= (:id %) (meta/id :people :latitude))
+ (= :source/implicitly-joinable (:lib/source %)))
+ (lib/breakoutable-columns query))
+ direct (lib/available-binning-strategies
+ (lib/query meta/metadata-provider (meta/table-metadata :people))
+ (meta/field-metadata :people :latitude))]
+ (is (some? lat))
+ (is (= (map :display-name direct)
+ (map :display-name (lib/available-binning-strategies query lat))))))
+ (testing "temporal buckets on an implicitly-joined column"
+ (let [bd (m/find-first #(and (= (:id %) (meta/id :people :birth-date))
+ (= :source/implicitly-joinable (:lib/source %)))
+ (lib/breakoutable-columns query))
+ direct (lib/available-temporal-buckets
+ (lib/query meta/metadata-provider (meta/table-metadata :people))
+ (meta/field-metadata :people :birth-date))]
+ (is (some? bd))
+ (is (= (map :display-name direct)
+ (map :display-name (lib/available-temporal-buckets query bd)))))))))
+
+(deftest ^:parallel breakout-columns-no-duplicate-created-at-on-fk-remap-test
+ (testing "#15563 a datetime FK remap does not duplicate Created At in breakoutable-columns"
+ (let [mp (lib.tu/remap-metadata-provider
+ meta/metadata-provider
+ (meta/id :reviews :created-at) (meta/id :orders :created-at))
+ query (lib/query mp (meta/table-metadata :reviews))
+ cols (filter #(and (= (:display-name %) "Created At")
+ (= :source/table-defaults (:lib/source %)))
+ (lib/breakoutable-columns query))]
+ (is (= 1 (count cols))))))
diff --git a/test/metabase/lib/card_test.cljc b/test/metabase/lib/card_test.cljc
index 2f05663d2cd..ab1879bbda3 100644
--- a/test/metabase/lib/card_test.cljc
+++ b/test/metabase/lib/card_test.cljc
@@ -106,6 +106,24 @@
(for [col (meta/fields table)]
(meta/field-metadata table col)))
+(deftest ^:parallel columns-mapped-to-same-field-id-stay-distinct-test
+ (testing "distinct-named columns all mapped to the same field id remain separate columns (metabase#33427)"
+ (let [rm (for [[i n] (map-indexed vector ["A" "B" "C"])]
+ (assoc (meta/field-metadata :orders :id)
+ :name n
+ :display-name (str "ID" (inc i))))
+ mp (lib.tu/mock-metadata-provider
+ meta/metadata-provider
+ {:cards [{:id 1
+ :name "M"
+ :database-id (meta/id)
+ :dataset-query (lib.tu/native-query)
+ :result-metadata (vec rm)}]})
+ q (lib/query mp (lib.metadata/card mp 1))]
+ (is (= 3 (count (lib/returned-columns q))))
+ (is (= ["ID1" "ID2" "ID3"]
+ (map #(:display-name (lib/display-info q %)) (lib/returned-columns q)))))))
+
(defn- sort-cols [cols]
(sort-by (juxt :id :name :lib/join-alias :lib/desired-column-alias) cols))
diff --git a/test/metabase/lib/column_group_test.cljc b/test/metabase/lib/column_group_test.cljc
index e29a8bdd3e4..c0cb66802ac 100644
--- a/test/metabase/lib/column_group_test.cljc
+++ b/test/metabase/lib/column_group_test.cljc
@@ -517,3 +517,14 @@
(is (not= (:display-name (first join-infos))
(:display-name (second join-infos)))
"Join column groups for the same table should have different display names"))))
+
+(deftest ^:parallel breakout-groups-for-added-fk-test
+ (testing "#36122 a newly-FK'd column produces its own implicit-join breakout group"
+ (let [rating (assoc (meta/field-metadata :reviews :rating)
+ :semantic-type :type/FK
+ :fk-target-field-id (meta/id :products :id))
+ mp (lib.tu/mock-metadata-provider meta/metadata-provider {:fields [rating]})
+ query (lib/query mp (meta/table-metadata :reviews))
+ groups (lib/group-columns (lib/breakoutable-columns query))]
+ (is (= #{"Reviews" "Product" "Rating"}
+ (set (map #(:display-name (lib/display-info query %)) groups)))))))
diff --git a/test/metabase/lib/convert_test.cljc b/test/metabase/lib/convert_test.cljc
index d86d54d6d5f..1206d14185a 100644
--- a/test/metabase/lib/convert_test.cljc
+++ b/test/metabase/lib/convert_test.cljc
@@ -1676,3 +1676,23 @@
:type :dimension
:widget-type :date/all-options
:dimension [:field 2 nil]}}}))))
+
+(deftest ^:parallel round-trip-offset-inside-case-inside-aggregation-test
+ (testing "#42377 sum(case([Total] > 0, offset([Total], -1))) survives the legacy <-> pMBQL round-trip"
+ ;; OFFSET retains a random :lib/uuid in its (mbql5-style) options, so exact round-trip equality is not
+ ;; possible; instead assert the conversion happens without an "Error normalizing" exception and that the
+ ;; clause shape is preserved in both directions.
+ (let [legacy {:database 2762
+ :type :query
+ :query {:aggregation [[:sum [:case [[[:> [:field 139657 nil] 0]
+ [:offset {} [:field 139657 nil] -1]]]]]]
+ :breakout [[:field 139658 nil]]
+ :source-table 33674}}
+ mbql5 (lib.convert/->mbql5 legacy)]
+ (is (=? {:stages [{:aggregation [[:sum {}
+ [:case {}
+ [[[:> {} [:field {} 139657] 0]
+ [:offset {:lib/uuid string?} [:field {} 139657] -1]]]]]]}]}
+ mbql5))
+ (is (=? legacy (lib.convert/->legacy-MBQL mbql5)))
+ (is (some? (-> mbql5 lib.convert/->legacy-MBQL lib.convert/->mbql5))))))
diff --git a/test/metabase/lib/display_name_test.cljc b/test/metabase/lib/display_name_test.cljc
index 28c7ffa6c2e..4b8f9303e55 100644
--- a/test/metabase/lib/display_name_test.cljc
+++ b/test/metabase/lib/display_name_test.cljc
@@ -1,9 +1,15 @@
(ns metabase.lib.display-name-test
(:require
+ [clojure.string :as str]
[clojure.test :refer [deftest is testing]]
+ [medley.core :as m]
[metabase.lib.aggregation :as lib.aggregation]
+ [metabase.lib.core :as lib]
[metabase.lib.display-name :as lib.display-name]
- [metabase.lib.filter :as lib.filter]))
+ [metabase.lib.filter :as lib.filter]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]))
(deftest ^:parallel parse-column-display-name-parts-plain-column-test
(testing "Plain column names should be translatable"
@@ -211,3 +217,12 @@
(testing "Plain column name is unchanged when filter patterns are present"
(is (= [{:type :translatable, :value "Total"}]
(lib.display-name/parse-column-display-name-parts "Total" agg-patterns filter-patterns))))))
+
+(deftest ^:parallel source-card-date-column-display-name-no-default-period-test
+ (testing "#36631 a Date column inherited from a source card keeps its plain name with no 'Default period' suffix"
+ (let [mp (lib.tu/metadata-provider-with-card-from-query
+ 1 (lib/query meta/metadata-provider (meta/table-metadata :orders)))
+ query (lib/query mp (lib.metadata/card mp 1))
+ col (m/find-first #(= (:name %) "CREATED_AT") (lib/visible-columns query))]
+ (is (= "Created At" (lib/display-name query col)))
+ (is (not (str/includes? (lib/display-name query col) "Default period"))))))
diff --git a/test/metabase/lib/drill_thru/combine_columns_test.cljc b/test/metabase/lib/drill_thru/combine_columns_test.cljc
new file mode 100644
index 00000000000..a568141b012
--- /dev/null
+++ b/test/metabase/lib/drill_thru/combine_columns_test.cljc
@@ -0,0 +1,35 @@
+(ns metabase.lib.drill-thru.combine-columns-test
+ (:require
+ #?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
+ [clojure.test :refer [deftest use-fixtures]]
+ [metabase.lib.drill-thru.test-util :as lib.drill-thru.tu]
+ [metabase.lib.drill-thru.test-util.canned :as canned]
+ [metabase.lib.types.isa :as lib.types.isa]))
+
+#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))
+
+(use-fixtures :each lib.drill-thru.tu/with-native-card-id)
+
+;; `combine-columns` has no BE application path (its drill-thru-method deliberately throws; the
+;; FE adds the :concat expression directly), so the BE-testable surface is availability and the
+;; returned drill.
+
+(deftest ^:parallel combine-columns-availability-test
+ (canned/canned-test
+ :drill-thru/combine-columns
+ (fn [test-case {:keys [column] :as _context} {:keys [click]}]
+ ;; available only on header clicks of string columns of an mbql stage (never on a raw native query)
+ (and (= click :header)
+ (not (:native? test-case))
+ (lib.types.isa/string? column)))))
+
+(deftest ^:parallel combine-columns-drill-returned-test
+ ;; runs against both MBQL and (card-wrapped) native sources - `combine-columns` must work on both.
+ (lib.drill-thru.tu/test-returns-drill
+ {:drill-type :drill-thru/combine-columns
+ :click-type :header
+ :query-type :unaggregated
+ :query-table "PRODUCTS"
+ :column-name "TITLE"
+ :expected {:type :drill-thru/combine-columns
+ :column {:name "TITLE"}}}))
diff --git a/test/metabase/lib/drill_thru/pivot_test.cljc b/test/metabase/lib/drill_thru/pivot_test.cljc
index a1d0d583505..9d64e48597a 100644
--- a/test/metabase/lib/drill_thru/pivot_test.cljc
+++ b/test/metabase/lib/drill_thru/pivot_test.cljc
@@ -2,9 +2,11 @@
(:require
#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
[clojure.test :refer [deftest is testing use-fixtures]]
+ [medley.core :as m]
[metabase.lib.core :as lib]
[metabase.lib.drill-thru.test-util :as lib.drill-thru.tu]
[metabase.lib.drill-thru.test-util.canned :as canned]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]
[metabase.util.malli :as mu]))
@@ -316,6 +318,46 @@
"count" 10}}
(expecting ["IS_OPEN"] [:category :time])))))
+(deftest ^:parallel pivot-drill-on-metric-test
+ (testing "pivot drill offers to break out by a category on a timeseries metric-consumer query"
+ (let [metric-id 101
+ provider (lib.tu/mock-metadata-provider
+ meta/metadata-provider
+ {:cards [{:lib/type :metadata/card
+ :type :metric
+ :id metric-id
+ :name "Count of orders over time"
+ :database-id (meta/id)
+ :dataset-query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (lib/count)))}]})
+ query (-> (lib/query provider (meta/table-metadata :orders))
+ (lib/aggregate (lib.metadata/metric provider metric-id))
+ (lib/breakout (lib/with-temporal-bucket (meta/field-metadata :orders :created-at) :month)))
+ cols (lib/returned-columns query)
+ metric-col (m/find-first #(= (:lib/source %) :source/aggregations) cols)
+ _ (is (some? metric-col))
+ created-at (m/find-first #(= (:name %) "CREATED_AT") cols)
+ _ (is (some? created-at))
+ context {:column metric-col
+ :column-ref (lib/ref metric-col)
+ :value 100
+ :dimensions [{:column created-at
+ :column-ref (lib/ref created-at)
+ :value "2027-03-01T00:00:00Z"}]}
+ pivot (m/find-first #(= (:type %) :drill-thru/pivot)
+ (lib/available-drill-thrus query -1 context))]
+ (is (some? pivot))
+ (testing "breaking out by User → Source adds the expected breakout and filters the clicked month"
+ (let [source-col (m/find-first #(= (:name %) "SOURCE")
+ (lib/pivot-columns-for-type pivot :category))]
+ (is (some? source-col))
+ (is (=? {:stages [{:filters [[:= {}
+ [:field {:temporal-unit :month} (meta/id :orders :created-at)]
+ "2027-03-01T00:00:00Z"]]
+ :breakout [[:field {:source-field (meta/id :orders :user-id)}
+ (meta/id :people :source)]]}]}
+ (lib/drill-thru query -1 nil pivot source-col))))))))
+
(deftest ^:parallel expression-after-aggregation-test
(testing "custom column defined after aggregation should not offer pivot drill (#66715)"
(let [;; Stage 0: Count of products by category
diff --git a/test/metabase/lib/drill_thru/quick_filter_test.cljc b/test/metabase/lib/drill_thru/quick_filter_test.cljc
index 32ecea7b71b..f5fd7162db9 100644
--- a/test/metabase/lib/drill_thru/quick_filter_test.cljc
+++ b/test/metabase/lib/drill_thru/quick_filter_test.cljc
@@ -343,6 +343,62 @@
"2023-03-01T00:00:00Z"]]}]}
(lib/drill-thru base-query -1 nil drill "="))))))
+(deftest ^:parallel quick-filter-bigint-value-test
+ (testing "quick-filter '=' on a bigint numeric cell wraps the value in a :value clause at full precision"
+ (let [big "9223372036854775807"]
+ (lib.drill-thru.tu/test-drill-application
+ {:click-type :cell
+ :query-type :unaggregated
+ :query-kinds [:mbql]
+ :column-name "QUANTITY"
+ :drill-type :drill-thru/quick-filter
+ :custom-row (assoc (get-in lib.drill-thru.tu/test-queries ["ORDERS" :unaggregated :row])
+ "QUANTITY" big)
+ :expected {:type :drill-thru/quick-filter}
+ :drill-args ["="]
+ ;; the emitted filter keeps the full bigint precision (stored as a string in the :value clause)
+ :expected-query {:stages [{:filters [[:= {}
+ [:field {} (meta/id :orders :quantity)]
+ [:value {:base-type :type/BigInteger} big]]]}]}}))))
+
+(deftest ^:parallel quick-filter-drill-on-expression-column-test
+ (testing "quick-filter on an expression column value produces a filter referencing the expression (#32032)"
+ (lib.drill-thru.tu/test-drill-application
+ {:click-type :cell
+ :query-type :unaggregated
+ :query-kinds [:mbql]
+ :column-name "Custom Reviewer"
+ :drill-type :drill-thru/quick-filter
+ :custom-query (-> (lib/query meta/metadata-provider (meta/table-metadata :reviews))
+ (lib/expression "Custom Reviewer" (meta/field-metadata :reviews :reviewer)))
+ :custom-row {"Custom Reviewer" "xavier"}
+ :expected {:type :drill-thru/quick-filter
+ :operators [{:name "="} {:name "≠"}]}
+ :drill-args ["="]
+ :expected-query {:stages [{:filters [[:= {} [:expression {} "Custom Reviewer"] "xavier"]]}]}})))
+
+(deftest ^:parallel quick-filter-null-numeric-cell-test
+ (testing "quick-filter '='/'≠' on a null numeric (Discount) cell produce is-null / not-null filters (#29082)"
+ (let [field-key (lib.drill-thru.tu/field-key= (meta/id :orders :discount) "DISCOUNT")
+ base {:drill-type :drill-thru/quick-filter
+ :click-type :cell
+ :query-type :unaggregated
+ :column-name "DISCOUNT"
+ :expected {:type :drill-thru/quick-filter
+ :value :null
+ :operators [{:name "=", :filter [:is-null {} [:field {} field-key]]}
+ {:name "≠", :filter [:not-null {} [:field {} field-key]]}]}}]
+ (testing "= applies an is-null filter"
+ (lib.drill-thru.tu/test-drill-application
+ (assoc base
+ :drill-args ["="]
+ :expected-query {:stages [{:filters [[:is-null {} [:field {} field-key]]]}]})))
+ (testing "≠ applies a not-null filter"
+ (lib.drill-thru.tu/test-drill-application
+ (assoc base
+ :drill-args ["≠"]
+ :expected-query {:stages [{:filters [[:not-null {} [:field {} field-key]]]}]}))))))
+
(deftest ^:parallel quick-filter-on-binned-column-keeps-binning-test
(let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
(lib/aggregate (lib/count))
diff --git a/test/metabase/lib/drill_thru/summarize_column_test.cljc b/test/metabase/lib/drill_thru/summarize_column_test.cljc
index 11531e174cc..43255d7bfb6 100644
--- a/test/metabase/lib/drill_thru/summarize_column_test.cljc
+++ b/test/metabase/lib/drill_thru/summarize_column_test.cljc
@@ -1,12 +1,18 @@
(ns metabase.lib.drill-thru.summarize-column-test
(:require
- [clojure.test :refer [deftest testing use-fixtures]]
+ #?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
+ [clojure.test :refer [deftest is testing use-fixtures]]
+ [medley.core :as m]
[metabase.lib.core :as lib]
[metabase.lib.drill-thru.test-util :as lib.drill-thru.tu]
[metabase.lib.drill-thru.test-util.canned :as canned]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]
[metabase.lib.types.isa :as lib.types.isa]))
+#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))
+
(use-fixtures :each lib.drill-thru.tu/with-native-card-id)
(deftest ^:parallel summarize-column-availability-test
@@ -84,6 +90,24 @@
"count" 77}
:column-name column-name}))))
+(deftest ^:parallel distinct-drill-preserves-model-source-test
+ (testing "a Distinct values drill on a model column keeps the model as the query's source-card (#50915)"
+ (let [model-id 1
+ mp (lib.tu/metadata-provider-with-card-from-query
+ meta/metadata-provider model-id
+ (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ {:type :model :name "Orders Model"})
+ query (lib/query mp (lib.metadata/card mp model-id))
+ col (m/find-first #(= (:name %) "DISCOUNT") (lib/returned-columns query))
+ _ (is (some? col))
+ drill (m/find-first #(= (:type %) :drill-thru/summarize-column)
+ (lib/available-drill-thrus query -1 {:column col
+ :column-ref (lib/ref col)
+ :value nil}))]
+ (is (some? drill))
+ (is (=? {:stages [{:source-card model-id}]}
+ (lib/drill-thru query -1 nil drill "distinct"))))))
+
(deftest ^:parallel custom-column-test
(testing "#34957"
(lib.drill-thru.tu/test-drill-application
diff --git a/test/metabase/lib/drill_thru/underlying_records_test.cljc b/test/metabase/lib/drill_thru/underlying_records_test.cljc
index bea0c8ddc54..f1111cf6dcf 100644
--- a/test/metabase/lib/drill_thru/underlying_records_test.cljc
+++ b/test/metabase/lib/drill_thru/underlying_records_test.cljc
@@ -1032,3 +1032,37 @@
:breakout (symbol "nil #_\"key is not present.\"")
:fields (symbol "nil #_\"key is not present.\"")}]}
result)))))
+
+(deftest ^:parallel native-card-day-breakout-drill-test
+ ;; The day bucket produces a single-day `:between` (identical bounds) - not a multi-day range - which the
+ ;; filters panel renders as "CREATED_AT is Oct 11, 2026". This is the regression #54108 guarded.
+ (testing "underlying-records drill on a day-bucketed breakout over a native card keeps the model as
+ source-card and filters the single clicked day (#54108)"
+ (let [mp (lib.tu/metadata-provider-with-mock-cards)
+ card (:orders/native (lib.tu/mock-cards))
+ query (as-> (lib/query mp card) q
+ (lib/aggregate q (lib/count))
+ (lib/breakout q (lib/with-temporal-bucket
+ (m/find-first #(= (:name %) "CREATED_AT")
+ (lib/breakoutable-columns q))
+ :day)))
+ cols (lib/returned-columns query)
+ count-col (m/find-first #(= (:name %) "count") cols)
+ _ (is (some? count-col))
+ created-at (m/find-first #(= (:name %) "CREATED_AT") cols)
+ _ (is (some? created-at))
+ context {:column count-col
+ :column-ref (lib/ref count-col)
+ :value 6
+ :dimensions [{:column created-at
+ :column-ref (lib/ref created-at)
+ :value "2026-10-11T00:00:00Z"}]}
+ drill (m/find-first #(= (:type %) :drill-thru/underlying-records)
+ (lib/available-drill-thrus query context))]
+ (is (some? drill))
+ (is (=? [{:source-card (:id card)
+ :filters [[:between {}
+ [:field {:temporal-unit :day} "CREATED_AT"]
+ "2026-10-11"
+ "2026-10-11"]]}]
+ (:stages (lib/drill-thru query drill)))))))
diff --git a/test/metabase/lib/drill_thru/zoom_in_timeseries_test.cljc b/test/metabase/lib/drill_thru/zoom_in_timeseries_test.cljc
index 5b169aec4ce..d262279d3b1 100644
--- a/test/metabase/lib/drill_thru/zoom_in_timeseries_test.cljc
+++ b/test/metabase/lib/drill_thru/zoom_in_timeseries_test.cljc
@@ -10,6 +10,7 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.temporal-bucket :as lib.temporal-bucket]
[metabase.lib.test-metadata :as meta]
+ [metabase.lib.test-util :as lib.tu]
[metabase.lib.test-util.metadata-providers.merged-mock :as merged-mock]
[metabase.util.malli :as mu]))
@@ -335,3 +336,84 @@
:filters [[:= {}
[:field {:temporal-unit unit1} (meta/id :orders :created-at)]
"2022-12-09"]]}]}})))))
+
+(deftest ^:parallel zoom-in-with-expression-breakout-test
+ (testing "zoom-in.timeseries works when the stage also has an expression breakout (#13289)"
+ (let [base (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/expression "Math" (lib/+ 1 1)))
+ math-col (m/find-first #(= (:name %) "Math")
+ (lib/breakoutable-columns base))
+ _ (is (some? math-col))
+ query (-> base
+ (lib/aggregate (lib/count))
+ (lib/breakout math-col)
+ (lib/breakout (-> (meta/field-metadata :orders :created-at)
+ (lib/with-temporal-bucket :month))))
+ columns (lib/returned-columns query)
+ created-at (m/find-first #(and (= (:name %) "CREATED_AT")
+ (= (lib.temporal-bucket/raw-temporal-bucket %) :month))
+ columns)
+ _ (is (some? created-at))
+ count-col (m/find-first #(= (:name %) "count") columns)
+ _ (is (some? count-col))
+ drill (m/find-first #(= (:type %) :drill-thru/zoom-in.timeseries)
+ (lib/available-drill-thrus
+ query -1
+ {:column count-col
+ :column-ref (lib/ref count-col)
+ :value 100
+ :dimensions [{:column created-at
+ :column-ref (lib/ref created-at)
+ :value "2025-09-01T00:00:00Z"}]}))]
+ (is (=? {:type :drill-thru/zoom-in.timeseries
+ :next-unit :week
+ :display-name "See this month by week"}
+ drill))
+ (testing "drilling preserves the expression breakout and re-buckets the datetime breakout"
+ (is (=? {:stages [{:breakout [[:expression {} "Math"]
+ [:field {:temporal-unit :week} (meta/id :orders :created-at)]]
+ :filters [[:= {}
+ [:field {:temporal-unit :month} (meta/id :orders :created-at)]
+ "2025-09-01T00:00:00Z"]]}]}
+ (lib/drill-thru query -1 nil drill)))))))
+
+(deftest ^:parallel zoom-in-day-to-hour-on-join-aliased-native-datetime-column-test
+ (testing "zooming a join-aliased native-card datetime breakout from day to hour produces a valid :hour query (#42817)"
+ (let [mp (lib.tu/metadata-provider-with-mock-cards)
+ card (:orders/native (lib.tu/mock-cards))
+ card-id (m/find-first #(= "ID" (:name %))
+ (lib/returned-columns (lib/query mp card)))
+ joined (lib/join (lib/query mp (meta/table-metadata :orders))
+ (-> (lib/join-clause card
+ [(lib/= (meta/field-metadata :orders :id) card-id)])
+ (lib/with-join-alias "NativeOrders")
+ (lib/with-join-fields :all)))
+ card-created (m/find-first #(and (= "CREATED_AT" (:name %))
+ (= :source/joins (:lib/source %)))
+ (lib/breakoutable-columns joined))
+ query (-> joined
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket card-created :day)))
+ cols (lib/returned-columns query)
+ created-at (m/find-first #(and (= (:name %) "CREATED_AT")
+ (= (lib.temporal-bucket/raw-temporal-bucket %) :day))
+ cols)
+ _ (is (some? created-at))
+ count-col (m/find-first #(= (:name %) "count") cols)
+ _ (is (some? count-col))
+ drill (m/find-first #(= (:type %) :drill-thru/zoom-in.timeseries)
+ (lib/available-drill-thrus
+ query -1
+ {:column count-col
+ :column-ref (lib/ref count-col)
+ :value 50
+ :dimensions [{:column created-at
+ :column-ref (lib/ref created-at)
+ :value "2026-06-23T00:00:00Z"}]}))]
+ (is (=? {:type :drill-thru/zoom-in.timeseries
+ :next-unit :hour
+ :display-name "See this day by hour"}
+ drill))
+ (testing "drilling produces a valid :hour breakout without an invalid-temporal-unit error"
+ (is (=? {:stages [{:breakout [[:field {:temporal-unit :hour, :join-alias "NativeOrders"} "CREATED_AT"]]}]}
+ (lib/drill-thru query -1 nil drill)))))))
diff --git a/test/metabase/lib/expression_test.cljc b/test/metabase/lib/expression_test.cljc
index 1576e0e03e8..68ddb5473ad 100644
--- a/test/metabase/lib/expression_test.cljc
+++ b/test/metabase/lib/expression_test.cljc
@@ -1,6 +1,7 @@
(ns metabase.lib.expression-test
(:require
#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
+ [clojure.string :as str]
[clojure.test :refer [deftest is are testing]]
[medley.core :as m]
[metabase.lib.convert :as lib.convert]
@@ -843,3 +844,56 @@
(deftest ^:parallel absolute-datetime-raw-temporal-bucket-test
(is (= :day
(lib/raw-temporal-bucket [:absolute-datetime {:lib/uuid "6360380d-137a-4197-b517-9af9eebde16b"} "2025-09-08" :day]))))
+
+(deftest ^:parallel temporal-functions-require-temporal-args-test
+ (testing "#26512 temporal-extraction / datetime-arithmetic functions reject non-temporal first args"
+ (are [expr] (=? {:message #"(?i).*incompatible.*" :friendly true}
+ (lib.expression/diagnose-expression
+ (lib.tu/venues-query) 0 :expression (lib.convert/->mbql5 expr)
+ #?(:clj nil :cljs js/undefined)))
+ [:get-year "a string"]
+ [:datetime-add 42 1 :day]
+ [:datetime-diff true 1 :day])))
+
+(deftest ^:parallel expression-self-reference-rejected-test
+ (testing "#61010 an expression referencing itself at its own position is rejected"
+ (let [q (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/expression "Foo" (lib/+ 1 1)))
+ pos (dec (count (lib/expressions q)))]
+ (is (some? (lib.expression/diagnose-expression
+ q 0 :expression (lib/+ (lib/expression-ref q "Foo") 1) pos))))))
+
+(deftest ^:parallel unknown-field-ref-in-expression-degrades-gracefully-test
+ (testing "#48562 an expression over a non-existent field ref renders a non-blank display name without throwing"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :venues))
+ (lib/expression "CC" (lib.convert/->mbql5 [:contains [:field 10000 nil] "abc"])))
+ expr (first (lib/expressions query))]
+ (is (string? (lib/display-name query expr)))
+ (is (not (str/blank? (lib/display-name query expr))))
+ (is (some? (lib/visible-columns query))))))
+
+(deftest ^:parallel post-aggregation-expression-keeps-filterable-columns-test
+ (testing "#19744 a post-aggregation expression must not drop first-stage temporal columns from filterable columns"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/breakout (lib/with-temporal-bucket (meta/field-metadata :orders :created-at) :month))
+ (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
+ lib/append-stage
+ (lib/expression "CC" (lib/+ 1 1)))]
+ (is (some #(= "CREATED_AT" (:name %)) (lib/filterable-columns query))))))
+
+(deftest ^:parallel same-name-expression-and-inherited-column-test
+ (testing "#39150 an expression named like an inherited source-card column yields two distinct resolvable columns"
+ (let [mp (lib.tu/metadata-provider-with-card-from-query
+ 1 (lib/query meta/metadata-provider (meta/table-metadata :reviews)))
+ nested (-> (lib/query mp (lib.metadata/card mp 1))
+ (lib/expression "Rating" (lib/+ 1 1)))
+ cols (lib/returned-columns nested)]
+ (is (= 2 (count (filter #(= "Rating" (:display-name %)) cols)))))))
+
+(deftest ^:parallel expression-with-unresolvable-field-ref-does-not-throw-test
+ (testing "#28221 an expression whose inner field id no longer exists must not crash visible-columns / display-info"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/expression "Non-existing field" (lib.options/ensure-uuid [:field {} 9999])))]
+ (is (some? (lib/visible-columns query)))
+ (is (= "Non-existing field"
+ (:display-name (m/find-first :lib/expression-name (lib/visible-columns query))))))))
diff --git a/test/metabase/lib/fe_util_test.cljc b/test/metabase/lib/fe_util_test.cljc
index 8acd71bf9a7..c5cb0e5b213 100644
--- a/test/metabase/lib/fe_util_test.cljc
+++ b/test/metabase/lib/fe_util_test.cljc
@@ -702,6 +702,17 @@
(lib.filter/is-null column)
(lib.filter/and (lib.filter/time-interval column -10 :month) true)))))
+(deftest ^:parallel relative-date-filter-parts-on-temporal-expression-test
+ (testing "QUE-2567 a relative-date filter over a temporal expression column round-trips to date-picker parts"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/expression "Foo" (lib/datetime-add (meta/field-metadata :orders :created-at) 5 :day)))
+ query (lib/filter query (lib/time-interval (lib/expression-ref query "Foo") -12 :month))
+ parts (lib.fe-util/relative-date-filter-parts query -1 (first (lib/filters query)))]
+ (is (some? parts))
+ (is (=? {:value -12
+ :unit :month}
+ parts)))))
+
(deftest ^:parallel exclude-date-filter-parts-test
(let [query (lib.tu/venues-query)
column (m/filter-vals some? (meta/field-metadata :checkins :date))]
diff --git a/test/metabase/lib/field_test.cljc b/test/metabase/lib/field_test.cljc
index baac17282cb..ba0b47c3131 100644
--- a/test/metabase/lib/field_test.cljc
+++ b/test/metabase/lib/field_test.cljc
@@ -651,6 +651,15 @@
(m/find-first (comp #{"myadd"} :name))
(lib/available-binning-strategies query)))))))
+(deftest ^:parallel available-binning-strategies-entity-key-test
+ (testing "PK/FK columns offer no binning strategies or temporal buckets (metabase#16787, metabase#17768)"
+ (let [query (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ id (meta/field-metadata :orders :id)
+ user-id (meta/field-metadata :orders :user-id)]
+ (is (empty? (lib/available-binning-strategies query id)))
+ (is (empty? (lib/available-binning-strategies query user-id)))
+ (is (empty? (lib/available-temporal-buckets query user-id))))))
+
(deftest ^:parallel binning-display-info-test
(testing "numeric binning"
(let [query (lib/query meta/metadata-provider (meta/table-metadata :orders))
@@ -1912,7 +1921,7 @@
(deftest ^:parallel field-values-search-info-test
(testing "type/PK field remapped to a type/Name field within the same table"
- (let [name-field (lib.metadata/field meta/metadata-provider (meta/id :venues :name))
+ (let [name-field (meta/field-metadata :venues :name)
metadata-provider (lib.tu/merged-mock-metadata-provider
meta/metadata-provider
{:fields [{:id (meta/id :venues :id)
@@ -2583,7 +2592,7 @@
(deftest ^:parallel add-field-to-join-disambiguated-by-join-alias-test
(testing "adding a column back to a join that matches a column from a joined native model works (#64779)"
- (let [id-col (-> (lib.metadata/field meta/metadata-provider (meta/id :products :id))
+ (let [id-col (-> (meta/field-metadata :products :id)
(dissoc :table-id :id :fk-target-field-id))
mp (lib.tu/metadata-provider-with-mock-card {:lib/type :metadata/card
:id 1
diff --git a/test/metabase/lib/filter_test.cljc b/test/metabase/lib/filter_test.cljc
index b9ede2ef4fe..2b8ff155973 100644
--- a/test/metabase/lib/filter_test.cljc
+++ b/test/metabase/lib/filter_test.cljc
@@ -812,3 +812,64 @@
"Between" :between
"Is empty" :is-null
"Not empty" :not-null)))
+
+(deftest ^:parallel cross-field-comparison-filter-display-names-test
+ (testing "#15748 a comparison filter between two field refs renders both field names"
+ (check-display-names
+ [{:clause [:< (meta/field-metadata :orders :total) (meta/field-metadata :orders :subtotal)]
+ :name "Total is less than Subtotal"}
+ {:clause [:> (meta/field-metadata :orders :total) (meta/field-metadata :orders :subtotal)]
+ :name "Total is greater than Subtotal"}])))
+
+(deftest ^:parallel multi-value-and-include-current-display-names-test
+ (testing "multi-value equality renders an \"N selections\" display name"
+ (let [city (meta/field-metadata :people :city)]
+ (check-display-names
+ [{:clause [:= city "Indiantown" "Indian Valley"], :name "City is 2 selections"}])))
+ (testing "an include-current relative interval renders the composed column-prefixed sentence"
+ (let [created-at (meta/field-metadata :products :created-at)]
+ (check-display-names
+ [{:clause [:time-interval created-at -1 :month], :options {:include-current true}
+ :name "Created At is in the previous month or this month"}]))))
+
+(deftest ^:parallel max-of-string-column-is-text-typed-test
+ (testing "#21973 #22154 a plain max/min aggregation over a Text column stays Text-typed in a later stage
+ (so the FE offers string filter operators)"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
+ (lib/aggregate (lib/max (meta/field-metadata :people :name)))
+ (lib/breakout (meta/field-metadata :people :source))
+ lib/append-stage)
+ max-col (m/find-first (comp #{"max"} :name) (lib/filterable-columns query))]
+ (is (some? max-col))
+ (is (= :type/Text (lib/type-of query max-col))))))
+
+(deftest ^:parallel distinct-aggregation-and-breakout-filterable-column-test
+ (testing "#36508 a distinct aggregation column is numeric-typed (so the FE offers numeric filter operators)"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :people))
+ (lib/aggregate (lib/distinct (meta/field-metadata :people :email)))
+ (lib/breakout (meta/field-metadata :people :source))
+ lib/append-stage)
+ distinct-col (m/find-first (comp #{"count"} :name) (lib/filterable-columns query))]
+ (is (some? distinct-col))
+ (is (isa? (lib/type-of query distinct-col) :type/Number))))
+ (testing "#25927 a breakout column stays filterable when the stage carries an expression over an aggregation"
+ (let [base (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/breakout (meta/field-metadata :orders :product-id))
+ (lib/aggregate (lib/count))
+ lib/append-stage)
+ count-col (m/find-first (comp #{"count"} :name) (lib/visible-columns base))
+ query (lib/expression base "x2" (lib/* 2 count-col))]
+ (is (some (comp #{"Product ID"} :display-name) (lib/filterable-columns query))))))
+
+(deftest ^:parallel filterable-columns-layered-on-card-source-test
+ (testing "an expression layered on a structured card source is offered as a filterable column"
+ (let [base (lib.tu/query-with-source-card)
+ user-id (m/find-first (comp #{"USER_ID"} :name) (lib/visible-columns base))
+ query (lib/expression base "Total100" (lib/+ user-id 100))]
+ (is (some (comp #{"Total100"} :name) (lib/filterable-columns query)))))
+ (testing "an explicit join layered on a card source exposes the joined table's columns for filtering"
+ (let [base (lib.tu/query-with-source-card)
+ user-id (m/find-first (comp #{"USER_ID"} :name) (lib/visible-columns base))
+ query (lib/join base (lib/join-clause (meta/table-metadata :venues)
+ [(lib/= user-id (meta/field-metadata :venues :id))]))]
+ (is (some (comp #{"PRICE"} :name) (lib/filterable-columns query))))))
diff --git a/test/metabase/lib/join_test.cljc b/test/metabase/lib/join_test.cljc
index 544162ac7ca..9853e0bd386 100644
--- a/test/metabase/lib/join_test.cljc
+++ b/test/metabase/lib/join_test.cljc
@@ -2051,3 +2051,115 @@
{:lib/join-alias "Q2"
:lib/source-column-alias "count"}]
(lib.join/join-fields-to-add-to-parent-stage query -1 (first (lib/joins query -1)) {}))))))
+
+(deftest ^:parallel join-condition-numeric-operand-not-binned-test
+ (testing "#18589 numeric columns used in a join condition are not auto-binned"
+ (let [cnd (lib/= (meta/field-metadata :orders :quantity)
+ (meta/field-metadata :products :rating))]
+ (is (every? #(nil? (get-in % [1 :binning])) (drop 2 cnd))))))
+
+(deftest ^:parallel breakoutable-joined-column-marked-selected-test
+ (testing "#27873 a joined column that is already broken out is marked :selected? in breakoutable-columns"
+ (let [q (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/join (meta/table-metadata :products)))
+ rating (m/find-first #(and (= "RATING" (:name %)) (= :source/joins (:lib/source %)))
+ (lib/breakoutable-columns q))
+ q2 (lib/breakout q rating)
+ rating2 (m/find-first #(and (= "RATING" (:name %)) (= :source/joins (:lib/source %)))
+ (lib/breakoutable-columns q2))]
+ (is (some? rating))
+ (is (= [0] (:breakout-positions (lib/display-info q2 rating2)))))))
+
+(deftest ^:parallel replace-join-condition-literal-with-expression-test
+ (testing "replacing a literal join condition with a column-expression condition keeps a runnable query"
+ (let [q (-> (lib.tu/venues-query)
+ (lib/join (lib/join-clause (meta/table-metadata :categories) [(lib/= 1 1)])))
+ cnd (first (lib/join-conditions (first (lib/joins q))))
+ q' (lib/replace-clause q cnd
+ (lib/= (lib/+ (meta/field-metadata :venues :id) 1)
+ (lib/+ (meta/field-metadata :categories :id) 1)))]
+ (is (=? [[[:= {} [:+ {} [:field {} some?] 1] [:+ {} [:field {} some?] 1]]]]
+ (map lib/join-conditions (lib/joins q')))))))
+
+(deftest ^:parallel model-metadata-wins-over-raw-field-in-join-test
+ (testing "#25113 a model's overridden column metadata wins over raw field metadata when the model is a join source"
+ (let [people-query (lib/query meta/metadata-provider (meta/table-metadata :people))
+ people-cols (lib/returned-columns people-query)
+ result-meta (mapv (fn [col]
+ (cond-> (select-keys col [:id :name :base-type :effective-type :display-name])
+ (= (:id col) (meta/id :people :id))
+ (assoc :display-name "ID renamed")))
+ people-cols)
+ mp (lib.tu/metadata-provider-with-card-from-query
+ meta/metadata-provider 1 people-query
+ {:type :model :name "People Model" :result-metadata result-meta})
+ model (lib.metadata/card mp 1)
+ model-id (m/find-first #(= "ID renamed" (:display-name %))
+ (lib/returned-columns (lib/query mp model)))
+ q (-> (lib/query mp (meta/table-metadata :orders))
+ (lib/join (lib/join-clause model
+ [(lib/= (meta/field-metadata :orders :user-id) model-id)])))
+ joined (m/find-first #(and (= :source/joins (:lib/source %))
+ (= "ID_2" (:name %)))
+ (lib/returned-columns q))]
+ (is (some? model-id))
+ (is (some? joined))
+ (testing "the model's overridden display name wins over raw People.ID metadata"
+ (is (= "People Model - User → ID renamed" (lib/display-name q joined)))))))
+
+(deftest ^:parallel join-native-card-columns-marked-selected-test
+ (testing "#39033 columns are correctly marked :selected? when joining a native card"
+ (let [mp (lib.tu/metadata-provider-with-mock-cards)
+ q1 (:orders/native (lib.tu/mock-cards))
+ q2 (:products/native (lib.tu/mock-cards))
+ query (lib/query mp q1)
+ lhs (m/find-first #(= "PRODUCT_ID" (:name %)) (lib/visible-columns query))
+ rhs (m/find-first #(= "ID" (:name %)) (lib/returned-columns (lib/query mp q2)))
+ joined (lib/join query (-> (lib/join-clause q2 [(lib/= lhs rhs)])
+ (lib/with-join-fields :all)))
+ jn (first (lib/joins joined))]
+ (testing ":fields :all marks every joined column as selected"
+ (let [cols (lib/join-fieldable-columns joined jn)]
+ (is (seq cols) "the join must expose fieldable columns, or `every?` below checks nothing")
+ (is (every? :selected? cols))))
+ (testing "restricting :fields unselects the dropped column"
+ (let [some-cols (drop 1 (lib/join-fieldable-columns joined jn))
+ jn' (lib/with-join-fields jn some-cols)
+ joined2 (lib/replace-clause joined jn jn')
+ jn2 (first (lib/joins joined2))]
+ (is (not (:selected? (first (lib/join-fieldable-columns joined2 jn2))))))))))
+
+(deftest ^:parallel expression-over-joined-model-columns-test
+ (testing "#56602 expressions (coalesce) can reference columns from a joined model"
+ (let [model-query (lib/query meta/metadata-provider (meta/table-metadata :products))
+ mp (lib.tu/metadata-provider-with-card-from-query
+ meta/metadata-provider 1 model-query {:type :model :name "Products Model"})
+ model (lib.metadata/card mp 1)
+ base (lib/query mp (meta/table-metadata :orders))
+ model-id (m/find-first #(= "ID" (:name %)) (lib/returned-columns (lib/query mp model)))
+ joined (lib/join base (lib/join-clause model
+ [(lib/= (meta/field-metadata :orders :product-id) model-id)]))
+ model-price (m/find-first #(and (= "PRICE" (:name %)) (= :source/joins (:lib/source %)))
+ (lib/visible-columns joined))
+ q (lib/expression joined "Coalesced"
+ (lib/coalesce (meta/field-metadata :orders :total) model-price))
+ cc (m/find-first #(= "Coalesced" (:name %)) (lib/returned-columns q))]
+ (is (some? model-price))
+ (is (some? cc))
+ (is (= "Coalesced" (:display-name cc)))))
+ (testing "#58371 a joined column whose name contains a dash renders in expression display names"
+ (let [agg-card (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (-> (lib/count) (lib/with-expression-name "Agg - Dash")))
+ (lib/breakout (meta/field-metadata :orders :product-id)))
+ mp (lib.tu/metadata-provider-with-card-from-query
+ meta/metadata-provider 1 agg-card {:name "Other Question"})
+ card (lib.metadata/card mp 1)
+ base (lib/query mp (meta/table-metadata :products))
+ card-pid (m/find-first #(= "PRODUCT_ID" (:name %)) (lib/returned-columns (lib/query mp card)))
+ joined (lib/join base (lib/join-clause card
+ [(lib/= (meta/field-metadata :products :id) card-pid)]))
+ dash-col (m/find-first #(and (= "Agg - Dash" (:name %)) (= :source/joins (:lib/source %)))
+ (lib/visible-columns joined))]
+ (is (some? dash-col))
+ (testing "the dash-named joined column resolves in the expression display name (not \"Unknown\")"
+ (is (= "0 + Other Question → Agg - Dash" (lib/display-name joined (lib/+ 0 dash-col))))))))
diff --git a/test/metabase/lib/metadata/calculation_test.cljc b/test/metabase/lib/metadata/calculation_test.cljc
index 130943a55ec..19651762a2c 100644
--- a/test/metabase/lib/metadata/calculation_test.cljc
+++ b/test/metabase/lib/metadata/calculation_test.cljc
@@ -1,6 +1,7 @@
(ns metabase.lib.metadata.calculation-test
(:require
#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
+ [clojure.string :as str]
[clojure.test :refer [deftest is testing]]
[medley.core :as m]
[metabase.lib.computed :as lib.computed]
@@ -396,7 +397,7 @@
(let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :reviews))
(lib/join (lib/join-clause (meta/table-metadata :products)))
(lib/join (lib/join-clause (meta/table-metadata :orders))))
- original (lib.metadata/field meta/metadata-provider (meta/id :people :latitude))
+ original (meta/field-metadata :people :latitude)
{latitude "LATITUDE"} (m/index-by :name (lib/visible-columns query))]
(is (some? original))
(is (some? latitude))))
@@ -1217,3 +1218,21 @@
(lib.metadata.calculation/primary-source card-query)))))
(testing "returns nil for a query based on a table"
(is (nil? (lib.metadata.calculation/primary-source-card table-query)))))))
+
+(deftest ^:parallel multi-join-display-names-survive-nesting-test
+ (testing "#40635 multi-join column display names are preserved after wrapping as a nested (card) query"
+ (let [base (as-> (lib/query meta/metadata-provider (meta/table-metadata :orders)) q
+ (lib/join q (-> (lib/join-clause (meta/table-metadata :products)
+ (lib/suggested-join-conditions q (meta/table-metadata :products)))
+ (lib/with-join-fields [(meta/field-metadata :products :id)])))
+ (lib/join q (-> (lib/join-clause (meta/table-metadata :products)
+ [(lib/= (meta/field-metadata :orders :user-id)
+ (meta/field-metadata :products :id))])
+ (lib/with-join-fields [(meta/field-metadata :products :id)]))))
+ mp (lib.tu/metadata-provider-with-card-from-query 1 base)
+ nested (lib/query mp (lib.metadata/card mp 1))
+ nnames (set (map #(lib/display-name nested %) (lib/returned-columns nested)))]
+ (testing "the two joined Product ID columns get distinct disambiguated display names in the nested query"
+ (is (contains? nnames "Products → ID"))
+ (is (contains? nnames "Products - User → ID"))
+ (is (= 2 (count (filter #(str/includes? % "→ ID") nnames))))))))
diff --git a/test/metabase/lib/metadata/result_metadata_test.cljc b/test/metabase/lib/metadata/result_metadata_test.cljc
index 4eb5084f2bc..319499adb07 100644
--- a/test/metabase/lib/metadata/result_metadata_test.cljc
+++ b/test/metabase/lib/metadata/result_metadata_test.cljc
@@ -1173,3 +1173,19 @@
:lib/desired-column-alias "Total_number_of_people_from_each_state_separated_by_state_and_then_we_do_a_count_2"}]
(map #(select-keys % [:lib/source-column-alias :lib/desired-column-alias])
(result-metadata/returned-columns query initial-cols)))))))
+
+(deftest ^:parallel explicit-join-in-card-plus-outer-implicit-join-stay-separate-test
+ (testing "#33972 an implicitly-joined Products.Category carried by a source card and an outer explicit Products.Category join stay distinct"
+ (let [card-q (as-> (lib/query meta/metadata-provider (meta/table-metadata :orders)) q
+ (lib/aggregate q (lib/count))
+ (lib/breakout q (m/find-first #(= (:id %) (meta/id :products :category))
+ (lib/breakoutable-columns q))))
+ mp (lib.tu/metadata-provider-with-card-from-query 1 card-q)
+ outer (-> (lib/query mp (lib.metadata/card mp 1))
+ (lib/join (-> (lib/join-clause (meta/table-metadata :products)
+ [(lib/= (meta/field-metadata :orders :product-id)
+ (meta/field-metadata :products :id))])
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields [(meta/field-metadata :products :category)]))))
+ cols (lib/visible-columns outer)]
+ (is (= 2 (count (filter #(= (:id %) (meta/id :products :category)) cols)))))))
diff --git a/test/metabase/lib/native_test.cljc b/test/metabase/lib/native_test.cljc
index b8e46038581..d030740efe7 100644
--- a/test/metabase/lib/native_test.cljc
+++ b/test/metabase/lib/native_test.cljc
@@ -144,6 +144,99 @@
"SELECT * FROM {{snippet:another snippet}}"
{"snippet: first snippet" (assoc s1 :id s1-uuid)})))))))
+(deftest ^:parallel variable-tag-with-dots-and-underscores-test
+ (testing "dots and underscores are legal in variable names (metabase#15029)"
+ (are [exp input] (= exp (set (keys (lib.native/extract-template-tags meta/metadata-provider input))))
+ #{"number.of.stars"} "select * from products where rating = {{number.of.stars}}"
+ #{"a_b" "c.d"} "select {{a_b}}, {{c.d}}")))
+
+(deftest ^:parallel snippet-inner-tags-surfaced-test
+ (testing "a snippet's own inner template tags are surfaced onto the outer query"
+ (doseq [[description snippets query expected]
+ [["inner variable tag"
+ [{:id 1
+ :name "cat-filter"
+ :content "category = {{category}}"
+ :template-tags {"category" {:name "category"
+ :type :text
+ :display-name "Category"}}}]
+ "select * from products where {{snippet: cat-filter}}"
+ "category"]
+ ["inner card tag"
+ [{:id 1
+ :name "card-ref"
+ :content "id in ({{#123}})"
+ :template-tags {"#123" {:name "#123"
+ :type :card
+ :display-name "#123"
+ :card-id 123}}}]
+ "select * from products where {{snippet: card-ref}}"
+ "#123"]
+ ["inner table tag"
+ [{:id 1
+ :name "table-ref"
+ :content "{{orders}}"
+ :template-tags {"orders" {:name "orders"
+ :type :table
+ :display-name "Orders"
+ :table-id (meta/id :orders)}}}]
+ "select * from {{snippet: table-ref}}"
+ "orders"]
+ ["nested snippet's inner tags"
+ [{:id 1
+ :name "outer"
+ :content "{{snippet: inner}}"
+ :template-tags {"snippet: inner" {:name "snippet: inner"
+ :type :snippet
+ :display-name "Inner"
+ :snippet-name "inner"}}}
+ {:id 2
+ :name "inner"
+ :content "category = {{category}}"
+ :template-tags {"category" {:name "category"
+ :type :text
+ :display-name "Category"}}}]
+ "select * from products where {{snippet: outer}}"
+ "category"]]]
+ (testing description
+ (let [mp (lib.tu/mock-metadata-provider
+ meta/metadata-provider
+ {:native-query-snippets snippets})]
+ (is (contains? (lib.native/extract-template-tags mp query) expected)))))))
+
+(deftest ^:parallel snippet-inner-tag-dedup-test
+ (doseq [[description snippets query expected]
+ [["a local tag and a snippet's surfaced inner tag of the same name collapse to one parameter"
+ [{:id 1
+ :name "s"
+ :content "category = {{filter}}"
+ :template-tags {"filter" {:name "filter"
+ :type :text
+ :display-name "Filter"}}}]
+ "select * from products where {{snippet: s}} and x = {{filter}}"
+ "filter"]
+ ["two snippets sharing an inner tag name dedup to a single entry"
+ [{:id 1
+ :name "s1"
+ :content "a = {{category2}}"
+ :template-tags {"category2" {:name "category2"
+ :type :text
+ :display-name "Category2"}}}
+ {:id 2
+ :name "s2"
+ :content "b = {{category2}}"
+ :template-tags {"category2" {:name "category2"
+ :type :text
+ :display-name "Category2"}}}]
+ "select * from products where {{snippet: s1}} and {{snippet: s2}}"
+ "category2"]]]
+ (testing description
+ (let [mp (lib.tu/mock-metadata-provider
+ meta/metadata-provider
+ {:native-query-snippets snippets})
+ tags (lib.native/extract-template-tags mp query)]
+ (is (= 1 (count (filter #(= expected %) (keys tags)))))))))
+
(def ^:private qp-results-metadata
"Capture of the `data.results_metadata` that would come back when running `SELECT * FROM VENUES;` with the Query
Processor.
diff --git a/test/metabase/lib/order_by_test.cljc b/test/metabase/lib/order_by_test.cljc
index 11b072f2c0a..78cf228e7c3 100644
--- a/test/metabase/lib/order_by_test.cljc
+++ b/test/metabase/lib/order_by_test.cljc
@@ -896,3 +896,18 @@
ref-no-types (lib.options/update-options a-ref dissoc :base-type :effective-type)
query'' (lib/order-by query' ref-no-types)]
(is (= 1 (count (lib/order-bys query'')))))))
+
+(deftest ^:parallel order-by-source-card-expression-breakout-test
+ (testing "#49305 a custom-column breakout inherited from a source card can be used in order-by"
+ (let [q0 (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/expression "CC" (lib/+ (meta/field-metadata :orders :total) 1)))
+ cc (m/find-first #(= "CC" (:name %)) (lib/breakoutable-columns q0))
+ source (-> q0
+ (lib/aggregate (lib/count))
+ (lib/breakout cc))
+ mp (lib.tu/metadata-provider-with-card-from-query 1 source)
+ query (lib/query mp (lib.metadata/card mp 1))
+ cc-col (m/find-first #(= "CC" (:display-name %)) (lib/orderable-columns query))]
+ (is (some? cc-col))
+ (is (=? [[:desc {} [:field {} "CC"]]]
+ (lib/order-bys (lib/order-by query cc-col :desc)))))))
diff --git a/test/metabase/lib/remove_replace_test.cljc b/test/metabase/lib/remove_replace_test.cljc
index cb5820729a8..907e07a41a4 100644
--- a/test/metabase/lib/remove_replace_test.cljc
+++ b/test/metabase/lib/remove_replace_test.cljc
@@ -5,6 +5,7 @@
[medley.core :as m]
[metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
+ [metabase.lib.fe-util :as lib.fe-util]
[metabase.lib.field.util :as lib.field.util]
[metabase.lib.join :as lib.join]
[metabase.lib.metadata :as lib.metadata]
@@ -1798,3 +1799,101 @@
(update-in [:stages 0 :aggregation] (comp vec rest))
(update-in [:stages 1] dissoc :filters))
(lib/remove-clause query 0 cnt0))))))
+
+(deftest ^:parallel removing-previous-stage-filter-keeps-next-stage-expression-test
+ (testing "#14193 removing a stage-0 filter does not drop an unrelated stage-1 expression"
+ (let [q0 (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/filter (lib/> (meta/field-metadata :orders :subtotal) 0))
+ (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
+ lib/append-stage)
+ sum (first (lib/filterable-columns q0))
+ query (lib/expression q0 "Double the fun" (lib/* sum 2))
+ fltr (first (lib/filters query -2))
+ after (lib/remove-clause query -2 fltr)]
+ (is (= 1 (count (lib/expressions after -1))))
+ (is (empty? (lib/filters after -2))))))
+
+(deftest ^:parallel remove-last-expression-unwraps-wrapping-stage-test
+ (testing "#19745 removing the only expression in a wrapping stage collapses it back to a single stage"
+ (let [query (-> (lib.tu/query-with-source-card)
+ lib/append-stage
+ (lib/expression "CC" (lib/+ 1 1)))
+ expr (first (lib/expressions query -1))
+ after (lib/remove-clause query -1 expr)]
+ (is (= 2 (lib/stage-count query)))
+ (is (= 1 (lib/stage-count after))))))
+
+(deftest ^:parallel remove-one-of-two-same-field-self-join-columns-test
+ (testing "#41785 #46756 removing one of two columns that map to the same field but differ by join alias"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :products))
+ (lib/join (-> (lib/join-clause (meta/table-metadata :products)
+ [(lib/= (meta/field-metadata :products :id)
+ (meta/field-metadata :products :id))])
+ (lib/with-join-alias "Products_2")
+ (lib/with-join-fields :all))))
+ ean-2 (m/find-first #(and (= (:id %) (meta/id :products :ean))
+ (= "Products_2" (:lib/join-alias %)))
+ (lib/returned-columns query))
+ query' (lib/remove-field query -1 ean-2)]
+ (is (some? ean-2))
+ (is (= (dec (count (lib/returned-columns query)))
+ (count (lib/returned-columns query'))))
+ (is (some (comp #{"Ean"} :display-name) (lib/returned-columns query'))))))
+
+(deftest ^:parallel remove-join-drops-orphaned-field-refs-test
+ (testing "#17514 removing a join drops references to its columns, leaving a valid query"
+ (let [base (lib.tu/query-with-join)
+ cat-col (m/find-first (comp #{"Cat"} :lib/join-alias) (lib/returned-columns base))
+ query (lib/order-by base cat-col)
+ removed (lib/remove-clause query (first (lib/joins query)))]
+ (is (empty? (lib/joins removed)))
+ (is (not-any? (comp #{"Cat"} :lib/join-alias) (lib/returned-columns removed)))
+ (is (empty? (lib/order-bys removed))))))
+
+(deftest ^:parallel remove-expression-used-in-breakout-cascades-test
+ (testing "#32625 #31635 removing an expression removes a dependent breakout but keeps the aggregation"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/expression "promo" (lib/case [[(lib/> (meta/field-metadata :orders :discount) 0) 1]] 0))
+ (as-> q (lib/breakout q (lib/expression-ref q "promo")))
+ (lib/aggregate (lib/distinct (meta/field-metadata :orders :product-id))))
+ query' (lib/remove-clause query (first (lib/expressions query)))]
+ (is (empty? (lib/expressions query')))
+ (is (empty? (lib/breakouts query')))
+ (is (= 1 (count (lib/aggregations query')))))))
+
+(deftest ^:parallel remove-clause-referencing-missing-field-test
+ (testing "#33835 an aggregation/breakout on a field absent from the metadata provider can still be removed"
+ ;; The query's own metadata provider deliberately omits Orders.total, but the aggregation/breakout is
+ ;; built (via lib) over Orders.total from the full metadata provider, so the ref points at a field the
+ ;; query itself cannot resolve.
+ (let [mp (lib.tu/mock-metadata-provider
+ {:database meta/database
+ :tables [(meta/table-metadata :orders)]
+ :fields (mapv #(meta/field-metadata :orders %) [:id :tax :quantity])})
+ total (meta/field-metadata :orders :total)]
+ (testing "aggregation"
+ (let [query (lib/aggregate (lib/query mp (meta/table-metadata :orders)) (lib/avg total))]
+ (is (= 1 (count (lib/aggregations query))))
+ (is (empty? (lib/aggregations (lib/remove-clause query (first (lib/aggregations query))))))))
+ (testing "binned breakout"
+ (let [query (lib/breakout (lib/query mp (meta/table-metadata :orders))
+ (lib/with-binning total {:strategy :num-bins :num-bins 10}))]
+ (is (= 1 (count (lib/breakouts query))))
+ (is (empty? (lib/breakouts (lib/remove-clause query (first (lib/breakouts query)))))))))))
+
+(deftest ^:parallel remove-first-of-three-sums-keeps-downstream-filter-ref-test
+ (testing "#48752 removing the first of three same-op aggregations keeps a downstream filter pointing at the right one"
+ (let [q (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))
+ (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
+ (lib/aggregate (lib/sum (meta/field-metadata :orders :subtotal)))
+ (lib/aggregate (lib/sum (meta/field-metadata :orders :tax)))
+ (lib/breakout (meta/field-metadata :orders :user-id))
+ lib/append-stage)
+ subtotal-col (m/find-first (comp #{"Sum of Subtotal"} :display-name) (lib/filterable-columns q))
+ q (lib/filter q (lib/>= subtotal-col 10))
+ q' (lib/remove-clause q 0 (first (lib/aggregations q 0)))
+ filter-col (->> (lib/filters q' 1)
+ first
+ (lib.fe-util/number-filter-parts q' 1)
+ :column)]
+ (is (= "Sum of Subtotal" (:display-name (lib/display-info q' 1 filter-col)))))))
diff --git a/test/metabase/lib/schema/expression/string_test.cljc b/test/metabase/lib/schema/expression/string_test.cljc
index dbefac1c9e3..95d610f089a 100644
--- a/test/metabase/lib/schema/expression/string_test.cljc
+++ b/test/metabase/lib/schema/expression/string_test.cljc
@@ -1,8 +1,9 @@
(ns metabase.lib.schema.expression.string-test
(:require
- [clojure.test :refer [are deftest]]
+ [clojure.test :refer [are deftest testing]]
[malli.error :as me]
[metabase.lib.schema]
+ [metabase.lib.schema.expression :as lib.schema.expression]
[metabase.util.malli.registry :as mr]))
(comment metabase.lib.schema/keep-me)
@@ -44,3 +45,20 @@
[:sum
{:lib/uuid "e47d33bc-c89c-48af-bffe-842c815f930a"}
[:field {:lib/uuid "e47d33bc-c89c-48af-bffe-842c815f930b"} 2]]]))
+
+(deftest ^:parallel split-part-position-must-be-positive-test
+ (testing "split-part position must be a positive integer literal"
+ (are [clause] (me/humanize (mr/explain :mbql.clause/split-part clause))
+ [:split-part {:lib/uuid "00000000-0000-0000-0000-000000000000"} "a b" " " 0]
+ [:split-part {:lib/uuid "00000000-0000-0000-0000-000000000000"} "a b" " " -1])
+ (are [clause] (not (me/humanize (mr/explain :mbql.clause/split-part clause)))
+ [:split-part {:lib/uuid "00000000-0000-0000-0000-000000000000"} "a b" " " 1]
+ [:split-part {:lib/uuid "00000000-0000-0000-0000-000000000000"} "a b" " " 2])))
+
+(deftest ^:parallel is-empty-not-empty-accept-string-expressions-test
+ (testing "is-empty / not-empty accept string-typed expressions and string literals (#55687)"
+ (are [clause] (mr/validate ::lib.schema.expression/boolean clause)
+ [:is-empty {:lib/uuid "00000000-0000-0000-0000-000000000000"} [:ltrim {:lib/uuid "00000000-0000-0000-0000-000000000001"} "AAA"]]
+ [:is-empty {:lib/uuid "00000000-0000-0000-0000-000000000000"} "AAA"]
+ [:not-empty {:lib/uuid "00000000-0000-0000-0000-000000000000"} [:ltrim {:lib/uuid "00000000-0000-0000-0000-000000000001"} "AAA"]]
+ [:not-empty {:lib/uuid "00000000-0000-0000-0000-000000000000"} "AAA"])))
diff --git a/test/metabase/measures/api_test.clj b/test/metabase/measures/api_test.clj
index c2c96fecff0..df6b0bc2d18 100644
--- a/test/metabase/measures/api_test.clj
+++ b/test/metabase/measures/api_test.clj
@@ -178,6 +178,30 @@
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "measure/" (u/the-id measure))))))))))
+(deftest data-analyst-readonly-measure-access-test
+ (testing "a data-analyst role (manage-table-metadata, not superuser) can read but not write measures
+ without unrestricted view-data on the underlying table"
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-temp [:model/Measure {measure-id :id} {:table_id (mt/id :venues)
+ :definition (mbql5-measure-definition (mt/id :venues) (mt/id :venues :price))}]
+ (mt/with-data-analyst-role! (mt/user->id :lucky)
+ (testing "GET /api/measure/:id succeeds"
+ (is (=? {:id measure-id}
+ (mt/user-http-request :lucky :get 200 (str "measure/" measure-id)))))
+ (testing "GET /api/measure (list) succeeds and includes the measure"
+ (is (some #(= measure-id (:id %))
+ (mt/user-http-request :lucky :get 200 "measure/"))))
+ (testing "POST /api/measure is still blocked"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :lucky :post 403 "measure"
+ {:name "New Measure"
+ :table_id (mt/id :venues)
+ :definition (mbql5-measure-definition (mt/id :venues) (mt/id :venues :price))}))))
+ (testing "PUT /api/measure/:id is still blocked"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :lucky :put 403 (str "measure/" measure-id)
+ {:name "Updated Name" :revision_message "attempted edit"})))))))))
+
(deftest fetch-measure-test
(testing "GET /api/measure/:id"
(mt/with-temp [:model/Measure {:keys [id]} {:creator_id (mt/user->id :crowberto)
diff --git a/test/metabase/metabot/api/document_test.clj b/test/metabase/metabot/api/document_test.clj
index 950f2de7ee7..7e15d0352ad 100644
--- a/test/metabase/metabot/api/document_test.clj
+++ b/test/metabase/metabot/api/document_test.clj
@@ -5,6 +5,8 @@
[metabase.metabot.scope :as scope]
[metabase.metabot.self.openrouter :as openrouter]
[metabase.metabot.test-util :as mut]
+ [metabase.metabot.tools.sql.create :as create-sql-query-tools]
+ [metabase.query-processor :as qp]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]))
@@ -54,6 +56,45 @@
(is (== 20 (mt/metric-value system :metabase-metabot/llm-output-tokens
{:model "openrouter/anthropic/claude-haiku-4-5" :source "agent"}))))))
+(deftest generate-content-tool-call-produces-draft-card-test
+ (testing "a document_construct_sql_chart tool call round trip produces a :draft_card (#73690)"
+ ;; resolve the test database *before* process-query gets redefed below, so DB sync (which
+ ;; itself calls process-query) isn't affected by the mock
+ (let [db-id (mt/id)]
+ (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
+ (mt/with-dynamic-fn-redefs [create-sql-query-tools/create-sql-query
+ (fn [_]
+ {:validation-result {:valid? true, :dialect "h2"}
+ :action-result {:query-id "q-1"
+ :query {:database db-id
+ :type "native"
+ :native {:query "SELECT COUNT(*) FROM ORDERS"
+ :template-tags {}}}}})
+ qp/process-query (fn [_] nil)
+ openrouter/openrouter
+ (let [call-count (atom 0)]
+ (fn [_]
+ (if (= 1 (swap! call-count inc))
+ (mut/mock-llm-response
+ [{:type :tool-input
+ :id "t1"
+ :function "document_construct_sql_chart"
+ :arguments {:database_id db-id
+ :name "Orders by day"
+ :description "Count of orders"
+ :analysis "Simple count"
+ :approach "Direct SQL"
+ :sql "SELECT COUNT(*) FROM ORDERS"
+ :viz_settings {:chart_type "bar"}}}])
+ (mut/mock-llm-response
+ [{:type :text :text "Chart created"}]))))]
+ (let [response (mt/user-http-request :crowberto
+ :post 200 "metabot/document/generate-content"
+ {:instructions "chart it"})]
+ (is (=? {:error nil
+ :draft_card {:name "Orders by day"}}
+ response))))))))
+
(deftest generate-content-snowplow-test
(mt/with-temporary-setting-values [llm-metabot-provider test-provider]
(binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
diff --git a/test/metabase/metrics/api_dataset_test.clj b/test/metabase/metrics/api_dataset_test.clj
index 0961c3f9bdf..678394f5a72 100644
--- a/test/metabase/metrics/api_dataset_test.clj
+++ b/test/metabase/metrics/api_dataset_test.clj
@@ -15,6 +15,7 @@
{:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.metrics.api-dataset-test]}}}}}}
(:require
[clojure.test :refer :all]
+ [metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.test :as mt]
@@ -1281,3 +1282,33 @@
:projection [[:dimension {} (:id expr-dim)]]}]})]
(is (= "completed" (:status response)))
(is (< 1 (:row_count response)))))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Category 12: Segment and BigInteger Filters |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(deftest dataset-segment-filter-test
+ (testing "POST /api/metric/dataset with a [:segment] filter narrows rows exactly like the underlying filter (#2004)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ total (lib.metadata/field mp (mt/id :orders :total))]
+ (mt/with-temp [:model/Card metric {:name "Orders Count Metric"
+ :type :metric
+ :dataset_query (-> (lib/query mp orders)
+ (lib/aggregate (lib/count)))}
+ :model/Segment {sid :id} {:table_id (mt/id :orders)
+ :definition {:source-table (mt/id :orders)
+ :filter (lib.convert/->legacy-MBQL
+ (lib/> total 100))}}]
+ (let [hydrated (hydrate-metric (:id metric))
+ total-dim (find-dimension-by-name hydrated "TOTAL")]
+ (is (some? total-dim))
+ (let [via-filter (first-result (dataset-request {:expression [:metric {:lib/uuid "a"} (:id metric)]
+ :filters [{:lib/uuid "a"
+ :filter [:> {} [:dimension {} (:id total-dim)] 100]}]}))
+ via-segment (first-result (dataset-request {:expression [:metric {:lib/uuid "a"} (:id metric)]
+ :filters [{:lib/uuid "a"
+ :filter [:segment {} sid]}]}))]
+ (is (pos? via-filter))
+ (is (= via-filter via-segment)))))))))
diff --git a/test/metabase/notification/api/notification_test.clj b/test/metabase/notification/api/notification_test.clj
index 08df718a5f3..ccf666046ed 100644
--- a/test/metabase/notification/api/notification_test.clj
+++ b/test/metabase/notification/api/notification_test.clj
@@ -197,6 +197,22 @@
:details nil}]}]}}
(mt/latest-audit-log-entry))))))))))
+(deftest slack-recipient-persists-channel-id-and-name-test
+ (testing "A Slack recipient's details persist both the display name and the immutable channel_id"
+ (mt/with-model-cleanup [:model/Notification]
+ (mt/with-temp [:model/Card {card-id :id} {}]
+ (let [notification {:payload_type "notification/card"
+ :active true
+ :creator_id (mt/user->id :crowberto)
+ :payload {:card_id card-id}
+ :handlers [{:channel_type :channel/slack
+ :recipients [{:type :notification-recipient/raw-value
+ :details {:value "#work" :channel_id "C001"}}]}]}
+ created (mt/user-http-request :crowberto :post 200 "notification" notification)
+ slack-details (-> created :handlers first :recipients first :details)]
+ (is (=? {:value "#work" :channel_id "C001"}
+ slack-details)))))))
+
(deftest create-notification-error-test
(testing "require auth"
(is (= "Unauthenticated" (mt/client :post 401 "notification"))))
diff --git a/test/metabase/notification/condition_test.clj b/test/metabase/notification/condition_test.clj
index 59fad63a99b..fe5067458cf 100644
--- a/test/metabase/notification/condition_test.clj
+++ b/test/metabase/notification/condition_test.clj
@@ -1,7 +1,12 @@
(ns metabase.notification.condition-test
(:require
[clojure.test :refer :all]
- [metabase.notification.condition :refer [evaluate-expression]]))
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.notification.condition :refer [evaluate-expression]]
+ [metabase.notification.payload.impl.card :as payload.card]
+ [metabase.query-processor.test :as qp]
+ [metabase.test :as mt]))
#_{:clj-kondo/ignore [:equals-true]}
(deftest evaluate-literal-values-test
@@ -139,3 +144,14 @@
["=" ["context" "status"] "active"]
[">" ["context" "score"] 90]]
{:status "inactive", :score 85})))
+
+(deftest goal-condition-evaluates-without-crashing-for-multi-series-card-test
+ (testing "goal_above evaluation doesn't crash for a card with multiple breakout series"
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib.metadata/field mp (mt/id :orders :quantity)))
+ (lib/breakout (lib/with-temporal-bucket (lib.metadata/field mp (mt/id :orders :created_at)) :month)))
+ card {:display :line, :visualization_settings {:graph.goal_value 10}}
+ card-part {:card card, :result (qp/process-query query)}]
+ (is (boolean? (#'payload.card/goal-met? {:send_condition :goal_above} card-part))))))
diff --git a/test/metabase/parameters/dashboard_test.clj b/test/metabase/parameters/dashboard_test.clj
index e99fff1b1d1..9d40b5913fd 100644
--- a/test/metabase/parameters/dashboard_test.clj
+++ b/test/metabase/parameters/dashboard_test.clj
@@ -4,10 +4,14 @@
[clojure.test :refer :all]
[metabase.api.common :as api]
[metabase.dashboards-rest.api-test :as api.dashboard-test]
+ [metabase.lib.convert :as lib.convert]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.parameters.dashboard :as parameters.dashboard]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.permissions.test-util :as perms.test-util]
+ [metabase.query-processor :as qp]
[metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -341,3 +345,91 @@
(is (= products-title-field-id
(#'parameters.dashboard/find-common-remapping-target [orders-product-id-field-id]))
"Should return target for single FK with remapping")))))))
+
+(deftest ^:sequential field-values-without-create-queries-perms-test
+ (testing "a user with view-data but no create-queries permissions still gets field-values for a mapped dashboard param (#47097)"
+ (mt/dataset test-data
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :products)))}
+ :model/Dashboard {dashboard-id :id} {:parameters [{:id "p1"
+ :name "Category"
+ :slug "p1"
+ :type "string/="
+ :sectionId "string"}]}
+ :model/DashboardCard {} {:dashboard_id dashboard-id
+ :card_id card-id
+ :parameter_mappings [{:card_id card-id
+ :parameter_id "p1"
+ :target [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :products :category))))]}]}]
+ (perms.test-util/with-perms-for-group-and-tables!
+ (perms-group/all-users)
+ {(mt/id :products) {:perms/create-queries :no}}
+ (data-perms/disable-perms-cache
+ ;; Mimicks the API endpoint (required):
+ (binding [api/*current-user-id* (mt/user->id :rasta)
+ qp.perms/*param-values-query* true]
+ (let [dashboard (t2/select-one :model/Dashboard :id dashboard-id)
+ {:keys [values]} (parameters.dashboard/param-values dashboard "p1" {})]
+ (is (= #{["Doohickey"] ["Gadget"] ["Gizmo"] ["Widget"]}
+ (set values)))))))))))
+
+(deftest ^:sequential remapped-param-value-with-model-card-test
+ (testing "remapped id-param values work when the mapped source card is a model (#44231)"
+ (mt/dataset test-data
+ (mt/with-temp [:model/Card {model-id :id} {:type :model
+ :dataset_query (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))}
+ :model/Dashboard {dashboard-id :id} {:parameters [{:id "p1"
+ :name "Product ID"
+ :slug "p1"
+ :type "id"
+ :sectionId "id"
+ :default 1}]}
+ :model/DashboardCard {} {:dashboard_id dashboard-id
+ :card_id model-id
+ :parameter_mappings [{:card_id model-id
+ :parameter_id "p1"
+ :target [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :orders :product_id))))]}]}]
+ (mt/with-column-remappings [orders.product_id products.title]
+ (mt/with-full-data-perms-for-all-users!
+ (data-perms/disable-perms-cache
+ (binding [api/*current-user-id* (mt/user->id :rasta)
+ qp.perms/*param-values-query* true]
+ (let [dashboard (t2/select-one :model/Dashboard :id dashboard-id)
+ parameter (first (:parameters dashboard))]
+ (is (= [1 "Rustic Paper Wallet"]
+ (parameters.dashboard/dashboard-param-remapped-value dashboard (:id parameter) 1))))))))))))
+
+(deftest ^:sequential implicit-fk-pk-name-remapped-value-single-field-test
+ (testing "a single-field id param on an FK column resolves via the implicit fk->pk->name remap"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ name-field (lib.metadata/field mp (mt/id :people :name))
+ people-query (-> (lib/query mp (lib.metadata/table mp (mt/id :people)))
+ (lib/filter (lib/= (lib.metadata/field mp (mt/id :people :id)) 1))
+ (lib/with-fields [name-field]))
+ person-name (-> (mt/formatted-rows [str] (qp/process-query people-query))
+ first first)]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))}
+ :model/Dashboard {dashboard-id :id} {:parameters [{:id "p1"
+ :name "User ID"
+ :slug "p1"
+ :type "id"
+ :sectionId "id"}]}
+ :model/DashboardCard {} {:dashboard_id dashboard-id
+ :card_id card-id
+ :parameter_mappings [{:card_id card-id
+ :parameter_id "p1"
+ :target [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :orders :user_id))))]}]}]
+ (mt/with-full-data-perms-for-all-users!
+ (data-perms/disable-perms-cache
+ (binding [api/*current-user-id* (mt/user->id :rasta)
+ qp.perms/*param-values-query* true]
+ (let [dashboard (t2/select-one :model/Dashboard :id dashboard-id)
+ parameter (first (:parameters dashboard))]
+ (is (= [1 person-name]
+ (parameters.dashboard/dashboard-param-remapped-value dashboard (:id parameter) 1))))))))))))
diff --git a/test/metabase/permissions_rest/api_test.clj b/test/metabase/permissions_rest/api_test.clj
index 7da67ab5dc8..3a79a70fb82 100644
--- a/test/metabase/permissions_rest/api_test.clj
+++ b/test/metabase/permissions_rest/api_test.clj
@@ -397,6 +397,32 @@
(do-perm-put "permissions/graph?force=false" 409)))
(do-perm-put "permissions/graph?force=true" 200)))))
+;; NOTE: `oss-preserves-sandboxed-view-data-test` lives in
+;; `metabase-enterprise.sandbox.api.permissions-test`: it references the EE-only `:model/Sandbox` model,
+;; which is not on the OSS classpath. It exercises OSS-token graph semantics under `with-premium-features #{}`.
+
+(deftest oss-edit-create-queries-on-blocked-row-test
+ (testing "PUT /api/permissions/graph in OSS: a create-queries-only edit on a :blocked database returns 200 and bumps view-data to :unrestricted"
+ (mt/with-temp [:model/PermissionsGroup {gid :id} {}
+ :model/Database {db-id :id} {}]
+ (mt/with-premium-features #{:advanced-permissions}
+ (data-perms/set-database-permission! gid db-id :perms/view-data :blocked))
+ (mt/with-premium-features #{}
+ (mt/user-http-request
+ :crowberto :put 200 "permissions/graph"
+ (assoc-in (data-perms.graph/api-graph) [:groups gid db-id :create-queries] :query-builder-and-native))
+ (is (= :unrestricted (data-perms/table-permission-for-groups #{gid} :perms/view-data db-id nil)))))))
+
+(deftest update-graph-response-echoes-only-modified-groups-test
+ (testing "PUT /api/permissions/graph response :groups map contains only the request's modified group ids"
+ (mt/with-temp [:model/PermissionsGroup g1 {} :model/PermissionsGroup g2 {}]
+ (let [body (assoc-in (data-perms.graph/api-graph)
+ [:groups (u/the-id g1) (mt/id) :view-data] :unrestricted)
+ resp (mt/user-http-request :crowberto :put 200 "permissions/graph"
+ (update body :groups select-keys [(u/the-id g1)]))]
+ (is (= #{(u/the-id g1)} (set (keys (:groups resp)))))
+ (is (not (contains? (:groups resp) (u/the-id g2))))))))
+
(deftest can-revoke-permsissions-via-graph-test
(testing "PUT /api/permissions/graph"
(let [table-id (mt/id :venues)]
diff --git a/test/metabase/public_sharing_rest/api_documents_test.clj b/test/metabase/public_sharing_rest/api_documents_test.clj
index 9e4ed3993a0..3d66d73a207 100644
--- a/test/metabase/public_sharing_rest/api_documents_test.clj
+++ b/test/metabase/public_sharing_rest/api_documents_test.clj
@@ -114,6 +114,14 @@
(is (= "Not found."
(mt/client :get 404 (str "public/document/" uuid))))))))))
+(deftest public-document-endpoint-is-read-only-test
+ (testing "PUT /api/public/document/:uuid does not exist -- public document sharing is read-only"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Document document (document-with-public-link {})]
+ (is (= 404
+ (:status (mt/client-full-response :put (str "public/document/" (:public_uuid document))
+ {:name "hacked"}))))))))
+
;;; ------------------------------ GET /api/public/document/:uuid/card/:card-id ---------------------------------------
(deftest fetch-public-document-card-test
diff --git a/test/metabase/public_sharing_rest/api_test.clj b/test/metabase/public_sharing_rest/api_test.clj
index 97a223cf2fd..895b5a068f7 100644
--- a/test/metabase/public_sharing_rest/api_test.clj
+++ b/test/metabase/public_sharing_rest/api_test.clj
@@ -10,6 +10,8 @@
[metabase.analytics.snowplow-test :as snowplow-test]
[metabase.analytics.stats :as stats]
[metabase.dashboards-rest.api-test :as api.dashboard-test]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.parameters.chain-filter-test :as chain-filter-test]
[metabase.parameters.custom-values :as custom-values]
[metabase.permissions.models.permissions :as perms]
@@ -312,6 +314,64 @@
(parse-xlsx-response
(client/client :get 200 (str "public/card/" uuid "/query/xlsx?format_rows=true"))))))))))
+(deftest execute-public-card-with-snippet-test
+ (testing "GET /api/public/card/:uuid/query resolves {{snippet: name}} snippets at execution time"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/NativeQuerySnippet snippet {:name "greeting" :content "'hello'"}]
+ (with-temp-public-card
+ [{uuid :public_uuid}
+ {:dataset_query
+ (lib/with-template-tags
+ (lib/native-query (mt/metadata-provider) "select {{snippet: greeting}}")
+ {"snippet: greeting" {:type :snippet
+ :name "snippet: greeting"
+ :id (str (random-uuid))
+ :snippet-name "greeting"
+ :display-name "Snippet: Greeting"
+ :snippet-id (:id snippet)}})}]
+ (is (= [["hello"]] (mt/rows (client/client :get 202 (str "public/card/" uuid "/query"))))))))))
+
+(deftest execute-public-card-with-referenced-card-template-tag-test
+ (testing "GET /api/public/card/:uuid/query resolves {{#<id>}} referenced-card template tags at execution time"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Card ref-card {:dataset_query (lib/native-query (mt/metadata-provider) "SELECT 1 AS n")}]
+ (let [tag-name (str (:id ref-card) "-ref")]
+ (with-temp-public-card
+ [{uuid :public_uuid}
+ {:dataset_query
+ (lib/with-template-tags
+ (lib/native-query (mt/metadata-provider) (format "select * from {{#%s}}" tag-name))
+ {tag-name {:type :card
+ :name tag-name
+ :id (str (random-uuid))
+ :display-name "Referenced card"
+ :card-id (:id ref-card)}})}]
+ (is (= [[1]] (mt/rows (client/client :get 202 (str "public/card/" uuid "/query")))))))))))
+
+(deftest execute-public-card-with-multi-value-parameter-test
+ (testing "GET /api/public/card/:uuid/query resolves a multi-value (IN (...)) field-filter parameter"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (with-temp-public-card
+ [{uuid :public_uuid}
+ (let [mp (mt/metadata-provider)]
+ {:dataset_query
+ (lib/with-template-tags
+ (lib/native-query mp "SELECT count(*) FROM venues WHERE {{price}}")
+ {"price" {:id "_PRICE_"
+ :name "price"
+ :display-name "Price"
+ :type :dimension
+ :dimension (lib/ref (lib.metadata/field mp (mt/id :venues :price)))
+ :widget-type :category}})
+ :parameters [{:id "_PRICE_" :type :category :target [:dimension [:template-tag "price"]]}]})]
+ (is (=? {:status "completed"
+ :json_query {:parameters [{:id "_PRICE_" :value [1 2]}]}}
+ (client/client :get 202 (str "public/card/" uuid "/query")
+ :parameters (json/encode [{:id "_PRICE_"
+ :type "category"
+ :target ["dimension" ["template-tag" "price"]]
+ :value [1 2]}]))))))))
+
(deftest download-public-card-filename-test
(testing "GET /api/public/card/:uuid/query - filename generation"
(mt/with-temporary-setting-values [enable-public-sharing true]
@@ -660,6 +720,33 @@
(is (= {:name true, :dashcards 2, :tabs 2}
(fetch-public-dashboard (t2/select-one :model/Dashboard :id dashboard-id)))))))))
+(deftest get-public-dashboard-exposes-auto-apply-filters-test
+ (testing "GET /api/public/dashboard/:uuid round-trips the dashboard's auto_apply_filters value"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (with-temp-public-dashboard [dash]
+ (t2/update! :model/Dashboard (:id dash) {:auto_apply_filters false})
+ (is (false? (:auto_apply_filters (client/client :get 200 (str "public/dashboard/" (:public_uuid dash))))))))))
+
+(deftest public-dashboard-with-nested-card-and-parameter-test
+ (testing "GET /api/public/dashboard/:uuid resolves a nested (source-card) query with a mapped parameter (#20393)"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card source-card {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}]
+ (let [nested-query (lib/query mp (lib.metadata/card mp (:id source-card)))]
+ (mt/with-temp [:model/Card nested-card {:dataset_query nested-query}
+ :model/Dashboard dash {:public_uuid (str (random-uuid))
+ :parameters [{:name "Date" :slug "date" :id "d1" :type "date/all-options"}]}
+ :model/DashboardCard _ {:dashboard_id (:id dash)
+ :card_id (:id nested-card)
+ :parameter_mappings [{:parameter_id "d1"
+ :card_id (:id nested-card)
+ :target [:dimension [:field "CREATED_AT" {:base-type :type/DateTime}]]}]}]
+ (is (=? {:parameters [{:id "d1" :slug "date" :type "date/all-options"}]
+ :dashcards [{:card_id (:id nested-card)
+ :parameter_mappings [{:parameter_id "d1"
+ :card_id (:id nested-card)}]}]}
+ (client/client :get 200 (str "public/dashboard/" (:public_uuid dash))))))))))))
+
(deftest public-dashboard-with-implicit-action-only-expose-unhidden-fields
(mt/with-temporary-setting-values [enable-public-sharing true]
(mt/test-drivers (mt/normal-drivers-with-feature :actions)
@@ -829,6 +916,27 @@
:value nil
:id "_VENUE_ID_"}]))))))))))))
+(deftest public-dashboard-visualizer-series-card-test
+ (testing "GET /api/public/dashboard/:uuid exposes visualizer viz-settings and authorizes series-card queries"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (with-temp-public-dashboard [dash]
+ (let [mp (mt/metadata-provider)
+ q (fn [] (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/aggregate (lib/count))))]
+ (mt/with-temp [:model/Card card-1 {:dataset_query (q)}
+ :model/Card card-2 {:dataset_query (q)}]
+ (let [dashcard (add-card-to-dashboard!
+ card-1 dash
+ {:visualization_settings
+ {:visualization {:columnValuesMapping {:COLUMN_1 [{:sourceId (str "card:" (u/the-id card-2))}]}}}})]
+ (mt/with-temp [:model/DashboardCardSeries _ {:dashboardcard_id (u/the-id dashcard) :card_id (u/the-id card-2)}]
+ (testing "public dashboard response exposes the visualizer viz-settings unchanged"
+ (is (=? {:columnValuesMapping {:COLUMN_1 [{:sourceId (str "card:" (u/the-id card-2))}]}}
+ (-> (client/client :get 200 (str "public/dashboard/" (:public_uuid dash)))
+ :dashcards first :visualization_settings :visualization))))
+ (testing "dashcard-query endpoint authorizes the series card via a real DashboardCardSeries row"
+ (is (= 202 (:status (client/client-full-response :get (dashcard-url dash card-2 dashcard))))))))))))))
+
(deftest execute-public-dashcard-as-user-without-perms-test
(testing "GET /api/public/dashboard/:uuid/card/:card-id"
(testing "A user that doesn't have permissions to run the query normally should still be able to run a public DashCard"
@@ -1631,6 +1739,20 @@
:user-id nil}
(last (snowplow-test/pop-event-data-and-user-id!))))))))))))))
+(deftest execute-public-action-implicit-row-update-test
+ (testing "POST /api/public/action/:uuid/execute works for an implicit row/update action"
+ (mt/with-premium-features #{:advanced-permissions}
+ (mt/with-actions-test-data-and-actions-enabled
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (let [mp (mt/metadata-provider)
+ action-opts (assoc (shared-obj) :type :implicit :kind "row/update")]
+ (mt/with-actions [_ {:type :model, :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :categories)))}
+ {} action-opts]
+ (is (=? {:rows-updated 1}
+ (client/client :post 200
+ (format "public/action/%s/execute" (:public_uuid action-opts))
+ {:parameters {:id 1 :name "Bouncy Bears"}}))))))))))
+
(deftest format-export-middleware-test
(mt/with-temporary-setting-values [enable-public-sharing true]
(testing "The `:format-export?` query processor middleware has the intended effect on file exports."
diff --git a/test/metabase/pulse/api/pulse_test.clj b/test/metabase/pulse/api/pulse_test.clj
index 7f35626eee3..43f4c4942fd 100644
--- a/test/metabase/pulse/api/pulse_test.clj
+++ b/test/metabase/pulse/api/pulse_test.clj
@@ -10,6 +10,7 @@
[metabase.channel.impl.http-test :as channel.http-test]
[metabase.channel.settings :as channel.settings]
[metabase.driver :as driver]
+ [metabase.lib.core :as lib]
[metabase.notification.test-util :as notification.tu]
[metabase.permissions.models.permissions :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
@@ -1348,3 +1349,85 @@
(mt/with-temp [:model/PulseChannelRecipient _ {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
(is (= "Not found."
(mt/user-http-request :lucky :delete 404 (str "pulse/" pulse-id "/subscription")))))))))
+
+(deftest unsubscribe-without-collection-perms-test
+ (testing "A recipient without collection perms can still list and unsubscribe from a subscription (#22473)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}
+ :model/Pulse {pulse-id :id} {:creator_id (mt/user->id :crowberto) :dashboard_id dashboard-id}
+ :model/PulseChannel {channel-id :id} {:pulse_id pulse-id :channel_type "email" :schedule_type "daily"}
+ :model/PulseChannelRecipient _ {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
+ (with-pulses-in-nonreadable-collection! [pulse-id]
+ (is (some #(= pulse-id (:id %)) (mt/user-http-request :rasta :get 200 "pulse?creator_or_recipient=true")))
+ (is (nil? (mt/user-http-request :rasta :delete 204 (str "pulse/" pulse-id "/subscription")))))))))
+
+(deftest pulse-slack-channel-persists-channel-id-test
+ (testing "PUT /api/pulse persists the immutable Slack channel_id alongside the channel display name (#...)"
+ (mt/with-temp [:model/Pulse pulse {}
+ :model/Card card {}]
+ (with-pulses-in-writeable-collection! [pulse]
+ (api.card-test/with-cards-in-readable-collection! [card]
+ (let [response (mt/user-http-request :rasta :put 200 (format "pulse/%d" (u/the-id pulse))
+ {:name "Slack Pulse"
+ :cards [{:id (u/the-id card) :include_csv false :include_xls false :dashboard_card_id nil}]
+ :channels [{:enabled true
+ :channel_type "slack"
+ :schedule_type "hourly"
+ :recipients []
+ :details {:channels "#work" :channel_id "C001"}}]})]
+ (is (= {:channels "#work" :channel_id "C001"}
+ (-> response :channels first :details)))))))))
+
+;; Subscription parameter overrides are an EE feature: the OSS `the-parameters` fallback ignores the
+;; request's parameters and uses the dashboard defaults, so this can only pass with EE on the classpath.
+;; The EE app-db jobs run this same file with EE available and cover the override behavior.
+(deftest send-test-pulse-native-query-non-default-parameters-test
+ (mt/when-ee-evailable
+ (testing "POST /api/pulse/test uses the request's explicit parameter override, not the dashboard's persisted default (#18669)"
+ (mt/with-premium-features #{:dashboard-subscription-filters}
+ (let [mp (mt/metadata-provider)
+ query (lib/native-query mp "SELECT {{p}} AS val, 1 AS n")
+ p-tag (get (lib/template-tags query) "p")
+ query (lib/with-template-tags query {"p" (assoc p-tag :required true)})]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query query
+ :display "table"}
+ :model/Dashboard {dashboard-id :id} {:name "Overridable Pulse"
+ :parameters [{:name "P"
+ :slug "p"
+ :id "__P__"
+ :type "category"
+ :default "default-val"}]}
+ :model/DashboardCard _ {:card_id card-id
+ :dashboard_id dashboard-id
+ :parameter_mappings [{:parameter_id "__P__"
+ :card_id card-id
+ :target [:variable [:template-tag "p"]]}]}]
+ (mt/with-fake-inbox
+ (let [channel-messages (pulse.test-util/with-captured-channel-send-messages!
+ (is (= {:ok true}
+ (mt/user-http-request :rasta :post 200 "pulse/test"
+ {:name (mt/random-name)
+ :dashboard_id dashboard-id
+ :parameters [{:id "__P__" :value "override-val"}]
+ :cards [{:id card-id
+ :include_csv false
+ :include_xls false
+ :dashboard_card_id nil}]
+ :channels [{:enabled true
+ :channel_type "email"
+ :schedule_type "daily"
+ :schedule_hour 12
+ :schedule_day nil
+ :recipients [(mt/fetch-user :rasta)]}]
+ :skip_if_empty false}))))
+ content (-> channel-messages :channel/email first :message first :content)]
+ (is (str/includes? content "override-val"))
+ (is (not (str/includes? content "default-val")))))))))))
+
+(deftest archive-pulse-after-dashboard-collection-move-test
+ (testing "PUT /api/pulse/:id {archived: true} succeeds even after the pulse's dashboard moved to another collection (#17658)"
+ (mt/with-temp [:model/Collection coll {}
+ :model/Dashboard {dash-id :id} {}
+ :model/Pulse {pulse-id :id} {:dashboard_id dash-id}]
+ (mt/user-http-request :crowberto :put 200 (str "dashboard/" dash-id) {:collection_id (:id coll)})
+ (is (true? (:archived (mt/user-http-request :crowberto :put 200 (str "pulse/" pulse-id) {:archived true})))))))
diff --git a/test/metabase/pulse/dashboard_subscription_test.clj b/test/metabase/pulse/dashboard_subscription_test.clj
index 75967e95676..b6b282e7186 100644
--- a/test/metabase/pulse/dashboard_subscription_test.clj
+++ b/test/metabase/pulse/dashboard_subscription_test.clj
@@ -4,12 +4,15 @@
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer :all]
+ [medley.core :as m]
[metabase.channel.core :as channel]
[metabase.channel.email.result-attachment :as email.result-attachment]
[metabase.channel.impl.slack :as channel.slack]
[metabase.channel.render.body :as body]
[metabase.channel.render.core :as channel.render]
[metabase.channel.shared :as channel.shared]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.notification.payload.execute :as notification.payload.execute]
[metabase.notification.payload.temp-storage :as notification.temp-storage]
[metabase.notification.test-util :as notification.tu]
@@ -17,6 +20,7 @@
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.pulse.send :as pulse.send]
[metabase.pulse.test-util :as pulse.test-util]
+ [metabase.query-processor.pivot.test-util :as api.pivots]
[metabase.system.core :as system]
[metabase.test :as mt]
[metabase.util :as u]
@@ -1230,6 +1234,45 @@
(mt/summarize-multipart-single-email email
#"Aviary KPIs"))))}}))
+(deftest dashboard-sub-pivot-csv-attachment-test
+ (testing "PulseCard.pivot_results true produces a pivoted (not flat) CSV attachment (#49525)"
+ (let [{:keys [dataset_query visualization_settings]} (api.pivots/pivot-card)
+ header-col-count (fn [pivot?]
+ (let [col-count (atom nil)]
+ (do-test!
+ {:card {:dataset_query dataset_query
+ :display :pivot
+ :visualization_settings visualization_settings}
+ :dashcard {:visualization_settings visualization_settings}
+ :pulse-card {:include_csv true
+ :pivot_results pivot?}
+ :assert
+ {:email
+ (fn [_ [email]]
+ (let [csv-part (m/find-first #(= "text/csv" (:content-type %)) (:message email))]
+ (reset! col-count (-> csv-part :content slurp str/split-lines first (str/split #",") count))))}})
+ @col-count))]
+ (is (not= (header-col-count true) (header-col-count false))
+ "the pivoted CSV header shape must differ from the flat CSV header shape"))))
+
+(deftest dashboard-subscription-email-branding-respects-whitelabel-test
+ (testing "the 'Made with Metabase' footer in dashboard subscription emails respects the :whitelabel premium feature"
+ (let [mp (mt/metadata-provider)
+ query (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ has-branding? (fn [email] (str/includes? (-> email :message first :content) "Made with"))]
+ (mt/with-premium-features #{}
+ (do-test!
+ {:card {:dataset_query query}
+ :assert {:email (fn [_ [email]] (is (true? (has-branding? email))))}}))
+ ;; Whitelabeling is only wired up in EE builds (`enable-whitelabeling?` is gated on
+ ;; `config/ee-available?`), so `:whitelabel` can never hide the footer on OSS builds.
+ ;; The EE app-db jobs run this same file with EE on the classpath and cover the hidden case.
+ (mt/when-ee-evailable
+ (mt/with-premium-features #{:whitelabel}
+ (do-test!
+ {:card {:dataset_query query}
+ :assert {:email (fn [_ [email]] (is (false? (has-branding? email))))}}))))))
+
(deftest multi-series-test
(mt/with-temp
[:model/Card {card-1 :id} {:name "Source card"
diff --git a/test/metabase/pulse/send_test.clj b/test/metabase/pulse/send_test.clj
index c5fd1aadd4f..b96f76df82a 100644
--- a/test/metabase/pulse/send_test.clj
+++ b/test/metabase/pulse/send_test.clj
@@ -9,6 +9,8 @@
[metabase.channel.core :as channel]
[metabase.channel.impl.http-test :as channel.http-test]
[metabase.channel.render.body :as body]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.notification.test-util :as notification.tu]
[metabase.pulse.models.pulse :as models.pulse]
[metabase.pulse.send :as pulse.send]
@@ -693,6 +695,24 @@
(pulse.send/send-pulse! (models.pulse/retrieve-notification pulse-id)))
:channel/email)))))
+(deftest send-pulse-with-no-self-service-creator-test
+ (testing "A dashboard subscription still sends successfully when its creator has no data permissions on the underlying table (#18009)"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Dashboard {dash-id :id} {}
+ :model/Card {card-id :id} {:dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count)))}
+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id}]
+ (mt/with-no-data-perms-for-all-users!
+ (with-pulse-for-card [{pulse-id :id}
+ {:card card-id
+ :pulse {:dashboard_id dash-id :creator_id (mt/user->id :rasta)}
+ :pulse-card {:dashboard_card_id dc-id}}]
+ (mt/with-fake-inbox
+ (let [results (pulse.test-util/with-captured-channel-send-messages!
+ (mt/with-temporary-setting-values [site-url "https://testmb.com"]
+ (pulse.send/send-pulse! (t2/select-one :model/Pulse pulse-id))))]
+ (is (seq (:channel/email results)))))))))))
+
(deftest send-skip-alert-test
(testing "alerts are skipped (#63189)"
(let [pulse-sent-called? (atom false)]
diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.clj
index 82b1cd6e53f..d0c6cb59bb1 100644
--- a/test/metabase/queries/models/card_test.clj
+++ b/test/metabase/queries/models/card_test.clj
@@ -14,6 +14,8 @@
[metabase.lib.test-util.notebook-helpers :as notebook-helpers]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
+ [metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.queries.models.card :as card]
[metabase.queries.models.parameter-card :as parameter-card]
[metabase.queries.schema :as queries.schema]
@@ -990,6 +992,23 @@
(is (=? {:can_run_adhoc_query false}
(t2/hydrate no-query :can_run_adhoc_query)))))))
+(deftest can-run-adhoc-query-respects-create-queries-perm-test
+ (testing "can_run_adhoc_query reflects a non-admin's create-queries permission on the card's table (#13347)"
+ (let [mp (mt/metadata-provider)
+ venues (lib.metadata/table mp (mt/id :venues))
+ query (lib/query mp venues)]
+ (mt/with-temp [:model/Card card {:dataset_query query}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :venues) :perms/create-queries :no)
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (=? {:can_run_adhoc_query false}
+ (t2/hydrate (t2/select-one :model/Card :id (:id card)) :can_run_adhoc_query))))
+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :venues) :perms/create-queries :query-builder)
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (=? {:can_run_adhoc_query true}
+ (t2/hydrate (t2/select-one :model/Card :id (:id card)) :can_run_adhoc_query)))))))))
+
(deftest audit-card-permissions-test
(testing "Cards in audit collections are not readable or writable on OSS, even if they exist (#42645)"
;; Here we're testing the specific scenario where an EE instance is downgraded to OSS, but still has the audit
diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.clj
index ed7106ec5a3..d5c0c9f4551 100644
--- a/test/metabase/queries_rest/api/card_test.clj
+++ b/test/metabase/queries_rest/api/card_test.clj
@@ -4977,3 +4977,270 @@
:value "1"}]})
(is (some? (t2/select-one-fn :result_metadata :model/Card :id card-id))
"result_metadata should be persisted when native card runs with default parameter values")))))
+
+(deftest query-metadata-excludes-unreadable-source-card-test
+ (testing "GET /api/card/:id/query_metadata silently omits a source card the user can't read (collection perms)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {source-coll :id} {}
+ :model/Collection {nested-coll :id} {}
+ :model/Card {source-id :id} {:collection_id source-coll
+ :dataset_query (let [mp (mt/metadata-provider)]
+ (lib/query mp (lib.metadata/table mp (mt/id :orders))))}
+ :model/Card {nested-id :id} {:collection_id nested-coll
+ :dataset_query (let [mp (mt/metadata-provider)]
+ (lib/query mp (lib.metadata/card mp source-id)))}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) nested-coll)
+ (is (empty? (:tables (mt/user-http-request :rasta :get 200 (str "card/" nested-id "/query_metadata")))))
+ (is (seq (:tables (mt/user-http-request :crowberto :get 200 (str "card/" nested-id "/query_metadata")))))))))
+
+(deftest query-metadata-excludes-database-without-create-queries-perm-test
+ (testing "GET /api/card/:id/query_metadata omits a database the user lacks create-queries perms for"
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (let [mp (mt/metadata-provider)]
+ (lib/query mp (lib.metadata/table mp (mt/id :venues))))}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/create-queries :no)
+ (is (empty? (:databases (mt/user-http-request :rasta :get 200 (str "card/" card-id "/query_metadata")))))))))
+
+(deftest offset-card-save-and-query-test
+ (testing "POST /api/card + POST /api/card/:id/query with a saved :offset aggregation (#42323)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created (lib.metadata/field mp (mt/id :orders :created_at))
+ total (lib.metadata/field mp (mt/id :orders :total))
+ query (-> (lib/query mp orders)
+ (lib/breakout (lib/with-temporal-bucket created :month))
+ (lib/aggregate (lib/offset (lib/sum total) -1))
+ (lib/limit 3))]
+ (mt/with-model-cleanup [:model/Card]
+ (let [card (mt/user-http-request :rasta :post 200 "card"
+ (assoc (card-with-name-and-query "Offset card" query)
+ :display "line" :visualization_settings {}))
+ resp (mt/user-http-request :rasta :post 202 (format "card/%d/query" (:id card)))]
+ (is (= 3 (count (get-in resp [:data :rows]))))))))))
+
+(deftest can-run-adhoc-query-nested-card-source-test
+ (testing "can_run_adhoc_query for a card sourced from another card matches the collection-perms model (#23857)"
+ (let [mp (mt/metadata-provider)
+ source-query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]
+ (mt/with-temp [:model/Card source {:dataset_query source-query}]
+ (let [nested-query (lib/query mp (lib.metadata/card mp (:id source)))]
+ (mt/with-temp [:model/Card nested {:dataset_query nested-query}]
+ (mt/with-no-data-perms-for-all-users!
+ (is (=? {:can_run_adhoc_query true}
+ (mt/user-http-request :rasta :get 200 (str "card/" (:id nested)))))
+ (is (=? {:can_run_adhoc_query false}
+ (mt/user-http-request :rasta :get 200 (str "card/" (:id source))))))))))))
+
+(deftest ^:parallel reduced-fields-propagate-to-downstream-card-test
+ (testing "A card with reduced :fields only exposes those columns to a card sourced from it (#30610)"
+ (let [mp (mt/metadata-provider)
+ venues-id (lib.metadata/field mp (mt/id :venues :id))
+ full-query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]
+ (mt/with-temp [:model/Card {source-id :id} (mt/card-with-metadata {:dataset_query full-query})]
+ (mt/user-http-request :crowberto :put 200 (str "card/" source-id)
+ {:dataset_query (lib/with-fields full-query [venues-id])})
+ (let [downstream-query (lib/query mp (lib.metadata/card mp source-id))]
+ (mt/with-temp [:model/Card {downstream-id :id} {:dataset_query downstream-query}]
+ (let [cols (->> (mt/user-http-request :crowberto :post 202 (format "card/%d/query" downstream-id))
+ :data :cols (map (comp u/lower-case-en :name)))]
+ (is (= ["id"] cols)))))))))
+
+(deftest ^:parallel downstream-card-sees-updated-native-source-columns-test
+ (testing "A card built on a native source picks up new columns after the source is edited (#43216)"
+ (mt/with-temp [:model/Card {src :id} {:dataset_query (lib/native-query (mt/metadata-provider)
+ "select 1 as A, 2 as B, 3 as C")}]
+ (mt/user-http-request :crowberto :post 202 (format "card/%d/query" src))
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card {tgt :id} {:dataset_query (lib/query mp (lib.metadata/card mp src))}]
+ (mt/user-http-request :crowberto :put 200 (str "card/" src)
+ {:dataset_query (lib/native-query (mt/metadata-provider)
+ "select 1 as A, 2 as B, 3 as C, 4 as D")})
+ (let [cols (->> (mt/user-http-request :crowberto :get 200 (format "card/%d/query_metadata" tgt))
+ :tables first :fields (map :name))]
+ (is (some #{"D"} cols))))))))
+
+(deftest copy-card-preserves-non-default-display-test
+ (testing "POST /api/card/:id/copy preserves a non-default display and viz settings"
+ (mt/with-model-cleanup [:model/Card]
+ (let [mp (mt/metadata-provider)
+ query (lib/aggregate (lib/query mp (lib.metadata/table mp (mt/id :venues))) (lib/count))]
+ (mt/with-temp [:model/Card card {:display :list
+ :visualization_settings {:list.columns ["ID"]}
+ :dataset_query query}]
+ (let [newcard (mt/user-http-request :rasta :post 200 (format "card/%d/copy" (u/the-id card)))]
+ (is (=? {:display "list"
+ :visualization_settings {:list.columns ["ID"]}}
+ newcard))))))))
+
+(deftest ^:parallel model-metadata-settings-override-preserved-test
+ (testing "Column-level :settings overrides (e.g. show_mini_bar) persist through result_metadata PUT"
+ (mt/with-temp [:model/Card card (assoc (mt/card-with-metadata
+ {:dataset_query (let [mp (mt/metadata-provider)]
+ (lib/query mp (lib.metadata/table mp (mt/id :orders))))})
+ :type :model)]
+ (let [metadata (t2/select-one-fn :result_metadata :model/Card :id (u/the-id card))
+ edited (mapv #(if (= (:name %) "SUBTOTAL") (assoc % :settings {:show_mini_bar true}) %) metadata)
+ updated (mt/user-http-request :crowberto :put 200 (str "card/" (u/the-id card))
+ {:result_metadata edited})]
+ (is (=? {:show_mini_bar true}
+ (->> updated :result_metadata (m/find-first #(= (:name %) "SUBTOTAL")) :settings)))))))
+
+(deftest ^:parallel put-card-persists-fk-relation-override-on-computed-column-test
+ (testing "PUT /api/card/:id persists a user-set FK relation on a column with no numeric :id (#29318)"
+ (mt/with-temp [:model/Card card (assoc (mt/card-with-metadata
+ {:dataset_query (lib/native-query (mt/metadata-provider)
+ "SELECT USER_ID FROM ORDERS LIMIT 5")})
+ :type :model)]
+ (let [target-id (mt/id :people :id)
+ new-metadata (mapv #(assoc % :semantic_type :type/FK :fk_target_field_id target-id)
+ (:result_metadata card))
+ updated (mt/user-http-request :crowberto :put 200 (str "card/" (:id card))
+ {:result_metadata new-metadata})]
+ (is (every? #(= "type/FK" (:semantic_type %)) (:result_metadata updated)))))))
+
+(deftest ^:parallel expression-column-display-name-override-survives-query-change-test
+ (testing "display_name override on an expression column survives a dataset_query change (#36161)"
+ (let [mp (mt/metadata-provider)
+ venues-id (lib.metadata/field mp (mt/id :venues :id))
+ base-query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/expression "ID2" venues-id))
+ expr-col (m/find-first (comp #{"ID2"} :name) (lib/returned-columns base-query))
+ query (lib/with-fields base-query [expr-col])]
+ (mt/with-temp [:model/Card card (assoc (mt/card-with-metadata {:dataset_query query}) :type :model)]
+ (let [edited (mapv #(assoc % :display_name "ID2 custom")
+ (t2/select-one-fn :result_metadata :model/Card :id (:id card)))
+ updated (mt/user-http-request :crowberto :put 200 (str "card/" (:id card)) {:result_metadata edited})
+ updated2 (mt/user-http-request :crowberto :put 200 (str "card/" (:id card))
+ {:dataset_query (lib/limit query 5)})]
+ (is (= ["ID2 custom"] (map :display_name (:result_metadata updated))))
+ (is (= ["ID2 custom"] (map :display_name (:result_metadata updated2)))))))))
+
+(deftest renaming-joined-column-metadata-does-not-break-model-query-test
+ (testing "Renaming a joined column's display_name override should not break re-running the model (#57359)"
+ (mt/with-model-cleanup [:model/Card]
+ (let [mp (mt/metadata-provider)
+ orders-table (lib.metadata/table mp (mt/id :orders))
+ products-table (lib.metadata/table mp (mt/id :products))
+ products-id (lib.metadata/field mp (mt/id :products :id))
+ products-created (lib.metadata/field mp (mt/id :products :created_at))
+ orders-id (lib.metadata/field mp (mt/id :orders :id))
+ orders-product-id (lib.metadata/field mp (mt/id :orders :product_id))
+ query (-> (lib/query mp orders-table)
+ (lib/with-fields [orders-id orders-product-id])
+ (lib/join (-> (lib/join-clause products-table
+ [(lib/= orders-product-id products-id)])
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields [products-id products-created]))))
+ card (mt/user-http-request :rasta :post 200 "card"
+ (assoc (card-with-name-and-query "model 57359" query)
+ :type :model :display :table))
+ renamed (mapv #(cond-> % (= (:name %) "ID_2") (assoc :display_name "Product ID2"))
+ (:result_metadata card))
+ updated (mt/user-http-request :rasta :put 200 (str "card/" (:id card)) {:result_metadata renamed})]
+ (is (some #(= "Product ID2" (:display_name %)) (:result_metadata updated)))
+ (is (=? {:data {:rows some?}}
+ (mt/user-http-request :rasta :post 202 (format "card/%d/query" (:id card)))))))))
+
+(deftest model-source-table-change-uses-fresh-ids-for-permissions-test
+ (testing "Changing an MBQL model's source table re-derives result_metadata ids for permissions (#67680)"
+ (mt/with-premium-features #{}
+ (mt/with-temp-copy-of-db
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :orders) :perms/view-data :blocked)
+ (data-perms/set-table-permission! (perms-group/all-users) (mt/id :products) :perms/view-data :unrestricted)
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/create-queries :query-builder)
+ (let [mp (mt/metadata-provider)
+ orders-query (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ products-query (lib/query mp (lib.metadata/table mp (mt/id :products)))]
+ (mt/with-temp [:model/Card {card-id :id} (assoc (mt/card-with-metadata {:dataset_query orders-query})
+ :type :model)]
+ (mt/user-http-request :rasta :put 200 (str "card/" card-id) {:dataset_query products-query})
+ (is (=? {:status "completed"}
+ (mt/user-http-request :rasta :post (format "card/%d/query" card-id)))))))))))
+
+(deftest create-model-with-snippet-template-tag-test
+ (testing "POST /api/card: a native query using only a snippet tag can be saved as a model (#20963)"
+ (mt/with-temp [:model/NativeQuerySnippet snippet {:name "cat" :content "category = 'Gizmo'"}]
+ (mt/with-model-cleanup [:model/Card]
+ (let [mp (mt/metadata-provider)
+ query (lib/native-query mp (format "select * from products where {{snippet: %s}}" (:name snippet)))]
+ (is (=? {:id pos-int?}
+ (mt/user-http-request :rasta :post 200 "card"
+ (assoc (card-with-name-and-query "model with snippet" query)
+ :type :model :display :table)))))))))
+
+(deftest create-model-without-result-metadata-test
+ (testing "POST /api/card currently allows saving a native-query model without an explicit result_metadata (#37009 gap)"
+ (mt/with-model-cleanup [:model/Card]
+ (is (=? {:id pos-int?}
+ (mt/user-http-request :rasta :post 200 "card"
+ (assoc (card-with-name-and-query
+ "model no metadata"
+ (lib/native-query (mt/metadata-provider) "select * from products"))
+ :type :model :display :table)))))))
+
+(deftest copy-card-preserves-nested-query-test
+ (testing "POST /api/card/:id/copy preserves a multi-stage query verbatim, doesn't reference the original (#31309)"
+ (mt/with-model-cleanup [:model/Card]
+ (let [mp (mt/metadata-provider)
+ orders-table (lib.metadata/table mp (mt/id :orders))
+ people-table (lib.metadata/table mp (mt/id :people))
+ orders-total (lib.metadata/field mp (mt/id :orders :total))
+ orders-user-id (lib.metadata/field mp (mt/id :orders :user_id))
+ people-id (lib.metadata/field mp (mt/id :people :id))
+ people-name (lib.metadata/field mp (mt/id :people :name))
+ base-query (-> (lib/query mp orders-table)
+ (lib/join (lib/join-clause people-table [(lib/= orders-user-id people-id)]))
+ (lib/aggregate (lib/sum orders-total))
+ (lib/breakout people-name))
+ query2 (lib/append-stage base-query)
+ sum-col (m/find-first (comp #{"sum"} :name) (lib/returned-columns query2))
+ query (-> query2
+ (lib/filter (lib/< sum-col 5000))
+ (lib/limit 10))
+ card (mt/user-http-request :rasta :post 200 "card"
+ (assoc (card-with-name-and-query "orig" query)
+ :display :table :type :model))
+ newcard (mt/user-http-request :rasta :post 200 (format "card/%d/copy" (u/the-id card)))]
+ (is (= (:dataset_query card) (:dataset_query newcard)))
+ (is (not (some #{(str "card__" (u/the-id card))}
+ (tree-seq coll? seq (:dataset_query newcard)))))))))
+
+(deftest can-fetch-and-query-metric-sourced-from-inaccessible-model-test
+ (testing "GET/POST card endpoints don't require collection-read on nested source cards they reference"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection model-coll {}
+ :model/Collection metric-coll {}
+ :model/Card model {:type "model"
+ :collection_id (u/the-id model-coll)
+ :dataset_query (let [mp (mt/metadata-provider)]
+ (lib/query mp (lib.metadata/table mp (mt/id :orders))))}
+ :model/Card metric {:type "metric"
+ :collection_id (u/the-id metric-coll)
+ :dataset_query (let [mp (mt/metadata-provider)]
+ (lib/aggregate
+ (lib/query mp (lib.metadata/card mp (u/the-id model)))
+ (lib/count)))}]
+ (perms/grant-collection-read-permissions! (perms-group/all-users) metric-coll)
+ (is (=? {:id (u/the-id metric)}
+ (mt/user-http-request :rasta :get 200 (str "card/" (u/the-id metric)))))
+ (is (=? {:status "completed"}
+ (mt/user-http-request :rasta :post (str "card/" (u/the-id metric) "/query"))))))))
+
+(deftest native-card-ref-runs-with-no-data-perms-test
+ (testing "A native card referencing another native card via {{#id}} runs for a user with no query-building data perms (#216)"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card inner {:collection_id (u/the-id collection)
+ :dataset_query (lib/native-query (mt/metadata-provider)
+ "select * from people where id < 10")}]
+ (mt/with-non-admin-groups-no-collection-perms collection
+ (perms/grant-collection-read-permissions! (perms-group/all-users) collection)
+ (let [mp (mt/metadata-provider)
+ outer-sql (format "select count(*) from {{#%d}}" (u/the-id inner))
+ outer-query (lib/native-query mp outer-sql)]
+ (mt/with-temp [:model/Card outer {:collection_id (u/the-id collection) :dataset_query outer-query}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/create-queries :no)
+ (is (= [[9]] (mt/rows (mt/user-http-request :rasta :post 202 (format "card/%d/query" (u/the-id outer)))))))))))))
diff --git a/test/metabase/queries_rest/api/cards_test.clj b/test/metabase/queries_rest/api/cards_test.clj
index 018efaaf342..7e426fc646d 100644
--- a/test/metabase/queries_rest/api/cards_test.clj
+++ b/test/metabase/queries_rest/api/cards_test.clj
@@ -34,6 +34,17 @@
(->> (mt/user-http-request :rasta :post 200 "cards/dashboards" {:card_ids [card-id]})
(map #(update % :dashboards set)))))))))
+(deftest ^:parallel dashboards-for-cards-includes-series-only-test
+ (testing "POST /api/cards/dashboards reports a dashboard where the card appears only as a dashcard series"
+ (mt/with-temp [:model/Card series-card {}
+ :model/Card primary-card {}
+ :model/Dashboard {dash-id :id dash-name :name} {}
+ :model/DashboardCard dc {:card_id (:id primary-card) :dashboard_id dash-id}
+ :model/DashboardCardSeries _ {:dashboardcard_id (:id dc) :card_id (:id series-card) :position 0}]
+ (is (= [{:card_id (:id series-card)
+ :dashboards [{:id dash-id :name dash-name}]}]
+ (mt/user-http-request :rasta :post 200 "cards/dashboards" {:card_ids [(:id series-card)]}))))))
+
(deftest ^:parallel bulk-move-endpoint-works
(testing "a simple move"
(mt/with-temp [:model/Card {card-id :id} {}
diff --git a/test/metabase/query_processor/aggregation_test.clj b/test/metabase/query_processor/aggregation_test.clj
index 282985b8f48..d49f9f71b1c 100644
--- a/test/metabase/query_processor/aggregation_test.clj
+++ b/test/metabase/query_processor/aggregation_test.clj
@@ -465,3 +465,175 @@
;; ! tests for named aggregations can be found in `expression-aggregations-test` !
;; ! !
;; !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+(deftest ^:parallel min-max-non-numeric-test
+ (mt/test-drivers (mt/normal-drivers)
+ (let [mp (mt/metadata-provider)]
+ (testing "min/max over a Text column return the lexical extremes (#18207, #22155)"
+ (let [category (lib.metadata/field mp (mt/id :products :category))
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/aggregate (lib/min category))
+ (lib/aggregate (lib/max category)))]
+ (is (= [["Doohickey" "Widget"]]
+ (mt/formatted-rows [str str] (qp/process-query query))))))
+ (testing "min/max over a temporal column return temporal values (#4482)"
+ (let [created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/min created-at))
+ (lib/aggregate (lib/max created-at)))
+ row (first (mt/rows (qp/process-query query)))]
+ (is (= 2 (count row)))
+ (is (every? some? row)))))))
+
+(deftest ^:parallel count-with-field-arg-test
+ (mt/test-drivers (mt/normal-drivers)
+ (testing "count with a field argument counts only non-null values of that field (#13814)"
+ ;; orders.discount is NULL for most rows, so count(discount) must skip the NULLs: it equals
+ ;; the non-null count and is strictly less than count(*). A regression to COUNT(*) fails both.
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ discount (lib.metadata/field mp (mt/id :orders :discount))
+ [total cnt-field] (->> (-> (lib/query mp orders)
+ (lib/aggregate (lib/count))
+ (lib/aggregate (lib/count discount)))
+ qp/process-query
+ (mt/formatted-rows [int int]) first)
+ non-null (->> (-> (lib/query mp orders)
+ (lib/filter (lib/not-null discount))
+ (lib/aggregate (lib/count)))
+ qp/process-query
+ (mt/formatted-rows [int]) ffirst)]
+ (is (= non-null cnt-field))
+ (is (< cnt-field total))))))
+
+(deftest ^:parallel distinct-case-with-breakout-and-expression-test
+ (mt/test-drivers (mt/normal-drivers)
+ (testing "Distinct(case(...)) with a breakout and an extra custom column executes without error (#17512)"
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ discount (lib.metadata/field mp (mt/id :orders :discount))
+ subtotal (lib.metadata/field mp (mt/id :orders :subtotal))
+ total (lib.metadata/field mp (mt/id :orders :total))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ result (-> (lib/query mp orders)
+ (lib/expression "CC" (lib/+ 1 1))
+ (lib/aggregate (lib/distinct (lib/case [[(lib/> discount 0) subtotal]] total)))
+ (lib/breakout (lib/with-temporal-bucket created-at :month))
+ qp/process-query)]
+ (is (=? {:status :completed} result))
+ ;; coerce the count column via formatted-rows so pos-int? holds for drivers that return it as BigDecimal
+ (let [rows (mt/formatted-rows [str int] result)]
+ (is (seq rows))
+ (testing "each breakout row carries a positive distinct count"
+ (is (every? (fn [[_month cnt]] (pos-int? cnt)) rows))))))))
+
+(deftest ^:parallel num-bins-width-uses-filtered-range-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :binning)
+ (testing "a num-bins binned breakout derives its bin width from the FILTERED range, not the full range (#42942)"
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ total (lib.metadata/field mp (mt/id :orders :total))]
+ (letfn [(bin-width [min-total]
+ (let [edges (->> (-> (lib/query mp orders)
+ (lib/filter (lib/>= total min-total))
+ (lib/breakout (lib/with-binning total {:strategy :num-bins, :num-bins 100}))
+ (lib/aggregate (lib/count))
+ qp/process-query
+ mt/rows)
+ (map (comp double first))
+ sort)]
+ (apply min (map - (rest edges) edges))))]
+ ;; a filter that narrows the range to a smaller window must yield a finer bin width
+ (is (< (bin-width 150) (bin-width 90))))))))
+
+(deftest ^:parallel nested-median-over-expression-and-aggregation-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :percentile-aggregations :nested-queries :expressions)
+ (testing "Median over a custom column, then a second stage taking Median of that median"
+ (let [mp (mt/metadata-provider)
+ price (lib.metadata/field mp (mt/id :products :price))
+ category (lib.metadata/field mp (mt/id :products :category))
+ q1 (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/expression "Mega" (lib/* price 10))
+ (as-> $ (lib/aggregate $ (lib/median (lib/expression-ref $ "Mega"))))
+ (lib/breakout category)
+ lib/append-stage)
+ ;; Reference the stage-1 median aggregation column by its display name. Matching the wrong column here
+ ;; (e.g. the non-existent "Mega") yields `(lib/median nil)` -> `MEDIAN(NULL)`, which returns NULL on H2
+ ;; and errors on Oracle/Redshift/SQL Server. The real median column keeps the aggregation numeric.
+ mega-col (m/find-first (comp #{"Median of Mega"} :display-name) (lib/aggregable-columns q1 nil))
+ _ (assert (some? mega-col))
+ q2 (lib/aggregate q1 (lib/median mega-col))
+ rows (mt/rows (qp/process-query q2))]
+ (is (= 1 (count rows)))
+ ;; a real median-of-medians value (not a NULL artifact from a mis-resolved column ref)
+ (is (number? (ffirst rows)))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Measure Edge Cases |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(defn- orders-measure-provider
+ "Metadata provider that exposes `definition` as measure 1 on the orders table."
+ [mp definition]
+ (lib.tu/mock-metadata-provider
+ mp
+ {:measures [{:id 1
+ :name "the measure"
+ :table-id (mt/id :orders)
+ :definition definition}]}))
+
+(deftest ^:parallel measure-with-offset-test
+ (testing "a measure whose definition uses an offset() window executes like the equivalent inline aggregation"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ total (lib.metadata/field mp (mt/id :orders :total))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ definition (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/offset (lib/sum total) -1)))
+ mp (orders-measure-provider mp definition)
+ measure-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib.metadata/measure mp 1))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))
+ direct-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/offset (lib/sum total) -1))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))]
+ ;; round the numeric column: Presto's distributed SUM is ULP-nondeterministic across the two runs
+ (is (= (mt/formatted-rows [str 2.0] (qp/process-query direct-query))
+ (mt/formatted-rows [str 2.0] (qp/process-query measure-query))))))))
+
+(deftest ^:parallel measure-with-implicit-join-column-test
+ (testing "a measure aggregating an implicit-join column executes like the equivalent inline aggregation"
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join)
+ (let [mp (mt/metadata-provider)
+ orders-q (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ rating (m/find-first (comp #{(mt/id :products :rating)} :id)
+ (lib/visible-columns orders-q))
+ _ (assert (some? rating))
+ definition (lib/aggregate orders-q (lib/sum rating))
+ mp (orders-measure-provider mp definition)
+ measure-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib.metadata/measure mp 1)))
+ direct-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/sum rating)))]
+ ;; round the numeric column: Presto's distributed SUM is ULP-nondeterministic across the two runs
+ (is (= (mt/formatted-rows [2.0] (qp/process-query direct-query))
+ (mt/formatted-rows [2.0] (qp/process-query measure-query))))))))
+
+(deftest ^:parallel offset-of-measure-test
+ (testing "wrapping a measure ref in offset() executes like the equivalent inline offset aggregation"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ total (lib.metadata/field mp (mt/id :orders :total))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ definition (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/sum total)))
+ mp (orders-measure-provider mp definition)
+ measure-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/offset (lib.metadata/measure mp 1) -1))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))
+ direct-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/offset (lib/sum total) -1))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))]
+ ;; round the numeric column: Presto's distributed SUM is ULP-nondeterministic across the two runs
+ (is (= (mt/formatted-rows [str 2.0] (qp/process-query direct-query))
+ (mt/formatted-rows [str 2.0] (qp/process-query measure-query))))))))
diff --git a/test/metabase/query_processor/binning_test.clj b/test/metabase/query_processor/binning_test.clj
index e4b684bd4f0..d06903157c2 100644
--- a/test/metabase/query_processor/binning_test.clj
+++ b/test/metabase/query_processor/binning_test.clj
@@ -3,11 +3,14 @@
(:require
[clojure.test :refer [deftest is testing]]
[medley.core :as m]
+ [metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-util :as lib.tu]
[metabase.query-processor.test :as qp]
- [metabase.test :as mt]))
+ [metabase.query-processor.test-util :as qp.test-util]
+ [metabase.test :as mt]
+ [metabase.util :as u]))
(deftest ^:parallel binning-in-result-cols-display-name-test
(doseq [[table-key field-key binning-name expected-display-name]
@@ -80,6 +83,18 @@
[137.5 6]]
(mt/formatted-rows [2.0 int] (qp/process-query query')))))))
+(deftest ^:parallel bucket-implicitly-joined-column-test
+ (testing "temporal bucketing an implicitly-joined column executes and gets an fk-prefixed display name (metabase#15648, metabase#16674)"
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count)))
+ birth (m/find-first #(= (:id %) (mt/id :people :birth_date))
+ (lib/breakoutable-columns query))
+ query (lib/breakout query (lib/with-temporal-bucket birth :year))
+ res (qp/process-query query)]
+ (is (= "User → Birth Date: Year" (-> res mt/cols first :display_name)))
+ (is (seq (mt/rows res))))))
+
(deftest ^:parallel multiple-bins-on-same-column-test
(let [query (lib/query
(mt/metadata-provider)
@@ -103,3 +118,58 @@
[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))))))
+
+(deftest ^:parallel temporal-bucket-on-native-source-card-test
+ (testing "default temporal bucket for a native source card's datetime column resolves to Month (not Minute) via result_metadata (metabase#16671)"
+ (let [mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
+ [(lib.convert/->legacy-MBQL (lib/native-query (mt/metadata-provider) "SELECT CREATED_AT FROM ORDERS"))])
+ q (lib/query mp (lib.metadata/card mp 1))
+ col (m/find-first (comp #{"created_at"} u/lower-case-en :name) (lib/breakoutable-columns q))]
+ (is (some? col))
+ (is (some :default (filter (comp #{:month} :unit) (lib/available-temporal-buckets q col))))
+ (is (seq (mt/rows (qp/process-query
+ (-> q
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket col :year))))))))))
+
+(deftest ^:parallel binning-on-native-source-card-test
+ (testing "auto/explicit binning for a native source card's column is driven by result_metadata fingerprint (metabase#16670, metabase#16672)"
+ (doseq [[sql col-name strategy-display-name]
+ [["SELECT TOTAL FROM ORDERS" "TOTAL" "Auto bin"]
+ ["SELECT LONGITUDE FROM PEOPLE" "LONGITUDE" "Bin every 10 degrees"]]]
+ (testing (format "%s on %s" strategy-display-name col-name)
+ (let [mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
+ [(lib.convert/->legacy-MBQL (lib/native-query (mt/metadata-provider) sql))])
+ q (lib/query mp (lib.metadata/card mp 1))
+ col (m/find-first (comp #{(u/lower-case-en col-name)} u/lower-case-en :name) (lib/breakoutable-columns q))
+ strat (m/find-first (comp #{strategy-display-name} :display-name)
+ (lib/available-binning-strategies q col))]
+ (is (some? col))
+ (is (some? strat))
+ (is (seq (mt/rows (qp/process-query
+ (-> q
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-binning col strat))))))))))))
+
+(deftest ^:parallel post-aggregation-filter-on-same-column-breakouts-test
+ (testing "a later stage can filter on each of two disambiguated same-column breakout columns (metabase#46536, metabase#46776)"
+ (let [mp (mt/metadata-provider)
+ base (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ total (m/find-first #(= (:id %) (mt/id :orders :total))
+ (lib/breakoutable-columns base))
+ unfiltered (-> base
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-binning total {:strategy :num-bins, :num-bins 10}))
+ (lib/breakout (lib/with-binning total {:strategy :num-bins, :num-bins 50}))
+ lib/append-stage)
+ ;; the two same-column breakouts surface as distinct filterable columns (same field id, different
+ ;; source-column-alias, e.g. TOTAL / TOTAL_2); filter both to prove they resolve independently
+ total-cols (filter #(= (:id %) (mt/id :orders :total)) (lib/filterable-columns unfiltered))
+ filtered (reduce (fn [q c] (lib/filter q (lib/between c 10 50))) unfiltered total-cols)
+ n-all (count (mt/rows (qp/process-query unfiltered)))
+ n-filtered (count (mt/rows (qp/process-query filtered)))]
+ (is (= 2 (count total-cols)))
+ ;; filtering on both disambiguated same-column breakout outputs matches some rows and is strictly narrower than
+ ;; the unfiltered two-breakout result — proving the two same-column breakouts resolve as distinct columns.
+ (is (pos? n-filtered))
+ (is (< n-filtered n-all)))))
diff --git a/test/metabase/query_processor/breakout_test.clj b/test/metabase/query_processor/breakout_test.clj
index c91ea626435..26593603f6b 100644
--- a/test/metabase/query_processor/breakout_test.clj
+++ b/test/metabase/query_processor/breakout_test.clj
@@ -6,6 +6,7 @@
[clojure.test :refer :all]
[medley.core :as m]
[metabase.driver :as driver]
+ [metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-util :as lib.tu]
@@ -365,6 +366,44 @@
[-80.0 2275]]
(mt/formatted-rows [1.0 int] (qp/process-query query)))))))))))
+(deftest ^:parallel binning-with-source-card-with-explicit-joins-temporal-and-numeric-test
+ (testing "Temporal bucketing and numeric binning work on explicitly-joined columns off a source card (metabase#15446, metabase#16675, metabase#16693)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :binning :nested-queries :left-join)
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ field (fn [t c] (lib.metadata/field mp0 (mt/id t c)))
+ base (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ people (lib.metadata/table mp0 (mt/id :people))
+ products (lib.metadata/table mp0 (mt/id :products))
+ people-join (-> (lib/join-clause people (lib/suggested-join-conditions base people))
+ (lib/with-join-alias "People")
+ (lib/with-join-fields [(lib/with-temporal-bucket (field :people :birth_date) :default)]))
+ products-join (-> (lib/join-clause products (lib/suggested-join-conditions base products))
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields [(field :products :price)]))
+ source-card-query (-> base
+ (lib/join people-join)
+ (lib/join products-join)
+ (lib/with-fields [(field :orders :id)])
+ lib.convert/->legacy-MBQL)]
+ (qp.store/with-metadata-provider (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
+ [source-card-query])
+ (let [query (-> (lib/query (qp.store/metadata-provider) (lib.metadata/card (qp.store/metadata-provider) 1))
+ (lib/aggregate (lib/count)))
+ birth-date (m/find-first #(= (:id %) (mt/id :people :birth_date))
+ (lib/breakoutable-columns query))
+ price (m/find-first #(= (:id %) (mt/id :products :price))
+ (lib/breakoutable-columns query))
+ _ (is (some? birth-date))
+ _ (is (some? price))
+ query (-> query
+ (lib/breakout (lib/with-temporal-bucket birth-date :year))
+ (lib/breakout (lib/with-binning price {:strategy :num-bins, :num-bins 50})))
+ result (qp/process-query query)]
+ (is (seq (mt/rows result)))
+ (is (= ["People → Birth Date: Year" "Products → Price: 50 bins"]
+ (map :display_name (take 2 (mt/cols result))))))))))))
+
(deftest ^:parallel breakout-and-fields-test
(mt/test-drivers (mt/normal-drivers)
(testing "adding a breakout to a query with fields works"
diff --git a/test/metabase/query_processor/card_test.clj b/test/metabase/query_processor/card_test.clj
index 0fdd6312459..9cff7076362 100644
--- a/test/metabase/query_processor/card_test.clj
+++ b/test/metabase/query_processor/card_test.clj
@@ -272,6 +272,17 @@
(is (= [[1] [2]]
(mt/rows (process-query-for-card child-card))))))))))))
+(deftest ^:parallel archived-source-card-still-queryable-test
+ (testing "a card whose source is an archived card can still be run (#52071)"
+ (mt/with-temp [:model/Card {model-id :id} {:type :model
+ :archived true
+ :dataset_query (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :venues)))}
+ :model/Card child-card {:dataset_query (let [mp (mt/metadata-provider)]
+ (lib/query mp (lib.metadata/card mp model-id)))}]
+ (is (=? {:status :completed}
+ (run-query-for-card child-card))))))
+
(deftest ^:parallel updates-metadata-provider
(testing "should set the previous results metadata to the store"
(let [entity-id (u/generate-nano-id)]
diff --git a/test/metabase/query_processor/case_test.clj b/test/metabase/query_processor/case_test.clj
index 0c63d55c78b..c1fe8013bd4 100644
--- a/test/metabase/query_processor/case_test.clj
+++ b/test/metabase/query_processor/case_test.clj
@@ -4,6 +4,7 @@
(:require
[clojure.test :refer :all]
[metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-util :as lib.tu]
[metabase.query-processor.test :as qp]
[metabase.test :as mt]))
@@ -149,6 +150,17 @@
:limit 2
:order-by [[:asc $id]]})))))))
+(deftest ^:parallel case-with-boolean-column-condition-test
+ (testing "a boolean column can be used directly as a :case condition (#16386)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :basic-aggregations :expressions)
+ (mt/dataset places-cam-likes
+ (let [mp (mt/metadata-provider)
+ liked (lib.metadata/field mp (mt/id :places :liked))
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :places)))
+ (lib/aggregate (lib/sum (lib/case [[liked 1]] 0))))]
+ (is (= [[2.0]]
+ (mt/formatted-rows [1.0] (qp/process-query query)))))))))
+
(deftest ^:parallel if-test
(testing "If should work as syntactic sugar for case"
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
diff --git a/test/metabase/query_processor/coercion_test.clj b/test/metabase/query_processor/coercion_test.clj
index 329e0c045a4..e4f1962c2d9 100644
--- a/test/metabase/query_processor/coercion_test.clj
+++ b/test/metabase/query_processor/coercion_test.clj
@@ -166,3 +166,21 @@
(u.date/format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" (u.date/parse s))
s))]
(qp/process-query query)))))))))
+
+(deftest ^:parallel coerced-field-through-model-test
+ (testing "#22519 a field with a coercion strategy still executes through a model source"
+ (mt/test-drivers (mt/normal-drivers)
+ (let [base-mp (lib.tu/merged-mock-metadata-provider
+ (mt/metadata-provider)
+ {:fields [{:id (mt/id :reviews :rating)
+ :coercion-strategy :Coercion/UNIXSeconds->DateTime
+ :effective-type :type/DateTime}]})
+ mp (lib.tu/mock-metadata-provider
+ base-mp
+ {:cards [{:id 1
+ :type :model
+ :database-id (mt/id)
+ :dataset-query (lib/query base-mp (lib.metadata/table base-mp (mt/id :reviews)))}]})
+ query (lib/query mp (lib.metadata/card mp 1))]
+ (mt/with-native-query-testing-context query
+ (is (seq (mt/rows (qp/process-query query)))))))))
diff --git a/test/metabase/query_processor/cumulative_aggregation_test.clj b/test/metabase/query_processor/cumulative_aggregation_test.clj
index aa6f45dea83..54cdcc2d247 100644
--- a/test/metabase/query_processor/cumulative_aggregation_test.clj
+++ b/test/metabase/query_processor/cumulative_aggregation_test.clj
@@ -619,3 +619,52 @@
(mt/formatted-rows
[->local-date str 2.0 2.0]
(qp/process-query query)))))))))
+
+(deftest ^:parallel expression-in-stage-after-cumulative-count-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/cumulative)
+ (testing "an expression in the outer stage does not break a cum-count source query (#13634)"
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ query (-> (lib/query mp orders)
+ (lib/aggregate (lib/cum-count))
+ (lib/breakout (lib/with-temporal-bucket created-at :month))
+ lib/append-stage
+ (lib/expression "Foo Bar" (lib/+ 57910 1)))]
+ (is (seq (mt/rows (qp/process-query query))))))))
+
+(deftest ^:parallel cumulative-count-with-post-aggregation-filter-test
+ (testing "a cum-count + month breakout query wrapped in an outer filter stage still returns rows (#33330)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/cumulative)
+ (let [metadata-provider (mt/metadata-provider)
+ orders (lib.metadata/table metadata-provider (mt/id :orders))
+ created-at (lib.metadata/field metadata-provider (mt/id :orders :created_at))
+ base (-> (lib/query metadata-provider orders)
+ (lib/aggregate (lib/cum-count))
+ (lib/breakout (lib/with-temporal-bucket created-at :month))
+ lib/append-stage)
+ outer-col (m/find-first (comp #{"Created At: Month"} :display-name)
+ (lib/filterable-columns base))
+ _ (assert (some? outer-col))
+ query (lib/filter base (lib/= outer-col "2016-05-01"))]
+ (is (seq (mt/rows (qp/process-query query))))))))
+
+(deftest ^:parallel offset-post-aggregation-expression-filter-sort-test
+ (testing "a post-aggregation custom column, filter, and sort can all reference an offset aggregation"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [metadata-provider (mt/metadata-provider)
+ orders (lib.metadata/table metadata-provider (mt/id :orders))
+ created-at (lib.metadata/field metadata-provider (mt/id :orders :created_at))
+ total (lib.metadata/field metadata-provider (mt/id :orders :total))
+ base (-> (lib/query metadata-provider orders)
+ (lib/breakout (lib/with-temporal-bucket created-at :month))
+ (lib/aggregate (lib/offset (lib/sum total) -1))
+ lib/append-stage)
+ ofs (m/find-first (comp #(re-find #"(?i)offset" (or % "")) :display-name)
+ (lib/returned-columns base))
+ _ (assert (some? ofs))
+ query (-> base
+ (lib/expression "x2" (lib/* ofs 2))
+ (lib/filter (lib/> ofs 1000))
+ (lib/order-by ofs))]
+ (is (seq (mt/rows (qp/process-query query))))))))
diff --git a/test/metabase/query_processor/dashboard_test.clj b/test/metabase/query_processor/dashboard_test.clj
index ab14be7b0ce..df5b0510d2c 100644
--- a/test/metabase/query_processor/dashboard_test.clj
+++ b/test/metabase/query_processor/dashboard_test.clj
@@ -7,11 +7,13 @@
[clojure.test :refer :all]
[metabase.dashboards-rest.api-test :as api.dashboard-test]
[metabase.driver.common :as driver.common]
+ [metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.query-processor.card-test :as qp.card-test]
[metabase.query-processor.dashboard :as qp.dashboard]
[metabase.query-processor.test :as qp]
+ [metabase.query-processor.test-util :as qp.test-util]
[metabase.test :as mt]
[toucan2.core :as t2]))
@@ -523,3 +525,124 @@
;; '2026-02-23 00:00:00' and extracts day-of-week from it, rather than
;; comparing with a numeric constant directly.
(is (not (re-find #"'\d{4}-\d{2}-\d{2}" dashboard-sql)))))))))
+
+(deftest ignore-parameter-mapping-to-native-model-test
+ (testing "param mapped to a native model is ignored, but applied to a sibling MBQL card (#44288)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ cat-target [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field mp (mt/id :products :category))))]]
+ (mt/with-temp
+ [:model/Card {mbql-card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :products)))}
+ :model/Card {native-model-id :id} {:type :model
+ :dataset_query (lib/native-query mp "SELECT * FROM PRODUCTS")}
+ :model/Dashboard {dashboard-id :id} {:parameters [{:name "Category"
+ :slug "category"
+ :id "_CAT_"
+ :type "string/="}]}
+ :model/DashboardCard {mbql-dashcard-id :id}
+ {:dashboard_id dashboard-id
+ :card_id mbql-card-id
+ :parameter_mappings [{:parameter_id "_CAT_"
+ :card_id mbql-card-id
+ :target cat-target}]}
+ :model/DashboardCard {native-dashcard-id :id}
+ {:dashboard_id dashboard-id
+ :card_id native-model-id
+ :parameter_mappings [{:parameter_id "_CAT_"
+ :card_id native-model-id
+ :target cat-target}]}]
+ (testing "MBQL card applies the mapping: strictly fewer rows with the param than without"
+ (let [with-param (count (mt/rows (run-query-for-dashcard dashboard-id mbql-card-id mbql-dashcard-id
+ :parameters [{:id "_CAT_" :value ["Gadget"]}])))
+ without (count (mt/rows (run-query-for-dashcard dashboard-id mbql-card-id mbql-dashcard-id)))]
+ (is (pos? with-param))
+ (is (< with-param without))))
+ (testing "native model ignores the mapping: same rows with and without the param, and no error"
+ (let [with-param (count (mt/rows (run-query-for-dashcard dashboard-id native-model-id native-dashcard-id
+ :parameters [{:id "_CAT_" :value ["Gadget"]}])))
+ without (count (mt/rows (run-query-for-dashcard dashboard-id native-model-id native-dashcard-id)))]
+ (is (pos? without))
+ (is (= without with-param)))))))))
+
+(deftest missing-param-column-does-not-crash-test
+ (testing "param mapped to a column missing from a model source card does not crash the dashcard (#32573)"
+ (mt/dataset test-data
+ (mt/with-temp
+ [:model/Card {model-id :id} (assoc (qp.test-util/card-with-source-metadata-for-query
+ (-> (lib/query (mt/metadata-provider) (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))
+ (lib/with-fields [(lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :orders :tax)))])))
+ :type :model)
+ :model/Card {question-id :id} {:dataset_query (lib/query (mt/metadata-provider)
+ (lib.metadata/card (mt/metadata-provider) model-id))}
+ :model/Dashboard {dashboard-id :id} {:parameters [{:name "ID"
+ :slug "id"
+ :id "_ID_"
+ :type "id"}]}
+ :model/DashboardCard {dashcard-id :id}
+ {:dashboard_id dashboard-id
+ :card_id question-id
+ ;; Intentionally a name-based ref to a column ("ID") that the model does NOT expose (only TAX);
+ ;; this is the whole point of #32573, so it cannot be derived from the source card's metadata.
+ :parameter_mappings [{:parameter_id "_ID_"
+ :card_id question-id
+ :target [:dimension [:field "ID" {:base-type :type/BigInteger}]]}]}]
+ (testing "parameter resolution does not throw (dashboard stays loadable)"
+ (is (=? [{:id "_ID_", :target [:dimension [:field "ID" {:base-type :type/BigInteger}]]}]
+ (resolve-params-for-query dashboard-id question-id dashcard-id
+ [{:id "_ID_" :value 1}]))))
+ (testing "the broken dashcard surfaces a contained query-execution error, not a catastrophic crash"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Error executing query"
+ (run-query-for-dashcard dashboard-id question-id dashcard-id
+ :parameters [{:id "_ID_" :value 1}]))))))))
+
+(deftest dashboard-param-on-custom-column-in-later-stage-test
+ (testing "a dashboard param with {:stage-number 1} on a custom column filters the later stage (#48258)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ query (let [q0 (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib.metadata/field mp (mt/id :products :category))))
+ q1 (lib/append-stage q0)
+ cnt (first (filter #(= (:name %) "count") (lib/visible-columns q1)))
+ q2 (lib/expression q1 "5xCount" (lib/* 5 cnt))]
+ (lib/with-fields q2 [(lib/expression-ref q2 "5xCount")]))
+ cc-ref (lib.convert/->legacy-MBQL (lib/expression-ref query "5xCount"))]
+ (mt/with-temp
+ [:model/Card {card-id :id}
+ {:dataset_query query}
+ :model/Dashboard {dashboard-id :id}
+ {:parameters [{:slug "cc" :id "_CC_" :name "cc" :type "number/>="}]}
+ :model/DashboardCard {dashcard-id :id}
+ {:dashboard_id dashboard-id
+ :card_id card-id
+ :parameter_mappings [{:parameter_id "_CC_"
+ :card_id card-id
+ :target [:dimension cc-ref {:stage-number 1}]}]}]
+ (testing "no filter: one row per category"
+ (is (= 4 (count (mt/rows (run-query-for-dashcard dashboard-id card-id dashcard-id))))))
+ (testing "filter on the stage-1 custom column narrows rows"
+ (is (= 2 (count (mt/rows (run-query-for-dashcard dashboard-id card-id dashcard-id
+ :parameters [{:id "_CC_" :value 260}])))))))))))
+
+(deftest dashcard-id-param-on-nested-card-test
+ (testing "an id param mapped to a field on an MBQL nested-card source filters the outer query to one row (#17213, #17212)"
+ (mt/dataset test-data
+ (mt/with-temp
+ [:model/Card {base-id :id} {:dataset_query (lib/query (mt/metadata-provider)
+ (lib.metadata/table (mt/metadata-provider) (mt/id :products)))}
+ :model/Card {nested-id :id} {:dataset_query (lib/query (mt/metadata-provider)
+ (lib.metadata/card (mt/metadata-provider) base-id))}
+ :model/Dashboard {dashboard-id :id} {:parameters [{:id "_ID_" :name "ID" :slug "id" :type "id"}]}
+ :model/DashboardCard {dashcard-id :id}
+ {:dashboard_id dashboard-id
+ :card_id nested-id
+ :parameter_mappings [{:parameter_id "_ID_"
+ :card_id nested-id
+ :target [:dimension (lib.convert/->legacy-MBQL
+ (lib/ref (lib.metadata/field (mt/metadata-provider) (mt/id :products :id))))]}]}]
+ (is (= 1
+ (count (mt/rows (run-query-for-dashcard dashboard-id nested-id dashcard-id
+ :parameters [{:id "_ID_" :value 3}])))))))))
diff --git a/test/metabase/query_processor/date_bucketing_test.clj b/test/metabase/query_processor/date_bucketing_test.clj
index 3674de61acd..2ee998fad62 100644
--- a/test/metabase/query_processor/date_bucketing_test.clj
+++ b/test/metabase/query_processor/date_bucketing_test.clj
@@ -1393,6 +1393,21 @@
{:aggregation [[:count]]
:filter [:relative-time-interval $timestamp -1 :week 0 :week]})))))))))
+(deftest ^:parallel relative-time-interval-positive-offset-test
+ (mt/test-drivers
+ (mt/normal-drivers-with-feature :date-arithmetics :test/dynamic-dataset-loading)
+ (testing "positive-offset relative-time-interval (\"Next N, starting N from now\") executes and returns the shifted window"
+ (mt/dataset checkins:1-per-day:60
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :checkins)))
+ (lib/aggregate (lib/count))
+ (lib/filter (lib/relative-time-interval
+ (lib.metadata/field mp (mt/id :checkins :timestamp))
+ 1 :week 1 :week)))]
+ (is (= 7
+ (ffirst
+ (mt/formatted-rows [int] (qp/process-query query))))))))))
+
;; Make sure that when referencing the same field multiple times with different units we return the one that actually
;; reflects the units the results are in. eg when we breakout by one unit and filter by another, make sure the results
;; and the col info use the unit used by breakout
diff --git a/test/metabase/query_processor/explicit_joins_test.clj b/test/metabase/query_processor/explicit_joins_test.clj
index 8b06442be37..ac2d9e990a9 100644
--- a/test/metabase/query_processor/explicit_joins_test.clj
+++ b/test/metabase/query_processor/explicit_joins_test.clj
@@ -5,6 +5,7 @@
[clojure.set :as set]
[clojure.string :as str]
[clojure.test :refer :all]
+ [medley.core :as m]
[metabase.driver :as driver]
[metabase.driver.mysql :as mysql]
[metabase.driver.sql.query-processor-test-util :as sql.qp-test-util]
@@ -26,7 +27,8 @@
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.util :as u]
- [metabase.util.date-2 :as u.date]))
+ [metabase.util.date-2 :as u.date]
+ [metabase.util.json :as json]))
(deftest ^:parallel explict-join-with-default-options-test
(testing "Can we specify an *explicit* JOIN using the default options?"
@@ -1739,3 +1741,293 @@
:dataset-query q1b}]})]
(is (thrown-with-msg? Exception #"Join condition refers to a column from outside this join"
(qp.compile/compile (lib/query mp q2)))))))
+
+(deftest ^:parallel join-against-native-source-card-test
+ (testing "Left-join a native source card, restrict its fields, filter, and aggregate (#37100, #29795)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :left-join :basic-aggregations)
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ products-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :products)))
+ (lib/with-fields [(lib.metadata/field mp0 (mt/id :products :id))
+ (lib.metadata/field mp0 (mt/id :products :category))]))
+ compiled (:query (qp.compile/compile products-q))
+ ;; non-SQL drivers (mongo) compile to a pipeline vector; a saved native query stores its JSON text
+ native-q (-> (lib/native-query mp0 (cond-> compiled (not (string? compiled)) json/encode))
+ (lib/with-native-extras {:collection "products"}))
+ mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries [native-q])
+ card (lib.metadata/card mp 1)
+ base (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ product-id (lib.metadata/field mp (mt/id :orders :product_id))
+ id-name (u/lower-case-en (:name (lib.metadata/field mp0 (mt/id :products :id))))
+ ;; native card columns have no field id -- match by lower-cased name for case-folding drivers
+ card-id (m/find-first #(= id-name (u/lower-case-en (:name %)))
+ (lib/join-condition-rhs-columns base card (lib/ref product-id) nil))
+ joined (lib/join base (-> (lib/join-clause card [(lib/= product-id card-id)])
+ (lib/with-join-alias "P")
+ (lib/with-join-fields :all)))
+ category (m/find-first #(and (= :source/joins (:lib/source %))
+ (= "category" (u/lower-case-en (:name %))))
+ (lib/breakoutable-columns joined))]
+ (testing "aggregate grouped by a column coming from the native join card"
+ (is (= #{"Doohickey" "Gadget" "Gizmo" "Widget"}
+ (set (map first
+ (mt/rows
+ (qp/process-query
+ (-> joined
+ (lib/aggregate (lib/count))
+ (lib/breakout category)))))))))
+ (testing "filter on a column coming from the native join card"
+ (is (seq (mt/rows
+ (qp/process-query
+ (-> joined
+ (lib/filter (lib/= category "Gadget"))
+ (lib/aggregate (lib/count)))))))))))))
+
+(deftest ^:parallel order-by-joined-breakout-column-test
+ (testing "Sorting on a joined-table breakout column (#30743)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join :basic-aggregations)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ base (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ products (lib.metadata/table mp (mt/id :products))
+ joined (lib/join base (-> (lib/join-clause products (lib/suggested-join-conditions base products))
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields :all)))
+ category (m/find-first #(and (= :source/joins (:lib/source %))
+ (= (mt/id :products :category) (:id %)))
+ (lib/breakoutable-columns joined))]
+ (is (= ["Doohickey" "Gadget" "Gizmo" "Widget"]
+ (map first
+ (mt/rows
+ (qp/process-query
+ (-> joined
+ (lib/aggregate (lib/count))
+ (lib/breakout category)
+ (lib/order-by category :asc))))))))))))
+
+(deftest ^:parallel join-condition-on-inner-expression-field-literal-test
+ (testing "A join whose condition operand is a field-literal referencing an inner expression executes (#18630)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join :expressions :nested-queries)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ ;; a fresh copy per call -- reusing one query as both source and join target collides :lib/uuids
+ mk-inner (fn []
+ (as-> (lib/query mp (lib.metadata/table mp (mt/id :orders))) q
+ (lib/expression q "CC" (lib/coalesce (lib.metadata/field mp (mt/id :orders :discount)) 0))
+ (lib/aggregate q (lib/count))
+ (lib/breakout q (m/find-first #(= "CC" (:name %)) (lib/breakoutable-columns q)))))
+ outer (lib/append-stage (mk-inner))
+ lhs-cc (m/find-first #(= "cc" (u/lower-case-en (:name %))) (lib/visible-columns outer))
+ rhs-cc (lib/with-join-alias lhs-cc "Q2")]
+ (is (seq (mt/rows
+ (qp/process-query
+ (-> outer
+ (lib/join (-> (lib/join-clause (mk-inner) [(lib/= lhs-cc rhs-cc)])
+ (lib/with-join-alias "Q2")
+ (lib/with-join-fields :all)))
+ (lib/limit 5)))))))))))
+
+(deftest ^:parallel post-join-filter-then-aggregate-test
+ (testing "Filter on a joined column, then aggregate grouped by another joined column (#11452, #12221, #15570)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join :basic-aggregations)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ joined (lib/join (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (-> (lib/join-clause (lib.metadata/table mp (mt/id :reviews))
+ [(lib/= (lib.metadata/field mp (mt/id :orders :product_id))
+ (lib.metadata/field mp (mt/id :reviews :product_id)))])
+ (lib/with-join-alias "Reviews")
+ (lib/with-join-fields :all)))
+ rating (m/find-first #(and (= :source/joins (:lib/source %))
+ (= (mt/id :reviews :rating) (:id %)))
+ (lib/breakoutable-columns joined))
+ reviewer (m/find-first #(and (= :source/joins (:lib/source %))
+ (= (mt/id :reviews :reviewer) (:id %)))
+ (lib/breakoutable-columns joined))
+ rows (mt/rows
+ (qp/process-query
+ (-> joined
+ (lib/filter (lib/= rating 2))
+ (lib/aggregate (lib/avg rating))
+ (lib/breakout reviewer))))]
+ (is (seq rows))
+ (testing "avg of a column filtered to a single value equals that value for every group"
+ (is (every? (fn [[_reviewer avg]] (== 2 avg)) rows))))))))
+
+(deftest ^:parallel join-expression-condition-over-model-source-test
+ (testing "An arithmetic expression join condition over a self-joined model source executes like the table equivalent"
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :left-join :expressions)
+ (mt/dataset test-data
+ (let [orders-q (lib/query (mt/metadata-provider) (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))
+ mp (-> (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries [orders-q])
+ (lib.tu/merged-mock-metadata-provider {:cards [{:id 1, :type :model}]}))
+ ;; derive refs by field id -- hardcoded upper/lowercase name literals break on case-folding drivers
+ col-of (fn [cols field-id] (m/find-first #(= field-id (:id %)) cols))
+ card (lib.metadata/card mp 1)
+ base (lib/query mp card)
+ cols (lib/returned-columns base)
+ id (col-of cols (mt/id :orders :id))
+ user-id (col-of cols (mt/id :orders :user_id))
+ product-id (col-of cols (mt/id :orders :product_id))
+ model-rows (mt/rows
+ (qp/process-query
+ (-> base
+ (lib/join (-> (lib/join-clause
+ card
+ [(lib/= (lib/+ id user-id)
+ (lib/+ (lib/with-join-alias id "m")
+ (lib/with-join-alias product-id "m")))])
+ (lib/with-join-alias "m")
+ (lib/with-join-fields :all)))
+ (lib/filter (lib/<= id 5)))))
+ tbase (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ tid (lib.metadata/field mp (mt/id :orders :id))
+ tuid (lib.metadata/field mp (mt/id :orders :user_id))
+ tpid (lib.metadata/field mp (mt/id :orders :product_id))
+ table-rows (mt/rows
+ (qp/process-query
+ (-> tbase
+ (lib/join (-> (lib/join-clause
+ (lib.metadata/table mp (mt/id :orders))
+ [(lib/= (lib/+ tid tuid)
+ (lib/+ (lib/with-join-alias tid "m")
+ (lib/with-join-alias tpid "m")))])
+ (lib/with-join-alias "m")
+ (lib/with-join-fields :all)))
+ (lib/filter (lib/<= tid 5)))))]
+ (is (seq model-rows))
+ (testing "model source yields the same number of joined rows as the equivalent table self-join"
+ (is (= (count table-rows) (count model-rows)))))))))
+
+(deftest ^:parallel join-two-models-with-same-internal-join-alias-test
+ (testing "Joining two models that each internally join PRODUCTS under the same alias resolves and executes (#47988)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :left-join)
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ add-products (fn [q]
+ (let [products (lib.metadata/table mp0 (mt/id :products))]
+ (lib/join q (-> (lib/join-clause products (lib/suggested-join-conditions q products))
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields :all)))))
+ card1-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ add-products)
+ card2-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ add-products
+ (lib/join (-> (lib/join-clause (lib.metadata/table mp0 (mt/id :reviews))
+ [(lib/= (lib.metadata/field mp0 (mt/id :orders :product_id))
+ (lib.metadata/field mp0 (mt/id :reviews :product_id)))])
+ (lib/with-join-alias "Reviews")
+ (lib/with-join-fields :all))))
+ mp (-> (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries [card1-q card2-q])
+ (lib.tu/merged-mock-metadata-provider {:cards [{:id 1, :type :model}
+ {:id 2, :type :model}]}))
+ card2 (lib.metadata/card mp 2)
+ base (lib/query mp (lib.metadata/card mp 1))
+ lhs (m/find-first #(= (mt/id :orders :id) (:id %)) (lib/returned-columns base))
+ rhs (m/find-first #(= (mt/id :orders :id) (:id %))
+ (lib/join-condition-rhs-columns base card2 (lib/ref lhs) nil))]
+ (is (seq (mt/rows
+ (qp/process-query
+ (-> base
+ (lib/join (-> (lib/join-clause card2 [(lib/= lhs rhs)])
+ (lib/with-join-alias "M2")
+ (lib/with-join-fields :all)))
+ (lib/limit 1)))))))))))
+
+(deftest ^:parallel dedup-same-named-joins-across-nested-cards-test
+ (testing "Joining two cards that each join Products with the default alias \"Products\" does not collide (#51856)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :left-join)
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ card-q (fn [table-id]
+ (let [q (lib/query mp0 (lib.metadata/table mp0 table-id))
+ products (lib.metadata/table mp0 (mt/id :products))]
+ (lib/join q (-> (lib/join-clause products (lib/suggested-join-conditions q products))
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields :all)))))
+ mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
+ [(card-q (mt/id :orders))
+ (card-q (mt/id :reviews))])
+ card2 (lib.metadata/card mp 2)
+ base (lib/query mp (lib.metadata/card mp 1))
+ cat1 (m/find-first #(= (:id %) (mt/id :products :category)) (lib/returned-columns base))
+ cat2 (m/find-first #(= (:id %) (mt/id :products :category))
+ (lib/join-condition-rhs-columns base card2 (lib/ref cat1) nil))
+ query (-> base
+ (lib/join (-> (lib/join-clause card2 [(lib/= cat1 cat2)])
+ (lib/with-join-alias "Q2")
+ (lib/with-join-fields :all)))
+ (lib/limit 5))]
+ (mt/with-native-query-testing-context query
+ (is (seq (mt/rows (qp/process-query query))))))))))
+
+(deftest ^:parallel join-saved-card-on-fk-sourced-breakout-test
+ (testing "Join a saved card on an FK-sourced implicit-join breakout column (#48754)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join :basic-aggregations :nested-queries)
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ fk-category (fn [q] (m/find-first #(and (= (mt/id :products :category) (:id %))
+ (= :source/implicitly-joinable (:lib/source %)))
+ (lib/breakoutable-columns q)))
+ card-q (as-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders))) q
+ (lib/aggregate q (lib/count))
+ (lib/breakout q (fk-category q)))
+ mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries [card-q])
+ card (lib.metadata/card mp 1)
+ base (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ category (fk-category base)
+ order-id (lib.metadata/field mp (mt/id :orders :id))
+ ;; derive the card's category column instead of a hardcoded "CATEGORY" literal (case-folding drivers)
+ card-cat (m/find-first #(= "category" (u/lower-case-en (:name %)))
+ (lib/join-condition-rhs-columns base card (lib/ref category) nil))]
+ ;; id<=100 bounds the outer rows so H2 doesn't re-evaluate the aggregated card subquery per-row and time
+ ;; out; the first 100 orders still cover all 4 categories.
+ (is (= 4
+ (count (mt/rows
+ (qp/process-query
+ (-> base
+ (lib/filter (lib/<= order-id 100))
+ (lib/aggregate (lib/count))
+ (lib/breakout category)
+ (lib/join (-> (lib/join-clause card [(lib/= category card-cat)])
+ (lib/with-join-alias "Q1")
+ (lib/with-join-fields :all))))))))))))))
+
+(deftest ^:parallel filter-on-long-named-joined-card-column-uses-inner-name-test
+ (testing "Filtering on a long-named joined-card column references the inner column, not the truncated alias (#56416)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :left-join :basic-aggregations)
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ card-base (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ fk-category (m/find-first #(and (= (mt/id :products :category) (:id %))
+ (= :source/implicitly-joinable (:lib/source %)))
+ (lib/breakoutable-columns card-base))
+ product-id (m/find-first #(= (mt/id :orders :product_id) (:id %))
+ (lib/breakoutable-columns card-base))
+ card-q (-> card-base
+ (lib/aggregate (lib/count))
+ (lib/breakout fk-category)
+ (lib/breakout product-id))
+ mp (-> (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries [card-q])
+ (lib.tu/merged-mock-metadata-provider
+ {:cards [{:id 1, :name (apply str (repeat 65 \a))}]}))
+ card (lib.metadata/card mp 1)
+ base (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ orders-pid (lib.metadata/field mp (mt/id :orders :product_id))
+ ;; derive the joined card's columns instead of hardcoding "PRODUCT_ID"/"CATEGORY" (CI: case-folding drivers)
+ card-pid (m/find-first #(= (mt/id :orders :product_id) (:id %))
+ (lib/join-condition-rhs-columns base card (lib/ref orders-pid) nil))
+ joined (lib/join base (-> (lib/join-clause card [(lib/= orders-pid card-pid)])
+ (lib/with-join-alias "J")
+ (lib/with-join-fields :all)))
+ j-category (m/find-first #(and (= (mt/id :products :category) (:id %))
+ (= :source/joins (:lib/source %)))
+ (lib/visible-columns joined))]
+ (is (= [["Gadget"]]
+ (map (fn [[category _count]] [category])
+ (mt/rows
+ (qp/process-query
+ (-> joined
+ (lib/filter (lib/= j-category "Gadget"))
+ (lib/breakout j-category)
+ (lib/aggregate (lib/count)))))))))))))
diff --git a/test/metabase/query_processor/expressions_test.clj b/test/metabase/query_processor/expressions_test.clj
index 1d861597c75..64aacb21c90 100644
--- a/test/metabase/query_processor/expressions_test.clj
+++ b/test/metabase/query_processor/expressions_test.clj
@@ -8,7 +8,9 @@
[medley.core :as m]
[metabase.driver :as driver]
[metabase.lib.core :as lib]
+ [metabase.lib.expression :as lib.expression]
[metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.options :as lib.options]
[metabase.query-processor.test :as qp]
[metabase.test :as mt]
[metabase.util :as u]
@@ -1219,3 +1221,215 @@
(mt/formatted-rows
[int u.date/temporal-str->iso8601-str int u.date/temporal-str->iso8601-str]
(qp/process-query query))))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | BOOLEAN FUNCTION EXPRESSIONS |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+;; Selecting a bare boolean expression as a value column is unsupported on two normal drivers: Oracle has no boolean
+;; SQL type (ORA-00923), and Mongo returns the boolean expression clause uncompiled. No single feature captures "can
+;; select a boolean expression", but the supported-driver sets of two real features coincide with it exactly: Oracle
+;; is the only `:expressions` driver lacking `:expressions/date`, and Mongo the only one lacking `:distinct-where`.
+(deftest ^:parallel boolean-function-as-selected-column-test
+ (testing "boolean function expressions can be selected as value-producing columns (#15922)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :expressions/date :distinct-where)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ category (lib.metadata/field mp (mt/id :products :category))
+ price (lib.metadata/field mp (mt/id :products :price))
+ id (lib.metadata/field mp (mt/id :products :id))
+ query (as-> (lib/query mp (lib.metadata/table mp (mt/id :products))) q
+ (lib/expression q "isnull" (lib/is-null category))
+ (lib/expression q "notnull" (lib/not-null category))
+ (lib/expression q "starts" (lib/starts-with category "mo"))
+ (lib/expression q "btw" (lib/between price 0 1000))
+ (lib/with-fields q [(lib/expression-ref q "isnull")
+ (lib/expression-ref q "notnull")
+ (lib/expression-ref q "starts")
+ (lib/expression-ref q "btw")])
+ (lib/order-by q id :asc)
+ (lib/limit q 1))]
+ (is (= [[false true false true]]
+ (mt/formatted-rows
+ [mt/boolish->bool mt/boolish->bool mt/boolish->bool mt/boolish->bool]
+ (qp/process-query query)))))))))
+
+;; Breaking out on a bare boolean expression is unsupported on Oracle (no boolean SQL type, ORA-00923) and Mongo
+;; (returns the clause uncompiled); those are exactly the `:expressions` drivers lacking `:expressions/date` (Oracle)
+;; and `:distinct-where` (Mongo). The downstream `count-where` consumption is portable, so SQL Server and Redshift —
+;; which can group by a boolean but cannot `min`/`max` one — are included rather than excluded.
+(deftest ^:parallel boolean-expression-consumed-downstream-test
+ (testing "a named boolean expression can be broken out on and consumed downstream (#34286)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :basic-aggregations :expressions/date :distinct-where)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ category (lib.metadata/field mp (mt/id :products :category))
+ base (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/expression "b" (lib/starts-with category "Gi")))]
+ (testing "same-stage breakout"
+ (let [query (-> base
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/expression-ref base "b")))]
+ (is (= {false 149, true 51}
+ (into {} (mt/formatted-rows [mt/boolish->bool int] (qp/process-query query)))))))
+ (testing "count-where over the boolean expression"
+ (let [query (-> base
+ (lib/aggregate (lib/count-where (lib/expression-ref base "b"))))]
+ (is (= [[51]]
+ (mt/formatted-rows [int] (qp/process-query query)))))))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | EXPRESSION NAME RESOLUTION |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(defn- case-preserving-identifier-expression-drivers
+ "Drivers that preserve identifier case, so the four case-variant expression aliases in
+ [[case-sensitive-expression-name-resolution-test]] stay distinct. Drivers that fold identifiers (e.g. Redshift,
+ Snowflake) would collapse them into one and make the result ambiguous."
+ []
+ (filter #{:h2 :postgres} (mt/normal-drivers-with-feature :expressions :expression-literals)))
+
+(deftest ^:parallel case-sensitive-expression-name-resolution-test
+ (testing "expressions with the same spelling but different case resolve distinctly (#56962)"
+ (mt/test-drivers (case-preserving-identifier-expression-drivers)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ id (lib.metadata/field mp (mt/id :orders :id))
+ query (as-> (lib/query mp (lib.metadata/table mp (mt/id :orders))) q
+ (lib/expression q "FOO" (lib.expression/value "upper"))
+ (lib/expression q "foo" (lib.expression/value "lower"))
+ (lib/expression q "Foo" (lib.expression/value "sentence"))
+ (lib/expression q "FoO" (lib.expression/value "silly"))
+ (lib/with-fields q [(lib/expression-ref q "FOO")
+ (lib/expression-ref q "foo")
+ (lib/expression-ref q "Foo")
+ (lib/expression-ref q "FoO")])
+ (lib/order-by q id :asc)
+ (lib/limit q 1))]
+ (is (= [["upper" "lower" "sentence" "silly"]]
+ (mt/formatted-rows [str str str str] (qp/process-query query)))))))))
+
+(deftest ^:parallel expression-name-collision-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :left-join)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)]
+ (testing "#12649 base-table ID leads over a joined ID"
+ (let [order-id (lib.metadata/field mp (mt/id :orders :id))
+ products (lib.metadata/table mp (mt/id :products))
+ base (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ query (-> base
+ (lib/join (-> (lib/join-clause products (lib/suggested-join-conditions base products))
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields :all)))
+ (lib/expression "x" (lib/+ 1 1))
+ (lib/order-by order-id :asc)
+ (lib/limit 1))]
+ ;; coerce the leading ID via formatted-rows: Oracle returns it as BigDecimal
+ (is (= 1 (->> (qp/process-query query) (mt/formatted-rows [int]) ffirst)))))
+ (testing "#21135 an expression shadowing a column name keeps both columns"
+ (let [price (lib.metadata/field mp (mt/id :products :price))
+ cols (mt/cols (qp/process-query
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/expression "Price" (lib/+ price 2))
+ (lib/limit 1))))]
+ (is (= 2 (count (filter #(= "Price" (:display_name %)) cols))))))))))
+
+(deftest ^:parallel in-and-not-in-expression-functions-test
+ (testing "the `in` function works as a filter and inside count-where"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :basic-aggregations)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ id (lib.metadata/field mp (mt/id :products :id))]
+ (is (= 3 (->> (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/filter (lib/in id 1 2 3))
+ (lib/aggregate (lib/count)))
+ qp/process-query mt/rows ffirst long)))
+ (is (= 2 (->> (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/aggregate (lib/count-where (lib/in id 1 2))))
+ qp/process-query mt/rows ffirst long)))
+ (is (= 197 (->> (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/filter (lib/not-in id 1 2 3))
+ (lib/aggregate (lib/count)))
+ qp/process-query mt/rows ffirst long))))))))
+
+(deftest ^:parallel temporal-filter-on-date-expression-test
+ ;; the case() default resolves an implicit-join column (products.created_at), which compiles to a LEFT JOIN
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :left-join)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ oq (lib/query mp orders)
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ discount (lib.metadata/field mp (mt/id :orders :discount))
+ id (lib.metadata/field mp (mt/id :orders :id))]
+ (testing "absolute range filter on a date passthrough expression runs"
+ (let [query (as-> oq q
+ (lib/expression q "CustomDate" created-at)
+ (lib/filter q (lib/between (lib/expression-ref q "CustomDate")
+ "2019-01-01" "2019-06-30"))
+ (lib/aggregate q (lib/count)))]
+ (is (seq (mt/rows (qp/process-query query))))))
+ (testing "#16273 relative-date filter on a case()-typed date expression runs"
+ (let [products-created (m/find-first #(= (mt/id :products :created_at) (:id %))
+ (lib/visible-columns oq))
+ _ (assert (some? products-created))
+ query (as-> oq q
+ (lib/expression q "MiscDate" (lib/case [[(lib/> discount 0) created-at]]
+ products-created))
+ (lib/filter q (lib.options/update-options
+ (lib/time-interval (lib/expression-ref q "MiscDate") -30 :year)
+ assoc :include-current true))
+ (lib/with-fields q [id (lib/expression-ref q "MiscDate")])
+ (lib/limit q 5))]
+ (is (seq (mt/rows (qp/process-query query))))))))))
+
+(deftest ^:parallel sum-of-expression-with-implicit-join-distinct-test
+ (testing "#14080 sum([expr]) + distinct(fk->) + temporal breakout compiles and runs"
+ ;; distinct over products.id via the product_id FK compiles to a LEFT JOIN
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :basic-aggregations :left-join)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ base (-> (lib/query mp orders)
+ (lib/expression "OneisOne" (lib/* 1 1)))
+ products-id (m/find-first #(= (mt/id :products :id) (:id %))
+ (lib/visible-columns base))
+ _ (assert (some? products-id))
+ query (-> base
+ (lib/aggregate (lib/distinct products-id))
+ (lib/aggregate (lib/sum (lib/expression-ref base "OneisOne")))
+ (lib/breakout (lib/with-temporal-bucket created-at :year)))]
+ (is (seq (mt/rows (qp/process-query query)))))))))
+
+(deftest ^:parallel literal-column-across-clauses-test
+ (testing "a literal expression column can be filtered, aggregated, broken out and sorted in one query"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :expression-literals :basic-aggregations)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ query (as-> (lib/query mp (lib.metadata/table mp (mt/id :products))) q
+ (lib/expression q "c" (lib.expression/value 10))
+ (lib/filter q (lib/> (lib/expression-ref q "c") 5))
+ (lib/aggregate q (lib/avg (lib/expression-ref q "c")))
+ (lib/breakout q (lib/expression-ref q "c"))
+ (lib/order-by q (lib/expression-ref q "c") :asc))]
+ (is (= [[10 10.0]]
+ (mt/formatted-rows [int 1.0] (qp/process-query query)))))))))
+
+(deftest ^:parallel arithmetic-expression-filter-test
+ (testing "a filter comparing an arithmetic expression against a constant executes (#13175, #18094)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ subtotal (lib.metadata/field mp (mt/id :orders :subtotal))
+ tax (lib.metadata/field mp (mt/id :orders :tax))
+ rows (mt/rows (qp/process-query
+ (-> (lib/query mp orders)
+ (lib/with-fields [subtotal tax])
+ (lib/filter (lib/> (lib/- subtotal tax) 140)))))]
+ (testing "every returned row actually satisfies subtotal - tax > 140"
+ (is (every? (fn [[subtotal tax]] (> (- subtotal tax) 140)) rows)))
+ (testing "the filter matches some but not all of the 18760 orders"
+ (is (pos? (count rows)))
+ (is (< (count rows) 18760))))))))
diff --git a/test/metabase/query_processor/field_visibility_test.clj b/test/metabase/query_processor/field_visibility_test.clj
index 5248d084d5b..609d0b3b969 100644
--- a/test/metabase/query_processor/field_visibility_test.clj
+++ b/test/metabase/query_processor/field_visibility_test.clj
@@ -5,6 +5,11 @@
(:require
[clojure.test :refer :all]
[medley.core :as m]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.test-util :as lib.tu]
+ [metabase.query-processor :as qp]
+ ^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]
[metabase.query-processor.test-util :as qp.test-util]
[metabase.test :as mt]
[metabase.test.util :as tu]
@@ -56,3 +61,26 @@
(qp.test-util/rows-and-cols
(mt/run-mbql-query users
{:order-by [[:asc $id]]}))))))))
+
+(deftest ^:parallel sensitive-field-hidden-in-model-query-test
+ (testing "a model whose stored result_metadata still lists a field made :sensitive after creation drops that column (#45919)"
+ (mt/test-drivers (mt/normal-drivers)
+ (mt/dataset test-data
+ ;; the model's result-metadata is computed while PASSWORD is still visible, then the field is flipped to
+ ;; :sensitive -- reproducing a field made sensitive after the model was created
+ (let [mp0 (mt/metadata-provider)
+ base-mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
+ [(lib/query mp0 (lib.metadata/table mp0 (mt/id :people)))])
+ mp (lib.tu/merged-mock-metadata-provider
+ base-mp
+ {:cards [{:id 1, :type :model}]
+ :fields [{:id (mt/id :people :password), :visibility-type :sensitive}]})]
+ (qp.store/with-metadata-provider mp
+ (let [col-names (into #{}
+ (map (comp u/lower-case-en :name))
+ (mt/cols (qp/process-query (-> (lib/query mp (lib.metadata/card mp 1))
+ (lib/limit 1)))))]
+ (testing "the sensitive PASSWORD column is dropped"
+ (is (not (contains? col-names "password"))))
+ (testing "a normal column (EMAIL) is still returned"
+ (is (contains? col-names "email"))))))))))
diff --git a/test/metabase/query_processor/filter_test.clj b/test/metabase/query_processor/filter_test.clj
index e9fcdaf6f21..b1573de6fe3 100644
--- a/test/metabase/query_processor/filter_test.clj
+++ b/test/metabase/query_processor/filter_test.clj
@@ -1254,3 +1254,85 @@
(lib/limit 2))]
(is (= [[3 "Artisan"] [4 "Asian"]]
(mt/formatted-rows [int str] (qp/process-query query)))))))
+
+(defn- lib-field
+ "Column metadata for `table`.`field` in the current dataset."
+ [mp table field]
+ (lib.metadata/field mp (mt/id table field)))
+
+(defn- lib-filtered-count
+ "Build `SELECT count(*) FROM <table> WHERE <filter>` entirely with lib and return the integer count.
+ `filter-fn` receives the metadata provider and returns a lib filter expression."
+ [table filter-fn]
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id table)))
+ (lib/aggregate (lib/count))
+ (lib/filter (filter-fn mp)))]
+ ;; mongo returns no rows instead of 0 for an empty count (#5419)
+ (or (ffirst (mt/formatted-rows [int] (qp/process-query query)))
+ 0)))
+
+(deftest ^:parallel does-not-contain-keeps-null-rows-test
+ (mt/test-drivers (mt/normal-drivers)
+ (mt/dataset airports
+ (testing "`:does-not-contain` must keep rows with a NULL value (metabase#13332, metabase#37100)"
+ ;; region.name has 8 NULLs out of 415 rows; the NULL rows must survive the filter
+ (is (= 412
+ (lib-filtered-count :region
+ (fn [mp]
+ (lib/does-not-contain (lib-field mp :region :name) "Cali")))))))))
+
+(deftest ^:parallel compare-two-fields-filter-test
+ (mt/test-drivers (mt/normal-drivers)
+ (testing "a comparison filter with two field operands (metabase#17963)"
+ ;; orders.discount is NULL for most rows; under SQL three-valued logic those rows fail `>`
+ ;; and must land in the complement, so the two disjoint filters partition every row.
+ (let [total 18760
+ gt (lib-filtered-count :orders
+ (fn [mp]
+ (lib/> (lib-field mp :orders :discount)
+ (lib-field mp :orders :quantity))))
+ not-gt (lib-filtered-count :orders
+ (fn [mp]
+ (lib/or (lib/<= (lib-field mp :orders :discount)
+ (lib-field mp :orders :quantity))
+ (lib/is-null (lib-field mp :orders :discount)))))]
+ (is (pos? gt))
+ (is (< gt total))
+ (is (= total (+ gt not-gt)))))))
+
+(deftest ^:parallel date-vs-datetime-equality-filter-test
+ (mt/test-drivers (mt/normal-drivers)
+ (testing "`=` filters on a datetime column distinguish a date-only literal from an exact timestamp (metabase#43057)"
+ (let [total 18760
+ whole-day (lib-filtered-count :orders
+ (fn [mp]
+ (lib/= (lib/with-temporal-bucket (lib-field mp :orders :created_at) :day)
+ "2019-06-26")))
+ exact (lib-filtered-count :orders
+ (fn [mp]
+ (lib/= (lib-field mp :orders :created_at)
+ "2019-06-26T00:40:07.285Z")))]
+ (testing "a date-only literal matches the whole day, not a single instant"
+ (is (< 1 whole-day)) ; more than one row => day granularity, not instant matching
+ (is (< whole-day total))) ; and the filter is not a no-op
+ (testing "an exact timestamp matches a single instant, not the whole day"
+ ;; drivers that truncate fractional seconds match 0 rows; all match at most one, strictly fewer than the day
+ (is (<= exact 1))
+ (is (< exact whole-day)))))))
+
+(deftest ^:parallel exclude-temporal-extract-filter-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :temporal-extract)
+ (testing "an exclude-date filter on an extracted temporal unit filters rows out"
+ ;; every row is either in Q1 or not; the two extractions partition all rows, and excluding
+ ;; Q1 must actually drop rows (a dropped filter would leave the count at the total).
+ (let [total 18760
+ not-q1 (lib-filtered-count :orders
+ (fn [mp]
+ (lib/!= (lib/get-quarter (lib-field mp :orders :created_at)) 1)))
+ q1 (lib-filtered-count :orders
+ (fn [mp]
+ (lib/= (lib/get-quarter (lib-field mp :orders :created_at)) 1)))]
+ (is (pos? q1))
+ (is (< not-q1 total))
+ (is (= total (+ not-q1 q1)))))))
diff --git a/test/metabase/query_processor/implicit_joins_test.clj b/test/metabase/query_processor/implicit_joins_test.clj
index c66fd0257b2..82d8dd991d5 100644
--- a/test/metabase/query_processor/implicit_joins_test.clj
+++ b/test/metabase/query_processor/implicit_joins_test.clj
@@ -384,3 +384,61 @@
;; 3 months with log counts
(is (= 3
(count (mt/rows (qp/process-query query)))))))))))))
+
+(deftest ^:parallel implicit-join-filter-through-explicit-self-join-test
+ (testing "Two implicit-join filters through an explicit self-join execute and return the expected row count (#46845)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ orders-uid (lib.metadata/field mp (mt/id :orders :user_id))
+ orders-id (lib.metadata/field mp (mt/id :orders :id))
+ orders-pid (lib.metadata/field mp (mt/id :orders :product_id))
+ products-id (lib.metadata/field mp (mt/id :products :id))
+ ;; 1:1 self-join (orders.id is unique) keeps the pipeline fan-out-free, so it stays fast
+ ;; on every driver including Mongo's $lookup
+ o2-join (fn [] (-> (lib/join-clause (lib.metadata/table mp (mt/id :orders))
+ [(lib/= orders-uid orders-id)])
+ (lib/with-join-alias "O2")))
+ vendor "Gibson, Turner and Douglas"
+ o2-vendor "Zemlak, Botsford and Corkery"
+ ;; implicit: products.vendor reached directly via orders.product_id, and via the O2 self-join's
+ ;; product_id -- the QP must resolve these two implicit joins independently (#46845)
+ i-joined (lib/join (lib/query mp (lib.metadata/table mp (mt/id :orders))) (o2-join))
+ vendors (filter #(= (mt/id :products :vendor) (:id %)) (lib/filterable-columns i-joined))
+ v-direct (m/find-first #(and (= :source/implicitly-joinable (:lib/source %))
+ (not (:fk-join-alias %)))
+ vendors)
+ v-via-o2 (m/find-first #(= "O2" (:fk-join-alias %)) vendors)
+ implicit (mt/formatted-rows [int]
+ (qp/process-query
+ (-> i-joined
+ (lib/filter (lib/= v-direct vendor))
+ (lib/filter (lib/= v-via-o2 o2-vendor))
+ (lib/aggregate (lib/count)))))
+ ;; explicit: spell the same two paths out as P1 (off orders) and P2 (off the O2 self-join)
+ explicit (mt/formatted-rows
+ [int]
+ (qp/process-query
+ (as-> (lib/query mp (lib.metadata/table mp (mt/id :orders))) q
+ (lib/join q (o2-join))
+ (lib/join q (-> (lib/join-clause (lib.metadata/table mp (mt/id :products))
+ [(lib/= orders-pid products-id)])
+ (lib/with-join-alias "P1")))
+ (lib/join q (-> (lib/join-clause
+ (lib.metadata/table mp (mt/id :products))
+ [(lib/= (m/find-first #(and (= (mt/id :orders :product_id) (:id %))
+ (= "O2" (:lib/join-alias %)))
+ (lib/visible-columns q))
+ products-id)])
+ (lib/with-join-alias "P2")))
+ (lib/filter q (lib/= (m/find-first #(and (= (mt/id :products :vendor) (:id %))
+ (= "P1" (:lib/join-alias %)))
+ (lib/visible-columns q))
+ vendor))
+ (lib/filter q (lib/= (m/find-first #(and (= (mt/id :products :vendor) (:id %))
+ (= "P2" (:lib/join-alias %)))
+ (lib/visible-columns q))
+ o2-vendor))
+ (lib/aggregate q (lib/count)))))]
+ (is (= implicit explicit))
+ (is (pos? (ffirst implicit))))))))
diff --git a/test/metabase/query_processor/middleware/expand_macros_test.clj b/test/metabase/query_processor/middleware/expand_macros_test.clj
index 8baf45a9bd3..5e8438e6f68 100644
--- a/test/metabase/query_processor/middleware/expand_macros_test.clj
+++ b/test/metabase/query_processor/middleware/expand_macros_test.clj
@@ -128,6 +128,19 @@
[:segment 2]
[:> $price 1]]]]]})))))))
+(deftest ^:parallel segment-in-case-expression-test
+ (testing "a :segment reference nested inside a :case custom expression is expanded (#24922)"
+ (qp.store/with-metadata-provider mock-metadata-provider
+ (is (=? {:query {:expressions
+ {"CC" [:case
+ [[[:= [:field (meta/id :venues :name) {:base-type :type/Text}] "abc"]
+ "Segment"]]
+ {:default "Other"}]}}}
+ (expand-macros
+ (lib.convert/->legacy-MBQL
+ (-> (lib/query mock-metadata-provider (meta/table-metadata :venues))
+ (lib/expression "CC" (lib/case [[(lib/segment 1) "Segment"]] "Other"))))))))))
+
(deftest ^:parallel expand-macros-in-nested-queries-test
(testing "expand-macros should expand things in the correct nested level (#12507)"
(qp.store/with-metadata-provider mock-metadata-provider
diff --git a/test/metabase/query_processor/middleware/metrics_test.clj b/test/metabase/query_processor/middleware/metrics_test.clj
index 6fbaefc69e6..8666c21829f 100644
--- a/test/metabase/query_processor/middleware/metrics_test.clj
+++ b/test/metabase/query_processor/middleware/metrics_test.clj
@@ -19,6 +19,7 @@
[metabase.lib.util :as lib.util]
[metabase.query-processor.middleware.fetch-source-query :as fetch-source-query]
[metabase.query-processor.middleware.metrics :as metrics]
+ ^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]
[metabase.query-processor.test :as qp]
[metabase.test :as mt]
[metabase.util :as u]
@@ -320,6 +321,25 @@
[:field {} (meta/id :products :rating)]]]]]]}]}
(adjust query)))))
+(deftest ^:parallel metric-defined-as-ratio-of-metrics-test
+ (testing "a metric defined as a custom-named ratio of two different metric refs expands both nested :metric clauses and executes (#30574)"
+ (let [base-mp (mt/metadata-provider)
+ ;; Two DIFFERENT metrics so the ratio is discriminating: if both refs collapsed to the same
+ ;; underlying aggregation the result would be 1.0 and tell us nothing about what was expanded.
+ count-q (-> (lib/query base-mp (lib.metadata/table base-mp (mt/id :products)))
+ (lib/aggregate (lib/count)))
+ [m-count mp] (mock-metric base-mp count-q {:name "Count metric", :database-id (mt/id)})
+ sum-q (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/aggregate (lib/sum (lib.metadata/field mp (mt/id :products :rating)))))
+ [m-sum mp] (mock-metric mp sum-q {:name "Sum metric", :database-id (mt/id)})
+ m2-query (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/aggregate (-> (lib// (lib.metadata/metric mp (:id m-count)) (lib.metadata/metric mp (:id m-sum)))
+ (lib/with-expression-name "X"))))
+ [m2 mp] (mock-metric mp m2-query {:name "M2", :database-id (mt/id)})
+ query (lib/query mp (lib.metadata/card mp (:id m2)))]
+ ;; count(products)=200 / sum(rating)=694.3 = 0.2881 (rounded), i.e. clearly not 1.0.
+ (is (= [[0.2881]] (mt/formatted-rows [4.0] (qp/process-query query)))))))
+
(deftest ^:parallel adjust-filter-test
(let [[source-metric mp] (mock-metric (lib/filter (basic-metric-query) (lib/> (meta/field-metadata :products :price) 1)))
query (-> (lib/query mp source-metric)
@@ -866,6 +886,35 @@
[u.date/temporal-str->iso8601-str int]
(mt/rows (qp/process-query query)))))))
+(deftest ^:parallel metric-card-with-field-filter-parameter-test
+ (testing "a mapped field-filter parameter narrows a metric card's result via an implicit join, matching an explicit filter"
+ (let [mp0 (mt/metadata-provider)
+ [metric mp] (mock-metric mp0
+ (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ (lib/aggregate (lib/count)))
+ {:name "Orders, Count", :database-id (mt/id)})
+ metric-id (:id metric)]
+ (qp.store/with-metadata-provider mp
+ (let [orders-query (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ ;; products.category reached from orders via the product_id FK (an implicit join)
+ category-col (m/find-first #(and (= (mt/id :products :category) (:id %))
+ (= (mt/id :orders :product_id) (:fk-field-id %)))
+ (lib/visible-columns orders-query))
+ metric-agg (lib.metadata/metric mp metric-id)
+ param-query (-> orders-query
+ (lib/aggregate metric-agg)
+ (assoc :parameters
+ [{:type :string/=
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref category-col))]
+ :value ["Gadget"]}]))
+ filter-query (-> orders-query
+ (lib/aggregate metric-agg)
+ (lib/filter (lib/= category-col "Gadget")))
+ param-rows (mt/rows (qp/process-query param-query))]
+ (is (seq param-rows))
+ (is (= (mt/rows (qp/process-query filter-query))
+ param-rows)))))))
+
(deftest ^:parallel metric-in-offset-test
(let [mp (mt/metadata-provider)
metric-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
diff --git a/test/metabase/query_processor/middleware/parameters/mbql_test.clj b/test/metabase/query_processor/middleware/parameters/mbql_test.clj
index 17546466342..4bafac61408 100644
--- a/test/metabase/query_processor/middleware/parameters/mbql_test.clj
+++ b/test/metabase/query_processor/middleware/parameters/mbql_test.clj
@@ -6,9 +6,11 @@
(:require
[clojure.string :as str]
[clojure.test :refer :all]
+ [medley.core :as m]
[metabase.driver :as driver]
[metabase.driver.util :as driver.u]
[metabase.legacy-mbql.normalize :as mbql.normalize]
+ [metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util.macros :as lib.tu.macros]
@@ -515,3 +517,137 @@
:value :week}]})]
(is (=? ["2016-04-30T00:00:00Z" "2016-04-24T00:00:00Z" 1]
(first (mt/rows (mt/process-query query))))))))
+
+(deftest ^:parallel param-targeting-explicit-join-column-test
+ (testing "a param with a :dimension target carrying {:join-alias …} compiles to a filter on the explicitly-joined column (#43799)"
+ (let [mp meta/metadata-provider
+ products (meta/table-metadata :products)
+ base (lib/query mp (meta/table-metadata :orders))
+ query (lib/join base (-> (lib/join-clause products (lib/suggested-join-conditions base products))
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields :all)))
+ title-col (m/find-first #(and (= (:id %) (meta/id :products :title))
+ (= (:lib/join-alias %) "Products"))
+ (lib/visible-columns query))]
+ (is (=? {:query {:filter [:= [:field (meta/id :products :title) {:join-alias "Products"}] "Google"]}}
+ (expand-parameters
+ (-> (lib.convert/->legacy-MBQL query)
+ (assoc :parameters
+ [{:type :string/=
+ :value ["Google"]
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref title-col))]}]))))))))
+
+(deftest ^:parallel boolean-mbql-parameter-test
+ (testing "a boolean/= param mapped to a boolean expression column expands to an equality filter on that expression"
+ (let [mp meta/metadata-provider
+ query (as-> (lib/query mp (meta/table-metadata :products)) q
+ (lib/expression q "Bool" (lib/= (meta/field-metadata :products :id) 1))
+ (lib/with-fields q [(meta/field-metadata :products :id)
+ (m/find-first #(= (:lib/expression-name %) "Bool")
+ (lib/visible-columns q))]))]
+ (doseq [v [true false]]
+ (testing (format "value = %s" (pr-str v))
+ (is (=? {:query {:filter [:= [:expression "Bool" {:base-type :type/Boolean}] v]}}
+ (expand-parameters
+ (-> (lib.convert/->legacy-MBQL query)
+ (assoc :parameters
+ [{:type :boolean/=
+ :value [v]
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/expression-ref query "Bool"))]}]))))))))))
+
+(deftest ^:parallel duplicate-temporal-unit-params-same-breakout-test
+ ;; NOTE: this pins CURRENT product behavior. The documented intent for #44684 is for the LAST param to take priority
+ ;; (which would yield :year here), but that is not what the product does today for two params on the *same* breakout.
+ (testing (str "two temporal-unit params on the same breakout: the FIRST matching param wins (:quarter) as a mechanical"
+ " consequence of sequential expansion — each param retargets by matching the breakout's current unit, so"
+ " once the first changes :month to :quarter the second (still targeting :month) no longer matches and is"
+ " a no-op (#44684)")
+ (let [mp meta/metadata-provider
+ created-at (meta/field-metadata :orders :created-at)
+ month-ref (fn [] (lib.convert/->legacy-MBQL (lib/with-temporal-bucket (lib/ref created-at) :month)))
+ query (-> (lib/query mp (meta/table-metadata :orders))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))]
+ (is (=? {:query {:breakout [[:field (meta/id :orders :created-at) {:temporal-unit :quarter}]]}}
+ (expand-parameters
+ (-> (lib.convert/->legacy-MBQL query)
+ (assoc :parameters
+ [{:type :temporal-unit, :target [:dimension (month-ref)], :value :quarter}
+ {:type :temporal-unit, :target [:dimension (month-ref)], :value :year}]))))))))
+
+(deftest ^:parallel temporal-unit-param-disambiguates-same-column-breakouts-test
+ (testing "two temporal-unit params retarget only the breakout matching their current unit (#46536, #46776)"
+ (let [mp meta/metadata-provider
+ created-at (meta/field-metadata :orders :created-at)
+ bucket (fn [u] (lib/with-temporal-bucket created-at u))
+ ;; parameter :target dimensions carry LEGACY field refs even inside an MBQL 5 stage
+ legacy-bucket (fn [u] (lib.convert/->legacy-MBQL (lib/ref (bucket u))))
+ query (-> (lib/query mp (meta/table-metadata :orders))
+ (lib/aggregate (lib/count))
+ (lib/breakout (bucket :year))
+ (lib/breakout (bucket :month))
+ (lib/update-query-stage
+ 0 assoc :parameters
+ [{:type :temporal-unit
+ :value "quarter"
+ :target [:dimension (legacy-bucket :year) {}]}
+ {:type :temporal-unit
+ :value "week"
+ :target [:dimension (legacy-bucket :month) {}]}]))]
+ (is (=? {:stages [{:breakout [[:field {:temporal-unit :quarter} (meta/id :orders :created-at)]
+ [:field {:temporal-unit :week} (meta/id :orders :created-at)]]}]}
+ (expand-parameters query))))))
+
+(deftest ^:parallel bigint-number-operators-test
+ (testing "number operator params preserve type/BigInteger values without collapsing to a double (#5816)"
+ (let [mp meta/metadata-provider
+ big (biginteger "9223372036854775808")
+ id-ref (lib.convert/->legacy-MBQL (lib/ref (meta/field-metadata :orders :id)))]
+ (doseq [[ptype value expected]
+ [[:number/!= [big] [:!= [:field (meta/id :orders :id) {:base-type :type/BigInteger}] big]]
+ [:number/>= [big] [:>= [:field (meta/id :orders :id) {:base-type :type/BigInteger}] big]]
+ [:number/<= [big] [:<= [:field (meta/id :orders :id) {:base-type :type/BigInteger}] big]]
+ [:number/between [0 big] [:between [:field (meta/id :orders :id) {:base-type :type/BigInteger}] 0 big]]]]
+ (testing (pr-str ptype)
+ (is (=? {:query {:filter expected}}
+ (expand-parameters
+ (-> (lib.convert/->legacy-MBQL (lib/query mp (meta/table-metadata :orders)))
+ (assoc :parameters
+ [{:type ptype
+ :value value
+ :target [:dimension id-ref]}]))))))))))
+
+(deftest ^:parallel two-params-same-column-conjunction-test
+ (testing "two params mapped to the same column AND-combine (intersection)"
+ (let [mp meta/metadata-provider
+ cat-ref (lib.convert/->legacy-MBQL (lib/ref (meta/field-metadata :products :category)))]
+ (is (=? {:query {:filter [:and
+ [:= [:field (meta/id :products :category) {:base-type :type/Text}] "Doohickey" "Gizmo"]
+ [:= [:field (meta/id :products :category) {:base-type :type/Text}] "Gadget"]]}}
+ (expand-parameters
+ (-> (lib.convert/->legacy-MBQL (-> (lib/query mp (meta/table-metadata :products))
+ (lib/aggregate (lib/count))))
+ (assoc :parameters
+ [{:type :string/=
+ :value ["Doohickey" "Gizmo"]
+ :target [:dimension cat-ref]}
+ {:type :string/=
+ :value ["Gadget"]
+ :target [:dimension cat-ref]}]))))))))
+
+(deftest ^:parallel temporal-unit-allowlist-not-enforced-at-execution-test
+ (testing "a :temporal_units allow-list on the parameter is not enforced when expanding the query"
+ (let [mp meta/metadata-provider
+ created-at (meta/field-metadata :orders :created-at)
+ month-ref (lib.convert/->legacy-MBQL (lib/ref (lib/with-temporal-bucket created-at :month)))
+ query (-> (lib/query mp (meta/table-metadata :orders))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created-at :month)))]
+ (is (=? {:query {:breakout [[:field (meta/id :orders :created-at) {:temporal-unit :year}]]}}
+ (expand-parameters
+ (-> (lib.convert/->legacy-MBQL query)
+ (assoc :parameters
+ [{:type :temporal-unit
+ :target [:dimension month-ref]
+ :value :year
+ :temporal_units [:month :quarter]}]))))))))
diff --git a/test/metabase/query_processor/middleware/parameters_test.clj b/test/metabase/query_processor/middleware/parameters_test.clj
index 9f48aaf3013..128efb63958 100644
--- a/test/metabase/query_processor/middleware/parameters_test.clj
+++ b/test/metabase/query_processor/middleware/parameters_test.clj
@@ -502,3 +502,21 @@
[:expression {} "Quantity_2"]
14]]}]}
(substitute-params query)))))
+
+(deftest ^:parallel temporal-expression-parameter-test
+ (testing "a temporal (date) param mapped to an [:expression] custom column compiles to a temporal filter (#17775, #34955)"
+ (let [query (as-> (lib/query meta/metadata-provider (meta/table-metadata :orders)) q
+ (lib/expression q "CC Date" (meta/field-metadata :orders :created-at))
+ (assoc q :parameters
+ [{:id "c77842b9"
+ :target [:dimension
+ (lib/->legacy-MBQL (lib/expression-ref q "CC Date"))
+ {:stage-number 0}]
+ :type :date/range
+ :value "2026-01-01~2026-03-31"}]))]
+ (is (=? {:stages [{:filters [[:between
+ {}
+ [:expression {} "CC Date"]
+ "2026-01-01"
+ "2026-03-31"]]}]}
+ (substitute-params query))))))
diff --git a/test/metabase/query_processor/middleware/permissions_test.clj b/test/metabase/query_processor/middleware/permissions_test.clj
index 80ec570ad13..f4a440a8bab 100644
--- a/test/metabase/query_processor/middleware/permissions_test.clj
+++ b/test/metabase/query_processor/middleware/permissions_test.clj
@@ -4,6 +4,7 @@
:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.query-processor.middleware.permissions-test]}}}}}}
(:require
[clojure.test :refer :all]
+ [medley.core :as m]
[metabase.api.common :as api]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
@@ -2424,3 +2425,74 @@
(when (map? result)
(is (re-find #"(?i)permission" (str (:message result) (:error result) (:error_type result)))
"Join to an unauthorized table via pivot download is blocked"))))))))
+
+(deftest query-runs-when-fk-target-table-blocked-test
+ (testing "a query on ORDERS succeeds and resolves the Product ID FK column even though the FK target PRODUCTS is blocked (#76710)"
+ (mt/with-temp-copy-of-db
+ (mt/with-no-data-perms-for-all-users!
+ (perms/set-table-permission! (perms/all-users-group) (mt/id :orders) :perms/view-data :unrestricted)
+ (perms/set-table-permission! (perms/all-users-group) (mt/id :orders) :perms/create-queries :query-builder)
+ (perms/set-table-permission! (perms/all-users-group) (mt/id :products) :perms/view-data :blocked)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/order-by (lib.metadata/field mp (mt/id :orders :id)) :asc)
+ (lib/limit 5))]
+ (mt/with-test-user :rasta
+ (is (seq (mt/rows (qp/process-query query))))))))))
+
+(deftest e2e-model-based-metric-blocked-table-passthrough-test
+ (testing "a user who cannot build ad-hoc queries can still run a metric card sourced from a model, via card-perms passthrough"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp-copy-of-db
+ (mt/with-no-data-perms-for-all-users!
+ (perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data :unrestricted)
+ (perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/create-queries :no)
+ (mt/with-temp [:model/Collection collection]
+ (perms/grant-collection-read-permissions! (perms/all-users-group) collection)
+ (let [mp (mt/metadata-provider)
+ model-query (lib/query mp (lib.metadata/table mp (mt/id :orders)))]
+ (mt/with-temp [:model/Card {model-id :id} {:collection_id (u/the-id collection)
+ :type :model
+ :dataset_query model-query}]
+ (let [mp2 (mt/metadata-provider)
+ metric-query (-> (lib/query mp2 (lib.metadata/card mp2 model-id))
+ (lib/aggregate (lib/count)))]
+ (mt/with-temp [:model/Card metric {:collection_id (u/the-id collection)
+ :type :metric
+ :dataset_query metric-query}]
+ (mt/with-test-user :rasta
+ (binding [qp.perms/*card-id* (u/the-id metric)]
+ (is (= [[18760]]
+ (mt/rows (qp/process-query (:dataset_query metric)))))))))))))))))
+
+(deftest post-agg-filter-over-native-model-nosql-user-test
+ (testing "a GUI/nosql user can run a multi-stage query over a native-SQL model with a post-aggregation filter (#48771)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp-copy-of-db
+ (mt/with-no-data-perms-for-all-users!
+ (perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/view-data :unrestricted)
+ ;; query-builder (not query-builder-and-native): the user has no native access
+ (perms/set-database-permission! (perms/all-users-group) (mt/id) :perms/create-queries :query-builder)
+ (mt/with-temp [:model/Collection collection]
+ (perms/grant-collection-read-permissions! (perms/all-users-group) collection)
+ (let [mp (mt/metadata-provider)
+ native (lib/native-query mp "SELECT * FROM orders")]
+ (mt/with-temp [:model/Card {model-id :id} {:collection_id (u/the-id collection)
+ :type :model
+ :dataset_query native
+ ;; native models need stored result metadata for the
+ ;; downstream GUI query to reference their columns
+ :result_metadata (mt/cols (qp/process-query native))}]
+ (let [mp2 (mt/metadata-provider)
+ base (lib/query mp2 (lib.metadata/card mp2 model-id))
+ uid (m/find-first #(= "user_id" (u/lower-case-en (:name %)))
+ (lib/returned-columns base))
+ stage1 (-> base
+ (lib/aggregate (lib/count))
+ (lib/breakout uid)
+ lib/append-stage)
+ cnt (m/find-first #(= "count" (u/lower-case-en (:name %)))
+ (lib/filterable-columns stage1))
+ query (lib/filter stage1 (lib/> cnt 5))]
+ (mt/with-test-user :rasta
+ (is (seq (mt/rows (qp/process-query query))))))))))))))
diff --git a/test/metabase/query_processor/middleware/process_userland_query_test.clj b/test/metabase/query_processor/middleware/process_userland_query_test.clj
index 61cfb3ac05b..0a1c450be28 100644
--- a/test/metabase/query_processor/middleware/process_userland_query_test.clj
+++ b/test/metabase/query_processor/middleware/process_userland_query_test.clj
@@ -50,7 +50,8 @@
:query-execution-query (:json_query query-execution)})))))]
(run
(fn qe-result* []
- (let [qe (deref result 1000 ::timed-out)]
+ ;; generous deadline: slow exports (xlsx/POI) on loaded CI runners miss a 1s window
+ (let [qe (deref result 30000 ::timed-out)]
(cond-> qe
(:running_time qe) (update :running_time int?)
(:hash qe) (update :hash (fn [^bytes a-hash]
diff --git a/test/metabase/query_processor/middleware/resolve_referenced_test.clj b/test/metabase/query_processor/middleware/resolve_referenced_test.clj
index 6943615a860..f6066ec41a1 100644
--- a/test/metabase/query_processor/middleware/resolve_referenced_test.clj
+++ b/test/metabase/query_processor/middleware/resolve_referenced_test.clj
@@ -7,6 +7,10 @@
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]
+ [metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
+ [metabase.query-processor :as qp]
+ [metabase.query-processor.card :as qp.card]
[metabase.query-processor.middleware.parameters-test :refer [card-template-tags]]
[metabase.query-processor.middleware.resolve-referenced :as qp.resolve-referenced]
[metabase.test :as mt])
@@ -41,6 +45,32 @@
:metadata/column
(mt/id :venues :price)))))))
+(deftest native-card-ref-runs-with-card-read-only-perms-test
+ (testing "a saved native card referencing another card via a {{#id}} tag executes for a user with card-read but no table data perms"
+ (mt/dataset test-data
+ (mt/with-no-data-perms-for-all-users!
+ ;; a viewer-only user: can view data (so not blocked) but cannot build ad-hoc queries
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :unrestricted)
+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/create-queries :no)
+ ;; allowing `with-temp` here: this exercises app-DB permission enforcement (card-read perms, current user)
+ ;; via `process-query-for-card`, which a metadata provider does not model
+ (let [mp (mt/metadata-provider)]
+ #_{:clj-kondo/ignore [:discouraged-var]}
+ (mt/with-temp
+ [:model/Card {parent-id :id} {:database_id (mt/id)
+ :dataset_query (lib/native-query mp "SELECT * FROM PEOPLE WHERE STATE = 'WA'")}
+ ;; the {{#<parent-id>}} tag is a card reference; lib extracts it as a :card tag with :card-id parent-id
+ :model/Card child-card {:database_id (mt/id)
+ :dataset_query (lib/native-query mp (format "SELECT COUNT(*) FROM {{#%d}}" parent-id))}]
+ (mt/with-test-user :rasta
+ (is (= [[41]]
+ (mt/rows
+ (qp.card/process-query-for-card
+ child-card :api
+ :make-run (constantly
+ (fn [query info]
+ (qp/process-query (assoc query :info (assoc info :query-hash (byte-array 0)))))))))))))))))
+
(deftest ^:parallel referenced-query-from-different-db-test
(testing "fails on query that references a native query from a different database"
(let [metadata-provider meta/metadata-provider
diff --git a/test/metabase/query_processor/nested_queries_test.clj b/test/metabase/query_processor/nested_queries_test.clj
index cd9a6897d01..200624c176b 100644
--- a/test/metabase/query_processor/nested_queries_test.clj
+++ b/test/metabase/query_processor/nested_queries_test.clj
@@ -1762,3 +1762,447 @@
(mt/rows query)))
(is (= ""
(-> query :data :results_metadata :columns first :name))))))))
+
+;;; A date equality/range filter's result count must be identical whether applied to the base question or an ad-hoc
+;;; nested query, for the after/before (`>`+`<`) and on-day (`=`) variants (extends date-range-test, #15352).
+(deftest ^:parallel date-range-parity-after-before-and-on-day-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries)
+ (testing "after/before and on-day date filters give the same count directly and nested (#15352)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ created (lib.metadata/field mp (mt/id :orders :created_at))]
+ (doseq [flt [[(lib/> created "2020-01-31") (lib/< created "2020-03-01")]
+ [(lib/= created "2020-02-01")]]]
+ (let [base (reduce lib/filter
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count)))
+ flt)
+ nested (lib/append-stage base)]
+ (is (= (mt/formatted-rows [int] (qp/process-query base))
+ (mt/formatted-rows [int] (qp/process-query nested)))
+ (str "filter " (pr-str flt))))))))))
+
+;;; The Distribution drill (count + binned breakout) and Sum-over-time drill (sum by month) must build and execute
+;;; over a nested card source, matching the results of the same aggregation run directly on the table.
+(deftest ^:parallel distribution-and-sum-over-time-on-nested-question-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (testing "sum-over-time and distribution drills execute over a nested card source (#12568)"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ mp (qp.test-util/metadata-provider-with-cards-for-queries
+ mp0 [(lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))])
+ total (lib.metadata/field mp (mt/id :orders :total))
+ created (lib.metadata/field mp (mt/id :orders :created_at))
+ quantity (lib.metadata/field mp (mt/id :orders :quantity))]
+ (testing "sum over time (sum of total by month)"
+ (is (= (mt/formatted-rows [str 2.0]
+ (qp/process-query
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/sum total))
+ (lib/breakout (lib/with-temporal-bucket created :month)))))
+ (mt/formatted-rows [str 2.0]
+ (qp/process-query
+ (-> (lib/query mp (lib.metadata/card mp 1))
+ (lib/aggregate (lib/sum total))
+ (lib/breakout (lib/with-temporal-bucket created :month))))))))
+ (testing "distribution (count by binned quantity)"
+ (is (= (mt/formatted-rows [1.0 int]
+ (qp/process-query
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-binning quantity {:strategy :num-bins :num-bins 8})))))
+ (mt/formatted-rows [1.0 int]
+ (qp/process-query
+ (-> (lib/query mp (lib.metadata/card mp 1))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-binning quantity {:strategy :num-bins :num-bins 8})))))))))))))
+
+(defn- do-with-native-source-card
+ "Compile `source-query` (a lib query) to native SQL per-driver, expose it as a saved native card with result
+ metadata, and invoke `f` with the nested lib query over the card plus the seq of the card's returned columns
+ (each test picks the column it needs by destructuring/name, never by a hardcoded column-name literal)."
+ [source-query f]
+ (let [mp (lib.metadata/->metadata-provider source-query)
+ native (-> source-query qp.compile/compile :query)
+ mp+card (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries
+ mp [(lib/native-query mp native)])
+ nested (lib/query mp+card (lib.metadata/card mp+card 1))]
+ (f nested (lib/returned-columns nested))))
+
+;;; A nested query over a saved native question can group by / aggregate one of the native card's result columns.
+(deftest ^:parallel aggregate-over-native-card-result-column-test
+ (mt/test-drivers (set/intersection (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (descendants driver/hierarchy :sql))
+ (testing "count/avg over a saved native question's result column (#15397)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)]
+ (do-with-native-source-card
+ ;; :limit keeps the breakout's ORDER BY legal inside the wrapping subquery on SQL Server
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib.metadata/field mp (mt/id :orders :product_id)))
+ (lib/limit 100))
+ (fn [nested [_product-id cnt-col]]
+ (let [rows (mt/rows (qp/process-query (lib/aggregate nested (lib/avg cnt-col))))]
+ (is (= 1 (count rows)))
+ (is (number? (ffirst rows)))))))))))
+
+;;; When a source query aggregates a count broken out by an implicit-join (source-field) FK column, an outer stage
+;;; that filters on the aggregate must retain the implicit-join breakout column.
+(deftest ^:parallel post-aggregation-filter-preserves-implicit-join-breakout-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations :left-join)
+ (testing "outer filter keeps the source-field breakout column (#11561)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ query (as-> (lib/query mp (lib.metadata/table mp (mt/id :orders))) q
+ (lib/aggregate q (lib/count))
+ (lib/breakout q (m/find-first #(and (= (mt/id :people :id) (:id %))
+ (= (mt/id :orders :user_id) (:fk-field-id %)))
+ (lib/breakoutable-columns q)))
+ (lib/append-stage q)
+ (lib/filter q (lib/= (m/find-first #(= "count" (u/lower-case-en (:name %)))
+ (lib/filterable-columns q))
+ 5)))]
+ (is (some #(= (mt/id :people :id) (:id %))
+ (qp.preprocess/query->expected-cols query)))
+ (is (=? {:status :completed} (qp/process-query query))))))))
+
+;;; An integer field-literal filter over a nested native-card query returns only the matching rows.
+(deftest ^:parallel integer-filter-on-native-card-source-test
+ (mt/test-drivers (set/intersection (mt/normal-drivers-with-feature :nested-queries)
+ (descendants driver/hierarchy :sql))
+ (testing "RATING = 4 filter over a native card selecting reviews columns (#15808)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)]
+ (do-with-native-source-card
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :reviews)))
+ (lib/with-fields [(lib.metadata/field mp (mt/id :reviews :id))
+ (lib.metadata/field mp (mt/id :reviews :rating))]))
+ (fn [nested [_id rating-col]]
+ (let [rows (mt/formatted-rows [int int]
+ (qp/process-query (lib/filter nested (lib/= rating-col 4))))]
+ (is (seq rows))
+ (is (every? #(= 4 (nth % 1)) rows))))))))))
+
+;;; A temporal breakout over a native model whose CREATED_AT column carries a DateTime base-type buckets and executes;
+;;; the bucket counts must sum to the full order count.
+(deftest ^:parallel temporal-breakout-over-native-model-test
+ (mt/test-drivers (set/intersection (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (descendants driver/hierarchy :sql))
+ (testing "month breakout over a native card exposing CREATED_AT (#29517)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)]
+ (do-with-native-source-card
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/with-fields [(lib.metadata/field mp (mt/id :orders :id))
+ (lib.metadata/field mp (mt/id :orders :created_at))]))
+ (fn [nested [_id created-col]]
+ (let [rows (mt/formatted-rows [identity int]
+ (qp/process-query
+ (-> nested
+ (lib/breakout (lib/with-temporal-bucket created-col :month))
+ (lib/aggregate (lib/count)))))]
+ (is (seq rows))
+ (is (= 18760 (reduce + (map #(nth % 1) rows))))))))))))
+
+;;; A distinct aggregation over a native-model column executes.
+(deftest ^:parallel distinct-over-native-model-column-test
+ (mt/test-drivers (set/intersection (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (descendants driver/hierarchy :sql))
+ (testing "distinct over a native card's SOURCE column (#52465)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)]
+ (do-with-native-source-card
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :people)))
+ (lib/with-fields [(lib.metadata/field mp (mt/id :people :id))
+ (lib.metadata/field mp (mt/id :people :source))]))
+ (fn [nested [_id source-col]]
+ (is (= [[5]]
+ (mt/formatted-rows [int]
+ (qp/process-query (lib/aggregate nested (lib/distinct source-col)))))))))))))
+
+;;; Two same-column breakouts exposed by a saved source card must both be referenceable downstream.
+(deftest ^:parallel same-column-breakouts-from-source-card-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (testing "both disambiguated same-column breakout columns are referenceable through a card source (#46536)"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ total (lib.metadata/field mp0 (mt/id :orders :total))
+ card-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-binning total {:strategy :num-bins :num-bins 10}))
+ (lib/breakout (lib/with-binning total {:strategy :num-bins :num-bins 50})))
+ mp (qp.test-util/metadata-provider-with-cards-for-queries mp0 [card-q])
+ base (lib/query mp (lib.metadata/card mp 1))
+ [total-1 total-2] (lib/returned-columns base)]
+ (testing "the source card exposes two distinct total-derived breakout columns plus the count"
+ (is (= 3 (count (mt/cols (qp/process-query base))))))
+ (testing "a downstream filter can reference each disambiguated column"
+ (let [result (qp/process-query
+ (-> base
+ (lib/filter (lib/between total-1 10 50))
+ (lib/filter (lib/between total-2 10 50))))]
+ (is (=? {:status :completed} result))
+ (is (seq (mt/rows result))))))))))
+
+;;; An expression breakout inherited from a source card is sortable in a following stage. The expression yields an
+;;; integer (1/0) rather than a bare boolean so the shape runs on every driver (Oracle has no boolean SQL type and
+;;; Mongo can't select/sort a raw boolean expression); #49305 is about sorting the inherited expression breakout, and
+;;; the boolean-ness is incidental.
+(deftest ^:parallel sort-by-source-card-expression-breakout-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :expressions)
+ (testing "#49305 an expression breakout inherited from a source card is sortable"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ category (lib.metadata/field mp0 (mt/id :products :category))
+ card-q (as-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :products))) q
+ (lib/expression q "b" (lib/case [[(lib/starts-with category "Gi") 1]] 0))
+ (lib/aggregate q (lib/count))
+ (lib/breakout q (lib/expression-ref q "b")))
+ mp (qp.test-util/metadata-provider-with-cards-for-queries mp0 [card-q])
+ base (lib/query mp (lib.metadata/card mp 1))
+ b-col (m/find-first #(= "b" (u/lower-case-en (:name %))) (lib/returned-columns base))]
+ (is (= [[1] [0]]
+ (mt/formatted-rows [int]
+ (qp/process-query
+ (-> base
+ (lib/with-fields [b-col])
+ (lib/order-by b-col :desc)))))))))))
+
+;;; A custom column that is just a field reference (CREATED_AT) survives nesting as a distinct column.
+(deftest ^:parallel field-only-expression-survives-nesting-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :expressions)
+ (testing "#25189 a field-only expression is preserved as a distinct column when nested"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ card-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ (lib/expression "Custom Created" (lib.metadata/field mp0 (mt/id :orders :created_at)))
+ (lib/limit 5))
+ mp (qp.test-util/metadata-provider-with-cards-for-queries mp0 [card-q])
+ cols (mt/cols (qp/process-query (-> (lib/query mp (lib.metadata/card mp 1)) (lib/limit 1))))]
+ (is (contains? (set (map :name cols)) "Custom Created")))))))
+
+;;; An outer expression can reference two named aggregation columns (a plain agg and one that self-references
+;;; aggregation 0) exposed by a source card.
+(deftest ^:parallel reference-source-card-aggregation-columns-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations :expression-aggregations)
+ (testing "an outer custom column references named aggregation columns from a source card"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ subtotal (lib.metadata/field mp0 (mt/id :orders :subtotal))
+ tax (lib.metadata/field mp0 (mt/id :orders :tax))
+ card-q (as-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders))) q
+ (lib/aggregate q (lib/with-expression-name (lib/min subtotal) "Foo"))
+ (lib/aggregate q (lib/with-expression-name
+ (lib/+ (lib/aggregation-ref q 0) (lib/avg tax))
+ "Bar")))
+ mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries mp0 [card-q])
+ base (lib/query mp (lib.metadata/card mp 1))
+ cols (lib/returned-columns base)
+ foo-col (m/find-first #(= "foo" (u/lower-case-en (:name %))) cols)
+ bar-col (m/find-first #(= "bar" (u/lower-case-en (:name %))) cols)
+ [[foo bar sum]] (mt/rows (qp/process-query
+ (lib/expression base "Sum" (lib/+ foo-col bar-col))))]
+ (is (every? number? [foo bar sum]))
+ (is (< (abs (- (double sum) (+ (double foo) (double bar)))) 1e-6)))))))
+
+;;; A string-named field ref inside a later-stage expression resolves against the source-card columns and is
+;;; usable as a breakout.
+(deftest ^:parallel expression-string-named-field-ref-nested-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations :expressions)
+ (testing "#18814 a string-named field ref inside a nested expression breaks out correctly"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ created (lib.metadata/field mp0 (mt/id :orders :created_at))
+ card-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created :year)))
+ mp (qp.test-util/metadata-provider-with-cards-for-queries mp0 [card-q])
+ base (lib/query mp (lib.metadata/card mp 1))
+ cc-src (m/find-first #(= (mt/id :orders :created_at) (:id %)) (lib/returned-columns base))
+ result (qp/process-query
+ (as-> base q
+ (lib/expression q "CC" cc-src)
+ (lib/breakout q (lib/expression-ref q "CC"))
+ (lib/aggregate q (lib/count))))]
+ (is (=? {:status :completed} result))
+ (is (seq (mt/rows result))))))))
+
+;;; Value expressions exported by a source card can be referenced as filter operands against real columns.
+(deftest ^:parallel value-expression-from-source-card-as-filter-operand-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :expressions :expression-literals)
+ (testing "QUE-726 a source card's value expressions are usable as filter operands"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ id (lib.metadata/field mp0 (mt/id :products :id))
+ title (lib.metadata/field mp0 (mt/id :products :title))
+ price (lib.metadata/field mp0 (mt/id :products :price))
+ card-q (as-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :products))) q
+ (lib/expression q "Rustic" "Rustic Paper Wallet")
+ (lib/expression q "MinPrice" 20.0)
+ (lib/with-fields q [id title price
+ (lib/expression-ref q "Rustic")
+ (lib/expression-ref q "MinPrice")]))
+ mp (qp.test-util/metadata-provider-with-cards-for-queries mp0 [card-q])
+ base (lib/query mp (lib.metadata/card mp 1))
+ cols (lib/returned-columns base)
+ title-col (m/find-first #(= (mt/id :products :title) (:id %)) cols)
+ price-col (m/find-first #(= (mt/id :products :price) (:id %)) cols)
+ rustic-col (m/find-first #(= "rustic" (u/lower-case-en (:name %))) cols)
+ min-col (m/find-first #(= "minprice" (u/lower-case-en (:name %))) cols)
+ rows (mt/rows (qp/process-query
+ (-> base
+ (lib/filter (lib/= title-col rustic-col))
+ (lib/filter (lib/> price-col min-col)))))]
+ (is (seq rows))
+ (is (every? #(= "Rustic Paper Wallet" (nth % 1)) rows)))))))
+
+;;; A distinct aggregation over a nested "Average of Total" column returns the right scalar.
+(deftest ^:parallel distinct-over-nested-aggregation-column-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (testing "distinct over a nested avg aggregation column (#24839)"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ quantity (lib.metadata/field mp0 (mt/id :orders :quantity))
+ total (lib.metadata/field mp0 (mt/id :orders :total))
+ created (lib.metadata/field mp0 (mt/id :orders :created_at))
+ card-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ (lib/aggregate (lib/sum quantity))
+ (lib/aggregate (lib/avg total))
+ (lib/breakout (lib/with-temporal-bucket created :month)))
+ mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries mp0 [card-q])
+ base (lib/query mp (lib.metadata/card mp 1))
+ ;; source columns are [month, sum, avg]
+ source-rows (mt/rows (qp/process-query base))
+ expected (count (distinct (map #(nth % 2) source-rows)))
+ avg-col (nth (lib/returned-columns base) 2)
+ actual (ffirst (mt/formatted-rows [int]
+ (qp/process-query (lib/aggregate base (lib/distinct avg-col)))))]
+ (is (pos? expected))
+ (is (= expected actual)))))))
+
+;;; A two-level query with an outer filter on the outer breakout dimension returns one row.
+(deftest ^:parallel filter-by-outer-breakout-column-multi-stage-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (testing "filter by an outer breakout column in a multi-stage query (#25016)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ created (lib.metadata/field mp (mt/id :products :created_at))
+ category (lib.metadata/field mp (mt/id :products :category))
+ stage2 (-> (lib/query mp (lib.metadata/table mp (mt/id :products)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created :month))
+ (lib/breakout category)
+ lib/append-stage)
+ cat-col (m/find-first #(= (mt/id :products :category) (:id %))
+ (lib/breakoutable-columns stage2))
+ query (-> stage2
+ (lib/aggregate (lib/count))
+ (lib/breakout cat-col)
+ (lib/filter (lib/= cat-col "Gadget")))]
+ (is (= 1 (count (mt/rows (qp/process-query query))))))))))
+
+;;; Reducing a source card's :fields exposes only those columns to a nested query.
+(deftest ^:parallel reduced-source-fields-propagate-to-nested-query-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries)
+ (testing "reducing a source card's :fields propagates to a nested query (#30610, #43216)"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ card-q (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ (lib/with-fields [(lib.metadata/field mp0 (mt/id :orders :id))]))
+ mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries mp0 [card-q])
+ cols (mt/cols (qp/process-query (lib/query mp (lib.metadata/card mp 1))))]
+ (is (= [(mt/id :orders :id)] (map :id cols)))
+ (is (= [(u/lower-case-en (:name (lib.metadata/field mp0 (mt/id :orders :id))))]
+ (map (comp u/lower-case-en :name) cols))))))))
+
+;;; Removing Products.Created At from a source card's join :fields must not shift a downstream filter on the
+;;; same-named Reviews.Created At column: the filtered count is unchanged.
+(deftest ^:parallel remove-same-named-join-field-keeps-downstream-filter-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations :left-join)
+ (testing "dropping a same-named join field from the source card does not shift the downstream filter (#54920)"
+ (mt/dataset test-data
+ (letfn [(count-with-products-created-at? [include-products-created-at?]
+ (let [mp0 (mt/metadata-provider)
+ orders (lib/query mp0 (lib.metadata/table mp0 (mt/id :orders)))
+ products-t (lib.metadata/table mp0 (mt/id :products))
+ product-id (lib.metadata/field mp0 (mt/id :orders :product_id))
+ prod-category (lib.metadata/field mp0 (mt/id :products :category))
+ prod-created (lib.metadata/field mp0 (mt/id :products :created_at))
+ rev-rating (lib.metadata/field mp0 (mt/id :reviews :rating))
+ rev-created (lib.metadata/field mp0 (mt/id :reviews :created_at))
+ rev-product-id (lib.metadata/field mp0 (mt/id :reviews :product_id))
+ products-join (-> (lib/join-clause products-t (lib/suggested-join-conditions orders products-t))
+ (lib/with-join-alias "Products")
+ (lib/with-join-fields (if include-products-created-at?
+ [prod-category prod-created]
+ [prod-category])))
+ reviews-join (-> (lib/join-clause (lib.metadata/table mp0 (mt/id :reviews))
+ [(lib/= product-id rev-product-id)])
+ (lib/with-join-alias "Reviews")
+ (lib/with-join-fields [rev-rating rev-created]))
+ card-q (-> orders
+ (lib/join products-join)
+ (lib/join reviews-join))
+ mp (qp.test-util/metadata-provider-with-cards-with-metadata-for-queries mp0 [card-q])
+ base (lib/query mp (lib.metadata/card mp 1))
+ reviews-created (m/find-first #(= (mt/id :reviews :created_at) (:id %))
+ (lib/returned-columns base))]
+ (count (mt/rows (qp/process-query
+ (lib/filter base (lib/between reviews-created "2019-01-01" "2020-01-01")))))))]
+ (is (= (count-with-products-created-at? true)
+ (count-with-products-created-at? false))))))))
+
+;;; A filter over an aggregation-result column in an appended stage compiles and returns the right rows.
+(deftest ^:parallel filter-on-aggregation-result-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :basic-aggregations)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)]
+ (testing "starts-with filter on a max(name) aggregation-result column (#22230)"
+ (let [inner (-> (lib/query mp (lib.metadata/table mp (mt/id :people)))
+ (lib/aggregate (lib/max (lib.metadata/field mp (mt/id :people :name))))
+ (lib/breakout (lib.metadata/field mp (mt/id :people :source))))
+ source-rows (mt/rows (qp/process-query inner))
+ expected (count (filter (fn [[_ mx]] (str/starts-with? (str mx) "Zo")) source-rows))
+ actual (count (mt/rows (qp/process-query
+ (as-> (lib/append-stage inner) q
+ (lib/filter q (lib/starts-with
+ (m/find-first #(= "max" (u/lower-case-en (:name %)))
+ (lib/filterable-columns q))
+ "Zo"))))))]
+ (is (= expected actual))))
+ (testing "between-date filter on an aggregation-result column (#25994)"
+ (let [result (qp/process-query
+ (as-> (lib/query mp (lib.metadata/table mp (mt/id :orders))) q
+ (lib/aggregate q (lib/max (lib.metadata/field mp (mt/id :orders :created_at))))
+ (lib/breakout q (lib.metadata/field mp (mt/id :orders :user_id)))
+ (lib/append-stage q)
+ (lib/filter q (lib/between (m/find-first #(= "max" (u/lower-case-en (:name %)))
+ (lib/filterable-columns q))
+ "2018-01-01" "2020-01-01"))))]
+ (is (=? {:status :completed} result))))))))
+
+;;; A filter over an explicitly-joined column exposed through a nested aggregated query resolves and executes.
+(deftest ^:parallel filter-explicit-joined-col-through-nested-query-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :left-join :basic-aggregations)
+ (testing "filter on an explicit-join column through a nested aggregated query (#25990)"
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ orders (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ people-t (lib.metadata/table mp (mt/id :people))
+ created (lib.metadata/field mp (mt/id :orders :created_at))
+ people-join (-> (lib/join-clause people-t (lib/suggested-join-conditions orders people-t))
+ (lib/with-join-alias "P")
+ (lib/with-join-fields :all))
+ inner (lib/join orders people-join)
+ ;; filter the joined column in the aggregating stage, then nest (a later stage cannot reference an
+ ;; inner-only join column)
+ p-id-col (m/find-first #(and (= (mt/id :people :id) (:id %))
+ (= "P" (lib/current-join-alias %)))
+ (lib/visible-columns inner))
+ query (-> inner
+ (lib/filter (lib/= p-id-col 10))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created :month))
+ lib/append-stage)]
+ (is (=? {:status :completed} (qp/process-query query))))))))
diff --git a/test/metabase/query_processor/offset_test.clj b/test/metabase/query_processor/offset_test.clj
index a3e7d3fc0b7..b46c328a708 100644
--- a/test/metabase/query_processor/offset_test.clj
+++ b/test/metabase/query_processor/offset_test.clj
@@ -9,6 +9,7 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.test-util :as lib.tu]
+ [metabase.query-processor.compile :as qp.compile]
[metabase.query-processor.test :as qp]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]))
@@ -261,3 +262,137 @@
(->> query
(qp/process-query)
(mt/formatted-rows [->local-date 2.0 2.0]))))))))
+
+(deftest ^:parallel offset-with-explicit-join-test
+ (testing "offset window over an explicitly-joined breakout column works with the offset first or second, and with avg"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset :left-join)
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ products (lib.metadata/table mp (mt/id :products))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ total (lib.metadata/field mp (mt/id :orders :total))
+ category (lib.metadata/field mp (mt/id :products :category))
+ joined (-> (lib/query mp orders)
+ (lib/join products)
+ (lib/breakout category)
+ (lib/breakout (lib/with-temporal-bucket created-at :year)))]
+ (testing "offset as the first aggregation"
+ (let [rows (mt/rows (qp/process-query
+ (-> joined
+ (lib/aggregate (lib/offset (lib/sum total) -1))
+ (lib/aggregate (lib/sum total)))))]
+ (is (seq rows))
+ (is (some (comp nil? #(nth % 2)) rows))))
+ (testing "offset as the second aggregation"
+ (let [rows (mt/rows (qp/process-query
+ (-> joined
+ (lib/aggregate (lib/sum total))
+ (lib/aggregate (lib/offset (lib/sum total) -1)))))]
+ (is (seq rows))
+ (is (some (comp nil? #(nth % 3)) rows))))
+ (testing "offset of avg applied to a custom column"
+ (let [base (-> (lib/query mp orders)
+ (lib/expression "CC" (lib/* total 2)))
+ cc (m/find-first (comp #{"CC"} :name) (lib/visible-columns base))
+ q (-> base
+ (lib/breakout (lib/with-temporal-bucket created-at :year))
+ (lib/aggregate (lib/offset (lib/avg cc) -1)))]
+ (is (seq (mt/rows (qp/process-query q))))))))))
+
+;; A constant custom column used as a breakout compiles to `PARTITION BY <constant>` in the offset window. The #47870
+;; regression was a query-processor crash while compiling that shape, so assert compilation succeeds rather than
+;; executing: that keeps the test portable (Redshift compiles it fine and only its engine rejects a constant
+;; PARTITION BY at execution time) while still catching a recurrence of the compile-time crash.
+(deftest ^:parallel offset-with-constant-expression-breakout-test
+ (testing "a constant custom column used as a breakout combined with offset(sum) compiles without crashing (#47870)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ total (lib.metadata/field mp (mt/id :orders :total))
+ base (-> (lib/query mp orders)
+ (lib/expression "two" (lib/+ 1 1)))
+ two (m/find-first (comp #{"two"} :name) (lib/breakoutable-columns base))
+ _ (assert (some? two))]
+ (testing "constant CC as the first breakout"
+ (is (string? (:query (qp.compile/compile
+ (-> base
+ (lib/breakout two)
+ (lib/breakout (lib/with-temporal-bucket created-at :year))
+ (lib/aggregate (lib/sum total))
+ (lib/aggregate (lib/offset (lib/sum total) -1))))))))
+ (testing "constant CC not in the first breakout position"
+ (is (string? (:query (qp.compile/compile
+ (-> base
+ (lib/breakout (lib/with-temporal-bucket created-at :year))
+ (lib/breakout two)
+ (lib/aggregate (lib/sum total))
+ (lib/aggregate (lib/offset (lib/sum total) -1))))))))))))
+
+(deftest ^:parallel offset-three-breakouts-test
+ (testing "offset(sum) over three breakouts compiles and executes"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ total (lib.metadata/field mp (mt/id :orders :total))
+ query (-> (lib/query mp orders)
+ (lib/breakout (lib/with-temporal-bucket created-at :year))
+ (lib/breakout (lib.metadata/field mp (mt/id :orders :product_id)))
+ (lib/breakout (lib.metadata/field mp (mt/id :orders :user_id)))
+ (lib/aggregate (lib/sum total))
+ (lib/aggregate (lib/offset (lib/sum total) -1)))]
+ (is (seq (mt/rows (qp/process-query query))))))))
+
+(deftest ^:parallel offset-with-segment-filter-test
+ (testing "a saved segment filter coexists with offset window compilation"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ total (lib.metadata/field mp (mt/id :orders :total))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ mp (lib.tu/mock-metadata-provider
+ mp
+ {:segments [{:id 1
+ :name "Small orders"
+ :table-id (mt/id :orders)
+ :definition (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/filter (lib/< total 100)))}]})
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/filter (lib.metadata/segment mp 1))
+ (lib/breakout (lib/with-temporal-bucket created-at :year))
+ (lib/aggregate (lib/sum total))
+ (lib/aggregate (lib/offset (lib/sum total) -1)))]
+ (is (seq (mt/rows (qp/process-query query))))))))
+
+(deftest ^:parallel offset-follows-desc-order-by-breakout-test
+ (testing "with a desc order-by on the breakout, the offset window follows the display order: the first (latest) row has a nil offset and each following row's offset is the previous displayed row's sum"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ orders (lib.metadata/table mp (mt/id :orders))
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ total (lib.metadata/field mp (mt/id :orders :total))
+ query (-> (lib/query mp orders)
+ (lib/breakout (lib/with-temporal-bucket created-at :year))
+ (lib/aggregate (lib/sum total))
+ (lib/aggregate (lib/offset (lib/sum total) -1))
+ (lib/order-by (lib/with-temporal-bucket created-at :year) :desc)
+ (assoc-in [:middleware :format-rows?] false))
+ rows (mt/formatted-rows [->local-date 2.0 2.0] (qp/process-query query))
+ years (map first rows)
+ sums (map second rows)
+ offsets (map #(nth % 2) rows)]
+ (testing "breakout years are displayed in descending order"
+ (is (= (reverse (sort years)) years)))
+ (testing "the first (latest) row has no previous row in the window -> nil offset"
+ (is (nil? (first offsets))))
+ (testing "each following row's offset is the sum of the row displayed above it"
+ (is (= (butlast sums) (rest offsets))))))))
+
+(deftest ^:parallel offset-without-breakout-compiles-test
+ (testing "an offset aggregation with no breakout still compiles to native SQL without erroring (#47819)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :window-functions/offset)
+ (let [mp (mt/metadata-provider)
+ total (lib.metadata/field mp (mt/id :orders :total))
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/offset (lib/sum total) -1)))]
+ (is (string? (:query (qp.compile/compile query))))))))
diff --git a/test/metabase/query_processor/parameters/dates_test.clj b/test/metabase/query_processor/parameters/dates_test.clj
index 1040c31b2a3..e0b0d1f8fdd 100644
--- a/test/metabase/query_processor/parameters/dates_test.clj
+++ b/test/metabase/query_processor/parameters/dates_test.clj
@@ -6,6 +6,7 @@
[clojure.test.check.properties :as prop]
[java-time.api :as t]
[metabase.driver :as driver]
+ [metabase.lib.core :as lib]
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]
[metabase.query-processor.parameters.dates :as params.dates]
@@ -44,6 +45,16 @@
"2019-04-01"
[:field {:lib/uuid "00000000-0000-0000-0000-000000000000", :base-type :type/DateTime} "field"])))))
+(deftest ^:parallel date-string->filter-test-3b
+ (testing "single hour-granular value"
+ (is (=? [:=
+ {}
+ [:field {:temporal-unit :minute} (meta/id :orders :created-at)]
+ "2025-04-01T09:00:00"]
+ (params.dates/date-string->filter
+ "2025-04-01T09"
+ (lib/ref (meta/field-metadata :orders :created-at)))))))
+
(deftest ^:parallel date-string->filter-test-4
(testing "single minute"
(is (=? [:=
diff --git a/test/metabase/query_processor/parameters/temporal_units_test.clj b/test/metabase/query_processor/parameters/temporal_units_test.clj
index 6e3d069aec3..06d2936bb23 100644
--- a/test/metabase/query_processor/parameters/temporal_units_test.clj
+++ b/test/metabase/query_processor/parameters/temporal_units_test.clj
@@ -5,6 +5,8 @@
[clojure.test :refer :all]
[java-time.api :as t]
[metabase.driver :as driver]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.query-processor.test :as qp]
[metabase.test :as mt]))
@@ -128,6 +130,30 @@
(subvec 0 2)))
(str "Unexpected results for aliased grouping " grouping)))))))
+(deftest ^:parallel temporal-unit-in-optional-clause-test
+ ;; Unlike the sibling tests, this one relies on a hand-written H2 query (LIMIT + an optional `[[…]]` clause) that the
+ ;; portable `mt/arbitrary-select-query` helper can't express, so it is gated to :h2 rather than the full driver set.
+ (mt/test-driver :h2
+ (testing "a :temporal-unit template tag inside an optional [[…]] clause"
+ (let [mp (mt/metadata-provider)
+ make (fn [default]
+ (let [q0 (lib/native-query mp "SELECT ID [[, {{unit}} AS unit]] FROM PEOPLE ORDER BY ID LIMIT 2")
+ existing (get (lib/template-tags q0) "unit")]
+ (lib/with-template-tags
+ q0 {"unit" (merge existing
+ {:display-name "Unit"
+ :type :temporal-unit
+ :dimension (lib/ref (lib.metadata/field mp (mt/id :people :created_at)))
+ :default default})})))]
+ (testing "the clause is included and bucketed when a default value is present"
+ (let [rows (mt/rows (qp/process-query (make "year")))]
+ (is (= 2 (count rows)))
+ (is (= 2 (count (first rows))))))
+ (testing "the clause is dropped entirely when the tag is unset"
+ (let [rows (mt/rows (qp/process-query (make nil)))]
+ (is (= 2 (count rows)))
+ (is (= 1 (count (first rows))))))))))
+
(deftest ^:parallel bad-field-reference-throws-errors-test
(mt/test-drivers (mt/normal-drivers-with-feature :native-parameters :native-temporal-units ::temporal-units-test)
(testing "temporal unit parameters"
diff --git a/test/metabase/query_processor/parameters_test.clj b/test/metabase/query_processor/parameters_test.clj
index 0d3b7b41739..b480e979176 100644
--- a/test/metabase/query_processor/parameters_test.clj
+++ b/test/metabase/query_processor/parameters_test.clj
@@ -9,6 +9,7 @@
[java-time.api :as t]
[medley.core :as m]
[metabase.driver :as driver]
+ [metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.native :as lib-native]
@@ -799,3 +800,74 @@
mp
(query-result-ids (lib/query mp (lib.metadata/table mp (mt/id :products))))
{:table-id (mt/id :products)})))))
+
+(deftest ^:parallel number-parameter-on-expression-column-test
+ (testing "a :number/= parameter targeting an [:expression] custom column filters the card (#18747)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/expression "Quantity_2" (lib.metadata/field mp (mt/id :orders :quantity))))
+ query (assoc query :parameters [{:type :number/=
+ :target [:dimension (lib.convert/->legacy-MBQL
+ (lib/expression-ref query "Quantity_2"))]
+ :value [14]}])]
+ (is (= 1
+ (count (mt/rows (qp/process-query query))))))))))
+
+(deftest ^:parallel field-filter-operators-execution-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :native-parameters ::field-filter-param-test-2)
+ ;; expected counts are constants derived from the immutable `test-data` `venues` table (100 rows). They match the
+ ;; result of running the equivalent MBQL filter: `<= 3`, `!= 1`, `between 2 3`, `ends-with "s"`,
+ ;; `does-not-contain "ouse"`. The `does-not-contain` probe is collation-neutral: "ouse" matches the same 3 venue
+ ;; names whether the driver's LIKE is case-sensitive or not, so 97 holds everywhere.
+ (mt/dataset test-data
+ (doseq [[field value-type value expected]
+ [[:price :number/<= [3] 94]
+ [:price :number/!= [1] 78]
+ [:price :number/between [2 3] 72]
+ [:name :string/ends-with ["s"] 8]
+ [:name :string/does-not-contain ["ouse"] 97]]]
+ (testing (format "%s field filter with value %s" value-type (pr-str value))
+ (field-filter-param-test-is-count-= expected :venues field value-type value))))))
+
+(deftest ^:parallel field-filter-string-contains-execution-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :native-parameters ::field-filter-param-test-2)
+ (mt/dataset test-data
+ (testing "'contains' field filter resolves to the case-insensitive default count (#16181)"
+ ;; 147 = number of `test-data` `products` whose `category` contains "i" (Doohickey/Gizmo/Widget, not Gadget).
+ (field-filter-param-test-is-count-= 147 :products :category :string/contains ["i"])))))
+
+(deftest ^:parallel filter-on-joined-source-card-expression-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :left-join :expressions)
+ (testing "a string param mapped to [:field \"source state\" {:join-alias …}] pointing at a source-card expression resolves and filters (#32483)"
+ (mt/dataset test-data
+ (let [mp0 (mt/metadata-provider)
+ inner (-> (lib/query mp0 (lib.metadata/table mp0 (mt/id :people)))
+ (lib/expression "source state"
+ (lib/concat (lib.metadata/field mp0 (mt/id :people :source))
+ " "
+ (lib.metadata/field mp0 (mt/id :people :state)))))
+ mp (lib.tu/metadata-provider-with-cards-for-queries mp0 [inner])
+ card (lib.metadata/card mp 1)
+ base (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ query (-> base
+ (lib/join (-> (lib/join-clause card (lib/suggested-join-conditions base card))
+ (lib/with-join-alias "People - User")
+ (lib/with-join-fields :all)))
+ (lib/limit 10))
+ ;; the joined card exposes "source state" (an expression column, so no field id) under the join alias;
+ ;; match it case-insensitively so lowercase-folding drivers still find it
+ ss-col (m/find-first #(and (= (u/lower-case-en (:name %)) "source state")
+ (= (:lib/join-alias %) "People - User"))
+ (lib/visible-columns query))
+ ss-idx (first (keep-indexed (fn [i col]
+ (when (= (u/lower-case-en (:name col)) "source state") i))
+ (lib/returned-columns query)))
+ query (assoc query :parameters [{:type :string/=
+ :value ["Facebook MN"]
+ :target [:dimension (lib.convert/->legacy-MBQL (lib/ref ss-col))]}])
+ rows (mt/rows (qp/process-query query))]
+ (is (some? ss-idx))
+ (is (seq rows))
+ (is (every? #(= "Facebook MN" (nth % ss-idx)) rows)))))))
diff --git a/test/metabase/query_processor/pivot_test.clj b/test/metabase/query_processor/pivot_test.clj
index 770fb80e3fe..d4befd0c2ca 100644
--- a/test/metabase/query_processor/pivot_test.clj
+++ b/test/metabase/query_processor/pivot_test.clj
@@ -512,6 +512,31 @@
:aggregation [[:count]]
:breakout [$user_id->people.source [:expression "Product Rating + 1"]]})))))))
+(deftest ^:parallel measure-in-pivot-table-test
+ (testing "a :measure clause used inside a pivot query executes like the equivalent inline aggregation"
+ (mt/test-drivers (qp.pivot.test-util/applicable-drivers)
+ (let [mp (mt/metadata-provider)
+ total (lib.metadata/field mp (mt/id :orders :total))
+ quantity (lib.metadata/field mp (mt/id :orders :quantity))
+ definition (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/sum total)))
+ mp (lib.tu/mock-metadata-provider
+ mp
+ {:measures [{:id 1
+ :name "Sum of Total"
+ :table-id (mt/id :orders)
+ :definition definition}]})
+ pivot (fn [agg]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate agg)
+ (lib/breakout quantity)))
+ measure-pivot (pivot (lib.metadata/measure mp 1))
+ inline-pivot (pivot (lib/sum total))]
+ ;; the spliced measure must produce the same pivot output (leaf + grand-total rows) as
+ ;; the equivalent inline sum aggregation
+ (is (= (mt/rows (qp.pivot/run-pivot-query inline-pivot))
+ (mt/rows (qp.pivot/run-pivot-query measure-pivot))))))))
+
(deftest pivot-query-should-work-without-data-permissions-test
(testing "Pivot queries should work if the current user only has permissions to view the Card -- no data perms (#14989)"
(mt/dataset test-data
diff --git a/test/metabase/query_processor/remapping_test.clj b/test/metabase/query_processor/remapping_test.clj
index 6d7288454ba..0478479e36b 100644
--- a/test/metabase/query_processor/remapping_test.clj
+++ b/test/metabase/query_processor/remapping_test.clj
@@ -573,6 +573,42 @@
;; make sure the title is returned
(is (string? (last (first (mt/rows (qp/process-query query)))))))))
+(deftest ^:parallel fk-remap-to-temporal-target-test
+ (testing "an FK remapped to a temporal target column projects the datetime value, not the raw id (#7108)"
+ (mt/test-drivers (mt/normal-drivers-with-feature :left-join)
+ (mt/dataset test-data
+ (let [mp (-> (mt/metadata-provider)
+ (lib.tu/remap-metadata-provider (mt/id :orders :product_id)
+ (mt/id :products :created_at)))
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/limit 1))
+ result (qp/process-query query)
+ cols (mt/cols result)
+ remap-col (first (filter #(= (mt/id :products :created_at) (:id %)) cols))]
+ (testing "the remapped column is the temporal target"
+ (is (some? remap-col))
+ (is (isa? (:base_type remap-col) :type/Temporal))
+ (is (= (mt/id :orders :product_id) (:fk_field_id remap-col))))
+ (testing "the projected value is a datetime, not the raw product id"
+ (let [idx (first (keep-indexed (fn [i col]
+ (when (= (mt/id :products :created_at) (:id col)) i))
+ cols))
+ v (nth (first (mt/rows result)) idx)]
+ (is (not (integer? v))))))))))
+
+(deftest ^:parallel internal-remap-on-model-test
+ (testing "internal (FieldValues) remap values still surface through a model card query (#23449)"
+ (let [base (mt/metadata-provider)
+ mp (-> base
+ (lib.tu/remap-metadata-provider (mt/id :reviews :rating) {1 "Awful" 5 "Perfecto"})
+ (lib.tu/metadata-provider-with-cards-for-queries
+ [(lib/query base (lib.metadata/table base (mt/id :reviews)))])
+ (lib.tu/merged-mock-metadata-provider {:cards [{:id 1, :type :model}]}))]
+ (qp.store/with-metadata-provider mp
+ (let [result (qp/process-query (lib/query mp (lib.metadata/card mp 1)))
+ all-vals (into #{} (mapcat identity) (mt/rows result))]
+ (is (contains? all-vals "Perfecto")))))))
+
(deftest ^:parallel fk-excluded-should-not-break-test
(doseq [field [:id :title]
vis [:sensitive :retired]]
diff --git a/test/metabase/query_processor/string_extracts_test.clj b/test/metabase/query_processor/string_extracts_test.clj
index ef16f47757f..cc8c82f2a0a 100644
--- a/test/metabase/query_processor/string_extracts_test.clj
+++ b/test/metabase/query_processor/string_extracts_test.clj
@@ -172,6 +172,59 @@
[2 "[email protected]" "yahoo" "yahoo.com"]]
(mt/formatted-rows [int str str str] (qp/process-query query))))))))
+(deftest ^:parallel filter-on-string-expression-result-test
+ (testing "#13751 filter `=` on the result of a regex-match-first expression"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ people (lib.metadata/table mp (mt/id :people))
+ state (lib.metadata/field mp (mt/id :people :state))
+ co-count (->> (-> (lib/query mp people)
+ (lib/filter (lib/= state "CO"))
+ (lib/aggregate (lib/count)))
+ qp/process-query mt/rows ffirst long)
+ expr-q (-> (lib/query mp people)
+ (lib/expression "C" (lib/regex-match-first state "^C[A-Z]")))
+ expr-q (-> expr-q
+ (lib/filter (lib/= (lib/expression-ref expr-q "C") "CO"))
+ (lib/aggregate (lib/count)))]
+ (is (pos? co-count))
+ (is (= co-count
+ (->> expr-q qp/process-query mt/rows ffirst long)))))))
+ (testing "#14843 filter `!=` on the result of a length expression"
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ people (lib.metadata/table mp (mt/id :people))
+ city (lib.metadata/field mp (mt/id :people :city))
+ query (as-> (lib/query mp people) q
+ (lib/expression q "L" (lib/length city))
+ (lib/filter q (lib/!= (lib/expression-ref q "L") 3))
+ (lib/with-fields q [city])
+ (lib/limit q 200))
+ rows (mt/rows (qp/process-query query))]
+ (is (seq rows))
+ (is (not-any? #(= 3 (count (first %))) rows)))))))
+
+(deftest ^:parallel string-function-escape-literals-test
+ (mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex)
+ (mt/dataset test-data
+ (let [mp (mt/metadata-provider)
+ venues (lib.metadata/table mp (mt/id :venues))
+ venues-id (lib.metadata/field mp (mt/id :venues :id))
+ venues-name (lib.metadata/field mp (mt/id :venues :name))
+ extract (fn [expr]
+ (let [q (as-> (lib/query mp venues) q
+ (lib/expression q "test" expr)
+ (lib/with-fields q [(lib/expression-ref q "test")])
+ (lib/order-by q venues-id :asc)
+ (lib/limit q 1))]
+ (ffirst (mt/rows (qp/process-query q)))))]
+ (testing "#53527 a double-quote replacement literal strips the quote"
+ (is (= "ab" (extract (lib/replace "a\"b" "\"" "")))))
+ (testing "#56596 a `\\s` whitespace class keeps its backslash and captures a leading space"
+ (is (= " Medicine" (extract (lib/regex-match-first venues-name "\\s.*")))))))))
+
(deftest ^:parallel url-extractions-test
(testing "`:domain`, `:subdomain`, `:host`, and `:path` extractions from URLs should work correctly"
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex/lookaheads-and-lookbehinds)
diff --git a/test/metabase/revisions/api_test.clj b/test/metabase/revisions/api_test.clj
index af28c9b4443..a68fd71debc 100644
--- a/test/metabase/revisions/api_test.clj
+++ b/test/metabase/revisions/api_test.clj
@@ -3,6 +3,8 @@
(:require
[clojure.test :refer :all]
[metabase.config.core :as config]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.revisions.models.revision :as revision]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -835,3 +837,115 @@
:database database-id}}}
:description "created this."}]
(mt/user-http-request :crowberto :get 200 (format "revision/segment/%d" id)))))))))
+
+(deftest dashboard-double-revert-test
+ (testing "Reverting past an add/delete-card boundary then reverting forward again both succeed (#15237)"
+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}
+ :model/Card {card-id :id} {}]
+ (create-dashboard-revision! dashboard-id true :rasta)
+ (let [dashcard (first (t2/insert-returning-instances! :model/DashboardCard
+ :dashboard_id dashboard-id
+ :card_id card-id
+ :size_x 4 :size_y 4 :row 0 :col 0))]
+ (create-dashboard-revision! dashboard-id false :rasta)
+ (t2/delete! (t2/table-name :model/DashboardCard) :id (:id dashcard)))
+ (create-dashboard-revision! dashboard-id false :rasta)
+ (let [revisions (revision/revisions+details :model/Dashboard dashboard-id)
+ created-rev-id (:id (some #(when (= "created this." (:description %)) %) revisions))
+ added-card-rev-id (:id (some #(when (= "added a card." (:description %)) %) revisions))
+ revert-back (mt/user-http-request :rasta :post 200 "revision/revert"
+ {:entity :dashboard :id dashboard-id :revision_id created-rev-id})]
+ (is (not (contains? revert-back :cause)))
+ (is (zero? (t2/count :model/DashboardCard :dashboard_id dashboard-id)))
+ (testing "revert forward again past that boundary"
+ (let [revert-forward (mt/user-http-request :rasta :post 200 "revision/revert"
+ {:entity :dashboard :id dashboard-id :revision_id added-card-rev-id})]
+ (is (not (contains? revert-forward :cause)))
+ (is (= 1 (t2/count :model/DashboardCard :dashboard_id dashboard-id)))))))))
+
+(deftest revert-card-test
+ (testing "Reverting a Card through the API works"
+ (mt/with-temp [:model/Card {card-id :id} {:name "revert test"}]
+ (create-card-revision! card-id true :crowberto)
+ (t2/update! :model/Card card-id {:description "hi"})
+ (create-card-revision! card-id false :crowberto)
+ (let [[_ {prev-id :id}] (revision/revisions :model/Card card-id)]
+ (is (=? {:description "reverted to an earlier version."}
+ (mt/user-http-request :crowberto :post 200 "revision/revert"
+ {:entity :card :id card-id :revision_id prev-id})))
+ (is (nil? (t2/select-one-fn :description :model/Card :id card-id)))))))
+
+(deftest permission-check-on-card-revert-test
+ (testing "Are permissions enforced by the revert action in the revision api for Cards? (#13229)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection collection {}
+ :model/Card card {:collection_id (u/the-id collection) :name "Q1"}]
+ (create-card-revision! (:id card) true :crowberto)
+ (mt/user-http-request :crowberto :put 200 (str "card/" (:id card)) {:name "Q1 renamed"})
+ (let [[_ {prev-rev-id :id}] (revision/revisions :model/Card (:id card))]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post "revision/revert"
+ {:entity :card :id (:id card) :revision_id prev-rev-id}))))))))
+
+(deftest revert-model-restores-metadata-and-viz-settings-test
+ (testing "Reverting a model restores result_metadata and visualization_settings together (#45926)"
+ (mt/with-temp [:model/Card {card-id :id} (assoc (mt/card-with-metadata
+ {:dataset_query (let [mp (mt/metadata-provider)]
+ (lib/query mp (lib.metadata/table mp (mt/id :venues))))})
+ :type :model
+ :visualization_settings {})]
+ (let [original-metadata (t2/select-one-fn :result_metadata :model/Card :id card-id)
+ original-names (map :display_name original-metadata)]
+ (create-card-revision! card-id true :crowberto)
+ (t2/update! :model/Card card-id
+ {:result_metadata (mapv #(assoc % :display_name "EDITED") original-metadata)
+ :visualization_settings {:some_setting true}})
+ (create-card-revision! card-id false :crowberto)
+ ;; order by :id (monotonic), not :timestamp -- on Postgres `now()` is frozen for the whole test
+ ;; transaction, so consecutive revisions here can tie on :timestamp and pick the wrong revision.
+ (let [earlier-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:id :asc]]})]
+ (mt/user-http-request :crowberto :post 200 "revision/revert"
+ {:entity :card :id card-id :revision_id earlier-id})
+ (is (=? {:result_metadata (mapv (fn [name] {:display_name name}) original-names)
+ :visualization_settings {}}
+ (t2/select-one :model/Card :id card-id))))))))
+
+(deftest revert-restores-card-type-test
+ (testing "Reverting a Card revision restores a previous :type (e.g. model <-> question)"
+ (mt/with-temp [:model/Card {card-id :id} {:type :question}]
+ (create-card-revision! card-id true :crowberto)
+ (t2/update! :model/Card :id card-id {:type :model})
+ (create-card-revision! card-id false :crowberto)
+ ;; order by :id (monotonic), not :timestamp -- see comment above in
+ ;; revert-model-restores-metadata-and-viz-settings-test.
+ (let [earlier-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:id :asc]]})]
+ (mt/user-http-request :crowberto :post 200 "revision/revert"
+ {:entity :card :id card-id :revision_id earlier-id})
+ (is (= :question (t2/select-one-fn :type :model/Card :id card-id)))))))
+
+(deftest revert-card-preserves-dashcard-parameter-mappings-test
+ (testing "POST /revision/revert on a card keeps dashcard parameter_mappings referencing its template tags (#35954)"
+ (let [mp (mt/metadata-provider)
+ reviews-rating (lib.metadata/field mp (mt/id :reviews :rating))]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (lib/query mp (lib.metadata/table mp (mt/id :reviews)))}
+ :model/Dashboard {dash-id :id} {:parameters [{:id "num" :name "Number" :slug "number" :type :number/=}]}
+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id
+ :card_id card-id
+ :parameter_mappings [{:parameter_id "num"
+ :card_id card-id
+ :target [:dimension [:template-tag "RATING"]]}]}]
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id)
+ {:dataset_query
+ (lib/with-template-tags
+ (lib/native-query mp "SELECT * FROM REVIEWS WHERE {{RATING}}")
+ {"RATING" {:name "RATING"
+ :display-name "R"
+ :id "x"
+ :type :dimension
+ :widget-type :number/=
+ :dimension (lib/ref reviews-rating)}})})
+ (let [first-rev-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id {:order-by [[:id :asc]]})]
+ (mt/user-http-request :crowberto :post 200 "revision/revert"
+ {:entity :card :id card-id :revision_id first-rev-id})
+ (is (=? [{:target [:dimension [:template-tag "RATING"]]}]
+ (t2/select-one-fn :parameter_mappings :model/DashboardCard :id dc-id))))))))
diff --git a/test/metabase/revisions/impl/dashboard_test.clj b/test/metabase/revisions/impl/dashboard_test.clj
index b855d9685ea..e72c4afa37c 100644
--- a/test/metabase/revisions/impl/dashboard_test.clj
+++ b/test/metabase/revisions/impl/dashboard_test.clj
@@ -157,6 +157,15 @@
{:cards [{:id 1} {:id 3}]}
"modified the cards.")))
+(deftest ^:parallel diff-dashboards-str-add-card-with-autoplace-test
+ (testing "adding a card should still be reported as \"added a card\" even when auto-placement also
+ repositions an existing card (metabase#6884)"
+ (is (= "added a card."
+ (u/build-sentence
+ (revision/diff-strings :model/Dashboard
+ {:cards [{:id 1 :row 0 :col 0}]}
+ {:cards [{:id 1 :row 4 :col 0} {:id 2 :row 0 :col 0}]}))))))
+
(deftest diff-dashboards-str-update-collection-test
(testing "update collection ---"
(is (= "moved this Dashboard to Our analytics."
diff --git a/test/metabase/revisions/impl/measure_test.clj b/test/metabase/revisions/impl/measure_test.clj
new file mode 100644
index 00000000000..04bb6790068
--- /dev/null
+++ b/test/metabase/revisions/impl/measure_test.clj
@@ -0,0 +1,43 @@
+(ns metabase.revisions.impl.measure-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.revisions.init]
+ [metabase.revisions.models.revision :as revision]
+ [metabase.test :as mt]
+ [metabase.util :as u]))
+
+(comment metabase.revisions.init/keep-me)
+
+(defn- measure-definition [agg-fn field-key]
+ (let [mp (mt/metadata-provider)
+ table (lib.metadata/table mp (mt/id :venues))
+ field (lib.metadata/field mp (mt/id :venues field-key))]
+ (lib/aggregate (lib/query mp table) (agg-fn field))))
+
+(deftest ^:parallel diff-measures-str-rename-test
+ (testing "renaming a measure produces a human-readable diff sentence"
+ (is (= "renamed this Measure from \"Original\" to \"Updated\"."
+ (u/build-sentence
+ (revision/diff-strings :model/Measure
+ {:name "Original"}
+ {:name "Updated"}))))))
+
+(deftest ^:parallel diff-measures-str-description-test
+ (testing "adding a description produces a human-readable diff sentence"
+ (is (= "added a description."
+ (u/build-sentence
+ (revision/diff-strings :model/Measure
+ {:name "Original" :description nil}
+ {:name "Original" :description "What it measures"}))))))
+
+(deftest diff-measures-str-definition-only-test
+ (testing "a definition-only change (e.g. changing the aggregation) currently produces no human-readable
+ diff sentence -- diff-strings has no :definition case, unlike diff-map which does track it structurally"
+ (let [before {:name "Orders Total" :definition (measure-definition lib/count :id)}
+ after (assoc before :definition (measure-definition lib/sum :price))]
+ (is (some? (:definition (revision/diff-map :model/Measure before after)))
+ "diff-map does track the definition change...")
+ (is (nil? (u/build-sentence (revision/diff-strings :model/Measure before after)))
+ "...but diff-strings has no wording for it, so no sentence is produced"))))
diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.clj
index 42b18aa4554..1c07d28b79e 100644
--- a/test/metabase/search/api_test.clj
+++ b/test/metabase/search/api_test.clj
@@ -2073,6 +2073,16 @@
(is (not (contains? result-ids table-id))
"Published table should NOT be included in collection search in OSS")))))))
+(deftest collection-filter-respects-permissions-test
+ (testing "GET /api/search?collection=<id> excludes results the user cannot read, and includes them once granted (metabase#entity-picker)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Card {card-id :id} {:collection_id coll-id :name "scoped one"}]
+ (is (empty? (:data (mt/user-http-request :rasta :get 200 "search" :collection coll-id))))
+ (perms/grant-collection-read-permissions! (perms/all-users-group) coll-id)
+ (is (= #{card-id coll-id}
+ (set (map :id (:data (mt/user-http-request :rasta :get 200 "search" :collection coll-id))))))))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Measure Search Tests (Phase 4) |
;;; +----------------------------------------------------------------------------------------------------------------+
diff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.clj
index c92101c7958..37dd128db84 100644
--- a/test/metabase/session/api_test.clj
+++ b/test/metabase/session/api_test.clj
@@ -132,6 +132,14 @@
(mt/client :post 401 "session" (-> (mt/user->credentials :rasta)
(assoc :password "something else")))))))
+(deftest login-unknown-email-does-not-leak-account-existence-test
+ (testing "POST /api/session - an unknown email returns the same 401 error as a wrong password (anti-enumeration)"
+ (let [unknown-email-resp (mt/client :post 401 "session" {:username "[email protected]"
+ :password "whatever-UP12!!"})
+ wrong-password-resp (mt/client :post 401 "session" (-> (mt/user->credentials :rasta)
+ (assoc :password "whatever-UP12!!")))]
+ (is (= wrong-password-resp unknown-email-resp)))))
+
(deftest login-throttling-test
(testing (str "Test that people get blocked from attempting to login if they try too many times (Check that"
" throttling works at the API level -- more tests in the throttle library itself:"
diff --git a/test/metabase/settings_rest/api_test.clj b/test/metabase/settings_rest/api_test.clj
index 2012bb47007..a7abba63f45 100644
--- a/test/metabase/settings_rest/api_test.clj
+++ b/test/metabase/settings_rest/api_test.clj
@@ -395,3 +395,11 @@
(test-deprecated-setting! "hello")
(is (re-find #"Setting test-deprecated-setting is deprecated as of Metabase 0.51.0"
(str/join " " (map :message (warnings)))))))
+
+(deftest site-name-description-reflects-application-name-test
+ (testing "GET /api/setting returns the site-name description interpolated with a whitelabel application-name (#17043)"
+ (mt/with-premium-features #{:whitelabel}
+ (mt/with-temporary-setting-values [application-name "New Test Co"]
+ (let [site-name-setting (some #(when (= "site-name" (:key %)) %)
+ (mt/user-http-request :crowberto :get 200 "setting"))]
+ (is (str/includes? (:description site-name-setting) "New Test Co")))))))
diff --git a/test/metabase/sso/api/google_test.clj b/test/metabase/sso/api/google_test.clj
index 9aab0fe8067..8b39cb929f6 100644
--- a/test/metabase/sso/api/google_test.clj
+++ b/test/metabase/sso/api/google_test.clj
@@ -20,3 +20,21 @@
(sso.settings/google-auth-client-id)))
(is (= "foo.com"
(sso.settings/google-auth-auto-create-accounts-domain)))))))
+
+(deftest google-settings-reset-test
+ (testing "PUT /api/google/settings can clear the settings, disabling Google Sign-In"
+ (mt/with-temporary-setting-values [google-auth-client-id nil
+ google-auth-auto-create-accounts-domain nil
+ google-auth-enabled nil]
+ (mt/user-http-request :crowberto :put 200 "google/settings"
+ {:google-auth-client-id test-client-id
+ :google-auth-enabled true
+ :google-auth-auto-create-accounts-domain "foo.com"})
+ (is (sso.settings/google-auth-enabled))
+ (mt/user-http-request :crowberto :put 200 "google/settings"
+ {:google-auth-client-id nil
+ :google-auth-enabled false
+ :google-auth-auto-create-accounts-domain nil})
+ (is (nil? (sso.settings/google-auth-client-id)))
+ (is (nil? (sso.settings/google-auth-auto-create-accounts-domain)))
+ (is (not (sso.settings/google-auth-enabled))))))
diff --git a/test/metabase/sso/api/ldap_test.clj b/test/metabase/sso/api/ldap_test.clj
index aa4b7d3784c..74983caef80 100644
--- a/test/metabase/sso/api/ldap_test.clj
+++ b/test/metabase/sso/api/ldap_test.clj
@@ -69,3 +69,13 @@
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 "ldap/settings"
(assoc (ldap-test-details) :ldap-port "" :ldap-enabled false))))))))
+
+(deftest ldap-settings-reset-test
+ (testing "PUT /api/ldap/settings clearing the settings disables LDAP and clears the host"
+ (ldap.test/with-ldap-server!
+ (mt/user-http-request :crowberto :put 200 "ldap/settings" (ldap-test-details))
+ (is (sso.settings/ldap-enabled))
+ (mt/with-dynamic-fn-redefs [ldap/test-ldap-connection (constantly {:status :SUCCESS})]
+ (mt/user-http-request :crowberto :put 200 "ldap/settings" {:ldap-host nil :ldap-enabled false}))
+ (is (not (sso.settings/ldap-enabled)))
+ (is (nil? (sso.settings/ldap-host))))))
diff --git a/test/metabase/task_history/task/task_run_heartbeat_test.clj b/test/metabase/task_history/task/task_run_heartbeat_test.clj
index 29426de03bd..5c64684e069 100644
--- a/test/metabase/task_history/task/task_run_heartbeat_test.clj
+++ b/test/metabase/task_history/task/task_run_heartbeat_test.clj
@@ -32,7 +32,8 @@
(deftest send-heartbeat-ignores-other-processes-test
(mt/with-model-cleanup [:model/TaskRun]
(testing "send-heartbeat! does NOT update runs belonging to other processes"
- (let [old-time (t/minus (t/offset-date-time) (t/hours 3))
+ ;; millisecond-clean so app-DB storage rounding can't shift it (truncation below can't undo rounding-up)
+ (let [old-time (t/truncate-to (t/minus (t/offset-date-time) (t/hours 3)) :millis)
other-uuid "other-process-uuid"]
(mt/with-temp [:model/TaskRun {run-id :id} {:run_type :sync
:entity_type :database
diff --git a/test/metabase/timeline/api/timeline_test.clj b/test/metabase/timeline/api/timeline_test.clj
index b9dc8c6511d..5517acc11a4 100644
--- a/test/metabase/timeline/api/timeline_test.clj
+++ b/test/metabase/timeline/api/timeline_test.clj
@@ -66,6 +66,18 @@
(is (= '()
(->> (collection-timelines-request coll-c true) first :events)))))))
+(deftest collection-archived-timelines-test
+ (testing "GET /api/timeline/collection/:id?archived=true returns only archived timelines"
+ (mt/with-temp [:model/Collection coll-b {:name "Collection B"}
+ :model/Timeline _tl-b {:name "Timeline B"
+ :collection_id (u/the-id coll-b)}
+ :model/Timeline _tl-b-old {:name "Timeline B-old"
+ :collection_id (u/the-id coll-b)
+ :archived true}]
+ (is (= #{"Timeline B-old"}
+ (timeline-names (mt/user-http-request :rasta :get 200
+ (str "timeline/collection/" (u/the-id coll-b)) :archived true)))))))
+
(deftest collection-timelines-permissions-test
(testing "GET /api/timeline/collection/:id"
(mt/with-temp [:model/Collection coll-a {:name "Collection A"}
diff --git a/test/metabase/transforms/test_util.clj b/test/metabase/transforms/test_util.clj
index d33a5b2629b..10b7bddd8ee 100644
--- a/test/metabase/transforms/test_util.clj
+++ b/test/metabase/transforms/test_util.clj
@@ -96,12 +96,24 @@
~@body)))
(defn table-rows
+ "Fetch all rows of `table-name` in the current test database.
+
+ Dataset tables (e.g. `transforms_products`) are resolved by their logical name via `mt/id`, which handles
+ drivers like Redshift that load datasets under prefixed physical names (`transforms_test_transforms_products`).
+ Transform TARGET tables are created with their exact requested name, so they are looked up by bare name scoped
+ to the current test database and, when the transforms dataset is loaded, to its schema — avoiding an unrelated
+ `Table` row with the same name under a different database/schema."
[table-name]
- (->>
- (mt/rows (mt/process-query {:database (mt/id)
- :query {:source-table (t2/select-one-pk :model/Table :name table-name)}
- :type :query}))
- (map (fn [x] (if (= :mongo driver/*driver*) (rest x) x)))))
+ (let [pk (or (try (mt/id (keyword table-name)) (catch Exception _ nil))
+ (if-let [schema (when-let [products-id (try (mt/id :transforms_products) (catch Exception _ nil))]
+ (t2/select-one-fn :schema :model/Table products-id))]
+ (t2/select-one-pk :model/Table :db_id (mt/id) :schema schema :name table-name)
+ (t2/select-one-pk :model/Table :db_id (mt/id) :name table-name)))]
+ (->>
+ (mt/rows (mt/process-query {:database (mt/id)
+ :query {:source-table pk}
+ :type :query}))
+ (map (fn [x] (if (= :mongo driver/*driver*) (rest x) x))))))
(defn parse-timestamp
"Parse a local datetime and convert it to a ZonedDateTime in the default timezone."
@@ -121,17 +133,25 @@
(-> timestamp-string parse-instant str))
(defn wait-for-table
- "Wait for a table to appear in metadata, with timeout."
+ "Wait for a table to become queryable in the current test database, with timeout.
+
+ Sync creates the target's `Table` row first (already active) and inserts its `Field` rows in a later
+ step, so \"table exists but has no fields\" is a normal mid-sync state; a query against the table in
+ that state fails in `add-implicit-clauses` with \"Table has no Fields associated with it\". Wait for
+ the same condition the QP requires: an active table row (scoped to the current test database, like
+ `mt/id` resolution) with at least one active field."
[^String table-name timeout-ms]
(let [timer (u/start-timer)]
(loop []
- (let [table (t2/select-one :model/Table :name table-name)
- fields (t2/select :model/Field :table_id (:id table))]
+ (let [table (t2/select-one :model/Table :db_id (mt/id) :name table-name :active true)]
(cond
- (and table (seq fields)) table
+ (and table (t2/exists? :model/Field :table_id (:id table) :active true))
+ table
+
(> (u/since-ms timer) timeout-ms)
- (throw (ex-info (format "Table %s did not appear after %dms" table-name timeout-ms)
+ (throw (ex-info (format "Table %s did not become queryable after %dms" table-name timeout-ms)
{:table-name table-name :timeout-ms timeout-ms}))
+
:else (do (Thread/sleep 100)
(recur)))))))
diff --git a/test/metabase/transforms_rest/api/transform_job_test.clj b/test/metabase/transforms_rest/api/transform_job_test.clj
index 3ac8c39d9d3..86d2131b561 100644
--- a/test/metabase/transforms_rest/api/transform_job_test.clj
+++ b/test/metabase/transforms_rest/api/transform_job_test.clj
@@ -506,3 +506,23 @@
:start_time (parse-instant "2025-09-01T10:00:00")}]
(mt/user-http-request :rasta :get 403
(str "transform-job/" job-id "/runs/" run-id "/transform-runs"))))))
+
+(deftest built-in-jobs-and-tags-seeded-test
+ (testing "the built-in Hourly/Daily/Weekly/Monthly jobs and tags are pre-seeded (migration data)"
+ ;; Looked up by :name (stable) rather than :entity_id/:built_in_type: editing a built-in job in
+ ;; any way (even flipping :active, see update-all-jobs-active-test) permanently clears
+ ;; :built_in_type per metabase.transforms.models.transform-job's before-update hook ("never
+ ;; translate again"), so :built_in_type is not a stable signal once other tests in this
+ ;; JVM/app-db have exercised the update path on these rows. Names, seeded once in
+ ;; 057_update_migrations.yaml, remain stable.
+ (doseq [[job-name tag-name] [["Hourly job" "hourly"]
+ ["Daily job" "daily"]
+ ["Weekly job" "weekly"]
+ ["Monthly job" "monthly"]]]
+ (let [job (t2/select-one :model/TransformJob :name job-name)
+ tag (t2/select-one :model/TransformTag :name tag-name)]
+ (is (some? job) (str "missing built-in job " job-name))
+ (is (some? tag) (str "missing built-in tag " tag-name))
+ (is (seq (:schedule job)) (str job-name " should carry a schedule"))
+ (is (t2/exists? :model/TransformJobTransformTag :job_id (:id job) :tag_id (:id tag))
+ (str job-name " should be linked to the " tag-name " tag"))))))
diff --git a/test/metabase/transforms_rest/api/transform_test.clj b/test/metabase/transforms_rest/api/transform_test.clj
index 13b1e59b671..6855803f8f0 100644
--- a/test/metabase/transforms_rest/api/transform_test.clj
+++ b/test/metabase/transforms_rest/api/transform_test.clj
@@ -5,7 +5,9 @@
[clojure.test :refer :all]
[medley.core :as m]
[metabase.driver :as driver]
+ [metabase.driver.sql.util :as sql.u]
[metabase.driver.util :as driver.u]
+ [metabase.lib-be.metadata.jvm :as lib.metadata.jvm]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.permissions.core :as perms]
@@ -15,13 +17,16 @@
[metabase.test :as mt]
[metabase.transforms-base.util :as transforms-base.u]
[metabase.transforms-rest.api.transform]
+ [metabase.transforms.core :as transforms.core]
[metabase.transforms.models.transform :as transform.model]
[metabase.transforms.query-test-util :as query-test-util]
[metabase.transforms.test-dataset :as transforms-dataset]
[metabase.transforms.test-util :refer [get-test-schema
parse-instant
seconds-from-now-ns
+ table-rows
utc-timestamp
+ wait-for-table
with-transform-cleanup!]]
[metabase.util :as u]
[toucan2.core :as t2]))
@@ -816,19 +821,6 @@
(str "Expected " (count ids) " rows with category " category
" in table " table-name ", but got " actual-count)))))
-(defn- wait-for-table
- "Wait for a table to appear in metadata, with timeout.
- Copied from execute_test.clj - will consolidate later."
- [table-name timeout-ms]
- (let [mp (mt/metadata-provider)
- limit (+ (System/currentTimeMillis) timeout-ms)]
- (loop []
- (Thread/sleep 200)
- (when (> (System/currentTimeMillis) limit)
- (throw (ex-info "table has not been created" {:table-name table-name, :timeout-ms timeout-ms})))
- (or (m/find-first (comp #{table-name} :name) (lib.metadata/tables mp))
- (recur)))))
-
(deftest execute-transform-test
(mt/with-premium-features #{}
(testing "transform execution with :transforms/table target"
@@ -851,7 +843,7 @@
{transform-id :id} (mt/user-http-request :lucky :post 200 "transform"
original)
_ (do (test-run! transform-id)
- (wait-for-table table1-name 5000))
+ (wait-for-table table1-name 30000))
_ (is (true? (transforms-base.u/target-table-exists? original)))
_ (check-query-results table1-name [5 11 16] "Gadget")
updated {:name "Doohickey Products"
@@ -865,7 +857,7 @@
(mt/user-http-request :lucky :put 200 (format "transform/%s" transform-id) updated)
(update-in [:source :query] lib/normalize))))
(test-run! transform-id)
- (wait-for-table table2-name 5000)
+ (wait-for-table table2-name 30000)
(is (true? (transforms-base.u/target-table-exists? original)))
(is (true? (transforms-base.u/target-table-exists? updated)))
(check-query-results table2-name [2 3 4 13] "Doohickey")))))))))))
@@ -1259,7 +1251,8 @@
:target {:type "table" :name (mt/random-name)}})
(mt/user-http-request :rasta :put 403 (str "transform/" (:id transform))
{:name "Updated"})
- (mt/user-http-request :rasta :delete 403 (str "transform/" (:id transform))))
+ (mt/user-http-request :rasta :delete 403 (str "transform/" (:id transform)))
+ (mt/user-http-request :rasta :post 403 (format "transform/%d/run" (:id transform))))
(testing "Data analysts can read transforms"
(mt/with-data-analyst-role! (mt/user->id :lucky)
(mt/user-http-request :lucky :get 200 "transform")
@@ -1919,3 +1912,154 @@
(mt/user-http-request :crowberto :get 400 "transform/run"
:sort-column "bogus"
:sort-direction "asc")))))))
+
+(deftest execute-transform-with-field-filter-template-tag-test
+ (testing "a required field-filter (:dimension) template tag resolves via its default value at unattended execution"
+ (mt/with-premium-features #{}
+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table)
+ (mt/dataset transforms-dataset/transforms-test
+ (mt/with-db-perm-for-group! (perms-group/all-users) (mt/id) :perms/transforms :yes
+ (mt/with-data-analyst-role! (mt/user->id :lucky)
+ (with-transform-cleanup! [table-name "field_filter_default_output"]
+ (let [mp (mt/metadata-provider)
+ category-col (lib.metadata/field mp (mt/id :transforms_products :category))
+ [source-schema source-table-name] (t2/select-one-fn (juxt :schema :name) :model/Table
+ (mt/id :transforms_products))
+ ;; Qualify the FROM clause with its schema so that drivers which require the WHERE clause's
+ ;; field-filter substitution (a fully qualified `schema.table.column` reference) to agree with
+ ;; the table expression named in FROM (e.g. ClickHouse) can resolve the query. An unqualified
+ ;; `FROM transforms_products` combined with a qualified WHERE reference is invalid there.
+ qualified-source-table (sql.u/quote-name driver/*driver* :table
+ source-schema source-table-name)
+ query (lib/with-template-tags
+ (lib/native-query mp (format "SELECT * FROM %s WHERE {{ cat }}" qualified-source-table))
+ {"cat" {:id "cat" :name "cat" :display-name "Cat"
+ :type :dimension :widget-type :string/=
+ :dimension (lib/ref category-col)
+ :required true :default ["Gadget"]}})
+ {id :id} (mt/user-http-request :lucky :post 200 "transform"
+ {:name "Field Filter Transform"
+ :source {:type "query" :query query}
+ :target {:type "table"
+ :schema (get-test-schema)
+ :name table-name}})]
+ (test-run! id)
+ (check-query-results table-name [5 11 16] "Gadget"))))))))))
+
+(deftest execute-transform-with-table-template-tag-test
+ (testing "a table (table-variable) template tag substitutes a schema-qualified identifier at unattended execution"
+ (mt/with-premium-features #{}
+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table)
+ (mt/dataset transforms-dataset/transforms-test
+ (mt/with-db-perm-for-group! (perms-group/all-users) (mt/id) :perms/transforms :yes
+ (mt/with-data-analyst-role! (mt/user->id :lucky)
+ (with-transform-cleanup! [table-name "table_tag_output"]
+ (let [source-table-id (mt/id :transforms_products)
+ query (lib/with-template-tags
+ (lib/native-query (mt/metadata-provider) "SELECT * FROM {{ tbl }}")
+ {"tbl" {:id "tbl" :name "tbl" :display-name "Tbl" :type :table
+ :table-id source-table-id}})
+ {id :id} (mt/user-http-request :lucky :post 200 "transform"
+ {:name "Table Tag Transform"
+ :source {:type "query" :query query}
+ :target {:type "table"
+ :schema (get-test-schema)
+ :name table-name}})]
+ (test-run! id)
+ (wait-for-table table-name 30000)
+ (is (= (count (table-rows "transforms_products"))
+ (count (table-rows table-name)))))))))))))
+
+(deftest reject-target-name-collision-test
+ (testing "target-name collision with a pre-existing, non-transform table is rejected"
+ (mt/with-premium-features #{}
+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table)
+ (mt/dataset transforms-dataset/transforms-test
+ (mt/with-db-perm-for-group! (perms-group/all-users) (mt/id) :perms/transforms :yes
+ (mt/with-data-analyst-role! (mt/user->id :lucky)
+ (let [schema (get-test-schema)
+ existing-table-name (t2/select-one-fn :name :model/Table (mt/id :transforms_products))
+ other-existing-name (t2/select-one-fn :name :model/Table (mt/id :transforms_orders))]
+ (testing "POST /api/transform"
+ (mt/user-http-request :lucky :post 403 "transform"
+ {:name "Colliding Transform"
+ :source {:type "query" :query (make-query "Gadget")}
+ :target {:type "table"
+ :schema schema
+ :name existing-table-name}}))
+ (testing "PUT /api/transform/:id (target-change collision)"
+ (with-transform-cleanup! [table-name "collision_source"]
+ (let [created (mt/user-http-request :lucky :post 200 "transform"
+ {:name "Non-colliding Transform"
+ :source {:type "query" :query (make-query "Gadget")}
+ :target {:type "table"
+ :schema schema
+ :name table-name}})]
+ (mt/user-http-request :lucky :put 403 (format "transform/%d" (:id created))
+ {:target {:type "table"
+ :schema schema
+ :name other-existing-name}}))))))))))))
+
+(deftest delete-target-then-recreate-same-name-test
+ (testing "re-running after DELETE /api/transform/:id/table recreates the same target name"
+ (mt/with-premium-features #{}
+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table)
+ (mt/dataset transforms-dataset/transforms-test
+ (with-transform-cleanup! [table-name "gadget_products_recreate"]
+ (let [target {:type "table" :schema (get-test-schema) :name table-name}
+ definition {:name "Recreate Target Transform"
+ :source {:type "query" :query (make-query "Gadget")}
+ :target target}
+ {id :id} (mt/user-http-request :crowberto :post 200 "transform" definition)]
+ (test-run! id)
+ (is (true? (transforms-base.u/target-table-exists? definition)))
+ (mt/user-http-request :crowberto :delete 204 (format "transform/%s/table" id))
+ (is (false? (transforms-base.u/target-table-exists? definition)))
+ (test-run! id)
+ (is (true? (transforms-base.u/target-table-exists? definition))))))))))
+
+(deftest get-transform-with-deleted-database-test
+ (testing "GET /api/transform/:id degrades gracefully when its source database has been deleted"
+ (mt/with-temp [:model/Database db {}]
+ (let [mp (lib.metadata.jvm/application-database-metadata-provider (:id db))
+ query (lib/native-query mp "select 1")]
+ (mt/with-temp [:model/Transform transform {:source {:type "query" :query query}
+ :target {:type "table" :name (mt/random-name)}}]
+ (t2/delete! :model/Database (:id db))
+ (is (=? {:id (:id transform)}
+ (mt/user-http-request :crowberto :get 200 (str "transform/" (:id transform))))))))))
+
+(deftest cancel-transform-run-endpoint-test
+ (testing "POST /api/transform/:id/cancel"
+ (mt/with-premium-features #{}
+ (mt/test-driver :postgres
+ (mt/dataset transforms-dataset/transforms-test
+ (with-transform-cleanup! [table-name "cancel_endpoint_output"]
+ (let [query (lib/native-query (mt/metadata-provider)
+ "SELECT a FROM (SELECT pg_sleep(5)) x, generate_series(1, 5) a")
+ {id :id} (mt/user-http-request :crowberto :post 200 "transform"
+ {:name "Slow Transform"
+ :source {:type "query" :query query}
+ :target {:type "table"
+ :schema (get-test-schema)
+ :name table-name}})]
+ (testing "cancelling a running transform synchronously marks the run canceling"
+ (mt/user-http-request :crowberto :post 202 (format "transform/%s/run" id))
+ (mt/user-http-request :crowberto :post 204 (format "transform/%s/cancel" id))
+ ;; A background poller (every 20s, see metabase.transforms.canceling/CancelRuns) drives
+ ;; the same transition, so an unlucky race can already land the run in "canceled" by the
+ ;; time we check here.
+ (is (contains? #{"canceling" "canceled"}
+ (-> (mt/user-http-request :crowberto :get 200 (format "transform/%s" id))
+ :last_run :status))))
+ ;; Drive the cancelation to completion directly instead of waiting on the 20s background
+ ;; poller — the same mechanism metabase.transforms.canceling-test uses to settle a run
+ ;; synchronously. `running-run-for-transform-id` returns nil if the poller already beat us
+ ;; to it, in which case there's nothing left to do.
+ (when-let [run (transforms.core/running-run-for-transform-id id)]
+ (transforms.core/cancel-run! run (java.time.OffsetDateTime/now)))
+ (is (= "canceled"
+ (-> (mt/user-http-request :crowberto :get 200 (format "transform/%s" id))
+ :last_run :status)))
+ (testing "cancelling a transform with no running run is a 404"
+ (mt/user-http-request :crowberto :post 404 (format "transform/%s/cancel" id))))))))))
diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.clj
index d6b6337d733..336ea2f95b8 100644
--- a/test/metabase/users_rest/api_test.clj
+++ b/test/metabase/users_rest/api_test.clj
@@ -6,6 +6,7 @@
[metabase.collections.models.collection :as collection]
[metabase.config.core :as config]
[metabase.models.interface :as mi]
+ [metabase.notification.test-util :as notification.tu]
[metabase.permissions.core :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.permissions.util :as perms-util]
@@ -25,7 +26,7 @@
(use-fixtures
:once
- (fixtures/initialize :test-users-personal-collections))
+ (fixtures/initialize :test-users-personal-collections :notifications))
(def ^:private user-defaults
(delay
@@ -1774,3 +1775,32 @@
(testing "POST /api/user/:id/password-reset-url nonexistent user gets 404"
(mt/user-http-request :crowberto :post 404
"user/999999/password-reset-url")))
+
+(deftest create-user-without-names-test
+ (testing "POST /api/user succeeds when first and last name are omitted (#22754)"
+ (mt/with-model-cleanup [:model/User]
+ (mt/with-fake-inbox
+ (let [email (mt/random-email)
+ resp (mt/user-http-request :crowberto :post 200 "user" {:email email})]
+ (is (=? {:first_name nil
+ :last_name nil
+ :email email}
+ resp)))))))
+
+(deftest update-blank-name-rejected-test
+ (testing "PUT /api/user/:id rejects a blank/whitespace first_name (#46449)"
+ (mt/with-temp [:model/User {id :id} {}]
+ (let [resp (mt/user-http-request :crowberto :put 400 (str "user/" id) {:first_name " "})]
+ (is (contains? (:errors resp) :first_name))))))
+
+(deftest invite-email-links-to-password-reset-test
+ (testing "POST /api/user with SMTP configured sends an invite email linking to the set-a-password flow (#23630)"
+ (mt/with-model-cleanup [:model/User]
+ (notification.tu/with-send-notification-sync
+ (mt/with-fake-inbox
+ (let [email (mt/random-email)]
+ (mt/user-http-request :crowberto :post 200 "user"
+ {:first_name "Inv" :last_name "Itee" :email email})
+ (let [body (-> @mt/inbox (get email) first :body first :content)]
+ (is (some? body))
+ (is (re-find #"/auth/reset_password/" body)))))))))
diff --git a/test/metabase/warehouse_schema_rest/api/field_test.clj b/test/metabase/warehouse_schema_rest/api/field_test.clj
index 9b8f67f1854..037bc69f79a 100644
--- a/test/metabase/warehouse_schema_rest/api/field_test.clj
+++ b/test/metabase/warehouse_schema_rest/api/field_test.clj
@@ -955,3 +955,25 @@
(data-perms/set-database-permission! pg (mt/id) :perms/create-queries :query-builder)
(is (= {:values [[1] [2] [3] [4]], :field_id (mt/id :venues :price), :has_more_values false}
(mt/user-http-request :rasta :get 200 (format "field/%d/values" (mt/id :venues :price)))))))))))
+
+(deftest update-has-field-values-test
+ (testing "PUT /api/field/:id can change has_field_values across the list/search/none filtering types"
+ (mt/with-temp [:model/Field {fid :id} {:base_type :type/Integer :has_field_values "list"}]
+ (doseq [v ["search" "none" "list"]]
+ (testing (format "has_field_values = %s" v)
+ (mt/user-http-request :crowberto :put 200 (format "field/%d" fid) {:has_field_values v})
+ (is (= (keyword v)
+ (t2/select-one-fn :has_field_values :model/Field :id fid))))))))
+
+(deftest discard-field-values-test
+ (testing "POST /api/field/:id/discard_values"
+ (mt/with-temp [:model/Field {fid :id} {:table_id (mt/id :venues)}
+ :model/FieldValues {fv :id} {:field_id fid :values [1 2 3]}]
+ (testing "requires metadata write permissions"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 (format "field/%d/discard_values" fid))))
+ (is (t2/exists? :model/FieldValues :id fv)))
+ (testing "an admin can discard the cached field values"
+ (is (= {:status "success"}
+ (mt/user-http-request :crowberto :post 200 (format "field/%d/discard_values" fid))))
+ (is (not (t2/exists? :model/FieldValues :id fv)))))))
diff --git a/test/metabase/warehouse_schema_rest/api/table_test.clj b/test/metabase/warehouse_schema_rest/api/table_test.clj
index ec83d0a8ff7..209ac8fdc14 100644
--- a/test/metabase/warehouse_schema_rest/api/table_test.clj
+++ b/test/metabase/warehouse_schema_rest/api/table_test.clj
@@ -1213,7 +1213,7 @@
(deftest trigger-metadata-sync-for-table-test
(testing "Can we trigger a metadata sync for a table?"
(let [sync-called? (promise)
- timeout (* 10 1000)]
+ timeout (* 60 1000)]
(mt/with-premium-features #{:audit-app}
(mt/with-temp [:model/Database {db-id :id} {:engine "h2", :details (:details (mt/db))}
:model/Table table {:db_id db-id :schema "PUBLIC"}]
@@ -1227,7 +1227,7 @@
(testing "POST /api/table/:id/sync_schema"
(testing "User with manage-table-metadata permission can sync table"
(let [sync-called? (promise)
- timeout (* 10 1000)]
+ timeout (* 60 1000)]
(mt/with-premium-features #{:audit-app}
(mt/with-temp [:model/Database {db-id :id} {:engine "h2", :details (:details (mt/db))}
:model/Table table {:db_id db-id :schema "PUBLIC"}]
@@ -1480,3 +1480,16 @@
(data-perms/set-table-permission! (perms-group/all-users) table-id :perms/create-queries :query-builder)
(let [response (mt/user-http-request :rasta :get 202 (format "table/%d/data" table-id))]
(is (map? response))))))))
+
+(deftest bulk-update-tables-visibility-persists-test
+ (testing "PUT /api/table with an ids vector flips visibility_type on every listed table"
+ (mt/with-temp [:model/Table {t1 :id} {:db_id (mt/id) :visibility_type nil}
+ :model/Table {t2 :id} {:db_id (mt/id) :visibility_type nil}]
+ (mt/user-http-request :crowberto :put 200 "table"
+ {:ids [t1 t2] :visibility_type "hidden"})
+ (is (= [:hidden :hidden]
+ (map #(t2/select-one-fn :visibility_type :model/Table :id %) [t1 t2])))
+ (mt/user-http-request :crowberto :put 200 "table"
+ {:ids [t1 t2] :visibility_type nil})
+ (is (= [nil nil]
+ (map #(t2/select-one-fn :visibility_type :model/Table :id %) [t1 t2]))))))
diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.clj
index 96ea9d985ba..47c8e6d6435 100644
--- a/test/metabase/warehouses_rest/api_test.clj
+++ b/test/metabase/warehouses_rest/api_test.clj
@@ -15,6 +15,8 @@
[metabase.driver.settings :as driver.settings]
[metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
[metabase.driver.util :as driver.u]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.models.permissions :as perms]
@@ -35,7 +37,6 @@
[metabase.test.data.users :as test.users]
[metabase.test.fixtures :as fixtures]
[metabase.test.http-client :as client]
- [metabase.test.util :as tu]
[metabase.util :as u]
[metabase.util.cron :as u.cron]
[metabase.util.i18n :refer [deferred-tru]]
@@ -1228,10 +1229,18 @@
(mt/user-http-request :lucky :get 200 "database?saved=true"))))))
(deftest databases-list-include-saved-questions-test-3
- (testing "GET /api/database?saved=true"
- (testing "Omit virtual DB if nested queries are disabled"
- (tu/with-temporary-setting-values [enable-nested-queries false]
- (is (every? some? (:data (mt/user-http-request :lucky :get 200 "database?saved=true"))))))))
+ (testing "GET /api/database?saved=true -- Omit virtual DB if nested queries are disabled (#19341)"
+ (mt/with-temp [:model/Card _ (assoc (card-with-native-query "Some Card")
+ :result_metadata [{:name "col_name"
+ :display_name "Col Name"
+ :base_type :type/Text}])]
+ (testing "sanity check: the virtual DB is present when nested queries are enabled"
+ (is (some :is_saved_questions
+ (:data (mt/user-http-request :lucky :get 200 "database?saved=true")))))
+ (testing "the virtual DB is omitted entirely when nested queries are disabled"
+ (mt/with-temp-env-var-value! ["MB_ENABLE_NESTED_QUERIES" "false"]
+ (is (not-any? :is_saved_questions
+ (:data (mt/user-http-request :lucky :get 200 "database?saved=true")))))))))
(deftest fetch-databases-with-invalid-driver-test
(testing "GET /api/database"
@@ -3144,3 +3153,90 @@
(mt/user-http-request :crowberto :put 400 (format "database/%d" router-id)
{:admin_details {:host "admin-host"
:admin-connection true}}))))))))
+
+(deftest databases-list-can-upload-respects-view-data-test
+ (testing "GET /api/database/:id can_upload reflects the user's view-data permission, not just uploads_enabled"
+ (mt/with-temp [:model/Database {db-id :id} {:engine :postgres
+ :uploads_enabled true
+ :uploads_schema_name "public"}]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) db-id :perms/manage-database :yes)
+ (testing "view-data blocked => can_upload is false"
+ (data-perms/set-database-permission! (perms-group/all-users) db-id :perms/view-data :blocked)
+ (is (false? (:can_upload (mt/user-http-request :rasta :get 200 (str "database/" db-id))))))
+ (testing "unrestricted view-data + query-builder create-queries => can_upload is true"
+ (data-perms/set-database-permission! (perms-group/all-users) db-id :perms/view-data :unrestricted)
+ (data-perms/set-database-permission! (perms-group/all-users) db-id :perms/create-queries :query-builder)
+ (is (true? (:can_upload (mt/user-http-request :rasta :get 200 (str "database/" db-id))))))))))
+
+(deftest native-permissions-value-test
+ (testing "GET /api/database :native_permissions is :write only when create-queries is :query-builder-and-native (#39053)"
+ (mt/with-temp [:model/Database {db-id :id} {}]
+ (letfn [(native-perms []
+ (->> (mt/user-http-request :rasta :get 200 "database")
+ :data
+ (m/find-first (comp #{db-id} :id))
+ :native_permissions
+ keyword))]
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! (perms-group/all-users) db-id :perms/create-queries :query-builder)
+ (is (= :none (native-perms)))
+ (data-perms/set-database-permission! (perms-group/all-users) db-id :perms/create-queries :query-builder-and-native)
+ (is (= :write (native-perms)))
+ (testing "revoking native access reverts :native_permissions to :none"
+ (data-perms/set-database-permission! (perms-group/all-users) db-id :perms/create-queries :query-builder)
+ (is (= :none (native-perms)))))))))
+
+(deftest idfields-excludes-model-cards-test
+ (testing "GET /api/database/:id/idfields only returns real table/field pairs, never model Cards (#31663)"
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Card _ {:type :model
+ :name "Orders Model"
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}]
+ (let [rows (mt/user-http-request :crowberto :get 200 (format "database/%d/idfields" (mt/id)))]
+ (is (seq rows))
+ (is (every? #(t2/exists? :model/Table :id (:table_id %)) rows))
+ (is (every? #(t2/exists? :model/Field :id (:id %)) rows)))))))
+
+(deftest get-schema-tables-include-measures-test
+ (let [mp (mt/metadata-provider)
+ schema (t2/select-one-fn :schema :model/Table :id (mt/id :orders))
+ orders-name (t2/select-one-fn :name :model/Table :id (mt/id :orders))
+ people-name (t2/select-one-fn :name :model/Table :id (mt/id :people))]
+ (testing "GET /api/database/:id/schema/:schema?include_measures=true hydrates :measures per table"
+ (mt/with-temp [:model/Measure _ {:table_id (mt/id :orders)
+ :name "Some measure"
+ :creator_id (mt/user->id :crowberto)
+ :definition (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count)))}]
+ (let [tables (mt/user-http-request :crowberto :get 200
+ (format "database/%d/schema/%s" (mt/id) schema)
+ :include_measures true)
+ by-name (into {} (map (juxt :name identity)) tables)]
+ (is (seq (:measures (get by-name orders-name))))
+ (is (= [] (:measures (get by-name people-name)))))))
+ (testing "measures key is omitted when include_measures is not passed"
+ (let [tables (mt/user-http-request :crowberto :get 200
+ (format "database/%d/schema/%s" (mt/id) schema))]
+ (is (not (contains? (first tables) :measures)))))))
+
+(deftest delete-database-cascades-to-content-test
+ (testing "DELETE /api/database/:id removes the database's dependent Cards and Segments"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {t :id} {:db_id db-id}
+ :model/Card {c :id} {:database_id db-id :table_id t}
+ :model/Segment {s :id} {:table_id t}]
+ (mt/user-http-request :crowberto :delete 204 (format "database/%d" db-id))
+ (is (not (t2/exists? :model/Database :id db-id)))
+ (is (not (t2/exists? :model/Card :id c)))
+ (is (not (t2/exists? :model/Segment :id s))))))
+
+(deftest restore-sample-database-endpoint-test
+ (testing "POST /api/database/sample_database"
+ (testing "requires a superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "database/sample_database"))))
+ (testing "restores and returns the sample database"
+ (mt/with-model-cleanup [:model/Database]
+ (is (=? {:is_sample true}
+ (mt/user-http-request :crowberto :post 200 "database/sample_database")))))))