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
Remove legacy MBQL conversion steps from SerDes (#71614)
Cam Saulb6a9236b1d38
diff --git a/enterprise/backend/test/metabase_enterprise/analytics/stats_test.clj b/enterprise/backend/test/metabase_enterprise/analytics/stats_test.cljindex 7ddd77d8c5b..f9d5e9038e9 100644--- a/enterprise/backend/test/metabase_enterprise/analytics/stats_test.clj+++ b/enterprise/backend/test/metabase_enterprise/analytics/stats_test.clj@@ -6,9 +6,12 @@[metabase.analytics.stats :as stats][metabase.app-db.core :as mdb][metabase.test :as mt]+ [metabase.test.fixtures :as fixtures][toucan2.core :as t2]))-(deftest ee-snowplow-features-test+(use-fixtures :once (fixtures/initialize :db))++(deftest ^:parallel ee-snowplow-features-test(testing "Every feature returned by `ee-snowplow-features-data` has a corresponding OSS fallback"(let [ee-features (map :name (ee-stats/ee-snowplow-features-data))oss-features (map :name (@#'stats/ee-snowplow-features-data'))]diff --git a/enterprise/backend/test/metabase_enterprise/serialization/test_util.clj b/enterprise/backend/test/metabase_enterprise/serialization/test_util.cljindex 2c1cd414ecf..bf8bbfeee72 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/test_util.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/test_util.clj@@ -59,7 +59,10 @@(defn -data-source-url [^metabase.app_db.data_source.DataSource data-source](.url data-source))-(defmacro with-db [data-source & body]+;; TODO (Cam 2026-03-30) -- give this a clearer name, like `with-current-h2-app-db`+(defmacro with-db+ "Execute `body` with the current app DB bound to an H2 `data-source`."+ [data-source & body]`(binding [mdb.connection/*application-db* (mdb.connection/application-db :h2 ~data-source)](with-open [conn# (.getConnection mdb.connection/*application-db*)](binding [t2.conn/*current-connectable* conn#]@@ -91,10 +94,10 @@(defmacro with-dbs"Create and set up in-memory H2 application databases for each symbol in the bindings vector, each of which is then- bound to the corresponding data-source when executing the body. You can then use [[with-db]] to make any of these- data-sources the current application database.+ bound to the corresponding data-source when executing the body. You can then use [[with-db]] to make any of these+ data-sources the current application database.- This is particularly useful for load/dump/serialization tests, where you need both a source and application db."+ This is particularly useful for load/dump/serialization tests, where you need both a source and application db."{:style/indent [:defn]}[bindings & body](let [arity (count bindings)diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.cljindex 2bc72966b29..0d0032ee57f 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj@@ -337,9 +337,11 @@:table_id ["My Database" nil "Schemaless Table"]:creator_id "[email protected]":collection_id coll-eid- :dataset_query {:query {:source-table ["My Database" nil "Schemaless Table"]- :filter [:>= [:field ["My Database" nil "Schemaless Table" "Some Field"] {}] 18]- :aggregation [[:count]]}+ :dataset_query {:stages [{:source-table ["My Database" nil "Schemaless Table"]+ :filters [[:>= {}+ [:field {} ["My Database" nil "Schemaless Table" "Some Field"]]+ 18]]+ :aggregation [[:count {}]]}]:database "My Database"}:created_at string?}ser))@@ -437,8 +439,8 @@:table_id ["My Database" nil "Schemaless Table"]:creator_id "[email protected]":collection_id coll-eid- :dataset_query {:query {:source-table c4-eid- :aggregation [[:count]]}+ :dataset_query {:stages [{:source-card c4-eid+ :aggregation [[:count {}]]}]:database "My Database"}:created_at string?}ser))@@ -900,9 +902,11 @@:table_id ["My Database" nil "Schemaless Table"]:creator_id "[email protected]":definition {:database "My Database",- :type :query,- :query {:source-table ["My Database" nil "Schemaless Table"],- :filter [:< [:field ["My Database" nil "Schemaless Table" "Some Field"] nil] 18]}}+ :lib/type :mbql/query+ :stages [{:source-table ["My Database" nil "Schemaless Table"],+ :filters [[:< {}+ [:field {} ["My Database" nil "Schemaless Table" "Some Field"]]+ 18]]}]}:created_at string?}ser))(is (not (contains? ser :id)))@@ -947,9 +951,9 @@:table_id ["My Database" nil "Schemaless Table"]:creator_id "[email protected]":definition {:database "My Database"- :type :query- :query {:source-table ["My Database" nil "Schemaless Table"]- :aggregation [[:sum [:field ["My Database" nil "Schemaless Table" "Some Field"] map?]]]}}+ :lib/type :mbql/query+ :stages [{:source-table ["My Database" nil "Schemaless Table"]+ :aggregation [[:sum {} [:field {} ["My Database" nil "Schemaless Table" "Some Field"]]]]}]}:created_at string?}ser))(is (not (contains? ser :id)))@@ -997,9 +1001,9 @@:table_id ["My Database" nil "My Table"]:creator_id "[email protected]":definition {:database "My Database"- :type :query- :query {:source-table ["My Database" nil "My Table"]- :aggregation [[:* [:measure m1-eid] 2]]}}}+ :lib/type :mbql/query+ :stages [{:source-table ["My Database" nil "My Table"]+ :aggregation [[:* {} [:measure {} m1-eid] 2]]}]}}ser))(testing "depends on the referenced Measure"(is (contains? (set (serdes/dependencies ser))@@ -1040,9 +1044,9 @@:table_id ["My Database" nil "My Table"]:creator_id "[email protected]":definition {:database "My Database"- :type :query- :query {:source-table ["My Database" nil "My Table"]- :aggregation [[:count-where [:segment seg-eid]]]}}}+ :lib/type :mbql/query+ :stages [{:source-table ["My Database" nil "My Table"]+ :aggregation [[:count-where {} [:segment {} seg-eid]]]}]}}ser))(testing "depends on the referenced Segment"(is (contains? (set (serdes/dependencies ser))@@ -1157,8 +1161,9 @@:creator_id "[email protected]":created_at string?:query [{:dataset_query {:database "My Database"- :type :native- :native {:query "select 1"}}}]+ :lib/type :mbql/query+ :stages [{:lib/type :mbql.stage/native+ :native "select 1"}]}}]:model_id card-eid-1}ser))(is (not (contains? ser :id)))@@ -2322,7 +2327,9 @@(is (not (contains? ser :id))))(testing "source and target MBQL export"- (is (=? {:source {:query {:database "My Database" :type :query :query {:source-table ["My Database" nil "Schemaless Table"]}}}+ (is (=? {:source {:query {:database "My Database"+ :lib/type :mbql/query+ :stages [{:source-table ["My Database" nil "Schemaless Table"]}]}}:target {:database "My Database" :type "table" :schema "public" :name "target_table"}}(select-keys ser [:source :target]))))diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.cljindex c300cf6a333..fb28e2d064f 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj@@ -239,10 +239,10 @@(testing "the serialized form is as desired"(let [card (first (by-model @serialized "Card"))]- (is (=? {:type :query- :query {:source-table ["my-db" nil "customers"]- :filter [:>= [:field ["my-db" nil "customers" "age"] {}] 18]- :aggregation [[:count]]}+ (is (=? {:lib/type :mbql/query+ :stages [{:source-table ["my-db" nil "customers"]+ :filters [[:>= {} [:field {} ["my-db" nil "customers" "age"]] 18]]+ :aggregation [[:count {}]]}]:database "my-db"}(:dataset_query card)))))@@ -317,14 +317,14 @@(reset! serialized (into [] (serdes.extract/extract {})))))(testing "exported form is properly converted"- (is (= {:database "my-db"- :query {:filter [:< [:field ["my-db" nil "customers" "age"] nil] 18]- :source-table ["my-db" nil "customers"]}- :type :query}- (-> @serialized- (by-model "Segment")- first- :definition))))+ (is (=? {:database "my-db"+ :stages [{:filters [[:< {} [:field {} ["my-db" nil "customers" "age"]] 18]]+ :source-table ["my-db" nil "customers"]}]+ :lib/type :mbql/query}+ (-> @serialized+ (by-model "Segment")+ first+ :definition))))(testing "deserializing adjusts the IDs properly"(ts/with-db dest-db@@ -357,15 +357,15 @@:database (:id @db1d)}(:definition @seg1d))))))))))-(defn- pmbql-query- "Create a simple pMBQL query for the given database and table."+(defn- mbql5-query+ "Create a simple MBQL 5 query for the given database and table."[db-id table-id](let [metadata-provider (lib-be/application-database-metadata-provider db-id)table (lib.metadata/table metadata-provider table-id)](lib/query metadata-provider table)))-(defn- pmbql-segment-definition- "Create a simple pMBQL segment definition with a filter."+(defn- mbql5-segment-definition+ "Create a simple MBQL 5 segment definition with a filter."[db-id table-id field-id](let [metadata-provider (lib-be/application-database-metadata-provider db-id)table (lib.metadata/table metadata-provider table-id)@@ -373,8 +373,8 @@field (lib.metadata/field metadata-provider field-id)](lib/filter query (lib/< field 18))))-(defn- pmbql-measure-definition- "Create an MBQL5 measure definition with a sum aggregation."+(defn- mbql5-measure-definition+ "Create an MBQL 5 measure definition with a sum aggregation."[db-id table-id field-id](let [metadata-provider (lib-be/application-database-metadata-provider db-id)table (lib.metadata/table metadata-provider table-id)@@ -393,16 +393,7 @@table1s (atom nil)field1s (atom nil)msr1s (atom nil)- user1s (atom nil)- db1d (atom nil)- table1d (atom nil)- field1d (atom nil)- user1d (atom nil)- msr1d (atom nil)- db2d (atom nil)- table2d (atom nil)- field2d (atom nil)]-+ user1s (atom nil)](ts/with-dbs [source-db dest-db](testing "serializing the original database, table, field and measure"(ts/with-db source-db@@ -411,50 +402,47 @@(reset! field1s (ts/create! :model/Field :name "amount" :table_id (:id @table1s)))(reset! user1s (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]"))(reset! msr1s (ts/create! :model/Measure :table_id (:id @table1s) :name "Total Sales"- :definition (pmbql-measure-definition (:id @db1s) (:id @table1s) (:id @field1s))+ :definition (mbql5-measure-definition (:id @db1s) (:id @table1s) (:id @field1s)):creator_id (:id @user1s)))(reset! serialized (into [] (serdes.extract/extract {})))))-(testing "exported form is properly converted"(is (=? {:database "my-db"- :query {:aggregation [[:sum [:field ["my-db" nil "sales" "amount"] map?]]]- :source-table ["my-db" nil "sales"]}- :type :query}+ :lib/type :mbql/query+ :stages [{:aggregation [[:sum {} [:field {} ["my-db" nil "sales" "amount"]]]]+ :source-table ["my-db" nil "sales"]}]}(-> @serialized(by-model "Measure")first:definition))))-(testing "deserializing adjusts the IDs properly"(ts/with-db dest-db;; A different database and tables, so the IDs don't match.- (reset! db2d (ts/create! :model/Database :name "other-db"))- (reset! table2d (ts/create! :model/Table :name "orders" :db_id (:id @db2d)))- (reset! field2d (ts/create! :model/Field :name "subtotal" :table_id (:id @table2d)))- (reset! user1d (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]"))-- ;; Load the serialized content.- (serdes.load/load-metabase! (ingestion-in-memory @serialized))-- ;; Fetch the relevant bits- (reset! db1d (t2/select-one :model/Database :name "my-db"))- (reset! table1d (t2/select-one :model/Table :name "sales"))- (reset! field1d (t2/select-one :model/Field :table_id (:id @table1d) :name "amount"))- (reset! msr1d (t2/select-one :model/Measure :name "Total Sales"))-- (testing "the main Database, Table, and Field have different IDs now"- (is (not= (:id @db1s) (:id @db1d)))- (is (not= (:id @table1s) (:id @table1d)))- (is (not= (:id @field1s) (:id @field1d))))-- (is (not= (:definition @msr1s)- (:definition @msr1d)))- (testing "the Measure's definition is based on the new Database, Table, and Field IDs"- (is (=? {:lib/type :mbql/query- :stages [{:source-table (:id @table1d)- :aggregation [[:sum map? [:field map? (:id @field1d)]]]}]- :database (:id @db1d)}- (:definition @msr1d))))))))))+ (let [db2d (ts/create! :model/Database :name "other-db")+ table2d (ts/create! :model/Table :name "orders" :db_id (:id db2d))+ _ (ts/create! :model/Field :name "subtotal" :table_id (:id table2d))+ _ (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]")]+ ;; Load the serialized content.+ (serdes.load/load-metabase! (ingestion-in-memory @serialized))+ ;; Fetch the relevant bits+ (let [db1d (t2/select-one :model/Database :name "my-db")+ table1d (t2/select-one :model/Table :name "sales")+ field1d (t2/select-one :model/Field :table_id (:id table1d) :name "amount")+ msr1d (t2/select-one :model/Measure :name "Total Sales")]+ (testing "the main Database, Table, and Field have different IDs now"+ (is (pos-int? (:id db1d)))+ (is (not= (:id @db1s) (:id db1d)))+ (is (pos-int? (:id table1d)))+ (is (not= (:id @table1s) (:id table1d)))+ (is (pos-int? (:id field1d)))+ (is (not= (:id @field1s) (:id field1d))))+ (is (not= (:definition @msr1s)+ (:definition msr1d)))+ (testing "the Measure's definition is based on the new Database, Table, and Field IDs"+ (is (=? {:lib/type :mbql/query+ :stages [{:source-table (:id table1d)+ :aggregation [[:sum {} [:field {} (:id field1d)]]]}]+ :database (:id db1d)}+ (:definition msr1d))))))))))))(deftest measure-referencing-measure-test;; Test that a measure referencing another measure can be serialized and deserialized correctly.@@ -466,13 +454,7 @@field1s (atom nil)msr1s (atom nil)msr2s (atom nil)- user1s (atom nil)- db1d (atom nil)- table1d (atom nil)- field1d (atom nil)- msr1d (atom nil)- msr2d (atom nil)]-+ user1s (atom nil)](ts/with-dbs [source-db dest-db](testing "serializing measures where one references the other"(ts/with-db source-db@@ -482,7 +464,7 @@(reset! user1s (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]"));; Create base measure: sum(amount)(reset! msr1s (ts/create! :model/Measure :table_id (:id @table1s) :name "Total Sales"- :definition (pmbql-measure-definition (:id @db1s) (:id @table1s) (:id @field1s))+ :definition (mbql5-measure-definition (:id @db1s) (:id @table1s) (:id @field1s)):creator_id (:id @user1s)));; Create derived measure: base_measure * 2(let [mp (lib-be/application-database-metadata-provider (:id @db1s))@@ -494,36 +476,34 @@:definition derived-definition:creator_id (:id @user1s))))(reset! serialized (into [] (serdes.extract/extract {})))))-(testing "exported form has measure reference with entity_id"(let [derived-measure (first (filter #(= "Double Sales" (:name %)) (by-model @serialized "Measure")))]- (is (=? {:definition {:query {:aggregation [[:* [:measure (:entity_id @msr1s)] 2]]}}}- derived-measure))))-+ (is (=? {:definition {:stages [{:aggregation [[:* {} [:measure {} (:entity_id @msr1s)] 2]]}]}}+ derived-measure))+ (is (= #{[{:id "my-db", :model "Database"}]+ [{:id "my-db", :model "Database"} {:id "sales", :model "Table"}]+ [{:id (:entity_id @msr1s), :model "Measure"}]}+ (serdes/mbql-deps (:definition derived-measure))))))(testing "deserializing adjusts the measure IDs properly"(ts/with-db dest-db- (reset! user1s (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]"))-+ (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]");; Load the serialized content(serdes.load/load-metabase! (ingestion-in-memory @serialized))-;; Fetch the relevant bits- (reset! db1d (t2/select-one :model/Database :name "my-db"))- (reset! table1d (t2/select-one :model/Table :name "sales"))- (reset! field1d (t2/select-one :model/Field :table_id (:id @table1d) :name "amount"))- (reset! msr1d (t2/select-one :model/Measure :name "Total Sales"))- (reset! msr2d (t2/select-one :model/Measure :name "Double Sales"))-- (testing "both measures were loaded"- (is (some? @msr1d))- (is (some? @msr2d)))-- (testing "the derived measure's definition references the base measure by new ID"- (is (=? {:lib/type :mbql/query- :stages [{:source-table (:id @table1d)- :aggregation [[:* {} [:measure {} (:id @msr1d)] 2]]}]- :database (:id @db1d)}- (:definition @msr2d))))))))))+ (let [db1d (t2/select-one :model/Database :name "my-db")+ table1d (t2/select-one :model/Table :name "sales")+ ;; field1d (t2/select-one :model/Field :table_id (:id table1d) :name "amount")+ msr1d (t2/select-one :model/Measure :name "Total Sales")+ msr2d (t2/select-one :model/Measure :name "Double Sales")]+ (testing "both measures were loaded"+ (is (some? msr1d))+ (is (some? msr2d)))+ (testing "the derived measure's definition references the base measure by new ID"+ (is (=? {:lib/type :mbql/query+ :stages [{:source-table (:id table1d)+ :aggregation [[:* {} [:measure {} (:id msr1d)] 2]]}]+ :database (:id db1d)}+ (:definition msr2d)))))))))))(deftest measure-referencing-segment-test;; Test that a measure referencing a segment can be serialized and deserialized correctly.@@ -567,7 +547,7 @@(testing "exported form has segment reference with entity_id"(let [measure (first (by-model @serialized "Measure"))]- (is (=? {:definition {:query {:aggregation [[:count-where [:segment (:entity_id @seg1s)]]]}}}+ (is (=? {:definition {:stages [{:aggregation [[:count-where {} [:segment {} (:entity_id @seg1s)]]]}]}}measure))))(testing "deserializing adjusts the segment IDs properly"@@ -654,7 +634,7 @@{:name "Average order total":fieldRef [:field "Average order total" {:base-type :type/Float}]:enabled true}]- mapping-id (format "[\"dimension\",[\"fk->\",[\"field\",%d,null],[\"field\",%d,null]]]" (:id @field1s) (:id @field2s))+ mapping-id (json/encode [:dimension [:field (:id @field2s) {:source-field (:id @field1s)}]])mapping-dimension [:dimension [:field (:id @field2s) {:source-field (:id @field1s)}]]](reset! card1s (ts/create! :model/Card :name "The Card" :database_id (:id @db1s) :table_id (:id @table1s):collection_id (:id @coll1s) :creator_id (:id @user1s)@@ -662,8 +642,7 @@{:table.pivot_column "SOURCE":table.cell_column "sum":table.columns columns- :column_settings- {(str "[\"ref\",[\"field\"," (:id @field2s) ",null]]") {:column_title "Locus"}}}+ :column_settings {(json/encode [:ref [:field (:id @field2s) nil]]) {:column_title "Locus"}}}:parameter_mappings [{:parameter_id "12345678":target [:dimension [:field (:id @field1s) {:source-field (:id @field2s)}]]}]))(reset! dashcard1s (ts/create! :model/DashboardCard :dashboard_id (:id @dash1s) :card_id (:id @card1s)@@ -736,9 +715,7 @@:column_settings{"[\"ref\",[\"field\",[\"my-db\",null,\"orders\",\"invoice\"],null]]" {:column_title "Locus"}}}dimension [:dimension [:field ["my-db" nil "orders" "invoice"] {:source-field ["my-db" nil "orders" "subtotal"]}]]- dimension-id (json/encode [:dimension [:fk->- [:field [:my-db nil :orders :subtotal] nil]- [:field [:my-db nil :orders :invoice] nil]]])+ dimension-id (json/encode [:dimension [:field [:my-db nil :orders :invoice] {:source-field [:my-db nil :orders :subtotal]}]])exp-dashcard (-> exp-card(assoc :click_behavior {:type "link":linkType "question"@@ -1188,11 +1165,11 @@(serdes.load/load-metabase! ingestion)))))))))(deftest card-with-snippet-test- (let [db1s (atom nil)- table1s (atom nil)- snippet1s (atom nil)- card1s (atom nil)- extracted (atom nil)]+ (let [db1s (atom nil)+ table1s (atom nil)+ snippet1s (atom nil)+ card1s (atom nil)+ extracted (atom nil)](testing "snippets referenced by native cards must be deserialized"(mt/with-empty-h2-app-db!(reset! db1s (ts/create! :model/Database :name "my-db"))@@ -1201,22 +1178,22 @@(reset! card1s (ts/create! :model/Card:name "the query":dataset_query {:database (:id @db1s)- :type :native- :native {:template-tags {"snippet: things"- {:id "e2d15f07-37b3-01fc-3944-2ff860a5eb46"- :name "snippet: filtered data"- :display-name "Snippet: Filtered Data"- :type :snippet- :snippet-name "filtered data"- :snippet-id (:id @snippet1s)}}- :query "SELECT 1;"}}))+ :type :native+ :native {:template-tags {"snippet: things"+ {:id "e2d15f07-37b3-01fc-3944-2ff860a5eb46"+ :name "snippet: filtered data"+ :display-name "Snippet: Filtered Data"+ :type :snippet+ :snippet-name "filtered data"+ :snippet-id (:id @snippet1s)}}+ :query "SELECT 1;"}}))(ts/create! :model/User :first_name "Geddy" :last_name "Lee" :email "[email protected]")(testing "on extraction"(reset! extracted (serdes/extract-one "Card" {} @card1s))- (is (= (:entity_id @snippet1s)- (-> @extracted :dataset_query :native :template-tags (get "snippet: things") :snippet-id))))-+ (is (=? {:stages [{:lib/type :mbql.stage/native+ :template-tags {"snippet: things" {:snippet-id (:entity_id @snippet1s)}}}]}+ (:dataset_query @extracted))))(testing "when loading"(let [new-eid (u/generate-nano-id)ingestion (ingestion-in-memory [(assoc @extracted :entity_id new-eid)])]@@ -1880,7 +1857,7 @@field (ts/create! :model/Field :name "age" :table_id (:id table))user (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]")_segment (ts/create! :model/Segment :table_id (:id table) :name "Minors"- :definition (pmbql-segment-definition (:id db) (:id table) (:id field))+ :definition (mbql5-segment-definition (:id db) (:id table) (:id field)):creator_id (:id user))](reset! serialized (into [] (serdes.extract/extract {})))))@@ -1907,7 +1884,7 @@field (ts/create! :model/Field :name "amount" :table_id (:id table))user (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]")_measure (ts/create! :model/Measure :table_id (:id table) :name "Total Sales"- :definition (pmbql-measure-definition (:id db) (:id table) (:id field))+ :definition (mbql5-measure-definition (:id db) (:id table) (:id field)):creator_id (:id user))](reset! serialized (into [] (serdes.extract/extract {})))))@@ -1936,7 +1913,7 @@:collection_id nil:creator_id (:id user):name "Example Card"- :dataset_query (pmbql-query (:id db) (:id table))+ :dataset_query (mbql5-query (:id db) (:id table)):display :line)](reset! serialized (into [] (serdes.extract/extract {})))))@@ -1972,7 +1949,7 @@:name "Test Transform":description "A test transform":collection_id (:id coll)- :source {:query (pmbql-query (:id db) (:id table))+ :source {:query (mbql5-query (:id db) (:id table)):type "query"}:target {:database (:id db):type "table"diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.cljindex eaa0615f3f0..fcd83baf8c7 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/round_trip_test.clj@@ -156,37 +156,29 @@(try(mt/with-empty-h2-app-db!(delete-dir-contents! dev-inspect-dir)-(load-extract! source-dir output-dir)-(let [source-files (fileset source-dir)output-files (fileset output-dir)missing-files (set/difference source-files output-files)added-files (set/difference output-files source-files)]-(testing "No files are missing"(is (empty? missing-files)))(testing "No files have been added"(is (empty? added-files)))-(testing "File contents\n"(doseq [file source-files:let [ref-file (io/file source-dir file)out-file (io/file output-dir file)]:when (.exists out-file):let [delta (compare-files ref-file out-file)]]-(is (nil? delta)(str "Content mismatch for file: " (strip-base-path source-dir file)))-;; Leave behind files for developers to inspect(when (and (.exists dev-inspect-dir) delta)(vreset! wrote-files? true)(create-files-to-diff! ref-file out-file))))-(when @wrote-files?(log/warn "Mismatching files have been written to /dev/serialization_deltas"))))-(finally(delete-dir-contents! output-dir))))))diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/test_util_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/test_util_test.cljindex 29c3457c7b8..886009194d5 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/test_util_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/test_util_test.clj@@ -19,13 +19,15 @@:type "query":query {:source-table crm-id:aggregation [["cum-count"]]- :breakout [["datetime-field" [:field created-id] "week"]]- :filter ["<" [:field nps-id] 9]}}+ :breakout [[:field created-id {"temporal-unit" "week"}]]+ :filter ["<" [:field nps-id nil] 9]}}(#'serdes/mbql-fully-qualified-names->ids{:database "Metabase Store",:type "query",:query {:source-table ["Metabase Store" "public" "crm_survey_response"],:aggregation [["cum-count"]],- :breakout [["datetime-field" ["field-id" ["Metabase Store" "public"- "crm_survey_response" "created_at"]] "week"]],- :filter ["<" ["field-id" ["Metabase Store" "public" "crm_survey_response" "nps"]] 9]}}))))))+ :breakout [["field"+ ["Metabase Store" "public"+ "crm_survey_response" "created_at"]+ {"temporal-unit" "week"}]]+ :filter ["<" ["field" ["Metabase Store" "public" "crm_survey_response" "nps"] nil] 9]}}))))))diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljcindex 70365f69ac4..0e379960e08 100644--- a/src/metabase/legacy_mbql/schema.cljc+++ b/src/metabase/legacy_mbql/schema.cljc@@ -391,8 +391,11 @@[_tag dest-field-id _opts] (normalize-field dest-field)][:field dest-field-id {:source-field source-field-id}]):field (let [[_tag id-or-name opts] x]+ (assert ((some-fn nil? map?) opts) "Attempted to normalize an MBQL 5 :field clause as MBQL 4");; if someone accidentally nests `:field` clauses fix it for them- (if (sequential? id-or-name)+ (if (and (sequential? id-or-name)+ ((some-fn keyword? string?) (first id-or-name))+ (= (keyword (first id-or-name)) :field))(let [[_tag id-or-name recursive-opts] (normalize-field id-or-name)][:field id-or-name (not-empty (merge recursive-opts opts))])[:field id-or-name (not-empty opts)]))diff --git a/src/metabase/lib/metadata/cached_provider.cljc b/src/metabase/lib/metadata/cached_provider.cljcindex 2b5fa992740..d3a70fdb3e3 100644--- a/src/metabase/lib/metadata/cached_provider.cljc+++ b/src/metabase/lib/metadata/cached_provider.cljc@@ -1,7 +1,8 @@(ns metabase.lib.metadata.cached-provider(:refer-clojure :exclude [update-keys get-in #?(:clj doseq)])(:require- #?@(:clj ([metabase.util.json :as json]+ #?@(:clj (^{:clj-kondo/ignore [:discouraged-namespace]} [clj-yaml.core]+ [metabase.util.json :as json][pretty.core :as pretty]))[clojure.set :as set][metabase.lib.metadata.protocols :as lib.metadata.protocols]@@ -172,3 +173,9 @@CachedProxyMetadataProvider(fn [_mp json-generator](json/generate-nil nil json-generator))))++#?(:clj+ (extend-protocol clj-yaml.core/YAMLCodec+ CachedProxyMetadataProvider+ (encode [_this]+ nil)))diff --git a/src/metabase/lib/metadata/invocation_tracker.cljc b/src/metabase/lib/metadata/invocation_tracker.cljcindex dc356e92be9..33c1cf83dfb 100644--- a/src/metabase/lib/metadata/invocation_tracker.cljc+++ b/src/metabase/lib/metadata/invocation_tracker.cljc@@ -105,10 +105,8 @@(fn [_mp json-generator](json/generate-nil nil json-generator))))-;;; this is here as a sanity check to make sure we're not trying to write MBQL 5 to SerDes yet until we update the-;;; SerDes code to handle it#?(:clj(extend-protocol clj-yaml.core/YAMLCodecInvocationTracker(encode [_this]- (throw (Exception. "Encoding MBQL 5 queries to YAML for SerDes is not yet supported; please convert the query to legacy first.")))))+ nil)))diff --git a/src/metabase/lib_be/metadata/jvm.clj b/src/metabase/lib_be/metadata/jvm.cljindex bdc70151009..62ccd30e62f 100644--- a/src/metabase/lib_be/metadata/jvm.clj+++ b/src/metabase/lib_be/metadata/jvm.clj@@ -2,6 +2,7 @@"Implementation(s) of [[metabase.lib.metadata.protocols/MetadataProvider]] only for the JVM."(:refer-clojure :exclude [get-in])(:require+ ^{:clj-kondo/ignore [:discouraged-namespace]} [clj-yaml.core][clojure.core.cache :as cache][clojure.core.cache.wrapped :as cache.wrapped][clojure.string :as str]@@ -624,3 +625,8 @@UncachedApplicationDatabaseMetadataProvider(fn [_mp json-generator](json/generate-nil nil json-generator)))++(extend-protocol clj-yaml.core/YAMLCodec+ UncachedApplicationDatabaseMetadataProvider+ (encode [_this]+ nil))diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.cljindex e2a4bba33af..e8e57db6dfc 100644--- a/src/metabase/models/serialization.clj+++ b/src/metabase/models/serialization.clj@@ -63,9 +63,10 @@[malli.transform :as mtx][medley.core :as m];; legacy usages -- do not use in new code- ^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.normalize :as mbql.normalize]+ ^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.schema :as mbql.s][metabase.lib.core :as lib][metabase.lib.schema.id :as lib.schema.id]+ [metabase.lib.schema.parameter :as lib.schema.parameter][metabase.lib.util.match :as lib.util.match][metabase.models.interface :as mi][metabase.models.visualization-settings :as mb.viz]@@ -73,6 +74,8 @@[metabase.util.date-2 :as u.date][metabase.util.json :as json][metabase.util.log :as log]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr][toucan2.core :as t2][toucan2.model :as t2.model][toucan2.realize :as t2.realize]))@@ -82,6 +85,17 @@;; there was no science behind picking 100 as a number(def ^:private extract-nested-batch-limit "max amount of entities to fetch nested entities for" 100)+(mr/def ::model-keyword+ [:and+ qualified-keyword?+ [:fn+ {:error/message ":model/X keyword"}+ #(when (qualified-keyword? %)+ (= (namespace %) "model"))]])++(mr/def ::model-keyword-or-symbol+ [:or symbol? ::model-keyword])+;;; # Serialization Overview;;;;;; Serialization (or "serdes") is a system for exporting entities (Dashboards, Cards, Collections, etc.) from one@@ -835,23 +849,23 @@;; TODO: Clean up this [[identity-hash]] infrastructure once the `seed_entity_ids` issue is fixed. See above on the;; details of the two hashing schemes.-(defn- find-by-identity-hash+(mu/defn- find-by-identity-hash"Given a model and a target identity hash, this scans the appdb for any instance of the model corresponding to thehash. Does a complete scan, so this should be called sparingly!";; TODO This should be able to use a cache of identity-hash values from the start of the deserialization process.;; Note that it needs to include either updates (or worst-case, invalidation) at [[load-one!]] time.- [model id-hash]+ [model :- ::model-keyword-or-symbol id-hash](->> (t2/reducible-select model)(into [] (comp (filter #(= id-hash (identity-hash %)))(map t2.realize/realize)(take 1)))first))-(defn lookup-by-id+(mu/defn lookup-by-id"Given an ID string, this endeavours to find the matching entity, whether it's an entity ID or identity hash.This is useful when writing [[xform-one]] to turn a foreign key from a portable form to an appdb ID.Returns a Toucan entity or nil."- [model id-str]+ [model :- ::model-keyword-or-symbol id-str](if (entity-id? id-str)(t2/select-one model :entity_id id-str)(find-by-identity-hash model id-str)))@@ -914,14 +928,15 @@;;; ## General foreign keys-(defn ^:dynamic ^::cache *export-fk*+(mu/defn ^:dynamic ^::cache *export-fk*"Given a numeric foreign key and its model (symbol, name or IModel), looks up the entity by ID and gets its entity IDor identity hash.Unusual parameter order means this can be used as `(update x :some_id export-fk 'SomeModel)`.NOTE: This works for both top-level and nested entities. Top-level entities like `Card` are returned as just aportable ID string.. Nested entities are returned as a vector of such ID strings."- [id model]+ [id :- [:maybe pos-int?]+ model :- ::model-keyword-or-symbol](when id(let [model-name (name model)entity (t2/select-one model (first (t2/primary-keys model)) id)@@ -945,7 +960,7 @@(throw e#))nil)))-(defn ^:dynamic ^::cache *import-fk*+(mu/defn ^:dynamic ^::cache *import-fk*"Given an identifier, and the model it represents (symbol, name or IModel), looks up the correspondingentity and gets its primary key.@@ -956,7 +971,8 @@Throws if the corresponding entity cannot be found.Unusual parameter order means this can be used as `(update x :some_id import-fk 'SomeModel)`."- [eid model]+ [eid+ model :- ::model-keyword-or-symbol](when eid(let [eid (if (vector? eid)(last eid)@@ -967,14 +983,16 @@(throw (ex-info "Could not find foreign key target - bad serdes dependencies or other serialization error"{:entity_id eid :model (name model)}))))))-(defn ^:dynamic ^::cache *export-fk-keyed*+(mu/defn ^:dynamic ^::cache *export-fk-keyed*"Given a numeric ID, look up a different identifying field for that entity, and return it as a portable ID.Eg. `Database.name`.[[import-fk-keyed]] is the inverse.Unusual parameter order lets this be called as, for example, `(update x :db_id export-fk-keyed :model/Database :name)`.Note: This assumes the primary key is called `:id`."- [id model field]+ [id+ model :- ::model-keyword-or-symbol+ field](t2/select-one-fn field model :id id))(defn ^:dynamic ^::cache *import-fk-keyed*@@ -988,19 +1006,19 @@(t2/select-one-pk model field portable));;; ## Users-(defn ^:dynamic ^::cache *export-user*+(mu/defn ^:dynamic ^::cache *export-user*"Exports a user as the email address.This just calls [[export-fk-keyed]], but the counterpart [[import-user]] is more involved. This is a unique functionso they form a pair."- [id]+ [id :- [:maybe ::lib.schema.id/user]](when id (*export-fk-keyed* id 'User :email)))-(defn ^:dynamic ^::cache *import-user*+(mu/defn ^:dynamic ^::cache *import-user*"Imports a user by their email address.If a user with that email address exists, returns its primary key.If no such user exists, creates a dummy inactive one with the default settings, blank name, and randomized password.Does not send any invite emails."- [email]+ [email :- [:maybe string?]](when email(or (*import-fk-keyed* email 'User :email);; Need to break a circular dependency here.@@ -1008,21 +1026,21 @@;;; ## Tables-(defn ^:dynamic ^::cache *export-table-fk*+(mu/defn ^:dynamic ^::cache *export-table-fk*"Given a numeric `table_id`, return a portable table reference.If the `table_id` is `nil`, return `nil`. This is legal for a native question.That has the form `[db-name schema table-name]`, where the `schema` might be nil.[[import-table-fk]] is the inverse."- [table-id]+ [table-id :- [:maybe ::lib.schema.id/table]](when table-id(let [{:keys [db_id name schema]} (t2/select-one :model/Table :id table-id)db-name (t2/select-one-fn :name :model/Database :id db_id)][db-name schema name])))-(defn ^:dynamic ^::cache *import-table-fk*+(mu/defn ^:dynamic ^::cache *import-table-fk*"Given a `table_id` as exported by [[export-table-fk]], resolve it back into a numeric `table_id`.The input might be nil, in which case so is the output. This is legal for a native question."- [[db-name schema table-name :as table-id]]+ [[db-name schema table-name :as table-id] :- [:maybe [:tuple string? [:maybe string?] string?]]](when table-id(if-let [db-id (t2/select-one-fn :id :model/Database :name db-name)](or (t2/select-one-fn :id :model/Table :name table-name :schema schema :db_id db-id)@@ -1088,19 +1106,19 @@[:= :name field][:= :parent_id (recursively-find-field-q table-id rest)]]}))-(defn ^:dynamic ^::cache *export-field-fk*+(mu/defn ^:dynamic ^::cache *export-field-fk*"Given a numeric `field_id`, return a portable field reference.That has the form `[db-name schema table-name field-name]`, where the `schema` might be nil.[[*import-field-fk*]] is the inverse."- [field-id]+ [field-id :- [:maybe ::lib.schema.id/field]](when field-id(let [fields (field-hierarchy field-id)[db-name schema field-name] (*export-table-fk* (:table_id (first fields)))](into [db-name schema field-name] (map :name fields)))))-(defn ^:dynamic ^::cache *import-field-fk*+(mu/defn ^:dynamic ^::cache *import-field-fk* :- [:maybe pos-int?]"Given a `field_id` as exported by [[*export-field-fk*]], resolve it back into a numeric `field_id`."- [[db-name schema table-name & fields :as field-id]]+ [[db-name schema table-name & fields :as field-id] :- [:maybe [:cat string? [:maybe string?] string? #_fields [:+ string?]]]](when field-id(let [table-id (*import-table-fk* [db-name schema table-name])field-q (recursively-find-field-q table-id (reverse fields))]@@ -1117,67 +1135,74 @@;;; ## MBQL Fields-(defn- mbql-entity-reference?+(mu/defn- mbql-clause-tag :- [:maybe [:enum :field :dimension :metric :segment :measure]]"Is given form an MBQL entity reference?"[form]- (mbql.normalize/is-clause? #{:field :field-id :fk-> :dimension :metric :segment :measure} form))+ (when (and (vector? form)+ (#{:field :dimension :metric :segment :measure} (keyword (first form))))+ (keyword (first form))))(defn- normalize [mbql]- (if-not (mbql-entity-reference? mbql)- mbql- (into [(keyword (first mbql))] (map normalize) (rest mbql))))+ (let [tag (mbql-clause-tag mbql)+ schema (case tag+ :field [:multi+ {:dispatch #(and (vector? %)+ (map? (second %)))}+ [true :mbql.clause/field]+ [false ::mbql.s/field]] ; legacy MBQL clause+ :dimension ::lib.schema.parameter/dimension+ :metric :mbql.clause/metric+ :segment :mbql.clause/segment+ :measure :mbql.clause/measure+ #_else nil)]+ (cond->> mbql+ schema (lib/normalize schema mbql))))(defn- mbql-id->fully-qualified-name[mbql]- (-> mbql- normalize- (lib.util.match/replace-lite- ;; `integer?` guard is here to make the operation idempotent- [:field (id :guard integer?) opts]- [:field (*export-field-fk* id) (mbql-id->fully-qualified-name opts)]-- ;; `integer?` guard is here to make the operation idempotent- ;; field-id is still used within parameter mapping dimensions- ;; example relevant clause - [:dimension [:fk-> [:field-id 1] [:field-id 2]]]- [(tag :guard #{:field :field-id}) (id :guard integer?)]- [tag (*export-field-fk* id)]-- {:source-table (id :guard integer?)}- (assoc &match :source-table (*export-table-fk* id))-- ;; source-field is also used within parameter mapping dimensions- ;; example relevant clause - [:field 2 {:source-field 1}]- {:source-field (id :guard integer?)}- (assoc &match :source-field (*export-field-fk* id))-- [:dimension (dim :guard vector?)]- [:dimension (mbql-id->fully-qualified-name dim)]-- [(tag :guard #{:metric :segment :measure}) (id :guard integer?)]- [tag (*export-fk* id (case tag- :metric 'Card- :segment 'Segment- :measure 'Measure))])))--(defn- export-source-table- [source-table]- (if (and (string? source-table)- (str/starts-with? source-table "card__"))- (*export-fk* (-> source-table- (str/split #"__")- second- Integer/parseInt)- 'Card)- (*export-table-fk* source-table)))--(defn- ids->fully-qualified-names+ (lib.util.match/replace-lite (normalize mbql)+ ;; `pos-int?` guard is here to make the operation idempotent+ [:field (opts :guard map?) (id :guard pos-int?)]+ [:field (mbql-id->fully-qualified-name opts) (*export-field-fk* id)]++ ;; legacy (MBQL 4) field refs are still supported in parameter targets and in result metadata `field_ref`...+ [:field (id :guard pos-int?) (opts :guard (some-fn map? nil?))]+ [:field (*export-field-fk* id) (mbql-id->fully-qualified-name opts)]++ ;; MBQL 3 `:field-id` can (allegedly) still show up sometimes? Support it just in case.+ [(tag :guard #{:field :field-id}) (id :guard pos-int?)]+ [tag (*export-field-fk* id)]++ {:source-table (id :guard pos-int?)}+ (assoc &match :source-table (*export-table-fk* id))++ ;; source-field is also used within parameter mapping dimensions+ ;; example relevant clause - [:field 2 {:source-field 1}]+ {:source-field (id :guard pos-int?)}+ (assoc &match :source-field (*export-field-fk* id))++ [:dimension (dim :guard vector?)]+ [:dimension (mbql-id->fully-qualified-name dim)]++ [:metric opts (id :guard pos-int?)]+ [:metric (mbql-id->fully-qualified-name opts) (*export-fk* id 'Card)]++ [:segment opts (id :guard pos-int?)]+ [:segment (mbql-id->fully-qualified-name opts) (*export-fk* id 'Segment)]++ [:measure opts (id :guard pos-int?)]+ [:measure (mbql-id->fully-qualified-name opts) (*export-fk* id 'Measure)]))++(defn export-mbql+ "Given an MBQL expression, convert it to an EDN structure and turn the non-portable Database, Table and Field IDs+ inside it into portable references."[entity](lib.util.match/replace-lite entity- (_ :guard mbql-entity-reference?)+ (_ :guard mbql-clause-tag)(mbql-id->fully-qualified-name &match)(_ :guard sequential?)- (mapv ids->fully-qualified-names &match)+ (mapv export-mbql &match)(_ :guard map?)(reduce-kv@@ -1188,24 +1213,17 @@"database/__virtual"(t2/select-one-fn :name :model/Database :id db-id)))(:card_id :card-id) #(*export-fk* % :model/Card) ; attributes that refer to db fields use `_`; template-tags use `-`- (:source_table :source-table) export-source-table+ (:source_table :source-table) *export-table-fk*+ (:source_card :source-card) #(*export-fk* % :model/Card)::mb.viz/param-mapping-source *export-field-fk*:segment #(*export-fk* % :model/Segment):snippet-id #(*export-fk* % :model/NativeQuerySnippet)- #_else ids->fully-qualified-names)]+ :lib/metadata (constantly nil)+ #_else export-mbql)](update entity k f)))&match&match)))-(defn export-mbql- "Given an MBQL expression, convert it to an EDN structure and turn the non-portable Database, Table and Field IDs- inside it into portable references."- [encoded]- (let [encoded (cond-> encoded- ;; temporary usage until we port SerDes to Lib / MBQL 5- (:lib/type encoded) #_{:clj-kondo/ignore [:discouraged-var]} lib/->legacy-MBQL)]- (ids->fully-qualified-names encoded)))-(defn- portable-id?"True if the provided string is either an Entity ID or identity-hash string."[s]@@ -1216,16 +1234,16 @@(defn- mbql-fully-qualified-names->ids*[entity](lib.util.match/replace-lite entity- ;; handle legacy `:field-id` forms encoded prior to 0.39.0- ;; and also *current* expression forms used in parameter mapping dimensions- ;; example relevant clause - [:dimension [:fk-> [:field-id 1] [:field-id 2]]]- [#{:field-id "field-id"} fully-qualified-name]- (mbql-fully-qualified-names->ids* [:field fully-qualified-name])+ [#{:field "field"} (opts :guard map?) (fully-qualified-name :guard vector?)]+ [:field (mbql-fully-qualified-names->ids* opts) (*import-field-fk* fully-qualified-name)]- [#{:field "field"} (fully-qualified-name :guard vector?) opts]- [:field (*import-field-fk* fully-qualified-name) (mbql-fully-qualified-names->ids* opts)]- [#{:field "field"} (fully-qualified-name :guard vector?)]- [:field (*import-field-fk* fully-qualified-name)]+ ;; legacy field refs, still used in parameters and result metadata `field_ref`+ [#{:field "field"} (fully-qualified-name :guard vector?) (opts :guard (some-fn map? nil))]+ [:field (*import-field-fk* fully-qualified-name) (some-> opts mbql-fully-qualified-names->ids*)]++ ;; MBQL 3 `:field-id` can (allegedly) still show up sometimes? Support it just in case.+ [(tag :guard #{:field :field-id "field" "field-id"}) (id :guard vector?)]+ [:field (*import-field-fk* id) nil];; source-field is also used within parameter mapping dimensions;; example relevant clause - [:field 2 {:source-field 1}]@@ -1244,14 +1262,24 @@(assoc :card-id (*import-fk* entity-id 'Card))mbql-fully-qualified-names->ids*) ; Process other keys+ [#{:metric "metric"} opts (entity-id :guard portable-id?)]+ [:metric (mbql-fully-qualified-names->ids* opts) (*import-fk* entity-id 'Card)]++ [#{:segment "segment"} opts (entity-id :guard portable-id?)]+ [:segment (mbql-fully-qualified-names->ids* opts) (*import-fk* entity-id 'Segment)]++ [#{:measure "measure"} opts (entity-id :guard portable-id?)]+ [:measure (mbql-fully-qualified-names->ids* opts) (*import-fk* entity-id 'Measure)]++ ;; support legacy MBQL 4 refs for things like the serialized Audit v2 queries[#{:metric "metric"} (entity-id :guard portable-id?)][:metric (*import-fk* entity-id 'Card)]- [#{:segment "segment"} (fully-qualified-name :guard portable-id?)]- [:segment (*import-fk* fully-qualified-name 'Segment)]+ [#{:segment "segment"} (entity-id :guard portable-id?)]+ [:segment (*import-fk* entity-id 'Segment)]- [#{:measure "measure"} (fully-qualified-name :guard portable-id?)]- [:measure (*import-fk* fully-qualified-name 'Measure)]+ [#{:measure "measure"} (entity-id :guard portable-id?)]+ [:measure (*import-fk* entity-id 'Measure)]{:source-table (_ :guard vector?)}(-> &match@@ -1263,15 +1291,16 @@(update :source_table *import-table-fk*)mbql-fully-qualified-names->ids*)+ ;; support legacy MBQL 4 for the Audit v2 queries{:source-table (id :guard portable-id?)}(-> &match(assoc :source-table (str "card__" (*import-fk* id 'Card)))mbql-fully-qualified-names->ids*)- {:source_table (id :guard portable-id?)}+ {:source-card (id :guard portable-id?)}(-> &match- (assoc :source_table (str "card__" (*import-fk* id 'Card)))- mbql-fully-qualified-names->ids*) ;; process other keys+ (assoc :source-card (*import-fk* id 'Card))+ mbql-fully-qualified-names->ids*){:snippet-id (id :guard portable-id?)}(-> &match@@ -1291,20 +1320,23 @@(defn- mbql-deps-vector [entity](match entity- [:field (field :guard vector?)] #{(field->path field)}- ["field" (field :guard vector?)] #{(field->path field)}- [:field-id (field :guard vector?)] #{(field->path field)}- ["field-id" (field :guard vector?)] #{(field->path field)}- [:field (field :guard vector?) tail] (into #{(field->path field)} (mbql-deps-map tail))- ["field" (field :guard vector?) tail] (into #{(field->path field)} (mbql-deps-map tail))- [:field-id (field :guard vector?) tail] (into #{(field->path field)} (mbql-deps-map tail))- ["field-id" (field :guard vector?) tail] (into #{(field->path field)} (mbql-deps-map tail))- [:metric (field :guard portable-id?)] #{[{:model "Card" :id field}]}- ["metric" (field :guard portable-id?)] #{[{:model "Card" :id field}]}- [:segment (field :guard portable-id?)] #{[{:model "Segment" :id field}]}- ["segment" (field :guard portable-id?)] #{[{:model "Segment" :id field}]}- [:measure (field :guard portable-id?)] #{[{:model "Measure" :id field}]}- ["measure" (field :guard portable-id?)] #{[{:model "Measure" :id field}]}+ [:field (opts :guard map?) (id :guard vector?)] (into #{(field->path id)} (mbql-deps-map opts))+ ["field" (opts :guard map?) (id :guard vector?)] (into #{(field->path id)} (mbql-deps-map opts))+ [:metric (opts :guard map?) (id :guard portable-id?)] (into #{[{:model "Card" :id id}]} (mbql-deps-map opts))+ ["metric" (opts :guard map?) (id :guard portable-id?)] (into #{[{:model "Card" :id id}]} (mbql-deps-map opts))+ [:segment (opts :guard map?) (id :guard portable-id?)] (into #{[{:model "Segment" :id id}]} (mbql-deps-map opts))+ ["segment" (opts :guard map?) (id :guard portable-id?)] (into #{[{:model "Segment" :id id}]} (mbql-deps-map opts))+ [:measure (opts :guard map?) (id :guard portable-id?)] (into #{[{:model "Measure" :id id}]} (mbql-deps-map opts))+ ["measure" (opts :guard map?) (id :guard portable-id?)] (into #{[{:model "Measure" :id id}]} (mbql-deps-map opts))+ ;; legacy (MBQL 4) refs+ [:field (id :guard vector?) opts] (into #{(field->path id)} (mbql-deps-map opts))+ ["field" (id :guard vector?) opts] (into #{(field->path id)} (mbql-deps-map opts))+ [:metric (id :guard portable-id?)] #{[{:model "Card" :id id}]}+ ["metric" (id :guard portable-id?)] #{[{:model "Card" :id id}]}+ [:segment (id :guard portable-id?)] #{[{:model "Segment" :id id}]}+ ["segment" (id :guard portable-id?)] #{[{:model "Segment" :id id}]}+ [:measure (id :guard portable-id?)] #{[{:model "Measure" :id id}]}+ ["measure" (id :guard portable-id?)] #{[{:model "Measure" :id id}]}:else (reduce #(cond(map? %2) (into %1 (mbql-deps-map %2))(vector? %2) (into %1 (mbql-deps-vector %2))@@ -1312,23 +1344,22 @@#{}entity)))-(defn- mbql-deps-map [entity]- (assert (not (:lib/type entity))- "SerDes v2 does not currently work on MBQL 5, please convert to legacy first")- (->> (for [[k v] entity]- (cond- (and (= k :database)- (string? v)- (not= v "database/__virtual")) #{[{:model "Database" :id v}]}- (and (= k :source-table) (vector? v)) #{(table->path v)}- (and (= k :source-table) (portable-id? v)) #{[{:model "Card" :id v}]}- (and (= k :source-field) (vector? v)) #{(field->path v)}- (and (= k :snippet-id) (portable-id? v)) #{[{:model "NativeQuerySnippet" :id v}]}- (and (= k :card_id) (string? v)) #{[{:model "Card" :id v}]}- (and (= k :card-id) (string? v)) #{[{:model "Card" :id v}]}- (map? v) (mbql-deps-map v)- (vector? v) (mbql-deps-vector v)))- (reduce set/union #{})))+(defn- mbql-deps-map [m]+ (into #{}+ (mapcat (fn [[k v]]+ (cond+ (and (= k :database)+ (string? v)+ (not= v "database/__virtual")) #{[{:model "Database" :id v}]}+ (and (= k :source-table) (vector? v)) #{(table->path v)}+ (and (= k :source-table) (portable-id? v)) #{[{:model "Card" :id v}]}+ (and (= k :source-card) (portable-id? v)) #{[{:model "Card" :id v}]}+ (and (= k :source-field) (vector? v)) #{(field->path v)}+ (and (= k :snippet-id) (portable-id? v)) #{[{:model "NativeQuerySnippet" :id v}]}+ (and (#{:card_id :card-id} k) (string? v)) #{[{:model "Card" :id v}]}+ (map? v) (mbql-deps-map v)+ (vector? v) (mbql-deps-vector v))))+ m))(defn mbql-deps"Given an MBQL expression as exported, with qualified names like `[\"some-db\" \"schema\" \"table_name\"]` instead of@@ -1343,7 +1374,7 @@;;; ## Dashboard/Question Parameters(defn- export-parameter-mapping [mapping]- (ids->fully-qualified-names mapping))+ (export-mbql mapping))(defn export-parameter-mappings"Given the :parameter_mappings field of a `Card` or `DashboardCard`, as a vector of maps, converts@@ -1371,7 +1402,7 @@(->> parameters(map-indexed (fn [i p] (assoc p :position i)))(sort-by :id)- (mapv ids->fully-qualified-names)))+ (mapv export-mbql)))(defn import-parameters"Given the :parameter field as exported by serialization convert its field references@@ -1425,13 +1456,13 @@"database" (*export-fk-keyed* id :model/Database :name)(*export-fk* id (link-card-model->toucan-model model)))}))))-(defn- json-ids->fully-qualified-names+(defn- json-export-mbql"Converts IDs to fully qualified names inside a JSON string.Returns a new JSON string with the IDs converted inside."[json-str](-> json-strjson/decode+kw- ids->fully-qualified-names+ export-mbqljson/encode))(defn- json-mbql-fully-qualified-names->ids@@ -1453,14 +1484,16 @@(defn- import-viz-click-behavior-link[{:keys [linkType type] :as click-behavior}](cond-> click-behavior- (= type "link") (-> (update :targetId *import-fk* (link-card-model->toucan-model linkType))+ (= type "link") (-> (u/update-some :targetId (fn [eid]+ (when-let [model (link-card-model->toucan-model linkType)]+ (*import-fk* eid model))))(u/update-some :tabId *import-fk* :model/DashboardTab))))(defn- export-viz-click-behavior-mapping [mapping](-> mapping- (m/update-existing :id json-ids->fully-qualified-names)- (m/update-existing-in [:target :id] json-ids->fully-qualified-names)- (m/update-existing-in [:target :dimension] ids->fully-qualified-names)))+ (m/update-existing :id json-export-mbql)+ (m/update-existing-in [:target :id] json-export-mbql)+ (m/update-existing-in [:target :dimension] export-mbql)))(defn- import-viz-click-behavior-mapping [mapping](-> mapping@@ -1479,7 +1512,7 @@;; click_behavior or not convert it's keys to a keywords. We need its full content here.:let [k (u/qualified-name kw-key)]](if (mb.viz/dimension-param-mapping? mapping)- [(json-ids->fully-qualified-names k)+ [(json-export-mbql k)(export-viz-click-behavior-mapping mapping)][k mapping]))))@@ -1506,8 +1539,8 @@(defn- export-pivot-table [settings](some-> settings- (m/update-existing-in [:pivot_table.column_split :rows] ids->fully-qualified-names)- (m/update-existing-in [:pivot_table.column_split :columns] ids->fully-qualified-names)))+ (m/update-existing-in [:pivot_table.column_split :rows] export-mbql)+ (m/update-existing-in [:pivot_table.column_split :columns] export-mbql)))(defn- import-pivot-table [settings](some-> settings@@ -1516,14 +1549,12 @@(defn- export-visualizations [entity](lib.util.match/replace-lite entity- ["field-id" (id :guard number?)] ["field-id" (*export-field-fk* id)]- [:field-id (id :guard number?)] [:field-id (*export-field-fk* id)]- ["field-id" (id :guard number?) tail] ["field-id" (*export-field-fk* id) (export-visualizations tail)]- [:field-id (id :guard number?) tail] [:field-id (*export-field-fk* id) (export-visualizations tail)]- ["field" (id :guard number?)] ["field" (*export-field-fk* id)]- [:field (id :guard number?)] [:field (*export-field-fk* id)]- ["field" (id :guard number?) tail] ["field" (*export-field-fk* id) (export-visualizations tail)]- [:field (id :guard number?) tail] [:field (*export-field-fk* id) (export-visualizations tail)]+ [#{"field" :field} (opts :guard map?) (id :guard pos-int?)] [:field (export-visualizations opts) (*export-field-fk* id)]+ ;; legacy refs (MBQL 4)+ [#{"field" :field} (id :guard pos-int?) opts] [:field (*export-field-fk* id) (export-visualizations opts)]+ ;; super-legacy refs (MBQL 3)... not sure these can even still show up IRL+ [#{"field-id" :field-id} (id :guard pos-int?)] [:field-id (*export-field-fk* id)]+ [#{"field-id" :field-id} (id :guard pos-int?) opts] [:field-id (*export-field-fk* id) (export-visualizations opts)](_ :guard map?)(m/map-vals export-visualizations &match)@@ -1600,16 +1631,20 @@(defn- import-visualizations [entity](lib.util.match/replace-lite entity- [#{:field-id "field-id"} (fully-qualified-name :guard vector?) tail]- [:field-id (*import-field-fk* fully-qualified-name) (import-visualizations tail)]+ [#{:field "field"} (opts :guard map?) (fully-qualified-name :guard vector?)]+ [:field (import-visualizations opts) (*import-field-fk* fully-qualified-name)]++ ;; legacy (MBQL 4) field refs+ [#{:field "field"} (fully-qualified-name :guard vector?) opts]+ [:field (*import-field-fk* fully-qualified-name) (import-visualizations opts)]++ ;; super-legacy (MBQL 3) field refs... not even sure these can still show up+ [#{:field-id "field-id"} (fully-qualified-name :guard vector?) opts]+ [:field-id (*import-field-fk* fully-qualified-name) (import-visualizations opts)]+[#{:field-id "field-id"} (fully-qualified-name :guard vector?)][:field-id (*import-field-fk* fully-qualified-name)]- [#{:field "field"} (fully-qualified-name :guard vector?) tail]- [:field (*import-field-fk* fully-qualified-name) (import-visualizations tail)]- [#{:field "field"} (fully-qualified-name :guard vector?)]- [:field (*import-field-fk* fully-qualified-name)]-(_ :guard map?)(m/map-vals import-visualizations &match)@@ -1825,13 +1860,6 @@[k xform](assoc xform :as k))-(def backfill-entity-id-transformer- "Backfills a missing `:entity_id` before export, and imports it as-is."- (constantly- {:export-with-context (fn [instance _key _eid]- (backfill-entity-id instance))- :import identity}))-(defn- compose*"Given two functions that transform the value at `k` within `x`, return their composition."[f g]diff --git a/test/metabase/legacy_mbql/schema_test.cljc b/test/metabase/legacy_mbql/schema_test.cljcindex 62ba22c767c..d94bcfa408b 100644--- a/test/metabase/legacy_mbql/schema_test.cljc+++ b/test/metabase/legacy_mbql/schema_test.cljc@@ -658,3 +658,9 @@[:expression "Last_Date_Active" {:base-type :type/DateTimeWithLocalTZ}]]normalized))(is (mr/validate ::mbql.s/- normalized))))++(deftest ^:parallel fix-incorrectly-nested-field-refs-test+ (are [clause expected] (= expected+ (#'mbql.s/normalize-field clause))+ [:field [:field 1 nil] nil] [:field 1 nil]+ [:field [:field 1 {:x 2, :y 2, :z 2}] {:x 1}] [:field 1 {:x 1, :y 2, :z 2}]))diff --git a/test_resources/serialization_baseline/collections/main/source_question.yaml b/test_resources/serialization_baseline/collections/main/source_question.yamlindex 311a811110b..afb065c7f06 100644--- a/test_resources/serialization_baseline/collections/main/source_question.yaml+++ b/test_resources/serialization_baseline/collections/main/source_question.yaml@@ -8,10 +8,12 @@ database_id: My Databaseparameters: []parameter_mappings: []dataset_query:+ "lib/type": mbql/query+ "lib/metadata": nulldatabase: My Database- native:- query: select 1- type: native+ stages:+ - "lib/type": mbql.stage/native+ native: select 1visualization_settings:column_settings: nullcard_schema: 23diff --git a/test_resources/serialization_baseline/collections/transforms/test_transform.yaml b/test_resources/serialization_baseline/collections/transforms/test_transform.yamlindex 7f12ae621c1..27048291495 100644--- a/test_resources/serialization_baseline/collections/transforms/test_transform.yaml+++ b/test_resources/serialization_baseline/collections/transforms/test_transform.yaml@@ -5,13 +5,15 @@ entity_id: 2HzIFwJ6720JAx07UMavlname: Test Transformsource:query:+ "lib/type": mbql/query+ "lib/metadata": nulldatabase: My Database- query:- source-table:- - My Database- - null- - Schemaless Table- type: query+ stages:+ - "lib/type": mbql.stage/mbql+ source-table:+ - My Database+ - null+ - Schemaless Tabletype: querysource_database_id: My Databasetags:diff --git a/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/measures/my_measure.yaml b/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/measures/my_measure.yamlindex 0161746dd81..b7ae943d817 100644--- a/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/measures/my_measure.yaml+++ b/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/measures/my_measure.yaml@@ -2,20 +2,24 @@ created_at: '2025-12-16T20:33:13.171335Z'creator_id: [email protected]definition:database: My Database- query:- aggregation:- - - sum- - - field- - - My Database- - null- - Schemaless Table- - Some Field- - base-type: type/Text- source-table:- - My Database- - null- - Schemaless Table- type: query+ "lib/type": mbql/query+ "lib/metadata": null+ stages:+ - "lib/type": mbql.stage/mbql+ aggregation:+ - - sum+ - "lib/uuid": 865abdef-bb71-490c-9796-fa5b01bf16a2+ - - field+ - "lib/uuid": c115167e-2961-4ff1-b2e9-8affbff1a20b+ base-type: type/Text+ - - My Database+ - null+ - Schemaless Table+ - Some Field+ source-table:+ - My Database+ - null+ - Schemaless Tableentity_id: 0SHLtATxX8wbutAOlZAtMname: My Measuretable_id:diff --git a/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/segments/my_segment.yaml b/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/segments/my_segment.yamlindex fcb230248e7..28697330fd4 100644--- a/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/segments/my_segment.yaml+++ b/test_resources/serialization_baseline/databases/my_database/tables/schemaless_table/segments/my_segment.yaml@@ -1,22 +1,25 @@created_at: '2024-08-28T14:28:03.451106Z'creator_id: [email protected]definition:+ "lib/type": mbql/query+ "lib/metadata": nulldatabase: My Database- query:- filter:- - <- - - field- - - My Database- - null- - Schemaless Table- - Some Field+ stages:+ - "lib/type": mbql.stage/mbql+ filters:+ - - <+ - "lib/uuid": eb938c48-cdf5-49b4-8652-cb816e281a8b+ - - field+ - "lib/uuid": cfe7c17c-789d-4486-9592-a26f49f06992+ - - My Database+ - null+ - Schemaless Table+ - Some Field+ - 18+ source-table:+ - My Database- null- - 18- source-table:- - My Database- - null- - Schemaless Table- type: query+ - Schemaless Tabledescription: Lookin' for a blueberryentity_id: TNdMrOCMHrQc_UtvCbTC5name: My Segment