Skip to content

Databricks

Use DatabricksConfig to run SQL, stream Cloud Fetch Arrow results, and load Delta Lake tables on Databricks SQL Warehouses through databricks-sql-connector>=4.0.0. The adapter is synchronous and owns a bounded connection pool. Install sqlspec[databricks] to include the connector and PyArrow.

Installation and Quickstart

uv add "sqlspec[databricks]"
pip install "sqlspec[databricks]"
pdm add "sqlspec[databricks]"
poetry add "sqlspec[databricks]"

Configure your workspace host name, SQL Warehouse HTTP path, and access token, then run:

import os

from sqlspec import SQLSpec
from sqlspec.adapters.databricks import DatabricksConfig

spec = SQLSpec()
config = spec.add_config(
    DatabricksConfig(
        connection_config={
            "server_hostname": os.environ["DATABRICKS_SERVER_HOSTNAME"],
            "http_path": os.environ["DATABRICKS_HTTP_PATH"],
            "access_token": os.environ["DATABRICKS_ACCESS_TOKEN"],
            "catalog": "main",
            "schema": "default",
        }
    )
)
try:
    with config.provide_session() as session:
        print(session.select_value("SELECT CAST(? AS INT)", 42))
finally:
    config.close_pool()

Output: 42. Session contexts release their connection back to the pool; close the pool when the application stops. Standard Delta tables run with ignore_transactions=True by default, so commit() is a no-op and begin() raises TransactionError. For Unity Catalog catalog-managed tables on Databricks Runtime >=18.0, set ignore_transactions=False to opt into interactive BEGIN TRANSACTION blocks. Savepoint methods raise NotImplementedError.

Choosing a Databricks Adapter

Choose When you need
DatabricksConfig with sqlspec[databricks] Databricks SQL Warehouses over databricks-sql-connector>=4.0.0: Cloud Fetch Arrow export, Unity Catalog Volumes staging, Unity Catalog introspection, migrations, tenant isolation, and Databricks extension stores.
AsyncpgConfig or PsycopgConfig Databricks Lakebase (PostgreSQL wire protocol). Connect through asyncpg or psycopg.

Authentication and Session Settings

Read credentials from your environment or secret manager.

import os

from sqlspec.adapters.databricks import DatabricksConfig

config = DatabricksConfig(
    connection_config={
        "server_hostname": "adb-12345.12.azuredatabricks.net",
        "http_path": "/sql/1.0/warehouses/0123456789abcdef",
        "access_token": os.environ["DATABRICKS_ACCESS_TOKEN"],
        "catalog": "analytics",
        "schema": "reporting",
    }
)
auth_type="pat" is optional when passing access_token. You can also pass a databricks://token:<token>@<host>/<catalog>/<schema>?http_path=... string in dsn; explicit keys in connection_config always take precedence over parsed DSN values.

import os

from sqlspec.adapters.databricks import DatabricksConfig

config = DatabricksConfig(
    connection_config={
        "server_hostname": "adb-12345.12.azuredatabricks.net",
        "http_path": "/sql/1.0/warehouses/0123456789abcdef",
        "auth_type": "oauth-m2m",
        "client_id": os.environ["DATABRICKS_CLIENT_ID"],
        "client_secret": os.environ["DATABRICKS_CLIENT_SECRET"],
    }
)
oauth-m2m exchanges service principal credentials via databricks-sdk (oauth_service_principal). For interactive user-to-machine OAuth, set auth_type="databricks-oauth" without client_id or client_secret.

from databricks.sdk.core import Config as SdkConfig
from sqlspec.adapters.databricks import DatabricksConfig

sdk_config = SdkConfig(host="https://adb-12345.12.azuredatabricks.net")
config = DatabricksConfig(
    connection_config={
        "server_hostname": "adb-12345.12.azuredatabricks.net",
        "http_path": "/sql/1.0/warehouses/0123456789abcdef",
        "credentials_provider": sdk_config.authenticate,
    }
)
credentials_provider accepts any zero-argument callable compatible with databricks-sdk Config.authenticate, enabling unified workspace profiles and cloud identity federation (AWS IAM, Azure Managed Identity, or Google Cloud service accounts).

import os

from sqlspec.adapters.databricks import DatabricksConfig

config = DatabricksConfig(
    connection_config={
        "server_hostname": os.environ["DATABRICKS_SERVER_HOSTNAME"],
        "http_path": os.environ["DATABRICKS_HTTP_PATH"],
        "access_token": os.environ["DATABRICKS_ACCESS_TOKEN"],
        "catalog": "analytics",
        "schema": "reporting",
        "session_configuration": {"TIMEZONE": "UTC", "ANSI_MODE": "true"},
        "query_tags": {"app": "billing", "env": "prod"},
        "ignore_transactions": True,
    },
    driver_features={"enable_query_tag_correlation": True},
)
session_configuration and query_tags are forwarded when opening each SQL Warehouse session. Setting enable_query_tag_correlation=True merges sqlspec_correlation and sqlspec_read_only into per-statement query tags whenever a SQLSpec correlation ID is active.

Connection and Pool Configuration

Pass connection and pool keys in connection_config, and feature flags in driver_features. The pool defaults to 0 initial connections, 5 maximum connections, a 30.0-second acquisition timeout, 3600-second connection recycling, and 60.0-second idle SELECT 1 health checks that discard and replace expired sessions (SessionAlreadyClosedError). A pool inherited across a process fork must be recreated.

Key Type Default Description
server_hostname str - Databricks workspace host name, such as adb-12345.12.azuredatabricks.net.
http_path str - SQL Warehouse HTTP path, such as /sql/1.0/warehouses/<id>.
access_token str - Personal access token or bearer token for Databricks authentication.
auth_type Literal['databricks-oauth', 'oauth-m2m', 'pat'] - Authentication mode shorthand: databricks-oauth, oauth-m2m, or pat.
client_id str - Service principal OAuth client identifier for oauth-m2m authentication.
client_secret str - Service principal OAuth client secret for oauth-m2m authentication.
credentials_provider Callable[[], Any] - Zero-argument callback compatible with databricks-sdk Config.authenticate.
catalog str - Initial Unity Catalog name selected for the session.
schema str - Initial schema name selected for the session.
http_headers Sequence[tuple[str, str]] - Additional HTTP headers sent with SQL Warehouse Thrift requests.
session_configuration Mapping[str, Any] - Spark SQL session configuration parameters applied when opening the session.
query_tags Mapping[str, str] - Key-value query tags forwarded to Databricks query history.
ignore_transactions bool True Ignore DB-API transaction calls on standard Delta tables; defaults to True.
_use_arrow_native_complex_types bool True Decode Arrow complex types natively in Cloud Fetch results; defaults to True.
staging_allowed_local_path str or Path or Sequence[str or Path] - Allowed local filesystem path or paths for Unity Catalog Volumes PUT INTO staging.
_user_agent_entry str - Custom user-agent product entry reported to Databricks SQL Warehouses.
paramstyle Literal['qmark', 'named'] qmark Connector parameter binding style (qmark or named); defaults to qmark.
dsn str - Optional databricks:// connection URL parsed with explicit options taking precedence.
extra Mapping[str, Any] - Additional connector keyword arguments, with explicit modeled options taking precedence.
pool_min_size int 0 Number of physical sessions opened when constructing the pool; defaults to 0.
pool_max_size int 5 Maximum number of simultaneously owned sessions; defaults to 5.
pool_timeout float 30.0 Maximum seconds waiting for an available pool slot; defaults to 30.0.
pool_recycle_seconds int 3600 Maximum connection lifetime in seconds; 0 disables recycling; defaults to 3600.
health_check_interval float 60.0 Idle seconds between connection health checks; defaults to 60.0.

Driver Features

Key Type Default Description
json_serializer Callable[[Any], str] - Serialize structured parameters to JSON text.
json_deserializer Callable[[str], Any] - Decode Databricks semi-structured result values.
on_connection_create Callable[[DatabricksConnection], None] - Callback invoked for each newly opened physical connection.
enable_lowercase_column_names bool True Lowercase implicitly uppercase result names while preserving mixed-case aliases; defaults to True.
enable_json_deserialization bool True Decode VARIANT, STRUCT, ARRAY, MAP, and JSON result values with json_deserializer; defaults to True.
enable_query_tag_correlation bool False Attach statement correlation metadata to Databricks query tags; defaults to False.
enable_volume_staging bool False Enable Unity Catalog Volumes Parquet staging for large bulk loads; defaults to False.
staging_volume_path str or None None Unity Catalog Volumes prefix starting with /Volumes/ used for staged Parquet loads; defaults to None.
stage_parquet_threshold_rows int 1000 Minimum row count selecting Volumes Parquet staging; defaults to 1000.
enable_events bool True Enable SQLSpec table-backed event channels; defaults to True.
events_backend Literal['poll_queue'] - Event backend used for Databricks table queues ('poll_queue').
tenant_strategy SyncTenantStrategy or TenantStrategyShorthand or None - Opt-in tenant strategy, or shorthand, applied to every session and connection lease.

Cloud Fetch Arrow Export and Unity Catalog Volumes Staging

select_to_arrow() returns an ArrowResult backed by Databricks Cloud Fetch (cursor.fetchall_arrow()), and return_format="reader" streams chunked RecordBatchReader batches via cursor.fetchmany_arrow() without loading pandas. Empty result sets construct typed schemas from cursor.description, and statements without Arrow payloads fall back to row materialization. select_stream() yields lazy row chunks over the same Cloud Fetch Arrow stream and closes its cursor on exhaustion, early close, or session close. Implicitly uppercase ASCII column names fold to lowercase by default (enable_lowercase_column_names=True) while preserving mixed-case aliases, and _use_arrow_native_complex_types=True decodes Arrow nested types natively.

For bulk ingestion, load_from_arrow(table, source) and load_from_storage(table, source, file_format="parquet") stage Parquet files into a Unity Catalog Volume when enable_volume_staging=True, staging_volume_path starts with /Volumes/<catalog>/<schema>/<volume>, and the row count meets stage_parquet_threshold_rows (default 1000):

import os

from sqlspec.adapters.databricks import DatabricksConfig

config = DatabricksConfig(
    connection_config={
        "server_hostname": os.environ["DATABRICKS_SERVER_HOSTNAME"],
        "http_path": os.environ["DATABRICKS_HTTP_PATH"],
        "access_token": os.environ["DATABRICKS_ACCESS_TOKEN"],
        "staging_allowed_local_path": ["/tmp/sqlspec-staging"],
    },
    driver_features={
        "enable_volume_staging": True,
        "staging_volume_path": "/Volumes/analytics/staging/ingest",
        "stage_parquet_threshold_rows": 1000,
    },
)

When staging_allowed_local_path includes a writable directory (or allows a local Parquet file passed directly to load_from_storage()), SQLSpec uploads Parquet via PUT '<local_parquet>' INTO '/Volumes/.../sqlspec_<uuid>.parquet' OVERWRITE. When no writable local staging directory is configured, load_from_arrow() streams an in-memory Parquet buffer via PUT '__input_stream__' INTO '/Volumes/.../sqlspec_<uuid>.parquet' OVERWRITE with input_stream. The driver then executes COPY INTO <table> FROM '/Volumes/.../sqlspec_<uuid>.parquet' FILEFORMAT = PARQUET (creating the target Delta table first when if_not_exists=True, or clearing existing rows with DELETE FROM when overwrite=True) and always runs REMOVE '/Volumes/.../sqlspec_<uuid>.parquet' in a finally block so failed loads never orphan Volume files.

When Volumes staging is disabled or the payload has fewer rows than stage_parquet_threshold_rows, load_from_arrow() falls back to batched INSERT statements via execute_many(). Pass stage_table=True with conflict_keys for staged MERGE INTO upserts. See Arrow and storage.

SQL Parameters, Async Warehouse Queries, and Extension Stores

SQLSpec compiles Databricks statements using SQLGlot's built-in databricks dialect with backtick-quoted 1-, 2-, and 3-part identifiers (catalog.schema.table). The default execution parameter style is qmark (?). Set paramstyle="named" in connection_config to send :param bindings directly on Databricks Runtime >=14.2.

execute_script() splits multi-statement SQL with SQLSpec's Databricks splitter—keeping backtick identifiers, BEGIN ATOMIC / CASE blocks, and BEGIN TRANSACTION; intact—and executes each statement on its own managed cursor. For long-running warehouse jobs, submit statements without blocking and retrieve or cancel them by query ID:

with config.provide_session() as session:
    query_id = session.execute_async_query(
        "SELECT COUNT(*) AS total FROM analytics.reporting.events"
    )
    result = session.fetch_async_query_result(query_id)

Call session.cancel_query(query_id) to cancel an in-flight warehouse query and close its cursor. All driver methods are synchronous Python calls; async web frameworks bridge them through sqlspec.utils.sync_tools.async_().

  • Litestar sessions: DatabricksStore (sqlspec.adapters.databricks.litestar) persists binary session payloads in Delta BINARY columns using MERGE INTO (UNHEX(?)) upserts and Delta-safe TTL expiration queries.
  • Event queues: DatabricksEventQueueStore (sqlspec.adapters.databricks.events) stores payloads in STRING / TIMESTAMP Delta columns and uses the lock-free poll_queue backend (select_for_update=False, skip_locked=False, poll_interval=2.0, lease_seconds=60).
  • Google ADK: DatabricksADKStore and DatabricksADKMemoryStore (sqlspec.adapters.databricks.adk) support 3-part Unity Catalog table names, STRING JSON state columns, MERGE INTO scoped-state upserts, and case-insensitive CONTAINS memory search (vector embeddings are unsupported).

Built-in schema reconciliation creates extension tables on Delta Lake without secondary indexes.

Tenant Isolation

Set driver_features={"tenant_strategy": "catalog_schema"} (or "default" / True) to isolate each session to a tenant's Unity Catalog catalog and schema through DatabricksCatalogSchemaStrategy. Pass DatabricksCatalogSchemaStrategy(mode="catalog_schema") to require both catalog and schema on every lease, or mode="catalog" to switch catalogs only.

import os

from sqlspec.adapters.databricks import DatabricksConfig

config = DatabricksConfig(
    connection_config={
        "server_hostname": os.environ["DATABRICKS_SERVER_HOSTNAME"],
        "http_path": os.environ["DATABRICKS_HTTP_PATH"],
        "access_token": os.environ["DATABRICKS_ACCESS_TOKEN"],
    },
    driver_features={"tenant_strategy": "catalog_schema"},
)

with config.provide_session(tenant="prod.acme") as session:
    rows = session.select("SELECT order_id FROM orders")

On checkout, DatabricksCatalogSchemaStrategy validates ordinary identifiers ([A-Za-z_][A-Za-z0-9_]*, up to 255 characters), captures the baseline scope via SELECT current_catalog(), current_schema(), issues backtick-quoted USE CATALOG / USE SCHEMA statements, and verifies the active scope before yielding the session. On exit, DatabricksTenantLease restores and verifies the baseline scope before returning the connection to the pool; any checkout, restore, or verification failure discards the connection. Pass an explicit DatabricksCatalogSchemaStrategy(mode="schema", catalog="prod", schema_prefix="tenant_") when switching schemas within a fixed catalog. Standalone create_connection() is rejected while tenant isolation is active; use provide_session() or provide_connection(). See Multi-Tenancy.

Read Warehouses and Replicas

Pass replicas="/sql/1.0/warehouses/<ro-warehouse-id>", a databricks:// URL, or a mapping of overrides to route read sessions onto a separate SQL Warehouse. Derived pools retain DatabricksTenantLease and merge session_configuration and query_tags overrides without mutating the primary configuration. See Read Replicas and Replica Operations.

Unity Catalog Introspection and Type Mappings

session.data_dictionary (DatabricksSyncDataDictionary) reflects schemas, objects, tables, columns, constraints, foreign keys, views, routines, and DDL from system.information_schema with 3-part catalog.schema.table qualification. When system.information_schema is unavailable—such as on legacy hive_metastore catalogs or permission-restricted workspaces—introspection falls back automatically to SHOW SCHEMAS, SHOW TABLES, and DESCRIBE TABLE. Indexes, sequences, privileges, and dependencies are reported as unsupported.

Databricks SQL Python / Arrow
TINYINT / BYTE, SMALLINT / SHORT, INT, BIGINT / LONG int; pa.int8(), pa.int16(), pa.int32(), pa.int64()
FLOAT, DOUBLE, DECIMAL(p, s) float, Decimal; pa.float32(), pa.float64(), pa.decimal128(p, s)
STRING, BINARY, BOOLEAN str, bytes, bool; pa.string(), pa.binary(), pa.bool_()
TIMESTAMP, TIMESTAMP_NTZ, DATE datetime (UTC-aware or naive), date; pa.timestamp("us", tz="UTC"), pa.timestamp("us"), pa.date32()
VARIANT, STRUCT, ARRAY, MAP, JSON Decoded Python JSON values for row results (enable_json_deserialization=True); native Arrow complex types via Cloud Fetch (_use_arrow_native_complex_types=True)

See the adapter API and catalog reference.