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-warehouse): only treat clickhouse sources as direct when they are (#74127)

Andersf59d2a92cd54
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index caadb74213c5..532b83b9c909 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -62,6 +62,8 @@ class HogQLContext:
database: Optional["Database"] = None
# Metadata discovered for a direct Postgres connection, if one is selected
direct_postgres_connection_metadata: dict[str, Any] | None = None
+ # Set when the query executes against an external direct-SQL connection instead of PostHog's own cluster
+ is_direct_query: bool = False
# If set, will save string constants to this dict. Inlines strings into the query if None.
values: dict = field(default_factory=dict)
# Query-scoped ClickHouse external data tables accumulated during printing (keyed by table name).
diff --git a/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py b/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py
index 67b373bf69e8..1c6fff88a9bf 100644
--- a/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py
+++ b/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py
@@ -1,17 +1,23 @@
from typing import Any
+from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTable
+from posthog.hogql.database.models import StringDatabaseField, TableNode
from posthog.hogql.direct_sql.clickhouse_adapter import (
_fetch_capped_clickhouse_rows,
ensure_read_only_raw_clickhouse_statement,
)
from posthog.hogql.errors import ExposedHogQLError, QueryError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer.utils import prepare_and_print_ast
class TestDirectClickHouseTable(SimpleTestCase):
@@ -49,6 +55,38 @@ class TestDirectClickHouseTable(SimpleTestCase):
table.to_printed_mysql(None)
+class TestDirectClickHouseTeamIdGuard(BaseTest):
+ def _print(self, *, is_direct_query: bool) -> str:
+ table = DirectClickHouseTable(
+ name="external_events",
+ fields={"col1": StringDatabaseField(name="col1")},
+ clickhouse_database="mydb",
+ clickhouse_table_name="events",
+ external_data_source_id="src",
+ )
+ database = Database()
+ root = TableNode()
+ root.add_child(TableNode(name="external_events", table=table))
+ database._add_warehouse_tables(root)
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ database=database,
+ is_direct_query=is_direct_query,
+ )
+ return prepare_and_print_ast(parse_select("SELECT col1 FROM external_events"), context, "clickhouse")[0]
+
+ def test_direct_query_prints_external_table_without_team_id(self):
+ printed = self._print(is_direct_query=True)
+ self.assertIn("mydb.events", printed)
+ self.assertNotIn("team_id", printed)
+
+ def test_refuses_external_table_outside_a_direct_query(self):
+ # Our own cluster would happily resolve `mydb.events` — printing it there must fail, not read it.
+ with self.assertRaisesRegex(QueryError, "direct connection"):
+ self._print(is_direct_query=False)
+
+
class TestClickHouseReadOnlyGuard(SimpleTestCase):
@parameterized.expand(
[
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 0ce7c0cfbe55..2f3d8a022be4 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -9,6 +9,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.direct_sql_table import DirectSQLTable
from posthog.hogql.database.models import (
DANGEROUS_NoTeamIdCheckTable,
SavedQuery,
@@ -921,6 +922,17 @@ class ClickHousePrinter(BasePrinter):
):
# :IMPORTANT: This assures a "team_id" where clause is present on every selected table.
# Skip warehouse tables and tables with an explicit skip.
+ if isinstance(table_type.table, DirectSQLTable):
+ # An external table has no team_id — the connection it belongs to is what scopes it to a team.
+ # ClickHouse is both our own dialect and a direct engine, so refuse to print a direct table into a
+ # query aimed at our cluster: without this, a mislabelled table would silently read whatever
+ # `<database>.<table>` resolves to there, unfiltered.
+ if not self.context.is_direct_query:
+ raise QueryError(
+ f'Table "{table_type.table.to_printed_hogql()}" can only be queried through its direct connection.'
+ )
+ return None
+
if (
not isinstance(table_type.table, DataWarehouseTable)
and not isinstance(table_type.table, SavedQuery)
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index c4af4c7ced0c..e860b0f16ecf 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -381,6 +381,7 @@ class HogQLQueryExecutor:
direct_context = dataclasses.replace(
self.context,
+ is_direct_query=True,
team_id=self.team.pk,
team=self.team,
enable_select_queries=True,
diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.py
index e2cc5ddaf0e8..acc3ff6441ee 100644
--- a/products/data_warehouse/backend/models/test/test_table.py
+++ b/products/data_warehouse/backend/models/test/test_table.py
@@ -5,6 +5,7 @@ from unittest.mock import patch
from clickhouse_driver.errors import ServerException
from parameterized import parameterized
+from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTable
from posthog.hogql.database.direct_mysql_table import DirectMySQLTable
from posthog.hogql.database.direct_postgres_table import DirectPostgresTable
from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTable
@@ -159,6 +160,60 @@ class TestTable(BaseTest):
with pytest.raises(QueryError, match="Direct Postgres tables cannot be printed into ClickHouse SQL"):
definition.to_printed_clickhouse(context=None)
+ @parameterized.expand(
+ [
+ (
+ "direct",
+ ExternalDataSourceType.CLICKHOUSE,
+ ExternalDataSource.AccessMethod.DIRECT,
+ DirectClickHouseTable,
+ ),
+ (
+ "synced",
+ ExternalDataSourceType.CLICKHOUSE,
+ ExternalDataSource.AccessMethod.WAREHOUSE,
+ HogQLDataWarehouseTable,
+ ),
+ # Both ClickHouse source types share the "clickhouse" engine, so both must resolve alike.
+ (
+ "direct_cloud",
+ ExternalDataSourceType.CLICKHOUSECLOUD,
+ ExternalDataSource.AccessMethod.DIRECT,
+ DirectClickHouseTable,
+ ),
+ (
+ "synced_cloud",
+ ExternalDataSourceType.CLICKHOUSECLOUD,
+ ExternalDataSource.AccessMethod.WAREHOUSE,
+ HogQLDataWarehouseTable,
+ ),
+ ]
+ )
+ def test_clickhouse_table_is_direct_only_for_a_direct_source(
+ self, _name: str, source_type: str, access_method: str, expected_type: type
+ ):
+ source = ExternalDataSource.objects.create(
+ source_id="source-id",
+ connection_id="connection-id",
+ destination_id="destination-id",
+ team=self.team,
+ sync_frequency=ExternalDataSource.SyncFrequency.DAILY,
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=source_type,
+ prefix="Readable Name",
+ access_method=access_method,
+ job_inputs={"database": "mydb"},
+ )
+ table = DataWarehouseTable.objects.create(
+ name="events",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team=self.team,
+ external_data_source=source,
+ columns={"id": {"clickhouse": "String", "hogql": "StringDatabaseField"}},
+ )
+
+ assert isinstance(table.hogql_definition(), expected_type)
+
def test_direct_mysql_table_uses_physical_schema_and_table_options(self):
source = ExternalDataSource.objects.create(
source_id="source-id",