Skip to content

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

Include segments in dependencies graph (#66264)

Riley Thompson7a98f93ad77c
diff --git a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
index 9709569aa99..d1d9cc7f485 100644
--- a/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
+++ b/e2e/test/scenarios/dependencies/dependency-graph.cy.spec.ts
@@ -15,6 +15,7 @@ import type {
DependencyId,
DependencyType,
NativeQuerySnippetId,
+ SegmentId,
TableId,
TransformId,
} from "metabase-types/api";
@@ -43,6 +44,11 @@ const SNIPPET_BASED_QUESTION_NAME = "Snippet-based question";
const SNIPPET_BASED_MODEL_NAME = "Snippet-based model";
const SNIPPET_BASED_TRANSFORM_NAME = "Snippet-based transform";
const SNIPPET_BASED_SNIPPET_NAME = "Snippet-based snippet";
+const TABLE_BASED_SEGMENT_NAME = "Table-based segment";
+const SEGMENT_BASED_QUESTION_NAME = "Segment-based question";
+const SEGMENT_BASED_MODEL_NAME = "Segment-based model";
+const SEGMENT_BASED_METRIC_NAME = "Segment-based metric";
+const SEGMENT_BASED_SEGMENT_NAME = "Segment-based segment";
describe("scenarios > dependencies > dependency graph", () => {
beforeEach(() => {
@@ -248,6 +254,7 @@ describe("scenarios > dependencies > dependency graph", () => {
createTableBasedModel({ tableId });
createTableBasedMetric({ tableId });
createTableBasedTransform({ tableName: TABLE_NAME });
+ createTableBasedSegment({ tableId });
visitGraphForEntity(tableId, "table");
});
verifyPanelNavigation({
@@ -270,6 +277,43 @@ describe("scenarios > dependencies > dependency graph", () => {
groupTitle: "1 transform",
dependentItemTitle: TABLE_BASED_TRANSFORM_NAME,
});
+ verifyPanelNavigation({
+ itemTitle: TABLE_DISPLAY_NAME,
+ groupTitle: "1 segment",
+ dependentItemTitle: TABLE_BASED_SEGMENT_NAME,
+ });
+ });
+
+ it("should display dependencies for a segment and navigate to them", () => {
+ getScoreboardTableId().then((tableId) =>
+ createTableBasedSegment({ tableId }).then(({ body: segment }) => {
+ createSegmentBasedQuestion({ tableId, segmentId: segment.id });
+ createSegmentBasedModel({ tableId, segmentId: segment.id });
+ createSegmentBasedMetric({ tableId, segmentId: segment.id });
+ createSegmentBasedSegment({ tableId, segmentId: segment.id });
+ visitGraphForEntity(segment.id, "segment");
+ }),
+ );
+ verifyPanelNavigation({
+ itemTitle: TABLE_BASED_SEGMENT_NAME,
+ groupTitle: "1 question",
+ dependentItemTitle: SEGMENT_BASED_QUESTION_NAME,
+ });
+ verifyPanelNavigation({
+ itemTitle: TABLE_BASED_SEGMENT_NAME,
+ groupTitle: "1 model",
+ dependentItemTitle: SEGMENT_BASED_MODEL_NAME,
+ });
+ verifyPanelNavigation({
+ itemTitle: TABLE_BASED_SEGMENT_NAME,
+ groupTitle: "1 metric",
+ dependentItemTitle: SEGMENT_BASED_METRIC_NAME,
+ });
+ verifyPanelNavigation({
+ itemTitle: TABLE_BASED_SEGMENT_NAME,
+ groupTitle: "1 segment",
+ dependentItemTitle: SEGMENT_BASED_SEGMENT_NAME,
+ });
});
it("should display dependencies for a question and navigate to them", () => {
@@ -955,3 +999,101 @@ function createSnippetBasedSnippet({ snippetName }: { snippetName: string }) {
content: `{{snippet:${snippetName}}}`,
});
}
+
+function createTableBasedSegment({ tableId }: { tableId: TableId }) {
+ return H.createSegment({
+ name: TABLE_BASED_SEGMENT_NAME,
+ description: "Segment description",
+ table_id: tableId,
+ definition: {
+ "source-table": tableId,
+ filter: ["=", 1, 1],
+ },
+ });
+}
+
+function createSegmentBasedSegment({
+ tableId,
+ segmentId,
+}: {
+ tableId: TableId;
+ segmentId: SegmentId;
+}) {
+ return H.createSegment({
+ name: SEGMENT_BASED_SEGMENT_NAME,
+ description: "Segment description",
+ table_id: tableId,
+ definition: {
+ "source-table": tableId,
+ filter: ["segment", segmentId],
+ },
+ });
+}
+
+function createSegmentBasedCard({
+ name,
+ type,
+ tableId,
+ segmentId,
+}: {
+ name: string;
+ type: CardType;
+ tableId: TableId;
+ segmentId: SegmentId;
+}) {
+ return H.createQuestion({
+ name,
+ type,
+ database: WRITABLE_DB_ID,
+ query: {
+ "source-table": tableId,
+ filter: ["segment", segmentId],
+ aggregation: [["count"]],
+ },
+ });
+}
+
+function createSegmentBasedQuestion({
+ tableId,
+ segmentId,
+}: {
+ tableId: TableId;
+ segmentId: SegmentId;
+}) {
+ return createSegmentBasedCard({
+ name: SEGMENT_BASED_QUESTION_NAME,
+ type: "question",
+ tableId,
+ segmentId,
+ });
+}
+
+function createSegmentBasedModel({
+ tableId,
+ segmentId,
+}: {
+ tableId: TableId;
+ segmentId: SegmentId;
+}) {
+ return createSegmentBasedCard({
+ name: SEGMENT_BASED_MODEL_NAME,
+ type: "model",
+ tableId,
+ segmentId,
+ });
+}
+
+function createSegmentBasedMetric({
+ tableId,
+ segmentId,
+}: {
+ tableId: TableId;
+ segmentId: SegmentId;
+}) {
+ return createSegmentBasedCard({
+ name: SEGMENT_BASED_METRIC_NAME,
+ type: "metric",
+ tableId,
+ segmentId,
+ });
+}
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
index 23bc40b35ac..ff22fac7d11 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj
@@ -167,7 +167,8 @@
:document [:name :description :view_count
:created_at :creator
:collection :collection_id]
- :sandbox [:table :table_id]})
+ :sandbox [:table :table_id]
+ :segment [:name :description :created_at :creator :creator_id :table :table_id]})
(defn- format-subentity [entity]
(case (t2/model entity)
@@ -189,7 +190,8 @@
:transform :model/Transform
:dashboard :model/Dashboard
:document :model/Document
- :sandbox :model/Sandbox})
+ :sandbox :model/Sandbox
+ :segment :model/Segment})
;; IMPORTANT: This map defines which fields to select when fetching entities for the dependency graph.
;; These field lists MUST be kept in sync with the frontend type definitions in:
@@ -211,7 +213,8 @@
;; :source has to be selected otherwise the BE won't know what DB it belongs to
:source]
:snippet [:id :name :description]
- :sandbox [:id :table_id]})
+ :sandbox [:id :table_id]
+ :segment [:id :name :description :created_at :creator_id :table_id]})
(defn- visible-entities-filter-clause
"Returns a HoneySQL WHERE clause for filtering dependency graph entities by user visibility.
@@ -291,7 +294,33 @@
:exclude [:and
[:= active-column true]
[:= visibility-type-column nil]]
- (:only :all) nil)]}]])))))
+ (:only :all) nil)]}]])
+
+ ;; Segment with table permissions and archived filtering
+ :model/Segment
+ (let [archived-column (keyword (name table-name) "archived")
+ table-id-column (keyword (name table-name) "table_id")]
+ [:and
+ [:= entity-type-field (name entity-type)]
+ [:in entity-id-field {:select [:id]
+ :from [table-name]
+ :where [:and
+ ;; Check that user can see the table this segment belongs to
+ [:in table-id-column
+ {:select [:metabase_table.id]
+ :from [:metabase_table]
+ :where (mi/visible-filter-clause
+ :model/Table
+ :metabase_table.id
+ {:user-id api/*current-user-id*
+ :is-superuser? api/*is-superuser?*}
+ {:perms/view-data :unrestricted
+ :perms/create-queries :query-builder})}]
+ ;; Filter by archived status
+ (case include-archived-items
+ :exclude [:= archived-column false]
+ :only [:= archived-column true]
+ :all nil)]}]])))))
entity-model)))
(defn- readable-graph-dependencies
@@ -349,7 +378,8 @@
(revisions/with-last-edit-info :dashboard))
(= entity-type :document) (-> (t2/hydrate :creator [:collection :is_personal])
(->> (map collection.root/hydrate-root-collection)))
- (= entity-type :sandbox) (t2/hydrate [:table :db :fields]))
+ (= entity-type :sandbox) (t2/hydrate [:table :db :fields])
+ (= entity-type :segment) (t2/hydrate :creator [:table :db]))
(mapv #(entity-value entity-type % usages)))))
nodes-by-type)))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj b/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
index 2802c8e4279..8f4f4594dfe 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/calculation.clj
@@ -14,6 +14,7 @@
(mu/defn- upstream-deps:mbql-query :- ::deps.schema/upstream-deps
[query :- ::lib.schema/query]
{:card (or (lib/all-source-card-ids query) #{})
+ :segment (or (lib/all-segment-ids query) #{})
:table (-> #{}
(into (lib/all-source-table-ids query))
(into (lib/all-implicitly-joined-table-ids query)))})
@@ -130,3 +131,10 @@
(if-let [card-id (:card_id sandbox)]
{:card #{card-id}}
{}))
+
+(mu/defn upstream-deps:segment :- ::deps.schema/upstream-deps
+ "Given a segment, return its upstream dependencies (the table it filters and any segments it references)"
+ [{:keys [table_id definition] :as _segment}]
+ {:segment (or (lib/all-segment-ids definition) #{})
+ :table (cond-> (into #{} (lib/all-implicitly-joined-table-ids definition))
+ table_id (conj table_id))})
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
index 805ab3b3a7a..a451db76611 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj
@@ -223,3 +223,27 @@
[_ {:keys [object]}]
(when (premium-features/has-feature? :dependencies)
(t2/delete! :model/Dependency :from_entity_type :sandbox :from_entity_id (:id object))))
+
+;; ### Segments
+(derive ::segment-deps :metabase/event)
+(derive :event/segment-create ::segment-deps)
+(derive :event/segment-update ::segment-deps)
+
+(methodical/defmethod events/publish-event! ::segment-deps
+ [_ {:keys [object]}]
+ (when (premium-features/has-feature? :dependencies)
+ (t2/with-transaction [_conn]
+ (models.dependency/replace-dependencies! :segment (:id object)
+ (ignore-errors
+ (deps.calculation/upstream-deps:segment object)))
+ (when (not= (:dependency_analysis_version object) models.dependency/current-dependency-analysis-version)
+ (t2/update! :model/Segment (:id object)
+ {:dependency_analysis_version models.dependency/current-dependency-analysis-version})))))
+
+(derive ::segment-delete :metabase/event)
+(derive :event/segment-delete ::segment-delete)
+
+(methodical/defmethod events/publish-event! ::segment-delete
+ [_ {:keys [object]}]
+ (when (premium-features/has-feature? :dependencies)
+ (t2/delete! :model/Dependency :from_entity_type :segment :from_entity_id (:id object))))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj
index f2d96a84e13..001eea42c9d 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_provider.clj
@@ -245,6 +245,11 @@
(defmethod add-override :sandbox [^OverridingMetadataProvider mp _entity-type _id _updates]
mp)
+(defmethod add-override :segment [^OverridingMetadataProvider mp _entity-type id updates]
+ {[:metadata/segment id] (delay (merge (when id
+ (lib.metadata/segment (inner-mp mp) id))
+ updates))})
+
(defn all-overrides
"Returns all the overrides by ID, in the same form as the map input to [[with-deps]]:
`{:card [1 2 3], :transform [45 99]}."
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj
index 1b1341e42f8..55c56c114a7 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj
@@ -11,7 +11,7 @@
(def current-dependency-analysis-version
"Current version of the dependency analysis logic.
This should be incremented when the dependency analysis logic changes."
- 2)
+ 3)
(methodical/defmethod t2/table-name :model/Dependency [_model] :dependency)
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/schema.clj b/enterprise/backend/src/metabase_enterprise/dependencies/schema.clj
index 6772d49e939..5be605e1aa5 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/schema.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/schema.clj
@@ -11,4 +11,5 @@
[:transform {:optional true} [:set ::lib.schema.id/transform]]
[:dashboard {:optional true} [:set ::lib.schema.id/dashboard]]
[:document {:optional true} [:set ::lib.schema.id/document]]
- [:sandbox {:optional true} [:set ::lib.schema.id/sandbox]]])
+ [:sandbox {:optional true} [:set ::lib.schema.id/sandbox]]
+ [:segment {:optional true} [:set ::lib.schema.id/segment]]])
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj b/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj
index 7ad7b6c83ed..da5ce75a83e 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj
@@ -37,7 +37,8 @@
:model/NativeQuerySnippet
:model/Dashboard
:model/Document
- :model/Sandbox])
+ :model/Sandbox
+ :model/Segment])
;; In-memory state for tracking failed entities
;; Stores {:model/Type {id {:fail-count N :next-retry-timestamp M}}}
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
index a548359ba50..faec069bfb4 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/calculation_test.clj
@@ -1,6 +1,6 @@
(ns metabase-enterprise.dependencies.calculation-test
(:require
- [clojure.test :refer [deftest is]]
+ [clojure.test :refer [deftest is testing]]
[metabase-enterprise.dependencies.calculation :as calculation]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
@@ -18,9 +18,11 @@
(lib/filter (lib/= product-category
"Widget")))}]
(is (= {:card #{}
+ :segment #{}
:table #{products-id}}
(calculation/upstream-deps:card prod-card)))
(is (= {:card #{prod-card-id}
+ :segment #{}
:table #{}}
(calculation/upstream-deps:card widget-card))))))
@@ -34,9 +36,11 @@
:model/Card joined-card {:dataset_query (-> (lib/query mp (lib.metadata/card mp products-card-id))
(lib/join orders))}]
(is (= {:card #{}
+ :segment #{}
:table #{products-id}}
(calculation/upstream-deps:card products-card)))
(is (= {:card #{products-card-id}
+ :segment #{}
:table #{orders-id}}
(calculation/upstream-deps:card joined-card))))))
@@ -52,6 +56,7 @@
user-name (lib.tu.notebook/find-col-with-spec base-query visible-cols "User" "Name")]
(mt/with-temp [:model/Card card {:dataset_query (lib/with-fields base-query [venue-name user-name])}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id users-id}}
(calculation/upstream-deps:card card))))))
@@ -65,6 +70,7 @@
venue-name (lib.tu.notebook/find-col-with-spec base-query filterable-cols "Venue" "Name")]
(mt/with-temp [:model/Card card {:dataset_query (lib/filter base-query (lib/= venue-name "Bird's Nest"))}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id}}
(calculation/upstream-deps:card card))))))
@@ -78,6 +84,7 @@
venue-name (lib.tu.notebook/find-col-with-spec base-query breakoutable-cols "Venue" "Name")]
(mt/with-temp [:model/Card card {:dataset_query (lib/breakout base-query venue-name)}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id}}
(calculation/upstream-deps:card card))))))
@@ -91,6 +98,7 @@
venue-price (lib.tu.notebook/find-col-with-spec base-query visible-cols "Venue" "Price")]
(mt/with-temp [:model/Card card {:dataset_query (lib/aggregate base-query (lib/sum venue-price))}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id}}
(calculation/upstream-deps:card card))))))
@@ -104,6 +112,7 @@
venue-name (lib.tu.notebook/find-col-with-spec base-query orderable-cols "Venue" "Name")]
(mt/with-temp [:model/Card card {:dataset_query (lib/order-by base-query venue-name)}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id}}
(calculation/upstream-deps:card card))))))
@@ -125,6 +134,7 @@
:target {:schema "PUBLIC"
:name "test_output"}}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id users-id}}
(calculation/upstream-deps:transform transform)))))))
@@ -146,6 +156,7 @@
:target {:schema "PUBLIC"
:name "test_output"}}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id}}
(calculation/upstream-deps:transform transform)))))))
@@ -166,6 +177,7 @@
:target {:schema "PUBLIC"
:name "test_output"}}]
(is (= {:card #{}
+ :segment #{}
:table #{checkins-id venues-id}}
(calculation/upstream-deps:transform transform)))))))
@@ -195,6 +207,7 @@
:values_source_type "card"
:values_source_config {:card_id category-values-card-id}}]}]
(is (= {:card #{}
+ :segment #{}
:table #{products-id}}
(calculation/upstream-deps:card category-values-card)))
(is (= {:card #{category-values-card-id}
@@ -383,3 +396,79 @@
:card_id sandbox-card-id}]
(is (= {:card #{sandbox-card-id}}
(calculation/upstream-deps:sandbox sandbox))))))
+
+(deftest ^:parallel upstream-deps-segment-test
+ (let [products-id (mt/id :products)
+ price-field-id (mt/id :products :price)
+ category-field-id (mt/id :products :category)]
+ (testing "segment depending only on table"
+ (mt/with-temp [:model/Segment segment {:table_id products-id
+ :definition {:filter [:> [:field price-field-id nil] 50]}}]
+ (is (= {:segment #{} :table #{products-id}}
+ (calculation/upstream-deps:segment segment)))))
+
+ (testing "segment depending on another segment"
+ (mt/with-temp [:model/Segment {segment-a-id :id :as segment-a} {:table_id products-id
+ :definition {:filter [:> [:field price-field-id nil] 50]}}
+ :model/Segment segment-b {:table_id products-id
+ :definition {:filter [:and
+ [:segment segment-a-id]
+ [:= [:field category-field-id nil] "Widget"]]}}]
+ (testing "base segment depends only on table"
+ (is (= {:segment #{} :table #{products-id}}
+ (calculation/upstream-deps:segment segment-a))))
+ (testing "dependent segment depends on both table and segment"
+ (is (= {:table #{products-id}
+ :segment #{segment-a-id}}
+ (calculation/upstream-deps:segment segment-b))))))))
+
+(deftest ^:parallel upstream-deps-card-with-multiple-segments-test
+ (testing "Card using multiple segments depends on all of them"
+ (let [products-id (mt/id :products)
+ price-field-id (mt/id :products :price)
+ category-field-id (mt/id :products :category)]
+ (mt/with-temp [:model/Segment {segment-a-id :id} {:table_id products-id
+ :definition {:filter [:> [:field price-field-id nil] 50]}}
+ :model/Segment {segment-b-id :id} {:table_id products-id
+ :definition {:filter [:= [:field category-field-id nil] "Widget"]}}
+ :model/Card card {:dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table products-id
+ :filter [:and
+ [:segment segment-a-id]
+ [:segment segment-b-id]]}}}]
+ (is (= {:card #{}
+ :table #{products-id}
+ :segment #{segment-a-id segment-b-id}}
+ (calculation/upstream-deps:card card)))))))
+
+(deftest ^:parallel upstream-deps-segment-with-multiple-segments-test
+ (testing "Segment depending on multiple other segments tracks all dependencies"
+ (let [products-id (mt/id :products)
+ price-field-id (mt/id :products :price)
+ category-field-id (mt/id :products :category)
+ rating-field-id (mt/id :products :rating)]
+ (mt/with-temp [:model/Segment {segment-a-id :id} {:table_id products-id
+ :definition {:filter [:> [:field price-field-id nil] 50]}}
+ :model/Segment {segment-b-id :id} {:table_id products-id
+ :definition {:filter [:= [:field category-field-id nil] "Widget"]}}
+ :model/Segment segment-c {:table_id products-id
+ :definition {:filter [:and
+ [:segment segment-a-id]
+ [:segment segment-b-id]
+ [:> [:field rating-field-id nil] 4]]}}]
+ (is (= {:table #{products-id}
+ :segment #{segment-a-id segment-b-id}}
+ (calculation/upstream-deps:segment segment-c)))))))
+
+(deftest ^:parallel upstream-deps-segment-implicit-join-test
+ (testing "Segment depending on implicitly joined field adds dep on that field's table"
+ (let [checkins-id (mt/id :checkins)
+ venues-id (mt/id :venues)
+ venue-fk-field-id (mt/id :checkins :venue_id)
+ venue-name-field-id (mt/id :venues :name)]
+ (mt/with-temp [:model/Segment segment {:table_id checkins-id
+ :definition {:filter [:= [:field venue-name-field-id {:source-field venue-fk-field-id}] "Bird's Nest"]}}]
+ (is (= {:segment #{}
+ :table #{checkins-id venues-id}}
+ (calculation/upstream-deps:segment segment)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
index c9dd1963a90..4083125d700 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj
@@ -376,3 +376,88 @@
(is (= models.dependency/current-dependency-analysis-version
(t2/select-one-fn :dependency_analysis_version :model/Sandbox :id sandbox-id)))
(is (empty? (t2/select :model/Dependency :from_entity_id sandbox-id :from_entity_type :sandbox))))))))))))
+
+(deftest segment-update-sets-correct-dependencies
+ (mt/with-test-user :rasta
+ (let [products-id (mt/id :products)
+ price-field-id (mt/id :products :price)
+ category-field-id (mt/id :products :category)]
+ (mt/with-premium-features #{:dependencies}
+ (mt/with-temp [:model/Segment {segment-id :id :as segment} {:table_id products-id
+ :definition {:filter [:> [:field price-field-id nil] 50]}}]
+ (testing "creating a segment creates dependency to its table"
+ (events/publish-event! :event/segment-create {:object segment :user-id api/*current-user-id*})
+ (is (= #{{:from_entity_type :segment
+ :from_entity_id segment-id
+ :to_entity_type :table
+ :to_entity_id products-id}}
+ (into #{} (map #(dissoc % :id)
+ (t2/select :model/Dependency :from_entity_id segment-id :from_entity_type :segment))))))
+ (testing "updating segment definition recalculates dependencies"
+ (t2/update! :model/Segment segment-id {:definition {:filter [:= [:field category-field-id nil] "Widget"]}})
+ (let [updated-segment (t2/select-one :model/Segment :id segment-id)]
+ (events/publish-event! :event/segment-update {:object updated-segment :user-id api/*current-user-id*})
+ (is (= #{{:from_entity_type :segment
+ :from_entity_id segment-id
+ :to_entity_type :table
+ :to_entity_id products-id}}
+ (into #{} (map #(dissoc % :id)
+ (t2/select :model/Dependency :from_entity_id segment-id :from_entity_type :segment)))))))
+ (testing "deleting segment removes all dependencies"
+ (t2/delete! :model/Segment segment-id)
+ (events/publish-event! :event/segment-delete {:object segment :user-id api/*current-user-id*})
+ (is (empty? (t2/select :model/Dependency :from_entity_id segment-id :from_entity_type :segment)))))))))
+
+(deftest card-with-segment-dependencies
+ (mt/with-test-user :rasta
+ (let [products-id (mt/id :products)
+ price-field-id (mt/id :products :price)]
+ (mt/with-premium-features #{:dependencies}
+ (mt/with-temp [:model/Segment {segment-id :id :as segment} {:table_id products-id
+ :definition {:filter [:> [:field price-field-id nil] 50]}}]
+ (testing "creating a card using a segment creates dependencies to both segment and table"
+ (events/publish-event! :event/segment-create {:object segment :user-id api/*current-user-id*})
+ (mt/with-temp [:model/Card {card-id :id :as card} {:dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table products-id
+ :filter [:segment segment-id]}}}]
+ (events/publish-event! :event/card-create {:object card :user-id api/*current-user-id*})
+ (is (= #{{:from_entity_type :card
+ :from_entity_id card-id
+ :to_entity_type :segment
+ :to_entity_id segment-id}
+ {:from_entity_type :card
+ :from_entity_id card-id
+ :to_entity_type :table
+ :to_entity_id products-id}}
+ (into #{} (map #(dissoc % :id)
+ (t2/select :model/Dependency :from_entity_id card-id :from_entity_type :card))))))))))))
+
+(deftest segment-dependency-calculation-error-handling-test
+ (testing "When segment dependency calculation throws an error, it should be logged and the version should still be updated"
+ (mt/with-test-user :rasta
+ (let [products-id (mt/id :products)
+ price-field-id (mt/id :products :price)]
+ (mt/with-premium-features #{:dependencies}
+ (mt/with-temp [:model/Segment {segment-id :id :as segment} {:table_id products-id
+ :definition {:filter [:> [:field price-field-id nil] 50]}}]
+ (log.capture/with-log-messages-for-level [messages ["metabase-enterprise.dependencies.events" :error]]
+ (with-redefs [deps.calculation/upstream-deps:segment (fn [_]
+ (throw (ex-info "Segment dependency calculation failed"
+ {:segment-id segment-id})))]
+ (testing "on create event"
+ (events/publish-event! :event/segment-create {:object segment :user-id api/*current-user-id*})
+ (is (some #(and (= "Segment dependency calculation failed" (ex-message (:e %)))
+ (= :error (:level %)))
+ (messages)))
+ (is (= models.dependency/current-dependency-analysis-version
+ (t2/select-one-fn :dependency_analysis_version :model/Segment :id segment-id)))
+ (is (empty? (t2/select :model/Dependency :from_entity_id segment-id :from_entity_type :segment))))
+ (testing "on update event"
+ (events/publish-event! :event/segment-update {:object segment :user-id api/*current-user-id*})
+ (is (some #(and (= "Segment dependency calculation failed" (ex-message (:e %)))
+ (= :error (:level %)))
+ (messages)))
+ (is (= models.dependency/current-dependency-analysis-version
+ (t2/select-one-fn :dependency_analysis_version :model/Segment :id segment-id)))
+ (is (empty? (t2/select :model/Dependency :from_entity_id segment-id :from_entity_type :segment))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
index f9f39735497..dce5eaed7f6 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
@@ -247,5 +247,5 @@
dep-version-after (t2/select-one-fn :dependency_analysis_version :model/Card :id card-id)
deps-after (t2/count :model/Dependency :from_entity_type :card :from_entity_id card-id)]
(is (= 0 revision-count-after))
- (is (= 2 dep-version-after))
+ (is (= 3 dep-version-after))
(is (= 1 deps-after))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index 3ffa010caf9..c5930ecd3cc 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -17,6 +17,7 @@ import type {
DocumentDependencyNode,
PythonLibrary,
SandboxDependencyNode,
+ SegmentDependencyNode,
SnippetDependencyNode,
SupportAccessGrant,
TableDependencyNode,
@@ -241,6 +242,16 @@ function provideSandboxDependencyNodeTags(
];
}
+function provideSegmentDependencyNodeTags(
+ node: SegmentDependencyNode,
+): TagDescription<EnterpriseTagType>[] {
+ return [
+ idTag("segment", node.id),
+ ...(node.data.creator != null ? provideUserTags(node.data.creator) : []),
+ ...(node.data.table ? provideTableTags(node.data.table) : []),
+ ];
+}
+
export function provideDependencyNodeTags(
node: DependencyNode,
): TagDescription<EnterpriseTagType>[] {
@@ -259,6 +270,8 @@ export function provideDependencyNodeTags(
return provideDocumentDependencyNodeTags(node);
case "sandbox":
return provideSandboxDependencyNodeTags(node);
+ case "segment":
+ return provideSegmentDependencyNodeTags(node);
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts
index 1f25b699010..e2827561b30 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphDependencyPanel/PanelHeader/utils.ts
@@ -31,5 +31,7 @@ export function getHeaderLabel(
return t`Documents that use ${nodeLabel}`;
case "sandbox":
return t`Row and column security rules that use ${nodeLabel}`;
+ case "segment":
+ return t`Segments that use ${nodeLabel}`;
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntrySearchInput/SearchModelPicker/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntrySearchInput/SearchModelPicker/utils.ts
index 0a717a552ce..5f5cbe56c9d 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntrySearchInput/SearchModelPicker/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/EntrySearchInput/SearchModelPicker/utils.ts
@@ -18,6 +18,7 @@ export function getSearchModelItems(data: SearchResponse): SearchModelItem[] {
metric: t`Metrics`,
dashboard: t`Dashboards`,
document: t`Documents`,
+ segment: t`Segments`,
};
const allItems = ENABLED_SEARCH_MODELS.map((model) => ({
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/constants.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/constants.ts
index f26d64a6313..e8860e86ea2 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/constants.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphEntryInput/constants.ts
@@ -11,6 +11,7 @@ export const ENABLED_SEARCH_MODELS = [
"metric",
"dashboard",
"document",
+ "segment",
] as const satisfies SearchModel[];
export const ENABLED_SEARCH_MODEL_TO_GROUP_TYPE: Record<
@@ -24,6 +25,7 @@ export const ENABLED_SEARCH_MODEL_TO_GROUP_TYPE: Record<
metric: "metric",
dashboard: "dashboard",
document: "document",
+ segment: "segment",
};
export const SEARCH_MODELS: SearchModel[] = ENABLED_SEARCH_MODELS;
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts
index 7e0fabe2b20..cebc10cd4be 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphInfoPanel/PanelBody/utils.ts
@@ -16,6 +16,7 @@ export function getNodeCreatedAt(node: DependencyNode): string | null {
case "card":
case "dashboard":
case "document":
+ case "segment":
return node.data.created_at;
case "table":
case "transform":
@@ -30,6 +31,7 @@ export function getNodeCreatedBy(node: DependencyNode): UserInfo | null {
case "card":
case "dashboard":
case "document":
+ case "segment":
return node.data.creator ?? null;
case "table":
case "transform":
@@ -44,6 +46,7 @@ export function getNodeLastEditedAt(node: DependencyNode): string | null {
case "card":
case "dashboard":
return node.data["last-edit-info"]?.timestamp ?? null;
+ case "segment":
case "table":
case "transform":
case "snippet":
@@ -58,6 +61,7 @@ export function getNodeLastEditedBy(node: DependencyNode): LastEditInfo | null {
case "card":
case "dashboard":
return node.data["last-edit-info"] ?? null;
+ case "segment":
case "table":
case "transform":
case "snippet":
@@ -117,6 +121,7 @@ export function getNodeFields(node: DependencyNode): Field[] {
case "snippet":
case "dashboard":
case "document":
+ case "segment":
return [];
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts
index 10f36d17436..3880da75a34 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/GraphNode/utils.ts
@@ -1,4 +1,4 @@
-import { msgid, ngettext, t } from "ttag";
+import { c, msgid, ngettext, t } from "ttag";
import type { DependencyNode } from "metabase-types/api";
@@ -15,6 +15,7 @@ export function getDependentGroups(node: DependencyNode): DependentGroup[] {
dashboard = 0,
document = 0,
sandbox = 0,
+ segment = 0,
} = node.dependents_count ?? {};
const groups: DependentGroup[] = [
@@ -27,6 +28,7 @@ export function getDependentGroups(node: DependencyNode): DependentGroup[] {
{ type: "dashboard", count: dashboard },
{ type: "document", count: document },
{ type: "sandbox", count: sandbox },
+ { type: "segment", count: segment },
];
return groups.filter(({ count }) => count !== 0);
@@ -75,5 +77,11 @@ export function getDependentGroupLabel({
`${count} row and column security rules`,
count,
);
+ case "segment":
+ return c("{0} is the number of segments").ngettext(
+ msgid`${count} segment`,
+ `${count} segments`,
+ count,
+ );
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts
index dc75bb8723d..e80052b6cbe 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.ts
@@ -146,6 +146,8 @@ export function getNodeIconWithType(
return "document";
case "sandbox":
return "permissions_limited";
+ case "segment":
+ return "segment";
}
}
@@ -203,6 +205,11 @@ export function getNodeLink(node: DependencyNode): NodeLink | null {
};
}
return null;
+ case "segment":
+ return {
+ label: t`View this segment`,
+ url: Urls.dataStudioSegment(node.id),
+ };
case "snippet":
return null;
}
@@ -253,6 +260,20 @@ export function getNodeLocationInfo(node: DependencyNode): NodeLink[] | null {
];
}
return null;
+ case "segment":
+ if (node.data.table != null) {
+ return [
+ {
+ label: node.data.table.display_name,
+ url: Urls.dataModelTable(
+ node.data.table.db_id,
+ node.data.table.schema,
+ node.data.table.id,
+ ),
+ },
+ ];
+ }
+ return null;
case "transform":
case "snippet":
case "sandbox":
@@ -275,6 +296,7 @@ export function getNodeViewCount(node: DependencyNode): number | null {
case "transform":
case "snippet":
case "sandbox":
+ case "segment":
return null;
}
}
@@ -327,5 +349,7 @@ export function getNodeTypeInfo(node: DependencyNode): NodeTypeInfo {
return { label: t`Document`, color: "text-secondary" };
case "sandbox":
return { label: t`Row and column security rule`, color: "error" };
+ case "segment":
+ return { label: t`Segment`, color: "accent2" };
}
}
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.unit.spec.ts
index be40075f2a4..71a12ae9f6f 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/components/DependencyGraph/utils.unit.spec.ts
@@ -4,6 +4,7 @@ import type { DependencyNode } from "metabase-types/api";
import {
createMockCardDependencyNode,
createMockCardDependencyNodeData,
+ createMockSegmentDependencyNode,
createMockSnippetDependencyNode,
createMockTableDependencyNode,
createMockTableDependencyNodeData,
@@ -121,6 +122,15 @@ describe("getNodeLink", () => {
url: "/admin/datamodel/database/2/schema/2:not%20public/table/1",
},
},
+ {
+ node: createMockSegmentDependencyNode({
+ id: 1,
+ }),
+ expectedLink: {
+ label: "View this segment",
+ url: "/admin/datamodel/segment/1",
+ },
+ },
])("should get the node link", ({ node, expectedLink }) => {
expect(getNodeLink(node)).toEqual(expectedLink);
});
diff --git a/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/utils.ts
index 578a456c5c8..11cb3a75379 100644
--- a/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/dependencies/pages/DependencyGraphPage/utils.ts
@@ -19,6 +19,7 @@ function parseDependencyType(type: unknown): DependencyType | undefined {
case "dashboard":
case "document":
case "sandbox":
+ case "segment":
return type;
default:
return undefined;
diff --git a/frontend/src/metabase-types/api/dependencies.ts b/frontend/src/metabase-types/api/dependencies.ts
index bea8b28ffcb..105877deb55 100644
--- a/frontend/src/metabase-types/api/dependencies.ts
+++ b/frontend/src/metabase-types/api/dependencies.ts
@@ -6,6 +6,7 @@
import type { Card, CardType } from "./card";
import type { Dashboard } from "./dashboard";
import type { Document } from "./document";
+import type { Segment } from "./segment";
import type { NativeQuerySnippet } from "./snippets";
import type { Table, TableId } from "./table";
import type { Transform } from "./transform";
@@ -18,7 +19,8 @@ export type DependencyType =
| "snippet"
| "dashboard"
| "document"
- | "sandbox";
+ | "sandbox"
+ | "segment";
export type DependencyGroupType = CardType | Exclude<DependencyType, "card">;
export type DependencyEntry = {
@@ -131,6 +133,18 @@ export type SandboxDependencyNode = BaseDependencyNode<
SandboxDependencyNodeData
>;
+export type SegmentDependencyNodeData = Pick<
+ Segment,
+ "name" | "description" | "table_id" | "created_at" | "creator_id" | "creator"
+> & {
+ table?: Table | null;
+};
+
+export type SegmentDependencyNode = BaseDependencyNode<
+ "segment",
+ SegmentDependencyNodeData
+>;
+
export type DependencyNode =
| TableDependencyNode
| TransformDependencyNode
@@ -138,7 +152,8 @@ export type DependencyNode =
| SnippetDependencyNode
| DashboardDependencyNode
| DocumentDependencyNode
- | SandboxDependencyNode;
+ | SandboxDependencyNode
+ | SegmentDependencyNode;
export type DependencyEdge = {
from_entity_id: DependencyId;
diff --git a/frontend/src/metabase-types/api/mocks/dependencies.ts b/frontend/src/metabase-types/api/mocks/dependencies.ts
index 6bf25ad5abe..7829a685308 100644
--- a/frontend/src/metabase-types/api/mocks/dependencies.ts
+++ b/frontend/src/metabase-types/api/mocks/dependencies.ts
@@ -8,6 +8,8 @@ import type {
DependencyEdge,
DependencyEntry,
DependencyGraph,
+ SegmentDependencyNode,
+ SegmentDependencyNodeData,
SnippetDependencyNode,
SnippetDependencyNodeData,
TableDependencyNode,
@@ -146,6 +148,31 @@ export function createMockSnippetDependencyNodeData(
};
}
+export function createMockSegmentDependencyNodeData(
+ opts?: Partial<SegmentDependencyNodeData>,
+): SegmentDependencyNodeData {
+ return {
+ name: "Segment",
+ description: "",
+ table_id: 1,
+ created_at: "2020-01-01T00:00:00Z",
+ creator_id: 1,
+ ...opts,
+ };
+}
+
+export function createMockSegmentDependencyNode(
+ opts?: Partial<SegmentDependencyNode>,
+): SegmentDependencyNode {
+ return {
+ id: 1,
+ type: "segment",
+ data: createMockSegmentDependencyNodeData(),
+ dependents_count: {},
+ ...opts,
+ };
+}
+
export function createMockCheckCardDependenciesRequest(
opts?: Partial<CheckCardDependenciesRequest>,
): CheckCardDependenciesRequest {
diff --git a/frontend/src/metabase-types/api/mocks/segment.ts b/frontend/src/metabase-types/api/mocks/segment.ts
index 66c6ff50d68..20e5a664cd9 100644
--- a/frontend/src/metabase-types/api/mocks/segment.ts
+++ b/frontend/src/metabase-types/api/mocks/segment.ts
@@ -10,5 +10,7 @@ export const createMockSegment = (opts?: Partial<Segment>): Segment => ({
archived: false,
definition: createMockStructuredDatasetQuery(),
definition_description: "",
+ created_at: "2021-01-01T00:00:00Z",
+ creator_id: 1,
...opts,
});
diff --git a/frontend/src/metabase-types/api/segment.ts b/frontend/src/metabase-types/api/segment.ts
index 4c33d80c0d9..e7ed7aa887e 100644
--- a/frontend/src/metabase-types/api/segment.ts
+++ b/frontend/src/metabase-types/api/segment.ts
@@ -1,5 +1,6 @@
import type { DatasetQuery } from "./query";
import type { Table, TableId } from "./table";
+import type { UserInfo } from "./user";
export type SegmentId = number;
@@ -14,6 +15,9 @@ export interface Segment {
definition: DatasetQuery;
definition_description: string;
revision_message?: string;
+ created_at: string;
+ creator_id: number;
+ creator?: UserInfo;
}
export interface CreateSegmentRequest {
diff --git a/frontend/src/metabase/lib/urls/data-studio.ts b/frontend/src/metabase/lib/urls/data-studio.ts
index 5db478c0b7d..80193e1a209 100644
--- a/frontend/src/metabase/lib/urls/data-studio.ts
+++ b/frontend/src/metabase/lib/urls/data-studio.ts
@@ -2,6 +2,7 @@ import type {
CardId,
CollectionId,
NativeQuerySnippetId,
+ SegmentId,
} from "metabase-types/api";
const ROOT_URL = "/data-studio";
@@ -106,3 +107,11 @@ export function dataStudioSnippetDependencies(snippetId: NativeQuerySnippetId) {
export function newDataStudioSnippet() {
return `${dataStudioModeling()}/snippets/new`;
}
+
+export function dataStudioSegment(segmentId: SegmentId) {
+ return `/admin/datamodel/segment/${segmentId}`;
+}
+
+export function dataStudioSegmentDependencies(segmentId: SegmentId) {
+ return `${dataStudioSegment(segmentId)}/dependencies`;
+}
diff --git a/resources/migrations/058_update_migrations.yaml b/resources/migrations/058_update_migrations.yaml
index 725ce91b4ae..656a7f15c9c 100644
--- a/resources/migrations/058_update_migrations.yaml
+++ b/resources/migrations/058_update_migrations.yaml
@@ -815,6 +815,26 @@ databaseChangeLog:
- sql:
sql: UPDATE collection SET type = 'remote-synced' WHERE is_remote_synced = true
+ - changeSet:
+ id: v58.2025-11-25T17:04:00
+ author: dependencies
+ comment: Add dependency_analysis_version to segment table for tracking dependency changes
+ changes:
+ - addColumn:
+ tableName: segment
+ columns:
+ - column:
+ name: dependency_analysis_version
+ type: integer
+ defaultValueNumeric: 0
+ remarks: Version number for dependency analysis to track when dependencies need recalculation
+ constraints:
+ nullable: false
+ rollback:
+ - dropColumn:
+ tableName: segment
+ columnName: dependency_analysis_version
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljc
index 39ccb2bad7a..438f889b19d 100644
--- a/src/metabase/lib/core.cljc
+++ b/src/metabase/lib/core.cljc
@@ -497,6 +497,7 @@
all-field-ids
all-implicitly-joined-field-ids
all-implicitly-joined-table-ids
+ all-segment-ids
all-source-card-ids
all-source-table-ids
all-template-tag-field-ids
diff --git a/src/metabase/lib/walk/util.cljc b/src/metabase/lib/walk/util.cljc
index 7025005869a..b7cdb27e929 100644
--- a/src/metabase/lib/walk/util.cljc
+++ b/src/metabase/lib/walk/util.cljc
@@ -78,6 +78,20 @@
nil))))
(not-empty (persistent! @metric-ids))))
+(mu/defn all-segment-ids :- [:maybe [:set {:min 1} ::lib.schema.id/segment]]
+ "Return a set of all segment IDs anywhere in the query."
+ [query]
+ (let [segment-ids (volatile! (transient #{}))]
+ (lib.walk/walk-clauses
+ query
+ (fn [_query _path-type _stage-or-join-path clause]
+ (lib.util.match/match-lite clause
+ [:segment _opts (id :guard pos-int?)]
+ (do
+ (vswap! segment-ids conj! id)
+ nil))))
+ (not-empty (persistent! @segment-ids))))
+
(defn- all-template-tag-card-ids [query]
(not-empty
(into #{}
diff --git a/src/metabase/revisions/impl/segment.clj b/src/metabase/revisions/impl/segment.clj
index 662ad1cf17d..09c6430ba5e 100644
--- a/src/metabase/revisions/impl/segment.clj
+++ b/src/metabase/revisions/impl/segment.clj
@@ -4,9 +4,12 @@
[metabase.lib.schema.util :as lib.schema.util]
[metabase.revisions.models.revision :as revision]))
+(def ^:private excluded-columns-for-segment-revision
+ #{:created_at :updated_at :dependency_analysis_versions})
+
(defmethod revision/serialize-instance :model/Segment
[_model _id instance]
- (dissoc instance :created_at :updated_at))
+ (apply dissoc instance excluded-columns-for-segment-revision))
(defn- normalize-segment
[segment]
diff --git a/src/metabase/segments/models/segment.clj b/src/metabase/segments/models/segment.clj
index 3c3854920d6..4c7f5e5e725 100644
--- a/src/metabase/segments/models/segment.clj
+++ b/src/metabase/segments/models/segment.clj
@@ -156,7 +156,7 @@
(defmethod serdes/make-spec "Segment" [_model-name _opts]
{:copy [:name :points_of_interest :archived :caveats :description :entity_id :show_in_getting_started]
- :skip []
+ :skip [:dependency_analysis_version]
:transform {:created_at (serdes/date)
:table_id (serdes/fk :model/Table)
:creator_id (serdes/fk :model/User)
diff --git a/test/metabase/segments/api_test.clj b/test/metabase/segments/api_test.clj
index 9120c471785..b10e5ca1449 100644
--- a/test/metabase/segments/api_test.clj
+++ b/test/metabase/segments/api_test.clj
@@ -20,11 +20,12 @@
(defn- segment-response [segment]
(-> (into {} segment)
- (dissoc :id :table_id)
+ (dissoc :id :table_id :dependency_analysis_version)
(update :creator #(into {} %))
(update :entity_id some?)
(update :created_at some?)
- (update :updated_at some?)))
+ (update :updated_at some?)
+ (update :definition map?)))
(defn- mbql4-segment-definition
"Create a legacy MBQL4 segment definition"
@@ -108,8 +109,7 @@
:points_of_interest nil
:table_id id
:definition (definition-fn 10 20)})
- segment-response
- (update :definition map?))))))))
+ segment-response)))))))
;; ## PUT /api/segment
@@ -172,8 +172,7 @@
:table_id 456
:revision_message "I got me some revisions"
:definition (eq-fn 2 "cans")})
- segment-response
- (update :definition map?)))))))))
+ segment-response))))))))
(deftest partial-update-test
(testing "PUT /api/segment/:id"
@@ -244,8 +243,7 @@
:archived true
:definition true}
(-> (mt/user-http-request :crowberto :get 200 (format "segment/%d" id))
- segment-response
- (update :definition map?))))))))
+ segment-response)))))))
;; ## GET /api/segment/:id
@@ -285,8 +283,7 @@
:definition true}
(-> (mt/user-http-request :rasta :get 200 (format "segment/%d" id))
segment-response
- (dissoc :query_description)
- (update :definition map?)))))))))))
+ (dissoc :query_description)))))))))))
(deftest list-test
(testing "GET /api/segment/"