Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-catalog): support scoped BI catalog handoffs (#117985)

Marius Andrac8dc01d4b4da
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index d6e5b421a1b8..56a349ca8377 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -9,7 +9,7 @@ from operator import or_
from typing import cast
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVectorField
-from django.db.models import Func, QuerySet, Value
+from django.db.models import Func, Q, QuerySet, Value
from django.db.models.expressions import CombinedExpression
from django.db.models.functions import Coalesce
@@ -118,11 +118,16 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
queryset = Metric.objects.unscoped()
def safely_get_queryset(self, queryset: QuerySet[Metric]) -> QuerySet[Metric]:
- return api.metrics_visible_to_user(
+ metrics = api.metrics_visible_to_user(
self.team,
cast(User, self.request.user),
self.user_access_control,
)
+ if status_filter := self.request.query_params.get("status"):
+ metrics = metrics.filter(status=status_filter)
+ if definition_kind := self.request.query_params.get("definition_kind"):
+ metrics = metrics.filter(definition__kind=definition_kind)
+ return metrics
def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:
if getattr(view, "action", None) not in ("create", "update", "partial_update"):
@@ -147,6 +152,14 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return [ClickHouseBurstRateThrottle(), ClickHouseSustainedRateThrottle()]
return super().get_throttles()
+ @extend_schema(
+ parameters=[
+ OpenApiParameter("status", OpenApiTypes.STR, description="Only metrics with this review status."),
+ OpenApiParameter(
+ "definition_kind", OpenApiTypes.STR, description="Only metrics with this query node kind."
+ ),
+ ]
+ )
def list(self, request: Request, *args, **kwargs) -> Response:
# Precompute drift for the whole page in one bulk query, so is_drifted doesn't fan out
# into a per-metric insight lookup (an N+1 over the catalog list).
@@ -311,6 +324,20 @@ class MetricViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return Response(envelope)
+class CertificationSearchFilter(CatalogSearchFilter):
+ def get_schema_operation_parameters(self, view: APIView) -> list[dict[str, object]]:
+ return [
+ *super().get_schema_operation_parameters(view),
+ {
+ "name": "status",
+ "required": False,
+ "in": "query",
+ "description": "Only certifications with this review status.",
+ "schema": {"type": "string"},
+ },
+ ]
+
+
class CertificationViewSet(
TeamAndOrgViewSetMixin,
mixins.ListModelMixin,
@@ -322,13 +349,16 @@ class CertificationViewSet(
"""Trust marks on warehouse tables and views. Reads exclude soft-deleted targets."""
scope_object = "data_catalog"
- filter_backends = [CatalogSearchFilter]
+ filter_backends = [CertificationSearchFilter]
search_fields = ["table__name", "saved_query__name", "notes"]
serializer_class = CertificationSerializer
queryset = TableCertification.objects.unscoped()
def safely_get_queryset(self, queryset: QuerySet[TableCertification]) -> QuerySet[TableCertification]:
- return api.certifications_for_team(self.team)
+ certifications = api.certifications_for_team(self.team)
+ if status_filter := self.request.query_params.get("status"):
+ certifications = certifications.filter(status=status_filter)
+ return certifications
def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:
action = getattr(view, "action", None)
@@ -398,10 +428,20 @@ class RelationshipProposalViewSet(
def safely_get_queryset(self, queryset: QuerySet[RelationshipProposal]) -> QuerySet[RelationshipProposal]:
proposals = api.relationships_for_team(self.team)
status_filter = self.request.query_params.get("status")
- return proposals.filter(status=status_filter) if status_filter else proposals
+ if status_filter:
+ proposals = proposals.filter(status=status_filter)
+ table_name = self.request.query_params.get("table_name")
+ if table_name:
+ proposals = proposals.filter(Q(source_table_name=table_name) | Q(joining_table_name=table_name))
+ return proposals
@extend_schema(
- parameters=[OpenApiParameter("status", OpenApiTypes.STR, description="Filter by proposed/accepted/rejected.")]
+ parameters=[
+ OpenApiParameter("status", OpenApiTypes.STR, description="Filter by proposed/accepted/rejected."),
+ OpenApiParameter(
+ "table_name", OpenApiTypes.STR, description="Only relationships involving this table on either side."
+ ),
+ ]
)
def list(self, request: Request, *args, **kwargs) -> Response:
return super().list(request, *args, **kwargs)
diff --git a/products/data_catalog/backend/tests/test_api.py b/products/data_catalog/backend/tests/test_api.py
index e7ee76f88b2f..5379722c2556 100644
--- a/products/data_catalog/backend/tests/test_api.py
+++ b/products/data_catalog/backend/tests/test_api.py
@@ -54,6 +54,21 @@ class TestMetricAPI(APIBaseTest):
assert body["name"] == "mrr"
assert body["status"] == MetricStatus.PROPOSED
+ def test_list_filters_status_and_definition_kind_before_pagination(self) -> None:
+ for name, metric_status, definition in [
+ ("approved_sql", MetricStatus.APPROVED, _HOGQL),
+ ("proposed_sql", MetricStatus.PROPOSED, _HOGQL),
+ ("approved_markdown", MetricStatus.APPROVED, None),
+ ]:
+ Metric.objects.for_team(self.team.id).create(
+ team=self.team, name=name, status=metric_status, definition=definition
+ )
+ response = self.client.get(self.url, {"status": "approved", "definition_kind": "HogQLQuery", "limit": "1"})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["count"] == 1
+ assert [row["name"] for row in response.json()["results"]] == ["approved_sql"]
+
def test_status_and_approval_are_not_writable(self) -> None:
response = self.client.post(
self.url,
diff --git a/products/data_catalog/backend/tests/test_certifications.py b/products/data_catalog/backend/tests/test_certifications.py
index 960bc32e2570..85ba0ff15ec4 100644
--- a/products/data_catalog/backend/tests/test_certifications.py
+++ b/products/data_catalog/backend/tests/test_certifications.py
@@ -362,6 +362,20 @@ class TestCertificationAPI(APIBaseTest):
super().setUp()
self.url = f"/api/projects/{self.team.id}/data_catalog/certifications/"
+ def test_list_filters_status_before_pagination(self) -> None:
+ certified = TableCertification.objects.for_team(self.team.id).create(
+ team=self.team, table=_table(self.team, "approved_source"), status=CertificationStatus.CERTIFIED
+ )
+ TableCertification.objects.for_team(self.team.id).create(
+ team=self.team, table=_table(self.team, "proposed_source"), status=CertificationStatus.PROPOSED
+ )
+
+ response = self.client.get(self.url, {"status": "certified", "limit": "1"})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["count"] == 1
+ assert [row["id"] for row in response.json()["results"]] == [str(certified.id)]
+
@parameterized.expand(
[
("table_name", "table", False),
diff --git a/products/data_catalog/backend/tests/test_relationships.py b/products/data_catalog/backend/tests/test_relationships.py
index d519631e6f08..8f61a23c549f 100644
--- a/products/data_catalog/backend/tests/test_relationships.py
+++ b/products/data_catalog/backend/tests/test_relationships.py
@@ -283,6 +283,11 @@ class TestRelationshipAPI(APIBaseTest):
response = self.client.post(self.url, _JOIN, format="json")
assert response.status_code == status.HTTP_201_CREATED, response.json()
assert response.json()["status"] == RelationshipStatus.PROPOSED
+ proposal_id = response.json()["id"]
+ for table_name in (_JOIN["source_table_name"], _JOIN["joining_table_name"]):
+ listed = self.client.get(self.url, {"table_name": table_name})
+ assert [item["id"] for item in listed.json()["results"]] == [proposal_id]
+ assert self.client.get(self.url, {"table_name": "unrelated"}).json()["results"] == []
def test_duplicate_pair_returns_409_with_proposal_id(self) -> None:
# The dedupe conflict must render through the HTTP exception handler and hand back the
diff --git a/products/data_catalog/frontend/certificationsLogic.tsx b/products/data_catalog/frontend/certificationsLogic.tsx
index eb5e03b08cf8..1975508ab25c 100644
--- a/products/data_catalog/frontend/certificationsLogic.tsx
+++ b/products/data_catalog/frontend/certificationsLogic.tsx
@@ -1,10 +1,12 @@
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { urlToAction } from 'kea-router'
import { ApiConfig, ApiError } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { createFuseSearch } from 'lib/utils/fuseSearch'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
+import { urls } from 'scenes/urls'
import {
dataCatalogCertificationsCertifyCreate,
@@ -319,6 +321,13 @@ export const certificationsLogic = kea<certificationsLogicType>([
},
}
}),
+ urlToAction(({ actions }) => ({
+ [urls.dataCatalog()]: (_, searchParams) => {
+ if (searchParams.tab === 'certifications' && typeof searchParams.table === 'string') {
+ actions.setFilters({ search: searchParams.table })
+ }
+ },
+ })),
afterMount(({ actions }) => {
actions.loadCertifications()
}),
diff --git a/products/data_catalog/frontend/components/RelationshipProposalModal.tsx b/products/data_catalog/frontend/components/RelationshipProposalModal.tsx
new file mode 100644
index 000000000000..ee5db8040b73
--- /dev/null
+++ b/products/data_catalog/frontend/components/RelationshipProposalModal.tsx
@@ -0,0 +1,65 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInput, LemonModal, LemonTextArea } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { relationshipsLogic } from '../relationshipsLogic'
+
+const FIELDS = [
+ ['source_table_name', 'Source table'],
+ ['source_table_key', 'Source key'],
+ ['joining_table_name', 'Related table'],
+ ['joining_table_key', 'Related key'],
+ ['field_name', 'Relationship name'],
+] as const
+
+export function RelationshipProposalModal(): JSX.Element {
+ const { proposalOpen, proposalDraft: draft, proposing } = useValues(relationshipsLogic)
+ const { closeProposal, setProposalDraft, proposeRelationship } = useActions(relationshipsLogic)
+ return (
+ <LemonModal
+ isOpen={proposalOpen}
+ onClose={() => !proposing && closeProposal()}
+ title="Propose a relationship"
+ footer={
+ <LemonButton
+ type="primary"
+ data-attr="data-catalog-propose-relationship"
+ onClick={proposeRelationship}
+ loading={proposing}
+ disabledReason={
+ FIELDS.some(([key]) => !draft[key].trim())
+ ? 'Fill in both tables, keys, and a relationship name'
+ : undefined
+ }
+ >
+ Send for review
+ </LemonButton>
+ }
+ >
+ <p>A catalog reviewer must accept this proposal before it becomes a join available to worksheets.</p>
+ <div className="flex flex-col gap-3">
+ {FIELDS.map(([key, label]) => (
+ <LemonField.Pure key={key} label={label}>
+ <LemonInput
+ aria-label={label}
+ value={draft[key]}
+ onChange={(value) => setProposalDraft({ [key]: value })}
+ maxLength={400}
+ disabled={proposing}
+ />
+ </LemonField.Pure>
+ ))}
+ <LemonField.Pure label="Why should these tables be related?">
+ <LemonTextArea
+ aria-label="Why should these tables be related?"
+ value={draft.reasoning ?? ''}
+ disabled={proposing}
+ onChange={(reasoning) => setProposalDraft({ reasoning })}
+ />
+ </LemonField.Pure>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/data_catalog/frontend/dataCatalogSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogSceneLogic.tsx
index 45c31c306d87..d40df4edddfe 100644
--- a/products/data_catalog/frontend/dataCatalogSceneLogic.tsx
+++ b/products/data_catalog/frontend/dataCatalogSceneLogic.tsx
@@ -1,5 +1,5 @@
import { MakeLogicType, actions, connect, kea, path, reducers } from 'kea'
-import { actionToUrl, urlToAction } from 'kea-router'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import { urls } from 'scenes/urls'
@@ -38,7 +38,11 @@ export const dataCatalogSceneLogic = kea<dataCatalogSceneLogicType>([
],
}),
actionToUrl(({ values }) => ({
- setActiveTab: () => urls.dataCatalog(values.activeTab === 'metrics' ? undefined : values.activeTab),
+ setActiveTab: () => {
+ if ((router.values.searchParams.tab ?? 'metrics') !== values.activeTab) {
+ return urls.dataCatalog(values.activeTab === 'metrics' ? undefined : values.activeTab)
+ }
+ },
})),
urlToAction(({ actions, values }) => ({
[urls.dataCatalog()]: (_, searchParams) => {
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index 6463c9fd14a3..9bba2a32d946 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -564,9 +564,17 @@ export type DataCatalogCertificationsListParams = {
* A search term.
*/
search?: string
+ /**
+ * Only certifications with this review status.
+ */
+ status?: string
}
export type DataCatalogMetricsListParams = {
+ /**
+ * Only metrics with this query node kind.
+ */
+ definition_kind?: string
/**
* Number of results to return per page.
*/
@@ -579,6 +587,10 @@ export type DataCatalogMetricsListParams = {
* A search term.
*/
search?: string
+ /**
+ * Only metrics with this review status.
+ */
+ status?: string
}
export type DataCatalogMetricsRunCreateParams = {
@@ -625,4 +637,8 @@ export type DataCatalogRelationshipProposalsListParams = {
* Filter by proposed/accepted/rejected.
*/
status?: string
+ /**
+ * Only relationships involving this table on either side.
+ */
+ table_name?: string
}
diff --git a/products/data_catalog/frontend/relationshipsLogic.test.ts b/products/data_catalog/frontend/relationshipsLogic.test.ts
index 2ba772e5ace1..caaa1aa09b0f 100644
--- a/products/data_catalog/frontend/relationshipsLogic.test.ts
+++ b/products/data_catalog/frontend/relationshipsLogic.test.ts
@@ -1,14 +1,17 @@
-import api from 'lib/api'
+import { router } from 'kea-router'
+
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { initKeaTests } from '~/test/init'
import { expectLogic } from '~/test/keaTestUtils'
-import { DataWarehouseViewLink } from '~/types'
+import { warehouseViewLinksList } from 'products/data_warehouse/frontend/generated/api'
+import { ViewLinkApi } from 'products/data_warehouse/frontend/generated/api.schemas'
import { viewLinkLogic } from 'products/data_warehouse/frontend/shared/logics/viewLinkLogic'
import {
+ dataCatalogRelationshipProposalsCreate,
dataCatalogRelationshipProposalsAcceptCreate,
dataCatalogRelationshipProposalsList,
dataCatalogRelationshipProposalsRejectCreate,
@@ -17,6 +20,8 @@ import type { DataCatalogRelationshipProposalApi } from './generated/api.schemas
import { relationshipsLogic } from './relationshipsLogic'
import type { RelationshipsFilters } from './relationshipsLogic'
+jest.mock('products/data_warehouse/frontend/generated/api', () => ({ warehouseViewLinksList: jest.fn() }))
+
jest.mock('lib/api', () => {
class ApiError extends Error {
status?: number
@@ -41,6 +46,7 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
jest.mock('./generated/api', () => ({
dataCatalogRelationshipProposalsList: jest.fn(),
+ dataCatalogRelationshipProposalsCreate: jest.fn(),
dataCatalogRelationshipProposalsAcceptCreate: jest.fn(),
dataCatalogRelationshipProposalsRejectCreate: jest.fn(),
}))
@@ -77,7 +83,7 @@ describe('relationshipsLogic', () => {
results: proposals,
count: proposals.filter((proposal) => proposal.status === 'proposed').length,
})
- ;(api.dataWarehouseViewLinks.list as jest.Mock).mockResolvedValue({ results: joins })
+ ;(warehouseViewLinksList as jest.Mock).mockResolvedValue({ results: joins })
initKeaTests()
logic = relationshipsLogic()
logic.mount()
@@ -92,9 +98,79 @@ describe('relationshipsLogic', () => {
jest.clearAllMocks()
})
+ it('prefills a proposal from a BI source and prevents duplicate submissions', async () => {
+ await mountWith([], [])
+ router.actions.push('/data-catalog', { tab: 'relationships', table: 'events', propose_table: 'events' })
+ expect(logic.values.proposalOpen).toBe(true)
+ expect(logic.values.proposalDraft.source_table_name).toBe('events')
+ logic.actions.setProposalDraft({
+ source_table_key: 'account_id',
+ joining_table_name: 'accounts',
+ joining_table_key: 'id',
+ field_name: 'account',
+ })
+ let finish: (value: unknown) => void = () => {}
+ ;(dataCatalogRelationshipProposalsCreate as jest.Mock).mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve
+ })
+ )
+ logic.actions.proposeRelationship()
+ logic.actions.proposeRelationship()
+ expect(dataCatalogRelationshipProposalsCreate).toHaveBeenCalledTimes(1)
+ await expectLogic(logic, () => finish({ id: 'proposed' })).toFinishAllListeners()
+ expect(logic.values.proposalOpen).toBe(false)
+ expect(logic.values.proposing).toBe(false)
+ expect(router.values.searchParams.propose_table).toBeUndefined()
+ })
+
+ it('loads proposals with the linked table filter before pagination and clears it on general navigation', async () => {
+ await mountWith([], [])
+ ;(dataCatalogRelationshipProposalsList as jest.Mock).mockImplementation((_project, params) =>
+ Promise.resolve({ results: params?.table_name === 'events' ? [buildProposal({})] : [] })
+ )
+ await expectLogic(logic, () =>
+ router.actions.push('/data-catalog', { tab: 'relationships', table: 'events' })
+ ).toFinishAllListeners()
+ expect(dataCatalogRelationshipProposalsList).toHaveBeenLastCalledWith('1', { table_name: 'events' })
+ expect(logic.values.proposals).toHaveLength(1)
+ await expectLogic(logic, () => logic.actions.loadProposals()).toFinishAllListeners()
+ expect(dataCatalogRelationshipProposalsList).toHaveBeenLastCalledWith('1', { table_name: 'events' })
+ await expectLogic(logic, () =>
+ router.actions.push('/data-catalog', { tab: 'relationships' })
+ ).toFinishAllListeners()
+ expect(dataCatalogRelationshipProposalsList).toHaveBeenLastCalledWith('1', undefined)
+ expect(logic.values.proposals).toEqual([])
+ })
+
+ it.each(['', 'orders'])('removes the linked table scope when search changes to %j', async (search) => {
+ await mountWith([], [])
+ const eventsProposal = buildProposal({})
+ const ordersProposal = buildProposal({ id: 'orders-proposal', source_table_name: 'orders' })
+ ;(dataCatalogRelationshipProposalsList as jest.Mock).mockImplementation((_project, params) =>
+ Promise.resolve({
+ results: params?.table_name === 'events' ? [eventsProposal] : [eventsProposal, ordersProposal],
+ })
+ )
+ await expectLogic(logic, () =>
+ router.actions.push('/data-catalog', { tab: 'relationships', table: 'events' })
+ ).toFinishAllListeners()
+ logic.actions.setFilters({ status: 'pending' })
+ expect(router.values.searchParams.table).toBe('events')
+
+ await expectLogic(logic, () => logic.actions.setFilters({ search })).toFinishAllListeners()
+
+ expect(router.values.searchParams.table).toBeUndefined()
+ expect(logic.values.filters).toEqual({ search, status: 'pending' })
+ expect(dataCatalogRelationshipProposalsList).toHaveBeenLastCalledWith('1', undefined)
+ expect(logic.values.filteredRows.map((row) => row.proposalId)).toContain('orders-proposal')
+ await expectLogic(logic, () => logic.actions.loadProposals()).toFinishAllListeners()
+ expect(dataCatalogRelationshipProposalsList).toHaveBeenLastCalledWith('1', undefined)
+ })
+
it('loads only the lightweight badge count on mount, not the full proposal payloads', async () => {
;(dataCatalogRelationshipProposalsList as jest.Mock).mockResolvedValue({ results: [], count: 3 })
- ;(api.dataWarehouseViewLinks.list as jest.Mock).mockResolvedValue({ results: [] })
+ ;(warehouseViewLinksList as jest.Mock).mockResolvedValue({ results: [] })
initKeaTests()
logic = relationshipsLogic()
logic.mount()
@@ -168,12 +244,12 @@ describe('relationshipsLogic', () => {
it('reloads joins when the shared join modal saves', async () => {
await mountWith([], [])
- ;(api.dataWarehouseViewLinks.list as jest.Mock).mockClear()
+ ;(warehouseViewLinksList as jest.Mock).mockClear()
viewLinkLogic.build().actions.submitViewLinkSuccess({} as any)
await expectLogic(logic).toDispatchActions(['loadJoins', 'loadJoinsSuccess'])
- expect(api.dataWarehouseViewLinks.list).toHaveBeenCalledTimes(1)
+ expect(warehouseViewLinksList).toHaveBeenCalledTimes(1)
})
it('deletes a join against the singular view-link endpoint and reloads', async () => {
@@ -183,7 +259,7 @@ describe('relationshipsLogic', () => {
id: 'join-1',
field_name: 'person',
source_table_name: 'events',
- } as DataWarehouseViewLink)
+ } as ViewLinkApi)
await expectLogic(logic).toFinishAllListeners()
expect(deleteWithUndo).toHaveBeenCalledWith(
@@ -192,7 +268,7 @@ describe('relationshipsLogic', () => {
object: expect.objectContaining({ id: 'join-1' }),
})
)
- ;(api.dataWarehouseViewLinks.list as jest.Mock).mockClear()
+ ;(warehouseViewLinksList as jest.Mock).mockClear()
;(deleteWithUndo as jest.Mock).mock.calls[0][0].callback()
await expectLogic(logic).toDispatchActions(['loadJoins', 'loadJoinsSuccess'])
})
diff --git a/products/data_catalog/frontend/relationshipsLogic.tsx b/products/data_catalog/frontend/relationshipsLogic.tsx
index 9d6354c5a3b3..b22902f1db62 100644
--- a/products/data_catalog/frontend/relationshipsLogic.tsx
+++ b/products/data_catalog/frontend/relationshipsLogic.tsx
@@ -1,24 +1,30 @@
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { urlToAction } from 'kea-router'
+import { router, urlToAction } from 'kea-router'
-import api, { ApiConfig, ApiError } from 'lib/api'
+import { ApiConfig, ApiError } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { createFuseSearch } from 'lib/utils/fuseSearch'
import { urls } from 'scenes/urls'
-import { DataWarehouseViewLink } from '~/types'
-
+import { warehouseViewLinksList } from 'products/data_warehouse/frontend/generated/api'
+import { ViewLinkApi } from 'products/data_warehouse/frontend/generated/api.schemas'
import { viewLinkLogic } from 'products/data_warehouse/frontend/shared/logics/viewLinkLogic'
import {
+ dataCatalogRelationshipProposalsCreate,
dataCatalogRelationshipProposalsAcceptCreate,
dataCatalogRelationshipProposalsList,
dataCatalogRelationshipProposalsRejectCreate,
} from './generated/api'
import type { DataCatalogRelationshipProposalApi } from './generated/api.schemas'
+type CatalogJoin = Pick<
+ ViewLinkApi,
+ 'id' | 'source_table_name' | 'source_table_key' | 'joining_table_name' | 'joining_table_key' | 'field_name'
+>
+
export type RelationshipStatusFilter = 'all' | 'pending' | 'active' | 'rejected'
export type RelationshipRowStatus = 'pending' | 'active' | 'rejected'
@@ -71,13 +77,24 @@ export interface relationshipsLogicValues {
actionsInFlight: Record<string, boolean>
filteredRows: RelationshipRow[]
filters: RelationshipsFilters
- joins: DataWarehouseViewLink[]
- joinsById: Record<string, DataWarehouseViewLink>
+ joins: CatalogJoin[]
+ joinsById: Record<string, CatalogJoin>
joinsLoading: boolean
pendingCount: number
pendingCountLoading: boolean
+ proposalDraft: Pick<
+ DataCatalogRelationshipProposalApi,
+ | 'field_name'
+ | 'joining_table_key'
+ | 'joining_table_name'
+ | 'reasoning'
+ | 'source_table_key'
+ | 'source_table_name'
+ >
+ proposalOpen: boolean
proposals: DataCatalogRelationshipProposalApi[]
proposalsLoading: boolean
+ proposing: boolean
rows: RelationshipRow[]
}
@@ -86,8 +103,11 @@ export interface relationshipsLogicActions {
acceptProposal: (id: string) => {
id: string
}
- deleteJoin: (join: DataWarehouseViewLink) => {
- join: DataWarehouseViewLink
+ closeProposal: () => {
+ value: true
+ }
+ deleteJoin: (join: CatalogJoin) => {
+ join: CatalogJoin
}
loadJoins: () => any
loadJoinsFailure: (
@@ -98,10 +118,10 @@ export interface relationshipsLogicActions {
errorObject?: any
}
loadJoinsSuccess: (
- joins: DataWarehouseViewLink[],
+ joins: ViewLinkApi[],
payload?: any
) => {
- joins: DataWarehouseViewLink[]
+ joins: ViewLinkApi[]
payload?: any
}
loadPendingCount: () => any
@@ -119,7 +139,7 @@ export interface relationshipsLogicActions {
pendingCount: number
payload?: any
}
- loadProposals: () => any
+ loadProposals: (_: void) => void
loadProposalsFailure: (
error: string,
errorObject?: any
@@ -129,10 +149,16 @@ export interface relationshipsLogicActions {
}
loadProposalsSuccess: (
proposals: DataCatalogRelationshipProposalApi[],
- payload?: any
+ payload?: void
) => {
proposals: DataCatalogRelationshipProposalApi[]
- payload?: any
+ payload?: void
+ }
+ openProposal: (table?: any) => {
+ table: any
+ }
+ proposeRelationship: () => {
+ value: true
}
rejectProposal: (
id: string,
@@ -151,14 +177,20 @@ export interface relationshipsLogicActions {
setFilters: (filters: Partial<RelationshipsFilters>) => {
filters: Partial<RelationshipsFilters>
}
+ setProposalDraft: (draft: Partial<DataCatalogRelationshipProposalApi>) => {
+ draft: Partial<DataCatalogRelationshipProposalApi>
+ }
+ setProposing: (proposing: boolean) => {
+ proposing: boolean
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface relationshipsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- rows: (proposals: DataCatalogRelationshipProposalApi[], joins: DataWarehouseViewLink[]) => RelationshipRow[]
+ rows: (proposals: DataCatalogRelationshipProposalApi[], joins: CatalogJoin[]) => RelationshipRow[]
filteredRows: (rows: RelationshipRow[], filters: RelationshipsFilters) => RelationshipRow[]
- joinsById: (joins: DataWarehouseViewLink[]) => Record<string, DataWarehouseViewLink>
+ joinsById: (joins: CatalogJoin[]) => Record<string, CatalogJoin>
}
}
@@ -172,11 +204,16 @@ export type relationshipsLogicType = MakeLogicType<
export const relationshipsLogic = kea<relationshipsLogicType>([
path(['products', 'data_catalog', 'frontend', 'relationshipsLogic']),
actions({
+ openProposal: (table = '') => ({ table }),
+ closeProposal: true,
+ setProposing: (proposing: boolean) => ({ proposing }),
+ setProposalDraft: (draft: Partial<DataCatalogRelationshipProposalApi>) => ({ draft }),
+ proposeRelationship: true,
setFilters: (filters: Partial<RelationshipsFilters>) => ({ filters }),
acceptProposal: (id: string) => ({ id }),
rejectProposal: (id: string, rejectionReason: string) => ({ id, rejectionReason }),
setActionInFlight: (id: string, inFlight: boolean) => ({ id, inFlight }),
- deleteJoin: (join: DataWarehouseViewLink) => ({ join }),
+ deleteJoin: (join: CatalogJoin) => ({ join }),
}),
loaders(() => ({
// Badge count only — never pull the full proposal payloads (unbounded reasoning/evidence)
@@ -196,23 +233,59 @@ export const relationshipsLogic = kea<relationshipsLogicType>([
proposals: [
[] as DataCatalogRelationshipProposalApi[],
{
- loadProposals: async () => {
- const response = await dataCatalogRelationshipProposalsList(projectId())
+ loadProposals: async (_: void, breakpoint) => {
+ const table = router.values.searchParams.table
+ const response = await dataCatalogRelationshipProposalsList(
+ projectId(),
+ typeof table === 'string' ? { table_name: table } : undefined
+ )
+ breakpoint()
return response.results || []
},
},
],
joins: [
- [] as DataWarehouseViewLink[],
+ [] as CatalogJoin[],
{
loadJoins: async () => {
- const response = await api.dataWarehouseViewLinks.list()
+ const response = await warehouseViewLinksList(projectId())
return response.results || []
},
},
],
})),
reducers({
+ proposalOpen: [false, { openProposal: () => true, closeProposal: () => false }],
+ proposing: [false, { setProposing: (_, { proposing }) => proposing }],
+ proposalDraft: [
+ {
+ source_table_name: '',
+ source_table_key: '',
+ joining_table_name: '',
+ joining_table_key: '',
+ field_name: '',
+ reasoning: '',
+ } as Pick<
+ DataCatalogRelationshipProposalApi,
+ | 'source_table_name'
+ | 'source_table_key'
+ | 'joining_table_name'
+ | 'joining_table_key'
+ | 'field_name'
+ | 'reasoning'
+ >,
+ {
+ openProposal: (_, { table }) => ({
+ source_table_name: table,
+ source_table_key: '',
+ joining_table_name: '',
+ joining_table_key: '',
+ field_name: '',
+ reasoning: '',
+ }),
+ setProposalDraft: (state, { draft }) => ({ ...state, ...draft }),
+ },
+ ],
filters: [
DEFAULT_RELATIONSHIPS_FILTERS as RelationshipsFilters,
{
@@ -229,7 +302,7 @@ export const relationshipsLogic = kea<relationshipsLogicType>([
selectors({
rows: [
(s) => [s.proposals, s.joins],
- (proposals: DataCatalogRelationshipProposalApi[], joins: DataWarehouseViewLink[]): RelationshipRow[] => {
+ (proposals: DataCatalogRelationshipProposalApi[], joins: CatalogJoin[]): RelationshipRow[] => {
const acceptedByJoinId = new Map<string, DataCatalogRelationshipProposalApi>()
proposals
.filter((proposal) => proposal.status === 'accepted' && proposal.created_join)
@@ -313,11 +386,41 @@ export const relationshipsLogic = kea<relationshipsLogicType>([
],
joinsById: [
(s) => [s.joins],
- (joins: DataWarehouseViewLink[]): Record<string, DataWarehouseViewLink> =>
+ (joins: CatalogJoin[]): Record<string, CatalogJoin> =>
Object.fromEntries(joins.map((join) => [join.id, join])),
],
}),
listeners(({ values, actions }) => ({
+ setFilters: ({ filters }) => {
+ const { table, ...search } = router.values.searchParams
+ if (typeof table === 'string' && filters.search !== undefined && filters.search !== table) {
+ router.actions.replace(urls.dataCatalog(), search, router.values.hashParams)
+ }
+ },
+ closeProposal: () => {
+ const { propose_table, ...search } = router.values.searchParams
+ router.actions.replace(urls.dataCatalog(), search, router.values.hashParams)
+ },
+ proposeRelationship: async () => {
+ if (values.proposing) {
+ return
+ }
+ actions.setProposing(true)
+ try {
+ await dataCatalogRelationshipProposalsCreate(
+ projectId(),
+ values.proposalDraft as DataCatalogRelationshipProposalApi
+ )
+ actions.closeProposal()
+ actions.loadProposals()
+ actions.loadPendingCount()
+ lemonToast.success('Relationship proposed for review')
+ } catch (error) {
+ lemonToast.error(apiErrorDetail(error) || 'Could not propose the relationship')
+ } finally {
+ actions.setProposing(false)
+ }
+ },
acceptProposal: async ({ id }) => {
if (values.actionsInFlight[id]) {
return
@@ -367,10 +470,16 @@ export const relationshipsLogic = kea<relationshipsLogicType>([
actions.loadJoins()
},
})),
- urlToAction(({ actions }) => ({
+ urlToAction(({ actions, values }) => ({
// Load the full proposals and joins only when the Relationships tab is actually viewed.
[urls.dataCatalog()]: (_, searchParams) => {
if (searchParams.tab === 'relationships') {
+ if (typeof searchParams.table === 'string') {
+ actions.setFilters({ search: searchParams.table })
+ }
+ if (typeof searchParams.propose_table === 'string' && !values.proposalOpen) {
+ actions.openProposal(searchParams.propose_table)
+ }
actions.loadProposals()
actions.loadJoins()
}
diff --git a/products/data_catalog/frontend/tabs/RelationshipsTab.tsx b/products/data_catalog/frontend/tabs/RelationshipsTab.tsx
index 5b3bb4545e9d..7ba97f1c83e6 100644
--- a/products/data_catalog/frontend/tabs/RelationshipsTab.tsx
+++ b/products/data_catalog/frontend/tabs/RelationshipsTab.tsx
@@ -16,6 +16,7 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { ViewLinkModal } from 'products/data_warehouse/frontend/shared/components/ViewLinkModal'
import { viewLinkLogic } from 'products/data_warehouse/frontend/shared/logics/viewLinkLogic'
+import { RelationshipProposalModal } from '../components/RelationshipProposalModal'
import { RelationshipRow, RelationshipStatusFilter, relationshipsLogic } from '../relationshipsLogic'
const STATUS_FILTER_OPTIONS: { value: RelationshipStatusFilter; label: string }[] = [
@@ -47,7 +48,7 @@ function TableRefCell({ table, refKey }: { table: string; refKey: string }): JSX
export function RelationshipsTab(): JSX.Element {
const { filteredRows, proposalsLoading, joinsLoading, filters, actionsInFlight, joinsById } =
useValues(relationshipsLogic)
- const { setFilters, acceptProposal, rejectProposal, loadProposals, loadJoins, deleteJoin } =
+ const { setFilters, acceptProposal, rejectProposal, loadProposals, loadJoins, deleteJoin, openProposal } =
useActions(relationshipsLogic)
const { toggleNewJoinModal, toggleEditJoinModal } = useActions(viewLinkLogic)
@@ -160,6 +161,7 @@ export function RelationshipsTab(): JSX.Element {
return (
<div className="flex flex-col gap-4">
+ <RelationshipProposalModal />
<div className="flex justify-between gap-2 flex-wrap items-center">
<LemonInput
type="search"
@@ -168,6 +170,9 @@ export function RelationshipsTab(): JSX.Element {
onChange={(search) => setFilters({ search })}
/>
<div className="flex items-center gap-2 flex-wrap">
+ <LemonButton size="small" onClick={() => openProposal()}>
+ Propose a relationship
+ </LemonButton>
<LemonSegmentedButton
value={filters.status}
onChange={(status) => setFilters({ status })}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 02c3b1ad0cd3..590239f14c74 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -122393,9 +122393,17 @@ export namespace Schemas {
* A search term.
*/
search?: string;
+ /**
+ * Only certifications with this review status.
+ */
+ status?: string;
};
export type DataCatalogMetricsListParams = {
+ /**
+ * Only metrics with this query node kind.
+ */
+ definition_kind?: string;
/**
* Number of results to return per page.
*/
@@ -122408,6 +122416,10 @@ export namespace Schemas {
* A search term.
*/
search?: string;
+ /**
+ * Only metrics with this review status.
+ */
+ status?: string;
};
export type DataCatalogMetricsRunCreateParams = {
@@ -122454,6 +122466,10 @@ export namespace Schemas {
* Filter by proposed/accepted/rejected.
*/
status?: string;
+ /**
+ * Only relationships involving this table on either side.
+ */
+ table_name?: string;
};
export type DataColorThemesListParams = {
diff --git a/services/mcp/src/generated/data_catalog/api.ts b/services/mcp/src/generated/data_catalog/api.ts
index e2afca09a0ef..2e1d657a308a 100644
--- a/services/mcp/src/generated/data_catalog/api.ts
+++ b/services/mcp/src/generated/data_catalog/api.ts
@@ -74,9 +74,11 @@ export const DataCatalogMetricsListParams = () => zod.object({
})
export const DataCatalogMetricsListQueryParams = () => zod.object({
+ definition_kind: zod.string().optional().describe('Only metrics with this query node kind.'),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
search: zod.string().optional().describe('A search term.'),
+ status: zod.string().optional().describe('Only metrics with this review status.'),
})
/**
diff --git a/services/mcp/src/tools/generated/data_catalog.ts b/services/mcp/src/tools/generated/data_catalog.ts
index 7330cec0725f..e7c5ad1268b7 100644
--- a/services/mcp/src/tools/generated/data_catalog.ts
+++ b/services/mcp/src/tools/generated/data_catalog.ts
@@ -751,9 +751,11 @@ const metricList = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/data_catalog/metrics/`,
query: {
+ definition_kind: params.definition_kind,
limit: params.limit,
offset: params.offset,
search: params.search,
+ status: params.status,
},
})
const filtered = {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json
index bc560e594d69..a17b6c3fb90c 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/metric-list.json
@@ -1,6 +1,10 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
+ "definition_kind": {
+ "description": "Only metrics with this query node kind.",
+ "type": "string"
+ },
"limit": {
"description": "Number of results to return per page.",
"type": "number"
@@ -12,6 +16,10 @@
"search": {
"description": "A search term.",
"type": "string"
+ },
+ "status": {
+ "description": "Only metrics with this review status.",
+ "type": "string"
}
},
"type": "object"