Skip to content

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

20.2 KB
Raw Blame
(ns metabase-enterprise.dependencies.models.dependency-test
  {:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase-enterprise.dependencies.models.dependency-test]}}}}}}
  (:require
   [clojure.set :as set]
   [clojure.test :refer [deftest is testing]]
   [metabase-enterprise.dependencies.models.dependency :as deps.graph]
   [metabase-enterprise.dependencies.test-util :as deps.test]
   [metabase.graph.core :as graph]
   [metabase.lib.core :as lib]
   [metabase.lib.metadata :as lib.metadata]
   [metabase.queries.models.card :as card]
   [metabase.test :as mt]
   [toucan2.core :as t2]))

(defn- depends-on-> [from-type from-id to-type to-id]
  {:from_entity_type from-type
   :from_entity_id   from-id
   :to_entity_type   to-type
   :to_entity_id     to-id})

(defn- upstream-of [from-type from-id]
  (t2/select-fn-set #(select-keys % [:from_entity_type :from_entity_id :to_entity_type :to_entity_id])
                    :model/Dependency :from_entity_type from-type :from_entity_id from-id))

(defn basic-orders
  "Construct a basic card for dependency testing."
  []
  {:name                   "Test card"
   :database_id            (mt/id)
   :table_id               (mt/id :orders)
   :display                :table
   :query_type             :query
   :type                   :question
   :dataset_query          (mt/mbql-query orders)
   :visualization_settings {}})

(defn wrap-card
  "Construct a card depending on `inner-card` for dependency testing."
  [inner-card]
  {:name                   "Downstream card"
   :database_id            (mt/id)
   :display                :table
   :query_type             :query
   :type                   :question
   :dataset_query          (mt/mbql-query nil
                             {:source-table (str "card__" (:id inner-card))})
   :visualization_settings {}})

(deftest ^:synchronized card-deps-maintenance-test-1-new-card
  (testing "upstream deps of a card are updated correctly"
    (mt/test-helpers-set-global-values!
      (mt/dataset test-data
        (mt/with-temp [:model/User user {:email "[email protected]"}]
          (mt/with-premium-features #{:dependencies}
            (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
              (let [card1 (card/create-card! (basic-orders) user)]
                (deps.test/synchronously-run-dependency-job!)
                (is (integer? (:id card1)))
                (testing "when creating a new card"
                  (is (=? #{(depends-on-> :card (:id card1) :table (mt/id :orders))}
                          (upstream-of :card (:id card1))))
                  (testing "that depends on another card"
                    (let [card2 (card/create-card! (wrap-card card1) user)]
                      (deps.test/synchronously-run-dependency-job!)
                      (is (=? #{(depends-on-> :card (:id card2) :card (:id card1))}
                              (upstream-of :card (:id card2))))
                      (testing "but that doesn't affect the upstream deps of the inner card"
                        (is (=? #{(depends-on-> :card (:id card1) :table (mt/id :orders))}
                                (upstream-of :card (:id card1))))))))
                (testing "when updating an existing card"
                  (testing "to add a new table dep"
                    (card/update-card! {:card-before-update card1
                                        :card-updates
                                        {:dataset_query (mt/mbql-query orders
                                                          {:joins [{:alias "Products"
                                                                    :source-table (mt/id :products)
                                                                    :condition [:= $id &Products.$products.id]}]})}})
                    (deps.test/synchronously-run-dependency-job!)
                    (is (=? #{(depends-on-> :card (:id card1) :table (mt/id :orders))
                              (depends-on-> :card (:id card1) :table (mt/id :products))}
                            (upstream-of :card (:id card1)))))
                  (testing "to remove a table dep"
                    (card/update-card! {:card-before-update (t2/select-one :model/Card :id (:id card1))
                                        :card-updates
                                        {:dataset_query (mt/mbql-query products)}})
                    (deps.test/synchronously-run-dependency-job!)
                    (is (=? #{(depends-on-> :card (:id card1) :table (mt/id :products))}
                            (upstream-of :card (:id card1))))))))))))))

(deftest ^:synchronized card-deps-graph-test-1-mbql-card-chain
  (testing "deps graph is connected properly for a chain of MBQL cards"
    (mt/dataset test-data
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-premium-features #{:dependencies}
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
            (let [{id1 :id :as card1} (card/create-card! (basic-orders) user)
                  {id2 :id :as card2} (card/create-card! (wrap-card card1) user)
                  {id3 :id :as card3} (card/create-card! (wrap-card card2) user)]
              (deps.test/synchronously-run-dependency-job!)
              (testing "raw deps are recorded correctly"
                (is (=? #{(depends-on-> :card id1 :table (mt/id :orders))} (upstream-of :card id1)))
                (is (=? #{(depends-on-> :card id2 :card id1)} (upstream-of :card id2)))
                (is (=? #{(depends-on-> :card id3 :card id2)} (upstream-of :card id3))))
              (testing "transitive deps are computed correctly"
                (testing "for each card"
                  (is (=? {:card #{id2 id3}}
                          (deps.graph/transitive-dependents {:card [card1]})))
                  (is (=? {:card #{id3}}
                          (deps.graph/transitive-dependents {:card [card2]})))
                  (is (=? {}
                          (deps.graph/transitive-dependents {:card [card3]}))))
                (testing "for the table"
                  (is (set/subset? #{id1 id2 id3}
                                   (-> {:table [{:id (mt/id :orders)}]}
                                       deps.graph/transitive-dependents
                                       :card))))))))))))

(defn- sql-card [metadata-provider sql]
  {:name                   "SQL card"
   :database_id            (mt/id)
   :display                :table
   :query_type             :query
   :type                   :question
   :dataset_query          (-> (lib/native-query metadata-provider sql)
                               lib/->legacy-MBQL)
   :visualization_settings {}})

(deftest ^:synchronized card-deps-graph-test-2-native-card-chain
  (testing "deps graph is connected properly for a chain of native cards"
    (mt/dataset test-data
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-premium-features #{:dependencies}
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
            (let [mp (mt/metadata-provider)
                  {id1 :id :as card1} (card/create-card! (sql-card mp "SELECT * FROM orders;") user)
                  {id2 :id :as card2} (card/create-card! (sql-card mp (str "SELECT * FROM {{#" id1 "}}")) user)
                  {id3 :id :as card3} (card/create-card! (sql-card mp (str "SELECT * FROM {{#" id2 "}}")) user)]
              (deps.test/synchronously-run-dependency-job!)
              (testing "raw deps are recorded correctly"
                (is (=? #{(depends-on-> :card id1 :table (mt/id :orders))} (upstream-of :card id1)))
                (is (=? #{(depends-on-> :card id2 :card id1)} (upstream-of :card id2)))
                (is (=? #{(depends-on-> :card id3 :card id2)} (upstream-of :card id3))))
              (testing "transitive deps are computed correctly"
                (testing "for each card"
                  (is (=? {:card #{id2 id3}}
                          (deps.graph/transitive-dependents {:card [card1]})))
                  (is (=? {:card #{id3}}
                          (deps.graph/transitive-dependents {:card [card2]})))
                  (is (=? {}
                          (deps.graph/transitive-dependents {:card [card3]}))))
                (testing "for the table"
                  (is (set/subset? #{id1 id2 id3}
                                   (-> {:table [{:id (mt/id :orders)}]}
                                       deps.graph/transitive-dependents
                                       :card))))))))))))

(deftest ^:synchronized card-deps-graph-metric-test
  (testing "deps graph is connected properly for a question using a metric"
    (mt/dataset test-data
      (mt/with-temp [:model/User user {:email "[email protected]"}]
        (mt/with-premium-features #{:dependencies}
          (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
            (let [metric-card (card/create-card! {:name "Test Metric"
                                                  :database_id (mt/id)
                                                  :table_id (mt/id :orders)
                                                  :display :scalar
                                                  :query_type :query
                                                  :type :metric
                                                  :dataset_query (mt/mbql-query orders {:aggregation [[:count]]})
                                                  :visualization_settings {}}
                                                 user)
                  question-card (card/create-card! {:name "Question using Metric"
                                                    :database_id (mt/id)
                                                    :display :table
                                                    :query_type :query
                                                    :type :question
                                                    :dataset_query (mt/mbql-query orders
                                                                     {:aggregation [[:metric (:id metric-card)]]})
                                                    :visualization_settings {}}
                                                   user)]
              (deps.test/synchronously-run-dependency-job!)
              (testing "raw deps are recorded correctly for question using metric"
                (is (=? #{(depends-on-> :card (:id question-card) :table (mt/id :orders))
                          (depends-on-> :card (:id question-card) :card (:id metric-card))}
                        (upstream-of :card (:id question-card))))))))))))

(def ^:private pending? deps.test/dependency-pending?)

(def ^:private computed! deps.test/record-dependencies-computed!)

(deftest ^:synchronized dependency-status-marks-test
  (testing "updating what the dependency job reads of an entity marks its status stale, and creating one writes no
           status"
    (mt/test-helpers-set-global-values!
      (mt/with-model-cleanup [:model/DependencyStatus :model/Dependency]
        (mt/with-premium-features #{:dependencies}
          (testing "cards"
            (mt/with-temp [:model/Card card {}]
              (is (not (t2/exists? :model/DependencyStatus :entity_type :card :entity_id (:id card))))
              (computed! :card (:id card))
              (card/update-card! {:card-before-update card
                                  :card-updates       {:dataset_query (mt/mbql-query orders)}})
              (is (pending? :card (:id card)))))
          (testing "transforms"
            (mt/with-temp [:model/Transform transform]
              (is (not (t2/exists? :model/DependencyStatus :entity_type :transform :entity_id (:id transform))))
              (computed! :transform (:id transform))
              (t2/update! :model/Transform :id (:id transform) {:source {:type :query :query (lib/query (mt/metadata-provider) (lib.metadata/table (mt/metadata-provider) (mt/id :products)))}})
              (is (pending? :transform (:id transform)))))
          (testing "snippets"
            (mt/with-temp [:model/NativeQuerySnippet snippet]
              (is (not (t2/exists? :model/DependencyStatus :entity_type :snippet :entity_id (:id snippet))))
              (computed! :snippet (:id snippet))
              (t2/update! :model/NativeQuerySnippet :id (:id snippet) {:content "new content"})
              (is (pending? :snippet (:id snippet))))))))))

(deftest dependency-status-absent-until-backfill-on-card-create-test
  (testing "a created card has no dependency_status row until the dependency job processes it"
    (mt/with-premium-features #{:dependencies}
      (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
        (mt/with-temp [:model/User user]
          (let [card (card/create-card! (basic-orders) user)]
            (is (not (t2/exists? :model/DependencyStatus :entity_type :card :entity_id (:id card))))
            (deps.test/synchronously-run-dependency-job!)
            (is (t2/exists? :model/DependencyStatus :entity_type :card :entity_id (:id card)))
            (is (not (pending? :card (:id card))))))))))

(deftest filtered-graph-dependencies-test
  (testing "filtered-graph-dependencies respects filter clause"
    (mt/with-temp [:model/User user {:email "[email protected]"}]
      (mt/with-premium-features #{:dependencies}
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
          (let [{id1 :id :as card1} (card/create-card! (basic-orders) user)
                {id2 :id :as card2} (card/create-card! (wrap-card card1) user)
                {id3 :id :as _card3} (card/create-card! (wrap-card card2) user)]
            (deps.test/synchronously-run-dependency-job!)
            (testing "without filter, returns all dependencies"
              (let [graph (deps.graph/graph-dependencies)
                    deps (graph/transitive graph [[:card id3]])]
                (is (= #{[:card id2] [:card id1] [:table (mt/id :orders)]}
                       (set deps)))))
            (testing "with filter excluding card1, omits card1 and its dependencies"
              (let [graph (deps.graph/filtered-graph-dependencies {:entity-type :card :ids [id2 id3]})
                    deps (graph/transitive graph [[:card id3]])]
                (is (= #{[:card id2]}
                       (set deps))
                    "Should only include card2, not card1 or table")))
            (testing "with filter excluding card2, breaks the chain"
              (let [graph (deps.graph/filtered-graph-dependencies {:entity-type :card :ids [id1 id3]})
                    deps (graph/transitive graph [[:card id3]])]
                (is (= #{}
                       (set deps))
                    "Should be empty, chain is broken at card2")))))))))

(deftest filtered-graph-dependents-test
  (testing "filtered-graph-dependents respects filter clause"
    (mt/with-temp [:model/User user {:email "[email protected]"}]
      (mt/with-premium-features #{:dependencies}
        (mt/with-model-cleanup [:model/Card :model/Dependency :model/DependencyStatus]
          (let [{id1 :id :as card1} (card/create-card! (basic-orders) user)
                {id2 :id :as card2} (card/create-card! (wrap-card card1) user)
                {id3 :id :as _card3} (card/create-card! (wrap-card card2) user)]
            (deps.test/synchronously-run-dependency-job!)
            (testing "without filter, returns all dependents"
              (let [graph (deps.graph/graph-dependents)
                    deps (graph/transitive graph [[:card id1]])]
                (is (= #{[:card id2] [:card id3]}
                       (set deps)))))
            (testing "with filter excluding card3, omits card3"
              (let [graph (deps.graph/filtered-graph-dependents {:entity-type :card :ids [id1 id2]})
                    deps (graph/transitive graph [[:card id1]])]
                (is (= #{[:card id2]}
                       (set deps))
                    "Should only include card2, not card3")))
            (testing "with filter excluding card2, breaks the chain"
              (let [graph (deps.graph/filtered-graph-dependents {:entity-type :card :ids [id1 id3]})
                    deps (graph/transitive graph [[:card id1]])]
                (is (= #{}
                       (set deps))
                    "Should be empty, chain is broken at card2")))))))))

(deftest swap-dependency!-test
  (testing "swap-dependency! handles the various cases correctly"
    (mt/with-temp [:model/Card card1 {}
                   :model/Card card2 {}
                   :model/Table table1 {:db_id (mt/id)}
                   :model/Table table2 {:db_id (mt/id)}]
      (mt/with-model-cleanup [:model/Dependency]
        (testing "basic swap - old dep exists, new dep doesn't"
          (t2/insert! :model/Dependency {:from_entity_type :card
                                         :from_entity_id (:id card1)
                                         :to_entity_type :table
                                         :to_entity_id (:id table1)})
          (deps.graph/swap-dependency! :card (:id card1) [:table (:id table1)] [:table (:id table2)])
          (deps.test/synchronously-run-dependency-job!)
          (is (not (t2/exists? :model/Dependency
                               :from_entity_type :card
                               :from_entity_id (:id card1)
                               :to_entity_type :table
                               :to_entity_id (:id table1)))
              "Old dependency should be gone")
          (is (t2/exists? :model/Dependency
                          :from_entity_type :card
                          :from_entity_id (:id card1)
                          :to_entity_type :table
                          :to_entity_id (:id table2))
              "New dependency should exist"))
        (testing "swap when new dep already exists - should just delete old"
          ;; Set up: card2 depends on both table1 and table2
          (t2/insert! :model/Dependency [{:from_entity_type :card
                                          :from_entity_id (:id card2)
                                          :to_entity_type :table
                                          :to_entity_id (:id table1)}
                                         {:from_entity_type :card
                                          :from_entity_id (:id card2)
                                          :to_entity_type :table
                                          :to_entity_id (:id table2)}])
          ;; This would fail with duplicate key error before the fix
          (deps.graph/swap-dependency! :card (:id card2) [:table (:id table1)] [:table (:id table2)])
          (deps.test/synchronously-run-dependency-job!)
          (is (not (t2/exists? :model/Dependency
                               :from_entity_type :card
                               :from_entity_id (:id card2)
                               :to_entity_type :table
                               :to_entity_id (:id table1)))
              "Old dependency should be deleted")
          (is (t2/exists? :model/Dependency
                          :from_entity_type :card
                          :from_entity_id (:id card2)
                          :to_entity_type :table
                          :to_entity_id (:id table2))
              "New dependency should still exist (only one copy)")
          (is (= 1 (t2/count :model/Dependency
                             :from_entity_type :card
                             :from_entity_id (:id card2)
                             :to_entity_type :table
                             :to_entity_id (:id table2)))
              "Should have exactly one dependency to table2"))))))

(deftest replace-dependencies!-rejects-non-integer-ids-test
  (testing "a non-integer to-entity-id is rejected before it is inserted"
    (is (thrown-with-msg?
         clojure.lang.ExceptionInfo #"must be a positive integer"
         (deps.graph/replace-dependencies! "document" 1 {"card" #{{:raw "x"}}}))))
  (testing "legitimate integer ids are accepted and inserted"
    (mt/with-temp [:model/Card card {}]
      (mt/with-model-cleanup [:model/Dependency]
        (deps.graph/replace-dependencies! "card" (:id card) {"card" #{(:id card)}})
        (is (pos? (t2/count :model/Dependency
                            :from_entity_type "card"
                            :from_entity_id (:id card))))))))