parquet/arrow/array_reader/mod.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Logic for reading into arrow arrays: [`ArrayReader`] and [`RowGroups`]
19
20use crate::errors::Result;
21use arrow_array::ArrayRef;
22use arrow_schema::DataType as ArrowType;
23use std::any::Any;
24use std::sync::Arc;
25
26use crate::arrow::record_reader::GenericRecordReader;
27use crate::arrow::record_reader::buffer::ValuesBuffer;
28use crate::column::page::PageIterator;
29use crate::column::reader::decoder::ColumnValueDecoder;
30use crate::file::metadata::ParquetMetaData;
31use crate::file::reader::{FilePageIterator, FileReader};
32
33mod builder;
34mod byte_array;
35mod byte_array_dictionary;
36mod byte_view_array;
37mod cached_array_reader;
38mod empty_array;
39mod fixed_len_byte_array;
40mod fixed_size_list_array;
41mod list_array;
42mod list_view_array;
43mod map_array;
44mod null_array;
45mod primitive_array;
46mod row_group_cache;
47mod row_group_index;
48mod row_number;
49mod struct_array;
50
51#[cfg(test)]
52pub(crate) mod test_util;
53
54// Note that this crate is public under the `experimental` feature flag.
55use crate::file::metadata::RowGroupMetaData;
56pub use builder::{ArrayReaderBuilder, CacheOptions, CacheOptionsBuilder};
57pub use byte_array::make_byte_array_reader;
58pub use byte_array_dictionary::make_byte_array_dictionary_reader;
59#[cfg_attr(not(feature = "experimental"), expect(unused_imports))]
60pub use byte_view_array::make_byte_view_array_reader;
61#[cfg_attr(not(feature = "experimental"), expect(unused_imports))]
62pub use fixed_len_byte_array::make_fixed_len_byte_array_reader;
63pub use fixed_size_list_array::FixedSizeListArrayReader;
64pub use list_array::ListArrayReader;
65pub use list_view_array::ListViewArrayReader;
66pub use map_array::MapArrayReader;
67pub use null_array::NullArrayReader;
68pub use primitive_array::PrimitiveArrayReader;
69pub use row_group_cache::RowGroupCache;
70pub use struct_array::StructArrayReader;
71
72/// Reads Parquet data into Arrow Arrays.
73///
74/// This is an internal implementation detail of the Parquet reader, and is not
75/// intended for public use.
76///
77/// This is the core trait for reading encoded Parquet data directly into Arrow
78/// Arrays efficiently. There are various specializations of this trait for
79/// different combinations of encodings and arrays, such as
80/// [`PrimitiveArrayReader`], [`ListArrayReader`], etc.
81///
82/// Each `ArrayReader` logically contains the following state
83/// 1. A handle to the encoded Parquet data
84/// 2. An in progress buffered Array
85///
86/// Data can either be read in batches using [`ArrayReader::next_batch`] or
87/// incrementally using [`ArrayReader::read_records`] and [`ArrayReader::skip_records`].
88pub trait ArrayReader: Send {
89 // TODO: this function is never used, and the trait is not public. Perhaps this should be
90 // removed.
91 fn as_any(&self) -> &dyn Any;
92
93 /// Returns the arrow type of this array reader.
94 fn get_data_type(&self) -> &ArrowType;
95
96 /// Reads at most `batch_size` records into an arrow array and return it.
97 #[cfg(any(feature = "experimental", test))]
98 fn next_batch(&mut self, batch_size: usize) -> Result<ArrayRef> {
99 self.read_records(batch_size)?;
100 self.consume_batch()
101 }
102
103 /// Reads at most `batch_size` records' bytes into buffer
104 ///
105 /// Returns the number of records read, which can be less than `batch_size` if
106 /// pages is exhausted.
107 fn read_records(&mut self, batch_size: usize) -> Result<usize>;
108
109 /// Consume all currently stored buffer data
110 /// into an arrow array and return it.
111 fn consume_batch(&mut self) -> Result<ArrayRef>;
112
113 /// Skips over `num_records` records, returning the number of rows skipped
114 ///
115 /// Note that calling `skip_records` with large values of `num_records` is
116 /// efficient as it avoids decoding data into the the in-progress array.
117 /// However, there is overhead to calling this function, so for small values of
118 /// `num_records`, it can be more efficient to call read_records and apply
119 /// a filter to the resulting array.
120 fn skip_records(&mut self, num_records: usize) -> Result<usize>;
121
122 /// If this array has a non-zero definition level, i.e. has a nullable parent
123 /// array, returns the definition levels of data from the last call of `next_batch`
124 ///
125 /// Otherwise returns None
126 ///
127 /// This is used by parent [`ArrayReader`] to compute their null bitmaps
128 fn get_def_levels(&self) -> Option<&[i16]>;
129
130 /// If this array has a non-zero repetition level, i.e. has a repeated parent
131 /// array, returns the repetition levels of data from the last call of `next_batch`
132 ///
133 /// Otherwise returns None
134 ///
135 /// This is used by parent [`ArrayReader`] to compute their array offsets
136 fn get_rep_levels(&self) -> Option<&[i16]>;
137
138 /// Returns the maximum definition level for this reader as defined by
139 /// the Parquet schema. For leaf readers this is the column's max def level;
140 /// for composite readers it is the level at which the composite itself is
141 /// fully defined.
142 ///
143 /// The default panics. Synthetic readers that are not backed by a Parquet
144 /// column (e.g. row-number or empty-struct readers) may rely on this
145 /// default because they are never used as children of schema-driven
146 /// composite readers (list, map, struct), which are the only callers.
147 fn max_def_level(&self) -> i16 {
148 panic!("max_def_level called on a reader that does not track definition levels")
149 }
150}
151
152/// Interface for reading data pages from the columns of one or more RowGroups.
153pub trait RowGroups {
154 /// Get the number of rows in this collection
155 fn num_rows(&self) -> usize;
156
157 /// Returns a [`PageIterator`] for all pages in the specified column chunk
158 /// across all row groups in this collection.
159 fn column_chunks(&self, i: usize) -> Result<Box<dyn PageIterator>>;
160
161 /// Returns an iterator over the row groups in this collection
162 ///
163 /// Note this may not include all row groups in [`Self::metadata`].
164 fn row_groups(&self) -> Box<dyn Iterator<Item = &RowGroupMetaData> + '_>;
165
166 /// Returns the parquet metadata
167 fn metadata(&self) -> &ParquetMetaData;
168}
169
170impl RowGroups for Arc<dyn FileReader> {
171 fn num_rows(&self) -> usize {
172 FileReader::metadata(self.as_ref())
173 .file_metadata()
174 .num_rows() as usize
175 }
176
177 fn column_chunks(&self, column_index: usize) -> Result<Box<dyn PageIterator>> {
178 let iterator = FilePageIterator::new(column_index, Arc::clone(self))?;
179 Ok(Box::new(iterator))
180 }
181
182 fn row_groups(&self) -> Box<dyn Iterator<Item = &RowGroupMetaData> + '_> {
183 Box::new(FileReader::metadata(self.as_ref()).row_groups().iter())
184 }
185
186 fn metadata(&self) -> &ParquetMetaData {
187 FileReader::metadata(self.as_ref())
188 }
189}
190
191/// Uses `record_reader` to read up to `batch_size` records from `pages`
192///
193/// Returns the number of records read, which can be less than `batch_size` if
194/// pages is exhausted.
195fn read_records<V, CV>(
196 record_reader: &mut GenericRecordReader<V, CV>,
197 pages: &mut dyn PageIterator,
198 batch_size: usize,
199) -> Result<usize>
200where
201 V: ValuesBuffer,
202 CV: ColumnValueDecoder<Buffer = V>,
203{
204 let mut records_read = 0usize;
205 while records_read < batch_size {
206 let records_to_read = batch_size - records_read;
207
208 let records_read_once = record_reader.read_records(records_to_read)?;
209 records_read += records_read_once;
210
211 // Record reader exhausted
212 if records_read_once < records_to_read {
213 if let Some(page_reader) = pages.next() {
214 // Read from new page reader (i.e. column chunk)
215 record_reader.set_page_reader(page_reader?)?;
216 } else {
217 // Page reader also exhausted
218 break;
219 }
220 }
221 }
222 Ok(records_read)
223}
224
225/// Uses `record_reader` to skip up to `batch_size` records from `pages`
226///
227/// Returns the number of records skipped, which can be less than `batch_size` if
228/// pages is exhausted
229fn skip_records<V, CV>(
230 record_reader: &mut GenericRecordReader<V, CV>,
231 pages: &mut dyn PageIterator,
232 batch_size: usize,
233) -> Result<usize>
234where
235 V: ValuesBuffer,
236 CV: ColumnValueDecoder<Buffer = V>,
237{
238 let mut records_skipped = 0usize;
239 while records_skipped < batch_size {
240 let records_to_read = batch_size - records_skipped;
241
242 let records_skipped_once = record_reader.skip_records(records_to_read)?;
243 records_skipped += records_skipped_once;
244
245 // Record reader exhausted
246 if records_skipped_once < records_to_read {
247 if let Some(page_reader) = pages.next() {
248 // Read from new page reader (i.e. column chunk)
249 record_reader.set_page_reader(page_reader?)?;
250 } else {
251 // Page reader also exhausted
252 break;
253 }
254 }
255 }
256 Ok(records_skipped)
257}