Skip to content
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

### Driver changes

- Reduce per-cell CPU in kernel row iteration by binding typed column readers once per batch; result values and types are unchanged.
- **Behavior change:** Bound each whole-transfer Thrift CloudFetch download attempt, including `WithTransport`, by the existing 900s `ClientTimeout`, and omit the link's presigned query string from download errors (databricks/databricks-sql-go#475).
- **Behavior change:** Without direct results, `ArrowIPCStreamIterator.SchemaBytes()` and `ArrowBatchIterator.Schema()` now retrieve result metadata without fetching data and return the result schema, including for empty results, and can return request or schema-conversion errors. Schemas inferred from Thrift metadata may differ from CloudFetch file schemas when server ArrowSchema is absent (databricks/databricks-sql-go#312).
- Evict kernel connections when SEA reports a missing or invalid session, and reject later requests locally without replaying the failed statement.
Expand Down
9 changes: 5 additions & 4 deletions internal/arrowscan/arrowscan.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ func ScanCellCached(col arrow.Array, row int, loc *time.Location, keys *StructKe
// fieldlessLocation applies IsTimestampNTZField's zone-less fallback for the
// entry points that receive only an array, not its schema Field: a top-level
// timestamp with an empty TimeZone is treated as TIMESTAMP_NTZ and scanned in
// UTC. Callers that know the Field (the kernel rows via
// ScanCellCachedWithOptions) decide NTZ from its metadata and pass loc directly.
// UTC. Callers that know the Field (the kernel rows via BindCellScanner) decide
// NTZ from its metadata and pass loc directly.
func fieldlessLocation(col arrow.Array, loc *time.Location) *time.Location {
if IsTimestampNTZField(arrow.Field{Type: col.DataType()}) {
return time.UTC
Expand All @@ -146,8 +146,8 @@ type ScanOptions struct {
GeospatialBinary bool
}

// ScanCellCachedWithOptions is the full scanner entry point used by the kernel
// rows implementation. Callers that do not need result-specific adaptations
// ScanCellCachedWithOptions is the one-shot counterpart to BindCellScanner,
// which the kernel rows implementation uses. Callers without result adaptations
// should continue to use ScanCellCached. Unlike the field-less entry points, loc
// is authoritative here: the caller decides TIMESTAMP_NTZ from the schema Field
// (IsTimestampNTZField) and passes time.UTC for an NTZ column.
Expand All @@ -165,6 +165,7 @@ func scanCell(col arrow.Array, row int, loc *time.Location, keys *StructKeyCache
switch c := col.(type) {
case *array.Null:
return nil, nil
// Keep scalar results in sync with the bound readers in bind.go.
case *array.Boolean:
return c.Value(row), nil
case *array.Int8:
Expand Down
80 changes: 80 additions & 0 deletions internal/arrowscan/bind.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package arrowscan

import (
"database/sql/driver"
"strings"
"time"

"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/bitutil"
)

// CellScanner reads a cell while its caller-owned Arrow array is alive.
type CellScanner func(row int) (driver.Value, error)

// BindCellScanner resolves a column's scalar reader and null bitmap once per
// batch. Like ScanCellCachedWithOptions, loc is authoritative for timestamps.
func BindCellScanner(col arrow.Array, loc *time.Location, keys *StructKeyCache, options ScanOptions) CellScanner {
if options.GeospatialBinary {
return func(row int) (driver.Value, error) {
return scanCell(col, row, loc, keys, options)
}
}
var read CellScanner
switch column := col.(type) {
case *array.Boolean:
var values []byte
if buffer := column.Data().Buffers()[1]; buffer != nil {
values = buffer.Bytes()
}
offset := column.Data().Offset()
read = func(row int) (driver.Value, error) { return bitutil.BitIsSet(values, offset+row), nil }
case *array.Int8:
read = bindValues(column.Values())
case *array.Int16:
read = bindValues(column.Values())
case *array.Int32:
read = bindValues(column.Values())
case *array.Int64:
read = bindValues(column.Values())
case *array.Float32:
read = bindValues(column.Values())
case *array.Float64:
read = bindValues(column.Values())
case *array.Date32:
values := column.Values()
read = func(row int) (driver.Value, error) { return inLocation(values[row].ToTime(), loc), nil }
case *array.Date64:
values := column.Values()
read = func(row int) (driver.Value, error) { return inLocation(values[row].ToTime(), loc), nil }
case *array.Timestamp:
values := column.Values()
unit := column.DataType().(*arrow.TimestampType).Unit
read = func(row int) (driver.Value, error) {
return inLocation(timestampToTime(int64(values[row]), unit), loc), nil
}
case *array.String:
read = func(row int) (driver.Value, error) { return strings.Clone(column.Value(row)), nil }
case *array.Binary:
read = func(row int) (driver.Value, error) { return column.Value(row), nil }
default:
return func(row int) (driver.Value, error) {
return scanCell(col, row, loc, keys, options)
}
}
if col.NullN() == 0 || len(col.NullBitmapBytes()) == 0 {
return read
}
bitmap, offset := col.NullBitmapBytes(), col.Data().Offset()
return func(row int) (driver.Value, error) {
if !bitutil.BitIsSet(bitmap, offset+row) {
return nil, nil
}
return read(row)
}
}

func bindValues[Value any](values []Value) CellScanner {
return func(row int) (driver.Value, error) { return values[row], nil }
}
96 changes: 96 additions & 0 deletions internal/arrowscan/bind_cdata_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
//go:build cgo

package arrowscan

import (
"strings"
"testing"

"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/cdata"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/arrow/memory/mallocator"
)

func TestBoundCellCDataParity(t *testing.T) {
fixtures := []struct {
name string
dataType arrow.DataType
values []string
}{
{"bool", arrow.FixedWidthTypes.Boolean, []string{"true", "false"}},
{"int8", arrow.PrimitiveTypes.Int8, []string{"-128", "127"}},
{"int16", arrow.PrimitiveTypes.Int16, []string{"-32768", "32767"}},
{"int32", arrow.PrimitiveTypes.Int32, []string{"-12345", "67890"}},
{"int64", arrow.PrimitiveTypes.Int64, []string{"-9223372036854775808", "9223372036854775807"}},
{"float32", arrow.PrimitiveTypes.Float32, []string{"0.1", "-0.0"}},
{"float64", arrow.PrimitiveTypes.Float64, []string{"0.1", "-0.0"}},
{"date32", arrow.FixedWidthTypes.Date32, []string{`"0001-01-01"`, `"9999-12-31"`}},
{"date64", arrow.FixedWidthTypes.Date64, []string{`"0001-01-01"`, `"9999-12-31"`}},
{"timestamp", &arrow.TimestampType{Unit: arrow.Microsecond, TimeZone: "UTC"}, []string{"-123456789", "123456789"}},
{"string", arrow.BinaryTypes.String, []string{`""`, `"héllo\u0000世界"`}},
{"binary", arrow.BinaryTypes.Binary, []string{`""`, `"AAEC/w=="`}},
{"decimal", &arrow.Decimal128Type{Precision: 10, Scale: 2}, []string{`"-123.45"`, `"678.90"`}},
{"list", arrow.ListOf(arrow.PrimitiveTypes.Int32), []string{"[1,null,3]", "[]"}},
}
for _, mode := range []string{"nullable", "no-bitmap"} {
t.Run(mode, func(t *testing.T) {
pool := memory.NewCheckedAllocator(mallocator.NewMallocator())
defer pool.AssertSize(t, 0)
fields := make([]arrow.Field, len(fixtures))
columns := make([]arrow.Array, len(fixtures))
for index, fixture := range fixtures {
values := make([]string, 40)
for row := range values {
values[row] = fixture.values[row%len(fixture.values)]
if mode == "nullable" && row%5 == 0 {
values[row] = "null"
}
}
column, _, err := array.FromJSON(pool, fixture.dataType, strings.NewReader("["+strings.Join(values, ",")+"]"))
if err != nil {
t.Fatal(err)
}
if mode == "no-bitmap" {
data := column.Data()
buffers := append([]*memory.Buffer(nil), data.Buffers()...)
buffers[0] = nil
withoutBitmap := array.NewData(data.DataType(), data.Len(), buffers, data.Children(), 0, data.Offset())
column.Release()
column = array.MakeFromData(withoutBitmap)
withoutBitmap.Release()
}
defer column.Release()
fields[index] = arrow.Field{Name: fixture.name, Type: fixture.dataType, Nullable: true}
columns[index] = column
}
record := array.NewRecordBatch(arrow.NewSchema(fields, nil), columns, 40)
defer record.Release()
sliced := record.NewSlice(7, 31)
defer sliced.Release()
var exportedArray cdata.CArrowArray
var exportedSchema cdata.CArrowSchema
cdata.ExportArrowRecordBatch(sliced, &exportedArray, &exportedSchema)
defer cdata.ReleaseCArrowArray(&exportedArray)
defer cdata.ReleaseCArrowSchema(&exportedSchema)
imported, err := cdata.ImportCRecordBatch(&exportedArray, &exportedSchema)
if err != nil {
t.Fatal(err)
}
defer imported.Release()
if imported.NumRows() != sliced.NumRows() || imported.NumCols() != sliced.NumCols() {
t.Fatal("C Data round-trip changed the record shape")
}
for _, column := range imported.Columns() {
if column.Data().Offset() != 7 {
t.Fatalf("C Data round-trip lost the slice offset: %d", column.Data().Offset())
}
if mode == "no-bitmap" && len(column.NullBitmapBytes()) != 0 {
t.Fatal("C Data round-trip introduced a validity bitmap")
}
checkBoundParity(t, column)
}
})
}
}
Loading
Loading