Skip to main content

parquet/arrow/arrow_writer/
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//! Contains writer which writes arrow data into parquet data.
19
20use crate::column::chunker::ContentDefinedChunker;
21
22use bytes::Bytes;
23use std::io::Write;
24use std::slice::Iter;
25use std::sync::{Arc, Mutex};
26use std::vec::IntoIter;
27
28use arrow_array::cast::AsArray;
29use arrow_array::{ArrayRef, Int32Array, RecordBatch, RecordBatchWriter};
30use arrow_array::{PrimitiveArray, types::*};
31use arrow_schema::{
32    ArrowError, DataType as ArrowDataType, Field, IntervalUnit, SchemaRef, TimeUnit,
33};
34
35use super::schema::{add_encoded_arrow_schema_to_metadata, decimal_length_from_precision};
36
37use crate::arrow::ArrowSchemaConverter;
38use crate::arrow::arrow_writer::byte_array::ByteArrayEncoder;
39use crate::basic::PageType;
40use crate::column::page::{CompressedPage, PageWriteSpec, PageWriter};
41use crate::column::page_encryption::PageEncryptor;
42use crate::column::writer::encoder::ColumnValueEncoder;
43use crate::column::writer::{
44    ColumnCloseResult, ColumnWriter, GenericColumnWriter, get_column_writer,
45};
46use crate::data_type::{ByteArray, FixedLenByteArray};
47use std::collections::HashSet;
48type DistinctValuesSet = HashSet<u64>;
49#[cfg(feature = "encryption")]
50use crate::encryption::encrypt::FileEncryptor;
51use crate::errors::{ParquetError, Result};
52use crate::file::metadata::{KeyValue, ParquetMetaData, RowGroupMetaData};
53use crate::file::properties::{WriterProperties, WriterPropertiesPtr};
54use crate::file::writer::{SerializedFileWriter, SerializedRowGroupWriter};
55use crate::parquet_thrift::{ThriftCompactOutputProtocol, WriteThrift};
56use crate::schema::types::{ColumnDescPtr, SchemaDescPtr, SchemaDescriptor};
57use levels::{ArrayLevels, calculate_array_levels};
58
59mod byte_array;
60mod levels;
61
62#[doc(inline)]
63pub use crate::column::page_store::{
64    InMemoryPageStore, InMemoryPageStoreFactory, PageKey, PageStore, PageStoreArgs,
65    PageStoreFactory,
66};
67
68/// Encodes [`RecordBatch`] to parquet
69///
70/// Writes Arrow `RecordBatch`es to a Parquet writer. Multiple [`RecordBatch`] will be encoded
71/// to the same row group, up to `max_row_group_size` rows. Any remaining rows will be
72/// flushed on close, leading the final row group in the output file to potentially
73/// contain fewer than `max_row_group_size` rows
74///
75/// # Example: Writing `RecordBatch`es
76/// ```
77/// # use std::sync::Arc;
78/// # use bytes::Bytes;
79/// # use arrow_array::{ArrayRef, Int64Array};
80/// # use arrow_array::RecordBatch;
81/// # use parquet::arrow::arrow_writer::ArrowWriter;
82/// # use parquet::arrow::arrow_reader::ParquetRecordBatchReader;
83/// let col = Arc::new(Int64Array::from_iter_values([1, 2, 3])) as ArrayRef;
84/// let to_write = RecordBatch::try_from_iter([("col", col)]).unwrap();
85///
86/// let mut buffer = Vec::new();
87/// let mut writer = ArrowWriter::try_new(&mut buffer, to_write.schema(), None).unwrap();
88/// writer.write(&to_write).unwrap();
89/// writer.close().unwrap();
90///
91/// let mut reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), 1024).unwrap();
92/// let read = reader.next().unwrap().unwrap();
93///
94/// assert_eq!(to_write, read);
95/// ```
96///
97/// # Memory Usage and Limiting
98///
99/// The nature of Parquet requires buffering of an entire row group before it can
100/// be flushed to the underlying writer. Data is mostly buffered in its encoded
101/// form, reducing memory usage. However, some data such as dictionary keys,
102/// large strings or very nested data may still result in non-trivial memory
103/// usage.
104///
105/// See Also:
106/// * [`ArrowWriter::memory_size`]: the current memory usage of the writer.
107/// * [`ArrowWriter::in_progress_size`]: Estimated size of the buffered row group,
108///
109/// Call [`Self::flush`] to trigger an early flush of a row group based on a
110/// memory threshold and/or global memory pressure. However,  smaller row groups
111/// result in higher metadata overheads, and thus may worsen compression ratios
112/// and query performance.
113///
114/// ```no_run
115/// # use std::io::Write;
116/// # use arrow_array::RecordBatch;
117/// # use parquet::arrow::ArrowWriter;
118/// # let mut writer: ArrowWriter<Vec<u8>> = todo!();
119/// # let batch: RecordBatch = todo!();
120/// writer.write(&batch).unwrap();
121/// // Trigger an early flush if anticipated size exceeds 1_000_000
122/// if writer.in_progress_size() > 1_000_000 {
123///     writer.flush().unwrap();
124/// }
125/// ```
126///
127/// ## Type Support
128///
129/// The writer supports writing all Arrow [`DataType`]s that have a direct mapping to
130/// Parquet types including  [`StructArray`] and [`ListArray`].
131///
132/// The following are not supported:
133///
134/// * [`IntervalMonthDayNanoArray`]: Parquet does not [support nanosecond intervals].
135///
136/// [`DataType`]: https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html
137/// [`StructArray`]: https://docs.rs/arrow/latest/arrow/array/struct.StructArray.html
138/// [`ListArray`]: https://docs.rs/arrow/latest/arrow/array/type.ListArray.html
139/// [`IntervalMonthDayNanoArray`]: https://docs.rs/arrow/latest/arrow/array/type.IntervalMonthDayNanoArray.html
140/// [support nanosecond intervals]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md#interval
141///
142/// ## Type Compatibility
143/// The writer can write Arrow [`RecordBatch`]s that are logically equivalent. This means that for
144/// a  given column, the writer can accept multiple Arrow [`DataType`]s that contain the same
145/// value type.
146///
147/// For example, the following [`DataType`]s are all logically equivalent and can be written
148/// to the same column:
149/// * String, LargeString, StringView
150/// * Binary, LargeBinary, BinaryView
151///
152/// The writer can will also accept both native and dictionary encoded arrays if the dictionaries
153/// contain compatible values.
154/// ```
155/// # use std::sync::Arc;
156/// # use arrow_array::{DictionaryArray, LargeStringArray, RecordBatch, StringArray, UInt8Array};
157/// # use arrow_schema::{DataType, Field, Schema};
158/// # use parquet::arrow::arrow_writer::ArrowWriter;
159/// let record_batch1 = RecordBatch::try_new(
160///    Arc::new(Schema::new(vec![Field::new("col", DataType::LargeUtf8, false)])),
161///    vec![Arc::new(LargeStringArray::from_iter_values(vec!["a", "b"]))]
162///  )
163/// .unwrap();
164///
165/// let mut buffer = Vec::new();
166/// let mut writer = ArrowWriter::try_new(&mut buffer, record_batch1.schema(), None).unwrap();
167/// writer.write(&record_batch1).unwrap();
168///
169/// let record_batch2 = RecordBatch::try_new(
170///     Arc::new(Schema::new(vec![Field::new(
171///         "col",
172///         DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
173///          false,
174///     )])),
175///     vec![Arc::new(DictionaryArray::new(
176///          UInt8Array::from_iter_values(vec![0, 1]),
177///          Arc::new(StringArray::from_iter_values(vec!["b", "c"])),
178///      ))],
179///  )
180///  .unwrap();
181///  writer.write(&record_batch2).unwrap();
182///  writer.close();
183/// ```
184pub struct ArrowWriter<W: Write> {
185    /// Underlying Parquet writer
186    writer: SerializedFileWriter<W>,
187
188    /// The in-progress row group if any
189    in_progress: Option<ArrowRowGroupWriter>,
190
191    /// A copy of the Arrow schema.
192    ///
193    /// The schema is used to verify that each record batch written has the correct schema
194    arrow_schema: SchemaRef,
195
196    /// Creates new [`ArrowRowGroupWriter`] instances as required
197    row_group_writer_factory: ArrowRowGroupWriterFactory,
198
199    /// The maximum number of rows to write to each row group, or None for unlimited
200    max_row_group_row_count: Option<usize>,
201
202    /// The maximum size in bytes for a row group, or None for unlimited
203    max_row_group_bytes: Option<usize>,
204
205    /// CDC chunkers persisted across row groups (one per leaf column).
206    cdc_chunkers: Option<Vec<ContentDefinedChunker>>,
207}
208
209impl<W: Write + Send> std::fmt::Debug for ArrowWriter<W> {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        let buffered_memory = self.in_progress_size();
212        f.debug_struct("ArrowWriter")
213            .field("writer", &self.writer)
214            .field("in_progress_size", &format_args!("{buffered_memory} bytes"))
215            .field("in_progress_rows", &self.in_progress_rows())
216            .field("arrow_schema", &self.arrow_schema)
217            .field("max_row_group_row_count", &self.max_row_group_row_count)
218            .field("max_row_group_bytes", &self.max_row_group_bytes)
219            .finish()
220    }
221}
222
223impl<W: Write + Send> ArrowWriter<W> {
224    /// Try to create a new Arrow writer
225    ///
226    /// The writer will fail if:
227    ///  * a `SerializedFileWriter` cannot be created from the ParquetWriter
228    ///  * the Arrow schema contains unsupported datatypes such as Unions
229    pub fn try_new(
230        writer: W,
231        arrow_schema: SchemaRef,
232        props: Option<WriterProperties>,
233    ) -> Result<Self> {
234        let options = ArrowWriterOptions::new().with_properties(props.unwrap_or_default());
235        Self::try_new_with_options(writer, arrow_schema, options)
236    }
237
238    /// Try to create a new Arrow writer with [`ArrowWriterOptions`].
239    ///
240    /// The writer will fail if:
241    ///  * a `SerializedFileWriter` cannot be created from the ParquetWriter
242    ///  * the Arrow schema contains unsupported datatypes such as Unions
243    pub fn try_new_with_options(
244        writer: W,
245        arrow_schema: SchemaRef,
246        options: ArrowWriterOptions,
247    ) -> Result<Self> {
248        let mut props = options.properties;
249
250        let schema = if let Some(parquet_schema) = options.schema_descr {
251            parquet_schema.clone()
252        } else {
253            let mut converter = ArrowSchemaConverter::new().with_coerce_types(props.coerce_types());
254            if let Some(schema_root) = &options.schema_root {
255                converter = converter.schema_root(schema_root);
256            }
257
258            converter.convert(&arrow_schema)?
259        };
260
261        if !options.skip_arrow_metadata {
262            // add serialized arrow schema
263            add_encoded_arrow_schema_to_metadata(&arrow_schema, &mut props);
264        }
265
266        let max_row_group_row_count = props.max_row_group_row_count();
267        let max_row_group_bytes = props.max_row_group_bytes();
268
269        let props_ptr = Arc::new(props);
270        let file_writer =
271            SerializedFileWriter::new(writer, schema.root_schema_ptr(), Arc::clone(&props_ptr))?;
272
273        let mut row_group_writer_factory =
274            ArrowRowGroupWriterFactory::new(&file_writer, arrow_schema.clone());
275        if let Some(page_store_factory) = options.page_store_factory {
276            row_group_writer_factory =
277                row_group_writer_factory.with_page_store_factory(page_store_factory);
278        }
279
280        let cdc_chunkers = props_ptr
281            .content_defined_chunking()
282            .map(|opts| {
283                file_writer
284                    .schema_descr()
285                    .columns()
286                    .iter()
287                    .map(|desc| ContentDefinedChunker::new(desc, opts))
288                    .collect::<Result<Vec<_>>>()
289            })
290            .transpose()?;
291
292        Ok(Self {
293            writer: file_writer,
294            in_progress: None,
295            arrow_schema,
296            row_group_writer_factory,
297            max_row_group_row_count,
298            max_row_group_bytes,
299            cdc_chunkers,
300        })
301    }
302
303    /// Returns metadata for any flushed row groups
304    pub fn flushed_row_groups(&self) -> &[RowGroupMetaData] {
305        self.writer.flushed_row_groups()
306    }
307
308    /// Estimated memory usage, in bytes, of this `ArrowWriter`
309    ///
310    /// This estimate is formed bu summing the values of
311    /// [`ArrowColumnWriter::memory_size`] all in progress columns.
312    pub fn memory_size(&self) -> usize {
313        match &self.in_progress {
314            Some(in_progress) => in_progress.writers.iter().map(|x| x.memory_size()).sum(),
315            None => 0,
316        }
317    }
318
319    /// Anticipated encoded size of the in progress row group.
320    ///
321    /// This estimate the row group size after being completely encoded is,
322    /// formed by summing the values of
323    /// [`ArrowColumnWriter::get_estimated_total_bytes`] for all in progress
324    /// columns.
325    pub fn in_progress_size(&self) -> usize {
326        match &self.in_progress {
327            Some(in_progress) => in_progress
328                .writers
329                .iter()
330                .map(|x| x.get_estimated_total_bytes())
331                .sum(),
332            None => 0,
333        }
334    }
335
336    /// Returns the number of rows buffered in the in progress row group
337    pub fn in_progress_rows(&self) -> usize {
338        self.in_progress
339            .as_ref()
340            .map(|x| x.buffered_rows)
341            .unwrap_or_default()
342    }
343
344    /// Returns the number of bytes written by this instance
345    pub fn bytes_written(&self) -> usize {
346        self.writer.bytes_written()
347    }
348
349    /// Encodes the provided [`RecordBatch`]
350    ///
351    /// If this would cause the current row group to exceed [`WriterProperties::max_row_group_row_count`]
352    /// rows or [`WriterProperties::max_row_group_bytes`] bytes, the contents of `batch` will be
353    /// written to one or more row groups such that limits are respected.
354    ///
355    /// If both limits are `None`, all data is written to a single row group.
356    /// If one limit is set, that limit is respected.
357    /// If both limits are set, the lower bound (whichever triggers first) is respected.
358    ///
359    /// This will fail if the `batch`'s schema does not match the writer's schema.
360    pub fn write(&mut self, batch: &RecordBatch) -> Result<()> {
361        if batch.num_rows() == 0 {
362            return Ok(());
363        }
364
365        // Rows not yet handed to a row group writer. Splitting iterates here instead of
366        // recursing, so a small row group limit over a large batch cannot exhaust the stack.
367        let mut remaining = batch.clone();
368
369        loop {
370            let in_progress = match &mut self.in_progress {
371                Some(in_progress) => in_progress,
372                x => x.insert(
373                    self.row_group_writer_factory
374                        .create_row_group_writer(self.writer.flushed_row_groups().len())?,
375                ),
376            };
377            let buffered_rows = in_progress.buffered_rows;
378
379            // Leading rows of `remaining` that still fit in the current row group, when the
380            // rest has to go to a later one.
381            let mut split_at = match self.max_row_group_row_count {
382                Some(max_rows) if buffered_rows + remaining.num_rows() > max_rows => {
383                    Some(max_rows - buffered_rows)
384                }
385                _ => None,
386            };
387
388            // Check byte limit: if we have buffered data, use measured average row size
389            // to split batch proactively before exceeding byte limit. Both limits apply to
390            // the same rows, so measure against whatever the row limit already trimmed
391            // `remaining` down to; otherwise the row limit would always win.
392            let candidate_rows = split_at.unwrap_or_else(|| remaining.num_rows());
393
394            if let Some(max_bytes) = self.max_row_group_bytes
395                && buffered_rows > 0
396            {
397                let current_bytes = in_progress.get_estimated_total_bytes();
398
399                if current_bytes >= max_bytes {
400                    self.flush()?;
401                    continue;
402                }
403
404                let avg_row_bytes = current_bytes / buffered_rows;
405                if let Some(rows_that_fit) = (max_bytes - current_bytes).checked_div(avg_row_bytes)
406                {
407                    // At this point, `current_bytes < max_bytes` (checked above)
408                    if candidate_rows > rows_that_fit {
409                        if rows_that_fit > 0 {
410                            split_at = Some(rows_that_fit);
411                        } else {
412                            self.flush()?;
413                            continue;
414                        }
415                    }
416                }
417            }
418
419            let rest = split_at.map(|to_write| {
420                let rest = remaining.slice(to_write, remaining.num_rows() - to_write);
421                remaining = remaining.slice(0, to_write);
422                rest
423            });
424
425            let in_progress = self.in_progress.as_mut().unwrap();
426            match self.cdc_chunkers.as_mut() {
427                Some(chunkers) => in_progress.write_with_chunkers(&remaining, chunkers)?,
428                None => in_progress.write(&remaining)?,
429            }
430
431            let should_flush = self
432                .max_row_group_row_count
433                .is_some_and(|max| in_progress.buffered_rows >= max)
434                || self
435                    .max_row_group_bytes
436                    .is_some_and(|max| in_progress.get_estimated_total_bytes() >= max);
437
438            if should_flush {
439                self.flush()?
440            }
441
442            match rest {
443                Some(rest) => remaining = rest,
444                None => return Ok(()),
445            }
446        }
447    }
448
449    /// Writes the given buf bytes to the internal buffer.
450    ///
451    /// It's safe to use this method to write data to the underlying writer,
452    /// because it will ensure that the buffering and byte‐counting layers are used.
453    pub fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
454        self.writer.write_all(buf)
455    }
456
457    /// Flushes underlying writer
458    pub fn sync(&mut self) -> std::io::Result<()> {
459        self.writer.flush()
460    }
461
462    /// Flushes all buffered rows into a new row group
463    ///
464    /// Note the underlying writer is not flushed with this call.
465    /// If this is a desired behavior, please call [`ArrowWriter::sync`].
466    pub fn flush(&mut self) -> Result<()> {
467        let Some(in_progress) = self.in_progress.take() else {
468            return Ok(());
469        };
470
471        let mut row_group_writer = self.writer.next_row_group()?;
472        for chunk in in_progress.close()? {
473            chunk.append_to_row_group(&mut row_group_writer)?;
474        }
475        row_group_writer.close()?;
476        Ok(())
477    }
478
479    /// Additional [`KeyValue`] metadata to be written in addition to those from [`WriterProperties`]
480    ///
481    /// This method provide a way to append kv_metadata after write RecordBatch
482    pub fn append_key_value_metadata(&mut self, kv_metadata: KeyValue) {
483        self.writer.append_key_value_metadata(kv_metadata)
484    }
485
486    /// Returns a reference to the underlying writer.
487    pub fn inner(&self) -> &W {
488        self.writer.inner()
489    }
490
491    /// Returns a mutable reference to the underlying writer.
492    ///
493    /// **Warning**: if you write directly to this writer, you will skip
494    /// the `TrackedWrite` buffering and byte‐counting layers. That’ll cause
495    /// the file footer’s recorded offsets and sizes to diverge from reality,
496    /// resulting in an unreadable or corrupted Parquet file.
497    ///
498    /// If you want to write safely to the underlying writer, use [`Self::write_all`].
499    pub fn inner_mut(&mut self) -> &mut W {
500        self.writer.inner_mut()
501    }
502
503    /// Flushes any outstanding data and returns the underlying writer.
504    pub fn into_inner(mut self) -> Result<W> {
505        self.flush()?;
506        self.writer.into_inner()
507    }
508
509    /// Close and finalize the underlying Parquet writer
510    ///
511    /// Unlike [`Self::close`] this does not consume self
512    ///
513    /// Attempting to write after calling finish will result in an error
514    pub fn finish(&mut self) -> Result<ParquetMetaData> {
515        self.flush()?;
516        self.writer.finish()
517    }
518
519    /// Close and finalize the underlying Parquet writer
520    pub fn close(mut self) -> Result<ParquetMetaData> {
521        self.finish()
522    }
523
524    /// Converts this writer into a lower-level [`SerializedFileWriter`] and [`ArrowRowGroupWriterFactory`].
525    ///
526    /// Flushes any outstanding data before returning.
527    ///
528    /// This can be useful to provide more control over how files are written, for example
529    /// to write columns in parallel. See the example on [`ArrowColumnWriter`].
530    pub fn into_serialized_writer(
531        mut self,
532    ) -> Result<(SerializedFileWriter<W>, ArrowRowGroupWriterFactory)> {
533        self.flush()?;
534        Ok((self.writer, self.row_group_writer_factory))
535    }
536}
537
538impl<W: Write + Send> RecordBatchWriter for ArrowWriter<W> {
539    fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
540        self.write(batch).map_err(|e| e.into())
541    }
542
543    fn close(self) -> std::result::Result<(), ArrowError> {
544        self.close()?;
545        Ok(())
546    }
547}
548
549/// Arrow-specific configuration settings for writing parquet files.
550///
551/// See [`ArrowWriter`] for how to configure the writer.
552#[derive(Debug, Clone, Default)]
553pub struct ArrowWriterOptions {
554    properties: WriterProperties,
555    skip_arrow_metadata: bool,
556    schema_root: Option<String>,
557    schema_descr: Option<SchemaDescriptor>,
558    page_store_factory: Option<Arc<dyn PageStoreFactory>>,
559}
560
561impl ArrowWriterOptions {
562    /// Creates a new [`ArrowWriterOptions`] with the default settings.
563    pub fn new() -> Self {
564        Self::default()
565    }
566
567    /// Sets the [`WriterProperties`] for writing parquet files.
568    pub fn with_properties(self, properties: WriterProperties) -> Self {
569        Self { properties, ..self }
570    }
571
572    /// Sets the [`PageStoreFactory`] used to buffer completed pages while a row
573    /// group is being written.
574    ///
575    /// The default implementation ([`InMemoryPageStore`]) buffers all completed
576    /// pages on the heap until the row group is flushed, so peak write memory
577    /// grows with the row group size. Using this API, pages can be spilled to a
578    /// file or object storage instead, reducing peak write memory substantially
579    /// at the expense of an extra write to and read from secondary storage.
580    ///
581    /// # Example: spilling pages to a temp file
582    ///
583    /// A simple spilling backend uses one temp file per column chunk; `put`
584    /// appends the page and `take` reads it back.
585    ///
586    /// ```
587    /// # use std::fs::File;
588    /// # use std::io::{Read, Seek, SeekFrom, Write};
589    /// # use std::sync::Arc;
590    /// # use bytes::Bytes;
591    /// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
592    /// # use parquet::arrow::arrow_writer::{
593    /// #     ArrowWriter, ArrowWriterOptions, PageKey, PageStore, PageStoreArgs, PageStoreFactory,
594    /// # };
595    /// # use parquet::arrow::arrow_reader::ParquetRecordBatchReader;
596    /// # use parquet::errors::Result;
597    /// struct TempFilePageStore {
598    ///     file: File,
599    ///     /// Total size of the file
600    ///     end: u64,
601    ///     /// Location of pages: (offset, len)
602    ///     locs: Vec<(u64, usize)>,
603    /// }
604    ///
605    /// impl PageStore for TempFilePageStore {
606    ///     fn put(&mut self, value: Bytes) -> Result<PageKey> {
607    ///         // Append to the end of the file
608    ///         self.file.seek(SeekFrom::Start(self.end))?;
609    ///         self.file.write_all(&value)?;
610    ///         let key = PageKey::new(self.locs.len() as u64);
611    ///         self.locs.push((self.end, value.len()));
612    ///         self.end += value.len() as u64;
613    ///         Ok(key)
614    ///     }
615    ///
616    ///     fn take(&mut self, key: PageKey) -> Result<Bytes> {
617    ///         let (offset, len) = self.locs[key.get() as usize];
618    ///         let mut buf = vec![0u8; len];
619    ///         self.file.seek(SeekFrom::Start(offset))?;
620    ///         self.file.read_exact(&mut buf)?;
621    ///         Ok(Bytes::from(buf))
622    ///     }
623    /// }
624    ///
625    /// /// Factory for creating [`TempFilePageStore`]
626    /// #[derive(Debug)]
627    /// struct TempFilePageStoreFactory;
628    ///
629    /// impl PageStoreFactory for TempFilePageStoreFactory {
630    ///     fn create(&self, args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
631    ///         // `args` exposes the column index and descriptor (physical/logical
632    ///         // type, path), so a real backend might choose to spill only large columns.
633    ///         let _ = (args.column_index(), args.column_descriptor());
634    ///         Ok(Box::new(TempFilePageStore {
635    ///             file: tempfile::tempfile()?, // temp file is cleaned on drop
636    ///             end: 0,
637    ///             locs: Vec::new(),
638    ///         }))
639    ///     }
640    /// }
641    /// // write 1000 integers
642    /// let col = Arc::new(Int64Array::from_iter_values(0..1000)) as ArrayRef;
643    /// let to_write = RecordBatch::try_from_iter([("col", col)]).unwrap();
644    ///
645    /// let options =
646    ///     ArrowWriterOptions::new().with_page_store_factory(Arc::new(TempFilePageStoreFactory));
647    /// let mut buffer = Vec::new();
648    /// let mut writer =
649    ///     ArrowWriter::try_new_with_options(&mut buffer, to_write.schema(), options).unwrap();
650    /// writer.write(&to_write).unwrap();
651    /// writer.close().unwrap();
652    ///
653    /// // buffer now holds valid Parquet data, which can be read as normal:
654    /// let mut reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), 1024).unwrap();
655    /// assert_eq!(to_write, reader.next().unwrap().unwrap());
656    /// ```
657    pub fn with_page_store_factory(self, page_store_factory: Arc<dyn PageStoreFactory>) -> Self {
658        Self {
659            page_store_factory: Some(page_store_factory),
660            ..self
661        }
662    }
663
664    /// Skip encoding the embedded arrow metadata (defaults to `false`)
665    ///
666    /// Parquet files generated by the [`ArrowWriter`] contain embedded arrow schema
667    /// by default.
668    ///
669    /// Set `skip_arrow_metadata` to true, to skip encoding the embedded metadata.
670    pub fn with_skip_arrow_metadata(self, skip_arrow_metadata: bool) -> Self {
671        Self {
672            skip_arrow_metadata,
673            ..self
674        }
675    }
676
677    /// Set the name of the root parquet schema element (defaults to `"arrow_schema"`)
678    pub fn with_schema_root(self, schema_root: String) -> Self {
679        Self {
680            schema_root: Some(schema_root),
681            ..self
682        }
683    }
684
685    /// Explicitly specify the Parquet schema to be used
686    ///
687    /// If omitted (the default), the [`ArrowSchemaConverter`] is used to compute the
688    /// Parquet [`SchemaDescriptor`]. This may be used When the [`SchemaDescriptor`] is
689    /// already known or must be calculated using custom logic.
690    pub fn with_parquet_schema(self, schema_descr: SchemaDescriptor) -> Self {
691        Self {
692            schema_descr: Some(schema_descr),
693            ..self
694        }
695    }
696}
697
698/// A single column chunk produced by [`ArrowColumnWriter`].
699///
700/// Holds the serialized page blobs (each page's header ‖ compressed data, in
701/// write order) in a [`PageStore`], plus the handles needed to read them back,
702/// in order, when the chunk is spliced into the output file.
703struct ArrowColumnChunkData {
704    length: usize,
705    store: Box<dyn PageStore>,
706    keys: Vec<PageKey>,
707    /// Handles to the dictionary page's blobs (header then data) in the store.
708    ///
709    /// A dictionary page is produced at most once and bounded by
710    /// `dict_page_size_limit`, but it must be written *first* in the chunk even
711    /// though the data pages reach the writer before it (see
712    /// [`PageWriter::defers_dictionary_ordering`]). Its header and data are `put`
713    /// into the store like any other page — which keeps the store uniform, and
714    /// lets an oversized dictionary page spill — and their handles are held apart
715    /// so they can be emitted ahead of the data pages at splice.
716    /// Empty for non-dictionary columns.
717    dictionary_keys: Vec<PageKey>,
718    /// Serialized length of the dictionary page (0 if there is none), recorded
719    /// so the data pages can be shifted past it when offsets are rewritten to a
720    /// dictionary-first layout at splice.
721    dictionary_len: usize,
722}
723
724impl ArrowColumnChunkData {
725    fn new(store: Box<dyn PageStore>) -> Self {
726        Self {
727            length: 0,
728            store,
729            keys: Vec::new(),
730            dictionary_keys: Vec::new(),
731            dictionary_len: 0,
732        }
733    }
734
735    /// Append a data-page blob to the store, recording its handle in write
736    /// order.
737    fn push(&mut self, value: Bytes) -> Result<()> {
738        let key = self.store.put(value)?;
739        self.keys.push(key);
740        Ok(())
741    }
742
743    /// Store a dictionary-page blob (header or data) in the page store,
744    /// recording its handle (emitted first at splice) and accumulating its
745    /// serialized length.
746    fn push_dictionary(&mut self, value: Bytes) -> Result<()> {
747        self.dictionary_len += value.len();
748        let key = self.store.put(value)?;
749        self.dictionary_keys.push(key);
750        Ok(())
751    }
752
753    /// Bytes this chunk currently holds on the heap: whatever the store keeps
754    /// resident (zero for a spilling backend).
755    fn memory_size(&self) -> usize {
756        self.store.memory_size()
757    }
758}
759
760/// A streaming iterator over one column chunk's buffered page blobs, in final
761/// file order: the dictionary page (if any) first, then the data pages.
762///
763/// Each blob is taken back out of the [`PageStore`] *as it is
764/// consumed* and released immediately afterwards, so splicing a chunk into the
765/// output file never materializes more than a single page in memory at a time.
766/// This is what keeps the splice phase within the memory bound for a spilling
767/// backend (an in-memory store already holds the bytes, so it is unaffected).
768struct StreamingColumnChunkPages {
769    store: Box<dyn PageStore>,
770    /// Page handles in final file order: the dictionary page first (if any),
771    /// then the data pages.
772    keys: IntoIter<PageKey>,
773}
774
775impl StreamingColumnChunkPages {
776    fn new(data: ArrowColumnChunkData) -> Self {
777        // The dictionary page must be emitted first, ahead of the data pages,
778        // even though it was the last page produced.
779        let keys = if data.dictionary_keys.is_empty() {
780            data.keys
781        } else {
782            let mut keys = Vec::with_capacity(data.dictionary_keys.len() + data.keys.len());
783            keys.extend(data.dictionary_keys);
784            keys.extend(data.keys);
785            keys
786        };
787        Self {
788            store: data.store,
789            keys: keys.into_iter(),
790        }
791    }
792}
793
794impl Iterator for StreamingColumnChunkPages {
795    type Item = Result<Bytes>;
796
797    fn next(&mut self) -> Option<Self::Item> {
798        let key = self.keys.next()?;
799        Some(self.store.take(key))
800    }
801}
802
803/// A shared [`ArrowColumnChunkData`]
804///
805/// This allows it to be owned by [`ArrowPageWriter`] whilst allowing access via
806/// [`ArrowRowGroupWriter`] on flush, without requiring self-referential borrows
807type SharedColumnChunk = Arc<Mutex<ArrowColumnChunkData>>;
808
809struct ArrowPageWriter {
810    buffer: SharedColumnChunk,
811    #[cfg(feature = "encryption")]
812    page_encryptor: Option<PageEncryptor>,
813}
814
815impl ArrowPageWriter {
816    /// Create a page writer that buffers completed pages in `store`.
817    fn new(store: Box<dyn PageStore>) -> Self {
818        Self {
819            buffer: Arc::new(Mutex::new(ArrowColumnChunkData::new(store))),
820            #[cfg(feature = "encryption")]
821            page_encryptor: None,
822        }
823    }
824
825    #[cfg(feature = "encryption")]
826    pub fn with_encryptor(mut self, page_encryptor: Option<PageEncryptor>) -> Self {
827        self.page_encryptor = page_encryptor;
828        self
829    }
830
831    #[cfg(feature = "encryption")]
832    fn page_encryptor_mut(&mut self) -> Option<&mut PageEncryptor> {
833        self.page_encryptor.as_mut()
834    }
835
836    // Mirrors the signature of the encryption-enabled version above, so that the
837    // callers do not need a `cfg` of their own.
838    #[cfg(not(feature = "encryption"))]
839    #[expect(
840        clippy::needless_pass_by_ref_mut,
841        reason = "mirrors the encryption-enabled signature"
842    )]
843    fn page_encryptor_mut(&mut self) -> Option<&mut PageEncryptor> {
844        None
845    }
846}
847
848impl PageWriter for ArrowPageWriter {
849    fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> {
850        let page = match self.page_encryptor_mut() {
851            Some(page_encryptor) => page_encryptor.encrypt_compressed_page(page)?,
852            None => page,
853        };
854
855        let page_header = page.to_thrift_header()?;
856        let header = {
857            let mut header = Vec::with_capacity(1024);
858
859            match self.page_encryptor_mut() {
860                Some(page_encryptor) => {
861                    page_encryptor.encrypt_page_header(&page_header, &mut header)?;
862                    if page.compressed_page().is_data_page() {
863                        page_encryptor.increment_page();
864                    }
865                }
866                None => {
867                    let mut protocol = ThriftCompactOutputProtocol::new(&mut header);
868                    page_header.write_thrift(&mut protocol)?;
869                }
870            }
871
872            Bytes::from(header)
873        };
874
875        let mut buf = self.buffer.try_lock().unwrap();
876
877        let data = page.compressed_page().buffer().clone();
878        let compressed_size = data.len() + header.len();
879
880        let mut spec = PageWriteSpec::new();
881        spec.page_type = page.page_type();
882        spec.num_values = page.num_values();
883        spec.uncompressed_size = page.uncompressed_size() + header.len();
884        spec.offset = buf.length as u64;
885        spec.compressed_size = compressed_size;
886        spec.bytes_written = compressed_size as u64;
887
888        buf.length += compressed_size;
889        if spec.page_type == PageType::DICTIONARY_PAGE {
890            // Recorded apart from the data pages so it is emitted first at
891            // splice — see `ArrowColumnChunkData::dictionary_keys`.
892            buf.push_dictionary(header)?;
893            buf.push_dictionary(data)?;
894        } else {
895            buf.push(header)?;
896            buf.push(data)?;
897        }
898
899        Ok(spec)
900    }
901
902    fn defers_dictionary_ordering(&self) -> bool {
903        // The Arrow chunk is buffered in full and spliced at row-group flush, so
904        // data pages may be accepted before the dictionary page and reordered
905        // then. This lets `GenericColumnWriter` stream dictionary-column data
906        // pages straight through instead of buffering them in memory.
907        true
908    }
909
910    fn buffered_memory_size(&self) -> usize {
911        // Only what is actually resident: a spilling store reports ~0 here even
912        // though the chunk's bytes have all passed through it.
913        self.buffer.try_lock().unwrap().memory_size()
914    }
915
916    fn close(&mut self) -> Result<()> {
917        Ok(())
918    }
919}
920
921/// A leaf column that can be encoded by [`ArrowColumnWriter`]
922#[derive(Debug)]
923pub struct ArrowLeafColumn(ArrayLevels);
924
925/// Computes the [`ArrowLeafColumn`] for a potentially nested [`ArrayRef`]
926///
927/// This function can be used to encode individual columns in parallel.
928/// See example on [`ArrowColumnWriter`]
929pub fn compute_leaves(field: &Field, array: &ArrayRef) -> Result<Vec<ArrowLeafColumn>> {
930    let levels = calculate_array_levels(array, field)?;
931    Ok(levels.into_iter().map(ArrowLeafColumn).collect())
932}
933
934/// The data for a single column chunk, see [`ArrowColumnWriter`]
935pub struct ArrowColumnChunk {
936    data: ArrowColumnChunkData,
937    close: ColumnCloseResult,
938}
939
940impl std::fmt::Debug for ArrowColumnChunk {
941    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
942        f.debug_struct("ArrowColumnChunk")
943            .field("length", &self.data.length)
944            .finish_non_exhaustive()
945    }
946}
947
948impl ArrowColumnChunk {
949    /// Returns the [`ColumnCloseResult`] produced when the chunk was closed.
950    ///
951    /// Exposes encoding information, collected statistics, and the optional
952    /// [`ColumnIndexMetaData`](crate::file::page_index::column_index::ColumnIndexMetaData)
953    /// / [`OffsetIndexMetaData`](crate::file::page_index::offset_index::OffsetIndexMetaData)
954    /// gathered for the column chunk.
955    pub fn close(&self) -> &ColumnCloseResult {
956        &self.close
957    }
958
959    /// Returns a mutable reference to the [`ColumnCloseResult`].
960    ///
961    /// This allows callers to mutate the close result before the chunk is
962    /// appended to a row group — for example, clearing `column_index` or
963    /// `bloom_filter` based on a dynamic rule that inspects the encodings and
964    /// collected page statistics.
965    pub fn close_mut(&mut self) -> &mut ColumnCloseResult {
966        &mut self.close
967    }
968
969    /// Splices this column's buffered pages into the row group, streaming them
970    /// back out of the [`PageStore`] one page at a time.
971    pub fn append_to_row_group<W: Write + Send>(
972        self,
973        writer: &mut SerializedRowGroupWriter<'_, W>,
974    ) -> Result<()> {
975        let ArrowColumnChunk { data, close } = self;
976
977        // The dictionary page is produced *after* the data pages on this path (so
978        // they can stream straight through) but must be written *first*, so move
979        // it ahead of the data pages in the recorded offsets before the splice.
980        let close = close.update_dictionary_location(data.dictionary_len)?;
981
982        let pages = StreamingColumnChunkPages::new(data);
983        writer.append_column_from_pages(pages, close)
984    }
985}
986
987/// Encodes [`ArrowLeafColumn`] to [`ArrowColumnChunk`]
988///
989/// `ArrowColumnWriter` instances can be created using an [`ArrowRowGroupWriterFactory`];
990///
991/// Note: This is a low-level interface for applications that require
992/// fine-grained control of encoding (e.g. encoding using multiple threads),
993/// see [`ArrowWriter`] for a higher-level interface
994///
995/// # Example: Encoding two Arrow Array's in Parallel
996/// ```
997/// // The arrow schema
998/// # use std::sync::Arc;
999/// # use arrow_array::*;
1000/// # use arrow_schema::*;
1001/// # use parquet::arrow::ArrowSchemaConverter;
1002/// # use parquet::arrow::arrow_writer::{compute_leaves, ArrowColumnChunk, ArrowLeafColumn, ArrowRowGroupWriterFactory};
1003/// # use parquet::file::properties::WriterProperties;
1004/// # use parquet::file::writer::{SerializedFileWriter, SerializedRowGroupWriter};
1005/// #
1006/// let schema = Arc::new(Schema::new(vec![
1007///     Field::new("i32", DataType::Int32, false),
1008///     Field::new("f32", DataType::Float32, false),
1009/// ]));
1010///
1011/// // Compute the parquet schema
1012/// let props = Arc::new(WriterProperties::default());
1013/// let parquet_schema = ArrowSchemaConverter::new()
1014///   .with_coerce_types(props.coerce_types())
1015///   .convert(&schema)
1016///   .unwrap();
1017///
1018/// // Create parquet writer
1019/// let root_schema = parquet_schema.root_schema_ptr();
1020/// // write to memory in the example, but this could be a File
1021/// let mut out = Vec::with_capacity(1024);
1022/// let mut writer = SerializedFileWriter::new(&mut out, root_schema, props.clone())
1023///   .unwrap();
1024///
1025/// // Create a factory for building Arrow column writers
1026/// let row_group_factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
1027/// // Create column writers for the 0th row group
1028/// let col_writers = row_group_factory.create_column_writers(0).unwrap();
1029///
1030/// // Spawn a worker thread for each column
1031/// //
1032/// // Note: This is for demonstration purposes, a thread-pool e.g. rayon or tokio, would be better.
1033/// // The `map` produces an iterator of type `tuple of (thread handle, send channel)`.
1034/// let mut workers: Vec<_> = col_writers
1035///     .into_iter()
1036///     .map(|mut col_writer| {
1037///         let (send, recv) = std::sync::mpsc::channel::<ArrowLeafColumn>();
1038///         let handle = std::thread::spawn(move || {
1039///             // receive Arrays to encode via the channel
1040///             for col in recv {
1041///                 col_writer.write(&col)?;
1042///             }
1043///             // once the input is complete, close the writer
1044///             // to return the newly created ArrowColumnChunk
1045///             col_writer.close()
1046///         });
1047///         (handle, send)
1048///     })
1049///     .collect();
1050///
1051/// // Start row group
1052/// let mut row_group_writer: SerializedRowGroupWriter<'_, _> = writer
1053///   .next_row_group()
1054///   .unwrap();
1055///
1056/// // Create some example input columns to encode
1057/// let to_write = vec![
1058///     Arc::new(Int32Array::from_iter_values([1, 2, 3])) as _,
1059///     Arc::new(Float32Array::from_iter_values([1., 45., -1.])) as _,
1060/// ];
1061///
1062/// // Send the input columns to the workers
1063/// let mut worker_iter = workers.iter_mut();
1064/// for (arr, field) in to_write.iter().zip(&schema.fields) {
1065///     for leaves in compute_leaves(field, arr).unwrap() {
1066///         worker_iter.next().unwrap().1.send(leaves).unwrap();
1067///     }
1068/// }
1069///
1070/// // Wait for the workers to complete encoding, and append
1071/// // the resulting column chunks to the row group (and the file)
1072/// for (handle, send) in workers {
1073///     drop(send); // Drop send side to signal termination
1074///     // wait for the worker to send the completed chunk
1075///     let chunk: ArrowColumnChunk = handle.join().unwrap().unwrap();
1076///     chunk.append_to_row_group(&mut row_group_writer).unwrap();
1077/// }
1078/// // Close the row group which writes to the underlying file
1079/// row_group_writer.close().unwrap();
1080///
1081/// let metadata = writer.close().unwrap();
1082/// assert_eq!(metadata.file_metadata().num_rows(), 3);
1083/// ```
1084pub struct ArrowColumnWriter {
1085    writer: ArrowColumnWriterImpl,
1086    chunk: SharedColumnChunk,
1087    /// Non-null value hashes accumulated across all writes for this column's row group.
1088    /// `None` when tracking is disabled via [`WriterProperties::write_row_group_number_distinct_values`].
1089    distinct_values_seen: Option<DistinctValuesSet>,
1090}
1091
1092impl std::fmt::Debug for ArrowColumnWriter {
1093    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1094        f.debug_struct("ArrowColumnWriter").finish_non_exhaustive()
1095    }
1096}
1097
1098enum ArrowColumnWriterImpl {
1099    ByteArray(GenericColumnWriter<'static, ByteArrayEncoder>),
1100    Column(ColumnWriter<'static>),
1101}
1102
1103impl ArrowColumnWriter {
1104    /// Write an [`ArrowLeafColumn`]
1105    pub fn write(&mut self, col: &ArrowLeafColumn) -> Result<()> {
1106        self.write_internal(&col.0)
1107    }
1108
1109    /// Write with content-defined chunking, inserting page flushes at chunk boundaries.
1110    fn write_with_chunker(
1111        &mut self,
1112        col: &ArrowLeafColumn,
1113        chunker: &mut ContentDefinedChunker,
1114    ) -> Result<()> {
1115        let levels = &col.0;
1116        let chunks = chunker.get_arrow_chunks(
1117            levels.def_level_data().as_ref(),
1118            levels.rep_level_data().as_ref(),
1119            levels.array(),
1120        )?;
1121
1122        let num_chunks = chunks.len();
1123        for (i, chunk) in chunks.iter().enumerate() {
1124            let chunk_levels = levels.slice_for_chunk(chunk);
1125            self.write_internal(&chunk_levels)?;
1126
1127            // Add a page break after each chunk except the last
1128            if i + 1 < num_chunks {
1129                match &mut self.writer {
1130                    ArrowColumnWriterImpl::Column(c) => c.add_data_page()?,
1131                    ArrowColumnWriterImpl::ByteArray(c) => c.add_data_page()?,
1132                }
1133            }
1134        }
1135        Ok(())
1136    }
1137
1138    fn write_internal(&mut self, levels: &ArrayLevels) -> Result<()> {
1139        if let Some(seen) = &mut self.distinct_values_seen {
1140            let array = levels.array();
1141            let non_null = levels.non_null_indices();
1142            match array.as_any_dictionary_opt() {
1143                Some(dict) => {
1144                    // Hash referenced values, not key indices: keys can map to different
1145                    // values across batches, and unreferenced values must not count toward NDV.
1146                    let values = dict.values();
1147                    let keys = dict.normalized_keys();
1148                    let referenced_value_indices: Vec<usize> = non_null
1149                        .iter()
1150                        .map(|&pos| keys[pos])
1151                        .filter(|&val_idx| values.is_valid(val_idx))
1152                        .collect();
1153                    update_distinct_values_seen(values.as_ref(), &referenced_value_indices, seen);
1154                }
1155                // For plain arrays, hash the actual values directly.
1156                None => update_distinct_values_seen(array.as_ref(), non_null, seen),
1157            }
1158        }
1159
1160        match &mut self.writer {
1161            ArrowColumnWriterImpl::Column(c) => {
1162                let leaf = levels.array();
1163                match leaf.as_any_dictionary_opt() {
1164                    Some(dictionary) => {
1165                        let materialized =
1166                            arrow_select::take::take(dictionary.values(), dictionary.keys(), None)?;
1167                        write_leaf(c, &materialized, levels)?
1168                    }
1169                    None => write_leaf(c, leaf, levels)?,
1170                };
1171            }
1172            ArrowColumnWriterImpl::ByteArray(c) => {
1173                write_primitive(c, levels.array().as_ref(), levels)?;
1174            }
1175        }
1176        Ok(())
1177    }
1178
1179    /// Close this column returning the written [`ArrowColumnChunk`]
1180    ///
1181    /// # Errors
1182    ///
1183    /// Returns an error if the column could not be finalised, or if another thread
1184    /// panicked while holding the column chunk. The caller cannot cause either.
1185    pub fn close(self) -> Result<ArrowColumnChunk> {
1186        let distinct_count = self
1187            .distinct_values_seen
1188            .as_ref()
1189            .filter(|s| !s.is_empty())
1190            .map(|s| s.len() as u64);
1191        let close = match self.writer {
1192            ArrowColumnWriterImpl::ByteArray(mut c) => {
1193                if let Some(count) = distinct_count {
1194                    c.set_distinct_count_override(count);
1195                }
1196                c.close()?
1197            }
1198            ArrowColumnWriterImpl::Column(mut c) => {
1199                if let Some(count) = distinct_count {
1200                    c.set_distinct_count_override(count);
1201                }
1202                c.close()?
1203            }
1204        };
1205        // Closing the writer above dropped the only other handle on the chunk.
1206        let chunk = Arc::try_unwrap(self.chunk)
1207            .map_err(|_| general_err!("Internal Error: the column chunk is still shared"))?;
1208        let data = chunk
1209            .into_inner()
1210            .map_err(|_| general_err!("The column chunk lock is poisoned"))?;
1211        Ok(ArrowColumnChunk { data, close })
1212    }
1213
1214    /// Returns the estimated total memory usage by the writer.
1215    ///
1216    /// This  [`Self::get_estimated_total_bytes`] this is an estimate
1217    /// of the current memory usage and not it's anticipated encoded size.
1218    ///
1219    /// This includes:
1220    /// 1. Data buffered in encoded form
1221    /// 2. Data buffered in un-encoded form (e.g. `usize` dictionary keys)
1222    ///
1223    /// This value should be greater than or equal to [`Self::get_estimated_total_bytes`]
1224    pub fn memory_size(&self) -> usize {
1225        match &self.writer {
1226            ArrowColumnWriterImpl::ByteArray(c) => c.memory_size(),
1227            ArrowColumnWriterImpl::Column(c) => c.memory_size(),
1228        }
1229    }
1230
1231    /// Returns the estimated total encoded bytes for this column writer.
1232    ///
1233    /// This includes:
1234    /// 1. Data buffered in encoded form
1235    /// 2. An estimate of how large the data buffered in un-encoded form would be once encoded
1236    ///
1237    /// This value should be less than or equal to [`Self::memory_size`]
1238    pub fn get_estimated_total_bytes(&self) -> usize {
1239        match &self.writer {
1240            ArrowColumnWriterImpl::ByteArray(c) => c.get_estimated_total_bytes() as _,
1241            ArrowColumnWriterImpl::Column(c) => c.get_estimated_total_bytes() as _,
1242        }
1243    }
1244}
1245
1246/// Encodes [`RecordBatch`] to a parquet row group
1247///
1248/// Note: this structure is created by [`ArrowRowGroupWriterFactory`] internally used to
1249/// create [`ArrowRowGroupWriter`]s, but it is not exposed publicly.
1250///
1251/// See the example on [`ArrowColumnWriter`] for how to encode columns in parallel
1252#[derive(Debug)]
1253struct ArrowRowGroupWriter {
1254    writers: Vec<ArrowColumnWriter>,
1255    schema: SchemaRef,
1256    buffered_rows: usize,
1257}
1258
1259impl ArrowRowGroupWriter {
1260    fn new(writers: Vec<ArrowColumnWriter>, arrow: &SchemaRef) -> Self {
1261        Self {
1262            writers,
1263            schema: arrow.clone(),
1264            buffered_rows: 0,
1265        }
1266    }
1267
1268    fn write(&mut self, batch: &RecordBatch) -> Result<()> {
1269        self.buffered_rows += batch.num_rows();
1270        let mut writers = self.writers.iter_mut();
1271        for (field, column) in self.schema.fields().iter().zip(batch.columns()) {
1272            for leaf in compute_leaves(field.as_ref(), column)? {
1273                writers.next().unwrap().write(&leaf)?;
1274            }
1275        }
1276        Ok(())
1277    }
1278
1279    fn write_with_chunkers(
1280        &mut self,
1281        batch: &RecordBatch,
1282        chunkers: &mut [ContentDefinedChunker],
1283    ) -> Result<()> {
1284        self.buffered_rows += batch.num_rows();
1285        let mut writers = self.writers.iter_mut();
1286        let mut chunkers = chunkers.iter_mut();
1287        for (field, column) in self.schema.fields().iter().zip(batch.columns()) {
1288            for leaf in compute_leaves(field.as_ref(), column)? {
1289                writers
1290                    .next()
1291                    .unwrap()
1292                    .write_with_chunker(&leaf, chunkers.next().unwrap())?;
1293            }
1294        }
1295        Ok(())
1296    }
1297
1298    /// Returns the estimated total encoded bytes for this row group
1299    fn get_estimated_total_bytes(&self) -> usize {
1300        self.writers
1301            .iter()
1302            .map(|x| x.get_estimated_total_bytes())
1303            .sum()
1304    }
1305
1306    fn close(self) -> Result<Vec<ArrowColumnChunk>> {
1307        self.writers
1308            .into_iter()
1309            .map(|writer| writer.close())
1310            .collect()
1311    }
1312}
1313
1314/// Factory that creates new column writers for each row group in the Parquet file.
1315///
1316/// You can create this structure via an [`ArrowWriter::into_serialized_writer`].
1317/// See the example on [`ArrowColumnWriter`] for how to encode columns in parallel
1318#[derive(Debug)]
1319pub struct ArrowRowGroupWriterFactory {
1320    schema: SchemaDescPtr,
1321    arrow_schema: SchemaRef,
1322    props: WriterPropertiesPtr,
1323    page_store_factory: Arc<dyn PageStoreFactory>,
1324    #[cfg(feature = "encryption")]
1325    file_encryptor: Option<Arc<FileEncryptor>>,
1326}
1327
1328impl ArrowRowGroupWriterFactory {
1329    /// Create a new [`ArrowRowGroupWriterFactory`] for the provided file writer and Arrow schema
1330    pub fn new<W: Write + Send>(
1331        file_writer: &SerializedFileWriter<W>,
1332        arrow_schema: SchemaRef,
1333    ) -> Self {
1334        let schema = Arc::clone(file_writer.schema_descr_ptr());
1335        let props = Arc::clone(file_writer.properties());
1336        Self {
1337            schema,
1338            arrow_schema,
1339            props,
1340            page_store_factory: Arc::new(InMemoryPageStoreFactory),
1341            #[cfg(feature = "encryption")]
1342            file_encryptor: file_writer.file_encryptor(),
1343        }
1344    }
1345
1346    /// Set the [`PageStoreFactory`] used to allocate the buffer for each column
1347    /// chunk, e.g. to spill completed pages to a temp file or object storage
1348    /// instead of the heap. Defaults to [`InMemoryPageStoreFactory`].
1349    pub fn with_page_store_factory(
1350        mut self,
1351        page_store_factory: Arc<dyn PageStoreFactory>,
1352    ) -> Self {
1353        self.page_store_factory = page_store_factory;
1354        self
1355    }
1356
1357    fn create_row_group_writer(&self, row_group_index: usize) -> Result<ArrowRowGroupWriter> {
1358        let writers = self.create_column_writers(row_group_index)?;
1359        Ok(ArrowRowGroupWriter::new(writers, &self.arrow_schema))
1360    }
1361
1362    /// Create column writers for a new row group, with the given row group index
1363    pub fn create_column_writers(&self, row_group_index: usize) -> Result<Vec<ArrowColumnWriter>> {
1364        let mut writers = Vec::with_capacity(self.arrow_schema.fields.len());
1365        let mut leaves = self.schema.columns().iter();
1366        let column_factory = self.column_writer_factory(row_group_index);
1367        for field in &self.arrow_schema.fields {
1368            column_factory.get_arrow_column_writer(
1369                field.data_type(),
1370                &self.props,
1371                &mut leaves,
1372                &mut writers,
1373            )?;
1374        }
1375        Ok(writers)
1376    }
1377
1378    #[cfg(feature = "encryption")]
1379    fn column_writer_factory(&self, row_group_idx: usize) -> ArrowColumnWriterFactory {
1380        ArrowColumnWriterFactory::new()
1381            .with_page_store_factory(self.page_store_factory.clone())
1382            .with_file_encryptor(row_group_idx, self.file_encryptor.clone())
1383    }
1384
1385    #[cfg(not(feature = "encryption"))]
1386    fn column_writer_factory(&self, _row_group_idx: usize) -> ArrowColumnWriterFactory {
1387        ArrowColumnWriterFactory::new().with_page_store_factory(self.page_store_factory.clone())
1388    }
1389}
1390
1391/// Creates [`ArrowColumnWriter`] instances
1392struct ArrowColumnWriterFactory {
1393    /// Allocates the per-column-chunk [`PageStore`] backing each page writer.
1394    page_store_factory: Arc<dyn PageStoreFactory>,
1395    #[cfg(feature = "encryption")]
1396    row_group_index: usize,
1397    #[cfg(feature = "encryption")]
1398    file_encryptor: Option<Arc<FileEncryptor>>,
1399}
1400
1401impl ArrowColumnWriterFactory {
1402    pub fn new() -> Self {
1403        Self {
1404            page_store_factory: Arc::new(InMemoryPageStoreFactory),
1405            #[cfg(feature = "encryption")]
1406            row_group_index: 0,
1407            #[cfg(feature = "encryption")]
1408            file_encryptor: None,
1409        }
1410    }
1411
1412    /// Use `page_store_factory` to allocate the buffer for each column chunk.
1413    pub fn with_page_store_factory(
1414        mut self,
1415        page_store_factory: Arc<dyn PageStoreFactory>,
1416    ) -> Self {
1417        self.page_store_factory = page_store_factory;
1418        self
1419    }
1420
1421    #[cfg(feature = "encryption")]
1422    pub fn with_file_encryptor(
1423        mut self,
1424        row_group_index: usize,
1425        file_encryptor: Option<Arc<FileEncryptor>>,
1426    ) -> Self {
1427        self.row_group_index = row_group_index;
1428        self.file_encryptor = file_encryptor;
1429        self
1430    }
1431
1432    #[cfg(feature = "encryption")]
1433    fn create_page_writer(
1434        &self,
1435        column_descriptor: &ColumnDescPtr,
1436        column_index: usize,
1437    ) -> Result<Box<ArrowPageWriter>> {
1438        let column_path = column_descriptor.path().string();
1439        let page_encryptor = PageEncryptor::create_if_column_encrypted(
1440            self.file_encryptor.as_ref(),
1441            self.row_group_index,
1442            column_index,
1443            &column_path,
1444        )?;
1445        let args = PageStoreArgs::new(column_index, column_descriptor);
1446        let store = self.page_store_factory.create(&args)?;
1447        Ok(Box::new(
1448            ArrowPageWriter::new(store).with_encryptor(page_encryptor),
1449        ))
1450    }
1451
1452    #[cfg(not(feature = "encryption"))]
1453    fn create_page_writer(
1454        &self,
1455        column_descriptor: &ColumnDescPtr,
1456        column_index: usize,
1457    ) -> Result<Box<ArrowPageWriter>> {
1458        let args = PageStoreArgs::new(column_index, column_descriptor);
1459        let store = self.page_store_factory.create(&args)?;
1460        Ok(Box::new(ArrowPageWriter::new(store)))
1461    }
1462
1463    /// Gets an [`ArrowColumnWriter`] for the given `data_type`, appending the
1464    /// output ColumnDesc to `leaves` and the column writers to `out`
1465    fn get_arrow_column_writer(
1466        &self,
1467        data_type: &ArrowDataType,
1468        props: &WriterPropertiesPtr,
1469        leaves: &mut Iter<'_, ColumnDescPtr>,
1470        out: &mut Vec<ArrowColumnWriter>,
1471    ) -> Result<()> {
1472        let write_distinct_values = props.write_row_group_number_distinct_values();
1473
1474        // Instantiate writers for normal columns
1475        let col = |desc: &ColumnDescPtr| -> Result<ArrowColumnWriter> {
1476            let page_writer = self.create_page_writer(desc, out.len())?;
1477            let chunk = page_writer.buffer.clone();
1478            let writer = get_column_writer(desc.clone(), props.clone(), page_writer);
1479            Ok(ArrowColumnWriter {
1480                chunk,
1481                writer: ArrowColumnWriterImpl::Column(writer),
1482                distinct_values_seen: write_distinct_values.then(HashSet::new),
1483            })
1484        };
1485
1486        // Instantiate writers for byte arrays (e.g. Utf8,  Binary, etc)
1487        let bytes = |desc: &ColumnDescPtr| -> Result<ArrowColumnWriter> {
1488            let page_writer = self.create_page_writer(desc, out.len())?;
1489            let chunk = page_writer.buffer.clone();
1490            let writer = GenericColumnWriter::new(desc.clone(), props.clone(), page_writer);
1491            Ok(ArrowColumnWriter {
1492                chunk,
1493                writer: ArrowColumnWriterImpl::ByteArray(writer),
1494                distinct_values_seen: write_distinct_values.then(HashSet::new),
1495            })
1496        };
1497
1498        match data_type {
1499            _ if data_type.is_primitive() => out.push(col(leaves.next().unwrap())?),
1500            ArrowDataType::FixedSizeBinary(_) | ArrowDataType::Boolean | ArrowDataType::Null => {
1501                out.push(col(leaves.next().unwrap())?)
1502            }
1503            ArrowDataType::LargeBinary
1504            | ArrowDataType::Binary
1505            | ArrowDataType::Utf8
1506            | ArrowDataType::LargeUtf8
1507            | ArrowDataType::BinaryView
1508            | ArrowDataType::Utf8View => out.push(bytes(leaves.next().unwrap())?),
1509            ArrowDataType::List(f)
1510            | ArrowDataType::LargeList(f)
1511            | ArrowDataType::FixedSizeList(f, _)
1512            | ArrowDataType::ListView(f)
1513            | ArrowDataType::LargeListView(f) => {
1514                self.get_arrow_column_writer(f.data_type(), props, leaves, out)?
1515            }
1516            ArrowDataType::Struct(fields) => {
1517                for field in fields {
1518                    self.get_arrow_column_writer(field.data_type(), props, leaves, out)?
1519                }
1520            }
1521            ArrowDataType::Map(f, _) => match f.data_type() {
1522                ArrowDataType::Struct(f) => {
1523                    self.get_arrow_column_writer(f[0].data_type(), props, leaves, out)?;
1524                    self.get_arrow_column_writer(f[1].data_type(), props, leaves, out)?
1525                }
1526                _ => unreachable!("invalid map type"),
1527            },
1528            ArrowDataType::Dictionary(_, value_type) => match value_type.as_ref() {
1529                ArrowDataType::Utf8
1530                | ArrowDataType::LargeUtf8
1531                | ArrowDataType::Binary
1532                | ArrowDataType::LargeBinary => out.push(bytes(leaves.next().unwrap())?),
1533                ArrowDataType::Utf8View | ArrowDataType::BinaryView => {
1534                    out.push(bytes(leaves.next().unwrap())?)
1535                }
1536                _ => out.push(col(leaves.next().unwrap())?),
1537            },
1538            ArrowDataType::RunEndEncoded(_, value_field) => {
1539                self.get_arrow_column_writer(value_field.data_type(), props, leaves, out)?
1540            }
1541            _ => {
1542                return Err(ParquetError::NYI(format!(
1543                    "Attempting to write an Arrow type {data_type} to parquet that is not yet implemented"
1544                )));
1545            }
1546        }
1547        Ok(())
1548    }
1549}
1550
1551fn write_leaf(
1552    writer: &mut ColumnWriter<'_>,
1553    column: &dyn arrow_array::Array,
1554    levels: &ArrayLevels,
1555) -> Result<usize> {
1556    let indices = levels.non_null_indices();
1557
1558    match writer {
1559        // Note: this should match the contents of arrow_to_parquet_type
1560        ColumnWriter::Int32ColumnWriter(typed) => {
1561            match column.data_type() {
1562                ArrowDataType::Null => {
1563                    let array = Int32Array::new_null(column.len());
1564                    write_primitive(typed, array.values(), levels)
1565                }
1566                ArrowDataType::Int8 => {
1567                    let array: Int32Array = column.as_primitive::<Int8Type>().unary(|x| x as i32);
1568                    write_primitive(typed, array.values(), levels)
1569                }
1570                ArrowDataType::Int16 => {
1571                    let array: Int32Array = column.as_primitive::<Int16Type>().unary(|x| x as i32);
1572                    write_primitive(typed, array.values(), levels)
1573                }
1574                ArrowDataType::Int32 => {
1575                    write_primitive(typed, column.as_primitive::<Int32Type>().values(), levels)
1576                }
1577                ArrowDataType::UInt8 => {
1578                    let array: Int32Array = column.as_primitive::<UInt8Type>().unary(|x| x as i32);
1579                    write_primitive(typed, array.values(), levels)
1580                }
1581                ArrowDataType::UInt16 => {
1582                    let array: Int32Array = column.as_primitive::<UInt16Type>().unary(|x| x as i32);
1583                    write_primitive(typed, array.values(), levels)
1584                }
1585                ArrowDataType::UInt32 => {
1586                    // follow C++ implementation and use overflow/reinterpret cast from  u32 to i32 which will map
1587                    // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0`
1588                    let array = column.as_primitive::<UInt32Type>();
1589                    write_primitive(typed, array.values().inner().typed_data(), levels)
1590                }
1591                ArrowDataType::Date32 => {
1592                    let array = column.as_primitive::<Date32Type>();
1593                    write_primitive(typed, array.values(), levels)
1594                }
1595                ArrowDataType::Time32(TimeUnit::Second) => {
1596                    let array = column.as_primitive::<Time32SecondType>();
1597                    write_primitive(typed, array.values(), levels)
1598                }
1599                ArrowDataType::Time32(TimeUnit::Millisecond) => {
1600                    let array = column.as_primitive::<Time32MillisecondType>();
1601                    write_primitive(typed, array.values(), levels)
1602                }
1603                ArrowDataType::Date64 => {
1604                    // If the column is a Date64, we truncate it
1605                    let array: Int32Array = column
1606                        .as_primitive::<Date64Type>()
1607                        .unary(|x| (x / 86_400_000) as _);
1608
1609                    write_primitive(typed, array.values(), levels)
1610                }
1611                ArrowDataType::Decimal32(_, _) => {
1612                    let array = column
1613                        .as_primitive::<Decimal32Type>()
1614                        .unary::<_, Int32Type>(|v| v);
1615                    write_primitive(typed, array.values(), levels)
1616                }
1617                ArrowDataType::Decimal64(_, _) => {
1618                    // use the int32 to represent the decimal with low precision
1619                    let array = column
1620                        .as_primitive::<Decimal64Type>()
1621                        .unary::<_, Int32Type>(|v| v as i32);
1622                    write_primitive(typed, array.values(), levels)
1623                }
1624                ArrowDataType::Decimal128(_, _) => {
1625                    // use the int32 to represent the decimal with low precision
1626                    let array = column
1627                        .as_primitive::<Decimal128Type>()
1628                        .unary::<_, Int32Type>(|v| v as i32);
1629                    write_primitive(typed, array.values(), levels)
1630                }
1631                ArrowDataType::Decimal256(_, _) => {
1632                    // use the int32 to represent the decimal with low precision
1633                    let array = column
1634                        .as_primitive::<Decimal256Type>()
1635                        .unary::<_, Int32Type>(|v| v.as_i128() as i32);
1636                    write_primitive(typed, array.values(), levels)
1637                }
1638                d => Err(ParquetError::General(format!("Cannot coerce {d} to I32"))),
1639            }
1640        }
1641        ColumnWriter::BoolColumnWriter(typed) => {
1642            let array = column.as_boolean();
1643            let values = get_bool_array_slice(array, indices.iter().copied());
1644            typed.write_batch_internal(
1645                values.as_slice(),
1646                None,
1647                levels.def_level_data().as_ref(),
1648                levels.rep_level_data().as_ref(),
1649                None,
1650                None,
1651                None,
1652            )
1653        }
1654        ColumnWriter::Int64ColumnWriter(typed) => {
1655            match column.data_type() {
1656                ArrowDataType::Date64 => {
1657                    let array = column
1658                        .as_primitive::<Date64Type>()
1659                        .reinterpret_cast::<Int64Type>();
1660
1661                    write_primitive(typed, array.values(), levels)
1662                }
1663                ArrowDataType::Int64 => {
1664                    let array = column.as_primitive::<Int64Type>();
1665                    write_primitive(typed, array.values(), levels)
1666                }
1667                ArrowDataType::UInt64 => {
1668                    let values = column.as_primitive::<UInt64Type>().values();
1669                    // follow C++ implementation and use overflow/reinterpret cast from  u64 to i64 which will map
1670                    // `(i64::MAX as u64)..u64::MAX` to `i64::MIN..0`
1671                    let array = values.inner().typed_data::<i64>();
1672                    write_primitive(typed, array, levels)
1673                }
1674                ArrowDataType::Time64(TimeUnit::Microsecond) => {
1675                    let array = column.as_primitive::<Time64MicrosecondType>();
1676                    write_primitive(typed, array.values(), levels)
1677                }
1678                ArrowDataType::Time64(TimeUnit::Nanosecond) => {
1679                    let array = column.as_primitive::<Time64NanosecondType>();
1680                    write_primitive(typed, array.values(), levels)
1681                }
1682                ArrowDataType::Timestamp(unit, _) => match unit {
1683                    TimeUnit::Second => {
1684                        let array = column.as_primitive::<TimestampSecondType>();
1685                        write_primitive(typed, array.values(), levels)
1686                    }
1687                    TimeUnit::Millisecond => {
1688                        let array = column.as_primitive::<TimestampMillisecondType>();
1689                        write_primitive(typed, array.values(), levels)
1690                    }
1691                    TimeUnit::Microsecond => {
1692                        let array = column.as_primitive::<TimestampMicrosecondType>();
1693                        write_primitive(typed, array.values(), levels)
1694                    }
1695                    TimeUnit::Nanosecond => {
1696                        let array = column.as_primitive::<TimestampNanosecondType>();
1697                        write_primitive(typed, array.values(), levels)
1698                    }
1699                },
1700                ArrowDataType::Duration(unit) => match unit {
1701                    TimeUnit::Second => {
1702                        let array = column.as_primitive::<DurationSecondType>();
1703                        write_primitive(typed, array.values(), levels)
1704                    }
1705                    TimeUnit::Millisecond => {
1706                        let array = column.as_primitive::<DurationMillisecondType>();
1707                        write_primitive(typed, array.values(), levels)
1708                    }
1709                    TimeUnit::Microsecond => {
1710                        let array = column.as_primitive::<DurationMicrosecondType>();
1711                        write_primitive(typed, array.values(), levels)
1712                    }
1713                    TimeUnit::Nanosecond => {
1714                        let array = column.as_primitive::<DurationNanosecondType>();
1715                        write_primitive(typed, array.values(), levels)
1716                    }
1717                },
1718                ArrowDataType::Decimal64(_, _) => {
1719                    let array = column
1720                        .as_primitive::<Decimal64Type>()
1721                        .reinterpret_cast::<Int64Type>();
1722                    write_primitive(typed, array.values(), levels)
1723                }
1724                ArrowDataType::Decimal128(_, _) => {
1725                    // use the int64 to represent the decimal with low precision
1726                    let array = column
1727                        .as_primitive::<Decimal128Type>()
1728                        .unary::<_, Int64Type>(|v| v as i64);
1729                    write_primitive(typed, array.values(), levels)
1730                }
1731                ArrowDataType::Decimal256(_, _) => {
1732                    // use the int64 to represent the decimal with low precision
1733                    let array = column
1734                        .as_primitive::<Decimal256Type>()
1735                        .unary::<_, Int64Type>(|v| v.as_i128() as i64);
1736                    write_primitive(typed, array.values(), levels)
1737                }
1738                d => Err(ParquetError::General(format!("Cannot coerce {d} to I64"))),
1739            }
1740        }
1741        ColumnWriter::Int96ColumnWriter(_typed) => {
1742            unreachable!("Currently unreachable because data type not supported")
1743        }
1744        ColumnWriter::FloatColumnWriter(typed) => {
1745            let array = column.as_primitive::<Float32Type>();
1746            write_primitive(typed, array.values(), levels)
1747        }
1748        ColumnWriter::DoubleColumnWriter(typed) => {
1749            let array = column.as_primitive::<Float64Type>();
1750            write_primitive(typed, array.values(), levels)
1751        }
1752        ColumnWriter::ByteArrayColumnWriter(_) => {
1753            unreachable!("should use ByteArrayWriter")
1754        }
1755        ColumnWriter::FixedLenByteArrayColumnWriter(typed) => {
1756            let bytes = match column.data_type() {
1757                ArrowDataType::Interval(interval_unit) => match interval_unit {
1758                    IntervalUnit::YearMonth => {
1759                        let array = column.as_primitive::<IntervalYearMonthType>();
1760                        get_interval_ym_array_slice(array, indices.iter().copied())
1761                    }
1762                    IntervalUnit::DayTime => {
1763                        let array = column.as_primitive::<IntervalDayTimeType>();
1764                        get_interval_dt_array_slice(array, indices.iter().copied())
1765                    }
1766                    IntervalUnit::MonthDayNano => {
1767                        return Err(ParquetError::NYI(format!(
1768                            "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented"
1769                        )));
1770                    }
1771                },
1772                ArrowDataType::FixedSizeBinary(_) => {
1773                    let array = column.as_fixed_size_binary();
1774                    get_fsb_array_slice(array, indices.iter().copied())
1775                }
1776                ArrowDataType::Decimal32(_, _) => {
1777                    let array = column.as_primitive::<Decimal32Type>();
1778                    get_decimal_array_slice(array, indices.iter().copied())
1779                }
1780                ArrowDataType::Decimal64(_, _) => {
1781                    let array = column.as_primitive::<Decimal64Type>();
1782                    get_decimal_array_slice(array, indices.iter().copied())
1783                }
1784                ArrowDataType::Decimal128(_, _) => {
1785                    let array = column.as_primitive::<Decimal128Type>();
1786                    get_decimal_array_slice(array, indices.iter().copied())
1787                }
1788                ArrowDataType::Decimal256(_, _) => {
1789                    let array = column.as_primitive::<Decimal256Type>();
1790                    get_decimal_array_slice(array, indices.iter().copied())
1791                }
1792                ArrowDataType::Float16 => {
1793                    let array = column.as_primitive::<Float16Type>();
1794                    get_float_16_array_slice(array, indices.iter().copied())
1795                }
1796                _ => {
1797                    return Err(ParquetError::NYI(
1798                        "Attempting to write an Arrow type that is not yet implemented".to_string(),
1799                    ));
1800                }
1801            };
1802            typed.write_batch_internal(
1803                bytes.as_slice(),
1804                None,
1805                levels.def_level_data().as_ref(),
1806                levels.rep_level_data().as_ref(),
1807                None,
1808                None,
1809                None,
1810            )
1811        }
1812    }
1813}
1814
1815fn write_primitive<E: ColumnValueEncoder>(
1816    writer: &mut GenericColumnWriter<E>,
1817    values: &E::Values,
1818    levels: &ArrayLevels,
1819) -> Result<usize> {
1820    writer.write_batch_internal(
1821        values,
1822        Some(levels.non_null_indices()),
1823        levels.def_level_data().as_ref(),
1824        levels.rep_level_data().as_ref(),
1825        None,
1826        None,
1827        None,
1828    )
1829}
1830
1831fn get_bool_array_slice(
1832    array: &arrow_array::BooleanArray,
1833    indices: impl ExactSizeIterator<Item = usize>,
1834) -> Vec<bool> {
1835    let mut values = Vec::with_capacity(indices.len());
1836    for i in indices {
1837        values.push(array.value(i))
1838    }
1839    values
1840}
1841
1842/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1843/// An Arrow YearMonth interval only stores months, thus only the first 4 bytes are populated.
1844fn get_interval_ym_array_slice(
1845    array: &arrow_array::IntervalYearMonthArray,
1846    indices: impl ExactSizeIterator<Item = usize>,
1847) -> Vec<FixedLenByteArray> {
1848    chunk_array_slice(12, indices, move |i, chunk| {
1849        let value = array.value(i);
1850        chunk[0..4].copy_from_slice(&value.to_le_bytes());
1851    })
1852}
1853
1854/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1855/// An Arrow DayTime interval only stores days and millis, thus the first 4 bytes are not populated.
1856fn get_interval_dt_array_slice(
1857    array: &arrow_array::IntervalDayTimeArray,
1858    indices: impl ExactSizeIterator<Item = usize>,
1859) -> Vec<FixedLenByteArray> {
1860    chunk_array_slice(12, indices, move |i, chunk| {
1861        let value = array.value(i);
1862        chunk[4..8].copy_from_slice(&value.days.to_le_bytes());
1863        chunk[8..12].copy_from_slice(&value.milliseconds.to_le_bytes());
1864    })
1865}
1866
1867trait NativeDecimalType: DecimalType {
1868    type NativeBytes: AsRef<[u8]>;
1869
1870    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes;
1871}
1872impl NativeDecimalType for Decimal32Type {
1873    type NativeBytes = [u8; Self::BYTE_LENGTH];
1874
1875    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1876        value.to_be_bytes()
1877    }
1878}
1879impl NativeDecimalType for Decimal64Type {
1880    type NativeBytes = [u8; Self::BYTE_LENGTH];
1881
1882    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1883        value.to_be_bytes()
1884    }
1885}
1886impl NativeDecimalType for Decimal128Type {
1887    type NativeBytes = [u8; Self::BYTE_LENGTH];
1888
1889    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1890        value.to_be_bytes()
1891    }
1892}
1893impl NativeDecimalType for Decimal256Type {
1894    type NativeBytes = [u8; Self::BYTE_LENGTH];
1895
1896    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1897        value.to_be_bytes()
1898    }
1899}
1900
1901fn get_decimal_array_slice<T: NativeDecimalType>(
1902    array: &PrimitiveArray<T>,
1903    indices: impl ExactSizeIterator<Item = usize>,
1904) -> Vec<FixedLenByteArray> {
1905    let chunk_size = decimal_length_from_precision(array.precision());
1906    assert!(chunk_size <= T::BYTE_LENGTH);
1907
1908    if chunk_size == T::BYTE_LENGTH {
1909        // Special-case that allows inlining memcpy.
1910        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1911            let as_be_bytes = T::to_be_bytes(array.value(i));
1912            chunk.copy_from_slice(as_be_bytes.as_ref());
1913        })
1914    } else {
1915        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1916            let as_be_bytes = T::to_be_bytes(array.value(i));
1917            let resized_value = &as_be_bytes.as_ref()[(T::BYTE_LENGTH - chunk.len())..];
1918            chunk.copy_from_slice(resized_value);
1919        })
1920    }
1921}
1922
1923fn get_float_16_array_slice(
1924    array: &arrow_array::Float16Array,
1925    indices: impl ExactSizeIterator<Item = usize>,
1926) -> Vec<FixedLenByteArray> {
1927    chunk_array_slice(2, indices, move |i, chunk| {
1928        let value = array.value(i).to_le_bytes();
1929        chunk.copy_from_slice(&value);
1930    })
1931}
1932
1933fn get_fsb_array_slice(
1934    array: &arrow_array::FixedSizeBinaryArray,
1935    indices: impl ExactSizeIterator<Item = usize>,
1936) -> Vec<FixedLenByteArray> {
1937    chunk_array_slice(array.value_size(), indices, move |i, chunk| {
1938        let value = array.value(i);
1939        chunk.copy_from_slice(value);
1940    })
1941}
1942
1943#[inline]
1944fn chunk_array_slice(
1945    chunk_size: usize,
1946    indices: impl ExactSizeIterator<Item = usize>,
1947    writer: impl Fn(usize, &mut [u8]),
1948) -> Vec<FixedLenByteArray> {
1949    let capacity = indices.len() * chunk_size;
1950    // TODO: This could be done with Vec::spare_capacity_mut,
1951    //       but [MaybeUninit]::write_copy_of_slice is gated behind MSRV 1.93
1952    let mut arena = vec![0; capacity];
1953    for (i, chunk) in indices.zip(arena.chunks_exact_mut(chunk_size)) {
1954        writer(i, chunk);
1955    }
1956    chunk_contiguous_vec(arena, chunk_size)
1957}
1958
1959fn chunk_contiguous_vec(arena: Vec<u8>, chunk_size: usize) -> Vec<FixedLenByteArray> {
1960    let mut values = Vec::with_capacity(arena.len() / chunk_size);
1961    let mut arena = Bytes::from(arena);
1962    while arena.len() >= chunk_size {
1963        let slice = arena.split_to(chunk_size);
1964        values.push(FixedLenByteArray::from(ByteArray::from(slice)));
1965    }
1966    values
1967}
1968
1969/// Hash a byte slice to a u64 for NDV tracking.
1970#[inline]
1971fn hash_bytes(bytes: &[u8]) -> u64 {
1972    twox_hash::XxHash64::oneshot(0, bytes)
1973}
1974
1975/// Returns the fixed byte width for primitive Arrow types, or `None` for variable-length types.
1976fn fixed_byte_width(dt: &ArrowDataType) -> Option<usize> {
1977    use ArrowDataType::*;
1978    match dt {
1979        Int8 | UInt8 => Some(1),
1980        Int16 | UInt16 | Float16 => Some(2),
1981        Int32 | UInt32 | Float32 | Date32 | Time32(_) | Decimal32(_, _) => Some(4),
1982        Int64
1983        | UInt64
1984        | Float64
1985        | Date64
1986        | Time64(_)
1987        | Timestamp(_, _)
1988        | Duration(_)
1989        | Decimal64(_, _) => Some(8),
1990        Interval(IntervalUnit::YearMonth) => Some(4),
1991        Interval(IntervalUnit::DayTime) => Some(8),
1992        Interval(IntervalUnit::MonthDayNano) => Some(16),
1993        Decimal128(_, _) => Some(16),
1994        Decimal256(_, _) => Some(32),
1995        _ => None,
1996    }
1997}
1998
1999/// Hash the non-null values in `array` (at `non_null_indices`) into `seen`.
2000///
2001/// Handles primitive, boolean, fixed-size-binary, and variable-length (Utf8/Binary)
2002/// arrays. Unsupported types are silently skipped, leaving `seen` unchanged for
2003/// those values (NDV is best-effort).
2004fn update_distinct_values_seen(
2005    array: &dyn arrow_array::Array,
2006    non_null_indices: &[usize],
2007    seen: &mut DistinctValuesSet,
2008) {
2009    let data = array.to_data();
2010    let offset = data.offset();
2011
2012    match array.data_type() {
2013        ArrowDataType::Boolean => {
2014            let arr = array
2015                .as_any()
2016                .downcast_ref::<arrow_array::BooleanArray>()
2017                .unwrap();
2018            for &row in non_null_indices {
2019                seen.insert(arr.value(row) as u64);
2020            }
2021        }
2022        ArrowDataType::Utf8 | ArrowDataType::Binary => {
2023            let offsets = data.buffers()[0].typed_data::<i32>();
2024            let values = data.buffers()[1].as_slice();
2025            for &row in non_null_indices {
2026                let start = offsets[offset + row] as usize;
2027                let end = offsets[offset + row + 1] as usize;
2028                seen.insert(hash_bytes(&values[start..end]));
2029            }
2030        }
2031        ArrowDataType::LargeUtf8 | ArrowDataType::LargeBinary => {
2032            let offsets = data.buffers()[0].typed_data::<i64>();
2033            let values = data.buffers()[1].as_slice();
2034            for &row in non_null_indices {
2035                let start = offsets[offset + row] as usize;
2036                let end = offsets[offset + row + 1] as usize;
2037                seen.insert(hash_bytes(&values[start..end]));
2038            }
2039        }
2040        ArrowDataType::FixedSizeBinary(byte_width) => {
2041            let byte_width = *byte_width as usize;
2042            let buffer = data.buffers()[0].as_slice();
2043            for &row in non_null_indices {
2044                let start = (offset + row) * byte_width;
2045                seen.insert(hash_bytes(&buffer[start..start + byte_width]));
2046            }
2047        }
2048        ArrowDataType::Utf8View => {
2049            let string_view_array = array.as_string_view();
2050            for &row in non_null_indices {
2051                seen.insert(hash_bytes(string_view_array.value(row).as_bytes()));
2052            }
2053        }
2054        ArrowDataType::BinaryView => {
2055            let binary_view_array = array.as_binary_view();
2056            for &row in non_null_indices {
2057                seen.insert(hash_bytes(binary_view_array.value(row)));
2058            }
2059        }
2060        data_type => {
2061            if let Some(width) = fixed_byte_width(data_type) {
2062                let buffer = data.buffers()[0].as_slice();
2063                for &row in non_null_indices {
2064                    let pos = (offset + row) * width;
2065                    seen.insert(hash_bytes(&buffer[pos..pos + width]));
2066                }
2067            }
2068            // nested types (List, LargeList, etc.) are Parquet groups, not leaf columns: skip
2069        }
2070    }
2071}
2072
2073// Allow the helpers to use the same imports in unit and integration tests.
2074#[cfg(test)]
2075use crate as parquet_crate;
2076
2077#[cfg(test)]
2078#[path = "../../../tests/arrow_writer/roundtrip_helpers.rs"]
2079mod roundtrip_helpers;
2080
2081#[cfg(test)]
2082mod tests {
2083    use super::roundtrip_helpers::{
2084        RoundTripTest, SMALL_SIZE, required_and_optional, roundtrip_opts,
2085        roundtrip_opts_with_array_validation,
2086    };
2087    use super::*;
2088    use std::cmp::Ordering;
2089    use std::collections::HashMap;
2090
2091    use std::fs::File;
2092
2093    use crate::arrow::ARROW_SCHEMA_META_KEY;
2094    use crate::arrow::arrow_reader::{ParquetRecordBatchReader, ParquetRecordBatchReaderBuilder};
2095    use crate::column::page::{Page, PageReader};
2096    use crate::file::metadata::thrift::PageHeader;
2097    use crate::file::page_index::column_index::ColumnIndexMetaData;
2098    use crate::file::reader::SerializedPageReader;
2099    use crate::parquet_thrift::{ReadThrift, ThriftSliceInputProtocol};
2100    use crate::schema::types::ColumnPath;
2101    use arrow::datatypes::{DataType, Schema};
2102    use arrow::error::Result as ArrowResult;
2103    use arrow::util::data_gen::create_random_array;
2104    use arrow::util::pretty::pretty_format_batches;
2105    use arrow::{array::*, buffer::Buffer};
2106    use arrow_buffer::{IntervalMonthDayNano, NullBuffer};
2107    use arrow_schema::Fields;
2108
2109    use crate::basic::{Encoding, EncodingMask};
2110    use crate::data_type::AsBytes;
2111    use crate::file::metadata::{ColumnChunkMetaData, ParquetMetaData, ParquetMetaDataReader};
2112    use crate::file::properties::{
2113        BloomFilterPosition, EnabledStatistics, ReaderProperties, WriterVersion,
2114    };
2115    use crate::file::serialized_reader::ReadOptionsBuilder;
2116    use crate::file::{
2117        reader::{FileReader, SerializedFileReader},
2118        statistics::Statistics,
2119    };
2120
2121    /// A [`PageStore`] that allocates *sparse, non-contiguous* handles and keeps
2122    /// blobs in a `HashMap` — nothing like the default `Vec<Bytes>`. Used to
2123    /// prove the writer relies only on the opaque-handle contract and never on
2124    /// handles being dense `Vec` indices. Records how many blobs were stored.
2125    #[derive(Debug, Default)]
2126    struct RecordingPageStore {
2127        next: u64,
2128        blobs: HashMap<u64, Bytes>,
2129        puts: Arc<std::sync::atomic::AtomicUsize>,
2130    }
2131
2132    impl PageStore for RecordingPageStore {
2133        fn put(&mut self, value: Bytes) -> Result<PageKey> {
2134            // Deliberately non-sequential, never-zero handles.
2135            let id = 100 + self.next * 7;
2136            self.next += 1;
2137            self.puts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2138            self.blobs.insert(id, value);
2139            Ok(PageKey::new(id))
2140        }
2141
2142        fn take(&mut self, key: PageKey) -> Result<Bytes> {
2143            self.blobs
2144                .remove(&key.get())
2145                .ok_or_else(|| ParquetError::General(format!("missing key {}", key.get())))
2146        }
2147    }
2148
2149    #[derive(Debug)]
2150    struct RecordingPageStoreFactory {
2151        puts: Arc<std::sync::atomic::AtomicUsize>,
2152    }
2153
2154    impl PageStoreFactory for RecordingPageStoreFactory {
2155        fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2156            Ok(Box::new(RecordingPageStore {
2157                puts: self.puts.clone(),
2158                ..Default::default()
2159            }))
2160        }
2161    }
2162
2163    /// A custom [`PageStore`] must produce byte-identical files to the in-memory
2164    /// default, across dictionary and non-dictionary columns and multiple row
2165    /// groups (so multiple store instances are exercised).
2166    #[test]
2167    fn custom_page_store_is_byte_identical_to_default() {
2168        let schema = Arc::new(Schema::new(vec![
2169            Field::new("i", DataType::Int32, true),
2170            // A low-cardinality string column to exercise the dictionary path.
2171            Field::new("s", DataType::Utf8, true),
2172        ]));
2173        let i = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5), Some(6)]);
2174        let s = StringArray::from(vec![
2175            Some("a"),
2176            Some("bb"),
2177            Some("a"),
2178            None,
2179            Some("bb"),
2180            Some("ccc"),
2181        ]);
2182        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(i), Arc::new(s)]).unwrap();
2183
2184        // Small row groups so multiple column chunks (hence multiple store
2185        // instances) are produced.
2186        let props = WriterProperties::builder()
2187            .set_max_row_group_row_count(Some(3))
2188            .build();
2189
2190        let write = |factory: Option<Arc<dyn PageStoreFactory>>| {
2191            let mut buffer = Vec::new();
2192            let mut opts = ArrowWriterOptions::new().with_properties(props.clone());
2193            if let Some(factory) = factory {
2194                opts = opts.with_page_store_factory(factory);
2195            }
2196            let mut writer =
2197                ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2198            writer.write(&batch).unwrap();
2199            writer.close().unwrap();
2200            buffer
2201        };
2202
2203        let default_bytes = write(None);
2204
2205        let puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2206        let custom_bytes = write(Some(Arc::new(RecordingPageStoreFactory {
2207            puts: puts.clone(),
2208        })));
2209
2210        assert!(
2211            puts.load(std::sync::atomic::Ordering::Relaxed) > 0,
2212            "custom PageStore was never written to"
2213        );
2214        assert_eq!(
2215            default_bytes, custom_bytes,
2216            "a custom PageStore must produce byte-identical output to the default"
2217        );
2218    }
2219
2220    /// A dictionary-encoded column written through the deferred-ordering Arrow
2221    /// path must round-trip correctly even with the offset index disabled, when
2222    /// only the chunk-level dictionary/data page offsets are rewritten (there is
2223    /// no offset index to rebuild). Spans multiple data pages so the
2224    /// dictionary-first reordering is exercised.
2225    #[test]
2226    #[cfg_attr(miri, ignore)] // Takes too long
2227    fn dictionary_column_round_trips_with_offset_index_disabled() {
2228        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2229
2230        // Low cardinality so the column stays dictionary-encoded; enough rows to
2231        // span several data pages within a single row group.
2232        let values: Vec<Option<i32>> = (0..50_000).map(|i| Some(i % 8)).collect();
2233        let array = Int32Array::from(values.clone());
2234        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2235
2236        let props = WriterProperties::builder()
2237            .set_offset_index_disabled(true)
2238            .set_data_page_row_count_limit(4096)
2239            .build();
2240        let opts = ArrowWriterOptions::new().with_properties(props);
2241
2242        let mut buffer = Vec::new();
2243        let mut writer =
2244            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2245        writer.write(&batch).unwrap();
2246        writer.close().unwrap();
2247
2248        let reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), values.len()).unwrap();
2249        let read: Vec<RecordBatch> = reader.collect::<ArrowResult<_>>().unwrap();
2250        let read_values: Vec<Option<i32>> = read
2251            .iter()
2252            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().iter())
2253            .collect();
2254        assert_eq!(read_values, values);
2255    }
2256
2257    /// The dictionary page is routed through the [`PageStore`] like any other
2258    /// page rather than held resident in memory, so a dictionary column chunk's
2259    /// *entire* serialized size — dictionary page included — passes through the
2260    /// store.
2261    #[test]
2262    fn dictionary_page_is_routed_through_the_store() {
2263        /// A store that sums the bytes handed to `put`.
2264        #[derive(Debug, Default)]
2265        struct SizeRecordingPageStore {
2266            blobs: Vec<Bytes>,
2267            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2268        }
2269        impl PageStore for SizeRecordingPageStore {
2270            fn put(&mut self, value: Bytes) -> Result<PageKey> {
2271                self.bytes_put
2272                    .fetch_add(value.len(), std::sync::atomic::Ordering::Relaxed);
2273                let key = PageKey::new(self.blobs.len() as u64);
2274                self.blobs.push(value);
2275                Ok(key)
2276            }
2277            fn take(&mut self, key: PageKey) -> Result<Bytes> {
2278                Ok(std::mem::take(&mut self.blobs[key.get() as usize]))
2279            }
2280        }
2281        #[derive(Debug)]
2282        struct Factory {
2283            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2284        }
2285        impl PageStoreFactory for Factory {
2286            fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2287                Ok(Box::new(SizeRecordingPageStore {
2288                    bytes_put: self.bytes_put.clone(),
2289                    ..Default::default()
2290                }))
2291            }
2292        }
2293
2294        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)]));
2295        // Low cardinality keeps the column dictionary-encoded with a real,
2296        // non-empty dictionary page.
2297        let values: Vec<&str> = (0..2048)
2298            .map(|i| ["alpha", "beta", "gamma", "delta"][i % 4])
2299            .collect();
2300        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(StringArray::from(values))])
2301            .unwrap();
2302
2303        let bytes_put = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2304        let opts = ArrowWriterOptions::new().with_page_store_factory(Arc::new(Factory {
2305            bytes_put: bytes_put.clone(),
2306        }));
2307
2308        // A single batch / single column means exactly one row group and one
2309        // store instance, so the bytes it saw map to one column chunk.
2310        let mut buffer = Vec::new();
2311        let mut writer =
2312            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2313        writer.write(&batch).unwrap();
2314        writer.close().unwrap();
2315
2316        let reader = SerializedFileReader::new(Bytes::from(buffer)).unwrap();
2317        let column = reader.metadata().row_group(0).column(0);
2318        assert!(
2319            column.dictionary_page_offset().is_some(),
2320            "expected the column to be dictionary-encoded"
2321        );
2322
2323        // The bytes the store was handed must account for the whole chunk,
2324        // dictionary page included. Holding the dictionary page apart from the
2325        // store would make this fall short by the dictionary page's size.
2326        assert_eq!(
2327            bytes_put.load(std::sync::atomic::Ordering::Relaxed) as i64,
2328            column.compressed_size(),
2329            "the dictionary page must pass through the store like any other page"
2330        );
2331    }
2332
2333    /// The `page_encoding_stats` list of a dictionary-encoded column chunk must
2334    /// list the dictionary page *before* the data pages, matching the on-disk
2335    /// page layout (the dictionary page is always written first) and the order
2336    /// produced by the column-at-a-time `SerializedFileWriter`.
2337    #[test]
2338    fn dictionary_page_encoding_stats_lists_dictionary_first() {
2339        use crate::basic::PageType;
2340        use crate::file::metadata::ParquetMetaDataOptions;
2341
2342        // A low-cardinality column so it stays dictionary-encoded, with enough
2343        // rows to emit at least one data page in addition to the dictionary page.
2344        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2345        let values: Vec<Option<i32>> = (0..4096).map(|i| Some(i % 4)).collect();
2346        let array = Int32Array::from(values);
2347        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2348
2349        let mut buffer = Vec::new();
2350        let mut writer = ArrowWriter::try_new(&mut buffer, schema.clone(), None).unwrap();
2351        writer.write(&batch).unwrap();
2352        writer.close().unwrap();
2353        let buffer = Bytes::from(buffer);
2354
2355        // Read the *full*, ordered page encoding stats. By default this crate
2356        // collapses them to a bitmask, which would discard the ordering this
2357        // test is about, so opt out of that here.
2358        let options = ParquetMetaDataOptions::new().with_encoding_stats_as_mask(false);
2359        let metadata = ParquetMetaDataReader::new()
2360            .with_metadata_options(Some(options))
2361            .parse_and_finish(&buffer)
2362            .unwrap();
2363
2364        let col = metadata.row_group(0).column(0);
2365        assert!(
2366            col.dictionary_page_offset().is_some(),
2367            "column should be dictionary encoded"
2368        );
2369        let stats = col
2370            .page_encoding_stats()
2371            .expect("full (non-mask) page encoding stats should be present");
2372
2373        // Arrow C++ (`IsColumnChunkFullyDictionaryEncoded`) requires the
2374        // dictionary page entry to be the first one.
2375        assert_eq!(
2376            stats[0].page_type,
2377            PageType::DICTIONARY_PAGE,
2378            "the DICTIONARY_PAGE encoding stat must come first, got {stats:?}"
2379        );
2380        assert!(
2381            stats[1..]
2382                .iter()
2383                .all(|s| s.page_type == PageType::DATA_PAGE)
2384        );
2385    }
2386
2387    fn get_bytes_after_close(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2388        let mut buffer = vec![];
2389
2390        let mut writer = ArrowWriter::try_new(&mut buffer, schema, None).unwrap();
2391        writer.write(expected_batch).unwrap();
2392        writer.close().unwrap();
2393
2394        buffer
2395    }
2396
2397    fn get_bytes_by_into_inner(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2398        let mut writer = ArrowWriter::try_new(Vec::new(), schema, None).unwrap();
2399        writer.write(expected_batch).unwrap();
2400        writer.into_inner().unwrap()
2401    }
2402
2403    #[test]
2404    fn roundtrip_bytes() {
2405        // define schema
2406        let schema = Arc::new(Schema::new(vec![
2407            Field::new("a", DataType::Int32, false),
2408            Field::new("b", DataType::Int32, true),
2409        ]));
2410
2411        // create some data
2412        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2413        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2414
2415        // build a record batch
2416        let expected_batch =
2417            RecordBatch::try_new(schema.clone(), vec![Arc::new(a), Arc::new(b)]).unwrap();
2418
2419        for buffer in [
2420            get_bytes_after_close(schema.clone(), &expected_batch),
2421            get_bytes_by_into_inner(schema, &expected_batch),
2422        ] {
2423            let cursor = Bytes::from(buffer);
2424            let mut record_batch_reader = ParquetRecordBatchReader::try_new(cursor, 1024).unwrap();
2425
2426            let actual_batch = record_batch_reader
2427                .next()
2428                .expect("No batch found")
2429                .expect("Unable to get batch");
2430
2431            assert_eq!(expected_batch.schema(), actual_batch.schema());
2432            assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
2433            assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
2434            for i in 0..expected_batch.num_columns() {
2435                let expected_data = expected_batch.column(i).to_data();
2436                let actual_data = actual_batch.column(i).to_data();
2437
2438                assert_eq!(expected_data, actual_data);
2439            }
2440        }
2441    }
2442
2443    #[test]
2444    fn arrow_writer_page_size() {
2445        let schema = Arc::new(Schema::new(vec![Field::new("col", DataType::Utf8, false)]));
2446
2447        let mut builder = StringBuilder::with_capacity(100, 329 * 10_000);
2448
2449        // Generate an array of 10 unique 10 character string
2450        for i in 0..10 {
2451            let value = i
2452                .to_string()
2453                .repeat(10)
2454                .chars()
2455                .take(10)
2456                .collect::<String>();
2457
2458            builder.append_value(value);
2459        }
2460
2461        let array = Arc::new(builder.finish());
2462
2463        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
2464
2465        let file = tempfile::tempfile().unwrap();
2466
2467        // Set everything very low so we fallback to PLAIN encoding after the first row
2468        let props = WriterProperties::builder()
2469            .set_data_page_size_limit(1)
2470            .set_dictionary_page_size_limit(1)
2471            .set_write_batch_size(1)
2472            .build();
2473
2474        let mut writer =
2475            ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), Some(props))
2476                .expect("Unable to write file");
2477        writer.write(&batch).unwrap();
2478        writer.close().unwrap();
2479
2480        let options = ReadOptionsBuilder::new().with_page_index().build();
2481        let reader =
2482            SerializedFileReader::new_with_options(file.try_clone().unwrap(), options).unwrap();
2483
2484        let column = reader.metadata().row_group(0).columns();
2485
2486        assert_eq!(column.len(), 1);
2487
2488        // We should write one row before falling back to PLAIN encoding so there should still be a
2489        // dictionary page.
2490        assert!(
2491            column[0].dictionary_page_offset().is_some(),
2492            "Expected a dictionary page"
2493        );
2494
2495        let page_index = reader
2496            .metadata()
2497            .page_index()
2498            .expect("page index should be present");
2499        let page_locations = page_index
2500            .page_locations(0, 0)
2501            .expect("page locations should exist");
2502
2503        // We should fallback to PLAIN encoding after the first row and our max page size is 1 bytes
2504        // so we expect one dictionary encoded page and then a page per row thereafter.
2505        assert_eq!(
2506            page_locations.len(),
2507            10,
2508            "Expected 10 pages but got {page_locations:#?}"
2509        );
2510    }
2511
2512    const MEDIUM_SIZE: usize = 63;
2513
2514    fn check_bloom_filter<T: AsBytes>(
2515        files: Vec<Bytes>,
2516        file_column: String,
2517        positive_values: Vec<T>,
2518        negative_values: Vec<T>,
2519    ) {
2520        files.into_iter().take(1).for_each(|file| {
2521            let file_reader = SerializedFileReader::new_with_options(
2522                file,
2523                ReadOptionsBuilder::new()
2524                    .with_reader_properties(
2525                        ReaderProperties::builder()
2526                            .set_read_bloom_filter(true)
2527                            .build(),
2528                    )
2529                    .build(),
2530            )
2531            .expect("Unable to open file as Parquet");
2532            let metadata = file_reader.metadata();
2533
2534            // Gets bloom filters from all row groups.
2535            let mut bloom_filters: Vec<_> = vec![];
2536            for (ri, row_group) in metadata.row_groups().iter().enumerate() {
2537                if let Some((column_index, _)) = row_group
2538                    .columns()
2539                    .iter()
2540                    .enumerate()
2541                    .find(|(_, column)| column.column_path().string() == file_column)
2542                {
2543                    let row_group_reader = file_reader
2544                        .get_row_group(ri)
2545                        .expect("Unable to read row group");
2546                    if let Some(sbbf) = row_group_reader.get_column_bloom_filter(column_index) {
2547                        bloom_filters.push(sbbf.clone());
2548                    } else {
2549                        panic!("No bloom filter for column named {file_column} found");
2550                    }
2551                } else {
2552                    panic!("No column named {file_column} found");
2553                }
2554            }
2555
2556            positive_values.iter().for_each(|value| {
2557                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
2558                assert!(
2559                    found.is_some(),
2560                    "{}",
2561                    format!("Value {:?} should be in bloom filter", value.as_bytes())
2562                );
2563            });
2564
2565            negative_values.iter().for_each(|value| {
2566                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
2567                assert!(
2568                    found.is_none(),
2569                    "{}",
2570                    format!("Value {:?} should not be in bloom filter", value.as_bytes())
2571                );
2572            });
2573        });
2574    }
2575
2576    #[test]
2577    #[cfg_attr(miri, ignore)] // Takes too long
2578    fn bool_large_single_column() {
2579        let values = Arc::new(
2580            [None, Some(true), Some(false)]
2581                .iter()
2582                .cycle()
2583                .copied()
2584                .take(200_000)
2585                .collect::<BooleanArray>(),
2586        );
2587        let schema = Schema::new(vec![Field::new("col", values.data_type().clone(), true)]);
2588        let expected_batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
2589        let file = tempfile::tempfile().unwrap();
2590
2591        let mut writer =
2592            ArrowWriter::try_new(file.try_clone().unwrap(), expected_batch.schema(), None)
2593                .expect("Unable to write file");
2594        writer.write(&expected_batch).unwrap();
2595        writer.close().unwrap();
2596    }
2597
2598    #[test]
2599    fn check_page_offset_index_with_nan() {
2600        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
2601        let schema = Schema::new(vec![Field::new("col", DataType::Float64, true)]);
2602        let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
2603
2604        let mut out = Vec::with_capacity(1024);
2605        let mut writer =
2606            ArrowWriter::try_new(&mut out, batch.schema(), None).expect("Unable to write file");
2607        writer.write(&batch).unwrap();
2608        let file_meta_data = writer.close().unwrap();
2609        for row_group in file_meta_data.row_groups() {
2610            for column in row_group.columns() {
2611                assert!(column.offset_index_offset().is_some());
2612                assert!(column.offset_index_length().is_some());
2613                assert!(column.column_index_offset().is_some());
2614                assert!(column.column_index_length().is_some());
2615            }
2616        }
2617        if let Some(page_index) = file_meta_data.page_index() {
2618            for rg in 0..file_meta_data.num_row_groups() {
2619                for col in 0..file_meta_data.row_group(rg).num_columns() {
2620                    let idx = page_index
2621                        .column_index(rg, col)
2622                        .expect("column index should exist");
2623                    assert!(idx.nan_counts().is_some());
2624                    let ColumnIndexMetaData::DOUBLE(float_idx) = idx else {
2625                        panic!("expected double statistics")
2626                    };
2627                    for i in 0..idx.num_pages() as usize {
2628                        assert_eq!(float_idx.nan_count(i), Some(10));
2629                        assert_eq!(
2630                            f64::NAN.total_cmp(float_idx.min_value(i).unwrap()),
2631                            Ordering::Equal
2632                        );
2633                        assert_eq!(
2634                            f64::NAN.total_cmp(float_idx.max_value(i).unwrap()),
2635                            Ordering::Equal
2636                        );
2637                    }
2638                }
2639            }
2640        } else {
2641            panic!("page index should be present");
2642        }
2643    }
2644
2645    #[test]
2646    fn check_page_offset_index_with_mixed_nan() {
2647        let schema = Arc::new(Schema::new(vec![Field::new(
2648            "col",
2649            DataType::Float64,
2650            true,
2651        )]));
2652
2653        let mut out = Vec::with_capacity(1024);
2654        let props = WriterProperties::builder()
2655            .set_data_page_row_count_limit(10)
2656            .build();
2657        let mut writer = ArrowWriter::try_new(&mut out, schema.clone(), Some(props))
2658            .expect("Unable to write file");
2659
2660        // write a page of all NaN (since batch min and max are NaN, global min/max are NaN)
2661        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
2662        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2663        writer.write(&batch).unwrap();
2664
2665        // write a page of all -NaN (batch min/max is -NaN, should update global min to -NaN)
2666        let values = Arc::new(Float64Array::from(vec![-f64::NAN; 10]));
2667        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2668        writer.write(&batch).unwrap();
2669
2670        // write a page of all 0 (non-NaN should override global min/max, now 0/0)
2671        let values = Arc::new(Float64Array::from(vec![0_f64; 10]));
2672        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2673        writer.write(&batch).unwrap();
2674
2675        // write a mixed page (should now have min -1, max 1)
2676        let values = Arc::new(Float64Array::from(vec![
2677            -1.0,
2678            0.0,
2679            f64::NAN,
2680            -f64::NAN,
2681            1.0,
2682        ]));
2683        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2684        writer.write(&batch).unwrap();
2685
2686        let file_meta_data = writer.close().unwrap();
2687
2688        // check the column chunk stats are correct
2689        let col_stats = file_meta_data
2690            .row_group(0)
2691            .column(0)
2692            .statistics()
2693            .expect("missing column chunk statistics");
2694
2695        assert_eq!(col_stats.nan_count_opt(), Some(22));
2696        assert_eq!(col_stats.min_bytes_opt(), Some((-1.0f64).as_bytes()));
2697        assert_eq!(col_stats.max_bytes_opt(), Some(1.0f64.as_bytes()));
2698
2699        assert!(file_meta_data.page_index().is_some());
2700        let col_idx = &file_meta_data.page_index().unwrap().column_index(0, 0);
2701        assert_eq!(col_idx.as_ref().unwrap().num_pages(), 4);
2702
2703        // test each page
2704        let Some(ColumnIndexMetaData::DOUBLE(float_idx)) = col_idx else {
2705            panic!("expected double statistics")
2706        };
2707
2708        assert_eq!(float_idx.nan_counts, Some(vec![10, 10, 0, 2]));
2709        assert_eq!(
2710            f64::NAN.total_cmp(float_idx.min_value(0).unwrap()),
2711            Ordering::Equal
2712        );
2713        assert_eq!(
2714            f64::NAN.total_cmp(float_idx.max_value(0).unwrap()),
2715            Ordering::Equal
2716        );
2717        assert_eq!(
2718            (-f64::NAN).total_cmp(float_idx.min_value(1).unwrap()),
2719            Ordering::Equal
2720        );
2721        assert_eq!(
2722            (-f64::NAN).total_cmp(float_idx.max_value(1).unwrap()),
2723            Ordering::Equal
2724        );
2725        assert_eq!(float_idx.min_value(2), Some(&0.0));
2726        assert_eq!(float_idx.max_value(2), Some(&0.0));
2727        assert_eq!(float_idx.min_value(3), Some(&-1.0));
2728        assert_eq!(float_idx.max_value(3), Some(&1.0));
2729    }
2730
2731    #[test]
2732    #[should_panic(
2733        expected = "Attempting to write an Arrow interval type MonthDayNano to parquet that is not yet implemented"
2734    )]
2735    fn interval_month_day_nano_single_column() {
2736        required_and_optional::<IntervalMonthDayNanoArray, _>(vec![
2737            IntervalMonthDayNano::new(0, 1, 5),
2738            IntervalMonthDayNano::new(0, 3, 2),
2739            IntervalMonthDayNano::new(3, -2, -5),
2740            IntervalMonthDayNano::new(-200, 4, -1),
2741        ]);
2742    }
2743
2744    #[test]
2745    #[cfg_attr(miri, ignore)] // Takes too long
2746    fn i32_column_bloom_filter_at_end() {
2747        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2748        let files = RoundTripTest::new(array)
2749            .with_nullable(false)
2750            .with_bloom_filter(true)
2751            .with_bloom_filter_position(BloomFilterPosition::End)
2752            .run();
2753
2754        check_bloom_filter(
2755            files,
2756            "col".to_string(),
2757            (0..SMALL_SIZE as i32).collect(),
2758            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2759        );
2760    }
2761
2762    #[test]
2763    #[cfg_attr(miri, ignore)] // Takes too long
2764    fn i32_column_bloom_filter() {
2765        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2766        let files = RoundTripTest::new(array)
2767            .with_nullable(false)
2768            .with_bloom_filter(true)
2769            .run();
2770
2771        check_bloom_filter(
2772            files,
2773            "col".to_string(),
2774            (0..SMALL_SIZE as i32).collect(),
2775            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2776        );
2777    }
2778
2779    fn write_with_bloom_filter(array: ArrayRef, dictionary_page_size_limit: usize) -> Bytes {
2780        let schema = Arc::new(Schema::new(vec![Field::new(
2781            "col",
2782            array.data_type().clone(),
2783            false,
2784        )]));
2785        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
2786        let props = WriterProperties::builder()
2787            .set_dictionary_enabled(true)
2788            .set_dictionary_page_size_limit(dictionary_page_size_limit)
2789            .set_write_batch_size(256)
2790            .set_bloom_filter_enabled(true)
2791            .build();
2792        let mut buf = Vec::new();
2793        let mut writer = ArrowWriter::try_new(&mut buf, schema, Some(props)).unwrap();
2794        writer.write(&batch).unwrap();
2795        writer.close().unwrap();
2796        Bytes::from(buf)
2797    }
2798
2799    fn data_page_encoding_mask(file: &Bytes) -> EncodingMask {
2800        let metadata = ParquetMetaDataReader::new().parse_and_finish(file).unwrap();
2801        *metadata
2802            .row_group(0)
2803            .column(0)
2804            .page_encoding_stats_mask()
2805            .unwrap()
2806    }
2807
2808    /// While a column is dictionary encoded the bloom filter is populated from the dictionary
2809    /// when it is flushed, so a chunk that stays dictionary encoded must still contain every value.
2810    #[test]
2811    fn string_column_bloom_filter_populated_from_dictionary() {
2812        let values: Vec<String> = (0..2000).map(|i| format!("value-{}", i % 10)).collect();
2813        let array = Arc::new(StringArray::from_iter_values(&values));
2814        let file = write_with_bloom_filter(array, 1024 * 1024);
2815        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
2816
2817        check_bloom_filter(
2818            vec![file],
2819            "col".to_string(),
2820            (0..10).map(|i| format!("value-{i}").into_bytes()).collect(),
2821            (10..20)
2822                .map(|i| format!("value-{i}").into_bytes())
2823                .collect(),
2824        );
2825    }
2826
2827    /// After falling back from dictionary encoding the filter holds the dictionary's values
2828    /// and every value written plain afterwards.
2829    #[test]
2830    fn string_column_bloom_filter_across_dictionary_fallback() {
2831        let values: Vec<String> = (0..2000).map(|i| format!("value-{i}")).collect();
2832        let array = Arc::new(StringArray::from_iter_values(&values));
2833        let file = write_with_bloom_filter(array, 1024);
2834        let encodings = data_page_encoding_mask(&file);
2835        assert!(
2836            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
2837            "expected dictionary and plain data pages, got {encodings:?}"
2838        );
2839
2840        check_bloom_filter(
2841            vec![file],
2842            "col".to_string(),
2843            values.into_iter().map(String::into_bytes).collect(),
2844            (2000..2010)
2845                .map(|i| format!("value-{i}").into_bytes())
2846                .collect(),
2847        );
2848    }
2849
2850    #[test]
2851    fn i64_column_bloom_filter_populated_from_dictionary() {
2852        let array = Arc::new(Int64Array::from_iter_values((0..2000).map(|i| i % 10)));
2853        let file = write_with_bloom_filter(array, 1024 * 1024);
2854        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
2855
2856        check_bloom_filter(
2857            vec![file],
2858            "col".to_string(),
2859            (0..10i64).collect(),
2860            (10..20i64).collect(),
2861        );
2862    }
2863
2864    #[test]
2865    fn i64_column_bloom_filter_across_dictionary_fallback() {
2866        let array = Arc::new(Int64Array::from_iter_values(0..2000i64));
2867        let file = write_with_bloom_filter(array, 1024);
2868        let encodings = data_page_encoding_mask(&file);
2869        assert!(
2870            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
2871            "expected dictionary and plain data pages, got {encodings:?}"
2872        );
2873
2874        check_bloom_filter(
2875            vec![file],
2876            "col".to_string(),
2877            (0..2000i64).collect(),
2878            (2000..2010i64).collect(),
2879        );
2880    }
2881
2882    /// Test that bloom filter folding produces correct results even when
2883    /// the configured NDV differs significantly from actual NDV.
2884    /// A large NDV means a larger initial filter that gets folded down;
2885    /// a small NDV means a smaller initial filter.
2886    #[test]
2887    #[cfg_attr(miri, ignore)] // Takes too long
2888    fn i32_column_bloom_filter_fixed_ndv() {
2889        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2890
2891        // NDV much larger than actual distinct values — tests folding a large filter down
2892        let files = RoundTripTest::new(array.clone())
2893            .with_nullable(false)
2894            .with_bloom_filter(true)
2895            .with_bloom_filter_ndv(1_000_000)
2896            .run();
2897
2898        check_bloom_filter(
2899            files,
2900            "col".to_string(),
2901            (0..SMALL_SIZE as i32).collect(),
2902            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2903        );
2904
2905        // NDV smaller than actual distinct values — tests the underestimate path
2906        let files = RoundTripTest::new(array)
2907            .with_nullable(false)
2908            .with_bloom_filter(true)
2909            .with_bloom_filter_ndv(3)
2910            .run();
2911
2912        check_bloom_filter(
2913            files,
2914            "col".to_string(),
2915            (0..SMALL_SIZE as i32).collect(),
2916            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2917        );
2918    }
2919
2920    #[test]
2921    #[cfg_attr(miri, ignore)] // Takes too long
2922    fn binary_column_bloom_filter() {
2923        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
2924        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
2925        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
2926
2927        let array = Arc::new(BinaryArray::from_iter_values(many_vecs_iter));
2928        let files = RoundTripTest::new(array)
2929            .with_nullable(false)
2930            .with_bloom_filter(true)
2931            .run();
2932
2933        check_bloom_filter(
2934            files,
2935            "col".to_string(),
2936            many_vecs,
2937            vec![vec![(SMALL_SIZE + 1) as u8]],
2938        );
2939    }
2940
2941    #[test]
2942    #[cfg_attr(miri, ignore)] // Takes too long
2943    fn empty_string_null_column_bloom_filter() {
2944        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
2945        let raw_strs = raw_values.iter().map(|s| s.as_str());
2946
2947        let array = Arc::new(StringArray::from_iter_values(raw_strs));
2948        let files = RoundTripTest::new(array)
2949            .with_nullable(false)
2950            .with_bloom_filter(true)
2951            .run();
2952
2953        let optional_raw_values: Vec<_> = raw_values
2954            .iter()
2955            .enumerate()
2956            .filter_map(|(i, v)| if i % 2 == 0 { None } else { Some(v.as_str()) })
2957            .collect();
2958        // For null slots, empty string should not be in bloom filter.
2959        check_bloom_filter(files, "col".to_string(), optional_raw_values, vec![""]);
2960    }
2961
2962    #[test]
2963    fn list_and_map_coerced_names() {
2964        // Create map and list with non-Parquet naming
2965        let list_field =
2966            Field::new_list("my_list", Field::new("item", DataType::Int32, false), false);
2967        let map_field = Field::new_map(
2968            "my_map",
2969            "my_entries",
2970            Field::new("my_keys", DataType::Int32, false),
2971            Field::new("my_values", DataType::Int32, true),
2972            false,
2973            true,
2974        );
2975
2976        let list_array = create_random_array(&list_field, 100, 0.0, 0.0).unwrap();
2977        let map_array = create_random_array(&map_field, 100, 0.0, 0.0).unwrap();
2978
2979        let arrow_schema = Arc::new(Schema::new(vec![list_field, map_field]));
2980
2981        // Write data to Parquet but coerce names to match spec
2982        let props = Some(WriterProperties::builder().set_coerce_types(true).build());
2983        let file = tempfile::tempfile().unwrap();
2984        let mut writer =
2985            ArrowWriter::try_new(file.try_clone().unwrap(), arrow_schema.clone(), props).unwrap();
2986
2987        let batch = RecordBatch::try_new(arrow_schema, vec![list_array, map_array]).unwrap();
2988        writer.write(&batch).unwrap();
2989        let file_metadata = writer.close().unwrap();
2990
2991        let schema = file_metadata.file_metadata().schema();
2992        // Coerced name of "item" should be "element"
2993        let list_field = &schema.get_fields()[0].get_fields()[0];
2994        assert_eq!(list_field.get_fields()[0].name(), "element");
2995
2996        let map_field = &schema.get_fields()[1].get_fields()[0];
2997        // Coerced name of "entries" should be "key_value"
2998        assert_eq!(map_field.name(), "key_value");
2999        // Coerced name of "my_keys" should be "key"
3000        assert_eq!(map_field.get_fields()[0].name(), "key");
3001        // Coerced name of "my_values" should be "value"
3002        assert_eq!(map_field.get_fields()[1].name(), "value");
3003
3004        // Double check schema after reading from the file
3005        let reader = SerializedFileReader::new(file).unwrap();
3006        let file_schema = reader.metadata().file_metadata().schema();
3007        let fields = file_schema.get_fields();
3008        let list_field = &fields[0].get_fields()[0];
3009        assert_eq!(list_field.get_fields()[0].name(), "element");
3010        let map_field = &fields[1].get_fields()[0];
3011        assert_eq!(map_field.name(), "key_value");
3012        assert_eq!(map_field.get_fields()[0].name(), "key");
3013        assert_eq!(map_field.get_fields()[1].name(), "value");
3014    }
3015
3016    #[test]
3017    #[cfg_attr(miri, ignore)] // Takes too long
3018    fn fallback_flush_data_page() {
3019        //tests if the Fallback::flush_data_page clears all buffers correctly
3020        let raw_values: Vec<_> = (0..MEDIUM_SIZE).map(|i| i.to_string()).collect();
3021        let values = Arc::new(StringArray::from(raw_values));
3022        let encodings = vec![
3023            Encoding::DELTA_BYTE_ARRAY,
3024            Encoding::DELTA_LENGTH_BYTE_ARRAY,
3025        ];
3026        let data_type = values.data_type().clone();
3027        let schema = Arc::new(Schema::new(vec![Field::new("col", data_type, false)]));
3028        let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
3029
3030        let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
3031        let data_page_size_limit: usize = 32;
3032        let write_batch_size: usize = 16;
3033
3034        for encoding in &encodings {
3035            for row_group_size in row_group_sizes {
3036                let props = WriterProperties::builder()
3037                    .set_writer_version(WriterVersion::PARQUET_2_0)
3038                    .set_max_row_group_row_count(Some(row_group_size))
3039                    .set_dictionary_enabled(false)
3040                    .set_encoding(*encoding)
3041                    .set_data_page_size_limit(data_page_size_limit)
3042                    .set_write_batch_size(write_batch_size)
3043                    .build();
3044
3045                roundtrip_opts_with_array_validation(&expected_batch, props, |a, b| {
3046                    let string_array_a = StringArray::from(a.clone());
3047                    let string_array_b = StringArray::from(b.clone());
3048                    let vec_a: Vec<&str> = string_array_a.iter().map(|v| v.unwrap()).collect();
3049                    let vec_b: Vec<&str> = string_array_b.iter().map(|v| v.unwrap()).collect();
3050                    assert_eq!(
3051                        vec_a, vec_b,
3052                        "failed for encoder: {encoding:?} and row_group_size: {row_group_size:?}"
3053                    );
3054                });
3055            }
3056        }
3057    }
3058
3059    #[test]
3060    #[cfg_attr(miri, ignore)] // Takes too long
3061    fn u32_min_max() {
3062        // check values roundtrip through parquet
3063        let src = [
3064            u32::MIN,
3065            1,
3066            (i32::MAX as u32) - 1,
3067            i32::MAX as u32,
3068            (i32::MAX as u32) + 1,
3069            u32::MAX - 1,
3070            u32::MAX,
3071        ];
3072        let values = Arc::new(UInt32Array::from_iter_values(src.iter().copied()));
3073        let files = RoundTripTest::new(values).with_nullable(false).run();
3074
3075        for file in files {
3076            // check statistics are valid
3077            let reader = SerializedFileReader::new(file).unwrap();
3078            let metadata = reader.metadata();
3079
3080            let mut row_offset = 0;
3081            for row_group in metadata.row_groups() {
3082                assert_eq!(row_group.num_columns(), 1);
3083                let column = row_group.column(0);
3084
3085                let num_values = column.num_values() as usize;
3086                let src_slice = &src[row_offset..row_offset + num_values];
3087                row_offset += column.num_values() as usize;
3088
3089                let stats = column.statistics().unwrap();
3090                if let Statistics::Int32(stats) = stats {
3091                    assert_eq!(
3092                        *stats.min_opt().unwrap() as u32,
3093                        *src_slice.iter().min().unwrap()
3094                    );
3095                    assert_eq!(
3096                        *stats.max_opt().unwrap() as u32,
3097                        *src_slice.iter().max().unwrap()
3098                    );
3099                } else {
3100                    panic!("Statistics::Int32 missing")
3101                }
3102            }
3103        }
3104    }
3105
3106    #[test]
3107    #[cfg_attr(miri, ignore)] // Takes too long
3108    fn u64_min_max() {
3109        // check values roundtrip through parquet
3110        let src = [
3111            u64::MIN,
3112            1,
3113            (i64::MAX as u64) - 1,
3114            i64::MAX as u64,
3115            (i64::MAX as u64) + 1,
3116            u64::MAX - 1,
3117            u64::MAX,
3118        ];
3119        let values = Arc::new(UInt64Array::from_iter_values(src.iter().copied()));
3120        let files = RoundTripTest::new(values).with_nullable(false).run();
3121
3122        for file in files {
3123            // check statistics are valid
3124            let reader = SerializedFileReader::new(file).unwrap();
3125            let metadata = reader.metadata();
3126
3127            let mut row_offset = 0;
3128            for row_group in metadata.row_groups() {
3129                assert_eq!(row_group.num_columns(), 1);
3130                let column = row_group.column(0);
3131
3132                let num_values = column.num_values() as usize;
3133                let src_slice = &src[row_offset..row_offset + num_values];
3134                row_offset += column.num_values() as usize;
3135
3136                let stats = column.statistics().unwrap();
3137                if let Statistics::Int64(stats) = stats {
3138                    assert_eq!(
3139                        *stats.min_opt().unwrap() as u64,
3140                        *src_slice.iter().min().unwrap()
3141                    );
3142                    assert_eq!(
3143                        *stats.max_opt().unwrap() as u64,
3144                        *src_slice.iter().max().unwrap()
3145                    );
3146                } else {
3147                    panic!("Statistics::Int64 missing")
3148                }
3149            }
3150        }
3151    }
3152
3153    #[test]
3154    #[cfg_attr(miri, ignore)] // Takes too long
3155    fn statistics_null_counts_only_nulls() {
3156        // check that null-count statistics for "only NULL"-columns are correct
3157        let values = Arc::new(UInt64Array::from(vec![None, None]));
3158        let files = RoundTripTest::new(values).run();
3159
3160        for file in files {
3161            // check statistics are valid
3162            let reader = SerializedFileReader::new(file).unwrap();
3163            let metadata = reader.metadata();
3164            assert_eq!(metadata.num_row_groups(), 1);
3165            let row_group = metadata.row_group(0);
3166            assert_eq!(row_group.num_columns(), 1);
3167            let column = row_group.column(0);
3168            let stats = column.statistics().unwrap();
3169            assert_eq!(stats.null_count_opt(), Some(2));
3170        }
3171    }
3172
3173    fn row_group_sizes(metadata: &ParquetMetaData) -> Vec<i64> {
3174        metadata.row_groups().iter().map(|x| x.num_rows()).collect()
3175    }
3176
3177    #[test]
3178    fn test_aggregates_records() {
3179        let arrays = [
3180            Int32Array::from((0..100).collect::<Vec<_>>()),
3181            Int32Array::from((0..50).collect::<Vec<_>>()),
3182            Int32Array::from((200..500).collect::<Vec<_>>()),
3183        ];
3184
3185        let schema = Arc::new(Schema::new(vec![Field::new(
3186            "int",
3187            ArrowDataType::Int32,
3188            false,
3189        )]));
3190
3191        let file = tempfile::tempfile().unwrap();
3192
3193        let props = WriterProperties::builder()
3194            .set_max_row_group_row_count(Some(200))
3195            .build();
3196
3197        let mut writer =
3198            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
3199
3200        for array in arrays {
3201            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
3202            writer.write(&batch).unwrap();
3203        }
3204
3205        writer.close().unwrap();
3206
3207        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
3208        assert_eq!(&row_group_sizes(builder.metadata()), &[200, 200, 50]);
3209
3210        let batches = builder
3211            .with_batch_size(100)
3212            .build()
3213            .unwrap()
3214            .collect::<ArrowResult<Vec<_>>>()
3215            .unwrap();
3216
3217        assert_eq!(batches.len(), 5);
3218        assert!(batches.iter().all(|x| x.num_columns() == 1));
3219
3220        let batch_sizes: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
3221
3222        assert_eq!(&batch_sizes, &[100, 100, 100, 100, 50]);
3223
3224        let values: Vec<_> = batches
3225            .iter()
3226            .flat_map(|x| {
3227                x.column(0)
3228                    .as_any()
3229                    .downcast_ref::<Int32Array>()
3230                    .unwrap()
3231                    .values()
3232                    .iter()
3233                    .copied()
3234            })
3235            .collect();
3236
3237        let expected_values: Vec<_> = [0..100, 0..50, 200..500].into_iter().flatten().collect();
3238        assert_eq!(&values, &expected_values)
3239    }
3240
3241    #[test]
3242    fn complex_aggregate() {
3243        // Tests aggregating nested data
3244        let field_a = Arc::new(Field::new("leaf_a", DataType::Int32, false));
3245        let field_b = Arc::new(Field::new("leaf_b", DataType::Int32, true));
3246        let struct_a = Arc::new(Field::new(
3247            "struct_a",
3248            DataType::Struct(vec![field_a.clone(), field_b.clone()].into()),
3249            true,
3250        ));
3251
3252        let list_a = Arc::new(Field::new("list", DataType::List(struct_a), true));
3253        let struct_b = Arc::new(Field::new(
3254            "struct_b",
3255            DataType::Struct(vec![list_a.clone()].into()),
3256            false,
3257        ));
3258
3259        let schema = Arc::new(Schema::new(vec![struct_b]));
3260
3261        // create nested data
3262        let field_a_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
3263        let field_b_array =
3264            Int32Array::from_iter(vec![Some(1), None, Some(2), None, None, Some(6)]);
3265
3266        let struct_a_array = StructArray::from(vec![
3267            (field_a.clone(), Arc::new(field_a_array) as ArrayRef),
3268            (field_b.clone(), Arc::new(field_b_array) as ArrayRef),
3269        ]);
3270
3271        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3272            .len(5)
3273            .add_buffer(Buffer::from_iter(vec![
3274                0_i32, 1_i32, 1_i32, 3_i32, 3_i32, 5_i32,
3275            ]))
3276            .null_bit_buffer(Some(Buffer::from_iter(vec![
3277                true, false, true, false, true,
3278            ])))
3279            .child_data(vec![struct_a_array.into_data()])
3280            .build()
3281            .unwrap();
3282
3283        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3284        let struct_b_array = StructArray::from(vec![(list_a.clone(), list_a_array)]);
3285
3286        let batch1 =
3287            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3288                .unwrap();
3289
3290        let field_a_array = Int32Array::from(vec![6, 7, 8, 9, 10]);
3291        let field_b_array = Int32Array::from_iter(vec![None, None, None, Some(1), None]);
3292
3293        let struct_a_array = StructArray::from(vec![
3294            (field_a, Arc::new(field_a_array) as ArrayRef),
3295            (field_b, Arc::new(field_b_array) as ArrayRef),
3296        ]);
3297
3298        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3299            .len(2)
3300            .add_buffer(Buffer::from_iter(vec![0_i32, 4_i32, 5_i32]))
3301            .child_data(vec![struct_a_array.into_data()])
3302            .build()
3303            .unwrap();
3304
3305        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3306        let struct_b_array = StructArray::from(vec![(list_a, list_a_array)]);
3307
3308        let batch2 =
3309            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3310                .unwrap();
3311
3312        let batches = &[batch1, batch2];
3313
3314        // Verify data is as expected
3315
3316        let expected = r"
3317            +-------------------------------------------------------------------------------------------------------+
3318            | struct_b                                                                                              |
3319            +-------------------------------------------------------------------------------------------------------+
3320            | {list: [{leaf_a: 1, leaf_b: 1}]}                                                                      |
3321            | {list: }                                                                                              |
3322            | {list: [{leaf_a: 2, leaf_b: }, {leaf_a: 3, leaf_b: 2}]}                                               |
3323            | {list: }                                                                                              |
3324            | {list: [{leaf_a: 4, leaf_b: }, {leaf_a: 5, leaf_b: }]}                                                |
3325            | {list: [{leaf_a: 6, leaf_b: }, {leaf_a: 7, leaf_b: }, {leaf_a: 8, leaf_b: }, {leaf_a: 9, leaf_b: 1}]} |
3326            | {list: [{leaf_a: 10, leaf_b: }]}                                                                      |
3327            +-------------------------------------------------------------------------------------------------------+
3328        ".trim().split('\n').map(|x| x.trim()).collect::<Vec<_>>().join("\n");
3329
3330        let actual = pretty_format_batches(batches).unwrap().to_string();
3331        assert_eq!(actual, expected);
3332
3333        // Write data
3334        let file = tempfile::tempfile().unwrap();
3335        let props = WriterProperties::builder()
3336            .set_max_row_group_row_count(Some(6))
3337            .build();
3338
3339        let mut writer =
3340            ArrowWriter::try_new(file.try_clone().unwrap(), schema, Some(props)).unwrap();
3341
3342        for batch in batches {
3343            writer.write(batch).unwrap();
3344        }
3345        writer.close().unwrap();
3346
3347        // Read Data
3348        // Should have written entire first batch and first row of second to the first row group
3349        // leaving a single row in the second row group
3350
3351        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
3352        assert_eq!(&row_group_sizes(builder.metadata()), &[6, 1]);
3353
3354        let batches = builder
3355            .with_batch_size(2)
3356            .build()
3357            .unwrap()
3358            .collect::<ArrowResult<Vec<_>>>()
3359            .unwrap();
3360
3361        assert_eq!(batches.len(), 4);
3362        let batch_counts: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
3363        assert_eq!(&batch_counts, &[2, 2, 2, 1]);
3364
3365        let actual = pretty_format_batches(&batches).unwrap().to_string();
3366        assert_eq!(actual, expected);
3367    }
3368
3369    #[test]
3370    fn test_arrow_writer_metadata() {
3371        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3372        let file_schema = batch_schema.clone().with_metadata([("foo", "bar")]);
3373
3374        let batch = RecordBatch::try_new(
3375            Arc::new(batch_schema),
3376            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3377        )
3378        .unwrap();
3379
3380        let mut buf = Vec::with_capacity(1024);
3381        let mut writer = ArrowWriter::try_new(&mut buf, Arc::new(file_schema), None).unwrap();
3382        writer.write(&batch).unwrap();
3383        writer.close().unwrap();
3384    }
3385
3386    #[test]
3387    fn in_progress_accounting() {
3388        // define schema
3389        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3390
3391        // create some data
3392        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3393
3394        // build a record batch
3395        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
3396
3397        let mut writer = ArrowWriter::try_new(vec![], batch.schema(), None).unwrap();
3398
3399        // starts empty
3400        assert_eq!(writer.in_progress_size(), 0);
3401        assert_eq!(writer.in_progress_rows(), 0);
3402        assert_eq!(writer.memory_size(), 0);
3403        assert_eq!(writer.bytes_written(), 4); // Initial header
3404        writer.write(&batch).unwrap();
3405
3406        // updated on write
3407        let initial_size = writer.in_progress_size();
3408        assert!(initial_size > 0);
3409        assert_eq!(writer.in_progress_rows(), 5);
3410        let initial_memory = writer.memory_size();
3411        assert!(initial_memory > 0);
3412        // memory estimate is larger than estimated encoded size
3413        assert!(
3414            initial_size <= initial_memory,
3415            "{initial_size} <= {initial_memory}"
3416        );
3417
3418        // updated on second write
3419        writer.write(&batch).unwrap();
3420        assert!(writer.in_progress_size() > initial_size);
3421        assert_eq!(writer.in_progress_rows(), 10);
3422        assert!(writer.memory_size() > initial_memory);
3423        assert!(
3424            writer.in_progress_size() <= writer.memory_size(),
3425            "in_progress_size {} <= memory_size {}",
3426            writer.in_progress_size(),
3427            writer.memory_size()
3428        );
3429
3430        // in progress tracking is cleared, but the overall data written is updated
3431        let pre_flush_bytes_written = writer.bytes_written();
3432        writer.flush().unwrap();
3433        assert_eq!(writer.in_progress_size(), 0);
3434        assert_eq!(writer.memory_size(), 0);
3435        assert!(writer.bytes_written() > pre_flush_bytes_written);
3436
3437        writer.close().unwrap();
3438    }
3439
3440    #[test]
3441    fn test_writer_all_null() {
3442        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3443        let b = Int32Array::new(vec![0; 5].into(), Some(NullBuffer::new_null(5)));
3444        let batch = RecordBatch::try_from_iter(vec![
3445            ("a", Arc::new(a) as ArrayRef),
3446            ("b", Arc::new(b) as ArrayRef),
3447        ])
3448        .unwrap();
3449
3450        let mut buf = Vec::with_capacity(1024);
3451        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
3452        writer.write(&batch).unwrap();
3453        writer.close().unwrap();
3454
3455        let bytes = Bytes::from(buf);
3456        let options = ReadOptionsBuilder::new().with_page_index().build();
3457        let reader = SerializedFileReader::new_with_options(bytes, options).unwrap();
3458        let index = reader.metadata().page_index().unwrap();
3459
3460        assert_eq!(index.num_data_pages(0, 0), Some(1)); // 1 page
3461        assert_eq!(index.num_data_pages(0, 1), Some(1)); // 1 page
3462    }
3463
3464    #[test]
3465    fn test_disabled_statistics_with_page() {
3466        let file_schema = Schema::new(vec![
3467            Field::new("a", DataType::Utf8, true),
3468            Field::new("b", DataType::Utf8, true),
3469        ]);
3470        let file_schema = Arc::new(file_schema);
3471
3472        let batch = RecordBatch::try_new(
3473            file_schema.clone(),
3474            vec![
3475                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
3476                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
3477            ],
3478        )
3479        .unwrap();
3480
3481        let props = WriterProperties::builder()
3482            .set_statistics_enabled(EnabledStatistics::None)
3483            .set_column_statistics_enabled("a".into(), EnabledStatistics::Page)
3484            .build();
3485
3486        let mut buf = Vec::with_capacity(1024);
3487        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
3488        writer.write(&batch).unwrap();
3489
3490        let metadata = writer.close().unwrap();
3491        assert_eq!(metadata.num_row_groups(), 1);
3492        let row_group = metadata.row_group(0);
3493        assert_eq!(row_group.num_columns(), 2);
3494        // Column "a" has both offset and column index, as requested
3495        assert!(row_group.column(0).offset_index_offset().is_some());
3496        assert!(row_group.column(0).column_index_offset().is_some());
3497        // Column "b" should only have offset index
3498        assert!(row_group.column(1).offset_index_offset().is_some());
3499        assert!(row_group.column(1).column_index_offset().is_none());
3500
3501        let options = ReadOptionsBuilder::new().with_page_index().build();
3502        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
3503
3504        let row_group = reader.get_row_group(0).unwrap();
3505        let a_col = row_group.metadata().column(0);
3506        let b_col = row_group.metadata().column(1);
3507
3508        // Column chunk of column "a" should have chunk level statistics
3509        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
3510            let min = byte_array_stats.min_opt().unwrap();
3511            let max = byte_array_stats.max_opt().unwrap();
3512
3513            assert_eq!(min.as_bytes(), b"a");
3514            assert_eq!(max.as_bytes(), b"d");
3515        } else {
3516            panic!("expecting Statistics::ByteArray");
3517        }
3518
3519        // The column chunk for column "b" shouldn't have statistics
3520        assert!(b_col.statistics().is_none());
3521
3522        let page_index = reader.metadata().page_index().unwrap();
3523
3524        let a_idx = page_index.column_index(0, 0);
3525        assert!(
3526            matches!(a_idx, Some(ColumnIndexMetaData::BYTE_ARRAY(_))),
3527            "{a_idx:?}"
3528        );
3529        let b_idx = page_index.column_index(0, 1);
3530        assert!(b_idx.is_none(), "{b_idx:?}");
3531    }
3532
3533    #[test]
3534    fn test_disabled_statistics_with_chunk() {
3535        let file_schema = Schema::new(vec![
3536            Field::new("a", DataType::Utf8, true),
3537            Field::new("b", DataType::Utf8, true),
3538        ]);
3539        let file_schema = Arc::new(file_schema);
3540
3541        let batch = RecordBatch::try_new(
3542            file_schema.clone(),
3543            vec![
3544                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
3545                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
3546            ],
3547        )
3548        .unwrap();
3549
3550        let props = WriterProperties::builder()
3551            .set_statistics_enabled(EnabledStatistics::None)
3552            .set_column_statistics_enabled("a".into(), EnabledStatistics::Chunk)
3553            .build();
3554
3555        let mut buf = Vec::with_capacity(1024);
3556        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
3557        writer.write(&batch).unwrap();
3558
3559        let metadata = writer.close().unwrap();
3560        assert_eq!(metadata.num_row_groups(), 1);
3561        let row_group = metadata.row_group(0);
3562        assert_eq!(row_group.num_columns(), 2);
3563        // Column "a" should only have offset index
3564        assert!(row_group.column(0).offset_index_offset().is_some());
3565        assert!(row_group.column(0).column_index_offset().is_none());
3566        // Column "b" should only have offset index
3567        assert!(row_group.column(1).offset_index_offset().is_some());
3568        assert!(row_group.column(1).column_index_offset().is_none());
3569
3570        let options = ReadOptionsBuilder::new().with_page_index().build();
3571        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
3572
3573        let row_group = reader.get_row_group(0).unwrap();
3574        let a_col = row_group.metadata().column(0);
3575        let b_col = row_group.metadata().column(1);
3576
3577        // Column chunk of column "a" should have chunk level statistics
3578        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
3579            let min = byte_array_stats.min_opt().unwrap();
3580            let max = byte_array_stats.max_opt().unwrap();
3581
3582            assert_eq!(min.as_bytes(), b"a");
3583            assert_eq!(max.as_bytes(), b"d");
3584        } else {
3585            panic!("expecting Statistics::ByteArray");
3586        }
3587
3588        // The column chunk for column "b"  shouldn't have statistics
3589        assert!(b_col.statistics().is_none());
3590
3591        let page_index = reader.metadata().page_index().unwrap();
3592
3593        let a_idx = page_index.column_index(0, 0);
3594        assert!(a_idx.is_none(), "{a_idx:?}");
3595        let b_idx = page_index.column_index(0, 1);
3596        assert!(b_idx.is_none(), "{b_idx:?}");
3597    }
3598
3599    #[test]
3600    fn test_arrow_writer_skip_metadata() {
3601        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3602        let file_schema = Arc::new(batch_schema.clone());
3603
3604        let batch = RecordBatch::try_new(
3605            Arc::new(batch_schema),
3606            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3607        )
3608        .unwrap();
3609        let skip_options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
3610
3611        let mut buf = Vec::with_capacity(1024);
3612        let mut writer =
3613            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
3614        writer.write(&batch).unwrap();
3615        writer.close().unwrap();
3616
3617        let bytes = Bytes::from(buf);
3618        let reader_builder = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
3619        assert_eq!(file_schema, *reader_builder.schema());
3620        if let Some(key_value_metadata) = reader_builder
3621            .metadata()
3622            .file_metadata()
3623            .key_value_metadata()
3624        {
3625            assert!(
3626                !key_value_metadata
3627                    .iter()
3628                    .any(|kv| kv.key.as_str() == ARROW_SCHEMA_META_KEY)
3629            );
3630        }
3631    }
3632
3633    #[test]
3634    fn test_arrow_writer_skip_path_in_schema() {
3635        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3636        let file_schema = Arc::new(batch_schema.clone());
3637
3638        let batch = RecordBatch::try_new(
3639            Arc::new(batch_schema),
3640            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3641        )
3642        .unwrap();
3643
3644        // default options should still write path_in_schema
3645        let skip_options = ArrowWriterOptions::new();
3646
3647        let mut buf = Vec::with_capacity(1024);
3648        let mut writer =
3649            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
3650        writer.write(&batch).unwrap();
3651        writer.close().unwrap();
3652
3653        // override to not write path_in_schema
3654        let skip_options = ArrowWriterOptions::new().with_properties(
3655            WriterProperties::builder()
3656                .set_write_path_in_schema(false)
3657                .build(),
3658        );
3659
3660        let mut buf2 = Vec::with_capacity(1024);
3661        let mut writer =
3662            ArrowWriter::try_new_with_options(&mut buf2, file_schema.clone(), skip_options)
3663                .unwrap();
3664        writer.write(&batch).unwrap();
3665        writer.close().unwrap();
3666
3667        // buf2 should be a bit smaller due to lack of path_in_schema
3668        assert!(buf.len() > buf2.len());
3669    }
3670
3671    #[test]
3672    fn mismatched_schemas() {
3673        let batch_schema = Schema::new(vec![Field::new("count", DataType::Int32, false)]);
3674        let file_schema = Arc::new(Schema::new(vec![Field::new(
3675            "temperature",
3676            DataType::Float64,
3677            false,
3678        )]));
3679
3680        let batch = RecordBatch::try_new(
3681            Arc::new(batch_schema),
3682            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3683        )
3684        .unwrap();
3685
3686        let mut buf = Vec::with_capacity(1024);
3687        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
3688
3689        let err = writer.write(&batch).unwrap_err().to_string();
3690        assert_eq!(
3691            err,
3692            "Arrow: Incompatible type. Field 'temperature' has type Float64, array has type Int32"
3693        );
3694    }
3695
3696    #[test]
3697    fn test_page_stats_not_written_by_default() {
3698        let string_field = Field::new("a", DataType::Utf8, false);
3699        let schema = Schema::new(vec![string_field]);
3700        let raw_string_values = vec!["Blart Versenwald III"];
3701        let string_values = StringArray::from(raw_string_values.clone());
3702        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
3703
3704        let props = WriterProperties::builder()
3705            .set_statistics_enabled(EnabledStatistics::Page)
3706            .set_dictionary_enabled(false)
3707            .set_encoding(Encoding::PLAIN)
3708            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3709            .build();
3710
3711        let file = roundtrip_opts(&batch, props);
3712
3713        // read file and decode page headers
3714        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3715
3716        // decode first page header
3717        let first_page = &file[4..];
3718        let mut prot = ThriftSliceInputProtocol::new(first_page);
3719        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3720        let stats = hdr.data_page_header.unwrap().statistics;
3721
3722        assert!(stats.is_none());
3723    }
3724
3725    #[test]
3726    fn test_page_stats_when_enabled() {
3727        let string_field = Field::new("a", DataType::Utf8, false);
3728        let schema = Schema::new(vec![string_field]);
3729        let raw_string_values = vec!["Blart Versenwald III", "Andrew Lamb"];
3730        let string_values = StringArray::from(raw_string_values.clone());
3731        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
3732
3733        let props = WriterProperties::builder()
3734            .set_statistics_enabled(EnabledStatistics::Page)
3735            .set_dictionary_enabled(false)
3736            .set_encoding(Encoding::PLAIN)
3737            .set_write_page_header_statistics(true)
3738            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3739            .build();
3740
3741        let file = roundtrip_opts(&batch, props);
3742
3743        // read file and decode page headers
3744        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3745
3746        // decode first page header
3747        let first_page = &file[4..];
3748        let mut prot = ThriftSliceInputProtocol::new(first_page);
3749        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3750        let stats = hdr.data_page_header.unwrap().statistics;
3751
3752        let stats = stats.unwrap();
3753        // check that min/max were actually written to the page
3754        assert!(stats.is_max_value_exact.unwrap());
3755        assert!(stats.is_min_value_exact.unwrap());
3756        assert_eq!(stats.max_value.unwrap(), b"Blart Versenwald III");
3757        assert_eq!(stats.min_value.unwrap(), b"Andrew Lamb");
3758    }
3759
3760    #[test]
3761    fn test_page_stats_truncation() {
3762        let string_field = Field::new("a", DataType::Utf8, false);
3763        let binary_field = Field::new("b", DataType::Binary, false);
3764        let schema = Schema::new(vec![string_field, binary_field]);
3765
3766        let raw_string_values = vec!["Blart Versenwald III"];
3767        let raw_binary_values = [b"Blart Versenwald III".to_vec()];
3768        let raw_binary_value_refs = raw_binary_values
3769            .iter()
3770            .map(|x| x.as_slice())
3771            .collect::<Vec<_>>();
3772
3773        let string_values = StringArray::from(raw_string_values.clone());
3774        let binary_values = BinaryArray::from(raw_binary_value_refs);
3775        let batch = RecordBatch::try_new(
3776            Arc::new(schema),
3777            vec![Arc::new(string_values), Arc::new(binary_values)],
3778        )
3779        .unwrap();
3780
3781        let props = WriterProperties::builder()
3782            .set_statistics_truncate_length(Some(2))
3783            .set_dictionary_enabled(false)
3784            .set_encoding(Encoding::PLAIN)
3785            .set_write_page_header_statistics(true)
3786            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3787            .build();
3788
3789        let file = roundtrip_opts(&batch, props);
3790
3791        // read file and decode page headers
3792        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3793
3794        // decode first page header
3795        let first_page = &file[4..];
3796        let mut prot = ThriftSliceInputProtocol::new(first_page);
3797        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3798        let stats = hdr.data_page_header.unwrap().statistics;
3799        assert!(stats.is_some());
3800        let stats = stats.unwrap();
3801        // check that min/max were properly truncated
3802        assert!(!stats.is_max_value_exact.unwrap());
3803        assert!(!stats.is_min_value_exact.unwrap());
3804        assert_eq!(stats.max_value.unwrap(), b"Bm");
3805        assert_eq!(stats.min_value.unwrap(), b"Bl");
3806
3807        // check second page now
3808        let second_page = &prot.as_slice()[hdr.compressed_page_size as usize..];
3809        let mut prot = ThriftSliceInputProtocol::new(second_page);
3810        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3811        let stats = hdr.data_page_header.unwrap().statistics;
3812        assert!(stats.is_some());
3813        let stats = stats.unwrap();
3814        // check that min/max were properly truncated
3815        assert!(!stats.is_max_value_exact.unwrap());
3816        assert!(!stats.is_min_value_exact.unwrap());
3817        assert_eq!(stats.max_value.unwrap(), b"Bm");
3818        assert_eq!(stats.min_value.unwrap(), b"Bl");
3819    }
3820
3821    #[test]
3822    fn test_page_encoding_statistics_roundtrip() {
3823        let batch_schema = Schema::new(vec![Field::new(
3824            "int32",
3825            arrow_schema::DataType::Int32,
3826            false,
3827        )]);
3828
3829        let batch = RecordBatch::try_new(
3830            Arc::new(batch_schema.clone()),
3831            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3832        )
3833        .unwrap();
3834
3835        let mut file: File = tempfile::tempfile().unwrap();
3836        let mut writer = ArrowWriter::try_new(&mut file, Arc::new(batch_schema), None).unwrap();
3837        writer.write(&batch).unwrap();
3838        let file_metadata = writer.close().unwrap();
3839
3840        assert_eq!(file_metadata.num_row_groups(), 1);
3841        assert_eq!(file_metadata.row_group(0).num_columns(), 1);
3842        assert!(
3843            file_metadata
3844                .row_group(0)
3845                .column(0)
3846                .page_encoding_stats()
3847                .is_some()
3848        );
3849        let chunk_page_stats = file_metadata
3850            .row_group(0)
3851            .column(0)
3852            .page_encoding_stats()
3853            .unwrap();
3854
3855        // check that the read metadata is also correct
3856        let options = ReadOptionsBuilder::new()
3857            .with_page_index()
3858            .with_encoding_stats_as_mask(false)
3859            .build();
3860        let reader = SerializedFileReader::new_with_options(file, options).unwrap();
3861
3862        let rowgroup = reader.get_row_group(0).expect("row group missing");
3863        assert_eq!(rowgroup.num_columns(), 1);
3864        let column = rowgroup.metadata().column(0);
3865        assert!(column.page_encoding_stats().is_some());
3866        let file_page_stats = column.page_encoding_stats().unwrap();
3867        assert_eq!(chunk_page_stats, file_page_stats);
3868    }
3869
3870    #[test]
3871    #[cfg_attr(miri, ignore)] // Takes too long
3872    fn test_different_dict_page_size_limit() {
3873        let array = Arc::new(Int64Array::from_iter(0..1024 * 1024));
3874        let schema = Arc::new(Schema::new(vec![
3875            Field::new("col0", arrow_schema::DataType::Int64, false),
3876            Field::new("col1", arrow_schema::DataType::Int64, false),
3877        ]));
3878        let batch =
3879            arrow_array::RecordBatch::try_new(schema.clone(), vec![array.clone(), array]).unwrap();
3880
3881        let props = WriterProperties::builder()
3882            .set_dictionary_page_size_limit(1024 * 1024)
3883            .set_column_dictionary_page_size_limit(ColumnPath::from("col1"), 1024 * 1024 * 4)
3884            .build();
3885        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3886        writer.write(&batch).unwrap();
3887        let data = Bytes::from(writer.into_inner().unwrap());
3888
3889        let mut metadata = ParquetMetaDataReader::new();
3890        metadata.try_parse(&data).unwrap();
3891        let metadata = metadata.finish().unwrap();
3892        let col0_meta = metadata.row_group(0).column(0);
3893        let col1_meta = metadata.row_group(0).column(1);
3894
3895        let get_dict_page_size = move |meta: &ColumnChunkMetaData| {
3896            let mut reader =
3897                SerializedPageReader::new(Arc::new(data.clone()), meta, 0, None).unwrap();
3898            let page = reader.get_next_page().unwrap().unwrap();
3899            match page {
3900                Page::DictionaryPage { buf, .. } => buf.len(),
3901                _ => panic!("expected DictionaryPage"),
3902            }
3903        };
3904
3905        assert_eq!(get_dict_page_size(col0_meta), 1024 * 1024);
3906        assert_eq!(get_dict_page_size(col1_meta), 1024 * 1024 * 4);
3907    }
3908
3909    #[test]
3910    #[cfg_attr(miri, ignore)] // Takes too long
3911    fn test_arrow_writer_granular_mode_roundtrip() {
3912        // Granular mode subdivides chunks and writes more pages than the
3913        // default batched path. Make sure the data we write back is
3914        // bit-identical to what went in — page-count assertions elsewhere
3915        // only prove pages were cut, not that the encoded data is correct.
3916        //
3917        // Mix value sizes so that the cumulative-byte-budget cutoff
3918        // lands mid-chunk, exercising both batched and granular paths
3919        // within the same `write_batch_internal` call.
3920        let small = "tiny".to_string();
3921        let big = "x".repeat(64 * 1024);
3922        let strings: Vec<String> = (0..256)
3923            .map(|i| {
3924                if i % 16 == 0 {
3925                    big.clone()
3926                } else {
3927                    small.clone()
3928                }
3929            })
3930            .collect();
3931
3932        let schema = Arc::new(Schema::new(vec![Field::new(
3933            "col",
3934            ArrowDataType::Utf8,
3935            false,
3936        )]));
3937        let batch = RecordBatch::try_new(
3938            schema.clone(),
3939            vec![Arc::new(StringArray::from(strings.clone())) as _],
3940        )
3941        .unwrap();
3942
3943        let props = WriterProperties::builder()
3944            .set_dictionary_enabled(false)
3945            .set_data_page_size_limit(16 * 1024)
3946            .build();
3947        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3948        writer.write(&batch).unwrap();
3949        let data = Bytes::from(writer.into_inner().unwrap());
3950
3951        let mut reader = ParquetRecordBatchReader::try_new(data, 1024).unwrap();
3952        let read = reader.next().unwrap().unwrap();
3953        assert!(reader.next().is_none(), "expected one batch");
3954        let col = read
3955            .column(0)
3956            .as_any()
3957            .downcast_ref::<StringArray>()
3958            .unwrap();
3959        assert_eq!(col.len(), strings.len());
3960        for (i, expected) in strings.iter().enumerate() {
3961            assert_eq!(
3962                col.value(i),
3963                expected.as_str(),
3964                "value mismatch at index {i}"
3965            );
3966        }
3967    }
3968
3969    #[test]
3970    fn test_arrow_writer_all_null_string_column() {
3971        // The `LevelDataRef::value_count` Uniform branch with
3972        // `value != max_def` (entirely-null chunk) must return 0 so the
3973        // sub-batch sizer short-circuits to batch mode without trying
3974        // to estimate byte budgets for non-existent values.
3975        let num_rows = 1024;
3976        let schema = Arc::new(Schema::new(vec![Field::new(
3977            "col",
3978            ArrowDataType::Utf8,
3979            true,
3980        )]));
3981        let nulls: Vec<Option<&str>> = vec![None; num_rows];
3982        let batch = RecordBatch::try_new(
3983            schema.clone(),
3984            vec![Arc::new(StringArray::from(nulls)) as _],
3985        )
3986        .unwrap();
3987
3988        let props = WriterProperties::builder()
3989            .set_dictionary_enabled(false)
3990            .set_data_page_size_limit(16 * 1024)
3991            .build();
3992        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3993        writer.write(&batch).unwrap();
3994        let data = Bytes::from(writer.into_inner().unwrap());
3995
3996        // Re-parse the file: row group has one column, every row is
3997        // null, all data pages report `num_rows / page_count` rows.
3998        let mut metadata = ParquetMetaDataReader::new();
3999        metadata.try_parse(&data).unwrap();
4000        let metadata = metadata.finish().unwrap();
4001        let row_group = metadata.row_group(0);
4002        let col_meta = row_group.column(0);
4003        assert_eq!(row_group.num_rows() as usize, num_rows);
4004        // Statistics record `null_count = num_rows` — proves every value
4005        // was written as null.
4006        if let Some(stats) = col_meta.statistics() {
4007            assert_eq!(
4008                stats.null_count_opt().unwrap_or(0) as usize,
4009                num_rows,
4010                "expected all-null column to report null_count = num_rows"
4011            );
4012        }
4013
4014        let mut reader =
4015            SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap();
4016        let mut total_values = 0u32;
4017        while let Some(page) = reader.get_next_page().unwrap() {
4018            if matches!(page, Page::DataPage { .. } | Page::DataPageV2 { .. }) {
4019                total_values += page.num_values();
4020            }
4021        }
4022        assert_eq!(
4023            total_values as usize, num_rows,
4024            "expected every level position to be represented in some page"
4025        );
4026    }
4027
4028    struct WriteBatchesShape {
4029        num_batches: usize,
4030        rows_per_batch: usize,
4031        row_size: usize,
4032    }
4033
4034    /// Helper function to write batches with the provided `WriteBatchesShape` into an `ArrowWriter`
4035    fn write_batches(
4036        WriteBatchesShape {
4037            num_batches,
4038            rows_per_batch,
4039            row_size,
4040        }: WriteBatchesShape,
4041        props: WriterProperties,
4042    ) -> ParquetRecordBatchReaderBuilder<File> {
4043        let schema = Arc::new(Schema::new(vec![Field::new(
4044            "str",
4045            ArrowDataType::Utf8,
4046            false,
4047        )]));
4048        let file = tempfile::tempfile().unwrap();
4049        let mut writer =
4050            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4051
4052        for batch_idx in 0..num_batches {
4053            let strings: Vec<String> = (0..rows_per_batch)
4054                .map(|i| format!("{:0>width$}", batch_idx * 10 + i, width = row_size))
4055                .collect();
4056            let array = StringArray::from(strings);
4057            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
4058            writer.write(&batch).unwrap();
4059        }
4060        writer.close().unwrap();
4061        ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
4062    }
4063
4064    #[test]
4065    // When both limits are None, all data should go into a single row group
4066    fn test_row_group_limit_none_writes_single_row_group() {
4067        let props = WriterProperties::builder()
4068            .set_max_row_group_row_count(None)
4069            .set_max_row_group_bytes(None)
4070            .build();
4071
4072        let builder = write_batches(
4073            WriteBatchesShape {
4074                num_batches: 1,
4075                rows_per_batch: 1000,
4076                row_size: 4,
4077            },
4078            props,
4079        );
4080
4081        assert_eq!(
4082            &row_group_sizes(builder.metadata()),
4083            &[1000],
4084            "With no limits, all rows should be in a single row group"
4085        );
4086    }
4087
4088    #[test]
4089    // When only max_row_group_size is set, respect the row limit
4090    fn test_row_group_limit_rows_only() {
4091        let props = WriterProperties::builder()
4092            .set_max_row_group_row_count(Some(300))
4093            .set_max_row_group_bytes(None)
4094            .build();
4095
4096        let builder = write_batches(
4097            WriteBatchesShape {
4098                num_batches: 1,
4099                rows_per_batch: 1000,
4100                row_size: 4,
4101            },
4102            props,
4103        );
4104
4105        assert_eq!(
4106            &row_group_sizes(builder.metadata()),
4107            &[300, 300, 300, 100],
4108            "Row groups should be split by row count"
4109        );
4110    }
4111
4112    #[test]
4113    #[cfg_attr(miri, ignore)] // Takes too long
4114    // A row limit far smaller than the batch splits it many times over; the split must not
4115    // consume stack proportional to the number of row groups.
4116    fn test_row_group_limit_rows_only_many_splits() {
4117        let props = WriterProperties::builder()
4118            .set_max_row_group_row_count(Some(1))
4119            .set_max_row_group_bytes(None)
4120            .build();
4121
4122        let rows = 50_000;
4123        let builder = write_batches(
4124            WriteBatchesShape {
4125                num_batches: 1,
4126                rows_per_batch: rows,
4127                row_size: 4,
4128            },
4129            props,
4130        );
4131
4132        let sizes = row_group_sizes(builder.metadata());
4133        assert_eq!(sizes.len(), rows, "Every row should get its own row group");
4134        assert_eq!(
4135            sizes.iter().sum::<i64>(),
4136            rows as i64,
4137            "Total rows should be preserved"
4138        );
4139    }
4140
4141    #[test]
4142    // When only max_row_group_bytes is set, respect the byte limit
4143    fn test_row_group_limit_bytes_only() {
4144        let props = WriterProperties::builder()
4145            .set_max_row_group_row_count(None)
4146            // Set byte limit to approximately fit ~30 rows worth of data (~100 bytes each)
4147            .set_max_row_group_bytes(Some(3500))
4148            .build();
4149
4150        let builder = write_batches(
4151            WriteBatchesShape {
4152                num_batches: 10,
4153                rows_per_batch: 10,
4154                row_size: 100,
4155            },
4156            props,
4157        );
4158
4159        let sizes = row_group_sizes(builder.metadata());
4160
4161        assert!(
4162            sizes.len() > 1,
4163            "Should have multiple row groups due to byte limit, got {sizes:?}",
4164        );
4165
4166        let total_rows: i64 = sizes.iter().sum();
4167        assert_eq!(total_rows, 100, "Total rows should be preserved");
4168    }
4169
4170    #[test]
4171    // If an in-progress row group is already oversized, it should be flushed before writing more.
4172    fn test_row_group_limit_bytes_flushes_when_current_group_already_too_large() {
4173        let schema = Arc::new(Schema::new(vec![Field::new(
4174            "str",
4175            ArrowDataType::Utf8,
4176            false,
4177        )]));
4178        let file = tempfile::tempfile().unwrap();
4179
4180        // Start with no byte limit so we can intentionally build an oversized in-progress row group.
4181        let props = WriterProperties::builder()
4182            .set_max_row_group_row_count(None)
4183            .set_max_row_group_bytes(None)
4184            .build();
4185        let mut writer =
4186            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4187
4188        let first_array = StringArray::from(
4189            (0..10)
4190                .map(|i| format!("{i:0>100}"))
4191                .collect::<Vec<String>>(),
4192        );
4193        let first_batch =
4194            RecordBatch::try_new(schema.clone(), vec![Arc::new(first_array)]).unwrap();
4195        writer.write(&first_batch).unwrap();
4196        assert_eq!(writer.in_progress_rows(), 10);
4197
4198        // Tighten the limit below the current in-progress bytes to exercise:
4199        // `if current_bytes >= max_bytes { self.flush()?; ... }`
4200        writer.max_row_group_bytes = Some(1);
4201
4202        let second_array = StringArray::from(vec!["x".to_string()]);
4203        let second_batch =
4204            RecordBatch::try_new(schema.clone(), vec![Arc::new(second_array)]).unwrap();
4205        writer.write(&second_batch).unwrap();
4206        writer.close().unwrap();
4207        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
4208
4209        assert_eq!(
4210            &row_group_sizes(builder.metadata()),
4211            &[10, 1],
4212            "The second write should flush an oversized in-progress row group first",
4213        );
4214    }
4215
4216    #[test]
4217    // When both limits are set, the row limit triggers first
4218    fn test_row_group_limit_both_row_wins_single_batch() {
4219        let props = WriterProperties::builder()
4220            .set_max_row_group_row_count(Some(200)) // Will trigger at 200 rows
4221            .set_max_row_group_bytes(Some(1024 * 1024)) // 1MB - won't trigger for small int data
4222            .build();
4223
4224        let builder = write_batches(
4225            WriteBatchesShape {
4226                num_batches: 1,
4227                row_size: 4,
4228                rows_per_batch: 1000,
4229            },
4230            props,
4231        );
4232
4233        assert_eq!(
4234            &row_group_sizes(builder.metadata()),
4235            &[200, 200, 200, 200, 200],
4236            "Row limit should trigger before byte limit"
4237        );
4238    }
4239
4240    #[test]
4241    // When both limits are set, the row limit triggers first
4242    fn test_row_group_limit_both_row_wins_multiple_batches() {
4243        let props = WriterProperties::builder()
4244            .set_max_row_group_row_count(Some(5)) // Will trigger every 5 rows
4245            .set_max_row_group_bytes(Some(9999)) // Won't trigger
4246            .build();
4247
4248        let builder = write_batches(
4249            WriteBatchesShape {
4250                num_batches: 10,
4251                rows_per_batch: 10,
4252                row_size: 100,
4253            },
4254            props,
4255        );
4256
4257        assert_eq!(
4258            &row_group_sizes(builder.metadata()),
4259            &[5; 20],
4260            "Row limit should trigger before byte limit"
4261        );
4262    }
4263
4264    #[test]
4265    // When both limits are set, the byte limit triggers first
4266    fn test_row_group_limit_both_bytes_wins() {
4267        let props = WriterProperties::builder()
4268            .set_max_row_group_row_count(Some(1000)) // Won't trigger for 100 rows
4269            .set_max_row_group_bytes(Some(3500)) // Will trigger at ~30-35 rows
4270            .build();
4271
4272        let builder = write_batches(
4273            WriteBatchesShape {
4274                num_batches: 10,
4275                rows_per_batch: 10,
4276                row_size: 100,
4277            },
4278            props,
4279        );
4280
4281        let sizes = row_group_sizes(builder.metadata());
4282
4283        assert!(
4284            sizes.len() > 1,
4285            "Byte limit should trigger before row limit, got {sizes:?}",
4286        );
4287
4288        assert!(
4289            sizes.iter().all(|&s| s < 1000),
4290            "No row group should hit the row limit"
4291        );
4292
4293        let total_rows: i64 = sizes.iter().sum();
4294        assert_eq!(total_rows, 100, "Total rows should be preserved");
4295    }
4296
4297    #[test]
4298    // Both limits can apply to the same batch: the row limit trims it to 5 rows, and the
4299    // byte limit then trims those 5 down to 4.
4300    fn test_row_group_limit_both_apply_to_same_batch() {
4301        let props = WriterProperties::builder()
4302            .set_max_row_group_row_count(Some(15))
4303            .set_max_row_group_bytes(Some(1500))
4304            .build();
4305
4306        let builder = write_batches(
4307            WriteBatchesShape {
4308                num_batches: 2,
4309                rows_per_batch: 10,
4310                row_size: 100,
4311            },
4312            props,
4313        );
4314
4315        assert_eq!(
4316            &row_group_sizes(builder.metadata()),
4317            &[14, 6],
4318            "Byte limit should still apply to a batch the row limit already split"
4319        );
4320    }
4321
4322    #[test]
4323    fn arrow_column_chunk_close_mut_drops_column_index() {
4324        use crate::arrow::ArrowSchemaConverter;
4325        use crate::file::writer::SerializedFileWriter;
4326
4327        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
4328        let props = Arc::new(
4329            WriterProperties::builder()
4330                .set_statistics_enabled(EnabledStatistics::Page)
4331                .build(),
4332        );
4333        let parquet_schema = ArrowSchemaConverter::new()
4334            .with_coerce_types(props.coerce_types())
4335            .convert(&schema)
4336            .unwrap();
4337
4338        let mut buf = Vec::with_capacity(1024);
4339        let mut writer =
4340            SerializedFileWriter::new(&mut buf, parquet_schema.root_schema_ptr(), props.clone())
4341                .unwrap();
4342
4343        let factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
4344        let mut col_writers = factory.create_column_writers(0).unwrap();
4345        let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..64));
4346        for leaves in compute_leaves(schema.field(0), &arr).unwrap() {
4347            col_writers[0].write(&leaves).unwrap();
4348        }
4349        let mut chunk = col_writers.pop().unwrap().close().unwrap();
4350
4351        // Immutable accessor exposes the close result produced at close time.
4352        assert!(
4353            chunk.close().column_index.is_some(),
4354            "EnabledStatistics::Page should produce a column_index"
4355        );
4356
4357        // Mutable accessor lets callers drop the page-level index before append.
4358        chunk.close_mut().column_index = None;
4359        assert!(chunk.close().column_index.is_none());
4360
4361        let mut rg = writer.next_row_group().unwrap();
4362        chunk.append_to_row_group(&mut rg).unwrap();
4363        rg.close().unwrap();
4364        let file_meta = writer.close().unwrap();
4365
4366        // After dropping column_index, the resulting file records no column
4367        // index offset/length for this chunk.
4368        let cc = file_meta.row_group(0).column(0);
4369        assert!(cc.column_index_range().is_none());
4370    }
4371
4372    #[test]
4373    #[cfg_attr(miri, ignore)] // Takes too long
4374    fn test_number_distinct_values_exact_count() {
4375        // 50 distinct Int32 values repeated across 100k rows, with every 7th row null.
4376        // Nulls must not be counted as a distinct value.
4377        let cardinality = 50u32;
4378        let array: ArrayRef = Arc::new(Int32Array::from_iter((0..100_000u32).map(|i| {
4379            if i % 7 == 0 {
4380                None
4381            } else {
4382                Some((i % cardinality) as i32)
4383            }
4384        })));
4385        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, true)]));
4386        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
4387
4388        let props = WriterProperties::builder()
4389            .set_write_row_group_number_distinct_values(true)
4390            .build();
4391        let mut buf = Vec::new();
4392        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4393        writer.write(&batch).unwrap();
4394        let metadata = writer.close().unwrap();
4395
4396        let count = metadata
4397            .row_group(0)
4398            .column(0)
4399            .statistics()
4400            .and_then(|s| s.distinct_count_opt())
4401            .expect("distinct_count should be set");
4402        // Must equal cardinality exactly; nulls must not inflate the count.
4403        assert_eq!(count, cardinality as u64);
4404    }
4405
4406    #[test]
4407    fn test_number_distinct_values_view_types() {
4408        // 5 distinct values repeated across 30 rows, with every 4th row null.
4409        // Verifies Utf8View is counted correctly (BinaryView shares the same code path).
4410        let cardinality = 5u32;
4411        let distinct_strings = ["alpha", "beta", "gamma", "delta", "epsilon"];
4412
4413        let string_view_col: ArrayRef = Arc::new(StringViewArray::from_iter((0..30u32).map(|i| {
4414            if i % 4 == 0 {
4415                None
4416            } else {
4417                Some(distinct_strings[(i % cardinality) as usize])
4418            }
4419        })));
4420
4421        let schema = Arc::new(Schema::new(vec![Field::new(
4422            "string_view_col",
4423            DataType::Utf8View,
4424            true,
4425        )]));
4426        let batch = RecordBatch::try_new(schema, vec![string_view_col]).unwrap();
4427
4428        let props = WriterProperties::builder()
4429            .set_write_row_group_number_distinct_values(true)
4430            .build();
4431        let mut parquet_bytes = Vec::new();
4432        let mut writer =
4433            ArrowWriter::try_new(&mut parquet_bytes, batch.schema(), Some(props)).unwrap();
4434        writer.write(&batch).unwrap();
4435        let metadata = writer.close().unwrap();
4436
4437        let distinct_count = metadata
4438            .row_group(0)
4439            .column(0)
4440            .statistics()
4441            .and_then(|s| s.distinct_count_opt())
4442            .expect("distinct_count should be set for Utf8View column");
4443        assert_eq!(distinct_count, cardinality as u64);
4444    }
4445
4446    #[test]
4447    fn test_number_distinct_values_not_written_by_default() {
4448        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
4449        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)]));
4450        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
4451
4452        let mut buf = Vec::new();
4453        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
4454        writer.write(&batch).unwrap();
4455        let metadata = writer.close().unwrap();
4456
4457        let count = metadata
4458            .row_group(0)
4459            .column(0)
4460            .statistics()
4461            .and_then(|s| s.distinct_count_opt());
4462        assert!(count.is_none());
4463    }
4464
4465    #[test]
4466    fn test_dictionary_ndv_single_batch() {
4467        // Dictionary array with 3 distinct string values repeated many times.
4468        // NDV must equal the number of distinct values in the dictionary (3),
4469        // not the number of rows.
4470        let keys = Int32Array::from(vec![0, 1, 2, 0, 1, 2, 0, 1, 2]);
4471        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "bird"]));
4472        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4473
4474        let schema = Arc::new(Schema::new(vec![Field::new(
4475            "x",
4476            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4477            false,
4478        )]));
4479        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
4480
4481        let props = WriterProperties::builder()
4482            .set_write_row_group_number_distinct_values(true)
4483            .build();
4484        let mut buf = Vec::new();
4485        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4486        writer.write(&batch).unwrap();
4487        let metadata = writer.close().unwrap();
4488
4489        let count = metadata
4490            .row_group(0)
4491            .column(0)
4492            .statistics()
4493            .and_then(|s| s.distinct_count_opt())
4494            .expect("distinct_count should be set");
4495        assert_eq!(count, 3);
4496    }
4497
4498    #[test]
4499    fn test_dictionary_ndv_excludes_unreferenced_values() {
4500        // Keys only reference indices 0 and 1; value at index 2 ("unreferenced") should not
4501        // count toward NDV even though it appears in the dictionary's values array.
4502        let keys = Int32Array::from(vec![0, 1, 0, 1]);
4503        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "unreferenced"]));
4504        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4505
4506        let schema = Arc::new(Schema::new(vec![Field::new(
4507            "x",
4508            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4509            false,
4510        )]));
4511        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
4512
4513        let props = WriterProperties::builder()
4514            .set_write_row_group_number_distinct_values(true)
4515            .build();
4516        let mut buf = Vec::new();
4517        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4518        writer.write(&batch).unwrap();
4519        let metadata = writer.close().unwrap();
4520
4521        let count = metadata
4522            .row_group(0)
4523            .column(0)
4524            .statistics()
4525            .and_then(|s| s.distinct_count_opt())
4526            .expect("distinct_count should be set");
4527        assert_eq!(
4528            count, 2,
4529            "unreferenced dictionary values must not count toward NDV"
4530        );
4531    }
4532
4533    #[test]
4534    fn test_dictionary_ndv_across_batches_regression() {
4535        // Regression test for https://github.com/apache/arrow-rs/issues/11172.
4536        let make_dict_batch = |a: &str, b: &str| -> RecordBatch {
4537            let keys = Int32Array::from(vec![0, 1, 0, 1]);
4538            let values: ArrayRef = Arc::new(StringArray::from(vec![a, b]));
4539            let dict: ArrayRef =
4540                Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4541            let schema = Arc::new(Schema::new(vec![Field::new(
4542                "x",
4543                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4544                false,
4545            )]));
4546            RecordBatch::try_new(schema, vec![dict]).unwrap()
4547        };
4548
4549        // batch1: dict = ["cat", "dog"], batch2: dict = ["fish", "cat"]
4550        // Distinct values across both batches: "cat", "dog", "fish" NDV = 3
4551        let batch1 = make_dict_batch("cat", "dog");
4552        let batch2 = make_dict_batch("fish", "cat");
4553
4554        let props = WriterProperties::builder()
4555            .set_write_row_group_number_distinct_values(true)
4556            .build();
4557        let mut buf = Vec::new();
4558        let mut writer = ArrowWriter::try_new(&mut buf, batch1.schema(), Some(props)).unwrap();
4559        writer.write(&batch1).unwrap();
4560        writer.write(&batch2).unwrap();
4561        let metadata = writer.close().unwrap();
4562
4563        let count = metadata
4564            .row_group(0)
4565            .column(0)
4566            .statistics()
4567            .and_then(|s| s.distinct_count_opt())
4568            .expect("distinct_count should be set");
4569        assert_eq!(
4570            count, 3,
4571            "NDV should count distinct values, not distinct key indices"
4572        );
4573    }
4574
4575    #[test]
4576    fn ree_struct_with_ree_child() {
4577        // Struct with a REE string field and a REE int field — confirms
4578        // recursion visits every child and each collapses to the right leaf type.
4579        let run_ends = Int32Array::from(vec![2i32, 3, 5]);
4580
4581        let col_a: ArrayRef = Arc::new(
4582            RunArray::try_new(
4583                &run_ends,
4584                &StringArray::from(vec![Some("foo"), None, Some("bar")]),
4585            )
4586            .unwrap(),
4587        );
4588        let col_b: ArrayRef = Arc::new(
4589            RunArray::try_new(&run_ends, &Int32Array::from(vec![Some(1), None, Some(2)])).unwrap(),
4590        );
4591
4592        let struct_array: ArrayRef = Arc::new(StructArray::new(
4593            Fields::from(vec![
4594                Field::new("a", col_a.data_type().clone(), true),
4595                Field::new("b", col_b.data_type().clone(), true),
4596            ]),
4597            vec![col_a, col_b],
4598            None,
4599        ));
4600
4601        let schema = Arc::new(Schema::new(vec![Field::new(
4602            "row",
4603            struct_array.data_type().clone(),
4604            true,
4605        )]));
4606        let batch = RecordBatch::try_new(schema.clone(), vec![struct_array]).unwrap();
4607
4608        let mut buf = Vec::new();
4609        let mut writer = ArrowWriter::try_new(&mut buf, schema, None).unwrap();
4610        writer.write(&batch).unwrap();
4611        let metadata = writer.close().unwrap();
4612
4613        let parquet_schema = metadata.file_metadata().schema_descr();
4614        assert_eq!(parquet_schema.num_columns(), 2);
4615        assert_eq!(
4616            parquet_schema.column(0).physical_type(),
4617            crate::basic::Type::BYTE_ARRAY
4618        );
4619        assert_eq!(parquet_schema.column(0).path().string(), "row.a");
4620        assert_eq!(
4621            parquet_schema.column(1).physical_type(),
4622            crate::basic::Type::INT32
4623        );
4624        assert_eq!(parquet_schema.column(1).path().string(), "row.b");
4625    }
4626}