: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
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.pyindex 504b8d759119..cc81112515fa 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -11,7 +11,7 @@ from posthog.hogql import astfrom posthog.hogql.ast import AST, Constant, StringTypefrom posthog.hogql.constants import HogQLDialectfrom 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, StructDatabaseFieldfrom posthog.hogql.database.s3_table import DataWarehouseTable, S3Tablefrom posthog.hogql.errors import ImpossibleASTError, InternalHogQLError, QueryErrorfrom 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.pyindex 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_queriesclass TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/test/test_oauth_impersonation.py b/posthog/test/test_oauth_impersonation.pyindex 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 settingsfrom django.contrib.auth import logoutfrom django.contrib.sessions.backends.db import SessionStorefrom django.core.signing import TimestampSigner-from django.test import RequestFactory+from django.test import RequestFactory, override_settingsfrom django.utils import timezonefrom loginas import settings as la_settingsfrom parameterized import parameterized+from posthog.api.oauth.test_dcr import generate_rsa_keyfrom posthog.api.oauth.views import _impersonator_id_for_requestfrom posthog.middleware import IMPERSONATION_READ_ONLY_SESSION_KEYfrom posthog.models import OAuthApplication, Userfrom 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 beshort-lived and refresh-less, so they expire at the impersonation idle timeout