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                if let Some(avg_row_bytes) = current_bytes
405                    .checked_div(buffered_rows)
406                    .filter(|avg_row_bytes| *avg_row_bytes > 0)
407                {
408                    // At this point, `current_bytes < max_bytes` (checked above)
409                    let remaining_bytes = max_bytes - current_bytes;
410                    let rows_that_fit = remaining_bytes.checked_div(avg_row_bytes).unwrap_or(0);
411
412                    if candidate_rows > rows_that_fit {
413                        if rows_that_fit > 0 {
414                            split_at = Some(rows_that_fit);
415                        } else {
416                            self.flush()?;
417                            continue;
418                        }
419                    }
420                }
421            }
422
423            let rest = split_at.map(|to_write| {
424                let rest = remaining.slice(to_write, remaining.num_rows() - to_write);
425                remaining = remaining.slice(0, to_write);
426                rest
427            });
428
429            let in_progress = self.in_progress.as_mut().unwrap();
430            match self.cdc_chunkers.as_mut() {
431                Some(chunkers) => in_progress.write_with_chunkers(&remaining, chunkers)?,
432                None => in_progress.write(&remaining)?,
433            }
434
435            let should_flush = self
436                .max_row_group_row_count
437                .is_some_and(|max| in_progress.buffered_rows >= max)
438                || self
439                    .max_row_group_bytes
440                    .is_some_and(|max| in_progress.get_estimated_total_bytes() >= max);
441
442            if should_flush {
443                self.flush()?
444            }
445
446            match rest {
447                Some(rest) => remaining = rest,
448                None => return Ok(()),
449            }
450        }
451    }
452
453    /// Writes the given buf bytes to the internal buffer.
454    ///
455    /// It's safe to use this method to write data to the underlying writer,
456    /// because it will ensure that the buffering and byte‐counting layers are used.
457    pub fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
458        self.writer.write_all(buf)
459    }
460
461    /// Flushes underlying writer
462    pub fn sync(&mut self) -> std::io::Result<()> {
463        self.writer.flush()
464    }
465
466    /// Flushes all buffered rows into a new row group
467    ///
468    /// Note the underlying writer is not flushed with this call.
469    /// If this is a desired behavior, please call [`ArrowWriter::sync`].
470    pub fn flush(&mut self) -> Result<()> {
471        let Some(in_progress) = self.in_progress.take() else {
472            return Ok(());
473        };
474
475        let mut row_group_writer = self.writer.next_row_group()?;
476        for chunk in in_progress.close()? {
477            chunk.append_to_row_group(&mut row_group_writer)?;
478        }
479        row_group_writer.close()?;
480        Ok(())
481    }
482
483    /// Additional [`KeyValue`] metadata to be written in addition to those from [`WriterProperties`]
484    ///
485    /// This method provide a way to append kv_metadata after write RecordBatch
486    pub fn append_key_value_metadata(&mut self, kv_metadata: KeyValue) {
487        self.writer.append_key_value_metadata(kv_metadata)
488    }
489
490    /// Returns a reference to the underlying writer.
491    pub fn inner(&self) -> &W {
492        self.writer.inner()
493    }
494
495    /// Returns a mutable reference to the underlying writer.
496    ///
497    /// **Warning**: if you write directly to this writer, you will skip
498    /// the `TrackedWrite` buffering and byte‐counting layers. That’ll cause
499    /// the file footer’s recorded offsets and sizes to diverge from reality,
500    /// resulting in an unreadable or corrupted Parquet file.
501    ///
502    /// If you want to write safely to the underlying writer, use [`Self::write_all`].
503    pub fn inner_mut(&mut self) -> &mut W {
504        self.writer.inner_mut()
505    }
506
507    /// Flushes any outstanding data and returns the underlying writer.
508    pub fn into_inner(mut self) -> Result<W> {
509        self.flush()?;
510        self.writer.into_inner()
511    }
512
513    /// Close and finalize the underlying Parquet writer
514    ///
515    /// Unlike [`Self::close`] this does not consume self
516    ///
517    /// Attempting to write after calling finish will result in an error
518    pub fn finish(&mut self) -> Result<ParquetMetaData> {
519        self.flush()?;
520        self.writer.finish()
521    }
522
523    /// Close and finalize the underlying Parquet writer
524    pub fn close(mut self) -> Result<ParquetMetaData> {
525        self.finish()
526    }
527
528    /// Converts this writer into a lower-level [`SerializedFileWriter`] and [`ArrowRowGroupWriterFactory`].
529    ///
530    /// Flushes any outstanding data before returning.
531    ///
532    /// This can be useful to provide more control over how files are written, for example
533    /// to write columns in parallel. See the example on [`ArrowColumnWriter`].
534    pub fn into_serialized_writer(
535        mut self,
536    ) -> Result<(SerializedFileWriter<W>, ArrowRowGroupWriterFactory)> {
537        self.flush()?;
538        Ok((self.writer, self.row_group_writer_factory))
539    }
540}
541
542impl<W: Write + Send> RecordBatchWriter for ArrowWriter<W> {
543    fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
544        self.write(batch).map_err(|e| e.into())
545    }
546
547    fn close(self) -> std::result::Result<(), ArrowError> {
548        self.close()?;
549        Ok(())
550    }
551}
552
553/// Arrow-specific configuration settings for writing parquet files.
554///
555/// See [`ArrowWriter`] for how to configure the writer.
556#[derive(Debug, Clone, Default)]
557pub struct ArrowWriterOptions {
558    properties: WriterProperties,
559    skip_arrow_metadata: bool,
560    schema_root: Option<String>,
561    schema_descr: Option<SchemaDescriptor>,
562    page_store_factory: Option<Arc<dyn PageStoreFactory>>,
563}
564
565impl ArrowWriterOptions {
566    /// Creates a new [`ArrowWriterOptions`] with the default settings.
567    pub fn new() -> Self {
568        Self::default()
569    }
570
571    /// Sets the [`WriterProperties`] for writing parquet files.
572    pub fn with_properties(self, properties: WriterProperties) -> Self {
573        Self { properties, ..self }
574    }
575
576    /// Sets the [`PageStoreFactory`] used to buffer completed pages while a row
577    /// group is being written.
578    ///
579    /// The default implementation ([`InMemoryPageStore`]) buffers all completed
580    /// pages on the heap until the row group is flushed, so peak write memory
581    /// grows with the row group size. Using this API, pages can be spilled to a
582    /// file or object storage instead, reducing peak write memory substantially
583    /// at the expense of an extra write to and read from secondary storage.
584    ///
585    /// # Example: spilling pages to a temp file
586    ///
587    /// A simple spilling backend uses one temp file per column chunk; `put`
588    /// appends the page and `take` reads it back.
589    ///
590    /// ```
591    /// # use std::fs::File;
592    /// # use std::io::{Read, Seek, SeekFrom, Write};
593    /// # use std::sync::Arc;
594    /// # use bytes::Bytes;
595    /// # use arrow_array::{ArrayRef, Int64Array, RecordBatch};
596    /// # use parquet::arrow::arrow_writer::{
597    /// #     ArrowWriter, ArrowWriterOptions, PageKey, PageStore, PageStoreArgs, PageStoreFactory,
598    /// # };
599    /// # use parquet::arrow::arrow_reader::ParquetRecordBatchReader;
600    /// # use parquet::errors::Result;
601    /// struct TempFilePageStore {
602    ///     file: File,
603    ///     /// Total size of the file
604    ///     end: u64,
605    ///     /// Location of pages: (offset, len)
606    ///     locs: Vec<(u64, usize)>,
607    /// }
608    ///
609    /// impl PageStore for TempFilePageStore {
610    ///     fn put(&mut self, value: Bytes) -> Result<PageKey> {
611    ///         // Append to the end of the file
612    ///         self.file.seek(SeekFrom::Start(self.end))?;
613    ///         self.file.write_all(&value)?;
614    ///         let key = PageKey::new(self.locs.len() as u64);
615    ///         self.locs.push((self.end, value.len()));
616    ///         self.end += value.len() as u64;
617    ///         Ok(key)
618    ///     }
619    ///
620    ///     fn take(&mut self, key: PageKey) -> Result<Bytes> {
621    ///         let (offset, len) = self.locs[key.get() as usize];
622    ///         let mut buf = vec![0u8; len];
623    ///         self.file.seek(SeekFrom::Start(offset))?;
624    ///         self.file.read_exact(&mut buf)?;
625    ///         Ok(Bytes::from(buf))
626    ///     }
627    /// }
628    ///
629    /// /// Factory for creating [`TempFilePageStore`]
630    /// #[derive(Debug)]
631    /// struct TempFilePageStoreFactory;
632    ///
633    /// impl PageStoreFactory for TempFilePageStoreFactory {
634    ///     fn create(&self, args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
635    ///         // `args` exposes the column index and descriptor (physical/logical
636    ///         // type, path), so a real backend might choose to spill only large columns.
637    ///         let _ = (args.column_index(), args.column_descriptor());
638    ///         Ok(Box::new(TempFilePageStore {
639    ///             file: tempfile::tempfile()?, // temp file is cleaned on drop
640    ///             end: 0,
641    ///             locs: Vec::new(),
642    ///         }))
643    ///     }
644    /// }
645    /// // write 1000 integers
646    /// let col = Arc::new(Int64Array::from_iter_values(0..1000)) as ArrayRef;
647    /// let to_write = RecordBatch::try_from_iter([("col", col)]).unwrap();
648    ///
649    /// let options =
650    ///     ArrowWriterOptions::new().with_page_store_factory(Arc::new(TempFilePageStoreFactory));
651    /// let mut buffer = Vec::new();
652    /// let mut writer =
653    ///     ArrowWriter::try_new_with_options(&mut buffer, to_write.schema(), options).unwrap();
654    /// writer.write(&to_write).unwrap();
655    /// writer.close().unwrap();
656    ///
657    /// // buffer now holds valid Parquet data, which can be read as normal:
658    /// let mut reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), 1024).unwrap();
659    /// assert_eq!(to_write, reader.next().unwrap().unwrap());
660    /// ```
661    pub fn with_page_store_factory(self, page_store_factory: Arc<dyn PageStoreFactory>) -> Self {
662        Self {
663            page_store_factory: Some(page_store_factory),
664            ..self
665        }
666    }
667
668    /// Skip encoding the embedded arrow metadata (defaults to `false`)
669    ///
670    /// Parquet files generated by the [`ArrowWriter`] contain embedded arrow schema
671    /// by default.
672    ///
673    /// Set `skip_arrow_metadata` to true, to skip encoding the embedded metadata.
674    pub fn with_skip_arrow_metadata(self, skip_arrow_metadata: bool) -> Self {
675        Self {
676            skip_arrow_metadata,
677            ..self
678        }
679    }
680
681    /// Set the name of the root parquet schema element (defaults to `"arrow_schema"`)
682    pub fn with_schema_root(self, schema_root: String) -> Self {
683        Self {
684            schema_root: Some(schema_root),
685            ..self
686        }
687    }
688
689    /// Explicitly specify the Parquet schema to be used
690    ///
691    /// If omitted (the default), the [`ArrowSchemaConverter`] is used to compute the
692    /// Parquet [`SchemaDescriptor`]. This may be used When the [`SchemaDescriptor`] is
693    /// already known or must be calculated using custom logic.
694    pub fn with_parquet_schema(self, schema_descr: SchemaDescriptor) -> Self {
695        Self {
696            schema_descr: Some(schema_descr),
697            ..self
698        }
699    }
700}
701
702/// A single column chunk produced by [`ArrowColumnWriter`].
703///
704/// Holds the serialized page blobs (each page's header ‖ compressed data, in
705/// write order) in a [`PageStore`], plus the handles needed to read them back,
706/// in order, when the chunk is spliced into the output file.
707struct ArrowColumnChunkData {
708    length: usize,
709    store: Box<dyn PageStore>,
710    keys: Vec<PageKey>,
711    /// Handles to the dictionary page's blobs (header then data) in the store.
712    ///
713    /// A dictionary page is produced at most once and bounded by
714    /// `dict_page_size_limit`, but it must be written *first* in the chunk even
715    /// though the data pages reach the writer before it (see
716    /// [`PageWriter::defers_dictionary_ordering`]). Its header and data are `put`
717    /// into the store like any other page — which keeps the store uniform, and
718    /// lets an oversized dictionary page spill — and their handles are held apart
719    /// so they can be emitted ahead of the data pages at splice.
720    /// Empty for non-dictionary columns.
721    dictionary_keys: Vec<PageKey>,
722    /// Serialized length of the dictionary page (0 if there is none), recorded
723    /// so the data pages can be shifted past it when offsets are rewritten to a
724    /// dictionary-first layout at splice.
725    dictionary_len: usize,
726}
727
728impl ArrowColumnChunkData {
729    fn new(store: Box<dyn PageStore>) -> Self {
730        Self {
731            length: 0,
732            store,
733            keys: Vec::new(),
734            dictionary_keys: Vec::new(),
735            dictionary_len: 0,
736        }
737    }
738
739    /// Append a data-page blob to the store, recording its handle in write
740    /// order.
741    fn push(&mut self, value: Bytes) -> Result<()> {
742        let key = self.store.put(value)?;
743        self.keys.push(key);
744        Ok(())
745    }
746
747    /// Store a dictionary-page blob (header or data) in the page store,
748    /// recording its handle (emitted first at splice) and accumulating its
749    /// serialized length.
750    fn push_dictionary(&mut self, value: Bytes) -> Result<()> {
751        self.dictionary_len += value.len();
752        let key = self.store.put(value)?;
753        self.dictionary_keys.push(key);
754        Ok(())
755    }
756
757    /// Bytes this chunk currently holds on the heap: whatever the store keeps
758    /// resident (zero for a spilling backend).
759    fn memory_size(&self) -> usize {
760        self.store.memory_size()
761    }
762}
763
764/// A streaming iterator over one column chunk's buffered page blobs, in final
765/// file order: the dictionary page (if any) first, then the data pages.
766///
767/// Each blob is taken back out of the [`PageStore`] *as it is
768/// consumed* and released immediately afterwards, so splicing a chunk into the
769/// output file never materializes more than a single page in memory at a time.
770/// This is what keeps the splice phase within the memory bound for a spilling
771/// backend (an in-memory store already holds the bytes, so it is unaffected).
772struct StreamingColumnChunkPages {
773    store: Box<dyn PageStore>,
774    /// Page handles in final file order: the dictionary page first (if any),
775    /// then the data pages.
776    keys: IntoIter<PageKey>,
777}
778
779impl StreamingColumnChunkPages {
780    fn new(data: ArrowColumnChunkData) -> Self {
781        // The dictionary page must be emitted first, ahead of the data pages,
782        // even though it was the last page produced.
783        let keys = if data.dictionary_keys.is_empty() {
784            data.keys
785        } else {
786            let mut keys = Vec::with_capacity(data.dictionary_keys.len() + data.keys.len());
787            keys.extend(data.dictionary_keys);
788            keys.extend(data.keys);
789            keys
790        };
791        Self {
792            store: data.store,
793            keys: keys.into_iter(),
794        }
795    }
796}
797
798impl Iterator for StreamingColumnChunkPages {
799    type Item = Result<Bytes>;
800
801    fn next(&mut self) -> Option<Self::Item> {
802        let key = self.keys.next()?;
803        Some(self.store.take(key))
804    }
805}
806
807/// A shared [`ArrowColumnChunkData`]
808///
809/// This allows it to be owned by [`ArrowPageWriter`] whilst allowing access via
810/// [`ArrowRowGroupWriter`] on flush, without requiring self-referential borrows
811type SharedColumnChunk = Arc<Mutex<ArrowColumnChunkData>>;
812
813struct ArrowPageWriter {
814    buffer: SharedColumnChunk,
815    #[cfg(feature = "encryption")]
816    page_encryptor: Option<PageEncryptor>,
817}
818
819impl ArrowPageWriter {
820    /// Create a page writer that buffers completed pages in `store`.
821    fn new(store: Box<dyn PageStore>) -> Self {
822        Self {
823            buffer: Arc::new(Mutex::new(ArrowColumnChunkData::new(store))),
824            #[cfg(feature = "encryption")]
825            page_encryptor: None,
826        }
827    }
828
829    #[cfg(feature = "encryption")]
830    pub fn with_encryptor(mut self, page_encryptor: Option<PageEncryptor>) -> Self {
831        self.page_encryptor = page_encryptor;
832        self
833    }
834
835    #[cfg(feature = "encryption")]
836    fn page_encryptor_mut(&mut self) -> Option<&mut PageEncryptor> {
837        self.page_encryptor.as_mut()
838    }
839
840    // Mirrors the signature of the encryption-enabled version above, so that the
841    // callers do not need a `cfg` of their own.
842    #[cfg(not(feature = "encryption"))]
843    #[expect(
844        clippy::needless_pass_by_ref_mut,
845        reason = "mirrors the encryption-enabled signature"
846    )]
847    fn page_encryptor_mut(&mut self) -> Option<&mut PageEncryptor> {
848        None
849    }
850}
851
852impl PageWriter for ArrowPageWriter {
853    fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> {
854        let page = match self.page_encryptor_mut() {
855            Some(page_encryptor) => page_encryptor.encrypt_compressed_page(page)?,
856            None => page,
857        };
858
859        let page_header = page.to_thrift_header()?;
860        let header = {
861            let mut header = Vec::with_capacity(1024);
862
863            match self.page_encryptor_mut() {
864                Some(page_encryptor) => {
865                    page_encryptor.encrypt_page_header(&page_header, &mut header)?;
866                    if page.compressed_page().is_data_page() {
867                        page_encryptor.increment_page();
868                    }
869                }
870                None => {
871                    let mut protocol = ThriftCompactOutputProtocol::new(&mut header);
872                    page_header.write_thrift(&mut protocol)?;
873                }
874            }
875
876            Bytes::from(header)
877        };
878
879        let mut buf = self.buffer.try_lock().unwrap();
880
881        let data = page.compressed_page().buffer().clone();
882        let compressed_size = data.len() + header.len();
883
884        let mut spec = PageWriteSpec::new();
885        spec.page_type = page.page_type();
886        spec.num_values = page.num_values();
887        spec.uncompressed_size = page.uncompressed_size() + header.len();
888        spec.offset = buf.length as u64;
889        spec.compressed_size = compressed_size;
890        spec.bytes_written = compressed_size as u64;
891
892        buf.length += compressed_size;
893        if spec.page_type == PageType::DICTIONARY_PAGE {
894            // Recorded apart from the data pages so it is emitted first at
895            // splice — see `ArrowColumnChunkData::dictionary_keys`.
896            buf.push_dictionary(header)?;
897            buf.push_dictionary(data)?;
898        } else {
899            buf.push(header)?;
900            buf.push(data)?;
901        }
902
903        Ok(spec)
904    }
905
906    fn defers_dictionary_ordering(&self) -> bool {
907        // The Arrow chunk is buffered in full and spliced at row-group flush, so
908        // data pages may be accepted before the dictionary page and reordered
909        // then. This lets `GenericColumnWriter` stream dictionary-column data
910        // pages straight through instead of buffering them in memory.
911        true
912    }
913
914    fn buffered_memory_size(&self) -> usize {
915        // Only what is actually resident: a spilling store reports ~0 here even
916        // though the chunk's bytes have all passed through it.
917        self.buffer.try_lock().unwrap().memory_size()
918    }
919
920    fn close(&mut self) -> Result<()> {
921        Ok(())
922    }
923}
924
925/// A leaf column that can be encoded by [`ArrowColumnWriter`]
926#[derive(Debug)]
927pub struct ArrowLeafColumn(ArrayLevels);
928
929/// Computes the [`ArrowLeafColumn`] for a potentially nested [`ArrayRef`]
930///
931/// This function can be used to encode individual columns in parallel.
932/// See example on [`ArrowColumnWriter`]
933pub fn compute_leaves(field: &Field, array: &ArrayRef) -> Result<Vec<ArrowLeafColumn>> {
934    let levels = calculate_array_levels(array, field)?;
935    Ok(levels.into_iter().map(ArrowLeafColumn).collect())
936}
937
938/// The data for a single column chunk, see [`ArrowColumnWriter`]
939pub struct ArrowColumnChunk {
940    data: ArrowColumnChunkData,
941    close: ColumnCloseResult,
942}
943
944impl std::fmt::Debug for ArrowColumnChunk {
945    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
946        f.debug_struct("ArrowColumnChunk")
947            .field("length", &self.data.length)
948            .finish_non_exhaustive()
949    }
950}
951
952impl ArrowColumnChunk {
953    /// Returns the [`ColumnCloseResult`] produced when the chunk was closed.
954    ///
955    /// Exposes encoding information, collected statistics, and the optional
956    /// [`ColumnIndexMetaData`](crate::file::page_index::column_index::ColumnIndexMetaData)
957    /// / [`OffsetIndexMetaData`](crate::file::page_index::offset_index::OffsetIndexMetaData)
958    /// gathered for the column chunk.
959    pub fn close(&self) -> &ColumnCloseResult {
960        &self.close
961    }
962
963    /// Returns a mutable reference to the [`ColumnCloseResult`].
964    ///
965    /// This allows callers to mutate the close result before the chunk is
966    /// appended to a row group — for example, clearing `column_index` or
967    /// `bloom_filter` based on a dynamic rule that inspects the encodings and
968    /// collected page statistics.
969    pub fn close_mut(&mut self) -> &mut ColumnCloseResult {
970        &mut self.close
971    }
972
973    /// Splices this column's buffered pages into the row group, streaming them
974    /// back out of the [`PageStore`] one page at a time.
975    pub fn append_to_row_group<W: Write + Send>(
976        self,
977        writer: &mut SerializedRowGroupWriter<'_, W>,
978    ) -> Result<()> {
979        let ArrowColumnChunk { data, close } = self;
980
981        // The dictionary page is produced *after* the data pages on this path (so
982        // they can stream straight through) but must be written *first*, so move
983        // it ahead of the data pages in the recorded offsets before the splice.
984        let close = close.update_dictionary_location(data.dictionary_len)?;
985
986        let pages = StreamingColumnChunkPages::new(data);
987        writer.append_column_from_pages(pages, close)
988    }
989}
990
991/// Encodes [`ArrowLeafColumn`] to [`ArrowColumnChunk`]
992///
993/// `ArrowColumnWriter` instances can be created using an [`ArrowRowGroupWriterFactory`];
994///
995/// Note: This is a low-level interface for applications that require
996/// fine-grained control of encoding (e.g. encoding using multiple threads),
997/// see [`ArrowWriter`] for a higher-level interface
998///
999/// # Example: Encoding two Arrow Array's in Parallel
1000/// ```
1001/// // The arrow schema
1002/// # use std::sync::Arc;
1003/// # use arrow_array::*;
1004/// # use arrow_schema::*;
1005/// # use parquet::arrow::ArrowSchemaConverter;
1006/// # use parquet::arrow::arrow_writer::{compute_leaves, ArrowColumnChunk, ArrowLeafColumn, ArrowRowGroupWriterFactory};
1007/// # use parquet::file::properties::WriterProperties;
1008/// # use parquet::file::writer::{SerializedFileWriter, SerializedRowGroupWriter};
1009/// #
1010/// let schema = Arc::new(Schema::new(vec![
1011///     Field::new("i32", DataType::Int32, false),
1012///     Field::new("f32", DataType::Float32, false),
1013/// ]));
1014///
1015/// // Compute the parquet schema
1016/// let props = Arc::new(WriterProperties::default());
1017/// let parquet_schema = ArrowSchemaConverter::new()
1018///   .with_coerce_types(props.coerce_types())
1019///   .convert(&schema)
1020///   .unwrap();
1021///
1022/// // Create parquet writer
1023/// let root_schema = parquet_schema.root_schema_ptr();
1024/// // write to memory in the example, but this could be a File
1025/// let mut out = Vec::with_capacity(1024);
1026/// let mut writer = SerializedFileWriter::new(&mut out, root_schema, props.clone())
1027///   .unwrap();
1028///
1029/// // Create a factory for building Arrow column writers
1030/// let row_group_factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
1031/// // Create column writers for the 0th row group
1032/// let col_writers = row_group_factory.create_column_writers(0).unwrap();
1033///
1034/// // Spawn a worker thread for each column
1035/// //
1036/// // Note: This is for demonstration purposes, a thread-pool e.g. rayon or tokio, would be better.
1037/// // The `map` produces an iterator of type `tuple of (thread handle, send channel)`.
1038/// let mut workers: Vec<_> = col_writers
1039///     .into_iter()
1040///     .map(|mut col_writer| {
1041///         let (send, recv) = std::sync::mpsc::channel::<ArrowLeafColumn>();
1042///         let handle = std::thread::spawn(move || {
1043///             // receive Arrays to encode via the channel
1044///             for col in recv {
1045///                 col_writer.write(&col)?;
1046///             }
1047///             // once the input is complete, close the writer
1048///             // to return the newly created ArrowColumnChunk
1049///             col_writer.close()
1050///         });
1051///         (handle, send)
1052///     })
1053///     .collect();
1054///
1055/// // Start row group
1056/// let mut row_group_writer: SerializedRowGroupWriter<'_, _> = writer
1057///   .next_row_group()
1058///   .unwrap();
1059///
1060/// // Create some example input columns to encode
1061/// let to_write = vec![
1062///     Arc::new(Int32Array::from_iter_values([1, 2, 3])) as _,
1063///     Arc::new(Float32Array::from_iter_values([1., 45., -1.])) as _,
1064/// ];
1065///
1066/// // Send the input columns to the workers
1067/// let mut worker_iter = workers.iter_mut();
1068/// for (arr, field) in to_write.iter().zip(&schema.fields) {
1069///     for leaves in compute_leaves(field, arr).unwrap() {
1070///         worker_iter.next().unwrap().1.send(leaves).unwrap();
1071///     }
1072/// }
1073///
1074/// // Wait for the workers to complete encoding, and append
1075/// // the resulting column chunks to the row group (and the file)
1076/// for (handle, send) in workers {
1077///     drop(send); // Drop send side to signal termination
1078///     // wait for the worker to send the completed chunk
1079///     let chunk: ArrowColumnChunk = handle.join().unwrap().unwrap();
1080///     chunk.append_to_row_group(&mut row_group_writer).unwrap();
1081/// }
1082/// // Close the row group which writes to the underlying file
1083/// row_group_writer.close().unwrap();
1084///
1085/// let metadata = writer.close().unwrap();
1086/// assert_eq!(metadata.file_metadata().num_rows(), 3);
1087/// ```
1088pub struct ArrowColumnWriter {
1089    writer: ArrowColumnWriterImpl,
1090    chunk: SharedColumnChunk,
1091    /// Non-null value hashes accumulated across all writes for this column's row group.
1092    /// `None` when tracking is disabled via [`WriterProperties::write_row_group_number_distinct_values`].
1093    distinct_values_seen: Option<DistinctValuesSet>,
1094}
1095
1096impl std::fmt::Debug for ArrowColumnWriter {
1097    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1098        f.debug_struct("ArrowColumnWriter").finish_non_exhaustive()
1099    }
1100}
1101
1102enum ArrowColumnWriterImpl {
1103    ByteArray(GenericColumnWriter<'static, ByteArrayEncoder>),
1104    Column(ColumnWriter<'static>),
1105}
1106
1107impl ArrowColumnWriter {
1108    /// Write an [`ArrowLeafColumn`]
1109    pub fn write(&mut self, col: &ArrowLeafColumn) -> Result<()> {
1110        self.write_internal(&col.0)
1111    }
1112
1113    /// Write with content-defined chunking, inserting page flushes at chunk boundaries.
1114    fn write_with_chunker(
1115        &mut self,
1116        col: &ArrowLeafColumn,
1117        chunker: &mut ContentDefinedChunker,
1118    ) -> Result<()> {
1119        let levels = &col.0;
1120        let chunks = chunker.get_arrow_chunks(
1121            levels.def_level_data().as_ref(),
1122            levels.rep_level_data().as_ref(),
1123            levels.array(),
1124        )?;
1125
1126        let num_chunks = chunks.len();
1127        for (i, chunk) in chunks.iter().enumerate() {
1128            let chunk_levels = levels.slice_for_chunk(chunk);
1129            self.write_internal(&chunk_levels)?;
1130
1131            // Add a page break after each chunk except the last
1132            if i + 1 < num_chunks {
1133                match &mut self.writer {
1134                    ArrowColumnWriterImpl::Column(c) => c.add_data_page()?,
1135                    ArrowColumnWriterImpl::ByteArray(c) => c.add_data_page()?,
1136                }
1137            }
1138        }
1139        Ok(())
1140    }
1141
1142    fn write_internal(&mut self, levels: &ArrayLevels) -> Result<()> {
1143        if let Some(seen) = &mut self.distinct_values_seen {
1144            let array = levels.array();
1145            let non_null = levels.non_null_indices();
1146            match array.as_any_dictionary_opt() {
1147                Some(dict) => {
1148                    // For dictionary arrays, hash the integer keys rather than the actual values.
1149                    // Key cardinality equals value cardinality, so distinct-value counting stays
1150                    // correct while avoiding the cost of hashing arbitrary-length values.
1151                    let keys = dict.keys();
1152                    let key_data = keys.to_data();
1153                    let offset = key_data.offset();
1154                    let width = arrow_key_byte_width(keys.data_type());
1155                    if width > 0 {
1156                        let buffer = key_data.buffers()[0].as_slice();
1157                        // Only visit non-null rows to avoid counting nulls as a distinct value.
1158                        for &row in non_null {
1159                            let pos = (offset + row) * width;
1160                            seen.insert(hash_bytes(&buffer[pos..pos + width]));
1161                        }
1162                    }
1163                }
1164                // For plain arrays, hash the actual values directly.
1165                None => update_distinct_values_seen(array.as_ref(), non_null, seen),
1166            }
1167        }
1168
1169        match &mut self.writer {
1170            ArrowColumnWriterImpl::Column(c) => {
1171                let leaf = levels.array();
1172                match leaf.as_any_dictionary_opt() {
1173                    Some(dictionary) => {
1174                        let materialized =
1175                            arrow_select::take::take(dictionary.values(), dictionary.keys(), None)?;
1176                        write_leaf(c, &materialized, levels)?
1177                    }
1178                    None => write_leaf(c, leaf, levels)?,
1179                };
1180            }
1181            ArrowColumnWriterImpl::ByteArray(c) => {
1182                write_primitive(c, levels.array().as_ref(), levels)?;
1183            }
1184        }
1185        Ok(())
1186    }
1187
1188    /// Close this column returning the written [`ArrowColumnChunk`]
1189    pub fn close(self) -> Result<ArrowColumnChunk> {
1190        let distinct_count = self
1191            .distinct_values_seen
1192            .as_ref()
1193            .filter(|s| !s.is_empty())
1194            .map(|s| s.len() as u64);
1195        let close = match self.writer {
1196            ArrowColumnWriterImpl::ByteArray(mut c) => {
1197                if let Some(count) = distinct_count {
1198                    c.set_distinct_count_override(count);
1199                }
1200                c.close()?
1201            }
1202            ArrowColumnWriterImpl::Column(mut c) => {
1203                if let Some(count) = distinct_count {
1204                    c.set_distinct_count_override(count);
1205                }
1206                c.close()?
1207            }
1208        };
1209        let chunk = Arc::try_unwrap(self.chunk).ok().unwrap();
1210        let data = chunk.into_inner().unwrap();
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 byte width of an Arrow dictionary key type, or 0 if unsupported.
1977fn arrow_key_byte_width(dt: &ArrowDataType) -> usize {
1978    match dt {
1979        ArrowDataType::Int8 | ArrowDataType::UInt8 => 1,
1980        ArrowDataType::Int16 | ArrowDataType::UInt16 => 2,
1981        ArrowDataType::Int32 | ArrowDataType::UInt32 => 4,
1982        ArrowDataType::Int64 | ArrowDataType::UInt64 => 8,
1983        _ => 0,
1984    }
1985}
1986
1987/// Returns the fixed byte width for primitive Arrow types, or `None` for variable-length types.
1988fn fixed_byte_width(dt: &ArrowDataType) -> Option<usize> {
1989    use ArrowDataType::*;
1990    match dt {
1991        Int8 | UInt8 => Some(1),
1992        Int16 | UInt16 | Float16 => Some(2),
1993        Int32 | UInt32 | Float32 | Date32 | Time32(_) | Decimal32(_, _) => Some(4),
1994        Int64
1995        | UInt64
1996        | Float64
1997        | Date64
1998        | Time64(_)
1999        | Timestamp(_, _)
2000        | Duration(_)
2001        | Decimal64(_, _) => Some(8),
2002        Interval(IntervalUnit::YearMonth) => Some(4),
2003        Interval(IntervalUnit::DayTime) => Some(8),
2004        Interval(IntervalUnit::MonthDayNano) => Some(16),
2005        Decimal128(_, _) => Some(16),
2006        Decimal256(_, _) => Some(32),
2007        _ => None,
2008    }
2009}
2010
2011/// Hash the non-null values in `array` (at `non_null_indices`) into `seen`.
2012///
2013/// Handles primitive, boolean, fixed-size-binary, and variable-length (Utf8/Binary)
2014/// arrays. Unsupported types are silently skipped, leaving `seen` unchanged for
2015/// those values (NDV is best-effort).
2016fn update_distinct_values_seen(
2017    array: &dyn arrow_array::Array,
2018    non_null_indices: &[usize],
2019    seen: &mut DistinctValuesSet,
2020) {
2021    let data = array.to_data();
2022    let offset = data.offset();
2023
2024    match array.data_type() {
2025        ArrowDataType::Boolean => {
2026            let arr = array
2027                .as_any()
2028                .downcast_ref::<arrow_array::BooleanArray>()
2029                .unwrap();
2030            for &row in non_null_indices {
2031                seen.insert(arr.value(row) as u64);
2032            }
2033        }
2034        ArrowDataType::Utf8 | ArrowDataType::Binary => {
2035            let offsets = data.buffers()[0].typed_data::<i32>();
2036            let values = data.buffers()[1].as_slice();
2037            for &row in non_null_indices {
2038                let start = offsets[offset + row] as usize;
2039                let end = offsets[offset + row + 1] as usize;
2040                seen.insert(hash_bytes(&values[start..end]));
2041            }
2042        }
2043        ArrowDataType::LargeUtf8 | ArrowDataType::LargeBinary => {
2044            let offsets = data.buffers()[0].typed_data::<i64>();
2045            let values = data.buffers()[1].as_slice();
2046            for &row in non_null_indices {
2047                let start = offsets[offset + row] as usize;
2048                let end = offsets[offset + row + 1] as usize;
2049                seen.insert(hash_bytes(&values[start..end]));
2050            }
2051        }
2052        ArrowDataType::FixedSizeBinary(byte_width) => {
2053            let byte_width = *byte_width as usize;
2054            let buffer = data.buffers()[0].as_slice();
2055            for &row in non_null_indices {
2056                let start = (offset + row) * byte_width;
2057                seen.insert(hash_bytes(&buffer[start..start + byte_width]));
2058            }
2059        }
2060        data_type => {
2061            if let Some(width) = fixed_byte_width(data_type) {
2062                let buffer = data.buffers()[0].as_slice();
2063                for &row in non_null_indices {
2064                    let pos = (offset + row) * width;
2065                    seen.insert(hash_bytes(&buffer[pos..pos + width]));
2066                }
2067            }
2068            // Utf8View, BinaryView, nested types: skip
2069        }
2070    }
2071}
2072
2073#[cfg(test)]
2074mod tests {
2075    use super::*;
2076    use std::cmp::Ordering;
2077    use std::collections::HashMap;
2078
2079    use std::fs::File;
2080
2081    use crate::arrow::arrow_reader::{ParquetRecordBatchReader, ParquetRecordBatchReaderBuilder};
2082    use crate::arrow::{ARROW_SCHEMA_META_KEY, PARQUET_FIELD_ID_META_KEY};
2083    use crate::column::page::{Page, PageReader};
2084    use crate::file::metadata::thrift::PageHeader;
2085    use crate::file::page_index::column_index::ColumnIndexMetaData;
2086    use crate::file::reader::SerializedPageReader;
2087    use crate::parquet_thrift::{ReadThrift, ThriftSliceInputProtocol};
2088    use crate::schema::types::ColumnPath;
2089    use arrow::datatypes::ToByteSlice;
2090    use arrow::datatypes::{DataType, Schema};
2091    use arrow::error::Result as ArrowResult;
2092    use arrow::util::data_gen::create_random_array;
2093    use arrow::util::pretty::pretty_format_batches;
2094    use arrow::{array::*, buffer::Buffer};
2095    use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano, NullBuffer, OffsetBuffer, i256};
2096    use arrow_schema::Fields;
2097    use half::f16;
2098    use num_traits::{FromPrimitive, ToPrimitive};
2099    use tempfile::tempfile;
2100
2101    use crate::basic::Encoding;
2102    use crate::data_type::AsBytes;
2103    use crate::file::metadata::{ColumnChunkMetaData, ParquetMetaData, ParquetMetaDataReader};
2104    use crate::file::properties::{
2105        BloomFilterPosition, EnabledStatistics, ReaderProperties, WriterVersion,
2106    };
2107    use crate::file::serialized_reader::ReadOptionsBuilder;
2108    use crate::file::{
2109        reader::{FileReader, SerializedFileReader},
2110        statistics::Statistics,
2111    };
2112
2113    /// A [`PageStore`] that allocates *sparse, non-contiguous* handles and keeps
2114    /// blobs in a `HashMap` — nothing like the default `Vec<Bytes>`. Used to
2115    /// prove the writer relies only on the opaque-handle contract and never on
2116    /// handles being dense `Vec` indices. Records how many blobs were stored.
2117    #[derive(Debug, Default)]
2118    struct RecordingPageStore {
2119        next: u64,
2120        blobs: HashMap<u64, Bytes>,
2121        puts: Arc<std::sync::atomic::AtomicUsize>,
2122    }
2123
2124    impl PageStore for RecordingPageStore {
2125        fn put(&mut self, value: Bytes) -> Result<PageKey> {
2126            // Deliberately non-sequential, never-zero handles.
2127            let id = 100 + self.next * 7;
2128            self.next += 1;
2129            self.puts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2130            self.blobs.insert(id, value);
2131            Ok(PageKey::new(id))
2132        }
2133
2134        fn take(&mut self, key: PageKey) -> Result<Bytes> {
2135            self.blobs
2136                .remove(&key.get())
2137                .ok_or_else(|| ParquetError::General(format!("missing key {}", key.get())))
2138        }
2139    }
2140
2141    #[derive(Debug)]
2142    struct RecordingPageStoreFactory {
2143        puts: Arc<std::sync::atomic::AtomicUsize>,
2144    }
2145
2146    impl PageStoreFactory for RecordingPageStoreFactory {
2147        fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2148            Ok(Box::new(RecordingPageStore {
2149                puts: self.puts.clone(),
2150                ..Default::default()
2151            }))
2152        }
2153    }
2154
2155    /// A custom [`PageStore`] must produce byte-identical files to the in-memory
2156    /// default, across dictionary and non-dictionary columns and multiple row
2157    /// groups (so multiple store instances are exercised).
2158    #[test]
2159    fn custom_page_store_is_byte_identical_to_default() {
2160        let schema = Arc::new(Schema::new(vec![
2161            Field::new("i", DataType::Int32, true),
2162            // A low-cardinality string column to exercise the dictionary path.
2163            Field::new("s", DataType::Utf8, true),
2164        ]));
2165        let i = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5), Some(6)]);
2166        let s = StringArray::from(vec![
2167            Some("a"),
2168            Some("bb"),
2169            Some("a"),
2170            None,
2171            Some("bb"),
2172            Some("ccc"),
2173        ]);
2174        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(i), Arc::new(s)]).unwrap();
2175
2176        // Small row groups so multiple column chunks (hence multiple store
2177        // instances) are produced.
2178        let props = WriterProperties::builder()
2179            .set_max_row_group_row_count(Some(3))
2180            .build();
2181
2182        let write = |factory: Option<Arc<dyn PageStoreFactory>>| {
2183            let mut buffer = Vec::new();
2184            let mut opts = ArrowWriterOptions::new().with_properties(props.clone());
2185            if let Some(factory) = factory {
2186                opts = opts.with_page_store_factory(factory);
2187            }
2188            let mut writer =
2189                ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2190            writer.write(&batch).unwrap();
2191            writer.close().unwrap();
2192            buffer
2193        };
2194
2195        let default_bytes = write(None);
2196
2197        let puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2198        let custom_bytes = write(Some(Arc::new(RecordingPageStoreFactory {
2199            puts: puts.clone(),
2200        })));
2201
2202        assert!(
2203            puts.load(std::sync::atomic::Ordering::Relaxed) > 0,
2204            "custom PageStore was never written to"
2205        );
2206        assert_eq!(
2207            default_bytes, custom_bytes,
2208            "a custom PageStore must produce byte-identical output to the default"
2209        );
2210    }
2211
2212    /// A dictionary-encoded column written through the deferred-ordering Arrow
2213    /// path must round-trip correctly even with the offset index disabled, when
2214    /// only the chunk-level dictionary/data page offsets are rewritten (there is
2215    /// no offset index to rebuild). Spans multiple data pages so the
2216    /// dictionary-first reordering is exercised.
2217    #[test]
2218    #[cfg_attr(miri, ignore)] // Takes too long
2219    fn dictionary_column_round_trips_with_offset_index_disabled() {
2220        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2221
2222        // Low cardinality so the column stays dictionary-encoded; enough rows to
2223        // span several data pages within a single row group.
2224        let values: Vec<Option<i32>> = (0..50_000).map(|i| Some(i % 8)).collect();
2225        let array = Int32Array::from(values.clone());
2226        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2227
2228        let props = WriterProperties::builder()
2229            .set_offset_index_disabled(true)
2230            .set_data_page_row_count_limit(4096)
2231            .build();
2232        let opts = ArrowWriterOptions::new().with_properties(props);
2233
2234        let mut buffer = Vec::new();
2235        let mut writer =
2236            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2237        writer.write(&batch).unwrap();
2238        writer.close().unwrap();
2239
2240        let reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), values.len()).unwrap();
2241        let read: Vec<RecordBatch> = reader.collect::<ArrowResult<_>>().unwrap();
2242        let read_values: Vec<Option<i32>> = read
2243            .iter()
2244            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().iter())
2245            .collect();
2246        assert_eq!(read_values, values);
2247    }
2248
2249    /// The dictionary page is routed through the [`PageStore`] like any other
2250    /// page rather than held resident in memory, so a dictionary column chunk's
2251    /// *entire* serialized size — dictionary page included — passes through the
2252    /// store.
2253    #[test]
2254    fn dictionary_page_is_routed_through_the_store() {
2255        /// A store that sums the bytes handed to `put`.
2256        #[derive(Debug, Default)]
2257        struct SizeRecordingPageStore {
2258            blobs: Vec<Bytes>,
2259            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2260        }
2261        impl PageStore for SizeRecordingPageStore {
2262            fn put(&mut self, value: Bytes) -> Result<PageKey> {
2263                self.bytes_put
2264                    .fetch_add(value.len(), std::sync::atomic::Ordering::Relaxed);
2265                let key = PageKey::new(self.blobs.len() as u64);
2266                self.blobs.push(value);
2267                Ok(key)
2268            }
2269            fn take(&mut self, key: PageKey) -> Result<Bytes> {
2270                Ok(std::mem::take(&mut self.blobs[key.get() as usize]))
2271            }
2272        }
2273        #[derive(Debug)]
2274        struct Factory {
2275            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2276        }
2277        impl PageStoreFactory for Factory {
2278            fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2279                Ok(Box::new(SizeRecordingPageStore {
2280                    bytes_put: self.bytes_put.clone(),
2281                    ..Default::default()
2282                }))
2283            }
2284        }
2285
2286        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)]));
2287        // Low cardinality keeps the column dictionary-encoded with a real,
2288        // non-empty dictionary page.
2289        let values: Vec<&str> = (0..2048)
2290            .map(|i| ["alpha", "beta", "gamma", "delta"][i % 4])
2291            .collect();
2292        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(StringArray::from(values))])
2293            .unwrap();
2294
2295        let bytes_put = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2296        let opts = ArrowWriterOptions::new().with_page_store_factory(Arc::new(Factory {
2297            bytes_put: bytes_put.clone(),
2298        }));
2299
2300        // A single batch / single column means exactly one row group and one
2301        // store instance, so the bytes it saw map to one column chunk.
2302        let mut buffer = Vec::new();
2303        let mut writer =
2304            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2305        writer.write(&batch).unwrap();
2306        writer.close().unwrap();
2307
2308        let reader = SerializedFileReader::new(Bytes::from(buffer)).unwrap();
2309        let column = reader.metadata().row_group(0).column(0);
2310        assert!(
2311            column.dictionary_page_offset().is_some(),
2312            "expected the column to be dictionary-encoded"
2313        );
2314
2315        // The bytes the store was handed must account for the whole chunk,
2316        // dictionary page included. Holding the dictionary page apart from the
2317        // store would make this fall short by the dictionary page's size.
2318        assert_eq!(
2319            bytes_put.load(std::sync::atomic::Ordering::Relaxed) as i64,
2320            column.compressed_size(),
2321            "the dictionary page must pass through the store like any other page"
2322        );
2323    }
2324
2325    #[test]
2326    fn arrow_writer() {
2327        // define schema
2328        let schema = Schema::new(vec![
2329            Field::new("a", DataType::Int32, false),
2330            Field::new("b", DataType::Int32, true),
2331        ]);
2332
2333        // create some data
2334        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2335        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2336
2337        // build a record batch
2338        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)]).unwrap();
2339
2340        roundtrip(batch, Some(SMALL_SIZE / 2));
2341    }
2342
2343    fn get_bytes_after_close(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2344        let mut buffer = vec![];
2345
2346        let mut writer = ArrowWriter::try_new(&mut buffer, schema, None).unwrap();
2347        writer.write(expected_batch).unwrap();
2348        writer.close().unwrap();
2349
2350        buffer
2351    }
2352
2353    fn get_bytes_by_into_inner(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2354        let mut writer = ArrowWriter::try_new(Vec::new(), schema, None).unwrap();
2355        writer.write(expected_batch).unwrap();
2356        writer.into_inner().unwrap()
2357    }
2358
2359    #[test]
2360    fn roundtrip_bytes() {
2361        // define schema
2362        let schema = Arc::new(Schema::new(vec![
2363            Field::new("a", DataType::Int32, false),
2364            Field::new("b", DataType::Int32, true),
2365        ]));
2366
2367        // create some data
2368        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2369        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2370
2371        // build a record batch
2372        let expected_batch =
2373            RecordBatch::try_new(schema.clone(), vec![Arc::new(a), Arc::new(b)]).unwrap();
2374
2375        for buffer in [
2376            get_bytes_after_close(schema.clone(), &expected_batch),
2377            get_bytes_by_into_inner(schema, &expected_batch),
2378        ] {
2379            let cursor = Bytes::from(buffer);
2380            let mut record_batch_reader = ParquetRecordBatchReader::try_new(cursor, 1024).unwrap();
2381
2382            let actual_batch = record_batch_reader
2383                .next()
2384                .expect("No batch found")
2385                .expect("Unable to get batch");
2386
2387            assert_eq!(expected_batch.schema(), actual_batch.schema());
2388            assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
2389            assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
2390            for i in 0..expected_batch.num_columns() {
2391                let expected_data = expected_batch.column(i).to_data();
2392                let actual_data = actual_batch.column(i).to_data();
2393
2394                assert_eq!(expected_data, actual_data);
2395            }
2396        }
2397    }
2398
2399    #[test]
2400    #[cfg_attr(miri, ignore)] // Takes too long
2401    fn arrow_writer_non_null() {
2402        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2403        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2404
2405        RoundTripTest::new(Arc::new(a))
2406            .with_schema(Arc::new(schema))
2407            .run();
2408    }
2409
2410    #[test]
2411    #[cfg_attr(miri, ignore)] // Takes too long
2412    fn arrow_writer_list() {
2413        // define schema
2414        let schema = Schema::new(vec![Field::new(
2415            "a",
2416            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false))),
2417            true,
2418        )]);
2419
2420        // create some data
2421        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2422
2423        // Construct a buffer for value offsets, for the nested array:
2424        //  [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
2425        let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
2426
2427        // Construct a list array from the above two
2428        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
2429            DataType::Int32,
2430            false,
2431        ))))
2432        .len(5)
2433        .add_buffer(a_value_offsets)
2434        .add_child_data(a_values.into_data())
2435        .null_bit_buffer(Some(Buffer::from([0b00011011])))
2436        .build()
2437        .unwrap();
2438        let a = ListArray::from(a_list_data);
2439        assert_eq!(a.null_count(), 1);
2440
2441        RoundTripTest::new(Arc::new(a))
2442            .with_schema(Arc::new(schema))
2443            .run();
2444    }
2445
2446    #[test]
2447    #[cfg_attr(miri, ignore)] // Takes too long
2448    fn arrow_writer_list_non_null() {
2449        // define schema
2450        let schema = Schema::new(vec![Field::new(
2451            "a",
2452            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false))),
2453            false,
2454        )]);
2455
2456        // create some data
2457        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2458
2459        // Construct a buffer for value offsets, for the nested array:
2460        //  [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
2461        let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
2462
2463        // Construct a list array from the above two
2464        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
2465            DataType::Int32,
2466            false,
2467        ))))
2468        .len(5)
2469        .add_buffer(a_value_offsets)
2470        .add_child_data(a_values.into_data())
2471        .build()
2472        .unwrap();
2473        let a = ListArray::from(a_list_data);
2474        assert_eq!(a.null_count(), 0);
2475
2476        RoundTripTest::new(Arc::new(a))
2477            .with_schema(Arc::new(schema))
2478            .run();
2479    }
2480
2481    #[test]
2482    #[cfg_attr(miri, ignore)] // Takes too long
2483    fn arrow_writer_list_view() {
2484        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2485        let schema = Schema::new(vec![Field::new(
2486            "a",
2487            DataType::ListView(list_field.clone()),
2488            true,
2489        )]);
2490
2491        //  [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
2492        let a = ListViewArray::new(
2493            list_field,
2494            vec![0, 1, 0, 3, 6].into(),
2495            vec![1, 2, 0, 3, 4].into(),
2496            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2497            Some(vec![true, true, false, true, true].into()),
2498        );
2499        assert_eq!(a.null_count(), 1);
2500
2501        RoundTripTest::new(Arc::new(a))
2502            .with_schema(Arc::new(schema))
2503            .run();
2504    }
2505
2506    #[test]
2507    #[cfg_attr(miri, ignore)] // Takes too long
2508    fn arrow_writer_list_view_non_null() {
2509        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2510        let schema = Schema::new(vec![Field::new(
2511            "a",
2512            DataType::ListView(list_field.clone()),
2513            false,
2514        )]);
2515
2516        //  [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
2517        let a = ListViewArray::new(
2518            list_field,
2519            vec![0, 1, 0, 3, 6].into(),
2520            vec![1, 2, 0, 3, 4].into(),
2521            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2522            None,
2523        );
2524        assert_eq!(a.null_count(), 0);
2525
2526        RoundTripTest::new(Arc::new(a))
2527            .with_schema(Arc::new(schema))
2528            .run();
2529    }
2530
2531    #[test]
2532    #[cfg_attr(miri, ignore)] // Takes too long
2533    fn arrow_writer_list_view_out_of_order() {
2534        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2535        let schema = Schema::new(vec![Field::new(
2536            "a",
2537            DataType::ListView(list_field.clone()),
2538            false,
2539        )]);
2540
2541        // [[1], [2, 3], [], [7, 8, 9, 10], [4, 5, 6]] - out of order offsets
2542        let a = ListViewArray::new(
2543            list_field,
2544            vec![0, 1, 0, 6, 3].into(),
2545            vec![1, 2, 0, 4, 3].into(),
2546            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2547            None,
2548        );
2549        assert_eq!(a.null_count(), 0);
2550
2551        RoundTripTest::new(Arc::new(a))
2552            .with_schema(Arc::new(schema))
2553            .run();
2554    }
2555
2556    #[test]
2557    #[cfg_attr(miri, ignore)] // Takes too long
2558    fn arrow_writer_large_list_view() {
2559        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2560        let schema = Schema::new(vec![Field::new(
2561            "a",
2562            DataType::LargeListView(list_field.clone()),
2563            true,
2564        )]);
2565
2566        //  [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
2567        let a = LargeListViewArray::new(
2568            list_field,
2569            vec![0i64, 1, 0, 3, 6].into(),
2570            vec![1i64, 2, 0, 3, 4].into(),
2571            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2572            Some(vec![true, true, false, true, true].into()),
2573        );
2574        assert_eq!(a.null_count(), 1);
2575
2576        RoundTripTest::new(Arc::new(a))
2577            .with_schema(Arc::new(schema))
2578            .run();
2579    }
2580
2581    #[test]
2582    #[cfg_attr(miri, ignore)] // Takes too long
2583    fn arrow_writer_list_view_with_struct() {
2584        // Test ListView containing Struct: ListView<Struct<Int32, Utf8>>
2585        let struct_fields = Fields::from(vec![
2586            Field::new("id", DataType::Int32, false),
2587            Field::new("name", DataType::Utf8, false),
2588        ]);
2589        let struct_type = DataType::Struct(struct_fields.clone());
2590        let list_field = Arc::new(Field::new("item", struct_type.clone(), false));
2591
2592        let schema = Schema::new(vec![Field::new(
2593            "a",
2594            DataType::ListView(list_field.clone()),
2595            true,
2596        )]);
2597
2598        // Create struct values
2599        let id_array = Int32Array::from(vec![1, 2, 3, 4, 5]);
2600        let name_array = StringArray::from(vec!["a", "b", "c", "d", "e"]);
2601        let struct_array = StructArray::new(
2602            struct_fields,
2603            vec![Arc::new(id_array), Arc::new(name_array)],
2604            None,
2605        );
2606
2607        // Create ListView: [{1, "a"}, {2, "b"}], null, [{3, "c"}, {4, "d"}, {5, "e"}]
2608        let list_view = ListViewArray::new(
2609            list_field,
2610            vec![0, 2, 2].into(), // offsets
2611            vec![2, 0, 3].into(), // sizes
2612            Arc::new(struct_array),
2613            Some(vec![true, false, true].into()),
2614        );
2615        assert_eq!(list_view.null_count(), 1);
2616
2617        RoundTripTest::new(Arc::new(list_view))
2618            .with_schema(Arc::new(schema))
2619            .run();
2620    }
2621
2622    #[test]
2623    #[cfg_attr(miri, ignore)] // Takes too long
2624    fn arrow_writer_binary() {
2625        let raw_string_values = vec!["foo", "bar", "baz", "quux"];
2626        let raw_binary_values = [
2627            b"foo".to_vec(),
2628            b"bar".to_vec(),
2629            b"baz".to_vec(),
2630            b"quux".to_vec(),
2631        ];
2632        let raw_binary_value_refs = raw_binary_values
2633            .iter()
2634            .map(|x| x.as_slice())
2635            .collect::<Vec<_>>();
2636
2637        let string_values = StringArray::from(raw_string_values.clone());
2638        let binary_values = BinaryArray::from(raw_binary_value_refs);
2639        assert_eq!(string_values.null_count(), 0);
2640        assert_eq!(binary_values.null_count(), 0);
2641
2642        RoundTripTest::new(Arc::new(string_values)).run();
2643        RoundTripTest::new(Arc::new(binary_values)).run();
2644    }
2645
2646    #[test]
2647    #[cfg_attr(miri, ignore)] // Takes too long
2648    fn arrow_writer_binary_view() {
2649        let raw_string_values = vec!["foo", "bar", "large payload over 12 bytes", "lulu"];
2650        let raw_binary_values = vec![
2651            b"foo".to_vec(),
2652            b"bar".to_vec(),
2653            b"large payload over 12 bytes".to_vec(),
2654            b"lulu".to_vec(),
2655        ];
2656        let nullable_string_values =
2657            vec![Some("foo"), None, Some("large payload over 12 bytes"), None];
2658
2659        let string_view_values = StringViewArray::from(raw_string_values);
2660        let binary_view_values = BinaryViewArray::from_iter_values(raw_binary_values);
2661        let nullable_string_view_values = StringViewArray::from(nullable_string_values);
2662
2663        RoundTripTest::new(Arc::new(string_view_values)).run();
2664        RoundTripTest::new(Arc::new(binary_view_values)).run();
2665        RoundTripTest::new(Arc::new(nullable_string_view_values)).run();
2666    }
2667
2668    #[test]
2669    #[cfg_attr(miri, ignore)] // Takes too long
2670    fn arrow_writer_binary_view_long_value() {
2671        // There is special case validation for long values (greater than 128)
2672        // 128 encodes as 0x80 0x00 0x00 0x00 in little endian, which should
2673        // trigger the long-string UTF-8 validation branch in the plain decoder.
2674        let long = "a".repeat(128);
2675        let raw_string_values = vec!["foo", long.as_str(), "bar"];
2676        let raw_binary_values = vec![b"foo".to_vec(), long.as_bytes().to_vec(), b"bar".to_vec()];
2677
2678        let string_view_values: ArrayRef = Arc::new(StringViewArray::from(raw_string_values));
2679        let binary_view_values: ArrayRef =
2680            Arc::new(BinaryViewArray::from_iter_values(raw_binary_values));
2681
2682        RoundTripTest::new(Arc::clone(&string_view_values))
2683            .with_nullable(false)
2684            .run();
2685        RoundTripTest::new(Arc::clone(&binary_view_values))
2686            .with_nullable(false)
2687            .run();
2688    }
2689
2690    /// Test round-trip of Dictionary<UInt32, Utf8View> and
2691    /// Dictionary<UInt32, BinaryView> typed columns.
2692    #[test]
2693    fn arrow_writer_string_view_dictionary() {
2694        let raw_string_values = vec!["a", "b", "large payload over 12 bytes"];
2695        let raw_binary_values = vec![
2696            b"a".to_vec(),
2697            b"b".to_vec(),
2698            b"large payload over 12 bytes".to_vec(),
2699        ];
2700
2701        let keys = UInt32Array::from(vec![Some(0), None, Some(2), Some(1), None]);
2702
2703        let string_view_values = Arc::new(StringViewArray::from(raw_string_values));
2704        let string_dict: ArrayRef = Arc::new(
2705            DictionaryArray::<UInt32Type>::try_new(keys.clone(), string_view_values).unwrap(),
2706        );
2707
2708        let binary_view_values = Arc::new(BinaryViewArray::from_iter_values(raw_binary_values));
2709        let binary_dict: ArrayRef =
2710            Arc::new(DictionaryArray::<UInt32Type>::try_new(keys, binary_view_values).unwrap());
2711
2712        RoundTripTest::new(string_dict).run();
2713        RoundTripTest::new(binary_dict).run();
2714    }
2715
2716    fn get_decimal_batch(precision: u8, scale: i8) -> RecordBatch {
2717        let decimal_field = Field::new("a", DataType::Decimal128(precision, scale), false);
2718        let schema = Schema::new(vec![decimal_field]);
2719
2720        let decimal_values = vec![10_000, 50_000, 0, -100]
2721            .into_iter()
2722            .map(Some)
2723            .collect::<Decimal128Array>()
2724            .with_precision_and_scale(precision, scale)
2725            .unwrap();
2726
2727        RecordBatch::try_new(Arc::new(schema), vec![Arc::new(decimal_values)]).unwrap()
2728    }
2729
2730    #[test]
2731    fn arrow_writer_decimal() {
2732        // int32 to store the decimal value
2733        let batch_int32_decimal = get_decimal_batch(5, 2);
2734        roundtrip(batch_int32_decimal, Some(SMALL_SIZE / 2));
2735        // int64 to store the decimal value
2736        let batch_int64_decimal = get_decimal_batch(12, 2);
2737        roundtrip(batch_int64_decimal, Some(SMALL_SIZE / 2));
2738        // fixed_length_byte_array to store the decimal value
2739        let batch_fixed_len_byte_array_decimal = get_decimal_batch(30, 2);
2740        roundtrip(batch_fixed_len_byte_array_decimal, Some(SMALL_SIZE / 2));
2741    }
2742
2743    #[test]
2744    #[cfg_attr(miri, ignore)] // Takes too long
2745    fn arrow_writer_complex() {
2746        // define schema
2747        let struct_field_d = Arc::new(Field::new("d", DataType::Float64, true));
2748        let struct_field_f = Arc::new(Field::new("f", DataType::Float32, true));
2749        let struct_field_g = Arc::new(Field::new_list(
2750            "g",
2751            Field::new_list_field(DataType::Int16, true),
2752            false,
2753        ));
2754        let struct_field_h = Arc::new(Field::new_list(
2755            "h",
2756            Field::new_list_field(DataType::Int16, false),
2757            true,
2758        ));
2759        let struct_field_e = Arc::new(Field::new_struct(
2760            "e",
2761            vec![
2762                struct_field_f.clone(),
2763                struct_field_g.clone(),
2764                struct_field_h.clone(),
2765            ],
2766            false,
2767        ));
2768        let schema = Schema::new(vec![
2769            Field::new("a", DataType::Int32, false),
2770            Field::new("b", DataType::Int32, true),
2771            Field::new_struct(
2772                "c",
2773                vec![struct_field_d.clone(), struct_field_e.clone()],
2774                false,
2775            ),
2776        ]);
2777
2778        // create some data
2779        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2780        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2781        let d = Float64Array::from(vec![None, None, None, Some(1.0), None]);
2782        let f = Float32Array::from(vec![Some(0.0), None, Some(333.3), None, Some(5.25)]);
2783
2784        let g_value = Int16Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2785
2786        // Construct a buffer for value offsets, for the nested array:
2787        //  [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
2788        let g_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
2789
2790        // Construct a list array from the above two
2791        let g_list_data = ArrayData::builder(struct_field_g.data_type().clone())
2792            .len(5)
2793            .add_buffer(g_value_offsets.clone())
2794            .add_child_data(g_value.to_data())
2795            .build()
2796            .unwrap();
2797        let g = ListArray::from(g_list_data);
2798        // The difference between g and h is that h has a null bitmap
2799        let h_list_data = ArrayData::builder(struct_field_h.data_type().clone())
2800            .len(5)
2801            .add_buffer(g_value_offsets)
2802            .add_child_data(g_value.to_data())
2803            .null_bit_buffer(Some(Buffer::from([0b00011011])))
2804            .build()
2805            .unwrap();
2806        let h = ListArray::from(h_list_data);
2807
2808        let e = StructArray::from(vec![
2809            (struct_field_f, Arc::new(f) as ArrayRef),
2810            (struct_field_g, Arc::new(g) as ArrayRef),
2811            (struct_field_h, Arc::new(h) as ArrayRef),
2812        ]);
2813
2814        let c = StructArray::from(vec![
2815            (struct_field_d, Arc::new(d) as ArrayRef),
2816            (struct_field_e, Arc::new(e) as ArrayRef),
2817        ]);
2818
2819        // build a record batch
2820        let batch = RecordBatch::try_new(
2821            Arc::new(schema),
2822            vec![Arc::new(a), Arc::new(b), Arc::new(c)],
2823        )
2824        .unwrap();
2825
2826        roundtrip(batch.clone(), Some(SMALL_SIZE / 2));
2827        roundtrip(batch, Some(SMALL_SIZE / 3));
2828    }
2829
2830    #[test]
2831    fn arrow_writer_complex_mixed() {
2832        // This test was added while investigating https://github.com/apache/arrow-rs/issues/244.
2833        // It was subsequently fixed while investigating https://github.com/apache/arrow-rs/issues/245.
2834
2835        // define schema
2836        let offset_field = Arc::new(Field::new("offset", DataType::Int32, false));
2837        let partition_field = Arc::new(Field::new("partition", DataType::Int64, true));
2838        let topic_field = Arc::new(Field::new("topic", DataType::Utf8, true));
2839        let schema = Schema::new(vec![Field::new(
2840            "some_nested_object",
2841            DataType::Struct(Fields::from(vec![
2842                offset_field.clone(),
2843                partition_field.clone(),
2844                topic_field.clone(),
2845            ])),
2846            false,
2847        )]);
2848
2849        // create some data
2850        let offset = Int32Array::from(vec![1, 2, 3, 4, 5]);
2851        let partition = Int64Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2852        let topic = StringArray::from(vec![Some("A"), None, Some("A"), Some(""), None]);
2853
2854        let some_nested_object = StructArray::from(vec![
2855            (offset_field, Arc::new(offset) as ArrayRef),
2856            (partition_field, Arc::new(partition) as ArrayRef),
2857            (topic_field, Arc::new(topic) as ArrayRef),
2858        ]);
2859
2860        // build a record batch
2861        let batch =
2862            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(some_nested_object)]).unwrap();
2863
2864        roundtrip(batch, Some(SMALL_SIZE / 2));
2865    }
2866
2867    #[test]
2868    fn arrow_writer_map() {
2869        // Note: we are using the JSON Arrow reader for brevity
2870        let json_content = r#"
2871        {"stocks":{"long": "$AAA", "short": "$BBB"}}
2872        {"stocks":{"long": null, "long": "$CCC", "short": null}}
2873        {"stocks":{"hedged": "$YYY", "long": null, "short": "$D"}}
2874        "#;
2875        let entries_struct_type = DataType::Struct(Fields::from(vec![
2876            Field::new(Field::MAP_KEY_FIELD_DEFAULT_NAME, DataType::Utf8, false),
2877            Field::new(Field::MAP_VALUE_FIELD_DEFAULT_NAME, DataType::Utf8, true),
2878        ]));
2879        let stocks_field = Field::new(
2880            "stocks",
2881            DataType::Map(
2882                Arc::new(Field::new(
2883                    Field::MAP_ENTRIES_FIELD_DEFAULT_NAME,
2884                    entries_struct_type,
2885                    false,
2886                )),
2887                false,
2888            ),
2889            true,
2890        );
2891        let schema = Arc::new(Schema::new(vec![stocks_field]));
2892        let builder = arrow::json::ReaderBuilder::new(schema).with_batch_size(64);
2893        let mut reader = builder.build(std::io::Cursor::new(json_content)).unwrap();
2894
2895        let batch = reader.next().unwrap().unwrap();
2896        roundtrip(batch, None);
2897    }
2898
2899    #[test]
2900    fn arrow_writer_2_level_struct() {
2901        // tests writing <struct<struct<primitive>>
2902        let field_c = Field::new("c", DataType::Int32, true);
2903        let field_b = Field::new("b", DataType::Struct(vec![field_c].into()), true);
2904        let type_a = DataType::Struct(vec![field_b.clone()].into());
2905        let field_a = Field::new("a", type_a, true);
2906        let schema = Schema::new(vec![field_a.clone()]);
2907
2908        // create data
2909        let c = Int32Array::from(vec![Some(1), None, Some(3), None, None, Some(6)]);
2910        let b_data = ArrayDataBuilder::new(field_b.data_type().clone())
2911            .len(6)
2912            .null_bit_buffer(Some(Buffer::from([0b00100111])))
2913            .add_child_data(c.into_data())
2914            .build()
2915            .unwrap();
2916        let b = StructArray::from(b_data);
2917        let a_data = ArrayDataBuilder::new(field_a.data_type().clone())
2918            .len(6)
2919            .null_bit_buffer(Some(Buffer::from([0b00101111])))
2920            .add_child_data(b.into_data())
2921            .build()
2922            .unwrap();
2923        let a = StructArray::from(a_data);
2924
2925        assert_eq!(a.null_count(), 1);
2926        assert_eq!(a.column(0).null_count(), 2);
2927
2928        // build a racord batch
2929        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
2930
2931        roundtrip(batch, Some(SMALL_SIZE / 2));
2932    }
2933
2934    #[test]
2935    fn arrow_writer_2_level_struct_non_null() {
2936        // tests writing <struct<struct<primitive>>
2937        let field_c = Field::new("c", DataType::Int32, false);
2938        let type_b = DataType::Struct(vec![field_c].into());
2939        let field_b = Field::new("b", type_b.clone(), false);
2940        let type_a = DataType::Struct(vec![field_b].into());
2941        let field_a = Field::new("a", type_a.clone(), false);
2942        let schema = Schema::new(vec![field_a]);
2943
2944        // create data
2945        let c = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
2946        let b_data = ArrayDataBuilder::new(type_b)
2947            .len(6)
2948            .add_child_data(c.into_data())
2949            .build()
2950            .unwrap();
2951        let b = StructArray::from(b_data);
2952        let a_data = ArrayDataBuilder::new(type_a)
2953            .len(6)
2954            .add_child_data(b.into_data())
2955            .build()
2956            .unwrap();
2957        let a = StructArray::from(a_data);
2958
2959        assert_eq!(a.null_count(), 0);
2960        assert_eq!(a.column(0).null_count(), 0);
2961
2962        // build a racord batch
2963        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
2964
2965        roundtrip(batch, Some(SMALL_SIZE / 2));
2966    }
2967
2968    #[test]
2969    fn arrow_writer_2_level_struct_mixed_null() {
2970        // tests writing <struct<struct<primitive>>
2971        let field_c = Field::new("c", DataType::Int32, false);
2972        let type_b = DataType::Struct(vec![field_c].into());
2973        let field_b = Field::new("b", type_b.clone(), true);
2974        let type_a = DataType::Struct(vec![field_b].into());
2975        let field_a = Field::new("a", type_a.clone(), false);
2976        let schema = Schema::new(vec![field_a]);
2977
2978        // create data
2979        let c = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
2980        let b_data = ArrayDataBuilder::new(type_b)
2981            .len(6)
2982            .null_bit_buffer(Some(Buffer::from([0b00100111])))
2983            .add_child_data(c.into_data())
2984            .build()
2985            .unwrap();
2986        let b = StructArray::from(b_data);
2987        // a intentionally has no null buffer, to test that this is handled correctly
2988        let a_data = ArrayDataBuilder::new(type_a)
2989            .len(6)
2990            .add_child_data(b.into_data())
2991            .build()
2992            .unwrap();
2993        let a = StructArray::from(a_data);
2994
2995        assert_eq!(a.null_count(), 0);
2996        assert_eq!(a.column(0).null_count(), 2);
2997
2998        // build a racord batch
2999        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
3000
3001        roundtrip(batch, Some(SMALL_SIZE / 2));
3002    }
3003
3004    #[test]
3005    fn arrow_writer_2_level_struct_mixed_null_2() {
3006        // tests writing <struct<struct<primitive>>, where the primitive columns are non-null.
3007        let field_c = Field::new("c", DataType::Int32, false);
3008        let field_d = Field::new("d", DataType::FixedSizeBinary(4), false);
3009        let field_e = Field::new(
3010            "e",
3011            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
3012            false,
3013        );
3014
3015        let field_b = Field::new(
3016            "b",
3017            DataType::Struct(vec![field_c, field_d, field_e].into()),
3018            false,
3019        );
3020        let type_a = DataType::Struct(vec![field_b.clone()].into());
3021        let field_a = Field::new("a", type_a, true);
3022        let schema = Schema::new(vec![field_a.clone()]);
3023
3024        // create data
3025        let c = Int32Array::from_iter_values(0..6);
3026        let d = FixedSizeBinaryArray::try_from_iter(
3027            ["aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff"].into_iter(),
3028        )
3029        .expect("four byte values");
3030        let e = Int32DictionaryArray::from_iter(["one", "two", "three", "four", "five", "one"]);
3031        let b_data = ArrayDataBuilder::new(field_b.data_type().clone())
3032            .len(6)
3033            .add_child_data(c.into_data())
3034            .add_child_data(d.into_data())
3035            .add_child_data(e.into_data())
3036            .build()
3037            .unwrap();
3038        let b = StructArray::from(b_data);
3039        let a_data = ArrayDataBuilder::new(field_a.data_type().clone())
3040            .len(6)
3041            .null_bit_buffer(Some(Buffer::from([0b00100101])))
3042            .add_child_data(b.into_data())
3043            .build()
3044            .unwrap();
3045        let a = StructArray::from(a_data);
3046
3047        assert_eq!(a.null_count(), 3);
3048        assert_eq!(a.column(0).null_count(), 0);
3049
3050        // build a record batch
3051        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
3052
3053        roundtrip(batch, Some(SMALL_SIZE / 2));
3054    }
3055
3056    #[test]
3057    fn test_fixed_size_binary_in_dict() {
3058        fn test_fixed_size_binary_in_dict_inner<K>()
3059        where
3060            K: ArrowDictionaryKeyType,
3061            K::Native: FromPrimitive + ToPrimitive + TryFrom<u8>,
3062            <<K as arrow_array::ArrowPrimitiveType>::Native as TryFrom<u8>>::Error: std::fmt::Debug,
3063        {
3064            let field = Field::new(
3065                "a",
3066                DataType::Dictionary(
3067                    Box::new(K::DATA_TYPE),
3068                    Box::new(DataType::FixedSizeBinary(4)),
3069                ),
3070                false,
3071            );
3072            let schema = Schema::new(vec![field]);
3073
3074            let keys: Vec<K::Native> = vec![
3075                K::Native::try_from(0u8).unwrap(),
3076                K::Native::try_from(0u8).unwrap(),
3077                K::Native::try_from(1u8).unwrap(),
3078            ];
3079            let keys = PrimitiveArray::<K>::from_iter_values(keys);
3080            let values = FixedSizeBinaryArray::try_from_iter(
3081                vec![vec![0, 0, 0, 0], vec![1, 1, 1, 1]].into_iter(),
3082            )
3083            .unwrap();
3084
3085            let data = DictionaryArray::<K>::new(keys, Arc::new(values));
3086            let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(data)]).unwrap();
3087            roundtrip(batch, None);
3088        }
3089
3090        test_fixed_size_binary_in_dict_inner::<UInt8Type>();
3091        test_fixed_size_binary_in_dict_inner::<UInt16Type>();
3092        test_fixed_size_binary_in_dict_inner::<UInt32Type>();
3093        test_fixed_size_binary_in_dict_inner::<UInt16Type>();
3094        test_fixed_size_binary_in_dict_inner::<Int8Type>();
3095        test_fixed_size_binary_in_dict_inner::<Int16Type>();
3096        test_fixed_size_binary_in_dict_inner::<Int32Type>();
3097        test_fixed_size_binary_in_dict_inner::<Int64Type>();
3098    }
3099
3100    #[test]
3101    fn test_empty_dict() {
3102        let struct_fields = Fields::from(vec![Field::new(
3103            "dict",
3104            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
3105            false,
3106        )]);
3107
3108        let schema = Schema::new(vec![Field::new_struct(
3109            "struct",
3110            struct_fields.clone(),
3111            true,
3112        )]);
3113        let dictionary = Arc::new(DictionaryArray::new(
3114            Int32Array::new_null(5),
3115            Arc::new(StringArray::new_null(0)),
3116        ));
3117
3118        let s = StructArray::new(
3119            struct_fields,
3120            vec![dictionary],
3121            Some(NullBuffer::new_null(5)),
3122        );
3123
3124        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(s)]).unwrap();
3125        roundtrip(batch, None);
3126    }
3127    #[test]
3128    fn arrow_writer_page_size() {
3129        let schema = Arc::new(Schema::new(vec![Field::new("col", DataType::Utf8, false)]));
3130
3131        let mut builder = StringBuilder::with_capacity(100, 329 * 10_000);
3132
3133        // Generate an array of 10 unique 10 character string
3134        for i in 0..10 {
3135            let value = i
3136                .to_string()
3137                .repeat(10)
3138                .chars()
3139                .take(10)
3140                .collect::<String>();
3141
3142            builder.append_value(value);
3143        }
3144
3145        let array = Arc::new(builder.finish());
3146
3147        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
3148
3149        let file = tempfile::tempfile().unwrap();
3150
3151        // Set everything very low so we fallback to PLAIN encoding after the first row
3152        let props = WriterProperties::builder()
3153            .set_data_page_size_limit(1)
3154            .set_dictionary_page_size_limit(1)
3155            .set_write_batch_size(1)
3156            .build();
3157
3158        let mut writer =
3159            ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), Some(props))
3160                .expect("Unable to write file");
3161        writer.write(&batch).unwrap();
3162        writer.close().unwrap();
3163
3164        let options = ReadOptionsBuilder::new().with_page_index().build();
3165        let reader =
3166            SerializedFileReader::new_with_options(file.try_clone().unwrap(), options).unwrap();
3167
3168        let column = reader.metadata().row_group(0).columns();
3169
3170        assert_eq!(column.len(), 1);
3171
3172        // We should write one row before falling back to PLAIN encoding so there should still be a
3173        // dictionary page.
3174        assert!(
3175            column[0].dictionary_page_offset().is_some(),
3176            "Expected a dictionary page"
3177        );
3178
3179        let page_index = reader
3180            .metadata()
3181            .page_index()
3182            .expect("page index should be present");
3183        let page_locations = page_index
3184            .page_locations(0, 0)
3185            .expect("page locations should exist");
3186
3187        // We should fallback to PLAIN encoding after the first row and our max page size is 1 bytes
3188        // so we expect one dictionary encoded page and then a page per row thereafter.
3189        assert_eq!(
3190            page_locations.len(),
3191            10,
3192            "Expected 10 pages but got {page_locations:#?}"
3193        );
3194    }
3195
3196    #[test]
3197    #[cfg_attr(miri, ignore)] // inline assembly is not supported
3198    fn arrow_writer_float_nans() {
3199        let f16_field = Field::new("a", DataType::Float16, false);
3200        let f32_field = Field::new("b", DataType::Float32, false);
3201        let f64_field = Field::new("c", DataType::Float64, false);
3202        let schema = Schema::new(vec![f16_field, f32_field, f64_field]);
3203
3204        let f16_values = (0..MEDIUM_SIZE)
3205            .map(|i| {
3206                Some(if i % 2 == 0 {
3207                    f16::NAN
3208                } else {
3209                    f16::from_f32(i as f32)
3210                })
3211            })
3212            .collect::<Float16Array>();
3213
3214        let f32_values = (0..MEDIUM_SIZE)
3215            .map(|i| Some(if i % 2 == 0 { f32::NAN } else { i as f32 }))
3216            .collect::<Float32Array>();
3217
3218        let f64_values = (0..MEDIUM_SIZE)
3219            .map(|i| Some(if i % 2 == 0 { f64::NAN } else { i as f64 }))
3220            .collect::<Float64Array>();
3221
3222        let batch = RecordBatch::try_new(
3223            Arc::new(schema),
3224            vec![
3225                Arc::new(f16_values),
3226                Arc::new(f32_values),
3227                Arc::new(f64_values),
3228            ],
3229        )
3230        .unwrap();
3231
3232        roundtrip(batch, None);
3233    }
3234
3235    const SMALL_SIZE: usize = 7;
3236    const MEDIUM_SIZE: usize = 63;
3237
3238    // Write the batch to parquet and read it back out, ensuring
3239    // that what comes out is the same as what was written in
3240    fn roundtrip(expected_batch: RecordBatch, max_row_group_size: Option<usize>) -> Vec<Bytes> {
3241        let mut files = vec![];
3242        for version in [WriterVersion::PARQUET_1_0, WriterVersion::PARQUET_2_0] {
3243            let mut props = WriterProperties::builder().set_writer_version(version);
3244
3245            if let Some(size) = max_row_group_size {
3246                props = props.set_max_row_group_row_count(Some(size))
3247            }
3248
3249            let props = props.build();
3250            files.push(roundtrip_opts(&expected_batch, props))
3251        }
3252        files
3253    }
3254
3255    // Round trip the specified record batch with the specified writer properties,
3256    // to an in-memory file, and validate the arrays using the specified function.
3257    // Returns the in-memory file.
3258    fn roundtrip_opts_with_array_validation<F>(
3259        expected_batch: &RecordBatch,
3260        props: WriterProperties,
3261        validate: F,
3262    ) -> Bytes
3263    where
3264        F: Fn(&ArrayData, &ArrayData),
3265    {
3266        let mut file = vec![];
3267
3268        let mut writer = ArrowWriter::try_new(&mut file, expected_batch.schema(), Some(props))
3269            .expect("Unable to write file");
3270        writer.write(expected_batch).unwrap();
3271        writer.close().unwrap();
3272
3273        let file = Bytes::from(file);
3274        let mut record_batch_reader =
3275            ParquetRecordBatchReader::try_new(file.clone(), 1024).unwrap();
3276
3277        let actual_batch = record_batch_reader
3278            .next()
3279            .expect("No batch found")
3280            .expect("Unable to get batch");
3281
3282        assert_eq!(expected_batch.schema(), actual_batch.schema());
3283        assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
3284        assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
3285        for i in 0..expected_batch.num_columns() {
3286            let expected_data = expected_batch.column(i).to_data();
3287            let actual_data = actual_batch.column(i).to_data();
3288            validate(&expected_data, &actual_data);
3289        }
3290
3291        file
3292    }
3293
3294    fn roundtrip_opts(expected_batch: &RecordBatch, props: WriterProperties) -> Bytes {
3295        roundtrip_opts_with_array_validation(expected_batch, props, |a, b| {
3296            a.validate_full().expect("valid expected data");
3297            b.validate_full().expect("valid actual data");
3298            assert_eq!(a, b)
3299        })
3300    }
3301
3302    /// Round trip testing fixture:
3303    ///
3304    /// Tests based on this fixture write data to parquet and then read it back.
3305    struct RoundTripTest {
3306        values: ArrayRef,
3307        /// Optionally supplied schema
3308        schema: Option<SchemaRef>,
3309        /// If the created schema should be nullable. Defaults to true. Ignored
3310        /// if schema is set to Some.
3311        nullable: bool,
3312        bloom_filter: bool,
3313        bloom_filter_ndv: Option<u64>,
3314        bloom_filter_position: BloomFilterPosition,
3315    }
3316
3317    impl RoundTripTest {
3318        /// Create a test for round tripping values with a nullable schema
3319        fn new(values: ArrayRef) -> Self {
3320            Self {
3321                values,
3322                schema: None,
3323                nullable: true,
3324                bloom_filter: false,
3325                bloom_filter_ndv: None,
3326                bloom_filter_position: BloomFilterPosition::AfterRowGroup,
3327            }
3328        }
3329
3330        /// Set the schema
3331        fn with_schema(mut self, schema: SchemaRef) -> Self {
3332            self.schema = Some(schema);
3333            self
3334        }
3335
3336        /// Set the nullable flag
3337        fn with_nullable(mut self, nullable: bool) -> Self {
3338            self.nullable = nullable;
3339            self
3340        }
3341
3342        /// Set bloom filter
3343        fn with_bloom_filter(mut self, bloom_filter: bool) -> Self {
3344            self.bloom_filter = bloom_filter;
3345            self
3346        }
3347
3348        /// Set bloom filter max ndv
3349        fn with_bloom_filter_ndv(mut self, bloom_filter_ndv: u64) -> Self {
3350            self.bloom_filter_ndv = Some(bloom_filter_ndv);
3351            self
3352        }
3353
3354        /// Set bloom filter position
3355        fn with_bloom_filter_position(
3356            mut self,
3357            bloom_filter_position: BloomFilterPosition,
3358        ) -> Self {
3359            self.bloom_filter_position = bloom_filter_position;
3360            self
3361        }
3362
3363        /// Run the test specified by the options, returning the encoded Parquet bytes
3364        fn run(self) -> Vec<Bytes> {
3365            let RoundTripTest {
3366                values,
3367                schema,
3368                nullable,
3369                bloom_filter,
3370                bloom_filter_ndv,
3371                bloom_filter_position,
3372            } = self;
3373
3374            let schema = schema.unwrap_or_else(|| {
3375                let data_type = values.data_type().clone();
3376                Arc::new(Schema::new(vec![Field::new("col", data_type, nullable)]))
3377            });
3378
3379            let encodings = match values.data_type() {
3380                DataType::Utf8 | DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary => {
3381                    vec![
3382                        Encoding::PLAIN,
3383                        Encoding::DELTA_BYTE_ARRAY,
3384                        Encoding::DELTA_LENGTH_BYTE_ARRAY,
3385                    ]
3386                }
3387                DataType::Int64
3388                | DataType::Int32
3389                | DataType::Int16
3390                | DataType::Int8
3391                | DataType::UInt64
3392                | DataType::UInt32
3393                | DataType::UInt16
3394                | DataType::UInt8 => vec![
3395                    Encoding::PLAIN,
3396                    Encoding::DELTA_BINARY_PACKED,
3397                    Encoding::BYTE_STREAM_SPLIT,
3398                ],
3399                DataType::Float32 | DataType::Float64 => {
3400                    vec![Encoding::PLAIN, Encoding::BYTE_STREAM_SPLIT]
3401                }
3402                _ => vec![Encoding::PLAIN],
3403            };
3404
3405            let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
3406
3407            let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
3408
3409            let mut files = vec![];
3410            for dictionary_size in [0, 1, 1024] {
3411                for encoding in &encodings {
3412                    for version in [WriterVersion::PARQUET_1_0, WriterVersion::PARQUET_2_0] {
3413                        for row_group_size in row_group_sizes {
3414                            let mut builder = WriterProperties::builder()
3415                                .set_writer_version(version)
3416                                .set_max_row_group_row_count(Some(row_group_size))
3417                                .set_dictionary_enabled(dictionary_size != 0)
3418                                .set_dictionary_page_size_limit(dictionary_size.max(1))
3419                                .set_encoding(*encoding)
3420                                .set_bloom_filter_enabled(bloom_filter)
3421                                .set_bloom_filter_position(bloom_filter_position);
3422                            if let Some(ndv) = bloom_filter_ndv {
3423                                builder = builder.set_bloom_filter_max_ndv(ndv);
3424                            }
3425                            let props = builder.build();
3426
3427                            files.push(roundtrip_opts(&expected_batch, props))
3428                        }
3429                    }
3430                }
3431            }
3432            files
3433        }
3434    }
3435
3436    fn values_required<A, I>(iter: I) -> Vec<Bytes>
3437    where
3438        A: From<Vec<I::Item>> + Array + 'static,
3439        I: IntoIterator,
3440    {
3441        let raw_values: Vec<_> = iter.into_iter().collect();
3442        let values = Arc::new(A::from(raw_values));
3443        RoundTripTest::new(values).with_nullable(false).run()
3444    }
3445
3446    fn values_optional<A, I>(iter: I) -> Vec<Bytes>
3447    where
3448        A: From<Vec<Option<I::Item>>> + Array + 'static,
3449        I: IntoIterator,
3450    {
3451        let optional_raw_values: Vec<_> = iter
3452            .into_iter()
3453            .enumerate()
3454            .map(|(i, v)| if i % 2 == 0 { None } else { Some(v) })
3455            .collect();
3456        let optional_values = Arc::new(A::from(optional_raw_values));
3457        RoundTripTest::new(optional_values).run()
3458    }
3459
3460    fn required_and_optional<A, I>(iter: I)
3461    where
3462        A: From<Vec<I::Item>> + From<Vec<Option<I::Item>>> + Array + 'static,
3463        I: IntoIterator + Clone,
3464    {
3465        values_required::<A, I>(iter.clone());
3466        values_optional::<A, I>(iter);
3467    }
3468
3469    fn check_bloom_filter<T: AsBytes>(
3470        files: Vec<Bytes>,
3471        file_column: String,
3472        positive_values: Vec<T>,
3473        negative_values: Vec<T>,
3474    ) {
3475        files.into_iter().take(1).for_each(|file| {
3476            let file_reader = SerializedFileReader::new_with_options(
3477                file,
3478                ReadOptionsBuilder::new()
3479                    .with_reader_properties(
3480                        ReaderProperties::builder()
3481                            .set_read_bloom_filter(true)
3482                            .build(),
3483                    )
3484                    .build(),
3485            )
3486            .expect("Unable to open file as Parquet");
3487            let metadata = file_reader.metadata();
3488
3489            // Gets bloom filters from all row groups.
3490            let mut bloom_filters: Vec<_> = vec![];
3491            for (ri, row_group) in metadata.row_groups().iter().enumerate() {
3492                if let Some((column_index, _)) = row_group
3493                    .columns()
3494                    .iter()
3495                    .enumerate()
3496                    .find(|(_, column)| column.column_path().string() == file_column)
3497                {
3498                    let row_group_reader = file_reader
3499                        .get_row_group(ri)
3500                        .expect("Unable to read row group");
3501                    if let Some(sbbf) = row_group_reader.get_column_bloom_filter(column_index) {
3502                        bloom_filters.push(sbbf.clone());
3503                    } else {
3504                        panic!("No bloom filter for column named {file_column} found");
3505                    }
3506                } else {
3507                    panic!("No column named {file_column} found");
3508                }
3509            }
3510
3511            positive_values.iter().for_each(|value| {
3512                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
3513                assert!(
3514                    found.is_some(),
3515                    "{}",
3516                    format!("Value {:?} should be in bloom filter", value.as_bytes())
3517                );
3518            });
3519
3520            negative_values.iter().for_each(|value| {
3521                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
3522                assert!(
3523                    found.is_none(),
3524                    "{}",
3525                    format!("Value {:?} should not be in bloom filter", value.as_bytes())
3526                );
3527            });
3528        });
3529    }
3530
3531    #[test]
3532    #[cfg_attr(miri, ignore)] // Takes too long
3533    fn all_null_primitive_single_column() {
3534        let values = Arc::new(Int32Array::from(vec![None; SMALL_SIZE]));
3535        RoundTripTest::new(values).run();
3536    }
3537    #[test]
3538    #[cfg_attr(miri, ignore)] // Takes too long
3539    fn null_single_column() {
3540        let values = Arc::new(NullArray::new(SMALL_SIZE));
3541        RoundTripTest::new(values).run();
3542        // null arrays are always nullable, a test with non-nullable nulls fails
3543    }
3544
3545    #[test]
3546    #[cfg_attr(miri, ignore)] // Takes too long
3547    fn bool_single_column() {
3548        required_and_optional::<BooleanArray, _>(
3549            [true, false].iter().cycle().copied().take(SMALL_SIZE),
3550        );
3551    }
3552
3553    #[test]
3554    #[cfg_attr(miri, ignore)] // Takes too long
3555    fn bool_large_single_column() {
3556        let values = Arc::new(
3557            [None, Some(true), Some(false)]
3558                .iter()
3559                .cycle()
3560                .copied()
3561                .take(200_000)
3562                .collect::<BooleanArray>(),
3563        );
3564        let schema = Schema::new(vec![Field::new("col", values.data_type().clone(), true)]);
3565        let expected_batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
3566        let file = tempfile::tempfile().unwrap();
3567
3568        let mut writer =
3569            ArrowWriter::try_new(file.try_clone().unwrap(), expected_batch.schema(), None)
3570                .expect("Unable to write file");
3571        writer.write(&expected_batch).unwrap();
3572        writer.close().unwrap();
3573    }
3574
3575    #[test]
3576    fn check_page_offset_index_with_nan() {
3577        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
3578        let schema = Schema::new(vec![Field::new("col", DataType::Float64, true)]);
3579        let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
3580
3581        let mut out = Vec::with_capacity(1024);
3582        let mut writer =
3583            ArrowWriter::try_new(&mut out, batch.schema(), None).expect("Unable to write file");
3584        writer.write(&batch).unwrap();
3585        let file_meta_data = writer.close().unwrap();
3586        for row_group in file_meta_data.row_groups() {
3587            for column in row_group.columns() {
3588                assert!(column.offset_index_offset().is_some());
3589                assert!(column.offset_index_length().is_some());
3590                assert!(column.column_index_offset().is_some());
3591                assert!(column.column_index_length().is_some());
3592            }
3593        }
3594        if let Some(page_index) = file_meta_data.page_index() {
3595            for rg in 0..file_meta_data.num_row_groups() {
3596                for col in 0..file_meta_data.row_group(rg).num_columns() {
3597                    let idx = page_index
3598                        .column_index(rg, col)
3599                        .expect("column index should exist");
3600                    assert!(idx.nan_counts().is_some());
3601                    let ColumnIndexMetaData::DOUBLE(float_idx) = idx else {
3602                        panic!("expected double statistics")
3603                    };
3604                    for i in 0..idx.num_pages() as usize {
3605                        assert_eq!(float_idx.nan_count(i), Some(10));
3606                        assert_eq!(
3607                            f64::NAN.total_cmp(float_idx.min_value(i).unwrap()),
3608                            Ordering::Equal
3609                        );
3610                        assert_eq!(
3611                            f64::NAN.total_cmp(float_idx.max_value(i).unwrap()),
3612                            Ordering::Equal
3613                        );
3614                    }
3615                }
3616            }
3617        } else {
3618            panic!("page index should be present");
3619        }
3620    }
3621
3622    #[test]
3623    fn check_page_offset_index_with_mixed_nan() {
3624        let schema = Arc::new(Schema::new(vec![Field::new(
3625            "col",
3626            DataType::Float64,
3627            true,
3628        )]));
3629
3630        let mut out = Vec::with_capacity(1024);
3631        let props = WriterProperties::builder()
3632            .set_data_page_row_count_limit(10)
3633            .build();
3634        let mut writer = ArrowWriter::try_new(&mut out, schema.clone(), Some(props))
3635            .expect("Unable to write file");
3636
3637        // write a page of all NaN (since batch min and max are NaN, global min/max are NaN)
3638        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
3639        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3640        writer.write(&batch).unwrap();
3641
3642        // write a page of all -NaN (batch min/max is -NaN, should update global min to -NaN)
3643        let values = Arc::new(Float64Array::from(vec![-f64::NAN; 10]));
3644        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3645        writer.write(&batch).unwrap();
3646
3647        // write a page of all 0 (non-NaN should override global min/max, now 0/0)
3648        let values = Arc::new(Float64Array::from(vec![0_f64; 10]));
3649        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3650        writer.write(&batch).unwrap();
3651
3652        // write a mixed page (should now have min -1, max 1)
3653        let values = Arc::new(Float64Array::from(vec![
3654            -1.0,
3655            0.0,
3656            f64::NAN,
3657            -f64::NAN,
3658            1.0,
3659        ]));
3660        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3661        writer.write(&batch).unwrap();
3662
3663        let file_meta_data = writer.close().unwrap();
3664
3665        // check the column chunk stats are correct
3666        let col_stats = file_meta_data
3667            .row_group(0)
3668            .column(0)
3669            .statistics()
3670            .expect("missing column chunk statistics");
3671
3672        assert_eq!(col_stats.nan_count_opt(), Some(22));
3673        assert_eq!(col_stats.min_bytes_opt(), Some((-1.0f64).as_bytes()));
3674        assert_eq!(col_stats.max_bytes_opt(), Some(1.0f64.as_bytes()));
3675
3676        assert!(file_meta_data.page_index().is_some());
3677        let col_idx = &file_meta_data.page_index().unwrap().column_index(0, 0);
3678        assert_eq!(col_idx.as_ref().unwrap().num_pages(), 4);
3679
3680        // test each page
3681        let Some(ColumnIndexMetaData::DOUBLE(float_idx)) = col_idx else {
3682            panic!("expected double statistics")
3683        };
3684
3685        assert_eq!(float_idx.nan_counts, Some(vec![10, 10, 0, 2]));
3686        assert_eq!(
3687            f64::NAN.total_cmp(float_idx.min_value(0).unwrap()),
3688            Ordering::Equal
3689        );
3690        assert_eq!(
3691            f64::NAN.total_cmp(float_idx.max_value(0).unwrap()),
3692            Ordering::Equal
3693        );
3694        assert_eq!(
3695            (-f64::NAN).total_cmp(float_idx.min_value(1).unwrap()),
3696            Ordering::Equal
3697        );
3698        assert_eq!(
3699            (-f64::NAN).total_cmp(float_idx.max_value(1).unwrap()),
3700            Ordering::Equal
3701        );
3702        assert_eq!(float_idx.min_value(2), Some(&0.0));
3703        assert_eq!(float_idx.max_value(2), Some(&0.0));
3704        assert_eq!(float_idx.min_value(3), Some(&-1.0));
3705        assert_eq!(float_idx.max_value(3), Some(&1.0));
3706    }
3707
3708    #[test]
3709    #[cfg_attr(miri, ignore)] // Takes too long
3710    fn i8_single_column() {
3711        required_and_optional::<Int8Array, _>(0..SMALL_SIZE as i8);
3712    }
3713
3714    #[test]
3715    #[cfg_attr(miri, ignore)] // Takes too long
3716    fn i16_single_column() {
3717        required_and_optional::<Int16Array, _>(0..SMALL_SIZE as i16);
3718    }
3719
3720    #[test]
3721    #[cfg_attr(miri, ignore)] // Takes too long
3722    fn i32_single_column() {
3723        required_and_optional::<Int32Array, _>(0..SMALL_SIZE as i32);
3724    }
3725
3726    #[test]
3727    #[cfg_attr(miri, ignore)] // Takes too long
3728    fn i64_single_column() {
3729        required_and_optional::<Int64Array, _>(0..SMALL_SIZE as i64);
3730    }
3731
3732    #[test]
3733    #[cfg_attr(miri, ignore)] // Takes too long
3734    fn u8_single_column() {
3735        required_and_optional::<UInt8Array, _>(0..SMALL_SIZE as u8);
3736    }
3737
3738    #[test]
3739    #[cfg_attr(miri, ignore)] // Takes too long
3740    fn u16_single_column() {
3741        required_and_optional::<UInt16Array, _>(0..SMALL_SIZE as u16);
3742    }
3743
3744    #[test]
3745    #[cfg_attr(miri, ignore)] // Takes too long
3746    fn u32_single_column() {
3747        required_and_optional::<UInt32Array, _>(0..SMALL_SIZE as u32);
3748    }
3749
3750    #[test]
3751    #[cfg_attr(miri, ignore)] // Takes too long
3752    fn u64_single_column() {
3753        required_and_optional::<UInt64Array, _>(0..SMALL_SIZE as u64);
3754    }
3755
3756    #[test]
3757    #[cfg_attr(miri, ignore)] // Takes too long
3758    fn f32_single_column() {
3759        required_and_optional::<Float32Array, _>((0..SMALL_SIZE).map(|i| i as f32));
3760    }
3761
3762    #[test]
3763    #[cfg_attr(miri, ignore)] // Takes too long
3764    fn f64_single_column() {
3765        required_and_optional::<Float64Array, _>((0..SMALL_SIZE).map(|i| i as f64));
3766    }
3767
3768    // The timestamp array types don't implement From<Vec<T>> because they need the timezone
3769    // argument, and they also doesn't support building from a Vec<Option<T>>, so call
3770    // RoundTripTest manually instead of calling required_and_optional for these tests.
3771
3772    #[test]
3773    #[cfg_attr(miri, ignore)] // Takes too long
3774    fn timestamp_second_single_column() {
3775        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3776        let values = Arc::new(TimestampSecondArray::from(raw_values));
3777
3778        RoundTripTest::new(values).with_nullable(false).run();
3779    }
3780
3781    #[test]
3782    #[cfg_attr(miri, ignore)] // Takes too long
3783    fn timestamp_millisecond_single_column() {
3784        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3785        let values = Arc::new(TimestampMillisecondArray::from(raw_values));
3786
3787        RoundTripTest::new(values).with_nullable(false).run();
3788    }
3789
3790    #[test]
3791    #[cfg_attr(miri, ignore)] // Takes too long
3792    fn timestamp_microsecond_single_column() {
3793        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3794        let values = Arc::new(TimestampMicrosecondArray::from(raw_values));
3795
3796        RoundTripTest::new(values).with_nullable(false).run();
3797    }
3798
3799    #[test]
3800    #[cfg_attr(miri, ignore)] // Takes too long
3801    fn timestamp_nanosecond_single_column() {
3802        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3803        let values = Arc::new(TimestampNanosecondArray::from(raw_values));
3804
3805        RoundTripTest::new(values).with_nullable(false).run();
3806    }
3807
3808    #[test]
3809    #[cfg_attr(miri, ignore)] // Takes too long
3810    fn date32_single_column() {
3811        required_and_optional::<Date32Array, _>(0..SMALL_SIZE as i32);
3812    }
3813
3814    #[test]
3815    #[cfg_attr(miri, ignore)] // Takes too long
3816    fn date64_single_column() {
3817        // Date64 must be a multiple of 86400000, see ARROW-10925
3818        required_and_optional::<Date64Array, _>(
3819            (0..(SMALL_SIZE as i64 * 86400000)).step_by(86400000),
3820        );
3821    }
3822
3823    #[test]
3824    #[cfg_attr(miri, ignore)] // Takes too long
3825    fn time32_second_single_column() {
3826        required_and_optional::<Time32SecondArray, _>(0..SMALL_SIZE as i32);
3827    }
3828
3829    #[test]
3830    #[cfg_attr(miri, ignore)] // Takes too long
3831    fn time32_millisecond_single_column() {
3832        required_and_optional::<Time32MillisecondArray, _>(0..SMALL_SIZE as i32);
3833    }
3834
3835    #[test]
3836    #[cfg_attr(miri, ignore)] // Takes too long
3837    fn time64_microsecond_single_column() {
3838        required_and_optional::<Time64MicrosecondArray, _>(0..SMALL_SIZE as i64);
3839    }
3840
3841    #[test]
3842    #[cfg_attr(miri, ignore)] // Takes too long
3843    fn time64_nanosecond_single_column() {
3844        required_and_optional::<Time64NanosecondArray, _>(0..SMALL_SIZE as i64);
3845    }
3846
3847    #[test]
3848    #[cfg_attr(miri, ignore)] // Takes too long
3849    fn duration_second_single_column() {
3850        required_and_optional::<DurationSecondArray, _>(0..SMALL_SIZE as i64);
3851    }
3852
3853    #[test]
3854    #[cfg_attr(miri, ignore)] // Takes too long
3855    fn duration_millisecond_single_column() {
3856        required_and_optional::<DurationMillisecondArray, _>(0..SMALL_SIZE as i64);
3857    }
3858
3859    #[test]
3860    #[cfg_attr(miri, ignore)] // Takes too long
3861    fn duration_microsecond_single_column() {
3862        required_and_optional::<DurationMicrosecondArray, _>(0..SMALL_SIZE as i64);
3863    }
3864
3865    #[test]
3866    #[cfg_attr(miri, ignore)] // Takes too long
3867    fn duration_nanosecond_single_column() {
3868        required_and_optional::<DurationNanosecondArray, _>(0..SMALL_SIZE as i64);
3869    }
3870
3871    #[test]
3872    #[cfg_attr(miri, ignore)] // Takes too long
3873    fn interval_year_month_single_column() {
3874        required_and_optional::<IntervalYearMonthArray, _>(0..SMALL_SIZE as i32);
3875    }
3876
3877    #[test]
3878    #[cfg_attr(miri, ignore)] // Takes too long
3879    fn interval_day_time_single_column() {
3880        required_and_optional::<IntervalDayTimeArray, _>(vec![
3881            IntervalDayTime::new(0, 1),
3882            IntervalDayTime::new(0, 3),
3883            IntervalDayTime::new(3, -2),
3884            IntervalDayTime::new(-200, 4),
3885        ]);
3886    }
3887
3888    #[test]
3889    #[should_panic(
3890        expected = "Attempting to write an Arrow interval type MonthDayNano to parquet that is not yet implemented"
3891    )]
3892    fn interval_month_day_nano_single_column() {
3893        required_and_optional::<IntervalMonthDayNanoArray, _>(vec![
3894            IntervalMonthDayNano::new(0, 1, 5),
3895            IntervalMonthDayNano::new(0, 3, 2),
3896            IntervalMonthDayNano::new(3, -2, -5),
3897            IntervalMonthDayNano::new(-200, 4, -1),
3898        ]);
3899    }
3900
3901    #[test]
3902    #[cfg_attr(miri, ignore)] // Takes too long
3903    fn binary_single_column() {
3904        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
3905        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
3906        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
3907
3908        // BinaryArrays can't be built from Vec<Option<&str>>, so only call `values_required`
3909        values_required::<BinaryArray, _>(many_vecs_iter);
3910    }
3911
3912    #[test]
3913    #[cfg_attr(miri, ignore)] // Takes too long
3914    fn binary_view_single_column() {
3915        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
3916        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
3917        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
3918
3919        // BinaryArrays can't be built from Vec<Option<&str>>, so only call `values_required`
3920        values_required::<BinaryViewArray, _>(many_vecs_iter);
3921    }
3922
3923    #[test]
3924    #[cfg_attr(miri, ignore)] // Takes too long
3925    fn i32_column_bloom_filter_at_end() {
3926        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3927        let files = RoundTripTest::new(array)
3928            .with_nullable(false)
3929            .with_bloom_filter(true)
3930            .with_bloom_filter_position(BloomFilterPosition::End)
3931            .run();
3932
3933        check_bloom_filter(
3934            files,
3935            "col".to_string(),
3936            (0..SMALL_SIZE as i32).collect(),
3937            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3938        );
3939    }
3940
3941    #[test]
3942    #[cfg_attr(miri, ignore)] // Takes too long
3943    fn i32_column_bloom_filter() {
3944        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3945        let files = RoundTripTest::new(array)
3946            .with_nullable(false)
3947            .with_bloom_filter(true)
3948            .run();
3949
3950        check_bloom_filter(
3951            files,
3952            "col".to_string(),
3953            (0..SMALL_SIZE as i32).collect(),
3954            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3955        );
3956    }
3957
3958    /// Test that bloom filter folding produces correct results even when
3959    /// the configured NDV differs significantly from actual NDV.
3960    /// A large NDV means a larger initial filter that gets folded down;
3961    /// a small NDV means a smaller initial filter.
3962    #[test]
3963    #[cfg_attr(miri, ignore)] // Takes too long
3964    fn i32_column_bloom_filter_fixed_ndv() {
3965        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3966
3967        // NDV much larger than actual distinct values — tests folding a large filter down
3968        let files = RoundTripTest::new(array.clone())
3969            .with_nullable(false)
3970            .with_bloom_filter(true)
3971            .with_bloom_filter_ndv(1_000_000)
3972            .run();
3973
3974        check_bloom_filter(
3975            files,
3976            "col".to_string(),
3977            (0..SMALL_SIZE as i32).collect(),
3978            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3979        );
3980
3981        // NDV smaller than actual distinct values — tests the underestimate path
3982        let files = RoundTripTest::new(array)
3983            .with_nullable(false)
3984            .with_bloom_filter(true)
3985            .with_bloom_filter_ndv(3)
3986            .run();
3987
3988        check_bloom_filter(
3989            files,
3990            "col".to_string(),
3991            (0..SMALL_SIZE as i32).collect(),
3992            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3993        );
3994    }
3995
3996    #[test]
3997    #[cfg_attr(miri, ignore)] // Takes too long
3998    fn binary_column_bloom_filter() {
3999        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
4000        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
4001        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
4002
4003        let array = Arc::new(BinaryArray::from_iter_values(many_vecs_iter));
4004        let files = RoundTripTest::new(array)
4005            .with_nullable(false)
4006            .with_bloom_filter(true)
4007            .run();
4008
4009        check_bloom_filter(
4010            files,
4011            "col".to_string(),
4012            many_vecs,
4013            vec![vec![(SMALL_SIZE + 1) as u8]],
4014        );
4015    }
4016
4017    #[test]
4018    #[cfg_attr(miri, ignore)] // Takes too long
4019    fn empty_string_null_column_bloom_filter() {
4020        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4021        let raw_strs = raw_values.iter().map(|s| s.as_str());
4022
4023        let array = Arc::new(StringArray::from_iter_values(raw_strs));
4024        let files = RoundTripTest::new(array)
4025            .with_nullable(false)
4026            .with_bloom_filter(true)
4027            .run();
4028
4029        let optional_raw_values: Vec<_> = raw_values
4030            .iter()
4031            .enumerate()
4032            .filter_map(|(i, v)| if i % 2 == 0 { None } else { Some(v.as_str()) })
4033            .collect();
4034        // For null slots, empty string should not be in bloom filter.
4035        check_bloom_filter(files, "col".to_string(), optional_raw_values, vec![""]);
4036    }
4037
4038    #[test]
4039    #[cfg_attr(miri, ignore)] // Takes too long
4040    fn large_binary_single_column() {
4041        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
4042        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
4043        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
4044
4045        // LargeBinaryArrays can't be built from Vec<Option<&str>>, so only call `values_required`
4046        values_required::<LargeBinaryArray, _>(many_vecs_iter);
4047    }
4048
4049    #[test]
4050    #[cfg_attr(miri, ignore)] // Takes too long
4051    fn fixed_size_binary_single_column() {
4052        let mut builder = FixedSizeBinaryBuilder::new(4);
4053        builder.append_value(b"0123").unwrap();
4054        builder.append_null();
4055        builder.append_value(b"8910").unwrap();
4056        builder.append_value(b"1112").unwrap();
4057        let array = Arc::new(builder.finish());
4058
4059        RoundTripTest::new(array).run();
4060    }
4061
4062    #[test]
4063    #[cfg_attr(miri, ignore)] // Takes too long
4064    fn string_single_column() {
4065        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4066        let raw_strs = raw_values.iter().map(|s| s.as_str());
4067
4068        required_and_optional::<StringArray, _>(raw_strs);
4069    }
4070
4071    #[test]
4072    #[cfg_attr(miri, ignore)] // Takes too long
4073    fn large_string_single_column() {
4074        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4075        let raw_strs = raw_values.iter().map(|s| s.as_str());
4076
4077        required_and_optional::<LargeStringArray, _>(raw_strs);
4078    }
4079
4080    #[test]
4081    #[cfg_attr(miri, ignore)] // Takes too long
4082    fn string_view_single_column() {
4083        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4084        let raw_strs = raw_values.iter().map(|s| s.as_str());
4085
4086        required_and_optional::<StringViewArray, _>(raw_strs);
4087    }
4088
4089    #[test]
4090    fn null_list_single_column() {
4091        let null_field = Field::new_list_field(DataType::Null, true);
4092        let list_field = Field::new("emptylist", DataType::List(Arc::new(null_field)), true);
4093
4094        let schema = Schema::new(vec![list_field]);
4095
4096        // Build [[], null, [null, null]]
4097        let a_values = NullArray::new(2);
4098        let a_value_offsets = arrow::buffer::Buffer::from([0, 0, 0, 2].to_byte_slice());
4099        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
4100            DataType::Null,
4101            true,
4102        ))))
4103        .len(3)
4104        .add_buffer(a_value_offsets)
4105        .null_bit_buffer(Some(Buffer::from([0b00000101])))
4106        .add_child_data(a_values.into_data())
4107        .build()
4108        .unwrap();
4109
4110        let a = ListArray::from(a_list_data);
4111
4112        assert!(a.is_valid(0));
4113        assert!(!a.is_valid(1));
4114        assert!(a.is_valid(2));
4115
4116        assert_eq!(a.value(0).len(), 0);
4117        assert_eq!(a.value(2).len(), 2);
4118        assert_eq!(a.value(2).logical_nulls().unwrap().null_count(), 2);
4119
4120        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
4121        roundtrip(batch, None);
4122    }
4123
4124    #[test]
4125    #[cfg_attr(miri, ignore)] // Takes too long
4126    fn list_single_column() {
4127        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4128        let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
4129        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
4130            DataType::Int32,
4131            false,
4132        ))))
4133        .len(5)
4134        .add_buffer(a_value_offsets)
4135        .null_bit_buffer(Some(Buffer::from([0b00011011])))
4136        .add_child_data(a_values.into_data())
4137        .build()
4138        .unwrap();
4139
4140        assert_eq!(a_list_data.null_count(), 1);
4141
4142        let a = ListArray::from(a_list_data);
4143        let values = Arc::new(a);
4144
4145        RoundTripTest::new(values).run();
4146    }
4147
4148    #[test]
4149    #[cfg_attr(miri, ignore)] // Takes too long
4150    fn large_list_single_column() {
4151        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4152        let a_value_offsets = arrow::buffer::Buffer::from([0i64, 1, 3, 3, 6, 10].to_byte_slice());
4153        let a_list_data = ArrayData::builder(DataType::LargeList(Arc::new(Field::new(
4154            "large_item",
4155            DataType::Int32,
4156            true,
4157        ))))
4158        .len(5)
4159        .add_buffer(a_value_offsets)
4160        .add_child_data(a_values.into_data())
4161        .null_bit_buffer(Some(Buffer::from([0b00011011])))
4162        .build()
4163        .unwrap();
4164
4165        // I think this setup is incorrect because this should pass
4166        assert_eq!(a_list_data.null_count(), 1);
4167
4168        let a = LargeListArray::from(a_list_data);
4169        let values = Arc::new(a);
4170
4171        RoundTripTest::new(values).run();
4172    }
4173
4174    #[test]
4175    #[cfg_attr(miri, ignore)] // Takes too long
4176    fn list_nested_nulls() {
4177        use arrow::datatypes::Int32Type;
4178        let data = vec![
4179            Some(vec![Some(1)]),
4180            Some(vec![Some(2), Some(3)]),
4181            None,
4182            Some(vec![Some(4), Some(5), None]),
4183            Some(vec![None]),
4184            Some(vec![Some(6), Some(7)]),
4185        ];
4186
4187        let list = ListArray::from_iter_primitive::<Int32Type, _, _>(data.clone());
4188        RoundTripTest::new(Arc::new(list)).run();
4189
4190        let list = LargeListArray::from_iter_primitive::<Int32Type, _, _>(data);
4191        RoundTripTest::new(Arc::new(list)).run();
4192    }
4193
4194    #[test]
4195    #[cfg_attr(miri, ignore)] // Takes too long
4196    fn list_utf8_view_selective_padding_roundtrip() {
4197        let item = Arc::new(Field::new_list_field(DataType::Utf8View, true));
4198        let mut builder = ListBuilder::new(StringViewBuilder::new()).with_field(item);
4199        builder.values().append_value("a");
4200        builder.values().append_null();
4201        builder.append(true);
4202        // The null parent list covers selective padding dropping values below
4203        // the list definition level while preserving the preceding item null.
4204        builder.append(false);
4205        // The long string covers the non-inlined Utf8View buffer path.
4206        builder.values().append_value("large payload over 12 bytes");
4207        builder.append(true);
4208
4209        RoundTripTest::new(Arc::new(builder.finish())).run();
4210    }
4211
4212    #[test]
4213    #[cfg_attr(miri, ignore)] // Takes too long
4214    fn struct_single_column() {
4215        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4216        let struct_field_a = Arc::new(Field::new("f", DataType::Int32, false));
4217        let s = StructArray::from(vec![(struct_field_a, Arc::new(a_values) as ArrayRef)]);
4218
4219        let values = Arc::new(s);
4220        RoundTripTest::new(values).with_nullable(false).run();
4221    }
4222
4223    #[test]
4224    fn list_and_map_coerced_names() {
4225        // Create map and list with non-Parquet naming
4226        let list_field =
4227            Field::new_list("my_list", Field::new("item", DataType::Int32, false), false);
4228        let map_field = Field::new_map(
4229            "my_map",
4230            "my_entries",
4231            Field::new("my_keys", DataType::Int32, false),
4232            Field::new("my_values", DataType::Int32, true),
4233            false,
4234            true,
4235        );
4236
4237        let list_array = create_random_array(&list_field, 100, 0.0, 0.0).unwrap();
4238        let map_array = create_random_array(&map_field, 100, 0.0, 0.0).unwrap();
4239
4240        let arrow_schema = Arc::new(Schema::new(vec![list_field, map_field]));
4241
4242        // Write data to Parquet but coerce names to match spec
4243        let props = Some(WriterProperties::builder().set_coerce_types(true).build());
4244        let file = tempfile::tempfile().unwrap();
4245        let mut writer =
4246            ArrowWriter::try_new(file.try_clone().unwrap(), arrow_schema.clone(), props).unwrap();
4247
4248        let batch = RecordBatch::try_new(arrow_schema, vec![list_array, map_array]).unwrap();
4249        writer.write(&batch).unwrap();
4250        let file_metadata = writer.close().unwrap();
4251
4252        let schema = file_metadata.file_metadata().schema();
4253        // Coerced name of "item" should be "element"
4254        let list_field = &schema.get_fields()[0].get_fields()[0];
4255        assert_eq!(list_field.get_fields()[0].name(), "element");
4256
4257        let map_field = &schema.get_fields()[1].get_fields()[0];
4258        // Coerced name of "entries" should be "key_value"
4259        assert_eq!(map_field.name(), "key_value");
4260        // Coerced name of "my_keys" should be "key"
4261        assert_eq!(map_field.get_fields()[0].name(), "key");
4262        // Coerced name of "my_values" should be "value"
4263        assert_eq!(map_field.get_fields()[1].name(), "value");
4264
4265        // Double check schema after reading from the file
4266        let reader = SerializedFileReader::new(file).unwrap();
4267        let file_schema = reader.metadata().file_metadata().schema();
4268        let fields = file_schema.get_fields();
4269        let list_field = &fields[0].get_fields()[0];
4270        assert_eq!(list_field.get_fields()[0].name(), "element");
4271        let map_field = &fields[1].get_fields()[0];
4272        assert_eq!(map_field.name(), "key_value");
4273        assert_eq!(map_field.get_fields()[0].name(), "key");
4274        assert_eq!(map_field.get_fields()[1].name(), "value");
4275    }
4276
4277    #[test]
4278    #[cfg_attr(miri, ignore)] // Takes too long
4279    fn fallback_flush_data_page() {
4280        //tests if the Fallback::flush_data_page clears all buffers correctly
4281        let raw_values: Vec<_> = (0..MEDIUM_SIZE).map(|i| i.to_string()).collect();
4282        let values = Arc::new(StringArray::from(raw_values));
4283        let encodings = vec![
4284            Encoding::DELTA_BYTE_ARRAY,
4285            Encoding::DELTA_LENGTH_BYTE_ARRAY,
4286        ];
4287        let data_type = values.data_type().clone();
4288        let schema = Arc::new(Schema::new(vec![Field::new("col", data_type, false)]));
4289        let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4290
4291        let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
4292        let data_page_size_limit: usize = 32;
4293        let write_batch_size: usize = 16;
4294
4295        for encoding in &encodings {
4296            for row_group_size in row_group_sizes {
4297                let props = WriterProperties::builder()
4298                    .set_writer_version(WriterVersion::PARQUET_2_0)
4299                    .set_max_row_group_row_count(Some(row_group_size))
4300                    .set_dictionary_enabled(false)
4301                    .set_encoding(*encoding)
4302                    .set_data_page_size_limit(data_page_size_limit)
4303                    .set_write_batch_size(write_batch_size)
4304                    .build();
4305
4306                roundtrip_opts_with_array_validation(&expected_batch, props, |a, b| {
4307                    let string_array_a = StringArray::from(a.clone());
4308                    let string_array_b = StringArray::from(b.clone());
4309                    let vec_a: Vec<&str> = string_array_a.iter().map(|v| v.unwrap()).collect();
4310                    let vec_b: Vec<&str> = string_array_b.iter().map(|v| v.unwrap()).collect();
4311                    assert_eq!(
4312                        vec_a, vec_b,
4313                        "failed for encoder: {encoding:?} and row_group_size: {row_group_size:?}"
4314                    );
4315                });
4316            }
4317        }
4318    }
4319
4320    #[test]
4321    #[cfg_attr(miri, ignore)] // Takes too long
4322    fn arrow_writer_string_dictionary() {
4323        // define schema
4324        #[expect(deprecated)]
4325        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4326            "dictionary",
4327            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4328            true,
4329            42,
4330            true,
4331        )]));
4332
4333        // create some data
4334        let d: Int32DictionaryArray = [Some("alpha"), None, Some("beta"), Some("alpha")]
4335            .iter()
4336            .copied()
4337            .collect();
4338
4339        // build a record batch
4340        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4341    }
4342
4343    #[test]
4344    fn arrow_writer_test_type_compatibility() {
4345        fn ensure_compatible_write<T1, T2>(array1: T1, array2: T2, expected_result: T1)
4346        where
4347            T1: Array + 'static,
4348            T2: Array + 'static,
4349        {
4350            let schema1 = Arc::new(Schema::new(vec![Field::new(
4351                "a",
4352                array1.data_type().clone(),
4353                false,
4354            )]));
4355
4356            let file = tempfile().unwrap();
4357            let mut writer =
4358                ArrowWriter::try_new(file.try_clone().unwrap(), schema1.clone(), None).unwrap();
4359
4360            let rb1 = RecordBatch::try_new(schema1.clone(), vec![Arc::new(array1)]).unwrap();
4361            writer.write(&rb1).unwrap();
4362
4363            let schema2 = Arc::new(Schema::new(vec![Field::new(
4364                "a",
4365                array2.data_type().clone(),
4366                false,
4367            )]));
4368            let rb2 = RecordBatch::try_new(schema2, vec![Arc::new(array2)]).unwrap();
4369            writer.write(&rb2).unwrap();
4370
4371            writer.close().unwrap();
4372
4373            let mut record_batch_reader =
4374                ParquetRecordBatchReader::try_new(file.try_clone().unwrap(), 1024).unwrap();
4375            let actual_batch = record_batch_reader.next().unwrap().unwrap();
4376
4377            let expected_batch =
4378                RecordBatch::try_new(schema1, vec![Arc::new(expected_result)]).unwrap();
4379            assert_eq!(actual_batch, expected_batch);
4380        }
4381
4382        // check compatibility between native and dictionaries
4383
4384        ensure_compatible_write(
4385            DictionaryArray::new(
4386                UInt8Array::from_iter_values(vec![0]),
4387                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4388            ),
4389            StringArray::from_iter_values(vec!["barquet"]),
4390            DictionaryArray::new(
4391                UInt8Array::from_iter_values(vec![0, 1]),
4392                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4393            ),
4394        );
4395
4396        ensure_compatible_write(
4397            StringArray::from_iter_values(vec!["parquet"]),
4398            DictionaryArray::new(
4399                UInt8Array::from_iter_values(vec![0]),
4400                Arc::new(StringArray::from_iter_values(vec!["barquet"])),
4401            ),
4402            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4403        );
4404
4405        // check compatibility between dictionaries with different key types
4406
4407        ensure_compatible_write(
4408            DictionaryArray::new(
4409                UInt8Array::from_iter_values(vec![0]),
4410                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4411            ),
4412            DictionaryArray::new(
4413                UInt16Array::from_iter_values(vec![0]),
4414                Arc::new(StringArray::from_iter_values(vec!["barquet"])),
4415            ),
4416            DictionaryArray::new(
4417                UInt8Array::from_iter_values(vec![0, 1]),
4418                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4419            ),
4420        );
4421
4422        // check compatibility between dictionaries with different value types
4423        ensure_compatible_write(
4424            DictionaryArray::new(
4425                UInt8Array::from_iter_values(vec![0]),
4426                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4427            ),
4428            DictionaryArray::new(
4429                UInt8Array::from_iter_values(vec![0]),
4430                Arc::new(LargeStringArray::from_iter_values(vec!["barquet"])),
4431            ),
4432            DictionaryArray::new(
4433                UInt8Array::from_iter_values(vec![0, 1]),
4434                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4435            ),
4436        );
4437
4438        // check compatibility between a dictionary and a native array with a different type
4439        ensure_compatible_write(
4440            DictionaryArray::new(
4441                UInt8Array::from_iter_values(vec![0]),
4442                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4443            ),
4444            LargeStringArray::from_iter_values(vec!["barquet"]),
4445            DictionaryArray::new(
4446                UInt8Array::from_iter_values(vec![0, 1]),
4447                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4448            ),
4449        );
4450
4451        // check compatibility for string types
4452
4453        ensure_compatible_write(
4454            StringArray::from_iter_values(vec!["parquet"]),
4455            LargeStringArray::from_iter_values(vec!["barquet"]),
4456            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4457        );
4458
4459        ensure_compatible_write(
4460            LargeStringArray::from_iter_values(vec!["parquet"]),
4461            StringArray::from_iter_values(vec!["barquet"]),
4462            LargeStringArray::from_iter_values(vec!["parquet", "barquet"]),
4463        );
4464
4465        ensure_compatible_write(
4466            StringArray::from_iter_values(vec!["parquet"]),
4467            StringViewArray::from_iter_values(vec!["barquet"]),
4468            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4469        );
4470
4471        ensure_compatible_write(
4472            StringViewArray::from_iter_values(vec!["parquet"]),
4473            StringArray::from_iter_values(vec!["barquet"]),
4474            StringViewArray::from_iter_values(vec!["parquet", "barquet"]),
4475        );
4476
4477        ensure_compatible_write(
4478            LargeStringArray::from_iter_values(vec!["parquet"]),
4479            StringViewArray::from_iter_values(vec!["barquet"]),
4480            LargeStringArray::from_iter_values(vec!["parquet", "barquet"]),
4481        );
4482
4483        ensure_compatible_write(
4484            StringViewArray::from_iter_values(vec!["parquet"]),
4485            LargeStringArray::from_iter_values(vec!["barquet"]),
4486            StringViewArray::from_iter_values(vec!["parquet", "barquet"]),
4487        );
4488
4489        // check compatibility for binary types
4490
4491        ensure_compatible_write(
4492            BinaryArray::from_iter_values(vec![b"parquet"]),
4493            LargeBinaryArray::from_iter_values(vec![b"barquet"]),
4494            BinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4495        );
4496
4497        ensure_compatible_write(
4498            LargeBinaryArray::from_iter_values(vec![b"parquet"]),
4499            BinaryArray::from_iter_values(vec![b"barquet"]),
4500            LargeBinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4501        );
4502
4503        ensure_compatible_write(
4504            BinaryArray::from_iter_values(vec![b"parquet"]),
4505            BinaryViewArray::from_iter_values(vec![b"barquet"]),
4506            BinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4507        );
4508
4509        ensure_compatible_write(
4510            BinaryViewArray::from_iter_values(vec![b"parquet"]),
4511            BinaryArray::from_iter_values(vec![b"barquet"]),
4512            BinaryViewArray::from_iter_values(vec![b"parquet", b"barquet"]),
4513        );
4514
4515        ensure_compatible_write(
4516            BinaryViewArray::from_iter_values(vec![b"parquet"]),
4517            LargeBinaryArray::from_iter_values(vec![b"barquet"]),
4518            BinaryViewArray::from_iter_values(vec![b"parquet", b"barquet"]),
4519        );
4520
4521        ensure_compatible_write(
4522            LargeBinaryArray::from_iter_values(vec![b"parquet"]),
4523            BinaryViewArray::from_iter_values(vec![b"barquet"]),
4524            LargeBinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4525        );
4526
4527        // check compatibility for list types
4528
4529        let list_field_metadata = HashMap::from_iter(vec![(
4530            PARQUET_FIELD_ID_META_KEY.to_string(),
4531            "1".to_string(),
4532        )]);
4533        let list_field = Field::new_list_field(DataType::Int32, false);
4534
4535        let values1 = Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4]));
4536        let offsets1 = OffsetBuffer::new(vec![0, 2, 5].into());
4537
4538        let values2 = Arc::new(Int32Array::from(vec![5, 6, 7, 8, 9]));
4539        let offsets2 = OffsetBuffer::new(vec![0, 3, 5].into());
4540
4541        let values_expected = Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4542        let offsets_expected = OffsetBuffer::new(vec![0, 2, 5, 8, 10].into());
4543
4544        ensure_compatible_write(
4545            // when the initial schema has the metadata ...
4546            ListArray::try_new(
4547                Arc::new(
4548                    list_field
4549                        .clone()
4550                        .with_metadata(list_field_metadata.clone()),
4551                ),
4552                offsets1,
4553                values1,
4554                None,
4555            )
4556            .unwrap(),
4557            // ... and some intermediate schema doesn't have the metadata
4558            ListArray::try_new(Arc::new(list_field.clone()), offsets2, values2, None).unwrap(),
4559            // ... the write will still go through, and the resulting schema will inherit the initial metadata
4560            ListArray::try_new(
4561                Arc::new(
4562                    list_field
4563                        .clone()
4564                        .with_metadata(list_field_metadata.clone()),
4565                ),
4566                offsets_expected,
4567                values_expected,
4568                None,
4569            )
4570            .unwrap(),
4571        );
4572    }
4573
4574    #[test]
4575    #[cfg_attr(miri, ignore)] // Takes too long
4576    fn arrow_writer_primitive_dictionary() {
4577        // define schema
4578        #[expect(deprecated)]
4579        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4580            "dictionary",
4581            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::UInt32)),
4582            true,
4583            42,
4584            true,
4585        )]));
4586
4587        // create some data
4588        let mut builder = PrimitiveDictionaryBuilder::<UInt8Type, UInt32Type>::new();
4589        builder.append(12345678).unwrap();
4590        builder.append_null();
4591        builder.append(22345678).unwrap();
4592        builder.append(12345678).unwrap();
4593        let d = builder.finish();
4594
4595        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4596    }
4597
4598    #[test]
4599    #[cfg_attr(miri, ignore)] // Takes too long
4600    fn arrow_writer_decimal32_dictionary() {
4601        let integers = vec![12345, 56789, 34567];
4602
4603        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4604
4605        let values = Decimal32Array::from(integers.clone())
4606            .with_precision_and_scale(5, 2)
4607            .unwrap();
4608
4609        let array = DictionaryArray::new(keys, Arc::new(values));
4610        RoundTripTest::new(Arc::new(array.clone())).run();
4611
4612        let values = Decimal32Array::from(integers)
4613            .with_precision_and_scale(9, 2)
4614            .unwrap();
4615
4616        let array = array.with_values(Arc::new(values));
4617        RoundTripTest::new(Arc::new(array)).run();
4618    }
4619
4620    #[test]
4621    #[cfg_attr(miri, ignore)] // Takes too long
4622    fn arrow_writer_decimal64_dictionary() {
4623        let integers = vec![12345, 56789, 34567];
4624
4625        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4626
4627        let values = Decimal64Array::from(integers.clone())
4628            .with_precision_and_scale(5, 2)
4629            .unwrap();
4630
4631        let array = DictionaryArray::new(keys, Arc::new(values));
4632        RoundTripTest::new(Arc::new(array.clone())).run();
4633
4634        let values = Decimal64Array::from(integers)
4635            .with_precision_and_scale(12, 2)
4636            .unwrap();
4637
4638        let array = array.with_values(Arc::new(values));
4639        RoundTripTest::new(Arc::new(array)).run();
4640    }
4641
4642    #[test]
4643    #[cfg_attr(miri, ignore)] // Takes too long
4644    fn arrow_writer_decimal128_dictionary() {
4645        let integers = vec![12345, 56789, 34567];
4646
4647        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4648
4649        let values = Decimal128Array::from(integers.clone())
4650            .with_precision_and_scale(5, 2)
4651            .unwrap();
4652
4653        let array = DictionaryArray::new(keys, Arc::new(values));
4654        RoundTripTest::new(Arc::new(array.clone())).run();
4655
4656        let values = Decimal128Array::from(integers)
4657            .with_precision_and_scale(12, 2)
4658            .unwrap();
4659
4660        let array = array.with_values(Arc::new(values));
4661        RoundTripTest::new(Arc::new(array)).run();
4662    }
4663
4664    #[test]
4665    #[cfg_attr(miri, ignore)] // Takes too long
4666    fn arrow_writer_decimal256_dictionary() {
4667        let integers = vec![
4668            i256::from_i128(12345),
4669            i256::from_i128(56789),
4670            i256::from_i128(34567),
4671        ];
4672
4673        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4674
4675        let values = Decimal256Array::from(integers.clone())
4676            .with_precision_and_scale(5, 2)
4677            .unwrap();
4678
4679        let array = DictionaryArray::new(keys, Arc::new(values));
4680        RoundTripTest::new(Arc::new(array.clone())).run();
4681
4682        let values = Decimal256Array::from(integers)
4683            .with_precision_and_scale(12, 2)
4684            .unwrap();
4685
4686        let array = array.with_values(Arc::new(values));
4687        RoundTripTest::new(Arc::new(array)).run();
4688    }
4689
4690    #[test]
4691    #[cfg_attr(miri, ignore)] // Takes too long
4692    fn arrow_writer_string_dictionary_unsigned_index() {
4693        // define schema
4694        #[expect(deprecated)]
4695        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4696            "dictionary",
4697            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
4698            true,
4699            42,
4700            true,
4701        )]));
4702
4703        // create some data
4704        let d: UInt8DictionaryArray = [Some("alpha"), None, Some("beta"), Some("alpha")]
4705            .iter()
4706            .copied()
4707            .collect();
4708
4709        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4710    }
4711
4712    #[test]
4713    #[cfg_attr(miri, ignore)] // Takes too long
4714    fn u32_min_max() {
4715        // check values roundtrip through parquet
4716        let src = [
4717            u32::MIN,
4718            1,
4719            (i32::MAX as u32) - 1,
4720            i32::MAX as u32,
4721            (i32::MAX as u32) + 1,
4722            u32::MAX - 1,
4723            u32::MAX,
4724        ];
4725        let values = Arc::new(UInt32Array::from_iter_values(src.iter().copied()));
4726        let files = RoundTripTest::new(values).with_nullable(false).run();
4727
4728        for file in files {
4729            // check statistics are valid
4730            let reader = SerializedFileReader::new(file).unwrap();
4731            let metadata = reader.metadata();
4732
4733            let mut row_offset = 0;
4734            for row_group in metadata.row_groups() {
4735                assert_eq!(row_group.num_columns(), 1);
4736                let column = row_group.column(0);
4737
4738                let num_values = column.num_values() as usize;
4739                let src_slice = &src[row_offset..row_offset + num_values];
4740                row_offset += column.num_values() as usize;
4741
4742                let stats = column.statistics().unwrap();
4743                if let Statistics::Int32(stats) = stats {
4744                    assert_eq!(
4745                        *stats.min_opt().unwrap() as u32,
4746                        *src_slice.iter().min().unwrap()
4747                    );
4748                    assert_eq!(
4749                        *stats.max_opt().unwrap() as u32,
4750                        *src_slice.iter().max().unwrap()
4751                    );
4752                } else {
4753                    panic!("Statistics::Int32 missing")
4754                }
4755            }
4756        }
4757    }
4758
4759    #[test]
4760    #[cfg_attr(miri, ignore)] // Takes too long
4761    fn u64_min_max() {
4762        // check values roundtrip through parquet
4763        let src = [
4764            u64::MIN,
4765            1,
4766            (i64::MAX as u64) - 1,
4767            i64::MAX as u64,
4768            (i64::MAX as u64) + 1,
4769            u64::MAX - 1,
4770            u64::MAX,
4771        ];
4772        let values = Arc::new(UInt64Array::from_iter_values(src.iter().copied()));
4773        let files = RoundTripTest::new(values).with_nullable(false).run();
4774
4775        for file in files {
4776            // check statistics are valid
4777            let reader = SerializedFileReader::new(file).unwrap();
4778            let metadata = reader.metadata();
4779
4780            let mut row_offset = 0;
4781            for row_group in metadata.row_groups() {
4782                assert_eq!(row_group.num_columns(), 1);
4783                let column = row_group.column(0);
4784
4785                let num_values = column.num_values() as usize;
4786                let src_slice = &src[row_offset..row_offset + num_values];
4787                row_offset += column.num_values() as usize;
4788
4789                let stats = column.statistics().unwrap();
4790                if let Statistics::Int64(stats) = stats {
4791                    assert_eq!(
4792                        *stats.min_opt().unwrap() as u64,
4793                        *src_slice.iter().min().unwrap()
4794                    );
4795                    assert_eq!(
4796                        *stats.max_opt().unwrap() as u64,
4797                        *src_slice.iter().max().unwrap()
4798                    );
4799                } else {
4800                    panic!("Statistics::Int64 missing")
4801                }
4802            }
4803        }
4804    }
4805
4806    #[test]
4807    #[cfg_attr(miri, ignore)] // Takes too long
4808    fn statistics_null_counts_only_nulls() {
4809        // check that null-count statistics for "only NULL"-columns are correct
4810        let values = Arc::new(UInt64Array::from(vec![None, None]));
4811        let files = RoundTripTest::new(values).run();
4812
4813        for file in files {
4814            // check statistics are valid
4815            let reader = SerializedFileReader::new(file).unwrap();
4816            let metadata = reader.metadata();
4817            assert_eq!(metadata.num_row_groups(), 1);
4818            let row_group = metadata.row_group(0);
4819            assert_eq!(row_group.num_columns(), 1);
4820            let column = row_group.column(0);
4821            let stats = column.statistics().unwrap();
4822            assert_eq!(stats.null_count_opt(), Some(2));
4823        }
4824    }
4825
4826    #[test]
4827    #[cfg_attr(miri, ignore)] // Takes too long
4828    fn test_list_of_struct_roundtrip() {
4829        // define schema
4830        let int_field = Field::new("a", DataType::Int32, true);
4831        let int_field2 = Field::new("b", DataType::Int32, true);
4832
4833        let int_builder = Int32Builder::with_capacity(10);
4834        let int_builder2 = Int32Builder::with_capacity(10);
4835
4836        let struct_builder = StructBuilder::new(
4837            vec![int_field, int_field2],
4838            vec![Box::new(int_builder), Box::new(int_builder2)],
4839        );
4840        let mut list_builder = ListBuilder::new(struct_builder);
4841
4842        // Construct the following array
4843        // [{a: 1, b: 2}], [], null, [null, null], [{a: null, b: 3}], [{a: 2, b: null}]
4844
4845        // [{a: 1, b: 2}]
4846        let values = list_builder.values();
4847        values
4848            .field_builder::<Int32Builder>(0)
4849            .unwrap()
4850            .append_value(1);
4851        values
4852            .field_builder::<Int32Builder>(1)
4853            .unwrap()
4854            .append_value(2);
4855        values.append(true);
4856        list_builder.append(true);
4857
4858        // []
4859        list_builder.append(true);
4860
4861        // null
4862        list_builder.append(false);
4863
4864        // [null, null]
4865        let values = list_builder.values();
4866        values
4867            .field_builder::<Int32Builder>(0)
4868            .unwrap()
4869            .append_null();
4870        values
4871            .field_builder::<Int32Builder>(1)
4872            .unwrap()
4873            .append_null();
4874        values.append(false);
4875        values
4876            .field_builder::<Int32Builder>(0)
4877            .unwrap()
4878            .append_null();
4879        values
4880            .field_builder::<Int32Builder>(1)
4881            .unwrap()
4882            .append_null();
4883        values.append(false);
4884        list_builder.append(true);
4885
4886        // [{a: null, b: 3}]
4887        let values = list_builder.values();
4888        values
4889            .field_builder::<Int32Builder>(0)
4890            .unwrap()
4891            .append_null();
4892        values
4893            .field_builder::<Int32Builder>(1)
4894            .unwrap()
4895            .append_value(3);
4896        values.append(true);
4897        list_builder.append(true);
4898
4899        // [{a: 2, b: null}]
4900        let values = list_builder.values();
4901        values
4902            .field_builder::<Int32Builder>(0)
4903            .unwrap()
4904            .append_value(2);
4905        values
4906            .field_builder::<Int32Builder>(1)
4907            .unwrap()
4908            .append_null();
4909        values.append(true);
4910        list_builder.append(true);
4911
4912        let array = Arc::new(list_builder.finish());
4913
4914        RoundTripTest::new(array).run();
4915    }
4916
4917    fn row_group_sizes(metadata: &ParquetMetaData) -> Vec<i64> {
4918        metadata.row_groups().iter().map(|x| x.num_rows()).collect()
4919    }
4920
4921    #[test]
4922    fn test_aggregates_records() {
4923        let arrays = [
4924            Int32Array::from((0..100).collect::<Vec<_>>()),
4925            Int32Array::from((0..50).collect::<Vec<_>>()),
4926            Int32Array::from((200..500).collect::<Vec<_>>()),
4927        ];
4928
4929        let schema = Arc::new(Schema::new(vec![Field::new(
4930            "int",
4931            ArrowDataType::Int32,
4932            false,
4933        )]));
4934
4935        let file = tempfile::tempfile().unwrap();
4936
4937        let props = WriterProperties::builder()
4938            .set_max_row_group_row_count(Some(200))
4939            .build();
4940
4941        let mut writer =
4942            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4943
4944        for array in arrays {
4945            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
4946            writer.write(&batch).unwrap();
4947        }
4948
4949        writer.close().unwrap();
4950
4951        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
4952        assert_eq!(&row_group_sizes(builder.metadata()), &[200, 200, 50]);
4953
4954        let batches = builder
4955            .with_batch_size(100)
4956            .build()
4957            .unwrap()
4958            .collect::<ArrowResult<Vec<_>>>()
4959            .unwrap();
4960
4961        assert_eq!(batches.len(), 5);
4962        assert!(batches.iter().all(|x| x.num_columns() == 1));
4963
4964        let batch_sizes: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
4965
4966        assert_eq!(&batch_sizes, &[100, 100, 100, 100, 50]);
4967
4968        let values: Vec<_> = batches
4969            .iter()
4970            .flat_map(|x| {
4971                x.column(0)
4972                    .as_any()
4973                    .downcast_ref::<Int32Array>()
4974                    .unwrap()
4975                    .values()
4976                    .iter()
4977                    .copied()
4978            })
4979            .collect();
4980
4981        let expected_values: Vec<_> = [0..100, 0..50, 200..500].into_iter().flatten().collect();
4982        assert_eq!(&values, &expected_values)
4983    }
4984
4985    #[test]
4986    fn complex_aggregate() {
4987        // Tests aggregating nested data
4988        let field_a = Arc::new(Field::new("leaf_a", DataType::Int32, false));
4989        let field_b = Arc::new(Field::new("leaf_b", DataType::Int32, true));
4990        let struct_a = Arc::new(Field::new(
4991            "struct_a",
4992            DataType::Struct(vec![field_a.clone(), field_b.clone()].into()),
4993            true,
4994        ));
4995
4996        let list_a = Arc::new(Field::new("list", DataType::List(struct_a), true));
4997        let struct_b = Arc::new(Field::new(
4998            "struct_b",
4999            DataType::Struct(vec![list_a.clone()].into()),
5000            false,
5001        ));
5002
5003        let schema = Arc::new(Schema::new(vec![struct_b]));
5004
5005        // create nested data
5006        let field_a_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
5007        let field_b_array =
5008            Int32Array::from_iter(vec![Some(1), None, Some(2), None, None, Some(6)]);
5009
5010        let struct_a_array = StructArray::from(vec![
5011            (field_a.clone(), Arc::new(field_a_array) as ArrayRef),
5012            (field_b.clone(), Arc::new(field_b_array) as ArrayRef),
5013        ]);
5014
5015        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
5016            .len(5)
5017            .add_buffer(Buffer::from_iter(vec![
5018                0_i32, 1_i32, 1_i32, 3_i32, 3_i32, 5_i32,
5019            ]))
5020            .null_bit_buffer(Some(Buffer::from_iter(vec![
5021                true, false, true, false, true,
5022            ])))
5023            .child_data(vec![struct_a_array.into_data()])
5024            .build()
5025            .unwrap();
5026
5027        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
5028        let struct_b_array = StructArray::from(vec![(list_a.clone(), list_a_array)]);
5029
5030        let batch1 =
5031            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
5032                .unwrap();
5033
5034        let field_a_array = Int32Array::from(vec![6, 7, 8, 9, 10]);
5035        let field_b_array = Int32Array::from_iter(vec![None, None, None, Some(1), None]);
5036
5037        let struct_a_array = StructArray::from(vec![
5038            (field_a, Arc::new(field_a_array) as ArrayRef),
5039            (field_b, Arc::new(field_b_array) as ArrayRef),
5040        ]);
5041
5042        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
5043            .len(2)
5044            .add_buffer(Buffer::from_iter(vec![0_i32, 4_i32, 5_i32]))
5045            .child_data(vec![struct_a_array.into_data()])
5046            .build()
5047            .unwrap();
5048
5049        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
5050        let struct_b_array = StructArray::from(vec![(list_a, list_a_array)]);
5051
5052        let batch2 =
5053            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
5054                .unwrap();
5055
5056        let batches = &[batch1, batch2];
5057
5058        // Verify data is as expected
5059
5060        let expected = r"
5061            +-------------------------------------------------------------------------------------------------------+
5062            | struct_b                                                                                              |
5063            +-------------------------------------------------------------------------------------------------------+
5064            | {list: [{leaf_a: 1, leaf_b: 1}]}                                                                      |
5065            | {list: }                                                                                              |
5066            | {list: [{leaf_a: 2, leaf_b: }, {leaf_a: 3, leaf_b: 2}]}                                               |
5067            | {list: }                                                                                              |
5068            | {list: [{leaf_a: 4, leaf_b: }, {leaf_a: 5, leaf_b: }]}                                                |
5069            | {list: [{leaf_a: 6, leaf_b: }, {leaf_a: 7, leaf_b: }, {leaf_a: 8, leaf_b: }, {leaf_a: 9, leaf_b: 1}]} |
5070            | {list: [{leaf_a: 10, leaf_b: }]}                                                                      |
5071            +-------------------------------------------------------------------------------------------------------+
5072        ".trim().split('\n').map(|x| x.trim()).collect::<Vec<_>>().join("\n");
5073
5074        let actual = pretty_format_batches(batches).unwrap().to_string();
5075        assert_eq!(actual, expected);
5076
5077        // Write data
5078        let file = tempfile::tempfile().unwrap();
5079        let props = WriterProperties::builder()
5080            .set_max_row_group_row_count(Some(6))
5081            .build();
5082
5083        let mut writer =
5084            ArrowWriter::try_new(file.try_clone().unwrap(), schema, Some(props)).unwrap();
5085
5086        for batch in batches {
5087            writer.write(batch).unwrap();
5088        }
5089        writer.close().unwrap();
5090
5091        // Read Data
5092        // Should have written entire first batch and first row of second to the first row group
5093        // leaving a single row in the second row group
5094
5095        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
5096        assert_eq!(&row_group_sizes(builder.metadata()), &[6, 1]);
5097
5098        let batches = builder
5099            .with_batch_size(2)
5100            .build()
5101            .unwrap()
5102            .collect::<ArrowResult<Vec<_>>>()
5103            .unwrap();
5104
5105        assert_eq!(batches.len(), 4);
5106        let batch_counts: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
5107        assert_eq!(&batch_counts, &[2, 2, 2, 1]);
5108
5109        let actual = pretty_format_batches(&batches).unwrap().to_string();
5110        assert_eq!(actual, expected);
5111    }
5112
5113    #[test]
5114    fn test_arrow_writer_metadata() {
5115        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5116        let file_schema = batch_schema.clone().with_metadata([("foo", "bar")]);
5117
5118        let batch = RecordBatch::try_new(
5119            Arc::new(batch_schema),
5120            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5121        )
5122        .unwrap();
5123
5124        let mut buf = Vec::with_capacity(1024);
5125        let mut writer = ArrowWriter::try_new(&mut buf, Arc::new(file_schema), None).unwrap();
5126        writer.write(&batch).unwrap();
5127        writer.close().unwrap();
5128    }
5129
5130    #[test]
5131    fn test_arrow_writer_nullable() {
5132        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5133        let file_schema = Schema::new(vec![Field::new("int32", DataType::Int32, true)]);
5134        let file_schema = Arc::new(file_schema);
5135
5136        let batch = RecordBatch::try_new(
5137            Arc::new(batch_schema),
5138            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5139        )
5140        .unwrap();
5141
5142        let mut buf = Vec::with_capacity(1024);
5143        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
5144        writer.write(&batch).unwrap();
5145        writer.close().unwrap();
5146
5147        let mut read = ParquetRecordBatchReader::try_new(Bytes::from(buf), 1024).unwrap();
5148        let back = read.next().unwrap().unwrap();
5149        assert_eq!(back.schema(), file_schema);
5150        assert_ne!(back.schema(), batch.schema());
5151        assert_eq!(back.column(0).as_ref(), batch.column(0).as_ref());
5152    }
5153
5154    #[test]
5155    fn in_progress_accounting() {
5156        // define schema
5157        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
5158
5159        // create some data
5160        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
5161
5162        // build a record batch
5163        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
5164
5165        let mut writer = ArrowWriter::try_new(vec![], batch.schema(), None).unwrap();
5166
5167        // starts empty
5168        assert_eq!(writer.in_progress_size(), 0);
5169        assert_eq!(writer.in_progress_rows(), 0);
5170        assert_eq!(writer.memory_size(), 0);
5171        assert_eq!(writer.bytes_written(), 4); // Initial header
5172        writer.write(&batch).unwrap();
5173
5174        // updated on write
5175        let initial_size = writer.in_progress_size();
5176        assert!(initial_size > 0);
5177        assert_eq!(writer.in_progress_rows(), 5);
5178        let initial_memory = writer.memory_size();
5179        assert!(initial_memory > 0);
5180        // memory estimate is larger than estimated encoded size
5181        assert!(
5182            initial_size <= initial_memory,
5183            "{initial_size} <= {initial_memory}"
5184        );
5185
5186        // updated on second write
5187        writer.write(&batch).unwrap();
5188        assert!(writer.in_progress_size() > initial_size);
5189        assert_eq!(writer.in_progress_rows(), 10);
5190        assert!(writer.memory_size() > initial_memory);
5191        assert!(
5192            writer.in_progress_size() <= writer.memory_size(),
5193            "in_progress_size {} <= memory_size {}",
5194            writer.in_progress_size(),
5195            writer.memory_size()
5196        );
5197
5198        // in progress tracking is cleared, but the overall data written is updated
5199        let pre_flush_bytes_written = writer.bytes_written();
5200        writer.flush().unwrap();
5201        assert_eq!(writer.in_progress_size(), 0);
5202        assert_eq!(writer.memory_size(), 0);
5203        assert!(writer.bytes_written() > pre_flush_bytes_written);
5204
5205        writer.close().unwrap();
5206    }
5207
5208    #[test]
5209    fn test_writer_all_null() {
5210        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
5211        let b = Int32Array::new(vec![0; 5].into(), Some(NullBuffer::new_null(5)));
5212        let batch = RecordBatch::try_from_iter(vec![
5213            ("a", Arc::new(a) as ArrayRef),
5214            ("b", Arc::new(b) as ArrayRef),
5215        ])
5216        .unwrap();
5217
5218        let mut buf = Vec::with_capacity(1024);
5219        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
5220        writer.write(&batch).unwrap();
5221        writer.close().unwrap();
5222
5223        let bytes = Bytes::from(buf);
5224        let options = ReadOptionsBuilder::new().with_page_index().build();
5225        let reader = SerializedFileReader::new_with_options(bytes, options).unwrap();
5226        let index = reader.metadata().page_index().unwrap();
5227
5228        assert_eq!(index.num_data_pages(0, 0), Some(1)); // 1 page
5229        assert_eq!(index.num_data_pages(0, 1), Some(1)); // 1 page
5230    }
5231
5232    #[test]
5233    fn test_disabled_statistics_with_page() {
5234        let file_schema = Schema::new(vec![
5235            Field::new("a", DataType::Utf8, true),
5236            Field::new("b", DataType::Utf8, true),
5237        ]);
5238        let file_schema = Arc::new(file_schema);
5239
5240        let batch = RecordBatch::try_new(
5241            file_schema.clone(),
5242            vec![
5243                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
5244                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
5245            ],
5246        )
5247        .unwrap();
5248
5249        let props = WriterProperties::builder()
5250            .set_statistics_enabled(EnabledStatistics::None)
5251            .set_column_statistics_enabled("a".into(), EnabledStatistics::Page)
5252            .build();
5253
5254        let mut buf = Vec::with_capacity(1024);
5255        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
5256        writer.write(&batch).unwrap();
5257
5258        let metadata = writer.close().unwrap();
5259        assert_eq!(metadata.num_row_groups(), 1);
5260        let row_group = metadata.row_group(0);
5261        assert_eq!(row_group.num_columns(), 2);
5262        // Column "a" has both offset and column index, as requested
5263        assert!(row_group.column(0).offset_index_offset().is_some());
5264        assert!(row_group.column(0).column_index_offset().is_some());
5265        // Column "b" should only have offset index
5266        assert!(row_group.column(1).offset_index_offset().is_some());
5267        assert!(row_group.column(1).column_index_offset().is_none());
5268
5269        let options = ReadOptionsBuilder::new().with_page_index().build();
5270        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
5271
5272        let row_group = reader.get_row_group(0).unwrap();
5273        let a_col = row_group.metadata().column(0);
5274        let b_col = row_group.metadata().column(1);
5275
5276        // Column chunk of column "a" should have chunk level statistics
5277        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
5278            let min = byte_array_stats.min_opt().unwrap();
5279            let max = byte_array_stats.max_opt().unwrap();
5280
5281            assert_eq!(min.as_bytes(), b"a");
5282            assert_eq!(max.as_bytes(), b"d");
5283        } else {
5284            panic!("expecting Statistics::ByteArray");
5285        }
5286
5287        // The column chunk for column "b" shouldn't have statistics
5288        assert!(b_col.statistics().is_none());
5289
5290        let page_index = reader.metadata().page_index().unwrap();
5291
5292        let a_idx = page_index.column_index(0, 0);
5293        assert!(
5294            matches!(a_idx, Some(ColumnIndexMetaData::BYTE_ARRAY(_))),
5295            "{a_idx:?}"
5296        );
5297        let b_idx = page_index.column_index(0, 1);
5298        assert!(b_idx.is_none(), "{b_idx:?}");
5299    }
5300
5301    #[test]
5302    fn test_disabled_statistics_with_chunk() {
5303        let file_schema = Schema::new(vec![
5304            Field::new("a", DataType::Utf8, true),
5305            Field::new("b", DataType::Utf8, true),
5306        ]);
5307        let file_schema = Arc::new(file_schema);
5308
5309        let batch = RecordBatch::try_new(
5310            file_schema.clone(),
5311            vec![
5312                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
5313                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
5314            ],
5315        )
5316        .unwrap();
5317
5318        let props = WriterProperties::builder()
5319            .set_statistics_enabled(EnabledStatistics::None)
5320            .set_column_statistics_enabled("a".into(), EnabledStatistics::Chunk)
5321            .build();
5322
5323        let mut buf = Vec::with_capacity(1024);
5324        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
5325        writer.write(&batch).unwrap();
5326
5327        let metadata = writer.close().unwrap();
5328        assert_eq!(metadata.num_row_groups(), 1);
5329        let row_group = metadata.row_group(0);
5330        assert_eq!(row_group.num_columns(), 2);
5331        // Column "a" should only have offset index
5332        assert!(row_group.column(0).offset_index_offset().is_some());
5333        assert!(row_group.column(0).column_index_offset().is_none());
5334        // Column "b" should only have offset index
5335        assert!(row_group.column(1).offset_index_offset().is_some());
5336        assert!(row_group.column(1).column_index_offset().is_none());
5337
5338        let options = ReadOptionsBuilder::new().with_page_index().build();
5339        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
5340
5341        let row_group = reader.get_row_group(0).unwrap();
5342        let a_col = row_group.metadata().column(0);
5343        let b_col = row_group.metadata().column(1);
5344
5345        // Column chunk of column "a" should have chunk level statistics
5346        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
5347            let min = byte_array_stats.min_opt().unwrap();
5348            let max = byte_array_stats.max_opt().unwrap();
5349
5350            assert_eq!(min.as_bytes(), b"a");
5351            assert_eq!(max.as_bytes(), b"d");
5352        } else {
5353            panic!("expecting Statistics::ByteArray");
5354        }
5355
5356        // The column chunk for column "b"  shouldn't have statistics
5357        assert!(b_col.statistics().is_none());
5358
5359        let page_index = reader.metadata().page_index().unwrap();
5360
5361        let a_idx = page_index.column_index(0, 0);
5362        assert!(a_idx.is_none(), "{a_idx:?}");
5363        let b_idx = page_index.column_index(0, 1);
5364        assert!(b_idx.is_none(), "{b_idx:?}");
5365    }
5366
5367    #[test]
5368    fn test_arrow_writer_skip_metadata() {
5369        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5370        let file_schema = Arc::new(batch_schema.clone());
5371
5372        let batch = RecordBatch::try_new(
5373            Arc::new(batch_schema),
5374            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5375        )
5376        .unwrap();
5377        let skip_options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
5378
5379        let mut buf = Vec::with_capacity(1024);
5380        let mut writer =
5381            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
5382        writer.write(&batch).unwrap();
5383        writer.close().unwrap();
5384
5385        let bytes = Bytes::from(buf);
5386        let reader_builder = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
5387        assert_eq!(file_schema, *reader_builder.schema());
5388        if let Some(key_value_metadata) = reader_builder
5389            .metadata()
5390            .file_metadata()
5391            .key_value_metadata()
5392        {
5393            assert!(
5394                !key_value_metadata
5395                    .iter()
5396                    .any(|kv| kv.key.as_str() == ARROW_SCHEMA_META_KEY)
5397            );
5398        }
5399    }
5400
5401    #[test]
5402    fn test_arrow_writer_skip_path_in_schema() {
5403        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5404        let file_schema = Arc::new(batch_schema.clone());
5405
5406        let batch = RecordBatch::try_new(
5407            Arc::new(batch_schema),
5408            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5409        )
5410        .unwrap();
5411
5412        // default options should still write path_in_schema
5413        let skip_options = ArrowWriterOptions::new();
5414
5415        let mut buf = Vec::with_capacity(1024);
5416        let mut writer =
5417            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
5418        writer.write(&batch).unwrap();
5419        writer.close().unwrap();
5420
5421        // override to not write path_in_schema
5422        let skip_options = ArrowWriterOptions::new().with_properties(
5423            WriterProperties::builder()
5424                .set_write_path_in_schema(false)
5425                .build(),
5426        );
5427
5428        let mut buf2 = Vec::with_capacity(1024);
5429        let mut writer =
5430            ArrowWriter::try_new_with_options(&mut buf2, file_schema.clone(), skip_options)
5431                .unwrap();
5432        writer.write(&batch).unwrap();
5433        writer.close().unwrap();
5434
5435        // buf2 should be a bit smaller due to lack of path_in_schema
5436        assert!(buf.len() > buf2.len());
5437    }
5438
5439    #[test]
5440    fn mismatched_schemas() {
5441        let batch_schema = Schema::new(vec![Field::new("count", DataType::Int32, false)]);
5442        let file_schema = Arc::new(Schema::new(vec![Field::new(
5443            "temperature",
5444            DataType::Float64,
5445            false,
5446        )]));
5447
5448        let batch = RecordBatch::try_new(
5449            Arc::new(batch_schema),
5450            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5451        )
5452        .unwrap();
5453
5454        let mut buf = Vec::with_capacity(1024);
5455        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
5456
5457        let err = writer.write(&batch).unwrap_err().to_string();
5458        assert_eq!(
5459            err,
5460            "Arrow: Incompatible type. Field 'temperature' has type Float64, array has type Int32"
5461        );
5462    }
5463
5464    #[test]
5465    // https://github.com/apache/arrow-rs/issues/6988
5466    fn test_roundtrip_empty_schema() {
5467        // create empty record batch with empty schema
5468        let empty_batch = RecordBatch::try_new_with_options(
5469            Arc::new(Schema::empty()),
5470            vec![],
5471            &RecordBatchOptions::default().with_row_count(Some(0)),
5472        )
5473        .unwrap();
5474
5475        // write to parquet
5476        let mut parquet_bytes: Vec<u8> = Vec::new();
5477        let mut writer =
5478            ArrowWriter::try_new(&mut parquet_bytes, empty_batch.schema(), None).unwrap();
5479        writer.write(&empty_batch).unwrap();
5480        writer.close().unwrap();
5481
5482        // read from parquet
5483        let bytes = Bytes::from(parquet_bytes);
5484        let reader = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
5485        assert_eq!(reader.schema(), &empty_batch.schema());
5486        let batches: Vec<_> = reader
5487            .build()
5488            .unwrap()
5489            .collect::<ArrowResult<Vec<_>>>()
5490            .unwrap();
5491        assert_eq!(batches.len(), 0);
5492    }
5493
5494    #[test]
5495    fn test_page_stats_not_written_by_default() {
5496        let string_field = Field::new("a", DataType::Utf8, false);
5497        let schema = Schema::new(vec![string_field]);
5498        let raw_string_values = vec!["Blart Versenwald III"];
5499        let string_values = StringArray::from(raw_string_values.clone());
5500        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
5501
5502        let props = WriterProperties::builder()
5503            .set_statistics_enabled(EnabledStatistics::Page)
5504            .set_dictionary_enabled(false)
5505            .set_encoding(Encoding::PLAIN)
5506            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5507            .build();
5508
5509        let file = roundtrip_opts(&batch, props);
5510
5511        // read file and decode page headers
5512        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5513
5514        // decode first page header
5515        let first_page = &file[4..];
5516        let mut prot = ThriftSliceInputProtocol::new(first_page);
5517        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5518        let stats = hdr.data_page_header.unwrap().statistics;
5519
5520        assert!(stats.is_none());
5521    }
5522
5523    #[test]
5524    fn test_page_stats_when_enabled() {
5525        let string_field = Field::new("a", DataType::Utf8, false);
5526        let schema = Schema::new(vec![string_field]);
5527        let raw_string_values = vec!["Blart Versenwald III", "Andrew Lamb"];
5528        let string_values = StringArray::from(raw_string_values.clone());
5529        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
5530
5531        let props = WriterProperties::builder()
5532            .set_statistics_enabled(EnabledStatistics::Page)
5533            .set_dictionary_enabled(false)
5534            .set_encoding(Encoding::PLAIN)
5535            .set_write_page_header_statistics(true)
5536            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5537            .build();
5538
5539        let file = roundtrip_opts(&batch, props);
5540
5541        // read file and decode page headers
5542        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5543
5544        // decode first page header
5545        let first_page = &file[4..];
5546        let mut prot = ThriftSliceInputProtocol::new(first_page);
5547        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5548        let stats = hdr.data_page_header.unwrap().statistics;
5549
5550        let stats = stats.unwrap();
5551        // check that min/max were actually written to the page
5552        assert!(stats.is_max_value_exact.unwrap());
5553        assert!(stats.is_min_value_exact.unwrap());
5554        assert_eq!(stats.max_value.unwrap(), b"Blart Versenwald III");
5555        assert_eq!(stats.min_value.unwrap(), b"Andrew Lamb");
5556    }
5557
5558    #[test]
5559    fn test_page_stats_truncation() {
5560        let string_field = Field::new("a", DataType::Utf8, false);
5561        let binary_field = Field::new("b", DataType::Binary, false);
5562        let schema = Schema::new(vec![string_field, binary_field]);
5563
5564        let raw_string_values = vec!["Blart Versenwald III"];
5565        let raw_binary_values = [b"Blart Versenwald III".to_vec()];
5566        let raw_binary_value_refs = raw_binary_values
5567            .iter()
5568            .map(|x| x.as_slice())
5569            .collect::<Vec<_>>();
5570
5571        let string_values = StringArray::from(raw_string_values.clone());
5572        let binary_values = BinaryArray::from(raw_binary_value_refs);
5573        let batch = RecordBatch::try_new(
5574            Arc::new(schema),
5575            vec![Arc::new(string_values), Arc::new(binary_values)],
5576        )
5577        .unwrap();
5578
5579        let props = WriterProperties::builder()
5580            .set_statistics_truncate_length(Some(2))
5581            .set_dictionary_enabled(false)
5582            .set_encoding(Encoding::PLAIN)
5583            .set_write_page_header_statistics(true)
5584            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5585            .build();
5586
5587        let file = roundtrip_opts(&batch, props);
5588
5589        // read file and decode page headers
5590        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5591
5592        // decode first page header
5593        let first_page = &file[4..];
5594        let mut prot = ThriftSliceInputProtocol::new(first_page);
5595        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5596        let stats = hdr.data_page_header.unwrap().statistics;
5597        assert!(stats.is_some());
5598        let stats = stats.unwrap();
5599        // check that min/max were properly truncated
5600        assert!(!stats.is_max_value_exact.unwrap());
5601        assert!(!stats.is_min_value_exact.unwrap());
5602        assert_eq!(stats.max_value.unwrap(), b"Bm");
5603        assert_eq!(stats.min_value.unwrap(), b"Bl");
5604
5605        // check second page now
5606        let second_page = &prot.as_slice()[hdr.compressed_page_size as usize..];
5607        let mut prot = ThriftSliceInputProtocol::new(second_page);
5608        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5609        let stats = hdr.data_page_header.unwrap().statistics;
5610        assert!(stats.is_some());
5611        let stats = stats.unwrap();
5612        // check that min/max were properly truncated
5613        assert!(!stats.is_max_value_exact.unwrap());
5614        assert!(!stats.is_min_value_exact.unwrap());
5615        assert_eq!(stats.max_value.unwrap(), b"Bm");
5616        assert_eq!(stats.min_value.unwrap(), b"Bl");
5617    }
5618
5619    #[test]
5620    fn test_page_encoding_statistics_roundtrip() {
5621        let batch_schema = Schema::new(vec![Field::new(
5622            "int32",
5623            arrow_schema::DataType::Int32,
5624            false,
5625        )]);
5626
5627        let batch = RecordBatch::try_new(
5628            Arc::new(batch_schema.clone()),
5629            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5630        )
5631        .unwrap();
5632
5633        let mut file: File = tempfile::tempfile().unwrap();
5634        let mut writer = ArrowWriter::try_new(&mut file, Arc::new(batch_schema), None).unwrap();
5635        writer.write(&batch).unwrap();
5636        let file_metadata = writer.close().unwrap();
5637
5638        assert_eq!(file_metadata.num_row_groups(), 1);
5639        assert_eq!(file_metadata.row_group(0).num_columns(), 1);
5640        assert!(
5641            file_metadata
5642                .row_group(0)
5643                .column(0)
5644                .page_encoding_stats()
5645                .is_some()
5646        );
5647        let chunk_page_stats = file_metadata
5648            .row_group(0)
5649            .column(0)
5650            .page_encoding_stats()
5651            .unwrap();
5652
5653        // check that the read metadata is also correct
5654        let options = ReadOptionsBuilder::new()
5655            .with_page_index()
5656            .with_encoding_stats_as_mask(false)
5657            .build();
5658        let reader = SerializedFileReader::new_with_options(file, options).unwrap();
5659
5660        let rowgroup = reader.get_row_group(0).expect("row group missing");
5661        assert_eq!(rowgroup.num_columns(), 1);
5662        let column = rowgroup.metadata().column(0);
5663        assert!(column.page_encoding_stats().is_some());
5664        let file_page_stats = column.page_encoding_stats().unwrap();
5665        assert_eq!(chunk_page_stats, file_page_stats);
5666    }
5667
5668    #[test]
5669    #[cfg_attr(miri, ignore)] // Takes too long
5670    fn test_different_dict_page_size_limit() {
5671        let array = Arc::new(Int64Array::from_iter(0..1024 * 1024));
5672        let schema = Arc::new(Schema::new(vec![
5673            Field::new("col0", arrow_schema::DataType::Int64, false),
5674            Field::new("col1", arrow_schema::DataType::Int64, false),
5675        ]));
5676        let batch =
5677            arrow_array::RecordBatch::try_new(schema.clone(), vec![array.clone(), array]).unwrap();
5678
5679        let props = WriterProperties::builder()
5680            .set_dictionary_page_size_limit(1024 * 1024)
5681            .set_column_dictionary_page_size_limit(ColumnPath::from("col1"), 1024 * 1024 * 4)
5682            .build();
5683        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5684        writer.write(&batch).unwrap();
5685        let data = Bytes::from(writer.into_inner().unwrap());
5686
5687        let mut metadata = ParquetMetaDataReader::new();
5688        metadata.try_parse(&data).unwrap();
5689        let metadata = metadata.finish().unwrap();
5690        let col0_meta = metadata.row_group(0).column(0);
5691        let col1_meta = metadata.row_group(0).column(1);
5692
5693        let get_dict_page_size = move |meta: &ColumnChunkMetaData| {
5694            let mut reader =
5695                SerializedPageReader::new(Arc::new(data.clone()), meta, 0, None).unwrap();
5696            let page = reader.get_next_page().unwrap().unwrap();
5697            match page {
5698                Page::DictionaryPage { buf, .. } => buf.len(),
5699                _ => panic!("expected DictionaryPage"),
5700            }
5701        };
5702
5703        assert_eq!(get_dict_page_size(col0_meta), 1024 * 1024);
5704        assert_eq!(get_dict_page_size(col1_meta), 1024 * 1024 * 4);
5705    }
5706
5707    #[test]
5708    #[cfg_attr(miri, ignore)] // Takes too long
5709    fn test_arrow_writer_granular_mode_roundtrip() {
5710        // Granular mode subdivides chunks and writes more pages than the
5711        // default batched path. Make sure the data we write back is
5712        // bit-identical to what went in — page-count assertions elsewhere
5713        // only prove pages were cut, not that the encoded data is correct.
5714        //
5715        // Mix value sizes so that the cumulative-byte-budget cutoff
5716        // lands mid-chunk, exercising both batched and granular paths
5717        // within the same `write_batch_internal` call.
5718        let small = "tiny".to_string();
5719        let big = "x".repeat(64 * 1024);
5720        let strings: Vec<String> = (0..256)
5721            .map(|i| {
5722                if i % 16 == 0 {
5723                    big.clone()
5724                } else {
5725                    small.clone()
5726                }
5727            })
5728            .collect();
5729
5730        let schema = Arc::new(Schema::new(vec![Field::new(
5731            "col",
5732            ArrowDataType::Utf8,
5733            false,
5734        )]));
5735        let batch = RecordBatch::try_new(
5736            schema.clone(),
5737            vec![Arc::new(StringArray::from(strings.clone())) as _],
5738        )
5739        .unwrap();
5740
5741        let props = WriterProperties::builder()
5742            .set_dictionary_enabled(false)
5743            .set_data_page_size_limit(16 * 1024)
5744            .build();
5745        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5746        writer.write(&batch).unwrap();
5747        let data = Bytes::from(writer.into_inner().unwrap());
5748
5749        let mut reader = ParquetRecordBatchReader::try_new(data, 1024).unwrap();
5750        let read = reader.next().unwrap().unwrap();
5751        assert!(reader.next().is_none(), "expected one batch");
5752        let col = read
5753            .column(0)
5754            .as_any()
5755            .downcast_ref::<StringArray>()
5756            .unwrap();
5757        assert_eq!(col.len(), strings.len());
5758        for (i, expected) in strings.iter().enumerate() {
5759            assert_eq!(
5760                col.value(i),
5761                expected.as_str(),
5762                "value mismatch at index {i}"
5763            );
5764        }
5765    }
5766
5767    #[test]
5768    fn test_arrow_writer_all_null_string_column() {
5769        // The `LevelDataRef::value_count` Uniform branch with
5770        // `value != max_def` (entirely-null chunk) must return 0 so the
5771        // sub-batch sizer short-circuits to batch mode without trying
5772        // to estimate byte budgets for non-existent values.
5773        let num_rows = 1024;
5774        let schema = Arc::new(Schema::new(vec![Field::new(
5775            "col",
5776            ArrowDataType::Utf8,
5777            true,
5778        )]));
5779        let nulls: Vec<Option<&str>> = vec![None; num_rows];
5780        let batch = RecordBatch::try_new(
5781            schema.clone(),
5782            vec![Arc::new(StringArray::from(nulls)) as _],
5783        )
5784        .unwrap();
5785
5786        let props = WriterProperties::builder()
5787            .set_dictionary_enabled(false)
5788            .set_data_page_size_limit(16 * 1024)
5789            .build();
5790        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5791        writer.write(&batch).unwrap();
5792        let data = Bytes::from(writer.into_inner().unwrap());
5793
5794        // Re-parse the file: row group has one column, every row is
5795        // null, all data pages report `num_rows / page_count` rows.
5796        let mut metadata = ParquetMetaDataReader::new();
5797        metadata.try_parse(&data).unwrap();
5798        let metadata = metadata.finish().unwrap();
5799        let row_group = metadata.row_group(0);
5800        let col_meta = row_group.column(0);
5801        assert_eq!(row_group.num_rows() as usize, num_rows);
5802        // Statistics record `null_count = num_rows` — proves every value
5803        // was written as null.
5804        if let Some(stats) = col_meta.statistics() {
5805            assert_eq!(
5806                stats.null_count_opt().unwrap_or(0) as usize,
5807                num_rows,
5808                "expected all-null column to report null_count = num_rows"
5809            );
5810        }
5811
5812        let mut reader =
5813            SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap();
5814        let mut total_values = 0u32;
5815        while let Some(page) = reader.get_next_page().unwrap() {
5816            if matches!(page, Page::DataPage { .. } | Page::DataPageV2 { .. }) {
5817                total_values += page.num_values();
5818            }
5819        }
5820        assert_eq!(
5821            total_values as usize, num_rows,
5822            "expected every level position to be represented in some page"
5823        );
5824    }
5825
5826    struct WriteBatchesShape {
5827        num_batches: usize,
5828        rows_per_batch: usize,
5829        row_size: usize,
5830    }
5831
5832    /// Helper function to write batches with the provided `WriteBatchesShape` into an `ArrowWriter`
5833    fn write_batches(
5834        WriteBatchesShape {
5835            num_batches,
5836            rows_per_batch,
5837            row_size,
5838        }: WriteBatchesShape,
5839        props: WriterProperties,
5840    ) -> ParquetRecordBatchReaderBuilder<File> {
5841        let schema = Arc::new(Schema::new(vec![Field::new(
5842            "str",
5843            ArrowDataType::Utf8,
5844            false,
5845        )]));
5846        let file = tempfile::tempfile().unwrap();
5847        let mut writer =
5848            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
5849
5850        for batch_idx in 0..num_batches {
5851            let strings: Vec<String> = (0..rows_per_batch)
5852                .map(|i| format!("{:0>width$}", batch_idx * 10 + i, width = row_size))
5853                .collect();
5854            let array = StringArray::from(strings);
5855            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
5856            writer.write(&batch).unwrap();
5857        }
5858        writer.close().unwrap();
5859        ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
5860    }
5861
5862    #[test]
5863    // When both limits are None, all data should go into a single row group
5864    fn test_row_group_limit_none_writes_single_row_group() {
5865        let props = WriterProperties::builder()
5866            .set_max_row_group_row_count(None)
5867            .set_max_row_group_bytes(None)
5868            .build();
5869
5870        let builder = write_batches(
5871            WriteBatchesShape {
5872                num_batches: 1,
5873                rows_per_batch: 1000,
5874                row_size: 4,
5875            },
5876            props,
5877        );
5878
5879        assert_eq!(
5880            &row_group_sizes(builder.metadata()),
5881            &[1000],
5882            "With no limits, all rows should be in a single row group"
5883        );
5884    }
5885
5886    #[test]
5887    // When only max_row_group_size is set, respect the row limit
5888    fn test_row_group_limit_rows_only() {
5889        let props = WriterProperties::builder()
5890            .set_max_row_group_row_count(Some(300))
5891            .set_max_row_group_bytes(None)
5892            .build();
5893
5894        let builder = write_batches(
5895            WriteBatchesShape {
5896                num_batches: 1,
5897                rows_per_batch: 1000,
5898                row_size: 4,
5899            },
5900            props,
5901        );
5902
5903        assert_eq!(
5904            &row_group_sizes(builder.metadata()),
5905            &[300, 300, 300, 100],
5906            "Row groups should be split by row count"
5907        );
5908    }
5909
5910    #[test]
5911    #[cfg_attr(miri, ignore)] // Takes too long
5912    // A row limit far smaller than the batch splits it many times over; the split must not
5913    // consume stack proportional to the number of row groups.
5914    fn test_row_group_limit_rows_only_many_splits() {
5915        let props = WriterProperties::builder()
5916            .set_max_row_group_row_count(Some(1))
5917            .set_max_row_group_bytes(None)
5918            .build();
5919
5920        let rows = 50_000;
5921        let builder = write_batches(
5922            WriteBatchesShape {
5923                num_batches: 1,
5924                rows_per_batch: rows,
5925                row_size: 4,
5926            },
5927            props,
5928        );
5929
5930        let sizes = row_group_sizes(builder.metadata());
5931        assert_eq!(sizes.len(), rows, "Every row should get its own row group");
5932        assert_eq!(
5933            sizes.iter().sum::<i64>(),
5934            rows as i64,
5935            "Total rows should be preserved"
5936        );
5937    }
5938
5939    #[test]
5940    // When only max_row_group_bytes is set, respect the byte limit
5941    fn test_row_group_limit_bytes_only() {
5942        let props = WriterProperties::builder()
5943            .set_max_row_group_row_count(None)
5944            // Set byte limit to approximately fit ~30 rows worth of data (~100 bytes each)
5945            .set_max_row_group_bytes(Some(3500))
5946            .build();
5947
5948        let builder = write_batches(
5949            WriteBatchesShape {
5950                num_batches: 10,
5951                rows_per_batch: 10,
5952                row_size: 100,
5953            },
5954            props,
5955        );
5956
5957        let sizes = row_group_sizes(builder.metadata());
5958
5959        assert!(
5960            sizes.len() > 1,
5961            "Should have multiple row groups due to byte limit, got {sizes:?}",
5962        );
5963
5964        let total_rows: i64 = sizes.iter().sum();
5965        assert_eq!(total_rows, 100, "Total rows should be preserved");
5966    }
5967
5968    #[test]
5969    // If an in-progress row group is already oversized, it should be flushed before writing more.
5970    fn test_row_group_limit_bytes_flushes_when_current_group_already_too_large() {
5971        let schema = Arc::new(Schema::new(vec![Field::new(
5972            "str",
5973            ArrowDataType::Utf8,
5974            false,
5975        )]));
5976        let file = tempfile::tempfile().unwrap();
5977
5978        // Start with no byte limit so we can intentionally build an oversized in-progress row group.
5979        let props = WriterProperties::builder()
5980            .set_max_row_group_row_count(None)
5981            .set_max_row_group_bytes(None)
5982            .build();
5983        let mut writer =
5984            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
5985
5986        let first_array = StringArray::from(
5987            (0..10)
5988                .map(|i| format!("{i:0>100}"))
5989                .collect::<Vec<String>>(),
5990        );
5991        let first_batch =
5992            RecordBatch::try_new(schema.clone(), vec![Arc::new(first_array)]).unwrap();
5993        writer.write(&first_batch).unwrap();
5994        assert_eq!(writer.in_progress_rows(), 10);
5995
5996        // Tighten the limit below the current in-progress bytes to exercise:
5997        // `if current_bytes >= max_bytes { self.flush()?; ... }`
5998        writer.max_row_group_bytes = Some(1);
5999
6000        let second_array = StringArray::from(vec!["x".to_string()]);
6001        let second_batch =
6002            RecordBatch::try_new(schema.clone(), vec![Arc::new(second_array)]).unwrap();
6003        writer.write(&second_batch).unwrap();
6004        writer.close().unwrap();
6005        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
6006
6007        assert_eq!(
6008            &row_group_sizes(builder.metadata()),
6009            &[10, 1],
6010            "The second write should flush an oversized in-progress row group first",
6011        );
6012    }
6013
6014    #[test]
6015    // When both limits are set, the row limit triggers first
6016    fn test_row_group_limit_both_row_wins_single_batch() {
6017        let props = WriterProperties::builder()
6018            .set_max_row_group_row_count(Some(200)) // Will trigger at 200 rows
6019            .set_max_row_group_bytes(Some(1024 * 1024)) // 1MB - won't trigger for small int data
6020            .build();
6021
6022        let builder = write_batches(
6023            WriteBatchesShape {
6024                num_batches: 1,
6025                row_size: 4,
6026                rows_per_batch: 1000,
6027            },
6028            props,
6029        );
6030
6031        assert_eq!(
6032            &row_group_sizes(builder.metadata()),
6033            &[200, 200, 200, 200, 200],
6034            "Row limit should trigger before byte limit"
6035        );
6036    }
6037
6038    #[test]
6039    // When both limits are set, the row limit triggers first
6040    fn test_row_group_limit_both_row_wins_multiple_batches() {
6041        let props = WriterProperties::builder()
6042            .set_max_row_group_row_count(Some(5)) // Will trigger every 5 rows
6043            .set_max_row_group_bytes(Some(9999)) // Won't trigger
6044            .build();
6045
6046        let builder = write_batches(
6047            WriteBatchesShape {
6048                num_batches: 10,
6049                rows_per_batch: 10,
6050                row_size: 100,
6051            },
6052            props,
6053        );
6054
6055        assert_eq!(
6056            &row_group_sizes(builder.metadata()),
6057            &[5; 20],
6058            "Row limit should trigger before byte limit"
6059        );
6060    }
6061
6062    #[test]
6063    // When both limits are set, the byte limit triggers first
6064    fn test_row_group_limit_both_bytes_wins() {
6065        let props = WriterProperties::builder()
6066            .set_max_row_group_row_count(Some(1000)) // Won't trigger for 100 rows
6067            .set_max_row_group_bytes(Some(3500)) // Will trigger at ~30-35 rows
6068            .build();
6069
6070        let builder = write_batches(
6071            WriteBatchesShape {
6072                num_batches: 10,
6073                rows_per_batch: 10,
6074                row_size: 100,
6075            },
6076            props,
6077        );
6078
6079        let sizes = row_group_sizes(builder.metadata());
6080
6081        assert!(
6082            sizes.len() > 1,
6083            "Byte limit should trigger before row limit, got {sizes:?}",
6084        );
6085
6086        assert!(
6087            sizes.iter().all(|&s| s < 1000),
6088            "No row group should hit the row limit"
6089        );
6090
6091        let total_rows: i64 = sizes.iter().sum();
6092        assert_eq!(total_rows, 100, "Total rows should be preserved");
6093    }
6094
6095    #[test]
6096    // Both limits can apply to the same batch: the row limit trims it to 5 rows, and the
6097    // byte limit then trims those 5 down to 4.
6098    fn test_row_group_limit_both_apply_to_same_batch() {
6099        let props = WriterProperties::builder()
6100            .set_max_row_group_row_count(Some(15))
6101            .set_max_row_group_bytes(Some(1500))
6102            .build();
6103
6104        let builder = write_batches(
6105            WriteBatchesShape {
6106                num_batches: 2,
6107                rows_per_batch: 10,
6108                row_size: 100,
6109            },
6110            props,
6111        );
6112
6113        assert_eq!(
6114            &row_group_sizes(builder.metadata()),
6115            &[14, 6],
6116            "Byte limit should still apply to a batch the row limit already split"
6117        );
6118    }
6119
6120    #[test]
6121    fn arrow_column_chunk_close_mut_drops_column_index() {
6122        use crate::arrow::ArrowSchemaConverter;
6123        use crate::file::writer::SerializedFileWriter;
6124
6125        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
6126        let props = Arc::new(
6127            WriterProperties::builder()
6128                .set_statistics_enabled(EnabledStatistics::Page)
6129                .build(),
6130        );
6131        let parquet_schema = ArrowSchemaConverter::new()
6132            .with_coerce_types(props.coerce_types())
6133            .convert(&schema)
6134            .unwrap();
6135
6136        let mut buf = Vec::with_capacity(1024);
6137        let mut writer =
6138            SerializedFileWriter::new(&mut buf, parquet_schema.root_schema_ptr(), props.clone())
6139                .unwrap();
6140
6141        let factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
6142        let mut col_writers = factory.create_column_writers(0).unwrap();
6143        let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..64));
6144        for leaves in compute_leaves(schema.field(0), &arr).unwrap() {
6145            col_writers[0].write(&leaves).unwrap();
6146        }
6147        let mut chunk = col_writers.pop().unwrap().close().unwrap();
6148
6149        // Immutable accessor exposes the close result produced at close time.
6150        assert!(
6151            chunk.close().column_index.is_some(),
6152            "EnabledStatistics::Page should produce a column_index"
6153        );
6154
6155        // Mutable accessor lets callers drop the page-level index before append.
6156        chunk.close_mut().column_index = None;
6157        assert!(chunk.close().column_index.is_none());
6158
6159        let mut rg = writer.next_row_group().unwrap();
6160        chunk.append_to_row_group(&mut rg).unwrap();
6161        rg.close().unwrap();
6162        let file_meta = writer.close().unwrap();
6163
6164        // After dropping column_index, the resulting file records no column
6165        // index offset/length for this chunk.
6166        let cc = file_meta.row_group(0).column(0);
6167        assert!(cc.column_index_range().is_none());
6168    }
6169
6170    /// Writes a single-column RecordBatch to an in-memory Parquet buffer.
6171    fn write_column_to_bytes(array: ArrayRef) -> Bytes {
6172        let schema = Arc::new(Schema::new(vec![Field::new(
6173            "col",
6174            array.data_type().clone(),
6175            true,
6176        )]));
6177        let buf = get_bytes_after_close(
6178            schema.clone(),
6179            &RecordBatch::try_new(schema, vec![array]).unwrap(),
6180        );
6181        Bytes::from(buf)
6182    }
6183
6184    /// Reads column 0 from a single-row-group Parquet buffer, projecting it with the given schema.
6185    /// Passing a flat schema when the buffer was written from a REE array lets callers decode
6186    /// the physical values without the run-end encoding wrapper.
6187    fn read_column_with_schema(bytes: Bytes, schema: SchemaRef) -> ArrayRef {
6188        let opts = crate::arrow::arrow_reader::ArrowReaderOptions::new().with_schema(schema);
6189        ParquetRecordBatchReaderBuilder::try_new_with_options(bytes, opts)
6190            .unwrap()
6191            .build()
6192            .unwrap()
6193            .next()
6194            .unwrap()
6195            .unwrap()
6196            .column(0)
6197            .clone()
6198    }
6199
6200    fn ree_write_read_roundtrip(ree: ArrayRef, flat: ArrayRef) {
6201        let flat_schema = Arc::new(Schema::new(vec![Field::new(
6202            "col",
6203            flat.data_type().clone(),
6204            true,
6205        )]));
6206        let ree_bytes = write_column_to_bytes(ree);
6207        let flat_bytes = write_column_to_bytes(flat.clone());
6208        assert_eq!(
6209            ree_bytes, flat_bytes,
6210            "REE and flat bytes should be identical"
6211        );
6212
6213        let decoded_ree = read_column_with_schema(ree_bytes, flat_schema.clone());
6214        let decoded_flat = read_column_with_schema(flat_bytes, flat_schema);
6215
6216        assert_eq!(decoded_ree.as_ref(), flat.as_ref());
6217        assert_eq!(decoded_ree.as_ref(), decoded_flat.as_ref());
6218    }
6219
6220    #[test]
6221    fn ree_string() {
6222        let ree: ArrayRef = Arc::new(
6223            [Some("a"), Some("a"), None, Some("b"), Some("b")]
6224                .into_iter()
6225                .collect::<Int32RunArray>(),
6226        );
6227        let flat: ArrayRef = Arc::new(StringArray::from(vec![
6228            Some("a"),
6229            Some("a"),
6230            None,
6231            Some("b"),
6232            Some("b"),
6233        ]));
6234        ree_write_read_roundtrip(ree, flat);
6235    }
6236
6237    #[test]
6238    fn ree_int32() {
6239        let mut b = PrimitiveRunBuilder::<Int32Type, Int32Type>::new();
6240        for v in [Some(1), Some(1), None, Some(2), Some(2)] {
6241            b.append_option(v);
6242        }
6243        let ree: ArrayRef = Arc::new(b.finish());
6244        let flat: ArrayRef = Arc::new(Int32Array::from(vec![
6245            Some(1),
6246            Some(1),
6247            None,
6248            Some(2),
6249            Some(2),
6250        ]));
6251        ree_write_read_roundtrip(ree, flat);
6252    }
6253
6254    #[test]
6255    fn ree_bool() {
6256        // run_ends [3, 5, 7] → [T,T,T, null,null, F,F]
6257        let ree: ArrayRef = Arc::new(
6258            RunArray::try_new(
6259                &Int32Array::from(vec![3, 5, 7]),
6260                &BooleanArray::from(vec![Some(true), None, Some(false)]),
6261            )
6262            .unwrap(),
6263        );
6264        let flat: ArrayRef = Arc::new(BooleanArray::from(vec![
6265            Some(true),
6266            Some(true),
6267            Some(true),
6268            None,
6269            None,
6270            Some(false),
6271            Some(false),
6272        ]));
6273        ree_write_read_roundtrip(ree, flat);
6274    }
6275
6276    #[test]
6277    fn ree_fixed_size_binary() {
6278        let mk = |vals: &[Option<&[u8]>]| -> FixedSizeBinaryArray {
6279            let mut b = FixedSizeBinaryBuilder::new(2);
6280            for v in vals {
6281                match v {
6282                    Some(x) => b.append_value(x).unwrap(),
6283                    None => b.append_null(),
6284                }
6285            }
6286            b.finish()
6287        };
6288        // run_ends [2, 4, 6] → [aa,aa, null,null, bb,bb]
6289        let ree: ArrayRef = Arc::new(
6290            RunArray::try_new(
6291                &Int32Array::from(vec![2, 4, 6]),
6292                &mk(&[Some(b"aa"), None, Some(b"bb")]),
6293            )
6294            .unwrap(),
6295        );
6296        let flat: ArrayRef = Arc::new(mk(&[
6297            Some(b"aa"),
6298            Some(b"aa"),
6299            None,
6300            None,
6301            Some(b"bb"),
6302            Some(b"bb"),
6303        ]));
6304        ree_write_read_roundtrip(ree, flat);
6305    }
6306
6307    #[test]
6308    fn ree_single_run() {
6309        let ree: ArrayRef = Arc::new(["x", "x", "x"].into_iter().collect::<Int32RunArray>());
6310        let flat: ArrayRef = Arc::new(StringArray::from(vec!["x", "x", "x"]));
6311        ree_write_read_roundtrip(ree, flat);
6312    }
6313
6314    #[test]
6315    fn ree_float32() {
6316        // run_ends [2, 4, 5] → [1.0, 1.0, null, null, 2.5]
6317        let ree: ArrayRef = Arc::new(
6318            RunArray::try_new(
6319                &Int32Array::from(vec![2, 4, 5]),
6320                &Float32Array::from(vec![Some(1.0_f32), None, Some(2.5_f32)]),
6321            )
6322            .unwrap(),
6323        );
6324        let flat: ArrayRef = Arc::new(Float32Array::from(vec![
6325            Some(1.0_f32),
6326            Some(1.0_f32),
6327            None,
6328            None,
6329            Some(2.5_f32),
6330        ]));
6331        ree_write_read_roundtrip(ree, flat);
6332    }
6333
6334    #[test]
6335    fn ree_sliced() {
6336        // A sliced (non-zero offset) REE array: verify that get_physical_index
6337        // correctly accounts for the logical offset when expanding.
6338        // Full array: run_ends [3, 5, 7] → [a,a,a, b,b, c,c]
6339        // After slice(2, 5) the logical view is [a, b, b, c, c].
6340        let full: ArrayRef = Arc::new(
6341            RunArray::try_new(
6342                &Int32Array::from(vec![3, 5, 7]),
6343                &StringArray::from(vec!["a", "b", "c"]),
6344            )
6345            .unwrap(),
6346        );
6347        let sliced = full.slice(2, 5);
6348        let flat: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "b", "c", "c"]));
6349        ree_write_read_roundtrip(sliced, flat);
6350    }
6351
6352    #[test]
6353    #[cfg_attr(miri, ignore)] // Takes too long
6354    fn test_number_distinct_values_exact_count() {
6355        // 50 distinct Int32 values repeated across 100k rows, with every 7th row null.
6356        // Nulls must not be counted as a distinct value.
6357        let cardinality = 50u32;
6358        let array: ArrayRef = Arc::new(Int32Array::from_iter((0..100_000u32).map(|i| {
6359            if i % 7 == 0 {
6360                None
6361            } else {
6362                Some((i % cardinality) as i32)
6363            }
6364        })));
6365        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, true)]));
6366        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
6367
6368        let props = WriterProperties::builder()
6369            .set_write_row_group_number_distinct_values(true)
6370            .build();
6371        let mut buf = Vec::new();
6372        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
6373        writer.write(&batch).unwrap();
6374        let metadata = writer.close().unwrap();
6375
6376        let count = metadata
6377            .row_group(0)
6378            .column(0)
6379            .statistics()
6380            .and_then(|s| s.distinct_count_opt())
6381            .expect("distinct_count should be set");
6382        // Must equal cardinality exactly; nulls must not inflate the count.
6383        assert_eq!(count, cardinality as u64);
6384    }
6385
6386    #[test]
6387    fn test_number_distinct_values_not_written_by_default() {
6388        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
6389        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)]));
6390        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
6391
6392        let mut buf = Vec::new();
6393        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
6394        writer.write(&batch).unwrap();
6395        let metadata = writer.close().unwrap();
6396
6397        let count = metadata
6398            .row_group(0)
6399            .column(0)
6400            .statistics()
6401            .and_then(|s| s.distinct_count_opt());
6402        assert!(count.is_none());
6403    }
6404
6405    #[test]
6406    fn ree_struct_with_ree_child() {
6407        // Struct with a REE string field and a REE int field — confirms
6408        // recursion visits every child and each collapses to the right leaf type.
6409        let run_ends = Int32Array::from(vec![2i32, 3, 5]);
6410
6411        let col_a: ArrayRef = Arc::new(
6412            RunArray::try_new(
6413                &run_ends,
6414                &StringArray::from(vec![Some("foo"), None, Some("bar")]),
6415            )
6416            .unwrap(),
6417        );
6418        let col_b: ArrayRef = Arc::new(
6419            RunArray::try_new(&run_ends, &Int32Array::from(vec![Some(1), None, Some(2)])).unwrap(),
6420        );
6421
6422        let struct_array: ArrayRef = Arc::new(StructArray::new(
6423            Fields::from(vec![
6424                Field::new("a", col_a.data_type().clone(), true),
6425                Field::new("b", col_b.data_type().clone(), true),
6426            ]),
6427            vec![col_a, col_b],
6428            None,
6429        ));
6430
6431        let schema = Arc::new(Schema::new(vec![Field::new(
6432            "row",
6433            struct_array.data_type().clone(),
6434            true,
6435        )]));
6436        let batch = RecordBatch::try_new(schema.clone(), vec![struct_array]).unwrap();
6437
6438        let mut buf = Vec::new();
6439        let mut writer = ArrowWriter::try_new(&mut buf, schema, None).unwrap();
6440        writer.write(&batch).unwrap();
6441        let metadata = writer.close().unwrap();
6442
6443        let parquet_schema = metadata.file_metadata().schema_descr();
6444        assert_eq!(parquet_schema.num_columns(), 2);
6445        assert_eq!(
6446            parquet_schema.column(0).physical_type(),
6447            crate::basic::Type::BYTE_ARRAY
6448        );
6449        assert_eq!(parquet_schema.column(0).path().string(), "row.a");
6450        assert_eq!(
6451            parquet_schema.column(1).physical_type(),
6452            crate::basic::Type::INT32
6453        );
6454        assert_eq!(parquet_schema.column(1).path().string(), "row.b");
6455    }
6456}