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.

fix(data-catalog): support dotted warehouse table names (#91040)

Thiago Salvatorefa6167c1373d
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index b67afbeb95cb..4fa10e38ef71 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -1553,11 +1553,13 @@ def _catalog_certification_rows(context: "HogQLContext", allowed: Optional[froze
Returns nothing unless the caller has data_catalog read access. Excludes certifications whose target
is soft-deleted (or orphaned by a soft-deleted source) — matching `certifications_for_team` — and
drops any whose target is denied or invisible to the caller. `allowed` trims the query to the
- pushed-down set of target names.
+ requested set of target names.
"""
team_id = context.team_id
if team_id is None or not _can_read_catalog(context):
return []
+ from posthog.hogql.database.database import get_data_warehouse_table_name # noqa: PLC0415
+
from products.data_catalog.backend.facade.models import TableCertification # noqa: PLC0415
record_catalog_read("certifications")
@@ -1567,21 +1569,25 @@ def _catalog_certification_rows(context: "HogQLContext", allowed: Optional[froze
.exclude(table__deleted=True)
.exclude(table__external_data_source__deleted=True)
.exclude(saved_query__deleted=True)
- .select_related("table", "saved_query", "certified_by")
+ .select_related("table", "table__external_data_source", "saved_query", "certified_by")
.order_by("-created_at")
)
- if allowed is not None:
- certs = certs.filter(Q(table__name__in=allowed) | Q(saved_query__name__in=allowed))
rows: list[list[Any]] = []
for cert in certs:
if cert.table_id is not None:
- target_name = cert.table.name if cert.table else None
+ target_name = (
+ get_data_warehouse_table_name(cert.table.external_data_source, cert.table.name)
+ if cert.table
+ else None
+ )
target_id = str(cert.table_id)
target_kind = "table"
else:
target_name = cert.saved_query.name if cert.saved_query else None
target_id = str(cert.saved_query_id)
target_kind = "view"
+ if allowed is not None and target_name not in allowed:
+ continue
if target_name is None or not _catalog_table_visible(context, target_name):
continue
rows.append(
@@ -1914,7 +1920,10 @@ class InformationSchemaCertificationsTable(InformationSchemaTable):
description: str = _CERTIFICATIONS_DESCRIPTION
fields: dict[str, FieldOrTable] = {
"id": _string_field("id", description="Certification UUID — pass to the certify/deprecate tools."),
- "target_name": _string_field("target_name", description="Name of the certified table or view."),
+ "target_name": _string_field(
+ "target_name",
+ description="Queryable HogQL name of the certified table or view (for example, stripe.subscriptions).",
+ ),
"target_id": _string_field(
"target_id",
description=(
diff --git a/products/data_catalog/backend/facade/api.py b/products/data_catalog/backend/facade/api.py
index 9d9d0464d772..1c8ff9ea8d53 100644
--- a/products/data_catalog/backend/facade/api.py
+++ b/products/data_catalog/backend/facade/api.py
@@ -6,6 +6,7 @@ logic surface and model classes so the isolation boundary stays clean: presentat
into ``logic`` or ``models`` directly.
"""
+from ..logic.analytics import certification_target_name
from ..logic.certifications import (
certifications_for_team,
certify,
@@ -48,6 +49,7 @@ __all__ = [
"approved_metric_names_for_team",
"bulk_approve_metrics",
"bulk_soft_delete_metrics",
+ "certification_target_name",
"certifications_for_team",
"certify",
"compute_drift",
diff --git a/products/data_catalog/backend/logic/analytics.py b/products/data_catalog/backend/logic/analytics.py
index 0eb5a51bf73e..4e54b6f99dd2 100644
--- a/products/data_catalog/backend/logic/analytics.py
+++ b/products/data_catalog/backend/logic/analytics.py
@@ -9,6 +9,8 @@ from people-facing counts.
from typing import TYPE_CHECKING, Any, Optional
+from posthog.hogql.database.database import get_data_warehouse_table_name
+
from posthog.event_usage import get_request_analytics_properties, report_user_action, report_user_or_team_action
from posthog.models import Team, User
@@ -35,7 +37,7 @@ RELATIONSHIP_REJECTED_EVENT = "data catalog relationship rejected"
def certification_target_name(cert: "TableCertification") -> str:
if cert.table_id:
- return cert.table.name if cert.table else ""
+ return get_data_warehouse_table_name(cert.table.external_data_source, cert.table.name) if cert.table else ""
return cert.saved_query.name if cert.saved_query else ""
diff --git a/products/data_catalog/backend/logic/certifications.py b/products/data_catalog/backend/logic/certifications.py
index 3b29124f7462..35ef173c0dcf 100644
--- a/products/data_catalog/backend/logic/certifications.py
+++ b/products/data_catalog/backend/logic/certifications.py
@@ -6,18 +6,22 @@ leave newest-wins duplicates), an ambiguous name returns a 409 listing the candi
picks explicitly. Revocation is a hard delete; both are activity-logged.
"""
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Optional, TypeVar
from uuid import UUID
from django.db import IntegrityError, transaction
-from django.db.models import QuerySet
+from django.db.models import Model, QuerySet
from django.utils import timezone
from rest_framework.exceptions import ValidationError
+from posthog.hogql.database.database import get_data_warehouse_table_name
+
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.scopes import APIScopeObject
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -38,6 +42,8 @@ if TYPE_CHECKING:
_SCOPE = "TableCertification"
+_Target = TypeVar("_Target", bound=Model)
+
def _log(user: Optional[User], cert: TableCertification, activity: str, changes: Optional[list[Change]] = None) -> None:
log_activity(
@@ -56,41 +62,78 @@ def _duplicate_target_conflict(certification: TableCertification) -> CatalogConf
return CatalogConflict(detail=f"This target is already marked '{certification.status}'.")
-def _resolve_table(team: Team, table_id: str | UUID | None, table_name: str | None) -> DataWarehouseTable:
- # queryable() drops soft-deleted tables and those orphaned by a soft-deleted source.
- live = DataWarehouseTable.objects.queryable().filter(team_id=team.id)
+def _visible_targets(
+ uac: Optional[UserAccessControl], team: Team, targets: list[_Target], resource: APIScopeObject
+) -> list[_Target]:
+ if uac is None:
+ return targets
+ if targets:
+ uac.preload_access_levels(team=team, resource=resource)
+ return [target for target in targets if uac.check_access_level_for_object(target, "viewer")]
+
+
+def _resolve_table(
+ team: Team, uac: Optional[UserAccessControl], table_id: str | UUID | None, table_name: str | None
+) -> DataWarehouseTable:
+ # raw_objects skips the default manager's externaldataschema_set prefetch and created_by join,
+ # which this path never reads; queryable() still drops soft-deleted and orphaned tables.
+ live = DataWarehouseTable.raw_objects.queryable().filter(team_id=team.id).select_related("external_data_source")
if table_id:
table = live.filter(id=table_id).first()
- if table is None:
+ if table is None or not _visible_targets(uac, team, [table], "warehouse_table"):
raise ValidationError({"table_id": "Table not found."})
return table
- matches = list(live.filter(name=table_name))
+ matches = list(live.filter(name=table_name).defer("columns"))
+ if table_name is not None and "." in table_name:
+ suffix = table_name.rsplit(".", 1)[-1]
+ matches += [
+ table
+ for table in live.exclude(name=table_name).filter(name__iendswith=suffix).defer("columns")
+ if get_data_warehouse_table_name(table.external_data_source, table.name) == table_name
+ ]
+ matches = _visible_targets(uac, team, matches, "warehouse_table")
if not matches:
raise ValidationError({"table_name": f"No table named '{table_name}'."})
if len(matches) > 1:
raise CatalogConflict(
detail=f"Multiple tables named '{table_name}'. Pass table_id to disambiguate.",
- extra={"candidates": [{"id": str(t.id), "created_at": t.created_at.isoformat()} for t in matches]},
+ extra={
+ "candidates": [
+ {
+ "id": str(table.id),
+ "created_at": table.created_at.isoformat(),
+ "name": table.name,
+ "source_id": str(table.external_data_source_id) if table.external_data_source_id else None,
+ "source_prefix": table.external_data_source.prefix if table.external_data_source else None,
+ }
+ for table in matches
+ ]
+ },
)
return matches[0]
def _resolve_saved_query(
- team: Team, saved_query_id: str | UUID | None, view_name: str | None
+ team: Team, uac: Optional[UserAccessControl], saved_query_id: str | UUID | None, view_name: str | None
) -> DataWarehouseSavedQuery:
live = DataWarehouseSavedQuery.objects.filter(team_id=team.id, deleted=False)
if saved_query_id:
saved_query = live.filter(id=saved_query_id).first()
- if saved_query is None:
+ if saved_query is None or not _visible_targets(uac, team, [saved_query], "warehouse_view"):
raise ValidationError({"saved_query_id": "View not found."})
return saved_query
- matches = list(live.filter(name=view_name))
+ matches = _visible_targets(uac, team, list(live.filter(name=view_name)), "warehouse_view")
if not matches:
raise ValidationError({"view_name": f"No view named '{view_name}'."})
if len(matches) > 1:
raise CatalogConflict(
detail=f"Multiple views named '{view_name}'. Pass saved_query_id to disambiguate.",
- extra={"candidates": [{"id": str(v.id), "created_at": v.created_at.isoformat()} for v in matches]},
+ extra={
+ "candidates": [
+ {"id": str(view.id), "created_at": view.created_at.isoformat(), "name": view.name}
+ for view in matches
+ ]
+ },
)
return matches[0]
@@ -118,11 +161,12 @@ def propose_certification(
if sum(value is not None for value in selectors.values()) != 1:
raise ValidationError({"target": "Provide exactly one of table_id, saved_query_id, table_name, or view_name."})
+ uac = None if user is None else UserAccessControl(user=user, team=team)
target_table = target_saved_query = None
if table_id is not None or table_name is not None:
- target_table = _resolve_table(team, table_id, table_name)
+ target_table = _resolve_table(team, uac, table_id, table_name)
else:
- target_saved_query = _resolve_saved_query(team, saved_query_id, view_name)
+ target_saved_query = _resolve_saved_query(team, uac, saved_query_id, view_name)
certifications = TableCertification.objects.for_team(team.id)
existing = certifications.filter(table=target_table, saved_query=target_saved_query).first()
@@ -190,6 +234,6 @@ def certifications_for_team(team: Team) -> QuerySet[TableCertification]:
.exclude(table__deleted=True)
.exclude(table__external_data_source__deleted=True)
.exclude(saved_query__deleted=True)
- .select_related("table", "saved_query", "certified_by")
+ .select_related("table", "table__external_data_source", "saved_query", "certified_by")
.order_by("-created_at")
)
diff --git a/products/data_catalog/backend/presentation/serializers.py b/products/data_catalog/backend/presentation/serializers.py
index b48f1f064f3c..735b79fc937b 100644
--- a/products/data_catalog/backend/presentation/serializers.py
+++ b/products/data_catalog/backend/presentation/serializers.py
@@ -247,7 +247,7 @@ class CertificationSerializer(serializers.ModelSerializer):
"(avoid this source). Informational once the mark is settled.",
)
target_type = serializers.SerializerMethodField(help_text="Whether the marked target is a 'table' or a 'view'.")
- target_name = serializers.SerializerMethodField(help_text="Name of the marked table or view.")
+ target_name = serializers.SerializerMethodField(help_text="Queryable HogQL name of the marked table or view.")
certified_by = UserBasicSerializer(
read_only=True, allow_null=True, help_text="User who last set certified/deprecated, or null."
)
@@ -287,9 +287,7 @@ class CertificationSerializer(serializers.ModelSerializer):
@extend_schema_field(OpenApiTypes.STR)
def get_target_name(self, obj: TableCertification) -> str:
- if obj.table_id:
- return obj.table.name if obj.table else ""
- return obj.saved_query.name if obj.saved_query else ""
+ return api.certification_target_name(obj)
class CertificationCreateSerializer(serializers.Serializer):
@@ -297,8 +295,12 @@ class CertificationCreateSerializer(serializers.Serializer):
table_id = serializers.UUIDField(required=False, help_text="Warehouse table id to certify (XOR the other targets).")
saved_query_id = serializers.UUIDField(required=False, help_text="Warehouse view (saved query) id to certify.")
- table_name = serializers.CharField(required=False, help_text="Table name; 409 with candidates if ambiguous.")
- view_name = serializers.CharField(required=False, help_text="View name; 409 with candidates if ambiguous.")
+ table_name = serializers.CharField(
+ required=False, help_text="Queryable HogQL table name; 409 with candidates if ambiguous."
+ )
+ view_name = serializers.CharField(
+ required=False, help_text="Queryable HogQL view name; 409 with candidates if ambiguous."
+ )
notes = serializers.CharField(required=False, allow_blank=True, help_text="Why this mark exists.")
proposed_status = serializers.ChoiceField(
choices=["certified", "deprecated"],
diff --git a/products/data_catalog/backend/presentation/views.py b/products/data_catalog/backend/presentation/views.py
index 2f014fe7b182..5a31915f5792 100644
--- a/products/data_catalog/backend/presentation/views.py
+++ b/products/data_catalog/backend/presentation/views.py
@@ -277,8 +277,16 @@ class CertificationViewSet(
return api.certifications_for_team(self.team)
def dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str] | None:
- if getattr(view, "action", None) == "destroy":
+ action = getattr(view, "action", None)
+ if action == "destroy":
return ["data_catalog_approval:write", "data_catalog:read"]
+ if action == "create" and isinstance(request.data, dict):
+ scopes = ["data_catalog:write"]
+ if request.data.get("table_id") or request.data.get("table_name"):
+ scopes.append("warehouse_table:read")
+ if request.data.get("saved_query_id") or request.data.get("view_name"):
+ scopes.append("warehouse_view:read")
+ return scopes if len(scopes) > 1 else None
return None
@extend_schema(request=CertificationCreateSerializer, responses={201: CertificationSerializer})
diff --git a/products/data_catalog/backend/tests/test_certifications.py b/products/data_catalog/backend/tests/test_certifications.py
index c214c631d8bd..c5710d743d7c 100644
--- a/products/data_catalog/backend/tests/test_certifications.py
+++ b/products/data_catalog/backend/tests/test_certifications.py
@@ -53,10 +53,30 @@ def _table(
)
+def _external_source(team: Team, source_id: str = "stripe", prefix: str | None = None) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team,
+ source_id=source_id,
+ connection_id=source_id,
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type="Stripe",
+ prefix=prefix,
+ )
+
+
def _view(team: Team, name: str = "revenue_view") -> DataWarehouseSavedQuery:
return DataWarehouseSavedQuery.objects.create(team=team, name=name, query={"kind": "HogQLQuery"})
+_CHECK_ACCESS = (
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_object"
+)
+
+
+def _deny_warehouse_targets(obj: Any = None, *args: Any, **kwargs: Any) -> bool:
+ return type(obj).__name__ not in ("DataWarehouseTable", "DataWarehouseSavedQuery")
+
+
class TestTableCertificationModel(BaseTest):
def test_requires_exactly_one_target(self) -> None:
table = _table(self.team)
@@ -93,6 +113,32 @@ class TestCertificationLogic(BaseTest):
assert certification.table_id == (target.id if target_type == "table" else None)
assert certification.saved_query_id == (target.id if target_type == "view" else None)
+ @parameterized.expand(
+ [
+ ("dotted", "stripe_subscriptions", None, "stripe.subscriptions", True),
+ ("prefixed", "stripe_subscriptions", "prod_", "stripe.prod.subscriptions", True),
+ ("raw", "stripe_subscriptions", None, "stripe_subscriptions", True),
+ ("mixed_case_stored_name", "Stripe_Subscriptions", None, "stripe.subscriptions", True),
+ ("missing_dotted", "stripe_subscriptions", None, "stripe.refunds", False),
+ ]
+ )
+ def test_propose_by_external_table_name(
+ self, _name: str, table_name: str, source_prefix: str | None, selector: str, found: bool
+ ) -> None:
+ table = _table(
+ self.team, name=table_name, external_data_source=_external_source(self.team, prefix=source_prefix)
+ )
+
+ if not found:
+ with self.assertRaises(ValidationError) as error:
+ propose_certification(team=self.team, user=self.user, table_name=selector)
+ assert "table_name" in error.exception.detail
+ return
+
+ certification = propose_certification(team=self.team, user=self.user, table_name=selector)
+
+ assert certification.table_id == table.id
+
def test_propose_deprecation_records_intent_and_settles(self) -> None:
table = _table(self.team)
cert = propose_certification(
@@ -109,10 +155,67 @@ class TestCertificationLogic(BaseTest):
propose_certification(team=self.team, user=self.user, table_id=str(table.id), proposed_status="proposed")
def test_ambiguous_table_name_returns_candidates(self) -> None:
- _table(self.team, name="dupe")
- _table(self.team, name="dupe")
- with self.assertRaises(CatalogConflict):
- propose_certification(team=self.team, user=self.user, table_name="dupe")
+ first_source = _external_source(self.team, source_id="stripe-first")
+ second_source = _external_source(self.team, source_id="stripe-second")
+ first_table = _table(self.team, name="stripe_subscriptions", external_data_source=first_source)
+ second_table = _table(self.team, name="stripe_subscriptions", external_data_source=second_source)
+
+ with self.assertRaises(CatalogConflict) as error:
+ propose_certification(team=self.team, user=self.user, table_name="stripe.subscriptions")
+
+ candidates = error.exception.extra["candidates"]
+ assert {candidate["id"] for candidate in candidates} == {str(first_table.id), str(second_table.id)}
+ assert {candidate["name"] for candidate in candidates} == {"stripe_subscriptions"}
+ assert {candidate["source_id"] for candidate in candidates} == {str(first_source.id), str(second_source.id)}
+ assert {candidate["source_prefix"] for candidate in candidates} == {None}
+
+ @parameterized.expand(
+ [("table_id", "table"), ("table_name", "table"), ("saved_query_id", "view"), ("view_name", "view")]
+ )
+ def test_denied_target_reads_as_missing(self, selector: str, target_type: str) -> None:
+ target = _table(self.team) if target_type == "table" else _view(self.team)
+ selector_kwargs: dict[str, Any] = {selector: str(target.id) if selector.endswith("_id") else target.name}
+
+ with patch(_CHECK_ACCESS, side_effect=_deny_warehouse_targets):
+ with self.assertRaises(ValidationError):
+ propose_certification(team=self.team, user=self.user, **selector_kwargs)
+
+ assert not TableCertification.objects.for_team(self.team.id).exists()
+
+ def test_mixed_visibility_dotted_name_resolves_to_visible_candidate(self) -> None:
+ visible = _table(
+ self.team, name="stripe_subscriptions", external_data_source=_external_source(self.team, source_id="a")
+ )
+ hidden = _table(
+ self.team, name="stripe_subscriptions", external_data_source=_external_source(self.team, source_id="b")
+ )
+
+ with patch(_CHECK_ACCESS, side_effect=lambda obj=None, *a, **k: getattr(obj, "id", None) != hidden.id):
+ certification = propose_certification(team=self.team, user=self.user, table_name="stripe.subscriptions")
+
+ assert certification.table_id == visible.id
+
+ def test_all_denied_dotted_candidates_read_as_missing(self) -> None:
+ for source_id in ("a", "b"):
+ _table(
+ self.team,
+ name="stripe_subscriptions",
+ external_data_source=_external_source(self.team, source_id=source_id),
+ )
+
+ with patch(_CHECK_ACCESS, side_effect=_deny_warehouse_targets):
+ with self.assertRaises(ValidationError) as error:
+ propose_certification(team=self.team, user=self.user, table_name="stripe.subscriptions")
+
+ assert "table_name" in error.exception.detail
+
+ def test_system_caller_bypasses_object_access(self) -> None:
+ table = _table(self.team)
+
+ with patch(_CHECK_ACCESS, side_effect=AssertionError("system callers must skip the access check")):
+ certification = propose_certification(team=self.team, user=None, table_id=str(table.id))
+
+ assert certification.table_id == table.id
@parameterized.expand([("table_id", "table"), ("saved_query_id", "view")])
def test_duplicate_target_conflicts(self, selector: str, target_type: str) -> None:
@@ -202,7 +305,8 @@ class TestCertificationLogic(BaseTest):
assert certifications_for_team(self.team).count() == 0
def test_serializes_mixed_certifications_in_one_query(self) -> None:
- table_certification = propose_certification(team=self.team, user=self.user, table_id=str(_table(self.team).id))
+ table = _table(self.team, name="stripe_subscriptions", external_data_source=_external_source(self.team))
+ table_certification = propose_certification(team=self.team, user=self.user, table_id=str(table.id))
certify(table_certification, self.user)
propose_certification(team=self.team, user=self.user, saved_query_id=str(_view(self.team).id))
@@ -210,6 +314,10 @@ class TestCertificationLogic(BaseTest):
serialized = CertificationSerializer(certifications_for_team(self.team), many=True).data
assert {certification["target_type"] for certification in serialized} == {"table", "view"}
+ assert {certification["target_name"] for certification in serialized} == {
+ "stripe.subscriptions",
+ "revenue_view",
+ }
assert any(certification["certified_by"] is None for certification in serialized)
def test_proposal_stays_in_the_requested_environment(self) -> None:
@@ -358,6 +466,30 @@ class TestCertificationAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
+ @parameterized.expand(
+ [
+ ("table_with_read", "table", ["data_catalog:write", "warehouse_table:read"], status.HTTP_201_CREATED),
+ ("table_without_read", "table", ["data_catalog:write"], status.HTTP_403_FORBIDDEN),
+ ("table_wrong_read", "table", ["data_catalog:write", "warehouse_view:read"], status.HTTP_403_FORBIDDEN),
+ ("view_with_read", "view", ["data_catalog:write", "warehouse_view:read"], status.HTTP_201_CREATED),
+ ("view_without_read", "view", ["data_catalog:write"], status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ def test_create_requires_selector_read_scope(
+ self, _name: str, target_type: str, scopes: list[str], expected_status: int
+ ) -> None:
+ target = _table(self.team) if target_type == "table" else _view(self.team)
+ selector = "table_id" if target_type == "table" else "saved_query_id"
+ raw = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="k", user=self.user, secure_value=hash_key_value(raw), scopes=scopes)
+ self.client.logout()
+
+ response = self.client.post(
+ self.url, {selector: str(target.id)}, format="json", HTTP_AUTHORIZATION=f"Bearer {raw}"
+ )
+
+ assert response.status_code == expected_status, response.content
+
@parameterized.expand([("put",), ("patch",)])
def test_update_methods_not_allowed(self, method: str) -> None:
table = _table(self.team)
diff --git a/products/data_catalog/backend/tests/test_information_schema.py b/products/data_catalog/backend/tests/test_information_schema.py
index 94a46bf9968e..7174a375d665 100644
--- a/products/data_catalog/backend/tests/test_information_schema.py
+++ b/products/data_catalog/backend/tests/test_information_schema.py
@@ -814,6 +814,38 @@ class TestInformationSchemaCertificationsAndRelationships(ClickhouseTestMixin, A
)
assert response.results == [("cert_push_view",)]
+ @parameterized.expand(
+ [
+ ("raw", "cert_push_table", "cert_push_table"),
+ ("dotted", "stripe_cert_push_table", "stripe.cert_push_table"),
+ ]
+ )
+ def test_certifications_table_target_name_pushdown_keeps_table_rows(
+ self, _name: str, raw_name: str, target_name: str
+ ) -> None:
+ external_data_source = None
+ if target_name != raw_name:
+ external_data_source = ExternalDataSource.objects.create(
+ team=self.team, source_type=ExternalDataSourceType.STRIPE
+ )
+ table = DataWarehouseTable.objects.create(
+ name=raw_name,
+ format="Parquet",
+ team=self.team,
+ external_data_source=external_data_source,
+ url_pattern=f"s3://bucket/{raw_name}",
+ columns=_COLUMNS,
+ )
+ propose_certification(team=self.team, user=self.user, table_id=str(table.id))
+
+ response = execute_hogql_query(
+ f"SELECT target_name FROM system.information_schema.certifications WHERE target_name = '{target_name}'",
+ team=self.team,
+ context=self._context(),
+ )
+
+ assert response.results == [(target_name,)]
+
def test_certifications_table_team_isolation(self) -> None:
other = Team.objects.create_with_data(organization=self.organization, initiating_user=self.user, name="Other")
table = DataWarehouseTable.objects.create(
diff --git a/products/data_catalog/frontend/certificationsLogic.test.ts b/products/data_catalog/frontend/certificationsLogic.test.ts
index e57c552b888d..372e2c95b9de 100644
--- a/products/data_catalog/frontend/certificationsLogic.test.ts
+++ b/products/data_catalog/frontend/certificationsLogic.test.ts
@@ -1,10 +1,11 @@
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { initKeaTests } from '~/test/init'
import { expectLogic } from '~/test/keaTestUtils'
import { certificationsLogic } from './certificationsLogic'
-import type { CertificationsFilters } from './certificationsLogic'
+import type { CertificationsFilters, NewCertificationForm } from './certificationsLogic'
import {
dataCatalogCertificationsCertifyCreate,
dataCatalogCertificationsCreate,
@@ -120,22 +121,49 @@ describe('certificationsLogic', () => {
expect(mockLoadDatabase).toHaveBeenCalledWith({ force: true })
})
- it('sends the proposal intent when creating', async () => {
+ it.each<[string, Partial<NewCertificationForm>, Record<string, string>]>([
+ [
+ 'a table id',
+ { targetId: 'table-id', targetName: 'stale_revenue', targetType: 'table' },
+ { table_id: 'table-id' },
+ ],
+ [
+ 'a view id',
+ { targetId: 'view-id', targetName: 'stale_revenue', targetType: 'view' },
+ { saved_query_id: 'view-id' },
+ ],
+ [
+ 'a target name without an id',
+ { targetName: 'stale_revenue', targetType: 'table' },
+ { table_name: 'stale_revenue' },
+ ],
+ ])('sends the proposal intent with %s when creating', async (_description, form, target) => {
;(dataCatalogCertificationsCreate as jest.Mock).mockResolvedValue(
buildCertification({ id: 'cert-3', status: 'proposed' })
)
- logic.actions.setNewCertificationForm({ targetName: 'stale_revenue', proposedStatus: 'deprecated' })
+ logic.actions.setNewCertificationForm({ ...form, proposedStatus: 'deprecated' })
logic.actions.createCertification()
await expectLogic(logic).toFinishAllListeners()
expect(dataCatalogCertificationsCreate).toHaveBeenCalledWith('1', {
- table_name: 'stale_revenue',
+ ...target,
notes: undefined,
proposed_status: 'deprecated',
})
})
+ it('shows an error and resets the submitting state when creation fails', async () => {
+ ;(dataCatalogCertificationsCreate as jest.Mock).mockRejectedValue(new Error('Request failed'))
+
+ logic.actions.setNewCertificationForm({ targetId: 'table-id', targetName: 'stale_revenue' })
+ logic.actions.createCertification()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(lemonToast.error).toHaveBeenCalledWith('Could not create the proposal. Try again.')
+ expect(logic.values.isCreatingCertification).toBe(false)
+ })
+
it('removes the row when revoking', async () => {
;(dataCatalogCertificationsDestroy as jest.Mock).mockResolvedValue(undefined)
diff --git a/products/data_catalog/frontend/certificationsLogic.tsx b/products/data_catalog/frontend/certificationsLogic.tsx
index 07a483f29146..eb5e03b08cf8 100644
--- a/products/data_catalog/frontend/certificationsLogic.tsx
+++ b/products/data_catalog/frontend/certificationsLogic.tsx
@@ -30,6 +30,7 @@ export const DEFAULT_CERTIFICATIONS_FILTERS: CertificationsFilters = {
}
export interface NewCertificationForm {
+ targetId: string
targetName: string
targetType: CertificationTargetType
notes: string
@@ -37,6 +38,7 @@ export interface NewCertificationForm {
}
export const EMPTY_NEW_CERTIFICATION_FORM: NewCertificationForm = {
+ targetId: '',
targetName: '',
targetType: 'table',
notes: '',
@@ -263,9 +265,13 @@ export const certificationsLogic = kea<certificationsLogicType>([
const form = values.newCertificationForm
try {
const created = await dataCatalogCertificationsCreate(projectId(), {
- ...(form.targetType === 'view'
- ? { view_name: form.targetName }
- : { table_name: form.targetName }),
+ ...(form.targetId
+ ? form.targetType === 'view'
+ ? { saved_query_id: form.targetId }
+ : { table_id: form.targetId }
+ : form.targetType === 'view'
+ ? { view_name: form.targetName }
+ : { table_name: form.targetName }),
notes: form.notes || undefined,
proposed_status: form.proposedStatus,
})
diff --git a/products/data_catalog/frontend/components/NewCertificationModal.tsx b/products/data_catalog/frontend/components/NewCertificationModal.tsx
index 4545691cc176..71d9effc5abe 100644
--- a/products/data_catalog/frontend/components/NewCertificationModal.tsx
+++ b/products/data_catalog/frontend/components/NewCertificationModal.tsx
@@ -10,7 +10,8 @@ import { databaseTableListLogic } from 'scenes/data-management/database/database
import { CertificationTargetType, ProposedStatus, certificationsLogic } from '../certificationsLogic'
-const VIEW_TABLE_TYPES = new Set(['view', 'materialized_view', 'managed_view'])
+// TODO: Managed-view certification needs its own target column and migration.
+const VIEW_TABLE_TYPES = new Set(['view', 'materialized_view'])
function targetTypeForTable(tableType: string): CertificationTargetType | null {
if (tableType === 'data_warehouse') {
@@ -37,6 +38,7 @@ export function NewCertificationModal(): JSX.Element {
)
.map(({ table, targetType }) => ({
value: `${targetType}:${table.name}`,
+ id: table.id,
name: table.name,
targetType,
}))
@@ -70,6 +72,7 @@ export function NewCertificationModal(): JSX.Element {
const selected = optionEntries.find((entry) => entry.value === value)
setNewCertificationForm({
targetName: selected?.name ?? '',
+ targetId: selected?.id ?? '',
targetType: selected?.targetType ?? 'table',
})
}}
diff --git a/products/data_catalog/frontend/generated/api.schemas.ts b/products/data_catalog/frontend/generated/api.schemas.ts
index 20ddd246f2a2..c3435f899010 100644
--- a/products/data_catalog/frontend/generated/api.schemas.ts
+++ b/products/data_catalog/frontend/generated/api.schemas.ts
@@ -78,7 +78,7 @@ export interface DataCatalogCertificationApi {
readonly saved_query: string | null
/** Whether the marked target is a 'table' or a 'view'. */
readonly target_type: string
- /** Name of the marked table or view. */
+ /** Queryable HogQL name of the marked table or view. */
readonly target_name: string
/** proposed, certified (prefer this source), or deprecated (avoid this source). */
readonly status: string
@@ -123,9 +123,9 @@ export interface CertificationCreateApi {
table_id?: string
/** Warehouse view (saved query) id to certify. */
saved_query_id?: string
- /** Table name; 409 with candidates if ambiguous. */
+ /** Queryable HogQL table name; 409 with candidates if ambiguous. */
table_name?: string
- /** View name; 409 with candidates if ambiguous. */
+ /** Queryable HogQL view name; 409 with candidates if ambiguous. */
view_name?: string
/** Why this mark exists. */
notes?: string
diff --git a/products/data_catalog/frontend/generated/api.zod.ts b/products/data_catalog/frontend/generated/api.zod.ts
index 3ac2430ab756..bccd4e4ff885 100644
--- a/products/data_catalog/frontend/generated/api.zod.ts
+++ b/products/data_catalog/frontend/generated/api.zod.ts
@@ -18,8 +18,8 @@ export const DataCatalogCertificationsCreateBody = /* @__PURE__ */ zod
.object({
table_id: zod.uuid().optional().describe('Warehouse table id to certify (XOR the other targets).'),
saved_query_id: zod.uuid().optional().describe('Warehouse view (saved query) id to certify.'),
- table_name: zod.string().optional().describe('Table name; 409 with candidates if ambiguous.'),
- view_name: zod.string().optional().describe('View name; 409 with candidates if ambiguous.'),
+ table_name: zod.string().optional().describe('Queryable HogQL table name; 409 with candidates if ambiguous.'),
+ view_name: zod.string().optional().describe('Queryable HogQL view name; 409 with candidates if ambiguous.'),
notes: zod.string().optional().describe('Why this mark exists.'),
proposed_status: zod
.enum(['certified', 'deprecated'])
diff --git a/products/data_catalog/skills/setting-up-data-catalog/SKILL.md b/products/data_catalog/skills/setting-up-data-catalog/SKILL.md
index e21fedb83d8d..df5397573296 100644
--- a/products/data_catalog/skills/setting-up-data-catalog/SKILL.md
+++ b/products/data_catalog/skills/setting-up-data-catalog/SKILL.md
@@ -34,7 +34,8 @@ Work top-down, stopping at `proposed` for everything (a human promotes later):
clearly relies on, `posthog:data-catalog-certification-propose` them (the tool's default
`proposed_status` is `'certified'`); flag obvious stale or duplicate copies by proposing them with
`proposed_status: 'deprecated'`. Either way the proposal lands unapproved and an approver settles
- it later. Address targets by id when a name is ambiguous.
+ it later. Warehouse-source tables accept their queryable HogQL name (for example,
+ `stripe.subscriptions`); address targets by id when a name is ambiguous.
2. **Discover joins with evidence.** For plausible table pairs, sample both sides with
`posthog:execute-sql` to measure the match rate of a candidate key (e.g. `count(DISTINCT a.key)`
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 64695cbefb3e..2e52417f5355 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -124,7 +124,7 @@ warehouse_sources.DataWarehouseTable posthog.hogql.direct_connection instance-ma
warehouse_sources.DataWarehouseTable posthog.hogql_queries.access_controlled_resources instance-many(only) 1
warehouse_sources.DataWarehouseTable posthog.tasks.usage_report instance-many(annotate) 2
warehouse_sources.DataWarehouseTable posthog.temporal.data_modeling.run_workflow instance-single 2
-warehouse_sources.DataWarehouseTable products.data_catalog.backend.logic.certifications instance-many(filter) 1
+warehouse_sources.DataWarehouseTable products.data_catalog.backend.logic.certifications instance-many(select_related) 1
warehouse_sources.DataWarehouseTable products.data_catalog.evals.seeders instance-many(filter) 1
warehouse_sources.DataWarehouseTable products.data_catalog.evals.seeders write(create) 1
warehouse_sources.DataWarehouseTable products.data_modeling.backend.logic.node_frequency instance-many(exclude) 1
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 02529c598eca..68f281a10549 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -16846,9 +16846,9 @@ export namespace Schemas {
table_id?: string;
/** Warehouse view (saved query) id to certify. */
saved_query_id?: string;
- /** Table name; 409 with candidates if ambiguous. */
+ /** Queryable HogQL table name; 409 with candidates if ambiguous. */
table_name?: string;
- /** View name; 409 with candidates if ambiguous. */
+ /** Queryable HogQL view name; 409 with candidates if ambiguous. */
view_name?: string;
/** Why this mark exists. */
notes?: string;
@@ -20945,7 +20945,7 @@ export namespace Schemas {
readonly saved_query: string | null;
/** Whether the marked target is a 'table' or a 'view'. */
readonly target_type: string;
- /** Name of the marked table or view. */
+ /** Queryable HogQL name of the marked table or view. */
readonly target_name: string;
/** proposed, certified (prefer this source), or deprecated (avoid this source). */
readonly status: string;
diff --git a/services/mcp/src/generated/data_catalog/api.ts b/services/mcp/src/generated/data_catalog/api.ts
index fd79c656115a..c6f5adff1de3 100644
--- a/services/mcp/src/generated/data_catalog/api.ts
+++ b/services/mcp/src/generated/data_catalog/api.ts
@@ -25,8 +25,8 @@ export const DataCatalogCertificationsCreateBody = /* @__PURE__ */ zod
.object({
table_id: zod.string().optional().describe('Warehouse table id to certify (XOR the other targets).'),
saved_query_id: zod.string().optional().describe('Warehouse view (saved query) id to certify.'),
- table_name: zod.string().optional().describe('Table name; 409 with candidates if ambiguous.'),
- view_name: zod.string().optional().describe('View name; 409 with candidates if ambiguous.'),
+ table_name: zod.string().optional().describe('Queryable HogQL table name; 409 with candidates if ambiguous.'),
+ view_name: zod.string().optional().describe('Queryable HogQL view name; 409 with candidates if ambiguous.'),
notes: zod.string().optional().describe('Why this mark exists.'),
proposed_status: zod
.enum(['certified', 'deprecated'])
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/data-catalog-certification-propose.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-catalog-certification-propose.json
index d674b995db7c..48c8c5b0e52d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/data-catalog-certification-propose.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/data-catalog-certification-propose.json
@@ -21,11 +21,11 @@
"type": "string"
},
"table_name": {
- "description": "Table name; 409 with candidates if ambiguous.",
+ "description": "Queryable HogQL table name; 409 with candidates if ambiguous.",
"type": "string"
},
"view_name": {
- "description": "View name; 409 with candidates if ambiguous.",
+ "description": "Queryable HogQL view name; 409 with candidates if ambiguous.",
"type": "string"
}
},