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