Skip to main content

parquet/file/metadata/
page_index.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Page Index structures for efficient page-level skipping
6//!
7//! Row-group and column counts are each limited to `i32::MAX`, consistent with the
8//! Parquet/Thrift metadata format. Populated entries are stored sparsely, subject to platform
9//! address-space and available-memory limits.
10
11use crate::errors::{ParquetError, Result};
12use crate::file::metadata::column_chunk::{ColumnChunkEntries, ColumnChunkMap};
13use crate::file::metadata::memory::HeapSize;
14use crate::file::page_index::{
15    column_index::ColumnIndexMetaData,
16    offset_index::{OffsetIndexMetaData, PageLocation},
17};
18use std::sync::Arc;
19
20/// Trait for accessing Parquet [Page Index] data for efficient page-level skipping
21///
22/// The [Page Index] enables query engines to skip irrelevant data pages during scans,
23/// significantly improving I/O efficiency. It provides access to two complementary
24/// structures:
25///
26/// * **[`ColumnIndex`]**: Per-page min/max value boundaries that enable predicate-based
27///   page filtering. Allows determining which pages might contain rows matching a query
28///   predicate without reading the actual data pages.
29///
30/// * **[`OffsetIndex`]**: Physical locations and sizes of data pages, plus the first row
31///   index of each page. Used to locate and read only the pages identified as relevant
32///   by the ColumnIndex.
33///
34/// Together, these indexes enable:
35/// - Single-row lookups reading only one data page per column (on sorted columns)
36/// - Range scans reading only pages containing values in the query range
37/// - Efficient cross-column filtering by skipping corresponding row ranges
38///
39/// # Structure
40///
41/// Within a Parquet file, both indexes are organized as a two-level structure, with
42/// indexes arranged first by row group, and then column. The [`ColumnChunkMetaData`]
43/// contains pointers to the indexes for a given column chunk, so they may be
44/// populated piecemeal. This trait allows access by row group index and column number
45/// ([Self::column_index], [Self::offset_index]). Access by row group is provided by
46/// [`RowGroupPageIndex`].
47///
48/// Each entry is `Option<T>` because:
49/// - The entire page index might be absent (old files, disabled during write)
50/// - Individual columns might lack indexes (unsupported types, statistics disabled)
51///
52/// # Example: Checking if Page Index is Available
53///
54/// ```
55/// use parquet::file::metadata::ParquetMetaData;
56/// # use parquet::errors::Result;
57///
58/// fn check_page_index_availability(metadata: &ParquetMetaData) -> Result<()> {
59///     if let Some(page_index) = metadata.page_index() {
60///         println!("Page index present:");
61///         println!("  Has offset indexes: {}", page_index.has_offset_indexes());
62///         println!("  Has column indexes: {}", page_index.has_column_indexes());
63///
64///         // Check availability for first row group, first column
65///         if let Some(col_idx) = page_index.column_index(0, 0) {
66///             println!("  Column index found for row group 0, column 0");
67///             println!("    Number of pages: {}", col_idx.num_pages());
68///         }
69///
70///         if let Some(offset_idx) = page_index.offset_index(0, 0) {
71///             println!("  Offset index found for row group 0, column 0");
72///             println!("    Number of pages: {}", offset_idx.page_locations().len());
73///         }
74///     } else {
75///         println!("No page index available");
76///     }
77///     Ok(())
78/// }
79/// ```
80///
81/// # Example: Using Page Index for Predicate Pushdown
82///
83/// ```
84/// use parquet::file::metadata::ParquetMetaData;
85/// use parquet::file::page_index::column_index::ColumnIndexMetaData;
86/// # use parquet::errors::Result;
87///
88/// /// Identifies which pages in a column might contain values >= min_value
89/// fn find_relevant_pages(
90///     metadata: &ParquetMetaData,
91///     row_group_idx: usize,
92///     column_idx: usize,
93///     min_value: i32,
94/// ) -> Vec<usize> {
95///     let mut relevant_pages = Vec::new();
96///
97///     let Some(page_index) = metadata.page_index() else {
98///         // No page index - must read all pages
99///         return relevant_pages;
100///     };
101///
102///     let Some(column_index) = page_index.column_index(row_group_idx, column_idx) else {
103///         // No column index - must read all pages
104///         return relevant_pages;
105///     };
106///
107///     // Check each page's statistics
108///     match column_index {
109///         ColumnIndexMetaData::INT32(index) => {
110///             for (page_num, max_value) in index.max_values_iter().enumerate() {
111///                 // Page might contain matching rows if its max >= our min
112///                 if let Some(max) = max_value {
113///                     if *max >= min_value {
114///                         relevant_pages.push(page_num);
115///                     }
116///                 }
117///             }
118///         }
119///         _ => {
120///             // Wrong column type - read all pages
121///         }
122///     }
123///
124///     relevant_pages
125/// }
126/// ```
127///
128/// # Caching the Page Index
129///
130/// The Page Index can be much larger than the rest of the metadata, so some
131/// systems may want to incrementally fetch or assemble the relevant data. See
132/// [`page_index_cache.rs`] for an example of an incremental page index cache.
133///
134/// [Page Index]: https://parquet.apache.org/docs/file-format/pageindex/
135/// [`ColumnIndex`]: crate::file::page_index::column_index::ColumnIndexMetaData
136/// [`OffsetIndex`]: crate::file::page_index::offset_index::OffsetIndexMetaData
137/// [`ColumnChunkMetaData`]: crate::file::metadata::ColumnChunkMetaData
138/// [`page_index_cache.rs`]: https://github.com/apache/arrow-rs/blob/main/parquet/examples/page_index_cache.rs
139pub trait PageIndexProvider: Send + Sync + std::fmt::Debug {
140    /// Returns `true` if offset index structures are available via this provider
141    ///
142    /// This indicates whether [`OffsetIndexMetaData`] structures were loaded or created.
143    /// Returns `true` even if some individual columns lack offset indexes.
144    /// This should return `false` if all calls to [`Self::offset_index`] will return `None`.
145    ///
146    /// This does *not* indicate if the underlying Parquet file contains offset indexes.
147    ///
148    /// To check if a specific column has an offset index, use [`Self::offset_index`].
149    fn has_offset_indexes(&self) -> bool;
150
151    /// Returns `true` if column index structures are available via this provider
152    ///
153    /// This indicates whether [`ColumnIndexMetaData`] structures were loaded or created.
154    /// Returns `true` even if some individual columns lack column indexes.
155    /// This should return `false` if all calls to [`Self::column_index`] will return `None`.
156    ///
157    /// This does *not* indicate if the underlying Parquet file contains column indexes.
158    ///
159    /// To check if a specific column has a column index, use [`Self::column_index`].
160    fn has_column_indexes(&self) -> bool;
161
162    /// Returns `true` if both the offset and column index structures are present
163    ///
164    /// This is equivalent to both [`Self::has_offset_indexes`] and [`Self::has_column_indexes`]
165    /// returning `true`.
166    fn is_complete(&self) -> bool {
167        self.has_column_indexes() && self.has_offset_indexes()
168    }
169
170    /// Returns the column index for a specific row group and column
171    ///
172    /// This is the primary method for accessing page-level min/max statistics
173    /// used in predicate pushdown and page skipping optimizations.
174    ///
175    /// Returns:
176    /// * `Some(&ColumnIndexMetaData)` - Column index is available with statistics
177    /// * `None` - Index unavailable (not loaded, row group/column out of bounds, or no statistics)
178    ///
179    /// For access to the indexes for a specific row group, use [`RowGroupPageIndex`].
180    fn column_index(&self, row_group_idx: usize, column_idx: usize)
181    -> Option<&ColumnIndexMetaData>;
182
183    /// Returns the offset index for a specific row group and column
184    ///
185    /// This provides physical locations and sizes of data pages, enabling:
186    /// - Direct seeking to specific pages identified by column index filtering
187    /// - Reading only relevant pages without scanning entire column chunks
188    /// - Efficient cross-column row-based filtering
189    ///
190    /// Returns:
191    /// * `Some(&OffsetIndexMetaData)` - Offset index is available
192    /// * `None` - Index unavailable (not loaded, row group/column out of bounds)
193    ///
194    /// For access to the indexes for a specific row group, use [`RowGroupPageIndex`].
195    fn offset_index(&self, row_group_idx: usize, column_idx: usize)
196    -> Option<&OffsetIndexMetaData>;
197
198    /// Returns the expected number of data pages for a specific column chunk
199    ///
200    /// This count includes only data pages, not dictionary pages or other metadata pages.
201    ///
202    /// Returns:
203    /// * `Some(usize)` - Number of data pages if any index is available
204    /// * `None` - No index information available for this column
205    fn num_data_pages(&self, row_group_idx: usize, column_idx: usize) -> Option<usize> {
206        match self.offset_index(row_group_idx, column_idx) {
207            Some(offset_index) => Some(offset_index.page_locations.len()),
208            None => Some(self.column_index(row_group_idx, column_idx)?.num_pages() as usize),
209        }
210    }
211
212    /// Returns the physical locations of all data pages in a column chunk
213    ///
214    /// Each [`PageLocation`] contains:
215    /// - File offset where the page begins
216    /// - Compressed size of the page
217    /// - First row index within the row group
218    ///
219    /// This enables direct I/O to specific pages without reading the entire column chunk.
220    ///
221    /// Returns:
222    /// * `Some(&Vec<PageLocation>)` - Vector of page locations if offset index exists
223    /// * `None` - Offset index not available
224    fn page_locations(
225        &self,
226        row_group_idx: usize,
227        column_idx: usize,
228    ) -> Option<&Vec<PageLocation>> {
229        Some(
230            self.offset_index(row_group_idx, column_idx)?
231                .page_locations(),
232        )
233    }
234
235    /// Returns a reference to the trait object as `&dyn Any` for downcasting
236    ///
237    /// This allows downcasting to concrete types when needed (e.g., for serialization)
238    fn as_any(&self) -> &dyn std::any::Any;
239}
240
241/// Provides convenient access to page index data for a specific row group
242///
243/// This struct wraps a [`PageIndexProvider`] and automatically applies the row group
244/// index, simplifying access to column and offset indexes for a single row group.
245/// It is primarily used by readers to avoid repeatedly passing the row group index
246/// when accessing page-level metadata.
247///
248/// # Example
249///
250/// ```
251/// use parquet::file::metadata::ParquetMetaData;
252/// # use parquet::errors::Result;
253///
254/// fn process_row_group_pages(metadata: &ParquetMetaData, row_group_idx: usize) -> Result<()> {
255///     // Create a row-group-specific view of the page index
256///     let rg_page_index = metadata.page_index_for_row_group(row_group_idx);
257///
258///     // Now access column indexes without specifying row_group_idx each time
259///     for col_idx in 0..metadata.file_metadata().schema_descr().num_columns() {
260///         if let Some(col_idx_data) = rg_page_index.column_index(col_idx) {
261///             println!("Column {} has {} pages", col_idx, col_idx_data.num_pages());
262///         }
263///     }
264///     Ok(())
265/// }
266/// ```
267#[derive(Debug)]
268pub struct RowGroupPageIndex {
269    row_group_idx: usize,
270    page_index: Option<Arc<dyn PageIndexProvider>>,
271}
272
273impl RowGroupPageIndex {
274    /// Creates a new [`RowGroupPageIndex`] for the specified row group
275    ///
276    /// # Arguments
277    ///
278    /// * `row_group_idx` - The index of the row group within the file
279    /// * `page_index` - Optional page index provider containing the index data
280    pub fn new(row_group_idx: usize, page_index: Option<Arc<dyn PageIndexProvider>>) -> Self {
281        Self {
282            row_group_idx,
283            page_index,
284        }
285    }
286
287    /// Returns the column index for a specific column in this row group
288    ///
289    /// This is a convenience method that wraps [`PageIndexProvider::column_index`],
290    /// automatically applying the row group index stored in this struct.
291    ///
292    /// # Returns
293    ///
294    /// * `Some(&ColumnIndexMetaData)` - Column index is available with page-level statistics
295    /// * `None` - Index unavailable (no page index, column out of bounds, or no statistics)
296    ///
297    /// # See Also
298    ///
299    /// * [`PageIndexProvider::column_index`] for more details on column indexes
300    pub fn column_index(&self, column_idx: usize) -> Option<&ColumnIndexMetaData> {
301        self.page_index
302            .as_ref()?
303            .column_index(self.row_group_idx, column_idx)
304    }
305
306    /// Returns the offset index for a specific column in this row group
307    ///
308    /// This is a convenience method that wraps [`PageIndexProvider::offset_index`],
309    /// automatically applying the row group index stored in this struct.
310    ///
311    /// # Returns
312    ///
313    /// * `Some(&OffsetIndexMetaData)` - Offset index is available with page locations
314    /// * `None` - Index unavailable (no page index, column out of bounds)
315    ///
316    /// # See Also
317    ///
318    /// * [`PageIndexProvider::offset_index`] for more details on offset indexes
319    pub fn offset_index(&self, column_idx: usize) -> Option<&OffsetIndexMetaData> {
320        self.page_index
321            .as_ref()?
322            .offset_index(self.row_group_idx, column_idx)
323    }
324
325    /// Returns the physical locations of all data pages for a specific column in this row group
326    ///
327    /// This is a convenience method that wraps [`PageIndexProvider::page_locations`],
328    /// automatically applying the row group index stored in this struct.
329    ///
330    /// This enables direct I/O to specific pages without reading the entire column chunk.
331    ///
332    /// # Returns
333    ///
334    /// * `Some(&Vec<PageLocation>)` - Vector of page locations if offset index exists
335    /// * `None` - Offset index not available for this column
336    ///
337    /// # See Also
338    ///
339    /// * [`PageIndexProvider::page_locations`] for more details on page locations
340    pub fn page_locations(&self, column_idx: usize) -> Option<&Vec<PageLocation>> {
341        Some(self.offset_index(column_idx)?.page_locations())
342    }
343
344    /// Returns the expected number of data pages for a specific column in this row group
345    ///
346    /// This count includes only data pages, not dictionary pages or other metadata pages.
347    ///
348    /// This is a convenience method that wraps [`PageIndexProvider::num_data_pages`],
349    /// automatically applying the row group index stored in this struct.
350    ///
351    /// # Returns
352    ///
353    /// * `Some(usize)` - Number of data pages if any index is available
354    /// * `None` - No index information available for this column
355    ///
356    /// # See Also
357    ///
358    /// * [`PageIndexProvider::num_data_pages`] for more details
359    pub fn num_data_pages(&self, column_idx: usize) -> Option<usize> {
360        self.page_index
361            .as_ref()?
362            .num_data_pages(self.row_group_idx, column_idx)
363    }
364}
365
366/// Struct to encapsulate the Parquet [Page Index]
367///
368/// This struct provides a sparse, immutable representation of the Page Index, stored in row-major
369/// order and keyed by row group and column index. It owns its populated column and offset index
370/// metadata. Use [`Self::into_index_entries`] to move that metadata into an external cache.
371/// It is used internally by this crate when assembling and writing the Page Index, and is the
372/// default implementation of the [`PageIndexProvider`] contained in the [`ParquetMetaData`].
373///
374/// # Example: Constructing a synthetic `PageIndex`
375///
376/// This example builds a [`ParquetMetaData`] for a file with a single row
377/// group containing a single `BYTE_ARRAY` column with one data page, and
378/// attaches a matching `PageIndex`, as might be done in tests that
379/// exercise page-level statistics handling.
380///
381/// ```
382/// # use std::sync::Arc;
383/// # use parquet::basic::{BoundaryOrder, Type as PhysicalType};
384/// # use parquet::file::metadata::{
385/// #     ColumnChunkMetaData, ColumnIndexBuilder, FileMetaData, OffsetIndexBuilder,
386/// #     ParquetMetaData, RowGroupMetaData,
387/// # };
388/// # use parquet::file::metadata::page_index::PageIndexBuilder;
389/// # use parquet::schema::types::{SchemaDescriptor, Type};
390/// // Create metadata for a file with a single row group containing a
391/// // single BYTE_ARRAY column "s" with three values
392/// # let schema = Arc::new(SchemaDescriptor::new(Arc::new(
393/// #     Type::group_type_builder("schema")
394/// #         .with_fields(vec![Arc::new(
395/// #             Type::primitive_type_builder("s", PhysicalType::BYTE_ARRAY)
396/// #                 .build()
397/// #                 .unwrap(),
398/// #         )])
399/// #         .build()
400/// #         .unwrap(),
401/// # )));
402/// # let column = ColumnChunkMetaData::builder(schema.column(0))
403/// #     .set_num_values(3)
404/// #     .build()
405/// #     .unwrap();
406/// # let row_group = RowGroupMetaData::builder(Arc::clone(&schema))
407/// #     .set_num_rows(3)
408/// #     .set_column_metadata(vec![column])
409/// #     .build()
410/// #     .unwrap();
411/// let file_metadata = FileMetaData::new(1, 3, None, None, schema, None);
412/// let metadata = ParquetMetaData::new(file_metadata, vec![row_group]);
413///
414/// // Build a column index with min/max statistics for the single page
415/// let mut column_index = ColumnIndexBuilder::new(PhysicalType::BYTE_ARRAY);
416/// column_index.append(false, b"az".to_vec(), b"b".to_vec(), 0, None);
417/// column_index.set_boundary_order(BoundaryOrder::ASCENDING);
418/// let column_index = column_index.build().unwrap();
419///
420/// // Build an offset index recording the location of the single page
421/// let mut offset_index = OffsetIndexBuilder::new();
422/// offset_index.append_row_count(3);
423/// offset_index.append_offset_and_size(4, 100);
424/// let offset_index = offset_index.build();
425///
426/// // Assemble the PageIndex (one entry per row group, each with one
427/// // entry per column) and attach it to the metadata
428/// let mut page_index = PageIndexBuilder::try_new(1, 1).unwrap();
429/// page_index
430///     .try_put_column_index(column_index, 0, 0)
431///     .unwrap();
432/// page_index
433///     .try_put_offset_index(offset_index, 0, 0)
434///     .unwrap();
435/// let page_index = page_index.build();
436/// let metadata = metadata
437///     .into_builder()
438///     .set_page_index(Some(Arc::new(page_index)))
439///     .build();
440/// assert!(metadata.page_index().unwrap().is_complete());
441/// ```
442///
443/// [Page Index]: https://parquet.apache.org/docs/file-format/pageindex/
444/// [`ColumnIndex`]: crate::file::page_index::column_index::ColumnIndexMetaData
445/// [`OffsetIndex`]: crate::file::page_index::offset_index::OffsetIndexMetaData
446/// [`ParquetMetaData`]: crate::file::metadata::ParquetMetaData
447#[derive(Debug, Clone, PartialEq)]
448pub struct PageIndex {
449    column_indexes: Option<ColumnChunkEntries<ColumnIndexMetaData>>,
450    offset_indexes: Option<ColumnChunkEntries<OffsetIndexMetaData>>,
451}
452
453impl PageIndex {
454    pub(crate) fn try_new(
455        column_indexes: Option<Vec<Vec<Option<ColumnIndexMetaData>>>>,
456        offset_indexes: Option<Vec<Vec<Option<OffsetIndexMetaData>>>>,
457    ) -> Result<Self> {
458        let column_indexes = column_indexes
459            .map(ColumnChunkEntries::try_from_rows)
460            .transpose()?;
461        let offset_indexes = offset_indexes
462            .map(ColumnChunkEntries::try_from_rows)
463            .transpose()?;
464
465        Ok(Self::from_entries(column_indexes, offset_indexes))
466    }
467
468    pub(crate) fn from_entries(
469        column_indexes: Option<ColumnChunkEntries<ColumnIndexMetaData>>,
470        offset_indexes: Option<ColumnChunkEntries<OffsetIndexMetaData>>,
471    ) -> Self {
472        Self {
473            column_indexes: column_indexes.filter(|indexes| !indexes.is_empty()),
474            offset_indexes: offset_indexes.filter(|indexes| !indexes.is_empty()),
475        }
476    }
477
478    /// Convert this `PageIndex` into a [`PageIndexBuilder`]
479    pub fn into_builder(self) -> PageIndexBuilder {
480        self.try_into_builder()
481            .unwrap_or_else(|err| panic!("failed to thaw page index: {err}"))
482    }
483
484    /// Fallibly converts this `PageIndex` into a [`PageIndexBuilder`].
485    pub fn try_into_builder(self) -> Result<PageIndexBuilder> {
486        PageIndexBuilder::try_new_from(self)
487    }
488
489    /// Consumes this page index and returns its populated column and offset index entries.
490    ///
491    /// Each entry contains its `(row_group_index, column_index)` coordinate and owned index
492    /// metadata. This can be used to move parsed indexes into a cache without cloning their
493    /// metadata. Entries are returned in row-major order.
494    ///
495    /// For an example of using this to populate an incremental page index
496    /// cache, see [`page_index_cache.rs`]
497    ///
498    /// [`page_index_cache.rs`]: https://github.com/apache/arrow-rs/blob/main/parquet/examples/page_index_cache.rs
499    #[expect(clippy::type_complexity)]
500    pub fn into_index_entries(
501        self,
502    ) -> (
503        impl Iterator<Item = ((usize, usize), ColumnIndexMetaData)>,
504        impl Iterator<Item = ((usize, usize), OffsetIndexMetaData)>,
505    ) {
506        let column_indexes = self
507            .column_indexes
508            .into_iter()
509            .flat_map(ColumnChunkEntries::into_iter)
510            .map(|(key, index)| (key.coordinates(), index));
511        let offset_indexes = self
512            .offset_indexes
513            .into_iter()
514            .flat_map(ColumnChunkEntries::into_iter)
515            .map(|(key, index)| (key.coordinates(), index));
516
517        (column_indexes, offset_indexes)
518    }
519}
520
521impl PageIndexProvider for PageIndex {
522    fn has_offset_indexes(&self) -> bool {
523        self.offset_indexes.is_some()
524    }
525
526    fn has_column_indexes(&self) -> bool {
527        self.column_indexes.is_some()
528    }
529
530    fn column_index(
531        &self,
532        row_group_idx: usize,
533        column_idx: usize,
534    ) -> Option<&ColumnIndexMetaData> {
535        self.column_indexes
536            .as_ref()?
537            .get(row_group_idx, column_idx)
538            .ok()?
539    }
540
541    fn offset_index(
542        &self,
543        row_group_idx: usize,
544        column_idx: usize,
545    ) -> Option<&OffsetIndexMetaData> {
546        self.offset_indexes
547            .as_ref()?
548            .get(row_group_idx, column_idx)
549            .ok()?
550    }
551
552    fn as_any(&self) -> &dyn std::any::Any {
553        self
554    }
555}
556
557impl HeapSize for PageIndex {
558    fn heap_size(&self) -> usize {
559        self.column_indexes.heap_size() + self.offset_indexes.heap_size()
560    }
561}
562
563/// Builder for constructing [`PageIndex`] structures
564///
565/// It supports:
566/// - Populating column indexes for predicate columns (for page filtering)
567/// - Populating offset indexes for projected columns (for direct I/O)
568/// - Automatic conversion of empty structures to `None` to save memory
569#[derive(Default, Debug)]
570pub struct PageIndexBuilder {
571    column_indexes: Option<ColumnChunkMap<ColumnIndexMetaData>>,
572    offset_indexes: Option<ColumnChunkMap<OffsetIndexMetaData>>,
573}
574
575impl PageIndexBuilder {
576    /// Creates a new [`PageIndexBuilder`] for the specified number of row groups and columns.
577    ///
578    /// The dimensions are used to validate inserted coordinates. Storage is allocated only for
579    /// entries populated using
580    /// [`try_put_column_index`](Self::try_put_column_index) and
581    /// [`try_put_offset_index`](Self::try_put_offset_index).
582    ///
583    /// # Panics
584    ///
585    /// Panics if either dimension exceeds `i32::MAX`, the maximum collection size representable
586    /// by Thrift.
587    ///
588    /// Use [`try_new`](Self::try_new) for a fallible alternative.
589    pub fn new(num_row_groups: usize, num_columns: usize) -> Self {
590        Self::try_new(num_row_groups, num_columns).expect("invalid page index dimensions")
591    }
592
593    /// Attempts to create a new [`PageIndexBuilder`] for the specified number of row groups and columns.
594    ///
595    /// # Errors
596    ///
597    /// Returns an error if either dimension exceeds `i32::MAX`, the maximum collection size
598    /// representable by Thrift.
599    pub fn try_new(num_row_groups: usize, num_columns: usize) -> Result<Self> {
600        Ok(Self {
601            column_indexes: Some(ColumnChunkMap::try_new(num_row_groups, num_columns)?),
602            offset_indexes: Some(ColumnChunkMap::try_new(num_row_groups, num_columns)?),
603        })
604    }
605
606    /// Creates a new [`PageIndexBuilder`] from an existing [`PageIndex`]
607    ///
608    /// This takes ownership of the index structures from the provided [`PageIndex`],
609    /// allowing them to be modified and rebuilt. Useful for updating existing page indexes.
610    pub(crate) fn new_from(page_index: PageIndex) -> Self {
611        Self::try_new_from(page_index)
612            .unwrap_or_else(|err| panic!("failed to thaw page index: {err}"))
613    }
614
615    fn try_new_from(page_index: PageIndex) -> Result<Self> {
616        Ok(Self {
617            column_indexes: page_index
618                .column_indexes
619                .map(ColumnChunkEntries::try_into_map)
620                .transpose()?,
621            offset_indexes: page_index
622                .offset_indexes
623                .map(ColumnChunkEntries::try_into_map)
624                .transpose()?,
625        })
626    }
627
628    /// Allocates space for column indexes
629    ///
630    /// This replaces any existing column indexes with an empty sparse map having the specified
631    /// dimensions. It can then be populated using
632    /// [`try_put_column_index`](Self::try_put_column_index).
633    ///
634    /// This can be used to add column index storage to a builder that lacks one
635    /// (either a `Default` builder, or one created from a [`PageIndex`] without column indexes).
636    ///
637    /// # Panics
638    ///
639    /// Panics if either dimension exceeds `i32::MAX`, the maximum collection size representable
640    /// by Thrift.
641    ///
642    /// Use [`try_allocate_column_indexes`](Self::try_allocate_column_indexes) for a
643    /// fallible alternative.
644    pub fn allocate_column_indexes(&mut self, num_row_groups: usize, num_columns: usize) {
645        self.try_allocate_column_indexes(num_row_groups, num_columns)
646            .expect("invalid page index dimensions");
647    }
648
649    /// Attempts to allocate space for column indexes
650    ///
651    /// This is a fallible version of [`allocate_column_indexes`](Self::allocate_column_indexes).
652    ///
653    /// # Errors
654    ///
655    /// Returns an error if either dimension exceeds `i32::MAX`, the maximum collection size
656    /// representable by Thrift.
657    pub fn try_allocate_column_indexes(
658        &mut self,
659        num_row_groups: usize,
660        num_columns: usize,
661    ) -> Result<()> {
662        self.column_indexes = Some(ColumnChunkMap::try_new(num_row_groups, num_columns)?);
663        Ok(())
664    }
665
666    /// Allocates space for offset indexes
667    ///
668    /// This replaces any existing offset indexes with an empty sparse map having the specified
669    /// dimensions. It can then be populated using
670    /// [`try_put_offset_index`](Self::try_put_offset_index).
671    ///
672    /// This can be used to add offset index storage to a builder that lacks one
673    /// (either a `Default` builder, or one created from a [`PageIndex`] without offset indexes).
674    ///
675    /// # Panics
676    ///
677    /// Panics if either dimension exceeds `i32::MAX`, the maximum collection size representable
678    /// by Thrift.
679    ///
680    /// Use [`try_allocate_offset_indexes`](Self::try_allocate_offset_indexes) for a
681    /// fallible alternative.
682    pub fn allocate_offset_indexes(&mut self, num_row_groups: usize, num_columns: usize) {
683        self.try_allocate_offset_indexes(num_row_groups, num_columns)
684            .expect("invalid page index dimensions");
685    }
686
687    /// Attempts to allocate space for offset indexes
688    ///
689    /// This is a fallible version of [`allocate_offset_indexes`](Self::allocate_offset_indexes).
690    ///
691    /// # Errors
692    ///
693    /// Returns an error if either dimension exceeds `i32::MAX`, the maximum collection size
694    /// representable by Thrift.
695    pub fn try_allocate_offset_indexes(
696        &mut self,
697        num_row_groups: usize,
698        num_columns: usize,
699    ) -> Result<()> {
700        self.offset_indexes = Some(ColumnChunkMap::try_new(num_row_groups, num_columns)?);
701        Ok(())
702    }
703
704    /// Sets the column index for a specific row group and column
705    ///
706    /// If column indexes were not allocated (see [`Self::allocate_column_indexes`]),
707    /// or the row group or column index is out of bounds, this method does nothing.
708    #[deprecated(
709        since = "60.2.0",
710        note = "Use `try_put_column_index` to detect invalid coordinates or unavailable index storage"
711    )]
712    pub fn put_column_index(
713        &mut self,
714        column_index: ColumnIndexMetaData,
715        row_group_idx: usize,
716        column_idx: usize,
717    ) {
718        // preserve stated contract that this does nothing when indexes were not allocated
719        // or passed in indices are out of bounds
720        let Some(indexes) = self.column_indexes.as_ref() else {
721            return;
722        };
723        if row_group_idx >= indexes.num_row_groups() || column_idx >= indexes.num_columns() {
724            return;
725        }
726        self.try_put_column_index(column_index, row_group_idx, column_idx)
727            .unwrap_or_else(|err| panic!("{err}"));
728    }
729
730    /// Attempts to set the column index for a specific row group and column.
731    ///
732    /// # Errors
733    ///
734    /// Returns an error, and drops `column_index`, if column indexes were not allocated or the
735    /// coordinate is out of bounds.
736    pub fn try_put_column_index(
737        &mut self,
738        column_index: ColumnIndexMetaData,
739        row_group_idx: usize,
740        column_idx: usize,
741    ) -> Result<()> {
742        let indexes = self
743            .column_indexes
744            .as_mut()
745            .ok_or_else(|| ParquetError::General("column indexes are not allocated".to_string()))?;
746        indexes
747            .try_insert(row_group_idx, column_idx, column_index)
748            .map(|_| ())
749    }
750
751    /// Sets the offset index for a specific row group and column
752    ///
753    /// If offset indexes were not allocated (see [`Self::allocate_offset_indexes`]),
754    /// or the row group or column index is out of bounds, this method does nothing.
755    #[deprecated(
756        since = "60.2.0",
757        note = "Use `try_put_offset_index` to detect invalid coordinates or unavailable index storage"
758    )]
759    pub fn put_offset_index(
760        &mut self,
761        offset_index: OffsetIndexMetaData,
762        row_group_idx: usize,
763        column_idx: usize,
764    ) {
765        // preserve stated contract that this does nothing when indexes were not allocated
766        // or passed in indices are out of bounds
767        let Some(indexes) = self.offset_indexes.as_ref() else {
768            return;
769        };
770        if row_group_idx >= indexes.num_row_groups() || column_idx >= indexes.num_columns() {
771            return;
772        }
773        self.try_put_offset_index(offset_index, row_group_idx, column_idx)
774            .unwrap_or_else(|err| panic!("{err}"));
775    }
776
777    /// Attempts to set the offset index for a specific row group and column.
778    ///
779    /// # Errors
780    ///
781    /// Returns an error, and drops `offset_index`, if offset indexes were not allocated or the
782    /// coordinate is out of bounds.
783    pub fn try_put_offset_index(
784        &mut self,
785        offset_index: OffsetIndexMetaData,
786        row_group_idx: usize,
787        column_idx: usize,
788    ) -> Result<()> {
789        let indexes = self
790            .offset_indexes
791            .as_mut()
792            .ok_or_else(|| ParquetError::General("offset indexes are not allocated".to_string()))?;
793        indexes
794            .try_insert(row_group_idx, column_idx, offset_index)
795            .map(|_| ())
796    }
797
798    /// Checks if an index structure is entirely empty.
799    fn is_empty_index<T>(index: Option<&ColumnChunkMap<T>>) -> bool {
800        index.is_none_or(ColumnChunkMap::is_empty)
801    }
802
803    /// Consumes the builder and returns a [`PageIndex`]
804    ///
805    /// If an index structure was allocated but remains entirely empty (all entries are `None`),
806    /// it will be converted to `None` in the final [`PageIndex`]. This ensures that:
807    /// - Empty structures don't consume memory unnecessarily
808    /// - [`PageIndex::has_column_indexes()`] and [`PageIndex::has_offset_indexes()`]
809    ///   correctly return `false` for unpopulated indexes
810    pub fn build(self) -> PageIndex {
811        self.try_build().expect("failed to build page index")
812    }
813
814    /// Fallibly consumes the builder and returns a [`PageIndex`].
815    pub fn try_build(self) -> Result<PageIndex> {
816        let column_indexes = if Self::is_empty_index(self.column_indexes.as_ref()) {
817            None
818        } else {
819            self.column_indexes
820        };
821
822        let offset_indexes = if Self::is_empty_index(self.offset_indexes.as_ref()) {
823            None
824        } else {
825            self.offset_indexes
826        };
827
828        Ok(PageIndex {
829            column_indexes: column_indexes.map(ColumnChunkMap::try_freeze).transpose()?,
830            offset_indexes: offset_indexes.map(ColumnChunkMap::try_freeze).transpose()?,
831        })
832    }
833}
834
835impl From<PageIndex> for PageIndexBuilder {
836    fn from(page_index: PageIndex) -> Self {
837        Self::new_from(page_index)
838    }
839}
840
841#[cfg(test)]
842mod tests {
843    use super::*;
844    use crate::basic::Type as PhysicalType;
845    use crate::file::metadata::{ColumnIndexBuilder, OffsetIndexBuilder};
846
847    #[test]
848    fn test_dimensions_within_i32_max() {
849        // Valid dimensions should work
850        let builder = PageIndexBuilder::new(100, 50);
851        assert!(builder.column_indexes.is_some());
852        assert!(builder.offset_indexes.is_some());
853
854        let result = PageIndexBuilder::try_new(100, 50);
855        assert!(result.is_ok());
856    }
857
858    #[test]
859    fn test_try_new_validates_dimensions() {
860        // Test row group count exceeding i32::MAX
861        let oversized = i32::MAX as usize + 1;
862        let result = PageIndexBuilder::try_new(oversized, 10);
863        assert!(result.is_err());
864        let err = result.unwrap_err();
865        assert!(
866            err.to_string().contains("row group count exceeds i32::MAX"),
867            "unexpected error: {err}"
868        );
869
870        // Test column count exceeding i32::MAX
871        let result = PageIndexBuilder::try_new(10, oversized);
872        assert!(result.is_err());
873        let err = result.unwrap_err();
874        assert!(
875            err.to_string().contains("column count exceeds i32::MAX"),
876            "unexpected error: {err}"
877        );
878    }
879
880    #[test]
881    #[should_panic(expected = "invalid page index dimensions")]
882    fn test_new_panics_on_oversized_row_groups() {
883        let oversized = i32::MAX as usize + 1;
884        PageIndexBuilder::new(oversized, 10);
885    }
886
887    #[test]
888    #[should_panic(expected = "invalid page index dimensions")]
889    fn test_new_panics_on_oversized_columns() {
890        let oversized = i32::MAX as usize + 1;
891        PageIndexBuilder::new(10, oversized);
892    }
893
894    #[test]
895    fn test_try_allocate_column_indexes_validates_dimensions() {
896        let mut builder = PageIndexBuilder::default();
897        let oversized = i32::MAX as usize + 1;
898
899        let result = builder.try_allocate_column_indexes(oversized, 10);
900        assert!(result.is_err());
901        let err = result.unwrap_err();
902        assert!(
903            err.to_string().contains("row group count exceeds i32::MAX"),
904            "unexpected error: {err}"
905        );
906
907        let result = builder.try_allocate_column_indexes(10, oversized);
908        assert!(result.is_err());
909        let err = result.unwrap_err();
910        assert!(
911            err.to_string().contains("column count exceeds i32::MAX"),
912            "unexpected error: {err}"
913        );
914    }
915
916    #[test]
917    #[should_panic(expected = "invalid page index dimensions")]
918    fn test_allocate_column_indexes_panics_on_oversized() {
919        let mut builder = PageIndexBuilder::default();
920        let oversized = i32::MAX as usize + 1;
921        builder.allocate_column_indexes(oversized, 10);
922    }
923
924    #[test]
925    fn test_try_allocate_offset_indexes_validates_dimensions() {
926        let mut builder = PageIndexBuilder::default();
927        let oversized = i32::MAX as usize + 1;
928
929        let result = builder.try_allocate_offset_indexes(oversized, 10);
930        assert!(result.is_err());
931        let err = result.unwrap_err();
932        assert!(
933            err.to_string().contains("row group count exceeds i32::MAX"),
934            "unexpected error: {err}"
935        );
936
937        let result = builder.try_allocate_offset_indexes(10, oversized);
938        assert!(result.is_err());
939        let err = result.unwrap_err();
940        assert!(
941            err.to_string().contains("column count exceeds i32::MAX"),
942            "unexpected error: {err}"
943        );
944    }
945
946    #[test]
947    #[should_panic(expected = "invalid page index dimensions")]
948    fn test_allocate_offset_indexes_panics_on_oversized() {
949        let mut builder = PageIndexBuilder::default();
950        let oversized = i32::MAX as usize + 1;
951        builder.allocate_offset_indexes(oversized, 10);
952    }
953
954    #[test]
955    fn test_page_index_builder_basic_operations() {
956        let mut builder = PageIndexBuilder::new(2, 3);
957
958        // Create a simple column index
959        let mut col_index = ColumnIndexBuilder::new(PhysicalType::INT32);
960        col_index.append(
961            false,
962            1i32.to_le_bytes().to_vec(),
963            10i32.to_le_bytes().to_vec(),
964            0,
965            None,
966        );
967        let col_index = col_index.build().unwrap();
968
969        // Create a simple offset index
970        let mut off_index = OffsetIndexBuilder::new();
971        off_index.append_row_count(100);
972        off_index.append_offset_and_size(1000, 500);
973        let off_index = off_index.build();
974
975        // Insert indexes and report coordinates that cannot be populated
976        assert!(
977            builder
978                .try_put_column_index(col_index.clone(), 0, 0)
979                .is_ok()
980        );
981        assert!(
982            builder
983                .try_put_offset_index(off_index.clone(), 0, 0)
984                .is_ok()
985        );
986        assert!(
987            builder
988                .try_put_column_index(col_index.clone(), 2, 0)
989                .is_err()
990        );
991        assert!(
992            builder
993                .try_put_offset_index(off_index.clone(), 0, 3)
994                .is_err()
995        );
996
997        // Deprecated insertion still populates valid coordinates, and remains a no-op
998        // for unallocated storage and invalid coordinates.
999        #[expect(deprecated, reason = "verify the legacy insertion contract")]
1000        {
1001            let mut legacy_unallocated = PageIndexBuilder::default();
1002            legacy_unallocated.put_column_index(col_index.clone(), 0, 0);
1003            legacy_unallocated.put_offset_index(off_index.clone(), 0, 0);
1004            let empty_page_index = legacy_unallocated.build();
1005            assert!(!empty_page_index.has_column_indexes());
1006            assert!(!empty_page_index.has_offset_indexes());
1007
1008            let mut legacy_builder = PageIndexBuilder::new(2, 3);
1009            legacy_builder.put_column_index(col_index.clone(), 0, 0);
1010            legacy_builder.put_offset_index(off_index.clone(), 0, 0);
1011            legacy_builder.put_column_index(col_index.clone(), 2, 0);
1012            legacy_builder.put_column_index(col_index.clone(), 0, 3);
1013            legacy_builder.put_offset_index(off_index.clone(), 2, 0);
1014            legacy_builder.put_offset_index(off_index.clone(), 0, 3);
1015            let legacy_page_index = legacy_builder.build();
1016            assert_eq!(legacy_page_index.column_index(0, 0), Some(&col_index));
1017            assert_eq!(legacy_page_index.offset_index(0, 0), Some(&off_index));
1018            assert_eq!(legacy_page_index.column_index(0, 1), None);
1019            assert_eq!(legacy_page_index.offset_index(1, 0), None);
1020        }
1021
1022        let mut unallocated = PageIndexBuilder::default();
1023        assert!(unallocated.try_put_column_index(col_index, 0, 0).is_err());
1024        assert!(unallocated.try_put_offset_index(off_index, 0, 0).is_err());
1025
1026        // Build and verify
1027        let page_index = builder.build();
1028        assert!(page_index.has_column_indexes());
1029        assert!(page_index.has_offset_indexes());
1030        assert!(page_index.column_index(0, 0).is_some());
1031        assert!(page_index.offset_index(0, 0).is_some());
1032        assert!(page_index.column_index(0, 1).is_none());
1033        assert!(page_index.offset_index(1, 0).is_none());
1034    }
1035
1036    #[test]
1037    fn test_into_index_entries_moves_owned_values_in_row_major_order() {
1038        fn column_index(seed: i32, num_pages: usize) -> ColumnIndexMetaData {
1039            let mut builder = ColumnIndexBuilder::new(PhysicalType::INT32);
1040            for page in 0..num_pages {
1041                let min = seed + page as i32;
1042                builder.append(
1043                    false,
1044                    min.to_le_bytes().to_vec(),
1045                    (min + 10).to_le_bytes().to_vec(),
1046                    0,
1047                    None,
1048                );
1049            }
1050            builder.build().unwrap()
1051        }
1052
1053        fn offset_index(seed: i64, num_pages: usize) -> OffsetIndexMetaData {
1054            let mut builder = OffsetIndexBuilder::new();
1055            for page in 0..num_pages {
1056                builder.append_row_count(10);
1057                builder.append_offset_and_size(seed + page as i64 * 100, 100);
1058            }
1059            builder.build()
1060        }
1061
1062        let first_column = column_index(1, 1);
1063        let second_column = column_index(2, 2);
1064        let column_values = match &second_column {
1065            ColumnIndexMetaData::INT32(index) => index.min_values().as_ptr(),
1066            _ => unreachable!(),
1067        };
1068        let offset = offset_index(10, 3);
1069        let page_locations = offset.page_locations().as_ptr();
1070
1071        let mut builder = PageIndexBuilder::new(3, 3);
1072        builder.try_put_column_index(second_column, 2, 0).unwrap();
1073        builder.try_put_offset_index(offset, 1, 1).unwrap();
1074        builder
1075            .try_put_column_index(first_column.clone(), 0, 2)
1076            .unwrap();
1077
1078        let (column_entries, offset_entries) = builder.build().into_index_entries();
1079        let column_entries = column_entries.collect::<Vec<_>>();
1080        let offset_entries = offset_entries.collect::<Vec<_>>();
1081        assert_eq!(
1082            column_entries,
1083            vec![((0, 2), first_column), ((2, 0), column_index(2, 2))]
1084        );
1085        assert_eq!(offset_entries, vec![((1, 1), offset_index(10, 3))]);
1086        match &column_entries[1].1 {
1087            ColumnIndexMetaData::INT32(index) => {
1088                assert_eq!(index.min_values().as_ptr(), column_values)
1089            }
1090            _ => unreachable!(),
1091        }
1092        assert_eq!(
1093            offset_entries[0].1.page_locations().as_ptr(),
1094            page_locations
1095        );
1096
1097        let column = column_index(3, 1);
1098        let mut builder = PageIndexBuilder::default();
1099        builder.try_allocate_column_indexes(1, 1).unwrap();
1100        builder.try_put_column_index(column.clone(), 0, 0).unwrap();
1101        let (column_entries, offset_entries) = builder.build().into_index_entries();
1102        assert_eq!(column_entries.collect::<Vec<_>>(), vec![((0, 0), column)]);
1103        assert_eq!(offset_entries.count(), 0);
1104    }
1105
1106    #[test]
1107    fn test_page_index_try_new_discards_empty_indexes() {
1108        let page_index = PageIndex::try_new(Some(vec![vec![None]]), Some(vec![])).unwrap();
1109        assert!(!page_index.has_column_indexes());
1110        assert!(!page_index.has_offset_indexes());
1111    }
1112}