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(warehouse-sources): Add BigQuery direct-query support (#113994)

Juraj Majerikf75e26e5b77a
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index ca4d5ed795e9..5ef30fefe62d 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -200,6 +200,7 @@ export const FEATURE_FLAGS = {
AUDIT_LOGS_ACCESS: 'audit-logs-access', // owner: #team-platform-features, used to control access to audit logs
BATCH_EXPORT_ALERTS: 'batch-export-alerts', // owner: #team-batch-exports
BATCH_EXPORT_EARLIEST_BACKFILL: 'batch-export-earliest-backfill', // owner: #team-batch-exports, allow backfilling from beginning of time
+ BIGQUERY_DIRECT_QUERY: 'bigquery-direct-query', // owner: @jurajmajerik #team-experiments, offers BigQuery as a direct (live query) connection in the source wizard
CONTROL_SUPPORT_LOGIN: 'control_support_login', // owner: #team-security, used to control whether users can opt out of support impersonation
CUSTOM_CSS_THEMES: 'custom-css-themes', // owner: #team-growth, used to enable custom CSS for teams who want to have fun
EXPERIMENT_ACTIVATION_EVENT: 'experiment-activation-event', // owner: #team-experiments, offers an activation event on top of the default exposure instead of legacy custom exposure events
diff --git a/posthog/hogql/direct_query_metrics.py b/posthog/hogql/direct_query_metrics.py
index cae0da9e148d..eeadf1066f39 100644
--- a/posthog/hogql/direct_query_metrics.py
+++ b/posthog/hogql/direct_query_metrics.py
@@ -28,6 +28,7 @@ DirectQueryDialect = Literal[
"duckgres",
"motherduck",
"trino",
+ "bigquery",
]
DirectQueryStatus = Literal["success", "error"]
diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.py
index a354a4137c43..4fb4a6b6f6f2 100644
--- a/posthog/hogql/direct_sql/__init__.py
+++ b/posthog/hogql/direct_sql/__init__.py
@@ -4,6 +4,7 @@ from posthog.hogql.direct_sql.adapter import (
DirectQueryResult,
DirectSQLAdapter,
)
+from posthog.hogql.direct_sql.bigquery_adapter import BigQueryAdapter
from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable
from posthog.hogql.direct_sql.clickhouse_adapter import ClickHouseAdapter
from posthog.hogql.direct_sql.duckgres_adapter import DuckgresRawAdapter
@@ -26,6 +27,7 @@ register_adapter(RedshiftAdapter())
register_adapter(ClickHouseAdapter())
register_adapter(MotherDuckAdapter())
register_adapter(TrinoAdapter())
+register_adapter(BigQueryAdapter())
def get_raw_adapter_for_source(source: ExternalDataSource) -> DirectSQLAdapter | None:
@@ -45,6 +47,7 @@ __all__ = [
"DirectQueryPrincipal",
"DirectQueryResult",
"DirectSQLAdapter",
+ "BigQueryAdapter",
"ClickHouseAdapter",
"DuckgresRawAdapter",
"MotherDuckAdapter",
diff --git a/posthog/hogql/direct_sql/bigquery_adapter.py b/posthog/hogql/direct_sql/bigquery_adapter.py
new file mode 100644
index 000000000000..577344de5d69
--- /dev/null
+++ b/posthog/hogql/direct_sql/bigquery_adapter.py
@@ -0,0 +1,242 @@
+from __future__ import annotations
+
+import base64
+from concurrent import futures
+from typing import TYPE_CHECKING, Any, cast
+
+import sqlparse
+from opentelemetry import trace
+from sqlparse import tokens as sqlparse_tokens
+
+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, parse_direct_source_config
+from posthog.hogql.direct_sql.capability import bigquery_direct_query_enabled, is_direct_capable
+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement
+from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError
+
+if TYPE_CHECKING:
+ from google.cloud import bigquery
+
+ from posthog.models.team import Team
+
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.source import BigQuerySource
+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigquery import (
+ BigQuerySourceConfig,
+ )
+
+DIRECT_BIGQUERY_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600
+# Backstop against loading an unbounded result set into memory: a raw passthrough
+# `SELECT * FROM huge_table` carries no LIMIT.
+DIRECT_BIGQUERY_MAX_ROWS = 1_000_000
+RAW_BIGQUERY_READ_ONLY_ERROR = "Raw BigQuery queries must be read-only SELECT statements."
+DIRECT_BIGQUERY_ROW_CAP_ERROR = (
+ f"BigQuery query returned more than {DIRECT_BIGQUERY_MAX_ROWS:,} rows. Add a LIMIT clause."
+)
+DIRECT_BIGQUERY_TIMEOUT_ERROR = "BigQuery query timed out."
+
+# BigQuery reports legacy type names (INTEGER not INT64, BOOLEAN not BOOL). The standard-SQL
+# aliases are included so a client library change degrades to the same mapping.
+BIGQUERY_FIELD_TYPE_TO_CLICKHOUSE_TYPE: dict[str, str] = {
+ "INTEGER": "Int64",
+ "INT64": "Int64",
+ "FLOAT": "Float64",
+ "FLOAT64": "Float64",
+ "NUMERIC": "Decimal",
+ "BIGNUMERIC": "Decimal",
+ "STRING": "String",
+ "BOOLEAN": "Bool",
+ "BOOL": "Bool",
+ "DATE": "Date",
+ "DATETIME": "DateTime64(6, 'UTC')",
+ "TIMESTAMP": "DateTime64(6, 'UTC')",
+ "TIME": "String",
+ "BYTES": "String",
+ "RECORD": "String",
+ "STRUCT": "String",
+ "GEOGRAPHY": "String",
+ "JSON": "String",
+ "INTERVAL": "String",
+ "RANGE": "String",
+}
+
+
+def bigquery_field_to_clickhouse_type(field_type: str | None, mode: str | None = None) -> str:
+ # A REPEATED field is an array; arrays surface as String, like Snowflake's ARRAY.
+ if mode == "REPEATED":
+ return "String"
+ if not field_type:
+ return "String"
+ return BIGQUERY_FIELD_TYPE_TO_CLICKHOUSE_TYPE.get(field_type.upper(), "String")
+
+
+def bigquery_error_to_message(error: Exception) -> str:
+ # google.api_core call errors carry the server's message without the "403 GET https://…"
+ # prefix str() adds.
+ message = getattr(error, "message", None)
+ if not isinstance(message, str) or not message.strip():
+ message = str(error).strip()
+ if not message:
+ return "BigQuery query failed."
+ return message.splitlines()[0]
+
+
+def ensure_read_only_raw_bigquery_statement(sql: str) -> str:
+ 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_BIGQUERY_READ_ONLY_ERROR)
+ # BigQuery has no read-only session switch, and a single query job will run a
+ # multi-statement script, so this gate is the enforcement boundary on our side. The
+ # service account's read-only grants (Data Viewer + Job User) are the server-side
+ # backstop. The token scan below catches a write smuggled into a subquery. Unlike
+ # Snowflake there are no session-scoped functions to blocklist.
+ for token in statements[0].flatten():
+ if token.ttype in sqlparse_tokens.DDL:
+ raise ExposedHogQLError(RAW_BIGQUERY_READ_ONLY_ERROR)
+ if token.ttype in sqlparse_tokens.DML and token.value.upper() != "SELECT":
+ raise ExposedHogQLError(RAW_BIGQUERY_READ_ONLY_ERROR)
+ return sql
+
+
+def _resolve_query_location(config: BigQuerySourceConfig) -> str | None:
+ """The BigQuery location to pin query jobs to, or None to let the server infer it.
+
+ The server infers a job's location from the datasets the query references, so None
+ works for ordinary table reads.
+ """
+ custom_region = config.use_custom_region
+ if custom_region is not None and custom_region.enabled and custom_region.region:
+ return custom_region.region.strip() or None
+ return None
+
+
+def _json_safe_bigquery_value(value: Any) -> Any:
+ """BYTES columns arrive as `bytes`, which the response serializer rejects. Base64 is the
+ encoding BigQuery's own JSON output uses. Lists and dicts are REPEATED and RECORD fields,
+ which can carry bytes inside."""
+ if isinstance(value, bytes):
+ return base64.b64encode(value).decode("ascii")
+ if isinstance(value, list):
+ return [_json_safe_bigquery_value(item) for item in value]
+ if isinstance(value, dict):
+ return {key: _json_safe_bigquery_value(item) for key, item in value.items()}
+ return value
+
+
+def _fetch_capped_bigquery_rows(row_iterator: bigquery.table.RowIterator) -> list[list[Any]]:
+ """Collect up to the row cap, raising if the result exceeds it. The iterator is created
+ with max_results one past the cap, so the overflow is detectable."""
+ rows = [[_json_safe_bigquery_value(value) for value in row.values()] for row in row_iterator]
+ if len(rows) > DIRECT_BIGQUERY_MAX_ROWS:
+ DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="bigquery").inc()
+ raise ExposedHogQLError(DIRECT_BIGQUERY_ROW_CAP_ERROR)
+ return rows
+
+
+class BigQueryAdapter:
+ engine = "bigquery"
+ # Raw-only: no HogQL printer dialect exists for BigQuery, so only sendRawQuery works.
+ dialect: HogQLDialect | None = None
+
+ def validate_source_config(
+ self, source: ExternalDataSource, team: Team
+ ) -> tuple[BigQuerySource, BigQuerySourceConfig]:
+ 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 BigQuery connection.")
+
+ # The flag is also checked where connections are created; checking here too makes
+ # turning it off stop queries on already-created connections.
+ if not bigquery_direct_query_enabled(team):
+ raise ExposedHogQLError("BigQuery direct queries are not enabled for this project.")
+
+ bigquery_source = cast("BigQuerySource", SourceRegistry.get_source(ExternalDataSourceType.BIGQUERY))
+ config = parse_direct_source_config(bigquery_source, source)
+
+ # No host/SSRF check needed: every request goes to Google's fixed API hosts, and the
+ # key file's token_uri is checked against the Google OAuth allowlist when credentials
+ # are built.
+ return bigquery_source, config
+
+ def prepare_raw_sql(self, sql: str) -> str:
+ return ensure_read_only_raw_bigquery_statement(sql)
+
+ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:
+ """Execute a single read-only statement against the source's BigQuery project.
+
+ The job gets a server-side timeout (`job_timeout_ms`) in addition to the client-side
+ wait, so an abandoned request doesn't keep billing the customer.
+ """
+ from google.api_core import exceptions as google_api_exceptions
+ from google.auth import exceptions as google_auth_exceptions
+ from google.cloud import bigquery
+
+ from products.warehouse_sources.backend.facade.source_management import (
+ bigquery_client,
+ is_bigquery_auth_error,
+ resolve_bigquery_auth,
+ )
+
+ source = request.source
+ _, source_config = self.validate_source_config(source, request.team)
+ if request.values:
+ # Only the raw path reaches this adapter, and raw SQL never carries bound parameters.
+ raise InternalHogQLError("Direct BigQuery queries do not support bound parameters.")
+ statement_timeout_seconds = max(
+ request.settings.max_execution_time or DIRECT_BIGQUERY_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("bigquery_execute"), observe_direct_query("bigquery"):
+ auth = resolve_bigquery_auth(source_config, request.team.pk)
+ job_config = bigquery.QueryJobConfig(
+ use_legacy_sql=False,
+ job_timeout_ms=statement_timeout_seconds * 1000,
+ )
+ with bigquery_client(
+ auth.project_id, _resolve_query_location(source_config), auth.credentials
+ ) as client:
+ job = client.query(request.sql, job_config=job_config)
+ row_iterator = job.result(
+ timeout=statement_timeout_seconds, max_results=DIRECT_BIGQUERY_MAX_ROWS + 1
+ )
+ results = _fetch_capped_bigquery_rows(row_iterator)
+ schema_fields = list(row_iterator.schema or [])
+ except Exception as error:
+ # The auth error classes stay inside warehouse_sources; the facade exposes a
+ # predicate for them instead.
+ handled = isinstance(
+ error,
+ futures.TimeoutError
+ | google_api_exceptions.GoogleAPIError
+ | google_auth_exceptions.GoogleAuthError
+ | ExposedHogQLError,
+ ) or is_bigquery_auth_error(error)
+ if not handled:
+ raise
+ span.set_attribute("error_type", error.__class__.__name__)
+ message = (
+ DIRECT_BIGQUERY_TIMEOUT_ERROR
+ if isinstance(error, futures.TimeoutError)
+ else bigquery_error_to_message(error)
+ )
+ if request.debug:
+ return DirectQueryResult(results=[], types=[], print_columns=[], error=message)
+ raise ExposedHogQLError(message) from error
+
+ span.set_attribute("row_count", len(results))
+ types: list[tuple[str, str]] = [
+ (field.name, bigquery_field_to_clickhouse_type(field.field_type, field.mode)) for field in schema_fields
+ ]
+ print_columns = [field.name for field in schema_fields]
+ return DirectQueryResult(results=results, types=types, print_columns=print_columns)
diff --git a/posthog/hogql/direct_sql/capability.py b/posthog/hogql/direct_sql/capability.py
index 425093818dfd..d5bbafcd7f86 100644
--- a/posthog/hogql/direct_sql/capability.py
+++ b/posthog/hogql/direct_sql/capability.py
@@ -1,5 +1,34 @@
+from typing import TYPE_CHECKING
+
from products.warehouse_sources.backend.facade.models import ExternalDataSource
-from products.warehouse_sources.backend.facade.types import DIRECT_ENGINE_BY_SOURCE_TYPE, ExternalDataSourceAccessMethod
+from products.warehouse_sources.backend.facade.types import (
+ DIRECT_ENGINE_BY_SOURCE_TYPE,
+ ExternalDataSourceAccessMethod,
+ ExternalDataSourceType,
+)
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+
+# Gates BigQuery direct query while it is tested internally. It exists for warehouse-native
+# experiment metrics; teams outside the rollout must not be able to connect or query it.
+BIGQUERY_DIRECT_QUERY_FLAG = "bigquery-direct-query"
+
+
+def bigquery_direct_query_enabled(team: "Team") -> bool:
+ # Function-local: keeps the analytics client off the django.setup() path.
+ from posthog.ph_client import feature_enabled_or_false # noqa: PLC0415
+
+ return feature_enabled_or_false(
+ BIGQUERY_DIRECT_QUERY_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ send_feature_flag_events=False,
+ )
def direct_capable_source_types() -> frozenset[str]:
@@ -7,6 +36,16 @@ def direct_capable_source_types() -> frozenset[str]:
return frozenset(DIRECT_ENGINE_BY_SOURCE_TYPE.keys())
+def direct_capable_source_types_for_team(team: "Team") -> frozenset[str]:
+ """Source types this team can add as a direct connection: the static surface minus the
+ engines still behind a rollout flag. The presentation layer asks this instead of naming
+ a source type, so the flag check lives in one place."""
+ source_types = set(DIRECT_ENGINE_BY_SOURCE_TYPE.keys())
+ if not bigquery_direct_query_enabled(team):
+ source_types.discard(ExternalDataSourceType.BIGQUERY)
+ return frozenset(source_types)
+
+
def is_direct_capable(source: ExternalDataSource) -> bool:
"""Whether this source can be queried live via a direct connection.
diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.py
index e55a89d61249..37f766120a00 100644
--- a/posthog/hogql/direct_sql/test/test_registry_and_capability.py
+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py
@@ -23,13 +23,13 @@ class TestDirectSQLRegistry(SimpleTestCase):
self.assertIsInstance(get_adapter("clickhouse"), ClickHouseAdapter)
self.assertIsInstance(get_adapter("trino"), TrinoAdapter)
- @parameterized.expand([("none", None), ("unregistered", "bigquery")])
+ @parameterized.expand([("none", None), ("unregistered", "sqlite")])
def test_get_adapter_returns_none_for_unknown_engine(self, _name, engine):
self.assertIsNone(get_adapter(engine))
def test_registered_engines_includes_all_engines(self):
self.assertEqual(
- {"postgres", "mysql", "snowflake", "redshift", "clickhouse", "motherduck", "trino"},
+ {"postgres", "mysql", "snowflake", "redshift", "clickhouse", "motherduck", "trino", "bigquery"},
set(registered_engines()),
)
@@ -44,6 +44,12 @@ class TestDirectSQLRegistry(SimpleTestCase):
assert adapter is not None
self.assertEqual(adapter.dialect, "trino")
+ def test_bigquery_adapter_is_raw_only(self):
+ adapter = get_adapter("bigquery")
+ assert adapter is not None
+ # No BigQuery printer dialect exists; a non-None dialect would route HogQL to a wrong printer.
+ self.assertIsNone(adapter.dialect)
+
def test_register_adapter_round_trips(self):
class FakeAdapter:
engine = "fake"
@@ -71,6 +77,8 @@ class TestDirectSQLCapability(SimpleTestCase):
("motherduck_direct_ignores_toggle", ExternalDataSourceType.MOTHERDUCK, "direct", False, True),
("trino_direct_ignores_toggle", ExternalDataSourceType.TRINO, "direct", False, True),
("motherduck_synced_enabled", ExternalDataSourceType.MOTHERDUCK, "warehouse", True, True),
+ ("bigquery_direct_ignores_toggle", ExternalDataSourceType.BIGQUERY, "direct", False, True),
+ ("bigquery_synced_enabled", ExternalDataSourceType.BIGQUERY, "warehouse", True, True),
("unmapped_engine_synced", ExternalDataSourceType.STRIPE, "warehouse", True, False),
("unmapped_engine_direct", ExternalDataSourceType.STRIPE, "direct", True, False),
]
@@ -94,6 +102,7 @@ class TestDirectSQLCapability(SimpleTestCase):
ExternalDataSourceType.CLICKHOUSECLOUD,
ExternalDataSourceType.MOTHERDUCK,
ExternalDataSourceType.TRINO,
+ ExternalDataSourceType.BIGQUERY,
},
set(direct_capable_source_types()),
)
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index de0a2dd345e1..d4c61755f75a 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -446,6 +446,10 @@ class HogQLQueryExecutor:
source = self._direct_source
adapter = get_adapter(source.direct_engine) if source is not None else None
+ if adapter is not None and adapter.dialect is None:
+ # A raw-only engine (BigQuery) has no HogQL printer; falling back to another
+ # dialect would send SQL the engine cannot parse.
+ raise ExposedHogQLError("This connection supports raw SQL queries only (sendRawQuery).")
dialect: HogQLDialect = adapter.dialect if adapter is not None and adapter.dialect is not None else "postgres"
direct_context = dataclasses.replace(
diff --git a/posthog/hogql/test/test_direct_bigquery_query.py b/posthog/hogql/test/test_direct_bigquery_query.py
new file mode 100644
index 000000000000..f0748b0a5db1
--- /dev/null
+++ b/posthog/hogql/test/test_direct_bigquery_query.py
@@ -0,0 +1,283 @@
+import json
+from types import SimpleNamespace
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from google.api_core import exceptions as google_api_exceptions
+from google.cloud.bigquery.table import Row
+from parameterized import parameterized
+
+from posthog.hogql.direct_sql.bigquery_adapter import bigquery_error_to_message, bigquery_field_to_clickhouse_type
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.query import HogQLQueryExecutor
+
+from products.warehouse_sources.backend.facade.models import ExternalDataSource
+
+_FACADE = "products.warehouse_sources.backend.facade.source_management"
+
+
+class TestDirectBigQueryQuery(APIBaseTest):
+ def _create_source(self, prefix: str = "bq") -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=str(uuid4()),
+ connection_id=str(uuid4()),
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type="BigQuery",
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ prefix=prefix,
+ job_inputs={
+ "dataset_id": "analytics",
+ "auth_type": {
+ "selection": "key_file",
+ "key_file": {
+ "project_id": "acme-project",
+ "private_key": "-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----",
+ "private_key_id": "fakekeyid",
+ "client_email": "[email protected]",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ },
+ },
+ },
+ )
+
+ def _mock_bigquery_client(self, rows: list[tuple], schema_fields: list[SimpleNamespace]) -> MagicMock:
+ # Real SDK rows, so the values the adapter sees are the types the SDK decodes to.
+ field_to_index = {field.name: index for index, field in enumerate(schema_fields)}
+ row_iterator = MagicMock()
+ row_iterator.__iter__.return_value = iter([Row(row, field_to_index) for row in rows])
+ row_iterator.schema = schema_fields
+
+ job = MagicMock()
+ job.result.return_value = row_iterator
+
+ client = MagicMock()
+ client.query.return_value = job
+ return client
+
+ def _patched_execute(self, executor: HogQLQueryExecutor, client: MagicMock):
+ config = SimpleNamespace(use_custom_region=None)
+ auth = SimpleNamespace(project_id="acme-project", credentials=MagicMock())
+
+ client_cm = MagicMock()
+ client_cm.__enter__.return_value = client
+ client_cm.__exit__.return_value = False
+
+ with (
+ patch(
+ "posthog.hogql.direct_sql.bigquery_adapter.BigQueryAdapter.validate_source_config",
+ return_value=(MagicMock(), config),
+ ),
+ patch(f"{_FACADE}.resolve_bigquery_auth", return_value=auth),
+ patch(f"{_FACADE}.bigquery_client", return_value=client_cm),
+ ):
+ return executor.execute()
+
+ def test_execute_returns_rows_and_maps_types(self):
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query="SELECT id, amount FROM `acme-project.analytics.orders`",
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ client = self._mock_bigquery_client(
+ rows=[(1, "100.50")],
+ schema_fields=[
+ SimpleNamespace(name="id", field_type="INTEGER", mode="NULLABLE"),
+ SimpleNamespace(name="amount", field_type="NUMERIC", mode="NULLABLE"),
+ ],
+ )
+
+ response = self._patched_execute(executor, client)
+
+ # The job carries a server-side timeout so an abandoned request doesn't keep billing.
+ job_config = client.query.call_args.kwargs["job_config"]
+ self.assertIsNotNone(job_config.job_timeout_ms)
+ self.assertEqual(response.results, [[1, "100.50"]])
+ self.assertEqual(response.types, [("id", "Int64"), ("amount", "Decimal")])
+
+ def test_execute_encodes_bytes_values_so_the_response_serializes(self):
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query="SELECT payload, chunks, meta FROM `acme-project.analytics.blobs`",
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ client = self._mock_bigquery_client(
+ rows=[(b"\xff", [b"\x00", b"\x01"], {"digest": b"\x02", "label": "x"})],
+ schema_fields=[
+ SimpleNamespace(name="payload", field_type="BYTES", mode="NULLABLE"),
+ SimpleNamespace(name="chunks", field_type="BYTES", mode="REPEATED"),
+ SimpleNamespace(name="meta", field_type="RECORD", mode="NULLABLE"),
+ ],
+ )
+
+ response = self._patched_execute(executor, client)
+
+ self.assertEqual(response.results, [["/w==", ["AA==", "AQ=="], {"digest": "Ag==", "label": "x"}]])
+ json.dumps(response.model_dump(mode="json"))
+
+ def test_execute_rejects_result_over_row_cap(self):
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query="SELECT id FROM `acme-project.analytics.orders`",
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ client = self._mock_bigquery_client(
+ rows=[(i,) for i in range(4)],
+ schema_fields=[SimpleNamespace(name="id", field_type="INTEGER", mode="NULLABLE")],
+ )
+
+ with patch("posthog.hogql.direct_sql.bigquery_adapter.DIRECT_BIGQUERY_MAX_ROWS", 3):
+ with self.assertRaisesRegex(ExposedHogQLError, "Add a LIMIT clause"):
+ self._patched_execute(executor, client)
+
+ def test_raw_query_rejected_when_flag_off(self):
+ # The flag is the kill switch: turning it off must stop queries on already-created
+ # connections, not just block new ones. It is off by default in tests.
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query="SELECT id FROM `acme-project.analytics.orders`",
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ with self.assertRaisesRegex(ExposedHogQLError, "not enabled"):
+ executor.execute()
+
+ def test_hogql_query_against_raw_only_connection_is_rejected(self):
+ # Without this guard a HogQL query on a BigQuery connection would be printed in the
+ # postgres dialect and shipped to BigQuery.
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query="SELECT 1",
+ team=self.team,
+ connection_id=str(source.id),
+ )
+
+ with self.assertRaisesRegex(ExposedHogQLError, "raw SQL"):
+ executor.execute()
+
+ @parameterized.expand(
+ [
+ # Leading-keyword writes (rejected by the SELECT classification).
+ ("delete", "DELETE FROM `acme.analytics.orders` WHERE id = 1"),
+ ("insert", "INSERT INTO `acme.analytics.orders` VALUES (1)"),
+ ("update", "UPDATE `acme.analytics.orders` SET name = 'x' WHERE true"),
+ ("drop", "DROP TABLE `acme.analytics.orders`"),
+ ("create", "CREATE TABLE `acme.analytics.t` (c INT64)"),
+ ("alter", "ALTER TABLE `acme.analytics.orders` ADD COLUMN c INT64"),
+ ("truncate", "TRUNCATE TABLE `acme.analytics.orders`"),
+ ("multiple_statements", "SELECT 1; DROP TABLE `acme.analytics.orders`"),
+ ("merge", "MERGE INTO `acme.analytics.orders` USING s ON orders.id = s.id WHEN MATCHED THEN DELETE"),
+ # BigQuery side-effecting statements that classify as UNKNOWN, not SELECT.
+ ("call_procedure", "CALL `acme.analytics.my_writing_proc`()"),
+ ("execute_immediate", "EXECUTE IMMEDIATE 'DELETE FROM `acme.analytics.orders` WHERE true'"),
+ ("grant", "GRANT `roles/bigquery.dataViewer` ON TABLE `acme.analytics.orders` TO 'user:[email protected]'"),
+ ("begin_script", "BEGIN DELETE FROM `acme.analytics.orders` WHERE true; END"),
+ # Writes smuggled into an otherwise SELECT-classified statement.
+ ("write_in_cte", "WITH x AS (DELETE FROM `acme.analytics.orders` WHERE true) SELECT 1"),
+ ]
+ )
+ def test_raw_query_rejects_non_select(self, _name: str, query: str):
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query=query,
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ with patch("posthog.hogql.direct_sql.bigquery_adapter.BigQueryAdapter.validate_source_config") as mock_validate:
+ with self.assertRaises(ExposedHogQLError):
+ executor.execute()
+
+ # The statement is rejected before any credentials are resolved.
+ mock_validate.assert_not_called()
+ self.assertIsNone(executor.direct_sql)
+
+ @parameterized.expand(
+ [
+ ("plain_select", "SELECT id FROM `acme-project.analytics.orders`"),
+ ("cte_select", "WITH x AS (SELECT 1 AS v) SELECT v FROM x"),
+ # A write keyword inside a string literal must not trip the token scan.
+ ("write_word_in_string", "SELECT id FROM `acme-project.analytics.orders` WHERE status = 'DELETE'"),
+ # Backtick-quoted project.dataset.table identifiers are BigQuery's native form.
+ ("backtick_identifiers", "SELECT `select`.id FROM `acme-project.analytics.orders` AS `select`"),
+ ]
+ )
+ def test_raw_query_allows_read_only_selects(self, _name: str, query: str):
+ source = self._create_source()
+
+ executor = HogQLQueryExecutor(
+ query=query,
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ )
+
+ client = self._mock_bigquery_client(
+ rows=[(1,)],
+ schema_fields=[SimpleNamespace(name="id", field_type="INTEGER", mode="NULLABLE")],
+ )
+
+ self._patched_execute(executor, client)
+
+ # The statement passed the read-only gate and reached execution unchanged.
+ self.assertEqual(executor.direct_sql, query)
+
+ @parameterized.expand(
+ [
+ ("integer_legacy", "INTEGER", "NULLABLE", "Int64"),
+ ("int64_standard", "INT64", "NULLABLE", "Int64"),
+ ("float_legacy", "FLOAT", "NULLABLE", "Float64"),
+ ("numeric", "NUMERIC", "NULLABLE", "Decimal"),
+ ("bignumeric", "BIGNUMERIC", "NULLABLE", "Decimal"),
+ ("string", "STRING", "NULLABLE", "String"),
+ ("boolean_legacy", "BOOLEAN", "NULLABLE", "Bool"),
+ ("date", "DATE", "NULLABLE", "Date"),
+ ("datetime", "DATETIME", "NULLABLE", "DateTime64(6, 'UTC')"),
+ ("timestamp", "TIMESTAMP", "NULLABLE", "DateTime64(6, 'UTC')"),
+ ("time", "TIME", "NULLABLE", "String"),
+ ("bytes", "BYTES", "NULLABLE", "String"),
+ ("record_struct", "RECORD", "NULLABLE", "String"),
+ ("json", "JSON", "NULLABLE", "String"),
+ ("geography", "GEOGRAPHY", "NULLABLE", "String"),
+ ("repeated_is_array", "INTEGER", "REPEATED", "String"),
+ ("unknown", "FUTURETYPE", "NULLABLE", "String"),
+ ("none_type", None, "NULLABLE", "String"),
+ ]
+ )
+ def test_bigquery_field_to_clickhouse_type(self, _name: str, field_type: str | None, mode: str, expected: str):
+ self.assertEqual(bigquery_field_to_clickhouse_type(field_type, mode), expected)
+
+ @parameterized.expand(
+ [
+ # google.api_core errors carry the clean server message; str() prefixes the code + URL.
+ (
+ "api_call_error_uses_message",
+ google_api_exceptions.BadRequest("Syntax error: Unexpected keyword DELETE at [1:1]"),
+ "Syntax error: Unexpected keyword DELETE at [1:1]",
+ ),
+ ("plain_exception_first_line", Exception("boom\nsecond line"), "boom"),
+ ("empty_message", Exception(""), "BigQuery query failed."),
+ ]
+ )
+ def test_bigquery_error_to_message(self, _name: str, error: Exception, expected: str):
+ self.assertEqual(bigquery_error_to_message(error), expected)
diff --git a/products/data_warehouse/backend/test/test_direct_query_engines.py b/products/data_warehouse/backend/test/test_direct_query_engines.py
index 4658613f6b6f..75b3ff418161 100644
--- a/products/data_warehouse/backend/test/test_direct_query_engines.py
+++ b/products/data_warehouse/backend/test/test_direct_query_engines.py
@@ -16,7 +16,8 @@ class TestDirectQueryEngineRegistry:
assert adapter is not None
assert adapter.engine == engine
- @parameterized.expand([("none", None), ("unknown", "bigquery")])
+ # BigQuery is direct-capable but registers no materialization engine; the setup flow skips table registration.
+ @parameterized.expand([("none", None), ("raw_only_bigquery", "bigquery"), ("unknown", "sqlite")])
def test_non_direct_engine_returns_none(self, _name: str, engine):
assert get_direct_query_engine(engine) is None
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index e22e4715ed2f..33819eb92d88 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -264,6 +264,19 @@ export function resolveCreateDirectQueryEnabled(
return sourceValues.direct_query_enabled !== false
}
+export function buildCreateSourcePayload(
+ sourceValues: { access_method?: string; direct_query_enabled?: boolean },
+ connectorName: string
+): Record<string, any> {
+ const isDirectQueryMode = supportsDirectQuery(connectorName) && sourceValues.access_method === 'direct'
+ return {
+ ...sourceValues,
+ access_method: isDirectQueryMode ? 'direct' : 'warehouse',
+ direct_query_enabled: resolveCreateDirectQueryEnabled(sourceValues, connectorName),
+ source_type: connectorName,
+ }
+}
+
function webhookResultHasNoPendingInputs(webhookResult: WebhookCreateResult | null | undefined): boolean {
return !!webhookResult?.success && (webhookResult.pending_inputs?.length ?? 0) === 0
}
@@ -2720,17 +2733,8 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
},
submit: async (sourceValues) => {
if (values.selectedConnector) {
- const isDirectQueryMode =
- supportsDirectQuery(values.selectedConnector.name) && sourceValues.access_method === 'direct'
- const payload: Record<string, any> = {
- ...sourceValues,
- access_method: isDirectQueryMode ? 'direct' : 'warehouse',
- direct_query_enabled: resolveCreateDirectQueryEnabled(
- sourceValues,
- values.selectedConnector.name
- ),
- source_type: values.selectedConnector.name,
- }
+ const payload = buildCreateSourcePayload(sourceValues, values.selectedConnector.name)
+ const isDirectQueryMode = payload.access_method === 'direct'
actions.setIsLoading(true)
try {
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
index cc77a3abe8f3..e833a78d5e45 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -15,6 +15,7 @@ import type { AvailableColumn, ExternalDataSource, ExternalDataSourceSyncSchema,
import type { SourceConfigResponseApi } from 'products/warehouse_sources/frontend/generated/api.schemas'
import {
+ buildCreateSourcePayload,
buildKeaFormDefaultFromSourceDetails,
getDatabaseSchemaPayload,
getErrorsForFields,
@@ -325,6 +326,27 @@ describe('sourceWizardLogic', () => {
})
})
+ describe('buildCreateSourcePayload', () => {
+ beforeEach(() => {
+ featureFlagLogic.mount()
+ })
+
+ it.each([
+ { connector: 'Postgres', flagOn: false, expectedAccessMethod: 'direct' },
+ { connector: 'BigQuery', flagOn: false, expectedAccessMethod: 'warehouse' },
+ { connector: 'BigQuery', flagOn: true, expectedAccessMethod: 'direct' },
+ ])(
+ 'keeps direct mode for $connector only when supported (flag on: $flagOn)',
+ ({ connector, flagOn, expectedAccessMethod }) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.BIGQUERY_DIRECT_QUERY]: flagOn })
+
+ const payload = buildCreateSourcePayload({ access_method: 'direct', prefix: 'bq' } as any, connector)
+
+ expect(payload).toMatchObject({ access_method: expectedAccessMethod, source_type: connector })
+ }
+ )
+ })
+
describe('getDatabaseSchemaPayload', () => {
it('includes the selected access method for schema discovery', () => {
expect(
diff --git a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
index da4074af96c8..a30ad0110815 100644
--- a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts
@@ -1,3 +1,5 @@
+import { FEATURE_FLAGS, type FeatureFlagKey } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { groupBy } from 'lib/utils/arrays'
/** Source types that support `access_method: 'direct'` (live querying without syncing to the warehouse). */
@@ -11,8 +13,21 @@ export const DIRECT_QUERY_SOURCE_TYPES = [
'Trino',
] as const
+const FLAG_GATED_DIRECT_QUERY_SOURCE_TYPES: Record<string, FeatureFlagKey> = {
+ BigQuery: FEATURE_FLAGS.BIGQUERY_DIRECT_QUERY,
+}
+
export function supportsDirectQuery(sourceType: string | null | undefined): boolean {
- return !!sourceType && DIRECT_QUERY_SOURCE_TYPES.includes(sourceType as (typeof DIRECT_QUERY_SOURCE_TYPES)[number])
+ if (!sourceType) {
+ return false
+ }
+ const gatingFlag = FLAG_GATED_DIRECT_QUERY_SOURCE_TYPES[sourceType]
+ if (gatingFlag) {
+ // Read the mounted logic directly: this helper is called from logics and plain
+ // functions, not only from rendering components.
+ return !!featureFlagLogic.findMounted()?.values.featureFlags[gatingFlag]
+ }
+ return DIRECT_QUERY_SOURCE_TYPES.includes(sourceType as (typeof DIRECT_QUERY_SOURCE_TYPES)[number])
}
export function splitQualifiedTableName(
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index 9d7255a86692..3c8f874b4ef0 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -32,6 +32,9 @@ _LAZY = {
"CDC_RESET_PENDING_KEY": "cdc.snapshot_lane",
"hand_reset_to_capture_if_sync_running": "cdc.snapshot_lane",
"resnapshot_stays_in_buffer": "cdc.snapshot_lane",
+ "bigquery_client": "sources.bigquery.bigquery",
+ "is_bigquery_auth_error": "sources.bigquery.bigquery",
+ "resolve_bigquery_auth": "sources.bigquery.bigquery",
"ClickHouseConnectionError": "sources.clickhouse.clickhouse",
"ClickHouseSource": "sources.clickhouse.source",
"AnySource": "sources.common.base",
diff --git a/products/warehouse_sources/backend/facade/types.py b/products/warehouse_sources/backend/facade/types.py
index a01cfeb37b8d..b406f53b16bf 100644
--- a/products/warehouse_sources/backend/facade/types.py
+++ b/products/warehouse_sources/backend/facade/types.py
@@ -1466,6 +1466,7 @@ DIRECT_ENGINE_BY_SOURCE_TYPE: dict[str, str] = {
ExternalDataSourceType.CLICKHOUSECLOUD: "clickhouse",
ExternalDataSourceType.MOTHERDUCK: "motherduck",
ExternalDataSourceType.TRINO: "trino",
+ ExternalDataSourceType.BIGQUERY: "bigquery",
}
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
index ae9c352d46d1..ac0baf6231f3 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
@@ -12,7 +12,7 @@ from rest_framework import serializers, status
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.hogql.direct_sql.capability import direct_capable_source_types
+from posthog.hogql.direct_sql.capability import direct_capable_source_types, direct_capable_source_types_for_team
from posthog.api.utils import action
from posthog.models.user import User
@@ -240,7 +240,7 @@ class ExternalDataSourceConnectionOptionsMixin(base.ExternalDataSourceViewSetBas
"""Source types the user can add as a direct connection, driven by the direct-SQL capability
surface so the picker never drifts from the engines we actually support."""
with tracer.start_as_current_span("warehouse_sources.direct_connection_options.catalog"):
- direct_types = direct_capable_source_types()
+ direct_types = direct_capable_source_types_for_team(self.team)
configs = build_source_configs(include_tables=False)
options = [
{
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
index 31fe79f4857a..f10d0235adf6 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
@@ -19,7 +19,7 @@ from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
-from posthog.hogql.direct_sql.capability import direct_capable_source_types
+from posthog.hogql.direct_sql.capability import direct_capable_source_types, direct_capable_source_types_for_team
from posthog.api.utils import action
from posthog.event_usage import EventSource, get_event_source, is_wizard_self_driving_program, report_user_action
@@ -1157,7 +1157,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
data={"message": helpers.RESERVED_SOURCE_NAME_MESSAGE},
)
- if is_direct_query and source_type not in direct_capable_source_types():
+ if is_direct_query and source_type not in direct_capable_source_types_for_team(self.team):
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": helpers.DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
index aa28082cc021..0e834056657d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigquery/bigquery.py
@@ -269,6 +269,11 @@ class BigQueryAuthResolutionError(Exception):
"""Carries a user-safe explanation of why a source's credentials could not be resolved."""
+def is_bigquery_auth_error(error: BaseException) -> bool:
+ """Whether `resolve_bigquery_auth` raised `error` with a message safe to show the user."""
+ return isinstance(error, BigQueryAuthResolutionError | BigQueryInvalidTokenUriError)
+
+
# BigQuery occasionally fails a query job with a transient `jobInternalError`, surfaced from the
# `jobs.getQueryResults` REST call as a 400 BadRequest whose message ends "The job encountered an
# error during execution. Retrying the job may solve the problem.". The client's default job-retry
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.py
index c32575a6fe85..9ea6e20eb2c9 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
@@ -2990,6 +2990,17 @@ class TestExternalDataSource(APIBaseTest):
# Guards the drift the picker hit: a direct-capable engine must surface as an addable option.
self.assertTrue({"Postgres", "MySQL", "Snowflake", "Redshift", "ClickHouse", "Trino"}.issubset(source_types))
self.assertNotIn("Stripe", source_types)
+ # BigQuery is gated on the bigquery-direct-query flag, off by default.
+ self.assertNotIn("BigQuery", source_types)
+
+ with patch(
+ "posthog.hogql.direct_sql.capability.bigquery_direct_query_enabled",
+ return_value=True,
+ ):
+ flag_on = self.client.get(
+ f"/api/environments/{self.team.pk}/external_data_sources/direct_connection_options/"
+ )
+ self.assertIn("BigQuery", {option["source_type"] for option in flag_on.json()})
clickhouse = next(option for option in payload if option["source_type"] == "ClickHouse")
self.assertEqual(clickhouse["label"], "ClickHouse")
@@ -4312,6 +4323,52 @@ class TestExternalDataSource(APIBaseTest):
self.assertEqual(connection_metadata["database"], "app")
self.assertEqual(connection_metadata["available_functions"], ["duckdb_functions", "date_bin"])
+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")
+ def test_create_direct_bigquery_source_without_table_registration(self, mock_get_source):
+ # BigQuery has no materialization engine, so a pure-direct connection is created with
+ # schema rows but no DataWarehouseTable. Creation is gated on the bigquery-direct-query flag.
+ _configure_source_mock_versioning(mock_get_source)
+ source_mock = mock_get_source.return_value
+ source_mock.validate_config.return_value = (True, [])
+ parsed_config = Mock()
+ parsed_config.to_dict.return_value = {"dataset_id": "analytics"}
+ source_mock.parse_config.return_value = parsed_config
+ source_mock.validate_credentials.return_value = (True, None)
+ source_mock.get_schemas.return_value = [
+ SourceSchema(
+ name="orders",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "INTEGER", False)],
+ foreign_keys=[],
+ ),
+ ]
+
+ request_data = {
+ "source_type": "BigQuery",
+ "created_via": "web",
+ "access_method": "direct",
+ "prefix": "Analytics warehouse",
+ "payload": {"dataset_id": "analytics"},
+ }
+
+ # Flag off (the default): a direct BigQuery connection cannot be created.
+ response = self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/", data=request_data)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json(), {"message": DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE})
+
+ with patch(
+ "posthog.hogql.direct_sql.capability.bigquery_direct_query_enabled",
+ return_value=True,
+ ):
+ response = self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/", data=request_data)
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ source = ExternalDataSource.objects.get(pk=response.json()["id"])
+ self.assertEqual(source.access_method, ExternalDataSource.AccessMethod.DIRECT)
+ schema = ExternalDataSchema.objects.get(team_id=self.team.pk, source=source, name="orders")
+ self.assertIsNone(schema.table)
+
def test_create_direct_postgres_requires_name(self):
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/",
diff --git a/products/warehouse_sources/turbo.json b/products/warehouse_sources/turbo.json
index 8f1a3a48de8a..875d96621911 100644
--- a/products/warehouse_sources/turbo.json
+++ b/products/warehouse_sources/turbo.json
@@ -12,6 +12,7 @@
"backend/temporal/data_imports/naming_convention.py",
"backend/temporal/data_imports/pipelines/core/consts.py",
"backend/temporal/data_imports/sources/generated_configs/__init__.py",
+ "backend/temporal/data_imports/sources/generated_configs/bigquery.py",
"backend/temporal/data_imports/sources/generated_configs/clickhouse.py",
"backend/temporal/data_imports/sources/generated_configs/custom.py",
"backend/temporal/data_imports/sources/generated_configs/github.py",
@@ -25,6 +26,7 @@
"backend/temporal/data_imports/sources/generated_configs/snowflake.py",
"backend/temporal/data_imports/sources/generated_configs/stripe.py",
"backend/temporal/data_imports/sources/generated_configs/trino.py",
+ "backend/temporal/data_imports/sources/bigquery/**",
"backend/temporal/data_imports/sources/clickhouse/**",
"backend/temporal/data_imports/sources/common/**",
"backend/temporal/data_imports/sources/google_search_console/**",
@@ -37,6 +39,7 @@
"backend/temporal/data_imports/sources/snowflake/**",
"backend/temporal/data_imports/sources/stripe/**",
"backend/temporal/data_imports/sources/trino/**",
+ "!backend/temporal/data_imports/sources/bigquery/tests/**",
"!backend/temporal/data_imports/sources/common/rest_source/**",
"!backend/temporal/data_imports/sources/common/test/**",
"!backend/temporal/data_imports/sources/common/sql/tests/**",