forked from databricks/databricks-sql-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rows.go
604 lines (515 loc) · 16.9 KB
/
rows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package dbsql
import (
"context"
"database/sql"
"database/sql/driver"
"io"
"math"
"reflect"
"strings"
"time"
"github.com/databricks/databricks-sql-go/driverctx"
"github.com/databricks/databricks-sql-go/internal/cli_service"
"github.com/databricks/databricks-sql-go/internal/client"
"github.com/databricks/databricks-sql-go/logger"
"github.com/pkg/errors"
)
type rows struct {
client cli_service.TCLIService
connId string
correlationId string
opHandle *cli_service.TOperationHandle
pageSize int64
location *time.Location
fetchResults *cli_service.TFetchResultsResp
fetchResultsMetadata *cli_service.TGetResultSetMetadataResp
nextRowIndex int64
nextRowNumber int64
closed bool
}
var _ driver.Rows = (*rows)(nil)
var _ driver.RowsColumnTypeScanType = (*rows)(nil)
var _ driver.RowsColumnTypeDatabaseTypeName = (*rows)(nil)
var _ driver.RowsColumnTypeNullable = (*rows)(nil)
var _ driver.RowsColumnTypeLength = (*rows)(nil)
var errRowsFetchPriorToStart = "databricks: unable to fetch row page prior to start of results"
var errRowsNoSchemaAvailable = "databricks: no schema in result set metadata response"
var errRowsNoClient = "databricks: instance of Rows missing client"
var errRowsNilRows = "databricks: nil Rows instance"
var errRowsParseValue = "databricks: unable to parse %s value '%s' from column %s"
// NewRows generates a new rows object given the rows' fields.
// NewRows will also parse directResults if it is available for some rows' fields.
func NewRows(connID string, corrId string, client cli_service.TCLIService, opHandle *cli_service.TOperationHandle, pageSize int64, location *time.Location, directResults *cli_service.TSparkDirectResults) driver.Rows {
r := &rows{
connId: connID,
correlationId: corrId,
client: client,
opHandle: opHandle,
pageSize: pageSize,
location: location,
}
if directResults != nil {
r.fetchResults = directResults.ResultSet
r.fetchResultsMetadata = directResults.ResultSetMetadata
if directResults.CloseOperation != nil {
r.closed = true
}
}
return r
}
// Columns returns the names of the columns. The number of
// columns of the result is inferred from the length of the
// slice. If a particular column name isn't known, an empty
// string should be returned for that entry.
func (r *rows) Columns() []string {
err := isValidRows(r)
if err != nil {
return []string{}
}
resultMetadata, err := r.getResultMetadata()
if err != nil {
return []string{}
}
if !resultMetadata.IsSetSchema() {
return []string{}
}
tColumns := resultMetadata.Schema.GetColumns()
colNames := make([]string, len(tColumns))
for i := range tColumns {
colNames[i] = tColumns[i].ColumnName
}
return colNames
}
// Close closes the rows iterator.
func (r *rows) Close() error {
if !r.closed {
err := isValidRows(r)
if err != nil {
return err
}
req := cli_service.TCloseOperationReq{
OperationHandle: r.opHandle,
}
ctx := driverctx.NewContextWithCorrelationId(driverctx.NewContextWithConnId(context.Background(), r.connId), r.correlationId)
_, err1 := r.client.CloseOperation(ctx, &req)
if err1 != nil {
return err1
}
}
return nil
}
// Next is called to populate the next row of data into
// the provided slice. The provided slice will be the same
// size as the Columns() are wide.
//
// Next should return io.EOF when there are no more rows.
//
// The dest should not be written to outside of Next. Care
// should be taken when closing Rows not to modify
// a buffer held in dest.
func (r *rows) Next(dest []driver.Value) error {
err := isValidRows(r)
if err != nil {
return err
}
// if the next row is not in the current result page
// fetch the containing page
if !r.isNextRowInPage() {
err := r.fetchResultPage()
if err != nil {
return err
}
}
// need the column info to retrieve/convert values
metadata, err := r.getResultMetadata()
if err != nil {
return err
}
// populate the destination slice
for i := range dest {
val, err := value(r.fetchResults.Results.Columns[i], metadata.Schema.Columns[i], r.nextRowIndex, r.location)
if err != nil {
return err
}
dest[i] = val
}
r.nextRowIndex++
r.nextRowNumber++
return nil
}
// ColumnTypeScanType returns column's native type
func (r *rows) ColumnTypeScanType(index int) reflect.Type {
err := isValidRows(r)
if err != nil {
// TODO: is there a better way to handle this
return nil
}
column, err := r.getColumnMetadataByIndex(index)
if err != nil {
// TODO: is there a better way to handle this
return nil
}
scanType := getScanType(column)
return scanType
}
// ColumnTypeDatabaseTypeName returns column's database type name
func (r *rows) ColumnTypeDatabaseTypeName(index int) string {
err := isValidRows(r)
if err != nil {
// TODO: is there a better way to handle this
return ""
}
column, err := r.getColumnMetadataByIndex(index)
if err != nil {
// TODO: is there a better way to handle this
return ""
}
dbtype := getDBTypeName(column)
return dbtype
}
// ColumnTypeNullable returns a flag indicating whether the column is nullable
// and an ok value of true if the status of the column is known. Otherwise
// a value of false is returned for ok.
func (r *rows) ColumnTypeNullable(index int) (nullable, ok bool) {
return false, false
}
func (r *rows) ColumnTypeLength(index int) (length int64, ok bool) {
columnInfo, err := r.getColumnMetadataByIndex(index)
if err != nil {
return 0, false
}
typeName := getDBTypeID(columnInfo)
switch typeName {
case cli_service.TTypeId_STRING_TYPE,
cli_service.TTypeId_VARCHAR_TYPE,
cli_service.TTypeId_BINARY_TYPE,
cli_service.TTypeId_ARRAY_TYPE,
cli_service.TTypeId_MAP_TYPE,
cli_service.TTypeId_STRUCT_TYPE:
return math.MaxInt64, true
default:
return 0, false
}
}
var (
scanTypeNull = reflect.TypeOf(nil)
scanTypeBoolean = reflect.TypeOf(true)
scanTypeFloat32 = reflect.TypeOf(float32(0))
scanTypeFloat64 = reflect.TypeOf(float64(0))
scanTypeInt8 = reflect.TypeOf(int8(0))
scanTypeInt16 = reflect.TypeOf(int16(0))
scanTypeInt32 = reflect.TypeOf(int32(0))
scanTypeInt64 = reflect.TypeOf(int64(0))
scanTypeString = reflect.TypeOf("")
scanTypeDateTime = reflect.TypeOf(time.Time{})
scanTypeRawBytes = reflect.TypeOf(sql.RawBytes{})
scanTypeUnknown = reflect.TypeOf(new(any))
)
func getScanType(column *cli_service.TColumnDesc) reflect.Type {
entry := column.TypeDesc.Types[0].PrimitiveEntry
switch entry.Type {
case cli_service.TTypeId_BOOLEAN_TYPE:
return scanTypeBoolean
case cli_service.TTypeId_TINYINT_TYPE:
return scanTypeInt8
case cli_service.TTypeId_SMALLINT_TYPE:
return scanTypeInt16
case cli_service.TTypeId_INT_TYPE:
return scanTypeInt32
case cli_service.TTypeId_BIGINT_TYPE:
return scanTypeInt64
case cli_service.TTypeId_FLOAT_TYPE:
return scanTypeFloat32
case cli_service.TTypeId_DOUBLE_TYPE:
return scanTypeFloat64
case cli_service.TTypeId_NULL_TYPE:
return scanTypeNull
case cli_service.TTypeId_STRING_TYPE:
return scanTypeString
case cli_service.TTypeId_CHAR_TYPE:
return scanTypeString
case cli_service.TTypeId_VARCHAR_TYPE:
return scanTypeString
case cli_service.TTypeId_DATE_TYPE, cli_service.TTypeId_TIMESTAMP_TYPE:
return scanTypeDateTime
case cli_service.TTypeId_DECIMAL_TYPE, cli_service.TTypeId_BINARY_TYPE, cli_service.TTypeId_ARRAY_TYPE,
cli_service.TTypeId_STRUCT_TYPE, cli_service.TTypeId_MAP_TYPE, cli_service.TTypeId_UNION_TYPE:
return scanTypeRawBytes
case cli_service.TTypeId_USER_DEFINED_TYPE:
return scanTypeUnknown
case cli_service.TTypeId_INTERVAL_DAY_TIME_TYPE, cli_service.TTypeId_INTERVAL_YEAR_MONTH_TYPE:
return scanTypeString
default:
return scanTypeUnknown
}
}
func getDBTypeName(column *cli_service.TColumnDesc) string {
entry := column.TypeDesc.Types[0].PrimitiveEntry
dbtype := strings.TrimSuffix(entry.Type.String(), "_TYPE")
return dbtype
}
func getDBTypeID(column *cli_service.TColumnDesc) cli_service.TTypeId {
entry := column.TypeDesc.Types[0].PrimitiveEntry
return entry.Type
}
// isValidRows checks that the row instance is not nil
// and that it has a client
func isValidRows(r *rows) error {
if r == nil {
return errors.New(errRowsNilRows)
}
if r.client == nil {
return errors.New(errRowsNoClient)
}
return nil
}
func (r *rows) getColumnMetadataByIndex(index int) (*cli_service.TColumnDesc, error) {
err := isValidRows(r)
if err != nil {
return nil, err
}
resultMetadata, err := r.getResultMetadata()
if err != nil {
return nil, err
}
if !resultMetadata.IsSetSchema() {
return nil, errors.New(errRowsNoSchemaAvailable)
}
columns := resultMetadata.GetSchema().GetColumns()
if index < 0 || index >= len(columns) {
return nil, errors.Errorf("invalid column index: %d", index)
}
return columns[index], nil
}
// isNextRowInPage returns a boolean flag indicating whether
// the next result set row is in the current result set page
func (r *rows) isNextRowInPage() bool {
if r == nil || r.fetchResults == nil {
return false
}
nRowsInPage := getNRows(r.fetchResults.GetResults())
if nRowsInPage == 0 {
return false
}
startRowOffset := r.getPageStartRowNum()
return r.nextRowNumber >= startRowOffset && r.nextRowNumber < (startRowOffset+nRowsInPage)
}
func (r *rows) getResultMetadata() (*cli_service.TGetResultSetMetadataResp, error) {
if r.fetchResultsMetadata == nil {
err := isValidRows(r)
if err != nil {
return nil, err
}
req := cli_service.TGetResultSetMetadataReq{
OperationHandle: r.opHandle,
}
ctx := driverctx.NewContextWithCorrelationId(driverctx.NewContextWithConnId(context.Background(), r.connId), r.correlationId)
resp, err := r.client.GetResultSetMetadata(ctx, &req)
if err != nil {
return nil, err
}
r.fetchResultsMetadata = resp
}
return r.fetchResultsMetadata, nil
}
func (r *rows) fetchResultPage() error {
err := isValidRows(r)
if err != nil {
return err
}
var log *logger.DBSQLLogger
if r.opHandle != nil {
log = logger.WithContext(r.connId, r.correlationId, client.SprintGuid(r.opHandle.OperationId.GUID))
} else {
log = logger.WithContext(r.connId, r.correlationId, "")
}
for !r.isNextRowInPage() {
// determine the direction of page fetching. Currently we only handle
// TFetchOrientation_FETCH_PRIOR and TFetchOrientation_FETCH_NEXT
var direction cli_service.TFetchOrientation = r.getPageFetchDirection()
if direction == cli_service.TFetchOrientation_FETCH_PRIOR {
if r.getPageStartRowNum() == 0 {
return errors.New(errRowsFetchPriorToStart)
}
} else if direction == cli_service.TFetchOrientation_FETCH_NEXT {
if r.fetchResults != nil && !r.fetchResults.GetHasMoreRows() {
return io.EOF
}
} else {
return errors.Errorf("unhandled fetch result orientation: %s", direction)
}
req := cli_service.TFetchResultsReq{
OperationHandle: r.opHandle,
MaxRows: r.pageSize,
Orientation: direction,
}
ctx := driverctx.NewContextWithCorrelationId(driverctx.NewContextWithConnId(context.Background(), r.connId), r.correlationId)
log.Debug().Msgf("fetching next batch of %d rows", r.pageSize)
fetchResult, err := r.client.FetchResults(ctx, &req)
if err != nil {
return err
}
r.fetchResults = fetchResult
}
// don't assume the next row is the first row in the page
r.nextRowIndex = r.nextRowNumber - r.getPageStartRowNum()
return nil
}
// getPageFetchDirection returns the cli_service.TFetchOrientation
// necessary to fetch a result page containing the next row number.
// Note: if the next row number is in the current page TFetchOrientation_FETCH_NEXT
// is returned. Use rows.nextRowInPage to determine if a fetch is necessary
func (r *rows) getPageFetchDirection() cli_service.TFetchOrientation {
if r == nil {
return cli_service.TFetchOrientation_FETCH_NEXT
}
if r.nextRowNumber < r.getPageStartRowNum() {
return cli_service.TFetchOrientation_FETCH_PRIOR
}
return cli_service.TFetchOrientation_FETCH_NEXT
}
// getPageStartRowNum returns an int64 value which is the
// starting row number of the current result page, -1 is returned
// if there is no result page
func (r *rows) getPageStartRowNum() int64 {
if r == nil || r.fetchResults == nil || r.fetchResults.GetResults() == nil {
return 0
}
return r.fetchResults.GetResults().GetStartRowOffset()
}
var dateTimeFormats map[string]string = map[string]string{
"TIMESTAMP": "2006-01-02 15:04:05.999999999",
"DATE": "2006-01-02",
}
func value(tColumn *cli_service.TColumn, tColumnDesc *cli_service.TColumnDesc, rowNum int64, location *time.Location) (val any, err error) {
if location == nil {
location = time.UTC
}
entry := tColumnDesc.TypeDesc.Types[0].PrimitiveEntry
dbtype := strings.TrimSuffix(entry.Type.String(), "_TYPE")
if tVal := tColumn.GetStringVal(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
val = tVal.Values[rowNum]
val, err = handleDateTime(val, dbtype, tColumnDesc.ColumnName, location)
} else if tVal := tColumn.GetByteVal(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
val = tVal.Values[rowNum]
} else if tVal := tColumn.GetI16Val(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
val = tVal.Values[rowNum]
} else if tVal := tColumn.GetI32Val(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
val = tVal.Values[rowNum]
} else if tVal := tColumn.GetI64Val(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
val = tVal.Values[rowNum]
} else if tVal := tColumn.GetBoolVal(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
val = tVal.Values[rowNum]
} else if tVal := tColumn.GetDoubleVal(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
if dbtype == "FLOAT" {
// database types FLOAT and DOUBLE are both returned as a float64
// convert to a float32 is valid because the FLOAT type would have
// only been four bytes on the server
val = float32(tVal.Values[rowNum])
} else {
val = tVal.Values[rowNum]
}
} else if tVal := tColumn.GetBinaryVal(); tVal != nil && !isNull(tVal.Nulls, rowNum) {
val = tVal.Values[rowNum]
}
return val, err
}
// handleDateTime will convert the passed val to a time.Time value if necessary
func handleDateTime(val any, dbType, columnName string, location *time.Location) (any, error) {
// if there is a date/time format corresponding to the column type we need to
// convert to time.Time
if format, ok := dateTimeFormats[dbType]; ok {
t, err := parseInLocation(format, val.(string), location)
if err != nil {
err = wrapErrf(err, errRowsParseValue, dbType, val, columnName)
}
return t, err
}
return val, nil
}
func isNull(nulls []byte, position int64) bool {
index := position / 8
if int64(len(nulls)) > index {
b := nulls[index]
return (b & (1 << (uint)(position%8))) != 0
}
return false
}
func getNRows(rs *cli_service.TRowSet) int64 {
if rs == nil {
return 0
}
for _, col := range rs.Columns {
if col.BoolVal != nil {
return int64(len(col.BoolVal.Values))
}
if col.ByteVal != nil {
return int64(len(col.ByteVal.Values))
}
if col.I16Val != nil {
return int64(len(col.I16Val.Values))
}
if col.I32Val != nil {
return int64(len(col.I32Val.Values))
}
if col.I64Val != nil {
return int64(len(col.I64Val.Values))
}
if col.StringVal != nil {
return int64(len(col.StringVal.Values))
}
if col.DoubleVal != nil {
return int64(len(col.DoubleVal.Values))
}
if col.BinaryVal != nil {
return int64(len(col.BinaryVal.Values))
}
}
return 0
}
// parseInLocation parses a date/time string in the given format and using the provided
// location.
// This is, essentially, a wrapper around time.ParseInLocation to handle negative year
// values
func parseInLocation(format, dateTimeString string, loc *time.Location) (time.Time, error) {
// we want to handle dates with negative year values and currently we only
// support formats that start with the year so we can just strip a leading minus
// sign
var isNegative bool
dateTimeString, isNegative = stripLeadingNegative(dateTimeString)
date, err := time.ParseInLocation(format, dateTimeString, loc)
if err != nil {
return time.Time{}, err
}
if isNegative {
date = date.AddDate(-2*date.Year(), 0, 0)
}
return date, nil
}
// stripLeadingNegative will remove a leading ascii or unicode minus
// if present. The possibly shortened string is returned and a flag indicating if
// the string was altered
func stripLeadingNegative(dateTimeString string) (string, bool) {
if dateStartsWithNegative(dateTimeString) {
// strip leading rune from dateTimeString
// using range because it is supposed to be faster than utf8.DecodeRuneInString
for i := range dateTimeString {
if i > 0 {
return dateTimeString[i:], true
}
}
}
return dateTimeString, false
}
// ISO 8601 allows for both the ascii and unicode characters for minus
const (
// unicode minus sign
uMinus string = "\u2212"
// ascii hyphen/minus
aMinus string = "\x2D"
)
// dateStartsWithNegative returns true if the string starts with
// a minus sign
func dateStartsWithNegative(val string) bool {
return strings.HasPrefix(val, aMinus) || strings.HasPrefix(val, uMinus)
}