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                ArrowDataType::FixedSizeBinary(_) => out.push(bytes(leaves.next().unwrap())?),
1537                _ => out.push(col(leaves.next().unwrap())?),
1538            },
1539            ArrowDataType::RunEndEncoded(_, value_field) => {
1540                self.get_arrow_column_writer(value_field.data_type(), props, leaves, out)?
1541            }
1542            _ => {
1543                return Err(ParquetError::NYI(format!(
1544                    "Attempting to write an Arrow type {data_type} to parquet that is not yet implemented"
1545                )));
1546            }
1547        }
1548        Ok(())
1549    }
1550}
1551
1552fn write_leaf(
1553    writer: &mut ColumnWriter<'_>,
1554    column: &dyn arrow_array::Array,
1555    levels: &ArrayLevels,
1556) -> Result<usize> {
1557    let indices = levels.non_null_indices();
1558
1559    match writer {
1560        // Note: this should match the contents of arrow_to_parquet_type
1561        ColumnWriter::Int32ColumnWriter(typed) => {
1562            match column.data_type() {
1563                ArrowDataType::Null => {
1564                    let array = Int32Array::new_null(column.len());
1565                    write_primitive(typed, array.values(), levels)
1566                }
1567                ArrowDataType::Int8 => {
1568                    let array: Int32Array = column.as_primitive::<Int8Type>().unary(|x| x as i32);
1569                    write_primitive(typed, array.values(), levels)
1570                }
1571                ArrowDataType::Int16 => {
1572                    let array: Int32Array = column.as_primitive::<Int16Type>().unary(|x| x as i32);
1573                    write_primitive(typed, array.values(), levels)
1574                }
1575                ArrowDataType::Int32 => {
1576                    write_primitive(typed, column.as_primitive::<Int32Type>().values(), levels)
1577                }
1578                ArrowDataType::UInt8 => {
1579                    let array: Int32Array = column.as_primitive::<UInt8Type>().unary(|x| x as i32);
1580                    write_primitive(typed, array.values(), levels)
1581                }
1582                ArrowDataType::UInt16 => {
1583                    let array: Int32Array = column.as_primitive::<UInt16Type>().unary(|x| x as i32);
1584                    write_primitive(typed, array.values(), levels)
1585                }
1586                ArrowDataType::UInt32 => {
1587                    // follow C++ implementation and use overflow/reinterpret cast from  u32 to i32 which will map
1588                    // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0`
1589                    let array = column.as_primitive::<UInt32Type>();
1590                    write_primitive(typed, array.values().inner().typed_data(), levels)
1591                }
1592                ArrowDataType::Date32 => {
1593                    let array = column.as_primitive::<Date32Type>();
1594                    write_primitive(typed, array.values(), levels)
1595                }
1596                ArrowDataType::Time32(TimeUnit::Second) => {
1597                    let array = column.as_primitive::<Time32SecondType>();
1598                    write_primitive(typed, array.values(), levels)
1599                }
1600                ArrowDataType::Time32(TimeUnit::Millisecond) => {
1601                    let array = column.as_primitive::<Time32MillisecondType>();
1602                    write_primitive(typed, array.values(), levels)
1603                }
1604                ArrowDataType::Date64 => {
1605                    // If the column is a Date64, we truncate it
1606                    let array: Int32Array = column
1607                        .as_primitive::<Date64Type>()
1608                        .unary(|x| (x / 86_400_000) as _);
1609
1610                    write_primitive(typed, array.values(), levels)
1611                }
1612                ArrowDataType::Decimal32(_, _) => {
1613                    let array = column
1614                        .as_primitive::<Decimal32Type>()
1615                        .unary::<_, Int32Type>(|v| v);
1616                    write_primitive(typed, array.values(), levels)
1617                }
1618                ArrowDataType::Decimal64(_, _) => {
1619                    // use the int32 to represent the decimal with low precision
1620                    let array = column
1621                        .as_primitive::<Decimal64Type>()
1622                        .unary::<_, Int32Type>(|v| v as i32);
1623                    write_primitive(typed, array.values(), levels)
1624                }
1625                ArrowDataType::Decimal128(_, _) => {
1626                    // use the int32 to represent the decimal with low precision
1627                    let array = column
1628                        .as_primitive::<Decimal128Type>()
1629                        .unary::<_, Int32Type>(|v| v as i32);
1630                    write_primitive(typed, array.values(), levels)
1631                }
1632                ArrowDataType::Decimal256(_, _) => {
1633                    // use the int32 to represent the decimal with low precision
1634                    let array = column
1635                        .as_primitive::<Decimal256Type>()
1636                        .unary::<_, Int32Type>(|v| v.as_i128() as i32);
1637                    write_primitive(typed, array.values(), levels)
1638                }
1639                d => Err(ParquetError::General(format!("Cannot coerce {d} to I32"))),
1640            }
1641        }
1642        ColumnWriter::BoolColumnWriter(typed) => {
1643            let array = column.as_boolean();
1644            let values = get_bool_array_slice(array, indices.iter().copied());
1645            typed.write_batch_internal(
1646                values.as_slice(),
1647                None,
1648                levels.def_level_data().as_ref(),
1649                levels.rep_level_data().as_ref(),
1650                None,
1651                None,
1652                None,
1653            )
1654        }
1655        ColumnWriter::Int64ColumnWriter(typed) => {
1656            match column.data_type() {
1657                ArrowDataType::Date64 => {
1658                    let array = column
1659                        .as_primitive::<Date64Type>()
1660                        .reinterpret_cast::<Int64Type>();
1661
1662                    write_primitive(typed, array.values(), levels)
1663                }
1664                ArrowDataType::Int64 => {
1665                    let array = column.as_primitive::<Int64Type>();
1666                    write_primitive(typed, array.values(), levels)
1667                }
1668                ArrowDataType::UInt64 => {
1669                    let values = column.as_primitive::<UInt64Type>().values();
1670                    // follow C++ implementation and use overflow/reinterpret cast from  u64 to i64 which will map
1671                    // `(i64::MAX as u64)..u64::MAX` to `i64::MIN..0`
1672                    let array = values.inner().typed_data::<i64>();
1673                    write_primitive(typed, array, levels)
1674                }
1675                ArrowDataType::Time64(TimeUnit::Microsecond) => {
1676                    let array = column.as_primitive::<Time64MicrosecondType>();
1677                    write_primitive(typed, array.values(), levels)
1678                }
1679                ArrowDataType::Time64(TimeUnit::Nanosecond) => {
1680                    let array = column.as_primitive::<Time64NanosecondType>();
1681                    write_primitive(typed, array.values(), levels)
1682                }
1683                ArrowDataType::Timestamp(unit, _) => match unit {
1684                    TimeUnit::Second => {
1685                        let array = column.as_primitive::<TimestampSecondType>();
1686                        write_primitive(typed, array.values(), levels)
1687                    }
1688                    TimeUnit::Millisecond => {
1689                        let array = column.as_primitive::<TimestampMillisecondType>();
1690                        write_primitive(typed, array.values(), levels)
1691                    }
1692                    TimeUnit::Microsecond => {
1693                        let array = column.as_primitive::<TimestampMicrosecondType>();
1694                        write_primitive(typed, array.values(), levels)
1695                    }
1696                    TimeUnit::Nanosecond => {
1697                        let array = column.as_primitive::<TimestampNanosecondType>();
1698                        write_primitive(typed, array.values(), levels)
1699                    }
1700                },
1701                ArrowDataType::Duration(unit) => match unit {
1702                    TimeUnit::Second => {
1703                        let array = column.as_primitive::<DurationSecondType>();
1704                        write_primitive(typed, array.values(), levels)
1705                    }
1706                    TimeUnit::Millisecond => {
1707                        let array = column.as_primitive::<DurationMillisecondType>();
1708                        write_primitive(typed, array.values(), levels)
1709                    }
1710                    TimeUnit::Microsecond => {
1711                        let array = column.as_primitive::<DurationMicrosecondType>();
1712                        write_primitive(typed, array.values(), levels)
1713                    }
1714                    TimeUnit::Nanosecond => {
1715                        let array = column.as_primitive::<DurationNanosecondType>();
1716                        write_primitive(typed, array.values(), levels)
1717                    }
1718                },
1719                ArrowDataType::Decimal64(_, _) => {
1720                    let array = column
1721                        .as_primitive::<Decimal64Type>()
1722                        .reinterpret_cast::<Int64Type>();
1723                    write_primitive(typed, array.values(), levels)
1724                }
1725                ArrowDataType::Decimal128(_, _) => {
1726                    // use the int64 to represent the decimal with low precision
1727                    let array = column
1728                        .as_primitive::<Decimal128Type>()
1729                        .unary::<_, Int64Type>(|v| v as i64);
1730                    write_primitive(typed, array.values(), levels)
1731                }
1732                ArrowDataType::Decimal256(_, _) => {
1733                    // use the int64 to represent the decimal with low precision
1734                    let array = column
1735                        .as_primitive::<Decimal256Type>()
1736                        .unary::<_, Int64Type>(|v| v.as_i128() as i64);
1737                    write_primitive(typed, array.values(), levels)
1738                }
1739                d => Err(ParquetError::General(format!("Cannot coerce {d} to I64"))),
1740            }
1741        }
1742        ColumnWriter::Int96ColumnWriter(_typed) => {
1743            unreachable!("Currently unreachable because data type not supported")
1744        }
1745        ColumnWriter::FloatColumnWriter(typed) => {
1746            let array = column.as_primitive::<Float32Type>();
1747            write_primitive(typed, array.values(), levels)
1748        }
1749        ColumnWriter::DoubleColumnWriter(typed) => {
1750            let array = column.as_primitive::<Float64Type>();
1751            write_primitive(typed, array.values(), levels)
1752        }
1753        ColumnWriter::ByteArrayColumnWriter(_) => {
1754            unreachable!("should use ByteArrayWriter")
1755        }
1756        ColumnWriter::FixedLenByteArrayColumnWriter(typed) => {
1757            let bytes = match column.data_type() {
1758                ArrowDataType::Interval(interval_unit) => match interval_unit {
1759                    IntervalUnit::YearMonth => {
1760                        let array = column.as_primitive::<IntervalYearMonthType>();
1761                        get_interval_ym_array_slice(array, indices.iter().copied())
1762                    }
1763                    IntervalUnit::DayTime => {
1764                        let array = column.as_primitive::<IntervalDayTimeType>();
1765                        get_interval_dt_array_slice(array, indices.iter().copied())
1766                    }
1767                    IntervalUnit::MonthDayNano => {
1768                        return Err(ParquetError::NYI(format!(
1769                            "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented"
1770                        )));
1771                    }
1772                },
1773                ArrowDataType::FixedSizeBinary(_) => {
1774                    let array = column.as_fixed_size_binary();
1775                    get_fsb_array_slice(array, indices.iter().copied())
1776                }
1777                ArrowDataType::Decimal32(_, _) => {
1778                    let array = column.as_primitive::<Decimal32Type>();
1779                    get_decimal_array_slice(array, indices.iter().copied())
1780                }
1781                ArrowDataType::Decimal64(_, _) => {
1782                    let array = column.as_primitive::<Decimal64Type>();
1783                    get_decimal_array_slice(array, indices.iter().copied())
1784                }
1785                ArrowDataType::Decimal128(_, _) => {
1786                    let array = column.as_primitive::<Decimal128Type>();
1787                    get_decimal_array_slice(array, indices.iter().copied())
1788                }
1789                ArrowDataType::Decimal256(_, _) => {
1790                    let array = column.as_primitive::<Decimal256Type>();
1791                    get_decimal_array_slice(array, indices.iter().copied())
1792                }
1793                ArrowDataType::Float16 => {
1794                    let array = column.as_primitive::<Float16Type>();
1795                    get_float_16_array_slice(array, indices.iter().copied())
1796                }
1797                _ => {
1798                    return Err(ParquetError::NYI(
1799                        "Attempting to write an Arrow type that is not yet implemented".to_string(),
1800                    ));
1801                }
1802            };
1803            typed.write_batch_internal(
1804                bytes.as_slice(),
1805                None,
1806                levels.def_level_data().as_ref(),
1807                levels.rep_level_data().as_ref(),
1808                None,
1809                None,
1810                None,
1811            )
1812        }
1813    }
1814}
1815
1816fn write_primitive<E: ColumnValueEncoder>(
1817    writer: &mut GenericColumnWriter<E>,
1818    values: &E::Values,
1819    levels: &ArrayLevels,
1820) -> Result<usize> {
1821    writer.write_batch_internal(
1822        values,
1823        Some(levels.non_null_indices()),
1824        levels.def_level_data().as_ref(),
1825        levels.rep_level_data().as_ref(),
1826        None,
1827        None,
1828        None,
1829    )
1830}
1831
1832fn get_bool_array_slice(
1833    array: &arrow_array::BooleanArray,
1834    indices: impl ExactSizeIterator<Item = usize>,
1835) -> Vec<bool> {
1836    let mut values = Vec::with_capacity(indices.len());
1837    for i in indices {
1838        values.push(array.value(i))
1839    }
1840    values
1841}
1842
1843/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1844/// An Arrow YearMonth interval only stores months, thus only the first 4 bytes are populated.
1845fn get_interval_ym_array_slice(
1846    array: &arrow_array::IntervalYearMonthArray,
1847    indices: impl ExactSizeIterator<Item = usize>,
1848) -> Vec<FixedLenByteArray> {
1849    chunk_array_slice(12, indices, move |i, chunk| {
1850        let value = array.value(i);
1851        chunk[0..4].copy_from_slice(&value.to_le_bytes());
1852    })
1853}
1854
1855/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1856/// An Arrow DayTime interval only stores days and millis, thus the first 4 bytes are not populated.
1857fn get_interval_dt_array_slice(
1858    array: &arrow_array::IntervalDayTimeArray,
1859    indices: impl ExactSizeIterator<Item = usize>,
1860) -> Vec<FixedLenByteArray> {
1861    chunk_array_slice(12, indices, move |i, chunk| {
1862        let value = array.value(i);
1863        chunk[4..8].copy_from_slice(&value.days.to_le_bytes());
1864        chunk[8..12].copy_from_slice(&value.milliseconds.to_le_bytes());
1865    })
1866}
1867
1868trait NativeDecimalType: DecimalType {
1869    type NativeBytes: AsRef<[u8]>;
1870
1871    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes;
1872}
1873impl NativeDecimalType for Decimal32Type {
1874    type NativeBytes = [u8; Self::BYTE_LENGTH];
1875
1876    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1877        value.to_be_bytes()
1878    }
1879}
1880impl NativeDecimalType for Decimal64Type {
1881    type NativeBytes = [u8; Self::BYTE_LENGTH];
1882
1883    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1884        value.to_be_bytes()
1885    }
1886}
1887impl NativeDecimalType for Decimal128Type {
1888    type NativeBytes = [u8; Self::BYTE_LENGTH];
1889
1890    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1891        value.to_be_bytes()
1892    }
1893}
1894impl NativeDecimalType for Decimal256Type {
1895    type NativeBytes = [u8; Self::BYTE_LENGTH];
1896
1897    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1898        value.to_be_bytes()
1899    }
1900}
1901
1902fn get_decimal_array_slice<T: NativeDecimalType>(
1903    array: &PrimitiveArray<T>,
1904    indices: impl ExactSizeIterator<Item = usize>,
1905) -> Vec<FixedLenByteArray> {
1906    let chunk_size = decimal_length_from_precision(array.precision());
1907    assert!(chunk_size <= T::BYTE_LENGTH);
1908
1909    if chunk_size == T::BYTE_LENGTH {
1910        // Special-case that allows inlining memcpy.
1911        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1912            let as_be_bytes = T::to_be_bytes(array.value(i));
1913            chunk.copy_from_slice(as_be_bytes.as_ref());
1914        })
1915    } else {
1916        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1917            let as_be_bytes = T::to_be_bytes(array.value(i));
1918            let resized_value = &as_be_bytes.as_ref()[(T::BYTE_LENGTH - chunk.len())..];
1919            chunk.copy_from_slice(resized_value);
1920        })
1921    }
1922}
1923
1924fn get_float_16_array_slice(
1925    array: &arrow_array::Float16Array,
1926    indices: impl ExactSizeIterator<Item = usize>,
1927) -> Vec<FixedLenByteArray> {
1928    chunk_array_slice(2, indices, move |i, chunk| {
1929        let value = array.value(i).to_le_bytes();
1930        chunk.copy_from_slice(&value);
1931    })
1932}
1933
1934fn get_fsb_array_slice(
1935    array: &arrow_array::FixedSizeBinaryArray,
1936    indices: impl ExactSizeIterator<Item = usize>,
1937) -> Vec<FixedLenByteArray> {
1938    chunk_array_slice(array.value_size(), indices, move |i, chunk| {
1939        let value = array.value(i);
1940        chunk.copy_from_slice(value);
1941    })
1942}
1943
1944#[inline]
1945fn chunk_array_slice(
1946    chunk_size: usize,
1947    indices: impl ExactSizeIterator<Item = usize>,
1948    writer: impl Fn(usize, &mut [u8]),
1949) -> Vec<FixedLenByteArray> {
1950    let capacity = indices.len() * chunk_size;
1951    // TODO: This could be done with Vec::spare_capacity_mut,
1952    //       but [MaybeUninit]::write_copy_of_slice is gated behind MSRV 1.93
1953    let mut arena = vec![0; capacity];
1954    for (i, chunk) in indices.zip(arena.chunks_exact_mut(chunk_size)) {
1955        writer(i, chunk);
1956    }
1957    chunk_contiguous_vec(arena, chunk_size)
1958}
1959
1960fn chunk_contiguous_vec(arena: Vec<u8>, chunk_size: usize) -> Vec<FixedLenByteArray> {
1961    let mut values = Vec::with_capacity(arena.len() / chunk_size);
1962    let mut arena = Bytes::from(arena);
1963    while arena.len() >= chunk_size {
1964        let slice = arena.split_to(chunk_size);
1965        values.push(FixedLenByteArray::from(ByteArray::from(slice)));
1966    }
1967    values
1968}
1969
1970/// Hash a byte slice to a u64 for NDV tracking.
1971#[inline]
1972fn hash_bytes(bytes: &[u8]) -> u64 {
1973    twox_hash::XxHash64::oneshot(0, bytes)
1974}
1975
1976/// Returns the fixed byte width for primitive Arrow types, or `None` for variable-length types.
1977fn fixed_byte_width(dt: &ArrowDataType) -> Option<usize> {
1978    use ArrowDataType::*;
1979    match dt {
1980        Int8 | UInt8 => Some(1),
1981        Int16 | UInt16 | Float16 => Some(2),
1982        Int32 | UInt32 | Float32 | Date32 | Time32(_) | Decimal32(_, _) => Some(4),
1983        Int64
1984        | UInt64
1985        | Float64
1986        | Date64
1987        | Time64(_)
1988        | Timestamp(_, _)
1989        | Duration(_)
1990        | Decimal64(_, _) => Some(8),
1991        Interval(IntervalUnit::YearMonth) => Some(4),
1992        Interval(IntervalUnit::DayTime) => Some(8),
1993        Interval(IntervalUnit::MonthDayNano) => Some(16),
1994        Decimal128(_, _) => Some(16),
1995        Decimal256(_, _) => Some(32),
1996        _ => None,
1997    }
1998}
1999
2000/// Hash the non-null values in `array` (at `non_null_indices`) into `seen`.
2001///
2002/// Handles primitive, boolean, fixed-size-binary, and variable-length (Utf8/Binary)
2003/// arrays. Unsupported types are silently skipped, leaving `seen` unchanged for
2004/// those values (NDV is best-effort).
2005fn update_distinct_values_seen(
2006    array: &dyn arrow_array::Array,
2007    non_null_indices: &[usize],
2008    seen: &mut DistinctValuesSet,
2009) {
2010    let data = array.to_data();
2011    let offset = data.offset();
2012
2013    match array.data_type() {
2014        ArrowDataType::Boolean => {
2015            let arr = array
2016                .as_any()
2017                .downcast_ref::<arrow_array::BooleanArray>()
2018                .unwrap();
2019            for &row in non_null_indices {
2020                seen.insert(arr.value(row) as u64);
2021            }
2022        }
2023        ArrowDataType::Utf8 | ArrowDataType::Binary => {
2024            let offsets = data.buffers()[0].typed_data::<i32>();
2025            let values = data.buffers()[1].as_slice();
2026            for &row in non_null_indices {
2027                let start = offsets[offset + row] as usize;
2028                let end = offsets[offset + row + 1] as usize;
2029                seen.insert(hash_bytes(&values[start..end]));
2030            }
2031        }
2032        ArrowDataType::LargeUtf8 | ArrowDataType::LargeBinary => {
2033            let offsets = data.buffers()[0].typed_data::<i64>();
2034            let values = data.buffers()[1].as_slice();
2035            for &row in non_null_indices {
2036                let start = offsets[offset + row] as usize;
2037                let end = offsets[offset + row + 1] as usize;
2038                seen.insert(hash_bytes(&values[start..end]));
2039            }
2040        }
2041        ArrowDataType::FixedSizeBinary(byte_width) => {
2042            let byte_width = *byte_width as usize;
2043            let buffer = data.buffers()[0].as_slice();
2044            for &row in non_null_indices {
2045                let start = (offset + row) * byte_width;
2046                seen.insert(hash_bytes(&buffer[start..start + byte_width]));
2047            }
2048        }
2049        ArrowDataType::Utf8View => {
2050            let string_view_array = array.as_string_view();
2051            for &row in non_null_indices {
2052                seen.insert(hash_bytes(string_view_array.value(row).as_bytes()));
2053            }
2054        }
2055        ArrowDataType::BinaryView => {
2056            let binary_view_array = array.as_binary_view();
2057            for &row in non_null_indices {
2058                seen.insert(hash_bytes(binary_view_array.value(row)));
2059            }
2060        }
2061        data_type => {
2062            if let Some(width) = fixed_byte_width(data_type) {
2063                let buffer = data.buffers()[0].as_slice();
2064                for &row in non_null_indices {
2065                    let pos = (offset + row) * width;
2066                    seen.insert(hash_bytes(&buffer[pos..pos + width]));
2067                }
2068            }
2069            // nested types (List, LargeList, etc.) are Parquet groups, not leaf columns: skip
2070        }
2071    }
2072}
2073
2074// Allow the helpers to use the same imports in unit and integration tests.
2075#[cfg(test)]
2076use crate as parquet_crate;
2077
2078#[cfg(test)]
2079#[path = "../../../tests/arrow_writer/roundtrip_helpers.rs"]
2080mod roundtrip_helpers;
2081
2082#[cfg(test)]
2083mod tests {
2084    use super::roundtrip_helpers::{
2085        RoundTripTest, SMALL_SIZE, required_and_optional, roundtrip_opts,
2086        roundtrip_opts_with_array_validation,
2087    };
2088    use super::*;
2089    use std::cmp::Ordering;
2090    use std::collections::HashMap;
2091
2092    use std::fs::File;
2093
2094    use crate::arrow::ARROW_SCHEMA_META_KEY;
2095    use crate::arrow::arrow_reader::{ParquetRecordBatchReader, ParquetRecordBatchReaderBuilder};
2096    use crate::column::page::{Page, PageReader};
2097    use crate::file::metadata::thrift::PageHeader;
2098    use crate::file::page_index::column_index::ColumnIndexMetaData;
2099    use crate::file::reader::SerializedPageReader;
2100    use crate::parquet_thrift::{ReadThrift, ThriftSliceInputProtocol};
2101    use crate::schema::types::ColumnPath;
2102    use arrow::datatypes::{DataType, Schema};
2103    use arrow::error::Result as ArrowResult;
2104    use arrow::util::data_gen::create_random_array;
2105    use arrow::util::pretty::pretty_format_batches;
2106    use arrow::{array::*, buffer::Buffer};
2107    use arrow_buffer::{IntervalMonthDayNano, NullBuffer};
2108    use arrow_schema::Fields;
2109
2110    use crate::basic::{Encoding, EncodingMask};
2111    use crate::data_type::AsBytes;
2112    use crate::file::metadata::{ColumnChunkMetaData, ParquetMetaData, ParquetMetaDataReader};
2113    use crate::file::properties::{
2114        BloomFilterPosition, EnabledStatistics, ReaderProperties, WriterVersion,
2115    };
2116    use crate::file::serialized_reader::ReadOptionsBuilder;
2117    use crate::file::{
2118        reader::{FileReader, SerializedFileReader},
2119        statistics::Statistics,
2120    };
2121
2122    /// A [`PageStore`] that allocates *sparse, non-contiguous* handles and keeps
2123    /// blobs in a `HashMap` — nothing like the default `Vec<Bytes>`. Used to
2124    /// prove the writer relies only on the opaque-handle contract and never on
2125    /// handles being dense `Vec` indices. Records how many blobs were stored.
2126    #[derive(Debug, Default)]
2127    struct RecordingPageStore {
2128        next: u64,
2129        blobs: HashMap<u64, Bytes>,
2130        puts: Arc<std::sync::atomic::AtomicUsize>,
2131    }
2132
2133    impl PageStore for RecordingPageStore {
2134        fn put(&mut self, value: Bytes) -> Result<PageKey> {
2135            // Deliberately non-sequential, never-zero handles.
2136            let id = 100 + self.next * 7;
2137            self.next += 1;
2138            self.puts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2139            self.blobs.insert(id, value);
2140            Ok(PageKey::new(id))
2141        }
2142
2143        fn take(&mut self, key: PageKey) -> Result<Bytes> {
2144            self.blobs
2145                .remove(&key.get())
2146                .ok_or_else(|| ParquetError::General(format!("missing key {}", key.get())))
2147        }
2148    }
2149
2150    #[derive(Debug)]
2151    struct RecordingPageStoreFactory {
2152        puts: Arc<std::sync::atomic::AtomicUsize>,
2153    }
2154
2155    impl PageStoreFactory for RecordingPageStoreFactory {
2156        fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2157            Ok(Box::new(RecordingPageStore {
2158                puts: self.puts.clone(),
2159                ..Default::default()
2160            }))
2161        }
2162    }
2163
2164    /// A custom [`PageStore`] must produce byte-identical files to the in-memory
2165    /// default, across dictionary and non-dictionary columns and multiple row
2166    /// groups (so multiple store instances are exercised).
2167    #[test]
2168    fn custom_page_store_is_byte_identical_to_default() {
2169        let schema = Arc::new(Schema::new(vec![
2170            Field::new("i", DataType::Int32, true),
2171            // A low-cardinality string column to exercise the dictionary path.
2172            Field::new("s", DataType::Utf8, true),
2173        ]));
2174        let i = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5), Some(6)]);
2175        let s = StringArray::from(vec![
2176            Some("a"),
2177            Some("bb"),
2178            Some("a"),
2179            None,
2180            Some("bb"),
2181            Some("ccc"),
2182        ]);
2183        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(i), Arc::new(s)]).unwrap();
2184
2185        // Small row groups so multiple column chunks (hence multiple store
2186        // instances) are produced.
2187        let props = WriterProperties::builder()
2188            .set_max_row_group_row_count(Some(3))
2189            .build();
2190
2191        let write = |factory: Option<Arc<dyn PageStoreFactory>>| {
2192            let mut buffer = Vec::new();
2193            let mut opts = ArrowWriterOptions::new().with_properties(props.clone());
2194            if let Some(factory) = factory {
2195                opts = opts.with_page_store_factory(factory);
2196            }
2197            let mut writer =
2198                ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2199            writer.write(&batch).unwrap();
2200            writer.close().unwrap();
2201            buffer
2202        };
2203
2204        let default_bytes = write(None);
2205
2206        let puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2207        let custom_bytes = write(Some(Arc::new(RecordingPageStoreFactory {
2208            puts: puts.clone(),
2209        })));
2210
2211        assert!(
2212            puts.load(std::sync::atomic::Ordering::Relaxed) > 0,
2213            "custom PageStore was never written to"
2214        );
2215        assert_eq!(
2216            default_bytes, custom_bytes,
2217            "a custom PageStore must produce byte-identical output to the default"
2218        );
2219    }
2220
2221    /// A dictionary-encoded column written through the deferred-ordering Arrow
2222    /// path must round-trip correctly even with the offset index disabled, when
2223    /// only the chunk-level dictionary/data page offsets are rewritten (there is
2224    /// no offset index to rebuild). Spans multiple data pages so the
2225    /// dictionary-first reordering is exercised.
2226    #[test]
2227    #[cfg_attr(miri, ignore)] // Takes too long
2228    fn dictionary_column_round_trips_with_offset_index_disabled() {
2229        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2230
2231        // Low cardinality so the column stays dictionary-encoded; enough rows to
2232        // span several data pages within a single row group.
2233        let values: Vec<Option<i32>> = (0..50_000).map(|i| Some(i % 8)).collect();
2234        let array = Int32Array::from(values.clone());
2235        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2236
2237        let props = WriterProperties::builder()
2238            .set_offset_index_disabled(true)
2239            .set_data_page_row_count_limit(4096)
2240            .build();
2241        let opts = ArrowWriterOptions::new().with_properties(props);
2242
2243        let mut buffer = Vec::new();
2244        let mut writer =
2245            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2246        writer.write(&batch).unwrap();
2247        writer.close().unwrap();
2248
2249        let reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), values.len()).unwrap();
2250        let read: Vec<RecordBatch> = reader.collect::<ArrowResult<_>>().unwrap();
2251        let read_values: Vec<Option<i32>> = read
2252            .iter()
2253            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().iter())
2254            .collect();
2255        assert_eq!(read_values, values);
2256    }
2257
2258    /// The dictionary page is routed through the [`PageStore`] like any other
2259    /// page rather than held resident in memory, so a dictionary column chunk's
2260    /// *entire* serialized size — dictionary page included — passes through the
2261    /// store.
2262    #[test]
2263    fn dictionary_page_is_routed_through_the_store() {
2264        /// A store that sums the bytes handed to `put`.
2265        #[derive(Debug, Default)]
2266        struct SizeRecordingPageStore {
2267            blobs: Vec<Bytes>,
2268            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2269        }
2270        impl PageStore for SizeRecordingPageStore {
2271            fn put(&mut self, value: Bytes) -> Result<PageKey> {
2272                self.bytes_put
2273                    .fetch_add(value.len(), std::sync::atomic::Ordering::Relaxed);
2274                let key = PageKey::new(self.blobs.len() as u64);
2275                self.blobs.push(value);
2276                Ok(key)
2277            }
2278            fn take(&mut self, key: PageKey) -> Result<Bytes> {
2279                Ok(std::mem::take(&mut self.blobs[key.get() as usize]))
2280            }
2281        }
2282        #[derive(Debug)]
2283        struct Factory {
2284            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2285        }
2286        impl PageStoreFactory for Factory {
2287            fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2288                Ok(Box::new(SizeRecordingPageStore {
2289                    bytes_put: self.bytes_put.clone(),
2290                    ..Default::default()
2291                }))
2292            }
2293        }
2294
2295        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)]));
2296        // Low cardinality keeps the column dictionary-encoded with a real,
2297        // non-empty dictionary page.
2298        let values: Vec<&str> = (0..2048)
2299            .map(|i| ["alpha", "beta", "gamma", "delta"][i % 4])
2300            .collect();
2301        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(StringArray::from(values))])
2302            .unwrap();
2303
2304        let bytes_put = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2305        let opts = ArrowWriterOptions::new().with_page_store_factory(Arc::new(Factory {
2306            bytes_put: bytes_put.clone(),
2307        }));
2308
2309        // A single batch / single column means exactly one row group and one
2310        // store instance, so the bytes it saw map to one column chunk.
2311        let mut buffer = Vec::new();
2312        let mut writer =
2313            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2314        writer.write(&batch).unwrap();
2315        writer.close().unwrap();
2316
2317        let reader = SerializedFileReader::new(Bytes::from(buffer)).unwrap();
2318        let column = reader.metadata().row_group(0).column(0);
2319        assert!(
2320            column.dictionary_page_offset().is_some(),
2321            "expected the column to be dictionary-encoded"
2322        );
2323
2324        // The bytes the store was handed must account for the whole chunk,
2325        // dictionary page included. Holding the dictionary page apart from the
2326        // store would make this fall short by the dictionary page's size.
2327        assert_eq!(
2328            bytes_put.load(std::sync::atomic::Ordering::Relaxed) as i64,
2329            column.compressed_size(),
2330            "the dictionary page must pass through the store like any other page"
2331        );
2332    }
2333
2334    fn get_bytes_after_close(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2335        let mut buffer = vec![];
2336
2337        let mut writer = ArrowWriter::try_new(&mut buffer, schema, None).unwrap();
2338        writer.write(expected_batch).unwrap();
2339        writer.close().unwrap();
2340
2341        buffer
2342    }
2343
2344    fn get_bytes_by_into_inner(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2345        let mut writer = ArrowWriter::try_new(Vec::new(), schema, None).unwrap();
2346        writer.write(expected_batch).unwrap();
2347        writer.into_inner().unwrap()
2348    }
2349
2350    #[test]
2351    fn roundtrip_bytes() {
2352        // define schema
2353        let schema = Arc::new(Schema::new(vec![
2354            Field::new("a", DataType::Int32, false),
2355            Field::new("b", DataType::Int32, true),
2356        ]));
2357
2358        // create some data
2359        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2360        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2361
2362        // build a record batch
2363        let expected_batch =
2364            RecordBatch::try_new(schema.clone(), vec![Arc::new(a), Arc::new(b)]).unwrap();
2365
2366        for buffer in [
2367            get_bytes_after_close(schema.clone(), &expected_batch),
2368            get_bytes_by_into_inner(schema, &expected_batch),
2369        ] {
2370            let cursor = Bytes::from(buffer);
2371            let mut record_batch_reader = ParquetRecordBatchReader::try_new(cursor, 1024).unwrap();
2372
2373            let actual_batch = record_batch_reader
2374                .next()
2375                .expect("No batch found")
2376                .expect("Unable to get batch");
2377
2378            assert_eq!(expected_batch.schema(), actual_batch.schema());
2379            assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
2380            assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
2381            for i in 0..expected_batch.num_columns() {
2382                let expected_data = expected_batch.column(i).to_data();
2383                let actual_data = actual_batch.column(i).to_data();
2384
2385                assert_eq!(expected_data, actual_data);
2386            }
2387        }
2388    }
2389
2390    #[test]
2391    fn arrow_writer_page_size() {
2392        let schema = Arc::new(Schema::new(vec![Field::new("col", DataType::Utf8, false)]));
2393
2394        let mut builder = StringBuilder::with_capacity(100, 329 * 10_000);
2395
2396        // Generate an array of 10 unique 10 character string
2397        for i in 0..10 {
2398            let value = i
2399                .to_string()
2400                .repeat(10)
2401                .chars()
2402                .take(10)
2403                .collect::<String>();
2404
2405            builder.append_value(value);
2406        }
2407
2408        let array = Arc::new(builder.finish());
2409
2410        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
2411
2412        let file = tempfile::tempfile().unwrap();
2413
2414        // Set everything very low so we fallback to PLAIN encoding after the first row
2415        let props = WriterProperties::builder()
2416            .set_data_page_size_limit(1)
2417            .set_dictionary_page_size_limit(1)
2418            .set_write_batch_size(1)
2419            .build();
2420
2421        let mut writer =
2422            ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), Some(props))
2423                .expect("Unable to write file");
2424        writer.write(&batch).unwrap();
2425        writer.close().unwrap();
2426
2427        let options = ReadOptionsBuilder::new().with_page_index().build();
2428        let reader =
2429            SerializedFileReader::new_with_options(file.try_clone().unwrap(), options).unwrap();
2430
2431        let column = reader.metadata().row_group(0).columns();
2432
2433        assert_eq!(column.len(), 1);
2434
2435        // We should write one row before falling back to PLAIN encoding so there should still be a
2436        // dictionary page.
2437        assert!(
2438            column[0].dictionary_page_offset().is_some(),
2439            "Expected a dictionary page"
2440        );
2441
2442        let page_index = reader
2443            .metadata()
2444            .page_index()
2445            .expect("page index should be present");
2446        let page_locations = page_index
2447            .page_locations(0, 0)
2448            .expect("page locations should exist");
2449
2450        // We should fallback to PLAIN encoding after the first row and our max page size is 1 bytes
2451        // so we expect one dictionary encoded page and then a page per row thereafter.
2452        assert_eq!(
2453            page_locations.len(),
2454            10,
2455            "Expected 10 pages but got {page_locations:#?}"
2456        );
2457    }
2458
2459    const MEDIUM_SIZE: usize = 63;
2460
2461    fn check_bloom_filter<T: AsBytes>(
2462        files: Vec<Bytes>,
2463        file_column: String,
2464        positive_values: Vec<T>,
2465        negative_values: Vec<T>,
2466    ) {
2467        files.into_iter().take(1).for_each(|file| {
2468            let file_reader = SerializedFileReader::new_with_options(
2469                file,
2470                ReadOptionsBuilder::new()
2471                    .with_reader_properties(
2472                        ReaderProperties::builder()
2473                            .set_read_bloom_filter(true)
2474                            .build(),
2475                    )
2476                    .build(),
2477            )
2478            .expect("Unable to open file as Parquet");
2479            let metadata = file_reader.metadata();
2480
2481            // Gets bloom filters from all row groups.
2482            let mut bloom_filters: Vec<_> = vec![];
2483            for (ri, row_group) in metadata.row_groups().iter().enumerate() {
2484                if let Some((column_index, _)) = row_group
2485                    .columns()
2486                    .iter()
2487                    .enumerate()
2488                    .find(|(_, column)| column.column_path().string() == file_column)
2489                {
2490                    let row_group_reader = file_reader
2491                        .get_row_group(ri)
2492                        .expect("Unable to read row group");
2493                    if let Some(sbbf) = row_group_reader.get_column_bloom_filter(column_index) {
2494                        bloom_filters.push(sbbf.clone());
2495                    } else {
2496                        panic!("No bloom filter for column named {file_column} found");
2497                    }
2498                } else {
2499                    panic!("No column named {file_column} found");
2500                }
2501            }
2502
2503            positive_values.iter().for_each(|value| {
2504                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
2505                assert!(
2506                    found.is_some(),
2507                    "{}",
2508                    format!("Value {:?} should be in bloom filter", value.as_bytes())
2509                );
2510            });
2511
2512            negative_values.iter().for_each(|value| {
2513                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
2514                assert!(
2515                    found.is_none(),
2516                    "{}",
2517                    format!("Value {:?} should not be in bloom filter", value.as_bytes())
2518                );
2519            });
2520        });
2521    }
2522
2523    #[test]
2524    #[cfg_attr(miri, ignore)] // Takes too long
2525    fn bool_large_single_column() {
2526        let values = Arc::new(
2527            [None, Some(true), Some(false)]
2528                .iter()
2529                .cycle()
2530                .copied()
2531                .take(200_000)
2532                .collect::<BooleanArray>(),
2533        );
2534        let schema = Schema::new(vec![Field::new("col", values.data_type().clone(), true)]);
2535        let expected_batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
2536        let file = tempfile::tempfile().unwrap();
2537
2538        let mut writer =
2539            ArrowWriter::try_new(file.try_clone().unwrap(), expected_batch.schema(), None)
2540                .expect("Unable to write file");
2541        writer.write(&expected_batch).unwrap();
2542        writer.close().unwrap();
2543    }
2544
2545    #[test]
2546    fn check_page_offset_index_with_nan() {
2547        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
2548        let schema = Schema::new(vec![Field::new("col", DataType::Float64, true)]);
2549        let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
2550
2551        let mut out = Vec::with_capacity(1024);
2552        let mut writer =
2553            ArrowWriter::try_new(&mut out, batch.schema(), None).expect("Unable to write file");
2554        writer.write(&batch).unwrap();
2555        let file_meta_data = writer.close().unwrap();
2556        for row_group in file_meta_data.row_groups() {
2557            for column in row_group.columns() {
2558                assert!(column.offset_index_offset().is_some());
2559                assert!(column.offset_index_length().is_some());
2560                assert!(column.column_index_offset().is_some());
2561                assert!(column.column_index_length().is_some());
2562            }
2563        }
2564        if let Some(page_index) = file_meta_data.page_index() {
2565            for rg in 0..file_meta_data.num_row_groups() {
2566                for col in 0..file_meta_data.row_group(rg).num_columns() {
2567                    let idx = page_index
2568                        .column_index(rg, col)
2569                        .expect("column index should exist");
2570                    assert!(idx.nan_counts().is_some());
2571                    let ColumnIndexMetaData::DOUBLE(float_idx) = idx else {
2572                        panic!("expected double statistics")
2573                    };
2574                    for i in 0..idx.num_pages() as usize {
2575                        assert_eq!(float_idx.nan_count(i), Some(10));
2576                        assert_eq!(
2577                            f64::NAN.total_cmp(float_idx.min_value(i).unwrap()),
2578                            Ordering::Equal
2579                        );
2580                        assert_eq!(
2581                            f64::NAN.total_cmp(float_idx.max_value(i).unwrap()),
2582                            Ordering::Equal
2583                        );
2584                    }
2585                }
2586            }
2587        } else {
2588            panic!("page index should be present");
2589        }
2590    }
2591
2592    #[test]
2593    fn check_page_offset_index_with_mixed_nan() {
2594        let schema = Arc::new(Schema::new(vec![Field::new(
2595            "col",
2596            DataType::Float64,
2597            true,
2598        )]));
2599
2600        let mut out = Vec::with_capacity(1024);
2601        let props = WriterProperties::builder()
2602            .set_data_page_row_count_limit(10)
2603            .build();
2604        let mut writer = ArrowWriter::try_new(&mut out, schema.clone(), Some(props))
2605            .expect("Unable to write file");
2606
2607        // write a page of all NaN (since batch min and max are NaN, global min/max are NaN)
2608        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
2609        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2610        writer.write(&batch).unwrap();
2611
2612        // write a page of all -NaN (batch min/max is -NaN, should update global min to -NaN)
2613        let values = Arc::new(Float64Array::from(vec![-f64::NAN; 10]));
2614        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2615        writer.write(&batch).unwrap();
2616
2617        // write a page of all 0 (non-NaN should override global min/max, now 0/0)
2618        let values = Arc::new(Float64Array::from(vec![0_f64; 10]));
2619        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2620        writer.write(&batch).unwrap();
2621
2622        // write a mixed page (should now have min -1, max 1)
2623        let values = Arc::new(Float64Array::from(vec![
2624            -1.0,
2625            0.0,
2626            f64::NAN,
2627            -f64::NAN,
2628            1.0,
2629        ]));
2630        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
2631        writer.write(&batch).unwrap();
2632
2633        let file_meta_data = writer.close().unwrap();
2634
2635        // check the column chunk stats are correct
2636        let col_stats = file_meta_data
2637            .row_group(0)
2638            .column(0)
2639            .statistics()
2640            .expect("missing column chunk statistics");
2641
2642        assert_eq!(col_stats.nan_count_opt(), Some(22));
2643        assert_eq!(col_stats.min_bytes_opt(), Some((-1.0f64).as_bytes()));
2644        assert_eq!(col_stats.max_bytes_opt(), Some(1.0f64.as_bytes()));
2645
2646        assert!(file_meta_data.page_index().is_some());
2647        let col_idx = &file_meta_data.page_index().unwrap().column_index(0, 0);
2648        assert_eq!(col_idx.as_ref().unwrap().num_pages(), 4);
2649
2650        // test each page
2651        let Some(ColumnIndexMetaData::DOUBLE(float_idx)) = col_idx else {
2652            panic!("expected double statistics")
2653        };
2654
2655        assert_eq!(float_idx.nan_counts, Some(vec![10, 10, 0, 2]));
2656        assert_eq!(
2657            f64::NAN.total_cmp(float_idx.min_value(0).unwrap()),
2658            Ordering::Equal
2659        );
2660        assert_eq!(
2661            f64::NAN.total_cmp(float_idx.max_value(0).unwrap()),
2662            Ordering::Equal
2663        );
2664        assert_eq!(
2665            (-f64::NAN).total_cmp(float_idx.min_value(1).unwrap()),
2666            Ordering::Equal
2667        );
2668        assert_eq!(
2669            (-f64::NAN).total_cmp(float_idx.max_value(1).unwrap()),
2670            Ordering::Equal
2671        );
2672        assert_eq!(float_idx.min_value(2), Some(&0.0));
2673        assert_eq!(float_idx.max_value(2), Some(&0.0));
2674        assert_eq!(float_idx.min_value(3), Some(&-1.0));
2675        assert_eq!(float_idx.max_value(3), Some(&1.0));
2676    }
2677
2678    #[test]
2679    #[should_panic(
2680        expected = "Attempting to write an Arrow interval type MonthDayNano to parquet that is not yet implemented"
2681    )]
2682    fn interval_month_day_nano_single_column() {
2683        required_and_optional::<IntervalMonthDayNanoArray, _>(vec![
2684            IntervalMonthDayNano::new(0, 1, 5),
2685            IntervalMonthDayNano::new(0, 3, 2),
2686            IntervalMonthDayNano::new(3, -2, -5),
2687            IntervalMonthDayNano::new(-200, 4, -1),
2688        ]);
2689    }
2690
2691    #[test]
2692    #[cfg_attr(miri, ignore)] // Takes too long
2693    fn i32_column_bloom_filter_at_end() {
2694        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2695        let files = RoundTripTest::new(array)
2696            .with_nullable(false)
2697            .with_bloom_filter(true)
2698            .with_bloom_filter_position(BloomFilterPosition::End)
2699            .run();
2700
2701        check_bloom_filter(
2702            files,
2703            "col".to_string(),
2704            (0..SMALL_SIZE as i32).collect(),
2705            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2706        );
2707    }
2708
2709    #[test]
2710    #[cfg_attr(miri, ignore)] // Takes too long
2711    fn i32_column_bloom_filter() {
2712        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2713        let files = RoundTripTest::new(array)
2714            .with_nullable(false)
2715            .with_bloom_filter(true)
2716            .run();
2717
2718        check_bloom_filter(
2719            files,
2720            "col".to_string(),
2721            (0..SMALL_SIZE as i32).collect(),
2722            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2723        );
2724    }
2725
2726    fn write_with_bloom_filter(array: ArrayRef, dictionary_page_size_limit: usize) -> Bytes {
2727        let schema = Arc::new(Schema::new(vec![Field::new(
2728            "col",
2729            array.data_type().clone(),
2730            false,
2731        )]));
2732        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
2733        let props = WriterProperties::builder()
2734            .set_dictionary_enabled(true)
2735            .set_dictionary_page_size_limit(dictionary_page_size_limit)
2736            .set_write_batch_size(256)
2737            .set_bloom_filter_enabled(true)
2738            .build();
2739        let mut buf = Vec::new();
2740        let mut writer = ArrowWriter::try_new(&mut buf, schema, Some(props)).unwrap();
2741        writer.write(&batch).unwrap();
2742        writer.close().unwrap();
2743        Bytes::from(buf)
2744    }
2745
2746    fn data_page_encoding_mask(file: &Bytes) -> EncodingMask {
2747        let metadata = ParquetMetaDataReader::new().parse_and_finish(file).unwrap();
2748        *metadata
2749            .row_group(0)
2750            .column(0)
2751            .page_encoding_stats_mask()
2752            .unwrap()
2753    }
2754
2755    /// While a column is dictionary encoded the bloom filter is populated from the dictionary
2756    /// when it is flushed, so a chunk that stays dictionary encoded must still contain every value.
2757    #[test]
2758    fn string_column_bloom_filter_populated_from_dictionary() {
2759        let values: Vec<String> = (0..2000).map(|i| format!("value-{}", i % 10)).collect();
2760        let array = Arc::new(StringArray::from_iter_values(&values));
2761        let file = write_with_bloom_filter(array, 1024 * 1024);
2762        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
2763
2764        check_bloom_filter(
2765            vec![file],
2766            "col".to_string(),
2767            (0..10).map(|i| format!("value-{i}").into_bytes()).collect(),
2768            (10..20)
2769                .map(|i| format!("value-{i}").into_bytes())
2770                .collect(),
2771        );
2772    }
2773
2774    /// After falling back from dictionary encoding the filter holds the dictionary's values
2775    /// and every value written plain afterwards.
2776    #[test]
2777    fn string_column_bloom_filter_across_dictionary_fallback() {
2778        let values: Vec<String> = (0..2000).map(|i| format!("value-{i}")).collect();
2779        let array = Arc::new(StringArray::from_iter_values(&values));
2780        let file = write_with_bloom_filter(array, 1024);
2781        let encodings = data_page_encoding_mask(&file);
2782        assert!(
2783            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
2784            "expected dictionary and plain data pages, got {encodings:?}"
2785        );
2786
2787        check_bloom_filter(
2788            vec![file],
2789            "col".to_string(),
2790            values.into_iter().map(String::into_bytes).collect(),
2791            (2000..2010)
2792                .map(|i| format!("value-{i}").into_bytes())
2793                .collect(),
2794        );
2795    }
2796
2797    #[test]
2798    fn i64_column_bloom_filter_populated_from_dictionary() {
2799        let array = Arc::new(Int64Array::from_iter_values((0..2000).map(|i| i % 10)));
2800        let file = write_with_bloom_filter(array, 1024 * 1024);
2801        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
2802
2803        check_bloom_filter(
2804            vec![file],
2805            "col".to_string(),
2806            (0..10i64).collect(),
2807            (10..20i64).collect(),
2808        );
2809    }
2810
2811    #[test]
2812    fn i64_column_bloom_filter_across_dictionary_fallback() {
2813        let array = Arc::new(Int64Array::from_iter_values(0..2000i64));
2814        let file = write_with_bloom_filter(array, 1024);
2815        let encodings = data_page_encoding_mask(&file);
2816        assert!(
2817            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
2818            "expected dictionary and plain data pages, got {encodings:?}"
2819        );
2820
2821        check_bloom_filter(
2822            vec![file],
2823            "col".to_string(),
2824            (0..2000i64).collect(),
2825            (2000..2010i64).collect(),
2826        );
2827    }
2828
2829    /// Test that bloom filter folding produces correct results even when
2830    /// the configured NDV differs significantly from actual NDV.
2831    /// A large NDV means a larger initial filter that gets folded down;
2832    /// a small NDV means a smaller initial filter.
2833    #[test]
2834    #[cfg_attr(miri, ignore)] // Takes too long
2835    fn i32_column_bloom_filter_fixed_ndv() {
2836        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
2837
2838        // NDV much larger than actual distinct values — tests folding a large filter down
2839        let files = RoundTripTest::new(array.clone())
2840            .with_nullable(false)
2841            .with_bloom_filter(true)
2842            .with_bloom_filter_ndv(1_000_000)
2843            .run();
2844
2845        check_bloom_filter(
2846            files,
2847            "col".to_string(),
2848            (0..SMALL_SIZE as i32).collect(),
2849            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2850        );
2851
2852        // NDV smaller than actual distinct values — tests the underestimate path
2853        let files = RoundTripTest::new(array)
2854            .with_nullable(false)
2855            .with_bloom_filter(true)
2856            .with_bloom_filter_ndv(3)
2857            .run();
2858
2859        check_bloom_filter(
2860            files,
2861            "col".to_string(),
2862            (0..SMALL_SIZE as i32).collect(),
2863            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
2864        );
2865    }
2866
2867    #[test]
2868    #[cfg_attr(miri, ignore)] // Takes too long
2869    fn binary_column_bloom_filter() {
2870        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
2871        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
2872        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
2873
2874        let array = Arc::new(BinaryArray::from_iter_values(many_vecs_iter));
2875        let files = RoundTripTest::new(array)
2876            .with_nullable(false)
2877            .with_bloom_filter(true)
2878            .run();
2879
2880        check_bloom_filter(
2881            files,
2882            "col".to_string(),
2883            many_vecs,
2884            vec![vec![(SMALL_SIZE + 1) as u8]],
2885        );
2886    }
2887
2888    #[test]
2889    #[cfg_attr(miri, ignore)] // Takes too long
2890    fn empty_string_null_column_bloom_filter() {
2891        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
2892        let raw_strs = raw_values.iter().map(|s| s.as_str());
2893
2894        let array = Arc::new(StringArray::from_iter_values(raw_strs));
2895        let files = RoundTripTest::new(array)
2896            .with_nullable(false)
2897            .with_bloom_filter(true)
2898            .run();
2899
2900        let optional_raw_values: Vec<_> = raw_values
2901            .iter()
2902            .enumerate()
2903            .filter_map(|(i, v)| if i % 2 == 0 { None } else { Some(v.as_str()) })
2904            .collect();
2905        // For null slots, empty string should not be in bloom filter.
2906        check_bloom_filter(files, "col".to_string(), optional_raw_values, vec![""]);
2907    }
2908
2909    #[test]
2910    fn list_and_map_coerced_names() {
2911        // Create map and list with non-Parquet naming
2912        let list_field =
2913            Field::new_list("my_list", Field::new("item", DataType::Int32, false), false);
2914        let map_field = Field::new_map(
2915            "my_map",
2916            "my_entries",
2917            Field::new("my_keys", DataType::Int32, false),
2918            Field::new("my_values", DataType::Int32, true),
2919            false,
2920            true,
2921        );
2922
2923        let list_array = create_random_array(&list_field, 100, 0.0, 0.0).unwrap();
2924        let map_array = create_random_array(&map_field, 100, 0.0, 0.0).unwrap();
2925
2926        let arrow_schema = Arc::new(Schema::new(vec![list_field, map_field]));
2927
2928        // Write data to Parquet but coerce names to match spec
2929        let props = Some(WriterProperties::builder().set_coerce_types(true).build());
2930        let file = tempfile::tempfile().unwrap();
2931        let mut writer =
2932            ArrowWriter::try_new(file.try_clone().unwrap(), arrow_schema.clone(), props).unwrap();
2933
2934        let batch = RecordBatch::try_new(arrow_schema, vec![list_array, map_array]).unwrap();
2935        writer.write(&batch).unwrap();
2936        let file_metadata = writer.close().unwrap();
2937
2938        let schema = file_metadata.file_metadata().schema();
2939        // Coerced name of "item" should be "element"
2940        let list_field = &schema.get_fields()[0].get_fields()[0];
2941        assert_eq!(list_field.get_fields()[0].name(), "element");
2942
2943        let map_field = &schema.get_fields()[1].get_fields()[0];
2944        // Coerced name of "entries" should be "key_value"
2945        assert_eq!(map_field.name(), "key_value");
2946        // Coerced name of "my_keys" should be "key"
2947        assert_eq!(map_field.get_fields()[0].name(), "key");
2948        // Coerced name of "my_values" should be "value"
2949        assert_eq!(map_field.get_fields()[1].name(), "value");
2950
2951        // Double check schema after reading from the file
2952        let reader = SerializedFileReader::new(file).unwrap();
2953        let file_schema = reader.metadata().file_metadata().schema();
2954        let fields = file_schema.get_fields();
2955        let list_field = &fields[0].get_fields()[0];
2956        assert_eq!(list_field.get_fields()[0].name(), "element");
2957        let map_field = &fields[1].get_fields()[0];
2958        assert_eq!(map_field.name(), "key_value");
2959        assert_eq!(map_field.get_fields()[0].name(), "key");
2960        assert_eq!(map_field.get_fields()[1].name(), "value");
2961    }
2962
2963    #[test]
2964    #[cfg_attr(miri, ignore)] // Takes too long
2965    fn fallback_flush_data_page() {
2966        //tests if the Fallback::flush_data_page clears all buffers correctly
2967        let raw_values: Vec<_> = (0..MEDIUM_SIZE).map(|i| i.to_string()).collect();
2968        let values = Arc::new(StringArray::from(raw_values));
2969        let encodings = vec![
2970            Encoding::DELTA_BYTE_ARRAY,
2971            Encoding::DELTA_LENGTH_BYTE_ARRAY,
2972        ];
2973        let data_type = values.data_type().clone();
2974        let schema = Arc::new(Schema::new(vec![Field::new("col", data_type, false)]));
2975        let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
2976
2977        let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
2978        let data_page_size_limit: usize = 32;
2979        let write_batch_size: usize = 16;
2980
2981        for encoding in &encodings {
2982            for row_group_size in row_group_sizes {
2983                let props = WriterProperties::builder()
2984                    .set_writer_version(WriterVersion::PARQUET_2_0)
2985                    .set_max_row_group_row_count(Some(row_group_size))
2986                    .set_dictionary_enabled(false)
2987                    .set_encoding(*encoding)
2988                    .set_data_page_size_limit(data_page_size_limit)
2989                    .set_write_batch_size(write_batch_size)
2990                    .build();
2991
2992                roundtrip_opts_with_array_validation(&expected_batch, props, |a, b| {
2993                    let string_array_a = StringArray::from(a.clone());
2994                    let string_array_b = StringArray::from(b.clone());
2995                    let vec_a: Vec<&str> = string_array_a.iter().map(|v| v.unwrap()).collect();
2996                    let vec_b: Vec<&str> = string_array_b.iter().map(|v| v.unwrap()).collect();
2997                    assert_eq!(
2998                        vec_a, vec_b,
2999                        "failed for encoder: {encoding:?} and row_group_size: {row_group_size:?}"
3000                    );
3001                });
3002            }
3003        }
3004    }
3005
3006    #[test]
3007    #[cfg_attr(miri, ignore)] // Takes too long
3008    fn u32_min_max() {
3009        // check values roundtrip through parquet
3010        let src = [
3011            u32::MIN,
3012            1,
3013            (i32::MAX as u32) - 1,
3014            i32::MAX as u32,
3015            (i32::MAX as u32) + 1,
3016            u32::MAX - 1,
3017            u32::MAX,
3018        ];
3019        let values = Arc::new(UInt32Array::from_iter_values(src.iter().copied()));
3020        let files = RoundTripTest::new(values).with_nullable(false).run();
3021
3022        for file in files {
3023            // check statistics are valid
3024            let reader = SerializedFileReader::new(file).unwrap();
3025            let metadata = reader.metadata();
3026
3027            let mut row_offset = 0;
3028            for row_group in metadata.row_groups() {
3029                assert_eq!(row_group.num_columns(), 1);
3030                let column = row_group.column(0);
3031
3032                let num_values = column.num_values() as usize;
3033                let src_slice = &src[row_offset..row_offset + num_values];
3034                row_offset += column.num_values() as usize;
3035
3036                let stats = column.statistics().unwrap();
3037                if let Statistics::Int32(stats) = stats {
3038                    assert_eq!(
3039                        *stats.min_opt().unwrap() as u32,
3040                        *src_slice.iter().min().unwrap()
3041                    );
3042                    assert_eq!(
3043                        *stats.max_opt().unwrap() as u32,
3044                        *src_slice.iter().max().unwrap()
3045                    );
3046                } else {
3047                    panic!("Statistics::Int32 missing")
3048                }
3049            }
3050        }
3051    }
3052
3053    #[test]
3054    #[cfg_attr(miri, ignore)] // Takes too long
3055    fn u64_min_max() {
3056        // check values roundtrip through parquet
3057        let src = [
3058            u64::MIN,
3059            1,
3060            (i64::MAX as u64) - 1,
3061            i64::MAX as u64,
3062            (i64::MAX as u64) + 1,
3063            u64::MAX - 1,
3064            u64::MAX,
3065        ];
3066        let values = Arc::new(UInt64Array::from_iter_values(src.iter().copied()));
3067        let files = RoundTripTest::new(values).with_nullable(false).run();
3068
3069        for file in files {
3070            // check statistics are valid
3071            let reader = SerializedFileReader::new(file).unwrap();
3072            let metadata = reader.metadata();
3073
3074            let mut row_offset = 0;
3075            for row_group in metadata.row_groups() {
3076                assert_eq!(row_group.num_columns(), 1);
3077                let column = row_group.column(0);
3078
3079                let num_values = column.num_values() as usize;
3080                let src_slice = &src[row_offset..row_offset + num_values];
3081                row_offset += column.num_values() as usize;
3082
3083                let stats = column.statistics().unwrap();
3084                if let Statistics::Int64(stats) = stats {
3085                    assert_eq!(
3086                        *stats.min_opt().unwrap() as u64,
3087                        *src_slice.iter().min().unwrap()
3088                    );
3089                    assert_eq!(
3090                        *stats.max_opt().unwrap() as u64,
3091                        *src_slice.iter().max().unwrap()
3092                    );
3093                } else {
3094                    panic!("Statistics::Int64 missing")
3095                }
3096            }
3097        }
3098    }
3099
3100    #[test]
3101    #[cfg_attr(miri, ignore)] // Takes too long
3102    fn statistics_null_counts_only_nulls() {
3103        // check that null-count statistics for "only NULL"-columns are correct
3104        let values = Arc::new(UInt64Array::from(vec![None, None]));
3105        let files = RoundTripTest::new(values).run();
3106
3107        for file in files {
3108            // check statistics are valid
3109            let reader = SerializedFileReader::new(file).unwrap();
3110            let metadata = reader.metadata();
3111            assert_eq!(metadata.num_row_groups(), 1);
3112            let row_group = metadata.row_group(0);
3113            assert_eq!(row_group.num_columns(), 1);
3114            let column = row_group.column(0);
3115            let stats = column.statistics().unwrap();
3116            assert_eq!(stats.null_count_opt(), Some(2));
3117        }
3118    }
3119
3120    fn row_group_sizes(metadata: &ParquetMetaData) -> Vec<i64> {
3121        metadata.row_groups().iter().map(|x| x.num_rows()).collect()
3122    }
3123
3124    #[test]
3125    fn test_aggregates_records() {
3126        let arrays = [
3127            Int32Array::from((0..100).collect::<Vec<_>>()),
3128            Int32Array::from((0..50).collect::<Vec<_>>()),
3129            Int32Array::from((200..500).collect::<Vec<_>>()),
3130        ];
3131
3132        let schema = Arc::new(Schema::new(vec![Field::new(
3133            "int",
3134            ArrowDataType::Int32,
3135            false,
3136        )]));
3137
3138        let file = tempfile::tempfile().unwrap();
3139
3140        let props = WriterProperties::builder()
3141            .set_max_row_group_row_count(Some(200))
3142            .build();
3143
3144        let mut writer =
3145            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
3146
3147        for array in arrays {
3148            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
3149            writer.write(&batch).unwrap();
3150        }
3151
3152        writer.close().unwrap();
3153
3154        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
3155        assert_eq!(&row_group_sizes(builder.metadata()), &[200, 200, 50]);
3156
3157        let batches = builder
3158            .with_batch_size(100)
3159            .build()
3160            .unwrap()
3161            .collect::<ArrowResult<Vec<_>>>()
3162            .unwrap();
3163
3164        assert_eq!(batches.len(), 5);
3165        assert!(batches.iter().all(|x| x.num_columns() == 1));
3166
3167        let batch_sizes: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
3168
3169        assert_eq!(&batch_sizes, &[100, 100, 100, 100, 50]);
3170
3171        let values: Vec<_> = batches
3172            .iter()
3173            .flat_map(|x| {
3174                x.column(0)
3175                    .as_any()
3176                    .downcast_ref::<Int32Array>()
3177                    .unwrap()
3178                    .values()
3179                    .iter()
3180                    .copied()
3181            })
3182            .collect();
3183
3184        let expected_values: Vec<_> = [0..100, 0..50, 200..500].into_iter().flatten().collect();
3185        assert_eq!(&values, &expected_values)
3186    }
3187
3188    #[test]
3189    fn complex_aggregate() {
3190        // Tests aggregating nested data
3191        let field_a = Arc::new(Field::new("leaf_a", DataType::Int32, false));
3192        let field_b = Arc::new(Field::new("leaf_b", DataType::Int32, true));
3193        let struct_a = Arc::new(Field::new(
3194            "struct_a",
3195            DataType::Struct(vec![field_a.clone(), field_b.clone()].into()),
3196            true,
3197        ));
3198
3199        let list_a = Arc::new(Field::new("list", DataType::List(struct_a), true));
3200        let struct_b = Arc::new(Field::new(
3201            "struct_b",
3202            DataType::Struct(vec![list_a.clone()].into()),
3203            false,
3204        ));
3205
3206        let schema = Arc::new(Schema::new(vec![struct_b]));
3207
3208        // create nested data
3209        let field_a_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
3210        let field_b_array =
3211            Int32Array::from_iter(vec![Some(1), None, Some(2), None, None, Some(6)]);
3212
3213        let struct_a_array = StructArray::from(vec![
3214            (field_a.clone(), Arc::new(field_a_array) as ArrayRef),
3215            (field_b.clone(), Arc::new(field_b_array) as ArrayRef),
3216        ]);
3217
3218        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3219            .len(5)
3220            .add_buffer(Buffer::from_iter(vec![
3221                0_i32, 1_i32, 1_i32, 3_i32, 3_i32, 5_i32,
3222            ]))
3223            .null_bit_buffer(Some(Buffer::from_iter(vec![
3224                true, false, true, false, true,
3225            ])))
3226            .child_data(vec![struct_a_array.into_data()])
3227            .build()
3228            .unwrap();
3229
3230        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3231        let struct_b_array = StructArray::from(vec![(list_a.clone(), list_a_array)]);
3232
3233        let batch1 =
3234            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3235                .unwrap();
3236
3237        let field_a_array = Int32Array::from(vec![6, 7, 8, 9, 10]);
3238        let field_b_array = Int32Array::from_iter(vec![None, None, None, Some(1), None]);
3239
3240        let struct_a_array = StructArray::from(vec![
3241            (field_a, Arc::new(field_a_array) as ArrayRef),
3242            (field_b, Arc::new(field_b_array) as ArrayRef),
3243        ]);
3244
3245        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
3246            .len(2)
3247            .add_buffer(Buffer::from_iter(vec![0_i32, 4_i32, 5_i32]))
3248            .child_data(vec![struct_a_array.into_data()])
3249            .build()
3250            .unwrap();
3251
3252        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
3253        let struct_b_array = StructArray::from(vec![(list_a, list_a_array)]);
3254
3255        let batch2 =
3256            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
3257                .unwrap();
3258
3259        let batches = &[batch1, batch2];
3260
3261        // Verify data is as expected
3262
3263        let expected = r"
3264            +-------------------------------------------------------------------------------------------------------+
3265            | struct_b                                                                                              |
3266            +-------------------------------------------------------------------------------------------------------+
3267            | {list: [{leaf_a: 1, leaf_b: 1}]}                                                                      |
3268            | {list: }                                                                                              |
3269            | {list: [{leaf_a: 2, leaf_b: }, {leaf_a: 3, leaf_b: 2}]}                                               |
3270            | {list: }                                                                                              |
3271            | {list: [{leaf_a: 4, leaf_b: }, {leaf_a: 5, leaf_b: }]}                                                |
3272            | {list: [{leaf_a: 6, leaf_b: }, {leaf_a: 7, leaf_b: }, {leaf_a: 8, leaf_b: }, {leaf_a: 9, leaf_b: 1}]} |
3273            | {list: [{leaf_a: 10, leaf_b: }]}                                                                      |
3274            +-------------------------------------------------------------------------------------------------------+
3275        ".trim().split('\n').map(|x| x.trim()).collect::<Vec<_>>().join("\n");
3276
3277        let actual = pretty_format_batches(batches).unwrap().to_string();
3278        assert_eq!(actual, expected);
3279
3280        // Write data
3281        let file = tempfile::tempfile().unwrap();
3282        let props = WriterProperties::builder()
3283            .set_max_row_group_row_count(Some(6))
3284            .build();
3285
3286        let mut writer =
3287            ArrowWriter::try_new(file.try_clone().unwrap(), schema, Some(props)).unwrap();
3288
3289        for batch in batches {
3290            writer.write(batch).unwrap();
3291        }
3292        writer.close().unwrap();
3293
3294        // Read Data
3295        // Should have written entire first batch and first row of second to the first row group
3296        // leaving a single row in the second row group
3297
3298        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
3299        assert_eq!(&row_group_sizes(builder.metadata()), &[6, 1]);
3300
3301        let batches = builder
3302            .with_batch_size(2)
3303            .build()
3304            .unwrap()
3305            .collect::<ArrowResult<Vec<_>>>()
3306            .unwrap();
3307
3308        assert_eq!(batches.len(), 4);
3309        let batch_counts: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
3310        assert_eq!(&batch_counts, &[2, 2, 2, 1]);
3311
3312        let actual = pretty_format_batches(&batches).unwrap().to_string();
3313        assert_eq!(actual, expected);
3314    }
3315
3316    #[test]
3317    fn test_arrow_writer_metadata() {
3318        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3319        let file_schema = batch_schema.clone().with_metadata([("foo", "bar")]);
3320
3321        let batch = RecordBatch::try_new(
3322            Arc::new(batch_schema),
3323            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3324        )
3325        .unwrap();
3326
3327        let mut buf = Vec::with_capacity(1024);
3328        let mut writer = ArrowWriter::try_new(&mut buf, Arc::new(file_schema), None).unwrap();
3329        writer.write(&batch).unwrap();
3330        writer.close().unwrap();
3331    }
3332
3333    #[test]
3334    fn in_progress_accounting() {
3335        // define schema
3336        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3337
3338        // create some data
3339        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3340
3341        // build a record batch
3342        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
3343
3344        let mut writer = ArrowWriter::try_new(vec![], batch.schema(), None).unwrap();
3345
3346        // starts empty
3347        assert_eq!(writer.in_progress_size(), 0);
3348        assert_eq!(writer.in_progress_rows(), 0);
3349        assert_eq!(writer.memory_size(), 0);
3350        assert_eq!(writer.bytes_written(), 4); // Initial header
3351        writer.write(&batch).unwrap();
3352
3353        // updated on write
3354        let initial_size = writer.in_progress_size();
3355        assert!(initial_size > 0);
3356        assert_eq!(writer.in_progress_rows(), 5);
3357        let initial_memory = writer.memory_size();
3358        assert!(initial_memory > 0);
3359        // memory estimate is larger than estimated encoded size
3360        assert!(
3361            initial_size <= initial_memory,
3362            "{initial_size} <= {initial_memory}"
3363        );
3364
3365        // updated on second write
3366        writer.write(&batch).unwrap();
3367        assert!(writer.in_progress_size() > initial_size);
3368        assert_eq!(writer.in_progress_rows(), 10);
3369        assert!(writer.memory_size() > initial_memory);
3370        assert!(
3371            writer.in_progress_size() <= writer.memory_size(),
3372            "in_progress_size {} <= memory_size {}",
3373            writer.in_progress_size(),
3374            writer.memory_size()
3375        );
3376
3377        // in progress tracking is cleared, but the overall data written is updated
3378        let pre_flush_bytes_written = writer.bytes_written();
3379        writer.flush().unwrap();
3380        assert_eq!(writer.in_progress_size(), 0);
3381        assert_eq!(writer.memory_size(), 0);
3382        assert!(writer.bytes_written() > pre_flush_bytes_written);
3383
3384        writer.close().unwrap();
3385    }
3386
3387    #[test]
3388    fn test_writer_all_null() {
3389        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3390        let b = Int32Array::new(vec![0; 5].into(), Some(NullBuffer::new_null(5)));
3391        let batch = RecordBatch::try_from_iter(vec![
3392            ("a", Arc::new(a) as ArrayRef),
3393            ("b", Arc::new(b) as ArrayRef),
3394        ])
3395        .unwrap();
3396
3397        let mut buf = Vec::with_capacity(1024);
3398        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
3399        writer.write(&batch).unwrap();
3400        writer.close().unwrap();
3401
3402        let bytes = Bytes::from(buf);
3403        let options = ReadOptionsBuilder::new().with_page_index().build();
3404        let reader = SerializedFileReader::new_with_options(bytes, options).unwrap();
3405        let index = reader.metadata().page_index().unwrap();
3406
3407        assert_eq!(index.num_data_pages(0, 0), Some(1)); // 1 page
3408        assert_eq!(index.num_data_pages(0, 1), Some(1)); // 1 page
3409    }
3410
3411    #[test]
3412    fn test_disabled_statistics_with_page() {
3413        let file_schema = Schema::new(vec![
3414            Field::new("a", DataType::Utf8, true),
3415            Field::new("b", DataType::Utf8, true),
3416        ]);
3417        let file_schema = Arc::new(file_schema);
3418
3419        let batch = RecordBatch::try_new(
3420            file_schema.clone(),
3421            vec![
3422                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
3423                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
3424            ],
3425        )
3426        .unwrap();
3427
3428        let props = WriterProperties::builder()
3429            .set_statistics_enabled(EnabledStatistics::None)
3430            .set_column_statistics_enabled("a".into(), EnabledStatistics::Page)
3431            .build();
3432
3433        let mut buf = Vec::with_capacity(1024);
3434        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
3435        writer.write(&batch).unwrap();
3436
3437        let metadata = writer.close().unwrap();
3438        assert_eq!(metadata.num_row_groups(), 1);
3439        let row_group = metadata.row_group(0);
3440        assert_eq!(row_group.num_columns(), 2);
3441        // Column "a" has both offset and column index, as requested
3442        assert!(row_group.column(0).offset_index_offset().is_some());
3443        assert!(row_group.column(0).column_index_offset().is_some());
3444        // Column "b" should only have offset index
3445        assert!(row_group.column(1).offset_index_offset().is_some());
3446        assert!(row_group.column(1).column_index_offset().is_none());
3447
3448        let options = ReadOptionsBuilder::new().with_page_index().build();
3449        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
3450
3451        let row_group = reader.get_row_group(0).unwrap();
3452        let a_col = row_group.metadata().column(0);
3453        let b_col = row_group.metadata().column(1);
3454
3455        // Column chunk of column "a" should have chunk level statistics
3456        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
3457            let min = byte_array_stats.min_opt().unwrap();
3458            let max = byte_array_stats.max_opt().unwrap();
3459
3460            assert_eq!(min.as_bytes(), b"a");
3461            assert_eq!(max.as_bytes(), b"d");
3462        } else {
3463            panic!("expecting Statistics::ByteArray");
3464        }
3465
3466        // The column chunk for column "b" shouldn't have statistics
3467        assert!(b_col.statistics().is_none());
3468
3469        let page_index = reader.metadata().page_index().unwrap();
3470
3471        let a_idx = page_index.column_index(0, 0);
3472        assert!(
3473            matches!(a_idx, Some(ColumnIndexMetaData::BYTE_ARRAY(_))),
3474            "{a_idx:?}"
3475        );
3476        let b_idx = page_index.column_index(0, 1);
3477        assert!(b_idx.is_none(), "{b_idx:?}");
3478    }
3479
3480    #[test]
3481    fn test_disabled_statistics_with_chunk() {
3482        let file_schema = Schema::new(vec![
3483            Field::new("a", DataType::Utf8, true),
3484            Field::new("b", DataType::Utf8, true),
3485        ]);
3486        let file_schema = Arc::new(file_schema);
3487
3488        let batch = RecordBatch::try_new(
3489            file_schema.clone(),
3490            vec![
3491                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
3492                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
3493            ],
3494        )
3495        .unwrap();
3496
3497        let props = WriterProperties::builder()
3498            .set_statistics_enabled(EnabledStatistics::None)
3499            .set_column_statistics_enabled("a".into(), EnabledStatistics::Chunk)
3500            .build();
3501
3502        let mut buf = Vec::with_capacity(1024);
3503        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
3504        writer.write(&batch).unwrap();
3505
3506        let metadata = writer.close().unwrap();
3507        assert_eq!(metadata.num_row_groups(), 1);
3508        let row_group = metadata.row_group(0);
3509        assert_eq!(row_group.num_columns(), 2);
3510        // Column "a" should only have offset index
3511        assert!(row_group.column(0).offset_index_offset().is_some());
3512        assert!(row_group.column(0).column_index_offset().is_none());
3513        // Column "b" should only have offset index
3514        assert!(row_group.column(1).offset_index_offset().is_some());
3515        assert!(row_group.column(1).column_index_offset().is_none());
3516
3517        let options = ReadOptionsBuilder::new().with_page_index().build();
3518        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
3519
3520        let row_group = reader.get_row_group(0).unwrap();
3521        let a_col = row_group.metadata().column(0);
3522        let b_col = row_group.metadata().column(1);
3523
3524        // Column chunk of column "a" should have chunk level statistics
3525        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
3526            let min = byte_array_stats.min_opt().unwrap();
3527            let max = byte_array_stats.max_opt().unwrap();
3528
3529            assert_eq!(min.as_bytes(), b"a");
3530            assert_eq!(max.as_bytes(), b"d");
3531        } else {
3532            panic!("expecting Statistics::ByteArray");
3533        }
3534
3535        // The column chunk for column "b"  shouldn't have statistics
3536        assert!(b_col.statistics().is_none());
3537
3538        let page_index = reader.metadata().page_index().unwrap();
3539
3540        let a_idx = page_index.column_index(0, 0);
3541        assert!(a_idx.is_none(), "{a_idx:?}");
3542        let b_idx = page_index.column_index(0, 1);
3543        assert!(b_idx.is_none(), "{b_idx:?}");
3544    }
3545
3546    #[test]
3547    fn test_arrow_writer_skip_metadata() {
3548        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3549        let file_schema = Arc::new(batch_schema.clone());
3550
3551        let batch = RecordBatch::try_new(
3552            Arc::new(batch_schema),
3553            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3554        )
3555        .unwrap();
3556        let skip_options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
3557
3558        let mut buf = Vec::with_capacity(1024);
3559        let mut writer =
3560            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
3561        writer.write(&batch).unwrap();
3562        writer.close().unwrap();
3563
3564        let bytes = Bytes::from(buf);
3565        let reader_builder = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
3566        assert_eq!(file_schema, *reader_builder.schema());
3567        if let Some(key_value_metadata) = reader_builder
3568            .metadata()
3569            .file_metadata()
3570            .key_value_metadata()
3571        {
3572            assert!(
3573                !key_value_metadata
3574                    .iter()
3575                    .any(|kv| kv.key.as_str() == ARROW_SCHEMA_META_KEY)
3576            );
3577        }
3578    }
3579
3580    #[test]
3581    fn test_arrow_writer_skip_path_in_schema() {
3582        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
3583        let file_schema = Arc::new(batch_schema.clone());
3584
3585        let batch = RecordBatch::try_new(
3586            Arc::new(batch_schema),
3587            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3588        )
3589        .unwrap();
3590
3591        // default options should still write path_in_schema
3592        let skip_options = ArrowWriterOptions::new();
3593
3594        let mut buf = Vec::with_capacity(1024);
3595        let mut writer =
3596            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
3597        writer.write(&batch).unwrap();
3598        writer.close().unwrap();
3599
3600        // override to not write path_in_schema
3601        let skip_options = ArrowWriterOptions::new().with_properties(
3602            WriterProperties::builder()
3603                .set_write_path_in_schema(false)
3604                .build(),
3605        );
3606
3607        let mut buf2 = Vec::with_capacity(1024);
3608        let mut writer =
3609            ArrowWriter::try_new_with_options(&mut buf2, file_schema.clone(), skip_options)
3610                .unwrap();
3611        writer.write(&batch).unwrap();
3612        writer.close().unwrap();
3613
3614        // buf2 should be a bit smaller due to lack of path_in_schema
3615        assert!(buf.len() > buf2.len());
3616    }
3617
3618    #[test]
3619    fn mismatched_schemas() {
3620        let batch_schema = Schema::new(vec![Field::new("count", DataType::Int32, false)]);
3621        let file_schema = Arc::new(Schema::new(vec![Field::new(
3622            "temperature",
3623            DataType::Float64,
3624            false,
3625        )]));
3626
3627        let batch = RecordBatch::try_new(
3628            Arc::new(batch_schema),
3629            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3630        )
3631        .unwrap();
3632
3633        let mut buf = Vec::with_capacity(1024);
3634        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
3635
3636        let err = writer.write(&batch).unwrap_err().to_string();
3637        assert_eq!(
3638            err,
3639            "Arrow: Incompatible type. Field 'temperature' has type Float64, array has type Int32"
3640        );
3641    }
3642
3643    #[test]
3644    fn test_page_stats_not_written_by_default() {
3645        let string_field = Field::new("a", DataType::Utf8, false);
3646        let schema = Schema::new(vec![string_field]);
3647        let raw_string_values = vec!["Blart Versenwald III"];
3648        let string_values = StringArray::from(raw_string_values.clone());
3649        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
3650
3651        let props = WriterProperties::builder()
3652            .set_statistics_enabled(EnabledStatistics::Page)
3653            .set_dictionary_enabled(false)
3654            .set_encoding(Encoding::PLAIN)
3655            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3656            .build();
3657
3658        let file = roundtrip_opts(&batch, props);
3659
3660        // read file and decode page headers
3661        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3662
3663        // decode first page header
3664        let first_page = &file[4..];
3665        let mut prot = ThriftSliceInputProtocol::new(first_page);
3666        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3667        let stats = hdr.data_page_header.unwrap().statistics;
3668
3669        assert!(stats.is_none());
3670    }
3671
3672    #[test]
3673    fn test_page_stats_when_enabled() {
3674        let string_field = Field::new("a", DataType::Utf8, false);
3675        let schema = Schema::new(vec![string_field]);
3676        let raw_string_values = vec!["Blart Versenwald III", "Andrew Lamb"];
3677        let string_values = StringArray::from(raw_string_values.clone());
3678        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
3679
3680        let props = WriterProperties::builder()
3681            .set_statistics_enabled(EnabledStatistics::Page)
3682            .set_dictionary_enabled(false)
3683            .set_encoding(Encoding::PLAIN)
3684            .set_write_page_header_statistics(true)
3685            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3686            .build();
3687
3688        let file = roundtrip_opts(&batch, props);
3689
3690        // read file and decode page headers
3691        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3692
3693        // decode first page header
3694        let first_page = &file[4..];
3695        let mut prot = ThriftSliceInputProtocol::new(first_page);
3696        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3697        let stats = hdr.data_page_header.unwrap().statistics;
3698
3699        let stats = stats.unwrap();
3700        // check that min/max were actually written to the page
3701        assert!(stats.is_max_value_exact.unwrap());
3702        assert!(stats.is_min_value_exact.unwrap());
3703        assert_eq!(stats.max_value.unwrap(), b"Blart Versenwald III");
3704        assert_eq!(stats.min_value.unwrap(), b"Andrew Lamb");
3705    }
3706
3707    #[test]
3708    fn test_page_stats_truncation() {
3709        let string_field = Field::new("a", DataType::Utf8, false);
3710        let binary_field = Field::new("b", DataType::Binary, false);
3711        let schema = Schema::new(vec![string_field, binary_field]);
3712
3713        let raw_string_values = vec!["Blart Versenwald III"];
3714        let raw_binary_values = [b"Blart Versenwald III".to_vec()];
3715        let raw_binary_value_refs = raw_binary_values
3716            .iter()
3717            .map(|x| x.as_slice())
3718            .collect::<Vec<_>>();
3719
3720        let string_values = StringArray::from(raw_string_values.clone());
3721        let binary_values = BinaryArray::from(raw_binary_value_refs);
3722        let batch = RecordBatch::try_new(
3723            Arc::new(schema),
3724            vec![Arc::new(string_values), Arc::new(binary_values)],
3725        )
3726        .unwrap();
3727
3728        let props = WriterProperties::builder()
3729            .set_statistics_truncate_length(Some(2))
3730            .set_dictionary_enabled(false)
3731            .set_encoding(Encoding::PLAIN)
3732            .set_write_page_header_statistics(true)
3733            .set_compression(crate::basic::Compression::UNCOMPRESSED)
3734            .build();
3735
3736        let file = roundtrip_opts(&batch, props);
3737
3738        // read file and decode page headers
3739        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
3740
3741        // decode first page header
3742        let first_page = &file[4..];
3743        let mut prot = ThriftSliceInputProtocol::new(first_page);
3744        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3745        let stats = hdr.data_page_header.unwrap().statistics;
3746        assert!(stats.is_some());
3747        let stats = stats.unwrap();
3748        // check that min/max were properly truncated
3749        assert!(!stats.is_max_value_exact.unwrap());
3750        assert!(!stats.is_min_value_exact.unwrap());
3751        assert_eq!(stats.max_value.unwrap(), b"Bm");
3752        assert_eq!(stats.min_value.unwrap(), b"Bl");
3753
3754        // check second page now
3755        let second_page = &prot.as_slice()[hdr.compressed_page_size as usize..];
3756        let mut prot = ThriftSliceInputProtocol::new(second_page);
3757        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
3758        let stats = hdr.data_page_header.unwrap().statistics;
3759        assert!(stats.is_some());
3760        let stats = stats.unwrap();
3761        // check that min/max were properly truncated
3762        assert!(!stats.is_max_value_exact.unwrap());
3763        assert!(!stats.is_min_value_exact.unwrap());
3764        assert_eq!(stats.max_value.unwrap(), b"Bm");
3765        assert_eq!(stats.min_value.unwrap(), b"Bl");
3766    }
3767
3768    #[test]
3769    fn test_page_encoding_statistics_roundtrip() {
3770        let batch_schema = Schema::new(vec![Field::new(
3771            "int32",
3772            arrow_schema::DataType::Int32,
3773            false,
3774        )]);
3775
3776        let batch = RecordBatch::try_new(
3777            Arc::new(batch_schema.clone()),
3778            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
3779        )
3780        .unwrap();
3781
3782        let mut file: File = tempfile::tempfile().unwrap();
3783        let mut writer = ArrowWriter::try_new(&mut file, Arc::new(batch_schema), None).unwrap();
3784        writer.write(&batch).unwrap();
3785        let file_metadata = writer.close().unwrap();
3786
3787        assert_eq!(file_metadata.num_row_groups(), 1);
3788        assert_eq!(file_metadata.row_group(0).num_columns(), 1);
3789        assert!(
3790            file_metadata
3791                .row_group(0)
3792                .column(0)
3793                .page_encoding_stats()
3794                .is_some()
3795        );
3796        let chunk_page_stats = file_metadata
3797            .row_group(0)
3798            .column(0)
3799            .page_encoding_stats()
3800            .unwrap();
3801
3802        // check that the read metadata is also correct
3803        let options = ReadOptionsBuilder::new()
3804            .with_page_index()
3805            .with_encoding_stats_as_mask(false)
3806            .build();
3807        let reader = SerializedFileReader::new_with_options(file, options).unwrap();
3808
3809        let rowgroup = reader.get_row_group(0).expect("row group missing");
3810        assert_eq!(rowgroup.num_columns(), 1);
3811        let column = rowgroup.metadata().column(0);
3812        assert!(column.page_encoding_stats().is_some());
3813        let file_page_stats = column.page_encoding_stats().unwrap();
3814        assert_eq!(chunk_page_stats, file_page_stats);
3815    }
3816
3817    #[test]
3818    #[cfg_attr(miri, ignore)] // Takes too long
3819    fn test_different_dict_page_size_limit() {
3820        let array = Arc::new(Int64Array::from_iter(0..1024 * 1024));
3821        let schema = Arc::new(Schema::new(vec![
3822            Field::new("col0", arrow_schema::DataType::Int64, false),
3823            Field::new("col1", arrow_schema::DataType::Int64, false),
3824        ]));
3825        let batch =
3826            arrow_array::RecordBatch::try_new(schema.clone(), vec![array.clone(), array]).unwrap();
3827
3828        let props = WriterProperties::builder()
3829            .set_dictionary_page_size_limit(1024 * 1024)
3830            .set_column_dictionary_page_size_limit(ColumnPath::from("col1"), 1024 * 1024 * 4)
3831            .build();
3832        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3833        writer.write(&batch).unwrap();
3834        let data = Bytes::from(writer.into_inner().unwrap());
3835
3836        let mut metadata = ParquetMetaDataReader::new();
3837        metadata.try_parse(&data).unwrap();
3838        let metadata = metadata.finish().unwrap();
3839        let col0_meta = metadata.row_group(0).column(0);
3840        let col1_meta = metadata.row_group(0).column(1);
3841
3842        let get_dict_page_size = move |meta: &ColumnChunkMetaData| {
3843            let mut reader =
3844                SerializedPageReader::new(Arc::new(data.clone()), meta, 0, None).unwrap();
3845            let page = reader.get_next_page().unwrap().unwrap();
3846            match page {
3847                Page::DictionaryPage { buf, .. } => buf.len(),
3848                _ => panic!("expected DictionaryPage"),
3849            }
3850        };
3851
3852        assert_eq!(get_dict_page_size(col0_meta), 1024 * 1024);
3853        assert_eq!(get_dict_page_size(col1_meta), 1024 * 1024 * 4);
3854    }
3855
3856    #[test]
3857    #[cfg_attr(miri, ignore)] // Takes too long
3858    fn test_arrow_writer_granular_mode_roundtrip() {
3859        // Granular mode subdivides chunks and writes more pages than the
3860        // default batched path. Make sure the data we write back is
3861        // bit-identical to what went in — page-count assertions elsewhere
3862        // only prove pages were cut, not that the encoded data is correct.
3863        //
3864        // Mix value sizes so that the cumulative-byte-budget cutoff
3865        // lands mid-chunk, exercising both batched and granular paths
3866        // within the same `write_batch_internal` call.
3867        let small = "tiny".to_string();
3868        let big = "x".repeat(64 * 1024);
3869        let strings: Vec<String> = (0..256)
3870            .map(|i| {
3871                if i % 16 == 0 {
3872                    big.clone()
3873                } else {
3874                    small.clone()
3875                }
3876            })
3877            .collect();
3878
3879        let schema = Arc::new(Schema::new(vec![Field::new(
3880            "col",
3881            ArrowDataType::Utf8,
3882            false,
3883        )]));
3884        let batch = RecordBatch::try_new(
3885            schema.clone(),
3886            vec![Arc::new(StringArray::from(strings.clone())) as _],
3887        )
3888        .unwrap();
3889
3890        let props = WriterProperties::builder()
3891            .set_dictionary_enabled(false)
3892            .set_data_page_size_limit(16 * 1024)
3893            .build();
3894        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3895        writer.write(&batch).unwrap();
3896        let data = Bytes::from(writer.into_inner().unwrap());
3897
3898        let mut reader = ParquetRecordBatchReader::try_new(data, 1024).unwrap();
3899        let read = reader.next().unwrap().unwrap();
3900        assert!(reader.next().is_none(), "expected one batch");
3901        let col = read
3902            .column(0)
3903            .as_any()
3904            .downcast_ref::<StringArray>()
3905            .unwrap();
3906        assert_eq!(col.len(), strings.len());
3907        for (i, expected) in strings.iter().enumerate() {
3908            assert_eq!(
3909                col.value(i),
3910                expected.as_str(),
3911                "value mismatch at index {i}"
3912            );
3913        }
3914    }
3915
3916    #[test]
3917    fn test_arrow_writer_all_null_string_column() {
3918        // The `LevelDataRef::value_count` Uniform branch with
3919        // `value != max_def` (entirely-null chunk) must return 0 so the
3920        // sub-batch sizer short-circuits to batch mode without trying
3921        // to estimate byte budgets for non-existent values.
3922        let num_rows = 1024;
3923        let schema = Arc::new(Schema::new(vec![Field::new(
3924            "col",
3925            ArrowDataType::Utf8,
3926            true,
3927        )]));
3928        let nulls: Vec<Option<&str>> = vec![None; num_rows];
3929        let batch = RecordBatch::try_new(
3930            schema.clone(),
3931            vec![Arc::new(StringArray::from(nulls)) as _],
3932        )
3933        .unwrap();
3934
3935        let props = WriterProperties::builder()
3936            .set_dictionary_enabled(false)
3937            .set_data_page_size_limit(16 * 1024)
3938            .build();
3939        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
3940        writer.write(&batch).unwrap();
3941        let data = Bytes::from(writer.into_inner().unwrap());
3942
3943        // Re-parse the file: row group has one column, every row is
3944        // null, all data pages report `num_rows / page_count` rows.
3945        let mut metadata = ParquetMetaDataReader::new();
3946        metadata.try_parse(&data).unwrap();
3947        let metadata = metadata.finish().unwrap();
3948        let row_group = metadata.row_group(0);
3949        let col_meta = row_group.column(0);
3950        assert_eq!(row_group.num_rows() as usize, num_rows);
3951        // Statistics record `null_count = num_rows` — proves every value
3952        // was written as null.
3953        if let Some(stats) = col_meta.statistics() {
3954            assert_eq!(
3955                stats.null_count_opt().unwrap_or(0) as usize,
3956                num_rows,
3957                "expected all-null column to report null_count = num_rows"
3958            );
3959        }
3960
3961        let mut reader =
3962            SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap();
3963        let mut total_values = 0u32;
3964        while let Some(page) = reader.get_next_page().unwrap() {
3965            if matches!(page, Page::DataPage { .. } | Page::DataPageV2 { .. }) {
3966                total_values += page.num_values();
3967            }
3968        }
3969        assert_eq!(
3970            total_values as usize, num_rows,
3971            "expected every level position to be represented in some page"
3972        );
3973    }
3974
3975    struct WriteBatchesShape {
3976        num_batches: usize,
3977        rows_per_batch: usize,
3978        row_size: usize,
3979    }
3980
3981    /// Helper function to write batches with the provided `WriteBatchesShape` into an `ArrowWriter`
3982    fn write_batches(
3983        WriteBatchesShape {
3984            num_batches,
3985            rows_per_batch,
3986            row_size,
3987        }: WriteBatchesShape,
3988        props: WriterProperties,
3989    ) -> ParquetRecordBatchReaderBuilder<File> {
3990        let schema = Arc::new(Schema::new(vec![Field::new(
3991            "str",
3992            ArrowDataType::Utf8,
3993            false,
3994        )]));
3995        let file = tempfile::tempfile().unwrap();
3996        let mut writer =
3997            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
3998
3999        for batch_idx in 0..num_batches {
4000            let strings: Vec<String> = (0..rows_per_batch)
4001                .map(|i| format!("{:0>width$}", batch_idx * 10 + i, width = row_size))
4002                .collect();
4003            let array = StringArray::from(strings);
4004            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
4005            writer.write(&batch).unwrap();
4006        }
4007        writer.close().unwrap();
4008        ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
4009    }
4010
4011    #[test]
4012    // When both limits are None, all data should go into a single row group
4013    fn test_row_group_limit_none_writes_single_row_group() {
4014        let props = WriterProperties::builder()
4015            .set_max_row_group_row_count(None)
4016            .set_max_row_group_bytes(None)
4017            .build();
4018
4019        let builder = write_batches(
4020            WriteBatchesShape {
4021                num_batches: 1,
4022                rows_per_batch: 1000,
4023                row_size: 4,
4024            },
4025            props,
4026        );
4027
4028        assert_eq!(
4029            &row_group_sizes(builder.metadata()),
4030            &[1000],
4031            "With no limits, all rows should be in a single row group"
4032        );
4033    }
4034
4035    #[test]
4036    // When only max_row_group_size is set, respect the row limit
4037    fn test_row_group_limit_rows_only() {
4038        let props = WriterProperties::builder()
4039            .set_max_row_group_row_count(Some(300))
4040            .set_max_row_group_bytes(None)
4041            .build();
4042
4043        let builder = write_batches(
4044            WriteBatchesShape {
4045                num_batches: 1,
4046                rows_per_batch: 1000,
4047                row_size: 4,
4048            },
4049            props,
4050        );
4051
4052        assert_eq!(
4053            &row_group_sizes(builder.metadata()),
4054            &[300, 300, 300, 100],
4055            "Row groups should be split by row count"
4056        );
4057    }
4058
4059    #[test]
4060    #[cfg_attr(miri, ignore)] // Takes too long
4061    // A row limit far smaller than the batch splits it many times over; the split must not
4062    // consume stack proportional to the number of row groups.
4063    fn test_row_group_limit_rows_only_many_splits() {
4064        let props = WriterProperties::builder()
4065            .set_max_row_group_row_count(Some(1))
4066            .set_max_row_group_bytes(None)
4067            .build();
4068
4069        let rows = 50_000;
4070        let builder = write_batches(
4071            WriteBatchesShape {
4072                num_batches: 1,
4073                rows_per_batch: rows,
4074                row_size: 4,
4075            },
4076            props,
4077        );
4078
4079        let sizes = row_group_sizes(builder.metadata());
4080        assert_eq!(sizes.len(), rows, "Every row should get its own row group");
4081        assert_eq!(
4082            sizes.iter().sum::<i64>(),
4083            rows as i64,
4084            "Total rows should be preserved"
4085        );
4086    }
4087
4088    #[test]
4089    // When only max_row_group_bytes is set, respect the byte limit
4090    fn test_row_group_limit_bytes_only() {
4091        let props = WriterProperties::builder()
4092            .set_max_row_group_row_count(None)
4093            // Set byte limit to approximately fit ~30 rows worth of data (~100 bytes each)
4094            .set_max_row_group_bytes(Some(3500))
4095            .build();
4096
4097        let builder = write_batches(
4098            WriteBatchesShape {
4099                num_batches: 10,
4100                rows_per_batch: 10,
4101                row_size: 100,
4102            },
4103            props,
4104        );
4105
4106        let sizes = row_group_sizes(builder.metadata());
4107
4108        assert!(
4109            sizes.len() > 1,
4110            "Should have multiple row groups due to byte limit, got {sizes:?}",
4111        );
4112
4113        let total_rows: i64 = sizes.iter().sum();
4114        assert_eq!(total_rows, 100, "Total rows should be preserved");
4115    }
4116
4117    #[test]
4118    // If an in-progress row group is already oversized, it should be flushed before writing more.
4119    fn test_row_group_limit_bytes_flushes_when_current_group_already_too_large() {
4120        let schema = Arc::new(Schema::new(vec![Field::new(
4121            "str",
4122            ArrowDataType::Utf8,
4123            false,
4124        )]));
4125        let file = tempfile::tempfile().unwrap();
4126
4127        // Start with no byte limit so we can intentionally build an oversized in-progress row group.
4128        let props = WriterProperties::builder()
4129            .set_max_row_group_row_count(None)
4130            .set_max_row_group_bytes(None)
4131            .build();
4132        let mut writer =
4133            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4134
4135        let first_array = StringArray::from(
4136            (0..10)
4137                .map(|i| format!("{i:0>100}"))
4138                .collect::<Vec<String>>(),
4139        );
4140        let first_batch =
4141            RecordBatch::try_new(schema.clone(), vec![Arc::new(first_array)]).unwrap();
4142        writer.write(&first_batch).unwrap();
4143        assert_eq!(writer.in_progress_rows(), 10);
4144
4145        // Tighten the limit below the current in-progress bytes to exercise:
4146        // `if current_bytes >= max_bytes { self.flush()?; ... }`
4147        writer.max_row_group_bytes = Some(1);
4148
4149        let second_array = StringArray::from(vec!["x".to_string()]);
4150        let second_batch =
4151            RecordBatch::try_new(schema.clone(), vec![Arc::new(second_array)]).unwrap();
4152        writer.write(&second_batch).unwrap();
4153        writer.close().unwrap();
4154        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
4155
4156        assert_eq!(
4157            &row_group_sizes(builder.metadata()),
4158            &[10, 1],
4159            "The second write should flush an oversized in-progress row group first",
4160        );
4161    }
4162
4163    #[test]
4164    // When both limits are set, the row limit triggers first
4165    fn test_row_group_limit_both_row_wins_single_batch() {
4166        let props = WriterProperties::builder()
4167            .set_max_row_group_row_count(Some(200)) // Will trigger at 200 rows
4168            .set_max_row_group_bytes(Some(1024 * 1024)) // 1MB - won't trigger for small int data
4169            .build();
4170
4171        let builder = write_batches(
4172            WriteBatchesShape {
4173                num_batches: 1,
4174                row_size: 4,
4175                rows_per_batch: 1000,
4176            },
4177            props,
4178        );
4179
4180        assert_eq!(
4181            &row_group_sizes(builder.metadata()),
4182            &[200, 200, 200, 200, 200],
4183            "Row limit should trigger before byte limit"
4184        );
4185    }
4186
4187    #[test]
4188    // When both limits are set, the row limit triggers first
4189    fn test_row_group_limit_both_row_wins_multiple_batches() {
4190        let props = WriterProperties::builder()
4191            .set_max_row_group_row_count(Some(5)) // Will trigger every 5 rows
4192            .set_max_row_group_bytes(Some(9999)) // Won't trigger
4193            .build();
4194
4195        let builder = write_batches(
4196            WriteBatchesShape {
4197                num_batches: 10,
4198                rows_per_batch: 10,
4199                row_size: 100,
4200            },
4201            props,
4202        );
4203
4204        assert_eq!(
4205            &row_group_sizes(builder.metadata()),
4206            &[5; 20],
4207            "Row limit should trigger before byte limit"
4208        );
4209    }
4210
4211    #[test]
4212    // When both limits are set, the byte limit triggers first
4213    fn test_row_group_limit_both_bytes_wins() {
4214        let props = WriterProperties::builder()
4215            .set_max_row_group_row_count(Some(1000)) // Won't trigger for 100 rows
4216            .set_max_row_group_bytes(Some(3500)) // Will trigger at ~30-35 rows
4217            .build();
4218
4219        let builder = write_batches(
4220            WriteBatchesShape {
4221                num_batches: 10,
4222                rows_per_batch: 10,
4223                row_size: 100,
4224            },
4225            props,
4226        );
4227
4228        let sizes = row_group_sizes(builder.metadata());
4229
4230        assert!(
4231            sizes.len() > 1,
4232            "Byte limit should trigger before row limit, got {sizes:?}",
4233        );
4234
4235        assert!(
4236            sizes.iter().all(|&s| s < 1000),
4237            "No row group should hit the row limit"
4238        );
4239
4240        let total_rows: i64 = sizes.iter().sum();
4241        assert_eq!(total_rows, 100, "Total rows should be preserved");
4242    }
4243
4244    #[test]
4245    // Both limits can apply to the same batch: the row limit trims it to 5 rows, and the
4246    // byte limit then trims those 5 down to 4.
4247    fn test_row_group_limit_both_apply_to_same_batch() {
4248        let props = WriterProperties::builder()
4249            .set_max_row_group_row_count(Some(15))
4250            .set_max_row_group_bytes(Some(1500))
4251            .build();
4252
4253        let builder = write_batches(
4254            WriteBatchesShape {
4255                num_batches: 2,
4256                rows_per_batch: 10,
4257                row_size: 100,
4258            },
4259            props,
4260        );
4261
4262        assert_eq!(
4263            &row_group_sizes(builder.metadata()),
4264            &[14, 6],
4265            "Byte limit should still apply to a batch the row limit already split"
4266        );
4267    }
4268
4269    #[test]
4270    fn arrow_column_chunk_close_mut_drops_column_index() {
4271        use crate::arrow::ArrowSchemaConverter;
4272        use crate::file::writer::SerializedFileWriter;
4273
4274        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
4275        let props = Arc::new(
4276            WriterProperties::builder()
4277                .set_statistics_enabled(EnabledStatistics::Page)
4278                .build(),
4279        );
4280        let parquet_schema = ArrowSchemaConverter::new()
4281            .with_coerce_types(props.coerce_types())
4282            .convert(&schema)
4283            .unwrap();
4284
4285        let mut buf = Vec::with_capacity(1024);
4286        let mut writer =
4287            SerializedFileWriter::new(&mut buf, parquet_schema.root_schema_ptr(), props.clone())
4288                .unwrap();
4289
4290        let factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
4291        let mut col_writers = factory.create_column_writers(0).unwrap();
4292        let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..64));
4293        for leaves in compute_leaves(schema.field(0), &arr).unwrap() {
4294            col_writers[0].write(&leaves).unwrap();
4295        }
4296        let mut chunk = col_writers.pop().unwrap().close().unwrap();
4297
4298        // Immutable accessor exposes the close result produced at close time.
4299        assert!(
4300            chunk.close().column_index.is_some(),
4301            "EnabledStatistics::Page should produce a column_index"
4302        );
4303
4304        // Mutable accessor lets callers drop the page-level index before append.
4305        chunk.close_mut().column_index = None;
4306        assert!(chunk.close().column_index.is_none());
4307
4308        let mut rg = writer.next_row_group().unwrap();
4309        chunk.append_to_row_group(&mut rg).unwrap();
4310        rg.close().unwrap();
4311        let file_meta = writer.close().unwrap();
4312
4313        // After dropping column_index, the resulting file records no column
4314        // index offset/length for this chunk.
4315        let cc = file_meta.row_group(0).column(0);
4316        assert!(cc.column_index_range().is_none());
4317    }
4318
4319    #[test]
4320    #[cfg_attr(miri, ignore)] // Takes too long
4321    fn test_number_distinct_values_exact_count() {
4322        // 50 distinct Int32 values repeated across 100k rows, with every 7th row null.
4323        // Nulls must not be counted as a distinct value.
4324        let cardinality = 50u32;
4325        let array: ArrayRef = Arc::new(Int32Array::from_iter((0..100_000u32).map(|i| {
4326            if i % 7 == 0 {
4327                None
4328            } else {
4329                Some((i % cardinality) as i32)
4330            }
4331        })));
4332        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, true)]));
4333        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
4334
4335        let props = WriterProperties::builder()
4336            .set_write_row_group_number_distinct_values(true)
4337            .build();
4338        let mut buf = Vec::new();
4339        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4340        writer.write(&batch).unwrap();
4341        let metadata = writer.close().unwrap();
4342
4343        let count = metadata
4344            .row_group(0)
4345            .column(0)
4346            .statistics()
4347            .and_then(|s| s.distinct_count_opt())
4348            .expect("distinct_count should be set");
4349        // Must equal cardinality exactly; nulls must not inflate the count.
4350        assert_eq!(count, cardinality as u64);
4351    }
4352
4353    #[test]
4354    fn test_number_distinct_values_view_types() {
4355        // 5 distinct values repeated across 30 rows, with every 4th row null.
4356        // Verifies Utf8View is counted correctly (BinaryView shares the same code path).
4357        let cardinality = 5u32;
4358        let distinct_strings = ["alpha", "beta", "gamma", "delta", "epsilon"];
4359
4360        let string_view_col: ArrayRef = Arc::new(StringViewArray::from_iter((0..30u32).map(|i| {
4361            if i % 4 == 0 {
4362                None
4363            } else {
4364                Some(distinct_strings[(i % cardinality) as usize])
4365            }
4366        })));
4367
4368        let schema = Arc::new(Schema::new(vec![Field::new(
4369            "string_view_col",
4370            DataType::Utf8View,
4371            true,
4372        )]));
4373        let batch = RecordBatch::try_new(schema, vec![string_view_col]).unwrap();
4374
4375        let props = WriterProperties::builder()
4376            .set_write_row_group_number_distinct_values(true)
4377            .build();
4378        let mut parquet_bytes = Vec::new();
4379        let mut writer =
4380            ArrowWriter::try_new(&mut parquet_bytes, batch.schema(), Some(props)).unwrap();
4381        writer.write(&batch).unwrap();
4382        let metadata = writer.close().unwrap();
4383
4384        let distinct_count = metadata
4385            .row_group(0)
4386            .column(0)
4387            .statistics()
4388            .and_then(|s| s.distinct_count_opt())
4389            .expect("distinct_count should be set for Utf8View column");
4390        assert_eq!(distinct_count, cardinality as u64);
4391    }
4392
4393    #[test]
4394    fn test_number_distinct_values_not_written_by_default() {
4395        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
4396        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)]));
4397        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
4398
4399        let mut buf = Vec::new();
4400        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
4401        writer.write(&batch).unwrap();
4402        let metadata = writer.close().unwrap();
4403
4404        let count = metadata
4405            .row_group(0)
4406            .column(0)
4407            .statistics()
4408            .and_then(|s| s.distinct_count_opt());
4409        assert!(count.is_none());
4410    }
4411
4412    #[test]
4413    fn test_dictionary_ndv_single_batch() {
4414        // Dictionary array with 3 distinct string values repeated many times.
4415        // NDV must equal the number of distinct values in the dictionary (3),
4416        // not the number of rows.
4417        let keys = Int32Array::from(vec![0, 1, 2, 0, 1, 2, 0, 1, 2]);
4418        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "bird"]));
4419        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4420
4421        let schema = Arc::new(Schema::new(vec![Field::new(
4422            "x",
4423            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4424            false,
4425        )]));
4426        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
4427
4428        let props = WriterProperties::builder()
4429            .set_write_row_group_number_distinct_values(true)
4430            .build();
4431        let mut buf = Vec::new();
4432        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4433        writer.write(&batch).unwrap();
4434        let metadata = writer.close().unwrap();
4435
4436        let count = metadata
4437            .row_group(0)
4438            .column(0)
4439            .statistics()
4440            .and_then(|s| s.distinct_count_opt())
4441            .expect("distinct_count should be set");
4442        assert_eq!(count, 3);
4443    }
4444
4445    #[test]
4446    fn test_dictionary_ndv_excludes_unreferenced_values() {
4447        // Keys only reference indices 0 and 1; value at index 2 ("unreferenced") should not
4448        // count toward NDV even though it appears in the dictionary's values array.
4449        let keys = Int32Array::from(vec![0, 1, 0, 1]);
4450        let values: ArrayRef = Arc::new(StringArray::from(vec!["cat", "dog", "unreferenced"]));
4451        let dict: ArrayRef = Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4452
4453        let schema = Arc::new(Schema::new(vec![Field::new(
4454            "x",
4455            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4456            false,
4457        )]));
4458        let batch = RecordBatch::try_new(schema, vec![dict]).unwrap();
4459
4460        let props = WriterProperties::builder()
4461            .set_write_row_group_number_distinct_values(true)
4462            .build();
4463        let mut buf = Vec::new();
4464        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
4465        writer.write(&batch).unwrap();
4466        let metadata = writer.close().unwrap();
4467
4468        let count = metadata
4469            .row_group(0)
4470            .column(0)
4471            .statistics()
4472            .and_then(|s| s.distinct_count_opt())
4473            .expect("distinct_count should be set");
4474        assert_eq!(
4475            count, 2,
4476            "unreferenced dictionary values must not count toward NDV"
4477        );
4478    }
4479
4480    #[test]
4481    fn test_dictionary_ndv_across_batches_regression() {
4482        // Regression test for https://github.com/apache/arrow-rs/issues/11172.
4483        let make_dict_batch = |a: &str, b: &str| -> RecordBatch {
4484            let keys = Int32Array::from(vec![0, 1, 0, 1]);
4485            let values: ArrayRef = Arc::new(StringArray::from(vec![a, b]));
4486            let dict: ArrayRef =
4487                Arc::new(DictionaryArray::<Int32Type>::try_new(keys, values).unwrap());
4488            let schema = Arc::new(Schema::new(vec![Field::new(
4489                "x",
4490                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4491                false,
4492            )]));
4493            RecordBatch::try_new(schema, vec![dict]).unwrap()
4494        };
4495
4496        // batch1: dict = ["cat", "dog"], batch2: dict = ["fish", "cat"]
4497        // Distinct values across both batches: "cat", "dog", "fish" NDV = 3
4498        let batch1 = make_dict_batch("cat", "dog");
4499        let batch2 = make_dict_batch("fish", "cat");
4500
4501        let props = WriterProperties::builder()
4502            .set_write_row_group_number_distinct_values(true)
4503            .build();
4504        let mut buf = Vec::new();
4505        let mut writer = ArrowWriter::try_new(&mut buf, batch1.schema(), Some(props)).unwrap();
4506        writer.write(&batch1).unwrap();
4507        writer.write(&batch2).unwrap();
4508        let metadata = writer.close().unwrap();
4509
4510        let count = metadata
4511            .row_group(0)
4512            .column(0)
4513            .statistics()
4514            .and_then(|s| s.distinct_count_opt())
4515            .expect("distinct_count should be set");
4516        assert_eq!(
4517            count, 3,
4518            "NDV should count distinct values, not distinct key indices"
4519        );
4520    }
4521
4522    #[test]
4523    fn ree_struct_with_ree_child() {
4524        // Struct with a REE string field and a REE int field — confirms
4525        // recursion visits every child and each collapses to the right leaf type.
4526        let run_ends = Int32Array::from(vec![2i32, 3, 5]);
4527
4528        let col_a: ArrayRef = Arc::new(
4529            RunArray::try_new(
4530                &run_ends,
4531                &StringArray::from(vec![Some("foo"), None, Some("bar")]),
4532            )
4533            .unwrap(),
4534        );
4535        let col_b: ArrayRef = Arc::new(
4536            RunArray::try_new(&run_ends, &Int32Array::from(vec![Some(1), None, Some(2)])).unwrap(),
4537        );
4538
4539        let struct_array: ArrayRef = Arc::new(StructArray::new(
4540            Fields::from(vec![
4541                Field::new("a", col_a.data_type().clone(), true),
4542                Field::new("b", col_b.data_type().clone(), true),
4543            ]),
4544            vec![col_a, col_b],
4545            None,
4546        ));
4547
4548        let schema = Arc::new(Schema::new(vec![Field::new(
4549            "row",
4550            struct_array.data_type().clone(),
4551            true,
4552        )]));
4553        let batch = RecordBatch::try_new(schema.clone(), vec![struct_array]).unwrap();
4554
4555        let mut buf = Vec::new();
4556        let mut writer = ArrowWriter::try_new(&mut buf, schema, None).unwrap();
4557        writer.write(&batch).unwrap();
4558        let metadata = writer.close().unwrap();
4559
4560        let parquet_schema = metadata.file_metadata().schema_descr();
4561        assert_eq!(parquet_schema.num_columns(), 2);
4562        assert_eq!(
4563            parquet_schema.column(0).physical_type(),
4564            crate::basic::Type::BYTE_ARRAY
4565        );
4566        assert_eq!(parquet_schema.column(0).path().string(), "row.a");
4567        assert_eq!(
4568            parquet_schema.column(1).physical_type(),
4569            crate::basic::Type::INT32
4570        );
4571        assert_eq!(parquet_schema.column(1).path().string(), "row.b");
4572    }
4573}