: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(data-warehouse): fix clickhouse direct-query database and label (#74417)
Tom Owersd79d61d78c5a
diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.tsindex aaf5534d326e..b9693e543040 100644--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts@@ -5,6 +5,7 @@ import { ApiConfig } from 'lib/api'import { urls } from 'scenes/urls'import IconPostHog from 'public/posthog-icon.svg'+import IconClickHouse from 'public/services/clickhouse.png'import IconDuckDB from 'public/services/duckdb.svg'import IconMySQL from 'public/services/mysql.png'import IconPostgres from 'public/services/postgres.png'@@ -44,7 +45,7 @@ export interface ConnectionSelectOptionGroup {options: ConnectionSelectOption[]}-type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift'+type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift' | 'clickhouse'const ENGINE_LABELS: Record<ConnectionEngine, string> = {duckdb: 'DuckDB',@@ -52,6 +53,7 @@ const ENGINE_LABELS: Record<ConnectionEngine, string> = {mysql: 'MySQL',snowflake: 'Snowflake',redshift: 'Redshift',+ clickhouse: 'ClickHouse',}const ENGINE_ICONS: Record<ConnectionEngine, string> = {@@ -60,6 +62,7 @@ const ENGINE_ICONS: Record<ConnectionEngine, string> = {mysql: IconMySQL,snowflake: IconSnowflake,redshift: IconRedshift,+ clickhouse: IconClickHouse,}function getConnectionEngine(@@ -69,7 +72,8 @@ function getConnectionEngine(source.engine === 'duckdb' ||source.engine === 'mysql' ||source.engine === 'snowflake' ||- source.engine === 'redshift'+ source.engine === 'redshift' ||+ source.engine === 'clickhouse') {return source.engine}diff --git a/posthog/hogql/test/test_direct_clickhouse_query.py b/posthog/hogql/test/test_direct_clickhouse_query.pynew file mode 100644index 000000000000..41a2bfc240a5--- /dev/null+++ b/posthog/hogql/test/test_direct_clickhouse_query.py@@ -0,0 +1,88 @@+from uuid import uuid4++from posthog.test.base import APIBaseTest++from posthog.hogql.query import HogQLQueryExecutor++from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource++# Storage keys / URL pattern for direct-ClickHouse tables, duplicated as literals to respect the+# products.data_warehouse module boundary (the canonical constants live in+# products/data_warehouse/backend/direct_clickhouse.py).+DIRECT_CLICKHOUSE_URL_PATTERN = "direct://clickhouse"+DIRECT_CLICKHOUSE_DATABASE_OPTION = "direct_clickhouse_database"+DIRECT_CLICKHOUSE_TABLE_OPTION = "direct_clickhouse_table"+++class TestDirectClickHouseQuery(APIBaseTest):+ def _create_source(self, *, database: str) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status=ExternalDataSource.Status.COMPLETED,+ source_type="ClickHouse",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ prefix="ch",+ job_inputs={+ "host": "localhost",+ "port": 8443,+ "database": database,+ "user": "readonly_direct_connect",+ "password": "password",+ },+ )++ def _create_table(self, source: ExternalDataSource, *, options: dict | None = None) -> DataWarehouseTable:+ return DataWarehouseTable.objects.create(+ name="events",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ url_pattern=DIRECT_CLICKHOUSE_URL_PATTERN,+ # A team_id column is present so the query compiles — the ClickHouse printer's team_id+ # guard on direct tables is a separate concern and not what this test exercises.+ columns={+ "id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},+ "team_id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},+ },+ options=options or {},+ )++ def _from_database(self, source: ExternalDataSource) -> str:+ executor = HogQLQueryExecutor(query="SELECT * FROM events", team=self.team, connection_id=str(source.id))+ sql, _context = executor.generate_clickhouse_sql()+ # Normalize away identifier backticks so the assertion is agnostic to escaping.+ return sql.replace("`", "")++ def test_uses_the_sources_configured_database(self):+ source = self._create_source(database="posthog")+ self._create_table(source)++ sql = self._from_database(source)+ self.assertIn("posthog.events", sql)++ def test_configured_database_overrides_a_stale_default_option(self):+ # Regression: a table synced before the source's database was set stored "default" in its+ # per-table options. The live config ("posthog") must win, else the query targets+ # default.events and the server returns UNKNOWN_DATABASE.+ source = self._create_source(database="posthog")+ self._create_table(+ source,+ options={DIRECT_CLICKHOUSE_DATABASE_OPTION: "default", DIRECT_CLICKHOUSE_TABLE_OPTION: "events"},+ )++ sql = self._from_database(source)+ self.assertIn("posthog.events", sql)+ self.assertNotIn("default.events", sql)++ def test_falls_back_to_stored_option_when_no_database_configured(self):+ # When the source has no configured database, the per-table option is the only signal.+ source = self._create_source(database="")+ self._create_table(+ source,+ options={DIRECT_CLICKHOUSE_DATABASE_OPTION: "analytics", DIRECT_CLICKHOUSE_TABLE_OPTION: "events"},+ )++ sql = self._from_database(source)+ self.assertIn("analytics.events", sql)diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 20d092c489c0..7912bf95da87 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -760,11 +760,17 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletand 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")- )+ # Every direct-ClickHouse table is discovered from the source's single configured+ # database, so the live source config is authoritative. Prefer it over the per-table+ # option, which can be stale — e.g. stored as "default" when the source was first synced+ # before a database was set — and would otherwise resolve to a database that doesn't+ # exist on the server. Fall back to the stored option only when no database is configured.+ configured_database = job_inputs.get("database")+ if isinstance(configured_database, str) and configured_database.strip():+ clickhouse_database = configured_database+ else:+ stored_database = self.options.get(DIRECT_CLICKHOUSE_DATABASE_OPTION)+ clickhouse_database = stored_database if isinstance(stored_database, str) else "default"clickhouse_table_name = (self.options.get(DIRECT_CLICKHOUSE_TABLE_OPTION)if isinstance(self.options.get(DIRECT_CLICKHOUSE_TABLE_OPTION), str)