Repository navigation
Expand file tree
/
Copy pathvariant.go
More file actions
1835 lines (1588 loc) · 48.5 KB
/
Copy pathvariant.go
File metadata and controls
1835 lines (1588 loc) · 48.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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package extensions
import (
"bytes"
"errors"
"fmt"
"math"
"reflect"
"strings"
"sync"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/decimal"
"github.com/apache/arrow-go/v18/arrow/decimal128"
"github.com/apache/arrow-go/v18/arrow/internal/debug"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/internal/json"
"github.com/apache/arrow-go/v18/parquet/schema"
"github.com/apache/arrow-go/v18/parquet/variant"
"github.com/google/uuid"
)
// VariantType is the arrow extension type for representing Variant values as
// defined by the Parquet Variant specification for encoding and shredding values.
// The underlying storage must be a struct type with a minimum of two fields
// ("metadata" and "value") and an optional third field ("typed_value").
//
// See the documentation for [NewVariantType] for the rules for creating a variant
// type.
type VariantType struct {
arrow.ExtensionBase
metadataFieldIdx int
valueFieldIdx int
typedValueFieldIdx int
}
// NewDefaultVariantType creates a basic, non-shredded variant type. The underlying
// storage type will be struct<metadata: binary non-null, value: binary non-null>.
func NewDefaultVariantType() *VariantType {
s := arrow.StructOf(
arrow.Field{Name: "metadata", Type: arrow.BinaryTypes.Binary, Nullable: false},
arrow.Field{Name: "value", Type: arrow.BinaryTypes.Binary, Nullable: false})
vt, _ := NewVariantType(s)
return vt
}
func createShreddedField(dt arrow.DataType) arrow.DataType {
switch t := dt.(type) {
case arrow.ListLikeType:
return arrow.ListOfNonNullable(arrow.StructOf(
arrow.Field{Name: "value", Type: arrow.BinaryTypes.Binary, Nullable: true},
arrow.Field{Name: "typed_value", Type: createShreddedField(t.Elem()), Nullable: true},
))
case *arrow.StructType:
fields := make([]arrow.Field, 0, t.NumFields())
for i := range t.NumFields() {
f := t.Field(i)
fields = append(fields, arrow.Field{
Name: f.Name,
Type: arrow.StructOf(arrow.Field{
Name: "value",
Type: arrow.BinaryTypes.Binary,
Nullable: true,
}, arrow.Field{
Name: "typed_value",
Type: createShreddedField(f.Type),
Nullable: true,
}),
Nullable: false,
Metadata: f.Metadata,
})
}
return arrow.StructOf(fields...)
default:
return dt
}
}
// NewShreddedVariantType creates a new VariantType extension type using the provided
// type to define a shredded schema by setting the `typed_value` field accordingly and
// properly constructing the shredded fields for structs, lists and so on.
//
// For example:
//
// NewShreddedVariantType(arrow.StructOf(
// arrow.Field{Name: "latitude", Type: arrow.PrimitiveTypes.Float64},
// arrow.Field{Name: "longitude", Type: arrow.PrimitiveTypes.Float32}))
//
// Will create a variant type with the following structure:
//
// arrow.StructOf(
// arrow.Field{Name: "metadata", Type: arrow.BinaryTypes.Binary, Nullable: false},
// arrow.Field{Name: "value", Type: arrow.BinaryTypes.Binary, Nullable: true},
// arrow.Field{Name: "typed_value", Type: arrow.StructOf(
// arrow.Field{Name: "latitude", Type: arrow.StructOf(
// arrow.Field{Name: "value", Type: arrow.BinaryTypes.Binary, Nullable: true},
// arrow.Field{Name: "typed_value", Type: arrow.PrimitiveTypes.Float64, Nullable: true}),
// Nullable: false},
// arrow.Field{Name: "longitude", Type: arrow.StructOf(
// arrow.Field{Name: "value", Type: arrow.BinaryTypes.Binary, Nullable: true},
// arrow.Field{Name: "typed_value", Type: arrow.PrimitiveTypes.Float32, Nullable: true}),
// Nullable: false},
// ), Nullable: true})
//
// This is intended to be a convenient way to create a shredded variant type from a definition
// of the fields to shred. If the provided data type is nil or Null (including an
// extension whose storage is Null), it will create a default variant type.
func NewShreddedVariantType(dt arrow.DataType) *VariantType {
if dt == nil || isNullType(dt) {
return NewDefaultVariantType()
}
vt, _ := NewVariantType(arrow.StructOf(
arrow.Field{Name: "metadata", Type: arrow.BinaryTypes.Binary, Nullable: false},
arrow.Field{Name: "value", Type: arrow.BinaryTypes.Binary, Nullable: true},
arrow.Field{
Name: "typed_value",
Type: createShreddedField(dt),
Nullable: true,
}))
return vt
}
// NewVariantType creates a new variant type based on the provided storage type.
//
// The rules for a variant storage type are:
// 1. MUST be a struct
// 2. MUST have non-nullable field named "metadata" that is binary/largebinary/binary_view
// 3. Must satisfy exactly one of the following:
// a. MUST have non-nullable field named "value" that is binary/largebinary/binary_view
// b. MUST have an nullable field named "value" that is binary/largebinary/binary_view
// and another nullable field named "typed_value" that is either a primitive type or
// a list/large_list/list_view or struct which also satisfies the following requirements:
// i. The elements must be NON-NULLABLE
// ii. There must either be a single NON-NULLABLE field named "value" which is
// binary/largebinary/binary_view or have an nullable "value" field and an nullable
// "typed_value" field that follows the rules laid out in (b).
//
// The metadata field may also be dictionary encoded
func NewVariantType(storage arrow.DataType) (*VariantType, error) {
s, ok := storage.(*arrow.StructType)
if !ok {
return nil, fmt.Errorf("%w: bad storage type %s for variant type", arrow.ErrInvalid, storage)
}
var (
metadataFieldIdx = -1
valueFieldIdx = -1
typedValueFieldIdx = -1
)
if metadataFieldIdx, ok = s.FieldIdx("metadata"); !ok {
return nil, fmt.Errorf("%w: missing non-nullable field 'metadata' in variant storage type %s", arrow.ErrInvalid, storage)
}
var valueOk, typedValueOk bool
valueFieldIdx, valueOk = s.FieldIdx("value")
typedValueFieldIdx, typedValueOk = s.FieldIdx("typed_value")
if !valueOk && !typedValueOk {
return nil, fmt.Errorf("%w: there must be at least one of 'value' or 'typed_value' fields in variant storage type %s", arrow.ErrInvalid, storage)
}
if s.NumFields() == 3 && (!valueOk || !typedValueOk) {
return nil, fmt.Errorf("%w: has 3 fields, but missing one of 'value' or 'typed_value' fields, %s", arrow.ErrInvalid, storage)
}
if s.NumFields() > 3 {
return nil, fmt.Errorf("%w: too many fields in variant storage type %s, expected 2 or 3", arrow.ErrInvalid, storage)
}
mdField := s.Field(metadataFieldIdx)
if mdField.Nullable {
return nil, fmt.Errorf("%w: metadata field must be non-nullable binary type, got %s", arrow.ErrInvalid, mdField.Type)
}
if !isBinary(mdField.Type) {
if mdField.Type.ID() != arrow.DICTIONARY || !isBinary(mdField.Type.(*arrow.DictionaryType).ValueType) {
return nil, fmt.Errorf("%w: metadata field must be non-nullable binary type, got %s", arrow.ErrInvalid, mdField.Type)
}
}
if valueOk {
valField := s.Field(valueFieldIdx)
if !isBinary(valField.Type) {
return nil, fmt.Errorf("%w: value field must be binary type, got %s", arrow.ErrInvalid, valField.Type)
}
}
if !typedValueOk {
return &VariantType{
ExtensionBase: arrow.ExtensionBase{Storage: storage},
metadataFieldIdx: metadataFieldIdx,
valueFieldIdx: valueFieldIdx,
typedValueFieldIdx: -1,
}, nil
}
typedValueField := s.Field(typedValueFieldIdx)
if !typedValueField.Nullable {
return nil, fmt.Errorf("%w: typed_value field must be nullable, got %s", arrow.ErrInvalid, typedValueField.Type)
}
dt := storageType(typedValueField.Type)
if dt == nil {
return nil, fmt.Errorf("%w: typed_value field has invalid storage type", arrow.ErrInvalid)
}
if dt.ID() == arrow.NULL {
return nil, fmt.Errorf("%w: typed_value field must not be null type", arrow.ErrInvalid)
}
if nt, ok := dt.(arrow.NestedType); ok {
if !validNestedType(nt) {
return nil, fmt.Errorf("%w: typed_value field must be a valid nested type, got %s", arrow.ErrInvalid, typedValueField.Type)
}
}
return &VariantType{
ExtensionBase: arrow.ExtensionBase{Storage: storage},
metadataFieldIdx: metadataFieldIdx,
valueFieldIdx: valueFieldIdx,
typedValueFieldIdx: typedValueFieldIdx,
}, nil
}
func (*VariantType) ArrayType() reflect.Type {
return reflect.TypeOf(VariantArray{})
}
func (v *VariantType) Metadata() arrow.Field {
return v.StorageType().(*arrow.StructType).Field(v.metadataFieldIdx)
}
func (v *VariantType) Value() arrow.Field {
if v.valueFieldIdx == -1 {
return arrow.Field{}
}
return v.StorageType().(*arrow.StructType).Field(v.valueFieldIdx)
}
func (v *VariantType) TypedValue() arrow.Field {
if v.typedValueFieldIdx == -1 {
return arrow.Field{}
}
return v.StorageType().(*arrow.StructType).Field(v.typedValueFieldIdx)
}
const (
// VariantExtensionName is the canonical Arrow extension type name.
// See https://arrow.apache.org/docs/format/CanonicalExtensions.html#parquet-variant
VariantExtensionName = "arrow.parquet.variant"
// LegacyVariantExtensionName was used by arrow-go before the canonical
// name landed. It is still accepted when reading IPC so older data
// continues to deserialize as VariantType.
LegacyVariantExtensionName = "parquet.variant"
)
// IsVariantExtensionName reports whether name is the canonical or historical
// Variant extension type name.
func IsVariantExtensionName(name string) bool {
return name == VariantExtensionName || name == LegacyVariantExtensionName
}
func (*VariantType) ExtensionName() string { return VariantExtensionName }
func (v *VariantType) String() string {
return fmt.Sprintf("extension<%s>", v.ExtensionName())
}
func variantExtensionEquals(storage arrow.DataType, other arrow.ExtensionType) bool {
return IsVariantExtensionName(other.ExtensionName()) &&
arrow.TypeEqual(storage, other.StorageType())
}
func (v *VariantType) ExtensionEquals(other arrow.ExtensionType) bool {
return variantExtensionEquals(v.Storage, other)
}
func asVariantType(dt arrow.ExtensionType) *VariantType {
if vt, ok := dt.(*VariantType); ok {
return vt
}
vt, err := NewVariantType(dt.StorageType())
if err != nil {
panic(err)
}
return vt
}
func (*VariantType) Serialize() string { return "" }
func (*VariantType) Deserialize(storageType arrow.DataType, _ string) (arrow.ExtensionType, error) {
return NewVariantType(storageType)
}
func (*VariantType) ParquetLogicalType() schema.LogicalType {
return schema.VariantLogicalType{}
}
func (v *VariantType) NewBuilder(mem memory.Allocator) array.Builder {
return NewVariantBuilder(mem, v)
}
func isBinary(dt arrow.DataType) bool {
return dt.ID() == arrow.BINARY || dt.ID() == arrow.LARGE_BINARY ||
dt.ID() == arrow.BINARY_VIEW
}
func storageType(dt arrow.DataType) arrow.DataType {
seen := make(map[arrow.DataType]struct{})
for dt != nil {
ext, ok := dt.(arrow.ExtensionType)
if !ok {
return dt
}
if _, dup := seen[dt]; dup {
return nil
}
seen[dt] = struct{}{}
dt = ext.StorageType()
}
return nil
}
func isNullType(dt arrow.DataType) bool {
st := storageType(dt)
return st == nil || st.ID() == arrow.NULL
}
func validStruct(s *arrow.StructType) bool {
switch s.NumFields() {
case 1:
f := s.Field(0)
if f.Name == "value" {
return isBinary(f.Type)
}
return f.Name == "typed_value" && !isNullType(f.Type)
case 2:
valField, ok := s.FieldByName("value")
if !ok || !valField.Nullable || !isBinary(valField.Type) {
return false
}
typedField, ok := s.FieldByName("typed_value")
if !ok || !typedField.Nullable {
return false
}
if nt, ok := typedField.Type.(arrow.NestedType); ok && nt.Name() != "extension" {
return validNestedType(nt)
}
return !isNullType(typedField.Type)
default:
return false
}
}
func validNestedType(dt arrow.NestedType) bool {
switch t := dt.(type) {
case arrow.ListLikeType:
if t.ElemField().Nullable {
return false
}
s, ok := t.Elem().(*arrow.StructType)
if !ok {
return false
}
return validStruct(s)
case *arrow.StructType:
if t.NumFields() == 0 {
return false
}
for i := range t.NumFields() {
f := t.Field(i)
if f.Nullable {
return false
}
s, ok := f.Type.(*arrow.StructType)
if !ok {
return false
}
if !validStruct(s) {
return false
}
}
return true
default:
return false
}
}
// VariantArray is an extension Array type containing Variant values which may
// potentially be shredded into multiple fields.
type VariantArray struct {
array.ExtensionArrayBase
rdr variantReader
rdrErr error
initRdr sync.Once
}
func (v *VariantArray) initReader() {
// initialize a reader that coalesces shredded fields back into a variant
// or just returns the basic variants if the array is not shredded.
v.initRdr.Do(func() {
vt := asVariantType(v.ExtensionType())
st := v.Storage().(*array.Struct)
metaField := st.Field(vt.metadataFieldIdx)
metadata, ok := metaField.(arrow.TypedArray[[]byte])
if !ok {
// we already validated that if the metadata field isn't a binary
// type directly, it must be a dictionary with a binary value type.
metadata, _ = array.NewDictWrapper[[]byte](metaField.(*array.Dictionary))
}
var value arrow.TypedArray[[]byte]
if vt.valueFieldIdx != -1 {
valueField := st.Field(vt.valueFieldIdx)
value = valueField.(arrow.TypedArray[[]byte])
}
var ivreader typedValReader
var err error
if vt.typedValueFieldIdx != -1 {
ivreader, err = getReader(st.Field(vt.typedValueFieldIdx))
if err != nil {
v.rdrErr = err
return
}
v.rdr = &shreddedVariantReader{
metadata: metadata,
value: value,
typedValue: ivreader,
}
} else {
v.rdr = &basicVariantReader{
metadata: metadata,
value: value,
}
}
})
}
// Metadata returns the metadata column of the variant array, containing the
// metadata for each variant value.
func (v *VariantArray) Metadata() arrow.TypedArray[[]byte] {
vt := asVariantType(v.ExtensionType())
return v.Storage().(*array.Struct).Field(vt.metadataFieldIdx).(arrow.TypedArray[[]byte])
}
// UntypedValues returns the untyped variant values for each element of the array,
// if the array is not shredded this will contain the variant bytes for each value.
// If the array is shredded, this will contain any variant values that are either
// partially shredded objects or are not shredded at all (e.g. a value that doesn't
// match the types of the shredding).
//
// The shredded array and the untyped values array together are used to encode a
// single value. If this is not encoding shredded object fields, then a given index
// will never be null in both arrays. (A null value will be an encoded null variant value
// in this array with a null in the shredded array).
//
// If both arrays are null for a given index (only valid for shredded object fields),
// it means that the value is missing entirely (as opposed to existing and having a
// value of null).
func (v *VariantArray) UntypedValues() arrow.TypedArray[[]byte] {
vt := asVariantType(v.ExtensionType())
if vt.valueFieldIdx == -1 {
return nil
}
return v.Storage().(*array.Struct).Field(vt.valueFieldIdx).(arrow.TypedArray[[]byte])
}
// Shredded returns the typed array for the shredded values of the variant array,
// following the rules of the Parquet Variant specification. As such, this array will
// always be either a struct, a list, or a primitive array.
//
// The reason for exposing this is to allow users to quickly access one of the shredded
// fields without having to decode the entire variant value.
func (v *VariantArray) Shredded() arrow.Array {
vt := asVariantType(v.ExtensionType())
if vt.typedValueFieldIdx == -1 {
return nil
}
return v.Storage().(*array.Struct).Field(vt.typedValueFieldIdx)
}
// IsShredded returns true if the variant has shredded columns.
func (v *VariantArray) IsShredded() bool {
return asVariantType(v.ExtensionType()).typedValueFieldIdx != -1
}
// VariantType returns the array's extension type without the ExtensionType cast.
func (v *VariantArray) VariantType() *VariantType {
return v.ExtensionType().(*VariantType)
}
// UnshredVariant returns an equivalent VariantArray in the non-shredded layout
// (a struct of metadata and value), reassembling each row's value from the
// shredded typed_value and value columns. If the array is already non-shredded
// it is returned unchanged with an added reference so callers can Release it the
// same way.
//
// A physically null row becomes null. A present row that holds an encoded variant
// null (the 0x00 value) stays present.
func UnshredVariant(arr *VariantArray, mem memory.Allocator) (*VariantArray, error) {
if !arr.IsShredded() {
arr.Retain()
return arr, nil
}
// Rebuild through the default-type builder rather than reusing the input's
// metadata column: that column may be dictionary- or large-binary-encoded,
// while the non-shredded layout requires plain binary metadata.
bldr := NewVariantBuilder(mem, NewDefaultVariantType())
defer bldr.Release()
bldr.Reserve(arr.Len())
storage := arr.Storage()
for i := 0; i < arr.Len(); i++ {
if storage.IsNull(i) {
bldr.AppendNull()
continue
}
val, err := arr.Value(i)
if err != nil {
return nil, fmt.Errorf("variant: reassembling shredded row %d: %w", i, err)
}
bldr.Append(val)
}
return bldr.NewArray().(*VariantArray), nil
}
// IsNull will also take into account the special case where there is an
// encoded null variant in the untyped values array for this index and return
// appropriately.
func (v *VariantArray) IsNull(i int) bool {
if v.Storage().IsNull(i) {
return true
}
vt := asVariantType(v.ExtensionType())
if vt.typedValueFieldIdx != -1 {
typedArr := v.Storage().(*array.Struct).Field(vt.typedValueFieldIdx)
if !typedArr.IsNull(i) {
return false
}
}
if vt.valueFieldIdx == -1 {
// No residual value column: a null typed_value means the value is missing.
return true
}
valArr := v.Storage().(*array.Struct).Field(vt.valueFieldIdx)
b := valArr.(arrow.TypedArray[[]byte]).Value(i)
return len(b) == 1 && b[0] == 0 // variant null
}
func (v *VariantArray) IsValid(i int) bool {
return !v.IsNull(i)
}
func (v *VariantArray) String() string {
o := new(strings.Builder)
o.WriteString("VariantArray[")
for i := 0; i < v.Len(); i++ {
if i > 0 {
o.WriteString(" ")
}
if v.IsNull(i) {
o.WriteString(array.NullValueStr)
continue
}
val, err := v.Value(i)
if err != nil {
fmt.Fprintf(o, "error: %v", err)
continue
}
o.WriteString(val.String())
}
o.WriteString("]")
return o.String()
}
func (v *VariantArray) Value(i int) (variant.Value, error) {
v.initReader()
if v.rdrErr != nil {
return variant.Value{}, v.rdrErr
}
return v.rdr.Value(i)
}
func (v *VariantArray) Values() ([]variant.Value, error) {
values := make([]variant.Value, v.Len())
for i := range v.Len() {
val, err := v.Value(i)
if err != nil {
return nil, fmt.Errorf("error getting value at index %d: %w", i, err)
}
values[i] = val
}
return values, nil
}
func (v *VariantArray) ValueStr(i int) string {
if v.IsNull(i) {
return array.NullValueStr
}
val, err := v.Value(i)
if err != nil {
return fmt.Sprintf("error: %v", err)
}
return val.String()
}
func (v *VariantArray) MarshalJSON() ([]byte, error) {
values := make([]any, v.Len())
for i := range v.Len() {
if v.IsNull(i) {
values[i] = nil
continue
}
val, err := v.Value(i)
if err != nil {
values[i] = fmt.Sprintf("error: %v", err)
continue
}
values[i] = val.Value()
}
return json.Marshal(values)
}
func (v *VariantArray) GetOneForMarshal(i int) any {
if v.IsNull(i) {
return nil
}
val, err := v.Value(i)
if err != nil {
return fmt.Sprintf("error: %v", err)
}
return val.Value()
}
func (v *VariantArray) ValueAsAny(i int) any {
if v.IsNull(i) {
return nil
}
val, err := v.Value(i)
if err != nil {
return err
}
return val.Value()
}
type variantReader interface {
IsNull(i int) bool
Value(i int) (variant.Value, error)
}
type basicVariantReader struct {
metadata arrow.TypedArray[[]byte]
value arrow.TypedArray[[]byte]
}
func (r *basicVariantReader) IsNull(i int) bool {
if r.value.IsNull(i) {
return true
}
// special case for null variant
val := r.value.Value(i)
return len(val) == 1 && val[0] == 0
}
func (r *basicVariantReader) Value(i int) (variant.Value, error) {
if r.IsNull(i) {
return variant.NullValue, nil
}
meta := r.metadata.Value(i)
val := r.value.Value(i)
return variant.New(meta, val)
}
func createPrimitiveVariantReader(arr arrow.Array) (typedValReader, error) {
switch a := arr.(type) {
case *array.Boolean:
return asVariantReader[bool]{typedVal: a}, nil
case *array.Int8:
return asVariantReader[int8]{typedVal: a}, nil
case *array.Uint8:
return asVariantReader[uint8]{typedVal: a}, nil
case *array.Int16:
return asVariantReader[int16]{typedVal: a}, nil
case *array.Uint16:
return asVariantReader[uint16]{typedVal: a}, nil
case *array.Int32:
return asVariantReader[int32]{typedVal: a}, nil
case *array.Uint32:
return asVariantReader[uint32]{typedVal: a}, nil
case *array.Int64:
return asVariantReader[int64]{typedVal: a}, nil
case *array.Float32:
return asVariantReader[float32]{typedVal: a}, nil
case *array.Float64:
return asVariantReader[float64]{typedVal: a}, nil
case array.StringLike:
return asVariantReader[string]{typedVal: a}, nil
case arrow.TypedArray[[]byte]:
return asVariantReader[[]byte]{typedVal: a}, nil
case *array.Date32:
return asVariantReader[arrow.Date32]{typedVal: a}, nil
case *array.Time64:
if a.DataType().(*arrow.Time64Type).Unit != arrow.Microsecond {
return nil, fmt.Errorf("%w: unsupported time64 unit %s for variant",
arrow.ErrInvalid, a.DataType().(*arrow.Time64Type).Unit)
}
return asVariantReader[arrow.Time64]{typedVal: a}, nil
case *array.Timestamp:
var opt variant.AppendOpt
dt := a.DataType().(*arrow.TimestampType)
switch dt.Unit {
case arrow.Microsecond:
case arrow.Nanosecond:
opt |= variant.OptTimestampNano
default:
return nil, fmt.Errorf("%w: unsupported timestamp unit %s for variant",
arrow.ErrInvalid, a.DataType().(*arrow.TimestampType).Unit)
}
if dt.TimeZone != "" {
opt |= variant.OptTimestampUTC
}
return asVariantReader[arrow.Timestamp]{typedVal: a, opts: opt}, nil
case *UUIDArray:
return asVariantReader[uuid.UUID]{typedVal: a}, nil
case *array.Decimal32:
return asVariantReader[variant.DecimalValue[decimal.Decimal32]]{
typedVal: decimal32Wrapper{
Decimal32: a,
scale: uint8(a.DataType().(*arrow.Decimal32Type).Scale),
},
}, nil
case *array.Decimal64:
return asVariantReader[variant.DecimalValue[decimal.Decimal64]]{
typedVal: decimal64Wrapper{
Decimal64: a,
scale: uint8(a.DataType().(*arrow.Decimal64Type).Scale),
},
}, nil
case *array.Decimal128:
return asVariantReader[variant.DecimalValue[decimal.Decimal128]]{
typedVal: decimal128Wrapper{
Decimal128: a,
scale: uint8(a.DataType().(*arrow.Decimal128Type).Scale),
},
}, nil
}
return nil, fmt.Errorf("%w: unsupported primitive type %s for variant",
arrow.ErrInvalid, arr.DataType().String())
}
type decimal32Wrapper struct {
*array.Decimal32
scale uint8
}
func (d decimal32Wrapper) Value(i int) variant.DecimalValue[decimal.Decimal32] {
return variant.DecimalValue[decimal.Decimal32]{
Value: d.Decimal32.Value(i),
Scale: d.scale,
}
}
type decimal64Wrapper struct {
*array.Decimal64
scale uint8
}
func (d decimal64Wrapper) Value(i int) variant.DecimalValue[decimal.Decimal64] {
return variant.DecimalValue[decimal.Decimal64]{
Value: d.Decimal64.Value(i),
Scale: d.scale,
}
}
type decimal128Wrapper struct {
*array.Decimal128
scale uint8
}
func (d decimal128Wrapper) Value(i int) variant.DecimalValue[decimal.Decimal128] {
return variant.DecimalValue[decimal.Decimal128]{
Value: d.Decimal128.Value(i),
Scale: d.scale,
}
}
type arrowVariantPrimitiveType interface {
arrow.NumericType | bool | string | []byte | uuid.UUID |
variant.DecimalValue[decimal.Decimal32] |
variant.DecimalValue[decimal.Decimal64] |
variant.DecimalValue[decimal.Decimal128]
}
type typedArr[T arrowVariantPrimitiveType] interface {
arrow.Array
Value(int) T
}
type asVariantReader[T arrowVariantPrimitiveType] struct {
typedVal typedArr[T]
opts variant.AppendOpt
}
func (vr asVariantReader[T]) IsNull(i int) bool {
return vr.typedVal.IsNull(i)
}
func (vr asVariantReader[T]) Value(_ variant.Metadata, i int) (any, error) {
if vr.typedVal.IsNull(i) {
return nil, nil
}
return variant.Encode(vr.typedVal.Value(i), vr.opts)
}
func getReader(typedArr arrow.Array) (typedValReader, error) {
switch arr := typedArr.(type) {
case *array.Struct:
fieldReaders := make(map[string]fieldReaderPair)
fieldList := arr.DataType().(*arrow.StructType).Fields()
for i := range arr.NumField() {
child := arr.Field(i).(*array.Struct)
childType := child.DataType().(*arrow.StructType)
valueIdx, _ := childType.FieldIdx("value")
var valueArr arrow.TypedArray[[]byte]
if valueIdx != -1 {
valueArr = child.Field(valueIdx).(arrow.TypedArray[[]byte])
}
typedValueIdx, exists := childType.FieldIdx("typed_value")
if !exists {
fieldReaders[fieldList[i].Name] = fieldReaderPair{
values: valueArr,
typedVal: nil,
}
continue
}
typedRdr, err := getReader(child.Field(typedValueIdx))
if err != nil {
return nil, fmt.Errorf("error getting typed value reader for field %s: %w", fieldList[i].Name, err)
}
fieldReaders[fieldList[i].Name] = fieldReaderPair{
values: valueArr,
typedVal: typedRdr,
}
}
return &typedObjReader{
objArr: arr,
fieldRdrs: fieldReaders,
}, nil
case array.ListLike:
listValues := arr.ListValues().(*array.Struct)
elemType := listValues.DataType().(*arrow.StructType)
var valueArr arrow.TypedArray[[]byte]
var typedRdr typedValReader
valueIdx, _ := elemType.FieldIdx("value")
if valueIdx != -1 {
valueArr = listValues.Field(valueIdx).(arrow.TypedArray[[]byte])
}
typedValueIdx, _ := elemType.FieldIdx("typed_value")
if typedValueIdx != -1 {
var err error
typedRdr, err = getReader(listValues.Field(typedValueIdx))
if err != nil {
return nil, fmt.Errorf("error getting typed value reader: %w", err)
}
}
return &typedListReader{
listArr: arr,
valueArr: valueArr,
typedVal: typedRdr,
}, nil
default:
return createPrimitiveVariantReader(arr)
}
}
type typedPair struct {
Value []byte
TypedValue any
}
func constructVariant(b *variant.Builder, meta variant.Metadata, value []byte, typedVal any) error {
switch v := typedVal.(type) {
case nil:
if len(value) == 0 {
b.AppendNull()
return nil
}
return b.UnsafeAppendEncoded(value)
case map[string]typedPair:
fields := make([]variant.FieldEntry, 0, len(v))
objstart := b.Offset()
for k, pair := range v {
if pair.TypedValue != nil || len(pair.Value) != 0 {
fields = append(fields, b.NextField(objstart, k))
if err := constructVariant(b, meta, pair.Value, pair.TypedValue); err != nil {
return err
}
}
}
if len(value) > 0 {
obj, err := variant.NewWithMetadata(meta, value)
if err != nil {
return err
}
objval, ok := obj.Value().(variant.ObjectValue)
if !ok {
return fmt.Errorf("%w: expected object value, got %T", arrow.ErrInvalid, obj.Value())
}
for key, field := range objval.Values() {
fields = append(fields, b.NextField(objstart, key))
if err := b.UnsafeAppendEncoded(field.Bytes()); err != nil {
return fmt.Errorf("error appending field %s: %w", key, err)
}
}
}
return b.FinishObject(objstart, fields)
case []typedPair:
debug.Assert(len(value) == 0, "shredded array must not conflict with variant value")
elems := make([]int, 0, len(v))
arrstart := b.Offset()
for _, pair := range v {
elems = append(elems, b.NextElement(arrstart))
if err := constructVariant(b, meta, pair.Value, pair.TypedValue); err != nil {
return err
}