Skip to main content

Databricks Destination

Write data back to Databricks Delta Lake tables via the Databricks SQL Connector. Supports INSERT, MERGE (upsert), and sync.mode: mirror (upsert + DELETE-missing) — the same modes as the Snowflake destination.

YAML Example — INSERT (append)​

destination:
type: databricks
host_env: DATABRICKS_HOST
http_path_env: DATABRICKS_HTTP_PATH
token_env: DATABRICKS_TOKEN
catalog: main
schema: default
table: user_events
mode: insert

YAML Example — MERGE (upsert)​

destination:
type: databricks
host_env: DATABRICKS_HOST
http_path_env: DATABRICKS_HTTP_PATH
token_env: DATABRICKS_TOKEN
catalog: main
schema: default
table: user_scores
mode: merge
upsert_key: [user_id]

YAML Example — Mirror (upsert + delete-missing)​

destination:
type: databricks
host_env: DATABRICKS_HOST
http_path_env: DATABRICKS_HTTP_PATH
token_env: DATABRICKS_TOKEN
catalog: main
schema: analytics
table: active_users
upsert_key: [user_id] # required for mirror

sync:
mode: mirror # forces MERGE write path + end-of-sync DELETE

Configuration​

FieldTypeDefaultDescription
type"databricks"—Required
host_envstring—Env var name holding the workspace hostname (e.g. dbc-abc12345-1234.cloud.databricks.com)
http_path_envstring—Env var name holding the SQL warehouse HTTP path (e.g. /sql/1.0/warehouses/abc123def456)
token_envstring—Env var name holding a Databricks personal access token (PAT, starts with dapi)
catalogstring—Unity Catalog catalog name. Use hive_metastore for legacy workspaces.
schemastring—Database/schema name within the catalog
tablestring—Target Delta Lake table name
modeinsert | mergeinsertWrite mode. merge requires upsert_key.
upsert_keylist[str] | nullnullColumn list that uniquely identifies a row. Required for mode: merge and for sync.mode: mirror. Composite keys supported ([tenant_id, user_id]).

Authentication​

Databricks SQL Connector authenticates via a personal access token (PAT). Generate one in the Databricks workspace at User Settings → Developer → Access tokens.

export DATABRICKS_HOST=dbc-abc12345-1234.cloud.databricks.com
export DATABRICKS_HTTP_PATH=/sql/1.0/warehouses/abc123def456
export DATABRICKS_TOKEN=dapi-xxxxxxxxxxxxxxxxxxxx

The token-bearing principal needs:

  • USAGE on the catalog and schema
  • MODIFY on the target table
  • CREATE on the schema (for the merge-path staging table — see below)

OAuth M2M / service principal flows are not yet supported. Track #634 if you need them — for now use a PAT on a service-principal-scoped account.

Write modes​

mode: insert​

Issues one INSERT INTO catalog.schema.table (...) VALUES (...) per record. Best for append-only workloads — event streams, audit logs, telemetry.

Errors at the row level are tracked in result.row_errors; the sync continues for the rest of the batch unless on_error: fail.

mode: merge​

Creates a uniquely-named Delta scratch table (catalog.schema.__drt_staging_<table>), stages rows into it via per-row INSERT, then issues MERGE INTO target USING staging ON <upsert_key> WHEN MATCHED THEN UPDATE WHEN NOT MATCHED THEN INSERT, and finally DROP TABLE the staging table.

Why a Delta scratch table and not CREATE TEMP TABLE? Databricks Delta Lake doesn't have session-local tables — the standard CREATE TEMP TABLE syntax isn't supported. A uniquely-named scratch table in the same catalog.schema is the idiomatic shape. The __drt_staging_* prefix makes it identifiable in audit logs.

Composite keys are supported (upsert_key: [tenant_id, user_id]) — the ON clause becomes target.tenant_id = source.tenant_id AND target.user_id = source.user_id.

If every column is in upsert_key, the MERGE skips the UPDATE clause (no non-key columns to update); the resulting statement is effectively INSERT-IF-NOT-EXISTS.

sync.mode: mirror​

Mirrors the source table to the destination: upserts source rows AND deletes destination rows whose upsert_key was not observed in the source. Forces the MERGE write path regardless of config.mode, so the only YAML changes needed are:

destination:
...
upsert_key: [user_id] # required
sync:
mode: mirror

End-of-sync, drt issues a single DELETE FROM catalog.schema.table WHERE upsert_key NOT IN (observed) against the destination. Keys are staged in a scratch Delta table so the operation is not limited by the driver's 255 native-parameter ceiling. Composite keys use Delta's supported MERGE anti-join with WHEN NOT MATCHED BY SOURCE THEN DELETE; Delta rejects tuple IN predicates.

Safety guard: if no batch ever produced records (source returned zero rows), the DELETE is skipped entirely — protects against wiping the destination when the source is transiently empty.

Run-time change guards (sync.guards.max_deletes / max_delete_pct): Delta has no multi-statement rollback, so drt counts first. It runs a COUNT(*) over the exact predicate of the staged DELETE/MERGE (and the scoped table size when a percentage is set), refuses before deleting anything if a limit is exceeded, and then re-checks the statement's own result row. If a concurrent writer made the statement remove more rows than were counted and the larger value exceeds a limit, or the result row cannot be read back, drt raises an error saying the deletion is already committed (never "nothing was deleted"); recover with RESTORE TABLE ... TO VERSION AS OF. Tracked mirror takes its percentage denominator from the state table and fails the percentage closed when legacy scope-less rows make that denominator inexact; diff mirror has no percentage baseline, so use max_deletes there. Replace-swap compares live keys absent from the shadow table before INSERT OVERWRITE (no table lock exists: a concurrent writer to the shadow is a documented residual). drt run --force-guards proceeds and records the override.

Mirror semantics fit the same shape as Postgres / MySQL / ClickHouse / Snowflake mirror destinations (see #340) — same upsert_key contract, same source-key-cardinality memory bound on _mirror_keys.

Diff mirror (mirror.strategy: diff, #1110/#1177) — delete only source-snapshot removals:

sync:
mode: mirror
incremental_strategy: diff
mirror:
strategy: diff

Added and changed rows follow the normal Delta MERGE write path; finalize_sync stages exactly the keys source-side snapshot diff classified as removed and deletes only matches. Single-column keys use DELETE ... IN (SELECT ...); composite keys use MERGE ... WHEN MATCHED THEN DELETE, avoiding Delta's unsupported multi-column tuple-IN predicate. A removal-only run still performs this finalizer even when no records were loaded in the run, and --dry-run --diff previews the same removed-key list without an additional destination scan.

As on Postgres, MySQL, Snowflake, and ClickHouse, strategy: diff does not accept mirror.scope: the source snapshot comparison already provides the exact row-level removal set.

Tracked mirror (mirror.strategy: tracked, #686/#692) — for tables the application also writes to:

sync:
mode: mirror
mirror:
strategy: tracked # default: "destination" (the NOT IN behaviour above)

Same Census-style semantics as the other three dialects (see the Postgres tracked-mirror section for the full write-up): drt persists the set of upsert_key tuples it has itself synced in a drt-managed catalog.schema._drt_synced_keys Delta table, and each run deletes only previously-synced − current-source keys.

The target DELETE reuses the exact same staged-anti-join mechanism the destination-strategy DELETE above already needs (_delete_via_staged_keys) — a tracked table's stale-key list can just as easily exceed the native ? paramstyle's 255-marker-per-statement limit as the destination-strategy diff can, so there was never a simpler path available here even for the tracked case. State reads/writes bind a single sync_name parameter (well under the limit) and don't need staging.

Scoped mirror (mirror.scope, #687/#692): scope: [parent_id] restricts the mirror DELETE to rows whose scope values appeared in this run's source — the fit for 1:N regeneration. Composable with strategy: tracked (#694) provided scope is a subset of upsert_key. See the Postgres scoped-mirror section for the full semantics. Scope values are inlined as ? markers directly (not staged) — expected distinct-parent cardinality stays well under the marker limit even when the key cardinality it restricts does not.

sync.mode: replace (#643)​

Rebuilds the destination table from the current source snapshot. Two strategies:

replace_strategy: truncate (default) — TRUNCATE TABLE once, then INSERT every batch.

sync:
mode: replace # replace_strategy defaults to truncate

replace_strategy: swap — zero-downtime. Delta has no ALTER TABLE … SWAP WITH, so drt stages every batch into a shadow <table>__drt_swap (CREATE OR REPLACE TABLE … AS SELECT * … WHERE 1=0 clones the schema), then at end-of-sync runs an atomic INSERT OVERWRITE <table> SELECT * FROM <shadow> and drops the shadow. INSERT OVERWRITE commits a new Delta table version atomically (snapshot isolation), so readers always see the full old or full new data — never a half-written table — and the target table object is preserved (grants, properties, clustering / liquid clustering all survive; the table itself is never recreated).

sync:
mode: replace
replace_strategy: swap
  • First run (target table doesn't exist yet) falls through to a direct write into the target and skips the swap.
  • Interrupted swaps leave a <table>__drt_swap shadow; drt clean --orphans lists and drops them (only __drt_swap-suffixed tables are eligible).

Swap requires mode: replace (enforced by config validation). The same replace_strategy: swap is supported on Postgres, MySQL, ClickHouse, and Snowflake.

Sync modes​

sync.modeBehaviour on Databricks
fullRe-extracts every run + writes via config.mode (insert / merge).
incrementalWatermark-based — extracts rows with cursor_field > last_value, writes via config.mode.
upsertSame as incremental but with upsert_key enforced.
mirrorForces the MERGE write path + end-of-sync DELETE. upsert_key required.
replaceFull table replace. replace_strategy: truncate (default) TRUNCATEs + re-inserts; replace_strategy: swap is zero-downtime via a shadow + atomic INSERT OVERWRITE. See above.

Complex columns (STRUCT / ARRAY / MAP / VARIANT)​

dict and list values bound for a Databricks STRUCT / ARRAY / MAP / VARIANT column can't be inserted as plain parameters — Databricks needs them reconstructed with from_json (or parse_json for VARIANT). By default (introspect_schema: true) drt reads <catalog>.information_schema.columns for the target table once per sync, detects the complex columns, and rewrites the INSERT to wrap them:

-- a STRUCT column "profile" and a VARIANT column "doc" are loaded as:
INSERT INTO main.default.t (id, profile, doc)
SELECT %s, from_json(%s, 'struct<city: string, zip: string>'), parse_json(%s)

The from_json DDL (e.g. array<string>, struct<...>) comes from the column's full_data_type in information_schema; VARIANT columns use parse_json (no DDL). The value itself stays a bind — the DDL is a literal read verbatim from information_schema. So a dict/list lands as a proper complex value instead of a stringified repr, with no configuration. When no column needs wrapping, the INSERT is the unchanged VALUES (...) form. Introspection is best-effort: if information_schema isn't readable for the token's principal, drt falls back to binding values directly. Disable with introspect_schema: false.

As a source — retry on transient extract failures (#766)​

When Databricks is the source of a sync, opening the connection and running the model query are retried automatically (3 attempts, exponential backoff from 1s, capped at 60s). No configuration — it is always on, and separate from the sync.retry knobs that govern the load side.

Retried, from databricks.sql.exc:

  • OperationalError — the connector's class for connection and service-availability trouble.
  • RequestError — a failed request to the SQL endpoint. In practice this is the SQL warehouse cold start: a stopped warehouse takes minutes to resume, and the first requests fail while it does. Observed during the #654 real-warehouse smoke programme, and the single most valuable retry here — the warehouse is coming up, and the very same query succeeds shortly after. Before #766 a scheduled sync hitting an auto-stopped warehouse simply failed.

Not retried: ProgrammingError (bad SQL, missing table), DatabaseError, NotSupportedError. The driver derives its classes from PEP 249, so OperationalError and ProgrammingError are siblings under DatabaseError — matching the specific classes keeps a SQL typo from being retried. (RequestError sits outside that tree, subclassing the driver's own Error.)

If your warehouse auto-stops aggressively, note that 3 attempts with backoff capped at 60s covers a short resume, not an arbitrarily long one. A warehouse with a multi-minute cold start may still exhaust the attempts.

⚠️ Scope: connection + query execution + fetching the result set only. A failure after the first row has been yielded is not retried and fails the sync — those rows are already loaded into the destination and cannot be un-sent. See API_REFERENCE for the full rationale.

As a source — streaming extraction (#765)​

Rows are read by iterating the cursor rather than buffered whole with fetchall(), so peak memory tracks the batch instead of the result set. The cursor's iterator is a fetchone() loop over the result set, so this streams without any extra configuration.

Databricks takes no fetch_size (unlike Postgres/Redshift/Snowflake): its cursor exposes no arraysize, and fetchmany(size) takes a required argument rather than reading a configured one, so there would be nothing for a profile field to set.

⚠️ The connection is held open for the whole load, not just the extract. A slow destination keeps the SQL warehouse busy for the duration. Per #766 a failure after the first row has been yielded is not retried.

As a source — diff-based incremental (#1114)​

Databricks supports sync.incremental_strategy: diff for models without a reliable cursor column. Each run materializes the full model result in a Delta table named _drt_snapshot_<sync_name>_<digest> under the source profile's managed_schema, then classifies added, changed, and removed rows with server-side joins on destination.upsert_key. Added and changed rows follow the normal upsert path; removed keys are exposed through SyncResult.diff_removed_keys, power mirror.strategy: diff where the destination supports it, and appear in --dry-run --diff deletion previews.

# ~/.drt/profiles.yml
databricks_prod:
type: databricks
server_hostname: dbc-abc123.cloud.databricks.com
http_path: /sql/1.0/warehouses/abc123xyz
access_token_env: DATABRICKS_TOKEN
catalog: main # required for drt-managed snapshot tables
schema: analytics
managed_schema: _drt # default; drt needs table create/replace here
destination:
type: databricks
# ... connection fields ...
mode: merge
upsert_key: [id]

sync:
mode: upsert # or mirror
incremental_strategy: diff
diff:
hash_columns: all # or an explicit non-empty column list

Column matching follows Delta's case-insensitive identifier rules (id finds ID), while emitted key names are restored to the spelling configured in upsert_key. hash_columns: all compares every output column except the key; an explicit list is validated against the actual CTAS schema. Changed-row SQL uses typed xxhash64(...) inputs paired with an explicit nullness flag for every column, so SQL NULL and an empty string are distinct without delimiter ambiguity.

The baseline advances only after a non-dry-run, unlimited sync finishes with zero row failures. Scratch is rebuilt atomically with Delta CREATE OR REPLACE TABLE ... AS SELECT, so a failed delivery leaves the old baseline intact and the same diff is detected on the next run. Promotion is another single CREATE OR REPLACE TABLE ... AS SELECT Delta commit; unlike DROP + RENAME, readers never observe an absent or partially populated baseline. Diff therefore requires CREATE TABLE/MODIFY privileges in managed_schema; cursor incremental remains the read-only alternative.

Concurrent runs of the same diff sync are unsupported. A per-run UUID is stored in the scratch table's TBLPROPERTIES; each classification stream checks it before and after reading, and commit checks it before and after baseline replacement. If another run replaced scratch during promotion, drt restores the previous Delta baseline version (or removes the first-run baseline) and fails loudly. This is best-effort overlap detection, not a lock: Databricks has no multi-statement transaction that can span extraction, destination delivery, the property check, and replacement, so a narrow check-to-statement/recovery race remains. Use drt serve request coalescing (#854) or scheduler overlap protection.

Notes​

  • Requires pip install drt-core[databricks] (depends on databricks-sql-connector>=3.0).
  • Query tagging (#768): every write query gets both the driver's native query_tags connect kwarg (a QUERY_TAGS session config applied to every query the session runs) and a leading /* drt app=drt sync=<name> run_id=<id> ... */ comment, by default — see query_tagging in docs/llm/API_REFERENCE.md.
  • Target table must be a Delta Lake table. Non-Delta formats fail at MERGE INTO time with a Databricks server error.
  • Empty batches short-circuit before any databricks.sql import or warehouse call — the same "no driver was imported" contract used by the SQL destinations (#595). A run with zero source rows produces zero warehouse statements.
  • Errors during the connect step (missing env vars, bad token, network) raise immediately; errors during row INSERT are captured per-row and surface in result.row_errors.
  • The __drt_staging_* scratch table is dropped at the end of every merge run. If a sync is interrupted mid-merge, the next run's CREATE OR REPLACE TABLE overwrites it cleanly.
  • Unity Catalog three-part names are the default. Workspaces still on Hive Metastore should use catalog: hive_metastore.

References​