diff --git a/.github/workflows/nightly-e2e.yml b/.github/workflows/nightly-e2e.yml index 0a17f1e1e..849ad9306 100644 --- a/.github/workflows/nightly-e2e.yml +++ b/.github/workflows/nightly-e2e.yml @@ -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 @@ -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) diff --git a/CHANGELOG.md b/CHANGELOG.md index 619a69c53..3d42eb146 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6aa25e158..9c057df5d 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -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 diff --git a/README.md b/README.md index 4da2e985b..13d8e67cd 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/connection_test.go b/connection_test.go index 9057e50f4..23b115507 100644 --- a/connection_test.go +++ b/connection_test.go @@ -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) { diff --git a/connector.go b/connector.go index 78db0fdcc..c5b0bb3f9 100644 --- a/connector.go +++ b/connector.go @@ -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. diff --git a/connector_test.go b/connector_test.go index 13ba6b213..2866516ee 100644 --- a/connector_test.go +++ b/connector_test.go @@ -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" diff --git a/doc.go b/doc.go index b5f4adb28..b0d2f8295 100644 --- a/doc.go +++ b/doc.go @@ -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 @@ -91,6 +92,7 @@ Supported functional options include: - WithUserAgentEntry( string). Used to identify partners. Optional - WithCloudFetch (bool). Used to enable cloud fetch for the query execution. Default is true. Optional - WithMaxDownloadThreads ( 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 ( auth.Authenticator). Sets up authentication. Required if neither access token or client credentials are provided. - WithClientCredentials( string, string). Sets up Oauth M2M authentication. - WithUseKernel( 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 diff --git a/driver_e2e_test.go b/driver_e2e_test.go index c46bd26e1..562f370a2 100644 --- a/driver_e2e_test.go +++ b/driver_e2e_test.go @@ -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) { + 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 diff --git a/internal/backend/kernel/affectedrows.go b/internal/backend/kernel/affectedrows.go index ca2bd564a..d163d8904 100644 --- a/internal/backend/kernel/affectedrows.go +++ b/internal/backend/kernel/affectedrows.go @@ -12,9 +12,14 @@ package kernel // that doesn't surface the counter (the kernel's num_modified_rows Option 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 diff --git a/internal/backend/kernel/affectedrows_test.go b/internal/backend/kernel/affectedrows_test.go index 9df1b5f0d..64584d122 100644 --- a/internal/backend/kernel/affectedrows_test.go +++ b/internal/backend/kernel/affectedrows_test.go @@ -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) } }) } diff --git a/internal/backend/kernel/config.go b/internal/backend/kernel/config.go index c3f97ed83..f8cf1cb62 100644 --- a/internal/backend/kernel/config.go +++ b/internal/backend/kernel/config.go @@ -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 Arrow // representation; false requests WKT / EWKT strings. The connector always diff --git a/internal/backend/kernel/operation.go b/internal/backend/kernel/operation.go index e2f355f01..329b8a7e3 100644 --- a/internal/backend/kernel/operation.go +++ b/internal/backend/kernel/operation.go @@ -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 diff --git a/internal/backend/thrift/operation.go b/internal/backend/thrift/operation.go index f161c3cfe..9857accd7 100644 --- a/internal/backend/thrift/operation.go +++ b/internal/backend/thrift/operation.go @@ -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()) { + return -1 + } return o.opStatusResp.GetNumModifiedRows() } diff --git a/internal/backend/thrift/operation_test.go b/internal/backend/thrift/operation_test.go index 55dfc900c..320da3842 100644 --- a/internal/backend/thrift/operation_test.go +++ b/internal/backend/thrift/operation_test.go @@ -149,7 +149,8 @@ func TestOperationStatementID(t *testing.T) { // which returns 0 when the field is unset. AffectedRows is defined only on // the success path (per backend.Operation), where runQuery has guaranteed a // non-nil opStatusResp, so a nil-opStatusResp input is out of contract and -// not tested. +// not tested here (TestOperationAffectedRowsReportUnknown covers it under the +// option). func TestOperationAffectedRows(t *testing.T) { be := NewForTest(&client.TestClient{}, getTestSession(), config.WithDefaults()) @@ -169,6 +170,41 @@ func TestOperationAffectedRows(t *testing.T) { ) assert.Equal(t, int64(0), op.AffectedRows()) }) + + t.Run("returns an explicit 0 as 0", func(t *testing.T) { + zero := int64(0) + op := be.OperationForTest( + &cli_service.TExecuteStatementResp{OperationHandle: opHandle()}, + &cli_service.TGetOperationStatusResp{NumModifiedRows: &zero}, + ) + assert.Equal(t, int64(0), op.AffectedRows()) + }) +} + +// TestOperationAffectedRowsReportUnknown pins WithReportUnknownRowsAffected: an +// unreported count becomes -1, while any reported count (including 0) is kept. +func TestOperationAffectedRowsReportUnknown(t *testing.T) { + cfg := config.WithDefaults() + cfg.ReportUnknownRowsAffected = true + be := NewForTest(&client.TestClient{}, getTestSession(), cfg) + count := func(n int64) *int64 { return &n } + + cases := []struct { + name string + opStatus *cli_service.TGetOperationStatusResp + want int64 + }{ + {"unset NumModifiedRows -> -1", &cli_service.TGetOperationStatusResp{}, -1}, + {"nil status response -> -1", nil, -1}, + {"explicit 0 stays 0", &cli_service.TGetOperationStatusResp{NumModifiedRows: count(0)}, 0}, + {"positive count unchanged", &cli_service.TGetOperationStatusResp{NumModifiedRows: count(42)}, 42}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + op := be.OperationForTest(&cli_service.TExecuteStatementResp{OperationHandle: opHandle()}, tc.opStatus) + assert.Equal(t, tc.want, op.AffectedRows()) + }) + } } // TestOperationClose_Idempotency pins the interface contract: a second Close diff --git a/internal/config/config.go b/internal/config/config.go index f9c5143e2..80d45ed79 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -290,6 +290,11 @@ type UserConfig struct { Transport http.RoundTripper UseLz4Compression bool EnableMetricViewMetadata bool + // ReportUnknownRowsAffected makes Result.RowsAffected() return -1 instead of 0 + // when the server reports no modified-row count (DDL, SELECT, or a server that + // does not surface one), on both backends. A reported count, including 0, is + // returned unchanged. Off by default. DSN: reportUnknownRowsAffected=true. + ReportUnknownRowsAffected bool // UseArrowNativeDecimalDSN is a DSN-only carrier for the useArrowNativeDecimal // parameter. The authoritative setting lives on ArrowConfig; ParseDSN records // the DSN value here (because it can only return a UserConfig) and the @@ -339,33 +344,34 @@ func (ucfg UserConfig) DeepCopy() UserConfig { } result := UserConfig{ - Protocol: ucfg.Protocol, - Host: ucfg.Host, - Port: ucfg.Port, - HTTPPath: ucfg.HTTPPath, - Catalog: ucfg.Catalog, - Schema: ucfg.Schema, - Authenticator: ucfg.Authenticator, - AccessToken: ucfg.AccessToken, - MaxRows: ucfg.MaxRows, - QueryTimeout: ucfg.QueryTimeout, - UserAgentEntry: ucfg.UserAgentEntry, - Location: loccp, - SessionParams: sessionParams, - RetryWaitMin: ucfg.RetryWaitMin, - RetryWaitMax: ucfg.RetryWaitMax, - RetryMax: ucfg.RetryMax, - Transport: ucfg.Transport, - UseLz4Compression: ucfg.UseLz4Compression, - EnableMetricViewMetadata: ucfg.EnableMetricViewMetadata, - UseArrowNativeDecimalDSN: ucfg.UseArrowNativeDecimalDSN, - CloudFetchConfig: ucfg.CloudFetchConfig, - EnableTelemetry: ucfg.EnableTelemetry, - TelemetryBatchSize: ucfg.TelemetryBatchSize, - TelemetryFlushInterval: ucfg.TelemetryFlushInterval, - UseKernel: ucfg.UseKernel, - WarehouseID: ucfg.WarehouseID, - TokenCacheEnabledDSN: ucfg.TokenCacheEnabledDSN, + Protocol: ucfg.Protocol, + Host: ucfg.Host, + Port: ucfg.Port, + HTTPPath: ucfg.HTTPPath, + Catalog: ucfg.Catalog, + Schema: ucfg.Schema, + Authenticator: ucfg.Authenticator, + AccessToken: ucfg.AccessToken, + MaxRows: ucfg.MaxRows, + QueryTimeout: ucfg.QueryTimeout, + UserAgentEntry: ucfg.UserAgentEntry, + Location: loccp, + SessionParams: sessionParams, + RetryWaitMin: ucfg.RetryWaitMin, + RetryWaitMax: ucfg.RetryWaitMax, + RetryMax: ucfg.RetryMax, + Transport: ucfg.Transport, + UseLz4Compression: ucfg.UseLz4Compression, + EnableMetricViewMetadata: ucfg.EnableMetricViewMetadata, + ReportUnknownRowsAffected: ucfg.ReportUnknownRowsAffected, + UseArrowNativeDecimalDSN: ucfg.UseArrowNativeDecimalDSN, + CloudFetchConfig: ucfg.CloudFetchConfig, + EnableTelemetry: ucfg.EnableTelemetry, + TelemetryBatchSize: ucfg.TelemetryBatchSize, + TelemetryFlushInterval: ucfg.TelemetryFlushInterval, + UseKernel: ucfg.UseKernel, + WarehouseID: ucfg.WarehouseID, + TokenCacheEnabledDSN: ucfg.TokenCacheEnabledDSN, } if ucfg.EnableGeoSpatialSupportDSN != nil { enabled := *ucfg.EnableGeoSpatialSupportDSN @@ -525,6 +531,13 @@ func ParseDSN(dsn string) (UserConfig, error) { ucfg.EnableMetricViewMetadata = enableMetricViewMetadata } + if reportUnknownRowsAffected, ok, err := params.extractAsBool("reportUnknownRowsAffected"); ok { + if err != nil { + return UserConfig{}, err + } + ucfg.ReportUnknownRowsAffected = reportUnknownRowsAffected + } + // Arrow parameters if useArrowNativeDecimal, ok, err := params.extractAsBool("useArrowNativeDecimal"); ok { if err != nil { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 518ccaf29..e3274c4fd 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -730,6 +730,36 @@ func TestParseDSNEnableGeoSpatialSupport(t *testing.T) { } } +func TestParseDSNReportUnknownRowsAffected(t *testing.T) { + base := "token:supersecret@example.cloud.databricks.com:443/sql/1.0/endpoints/abc" + for _, tc := range []struct { + name string + query string + want bool + }{ + {name: "omitted defaults to false", query: "", want: false}, + {name: "enabled", query: "?reportUnknownRowsAffected=true", want: true}, + {name: "disabled", query: "?reportUnknownRowsAffected=false", want: false}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := ParseDSN(base + tc.query) + if err != nil { + t.Fatal(err) + } + if got.ReportUnknownRowsAffected != tc.want { + t.Errorf("ReportUnknownRowsAffected = %v, want %v", got.ReportUnknownRowsAffected, tc.want) + } + if _, leaked := got.SessionParams["reportUnknownRowsAffected"]; leaked { + t.Error("reportUnknownRowsAffected must be consumed, not forwarded as a session param") + } + }) + } + + if _, err := ParseDSN(base + "?reportUnknownRowsAffected=notabool"); err == nil { + t.Error("malformed reportUnknownRowsAffected should fail DSN parsing") + } +} + func TestParseDSNQueryTimeoutRange(t *testing.T) { if strconv.IntSize < 64 { t.Skip("strconv.Atoi rejects these values before the range check on 32-bit platforms") @@ -856,6 +886,7 @@ func TestUserConfig_DeepCopy(t *testing.T) { MaxDownloadThreads: 10, MaxDownloadThreadsSet: true, }, + ReportUnknownRowsAffected: true, } cfg_copy := cfg.DeepCopy() diff --git a/kernel_config.go b/kernel_config.go index 5a894970e..03abfd872 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -180,6 +180,8 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { // Preserve string results by default, including automatic kernel recovery. // An explicit true below opts into native geospatial values. EnableGeoSpatialSupport: false, + // Client-side: how the kernel's "no modified-row count" sentinel is reported. + ReportUnknownRowsAffected: cfg.ReportUnknownRowsAffected, } hasChunkLimit := false for key := range kc.SessionConf { diff --git a/kernel_config_test.go b/kernel_config_test.go index d8cd3c0c4..a995236b5 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -438,6 +438,8 @@ var kernelConfigFieldDisposition = map[string]string{ // Folded into SessionConf by config.EffectiveSessionParams (metric-view conf), // sent identically on both backends. "EnableMetricViewMetadata": "forwarded", + // Client-side: kernel.Config.ReportUnknownRowsAffected → normalizeAffectedRows. + "ReportUnknownRowsAffected": "forwarded", // Applied post-connect via USE CATALOG / USE SCHEMA (no kernel config setter). "Catalog": "forwarded", "Schema": "forwarded", @@ -552,6 +554,20 @@ func TestBuildKernelConfig(t *testing.T) { } }) + t.Run("report unknown rows affected defaults false and is forwarded", func(t *testing.T) { + c := baseKernelConfig() + kc := buildKernelConfig(c, kernel.Auth{Mode: kernel.AuthPAT, Token: "dapi-x"}) + if kc.ReportUnknownRowsAffected { + t.Fatal("omitted ReportUnknownRowsAffected = true, want default false") + } + + WithReportUnknownRowsAffected(true)(c) + kc = buildKernelConfig(c, kernel.Auth{Mode: kernel.AuthPAT, Token: "dapi-x"}) + if !kc.ReportUnknownRowsAffected { + t.Fatal("WithReportUnknownRowsAffected(true) was not forwarded to kernel.Config") + } + }) + t.Run("max connections forwarded", func(t *testing.T) { c := baseKernelConfig() WithKernelMaxConnections(37)(c) diff --git a/kernel_e2e_test.go b/kernel_e2e_test.go index d2d39575d..c698c7b51 100644 --- a/kernel_e2e_test.go +++ b/kernel_e2e_test.go @@ -47,6 +47,27 @@ func TestKernelE2EDecimalMetadata(t *testing.T) { } } +// TestKernelE2EReportUnknownRowsAffected checks that the kernel reports its +// unknown-count sentinel for view DDL, which the unit tests can only assume. +// See https://github.com/databricks/databricks-sql-go/issues/588. +func TestKernelE2EReportUnknownRowsAffected(t *testing.T) { + for _, report := range []bool{false, true} { + name := "report=false" + if report { + name = "report=true" + } + t.Run(name, func(t *testing.T) { + db := kernelTestDBWith(t, WithReportUnknownRowsAffected(report)) + t.Cleanup(func() { + if err := db.Close(); err != nil { + t.Error(err) + } + }) + testViewDDLRowsAffected(t, db, report) + }) + } +} + // TestKernelE2ESelect1 is the smallest end-to-end proof: PAT session over the // kernel, execute, scan one scalar row. func TestKernelE2ESelect1(t *testing.T) {