/
metadata_internal.cc
1572 lines (1359 loc) · 57.9 KB
/
metadata_internal.cc
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.
#include "arrow/ipc/metadata_internal.h"
#include <cstdint>
#include <memory>
#include <sstream>
#include <unordered_map>
#include <utility>
#include <flatbuffers/flatbuffers.h>
#include "arrow/extension_type.h"
#include "arrow/io/interfaces.h"
#include "arrow/ipc/dictionary.h"
#include "arrow/ipc/message.h"
#include "arrow/ipc/options.h"
#include "arrow/ipc/util.h"
#include "arrow/sparse_tensor.h"
#include "arrow/status.h"
#include "arrow/type.h"
#include "arrow/type_traits.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/string.h"
#include "arrow/util/ubsan.h"
#include "arrow/visit_type_inline.h"
#include "generated/File_generated.h"
#include "generated/Message_generated.h"
#include "generated/Schema_generated.h"
#include "generated/SparseTensor_generated.h"
#include "generated/Tensor_generated.h"
namespace arrow {
namespace flatbuf = org::apache::arrow::flatbuf;
using internal::checked_cast;
using internal::ToChars;
namespace ipc {
namespace internal {
using FBB = flatbuffers::FlatBufferBuilder;
using DictionaryOffset = flatbuffers::Offset<flatbuf::DictionaryEncoding>;
using FieldOffset = flatbuffers::Offset<flatbuf::Field>;
using RecordBatchOffset = flatbuffers::Offset<flatbuf::RecordBatch>;
using SparseTensorOffset = flatbuffers::Offset<flatbuf::SparseTensor>;
using Offset = flatbuffers::Offset<void>;
using FBString = flatbuffers::Offset<flatbuffers::String>;
MetadataVersion GetMetadataVersion(flatbuf::MetadataVersion version) {
switch (version) {
case flatbuf::MetadataVersion::V1:
// Arrow 0.1
return MetadataVersion::V1;
case flatbuf::MetadataVersion::V2:
// Arrow 0.2
return MetadataVersion::V2;
case flatbuf::MetadataVersion::V3:
// Arrow 0.3 to 0.7.1
return MetadataVersion::V3;
case flatbuf::MetadataVersion::V4:
// Arrow 0.8 to 0.17
return MetadataVersion::V4;
case flatbuf::MetadataVersion::V5:
// Arrow >= 1.0
return MetadataVersion::V5;
// Add cases as other versions become available
default:
return MetadataVersion::V5;
}
}
flatbuf::MetadataVersion MetadataVersionToFlatbuffer(MetadataVersion version) {
switch (version) {
case MetadataVersion::V1:
return flatbuf::MetadataVersion::V1;
case MetadataVersion::V2:
return flatbuf::MetadataVersion::V2;
case MetadataVersion::V3:
return flatbuf::MetadataVersion::V3;
case MetadataVersion::V4:
return flatbuf::MetadataVersion::V4;
case MetadataVersion::V5:
return flatbuf::MetadataVersion::V5;
// Add cases as other versions become available
default:
return flatbuf::MetadataVersion::V5;
}
}
bool HasValidityBitmap(Type::type type_id, MetadataVersion version) {
// In V4, null types have no validity bitmap
// In V5 and later, null and union types have no validity bitmap
return (version < MetadataVersion::V5)
? (type_id != Type::NA)
: ::arrow::internal::may_have_validity_bitmap(type_id);
}
namespace {
Status IntFromFlatbuffer(const flatbuf::Int* int_data, std::shared_ptr<DataType>* out) {
if (int_data->bitWidth() > 64) {
return Status::NotImplemented("Integers with more than 64 bits not implemented");
}
if (int_data->bitWidth() < 8) {
return Status::NotImplemented("Integers with less than 8 bits not implemented");
}
switch (int_data->bitWidth()) {
case 8:
*out = int_data->is_signed() ? int8() : uint8();
break;
case 16:
*out = int_data->is_signed() ? int16() : uint16();
break;
case 32:
*out = int_data->is_signed() ? int32() : uint32();
break;
case 64:
*out = int_data->is_signed() ? int64() : uint64();
break;
default:
return Status::NotImplemented("Integers not in cstdint are not implemented");
}
return Status::OK();
}
Status FloatFromFlatbuffer(const flatbuf::FloatingPoint* float_data,
std::shared_ptr<DataType>* out) {
if (float_data->precision() == flatbuf::Precision::HALF) {
*out = float16();
} else if (float_data->precision() == flatbuf::Precision::SINGLE) {
*out = float32();
} else {
*out = float64();
}
return Status::OK();
}
Offset IntToFlatbuffer(FBB& fbb, int bitWidth, bool is_signed) {
return flatbuf::CreateInt(fbb, bitWidth, is_signed).Union();
}
Offset FloatToFlatbuffer(FBB& fbb, flatbuf::Precision precision) {
return flatbuf::CreateFloatingPoint(fbb, precision).Union();
}
// ----------------------------------------------------------------------
// Union implementation
Status UnionFromFlatbuffer(const flatbuf::Union* union_data,
const std::vector<std::shared_ptr<Field>>& children,
std::shared_ptr<DataType>* out) {
UnionMode::type mode =
(union_data->mode() == flatbuf::UnionMode::Sparse ? UnionMode::SPARSE
: UnionMode::DENSE);
std::vector<int8_t> type_codes;
const flatbuffers::Vector<int32_t>* fb_type_ids = union_data->typeIds();
if (fb_type_ids == nullptr) {
for (int8_t i = 0; i < static_cast<int8_t>(children.size()); ++i) {
type_codes.push_back(i);
}
} else {
for (int32_t id : (*fb_type_ids)) {
const auto type_code = static_cast<int8_t>(id);
if (id != type_code) {
return Status::Invalid("union type id out of bounds");
}
type_codes.push_back(type_code);
}
}
if (mode == UnionMode::SPARSE) {
ARROW_ASSIGN_OR_RAISE(
*out, SparseUnionType::Make(std::move(children), std::move(type_codes)));
} else {
ARROW_ASSIGN_OR_RAISE(
*out, DenseUnionType::Make(std::move(children), std::move(type_codes)));
}
return Status::OK();
}
#define INT_TO_FB_CASE(BIT_WIDTH, IS_SIGNED) \
*out_type = flatbuf::Type::Int; \
*offset = IntToFlatbuffer(fbb, BIT_WIDTH, IS_SIGNED); \
break;
} // namespace
flatbuf::TimeUnit ToFlatbufferUnit(TimeUnit::type unit) {
switch (unit) {
case TimeUnit::SECOND:
return flatbuf::TimeUnit::SECOND;
case TimeUnit::MILLI:
return flatbuf::TimeUnit::MILLISECOND;
case TimeUnit::MICRO:
return flatbuf::TimeUnit::MICROSECOND;
case TimeUnit::NANO:
return flatbuf::TimeUnit::NANOSECOND;
default:
break;
}
return flatbuf::TimeUnit::MIN;
}
TimeUnit::type FromFlatbufferUnit(flatbuf::TimeUnit unit) {
switch (unit) {
case flatbuf::TimeUnit::SECOND:
return TimeUnit::SECOND;
case flatbuf::TimeUnit::MILLISECOND:
return TimeUnit::MILLI;
case flatbuf::TimeUnit::MICROSECOND:
return TimeUnit::MICRO;
case flatbuf::TimeUnit::NANOSECOND:
return TimeUnit::NANO;
default:
break;
}
// cannot reach
return TimeUnit::SECOND;
}
Status ConcreteTypeFromFlatbuffer(flatbuf::Type type, const void* type_data,
FieldVector children, std::shared_ptr<DataType>* out) {
switch (type) {
case flatbuf::Type::NONE:
return Status::Invalid("Type metadata cannot be none");
case flatbuf::Type::Null:
*out = null();
return Status::OK();
case flatbuf::Type::Int:
return IntFromFlatbuffer(static_cast<const flatbuf::Int*>(type_data), out);
case flatbuf::Type::FloatingPoint:
return FloatFromFlatbuffer(static_cast<const flatbuf::FloatingPoint*>(type_data),
out);
case flatbuf::Type::Binary:
*out = binary();
return Status::OK();
case flatbuf::Type::LargeBinary:
*out = large_binary();
return Status::OK();
case flatbuf::Type::BinaryView:
*out = binary_view();
return Status::OK();
case flatbuf::Type::FixedSizeBinary: {
auto fw_binary = static_cast<const flatbuf::FixedSizeBinary*>(type_data);
return FixedSizeBinaryType::Make(fw_binary->byteWidth()).Value(out);
}
case flatbuf::Type::Utf8:
*out = utf8();
return Status::OK();
case flatbuf::Type::LargeUtf8:
*out = large_utf8();
return Status::OK();
case flatbuf::Type::Utf8View:
*out = utf8_view();
return Status::OK();
case flatbuf::Type::Bool:
*out = boolean();
return Status::OK();
case flatbuf::Type::Decimal: {
auto dec_type = static_cast<const flatbuf::Decimal*>(type_data);
if (dec_type->bitWidth() == 128) {
return Decimal128Type::Make(dec_type->precision(), dec_type->scale()).Value(out);
} else if (dec_type->bitWidth() == 256) {
return Decimal256Type::Make(dec_type->precision(), dec_type->scale()).Value(out);
} else {
return Status::Invalid("Library only supports 128-bit or 256-bit decimal values");
}
}
case flatbuf::Type::Date: {
auto date_type = static_cast<const flatbuf::Date*>(type_data);
if (date_type->unit() == flatbuf::DateUnit::DAY) {
*out = date32();
} else {
*out = date64();
}
return Status::OK();
}
case flatbuf::Type::Time: {
auto time_type = static_cast<const flatbuf::Time*>(type_data);
TimeUnit::type unit = FromFlatbufferUnit(time_type->unit());
int32_t bit_width = time_type->bitWidth();
switch (unit) {
case TimeUnit::SECOND:
case TimeUnit::MILLI:
if (bit_width != 32) {
return Status::Invalid("Time is 32 bits for second/milli unit");
}
*out = time32(unit);
break;
default:
if (bit_width != 64) {
return Status::Invalid("Time is 64 bits for micro/nano unit");
}
*out = time64(unit);
break;
}
return Status::OK();
}
case flatbuf::Type::Timestamp: {
auto ts_type = static_cast<const flatbuf::Timestamp*>(type_data);
TimeUnit::type unit = FromFlatbufferUnit(ts_type->unit());
*out = timestamp(unit, StringFromFlatbuffers(ts_type->timezone()));
return Status::OK();
}
case flatbuf::Type::Duration: {
auto duration = static_cast<const flatbuf::Duration*>(type_data);
TimeUnit::type unit = FromFlatbufferUnit(duration->unit());
*out = arrow::duration(unit);
return Status::OK();
}
case flatbuf::Type::Interval: {
auto i_type = static_cast<const flatbuf::Interval*>(type_data);
switch (i_type->unit()) {
case flatbuf::IntervalUnit::YEAR_MONTH: {
*out = month_interval();
return Status::OK();
}
case flatbuf::IntervalUnit::DAY_TIME: {
*out = day_time_interval();
return Status::OK();
}
case flatbuf::IntervalUnit::MONTH_DAY_NANO: {
*out = month_day_nano_interval();
return Status::OK();
}
}
return Status::NotImplemented("Unrecognized interval type.");
}
case flatbuf::Type::List:
if (children.size() != 1) {
return Status::Invalid("List must have exactly 1 child field");
}
*out = std::make_shared<ListType>(children[0]);
return Status::OK();
case flatbuf::Type::LargeList:
if (children.size() != 1) {
return Status::Invalid("LargeList must have exactly 1 child field");
}
*out = std::make_shared<LargeListType>(children[0]);
return Status::OK();
case flatbuf::Type::ListView:
if (children.size() != 1) {
return Status::Invalid("ListView must have exactly 1 child field");
}
*out = std::make_shared<ListViewType>(children[0]);
return Status::OK();
case flatbuf::Type::LargeListView:
if (children.size() != 1) {
return Status::Invalid("LargeListView must have exactly 1 child field");
}
*out = std::make_shared<LargeListViewType>(children[0]);
return Status::OK();
case flatbuf::Type::Map:
if (children.size() != 1) {
return Status::Invalid("Map must have exactly 1 child field");
}
if (children[0]->nullable() || children[0]->type()->id() != Type::STRUCT ||
children[0]->type()->num_fields() != 2) {
return Status::Invalid("Map's key-item pairs must be non-nullable structs");
}
if (children[0]->type()->field(0)->nullable()) {
return Status::Invalid("Map's keys must be non-nullable");
} else {
auto map = static_cast<const flatbuf::Map*>(type_data);
*out = std::make_shared<MapType>(children[0]->type()->field(0)->WithName("key"),
children[0]->type()->field(1)->WithName("value"),
map->keysSorted());
}
return Status::OK();
case flatbuf::Type::FixedSizeList:
if (children.size() != 1) {
return Status::Invalid("FixedSizeList must have exactly 1 child field");
} else {
auto fs_list = static_cast<const flatbuf::FixedSizeList*>(type_data);
*out = std::make_shared<FixedSizeListType>(children[0], fs_list->listSize());
}
return Status::OK();
case flatbuf::Type::Struct_:
*out = std::make_shared<StructType>(children);
return Status::OK();
case flatbuf::Type::Union:
return UnionFromFlatbuffer(static_cast<const flatbuf::Union*>(type_data), children,
out);
case flatbuf::Type::RunEndEncoded:
if (children.size() != 2) {
return Status::Invalid("RunEndEncoded must have exactly 2 child fields");
}
if (!is_run_end_type(children[0]->type()->id())) {
return Status::Invalid(
"RunEndEncoded run_ends field must be typed as: int16, int32, or int64");
}
*out =
std::make_shared<RunEndEncodedType>(children[0]->type(), children[1]->type());
return Status::OK();
default:
return Status::Invalid("Unrecognized type: " + ToChars(static_cast<int>(type)));
}
}
namespace {
Status TensorTypeToFlatbuffer(FBB& fbb, const DataType& type, flatbuf::Type* out_type,
Offset* offset) {
switch (type.id()) {
case Type::UINT8:
INT_TO_FB_CASE(8, false);
case Type::INT8:
INT_TO_FB_CASE(8, true);
case Type::UINT16:
INT_TO_FB_CASE(16, false);
case Type::INT16:
INT_TO_FB_CASE(16, true);
case Type::UINT32:
INT_TO_FB_CASE(32, false);
case Type::INT32:
INT_TO_FB_CASE(32, true);
case Type::UINT64:
INT_TO_FB_CASE(64, false);
case Type::INT64:
INT_TO_FB_CASE(64, true);
case Type::HALF_FLOAT:
*out_type = flatbuf::Type::FloatingPoint;
*offset = FloatToFlatbuffer(fbb, flatbuf::Precision::HALF);
break;
case Type::FLOAT:
*out_type = flatbuf::Type::FloatingPoint;
*offset = FloatToFlatbuffer(fbb, flatbuf::Precision::SINGLE);
break;
case Type::DOUBLE:
*out_type = flatbuf::Type::FloatingPoint;
*offset = FloatToFlatbuffer(fbb, flatbuf::Precision::DOUBLE);
break;
default:
*out_type = flatbuf::Type::NONE; // Make clang-tidy happy
return Status::NotImplemented("Unable to convert type: ", type.ToString());
}
return Status::OK();
}
static Status GetDictionaryEncoding(FBB& fbb, const std::shared_ptr<Field>& field,
const DictionaryType& type, int64_t dictionary_id,
DictionaryOffset* out) {
// We assume that the dictionary index type (as an integer) has already been
// validated elsewhere, and can safely assume we are dealing with integers
const auto& index_type = checked_cast<const IntegerType&>(*type.index_type());
auto index_type_offset =
flatbuf::CreateInt(fbb, index_type.bit_width(), index_type.is_signed());
*out = flatbuf::CreateDictionaryEncoding(fbb, dictionary_id, index_type_offset,
type.ordered());
return Status::OK();
}
static KeyValueOffset AppendKeyValue(FBB& fbb, const std::string& key,
const std::string& value) {
return flatbuf::CreateKeyValue(fbb, fbb.CreateString(key), fbb.CreateString(value));
}
static void AppendKeyValueMetadata(FBB& fbb, const KeyValueMetadata& metadata,
std::vector<KeyValueOffset>* key_values) {
key_values->reserve(metadata.size());
for (int i = 0; i < metadata.size(); ++i) {
key_values->push_back(AppendKeyValue(fbb, metadata.key(i), metadata.value(i)));
}
}
class FieldToFlatbufferVisitor {
public:
FieldToFlatbufferVisitor(FBB& fbb, const DictionaryFieldMapper& mapper,
const FieldPosition& field_pos)
: fbb_(fbb), mapper_(mapper), field_pos_(field_pos) {}
Status VisitType(const DataType& type) { return VisitTypeInline(type, this); }
Status Visit(const NullType& type) {
fb_type_ = flatbuf::Type::Null;
type_offset_ = flatbuf::CreateNull(fbb_).Union();
return Status::OK();
}
Status Visit(const BooleanType& type) {
fb_type_ = flatbuf::Type::Bool;
type_offset_ = flatbuf::CreateBool(fbb_).Union();
return Status::OK();
}
template <int BitWidth, bool IsSigned, typename T>
Status Visit(const T& type) {
fb_type_ = flatbuf::Type::Int;
type_offset_ = IntToFlatbuffer(fbb_, BitWidth, IsSigned);
return Status::OK();
}
template <typename T>
enable_if_integer<T, Status> Visit(const T& type) {
constexpr bool is_signed = is_signed_integer_type<T>::value;
return Visit<sizeof(typename T::c_type) * 8, is_signed>(type);
}
Status Visit(const HalfFloatType& type) {
fb_type_ = flatbuf::Type::FloatingPoint;
type_offset_ = FloatToFlatbuffer(fbb_, flatbuf::Precision::HALF);
return Status::OK();
}
Status Visit(const FloatType& type) {
fb_type_ = flatbuf::Type::FloatingPoint;
type_offset_ = FloatToFlatbuffer(fbb_, flatbuf::Precision::SINGLE);
return Status::OK();
}
Status Visit(const DoubleType& type) {
fb_type_ = flatbuf::Type::FloatingPoint;
type_offset_ = FloatToFlatbuffer(fbb_, flatbuf::Precision::DOUBLE);
return Status::OK();
}
Status Visit(const FixedSizeBinaryType& type) {
const auto& fw_type = checked_cast<const FixedSizeBinaryType&>(type);
fb_type_ = flatbuf::Type::FixedSizeBinary;
type_offset_ = flatbuf::CreateFixedSizeBinary(fbb_, fw_type.byte_width()).Union();
return Status::OK();
}
Status Visit(const BinaryType& type) {
fb_type_ = flatbuf::Type::Binary;
type_offset_ = flatbuf::CreateBinary(fbb_).Union();
return Status::OK();
}
Status Visit(const BinaryViewType& type) {
fb_type_ = flatbuf::Type::BinaryView;
type_offset_ = flatbuf::CreateBinaryView(fbb_).Union();
return Status::OK();
}
Status Visit(const StringViewType& type) {
fb_type_ = flatbuf::Type::Utf8View;
type_offset_ = flatbuf::CreateUtf8View(fbb_).Union();
return Status::OK();
}
Status Visit(const LargeBinaryType& type) {
fb_type_ = flatbuf::Type::LargeBinary;
type_offset_ = flatbuf::CreateLargeBinary(fbb_).Union();
return Status::OK();
}
Status Visit(const StringType& type) {
fb_type_ = flatbuf::Type::Utf8;
type_offset_ = flatbuf::CreateUtf8(fbb_).Union();
return Status::OK();
}
Status Visit(const LargeStringType& type) {
fb_type_ = flatbuf::Type::LargeUtf8;
type_offset_ = flatbuf::CreateLargeUtf8(fbb_).Union();
return Status::OK();
}
Status Visit(const Date32Type& type) {
fb_type_ = flatbuf::Type::Date;
type_offset_ = flatbuf::CreateDate(fbb_, flatbuf::DateUnit::DAY).Union();
return Status::OK();
}
Status Visit(const Date64Type& type) {
fb_type_ = flatbuf::Type::Date;
type_offset_ = flatbuf::CreateDate(fbb_, flatbuf::DateUnit::MILLISECOND).Union();
return Status::OK();
}
Status Visit(const Time32Type& type) {
const auto& time_type = checked_cast<const Time32Type&>(type);
fb_type_ = flatbuf::Type::Time;
type_offset_ =
flatbuf::CreateTime(fbb_, ToFlatbufferUnit(time_type.unit()), 32).Union();
return Status::OK();
}
Status Visit(const Time64Type& type) {
const auto& time_type = checked_cast<const Time64Type&>(type);
fb_type_ = flatbuf::Type::Time;
type_offset_ =
flatbuf::CreateTime(fbb_, ToFlatbufferUnit(time_type.unit()), 64).Union();
return Status::OK();
}
Status Visit(const TimestampType& type) {
const auto& ts_type = checked_cast<const TimestampType&>(type);
fb_type_ = flatbuf::Type::Timestamp;
flatbuf::TimeUnit fb_unit = ToFlatbufferUnit(ts_type.unit());
FBString fb_timezone = 0;
if (ts_type.timezone().size() > 0) {
fb_timezone = fbb_.CreateString(ts_type.timezone());
}
type_offset_ = flatbuf::CreateTimestamp(fbb_, fb_unit, fb_timezone).Union();
return Status::OK();
}
Status Visit(const DurationType& type) {
fb_type_ = flatbuf::Type::Duration;
flatbuf::TimeUnit fb_unit = ToFlatbufferUnit(type.unit());
type_offset_ = flatbuf::CreateDuration(fbb_, fb_unit).Union();
return Status::OK();
}
Status Visit(const DayTimeIntervalType& type) {
fb_type_ = flatbuf::Type::Interval;
type_offset_ = flatbuf::CreateInterval(fbb_, flatbuf::IntervalUnit::DAY_TIME).Union();
return Status::OK();
}
Status Visit(const MonthDayNanoIntervalType& type) {
fb_type_ = flatbuf::Type::Interval;
type_offset_ =
flatbuf::CreateInterval(fbb_, flatbuf::IntervalUnit::MONTH_DAY_NANO).Union();
return Status::OK();
}
Status Visit(const MonthIntervalType& type) {
fb_type_ = flatbuf::Type::Interval;
type_offset_ =
flatbuf::CreateInterval(fbb_, flatbuf::IntervalUnit::YEAR_MONTH).Union();
return Status::OK();
}
Status Visit(const Decimal128Type& type) {
const auto& dec_type = checked_cast<const Decimal128Type&>(type);
fb_type_ = flatbuf::Type::Decimal;
type_offset_ = flatbuf::CreateDecimal(fbb_, dec_type.precision(), dec_type.scale(),
/*bitWidth=*/128)
.Union();
return Status::OK();
}
Status Visit(const Decimal256Type& type) {
const auto& dec_type = checked_cast<const Decimal256Type&>(type);
fb_type_ = flatbuf::Type::Decimal;
type_offset_ = flatbuf::CreateDecimal(fbb_, dec_type.precision(), dec_type.scale(),
/*bitWith=*/256)
.Union();
return Status::OK();
}
Status Visit(const ListType& type) {
fb_type_ = flatbuf::Type::List;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateList(fbb_).Union();
return Status::OK();
}
Status Visit(const LargeListType& type) {
fb_type_ = flatbuf::Type::LargeList;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateLargeList(fbb_).Union();
return Status::OK();
}
Status Visit(const ListViewType& type) {
fb_type_ = flatbuf::Type::ListView;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateListView(fbb_).Union();
return Status::OK();
}
Status Visit(const LargeListViewType& type) {
fb_type_ = flatbuf::Type::LargeListView;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateListView(fbb_).Union();
return Status::OK();
}
Status Visit(const MapType& type) {
fb_type_ = flatbuf::Type::Map;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateMap(fbb_, type.keys_sorted()).Union();
return Status::OK();
}
Status Visit(const FixedSizeListType& type) {
fb_type_ = flatbuf::Type::FixedSizeList;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateFixedSizeList(fbb_, type.list_size()).Union();
return Status::OK();
}
Status Visit(const StructType& type) {
fb_type_ = flatbuf::Type::Struct_;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateStruct_(fbb_).Union();
return Status::OK();
}
Status Visit(const UnionType& type) {
fb_type_ = flatbuf::Type::Union;
RETURN_NOT_OK(VisitChildFields(type));
const auto& union_type = checked_cast<const UnionType&>(type);
flatbuf::UnionMode mode = union_type.mode() == UnionMode::SPARSE
? flatbuf::UnionMode::Sparse
: flatbuf::UnionMode::Dense;
std::vector<int32_t> type_ids;
type_ids.reserve(union_type.type_codes().size());
for (uint8_t code : union_type.type_codes()) {
type_ids.push_back(code);
}
auto fb_type_ids = fbb_.CreateVector(type_ids.data(), type_ids.size());
type_offset_ = flatbuf::CreateUnion(fbb_, mode, fb_type_ids).Union();
return Status::OK();
}
Status Visit(const DictionaryType& type) {
// In this library, the dictionary "type" is a logical construct. Here we
// pass through to the value type, as we've already captured the index
// type in the DictionaryEncoding metadata in the parent field
return VisitType(*checked_cast<const DictionaryType&>(type).value_type());
}
Status Visit(const RunEndEncodedType& type) {
fb_type_ = flatbuf::Type::RunEndEncoded;
RETURN_NOT_OK(VisitChildFields(type));
type_offset_ = flatbuf::CreateRunEndEncoded(fbb_).Union();
return Status::OK();
}
Status Visit(const ExtensionType& type) {
RETURN_NOT_OK(VisitType(*type.storage_type()));
extra_type_metadata_[kExtensionTypeKeyName] = type.extension_name();
extra_type_metadata_[kExtensionMetadataKeyName] = type.Serialize();
return Status::OK();
}
Status VisitChildFields(const DataType& type) {
for (int i = 0; i < type.num_fields(); ++i) {
FieldOffset child_offset;
FieldToFlatbufferVisitor child_visitor(fbb_, mapper_, field_pos_.child(i));
RETURN_NOT_OK(child_visitor.GetResult(type.field(i), &child_offset));
children_.push_back(child_offset);
}
return Status::OK();
}
Status GetResult(const std::shared_ptr<Field>& field, FieldOffset* offset) {
RETURN_NOT_OK(VisitType(*field->type()));
DictionaryOffset dictionary = 0;
const DataType* storage_type = field->type().get();
if (storage_type->id() == Type::EXTENSION) {
storage_type =
checked_cast<const ExtensionType&>(*storage_type).storage_type().get();
}
if (storage_type->id() == Type::DICTIONARY) {
ARROW_ASSIGN_OR_RAISE(const auto dictionary_id,
mapper_.GetFieldId(field_pos_.path()));
RETURN_NOT_OK(GetDictionaryEncoding(
fbb_, field, checked_cast<const DictionaryType&>(*storage_type), dictionary_id,
&dictionary));
}
auto metadata = field->metadata();
flatbuffers::Offset<KVVector> fb_custom_metadata;
std::vector<KeyValueOffset> key_values;
if (metadata != nullptr) {
AppendKeyValueMetadata(fbb_, *metadata, &key_values);
}
for (const auto& pair : extra_type_metadata_) {
key_values.push_back(AppendKeyValue(fbb_, pair.first, pair.second));
}
if (key_values.size() > 0) {
fb_custom_metadata = fbb_.CreateVector(key_values);
}
auto fb_name = fbb_.CreateString(field->name());
auto fb_children = fbb_.CreateVector(children_.data(), children_.size());
*offset =
flatbuf::CreateField(fbb_, fb_name, field->nullable(), fb_type_, type_offset_,
dictionary, fb_children, fb_custom_metadata);
return Status::OK();
}
private:
FBB& fbb_;
const DictionaryFieldMapper& mapper_;
FieldPosition field_pos_;
flatbuf::Type fb_type_;
Offset type_offset_;
std::vector<FieldOffset> children_;
std::unordered_map<std::string, std::string> extra_type_metadata_;
};
Status FieldFromFlatbuffer(const flatbuf::Field* field, FieldPosition field_pos,
DictionaryMemo* dictionary_memo, std::shared_ptr<Field>* out) {
std::shared_ptr<DataType> type;
std::shared_ptr<KeyValueMetadata> metadata;
RETURN_NOT_OK(internal::GetKeyValueMetadata(field->custom_metadata(), &metadata));
// Reconstruct the data type
// 1. Data type children
FieldVector child_fields;
const auto& children = field->children();
// As a tolerance, allow for a null children field meaning "no children" (ARROW-12100)
if (children != nullptr) {
child_fields.resize(children->size());
for (int i = 0; i < static_cast<int>(children->size()); ++i) {
RETURN_NOT_OK(FieldFromFlatbuffer(children->Get(i), field_pos.child(i),
dictionary_memo, &child_fields[i]));
}
}
// 2. Top-level concrete data type
auto type_data = field->type();
CHECK_FLATBUFFERS_NOT_NULL(type_data, "Field.type");
RETURN_NOT_OK(ConcreteTypeFromFlatbuffer(field->type_type(), type_data,
std::move(child_fields), &type));
// 3. Is it a dictionary type?
int64_t dictionary_id = -1;
std::shared_ptr<DataType> dict_value_type;
const flatbuf::DictionaryEncoding* encoding = field->dictionary();
if (encoding != nullptr) {
// The field is dictionary-encoded. Construct the DictionaryType
// based on the DictionaryEncoding metadata and record in the
// dictionary_memo
std::shared_ptr<DataType> index_type;
auto int_data = encoding->indexType();
CHECK_FLATBUFFERS_NOT_NULL(int_data, "DictionaryEncoding.indexType");
RETURN_NOT_OK(IntFromFlatbuffer(int_data, &index_type));
dict_value_type = type;
ARROW_ASSIGN_OR_RAISE(type,
DictionaryType::Make(index_type, type, encoding->isOrdered()));
dictionary_id = encoding->id();
}
// 4. Is it an extension type?
if (metadata != nullptr) {
// Look for extension metadata in custom_metadata field
int name_index = metadata->FindKey(kExtensionTypeKeyName);
if (name_index != -1) {
std::shared_ptr<ExtensionType> ext_type =
GetExtensionType(metadata->value(name_index));
if (ext_type != nullptr) {
int data_index = metadata->FindKey(kExtensionMetadataKeyName);
std::string type_data = data_index == -1 ? "" : metadata->value(data_index);
ARROW_ASSIGN_OR_RAISE(type, ext_type->Deserialize(type, type_data));
// Remove the metadata, for faithful roundtripping
if (data_index != -1) {
RETURN_NOT_OK(metadata->DeleteMany({name_index, data_index}));
} else {
RETURN_NOT_OK(metadata->Delete(name_index));
}
}
// NOTE: if extension type is unknown, we do not raise here and
// simply return the storage type.
}
}
// Reconstruct field
auto field_name = StringFromFlatbuffers(field->name());
*out =
::arrow::field(std::move(field_name), type, field->nullable(), std::move(metadata));
if (dictionary_id != -1) {
// We need both the id -> type mapping (to find the value type when
// reading a dictionary batch)
// and the field path -> id mapping (to find the dictionary when
// reading a record batch)
RETURN_NOT_OK(dictionary_memo->fields().AddField(dictionary_id, field_pos.path()));
RETURN_NOT_OK(dictionary_memo->AddDictionaryType(dictionary_id, dict_value_type));
}
return Status::OK();
}
// will return the endianness of the system we are running on
// based the NUMPY_API function. See NOTICE.txt
flatbuf::Endianness endianness() {
union {
uint32_t i;
char c[4];
} bint = {0x01020304};
return bint.c[0] == 1 ? flatbuf::Endianness::Big : flatbuf::Endianness::Little;
}
flatbuffers::Offset<KVVector> SerializeCustomMetadata(
FBB& fbb, const std::shared_ptr<const KeyValueMetadata>& metadata) {
std::vector<KeyValueOffset> key_values;
if (metadata != nullptr) {
AppendKeyValueMetadata(fbb, *metadata, &key_values);
return fbb.CreateVector(key_values);
} else {
// null
return 0;
}
}
Status SchemaToFlatbuffer(FBB& fbb, const Schema& schema,
const DictionaryFieldMapper& mapper,
flatbuffers::Offset<flatbuf::Schema>* out) {
std::vector<FieldOffset> field_offsets;
FieldPosition pos;
for (int i = 0; i < schema.num_fields(); ++i) {
FieldOffset offset;
FieldToFlatbufferVisitor field_visitor(fbb, mapper, pos.child(i));
RETURN_NOT_OK(field_visitor.GetResult(schema.field(i), &offset));
field_offsets.push_back(offset);
}
auto fb_offsets = fbb.CreateVector(field_offsets);
*out = flatbuf::CreateSchema(fbb, endianness(), fb_offsets,
SerializeCustomMetadata(fbb, schema.metadata()));
return Status::OK();
}
Result<std::shared_ptr<Buffer>> WriteFBMessage(
FBB& fbb, flatbuf::MessageHeader header_type, flatbuffers::Offset<void> header,
int64_t body_length, MetadataVersion version,
const std::shared_ptr<const KeyValueMetadata>& custom_metadata, MemoryPool* pool) {
auto message = flatbuf::CreateMessage(fbb, MetadataVersionToFlatbuffer(version),
header_type, header, body_length,
SerializeCustomMetadata(fbb, custom_metadata));
fbb.Finish(message);
return WriteFlatbufferBuilder(fbb, pool);
}
using FieldNodeVector =
flatbuffers::Offset<flatbuffers::Vector<const flatbuf::FieldNode*>>;
using BufferVector = flatbuffers::Offset<flatbuffers::Vector<const flatbuf::Buffer*>>;
using BodyCompressionOffset = flatbuffers::Offset<flatbuf::BodyCompression>;
static Status WriteFieldNodes(FBB& fbb, const std::vector<FieldMetadata>& nodes,
FieldNodeVector* out) {
std::vector<flatbuf::FieldNode> fb_nodes;
fb_nodes.reserve(nodes.size());
for (size_t i = 0; i < nodes.size(); ++i) {
const FieldMetadata& node = nodes[i];
if (node.offset != 0) {
return Status::Invalid("Field metadata for IPC must have offset 0");
}
fb_nodes.emplace_back(node.length, node.null_count);
}
*out = fbb.CreateVectorOfStructs(fb_nodes.data(), fb_nodes.size());
return Status::OK();
}
static Status WriteBuffers(FBB& fbb, const std::vector<BufferMetadata>& buffers,
BufferVector* out) {
std::vector<flatbuf::Buffer> fb_buffers;
fb_buffers.reserve(buffers.size());
for (size_t i = 0; i < buffers.size(); ++i) {
const BufferMetadata& buffer = buffers[i];
fb_buffers.emplace_back(buffer.offset, buffer.length);
}
*out = fbb.CreateVectorOfStructs(fb_buffers.data(), fb_buffers.size());
return Status::OK();
}
static Status GetBodyCompression(FBB& fbb, const IpcWriteOptions& options,
BodyCompressionOffset* out) {
if (options.codec != nullptr) {
flatbuf::CompressionType codec;
if (options.codec->compression_type() == Compression::LZ4_FRAME) {
codec = flatbuf::CompressionType::LZ4_FRAME;
} else if (options.codec->compression_type() == Compression::ZSTD) {