:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Snowflake as a direct query source (#66303)
George Munyorob898ee8ca42e
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 8b39271c989a..efc0bbd73541 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -308,7 +308,7 @@ jobs:run: |prefix="products/warehouse_sources/backend/temporal/data_imports/sources/"# Space-separated, double-quoted, single line — parsed by the guard test.- coupled="common google_search_console mysql postgres salesforce stripe"+ coupled="common google_search_console mysql postgres salesforce snowflake stripe"only_sources=falseif [ -n "$BACKEND_FILES" ]; thenonly_sources=truediff --git a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsxindex 5adc3921da37..e0638b2b7796 100644--- a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx+++ b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx@@ -3,14 +3,16 @@ import { router } from 'kea-router'import { IconGear } from '@posthog/icons'-import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { LemonSelect, LemonSelectOption } from 'lib/lemon-ui/LemonSelect'import { newInternalTab } from 'lib/utils/newInternalTab'import { urls } from 'scenes/urls'import {ADD_MYSQL_DIRECT_CONNECTION,ADD_POSTGRES_DIRECT_CONNECTION,+ ADD_SNOWFLAKE_DIRECT_CONNECTION,CONFIGURE_SOURCES,+ type ConnectionSelectOption,POSTHOG_WAREHOUSE,connectionSelectorLogic,getConnectionSelectorValue,@@ -72,6 +74,11 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elemreturn}+ if (nextValue === ADD_SNOWFLAKE_DIRECT_CONNECTION) {+ router.actions.push(urls.dataWarehouseSourceNew('Snowflake', undefined, undefined, 'direct'))+ return+ }+if (nextValue === CONFIGURE_SOURCES) {router.actions.push(urls.sources())return@@ -88,20 +95,31 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.ElemsyncUrlWithQuery()}}options={connectionSelectOptions.map((group) => ({- options: group.options.map((option) => ({- ...option,- icon: option.iconSrc ? sourceIcon(option.iconSrc) : undefined,- sideAction: option.managementUrl- ? {- onClick: () => newInternalTab(option.managementUrl),- icon: <IconGear />,- tooltip: 'Open source settings',- 'aria-label': `Open settings for ${option.label}`,- 'data-attr': 'connection-selector-source-settings',- }- : undefined,- })),+ options: group.options.map(toLemonSelectOption),}))}/>)}++// A connection option is either a leaf (selectable `value`) or a node with nested `options` that+// LemonSelect renders as a submenu (e.g. "Add direct connection" → Postgres / MySQL / Snowflake).+function toLemonSelectOption(option: ConnectionSelectOption): LemonSelectOption<string> {+ const icon = option.iconSrc ? sourceIcon(option.iconSrc) : undefined+ if (option.options) {+ return { label: option.label, icon, options: option.options.map(toLemonSelectOption) }+ }+ return {+ value: option.value as string,+ label: option.label,+ icon,+ sideAction: option.managementUrl+ ? {+ onClick: () => newInternalTab(option.managementUrl),+ icon: <IconGear />,+ tooltip: 'Open source settings',+ 'aria-label': `Open settings for ${option.label}`,+ 'data-attr': 'connection-selector-source-settings',+ }+ : undefined,+ }+}diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.tsindex 623a34183eba..9abbc63d8b94 100644--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts@@ -10,6 +10,7 @@ import IconPostHog from 'public/posthog-icon.svg'import IconDuckDB from 'public/services/duckdb.svg'import IconMySQL from 'public/services/mysql.png'import IconPostgres from 'public/services/postgres.png'+import IconSnowflake from 'public/services/snowflake.png'import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'@@ -19,36 +20,41 @@ export const POSTHOG_WAREHOUSE = '__posthog_warehouse__'export const LOADING_CONNECTIONS = '__loading_connections__'export const ADD_POSTGRES_DIRECT_CONNECTION = '__add_postgres_direct_connection__'export const ADD_MYSQL_DIRECT_CONNECTION = '__add_mysql_direct_connection__'+export const ADD_SNOWFLAKE_DIRECT_CONNECTION = '__add_snowflake_direct_connection__'export const CONFIGURE_SOURCES = '__configure_sources__'export interface ConnectionSelectOption {- value: string+ // A leaf carries a `value`; a node carries nested `options` and renders as a submenu.+ value?: stringlabel: stringdisabled?: booleaniconSrc?: stringmanagementUrl?: string+ options?: ConnectionSelectOption[]}export interface ConnectionSelectOptionGroup {options: ConnectionSelectOption[]}-type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql'+type ConnectionEngine = 'duckdb' | 'postgres' | 'mysql' | 'snowflake'const ENGINE_LABELS: Record<ConnectionEngine, string> = {duckdb: 'DuckDB',postgres: 'Postgres',mysql: 'MySQL',+ snowflake: 'Snowflake',}const ENGINE_ICONS: Record<ConnectionEngine, string> = {duckdb: IconDuckDB,postgres: IconPostgres,mysql: IconMySQL,+ snowflake: IconSnowflake,}function getConnectionEngine(source: Pick<ExternalDataSourceConnectionOption, 'engine'>): ConnectionEngine {- if (source.engine === 'duckdb' || source.engine === 'mysql') {+ if (source.engine === 'duckdb' || source.engine === 'mysql' || source.engine === 'snowflake') {return source.engine}return 'postgres'@@ -127,8 +133,22 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([{options: [{ value: CONFIGURE_SOURCES, label: 'Configure sources' },- { value: ADD_POSTGRES_DIRECT_CONNECTION, label: '+ Add Postgres direct connection' },- { value: ADD_MYSQL_DIRECT_CONNECTION, label: '+ Add MySQL direct connection' },+ {+ label: 'Add direct connection',+ options: [+ {+ value: ADD_POSTGRES_DIRECT_CONNECTION,+ label: 'Postgres',+ iconSrc: IconPostgres,+ },+ { value: ADD_MYSQL_DIRECT_CONNECTION, label: 'MySQL', iconSrc: IconMySQL },+ {+ value: ADD_SNOWFLAKE_DIRECT_CONNECTION,+ label: 'Snowflake',+ iconSrc: IconSnowflake,+ },+ ],+ },],},]diff --git a/frontend/src/scenes/urls.test.ts b/frontend/src/scenes/urls.test.tsindex 62e1d5a4441e..b752a2218234 100644--- a/frontend/src/scenes/urls.test.ts+++ b/frontend/src/scenes/urls.test.ts@@ -5,7 +5,7 @@ describe('urls', () => {expect(urls.webAnalyticsRecap()).toEqual('/web/recap')})- it.each(['Postgres', 'MySQL'] as const)(+ it.each(['Postgres', 'MySQL', 'Snowflake'] as const)('includes direct access method when opening the new %s source wizard in direct mode',(sourceType) => {expect(urls.dataWarehouseSourceNew(sourceType, undefined, undefined, 'direct')).toEqual(diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 5eaba6262d14..01776b712f48 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -6071,7 +6071,7 @@ export interface ExternalDataSourceConnectionMetadata {export interface ExternalDataSourceConnectionOption {id: stringprefix: string | null- engine?: 'duckdb' | 'postgres' | 'mysql' | null+ engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | null}export interface ExternalDataSource {diff --git a/playwright/e2e/sql-editor-direct-postgres.spec.ts b/playwright/e2e/sql-editor-direct-postgres.spec.tsindex b02ddd128023..83200c01703b 100644--- a/playwright/e2e/sql-editor-direct-postgres.spec.ts+++ b/playwright/e2e/sql-editor-direct-postgres.spec.ts@@ -45,7 +45,8 @@ test.describe('SQL Editor direct Postgres queries', () => {const connectionSelector = page.getByRole('button', { name: /PostHog \(ClickHouse\)/ })await connectionSelector.click()- await page.getByRole('menuitem', { name: '+ Add postgres direct connection' }).click()+ await page.getByRole('menuitem', { name: 'Add direct connection' }).click()+ await page.getByRole('menuitem', { name: 'Postgres', exact: true }).click()await expect(page).toHaveURL(/.*\/data-warehouse\/new-source/)await expect(page).toHaveURL(/kind=Postgres/)diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.pyindex b81e96cc89c0..a1558742efa0 100644--- a/posthog/hogql/constants.py+++ b/posthog/hogql/constants.py@@ -48,7 +48,7 @@ BREAKDOWN_VALUES_LIMIT = 25BREAKDOWN_VALUES_LIMIT_FOR_COUNTRIES = 300BREAKDOWN_VALUE_MAX_LENGTH = 400-type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql"]+type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb", "mysql", "snowflake"]# All dialects that compile to an external SQL database queried directly (as opposed to# ClickHouse / HogQL). MySQL shares the standard-SQL keyword surface (CURRENT_DATE & co.)diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 88a31e6ff79f..d3caebeae981 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -1573,9 +1573,16 @@ class Database(BaseModel):# For a chain of type a.b.c, we want to create a nested table node# where a is the parent, b is the child of a, and c is the child of b- # where a.b.c will contain the table+ # where a.b.c will contain the table.+ # Snowflake stores identifiers uppercase but resolves them+ # case-insensitively, so mark its nodes so `from tpch_sf1.nation`+ # (any case) resolves to the canonical `TPCH_SF1.NATION`.warehouse_tables.add_child(- TableNode.create_nested_for_chain(table_chain, table_for_key),+ TableNode.create_nested_for_chain(+ table_chain,+ table_for_key,+ case_insensitive=table.external_data_source.is_direct_snowflake,+ ),table_conflict_mode=table_conflict_mode,)diff --git a/posthog/hogql/database/direct_snowflake_table.py b/posthog/hogql/database/direct_snowflake_table.pynew file mode 100644index 000000000000..cfb4652b4aac--- /dev/null+++ b/posthog/hogql/database/direct_snowflake_table.py@@ -0,0 +1,51 @@+from posthog.hogql.database.direct_sql_table import DirectSQLTable+from posthog.hogql.database.models import FieldOrTable+from posthog.hogql.errors import QueryError+from posthog.hogql.escape_sql import escape_snowflake_identifier+++class DirectSnowflakeTable(DirectSQLTable):+ snowflake_catalog: str | None = None+ snowflake_schema: str+ snowflake_table_name: str++ # Snowflake stores object names uppercase but resolves unquoted identifiers case-insensitively.+ # We quote every identifier (quoted names are case-sensitive in Snowflake), so resolve a HogQL+ # field to its canonically-cased column regardless of how the user typed it, then print that.+ def _canonical_field_key(self, name: str | int) -> str | None:+ target = str(name).lower()+ for key in self.fields:+ if key.lower() == target:+ return key+ return None++ def has_field(self, name: str | int) -> bool:+ return super().has_field(name) or self._canonical_field_key(name) is not None++ def get_field(self, name: str | int) -> FieldOrTable:+ if super().has_field(name):+ return super().get_field(name)+ key = self._canonical_field_key(name)+ if key is not None:+ return self.fields[key]+ return super().get_field(name)++ def to_printed_snowflake(self, context) -> str:+ if not self.snowflake_schema.strip():+ raise QueryError("Direct Snowflake tables require a schema name.")+ parts = []+ if self.snowflake_catalog:+ parts.append(escape_snowflake_identifier(self.snowflake_catalog))+ parts.extend(+ [+ escape_snowflake_identifier(self.snowflake_schema),+ escape_snowflake_identifier(self.snowflake_table_name),+ ]+ )+ return ".".join(parts)++ def to_printed_postgres(self, context) -> str:+ raise QueryError("Direct Snowflake tables cannot be printed into Postgres SQL")++ def to_printed_clickhouse(self, context) -> str:+ raise QueryError("Direct Snowflake tables cannot be printed into ClickHouse SQL")diff --git a/posthog/hogql/database/models.py b/posthog/hogql/database/models.pyindex 881267c609c5..47f54710397a 100644--- a/posthog/hogql/database/models.py+++ b/posthog/hogql/database/models.py@@ -274,6 +274,10 @@ class TableNode(BaseModel):# When True, the table is reachable by the resolver (so other tables can reference it# via subqueries) but is omitted from the SQL editor schema and autocomplete lists.hidden: bool = False+ # When True, this node may be reached by a case-insensitive name match (used for Snowflake,+ # which stores identifiers uppercase but resolves unquoted names case-insensitively). Only+ # opt-in nodes participate in the fallback, so ClickHouse/event tables stay exact-match.+ case_insensitive: bool = Falsedef __getstate__(self) -> dict[Any, Any]:return _slim_pickle_getstate(self)@@ -291,6 +295,19 @@ class TableNode(BaseModel):return self.table+ def _match_child(self, name: str) -> Optional["TableNode"]:+ child = self.children.get(name)+ if child is not None:+ return child+ # Fall back to a case-insensitive match, but only to children that opt in — keeps+ # ClickHouse/event tables exact-match while letting Snowflake schemas/tables resolve+ # the way Snowflake itself does (unquoted identifiers fold case).+ target = name.lower()+ for key, node in self.children.items():+ if node.case_insensitive and key.lower() == target:+ return node+ return None+# NOTE: This only returns True if the path we pass in# is a valid path to a child table - not just any path.def has_child(self, path: list[str]) -> bool:@@ -298,20 +315,22 @@ class TableNode(BaseModel):return self.table is not Nonefirst, *rest_of_path = path- if first not in self.children:+ child = self._match_child(first)+ if child is None:return False- return self.children[first].has_child(rest_of_path)+ return child.has_child(rest_of_path)def get_child(self, path: list[str]) -> "TableNode":if len(path) == 0:return selffirst, *rest_of_path = path- if first not in self.children:+ child = self._match_child(first)+ if child is None:raise ResolutionError(f"Unknown table `{first}`.")- return self.children[first].get_child(rest_of_path)+ return child.get_child(rest_of_path)def add_child(self,@@ -399,14 +418,14 @@ class TableNode(BaseModel):return names@staticmethod- def create_nested_for_chain(chain: list[str], table: Table) -> "TableNode":+ def create_nested_for_chain(chain: list[str], table: Table, *, case_insensitive: bool = False) -> "TableNode":assert len(chain) > 0# Create a deeply nested table node structure- start: TableNode = TableNode(name=chain[0])+ start: TableNode = TableNode(name=chain[0], case_insensitive=case_insensitive)current: TableNode = startfor name in chain[1:]:- child = TableNode(name=name)+ child = TableNode(name=name, case_insensitive=case_insensitive)current.add_child(child)current = childdiff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex 958dd04adc3a..947554ac0c55 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -35,9 +35,11 @@ from posthog.hogql.database.database import (get_data_warehouse_table_name,)from posthog.hogql.database.direct_postgres_table import DirectPostgresTable+from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.lazy_join_tags import FOREIGN_KEYfrom posthog.hogql.database.models import (DANGEROUS_NoTeamIdCheckTable,+ DatabaseField,ExpressionField,FieldTraverser,LazyJoin,@@ -965,6 +967,74 @@ class TestDatabase(BaseTest, QueryMatchingTest):# The schema came from the source's job_inputs, proving that branch ran during the zero-query build.assert direct_table.postgres_schema == "myschema"+ @patch("posthog.hogql.query.sync_execute", return_value=([], []))+ def test_build_from_sources_resolves_direct_snowflake_case_insensitively(self, patch_execute):+ # Snowflake stores object names uppercase but resolves unquoted identifiers case-insensitively.+ # A natural all-lowercase query must resolve to the canonical uppercase table and columns.+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="snowflake_source",+ source_type=ExternalDataSourceType.SNOWFLAKE,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"database": "DB", "schema": ""},+ )+ DataWarehouseTable.objects.create(+ name="TPCH_SF1.NATION",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ external_data_source_id=source.id,+ url_pattern="s3://test/*",+ options={+ "direct_snowflake_catalog": "DB",+ "direct_snowflake_schema": "TPCH_SF1",+ "direct_snowflake_table": "NATION",+ },+ columns={"N_NAME": {"clickhouse": "String", "hogql": "string"}},+ )++ sources = Database._fetch_sources(team=self.team, connection_id=str(source.id))+ db = Database._build_from_sources(sources)++ canonical = db.get_table("TPCH_SF1.NATION")+ assert isinstance(canonical, DirectSnowflakeTable)+ # Any-case table name resolves to the same direct table (Snowflake folds unquoted names).+ for typed_name in ("tpch_sf1.nation", "Tpch_Sf1.Nation", "TPCH_SF1.nation"):+ resolved = db.get_table(typed_name)+ assert isinstance(resolved, DirectSnowflakeTable), typed_name+ # Columns resolve regardless of case and report their canonical stored name.+ assert canonical.has_field("n_name")+ resolved_field = canonical.get_field("N_Name")+ assert isinstance(resolved_field, DatabaseField)+ assert resolved_field.name == "N_NAME"++ @patch("posthog.hogql.query.sync_execute", return_value=([], []))+ def test_build_from_sources_keeps_non_snowflake_tables_case_sensitive(self, patch_execute):+ # The case-insensitive fallback is opt-in per node, so a non-Snowflake direct table must NOT+ # resolve under a different case.+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="pg_source",+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"schema": "public"},+ )+ DataWarehouseTable.objects.create(+ name="accounts",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ external_data_source_id=source.id,+ url_pattern="s3://test/*",+ columns={"id": {"clickhouse": "Int64", "hogql": "integer"}},+ )++ sources = Database._fetch_sources(team=self.team, connection_id=str(source.id))+ db = Database._build_from_sources(sources)++ assert db.has_table("accounts")+ assert not db.has_table("ACCOUNTS")+@patch("posthog.hogql.query.sync_execute", return_value=([], []))def test_build_from_sources_raises_when_modifier_table_has_no_backing_row(self, patch_execute):# A dataWarehouseEventsModifier whose table resolves to a node with no backing row must faildiff --git a/posthog/hogql/direct_query_metrics.py b/posthog/hogql/direct_query_metrics.pynew file mode 100644index 000000000000..1d6b8a3c5b0f--- /dev/null+++ b/posthog/hogql/direct_query_metrics.py@@ -0,0 +1,60 @@+"""Prometheus metrics for direct-query execution.++Direct queries run against a customer's own database over the network, so their+latency and failure modes are independent of ClickHouse. These low-cardinality+metrics make per-dialect error and timeout rates observable without leaking+team-specific labels. The instrumentation is dialect-agnostic (the dialect is a+label); the Snowflake adapter is the only caller today.+"""++from __future__ import annotations++from collections.abc import Iterator+from contextlib import contextmanager+from time import perf_counter+from typing import Literal++from prometheus_client import (+ Counter as PromCounter,+ Histogram,+)++DirectQueryDialect = Literal["postgres", "mysql", "snowflake"]+DirectQueryStatus = Literal["success", "error"]++DIRECT_QUERY_TOTAL = PromCounter(+ "hogql_direct_query_total",+ "Direct external-database query executions by dialect and result.",+ labelnames=["dialect", "status"],+)+DIRECT_QUERY_DURATION_SECONDS = Histogram(+ "hogql_direct_query_duration_seconds",+ "Wall-clock duration of a direct external-database query execution.",+ labelnames=["dialect"],+ buckets=(0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),+)+DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL = PromCounter(+ "hogql_direct_query_row_cap_exceeded_total",+ "Direct queries rejected for exceeding the result-row cap, by dialect.",+ labelnames=["dialect"],+)+SNOWFLAKE_CONNECTION_CACHE_TOTAL = PromCounter(+ "hogql_snowflake_connection_cache_total",+ "Direct Snowflake connection-cache lookups by result (reused vs opened).",+ labelnames=["result"],+)+++@contextmanager+def observe_direct_query(dialect: DirectQueryDialect) -> Iterator[None]:+ """Record duration and success/error outcome for one direct-query execution."""+ started = perf_counter()+ status: DirectQueryStatus = "success"+ try:+ yield+ except Exception:+ status = "error"+ raise+ finally:+ DIRECT_QUERY_DURATION_SECONDS.labels(dialect=dialect).observe(perf_counter() - started)+ DIRECT_QUERY_TOTAL.labels(dialect=dialect, status=status).inc()diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.pyindex cc75836c09d2..77825a7c1808 100644--- a/posthog/hogql/direct_sql/__init__.py+++ b/posthog/hogql/direct_sql/__init__.py@@ -4,9 +4,11 @@ from posthog.hogql.direct_sql.mysql_adapter import MySQLAdapterfrom posthog.hogql.direct_sql.postgres_adapter import PostgresAdapterfrom posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statementfrom posthog.hogql.direct_sql.registry import get_adapter, register_adapter, registered_engines+from posthog.hogql.direct_sql.snowflake_adapter import SnowflakeAdapterregister_adapter(PostgresAdapter())register_adapter(MySQLAdapter())+register_adapter(SnowflakeAdapter())__all__ = ["DirectQueryRequest",@@ -14,6 +16,7 @@ __all__ = ["DirectSQLAdapter","PostgresAdapter","MySQLAdapter",+ "SnowflakeAdapter","direct_capable_source_types","is_direct_capable","ensure_single_direct_statement",diff --git a/posthog/hogql/direct_sql/snowflake_adapter.py b/posthog/hogql/direct_sql/snowflake_adapter.pynew file mode 100644index 000000000000..67016e74a2af--- /dev/null+++ b/posthog/hogql/direct_sql/snowflake_adapter.py@@ -0,0 +1,224 @@+import re+from typing import TYPE_CHECKING, cast++import sqlparse+import snowflake.connector+from opentelemetry import trace+from snowflake.connector.constants import FIELD_ID_TO_NAME+from sqlparse import tokens as sqlparse_tokens++from posthog.hogql.constants import HogQLDialect+from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_query+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.snowflake_connection_cache import cached_snowflake_connection++if TYPE_CHECKING:+ from posthog.models.team import Team++ from products.warehouse_sources.backend.facade.models import ExternalDataSource+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig+ from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake import (+ SnowflakeImplementation,+ )++DIRECT_SNOWFLAKE_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600+# Hard backstop against loading an unbounded result set into memory. Snowflake has no+# read-only transaction mode, so this guards a raw passthrough `SELECT * FROM huge_table`+# with no LIMIT. HogQL-authored queries already carry a LIMIT from the printer.+DIRECT_SNOWFLAKE_MAX_ROWS = 1_000_000+RAW_SNOWFLAKE_READ_ONLY_ERROR = "Raw Snowflake queries must be read-only SELECT statements."+RAW_SNOWFLAKE_BLOCKED_FUNCTION_ERROR = "This Snowflake function is not allowed in direct queries."++# Functions that parse as a plain SELECT but breach the read-only / session-isolation boundary,+# so the single-SELECT gate alone isn't enough. SYSTEM$* are admin / side-effecting (e.g.+# SYSTEM$CANCEL_QUERY); RESULT_SCAN + LAST_QUERY_ID can read another request's result set off a+# reused session. HogQL-authored SQL never emits these — only the raw passthrough path can — so+# block them there. Quoted identifiers tokenize as strings, not names, so a column legitimately+# named e.g. "result_scan" is unaffected.+_RAW_SNOWFLAKE_BLOCKED_FUNCTIONS = frozenset({"RESULT_SCAN", "LAST_QUERY_ID"})+DIRECT_SNOWFLAKE_ROW_CAP_ERROR = (+ f"Snowflake query returned more than {DIRECT_SNOWFLAKE_MAX_ROWS:,} rows. Add a LIMIT clause."+)++# A Snowflake account identifier is either the org-account form (`orgname-account_name`)+# or the legacy dotted form (`account.region.cloud`) — letters, digits, hyphens, underscores,+# and dots only. Rejecting anything else keeps a crafted value from steering the connector at+# an arbitrary host (the account is interpolated into the host it dials), closing the SSRF gap+# that host validation covers for the Postgres and MySQL adapters.+_SNOWFLAKE_ACCOUNT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")++# Snowflake's Python connector reports column types as integer codes in+# cursor.description[*].type_code, decoded to names via FIELD_ID_TO_NAME. Those names are+# Snowflake's *internal* vocabulary (FIXED/REAL/TEXT/…), not SQL type names — e.g.+# NUMBER/DECIMAL/INT all surface as FIXED, VARCHAR/CHAR as TEXT. FIXED is resolved separately+# (scale decides int vs decimal), so it's not here.+SNOWFLAKE_FIELD_NAME_TO_CLICKHOUSE_TYPE: dict[str, str] = {+ "REAL": "Float64",+ "TEXT": "String",+ "BOOLEAN": "Bool",+ "DATE": "Date",+ "TIME": "String",+ "TIMESTAMP": "DateTime64(6, 'UTC')",+ "TIMESTAMP_NTZ": "DateTime64(6, 'UTC')",+ "TIMESTAMP_LTZ": "DateTime64(6, 'UTC')",+ "TIMESTAMP_TZ": "DateTime64(6, 'UTC')",+ "VARIANT": "String",+ "OBJECT": "String",+ "ARRAY": "String",+ "MAP": "String",+ "BINARY": "String",+ "GEOGRAPHY": "String",+ "GEOMETRY": "String",+ "VECTOR": "String",+}+++def snowflake_field_type_to_clickhouse_type(type_code: object | None, scale: object | None = None) -> str:+ # type_code is the integer index into Snowflake's FIELD_ID_TO_NAME, taken from+ # cursor.description; a str(type_code) lookup never matches a name and silently types+ # every column as String.+ if not isinstance(type_code, int):+ return "String"+ name = FIELD_ID_TO_NAME.get(type_code, "")+ if name == "FIXED":+ # NUMBER/DECIMAL/INT all report as FIXED; scale 0 (or absent) is an integer.+ return "Decimal" if isinstance(scale, int) and scale > 0 else "Int64"+ return SNOWFLAKE_FIELD_NAME_TO_CLICKHOUSE_TYPE.get(name, "String")+++def snowflake_error_to_message(error: Exception) -> str:+ if isinstance(error, snowflake.connector.errors.Error):+ args = error.args+ if len(args) >= 2 and isinstance(args[1], str) and args[1].strip():+ return args[1].strip().splitlines()[0]+ message = str(error).strip()+ if not message:+ return "Snowflake query failed."+ return message.splitlines()[0]+++def validate_snowflake_account_id(account_id: str | None) -> str:+ candidate = (account_id or "").strip()+ if not candidate or not _SNOWFLAKE_ACCOUNT_ID_RE.fullmatch(candidate):+ raise ExposedHogQLError("Invalid Snowflake account identifier.")+ return candidate+++def ensure_read_only_raw_snowflake_statement(sql: str) -> str:+ sql = ensure_single_direct_statement(sql)+ statements = [statement for statement in sqlparse.parse(sql) if str(statement).strip(" \t\r\n;")]+ if len(statements) != 1 or statements[0].get_type() != "SELECT":+ raise ExposedHogQLError(RAW_SNOWFLAKE_READ_ONLY_ERROR)+ # Snowflake has no read-only session/transaction switch — the Postgres path sets+ # default_transaction_read_only on the connection, but Snowflake offers no equivalent. So+ # this single-read-only-SELECT gate is the enforcement boundary (backed at runtime by the+ # MULTI_STATEMENT_COUNT=1 session pin). As defense in depth, reject any DDL, or any DML+ # keyword other than SELECT, appearing anywhere in the statement — e.g. a write smuggled+ # into a subquery. String values and quoted identifiers aren't tagged DML/DDL, so a literal+ # or alias like 'DELETE' is unaffected.+ for token in statements[0].flatten():+ if token.ttype in sqlparse_tokens.DDL:+ raise ExposedHogQLError(RAW_SNOWFLAKE_READ_ONLY_ERROR)+ if token.ttype in sqlparse_tokens.DML and token.value.upper() != "SELECT":+ raise ExposedHogQLError(RAW_SNOWFLAKE_READ_ONLY_ERROR)+ if token.ttype in sqlparse_tokens.Name:+ name = token.value.upper()+ if name.startswith("SYSTEM$") or name in _RAW_SNOWFLAKE_BLOCKED_FUNCTIONS:+ raise ExposedHogQLError(RAW_SNOWFLAKE_BLOCKED_FUNCTION_ERROR)+ return sql+++def _fetch_capped_snowflake_rows(cursor: snowflake.connector.cursor.SnowflakeCursor) -> list:+ """Fetch up to the row cap, raising if the result would exceed it.++ Reads one row past the cap so the limit can be enforced without materializing the entire+ result set first.+ """+ rows = cursor.fetchmany(DIRECT_SNOWFLAKE_MAX_ROWS + 1)+ if len(rows) > DIRECT_SNOWFLAKE_MAX_ROWS:+ DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="snowflake").inc()+ raise ExposedHogQLError(DIRECT_SNOWFLAKE_ROW_CAP_ERROR)+ return list(rows)+++class SnowflakeAdapter:+ engine = "snowflake"+ dialect: HogQLDialect | None = "snowflake"++ def validate_source_config(+ self, source: "ExternalDataSource", team: "Team"+ ) -> tuple["SnowflakeImplementation", "SnowflakeSourceConfig"]:+ from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+ from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry+ from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.source import SnowflakeSource++ if not source.is_direct_snowflake:+ raise ExposedHogQLError("Invalid direct Snowflake connection.")++ snowflake_source = cast(SnowflakeSource, SourceRegistry.get_source(ExternalDataSourceType.SNOWFLAKE))+ config = snowflake_source.parse_config(source.job_inputs or {})++ # Snowflake has no host/SSH-tunnel config to validate (the Postgres/MySQL SSRF check),+ # but the account identifier flows into the host the connector dials, so it gets the+ # same scrutiny.+ validate_snowflake_account_id(config.account_id)++ return snowflake_source.get_implementation, config++ def prepare_raw_sql(self, sql: str) -> str:+ return ensure_read_only_raw_snowflake_statement(sql)++ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:+ """Execute a single read-only statement against the source's Snowflake account.++ Snowflake has no read-only session/transaction switch (the Postgres path sets+ default_transaction_read_only on the connection; there is no equivalent), so read-only+ is enforced our side: the statement is rejected unless it is a single read-only SELECT+ (`prepare_raw_sql`), HogQL-authored queries only ever emit SELECT, and the session pins+ MULTI_STATEMENT_COUNT=1 so the server refuses any stacked statement. A least-privilege+ SELECT-only role is recommended as defense in depth, but is not the boundary we rely on.+ """+ source = request.source+ snowflake_implementation, source_config = self.validate_source_config(source, request.team)+ settings = request.settings+ statement_timeout_seconds = max(+ settings.max_execution_time or DIRECT_SNOWFLAKE_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1+ )++ span = trace.get_current_span()+ span.set_attribute("team_id", request.team.pk)+ span.set_attribute("query_type", request.query_type)+ span.set_attribute("source_id", str(source.id))++ try:+ with request.timings.measure("snowflake_execute"), observe_direct_query("snowflake"):+ # Reuse a per-thread connection across queries — the auth handshake is the+ # dominant cost for interactive use.+ with cached_snowflake_connection(snowflake_implementation, source_config) as connection:+ with connection.cursor() as cursor:+ # Server-side backstop: refuse stacked statements regardless of the+ # connector default, so the single-statement parse gate can't be bypassed.+ cursor.execute("ALTER SESSION SET MULTI_STATEMENT_COUNT = 1")+ cursor.execute(f"ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS = {statement_timeout_seconds}")+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute+ request.sql, request.values or None+ )+ results = _fetch_capped_snowflake_rows(cursor)+ description = cursor.description or []+ except (snowflake.connector.errors.Error, ExposedHogQLError) as error:+ span.set_attribute("error_type", error.__class__.__name__)+ if request.debug:+ return DirectQueryResult(+ results=[], types=[], print_columns=[], error=snowflake_error_to_message(error)+ )+ raise ExposedHogQLError(snowflake_error_to_message(error)) from error++ span.set_attribute("row_count", len(results))+ types: list[tuple[str, str]] = [+ (column[0], snowflake_field_type_to_clickhouse_type(column[1], column[5] if len(column) > 5 else None))+ for column in description+ ]+ print_columns = [column[0] for column in description]+ return DirectQueryResult(results=results, types=types, print_columns=print_columns)diff --git a/posthog/hogql/direct_sql/test/test_registry_and_capability.py b/posthog/hogql/direct_sql/test/test_registry_and_capability.pyindex 6b0fb9857d6f..61bcd556f509 100644--- a/posthog/hogql/direct_sql/test/test_registry_and_capability.py+++ b/posthog/hogql/direct_sql/test/test_registry_and_capability.py@@ -19,12 +19,12 @@ class TestDirectSQLRegistry(SimpleTestCase):self.assertIsInstance(get_adapter("postgres"), PostgresAdapter)self.assertIsInstance(get_adapter("mysql"), MySQLAdapter)- @parameterized.expand([("none", None), ("unregistered", "snowflake")])+ @parameterized.expand([("none", None), ("unregistered", "bigquery")])def test_get_adapter_returns_none_for_unknown_engine(self, _name, engine):self.assertIsNone(get_adapter(engine))def test_registered_engines_includes_phase_one_engines(self):- self.assertEqual({"postgres", "mysql"}, set(registered_engines()))+ self.assertEqual({"postgres", "mysql", "snowflake"}, set(registered_engines()))def test_register_adapter_round_trips(self):class FakeAdapter:@@ -45,6 +45,7 @@ class TestDirectSQLCapability(SimpleTestCase):("postgres_synced_enabled", ExternalDataSourceType.POSTGRES, "warehouse", True, True),("postgres_synced_disabled", ExternalDataSourceType.POSTGRES, "warehouse", False, False),("mysql_synced_enabled", ExternalDataSourceType.MYSQL, "warehouse", True, True),+ ("snowflake_direct_ignores_toggle", ExternalDataSourceType.SNOWFLAKE, "direct", False, True),("unmapped_engine_synced", ExternalDataSourceType.STRIPE, "warehouse", True, False),("unmapped_engine_direct", ExternalDataSourceType.STRIPE, "direct", True, False),]@@ -59,6 +60,6 @@ class TestDirectSQLCapability(SimpleTestCase):def test_direct_capable_source_types(self):self.assertEqual(- {ExternalDataSourceType.POSTGRES, ExternalDataSourceType.MYSQL},+ {ExternalDataSourceType.POSTGRES, ExternalDataSourceType.MYSQL, ExternalDataSourceType.SNOWFLAKE},set(direct_capable_source_types()),)diff --git a/posthog/hogql/escape_sql.py b/posthog/hogql/escape_sql.pyindex ae7f19b071e6..fea9ffdf359c 100644--- a/posthog/hogql/escape_sql.py+++ b/posthog/hogql/escape_sql.py@@ -267,6 +267,15 @@ def escape_duckdb_identifier(v: str) -> str:return _quote_postgres_wire_identifier(v, extra_reserved_keywords=DUCKDB_EXTRA_RESERVED_KEYWORDS)+def escape_snowflake_identifier(v: str) -> str:+ # Always double-quote: Snowflake folds unquoted identifiers to uppercase, so quoting+ # preserves the column's stored case. ``%`` is rejected for parity with the other+ # parameterized direct-query escapers (the connector treats it as a placeholder).+ if "%" in v:+ raise QueryError(f'The Snowflake identifier "{v}" is not permitted as it contains the "%" character')+ return '"' + v.replace('"', '""') + '"'++def _quote_postgres_wire_identifier(v: str, extra_reserved_keywords: set[str] | None) -> str:# Reject ``%`` for parity with the HogQL and ClickHouse escape paths. psycopg# interprets ``%`` as the start of a parameter placeholder when scanning SQLdiff --git a/posthog/hogql/printer/__init__.py b/posthog/hogql/printer/__init__.pyindex 06fda3716b76..2fcfc3e78264 100644--- a/posthog/hogql/printer/__init__.py+++ b/posthog/hogql/printer/__init__.py@@ -4,6 +4,7 @@ from posthog.hogql.printer.duckdb import DuckDBPrinterfrom posthog.hogql.printer.hogql import HogQLPrinterfrom posthog.hogql.printer.mysql import MySQLPrinterfrom posthog.hogql.printer.postgres import PostgresPrinter+from posthog.hogql.printer.snowflake import SnowflakePrinterfrom posthog.hogql.printer.utils import (prepare_and_print_ast,prepare_ast_for_printing,@@ -22,4 +23,5 @@ __all__ = ["DuckDBPrinter","MySQLPrinter","PostgresPrinter",+ "SnowflakePrinter",]diff --git a/posthog/hogql/printer/hogql.py b/posthog/hogql/printer/hogql.pyindex 8961f315f88f..581cc4f3cad3 100644--- a/posthog/hogql/printer/hogql.py+++ b/posthog/hogql/printer/hogql.py@@ -15,6 +15,13 @@ class HogQLPrinter(BasePrinter):DIALECT_NAME: ClassVar[HogQLDialect] = "hogql"+ def _assert_qualify_supported(self) -> None:+ # QUALIFY is valid HogQL (the grammar and resolver support it), so the canonical+ # round-trip must print it back rather than reject — otherwise any query carrying a+ # QUALIFY clause fails when `query.py` renders `self.hogql` for the response, before+ # the target dialect ever runs.+ return+def visit_cte(self, node: ast.CTE) -> str:materialization_hint = ("" if node.materialized is None else ("MATERIALIZED " if node.materialized else "NOT MATERIALIZED ")diff --git a/posthog/hogql/printer/snowflake.py b/posthog/hogql/printer/snowflake.pynew file mode 100644index 000000000000..85d9f684d7dc--- /dev/null+++ b/posthog/hogql/printer/snowflake.py@@ -0,0 +1,328 @@+from collections.abc import Callable+from typing import ClassVar++from posthog.hogql import ast+from posthog.hogql.constants import HogQLDialect+from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTable+from posthog.hogql.database.models import DatabaseField+from posthog.hogql.errors import QueryError+from posthog.hogql.escape_sql import escape_snowflake_identifier+from posthog.hogql.printer.postgres import PostgresPrinter+from posthog.hogql.printer.snowflake_functions import (+ SNOWFLAKE_FUNCTION_HANDLERS_LOWER,+ SNOWFLAKE_FUNCTION_RENAMES_LOWER,+ SNOWFLAKE_PASSTHROUGH_FUNCTIONS,+)+from posthog.hogql.printer.types import JoinExprResponse++# Date parts accepted by dateDiff, inlined as a literal into DATEDIFF (allowlisted+# to keep the inlined value injection-safe).+_SNOWFLAKE_DATE_PARTS: frozenset[str] = frozenset(+ {"second", "minute", "hour", "day", "week", "month", "quarter", "year"}+)++# HogQL type names accepted by a `::` cast, mapped to Snowflake types. Mirrors the cast+# function handlers (toString → VARCHAR, toInt → BIGINT, …) so `x::String` and+# `toString(x)` agree. Unmapped names are rejected rather than emitted verbatim.+_SNOWFLAKE_CAST_TYPES: dict[str, str] = {+ "int": "BIGINT",+ "integer": "BIGINT",+ "int8": "BIGINT",+ "int16": "BIGINT",+ "int32": "BIGINT",+ "int64": "BIGINT",+ "uint8": "BIGINT",+ "uint16": "BIGINT",+ "uint32": "BIGINT",+ "uint64": "BIGINT",+ "float": "DOUBLE",+ "float32": "DOUBLE",+ "float64": "DOUBLE",+ "double": "DOUBLE",+ "real": "DOUBLE",+ "decimal": "DECIMAL",+ "numeric": "DECIMAL",+ "string": "VARCHAR",+ "text": "VARCHAR",+ "varchar": "VARCHAR",+ "char": "VARCHAR",+ "bool": "BOOLEAN",+ "boolean": "BOOLEAN",+ "date": "DATE",+ "datetime": "TIMESTAMP",+ "datetime64": "TIMESTAMP",+ "timestamp": "TIMESTAMP",+ "uuid": "VARCHAR",+}++# ClickHouse/strftime format specifier → Snowflake TO_CHAR format element.+_STRFTIME_TO_SNOWFLAKE: dict[str, str] = {+ "Y": "YYYY",+ "y": "YY",+ "m": "MM",+ "d": "DD",+ "H": "HH24",+ "I": "HH12",+ "M": "MI",+ "S": "SS",+ "p": "AM",+ "F": "YYYY-MM-DD",+ "T": "HH24:MI:SS",+ "R": "HH24:MI",+}+++class SnowflakePrinter(PostgresPrinter):+ """Prints a HogQL AST as Snowflake SQL."""++ DIALECT_NAME: ClassVar[HogQLDialect] = "snowflake"+ DIALECT_LABEL: ClassVar[str] = "Snowflake"++ def _print_table_sql(self, table) -> str:+ return self._print_table(table)++ def _print_table(self, table) -> str:+ if isinstance(table, DirectSnowflakeTable):+ return table.to_printed_snowflake(self.context)+ if hasattr(table, "to_printed_snowflake"):+ return table.to_printed_snowflake(self.context)+ return super()._print_table(table)++ def _print_identifier(self, name: str) -> str:+ # Always double-quote. The base (Postgres) printer leaves simple lowercase identifiers+ # unquoted, but Snowflake folds unquoted names to uppercase — an unquoted lowercase column+ # would read a different column than the one resolved. Quoting pins the exact name, matching+ # how table names are printed.+ return escape_snowflake_identifier(name)++ # --- PIVOT / UNPIVOT+ #+ # Snowflake's `PIVOT (agg(value) FOR col IN (...))` / `UNPIVOT (value FOR name IN (cols))`+ # reference their columns by bare, unqualified name — a table-qualified `t.col` is a syntax+ # error inside the clause. While rendering the clause body we flip `_in_pivot_clause` so fields+ # print as their bare (still quoted) column name; the source table itself prints normally.++ _in_pivot_clause: bool = False++ def visit_field_type(self, type: ast.FieldType) -> str:+ if self._in_pivot_clause:+ resolved = type.resolve_database_field(self.context)+ name = resolved.name if isinstance(resolved, DatabaseField) else type.name+ return self._print_identifier(name)+ return super().visit_field_type(type)++ def _render_pivot_source(self, table: ast.Expr) -> str:+ if isinstance(table, ast.JoinExpr):+ return self._print_join_expr_chain(table)+ rendered = self.visit(table)+ return rendered.printed_sql if isinstance(rendered, JoinExprResponse) else rendered++ def visit_pivot_expr(self, node: ast.PivotExpr) -> str:+ if node.group_by:+ raise QueryError(f"PIVOT with an explicit GROUP BY is not supported {self._dialect_error_suffix()}.")+ table = self._render_pivot_source(node.table)+ previous, self._in_pivot_clause = self._in_pivot_clause, True+ try:+ aggregates = ", ".join(self.visit(agg) for agg in node.aggregates)+ columns = " ".join(self.visit(col) for col in node.columns)+ finally:+ self._in_pivot_clause = previous+ return f"{table} PIVOT ({aggregates} FOR {columns})"++ def visit_unpivot_expr(self, node: ast.UnpivotExpr) -> str:+ table = self._render_pivot_source(node.table)+ include_nulls = "INCLUDE NULLS " if node.include_nulls else ""+ previous, self._in_pivot_clause = self._in_pivot_clause, True+ try:+ columns = " ".join(self.visit(col) for col in node.columns)+ finally:+ self._in_pivot_clause = previous+ return f"{table} UNPIVOT {include_nulls}({columns})"++ # --- Function Calls++ def _get_function_renames(self) -> dict[str, str]:+ return SNOWFLAKE_FUNCTION_RENAMES_LOWER++ def _get_function_handlers(self) -> dict[str, Callable[[list[str]], str]]:+ return SNOWFLAKE_FUNCTION_HANDLERS_LOWER++ def _get_passthrough_functions(self) -> frozenset[str]:+ return SNOWFLAKE_PASSTHROUGH_FUNCTIONS++ # --- ClickHouse-only SELECT clauses+ #+ # The inherited (base) visit_select_query emits these verbatim; Snowflake has no+ # equivalent, so reject loudly rather than emit SQL Snowflake can't run.++ def visit_select_query(self, node: ast.SelectQuery) -> str:+ if node.array_join_op is not None:+ raise QueryError(f"ARRAY JOIN is not supported {self._dialect_error_suffix()}.")+ if node.prewhere is not None:+ raise QueryError(f"PREWHERE is not supported {self._dialect_error_suffix()}.")+ if node.limit_by is not None:+ raise QueryError(f"LIMIT BY is not supported {self._dialect_error_suffix()}; use QUALIFY ROW_NUMBER().")+ return super().visit_select_query(node)++ def visit_sample_expr(self, node: ast.SampleExpr) -> str:+ # SAMPLE hangs off the table (JoinExpr), so reject it here rather than in the select query.+ raise QueryError(f"SAMPLE is not supported {self._dialect_error_suffix()}.")++ # --- Operators and literals+ #+ # Snowflake has no `~` regex operators, `[...]` array / `{...}` object literals, scalar+ # tuples, or `[a:b]` slices — translate the ones with a clean equivalent and reject the rest.++ def _get_compare_op(self, op: ast.CompareOperationOp, left: str, right: str) -> str:+ # match()-style "found anywhere" semantics (REGEXP_INSTR != 0), consistent with the+ # `match` function handler. The 6th arg 'i' makes the case-insensitive variants ignore case.+ if op == ast.CompareOperationOp.Regex:+ return f"(REGEXP_INSTR({left}, {right}) != 0)"+ if op == ast.CompareOperationOp.NotRegex:+ return f"(REGEXP_INSTR({left}, {right}) = 0)"+ if op == ast.CompareOperationOp.IRegex:+ return f"(REGEXP_INSTR({left}, {right}, 1, 1, 0, 'i') != 0)"+ if op == ast.CompareOperationOp.NotIRegex:+ return f"(REGEXP_INSTR({left}, {right}, 1, 1, 0, 'i') = 0)"+ return super()._get_compare_op(op, left, right)++ def visit_type_cast(self, node: ast.TypeCast) -> str:+ target = _SNOWFLAKE_CAST_TYPES.get(node.type_name.lower())+ if target is None:+ raise QueryError(f"Unsupported cast to type '{node.type_name}' {self._dialect_error_suffix()}.")+ return f"CAST({self.visit(node.expr)} AS {target})"++ def visit_array(self, node: ast.Array) -> str:+ return f"ARRAY_CONSTRUCT({', '.join(self.visit(expr) for expr in node.exprs)})"++ def visit_tuple(self, node: ast.Tuple) -> str:+ # HogQL lowers `{...}` object literals to a tagged tuple+ # (`'__hx_tag', '__hx_obj', key, value, …`) before printing — emit those as a+ # Snowflake OBJECT. Genuine scalar tuples have no Snowflake type, so reject them.+ exprs = node.exprs+ if (+ len(exprs) >= 2+ and isinstance(exprs[0], ast.Constant)+ and exprs[0].value == "__hx_tag"+ and isinstance(exprs[1], ast.Constant)+ and exprs[1].value == "__hx_obj"+ ):+ return f"OBJECT_CONSTRUCT({', '.join(self.visit(expr) for expr in exprs[2:])})"+ raise QueryError(f"Tuple expressions are not supported {self._dialect_error_suffix()}.")++ def visit_array_slice(self, node: ast.ArraySlice) -> str:+ raise QueryError(f"Array slices are not supported {self._dialect_error_suffix()}; use ARRAY_SLICE().")++ def visit_call(self, node: ast.Call) -> str:+ # dateDiff / formatDateTime can't be plain handlers: their first argument+ # (date part / format string) must be inlined as a literal, but by the time+ # a handler runs it has already been bound as a parameter. Intercept here,+ # where the raw AST Constant is still available.+ name = node.name.lower()+ if name == "datediff":+ return self._visit_date_diff(node)+ if name == "formatdatetime":+ return self._visit_format_datetime(node)+ return super().visit_call(node)++ def _visit_date_diff(self, node: ast.Call) -> str:+ if len(node.args) != 3:+ raise QueryError(f"dateDiff expects exactly 3 arguments {self._dialect_error_suffix()}.")+ unit_node = node.args[0]+ if not (isinstance(unit_node, ast.Constant) and isinstance(unit_node.value, str)):+ raise QueryError(f"dateDiff requires a literal unit {self._dialect_error_suffix()}.")+ unit = unit_node.value.lower()+ if unit not in _SNOWFLAKE_DATE_PARTS:+ raise QueryError(f"Unsupported dateDiff unit '{unit}' {self._dialect_error_suffix()}.")+ start = self.visit(node.args[1])+ end = self.visit(node.args[2])+ return f"DATEDIFF('{unit}', {start}, {end})"++ def _visit_format_datetime(self, node: ast.Call) -> str:+ if len(node.args) != 2:+ raise QueryError(f"formatDateTime expects exactly 2 arguments {self._dialect_error_suffix()}.")+ format_node = node.args[1]+ if not (isinstance(format_node, ast.Constant) and isinstance(format_node.value, str)):+ raise QueryError(f"formatDateTime requires a literal format string {self._dialect_error_suffix()}.")+ snowflake_format = self._translate_strftime_format(format_node.value)+ time_sql = self.visit(node.args[0])+ # The format is inlined into a single-quoted SQL literal, so any `'` it carries (a literal+ # quote the user escaped as `''` in HogQL) must be re-escaped as `''` — otherwise it closes+ # the string early, breaking the query or allowing injection.+ escaped_format = snowflake_format.replace("'", "''")+ return f"TO_CHAR({time_sql}, '{escaped_format}')"++ def _translate_strftime_format(self, fmt: str) -> str:+ # Translate ClickHouse/strftime %-specifiers to Snowflake TO_CHAR elements.+ # Literal runs containing letters are double-quoted so Snowflake doesn't+ # parse them as format elements.+ out: list[str] = []+ literal: list[str] = []++ def flush_literal() -> None:+ if not literal:+ return+ text = "".join(literal)+ literal.clear()+ # Letters would be read as format elements, and a literal double-quote would+ # open a quoted section — both must sit inside a quoted block, with `"` escaped+ # as `""` rather than dropped.+ if any(ch.isalpha() or ch == '"' for ch in text):+ out.append('"' + text.replace('"', '""') + '"')+ else:+ out.append(text)++ index = 0+ while index < len(fmt):+ char = fmt[index]+ if char != "%":+ literal.append(char)+ index += 1+ continue+ if index + 1 >= len(fmt):+ raise QueryError(f"Trailing '%' in formatDateTime format {self._dialect_error_suffix()}.")+ specifier = fmt[index + 1]+ if specifier == "%":+ literal.append("%")+ elif specifier in _STRFTIME_TO_SNOWFLAKE:+ flush_literal()+ out.append(_STRFTIME_TO_SNOWFLAKE[specifier])+ else:+ raise QueryError(f"Unsupported formatDateTime specifier '%{specifier}' {self._dialect_error_suffix()}.")+ index += 2+ flush_literal()+ return "".join(out)++ # --- Date truncation (toStartOf*)+ #+ # The inherited _visit_to_start_of_call dispatch (arg validation, week-mode+ # selection) is fine; only the rendering differs. Postgres emits make_date()+ # for ISO year and `n * interval` for minute buckets — neither exists / works+ # in Snowflake.++ def _render_start_of(self, unit: str, arg: str, week_mode: int = 3) -> str:+ if unit == "week":+ # DAYOFWEEKISO (Mon=1 … Sun=7) ignores the WEEK_START session param, so+ # the boundary is deterministic regardless of account configuration.+ if week_mode in {1, 3}: # ISO / Monday-start+ return f"DATE_TRUNC('day', DATEADD('day', 1 - DAYOFWEEKISO({arg}), {arg}))"+ if week_mode == 0: # Sunday-start+ return f"DATE_TRUNC('day', DATEADD('day', -(DAYOFWEEKISO({arg}) % 7), {arg}))"+ raise QueryError(f"Unsupported toStartOfWeek mode `{week_mode}` {self._dialect_error_suffix()}.")+ if unit == "isoyear":+ # Jan 4 is always in ISO week 1; the Monday of its week is the ISO year start.+ jan4 = f"DATE_FROM_PARTS(YEAROFWEEKISO({arg}), 1, 4)"+ return f"DATEADD('day', 1 - DAYOFWEEKISO({jan4}), {jan4})"+ return f"DATE_TRUNC('{unit}', {arg})"++ def _render_minute_bucket(self, arg: str, bucket_size: int) -> str:+ return f"TIME_SLICE({arg}, {bucket_size}, 'MINUTE')"++ # --- CTEs++ def visit_cte(self, node: ast.CTE):+ if node.materialized is not None:+ raise QueryError("MATERIALIZED CTE hints are not supported in the Snowflake dialect")+ if node.using_key is not None:+ raise QueryError("USING KEY is not supported in the Snowflake dialect")+ return super().visit_cte(node)diff --git a/posthog/hogql/printer/snowflake_functions.py b/posthog/hogql/printer/snowflake_functions.pynew file mode 100644index 000000000000..d0d8f7c4e280--- /dev/null+++ b/posthog/hogql/printer/snowflake_functions.py@@ -0,0 +1,361 @@+from collections.abc import Callable++from posthog.hogql.printer.postgres_functions import (+ _handle_e,+ _handle_empty,+ _handle_ends_with,+ _handle_if,+ _handle_is_not_null,+ _handle_is_null,+ _handle_log2,+ _handle_multi_if,+ _handle_noop,+ _handle_not_empty,+ _handle_to_last_day_of_week,+ _handle_to_yyyymm,+ _handle_to_yyyymmdd,+ _handle_to_yyyymmddhhmmss,+ _handle_today,+ _handle_uniq,+ _handle_yesterday,+ _make_cast_handler,+ _make_date_trunc_handler,+ _make_extract_handler,+)++# Snowflake function maps. Unlike MySQL/Postgres-direct, the Snowflake printer does+# NOT fall back to the Postgres maps — these are the complete surface. Anything not+# in a rename, handler, or passthrough raises "not supported in the Snowflake+# dialect". Handlers that emit standard SQL valid in Snowflake are imported from+# postgres_functions; the rest are defined here.+#+# NOTE: dateDiff and formatDateTime are NOT here — their first argument (the date+# part / format string) must be inlined as a literal, not bound as a parameter, so+# they are intercepted in SnowflakePrinter.visit_call where the raw AST is available.++# Simple 1:1 name swaps (args unchanged). ClickHouse/HogQL name → Snowflake name.+SNOWFLAKE_FUNCTION_RENAMES: dict[str, str] = {+ "ifNull": "COALESCE",+ "groupArray": "ARRAY_AGG",+ "fromUnixTimestamp": "TO_TIMESTAMP", # Snowflake reads a bare number as seconds+ "replaceAll": "REPLACE",+ "replaceRegexpAll": "REGEXP_REPLACE", # Snowflake replaces all occurrences by default+ "arrayStringConcat": "ARRAY_TO_STRING",+ "toTypeName": "TYPEOF",+ "any": "MIN", # no arbitrary-value aggregate; MIN is the portable fallback+ "startsWith": "STARTSWITH", # Postgres uses starts_with; Snowflake's builtin has no underscore+ "now": "CURRENT_TIMESTAMP", # Snowflake has no NOW()+ "pow": "POWER", # Snowflake has POWER, not POW+}+++# --- Date arithmetic: Snowflake cannot multiply an INTERVAL, so use DATEADD. ---+++def _make_dateadd_handler(unit: str, negate: bool = False) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ amount = f"-({args[1]})" if negate else args[1]+ return f"DATEADD('{unit}', {amount}, {args[0]})"++ return handler+++def _make_snowflake_interval_handler(unit: str) -> Callable[[list[str]], str]:+ # Snowflake interval literals can't be parameterized or built from an+ # expression — the count must be a literal. Fine for the common toIntervalX(7)+ # case; a non-literal argument produces SQL Snowflake will reject.+ def handler(args: list[str]) -> str:+ return f"INTERVAL '{args[0]} {unit}'"++ return handler+++def _handle_to_last_day_of_month(args: list[str]) -> str:+ return f"CAST(LAST_DAY({args[0]}) AS DATE)"+++def _handle_to_unix_timestamp(args: list[str]) -> str:+ return f"CAST(DATE_PART('epoch_second', {args[0]}) AS BIGINT)"+++# --- JSON: Snowflake reads semi-structured data via PARSE_JSON + bracket paths. ---+++def _snowflake_json_path(args: list[str]) -> str:+ # args = (json, key1, key2, ...). Bracket access accepts an expression key, so+ # the bound key params work; chaining walks nested objects/arrays.+ expr = f"PARSE_JSON({args[0]})"+ for key in args[1:]:+ expr = f"{expr}[{key}]"+ return expr+++def _make_json_extract_cast_handler(snowflake_type: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ return f"CAST({_snowflake_json_path(args)} AS {snowflake_type})"++ return handler+++def _handle_json_extract_raw(args: list[str]) -> str:+ return _snowflake_json_path(args)+++def _handle_json_length(args: list[str]) -> str:+ return f"ARRAY_SIZE(PARSE_JSON({args[0]}))"+++# --- Strings ---+++def _handle_match(args: list[str]) -> str:+ # ClickHouse match() is a partial (search) match; Snowflake REGEXP_LIKE is+ # whole-string, so use REGEXP_INSTR != 0 to preserve "found anywhere" semantics.+ return f"(REGEXP_INSTR({args[0]}, {args[1]}) != 0)"+++def _handle_split_by(args: list[str]) -> str:+ # splitByString(sep, str) / splitByChar(sep, str) → SPLIT(str, sep) — args swap+ return f"SPLIT({args[1]}, {args[0]})"+++def _handle_replace_one(args: list[str]) -> str:+ # Snowflake REGEXP_REPLACE replaces all by default; position=1, occurrence=1+ # restricts it to the first match (matching replaceOne/replaceRegexpOne).+ return f"REGEXP_REPLACE({args[0]}, {args[1]}, {args[2]}, 1, 1)"+++# --- Math ---+++def _handle_rand(args: list[str]) -> str:+ # Snowflake RANDOM() returns a signed integer; UNIFORM gives the [0,1) float+ # the Postgres backend's random() rename produced.+ return "UNIFORM(0::float, 1::float, RANDOM())"+++def _handle_log10(args: list[str]) -> str:+ return f"LOG(10, {args[0]})"+++def _handle_log(args: list[str]) -> str:+ # HogQL log() is natural log; Snowflake LOG requires a base, so use LN.+ return f"LN({args[0]})"+++# --- Aggregate *If combinators: Snowflake has no FILTER (WHERE) clause. ---+++def _make_agg_if_handler(snowflake_fn: str) -> Callable[[list[str]], str]:+ def handler(args: list[str]) -> str:+ *agg_args, condition = args+ return f"{snowflake_fn}(CASE WHEN {condition} THEN {', '.join(agg_args)} END)"++ return handler+++def _handle_count(args: list[str]) -> str:+ # HogQL's argless count() means "count all rows", but Snowflake rejects a bare COUNT() —+ # it must be COUNT(*). count(expr) passes through unchanged.+ return "count(*)" if not args else f"count({', '.join(args)})"+++def _handle_count_if(args: list[str]) -> str:+ if len(args) == 1:+ return f"COUNT_IF({args[0]})"+ return f"COUNT(CASE WHEN {args[1]} THEN {args[0]} END)"+++def _handle_uniq_if(args: list[str]) -> str:+ *agg_args, condition = args+ return f"COUNT(DISTINCT CASE WHEN {condition} THEN {', '.join(agg_args)} END)"+++# Functions needing custom rendering: lowercased-name → callable(rendered_args) → SQL.+SNOWFLAKE_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {+ # Type conversions (Snowflake type synonyms; no UUID type → VARCHAR)+ "toDate": _make_cast_handler("DATE"),+ "toDateTime": _make_cast_handler("TIMESTAMP"),+ "toDateTime64": _make_cast_handler("TIMESTAMP"),+ "toString": _make_cast_handler("VARCHAR"),+ "toInt": _make_cast_handler("BIGINT"),+ "toIntOrZero": _make_cast_handler("BIGINT"),+ "toFloat": _make_cast_handler("DOUBLE"),+ "toFloatOrZero": _make_cast_handler("DOUBLE"),+ "toFloatOrDefault": _make_cast_handler("DOUBLE"),+ "toBool": _make_cast_handler("BOOLEAN"),+ "toDecimal": _make_cast_handler("DECIMAL"),+ "toUUID": _make_cast_handler("VARCHAR"),+ # Date extraction (Snowflake's EXTRACT unit names differ from Postgres')+ "toYear": _make_extract_handler("YEAR"),+ "toQuarter": _make_extract_handler("QUARTER"),+ "toMonth": _make_extract_handler("MONTH"),+ "toDayOfMonth": _make_extract_handler("DAY"),+ "toDayOfWeek": _make_extract_handler("dayofweekiso"),+ "toDayOfYear": _make_extract_handler("dayofyear"),+ "toHour": _make_extract_handler("HOUR"),+ "toMinute": _make_extract_handler("MINUTE"),+ "toSecond": _make_extract_handler("SECOND"),+ "toISOWeek": _make_extract_handler("weekiso"),+ "toISOYear": _make_extract_handler("yearofweekiso"),+ "toUnixTimestamp": _handle_to_unix_timestamp,+ # Date formatting to integers+ "toYYYYMM": _handle_to_yyyymm,+ "toYYYYMMDD": _handle_to_yyyymmdd,+ "toYYYYMMDDhhmmss": _handle_to_yyyymmddhhmmss,+ # Date truncation (WEEK_START session param governs week boundaries)+ "toMonday": _make_date_trunc_handler("week", cast_to_date=True),+ "toLastDayOfMonth": _handle_to_last_day_of_month,+ "toLastDayOfWeek": _handle_to_last_day_of_week,+ # Date generators+ "today": _handle_today,+ "yesterday": _handle_yesterday,+ # Intervals+ "toIntervalSecond": _make_snowflake_interval_handler("second"),+ "toIntervalMinute": _make_snowflake_interval_handler("minute"),+ "toIntervalHour": _make_snowflake_interval_handler("hour"),+ "toIntervalDay": _make_snowflake_interval_handler("day"),+ "toIntervalWeek": _make_snowflake_interval_handler("week"),+ "toIntervalMonth": _make_snowflake_interval_handler("month"),+ "toIntervalQuarter": _make_snowflake_interval_handler("quarter"),+ "toIntervalYear": _make_snowflake_interval_handler("year"),+ # Date arithmetic+ "addSeconds": _make_dateadd_handler("second"),+ "addMinutes": _make_dateadd_handler("minute"),+ "addHours": _make_dateadd_handler("hour"),+ "addDays": _make_dateadd_handler("day"),+ "addWeeks": _make_dateadd_handler("week"),+ "addMonths": _make_dateadd_handler("month"),+ "addQuarters": _make_dateadd_handler("quarter"),+ "addYears": _make_dateadd_handler("year"),+ "subtractSeconds": _make_dateadd_handler("second", negate=True),+ "subtractMinutes": _make_dateadd_handler("minute", negate=True),+ "subtractHours": _make_dateadd_handler("hour", negate=True),+ "subtractDays": _make_dateadd_handler("day", negate=True),+ "subtractWeeks": _make_dateadd_handler("week", negate=True),+ "subtractMonths": _make_dateadd_handler("month", negate=True),+ "subtractQuarters": _make_dateadd_handler("quarter", negate=True),+ "subtractYears": _make_dateadd_handler("year", negate=True),+ # Conditional+ "if": _handle_if,+ "multiIf": _handle_multi_if,+ # Null / empty+ "empty": _handle_empty,+ "notEmpty": _handle_not_empty,+ "isNull": _handle_is_null,+ "isNotNull": _handle_is_not_null,+ "assumeNotNull": _handle_noop,+ "toNullable": _handle_noop,+ # JSON+ "JSONExtractString": _make_json_extract_cast_handler("VARCHAR"),+ "JSONExtractRaw": _handle_json_extract_raw,+ "JSONExtractArrayRaw": _handle_json_extract_raw,+ "JSONExtractInt": _make_json_extract_cast_handler("INTEGER"),+ "JSONExtractUInt": _make_json_extract_cast_handler("INTEGER"),+ "JSONExtractFloat": _make_json_extract_cast_handler("DOUBLE"),+ "JSONExtractBool": _make_json_extract_cast_handler("BOOLEAN"),+ "JSONLength": _handle_json_length,+ # String+ "match": _handle_match,+ "splitByString": _handle_split_by,+ "splitByChar": _handle_split_by,+ "endsWith": _handle_ends_with,+ "replaceOne": _handle_replace_one,+ "replaceRegexpOne": _handle_replace_one,+ # Math+ "e": _handle_e,+ "log2": _handle_log2,+ "log10": _handle_log10,+ "log": _handle_log,+ "rand": _handle_rand,+ # Aggregation+ "uniq": _handle_uniq,+ "uniqExact": _handle_uniq,+ "count": _handle_count,+ "countIf": _handle_count_if,+ "sumIf": _make_agg_if_handler("SUM"),+ "avgIf": _make_agg_if_handler("AVG"),+ "minIf": _make_agg_if_handler("MIN"),+ "maxIf": _make_agg_if_handler("MAX"),+ "anyIf": _make_agg_if_handler("MIN"),+ "groupArrayIf": _make_agg_if_handler("ARRAY_AGG"),+ "uniqIf": _handle_uniq_if,+ "uniqExactIf": _handle_uniq_if,+}++# Standard-SQL functions valid in Snowflake verbatim. Anything not here, in a+# rename, or in a handler raises "not supported in the Snowflake dialect".+SNOWFLAKE_PASSTHROUGH_FUNCTIONS: frozenset[str] = frozenset(+ {+ # Aggregates+ "sum",+ "avg",+ "min",+ "max",+ # Math+ "abs",+ "floor",+ "ceil",+ "round",+ "sqrt",+ "power",+ "exp",+ "ln",+ "sign",+ "sin",+ "cos",+ "tan",+ "asin",+ "acos",+ "atan",+ "atan2",+ "pi",+ "degrees",+ "radians",+ "cbrt",+ "greatest",+ "least",+ # String+ "lower",+ "upper",+ "trim",+ "ltrim",+ "rtrim",+ "substring",+ "concat",+ "length",+ "left",+ "right",+ "position",+ "reverse",+ "replace",+ "lpad",+ "rpad",+ "repeat",+ "initcap",+ "ascii",+ # Window+ "row_number",+ "rank",+ "dense_rank",+ "lag",+ "lead",+ "first_value",+ "last_value",+ "nth_value",+ # Null+ "coalesce",+ "nullif",+ # Date / time+ "date_trunc",+ # Other+ "md5",+ },+)+++# Case-insensitive lookup maps — visit_call matches against node.name.lower().+SNOWFLAKE_FUNCTION_RENAMES_LOWER: dict[str, str] = {k.lower(): v for k, v in SNOWFLAKE_FUNCTION_RENAMES.items()}+SNOWFLAKE_FUNCTION_HANDLERS_LOWER: dict[str, Callable[[list[str]], str]] = {+ k.lower(): v for k, v in SNOWFLAKE_FUNCTION_HANDLERS.items()+}diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex c127cd354579..d1979a5cf465 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -7061,3 +7061,229 @@ class TestMySQLPrinter(BaseTest):printer = MySQLPrinter(context=HogQLContext(team_id=self.team.pk))with self.assertRaisesMessage(QueryError, 'is not permitted as it contains the "%" character'):printer._print_identifier("bad%name")+++# Pins what the Snowflake printer emits for each function category. The maps are+# standalone (no Postgres fallback), so this also guards that every still-valid+# function stays wired. (name, hogql_expr, expected_snowflake_sql)+SNOWFLAKE_EMIT_CASES: list[tuple[str, str, str]] = [+ # Casts (Snowflake type synonyms; no UUID type → VARCHAR)+ ("toString", "toString(1)", "CAST(1 AS VARCHAR)"),+ ("toFloat", "toFloat('1.5')", "CAST(%(hogql_val_0)s AS DOUBLE)"),+ ("toUUID", "toUUID('x')", "CAST(%(hogql_val_0)s AS VARCHAR)"),+ ("toDate", "toDate(now())", "CAST(CURRENT_TIMESTAMP() AS DATE)"),+ # Date extraction (Snowflake EXTRACT unit names)+ ("toYear", "toYear(now())", "EXTRACT(YEAR FROM CURRENT_TIMESTAMP())"),+ ("toDayOfWeek", "toDayOfWeek(now())", "EXTRACT(dayofweekiso FROM CURRENT_TIMESTAMP())"),+ ("toDayOfYear", "toDayOfYear(now())", "EXTRACT(dayofyear FROM CURRENT_TIMESTAMP())"),+ ("toISOWeek", "toISOWeek(now())", "EXTRACT(weekiso FROM CURRENT_TIMESTAMP())"),+ ("toISOYear", "toISOYear(now())", "EXTRACT(yearofweekiso FROM CURRENT_TIMESTAMP())"),+ ("toUnixTimestamp", "toUnixTimestamp(now())", "CAST(DATE_PART('epoch_second', CURRENT_TIMESTAMP()) AS BIGINT)"),+ ("toYYYYMMDD", "toYYYYMMDD(now())", "CAST(TO_CHAR(CURRENT_TIMESTAMP(), 'YYYYMMDD') AS INTEGER)"),+ # Date truncation / generators+ ("toMonday", "toMonday(now())", "CAST(DATE_TRUNC('week', CURRENT_TIMESTAMP()) AS DATE)"),+ ("toLastDayOfMonth", "toLastDayOfMonth(now())", "CAST(LAST_DAY(CURRENT_TIMESTAMP()) AS DATE)"),+ ("today", "today()", "CURRENT_DATE"),+ ("yesterday", "yesterday()", "(CURRENT_DATE - INTERVAL '1 day')"),+ # toStartOf* (DATE_TRUNC; week/ISO-year via DAYOFWEEKISO so WEEK_START is irrelevant;+ # sub-hour buckets via native TIME_SLICE)+ ("toStartOfDay", "toStartOfDay(now())", "DATE_TRUNC('day', CURRENT_TIMESTAMP())"),+ ("toStartOfMonth", "toStartOfMonth(now())", "DATE_TRUNC('month', CURRENT_TIMESTAMP())"),+ ("toStartOfHour", "toStartOfHour(now())", "DATE_TRUNC('hour', CURRENT_TIMESTAMP())"),+ ("toStartOfQuarter", "toStartOfQuarter(now())", "DATE_TRUNC('quarter', CURRENT_TIMESTAMP())"),+ (+ "toStartOfWeek",+ "toStartOfWeek(now())",+ "DATE_TRUNC('day', DATEADD('day', -(DAYOFWEEKISO(CURRENT_TIMESTAMP()) % 7), CURRENT_TIMESTAMP()))",+ ),+ (+ "toStartOfISOYear",+ "toStartOfISOYear(now())",+ "DATEADD('day', 1 - DAYOFWEEKISO(DATE_FROM_PARTS(YEAROFWEEKISO(CURRENT_TIMESTAMP()), 1, 4)), "+ "DATE_FROM_PARTS(YEAROFWEEKISO(CURRENT_TIMESTAMP()), 1, 4))",+ ),+ ("toStartOfFiveMinutes", "toStartOfFiveMinutes(now())", "TIME_SLICE(CURRENT_TIMESTAMP(), 5, 'MINUTE')"),+ (+ "toStartOfFifteenMinutes",+ "toStartOfFifteenMinutes(now())",+ "TIME_SLICE(CURRENT_TIMESTAMP(), 15, 'MINUTE')",+ ),+ # Intervals / arithmetic (DATEADD; no INTERVAL multiplication)+ ("toIntervalDay", "toIntervalDay(7)", "INTERVAL '7 day'"),+ ("addDays", "addDays(now(), 7)", "DATEADD('day', 7, CURRENT_TIMESTAMP())"),+ ("subtractMonths", "subtractMonths(now(), 3)", "DATEADD('month', -(3), CURRENT_TIMESTAMP())"),+ # dateDiff / formatDateTime — unit / format inlined as a literal+ ("dateDiff", "dateDiff('day', now(), now())", "DATEDIFF('day', CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP())"),+ (+ "formatDateTime",+ "formatDateTime(now(), '%Y-%m-%d %H:%M:%S')",+ "TO_CHAR(CURRENT_TIMESTAMP(), 'YYYY-MM-DD HH24:MI:SS')",+ ),+ # A literal double-quote is escaped as "" inside the quoted run, not dropped.+ (+ "formatDateTime_escapes_literal_quote",+ "formatDateTime(now(), '%Y\"q\"')",+ 'TO_CHAR(CURRENT_TIMESTAMP(), \'YYYY"""q"""\')',+ ),+ (+ "formatDateTime_escapes_lone_quote",+ "formatDateTime(now(), '%H\"%M')",+ 'TO_CHAR(CURRENT_TIMESTAMP(), \'HH24""""MI\')',+ ),+ # A literal single-quote (escaped `''` in HogQL) must be re-escaped as `''` so it can't close+ # the surrounding SQL string literal — guards the formatDateTime injection vector.+ (+ "formatDateTime_escapes_single_quote",+ "formatDateTime(now(), '%Y''T''%H')",+ "TO_CHAR(CURRENT_TIMESTAMP(), 'YYYY\"''T''\"HH24')",+ ),+ # Conditional / null+ ("if", "if(1, 2, 3)", "CASE WHEN 1 THEN 2 ELSE 3 END"),+ ("isNull", "isNull(1)", "(1 IS NULL)"),+ # Regex operators → REGEXP_INSTR (match()-style "found anywhere"); 'i' = case-insensitive+ ("regex_match", "'h' =~ 'h.*o'", "(REGEXP_INSTR(%(hogql_val_0)s, %(hogql_val_1)s) != 0)"),+ ("regex_not_match", "'h' !~ 'h.*o'", "(REGEXP_INSTR(%(hogql_val_0)s, %(hogql_val_1)s) = 0)"),+ ("regex_imatch", "'h' =~* 'h.*o'", "(REGEXP_INSTR(%(hogql_val_0)s, %(hogql_val_1)s, 1, 1, 0, 'i') != 0)"),+ ("regex_not_imatch", "'h' !~* 'h.*o'", "(REGEXP_INSTR(%(hogql_val_0)s, %(hogql_val_1)s, 1, 1, 0, 'i') = 0)"),+ # `::` casts map HogQL type names to Snowflake types (consistent with toString/toInt/...)+ ("cast_string", "1::String", "CAST(1 AS VARCHAR)"),+ ("cast_int", "1.5::Int", "CAST(1.5 AS BIGINT)"),+ ("cast_bool", "1::Bool", "CAST(1 AS BOOLEAN)"),+ # Array / object literals → constructors+ ("array_literal", "[1, 2, 3]", "ARRAY_CONSTRUCT(1, 2, 3)"),+ ("object_literal", "{'a': 1}", "OBJECT_CONSTRUCT(%(hogql_val_0)s, 1)"),+ # JSON (PARSE_JSON + bracket path; chained keys for nested access)+ (+ "JSONExtractString",+ "JSONExtractString('{}', 'a')",+ "CAST(PARSE_JSON(%(hogql_val_0)s)[%(hogql_val_1)s] AS VARCHAR)",+ ),+ (+ "JSONExtractInt_nested",+ "JSONExtractInt('{}', 'a', 'b')",+ "CAST(PARSE_JSON(%(hogql_val_0)s)[%(hogql_val_1)s][%(hogql_val_2)s] AS INTEGER)",+ ),+ ("JSONExtractRaw", "JSONExtractRaw('{}', 'a')", "PARSE_JSON(%(hogql_val_0)s)[%(hogql_val_1)s]"),+ ("JSONLength", "JSONLength('[]')", "ARRAY_SIZE(PARSE_JSON(%(hogql_val_0)s))"),+ # String+ ("match", "match('h', 'h.*o')", "(REGEXP_INSTR(%(hogql_val_0)s, %(hogql_val_1)s) != 0)"),+ ("splitByChar", "splitByChar(',', 'a,b')", "SPLIT(%(hogql_val_1)s, %(hogql_val_0)s)"),+ (+ "replaceOne",+ "replaceOne('a', 'b', 'c')",+ "REGEXP_REPLACE(%(hogql_val_0)s, %(hogql_val_1)s, %(hogql_val_2)s, 1, 1)",+ ),+ # Math+ ("log10", "log10(100)", "LOG(10, 100)"),+ ("log", "log(2)", "LN(2)"),+ ("rand", "rand()", "UNIFORM(0::float, 1::float, RANDOM())"),+ # Aggregation (no FILTER clause; CASE WHEN / COUNT_IF)+ ("countIf_1arg", "countIf(1)", "COUNT_IF(1)"),+ ("countIf_2arg", "countIf(event, 1)", 'COUNT(CASE WHEN 1 THEN events."event" END)'),+ ("sumIf", "sumIf(1, 1)", "SUM(CASE WHEN 1 THEN 1 END)"),+ ("avgIf", "avgIf(1, 1)", "AVG(CASE WHEN 1 THEN 1 END)"),+ ("anyIf", "anyIf(1, 1)", "MIN(CASE WHEN 1 THEN 1 END)"),+ ("groupArrayIf", "groupArrayIf(1, 1)", "ARRAY_AGG(CASE WHEN 1 THEN 1 END)"),+ ("uniqIf", "uniqIf(1, 1)", "COUNT(DISTINCT CASE WHEN 1 THEN 1 END)"),+ ("uniq", "uniq(1)", "COUNT(DISTINCT 1)"),+ # Renames+ ("ifNull", "ifNull(1, 2)", "COALESCE(1, 2)"),+ ("groupArray", "groupArray(event)", 'ARRAY_AGG(events."event")'),+ ("toTypeName", "toTypeName(1)", "TYPEOF(1)"),+ ("startsWith", "startsWith('a', 'b')", "STARTSWITH(%(hogql_val_0)s, %(hogql_val_1)s)"),+ ("now", "now()", "CURRENT_TIMESTAMP()"),+ ("pow", "pow(2, 3)", "POWER(2, 3)"),+ # count() means "count all rows"; Snowflake rejects a bare COUNT(), so emit COUNT(*).+ ("count_star", "count()", "count(*)"),+ ("count_expr", "count(event)", 'count(events."event")'),+ # Passthrough (valid Snowflake verbatim)+ ("avg", "avg(1)", "avg(1)"),+ ("coalesce", "coalesce(1, 2)", "coalesce(1, 2)"),+ ("power", "power(2, 3)", "power(2, 3)"),+]+++class TestSnowflakePrinter(BaseTest):+ maxDiff = None++ def _expr(+ self,+ query: ast.Expr | str,+ context: Optional[HogQLContext] = None,+ ) -> str:+ node = parse_expr(query, backend="cpp-json") if isinstance(query, str) else query+ context = context or HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ select_query = ast.SelectQuery(select=[node], select_from=ast.JoinExpr(table=ast.Field(chain=["events"])))+ prepared_select_query: ast.SelectQuery = cast(+ ast.SelectQuery,+ prepare_ast_for_printing(select_query, context=context, dialect="snowflake", stack=[select_query]),+ )+ return print_prepared_ast(+ prepared_select_query.select[0],+ context=context,+ dialect="snowflake",+ stack=[prepared_select_query],+ )++ @parameterized.expand(SNOWFLAKE_EMIT_CASES)+ def test_snowflake_emit(self, _name: str, hogql_expr: str, expected: str):+ self.assertEqual(self._expr(hogql_expr), expected)++ @parameterized.expand(+ [+ ("datediff_non_literal_unit", "dateDiff(event, now(), now())", "requires a literal unit"),+ ("datediff_bad_unit", "dateDiff('fortnight', now(), now())", "Unsupported dateDiff unit 'fortnight'"),+ (+ "format_unknown_specifier",+ "formatDateTime(now(), '%Q')",+ "Unsupported formatDateTime specifier '%Q'",+ ),+ ("unsupported_function", "argMax(1, 2)", "not supported in the Snowflake dialect"),+ # Tier 0: constructs with no safe Snowflake equivalent reject loudly+ ("tuple", "(1, 2)", "Tuple expressions are not supported"),+ ("array_slice", "[1, 2, 3][1:2]", "Array slices are not"),+ ("unsupported_cast", "1::Nonsense", "Unsupported cast to type 'nonsense'"),+ ]+ )+ def test_snowflake_errors(self, _name: str, hogql_expr: str, error_substring: str):+ with self.assertRaises(QueryError) as ctx:+ self._expr(hogql_expr)+ self.assertIn(error_substring, str(ctx.exception))++ def _select(self, query: str) -> str:+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)+ return prepare_and_print_ast(parse_select(query, backend="cpp-json"), context, "snowflake")[0]++ @parameterized.expand(+ [+ ("array_join", "SELECT x FROM events ARRAY JOIN [1, 2] AS x", "ARRAY JOIN is not supported"),+ ("prewhere", "SELECT event FROM events PREWHERE event = 'x'", "PREWHERE is not supported"),+ ("sample", "SELECT event FROM events SAMPLE 0.1", "SAMPLE is not supported"),+ ("limit_by", "SELECT event FROM events LIMIT 1 BY event", "LIMIT BY is not supported"),+ ]+ )+ def test_snowflake_clause_errors(self, _name: str, query: str, error_substring: str):+ with self.assertRaises(QueryError) as ctx:+ self._select(query)+ self.assertIn(error_substring, str(ctx.exception))++ def test_snowflake_qualify_emits_natively(self):+ # QUALIFY parses and resolves but the base/HogQL printers rejected it; Snowflake supports+ # it natively, so it should print straight through.+ sql = self._select("SELECT event FROM events QUALIFY row_number() OVER (ORDER BY timestamp) = 1")+ self.assertIn("QUALIFY", sql)++ def test_snowflake_pivot_emits_unqualified_columns_and_star_projection(self):+ # Snowflake rejects table-qualified columns inside PIVOT, and its output columns are named+ # after the IN values (which HogQL can't enumerate) — so the projection stays `*`.+ sql = self._select("SELECT * FROM events PIVOT(count(timestamp) FOR event IN ('pageview', 'click'))")+ self.assertIn('PIVOT (count("timestamp") FOR "event" IN (', sql)+ self.assertTrue(sql.startswith("SELECT * FROM events PIVOT ("), sql)++ def test_snowflake_unpivot_emits_unqualified_columns(self):+ sql = self._select("SELECT * FROM (SELECT 1 AS jan, 2 AS feb) AS t UNPIVOT(amount FOR month IN (jan, feb))")+ self.assertIn('UNPIVOT ("amount" FOR "month" IN ("jan", "feb"))', sql)++ def test_snowflake_pivot_rejects_inner_group_by(self):+ with self.assertRaises(QueryError):+ self._select("SELECT * FROM events PIVOT(count(timestamp) FOR event IN ('a') GROUP BY uuid)")diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 4b8f3a532b02..bb90c16695d5 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -24,6 +24,7 @@ from posthog.hogql.printer.duckdb import DuckDBPrinterfrom posthog.hogql.printer.hogql import HogQLPrinterfrom posthog.hogql.printer.mysql import MySQLPrinterfrom posthog.hogql.printer.postgres import PostgresPrinter+from posthog.hogql.printer.snowflake import SnowflakePrinterfrom posthog.hogql.resolver import ResolverFactory, resolve_typesfrom posthog.hogql.transforms.clickhouse_property_resolution import clickhouse_property_resolutionfrom posthog.hogql.transforms.events_predicate_pushdown import apply_events_predicate_pushdown, events_pushdown_enabled@@ -58,6 +59,7 @@ PRINTER_CLASSES: dict[HogQLDialect, type[BasePrinter]] = {"postgres": PostgresPrinter,"duckdb": DuckDBPrinter,"mysql": MySQLPrinter,+ "snowflake": SnowflakePrinter,"hogql": HogQLPrinter,}diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex 9c82feb5e5cb..b98b24e36e8b 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -115,6 +115,18 @@ assert POSTGRES_KEYWORD_TYPES.keys() == ast.VALID_KEYWORD_NAMES, (# takes the PG code path in the resolver._POSTGRES_FAMILY: frozenset[HogQLDialect] = frozenset({"postgres", "duckdb"})+# Dialects with native PIVOT/UNPIVOT support. Snowflake speaks the same standard-SQL+# `PIVOT (agg FOR col IN (...))` shape, so it joins the Postgres family here even though it+# isn't Postgres-wire compatible for the other gated constructs. `hogql` is included so the+# canonical round-trip (the re-printed `self.hogql`) doesn't reject a query the target dialect+# accepts.+_PIVOT_ONLY_DIALECTS: frozenset[HogQLDialect] = frozenset({"snowflake", "hogql"})+_PIVOT_DIALECTS: frozenset[HogQLDialect] = _POSTGRES_FAMILY | _PIVOT_ONLY_DIALECTS+++def _select_from_is_pivot(select_from: "ast.JoinExpr | None") -> bool:+ return select_from is not None and isinstance(select_from.table, ast.PivotExpr)+def resolve_constant_data_type(constant: Any) -> ConstantType:if constant is None:@@ -345,7 +357,7 @@ class Resolver(CloningVisitor):return resultdef visit_unpivot_expr(self, node: ast.UnpivotExpr):- if self.dialect not in _POSTGRES_FAMILY:+ if self.dialect not in _PIVOT_DIALECTS:raise QueryError(f"UNPIVOT is not allowed in {self.dialect} dialect")node = cast(ast.UnpivotExpr, clone_expr(node))@@ -532,7 +544,7 @@ class Resolver(CloningVisitor):self.scopes.pop()def visit_pivot_expr(self, node: ast.PivotExpr):- if self.dialect not in _POSTGRES_FAMILY:+ if self.dialect not in _PIVOT_DIALECTS:raise QueryError(f"PIVOT is not allowed in {self.dialect} dialect")node = cast(ast.PivotExpr, clone_expr(node))@@ -781,6 +793,13 @@ class Resolver(CloningVisitor):continuenew_expr = self.visit(expr)if isinstance(new_expr.type, ast.AsteriskType):+ # A PIVOT produces output columns named after its IN-list values, which we can't+ # enumerate at resolve time. Snowflake names them in ways HogQL can't express, so+ # keep `*` literal and let Snowflake expand it. (UNPIVOT output IS knowable, so it+ # still expands normally.)+ if self.dialect == "snowflake" and _select_from_is_pivot(new_node.select_from):+ select_nodes.append(new_expr)+ continuecolumns = self._asterisk_columns(new_expr.type, chain_prefix=new_expr.chain[:-1])for col in columns:visited_col = self.visit(col)diff --git a/posthog/hogql/snowflake_connection_cache.py b/posthog/hogql/snowflake_connection_cache.pynew file mode 100644index 000000000000..a9629439ddf9--- /dev/null+++ b/posthog/hogql/snowflake_connection_cache.py@@ -0,0 +1,169 @@+"""Thread-local connection cache for direct Snowflake queries.++Opening a Snowflake connection runs a full auth handshake (often hundreds of ms or+more), which dominates latency for the interactive SQL editor where a user issues+many small queries in sequence. This caches one open connection per+(credentials + target) per worker thread, reusing it across queries and reopening+lazily when it expires, dies, or is evicted.++Two deliberate scope choices:++- Direct-query path only. The data-import pipeline opens its own short-lived+ connections per sync and must not share these.+- Thread-local. A ``SnowflakeConnection`` is not safe to use from multiple threads+ concurrently, and the web app runs blocking DB work in a threadpool — so each+ thread keeps its own connection and never shares it, no locking required.+"""++from __future__ import annotations++import hashlib+import threading+from collections import OrderedDict+from collections.abc import Iterator+from contextlib import AbstractContextManager, contextmanager+from dataclasses import dataclass+from time import monotonic+from typing import TYPE_CHECKING++import snowflake.connector++from posthog.hogql.direct_query_metrics import SNOWFLAKE_CONNECTION_CACHE_TOTAL++if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig+ from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake import (+ SnowflakeImplementation,+ )++# Refresh well before Snowflake's session/token expiry so a cached connection is+# replaced proactively rather than failing mid-query.+SNOWFLAKE_CONNECTION_CACHE_TTL_SECONDS = 1800+# Bound per-thread connection count so a worker that touches many distinct sources+# can't accumulate open sessions without limit.+SNOWFLAKE_CONNECTION_CACHE_MAX_PER_THREAD = 8++# Transport/connection-level failures mean the cached session is suspect; SQL-level+# errors (ProgrammingError, IntegrityError) leave the connection healthy.+_CONNECTION_LEVEL_ERRORS = (+ snowflake.connector.errors.OperationalError,+ snowflake.connector.errors.InterfaceError,+)+++@dataclass+class _Entry:+ cm: AbstractContextManager[snowflake.connector.SnowflakeConnection]+ connection: snowflake.connector.SnowflakeConnection+ opened_at: float+++_thread_local = threading.local()+++def _cache() -> OrderedDict[str, _Entry]:+ cache = getattr(_thread_local, "cache", None)+ if cache is None:+ cache = OrderedDict()+ _thread_local.cache = cache+ return cache+++def _config_key(config: SnowflakeSourceConfig) -> str:+ auth = config.auth_type+ selection = auth.selection+ secret = auth.private_key if selection == "keypair" else auth.password++ def text(value: object) -> str:+ return str(value) if value else ""++ def digest(value: object) -> str:+ return hashlib.sha256(text(value).encode("utf-8")).hexdigest()++ # Hash the secret rather than carry it in the key. Keying on the credentials means+ # a rotation routes to a fresh connection automatically (old entry just expires).+ secret_digest = digest(secret)+ passphrase_digest = digest(getattr(auth, "passphrase", None))+ parts = [+ text(config.account_id),+ text(auth.user),+ text(config.warehouse),+ text(config.database),+ text(config.role),+ text(config.schema),+ text(selection),+ secret_digest,+ passphrase_digest,+ ]+ return hashlib.sha256("\x00".join(parts).encode("utf-8")).hexdigest()+++def _close_entry(entry: _Entry) -> None:+ try:+ entry.cm.__exit__(None, None, None)+ except Exception:+ pass+++def _evict(key: str) -> None:+ entry = _cache().pop(key, None)+ if entry is not None:+ _close_entry(entry)+++def _is_reusable(entry: _Entry, now: float) -> bool:+ if now - entry.opened_at >= SNOWFLAKE_CONNECTION_CACHE_TTL_SECONDS:+ return False+ try:+ return not entry.connection.is_closed()+ except Exception:+ return False+++@contextmanager+def cached_snowflake_connection(+ implementation: SnowflakeImplementation,+ config: SnowflakeSourceConfig,+) -> Iterator[snowflake.connector.SnowflakeConnection]:+ """Yield a cached open Snowflake connection for this thread, opening one if needed.++ The connection is kept open after the block exits so the next query on the same+ thread can reuse it. It is dropped (and reopened next time) on expiry, when found+ closed, on LRU eviction, or when the block raises a connection-level error.+ """+ key = _config_key(config)+ cache = _cache()+ now = monotonic()++ entry = cache.get(key)+ if entry is not None and _is_reusable(entry, now):+ cache.move_to_end(key)+ connection = entry.connection+ SNOWFLAKE_CONNECTION_CACHE_TOTAL.labels(result="reused").inc()+ else:+ if entry is not None:+ _evict(key)+ # Drive the implementation's own connect() contextmanager but keep it entered, so+ # we reuse its auth/keypair logic without closing the connection on block exit.+ cm = implementation.connect(config)+ connection = cm.__enter__()+ # A fresh key lands at the tail (LRU-newest) already, so no move_to_end needed here.+ cache[key] = _Entry(cm=cm, connection=connection, opened_at=now)+ SNOWFLAKE_CONNECTION_CACHE_TOTAL.labels(result="opened").inc()+ while len(cache) > SNOWFLAKE_CONNECTION_CACHE_MAX_PER_THREAD:+ _old_key, old_entry = cache.popitem(last=False)+ _close_entry(old_entry)++ try:+ yield connection+ except _CONNECTION_LEVEL_ERRORS:+ _evict(key)+ raise+++def clear_thread_local_snowflake_connections() -> None:+ """Close and drop every cached connection for the current thread (tests, shutdown)."""+ cache = _cache()+ for entry in list(cache.values()):+ _close_entry(entry)+ cache.clear()diff --git a/posthog/hogql/test/test_direct_snowflake_query.py b/posthog/hogql/test/test_direct_snowflake_query.pynew file mode 100644index 000000000000..193bcf243b65--- /dev/null+++ b/posthog/hogql/test/test_direct_snowflake_query.py@@ -0,0 +1,398 @@+from types import SimpleNamespace+from typing import TYPE_CHECKING, cast+from uuid import uuid4++import unittest+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++import snowflake.connector+from parameterized import parameterized++from posthog.hogql.direct_sql.snowflake_adapter import (+ snowflake_error_to_message,+ snowflake_field_type_to_clickhouse_type,+ validate_snowflake_account_id,+)+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.query import HogQLQueryExecutor+from posthog.hogql.snowflake_connection_cache import (+ cached_snowflake_connection,+ clear_thread_local_snowflake_connections,+)++from products.warehouse_sources.backend.facade.models import ExternalDataSource++if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig++# Snowflake connector type codes (indices into FIELD_ID_TO_NAME). cursor.description+# reports the integer code, not a name — see snowflake_field_type_to_clickhouse_type.+FIXED = 0+REAL = 1+TEXT = 2+DATE = 3+TIMESTAMP = 4+VARIANT = 5+TIMESTAMP_LTZ = 6+TIMESTAMP_TZ = 7+TIMESTAMP_NTZ = 8+OBJECT = 9+ARRAY = 10+BINARY = 11+TIME = 12+BOOLEAN = 13+GEOGRAPHY = 14+GEOMETRY = 15+VECTOR = 16+MAP = 17+++class TestDirectSnowflakeQuery(APIBaseTest):+ def setUp(self):+ super().setUp()+ # The connection cache is thread-local module state; isolate each test.+ clear_thread_local_snowflake_connections()+ self.addCleanup(clear_thread_local_snowflake_connections)++ def _create_source(self, prefix: str = "wh") -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid4()),+ connection_id=str(uuid4()),+ status=ExternalDataSource.Status.COMPLETED,+ source_type="Snowflake",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ prefix=prefix,+ connection_metadata={"engine": "snowflake", "database": "DB"},+ job_inputs={+ "account_id": "acme-prod",+ "database": "DB",+ "warehouse": "WH",+ "role": "REPORTING",+ "auth_type": {"selection": "password", "user": "svc", "password": "pw"},+ },+ )++ @parameterized.expand(+ [+ # FIXED covers NUMBER/DECIMAL/INT; scale decides int vs decimal.+ ("number_decimal", FIXED, 2, "Decimal"),+ ("number_integer_scale_0", FIXED, 0, "Int64"),+ ("number_integer_scale_none", FIXED, None, "Int64"),+ ("real_float", REAL, None, "Float64"),+ ("text_varchar", TEXT, None, "String"),+ ("date", DATE, None, "Date"),+ ("time", TIME, None, "String"),+ ("timestamp", TIMESTAMP, None, "DateTime64(6, 'UTC')"),+ ("timestamp_ntz", TIMESTAMP_NTZ, None, "DateTime64(6, 'UTC')"),+ ("timestamp_ltz", TIMESTAMP_LTZ, None, "DateTime64(6, 'UTC')"),+ ("timestamp_tz", TIMESTAMP_TZ, None, "DateTime64(6, 'UTC')"),+ ("boolean", BOOLEAN, None, "Bool"),+ ("variant", VARIANT, None, "String"),+ ("object", OBJECT, None, "String"),+ ("array", ARRAY, None, "String"),+ ("map", MAP, None, "String"),+ ("binary", BINARY, None, "String"),+ ("geography", GEOGRAPHY, None, "String"),+ ("geometry", GEOMETRY, None, "String"),+ ("vector", VECTOR, None, "String"),+ ("unknown_code", 99999, None, "String"),+ ("non_integer_code", "NUMBER", None, "String"),+ ("none_code", None, None, "String"),+ ]+ )+ def test_snowflake_field_type_to_clickhouse_type(+ self, _name: str, type_code: object | None, scale: object | None, expected: str+ ):+ self.assertEqual(snowflake_field_type_to_clickhouse_type(type_code, scale), expected)++ def test_snowflake_error_to_message_uses_server_message(self):+ error = snowflake.connector.errors.ProgrammingError(+ msg="SQL compilation error:\ninvalid identifier 'NOPE'", errno=904+ )+ # ProgrammingError formats args[1] as "<errno>: <msg>"; only the first line is surfaced.+ self.assertEqual(snowflake_error_to_message(error), "000904: SQL compilation error:")++ def test_snowflake_error_to_message_falls_back_to_str(self):+ self.assertEqual(snowflake_error_to_message(Exception("boom\nsecond line")), "boom")++ def test_snowflake_error_to_message_handles_empty(self):+ self.assertEqual(snowflake_error_to_message(Exception("")), "Snowflake query failed.")++ @parameterized.expand(+ [+ ("org_account", "acme-prod_account"),+ ("legacy_dotted", "xy12345.us-east-1.aws"),+ ("with_leading_alnum", "a1b2c3"),+ ]+ )+ def test_validate_snowflake_account_id_accepts_valid(self, _name: str, account_id: str):+ self.assertEqual(validate_snowflake_account_id(account_id), account_id)++ @parameterized.expand(+ [+ ("empty", ""),+ ("none", None),+ ("whitespace", " "),+ ("scheme", "http://evil.internal"),+ ("slash_path", "acme/../../etc"),+ ("at_sign", "user@host"),+ ("space_inside", "acme prod"),+ ("leading_dot", ".acme"),+ ]+ )+ def test_validate_snowflake_account_id_rejects_invalid(self, _name: str, account_id: str | None):+ with self.assertRaises(ExposedHogQLError):+ validate_snowflake_account_id(account_id)++ def _mock_snowflake_connection(self, rows: list[tuple], description: list[tuple]) -> tuple[MagicMock, MagicMock]:+ cursor = MagicMock()+ # Direct Snowflake reads through fetchmany (bounded), not fetchall.+ cursor.fetchmany.return_value = rows+ cursor.description = description+ connection = MagicMock()+ connection.is_closed.return_value = False+ connection.cursor.return_value.__enter__.return_value = cursor+ connection.cursor.return_value.__exit__.return_value = False++ implementation = MagicMock()+ implementation.connect.return_value.__enter__.return_value = connection+ implementation.connect.return_value.__exit__.return_value = False+ return implementation, cursor++ def test_execute_sets_statement_timeout_and_maps_types(self):+ source = self._create_source()++ executor = HogQLQueryExecutor(+ query="SELECT C_ID, C_ACCTBAL FROM CUSTOMER",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ )++ implementation, cursor = self._mock_snowflake_connection(+ rows=[(1, "100.50")],+ description=[+ ("C_ID", FIXED, None, None, None, 0, None),+ ("C_ACCTBAL", FIXED, None, None, 12, 2, None),+ ],+ )++ with patch(+ "posthog.hogql.direct_sql.snowflake_adapter.SnowflakeAdapter.validate_source_config",+ return_value=(implementation, MagicMock()),+ ):+ with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):+ response = executor.execute()++ executed_statements = [call.args[0] for call in cursor.execute.call_args_list]+ # Read-only is enforced our side: pin single-statement and the statement timeout+ # on the session before the query runs.+ self.assertEqual(executed_statements[0], "ALTER SESSION SET MULTI_STATEMENT_COUNT = 1")+ self.assertTrue(executed_statements[1].startswith("ALTER SESSION SET STATEMENT_TIMEOUT_IN_SECONDS"))+ self.assertEqual(executor.direct_dialect, "snowflake")+ self.assertEqual(response.results, [(1, "100.50")])+ # FIXED with scale 0 → Int64; scale 2 → Decimal (the bug that showed C_ACCTBAL as String).+ self.assertEqual(response.types, [("C_ID", "Int64"), ("C_ACCTBAL", "Decimal")])++ def test_execute_rejects_result_over_row_cap(self):+ source = self._create_source()++ executor = HogQLQueryExecutor(+ query="SELECT C_ID FROM CUSTOMER",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ )++ # fetchmany is asked for cap+1; returning that many signals the cap was exceeded.+ # Patch the cap small so the test doesn't allocate a million rows.+ implementation, _cursor = self._mock_snowflake_connection(+ rows=[(i,) for i in range(4)],+ description=[("C_ID", FIXED, None, None, None, 0, None)],+ )++ with patch("posthog.hogql.direct_sql.snowflake_adapter.DIRECT_SNOWFLAKE_MAX_ROWS", 3):+ with patch(+ "posthog.hogql.direct_sql.snowflake_adapter.SnowflakeAdapter.validate_source_config",+ return_value=(implementation, MagicMock()),+ ):+ with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):+ with self.assertRaisesRegex(ExposedHogQLError, "Add a LIMIT clause"):+ executor.execute()++ @parameterized.expand(+ [+ # Leading-keyword writes (rejected by the SELECT classification).+ ("delete", "DELETE FROM CUSTOMER WHERE C_ID = 1"),+ ("insert", "INSERT INTO CUSTOMER VALUES (1)"),+ ("update", "UPDATE CUSTOMER SET C_NAME = 'x'"),+ ("drop", "DROP TABLE CUSTOMER"),+ ("create", "CREATE TABLE t (c int)"),+ ("alter", "ALTER TABLE CUSTOMER ADD COLUMN c int"),+ ("truncate", "TRUNCATE TABLE CUSTOMER"),+ ("multiple_statements", "SELECT 1; DROP TABLE CUSTOMER"),+ ("merge", "MERGE INTO CUSTOMER USING staging ON CUSTOMER.C_ID = staging.id WHEN MATCHED THEN DELETE"),+ # Snowflake side-effecting statements that classify as UNKNOWN, not SELECT.+ ("call_procedure", "CALL my_writing_proc()"),+ ("copy_into", "COPY INTO CUSTOMER FROM @my_stage"),+ ("put_file", "PUT file:///tmp/x @my_stage"),+ ("get_file", "GET @my_stage file:///tmp/x"),+ ("grant", "GRANT SELECT ON CUSTOMER TO ROLE reporting"),+ ("use_database", "USE DATABASE other_db"),+ # Writes smuggled into an otherwise SELECT-classified statement.+ ("write_in_subquery", "SELECT * FROM (DELETE FROM CUSTOMER RETURNING C_ID)"),+ ("write_in_cte", "WITH x AS (INSERT INTO CUSTOMER VALUES (1) RETURNING C_ID) SELECT * FROM x"),+ # Side-effecting / session-leaking functions that parse as a plain SELECT.+ ("system_function", "SELECT SYSTEM$CANCEL_QUERY('01a-b-c')"),+ ("system_function_lower", "SELECT system$wait(1)"),+ ("result_scan", "SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID(-3)))"),+ ("last_query_id", "SELECT LAST_QUERY_ID()"),+ ]+ )+ def test_raw_query_rejects_non_select(self, _name: str, query: str):+ source = self._create_source()++ executor = HogQLQueryExecutor(+ query=query,+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ )++ with patch(+ "posthog.hogql.direct_sql.snowflake_adapter.SnowflakeAdapter.validate_source_config"+ ) as mock_validate:+ with self.assertRaises(ExposedHogQLError):+ executor.execute()++ # The statement is rejected before any connection is opened.+ mock_validate.assert_not_called()+ self.assertIsNone(executor.direct_sql)++ @parameterized.expand(+ [+ ("plain_select", "SELECT C_ID FROM CUSTOMER"),+ ("cte_select", "WITH x AS (SELECT 1 AS v) SELECT v FROM x"),+ # UDFs are read-only in Snowflake; a function call in a SELECT is fine.+ ("udf_call", "SELECT my_udf(C_ID) FROM CUSTOMER"),+ # A write keyword inside a string literal must not trip the token scan.+ ("write_word_in_string", "SELECT C_ID FROM CUSTOMER WHERE C_STATUS = 'DELETE'"),+ # A quoted identifier matching a blocked function name is a column, not a call.+ ("quoted_blocked_name_column", 'SELECT "result_scan" FROM CUSTOMER'),+ ]+ )+ def test_raw_query_allows_read_only_selects(self, _name: str, query: str):+ source = self._create_source()++ executor = HogQLQueryExecutor(+ query=query,+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ )++ implementation, _cursor = self._mock_snowflake_connection(+ rows=[(1,)],+ description=[("C_ID", FIXED, None, None, None, 0, None)],+ )++ with patch(+ "posthog.hogql.direct_sql.snowflake_adapter.SnowflakeAdapter.validate_source_config",+ return_value=(implementation, MagicMock()),+ ):+ with patch.object(HogQLQueryExecutor, "_capture_send_raw_query_translation_error"):+ executor.execute()++ # The statement passed the read-only gate and reached execution unchanged.+ self.assertEqual(executor.direct_sql, query)+++class TestSnowflakeConnectionCache(unittest.TestCase):+ def setUp(self):+ clear_thread_local_snowflake_connections()+ self.addCleanup(clear_thread_local_snowflake_connections)++ def _impl_and_config(+ self, secret: str = "pw", account: str = "acme-prod"+ ) -> tuple[MagicMock, "SnowflakeSourceConfig", MagicMock]:+ connection = MagicMock()+ connection.is_closed.return_value = False+ cm = MagicMock()+ cm.__enter__.return_value = connection+ cm.__exit__.return_value = False+ implementation = MagicMock()+ implementation.connect.return_value = cm+ auth = SimpleNamespace(selection="password", user="svc", password=secret, private_key=None, passphrase=None)+ config = SimpleNamespace(+ account_id=account, warehouse="WH", database="DB", role="R", schema="PUBLIC", auth_type=auth+ )+ return implementation, cast("SnowflakeSourceConfig", config), connection++ def test_reuses_connection_across_calls(self):+ implementation, config, connection = self._impl_and_config()++ with cached_snowflake_connection(implementation, config) as first:+ self.assertIs(first, connection)+ with cached_snowflake_connection(implementation, config) as second:+ self.assertIs(second, connection)++ implementation.connect.assert_called_once()++ def test_reopens_after_ttl(self):+ implementation, config, _connection = self._impl_and_config()++ with patch("posthog.hogql.snowflake_connection_cache.SNOWFLAKE_CONNECTION_CACHE_TTL_SECONDS", 0):+ with cached_snowflake_connection(implementation, config):+ pass+ with cached_snowflake_connection(implementation, config):+ pass++ self.assertEqual(implementation.connect.call_count, 2)++ def test_reopens_when_connection_reports_closed(self):+ implementation, config, connection = self._impl_and_config()++ with cached_snowflake_connection(implementation, config):+ pass+ connection.is_closed.return_value = True+ with cached_snowflake_connection(implementation, config):+ pass++ self.assertEqual(implementation.connect.call_count, 2)++ def test_evicts_on_connection_level_error(self):+ implementation, config, _connection = self._impl_and_config()++ with self.assertRaises(snowflake.connector.errors.OperationalError):+ with cached_snowflake_connection(implementation, config):+ raise snowflake.connector.errors.OperationalError(msg="connection dropped")+ with cached_snowflake_connection(implementation, config):+ pass++ # The suspect connection was dropped, so the next call reopens.+ self.assertEqual(implementation.connect.call_count, 2)++ def test_keeps_connection_on_sql_error(self):+ implementation, config, _connection = self._impl_and_config()++ with self.assertRaises(snowflake.connector.errors.ProgrammingError):+ with cached_snowflake_connection(implementation, config):+ raise snowflake.connector.errors.ProgrammingError(msg="bad sql")+ with cached_snowflake_connection(implementation, config):+ pass++ # A SQL error leaves the connection healthy, so it's reused.+ implementation.connect.assert_called_once()++ def test_different_credentials_use_separate_connections(self):+ implementation, config_a, _connection = self._impl_and_config(secret="pw-a")+ _implementation_b, config_b, _connection_b = self._impl_and_config(secret="pw-b")++ with cached_snowflake_connection(implementation, config_a):+ pass+ with cached_snowflake_connection(implementation, config_b):+ pass++ self.assertEqual(implementation.connect.call_count, 2)diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 26a6791ae726..0e23bee34634 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -17,6 +17,7 @@ from posthog.hogql import astfrom posthog.hogql.database.database import Databasefrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTable+from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.models import FieldOrTable, SavedQueryfrom posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTable@@ -336,7 +337,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,def hogql_definition(self, modifiers: Optional["HogQLQueryModifiers"] = None- ) -> Union[SavedQuery, HogQLDataWarehouseTable, DirectPostgresTable, DirectMySQLTable]:+ ) -> Union[SavedQuery, HogQLDataWarehouseTable, DirectPostgresTable, DirectMySQLTable, DirectSnowflakeTable]:if self.table is not None and self.is_materialized and modifiers is not None and modifiers.useMaterializedViews:return self.table.hogql_definition(modifiers)diff --git a/products/data_warehouse/backend/direct_snowflake.py b/products/data_warehouse/backend/direct_snowflake.pynew file mode 100644index 000000000000..91d502217a62--- /dev/null+++ b/products/data_warehouse/backend/direct_snowflake.py@@ -0,0 +1,87 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any++from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++if TYPE_CHECKING:+ from products.warehouse_sources.backend.models.table import DataWarehouseTable++type DirectSnowflakeColumns = dict[str, dict[str, Any]]+++DIRECT_SNOWFLAKE_URL_PATTERN = "direct://snowflake"+DIRECT_SNOWFLAKE_CATALOG_OPTION = "direct_snowflake_catalog"+DIRECT_SNOWFLAKE_SCHEMA_OPTION = "direct_snowflake_schema"+DIRECT_SNOWFLAKE_TABLE_OPTION = "direct_snowflake_table"+++def get_direct_snowflake_table_options(+ *, source_catalog: str | None = None, source_schema: str, source_table_name: str+) -> dict[str, str]:+ options = {+ DIRECT_SNOWFLAKE_SCHEMA_OPTION: source_schema,+ DIRECT_SNOWFLAKE_TABLE_OPTION: source_table_name,+ }+ if source_catalog:+ options[DIRECT_SNOWFLAKE_CATALOG_OPTION] = source_catalog+ return options+++def upsert_direct_snowflake_table(+ existing_table: DataWarehouseTable | None,+ *,+ schema_name: str,+ source: ExternalDataSource,+ columns: DirectSnowflakeColumns,+ source_catalog: str | None = None,+ source_schema: str,+ source_table_name: str,+) -> DataWarehouseTable:+ from products.warehouse_sources.backend.models.table import DataWarehouseTable++ options = {+ **(existing_table.options if existing_table is not None and isinstance(existing_table.options, dict) else {}),+ **get_direct_snowflake_table_options(+ source_catalog=source_catalog,+ source_schema=source_schema,+ source_table_name=source_table_name,+ ),+ }++ if existing_table is None:+ return DataWarehouseTable.objects.create(+ name=schema_name,+ format=DataWarehouseTable.TableFormat.Parquet,+ team_id=source.team_id,+ url_pattern=DIRECT_SNOWFLAKE_URL_PATTERN,+ external_data_source=source,+ columns=columns,+ options=options,+ )++ existing_table.name = schema_name+ existing_table.url_pattern = DIRECT_SNOWFLAKE_URL_PATTERN+ existing_table.external_data_source = source+ existing_table.columns = columns+ existing_table.options = options+ existing_table.deleted = False+ existing_table.deleted_at = None+ existing_table.save(+ update_fields=[+ "name",+ "url_pattern",+ "external_data_source",+ "columns",+ "options",+ "deleted",+ "deleted_at",+ "updated_at",+ ]+ )+ return existing_table+++def hide_direct_snowflake_table(table: DataWarehouseTable | None) -> None:+ if table is not None and not table.deleted:+ table.soft_delete()diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex c65497bbbcd7..14e35b7d82fe 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -63,11 +63,15 @@ _LAZY = {"get_postgres_source_location": "postgres_helpers","reconcile_postgres_schemas": "postgres_helpers","reproject_direct_postgres_table": "postgres_helpers",+ "reconcile_snowflake_schemas": "snowflake_helpers",+ "reproject_direct_snowflake_table": "snowflake_helpers","HogQLQueryFixerTool": "hogql_fixer_ai","hide_direct_mysql_table": "direct_mysql","upsert_direct_mysql_table": "direct_mysql","hide_direct_postgres_table": "direct_postgres","upsert_direct_postgres_table": "direct_postgres",+ "hide_direct_snowflake_table": "direct_snowflake",+ "upsert_direct_snowflake_table": "direct_snowflake","reconcile_refresh_name_substitutions": "postgres_warehouse_migration","apply_on_refresh": "sql_warehouse_migration","apply_on_schema_clear": "sql_warehouse_migration",diff --git a/products/data_warehouse/backend/facade/sources.py b/products/data_warehouse/backend/facade/sources.pyindex 5c9be5639cc1..580004556cf2 100644--- a/products/data_warehouse/backend/facade/sources.py+++ b/products/data_warehouse/backend/facade/sources.py@@ -12,6 +12,11 @@ from products.data_warehouse.backend.direct_postgres import (DIRECT_POSTGRES_SCHEMA_OPTION,DIRECT_POSTGRES_TABLE_OPTION,)+from products.data_warehouse.backend.direct_snowflake import (+ DIRECT_SNOWFLAKE_CATALOG_OPTION,+ DIRECT_SNOWFLAKE_SCHEMA_OPTION,+ DIRECT_SNOWFLAKE_TABLE_OPTION,+)__all__ = ["DIRECT_MYSQL_SCHEMA_OPTION",@@ -19,4 +24,7 @@ __all__ = ["DIRECT_POSTGRES_CATALOG_OPTION","DIRECT_POSTGRES_SCHEMA_OPTION","DIRECT_POSTGRES_TABLE_OPTION",+ "DIRECT_SNOWFLAKE_CATALOG_OPTION",+ "DIRECT_SNOWFLAKE_SCHEMA_OPTION",+ "DIRECT_SNOWFLAKE_TABLE_OPTION",]diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.pyindex 650ccc8c831f..436c7878ef41 100644--- a/products/data_warehouse/backend/models/test/test_table.py+++ b/products/data_warehouse/backend/models/test/test_table.py@@ -7,6 +7,7 @@ from parameterized import parameterizedfrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTable+from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.models import (DateTimeDatabaseField,IntegerDatabaseField,@@ -22,6 +23,11 @@ from products.data_warehouse.backend.direct_postgres import (DIRECT_POSTGRES_SCHEMA_OPTION,DIRECT_POSTGRES_TABLE_OPTION,)+from products.data_warehouse.backend.direct_snowflake import (+ DIRECT_SNOWFLAKE_CATALOG_OPTION,+ DIRECT_SNOWFLAKE_SCHEMA_OPTION,+ DIRECT_SNOWFLAKE_TABLE_OPTION,+)from products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING, DataWarehouseTable@@ -210,6 +216,68 @@ class TestTable(BaseTest):with pytest.raises(QueryError, match="Direct MySQL tables require a database name."):definition.to_printed_mysql(context=None)+ def test_direct_snowflake_table_uses_physical_catalog_schema_and_table_options(self):+ source = ExternalDataSource.objects.create(+ source_id="source-id",+ connection_id="connection-id",+ destination_id="destination-id",+ team=self.team,+ sync_frequency=ExternalDataSource.SyncFrequency.DAILY,+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.SNOWFLAKE,+ prefix="Readable Name",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"database": "ANALYTICS", "schema": ""},+ )+ table = DataWarehouseTable.objects.create(+ name="SALES.ORDERS",+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ external_data_source=source,+ options={+ DIRECT_SNOWFLAKE_CATALOG_OPTION: "ANALYTICS",+ DIRECT_SNOWFLAKE_SCHEMA_OPTION: "SALES",+ DIRECT_SNOWFLAKE_TABLE_OPTION: "ORDERS",+ },+ columns={"id": {"clickhouse": "String", "hogql": "StringDatabaseField"}},+ )++ definition = table.hogql_definition()++ assert isinstance(definition, DirectSnowflakeTable)+ assert definition.name == "SALES.ORDERS"+ assert definition.snowflake_catalog == "ANALYTICS"+ assert definition.snowflake_schema == "SALES"+ assert definition.snowflake_table_name == "ORDERS"+ assert definition.to_printed_snowflake(context=None) == '"ANALYTICS"."SALES"."ORDERS"'++ def test_direct_snowflake_table_requires_schema_when_printing(self):+ source = ExternalDataSource.objects.create(+ source_id="source-id",+ connection_id="connection-id",+ destination_id="destination-id",+ team=self.team,+ sync_frequency=ExternalDataSource.SyncFrequency.DAILY,+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.SNOWFLAKE,+ prefix="Readable Name",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={},+ )+ table = DataWarehouseTable.objects.create(+ name="ORDERS",+ format=DataWarehouseTable.TableFormat.Parquet,+ team=self.team,+ external_data_source=source,+ columns={"id": {"clickhouse": "String", "hogql": "StringDatabaseField"}},+ )++ definition = table.hogql_definition()++ assert isinstance(definition, DirectSnowflakeTable)+ with pytest.raises(QueryError, match="Direct Snowflake tables require a schema name."):+ definition.to_printed_snowflake(context=None)+def test_postgres_column_to_dwh_column_supports_struct_types(self):column = postgres_column_to_dwh_column("membership",diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.pyindex 7cac29adc7c5..04ebe4218856 100644--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py@@ -29,6 +29,7 @@ from products.data_warehouse.backend.facade.api import (get_postgres_source_location,hide_direct_mysql_table,hide_direct_postgres_table,+ hide_direct_snowflake_table,is_any_external_data_schema_paused,is_cdc_enabled_for_team,is_xmin_enabled_for_team,@@ -36,6 +37,7 @@ from products.data_warehouse.backend.facade.api import (reconcile_webhook_events,reproject_direct_mysql_table,reproject_direct_postgres_table,+ reproject_direct_snowflake_table,sync_cdc_extraction_schedule,sync_external_data_job_workflow,trigger_external_data_workflow,@@ -171,14 +173,17 @@ class RowFiltersField(serializers.JSONField):"""Typed JSON field for the list of `{column, operator, value}` row-filter predicates."""-def unsupported_row_filter_reason(*, is_direct_postgres: bool, is_cdc: bool) -> str | None:+def unsupported_row_filter_reason(*, is_direct_query: bool, is_cdc: bool) -> str | None:"""Row filters are only enforced on snapshot-style syncs, which apply them as a `WHERE`- clause. Direct Postgres queries tables live and CDC streams WAL changes — both bypass that+ clause. Direct-query sources read tables live and CDC streams WAL changes — both bypass thatquery, so a saved filter would silently leave excluded rows visible. Reject those up front.++ This covers every direct engine (Postgres, MySQL, Snowflake): none of the live-query executors+ apply the predicates, so accepting a filter would be a silent data-restriction bypass."""- if is_direct_postgres:+ if is_direct_query:return (- "Row filters are not supported for direct Postgres sources — "+ "Row filters are not supported for direct-query sources — ""tables are queried live and filters cannot be enforced at the source.")if is_cdc:@@ -579,7 +584,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):incoming_sync_type == ExternalDataSchema.SyncType.CDC if "sync_type" in data else instance.is_cdc)if reason := unsupported_row_filter_reason(- is_direct_postgres=instance.source.is_direct_postgres, is_cdc=target_is_cdc+ is_direct_query=instance.source.is_direct_query, is_cdc=target_is_cdc):raise ValidationError(reason)try:@@ -859,9 +864,12 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):newly_exposed = should_sync is True and instance.should_sync is Falseprojection_needs_refresh = enabled_columns_changed and instance.table is not None and instance.should_syncif newly_exposed or projection_needs_refresh:- reproject = (- reproject_direct_postgres_table if source.is_direct_postgres else reproject_direct_mysql_table- )+ if source.is_direct_postgres:+ reproject = reproject_direct_postgres_table+ elif source.is_direct_snowflake:+ reproject = reproject_direct_snowflake_table+ else:+ reproject = reproject_direct_mysql_tablevalidated_data["table"] = reproject(instance,source=source,@@ -871,6 +879,8 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):if should_sync is False and instance.should_sync is True:if source.is_direct_postgres:hide_direct_postgres_table(instance.table)+ elif source.is_direct_snowflake:+ hide_direct_snowflake_table(instance.table)else:hide_direct_mysql_table(instance.table)elif enabled_columns_changed and instance.table is not None and instance.should_sync:@@ -1328,6 +1338,8 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if instance.source.is_direct_query:if instance.source.is_direct_postgres:hide_direct_postgres_table(instance.table)+ elif instance.source.is_direct_snowflake:+ hide_direct_snowflake_table(instance.table)else:hide_direct_mysql_table(instance.table)instance.should_sync = Falsediff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 00777a7ab1e8..0a8d01a54da9 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -36,6 +36,7 @@ from posthog.schema import ()from posthog.hogql.database.database import Database+from posthog.hogql.direct_sql.capability import direct_capable_source_typesfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action@@ -78,6 +79,7 @@ from products.data_warehouse.backend.facade.api import (reconcile_mysql_schemas,reconcile_postgres_schemas,reconcile_refresh_name_substitutions as reconcile_postgres_refresh_name_substitutions,+ reconcile_snowflake_schemas,source_namespace_is_blank,sync_cdc_extraction_schedule,sync_discover_schemas_schedule,@@ -85,6 +87,7 @@ from products.data_warehouse.backend.facade.api import (trigger_external_data_source_workflow,upsert_direct_mysql_table,upsert_direct_postgres_table,+ upsert_direct_snowflake_table,)from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfigfrom products.data_warehouse.backend.presentation.views.external_data_schema import (@@ -99,6 +102,7 @@ from products.revenue_analytics.backend.facade.api import ensure_person_join, refrom products.warehouse_sources.backend.facade.api import (mysql_columns_to_dwh_columns,postgres_columns_to_dwh_columns,+ snowflake_columns_to_dwh_columns,validate_source_prefix,)from products.warehouse_sources.backend.facade.models import (@@ -440,7 +444,33 @@ def get_mysql_source_table_location()+def get_snowflake_source_table_location(+ *,+ schema_name: str,+ source_schema: SourceSchema | None,+ default_schema: str | None,+ default_catalog: str | None = None,+) -> tuple[str | None, str, str]:+ catalog = source_schema.source_catalog if source_schema and source_schema.source_catalog else default_catalog+ if source_schema and source_schema.source_schema and source_schema.source_table_name:+ return catalog, source_schema.source_schema, source_schema.source_table_name++ normalized_default_schema = (+ default_schema.strip() if isinstance(default_schema, str) and default_schema.strip() else None+ )+ if normalized_default_schema is None and "." in schema_name:+ inferred_schema, inferred_table_name = schema_name.split(".", 1)+ return catalog, inferred_schema, inferred_table_name++ return catalog, normalized_default_schema or "", schema_name++CUSTOM_SOURCE_LIMIT_MESSAGE = f"You can create at most {MAX_CUSTOM_SOURCES_PER_TEAM} custom sources per project."+DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = (+ "Direct query mode is currently supported only for Postgres, MySQL, and Snowflake sources."+)+# Engines surfaced on a direct connection's `connection_metadata.engine` (duckdb backs direct Postgres).+DIRECT_CONNECTION_ENGINE_CHOICES = ["duckdb", "postgres", "mysql", "snowflake"]def count_active_custom_sources(team_id: int) -> int:@@ -474,7 +504,7 @@ class ExternalDataSourceConnectionMetadataSerializer(serializers.Serializer):read_only=True,required=False,allow_null=True,- choices=["duckdb", "postgres", "mysql"],+ choices=DIRECT_CONNECTION_ENGINE_CHOICES,help_text="Backend engine detected for the direct connection.",)function_source = serializers.CharField(@@ -496,7 +526,7 @@ class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):source="connection_metadata.engine",read_only=True,allow_null=True,- choices=["duckdb", "postgres", "mysql"],+ choices=DIRECT_CONNECTION_ENGINE_CHOICES,help_text="Backend engine detected for the direct connection.",)@@ -659,7 +689,7 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerread_only=True,allow_null=True,required=False,- choices=["duckdb", "postgres", "mysql"],+ choices=DIRECT_CONNECTION_ENGINE_CHOICES,help_text="Backend engine detected for the direct connection.",)revenue_analytics_config = ExternalDataSourceRevenueAnalyticsConfigSerializer(@@ -1068,6 +1098,12 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializersource_schemas=discovered_schemas,team_id=instance.team_id,)+ elif updated_source.source_type == ExternalDataSourceType.SNOWFLAKE:+ reconcile_snowflake_schemas(+ source=updated_source,+ source_schemas=discovered_schemas,+ team_id=instance.team_id,+ )else:reconcile_mysql_schemas(source=updated_source,@@ -1569,13 +1605,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi# It avoids a second live credential round-trip — and the confusing failure mode where the# first check passes but a transient blip fails the second, leaving nothing created.is_direct_query = access_method == ExternalDataSource.AccessMethod.DIRECT- is_direct_postgres = is_direct_query and source_type == ExternalDataSourceType.POSTGRESis_direct_mysql = is_direct_query and source_type == ExternalDataSourceType.MYSQL+ is_direct_snowflake = is_direct_query and source_type == ExternalDataSourceType.SNOWFLAKE- if is_direct_query and not (is_direct_postgres or is_direct_mysql):+ if is_direct_query and source_type not in direct_capable_source_types():return Response(status=status.HTTP_400_BAD_REQUEST,- data={"message": "Direct query mode is currently supported only for Postgres and MySQL sources."},+ data={"message": DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE},)if is_direct_query:@@ -1853,6 +1889,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource_schema=source_schema,default_schema=default_source_schema or source_config.to_dict().get("database"),)+ elif is_direct_snowflake:+ metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (+ get_snowflake_source_table_location(+ schema_name=schema_name,+ source_schema=source_schema,+ default_schema=default_source_schema,+ default_catalog=source_config.to_dict().get("database"),+ )+ )else:metadata_source_catalog = source_schema.source_catalog if source_schema else Nonemetadata_source_schema = source_schema.source_schema if source_schema else None@@ -1872,7 +1917,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif row_filters is not None:if reason := unsupported_row_filter_reason(- is_direct_postgres=new_source_model.is_direct_postgres, is_cdc=sync_type == "cdc"+ is_direct_query=new_source_model.is_direct_query, is_cdc=sync_type == "cdc"):new_source_model.delete()return Response(@@ -2019,6 +2064,24 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource_table_name=cast(str, metadata_source_table_name),)schema_model.save(update_fields=["table"])+ elif new_source_model.is_direct_snowflake and should_sync:+ schema_model.table = upsert_direct_snowflake_table(+ None,+ schema_name=schema_name,+ source=new_source_model,+ columns=filter_dwh_columns_by_enabled_columns(+ snowflake_columns_to_dwh_columns(source_schema.columns if source_schema else []),+ enabled_columns,+ source_schema.detected_primary_keys if source_schema else None,+ incremental_field,+ # Direct-snowflake columns are keyed by raw, case-sensitive source names.+ normalize=False,+ ),+ source_catalog=metadata_source_catalog,+ source_schema=cast(str, metadata_source_schema),+ source_table_name=cast(str, metadata_source_table_name),+ )+ schema_model.save(update_fields=["table"])if should_sync and new_source_model.supports_scheduled_sync:active_schemas.append(schema_model)@@ -2413,6 +2476,14 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi)if reconciled_deleted_schemas:schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})+ elif instance.source_type == ExternalDataSourceType.SNOWFLAKE:+ reconciled_deleted_schemas = reconcile_snowflake_schemas(+ source=instance,+ source_schemas=schemas,+ team_id=self.team_id,+ )+ if reconciled_deleted_schemas:+ schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})elif isinstance(source, (SQLSource, ClickHouseSource)) and source.supports_column_selection:# ClickHouse isn't a SQLSource but exposes the same column-selection# capability and reconcile hook, so it reuses this path.@@ -3447,10 +3518,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiaccess_method = request.data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)if access_method == ExternalDataSource.AccessMethod.DIRECT:- if source_type not in (ExternalDataSourceType.POSTGRES, ExternalDataSourceType.MYSQL):+ if source_type not in direct_capable_source_types():return Response(status=status.HTTP_400_BAD_REQUEST,- data={"message": "Direct query mode is currently supported only for Postgres and MySQL sources."},+ data={"message": DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE},)normalized_prefix = prefix.strip() if isinstance(prefix, str) else ""@@ -3603,7 +3674,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiExternalDataSource._base_manager.filter(team_id=self.team_id,access_method=ExternalDataSource.AccessMethod.DIRECT,- source_type__in=(ExternalDataSourceType.POSTGRES, ExternalDataSourceType.MYSQL),+ source_type__in=direct_capable_source_types(),).exclude(deleted=True).only("id", "prefix", "connection_metadata")diff --git a/products/data_warehouse/backend/snowflake_helpers.py b/products/data_warehouse/backend/snowflake_helpers.pynew file mode 100644index 000000000000..f7c1ca7dcc17--- /dev/null+++ b/products/data_warehouse/backend/snowflake_helpers.py@@ -0,0 +1,299 @@+"""Snowflake source helpers shared between warehouse and direct-query modes.++Direct-query-only utilities (DataWarehouseTable upserts, the `direct://snowflake`+url_pattern, the option keys that encode source location on a direct table) live+in `direct_snowflake.py`. Generic projection / `schema_metadata` builders live in+`posthog/temporal/data_imports/sources/common/sql/{projection,metadata}.py`.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from django.db.models import Q++import structlog++from products.data_warehouse.backend.direct_snowflake import (+ DIRECT_SNOWFLAKE_CATALOG_OPTION,+ DIRECT_SNOWFLAKE_SCHEMA_OPTION,+ DIRECT_SNOWFLAKE_TABLE_OPTION,+ hide_direct_snowflake_table,+ upsert_direct_snowflake_table,+)+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.util import (+ snowflake_column_to_dwh_column,+ snowflake_columns_to_dwh_columns,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import sql_schema_metadata+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import normalize_namespace+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.metadata import (+ extract_available_column_names,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.projection import (+ filter_columns_by_enabled_columns,+ filter_dwh_columns_by_enabled_columns,+ prune_enabled_columns,+)++if TYPE_CHECKING:+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema++log = structlog.get_logger(__name__)++type SnowflakeSourceLocation = tuple[str | None, str, str] # (catalog, schema, table_name)+++def get_default_snowflake_schema(source: ExternalDataSource) -> str | None:+ """Get the default schema for a Snowflake source, if any."""+ job_inputs = source.job_inputs or {}+ if "schema" in job_inputs:+ return normalize_namespace(job_inputs.get("schema"))+ return None+++def get_default_snowflake_catalog(source: ExternalDataSource) -> str | None:+ database = (source.job_inputs or {}).get("database")+ return database if isinstance(database, str) and database.strip() else None+++def snowflake_schema_metadata_to_dwh_columns(schema_metadata: dict[str, Any] | None) -> dict[str, dict[str, Any]]:+ resolved: dict[str, dict[str, Any]] = {}+ if not schema_metadata:+ return resolved+ columns = schema_metadata.get("columns")+ if not isinstance(columns, list):+ return resolved+ for column in columns:+ if not isinstance(column, dict):+ continue+ column_name = column.get("name")+ snowflake_type = column.get("data_type")+ nullable = bool(column.get("is_nullable"))+ if not isinstance(column_name, str) or not isinstance(snowflake_type, str):+ continue+ resolved[column_name] = snowflake_column_to_dwh_column(column_name, snowflake_type, nullable)+ return resolved+++def reproject_direct_snowflake_table(+ schema_row: Any,+ *,+ source: ExternalDataSource,+ enabled_columns: list[str] | None,+) -> Any:+ """Rebuild the direct-query `DataWarehouseTable` with a fresh column projection — used on+ column-picker save and on `should_sync` False → True. No re-sync needed in direct mode.+ """+ source_catalog, source_schema, source_table_name = get_snowflake_source_location(+ schema_name=schema_row.name,+ schema_metadata=schema_row.schema_metadata,+ default_catalog=get_default_snowflake_catalog(source),+ default_schema=get_default_snowflake_schema(source),+ )+ return upsert_direct_snowflake_table(+ schema_row.table,+ schema_name=schema_row.name,+ source=source,+ columns=filter_dwh_columns_by_enabled_columns(+ snowflake_schema_metadata_to_dwh_columns(schema_row.schema_metadata),+ enabled_columns,+ schema_row.primary_key_columns,+ schema_row.incremental_field,+ # Direct-snowflake columns are keyed by raw, case-sensitive source names.+ normalize=False,+ ),+ source_catalog=source_catalog,+ source_schema=source_schema,+ source_table_name=source_table_name,+ )+++def get_snowflake_source_location(+ *,+ schema_name: str,+ schema_metadata: dict[str, Any] | None = None,+ default_catalog: str | None = None,+ default_schema: str | None = None,+) -> SnowflakeSourceLocation:+ """Resolve (catalog, schema, table_name) for a Snowflake source."""+ source_catalog = schema_metadata.get("source_catalog") if isinstance(schema_metadata, dict) else None+ source_schema = schema_metadata.get("source_schema") if isinstance(schema_metadata, dict) else None+ source_table_name = schema_metadata.get("source_table_name") if isinstance(schema_metadata, dict) else None+ normalized_default_schema = normalize_namespace(default_schema)++ catalog = source_catalog if isinstance(source_catalog, str) and source_catalog.strip() else default_catalog+ if isinstance(source_schema, str) and isinstance(source_table_name, str):+ return catalog, source_schema, source_table_name++ if normalized_default_schema is None and "." in schema_name:+ inferred_schema, inferred_table_name = schema_name.split(".", 1)+ return catalog, inferred_schema, inferred_table_name++ return catalog, normalized_default_schema or "", schema_name+++def get_snowflake_source_location_for_schema_model(+ *,+ schema_name: str,+ sync_type_config: dict[str, Any] | None = None,+ table_options: dict[str, Any] | None = None,+ default_catalog: str | None = None,+ default_schema: str | None = None,+) -> SnowflakeSourceLocation:+ schema_metadata = (+ sync_type_config.get("schema_metadata")+ if isinstance(sync_type_config, dict) and isinstance(sync_type_config.get("schema_metadata"), dict)+ else None+ )+ if schema_metadata is not None:+ return get_snowflake_source_location(+ schema_name=schema_name,+ schema_metadata=schema_metadata,+ default_catalog=default_catalog,+ default_schema=default_schema,+ )++ opts = table_options if isinstance(table_options, dict) else {}+ table_source_catalog = opts.get(DIRECT_SNOWFLAKE_CATALOG_OPTION)+ table_source_schema = opts.get(DIRECT_SNOWFLAKE_SCHEMA_OPTION)+ table_source_table_name = opts.get(DIRECT_SNOWFLAKE_TABLE_OPTION)++ if isinstance(table_source_schema, str) and isinstance(table_source_table_name, str):+ return (+ table_source_catalog if isinstance(table_source_catalog, str) else default_catalog,+ table_source_schema,+ table_source_table_name,+ )++ return get_snowflake_source_location(+ schema_name=schema_name,+ schema_metadata=None,+ default_catalog=default_catalog,+ default_schema=default_schema,+ )+++def reconcile_snowflake_schemas(+ *,+ source: ExternalDataSource,+ source_schemas: list[SourceSchema],+ team_id: int,+) -> list[str]:+ """Persist `schema_metadata` on every Snowflake row + (direct mode only) upsert its live-query+ `DataWarehouseTable`. Returns stale schema names that got soft-deleted (direct only)."""+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema++ is_direct = source.is_direct_query+ source_schema_names = [s.name for s in source_schemas]+ default_catalog = get_default_snowflake_catalog(source)+ default_schema = get_default_snowflake_schema(source)+ schema_models = {+ s.name: s for s in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False)+ }++ schema_models_by_location: dict[SnowflakeSourceLocation, ExternalDataSchema] = {}+ for schema_model in schema_models.values():+ location = get_snowflake_source_location_for_schema_model(+ schema_name=schema_model.name,+ sync_type_config=schema_model.sync_type_config,+ table_options=schema_model.table.options if schema_model.table is not None else None,+ default_catalog=default_catalog,+ default_schema=default_schema,+ )+ schema_models_by_location.setdefault(location, schema_model)++ for source_schema in source_schemas:+ resolved = get_snowflake_source_location(+ schema_name=source_schema.name,+ schema_metadata={+ "source_catalog": source_schema.source_catalog,+ "source_schema": source_schema.source_schema,+ "source_table_name": source_schema.source_table_name,+ },+ default_catalog=default_catalog,+ default_schema=default_schema,+ )+ matched: ExternalDataSchema | None = schema_models.get(source_schema.name)+ if matched is None:+ matched = schema_models_by_location.get(resolved)+ if matched is None:+ continue++ resolved_catalog, resolved_schema, resolved_table = resolved++ # Metadata holds the full column list (column-picker UI); projection lives on `enabled_columns`.+ schema_metadata = sql_schema_metadata(+ source_schema.columns,+ source_schema.foreign_keys,+ source_catalog=resolved_catalog,+ source_schema=resolved_schema,+ source_table_name=resolved_table,+ )+ new_sync_type_config = {**(matched.sync_type_config or {}), "schema_metadata": schema_metadata}+ # Persist the detected primary key without clobbering a value already stored — e.g. an+ # explicit override set during creation or a prior refresh.+ if source_schema.detected_primary_keys and not new_sync_type_config.get("primary_key_columns"):+ new_sync_type_config["primary_key_columns"] = source_schema.detected_primary_keys+ matched.sync_type_config = new_sync_type_config+ update_fields = ["sync_type_config", "updated_at"]++ # Drop dead columns so next sync doesn't emit `SELECT … missing_col`.+ available_names = extract_available_column_names(schema_metadata)+ pruned_enabled_columns, removed_columns = prune_enabled_columns(matched.enabled_columns, available_names)+ if removed_columns:+ log.info(+ "snowflake.reconcile_schemas.pruned_enabled_columns",+ source_id=str(source.id),+ schema_id=str(matched.id),+ schema_name=matched.name,+ removed_columns=removed_columns,+ )+ matched.enabled_columns = pruned_enabled_columns+ update_fields.append("enabled_columns")+ matched.save(update_fields=update_fields)++ if not is_direct:+ # Warehouse mode: the ingestion workflow manages `DataWarehouseTable` itself.+ continue++ if not matched.should_sync:+ hide_direct_snowflake_table(matched.table)+ continue++ projected_columns = filter_columns_by_enabled_columns(+ source_schema.columns,+ matched.enabled_columns,+ source_schema.detected_primary_keys,+ matched.incremental_field,+ )+ table_model = upsert_direct_snowflake_table(+ matched.table,+ schema_name=source_schema.name,+ source=source,+ columns=snowflake_columns_to_dwh_columns(projected_columns),+ source_catalog=resolved_catalog,+ source_schema=resolved_schema,+ source_table_name=resolved_table,+ )+ if matched.table_id != table_model.id:+ matched.table = table_model+ matched.save(update_fields=["table"])++ if not is_direct:+ # Warehouse mode delegates add/delete to `sync_old_schemas_with_new_schemas`.+ return []++ stale_names: list[str] = []+ stale = ExternalDataSchema.objects.filter(+ Q(team_id=team_id, source_id=source.id),+ Q(deleted=False) | Q(table__deleted=False),+ ).exclude(name__in=source_schema_names)+ for s in stale:+ hide_direct_snowflake_table(s.table)+ if not s.deleted:+ s.soft_delete()+ stale_names.append(s.name)+ return stale_namesdiff --git a/products/data_warehouse/backend/tests/api/test_external_data_schema.py b/products/data_warehouse/backend/tests/api/test_external_data_schema.pyindex 3763d3b3a3ef..4149c346809d 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_schema.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_schema.py@@ -26,6 +26,7 @@ from posthog.temporal.common.schedule import describe_schedulefrom products.data_modeling.backend.models import Edge, Nodefrom products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_PATTERN+from products.data_warehouse.backend.direct_snowflake import DIRECT_SNOWFLAKE_URL_PATTERNfrom products.data_warehouse.backend.logic.external_data_source.webhooks import WebhookHogFunctionCreateResultfrom products.data_warehouse.backend.tests.api.utils import create_external_data_source_okfrom products.warehouse_sources.backend.facade.models import (@@ -2306,6 +2307,131 @@ class TestUpdateExternalDataSchema:assert schema.should_sync is Falseassert DataWarehouseTable.raw_objects.get(pk=table.pk).deleted is True+ def test_update_schema_exposes_direct_snowflake_table_without_sync_type(+ self, team, user, client: HttpClient, temporal+ ):+ # Exercises the Snowflake reproject branch: a non-Postgres direct source must rebuild via the+ # Snowflake helper (DIRECT_SNOWFLAKE_URL_PATTERN), not silently fall through to the MySQL one.+ client.force_login(user)+ source = ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ status=ExternalDataSource.Status.RUNNING,+ source_type=ExternalDataSourceType.SNOWFLAKE,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"database": "ANALYTICS"},+ )+ schema = ExternalDataSchema.objects.create(+ team=team,+ source=source,+ name="SALES.ACCOUNTS",+ should_sync=False,+ sync_type=None,+ sync_type_config={+ "schema_metadata": {+ "columns": [{"name": "ID", "data_type": "NUMBER", "is_nullable": False}],+ "foreign_keys": [],+ "source_catalog": "ANALYTICS",+ "source_schema": "SALES",+ "source_table_name": "ACCOUNTS",+ }+ },+ )++ with (+ mock.patch(+ "products.data_warehouse.backend.presentation.views.external_data_schema.external_data_workflow_exists"+ ) as mock_external_data_workflow_exists,+ mock.patch(+ "products.data_warehouse.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"+ ) as mock_sync_external_data_job_workflow,+ ):+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={+ "id": str(schema.id),+ "name": schema.name,+ "should_sync": True,+ "incremental": False,+ "status": "Completed",+ "sync_type": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "sync_frequency": "6hour",+ "sync_time_of_day": "00:00:00",+ },+ content_type="application/json",+ )++ assert response.status_code == 200+ schema.refresh_from_db()+ assert schema.should_sync is True+ assert schema.table is not None+ assert schema.table.deleted is False+ assert schema.table.url_pattern == DIRECT_SNOWFLAKE_URL_PATTERN+ mock_external_data_workflow_exists.assert_not_called()+ mock_sync_external_data_job_workflow.assert_not_called()++ def test_update_schema_hides_direct_snowflake_table_when_disabled(self, team, user, client: HttpClient, temporal):+ client.force_login(user)+ source = ExternalDataSource.objects.create(+ team=team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ status=ExternalDataSource.Status.RUNNING,+ source_type=ExternalDataSourceType.SNOWFLAKE,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"database": "ANALYTICS"},+ )+ table = DataWarehouseTable.objects.create(+ name="SALES.ACCOUNTS",+ format=DataWarehouseTable.TableFormat.Parquet,+ team=team,+ url_pattern=DIRECT_SNOWFLAKE_URL_PATTERN,+ external_data_source=source,+ columns={"ID": {"clickhouse": "Int64", "hogql": "integer", "valid": True}},+ )+ schema = ExternalDataSchema.objects.create(+ team=team,+ source=source,+ name="SALES.ACCOUNTS",+ should_sync=True,+ sync_type=None,+ table=table,+ sync_type_config={+ "schema_metadata": {+ "columns": [{"name": "ID", "data_type": "NUMBER", "is_nullable": False}],+ "foreign_keys": [],+ }+ },+ )++ with mock.patch("products.data_warehouse.backend.presentation.views.external_data_schema.Database.create_for"):+ response = client.patch(+ f"/api/environments/{team.pk}/external_data_schemas/{schema.id}",+ data={+ "id": str(schema.id),+ "name": schema.name,+ "should_sync": False,+ "incremental": False,+ "status": "Completed",+ "sync_type": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "sync_frequency": "6hour",+ "sync_time_of_day": "00:00:00",+ },+ content_type="application/json",+ )++ assert response.status_code == 200+ schema.refresh_from_db()+ assert schema.should_sync is False+ assert DataWarehouseTable.raw_objects.get(pk=table.pk).deleted is True+def test_update_schema_cdc_with_blank_source_schema_uses_physical_schema_metadata(self, team, user, client: HttpClient, temporal):@@ -3201,10 +3327,19 @@ class TestExternalDataSchemaRowFilters(APIBaseTest):if expected_message:assert expected_message in str(response.json())- def test_row_filters_rejected_for_direct_postgres_source(self):+ @parameterized.expand(+ [+ ("postgres", ExternalDataSourceType.POSTGRES),+ ("mysql", ExternalDataSourceType.MYSQL),+ ("snowflake", ExternalDataSourceType.SNOWFLAKE),+ ]+ )+ def test_row_filters_rejected_for_direct_query_sources(self, _name, source_type):+ # No direct-query executor enforces row filters (they all read the table live), so accepting+ # a filter for any direct engine would silently leave excluded rows visible.source = ExternalDataSource.objects.create(team=self.team,- source_type=ExternalDataSourceType.POSTGRES,+ source_type=source_type,access_method=ExternalDataSource.AccessMethod.DIRECT,job_inputs={"host": "h", "port": "5432", "database": "d", "user": "u", "password": "p", "schema": "public"},)@@ -3216,7 +3351,7 @@ class TestExternalDataSchemaRowFilters(APIBaseTest):)response = self._patch(schema, [{"column": "id", "operator": ">", "value": 10}])assert response.status_code == 400- assert "not supported for direct Postgres" in str(response.json())+ assert "not supported for direct-query sources" in str(response.json())def test_row_filters_rejected_for_cdc_schema(self):source = ExternalDataSource.objects.create(diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.pyindex f86aacc925d9..724de5d4757c 100644--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py@@ -1657,6 +1657,18 @@ class TestExternalDataSource(APIBaseTest):job_inputs={"host": "localhost", "password": "secret"},connection_metadata={"engine": "mysql", "database": "warehouse", "version": "9.6.0"},)+ snowflake_source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Snowflake",+ created_by=self.user,+ prefix="Analytics Snowflake",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ job_inputs={"account_id": "acct", "database": "TPCH_SF1"},+ connection_metadata={"engine": "snowflake", "database": "TPCH_SF1"},+ )response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")@@ -1665,6 +1677,11 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(payload,[+ {+ "id": str(snowflake_source.pk),+ "prefix": "Analytics Snowflake",+ "engine": "snowflake",+ },{"id": str(postgres_source.pk),"prefix": "Primary database",@@ -2983,7 +3000,7 @@ class TestExternalDataSource(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("not supported for direct Postgres", str(response.json()))+ self.assertIn("not supported for direct-query sources", str(response.json()))self.assertFalse(ExternalDataSource.objects.filter(team_id=self.team.pk).exists())@patch("products.data_warehouse.backend.presentation.views.external_data_source.SourceRegistry.get_source")@@ -3758,7 +3775,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json(),- {"message": "Direct query mode is currently supported only for Postgres and MySQL sources."},+ {"message": "Direct query mode is currently supported only for Postgres, MySQL, and Snowflake sources."},)def test_source_prefix_rejects_direct_unsupported_source_type(self):@@ -3774,7 +3791,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json(),- {"message": "Direct query mode is currently supported only for Postgres and MySQL sources."},+ {"message": "Direct query mode is currently supported only for Postgres, MySQL, and Snowflake sources."},)def test_source_prefix_accepts_direct_mysql(self):diff --git a/products/data_warehouse/frontend/shared/components/SourceIcon.tsx b/products/data_warehouse/frontend/shared/components/SourceIcon.tsxindex 8577222640ab..a6f4343c754b 100644--- a/products/data_warehouse/frontend/shared/components/SourceIcon.tsx+++ b/products/data_warehouse/frontend/shared/components/SourceIcon.tsx@@ -78,7 +78,7 @@ export function SourceIcon({disableTooltip = false,}: {type: string- engine?: 'duckdb' | 'postgres' | 'mysql' | null+ engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | nullsize?: 'xsmall' | 'small' | 'medium'sizePx?: numberdisableTooltip?: booleandiff --git a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.tsindex 2f140558753c..5259125c0a9d 100644--- a/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts+++ b/products/data_warehouse/frontend/shared/components/forms/schemaGroupingUtils.ts@@ -1,7 +1,7 @@import { groupBy } from 'lib/utils/arrays'/** Source types that support `access_method: 'direct'` (live querying without syncing to the warehouse). */-export const DIRECT_QUERY_SOURCE_TYPES = ['Postgres', 'MySQL'] as const+export const DIRECT_QUERY_SOURCE_TYPES = ['Postgres', 'MySQL', 'Snowflake'] as constexport function supportsDirectQuery(sourceType: string | null | undefined): boolean {return !!sourceType && DIRECT_QUERY_SOURCE_TYPES.includes(sourceType as (typeof DIRECT_QUERY_SOURCE_TYPES)[number])diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex dfd0262f6910..cf2c85f3807f 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.models.util import (mysql_columns_to_dwh_columns,postgres_column_to_dwh_column,postgres_columns_to_dwh_columns,+ snowflake_columns_to_dwh_columns,validate_source_prefix,validate_warehouse_table_url_pattern,)@@ -49,6 +50,7 @@ __all__ = ["mysql_columns_to_dwh_columns","postgres_column_to_dwh_column","postgres_columns_to_dwh_columns",+ "snowflake_columns_to_dwh_columns","validate_source_prefix","validate_warehouse_table_url_pattern",]diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex 67c5e5d5af47..603cae61d48f 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -89,6 +89,10 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFielddef is_direct_mysql(self) -> bool:return self.is_direct_query and self.source_type == ExternalDataSourceType.MYSQL+ @property+ def is_direct_snowflake(self) -> bool:+ return self.is_direct_query and self.source_type == ExternalDataSourceType.SNOWFLAKE+@propertydef direct_engine(self) -> str | None:"""The direct-SQL engine for this source's type, or None if no engine maps to it.diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.pyindex 2f59cb49230e..d8a417ff2eaf 100644--- a/products/warehouse_sources/backend/models/table.py+++ b/products/warehouse_sources/backend/models/table.py@@ -16,6 +16,7 @@ from posthog.hogql.constants import HogQLQuerySettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.direct_mysql_table import DirectMySQLTablefrom posthog.hogql.database.direct_postgres_table import DirectPostgresTable+from posthog.hogql.database.direct_snowflake_table import DirectSnowflakeTablefrom posthog.hogql.database.models import DatabaseField, FieldOrTable, StructDatabaseFieldfrom posthog.hogql.database.s3_table import (DataWarehouseTable as HogQLDataWarehouseTable,@@ -38,6 +39,9 @@ from products.data_warehouse.backend.facade.sources import (DIRECT_POSTGRES_CATALOG_OPTION,DIRECT_POSTGRES_SCHEMA_OPTION,DIRECT_POSTGRES_TABLE_OPTION,+ DIRECT_SNOWFLAKE_CATALOG_OPTION,+ DIRECT_SNOWFLAKE_SCHEMA_OPTION,+ DIRECT_SNOWFLAKE_TABLE_OPTION,)from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.util import (@@ -503,7 +507,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletdef hogql_definition(self, modifiers: Optional["HogQLQueryModifiers"] = None- ) -> HogQLDataWarehouseTable | DirectPostgresTable | DirectMySQLTable:+ ) -> HogQLDataWarehouseTable | DirectPostgresTable | DirectMySQLTable | DirectSnowflakeTable:columns = self.columns or {}fields: dict[str, FieldOrTable] = {}@@ -585,6 +589,33 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Deletconnection_metadata=self.external_data_source.connection_metadata,)+ if self.external_data_source and self.external_data_source.is_direct_snowflake:+ job_inputs = self.external_data_source.job_inputs or {}+ snowflake_catalog = (+ self.options.get(DIRECT_SNOWFLAKE_CATALOG_OPTION)+ if isinstance(self.options.get(DIRECT_SNOWFLAKE_CATALOG_OPTION), str)+ else job_inputs.get("database")+ )+ snowflake_schema = (+ self.options.get(DIRECT_SNOWFLAKE_SCHEMA_OPTION)+ if isinstance(self.options.get(DIRECT_SNOWFLAKE_SCHEMA_OPTION), str)+ else job_inputs.get("schema", "")+ )+ snowflake_table_name = (+ self.options.get(DIRECT_SNOWFLAKE_TABLE_OPTION)+ if isinstance(self.options.get(DIRECT_SNOWFLAKE_TABLE_OPTION), str)+ else self.name+ )+ return DirectSnowflakeTable(+ name=self.name,+ fields=fields,+ snowflake_catalog=snowflake_catalog,+ snowflake_schema=snowflake_schema,+ snowflake_table_name=snowflake_table_name,+ external_data_source_id=str(self.external_data_source_id),+ connection_metadata=self.external_data_source.connection_metadata,+ )+# Replace fields with any redefined fields if they existexternal_table_fields = external_tables.get(self.table_name_without_prefix())default_fields = external_tables.get("*", {})diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex c6fb96594115..f69bafc713b3 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -474,6 +474,41 @@ def mysql_columns_to_dwh_columns(columns: list[tuple[str, str, bool]]) -> dict[s}+def snowflake_column_to_dwh_column(_column_name: str, snowflake_type: str, nullable: bool) -> dict[str, Any]:+ normalized_type = snowflake_type.lower()++ if normalized_type.startswith("number"):+ clickhouse_type = "Decimal"+ elif normalized_type.startswith("float"):+ clickhouse_type = "Float64"+ elif normalized_type.startswith("boolean"):+ clickhouse_type = "Bool"+ elif normalized_type.startswith("date"):+ clickhouse_type = "Date"+ elif normalized_type.startswith("timestamp"):+ clickhouse_type = "DateTime64"+ else:+ # variant/object/array (and anything unrecognized) map to String.+ clickhouse_type = "String"++ if nullable:+ clickhouse_type = f"Nullable({clickhouse_type})"++ raw_clickhouse_type = clean_type(clickhouse_type)+ return {+ "clickhouse": clickhouse_type,+ "hogql": CLICKHOUSE_TYPE_TO_HOGQL_LABEL.get(raw_clickhouse_type, "string"),+ "valid": True,+ }+++def snowflake_columns_to_dwh_columns(columns: list[tuple[str, str, bool]]) -> dict[str, dict[str, Any]]:+ return {+ column_name: snowflake_column_to_dwh_column(column_name, snowflake_type, nullable)+ for column_name, snowflake_type, nullable in columns+ }++def _is_safe_public_ip(host: str) -> bool:ip = ip_address(host)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex ffad50eb00fb..f920b90327c7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -130,7 +130,9 @@ def source_requires_ssl(source: ExternalDataSource, source_config: Any = None) -return Falseif source_config is not None:- ssh_tunnel = source_config.ssh_tunnel+ # Not every source config carries an SSH tunnel (e.g. Snowflake), and the param is typed+ # `Any` — only the tunnel opt-out can relax the SSL requirement, so its absence means "required".+ ssh_tunnel = getattr(source_config, "ssh_tunnel", None)if ssh_tunnel is not None and ssh_tunnel.enabled and not ssh_tunnel.require_tls.enabled:return Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.pyindex d2d46a2fb74d..a44e6f86a440 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py@@ -178,6 +178,19 @@ def _parse_clustering_key_leading_column(clustering_key: str | None) -> str | Noreturn leading.upper()+def get_connection_metadata(config: SnowflakeSourceConfig) -> dict[str, str | None]:+ """Connection metadata persisted on a direct-query source for the HogQL executor."""+ return {+ "engine": "snowflake",+ "account_id": config.account_id,+ "warehouse": config.warehouse,+ "database": config.database,+ "schema": normalize_namespace(config.schema),+ "role": config.role,+ "user": config.auth_type.user,+ }++class SnowflakeImplementation(SQLSourceImplementation[SnowflakeSourceConfig, snowflake.connector.SnowflakeConnection, Any]):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.pyindex 2b5c768d75e8..e7d4ff25afea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.py@@ -1,7 +1,10 @@-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, castfrom snowflake.connector.errors import DatabaseError, ForbiddenError, HttpError, ProgrammingError+if TYPE_CHECKING:+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,@@ -14,11 +17,16 @@ from posthog.schema import (from posthog.exceptions_capture import capture_exception+from products.data_warehouse.backend.facade.api import reconcile_snowflake_schemasfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldTypefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake import SnowflakeImplementation+from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake import (+ SnowflakeImplementation,+ get_connection_metadata as get_connection_metadata_snowflake,+)from products.warehouse_sources.backend.types import ExternalDataSourceType_SNOWFLAKE_IMPLEMENTATION = SnowflakeImplementation()@@ -261,6 +269,21 @@ class SnowflakeSource(SQLSource[SnowflakeSourceConfig]):"but view query produces": "A Snowflake view in your source is invalid — the columns it declares no longer match the columns its query returns. Please recreate the view in Snowflake so the two agree, then resync.",}+ def reconcile_schema_metadata(+ self,+ source: "ExternalDataSource",+ source_schemas: list[SourceSchema],+ team_id: int,+ ) -> list[str]:+ """Delegates to `reconcile_snowflake_schemas` so direct-query mode also rebuilds DWH tables."""+ return reconcile_snowflake_schemas(source=source, source_schemas=source_schemas, team_id=team_id)++ def get_connection_metadata(+ self, config: SnowflakeSourceConfig, team_id: int, require_ssl: bool = False+ ) -> dict[str, str | None]:+ # `require_ssl` keeps signature parity with Postgres/MySQL; Snowflake transport is always TLS.+ return get_connection_metadata_snowflake(config)+def validate_credentials(self, config: SnowflakeSourceConfig, team_id: int, schema_name: Optional[str] = None) -> tuple[bool, str | None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.pyindex 9cca1d4189b3..ec6c0691aa7c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py@@ -1,3 +1,5 @@+from datetime import UTC, datetime+import pytestfrom unittest.mock import MagicMock, patch@@ -6,12 +8,14 @@ from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsafrom snowflake.connector.errors import DatabaseError, HttpError+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (ColumnTypeCategory,ValidatedRowFilter,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres import source_requires_sslfrom products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake import (SnowflakeImplementation,_build_query,@@ -335,6 +339,14 @@ class TestConnect:assert mock_connect.call_args.kwargs["schema"] == "SALES"+class TestSourceRequiresSsl:+ def test_handles_config_without_ssh_tunnel(self):+ # `source_requires_ssl` is shared with Postgres/MySQL whose configs carry an `ssh_tunnel`.+ # The Snowflake config has none, so a naive `source_config.ssh_tunnel` access 500s on create.+ source = ExternalDataSource(created_at=datetime.now(UTC))+ assert source_requires_ssl(source, _make_config()) is True++# ---------------------------------------------------------------------------# Listing methods — they take a pre-opened connection# ---------------------------------------------------------------------------diff --git a/products/warehouse_sources/backend/types.py b/products/warehouse_sources/backend/types.pyindex 5ed59e5e6b62..d33bc21b9c70 100644--- a/products/warehouse_sources/backend/types.py+++ b/products/warehouse_sources/backend/types.py@@ -699,6 +699,7 @@ class ExternalDataSourceType(models.TextChoices):DIRECT_ENGINE_BY_SOURCE_TYPE: dict[str, str] = {ExternalDataSourceType.POSTGRES: "postgres",ExternalDataSourceType.MYSQL: "mysql",+ ExternalDataSourceType.SNOWFLAKE: "snowflake",}diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 31946f72ac78..29e9dc427657 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -1694,6 +1694,7 @@ export const AccessMethodEnumApi = {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql+ * * `snowflake` - snowflake*/export type EngineEnumApi = (typeof EngineEnumApi)[keyof typeof EngineEnumApi]@@ -1701,6 +1702,7 @@ export const EngineEnumApi = {Duckdb: 'duckdb',Postgres: 'postgres',Mysql: 'mysql',+ Snowflake: 'snowflake',} as constexport interface ExternalDataSourceRevenueAnalyticsConfigApi {@@ -1747,7 +1749,8 @@ export interface ExternalDataSourceSerializersApi {** * `duckdb` - duckdb* * `postgres` - postgres- * * `mysql` - mysql */+ * * `mysql` - mysql+ * * `snowflake` - snowflake */readonly engine: EngineEnumApi | null/** @nullable */readonly last_run_at: string | null@@ -2499,7 +2502,8 @@ export interface PatchedExternalDataSourceSerializersApi {** * `duckdb` - duckdb* * `postgres` - postgres- * * `mysql` - mysql */+ * * `mysql` - mysql+ * * `snowflake` - snowflake */readonly engine?: EngineEnumApi | null/** @nullable */readonly last_run_at?: string | null@@ -2614,7 +2618,8 @@ export interface ExternalDataSourceConnectionOptionApi {** * `duckdb` - duckdb* * `postgres` - postgres- * * `mysql` - mysql */+ * * `mysql` - mysql+ * * `snowflake` - snowflake */readonly engine: EngineEnumApi | null}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 27ade84f8ec5..1562786f5114 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18727,6 +18727,7 @@ export namespace Schemas {* * `duckdb` - duckdb* * `postgres` - postgres* * `mysql` - mysql+ * * `snowflake` - snowflake*/export type EngineEnum = typeof EngineEnum[keyof typeof EngineEnum];@@ -18735,6 +18736,7 @@ export namespace Schemas {Duckdb: 'duckdb',Postgres: 'postgres',Mysql: 'mysql',+ Snowflake: 'snowflake',} as const;/**@@ -22218,7 +22220,8 @@ export namespace Schemas {** * `duckdb` - duckdb* * `postgres` - postgres- * * `mysql` - mysql */+ * * `mysql` - mysql+ * * `snowflake` - snowflake */readonly engine: EngineEnum | null;}@@ -22970,7 +22973,8 @@ export namespace Schemas {** * `duckdb` - duckdb* * `postgres` - postgres- * * `mysql` - mysql */+ * * `mysql` - mysql+ * * `snowflake` - snowflake */readonly engine: EngineEnum | null;/** @nullable */readonly last_run_at: string | null;@@ -37173,7 +37177,8 @@ export namespace Schemas {** * `duckdb` - duckdb* * `postgres` - postgres- * * `mysql` - mysql */+ * * `mysql` - mysql+ * * `snowflake` - snowflake */readonly engine?: EngineEnum | null;/** @nullable */readonly last_run_at?: string | null;