forked from aliyun/aliyun-odps-go-sdk
/
metadata.go
1151 lines (976 loc) · 32.4 KB
/
metadata.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
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 ipc
import (
"encoding/binary"
"io"
"sort"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/arrow"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/arrow/internal/flatbuf"
"github.com/jiuzhiqian/aliyun-odps-go-sdk/arrow/memory"
flatbuffers "github.com/google/flatbuffers/go"
"golang.org/x/xerrors"
)
// Magic string identifying an Apache Arrow file.
var Magic = []byte("ARROW1")
const (
currentMetadataVersion = MetadataV5
minMetadataVersion = MetadataV4
// constants for the extension type metadata keys for the type name and
// any extension metadata to be passed to deserialize.
ExtensionTypeKeyName = "ARROW:extension:name"
ExtensionMetadataKeyName = "ARROW:extension:metadata"
// ARROW-109: We set this number arbitrarily to help catch user mistakes. For
// deeply nested schemas, it is expected the user will indicate explicitly the
// maximum allowed recursion depth
kMaxNestingDepth = 64
)
type startVecFunc func(b *flatbuffers.Builder, n int) flatbuffers.UOffsetT
type fieldMetadata struct {
Len int64
Nulls int64
Offset int64
}
type bufferMetadata struct {
Offset int64 // relative offset into the memory page to the starting byte of the buffer
Len int64 // absolute length in bytes of the buffer
}
type fileBlock struct {
Offset int64
Meta int32
Body int64
r io.ReaderAt
}
func fileBlocksToFB(b *flatbuffers.Builder, blocks []fileBlock, start startVecFunc) flatbuffers.UOffsetT {
start(b, len(blocks))
for i := len(blocks) - 1; i >= 0; i-- {
blk := blocks[i]
flatbuf.CreateBlock(b, blk.Offset, blk.Meta, blk.Body)
}
return b.EndVector(len(blocks))
}
func (blk fileBlock) NewMessage() (*Message, error) {
var (
err error
buf []byte
r = blk.section()
)
buf = make([]byte, blk.Meta)
_, err = io.ReadFull(r, buf)
if err != nil {
return nil, xerrors.Errorf("arrow/ipc: could not read message metadata: %w", err)
}
prefix := 0
switch binary.LittleEndian.Uint32(buf) {
case 0:
case kIPCContToken:
prefix = 8
default:
// ARROW-6314: backwards compatibility for reading old IPC
// messages produced prior to version 0.15.0
prefix = 4
}
meta := memory.NewBufferBytes(buf[prefix:]) // drop buf-size already known from blk.Meta
buf = make([]byte, blk.Body)
_, err = io.ReadFull(r, buf)
if err != nil {
return nil, xerrors.Errorf("arrow/ipc: could not read message body: %w", err)
}
body := memory.NewBufferBytes(buf)
return NewMessage(meta, body), nil
}
func (blk fileBlock) section() io.Reader {
return io.NewSectionReader(blk.r, blk.Offset, int64(blk.Meta)+blk.Body)
}
func unitFromFB(unit flatbuf.TimeUnit) arrow.TimeUnit {
switch unit {
case flatbuf.TimeUnitSECOND:
return arrow.Second
case flatbuf.TimeUnitMILLISECOND:
return arrow.Millisecond
case flatbuf.TimeUnitMICROSECOND:
return arrow.Microsecond
case flatbuf.TimeUnitNANOSECOND:
return arrow.Nanosecond
default:
panic(xerrors.Errorf("arrow/ipc: invalid flatbuf.TimeUnit(%d) value", unit))
}
}
func unitToFB(unit arrow.TimeUnit) flatbuf.TimeUnit {
switch unit {
case arrow.Second:
return flatbuf.TimeUnitSECOND
case arrow.Millisecond:
return flatbuf.TimeUnitMILLISECOND
case arrow.Microsecond:
return flatbuf.TimeUnitMICROSECOND
case arrow.Nanosecond:
return flatbuf.TimeUnitNANOSECOND
default:
panic(xerrors.Errorf("arrow/ipc: invalid arrow.TimeUnit(%d) value", unit))
}
}
// initFB is a helper function to handle flatbuffers' polymorphism.
func initFB(t interface {
Table() flatbuffers.Table
Init([]byte, flatbuffers.UOffsetT)
}, f func(tbl *flatbuffers.Table) bool) {
tbl := t.Table()
if !f(&tbl) {
panic(xerrors.Errorf("arrow/ipc: could not initialize %T from flatbuffer", t))
}
t.Init(tbl.Bytes, tbl.Pos)
}
func fieldFromFB(field *flatbuf.Field, memo *dictMemo) (arrow.Field, error) {
var (
err error
o arrow.Field
)
o.Name = string(field.Name())
o.Nullable = field.Nullable()
o.Metadata, err = metadataFromFB(field)
if err != nil {
return o, err
}
encoding := field.Dictionary(nil)
switch encoding {
case nil:
n := field.ChildrenLength()
children := make([]arrow.Field, n)
for i := range children {
var childFB flatbuf.Field
if !field.Children(&childFB, i) {
return o, xerrors.Errorf("arrow/ipc: could not load field child %d", i)
}
child, err := fieldFromFB(&childFB, memo)
if err != nil {
return o, xerrors.Errorf("arrow/ipc: could not convert field child %d: %w", i, err)
}
children[i] = child
}
o.Type, err = typeFromFB(field, children, &o.Metadata)
if err != nil {
return o, xerrors.Errorf("arrow/ipc: could not convert field type: %w", err)
}
default:
panic("not implemented") // FIXME(sbinet)
}
return o, nil
}
func fieldToFB(b *flatbuffers.Builder, field arrow.Field, memo *dictMemo) flatbuffers.UOffsetT {
var visitor = fieldVisitor{b: b, memo: memo, meta: make(map[string]string)}
return visitor.result(field)
}
type fieldVisitor struct {
b *flatbuffers.Builder
memo *dictMemo
dtype flatbuf.Type
offset flatbuffers.UOffsetT
kids []flatbuffers.UOffsetT
meta map[string]string
}
func (fv *fieldVisitor) visit(field arrow.Field) {
dt := field.Type
switch dt := dt.(type) {
case *arrow.NullType:
fv.dtype = flatbuf.TypeNull
flatbuf.NullStart(fv.b)
fv.offset = flatbuf.NullEnd(fv.b)
case *arrow.BooleanType:
fv.dtype = flatbuf.TypeBool
flatbuf.BoolStart(fv.b)
fv.offset = flatbuf.BoolEnd(fv.b)
case *arrow.Uint8Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), false)
case *arrow.Uint16Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), false)
case *arrow.Uint32Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), false)
case *arrow.Uint64Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), false)
case *arrow.Int8Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), true)
case *arrow.Int16Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), true)
case *arrow.Int32Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), true)
case *arrow.Int64Type:
fv.dtype = flatbuf.TypeInt
fv.offset = intToFB(fv.b, int32(dt.BitWidth()), true)
case *arrow.Float16Type:
fv.dtype = flatbuf.TypeFloatingPoint
fv.offset = floatToFB(fv.b, int32(dt.BitWidth()))
case *arrow.Float32Type:
fv.dtype = flatbuf.TypeFloatingPoint
fv.offset = floatToFB(fv.b, int32(dt.BitWidth()))
case *arrow.Float64Type:
fv.dtype = flatbuf.TypeFloatingPoint
fv.offset = floatToFB(fv.b, int32(dt.BitWidth()))
case *arrow.Decimal128Type:
fv.dtype = flatbuf.TypeDecimal
flatbuf.DecimalStart(fv.b)
flatbuf.DecimalAddPrecision(fv.b, dt.Precision)
flatbuf.DecimalAddScale(fv.b, dt.Scale)
fv.offset = flatbuf.DecimalEnd(fv.b)
case *arrow.FixedSizeBinaryType:
fv.dtype = flatbuf.TypeFixedSizeBinary
flatbuf.FixedSizeBinaryStart(fv.b)
flatbuf.FixedSizeBinaryAddByteWidth(fv.b, int32(dt.ByteWidth))
fv.offset = flatbuf.FixedSizeBinaryEnd(fv.b)
case *arrow.BinaryType:
fv.dtype = flatbuf.TypeBinary
flatbuf.BinaryStart(fv.b)
fv.offset = flatbuf.BinaryEnd(fv.b)
case *arrow.StringType:
fv.dtype = flatbuf.TypeUtf8
flatbuf.Utf8Start(fv.b)
fv.offset = flatbuf.Utf8End(fv.b)
case *arrow.Date32Type:
fv.dtype = flatbuf.TypeDate
flatbuf.DateStart(fv.b)
flatbuf.DateAddUnit(fv.b, flatbuf.DateUnitDAY)
fv.offset = flatbuf.DateEnd(fv.b)
case *arrow.Date64Type:
fv.dtype = flatbuf.TypeDate
flatbuf.DateStart(fv.b)
flatbuf.DateAddUnit(fv.b, flatbuf.DateUnitMILLISECOND)
fv.offset = flatbuf.DateEnd(fv.b)
case *arrow.Time32Type:
fv.dtype = flatbuf.TypeTime
flatbuf.TimeStart(fv.b)
flatbuf.TimeAddUnit(fv.b, unitToFB(dt.Unit))
flatbuf.TimeAddBitWidth(fv.b, 32)
fv.offset = flatbuf.TimeEnd(fv.b)
case *arrow.Time64Type:
fv.dtype = flatbuf.TypeTime
flatbuf.TimeStart(fv.b)
flatbuf.TimeAddUnit(fv.b, unitToFB(dt.Unit))
flatbuf.TimeAddBitWidth(fv.b, 64)
fv.offset = flatbuf.TimeEnd(fv.b)
case *arrow.TimestampType:
fv.dtype = flatbuf.TypeTimestamp
unit := unitToFB(dt.Unit)
var tz flatbuffers.UOffsetT
if dt.TimeZone != "" {
tz = fv.b.CreateString(dt.TimeZone)
}
flatbuf.TimestampStart(fv.b)
flatbuf.TimestampAddUnit(fv.b, unit)
flatbuf.TimestampAddTimezone(fv.b, tz)
fv.offset = flatbuf.TimestampEnd(fv.b)
case *arrow.StructType:
fv.dtype = flatbuf.TypeStruct_
offsets := make([]flatbuffers.UOffsetT, len(dt.Fields()))
for i, field := range dt.Fields() {
offsets[i] = fieldToFB(fv.b, field, fv.memo)
}
flatbuf.Struct_Start(fv.b)
for i := len(offsets) - 1; i >= 0; i-- {
fv.b.PrependUOffsetT(offsets[i])
}
fv.offset = flatbuf.Struct_End(fv.b)
fv.kids = append(fv.kids, offsets...)
case *arrow.ListType:
fv.dtype = flatbuf.TypeList
fv.kids = append(fv.kids, fieldToFB(fv.b, dt.ElemField(), fv.memo))
flatbuf.ListStart(fv.b)
fv.offset = flatbuf.ListEnd(fv.b)
case *arrow.FixedSizeListType:
fv.dtype = flatbuf.TypeFixedSizeList
fv.kids = append(fv.kids, fieldToFB(fv.b, dt.ElemField(), fv.memo))
flatbuf.FixedSizeListStart(fv.b)
flatbuf.FixedSizeListAddListSize(fv.b, dt.Len())
fv.offset = flatbuf.FixedSizeListEnd(fv.b)
case *arrow.MonthIntervalType:
fv.dtype = flatbuf.TypeInterval
flatbuf.IntervalStart(fv.b)
flatbuf.IntervalAddUnit(fv.b, flatbuf.IntervalUnitYEAR_MONTH)
fv.offset = flatbuf.IntervalEnd(fv.b)
case *arrow.DayTimeIntervalType:
fv.dtype = flatbuf.TypeInterval
flatbuf.IntervalStart(fv.b)
flatbuf.IntervalAddUnit(fv.b, flatbuf.IntervalUnitDAY_TIME)
fv.offset = flatbuf.IntervalEnd(fv.b)
case *arrow.MonthDayNanoIntervalType:
fv.dtype = flatbuf.TypeInterval
flatbuf.IntervalStart(fv.b)
flatbuf.IntervalAddUnit(fv.b, flatbuf.IntervalUnitMONTH_DAY_NANO)
fv.offset = flatbuf.IntervalEnd(fv.b)
case *arrow.DurationType:
fv.dtype = flatbuf.TypeDuration
unit := unitToFB(dt.Unit)
flatbuf.DurationStart(fv.b)
flatbuf.DurationAddUnit(fv.b, unit)
fv.offset = flatbuf.DurationEnd(fv.b)
case *arrow.MapType:
fv.dtype = flatbuf.TypeMap
fv.kids = append(fv.kids, fieldToFB(fv.b, dt.ValueField(), fv.memo))
flatbuf.MapStart(fv.b)
flatbuf.MapAddKeysSorted(fv.b, dt.KeysSorted)
fv.offset = flatbuf.MapEnd(fv.b)
case arrow.ExtensionType:
field.Type = dt.StorageType()
fv.visit(field)
fv.meta[ExtensionTypeKeyName] = dt.ExtensionName()
fv.meta[ExtensionMetadataKeyName] = string(dt.Serialize())
default:
err := xerrors.Errorf("arrow/ipc: invalid data type %v", dt)
panic(err) // FIXME(sbinet): implement all data-types.
}
}
func (fv *fieldVisitor) result(field arrow.Field) flatbuffers.UOffsetT {
nameFB := fv.b.CreateString(field.Name)
fv.visit(field)
flatbuf.FieldStartChildrenVector(fv.b, len(fv.kids))
for i := len(fv.kids) - 1; i >= 0; i-- {
fv.b.PrependUOffsetT(fv.kids[i])
}
kidsFB := fv.b.EndVector(len(fv.kids))
var dictFB flatbuffers.UOffsetT
if field.Type.ID() == arrow.DICTIONARY {
panic("not implemented") // FIXME(sbinet)
}
var (
metaFB flatbuffers.UOffsetT
kvs []flatbuffers.UOffsetT
)
for i, k := range field.Metadata.Keys() {
v := field.Metadata.Values()[i]
kk := fv.b.CreateString(k)
vv := fv.b.CreateString(v)
flatbuf.KeyValueStart(fv.b)
flatbuf.KeyValueAddKey(fv.b, kk)
flatbuf.KeyValueAddValue(fv.b, vv)
kvs = append(kvs, flatbuf.KeyValueEnd(fv.b))
}
{
keys := make([]string, 0, len(fv.meta))
for k := range fv.meta {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := fv.meta[k]
kk := fv.b.CreateString(k)
vv := fv.b.CreateString(v)
flatbuf.KeyValueStart(fv.b)
flatbuf.KeyValueAddKey(fv.b, kk)
flatbuf.KeyValueAddValue(fv.b, vv)
kvs = append(kvs, flatbuf.KeyValueEnd(fv.b))
}
}
if len(kvs) > 0 {
flatbuf.FieldStartCustomMetadataVector(fv.b, len(kvs))
for i := len(kvs) - 1; i >= 0; i-- {
fv.b.PrependUOffsetT(kvs[i])
}
metaFB = fv.b.EndVector(len(kvs))
}
flatbuf.FieldStart(fv.b)
flatbuf.FieldAddName(fv.b, nameFB)
flatbuf.FieldAddNullable(fv.b, field.Nullable)
flatbuf.FieldAddTypeType(fv.b, fv.dtype)
flatbuf.FieldAddType(fv.b, fv.offset)
flatbuf.FieldAddDictionary(fv.b, dictFB)
flatbuf.FieldAddChildren(fv.b, kidsFB)
flatbuf.FieldAddCustomMetadata(fv.b, metaFB)
offset := flatbuf.FieldEnd(fv.b)
return offset
}
func fieldFromFBDict(field *flatbuf.Field) (arrow.Field, error) {
var (
o = arrow.Field{
Name: string(field.Name()),
Nullable: field.Nullable(),
}
err error
memo = newMemo()
)
// any DictionaryEncoding set is ignored here.
kids := make([]arrow.Field, field.ChildrenLength())
for i := range kids {
var kid flatbuf.Field
if !field.Children(&kid, i) {
return o, xerrors.Errorf("arrow/ipc: could not load field child %d", i)
}
kids[i], err = fieldFromFB(&kid, &memo)
if err != nil {
return o, xerrors.Errorf("arrow/ipc: field from dict: %w", err)
}
}
meta, err := metadataFromFB(field)
if err != nil {
return o, xerrors.Errorf("arrow/ipc: metadata for field from dict: %w", err)
}
o.Type, err = typeFromFB(field, kids, &meta)
if err != nil {
return o, xerrors.Errorf("arrow/ipc: type for field from dict: %w", err)
}
return o, nil
}
func typeFromFB(field *flatbuf.Field, children []arrow.Field, md *arrow.Metadata) (arrow.DataType, error) {
var data flatbuffers.Table
if !field.Type(&data) {
return nil, xerrors.Errorf("arrow/ipc: could not load field type data")
}
dt, err := concreteTypeFromFB(field.TypeType(), data, children)
if err != nil {
return dt, err
}
// look for extension metadata in custom metadata field.
if md.Len() > 0 {
i := md.FindKey(ExtensionTypeKeyName)
if i < 0 {
return dt, err
}
extType := arrow.GetExtensionType(md.Values()[i])
if extType == nil {
// if the extension type is unknown, we do not error here.
// simply return the storage type.
return dt, err
}
var (
data string
dataIdx int
)
if dataIdx = md.FindKey(ExtensionMetadataKeyName); dataIdx >= 0 {
data = md.Values()[dataIdx]
}
dt, err = extType.Deserialize(dt, data)
if err != nil {
return dt, err
}
mdkeys := md.Keys()
mdvals := md.Values()
if dataIdx < 0 {
// if there was no extension metadata, just the name, we only have to
// remove the extension name metadata key/value to ensure roundtrip
// metadata consistency
*md = arrow.NewMetadata(append(mdkeys[:i], mdkeys[i+1:]...), append(mdvals[:i], mdvals[i+1:]...))
} else {
// if there was extension metadata, we need to remove both the type name
// and the extension metadata keys and values.
newkeys := make([]string, 0, md.Len()-2)
newvals := make([]string, 0, md.Len()-2)
for j := range mdkeys {
if j != i && j != dataIdx { // copy everything except the extension metadata keys/values
newkeys = append(newkeys, mdkeys[j])
newvals = append(newvals, mdvals[j])
}
}
*md = arrow.NewMetadata(newkeys, newvals)
}
}
return dt, err
}
func concreteTypeFromFB(typ flatbuf.Type, data flatbuffers.Table, children []arrow.Field) (arrow.DataType, error) {
switch typ {
case flatbuf.TypeNONE:
return nil, xerrors.Errorf("arrow/ipc: Type metadata cannot be none")
case flatbuf.TypeNull:
return arrow.Null, nil
case flatbuf.TypeInt:
var dt flatbuf.Int
dt.Init(data.Bytes, data.Pos)
return intFromFB(dt)
case flatbuf.TypeFloatingPoint:
var dt flatbuf.FloatingPoint
dt.Init(data.Bytes, data.Pos)
return floatFromFB(dt)
case flatbuf.TypeDecimal:
var dt flatbuf.Decimal
dt.Init(data.Bytes, data.Pos)
return decimalFromFB(dt)
case flatbuf.TypeBinary:
return arrow.BinaryTypes.Binary, nil
case flatbuf.TypeFixedSizeBinary:
var dt flatbuf.FixedSizeBinary
dt.Init(data.Bytes, data.Pos)
return &arrow.FixedSizeBinaryType{ByteWidth: int(dt.ByteWidth())}, nil
case flatbuf.TypeUtf8:
return arrow.BinaryTypes.String, nil
case flatbuf.TypeBool:
return arrow.FixedWidthTypes.Boolean, nil
case flatbuf.TypeList:
if len(children) != 1 {
return nil, xerrors.Errorf("arrow/ipc: List must have exactly 1 child field (got=%d)", len(children))
}
dt := arrow.ListOfField(children[0])
return dt, nil
case flatbuf.TypeFixedSizeList:
var dt flatbuf.FixedSizeList
dt.Init(data.Bytes, data.Pos)
if len(children) != 1 {
return nil, xerrors.Errorf("arrow/ipc: FixedSizeList must have exactly 1 child field (got=%d)", len(children))
}
ret := arrow.FixedSizeListOfField(dt.ListSize(), children[0])
return ret, nil
case flatbuf.TypeStruct_:
return arrow.StructOf(children...), nil
case flatbuf.TypeTime:
var dt flatbuf.Time
dt.Init(data.Bytes, data.Pos)
return timeFromFB(dt)
case flatbuf.TypeTimestamp:
var dt flatbuf.Timestamp
dt.Init(data.Bytes, data.Pos)
return timestampFromFB(dt)
case flatbuf.TypeDate:
var dt flatbuf.Date
dt.Init(data.Bytes, data.Pos)
return dateFromFB(dt)
case flatbuf.TypeInterval:
var dt flatbuf.Interval
dt.Init(data.Bytes, data.Pos)
return intervalFromFB(dt)
case flatbuf.TypeDuration:
var dt flatbuf.Duration
dt.Init(data.Bytes, data.Pos)
return durationFromFB(dt)
case flatbuf.TypeMap:
if len(children) != 1 {
return nil, xerrors.Errorf("arrow/ipc: Map must have exactly 1 child field")
}
if children[0].Nullable || children[0].Type.ID() != arrow.STRUCT || len(children[0].Type.(*arrow.StructType).Fields()) != 2 {
return nil, xerrors.Errorf("arrow/ipc: Map's key-item pairs must be non-nullable structs")
}
pairType := children[0].Type.(*arrow.StructType)
if pairType.Field(0).Nullable {
return nil, xerrors.Errorf("arrow/ipc: Map's keys must be non-nullable")
}
var dt flatbuf.Map
dt.Init(data.Bytes, data.Pos)
ret := arrow.MapOf(pairType.Field(0).Type, pairType.Field(1).Type)
ret.KeysSorted = dt.KeysSorted()
return ret, nil
default:
// FIXME(sbinet): implement all the other types.
panic(xerrors.Errorf("arrow/ipc: type %v not implemented", flatbuf.EnumNamesType[typ]))
}
}
func intFromFB(data flatbuf.Int) (arrow.DataType, error) {
bw := data.BitWidth()
if bw > 64 {
return nil, xerrors.Errorf("arrow/ipc: integers with more than 64 bits not implemented (bits=%d)", bw)
}
if bw < 8 {
return nil, xerrors.Errorf("arrow/ipc: integers with less than 8 bits not implemented (bits=%d)", bw)
}
switch bw {
case 8:
if !data.IsSigned() {
return arrow.PrimitiveTypes.Uint8, nil
}
return arrow.PrimitiveTypes.Int8, nil
case 16:
if !data.IsSigned() {
return arrow.PrimitiveTypes.Uint16, nil
}
return arrow.PrimitiveTypes.Int16, nil
case 32:
if !data.IsSigned() {
return arrow.PrimitiveTypes.Uint32, nil
}
return arrow.PrimitiveTypes.Int32, nil
case 64:
if !data.IsSigned() {
return arrow.PrimitiveTypes.Uint64, nil
}
return arrow.PrimitiveTypes.Int64, nil
default:
return nil, xerrors.Errorf("arrow/ipc: integers not in cstdint are not implemented")
}
}
func intToFB(b *flatbuffers.Builder, bw int32, isSigned bool) flatbuffers.UOffsetT {
flatbuf.IntStart(b)
flatbuf.IntAddBitWidth(b, bw)
flatbuf.IntAddIsSigned(b, isSigned)
return flatbuf.IntEnd(b)
}
func floatFromFB(data flatbuf.FloatingPoint) (arrow.DataType, error) {
switch p := data.Precision(); p {
case flatbuf.PrecisionHALF:
return arrow.FixedWidthTypes.Float16, nil
case flatbuf.PrecisionSINGLE:
return arrow.PrimitiveTypes.Float32, nil
case flatbuf.PrecisionDOUBLE:
return arrow.PrimitiveTypes.Float64, nil
default:
return nil, xerrors.Errorf("arrow/ipc: floating point type with %d precision not implemented", p)
}
}
func floatToFB(b *flatbuffers.Builder, bw int32) flatbuffers.UOffsetT {
switch bw {
case 16:
flatbuf.FloatingPointStart(b)
flatbuf.FloatingPointAddPrecision(b, flatbuf.PrecisionHALF)
return flatbuf.FloatingPointEnd(b)
case 32:
flatbuf.FloatingPointStart(b)
flatbuf.FloatingPointAddPrecision(b, flatbuf.PrecisionSINGLE)
return flatbuf.FloatingPointEnd(b)
case 64:
flatbuf.FloatingPointStart(b)
flatbuf.FloatingPointAddPrecision(b, flatbuf.PrecisionDOUBLE)
return flatbuf.FloatingPointEnd(b)
default:
panic(xerrors.Errorf("arrow/ipc: invalid floating point precision %d-bits", bw))
}
}
func decimalFromFB(data flatbuf.Decimal) (arrow.DataType, error) {
return &arrow.Decimal128Type{Precision: data.Precision(), Scale: data.Scale()}, nil
}
func timeFromFB(data flatbuf.Time) (arrow.DataType, error) {
bw := data.BitWidth()
unit := unitFromFB(data.Unit())
switch bw {
case 32:
switch unit {
case arrow.Millisecond:
return arrow.FixedWidthTypes.Time32ms, nil
case arrow.Second:
return arrow.FixedWidthTypes.Time32s, nil
default:
return nil, xerrors.Errorf("arrow/ipc: Time32 type with %v unit not implemented", unit)
}
case 64:
switch unit {
case arrow.Nanosecond:
return arrow.FixedWidthTypes.Time64ns, nil
case arrow.Microsecond:
return arrow.FixedWidthTypes.Time64us, nil
default:
return nil, xerrors.Errorf("arrow/ipc: Time64 type with %v unit not implemented", unit)
}
default:
return nil, xerrors.Errorf("arrow/ipc: Time type with %d bitwidth not implemented", bw)
}
}
func timestampFromFB(data flatbuf.Timestamp) (arrow.DataType, error) {
unit := unitFromFB(data.Unit())
tz := string(data.Timezone())
return &arrow.TimestampType{Unit: unit, TimeZone: tz}, nil
}
func dateFromFB(data flatbuf.Date) (arrow.DataType, error) {
switch data.Unit() {
case flatbuf.DateUnitDAY:
return arrow.FixedWidthTypes.Date32, nil
case flatbuf.DateUnitMILLISECOND:
return arrow.FixedWidthTypes.Date64, nil
}
return nil, xerrors.Errorf("arrow/ipc: Date type with %d unit not implemented", data.Unit())
}
func intervalFromFB(data flatbuf.Interval) (arrow.DataType, error) {
switch data.Unit() {
case flatbuf.IntervalUnitYEAR_MONTH:
return arrow.FixedWidthTypes.MonthInterval, nil
case flatbuf.IntervalUnitDAY_TIME:
return arrow.FixedWidthTypes.DayTimeInterval, nil
case flatbuf.IntervalUnitMONTH_DAY_NANO:
return arrow.FixedWidthTypes.MonthDayNanoInterval, nil
}
return nil, xerrors.Errorf("arrow/ipc: Interval type with %d unit not implemented", data.Unit())
}
func durationFromFB(data flatbuf.Duration) (arrow.DataType, error) {
switch data.Unit() {
case flatbuf.TimeUnitSECOND:
return arrow.FixedWidthTypes.Duration_s, nil
case flatbuf.TimeUnitMILLISECOND:
return arrow.FixedWidthTypes.Duration_ms, nil
case flatbuf.TimeUnitMICROSECOND:
return arrow.FixedWidthTypes.Duration_us, nil
case flatbuf.TimeUnitNANOSECOND:
return arrow.FixedWidthTypes.Duration_ns, nil
}
return nil, xerrors.Errorf("arrow/ipc: Duration type with %d unit not implemented", data.Unit())
}
type customMetadataer interface {
CustomMetadataLength() int
CustomMetadata(*flatbuf.KeyValue, int) bool
}
func metadataFromFB(md customMetadataer) (arrow.Metadata, error) {
var (
keys = make([]string, md.CustomMetadataLength())
vals = make([]string, md.CustomMetadataLength())
)
for i := range keys {
var kv flatbuf.KeyValue
if !md.CustomMetadata(&kv, i) {
return arrow.Metadata{}, xerrors.Errorf("arrow/ipc: could not read key-value %d from flatbuffer", i)
}
keys[i] = string(kv.Key())
vals[i] = string(kv.Value())
}
return arrow.NewMetadata(keys, vals), nil
}
func metadataToFB(b *flatbuffers.Builder, meta arrow.Metadata, start startVecFunc) flatbuffers.UOffsetT {
if meta.Len() == 0 {
return 0
}
n := meta.Len()
kvs := make([]flatbuffers.UOffsetT, n)
for i := range kvs {
k := b.CreateString(meta.Keys()[i])
v := b.CreateString(meta.Values()[i])
flatbuf.KeyValueStart(b)
flatbuf.KeyValueAddKey(b, k)
flatbuf.KeyValueAddValue(b, v)
kvs[i] = flatbuf.KeyValueEnd(b)
}
start(b, n)
for i := n - 1; i >= 0; i-- {
b.PrependUOffsetT(kvs[i])
}
return b.EndVector(n)
}
func schemaFromFB(schema *flatbuf.Schema, memo *dictMemo) (*arrow.Schema, error) {
var (
err error
fields = make([]arrow.Field, schema.FieldsLength())
)
for i := range fields {
var field flatbuf.Field
if !schema.Fields(&field, i) {
return nil, xerrors.Errorf("arrow/ipc: could not read field %d from schema", i)
}
fields[i], err = fieldFromFB(&field, memo)
if err != nil {
return nil, xerrors.Errorf("arrow/ipc: could not convert field %d from flatbuf: %w", i, err)
}
}
md, err := metadataFromFB(schema)
if err != nil {
return nil, xerrors.Errorf("arrow/ipc: could not convert schema metadata from flatbuf: %w", err)
}
return arrow.NewSchema(fields, &md), nil
}
func schemaToFB(b *flatbuffers.Builder, schema *arrow.Schema, memo *dictMemo) flatbuffers.UOffsetT {
fields := make([]flatbuffers.UOffsetT, len(schema.Fields()))
for i, field := range schema.Fields() {
fields[i] = fieldToFB(b, field, memo)
}
flatbuf.SchemaStartFieldsVector(b, len(fields))
for i := len(fields) - 1; i >= 0; i-- {
b.PrependUOffsetT(fields[i])
}
fieldsFB := b.EndVector(len(fields))
metaFB := metadataToFB(b, schema.Metadata(), flatbuf.SchemaStartCustomMetadataVector)
flatbuf.SchemaStart(b)
flatbuf.SchemaAddEndianness(b, flatbuf.EndiannessLittle)
flatbuf.SchemaAddFields(b, fieldsFB)
flatbuf.SchemaAddCustomMetadata(b, metaFB)
offset := flatbuf.SchemaEnd(b)
return offset
}
func dictTypesFromFB(schema *flatbuf.Schema) (dictTypeMap, error) {
var (
err error
fields = make(dictTypeMap, schema.FieldsLength())
)
for i := 0; i < schema.FieldsLength(); i++ {
var field flatbuf.Field
if !schema.Fields(&field, i) {
return nil, xerrors.Errorf("arrow/ipc: could not load field %d from schema", i)
}
fields, err = visitField(&field, fields)
if err != nil {
return nil, xerrors.Errorf("arrow/ipc: could not visit field %d from schema: %w", i, err)
}
}
return fields, err
}
func visitField(field *flatbuf.Field, dict dictTypeMap) (dictTypeMap, error) {
var err error
meta := field.Dictionary(nil)
switch meta {
case nil:
// field is not dictionary encoded.
// => visit children.
for i := 0; i < field.ChildrenLength(); i++ {
var child flatbuf.Field
if !field.Children(&child, i) {
return nil, xerrors.Errorf("arrow/ipc: could not visit child %d from field", i)
}
dict, err = visitField(&child, dict)
if err != nil {
return nil, err
}
}
default:
// field is dictionary encoded.
// construct the data type for the dictionary: no descendants can be dict-encoded.
dfield, err := fieldFromFBDict(field)
if err != nil {
return nil, xerrors.Errorf("arrow/ipc: could not create data type for dictionary: %w", err)
}
dict[meta.Id()] = dfield
}
return dict, err
}
// payloadsFromSchema returns a slice of payloads corresponding to the given schema.
// Callers of payloadsFromSchema will need to call Release after use.
func payloadsFromSchema(schema *arrow.Schema, mem memory.Allocator, memo *dictMemo) payloads {
dict := newMemo()
ps := make(payloads, 1, dict.Len()+1)
ps[0].msg = MessageSchema
ps[0].meta = writeSchemaMessage(schema, mem, &dict)
// append dictionaries.
if dict.Len() > 0 {
panic("payloads-from-schema: not-implemented")
// for id, arr := range dict.id2dict {
// // GetSchemaPayloads: writer.cc:535
// }
}
if memo != nil {
*memo = dict
}
return ps
}
func writeFBBuilder(b *flatbuffers.Builder, mem memory.Allocator) *memory.Buffer {
raw := b.FinishedBytes()
buf := memory.NewResizableBuffer(mem)
buf.Resize(len(raw))