:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(data-warehouse): migrate snowflake to SQLSourceImplementation (#59701)
Daniel RC0a6dbdf8b60a
diff --git a/posthog/temporal/data_imports/sources/snowflake/snowflake.py b/posthog/temporal/data_imports/sources/snowflake/snowflake.pyindex 448e4d63ecf3..df53df75ea6e 100644--- a/posthog/temporal/data_imports/sources/snowflake/snowflake.py+++ b/posthog/temporal/data_imports/sources/snowflake/snowflake.py@@ -1,14 +1,24 @@-import os-import tempfile+"""Snowflake driver for PostHog's data-warehouse import pipeline.++Everything Snowflake-specific — connection lifecycle (with password vs+keypair auth and the keypair tempfile dance), schema listing, per-cursor+metadata, and the dlt pipeline build — lives on+`SnowflakeImplementation`. The source-class `SnowflakeSource` is a thin+PostHog-layer wrapper that just holds an instance and validates+credentials.+"""++from __future__ import annotations+import collectionsfrom collections.abc import Iterator+from contextlib import contextmanagerfrom typing import Any, Optionalimport structlogimport snowflake.connectorfrom cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serialization-from snowflake.connector.cursor import SnowflakeCursorfrom structlog.types import FilteringBoundLoggerfrom posthog.exceptions_capture import capture_exception@@ -17,11 +27,18 @@ from posthog.temporal.data_imports.pipelines.helpers import (incremental_type_to_initial_value,incremental_type_to_operator,)-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.sources.common.sql.implementation import SQLSourceImplementation+from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilterfrom posthog.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfigfrom products.data_warehouse.backend.types import IncrementalFieldType+__all__ = [+ "SnowflakeImplementation",+ "filter_snowflake_incremental_fields",+]+def filter_snowflake_incremental_fields(columns: list[tuple[str, str, bool]],@@ -41,111 +58,6 @@ def filter_snowflake_incremental_fields(return results-def get_schemas(- config: SnowflakeSourceConfig, names: list[str] | None = None-) -> dict[str, list[tuple[str, str, bool]]]:- auth_connect_args: dict[str, str | None] = {}- file_name: str | None = None-- if config.auth_type.selection == "keypair" and config.auth_type.private_key is not None:- with tempfile.NamedTemporaryFile(delete=False) as tf:- tf.write(config.auth_type.private_key.encode("utf-8"))- file_name = tf.name-- auth_connect_args = {- "user": config.auth_type.user,- "private_key_file": file_name,- "private_key_file_pwd": config.auth_type.passphrase- if config.auth_type.passphrase and len(config.auth_type.passphrase) > 0- else None,- }- else:- auth_connect_args = {- "password": config.auth_type.password,- "user": config.auth_type.user,- }-- with snowflake.connector.connect(- account=config.account_id,- warehouse=config.warehouse,- database=config.database,- schema="information_schema",- role=config.role,- **auth_connect_args,- ) as connection:- with connection.cursor() as cursor:- if cursor is None:- raise Exception("Can't create cursor to Snowflake")-- cursor.execute(- "SELECT table_name, column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = %(schema)s ORDER BY table_name ASC",- {"schema": config.schema},- )- result = cursor.fetchall()-- schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)- for row in result:- schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))-- if file_name is not None:- os.unlink(file_name)-- 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 _get_connection(- account_id: str,- user: Optional[str],- password: Optional[str],- passphrase: Optional[str],- private_key: Optional[str],- auth_type: str,- database: str,- warehouse: str,- schema: str,- role: Optional[str] = None,-) -> snowflake.connector.SnowflakeConnection:- if auth_type == "password" and user is not None and password is not None:- return snowflake.connector.connect(- account=account_id,- user=user,- password=password,- warehouse=warehouse,- database=database,- schema=schema,- role=role if role else None,- )-- if private_key is None:- raise ValueError("Private key is missing for snowflake")-- p_key = serialization.load_pem_private_key(- private_key.encode("utf-8"),- password=passphrase.encode() if passphrase else None,- backend=default_backend(),- )-- pkb = p_key.private_bytes(- encoding=serialization.Encoding.DER,- format=serialization.PrivateFormat.PKCS8,- encryption_algorithm=serialization.NoEncryption(),- )-- return snowflake.connector.connect(- account=account_id,- user=user,- warehouse=warehouse,- database=database,- schema=schema,- role=role if role else None,- private_key=pkb,- )--def _build_query(database: str,schema: str,@@ -173,32 +85,6 @@ def _build_query()-def _get_rows_to_sync(- cursor: SnowflakeCursor, inner_query: str, inner_query_args: tuple[Any, ...], logger: FilteringBoundLogger-) -> int:- try:- query = f"SELECT COUNT(*) FROM ({inner_query}) as t"-- cursor.execute(query, inner_query_args)- row = cursor.fetchone()-- if row is None:- logger.debug(f"_get_rows_to_sync: No results returned. Using 0 as rows to sync")- return 0-- rows_to_sync = row[0] or 0- rows_to_sync_int = int(rows_to_sync)-- logger.debug(f"_get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")-- return int(rows_to_sync)- except Exception as e:- logger.debug(f"_get_rows_to_sync: Error: {e}. Using 0 as rows to sync", exc_info=e)- capture_exception(e)-- return 0--def _parse_clustering_key_leading_column(clustering_key: str | None) -> str | None:"""Extract the leading column from a Snowflake CLUSTERING_KEY string.@@ -228,38 +114,61 @@ def _parse_clustering_key_leading_column(clustering_key: str | None) -> str | Noreturn leading.upper()-def get_leading_clustering_columns_for_schemas(- config: SnowflakeSourceConfig,- table_names: list[str],-) -> dict[str, set[str]] | None:- """Return the leading column of the clustering key per table.+class SnowflakeImplementation(+ SQLSourceImplementation[SnowflakeSourceConfig, snowflake.connector.SnowflakeConnection, Any]+):+ """Snowflake driver implementation paired with `SnowflakeSource`.- Snowflake doesn't have B-tree indexes; clustering keys are the structure that- enables partition pruning for `WHERE col >= …` predicates. Tables without a- clustering key map to an empty set so the UI warning fires.+ One class owns everything Snowflake-specific: the connection+ lifecycle (password vs keypair, with private-key tempfile cleanup),+ `information_schema`-style batch queries used during schema listing,+ per-cursor metadata used during the streaming sync (primary keys),+ and the dlt pipeline factory (`build_pipeline`).- Returns None when discovery fails so the caller defaults to no warning.+ Snowflake does not currently use the optional streaming-side hooks+ (`fetch_table_stats`, `fetch_average_row_size`, `get_table_metadata`)+ — it streams via `cursor.fetch_arrow_batches()` and lets the base+ class return `None` for partition settings and the default chunk+ size. That preserves current behavior."""- if not table_names:- return {}-- result: dict[str, set[str]] = {table: set() for table in table_names}- file_name: str | None = None- try:- auth_connect_args: dict[str, str | None] = {}+ # ------------------------------------------------------------------+ # Connection lifecycle+ # ------------------------------------------------------------------++ @contextmanager+ def connect(+ self,+ config: SnowflakeSourceConfig,+ ) -> Iterator[snowflake.connector.SnowflakeConnection]:+ """Open a Snowflake connection for the duration of the context.++ Branches on `config.auth_type.selection`. In keypair mode the+ PEM private key is parsed in process and handed to the+ connector as DER bytes via `private_key=` — never written to+ disk, matching the streaming-side helper that the pre-refactor+ code used.++ Uses `config.schema` as the session schema. All listing queries+ use fully qualified `information_schema.<table>` references so+ the session schema does not affect their results.+ """+ auth_connect_args: dict[str, Any] = {}if config.auth_type.selection == "keypair" and config.auth_type.private_key is not None:- with tempfile.NamedTemporaryFile(delete=False) as tf:- tf.write(config.auth_type.private_key.encode("utf-8"))- file_name = tf.name-+ p_key = serialization.load_pem_private_key(+ config.auth_type.private_key.encode("utf-8"),+ password=config.auth_type.passphrase.encode() if config.auth_type.passphrase else None,+ backend=default_backend(),+ )+ pkb = p_key.private_bytes(+ encoding=serialization.Encoding.DER,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ )auth_connect_args = {"user": config.auth_type.user,- "private_key_file": file_name,- "private_key_file_pwd": config.auth_type.passphrase- if config.auth_type.passphrase and len(config.auth_type.passphrase) > 0- else None,+ "private_key": pkb,}else:auth_connect_args = {@@ -275,78 +184,63 @@ def get_leading_clustering_columns_for_schemas(role=config.role,**auth_connect_args,) as connection:- with connection.cursor() as cursor:- if cursor is None:- raise Exception("Can't create cursor to Snowflake")-- placeholders = ",".join(["%s"] * len(table_names))- cursor.execute(- f"""- SELECT TABLE_NAME, CLUSTERING_KEY- FROM INFORMATION_SCHEMA.TABLES- WHERE TABLE_CATALOG = %s- AND TABLE_SCHEMA = %s- AND TABLE_NAME IN ({placeholders})- """,- (config.database, config.schema, *table_names),- )-- for table_name, clustering_key in cursor:- leading = _parse_clustering_key_leading_column(clustering_key)- if leading is not None:- result.setdefault(table_name, set()).add(leading)- except Exception as e:- structlog.get_logger().warning("Failed to detect clustering keys for Snowflake schemas", exc_info=e)- return None- finally:- if file_name is not None:- os.unlink(file_name)-- return result---def get_primary_keys_for_schemas(- config: SnowflakeSourceConfig,- table_names: list[str],-) -> dict[str, list[str] | None]:- """Detect primary keys for all tables by iterating SHOW PRIMARY KEYS."""- result: dict[str, list[str] | None] = dict.fromkeys(table_names)- file_name: str | None = None-- try:- auth_connect_args: dict[str, str | None] = {}-- if config.auth_type.selection == "keypair" and config.auth_type.private_key is not None:- with tempfile.NamedTemporaryFile(delete=False) as tf:- tf.write(config.auth_type.private_key.encode("utf-8"))- file_name = tf.name+ yield connection++ # ------------------------------------------------------------------+ # Listing — batch queries run once during `get_schemas`+ # ------------------------------------------------------------------++ def get_columns(+ self,+ conn: snowflake.connector.SnowflakeConnection,+ config: SnowflakeSourceConfig,+ names: list[str] | None,+ ) -> dict[str, list[tuple[str, str, bool]]]:+ with conn.cursor() as cursor:+ if cursor is None:+ raise Exception("Can't create cursor to Snowflake")- auth_connect_args = {- "user": config.auth_type.user,- "private_key_file": file_name,- "private_key_file_pwd": config.auth_type.passphrase- if config.auth_type.passphrase and len(config.auth_type.passphrase) > 0- else None,- }- else:- auth_connect_args = {- "password": config.auth_type.password,- "user": config.auth_type.user,- }+ cursor.execute(+ "SELECT table_name, column_name, data_type, is_nullable"+ " FROM information_schema.columns"+ " WHERE table_schema = %(schema)s"+ " ORDER BY table_name ASC",+ {"schema": config.schema},+ )+ result = cursor.fetchall()- with snowflake.connector.connect(- account=config.account_id,- warehouse=config.warehouse,- database=config.database,- schema=config.schema,- role=config.role,- **auth_connect_args,- ) as connection:- with connection.cursor() as cursor:+ schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)+ for row in result:+ schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))++ if names is not None:+ names_set = set(names)+ schema_list = collections.defaultdict(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: snowflake.connector.SnowflakeConnection,+ config: SnowflakeSourceConfig,+ tables: list[str],+ ) -> dict[str, list[str] | None]:+ """Detect primary keys for all tables by iterating SHOW PRIMARY KEYS.++ Permission-sensitive — some Snowflake roles can't see+ catalog-level PK metadata. Swallow and log per-table failures so+ schema discovery keeps working without PKs.+ """+ result: dict[str, list[str] | None] = dict.fromkeys(tables)+ if not tables:+ return result++ try:+ with conn.cursor() as cursor:if cursor is None:raise Exception("Can't create cursor to Snowflake")- for tbl in table_names:+ for tbl in tables:try:cursor.execute("SHOW PRIMARY KEYS IN IDENTIFIER(%s)",@@ -369,73 +263,139 @@ def get_primary_keys_for_schemas(exc_info=e,)continue+ except Exception as e:+ structlog.get_logger().warning("Failed to detect primary keys for Snowflake schemas", exc_info=e)++ return result++ def get_leading_index_columns(+ self,+ conn: snowflake.connector.SnowflakeConnection,+ config: SnowflakeSourceConfig,+ tables: list[str],+ ) -> dict[str, set[str]] | None:+ """Return the leading column of the clustering key per table.++ Snowflake doesn't have B-tree indexes; clustering keys are the+ structure that enables partition pruning for `WHERE col >= …`+ predicates. Tables without a clustering key map to an empty set+ so the UI warning fires. Returns None when discovery fails so+ the caller defaults to no warning.+ """+ if not tables:+ return {}++ result: dict[str, set[str]] = {table: set() for table in tables}++ try:+ with conn.cursor() as cursor:+ if cursor is None:+ raise Exception("Can't create cursor to Snowflake")- except Exception as e:- structlog.get_logger().warning("Failed to detect primary keys for Snowflake schemas", exc_info=e)- finally:- if file_name is not None:- os.unlink(file_name)-- return result---def _get_primary_keys(cursor: SnowflakeCursor, database: str, schema: str, table_name: str) -> list[str] | None:- cursor.execute("SHOW PRIMARY KEYS IN IDENTIFIER(%s)", (f"{database}.{schema}.{table_name}",))-- column_index = next((i for i, row in enumerate(cursor.description) if row.name == "column_name"), -1)+ placeholders = ",".join(["%s"] * len(tables))+ cursor.execute(+ f"""+ SELECT TABLE_NAME, CLUSTERING_KEY+ FROM INFORMATION_SCHEMA.TABLES+ WHERE TABLE_CATALOG = %s+ AND TABLE_SCHEMA = %s+ AND TABLE_NAME IN ({placeholders})+ """,+ (config.database, config.schema, *tables),+ )- if column_index == -1:- raise ValueError("column_name not found in Snowflake cursor description")+ for table_name, clustering_key in cursor:+ leading = _parse_clustering_key_leading_column(clustering_key)+ if leading is not None:+ result.setdefault(table_name, set()).add(leading)+ except Exception as e:+ structlog.get_logger().warning("Failed to detect clustering keys for Snowflake schemas", exc_info=e)+ return None- keys = [row[column_index] for row in cursor]+ return result++ def get_incremental_filter(self) -> IncrementalFieldFilter:+ return filter_snowflake_incremental_fields++ # ------------------------------------------------------------------+ # Per-cursor metadata — used during `build_pipeline`+ # ------------------------------------------------------------------++ def get_primary_keys_for_table(+ self,+ cursor: Any,+ database: str,+ schema: str,+ table_name: str,+ ) -> list[str] | None:+ """Return the primary-key column names for a single table, or None.++ Snowflake's `SHOW PRIMARY KEYS IN IDENTIFIER(...)` requires the+ fully qualified `database.schema.table` reference, so this method+ takes `database` in addition to schema/table_name — the only+ driver to do so.+ """+ cursor.execute("SHOW PRIMARY KEYS IN IDENTIFIER(%s)", (f"{database}.{schema}.{table_name}",))++ column_index = next((i for i, row in enumerate(cursor.description) if row.name == "column_name"), -1)++ if column_index == -1:+ raise ValueError("column_name not found in Snowflake cursor description")++ keys = [row[column_index] for row in cursor]++ return keys if len(keys) > 0 else None++ def get_rows_to_sync(+ self,+ cursor: Any,+ inner_query: str,+ inner_query_args: tuple[Any, ...],+ logger: FilteringBoundLogger,+ ) -> int:+ """Count the rows the given `inner_query` will produce. Returns 0 on error."""+ try:+ query = f"SELECT COUNT(*) FROM ({inner_query}) as t"++ cursor.execute(query, inner_query_args)+ row = cursor.fetchone()++ if row is None:+ logger.debug("get_rows_to_sync: No results returned. Using 0 as rows to sync")+ return 0++ rows_to_sync = row[0] or 0+ rows_to_sync_int = int(rows_to_sync)++ logger.debug(f"get_rows_to_sync: rows_to_sync_int={rows_to_sync_int}")+ return rows_to_sync_int+ except Exception as e:+ logger.debug(f"get_rows_to_sync: Error: {e}. Using 0 as rows to sync", exc_info=e)+ capture_exception(e)+ return 0- return keys if len(keys) > 0 else None+ # ------------------------------------------------------------------+ # Pipeline build — the dlt `SourceResponse` for a single table+ # ------------------------------------------------------------------+ def build_pipeline(self, config: SnowflakeSourceConfig, inputs: SourceInputs) -> SourceResponse:+ table_name = inputs.schema_name+ if not table_name:+ raise ValueError("Table name is missing")-def snowflake_source(- account_id: str,- user: Optional[str],- password: Optional[str],- passphrase: Optional[str],- private_key: Optional[str],- auth_type: str,- database: str,- warehouse: str,- schema: str,- table_names: list[str],- should_use_incremental_field: bool,- logger: FilteringBoundLogger,- db_incremental_field_last_value: Optional[Any],- role: Optional[str] = None,- incremental_field: Optional[str] = None,- incremental_field_type: Optional[IncrementalFieldType] = None,-) -> SourceResponse:- table_name = table_names[0]- if not table_name:- raise ValueError("Table name is missing")-- with _get_connection(- account_id, user, password, passphrase, private_key, auth_type, database, warehouse, schema, role- ) as connection:- with connection.cursor() as cursor:- inner_query, inner_query_params = _build_query(- database,- schema,- table_name,- should_use_incremental_field,- incremental_field,- incremental_field_type,- db_incremental_field_last_value,- )- primary_keys = _get_primary_keys(cursor, database, schema, table_name)- rows_to_sync = _get_rows_to_sync(cursor, inner_query, inner_query_params, logger)+ database = config.database+ schema = config.schema+ logger = inputs.logger+ should_use_incremental_field = inputs.should_use_incremental_field+ incremental_field = inputs.incremental_field+ incremental_field_type = inputs.incremental_field_type+ db_incremental_field_last_value = inputs.db_incremental_field_last_value- def get_rows() -> Iterator[Any]:- with _get_connection(- account_id, user, password, passphrase, private_key, auth_type, database, warehouse, schema, role- ) as connection:+ with self.connect(config) as connection:with connection.cursor() as cursor:- query, params = _build_query(+ if cursor is None:+ raise Exception("Can't create cursor to Snowflake")+ inner_query, inner_query_params = _build_query(database,schema,table_name,@@ -444,13 +404,30 @@ def snowflake_source(incremental_field_type,db_incremental_field_last_value,)- logger.debug(f"Snowflake query: {query.format(params)}")- cursor.execute(query, params)-- # We cant control the batch size from snowflake when using the arrow function- # https://github.com/snowflakedb/snowflake-connector-python/issues/1712- yield from cursor.fetch_arrow_batches()-- name = NamingConvention.normalize_identifier(table_name)-- return SourceResponse(name=name, items=get_rows, primary_keys=primary_keys, rows_to_sync=rows_to_sync)+ primary_keys = self.get_primary_keys_for_table(cursor, database, schema, table_name)+ rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_params, logger)++ def get_rows() -> Iterator[Any]:+ with self.connect(config) as streaming_connection:+ with streaming_connection.cursor() as streaming_cursor:+ if streaming_cursor is None:+ raise Exception("Can't create cursor to Snowflake")+ query, params = _build_query(+ database,+ schema,+ table_name,+ should_use_incremental_field,+ incremental_field,+ incremental_field_type,+ db_incremental_field_last_value,+ )+ logger.debug(f"Snowflake query: {query.format(params)}")+ streaming_cursor.execute(query, params)++ # We cant control the batch size from snowflake when using the arrow function+ # https://github.com/snowflakedb/snowflake-connector-python/issues/1712+ yield from streaming_cursor.fetch_arrow_batches()++ name = NamingConvention.normalize_identifier(table_name)++ return SourceResponse(name=name, items=get_rows, primary_keys=primary_keys, rows_to_sync=rows_to_sync)diff --git a/posthog/temporal/data_imports/sources/snowflake/source.py b/posthog/temporal/data_imports/sources/snowflake/source.pyindex 246262bb346f..f9bee5510d70 100644--- a/posthog/temporal/data_imports/sources/snowflake/source.py+++ b/posthog/temporal/data_imports/sources/snowflake/source.py@@ -1,6 +1,5 @@from typing import Optional, cast-import structlogfrom snowflake.connector.errors import DatabaseError, ForbiddenError, ProgrammingErrorfrom posthog.schema import (@@ -13,20 +12,15 @@ from posthog.schema import ()from posthog.exceptions_capture import capture_exception-from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.sources.common.base import FieldTypefrom 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 SQLSourcefrom posthog.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig-from posthog.temporal.data_imports.sources.snowflake.snowflake import (- filter_snowflake_incremental_fields,- get_leading_clustering_columns_for_schemas as get_snowflake_leading_clustering_columns_for_schemas,- get_primary_keys_for_schemas as get_snowflake_primary_keys_for_schemas,- get_schemas as get_snowflake_schemas,- snowflake_source,-)+from posthog.temporal.data_imports.sources.snowflake.snowflake import SnowflakeImplementation++from products.data_warehouse.backend.types import ExternalDataSourceType-from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField+_SNOWFLAKE_IMPLEMENTATION = SnowflakeImplementation()SnowflakeErrors = {"No active warehouse selected in the current session": "No warehouse found for selected role",@@ -38,7 +32,11 @@ SnowflakeErrors = {@SourceRegistry.register-class SnowflakeSource(SimpleSource[SnowflakeSourceConfig]):+class SnowflakeSource(SQLSource[SnowflakeSourceConfig]):+ @property+ def get_implementation(self) -> SnowflakeImplementation:+ return _SNOWFLAKE_IMPLEMENTATION+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SNOWFLAKE@@ -189,59 +187,6 @@ class SnowflakeSource(SimpleSource[SnowflakeSourceConfig]):"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: SnowflakeSourceConfig,- team_id: int,- with_counts: bool = False,- names: list[str] | None = None,- force_refresh: bool = False,- ) -> list[SourceSchema]:- schemas = []-- db_schemas = get_snowflake_schemas(config, names=names)- try:- detected_pks = get_snowflake_primary_keys_for_schemas(- config=config,- table_names=list(db_schemas.keys()),- )- except Exception as e:- structlog.get_logger().warning("Failed to detect primary keys for Snowflake schemas", exc_info=e)- detected_pks = {}-- indexed_columns_by_table = get_snowflake_leading_clustering_columns_for_schemas(- config=config,- table_names=list(db_schemas.keys()),- )-- for table_name, columns in db_schemas.items():- incremental_field_tuples = filter_snowflake_incremental_fields(columns)- indexed_cols = indexed_columns_by_table.get(table_name) if indexed_columns_by_table is not None else None- incremental_fields: list[IncrementalField] = [- {- "label": field_name,- "type": field_type,- "field": field_name,- "field_type": field_type,- "nullable": nullable,- "is_indexed": True if indexed_cols is None else field_name in indexed_cols,- }- for field_name, field_type, nullable in incremental_field_tuples- ]-- schemas.append(- SourceSchema(- name=table_name,- supports_incremental=len(incremental_fields) > 0,- supports_append=len(incremental_fields) > 0,- incremental_fields=incremental_fields,- columns=columns,- detected_primary_keys=detected_pks.get(table_name),- )- )-- return schemas-def validate_credentials(self, config: SnowflakeSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:@@ -267,23 +212,3 @@ class SnowflakeSource(SimpleSource[SnowflakeSourceConfig]):return False, "Could not connect to Snowflake. Please check all connection details are valid."return True, None-- def source_for_pipeline(self, config: SnowflakeSourceConfig, inputs: SourceInputs) -> SourceResponse:- return snowflake_source(- account_id=config.account_id,- user=config.auth_type.user,- password=config.auth_type.password,- passphrase=config.auth_type.passphrase,- private_key=config.auth_type.private_key,- auth_type=config.auth_type.selection,- database=config.database,- warehouse=config.warehouse,- schema=config.schema,- role=config.role,- table_names=[inputs.schema_name],- should_use_incremental_field=inputs.should_use_incremental_field,- logger=inputs.logger,- incremental_field=inputs.incremental_field,- incremental_field_type=inputs.incremental_field_type,- db_incremental_field_last_value=inputs.db_incremental_field_last_value,- )diff --git a/posthog/temporal/data_imports/sources/snowflake/test_snowflake.py b/posthog/temporal/data_imports/sources/snowflake/test_snowflake.pydeleted file mode 100644index 3776d4e57d8a..000000000000--- a/posthog/temporal/data_imports/sources/snowflake/test_snowflake.py+++ /dev/null@@ -1,34 +0,0 @@-import pytest--from posthog.temporal.data_imports.sources.snowflake.snowflake import _parse_clustering_key_leading_column--- "clustering_key,expected",- [- # Snowflake stores clustering keys wrapped in LINEAR(...). Unquoted- # identifiers are uppercased to match the form Snowflake returns from- # INFORMATION_SCHEMA.COLUMNS — otherwise the source-level membership- # check `field_name in indexed_cols` misses on every clustering key- # that was written in lowercase.- ("LINEAR(created_at)", "CREATED_AT"),- ("LINEAR(created_at, user_id)", "CREATED_AT"),- ("LINEAR(CreatedAt)", "CREATEDAT"),- # Quoted identifiers preserve case sensitivity in Snowflake — strip the- # quotes and keep the case as-written.- ('LINEAR("CreatedAt", user_id)', "CreatedAt"),- ('LINEAR("created_at")', "created_at"),- # Older / non-LINEAR forms appear unwrapped in INFORMATION_SCHEMA.- ("created_at", "CREATED_AT"),- (" created_at ", "CREATED_AT"),- # Function expressions don't accelerate WHERE col >= … on the column- # they wrap, so we conservatively report no leading column.- ("LINEAR(DATE_TRUNC('day', created_at))", None),- # Empty / malformed inputs.- ("", None),- (None, None),- ("LINEAR(", None),- ],-)-def test_parse_clustering_key_leading_column(clustering_key, expected):- assert _parse_clustering_key_leading_column(clustering_key) == expecteddiff --git a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.pynew file mode 100644index 000000000000..996b057d9af8--- /dev/null+++ b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py@@ -0,0 +1,327 @@+import pytest+from unittest.mock import MagicMock, patch++from cryptography.hazmat.backends import default_backend+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig+from posthog.temporal.data_imports.sources.snowflake.snowflake import (+ SnowflakeImplementation,+ _build_query,+ _parse_clustering_key_leading_column,+ filter_snowflake_incremental_fields,+)++from products.data_warehouse.backend.types import IncrementalFieldType++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _generate_pem_key() -> str:+ """Generate a real PEM-encoded RSA key so `serialization.load_pem_private_key` succeeds."""+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())+ return key.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ ).decode("utf-8")+++def _make_config(auth_type: str = "password", **overrides) -> SnowflakeSourceConfig:+ auth: dict+ if auth_type == "password":+ auth = {"selection": "password", "user": "u", "password": "p"}+ else:+ auth = {+ "selection": "keypair",+ "user": "u",+ "private_key": _generate_pem_key(),+ "passphrase": "",+ }+ defaults: dict = {+ "account_id": "acc",+ "database": "DB",+ "warehouse": "WH",+ "schema": "PUBLIC",+ "role": "ROLE",+ "auth_type": auth,+ }+ defaults.update(overrides)+ return SnowflakeSourceConfig.from_dict(defaults)+++def _make_inputs(schema_name: str = "messages", **overrides) -> SourceInputs:+ defaults: dict = {+ "schema_name": schema_name,+ "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": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++# ---------------------------------------------------------------------------+# Module-level pure helpers+# ---------------------------------------------------------------------------+++ "clustering_key,expected",+ [+ # Snowflake stores clustering keys wrapped in LINEAR(...). Unquoted+ # identifiers are uppercased to match the form Snowflake returns from+ # INFORMATION_SCHEMA.COLUMNS — otherwise the source-level membership+ # check `field_name in indexed_cols` misses on every clustering key+ # that was written in lowercase.+ ("LINEAR(created_at)", "CREATED_AT"),+ ("LINEAR(created_at, user_id)", "CREATED_AT"),+ ("LINEAR(CreatedAt)", "CREATEDAT"),+ # Quoted identifiers preserve case sensitivity in Snowflake — strip the+ # quotes and keep the case as-written.+ ('LINEAR("CreatedAt", user_id)', "CreatedAt"),+ ('LINEAR("created_at")', "created_at"),+ # Older / non-LINEAR forms appear unwrapped in INFORMATION_SCHEMA.+ ("created_at", "CREATED_AT"),+ (" created_at ", "CREATED_AT"),+ # Function expressions don't accelerate WHERE col >= … on the column+ # they wrap, so we conservatively report no leading column.+ ("LINEAR(DATE_TRUNC('day', created_at))", None),+ # Empty / malformed inputs.+ ("", None),+ (None, None),+ ("LINEAR(", None),+ ],+)+def test_parse_clustering_key_leading_column(clustering_key, expected):+ assert _parse_clustering_key_leading_column(clustering_key) == expected+++class TestFilterIncrementalFields:+ @pytest.mark.parametrize(+ "data_type,expected",+ [+ ("TIMESTAMP_NTZ", IncrementalFieldType.Timestamp),+ ("timestamp_ltz", IncrementalFieldType.Timestamp),+ ("date", IncrementalFieldType.Date),+ ("datetime", IncrementalFieldType.DateTime),+ ("NUMBER", IncrementalFieldType.Numeric),+ ("numeric", IncrementalFieldType.Numeric),+ ],+ )+ def test_picks_up_supported_types(self, data_type, expected):+ out = filter_snowflake_incremental_fields([("c", data_type, True)])+ assert out == [("c", expected, True)]++ def test_drops_unsupported(self):+ assert filter_snowflake_incremental_fields([("c", "varchar", True)]) == []+++class TestBuildQuery:+ def test_incremental_requires_field(self):+ with pytest.raises(ValueError, match="incremental_field"):+ _build_query("DB", "PUBLIC", "t", True, None, None, None)++ def test_incremental_uses_operator_and_orders(self):+ sql, params = _build_query("DB", "PUBLIC", "t", True, "created_at", IncrementalFieldType.DateTime, "2025-01-01")+ assert "WHERE IDENTIFIER(%s)" in sql+ assert "ORDER BY IDENTIFIER(%s) ASC" in sql+ assert params == ("DB.PUBLIC.t", "created_at", "2025-01-01", "created_at")++ def test_incremental_seeds_initial_value_when_missing(self):+ # None last-value triggers fallback to incremental_type_to_initial_value+ _, params = _build_query("DB", "PUBLIC", "t", True, "created_at", IncrementalFieldType.DateTime, None)+ assert params[2] is not None+++# ---------------------------------------------------------------------------+# Implementation fixtures+# ---------------------------------------------------------------------------+++def impl() -> SnowflakeImplementation:+ return SnowflakeImplementation()+++def logger() -> MagicMock:+ return MagicMock()+++def cursor() -> MagicMock:+ c = MagicMock()+ c.__enter__.return_value = c+ c.fetchall.return_value = []+ c.fetchone.return_value = None+ return c+++# ---------------------------------------------------------------------------+# connect() — keypair auth passes DER bytes in-memory (no tempfile)+# ---------------------------------------------------------------------------+++class TestConnect:+ def test_keypair_passes_der_bytes_in_memory(self, impl):+ # Regression guard: the pre-refactor streaming path never wrote the+ # private key to disk. Make sure `connect()` matches it — DER bytes+ # via `private_key=`, no `private_key_file` kwarg.+ with patch("snowflake.connector.connect") as mock_connect:+ mock_connect.return_value.__enter__.return_value = MagicMock()+ with impl.connect(_make_config("keypair")):+ pass+ kwargs = mock_connect.call_args.kwargs+ assert "private_key_file" not in kwargs+ assert isinstance(kwargs["private_key"], bytes)+ # Sanity-check it's a DER-encoded PKCS8 blob the connector can parse.+ serialization.load_der_private_key(kwargs["private_key"], password=None, backend=default_backend())+++# ---------------------------------------------------------------------------+# Listing methods — they take a pre-opened connection+# ---------------------------------------------------------------------------+++def _conn_with_cursor(cursor: MagicMock) -> MagicMock:+ conn = MagicMock()+ conn.cursor.return_value = cursor+ return conn+++class TestGetColumns:+ def test_groups_columns_by_table(self, impl, cursor):+ cursor.fetchall.return_value = [+ ("users", "id", "NUMBER", "NO"),+ ("users", "email", "VARCHAR", "YES"),+ ("orders", "id", "NUMBER", "NO"),+ ]+ conn = _conn_with_cursor(cursor)+ result = impl.get_columns(conn, _make_config(), names=None)+ assert set(result.keys()) == {"users", "orders"}+ assert ("id", "NUMBER", False) in result["users"]+ assert ("email", "VARCHAR", True) in result["users"]++ def test_filters_by_names(self, impl, cursor):+ cursor.fetchall.return_value = [+ ("users", "id", "NUMBER", "NO"),+ ("orders", "id", "NUMBER", "NO"),+ ]+ conn = _conn_with_cursor(cursor)+ result = impl.get_columns(conn, _make_config(), names=["users"])+ assert list(result.keys()) == ["users"]+++class TestGetPrimaryKeys:+ def test_extracts_pk_column_names(self, impl, cursor):+ cursor.description = [MagicMock(name="column_name")]+ cursor.description[0].name = "column_name"+ cursor.__iter__.return_value = iter([("id",)])+ conn = _conn_with_cursor(cursor)+ out = impl.get_primary_keys(conn, _make_config(), tables=["t"])+ assert out["t"] == ["id"]++ def test_swallows_per_table_failure(self, impl, cursor):+ # Per-table failure leaves the None placeholder so schema discovery keeps going+ cursor.execute.side_effect = Exception("permission denied")+ conn = _conn_with_cursor(cursor)+ out = impl.get_primary_keys(conn, _make_config(), tables=["t"])+ assert out == {"t": None}+++class TestGetLeadingIndexColumns:+ def test_returns_leading_column_set_per_table(self, impl, cursor):+ cursor.__iter__.return_value = iter([("users", "LINEAR(created_at)"), ("orders", None)])+ conn = _conn_with_cursor(cursor)+ out = impl.get_leading_index_columns(conn, _make_config(), tables=["users", "orders"])+ assert out is not None+ assert out["users"] == {"CREATED_AT"}+ assert out["orders"] == set()++ def test_returns_none_on_failure(self, impl, cursor):+ # Discovery failure returns None so caller defaults to no warning+ cursor.execute.side_effect = Exception("perm")+ conn = _conn_with_cursor(cursor)+ assert impl.get_leading_index_columns(conn, _make_config(), tables=["t"]) is None+++# ---------------------------------------------------------------------------+# Per-cursor metadata methods+# ---------------------------------------------------------------------------+++class TestGetPrimaryKeysForTable:+ def test_returns_keys_when_present(self, impl, cursor):+ desc = MagicMock()+ desc.name = "column_name"+ cursor.description = [desc]+ cursor.__iter__.return_value = iter([("id",), ("email",)])+ assert impl.get_primary_keys_for_table(cursor, "DB", "PUBLIC", "t") == ["id", "email"]++ def test_raises_when_column_name_missing(self, impl, cursor):+ # Cursor description without `column_name` shouldn't silently return None — it's a Snowflake driver shape change worth surfacing.+ desc = MagicMock()+ desc.name = "something_else"+ cursor.description = [desc]+ with pytest.raises(ValueError, match="column_name"):+ impl.get_primary_keys_for_table(cursor, "DB", "PUBLIC", "t")+++class TestGetRowsToSync:+ def test_returns_count(self, impl, cursor, logger):+ cursor.fetchone.return_value = (321,)+ assert impl.get_rows_to_sync(cursor, "SELECT 1", (), logger) == 321++ def test_returns_zero_on_exception(self, impl, cursor, logger):+ # Sync must never bail because the COUNT(*) probe failed+ cursor.execute.side_effect = RuntimeError("boom")+ assert impl.get_rows_to_sync(cursor, "SELECT 1", (), logger) == 0+++# ---------------------------------------------------------------------------+# build_pipeline end-to-end (mocked driver)+# ---------------------------------------------------------------------------+++class TestBuildPipeline:+ def test_builds_source_response_and_streams(self, impl):+ # Two separate cursors: one for metadata pass, one for streaming.+ metadata_cursor = MagicMock()+ metadata_cursor.__enter__.return_value = metadata_cursor+ desc = MagicMock()+ desc.name = "column_name"+ metadata_cursor.description = [desc]+ metadata_cursor.__iter__.return_value = iter([("id",)])+ metadata_cursor.fetchone.return_value = (5,)++ streaming_cursor = MagicMock()+ streaming_cursor.__enter__.return_value = streaming_cursor+ streaming_cursor.fetch_arrow_batches.return_value = iter([b"batch-1", b"batch-2"])++ cursors = iter([metadata_cursor, streaming_cursor])++ def cursor_factory():+ return next(cursors)++ mock_connection = MagicMock()+ mock_connection.__enter__.return_value = mock_connection+ mock_connection.cursor.side_effect = cursor_factory++ with patch("snowflake.connector.connect", return_value=mock_connection):+ response = impl.build_pipeline(_make_config(), _make_inputs(schema_name="messages"))+ assert response.primary_keys == ["id"]+ assert response.rows_to_sync == 5+ assert list(response.items()) == [b"batch-1", b"batch-2"]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.pyindex ca2f0dc0f8a0..e31cabf56a01 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@@ -4,7 +4,7 @@ from typing import castfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, FuzzyInt-from unittest.mock import Mock, PropertyMock, patch+from unittest.mock import MagicMock, Mock, PropertyMock, patchfrom django.conf import settingsfrom django.test import override_settings@@ -4352,11 +4352,28 @@ class TestExternalDataSource(APIBaseTest):def test_snowflake_auth_type_create_and_update(self):"""Test that we can create and update the auth type for a Snowflake source"""- with patch(- "posthog.temporal.data_imports.sources.snowflake.source.get_snowflake_schemas"- ) as mocked_get_snowflake_schemas:- mocked_get_snowflake_schemas.return_value = {"my_table": [("something", "DATE", False)]}-+ with (+ patch(+ "posthog.temporal.data_imports.sources.snowflake.source.SnowflakeSource.validate_credentials",+ return_value=(True, None),+ ),+ patch(+ "posthog.temporal.data_imports.sources.snowflake.snowflake.SnowflakeImplementation.connect"+ ) as mocked_connect,+ patch(+ "posthog.temporal.data_imports.sources.snowflake.snowflake.SnowflakeImplementation.get_columns",+ return_value={"my_table": [("something", "DATE", False)]},+ ),+ patch(+ "posthog.temporal.data_imports.sources.snowflake.snowflake.SnowflakeImplementation.get_primary_keys",+ return_value={"my_table": None},+ ),+ patch(+ "posthog.temporal.data_imports.sources.snowflake.snowflake.SnowflakeImplementation.get_leading_index_columns",+ return_value={"my_table": set()},+ ),+ ):+ mocked_connect.return_value.__enter__.return_value = MagicMock()# Create a Snowflake source with password authresponse = self.client.post(f"/api/environments/{self.team.pk}/external_data_sources/",