dbsql

package module
v2.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 44 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Databricks SQL Driver for Go

A database/sql driver for Databricks SQL. It connects to Databricks SQL Warehouses and clusters and runs queries through Go's standard database/sql interface.

Contents

Quick start

import (
  "context"
  "database/sql"
  _ "github.com/databricks/databricks-sql-go/v2"
)

db, err := sql.Open("databricks", "token:********@********.databricks.com:443/sql/1.0/endpoints/********")
if err != nil {
  panic(err)
}
defer db.Close()

rows, err := db.QueryContext(context.Background(), "SELECT 1")
defer rows.Close()

See doc.go for full package documentation or the Databricks documentation for the SQL Driver for Go.

Using the driver in your own project? Add it with go get github.com/databricks/databricks-sql-go/v2 and go build — you never clone this repo. A default Thrift build pulls no kernel binaries. The "Cloning" section below is only for contributors working in this repo directly.

Migrating from v1

Install v2 with go get github.com/databricks/databricks-sql-go/v2@v2.0.0 and add /v2 to all driver import paths, including subpackages such as auth and rows.

If you use the Arrow batch API, migrate Arrow imports from github.com/apache/arrow/go/v12 to github.com/apache/arrow-go/v18. rows.ArrowBatchIterator now returns v18 arrow.RecordBatch values and *arrow.Schema metadata.

Cloning the repository

This repo is small: for the SEA/kernel backend it commits only the C header (internal/backend/kernel/include/databricks_kernel.h). The prebuilt kernel archives (per-platform libdatabricks_sql_kernel.a, ~60–95 MB each) live in a separate repo, databricks-sql-kernel-bindings, one Go module per platform. The driver requires them, so go get pulls only your platform's archive — no build step (see Building).

A plain git clone of this repo is cheap. Sparse-clone the bindings repo instead if its committed archives make a full clone heavy:

git clone --filter=blob:none --sparse https://github.com/databricks/databricks-sql-kernel-bindings
cd databricks-sql-kernel-bindings
git sparse-checkout set --no-cone '/*' '!/lib' 'lib/darwin_arm64'   # keep only your platform

Choosing a backend (Thrift vs SEA/kernel)

The driver has two execution backends, selected once per connection:

Backend Transport Default? Build requirement
Thrift / HiveServer2 Thrift RPC over HTTP ✅ yes pure Go, CGO_ENABLED=0, cross-compilable
SEA / kernel (experimental) Statement Execution API (REST) via the Rust databricks-sql-kernel, over a cgo C ABI no (opt-in) -tags databricks_kernel and CGO_ENABLED=1; links the kernel static library

Thrift is the default and needs no special setup. Select the SEA/kernel backend per connection either way:

  • Connector option: dbsql.WithUseKernel(true)
  • DSN parameter: useKernel=true

If the binary was not built with the databricks_kernel tag, selecting the kernel backend returns an error wrapping dbsqlerr.ErrKernelNotCompiled at connect — it never silently falls back to Thrift.

Parameter parity. Parameters are intended to behave identically on both backends. Where a backend can't honor an option it is rejected at connect or execute (wrapping dbsqlerr.ErrNotSupportedByKernel), not silently ignored. The Connection properties Protocol column records, per parameter, whether it applies to Both, Thrift-only, or SEA-only.

Building

Requires Go 1.27.3 or newer.

The two backends differ at build time, not just at connect.

Thrift (default) — pure Go, no extra step

Pure Go, CGO_ENABLED=0, go get-able, cross-compilable to any GOOS/GOARCH. No C, no Rust, no linked native library.

go build ./...
go test  ./...

# Repo Makefile equivalents (both CGO_ENABLED=0):
make build      # multi-arch pure-Go binaries (linux + darwin)
make test       # pure-Go unit tests

Cross-compiling is free, e.g. GOOS=windows GOARCH=amd64 go build ./....

SEA/kernel — cgo, no Rust

The kernel backend compiles in only under the databricks_kernel build tag with CGO_ENABLED=1. The prebuilt libdatabricks_sql_kernel.a for your platform is pulled automatically as a Go module dependency and linked — no Rust toolchain, no build step. You need only a C toolchain (cgo) on a supported platform: linux amd64/arm64/arm, darwin amd64/arm64, windows amd64/arm64.

CGO_ENABLED=1 go build -tags databricks_kernel ./...

Carry both flags — dropping either produces a pure-Go binary where WithUseKernel(true) fails at connect. Then select the backend per connection with WithUseKernel(true) (or useKernel=true in the DSN).

Build from source (contributors)

To build the archive from the pinned kernel revision instead of using the prebuilt module — for kernel development or an unsupported platform — you need a Rust toolchain (cargo, pinned in rust-toolchain.toml) and network access to clone databricks-sql-kernel at KERNEL_REV:

make kernel-lib     # clone + cargo-build the pinned archive into the cgo link dir
make build-kernel   # == CGO_ENABLED=1 go build -tags databricks_kernel ./...
make test-kernel    # build KERNEL_REV and run kernel-tagged unit tests against it

Stage a prebuilt archive without Rust via make kernel-lib KERNEL_LOCAL_A=/path/to/libdatabricks_sql_kernel.a.

Build differences at a glance
Thrift (default) SEA/kernel
Build tag none -tags databricks_kernel
cgo CGO_ENABLED=0 CGO_ENABLED=1
Native lib none prebuilt libdatabricks_sql_kernel.a, auto-linked via Go module
Extra toolchain none C toolchain (cgo) — no Rust
Prep step none none (prebuilt); make kernel-lib only for a source build
One-shot build go build ./... CGO_ENABLED=1 go build -tags databricks_kernel ./...
Platforms any GOOS/GOARCH linux amd64/arm64/arm · darwin amd64/arm64 · windows amd64/arm64

Connecting

DSN (Data Source Name)
token:[your token]@[Workspace hostname]:[Port number][Endpoint HTTP Path]?param=value&param=value

The token:[your token]@ prefix authenticates with a personal access token (PAT). For other authentication types, omit the prefix and use the authType, clientID/clientSecret, or accessToken parameters — see Authentication.

db, err := sql.Open("databricks",
  "token:<pat>@<host>:443/sql/1.0/warehouses/<id>?timeout=1000&maxRows=1000")

To use the SEA/kernel backend, append useKernel=true (and, optionally, warehouseId=<id>):

token:<pat>@<host>:443/sql/1.0/warehouses/<id>?useKernel=true
Connector object

You can also connect with a connector object built from functional options:

import (
  "database/sql"
  dbsql "github.com/databricks/databricks-sql-go/v2"
)

connector, err := dbsql.NewConnector(
  dbsql.WithServerHostname(<host>),
  dbsql.WithPort(<port>),
  dbsql.WithHTTPPath(<http path>),
  dbsql.WithAccessToken(<your token>),
  // dbsql.WithUseKernel(true), // opt into the SEA/kernel backend
)
if err != nil {
  log.Fatal(err)
}
db := sql.OpenDB(connector)
defer db.Close()

See doc.go or connector.go for the full set of functional options.

Connection properties

See CONNECTION_PARAMETERS.md for every connection, session, and per-statement parameter the driver accepts, and whether each one applies to the Thrift backend (default), the SEA/kernel backend, or both. The sections below cover the same parameters inline.

Optional DSN parameters are appended as ?param=value&param=value; the equivalent connector options are listed alongside. The Protocol column shows applicability:

  • Both — honored identically on Thrift and SEA/kernel.
  • Thrift only — honored on Thrift; rejected at connect on the kernel path (wraps ErrNotSupportedByKernel) unless noted "inert" (accepted, no effect).
  • SEA only — kernel path only. The experimental WithKernel* options are rejected on Thrift when set without WithUseKernel(true) (wraps ErrRequiresKernelBackend); warehouseId is the exception — Thrift silently ignores it (see its row).

Any parameter not recognized below (e.g. ansi_mode, timezone) is passed through as a session parameter on both backends.

Endpoint & routing
DSN parameter Connector option Protocol Default Description
(host) WithServerHostname Both (required) Workspace hostname.
(path) WithHTTPPath Both (required) Warehouse/endpoint HTTP path.
(port) WithPort Thrift only 443 Kernel connects on 443 only and rejects any other port.
warehouseId WithWarehouseID SEA only Bare warehouse id; the kernel routes by it (preferred over the HTTP path). The Thrift backend ignores it.
catalog WithInitialNamespace Both Initial catalog. Kernel applies it post-connect via USE CATALOG.
schema WithInitialNamespace Both Initial schema. Kernel applies it post-connect via USE SCHEMA.
useKernel WithUseKernel Both false Select the SEA/kernel backend. Requires a databricks_kernel build.
Query execution
DSN parameter Connector option Protocol Default Description
maxRows WithMaxRows Thrift only (inert on kernel) 100000 Max rows per fetch. On the kernel path the kernel manages paging, so this is accepted but has no effect.
timeout WithTimeout Thrift only no timeout Server-side query timeout, in seconds. On the kernel path use the STATEMENT_TIMEOUT session parameter instead.
— WithClientQueryTimeout SEA only legacy 600s ceiling Client-side execution deadline. Zero or the maximum time.Duration is unlimited. Connector-only; no DSN spelling.
userAgentEntry WithUserAgentEntry Both Identifies your application (partners/ISVs), format <isv-name+product-name>.
(session param) WithSessionParams Both Arbitrary session confs (e.g. ansi_mode, STATEMENT_TIMEOUT, QUERY_TAGS).
(via session param) WithQueryTags Both Session-level query tags (serialized into QUERY_TAGS).
timezone WithSessionParams(timezone=…) Both Session time zone (e.g. America/Los_Angeles).
enableMetricViewMetadata WithEnableMetricViewMetadata Both false Enables metric-view metadata (spark.sql.thriftserver.metadata.metricview.enabled=true).
Retry / backoff
Connector option Protocol Default Description
WithRetries(retryMax, waitMin, waitMax) Both 4, 1s, 30s Retry attempts and exponential-backoff bounds. retryMax < 0 disables retries.
WithKernelRetryOverallTimeout(d) SEA only kernel default (900s) Cumulative retry budget across all attempts. No Thrift equivalent.
Result rendering
DSN parameter Connector option Protocol Default Description
useArrowNativeDecimal WithArrowNativeDecimal Thrift only (inert on kernel) false Thrift: return DECIMAL as native Arrow decimal128 (lossless string when scanned via database/sql). The kernel path already renders DECIMAL as the exact string regardless.
WithKernelDecimalAsFloat(b) SEA only false Scan top-level DECIMAL as lossy float64 instead of the exact string.
enableGeoSpatialSupport WithEnableGeoSpatialSupport(b) SEA only false true: return top-level GEOMETRY / GEOGRAPHY as EWKB []byte with the per-row SRID embedded and a sql.RawBytes scan type; GetArrowBatches retains the full {srid,wkb} struct with OGC WKB. false: return WKT / EWKT strings with a string scan type. Both modes report the server SQL name including its declared SRID, such as GEOMETRY(0), GEOGRAPHY(4326) or GEOMETRY(ANY), rather than the bare names previously reported in enabled mode.

See Cloud Fetch, TLS, and Proxy for the remaining groups. Telemetry parameters are covered under Telemetry.

Authentication

Method DSN Connector option Protocol
Personal access token (PAT) token:<t>@…, or accessToken= / authType=Pat WithAccessToken Both
OAuth machine-to-machine (M2M) clientID=+clientSecret= / authType=OauthM2M WithClientCredentials Both
OAuth user-to-machine (U2M) authType=OauthU2M WithAuthenticator (u2m) Both
Custom / external / static token provider — WithTokenProvider, WithExternalToken, WithStaticToken Thrift only
Federated token provider — WithFederatedTokenProvider* Both

PAT (default): supply token:<pat>@… in the DSN, or WithAccessToken.

OAuth M2M: leave the token:...@ prefix off and pass the service principal's clientID and clientSecret:

[host]:443[path]?authType=OauthM2M&clientID=<id>&clientSecret=<secret>

authType=OauthM2M is optional — supplying clientID + clientSecret selects M2M. M2M requests the all-apis scope by default. For a secret limited to other scopes (e.g. sql), use WithAuthenticator(m2m.NewAuthenticatorWithScopes(id, secret, host, []string{"sql"})).

OAuth U2M (interactive browser login):

[host]:443[path]?authType=OauthU2M

Notes for the SEA/kernel backend:

  • The kernel snapshots one WithFederatedTokenProvider* token during setup; AndClientID also forwards the SP-wide client ID. Expired tokens require a new connection.
  • U2M is interactive: on a cache miss, connecting launches the browser and a connect-context deadline is not honored during the login window. U2M scopes are at parity with Thrift. Use PAT or M2M for headless/deadline-bound connects.
  • Custom token-provider / external / static authenticators are Thrift only.
  • OAuth token caching/refresh is owned by the kernel on the kernel path (no driver config).

Cloud Fetch

Cloud Fetch increases performance of extracting large results by fetching data in parallel via cloud storage (more info).

DSN parameter Connector option Protocol Default Description
useCloudFetch WithCloudFetch Both true Enable Cloud Fetch. Set to false to fetch results through the SQL connection without direct cloud-storage access.
maxDownloadThreads WithMaxDownloadThreads Both Thrift 10; kernel 16 CloudFetch download window. On the kernel, bounds downloading and queued chunks ahead of consumption, excluding consumer buffers. Not a byte limit. An explicit value <= 0 warns and uses 10.
WithKernelMaxChunksInMemory(n) SEA only maxDownloadThreads when set; otherwise 16 Positive values override the standard setting and raw chunk session parameters.

The kernel snapshots these options when connecting. A positive WithKernelMaxChunksInMemory wins over a case-insensitive cloudfetch_max_chunks_in_memory session parameter, which wins over WithMaxDownloadThreads. Values above 256 are clamped. Invalid raw chunk parameters warn and retain the kernel default of 16. These settings count chunks, not bytes, and do not include consumer or application buffers.

On the Thrift backend:

token:<pat>@<host>:443[path]?useCloudFetch=true&maxDownloadThreads=3
# or disable it entirely:
token:<pat>@<host>:443[path]?useCloudFetch=false

TLS

Connector option Protocol Description
WithSkipTLSHostVerify() Both Disable TLS chain + hostname verification. Use only for internal private-link hostnames — this is susceptible to machine-in-the-middle attacks.
WithTransport(http.RoundTripper) Thrift only Supply a custom HTTP transport (e.g. a custom CA, mTLS, or proxy). Rejected on the kernel path (wraps ErrNotSupportedByKernel) — the kernel uses its own HTTP stack; use WithKernelTrustedCerts / WithKernelProxy there.
WithKernelTrustedCerts(pem) SEA only Add a PEM CA bundle on top of the system roots (for a re-signing proxy / on-prem CA). Needed because the kernel's TLS stack does not read SSL_CERT_FILE.
WithKernelClientCertificate(certPEM, keyPEM) SEA only Configure a paired mTLS client certificate and unencrypted private key. Both must be non-empty; PKCS#8 keys are recommended.
WithKernelSkipHostnameVerify() SEA only Skip only the hostname check while keeping chain validation (finer-grained than WithSkipTLSHostVerify).

Proxy

The Thrift and kernel backends both honor the standard HTTP_PROXY / HTTPS_PROXY / NO_PROXY environment variables.

Connector option Protocol Description
(environment) Both HTTP(S)_PROXY / NO_PROXY.
WithKernelProxy(KernelProxy{URL, Username, Password, BypassHosts}) SEA only Explicit proxy with out-of-band basic-auth credentials and a structured bypass list — the "advanced" fields the env-var path can't express. Overrides the environment proxy; a malformed URL is rejected at connect.

Data types

Apart from the configurable geospatial representation, results render byte-for-byte identically on both backends. Scalars, DECIMAL (exact string), TIMESTAMP (rendered in the session time zone), TIMESTAMP_NTZ (wall-clock fields preserved in a time.Time with a UTC location), INTERVAL, and nested ARRAY / MAP / STRUCT and VARIANT (as JSON) are supported. BINARY is returned as sql.RawBytes. Both backends return GEOMETRY / GEOGRAPHY as WKT / EWKT by default. Set enableGeoSpatialSupport=true on the kernel path to opt into EWKB. In both modes, ColumnType.DatabaseTypeName() reports the server SQL name with its declared SRID for top-level columns. With WithEnableGeoSpatialSupport(true), previously bare GEOMETRY / GEOGRAPHY names now include that SRID; match the family before ( when selecting a decoder. Thrift retains STRING when no readable Arrow schema is available.

In ARRAY / MAP / STRUCT JSON, non-finite FLOAT and DOUBLE values render as the strings "NaN", "Infinity", and "-Infinity", distinct from SQL NULL (null). Finite values remain JSON numbers. Use any or a custom decoder for fields that can contain special values; encoding/json does not unmarshal these strings into plain float32 or float64 fields. Top-level FLOAT / DOUBLE values remain numeric. Non-finite floating-point MAP keys use the same "NaN", "Infinity", and "-Infinity" spellings.

SQL type Go value NULL detection
TIME time.Time on 0001-01-01 UTC sql.NullTime.Valid or a nil *time.Time, never IsZero(); midnight is the zero time and JSON omitzero omits it.

SQL TIME values in Arrow results scan into time.Time (or any) on the reference date 0001-01-01 in UTC, preserving the Arrow second/millisecond/microsecond/nanosecond precision. The date and location are carriers only; session time zones do not shift the clock. Scanning into string uses database/sql's RFC3339Nano format (for example, 0001-01-01T09:15:00.123456Z). NULL scans into any as nil; use sql.NullTime or *time.Time for nullable typed values. Non-NULL midnight equals time.Time{} and has IsZero() == true, so detect NULL with sql.NullTime.Valid, not IsZero(); JSON fields tagged omitzero omit midnight. Do not call .In(location) on this date-less value: it shifts the clock and may introduce historical timezone offsets. To bind TIME in CAST(? AS TIME), pass value.Format("15:04:05.999999"), not the time.Time: time.Time binds as TIMESTAMP and can shift the clock in non-UTC sessions. Column metadata reports TIME and time.Time with no length, even for empty or NULL-only results. Nested TIME values in ARRAY / MAP / STRUCT JSON use clock-only strings with trailing fractional zeros omitted, such as "09:15:00.5" rather than "09:15:00.500000"; their text can differ from server-rendered TIME(p) values. On Thrift, TIME column metadata requires a server-supplied Arrow schema; without it, the legacy Thrift column metadata is retained. On SEA, UTF-8 fields tagged TIME describe empty manifest schemas; non-empty TIME is assumed to arrive as Arrow time32/time64, not UTF-8.

Live TIME tests require the e2e build tag: go test -tags e2e -run '^TestE2ETimeResults$' . or go test -tags databricks_kernel,e2e -run '^TestKernelE2ETimeResults$' .. They require the DATABRICKS_PECOTESTING_* credentials and a workspace with the TIME beta enabled; missing credentials or unavailable TIME support fail the tests.

On Thrift, TIMESTAMP_NTZ handling requires native timestamp fields in the server-supplied Arrow schema. Without that schema, NTZ still reports TIMESTAMP and uses session-location handling. String timestamps (UseArrowNativeTimestamp=false, an internal setting) and non-Arrow values also retain legacy session-location parsing.

Top-level VARIANT columns report VARIANT in sql.ColumnType.DatabaseTypeName() on both backends. Values stay JSON text, and the scan type (string) and length match a STRING column. Nested VARIANT (inside ARRAY, MAP or STRUCT) is not reported by name. On Thrift, detection reads the server-supplied Arrow schema; without it, VARIANT reports STRING.

Metadata is reached through SQL (SHOW, DESCRIBE, information_schema) on both backends — the driver exposes no GetCatalogs/GetSchemas/GetTables/GetColumns API (a database/sql limitation, not backend-specific).

Telemetry

The driver includes optional telemetry to help improve performance and reliability. Go wrapper telemetry applies to the default Thrift backend. When enableTelemetry is left unset (the default), a server-side feature flag decides whether wrapper telemetry is active — so it may be enabled without an explicit opt-in. Setting enableTelemetry explicitly overrides the flag. On the kernel backend, the Go wrapper skips its telemetry interceptor entirely so it does not duplicate kernel-owned telemetry; enableTelemetry and telemetry_batch_size are forwarded into the kernel telemetry config instead.

# force on (regardless of the server flag):
token:<pat>@<host>:443[path]?enableTelemetry=true
# force off:
token:<pat>@<host>:443[path]?enableTelemetry=false
DSN parameter Default Description
enableTelemetry unset (server flag decides) Force telemetry on/off, overriding the server feature flag.
telemetry_batch_size 200 Events per batch.
telemetry_flush_interval 30s Flush interval.
telemetry_retry_count — Deprecated and ignored (retries are owned by the HTTP client + circuit breaker); logs a one-time warning.
telemetry_retry_delay — Deprecated and ignored (see above).

Collected: query latency/performance, error codes (not messages), feature usage, driver version/environment. Not collected: SQL text, query results/values, table/column names, user identities or credentials. Telemetry has < 1% overhead and is protected by a circuit breaker. The kernel path additionally emits a connection-config telemetry event at connect (mode, auth mechanism/flow, proxy, arrow, query tags, metric-view); the Thrift path's telemetry is unchanged. See telemetry/DESIGN.md.

Examples

Runnable examples live in examples/. Notable ones:

Develop

make tools builds the development tools. The test runner is declared by the tool directive in go.mod, with its version pinned by the matching require line; it can also be run with go tool gotestsum. golangci-lint is installed separately at the version pinned in the Makefile and CI.

Lint

We use golangci-lint. In VS Code:

{
  "go.lintTool": "golangci-lint",
  "go.lintFlags": ["--fast"]
}
Unit tests
go test           # default (Thrift) backend, pure Go
make test-kernel  # kernel-tagged unit tests against the source-built KERNEL_REV

Issues

If you find any issues, feel free to create an issue or send a pull request directly.

Contributing

See CONTRIBUTING.md.

License

Apache 2.0

Documentation

Overview

Package dbsql implements the go driver to Databricks SQL

Usage

Clients should use the database/sql package in conjunction with the driver:

import (
	"database/sql"

	_ "github.com/databricks/databricks-sql-go/v2"
)

func main() {
	db, err := sql.Open("databricks", "token:<token>@<hostname>:<port>/<endpoint_path>")

	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
}

Connection via DSN (Data Source Name)

Use sql.Open() to create a database handle via a data source name string:

db, err := sql.Open("databricks", "<dsn_string>")

The DSN format is:

token:[my_token]@[hostname]:[port]/[endpoint http path]?param=value

Supported optional connection parameters can be specified in param=value and include:

  • catalog: Sets the initial catalog name in the session
  • schema: Sets the initial schema name in the session
  • maxRows: Sets up the max rows fetched per request. Default is 100000
  • timeout: Adds timeout (in seconds) for the server query execution. Default is no timeout
  • userAgentEntry: Used to identify partners. Set as a string with format <isv-name+product-name>
  • useCloudFetch: Used to enable cloud fetch for the query execution. Default is true
  • maxDownloadThreads: Sets the CloudFetch download window on both backends. When unset, defaults to 10 on Thrift and 16 on the kernel; an explicit value <= 0 logs a warning and uses 10
  • useArrowNativeDecimal: Returns DECIMAL columns as native Arrow decimal128 (via GetArrowBatches); when scanned through database/sql they are returned as lossless strings. Default is false
  • authType: Specifies the desired authentication type. Valid values are: Pat, OauthM2M, OauthU2M
  • accessToken: Personal access token. Required if authType set to Pat
  • clientID: Specifies the client ID to use with OauthM2M
  • clientSecret: Specifies the client secret to use with OauthM2M
  • useKernel: Routes execution through the SEA-via-kernel backend instead of Thrift. Requires a build with -tags databricks_kernel (CGO_ENABLED=1); the default pure-Go build returns a clear error. Default is false. See the kernel-backend section below
  • warehouseId: The bare SQL warehouse id, used by the kernel backend (which addresses a warehouse by id) in preference to the http path. Ignored by the Thrift backend

Supported optional session parameters can be specified in param=value and include:

  • ansi_mode: (Boolean string). Session statements will adhere to rules defined by ANSI SQL specification.
  • timezone: (e.g. "America/Los_Angeles"). Sets the timezone of the session

Connection via new connector object

Use sql.OpenDB() to create a database handle via a new connector object created with dbsql.NewConnector():

import (
	"database/sql"
	dbsql "github.com/databricks/databricks-sql-go/v2"
)

func main() {
	connector, err := dbsql.NewConnector(
		dbsql.WithServerHostname(<hostname>),
		dbsql.WithPort(<port>),
		dbsql.WithHTTPPath(<http_path>),
		dbsql.WithAccessToken(<my_token>)
	)
	if err != nil {
		log.Fatal(err)
	}

	db := sql.OpenDB(connector)
	defer db.Close()
	...
}

Supported functional options include:

  • WithServerHostname(<hostname> string): Sets up the server hostname. The hostname can be prefixed with "http:" or "https:" to specify a protocol to use. Mandatory
  • WithPort(<port> int): Sets up the server port. Mandatory
  • WithAccessToken(<my_token> string): Sets up the Personal Access Token. Mandatory
  • WithHTTPPath(<http_path> string): Sets up the endpoint to the warehouse. Mandatory
  • WithInitialNamespace(<catalog> string, <schema> string): Sets up the catalog and schema name in the session. Optional
  • WithMaxRows(<max_rows> int): Sets up the max rows fetched per request. Default is 100000. Optional
  • WithSessionParams(<params_map> map[string]string): Sets up session parameters including "timezone" and "ansi_mode". Optional
  • WithTimeout(<timeout> Duration). Adds timeout (in time.Duration) for the server query execution. Default is no timeout. Optional
  • WithClientQueryTimeout(<timeout> Duration). Bounds client-side statement execution on the kernel backend. Omitted preserves the legacy 600s ceiling; zero or the maximum Duration is unlimited. Requires WithUseKernel(true). Optional
  • WithUserAgentEntry(<isv-name+product-name> string). Used to identify partners. Optional
  • WithCloudFetch (bool). Used to enable cloud fetch for the query execution. Default is true. Optional
  • WithMaxDownloadThreads (<num_threads> int). Sets the CloudFetch download window on both backends. When unset, defaults to 10 on Thrift and 16 on the kernel; an explicit value <= 0 logs a warning and uses 10. Optional
  • WithAuthenticator (<authenticator> auth.Authenticator). Sets up authentication. Required if neither access token or client credentials are provided.
  • WithClientCredentials(<clientID> string, <clientSecret> string). Sets up Oauth M2M authentication.
  • WithUseKernel(<useKernel> bool). Routes execution through the SEA-via-kernel backend instead of Thrift. Requires a build with -tags databricks_kernel (CGO_ENABLED=1); the default build returns a clear error. Default is false. See the kernel-backend section below. Optional
  • WithWarehouseID(<id> string). The bare SQL warehouse id used by the kernel backend in preference to the http path; ignored by the Thrift backend. Optional

Query cancellation and timeout

Cancelling a query via context cancellation or timeout is supported.

// Set up context timeout
ctx, cancel := context.WithTimeout(context.Background(), 30 * time.Second)
defer cancel()

WithClientQueryTimeout is a separate, connector-only kernel option. Its deadline covers execution through terminal-state mapping, including the initial execute RPC and status polling, but not result materialization or fetching. WithTimeout remains the independent server-side Thrift option.

// Execute query. Query will be cancelled after 30 seconds if still running
res, err := db.ExecContext(ctx, "CREATE TABLE example(id int, message string)")

CorrelationId and ConnId

Use the driverctx package under driverctx/ctx.go to add CorrelationId and ConnId to the context. CorrelationId and ConnId makes it convenient to parse and create metrics in logging.

**Connection Id** Internal id to track what happens under a connection. Connections can be reused so this would track across queries.

**Query Id** Internal id to track what happens under a query. Useful because the same query can be used with multiple connections.

**Correlation Id** External id, such as request ID, to track what happens under a request. Useful to track multiple connections in the same request.

ctx := dbsqlctx.NewContextWithCorrelationId(context.Background(), "workflow-example")

Logging

Use the logger package under logger.go to set up logging (from zerolog). By default, logging level is `warn`. If you want to disable logging, use `disabled`. The user can also utilize Track() and Duration() to custom log the elapsed time of anything tracked.

import (
	dbsqllog "github.com/databricks/databricks-sql-go/v2/logger"
	dbsqlctx "github.com/databricks/databricks-sql-go/v2/driverctx"
)

func main() {
	// Optional. Set the logging level with SetLogLevel()
	if err := dbsqllog.SetLogLevel("debug"); err != nil {
		log.Fatal(err)
	}

	// Optional. Set logging output with SetLogOutput()
	// Default is os.Stderr. If running in terminal, logger will use ConsoleWriter to prettify logs
	dbsqllog.SetLogOutput(os.Stdout)

	// Optional. Set correlation id with NewContextWithCorrelationId
	ctx := dbsqlctx.NewContextWithCorrelationId(context.Background(), "workflow-example")

	// Optional. Track time spent and log elapsed time
	msg, start := logger.Track("Run Main")
	defer log.Duration(msg, start)

	db, err := sql.Open("databricks", "<dsn_string>")
	...
}

The result log may look like this:

{"level":"debug","connId":"01ed6545-5669-1ec7-8c7e-6d8a1ea0ab16","corrId":"workflow-example","queryId":"01ed6545-57cc-188a-bfc5-d9c0eaf8e189","time":1668558402,"message":"Run Main elapsed time: 1.298712292s"}

SEA-via-kernel backend (experimental)

By default the driver uses the Thrift/HiveServer2 backend and is pure Go (CGO_ENABLED=0, go-gettable, cross-compilable). An experimental second backend runs statements over the Statement Execution API via the Rust databricks-sql-kernel, reached through a cgo C ABI. It is opt-in and compiled in only under a build tag, so the default build is unchanged.

To use it, build with the databricks_kernel tag and CGO enabled, and select it per connection with WithUseKernel. The tagged build links the kernel static library, which is not committed — run `make kernel-lib` first to produce it (and the C header) under the cgo link path; `make build-kernel` does both steps:

make kernel-lib      # builds the kernel .a + header at the pinned KERNEL_REV
CGO_ENABLED=1 go build -tags databricks_kernel ./...

connector, _ := dbsql.NewConnector(
	dbsql.WithServerHostname(host),
	dbsql.WithHTTPPath(httpPath),
	dbsql.WithAccessToken(token),
	dbsql.WithUseKernel(true),
)
db := sql.OpenDB(connector)

In a build without the tag, WithUseKernel(true) returns a clear error at connect time rather than silently using Thrift.

Kernel-backend logging uses the same knob as the rest of the driver: the binding-layer trace is emitted through the shared logger at Debug level, so DATABRICKS_LOG_LEVEL=debug or dbsql.SetLogLevel("debug") turns it on and it lands in the driver's normal sink (including a custom logger.SetLogOutput). Where a context is in scope, lines carry the usual connId/corrId/queryId fields. At the default Warn level the lines are suppressed with no cost.

dbsql.SetLogLevel("debug") // or DATABRICKS_LOG_LEVEL=debug

The same level is mapped into the kernel's internal (Rust) log subscriber. Its records are forwarded into the driver's logger, so they use the same output as the Go and Thrift paths, including a local file configured with logger.SetLogOutput. Changing SetLogOutput later safely retargets all three paths. The Rust verbosity is fixed when the first kernel session whose resolved level is not OFF is opened, so set the level before that first non-OFF connect.

For finer control of the Rust verbosity independent of the driver level, set DBSQL_KERNEL_DEBUG to any non-empty value: the callback then defers filtering to RUST_LOG. Filter on the target databricks::sql::kernel (note the colons):

# kernel logs only, at the kernel's own verbosity:
DBSQL_KERNEL_DEBUG=1 RUST_LOG=databricks::sql::kernel=debug ./your_app
# kernel logs plus its HTTP stack:
DBSQL_KERNEL_DEBUG=1 RUST_LOG=debug ./your_app

Supported on the kernel backend: PAT and OAuth (M2M via WithClientCredentials, U2M via the authType=oauthU2M DSN param); reading scalar, nested, and complex-typed results (CloudFetch is transparent); bound query parameters (positional and named); context cancellation during execute; the initial namespace (WithInitialNamespace, applied post-connect via USE CATALOG / USE SCHEMA); metric-view metadata (WithEnableMetricViewMetadata); the retry / backoff policy (WithRetries: RetryWaitMin / RetryWaitMax / RetryMax, including the disable form, forwarded to the kernel's HTTP retry config); and the TLS, proxy, and session-conf (query tags, statement timeout, time zone) options. Federated token providers use one token snapshot during setup. Nothing is silently ignored: WithTimeout and token-provider / external / static authenticators are rejected at connect; staging (PUT/GET/REMOVE on a Unity Catalog volume) is rejected at execute. WithMaxRows is accepted but inert (the kernel manages fetching below the C ABI).

Kernel HTTP requests inherit the driver's ClientTimeout (900s by default). If that value is zero, the kernel uses its own 120s default; zero is neither unlimited nor an immediate timeout.

OAuth U2M is interactive: on a cache miss, connecting launches the system browser and blocks until login completes or the kernel's ~120s callback timeout expires. Because the C ABI can't interrupt session open mid-call, a connection-context deadline is not honored during that window. Use PAT or OAuth M2M for headless / deadline-bound connects. The kernel runs a single, cloud-agnostic in-house U2M flow (OIDC discovery against {host}/oidc, no Azure branching), so on every cloud the kernel path uses the built-in databricks-sql-connector client and requests offline_access + sql. It does NOT forward the cloud-inferred client id / scopes the Thrift path computes: on AWS/GCP those already match, but on Azure the Thrift path uses the Entra-direct app id and <tenant>/user_impersonation scope, which would break the kernel's workspace-federated flow. So the two backends authorize identically on AWS/GCP and deliberately diverge on Azure. Neither backend exposes a U2M-scopes option.

Experimental kernel-only options (rejected by the default backend; the WithKernel* prefix marks them experimental):

  • WithKernelTrustedCerts(pem) adds a PEM CA bundle on top of the system roots (for a re-signing proxy or on-prem CA). Required because the kernel's TLS stack does not read SSL_CERT_FILE.
  • WithKernelClientCertificate(certPEM, keyPEM) configures a paired mTLS client identity. Both PEM buffers must be non-empty; the certificate may include intermediates and an unencrypted PKCS#8 private key is recommended.
  • WithKernelSkipHostnameVerify() skips only the hostname check while keeping chain validation (finer-grained than WithSkipTLSHostVerify).
  • WithKernelProxy(KernelProxy{URL, Username, Password, BypassHosts}) sets an explicit HTTP proxy, overriding the HTTP(S)_PROXY / NO_PROXY environment the kernel path otherwise mirrors. The fields are named (not positional) so the four same-typed strings can't be transposed at the call site. Use it for the advanced fields the env-var path can't express: a structured bypass (no-proxy) list, or basic-auth credentials supplied out of band rather than embedded in the URL. An explicit proxy takes precedence over the environment; empty credentials / bypass are passed to the kernel as unset, and a malformed URL is rejected at connect.
  • WithKernelRetryOverallTimeout(d) sets the cumulative retry budget across all attempts — the 4th retry knob, alongside the backoff bounds and max attempts carried by the backend-neutral WithRetries (also honored on the kernel path). It is kernel-only because the Thrift WithRetries surface has no overall-budget equivalent; it mirrors the pyo3/napi retry_overall_timeout knob. Zero keeps the kernel's default budget (900s).
  • WithKernelMaxConnections(n) sets the maximum number of idle HTTP connections retained per host. The default is 100; n must be positive.
  • WithKernelMaxChunksInMemory(n) bounds downloading and queued CloudFetch chunks ahead of consumption, excluding consumer buffers. It is not a byte limit. It is forwarded as the kernel's client-only cloudfetch_max_chunks_in_memory session conf, stripped before the SEA wire so it never reaches the server. A value <= 0 keeps an explicit cloudfetch_max_chunks_in_memory session parameter, maxDownloadThreads or the kernel default of 16 when unset.

Setting any of these without WithUseKernel fails Connect with an error wrapping the sentinel ErrRequiresKernelBackend, detectable with errors.Is.

Features above the backend seam are inherited unchanged: the database/sql connection pool and connection lifecycle. The Go wrapper telemetry interceptor is skipped on the kernel path so it does not duplicate kernel-owned telemetry for the same connection and statements; `enableTelemetry`, `telemetry_batch_size`, and `telemetry_flush_interval` are forwarded to kernel-owned telemetry config. Result types render byte-for-byte identical to the Thrift backend: scalars, DECIMAL (exact string), TIMESTAMP (rendered in the session time zone) and TIMESTAMP_NTZ (wall-clock fields preserved in a time.Time with a UTC location), INTERVAL, nested Array/Map/Struct and VARIANT (as JSON), and GEOMETRY / GEOGRAPHY (WKT). The server query id is surfaced on the success path, so a QueryIdCallback (see below) fires with the real id and EXECUTE_STATEMENT telemetry carries it.

On Thrift, TIMESTAMP_NTZ handling requires native timestamps in the server-supplied Arrow schema. Without that schema, NTZ still reports TIMESTAMP and uses session-location handling. String timestamps (internal UseArrowNativeTimestamp=false) and non-Arrow values also retain legacy session-location parsing.

Top-level VARIANT columns report VARIANT as the database type name on both backends. Values stay JSON text with the STRING scan type and length. On Thrift, detection reads the server-supplied Arrow schema; without it, VARIANT reports STRING.

Top-level GEOMETRY / GEOGRAPHY columns report the server SQL name including its declared SRID, such as GEOMETRY(0), GEOGRAPHY(4326) or GEOMETRY(ANY), in both modes. The default keeps WKT / EWKT strings and a string scan type; the kernel's WithEnableGeoSpatialSupport(true) keeps EWKB values and a sql.RawBytes scan type. Previously that opt-in reported bare GEOMETRY / GEOGRAPHY names; match the family before "(" when selecting a decoder. Thrift retains STRING without a readable Arrow schema. Raw Arrow schemas are unchanged.

On the read path, context cancellation is honored at result-batch boundaries, not mid-fetch: an in-flight CloudFetch batch runs to completion before the cancel takes effect.

OAuth token caching and HTTP client reuse are inherited from the kernel and need no driver configuration: the kernel caches U2M tokens on disk (~/.config/databricks-sql-kernel/oauth/, with refresh-token lifecycle) and M2M tokens in-memory with background refresh, and reuses a single pooled HTTP client per session across the control-plane, CloudFetch, and auth-refresh calls. There is no driver-side cache or pool knob because these live below the C ABI.

Programmatically Retrieving Connection and Query Id

Use the driverctx package under driverctx/ctx.go to add callbacks to the query context to receive the connection id and query id.

import (
	"github.com/databricks/databricks-sql-go/v2/driverctx"
)

func main() {

	...

	qidCallback := func(id string) {
		fmt.Println("query id: " + id)
	}

	connIdCallback := func(id string) {
		fmt.Println("connection id: " + id)
	}

	ctx := context.Background()
	ctx = driverctx.NewContextWithQueryIdCallback(ctx, qidCallback)
	ctx = driverctx.NewContextWithConnIdCallback(ctx, connIdCallback)

	rows, err1 := db.QueryContext(ctx, `select * from sometable`)

	...

}

Query parameters

Passing parameters to a query is supported when run against servers with version DBR 14.1.

// Named parameters:
p := dbsql.Parameter{Name: "p_bool", Value: true},
rows, err := db.QueryContext(ctx, `select * from sometable where condition=:p_bool`,dbsql.Parameter{Name: "p_bool", Value: true})

// Positional parameters - both `dbsql.Parameter` and plain values can be used:
rows, err := db.Query(`select *, ? from sometable where field=?`,dbsql.Parameter{Value: "123.456"}, "another parameter")

For complex types, you can specify the SQL type using the dbsql.Parameter type field. If this field is set, the value field MUST be set to a string.

Please note that named and positional parameters cannot be used together in the single query.

Staging Ingestion

The Go driver now supports staging operations. In order to use a staging operation, you first must update the context with a list of folders that you are allowing the driver to access.

ctx := driverctx.NewContextWithStagingInfo(context.Background(), []string{"staging/"})

After doing so, you can execute staging operations using this context using the exec context.

_, err1 := db.ExecContext(ctx, `PUT 'staging/file.csv' INTO '/Volumes/main/staging_test/e2etests/file.csv' OVERWRITE`)

Errors

There are three error types exposed via dbsql/errors

DBDriverError - An error in the go driver. Example: unimplemented functionality, invalid driver state, errors processing a server response, etc.

DBRequestError - An error that is caused by an invalid request. Example: permission denied, invalid http path or other connection parameter, resource not available, etc.

DBExecutionError - Any error that occurs after the SQL statement has been accepted such as a SQL syntax error, missing table, etc.

Each type has a corresponding sentinel value which can be used with errors.Is() to determine if one of the types is present in an error chain.

DriverError
RequestError
ExecutionError

The kernel backend (WithUseKernel, see above) additionally wraps every rejection of an option or feature it cannot yet honor with the sentinel ErrNotSupportedByKernel. A caller can detect this case with errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) — for example to fall back to the default (Thrift) backend — rather than matching on the error message text:

if errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) {
	// this option/statement isn't supported on the kernel backend yet;
	// retry with the default backend (omit WithUseKernel).
}

Conversely, a kernel-only option set without WithUseKernel is rejected on the default (Thrift) path with an error wrapping the mirror sentinel ErrRequiresKernelBackend, detectable the same way with errors.Is(err, dbsqlerr.ErrRequiresKernelBackend).

Example usage:

import (
	fmt
	errors
	dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors"
)

func main() {
	...
	_, err := db.ExecContext(ogCtx, `Select id from range(100)`)
	if err != nil {
		if errors.Is(err, dbsqlerr.ExecutionError) {
			var execErr dbsqlerr.DBExecutionError
			if ok := errors.As(err, &execError); ok {
					fmt.Printf("%s, corrId: %s, connId: %s, queryId: %s, sqlState: %s, isRetryable: %t, retryAfter: %f seconds",
					execErr.Error(),
					execErr.CorrelationId(),
					execErr.ConnectionId(),
					execErr.QueryId(),
					execErr.SqlState(),
				    execErr.IsRetryable(),
					execErr.RetryAfter().Seconds(),
				)
			}
		}
		...
	}
	...
}

See the documentation for dbsql/errors for more information.

Retrieving Arrow Batches

The driver supports the ability to retrieve Apache Arrow record batches. To work with record batches it is necessary to use sql.Conn.Raw() to access the underlying driver connection to retrieve a driver.Rows instance. The driver exposes two public interfaces for working with record batches from the rows sub-package:

type Rows interface {
	GetArrowBatches(context.Context) (ArrowBatchIterator, error)
}

type ArrowBatchIterator interface {
	// Retrieve the next arrow.RecordBatch.
	// Will return io.EOF if there are no more records
	Next() (arrow.RecordBatch, error)

	// Return true if the iterator contains more batches, false otherwise.
	HasNext() bool

	// Release any resources in use by the iterator.
	Close()
}

The driver.Rows instance retrieved using Conn.Raw() can be converted to a Databricks Rows instance via a type assertion, then use GetArrowBatches() to retrieve a batch iterator. If the ArrowBatchIterator is not closed it will leak resources, such as the underlying connection. Calling code must call Release() on records returned by DBSQLArrowBatchIterator.Next().

Example usage:

import (
	...
	dbsqlrows "github.com/databricks/databricks-sql-go/v2/rows"
)

func main() {
	...
	db := sql.OpenDB(connector)
	defer db.Close()

	conn, _ := db.Conn(context.BackGround())
	defer conn.Close()

	query := `select * from main.default.taxi_trip_data`

	var rows driver.Rows
	var err error
	err = conn.Raw(func(d interface{}) error {
		rows, err = d.(driver.QueryerContext).QueryContext(ctx, query, nil)
		return err
	})

	if err != nil {
		log.Fatalf("unable to run the query. err: %v", err)
	}
	defer rows.Close()

	batches, err := rows.(dbsqlrows.Rows).GetArrowBatches(context.BackGround())
	if err != nil {
		log.Fatalf("unable to get arrow batches. err: %v", err)
	}

	var iBatch, nRows int
	for batches.HasNext() {
		b, err := batches.Next()
		if err != nil {
			log.Fatalf("Failure retrieving batch. err: %v", err)
		}

		log.Printf("batch %v: nRecords=%v\n", iBatch, b.NumRows())
		iBatch += 1
		nRows += int(b.NumRows())
		b.Release()
	}
	log.Printf("NRows: %v\n", nRows)
}

Supported Data Types

==================================

Databricks Type --> Golang Type

==================================

BOOLEAN --> bool

TINYINT --> int8

SMALLINT --> int16

INT --> int32

BIGINT --> int64

FLOAT --> float32

DOUBLE --> float64

VOID --> nil

STRING --> string

DATE --> time.Time

TIME --> time.Time (0001-01-01 UTC). Detect NULL with sql.NullTime.Valid or a nil *time.Time, never IsZero(): non-NULL midnight is the zero time and JSON omitzero omits it. To bind TIME, pass value.Format("15:04:05.999999") to CAST(? AS TIME), not the time.Time: time.Time parameters bind as TIMESTAMP and can shift in non-UTC sessions.

TIMESTAMP --> time.Time

DECIMAL(p,s) --> sql.RawBytes

BINARY --> sql.RawBytes

ARRAY<elementType> --> sql.RawBytes

STRUCT --> sql.RawBytes

MAP<keyType, valueType> --> sql.RawBytes

INTERVAL (year-month) --> string

INTERVAL (day-time) --> string

For ARRAY, STRUCT, and MAP types, sql.Scan can cast sql.RawBytes to JSON string, which can be unmarshalled to Golang arrays, maps, and structs. Nested non-finite FLOAT and DOUBLE values are represented as the JSON strings "NaN", "Infinity", and "-Infinity", distinct from SQL NULL (null). Finite values remain JSON numbers. Use any or a custom decoder for fields that can contain special values; encoding/json cannot unmarshal these strings into plain float fields. Top-level FLOAT and DOUBLE values remain numeric. Non-finite floating-point MAP keys use the same "NaN", "Infinity", and "-Infinity" spellings. For example:

type structVal struct {
		StringField string `json:"string_field"`
		ArrayField  []int  `json:"array_field"`
}
type row struct {
	arrayVal  []int
	mapVal    map[string]int
	structVal structVal
}
res := []row{}

for rows.Next() {
	r := row{}
	tempArray := []byte{}
	tempStruct := []byte{}
	tempMap := []byte{}
	if err := rows.Scan(&tempArray, &tempMap, &tempStruct); err != nil {
		log.Fatal(err)
	}
	if err := json.Unmarshal(tempArray, &r.arrayVal); err != nil {
		log.Fatal(err)
	}
	if err := json.Unmarshal(tempMap, &r.mapVal); err != nil {
		log.Fatal(err)
	}
	if err := json.Unmarshal(tempStruct, &r.structVal); err != nil {
		log.Fatal(err)
	}
	res = append(res, r)
}

May generate the following row:

{arrayVal:[1,2,3] mapVal:{"key1":1} structVal:{"string_field":"string_val","array_field":[4,5,6]}}

Index

Constants

This section is empty.

Variables

View Source
var DriverVersion = "2.0.0" // update version before each release

Functions

func NewConnector

func NewConnector(options ...ConnOption) (driver.Connector, error)

NewConnector creates a connection that can be used with `sql.OpenDB()`. This is an easier way to set up the DB instead of having to construct a DSN string.

func SerializeQueryTags

func SerializeQueryTags(tags map[string]string) string

SerializeQueryTags converts a map of query tags to the wire format string. The format is comma-separated key:value pairs (e.g., "team:engineering,app:etl").

Escaping rules (consistent with Python and NodeJS connectors):

  • Keys: only backslashes are escaped
  • Values: backslashes, colons, and commas are escaped with a leading backslash
  • Empty string values result in just the key being emitted (no colon)

Returns empty string if the map is nil or empty.

The implementation lives in internal/querytags so the execution backends can share it without importing this package; this remains the public entry point.

func Succeeded

func Succeeded(response *http.Response) bool

Types

type ConnOption

type ConnOption func(*config.Config)

func WithAccessToken

func WithAccessToken(token string) ConnOption

WithAccessToken sets up the Personal Access Token. Mandatory for now.

func WithArrowNativeDecimal

func WithArrowNativeDecimal(useNativeDecimal bool) ConnOption

WithArrowNativeDecimal controls whether DECIMAL columns are returned as native Arrow decimal128 values. Default is false, in which case the server returns DECIMAL columns as strings.

When enabled, DECIMAL columns retrieved via GetArrowBatches carry the native arrow.Decimal128 type. When scanned through the standard database/sql Rows interface, DECIMAL values are returned as lossless, scale-applied strings to avoid the precision loss that a float64 would introduce.

See https://github.com/databricks/databricks-sql-go/issues/274.

func WithAuthenticator

func WithAuthenticator(authr auth.Authenticator) ConnOption

WithAuthenticator sets up the Authentication. Mandatory if access token is not provided.

func WithClientCredentials

func WithClientCredentials(clientID, clientSecret string) ConnOption

Setup of Oauth M2m authentication

func WithClientQueryTimeout

func WithClientQueryTimeout(timeout time.Duration) ConnOption

WithClientQueryTimeout sets a client-side deadline for kernel statement execution. It is independent of WithTimeout, which remains a server-side Thrift option. A positive duration is rounded up to the next millisecond; zero and the maximum time.Duration select unlimited execution. Omitting this option preserves the kernel's legacy 600-second polling ceiling.

This connector-only option requires WithUseKernel(true). Negative or out-of-range durations are rejected by NewConnector.

func WithCloudFetch

func WithCloudFetch(useCloudFetch bool) ConnOption

WithCloudFetch sets up the use of cloud fetch for query execution. Default is true.

func WithEnableGeoSpatialSupport

func WithEnableGeoSpatialSupport(enabled bool) ConnOption

WithEnableGeoSpatialSupport selects how the kernel path exposes top-level GEOMETRY and GEOGRAPHY result values. True returns EWKB bytes ([]byte), including the per-row SRID, with a sql.RawBytes scan type. False (the default) returns WKT / EWKT strings with a string scan type. Both modes report the server SQL name with its declared SRID, such as GEOMETRY(0), GEOGRAPHY(4326) or GEOMETRY(ANY). Enabled mode previously reported bare GEOMETRY / GEOGRAPHY names; match the family before "(" when selecting a decoder. The per-row SRID remains in the Arrow struct returned by the driver's GetArrowBatches API in enabled mode; that raw Arrow value retains Databricks' separate SRID and OGC WKB children.

The conversion is entirely client-side and is never forwarded to SEA. Nested geospatial values follow the driver's existing complex-value contract: disabled mode renders WKT / EWKT leaves in JSON, while enabled mode preserves the {"srid":...,"wkb":...} shape (with JSON base64 for WKB).

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this option at connect time.

func WithEnableMetricViewMetadata

func WithEnableMetricViewMetadata(enable bool) ConnOption

WithEnableMetricViewMetadata enables metric view metadata support. Default is false. When enabled, adds spark.sql.thriftserver.metadata.metricview.enabled=true to session configuration.

func WithExternalToken

func WithExternalToken(tokenFunc func() (string, error)) ConnOption

WithExternalToken sets up authentication using an external token function (passthrough)

func WithFederatedTokenProvider

func WithFederatedTokenProvider(baseProvider tokenprovider.TokenProvider) ConnOption

WithFederatedTokenProvider sets up authentication using token federation It wraps the base provider and automatically handles token exchange if needed

func WithFederatedTokenProviderAndClientID

func WithFederatedTokenProviderAndClientID(baseProvider tokenprovider.TokenProvider, clientID string) ConnOption

WithFederatedTokenProviderAndClientID sets up SP-wide token federation

func WithHTTPPath

func WithHTTPPath(path string) ConnOption

WithHTTPPath sets up the endpoint to the warehouse. Mandatory.

func WithInitialNamespace

func WithInitialNamespace(catalog, schema string) ConnOption

Sets the initial catalog name and schema name in the session. Use <select * from foo> instead of <select * from catalog.schema.foo>

func WithKernelClientCertificate

func WithKernelClientCertificate(certPEM, keyPEM []byte) ConnOption

WithKernelClientCertificate configures the PEM-encoded client certificate and matching private key used when a server requires mutual TLS (mTLS). certPEM contains the leaf certificate followed by any intermediate certificates; keyPEM contains the matching unencrypted private key. PKCS#8 is recommended for portability across the kernel's TLS backends.

Both values are required and must be non-empty. The driver copies them defensively and validates the pair at connect time. Server trust remains independent and strict by default; use WithKernelTrustedCerts when the server certificate chains to a private CA.

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect.

func WithKernelDecimalAsFloat

func WithKernelDecimalAsFloat(asFloat bool) ConnOption

WithKernelDecimalAsFloat makes the kernel path scan top-level DECIMAL columns to a lossy float64 instead of the exact fixed-point string. The kernel still receives native Arrow Decimal128; this only changes how the Go scanner materializes each cell, skipping per-cell string formatting for a cheap scalar. Precision beyond ~15-17 digits is lost, so it is opt-in and off by default; it mirrors the Thrift driver's pre-UseArrowNativeDecimal behavior.

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect (use WithArrowNativeDecimal there instead).

func WithKernelMaxChunksInMemory

func WithKernelMaxChunksInMemory(n int) ConnOption

WithKernelMaxChunksInMemory bounds downloading and queued CloudFetch chunks ahead of consumption on the kernel backend. Consumer and application buffers are additional; this is not a byte limit. A value <= 0 (the default) leaves WithMaxDownloadThreads, an explicit cloudfetch_max_chunks_in_memory session parameter or the kernel default in effect.

It is forwarded as the kernel's client-only "cloudfetch_max_chunks_in_memory" session conf, which the kernel applies to its result config and strips before the SEA wire — so it never reaches the server.

EXPERIMENTAL, kernel-only: the default (Thrift) backend has no in-memory-chunk knob and rejects this at connect.

func WithKernelMaxConnections

func WithKernelMaxConnections(n int) ConnOption

WithKernelMaxConnections sets the maximum number of idle HTTP connections retained per host by the kernel. The default is 100.

EXPERIMENTAL, kernel-only: n must be positive, and the default (Thrift) backend rejects this option at connect.

func WithKernelProxy

func WithKernelProxy(p KernelProxy) ConnOption

WithKernelProxy configures an explicit HTTP proxy for the kernel backend, with optional out-of-band basic-auth credentials and a comma-separated bypass (no-proxy) host list. It overrides the HTTP(S)_PROXY / NO_PROXY environment the kernel path otherwise mirrors from the Thrift path.

Use this instead of the proxy environment when you need the "advanced" fields the env-var path can't express: a structured bypass list (NO_PROXY is consumed during environment resolution, not forwarded to the kernel) or basic-auth credentials supplied out of band rather than embedded in the URL userinfo. KernelProxy.Username / Password / BypassHosts may be empty (passed to the kernel as NULL, i.e. unset). An empty KernelProxy.URL is a no-op — the environment-derived proxy, if any, stays in effect. A malformed URL is rejected at connect (errors.Is ErrInvalidKernelConfig).

An explicit WithKernelProxy takes precedence over the environment: consulting both would be ambiguous, and an explicit proxy is a deliberate override.

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect.

func WithKernelRetryOverallTimeout

func WithKernelRetryOverallTimeout(d time.Duration) ConnOption

WithKernelRetryOverallTimeout sets the cumulative retry budget across all attempts on the kernel backend — the total time the kernel may spend retrying a single logical request before giving up. This is the 4th retry knob, alongside the backoff bounds and max attempts carried by the backend-neutral WithRetries (RetryWaitMin / RetryWaitMax / RetryMax, which the kernel path also honors).

It is a kernel-only option because the Thrift-path WithRetries surface has no overall-budget equivalent; it mirrors the pyo3/napi retry_overall_timeout knob. Zero (the default) keeps the kernel's built-in budget (900s).

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect.

func WithKernelSkipHostnameVerify

func WithKernelSkipHostnameVerify() ConnOption

WithKernelSkipHostnameVerify skips only the certificate hostname-vs-SNI check on the kernel backend, while keeping chain validation. This is finer-grained than WithSkipTLSHostVerify, which relaxes both chain and hostname checks. WARNING: Skipping hostname verification still weakens TLS: a certificate issued by a trusted CA for a different host will be accepted, opening a machine-in-the-middle vector. Only use this when the hostname is an internal private-link hostname that legitimately differs from the certificate's subject.

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect.

func WithKernelTrustedCerts

func WithKernelTrustedCerts(pem []byte) ConnOption

WithKernelTrustedCerts adds a PEM CA-certificate bundle to the kernel's TLS trust store on top of the system roots — for a corporate re-signing proxy or an on-prem CA. Required (rather than relying on SSL_CERT_FILE) because the kernel's rustls stack does not read that environment variable.

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect.

func WithMaxDownloadThreads

func WithMaxDownloadThreads(numThreads int) ConnOption

WithMaxDownloadThreads sets up maximum download threads for cloud fetch. When unset, Thrift defaults to 10 and the kernel defaults to 16. An explicit value <= 0 logs a warning and uses 10. On the kernel backend it bounds downloading and queued chunks ahead of consumption, excluding consumer buffers; it is not a byte limit. Values above 256 are clamped. Configuration is fixed when connecting. An explicit chunk session parameter or positive WithKernelMaxChunksInMemory takes precedence.

func WithMaxRows

func WithMaxRows(n int) ConnOption

WithMaxRows sets up the max rows fetched per request. Default is 100000

func WithPort

func WithPort(port int) ConnOption

WithPort sets up the server port. Mandatory.

func WithQueryTags

func WithQueryTags(tags map[string]string) ConnOption

WithQueryTags sets session-level query tags from a map. Tags are serialized and passed as QUERY_TAGS in the session configuration. All queries in the session will carry these tags unless overridden at the statement level. This is the preferred way to set session-level query tags, as it handles serialization and escaping automatically (consistent with the statement-level API).

func WithRetries

func WithRetries(retryMax int, retryWaitMin time.Duration, retryWaitMax time.Duration) ConnOption

WithRetries sets up retrying logic. Sane defaults are provided. Negative retryMax will disable retry behavior By default retryWaitMin = 1 * time.Second By default retryWaitMax = 30 * time.Second By default retryMax = 4

func WithServerHostname

func WithServerHostname(host string) ConnOption

WithServerHostname sets up the server hostname. Mandatory.

func WithSessionParams

func WithSessionParams(params map[string]string) ConnOption

Session parameters are passed directly in TOpenSessionReq.Configuration during session creation.

func WithSkipTLSHostVerify

func WithSkipTLSHostVerify() ConnOption

WithSkipTLSHostVerify disables the verification of the hostname in the TLS certificate. WARNING: When this option is used, TLS is susceptible to machine-in-the-middle attacks. Please only use this option when the hostname is an internal private link hostname

func WithStaticToken

func WithStaticToken(token string) ConnOption

WithStaticToken sets up authentication using a static token

func WithTimeout

func WithTimeout(n time.Duration) ConnOption

WithTimeout adds timeout for the server query execution. Default is no timeout.

func WithTokenCache

func WithTokenCache(enabled bool) ConnOption

WithTokenCache controls the kernel's on-disk OAuth U2M token-cache persistence. When enabled is true, the refresh token is persisted encrypted to ~/.config/databricks-sql-kernel/oauth/ so the user is not sent through the browser on every connection. When false (the default), tokens are held in memory only. U2M-only: PAT and M2M ignore this setting.

EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect. Via this option, either value (WithTokenCache(true) or WithTokenCache(false)) opts the connection into the kernel backend — the setter allocates KernelExperimental unconditionally — so it must be paired with WithUseKernel(true)/useKernel=true or the connection is rejected at connect with ErrRequiresKernelBackend; this is not a silent no-op. Only tokenCache=false carried in a DSN is a no-op: that carrier is not forwarded into KernelExperimental (in-memory is already the default), so it does not opt into the kernel backend. (tokenCache=true in a DSN opts in, same as the option.) Mirrors the EnableTokenCache option exposed by the ODBC driver, but does not expose a passphrase option — pass NULL (empty) to the kernel (derived key).

func WithTokenProvider

func WithTokenProvider(provider tokenprovider.TokenProvider) ConnOption

WithTokenProvider sets up authentication using a custom token provider

func WithTransport

func WithTransport(t http.RoundTripper) ConnOption

WithTransport sets up the transport configuration to be used by the httpclient.

func WithUseKernel

func WithUseKernel(useKernel bool) ConnOption

WithUseKernel selects the SEA-via-kernel backend instead of the default Thrift backend. It has effect only in a build compiled with `-tags databricks_kernel` and CGO_ENABLED=1; in the default pure-Go build a connection made with this option set returns a clear error at connect time (the kernel backend is not linked in).

func WithUserAgentEntry

func WithUserAgentEntry(entry string) ConnOption

Used to identify partners. Set as a string with format <isv-name+product-name>.

func WithWarehouseID

func WithWarehouseID(id string) ConnOption

WithWarehouseID sets the bare SQL warehouse id. It has no effect unless WithUseKernel(true) is also set: the kernel backend addresses a warehouse by id (preferred over the http path when set), while the default Thrift backend ignores it entirely and continues to route by http path.

type KernelProxy

type KernelProxy struct {
	// URL is the proxy URL (e.g. "http://proxy.internal:3128"). Required; empty is a
	// no-op, leaving the environment-derived proxy (if any) in effect.
	URL string
	// Username / Password are optional out-of-band basic-auth credentials, supplied
	// here rather than embedded in the URL userinfo. Empty means unset.
	Username string
	Password string
	// BypassHosts is an optional comma-separated no-proxy host list. NO_PROXY is
	// consumed during environment resolution and not forwarded to the kernel, so this
	// is the only way to give the kernel a structured bypass list. Empty means unset.
	BypassHosts string
}

KernelProxy is the explicit-proxy configuration for WithKernelProxy. Its fields are named so a call site can't transpose the credentials — the four values are all strings, so a positional signature would let a Username/Password swap (or a misplaced BypassHosts) compile cleanly and fail only at runtime with wrong proxy credentials.

type Parameter

type Parameter struct {
	Name  string
	Type  SqlType
	Value any
}

type SqlType

type SqlType int
const (
	SqlUnkown SqlType = iota
	SqlString
	SqlDate
	SqlTimestamp
	SqlFloat
	SqlDecimal
	SqlDouble
	SqlInteger
	SqlBigInt
	SqlSmallInt
	SqlTinyInt
	SqlBoolean
	SqlIntervalMonth
	SqlIntervalDay
	SqlVoid
)

func (SqlType) String

func (s SqlType) String() string

Directories

Path Synopsis
pat
examples
arrrowbatches command
browser_oauth_federation command
Example: Browser OAuth (U2M) Authentication
Example: Browser OAuth (U2M) Authentication
catalog command
cloudfetch command
createdrop command
error command
ipcstreams command
kernel command
Command kernel demonstrates the experimental SEA-via-kernel backend.
Command kernel demonstrates the experimental SEA-via-kernel backend.
oauth command
parameters command
query_tags command
queryrow command
queryrows command
staging command
timeout command
timezone command
token_federation command
Example: Token Provider Authentication
Example: Token Provider Authentication
workflow command
internal
agent
Package agent detects whether the Go SQL driver is being invoked by an AI coding agent by checking for well-known environment variables that agents set in their spawned shell processes.
Package agent detects whether the Go SQL driver is being invoked by an AI coding agent by checking for well-known environment variables that agents set in their spawned shell processes.
arrowscan
Package arrowscan converts Arrow array cells to database/sql driver.Values, with nested types (List/Map/Struct) rendered to a JSON string byte-identical to the Thrift arrow path (internal/rows/arrowbased).
Package arrowscan converts Arrow array cells to database/sql driver.Values, with nested types (List/Map/Struct) rendered to a JSON string byte-identical to the Thrift arrow path (internal/rows/arrowbased).
backend
Package backend defines the execution-backend abstraction for the databricks-sql-go driver.
Package backend defines the execution-backend abstraction for the databricks-sql-go driver.
backend/thrift
Package thrift is the Thrift/HiveServer2 implementation of backend.Backend.
Package thrift is the Thrift/HiveServer2 implementation of backend.Backend.
debuglog
Package debuglog is the step-level debug tracer for the databricks-sql-go SEA/kernel integration.
Package debuglog is the step-level debug tracer for the databricks-sql-go SEA/kernel integration.
decimalfmt
Package decimalfmt renders Arrow decimal128 values as exact fixed-point strings, shared by the Thrift (arrowbased) and kernel result paths so a DECIMAL renders identically regardless of backend.
Package decimalfmt renders Arrow decimal128 values as exact fixed-point strings, shared by the Thrift (arrowbased) and kernel result paths so a DECIMAL renders identically regardless of backend.
featureflags
Package featureflags shares connector-service flags without requiring telemetry or a session.
Package featureflags shares connector-service flags without requiring telemetry or a session.
jsonfmt
Package jsonfmt renders scalar values as JSON for the nested-type renderers shared by the Thrift (arrowbased) and kernel (arrowscan) result paths.
Package jsonfmt renders scalar values as JSON for the nested-type renderers shared by the Thrift (arrowbased) and kernel (arrowscan) result paths.
querytags
Package querytags holds the query-tag wire serialization shared by the public dbsql API and the execution backends.
Package querytags holds the query-tag wire serialization shared by the public dbsql API and the execution backends.
retry
Package retry provides shared HTTP retry/backoff helpers for transient object-storage failures (S3 SlowDown, 5xx, etc.).
Package retry provides shared HTTP retry/backoff helpers for transient object-storage failures (S3 SlowDown, 5xx, etc.).
warehouse_cache
Package warehouse_cache maintains a process-wide cache of warehouses known to reject the legacy Thrift protocol.
Package warehouse_cache maintains a process-wide cache of warehouses known to reject the legacy Thrift protocol.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL