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(customer-analytics): expose account relationships in HogQL (#68669)

Arthur Moreira de Deus9c41da2a0630
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.py
index 592006464410..deb6a5d7e336 100644
--- a/posthog/hogql/database/lazy_join_registry.py
+++ b/posthog/hogql/database/lazy_join_registry.py
@@ -34,6 +34,7 @@ from posthog.hogql.database.warehouse_join_resolvers import (
from products.customer_analytics.backend.facade.hogql import (
account_custom_properties_join,
account_notebooks_join,
+ account_relationships_join,
account_tags_join,
)
@@ -77,6 +78,7 @@ RESOLVERS: dict[str, LazyJoinResolver] = {
tags.ACCOUNT_TAGS: account_tags_join,
tags.ACCOUNT_NOTEBOOKS: account_notebooks_join,
tags.ACCOUNT_CUSTOM_PROPERTIES: account_custom_properties_join,
+ tags.ACCOUNT_RELATIONSHIPS: account_relationships_join,
}
diff --git a/posthog/hogql/database/lazy_join_tags.py b/posthog/hogql/database/lazy_join_tags.py
index 3ce9f71e473a..a82d88ba47fb 100644
--- a/posthog/hogql/database/lazy_join_tags.py
+++ b/posthog/hogql/database/lazy_join_tags.py
@@ -26,3 +26,4 @@ ERROR_TRACKING_FINGERPRINT_ISSUE_STATE = "error_tracking_fingerprint_issue_state
ACCOUNT_TAGS = "account_tags"
ACCOUNT_NOTEBOOKS = "account_notebooks"
ACCOUNT_CUSTOM_PROPERTIES = "account_custom_properties"
+ACCOUNT_RELATIONSHIPS = "account_relationships"
diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.py
index 4dbc469a789d..3173a29da81d 100644
--- a/posthog/hogql/database/schema/system.py
+++ b/posthog/hogql/database/schema/system.py
@@ -24,6 +24,8 @@ from posthog.scopes import APIScopeObject
from products.customer_analytics.backend.facade.hogql import (
account_custom_property_values,
+ account_relationship_definitions,
+ account_relationships,
account_resource_notebooks,
account_tagged_items,
accounts,
@@ -2015,6 +2017,10 @@ class SystemTables(TableNode):
"_account_custom_property_values": TableNode(
name="_account_custom_property_values", table=account_custom_property_values, hidden=True
),
+ "account_relationship_definitions": TableNode(
+ name="account_relationship_definitions", table=account_relationship_definitions
+ ),
+ "account_relationships": TableNode(name="account_relationships", table=account_relationships),
"activity_logs": TableNode(name="activity_logs", table=activity_logs),
"actions": TableNode(name="actions", table=actions),
"alerts": TableNode(name="alerts", table=alerts),
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 2dafb6d6bb0d..50bec114ad39 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING
from posthog.test.base import BaseTest, NonAtomicBaseTest
from django.apps import apps
+from django.utils import timezone
from parameterized import parameterized
@@ -59,6 +60,10 @@ if TYPE_CHECKING:
from products.customer_analytics.backend.models.account import Account
from products.customer_analytics.backend.models.custom_property_definition import CustomPropertyDefinition
from products.customer_analytics.backend.models.custom_property_value import CustomPropertyValue
+ from products.customer_analytics.backend.models.relationship import (
+ AccountRelationship,
+ AccountRelationshipDefinition,
+ )
from products.error_tracking.backend.models import (
ErrorTrackingAssignmentRule,
ErrorTrackingBypassRule,
@@ -73,6 +78,8 @@ else:
Account = apps.get_model("customer_analytics", "Account")
CustomPropertyDefinition = apps.get_model("customer_analytics", "CustomPropertyDefinition")
CustomPropertyValue = apps.get_model("customer_analytics", "CustomPropertyValue")
+ AccountRelationship = apps.get_model("customer_analytics", "AccountRelationship")
+ AccountRelationshipDefinition = apps.get_model("customer_analytics", "AccountRelationshipDefinition")
ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
ErrorTrackingSymbolSet = apps.get_model("error_tracking", "ErrorTrackingSymbolSet")
ErrorTrackingIssueAssignment = apps.get_model("error_tracking", "ErrorTrackingIssueAssignment")
@@ -187,6 +194,16 @@ def _create_custom_property_definition(team: Team, label: str) -> "CustomPropert
return CustomPropertyDefinition.objects.unscoped().create(team=team, name=f"def_{label}", display_type="text")
+def _create_account_relationship(team: Team, label: str) -> "AccountRelationship":
+ account = Account.objects.unscoped().create(team=team, name=f"account_{label}")
+ definition = AccountRelationshipDefinition.objects.unscoped().create(team=team, name=f"rel_{label}")
+ return AccountRelationship.objects.unscoped().create(team=team, account=account, definition=definition)
+
+
+def _create_account_relationship_definition(team: Team, label: str) -> "AccountRelationshipDefinition":
+ return AccountRelationshipDefinition.objects.unscoped().create(team=team, name=f"rel_def_{label}")
+
+
def _create_action(team: Team, label: str) -> Action:
return Action.objects.create(team=team, name=f"action_{label}")
@@ -641,6 +658,8 @@ def _create_business_knowledge_chunk(team: Team, label: str):
SYSTEM_TABLE_FACTORIES = [
+ ("account_relationship_definitions", _create_account_relationship_definition),
+ ("account_relationships", _create_account_relationship),
("accounts", _create_account),
("activity_logs", _create_activity_log),
("actions", _create_action),
@@ -983,3 +1002,71 @@ class TestSystemAccountsLazyJoins(NonAtomicBaseTest):
assert str(account.id) in rows_by_id
assert rows_by_id[str(account.id)] != "secret"
assert rows_by_id[str(account.id)] in (None, "")
+
+ def _create_relationship_definition(self, name="CSM", **kwargs):
+ return AccountRelationshipDefinition.objects.unscoped().create(team=self.team, name=name, **kwargs)
+
+ def _create_relationship(self, account, definition, user, **kwargs):
+ return AccountRelationship.objects.unscoped().create(
+ team=self.team, account=account, definition=definition, user=user, **kwargs
+ )
+
+ def test_relationships_lazy_join_returns_active_user_ids_by_definition_id(self):
+ account = Account.objects.unscoped().create(team=self.team, name="A")
+ definition = self._create_relationship_definition()
+ self._create_relationship(account, definition, self.user)
+ Account.objects.unscoped().create(team=self.team, name="B") # no relationships
+
+ response = execute_hogql_query(
+ f"SELECT id, accounts.relationships.values.`{definition.id}` "
+ "FROM system.accounts AS accounts ORDER BY name",
+ team=self.team,
+ user=self.user,
+ )
+ rows_by_id = {str(row[0]): row[1] for row in response.results}
+
+ assert rows_by_id[str(account.id)] == [self.user.id]
+
+ def test_relationships_lazy_join_excludes_ended_rows(self):
+ account = Account.objects.unscoped().create(team=self.team, name="A")
+ definition = self._create_relationship_definition()
+ self._create_relationship(account, definition, self.user, ended_at=timezone.now())
+
+ response = execute_hogql_query(
+ f"SELECT accounts.relationships.values.`{definition.id}` FROM system.accounts AS accounts",
+ team=self.team,
+ user=self.user,
+ )
+ assert response.results[0][0] in ([], None)
+
+ def test_relationships_lazy_join_multi_holder_returns_all_active(self):
+ account = Account.objects.unscoped().create(team=self.team, name="A")
+ definition = self._create_relationship_definition(name="FDE", is_single_holder=False)
+ other_user = self._create_user("[email protected]")
+ self._create_relationship(account, definition, self.user)
+ self._create_relationship(account, definition, other_user)
+
+ response = execute_hogql_query(
+ f"SELECT accounts.relationships.values.`{definition.id}` FROM system.accounts AS accounts",
+ team=self.team,
+ user=self.user,
+ )
+ assert sorted(response.results[0][0]) == sorted([self.user.id, other_user.id])
+
+ def test_relationships_lazy_join_isolated_per_team(self):
+ account = Account.objects.unscoped().create(team=self.team, name="Ours")
+ other_account = Account.objects.unscoped().create(team=self.other_team, name="Theirs")
+ other_definition = AccountRelationshipDefinition.objects.unscoped().create(team=self.other_team, name="CSM")
+ AccountRelationship.objects.unscoped().create(
+ team=self.other_team, account=other_account, definition=other_definition, user=self.user
+ )
+
+ response = execute_hogql_query(
+ f"SELECT id, accounts.relationships.values.`{other_definition.id}` FROM system.accounts AS accounts",
+ team=self.team,
+ user=self.user,
+ )
+ rows_by_id = {str(row[0]): row[1] for row in response.results}
+
+ assert str(account.id) in rows_by_id
+ assert rows_by_id[str(account.id)] in ([], None)
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index 1b6fbeb321cf..fcf382859560 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -2741,6 +2741,19 @@
"schema_valid": true,
"table": "account_custom_properties",
"type": "lazy_table"
+ },
+ "relationships": {
+ "chain": null,
+ "fields": [
+ "account_id",
+ "values"
+ ],
+ "hogql_value": "relationships",
+ "id": "relationships",
+ "name": "relationships",
+ "schema_valid": true,
+ "table": "account_relationships",
+ "type": "lazy_table"
}
},
"id": "system.accounts",
@@ -2748,6 +2761,172 @@
"row_count": null,
"type": "system"
},
+ "system.account_relationship_definitions": {
+ "fields": {
+ "id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "id",
+ "id": null,
+ "name": "id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "name": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "name",
+ "id": null,
+ "name": "name",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "description": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "description",
+ "id": null,
+ "name": "description",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "is_single_holder": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "is_single_holder",
+ "id": null,
+ "name": "is_single_holder",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "updated_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "updated_at",
+ "id": null,
+ "name": "updated_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.account_relationship_definitions",
+ "name": "system.account_relationship_definitions",
+ "row_count": null,
+ "type": "system"
+ },
+ "system.account_relationships": {
+ "fields": {
+ "id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "id",
+ "id": null,
+ "name": "id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "definition_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "definition_id",
+ "id": null,
+ "name": "definition_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "account_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "account_id",
+ "id": null,
+ "name": "account_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "user_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "user_id",
+ "id": null,
+ "name": "user_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "started_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "started_at",
+ "id": null,
+ "name": "started_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "ended_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "ended_at",
+ "id": null,
+ "name": "ended_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.account_relationships",
+ "name": "system.account_relationships",
+ "row_count": null,
+ "type": "system"
+ },
"system.activity_logs": {
"fields": {
"id": {
@@ -11347,6 +11526,19 @@
"schema_valid": true,
"table": "account_custom_properties",
"type": "lazy_table"
+ },
+ "relationships": {
+ "chain": null,
+ "fields": [
+ "account_id",
+ "values"
+ ],
+ "hogql_value": "relationships",
+ "id": "relationships",
+ "name": "relationships",
+ "schema_valid": true,
+ "table": "account_relationships",
+ "type": "lazy_table"
}
},
"id": "system.accounts",
@@ -11354,6 +11546,172 @@
"row_count": null,
"type": "system"
},
+ "system.account_relationship_definitions": {
+ "fields": {
+ "id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "id",
+ "id": null,
+ "name": "id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "name": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "name",
+ "id": null,
+ "name": "name",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "description": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "description",
+ "id": null,
+ "name": "description",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "is_single_holder": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "is_single_holder",
+ "id": null,
+ "name": "is_single_holder",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "updated_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "updated_at",
+ "id": null,
+ "name": "updated_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.account_relationship_definitions",
+ "name": "system.account_relationship_definitions",
+ "row_count": null,
+ "type": "system"
+ },
+ "system.account_relationships": {
+ "fields": {
+ "id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "id",
+ "id": null,
+ "name": "id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "definition_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "definition_id",
+ "id": null,
+ "name": "definition_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "account_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "account_id",
+ "id": null,
+ "name": "account_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "user_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "user_id",
+ "id": null,
+ "name": "user_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "created_by_id": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_by_id",
+ "id": null,
+ "name": "created_by_id",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "started_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "started_at",
+ "id": null,
+ "name": "started_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "ended_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "ended_at",
+ "id": null,
+ "name": "ended_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
+ "created_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "created_at",
+ "id": null,
+ "name": "created_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ }
+ },
+ "id": "system.account_relationships",
+ "name": "system.account_relationships",
+ "row_count": null,
+ "type": "system"
+ },
"system.activity_logs": {
"fields": {
"id": {
diff --git a/posthog/hogql/database/test/test_lazy_join_resolvers.py b/posthog/hogql/database/test/test_lazy_join_resolvers.py
index b1809db17d6c..4361afaa1026 100644
--- a/posthog/hogql/database/test/test_lazy_join_resolvers.py
+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py
@@ -184,6 +184,7 @@ class TestLazyJoinManifest(SimpleTestCase):
assert sorted(RESOLVERS) == [
"account_custom_properties",
"account_notebooks",
+ "account_relationships",
"account_tags",
"data_warehouse",
"data_warehouse_experiments",
diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.py
index e8f6fe12a999..c3dea2cc6294 100644
--- a/posthog/hogql/database/test/test_postgres_table.py
+++ b/posthog/hogql/database/test/test_postgres_table.py
@@ -38,6 +38,23 @@ _SCOPED_SYSTEM_TABLES: dict[str, PostgresTable] = {
name: table for name, table in ALL_POSTGRES_SYSTEM_TABLES if table.access_scope is not None
}
+# Facade-isolated products route data through their facade: their viewsets declare
+# `queryset = None` and DTO serializers, so the object-restrictable model can't be derived
+# from the viewset. Declared by db_table so product internals stay unimported here.
+_FACADE_OBJECT_GRANT_TABLES: dict[str, str] = {
+ "customer_analytics_account": "account",
+}
+
+# Team-level definition tables gated under an object-restrictable scope for resource-level
+# access only: their rows describe shapes shared by every account, not any single account's
+# data, so object-level denies don't apply (the default pk guard never matches a denied id).
+_SCOPE_GATED_METADATA_TABLES: frozenset[str] = frozenset(
+ {
+ "custom_property_definitions",
+ "account_relationship_definitions",
+ }
+)
+
@lru_cache(maxsize=1)
def _object_grant_registry() -> dict[type[Model], str]:
@@ -66,6 +83,8 @@ def _object_grant_registry() -> dict[type[Model], str]:
model = getattr(meta, "model", None)
if model is not None:
registry[model] = scope
+ for db_table, scope in _FACADE_OBJECT_GRANT_TABLES.items():
+ registry[_model_by_pg_table()[db_table]] = scope
return registry
@@ -460,6 +479,14 @@ class TestObjectAccessControlIdField(SimpleTestCase):
)
return
+ if table_name in _SCOPE_GATED_METADATA_TABLES:
+ self.assertIsNone(
+ table.access_control_id_field,
+ f"system.{table_name} is team-level metadata under '{scope}'; object-level denies "
+ f"don't apply to it — leave access_control_id_field unset.",
+ )
+ return
+
# Child table: it must filter the FK pointing at one of the restricted parent models.
fk_columns = sorted(
field.attname
diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.py
index 89494379f39f..22abd0807424 100644
--- a/products/customer_analytics/backend/facade/hogql.py
+++ b/products/customer_analytics/backend/facade/hogql.py
@@ -17,7 +17,12 @@ resolved by the planner.
from posthog.hogql import ast
from posthog.hogql.base import Expr
from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.lazy_join_tags import ACCOUNT_CUSTOM_PROPERTIES, ACCOUNT_NOTEBOOKS, ACCOUNT_TAGS
+from posthog.hogql.database.lazy_join_tags import (
+ ACCOUNT_CUSTOM_PROPERTIES,
+ ACCOUNT_NOTEBOOKS,
+ ACCOUNT_RELATIONSHIPS,
+ ACCOUNT_TAGS,
+)
from posthog.hogql.database.models import (
BooleanDatabaseField,
DANGEROUS_NoTeamIdCheckTable,
@@ -191,6 +196,50 @@ def _account_custom_properties_select(fields_accessed: dict[str, list[str | int]
)
+def _account_relationships_select(fields_accessed: dict[str, list[str | int]]) -> ast.SelectQuery:
+ r"""Aggregate each account's ACTIVE relationship assignments.
+
+ Inner select: one row per (account, definition) with the array of active user ids.
+ Outer select: `values` as a JSON object keyed by definition id; each requested key
+ (`accounts.relationships.values.\`<id>\``, arriving as `values___<id>`) is materialized
+ as its own column via `anyIf` — a lazy-join subquery can't JSON-extract after the fact.
+ """
+ inner = parse_select(
+ """
+ SELECT
+ rel.account_id AS account_id,
+ toString(rel.definition_id) AS definition_key,
+ arraySort(groupArray(rel.user_id)) AS user_ids
+ FROM system.account_relationships AS rel
+ WHERE isNull(rel.ended_at) AND isNotNull(rel.user_id)
+ GROUP BY rel.account_id, rel.definition_id
+ """
+ )
+ select: list[ast.Expr] = [parse_expr("account_id AS account_id")]
+ for name, chain in fields_accessed.items():
+ if chain == ["account_id"]:
+ continue
+ if len(chain) >= 2 and chain[0] == "values":
+ select.append(
+ ast.Alias(
+ alias=name,
+ expr=parse_expr(
+ "anyIf(user_ids, definition_key = {key})",
+ placeholders={"key": ast.Constant(value=str(chain[1]))},
+ ),
+ )
+ )
+ elif chain == ["values"]:
+ select.append(
+ parse_expr("toJSONString(mapFromArrays(groupArray(definition_key), groupArray(user_ids))) AS values")
+ )
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=inner),
+ group_by=[ast.Field(chain=["account_id"])],
+ )
+
+
class _AccountTagsTable(LazyTable):
description: str = (
"Internal aggregating table backing `system.accounts.tags`: the distinct, sorted tag names per account."
@@ -271,6 +320,38 @@ class _AccountCustomPropertiesTable(LazyTable):
return "account_custom_properties"
+class _AccountRelationshipsTable(LazyTable):
+ description: str = (
+ "Internal aggregating table backing `system.accounts.relationships`: a JSON object of each "
+ "account's active relationship assignments, keyed by definition id."
+ )
+ fields: dict[str, FieldOrTable] = {
+ "account_id": UUIDDatabaseField(
+ name="account_id", description="Account these relationships belong to; join to `system.accounts.id`."
+ ),
+ "values": StringJSONDatabaseField(
+ name="values",
+ description=(
+ "JSON object of active relationship assignments keyed by definition id; each value is an "
+ "array of assigned user ids. Read one definition with "
+ "accounts.relationships.values.`<definition_id>` (backtick-quote the id). "
+ "Get definition ids and names from system.account_relationship_definitions."
+ ),
+ ),
+ }
+
+ def lazy_select(
+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery
+ ) -> ast.SelectQuery | ast.SelectSetQuery:
+ return _account_relationships_select(table_to_add.fields_accessed)
+
+ def to_printed_clickhouse(self, context: HogQLContext) -> str:
+ return "account_relationships"
+
+ def to_printed_hogql(self) -> str:
+ return "account_relationships"
+
+
def _join_on_account_id(select: ast.SelectQuery | ast.SelectSetQuery, join_to_add: LazyJoinToAdd) -> ast.JoinExpr:
return ast.JoinExpr(
alias=join_to_add.to_table,
@@ -307,6 +388,14 @@ def account_custom_properties_join(
return _join_on_account_id(_account_custom_properties_select(join_to_add.fields_accessed), join_to_add)
+def account_relationships_join(
+ join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery
+) -> ast.JoinExpr:
+ if not join_to_add.fields_accessed:
+ raise ResolutionError("No fields requested from `accounts.relationships`")
+ return _join_on_account_id(_account_relationships_select(join_to_add.fields_accessed), join_to_add)
+
+
account_tags_lazy_join: LazyJoin = LazyJoin(
from_field=["id"],
join_table=_AccountTagsTable(),
@@ -326,6 +415,77 @@ account_custom_properties_lazy_join: LazyJoin = LazyJoin(
)
+account_relationships_lazy_join: LazyJoin = LazyJoin(
+ from_field=["id"],
+ join_table=_AccountRelationshipsTable(),
+ resolver=ACCOUNT_RELATIONSHIPS,
+)
+
+
+account_relationship_definitions: PostgresTable = PostgresTable(
+ name="account_relationship_definitions",
+ postgres_table_name="customer_analytics_accountrelationshipdefinition",
+ # Sub-resource of accounts; gated at the account resource level (see customer_analytics backend CLAUDE.md).
+ access_scope="account",
+ description="Customer analytics account relationship definitions: team-defined relationship types between PostHog users and accounts (CSM, Account executive, ...), one row per definition. Per-account assignments live in system.account_relationships and via the system.accounts.relationships lazy join.",
+ fields={
+ "id": UUIDDatabaseField(name="id", description="Relationship definition UUID."),
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "name": StringDatabaseField(
+ name="name", description="Human-readable name of the relationship; unique within the team."
+ ),
+ "description": StringDatabaseField(
+ name="description", nullable=True, description="What this relationship means."
+ ),
+ "_is_single_holder": BooleanDatabaseField(name="is_single_holder", hidden=True),
+ "is_single_holder": ExpressionField(
+ name="is_single_holder",
+ expr=ast.Call(name="toInt", args=[ast.Field(chain=["_is_single_holder"])]),
+ description="1 if only one user can hold this relationship per account at a time, 0 otherwise.",
+ ),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="PostHog user who created the definition."
+ ),
+ "created_at": DateTimeDatabaseField(name="created_at", description="When the definition was created."),
+ "updated_at": DateTimeDatabaseField(
+ name="updated_at", nullable=True, description="When the definition was last updated."
+ ),
+ },
+)
+
+
+account_relationships: PostgresTable = PostgresTable(
+ name="account_relationships",
+ postgres_table_name="customer_analytics_accountrelationship",
+ # Sub-resource of accounts; gated at the account resource level (see customer_analytics backend CLAUDE.md).
+ access_scope="account",
+ # Child rows expose per-account data: object-level denies must filter the account FK,
+ # not the assignment's own id, or a denied account's relationships leak.
+ access_control_id_field="account_id",
+ description="User-to-account relationship assignments (CSM, Account executive, ...), one row per assignment with its effective range — `ended_at` is NULL while active, set when the assignment ends, so historical account management is queryable. Active assignments per account are also exposed as a JSON object via the `system.accounts.relationships` lazy join.",
+ fields={
+ "id": UUIDDatabaseField(name="id", description="Relationship assignment UUID."),
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "definition_id": UUIDDatabaseField(
+ name="definition_id",
+ description="Relationship definition this assignment is for; join to `system.account_relationship_definitions.id`.",
+ ),
+ "account_id": UUIDDatabaseField(
+ name="account_id", description="Account the assignment belongs to; join to `system.accounts.id`."
+ ),
+ "user_id": IntegerDatabaseField(name="user_id", nullable=True, description="Assigned PostHog user id."),
+ "created_by_id": IntegerDatabaseField(
+ name="created_by_id", nullable=True, description="PostHog user who made the assignment."
+ ),
+ "started_at": DateTimeDatabaseField(name="started_at", description="When the assignment became effective."),
+ "ended_at": DateTimeDatabaseField(
+ name="ended_at", nullable=True, description="When the assignment ended; NULL while active."
+ ),
+ "created_at": DateTimeDatabaseField(name="created_at", description="When the assignment row was created."),
+ },
+)
+
+
accounts: PostgresTable = PostgresTable(
name="accounts",
postgres_table_name="customer_analytics_account",
@@ -391,6 +551,7 @@ accounts: PostgresTable = PostgresTable(
"tags": account_tags_lazy_join,
"notebooks": account_notebooks_lazy_join,
"custom_properties": account_custom_properties_lazy_join,
+ "relationships": account_relationships_lazy_join,
},
)