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    fn get_bytes_after_close(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2334        let mut buffer = vec![];
2335
2336        let mut writer = ArrowWriter::try_new(&mut buffer, schema, None).unwrap();
2337        writer.write(expected_batch).unwrap();
2338        writer.close().unwrap();
2339
2340        buffer
2341    }
2342
2343    fn get_bytes_by_into_inner(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2344        let mut writer = ArrowWriter::try_new(Vec::new(), schema, None).unwrap();
2345        writer.write(expected_batch).unwrap();
2346        writer.into_inner().unwrap()
2347    }
2348
2349    #[test]
2350    fn roundtrip_bytes() {
2351        // define schema
2352        let schema = Arc::new(Schema::new(vec![
2353            Field::new("a", DataType::Int32, false),
2354            Field::new("b", DataType::Int32, true),
2355        ]));
2356
2357        // create some data
2358        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2359        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2360
2361        // build a record batch
2362        let expected_batch =
2363            RecordBatch::try_new(schema.clone(), vec![Arc::new(a), Arc::new(b)]).unwrap();
2364
2365        for buffer in [
2366            get_bytes_after_close(schema.clone(), &expected_batch),
2367            get_bytes_by_into_inner(schema, &expected_batch),
2368        ] {
2369            let cursor = Bytes::from(buffer);
2370            let mut record_batch_reader = ParquetRecordBatchReader::try_new(cursor, 1024).unwrap();
2371
2372            let actual_batch = record_batch_reader
2373                .next()
2374                .expect("No batch found")
2375                .expect("Unable to get batch");
2376
2377            assert_eq!(expected_batch.schema(), actual_batch.schema());
2378            assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
2379            assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
2380            for i in 0..expected_batch.num_columns() {
2381                let expected_data = expected_batch.column(i).to_data();
2382                let actual_data = actual_batch.column(i).to_data();
2383
2384                assert_eq!(expected_data, actual_data);
2385            }
2386        }
2387    }
2388
2389    #[test]
2390    fn arrow_writer_page_size() {
2391        let schema = Arc::new(Schema::new(vec![Field::new("col", DataType::Utf8, false)]));
2392
2393        let mut builder = StringBuilder::with_capacity(100, 329 * 10_000);
2394
2395        // Generate an array of 10 unique 10 character string
2396        for i in 0..10 {
2397            let value = i
2398                .to_string()
2399                .repeat(10)
2400                .chars()
2401                .take(10)
2402                .collect::<String>();
2403
2404            builder.append_value(value);
2405        }
2406
2407        let array = Arc::new(builder.finish());
2408
2409        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
2410
2411        let file = tempfile::tempfile().unwrap();
2412
2413        // Set everything very low so we fallback to PLAIN encoding after the first row
2414        let props = WriterProperties::builder()
2415            .set_data_page_size_limit(1)
2416            .set_dictionary_page_size_limit(1)
2417            .set_write_batch_size(1)
2418            .build();
2419
2420        let mut writer =
2421            ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), Some(props))
2422                .expect("Unable to write file");
2423        writer.write(&batch).unwrap();
2424        writer.close().unwrap();
2425
2426        let options = ReadOptionsBuilder::new().with_page_index().build();
2427        let reader =
2428            SerializedFileReader::new_with_options(file.try_clone().unwrap(), options).unwrap();
2429
2430        let column = reader.metadata().row_group(0).columns();
2431
2432        assert_eq!(column.len(), 1);
2433
2434        // We should write one row before falling back to PLAIN encoding so there should still be a
2435        // dictionary page.
2436        assert!(
2437            column[0].dictionary_page_offset().is_some(),
2438            "Expected a dictionary page"
2439        );
2440
2441        let page_index = reader
2442            .metadata()
2443            .page_index()
2444            .expect("page index should be present");
2445        let page_locations = page_index
2446            .page_locations(0, 0)
2447            .expect("page locations should exist");
2448
2449        // We should fallback to PLAIN encoding after the first row and our max page size is 1 bytes
2450        // so we expect one dictionary encoded page and then a page per row thereafter.
2451        assert_eq!(
2452            page_locations.len(),
2453            10,
2454            "Expected 10 pages but got {page_locations:#?}"
2455        );
2456    }
2457
2458    const MEDIUM_SIZE: usize = 63;
2459
2460    fn check_bloom_filter<T: AsBytes>(
2461        files: Vec<Bytes>,
2462        file_column: String,
2463        positive_values: Vec<T>,
2464        negative_values: Vec<T>,
2465    ) {
2466        files.into_iter().take(1).for_each(|file| {
2467            let file_reader = SerializedFileReader::new_with_options(
2468                file,
2469                ReadOptionsBuilder::new()
2470                    .with_reader_properties(
2471                        ReaderProperties::builder()
2472                            .set_read_bloom_filter(true)
2473                            .build(),
2474                    )
2475                    .build(),
2476            )
2477            .expect("Unable to open file as Parquet");
2478            let metadata = file_reader.metadata();
2479
2480            // Gets bloom filters from all row groups.
2481            let mut bloom_filters: Vec<_> = vec![];
2482            for (ri, row_group) in metadata.row_groups().iter().enumerate() {
2483                if let Some((column_index, _)) = row_group
2484                    .columns()
2485                    .iter()
2486                    .enumerate()
2487                    .find(|(_, column)| column.column_path().string() == file_column)
2488                {
2489                    let row_group_reader = file_reader
2490                        .get_row_group(ri)
2491                        .expect("Unable to read row group");
2492                    if let Some(sbbf) = row_group_reader.get_column_bloom_filter(column_index) {
2493                        bloom_filters.push(sbbf.clone());
2494                    } else {
2495                        panic!("No bloom filter for column named {file_column} found");
2496                    }
2497                } else {
2498                    panic!("No column named {file_column} found");
2499                }
2500            }
2501
2502            positive_values.iter().for_each(|value| {
2503                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
2504                assert!(
2505                    found.is_some(),
2506                    "{}",
2507                    format!("Value {:?} should be in bloom filter", value.as_bytes())
2508                );
2509            });
2510
2511            negative_values.iter().for_each(|value| {
2512                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
2513                assert!(
2514                    found.is_none(),
2515                    "{}",
2516                    format!("Value {:?} should not be in bloom filter", value.as_bytes())
2517                );
2518            });
2519        });
2520    }
2521
2522    #[test]
2523    #[cfg_attr(miri, ignore)] // Takes too long
2524    fn bool_large_single_column() {
2525        let values = Arc::new(
2526            [None, Some(true), Some(false)]
2527                .iter()
2528                .cycle()
2529                .copied()
2530                .take(200_000)
2531                .collect::<BooleanArray>(),
2532        );
2533        let schema = Schema::new(vec![Field::new("col", values.data_type().clone(), true)]);
2534        let expected_batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
2535        let file = tempfile::tempfile().unwrap();
2536
2537        let mut writer =
2538            ArrowWriter::try_new(file.try_clone().unwrap(), expected_batch.schema(), None)
2539                .expect("Unable to write file");
2540        writer.write(&expected_batch).unwrap();
2541        writer.close().unwrap();
2542    }
2543
2544    #[test]
2545    fn check_page_offset_index_with_nan() {
2546        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
2547        let schema = Schema::new(vec![Field::new("col", DataType::Float64, true)]);
2548        let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
2549
2550        let mut out = Vec::with_capacity(1024);
2551        let mut writer =
2552            ArrowWriter::try_new(&mut out, batch.schema(), None).expect("Unable to write file");
2553        writer.write(&batch).unwrap();
2554        let file_meta_data = writer.close().unwrap();
2555        for row_group in file_meta_data.row_groups() {
2556            for column in row_group.columns() {
2557                assert!(column.offset_index_offset().is_some());
2558                assert!(column.offset_index_length().is_some());
2559                assert!(column.column_index_offset().is_some());
2560                assert!(column.column_index_length().is_some());
2561            }
2562        }
2563        if let Some(page_index) = file_meta_data.page_index() {
2564            for rg in 0..file_meta_data.num_row_groups() {
2565                for col in 0..file_meta_data.row_group(rg).num_columns() {
2566                    let idx = page_index
2567                        .column_index(rg, col)
2568                        .expect("column index should exist");
2569                    assert!(idx.nan_counts().is_some());
2570                    let ColumnIndexMetaData::DOUBLE(float_idx) = idx else {
2571                        panic!("expected double statistics")
2572                    };
2573                    for i in 0..idx.num_pages() as usize {
2574                        assert_eq!(float_idx.nan_count(i), Some(10));
2575                        assert_eq!(
2576                            f64::NAN.total_cmp(float_idx.min_value(i).unwrap()),
2577                            Ordering::Equal
2578                        );
2579                        assert_eq!(
2580                            f64::NAN.total_cmp(float_idx.max_value(i).unwrap()),
2581                            Ordering::Equal
2582                        );
2583                    }
2584                }
2585            }
2586        } else {
2587            panic!("page index should be present");
2588        }
2589    }
2590
2591    #[test]
2592    fn check_page_offset_index_with_mixed_nan() {
2593        let schema = Arc::new(Schema::new(vec![Field::new(
2594            "col",
2595            DataType::Float64,
2596            true,
2597        )]));
2598
2599        let mut out = Vec::with_capacity(1024);
2600        let props = WriterProperties::builder()
2601            .set_data_page_row_count_limit(10)
2602            .build();
2603        let mut writer = ArrowWriter::try_new(&mut out, schema.clone(), Some(props))
2604            .expect("Unable to write file");
2605
2606        // write a page of all NaN (since batch min and max are NaN, global min/max are NaN)
2607        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
2608        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2609        writer.write(&batch).unwrap();
2610
2611        // write a page of all -NaN (batch min/max is -NaN, should update global min to -NaN)
2612        let values = Arc::new(Float64Array::from(vec![-f64::NAN; 10]));
2613        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2614        writer.write(&batch).unwrap();
2615
2616        // write a page of all 0 (non-NaN should override global min/max, now 0/0)
2617        let values = Arc::new(Float64Array::from(vec![0_f64; 10]));
2618        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2619        writer.write(&batch).unwrap();
2620
2621        // write a mixed page (should now have min -1, max 1)
2622        let values = Arc::new(Float64Array::from(vec![
2623            -1.0,
2624            0.0,
2625            f64::NAN,
2626            -f64::NAN,
2627            1.0,
2628        ]));
2629        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2630        writer.write(&batch).unwrap();
2631
2632        let file_meta_data = writer.close().unwrap();
2633
2634        // check the column chunk stats are correct
2635        let col_stats = file_meta_data
2636            .row_group(0)
2637            .column(0)
2638            .statistics()
2639            .expect("missing column chunk statistics");
2640
2641        assert_eq!(col_stats.nan_count_opt(), Some(22));
2642        assert_eq!(col_stats.min_bytes_opt(), Some((-1.0f64).as_bytes()));
2643        assert_eq!(col_stats.max_bytes_opt(), Some(1.0f64.as_bytes()));
2644
2645        assert!(file_meta_data.page_index().is_some());
2646        let col_idx = &file_meta_data.page_index().unwrap().column_index(0, 0);
2647        assert_eq!(col_idx.as_ref().unwrap().num_pages(), 4);
2648
2649        // test each page
2650        let Some(ColumnIndexMetaData::DOUBLE(float_idx)) = col_idx else {
2651            panic!("expected double statistics")
2652        };
2653
2654        assert_eq!(float_idx.nan_counts, Some(vec![10, 10, 0, 2]));
2655        assert_eq!(
2656            f64::NAN.total_cmp(float_idx.min_value(0).unwrap()),
2657            Ordering::Equal
2658        );
2659        assert_eq!(
2660            f64::NAN.total_cmp(float_idx.max_value(0).unwrap()),
2661            Ordering::Equal
2662        );
2663        assert_eq!(
2664            (-f64::NAN).total_cmp(float_idx.min_value(1).unwrap()),
2665            Ordering::Equal
2666        );
2667        assert_eq!(
2668            (-f64::NAN).total_cmp(float_idx.max_value(1).unwrap()),
2669            Ordering::Equal
2670        );
2671        assert_eq!(float_idx.min_value(2), Some(&0.0));
2672        assert_eq!(float_idx.max_value(2), Some(&0.0));
2673        assert_eq!(float_idx.min_value(3), Some(&-1.0));
2674        assert_eq!(float_idx.max_value(3), Some(&1.0));
2675    }
2676
2677    #[test]
2678    #[should_panic(
2679        expected = "Attempting to write an Arrow interval type MonthDayNano to parquet that is not yet implemented"
2680    )]
2681    fn interval_month_day_nano_single_column() {
2682        required_and_optional::<IntervalMonthDayNanoArray, _>(vec![
2683            IntervalMonthDayNano::new(0, 1, 5),
2684            IntervalMonthDayNano::new(0, 3, 2),
2685            IntervalMonthDayNano::new(3, -2, -5),
2686            IntervalMonthDayNano::new(-200, 4, -1),
2687        ]);
2688    }
2689
2690    #[test]
2691    #[cfg_attr(miri, ignore)] // Takes too long
2692    fn i32_column_bloom_filter_at_end() {
2693        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2694        let files = RoundTripTest::new(array)
2695            .with_nullable(false)
2696            .with_bloom_filter(true)
2697            .with_bloom_filter_position(BloomFilterPosition::End)
2698            .run();
2699
2700        check_bloom_filter(
2701            files,
2702            "col".to_string(),
2703            (0..SMALL_SIZE as i32).collect(),
2704            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2705        );
2706    }
2707
2708    #[test]
2709    #[cfg_attr(miri, ignore)] // Takes too long
2710    fn i32_column_bloom_filter() {
2711        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2712        let files = RoundTripTest::new(array)
2713            .with_nullable(false)
2714            .with_bloom_filter(true)
2715            .run();
2716
2717        check_bloom_filter(
2718            files,
2719            "col".to_string(),
2720            (0..SMALL_SIZE as i32).collect(),
2721            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2722        );
2723    }
2724
2725    fn write_with_bloom_filter(array: ArrayRef, dictionary_page_size_limit: usize) -> Bytes {
2726        let schema = Arc::new(Schema::new(vec![Field::new(
2727            "col",
2728            array.data_type().clone(),
2729            false,
2730        )]));
2731        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
2732        let props = WriterProperties::builder()
2733            .set_dictionary_enabled(true)
2734            .set_dictionary_page_size_limit(dictionary_page_size_limit)
2735            .set_write_batch_size(256)
2736            .set_bloom_filter_enabled(true)
2737            .build();
2738        let mut buf = Vec::new();
2739        let mut writer = ArrowWriter::try_new(&mut buf, schema, Some(props)).unwrap();
2740        writer.write(&batch).unwrap();
2741        writer.close().unwrap();
2742        Bytes::from(buf)
2743    }
2744
2745    fn data_page_encoding_mask(file: &Bytes) -> EncodingMask {
2746        let metadata = ParquetMetaDataReader::new().parse_and_finish(file).unwrap();
2747        *metadata
2748            .row_group(0)
2749            .column(0)
2750            .page_encoding_stats_mask()
2751            .unwrap()
2752    }
2753
2754    /// While a column is dictionary encoded the bloom filter is populated from the dictionary
2755    /// when it is flushed, so a chunk that stays dictionary encoded must still contain every value.
2756    #[test]
2757    fn string_column_bloom_filter_populated_from_dictionary() {
2758        let values: Vec<String> = (0..2000).map(|i| format!("value-{}", i % 10)).collect();
2759        let array = Arc::new(StringArray::from_iter_values(&values));
2760        let file = write_with_bloom_filter(array, 1024 * 1024);
2761        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
2762
2763        check_bloom_filter(
2764            vec![file],
2765            "col".to_string(),
2766            (0..10).map(|i| format!("value-{i}").into_bytes()).collect(),
2767            (10..20)
2768                .map(|i| format!("value-{i}").into_bytes())
2769                .collect(),
2770        );
2771    }
2772
2773    /// After falling back from dictionary encoding the filter holds the dictionary's values
2774    /// and every value written plain afterwards.
2775    #[test]
2776    fn string_column_bloom_filter_across_dictionary_fallback() {
2777        let values: Vec<String> = (0..2000).map(|i| format!("value-{i}")).collect();
2778        let array = Arc::new(StringArray::from_iter_values(&values));
2779        let file = write_with_bloom_filter(array, 1024);
2780        let encodings = data_page_encoding_mask(&file);
2781        assert!(
2782            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
2783            "expected dictionary and plain data pages, got {encodings:?}"
2784        );
2785
2786        check_bloom_filter(
2787            vec![file],
2788            "col".to_string(),
2789            values.into_iter().map(String::into_bytes).collect(),
2790            (2000..2010)
2791                .map(|i| format!("value-{i}").into_bytes())
2792                .collect(),
2793        );
2794    }
2795
2796    #[test]
2797    fn i64_column_bloom_filter_populated_from_dictionary() {
2798        let array = Arc::new(Int64Array::from_iter_values((0..2000).map(|i| i % 10)));
2799        let file = write_with_bloom_filter(array, 1024 * 1024);
2800        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
2801
2802        check_bloom_filter(
2803            vec![file],
2804            "col".to_string(),
2805            (0..10i64).collect(),
2806            (10..20i64).collect(),
2807        );
2808    }
2809
2810    #[test]
2811    fn i64_column_bloom_filter_across_dictionary_fallback() {
2812        let array = Arc::new(Int64Array::from_iter_values(0..2000i64));
2813        let file = write_with_bloom_filter(array, 1024);
2814        let encodings = data_page_encoding_mask(&file);
2815        assert!(
2816            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
2817            "expected dictionary and plain data pages, got {encodings:?}"
2818        );
2819
2820        check_bloom_filter(
2821            vec![file],
2822            "col".to_string(),
2823            (0..2000i64).collect(),
2824            (2000..2010i64).collect(),
2825        );
2826    }
2827
2828    /// Test that bloom filter folding produces correct results even when
2829    /// the configured NDV differs significantly from actual NDV.
2830    /// A large NDV means a larger initial filter that gets folded down;
2831    /// a small NDV means a smaller initial filter.
2832    #[test]
2833    #[cfg_attr(miri, ignore)] // Takes too long
2834    fn i32_column_bloom_filter_fixed_ndv() {
2835        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2836
2837        // NDV much larger than actual distinct values — tests folding a large filter down
2838        let files = RoundTripTest::new(array.clone())
2839            .with_nullable(false)
2840            .with_bloom_filter(true)
2841            .with_bloom_filter_ndv(1_000_000)
2842            .run();
2843
2844        check_bloom_filter(
2845            files,
2846            "col".to_string(),
2847            (0..SMALL_SIZE as i32).collect(),
2848            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2849        );
2850
2851        // NDV smaller than actual distinct values — tests the underestimate path
2852        let files = RoundTripTest::new(array)
2853            .with_nullable(false)
2854            .with_bloom_filter(true)
2855            .with_bloom_filter_ndv(3)
2856            .run();
2857
2858        check_bloom_filter(
2859            files,
2860            "col".to_string(),
2861            (0..SMALL_SIZE as i32).collect(),
2862            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2863        );
2864    }
2865
2866    #[test]
2867    #[cfg_attr(miri, ignore)] // Takes too long
2868    fn binary_column_bloom_filter() {
2869        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
2870        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
2871        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
2872
2873        let array = Arc::new(BinaryArray::from_iter_values(many_vecs_iter));
2874        let files = RoundTripTest::new(array)
2875            .with_nullable(false)
2876            .with_bloom_filter(true)
2877            .run();
2878
2879        check_bloom_filter(
2880            files,
2881            "col".to_string(),
2882            many_vecs,
2883            vec![vec![(SMALL_SIZE + 1) as u8]],
2884        );
2885    }
2886
2887    #[test]
2888    #[cfg_attr(miri, ignore)] // Takes too long
2889    fn empty_string_null_column_bloom_filter() {
2890        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
2891        let raw_strs = raw_values.iter().map(|s| s.as_str());
2892
2893        let array = Arc::new(StringArray::from_iter_values(raw_strs));
2894        let files = RoundTripTest::new(array)
2895            .with_nullable(false)
2896            .with_bloom_filter(true)
2897            .run();
2898
2899        let optional_raw_values: Vec<_> = raw_values
2900            .iter()
2901            .enumerate()
2902            .filter_map(|(i, v)| if i % 2 == 0 { None } else { Some(v.as_str()) })
2903            .collect();
2904        // For null slots, empty string should not be in bloom filter.
2905        check_bloom_filter(files, "col".to_string(), optional_raw_values, vec![""]);
2906    }
2907
2908    #[test]
2909    fn list_and_map_coerced_names() {
2910        // Create map and list with non-Parquet naming
2911        let list_field =
2912            Field::new_list("my_list", Field::new("item", DataType::Int32, false), false);
2913        let map_field = Field::new_map(
2914            "my_map",
2915            "my_entries",
2916            Field::new("my_keys", DataType::Int32, false),
2917            Field::new("my_values", DataType::Int32, true),
2918            false,
2919            true,
2920        );
2921
2922        let list_array = create_random_array(&list_field, 100, 0.0, 0.0).unwrap();
2923        let map_array = create_random_array(&map_field, 100, 0.0, 0.0).unwrap();
2924
2925        let arrow_schema = Arc::new(Schema::new(vec![list_field, map_field]));
2926
2927        // Write data to Parquet but coerce names to match spec
2928        let props = Some(WriterProperties::builder().set_coerce_types(true).build());
2929        let file = tempfile::tempfile().unwrap();
2930        let mut writer =
2931            ArrowWriter::try_new(file.try_clone().unwrap(), arrow_schema.clone(), props).unwrap();
2932
2933        let batch = RecordBatch::try_new(arrow_schema, vec![list_array, map_array]).unwrap();
2934        writer.write(&batch).unwrap();
2935        let file_metadata = writer.close().unwrap();
2936
2937        let schema = file_metadata.file_metadata().schema();
2938        // Coerced name of "item" should be "element"
2939        let list_field = &schema.get_fields()[0].get_fields()[0];
2940        assert_eq!(list_field.get_fields()[0].name(), "element");
2941
2942        let map_field = &schema.get_fields()[1].get_fields()[0];
2943        // Coerced name of "entries" should be "key_value"
2944        assert_eq!(map_field.name(), "key_value");
2945        // Coerced name of "my_keys" should be "key"
2946        assert_eq!(map_field.get_fields()[0].name(), "key");
2947        // Coerced name of "my_values" should be "value"
2948        assert_eq!(map_field.get_fields()[1].name(), "value");
2949
2950        // Double check schema after reading from the file
2951        let reader = SerializedFileReader::new(file).unwrap();
2952        let file_schema = reader.metadata().file_metadata().schema();
2953        let fields = file_schema.get_fields();
2954        let list_field = &fields[0].get_fields()[0];
2955        assert_eq!(list_field.get_fields()[0].name(), "element");
2956        let map_field = &fields[1].get_fields()[0];
2957        assert_eq!(map_field.name(), "key_value");
2958        assert_eq!(map_field.get_fields()[0].name(), "key");
2959        assert_eq!(map_field.get_fields()[1].name(), "value");
2960    }
2961
2962    #[test]
2963    #[cfg_attr(miri, ignore)] // Takes too long
2964    fn fallback_flush_data_page() {
2965        //tests if the Fallback::flush_data_page clears all buffers correctly
2966        let raw_values: Vec<_> = (0..MEDIUM_SIZE).map(|i| i.to_string()).collect();
2967        let values = Arc::new(StringArray::from(raw_values));
2968        let encodings = vec![
2969            Encoding::DELTA_BYTE_ARRAY,
2970            Encoding::DELTA_LENGTH_BYTE_ARRAY,
2971        ];
2972        let data_type = values.data_type().clone();
2973        let schema = Arc::new(Schema::new(vec![Field::new("col", data_type, false)]));
2974        let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
2975
2976        let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
2977        let data_page_size_limit: usize = 32;
2978        let write_batch_size: usize = 16;
2979
2980        for encoding in &encodings {
2981            for row_group_size in row_group_sizes {
2982                let props = WriterProperties::builder()
2983                    .set_writer_version(WriterVersion::PARQUET_2_0)
2984                    .set_max_row_group_row_count(Some(row_group_size))
2985                    .set_dictionary_enabled(false)
2986                    .set_encoding(*encoding)
2987                    .set_data_page_size_limit(data_page_size_limit)
2988                    .set_write_batch_size(write_batch_size)
2989                    .build();
2990
2991                roundtrip_opts_with_array_validation(&expected_batch, props, |a, b| {
2992                    let string_array_a = StringArray::from(a.clone());
2993                    let string_array_b = StringArray::from(b.clone());
2994                    let vec_a: Vec<&str> = string_array_a.iter().map(|v| v.unwrap()).collect();
2995                    let vec_b: Vec<&str> = string_array_b.iter().map(|v| v.unwrap()).collect();
2996                    assert_eq!(
2997                        vec_a, vec_b,
2998                        "failed for encoder: {encoding:?} and row_group_size: {row_group_size:?}"
2999                    );
3000                });
3001            }
3002        }
3003    }
3004
3005    #[test]
3006    #[cfg_attr(miri, ignore)] // Takes too long
3007    fn u32_min_max() {
3008        // check values roundtrip through parquet
3009        let src = [
3010            u32::MIN,
3011            1,
3012            (i32::MAX as u32) - 1,
3013            i32::MAX as u32,
3014            (i32::MAX as u32) + 1,
3015            u32::MAX - 1,
3016            u32::MAX,
3017        ];
3018        let values = Arc::new(UInt32Array::from_iter_values(src.iter().copied()));
3019        let files = RoundTripTest::new(values).with_nullable(false).run();
3020
3021        for file in files {
3022            // check statistics are valid
3023            let reader = SerializedFileReader::new(file).unwrap();
3024            let metadata = reader.metadata();
3025
3026            let mut row_offset = 0;
3027            for row_group in metadata.row_groups() {
3028                assert_eq!(row_group.num_columns(), 1);
3029                let column = row_group.column(0);
3030
3031                let num_values = column.num_values() as usize;
3032                let src_slice = &src[row_offset..row_offset + num_values];
3033                row_offset += column.num_values() as usize;
3034
3035                let stats = column.statistics().unwrap();
3036                if let Statistics::Int32(stats) = stats {
3037                    assert_eq!(
3038                        *stats.min_opt().unwrap() as u32,
3039                        *src_slice.iter().min().unwrap()
3040                    );
3041                    assert_eq!(
3042                        *stats.max_opt().unwrap() as u32,
3043                        *src_slice.iter().max().unwrap()
3044                    );
3045                } else {
3046                    panic!("Statistics::Int32 missing")
3047                }
3048            }
3049        }
3050    }
3051
3052    #[test]
3053    #[cfg_attr(miri, ignore)] // Takes too long
3054    fn u64_min_max() {
3055        // check values roundtrip through parquet
3056        let src = [
3057            u64::MIN,
3058            1,
3059            (i64::MAX as u64) - 1,
3060            i64::MAX as u64,
3061            (i64::MAX as u64) + 1,
3062            u64::MAX - 1,
3063            u64::MAX,
3064        ];
3065        let values = Arc::new(UInt64Array::from_iter_values(src.iter().copied()));
3066        let files = RoundTripTest::new(values).with_nullable(false).run();
3067
3068        for file in files {
3069            // check statistics are valid
3070            let reader = SerializedFileReader::new(file).unwrap();
3071            let metadata = reader.metadata();
3072
3073            let mut row_offset = 0;
3074            for row_group in metadata.row_groups() {
3075                assert_eq!(row_group.num_columns(), 1);
3076                let column = row_group.column(0);
3077
3078                let num_values = column.num_values() as usize;
3079                let src_slice = &src[row_offset..row_offset + num_values];
3080                row_offset += column.num_values() as usize;
3081
3082                let stats = column.statistics().unwrap();
3083                if let Statistics::Int64(stats) = stats {
3084                    assert_eq!(
3085                        *stats.min_opt().unwrap() as u64,
3086                        *src_slice.iter().min().unwrap()
3087                    );
3088                    assert_eq!(
3089                        *stats.max_opt().unwrap() as u64,
3090                        *src_slice.iter().max().unwrap()
3091                    );
3092                } else {
3093                    panic!("Statistics::Int64 missing")
3094                }
3095            }
3096        }
3097    }
3098
3099    #[test]
3100    #[cfg_attr(miri, ignore)] // Takes too long
3101    fn statistics_null_counts_only_nulls() {
3102        // check that null-count statistics for "only NULL"-columns are correct
3103        let values = Arc::new(UInt64Array::from(vec![None, None]));
3104        let files = RoundTripTest::new(values).run();
3105
3106        for file in files {
3107            // check statistics are valid
3108            let reader = SerializedFileReader::new(file).unwrap();
3109            let metadata = reader.metadata();
3110            assert_eq!(metadata.num_row_groups(), 1);
3111            let row_group = metadata.row_group(0);
3112            assert_eq!(row_group.num_columns(), 1);
3113            let column = row_group.column(0);
3114            let stats = column.statistics().unwrap();
3115            assert_eq!(stats.null_count_opt(), Some(2));
3116        }
3117    }
3118
3119    fn row_group_sizes(metadata: &ParquetMetaData) -> Vec<i64> {
3120        metadata.row_groups().iter().map(|x| x.num_rows()).collect()
3121    }
3122
3123    #[test]
3124    fn test_aggregates_records() {
3125        let arrays = [
3126            Int32Array::from((0..100).collect::<Vec<_>>()),
3127            Int32Array::from((0..50).collect::<Vec<_>>()),
3128            Int32Array::from((200..500).collect::<Vec<_>>()),
3129        ];
3130
3131        let schema = Arc::new(Schema::new(vec![Field::new(
3132            "int",
3133            ArrowDataType::Int32,
3134            false,
3135        )]));
3136
3137        let file = tempfile::tempfile().unwrap();
3138
3139        let props = WriterProperties::builder()
3140            .set_max_row_group_row_count(Some(200))
3141            .build();
3142
3143        let mut writer =
3144            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
3145
3146        for array in arrays {
3147            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
3148            writer.write(&batch).unwrap();
3149        }
3150
3151        writer.close().unwrap();
3152
3153        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
3154        assert_eq!(&row_group_sizes(builder.metadata()), &[200, 200, 50]);
3155
3156        let batches = builder
3157            .with_batch_size(100)
3158            .build()
3159            .unwrap()
3160            .collect::<ArrowResult<Vec<_>>>()
3161            .unwrap();
3162
3163        assert_eq!(batches.len(), 5);
3164        assert!(batches.iter().all(|x| x.num_columns() == 1));
3165
3166        let batch_sizes: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
3167
3168        assert_eq!(&batch_sizes, &[100, 100, 100, 100, 50]);
3169
3170        let values: Vec<_> = batches
3171            .iter()
3172            .flat_map(|x| {
3173                x.column(0)
3174                    .as_any()
3175                    .downcast_ref::<Int32Array>()
3176                    .unwrap()
3177                    .values()
3178                    .iter()
3179                    .copied()
3180            })
3181            .collect();
3182
3183        let expected_values: Vec<_> = [0..100, 0..50, 200..500].into_iter().flatten().collect();
3184        assert_eq!(&values, &expected_values)
3185    }
3186
3187    #[test]
3188    fn complex_aggregate() {
3189        // Tests aggregating nested data
3190        let field_a = Arc::new(Field::new("leaf_a", DataType::Int32, false));
3191        let field_b = Arc::new(Field::new("leaf_b", DataType::Int32, true));
3192        let struct_a = Arc::new(Field::new(
3193            "struct_a",
3194            DataType::Struct(vec![field_a.clone(), field_b.clone()].into()),
3195            true,
3196        ));
3197
3198        let list_a = Arc::new(Field::new("list", DataType::List(struct_a), true));
3199        let struct_b = Arc::new(Field::new(
3200            "struct_b",
3201            DataType::Struct(vec![list_a.clone()].into()),
3202            false,
3203        ));
3204
3205        let schema = Arc::new(Schema::new(vec![struct_b]));
3206
3207        // create nested data
3208        let field_a_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
3209        let field_b_array =
3210            Int32Array::from_iter(vec![Some(1), None, Some(2), None, None, Some(6)]);
3211
3212        let struct_a_array = StructArray::from(vec![
3213            (field_a.clone(), Arc::new(field_a_array) as ArrayRef),
3214            (field_b.clone(), Arc::new(field_b_array) as ArrayRef),
3215        ]);
3216
3217        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3218            .len(5)
3219            .add_buffer(Buffer::from_iter(vec![
3220                0_i32, 1_i32, 1_i32, 3_i32, 3_i32, 5_i32,
3221            ]))
3222            .null_bit_buffer(Some(Buffer::from_iter(vec![
3223                true, false, true, false, true,
3224            ])))
3225            .child_data(vec![struct_a_array.into_data()])
3226            .build()
3227            .unwrap();
3228
3229        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3230        let struct_b_array = StructArray::from(vec![(list_a.clone(), list_a_array)]);
3231
3232        let batch1 =
3233            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3234                .unwrap();
3235
3236        let field_a_array = Int32Array::from(vec![6, 7, 8, 9, 10]);
3237        let field_b_array = Int32Array::from_iter(vec![None, None, None, Some(1), None]);
3238
3239        let struct_a_array = StructArray::from(vec![
3240            (field_a, Arc::new(field_a_array) as ArrayRef),
3241            (field_b, Arc::new(field_b_array) as ArrayRef),
3242        ]);
3243
3244        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3245            .len(2)
3246            .add_buffer(Buffer::from_iter(vec![0_i32, 4_i32, 5_i32]))
3247            .child_data(vec![struct_a_array.into_data()])
3248            .build()
3249            .unwrap();
3250
3251        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3252        let struct_b_array = StructArray::from(vec![(list_a, list_a_array)]);
3253
3254        let batch2 =
3255            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3256                .unwrap();
3257
3258        let batches = &[batch1, batch2];
3259
3260        // Verify data is as expected
3261
3262        let expected = r"
3263            +-------------------------------------------------------------------------------------------------------+
3264            | struct_b                                                                                              |
3265            +-------------------------------------------------------------------------------------------------------+
3266            | {list: [{leaf_a: 1, leaf_b: 1}]}                                                                      |
3267            | {list: }                                                                                              |
3268            | {list: [{leaf_a: 2, leaf_b: }, {leaf_a: 3, leaf_b: 2}]}                                               |
3269            | {list: }                                                                                              |
3270            | {list: [{leaf_a: 4, leaf_b: }, {leaf_a: 5, leaf_b: }]}                                                |
3271            | {list: [{leaf_a: 6, leaf_b: }, {leaf_a: 7, leaf_b: }, {leaf_a: 8, leaf_b: }, {leaf_a: 9, leaf_b: 1}]} |
3272            | {list: [{leaf_a: 10, leaf_b: }]}                                                                      |
3273            +-------------------------------------------------------------------------------------------------------+
3274        ".trim().split('\n').map(|x| x.trim()).collect::<Vec<_>>().join("\n");
3275
3276        let actual = pretty_format_batches(batches).unwrap().to_string();
3277        assert_eq!(actual, expected);
3278
3279        // Write data
3280        let file = tempfile::tempfile().unwrap();
3281        let props = WriterProperties::builder()
3282            .set_max_row_group_row_count(Some(6))
3283            .build();
3284
3285        let mut writer =
3286            ArrowWriter::try_new(file.try_clone().unwrap(), schema, Some(props)).unwrap();
3287
3288        for batch in batches {
3289            writer.write(batch).unwrap();
3290        }
3291        writer.close().unwrap();
3292
3293        // Read Data
3294        // Should have written entire first batch and first row of second to the first row group
3295        // leaving a single row in the second row group
3296
3297        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
3298        assert_eq!(&row_group_sizes(builder.metadata()), &[6, 1]);
3299
3300        let batches = builder
3301            .with_batch_size(2)
3302            .build()
3303            .unwrap()
3304            .collect::<ArrowResult<Vec<_>>>()
3305            .unwrap();
3306
3307        assert_eq!(batches.len(), 4);
3308        let batch_counts: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
3309        assert_eq!(&batch_counts, &[2, 2, 2, 1]);
3310
3311        let actual = pretty_format_batches(&batches).unwrap().to_string();
3312        assert_eq!(actual, expected);
3313    }
3314
3315    #[test]
3316    fn test_arrow_writer_metadata() {
3317        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3318        let file_schema = batch_schema.clone().with_metadata([("foo", "bar")]);
3319
3320        let batch = RecordBatch::try_new(
3321            Arc::new(batch_schema),
3322            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3323        )
3324        .unwrap();
3325
3326        let mut buf = Vec::with_capacity(1024);
3327        let mut writer = ArrowWriter::try_new(&mut buf, Arc::new(file_schema), None).unwrap();
3328        writer.write(&batch).unwrap();
3329        writer.close().unwrap();
3330    }
3331
3332    #[test]
3333    fn in_progress_accounting() {
3334        // define schema
3335        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3336
3337        // create some data
3338        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3339
3340        // build a record batch
3341        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
3342
3343        let mut writer = ArrowWriter::try_new(vec![], batch.schema(), None).unwrap();
3344
3345        // starts empty
3346        assert_eq!(writer.in_progress_size(), 0);
3347        assert_eq!(writer.in_progress_rows(), 0);
3348        assert_eq!(writer.memory_size(), 0);
3349        assert_eq!(writer.bytes_written(), 4); // Initial header
3350        writer.write(&batch).unwrap();
3351
3352        // updated on write
3353        let initial_size = writer.in_progress_size();
3354        assert!(initial_size > 0);
3355        assert_eq!(writer.in_progress_rows(), 5);
3356        let initial_memory = writer.memory_size();
3357        assert!(initial_memory > 0);
3358        // memory estimate is larger than estimated encoded size
3359        assert!(
3360            initial_size <= initial_memory,
3361            "{initial_size} <= {initial_memory}"
3362        );
3363
3364        // updated on second write
3365        writer.write(&batch).unwrap();
3366        assert!(writer.in_progress_size() > initial_size);
3367        assert_eq!(writer.in_progress_rows(), 10);
3368        assert!(writer.memory_size() > initial_memory);
3369        assert!(
3370            writer.in_progress_size() <= writer.memory_size(),
3371            "in_progress_size {} <= memory_size {}",
3372            writer.in_progress_size(),
3373            writer.memory_size()
3374        );
3375
3376        // in progress tracking is cleared, but the overall data written is updated
3377        let pre_flush_bytes_written = writer.bytes_written();
3378        writer.flush().unwrap();
3379        assert_eq!(writer.in_progress_size(), 0);
3380        assert_eq!(writer.memory_size(), 0);
3381        assert!(writer.bytes_written() > pre_flush_bytes_written);
3382
3383        writer.close().unwrap();
3384    }
3385
3386    #[test]
3387    fn test_writer_all_null() {
3388        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3389        let b = Int32Array::new(vec![0; 5].into(), Some(NullBuffer::new_null(5)));
3390        let batch = RecordBatch::try_from_iter(vec![
3391            ("a", Arc::new(a) as ArrayRef),
3392            ("b", Arc::new(b) as ArrayRef),
3393        ])
3394        .unwrap();
3395
3396        let mut buf = Vec::with_capacity(1024);
3397        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
3398        writer.write(&batch).unwrap();
3399        writer.close().unwrap();
3400
3401        let bytes = Bytes::from(buf);
3402        let options = ReadOptionsBuilder::new().with_page_index().build();
3403        let reader = SerializedFileReader::new_with_options(bytes, options).unwrap();
3404        let index = reader.metadata().page_index().unwrap();
3405
3406        assert_eq!(index.num_data_pages(0, 0), Some(1)); // 1 page
3407        assert_eq!(index.num_data_pages(0, 1), Some(1)); // 1 page
3408    }
3409
3410    #[test]
3411    fn test_disabled_statistics_with_page() {
3412        let file_schema = Schema::new(vec![
3413            Field::new("a", DataType::Utf8, true),
3414            Field::new("b", DataType::Utf8, true),
3415        ]);
3416        let file_schema = Arc::new(file_schema);
3417
3418        let batch = RecordBatch::try_new(
3419            file_schema.clone(),
3420            vec![
3421                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
3422                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
3423            ],
3424        )
3425        .unwrap();
3426
3427        let props = WriterProperties::builder()
3428            .set_statistics_enabled(EnabledStatistics::None)
3429            .set_column_statistics_enabled("a".into(), EnabledStatistics::Page)
3430            .build();
3431
3432        let mut buf = Vec::with_capacity(1024);
3433        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
3434        writer.write(&batch).unwrap();
3435
3436        let metadata = writer.close().unwrap();
3437        assert_eq!(metadata.num_row_groups(), 1);
3438        let row_group = metadata.row_group(0);
3439        assert_eq!(row_group.num_columns(), 2);
3440        // Column "a" has both offset and column index, as requested
3441        assert!(row_group.column(0).offset_index_offset().is_some());
3442        assert!(row_group.column(0).column_index_offset().is_some());
3443        // Column "b" should only have offset index
3444        assert!(row_group.column(1).offset_index_offset().is_some());
3445        assert!(row_group.column(1).column_index_offset().is_none());
3446
3447        let options = ReadOptionsBuilder::new().with_page_index().build();
3448        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
3449
3450        let row_group = reader.get_row_group(0).unwrap();
3451        let a_col = row_group.metadata().column(0);
3452        let b_col = row_group.metadata().column(1);
3453
3454        // Column chunk of column "a" should have chunk level statistics
3455        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
3456            let min = byte_array_stats.min_opt().unwrap();
3457            let max = byte_array_stats.max_opt().unwrap();
3458
3459            assert_eq!(min.as_bytes(), b"a");
3460            assert_eq!(max.as_bytes(), b"d");
3461        } else {
3462            panic!("expecting Statistics::ByteArray");
3463        }
3464
3465        // The column chunk for column "b" shouldn't have statistics
3466        assert!(b_col.statistics().is_none());
3467
3468        let page_index = reader.metadata().page_index().unwrap();
3469
3470        let a_idx = page_index.column_index(0, 0);
3471        assert!(
3472            matches!(a_idx, Some(ColumnIndexMetaData::BYTE_ARRAY(_))),
3473            "{a_idx:?}"
3474        );
3475        let b_idx = page_index.column_index(0, 1);
3476        assert!(b_idx.is_none(), "{b_idx:?}");
3477    }
3478
3479    #[test]
3480    fn test_disabled_statistics_with_chunk() {
3481        let file_schema = Schema::new(vec![
3482            Field::new("a", DataType::Utf8, true),
3483            Field::new("b", DataType::Utf8, true),
3484        ]);
3485        let file_schema = Arc::new(file_schema);
3486
3487        let batch = RecordBatch::try_new(
3488            file_schema.clone(),
3489            vec![
3490                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
3491                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
3492            ],
3493        )
3494        .unwrap();
3495
3496        let props = WriterProperties::builder()
3497            .set_statistics_enabled(EnabledStatistics::None)
3498            .set_column_statistics_enabled("a".into(), EnabledStatistics::Chunk)
3499            .build();
3500
3501        let mut buf = Vec::with_capacity(1024);
3502        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
3503        writer.write(&batch).unwrap();
3504
3505        let metadata = writer.close().unwrap();
3506        assert_eq!(metadata.num_row_groups(), 1);
3507        let row_group = metadata.row_group(0);
3508        assert_eq!(row_group.num_columns(), 2);
3509        // Column "a" should only have offset index
3510        assert!(row_group.column(0).offset_index_offset().is_some());
3511        assert!(row_group.column(0).column_index_offset().is_none());
3512        // Column "b" should only have offset index
3513        assert!(row_group.column(1).offset_index_offset().is_some());
3514        assert!(row_group.column(1).column_index_offset().is_none());
3515
3516        let options = ReadOptionsBuilder::new().with_page_index().build();
3517        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
3518
3519        let row_group = reader.get_row_group(0).unwrap();
3520        let a_col = row_group.metadata().column(0);
3521        let b_col = row_group.metadata().column(1);
3522
3523        // Column chunk of column "a" should have chunk level statistics
3524        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
3525            let min = byte_array_stats.min_opt().unwrap();
3526            let max = byte_array_stats.max_opt().unwrap();
3527
3528            assert_eq!(min.as_bytes(), b"a");
3529            assert_eq!(max.as_bytes(), b"d");
3530        } else {
3531            panic!("expecting Statistics::ByteArray");
3532        }
3533
3534        // The column chunk for column "b"  shouldn't have statistics
3535        assert!(b_col.statistics().is_none());
3536
3537        let page_index = reader.metadata().page_index().unwrap();
3538
3539        let a_idx = page_index.column_index(0, 0);
3540        assert!(a_idx.is_none(), "{a_idx:?}");
3541        let b_idx = page_index.column_index(0, 1);
3542        assert!(b_idx.is_none(), "{b_idx:?}");
3543    }
3544
3545    #[test]
3546    fn test_arrow_writer_skip_metadata() {
3547        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3548        let file_schema = Arc::new(batch_schema.clone());
3549
3550        let batch = RecordBatch::try_new(
3551            Arc::new(batch_schema),
3552            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3553        )
3554        .unwrap();
3555        let skip_options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
3556
3557        let mut buf = Vec::with_capacity(1024);
3558        let mut writer =
3559            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
3560        writer.write(&batch).unwrap();
3561        writer.close().unwrap();
3562
3563        let bytes = Bytes::from(buf);
3564        let reader_builder = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
3565        assert_eq!(file_schema, *reader_builder.schema());
3566        if let Some(key_value_metadata) = reader_builder
3567            .metadata()
3568            .file_metadata()
3569            .key_value_metadata()
3570        {
3571            assert!(
3572                !key_value_metadata
3573                    .iter()
3574                    .any(|kv| kv.key.as_str() == ARROW_SCHEMA_META_KEY)
3575            );
3576        }
3577    }
3578
3579    #[test]
3580    fn test_arrow_writer_skip_path_in_schema() {
3581        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3582        let file_schema = Arc::new(batch_schema.clone());
3583
3584        let batch = RecordBatch::try_new(
3585            Arc::new(batch_schema),
3586            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3587        )
3588        .unwrap();
3589
3590        // default options should still write path_in_schema
3591        let skip_options = ArrowWriterOptions::new();
3592
3593        let mut buf = Vec::with_capacity(1024);
3594        let mut writer =
3595            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
3596        writer.write(&batch).unwrap();
3597        writer.close().unwrap();
3598
3599        // override to not write path_in_schema
3600        let skip_options = ArrowWriterOptions::new().with_properties(
3601            WriterProperties::builder()
3602                .set_write_path_in_schema(false)
3603                .build(),
3604        );
3605
3606        let mut buf2 = Vec::with_capacity(1024);
3607        let mut writer =
3608            ArrowWriter::try_new_with_options(&mut buf2, file_schema.clone(), skip_options)
3609                .unwrap();
3610        writer.write(&batch).unwrap();
3611        writer.close().unwrap();
3612
3613        // buf2 should be a bit smaller due to lack of path_in_schema
3614        assert!(buf.len() > buf2.len());
3615    }
3616
3617    #[test]
3618    fn mismatched_schemas() {
3619        let batch_schema = Schema::new(vec![Field::new("count", DataType::Int32, false)]);
3620        let file_schema = Arc::new(Schema::new(vec![Field::new(
3621            "temperature",
3622            DataType::Float64,
3623            false,
3624        )]));
3625
3626        let batch = RecordBatch::try_new(
3627            Arc::new(batch_schema),
3628            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3629        )
3630        .unwrap();
3631
3632        let mut buf = Vec::with_capacity(1024);
3633        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
3634
3635        let err = writer.write(&batch).unwrap_err().to_string();
3636        assert_eq!(
3637            err,
3638            "Arrow: Incompatible type. Field 'temperature' has type Float64, array has type Int32"
3639        );
3640    }
3641
3642    #[test]
3643    fn test_page_stats_not_written_by_default() {
3644        let string_field = Field::new("a", DataType::Utf8, false);
3645        let schema = Schema::new(vec![string_field]);
3646        let raw_string_values = vec!["Blart Versenwald III"];
3647        let string_values = StringArray::from(raw_string_values.clone());
3648        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
3649
3650        let props = WriterProperties::builder()
3651            .set_statistics_enabled(EnabledStatistics::Page)
3652            .set_dictionary_enabled(false)
3653            .set_encoding(Encoding::PLAIN)
3654            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3655            .build();
3656
3657        let file = roundtrip_opts(&batch, props);
3658
3659        // read file and decode page headers
3660        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3661
3662        // decode first page header
3663        let first_page = &file[4..];
3664        let mut prot = ThriftSliceInputProtocol::new(first_page);
3665        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3666        let stats = hdr.data_page_header.unwrap().statistics;
3667
3668        assert!(stats.is_none());
3669    }
3670
3671    #[test]
3672    fn test_page_stats_when_enabled() {
3673        let string_field = Field::new("a", DataType::Utf8, false);
3674        let schema = Schema::new(vec![string_field]);
3675        let raw_string_values = vec!["Blart Versenwald III", "Andrew Lamb"];
3676        let string_values = StringArray::from(raw_string_values.clone());
3677        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
3678
3679        let props = WriterProperties::builder()
3680            .set_statistics_enabled(EnabledStatistics::Page)
3681            .set_dictionary_enabled(false)
3682            .set_encoding(Encoding::PLAIN)
3683            .set_write_page_header_statistics(true)
3684            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3685            .build();
3686
3687        let file = roundtrip_opts(&batch, props);
3688
3689        // read file and decode page headers
3690        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3691
3692        // decode first page header
3693        let first_page = &file[4..];
3694        let mut prot = ThriftSliceInputProtocol::new(first_page);
3695        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3696        let stats = hdr.data_page_header.unwrap().statistics;
3697
3698        let stats = stats.unwrap();
3699        // check that min/max were actually written to the page
3700        assert!(stats.is_max_value_exact.unwrap());
3701        assert!(stats.is_min_value_exact.unwrap());
3702        assert_eq!(stats.max_value.unwrap(), b"Blart Versenwald III");
3703        assert_eq!(stats.min_value.unwrap(), b"Andrew Lamb");
3704    }
3705
3706    #[test]
3707    fn test_page_stats_truncation() {
3708        let string_field = Field::new("a", DataType::Utf8, false);
3709        let binary_field = Field::new("b", DataType::Binary, false);
3710        let schema = Schema::new(vec![string_field, binary_field]);
3711
3712        let raw_string_values = vec!["Blart Versenwald III"];
3713        let raw_binary_values = [b"Blart Versenwald III".to_vec()];
3714        let raw_binary_value_refs = raw_binary_values
3715            .iter()
3716            .map(|x| x.as_slice())
3717            .collect::<Vec<_>>();
3718
3719        let string_values = StringArray::from(raw_string_values.clone());
3720        let binary_values = BinaryArray::from(raw_binary_value_refs);
3721        let batch = RecordBatch::try_new(
3722            Arc::new(schema),
3723            vec![Arc::new(string_values), Arc::new(binary_values)],
3724        )
3725        .unwrap();
3726
3727        let props = WriterProperties::builder()
3728            .set_statistics_truncate_length(Some(2))
3729            .set_dictionary_enabled(false)
3730            .set_encoding(Encoding::PLAIN)
3731            .set_write_page_header_statistics(true)
3732            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3733            .build();
3734
3735        let file = roundtrip_opts(&batch, props);
3736
3737        // read file and decode page headers
3738        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3739
3740        // decode first page header
3741        let first_page = &file[4..];
3742        let mut prot = ThriftSliceInputProtocol::new(first_page);
3743        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3744        let stats = hdr.data_page_header.unwrap().statistics;
3745        assert!(stats.is_some());
3746        let stats = stats.unwrap();
3747        // check that min/max were properly truncated
3748        assert!(!stats.is_max_value_exact.unwrap());
3749        assert!(!stats.is_min_value_exact.unwrap());
3750        assert_eq!(stats.max_value.unwrap(), b"Bm");
3751        assert_eq!(stats.min_value.unwrap(), b"Bl");
3752
3753        // check second page now
3754        let second_page = &prot.as_slice()[hdr.compressed_page_size as usize..];
3755        let mut prot = ThriftSliceInputProtocol::new(second_page);
3756        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3757        let stats = hdr.data_page_header.unwrap().statistics;
3758        assert!(stats.is_some());
3759        let stats = stats.unwrap();
3760        // check that min/max were properly truncated
3761        assert!(!stats.is_max_value_exact.unwrap());
3762        assert!(!stats.is_min_value_exact.unwrap());
3763        assert_eq!(stats.max_value.unwrap(), b"Bm");
3764        assert_eq!(stats.min_value.unwrap(), b"Bl");
3765    }
3766
3767    #[test]
3768    fn test_page_encoding_statistics_roundtrip() {
3769        let batch_schema = Schema::new(vec![Field::new(
3770            "int32",
3771            arrow_schema::DataType::Int32,
3772            false,
3773        )]);
3774
3775        let batch = RecordBatch::try_new(
3776            Arc::new(batch_schema.clone()),
3777            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3778        )
3779        .unwrap();
3780
3781        let mut file: File = tempfile::tempfile().unwrap();
3782        let mut writer = ArrowWriter::try_new(&mut file, Arc::new(batch_schema), None).unwrap();
3783        writer.write(&batch).unwrap();
3784        let file_metadata = writer.close().unwrap();
3785
3786        assert_eq!(file_metadata.num_row_groups(), 1);
3787        assert_eq!(file_metadata.row_group(0).num_columns(), 1);
3788        assert!(
3789            file_metadata
3790                .row_group(0)
3791                .column(0)
3792                .page_encoding_stats()
3793                .is_some()
3794        );
3795        let chunk_page_stats = file_metadata
3796            .row_group(0)
3797            .column(0)
3798            .page_encoding_stats()
3799            .unwrap();
3800
3801        // check that the read metadata is also correct
3802        let options = ReadOptionsBuilder::new()
3803            .with_page_index()
3804            .with_encoding_stats_as_mask(false)
3805            .build();
3806        let reader = SerializedFileReader::new_with_options(file, options).unwrap();
3807
3808        let rowgroup = reader.get_row_group(0).expect("row group missing");
3809        assert_eq!(rowgroup.num_columns(), 1);
3810        let column = rowgroup.metadata().column(0);
3811        assert!(column.page_encoding_stats().is_some());
3812        let file_page_stats = column.page_encoding_stats().unwrap();
3813        assert_eq!(chunk_page_stats, file_page_stats);
3814    }
3815
3816    #[test]
3817    #[cfg_attr(miri, ignore)] // Takes too long
3818    fn test_different_dict_page_size_limit() {
3819        let array = Arc::new(Int64Array::from_iter(0..1024 * 1024));
3820        let schema = Arc::new(Schema::new(vec![
3821            Field::new("col0", arrow_schema::DataType::Int64, false),
3822            Field::new("col1", arrow_schema::DataType::Int64, false),
3823        ]));
3824        let batch =
3825            arrow_array::RecordBatch::try_new(schema.clone(), vec![array.clone(), array]).unwrap();
3826
3827        let props = WriterProperties::builder()
3828            .set_dictionary_page_size_limit(1024 * 1024)
3829            .set_column_dictionary_page_size_limit(ColumnPath::from("col1"), 1024 * 1024 * 4)
3830            .build();
3831        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3832        writer.write(&batch).unwrap();
3833        let data = Bytes::from(writer.into_inner().unwrap());
3834
3835        let mut metadata = ParquetMetaDataReader::new();
3836        metadata.try_parse(&data).unwrap();
3837        let metadata = metadata.finish().unwrap();
3838        let col0_meta = metadata.row_group(0).column(0);
3839        let col1_meta = metadata.row_group(0).column(1);
3840
3841        let get_dict_page_size = move |meta: &ColumnChunkMetaData| {
3842            let mut reader =
3843                SerializedPageReader::new(Arc::new(data.clone()), meta, 0, None).unwrap();
3844            let page = reader.get_next_page().unwrap().unwrap();
3845            match page {
3846                Page::DictionaryPage { buf, .. } => buf.len(),
3847                _ => panic!("expected DictionaryPage"),
3848            }
3849        };
3850
3851        assert_eq!(get_dict_page_size(col0_meta), 1024 * 1024);
3852        assert_eq!(get_dict_page_size(col1_meta), 1024 * 1024 * 4);
3853    }
3854
3855    #[test]
3856    #[cfg_attr(miri, ignore)] // Takes too long
3857    fn test_arrow_writer_granular_mode_roundtrip() {
3858        // Granular mode subdivides chunks and writes more pages than the
3859        // default batched path. Make sure the data we write back is
3860        // bit-identical to what went in — page-count assertions elsewhere
3861        // only prove pages were cut, not that the encoded data is correct.
3862        //
3863        // Mix value sizes so that the cumulative-byte-budget cutoff
3864        // lands mid-chunk, exercising both batched and granular paths
3865        // within the same `write_batch_internal` call.
3866        let small = "tiny".to_string();
3867        let big = "x".repeat(64 * 1024);
3868        let strings: Vec<String> = (0..256)
3869            .map(|i| {
3870                if i % 16 == 0 {
3871                    big.clone()
3872                } else {
3873                    small.clone()
3874                }
3875            })
3876            .collect();
3877
3878        let schema = Arc::new(Schema::new(vec![Field::new(
3879            "col",
3880            ArrowDataType::Utf8,
3881            false,
3882        )]));
3883        let batch = RecordBatch::try_new(
3884            schema.clone(),
3885            vec![Arc::new(StringArray::from(strings.clone())) as _],
3886        )
3887        .unwrap();
3888
3889        let props = WriterProperties::builder()
3890            .set_dictionary_enabled(false)
3891            .set_data_page_size_limit(16 * 1024)
3892            .build();
3893        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3894        writer.write(&batch).unwrap();
3895        let data = Bytes::from(writer.into_inner().unwrap());
3896
3897        let mut reader = ParquetRecordBatchReader::try_new(data, 1024).unwrap();
3898        let read = reader.next().unwrap().unwrap();
3899        assert!(reader.next().is_none(), "expected one batch");
3900        let col = read
3901            .column(0)
3902            .as_any()
3903            .downcast_ref::<StringArray>()
3904            .unwrap();
3905        assert_eq!(col.len(), strings.len());
3906        for (i, expected) in strings.iter().enumerate() {
3907            assert_eq!(
3908                col.value(i),
3909                expected.as_str(),
3910                "value mismatch at index {i}"
3911            );
3912        }
3913    }
3914
3915    #[test]
3916    fn test_arrow_writer_all_null_string_column() {
3917        // The `LevelDataRef::value_count` Uniform branch with
3918        // `value != max_def` (entirely-null chunk) must return 0 so the
3919        // sub-batch sizer short-circuits to batch mode without trying
3920        // to estimate byte budgets for non-existent values.
3921        let num_rows = 1024;
3922        let schema = Arc::new(Schema::new(vec![Field::new(
3923            "col",
3924            ArrowDataType::Utf8,
3925            true,
3926        )]));
3927        let nulls: Vec<Option<&str>> = vec![None; num_rows];
3928        let batch = RecordBatch::try_new(
3929            schema.clone(),
3930            vec![Arc::new(StringArray::from(nulls)) as _],
3931        )
3932        .unwrap();
3933
3934        let props = WriterProperties::builder()
3935            .set_dictionary_enabled(false)
3936            .set_data_page_size_limit(16 * 1024)
3937            .build();
3938        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3939        writer.write(&batch).unwrap();
3940        let data = Bytes::from(writer.into_inner().unwrap());
3941
3942        // Re-parse the file: row group has one column, every row is
3943        // null, all data pages report `num_rows / page_count` rows.
3944        let mut metadata = ParquetMetaDataReader::new();
3945        metadata.try_parse(&data).unwrap();
3946        let metadata = metadata.finish().unwrap();
3947        let row_group = metadata.row_group(0);
3948        let col_meta = row_group.column(0);
3949        assert_eq!(row_group.num_rows() as usize, num_rows);
3950        // Statistics record `null_count = num_rows` — proves every value
3951        // was written as null.
3952        if let Some(stats) = col_meta.statistics() {
3953            assert_eq!(
3954                stats.null_count_opt().unwrap_or(0) as usize,
3955                num_rows,
3956                "expected all-null column to report null_count = num_rows"
3957            );
3958        }
3959
3960        let mut reader =
3961            SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap();
3962        let mut total_values = 0u32;
3963        while let Some(page) = reader.get_next_page().unwrap() {
3964            if matches!(page, Page::DataPage { .. } | Page::DataPageV2 { .. }) {
3965                total_values += page.num_values();
3966            }
3967        }
3968        assert_eq!(
3969            total_values as usize, num_rows,
3970            "expected every level position to be represented in some page"
3971        );
3972    }
3973
3974    struct WriteBatchesShape {
3975        num_batches: usize,
3976        rows_per_batch: usize,
3977        row_size: usize,
3978    }
3979
3980    /// Helper function to write batches with the provided `WriteBatchesShape` into an `ArrowWriter`
3981    fn write_batches(
3982        WriteBatchesShape {
3983            num_batches,
3984            rows_per_batch,
3985            row_size,
3986        }: WriteBatchesShape,
3987        props: WriterProperties,
3988    ) -> ParquetRecordBatchReaderBuilder<File> {
3989        let schema = Arc::new(Schema::new(vec![Field::new(
3990            "str",
3991            ArrowDataType::Utf8,
3992            false,
3993        )]));
3994        let file = tempfile::tempfile().unwrap();
3995        let mut writer =
3996            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
3997
3998        for batch_idx in 0..num_batches {
3999            let strings: Vec<String> = (0..rows_per_batch)
4000                .map(|i| format!("{:0>width$}", batch_idx * 10 + i, width = row_size))
4001                .collect();
4002            let array = StringArray::from(strings);
4003            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
4004            writer.write(&batch).unwrap();
4005        }
4006        writer.close().unwrap();
4007        ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
4008    }
4009
4010    #[test]
4011    // When both limits are None, all data should go into a single row group
4012    fn test_row_group_limit_none_writes_single_row_group() {
4013        let props = WriterProperties::builder()
4014            .set_max_row_group_row_count(None)
4015            .set_max_row_group_bytes(None)
4016            .build();
4017
4018        let builder = write_batches(
4019            WriteBatchesShape {
4020                num_batches: 1,
4021                rows_per_batch: 1000,
4022                row_size: 4,
4023            },
4024            props,
4025        );
4026
4027        assert_eq!(
4028            &row_group_sizes(builder.metadata()),
4029            &[1000],
4030            "With no limits, all rows should be in a single row group"
4031        );
4032    }
4033
4034    #[test]
4035    // When only max_row_group_size is set, respect the row limit
4036    fn test_row_group_limit_rows_only() {
4037        let props = WriterProperties::builder()
4038            .set_max_row_group_row_count(Some(300))
4039            .set_max_row_group_bytes(None)
4040            .build();
4041
4042        let builder = write_batches(
4043            WriteBatchesShape {
4044                num_batches: 1,
4045                rows_per_batch: 1000,
4046                row_size: 4,
4047            },
4048            props,
4049        );
4050
4051        assert_eq!(
4052            &row_group_sizes(builder.metadata()),
4053            &[300, 300, 300, 100],
4054            "Row groups should be split by row count"
4055        );
4056    }
4057
4058    #[test]
4059    #[cfg_attr(miri, ignore)] // Takes too long
4060    // A row limit far smaller than the batch splits it many times over; the split must not
4061    // consume stack proportional to the number of row groups.
4062    fn test_row_group_limit_rows_only_many_splits() {
4063        let props = WriterProperties::builder()
4064            .set_max_row_group_row_count(Some(1))
4065            .set_max_row_group_bytes(None)
4066            .build();
4067
4068        let rows = 50_000;
4069        let builder = write_batches(
4070            WriteBatchesShape {
4071                num_batches: 1,
4072                rows_per_batch: rows,
4073                row_size: 4,
4074            },
4075            props,
4076        );
4077
4078        let sizes = row_group_sizes(builder.metadata());
4079        assert_eq!(sizes.len(), rows, "Every row should get its own row group");
4080        assert_eq!(
4081            sizes.iter().sum::<i64>(),
4082            rows as i64,
4083            "Total rows should be preserved"
4084        );
4085    }
4086
4087    #[test]
4088    // When only max_row_group_bytes is set, respect the byte limit
4089    fn test_row_group_limit_bytes_only() {
4090        let props = WriterProperties::builder()
4091            .set_max_row_group_row_count(None)
4092            // Set byte limit to approximately fit ~30 rows worth of data (~100 bytes each)
4093            .set_max_row_group_bytes(Some(3500))
4094            .build();
4095
4096        let builder = write_batches(
4097            WriteBatchesShape {
4098                num_batches: 10,
4099                rows_per_batch: 10,
4100                row_size: 100,
4101            },
4102            props,
4103        );
4104
4105        let sizes = row_group_sizes(builder.metadata());
4106
4107        assert!(
4108            sizes.len() > 1,
4109            "Should have multiple row groups due to byte limit, got {sizes:?}",
4110        );
4111
4112        let total_rows: i64 = sizes.iter().sum();
4113        assert_eq!(total_rows, 100, "Total rows should be preserved");
4114    }
4115
4116    #[test]
4117    // If an in-progress row group is already oversized, it should be flushed before writing more.
4118    fn test_row_group_limit_bytes_flushes_when_current_group_already_too_large() {
4119        let schema = Arc::new(Schema::new(vec![Field::new(
4120            "str",
4121            ArrowDataType::Utf8,
4122            false,
4123        )]));
4124        let file = tempfile::tempfile().unwrap();
4125
4126        // Start with no byte limit so we can intentionally build an oversized in-progress row group.
4127        let props = WriterProperties::builder()
4128            .set_max_row_group_row_count(None)
4129            .set_max_row_group_bytes(None)
4130            .build();
4131        let mut writer =
4132            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4133
4134        let first_array = StringArray::from(
4135            (0..10)
4136                .map(|i| format!("{i:0>100}"))
4137                .collect::<Vec<String>>(),
4138        );
4139        let first_batch =
4140            RecordBatch::try_new(schema.clone(), vec![Arc::new(first_array)]).unwrap();
4141        writer.write(&first_batch).unwrap();
4142        assert_eq!(writer.in_progress_rows(), 10);
4143
4144        // Tighten the limit below the current in-progress bytes to exercise:
4145        // `if current_bytes >= max_bytes { self.flush()?; ... }`
4146        writer.max_row_group_bytes = Some(1);
4147
4148        let second_array = StringArray::from(vec!["x".to_string()]);
4149        let second_batch =
4150            RecordBatch::try_new(schema.clone(), vec![Arc::new(second_array)]).unwrap();
4151        writer.write(&second_batch).unwrap();
4152        writer.close().unwrap();
4153        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
4154
4155        assert_eq!(
4156            &row_group_sizes(builder.metadata()),
4157            &[10, 1],
4158            "The second write should flush an oversized in-progress row group first",
4159        );
4160    }
4161
4162    #[test]
4163    // When both limits are set, the row limit triggers first
4164    fn test_row_group_limit_both_row_wins_single_batch() {
4165        let props = WriterProperties::builder()
4166            .set_max_row_group_row_count(Some(200)) // Will trigger at 200 rows
4167            .set_max_row_group_bytes(Some(1024 * 1024)) // 1MB - won't trigger for small int data
4168            .build();
4169
4170        let builder = write_batches(
4171            WriteBatchesShape {
4172                num_batches: 1,
4173                row_size: 4,
4174                rows_per_batch: 1000,
4175            },
4176            props,
4177        );
4178
4179        assert_eq!(
4180            &row_group_sizes(builder.metadata()),
4181            &[200, 200, 200, 200, 200],
4182            "Row limit should trigger before byte limit"
4183        );
4184    }
4185
4186    #[test]
4187    // When both limits are set, the row limit triggers first
4188    fn test_row_group_limit_both_row_wins_multiple_batches() {
4189        let props = WriterProperties::builder()
4190            .set_max_row_group_row_count(Some(5)) // Will trigger every 5 rows
4191            .set_max_row_group_bytes(Some(9999)) // Won't trigger
4192            .build();
4193
4194        let builder = write_batches(
4195            WriteBatchesShape {
4196                num_batches: 10,
4197                rows_per_batch: 10,
4198                row_size: 100,
4199            },
4200            props,
4201        );
4202
4203        assert_eq!(
4204            &row_group_sizes(builder.metadata()),
4205            &[5; 20],
4206            "Row limit should trigger before byte limit"
4207        );
4208    }
4209
4210    #[test]
4211    // When both limits are set, the byte limit triggers first
4212    fn test_row_group_limit_both_bytes_wins() {
4213        let props = WriterProperties::builder()
4214            .set_max_row_group_row_count(Some(1000)) // Won't trigger for 100 rows
4215            .set_max_row_group_bytes(Some(3500)) // Will trigger at ~30-35 rows
4216            .build();
4217
4218        let builder = write_batches(
4219            WriteBatchesShape {
4220                num_batches: 10,
4221                rows_per_batch: 10,
4222                row_size: 100,
4223            },
4224            props,
4225        );
4226
4227        let sizes = row_group_sizes(builder.metadata());
4228
4229        assert!(
4230            sizes.len() > 1,
4231            "Byte limit should trigger before row limit, got {sizes:?}",
4232        );
4233
4234        assert!(
4235            sizes.iter().all(|&s| s < 1000),
4236            "No row group should hit the row limit"
4237        );
4238
4239        let total_rows: i64 = sizes.iter().sum();
4240        assert_eq!(total_rows, 100, "Total rows should be preserved");
4241    }
4242
4243    #[test]
4244    // Both limits can apply to the same batch: the row limit trims it to 5 rows, and the
4245    // byte limit then trims those 5 down to 4.
4246    fn test_row_group_limit_both_apply_to_same_batch() {
4247        let props = WriterProperties::builder()
4248            .set_max_row_group_row_count(Some(15))
4249            .set_max_row_group_bytes(Some(1500))
4250            .build();
4251
4252        let builder = write_batches(
4253            WriteBatchesShape {
4254                num_batches: 2,
4255                rows_per_batch: 10,
4256                row_size: 100,
4257            },
4258            props,
4259        );
4260
4261        assert_eq!(
4262            &row_group_sizes(builder.metadata()),
4263            &[14, 6],
4264            "Byte limit should still apply to a batch the row limit already split"
4265        );
4266    }
4267
4268    #[test]
4269    fn arrow_column_chunk_close_mut_drops_column_index() {
4270        use crate::arrow::ArrowSchemaConverter;
4271        use crate::file::writer::SerializedFileWriter;
4272
4273        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
4274        let props = Arc::new(
4275            WriterProperties::builder()
4276                .set_statistics_enabled(EnabledStatistics::Page)
4277                .build(),
4278        );
4279        let parquet_schema = ArrowSchemaConverter::new()
4280            .with_coerce_types(props.coerce_types())
4281            .convert(&schema)
4282            .unwrap();
4283
4284        let mut buf = Vec::with_capacity(1024);
4285        let mut writer =
4286            SerializedFileWriter::new(&mut buf, parquet_schema.root_schema_ptr(), props.clone())
4287                .unwrap();
4288
4289        let factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
4290        let mut col_writers = factory.create_column_writers(0).unwrap();
4291        let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..64));
4292        for leaves in compute_leaves(schema.field(0), &arr).unwrap() {
4293            col_writers[0].write(&leaves).unwrap();
4294        }
4295        let mut chunk = col_writers.pop().unwrap().close().unwrap();
4296
4297        // Immutable accessor exposes the close result produced at close time.
4298        assert!(
4299            chunk.close().column_index.is_some(),
4300            "EnabledStatistics::Page should produce a column_index"
4301        );
4302
4303        // Mutable accessor lets callers drop the page-level index before append.
4304        chunk.close_mut().column_index = None;
4305        assert!(chunk.close().column_index.is_none());
4306
4307        let mut rg = writer.next_row_group().unwrap();
4308        chunk.append_to_row_group(&mut rg).unwrap();
4309        rg.close().unwrap();
4310        let file_meta = writer.close().unwrap();
4311
4312        // After dropping column_index, the resulting file records no column
4313        // index offset/length for this chunk.
4314        let cc = file_meta.row_group(0).column(0);
4315        assert!(cc.column_index_range().is_none());
4316    }
4317
4318    #[test]
4319    #[cfg_attr(miri, ignore)] // Takes too long
4320    fn test_number_distinct_values_exact_count() {
4321        // 50 distinct Int32 values repeated across 100k rows, with every 7th row null.
4322        // Nulls must not be counted as a distinct value.
4323        let cardinality = 50u32;
4324        let array: ArrayRef = Arc::new(Int32Array::from_iter((0..100_000u32).map(|i| {
4325            if i % 7 == 0 {
4326                None
4327            } else {
4328                Some((i % cardinality) as i32)
4329            }
4330        })));
4331        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, true)]));
4332        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
4333
4334        let props = WriterProperties::builder()
4335            .set_write_row_group_number_distinct_values(true)
4336            .build();
4337        let mut buf = Vec::new();
4338        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4339        writer.write(&batch).unwrap();
4340        let metadata = writer.close().unwrap();
4341
4342        let count = metadata
4343            .row_group(0)
4344            .column(0)
4345            .statistics()
4346            .and_then(|s| s.distinct_count_opt())
4347            .expect("distinct_count should be set");
4348        // Must equal cardinality exactly; nulls must not inflate the count.
4349        assert_eq!(count, cardinality as u64);
4350    }
4351
4352    #[test]
4353    fn test_number_distinct_values_view_types() {
4354        // 5 distinct values repeated across 30 rows, with every 4th row null.
4355        // Verifies Utf8View is counted correctly (BinaryView shares the same code path).
4356        let cardinality = 5u32;
4357        let distinct_strings = ["alpha", "beta", "gamma", "delta", "epsilon"];
4358
4359        let string_view_col: ArrayRef = Arc::new(StringViewArray::from_iter((0..30u32).map(|i| {
4360            if i % 4 == 0 {
4361                None
4362            } else {
4363                Some(distinct_strings[(i % cardinality) as usize])
4364            }
4365        })));
4366
4367        let schema = Arc::new(Schema::new(vec![Field::new(
4368            "string_view_col",
4369            DataType::Utf8View,
4370            true,
4371        )]));
4372        let batch = RecordBatch::try_new(schema, vec![string_view_col]).unwrap();
4373
4374        let props = WriterProperties::builder()
4375            .set_write_row_group_number_distinct_values(true)
4376            .build();
4377        let mut parquet_bytes = Vec::new();
4378        let mut writer =
4379            ArrowWriter::try_new(&mut parquet_bytes, batch.schema(), Some(props)).unwrap();
4380        writer.write(&batch).unwrap();
4381        let metadata = writer.close().unwrap();
4382
4383        let distinct_count = metadata
4384            .row_group(0)
4385            .column(0)
4386            .statistics()
4387            .and_then(|s| s.distinct_count_opt())
4388            .expect("distinct_count should be set for Utf8View column");
4389        assert_eq!(distinct_count, cardinality as u64);
4390    }
4391
4392    #[test]
4393    fn test_number_distinct_values_not_written_by_default() {
4394        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
4395        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)]));
4396        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
4397
4398        let mut buf = Vec::new();
4399        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
4400        writer.write(&batch).unwrap();
4401        let metadata = writer.close().unwrap();
4402
4403        let count = metadata
4404            .row_group(0)
4405            .column(0)
4406            .statistics()
4407            .and_then(|s| s.distinct_count_opt());
4408        assert!(count.is_none());
4409    }
4410
4411    #[test]
4412    fn test_dictionary_ndv_single_batch() {
4413        // Dictionary array with 3 distinct string values repeated many times.
4414        // NDV must equal the number of distinct values in the dictionary (3),
4415        // not the number of rows.
4416        let keys = Int32Array::from(vec![0, 1, 2, 0, 1, 2, 0, 1, 2]);
4417        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "bird"]));
4418        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4419
4420        let schema = Arc::new(Schema::new(vec![Field::new(
4421            "x",
4422            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4423            false,
4424        )]));
4425        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
4426
4427        let props = WriterProperties::builder()
4428            .set_write_row_group_number_distinct_values(true)
4429            .build();
4430        let mut buf = Vec::new();
4431        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4432        writer.write(&batch).unwrap();
4433        let metadata = writer.close().unwrap();
4434
4435        let count = metadata
4436            .row_group(0)
4437            .column(0)
4438            .statistics()
4439            .and_then(|s| s.distinct_count_opt())
4440            .expect("distinct_count should be set");
4441        assert_eq!(count, 3);
4442    }
4443
4444    #[test]
4445    fn test_dictionary_ndv_excludes_unreferenced_values() {
4446        // Keys only reference indices 0 and 1; value at index 2 ("unreferenced") should not
4447        // count toward NDV even though it appears in the dictionary's values array.
4448        let keys = Int32Array::from(vec![0, 1, 0, 1]);
4449        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "unreferenced"]));
4450        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4451
4452        let schema = Arc::new(Schema::new(vec![Field::new(
4453            "x",
4454            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4455            false,
4456        )]));
4457        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
4458
4459        let props = WriterProperties::builder()
4460            .set_write_row_group_number_distinct_values(true)
4461            .build();
4462        let mut buf = Vec::new();
4463        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4464        writer.write(&batch).unwrap();
4465        let metadata = writer.close().unwrap();
4466
4467        let count = metadata
4468            .row_group(0)
4469            .column(0)
4470            .statistics()
4471            .and_then(|s| s.distinct_count_opt())
4472            .expect("distinct_count should be set");
4473        assert_eq!(
4474            count, 2,
4475            "unreferenced dictionary values must not count toward NDV"
4476        );
4477    }
4478
4479    #[test]
4480    fn test_dictionary_ndv_across_batches_regression() {
4481        // Regression test for https://github.com/apache/arrow-rs/issues/11172.
4482        let make_dict_batch = |a: &str, b: &str| -> RecordBatch {
4483            let keys = Int32Array::from(vec![0, 1, 0, 1]);
4484            let values: ArrayRef = Arc::new(StringArray::from(vec![a, b]));
4485            let dict: ArrayRef =
4486                Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4487            let schema = Arc::new(Schema::new(vec![Field::new(
4488                "x",
4489                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4490                false,
4491            )]));
4492            RecordBatch::try_new(schema, vec![dict]).unwrap()
4493        };
4494
4495        // batch1: dict = ["cat", "dog"], batch2: dict = ["fish", "cat"]
4496        // Distinct values across both batches: "cat", "dog", "fish" NDV = 3
4497        let batch1 = make_dict_batch("cat", "dog");
4498        let batch2 = make_dict_batch("fish", "cat");
4499
4500        let props = WriterProperties::builder()
4501            .set_write_row_group_number_distinct_values(true)
4502            .build();
4503        let mut buf = Vec::new();
4504        let mut writer = ArrowWriter::try_new(&mut buf, batch1.schema(), Some(props)).unwrap();
4505        writer.write(&batch1).unwrap();
4506        writer.write(&batch2).unwrap();
4507        let metadata = writer.close().unwrap();
4508
4509        let count = metadata
4510            .row_group(0)
4511            .column(0)
4512            .statistics()
4513            .and_then(|s| s.distinct_count_opt())
4514            .expect("distinct_count should be set");
4515        assert_eq!(
4516            count, 3,
4517            "NDV should count distinct values, not distinct key indices"
4518        );
4519    }
4520
4521    #[test]
4522    fn ree_struct_with_ree_child() {
4523        // Struct with a REE string field and a REE int field — confirms
4524        // recursion visits every child and each collapses to the right leaf type.
4525        let run_ends = Int32Array::from(vec![2i32, 3, 5]);
4526
4527        let col_a: ArrayRef = Arc::new(
4528            RunArray::try_new(
4529                &run_ends,
4530                &StringArray::from(vec![Some("foo"), None, Some("bar")]),
4531            )
4532            .unwrap(),
4533        );
4534        let col_b: ArrayRef = Arc::new(
4535            RunArray::try_new(&run_ends, &Int32Array::from(vec![Some(1), None, Some(2)])).unwrap(),
4536        );
4537
4538        let struct_array: ArrayRef = Arc::new(StructArray::new(
4539            Fields::from(vec![
4540                Field::new("a", col_a.data_type().clone(), true),
4541                Field::new("b", col_b.data_type().clone(), true),
4542            ]),
4543            vec![col_a, col_b],
4544            None,
4545        ));
4546
4547        let schema = Arc::new(Schema::new(vec![Field::new(
4548            "row",
4549            struct_array.data_type().clone(),
4550            true,
4551        )]));
4552        let batch = RecordBatch::try_new(schema.clone(), vec![struct_array]).unwrap();
4553
4554        let mut buf = Vec::new();
4555        let mut writer = ArrowWriter::try_new(&mut buf, schema, None).unwrap();
4556        writer.write(&batch).unwrap();
4557        let metadata = writer.close().unwrap();
4558
4559        let parquet_schema = metadata.file_metadata().schema_descr();
4560        assert_eq!(parquet_schema.num_columns(), 2);
4561        assert_eq!(
4562            parquet_schema.column(0).physical_type(),
4563            crate::basic::Type::BYTE_ARRAY
4564        );
4565        assert_eq!(parquet_schema.column(0).path().string(), "row.a");
4566        assert_eq!(
4567            parquet_schema.column(1).physical_type(),
4568            crate::basic::Type::INT32
4569        );
4570        assert_eq!(parquet_schema.column(1).path().string(), "row.b");
4571    }
4572}