parquet/file/page_index/
index_reader.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//! Support for reading [`Index`] and [`PageLocation`] from parquet metadata.
19
20use crate::basic::Type;
21use crate::data_type::Int96;
22use crate::errors::ParquetError;
23use crate::file::metadata::ColumnChunkMetaData;
24use crate::file::page_index::index::{Index, NativeIndex};
25use crate::file::page_index::offset_index::OffsetIndexMetaData;
26use crate::file::reader::ChunkReader;
27use crate::format::{ColumnIndex, OffsetIndex, PageLocation};
28use crate::thrift::{TCompactSliceInputProtocol, TSerializable};
29use std::ops::Range;
30
31/// Computes the covering range of two optional ranges
32///
33/// For example `acc_range(Some(7..9), Some(1..3)) = Some(1..9)`
34pub(crate) fn acc_range(a: Option<Range<usize>>, b: Option<Range<usize>>) -> Option<Range<usize>> {
35    match (a, b) {
36        (Some(a), Some(b)) => Some(a.start.min(b.start)..a.end.max(b.end)),
37        (None, x) | (x, None) => x,
38    }
39}
40
41/// Reads per-column [`Index`] for all columns of a row group by
42/// decoding [`ColumnIndex`] .
43///
44/// Returns a vector of `index[column_number]`.
45///
46/// Returns `None` if this row group does not contain a [`ColumnIndex`].
47///
48/// See [Page Index Documentation] for more details.
49///
50/// [Page Index Documentation]: https://github.com/apache/parquet-format/blob/master/PageIndex.md
51pub fn read_columns_indexes<R: ChunkReader>(
52    reader: &R,
53    chunks: &[ColumnChunkMetaData],
54) -> Result<Option<Vec<Index>>, ParquetError> {
55    let fetch = chunks
56        .iter()
57        .fold(None, |range, c| acc_range(range, c.column_index_range()));
58
59    let fetch = match fetch {
60        Some(r) => r,
61        None => return Ok(None),
62    };
63
64    let bytes = reader.get_bytes(fetch.start as _, fetch.end - fetch.start)?;
65    let get = |r: Range<usize>| &bytes[(r.start - fetch.start)..(r.end - fetch.start)];
66
67    Some(
68        chunks
69            .iter()
70            .map(|c| match c.column_index_range() {
71                Some(r) => decode_column_index(get(r), c.column_type()),
72                None => Ok(Index::NONE),
73            })
74            .collect(),
75    )
76    .transpose()
77}
78
79/// Reads [`OffsetIndex`],  per-page [`PageLocation`] for all columns of a row
80/// group.
81///
82/// Returns a vector of `location[column_number][page_number]`
83///
84/// Return an empty vector if this row group does not contain an
85/// [`OffsetIndex]`.
86///
87/// See [Page Index Documentation] for more details.
88///
89/// [Page Index Documentation]: https://github.com/apache/parquet-format/blob/master/PageIndex.md
90#[deprecated(since = "53.0.0", note = "Use read_offset_indexes")]
91pub fn read_pages_locations<R: ChunkReader>(
92    reader: &R,
93    chunks: &[ColumnChunkMetaData],
94) -> Result<Vec<Vec<PageLocation>>, ParquetError> {
95    let fetch = chunks
96        .iter()
97        .fold(None, |range, c| acc_range(range, c.offset_index_range()));
98
99    let fetch = match fetch {
100        Some(r) => r,
101        None => return Ok(vec![]),
102    };
103
104    let bytes = reader.get_bytes(fetch.start as _, fetch.end - fetch.start)?;
105    let get = |r: Range<usize>| &bytes[(r.start - fetch.start)..(r.end - fetch.start)];
106
107    chunks
108        .iter()
109        .map(|c| match c.offset_index_range() {
110            Some(r) => decode_page_locations(get(r)),
111            None => Err(general_err!("missing offset index")),
112        })
113        .collect()
114}
115
116/// Reads per-column [`OffsetIndexMetaData`] for all columns of a row group by
117/// decoding [`OffsetIndex`] .
118///
119/// Returns a vector of `offset_index[column_number]`.
120///
121/// Returns `None` if this row group does not contain an [`OffsetIndex`].
122///
123/// See [Page Index Documentation] for more details.
124///
125/// [Page Index Documentation]: https://github.com/apache/parquet-format/blob/master/PageIndex.md
126pub fn read_offset_indexes<R: ChunkReader>(
127    reader: &R,
128    chunks: &[ColumnChunkMetaData],
129) -> Result<Option<Vec<OffsetIndexMetaData>>, ParquetError> {
130    let fetch = chunks
131        .iter()
132        .fold(None, |range, c| acc_range(range, c.offset_index_range()));
133
134    let fetch = match fetch {
135        Some(r) => r,
136        None => return Ok(None),
137    };
138
139    let bytes = reader.get_bytes(fetch.start as _, fetch.end - fetch.start)?;
140    let get = |r: Range<usize>| &bytes[(r.start - fetch.start)..(r.end - fetch.start)];
141
142    Some(
143        chunks
144            .iter()
145            .map(|c| match c.offset_index_range() {
146                Some(r) => decode_offset_index(get(r)),
147                None => Err(general_err!("missing offset index")),
148            })
149            .collect(),
150    )
151    .transpose()
152}
153
154pub(crate) fn decode_offset_index(data: &[u8]) -> Result<OffsetIndexMetaData, ParquetError> {
155    let mut prot = TCompactSliceInputProtocol::new(data);
156    let offset = OffsetIndex::read_from_in_protocol(&mut prot)?;
157    OffsetIndexMetaData::try_new(offset)
158}
159
160pub(crate) fn decode_page_locations(data: &[u8]) -> Result<Vec<PageLocation>, ParquetError> {
161    let mut prot = TCompactSliceInputProtocol::new(data);
162    let offset = OffsetIndex::read_from_in_protocol(&mut prot)?;
163    Ok(offset.page_locations)
164}
165
166pub(crate) fn decode_column_index(data: &[u8], column_type: Type) -> Result<Index, ParquetError> {
167    let mut prot = TCompactSliceInputProtocol::new(data);
168
169    let index = ColumnIndex::read_from_in_protocol(&mut prot)?;
170
171    let index = match column_type {
172        Type::BOOLEAN => Index::BOOLEAN(NativeIndex::<bool>::try_new(index)?),
173        Type::INT32 => Index::INT32(NativeIndex::<i32>::try_new(index)?),
174        Type::INT64 => Index::INT64(NativeIndex::<i64>::try_new(index)?),
175        Type::INT96 => Index::INT96(NativeIndex::<Int96>::try_new(index)?),
176        Type::FLOAT => Index::FLOAT(NativeIndex::<f32>::try_new(index)?),
177        Type::DOUBLE => Index::DOUBLE(NativeIndex::<f64>::try_new(index)?),
178        Type::BYTE_ARRAY => Index::BYTE_ARRAY(NativeIndex::try_new(index)?),
179        Type::FIXED_LEN_BYTE_ARRAY => Index::FIXED_LEN_BYTE_ARRAY(NativeIndex::try_new(index)?),
180    };
181
182    Ok(index)
183}