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(hogql): emit tupleElement for dot access on struct columns (#58993)

Nakshatra Nahara44bcb9f0cc1
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 504b8d759119..cc81112515fa 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -11,7 +11,7 @@ from posthog.hogql import ast
from posthog.hogql.ast import AST, Constant, StringType
from posthog.hogql.constants import HogQLDialect
from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.models import DANGEROUS_NoTeamIdCheckTable, DatabaseField, SavedQuery
+from posthog.hogql.database.models import DANGEROUS_NoTeamIdCheckTable, DatabaseField, SavedQuery, StructDatabaseField
from posthog.hogql.database.s3_table import DataWarehouseTable, S3Table
from posthog.hogql.errors import ImpossibleASTError, InternalHogQLError, QueryError
from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_clickhouse_string, safe_identifier
@@ -1530,3 +1530,22 @@ class ClickHousePrinter(BasePrinter):
def _get_table_name(self, table: ast.TableType) -> str:
return table.table.to_printed_clickhouse(self.context)
+
+ def visit_property_type(self, type: ast.PropertyType) -> str:
+ # Respect the joined-subquery projection: if the property has already been
+ # projected through a subquery, defer to base which renders the subquery alias
+ # correctly, rather than re-resolving against the original struct column.
+ if type.joined_subquery is not None and type.joined_subquery_field_name is not None:
+ return super().visit_property_type(type)
+
+ # Struct columns (e.g. Parquet structs from the data warehouse) are backed by a ClickHouse
+ # Tuple, not a JSON string. Emit chained tupleElement() calls instead of JSONExtractRaw(),
+ # which ClickHouse rejects on Tuple arguments. Closes #58480.
+ database_field = type.field_type.resolve_database_field(self.context)
+ if isinstance(database_field, StructDatabaseField):
+ expr = self.visit(type.field_type)
+ for link in type.chain:
+ expr = f"tupleElement({expr}, {self.context.add_value(str(link))})"
+ return expr
+
+ return super().visit_property_type(type)
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index c370f8f8813d..40177c3b425c 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -4042,6 +4042,81 @@ class TestPrinter(BaseTest):
result = self._expr(expr)
self.assertNotIn("$session_id_uuid", result)
+ @parameterized.expand(
+ [
+ (
+ "single_level_struct",
+ {
+ "membership": {
+ "clickhouse": "Tuple(type String, tier String)",
+ "hogql": "StructDatabaseField",
+ "valid": True,
+ "fields": {
+ "type": {"clickhouse": "String", "hogql": "string", "valid": True},
+ "tier": {"clickhouse": "String", "hogql": "string", "valid": True},
+ },
+ }
+ },
+ "SELECT membership.type FROM members",
+ "tupleElement(members.membership",
+ "JSONExtractRaw(members.membership",
+ ),
+ (
+ "nested_struct",
+ {
+ "customer": {
+ "clickhouse": "Tuple(address Tuple(city String))",
+ "hogql": "StructDatabaseField",
+ "valid": True,
+ "fields": {
+ "address": {
+ "clickhouse": "Tuple(city String)",
+ "hogql": "StructDatabaseField",
+ "valid": True,
+ "fields": {
+ "city": {
+ "clickhouse": "String",
+ "hogql": "string",
+ "valid": True,
+ },
+ },
+ }
+ },
+ }
+ },
+ "SELECT customer.address.city FROM members",
+ "tupleElement(tupleElement(members.customer",
+ "JSONExtractRaw(members.customer",
+ ),
+ ]
+ )
+ def test_data_warehouse_struct_dot_notation_emits_tuple_element(
+ self, _name, columns, query, expected_substring, forbidden_substring
+ ):
+ """Regression test for #58480.
+
+ Parquet struct columns surface in HogQL as ``StructDatabaseField``
+ backed by a ClickHouse ``Tuple(...)`` column. Dot notation on these
+ columns must emit ``tupleElement(col, 'field')`` (chained for nested
+ structs) rather than the ``JSONExtractRaw(col, 'field')`` chain used
+ for JSON-string columns, because ClickHouse rejects ``JSONExtractRaw``
+ on a ``Tuple`` argument with ``illegal type: Tuple(...)``.
+ """
+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="key", access_secret="secret")
+ DataWarehouseTable.objects.create(
+ team=self.team,
+ name="members",
+ format="Parquet",
+ url_pattern="http://s3/folder/",
+ credential=credential,
+ columns=columns,
+ )
+
+ printed = self._select(query)
+
+ self.assertNotIn(forbidden_substring, printed)
+ self.assertIn(expected_substring, printed)
+
@snapshot_clickhouse_queries
class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.py
index f6fd16f23a9f..38e8027cab22 100644
--- a/posthog/test/test_oauth_impersonation.py
+++ b/posthog/test/test_oauth_impersonation.py
@@ -10,18 +10,25 @@ from django.conf import settings
from django.contrib.auth import logout
from django.contrib.sessions.backends.db import SessionStore
from django.core.signing import TimestampSigner
-from django.test import RequestFactory
+from django.test import RequestFactory, override_settings
from django.utils import timezone
from loginas import settings as la_settings
from parameterized import parameterized
+from posthog.api.oauth.test_dcr import generate_rsa_key
from posthog.api.oauth.views import _impersonator_id_for_request
from posthog.middleware import IMPERSONATION_READ_ONLY_SESSION_KEY
from posthog.models import OAuthApplication, User
from posthog.models.oauth import OAuthAccessToken, OAuthGrant, OAuthRefreshToken
+TEST_OAUTH2_PROVIDER_WITH_RSA = {
+ **settings.OAUTH2_PROVIDER,
+ "OIDC_RSA_PRIVATE_KEY": generate_rsa_key(),
+}
+
+@override_settings(OAUTH2_PROVIDER=TEST_OAUTH2_PROVIDER_WITH_RSA)
class TestImpersonationOAuthRevocation(BaseTest):
def test_user_logged_out_revokes_only_impersonated_tokens(self) -> None:
admin = User.objects.create_user(email="[email protected]", password="x", first_name="A")
@@ -98,6 +105,7 @@ class TestImpersonationOAuthRevocation(BaseTest):
self.assertTrue(OAuthAccessToken.objects.filter(pk=customer_owned.pk).exists())
+@override_settings(OAUTH2_PROVIDER=TEST_OAUTH2_PROVIDER_WITH_RSA)
class TestImpersonationOAuthTokenIssuance(APIBaseTest):
"""Code-exchange flow: tokens minted from an impersonation-tagged grant must be
short-lived and refresh-less, so they expire at the impersonation idle timeout