: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 databricks source (#72848)
Tom Owers85522134e4f0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 574aecad6f30..e05ca40807bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -169,6 +169,7 @@ the row lists both.| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) || customerly | HTTP | requests | ✅ || dagster_cloud | HTTP (GraphQL) | requests | ✅ |+| databricks | DB protocol | databricks-sql-connector | ➖ || datadog | HTTP | requests | ✅ || dataforseo | HTTP | requests | ✅ || datahub | HTTP | requests | ✅ |@@ -842,7 +843,6 @@ doesn't conflict with concurrent PRs.- cube_cloud- curve- d2l_brightspace-- databricks- datascope- datorama- dayforcediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.pynew file mode 100644index 000000000000..5acda1b7f3f0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/databricks.py@@ -0,0 +1,486 @@+"""Databricks driver for PostHog's data-warehouse import pipeline.++Everything Databricks-specific — connection lifecycle (personal access+token vs OAuth M2M service principal auth), Unity Catalog+`information_schema` discovery, and the pipeline build — lives on+`DatabricksImplementation`. The source-class `DatabricksSource` is a thin+PostHog-layer wrapper that holds an instance and validates credentials.+"""++from __future__ import annotations++import collections+from collections.abc import Callable, Iterator+from contextlib import contextmanager+from typing import Any, Optional++import structlog+from databricks import sql as databricks_sql+from databricks.sdk.core import (+ Config as DatabricksSdkConfig,+ oauth_service_principal,+)+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import BacktickIdentifierQuoter+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import (+ SourceMetadata,+ SQLSourceImplementation,+ TableStats,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.incremental import (+ IncrementalFieldFilter,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.location import (+ normalize_namespace,+ resolve_source_location,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.query_builder import (+ ParamStyle,+ SelectQueryBuilder,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.databricks import (+ DatabricksSourceConfig,+)+from products.warehouse_sources.backend.types import IncrementalFieldType++__all__ = [+ "DatabricksImplementation",+ "clean_databricks_host",+ "filter_databricks_incremental_fields",+]++_IDENTIFIER_QUOTER = BacktickIdentifierQuoter()++# Databricks native (server-side) parameters use PEP-249 `named` paramstyle (`:name` + dict).+_QUERY_BUILDER = SelectQueryBuilder(quoter=_IDENTIFIER_QUOTER, param_style=ParamStyle.NAMED)++# Unity Catalog metadata schema present in every catalog; never user data.+DATABRICKS_SYSTEM_SCHEMA = "information_schema"++# `fetchmany_arrow` size. CloudFetch already chunks the result set into presigned cloud-storage+# files behind the cursor, so this only bounds how many rows we materialize per yielded batch.+DEFAULT_DATABRICKS_FETCH_SIZE = 10_000+++def filter_databricks_incremental_fields(+ columns: list[tuple[str, str, bool]],+) -> list[tuple[str, IncrementalFieldType, bool]]:+ results: list[tuple[str, IncrementalFieldType, bool]] = []+ for column_name, type, nullable in columns:+ type = type.lower()+ if type.startswith("timestamp"):+ # Covers TIMESTAMP and TIMESTAMP_NTZ.+ results.append((column_name, IncrementalFieldType.Timestamp, nullable))+ elif type == "date":+ results.append((column_name, IncrementalFieldType.Date, nullable))+ elif type in ("bigint", "int", "smallint", "tinyint") or type.startswith("decimal"):+ results.append((column_name, IncrementalFieldType.Numeric, nullable))++ return results+++def clean_databricks_host(host: str) -> str:+ """Normalize a pasted workspace URL down to the bare hostname the connector expects."""+ host = host.strip()+ for prefix in ("https://", "http://"):+ if host.startswith(prefix):+ host = host[len(prefix) :]+ return host.rstrip("/")+++def _split_display_name(display_name: str, default_schema: Optional[str]) -> tuple[Optional[str], str]:+ """Split a `schema.table` display name into `(schema, table)`.++ Multi-schema discovery qualifies every table as `schema.table`; a single-schema+ source keeps bare table names and falls back to the configured schema. The dotted+ form mirrors `resolve_source_location`'s self-heal so listing keys and per-row+ routing agree.+ """+ if "." in display_name:+ schema, _, table = display_name.partition(".")+ return (normalize_namespace(schema) or default_schema), table+ return default_schema, display_name+++class DatabricksImplementation(SQLSourceImplementation[DatabricksSourceConfig, Any, Any]):+ """Databricks driver implementation paired with `DatabricksSource`.++ One class owns everything Databricks-specific: the connection lifecycle+ (personal access token vs OAuth M2M service principal), the Unity Catalog+ `information_schema` batch queries used during schema listing, and the+ pipeline factory (`build_pipeline`).++ Databricks does not use the optional streaming-side hooks+ (`fetch_table_stats`, `fetch_average_row_size`, `get_table_metadata`) —+ it streams Arrow batches via `cursor.fetchmany_arrow()` (CloudFetch) and+ lets the base class return `None` for partition settings, matching the+ Snowflake driver.+ """++ # ------------------------------------------------------------------+ # Connection lifecycle+ # ------------------------------------------------------------------++ @contextmanager+ def connect(self, config: DatabricksSourceConfig) -> Iterator[Any]:+ """Open a Databricks SQL warehouse connection for the duration of the context.++ Branches on `config.auth_type.selection`: a personal access token is+ passed directly, while a service principal goes through the SDK's+ OAuth M2M credentials provider (1-hour tokens, auto-refreshed).++ Uses `config.catalog` as the session catalog so all two-part+ `schema.table` references resolve inside it; a blank schema+ (multi-schema import) leaves the session schema unset.+ """+ host = clean_databricks_host(config.host)+ auth_connect_args: dict[str, Any] = {}++ if config.auth_type.selection == "service_principal":+ client_id = config.auth_type.client_id+ client_secret = config.auth_type.client_secret++ def credentials_provider() -> Callable[[], dict[str, str]]:+ return oauth_service_principal(+ DatabricksSdkConfig(+ host=f"https://{host}",+ client_id=client_id,+ client_secret=client_secret,+ )+ )++ auth_connect_args = {"credentials_provider": credentials_provider}+ else:+ auth_connect_args = {"access_token": config.auth_type.access_token}++ log_connection_open(db_host=host, via="vendor_https")+ connection = databricks_sql.connect(+ server_hostname=host,+ http_path=config.http_path,+ catalog=config.catalog,+ # A blank schema (multi-schema import) must reach the connector as None, not "" —+ # `schema=""` would try `USE SCHEMA ""`, an invalid identifier, and fail at connect time.+ schema=normalize_namespace(config.schema),+ user_agent_entry="PostHog",+ **auth_connect_args,+ )+ try:+ yield connection+ finally:+ connection.close()++ # ------------------------------------------------------------------+ # Listing — batch queries run once during `get_schemas`+ # ------------------------------------------------------------------++ def get_columns(+ self,+ conn: Any,+ config: DatabricksSourceConfig,+ names: list[str] | None,+ ) -> dict[str, list[tuple[str, str, bool]]]:+ selected_schema = normalize_namespace(config.schema)+ qualify = selected_schema is None++ information_schema_columns = _IDENTIFIER_QUOTER.quote_qualified(+ config.catalog, DATABRICKS_SYSTEM_SCHEMA, "columns"+ )++ with conn.cursor() as cursor:+ if selected_schema is not None:+ cursor.execute(+ "SELECT table_schema, table_name, column_name, data_type, is_nullable"+ f" FROM {information_schema_columns}"+ " WHERE table_schema = :schema"+ " ORDER BY table_schema ASC, table_name ASC, ordinal_position ASC",+ {"schema": selected_schema},+ )+ else:+ cursor.execute(+ "SELECT table_schema, table_name, column_name, data_type, is_nullable"+ f" FROM {information_schema_columns}"+ " WHERE table_schema != :system_schema"+ " ORDER BY table_schema ASC, table_name ASC, ordinal_position ASC",+ {"system_schema": DATABRICKS_SYSTEM_SCHEMA},+ )+ result = cursor.fetchall()++ schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)+ for table_schema, table_name, column_name, data_type, is_nullable in result:+ display_name = f"{table_schema}.{table_name}" if qualify else table_name+ schema_list[display_name].append((column_name, data_type, is_nullable == "YES"))++ if names is not None:+ # Match qualified (`schema.table`) and bare (`table`) names — a row requested by its+ # qualified name can still map to a bare discovery key (or vice versa) mid-migration.+ available = dict(schema_list)+ filtered: dict[str, list[tuple[str, str, bool]]] = {}+ for name in names:+ if name in available:+ filtered[name] = available[name]+ elif "." in name:+ _schema, _, unqualified = name.partition(".")+ if unqualified in available:+ filtered[name] = available[unqualified]+ return filtered++ return dict(schema_list)++ def get_primary_keys(+ self,+ conn: Any,+ config: DatabricksSourceConfig,+ tables: list[str],+ ) -> dict[str, list[str] | None]:+ """Detect informational primary-key constraints for the given tables.++ One batched query over the catalog's `information_schema` joins+ `table_constraints` to `key_column_usage`, so a blank-namespace+ discovery over a wide catalog stays a single round trip.++ Unity Catalog PK constraints are informational and optional — most+ tables won't have one, and legacy `hive_metastore` has no+ `information_schema` at all. Swallow and log failures so schema+ discovery keeps working without PKs (the base falls back to an `id`+ column when present).+ """+ result: dict[str, list[str] | None] = dict.fromkeys(tables)+ if not tables:+ return result++ default_schema = normalize_namespace(config.schema)+ display_by_pair: dict[tuple[str, str], str] = {}+ for display_name in tables:+ schema, table = _split_display_name(display_name, default_schema)+ if schema is None:+ continue+ display_by_pair[(schema, table)] = display_name++ table_constraints = _IDENTIFIER_QUOTER.quote_qualified(+ config.catalog, DATABRICKS_SYSTEM_SCHEMA, "table_constraints"+ )+ key_column_usage = _IDENTIFIER_QUOTER.quote_qualified(+ config.catalog, DATABRICKS_SYSTEM_SCHEMA, "key_column_usage"+ )++ try:+ with conn.cursor() as cursor:+ cursor.execute(+ f"""+ SELECT kcu.table_schema, kcu.table_name, kcu.column_name, kcu.ordinal_position+ FROM {table_constraints} AS tc+ JOIN {key_column_usage} AS kcu+ ON tc.constraint_catalog = kcu.constraint_catalog+ AND tc.constraint_schema = kcu.constraint_schema+ AND tc.constraint_name = kcu.constraint_name+ WHERE tc.constraint_type = 'PRIMARY KEY'+ """+ )++ keys_by_pair: dict[tuple[str, str], list[tuple[int, str]]] = collections.defaultdict(list)+ for table_schema, table_name, column_name, ordinal_position in cursor.fetchall():+ keys_by_pair[(table_schema, table_name)].append((ordinal_position or 0, column_name))++ for pair, ordered in keys_by_pair.items():+ display_key = display_by_pair.get(pair)+ if display_key is None:+ continue+ keys = [column for _position, column in sorted(ordered, key=lambda item: item[0])]+ if keys:+ result[display_key] = keys+ except Exception as e:+ structlog.get_logger().warning("Failed to detect primary keys for Databricks tables", exc_info=e)++ return result++ def get_source_metadata(+ self,+ conn: Any,+ config: DatabricksSourceConfig,+ tables: list[str],+ ) -> SourceMetadata:+ """Stamp catalog/schema/table per discovered table so per-row routing can pin a namespace.++ The catalog is the connection's catalog (constant, display-only); the+ schema and unqualified table come from the `schema.table` display name,+ falling back to the configured schema for a single-schema source.+ """+ default_schema = normalize_namespace(config.schema)+ catalog_by_table: dict[str, str | None] = {}+ schema_by_table: dict[str, str | None] = {}+ table_name_by_table: dict[str, str | None] = {}+ for display_name in tables:+ schema, table = _split_display_name(display_name, default_schema)+ catalog_by_table[display_name] = config.catalog+ schema_by_table[display_name] = schema+ table_name_by_table[display_name] = table+ return SourceMetadata(+ catalog_by_table=catalog_by_table,+ schema_by_table=schema_by_table,+ table_name_by_table=table_name_by_table,+ )++ def get_incremental_filter(self) -> IncrementalFieldFilter:+ return filter_databricks_incremental_fields++ # ------------------------------------------------------------------+ # Per-cursor metadata — used during `build_pipeline`+ # ------------------------------------------------------------------++ def get_primary_keys_for_table(+ self,+ cursor: Any,+ catalog: str,+ schema: str,+ table_name: str,+ ) -> list[str] | None:+ """Return the primary-key column names for a single table, or None.++ Permission-sensitive like the schema-level `get_primary_keys` — swallow+ a failing lookup and return None so the pipeline falls back to a+ persisted or `id`-column primary key instead of crashing a merge.+ """+ table_constraints = _IDENTIFIER_QUOTER.quote_qualified(catalog, DATABRICKS_SYSTEM_SCHEMA, "table_constraints")+ key_column_usage = _IDENTIFIER_QUOTER.quote_qualified(catalog, DATABRICKS_SYSTEM_SCHEMA, "key_column_usage")++ try:+ cursor.execute(+ f"""+ SELECT kcu.column_name, kcu.ordinal_position+ FROM {table_constraints} AS tc+ JOIN {key_column_usage} AS kcu+ ON tc.constraint_catalog = kcu.constraint_catalog+ AND tc.constraint_schema = kcu.constraint_schema+ AND tc.constraint_name = kcu.constraint_name+ WHERE tc.constraint_type = 'PRIMARY KEY'+ AND kcu.table_schema = :schema+ AND kcu.table_name = :table_name+ ORDER BY kcu.ordinal_position ASC+ """,+ {"schema": schema, "table_name": table_name},+ )+ keys = [row[0] for row in cursor.fetchall()]+ except Exception as e:+ structlog.get_logger().warning(+ "Failed to detect primary key for Databricks table",+ catalog=catalog,+ schema=schema,+ table_name=table_name,+ exc_info=e,+ )+ return None++ return keys if len(keys) > 0 else None++ def fetch_table_stats(+ self,+ cursor: Any,+ schema: str,+ table_name: str,+ logger: FilteringBoundLogger,+ ) -> TableStats | None:+ """Estimate the table's size and row count for partition sizing.++ `DESCRIBE DETAIL` returns a Delta table's `sizeInBytes` but no row count;+ `COUNT(*)` on a Delta table is metadata-optimized (answered from file+ statistics, no scan). Non-Delta objects (views, federated tables) make+ `DESCRIBE DETAIL` raise or return no size — `get_partition_settings`+ treats any failure here as "no stats" and skips partition sizing.++ `sizeInBytes` is the compressed on-disk size, so the derived average row+ size is an underestimate and partitions come out larger than the byte+ target — acceptable for a best-effort estimate.+ """+ table_ref = _IDENTIFIER_QUOTER.quote_qualified(schema, table_name)++ cursor.execute(f"DESCRIBE DETAIL {table_ref}")+ detail_row = cursor.fetchone()+ if detail_row is None or cursor.description is None:+ return None+ size_index = next((i for i, column in enumerate(cursor.description) if column[0] == "sizeInBytes"), -1)+ if size_index == -1:+ return None+ size_in_bytes = detail_row[size_index]+ if not size_in_bytes:+ return None++ cursor.execute(f"SELECT COUNT(*) FROM {table_ref}")+ count_row = cursor.fetchone()+ if count_row is None:+ return None+ row_count = int(count_row[0] or 0)+ if row_count == 0:+ return None++ return TableStats(table_size_bytes=int(size_in_bytes), row_count=row_count)++ # ------------------------------------------------------------------+ # Pipeline build — the `SourceResponse` for a single table+ # ------------------------------------------------------------------++ def build_pipeline(self, config: DatabricksSourceConfig, inputs: SourceInputs) -> SourceResponse:+ # Per-row routing: a multi-schema row pins its own namespace via `schema_metadata`,+ # a legacy single-schema row falls back to `config.schema`. The catalog is fixed+ # per connection. `response_name` preserves the legacy Delta subdir (`dwh_storage_key`).+ location = resolve_source_location(inputs, config_namespace=config.schema)+ table_name = location.table_name+ schema = location.schema+ if not table_name:+ raise ValueError("Table name is missing")+ if not schema:+ raise ValueError("Schema is missing")++ logger = inputs.logger+ incremental_field = inputs.incremental_field if inputs.should_use_incremental_field else None+ incremental_field_type = inputs.incremental_field_type if inputs.should_use_incremental_field else None++ with self.connect(config) as connection:+ with connection.cursor() as cursor:+ primary_keys = self.get_primary_keys_for_table(cursor, config.catalog, schema, table_name)+ # The session catalog is pinned at connect time, so two-part `schema.table`+ # references always resolve inside `config.catalog`.+ query = _QUERY_BUILDER.select_all(+ schema=schema,+ table_name=table_name,+ incremental_field=incremental_field,+ incremental_field_type=incremental_field_type,+ incremental_last_value=inputs.db_incremental_field_last_value,+ enabled_columns=inputs.enabled_columns,+ primary_keys=primary_keys,+ row_filters=inputs.row_filters,+ )+ rows_to_sync = self.get_rows_to_sync(cursor, query.sql, query.params, logger)+ # Partition sizing only pays off on incremental merges (same as MSSQL/MySQL) —+ # full refreshes rewrite the whole table regardless, so skip the extra probes.+ partition_settings = (+ self.get_partition_settings(cursor, schema, table_name, logger)+ if inputs.should_use_incremental_field+ else None+ )++ def get_rows() -> Iterator[Any]:+ with self.connect(config) as streaming_connection:+ with streaming_connection.cursor() as streaming_cursor:+ logger.debug(f"Databricks query: {query.sql}")+ streaming_cursor.execute(query.sql, query.params)++ while True:+ table = streaming_cursor.fetchmany_arrow(DEFAULT_DATABRICKS_FETCH_SIZE)+ if table.num_rows == 0:+ break+ yield table++ return SourceResponse(+ name=location.response_name,+ items=get_rows,+ primary_keys=primary_keys,+ partition_count=partition_settings.partition_count if partition_settings else None,+ partition_size=partition_settings.partition_size if partition_settings else None,+ rows_to_sync=rows_to_sync,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/source.pyindex 90c773b5886c..022f997a5c0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/source.py@@ -1,21 +1,60 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.exceptions_capture import capture_exception++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource+from products.warehouse_sources.backend.temporal.data_imports.sources.databricks.databricks import (+ DatabricksImplementation,+ clean_databricks_host,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.databricks import (DatabricksSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+_DATABRICKS_IMPLEMENTATION = DatabricksImplementation()++# Error-substring → user-facing message map used by `validate_credentials`. Databricks surfaces+# stable SQLSTATE-style error classes in brackets (e.g. `[CATALOG_NOT_FOUND]`) plus a handful of+# stable auth phrases from the Thrift/OAuth layers; the hosts, request ids, and object names around+# them are volatile, so we match the stable fragment.+DatabricksErrors = {+ "Invalid access token": "Databricks rejected the access token. Check that the personal access token is correct and has not expired or been revoked.",+ "invalid_client": "Databricks rejected the service principal credentials. Check the client ID and client secret, and that the service principal still exists.",+ "CATALOG_NOT_FOUND": "Can't find the configured catalog. Check the catalog name and that your credentials have USE CATALOG on it.",+ "NO_SUCH_CATALOG_EXCEPTION": "Can't find the configured catalog. Check the catalog name and that your credentials have USE CATALOG on it.",+ "SCHEMA_NOT_FOUND": "Can't find the configured schema. Check the schema name and that your credentials have USE SCHEMA on it.",+ "PERMISSION_DENIED": "Your Databricks credentials don't have permission to access this data. Grant USE CATALOG, USE SCHEMA, and SELECT to the connecting principal, then try again.",+ "INSUFFICIENT_PERMISSIONS": "Your Databricks credentials don't have permission to access this data. Grant USE CATALOG, USE SCHEMA, and SELECT to the connecting principal, then try again.",+ "TABLE_OR_VIEW_NOT_FOUND": "The catalog has no `information_schema` — this usually means it's a legacy `hive_metastore` catalog. The Databricks source requires a Unity Catalog catalog.",+ "nodename nor servname provided": "Can't resolve the server hostname. Check the server hostname and try again.",+ "Name or service not known": "Can't resolve the server hostname. Check the server hostname and try again.",+ "Failed to resolve": "Can't resolve the server hostname. Check the server hostname and try again.",+}+@SourceRegistry.register-class DatabricksSource(SimpleSource[DatabricksSourceConfig]):+class DatabricksSource(SQLSource[DatabricksSourceConfig], ValidateDatabaseHostMixin):+ api_docs_url = "https://docs.databricks.com/aws/en/dev-tools/python-sql-connector"++ @property+ def get_implementation(self) -> DatabricksImplementation:+ return _DATABRICKS_IMPLEMENTATION+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DATABRICKS@@ -26,7 +65,149 @@ class DatabricksSource(SimpleSource[DatabricksSourceConfig]):name=SchemaExternalDataSourceType.DATABRICKS,category=DataWarehouseSourceCategory.DATABASES,label="Databricks",+ caption="Enter your Databricks SQL warehouse credentials to automatically pull your Databricks data into the PostHog Data warehouse. Requires a Unity Catalog catalog.",iconPath="/static/services/databricks.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/databricks",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["delta lake", "spark", "unity catalog", "sql warehouse"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Server hostname",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="dbc-a1b2345c-d6e7.cloud.databricks.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="http_path",+ label="HTTP path",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="/sql/1.0/warehouses/abcdef1234567890",+ secret=False,+ ),+ # the validation for these options happens in validate_credentials+ SourceFieldSelectConfig(+ name="auth_type",+ label="Authentication type",+ required=True,+ defaultValue="access_token",+ options=[+ SourceFieldSelectConfigOption(+ label="Personal access token",+ value="access_token",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="dapi...",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="Service principal (OAuth)",+ value="service_principal",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ SourceFieldInputConfig(+ name="catalog",+ label="Catalog",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="main",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="schema",+ label="Schema (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="Leave blank to import all schemas",+ secret=False,+ ),+ ],+ ),)++ @property+ def connection_host_fields(self) -> list[str]:+ # `host` already triggers the credential re-entry gate via `_CONNECTION_TARGET_FIELDS`;+ # declared here too so the intent survives if that framework list ever changes.+ return ["host"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ **self.default_non_retryable_errors(),+ "Invalid access token": "Databricks rejected the access token. Check that the personal access token is correct and has not expired or been revoked, then resync.",+ "invalid_client": "Databricks rejected the service principal credentials. Check the client ID and client secret, and that the service principal still exists, then resync.",+ # Unity Catalog error classes are stable identifiers; the object names around them are volatile.+ "CATALOG_NOT_FOUND": "The configured catalog no longer exists in Databricks, or your credentials lost USE CATALOG on it. Check the catalog and grants, then resync.",+ "SCHEMA_NOT_FOUND": "A schema this source syncs no longer exists in Databricks, or your credentials lost USE SCHEMA on it. Check the schema and grants, then resync.",+ "TABLE_OR_VIEW_NOT_FOUND": "A table this source syncs no longer exists in Databricks, or your credentials are no longer authorized to access it. Check that the table still exists and your grants are intact, then resync.",+ "PERMISSION_DENIED": "Your Databricks credentials don't have permission to access this data. Grant USE CATALOG, USE SCHEMA, and SELECT to the connecting principal, then resync.",+ "INSUFFICIENT_PERMISSIONS": "Your Databricks credentials don't have permission to access this data. Grant USE CATALOG, USE SCHEMA, and SELECT to the connecting principal, then resync.",+ # Raised when the SQL warehouse referenced by the HTTP path was deleted.+ "RESOURCE_DOES_NOT_EXIST": "The SQL warehouse referenced by the HTTP path no longer exists. Update the HTTP path to a running SQL warehouse, then resync.",+ }++ def validate_credentials(+ self, config: DatabricksSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if config.auth_type.selection == "access_token" and not config.auth_type.access_token:+ return False, "Missing required parameter: access token"++ if config.auth_type.selection == "service_principal" and (+ not config.auth_type.client_id or not config.auth_type.client_secret+ ):+ return False, "Missing required parameters: client ID, client secret"++ # Block SSRF to internal hosts before any OAuth/SQL request reaches the pasted host.+ valid_host, host_error = self.is_database_host_valid(clean_databricks_host(config.host), team_id)+ if not valid_host:+ return valid_host, host_error++ try:+ self.get_schemas(config, team_id)+ except Exception as e:+ # The connector raises `databricks.sql.exc.*` subclasses for server/auth errors, but the+ # OAuth M2M path can also raise from the SDK layer — match message fragments across all.+ error_msg = str(e)+ for key, value in DatabricksErrors.items():+ if key in error_msg:+ return False, value++ capture_exception(e)+ return False, "Could not connect to Databricks. Please check all connection details are valid."++ return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/tests/test_databricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/tests/test_databricks.pynew file mode 100644index 000000000000..d78c4280afd7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/databricks/tests/test_databricks.py@@ -0,0 +1,535 @@+import pytest+from unittest.mock import MagicMock, patch++import pyarrow as pa++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.implementation import TableStats+from products.warehouse_sources.backend.temporal.data_imports.sources.databricks.databricks import (+ DatabricksImplementation,+ clean_databricks_host,+ filter_databricks_incremental_fields,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.databricks.source import DatabricksSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.databricks import (+ DatabricksSourceConfig,+)+from products.warehouse_sources.backend.types import IncrementalFieldType++_CONNECT_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.databricks.databricks.databricks_sql.connect"+)++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _make_config(auth_type: str = "access_token", **overrides) -> DatabricksSourceConfig:+ auth: dict+ if auth_type == "access_token":+ auth = {"selection": "access_token", "access_token": "dapi-token"}+ else:+ auth = {"selection": "service_principal", "client_id": "cid", "client_secret": "secret"}+ defaults: dict = {+ "host": "dbc-abc123.cloud.databricks.com",+ "http_path": "/sql/1.0/warehouses/wh123",+ "catalog": "main",+ "schema": "analytics",+ "auth_type": auth,+ }+ defaults.update(overrides)+ return DatabricksSourceConfig.from_dict(defaults)+++def _make_inputs(schema_name: str = "users", **overrides) -> SourceInputs:+ defaults: dict = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++def _cursor() -> MagicMock:+ c = MagicMock()+ c.__enter__.return_value = c+ c.fetchall.return_value = []+ c.fetchone.return_value = None+ return c+++def _conn_with_cursor(cursor: MagicMock) -> MagicMock:+ conn = MagicMock()+ conn.cursor.return_value = cursor+ return conn+++# ---------------------------------------------------------------------------+# Module-level pure helpers+# ---------------------------------------------------------------------------+++ "raw,expected",+ [+ # Users paste the whole workspace URL from the browser; the connector wants a bare hostname.+ ("dbc-abc123.cloud.databricks.com", "dbc-abc123.cloud.databricks.com"),+ ("https://dbc-abc123.cloud.databricks.com", "dbc-abc123.cloud.databricks.com"),+ ("https://dbc-abc123.cloud.databricks.com/", "dbc-abc123.cloud.databricks.com"),+ ("http://adb-123.11.azuredatabricks.net/", "adb-123.11.azuredatabricks.net"),+ (" dbc-abc123.cloud.databricks.com ", "dbc-abc123.cloud.databricks.com"),+ ],+)+def test_clean_databricks_host(raw, expected):+ assert clean_databricks_host(raw) == expected+++class TestFilterIncrementalFields:+ @pytest.mark.parametrize(+ "data_type,expected",+ [+ ("TIMESTAMP", IncrementalFieldType.Timestamp),+ ("TIMESTAMP_NTZ", IncrementalFieldType.Timestamp),+ ("date", IncrementalFieldType.Date),+ ("BIGINT", IncrementalFieldType.Numeric),+ ("int", IncrementalFieldType.Numeric),+ ("SMALLINT", IncrementalFieldType.Numeric),+ ("TINYINT", IncrementalFieldType.Numeric),+ # Databricks reports the parameterized form, so an equality match would drop these.+ ("DECIMAL(10,2)", IncrementalFieldType.Numeric),+ ("decimal(38,0)", IncrementalFieldType.Numeric),+ ],+ )+ def test_picks_up_supported_types(self, data_type, expected):+ assert filter_databricks_incremental_fields([("c", data_type, True)]) == [("c", expected, True)]++ @pytest.mark.parametrize("data_type", ["STRING", "BOOLEAN", "BINARY", "DOUBLE", "FLOAT", "ARRAY<INT>", "VARIANT"])+ def test_drops_unsupported_types(self, data_type):+ # Floats are deliberately excluded — an imprecise cursor skips or re-reads rows at the boundary.+ assert filter_databricks_incremental_fields([("c", data_type, True)]) == []+++# ---------------------------------------------------------------------------+# Implementation fixtures+# ---------------------------------------------------------------------------+++def impl() -> DatabricksImplementation:+ return DatabricksImplementation()+++# ---------------------------------------------------------------------------+# connect()+# ---------------------------------------------------------------------------+++class TestConnect:+ def test_access_token_auth_passes_token(self, impl):+ with patch(_CONNECT_PATH) as mock_connect:+ with impl.connect(_make_config()):+ pass+ kwargs = mock_connect.call_args.kwargs+ assert kwargs["access_token"] == "dapi-token"+ assert "credentials_provider" not in kwargs+ assert kwargs["server_hostname"] == "dbc-abc123.cloud.databricks.com"+ assert kwargs["http_path"] == "/sql/1.0/warehouses/wh123"+ assert kwargs["catalog"] == "main"++ def test_service_principal_auth_uses_credentials_provider(self, impl):+ with patch(_CONNECT_PATH) as mock_connect:+ with impl.connect(_make_config("service_principal")):+ pass+ kwargs = mock_connect.call_args.kwargs+ assert "access_token" not in kwargs+ assert callable(kwargs["credentials_provider"])++ def test_pasted_workspace_url_is_cleaned(self, impl):+ # A `https://…/` host reaches the connector as a bare hostname, or every request fails.+ with patch(_CONNECT_PATH) as mock_connect:+ with impl.connect(_make_config(host="https://dbc-abc123.cloud.databricks.com/")):+ pass+ assert mock_connect.call_args.kwargs["server_hostname"] == "dbc-abc123.cloud.databricks.com"++ @pytest.mark.parametrize("blank", ["", " ", None])+ def test_blank_schema_reaches_connector_as_none(self, impl, blank):+ # `schema=""` would make the connector try `USE SCHEMA ""` (invalid) — normalize to None.+ with patch(_CONNECT_PATH) as mock_connect:+ with impl.connect(_make_config(schema=blank)):+ pass+ assert mock_connect.call_args.kwargs["schema"] is None++ def test_connection_closed_on_exit(self, impl):+ with patch(_CONNECT_PATH) as mock_connect:+ with impl.connect(_make_config()):+ mock_connect.return_value.close.assert_not_called()+ mock_connect.return_value.close.assert_called_once()++ def test_connection_closed_on_error(self, impl):+ with patch(_CONNECT_PATH) as mock_connect:+ with pytest.raises(RuntimeError):+ with impl.connect(_make_config()):+ raise RuntimeError("boom")+ mock_connect.return_value.close.assert_called_once()+++# ---------------------------------------------------------------------------+# Listing methods — they take a pre-opened connection+# ---------------------------------------------------------------------------+++class TestGetColumns:+ def test_groups_columns_by_table(self, impl):+ cursor = _cursor()+ cursor.fetchall.return_value = [+ ("analytics", "users", "id", "BIGINT", "NO"),+ ("analytics", "users", "email", "STRING", "YES"),+ ("analytics", "orders", "id", "BIGINT", "NO"),+ ]+ result = impl.get_columns(_conn_with_cursor(cursor), _make_config(), names=None)+ # Single-schema source keeps bare table names.+ assert set(result.keys()) == {"users", "orders"}+ assert ("id", "BIGINT", False) in result["users"]+ assert ("email", "STRING", True) in result["users"]++ def test_single_schema_filters_by_configured_schema(self, impl):+ cursor = _cursor()+ impl.get_columns(_conn_with_cursor(cursor), _make_config(schema="sales"), names=None)+ sql, params = cursor.execute.call_args.args+ assert "table_schema = :schema" in sql+ assert "`main`.`information_schema`.`columns`" in sql+ assert params == {"schema": "sales"}++ @pytest.mark.parametrize("blank", ["", " ", None])+ def test_blank_schema_discovers_all_namespaces_qualified(self, impl, blank):+ cursor = _cursor()+ cursor.fetchall.return_value = [+ ("analytics", "users", "id", "BIGINT", "NO"),+ ("sales", "users", "id", "BIGINT", "NO"),+ ("sales", "orders", "id", "BIGINT", "NO"),+ ]+ result = impl.get_columns(_conn_with_cursor(cursor), _make_config(schema=blank), names=None)+ # Same table name in two schemas must stay distinct and qualified.+ assert set(result.keys()) == {"analytics.users", "sales.users", "sales.orders"}+ sql, params = cursor.execute.call_args.args+ assert "table_schema != :system_schema" in sql+ assert params == {"system_schema": "information_schema"}++ def test_filters_by_names(self, impl):+ cursor = _cursor()+ cursor.fetchall.return_value = [+ ("analytics", "users", "id", "BIGINT", "NO"),+ ("analytics", "orders", "id", "BIGINT", "NO"),+ ]+ result = impl.get_columns(_conn_with_cursor(cursor), _make_config(), names=["users"])+ assert list(result.keys()) == ["users"]++ def test_qualified_name_falls_back_to_bare_discovery_key(self, impl):+ # Mid-migration a row may be requested qualified while a configured-schema source still+ # discovers it bare — keep the requested (qualified) key, mapped to the bare columns.+ cursor = _cursor()+ cursor.fetchall.return_value = [("analytics", "users", "id", "BIGINT", "NO")]+ result = impl.get_columns(+ _conn_with_cursor(cursor), _make_config(schema="analytics"), names=["analytics.users"]+ )+ assert result == {"analytics.users": [("id", "BIGINT", False)]}+++class TestGetPrimaryKeys:+ def test_orders_composite_key_by_ordinal_position(self, impl):+ cursor = _cursor()+ cursor.fetchall.return_value = [+ ("analytics", "users", "tenant_id", 2),+ ("analytics", "users", "id", 1),+ ]+ out = impl.get_primary_keys(_conn_with_cursor(cursor), _make_config(), tables=["users"])+ assert out["users"] == ["id", "tenant_id"]+ # One batched information_schema query, not one per table.+ assert cursor.execute.call_count == 1++ def test_multi_schema_routes_keys_to_qualified_display_names(self, impl):+ cursor = _cursor()+ cursor.fetchall.return_value = [+ ("analytics", "users", "id", 1),+ ("sales", "users", "uuid", 1),+ ]+ out = impl.get_primary_keys(+ _conn_with_cursor(cursor), _make_config(schema=""), tables=["analytics.users", "sales.users"]+ )+ assert out == {"analytics.users": ["id"], "sales.users": ["uuid"]}++ def test_swallows_failure_and_returns_none_placeholders(self, impl):+ # `hive_metastore` catalogs have no information_schema — discovery must keep working without PKs.+ cursor = _cursor()+ cursor.execute.side_effect = Exception("[TABLE_OR_VIEW_NOT_FOUND] information_schema")+ out = impl.get_primary_keys(_conn_with_cursor(cursor), _make_config(), tables=["users"])+ assert out == {"users": None}+++class TestGetSourceMetadata:+ def test_single_schema_pins_configured_namespace(self, impl):+ meta = impl.get_source_metadata(MagicMock(), _make_config(schema="analytics"), tables=["users"])+ assert meta.catalog_by_table == {"users": "main"}+ assert meta.schema_by_table == {"users": "analytics"}+ assert meta.table_name_by_table == {"users": "users"}++ def test_multi_schema_splits_qualified_display_names(self, impl):+ meta = impl.get_source_metadata(MagicMock(), _make_config(schema=""), tables=["analytics.users", "sales.users"])+ assert meta.schema_by_table == {"analytics.users": "analytics", "sales.users": "sales"}+ assert meta.table_name_by_table == {"analytics.users": "users", "sales.users": "users"}+++class TestGetPrimaryKeysForTable:+ def test_returns_ordered_keys_scoped_to_table(self, impl):+ cursor = _cursor()+ cursor.fetchall.return_value = [("id", 1), ("tenant_id", 2)]+ keys = impl.get_primary_keys_for_table(cursor, "main", "analytics", "users")+ assert keys == ["id", "tenant_id"]+ sql, params = cursor.execute.call_args.args+ assert params == {"schema": "analytics", "table_name": "users"}+ assert "`main`.`information_schema`.`table_constraints`" in sql++ def test_returns_none_when_lookup_fails(self, impl):+ # A permission/missing-information_schema failure must degrade to None so the pipeline falls+ # back to a persisted or `id`-column PK instead of crashing the sync.+ cursor = _cursor()+ cursor.execute.side_effect = Exception("PERMISSION_DENIED")+ assert impl.get_primary_keys_for_table(cursor, "main", "analytics", "users") is None++ def test_returns_none_when_no_pk_defined(self, impl):+ cursor = _cursor()+ cursor.fetchall.return_value = []+ assert impl.get_primary_keys_for_table(cursor, "main", "analytics", "users") is None+++class TestFetchTableStats:+ def test_reads_size_from_describe_detail_and_counts_rows(self, impl):+ cursor = _cursor()+ # `DESCRIBE DETAIL` column order isn't contractual — sizeInBytes must be found by name.+ cursor.description = [("format",), ("name",), ("sizeInBytes",)]+ cursor.fetchone.side_effect = [("delta", "users", 10_485_760), (2_000,)]+ stats = impl.fetch_table_stats(cursor, "analytics", "users", MagicMock())+ assert stats == TableStats(table_size_bytes=10_485_760, row_count=2_000)+ assert cursor.execute.call_args_list[0].args[0] == "DESCRIBE DETAIL `analytics`.`users`"+ assert cursor.execute.call_args_list[1].args[0] == "SELECT COUNT(*) FROM `analytics`.`users`"++ def test_returns_none_when_size_column_missing(self, impl):+ # Views and federated tables don't report sizeInBytes — partition sizing must be skipped.+ cursor = _cursor()+ cursor.description = [("format",), ("name",)]+ cursor.fetchone.return_value = ("view", "users")+ assert impl.fetch_table_stats(cursor, "analytics", "users", MagicMock()) is None++ def test_returns_none_for_empty_table(self, impl):+ cursor = _cursor()+ cursor.description = [("sizeInBytes",)]+ cursor.fetchone.side_effect = [(1024,), (0,)]+ assert impl.fetch_table_stats(cursor, "analytics", "users", MagicMock()) is None+++# ---------------------------------------------------------------------------+# build_pipeline end-to-end (mocked driver)+# ---------------------------------------------------------------------------+++def _pipeline_mocks(pk_rows: list[tuple], row_count: int, arrow_batches: list[pa.Table]):+ """Two connections (metadata pass + streaming pass), each with one cursor."""+ metadata_cursor = _cursor()+ metadata_cursor.fetchall.return_value = pk_rows+ metadata_cursor.fetchone.return_value = (row_count,)++ streaming_cursor = _cursor()+ streaming_cursor.fetchmany_arrow.side_effect = [*arrow_batches, pa.table({"id": pa.array([], type=pa.int64())})]++ connections = []+ for cursor in (metadata_cursor, streaming_cursor):+ conn = MagicMock()+ conn.cursor.return_value = cursor+ connections.append(conn)++ return metadata_cursor, streaming_cursor, connections+++class TestBuildPipeline:+ def test_builds_source_response_and_streams_until_empty_batch(self, impl):+ batch = pa.table({"id": [1, 2, 3]})+ metadata_cursor, streaming_cursor, connections = _pipeline_mocks(+ pk_rows=[("id", 1)], row_count=3, arrow_batches=[batch]+ )++ with patch(_CONNECT_PATH, side_effect=connections):+ response = impl.build_pipeline(_make_config(), _make_inputs(schema_name="users"))+ assert response.name == "users"+ assert response.primary_keys == ["id"]+ assert response.rows_to_sync == 3+ # Full refresh rewrites the whole table — the partition probes must be skipped.+ assert response.partition_count is None+ assert response.partition_size is None+ # The stream must terminate on the first empty arrow batch — not loop forever.+ assert list(response.items()) == [batch]++ sql, params = streaming_cursor.execute.call_args.args+ assert sql == "SELECT * FROM `analytics`.`users`"+ assert params == {}++ def test_incremental_query_filters_and_orders(self, impl):+ metadata_cursor, streaming_cursor, connections = _pipeline_mocks(+ pk_rows=[("id", 1)], row_count=1, arrow_batches=[pa.table({"id": [1]})]+ )+ # Incremental syncs also probe table stats: rows_to_sync COUNT, DESCRIBE DETAIL, stats COUNT.+ metadata_cursor.description = [("sizeInBytes",)]+ metadata_cursor.fetchone.side_effect = [(1_000,), (10_485_760,), (1_000,)]+ inputs = _make_inputs(+ schema_name="users",+ should_use_incremental_field=True,+ incremental_field="updated_at",+ incremental_field_type=IncrementalFieldType.Timestamp,+ db_incremental_field_last_value="2025-01-01T00:00:00",+ )++ with patch(_CONNECT_PATH, side_effect=connections):+ response = impl.build_pipeline(_make_config(), inputs)+ # Table stats feed the shared partition math so incremental merges get md5 partitioning.+ assert response.partition_count is not None+ assert response.partition_size is not None+ list(response.items())++ sql, params = streaming_cursor.execute.call_args.args+ assert "WHERE `updated_at` > :incremental_value" in sql+ assert "ORDER BY `updated_at` ASC" in sql+ assert params == {"incremental_value": "2025-01-01T00:00:00"}++ def test_enabled_columns_projection_retains_primary_key(self, impl):+ # Dropping the PK from the projection would break the Delta merge on every later sync.+ metadata_cursor, streaming_cursor, connections = _pipeline_mocks(+ pk_rows=[("id", 1)], row_count=1, arrow_batches=[pa.table({"id": [1]})]+ )+ inputs = _make_inputs(schema_name="users", enabled_columns=["email"])++ with patch(_CONNECT_PATH, side_effect=connections):+ response = impl.build_pipeline(_make_config(), inputs)+ list(response.items())++ sql, _ = streaming_cursor.execute.call_args.args+ assert sql.startswith("SELECT `email`, `id` FROM `analytics`.`users`")++ def test_multi_schema_row_routes_to_qualified_namespace(self, impl):+ # A blank-namespace source pins each row's schema via the dotted schema_name.+ metadata_cursor, streaming_cursor, connections = _pipeline_mocks(+ pk_rows=[("id", 1)], row_count=1, arrow_batches=[pa.table({"id": [1]})]+ )++ with patch(_CONNECT_PATH, side_effect=connections):+ response = impl.build_pipeline(_make_config(schema=""), _make_inputs(schema_name="sales.users"))+ # Delta subdir keeps the qualified, normalized name so cross-schema duplicates stay distinct.+ assert response.name == "sales_users"+ list(response.items())++ sql, _ = streaming_cursor.execute.call_args.args+ assert "FROM `sales`.`users`" in sql+ # PK probe targets the resolved schema too.+ pk_params = metadata_cursor.execute.call_args_list[0].args[1]+ assert pk_params == {"schema": "sales", "table_name": "users"}+++# ---------------------------------------------------------------------------+# Source-level behavior+# ---------------------------------------------------------------------------+++class TestDatabricksSource:+ @pytest.fixture+ def source(self) -> DatabricksSource:+ return DatabricksSource()++ def test_schema_field_is_optional_for_multi_schema_support(self, source):+ # `is_multi_schema_capable_sql_source` keys off the schema field being optional — making it+ # required would silently turn off multi-schema import for Databricks.+ schema_field = next(f for f in source.get_source_config.fields if f.name == "schema")+ assert schema_field.required is False++ def test_host_is_a_connection_host_field(self, source):+ # Retargeting the workspace hostname must force credential re-entry (exfiltration gate).+ assert source.connection_host_fields == ["host"]++ @pytest.mark.parametrize(+ "error_msg",+ [+ "Invalid access token.",+ "Error during request to server: b'Invalid access token. (403)'",+ "invalid_client: Client authentication failed",+ "[CATALOG_NOT_FOUND] The catalog 'main' cannot be found.",+ "[SCHEMA_NOT_FOUND] The schema 'analytics' cannot be found.",+ "PERMISSION_DENIED: User does not have USE SCHEMA on Schema 'analytics'.",+ "[TABLE_OR_VIEW_NOT_FOUND] The table or view `main`.`information_schema`.`columns` cannot be found.",+ ],+ )+ def test_permanent_failures_are_non_retryable(self, source, error_msg):+ non_retryable = source.get_non_retryable_errors()+ assert any(pattern in error_msg for pattern in non_retryable), f"Error should be non-retryable: {error_msg}"++ def test_validate_credentials_requires_access_token(self, source):+ config = DatabricksSourceConfig.from_dict(+ {"host": "h", "http_path": "p", "catalog": "main", "auth_type": {"selection": "access_token"}}+ )+ ok, message = source.validate_credentials(config, team_id=1)+ assert ok is False+ assert message is not None and "access token" in message++ def test_validate_credentials_requires_client_id_and_secret(self, source):+ config = DatabricksSourceConfig.from_dict(+ {+ "host": "h",+ "http_path": "p",+ "catalog": "main",+ "auth_type": {"selection": "service_principal", "client_id": "cid"},+ }+ )+ ok, message = source.validate_credentials(config, team_id=1)+ assert ok is False+ assert message is not None and "client" in message.lower()++ @pytest.mark.parametrize(+ "error_msg,expected_fragment",+ [+ ("Error during request to server: b'Invalid access token. (403)'", "access token"),+ ("invalid_client: Client authentication failed", "service principal"),+ ("[CATALOG_NOT_FOUND] The catalog 'main' cannot be found.", "catalog"),+ (+ "[TABLE_OR_VIEW_NOT_FOUND] The table or view `information_schema`.`columns` cannot be found.",+ "Unity Catalog",+ ),+ ("something totally unexpected", "Could not connect to Databricks"),+ ],+ )+ def test_validate_credentials_maps_connection_errors(self, source, error_msg, expected_fragment):+ with patch.object(DatabricksSource, "get_schemas", side_effect=Exception(error_msg)):+ ok, message = source.validate_credentials(_make_config(), team_id=1)+ assert ok is False+ assert message is not None and expected_fragment in message++ def test_validate_credentials_success(self, source):+ with patch.object(DatabricksSource, "get_schemas", return_value=[MagicMock()]):+ assert source.validate_credentials(_make_config(), team_id=1) == (True, None)++ def test_validate_credentials_blocks_internal_host_before_connecting(self, source):+ # Guards the SSRF fix: a rejected host must short-circuit before any request reaches it.+ with (+ patch.object(DatabricksSource, "is_database_host_valid", return_value=(False, "Host is not allowed")),+ patch.object(DatabricksSource, "get_schemas") as mock_get_schemas,+ ):+ ok, message = source.validate_credentials(_make_config(), team_id=1)+ assert ok is False+ assert message == "Host is not allowed"+ mock_get_schemas.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/databricks.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/databricks.pyindex 87eb89ee849f..13d3d170afdd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/databricks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/databricks.py@@ -1,9 +1,23 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class DatabricksAuthTypeConfig(config.Config):+ selection: Literal["access_token", "service_principal"] = "access_token"+ access_token: str | None = None+ client_id: str | None = None+ client_secret: str | None = None++@config.configclass DatabricksSourceConfig(config.Config):- pass+ host: str+ http_path: str+ auth_type: DatabricksAuthTypeConfig+ catalog: str+ schema: str | None = None