-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy patharrow_utils.go
More file actions
1643 lines (1347 loc) · 46.7 KB
/
arrow_utils.go
File metadata and controls
1643 lines (1347 loc) · 46.7 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 table
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"iter"
"slices"
"strconv"
"strings"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/bitutil"
"github.com/apache/arrow-go/v18/arrow/compute"
"github.com/apache/arrow-go/v18/arrow/decimal128"
"github.com/apache/arrow-go/v18/arrow/extensions"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/arrow/scalar"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/config"
"github.com/apache/iceberg-go/internal"
iceio "github.com/apache/iceberg-go/io"
tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/google/uuid"
"github.com/pterm/pterm"
"golang.org/x/sync/errgroup"
)
// constants to look for as Keys in Arrow field metadata
const (
ArrowFieldDocKey = "doc"
// Arrow schemas that are generated from the Parquet library will utilize
// this key to identify the field id of the source Parquet field.
// We use this when converting to Iceberg to provide field IDs
ArrowParquetFieldIDKey = "PARQUET:field_id"
defaultBinPackLookback = 20
)
// ArrowSchemaVisitor is an interface that can be implemented and used to
// call VisitArrowSchema for iterating
type ArrowSchemaVisitor[T any] interface {
Schema(*arrow.Schema, T) T
Struct(*arrow.StructType, []T) T
Field(arrow.Field, T) T
List(arrow.ListLikeType, T) T
Map(mt *arrow.MapType, keyResult T, valueResult T) T
Primitive(arrow.DataType) T
}
func VisitArrowSchema[T any](sc *arrow.Schema, visitor ArrowSchemaVisitor[T]) (res T, err error) {
if sc == nil {
err = fmt.Errorf("%w: cannot visit nil arrow schema", iceberg.ErrInvalidArgument)
return res, err
}
defer internal.RecoverError(&err)
return visitor.Schema(sc, visitArrowStruct(arrow.StructOf(sc.Fields()...), visitor)), err
}
func visitArrowField[T any](f arrow.Field, visitor ArrowSchemaVisitor[T]) T {
switch typ := f.Type.(type) {
case *arrow.StructType:
return visitArrowStruct(typ, visitor)
case *arrow.MapType:
return visitArrowMap(typ, visitor)
case arrow.ListLikeType:
return visitArrowList(typ, visitor)
default:
return visitor.Primitive(typ)
}
}
func visitArrowStruct[T any](dt *arrow.StructType, visitor ArrowSchemaVisitor[T]) T {
type (
beforeField interface {
BeforeField(arrow.Field)
}
afterField interface {
AfterField(arrow.Field)
}
)
results := make([]T, dt.NumFields())
bf, _ := visitor.(beforeField)
af, _ := visitor.(afterField)
for i, f := range dt.Fields() {
if bf != nil {
bf.BeforeField(f)
}
res := visitArrowField(f, visitor)
if af != nil {
af.AfterField(f)
}
results[i] = visitor.Field(f, res)
}
return visitor.Struct(dt, results)
}
func visitArrowMap[T any](dt *arrow.MapType, visitor ArrowSchemaVisitor[T]) T {
type (
beforeMapKey interface {
BeforeMapKey(arrow.Field)
}
beforeMapValue interface {
BeforeMapValue(arrow.Field)
}
afterMapKey interface {
AfterMapKey(arrow.Field)
}
afterMapValue interface {
AfterMapValue(arrow.Field)
}
)
key, val := dt.KeyField(), dt.ItemField()
if bmk, ok := visitor.(beforeMapKey); ok {
bmk.BeforeMapKey(key)
}
keyResult := visitArrowField(key, visitor)
if amk, ok := visitor.(afterMapKey); ok {
amk.AfterMapKey(key)
}
if bmv, ok := visitor.(beforeMapValue); ok {
bmv.BeforeMapValue(val)
}
valueResult := visitArrowField(val, visitor)
if amv, ok := visitor.(afterMapValue); ok {
amv.AfterMapValue(val)
}
return visitor.Map(dt, keyResult, valueResult)
}
func visitArrowList[T any](dt arrow.ListLikeType, visitor ArrowSchemaVisitor[T]) T {
type (
beforeListElem interface {
BeforeListElement(arrow.Field)
}
afterListElem interface {
AfterListElement(arrow.Field)
}
)
elemField := dt.ElemField()
if bl, ok := visitor.(beforeListElem); ok {
bl.BeforeListElement(elemField)
}
res := visitArrowField(elemField, visitor)
if al, ok := visitor.(afterListElem); ok {
al.AfterListElement(elemField)
}
return visitor.List(dt, res)
}
func getFieldID(f arrow.Field) *int {
if !f.HasMetadata() {
return nil
}
fieldIDStr, ok := f.Metadata.GetValue(ArrowParquetFieldIDKey)
if !ok {
return nil
}
id, err := strconv.Atoi(fieldIDStr)
if err != nil {
return nil
}
if id > 0 {
return &id
}
return nil
}
type hasIDs struct{}
func (hasIDs) Schema(sc *arrow.Schema, result bool) bool {
return result
}
func (hasIDs) Struct(st *arrow.StructType, results []bool) bool {
return !slices.Contains(results, false)
}
func (hasIDs) Field(f arrow.Field, result bool) bool {
return getFieldID(f) != nil
}
func (hasIDs) List(dt arrow.ListLikeType, elem bool) bool {
elemField := dt.ElemField()
return elem && getFieldID(elemField) != nil
}
func (hasIDs) Map(m *arrow.MapType, key, val bool) bool {
return key && val &&
getFieldID(m.KeyField()) != nil && getFieldID(m.ItemField()) != nil
}
func (hasIDs) Primitive(arrow.DataType) bool { return true }
type convertToIceberg struct {
downcastTimestamp bool
fieldID func(arrow.Field) int
}
func (convertToIceberg) Schema(_ *arrow.Schema, result iceberg.NestedField) iceberg.NestedField {
return result
}
func (convertToIceberg) Struct(_ *arrow.StructType, results []iceberg.NestedField) iceberg.NestedField {
return iceberg.NestedField{
Type: &iceberg.StructType{FieldList: results},
}
}
func (c convertToIceberg) Field(field arrow.Field, result iceberg.NestedField) iceberg.NestedField {
result.ID = c.fieldID(field)
if field.HasMetadata() {
if doc, ok := field.Metadata.GetValue(ArrowFieldDocKey); ok {
result.Doc = doc
}
}
result.Required = !field.Nullable
result.Name = field.Name
return result
}
func (c convertToIceberg) List(dt arrow.ListLikeType, elemResult iceberg.NestedField) iceberg.NestedField {
elemField := dt.ElemField()
elemID := c.fieldID(elemField)
return iceberg.NestedField{
Type: &iceberg.ListType{
ElementID: elemID,
Element: elemResult.Type,
ElementRequired: !elemField.Nullable,
},
}
}
func (c convertToIceberg) Map(m *arrow.MapType, keyResult, valueResult iceberg.NestedField) iceberg.NestedField {
keyField, valField := m.KeyField(), m.ItemField()
keyID, valID := c.fieldID(keyField), c.fieldID(valField)
return iceberg.NestedField{
Type: &iceberg.MapType{
KeyID: keyID,
KeyType: keyResult.Type,
ValueID: valID,
ValueType: valueResult.Type,
ValueRequired: !valField.Nullable,
},
}
}
var utcAliases = []string{"UTC", "+00:00", "Etc/UTC", "Z"}
func (c convertToIceberg) Primitive(dt arrow.DataType) (result iceberg.NestedField) {
switch dt := dt.(type) {
case *arrow.DictionaryType:
if _, ok := dt.ValueType.(arrow.NestedType); ok {
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
return c.Primitive(dt.ValueType)
case *arrow.RunEndEncodedType:
if _, ok := dt.Encoded().(arrow.NestedType); ok {
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
return c.Primitive(dt.Encoded())
case *arrow.BooleanType:
result.Type = iceberg.PrimitiveTypes.Bool
case *arrow.Uint8Type, *arrow.Uint16Type, *arrow.Uint32Type,
*arrow.Int8Type, *arrow.Int16Type, *arrow.Int32Type:
result.Type = iceberg.PrimitiveTypes.Int32
case *arrow.Uint64Type, *arrow.Int64Type:
result.Type = iceberg.PrimitiveTypes.Int64
case *arrow.Float16Type, *arrow.Float32Type:
result.Type = iceberg.PrimitiveTypes.Float32
case *arrow.Float64Type:
result.Type = iceberg.PrimitiveTypes.Float64
case *arrow.Decimal32Type, *arrow.Decimal64Type, *arrow.Decimal128Type:
dec := dt.(arrow.DecimalType)
result.Type = iceberg.DecimalTypeOf(int(dec.GetPrecision()), int(dec.GetScale()))
case *arrow.StringType, *arrow.LargeStringType:
result.Type = iceberg.PrimitiveTypes.String
case *arrow.BinaryType, *arrow.LargeBinaryType:
result.Type = iceberg.PrimitiveTypes.Binary
case *arrow.Date32Type:
result.Type = iceberg.PrimitiveTypes.Date
case *arrow.Time64Type:
if dt.Unit == arrow.Microsecond {
result.Type = iceberg.PrimitiveTypes.Time
} else {
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
case *arrow.TimestampType:
if dt.Unit == arrow.Nanosecond {
if !c.downcastTimestamp {
panic(fmt.Errorf("%w: 'ns' timestamp precision not supported", iceberg.ErrType))
}
// TODO: log something
}
if slices.Contains(utcAliases, dt.TimeZone) {
result.Type = iceberg.PrimitiveTypes.TimestampTz
} else if dt.TimeZone == "" {
result.Type = iceberg.PrimitiveTypes.Timestamp
} else {
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
case *arrow.FixedSizeBinaryType:
result.Type = iceberg.FixedTypeOf(dt.ByteWidth)
case arrow.ExtensionType:
if dt.ExtensionName() == "arrow.uuid" {
result.Type = iceberg.PrimitiveTypes.UUID
} else {
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
default:
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
return result
}
func ArrowTypeToIceberg(dt arrow.DataType, downcastNsTimestamp bool) (iceberg.Type, error) {
sc := arrow.NewSchema([]arrow.Field{{
Type: dt,
Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}),
}}, nil)
out, err := VisitArrowSchema(sc, convertToIceberg{
downcastTimestamp: downcastNsTimestamp,
fieldID: func(field arrow.Field) int {
if id := getFieldID(field); id != nil {
return *id
}
panic(fmt.Errorf("%w: cannot convert %s to Iceberg field, missing field_id",
iceberg.ErrInvalidSchema, field))
},
})
if err != nil {
return nil, err
}
return out.Type.(*iceberg.StructType).FieldList[0].Type, nil
}
func ArrowSchemaToIceberg(sc *arrow.Schema, downcastNsTimestamp bool, nameMapping iceberg.NameMapping) (*iceberg.Schema, error) {
hasIDs, _ := VisitArrowSchema(sc, hasIDs{})
switch {
case hasIDs:
out, err := VisitArrowSchema(sc, convertToIceberg{
downcastTimestamp: downcastNsTimestamp,
fieldID: func(field arrow.Field) int {
if id := getFieldID(field); id != nil {
return *id
}
panic(fmt.Errorf("%w: cannot convert %s to Iceberg field, missing field_id",
iceberg.ErrInvalidSchema, field))
},
})
if err != nil {
return nil, err
}
return iceberg.NewSchema(0, out.Type.(*iceberg.StructType).FieldList...), nil
case nameMapping != nil:
schemaWithoutIDs, err := arrowToSchemaWithoutIDs(sc, downcastNsTimestamp)
if err != nil {
return nil, err
}
return iceberg.ApplyNameMapping(schemaWithoutIDs, nameMapping)
default:
return nil, fmt.Errorf("%w: arrow schema does not have field-ids and no name mapping provided",
iceberg.ErrInvalidSchema)
}
}
func ArrowSchemaToIcebergWithFreshIDs(sc *arrow.Schema, downcastNsTimestamp bool) (*iceberg.Schema, error) {
schemaWithoutIDs, err := arrowToSchemaWithoutIDs(sc, downcastNsTimestamp)
if err != nil {
return nil, err
}
return iceberg.AssignFreshSchemaIDs(schemaWithoutIDs, nil)
}
func arrowToSchemaWithoutIDs(sc *arrow.Schema, downcastNsTimestamp bool) (*iceberg.Schema, error) {
withoutIDs, err := VisitArrowSchema(sc, convertToIceberg{
downcastTimestamp: downcastNsTimestamp,
fieldID: func(_ arrow.Field) int { return -1 },
})
if err != nil {
return nil, err
}
schemaWithoutIDs := iceberg.NewSchema(0, withoutIDs.Type.(*iceberg.StructType).FieldList...)
return schemaWithoutIDs, nil
}
type convertToSmallTypes struct{}
func (convertToSmallTypes) Schema(_ *arrow.Schema, structResult arrow.Field) arrow.Field {
return structResult
}
func (convertToSmallTypes) Struct(_ *arrow.StructType, results []arrow.Field) arrow.Field {
return arrow.Field{Type: arrow.StructOf(results...)}
}
func (convertToSmallTypes) Field(field arrow.Field, fieldResult arrow.Field) arrow.Field {
field.Type = fieldResult.Type
return field
}
func (convertToSmallTypes) List(_ arrow.ListLikeType, elemResult arrow.Field) arrow.Field {
return arrow.Field{Type: arrow.ListOfField(elemResult)}
}
func (convertToSmallTypes) Map(_ *arrow.MapType, keyResult, valueResult arrow.Field) arrow.Field {
return arrow.Field{
Type: arrow.MapOfWithMetadata(keyResult.Type, keyResult.Metadata,
valueResult.Type, valueResult.Metadata),
}
}
func (convertToSmallTypes) Primitive(dt arrow.DataType) arrow.Field {
switch dt.ID() {
case arrow.LARGE_STRING:
dt = arrow.BinaryTypes.String
case arrow.LARGE_BINARY:
dt = arrow.BinaryTypes.Binary
}
return arrow.Field{Type: dt}
}
func ensureSmallArrowTypes(dt arrow.DataType) (arrow.DataType, error) {
top, err := VisitArrowSchema(arrow.NewSchema([]arrow.Field{{Type: dt}}, nil), convertToSmallTypes{})
if err != nil {
return nil, err
}
return top.Type.(*arrow.StructType).Field(0).Type, nil
}
type convertToArrow struct {
metadata map[string]string
includeFieldIDs bool
useLargeTypes bool
}
func (c convertToArrow) Schema(_ *iceberg.Schema, result arrow.Field) arrow.Field {
result.Metadata = arrow.MetadataFrom(c.metadata)
return result
}
func (c convertToArrow) Struct(_ iceberg.StructType, results []arrow.Field) arrow.Field {
return arrow.Field{Type: arrow.StructOf(results...)}
}
func (c convertToArrow) Field(field iceberg.NestedField, result arrow.Field) arrow.Field {
meta := map[string]string{}
if len(field.Doc) > 0 {
meta[ArrowFieldDocKey] = field.Doc
}
if c.includeFieldIDs {
meta[ArrowParquetFieldIDKey] = strconv.Itoa(field.ID)
}
if len(meta) > 0 {
result.Metadata = arrow.MetadataFrom(meta)
}
result.Name, result.Nullable = field.Name, !field.Required
return result
}
func (c convertToArrow) List(list iceberg.ListType, elemResult arrow.Field) arrow.Field {
elemField := c.Field(list.ElementField(), elemResult)
if c.useLargeTypes {
return arrow.Field{Type: arrow.LargeListOfField(elemField)}
}
return arrow.Field{Type: arrow.ListOfField(elemField)}
}
func (c convertToArrow) Map(m iceberg.MapType, keyResult, valResult arrow.Field) arrow.Field {
keyField := c.Field(m.KeyField(), keyResult)
valField := c.Field(m.ValueField(), valResult)
return arrow.Field{Type: arrow.MapOfFields(keyField, valField)}
}
func (c convertToArrow) Primitive(iceberg.PrimitiveType) arrow.Field { panic("shouldn't be called") }
func (c convertToArrow) VisitFixed(f iceberg.FixedType) arrow.Field {
return arrow.Field{Type: &arrow.FixedSizeBinaryType{ByteWidth: f.Len()}}
}
func (c convertToArrow) VisitDecimal(d iceberg.DecimalType) arrow.Field {
return arrow.Field{Type: &arrow.Decimal128Type{
Precision: int32(d.Precision()), Scale: int32(d.Scale()),
}}
}
func (c convertToArrow) VisitBoolean() arrow.Field {
return arrow.Field{Type: arrow.FixedWidthTypes.Boolean}
}
func (c convertToArrow) VisitInt32() arrow.Field {
return arrow.Field{Type: arrow.PrimitiveTypes.Int32}
}
func (c convertToArrow) VisitInt64() arrow.Field {
return arrow.Field{Type: arrow.PrimitiveTypes.Int64}
}
func (c convertToArrow) VisitFloat32() arrow.Field {
return arrow.Field{Type: arrow.PrimitiveTypes.Float32}
}
func (c convertToArrow) VisitFloat64() arrow.Field {
return arrow.Field{Type: arrow.PrimitiveTypes.Float64}
}
func (c convertToArrow) VisitDate() arrow.Field {
return arrow.Field{Type: arrow.FixedWidthTypes.Date32}
}
func (c convertToArrow) VisitTime() arrow.Field {
return arrow.Field{Type: arrow.FixedWidthTypes.Time64us}
}
func (c convertToArrow) VisitTimestampTz() arrow.Field {
return arrow.Field{Type: arrow.FixedWidthTypes.Timestamp_us}
}
func (c convertToArrow) VisitTimestamp() arrow.Field {
return arrow.Field{Type: &arrow.TimestampType{Unit: arrow.Microsecond}}
}
func (c convertToArrow) VisitTimestampNs() arrow.Field {
return arrow.Field{Type: &arrow.TimestampType{Unit: arrow.Nanosecond}}
}
func (c convertToArrow) VisitTimestampNsTz() arrow.Field {
return arrow.Field{Type: arrow.FixedWidthTypes.Timestamp_ns}
}
func (c convertToArrow) VisitString() arrow.Field {
if c.useLargeTypes {
return arrow.Field{Type: arrow.BinaryTypes.LargeString}
}
return arrow.Field{Type: arrow.BinaryTypes.String}
}
func (c convertToArrow) VisitBinary() arrow.Field {
if c.useLargeTypes {
return arrow.Field{Type: arrow.BinaryTypes.LargeBinary}
}
return arrow.Field{Type: arrow.BinaryTypes.Binary}
}
func (c convertToArrow) VisitUUID() arrow.Field {
return arrow.Field{Type: extensions.NewUUIDType()}
}
func (c convertToArrow) VisitUnknown() arrow.Field {
return arrow.Field{
Type: extensions.NewOpaqueType(arrow.Null, "unknown", "apache.iceberg"),
}
}
var _ iceberg.SchemaVisitorPerPrimitiveType[arrow.Field] = convertToArrow{}
// SchemaToArrowSchema converts an Iceberg schema to an Arrow schema. If the metadata parameter
// is non-nil, it will be included as the top-level metadata in the schema. If includeFieldIDs
// is true, then each field of the schema will contain a metadata key PARQUET:field_id set to
// the field id from the iceberg schema.
func SchemaToArrowSchema(sc *iceberg.Schema, metadata map[string]string, includeFieldIDs, useLargeTypes bool) (*arrow.Schema, error) {
top, err := iceberg.Visit(sc, convertToArrow{
metadata: metadata,
includeFieldIDs: includeFieldIDs, useLargeTypes: useLargeTypes,
})
if err != nil {
return nil, err
}
return arrow.NewSchema(top.Type.(*arrow.StructType).Fields(), &top.Metadata), nil
}
// TypeToArrowType converts a given iceberg type, into the equivalent Arrow data type.
// For dealing with nested fields (List, Struct, Map) if includeFieldIDs is true, then
// the child fields will contain a metadata key PARQUET:field_id set to the field id.
func TypeToArrowType(t iceberg.Type, includeFieldIDs bool, useLargeTypes bool) (arrow.DataType, error) {
top, err := iceberg.Visit(iceberg.NewSchema(0, iceberg.NestedField{Type: t}),
convertToArrow{includeFieldIDs: includeFieldIDs, useLargeTypes: useLargeTypes})
if err != nil {
return nil, err
}
return top.Type.(*arrow.StructType).Field(0).Type, nil
}
type arrowAccessor struct {
fileSchema *iceberg.Schema
}
func (a arrowAccessor) SchemaPartner(partner arrow.Array) arrow.Array {
return partner
}
func (a arrowAccessor) FieldPartner(partnerStruct arrow.Array, fieldID int, _ string) arrow.Array {
if partnerStruct == nil {
return nil
}
field, ok := a.fileSchema.FindFieldByID(fieldID)
if !ok {
return nil
}
if st, ok := partnerStruct.(*array.Struct); ok {
if idx, ok := st.DataType().(*arrow.StructType).FieldIdx(field.Name); ok {
return st.Field(idx)
}
}
panic(fmt.Errorf("cannot find %s in expected partner_struct type %s",
field.Name, partnerStruct.DataType()))
}
func (a arrowAccessor) ListElementPartner(partnerList arrow.Array) arrow.Array {
if l, ok := partnerList.(array.ListLike); ok {
return l.ListValues()
}
return nil
}
func (a arrowAccessor) MapKeyPartner(partnerMap arrow.Array) arrow.Array {
if m, ok := partnerMap.(*array.Map); ok {
return m.Keys()
}
return nil
}
func (a arrowAccessor) MapValuePartner(partnerMap arrow.Array) arrow.Array {
if m, ok := partnerMap.(*array.Map); ok {
return m.Items()
}
return nil
}
func retOrPanic[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
// numericDefault converts v to T, accepting the typed iceberg form, the
// float64 that encoding/json produces when deserializing into any, or the
// json.Number that a decoder configured with UseNumber() produces.
func numericDefault[T ~int32 | ~int64 | ~float32 | ~float64](v any) T {
switch val := v.(type) {
case T:
return val
case float64:
return T(val)
case json.Number:
f, err := val.Float64()
if err != nil {
panic(fmt.Errorf("unsupported json.Number %q for numeric iceberg type: %w", val, err))
}
return T(f)
}
panic(fmt.Errorf("unsupported write-default value type %T for numeric iceberg type", v))
}
// defaultToScalar converts an Iceberg default value to an Arrow scalar.
func defaultToScalar(v any, t iceberg.Type, dt arrow.DataType) scalar.Scalar {
switch typ := t.(type) {
case iceberg.Float32Type:
s, err := scalar.MakeScalarParam(numericDefault[float32](v), dt)
if err != nil {
panic(fmt.Errorf("write-default float32 (iceberg type %s, value %v %T): %w", t, v, v, err))
}
return s
case iceberg.DateType:
return scalar.NewDate32Scalar(arrow.Date32(numericDefault[iceberg.Date](v)))
case iceberg.TimeType:
return scalar.NewTime64Scalar(arrow.Time64(numericDefault[iceberg.Time](v)), dt)
case iceberg.TimestampType, iceberg.TimestampTzType:
return scalar.NewTimestampScalar(arrow.Timestamp(numericDefault[iceberg.Timestamp](v)), dt)
case iceberg.TimestampNsType, iceberg.TimestampTzNsType:
return scalar.NewTimestampScalar(arrow.Timestamp(numericDefault[iceberg.TimestampNano](v)), dt)
case iceberg.UUIDType:
switch val := v.(type) {
case uuid.UUID:
s, err := scalar.MakeScalarParam(val[:], &arrow.FixedSizeBinaryType{ByteWidth: 16})
if err != nil {
panic(fmt.Errorf("write-default uuid (value %v): %w", val, err))
}
return s
case string:
u, err := uuid.Parse(val)
if err != nil {
panic(fmt.Errorf("write-default uuid: cannot parse string %q: %w", val, err))
}
s, err := scalar.MakeScalarParam(u[:], &arrow.FixedSizeBinaryType{ByteWidth: 16})
if err != nil {
panic(fmt.Errorf("write-default uuid (value %v): %w", val, err))
}
return s
}
panic(fmt.Errorf("write-default uuid: unsupported value type %T (%v)", v, v))
case iceberg.DecimalType:
switch val := v.(type) {
case iceberg.Decimal:
return scalar.NewDecimal128Scalar(val.Val, dt)
case string:
n, err := decimal128.FromString(val, int32(typ.Precision()), int32(typ.Scale()))
if err != nil {
panic(fmt.Errorf("write-default decimal(p=%d, s=%d): cannot parse string %q: %w", typ.Precision(), typ.Scale(), val, err))
}
return scalar.NewDecimal128Scalar(n, dt)
}
panic(fmt.Errorf("write-default decimal: unsupported value type %T (%v)", v, v))
case iceberg.BinaryType, iceberg.FixedType:
switch val := v.(type) {
case []byte:
s, err := scalar.MakeScalarParam(val, dt)
if err != nil {
panic(fmt.Errorf("write-default binary/fixed (iceberg type %s, value %v): %w", t, val, err))
}
return s
case string:
b, err := base64.StdEncoding.DecodeString(val)
if err != nil {
panic(fmt.Errorf("write-default binary/fixed (iceberg type %s): cannot base64-decode string %q: %w", t, val, err))
}
s, err := scalar.MakeScalarParam(b, dt)
if err != nil {
panic(fmt.Errorf("write-default binary/fixed (iceberg type %s, value %v): %w", t, b, err))
}
return s
}
panic(fmt.Errorf("write-default binary/fixed: unsupported value type %T (%v)", v, v))
// Float64, Bool, and String cast normally.
// Int32 and Int64 arrive as float64 from JSON and are handled by MakeScalarParam.
default:
s, err := scalar.MakeScalarParam(v, dt)
if err != nil {
panic(fmt.Errorf("write-default (iceberg type %s, value %v %T): %w", t, v, v, err))
}
return s
}
}
// defaultToArray creates an Arrow array of length n filled with the given default value v.
func defaultToArray(v any, t iceberg.Type, dt arrow.DataType, n int, alloc memory.Allocator) arrow.Array {
sc := defaultToScalar(v, t, dt)
out, err := scalar.MakeArrayFromScalar(sc, n, alloc)
if err != nil {
panic(fmt.Errorf("write-default (iceberg type %s, value %v %T): failed to create array: %w", t, v, v, err))
}
if _, ok := dt.(*extensions.UUIDType); ok {
defer out.Release()
data := array.NewData(dt, out.Len(), out.Data().Buffers(), nil, out.NullN(), 0)
defer data.Release()
return array.MakeFromData(data)
}
return out
}
type arrowProjectionVisitor struct {
ctx context.Context
fileSchema *iceberg.Schema
includeFieldIDs bool
downcastNsTimestamp bool
useLargeTypes bool
useWriteDefault bool
}
func (a *arrowProjectionVisitor) castIfNeeded(field iceberg.NestedField, vals arrow.Array) arrow.Array {
fileField, ok := a.fileSchema.FindFieldByID(field.ID)
if !ok {
panic(fmt.Errorf("could not find field id %d in schema", field.ID))
}
typ, ok := fileField.Type.(iceberg.PrimitiveType)
if !ok {
vals.Retain()
return vals
}
if !field.Type.Equals(typ) {
promoted := retOrPanic(iceberg.PromoteType(fileField.Type, field.Type))
targetType := retOrPanic(TypeToArrowType(promoted, a.includeFieldIDs, a.useLargeTypes))
if !a.useLargeTypes {
targetType = retOrPanic(ensureSmallArrowTypes(targetType))
}
return retOrPanic(compute.CastArray(a.ctx, vals,
compute.SafeCastOptions(targetType)))
}
targetType := retOrPanic(TypeToArrowType(field.Type, a.includeFieldIDs, a.useLargeTypes))
if !arrow.TypeEqual(targetType, vals.DataType()) {
switch field.Type.(type) {
case iceberg.TimestampType:
tt, tgtok := targetType.(*arrow.TimestampType)
vt, valok := vals.DataType().(*arrow.TimestampType)
if tgtok && valok && tt.TimeZone == "" && vt.TimeZone == "" && tt.Unit == arrow.Microsecond {
if vt.Unit == arrow.Nanosecond && a.downcastNsTimestamp {
return retOrPanic(compute.CastArray(a.ctx, vals, compute.UnsafeCastOptions(tt)))
} else if vt.Unit == arrow.Second || vt.Unit == arrow.Millisecond {
return retOrPanic(compute.CastArray(a.ctx, vals, compute.SafeCastOptions(tt)))
}
}
panic(fmt.Errorf("unsupported schema projection from %s to %s",
vals.DataType(), targetType))
case iceberg.TimestampTzType:
tt, tgtok := targetType.(*arrow.TimestampType)
vt, valok := vals.DataType().(*arrow.TimestampType)
if tgtok && valok && tt.TimeZone == "UTC" &&
slices.Contains(utcAliases, vt.TimeZone) && tt.Unit == arrow.Microsecond {
if vt.Unit == arrow.Nanosecond && a.downcastNsTimestamp {
return retOrPanic(compute.CastArray(a.ctx, vals, compute.UnsafeCastOptions(tt)))
} else if vt.Unit != arrow.Nanosecond {
return retOrPanic(compute.CastArray(a.ctx, vals, compute.SafeCastOptions(tt)))
}
}
panic(fmt.Errorf("unsupported schema projection from %s to %s",
vals.DataType(), targetType))
default:
return retOrPanic(compute.CastArray(a.ctx, vals,
compute.SafeCastOptions(targetType)))
}
}
vals.Retain()
return vals
}
func (a *arrowProjectionVisitor) constructField(field iceberg.NestedField, arrowType arrow.DataType) arrow.Field {
metadata := map[string]string{}
if field.Doc != "" {
metadata[ArrowFieldDocKey] = field.Doc
}
if a.includeFieldIDs {
metadata[ArrowParquetFieldIDKey] = strconv.Itoa(field.ID)
}
return arrow.Field{
Name: field.Name,
Type: arrowType,
Nullable: !field.Required,
Metadata: arrow.MetadataFrom(metadata),
}
}
func (a *arrowProjectionVisitor) Schema(_ *iceberg.Schema, _ arrow.Array, result arrow.Array) arrow.Array {
return result
}
func (a *arrowProjectionVisitor) Struct(st iceberg.StructType, structArr arrow.Array, fieldResults []arrow.Array) arrow.Array {
if structArr == nil {
return nil
}
fieldArrs := make([]arrow.Array, len(st.FieldList))
fields := make([]arrow.Field, len(st.FieldList))
for i, field := range st.FieldList {
arr := fieldResults[i]
if arr != nil {
if _, ok := arr.DataType().(arrow.NestedType); ok {
defer arr.Release()
}
arr = a.castIfNeeded(field, arr)
defer arr.Release()
fieldArrs[i] = arr
fields[i] = a.constructField(field, arr.DataType())
} else if !field.Required {
dt := retOrPanic(TypeToArrowType(field.Type, false, a.useLargeTypes))
if field.WriteDefault != nil && a.useWriteDefault {
arr = defaultToArray(field.WriteDefault, field.Type, dt, structArr.Len(), compute.GetAllocator(a.ctx))
} else if field.InitialDefault != nil && !a.useWriteDefault {
arr = defaultToArray(field.InitialDefault, field.Type, dt, structArr.Len(), compute.GetAllocator(a.ctx))
} else {
arr = array.MakeArrayOfNull(compute.GetAllocator(a.ctx), dt, structArr.Len())
}
defer arr.Release()
fieldArrs[i] = arr
fields[i] = a.constructField(field, arr.DataType())
} else {
panic(fmt.Errorf("%w: field is required, but could not be found in file: %s",
iceberg.ErrInvalidSchema, field))
}
}
var nullBitmap *memory.Buffer
if structArr.NullN() > 0 {
if structArr.Data().Offset() > 0 {
// the children already accounted for any offset because we used the `Field` method
// on the struct array in the FieldPartner accessor. So we just need to adjust the
// bitmap to account for the offset.
nullBitmap = memory.NewResizableBuffer(compute.GetAllocator(a.ctx))
defer nullBitmap.Release()
nullBitmap.Resize(int(bitutil.BytesForBits(int64(structArr.Len()))))
bitutil.CopyBitmap(structArr.NullBitmapBytes(), structArr.Data().Offset(), structArr.Len(),
nullBitmap.Bytes(), 0)
} else {
nullBitmap = structArr.Data().Buffers()[0]
}
}