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.

refactor(data-warehouse): migrate bigquery to SQLSourceImplementation (#59698)

Daniel RC018b36b51335
diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
index 76168ece9e5a..cae749a0088c 100644
--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py
+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py
@@ -1,9 +1,24 @@
+"""BigQuery driver for PostHog's data-warehouse import pipeline.
+
+Everything BigQuery-specific — client lifecycle (service account auth,
+optional custom region), schema / primary-key / clustering listing, the
+dlt pipeline build (temp-table dance for incremental syncs and views) —
+lives on `BigQueryImplementation`. The source-class `BigQuerySource` is
+a thin PostHog-layer wrapper that just holds an instance and validates
+credentials.
+"""
+
+from __future__ import annotations
+
import math
import typing
import contextlib
import collections
import collections.abc
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import date, datetime
+from typing import Any
import pyarrow as pa
import structlog
@@ -21,62 +36,51 @@ from posthog.temporal.data_imports.pipelines.helpers import (
incremental_type_to_operator,
)
from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_TABLE_SIZE_BYTES
-from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.pipelines.pipeline.utils import DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES
from posthog.temporal.data_imports.sources.common.http import DEFAULT_RETRY, TrackedHTTPAdapter
+from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation
+from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter
from posthog.temporal.data_imports.sources.generated_configs import BigQuerySourceConfig
from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
+__all__ = [
+ "BigQueryImplementation",
+ "bigquery_client",
+ "bigquery_storage_read_client",
+ "build_destination_table_prefix",
+ "delete_all_temp_destination_tables",
+ "delete_table",
+ "filter_bigquery_incremental_fields",
+ "validate_bigquery_credentials",
+]
+
+
+def build_destination_table_prefix(schema_id: str | None) -> str:
+ return f"__posthog_import_{schema_id.replace('-', '_') if schema_id else ''}"
-def get_schemas(
- config: BigQuerySourceConfig,
- logger: FilteringBoundLogger | None = None,
- names: list[str] | None = None,
-) -> dict[str, list[tuple[str, str, bool]]]:
- schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
- region: str | None = None
+def _resolve_region(config: BigQuerySourceConfig) -> str | None:
if (
config.use_custom_region
and config.use_custom_region.enabled
and config.use_custom_region.region is not None
and config.use_custom_region.region != ""
):
- region = config.use_custom_region.region
-
- with bigquery_client(
- config.key_file.project_id,
- region,
- config.key_file.private_key,
- config.key_file.private_key_id,
- config.key_file.client_email,
- config.key_file.token_uri,
- ) as bq:
- query = bq.query(
- f"SELECT table_name, column_name, data_type, is_nullable FROM `{config.dataset_id}.INFORMATION_SCHEMA.COLUMNS` ORDER BY table_name ASC",
- project=config.dataset_project.dataset_project_id
- if config.dataset_project and config.dataset_project.enabled
- else config.key_file.project_id,
- )
- try:
- rows = query.result()
- except Forbidden:
- if logger:
- logger.warning(
- "Could not obtain new schemas from BigQuery due to missing permissions on '%s.INFORMATION_SCHEMA.COLUMNS'",
- config.dataset_id,
- )
- return {}
-
- for row in rows:
- schema_list[row.table_name].append((row.column_name, row.data_type, row.is_nullable == "YES"))
+ return config.use_custom_region.region
+ return None
- if names is not None:
- names_set = set(names)
- schema_list = {k: v for k, v in schema_list.items() if k in names_set}
- return schema_list
+def _resolve_dataset_project_id(config: BigQuerySourceConfig) -> str | None:
+ if (
+ config.dataset_project
+ and config.dataset_project.enabled
+ and config.dataset_project.dataset_project_id is not None
+ and config.dataset_project.dataset_project_id != ""
+ ):
+ return config.dataset_project.dataset_project_id
+ return None
@contextlib.contextmanager
@@ -119,6 +123,29 @@ def bigquery_client(
client.close()
+def bigquery_storage_read_client(
+ project_id: str, private_key: str, private_key_id: str, client_email: str, token_uri: str
+):
+ """Manage a BigQuery Storage client."""
+ credentials = service_account.Credentials.from_service_account_info(
+ {
+ "private_key": private_key,
+ "private_key_id": private_key_id,
+ "token_uri": token_uri,
+ "client_email": client_email,
+ "project_id": project_id,
+ },
+ scopes=["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/cloud-platform"],
+ )
+
+ client = bigquery_storage.BigQueryReadClient(
+ credentials=credentials,
+ )
+
+ yield client
+
+
def delete_table(
table_id: str,
project_id: str,
@@ -156,7 +183,9 @@ def delete_all_temp_destination_tables(
capture_exception(e)
-def filter_incremental_fields(columns: list[tuple[str, str, bool]]) -> list[tuple[str, IncrementalFieldType, bool]]:
+def filter_bigquery_incremental_fields(
+ columns: list[tuple[str, str, bool]],
+) -> list[tuple[str, IncrementalFieldType, bool]]:
results: list[tuple[str, IncrementalFieldType, bool]] = []
for column_name, type, nullable in columns:
type = type.upper()
@@ -182,7 +211,7 @@ def filter_incremental_fields(columns: list[tuple[str, str, bool]]) -> list[tupl
return results
-def validate_credentials(
+def validate_bigquery_credentials(
dataset_id: str, key_file: dict[str, str], dataset_project_id: str | None, location: str | None
) -> bool:
project_id = key_file.get("project_id")
@@ -206,30 +235,7 @@ def validate_credentials(
return False
-def bigquery_storage_read_client(
- project_id: str, private_key: str, private_key_id: str, client_email: str, token_uri: str
-):
- """Manage a BigQuery Storage client."""
- credentials = service_account.Credentials.from_service_account_info(
- {
- "private_key": private_key,
- "private_key_id": private_key_id,
- "token_uri": token_uri,
- "client_email": client_email,
- "project_id": project_id,
- },
- scopes=["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/cloud-platform"],
- )
-
- client = bigquery_storage.BigQueryReadClient(
- credentials=credentials,
- )
-
- yield client
-
-
-def get_partition_settings(
+def _get_partition_settings(
table: bigquery.Table,
client: bigquery.Client,
partition_size_bytes: int = DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,
@@ -256,137 +262,7 @@ def get_partition_settings(
return PartitionSettings(partition_count=partition_count, partition_size=partition_size)
-def get_leading_indexed_columns_for_schemas(
- config: BigQuerySourceConfig,
- table_names: list[str],
-) -> dict[str, set[str]] | None:
- """Return columns that act as the leading "index" per BigQuery table.
-
- BigQuery doesn't have B-tree indexes; predicate pushdown for `WHERE col >= …`
- is accelerated by:
- - The partition column (INFORMATION_SCHEMA.COLUMNS.is_partitioning_column = 'YES')
- - The leading clustering column (clustering_ordinal_position = 1)
- Both are equally effective for skipping data, so we treat both as indexed.
-
- Returns None on discovery failure so callers default to no warning. Tables
- without partitioning or clustering map to an empty set so the UI warns for
- them.
- """
- if not table_names:
- return {}
-
- try:
- region: str | None = None
- if (
- config.use_custom_region
- and config.use_custom_region.enabled
- and config.use_custom_region.region is not None
- and config.use_custom_region.region != ""
- ):
- region = config.use_custom_region.region
-
- result: dict[str, set[str]] = {table: set() for table in table_names}
-
- with bigquery_client(
- config.key_file.project_id,
- region,
- config.key_file.private_key,
- config.key_file.private_key_id,
- config.key_file.client_email,
- config.key_file.token_uri,
- ) as bq:
- project = (
- config.dataset_project.dataset_project_id
- if config.dataset_project and config.dataset_project.enabled
- else config.key_file.project_id
- )
-
- query = f"""
- SELECT table_name, column_name
- FROM `{config.dataset_id}`.INFORMATION_SCHEMA.COLUMNS
- WHERE is_partitioning_column = 'YES'
- OR clustering_ordinal_position = 1
- """
-
- job = bq.query(query, job_config=QueryJobConfig(), project=project)
- for row in job.result():
- table_name = row["table_name"]
- if table_name in result:
- result[table_name].add(row["column_name"])
- except Exception as e:
- structlog.get_logger().warning("Failed to detect partitioning/clustering for BigQuery schemas", exc_info=e)
- return None
-
- return result
-
-
-def get_primary_keys_for_schemas(
- config: BigQuerySourceConfig,
- schemas: dict[str, list[tuple[str, str, bool]]],
-) -> dict[str, list[str] | None]:
- """Detect primary keys for all tables in a dataset.
-
- Returns a dict mapping table_name -> list of PK columns (or None).
- Uses the same logic as get_primary_keys but batched into a single query.
- """
- region: str | None = None
- if (
- config.use_custom_region
- and config.use_custom_region.enabled
- and config.use_custom_region.region is not None
- and config.use_custom_region.region != ""
- ):
- region = config.use_custom_region.region
-
- result: dict[str, list[str] | None] = {}
-
- with bigquery_client(
- config.key_file.project_id,
- region,
- config.key_file.private_key,
- config.key_file.private_key_id,
- config.key_file.client_email,
- config.key_file.token_uri,
- ) as bq:
- project = (
- config.dataset_project.dataset_project_id
- if config.dataset_project and config.dataset_project.enabled
- else config.key_file.project_id
- )
-
- query = f"""
- SELECT tc.table_name, kcu.column_name
- FROM `{config.dataset_id}`.INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
- JOIN `{config.dataset_id}`.INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
- ON tc.constraint_name = kcu.constraint_name
- WHERE tc.constraint_type = 'PRIMARY KEY'
- """
-
- constraint_pks: dict[str, list[str]] = collections.defaultdict(list)
- try:
- job = bq.query(query, job_config=QueryJobConfig(), project=project)
- for row in job.result():
- table_name = row["table_name"]
- col_name = row["column_name"].removeprefix(f"{table_name}.")
- constraint_pks[table_name].append(col_name)
- except Exception as e:
- structlog.get_logger().warning("Failed to detect primary keys for BigQuery schemas", exc_info=e)
-
- for table_name, columns in schemas.items():
- existing_fields = {col[0] for col in columns}
-
- if table_name in constraint_pks:
- pks = [pk for pk in constraint_pks[table_name] if pk in existing_fields]
- result[table_name] = pks if pks else None
- elif "id" in existing_fields:
- result[table_name] = ["id"]
- else:
- result[table_name] = None
-
- return result
-
-
-def get_primary_keys(table: bigquery.Table, client: bigquery.Client) -> list[str] | None:
+def _get_primary_keys_for_table(table: bigquery.Table, client: bigquery.Client) -> list[str] | None:
"""Attempt to fetch primary keys for a BigQuery table.
We will also attempt to look at table constraints to find primary keys.
@@ -422,7 +298,7 @@ def get_primary_keys(table: bigquery.Table, client: bigquery.Client) -> list[str
return primary_keys
-def has_duplicate_primary_keys(table: bigquery.Table, client: bigquery.Client, primary_keys: list[str] | None) -> bool:
+def _has_duplicate_primary_keys(table: bigquery.Table, client: bigquery.Client, primary_keys: list[str] | None) -> bool:
if not primary_keys or len(primary_keys) == 0:
return False
@@ -483,7 +359,7 @@ def _get_rows_to_sync(
logger.debug(f"_get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")
return rows_to_sync_int
- logger.debug(f"_get_rows_to_sync: No results returned. Using 0 as rows to sync")
+ logger.debug("_get_rows_to_sync: No results returned. Using 0 as rows to sync")
return 0
except Exception as e:
@@ -522,58 +398,280 @@ def _get_query(
return f"SELECT * FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`"
-def bigquery_source(
- project_id: str,
- location: str | None,
- dataset_id: str,
- table_name: str,
- private_key: str,
- private_key_id: str,
- dataset_project_id: str | None,
- client_email: str,
- token_uri: str,
- should_use_incremental_field: bool,
- bq_destination_table_id: str,
- db_incremental_field_last_value: typing.Any,
- logger: FilteringBoundLogger,
- incremental_field: str | None = None,
- incremental_field_type: IncrementalFieldType | None = None,
- partition_size_bytes: int = DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,
-) -> SourceResponse:
- """Produce a pipeline source for BigQuery.
+class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigquery.Client, Any]):
+ """BigQuery driver implementation paired with `BigQuerySource`.
- This source will iterate through rows in `pyarrow.Table` objects using BigQuery's
- Storage API as much as possible due to higher quotas and lower cost compared to
- alternatives.
+ `CursorT` is `Any`: BigQuery has no DB-API cursor and does not satisfy
+ `_CursorLike`. Streaming and partition sizing run against the
+ `bigquery.Client` + `bigquery.Table` objects directly, not via a
+ shared `cursor.execute(...)` flow, so the base class's `cursor`-based
+ partition / chunk math is bypassed here.
"""
- project_id_for_dataset = dataset_project_id or project_id
- name = NamingConvention.normalize_identifier(table_name)
- fully_qualified_table_name = f"{project_id_for_dataset}.{dataset_id}.{table_name}"
+ # ------------------------------------------------------------------
+ # Connection lifecycle
+ # ------------------------------------------------------------------
- with bigquery_client(
- project_id=project_id,
- location=location,
- private_key=private_key,
- private_key_id=private_key_id,
- client_email=client_email,
- token_uri=token_uri,
- ) as bq_client:
- bq_table = bq_client.get_table(fully_qualified_table_name)
- primary_keys = get_primary_keys(bq_table, bq_client)
- partition_settings = get_partition_settings(bq_table, bq_client, partition_size_bytes=partition_size_bytes)
- has_duplicate_keys = has_duplicate_primary_keys(bq_table, bq_client, primary_keys)
- rows_to_sync = _get_rows_to_sync(
- bq_table,
- bq_client,
- should_use_incremental_field,
- db_incremental_field_last_value,
- logger,
- incremental_field,
- incremental_field_type,
+ @contextmanager
+ def connect(self, config: BigQuerySourceConfig) -> Iterator[bigquery.Client]:
+ region = _resolve_region(config)
+ with bigquery_client(
+ config.key_file.project_id,
+ region,
+ config.key_file.private_key,
+ config.key_file.private_key_id,
+ config.key_file.client_email,
+ config.key_file.token_uri,
+ ) as bq:
+ yield bq
+
+ # ------------------------------------------------------------------
+ # Listing — batch queries run once during `get_schemas`
+ # ------------------------------------------------------------------
+
+ def get_columns(
+ self,
+ conn: bigquery.Client,
+ config: BigQuerySourceConfig,
+ names: list[str] | None,
+ ) -> dict[str, list[tuple[str, str, bool]]]:
+ schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)
+
+ query = conn.query(
+ f"SELECT table_name, column_name, data_type, is_nullable FROM `{config.dataset_id}.INFORMATION_SCHEMA.COLUMNS` ORDER BY table_name ASC",
+ project=config.dataset_project.dataset_project_id
+ if config.dataset_project and config.dataset_project.enabled
+ else config.key_file.project_id,
)
+ try:
+ rows = query.result()
+ except Forbidden:
+ structlog.get_logger().warning(
+ "Could not obtain new schemas from BigQuery due to missing permissions on '%s.INFORMATION_SCHEMA.COLUMNS'",
+ config.dataset_id,
+ )
+ return {}
+
+ for row in rows:
+ schema_list[row.table_name].append((row.column_name, row.data_type, row.is_nullable == "YES"))
+
+ # Filter out PostHog's own temp destination tables — they live in
+ # the user's dataset only because BigQuery's Storage API can't
+ # stream views/materialized views without copying to a real table
+ # first.
+ temp_prefix = build_destination_table_prefix(None)
+ schema_list = {k: v for k, v in schema_list.items() if not k.startswith(temp_prefix)}
+
+ if names is not None:
+ names_set = set(names)
+ schema_list = {k: v for k, v in schema_list.items() if k in names_set}
+
+ return dict(schema_list)
+
+ def get_primary_keys(
+ self,
+ conn: bigquery.Client,
+ config: BigQuerySourceConfig,
+ tables: list[str],
+ ) -> dict[str, list[str] | None]:
+ if not tables:
+ return {}
+
+ project = (
+ config.dataset_project.dataset_project_id
+ if config.dataset_project and config.dataset_project.enabled
+ else config.key_file.project_id
+ )
+
+ # Join against INFORMATION_SCHEMA.COLUMNS so a PK constraint that
+ # references a column already dropped (stale metadata between
+ # constraint and column catalogs) doesn't leak into
+ # `detected_primary_keys` and corrupt downstream dedup.
+ #
+ # KEY_COLUMN_USAGE.column_name is sometimes returned as
+ # `<table>.<column>` and sometimes plain `<column>` depending on
+ # the BigQuery region / metadata version, hence the
+ # `removeprefix` below — the JOIN has to tolerate both shapes or
+ # half the rows get dropped.
+ query = f"""
+ SELECT tc.table_name, kcu.column_name
+ FROM `{config.dataset_id}`.INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
+ JOIN `{config.dataset_id}`.INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
+ ON tc.constraint_name = kcu.constraint_name
+ JOIN `{config.dataset_id}`.INFORMATION_SCHEMA.COLUMNS c
+ ON kcu.table_name = c.table_name
+ AND (
+ kcu.column_name = c.column_name
+ OR kcu.column_name = CONCAT(kcu.table_name, '.', c.column_name)
+ )
+ WHERE tc.constraint_type = 'PRIMARY KEY'
+ """
+
+ constraint_pks: dict[str, list[str]] = collections.defaultdict(list)
+ try:
+ job = conn.query(query, job_config=QueryJobConfig(), project=project)
+ for row in job.result():
+ table_name = row["table_name"]
+ col_name = row["column_name"].removeprefix(f"{table_name}.")
+ constraint_pks[table_name].append(col_name)
+ except Exception as e:
+ structlog.get_logger().warning("Failed to detect primary keys for BigQuery schemas", exc_info=e)
+ return {}
+
+ tables_set = set(tables)
+ return {table_name: pks for table_name, pks in constraint_pks.items() if table_name in tables_set}
+
+ def get_leading_index_columns(
+ self,
+ conn: bigquery.Client,
+ config: BigQuerySourceConfig,
+ tables: list[str],
+ ) -> dict[str, set[str]] | None:
+ """Return columns that act as the leading "index" per BigQuery table.
+
+ BigQuery doesn't have B-tree indexes; predicate pushdown for `WHERE col >= …`
+ is accelerated by:
+ - The partition column (INFORMATION_SCHEMA.COLUMNS.is_partitioning_column = 'YES')
+ - The leading clustering column (clustering_ordinal_position = 1)
+ Both are equally effective for skipping data, so we treat both as indexed.
+
+ Returns None on discovery failure so callers default to no warning. Tables
+ without partitioning or clustering map to an empty set so the UI warns for
+ them.
+ """
+ if not tables:
+ return {}
+
+ try:
+ result: dict[str, set[str]] = {table: set() for table in tables}
+
+ project = (
+ config.dataset_project.dataset_project_id
+ if config.dataset_project and config.dataset_project.enabled
+ else config.key_file.project_id
+ )
+
+ query = f"""
+ SELECT table_name, column_name
+ FROM `{config.dataset_id}`.INFORMATION_SCHEMA.COLUMNS
+ WHERE is_partitioning_column = 'YES'
+ OR clustering_ordinal_position = 1
+ """
+
+ job = conn.query(query, job_config=QueryJobConfig(), project=project)
+ for row in job.result():
+ table_name = row["table_name"]
+ if table_name in result:
+ result[table_name].add(row["column_name"])
+ except Exception as e:
+ structlog.get_logger().warning("Failed to detect partitioning/clustering for BigQuery schemas", exc_info=e)
+ return None
+
+ return result
+
+ def get_incremental_filter(self) -> IncrementalFieldFilter:
+ return filter_bigquery_incremental_fields
+
+ # ------------------------------------------------------------------
+ # Pipeline build — the dlt `SourceResponse` for a single table
+ # ------------------------------------------------------------------
+
+ def build_pipeline(self, config: BigQuerySourceConfig, inputs: SourceInputs) -> SourceResponse:
+ if not config.key_file.private_key:
+ raise ValueError(f"Missing private key for BigQuery: '{inputs.job_id}'")
+
+ region = _resolve_region(config)
+ dataset_project_id = _resolve_dataset_project_id(config)
+ destination_table_dataset_id = config.dataset_id
+
+ if (
+ config.temporary_dataset
+ and config.temporary_dataset.enabled
+ and config.temporary_dataset.temporary_dataset_id is not None
+ and config.temporary_dataset.temporary_dataset_id != ""
+ ):
+ destination_table_dataset_id = config.temporary_dataset.temporary_dataset_id
+
+ # Including the schema ID in table prefix ensures we only delete tables
+ # from this schema, and that if we fail we will clean up any previous
+ # execution's tables.
+ # Table names in BigQuery can have up to 1024 bytes, so we can be pretty
+ # relaxed with using a relatively long UUID as part of the prefix.
+ destination_table_prefix = build_destination_table_prefix(inputs.schema_id)
+
+ destination_table = f"{config.key_file.project_id}.{destination_table_dataset_id}.{destination_table_prefix}_{inputs.job_id.replace('-', '_')}_{str(datetime.now().timestamp()).replace('.', '')}"
+
+ delete_all_temp_destination_tables(
+ dataset_id=destination_table_dataset_id,
+ table_prefix=destination_table_prefix,
+ project_id=config.key_file.project_id,
+ location=region,
+ dataset_project_id=dataset_project_id,
+ private_key=config.key_file.private_key,
+ private_key_id=config.key_file.private_key_id,
+ client_email=config.key_file.client_email,
+ token_uri=config.key_file.token_uri,
+ logger=inputs.logger,
+ )
+
+ try:
+ return self._build_source_response(
+ config=config,
+ inputs=inputs,
+ region=region,
+ dataset_project_id=dataset_project_id,
+ bq_destination_table_id=destination_table,
+ )
+ finally:
+ # Delete the destination table (if it exists) after we're done with it
+ delete_table(
+ table_id=destination_table,
+ project_id=config.key_file.project_id,
+ location=region,
+ private_key=config.key_file.private_key,
+ private_key_id=config.key_file.private_key_id,
+ client_email=config.key_file.client_email,
+ token_uri=config.key_file.token_uri,
+ )
+ inputs.logger.info(f"Deleting bigquery temp destination table: {destination_table}")
+
+ def _build_source_response(
+ self,
+ config: BigQuerySourceConfig,
+ inputs: SourceInputs,
+ region: str | None,
+ dataset_project_id: str | None,
+ bq_destination_table_id: str,
+ partition_size_bytes: int = DEFAULT_PARTITION_TARGET_SIZE_IN_BYTES,
+ ) -> SourceResponse:
+ """Produce a pipeline source for BigQuery.
+
+ Iterates rows in `pyarrow.Table` chunks using BigQuery's Storage API
+ for higher quota and lower cost vs. row-by-row reads.
+ """
+ table_name = inputs.schema_name
+ if not table_name:
+ raise ValueError("Table name is missing")
+
+ should_use_incremental_field = inputs.should_use_incremental_field
+ incremental_field = inputs.incremental_field if should_use_incremental_field else None
+ incremental_field_type = inputs.incremental_field_type if should_use_incremental_field else None
+ db_incremental_field_last_value = (
+ inputs.db_incremental_field_last_value if should_use_incremental_field else None
+ )
+ logger = inputs.logger
+
+ project_id = config.key_file.project_id
+ location = region
+ private_key = config.key_file.private_key
+ private_key_id = config.key_file.private_key_id
+ client_email = config.key_file.client_email
+ token_uri = config.key_file.token_uri
+
+ project_id_for_dataset = dataset_project_id or project_id
+ name = NamingConvention.normalize_identifier(table_name)
+ fully_qualified_table_name = f"{project_id_for_dataset}.{config.dataset_id}.{table_name}"
- def get_rows(max_table_size: int) -> collections.abc.Iterator[pa.Table]:
with bigquery_client(
project_id=project_id,
location=location,
@@ -583,108 +681,131 @@ def bigquery_source(
token_uri=token_uri,
) as bq_client:
bq_table = bq_client.get_table(fully_qualified_table_name)
-
- if should_use_incremental_field:
- # This is only done because incremental syncs require progress tracking.
- # This requirement means we need to enforce an order, as otherwise
- # progress could move ahead of the current stream. Thus, we need to run
- # a query job that moves all the data in `incremental_field` order to a
- # temporary table given by `bq_destination_table_id`.
- # TODO: Think about whether this is at all necessary. We (and our users)
- # are paying a (potentially high) cost to run this query job and store
- # this data, when we could instead give up tracking and read it.
- query = _get_query(
- should_use_incremental_field,
- db_incremental_field_last_value,
- bq_table,
- incremental_field,
- incremental_field_type,
- )
-
- destination_table = bigquery.Table(bq_destination_table_id)
- job_config = QueryJobConfig(destination=destination_table)
- job = bq_client.query(query, job_config=job_config, project=bq_table.project)
- _ = job.result()
-
- bq_table = bq_client.get_table(destination_table)
-
- elif bq_table.table_type in ("VIEW", "MATERIALIZED_VIEW", "EXTERNAL"):
- # BigQuery storage API does not support reading directly from views or
- # materialized views. So, similarly to incremental runs, we must copy the
- # results to a temporary table first. In the case of an incremental sync,
- # we already do this for all tables and views, so here we just handle the
- # views or materialized views that are not incremental.
- query = _get_query(
- should_use_incremental_field,
- db_incremental_field_last_value,
- bq_table,
- incremental_field,
- incremental_field_type,
- )
-
- destination_table = bigquery.Table(bq_destination_table_id)
- job_config = QueryJobConfig(destination=destination_table)
- job = bq_client.query(query, job_config=job_config, project=bq_table.project)
- _ = job.result()
-
- bq_table = bq_client.get_table(destination_table)
-
- requested_session = bigquery_storage.ReadSession(
- table=bq_table.to_bqstorage(),
- data_format=bigquery_storage.DataFormat.ARROW,
- read_options=bigquery_storage.ReadSession.TableReadOptions(
- arrow_serialization_options=bigquery_storage.ArrowSerializationOptions(
- # LZ4 offers a good trade-off of low resource usage for compression, so
- # as an initial value without further testing it should do fine. That being said,
- # TODO: Evaluate if ZSTD is a better alternative for our use case.
- buffer_compression=bigquery_storage.ArrowSerializationOptions.CompressionCodec.LZ4_FRAME
- )
- ),
+ primary_keys = _get_primary_keys_for_table(bq_table, bq_client)
+ partition_settings = _get_partition_settings(bq_table, bq_client, partition_size_bytes=partition_size_bytes)
+ has_duplicate_keys = _has_duplicate_primary_keys(bq_table, bq_client, primary_keys)
+ rows_to_sync = _get_rows_to_sync(
+ bq_table,
+ bq_client,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ logger,
+ incremental_field,
+ incremental_field_type,
)
- with bigquery_storage_read_client(
+
+ def get_rows(max_table_size: int) -> collections.abc.Iterator[pa.Table]:
+ with bigquery_client(
project_id=project_id,
+ location=location,
private_key=private_key,
private_key_id=private_key_id,
client_email=client_email,
token_uri=token_uri,
- ) as bq_storage:
- read_session = bq_storage.create_read_session(
- parent="projects/{}".format(bq_table.project),
- read_session=requested_session,
- # TODO: Currently, single stream. Could multi-thread here for performance.
- max_stream_count=1,
+ ) as bq_client:
+ bq_table = bq_client.get_table(fully_qualified_table_name)
+
+ if should_use_incremental_field:
+ # This is only done because incremental syncs require progress tracking.
+ # This requirement means we need to enforce an order, as otherwise
+ # progress could move ahead of the current stream. Thus, we need to run
+ # a query job that moves all the data in `incremental_field` order to a
+ # temporary table given by `bq_destination_table_id`.
+ # TODO: Think about whether this is at all necessary. We (and our users)
+ # are paying a (potentially high) cost to run this query job and store
+ # this data, when we could instead give up tracking and read it.
+ query = _get_query(
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ bq_table,
+ incremental_field,
+ incremental_field_type,
+ )
+
+ destination_table = bigquery.Table(bq_destination_table_id)
+ job_config = QueryJobConfig(destination=destination_table)
+ job = bq_client.query(query, job_config=job_config, project=bq_table.project)
+ _ = job.result()
+
+ bq_table = bq_client.get_table(destination_table)
+
+ elif bq_table.table_type in ("VIEW", "MATERIALIZED_VIEW", "EXTERNAL"):
+ # BigQuery storage API does not support reading directly from views or
+ # materialized views. So, similarly to incremental runs, we must copy the
+ # results to a temporary table first. In the case of an incremental sync,
+ # we already do this for all tables and views, so here we just handle the
+ # views or materialized views that are not incremental.
+ query = _get_query(
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ bq_table,
+ incremental_field,
+ incremental_field_type,
+ )
+
+ destination_table = bigquery.Table(bq_destination_table_id)
+ job_config = QueryJobConfig(destination=destination_table)
+ job = bq_client.query(query, job_config=job_config, project=bq_table.project)
+ _ = job.result()
+
+ bq_table = bq_client.get_table(destination_table)
+
+ requested_session = bigquery_storage.ReadSession(
+ table=bq_table.to_bqstorage(),
+ data_format=bigquery_storage.DataFormat.ARROW,
+ read_options=bigquery_storage.ReadSession.TableReadOptions(
+ arrow_serialization_options=bigquery_storage.ArrowSerializationOptions(
+ # LZ4 offers a good trade-off of low resource usage for compression, so
+ # as an initial value without further testing it should do fine. That being said,
+ # TODO: Evaluate if ZSTD is a better alternative for our use case.
+ buffer_compression=bigquery_storage.ArrowSerializationOptions.CompressionCodec.LZ4_FRAME
+ )
+ ),
)
+ with bigquery_storage_read_client(
+ project_id=project_id,
+ private_key=private_key,
+ private_key_id=private_key_id,
+ client_email=client_email,
+ token_uri=token_uri,
+ ) as bq_storage:
+ read_session = bq_storage.create_read_session(
+ parent="projects/{}".format(bq_table.project),
+ read_session=requested_session,
+ # TODO: Currently, single stream. Could multi-thread here for performance.
+ max_stream_count=1,
+ )
- if not read_session.streams:
- # Empty table, nothing to read
- return
+ if not read_session.streams:
+ # Empty table, nothing to read
+ return
- stream_name = read_session.streams[0].name
- read_rows_stream = bq_storage.read_rows(stream_name)
- rows_iterator = read_rows_stream.rows()
+ stream_name = read_session.streams[0].name
+ read_rows_stream = bq_storage.read_rows(stream_name)
+ rows_iterator = read_rows_stream.rows()
- record_batches = []
- table_size_bytes = 0
- for page in rows_iterator.pages:
- record_batch = page.to_arrow()
- # TODO: Perhaps we should support slicing record batches like we do in batch exports.
- table_size_bytes += record_batch.get_total_buffer_size()
- record_batches.append(record_batch)
+ record_batches = []
+ table_size_bytes = 0
+ for page in rows_iterator.pages:
+ record_batch = page.to_arrow()
+ # TODO: Perhaps we should support slicing record batches like we do in batch exports.
+ table_size_bytes += record_batch.get_total_buffer_size()
+ record_batches.append(record_batch)
- if table_size_bytes > max_table_size:
+ if table_size_bytes > max_table_size:
+ yield pa.Table.from_batches(record_batches)
+ record_batches = []
+ table_size_bytes = 0
+
+ if record_batches:
yield pa.Table.from_batches(record_batches)
- record_batches = []
- table_size_bytes = 0
-
- if record_batches:
- yield pa.Table.from_batches(record_batches)
-
- return SourceResponse(
- name=name,
- items=lambda: get_rows(DEFAULT_TABLE_SIZE_BYTES),
- primary_keys=primary_keys,
- partition_count=partition_settings.partition_count if partition_settings else None,
- partition_size=partition_settings.partition_size if partition_settings else None,
- rows_to_sync=rows_to_sync,
- has_duplicate_primary_keys=has_duplicate_keys,
- )
+
+ return SourceResponse(
+ name=name,
+ items=lambda: get_rows(DEFAULT_TABLE_SIZE_BYTES),
+ primary_keys=primary_keys,
+ partition_count=partition_settings.partition_count if partition_settings else None,
+ partition_size=partition_settings.partition_size if partition_settings else None,
+ rows_to_sync=rows_to_sync,
+ has_duplicate_primary_keys=has_duplicate_keys,
+ )
diff --git a/posthog/temporal/data_imports/sources/bigquery/source.py b/posthog/temporal/data_imports/sources/bigquery/source.py
index ad2bc98ca8be..a24ed27bcca0 100644
--- a/posthog/temporal/data_imports/sources/bigquery/source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/source.py
@@ -1,8 +1,5 @@
-from datetime import datetime
from typing import Optional, cast
-import structlog
-
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
SourceConfig,
@@ -13,31 +10,29 @@ from posthog.schema import (
SourceFieldSwitchGroupConfig,
)
-from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.bigquery.bigquery import (
- bigquery_source,
- delete_all_temp_destination_tables,
- delete_table,
- filter_incremental_fields as filter_bigquery_incremental_fields,
- get_leading_indexed_columns_for_schemas as get_bigquery_leading_indexed_columns_for_schemas,
- get_primary_keys_for_schemas as get_bigquery_primary_keys_for_schemas,
- get_schemas as get_bigquery_schemas,
- validate_credentials as validate_bigquery_credentials,
+ BigQueryImplementation,
+ build_destination_table_prefix,
+ validate_bigquery_credentials,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.sources.common.base import FieldType
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
-from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.common.sql.base import SQLSource
from posthog.temporal.data_imports.sources.generated_configs import BigQuerySourceConfig
-from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalFieldType
+from products.data_warehouse.backend.types import ExternalDataSourceType
+__all__ = ["BigQuerySource", "build_destination_table_prefix"]
-def build_destination_table_prefix(schema_id: str | None) -> str:
- return f"__posthog_import_{schema_id.replace('-', '_') if schema_id else ''}"
+_BIGQUERY_IMPLEMENTATION = BigQueryImplementation()
@SourceRegistry.register
-class BigQuerySource(SimpleSource[BigQuerySourceConfig]):
+class BigQuerySource(SQLSource[BigQuerySourceConfig]):
+ @property
+ def get_implementation(self) -> BigQueryImplementation:
+ return _BIGQUERY_IMPLEMENTATION
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BIGQUERY
@@ -54,61 +49,6 @@ class BigQuerySource(SimpleSource[BigQuerySourceConfig]):
"Source column type changed": "A column's type changed in your source database (for example an integer column was widened to bigint) and no longer fits the type we stored. We can't widen an existing column in place — please reset and fully re-sync this table to adopt the new type.",
}
- def get_schemas(
- self,
- config: BigQuerySourceConfig,
- team_id: int,
- with_counts: bool = False,
- names: list[str] | None = None,
- force_refresh: bool = False,
- ) -> list[SourceSchema]:
- bq_schemas = get_bigquery_schemas(
- config,
- logger=None,
- names=names,
- )
-
- try:
- detected_pks = get_bigquery_primary_keys_for_schemas(config, bq_schemas)
- except Exception as e:
- structlog.get_logger().warning("Failed to detect primary keys for BigQuery schemas", exc_info=e)
- detected_pks = {}
-
- indexed_columns_by_table = get_bigquery_leading_indexed_columns_for_schemas(
- config, table_names=list(bq_schemas.keys())
- )
-
- filtered_results = [
- (table_name, filter_bigquery_incremental_fields(columns)) for table_name, columns in bq_schemas.items()
- ]
-
- def _build_incremental_fields(table_name: str, columns: list[tuple[str, IncrementalFieldType, bool]]) -> list:
- indexed_cols = indexed_columns_by_table.get(table_name) if indexed_columns_by_table is not None else None
- return [
- {
- "label": column_name,
- "type": column_type,
- "field": column_name,
- "field_type": column_type,
- "nullable": nullable,
- "is_indexed": True if indexed_cols is None else column_name in indexed_cols,
- }
- for column_name, column_type, nullable in columns
- ]
-
- return [
- SourceSchema(
- name=table_name,
- supports_incremental=len(columns) > 0,
- supports_append=len(columns) > 0,
- incremental_fields=_build_incremental_fields(table_name, columns),
- columns=bq_schemas[table_name],
- detected_primary_keys=detected_pks.get(table_name),
- )
- for table_name, columns in filtered_results
- if not table_name.startswith(build_destination_table_prefix(None))
- ]
-
def validate_credentials(
self, config: BigQuerySourceConfig, team_id: int, schema_name: Optional[str] = None
) -> tuple[bool, str | None]:
@@ -136,93 +76,6 @@ class BigQuerySource(SimpleSource[BigQuerySourceConfig]):
return False, "Invalid BigQuery credentials"
- def source_for_pipeline(self, config: BigQuerySourceConfig, inputs: SourceInputs) -> SourceResponse:
- if not config.key_file.private_key:
- raise ValueError(f"Missing private key for BigQuery: '{inputs.job_id}'")
-
- region: str | None = None
- dataset_project_id: str | None = None
- destination_table_dataset_id = config.dataset_id
-
- if (
- config.use_custom_region
- and config.use_custom_region.enabled
- and config.use_custom_region.region is not None
- and config.use_custom_region.region != ""
- ):
- region = config.use_custom_region.region
-
- if (
- config.dataset_project
- and config.dataset_project.enabled
- and config.dataset_project.dataset_project_id is not None
- and config.dataset_project.dataset_project_id != ""
- ):
- dataset_project_id = config.dataset_project.dataset_project_id
-
- if (
- config.temporary_dataset
- and config.temporary_dataset.enabled
- and config.temporary_dataset.temporary_dataset_id is not None
- and config.temporary_dataset.temporary_dataset_id != ""
- ):
- destination_table_dataset_id = config.temporary_dataset.temporary_dataset_id
-
- # Including the schema ID in table prefix ensures we only delete tables
- # from this schema, and that if we fail we will clean up any previous
- # execution's tables.
- # Table names in BigQuery can have up to 1024 bytes, so we can be pretty
- # relaxed with using a relatively long UUID as part of the prefix.
- destination_table_prefix = build_destination_table_prefix(inputs.schema_id)
-
- destination_table = f"{config.key_file.project_id}.{destination_table_dataset_id}.{destination_table_prefix}_{inputs.job_id.replace('-', '_')}_{str(datetime.now().timestamp()).replace('.', '')}"
-
- delete_all_temp_destination_tables(
- dataset_id=destination_table_dataset_id,
- table_prefix=destination_table_prefix,
- project_id=config.key_file.project_id,
- location=region,
- dataset_project_id=dataset_project_id,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- logger=inputs.logger,
- )
-
- try:
- return bigquery_source(
- dataset_id=config.dataset_id,
- project_id=config.key_file.project_id,
- location=region,
- dataset_project_id=dataset_project_id,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- table_name=inputs.schema_name,
- should_use_incremental_field=inputs.should_use_incremental_field,
- logger=inputs.logger,
- bq_destination_table_id=destination_table,
- incremental_field=inputs.incremental_field if inputs.should_use_incremental_field else None,
- incremental_field_type=inputs.incremental_field_type if inputs.should_use_incremental_field else None,
- db_incremental_field_last_value=inputs.db_incremental_field_last_value
- if inputs.should_use_incremental_field
- else None,
- )
- finally:
- # Delete the destination table (if it exists) after we're done with it
- delete_table(
- table_id=destination_table,
- project_id=config.key_file.project_id,
- location=region,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- )
- inputs.logger.info(f"Deleting bigquery temp destination table: {destination_table}")
-
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
diff --git a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
index 73080a314ae9..f23d4ec8c592 100644
--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py
@@ -1,9 +1,11 @@
+import pytest
from freezegun import freeze_time
from unittest import mock
from dateutil import parser
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.bigquery.bigquery import BigQueryImplementation
from posthog.temporal.data_imports.sources.bigquery.source import BigQuerySource
from posthog.temporal.data_imports.sources.generated_configs import (
BigQueryDatasetProjectConfig,
@@ -13,30 +15,31 @@ from posthog.temporal.data_imports.sources.generated_configs import (
)
-def test_bigquery_get_schemas():
- with mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.get_bigquery_schemas", return_value={"table": []}
- ):
- source_cls = BigQuerySource()
- schemas = source_cls.get_schemas(mock.ANY, 1)
- assert len(schemas) == 1
- assert schemas[0].name == "table"
-
-
-def test_bigquery_get_schemas_with_existing_destination_tables():
- with mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.get_bigquery_schemas",
- return_value={"table": [], "__posthog_import_0000_0000": []},
- ):
- source_cls = BigQuerySource()
- schemas = source_cls.get_schemas(mock.ANY, 1)
- assert len(schemas) == 1
- assert schemas[0].name == "table"
-
-
-def test_bigquery_destination_table_default():
- source_cls = BigQuerySource()
- config = BigQuerySourceConfig(
+def _make_inputs(**overrides) -> SourceInputs:
+ defaults: dict = {
+ "schema_name": "schema",
+ "schema_id": "schema-id",
+ "source_id": "source-id",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-id",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+def _make_config(
+ *,
+ dataset_project: BigQueryDatasetProjectConfig | None = None,
+ temporary_dataset: BigQueryTemporaryDatasetConfig | None = None,
+) -> BigQuerySourceConfig:
+ return BigQuerySourceConfig(
key_file=BigQueryKeyFileConfig(
project_id="project-id",
private_key="private-key",
@@ -45,350 +48,80 @@ def test_bigquery_destination_table_default():
token_uri="token-uri",
),
dataset_id="dataset-id",
- dataset_project=None,
- temporary_dataset=None,
+ dataset_project=dataset_project,
+ temporary_dataset=temporary_dataset,
)
- with (
- freeze_time("2025-01-01T12:00:00.000Z"),
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_all_temp_destination_tables",
- ) as mock_delete_all_temp_destination_tables,
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.bigquery_source",
- ) as mock_bigquery_source,
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_table",
- ) as mock_delete_table,
- ):
- source_cls.source_for_pipeline(
- config,
- SourceInputs(
- schema_name="schema",
- schema_id="schema-id",
- source_id="source-id",
- team_id=1,
- should_use_incremental_field=False,
- db_incremental_field_last_value=None,
- db_incremental_field_earliest_value=None,
- incremental_field=None,
- incremental_field_type=None,
- job_id="job-id",
- logger=mock.MagicMock(),
- reset_pipeline=False,
- ),
- )
-
- mock_delete_all_temp_destination_tables.assert_called_once_with(
- dataset_id="dataset-id",
- table_prefix="__posthog_import_schema_id",
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- logger=mock.ANY,
- )
- mock_bigquery_source.assert_called_once_with(
- dataset_id=config.dataset_id,
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- table_name="schema",
- should_use_incremental_field=False,
- logger=mock.ANY,
- bq_destination_table_id=f"project-id.dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- incremental_field=None,
- incremental_field_type=None,
- db_incremental_field_last_value=None,
+def test_bigquery_get_columns_filters_existing_destination_tables():
+ """`get_columns` strips `__posthog_import_*` tables before returning."""
+ fake_client = mock.MagicMock()
+ fake_row_keep = mock.MagicMock(table_name="table", column_name="c", data_type="STRING", is_nullable="NO")
+ fake_row_skip = mock.MagicMock(
+ table_name="__posthog_import_0000_0000", column_name="c", data_type="STRING", is_nullable="NO"
)
+ fake_client.query.return_value.result.return_value = [fake_row_keep, fake_row_skip]
- mock_delete_table.assert_called_once_with(
- table_id=f"project-id.dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- project_id=config.key_file.project_id,
- location=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- )
+ columns = BigQueryImplementation().get_columns(fake_client, _make_config(), names=None)
+ assert list(columns.keys()) == ["table"]
-def test_bigquery_destination_table_with_dataset_project_set():
- source_cls = BigQuerySource()
- config = BigQuerySourceConfig(
- key_file=BigQueryKeyFileConfig(
- project_id="project-id",
- private_key="private-key",
- private_key_id="private-key-id",
- client_email="client-email",
- token_uri="token-uri",
+ "dataset_project,temporary_dataset,expected_dataset_project_id,expected_destination_dataset_id",
+ [
+ # default — no dataset_project, no temporary_dataset
+ (None, None, None, "dataset-id"),
+ # dataset_project enabled — propagated through both delete_all and _build_source_response
+ (
+ BigQueryDatasetProjectConfig(dataset_project_id="other-project-id", enabled=True),
+ None,
+ "other-project-id",
+ "dataset-id",
),
- dataset_id="dataset-id",
- dataset_project=BigQueryDatasetProjectConfig(
- dataset_project_id="other-project-id",
- enabled=True,
+ # temporary_dataset enabled — overrides destination_table_dataset_id
+ (
+ None,
+ BigQueryTemporaryDatasetConfig(temporary_dataset_id="some-other-dataset-id", enabled=True),
+ None,
+ "some-other-dataset-id",
),
- temporary_dataset=None,
- )
-
- with (
- freeze_time("2025-01-01T12:00:00.000Z"),
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_all_temp_destination_tables",
- ) as mock_delete_all_temp_destination_tables,
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.bigquery_source",
- ) as mock_bigquery_source,
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_table",
- ) as mock_delete_table,
- ):
- source_cls.source_for_pipeline(
- config,
- SourceInputs(
- schema_name="schema",
- schema_id="schema-id",
- source_id="source-id",
- team_id=1,
- should_use_incremental_field=False,
- db_incremental_field_last_value=None,
- db_incremental_field_earliest_value=None,
- incremental_field=None,
- incremental_field_type=None,
- job_id="job-id",
- logger=mock.MagicMock(),
- reset_pipeline=False,
- ),
- )
-
- mock_delete_all_temp_destination_tables.assert_called_once_with(
- dataset_id="dataset-id",
- table_prefix="__posthog_import_schema_id",
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id="other-project-id",
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- logger=mock.ANY,
- )
-
- mock_bigquery_source.assert_called_once_with(
- dataset_id=config.dataset_id,
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id="other-project-id",
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- table_name="schema",
- should_use_incremental_field=False,
- logger=mock.ANY,
- bq_destination_table_id=f"project-id.dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- incremental_field=None,
- incremental_field_type=None,
- db_incremental_field_last_value=None,
- )
-
- mock_delete_table.assert_called_once_with(
- table_id=f"project-id.dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- project_id=config.key_file.project_id,
- location=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- )
-
-
-def test_bigquery_destination_table_with_temporary_dataset_set():
- source_cls = BigQuerySource()
- config = BigQuerySourceConfig(
- key_file=BigQueryKeyFileConfig(
- project_id="project-id",
- private_key="private-key",
- private_key_id="private-key-id",
- client_email="client-email",
- token_uri="token-uri",
- ),
- dataset_id="dataset-id",
- dataset_project=None,
- temporary_dataset=BigQueryTemporaryDatasetConfig(
- temporary_dataset_id="some-other-dataset-id",
- enabled=True,
- ),
- )
-
- with (
- freeze_time("2025-01-01T12:00:00.000Z"),
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_all_temp_destination_tables",
- ) as mock_delete_all_temp_destination_tables,
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.bigquery_source",
- ) as mock_bigquery_source,
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_table",
- ) as mock_delete_table,
- ):
- source_cls.source_for_pipeline(
- config,
- SourceInputs(
- schema_name="schema",
- schema_id="schema-id",
- source_id="source-id",
- team_id=1,
- should_use_incremental_field=False,
- db_incremental_field_last_value=None,
- db_incremental_field_earliest_value=None,
- incremental_field=None,
- incremental_field_type=None,
- job_id="job-id",
- logger=mock.MagicMock(),
- reset_pipeline=False,
- ),
- )
-
- mock_delete_all_temp_destination_tables.assert_called_once_with(
- dataset_id="some-other-dataset-id",
- table_prefix="__posthog_import_schema_id",
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- logger=mock.ANY,
- )
-
- mock_bigquery_source.assert_called_once_with(
- dataset_id=config.dataset_id,
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- table_name="schema",
- should_use_incremental_field=False,
- logger=mock.ANY,
- bq_destination_table_id=f"project-id.some-other-dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- incremental_field=None,
- incremental_field_type=None,
- db_incremental_field_last_value=None,
- )
-
- mock_delete_table.assert_called_once_with(
- table_id=f"project-id.some-other-dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- project_id=config.key_file.project_id,
- location=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- )
-
-
-def test_bigquery_destination_table_with_both_temporary_dataset_and_dataset_project_set():
- source_cls = BigQuerySource()
- config = BigQuerySourceConfig(
- key_file=BigQueryKeyFileConfig(
- project_id="project-id",
- private_key="private-key",
- private_key_id="private-key-id",
- client_email="client-email",
- token_uri="token-uri",
- ),
- dataset_id="dataset-id",
- dataset_project=BigQueryDatasetProjectConfig(
- dataset_project_id="other-project-id",
- enabled=True,
- ),
- temporary_dataset=BigQueryTemporaryDatasetConfig(
- temporary_dataset_id="some-other-dataset-id",
- enabled=True,
+ # both set — temporary_dataset wins for destination, dataset_project still resolved
+ (
+ BigQueryDatasetProjectConfig(dataset_project_id="other-project-id", enabled=True),
+ BigQueryTemporaryDatasetConfig(temporary_dataset_id="some-other-dataset-id", enabled=True),
+ "other-project-id",
+ "some-other-dataset-id",
),
+ ],
+)
+def test_bigquery_build_pipeline_resolves_dataset_routing(
+ dataset_project, temporary_dataset, expected_dataset_project_id, expected_destination_dataset_id
+):
+ config = _make_config(dataset_project=dataset_project, temporary_dataset=temporary_dataset)
+ expected_table_id = (
+ f"project-id.{expected_destination_dataset_id}.__posthog_import_schema_id_job_id_"
+ f"{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}"
)
with (
freeze_time("2025-01-01T12:00:00.000Z"),
mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_all_temp_destination_tables",
- ) as mock_delete_all_temp_destination_tables,
+ "posthog.temporal.data_imports.sources.bigquery.bigquery.delete_all_temp_destination_tables",
+ ) as mock_delete_all,
+ mock.patch.object(
+ BigQueryImplementation, "_build_source_response", return_value=mock.MagicMock()
+ ) as mock_build,
mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.bigquery_source",
- ) as mock_bigquery_source,
- mock.patch(
- "posthog.temporal.data_imports.sources.bigquery.source.delete_table",
- ) as mock_delete_table,
+ "posthog.temporal.data_imports.sources.bigquery.bigquery.delete_table",
+ ) as mock_delete,
):
- source_cls.source_for_pipeline(
- config,
- SourceInputs(
- schema_name="schema",
- schema_id="schema-id",
- source_id="source-id",
- team_id=1,
- should_use_incremental_field=False,
- db_incremental_field_last_value=None,
- db_incremental_field_earliest_value=None,
- incremental_field=None,
- incremental_field_type=None,
- job_id="job-id",
- logger=mock.MagicMock(),
- reset_pipeline=False,
- ),
- )
+ BigQuerySource().source_for_pipeline(config, _make_inputs())
- mock_delete_all_temp_destination_tables.assert_called_once_with(
- dataset_id="some-other-dataset-id",
- table_prefix="__posthog_import_schema_id",
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id="other-project-id",
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- logger=mock.ANY,
- )
+ assert mock_delete_all.call_args.kwargs["dataset_id"] == expected_destination_dataset_id
+ assert mock_delete_all.call_args.kwargs["dataset_project_id"] == expected_dataset_project_id
+ assert mock_delete_all.call_args.kwargs["table_prefix"] == "__posthog_import_schema_id"
- mock_bigquery_source.assert_called_once_with(
- dataset_id=config.dataset_id,
- project_id=config.key_file.project_id,
- location=None,
- dataset_project_id="other-project-id",
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- table_name="schema",
- should_use_incremental_field=False,
- logger=mock.ANY,
- bq_destination_table_id=f"project-id.some-other-dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- incremental_field=None,
- incremental_field_type=None,
- db_incremental_field_last_value=None,
- )
+ assert mock_build.call_args.kwargs["dataset_project_id"] == expected_dataset_project_id
+ assert mock_build.call_args.kwargs["bq_destination_table_id"] == expected_table_id
- mock_delete_table.assert_called_once_with(
- table_id=f"project-id.some-other-dataset-id.__posthog_import_schema_id_job_id_{str(parser.parse('2025-01-01T12:00:00.000Z').timestamp()).replace('.', '')}",
- project_id=config.key_file.project_id,
- location=None,
- private_key=config.key_file.private_key,
- private_key_id=config.key_file.private_key_id,
- client_email=config.key_file.client_email,
- token_uri=config.key_file.token_uri,
- )
+ assert mock_delete.call_args.kwargs["table_id"] == expected_table_id
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index e31cabf56a01..4745379f11ab 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -776,15 +776,21 @@ class TestExternalDataSource(APIBaseTest):
"""Test we remove the `project_id` prefix of a `dataset_id`."""
with (
patch(
- "posthog.temporal.data_imports.sources.bigquery.source.get_bigquery_schemas"
- ) as mocked_get_bigquery_schemas,
+ "posthog.temporal.data_imports.sources.bigquery.source.BigQuerySource.get_schemas",
+ return_value=[
+ SourceSchema(
+ name="my_table",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("something", "DATE", False)],
+ )
+ ],
+ ),
patch(
"posthog.temporal.data_imports.sources.bigquery.source.BigQuerySource.validate_credentials",
return_value=(True, None),
),
):
- mocked_get_bigquery_schemas.return_value = {"my_table": [("something", "DATE", False)]}
-
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/",
data={
@@ -4476,11 +4482,17 @@ class TestExternalDataSource(APIBaseTest):
return_value=(True, None),
),
patch(
- "posthog.temporal.data_imports.sources.bigquery.source.get_bigquery_schemas"
- ) as mocked_get_bigquery_schemas,
+ "posthog.temporal.data_imports.sources.bigquery.source.BigQuerySource.get_schemas",
+ return_value=[
+ SourceSchema(
+ name="my_table",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("something", "DATE", False)],
+ )
+ ],
+ ),
):
- mocked_get_bigquery_schemas.return_value = {"my_table": [("something", "DATE", False)]}
-
# Create a BigQuery source
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/",