forked from marcboeker/go-duckdb
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathvalue.go
More file actions
595 lines (546 loc) · 14.5 KB
/
value.go
File metadata and controls
595 lines (546 loc) · 14.5 KB
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
package duckdb
import (
"fmt"
"math/big"
"reflect"
"time"
"github.com/duckdb/duckdb-go/v2/mapping"
)
func getValue(v mapping.Value) (any, error) {
// The logical type is valid as long as v (mapping.Value) is valid,
// i.e., it must not be destroyed.
lt := mapping.GetValueType(v)
t := mapping.GetTypeId(lt)
switch t {
case TYPE_BOOLEAN:
return mapping.GetBool(v), nil
case TYPE_TINYINT:
return mapping.GetInt8(v), nil
case TYPE_SMALLINT:
return mapping.GetInt16(v), nil
case TYPE_INTEGER:
return mapping.GetInt32(v), nil
case TYPE_BIGINT:
return mapping.GetInt64(v), nil
case TYPE_UTINYINT:
return mapping.GetUInt8(v), nil
case TYPE_USMALLINT:
return mapping.GetUInt16(v), nil
case TYPE_UINTEGER:
return mapping.GetUInt32(v), nil
case TYPE_UBIGINT:
return mapping.GetUInt64(v), nil
case TYPE_FLOAT:
return mapping.GetFloat(v), nil
case TYPE_DOUBLE:
return mapping.GetDouble(v), nil
case TYPE_TIMESTAMP_S:
ts := mapping.GetTimestampS(v)
return getTSS(&ts), nil
case TYPE_TIMESTAMP_MS:
ts := mapping.GetTimestampMS(v)
return getTSMS(&ts), nil
case TYPE_TIMESTAMP_NS:
ts := mapping.GetTimestampNS(v)
return getTSNS(&ts), nil
case TYPE_TIMESTAMP, TYPE_TIMESTAMP_TZ:
ts := mapping.GetTimestamp(v)
return getTS(t, &ts), nil
case TYPE_DATE:
date := mapping.GetDate(v)
return getDate(&date), nil
case TYPE_TIME:
ti := mapping.GetTime(v)
return getTime(&ti), nil
case TYPE_TIME_TZ:
ti := mapping.GetTimeTZ(v)
return getTimeTZ(&ti), nil
case TYPE_INTERVAL:
interval := mapping.GetInterval(v)
return getInterval(&interval), nil
case TYPE_HUGEINT:
hugeInt := mapping.GetHugeInt(v)
return hugeIntToNative(&hugeInt), nil
case TYPE_UHUGEINT:
uhugeInt := mapping.GetUHugeInt(v)
return uhugeIntToNative(&uhugeInt), nil
case TYPE_BIGNUM:
bigNum := mapping.GetBigNum(v)
defer mapping.DestroyBigNum(&bigNum)
return bigNumToNative(&bigNum), nil
case TYPE_VARCHAR:
return mapping.GetVarchar(v), nil
case TYPE_SQLNULL:
return nil, nil
default:
return nil, unsupportedTypeError(typeToStringMap[t])
}
}
func createValue(lt mapping.LogicalType, val any) (mapping.Value, error) {
t := mapping.GetTypeId(lt)
if isPrimitiveType(t) {
return createPrimitiveValue(t, val)
}
switch t {
case TYPE_ARRAY:
return createSliceValue(lt, t, val)
case TYPE_LIST:
return createSliceValue(lt, t, val)
case TYPE_STRUCT:
return createStructValue(lt, val)
case TYPE_MAP:
return createMapValue(lt, val)
default:
return mapping.Value{}, unsupportedTypeError(reflect.TypeOf(val).Name())
}
}
//nolint:gocyclo
func createPrimitiveValue(t mapping.Type, v any) (mapping.Value, error) {
switch t {
case TYPE_SQLNULL:
return mapping.CreateNullValue(), nil
case TYPE_BOOLEAN:
return mapping.CreateBool(v.(bool)), nil
case TYPE_TINYINT:
return mapping.CreateInt8(v.(int8)), nil
case TYPE_SMALLINT:
return mapping.CreateInt16(v.(int16)), nil
case TYPE_INTEGER:
return mapping.CreateInt32(v.(int32)), nil
case TYPE_BIGINT:
return mapping.CreateInt64(v.(int64)), nil
case TYPE_UTINYINT:
return mapping.CreateUInt8(v.(uint8)), nil
case TYPE_USMALLINT:
return mapping.CreateUInt16(v.(uint16)), nil
case TYPE_UINTEGER:
return mapping.CreateUInt32(v.(uint32)), nil
case TYPE_UBIGINT:
return mapping.CreateUInt64(v.(uint64)), nil
case TYPE_FLOAT:
return mapping.CreateFloat(v.(float32)), nil
case TYPE_DOUBLE:
return mapping.CreateDouble(v.(float64)), nil
case TYPE_VARCHAR:
return mapping.CreateVarchar(v.(string)), nil
case TYPE_TIMESTAMP:
vv, err := inferTimestamp(t, v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateTimestamp(vv), nil
case TYPE_TIMESTAMP_TZ:
vv, err := inferTimestamp(t, v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateTimestampTZ(vv), nil
case TYPE_TIMESTAMP_S:
vv, err := inferTimestampS(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateTimestampS(vv), nil
case TYPE_TIMESTAMP_MS:
vv, err := inferTimestampMS(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateTimestampMS(vv), nil
case TYPE_TIMESTAMP_NS:
vv, err := inferTimestampNS(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateTimestampNS(vv), nil
case TYPE_DATE:
vv, err := inferDate(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateDate(vv), nil
case TYPE_TIME:
vv, err := inferTime(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateTime(vv), nil
case TYPE_TIME_TZ:
vv, err := inferTimeTZ(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateTimeTZValue(vv), nil
case TYPE_INTERVAL:
vv, err := inferInterval(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateInterval(vv), nil
case TYPE_HUGEINT:
vv, err := inferHugeInt(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateHugeInt(vv), nil
case TYPE_UHUGEINT:
vv, err := inferUHugeInt(v)
if err != nil {
return mapping.Value{}, err
}
return mapping.CreateUHugeInt(vv), nil
case TYPE_BIGNUM:
vv, err := inferBigNum(v)
if err != nil {
return mapping.Value{}, err
}
defer mapping.DestroyBigNum(&vv)
return mapping.CreateBigNum(vv), nil
case TYPE_UUID:
vv, err := inferUUID(v)
if err != nil {
return mapping.Value{}, err
}
lower, upper := mapping.HugeIntMembers(&vv)
uHugeInt := mapping.NewUHugeInt(lower, uint64(upper))
return mapping.CreateUUID(uHugeInt), nil
}
return mapping.Value{}, unsupportedTypeError(typeToStringMap[t])
}
func getPointerValue(v any) any {
for {
if v == nil {
return nil
}
vo := reflect.ValueOf(v)
if vo.Kind() == reflect.Ptr {
if vo.IsNil() {
return nil
}
v = vo.Elem().Interface()
continue
}
return v
}
}
func isNil(i any) bool {
if i == nil {
return true
}
value := reflect.ValueOf(i)
kind := value.Kind()
switch kind {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Slice:
return value.IsNil()
default:
return false
}
}
func inferLogicalTypeAndValue(v any) (mapping.LogicalType, mapping.Value, error) {
// Try to create a primitive type.
t, vv := inferPrimitiveType(v)
if isPrimitiveType(t) {
val, err := createPrimitiveValue(t, vv)
if err != nil {
return mapping.LogicalType{}, mapping.Value{}, err
}
return mapping.CreateLogicalType(t), val, err
}
if t == TYPE_MAP {
// TODO.
return mapping.LogicalType{}, mapping.Value{}, unsupportedTypeError(typeToStringMap[t])
}
if t == TYPE_UNION {
// TODO.
return mapping.LogicalType{}, mapping.Value{}, unsupportedTypeError(typeToStringMap[t])
}
// User-provided type with a Stringer interface:
// We create a string and return a VARCHAR value.
// TYPE_DECIMAL has a Stringer interface.
if ss, ok := v.(fmt.Stringer); ok {
t = TYPE_VARCHAR
val, err := createPrimitiveValue(t, ss.String())
if err != nil {
return mapping.LogicalType{}, mapping.Value{}, err
}
return mapping.CreateLogicalType(t), val, err
}
// SQLNULL type.
if isNil(v) {
t = TYPE_SQLNULL
val, err := createPrimitiveValue(t, v)
if err != nil {
return mapping.LogicalType{}, mapping.Value{}, err
}
return mapping.CreateLogicalType(t), val, err
}
// Complex types.
r := reflect.ValueOf(v)
switch r.Kind() {
case reflect.Struct, reflect.Map:
// TODO.
return mapping.LogicalType{}, mapping.Value{}, unsupportedTypeError(typeToStringMap[TYPE_STRUCT])
case reflect.Ptr:
// Extract pointer and recurse.
return inferLogicalTypeAndValue(getPointerValue(v))
case reflect.Array, reflect.Slice:
return inferSliceLogicalTypeAndValue(r.Interface(), r.Kind() == reflect.Array, r.Len())
default:
return mapping.LogicalType{}, mapping.Value{}, unsupportedTypeError(reflect.TypeOf(v).Name())
}
}
func inferPrimitiveType(v any) (Type, any) {
// Return TYPE_INVALID for TYPE_ENUM, TYPE_LIST, TYPE_STRUCT, TYPE_ARRAY,
// and for the unsupported types.
t := TYPE_INVALID
switch vv := v.(type) {
case nil:
t = TYPE_SQLNULL
case bool:
t = TYPE_BOOLEAN
case int8:
t = TYPE_TINYINT
case int16:
t = TYPE_SMALLINT
case int32:
t = TYPE_INTEGER
case int64:
t = TYPE_BIGINT
case int:
t = TYPE_BIGINT
v = int64(vv)
case uint8:
t = TYPE_UTINYINT
case uint16:
t = TYPE_USMALLINT
case uint32:
t = TYPE_UINTEGER
case uint64:
t = TYPE_UBIGINT
case uint:
t = TYPE_UBIGINT
v = uint64(vv)
case float32:
t = TYPE_FLOAT
case float64:
t = TYPE_DOUBLE
case string:
t = TYPE_VARCHAR
case []byte:
// No support for TYPE_BLOB.
t = TYPE_VARCHAR
v = string(vv)
case time.Time:
// Go's time.Time always carries timezone information (via Location),
// so TIMESTAMP WITH TIME ZONE is the correct semantic mapping.
t = TYPE_TIMESTAMP_TZ
case Interval:
t = TYPE_INTERVAL
case *big.Int:
t = TYPE_HUGEINT
case Decimal:
t = TYPE_DECIMAL
case UUID:
t = TYPE_UUID
case Map, OrderedMap:
// We special-case TYPE_MAP to disambiguate with structs passed as map[string]any.
t = TYPE_MAP
case Union:
t = TYPE_UNION
}
return t, v
}
func isPrimitiveType(t Type) bool {
switch t {
case TYPE_DECIMAL, TYPE_ENUM, TYPE_LIST, TYPE_STRUCT, TYPE_MAP, TYPE_ARRAY, TYPE_UNION:
// Complex type.
return false
case TYPE_INVALID, TYPE_BIT, TYPE_ANY:
// Invalid or unsupported.
return false
}
return true
}
func inferSliceLogicalTypeAndValue[T any](val T, array bool, length int) (mapping.LogicalType, mapping.Value, error) {
createFunc := mapping.CreateListValue
typeFunc := mapping.CreateListType
if array {
createFunc = mapping.CreateArrayValue
typeFunc = func(child mapping.LogicalType) mapping.LogicalType {
return mapping.CreateArrayType(child, mapping.IdxT(length))
}
}
slice, err := extractSlice(val)
if err != nil {
return mapping.LogicalType{}, mapping.Value{}, err
}
values := make([]mapping.Value, 0, length)
defer func() { destroyValueSlice(values) }()
if len(slice) == 0 {
lt := mapping.CreateLogicalType(TYPE_SQLNULL)
defer mapping.DestroyLogicalType(<)
return typeFunc(lt), createFunc(lt, values), nil
}
logicalTypes := make([]mapping.LogicalType, 0, length)
defer func() { destroyLogicalTypes(logicalTypes) }()
var elemLogicalType mapping.LogicalType
expectedIndex := -1
expectedTypeStr := ""
for i, v := range slice {
et, vv, errInfer := inferLogicalTypeAndValue(v)
if errInfer != nil {
return mapping.LogicalType{}, mapping.Value{}, errInfer
}
values = append(values, vv)
logicalTypes = append(logicalTypes, et)
if et.Ptr != nil {
if elemLogicalType.Ptr == nil {
elemLogicalType = et
expectedIndex = i
expectedTypeStr = logicalTypeString(et)
continue
}
// Check if this element's type matches the first non-null element's type
if currentTypeStr := logicalTypeString(et); currentTypeStr != expectedTypeStr {
return mapping.LogicalType{}, mapping.Value{},
fmt.Errorf("mixed types in slice: cannot bind %s (index %d) and %s (index %d)",
expectedTypeStr, expectedIndex, currentTypeStr, i)
}
}
}
if elemLogicalType.Ptr == nil {
return elemLogicalType, mapping.Value{}, unsupportedTypeError(reflect.TypeOf(val).Name())
}
return typeFunc(elemLogicalType), createFunc(elemLogicalType, values), nil
}
func createSliceValue[T any](lt mapping.LogicalType, t Type, val T) (mapping.Value, error) {
var childType mapping.LogicalType
switch t {
case TYPE_ARRAY:
childType = mapping.ArrayTypeChildType(lt)
case TYPE_LIST:
childType = mapping.ListTypeChildType(lt)
}
defer mapping.DestroyLogicalType(&childType)
slice, err := extractSlice(val)
if err != nil {
return mapping.Value{}, err
}
var values []mapping.Value
defer func() { destroyValueSlice(values) }()
for _, v := range slice {
vv, err := createValue(childType, v)
if err != nil {
return mapping.Value{}, err
}
values = append(values, vv)
}
var v mapping.Value
switch t {
case TYPE_ARRAY:
v = mapping.CreateArrayValue(childType, values)
case TYPE_LIST:
v = mapping.CreateListValue(childType, values)
}
return v, nil
}
func createStructValue(lt mapping.LogicalType, val any) (mapping.Value, error) {
m, ok := val.(map[string]any)
if !ok {
return mapping.Value{}, castError(reflect.TypeOf(val).Name(), reflectTypeMapString.Name())
}
var values []mapping.Value
defer func() { destroyValueSlice(values) }()
childCount := mapping.StructTypeChildCount(lt)
for i := range uint64(childCount) {
name := mapping.StructTypeChildName(lt, mapping.IdxT(i))
t := mapping.StructTypeChildType(lt, mapping.IdxT(i))
defer mapping.DestroyLogicalType(&t)
v, exists := m[name]
if exists {
vv, err := createValue(t, v)
if err != nil {
return mapping.Value{}, err
}
values = append(values, vv)
} else {
values = append(values, mapping.CreateNullValue())
}
}
return mapping.CreateStructValue(lt, values), nil
}
func createMapValue(lt mapping.LogicalType, val any) (mapping.Value, error) {
var m OrderedMap
switch v := val.(type) {
case OrderedMap:
m = v
case Map:
m = OrderedMap{}
for key, value := range v {
m.Set(key, value)
}
default:
return mapping.Value{}, castError(reflect.TypeOf(val).String(), reflectTypeMap.Name())
}
keyType := mapping.MapTypeKeyType(lt)
defer mapping.DestroyLogicalType(&keyType)
valueType := mapping.MapTypeValueType(lt)
defer mapping.DestroyLogicalType(&valueType)
keys := make([]mapping.Value, m.Len())
defer destroyValueSlice(keys)
for i, k := range m.Keys() {
kv, err := createValue(keyType, k)
if err != nil {
return mapping.Value{}, err
}
keys[i] = kv
}
values := make([]mapping.Value, m.Len())
defer destroyValueSlice(values)
for i, v := range m.Values() {
vv, err := createValue(valueType, v)
if err != nil {
return mapping.Value{}, err
}
values[i] = vv
}
return mapping.CreateMapValue(lt, keys, values), nil
}
func destroyValueSlice(values []mapping.Value) {
for _, v := range values {
mapping.DestroyValue(&v)
}
}
func canNil(val reflect.Value) bool {
switch val.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer,
reflect.UnsafePointer, reflect.Interface, reflect.Slice:
return true
default:
return false
}
}
func extractSlice[S any](val S) ([]any, error) {
var s []any
switch v := any(val).(type) {
case []any:
s = v
default:
kind := reflect.TypeOf(val).Kind()
if kind != reflect.Array && kind != reflect.Slice {
return nil, castError(reflect.TypeOf(val).String(), reflectTypeSliceAny.String())
}
// Insert the values into the slice.
rv := reflect.ValueOf(val)
s = make([]any, rv.Len())
for i := range rv.Len() {
idx := rv.Index(i)
if canNil(idx) && idx.IsNil() {
s[i] = nil
continue
}
s[i] = idx.Interface()
}
}
return s, nil
}