Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/nightly-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ jobs:
# in the default pure-Go build (CGO_ENABLED=0). -run targets the high-value
# real-warehouse scenarios: large multi-page CloudFetch drain-past-caller-
# deadline, exact row count, and a non-positive download-thread count
# (issue #439), and DECIMAL metadata (issue #500). -count=1 defeats the test cache so a scheduled
# (issue #439), DECIMAL metadata (issue #500), and the unknown row count for
# view DDL (issue #588). -count=1 defeats the test cache so a scheduled
# run always re-exercises the warehouse. NOT -short, so
# TestE2ECloudFetchExactRowCount (guarded by -short) actually runs.
- name: Run Thrift E2E
Expand All @@ -90,7 +91,7 @@ jobs:
DATABRICKS_PECOTESTING_TOKEN_PERSONAL: ${{ secrets.DATABRICKS_PECOTESTING_TOKEN_PERSONAL }}
run: |
go test -tags e2e -count=1 -v -timeout 15m \
-run 'TestE2EArrowBatchesSurviveQueryContextCancellation|TestE2ECloudFetchExactRowCount|TestE2ECloudFetchNonPositiveMaxDownloadThreads|TestE2EDecimalMetadata|TestE2EVariantTypeName|TestE2EGeospatialTypeNames|^TestE2ETime(Results|ArrowResults)$|TestE2ERejectedRequestClosesResponse' .
-run 'TestE2EArrowBatchesSurviveQueryContextCancellation|TestE2ECloudFetchExactRowCount|TestE2ECloudFetchNonPositiveMaxDownloadThreads|TestE2EDecimalMetadata|TestE2EVariantTypeName|TestE2EGeospatialTypeNames|^TestE2ETime(Results|ArrowResults)$|TestE2ERejectedRequestClosesResponse|TestE2EReportUnknownRowsAffected' .

kernel-e2e:
name: E2E (kernel backend)
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Unreleased (v2.0.0 prototype)

- Fix leaked HTTP connections after failed or retry-exhausted requests, which could exhaust a connector's connection pool. Remove the MPL-2.0 go-retryablehttp and go-cleanhttp dependencies while preserving first-send bodies, streaming trailers and retry behavior (databricks/databricks-sql-go#177).
- Add the opt-in `WithReportUnknownRowsAffected` / `reportUnknownRowsAffected=true` option. When enabled, `Result.RowsAffected()` returns `-1` instead of `0` when the server reports no modified-row count (for example `CREATE VIEW` / `DROP VIEW`), so callers can tell it apart from zero rows modified. Reported counts, including `0`, are unchanged. Works on Thrift and SEA; the default is off and keeps returning `0` (databricks/databricks-sql-go#588).
- Fix OAuth M2M token requests hanging indefinitely when the token endpoint stops responding. Each request now uses a copy of `http.DefaultClient` with a timeout of at most 60s; `WithRetries` repeats failed fetches (databricks/databricks-sql-go#475).
- **Behavior change:** Top-level GEOMETRY and GEOGRAPHY columns report server SQL names including SRIDs on Thrift and SEA. With `WithEnableGeoSpatialSupport(true)` (`enableGeoSpatialSupport=true`, available since v1.17.0), previously bare `GEOMETRY` / `GEOGRAPHY` names now include the declared SRID, such as `GEOMETRY(0)`, `GEOGRAPHY(4326)` or `GEOMETRY(ANY)`; match the family before `(` when selecting a decoder. String mode previously reported `STRING`; values, scan types, lengths and raw Arrow schemas are unchanged, and Thrift retains `STRING` without a readable Arrow schema (databricks/databricks-sql-go#474).
- Render non-finite FLOAT / DOUBLE values inside ARRAY / MAP / STRUCT results as the JSON strings `"NaN"`, `"Infinity"`, and `"-Infinity"` on both backends instead of failing row iteration. SQL NULL remains `null`; top-level floats remain numeric (databricks/databricks-sql-go#573).
Expand Down
1 change: 1 addition & 0 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ Notes for the SEA/kernel backend:
| *(via session param)* | `WithQueryTags` | ✅ | ✅ | | Session-level query tags (serialized into `QUERY_TAGS`). |
| `timezone` | `WithSessionParams(timezone=…)` | ✅ | ✅ | | Session time zone (e.g. `America/Los_Angeles`). |
| `enableMetricViewMetadata` | `WithEnableMetricViewMetadata` | ✅ | ⚠️ | `false` | Enables metric-view metadata (sets `spark.sql.thriftserver.metadata.metricview.enabled=true`). Both paths forward the identical conf. Whether it takes effect on the SEA/kernel path depends on server-side SEA support (PECOBLR-4142). |
| `reportUnknownRowsAffected` | `WithReportUnknownRowsAffected` | ✅ | ✅ | `false` | `true`: `Result.RowsAffected()` returns `-1` when the server reports no modified-row count (e.g. DDL such as `CREATE VIEW`; Thrift: `NumModifiedRows` unset; kernel: the C ABI's unknown sentinel). A reported count, including `0`, is unchanged. `false`: an unreported count is `0`. Client-side only; nothing is sent to the server. |

### Kernel session confs

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ session parameter on both backends.
| *(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`). |
| `reportUnknownRowsAffected` | `WithReportUnknownRowsAffected` | Both | `false` | `true`: `Result.RowsAffected()` returns `-1` when the server reports no modified-row count (e.g. DDL such as `CREATE VIEW`). A reported count, including `0`, is unchanged. `false`: an unreported count is `0`. |

### Retry / backoff

Expand Down
64 changes: 64 additions & 0 deletions connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,70 @@ import (
"github.com/stretchr/testify/assert"
)

// TestConn_ExecContextReportUnknownRowsAffected drives ExecContext end to end
// through the Thrift backend for a statement whose status carries no
// NumModifiedRows (e.g. CREATE VIEW): RowsAffected is 0 by default and -1 under
// WithReportUnknownRowsAffected, while a reported count is unchanged either way.
func TestConn_ExecContextReportUnknownRowsAffected(t *testing.T) {
t.Parallel()

execWithStatus := func(t *testing.T, reportUnknown bool, numModifiedRows *int64) int64 {
testClient := &client.TestClient{
FnExecuteStatement: func(ctx context.Context, req *cli_service.TExecuteStatementReq) (*cli_service.TExecuteStatementResp, error) {
return &cli_service.TExecuteStatementResp{
Status: &cli_service.TStatus{StatusCode: cli_service.TStatusCode_SUCCESS_STATUS},
OperationHandle: &cli_service.TOperationHandle{
OperationId: &cli_service.THandleIdentifier{
GUID: []byte{1, 2, 3, 4, 2, 23, 4, 2, 3, 2, 3, 4, 4, 223, 34, 54},
Secret: []byte("b"),
},
},
}, nil
},
FnGetOperationStatus: func(ctx context.Context, req *cli_service.TGetOperationStatusReq) (*cli_service.TGetOperationStatusResp, error) {
return &cli_service.TGetOperationStatusResp{
OperationState: cli_service.TOperationStatePtr(cli_service.TOperationState_FINISHED_STATE),
NumModifiedRows: numModifiedRows,
}, nil
},
FnGetResultSetMetadata: func(ctx context.Context, req *cli_service.TGetResultSetMetadataReq) (*cli_service.TGetResultSetMetadataResp, error) {
isStaging := false
return &cli_service.TGetResultSetMetadataResp{IsStagingOperation: &isStaging}, nil
},
FnCloseOperation: func(ctx context.Context, req *cli_service.TCloseOperationReq) (*cli_service.TCloseOperationResp, error) {
return &cli_service.TCloseOperationResp{}, nil
},
}
cfg := config.WithDefaults()
WithReportUnknownRowsAffected(reportUnknown)(cfg)
testConn := &conn{
cfg: cfg,
backend: thriftbackend.NewForTest(testClient, getTestSession(), cfg),
}
res, err := testConn.ExecContext(context.Background(), "CREATE VIEW v AS SELECT 1", []driver.NamedValue{})
assert.NoError(t, err)
if !assert.NotNil(t, res) {
return 0
}
rowsAffected, err := res.RowsAffected()
assert.NoError(t, err)
return rowsAffected
}

t.Run("unreported count is 0 by default", func(t *testing.T) {
assert.Equal(t, int64(0), execWithStatus(t, false, nil))
})
t.Run("unreported count is -1 when enabled", func(t *testing.T) {
assert.Equal(t, int64(-1), execWithStatus(t, true, nil))
})
t.Run("reported 0 stays 0 when enabled", func(t *testing.T) {
assert.Equal(t, int64(0), execWithStatus(t, true, thrift.Int64Ptr(0)))
})
t.Run("reported count unchanged when enabled", func(t *testing.T) {
assert.Equal(t, int64(10), execWithStatus(t, true, thrift.Int64Ptr(10)))
})
}

func TestConn_ExecContext(t *testing.T) {
t.Parallel()
t.Run("ExecContext currently does not support query parameters", func(t *testing.T) {
Expand Down
15 changes: 15 additions & 0 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,21 @@ func WithEnableMetricViewMetadata(enable bool) ConnOption {
}
}

// WithReportUnknownRowsAffected controls what Result.RowsAffected() returns when
// the server reports no modified-row count for a statement (for example DDL such
// as CREATE VIEW, or a SELECT run through ExecContext). Default is false, which
// returns 0 in that case, so "no count reported" cannot be told apart from "zero
// rows modified". When enabled, RowsAffected() returns -1 for an unreported count;
// a reported count, including 0, is returned unchanged. Applies to both the
// default (Thrift) and the kernel backends. DSN: reportUnknownRowsAffected=true.
//
// See https://github.com/databricks/databricks-sql-go/issues/588.
func WithReportUnknownRowsAffected(enable bool) ConnOption {
return func(c *config.Config) {
c.ReportUnknownRowsAffected = enable
}
}

// 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.
Expand Down
34 changes: 34 additions & 0 deletions connector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,40 @@ func TestNewConnector(t *testing.T) {
assert.False(t, coni.cfg.EnableMetricViewMetadata)
})

t.Run("Connector test WithReportUnknownRowsAffected", func(t *testing.T) {
for _, tc := range []struct {
name string
opts []ConnOption
want bool
}{
{"disabled by default", nil, false},
{"enabled", []ConnOption{WithReportUnknownRowsAffected(true)}, true},
{"explicitly disabled", []ConnOption{WithReportUnknownRowsAffected(false)}, false},
} {
t.Run(tc.name, func(t *testing.T) {
opts := append([]ConnOption{
WithServerHostname("databricks-host"),
WithAccessToken("token"),
WithHTTPPath("http-path"),
}, tc.opts...)
con, err := NewConnector(opts...)
require.NoError(t, err)
coni, ok := con.(*connector)
require.True(t, ok)
assert.Equal(t, tc.want, coni.cfg.ReportUnknownRowsAffected)
})
}
})

t.Run("Connector test reportUnknownRowsAffected DSN parameter", func(t *testing.T) {
d := &databricksDriver{}
con, err := d.OpenConnector("token:supersecret@databricks-host:443/http-path?reportUnknownRowsAffected=true")
require.NoError(t, err)
coni, ok := con.(*connector)
require.True(t, ok)
assert.True(t, coni.cfg.ReportUnknownRowsAffected)
})

t.Run("Connector test WithArrowNativeDecimal enabled", func(t *testing.T) {
host := "databricks-host"
accessToken := "token"
Expand Down
2 changes: 2 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Supported optional connection parameters can be specified in param=value and inc
- useCloudFetch: Used to enable cloud fetch for the query execution. Default is true
- maxDownloadThreads: Sets the CloudFetch download window on both backends. When unset, defaults to 10 on Thrift and 16 on the kernel; an explicit value <= 0 logs a warning and uses 10
- useArrowNativeDecimal: Returns DECIMAL columns as native Arrow decimal128 (via GetArrowBatches); when scanned through database/sql they are returned as lossless strings. Default is false
- reportUnknownRowsAffected: When true, Result.RowsAffected() returns -1 if the server reports no modified-row count (e.g. DDL), instead of 0. A reported count, including 0, is unchanged. Both backends. 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
Expand Down Expand Up @@ -91,6 +92,7 @@ Supported functional options include:
- WithUserAgentEntry(<isv-name+product-name> string). Used to identify partners. Optional
- WithCloudFetch (bool). Used to enable cloud fetch for the query execution. Default is true. Optional
- WithMaxDownloadThreads (<num_threads> int). Sets the CloudFetch download window on both backends. When unset, defaults to 10 on Thrift and 16 on the kernel; an explicit value <= 0 logs a warning and uses 10. Optional
- WithReportUnknownRowsAffected (bool). When true, Result.RowsAffected() returns -1 if the server reports no modified-row count (e.g. DDL such as CREATE VIEW), so it can be told apart from zero rows modified; a reported count, including 0, is unchanged. Both backends. Default is false (returns 0). 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
Expand Down
46 changes: 46 additions & 0 deletions driver_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,52 @@ func TestE2EDSNQueryTimeout(t *testing.T) {
testDSNQueryTimeout(t, host, httpPath, token, "", "60", "-1")
}

// The unit tests mock TGetOperationStatusResp, so only a live warehouse shows
// whether the server leaves NumModifiedRows unset for a view DDL (the option
// would have no effect if it sent an explicit 0).
// See https://github.com/databricks/databricks-sql-go/issues/588.
func TestE2EReportUnknownRowsAffected(t *testing.T) {
Comment thread
shiminlin-db marked this conversation as resolved.
Resolved
host, httpPath, token := pecoTestingCreds(t)
for _, report := range []bool{false, true} {
t.Run(fmt.Sprintf("report=%t", report), func(t *testing.T) {
connector, err := NewConnector(
WithServerHostname(host), WithPort(443), WithHTTPPath(httpPath), WithAccessToken(token),
WithReportUnknownRowsAffected(report),
)
require.NoError(t, err)
db := sql.OpenDB(connector)
defer db.Close() //nolint:errcheck
testViewDDLRowsAffected(t, db, report)
})
}
}

// testViewDDLRowsAffected is shared with the kernel E2E suite.
func testViewDDLRowsAffected(t *testing.T, db *sql.DB, reportUnknown bool) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
// Temporary views are session-scoped, so pin one connection.
conn, err := db.Conn(ctx)
require.NoError(t, err)
defer conn.Close() //nolint:errcheck

want := int64(0)
if reportUnknown {
want = -1
}
for _, statement := range []string{
"CREATE OR REPLACE TEMPORARY VIEW go_e2e_rows_affected_unknown AS SELECT 1 AS id",
"DROP VIEW go_e2e_rows_affected_unknown",
} {
res, err := conn.ExecContext(ctx, statement)
require.NoError(t, err, statement)
rowsAffected, err := res.RowsAffected()
require.NoError(t, err, statement)
assert.Equal(t, want, rowsAffected, statement)
}
}

// TestE2ETimestampNTZTypeName asserts that a zoned TIMESTAMP and a TIMESTAMP_NTZ
// in the same result set report distinct database type names. The Databricks
// TIMESTAMP_NTZ type is a wall-clock value with no zone; it must be reported as
Expand Down
9 changes: 7 additions & 2 deletions internal/backend/kernel/affectedrows.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@ package kernel
// that doesn't surface the counter (the kernel's num_modified_rows Option<i64> is
// None). The Thrift path reports 0 in exactly those cases (TGetOperationStatusResp
// defaults NumModifiedRows to 0), so the -1 sentinel is folded to 0 for parity.
// A real DML count (>= 0) passes through unchanged.
func normalizeAffectedRows(n int64) int64 {
// With reportUnknown (WithReportUnknownRowsAffected) it is reported as -1
// instead, matching the Thrift path under the same option. A real DML count
// (>= 0) passes through unchanged either way.
func normalizeAffectedRows(n int64, reportUnknown bool) int64 {
if n < 0 {
if reportUnknown {
return -1
}
return 0
}
return n
Expand Down
26 changes: 16 additions & 10 deletions internal/backend/kernel/affectedrows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,26 @@ import "testing"

func TestNormalizeAffectedRows(t *testing.T) {
cases := []struct {
name string
in int64
want int64
name string
in int64
reportUnknown bool
want int64
}{
{"ddl or select sentinel (-1) folds to Thrift's 0", -1, 0},
{"any negative folds to 0", -42, 0},
{"zero real count is preserved", 0, 0},
{"positive DML count passes through", 7, 7},
{"large DML count passes through", 1_000_000, 1_000_000},
{"ddl or select sentinel (-1) folds to Thrift's 0", -1, false, 0},
{"any negative folds to 0", -42, false, 0},
{"zero real count is preserved", 0, false, 0},
{"positive DML count passes through", 7, false, 7},
{"large DML count passes through", 1_000_000, false, 1_000_000},

{"report unknown: sentinel (-1) stays -1", -1, true, -1},
{"report unknown: any negative maps to -1", -42, true, -1},
{"report unknown: zero real count is preserved", 0, true, 0},
{"report unknown: positive DML count passes through", 7, true, 7},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := normalizeAffectedRows(tc.in); got != tc.want {
t.Errorf("normalizeAffectedRows(%d) = %d, want %d", tc.in, got, tc.want)
if got := normalizeAffectedRows(tc.in, tc.reportUnknown); got != tc.want {
t.Errorf("normalizeAffectedRows(%d, %v) = %d, want %d", tc.in, tc.reportUnknown, got, tc.want)
}
})
}
Expand Down
4 changes: 4 additions & 0 deletions internal/backend/kernel/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ type Config struct {
// the exact string (from WithKernelDecimalAsFloat). Kernel still sends Decimal128.
DecimalAsFloat bool

// ReportUnknownRowsAffected keeps the C ABI's "no modified-row count" sentinel
// as -1 instead of folding it to 0 (from WithReportUnknownRowsAffected).
ReportUnknownRowsAffected bool

// EnableGeoSpatialSupport selects the local GEOMETRY / GEOGRAPHY result
// representation. True requests the canonical struct<srid,wkb> Arrow
// representation; false requests WKT / EWKT strings. The connector always
Expand Down
5 changes: 3 additions & 2 deletions internal/backend/kernel/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,9 @@ func (k *KernelBackend) execute(ctx context.Context, req backend.ExecRequest) (b
// Capture the modified-row count and server query id now, while exec is live —
// the operation is closed (nulling exec) before these are read on the
// ExecContext path, and the query-id pointer is only valid while exec lives.
// normalizeAffectedRows folds the C ABI's -1 sentinel to 0 for Thrift parity.
op.affectedRows = normalizeAffectedRows(int64(C.kernel_executed_statement_num_modified_rows(exec)))
// normalizeAffectedRows folds the C ABI's -1 sentinel to 0 for Thrift parity,
// or keeps it as -1 under WithReportUnknownRowsAffected.
op.affectedRows = normalizeAffectedRows(int64(C.kernel_executed_statement_num_modified_rows(exec)), k.cfg.ReportUnknownRowsAffected)
// A nil execErr means the statement reached a terminal state server-side (it
// committed). We deliberately do NOT re-check ctx.Err() here to convert a
// completed statement into a cancellation: for a non-idempotent DML that would
Expand Down
7 changes: 6 additions & 1 deletion internal/backend/thrift/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,13 @@ func (o *thriftOperation) StatementID() string {
}

// AffectedRows is the modified-row count for ExecContext, from the terminal
// status response.
// status response. An unset NumModifiedRows (DDL, SELECT, or a server that does
// not report it) reads as 0, or as -1 under WithReportUnknownRowsAffected so
// callers can tell it apart from a reported zero.
func (o *thriftOperation) AffectedRows() int64 {
if o.backend.cfg.ReportUnknownRowsAffected && (o.opStatusResp == nil || !o.opStatusResp.IsSetNumModifiedRows()) {
Comment thread
shiminlin-db marked this conversation as resolved.
Resolved
return -1
}
return o.opStatusResp.GetNumModifiedRows()
}

Expand Down
Loading
Loading