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(hogql): support embedded ClickHouse selects (#96265)

Paweł Szczur7a439ca6d424
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index 4df18f7359e3..b07864b07a2d 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -97,6 +97,8 @@ class HogQLContext:
limit_context: Optional[LimitContext] = None
# Apply a FORMAT clause to output data in given format.
output_format: str | None = None
+ emit_top_level_settings: bool = True
+ top_level_settings: dict[str, object] = field(default_factory=dict)
# Globals that will be resolved in the context of the query
globals: Optional[dict] = None
property_type_overrides: Optional[dict[str, str]] = None
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index f755799fdcdd..d67852afe44b 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -1620,27 +1620,33 @@ class BasePrinter(Visitor[str]):
merged[key] = value
return merged
- def _print_settings(self, settings: HogQLQuerySettings | dict[str, Any]) -> str | None:
- pairs = []
+ def _normalize_settings(self, settings: HogQLQuerySettings | dict[str, Any]) -> dict[str, bool | int | float | str]:
+ normalized: dict[str, bool | int | float | str] = {}
items = settings.items() if isinstance(settings, dict) else settings
for key, value in items:
if value is None:
continue
if not re.match(r"^[a-zA-Z0-9_]+$", key):
raise QueryError(f"Setting {key} is not supported")
- if isinstance(value, bool):
- pairs.append(f"{key}={1 if value else 0}")
- elif isinstance(value, int) or isinstance(value, float):
- pairs.append(f"{key}={value}")
- elif isinstance(value, list):
+ if isinstance(value, list):
if not all(isinstance(item, str) and item for item in value):
raise QueryError(f"List setting {key} can only contain non-empty strings")
- formatted_items = ", ".join(self._print_hogql_identifier_or_index(item) for item in value)
- pairs.append(f"{key}={self._print_escaped_string(formatted_items)}")
- elif isinstance(value, str):
- pairs.append(f"{key}={self._print_escaped_string(value)}")
+ normalized[key] = ", ".join(self._print_hogql_identifier_or_index(item) for item in value)
+ elif isinstance(value, bool | int | float | str):
+ normalized[key] = value
else:
raise QueryError(f"Setting {key} has unsupported type {type(value).__name__}")
+ return normalized
+
+ def _print_settings(self, settings: HogQLQuerySettings | dict[str, Any]) -> str | None:
+ pairs = []
+ for key, value in self._normalize_settings(settings).items():
+ if isinstance(value, bool):
+ pairs.append(f"{key}={1 if value else 0}")
+ elif isinstance(value, int | float):
+ pairs.append(f"{key}={value}")
+ else:
+ pairs.append(f"{key}={self._print_escaped_string(value)}")
if len(pairs) > 0:
return f"SETTINGS {', '.join(pairs)}"
return None
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 4ecb2fe16f41..47a717190c74 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -357,9 +357,14 @@ class ClickHousePrinter(BasePrinter):
if not isinstance(node, ast.SelectQuery) and not isinstance(node, ast.SelectSetQuery):
raise QueryError("Settings can only be applied to SELECT queries")
merged = self._merge_table_top_level_settings(self.settings)
- printed = self._print_settings(merged)
- if printed is not None:
- response += " " + printed
+ if self.context.emit_top_level_settings:
+ printed = self._print_settings(merged)
+ if printed is not None:
+ response += " " + printed
+ else:
+ self.context.top_level_settings = {
+ key: value for key, value in self._normalize_settings(merged).items() if key != "readonly"
+ }
return response
@@ -1177,7 +1182,9 @@ class ClickHousePrinter(BasePrinter):
# When self.settings exists, table-level settings are merged in visit() instead
merged = (
- self._merge_table_top_level_settings(node.settings)
+ None
+ if is_top_level_query and not self.context.emit_top_level_settings
+ else self._merge_table_top_level_settings(node.settings)
if is_top_level_query and not self.settings
else node.settings
)
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index 1e3647176186..d916a55eaf3b 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -62,12 +62,13 @@ from posthog.hogql.resolver_utils import extract_base_table_types, extract_lazy_
from posthog.hogql.timings import HogQLTimings
from posthog.hogql.transforms.preaggregated_table_transformation import do_preaggregated_table_transforms
from posthog.hogql.variables import replace_variables
-from posthog.hogql.visitor import clone_expr
+from posthog.hogql.visitor import TraversingVisitor, clone_expr
from posthog.hogql.warehouse_warnings import record_warnings
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
from posthog.clickhouse.query_tagging import get_query_tags, tag_queries
+from posthog.dataclasses import frozen
from posthog.direct_query_cancellation import build_direct_query_cancellation_token
from posthog.errors import CHQueryErrorS3Error, CHQueryErrorS3FileChangedDuringRead, ExposedCHQueryError
from posthog.models.team import Team
@@ -85,6 +86,20 @@ tracer = trace.get_tracer(__name__)
TRANSIENT_S3_ERROR_RETRY_DELAY_SECONDS = 1.0
+@frozen
+class EmbeddedClickHouseQuery:
+ sql: str
+ context: HogQLContext
+ settings: dict[str, object]
+
+
+class _EmbeddedSelectSettingsValidator(TraversingVisitor):
+ def visit_select_query(self, node: ast.SelectQuery) -> None:
+ if node.settings is not None:
+ raise ExposedHogQLError("SETTINGS are not allowed when embedding a HogQL query.")
+ super().visit_select_query(node)
+
+
@dataclasses.dataclass(frozen=False)
class HogQLQueryExecutor:
query: Union[str, ast.SelectQuery, ast.SelectSetQuery] | None
@@ -610,7 +625,7 @@ class HogQLQueryExecutor:
self.print_columns = result.print_columns
@tracer.start_as_current_span("HogQLQueryExecutor._generate_clickhouse_sql")
- def _generate_clickhouse_sql(self):
+ def _generate_clickhouse_sql(self, *, include_settings: bool = True):
settings = get_default_hogql_global_settings(self.team.pk, self.settings)
if self.limit_context in (
LimitContext.EXPORT,
@@ -639,6 +654,7 @@ class HogQLQueryExecutor:
modifiers=self.query_modifiers,
limit_context=self.limit_context,
database=self.hogql_context.database if self.hogql_context else None,
+ emit_top_level_settings=include_settings,
)
with self.timings.measure("prepare_ast_for_printing"):
self.clickhouse_prepared_ast = prepare_ast_for_printing(
@@ -675,9 +691,12 @@ class HogQLQueryExecutor:
else:
raise
- def _prepare_execution(self) -> _PreparedExecution:
+ def _prepare_execution(self, *, embedded_select: bool = False) -> _PreparedExecution:
self._parse_query()
+ if embedded_select:
+ self.context.limit_top_select = False
+
source = self._resolve_direct_source()
if source is not None and source.direct_engine == "trino":
trino_execution = self._prepare_pure_trino_query()
@@ -686,7 +705,10 @@ class HogQLQueryExecutor:
self._process_variables()
self._process_placeholders()
- self._apply_limit()
+ if embedded_select:
+ _EmbeddedSelectSettingsValidator().visit(self.select_query)
+ if not embedded_select:
+ self._apply_limit()
with self.timings.measure("_generate_hogql"):
self._generate_hogql()
@@ -695,7 +717,7 @@ class HogQLQueryExecutor:
return direct_execution
with self.timings.measure("_generate_clickhouse_sql"):
- self._generate_clickhouse_sql()
+ self._generate_clickhouse_sql(include_settings=not embedded_select)
assert self.clickhouse_sql is not None
assert self.clickhouse_context is not None
@@ -831,6 +853,17 @@ class HogQLQueryExecutor:
prepared_execution = self._prepare_execution()
return prepared_execution.sql, prepared_execution.context
+ @tracer.start_as_current_span("HogQLQueryExecutor.generate_clickhouse_subquery_sql")
+ def generate_clickhouse_subquery_sql(self) -> EmbeddedClickHouseQuery:
+ prepared_execution = self._prepare_execution(embedded_select=True)
+ if prepared_execution.engine != "clickhouse":
+ raise ExposedHogQLError("Only ClickHouse-backed HogQL queries can be embedded.")
+ return EmbeddedClickHouseQuery(
+ sql=prepared_execution.sql,
+ context=prepared_execution.context,
+ settings=prepared_execution.context.top_level_settings,
+ )
+
@tracer.start_as_current_span("HogQLQueryExecutor.execute")
def execute(self) -> HogQLQueryResponse:
trace.get_current_span().set_attribute("team_id", self.team.pk)
diff --git a/posthog/hogql/test/test_query.py b/posthog/hogql/test/test_query.py
index 832deb3f9295..988ec71d0354 100644
--- a/posthog/hogql/test/test_query.py
+++ b/posthog/hogql/test/test_query.py
@@ -33,6 +33,7 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.constants import HogQLQuerySettings
from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source
from posthog.hogql.errors import ExposedHogQLError, QueryError
from posthog.hogql.printer import prepare_ast_for_printing as unmocked_prepare_ast_for_printing
@@ -44,8 +45,11 @@ from posthog.hogql.test.utils import (
pretty_print_response_in_tests,
)
+from posthog.clickhouse.adhoc_events_deletion import ADHOC_EVENTS_DELETION_TABLE, ADHOC_EVENTS_DELETION_TABLE_SQL
+from posthog.clickhouse.client import sync_execute
from posthog.errors import CHQueryErrorS3Error, InternalCHQueryError
from posthog.models.exchange_rate.currencies import SUPPORTED_CURRENCY_CODES
+from posthog.models.team import Team
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.uuidt import UUIDT, uuid7
@@ -431,6 +435,99 @@ class TestQuery(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(executor.types, [])
mock_sync_execute.assert_not_called()
+ def test_compiled_hogql_select_can_be_embedded_in_insert(self) -> None:
+ sync_execute(ADHOC_EVENTS_DELETION_TABLE_SQL(on_cluster=False))
+ sync_execute(f"TRUNCATE TABLE {ADHOC_EVENTS_DELETION_TABLE}")
+ self.addCleanup(sync_execute, f"TRUNCATE TABLE {ADHOC_EVENTS_DELETION_TABLE}")
+
+ event_name = 'delete candidates with "quotes"'
+ expected_uuid = _create_event(team=self.team, distinct_id="selected", event=event_name)
+ other_team = Team.objects.create(organization=self.organization, name="Other project")
+ _create_event(team=other_team, distinct_id="not-selected", event=event_name)
+ flush_persons_and_events()
+
+ executor = HogQLQueryExecutor(
+ query="SELECT uuid FROM events WHERE event = {event_name}",
+ placeholders={"event_name": ast.Constant(value=event_name)},
+ team=self.team,
+ pretty=False,
+ )
+ selected = executor.generate_clickhouse_subquery_sql()
+ selected_sql = selected.sql
+
+ self.assertNotIn(" LIMIT ", selected_sql)
+ self.assertNotIn(" SETTINGS ", selected_sql)
+ self.assertNotIn(event_name, selected_sql)
+
+ # The outer statement and destination are server-owned; only the parsed and resolved SELECT is embedded.
+ insert_sql = ( # nosemgrep: clickhouse-injection-taint
+ f"INSERT INTO {ADHOC_EVENTS_DELETION_TABLE} (team_id, uuid) "
+ f"SELECT %(_deletion_team_id)s, selected.uuid FROM ({selected_sql}) AS selected"
+ )
+ sync_execute(
+ insert_sql,
+ {**selected.context.values, "_deletion_team_id": self.team.pk},
+ team_id=self.team.pk,
+ settings=selected.settings,
+ )
+
+ queued = sync_execute(
+ f"SELECT team_id, toString(uuid) FROM {ADHOC_EVENTS_DELETION_TABLE} ORDER BY team_id, uuid"
+ )
+ self.assertEqual(queued, [(self.team.pk, expected_uuid)])
+
+ def test_embedded_hogql_select_rejects_ast_settings(self) -> None:
+ query = ast.SelectQuery(
+ select=[ast.Field(chain=["uuid"])],
+ select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ settings=HogQLQuerySettings(max_bytes_to_read=1),
+ )
+ executor = HogQLQueryExecutor(query=query, team=self.team)
+
+ with self.assertRaisesRegex(ExposedHogQLError, "SETTINGS are not allowed"):
+ executor.generate_clickhouse_subquery_sql()
+
+ placeholder_executor = HogQLQueryExecutor(
+ query="SELECT uuid FROM {source}",
+ placeholders={"source": query},
+ team=self.team,
+ )
+
+ with self.assertRaisesRegex(ExposedHogQLError, "SETTINGS are not allowed"):
+ placeholder_executor.generate_clickhouse_subquery_sql()
+
+ def test_embedded_hogql_select_returns_required_table_settings(self) -> None:
+ from posthog.hogql.context import HogQLContext
+ from posthog.hogql.database.database import Database
+ from posthog.hogql.database.models import StringDatabaseField, TableNode
+ from posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTable
+
+ csv_table = HogQLDataWarehouseTable(
+ name="csv_table",
+ url="https://example.com/test.csv",
+ format="CSVWithNames",
+ fields={"uuid": StringDatabaseField(name="uuid")},
+ structure="`uuid` String",
+ top_level_settings=HogQLQuerySettings(format_csv_allow_double_quotes=True),
+ )
+ database = Database()
+ root = TableNode()
+ root.add_child(TableNode(name="csv_table", table=csv_table))
+ database._add_warehouse_tables(root)
+ executor = HogQLQueryExecutor(
+ query="SELECT uuid FROM csv_table",
+ team=self.team,
+ context=HogQLContext(team_id=self.team.pk, database=database),
+ modifiers=HogQLQueryModifiers(forceClickhouseDataSkippingIndexes=["idx"]),
+ )
+
+ selected = executor.generate_clickhouse_subquery_sql()
+
+ self.assertTrue(selected.settings["format_csv_allow_double_quotes"])
+ self.assertEqual(selected.settings["force_data_skipping_indices"], "idx")
+ self.assertNotIn("readonly", selected.settings)
+ self.assertNotIn(" SETTINGS ", selected.sql)
+
@pytest.mark.usefixtures("unittest_snapshot")
def test_query_joins_pdi_persons(self):
with freeze_time("2020-01-10"):