/
reader.cc
1490 lines (1251 loc) · 54.6 KB
/
reader.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 "parquet/arrow/reader.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
#include "arrow/api.h"
#include "arrow/util/bit-util.h"
#include "arrow/util/decimal.h"
#include "arrow/util/logging.h"
#include "arrow/util/parallel.h"
#include "parquet/arrow/record_reader.h"
#include "parquet/arrow/schema.h"
#include "parquet/column_reader.h"
#include "parquet/schema.h"
#include "parquet/util/schema-util.h"
using arrow::Array;
using arrow::BooleanArray;
using arrow::Column;
using arrow::Field;
using arrow::Int32Array;
using arrow::ListArray;
using arrow::MemoryPool;
using arrow::PoolBuffer;
using arrow::Status;
using arrow::StructArray;
using arrow::Table;
using arrow::TimestampArray;
using parquet::schema::Node;
// Help reduce verbosity
using ParquetReader = parquet::ParquetFileReader;
using arrow::ParallelFor;
using arrow::RecordBatchReader;
using parquet::internal::RecordReader;
namespace parquet {
namespace arrow {
using ::arrow::BitUtil::BytesForBits;
constexpr int64_t kJulianToUnixEpochDays = 2440588LL;
constexpr int64_t kMillisecondsInADay = 86400000LL;
constexpr int64_t kNanosecondsInADay = kMillisecondsInADay * 1000LL * 1000LL;
static inline int64_t impala_timestamp_to_nanoseconds(const Int96& impala_timestamp) {
int64_t days_since_epoch = impala_timestamp.value[2] - kJulianToUnixEpochDays;
int64_t nanoseconds = *(reinterpret_cast<const int64_t*>(&(impala_timestamp.value)));
return days_since_epoch * kNanosecondsInADay + nanoseconds;
}
template <typename ArrowType>
using ArrayType = typename ::arrow::TypeTraits<ArrowType>::ArrayType;
// ----------------------------------------------------------------------
// Iteration utilities
// Abstraction to decouple row group iteration details from the ColumnReader,
// so we can read only a single row group if we want
class FileColumnIterator {
public:
explicit FileColumnIterator(int column_index, ParquetFileReader* reader)
: column_index_(column_index),
reader_(reader),
schema_(reader->metadata()->schema()) {}
virtual ~FileColumnIterator() {}
virtual std::unique_ptr<::parquet::PageReader> NextChunk() = 0;
const SchemaDescriptor* schema() const { return schema_; }
const ColumnDescriptor* descr() const { return schema_->Column(column_index_); }
std::shared_ptr<FileMetaData> metadata() const { return reader_->metadata(); }
int column_index() const { return column_index_; }
protected:
int column_index_;
ParquetFileReader* reader_;
const SchemaDescriptor* schema_;
};
class AllRowGroupsIterator : public FileColumnIterator {
public:
explicit AllRowGroupsIterator(int column_index, ParquetFileReader* reader)
: FileColumnIterator(column_index, reader), next_row_group_(0) {}
std::unique_ptr<::parquet::PageReader> NextChunk() override {
std::unique_ptr<::parquet::PageReader> result;
if (next_row_group_ < reader_->metadata()->num_row_groups()) {
result = reader_->RowGroup(next_row_group_)->GetColumnPageReader(column_index_);
next_row_group_++;
} else {
result = nullptr;
}
return result;
}
private:
int next_row_group_;
};
class SingleRowGroupIterator : public FileColumnIterator {
public:
explicit SingleRowGroupIterator(int column_index, int row_group_number,
ParquetFileReader* reader)
: FileColumnIterator(column_index, reader),
row_group_number_(row_group_number),
done_(false) {}
std::unique_ptr<::parquet::PageReader> NextChunk() override {
if (done_) {
return nullptr;
}
auto result =
reader_->RowGroup(row_group_number_)->GetColumnPageReader(column_index_);
done_ = true;
return result;
}
private:
int row_group_number_;
bool done_;
};
class RowGroupRecordBatchReader : public ::arrow::RecordBatchReader {
public:
explicit RowGroupRecordBatchReader(const std::vector<int>& row_group_indices,
const std::vector<int>& column_indices,
std::shared_ptr<::arrow::Schema> schema,
FileReader* reader)
: row_group_indices_(row_group_indices),
column_indices_(column_indices),
schema_(schema),
file_reader_(reader),
next_row_group_(0) {}
~RowGroupRecordBatchReader() {}
std::shared_ptr<::arrow::Schema> schema() const override { return schema_; }
Status ReadNext(std::shared_ptr<::arrow::RecordBatch>* out) override {
if (table_ != nullptr) { // one row group has been loaded
std::shared_ptr<::arrow::RecordBatch> tmp;
RETURN_NOT_OK(table_batch_reader_->ReadNext(&tmp));
if (tmp != nullptr) { // some column chunks are left in table
*out = tmp;
return Status::OK();
} else { // the entire table is consumed
table_batch_reader_.reset();
table_.reset();
}
}
// all row groups has been consumed
if (next_row_group_ == row_group_indices_.size()) {
*out = nullptr;
return Status::OK();
}
RETURN_NOT_OK(file_reader_->ReadRowGroup(row_group_indices_[next_row_group_],
column_indices_, &table_));
next_row_group_++;
table_batch_reader_.reset(new ::arrow::TableBatchReader(*table_.get()));
return table_batch_reader_->ReadNext(out);
}
private:
std::vector<int> row_group_indices_;
std::vector<int> column_indices_;
std::shared_ptr<::arrow::Schema> schema_;
FileReader* file_reader_;
size_t next_row_group_;
std::shared_ptr<::arrow::Table> table_;
std::unique_ptr<::arrow::TableBatchReader> table_batch_reader_;
};
// ----------------------------------------------------------------------
// File reader implementation
class FileReader::Impl {
public:
Impl(MemoryPool* pool, std::unique_ptr<ParquetFileReader> reader)
: pool_(pool), reader_(std::move(reader)), num_threads_(1) {}
virtual ~Impl() {}
Status GetColumn(int i, std::unique_ptr<ColumnReader>* out);
Status ReadSchemaField(int i, std::shared_ptr<Array>* out);
Status ReadSchemaField(int i, const std::vector<int>& indices,
std::shared_ptr<Array>* out);
Status GetReaderForNode(int index, const Node* node, const std::vector<int>& indices,
int16_t def_level,
std::unique_ptr<ColumnReader::ColumnReaderImpl>* out);
Status ReadColumn(int i, std::shared_ptr<Array>* out);
Status ReadColumnChunk(int column_index, int row_group_index,
std::shared_ptr<Array>* out);
Status GetSchema(std::shared_ptr<::arrow::Schema>* out);
Status GetSchema(const std::vector<int>& indices,
std::shared_ptr<::arrow::Schema>* out);
Status ReadRowGroup(int row_group_index, const std::vector<int>& indices,
std::shared_ptr<::arrow::Table>* out);
Status ReadTable(const std::vector<int>& indices, std::shared_ptr<Table>* table);
Status ReadTable(std::shared_ptr<Table>* table);
Status ReadRowGroup(int i, std::shared_ptr<Table>* table);
bool CheckForFlatColumn(const ColumnDescriptor* descr);
bool CheckForFlatListColumn(const ColumnDescriptor* descr);
const ParquetFileReader* parquet_reader() const { return reader_.get(); }
int num_row_groups() const { return reader_->metadata()->num_row_groups(); }
int num_columns() const { return reader_->metadata()->num_columns(); }
void set_num_threads(int num_threads) { num_threads_ = num_threads; }
ParquetFileReader* reader() { return reader_.get(); }
private:
MemoryPool* pool_;
std::unique_ptr<ParquetFileReader> reader_;
int num_threads_;
};
class ColumnReader::ColumnReaderImpl {
public:
virtual ~ColumnReaderImpl() {}
virtual Status NextBatch(int64_t records_to_read, std::shared_ptr<Array>* out) = 0;
virtual Status GetDefLevels(const int16_t** data, size_t* length) = 0;
virtual Status GetRepLevels(const int16_t** data, size_t* length) = 0;
virtual const std::shared_ptr<Field> field() = 0;
};
// Reader implementation for primitive arrays
class PARQUET_NO_EXPORT PrimitiveImpl : public ColumnReader::ColumnReaderImpl {
public:
PrimitiveImpl(MemoryPool* pool, std::unique_ptr<FileColumnIterator> input)
: pool_(pool), input_(std::move(input)), descr_(input_->descr()) {
record_reader_ = RecordReader::Make(descr_, pool_);
DCHECK(NodeToField(*input_->descr()->schema_node(), &field_).ok());
NextRowGroup();
}
Status NextBatch(int64_t records_to_read, std::shared_ptr<Array>* out) override;
template <typename ParquetType>
Status WrapIntoListArray(std::shared_ptr<Array>* array);
Status GetDefLevels(const int16_t** data, size_t* length) override;
Status GetRepLevels(const int16_t** data, size_t* length) override;
const std::shared_ptr<Field> field() override { return field_; }
private:
void NextRowGroup();
MemoryPool* pool_;
std::unique_ptr<FileColumnIterator> input_;
const ColumnDescriptor* descr_;
std::shared_ptr<RecordReader> record_reader_;
std::shared_ptr<Field> field_;
};
// Reader implementation for struct array
class PARQUET_NO_EXPORT StructImpl : public ColumnReader::ColumnReaderImpl {
public:
explicit StructImpl(const std::vector<std::shared_ptr<ColumnReaderImpl>>& children,
int16_t struct_def_level, MemoryPool* pool, const Node* node)
: children_(children),
struct_def_level_(struct_def_level),
pool_(pool),
def_levels_buffer_(pool) {
InitField(node, children);
}
Status NextBatch(int64_t records_to_read, std::shared_ptr<Array>* out) override;
Status GetDefLevels(const int16_t** data, size_t* length) override;
Status GetRepLevels(const int16_t** data, size_t* length) override;
const std::shared_ptr<Field> field() override { return field_; }
private:
std::vector<std::shared_ptr<ColumnReaderImpl>> children_;
int16_t struct_def_level_;
MemoryPool* pool_;
std::shared_ptr<Field> field_;
PoolBuffer def_levels_buffer_;
Status DefLevelsToNullArray(std::shared_ptr<Buffer>* null_bitmap, int64_t* null_count);
void InitField(const Node* node,
const std::vector<std::shared_ptr<ColumnReaderImpl>>& children);
};
FileReader::FileReader(MemoryPool* pool, std::unique_ptr<ParquetFileReader> reader)
: impl_(new FileReader::Impl(pool, std::move(reader))) {}
FileReader::~FileReader() {}
Status FileReader::Impl::GetColumn(int i, std::unique_ptr<ColumnReader>* out) {
std::unique_ptr<FileColumnIterator> input(new AllRowGroupsIterator(i, reader_.get()));
std::unique_ptr<ColumnReader::ColumnReaderImpl> impl(
new PrimitiveImpl(pool_, std::move(input)));
*out = std::unique_ptr<ColumnReader>(new ColumnReader(std::move(impl)));
return Status::OK();
}
Status FileReader::Impl::GetReaderForNode(
int index, const Node* node, const std::vector<int>& indices, int16_t def_level,
std::unique_ptr<ColumnReader::ColumnReaderImpl>* out) {
*out = nullptr;
if (IsSimpleStruct(node)) {
const schema::GroupNode* group = static_cast<const schema::GroupNode*>(node);
std::vector<std::shared_ptr<ColumnReader::ColumnReaderImpl>> children;
for (int i = 0; i < group->field_count(); i++) {
std::unique_ptr<ColumnReader::ColumnReaderImpl> child_reader;
// TODO(itaiin): Remove the -1 index hack when all types of nested reads
// are supported. This currently just signals the lower level reader resolution
// to abort
RETURN_NOT_OK(GetReaderForNode(index, group->field(i).get(), indices,
static_cast<int16_t>(def_level + 1), &child_reader));
if (child_reader != nullptr) {
children.push_back(std::move(child_reader));
}
}
if (children.size() > 0) {
*out = std::unique_ptr<ColumnReader::ColumnReaderImpl>(
new StructImpl(children, def_level, pool_, node));
}
} else {
// This should be a flat field case - translate the field index to
// the correct column index by walking down to the leaf node
const Node* walker = node;
while (!walker->is_primitive()) {
DCHECK(walker->is_group());
auto group = static_cast<const GroupNode*>(walker);
if (group->field_count() != 1) {
return Status::NotImplemented("lists with structs are not supported.");
}
walker = group->field(0).get();
}
auto column_index = reader_->metadata()->schema()->ColumnIndex(*walker);
// If the index of the column is found then a reader for the coliumn is needed.
// Otherwise *out keeps the nullptr value.
if (std::find(indices.begin(), indices.end(), column_index) != indices.end()) {
std::unique_ptr<ColumnReader> reader;
RETURN_NOT_OK(GetColumn(column_index, &reader));
*out = std::move(reader->impl_);
}
}
return Status::OK();
}
Status FileReader::Impl::ReadSchemaField(int i, std::shared_ptr<Array>* out) {
std::vector<int> indices(reader_->metadata()->num_columns());
for (size_t j = 0; j < indices.size(); ++j) {
indices[j] = static_cast<int>(j);
}
return ReadSchemaField(i, indices, out);
}
Status FileReader::Impl::ReadSchemaField(int i, const std::vector<int>& indices,
std::shared_ptr<Array>* out) {
auto parquet_schema = reader_->metadata()->schema();
auto node = parquet_schema->group_node()->field(i).get();
std::unique_ptr<ColumnReader::ColumnReaderImpl> reader_impl;
RETURN_NOT_OK(GetReaderForNode(i, node, indices, 1, &reader_impl));
if (reader_impl == nullptr) {
*out = nullptr;
return Status::OK();
}
std::unique_ptr<ColumnReader> reader(new ColumnReader(std::move(reader_impl)));
// TODO(wesm): This calculation doesn't make much sense when we have repeated
// schema nodes
int64_t records_to_read = 0;
const FileMetaData& metadata = *reader_->metadata();
for (int j = 0; j < metadata.num_row_groups(); j++) {
records_to_read += metadata.RowGroup(j)->ColumnChunk(i)->num_values();
}
return reader->NextBatch(records_to_read, out);
}
Status FileReader::Impl::ReadColumn(int i, std::shared_ptr<Array>* out) {
std::unique_ptr<ColumnReader> flat_column_reader;
RETURN_NOT_OK(GetColumn(i, &flat_column_reader));
int64_t records_to_read = 0;
for (int j = 0; j < reader_->metadata()->num_row_groups(); j++) {
records_to_read += reader_->metadata()->RowGroup(j)->ColumnChunk(i)->num_values();
}
return flat_column_reader->NextBatch(records_to_read, out);
}
Status FileReader::Impl::GetSchema(const std::vector<int>& indices,
std::shared_ptr<::arrow::Schema>* out) {
auto descr = reader_->metadata()->schema();
auto parquet_key_value_metadata = reader_->metadata()->key_value_metadata();
return FromParquetSchema(descr, indices, parquet_key_value_metadata, out);
}
Status FileReader::Impl::ReadColumnChunk(int column_index, int row_group_index,
std::shared_ptr<Array>* out) {
auto rg_metadata = reader_->metadata()->RowGroup(row_group_index);
int64_t records_to_read = rg_metadata->ColumnChunk(column_index)->num_values();
std::unique_ptr<FileColumnIterator> input(
new SingleRowGroupIterator(column_index, row_group_index, reader_.get()));
std::unique_ptr<ColumnReader::ColumnReaderImpl> impl(
new PrimitiveImpl(pool_, std::move(input)));
ColumnReader flat_column_reader(std::move(impl));
std::shared_ptr<Array> array;
RETURN_NOT_OK(flat_column_reader.NextBatch(records_to_read, &array));
*out = array;
return Status::OK();
}
Status FileReader::Impl::ReadRowGroup(int row_group_index,
const std::vector<int>& indices,
std::shared_ptr<::arrow::Table>* out) {
std::shared_ptr<::arrow::Schema> schema;
RETURN_NOT_OK(GetSchema(indices, &schema));
auto rg_metadata = reader_->metadata()->RowGroup(row_group_index);
int num_columns = static_cast<int>(indices.size());
int nthreads = std::min<int>(num_threads_, num_columns);
std::vector<std::shared_ptr<Column>> columns(num_columns);
// TODO(wesm): Refactor to share more code with ReadTable
auto ReadColumnFunc = [&indices, &row_group_index, &schema, &columns, this](int i) {
int column_index = indices[i];
std::shared_ptr<Array> array;
RETURN_NOT_OK(ReadColumnChunk(column_index, row_group_index, &array));
columns[i] = std::make_shared<Column>(schema->field(i), array);
return Status::OK();
};
if (nthreads == 1) {
for (int i = 0; i < num_columns; i++) {
RETURN_NOT_OK(ReadColumnFunc(i));
}
} else {
RETURN_NOT_OK(ParallelFor(nthreads, num_columns, ReadColumnFunc));
}
*out = Table::Make(schema, columns);
return Status::OK();
}
Status FileReader::Impl::ReadTable(const std::vector<int>& indices,
std::shared_ptr<Table>* out) {
std::shared_ptr<::arrow::Schema> schema;
RETURN_NOT_OK(GetSchema(indices, &schema));
// We only need to read schema fields which have columns indicated
// in the indices vector
std::vector<int> field_indices;
if (!ColumnIndicesToFieldIndices(*reader_->metadata()->schema(), indices,
&field_indices)) {
return Status::Invalid("Invalid column index");
}
std::vector<std::shared_ptr<Column>> columns(field_indices.size());
auto ReadColumnFunc = [&indices, &field_indices, &schema, &columns, this](int i) {
std::shared_ptr<Array> array;
RETURN_NOT_OK(ReadSchemaField(field_indices[i], indices, &array));
columns[i] = std::make_shared<Column>(schema->field(i), array);
return Status::OK();
};
int num_fields = static_cast<int>(field_indices.size());
int nthreads = std::min<int>(num_threads_, num_fields);
if (nthreads == 1) {
for (int i = 0; i < num_fields; i++) {
RETURN_NOT_OK(ReadColumnFunc(i));
}
} else {
RETURN_NOT_OK(ParallelFor(nthreads, num_fields, ReadColumnFunc));
}
std::shared_ptr<Table> table = Table::Make(schema, columns);
RETURN_NOT_OK(table->Validate());
*out = table;
return Status::OK();
}
Status FileReader::Impl::ReadTable(std::shared_ptr<Table>* table) {
std::vector<int> indices(reader_->metadata()->num_columns());
for (size_t i = 0; i < indices.size(); ++i) {
indices[i] = static_cast<int>(i);
}
return ReadTable(indices, table);
}
Status FileReader::Impl::ReadRowGroup(int i, std::shared_ptr<Table>* table) {
std::vector<int> indices(reader_->metadata()->num_columns());
for (size_t i = 0; i < indices.size(); ++i) {
indices[i] = static_cast<int>(i);
}
return ReadRowGroup(i, indices, table);
}
// Static ctor
Status OpenFile(const std::shared_ptr<::arrow::io::ReadableFileInterface>& file,
MemoryPool* allocator, const ReaderProperties& props,
const std::shared_ptr<FileMetaData>& metadata,
std::unique_ptr<FileReader>* reader) {
std::unique_ptr<RandomAccessSource> io_wrapper(new ArrowInputFile(file));
std::unique_ptr<ParquetReader> pq_reader;
PARQUET_CATCH_NOT_OK(pq_reader =
ParquetReader::Open(std::move(io_wrapper), props, metadata));
reader->reset(new FileReader(allocator, std::move(pq_reader)));
return Status::OK();
}
Status OpenFile(const std::shared_ptr<::arrow::io::ReadableFileInterface>& file,
MemoryPool* allocator, std::unique_ptr<FileReader>* reader) {
return OpenFile(file, allocator, ::parquet::default_reader_properties(), nullptr,
reader);
}
Status FileReader::GetColumn(int i, std::unique_ptr<ColumnReader>* out) {
return impl_->GetColumn(i, out);
}
Status FileReader::GetSchema(const std::vector<int>& indices,
std::shared_ptr<::arrow::Schema>* out) {
return impl_->GetSchema(indices, out);
}
Status FileReader::ReadColumn(int i, std::shared_ptr<Array>* out) {
try {
return impl_->ReadColumn(i, out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
Status FileReader::ReadSchemaField(int i, std::shared_ptr<Array>* out) {
try {
return impl_->ReadSchemaField(i, out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
Status FileReader::GetRecordBatchReader(const std::vector<int>& row_group_indices,
std::shared_ptr<RecordBatchReader>* out) {
std::vector<int> indices(impl_->num_columns());
for (size_t j = 0; j < indices.size(); ++j) {
indices[j] = static_cast<int>(j);
}
return GetRecordBatchReader(row_group_indices, indices, out);
}
Status FileReader::GetRecordBatchReader(const std::vector<int>& row_group_indices,
const std::vector<int>& column_indices,
std::shared_ptr<RecordBatchReader>* out) {
// column indicies check
std::shared_ptr<::arrow::Schema> schema;
RETURN_NOT_OK(GetSchema(column_indices, &schema));
// row group indices check
int max_num = num_row_groups();
for (auto row_group_index : row_group_indices) {
if (row_group_index < 0 || row_group_index >= max_num) {
std::ostringstream ss;
ss << "Some index in row_group_indices is " << row_group_index
<< ", which is either < 0 or >= num_row_groups(" << max_num << ")";
return Status::Invalid(ss.str());
}
}
*out = std::make_shared<RowGroupRecordBatchReader>(row_group_indices, column_indices,
schema, this);
return Status::OK();
}
Status FileReader::ReadTable(std::shared_ptr<Table>* out) {
try {
return impl_->ReadTable(out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
Status FileReader::ReadTable(const std::vector<int>& indices,
std::shared_ptr<Table>* out) {
try {
return impl_->ReadTable(indices, out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
Status FileReader::ReadRowGroup(int i, std::shared_ptr<Table>* out) {
try {
return impl_->ReadRowGroup(i, out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
Status FileReader::ReadRowGroup(int i, const std::vector<int>& indices,
std::shared_ptr<Table>* out) {
try {
return impl_->ReadRowGroup(i, indices, out);
} catch (const ::parquet::ParquetException& e) {
return ::arrow::Status::IOError(e.what());
}
}
std::shared_ptr<RowGroupReader> FileReader::RowGroup(int row_group_index) {
return std::shared_ptr<RowGroupReader>(
new RowGroupReader(impl_.get(), row_group_index));
}
int FileReader::num_row_groups() const { return impl_->num_row_groups(); }
void FileReader::set_num_threads(int num_threads) { impl_->set_num_threads(num_threads); }
Status FileReader::ScanContents(std::vector<int> columns, const int32_t column_batch_size,
int64_t* num_rows) {
try {
*num_rows = ScanFileContents(columns, column_batch_size, impl_->reader());
return Status::OK();
} catch (const ::parquet::ParquetException& e) {
return Status::IOError(e.what());
}
}
const ParquetFileReader* FileReader::parquet_reader() const {
return impl_->parquet_reader();
}
template <typename ParquetType>
Status PrimitiveImpl::WrapIntoListArray(std::shared_ptr<Array>* array) {
const int16_t* def_levels = record_reader_->def_levels();
const int16_t* rep_levels = record_reader_->rep_levels();
const int64_t total_levels_read = record_reader_->levels_position();
std::shared_ptr<::arrow::Schema> arrow_schema;
RETURN_NOT_OK(FromParquetSchema(input_->schema(), {input_->column_index()},
input_->metadata()->key_value_metadata(),
&arrow_schema));
std::shared_ptr<Field> current_field = arrow_schema->field(0);
if (descr_->max_repetition_level() > 0) {
// Walk downwards to extract nullability
std::vector<bool> nullable;
std::vector<std::shared_ptr<::arrow::Int32Builder>> offset_builders;
std::vector<std::shared_ptr<::arrow::BooleanBuilder>> valid_bits_builders;
nullable.push_back(current_field->nullable());
while (current_field->type()->num_children() > 0) {
if (current_field->type()->num_children() > 1) {
return Status::NotImplemented(
"Fields with more than one child are not supported.");
} else {
if (current_field->type()->id() != ::arrow::Type::LIST) {
return Status::NotImplemented(
"Currently only nesting with Lists is supported.");
}
current_field = current_field->type()->child(0);
}
offset_builders.emplace_back(
std::make_shared<::arrow::Int32Builder>(::arrow::int32(), pool_));
valid_bits_builders.emplace_back(
std::make_shared<::arrow::BooleanBuilder>(::arrow::boolean(), pool_));
nullable.push_back(current_field->nullable());
}
int64_t list_depth = offset_builders.size();
// This describes the minimal definition that describes a level that
// reflects a value in the primitive values array.
int16_t values_def_level = descr_->max_definition_level();
if (nullable[nullable.size() - 1]) {
values_def_level--;
}
// The definition levels that are needed so that a list is declared
// as empty and not null.
std::vector<int16_t> empty_def_level(list_depth);
int def_level = 0;
for (int i = 0; i < list_depth; i++) {
if (nullable[i]) {
def_level++;
}
empty_def_level[i] = static_cast<int16_t>(def_level);
def_level++;
}
int32_t values_offset = 0;
std::vector<int64_t> null_counts(list_depth, 0);
for (int64_t i = 0; i < total_levels_read; i++) {
int16_t rep_level = rep_levels[i];
if (rep_level < descr_->max_repetition_level()) {
for (int64_t j = rep_level; j < list_depth; j++) {
if (j == (list_depth - 1)) {
RETURN_NOT_OK(offset_builders[j]->Append(values_offset));
} else {
RETURN_NOT_OK(offset_builders[j]->Append(
static_cast<int32_t>(offset_builders[j + 1]->length())));
}
if (((empty_def_level[j] - 1) == def_levels[i]) && (nullable[j])) {
RETURN_NOT_OK(valid_bits_builders[j]->Append(false));
null_counts[j]++;
break;
} else {
RETURN_NOT_OK(valid_bits_builders[j]->Append(true));
if (empty_def_level[j] == def_levels[i]) {
break;
}
}
}
}
if (def_levels[i] >= values_def_level) {
values_offset++;
}
}
// Add the final offset to all lists
for (int64_t j = 0; j < list_depth; j++) {
if (j == (list_depth - 1)) {
RETURN_NOT_OK(offset_builders[j]->Append(values_offset));
} else {
RETURN_NOT_OK(offset_builders[j]->Append(
static_cast<int32_t>(offset_builders[j + 1]->length())));
}
}
std::vector<std::shared_ptr<Buffer>> offsets;
std::vector<std::shared_ptr<Buffer>> valid_bits;
std::vector<int64_t> list_lengths;
for (int64_t j = 0; j < list_depth; j++) {
list_lengths.push_back(offset_builders[j]->length() - 1);
std::shared_ptr<Array> array;
RETURN_NOT_OK(offset_builders[j]->Finish(&array));
offsets.emplace_back(std::static_pointer_cast<Int32Array>(array)->values());
RETURN_NOT_OK(valid_bits_builders[j]->Finish(&array));
valid_bits.emplace_back(std::static_pointer_cast<BooleanArray>(array)->values());
}
std::shared_ptr<Array> output(*array);
for (int64_t j = list_depth - 1; j >= 0; j--) {
auto list_type =
::arrow::list(::arrow::field("item", output->type(), nullable[j + 1]));
output = std::make_shared<::arrow::ListArray>(
list_type, list_lengths[j], offsets[j], output, valid_bits[j], null_counts[j]);
}
*array = output;
}
return Status::OK();
}
template <typename ArrowType, typename ParquetType>
struct supports_fast_path_impl {
using ArrowCType = typename ArrowType::c_type;
using ParquetCType = typename ParquetType::c_type;
static constexpr bool value = std::is_same<ArrowCType, ParquetCType>::value;
};
template <typename ArrowType>
struct supports_fast_path_impl<ArrowType, ByteArrayType> {
static constexpr bool value = false;
};
template <typename ArrowType>
struct supports_fast_path_impl<ArrowType, FLBAType> {
static constexpr bool value = false;
};
template <typename ArrowType, typename ParquetType>
using supports_fast_path =
typename std::enable_if<supports_fast_path_impl<ArrowType, ParquetType>::value>::type;
template <typename ArrowType, typename ParquetType, typename Enable = void>
struct TransferFunctor {
using ArrowCType = typename ArrowType::c_type;
using ParquetCType = typename ParquetType::c_type;
Status operator()(RecordReader* reader, MemoryPool* pool,
const std::shared_ptr<::arrow::DataType>& type,
std::shared_ptr<Array>* out) {
static_assert(!std::is_same<ArrowType, ::arrow::Int32Type>::value,
"The fast path transfer functor should be used "
"for primitive values");
int64_t length = reader->values_written();
std::shared_ptr<Buffer> data;
RETURN_NOT_OK(::arrow::AllocateBuffer(pool, length * sizeof(ArrowCType), &data));
auto values = reinterpret_cast<const ParquetCType*>(reader->values());
auto out_ptr = reinterpret_cast<ArrowCType*>(data->mutable_data());
std::copy(values, values + length, out_ptr);
if (reader->nullable_values()) {
std::shared_ptr<PoolBuffer> is_valid = reader->ReleaseIsValid();
*out = std::make_shared<ArrayType<ArrowType>>(type, length, data, is_valid,
reader->null_count());
} else {
*out = std::make_shared<ArrayType<ArrowType>>(type, length, data);
}
return Status::OK();
}
};
template <typename ArrowType, typename ParquetType>
struct TransferFunctor<ArrowType, ParquetType,
supports_fast_path<ArrowType, ParquetType>> {
Status operator()(RecordReader* reader, MemoryPool* pool,
const std::shared_ptr<::arrow::DataType>& type,
std::shared_ptr<Array>* out) {
int64_t length = reader->values_written();
std::shared_ptr<PoolBuffer> values = reader->ReleaseValues();
if (reader->nullable_values()) {
std::shared_ptr<PoolBuffer> is_valid = reader->ReleaseIsValid();
*out = std::make_shared<ArrayType<ArrowType>>(type, length, values, is_valid,
reader->null_count());
} else {
*out = std::make_shared<ArrayType<ArrowType>>(type, length, values);
}
return Status::OK();
}
};
template <>
struct TransferFunctor<::arrow::BooleanType, BooleanType> {
Status operator()(RecordReader* reader, MemoryPool* pool,
const std::shared_ptr<::arrow::DataType>& type,
std::shared_ptr<Array>* out) {
int64_t length = reader->values_written();
std::shared_ptr<Buffer> data;
const int64_t buffer_size = BytesForBits(length);
RETURN_NOT_OK(::arrow::AllocateBuffer(pool, buffer_size, &data));
// Transfer boolean values to packed bitmap
auto values = reinterpret_cast<const bool*>(reader->values());
uint8_t* data_ptr = data->mutable_data();
memset(data_ptr, 0, buffer_size);
for (int64_t i = 0; i < length; i++) {
if (values[i]) {
::arrow::BitUtil::SetBit(data_ptr, i);
}
}
if (reader->nullable_values()) {
std::shared_ptr<PoolBuffer> is_valid = reader->ReleaseIsValid();
RETURN_NOT_OK(is_valid->Resize(BytesForBits(length), false));
*out = std::make_shared<BooleanArray>(type, length, data, is_valid,
reader->null_count());
} else {
*out = std::make_shared<BooleanArray>(type, length, data);
}
return Status::OK();
}
};
template <>
struct TransferFunctor<::arrow::TimestampType, Int96Type> {
Status operator()(RecordReader* reader, MemoryPool* pool,
const std::shared_ptr<::arrow::DataType>& type,
std::shared_ptr<Array>* out) {
int64_t length = reader->values_written();
auto values = reinterpret_cast<const Int96*>(reader->values());
std::shared_ptr<Buffer> data;
RETURN_NOT_OK(::arrow::AllocateBuffer(pool, length * sizeof(int64_t), &data));
auto data_ptr = reinterpret_cast<int64_t*>(data->mutable_data());
for (int64_t i = 0; i < length; i++) {
*data_ptr++ = impala_timestamp_to_nanoseconds(values[i]);
}
if (reader->nullable_values()) {
std::shared_ptr<PoolBuffer> is_valid = reader->ReleaseIsValid();
*out = std::make_shared<TimestampArray>(type, length, data, is_valid,
reader->null_count());
} else {
*out = std::make_shared<TimestampArray>(type, length, data);
}
return Status::OK();
}
};
template <>
struct TransferFunctor<::arrow::Date64Type, Int32Type> {
Status operator()(RecordReader* reader, MemoryPool* pool,
const std::shared_ptr<::arrow::DataType>& type,
std::shared_ptr<Array>* out) {
int64_t length = reader->values_written();
auto values = reinterpret_cast<const int32_t*>(reader->values());
std::shared_ptr<Buffer> data;
RETURN_NOT_OK(::arrow::AllocateBuffer(pool, length * sizeof(int64_t), &data));
auto out_ptr = reinterpret_cast<int64_t*>(data->mutable_data());
for (int64_t i = 0; i < length; i++) {
*out_ptr++ = static_cast<int64_t>(values[i]) * kMillisecondsInADay;
}
if (reader->nullable_values()) {
std::shared_ptr<PoolBuffer> is_valid = reader->ReleaseIsValid();
*out = std::make_shared<::arrow::Date64Array>(type, length, data, is_valid,
reader->null_count());
} else {
*out = std::make_shared<::arrow::Date64Array>(type, length, data);
}
return Status::OK();
}
};
template <typename ArrowType, typename ParquetType>
struct TransferFunctor<
ArrowType, ParquetType,
typename std::enable_if<std::is_same<ParquetType, ByteArrayType>::value ||
std::is_same<ParquetType, FLBAType>::value>::type> {
Status operator()(RecordReader* reader, MemoryPool* pool,
const std::shared_ptr<::arrow::DataType>& type,
std::shared_ptr<Array>* out) {
RETURN_NOT_OK(reader->builder()->Finish(out));
if (type->id() == ::arrow::Type::STRING) {
// Convert from BINARY type to STRING
auto new_data = (*out)->data()->Copy();
new_data->type = type;
*out = ::arrow::MakeArray(new_data);
}
return Status::OK();
}
};
static uint64_t BytesToInteger(const uint8_t* bytes, int32_t start, int32_t stop) {
using ::arrow::BitUtil::FromBigEndian;
const int32_t length = stop - start;
DCHECK_GE(length, 0);
DCHECK_LE(length, 8);
switch (length) {
case 0: