dbsql

package module
v1.15.1 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: Apache-2.0 Imports: 41 Imported by: 37

Image README

Databricks SQL Driver for Go

Image

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"
)

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 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.

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

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    # kernel-tagged unit tests

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"
)

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.
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.

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.

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.
  • Custom OAuth M2M scopes are rejected on the kernel path (the kernel applies its own default scopes). Default scopes work on both.
  • 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 Thrift only (inert on kernel) true Enable Cloud Fetch. On the kernel path Cloud Fetch is always managed internally, so the flag is inert.
maxDownloadThreads WithMaxDownloadThreads Thrift only (inert on kernel) 10 Concurrent download goroutines (Thrift). Inert on the kernel path.
WithKernelMaxChunksInMemory(n) SEA only kernel default (16) Bounds decompressed Cloud Fetch chunks held in memory — trades large-result throughput for peak memory.

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

Results render byte-for-byte identically on both backends. Scalars, DECIMAL (exact string), TIMESTAMP / TIMESTAMP_NTZ (shifted into the session time zone), INTERVAL, nested ARRAY / MAP / STRUCT and VARIANT (as JSON), and GEOMETRY / GEOGRAPHY (as WKT) are all supported. BINARY is returned as sql.RawBytes.

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

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 (links the prebuilt bindings; no Rust)

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

Image 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"
)

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 up the max number of concurrent workers for cloud fetch. Default is 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"
)

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
  • 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 up the max number of concurrent workers for cloud fetch. Default is 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()

// 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/logger"
	dbsqlctx "github.com/databricks/databricks-sql-go/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, token-provider / external / static authenticators, and custom M2M OAuth scopes (the kernel applies its own) 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).
  • WithKernelMaxChunksInMemory(n) bounds how many decompressed CloudFetch chunks the kernel holds in memory at once — the knob that trades large-result download throughput for peak RSS. Lower it (e.g. 4) to cap memory on wide, row-heavy result sets; raise it for more parallelism at higher memory. 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 the kernel's default (16).

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 / TIMESTAMP_NTZ (shifted into the session time zone), 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 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/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/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.Record.
	// Will return io.EOF if there are no more records
	Next() (arrow.Record, 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/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

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. 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 = "1.15.1" // 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 added in v1.11.0

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 added in v1.5.0

func Succeeded(response *http.Response) bool

Types

type ConnOption added in v1.6.0

type ConnOption func(*config.Config)

func WithAccessToken added in v0.2.0

func WithAccessToken(token string) ConnOption

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

func WithArrowNativeDecimal added in v1.13.1

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 added in v1.3.0

func WithAuthenticator(authr auth.Authenticator) ConnOption

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

func WithClientCredentials added in v1.5.0

func WithClientCredentials(clientID, clientSecret string) ConnOption

Setup of Oauth M2m authentication

func WithCloudFetch added in v1.4.0

func WithCloudFetch(useCloudFetch bool) ConnOption

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

func WithEnableMetricViewMetadata added in v1.10.0

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 added in v1.10.0

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

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

func WithFederatedTokenProvider added in v1.10.0

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 added in v1.10.0

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

WithFederatedTokenProviderAndClientID sets up SP-wide token federation

func WithHTTPPath added in v0.2.0

func WithHTTPPath(path string) ConnOption

WithHTTPPath sets up the endpoint to the warehouse. Mandatory.

func WithInitialNamespace added in v0.2.0

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 added in v1.15.0

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 added in v1.15.0

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 added in v1.15.0

func WithKernelMaxChunksInMemory(n int) ConnOption

WithKernelMaxChunksInMemory bounds how many decompressed CloudFetch chunks the kernel holds in memory at once on the kernel backend — the knob that trades large-result throughput for peak RSS. Lower it (e.g. 4) to cap memory on wide, row-heavy result sets; raise it for more download parallelism at higher memory. A value <= 0 (the default) leaves the kernel's built-in default (16) in place.

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 WithKernelProxy added in v1.15.0

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 added in v1.15.0

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 added in v1.15.0

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 added in v1.15.0

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 added in v1.4.0

func WithMaxDownloadThreads(numThreads int) ConnOption

WithMaxDownloadThreads sets up maximum download threads for cloud fetch. Default is 10.

func WithMaxRows added in v0.2.0

func WithMaxRows(n int) ConnOption

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

func WithPort added in v0.2.0

func WithPort(port int) ConnOption

WithPort sets up the server port. Mandatory.

func WithQueryTags added in v1.11.0

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 added in v1.1.0

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 added in v0.2.0

func WithServerHostname(host string) ConnOption

WithServerHostname sets up the server hostname. Mandatory.

func WithSessionParams added in v0.2.0

func WithSessionParams(params map[string]string) ConnOption

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

func WithSkipTLSHostVerify added in v1.5.6

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 added in v1.10.0

func WithStaticToken(token string) ConnOption

WithStaticToken sets up authentication using a static token

func WithTimeout added in v0.2.0

func WithTimeout(n time.Duration) ConnOption

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

func WithTokenCache added in v1.15.0

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 added in v1.10.0

func WithTokenProvider(provider tokenprovider.TokenProvider) ConnOption

WithTokenProvider sets up authentication using a custom token provider

func WithTransport added in v1.4.0

func WithTransport(t http.RoundTripper) ConnOption

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

func WithUseKernel added in v1.15.0

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 added in v0.2.0

func WithUserAgentEntry(entry string) ConnOption

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

func WithWarehouseID added in v1.15.0

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 added in v1.15.0

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 added in v1.5.0

type Parameter struct {
	Name  string
	Type  SqlType
	Value any
}

type SqlType added in v1.5.0

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

func (SqlType) String added in v1.5.0

func (s SqlType) String() string

Image Directories

Path Synopsis
pat
examples module
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, and VARIANT which arrives nested) 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, and VARIANT which arrives nested) 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.
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.).

Jump to

Keyboard shortcuts

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