: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
feat(data-warehouse): add direct-query support for clickhouse sources (#72906)
Tom Owers4f902e6d35e6
diff --git a/posthog/hogql/database/direct_clickhouse_table.py b/posthog/hogql/database/direct_clickhouse_table.pynew file mode 100644index 000000000000..f07f1ac659c8--- /dev/null+++ b/posthog/hogql/database/direct_clickhouse_table.py@@ -0,0 +1,25 @@+from posthog.hogql.database.direct_sql_table import DirectSQLTable+from posthog.hogql.errors import QueryError+from posthog.hogql.escape_sql import escape_clickhouse_identifier+++class DirectClickHouseTable(DirectSQLTable):+ # ClickHouse namespaces a table as database.table (there is no separate catalog level).+ clickhouse_database: str+ clickhouse_table_name: str++ def to_printed_clickhouse(self, context) -> str:+ # Unlike the other direct tables (which target a different SQL dialect and raise here),+ # ClickHouse IS the printer's native dialect — so this renders the external table reference+ # that the direct-query executor runs against the external ClickHouse connection.+ parts = []+ if self.clickhouse_database.strip():+ parts.append(escape_clickhouse_identifier(self.clickhouse_database))+ parts.append(escape_clickhouse_identifier(self.clickhouse_table_name))+ return ".".join(parts)++ def to_printed_postgres(self, context) -> str:+ raise QueryError("Direct ClickHouse tables cannot be printed into Postgres SQL")++ def to_printed_mysql(self, context) -> str:+ raise QueryError("Direct ClickHouse tables cannot be printed into MySQL SQL")diff --git a/posthog/hogql/direct_query_metrics.py b/posthog/hogql/direct_query_metrics.pyindex baa8cef5e610..3a3f02554db9 100644--- a/posthog/hogql/direct_query_metrics.py+++ b/posthog/hogql/direct_query_metrics.py@@ -19,7 +19,7 @@ from prometheus_client import (Histogram,)-DirectQueryDialect = Literal["postgres", "mysql", "snowflake", "redshift"]+DirectQueryDialect = Literal["postgres", "mysql", "snowflake", "redshift", "clickhouse"]DirectQueryStatus = Literal["success", "error"]DIRECT_QUERY_TOTAL = PromCounter(diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.pyindex b280e33d74f2..09f7918fa6af 100644--- a/posthog/hogql/direct_sql/__init__.py+++ b/posthog/hogql/direct_sql/__init__.py@@ -1,5 +1,6 @@from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, DirectSQLAdapterfrom posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable+from posthog.hogql.direct_sql.clickhouse_adapter import ClickHouseAdapterfrom posthog.hogql.direct_sql.mysql_adapter import MySQLAdapterfrom posthog.hogql.direct_sql.postgres_adapter import PostgresAdapterfrom posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement@@ -11,11 +12,13 @@ register_adapter(PostgresAdapter())register_adapter(MySQLAdapter())register_adapter(SnowflakeAdapter())register_adapter(RedshiftAdapter())+register_adapter(ClickHouseAdapter())__all__ = ["DirectQueryRequest","DirectQueryResult","DirectSQLAdapter",+ "ClickHouseAdapter","PostgresAdapter","MySQLAdapter","SnowflakeAdapter",diff --git a/posthog/hogql/direct_sql/clickhouse_adapter.py b/posthog/hogql/direct_sql/clickhouse_adapter.pynew file mode 100644index 000000000000..422699838ff1--- /dev/null+++ b/posthog/hogql/direct_sql/clickhouse_adapter.py@@ -0,0 +1,314 @@+from collections.abc import Iterator+from time import perf_counter+from typing import TYPE_CHECKING, Any, cast++import sqlparse+from opentelemetry import trace+from sqlparse import tokens as sqlparse_tokens+from sqlparse.sql import TokenList++from posthog.hogql.constants import HogQLDialect+from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_query+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult+from posthog.hogql.direct_sql.capability import is_direct_capable+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.errors import ExposedHogQLError++if TYPE_CHECKING:+ from clickhouse_connect.driver.client import Client as ClickHouseClient++ from posthog.models.team import Team++ from products.warehouse_sources.backend.facade.models import ExternalDataSource+ from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse.source import ClickHouseSource+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clickhouse import (+ ClickHouseSourceConfig,+ )++DIRECT_CLICKHOUSE_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600+# Hard backstop against loading an unbounded result set into memory — guards a raw passthrough+# `SELECT * FROM huge_table` with no LIMIT (the shared client runs with query_limit=0). HogQL-+# authored queries already carry a LIMIT from the printer.+DIRECT_CLICKHOUSE_MAX_ROWS = 1_000_000+DIRECT_CLICKHOUSE_ROW_CAP_ERROR = (+ f"ClickHouse query returned more than {DIRECT_CLICKHOUSE_MAX_ROWS:,} rows. Add a LIMIT clause."+)+DIRECT_CLICKHOUSE_TIMEOUT_ERROR = "ClickHouse query exceeded the execution time limit."+# Bounds the rows ClickHouse packs into one response block (the ClickHouse default). A block is+# materialized whole before the streaming loop can check the row cap, so this keeps peak memory+# per block bounded — and since raw SETTINGS overrides are rejected, a query can't inflate it.+DIRECT_CLICKHOUSE_MAX_BLOCK_SIZE = 65_536+RAW_CLICKHOUSE_READ_ONLY_ERROR = "Raw ClickHouse queries must be read-only SELECT statements."+RAW_CLICKHOUSE_SETTINGS_ERROR = "Raw ClickHouse queries may not set query-level SETTINGS."+RAW_CLICKHOUSE_BLOCKED_FUNCTION_ERROR = "This ClickHouse table function is not allowed in direct queries."++# Table functions that read over the network, from the local filesystem, or spawn a process.+# They parse as a plain SELECT (`SELECT * FROM url(...)`), so the read-only DML/DDL gate doesn't+# stop them — a raw query could otherwise reach the connected server's metadata endpoint (SSRF),+# federate in data from other databases the server can see, or read local files / run programs.+# HogQL-authored queries never emit these; only the raw passthrough path can, so block them by+# name there. Matched case-insensitively and only when the name is a function call (a column+# literally named e.g. `url` tokenizes as an identifier, not a Function, so it's unaffected).+_RAW_CLICKHOUSE_BLOCKED_TABLE_FUNCTIONS = frozenset(+ {+ "URL",+ "URLCLUSTER",+ "S3",+ "S3CLUSTER",+ "GCS",+ "REMOTE",+ "REMOTESECURE",+ "CLUSTER",+ "CLUSTERALLREPLICAS",+ "MYSQL",+ "POSTGRESQL",+ "MONGODB",+ "REDIS",+ "SQLITE",+ "JDBC",+ "ODBC",+ "HDFS",+ "HDFSCLUSTER",+ "FILE",+ "INPUT",+ "AZUREBLOBSTORAGE",+ "AZUREBLOBSTORAGECLUSTER",+ # Lakehouse table functions and every `*Cluster` twin — each reads a remote/object-store+ # dataset the same way the base function does, so the cluster form must be blocked too.+ "DELTALAKE",+ "DELTALAKECLUSTER",+ "DELTALAKES3",+ "DELTALAKEAZURE",+ "DELTALAKELOCAL",+ "HUDI",+ "HUDICLUSTER",+ "ICEBERG",+ "ICEBERGCLUSTER",+ "ICEBERGS3",+ "ICEBERGAZURE",+ "ICEBERGHDFS",+ "ICEBERGLOCAL",+ # `merge('.*', '.*')` reads across every table/db the server can see, bypassing per-source+ # scoping; `dictionary(...)` can be backed by a remote source.+ "MERGE",+ "DICTIONARY",+ "EXECUTABLE",+ }+)+++def clickhouse_error_to_message(error: Exception) -> str:+ message = str(error).strip()+ if not message:+ return "ClickHouse query failed."+ return message.splitlines()[0]+++def _normalize_function_name(name: str) -> str:+ """Strip ClickHouse identifier quoting so a quoted callee matches the blocklist by its bare name."""+ name = name.strip()+ if len(name) >= 2 and name[0] == name[-1] and name[0] in ('"', "`"):+ name = name[1:-1]+ return name+++def _iter_function_names(statement: TokenList) -> "Iterator[str]":+ """Yield the name of every function call in the statement.++ A call is a name token immediately followed by ``(``. Detecting it on the flattened token+ stream (rather than trusting ``sqlparse.sql.Function`` nodes) catches quoted callees: a+ double-quoted name like ``"remote"(...)`` parses as an identifier plus a *separate* parenthesis,+ never a Function, so a node-based check skips it entirely. Quoting is stripped so ``"remote"``+ and ```remote``` both match ``remote``. A bare identifier of the same spelling (``SELECT url``)+ has no following ``(`` and is unaffected.+ """+ significant = [+ token for token in statement.flatten() if not token.is_whitespace and token.ttype not in sqlparse_tokens.Comment+ ]+ for idx, token in enumerate(significant):+ if not (token.ttype in sqlparse_tokens.Name or token.ttype in sqlparse_tokens.String.Symbol):+ continue+ following = significant[idx + 1] if idx + 1 < len(significant) else None+ if following is not None and following.ttype is sqlparse_tokens.Punctuation and following.value == "(":+ yield _normalize_function_name(token.value)+++def _has_settings_clause(statement: TokenList) -> bool:+ """Whether the statement carries a ClickHouse ``SETTINGS <name> = ...`` clause.++ Distinguished from a column literally named ``settings`` by the trailing ``<identifier> =``:+ the clause is ``SETTINGS`` followed by a setting name and ``=``, whereas ``WHERE settings =``+ has ``=`` immediately after and ``SELECT settings FROM`` has no ``=`` at all.+ """+ significant = [+ token for token in statement.flatten() if not token.is_whitespace and token.ttype not in sqlparse_tokens.Comment+ ]+ for idx, token in enumerate(significant):+ if token.ttype not in (sqlparse_tokens.Keyword, sqlparse_tokens.Name) or token.value.upper() != "SETTINGS":+ continue+ name = significant[idx + 1] if idx + 1 < len(significant) else None+ equals = significant[idx + 2] if idx + 2 < len(significant) else None+ if (+ name is not None+ and name.ttype in (sqlparse_tokens.Name, sqlparse_tokens.Keyword)+ and equals is not None+ and equals.ttype in sqlparse_tokens.Comparison+ and equals.value == "="+ ):+ return True+ return False+++def ensure_read_only_raw_clickhouse_statement(sql: str) -> str:+ """Enforce read-only for raw ClickHouse SQL.++ ClickHouse has no read-only transaction switch we can set on the connection, so read-only is+ enforced our side (as with Snowflake/Redshift): the statement must be a single ``SELECT`` and+ any DDL — or any DML keyword other than ``SELECT`` anywhere in the statement — is rejected.+ A first-keyword check is not enough: ClickHouse accepts ``WITH 1 AS x INSERT INTO t SELECT x``,+ which starts with ``WITH`` but writes, so the whole statement is inspected. Network/file/exec+ table functions (``url``, ``s3``, ``remote``, ``file``, …) are rejected too: they run from a+ plain SELECT and would otherwise let a raw query reach the connected server's metadata endpoint+ (SSRF), read local files, or federate in other databases. HogQL-authored queries only ever emit+ a plain SELECT over the source's own tables. String values and quoted identifiers aren't tagged+ DML/DDL and a same-named column isn't a function call, so a literal, alias, or column like+ ``'DELETE'`` / ``url`` is unaffected.++ A query-level ``SETTINGS`` clause is rejected as well: ClickHouse lets it override connection+ settings, so a raw query could otherwise reset ``max_execution_time`` or inflate+ ``max_block_size`` to defeat the timeout and per-block memory bounds. HogQL-authored queries+ don't take this raw path, so they can still set whatever settings the printer emits.+ """+ sql = ensure_single_direct_statement(sql)+ statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]+ if len(statements) != 1 or statements[0].get_type() != "SELECT":+ raise ExposedHogQLError(RAW_CLICKHOUSE_READ_ONLY_ERROR)+ statement = statements[0]+ for token in statement.flatten():+ if token.ttype in sqlparse_tokens.DDL:+ raise ExposedHogQLError(RAW_CLICKHOUSE_READ_ONLY_ERROR)+ if token.ttype in sqlparse_tokens.DML and token.value.upper() != "SELECT":+ raise ExposedHogQLError(RAW_CLICKHOUSE_READ_ONLY_ERROR)+ for function_name in _iter_function_names(statement):+ if function_name.upper() in _RAW_CLICKHOUSE_BLOCKED_TABLE_FUNCTIONS:+ raise ExposedHogQLError(RAW_CLICKHOUSE_BLOCKED_FUNCTION_ERROR)+ if _has_settings_clause(statement):+ raise ExposedHogQLError(RAW_CLICKHOUSE_SETTINGS_ERROR)+ return sql+++def _fetch_capped_clickhouse_rows(+ client: "ClickHouseClient", sql: str, parameters: dict[str, Any] | None, deadline_seconds: float+) -> tuple[list, list[str], list[str]]:+ """Stream rows up to the row cap, raising if the result would exceed it or the deadline passes.++ The shared client is configured with ``query_limit=0``, so ``client.query`` would buffer the+ full response in the worker process. Streaming row blocks and stopping one row past the cap+ bounds memory to the cap plus a single block, matching the fetchmany(cap+1) guard the+ Snowflake/Redshift adapters use.++ The per-block wall-clock deadline is the real timeout backstop: a raw query can override the+ server-side ``max_execution_time`` with its own ``SETTINGS`` clause, and dribbling rows out in+ tiny blocks keeps the socket read-timeout from ever firing — so a slow query would otherwise+ pin the worker and SSH tunnel indefinitely. Bailing once ``deadline_seconds`` elapses (and+ closing the client, which drops the connection so ClickHouse cancels the query) enforces the+ cap regardless of any in-query setting.+ """+ rows: list = []+ started = perf_counter()+ with client.query_row_block_stream(sql, parameters=parameters) as stream:+ column_names = list(stream.source.column_names)+ column_types = [str(column_type) for column_type in stream.source.column_types]+ for block in stream:+ if perf_counter() - started > deadline_seconds:+ raise ExposedHogQLError(DIRECT_CLICKHOUSE_TIMEOUT_ERROR)+ rows.extend(block)+ if len(rows) > DIRECT_CLICKHOUSE_MAX_ROWS:+ DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="clickhouse").inc()+ raise ExposedHogQLError(DIRECT_CLICKHOUSE_ROW_CAP_ERROR)+ return rows, column_names, column_types+++class ClickHouseAdapter:+ engine = "clickhouse"+ dialect: HogQLDialect | None = "clickhouse"++ def validate_source_config(+ self, source: "ExternalDataSource", team: "Team"+ ) -> tuple["ClickHouseSource", "ClickHouseSourceConfig"]:+ from products.warehouse_sources.backend.facade.source_management import SourceRegistry+ from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++ # Capability, not access_method: a synced source with the direct-query toggle on is valid too.+ if not (is_direct_capable(source) and source.direct_engine == self.engine):+ raise ExposedHogQLError("Invalid direct ClickHouse connection.")++ source_type = (+ ExternalDataSourceType.CLICKHOUSECLOUD+ if source.source_type == ExternalDataSourceType.CLICKHOUSECLOUD+ else ExternalDataSourceType.CLICKHOUSE+ )+ clickhouse_source = cast("ClickHouseSource", SourceRegistry.get_source(source_type))+ config = clickhouse_source.parse_config(source.job_inputs or {})++ is_ssh_valid, ssh_valid_errors = clickhouse_source.ssh_tunnel_is_valid(config, team.pk)+ if not is_ssh_valid:+ raise ExposedHogQLError(ssh_valid_errors or "Invalid SSH tunnel configuration.")++ valid_host, host_errors = clickhouse_source.is_database_host_valid(+ config.host, team.pk, using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False+ )+ if not valid_host:+ raise ExposedHogQLError(host_errors or "Invalid ClickHouse host.")++ return clickhouse_source, config++ def prepare_raw_sql(self, sql: str) -> str:+ return ensure_read_only_raw_clickhouse_statement(sql)++ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:+ from clickhouse_connect.driver.exceptions import ClickHouseError++ source = request.source+ clickhouse_source, config = self.validate_source_config(source, request.team)+ settings = request.settings+ statement_timeout_seconds = max(+ settings.max_execution_time or DIRECT_CLICKHOUSE_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1+ )++ span = trace.get_current_span()+ span.set_attribute("team_id", request.team.pk)+ span.set_attribute("query_type", request.query_type)+ span.set_attribute("source_id", str(source.id))++ try:+ with request.timings.measure("clickhouse_execute"), observe_direct_query("clickhouse"):+ # The SSH tunnel (if any) is opened for the life of the query; the native driver+ # connects to the external ClickHouse directly, never through PostHog's cluster.+ with clickhouse_source.direct_query_client(+ config,+ request.team.pk,+ query_timeout=statement_timeout_seconds,+ # Server-side caps on top of the socket timeout and the streaming row cap.+ # `max_execution_time` and `max_block_size` are standard settings managed+ # servers accept (unlike a readonly override); raw SETTINGS overrides of them+ # are rejected in `prepare_raw_sql`, so these bounds hold for raw queries.+ settings={+ "max_execution_time": statement_timeout_seconds,+ "max_block_size": DIRECT_CLICKHOUSE_MAX_BLOCK_SIZE,+ },+ ) as client:+ rows, column_names, column_types = _fetch_capped_clickhouse_rows(+ client, request.sql, request.values or None, statement_timeout_seconds+ )+ except (ClickHouseError, OSError, ExposedHogQLError) as error:+ span.set_attribute("error_type", error.__class__.__name__)+ if request.debug:+ return DirectQueryResult(+ results=[], types=[], print_columns=[], error=clickhouse_error_to_message(error)+ )+ raise ExposedHogQLError(clickhouse_error_to_message(error)) from error++ span.set_attribute("row_count", len(rows))+ types: list[tuple[str, str]] = list(zip(column_names, column_types))+ return DirectQueryResult(results=[list(row) for row in rows], types=types, print_columns=column_names)diff --git a/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py b/posthog/hogql/direct_sql/test/test_clickhouse_adapter.pynew file mode 100644index 000000000000..67b373bf69e8--- /dev/null+++ b/posthog/hogql/direct_sql/test/test_clickhouse_adapter.py@@ -0,0 +1,168 @@+from typing import Any++from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTable+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+++class TestDirectClickHouseTable(SimpleTestCase):+ def _table(self, database: str) -> DirectClickHouseTable:+ return DirectClickHouseTable(+ name="events",+ fields={},+ clickhouse_database=database,+ clickhouse_table_name="events",+ external_data_source_id="src",+ )++ def test_renders_escaped_database_and_table(self):+ self.assertEqual(self._table("mydb").to_printed_clickhouse(None), "mydb.events")++ def test_renders_table_only_when_no_database(self):+ self.assertEqual(self._table("").to_printed_clickhouse(None), "events")++ def test_escapes_special_identifiers(self):+ table = DirectClickHouseTable(+ name="t",+ fields={},+ clickhouse_database="my db",+ clickhouse_table_name="weird.name",+ external_data_source_id="s",+ )+ # backtick-escaped because they contain a space / dot+ self.assertEqual(table.to_printed_clickhouse(None), "`my db`.`weird.name`")++ def test_refuses_other_dialects(self):+ table = self._table("mydb")+ with self.assertRaises(QueryError):+ table.to_printed_postgres(None)+ with self.assertRaises(QueryError):+ table.to_printed_mysql(None)+++class TestClickHouseReadOnlyGuard(SimpleTestCase):+ @parameterized.expand(+ [+ ("select", "SELECT * FROM events"),+ ("with_cte", "WITH x AS (SELECT 1) SELECT * FROM x"),+ ("lowercase", "select count() from events"),+ ("leading_comment", "-- hi\nSELECT 1"),+ # A column named like a blocked table function is an identifier, not a call — allowed.+ ("column_named_url", "SELECT url FROM events"),+ ("column_named_file", "SELECT file, count() FROM events"),+ # A column named `settings` is not a SETTINGS clause (no trailing `<name> =`).+ ("column_named_settings", "SELECT settings FROM events"),+ ("settings_in_where", "SELECT * FROM events WHERE settings = 'x'"),+ ("settings_as_alias", "SELECT 1 AS settings, 2 AS x"),+ ]+ )+ def test_allows_read_only(self, _name, sql):+ self.assertEqual(ensure_read_only_raw_clickhouse_statement(sql), sql)++ @parameterized.expand(+ [+ ("max_block_size", "SELECT * FROM numbers(10) SETTINGS max_block_size=1000000000"),+ ("max_execution_time", "SELECT 1 SETTINGS max_execution_time=0"),+ ("multiple", "SELECT 1 SETTINGS max_execution_time = 0, max_block_size = 1"),+ ]+ )+ def test_rejects_settings_clause(self, _name, sql):+ with self.assertRaises(ExposedHogQLError):+ ensure_read_only_raw_clickhouse_statement(sql)++ @parameterized.expand(+ [+ ("url_ssrf", "SELECT * FROM url('http://169.254.169.254/latest/meta-data/', RawBLOB)"),+ ("s3", "SELECT * FROM s3('http://x/f.csv')"),+ ("remote", "SELECT * FROM remote('other-host', db.t)"),+ ("mysql", "SELECT * FROM mysql('h:3306', 'db', 't', 'u', 'p')"),+ ("postgresql", "SELECT * FROM postgresql('h:5432', 'db', 't', 'u', 'p')"),+ ("file", "SELECT * FROM file('/etc/passwd', 'LineAsString')"),+ ("executable", "SELECT * FROM executable('script.sh', 'TabSeparated', 'x String')"),+ # Nested inside a subquery — the whole tree is walked.+ ("nested", "SELECT * FROM (SELECT * FROM url('http://x'))"),+ ("uppercase", "SELECT * FROM URL('http://x')"),+ # `*Cluster` twins read remotely just like their base function.+ ("iceberg_cluster", "SELECT * FROM icebergCluster('c', 'http://169.254.169.254/')"),+ ("delta_lake_cluster", "SELECT * FROM deltaLakeCluster('c', 'http://x')"),+ # merge() reads across every table the server can see; dictionary() can be remote-backed.+ ("merge", "SELECT * FROM merge('.*', '.*')"),+ ("dictionary", "SELECT * FROM dictionary('dict')"),+ # Quoted callees must still be caught — a double-quoted name doesn't parse as a Function.+ ("double_quoted_remote", "SELECT * FROM \"remote\"('other-host', db.t)"),+ ("backtick_remote", "SELECT * FROM `remote`('other-host', db.t)"),+ ]+ )+ def test_rejects_dangerous_table_functions(self, _name, sql):+ with self.assertRaises(ExposedHogQLError):+ ensure_read_only_raw_clickhouse_statement(sql)++ @parameterized.expand(+ [+ ("insert", "INSERT INTO events VALUES (1)"),+ ("alter", "ALTER TABLE events DELETE WHERE 1"),+ ("drop", "DROP TABLE events"),+ ("truncate", "TRUNCATE TABLE events"),+ ("system", "SYSTEM RELOAD DICTIONARIES"),+ ("multi_statement", "SELECT 1; DROP TABLE events"),+ # A first-keyword check treated these as read-only because they open with WITH/SELECT,+ # but the driver still runs the embedded write — the whole statement must be inspected.+ ("with_prefixed_insert", "WITH 1 AS x INSERT INTO target SELECT x"),+ ("write_in_subquery", "SELECT * FROM (INSERT INTO events VALUES (1))"),+ ]+ )+ def test_rejects_writes(self, _name, sql):+ with self.assertRaises(ExposedHogQLError):+ ensure_read_only_raw_clickhouse_statement(sql)+++class TestClickHouseRowCap(SimpleTestCase):+ def _stream_client(self, blocks: list[list[tuple]]) -> MagicMock:+ stream = MagicMock()+ stream.source.column_names = ["n"]+ stream.source.column_types = ["Int64"]+ stream.__iter__.return_value = iter(blocks)+ client = MagicMock()+ client.query_row_block_stream.return_value.__enter__.return_value = stream+ client.query_row_block_stream.return_value.__exit__.return_value = False+ return client++ def test_returns_rows_and_types_under_cap(self):+ client = self._stream_client([[(1,), (2,)], [(3,)]])+ rows, column_names, column_types = _fetch_capped_clickhouse_rows(client, "SELECT n FROM t", None, 600)+ self.assertEqual(rows, [(1,), (2,), (3,)])+ self.assertEqual(column_names, ["n"])+ self.assertEqual(column_types, ["Int64"])++ def test_raises_when_result_exceeds_cap(self):+ # The streaming guard trips one row past the cap — the memory-exhaustion path a raw+ # unbounded SELECT hits. Patch the cap small so the test doesn't allocate a million rows.+ client = self._stream_client([[(0,), (1,)], [(2,), (3,)]])+ with patch("posthog.hogql.direct_sql.clickhouse_adapter.DIRECT_CLICKHOUSE_MAX_ROWS", 3):+ with self.assertRaisesRegex(ExposedHogQLError, "Add a LIMIT clause"):+ _fetch_capped_clickhouse_rows(client, "SELECT n FROM t", None, 600)++ def test_raises_when_deadline_exceeded(self):+ # A raw query can set SETTINGS max_execution_time=0 and dribble out tiny blocks so the+ # socket timeout never fires; the wall-clock deadline is what stops it pinning the worker.+ client = self._stream_client([[(1,)], [(2,)]])+ with patch("posthog.hogql.direct_sql.clickhouse_adapter.perf_counter", side_effect=[0.0, 700.0]):+ with self.assertRaisesRegex(ExposedHogQLError, "execution time limit"):+ _fetch_capped_clickhouse_rows(client, "SELECT n FROM t", None, 600)++ def test_passes_parameters_through(self):+ client = self._stream_client([[(1,)]])+ params: dict[str, Any] = {"team_id": 1}+ _fetch_capped_clickhouse_rows(client, "SELECT n FROM t WHERE team = %(team_id)s", params, 600)+ client.query_row_block_stream.assert_called_once_with(+ "SELECT n FROM t WHERE team = %(team_id)s", parameters=params+ )diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.pyindex 081ad4c1c45e..f337adf872f2 100644--- a/posthog/hogql/direct_sql/test/test_registry_and_capability.py+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py@@ -3,6 +3,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom posthog.hogql.direct_sql import (+ ClickHouseAdapter,MySQLAdapter,PostgresAdapter,registry as registry_module,@@ -18,13 +19,20 @@ class TestDirectSQLRegistry(SimpleTestCase):def test_get_adapter_returns_registered_engine_adapter(self):self.assertIsInstance(get_adapter("postgres"), PostgresAdapter)self.assertIsInstance(get_adapter("mysql"), MySQLAdapter)+ self.assertIsInstance(get_adapter("clickhouse"), ClickHouseAdapter)@parameterized.expand([("none", None), ("unregistered", "bigquery")])def test_get_adapter_returns_none_for_unknown_engine(self, _name, engine):self.assertIsNone(get_adapter(engine))- def test_registered_engines_includes_phase_one_engines(self):- self.assertEqual({"postgres", "mysql", "snowflake", "redshift"}, set(registered_engines()))+ def test_registered_engines_includes_all_engines(self):+ self.assertEqual({"postgres", "mysql", "snowflake", "redshift", "clickhouse"}, set(registered_engines()))++ def test_clickhouse_adapter_compiles_hogql(self):+ adapter = get_adapter("clickhouse")+ assert adapter is not None+ # dialect is non-None, so direct_supports_hogql is True (not raw-only).+ self.assertEqual(adapter.dialect, "clickhouse")def test_register_adapter_round_trips(self):class FakeAdapter:@@ -46,6 +54,10 @@ class TestDirectSQLCapability(SimpleTestCase):("postgres_synced_disabled", ExternalDataSourceType.POSTGRES, "warehouse", False, False),("mysql_synced_enabled", ExternalDataSourceType.MYSQL, "warehouse", True, True),("snowflake_direct_ignores_toggle", ExternalDataSourceType.SNOWFLAKE, "direct", False, True),+ ("clickhouse_direct_ignores_toggle", ExternalDataSourceType.CLICKHOUSE, "direct", False, True),+ ("clickhouse_synced_enabled", ExternalDataSourceType.CLICKHOUSE, "warehouse", True, True),+ ("clickhouse_synced_disabled", ExternalDataSourceType.CLICKHOUSE, "warehouse", False, False),+ ("clickhousecloud_direct", ExternalDataSourceType.CLICKHOUSECLOUD, "direct", False, True),("unmapped_engine_synced", ExternalDataSourceType.STRIPE, "warehouse", True, False),("unmapped_engine_direct", ExternalDataSourceType.STRIPE, "direct", True, False),]@@ -65,6 +77,8 @@ class TestDirectSQLCapability(SimpleTestCase):ExternalDataSourceType.MYSQL,ExternalDataSourceType.SNOWFLAKE,ExternalDataSourceType.REDSHIFT,+ ExternalDataSourceType.CLICKHOUSE,+ ExternalDataSourceType.CLICKHOUSECLOUD,},set(direct_capable_source_types()),)diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 6fc0306ed69f..b327ec9e09e7 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -17,6 +17,7 @@ if TYPE_CHECKING:from posthog.hogql import astfrom posthog.hogql.database.database import Database+from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTablefrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTablefrom posthog.hogql.database.direct_redshift_table import DirectRedshiftTable@@ -418,6 +419,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,DirectMySQLTable,DirectSnowflakeTable,DirectRedshiftTable,+ DirectClickHouseTable,]:if self.table is not None and self.is_materialized and modifiers is not None and modifiers.useMaterializedViews:return self.table.hogql_definition(modifiers)diff --git a/products/data_warehouse/backend/clickhouse_helpers.py b/products/data_warehouse/backend/clickhouse_helpers.pynew file mode 100644index 000000000000..6246ad954033--- /dev/null+++ b/products/data_warehouse/backend/clickhouse_helpers.py@@ -0,0 +1,277 @@+"""ClickHouse source helpers shared between warehouse and direct-query modes.++Direct-query-only utilities (DataWarehouseTable upserts, the `direct://clickhouse` url_pattern, the+option keys that encode source location on a direct table) live in `direct_clickhouse.py`. ClickHouse+namespaces a table as database.table — there is no separate catalog level, and no foreign keys.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from django.db.models import Q++import structlog++from products.data_warehouse.backend.direct_clickhouse import (+ DIRECT_CLICKHOUSE_DATABASE_OPTION,+ DIRECT_CLICKHOUSE_TABLE_OPTION,+ hide_direct_clickhouse_table,+ upsert_direct_clickhouse_table,+)+from products.warehouse_sources.backend.facade.models import (+ ExternalDataSource,+ clickhouse_column_to_dwh_column,+ clickhouse_columns_to_dwh_columns,+)+from products.warehouse_sources.backend.facade.source_management import (+ SourceSchema,+ extract_available_column_names,+ filter_columns_by_enabled_columns,+ filter_dwh_columns_by_enabled_columns,+ normalize_namespace,+ prune_enabled_columns,+ sql_schema_metadata,+)++if TYPE_CHECKING:+ pass++log = structlog.get_logger(__name__)++type ClickHouseDwhColumns = dict[str, dict[str, Any]]+# (database, table). ClickHouse has no separate catalog level.+type ClickHouseSourceLocation = tuple[str, str]++# ClickHouse's implicit default database when a source config leaves it unset.+_DEFAULT_CLICKHOUSE_DATABASE = "default"+++def clickhouse_schema_metadata_to_dwh_columns(schema_metadata: dict[str, Any] | None) -> ClickHouseDwhColumns:+ resolved: ClickHouseDwhColumns = {}+ if not schema_metadata:+ return resolved+ columns = schema_metadata.get("columns")+ if not isinstance(columns, list):+ return resolved+ for column in columns:+ if not isinstance(column, dict):+ continue+ column_name = column.get("name")+ clickhouse_type = column.get("data_type")+ nullable = bool(column.get("is_nullable"))+ if not isinstance(column_name, str) or not isinstance(clickhouse_type, str):+ continue+ resolved[column_name] = clickhouse_column_to_dwh_column(column_name, clickhouse_type, nullable)+ return resolved+++def get_clickhouse_source_location(+ *,+ schema_name: str,+ schema_metadata: dict[str, Any] | None = None,+ default_database: str | None = None,+) -> ClickHouseSourceLocation:+ """Resolve `(source_database, source_table_name)` for a ClickHouse row.++ Priority: explicit metadata → dot-split when no default database → default database fallback.+ """+ source_schema = schema_metadata.get("source_schema") if isinstance(schema_metadata, dict) else None+ source_table_name = schema_metadata.get("source_table_name") if isinstance(schema_metadata, dict) else None+ normalized_default = normalize_namespace(default_database)++ if isinstance(source_schema, str) and isinstance(source_table_name, str):+ return source_schema, source_table_name++ if normalized_default is None and "." in schema_name:+ inferred_database, inferred_table = schema_name.split(".", 1)+ return inferred_database, inferred_table++ return normalized_default or _DEFAULT_CLICKHOUSE_DATABASE, schema_name+++def get_clickhouse_source_location_for_schema_model(+ *,+ schema_name: str,+ sync_type_config: dict[str, Any] | None = None,+ table_options: dict[str, Any] | None = None,+ default_database: str | None = None,+) -> ClickHouseSourceLocation:+ schema_metadata = (+ sync_type_config.get("schema_metadata")+ if isinstance(sync_type_config, dict) and isinstance(sync_type_config.get("schema_metadata"), dict)+ else None+ )+ if schema_metadata is not None:+ return get_clickhouse_source_location(+ schema_name=schema_name, schema_metadata=schema_metadata, default_database=default_database+ )++ table_source_database = (+ table_options.get(DIRECT_CLICKHOUSE_DATABASE_OPTION) if isinstance(table_options, dict) else None+ )+ table_source_table_name = (+ table_options.get(DIRECT_CLICKHOUSE_TABLE_OPTION) if isinstance(table_options, dict) else None+ )+ if isinstance(table_source_database, str) and isinstance(table_source_table_name, str):+ return table_source_database, table_source_table_name++ if "." in schema_name:+ inferred_database, inferred_table = schema_name.split(".", 1)+ return inferred_database, inferred_table++ return get_clickhouse_source_location(+ schema_name=schema_name, schema_metadata=None, default_database=default_database+ )+++def reconcile_clickhouse_schemas(+ *,+ source: ExternalDataSource,+ source_schemas: list[SourceSchema],+ team_id: int,+) -> list[str]:+ """Persist `schema_metadata` on every ClickHouse row + (direct mode only) upsert its live-query+ `DataWarehouseTable`. Returns stale schema names that got soft-deleted (direct only)."""+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema++ is_direct = source.is_direct_query+ source_schema_names = [s.name for s in source_schemas]+ default_database = (source.job_inputs or {}).get("database")+ schema_models = {+ s.name: s+ for s in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related(+ "table"+ )+ }++ schema_models_by_location: dict[ClickHouseSourceLocation, ExternalDataSchema] = {}+ for schema_model in schema_models.values():+ location = get_clickhouse_source_location_for_schema_model(+ schema_name=schema_model.name,+ sync_type_config=schema_model.sync_type_config,+ table_options=schema_model.table.options if schema_model.table is not None else None,+ default_database=default_database,+ )+ schema_models_by_location.setdefault(location, schema_model)++ for source_schema in source_schemas:+ matched: ExternalDataSchema | None = schema_models.get(source_schema.name)+ if matched is None:+ location = get_clickhouse_source_location(+ schema_name=source_schema.name,+ schema_metadata={+ "source_schema": source_schema.source_schema,+ "source_table_name": source_schema.source_table_name,+ },+ default_database=default_database,+ )+ matched = schema_models_by_location.get(location)+ if matched is None:+ continue++ resolved_database, resolved_table = get_clickhouse_source_location(+ schema_name=source_schema.name,+ schema_metadata={+ "source_schema": source_schema.source_schema,+ "source_table_name": source_schema.source_table_name,+ },+ default_database=default_database,+ )+ # Metadata holds the full column list (column-picker UI); projection lives on `enabled_columns`.+ schema_metadata = sql_schema_metadata(+ source_schema.columns,+ [],+ source_catalog=None,+ source_schema=resolved_database,+ source_table_name=resolved_table,+ )+ new_sync_type_config = {**(matched.sync_type_config or {}), "schema_metadata": schema_metadata}+ if source_schema.detected_primary_keys and not new_sync_type_config.get("primary_key_columns"):+ new_sync_type_config["primary_key_columns"] = source_schema.detected_primary_keys+ matched.sync_type_config = new_sync_type_config+ update_fields = ["sync_type_config", "updated_at"]++ available_names = extract_available_column_names(schema_metadata)+ pruned_enabled_columns, removed_columns = prune_enabled_columns(matched.enabled_columns, available_names)+ if removed_columns:+ log.info(+ "clickhouse.reconcile_schemas.pruned_enabled_columns",+ source_id=str(source.id),+ schema_id=str(matched.id),+ schema_name=matched.name,+ removed_columns=removed_columns,+ )+ matched.enabled_columns = pruned_enabled_columns+ update_fields.append("enabled_columns")+ matched.save(update_fields=update_fields)++ if not is_direct:+ continue++ if not matched.should_sync:+ hide_direct_clickhouse_table(matched.table)+ continue++ projected_columns = filter_columns_by_enabled_columns(+ source_schema.columns,+ matched.enabled_columns,+ source_schema.detected_primary_keys,+ matched.incremental_field,+ )+ table_model = upsert_direct_clickhouse_table(+ matched.table,+ schema_name=source_schema.name,+ source=source,+ columns=clickhouse_columns_to_dwh_columns(projected_columns),+ source_database=resolved_database,+ source_table_name=resolved_table,+ )+ if matched.table_id != table_model.id:+ matched.table = table_model+ matched.save(update_fields=["table"])++ if not is_direct:+ return []++ stale_names: list[str] = []+ stale = ExternalDataSchema.objects.filter(+ Q(team_id=team_id, source_id=source.id),+ Q(deleted=False) | Q(table__deleted=False),+ ).exclude(name__in=source_schema_names)+ for s in stale:+ hide_direct_clickhouse_table(s.table)+ if not s.deleted:+ s.soft_delete()+ stale_names.append(s.name)+ return stale_names+++def reproject_direct_clickhouse_table(+ schema_row: Any,+ *,+ source: ExternalDataSource,+ enabled_columns: list[str] | None,+) -> Any:+ """Rebuild the direct-query `DataWarehouseTable` with a fresh column projection — used on+ column-picker save and on `should_sync` False → True. No re-sync needed in direct mode."""+ source_database, source_table_name = get_clickhouse_source_location(+ schema_name=schema_row.name,+ schema_metadata=schema_row.schema_metadata,+ default_database=(source.job_inputs or {}).get("database"),+ )+ return upsert_direct_clickhouse_table(+ schema_row.table,+ schema_name=schema_row.name,+ source=source,+ columns=filter_dwh_columns_by_enabled_columns(+ clickhouse_schema_metadata_to_dwh_columns(schema_row.schema_metadata),+ enabled_columns,+ schema_row.primary_key_columns,+ schema_row.incremental_field,+ # Direct-ClickHouse columns are keyed by raw, case-sensitive source names.+ normalize=False,+ ),+ source_database=source_database,+ source_table_name=source_table_name,+ )diff --git a/products/data_warehouse/backend/direct_clickhouse.py b/products/data_warehouse/backend/direct_clickhouse.pynew file mode 100644index 000000000000..1dfb95e074fe--- /dev/null+++ b/products/data_warehouse/backend/direct_clickhouse.py@@ -0,0 +1,80 @@+"""Direct-query ClickHouse helpers — manages the live-query `DataWarehouseTable` that lets HogQL hit+an external ClickHouse without going through Delta. Code shared with warehouse mode lives in+`clickhouse_helpers.py`. ClickHouse namespaces a table as database.table (no separate catalog level).+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from products.warehouse_sources.backend.facade.models import ExternalDataSource++if TYPE_CHECKING:+ from products.warehouse_sources.backend.models.table import DataWarehouseTable++type DirectClickHouseColumns = dict[str, dict[str, Any]]++DIRECT_CLICKHOUSE_URL_PATTERN = "direct://clickhouse"+DIRECT_CLICKHOUSE_DATABASE_OPTION = "direct_clickhouse_database"+DIRECT_CLICKHOUSE_TABLE_OPTION = "direct_clickhouse_table"+++def get_direct_clickhouse_table_options(*, source_database: str, source_table_name: str) -> dict[str, str]:+ return {+ DIRECT_CLICKHOUSE_DATABASE_OPTION: source_database,+ DIRECT_CLICKHOUSE_TABLE_OPTION: source_table_name,+ }+++def upsert_direct_clickhouse_table(+ existing_table: DataWarehouseTable | None,+ *,+ schema_name: str,+ source: ExternalDataSource,+ columns: DirectClickHouseColumns,+ source_database: str,+ source_table_name: str,+) -> DataWarehouseTable:+ from products.warehouse_sources.backend.facade.models import DataWarehouseTable++ options = {+ **(existing_table.options if existing_table is not None and isinstance(existing_table.options, dict) else {}),+ **get_direct_clickhouse_table_options(source_database=source_database, source_table_name=source_table_name),+ }++ if existing_table is None:+ return DataWarehouseTable.objects.create(+ name=schema_name,+ format=DataWarehouseTable.TableFormat.Parquet,+ team_id=source.team_id,+ url_pattern=DIRECT_CLICKHOUSE_URL_PATTERN,+ external_data_source=source,+ columns=columns,+ options=options,+ )++ existing_table.name = schema_name+ existing_table.url_pattern = DIRECT_CLICKHOUSE_URL_PATTERN+ existing_table.external_data_source = source+ existing_table.columns = columns+ existing_table.options = options+ existing_table.deleted = False+ existing_table.deleted_at = None+ existing_table.save(+ update_fields=[+ "name",+ "url_pattern",+ "external_data_source",+ "columns",+ "options",+ "deleted",+ "deleted_at",+ "updated_at",+ ]+ )+ return existing_table+++def hide_direct_clickhouse_table(table: DataWarehouseTable | None) -> None:+ if table is not None and not table.deleted:+ table.soft_delete()diff --git a/products/data_warehouse/backend/direct_query_engines.py b/products/data_warehouse/backend/direct_query_engines.pyindex d182b49fbd52..230abfea3671 100644--- a/products/data_warehouse/backend/direct_query_engines.py+++ b/products/data_warehouse/backend/direct_query_engines.py@@ -12,6 +12,15 @@ columns, creating / reprojecting / hiding the row) and reconciling schema rows ofrom abc import ABC, abstractmethodfrom typing import Any+from products.data_warehouse.backend.clickhouse_helpers import (+ get_clickhouse_source_location,+ reconcile_clickhouse_schemas,+ reproject_direct_clickhouse_table,+)+from products.data_warehouse.backend.direct_clickhouse import (+ hide_direct_clickhouse_table,+ upsert_direct_clickhouse_table,+)from products.data_warehouse.backend.direct_mysql import hide_direct_mysql_table, upsert_direct_mysql_tablefrom products.data_warehouse.backend.direct_postgres import hide_direct_postgres_table, upsert_direct_postgres_tablefrom products.data_warehouse.backend.direct_redshift import hide_direct_redshift_table, upsert_direct_redshift_table@@ -37,6 +46,7 @@ from products.data_warehouse.backend.snowflake_helpers import (reproject_direct_snowflake_table,)from products.warehouse_sources.backend.facade.api import (+ clickhouse_columns_to_dwh_columns,mysql_columns_to_dwh_columns,postgres_columns_to_dwh_columns,snowflake_columns_to_dwh_columns,@@ -275,8 +285,50 @@ class _RedshiftEngine(DirectQueryEngine):return reconcile_redshift_schemas(source=source, source_schemas=source_schemas, team_id=team_id)+class _ClickHouseEngine(DirectQueryEngine):+ engine = "clickhouse"++ def source_table_location(self, *, schema_name, source_schema, default_schema, default_catalog=None):+ # ClickHouse has no catalog level; database occupies the "schema" slot, catalog stays None.+ database, table = get_clickhouse_source_location(+ schema_name=schema_name,+ schema_metadata=_location_metadata(source_schema),+ default_database=default_schema,+ )+ return None, database, table++ def columns_to_dwh_columns(self, source_columns):+ return clickhouse_columns_to_dwh_columns(source_columns)++ def upsert_table(+ self, existing_table, *, schema_name, source, columns, source_catalog, source_schema, source_table_name+ ):+ # source_schema carries the ClickHouse database; there is no catalog.+ return upsert_direct_clickhouse_table(+ existing_table,+ schema_name=schema_name,+ source=source,+ columns=columns,+ source_database=source_schema,+ source_table_name=source_table_name,+ )++ def reproject_table(self, schema_row, *, source, enabled_columns):+ return reproject_direct_clickhouse_table(schema_row, source=source, enabled_columns=enabled_columns)++ def hide_table(self, table):+ hide_direct_clickhouse_table(table)++ def reconcile_schemas(self, *, source, source_schemas, team_id):+ return reconcile_clickhouse_schemas(source=source, source_schemas=source_schemas, team_id=team_id)++ # No refresh_name_substitutions override — like MySQL/Snowflake/Redshift, ClickHouse has no+ # bespoke legacy-row remapping (only Postgres does), so it falls through to the generic path.++_ENGINES: dict[str, DirectQueryEngine] = {- engine.engine: engine for engine in (_PostgresEngine(), _MySQLEngine(), _SnowflakeEngine(), _RedshiftEngine())+ engine.engine: engine+ for engine in (_PostgresEngine(), _MySQLEngine(), _SnowflakeEngine(), _RedshiftEngine(), _ClickHouseEngine())}diff --git a/products/data_warehouse/backend/direct_virtual_tables.py b/products/data_warehouse/backend/direct_virtual_tables.pyindex 1eb81b65337c..737bdc598c27 100644--- a/products/data_warehouse/backend/direct_virtual_tables.py+++ b/products/data_warehouse/backend/direct_virtual_tables.py@@ -9,12 +9,17 @@ objects the pure-direct path derives from physical rows, but from eachfrom typing import TYPE_CHECKING+from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTablefrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTablefrom posthog.hogql.database.direct_redshift_table import DirectRedshiftTablefrom posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.direct_sql_table import DirectSQLTable+from products.data_warehouse.backend.clickhouse_helpers import (+ clickhouse_schema_metadata_to_dwh_columns,+ get_clickhouse_source_location,+)from products.data_warehouse.backend.mysql_helpers import (get_default_mysql_schema,get_mysql_source_location,@@ -197,4 +202,31 @@ def build_direct_table_for_schema(schema: "ExternalDataSchema", source: "Externaconnection_metadata=source.connection_metadata,)+ if engine == "clickhouse":+ columns = clickhouse_schema_metadata_to_dwh_columns(metadata)+ if not columns:+ return None+ columns = filter_dwh_columns_by_enabled_columns(+ columns,+ schema.enabled_columns,+ schema.primary_key_columns,+ schema.incremental_field,+ # Direct-ClickHouse columns are keyed by raw, case-sensitive source names.+ normalize=False,+ )+ fields, _ = hogql_fields_and_structure_for_columns(columns)+ clickhouse_database, table_name = get_clickhouse_source_location(+ schema_name=schema.name,+ schema_metadata=metadata,+ default_database=(source.job_inputs or {}).get("database"),+ )+ return DirectClickHouseTable(+ name=schema.name,+ fields=fields,+ clickhouse_database=clickhouse_database,+ clickhouse_table_name=table_name,+ external_data_source_id=str(source.id),+ connection_metadata=source.connection_metadata,+ )+return Nonediff --git a/products/data_warehouse/backend/facade/sources.py b/products/data_warehouse/backend/facade/sources.pyindex 49e34fcb8e48..6c1c6e58fda7 100644--- a/products/data_warehouse/backend/facade/sources.py+++ b/products/data_warehouse/backend/facade/sources.py@@ -6,6 +6,10 @@ imports (no DB drivers) so the setup-path consumers (the warehouse_sources tablemodel) add no boot cost."""+from products.data_warehouse.backend.direct_clickhouse import (+ DIRECT_CLICKHOUSE_DATABASE_OPTION,+ DIRECT_CLICKHOUSE_TABLE_OPTION,+)from products.data_warehouse.backend.direct_mysql import DIRECT_MYSQL_SCHEMA_OPTION, DIRECT_MYSQL_TABLE_OPTIONfrom products.data_warehouse.backend.direct_postgres import (DIRECT_POSTGRES_CATALOG_OPTION,@@ -24,6 +28,8 @@ from products.data_warehouse.backend.direct_snowflake import ()__all__ = [+ "DIRECT_CLICKHOUSE_DATABASE_OPTION",+ "DIRECT_CLICKHOUSE_TABLE_OPTION","DIRECT_MYSQL_SCHEMA_OPTION","DIRECT_MYSQL_TABLE_OPTION","DIRECT_POSTGRES_CATALOG_OPTION",diff --git a/products/data_warehouse/backend/test/test_direct_query_engines.py b/products/data_warehouse/backend/test/test_direct_query_engines.pyindex e46fed18eafa..df78ce9c58df 100644--- a/products/data_warehouse/backend/test/test_direct_query_engines.py+++ b/products/data_warehouse/backend/test/test_direct_query_engines.py@@ -10,7 +10,7 @@ def _source_schema(*, catalog=None, schema=None, table=None):class TestDirectQueryEngineRegistry:- @parameterized.expand(["postgres", "mysql", "snowflake", "redshift"])+ @parameterized.expand(["postgres", "mysql", "snowflake", "redshift", "clickhouse"])def test_known_engine_resolves(self, engine: str):adapter = get_direct_query_engine(engine)assert adapter is not None@@ -28,6 +28,7 @@ class TestDirectQueryEngineRegistry:("mysql", False),("snowflake", False),("redshift", False),+ ("clickhouse", False),])def test_resolves_location_in_warehouse_mode(self, engine: str, expected: bool):@@ -43,6 +44,8 @@ class TestDirectQueryEngineRegistry:("snowflake", ("db", "public", "users")),("redshift", ("db", "public", "users")),("mysql", (None, "public", "users")),+ # ClickHouse has no catalog level — the database occupies the "schema" slot.+ ("clickhouse", (None, "public", "users")),])def test_source_table_location_uses_explicit_metadata(self, engine: str, expected: tuple):@@ -82,7 +85,7 @@ class TestDirectQueryEngineRegistry:)assert location == ("WAREHOUSE", "analytics", "events")- @parameterized.expand(["mysql", "snowflake", "redshift"])+ @parameterized.expand(["mysql", "snowflake", "redshift", "clickhouse"])def test_non_postgres_engines_return_no_name_substitutions(self, engine: str):# Returning None (not {}) is the sentinel that makes the view fall through to the generic# multi-schema migration path; only Postgres has bespoke legacy-row remapping.diff --git a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.tsindex 8f78c1e95aa6..306edbcf6584 100644--- a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts+++ b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts@@ -1,7 +1,7 @@import { groupBy } from 'lib/utils/arrays'/** Source types that support `access_method: 'direct'` (live querying without syncing to the warehouse). */-export const DIRECT_QUERY_SOURCE_TYPES = ['Postgres', 'MySQL', 'Snowflake', 'Redshift'] as const+export const DIRECT_QUERY_SOURCE_TYPES = ['Postgres', 'MySQL', 'Snowflake', 'Redshift', 'ClickHouse'] as constexport function supportsDirectQuery(sourceType: string | null | undefined): boolean {return !!sourceType && DIRECT_QUERY_SOURCE_TYPES.includes(sourceType as (typeof DIRECT_QUERY_SOURCE_TYPES)[number])diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex bf9e2dca4e25..07e41c6874b7 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTable a# Framework-free helper transforms — re-exported as the public helper surface.from products.warehouse_sources.backend.models.util import (+ clickhouse_columns_to_dwh_columns,mysql_column_to_dwh_column,mysql_columns_to_dwh_columns,postgres_column_to_dwh_column,@@ -56,6 +57,7 @@ __all__ = ["list_tables_for_source","list_jobs_for_source",# framework-free helper transforms+ "clickhouse_columns_to_dwh_columns","mysql_column_to_dwh_column","mysql_columns_to_dwh_columns","postgres_column_to_dwh_column",diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.pyindex a48eda57607b..3c9ae79963e3 100644--- a/products/warehouse_sources/backend/facade/models.py+++ b/products/warehouse_sources/backend/facade/models.py@@ -47,6 +47,8 @@ from products.warehouse_sources.backend.models.table import (asave_datawarehousetable,)from products.warehouse_sources.backend.models.util import (+ clickhouse_column_to_dwh_column,+ clickhouse_columns_to_dwh_columns,mysql_column_to_dwh_column,mysql_columns_to_dwh_columns,postgres_column_to_dwh_column,@@ -79,6 +81,8 @@ __all__ = ["get_direct_external_data_source_for_connection","get_latest_run_if_exists","get_or_create_datawarehouse_credential",+ "clickhouse_column_to_dwh_column",+ "clickhouse_columns_to_dwh_columns","mysql_column_to_dwh_column","mysql_columns_to_dwh_columns","postgres_column_to_dwh_column",diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 9cc984411d27..fb4184c25030 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -16,6 +16,7 @@ from clickhouse_driver.errors import ServerException as ClickHouseServerExceptiofrom posthog.hogql import astfrom posthog.hogql.constants import HogQLQuerySettingsfrom posthog.hogql.context import HogQLContext+from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTablefrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTablefrom posthog.hogql.database.direct_redshift_table import DirectRedshiftTable@@ -614,11 +615,20 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletdef hogql_definition(self, modifiers: Optional["HogQLQueryModifiers"] = None- ) -> HogQLDataWarehouseTable | DirectPostgresTable | DirectMySQLTable | DirectSnowflakeTable | DirectRedshiftTable:+ ) -> (+ HogQLDataWarehouseTable+ | DirectPostgresTable+ | DirectMySQLTable+ | DirectSnowflakeTable+ | DirectRedshiftTable+ | DirectClickHouseTable+ ):# Deferred: importing data_warehouse's facade at module scope creates an import cycle# (data_warehouse models -> this model package -> data_warehouse.facade.sources -> ...).# These direct-query option keys are only needed here, at query-build time.from products.data_warehouse.backend.facade.sources import ( # noqa: PLC0415 — breaks an import cycle+ DIRECT_CLICKHOUSE_DATABASE_OPTION,+ DIRECT_CLICKHOUSE_TABLE_OPTION,DIRECT_MYSQL_SCHEMA_OPTION,DIRECT_MYSQL_TABLE_OPTION,DIRECT_POSTGRES_CATALOG_OPTION,@@ -740,6 +750,28 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletconnection_metadata=self.external_data_source.connection_metadata,)+ # Engine-keyed (no is_direct_clickhouse) to satisfy the source-agnostic guard.+ if self.external_data_source and self.external_data_source.direct_engine == "clickhouse":+ job_inputs = self.external_data_source.job_inputs or {}+ clickhouse_database = (+ self.options.get(DIRECT_CLICKHOUSE_DATABASE_OPTION)+ if isinstance(self.options.get(DIRECT_CLICKHOUSE_DATABASE_OPTION), str)+ else job_inputs.get("database", "default")+ )+ clickhouse_table_name = (+ self.options.get(DIRECT_CLICKHOUSE_TABLE_OPTION)+ if isinstance(self.options.get(DIRECT_CLICKHOUSE_TABLE_OPTION), str)+ else self.name+ )+ return DirectClickHouseTable(+ name=self.name,+ fields=fields,+ clickhouse_database=clickhouse_database,+ clickhouse_table_name=clickhouse_table_name,+ external_data_source_id=str(self.external_data_source_id),+ connection_metadata=self.external_data_source.connection_metadata,+ )+# Replace fields with any redefined fields if they existexternal_table_fields = external_tables.get(self.table_name_without_prefix())default_fields = external_tables.get("*", {})diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex 19e9cca52f8a..fd9af8f84842 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -550,6 +550,34 @@ def snowflake_columns_to_dwh_columns(columns: list[tuple[str, str, bool]]) -> di}+def clickhouse_column_to_dwh_column(_column_name: str, clickhouse_type: str, nullable: bool) -> dict[str, Any]:+ # The source is already ClickHouse, so the type string is a valid ClickHouse type — used verbatim.+ # `system.columns.type` usually already encodes nullability, so only wrap when it doesn't.+ ch_type = clickhouse_type.strip()+ already_nullable = ch_type.startswith("Nullable(") or ch_type.startswith("LowCardinality(Nullable(")+ if nullable and not already_nullable:+ if ch_type.startswith("LowCardinality(") and ch_type.endswith(")"):+ # LowCardinality must stay the outermost wrapper — ClickHouse rejects+ # Nullable(LowCardinality(...)), so nest Nullable inside it instead.+ inner = ch_type[len("LowCardinality(") : -1]+ ch_type = f"LowCardinality(Nullable({inner}))"+ else:+ ch_type = f"Nullable({ch_type})"+ raw_clickhouse_type = clean_type(ch_type)+ return {+ "clickhouse": ch_type,+ "hogql": CLICKHOUSE_TYPE_TO_HOGQL_LABEL.get(raw_clickhouse_type, "string"),+ "valid": True,+ }+++def clickhouse_columns_to_dwh_columns(columns: list[tuple[str, str, bool]]) -> dict[str, dict[str, Any]]:+ return {+ column_name: clickhouse_column_to_dwh_column(column_name, clickhouse_type, nullable)+ for column_name, clickhouse_type, nullable in columns+ }++def _is_safe_public_ip(host: str) -> bool:ip = ip_address(host)diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pyindex 361687dd25d7..dac801aab10c 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py@@ -469,10 +469,10 @@ def get_postgres_source_table_location(DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = (- "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources."+ "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, Redshift, and ClickHouse sources.")# Engines surfaced on a direct connection's `connection_metadata.engine` (duckdb backs direct Postgres).-DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake", "redshift"]+DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake", "redshift", "clickhouse"]def count_active_sources(team_id: int, source_type: str) -> int:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.pyindex 6ef7d92d3867..3d5050e61911 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clickhouse/source.py@@ -1,4 +1,6 @@-from typing import TYPE_CHECKING, Optional, cast+from collections.abc import Iterator+from contextlib import contextmanager+from typing import TYPE_CHECKING, Any, Optional, castfrom clickhouse_connect.driver.exceptions import ClickHouseError, DatabaseError, OperationalErrorfrom sshtunnel import BaseSSHTunnelForwarderError@@ -23,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.sources.clickhouse.clickhouse import (ClickHouseConnectionError,+ _get_client,clickhouse_source,filter_clickhouse_incremental_fields,get_clickhouse_row_count,@@ -46,6 +49,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldif TYPE_CHECKING:+ from clickhouse_connect.driver.client import Client as ClickHouseClient+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource# Shown when we can't map the failure to a specific cause. Names the usual@@ -281,6 +286,39 @@ class ClickHouseSource(SimpleSource[ClickHouseSourceConfig], SSHTunnelMixin, Val"returned response code 504",}+ @contextmanager+ def direct_query_client(+ self,+ config: ClickHouseSourceConfig,+ team_id: int,+ *,+ query_timeout: int,+ settings: dict[str, Any] | None = None,+ ) -> Iterator["ClickHouseClient"]:+ """Open a client against the source's ClickHouse for a single direct (HogQL) query.++ Opens the SSH tunnel (if any) for the life of the query and yields a clickhouse-connect+ client, closing both on exit. Client construction is an internal detail, so it stays in+ the product — the direct-SQL adapter drives the query through this method rather than+ importing the client factory.+ """+ with self.with_ssh_tunnel(config, team_id) as (host, port):+ client = _get_client(+ host=host,+ port=port,+ database=config.database,+ user=config.user,+ password=config.password,+ secure=config.secure,+ verify=config.verify,+ query_timeout=query_timeout,+ settings=settings,+ )+ try:+ yield client+ finally:+ client.close()+def get_schemas(self,config: ClickHouseSourceConfig,diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex dce0af2dd648..b85b9d973d0d 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -4553,7 +4553,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.json(),{- "message": "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources."+ "message": "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, Redshift, and ClickHouse sources."},)@@ -4571,7 +4571,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.json(),{- "message": "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources."+ "message": "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, Redshift, and ClickHouse sources."},)diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 83996c5a34c2..fb91c834064c 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -27,7 +27,11 @@ from products.warehouse_sources.backend.models.external_data_source import Exterfrom products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEventfrom products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnelfrom products.warehouse_sources.backend.models.table import DataWarehouseTable-from products.warehouse_sources.backend.models.util import CLICKHOUSE_HOGQL_MAPPING, clean_type+from products.warehouse_sources.backend.models.util import (+ CLICKHOUSE_HOGQL_MAPPING,+ clean_type,+ clickhouse_column_to_dwh_column,+)from products.warehouse_sources.backend.types import IncrementalFieldType@@ -557,6 +561,21 @@ def test_clean_type_unwraps_low_cardinality(clickhouse_type: str, expected: str)assert cleaned in CLICKHOUSE_HOGQL_MAPPING+ "clickhouse_type,nullable,expected",+ [+ ("String", False, "String"),+ ("String", True, "Nullable(String)"),+ ("Nullable(String)", True, "Nullable(String)"),+ # LowCardinality must stay outermost — ClickHouse rejects Nullable(LowCardinality(...)).+ ("LowCardinality(String)", True, "LowCardinality(Nullable(String))"),+ ("LowCardinality(Nullable(String))", True, "LowCardinality(Nullable(String))"),+ ],+)+def test_clickhouse_column_to_dwh_column_nullable_wrapping(clickhouse_type: str, nullable: bool, expected: str) -> None:+ assert clickhouse_column_to_dwh_column("col", clickhouse_type, nullable)["clickhouse"] == expected++@pytest.mark.parametrize("sync_type,expected",[diff --git a/products/warehouse_sources/backend/types.py b/products/warehouse_sources/backend/types.pyindex 1e54d6996d13..74c185d14f8f 100644--- a/products/warehouse_sources/backend/types.py+++ b/products/warehouse_sources/backend/types.py@@ -1301,6 +1301,8 @@ DIRECT_ENGINE_BY_SOURCE_TYPE: dict[str, str] = {ExternalDataSourceType.MYSQL: "mysql",ExternalDataSourceType.SNOWFLAKE: "snowflake",ExternalDataSourceType.REDSHIFT: "redshift",+ ExternalDataSourceType.CLICKHOUSE: "clickhouse",+ ExternalDataSourceType.CLICKHOUSECLOUD: "clickhouse",}diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 082a47b7a335..819f2225abb0 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -2937,6 +2937,7 @@ export const AccessMethodEnumApi = {* * `mysql` - mysql* * `snowflake` - snowflake* * `redshift` - redshift+ * * `clickhouse` - clickhouse*/export type EngineEnumApi = (typeof EngineEnumApi)[keyof typeof EngineEnumApi]@@ -2946,6 +2947,7 @@ export const EngineEnumApi = {Mysql: 'mysql',Snowflake: 'snowflake',Redshift: 'redshift',+ Clickhouse: 'clickhouse',} as constexport interface ExternalDataSourceRevenueAnalyticsConfigApi {@@ -3005,7 +3007,8 @@ export interface ExternalDataSourceSerializersApi {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake- * * `redshift` - redshift */+ * * `redshift` - redshift+ * * `clickhouse` - clickhouse */readonly engine: EngineEnumApi | null/** @nullable */readonly last_run_at: string | null@@ -4396,7 +4399,8 @@ export interface PatchedExternalDataSourceSerializersApi {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake- * * `redshift` - redshift */+ * * `redshift` - redshift+ * * `clickhouse` - clickhouse */readonly engine?: EngineEnumApi | null/** @nullable */readonly last_run_at?: string | null@@ -4522,7 +4526,8 @@ export interface ExternalDataSourceConnectionOptionApi {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake- * * `redshift` - redshift */+ * * `redshift` - redshift+ * * `clickhouse` - clickhouse */readonly engine: EngineEnumApi | null/** The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').*diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fb8a0758a8bd..3994dd1e4190 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23555,6 +23555,7 @@ export namespace Schemas {* * `mysql` - mysql* * `snowflake` - snowflake* * `redshift` - redshift+ * * `clickhouse` - clickhouse*/export type EngineEnum = typeof EngineEnum[keyof typeof EngineEnum];@@ -23565,6 +23566,7 @@ export namespace Schemas {Mysql: 'mysql',Snowflake: 'snowflake',Redshift: 'redshift',+ Clickhouse: 'clickhouse',} as const;export interface EngineeringAnalyticsCIBrokenDefaultBranchSignalExtra {@@ -27890,7 +27892,8 @@ export namespace Schemas {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake- * * `redshift` - redshift */+ * * `redshift` - redshift+ * * `clickhouse` - clickhouse */readonly engine: EngineEnum | null;/** The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').*@@ -30561,7 +30564,8 @@ export namespace Schemas {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake- * * `redshift` - redshift */+ * * `redshift` - redshift+ * * `clickhouse` - clickhouse */readonly engine: EngineEnum | null;/** @nullable */readonly last_run_at: string | null;@@ -48596,7 +48600,8 @@ export namespace Schemas {* * `postgres` - postgres* * `mysql` - mysql* * `snowflake` - snowflake- * * `redshift` - redshift */+ * * `redshift` - redshift+ * * `clickhouse` - clickhouse */readonly engine?: EngineEnum | null;/** @nullable */readonly last_run_at?: string | null;