forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype.cc
More file actions
2669 lines (2226 loc) · 80.4 KB
/
Copy pathtype.cc
File metadata and controls
2669 lines (2226 loc) · 80.4 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.
#include "arrow/type.h"
#include <algorithm>
#include <climits>
#include <cstddef>
#include <iterator>
#include <limits>
#include <memory>
#include <mutex>
#include <ostream>
#include <sstream> // IWYU pragma: keep
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "arrow/array.h"
#include "arrow/compare.h"
#include "arrow/record_batch.h"
#include "arrow/result.h"
#include "arrow/status.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/hash_util.h"
#include "arrow/util/hashing.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/range.h"
#include "arrow/util/string.h"
#include "arrow/util/vector.h"
#include "arrow/visit_type_inline.h"
namespace arrow {
constexpr Type::type NullType::type_id;
constexpr Type::type ListType::type_id;
constexpr Type::type LargeListType::type_id;
constexpr Type::type MapType::type_id;
constexpr Type::type FixedSizeListType::type_id;
constexpr Type::type BinaryType::type_id;
constexpr Type::type LargeBinaryType::type_id;
constexpr Type::type StringType::type_id;
constexpr Type::type LargeStringType::type_id;
constexpr Type::type FixedSizeBinaryType::type_id;
constexpr Type::type StructType::type_id;
constexpr Type::type Decimal128Type::type_id;
constexpr Type::type Decimal256Type::type_id;
constexpr Type::type SparseUnionType::type_id;
constexpr Type::type DenseUnionType::type_id;
constexpr Type::type Date32Type::type_id;
constexpr Type::type Date64Type::type_id;
constexpr Type::type Time32Type::type_id;
constexpr Type::type Time64Type::type_id;
constexpr Type::type TimestampType::type_id;
constexpr Type::type MonthIntervalType::type_id;
constexpr Type::type DayTimeIntervalType::type_id;
constexpr Type::type MonthDayNanoIntervalType::type_id;
constexpr Type::type DurationType::type_id;
constexpr Type::type DictionaryType::type_id;
std::vector<Type::type> AllTypeIds() {
return {Type::NA,
Type::BOOL,
Type::INT8,
Type::INT16,
Type::INT32,
Type::INT64,
Type::UINT8,
Type::UINT16,
Type::UINT32,
Type::UINT64,
Type::HALF_FLOAT,
Type::FLOAT,
Type::DOUBLE,
Type::DECIMAL128,
Type::DECIMAL256,
Type::DATE32,
Type::DATE64,
Type::TIME32,
Type::TIME64,
Type::TIMESTAMP,
Type::INTERVAL_DAY_TIME,
Type::INTERVAL_MONTHS,
Type::DURATION,
Type::STRING,
Type::BINARY,
Type::LARGE_STRING,
Type::LARGE_BINARY,
Type::FIXED_SIZE_BINARY,
Type::STRUCT,
Type::LIST,
Type::LARGE_LIST,
Type::FIXED_SIZE_LIST,
Type::MAP,
Type::DENSE_UNION,
Type::SPARSE_UNION,
Type::DICTIONARY,
Type::EXTENSION,
Type::INTERVAL_MONTH_DAY_NANO};
}
namespace internal {
struct TypeIdToTypeNameVisitor {
std::string out;
template <typename ArrowType>
Status Visit(const ArrowType*) {
out = ArrowType::type_name();
return Status::OK();
}
};
std::string ToTypeName(Type::type id) {
TypeIdToTypeNameVisitor visitor;
ARROW_CHECK_OK(VisitTypeIdInline(id, &visitor));
return std::move(visitor.out);
}
std::string ToString(Type::type id) {
switch (id) {
#define TO_STRING_CASE(_id) \
case Type::_id: \
return ARROW_STRINGIFY(_id);
TO_STRING_CASE(NA)
TO_STRING_CASE(BOOL)
TO_STRING_CASE(INT8)
TO_STRING_CASE(INT16)
TO_STRING_CASE(INT32)
TO_STRING_CASE(INT64)
TO_STRING_CASE(UINT8)
TO_STRING_CASE(UINT16)
TO_STRING_CASE(UINT32)
TO_STRING_CASE(UINT64)
TO_STRING_CASE(HALF_FLOAT)
TO_STRING_CASE(FLOAT)
TO_STRING_CASE(DOUBLE)
TO_STRING_CASE(DECIMAL128)
TO_STRING_CASE(DECIMAL256)
TO_STRING_CASE(DATE32)
TO_STRING_CASE(DATE64)
TO_STRING_CASE(TIME32)
TO_STRING_CASE(TIME64)
TO_STRING_CASE(TIMESTAMP)
TO_STRING_CASE(INTERVAL_DAY_TIME)
TO_STRING_CASE(INTERVAL_MONTH_DAY_NANO)
TO_STRING_CASE(INTERVAL_MONTHS)
TO_STRING_CASE(DURATION)
TO_STRING_CASE(STRING)
TO_STRING_CASE(BINARY)
TO_STRING_CASE(LARGE_STRING)
TO_STRING_CASE(LARGE_BINARY)
TO_STRING_CASE(FIXED_SIZE_BINARY)
TO_STRING_CASE(STRUCT)
TO_STRING_CASE(LIST)
TO_STRING_CASE(LARGE_LIST)
TO_STRING_CASE(FIXED_SIZE_LIST)
TO_STRING_CASE(MAP)
TO_STRING_CASE(DENSE_UNION)
TO_STRING_CASE(SPARSE_UNION)
TO_STRING_CASE(DICTIONARY)
TO_STRING_CASE(EXTENSION)
#undef TO_STRING_CASE
default:
ARROW_LOG(FATAL) << "Unhandled type id: " << id;
return "";
}
}
std::string ToString(TimeUnit::type unit) {
switch (unit) {
case TimeUnit::SECOND:
return "s";
case TimeUnit::MILLI:
return "ms";
case TimeUnit::MICRO:
return "us";
case TimeUnit::NANO:
return "ns";
default:
DCHECK(false);
return "";
}
}
} // namespace internal
namespace {
struct PhysicalTypeVisitor {
const std::shared_ptr<DataType>& real_type;
std::shared_ptr<DataType> result;
Status Visit(const DataType&) {
result = real_type;
return Status::OK();
}
template <typename Type, typename PhysicalType = typename Type::PhysicalType>
Status Visit(const Type&) {
result = TypeTraits<PhysicalType>::type_singleton();
return Status::OK();
}
};
} // namespace
std::shared_ptr<DataType> GetPhysicalType(const std::shared_ptr<DataType>& real_type) {
PhysicalTypeVisitor visitor{real_type, {}};
ARROW_CHECK_OK(VisitTypeInline(*real_type, &visitor));
return std::move(visitor.result);
}
namespace {
using internal::checked_cast;
// Merges `existing` and `other` if one of them is of NullType, otherwise
// returns nullptr.
// - if `other` if of NullType or is nullable, the unified field will be nullable.
// - if `existing` is of NullType but other is not, the unified field will
// have `other`'s type and will be nullable
std::shared_ptr<Field> MaybePromoteNullTypes(const Field& existing, const Field& other) {
if (existing.type()->id() != Type::NA && other.type()->id() != Type::NA) {
return nullptr;
}
if (existing.type()->id() == Type::NA) {
return other.WithNullable(true)->WithMetadata(existing.metadata());
}
// `other` must be null.
return existing.WithNullable(true);
}
} // namespace
Field::~Field() {}
bool Field::HasMetadata() const {
return (metadata_ != nullptr) && (metadata_->size() > 0);
}
std::shared_ptr<Field> Field::WithMetadata(
const std::shared_ptr<const KeyValueMetadata>& metadata) const {
return std::make_shared<Field>(name_, type_, nullable_, metadata);
}
std::shared_ptr<Field> Field::WithMergedMetadata(
const std::shared_ptr<const KeyValueMetadata>& metadata) const {
std::shared_ptr<const KeyValueMetadata> merged_metadata;
if (metadata_) {
merged_metadata = metadata_->Merge(*metadata);
} else {
merged_metadata = metadata;
}
return std::make_shared<Field>(name_, type_, nullable_, merged_metadata);
}
std::shared_ptr<Field> Field::RemoveMetadata() const {
return std::make_shared<Field>(name_, type_, nullable_);
}
std::shared_ptr<Field> Field::WithType(const std::shared_ptr<DataType>& type) const {
return std::make_shared<Field>(name_, type, nullable_, metadata_);
}
std::shared_ptr<Field> Field::WithName(const std::string& name) const {
return std::make_shared<Field>(name, type_, nullable_, metadata_);
}
std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
Result<std::shared_ptr<Field>> Field::MergeWith(const Field& other,
MergeOptions options) const {
if (name() != other.name()) {
return Status::Invalid("Field ", name(), " doesn't have the same name as ",
other.name());
}
if (Equals(other, /*check_metadata=*/false)) {
return Copy();
}
if (options.promote_nullability) {
if (type()->Equals(other.type())) {
return Copy()->WithNullable(nullable() || other.nullable());
}
std::shared_ptr<Field> promoted = MaybePromoteNullTypes(*this, other);
if (promoted) return promoted;
}
return Status::Invalid("Unable to merge: Field ", name(),
" has incompatible types: ", type()->ToString(), " vs ",
other.type()->ToString());
}
Result<std::shared_ptr<Field>> Field::MergeWith(const std::shared_ptr<Field>& other,
MergeOptions options) const {
DCHECK_NE(other, nullptr);
return MergeWith(*other, options);
}
std::vector<std::shared_ptr<Field>> Field::Flatten() const {
std::vector<std::shared_ptr<Field>> flattened;
if (type_->id() == Type::STRUCT) {
for (const auto& child : type_->fields()) {
auto flattened_child = child->Copy();
flattened.push_back(flattened_child);
flattened_child->name_.insert(0, name() + ".");
flattened_child->nullable_ |= nullable_;
}
} else {
flattened.push_back(this->Copy());
}
return flattened;
}
std::shared_ptr<Field> Field::Copy() const {
return ::arrow::field(name_, type_, nullable_, metadata_);
}
bool Field::Equals(const Field& other, bool check_metadata) const {
if (this == &other) {
return true;
}
if (this->name_ == other.name_ && this->nullable_ == other.nullable_ &&
this->type_->Equals(*other.type_.get(), check_metadata)) {
if (!check_metadata) {
return true;
} else if (this->HasMetadata() && other.HasMetadata()) {
return metadata_->Equals(*other.metadata_);
} else if (!this->HasMetadata() && !other.HasMetadata()) {
return true;
} else {
return false;
}
}
return false;
}
bool Field::Equals(const std::shared_ptr<Field>& other, bool check_metadata) const {
return Equals(*other.get(), check_metadata);
}
bool Field::IsCompatibleWith(const Field& other) const { return MergeWith(other).ok(); }
bool Field::IsCompatibleWith(const std::shared_ptr<Field>& other) const {
DCHECK_NE(other, nullptr);
return IsCompatibleWith(*other);
}
std::string Field::ToString(bool show_metadata) const {
std::stringstream ss;
ss << name_ << ": " << type_->ToString();
if (!nullable_) {
ss << " not null";
}
if (show_metadata && metadata_) {
ss << metadata_->ToString();
}
return ss.str();
}
void PrintTo(const Field& field, std::ostream* os) { *os << field.ToString(); }
DataType::~DataType() {}
bool DataType::Equals(const DataType& other, bool check_metadata) const {
return TypeEquals(*this, other, check_metadata);
}
bool DataType::Equals(const std::shared_ptr<DataType>& other, bool check_metadata) const {
if (!other) {
return false;
}
return Equals(*other.get(), check_metadata);
}
size_t DataType::Hash() const {
static constexpr size_t kHashSeed = 0;
size_t result = kHashSeed;
internal::hash_combine(result, this->fingerprint());
return result;
}
std::ostream& operator<<(std::ostream& os, const DataType& type) {
os << type.ToString();
return os;
}
std::ostream& operator<<(std::ostream& os, const TypeHolder& type) {
os << type.ToString();
return os;
}
// ----------------------------------------------------------------------
// TypeHolder
std::string TypeHolder::ToString(const std::vector<TypeHolder>& types) {
std::stringstream ss;
ss << "(";
for (size_t i = 0; i < types.size(); ++i) {
if (i > 0) {
ss << ", ";
}
ss << types[i].type->ToString();
}
ss << ")";
return ss.str();
}
std::vector<TypeHolder> TypeHolder::FromTypes(
const std::vector<std::shared_ptr<DataType>>& types) {
std::vector<TypeHolder> type_holders;
type_holders.reserve(types.size());
for (const auto& type : types) {
type_holders.emplace_back(type);
}
return type_holders;
}
// ----------------------------------------------------------------------
FixedWidthType::~FixedWidthType() {}
PrimitiveCType::~PrimitiveCType() {}
NumberType::~NumberType() {}
IntegerType::~IntegerType() {}
FloatingPointType::~FloatingPointType() {}
FloatingPointType::Precision HalfFloatType::precision() const {
return FloatingPointType::HALF;
}
FloatingPointType::Precision FloatType::precision() const {
return FloatingPointType::SINGLE;
}
FloatingPointType::Precision DoubleType::precision() const {
return FloatingPointType::DOUBLE;
}
std::ostream& operator<<(std::ostream& os,
DayTimeIntervalType::DayMilliseconds interval) {
os << interval.days << "d" << interval.milliseconds << "ms";
return os;
}
std::ostream& operator<<(std::ostream& os,
MonthDayNanoIntervalType::MonthDayNanos interval) {
os << interval.months << "M" << interval.days << "d" << interval.nanoseconds << "ns";
return os;
}
NestedType::~NestedType() {}
BaseBinaryType::~BaseBinaryType() {}
BaseListType::~BaseListType() {}
std::string ListType::ToString() const {
std::stringstream s;
s << "list<" << value_field()->ToString() << ">";
return s.str();
}
std::string LargeListType::ToString() const {
std::stringstream s;
s << "large_list<" << value_field()->ToString() << ">";
return s.str();
}
MapType::MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<DataType> item_type,
bool keys_sorted)
: MapType(::arrow::field("key", std::move(key_type), false),
::arrow::field("value", std::move(item_type)), keys_sorted) {}
MapType::MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<Field> item_field,
bool keys_sorted)
: MapType(::arrow::field("key", std::move(key_type), false), std::move(item_field),
keys_sorted) {}
MapType::MapType(std::shared_ptr<Field> key_field, std::shared_ptr<Field> item_field,
bool keys_sorted)
: MapType(
::arrow::field("entries",
struct_({std::move(key_field), std::move(item_field)}), false),
keys_sorted) {}
MapType::MapType(std::shared_ptr<Field> value_field, bool keys_sorted)
: ListType(std::move(value_field)), keys_sorted_(keys_sorted) {
id_ = type_id;
}
Result<std::shared_ptr<DataType>> MapType::Make(std::shared_ptr<Field> value_field,
bool keys_sorted) {
const auto& value_type = *value_field->type();
if (value_field->nullable() || value_type.id() != Type::STRUCT) {
return Status::TypeError("Map entry field should be non-nullable struct");
}
const auto& struct_type = checked_cast<const StructType&>(value_type);
if (struct_type.num_fields() != 2) {
return Status::TypeError("Map entry field should have two children (got ",
struct_type.num_fields(), ")");
}
if (struct_type.field(0)->nullable()) {
return Status::TypeError("Map key field should be non-nullable");
}
return std::make_shared<MapType>(std::move(value_field), keys_sorted);
}
std::string MapType::ToString() const {
std::stringstream s;
const auto print_field_name = [](std::ostream& os, const Field& field,
const char* std_name) {
if (field.name() != std_name) {
os << " ('" << field.name() << "')";
}
};
const auto print_field = [&](std::ostream& os, const Field& field,
const char* std_name) {
os << field.type()->ToString();
print_field_name(os, field, std_name);
};
s << "map<";
print_field(s, *key_field(), "key");
s << ", ";
print_field(s, *item_field(), "value");
if (keys_sorted_) {
s << ", keys_sorted";
}
print_field_name(s, *value_field(), "entries");
s << ">";
return s.str();
}
std::string FixedSizeListType::ToString() const {
std::stringstream s;
s << "fixed_size_list<" << value_field()->ToString() << ">[" << list_size_ << "]";
return s.str();
}
std::string BinaryType::ToString() const { return "binary"; }
std::string LargeBinaryType::ToString() const { return "large_binary"; }
std::string StringType::ToString() const { return "string"; }
std::string LargeStringType::ToString() const { return "large_string"; }
int FixedSizeBinaryType::bit_width() const { return CHAR_BIT * byte_width(); }
Result<std::shared_ptr<DataType>> FixedSizeBinaryType::Make(int32_t byte_width) {
if (byte_width < 0) {
return Status::Invalid("Negative FixedSizeBinaryType byte width");
}
if (byte_width > std::numeric_limits<int>::max() / CHAR_BIT) {
// bit_width() would overflow
return Status::Invalid("byte width of FixedSizeBinaryType too large");
}
return std::make_shared<FixedSizeBinaryType>(byte_width);
}
std::string FixedSizeBinaryType::ToString() const {
std::stringstream ss;
ss << "fixed_size_binary[" << byte_width_ << "]";
return ss.str();
}
TemporalType::~TemporalType() {}
// ----------------------------------------------------------------------
// Date types
DateType::DateType(Type::type type_id) : TemporalType(type_id) {}
Date32Type::Date32Type() : DateType(Type::DATE32) {}
Date64Type::Date64Type() : DateType(Type::DATE64) {}
std::string Date64Type::ToString() const { return std::string("date64[ms]"); }
std::string Date32Type::ToString() const { return std::string("date32[day]"); }
// ----------------------------------------------------------------------
// Time types
TimeType::TimeType(Type::type type_id, TimeUnit::type unit)
: TemporalType(type_id), unit_(unit) {}
Time32Type::Time32Type(TimeUnit::type unit) : TimeType(Type::TIME32, unit) {
ARROW_CHECK(unit == TimeUnit::SECOND || unit == TimeUnit::MILLI)
<< "Must be seconds or milliseconds";
}
std::string Time32Type::ToString() const {
std::stringstream ss;
ss << "time32[" << this->unit_ << "]";
return ss.str();
}
Time64Type::Time64Type(TimeUnit::type unit) : TimeType(Type::TIME64, unit) {
ARROW_CHECK(unit == TimeUnit::MICRO || unit == TimeUnit::NANO)
<< "Must be microseconds or nanoseconds";
}
std::string Time64Type::ToString() const {
std::stringstream ss;
ss << "time64[" << this->unit_ << "]";
return ss.str();
}
std::ostream& operator<<(std::ostream& os, TimeUnit::type unit) {
switch (unit) {
case TimeUnit::SECOND:
os << "s";
break;
case TimeUnit::MILLI:
os << "ms";
break;
case TimeUnit::MICRO:
os << "us";
break;
case TimeUnit::NANO:
os << "ns";
break;
}
return os;
}
// ----------------------------------------------------------------------
// Timestamp types
std::string TimestampType::ToString() const {
std::stringstream ss;
ss << "timestamp[" << this->unit_;
if (this->timezone_.size() > 0) {
ss << ", tz=" << this->timezone_;
}
ss << "]";
return ss.str();
}
// Duration types
std::string DurationType::ToString() const {
std::stringstream ss;
ss << "duration[" << this->unit_ << "]";
return ss.str();
}
// ----------------------------------------------------------------------
// Union type
constexpr int8_t UnionType::kMaxTypeCode;
constexpr int UnionType::kInvalidChildId;
UnionMode::type UnionType::mode() const {
return id_ == Type::SPARSE_UNION ? UnionMode::SPARSE : UnionMode::DENSE;
}
UnionType::UnionType(std::vector<std::shared_ptr<Field>> fields,
std::vector<int8_t> type_codes, Type::type id)
: NestedType(id),
type_codes_(std::move(type_codes)),
child_ids_(kMaxTypeCode + 1, kInvalidChildId) {
children_ = std::move(fields);
DCHECK_OK(ValidateParameters(children_, type_codes_, mode()));
for (int child_id = 0; child_id < static_cast<int>(type_codes_.size()); ++child_id) {
const auto type_code = type_codes_[child_id];
child_ids_[type_code] = child_id;
}
}
Status UnionType::ValidateParameters(const std::vector<std::shared_ptr<Field>>& fields,
const std::vector<int8_t>& type_codes,
UnionMode::type mode) {
if (fields.size() != type_codes.size()) {
return Status::Invalid("Union should get the same number of fields as type codes");
}
for (const auto type_code : type_codes) {
if (type_code < 0 || type_code > kMaxTypeCode) {
return Status::Invalid("Union type code out of bounds");
}
}
return Status::OK();
}
DataTypeLayout UnionType::layout() const {
if (mode() == UnionMode::SPARSE) {
return DataTypeLayout(
{DataTypeLayout::AlwaysNull(), DataTypeLayout::FixedWidth(sizeof(uint8_t))});
} else {
return DataTypeLayout({DataTypeLayout::AlwaysNull(),
DataTypeLayout::FixedWidth(sizeof(uint8_t)),
DataTypeLayout::FixedWidth(sizeof(int32_t))});
}
}
uint8_t UnionType::max_type_code() const {
return type_codes_.size() == 0
? 0
: *std::max_element(type_codes_.begin(), type_codes_.end());
}
std::string UnionType::ToString() const {
std::stringstream s;
s << name() << "<";
for (size_t i = 0; i < children_.size(); ++i) {
if (i) {
s << ", ";
}
s << children_[i]->ToString() << "=" << static_cast<int>(type_codes_[i]);
}
s << ">";
return s.str();
}
SparseUnionType::SparseUnionType(std::vector<std::shared_ptr<Field>> fields,
std::vector<int8_t> type_codes)
: UnionType(fields, type_codes, Type::SPARSE_UNION) {}
Result<std::shared_ptr<DataType>> SparseUnionType::Make(
std::vector<std::shared_ptr<Field>> fields, std::vector<int8_t> type_codes) {
RETURN_NOT_OK(ValidateParameters(fields, type_codes, UnionMode::SPARSE));
return std::make_shared<SparseUnionType>(fields, type_codes);
}
DenseUnionType::DenseUnionType(std::vector<std::shared_ptr<Field>> fields,
std::vector<int8_t> type_codes)
: UnionType(fields, type_codes, Type::DENSE_UNION) {}
Result<std::shared_ptr<DataType>> DenseUnionType::Make(
std::vector<std::shared_ptr<Field>> fields, std::vector<int8_t> type_codes) {
RETURN_NOT_OK(ValidateParameters(fields, type_codes, UnionMode::DENSE));
return std::make_shared<DenseUnionType>(fields, type_codes);
}
// ----------------------------------------------------------------------
// Struct type
namespace {
std::unordered_multimap<std::string, int> CreateNameToIndexMap(
const std::vector<std::shared_ptr<Field>>& fields) {
std::unordered_multimap<std::string, int> name_to_index;
for (size_t i = 0; i < fields.size(); ++i) {
name_to_index.emplace(fields[i]->name(), static_cast<int>(i));
}
return name_to_index;
}
template <int NotFoundValue = -1, int DuplicateFoundValue = -1>
int LookupNameIndex(const std::unordered_multimap<std::string, int>& name_to_index,
const std::string& name) {
auto p = name_to_index.equal_range(name);
auto it = p.first;
if (it == p.second) {
// Not found
return NotFoundValue;
}
auto index = it->second;
if (++it != p.second) {
// Duplicate field name
return DuplicateFoundValue;
}
return index;
}
} // namespace
class StructType::Impl {
public:
explicit Impl(const std::vector<std::shared_ptr<Field>>& fields)
: name_to_index_(CreateNameToIndexMap(fields)) {}
const std::unordered_multimap<std::string, int> name_to_index_;
};
StructType::StructType(const std::vector<std::shared_ptr<Field>>& fields)
: NestedType(Type::STRUCT), impl_(new Impl(fields)) {
children_ = fields;
}
StructType::~StructType() {}
std::string StructType::ToString() const {
std::stringstream s;
s << "struct<";
for (int i = 0; i < this->num_fields(); ++i) {
if (i > 0) {
s << ", ";
}
std::shared_ptr<Field> field = this->field(i);
s << field->ToString();
}
s << ">";
return s.str();
}
std::shared_ptr<Field> StructType::GetFieldByName(const std::string& name) const {
int i = GetFieldIndex(name);
return i == -1 ? nullptr : children_[i];
}
int StructType::GetFieldIndex(const std::string& name) const {
return LookupNameIndex(impl_->name_to_index_, name);
}
std::vector<int> StructType::GetAllFieldIndices(const std::string& name) const {
std::vector<int> result;
auto p = impl_->name_to_index_.equal_range(name);
for (auto it = p.first; it != p.second; ++it) {
result.push_back(it->second);
}
if (result.size() > 1) {
std::sort(result.begin(), result.end());
}
return result;
}
std::vector<std::shared_ptr<Field>> StructType::GetAllFieldsByName(
const std::string& name) const {
std::vector<std::shared_ptr<Field>> result;
auto p = impl_->name_to_index_.equal_range(name);
for (auto it = p.first; it != p.second; ++it) {
result.push_back(children_[it->second]);
}
return result;
}
Result<std::shared_ptr<StructType>> StructType::AddField(
int i, const std::shared_ptr<Field>& field) const {
if (i < 0 || i > this->num_fields()) {
return Status::Invalid("Invalid column index to add field.");
}
return std::make_shared<StructType>(internal::AddVectorElement(children_, i, field));
}
Result<std::shared_ptr<StructType>> StructType::RemoveField(int i) const {
if (i < 0 || i >= this->num_fields()) {
return Status::Invalid("Invalid column index to remove field.");
}
return std::make_shared<StructType>(internal::DeleteVectorElement(children_, i));
}
Result<std::shared_ptr<StructType>> StructType::SetField(
int i, const std::shared_ptr<Field>& field) const {
if (i < 0 || i >= this->num_fields()) {
return Status::Invalid("Invalid column index to set field.");
}
return std::make_shared<StructType>(
internal::ReplaceVectorElement(children_, i, field));
}
Result<std::shared_ptr<DataType>> DecimalType::Make(Type::type type_id, int32_t precision,
int32_t scale) {
if (type_id == Type::DECIMAL128) {
return Decimal128Type::Make(precision, scale);
} else if (type_id == Type::DECIMAL256) {
return Decimal256Type::Make(precision, scale);
} else {
return Status::Invalid("Not a decimal type_id: ", type_id);
}
}
// Taken from the Apache Impala codebase. The comments next
// to the return values are the maximum value that can be represented in 2's
// complement with the returned number of bytes.
int32_t DecimalType::DecimalSize(int32_t precision) {
DCHECK_GE(precision, 1) << "decimal precision must be greater than or equal to 1, got "
<< precision;
// Generated in python with:
// >>> decimal_size = lambda prec: int(math.ceil((prec * math.log2(10) + 1) / 8))
// >>> [-1] + [decimal_size(i) for i in range(1, 77)]
constexpr int32_t kBytes[] = {
-1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8, 9,
9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17,
17, 18, 18, 18, 19, 19, 20, 20, 21, 21, 21, 22, 22, 23, 23, 23, 24, 24, 25, 25,
26, 26, 26, 27, 27, 28, 28, 28, 29, 29, 30, 30, 31, 31, 31, 32, 32};
if (precision <= 76) {
return kBytes[precision];
}
return static_cast<int32_t>(std::ceil((precision / 8.0) * std::log2(10) + 1));
}
// ----------------------------------------------------------------------
// Decimal128 type
Decimal128Type::Decimal128Type(int32_t precision, int32_t scale)
: DecimalType(type_id, 16, precision, scale) {
ARROW_CHECK_GE(precision, kMinPrecision);
ARROW_CHECK_LE(precision, kMaxPrecision);
}
Result<std::shared_ptr<DataType>> Decimal128Type::Make(int32_t precision, int32_t scale) {
if (precision < kMinPrecision || precision > kMaxPrecision) {
return Status::Invalid("Decimal precision out of range [", int32_t(kMinPrecision),
", ", int32_t(kMaxPrecision), "]: ", precision);
}
return std::make_shared<Decimal128Type>(precision, scale);
}
// ----------------------------------------------------------------------
// Decimal256 type
Decimal256Type::Decimal256Type(int32_t precision, int32_t scale)
: DecimalType(type_id, 32, precision, scale) {
ARROW_CHECK_GE(precision, kMinPrecision);
ARROW_CHECK_LE(precision, kMaxPrecision);
}
Result<std::shared_ptr<DataType>> Decimal256Type::Make(int32_t precision, int32_t scale) {
if (precision < kMinPrecision || precision > kMaxPrecision) {
return Status::Invalid("Decimal precision out of range [", int32_t(kMinPrecision),
", ", int32_t(kMaxPrecision), "]: ", precision);
}
return std::make_shared<Decimal256Type>(precision, scale);
}
// ----------------------------------------------------------------------
// Dictionary-encoded type
Status DictionaryType::ValidateParameters(const DataType& index_type,
const DataType& value_type) {
if (!is_integer(index_type.id())) {
return Status::TypeError("Dictionary index type should be integer, got ",
index_type.ToString());
}
return Status::OK();
}
int DictionaryType::bit_width() const {
return checked_cast<const FixedWidthType&>(*index_type_).bit_width();
}
Result<std::shared_ptr<DataType>> DictionaryType::Make(
const std::shared_ptr<DataType>& index_type,
const std::shared_ptr<DataType>& value_type, bool ordered) {
RETURN_NOT_OK(ValidateParameters(*index_type, *value_type));
return std::make_shared<DictionaryType>(index_type, value_type, ordered);
}
DictionaryType::DictionaryType(const std::shared_ptr<DataType>& index_type,
const std::shared_ptr<DataType>& value_type, bool ordered)
: FixedWidthType(Type::DICTIONARY),
index_type_(index_type),
value_type_(value_type),
ordered_(ordered) {