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 ¶
- Variables
- func NewConnector(options ...ConnOption) (driver.Connector, error)
- func SerializeQueryTags(tags map[string]string) string
- func Succeeded(response *http.Response) bool
- type ConnOption
- func WithAccessToken(token string) ConnOption
- func WithArrowNativeDecimal(useNativeDecimal bool) ConnOption
- func WithAuthenticator(authr auth.Authenticator) ConnOption
- func WithClientCredentials(clientID, clientSecret string) ConnOption
- func WithCloudFetch(useCloudFetch bool) ConnOption
- func WithEnableMetricViewMetadata(enable bool) ConnOption
- func WithExternalToken(tokenFunc func() (string, error)) ConnOption
- func WithFederatedTokenProvider(baseProvider tokenprovider.TokenProvider) ConnOption
- func WithFederatedTokenProviderAndClientID(baseProvider tokenprovider.TokenProvider, clientID string) ConnOption
- func WithHTTPPath(path string) ConnOption
- func WithInitialNamespace(catalog, schema string) ConnOption
- func WithKernelClientCertificate(certPEM, keyPEM []byte) ConnOption
- func WithKernelDecimalAsFloat(asFloat bool) ConnOption
- func WithKernelMaxChunksInMemory(n int) ConnOption
- func WithKernelProxy(p KernelProxy) ConnOption
- func WithKernelRetryOverallTimeout(d time.Duration) ConnOption
- func WithKernelSkipHostnameVerify() ConnOption
- func WithKernelTrustedCerts(pem []byte) ConnOption
- func WithMaxDownloadThreads(numThreads int) ConnOption
- func WithMaxRows(n int) ConnOption
- func WithPort(port int) ConnOption
- func WithQueryTags(tags map[string]string) ConnOption
- func WithRetries(retryMax int, retryWaitMin time.Duration, retryWaitMax time.Duration) ConnOption
- func WithServerHostname(host string) ConnOption
- func WithSessionParams(params map[string]string) ConnOption
- func WithSkipTLSHostVerify() ConnOption
- func WithStaticToken(token string) ConnOption
- func WithTimeout(n time.Duration) ConnOption
- func WithTokenCache(enabled bool) ConnOption
- func WithTokenProvider(provider tokenprovider.TokenProvider) ConnOption
- func WithTransport(t http.RoundTripper) ConnOption
- func WithUseKernel(useKernel bool) ConnOption
- func WithUserAgentEntry(entry string) ConnOption
- func WithWarehouseID(id string) ConnOption
- type KernelProxy
- type Parameter
- type SqlType
Constants ¶
This section is empty.
Variables ¶
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
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.
Types ¶
type ConnOption ¶ added in v1.6.0
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
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
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.). |