parquet/file/metadata/thrift/
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//! This module is the bridge between a Parquet file's thrift encoded metadata
19//! and this crate's [Parquet metadata API]. It contains objects and functions used
20//! to serialize/deserialize metadata objects into/from the Thrift compact protocol
21//! format as defined by the [Parquet specification].
22//!
23//! [Parquet metadata API]: crate::file::metadata
24//! [Parquet specification]: https://github.com/apache/parquet-format/tree/master
25
26use std::io::Write;
27use std::sync::Arc;
28
29#[cfg(feature = "encryption")]
30pub(crate) mod encryption;
31
32#[cfg(feature = "encryption")]
33use crate::file::{
34    column_crypto_metadata::ColumnCryptoMetaData, metadata::thrift::encryption::EncryptionAlgorithm,
35};
36use crate::{
37    basic::{
38        ColumnOrder, Compression, ConvertedType, Encoding, EncodingMask, LogicalType, PageType,
39        Repetition, Type,
40    },
41    data_type::{ByteArray, FixedLenByteArray, Int96},
42    errors::{ParquetError, Result},
43    file::{
44        metadata::{
45            ColumnChunkMetaData, ColumnChunkMetaDataBuilder, KeyValue, LevelHistogram,
46            PageEncodingStats, ParquetMetaData, ParquetMetaDataOptions, ParquetPageEncodingStats,
47            RowGroupMetaData, RowGroupMetaDataBuilder, SortingColumn,
48        },
49        statistics::ValueStatistics,
50    },
51    parquet_thrift::{
52        ElementType, FieldType, ReadThrift, ThriftCompactInputProtocol,
53        ThriftCompactOutputProtocol, ThriftSliceInputProtocol, WriteThrift, WriteThriftField,
54        read_thrift_vec,
55    },
56    schema::types::{
57        ColumnDescriptor, SchemaDescriptor, TypePtr, num_nodes, parquet_schema_from_array,
58    },
59    thrift_struct,
60    util::bit_util::FromBytes,
61    write_thrift_field,
62};
63
64// this needs to be visible to the schema conversion code
65thrift_struct!(
66pub(crate) struct SchemaElement<'a> {
67  /// Data type for this field. Not set if the current element is a non-leaf node
68  1: optional Type r#type;
69  /// If type is FIXED_LEN_BYTE_ARRAY, this is the byte length of the values.
70  /// Otherwise, if specified, this is the maximum bit length to store any of the values.
71  /// (e.g. a low cardinality INT col could have this set to 3).  Note that this is
72  /// in the schema, and therefore fixed for the entire file.
73  2: optional i32 type_length;
74  /// Repetition of the field. The root of the schema does not have a repetition_type.
75  /// All other nodes must have one.
76  3: optional Repetition repetition_type;
77  /// Name of the field in the schema
78  4: required string<'a> name;
79  /// Nested fields. Since thrift does not support nested fields,
80  /// the nesting is flattened to a single list by a depth-first traversal.
81  /// The children count is used to construct the nested relationship.
82  /// This field is not set when the element is a primitive type.
83  5: optional i32 num_children;
84  /// DEPRECATED: When the schema is the result of a conversion from another model.
85  /// Used to record the original type to help with cross conversion.
86  ///
87  /// This is superseded by logical_type.
88  6: optional ConvertedType converted_type;
89  /// DEPRECATED: Used when this column contains decimal data.
90  /// See the DECIMAL converted type for more details.
91  ///
92  /// This is superseded by using the DecimalType annotation in logical_type.
93  7: optional i32 scale
94  8: optional i32 precision
95  /// When the original schema supports field ids, this will save the
96  /// original field id in the parquet schema
97  9: optional i32 field_id;
98  /// The logical type of this SchemaElement
99  ///
100  /// LogicalType replaces ConvertedType, but ConvertedType is still required
101  /// for some logical types to ensure forward-compatibility in format v1.
102  10: optional LogicalType logical_type
103}
104);
105
106thrift_struct!(
107struct Statistics<'a> {
108   1: optional binary<'a> max;
109   2: optional binary<'a> min;
110   3: optional i64 null_count;
111   4: optional i64 distinct_count;
112   5: optional binary<'a> max_value;
113   6: optional binary<'a> min_value;
114   7: optional bool is_max_value_exact;
115   8: optional bool is_min_value_exact;
116}
117);
118
119thrift_struct!(
120struct BoundingBox {
121  1: required double xmin;
122  2: required double xmax;
123  3: required double ymin;
124  4: required double ymax;
125  5: optional double zmin;
126  6: optional double zmax;
127  7: optional double mmin;
128  8: optional double mmax;
129}
130);
131
132thrift_struct!(
133struct GeospatialStatistics {
134  1: optional BoundingBox bbox;
135  2: optional list<i32> geospatial_types;
136}
137);
138
139thrift_struct!(
140struct SizeStatistics {
141   1: optional i64 unencoded_byte_array_data_bytes;
142   2: optional list<i64> repetition_level_histogram;
143   3: optional list<i64> definition_level_histogram;
144}
145);
146
147fn convert_geo_stats(
148    stats: Option<GeospatialStatistics>,
149) -> Option<Box<crate::geospatial::statistics::GeospatialStatistics>> {
150    stats.map(|st| {
151        let bbox = convert_bounding_box(st.bbox);
152        let geospatial_types: Option<Vec<i32>> = st.geospatial_types.filter(|v| !v.is_empty());
153        Box::new(crate::geospatial::statistics::GeospatialStatistics::new(
154            bbox,
155            geospatial_types,
156        ))
157    })
158}
159
160fn convert_bounding_box(
161    bbox: Option<BoundingBox>,
162) -> Option<crate::geospatial::bounding_box::BoundingBox> {
163    bbox.map(|bb| {
164        let mut newbb = crate::geospatial::bounding_box::BoundingBox::new(
165            bb.xmin.into(),
166            bb.xmax.into(),
167            bb.ymin.into(),
168            bb.ymax.into(),
169        );
170
171        newbb = match (bb.zmin, bb.zmax) {
172            (Some(zmin), Some(zmax)) => newbb.with_zrange(zmin.into(), zmax.into()),
173            // If either None or mismatch, leave it as None and don't error
174            _ => newbb,
175        };
176
177        newbb = match (bb.mmin, bb.mmax) {
178            (Some(mmin), Some(mmax)) => newbb.with_mrange(mmin.into(), mmax.into()),
179            // If either None or mismatch, leave it as None and don't error
180            _ => newbb,
181        };
182
183        newbb
184    })
185}
186
187/// Create a [`crate::file::statistics::Statistics`] from a thrift [`Statistics`] object.
188fn convert_stats(
189    column_descr: &Arc<ColumnDescriptor>,
190    thrift_stats: Option<Statistics>,
191) -> Result<Option<crate::file::statistics::Statistics>> {
192    use crate::file::statistics::Statistics as FStatistics;
193    Ok(match thrift_stats {
194        Some(stats) => {
195            // Number of nulls recorded, when it is not available, we just mark it as 0.
196            // TODO this should be `None` if there is no information about NULLS.
197            // see https://github.com/apache/arrow-rs/pull/6216/files
198            let null_count = stats.null_count.unwrap_or(0);
199
200            if null_count < 0 {
201                return Err(general_err!(
202                    "Statistics null count is negative {}",
203                    null_count
204                ));
205            }
206
207            // Generic null count.
208            let null_count = Some(null_count as u64);
209            // Generic distinct count (count of distinct values occurring)
210            let distinct_count = stats.distinct_count.map(|value| value as u64);
211            // Whether or not statistics use deprecated min/max fields.
212            let old_format = stats.min_value.is_none() && stats.max_value.is_none();
213            // Generic min value as bytes.
214            let min = if old_format {
215                stats.min
216            } else {
217                stats.min_value
218            };
219            // Generic max value as bytes.
220            let max = if old_format {
221                stats.max
222            } else {
223                stats.max_value
224            };
225
226            fn check_len(min: &Option<&[u8]>, max: &Option<&[u8]>, len: usize) -> Result<()> {
227                if let Some(min) = min {
228                    if min.len() < len {
229                        return Err(general_err!("Insufficient bytes to parse min statistic",));
230                    }
231                }
232                if let Some(max) = max {
233                    if max.len() < len {
234                        return Err(general_err!("Insufficient bytes to parse max statistic",));
235                    }
236                }
237                Ok(())
238            }
239
240            let physical_type = column_descr.physical_type();
241            match physical_type {
242                Type::BOOLEAN => check_len(&min, &max, 1),
243                Type::INT32 | Type::FLOAT => check_len(&min, &max, 4),
244                Type::INT64 | Type::DOUBLE => check_len(&min, &max, 8),
245                Type::INT96 => check_len(&min, &max, 12),
246                _ => Ok(()),
247            }?;
248
249            // Values are encoded using PLAIN encoding definition, except that
250            // variable-length byte arrays do not include a length prefix.
251            //
252            // Instead of using actual decoder, we manually convert values.
253            let res = match physical_type {
254                Type::BOOLEAN => FStatistics::boolean(
255                    min.map(|data| data[0] != 0),
256                    max.map(|data| data[0] != 0),
257                    distinct_count,
258                    null_count,
259                    old_format,
260                ),
261                Type::INT32 => FStatistics::int32(
262                    min.map(|data| i32::from_le_bytes(data[..4].try_into().unwrap())),
263                    max.map(|data| i32::from_le_bytes(data[..4].try_into().unwrap())),
264                    distinct_count,
265                    null_count,
266                    old_format,
267                ),
268                Type::INT64 => FStatistics::int64(
269                    min.map(|data| i64::from_le_bytes(data[..8].try_into().unwrap())),
270                    max.map(|data| i64::from_le_bytes(data[..8].try_into().unwrap())),
271                    distinct_count,
272                    null_count,
273                    old_format,
274                ),
275                Type::INT96 => {
276                    // INT96 statistics may not be correct, because comparison is signed
277                    let min = if let Some(data) = min {
278                        assert_eq!(data.len(), 12);
279                        Some(Int96::try_from_le_slice(data)?)
280                    } else {
281                        None
282                    };
283                    let max = if let Some(data) = max {
284                        assert_eq!(data.len(), 12);
285                        Some(Int96::try_from_le_slice(data)?)
286                    } else {
287                        None
288                    };
289                    FStatistics::int96(min, max, distinct_count, null_count, old_format)
290                }
291                Type::FLOAT => FStatistics::float(
292                    min.map(|data| f32::from_le_bytes(data[..4].try_into().unwrap())),
293                    max.map(|data| f32::from_le_bytes(data[..4].try_into().unwrap())),
294                    distinct_count,
295                    null_count,
296                    old_format,
297                ),
298                Type::DOUBLE => FStatistics::double(
299                    min.map(|data| f64::from_le_bytes(data[..8].try_into().unwrap())),
300                    max.map(|data| f64::from_le_bytes(data[..8].try_into().unwrap())),
301                    distinct_count,
302                    null_count,
303                    old_format,
304                ),
305                Type::BYTE_ARRAY => FStatistics::ByteArray(
306                    ValueStatistics::new(
307                        min.map(ByteArray::from),
308                        max.map(ByteArray::from),
309                        distinct_count,
310                        null_count,
311                        old_format,
312                    )
313                    .with_max_is_exact(stats.is_max_value_exact.unwrap_or(false))
314                    .with_min_is_exact(stats.is_min_value_exact.unwrap_or(false)),
315                ),
316                Type::FIXED_LEN_BYTE_ARRAY => FStatistics::FixedLenByteArray(
317                    ValueStatistics::new(
318                        min.map(ByteArray::from).map(FixedLenByteArray::from),
319                        max.map(ByteArray::from).map(FixedLenByteArray::from),
320                        distinct_count,
321                        null_count,
322                        old_format,
323                    )
324                    .with_max_is_exact(stats.is_max_value_exact.unwrap_or(false))
325                    .with_min_is_exact(stats.is_min_value_exact.unwrap_or(false)),
326                ),
327            };
328
329            Some(res)
330        }
331        None => None,
332    })
333}
334
335// bit positions for required fields in the Thrift ColumnMetaData struct
336const COL_META_TYPE: u16 = 1 << 1;
337const COL_META_ENCODINGS: u16 = 1 << 2;
338const COL_META_CODEC: u16 = 1 << 4;
339const COL_META_NUM_VALUES: u16 = 1 << 5;
340const COL_META_TOTAL_UNCOMP_SZ: u16 = 1 << 6;
341const COL_META_TOTAL_COMP_SZ: u16 = 1 << 7;
342const COL_META_DATA_PAGE_OFFSET: u16 = 1 << 9;
343
344// a mask where all required fields' bits are set
345const COL_META_ALL_REQUIRED: u16 = COL_META_TYPE
346    | COL_META_ENCODINGS
347    | COL_META_CODEC
348    | COL_META_NUM_VALUES
349    | COL_META_TOTAL_UNCOMP_SZ
350    | COL_META_TOTAL_COMP_SZ
351    | COL_META_DATA_PAGE_OFFSET;
352
353// check mask to see if all required fields are set. return an appropriate error if
354// any are missing.
355fn validate_column_metadata(mask: u16) -> Result<()> {
356    if mask != COL_META_ALL_REQUIRED {
357        if mask & COL_META_ENCODINGS == 0 {
358            return Err(general_err!("Required field encodings is missing"));
359        }
360
361        if mask & COL_META_CODEC == 0 {
362            return Err(general_err!("Required field codec is missing"));
363        }
364        if mask & COL_META_NUM_VALUES == 0 {
365            return Err(general_err!("Required field num_values is missing"));
366        }
367        if mask & COL_META_TOTAL_UNCOMP_SZ == 0 {
368            return Err(general_err!(
369                "Required field total_uncompressed_size is missing"
370            ));
371        }
372        if mask & COL_META_TOTAL_COMP_SZ == 0 {
373            return Err(general_err!(
374                "Required field total_compressed_size is missing"
375            ));
376        }
377        if mask & COL_META_DATA_PAGE_OFFSET == 0 {
378            return Err(general_err!("Required field data_page_offset is missing"));
379        }
380    }
381
382    Ok(())
383}
384
385fn read_encoding_stats_as_mask<'a>(
386    prot: &mut ThriftSliceInputProtocol<'a>,
387) -> Result<EncodingMask> {
388    // read the vector of stats, setting mask bits for data pages
389    let mut mask = 0i32;
390    let list_ident = prot.read_list_begin()?;
391    for _ in 0..list_ident.size {
392        let pes = PageEncodingStats::read_thrift(prot)?;
393        match pes.page_type {
394            PageType::DATA_PAGE | PageType::DATA_PAGE_V2 => mask |= 1 << pes.encoding as i32,
395            _ => {}
396        }
397    }
398    EncodingMask::try_new(mask)
399}
400
401// Decode `ColumnMetaData`. Returns a mask of all required fields that were observed.
402// This mask can be passed to `validate_column_metadata`.
403fn read_column_metadata<'a>(
404    prot: &mut ThriftSliceInputProtocol<'a>,
405    column: &mut ColumnChunkMetaData,
406    col_index: usize,
407    options: Option<&ParquetMetaDataOptions>,
408) -> Result<u16> {
409    // mask for seen required fields in ColumnMetaData
410    let mut seen_mask = 0u16;
411
412    let mut skip_pes = false;
413    let mut pes_mask = false;
414
415    if let Some(opts) = options {
416        skip_pes = opts.skip_encoding_stats(col_index);
417        pes_mask = opts.encoding_stats_as_mask();
418    }
419
420    // struct ColumnMetaData {
421    //   1: required Type type
422    //   2: required list<Encoding> encodings
423    //   3: required list<string> path_in_schema
424    //   4: required CompressionCodec codec
425    //   5: required i64 num_values
426    //   6: required i64 total_uncompressed_size
427    //   7: required i64 total_compressed_size
428    //   8: optional list<KeyValue> key_value_metadata
429    //   9: required i64 data_page_offset
430    //   10: optional i64 index_page_offset
431    //   11: optional i64 dictionary_page_offset
432    //   12: optional Statistics statistics;
433    //   13: optional list<PageEncodingStats> encoding_stats;
434    //   14: optional i64 bloom_filter_offset;
435    //   15: optional i32 bloom_filter_length;
436    //   16: optional SizeStatistics size_statistics;
437    //   17: optional GeospatialStatistics geospatial_statistics;
438    // }
439    let column_descr = &column.column_descr;
440
441    let mut last_field_id = 0i16;
442    loop {
443        let field_ident = prot.read_field_begin(last_field_id)?;
444        if field_ident.field_type == FieldType::Stop {
445            break;
446        }
447        match field_ident.id {
448            // 1: type is never used, we can use the column descriptor
449            1 => {
450                // read for error handling
451                Type::read_thrift(&mut *prot)?;
452                seen_mask |= COL_META_TYPE;
453            }
454            2 => {
455                column.encodings = EncodingMask::read_thrift(&mut *prot)?;
456                seen_mask |= COL_META_ENCODINGS;
457            }
458            // 3: path_in_schema is redundant
459            4 => {
460                column.compression = Compression::read_thrift(&mut *prot)?;
461                seen_mask |= COL_META_CODEC;
462            }
463            5 => {
464                column.num_values = i64::read_thrift(&mut *prot)?;
465                seen_mask |= COL_META_NUM_VALUES;
466            }
467            6 => {
468                column.total_uncompressed_size = i64::read_thrift(&mut *prot)?;
469                seen_mask |= COL_META_TOTAL_UNCOMP_SZ;
470            }
471            7 => {
472                column.total_compressed_size = i64::read_thrift(&mut *prot)?;
473                seen_mask |= COL_META_TOTAL_COMP_SZ;
474            }
475            // 8: we don't expose this key value
476            9 => {
477                column.data_page_offset = i64::read_thrift(&mut *prot)?;
478                seen_mask |= COL_META_DATA_PAGE_OFFSET;
479            }
480            10 => {
481                column.index_page_offset = Some(i64::read_thrift(&mut *prot)?);
482            }
483            11 => {
484                column.dictionary_page_offset = Some(i64::read_thrift(&mut *prot)?);
485            }
486            12 => {
487                column.statistics =
488                    convert_stats(column_descr, Some(Statistics::read_thrift(&mut *prot)?))?;
489            }
490            13 if !skip_pes => {
491                if pes_mask {
492                    let val = read_encoding_stats_as_mask(&mut *prot)?;
493                    column.encoding_stats = Some(ParquetPageEncodingStats::Mask(val));
494                } else {
495                    let val =
496                        read_thrift_vec::<PageEncodingStats, ThriftSliceInputProtocol>(&mut *prot)?;
497                    column.encoding_stats = Some(ParquetPageEncodingStats::Full(val));
498                }
499            }
500            14 => {
501                column.bloom_filter_offset = Some(i64::read_thrift(&mut *prot)?);
502            }
503            15 => {
504                column.bloom_filter_length = Some(i32::read_thrift(&mut *prot)?);
505            }
506            16 => {
507                let val = SizeStatistics::read_thrift(&mut *prot)?;
508                column.unencoded_byte_array_data_bytes = val.unencoded_byte_array_data_bytes;
509                column.repetition_level_histogram =
510                    val.repetition_level_histogram.map(LevelHistogram::from);
511                column.definition_level_histogram =
512                    val.definition_level_histogram.map(LevelHistogram::from);
513            }
514            17 => {
515                let val = GeospatialStatistics::read_thrift(&mut *prot)?;
516                column.geo_statistics = convert_geo_stats(Some(val));
517            }
518            _ => {
519                prot.skip(field_ident.field_type)?;
520            }
521        };
522        last_field_id = field_ident.id;
523    }
524
525    Ok(seen_mask)
526}
527
528// using ThriftSliceInputProtocol rather than ThriftCompactInputProtocl trait because
529// these are all internal and operate on slices.
530fn read_column_chunk<'a>(
531    prot: &mut ThriftSliceInputProtocol<'a>,
532    column_descr: &Arc<ColumnDescriptor>,
533    col_index: usize,
534    options: Option<&ParquetMetaDataOptions>,
535) -> Result<ColumnChunkMetaData> {
536    // create a default initialized ColumnMetaData
537    let mut col = ColumnChunkMetaDataBuilder::new(column_descr.clone()).build()?;
538
539    // seen flag for file_offset
540    let mut has_file_offset = false;
541
542    // mask of seen flags for ColumnMetaData
543    let mut col_meta_mask = 0u16;
544
545    // struct ColumnChunk {
546    //   1: optional string file_path
547    //   2: required i64 file_offset = 0
548    //   3: optional ColumnMetaData meta_data
549    //   4: optional i64 offset_index_offset
550    //   5: optional i32 offset_index_length
551    //   6: optional i64 column_index_offset
552    //   7: optional i32 column_index_length
553    //   8: optional ColumnCryptoMetaData crypto_metadata
554    //   9: optional binary encrypted_column_metadata
555    // }
556    let mut last_field_id = 0i16;
557    loop {
558        let field_ident = prot.read_field_begin(last_field_id)?;
559        if field_ident.field_type == FieldType::Stop {
560            break;
561        }
562        match field_ident.id {
563            1 => {
564                col.file_path = Some(String::read_thrift(&mut *prot)?);
565            }
566            2 => {
567                col.file_offset = i64::read_thrift(&mut *prot)?;
568                has_file_offset = true;
569            }
570            3 => {
571                col_meta_mask = read_column_metadata(&mut *prot, &mut col, col_index, options)?;
572            }
573            4 => {
574                col.offset_index_offset = Some(i64::read_thrift(&mut *prot)?);
575            }
576            5 => {
577                col.offset_index_length = Some(i32::read_thrift(&mut *prot)?);
578            }
579            6 => {
580                col.column_index_offset = Some(i64::read_thrift(&mut *prot)?);
581            }
582            7 => {
583                col.column_index_length = Some(i32::read_thrift(&mut *prot)?);
584            }
585            #[cfg(feature = "encryption")]
586            8 => {
587                let val = ColumnCryptoMetaData::read_thrift(&mut *prot)?;
588                col.column_crypto_metadata = Some(Box::new(val));
589            }
590            #[cfg(feature = "encryption")]
591            9 => {
592                col.encrypted_column_metadata = Some(<&[u8]>::read_thrift(&mut *prot)?.to_vec());
593            }
594            _ => {
595                prot.skip(field_ident.field_type)?;
596            }
597        };
598        last_field_id = field_ident.id;
599    }
600
601    // the only required field from ColumnChunk
602    if !has_file_offset {
603        return Err(general_err!("Required field file_offset is missing"));
604    };
605
606    // if encrypted just return. we'll decrypt after finishing the footer and populate the rest.
607    #[cfg(feature = "encryption")]
608    if col.encrypted_column_metadata.is_some() {
609        return Ok(col);
610    }
611
612    // not encrypted, so make sure all required fields were read
613    validate_column_metadata(col_meta_mask)?;
614
615    Ok(col)
616}
617
618fn read_row_group(
619    prot: &mut ThriftSliceInputProtocol,
620    schema_descr: &Arc<SchemaDescriptor>,
621    options: Option<&ParquetMetaDataOptions>,
622) -> Result<RowGroupMetaData> {
623    // create default initialized RowGroupMetaData
624    let mut row_group = RowGroupMetaDataBuilder::new(schema_descr.clone()).build_unchecked();
625
626    // mask values for required fields
627    const RG_COLUMNS: u8 = 1 << 1;
628    const RG_TOT_BYTE_SIZE: u8 = 1 << 2;
629    const RG_NUM_ROWS: u8 = 1 << 3;
630    const RG_ALL_REQUIRED: u8 = RG_COLUMNS | RG_TOT_BYTE_SIZE | RG_NUM_ROWS;
631
632    let mut mask = 0u8;
633
634    // struct RowGroup {
635    //   1: required list<ColumnChunk> columns
636    //   2: required i64 total_byte_size
637    //   3: required i64 num_rows
638    //   4: optional list<SortingColumn> sorting_columns
639    //   5: optional i64 file_offset
640    //   6: optional i64 total_compressed_size
641    //   7: optional i16 ordinal
642    // }
643    let mut last_field_id = 0i16;
644    loop {
645        let field_ident = prot.read_field_begin(last_field_id)?;
646        if field_ident.field_type == FieldType::Stop {
647            break;
648        }
649        match field_ident.id {
650            1 => {
651                let list_ident = prot.read_list_begin()?;
652                if schema_descr.num_columns() != list_ident.size as usize {
653                    return Err(general_err!(
654                        "Column count mismatch. Schema has {} columns while Row Group has {}",
655                        schema_descr.num_columns(),
656                        list_ident.size
657                    ));
658                }
659                for i in 0..list_ident.size as usize {
660                    let col = read_column_chunk(prot, &schema_descr.columns()[i], i, options)?;
661                    row_group.columns.push(col);
662                }
663                mask |= RG_COLUMNS;
664            }
665            2 => {
666                row_group.total_byte_size = i64::read_thrift(&mut *prot)?;
667                mask |= RG_TOT_BYTE_SIZE;
668            }
669            3 => {
670                row_group.num_rows = i64::read_thrift(&mut *prot)?;
671                mask |= RG_NUM_ROWS;
672            }
673            4 => {
674                let val = read_thrift_vec::<SortingColumn, ThriftSliceInputProtocol>(&mut *prot)?;
675                row_group.sorting_columns = Some(val);
676            }
677            5 => {
678                row_group.file_offset = Some(i64::read_thrift(&mut *prot)?);
679            }
680            // 6: we don't expose total_compressed_size
681            7 => {
682                row_group.ordinal = Some(i16::read_thrift(&mut *prot)?);
683            }
684            _ => {
685                prot.skip(field_ident.field_type)?;
686            }
687        };
688        last_field_id = field_ident.id;
689    }
690
691    if mask != RG_ALL_REQUIRED {
692        if mask & RG_COLUMNS == 0 {
693            return Err(general_err!("Required field columns is missing"));
694        }
695        if mask & RG_TOT_BYTE_SIZE == 0 {
696            return Err(general_err!("Required field total_byte_size is missing"));
697        }
698        if mask & RG_NUM_ROWS == 0 {
699            return Err(general_err!("Required field num_rows is missing"));
700        }
701    }
702
703    Ok(row_group)
704}
705
706/// Create a [`SchemaDescriptor`] from thrift input. The input buffer must contain a complete
707/// Parquet footer.
708pub(crate) fn parquet_schema_from_bytes(buf: &[u8]) -> Result<SchemaDescriptor> {
709    let mut prot = ThriftSliceInputProtocol::new(buf);
710
711    let mut last_field_id = 0i16;
712    loop {
713        let field_ident = prot.read_field_begin(last_field_id)?;
714        if field_ident.field_type == FieldType::Stop {
715            break;
716        }
717        match field_ident.id {
718            2 => {
719                // read schema and convert to SchemaDescriptor for use when reading row groups
720                let val = read_thrift_vec::<SchemaElement, ThriftSliceInputProtocol>(&mut prot)?;
721                let val = parquet_schema_from_array(val)?;
722                return Ok(SchemaDescriptor::new(val));
723            }
724            _ => prot.skip(field_ident.field_type)?,
725        }
726        last_field_id = field_ident.id;
727    }
728    Err(general_err!("Input does not contain a schema"))
729}
730
731/// Create [`ParquetMetaData`] from thrift input. Note that this only decodes the file metadata in
732/// the Parquet footer. Page indexes will need to be added later.
733pub(crate) fn parquet_metadata_from_bytes(
734    buf: &[u8],
735    options: Option<&ParquetMetaDataOptions>,
736) -> Result<ParquetMetaData> {
737    let mut prot = ThriftSliceInputProtocol::new(buf);
738
739    // begin reading the file metadata
740    let mut version: Option<i32> = None;
741    let mut num_rows: Option<i64> = None;
742    let mut row_groups: Option<Vec<RowGroupMetaData>> = None;
743    let mut key_value_metadata: Option<Vec<KeyValue>> = None;
744    let mut created_by: Option<&str> = None;
745    let mut column_orders: Option<Vec<ColumnOrder>> = None;
746    #[cfg(feature = "encryption")]
747    let mut encryption_algorithm: Option<EncryptionAlgorithm> = None;
748    #[cfg(feature = "encryption")]
749    let mut footer_signing_key_metadata: Option<&[u8]> = None;
750
751    // this will need to be set before parsing row groups
752    let mut schema_descr: Option<Arc<SchemaDescriptor>> = None;
753
754    // see if we already have a schema.
755    if let Some(options) = options {
756        schema_descr = options.schema().cloned();
757    }
758
759    // struct FileMetaData {
760    //   1: required i32 version
761    //   2: required list<SchemaElement> schema;
762    //   3: required i64 num_rows
763    //   4: required list<RowGroup> row_groups
764    //   5: optional list<KeyValue> key_value_metadata
765    //   6: optional string created_by
766    //   7: optional list<ColumnOrder> column_orders;
767    //   8: optional EncryptionAlgorithm encryption_algorithm
768    //   9: optional binary footer_signing_key_metadata
769    // }
770    let mut last_field_id = 0i16;
771    loop {
772        let field_ident = prot.read_field_begin(last_field_id)?;
773        if field_ident.field_type == FieldType::Stop {
774            break;
775        }
776        match field_ident.id {
777            1 => {
778                version = Some(i32::read_thrift(&mut prot)?);
779            }
780            2 => {
781                // If schema was passed in, skip parsing it
782                if schema_descr.is_some() {
783                    prot.skip(field_ident.field_type)?;
784                } else {
785                    // read schema and convert to SchemaDescriptor for use when reading row groups
786                    let val =
787                        read_thrift_vec::<SchemaElement, ThriftSliceInputProtocol>(&mut prot)?;
788                    let val = parquet_schema_from_array(val)?;
789                    schema_descr = Some(Arc::new(SchemaDescriptor::new(val)));
790                }
791            }
792            3 => {
793                num_rows = Some(i64::read_thrift(&mut prot)?);
794            }
795            4 => {
796                if schema_descr.is_none() {
797                    return Err(general_err!("Required field schema is missing"));
798                }
799                let schema_descr = schema_descr.as_ref().unwrap();
800                let list_ident = prot.read_list_begin()?;
801                let mut rg_vec = Vec::with_capacity(list_ident.size as usize);
802
803                // Read row groups and handle ordinal assignment
804                let mut assigner = OrdinalAssigner::new();
805                for ordinal in 0..list_ident.size {
806                    let ordinal: i16 = ordinal.try_into().map_err(|_| {
807                        ParquetError::General(format!(
808                            "Row group ordinal {ordinal} exceeds i16 max value",
809                        ))
810                    })?;
811                    let rg = read_row_group(&mut prot, schema_descr, options)?;
812                    rg_vec.push(assigner.ensure(ordinal, rg)?);
813                }
814                row_groups = Some(rg_vec);
815            }
816            5 => {
817                let val = read_thrift_vec::<KeyValue, ThriftSliceInputProtocol>(&mut prot)?;
818                key_value_metadata = Some(val);
819            }
820            6 => {
821                created_by = Some(<&str>::read_thrift(&mut prot)?);
822            }
823            7 => {
824                let val = read_thrift_vec::<ColumnOrder, ThriftSliceInputProtocol>(&mut prot)?;
825                column_orders = Some(val);
826            }
827            #[cfg(feature = "encryption")]
828            8 => {
829                let val = EncryptionAlgorithm::read_thrift(&mut prot)?;
830                encryption_algorithm = Some(val);
831            }
832            #[cfg(feature = "encryption")]
833            9 => {
834                footer_signing_key_metadata = Some(<&[u8]>::read_thrift(&mut prot)?);
835            }
836            _ => {
837                prot.skip(field_ident.field_type)?;
838            }
839        };
840        last_field_id = field_ident.id;
841    }
842    let Some(version) = version else {
843        return Err(general_err!("Required field version is missing"));
844    };
845    let Some(num_rows) = num_rows else {
846        return Err(general_err!("Required field num_rows is missing"));
847    };
848    let Some(row_groups) = row_groups else {
849        return Err(general_err!("Required field row_groups is missing"));
850    };
851
852    let created_by = created_by.map(|c| c.to_owned());
853
854    // we've tested for `None` by now so this is safe
855    let schema_descr = schema_descr.unwrap();
856
857    // need to map read column orders to actual values based on the schema
858    if column_orders
859        .as_ref()
860        .is_some_and(|cos| cos.len() != schema_descr.num_columns())
861    {
862        return Err(general_err!("Column order length mismatch"));
863    }
864    // replace default type defined column orders with ones having the correct sort order
865    // TODO(ets): this could instead be done above when decoding
866    let column_orders = column_orders.map(|mut cos| {
867        for (i, column) in schema_descr.columns().iter().enumerate() {
868            if let ColumnOrder::TYPE_DEFINED_ORDER(_) = cos[i] {
869                let sort_order = ColumnOrder::sort_order_for_type(
870                    column.logical_type_ref(),
871                    column.converted_type(),
872                    column.physical_type(),
873                );
874                cos[i] = ColumnOrder::TYPE_DEFINED_ORDER(sort_order);
875            }
876        }
877        cos
878    });
879
880    #[cfg(not(feature = "encryption"))]
881    let fmd = crate::file::metadata::FileMetaData::new(
882        version,
883        num_rows,
884        created_by,
885        key_value_metadata,
886        schema_descr,
887        column_orders,
888    );
889    #[cfg(feature = "encryption")]
890    let fmd = crate::file::metadata::FileMetaData::new(
891        version,
892        num_rows,
893        created_by,
894        key_value_metadata,
895        schema_descr,
896        column_orders,
897    )
898    .with_encryption_algorithm(encryption_algorithm)
899    .with_footer_signing_key_metadata(footer_signing_key_metadata.map(|v| v.to_vec()));
900
901    Ok(ParquetMetaData::new(fmd, row_groups))
902}
903
904/// Assign [`RowGroupMetaData::ordinal`]  if it is missing.
905#[derive(Debug, Default)]
906pub(crate) struct OrdinalAssigner {
907    first_has_ordinal: Option<bool>,
908}
909
910impl OrdinalAssigner {
911    fn new() -> Self {
912        Default::default()
913    }
914
915    /// Sets [`RowGroupMetaData::ordinal`] if it is missing.
916    ///
917    /// # Arguments
918    /// - actual_ordinal: The ordinal (index) of the row group being processed
919    ///   in the file metadata.
920    /// - rg: The [`RowGroupMetaData`] to potentially modify.
921    ///
922    /// Ensures:
923    /// 1. If the first row group has an ordinal, all subsequent row groups must
924    ///    also have ordinals.
925    /// 2. If the first row group does NOT have an ordinal, all subsequent row
926    ///    groups must also not have ordinals.
927    fn ensure(
928        &mut self,
929        actual_ordinal: i16,
930        mut rg: RowGroupMetaData,
931    ) -> Result<RowGroupMetaData> {
932        let rg_has_ordinal = rg.ordinal.is_some();
933
934        // Only set first_has_ordinal if it's None (first row group that arrives)
935        if self.first_has_ordinal.is_none() {
936            self.first_has_ordinal = Some(rg_has_ordinal);
937        }
938
939        // assign ordinal if missing and consistent with first row group
940        let first_has_ordinal = self.first_has_ordinal.unwrap();
941        if !first_has_ordinal && !rg_has_ordinal {
942            rg.ordinal = Some(actual_ordinal);
943        } else if first_has_ordinal != rg_has_ordinal {
944            return Err(general_err!(
945                "Inconsistent ordinal assignment: first_has_ordinal is set to \
946                {} but row-group with actual ordinal {} has rg_has_ordinal set to {}",
947                first_has_ordinal,
948                actual_ordinal,
949                rg_has_ordinal
950            ));
951        }
952        Ok(rg)
953    }
954}
955
956thrift_struct!(
957    pub(crate) struct IndexPageHeader {}
958);
959
960thrift_struct!(
961pub(crate) struct DictionaryPageHeader {
962  /// Number of values in the dictionary
963  1: required i32 num_values;
964
965  /// Encoding using this dictionary page
966  2: required Encoding encoding
967
968  /// If true, the entries in the dictionary are sorted in ascending order
969  3: optional bool is_sorted;
970}
971);
972
973thrift_struct!(
974/// Statistics for the page header.
975///
976/// This is a duplicate of the [`Statistics`] struct above. Because the page reader uses
977/// the [`Read`] API, we cannot read the min/max values as slices. This should not be
978/// a huge problem since this crate no longer reads the page header statistics by default.
979///
980/// [`Read`]: crate::parquet_thrift::ThriftReadInputProtocol
981pub(crate) struct PageStatistics {
982   1: optional binary max;
983   2: optional binary min;
984   3: optional i64 null_count;
985   4: optional i64 distinct_count;
986   5: optional binary max_value;
987   6: optional binary min_value;
988   7: optional bool is_max_value_exact;
989   8: optional bool is_min_value_exact;
990}
991);
992
993thrift_struct!(
994pub(crate) struct DataPageHeader {
995  1: required i32 num_values
996  2: required Encoding encoding
997  3: required Encoding definition_level_encoding;
998  4: required Encoding repetition_level_encoding;
999  5: optional PageStatistics statistics;
1000}
1001);
1002
1003impl DataPageHeader {
1004    // reader that skips decoding page statistics
1005    fn read_thrift_without_stats<'a, R>(prot: &mut R) -> Result<Self>
1006    where
1007        R: ThriftCompactInputProtocol<'a>,
1008    {
1009        let mut num_values: Option<i32> = None;
1010        let mut encoding: Option<Encoding> = None;
1011        let mut definition_level_encoding: Option<Encoding> = None;
1012        let mut repetition_level_encoding: Option<Encoding> = None;
1013        let statistics: Option<PageStatistics> = None;
1014        let mut last_field_id = 0i16;
1015        loop {
1016            let field_ident = prot.read_field_begin(last_field_id)?;
1017            if field_ident.field_type == FieldType::Stop {
1018                break;
1019            }
1020            match field_ident.id {
1021                1 => {
1022                    let val = i32::read_thrift(&mut *prot)?;
1023                    num_values = Some(val);
1024                }
1025                2 => {
1026                    let val = Encoding::read_thrift(&mut *prot)?;
1027                    encoding = Some(val);
1028                }
1029                3 => {
1030                    let val = Encoding::read_thrift(&mut *prot)?;
1031                    definition_level_encoding = Some(val);
1032                }
1033                4 => {
1034                    let val = Encoding::read_thrift(&mut *prot)?;
1035                    repetition_level_encoding = Some(val);
1036                }
1037                _ => {
1038                    prot.skip(field_ident.field_type)?;
1039                }
1040            };
1041            last_field_id = field_ident.id;
1042        }
1043        let Some(num_values) = num_values else {
1044            return Err(general_err!("Required field num_values is missing"));
1045        };
1046        let Some(encoding) = encoding else {
1047            return Err(general_err!("Required field encoding is missing"));
1048        };
1049        let Some(definition_level_encoding) = definition_level_encoding else {
1050            return Err(general_err!(
1051                "Required field definition_level_encoding is missing"
1052            ));
1053        };
1054        let Some(repetition_level_encoding) = repetition_level_encoding else {
1055            return Err(general_err!(
1056                "Required field repetition_level_encoding is missing"
1057            ));
1058        };
1059        Ok(Self {
1060            num_values,
1061            encoding,
1062            definition_level_encoding,
1063            repetition_level_encoding,
1064            statistics,
1065        })
1066    }
1067}
1068
1069thrift_struct!(
1070pub(crate) struct DataPageHeaderV2 {
1071  1: required i32 num_values
1072  2: required i32 num_nulls
1073  3: required i32 num_rows
1074  4: required Encoding encoding
1075  5: required i32 definition_levels_byte_length;
1076  6: required i32 repetition_levels_byte_length;
1077  7: optional bool is_compressed = true;
1078  8: optional PageStatistics statistics;
1079}
1080);
1081
1082impl DataPageHeaderV2 {
1083    // reader that skips decoding page statistics
1084    fn read_thrift_without_stats<'a, R>(prot: &mut R) -> Result<Self>
1085    where
1086        R: ThriftCompactInputProtocol<'a>,
1087    {
1088        let mut num_values: Option<i32> = None;
1089        let mut num_nulls: Option<i32> = None;
1090        let mut num_rows: Option<i32> = None;
1091        let mut encoding: Option<Encoding> = None;
1092        let mut definition_levels_byte_length: Option<i32> = None;
1093        let mut repetition_levels_byte_length: Option<i32> = None;
1094        let mut is_compressed: Option<bool> = None;
1095        let statistics: Option<PageStatistics> = None;
1096        let mut last_field_id = 0i16;
1097        loop {
1098            let field_ident = prot.read_field_begin(last_field_id)?;
1099            if field_ident.field_type == FieldType::Stop {
1100                break;
1101            }
1102            match field_ident.id {
1103                1 => {
1104                    let val = i32::read_thrift(&mut *prot)?;
1105                    num_values = Some(val);
1106                }
1107                2 => {
1108                    let val = i32::read_thrift(&mut *prot)?;
1109                    num_nulls = Some(val);
1110                }
1111                3 => {
1112                    let val = i32::read_thrift(&mut *prot)?;
1113                    num_rows = Some(val);
1114                }
1115                4 => {
1116                    let val = Encoding::read_thrift(&mut *prot)?;
1117                    encoding = Some(val);
1118                }
1119                5 => {
1120                    let val = i32::read_thrift(&mut *prot)?;
1121                    definition_levels_byte_length = Some(val);
1122                }
1123                6 => {
1124                    let val = i32::read_thrift(&mut *prot)?;
1125                    repetition_levels_byte_length = Some(val);
1126                }
1127                7 => {
1128                    let val = field_ident.bool_val.unwrap();
1129                    is_compressed = Some(val);
1130                }
1131                _ => {
1132                    prot.skip(field_ident.field_type)?;
1133                }
1134            };
1135            last_field_id = field_ident.id;
1136        }
1137        let Some(num_values) = num_values else {
1138            return Err(general_err!("Required field num_values is missing"));
1139        };
1140        let Some(num_nulls) = num_nulls else {
1141            return Err(general_err!("Required field num_nulls is missing"));
1142        };
1143        let Some(num_rows) = num_rows else {
1144            return Err(general_err!("Required field num_rows is missing"));
1145        };
1146        let Some(encoding) = encoding else {
1147            return Err(general_err!("Required field encoding is missing"));
1148        };
1149        let Some(definition_levels_byte_length) = definition_levels_byte_length else {
1150            return Err(general_err!(
1151                "Required field definition_levels_byte_length is missing"
1152            ));
1153        };
1154        let Some(repetition_levels_byte_length) = repetition_levels_byte_length else {
1155            return Err(general_err!(
1156                "Required field repetition_levels_byte_length is missing"
1157            ));
1158        };
1159        Ok(Self {
1160            num_values,
1161            num_nulls,
1162            num_rows,
1163            encoding,
1164            definition_levels_byte_length,
1165            repetition_levels_byte_length,
1166            is_compressed,
1167            statistics,
1168        })
1169    }
1170}
1171
1172thrift_struct!(
1173pub(crate) struct PageHeader {
1174  /// the type of the page: indicates which of the *_header fields is set
1175  1: required PageType r#type
1176
1177  /// Uncompressed page size in bytes (not including this header)
1178  2: required i32 uncompressed_page_size
1179
1180  /// Compressed (and potentially encrypted) page size in bytes, not including this header
1181  3: required i32 compressed_page_size
1182
1183  /// The 32-bit CRC checksum for the page, to be be calculated as follows:
1184  4: optional i32 crc
1185
1186  // Headers for page specific data.  One only will be set.
1187  5: optional DataPageHeader data_page_header;
1188  6: optional IndexPageHeader index_page_header;
1189  7: optional DictionaryPageHeader dictionary_page_header;
1190  8: optional DataPageHeaderV2 data_page_header_v2;
1191}
1192);
1193
1194impl PageHeader {
1195    // reader that skips reading page statistics. obtained by running
1196    // `cargo expand -p parquet --all-features --lib file::metadata::thrift`
1197    // and modifying the impl of `read_thrift`
1198    pub(crate) fn read_thrift_without_stats<'a, R>(prot: &mut R) -> Result<Self>
1199    where
1200        R: ThriftCompactInputProtocol<'a>,
1201    {
1202        let mut type_: Option<PageType> = None;
1203        let mut uncompressed_page_size: Option<i32> = None;
1204        let mut compressed_page_size: Option<i32> = None;
1205        let mut crc: Option<i32> = None;
1206        let mut data_page_header: Option<DataPageHeader> = None;
1207        let mut index_page_header: Option<IndexPageHeader> = None;
1208        let mut dictionary_page_header: Option<DictionaryPageHeader> = None;
1209        let mut data_page_header_v2: Option<DataPageHeaderV2> = None;
1210        let mut last_field_id = 0i16;
1211        loop {
1212            let field_ident = prot.read_field_begin(last_field_id)?;
1213            if field_ident.field_type == FieldType::Stop {
1214                break;
1215            }
1216            match field_ident.id {
1217                1 => {
1218                    let val = PageType::read_thrift(&mut *prot)?;
1219                    type_ = Some(val);
1220                }
1221                2 => {
1222                    let val = i32::read_thrift(&mut *prot)?;
1223                    uncompressed_page_size = Some(val);
1224                }
1225                3 => {
1226                    let val = i32::read_thrift(&mut *prot)?;
1227                    compressed_page_size = Some(val);
1228                }
1229                4 => {
1230                    let val = i32::read_thrift(&mut *prot)?;
1231                    crc = Some(val);
1232                }
1233                5 => {
1234                    let val = DataPageHeader::read_thrift_without_stats(&mut *prot)?;
1235                    data_page_header = Some(val);
1236                }
1237                6 => {
1238                    let val = IndexPageHeader::read_thrift(&mut *prot)?;
1239                    index_page_header = Some(val);
1240                }
1241                7 => {
1242                    let val = DictionaryPageHeader::read_thrift(&mut *prot)?;
1243                    dictionary_page_header = Some(val);
1244                }
1245                8 => {
1246                    let val = DataPageHeaderV2::read_thrift_without_stats(&mut *prot)?;
1247                    data_page_header_v2 = Some(val);
1248                }
1249                _ => {
1250                    prot.skip(field_ident.field_type)?;
1251                }
1252            };
1253            last_field_id = field_ident.id;
1254        }
1255        let Some(type_) = type_ else {
1256            return Err(general_err!("Required field type_ is missing"));
1257        };
1258        let Some(uncompressed_page_size) = uncompressed_page_size else {
1259            return Err(general_err!(
1260                "Required field uncompressed_page_size is missing"
1261            ));
1262        };
1263        let Some(compressed_page_size) = compressed_page_size else {
1264            return Err(general_err!(
1265                "Required field compressed_page_size is missing"
1266            ));
1267        };
1268        Ok(Self {
1269            r#type: type_,
1270            uncompressed_page_size,
1271            compressed_page_size,
1272            crc,
1273            data_page_header,
1274            index_page_header,
1275            dictionary_page_header,
1276            data_page_header_v2,
1277        })
1278    }
1279}
1280
1281/////////////////////////////////////////////////
1282// helper functions for writing file meta data
1283
1284// serialize the bits of the column chunk needed for a thrift ColumnMetaData
1285// struct ColumnMetaData {
1286//   1: required Type type
1287//   2: required list<Encoding> encodings
1288//   3: required list<string> path_in_schema
1289//   4: required CompressionCodec codec
1290//   5: required i64 num_values
1291//   6: required i64 total_uncompressed_size
1292//   7: required i64 total_compressed_size
1293//   8: optional list<KeyValue> key_value_metadata
1294//   9: required i64 data_page_offset
1295//   10: optional i64 index_page_offset
1296//   11: optional i64 dictionary_page_offset
1297//   12: optional Statistics statistics;
1298//   13: optional list<PageEncodingStats> encoding_stats;
1299//   14: optional i64 bloom_filter_offset;
1300//   15: optional i32 bloom_filter_length;
1301//   16: optional SizeStatistics size_statistics;
1302//   17: optional GeospatialStatistics geospatial_statistics;
1303// }
1304pub(super) fn serialize_column_meta_data<W: Write>(
1305    column_chunk: &ColumnChunkMetaData,
1306    w: &mut ThriftCompactOutputProtocol<W>,
1307) -> Result<()> {
1308    use crate::file::statistics::page_stats_to_thrift;
1309
1310    column_chunk.column_type().write_thrift_field(w, 1, 0)?;
1311    column_chunk
1312        .encodings()
1313        .collect::<Vec<_>>()
1314        .write_thrift_field(w, 2, 1)?;
1315    let path = column_chunk.column_descr.path().parts();
1316    let path: Vec<&str> = path.iter().map(|v| v.as_str()).collect();
1317    path.write_thrift_field(w, 3, 2)?;
1318    column_chunk.compression.write_thrift_field(w, 4, 3)?;
1319    column_chunk.num_values.write_thrift_field(w, 5, 4)?;
1320    column_chunk
1321        .total_uncompressed_size
1322        .write_thrift_field(w, 6, 5)?;
1323    column_chunk
1324        .total_compressed_size
1325        .write_thrift_field(w, 7, 6)?;
1326    // no key_value_metadata here
1327    let mut last_field_id = column_chunk.data_page_offset.write_thrift_field(w, 9, 7)?;
1328    if let Some(index_page_offset) = column_chunk.index_page_offset {
1329        last_field_id = index_page_offset.write_thrift_field(w, 10, last_field_id)?;
1330    }
1331    if let Some(dictionary_page_offset) = column_chunk.dictionary_page_offset {
1332        last_field_id = dictionary_page_offset.write_thrift_field(w, 11, last_field_id)?;
1333    }
1334    // PageStatistics is the same as thrift Statistics, but writable
1335    let stats = page_stats_to_thrift(column_chunk.statistics());
1336    if let Some(stats) = stats {
1337        last_field_id = stats.write_thrift_field(w, 12, last_field_id)?;
1338    }
1339    if let Some(page_encoding_stats) = column_chunk.page_encoding_stats() {
1340        last_field_id = page_encoding_stats.write_thrift_field(w, 13, last_field_id)?;
1341    }
1342    if let Some(bloom_filter_offset) = column_chunk.bloom_filter_offset {
1343        last_field_id = bloom_filter_offset.write_thrift_field(w, 14, last_field_id)?;
1344    }
1345    if let Some(bloom_filter_length) = column_chunk.bloom_filter_length {
1346        last_field_id = bloom_filter_length.write_thrift_field(w, 15, last_field_id)?;
1347    }
1348
1349    // SizeStatistics
1350    let size_stats = if column_chunk.unencoded_byte_array_data_bytes.is_some()
1351        || column_chunk.repetition_level_histogram.is_some()
1352        || column_chunk.definition_level_histogram.is_some()
1353    {
1354        let repetition_level_histogram = column_chunk
1355            .repetition_level_histogram()
1356            .map(|hist| hist.clone().into_inner());
1357
1358        let definition_level_histogram = column_chunk
1359            .definition_level_histogram()
1360            .map(|hist| hist.clone().into_inner());
1361
1362        Some(SizeStatistics {
1363            unencoded_byte_array_data_bytes: column_chunk.unencoded_byte_array_data_bytes,
1364            repetition_level_histogram,
1365            definition_level_histogram,
1366        })
1367    } else {
1368        None
1369    };
1370    if let Some(size_stats) = size_stats {
1371        last_field_id = size_stats.write_thrift_field(w, 16, last_field_id)?;
1372    }
1373
1374    if let Some(geo_stats) = column_chunk.geo_statistics() {
1375        geo_stats.write_thrift_field(w, 17, last_field_id)?;
1376    }
1377
1378    w.write_struct_end()
1379}
1380
1381// temp struct used for writing
1382pub(super) struct FileMeta<'a> {
1383    pub(super) file_metadata: &'a crate::file::metadata::FileMetaData,
1384    pub(super) row_groups: &'a Vec<RowGroupMetaData>,
1385}
1386
1387// struct FileMetaData {
1388//   1: required i32 version
1389//   2: required list<SchemaElement> schema;
1390//   3: required i64 num_rows
1391//   4: required list<RowGroup> row_groups
1392//   5: optional list<KeyValue> key_value_metadata
1393//   6: optional string created_by
1394//   7: optional list<ColumnOrder> column_orders;
1395//   8: optional EncryptionAlgorithm encryption_algorithm
1396//   9: optional binary footer_signing_key_metadata
1397// }
1398impl<'a> WriteThrift for FileMeta<'a> {
1399    const ELEMENT_TYPE: ElementType = ElementType::Struct;
1400
1401    // needed for last_field_id w/o encryption
1402    #[allow(unused_assignments)]
1403    fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
1404        self.file_metadata
1405            .version
1406            .write_thrift_field(writer, 1, 0)?;
1407
1408        // field 2 is schema. do depth-first traversal of tree, converting to SchemaElement and
1409        // writing along the way.
1410        let root = self.file_metadata.schema_descr().root_schema_ptr();
1411        let schema_len = num_nodes(&root)?;
1412        writer.write_field_begin(FieldType::List, 2, 1)?;
1413        writer.write_list_begin(ElementType::Struct, schema_len)?;
1414        // recursively write Type nodes as SchemaElements
1415        write_schema(&root, writer)?;
1416
1417        self.file_metadata
1418            .num_rows
1419            .write_thrift_field(writer, 3, 2)?;
1420
1421        // this will call RowGroupMetaData::write_thrift
1422        let mut last_field_id = self.row_groups.write_thrift_field(writer, 4, 3)?;
1423
1424        if let Some(kv_metadata) = self.file_metadata.key_value_metadata() {
1425            last_field_id = kv_metadata.write_thrift_field(writer, 5, last_field_id)?;
1426        }
1427        if let Some(created_by) = self.file_metadata.created_by() {
1428            last_field_id = created_by.write_thrift_field(writer, 6, last_field_id)?;
1429        }
1430        if let Some(column_orders) = self.file_metadata.column_orders() {
1431            last_field_id = column_orders.write_thrift_field(writer, 7, last_field_id)?;
1432        }
1433        #[cfg(feature = "encryption")]
1434        if let Some(algo) = self.file_metadata.encryption_algorithm.as_ref() {
1435            last_field_id = algo.write_thrift_field(writer, 8, last_field_id)?;
1436        }
1437        #[cfg(feature = "encryption")]
1438        if let Some(key) = self.file_metadata.footer_signing_key_metadata.as_ref() {
1439            key.as_slice()
1440                .write_thrift_field(writer, 9, last_field_id)?;
1441        }
1442
1443        writer.write_struct_end()
1444    }
1445}
1446
1447fn write_schema<W: Write>(
1448    schema: &TypePtr,
1449    writer: &mut ThriftCompactOutputProtocol<W>,
1450) -> Result<()> {
1451    if !schema.is_group() {
1452        return Err(general_err!("Root schema must be Group type"));
1453    }
1454    write_schema_helper(schema, writer)
1455}
1456
1457fn write_schema_helper<W: Write>(
1458    node: &TypePtr,
1459    writer: &mut ThriftCompactOutputProtocol<W>,
1460) -> Result<()> {
1461    match node.as_ref() {
1462        crate::schema::types::Type::PrimitiveType {
1463            basic_info,
1464            physical_type,
1465            type_length,
1466            scale,
1467            precision,
1468        } => {
1469            let element = SchemaElement {
1470                r#type: Some(*physical_type),
1471                type_length: if *type_length >= 0 {
1472                    Some(*type_length)
1473                } else {
1474                    None
1475                },
1476                repetition_type: Some(basic_info.repetition()),
1477                name: basic_info.name(),
1478                num_children: None,
1479                converted_type: match basic_info.converted_type() {
1480                    ConvertedType::NONE => None,
1481                    other => Some(other),
1482                },
1483                scale: if *scale >= 0 { Some(*scale) } else { None },
1484                precision: if *precision >= 0 {
1485                    Some(*precision)
1486                } else {
1487                    None
1488                },
1489                field_id: if basic_info.has_id() {
1490                    Some(basic_info.id())
1491                } else {
1492                    None
1493                },
1494                logical_type: basic_info.logical_type_ref().cloned(),
1495            };
1496            element.write_thrift(writer)
1497        }
1498        crate::schema::types::Type::GroupType { basic_info, fields } => {
1499            let repetition = if basic_info.has_repetition() {
1500                Some(basic_info.repetition())
1501            } else {
1502                None
1503            };
1504
1505            let element = SchemaElement {
1506                r#type: None,
1507                type_length: None,
1508                repetition_type: repetition,
1509                name: basic_info.name(),
1510                num_children: Some(fields.len().try_into()?),
1511                converted_type: match basic_info.converted_type() {
1512                    ConvertedType::NONE => None,
1513                    other => Some(other),
1514                },
1515                scale: None,
1516                precision: None,
1517                field_id: if basic_info.has_id() {
1518                    Some(basic_info.id())
1519                } else {
1520                    None
1521                },
1522                logical_type: basic_info.logical_type_ref().cloned(),
1523            };
1524
1525            element.write_thrift(writer)?;
1526
1527            // Add child elements for a group
1528            for field in fields {
1529                write_schema_helper(field, writer)?;
1530            }
1531            Ok(())
1532        }
1533    }
1534}
1535
1536// struct RowGroup {
1537//   1: required list<ColumnChunk> columns
1538//   2: required i64 total_byte_size
1539//   3: required i64 num_rows
1540//   4: optional list<SortingColumn> sorting_columns
1541//   5: optional i64 file_offset
1542//   6: optional i64 total_compressed_size
1543//   7: optional i16 ordinal
1544// }
1545impl WriteThrift for RowGroupMetaData {
1546    const ELEMENT_TYPE: ElementType = ElementType::Struct;
1547
1548    fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
1549        // this will call ColumnChunkMetaData::write_thrift
1550        self.columns.write_thrift_field(writer, 1, 0)?;
1551        self.total_byte_size.write_thrift_field(writer, 2, 1)?;
1552        let mut last_field_id = self.num_rows.write_thrift_field(writer, 3, 2)?;
1553        if let Some(sorting_columns) = self.sorting_columns() {
1554            last_field_id = sorting_columns.write_thrift_field(writer, 4, last_field_id)?;
1555        }
1556        if let Some(file_offset) = self.file_offset() {
1557            last_field_id = file_offset.write_thrift_field(writer, 5, last_field_id)?;
1558        }
1559        // this is optional, but we'll always write it
1560        last_field_id = self
1561            .compressed_size()
1562            .write_thrift_field(writer, 6, last_field_id)?;
1563        if let Some(ordinal) = self.ordinal() {
1564            ordinal.write_thrift_field(writer, 7, last_field_id)?;
1565        }
1566        writer.write_struct_end()
1567    }
1568}
1569
1570// struct ColumnChunk {
1571//   1: optional string file_path
1572//   2: required i64 file_offset = 0
1573//   3: optional ColumnMetaData meta_data
1574//   4: optional i64 offset_index_offset
1575//   5: optional i32 offset_index_length
1576//   6: optional i64 column_index_offset
1577//   7: optional i32 column_index_length
1578//   8: optional ColumnCryptoMetaData crypto_metadata
1579//   9: optional binary encrypted_column_metadata
1580// }
1581impl WriteThrift for ColumnChunkMetaData {
1582    const ELEMENT_TYPE: ElementType = ElementType::Struct;
1583
1584    #[allow(unused_assignments)]
1585    fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
1586        let mut last_field_id = 0i16;
1587        if let Some(file_path) = self.file_path() {
1588            last_field_id = file_path.write_thrift_field(writer, 1, last_field_id)?;
1589        }
1590        last_field_id = self
1591            .file_offset()
1592            .write_thrift_field(writer, 2, last_field_id)?;
1593
1594        #[cfg(feature = "encryption")]
1595        {
1596            // only write the ColumnMetaData if we haven't already encrypted it
1597            if self.encrypted_column_metadata.is_none() {
1598                writer.write_field_begin(FieldType::Struct, 3, last_field_id)?;
1599                serialize_column_meta_data(self, writer)?;
1600                last_field_id = 3;
1601            }
1602        }
1603        #[cfg(not(feature = "encryption"))]
1604        {
1605            // always write the ColumnMetaData
1606            writer.write_field_begin(FieldType::Struct, 3, last_field_id)?;
1607            serialize_column_meta_data(self, writer)?;
1608            last_field_id = 3;
1609        }
1610
1611        if let Some(offset_idx_off) = self.offset_index_offset() {
1612            last_field_id = offset_idx_off.write_thrift_field(writer, 4, last_field_id)?;
1613        }
1614        if let Some(offset_idx_len) = self.offset_index_length() {
1615            last_field_id = offset_idx_len.write_thrift_field(writer, 5, last_field_id)?;
1616        }
1617        if let Some(column_idx_off) = self.column_index_offset() {
1618            last_field_id = column_idx_off.write_thrift_field(writer, 6, last_field_id)?;
1619        }
1620        if let Some(column_idx_len) = self.column_index_length() {
1621            last_field_id = column_idx_len.write_thrift_field(writer, 7, last_field_id)?;
1622        }
1623        #[cfg(feature = "encryption")]
1624        {
1625            if let Some(crypto_metadata) = self.crypto_metadata() {
1626                last_field_id = crypto_metadata.write_thrift_field(writer, 8, last_field_id)?;
1627            }
1628            if let Some(encrypted_meta) = self.encrypted_column_metadata.as_ref() {
1629                encrypted_meta
1630                    .as_slice()
1631                    .write_thrift_field(writer, 9, last_field_id)?;
1632            }
1633        }
1634
1635        writer.write_struct_end()
1636    }
1637}
1638
1639// struct GeospatialStatistics {
1640//   1: optional BoundingBox bbox;
1641//   2: optional list<i32> geospatial_types;
1642// }
1643impl WriteThrift for crate::geospatial::statistics::GeospatialStatistics {
1644    const ELEMENT_TYPE: ElementType = ElementType::Struct;
1645
1646    fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
1647        let mut last_field_id = 0i16;
1648        if let Some(bbox) = self.bounding_box() {
1649            last_field_id = bbox.write_thrift_field(writer, 1, last_field_id)?;
1650        }
1651        if let Some(geo_types) = self.geospatial_types() {
1652            geo_types.write_thrift_field(writer, 2, last_field_id)?;
1653        }
1654
1655        writer.write_struct_end()
1656    }
1657}
1658
1659// macro cannot handle qualified names
1660use crate::geospatial::statistics::GeospatialStatistics as RustGeospatialStatistics;
1661write_thrift_field!(RustGeospatialStatistics, FieldType::Struct);
1662
1663// struct BoundingBox {
1664//   1: required double xmin;
1665//   2: required double xmax;
1666//   3: required double ymin;
1667//   4: required double ymax;
1668//   5: optional double zmin;
1669//   6: optional double zmax;
1670//   7: optional double mmin;
1671//   8: optional double mmax;
1672// }
1673impl WriteThrift for crate::geospatial::bounding_box::BoundingBox {
1674    const ELEMENT_TYPE: ElementType = ElementType::Struct;
1675
1676    fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
1677        self.get_xmin().write_thrift_field(writer, 1, 0)?;
1678        self.get_xmax().write_thrift_field(writer, 2, 1)?;
1679        self.get_ymin().write_thrift_field(writer, 3, 2)?;
1680        let mut last_field_id = self.get_ymax().write_thrift_field(writer, 4, 3)?;
1681
1682        if let Some(zmin) = self.get_zmin() {
1683            last_field_id = zmin.write_thrift_field(writer, 5, last_field_id)?;
1684        }
1685        if let Some(zmax) = self.get_zmax() {
1686            last_field_id = zmax.write_thrift_field(writer, 6, last_field_id)?;
1687        }
1688        if let Some(mmin) = self.get_mmin() {
1689            last_field_id = mmin.write_thrift_field(writer, 7, last_field_id)?;
1690        }
1691        if let Some(mmax) = self.get_mmax() {
1692            mmax.write_thrift_field(writer, 8, last_field_id)?;
1693        }
1694
1695        writer.write_struct_end()
1696    }
1697}
1698
1699// macro cannot handle qualified names
1700use crate::geospatial::bounding_box::BoundingBox as RustBoundingBox;
1701write_thrift_field!(RustBoundingBox, FieldType::Struct);
1702
1703#[cfg(test)]
1704pub(crate) mod tests {
1705    use crate::errors::Result;
1706    use crate::file::metadata::thrift::{BoundingBox, SchemaElement, write_schema};
1707    use crate::file::metadata::{ColumnChunkMetaData, RowGroupMetaData};
1708    use crate::parquet_thrift::tests::test_roundtrip;
1709    use crate::parquet_thrift::{
1710        ElementType, ThriftCompactOutputProtocol, ThriftSliceInputProtocol, read_thrift_vec,
1711    };
1712    use crate::schema::types::{
1713        ColumnDescriptor, SchemaDescriptor, TypePtr, num_nodes, parquet_schema_from_array,
1714    };
1715    use std::sync::Arc;
1716
1717    // for testing. decode thrift encoded RowGroup
1718    pub(crate) fn read_row_group(
1719        buf: &mut [u8],
1720        schema_descr: Arc<SchemaDescriptor>,
1721    ) -> Result<RowGroupMetaData> {
1722        let mut reader = ThriftSliceInputProtocol::new(buf);
1723        crate::file::metadata::thrift::read_row_group(&mut reader, &schema_descr, None)
1724    }
1725
1726    pub(crate) fn read_column_chunk(
1727        buf: &mut [u8],
1728        column_descr: Arc<ColumnDescriptor>,
1729    ) -> Result<ColumnChunkMetaData> {
1730        let mut reader = ThriftSliceInputProtocol::new(buf);
1731        crate::file::metadata::thrift::read_column_chunk(&mut reader, &column_descr, 0, None)
1732    }
1733
1734    pub(crate) fn roundtrip_schema(schema: TypePtr) -> Result<TypePtr> {
1735        let num_nodes = num_nodes(&schema)?;
1736        let mut buf = Vec::new();
1737        let mut writer = ThriftCompactOutputProtocol::new(&mut buf);
1738
1739        // kick off writing list
1740        writer.write_list_begin(ElementType::Struct, num_nodes)?;
1741
1742        // write SchemaElements
1743        write_schema(&schema, &mut writer)?;
1744
1745        let mut prot = ThriftSliceInputProtocol::new(&buf);
1746        let se: Vec<SchemaElement> = read_thrift_vec(&mut prot)?;
1747        parquet_schema_from_array(se)
1748    }
1749
1750    pub(crate) fn schema_to_buf(schema: &TypePtr) -> Result<Vec<u8>> {
1751        let num_nodes = num_nodes(schema)?;
1752        let mut buf = Vec::new();
1753        let mut writer = ThriftCompactOutputProtocol::new(&mut buf);
1754
1755        // kick off writing list
1756        writer.write_list_begin(ElementType::Struct, num_nodes)?;
1757
1758        // write SchemaElements
1759        write_schema(schema, &mut writer)?;
1760        Ok(buf)
1761    }
1762
1763    pub(crate) fn buf_to_schema_list<'a>(buf: &'a mut Vec<u8>) -> Result<Vec<SchemaElement<'a>>> {
1764        let mut prot = ThriftSliceInputProtocol::new(buf.as_mut_slice());
1765        read_thrift_vec(&mut prot)
1766    }
1767
1768    #[test]
1769    fn test_bounding_box_roundtrip() {
1770        test_roundtrip(BoundingBox {
1771            xmin: 0.1.into(),
1772            xmax: 10.3.into(),
1773            ymin: 0.001.into(),
1774            ymax: 128.5.into(),
1775            zmin: None,
1776            zmax: None,
1777            mmin: None,
1778            mmax: None,
1779        });
1780
1781        test_roundtrip(BoundingBox {
1782            xmin: 0.1.into(),
1783            xmax: 10.3.into(),
1784            ymin: 0.001.into(),
1785            ymax: 128.5.into(),
1786            zmin: Some(11.0.into()),
1787            zmax: Some(1300.0.into()),
1788            mmin: None,
1789            mmax: None,
1790        });
1791
1792        test_roundtrip(BoundingBox {
1793            xmin: 0.1.into(),
1794            xmax: 10.3.into(),
1795            ymin: 0.001.into(),
1796            ymax: 128.5.into(),
1797            zmin: Some(11.0.into()),
1798            zmax: Some(1300.0.into()),
1799            mmin: Some(3.7.into()),
1800            mmax: Some(42.0.into()),
1801        });
1802    }
1803}