The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Prevent writing queries failing the schema checks in the DB (#74884)
metambenac5737c926ab
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 34419119383..7089b8a6e17 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -996,7 +996,9 @@:entity_id (u/generate-nano-id))(cond-> (nil? type)(assoc :type :question))- (m/update-existing :dataset_query lib-be/normalize-query))+ ;; Strict so a malformed query throws here instead of being silently+ ;; coerced to `{}`. See #74615.+ (m/update-existing :dataset_query #(lib-be/normalize-query nil % {:strict? true}))){:keys [metadata metadata-future]} (card.metadata/maybe-async-result-metadata;; 1. This function is called when storing metadata.;; 2. The metadata for storage shouldn't have remaps.diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.cljindex 8b316ab54e9..d39315dc075 100644--- a/src/metabase/queries_rest/api/card.clj+++ b/src/metabase/queries_rest/api/card.clj@@ -547,6 +547,15 @@[:size_x ms/PositiveInt][:size_y ms/PositiveInt]]]]])+(defn- normalize-dataset-query-or-400+ "Strictly normalize an incoming `:dataset_query` from an API request, converting any normalization+ failure into a 400 Bad Request."+ [query]+ (try+ (lib-be/normalize-query nil query {:strict? true})+ (catch Throwable e+ (throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 400) e)))))+;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;@@ -557,8 +566,10 @@_query-params{card-type :type, collection-id :collection_id, :as card} :- CardCreateSchema](let [card (-> card- (update :dataset_query lib-be/normalize-query)+ (update :dataset_query normalize-dataset-query-or-400)(cond-> (some? collection-id)+ ;; Strict check to prevent a malformed query (coerced to `{}` by [[lib-be/normalize-query]])+ ;; from being written into the DB (#74615).(update :collection_id #(eid-translation/->id-or-404 :collection %))))query (:dataset_query card)](check-if-card-can-be-saved query card-type)@@ -671,7 +682,9 @@[id :- ::lib.schema.id/card{metadata :result_metadata, card-type :type, :as card-updates} :- CardUpdateSchemadelete-old-dashcards? :- :boolean]- (let [card-updates (m/update-existing card-updates :dataset_query lib-be/normalize-query)+ ;; Strict check to prevent a malformed query (coerced to `{}` by [[lib-be/normalize-query]])+ ;; from being written into the DB (#74615).+ (let [card-updates (m/update-existing card-updates :dataset_query normalize-dataset-query-or-400)query (:dataset_query card-updates)](check-if-card-can-be-saved query card-type)(when-some [query (:dataset_query card-updates)]diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex f3dc5cdfa1c..98858df03b3 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -1244,6 +1244,34 @@(is (some? card))(is (= remote-synced-coll-id (:collection_id card))))))))+(defn- malformed-native-dataset-query+ "See [[metabase.queries-rest.api.card-test/malformed-native-dataset-query]]."+ []+ {:type :native+ :database (mt/id)+ :native {:query "SELECT COUNT(*) FROM ORDERS WHERE {{df}}"+ :template-tags {"df" {:id (str (random-uuid))+ :name "df"+ :display-name "DF"+ :type :dimension+ :widget-type :date/range+ :dimension [:field+ {:base-type :type/DateTime}+ (mt/id :orders :created_at)]}}}})++(deftest create-card!-with-malformed-dataset-query-throws-test+ (testing "queries/create-card! with structurally malformed :dataset_query throws a normalization error, not a SQL constraint error (#74615)"+ (mt/with-model-cleanup [:model/Card]+ (is (thrown-with-msg?+ Throwable+ #"(?i)normaliz|MBQL"+ (card/create-card!+ {:name "Bad card"+ :display "table"+ :visualization_settings {}+ :dataset_query (malformed-native-dataset-query)}+ {:id (mt/user->id :rasta)}))))))+(deftest update-card-remote-synced-collection-non-remote-synced-deps-test(testing "update-card! should throw exception when moving to remote-synced collection with non-remote-synced dependencies"(mt/with-temp [:model/Collection {remote-synced-coll-id :id} {:is_remote_synced true}diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.cljindex beafad1659e..02d9f799dc7 100644--- a/test/metabase/queries_rest/api/card_test.clj+++ b/test/metabase/queries_rest/api/card_test.clj@@ -822,6 +822,41 @@(mt/user-http-request :crowberto :post 400 "card" {:visualization_settings {:global {:title nil}}:parameters "abc"})))))+(defn- malformed-native-dataset-query+ "Payload from #74615: legacy-envelope native query whose template-tag :dimension uses an+ MBQL 5 field reference shape ([:field {opts} id] instead of legacy [:field id opts])."+ []+ {:type :native+ :database (mt/id)+ :native {:query "SELECT COUNT(*) FROM ORDERS WHERE {{df}}"+ :template-tags {"df" {:id (str (random-uuid))+ :name "df"+ :display-name "DF"+ :type :dimension+ :widget-type :date/range+ :dimension [:field+ {:base-type :type/DateTime}+ (mt/id :orders :created_at)]}}}})++(deftest ^:parallel post-card-with-malformed-dataset-query-returns-400-test+ (testing "POST /api/card with structurally malformed :dataset_query returns 400, not 500 (#74615)"+ (is (=? {:cause #"(?si).*(normaliz|mbql).*"}+ (mt/user-http-request+ :crowberto :post 400 "card"+ (assoc (card-with-name-and-query)+ :dataset_query (malformed-native-dataset-query)))))))++(deftest ^:parallel put-card-with-malformed-dataset-query-returns-400-test+ (testing "PUT /api/card/:id with structurally malformed :dataset_query returns 400, not 200 with silent data loss (#74615)"+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (mbql-count-query)}]+ (is (=? {:cause #"(?si).*(normaliz|mbql).*"}+ (mt/user-http-request+ :crowberto :put 400 (str "card/" card-id)+ {:dataset_query (malformed-native-dataset-query)})))+ (testing "the existing dataset_query is preserved (not silently coerced to {})"+ (is (= :mbql/query+ (:lib/type (t2/select-one-fn :dataset_query :model/Card :id card-id))))))))+(deftest create-card-validation-test-2(testing "POST /api/card"(with-temp-native-card-with-params [db card]