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
[serdes] NativeQuerySnippet collection_id should not prevent export (#63870)
Oleksandr Solovyov21956d6ab78d
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.cljindex 6e004388c61..c359d2f9045 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj@@ -72,27 +72,28 @@(format "%d: %s" coll-id names))"[no collection]"))-(defn- card-label [card-id]- (let [card (t2/select-one [:model/Card :collection_id :name] :id card-id)]- (format "Card %d (%s from collection %s)" card-id (:name card) (collection-label (:collection_id card)))))+(defn- entity-label [{:keys [model id]}]+ (let [entity (t2/select-one [model :collection_id :name] :id id)]+ (format "%s %d (%s from collection %s)" (name model) id (:name entity) (collection-label (:collection_id entity)))))(defn- parse-target [[model-name id :as target]](if (string? id)[model-name (serdes/eid->id model-name id)]target))-(defn- escape-analysis [{colls "Collection" cards "Card"} nodes]+(defn- escape-analysis [{colls "Collection" cards "Card" :as _by-model} nodes](log/tracef "Running escape analysis for %d colls and %d cards" (count colls) (count cards))(when-let [colls (-> colls set not-empty)]- (let [known-cards (t2/select-pks-set :model/Card {:where [:or- [:in :collection_id colls]- (when (contains? colls nil)- [:= :collection_id nil])]})- escaped (->> (set/difference (set cards) known-cards)- (mapv (fn [id]- (-> (get nodes ["Card" id])- (assoc :escapee id)))))]- escaped)))+ (let [clause {:where [:or+ [:in :collection_id colls]+ (when (contains? colls nil)+ [:= :collection_id nil])]}+ possible-pks (t2/select-pks-set :model/Card clause)]+ (->> (set/difference (set cards) possible-pks)+ (mapv (fn [id]+ (-> (get nodes ["Card" id])+ (assoc :escapee {:model :model/Card+ :id id}))))))))(defn- log-escape-report! [escaped](let [dashboards (group-by #(get % "Dashboard") escaped)]@@ -100,15 +101,28 @@(log/warnf "Failed to export Dashboard %d (%s) containing Card saved outside requested collections: %s"dash-id(t2/select-one-fn :name :model/Dashboard :id dash-id)- (str/join ", " (map #(card-label (:escapee %)) escapes))))+ (str/join ", " (map #(entity-label (:escapee %)) escapes))))(when-let [other (not-empty (get dashboards nil))](log/warnf "Failed to export Cards based on questions outside requested collections: %s"(str/join ", " (for [item other](format "%s -> %s"(if (get item "Card")- (card-label (get item "Card"))+ (entity-label {:model :model/Card :id (get item "Card")})(dissoc item :escapee))- (card-label (:escapee item)))))))))+ (entity-label (:escapee item)))))))))++(defn- resolve-targets+ "Returns all targets (for either supplied initial `targets` or for supplied `user-id`)."+ [targets user-id]+ (let [initial-targets (if (seq targets)+ (mapv parse-target targets)+ (mapv vector (repeat "Collection") (collection-set-for-user user-id)))+ ;; a map of `{[model-name id] {source-model source-id ...}}`+ targets (u/traverse initial-targets #(serdes/descendants (first %) (second %)))]+ ;; due to traverse argument we'd lose original source entities, lets track them+ (merge-with into+ targets+ (u/traverse (map key targets) #(serdes/required (first %) (second %))))))(defn- extract-subtrees"Extracts the targeted entities and all their descendants into a reducible stream of extracted maps.@@ -125,16 +139,10 @@`opts` are passed down to [[serdes/extract-all]] for each model."[{:keys [targets user-id] :as opts}](log/tracef "Extracting subtrees with options: %s" (pr-str opts))- (let [inner-targets (if (seq targets)- (mapv parse-target targets)- (mapv vector (repeat "Collection") (collection-set-for-user user-id)))- ;; nodes are a map of `{[model-name id] {dep-model dep-id ...}}`- nodes (set/union- (u/traverse inner-targets #(serdes/ascendants (first %) (second %)))- (u/traverse inner-targets #(serdes/descendants (first %) (second %))))+ (let [nodes (resolve-targets targets user-id);; by model is a map of `{model-name [ids ...]}`- by-model (u/group-by first second (keys nodes))- escaped (escape-analysis by-model nodes)]+ by-model (u/group-by first second (keys nodes))+ escaped (escape-analysis by-model nodes)](if (seq escaped)(log-escape-report! escaped)(let [models (model-set opts)diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/storage.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/storage.cljindex 8ac9aba6316..d79c31dba64 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/storage.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/storage.clj@@ -4,7 +4,10 @@[clojure.string :as str][metabase-enterprise.serialization.dump :refer [spit-yaml!]][metabase.models.serialization :as serdes]- [metabase.util.log :as log]))+ [metabase.util.log :as log])+ (:import+ [java.io File]+ [java.nio.file Path]))(set! *warn-on-reflection* true)@@ -16,8 +19,7 @@(str/replace "/" "__SLASH__")(str/replace "\\" "__BACKSLASH__")))-(defn- file- [ctx entity]+(defn- file ^File [ctx entity](let [;; Get the desired [[serdes/storage-path]].base-path (serdes/storage-path entity ctx)dirnames (drop-last base-path)@@ -26,9 +28,12 @@(apply io/file (:root-dir ctx) (map escape-segment (concat dirnames [basename])))))(defn- store-entity! [opts entity]- (log/info "Storing" {:path (serdes/log-path-str (:serdes/meta entity))})- (spit-yaml! (file opts entity) entity)- (:serdes/meta entity))+ (let [f (file opts entity)]+ (log/info "Storing" {:path (serdes/log-path-str (:serdes/meta entity))+ :file (str (.relativize (Path/of (str (:root-dir opts)) (make-array String 0))+ (.toPath f)))})+ (spit-yaml! f entity)+ (:serdes/meta entity)))(defn- store-settings! [{:keys [root-dir]} settings](when (seq settings)diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.cljindex a156418dac7..9e58e0a7e06 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj@@ -12,6 +12,7 @@[metabase.core.core :as mbc][metabase.models.serialization :as serdes][metabase.query-processor :as qp]+ [metabase.search.test-util :as search.tu][metabase.test :as mt][metabase.util :as u][metabase.util.json :as json]@@ -21,6 +22,8 @@;; Use this spell in your test body to add the given fixtures to the round trip baseline.(round-trip-test/add-to-baseline!))+(use-fixtures :each (fn [f] (search.tu/with-index-disabled (f))))+(defn- by-model [model-name extraction](->> extraction(into [])@@ -676,37 +679,42 @@(deftest native-query-snippets-test(mt/with-empty-h2-app-db!- (ts/with-temp-dpc [:model/User- {ann-id :id}- {:first_name "Ann"- :last_name "Wilson"- :email "[email protected]"}-- :model/Collection- {coll-id :id- coll-eid :entity_id}- {:name "Shared Collection"- :personal_owner_id nil- :namespace :snippets}-- :model/NativeQuerySnippet- {s1-id :id- s1-eid :entity_id}- {:name "Snippet 1"- :collection_id coll-id- :creator_id ann-id}-- :model/NativeQuerySnippet- {s2-id :id- s2-eid :entity_id}- {:name "Snippet 2"- :collection_id nil- :creator_id ann-id}]+ (ts/with-temp-dpc [:model/User {ann-id :id} {:first_name "Ann"+ :last_name "Wilson"+ :email "[email protected]"}+ :model/Collection {coll-id :id+ coll-eid :entity_id} {:name "Shared Collection"+ :personal_owner_id nil+ :namespace :snippets}+ :model/Collection {coll2-id :id} {:name "Card Collection"+ :personal_owner_id nil}+ :model/NativeQuerySnippet {s1-id :id+ s1-eid :entity_id} {:name "Snippet 1"+ :collection_id coll-id+ :creator_id ann-id}++ :model/NativeQuerySnippet {s2-id :id+ s2-eid :entity_id} {:name "Snippet 2"+ :collection_id nil+ :creator_id ann-id}+ :model/Card {card-id :id} {:name "Card using Snippet 1"+ :creator_id ann-id+ :collection_id coll2-id+ :dataset_query+ (mt/native-query+ {:query "select {{snippet}}"+ :template-tags {"snippet"+ {:display-name "Snippet 1",+ :id s1-eid,+ :name "snippet 1",+ :snippet-id s1-id,+ :snippet-name "snip",+ :type "snippet"}}})}](testing "native query snippets"(testing "can belong to :snippets collections"(let [ser (serdes/extract-one "NativeQuerySnippet" {} (t2/select-one :model/NativeQuerySnippet :id s1-id))](is (=? {:serdes/meta [{:model "NativeQuerySnippet"- :id s1-eid+ :id s1-eid:label "snippet_1"}]:collection_id coll-eid:creator_id "[email protected]"@@ -716,7 +724,11 @@(testing "and depend on the Collection"(is (= #{[{:model "Collection" :id coll-eid}]}- (set (serdes/dependencies ser)))))))+ (set (serdes/dependencies ser)))))++ (testing "and will bring collection to extraction"+ (is (= {["Collection" coll-id] {"NativeQuerySnippet" s1-id}}+ (serdes/required "NativeQuerySnippet" s1-id))))))(testing "or can be outside collections"(let [ser (serdes/extract-one "NativeQuerySnippet" {} (t2/select-one :model/NativeQuerySnippet :id s2-id))]@@ -731,7 +743,14 @@(is (not (contains? ser :id)))(testing "and has no deps"- (is (empty? (serdes/dependencies ser))))))))))+ (is (empty? (serdes/dependencies ser))))))++ (testing "Snippet collection is exported when snippet is exported as a card dep (#51901)"+ (is (= {["Collection" coll2-id] nil+ ["Card" card-id] {"Collection" coll2-id}+ ["NativeQuerySnippet" s1-id] {"Card" card-id}+ ["Collection" coll-id] {"NativeQuerySnippet" s1-id}}+ (#'extract/resolve-targets [["Collection" coll2-id]] nil))))))))(deftest timelines-and-events-test(mt/with-empty-h2-app-db!@@ -1307,8 +1326,7 @@(testing "selecting a collection includes settings metabot and data model by default"(is (= #{"Card" "Collection" "Dashboard" "Database" "Setting" "TransformTag" "TransformJob"}- (->> {:targets [["Collection" coll1-id]]}- extract/extract+ (->> (extract/extract {:targets [["Collection" coll1-id]]})(map (comp :model first serdes/path))set))))diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex 777540cb978..401ce5b60c1 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -1469,12 +1469,13 @@(defmethod serdes/generate-path "Collection" [_ coll](serdes/maybe-labeled "Collection" coll :slug))-(defmethod serdes/ascendants "Collection" [_ id]+(defmethod serdes/required "Collection" [_ id](when id- (let [{:keys [location]} (t2/select-one :model/Collection :id id)]- ;; it would work returning just one, but why not return all if it's cheap- (into {} (for [parent-id (location-path->ids location)]- {["Collection" parent-id] {"Collection" id}})))))+ (let [{:keys [location]} (t2/select-one :model/Collection :id id)+ path (location-path->ids location)]+ ;; we'll recurse anyway, so just return immediate parent+ (when (seq path)+ {["Collection" (u/last path)] {"Collection" id}}))))(defmethod serdes/descendants "Collection" [_model-name id](let [location (when id (t2/select-one-fn :location :model/Collection :id id))diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.cljindex aa02e52e420..cd9307dfc4b 100644--- a/src/metabase/models/serialization.clj+++ b/src/metabase/models/serialization.clj@@ -525,8 +525,6 @@(eduction (map (partial log-and-extract-one model opts))(extract-query model opts)))-(declare extract-query)-(defn- transform->nested [transform opts batch](let [backward-fk (:backward-fk transform)entities (-> (extract-query (name (:model transform))@@ -556,7 +554,7 @@collection."[model {:keys [collection-set where] :as opts}](let [spec (make-spec (name model) opts)]- (if (or (nil? collection-set)+ (if (or (empty? collection-set)(nil? (-> spec :transform :collection_id)));; either no collections specified or our model has no collection(t2/reducible-select model {:where (or where true)})@@ -578,6 +576,8 @@"Returns map of `{[model-name database-id] {initiating-model id}}` for all entities contained or used by thisentity. e.g. the Dashboard implementation should return pairs for all DashboardCard entities it contains, etc.+ NOTE: This is called during **EXPORT**.+Dispatched on model-name."{:arglists '([model-name db-id])}(fn [model-name _] model-name))@@ -585,16 +585,18 @@(defmethod descendants :default [_ _]nil)-(defmulti ascendants- "Return map of `{[model-name database-id] {initiating-model id}}` for all entities containing this entity, required- to successfully load this entity in destination db. Notice that ascendants are searched recursively, but their- descendants are not analyzed.+(defmulti required+ "Returns map of `{[model-name database-id] {initiating-model id}}` for all entities that are necessary to load this+ entity back. Sort of reverse method for `dependencies`. This method will be called after determining all+ `descendants` to figure out if we're lacking containers etc.++ NOTE: This is called during **EXPORT**.- Dispatched on model-name."+ Dispatched on model-name."{:arglists '([model-name db-id])}(fn [model-name _] model-name))-(defmethod ascendants :default [_ _]+(defmethod required :default [_ _]nil);;; # Import Process@@ -694,13 +696,15 @@"Given an entity map as ingested (not a Toucan entity) returns a (possibly empty) list of its dependencies, where eachdependency is represented by its abstract path (its `:serdes/meta` value).+ NOTE: This is called during **LOAD**.+Keyed on the model name for this entity.- Default implementation returns an empty vector, so only models that have dependencies need to implement this."+ Default implementation returns `nil`, so only models that have dependencies need to implement this."{:arglists '([ingested])}ingested-model)(defmethod dependencies :default [_]- [])+ nil)(defmulti load-update!"Called by the default [[load-one!]] if there is a corresponding entity already in the appdb.diff --git a/src/metabase/native_query_snippets/models/native_query_snippet.clj b/src/metabase/native_query_snippets/models/native_query_snippet.cljindex 69c5c136cf6..abb821a52fe 100644--- a/src/metabase/native_query_snippets/models/native_query_snippet.clj+++ b/src/metabase/native_query_snippets/models/native_query_snippet.clj@@ -1,5 +1,6 @@(ns metabase.native-query-snippets.models.native-query-snippet(:require+ [honey.sql.helpers :as sql.helpers][metabase.collections.models.collection :as collection][metabase.lib.core :as lib][metabase.lib.normalize :as lib.normalize]@@ -110,8 +111,15 @@;;; ------------------------------------------------- Serialization ---------------------------------------------------(defmethod serdes/extract-query "NativeQuerySnippet" [_ opts]- (serdes/extract-query-collections :model/NativeQuerySnippet opts))+(defmethod serdes/extract-query "NativeQuerySnippet" [_ {:keys [collection-set where]}]+ ;; NativeQuerySnippets leave in their own special collections, so the logic is the following:+ ;; - you either are exporting one of those+ ;; - or it was requested as a dependency of some Card, so export it regardless of collection+ (t2/reducible-select :model/NativeQuerySnippet (cond-> {:where [:or+ [:in :collection_id (remove nil? collection-set)]+ (when (some nil? collection-set)+ [:= :collection_id nil])]}+ where (sql.helpers/where :or where))))(defmethod serdes/make-spec "NativeQuerySnippet" [_model-name _opts]{:copy [:archived :content :description :entity_id :name :template_tags]@@ -119,11 +127,15 @@:collection_id (serdes/fk :model/Collection):creator_id (serdes/fk :model/User)}})+(defmethod serdes/required "NativeQuerySnippet"+ [_model id]+ (when-let [collection_id (t2/select-one-fn :collection_id :model/NativeQuerySnippet :id id)]+ {["Collection" collection_id] {"NativeQuerySnippet" id}}))+(defmethod serdes/dependencies "NativeQuerySnippet"[{:keys [collection_id]}]- (if collection_id- [[{:model "Collection" :id collection_id}]]- []))+ (when collection_id+ [[{:model "Collection" :id collection_id}]]))(defmethod serdes/storage-path "NativeQuerySnippet" [snippet ctx];; Intended path here is ["snippets" "<nested ... collections>" "<snippet_eid_and_slug>"]diff --git a/src/metabase/util.cljc b/src/metabase/util.cljcindex c4c96c01871..aa7124499f2 100644--- a/src/metabase/util.cljc+++ b/src/metabase/util.cljc@@ -970,8 +970,11 @@(let [item (first to-traverse)found (traverse-fn (key item))traversed (conj traversed item)- to-traverse (into (dissoc to-traverse (key item))- (apply dissoc found (keys traversed)))]+ ;; `merge-with into` allows us to not lose dependency info if an entity was required from a few different+ ;; locations+ to-traverse (merge-with into+ (dissoc to-traverse (key item))+ (apply dissoc found (keys traversed)))](if (empty? to-traverse)traversed(recur to-traverse traversed)))))diff --git a/test/metabase/util_test.cljc b/test/metabase/util_test.cljcindex 677892a8a8d..15b6e73a5c0 100644--- a/test/metabase/util_test.cljc+++ b/test/metabase/util_test.cljc@@ -535,6 +535,20 @@[1 2] true[1 2 1] false))+(deftest ^:parallel traverse-test+ (testing "u/traverse tracks deps correctly"+ (let [graph {:a [:b :d]+ :b [:c :d]+ :c nil+ :d [:e]+ :e nil}]+ (is (= {:a nil+ :b #{:a}+ :c #{:b}+ :d #{:a :b}+ :e #{:d}}+ (u/traverse [:a] #(zipmap (get graph %) (repeat #{%}))))))))+(deftest ^:parallel round-to-decimals-test(are [decimal-place expected] (= expected(u/round-to-decimals decimal-place 1250.04253))