-
Notifications
You must be signed in to change notification settings - Fork 26
/
reader.rs
1267 lines (1113 loc) · 39.4 KB
/
reader.rs
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.
//! Contains file reader API and provides methods to access file metadata, row group
//! readers to read individual column chunks, or access record iterator.
use std::{
cell::RefCell, convert::TryFrom, fs::File, io::{self, Cursor, Read, Seek, SeekFrom}, path::Path, rc::Rc
};
use byteorder::{ByteOrder, LittleEndian};
use thrift::protocol::TCompactInputProtocol;
use crate::internal::{
basic::{ColumnOrder, Compression, Encoding, Type}, column::{
page::{Page, PageReader}, reader::{ColumnReader, ColumnReaderImpl}
}, compression::{create_codec, Codec}, errors::{ParquetError, Result}, file::{metadata::*, statistics, FOOTER_SIZE, PARQUET_MAGIC}, format::{ColumnOrder as TColumnOrder, FileMetaData as TFileMetaData, PageHeader, PageType}, record::{ParquetData, Predicate, RowIter}, schema::types::{self, SchemaDescriptor}, util::{
io::{BufReader, FileSource}, memory::ByteBufferPtr
}
};
// ----------------------------------------------------------------------
// APIs for file & row group readers
/// Parquet file reader API. With this, user can get metadata information about the
/// Parquet file, can get reader for each row group, and access record iterator.
pub trait FileReader {
type RowGroupReader: RowGroupReader;
/// Get metadata information about this file.
fn metadata(&self) -> ParquetMetaDataPtr;
/// Get the total number of row groups for this file.
fn num_row_groups(&self) -> usize;
/// Get the `i`th row group reader. Note this doesn't do bound check.
fn get_row_group(&self, i: usize) -> Result<Self::RowGroupReader>;
/// Get full iterator of `Row`s from a file (over all row groups).
///
/// [`Row`](`crate::internal::record::types::Row`) can be used for the type parameter `T` to
/// read as untyped rows. A tuple or a struct marked with `#[derive(Data)]` can
/// be used to read as typed rows.
///
/// Iterator will automatically load the next row group to advance.
///
/// Projected schema can be a subset of or equal to the file schema, when it is None,
/// full file schema is assumed.
fn get_row_iter<T>(self, projection: Option<Predicate>) -> Result<RowIter<Self, T>>
where
T: ParquetData,
Self: Sized,
{
RowIter::from_file(projection, self)
}
}
/// Enable APIs to be generic over values or references, including enabling
/// `get_row_iter<T>` to accept `&self` or `self`.
impl<'a, R> FileReader for &'a R
where
R: FileReader,
{
type RowGroupReader = R::RowGroupReader;
fn metadata(&self) -> ParquetMetaDataPtr {
<R as FileReader>::metadata(*self)
}
fn num_row_groups(&self) -> usize {
<R as FileReader>::num_row_groups(*self)
}
fn get_row_group(&self, i: usize) -> Result<Self::RowGroupReader> {
<R as FileReader>::get_row_group(*self, i)
}
}
impl<R> FileReader for Box<dyn FileReader<RowGroupReader = R>>
where
R: RowGroupReader,
{
type RowGroupReader = impl RowGroupReader;
fn metadata(&self) -> ParquetMetaDataPtr {
(**self).metadata()
}
fn num_row_groups(&self) -> usize {
(**self).num_row_groups()
}
fn get_row_group(&self, i: usize) -> Result<Self::RowGroupReader> {
(**self).get_row_group(i)
}
}
/// Parquet row group reader API. With this, user can get metadata information about the
/// row group, as well as readers for each individual column chunk.
pub trait RowGroupReader {
/// Get metadata information about this row group.
fn metadata(&self) -> RowGroupMetaDataPtr;
/// Get the total number of column chunks in this row group.
fn num_columns(&self) -> usize;
/// Get page reader for the `i`th column chunk.
fn get_column_page_reader(&self, i: usize) -> Result<Box<dyn PageReader>>;
/// Get value reader for the `i`th column chunk.
fn get_column_reader(&self, i: usize) -> Result<ColumnReader>;
/// Get iterator of `Row`s from this row group.
///
/// [`Row`](`crate::internal::record::types::Row`) can be used for the type parameter `T` to
/// read as untyped rows. A tuple or a struct marked with `#[derive(Data)]` can
/// be used to read as typed rows.
///
/// Projected schema can be a subset of or equal to the file schema, when it is None,
/// full file schema is assumed.
fn get_row_iter<T>(
&self, projection: Option<Predicate>,
) -> Result<RowIter<SerializedFileReader<Never>, T>>
where
T: ParquetData,
Self: Sized;
}
// ----------------------------------------------------------------------
// Serialized impl for file & row group readers
/// ParquetReader is the interface which needs to be fulfilled to be able to parse a
/// parquet source.
pub trait ParquetReader: Read + Seek {
/// Length should return the amount of bytes that implementor contains.
/// It's mainly used to read the metadata, which is at the end of the source.
/// Returns the amount of bytes of the inner source.
fn len(&self) -> u64;
}
impl ParquetReader for File {
fn len(&self) -> u64 {
self.metadata().map(|m| m.len()).unwrap_or(0u64)
}
}
impl<'a> ParquetReader for Cursor<&'a [u8]> {
fn len(&self) -> u64 {
self.get_ref().len() as u64
}
}
pub enum Never {}
impl Read for Never {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
unreachable!()
}
}
impl Seek for Never {
fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
unreachable!()
}
}
impl ParquetReader for Never {
fn len(&self) -> u64 {
unreachable!()
}
}
/// A serialized implementation for Parquet [`FileReader`].
pub struct SerializedFileReader<R: ParquetReader> {
buf: Rc<RefCell<BufReader<R>>>,
metadata: ParquetMetaDataPtr,
}
impl<R: ParquetReader> SerializedFileReader<R> {
/// Creates file reader from a Parquet file.
/// Returns error if Parquet file does not exist or is corrupt.
pub fn new(reader: R) -> Result<Self> {
let mut buf = Rc::new(RefCell::new(BufReader::with_capacity(256 * 1024, reader)));
let metadata = Self::parse_metadata(&mut buf)?;
Ok(Self {
buf,
metadata: Rc::new(metadata),
})
}
// Layout of Parquet file
// +---------------------------+---+-----+
// | Rest of file | B | A |
// +---------------------------+---+-----+
// where A: parquet footer, B: parquet metadata.
//
fn parse_metadata(buf: &mut Rc<RefCell<BufReader<R>>>) -> Result<ParquetMetaData> {
let buf = &mut *buf.borrow_mut();
let file_size = buf.len();
if file_size < (FOOTER_SIZE as u64) {
return Err(general_err!(
"Invalid Parquet file. Size is smaller than footer"
));
}
let mut footer_buffer: [u8; FOOTER_SIZE] = [0; FOOTER_SIZE];
let _ = buf.seek(SeekFrom::End(-(FOOTER_SIZE as i64)))?;
buf.read_exact(&mut footer_buffer)?;
if footer_buffer[4..] != PARQUET_MAGIC {
return Err(general_err!("Invalid Parquet file. Corrupt footer"));
}
let metadata_len = LittleEndian::read_i32(&footer_buffer[0..4]) as i64;
if metadata_len < 0 {
return Err(general_err!(
"Invalid Parquet file. Metadata length is less than zero ({})",
metadata_len
));
}
let metadata_start: i64 = file_size as i64 - FOOTER_SIZE as i64 - metadata_len;
if metadata_start < 0 {
return Err(general_err!(
"Invalid Parquet file. Metadata start is less than zero ({})",
metadata_start
));
}
let _ = buf.seek(SeekFrom::Start(metadata_start as u64))?;
let metadata_buf = buf.take(metadata_len as u64); //.into_inner();
// TODO: row group filtering
let mut prot = TCompactInputProtocol::new(metadata_buf);
let mut t_file_metadata: TFileMetaData = TFileMetaData::read_from_in_protocol(&mut prot)
.map_err(|e| ParquetError::General(format!("Could not parse metadata: {}", e)))?;
let schema = types::from_thrift(&mut t_file_metadata.schema)?;
let schema_descr = Rc::new(SchemaDescriptor::new(schema.clone()));
let mut row_groups = Vec::new();
for rg in t_file_metadata.row_groups {
row_groups.push(Rc::new(RowGroupMetaData::from_thrift(
schema_descr.clone(),
rg,
)?));
}
let column_orders = Self::parse_column_orders(t_file_metadata.column_orders, &schema_descr);
let file_metadata = FileMetaData::new(
t_file_metadata.version,
t_file_metadata.num_rows,
t_file_metadata.created_by,
schema,
schema_descr,
column_orders,
);
Ok(ParquetMetaData::new(file_metadata, row_groups))
}
/// Parses column orders from Thrift definition.
/// If no column orders are defined, returns `None`.
fn parse_column_orders(
t_column_orders: Option<Vec<TColumnOrder>>, schema_descr: &SchemaDescriptor,
) -> Option<Vec<ColumnOrder>> {
match t_column_orders {
Some(orders) => {
// Should always be the case
assert_eq!(
orders.len(),
schema_descr.num_columns(),
"Column order length mismatch"
);
let mut res = Vec::new();
for (i, column) in schema_descr.columns().iter().enumerate() {
match orders[i] {
TColumnOrder::TYPEORDER(_) => {
let sort_order = ColumnOrder::get_sort_order(
column.logical_type(),
column.physical_type(),
);
res.push(ColumnOrder::TypeDefinedOrder(sort_order));
}
}
}
Some(res)
}
None => None,
}
}
}
impl<R: 'static + ParquetReader> FileReader for SerializedFileReader<R> {
type RowGroupReader = SerializedRowGroupReader<R>;
fn metadata(&self) -> ParquetMetaDataPtr {
self.metadata.clone()
}
fn num_row_groups(&self) -> usize {
self.metadata.num_row_groups()
}
fn get_row_group(&self, i: usize) -> Result<Self::RowGroupReader> {
let row_group_metadata = self.metadata.row_group(i);
// Row groups should be processed sequentially.
// let f = self.buf.get_ref().clone();
Ok(SerializedRowGroupReader::new(
self.buf.clone(),
row_group_metadata,
))
}
}
impl TryFrom<File> for SerializedFileReader<File> {
type Error = ParquetError;
fn try_from(file: File) -> Result<Self> {
Self::new(file)
}
}
impl<'a> TryFrom<&'a Path> for SerializedFileReader<File> {
type Error = ParquetError;
fn try_from(path: &Path) -> Result<Self> {
let file = File::open(path)?;
Self::try_from(file)
}
}
impl TryFrom<String> for SerializedFileReader<File> {
type Error = ParquetError;
fn try_from(path: String) -> Result<Self> {
Self::try_from(Path::new(&path))
}
}
impl<'a> TryFrom<&'a str> for SerializedFileReader<File> {
type Error = ParquetError;
fn try_from(path: &str) -> Result<Self> {
Self::try_from(Path::new(&path))
}
}
// /// Conversion into a [`RowIter`](crate::internal::record::reader::RowIter)
// /// using the full file schema over all row groups.
// impl<T> IntoIterator for SerializedFileReader<File> {
// type Item = Row;
// type IntoIter = RowIter<'static,Self,T>;
// fn into_iter(self) -> Self::IntoIter {
// RowIter::from_file_into(Box::new(self))
// }
// }
/// A serialized implementation for Parquet [`RowGroupReader`].
pub struct SerializedRowGroupReader<R: ParquetReader> {
buf: Rc<RefCell<BufReader<R>>>,
metadata: RowGroupMetaDataPtr,
}
impl<R: 'static + ParquetReader> SerializedRowGroupReader<R> {
/// Creates new row group reader from a file and row group metadata.
fn new(buf: Rc<RefCell<BufReader<R>>>, metadata: RowGroupMetaDataPtr) -> Self {
Self { buf, metadata }
}
}
impl<R: 'static + ParquetReader> RowGroupReader for SerializedRowGroupReader<R> {
fn metadata(&self) -> RowGroupMetaDataPtr {
self.metadata.clone()
}
fn num_columns(&self) -> usize {
self.metadata.num_columns()
}
// TODO: fix PARQUET-816
fn get_column_page_reader(&self, i: usize) -> Result<Box<dyn PageReader>> {
let col = self.metadata.column(i);
let mut col_start = col.data_page_offset();
if col.has_dictionary_page() {
col_start = col.dictionary_page_offset().unwrap();
}
let col_length = col.compressed_size();
let file_chunk = FileSource::new(self.buf.clone(), col_start as u64, col_length as u64);
let page_reader = SerializedPageReader::new(
file_chunk,
col.num_values(),
col.compression(),
col.column_descr().physical_type(),
)?;
Ok(Box::new(page_reader))
}
fn get_column_reader(&self, i: usize) -> Result<ColumnReader> {
let schema_descr = self.metadata.schema_descr();
let col_descr = schema_descr.column(i);
let col_page_reader = self.get_column_page_reader(i)?;
let col_reader = match col_descr.physical_type() {
Type::Boolean => {
ColumnReader::BoolColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))
}
Type::Int32 => {
ColumnReader::Int32ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))
}
Type::Int64 => {
ColumnReader::Int64ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))
}
Type::Int96 => {
ColumnReader::Int96ColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))
}
Type::Float => {
ColumnReader::FloatColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))
}
Type::Double => {
ColumnReader::DoubleColumnReader(ColumnReaderImpl::new(col_descr, col_page_reader))
}
Type::ByteArray => ColumnReader::ByteArrayColumnReader(ColumnReaderImpl::new(
col_descr,
col_page_reader,
)),
Type::FixedLenByteArray => ColumnReader::FixedLenByteArrayColumnReader(
ColumnReaderImpl::new(col_descr, col_page_reader),
),
};
Ok(col_reader)
}
fn get_row_iter<T>(
&self, projection: Option<Predicate>,
) -> Result<RowIter<SerializedFileReader<Never>, T>>
where
T: ParquetData,
Self: Sized,
{
RowIter::from_row_group(projection, self)
}
}
/// A serialized implementation for Parquet [`PageReader`].
pub struct SerializedPageReader<T: Read> {
// The file source buffer which references exactly the bytes for the column trunk
// to be read by this page reader.
buf: T,
// The compression codec for this column chunk. Only set for non-PLAIN codec.
decompressor: Option<Box<dyn Codec>>,
// The number of values we have seen so far.
seen_num_values: i64,
// The number of total values in this column chunk.
total_num_values: i64,
// Column chunk type.
physical_type: Type,
}
impl<T: Read> SerializedPageReader<T> {
/// Creates a new serialized page reader from file source.
pub fn new(
buf: T, total_num_values: i64, compression: Compression, physical_type: Type,
) -> Result<Self> {
let decompressor = create_codec(compression)?;
let result = Self {
buf,
total_num_values,
seen_num_values: 0,
decompressor,
physical_type,
};
Ok(result)
}
/// Reads Page header from Thrift.
fn read_page_header(&mut self) -> Result<PageHeader> {
let mut prot = TCompactInputProtocol::new(&mut self.buf);
let page_header = PageHeader::read_from_in_protocol(&mut prot)?;
Ok(page_header)
}
}
impl<T: Read> PageReader for SerializedPageReader<T> {
fn get_next_page(&mut self) -> Result<Option<Page>> {
while self.seen_num_values < self.total_num_values {
let page_header = self.read_page_header()?;
// When processing data page v2, depending on enabled compression for the
// page, we should account for uncompressed data ('offset') of
// repetition and definition levels.
//
// We always use 0 offset for other pages other than v2, `true` flag means
// that compression will be applied if decompressor is defined
let mut offset: usize = 0;
let mut can_decompress = true;
if let Some(ref header_v2) = page_header.data_page_header_v2 {
offset = (header_v2.definition_levels_byte_length
+ header_v2.repetition_levels_byte_length) as usize;
// When is_compressed flag is missing the page is considered compressed
can_decompress = header_v2.is_compressed.unwrap_or(true);
}
let compressed_len = page_header.compressed_page_size as usize - offset;
let uncompressed_len = page_header.uncompressed_page_size as usize - offset;
// We still need to read all bytes from buffered stream
let mut buffer = vec![0; offset + compressed_len];
self.buf.read_exact(&mut buffer)?;
// TODO: page header could be huge because of statistics. We should set a
// maximum page header size and abort if that is exceeded.
if let Some(decompressor) = self.decompressor.as_mut() {
if can_decompress {
let mut decompressed_buffer = Vec::with_capacity(uncompressed_len);
let decompressed_size =
decompressor.decompress(&buffer[offset..], &mut decompressed_buffer)?;
if decompressed_size != uncompressed_len {
return Err(general_err!(
"Actual decompressed size doesn't match the expected one ({} vs {})",
decompressed_size,
uncompressed_len
));
}
if offset == 0 {
buffer = decompressed_buffer;
} else {
// Prepend saved offsets to the buffer
buffer.truncate(offset);
buffer.append(&mut decompressed_buffer);
}
}
}
let result = match page_header.type_ {
PageType::DictionaryPage => {
assert!(page_header.dictionary_page_header.is_some());
let dict_header = page_header.dictionary_page_header.as_ref().unwrap();
let is_sorted = dict_header.is_sorted.unwrap_or(false);
Page::DictionaryPage {
buf: ByteBufferPtr::new(buffer),
num_values: dict_header.num_values as u32,
encoding: Encoding::from(dict_header.encoding),
is_sorted,
}
}
PageType::DataPage => {
assert!(page_header.data_page_header.is_some());
let header = page_header.data_page_header.unwrap();
self.seen_num_values += header.num_values as i64;
Page::DataPage {
buf: ByteBufferPtr::new(buffer),
num_values: header.num_values as u32,
encoding: Encoding::from(header.encoding),
def_level_encoding: Encoding::from(header.definition_level_encoding),
rep_level_encoding: Encoding::from(header.repetition_level_encoding),
statistics: statistics::from_thrift(self.physical_type, header.statistics),
}
}
PageType::DataPageV2 => {
assert!(page_header.data_page_header_v2.is_some());
let header = page_header.data_page_header_v2.unwrap();
let is_compressed = header.is_compressed.unwrap_or(true);
self.seen_num_values += header.num_values as i64;
Page::DataPageV2 {
buf: ByteBufferPtr::new(buffer),
num_values: header.num_values as u32,
encoding: Encoding::from(header.encoding),
num_nulls: header.num_nulls as u32,
num_rows: header.num_rows as u32,
def_levels_byte_len: header.definition_levels_byte_length as u32,
rep_levels_byte_len: header.repetition_levels_byte_length as u32,
is_compressed,
statistics: statistics::from_thrift(self.physical_type, header.statistics),
}
}
_ => {
// For unknown page type (e.g., INDEX_PAGE), skip and read next.
continue;
}
};
return Ok(Some(result));
}
// We are at the end of this column chunk and no more page left. Return None.
Ok(None)
}
}
// /// Implementation of page iterator for parquet file.
// pub struct FilePageIterator {
// column_index: usize,
// row_group_indices: Box<Iterator<Item = usize>>,
// file_reader: Rc<FileReader<RowGroupReader=()>>,
// }
// impl FilePageIterator {
// /// Creates a page iterator for all row groups in file.
// pub fn new(column_index: usize, file_reader: Rc<FileReader<RowGroupReader=()>>) -> Result<Self> {
// let num_row_groups = file_reader.metadata().num_row_groups();
// let row_group_indices = Box::new(0..num_row_groups);
// Self::with_row_groups(column_index, row_group_indices, file_reader)
// }
// /// Create page iterator from parquet file reader with only some row groups.
// pub fn with_row_groups(
// column_index: usize,
// row_group_indices: Box<Iterator<Item = usize>>,
// file_reader: Rc<FileReader<RowGroupReader=()>>,
// ) -> Result<Self> {
// // Check that column_index is valid
// let num_columns = file_reader
// .metadata()
// .file_metadata()
// .schema_descr_ptr()
// .num_columns();
// if column_index >= num_columns {
// return Err(ParquetError::IndexOutOfBound(column_index, num_columns));
// }
// // We don't check iterators here because iterator may be infinite
// Ok(Self {
// column_index,
// row_group_indices,
// file_reader,
// })
// }
// }
// impl Iterator for FilePageIterator {
// type Item = Result<Box<PageReader>>;
// fn next(&mut self) -> Option<Result<Box<PageReader>>> {
// self.row_group_indices.next().map(|row_group_index| {
// self.file_reader
// .get_row_group(row_group_index)
// .and_then(|r| r.get_column_page_reader(self.column_index))
// })
// }
// }
// impl PageIterator for FilePageIterator {
// fn schema(&mut self) -> Result<SchemaDescPtr> {
// Ok(self
// .file_reader
// .metadata()
// .file_metadata()
// .schema_descr_ptr())
// }
// fn column_schema(&mut self) -> Result<ColumnDescPtr> {
// self.schema().map(|s| s.column(self.column_index))
// }
// }
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use test::Bencher;
use amadeus_types::{DateTime, Group};
use super::*;
use crate::internal::{
basic::SortOrder, column::reader::{get_typed_column_reader, ColumnReader}, data_type::*, file::reader::{FileReader, RowGroupReader, SerializedFileReader}, format::TypeDefinedOrder, schema::types::{ColumnPath, Type as SchemaType}, util::test_common::{get_temp_file, get_test_file, get_test_path}
};
#[test]
fn test_file_reader_metadata_size_smaller_than_footer() {
let test_file = get_temp_file("corrupt-1.parquet", &[]);
let reader_result = SerializedFileReader::new(test_file);
assert!(reader_result.is_err());
assert_eq!(
reader_result.err().unwrap(),
general_err!("Invalid Parquet file. Size is smaller than footer")
);
}
// use crate::internal::record::types::Group;
// #[test]
// fn test_cursor_and_file_has_the_same_behaviour() {
// let path = get_test_path("alltypes_plain.parquet");
// let buffer = include_bytes!(path);
// let cursor = Cursor::new(buffer.as_ref());
// let test_file = get_test_file("alltypes_plain.parquet");
// let read_from_file = SerializedFileReader::new(test_file).unwrap();
// let read_from_cursor = SerializedFileReader::new(cursor).unwrap();
// let file_iter = read_from_file.get_row_iter::<Group>(None).unwrap();
// let cursor_iter = read_from_cursor.get_row_iter::<Group>(None).unwrap();
// assert!(file_iter.eq(cursor_iter));
// }
#[test]
fn test_file_reader_metadata_corrupt_footer() {
let test_file = get_temp_file("corrupt-2.parquet", &[1, 2, 3, 4, 5, 6, 7, 8]);
let reader_result = SerializedFileReader::new(test_file);
assert!(reader_result.is_err());
assert_eq!(
reader_result.err().unwrap(),
general_err!("Invalid Parquet file. Corrupt footer")
);
}
#[test]
fn test_file_reader_metadata_invalid_length() {
let test_file = get_temp_file("corrupt-3.parquet", &[0, 0, 0, 255, b'P', b'A', b'R', b'1']);
let reader_result = SerializedFileReader::new(test_file);
assert!(reader_result.is_err());
assert_eq!(
reader_result.err().unwrap(),
general_err!("Invalid Parquet file. Metadata length is less than zero (-16777216)")
);
}
#[test]
fn test_file_reader_metadata_invalid_start() {
let test_file = get_temp_file("corrupt-4.parquet", &[255, 0, 0, 0, b'P', b'A', b'R', b'1']);
let reader_result = SerializedFileReader::new(test_file);
assert!(reader_result.is_err());
assert_eq!(
reader_result.err().unwrap(),
general_err!("Invalid Parquet file. Metadata start is less than zero (-255)")
);
}
#[test]
fn test_file_reader_column_orders_parse() {
// Define simple schema, we do not need to provide logical types.
let mut fields = vec![
Rc::new(
SchemaType::primitive_type_builder("col1", Type::Int32)
.build()
.unwrap(),
),
Rc::new(
SchemaType::primitive_type_builder("col2", Type::Float)
.build()
.unwrap(),
),
];
let schema = SchemaType::group_type_builder("schema")
.with_fields(&mut fields)
.build()
.unwrap();
let schema_descr = SchemaDescriptor::new(Rc::new(schema));
let t_column_orders = Some(vec![
TColumnOrder::TYPEORDER(TypeDefinedOrder::new()),
TColumnOrder::TYPEORDER(TypeDefinedOrder::new()),
]);
assert_eq!(
SerializedFileReader::<File>::parse_column_orders(t_column_orders, &schema_descr),
Some(vec![
ColumnOrder::TypeDefinedOrder(SortOrder::Signed),
ColumnOrder::TypeDefinedOrder(SortOrder::Signed)
])
);
// Test when no column orders are defined.
assert_eq!(
SerializedFileReader::<File>::parse_column_orders(None, &schema_descr),
None
);
}
#[test]
#[should_panic(expected = "Column order length mismatch")]
fn test_file_reader_column_orders_len_mismatch() {
let schema = SchemaType::group_type_builder("schema").build().unwrap();
let schema_descr = SchemaDescriptor::new(Rc::new(schema));
let t_column_orders = Some(vec![TColumnOrder::TYPEORDER(TypeDefinedOrder::new())]);
let _ = SerializedFileReader::<File>::parse_column_orders(t_column_orders, &schema_descr);
}
#[test]
fn test_file_reader_try_from() {
// Valid file path
let test_file = get_test_file("alltypes_plain.parquet");
let test_path_buf = get_test_path("alltypes_plain.parquet");
let test_path = test_path_buf.as_path();
let test_path_str = test_path.to_str().unwrap();
let reader = SerializedFileReader::try_from(test_file);
assert!(reader.is_ok());
let reader = SerializedFileReader::try_from(test_path);
assert!(reader.is_ok());
let reader = SerializedFileReader::try_from(test_path_str);
assert!(reader.is_ok());
let reader = SerializedFileReader::try_from(test_path_str.to_string());
assert!(reader.is_ok());
// Invalid file path
let test_path = Path::new("invalid.parquet");
let test_path_str = test_path.to_str().unwrap();
let reader = SerializedFileReader::try_from(test_path);
assert!(reader.is_err());
let reader = SerializedFileReader::try_from(test_path_str);
assert!(reader.is_err());
let reader = SerializedFileReader::try_from(test_path_str.to_string());
assert!(reader.is_err());
}
// #[test]
// fn test_file_reader_into_iter() -> Result<()> {
// let path = get_test_path("alltypes_plain.parquet");
// let vec = vec![path.clone(), path.clone()]
// .iter()
// .map(|p| SerializedFileReader::try_from(p.as_path()).unwrap())
// .flat_map(|r| r.into_iter())
// .flat_map(|r| r.get_int(0))
// .collect::<Vec<_>>();
// // rows in the parquet file are not sorted by "id"
// // each file contains [id:4, id:5, id:6, id:7, id:2, id:3, id:0, id:1]
// assert_eq!(vec, vec![4, 5, 6, 7, 2, 3, 0, 1, 4, 5, 6, 7, 2, 3, 0, 1]);
// Ok(())
// }
// #[test]
// fn test_file_reader_into_iter_project() -> Result<()> {
// let path = get_test_path("alltypes_plain.parquet");
// let result = vec![path]
// .iter()
// .map(|p| SerializedFileReader::try_from(p.as_path()).unwrap())
// .flat_map(|r| {
// let schema = "message schema { OPTIONAL INT32 id; }";
// let proj = parse_message_type(&schema).ok();
// r.into_iter().project(proj).unwrap()
// })
// .map(|r| format!("{}", r))
// .collect::<Vec<_>>()
// .join(",");
// assert_eq!(
// result,
// "{id: 4},{id: 5},{id: 6},{id: 7},{id: 2},{id: 3},{id: 0},{id: 1}"
// );
// Ok(())
// }
#[test]
fn test_reuse_file_chunk() {
// This test covers the case of maintaining the correct start position in a file
// stream for each column reader after initializing and moving to the next one
// (without necessarily reading the entire column).
let test_file = get_test_file("alltypes_plain.parquet");
let reader = SerializedFileReader::new(test_file).unwrap();
let row_group = reader.get_row_group(0).unwrap();
let mut page_readers = Vec::new();
for i in 0..row_group.num_columns() {
page_readers.push(row_group.get_column_page_reader(i).unwrap());
}
// Now buffer each col reader, we do not expect any failures like:
// General("underlying Thrift error: end of file")
for mut page_reader in page_readers {
assert!(page_reader.get_next_page().is_ok());
}
}
#[test]
fn test_file_reader() {
let test_file = get_test_file("alltypes_plain.parquet");
let reader_result = SerializedFileReader::new(test_file);
assert!(reader_result.is_ok());
let reader = reader_result.unwrap();
// Test contents in Parquet metadata
let metadata = reader.metadata();
assert_eq!(metadata.num_row_groups(), 1);
// Test contents in file metadata
let file_metadata = metadata.file_metadata();
assert!(file_metadata.created_by().is_some());
assert_eq!(
file_metadata.created_by().as_ref().unwrap(),
"impala version 1.3.0-INTERNAL (build 8a48ddb1eff84592b3fc06bc6f51ec120e1fffc9)"
);
assert_eq!(file_metadata.num_rows(), 8);
assert_eq!(file_metadata.version(), 1);
assert_eq!(file_metadata.column_orders(), None);
// Test contents in row group metadata
let row_group_metadata = metadata.row_group(0);
assert_eq!(row_group_metadata.num_columns(), 11);
assert_eq!(row_group_metadata.num_rows(), 8);
assert_eq!(row_group_metadata.total_byte_size(), 671);
// Check each column order
for i in 0..row_group_metadata.num_columns() {
assert_eq!(file_metadata.column_order(i), ColumnOrder::Undefined);
}
// Test row group reader
let row_group_reader_result = reader.get_row_group(0);
assert!(row_group_reader_result.is_ok());
let row_group_reader = row_group_reader_result.unwrap();
assert_eq!(
row_group_reader.num_columns(),
row_group_metadata.num_columns()
);
assert_eq!(
row_group_reader.metadata().total_byte_size(),
row_group_metadata.total_byte_size()
);
// Test page readers
// TODO: test for every column
let page_reader_0_result = row_group_reader.get_column_page_reader(0);
assert!(page_reader_0_result.is_ok());
let mut page_reader_0: Box<dyn PageReader> = page_reader_0_result.unwrap();
let mut page_count = 0;
while let Ok(Some(page)) = page_reader_0.get_next_page() {
let is_expected_page = match page {
Page::DictionaryPage {
buf,
num_values,
encoding,
is_sorted,
} => {
assert_eq!(buf.len(), 32);
assert_eq!(num_values, 8);
assert_eq!(encoding, Encoding::PlainDictionary);
assert_eq!(is_sorted, false);
true
}
Page::DataPage {
buf,
num_values,
encoding,
def_level_encoding,
rep_level_encoding,
statistics,
} => {
assert_eq!(buf.len(), 11);
assert_eq!(num_values, 8);
assert_eq!(encoding, Encoding::PlainDictionary);
assert_eq!(def_level_encoding, Encoding::Rle);
assert_eq!(rep_level_encoding, Encoding::BitPacked);
assert!(statistics.is_none());
true
}
_ => false,
};
assert!(is_expected_page);
page_count += 1;
}
assert_eq!(page_count, 2);
}
#[test]
fn test_file_reader_datapage_v2() {
let test_file = get_test_file("datapage_v2.snappy.parquet");
let reader_result = SerializedFileReader::new(test_file);
assert!(reader_result.is_ok());
let reader = reader_result.unwrap();
// Test contents in Parquet metadata
let metadata = reader.metadata();
assert_eq!(metadata.num_row_groups(), 1);
// Test contents in file metadata
let file_metadata = metadata.file_metadata();
assert!(file_metadata.created_by().is_some());
assert_eq!(
file_metadata.created_by().as_ref().unwrap(),
"parquet-mr version 1.8.1 (build 4aba4dae7bb0d4edbcf7923ae1339f28fd3f7fcf)"
);
assert_eq!(file_metadata.num_rows(), 5);
assert_eq!(file_metadata.version(), 1);
assert_eq!(file_metadata.column_orders(), None);
let row_group_metadata = metadata.row_group(0);
// Check each column order
for i in 0..row_group_metadata.num_columns() {