Skip to content

Commit 0b64f1b

Browse files
vuanhphungIsaac
andcommitted
fix: render Thrift complex values in linear time
Render nested Thrift ARRAY, MAP and STRUCT values into a shared byte buffer instead of repeatedly copying growing strings, making wide results linear while preserving their existing text representation. Fixes #596 Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 319b145 commit 0b64f1b

6 files changed

Lines changed: 453 additions & 120 deletions

File tree

‎.github/workflows/nightly-e2e.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ jobs:
9090
DATABRICKS_PECOTESTING_TOKEN_PERSONAL: ${{ secrets.DATABRICKS_PECOTESTING_TOKEN_PERSONAL }}
9191
run: |
9292
go test -tags e2e -count=1 -v -timeout 15m \
93-
-run 'TestE2EArrow(SchemaBeforeFetching|BatchesSurviveQueryContextCancellation)|TestE2ECloudFetchExactRowCount|TestE2ECloudFetchNonPositiveMaxDownloadThreads|TestE2EDecimalMetadata|TestE2EVariantTypeName|TestE2EGeospatialTypeNames|^TestE2ETime(Results|ArrowResults)$|TestE2ERejectedRequestClosesResponse' .
93+
-run 'TestE2EArrow(SchemaBeforeFetching|BatchesSurviveQueryContextCancellation)|TestE2ECloudFetchExactRowCount|TestE2ECloudFetchNonPositiveMaxDownloadThreads|TestE2EDecimalMetadata|TestE2EComplexRendering|TestE2EVariantTypeName|TestE2EGeospatialTypeNames|^TestE2ETime(Results|ArrowResults)$|TestE2ERejectedRequestClosesResponse' .
9494
9595
kernel-e2e:
9696
name: E2E (kernel backend)

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Driver changes
66

7+
- Render Thrift ARRAY, MAP and STRUCT values in linear time (databricks/databricks-sql-go#596).
78
- **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).
89
- **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).
910
- Evict kernel connections when SEA reports a missing or invalid session, and reject later requests locally without replaying the failed statement.

‎driver_e2e_test.go‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package dbsql
33
import (
44
"bytes"
55
"context"
6+
"crypto/sha256"
67
"database/sql"
78
"database/sql/driver"
89
"encoding/json"
@@ -37,6 +38,40 @@ import (
3738
"github.com/stretchr/testify/require"
3839
)
3940

41+
func TestE2EComplexRendering(t *testing.T) {
42+
host, httpPath, token := pecoTestingCreds(t)
43+
connector, err := NewConnector(WithServerHostname(host), WithHTTPPath(httpPath), WithAccessToken(token))
44+
require.NoError(t, err)
45+
db := sql.OpenDB(connector)
46+
t.Cleanup(func() { require.NoError(t, db.Close()) })
47+
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
48+
defer cancel()
49+
result, err := db.QueryContext(ctx, `SELECT
50+
transform(sequence(0, 1535), x -> CAST(x AS DOUBLE) / 7 - 0.5D),
51+
map(1, array(1.25D, NULL), 2, array()),
52+
named_struct('items', array(named_struct('id', 1, 'text', 'a"<>&')),
53+
'lookup', map('key', array(1, NULL, 3)))`)
54+
require.NoError(t, err)
55+
defer func() { require.NoError(t, result.Close()) }()
56+
start := time.Now()
57+
require.True(t, result.Next())
58+
var wide, mapping, nested string
59+
require.NoError(t, result.Scan(&wide, &mapping, &nested))
60+
scanTime := time.Since(start)
61+
values := make([]float64, 1536)
62+
for index := range values {
63+
values[index] = float64(index)/7 - 0.5
64+
}
65+
expected, err := json.Marshal(values)
66+
require.NoError(t, err)
67+
require.Equal(t, string(expected), wide)
68+
require.Equal(t, `{"1":[1.25,null],"2":[]}`, mapping)
69+
require.Equal(t, `{"items":[{"id":1,"text":"a\"\u003c\u003e\u0026"}],"lookup":{"key":[1,null,3]}}`, nested)
70+
t.Logf("1536-element array: %d bytes, sha256=%x, Next+Scan=%s (shared warehouse)", len(wide), sha256.Sum256([]byte(wide)), scanTime)
71+
require.False(t, result.Next())
72+
require.NoError(t, result.Err())
73+
}
74+
4075
func TestE2EDecimalMetadata(t *testing.T) {
4176
host, httpPath, token := pecoTestingCreds(t)
4277
for _, native := range []bool{false, true} {

‎internal/rows/arrowbased/columnValues.go‎

Lines changed: 104 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package arrowbased
22

33
import (
4-
"strings"
54
"time"
65

76
"github.com/apache/arrow-go/v18/arrow"
@@ -202,6 +201,7 @@ func (cv *columnValuesTyped[X, T]) SetValueArray(colData arrow.ArrayData) error
202201
var _ columnValues = (*columnValuesTyped[*array.Int16, int16])(nil)
203202

204203
type listValueContainer struct {
204+
scratch []byte
205205
listArray array.ListLike
206206
values columnValues
207207
complexValue bool
@@ -210,50 +210,62 @@ type listValueContainer struct {
210210

211211
var _ columnValues = (*listValueContainer)(nil)
212212

213+
type complexValueAppender interface {
214+
appendValue([]byte, int) ([]byte, error)
215+
}
216+
217+
func renderComplexValue(container complexValueAppender, scratch *[]byte, row int) (any, error) {
218+
value, err := container.appendValue((*scratch)[:0], row)
219+
if err != nil {
220+
return nil, err
221+
}
222+
*scratch = value
223+
return string(value), nil
224+
}
225+
226+
func appendColumnValue(dst []byte, holder columnValues, complex bool, row int) ([]byte, error) {
227+
if holder.IsNull(row) {
228+
return append(dst, "null"...), nil
229+
}
230+
if complex {
231+
return holder.(complexValueAppender).appendValue(dst, row)
232+
}
233+
value, err := holder.Value(row)
234+
if err != nil {
235+
return nil, err
236+
}
237+
return marshalScalar(dst, holder, row, value)
238+
}
239+
213240
func (lvc *listValueContainer) Value(i int) (any, error) {
214241
if i < lvc.listArray.Len() {
215-
var scratch [64]byte
216-
r := "["
217-
s, e := lvc.listArray.ValueOffsets(i)
218-
len := int(e - s)
219-
220-
for i := 0; i < len; i++ {
221-
if lvc.values.IsNull(i + int(s)) {
222-
r = r + "null"
223-
} else {
224-
225-
val, err := lvc.values.Value(i + int(s))
226-
if err != nil {
227-
return nil, err
228-
}
229-
230-
if !lvc.complexValue {
231-
vb, err := marshalScalar(scratch[:0], lvc.values, i+int(s), val)
232-
if err != nil {
233-
return nil, err
234-
}
235-
r = r + string(vb)
236-
} else {
237-
r = r + val.(string)
238-
}
239-
}
240-
241-
if i < len-1 {
242-
r = r + ","
243-
}
244-
}
245-
246-
r = r + "]"
247-
return r, nil
242+
return renderComplexValue(lvc, &lvc.scratch, i)
248243
}
249244
return nil, nil
250245
}
251246

247+
func (lvc *listValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
248+
dst = append(dst, '[')
249+
start, end := lvc.listArray.ValueOffsets(row)
250+
for index := start; index < end; index++ {
251+
if index > start {
252+
dst = append(dst, ',')
253+
}
254+
var err error
255+
dst, err = appendColumnValue(dst, lvc.values, lvc.complexValue, int(index))
256+
if err != nil {
257+
return nil, err
258+
}
259+
}
260+
return append(dst, ']'), nil
261+
}
262+
252263
func (lvc *listValueContainer) IsNull(i int) bool {
253264
return lvc.listArray.IsNull(i)
254265
}
255266

256267
func (lvc *listValueContainer) Release() {
268+
lvc.scratch = nil
257269
if lvc.listArray != nil {
258270
lvc.listArray.Release()
259271
}
@@ -264,6 +276,7 @@ func (lvc *listValueContainer) Release() {
264276
}
265277

266278
func (lvc *listValueContainer) SetValueArray(colData arrow.ArrayData) error {
279+
lvc.scratch = nil
267280
lvc.listArray = array.NewListData(colData)
268281
lvs := lvc.listArray.ListValues()
269282
err := lvc.values.SetValueArray(lvs.Data())
@@ -272,6 +285,7 @@ func (lvc *listValueContainer) SetValueArray(colData arrow.ArrayData) error {
272285
}
273286

274287
type mapValueContainer struct {
288+
scratch []byte
275289
mapArray *array.Map
276290
keys columnValues
277291
values columnValues
@@ -283,62 +297,50 @@ var _ columnValues = (*mapValueContainer)(nil)
283297

284298
func (mvc *mapValueContainer) Value(i int) (any, error) {
285299
if i < mvc.mapArray.Len() {
286-
s, e := mvc.mapArray.ValueOffsets(i)
287-
len := e - s
288-
var keyScratch, scratch [64]byte
289-
r := "{"
290-
for i := int64(0); i < len; i++ {
291-
k, err := mvc.keys.Value(int(i + s))
292-
if err != nil {
293-
return nil, err
294-
}
295-
296-
key, err := marshalScalar(keyScratch[:0], mvc.keys, int(i+s), k)
297-
if err != nil {
298-
return nil, err
299-
}
300-
301-
v, err := mvc.values.Value(int(i + s))
302-
if err != nil {
303-
return nil, err
304-
}
305-
306-
var b string
307-
if mvc.values.IsNull(int(i + s)) {
308-
b = "null"
309-
} else if mvc.complexValue {
310-
b = v.(string)
311-
} else {
312-
vb, err := marshalScalar(scratch[:0], mvc.values, int(i+s), v)
313-
if err != nil {
314-
return nil, err
315-
}
316-
b = string(vb)
317-
}
318-
319-
if !strings.HasPrefix(string(key), "\"") {
320-
r = r + "\"" + string(key) + "\":"
321-
} else {
322-
r = r + string(key) + ":"
323-
}
324-
325-
r = r + b
326-
if i < len-1 {
327-
r = r + ","
328-
}
329-
}
330-
r = r + "}"
331-
332-
return r, nil
300+
return renderComplexValue(mvc, &mvc.scratch, i)
333301
}
334302
return nil, nil
335303
}
336304

305+
func (mvc *mapValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
306+
dst = append(dst, '{')
307+
start, end := mvc.mapArray.ValueOffsets(row)
308+
var keyScratch [64]byte
309+
for index := start; index < end; index++ {
310+
if index > start {
311+
dst = append(dst, ',')
312+
}
313+
value, err := mvc.keys.Value(int(index))
314+
if err != nil {
315+
return nil, err
316+
}
317+
key, err := marshalScalar(keyScratch[:0], mvc.keys, int(index), value)
318+
if err != nil {
319+
return nil, err
320+
}
321+
quoted := len(key) > 0 && key[0] == '"'
322+
if !quoted {
323+
dst = append(dst, '"')
324+
}
325+
dst = append(dst, key...)
326+
if !quoted {
327+
dst = append(dst, '"')
328+
}
329+
dst = append(dst, ':')
330+
dst, err = appendColumnValue(dst, mvc.values, mvc.complexValue, int(index))
331+
if err != nil {
332+
return nil, err
333+
}
334+
}
335+
return append(dst, '}'), nil
336+
}
337+
337338
func (mvc *mapValueContainer) IsNull(i int) bool {
338339
return mvc.mapArray.IsNull(i)
339340
}
340341

341342
func (mvc *mapValueContainer) Release() {
343+
mvc.scratch = nil
342344
if mvc.mapArray != nil {
343345
mvc.mapArray.Release()
344346
}
@@ -353,6 +355,7 @@ func (mvc *mapValueContainer) Release() {
353355
}
354356

355357
func (mvc *mapValueContainer) SetValueArray(colData arrow.ArrayData) error {
358+
mvc.scratch = nil
356359
mvc.mapArray = array.NewMapData(colData)
357360
err := mvc.values.SetValueArray(mvc.mapArray.Items().Data())
358361
if err != nil {
@@ -364,6 +367,7 @@ func (mvc *mapValueContainer) SetValueArray(colData arrow.ArrayData) error {
364367
}
365368

366369
type structValueContainer struct {
370+
scratch []byte
367371
structArray *array.Struct
368372
fieldKeys []string // precomputed JSON-escaped `"name":` prefixes, one per field
369373
complexValue []bool
@@ -378,53 +382,33 @@ var _ columnValues = (*structValueContainer)(nil)
378382
// byte-identically — internal/rows/arrowbased/arrowscan_parity_test.go guards it.
379383
func (svc *structValueContainer) Value(i int) (any, error) {
380384
if i < svc.structArray.Len() {
381-
var scratch [64]byte
382-
r := "{"
383-
for j := range svc.fieldValues {
384-
// fieldKeys[j] is the precomputed JSON-escaped `"name":` prefix (built
385-
// once at construction). Escaping matters — a raw `"` + name + `"` concat
386-
// produces invalid JSON for a name with a quote/backslash/control char
387-
// (`a"b` → `{"a"b":...}`) — but doing it per row would re-marshal the same
388-
// constant strings N_rows × N_fields times on this hot path.
389-
r = r + svc.fieldKeys[j]
390-
391-
if svc.fieldValues[j].IsNull(int(i)) {
392-
r = r + "null"
393-
} else {
394-
v, err := svc.fieldValues[j].Value(int(i))
395-
if err != nil {
396-
return nil, err
397-
}
398-
399-
var b string
400-
if svc.complexValue[j] {
401-
b = v.(string)
402-
} else {
403-
vb, err := marshalScalar(scratch[:0], svc.fieldValues[j], int(i), v)
404-
if err != nil {
405-
return nil, err
406-
}
407-
b = string(vb)
408-
}
409-
410-
r = r + b
411-
}
412-
if j < len(svc.fieldValues)-1 {
413-
r = r + ","
414-
}
415-
}
416-
r = r + "}"
417-
418-
return r, nil
385+
return renderComplexValue(svc, &svc.scratch, i)
419386
}
420387
return nil, nil
421388
}
422389

390+
func (svc *structValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
391+
dst = append(dst, '{')
392+
for index, holder := range svc.fieldValues {
393+
if index > 0 {
394+
dst = append(dst, ',')
395+
}
396+
dst = append(dst, svc.fieldKeys[index]...)
397+
var err error
398+
dst, err = appendColumnValue(dst, holder, svc.complexValue[index], row)
399+
if err != nil {
400+
return nil, err
401+
}
402+
}
403+
return append(dst, '}'), nil
404+
}
405+
423406
func (svc *structValueContainer) IsNull(i int) bool {
424407
return svc.structArray.IsNull(i)
425408
}
426409

427410
func (svc *structValueContainer) Release() {
411+
svc.scratch = nil
428412
if svc.structArray != nil {
429413
svc.structArray.Release()
430414
}
@@ -437,6 +421,7 @@ func (svc *structValueContainer) Release() {
437421
}
438422

439423
func (svc *structValueContainer) SetValueArray(colData arrow.ArrayData) error {
424+
svc.scratch = nil
440425
svc.structArray = array.NewStructData(colData)
441426
for i := range svc.fieldValues {
442427
err := svc.fieldValues[i].SetValueArray(svc.structArray.Field(i).Data())

0 commit comments

Comments
 (0)