databricks Adapter¶
from sqlspec.adapters.databricks import (
DatabricksCatalogSchemaStrategy,
DatabricksConfig,
DatabricksConnectionParams,
DatabricksConnectionPool,
DatabricksDriver,
DatabricksDriverFeatures,
DatabricksExceptionHandler,
DatabricksPoolParams,
DatabricksSyncDataDictionary,
DatabricksSyncMigrationTracker,
)
Synchronous Databricks SQL Warehouse adapter built on databricks-sql-connector>=4.0.0, with bounded pooling, Cloud Fetch Arrow streaming, and Unity Catalog Volumes Parquet staging.
Scripts use SQLSpec's Databricks splitter and a managed cursor per statement. Standard Delta tables run with ignore_transactions=True by default; Unity Catalog catalog-managed tables on Databricks Runtime >=18.0 can opt into interactive BEGIN TRANSACTION blocks by setting ignore_transactions=False.
Inherited query and transaction methods are documented on SyncDriverAdapterBase.
See the Databricks setup guide and Databricks catalog reference.
Configuration and Parameters¶
DatabricksConfig
¶
Bases: SyncDatabaseConfig[DatabricksConnection, DatabricksConnectionPool, DatabricksDriver]
Configure Databricks SQL Warehouse sessions, authentication, and bounded pooling.
DatabricksConnectionParams
¶
Bases: TypedDict
Connection options forwarded to the Databricks SQL Connector for Python.
Attributes:
| Name | Type | Description |
|---|---|---|
server_hostname |
NotRequired[str]
|
Databricks workspace host name, such as |
http_path |
NotRequired[str]
|
SQL Warehouse HTTP path, such as |
access_token |
NotRequired[str]
|
Personal access token or bearer token for Databricks authentication. |
auth_type |
NotRequired[Literal['databricks-oauth', 'oauth-m2m', 'pat']]
|
Authentication mode shorthand: |
client_id |
NotRequired[str]
|
Service principal OAuth client identifier for |
client_secret |
NotRequired[str]
|
Service principal OAuth client secret for |
credentials_provider |
NotRequired[Callable[[], Any]]
|
Zero-argument callback compatible with |
catalog |
NotRequired[str]
|
Initial Unity Catalog name selected for the session. |
schema |
NotRequired[str]
|
Initial schema name selected for the session. |
http_headers |
NotRequired[Sequence[tuple[str, str]]]
|
Additional HTTP headers sent with SQL Warehouse Thrift requests. |
session_configuration |
NotRequired[Mapping[str, Any]]
|
Spark SQL session configuration parameters applied when opening the session. |
query_tags |
NotRequired[Mapping[str, str]]
|
Key-value query tags forwarded to Databricks query history. |
ignore_transactions |
NotRequired[bool]
|
Ignore DB-API transaction calls on standard Delta tables; defaults to |
staging_allowed_local_path |
NotRequired[str | Path | Sequence[str | Path]]
|
Allowed local filesystem path or paths for Unity Catalog Volumes |
paramstyle |
NotRequired[Literal['qmark', 'named']]
|
Connector parameter binding style ( |
dsn |
NotRequired[str]
|
Optional |
extra |
NotRequired[Mapping[str, Any]]
|
Additional connector keyword arguments, with explicit modeled options taking precedence. |
DatabricksPoolParams
¶
Bases: DatabricksConnectionParams
Databricks connection options and bounded pool settings.
Attributes:
| Name | Type | Description |
|---|---|---|
pool_min_size |
NotRequired[int]
|
Number of physical sessions opened when constructing the pool; defaults to |
pool_max_size |
NotRequired[int]
|
Maximum number of simultaneously owned sessions; defaults to |
pool_timeout |
NotRequired[float]
|
Maximum seconds waiting for an available pool slot; defaults to |
pool_recycle_seconds |
NotRequired[int]
|
Maximum connection lifetime in seconds; |
health_check_interval |
NotRequired[float]
|
Idle seconds between connection health checks; defaults to |
DatabricksDriverFeatures
¶
Bases: TypedDict
Databricks codec, staging, correlation, and event settings.
Attributes:
| Name | Type | Description |
|---|---|---|
json_serializer |
NotRequired[Callable[[Any], str]]
|
Serialize structured parameters to JSON text. |
json_deserializer |
NotRequired[Callable[[str], Any]]
|
Decode Databricks semi-structured result values. |
on_connection_create |
NotRequired[Callable[[DatabricksConnection], None]]
|
Callback invoked for each newly opened physical connection. |
enable_lowercase_column_names |
NotRequired[bool]
|
Lowercase implicitly uppercase result names while preserving mixed-case aliases; defaults to |
enable_json_deserialization |
NotRequired[bool]
|
Decode VARIANT, STRUCT, ARRAY, MAP, and JSON result values with |
enable_query_tag_correlation |
NotRequired[bool]
|
Attach statement correlation metadata to Databricks query tags; defaults to |
enable_volume_staging |
NotRequired[bool]
|
Enable Unity Catalog Volumes Parquet staging for large bulk loads; defaults to |
staging_volume_path |
NotRequired[str | None]
|
Unity Catalog Volumes prefix starting with |
stage_parquet_threshold_rows |
NotRequired[int]
|
Minimum row count selecting Volumes Parquet staging; defaults to |
enable_events |
NotRequired[bool]
|
Enable SQLSpec table-backed event channels; defaults to |
events_backend |
NotRequired[Literal['poll_queue']]
|
Event backend used for Databricks table queues ( |
tenant_strategy |
NotRequired[SyncTenantStrategy | TenantStrategyShorthand | None]
|
Opt-in tenant strategy, or shorthand, applied to every session and connection lease. |
Driver, Pool, and Data Dictionary¶
DatabricksDriver
¶
Bases: SyncDriverAdapterBase
Execute Databricks SQL Warehouse statements, scripts, transactions, and asynchronous queries.
execute_async_query
¶
Submit an asynchronous warehouse query and return its tracked query identifier.
The underlying cursor remains open and owned by the driver until
:meth:fetch_async_query_result, :meth:cancel_query, or :meth:close completes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statement
|
Statement | QueryBuilder
|
SQL string, |
required |
*parameters
|
StatementParameters | StatementFilter
|
Positional parameters or statement filters. |
()
|
statement_config
|
StatementConfig | None
|
Optional statement configuration override. |
None
|
**kwargs
|
Any
|
Named parameters or execution overrides. |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Warehouse query identifier string. |
Raises:
| Type | Description |
|---|---|
ImproperConfigurationError
|
If the session has already closed. |
SQLSpecError
|
If submission fails or returns an empty query identifier. |
fetch_async_query_result
¶
Wait for a submitted asynchronous warehouse query, materialize its result, and close its cursor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query_id
|
str
|
Identifier returned by :meth: |
required |
statement_config
|
StatementConfig | None
|
Optional statement configuration override. |
None
|
Returns:
| Type | Description |
|---|---|
SQLResult
|
Materialized |
Raises:
| Type | Description |
|---|---|
ImproperConfigurationError
|
If the session has already closed. |
NotFoundError
|
If |
SQLSpecError
|
If fetching the asynchronous result fails. |
cancel_query
¶
Cancel a tracked asynchronous warehouse query and close its cursor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query_id
|
str
|
Identifier returned by :meth: |
required |
Raises:
| Type | Description |
|---|---|
ImproperConfigurationError
|
If the session has already closed. |
NotFoundError
|
If |
DatabricksExceptionHandler
¶
Bases: BaseSyncExceptionHandler
Capture mapped Databricks connector exceptions for deferred re-raising.
DatabricksConnectionPool
¶
Own bounded exclusive sessions and reuse healthy handles between leases.
DatabricksSyncDataDictionary
¶
Bases: DatabricksSyncDataDictionary
Databricks-specific sync data dictionary.
DatabricksSyncMigrationTracker
¶
Bases: SyncMigrationTracker
Track migrations with Delta Lake column types, backtick qualification, and UTC timestamps.
Tenant Strategies¶
Set driver_features={"tenant_strategy": "catalog_schema"}; "default" and True select the same strategy. The strategy isolates each leased session to a tenant's Unity Catalog catalog and schema using DatabricksCatalogSchemaStrategy. Pass an explicit DatabricksCatalogSchemaStrategy(...) instance to configure mode ("schema", "catalog", or "catalog_schema"), a fixed catalog, payload catalog_variable / schema_variable keys, or identifier prefixes (catalog_prefix, schema_prefix). All target catalog and schema names are validated as ordinary identifiers ([A-Za-z_][A-Za-z0-9_]*, up to 255 characters) and folded to lowercase.
On checkout, the strategy captures the baseline scope with SELECT current_catalog(), current_schema(), issues backtick-quoted USE CATALOG and USE SCHEMA statements, and queries SELECT current_catalog(), current_schema() again to verify the active scope before yielding the session. On checkin, DatabricksTenantLease restores and verifies the captured baseline catalog and schema before returning the connection to DatabricksConnectionPool; any checkout, transaction cleanup, restore, or verification failure discards the connection. When ignore_transactions=False, unfinished transactions are rolled back before checkin. Standalone create_connection() is rejected in tenant mode; use provide_session() or provide_connection().
Missing tenant identity or invalid target resolution raises TenantContextError before or during checkout. Failed restore or cleanup raises TenantCleanupError when no body exception is pending; otherwise the body error keeps its identity and receives a cleanup note. See Multi-Tenancy and Tenant Operations.
DatabricksCatalogSchemaStrategy
¶
Switch, verify, and restore Databricks session catalog and schema per tenant lease.
Checkout captures current_catalog() and current_schema(), issues backtick-quoted
USE CATALOG and USE SCHEMA statements for validated ordinary identifiers, and
verifies the active session scope. Checkin restores the captured baseline and verifies
that the original scope is active before the connection returns to the pool.
__init__
¶
__init__(
*,
mode=DEFAULT_DATABRICKS_TENANT_MODE,
catalog=None,
catalog_variable=None,
schema_variable=None,
catalog_prefix="",
schema_prefix="",
)
Configure catalog and schema tenant target resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
Literal['schema', 'catalog', 'catalog_schema']
|
Target switching mode: |
DEFAULT_DATABRICKS_TENANT_MODE
|
catalog
|
str | None
|
Optional fixed Unity Catalog name used alongside schema switching. |
None
|
catalog_variable
|
str | None
|
Optional payload variable key providing the target catalog name. |
None
|
schema_variable
|
str | None
|
Optional payload variable key providing the target schema name. |
None
|
catalog_prefix
|
str
|
Optional ordinary identifier prefix prepended to dynamic catalog targets. |
''
|
schema_prefix
|
str
|
Optional ordinary identifier prefix prepended to dynamic schema targets. |
''
|
Raises:
| Type | Description |
|---|---|
ImproperConfigurationError
|
Any strategy option is invalid. |
checkout
¶
Capture baseline scope, switch catalog/schema, and verify the active session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Any
|
Active Databricks DB-API connection handle. |
required |
payload
|
TenantContextPayload
|
Immutable tenant identity and variable snapshot. |
required |
Returns:
| Type | Description |
|---|---|
TenantLeaseState
|
Lease state recording the captured baseline catalog and schema. |
Raises:
| Type | Description |
|---|---|
TenantContextError
|
Target resolution, scope switching, or verification failed. |
checkin
¶
Restore the captured baseline catalog and schema and verify the session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Any
|
Active Databricks DB-API connection handle. |
required |
state
|
TenantLeaseState
|
Lease state captured during checkout. |
required |
Raises:
| Type | Description |
|---|---|
TenantCleanupError
|
Baseline values are invalid, or restore or verification failed. |
Extension Stores¶
DatabricksStore
¶
Bases: BaseSQLSpecStore[DatabricksConfig]
Persist session bytes in Databricks Delta Lake BINARY columns.
DatabricksEventQueueStore
¶
Bases: BaseEventQueueStore[DatabricksConfig]
Store queue payloads in Delta Lake STRING columns without secondary indexes.
DatabricksADKStore
¶
Bases: BaseSyncADKStore[DatabricksConfig]
Store ADK sessions and events in Databricks Delta Lake tables.
DatabricksADKMemoryStore
¶
Bases: BaseSyncADKMemoryStore[DatabricksConfig]
Store ADK memories in Delta Lake with MERGE deduplication and CONTAINS text recall.