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    ///
1190    /// # Errors
1191    ///
1192    /// Returns an error if the column could not be finalised, or if another thread
1193    /// panicked while holding the column chunk. The caller cannot cause either.
1194    pub fn close(self) -> Result<ArrowColumnChunk> {
1195        let distinct_count = self
1196            .distinct_values_seen
1197            .as_ref()
1198            .filter(|s| !s.is_empty())
1199            .map(|s| s.len() as u64);
1200        let close = match self.writer {
1201            ArrowColumnWriterImpl::ByteArray(mut c) => {
1202                if let Some(count) = distinct_count {
1203                    c.set_distinct_count_override(count);
1204                }
1205                c.close()?
1206            }
1207            ArrowColumnWriterImpl::Column(mut c) => {
1208                if let Some(count) = distinct_count {
1209                    c.set_distinct_count_override(count);
1210                }
1211                c.close()?
1212            }
1213        };
1214        // Closing the writer above dropped the only other handle on the chunk.
1215        let chunk = Arc::try_unwrap(self.chunk)
1216            .map_err(|_| general_err!("Internal Error: the column chunk is still shared"))?;
1217        let data = chunk
1218            .into_inner()
1219            .map_err(|_| general_err!("The column chunk lock is poisoned"))?;
1220        Ok(ArrowColumnChunk { data, close })
1221    }
1222
1223    /// Returns the estimated total memory usage by the writer.
1224    ///
1225    /// This  [`Self::get_estimated_total_bytes`] this is an estimate
1226    /// of the current memory usage and not it's anticipated encoded size.
1227    ///
1228    /// This includes:
1229    /// 1. Data buffered in encoded form
1230    /// 2. Data buffered in un-encoded form (e.g. `usize` dictionary keys)
1231    ///
1232    /// This value should be greater than or equal to [`Self::get_estimated_total_bytes`]
1233    pub fn memory_size(&self) -> usize {
1234        match &self.writer {
1235            ArrowColumnWriterImpl::ByteArray(c) => c.memory_size(),
1236            ArrowColumnWriterImpl::Column(c) => c.memory_size(),
1237        }
1238    }
1239
1240    /// Returns the estimated total encoded bytes for this column writer.
1241    ///
1242    /// This includes:
1243    /// 1. Data buffered in encoded form
1244    /// 2. An estimate of how large the data buffered in un-encoded form would be once encoded
1245    ///
1246    /// This value should be less than or equal to [`Self::memory_size`]
1247    pub fn get_estimated_total_bytes(&self) -> usize {
1248        match &self.writer {
1249            ArrowColumnWriterImpl::ByteArray(c) => c.get_estimated_total_bytes() as _,
1250            ArrowColumnWriterImpl::Column(c) => c.get_estimated_total_bytes() as _,
1251        }
1252    }
1253}
1254
1255/// Encodes [`RecordBatch`] to a parquet row group
1256///
1257/// Note: this structure is created by [`ArrowRowGroupWriterFactory`] internally used to
1258/// create [`ArrowRowGroupWriter`]s, but it is not exposed publicly.
1259///
1260/// See the example on [`ArrowColumnWriter`] for how to encode columns in parallel
1261#[derive(Debug)]
1262struct ArrowRowGroupWriter {
1263    writers: Vec<ArrowColumnWriter>,
1264    schema: SchemaRef,
1265    buffered_rows: usize,
1266}
1267
1268impl ArrowRowGroupWriter {
1269    fn new(writers: Vec<ArrowColumnWriter>, arrow: &SchemaRef) -> Self {
1270        Self {
1271            writers,
1272            schema: arrow.clone(),
1273            buffered_rows: 0,
1274        }
1275    }
1276
1277    fn write(&mut self, batch: &RecordBatch) -> Result<()> {
1278        self.buffered_rows += batch.num_rows();
1279        let mut writers = self.writers.iter_mut();
1280        for (field, column) in self.schema.fields().iter().zip(batch.columns()) {
1281            for leaf in compute_leaves(field.as_ref(), column)? {
1282                writers.next().unwrap().write(&leaf)?;
1283            }
1284        }
1285        Ok(())
1286    }
1287
1288    fn write_with_chunkers(
1289        &mut self,
1290        batch: &RecordBatch,
1291        chunkers: &mut [ContentDefinedChunker],
1292    ) -> Result<()> {
1293        self.buffered_rows += batch.num_rows();
1294        let mut writers = self.writers.iter_mut();
1295        let mut chunkers = chunkers.iter_mut();
1296        for (field, column) in self.schema.fields().iter().zip(batch.columns()) {
1297            for leaf in compute_leaves(field.as_ref(), column)? {
1298                writers
1299                    .next()
1300                    .unwrap()
1301                    .write_with_chunker(&leaf, chunkers.next().unwrap())?;
1302            }
1303        }
1304        Ok(())
1305    }
1306
1307    /// Returns the estimated total encoded bytes for this row group
1308    fn get_estimated_total_bytes(&self) -> usize {
1309        self.writers
1310            .iter()
1311            .map(|x| x.get_estimated_total_bytes())
1312            .sum()
1313    }
1314
1315    fn close(self) -> Result<Vec<ArrowColumnChunk>> {
1316        self.writers
1317            .into_iter()
1318            .map(|writer| writer.close())
1319            .collect()
1320    }
1321}
1322
1323/// Factory that creates new column writers for each row group in the Parquet file.
1324///
1325/// You can create this structure via an [`ArrowWriter::into_serialized_writer`].
1326/// See the example on [`ArrowColumnWriter`] for how to encode columns in parallel
1327#[derive(Debug)]
1328pub struct ArrowRowGroupWriterFactory {
1329    schema: SchemaDescPtr,
1330    arrow_schema: SchemaRef,
1331    props: WriterPropertiesPtr,
1332    page_store_factory: Arc<dyn PageStoreFactory>,
1333    #[cfg(feature = "encryption")]
1334    file_encryptor: Option<Arc<FileEncryptor>>,
1335}
1336
1337impl ArrowRowGroupWriterFactory {
1338    /// Create a new [`ArrowRowGroupWriterFactory`] for the provided file writer and Arrow schema
1339    pub fn new<W: Write + Send>(
1340        file_writer: &SerializedFileWriter<W>,
1341        arrow_schema: SchemaRef,
1342    ) -> Self {
1343        let schema = Arc::clone(file_writer.schema_descr_ptr());
1344        let props = Arc::clone(file_writer.properties());
1345        Self {
1346            schema,
1347            arrow_schema,
1348            props,
1349            page_store_factory: Arc::new(InMemoryPageStoreFactory),
1350            #[cfg(feature = "encryption")]
1351            file_encryptor: file_writer.file_encryptor(),
1352        }
1353    }
1354
1355    /// Set the [`PageStoreFactory`] used to allocate the buffer for each column
1356    /// chunk, e.g. to spill completed pages to a temp file or object storage
1357    /// instead of the heap. Defaults to [`InMemoryPageStoreFactory`].
1358    pub fn with_page_store_factory(
1359        mut self,
1360        page_store_factory: Arc<dyn PageStoreFactory>,
1361    ) -> Self {
1362        self.page_store_factory = page_store_factory;
1363        self
1364    }
1365
1366    fn create_row_group_writer(&self, row_group_index: usize) -> Result<ArrowRowGroupWriter> {
1367        let writers = self.create_column_writers(row_group_index)?;
1368        Ok(ArrowRowGroupWriter::new(writers, &self.arrow_schema))
1369    }
1370
1371    /// Create column writers for a new row group, with the given row group index
1372    pub fn create_column_writers(&self, row_group_index: usize) -> Result<Vec<ArrowColumnWriter>> {
1373        let mut writers = Vec::with_capacity(self.arrow_schema.fields.len());
1374        let mut leaves = self.schema.columns().iter();
1375        let column_factory = self.column_writer_factory(row_group_index);
1376        for field in &self.arrow_schema.fields {
1377            column_factory.get_arrow_column_writer(
1378                field.data_type(),
1379                &self.props,
1380                &mut leaves,
1381                &mut writers,
1382            )?;
1383        }
1384        Ok(writers)
1385    }
1386
1387    #[cfg(feature = "encryption")]
1388    fn column_writer_factory(&self, row_group_idx: usize) -> ArrowColumnWriterFactory {
1389        ArrowColumnWriterFactory::new()
1390            .with_page_store_factory(self.page_store_factory.clone())
1391            .with_file_encryptor(row_group_idx, self.file_encryptor.clone())
1392    }
1393
1394    #[cfg(not(feature = "encryption"))]
1395    fn column_writer_factory(&self, _row_group_idx: usize) -> ArrowColumnWriterFactory {
1396        ArrowColumnWriterFactory::new().with_page_store_factory(self.page_store_factory.clone())
1397    }
1398}
1399
1400/// Creates [`ArrowColumnWriter`] instances
1401struct ArrowColumnWriterFactory {
1402    /// Allocates the per-column-chunk [`PageStore`] backing each page writer.
1403    page_store_factory: Arc<dyn PageStoreFactory>,
1404    #[cfg(feature = "encryption")]
1405    row_group_index: usize,
1406    #[cfg(feature = "encryption")]
1407    file_encryptor: Option<Arc<FileEncryptor>>,
1408}
1409
1410impl ArrowColumnWriterFactory {
1411    pub fn new() -> Self {
1412        Self {
1413            page_store_factory: Arc::new(InMemoryPageStoreFactory),
1414            #[cfg(feature = "encryption")]
1415            row_group_index: 0,
1416            #[cfg(feature = "encryption")]
1417            file_encryptor: None,
1418        }
1419    }
1420
1421    /// Use `page_store_factory` to allocate the buffer for each column chunk.
1422    pub fn with_page_store_factory(
1423        mut self,
1424        page_store_factory: Arc<dyn PageStoreFactory>,
1425    ) -> Self {
1426        self.page_store_factory = page_store_factory;
1427        self
1428    }
1429
1430    #[cfg(feature = "encryption")]
1431    pub fn with_file_encryptor(
1432        mut self,
1433        row_group_index: usize,
1434        file_encryptor: Option<Arc<FileEncryptor>>,
1435    ) -> Self {
1436        self.row_group_index = row_group_index;
1437        self.file_encryptor = file_encryptor;
1438        self
1439    }
1440
1441    #[cfg(feature = "encryption")]
1442    fn create_page_writer(
1443        &self,
1444        column_descriptor: &ColumnDescPtr,
1445        column_index: usize,
1446    ) -> Result<Box<ArrowPageWriter>> {
1447        let column_path = column_descriptor.path().string();
1448        let page_encryptor = PageEncryptor::create_if_column_encrypted(
1449            self.file_encryptor.as_ref(),
1450            self.row_group_index,
1451            column_index,
1452            &column_path,
1453        )?;
1454        let args = PageStoreArgs::new(column_index, column_descriptor);
1455        let store = self.page_store_factory.create(&args)?;
1456        Ok(Box::new(
1457            ArrowPageWriter::new(store).with_encryptor(page_encryptor),
1458        ))
1459    }
1460
1461    #[cfg(not(feature = "encryption"))]
1462    fn create_page_writer(
1463        &self,
1464        column_descriptor: &ColumnDescPtr,
1465        column_index: usize,
1466    ) -> Result<Box<ArrowPageWriter>> {
1467        let args = PageStoreArgs::new(column_index, column_descriptor);
1468        let store = self.page_store_factory.create(&args)?;
1469        Ok(Box::new(ArrowPageWriter::new(store)))
1470    }
1471
1472    /// Gets an [`ArrowColumnWriter`] for the given `data_type`, appending the
1473    /// output ColumnDesc to `leaves` and the column writers to `out`
1474    fn get_arrow_column_writer(
1475        &self,
1476        data_type: &ArrowDataType,
1477        props: &WriterPropertiesPtr,
1478        leaves: &mut Iter<'_, ColumnDescPtr>,
1479        out: &mut Vec<ArrowColumnWriter>,
1480    ) -> Result<()> {
1481        let write_distinct_values = props.write_row_group_number_distinct_values();
1482
1483        // Instantiate writers for normal columns
1484        let col = |desc: &ColumnDescPtr| -> Result<ArrowColumnWriter> {
1485            let page_writer = self.create_page_writer(desc, out.len())?;
1486            let chunk = page_writer.buffer.clone();
1487            let writer = get_column_writer(desc.clone(), props.clone(), page_writer);
1488            Ok(ArrowColumnWriter {
1489                chunk,
1490                writer: ArrowColumnWriterImpl::Column(writer),
1491                distinct_values_seen: write_distinct_values.then(HashSet::new),
1492            })
1493        };
1494
1495        // Instantiate writers for byte arrays (e.g. Utf8,  Binary, etc)
1496        let bytes = |desc: &ColumnDescPtr| -> Result<ArrowColumnWriter> {
1497            let page_writer = self.create_page_writer(desc, out.len())?;
1498            let chunk = page_writer.buffer.clone();
1499            let writer = GenericColumnWriter::new(desc.clone(), props.clone(), page_writer);
1500            Ok(ArrowColumnWriter {
1501                chunk,
1502                writer: ArrowColumnWriterImpl::ByteArray(writer),
1503                distinct_values_seen: write_distinct_values.then(HashSet::new),
1504            })
1505        };
1506
1507        match data_type {
1508            _ if data_type.is_primitive() => out.push(col(leaves.next().unwrap())?),
1509            ArrowDataType::FixedSizeBinary(_) | ArrowDataType::Boolean | ArrowDataType::Null => {
1510                out.push(col(leaves.next().unwrap())?)
1511            }
1512            ArrowDataType::LargeBinary
1513            | ArrowDataType::Binary
1514            | ArrowDataType::Utf8
1515            | ArrowDataType::LargeUtf8
1516            | ArrowDataType::BinaryView
1517            | ArrowDataType::Utf8View => out.push(bytes(leaves.next().unwrap())?),
1518            ArrowDataType::List(f)
1519            | ArrowDataType::LargeList(f)
1520            | ArrowDataType::FixedSizeList(f, _)
1521            | ArrowDataType::ListView(f)
1522            | ArrowDataType::LargeListView(f) => {
1523                self.get_arrow_column_writer(f.data_type(), props, leaves, out)?
1524            }
1525            ArrowDataType::Struct(fields) => {
1526                for field in fields {
1527                    self.get_arrow_column_writer(field.data_type(), props, leaves, out)?
1528                }
1529            }
1530            ArrowDataType::Map(f, _) => match f.data_type() {
1531                ArrowDataType::Struct(f) => {
1532                    self.get_arrow_column_writer(f[0].data_type(), props, leaves, out)?;
1533                    self.get_arrow_column_writer(f[1].data_type(), props, leaves, out)?
1534                }
1535                _ => unreachable!("invalid map type"),
1536            },
1537            ArrowDataType::Dictionary(_, value_type) => match value_type.as_ref() {
1538                ArrowDataType::Utf8
1539                | ArrowDataType::LargeUtf8
1540                | ArrowDataType::Binary
1541                | ArrowDataType::LargeBinary => out.push(bytes(leaves.next().unwrap())?),
1542                ArrowDataType::Utf8View | ArrowDataType::BinaryView => {
1543                    out.push(bytes(leaves.next().unwrap())?)
1544                }
1545                ArrowDataType::FixedSizeBinary(_) => out.push(bytes(leaves.next().unwrap())?),
1546                _ => out.push(col(leaves.next().unwrap())?),
1547            },
1548            ArrowDataType::RunEndEncoded(_, value_field) => {
1549                self.get_arrow_column_writer(value_field.data_type(), props, leaves, out)?
1550            }
1551            _ => {
1552                return Err(ParquetError::NYI(format!(
1553                    "Attempting to write an Arrow type {data_type} to parquet that is not yet implemented"
1554                )));
1555            }
1556        }
1557        Ok(())
1558    }
1559}
1560
1561fn write_leaf(
1562    writer: &mut ColumnWriter<'_>,
1563    column: &dyn arrow_array::Array,
1564    levels: &ArrayLevels,
1565) -> Result<usize> {
1566    let indices = levels.non_null_indices();
1567
1568    match writer {
1569        // Note: this should match the contents of arrow_to_parquet_type
1570        ColumnWriter::Int32ColumnWriter(typed) => {
1571            match column.data_type() {
1572                ArrowDataType::Null => {
1573                    let array = Int32Array::new_null(column.len());
1574                    write_primitive(typed, array.values(), levels)
1575                }
1576                ArrowDataType::Int8 => {
1577                    let array: Int32Array = column.as_primitive::<Int8Type>().unary(|x| x as i32);
1578                    write_primitive(typed, array.values(), levels)
1579                }
1580                ArrowDataType::Int16 => {
1581                    let array: Int32Array = column.as_primitive::<Int16Type>().unary(|x| x as i32);
1582                    write_primitive(typed, array.values(), levels)
1583                }
1584                ArrowDataType::Int32 => {
1585                    write_primitive(typed, column.as_primitive::<Int32Type>().values(), levels)
1586                }
1587                ArrowDataType::UInt8 => {
1588                    let array: Int32Array = column.as_primitive::<UInt8Type>().unary(|x| x as i32);
1589                    write_primitive(typed, array.values(), levels)
1590                }
1591                ArrowDataType::UInt16 => {
1592                    let array: Int32Array = column.as_primitive::<UInt16Type>().unary(|x| x as i32);
1593                    write_primitive(typed, array.values(), levels)
1594                }
1595                ArrowDataType::UInt32 => {
1596                    // follow C++ implementation and use overflow/reinterpret cast from  u32 to i32 which will map
1597                    // `(i32::MAX as u32)..u32::MAX` to `i32::MIN..0`
1598                    let array = column.as_primitive::<UInt32Type>();
1599                    write_primitive(typed, array.values().inner().typed_data(), levels)
1600                }
1601                ArrowDataType::Date32 => {
1602                    let array = column.as_primitive::<Date32Type>();
1603                    write_primitive(typed, array.values(), levels)
1604                }
1605                ArrowDataType::Time32(TimeUnit::Second) => {
1606                    let array = column.as_primitive::<Time32SecondType>();
1607                    write_primitive(typed, array.values(), levels)
1608                }
1609                ArrowDataType::Time32(TimeUnit::Millisecond) => {
1610                    let array = column.as_primitive::<Time32MillisecondType>();
1611                    write_primitive(typed, array.values(), levels)
1612                }
1613                ArrowDataType::Date64 => {
1614                    // If the column is a Date64, we truncate it
1615                    let array: Int32Array = column
1616                        .as_primitive::<Date64Type>()
1617                        .unary(|x| (x / 86_400_000) as _);
1618
1619                    write_primitive(typed, array.values(), levels)
1620                }
1621                ArrowDataType::Decimal32(_, _) => {
1622                    let array = column
1623                        .as_primitive::<Decimal32Type>()
1624                        .unary::<_, Int32Type>(|v| v);
1625                    write_primitive(typed, array.values(), levels)
1626                }
1627                ArrowDataType::Decimal64(_, _) => {
1628                    // use the int32 to represent the decimal with low precision
1629                    let array = column
1630                        .as_primitive::<Decimal64Type>()
1631                        .unary::<_, Int32Type>(|v| v as i32);
1632                    write_primitive(typed, array.values(), levels)
1633                }
1634                ArrowDataType::Decimal128(_, _) => {
1635                    // use the int32 to represent the decimal with low precision
1636                    let array = column
1637                        .as_primitive::<Decimal128Type>()
1638                        .unary::<_, Int32Type>(|v| v as i32);
1639                    write_primitive(typed, array.values(), levels)
1640                }
1641                ArrowDataType::Decimal256(_, _) => {
1642                    // use the int32 to represent the decimal with low precision
1643                    let array = column
1644                        .as_primitive::<Decimal256Type>()
1645                        .unary::<_, Int32Type>(|v| v.as_i128() as i32);
1646                    write_primitive(typed, array.values(), levels)
1647                }
1648                d => Err(ParquetError::General(format!("Cannot coerce {d} to I32"))),
1649            }
1650        }
1651        ColumnWriter::BoolColumnWriter(typed) => {
1652            let array = column.as_boolean();
1653            let values = get_bool_array_slice(array, indices.iter().copied());
1654            typed.write_batch_internal(
1655                values.as_slice(),
1656                None,
1657                levels.def_level_data().as_ref(),
1658                levels.rep_level_data().as_ref(),
1659                None,
1660                None,
1661                None,
1662            )
1663        }
1664        ColumnWriter::Int64ColumnWriter(typed) => {
1665            match column.data_type() {
1666                ArrowDataType::Date64 => {
1667                    let array = column
1668                        .as_primitive::<Date64Type>()
1669                        .reinterpret_cast::<Int64Type>();
1670
1671                    write_primitive(typed, array.values(), levels)
1672                }
1673                ArrowDataType::Int64 => {
1674                    let array = column.as_primitive::<Int64Type>();
1675                    write_primitive(typed, array.values(), levels)
1676                }
1677                ArrowDataType::UInt64 => {
1678                    let values = column.as_primitive::<UInt64Type>().values();
1679                    // follow C++ implementation and use overflow/reinterpret cast from  u64 to i64 which will map
1680                    // `(i64::MAX as u64)..u64::MAX` to `i64::MIN..0`
1681                    let array = values.inner().typed_data::<i64>();
1682                    write_primitive(typed, array, levels)
1683                }
1684                ArrowDataType::Time64(TimeUnit::Microsecond) => {
1685                    let array = column.as_primitive::<Time64MicrosecondType>();
1686                    write_primitive(typed, array.values(), levels)
1687                }
1688                ArrowDataType::Time64(TimeUnit::Nanosecond) => {
1689                    let array = column.as_primitive::<Time64NanosecondType>();
1690                    write_primitive(typed, array.values(), levels)
1691                }
1692                ArrowDataType::Timestamp(unit, _) => match unit {
1693                    TimeUnit::Second => {
1694                        let array = column.as_primitive::<TimestampSecondType>();
1695                        write_primitive(typed, array.values(), levels)
1696                    }
1697                    TimeUnit::Millisecond => {
1698                        let array = column.as_primitive::<TimestampMillisecondType>();
1699                        write_primitive(typed, array.values(), levels)
1700                    }
1701                    TimeUnit::Microsecond => {
1702                        let array = column.as_primitive::<TimestampMicrosecondType>();
1703                        write_primitive(typed, array.values(), levels)
1704                    }
1705                    TimeUnit::Nanosecond => {
1706                        let array = column.as_primitive::<TimestampNanosecondType>();
1707                        write_primitive(typed, array.values(), levels)
1708                    }
1709                },
1710                ArrowDataType::Duration(unit) => match unit {
1711                    TimeUnit::Second => {
1712                        let array = column.as_primitive::<DurationSecondType>();
1713                        write_primitive(typed, array.values(), levels)
1714                    }
1715                    TimeUnit::Millisecond => {
1716                        let array = column.as_primitive::<DurationMillisecondType>();
1717                        write_primitive(typed, array.values(), levels)
1718                    }
1719                    TimeUnit::Microsecond => {
1720                        let array = column.as_primitive::<DurationMicrosecondType>();
1721                        write_primitive(typed, array.values(), levels)
1722                    }
1723                    TimeUnit::Nanosecond => {
1724                        let array = column.as_primitive::<DurationNanosecondType>();
1725                        write_primitive(typed, array.values(), levels)
1726                    }
1727                },
1728                ArrowDataType::Decimal64(_, _) => {
1729                    let array = column
1730                        .as_primitive::<Decimal64Type>()
1731                        .reinterpret_cast::<Int64Type>();
1732                    write_primitive(typed, array.values(), levels)
1733                }
1734                ArrowDataType::Decimal128(_, _) => {
1735                    // use the int64 to represent the decimal with low precision
1736                    let array = column
1737                        .as_primitive::<Decimal128Type>()
1738                        .unary::<_, Int64Type>(|v| v as i64);
1739                    write_primitive(typed, array.values(), levels)
1740                }
1741                ArrowDataType::Decimal256(_, _) => {
1742                    // use the int64 to represent the decimal with low precision
1743                    let array = column
1744                        .as_primitive::<Decimal256Type>()
1745                        .unary::<_, Int64Type>(|v| v.as_i128() as i64);
1746                    write_primitive(typed, array.values(), levels)
1747                }
1748                d => Err(ParquetError::General(format!("Cannot coerce {d} to I64"))),
1749            }
1750        }
1751        ColumnWriter::Int96ColumnWriter(_typed) => {
1752            unreachable!("Currently unreachable because data type not supported")
1753        }
1754        ColumnWriter::FloatColumnWriter(typed) => {
1755            let array = column.as_primitive::<Float32Type>();
1756            write_primitive(typed, array.values(), levels)
1757        }
1758        ColumnWriter::DoubleColumnWriter(typed) => {
1759            let array = column.as_primitive::<Float64Type>();
1760            write_primitive(typed, array.values(), levels)
1761        }
1762        ColumnWriter::ByteArrayColumnWriter(_) => {
1763            unreachable!("should use ByteArrayWriter")
1764        }
1765        ColumnWriter::FixedLenByteArrayColumnWriter(typed) => {
1766            let bytes = match column.data_type() {
1767                ArrowDataType::Interval(interval_unit) => match interval_unit {
1768                    IntervalUnit::YearMonth => {
1769                        let array = column.as_primitive::<IntervalYearMonthType>();
1770                        get_interval_ym_array_slice(array, indices.iter().copied())
1771                    }
1772                    IntervalUnit::DayTime => {
1773                        let array = column.as_primitive::<IntervalDayTimeType>();
1774                        get_interval_dt_array_slice(array, indices.iter().copied())
1775                    }
1776                    IntervalUnit::MonthDayNano => {
1777                        return Err(ParquetError::NYI(format!(
1778                            "Attempting to write an Arrow interval type {interval_unit:?} to parquet that is not yet implemented"
1779                        )));
1780                    }
1781                },
1782                ArrowDataType::FixedSizeBinary(_) => {
1783                    let array = column.as_fixed_size_binary();
1784                    get_fsb_array_slice(array, indices.iter().copied())
1785                }
1786                ArrowDataType::Decimal32(_, _) => {
1787                    let array = column.as_primitive::<Decimal32Type>();
1788                    get_decimal_array_slice(array, indices.iter().copied())
1789                }
1790                ArrowDataType::Decimal64(_, _) => {
1791                    let array = column.as_primitive::<Decimal64Type>();
1792                    get_decimal_array_slice(array, indices.iter().copied())
1793                }
1794                ArrowDataType::Decimal128(_, _) => {
1795                    let array = column.as_primitive::<Decimal128Type>();
1796                    get_decimal_array_slice(array, indices.iter().copied())
1797                }
1798                ArrowDataType::Decimal256(_, _) => {
1799                    let array = column.as_primitive::<Decimal256Type>();
1800                    get_decimal_array_slice(array, indices.iter().copied())
1801                }
1802                ArrowDataType::Float16 => {
1803                    let array = column.as_primitive::<Float16Type>();
1804                    get_float_16_array_slice(array, indices.iter().copied())
1805                }
1806                _ => {
1807                    return Err(ParquetError::NYI(
1808                        "Attempting to write an Arrow type that is not yet implemented".to_string(),
1809                    ));
1810                }
1811            };
1812            typed.write_batch_internal(
1813                bytes.as_slice(),
1814                None,
1815                levels.def_level_data().as_ref(),
1816                levels.rep_level_data().as_ref(),
1817                None,
1818                None,
1819                None,
1820            )
1821        }
1822    }
1823}
1824
1825fn write_primitive<E: ColumnValueEncoder>(
1826    writer: &mut GenericColumnWriter<E>,
1827    values: &E::Values,
1828    levels: &ArrayLevels,
1829) -> Result<usize> {
1830    writer.write_batch_internal(
1831        values,
1832        Some(levels.non_null_indices()),
1833        levels.def_level_data().as_ref(),
1834        levels.rep_level_data().as_ref(),
1835        None,
1836        None,
1837        None,
1838    )
1839}
1840
1841fn get_bool_array_slice(
1842    array: &arrow_array::BooleanArray,
1843    indices: impl ExactSizeIterator<Item = usize>,
1844) -> Vec<bool> {
1845    let mut values = Vec::with_capacity(indices.len());
1846    for i in indices {
1847        values.push(array.value(i))
1848    }
1849    values
1850}
1851
1852/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1853/// An Arrow YearMonth interval only stores months, thus only the first 4 bytes are populated.
1854fn get_interval_ym_array_slice(
1855    array: &arrow_array::IntervalYearMonthArray,
1856    indices: impl ExactSizeIterator<Item = usize>,
1857) -> Vec<FixedLenByteArray> {
1858    chunk_array_slice(12, indices, move |i, chunk| {
1859        let value = array.value(i);
1860        chunk[0..4].copy_from_slice(&value.to_le_bytes());
1861    })
1862}
1863
1864/// Returns 12-byte values representing 3 values of months, days and milliseconds (4-bytes each).
1865/// An Arrow DayTime interval only stores days and millis, thus the first 4 bytes are not populated.
1866fn get_interval_dt_array_slice(
1867    array: &arrow_array::IntervalDayTimeArray,
1868    indices: impl ExactSizeIterator<Item = usize>,
1869) -> Vec<FixedLenByteArray> {
1870    chunk_array_slice(12, indices, move |i, chunk| {
1871        let value = array.value(i);
1872        chunk[4..8].copy_from_slice(&value.days.to_le_bytes());
1873        chunk[8..12].copy_from_slice(&value.milliseconds.to_le_bytes());
1874    })
1875}
1876
1877trait NativeDecimalType: DecimalType {
1878    type NativeBytes: AsRef<[u8]>;
1879
1880    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes;
1881}
1882impl NativeDecimalType for Decimal32Type {
1883    type NativeBytes = [u8; Self::BYTE_LENGTH];
1884
1885    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1886        value.to_be_bytes()
1887    }
1888}
1889impl NativeDecimalType for Decimal64Type {
1890    type NativeBytes = [u8; Self::BYTE_LENGTH];
1891
1892    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1893        value.to_be_bytes()
1894    }
1895}
1896impl NativeDecimalType for Decimal128Type {
1897    type NativeBytes = [u8; Self::BYTE_LENGTH];
1898
1899    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1900        value.to_be_bytes()
1901    }
1902}
1903impl NativeDecimalType for Decimal256Type {
1904    type NativeBytes = [u8; Self::BYTE_LENGTH];
1905
1906    fn to_be_bytes(value: Self::Native) -> Self::NativeBytes {
1907        value.to_be_bytes()
1908    }
1909}
1910
1911fn get_decimal_array_slice<T: NativeDecimalType>(
1912    array: &PrimitiveArray<T>,
1913    indices: impl ExactSizeIterator<Item = usize>,
1914) -> Vec<FixedLenByteArray> {
1915    let chunk_size = decimal_length_from_precision(array.precision());
1916    assert!(chunk_size <= T::BYTE_LENGTH);
1917
1918    if chunk_size == T::BYTE_LENGTH {
1919        // Special-case that allows inlining memcpy.
1920        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1921            let as_be_bytes = T::to_be_bytes(array.value(i));
1922            chunk.copy_from_slice(as_be_bytes.as_ref());
1923        })
1924    } else {
1925        chunk_array_slice(chunk_size, indices, move |i, chunk| {
1926            let as_be_bytes = T::to_be_bytes(array.value(i));
1927            let resized_value = &as_be_bytes.as_ref()[(T::BYTE_LENGTH - chunk.len())..];
1928            chunk.copy_from_slice(resized_value);
1929        })
1930    }
1931}
1932
1933fn get_float_16_array_slice(
1934    array: &arrow_array::Float16Array,
1935    indices: impl ExactSizeIterator<Item = usize>,
1936) -> Vec<FixedLenByteArray> {
1937    chunk_array_slice(2, indices, move |i, chunk| {
1938        let value = array.value(i).to_le_bytes();
1939        chunk.copy_from_slice(&value);
1940    })
1941}
1942
1943fn get_fsb_array_slice(
1944    array: &arrow_array::FixedSizeBinaryArray,
1945    indices: impl ExactSizeIterator<Item = usize>,
1946) -> Vec<FixedLenByteArray> {
1947    chunk_array_slice(array.value_size(), indices, move |i, chunk| {
1948        let value = array.value(i);
1949        chunk.copy_from_slice(value);
1950    })
1951}
1952
1953#[inline]
1954fn chunk_array_slice(
1955    chunk_size: usize,
1956    indices: impl ExactSizeIterator<Item = usize>,
1957    writer: impl Fn(usize, &mut [u8]),
1958) -> Vec<FixedLenByteArray> {
1959    let capacity = indices.len() * chunk_size;
1960    // TODO: This could be done with Vec::spare_capacity_mut,
1961    //       but [MaybeUninit]::write_copy_of_slice is gated behind MSRV 1.93
1962    let mut arena = vec![0; capacity];
1963    for (i, chunk) in indices.zip(arena.chunks_exact_mut(chunk_size)) {
1964        writer(i, chunk);
1965    }
1966    chunk_contiguous_vec(arena, chunk_size)
1967}
1968
1969fn chunk_contiguous_vec(arena: Vec<u8>, chunk_size: usize) -> Vec<FixedLenByteArray> {
1970    let mut values = Vec::with_capacity(arena.len() / chunk_size);
1971    let mut arena = Bytes::from(arena);
1972    while arena.len() >= chunk_size {
1973        let slice = arena.split_to(chunk_size);
1974        values.push(FixedLenByteArray::from(ByteArray::from(slice)));
1975    }
1976    values
1977}
1978
1979/// Hash a byte slice to a u64 for NDV tracking.
1980#[inline]
1981fn hash_bytes(bytes: &[u8]) -> u64 {
1982    twox_hash::XxHash64::oneshot(0, bytes)
1983}
1984
1985/// Returns the byte width of an Arrow dictionary key type, or 0 if unsupported.
1986fn arrow_key_byte_width(dt: &ArrowDataType) -> usize {
1987    match dt {
1988        ArrowDataType::Int8 | ArrowDataType::UInt8 => 1,
1989        ArrowDataType::Int16 | ArrowDataType::UInt16 => 2,
1990        ArrowDataType::Int32 | ArrowDataType::UInt32 => 4,
1991        ArrowDataType::Int64 | ArrowDataType::UInt64 => 8,
1992        _ => 0,
1993    }
1994}
1995
1996/// Returns the fixed byte width for primitive Arrow types, or `None` for variable-length types.
1997fn fixed_byte_width(dt: &ArrowDataType) -> Option<usize> {
1998    use ArrowDataType::*;
1999    match dt {
2000        Int8 | UInt8 => Some(1),
2001        Int16 | UInt16 | Float16 => Some(2),
2002        Int32 | UInt32 | Float32 | Date32 | Time32(_) | Decimal32(_, _) => Some(4),
2003        Int64
2004        | UInt64
2005        | Float64
2006        | Date64
2007        | Time64(_)
2008        | Timestamp(_, _)
2009        | Duration(_)
2010        | Decimal64(_, _) => Some(8),
2011        Interval(IntervalUnit::YearMonth) => Some(4),
2012        Interval(IntervalUnit::DayTime) => Some(8),
2013        Interval(IntervalUnit::MonthDayNano) => Some(16),
2014        Decimal128(_, _) => Some(16),
2015        Decimal256(_, _) => Some(32),
2016        _ => None,
2017    }
2018}
2019
2020/// Hash the non-null values in `array` (at `non_null_indices`) into `seen`.
2021///
2022/// Handles primitive, boolean, fixed-size-binary, and variable-length (Utf8/Binary)
2023/// arrays. Unsupported types are silently skipped, leaving `seen` unchanged for
2024/// those values (NDV is best-effort).
2025fn update_distinct_values_seen(
2026    array: &dyn arrow_array::Array,
2027    non_null_indices: &[usize],
2028    seen: &mut DistinctValuesSet,
2029) {
2030    let data = array.to_data();
2031    let offset = data.offset();
2032
2033    match array.data_type() {
2034        ArrowDataType::Boolean => {
2035            let arr = array
2036                .as_any()
2037                .downcast_ref::<arrow_array::BooleanArray>()
2038                .unwrap();
2039            for &row in non_null_indices {
2040                seen.insert(arr.value(row) as u64);
2041            }
2042        }
2043        ArrowDataType::Utf8 | ArrowDataType::Binary => {
2044            let offsets = data.buffers()[0].typed_data::<i32>();
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::LargeUtf8 | ArrowDataType::LargeBinary => {
2053            let offsets = data.buffers()[0].typed_data::<i64>();
2054            let values = data.buffers()[1].as_slice();
2055            for &row in non_null_indices {
2056                let start = offsets[offset + row] as usize;
2057                let end = offsets[offset + row + 1] as usize;
2058                seen.insert(hash_bytes(&values[start..end]));
2059            }
2060        }
2061        ArrowDataType::FixedSizeBinary(byte_width) => {
2062            let byte_width = *byte_width as usize;
2063            let buffer = data.buffers()[0].as_slice();
2064            for &row in non_null_indices {
2065                let start = (offset + row) * byte_width;
2066                seen.insert(hash_bytes(&buffer[start..start + byte_width]));
2067            }
2068        }
2069        data_type => {
2070            if let Some(width) = fixed_byte_width(data_type) {
2071                let buffer = data.buffers()[0].as_slice();
2072                for &row in non_null_indices {
2073                    let pos = (offset + row) * width;
2074                    seen.insert(hash_bytes(&buffer[pos..pos + width]));
2075                }
2076            }
2077            // Utf8View, BinaryView, nested types: skip
2078        }
2079    }
2080}
2081
2082#[cfg(test)]
2083mod tests {
2084    use super::*;
2085    use std::cmp::Ordering;
2086    use std::collections::HashMap;
2087
2088    use std::fs::File;
2089
2090    use crate::arrow::arrow_reader::{ParquetRecordBatchReader, ParquetRecordBatchReaderBuilder};
2091    use crate::arrow::{ARROW_SCHEMA_META_KEY, PARQUET_FIELD_ID_META_KEY};
2092    use crate::column::page::{Page, PageReader};
2093    use crate::file::metadata::thrift::PageHeader;
2094    use crate::file::page_index::column_index::ColumnIndexMetaData;
2095    use crate::file::reader::SerializedPageReader;
2096    use crate::parquet_thrift::{ReadThrift, ThriftSliceInputProtocol};
2097    use crate::schema::types::ColumnPath;
2098    use arrow::datatypes::ToByteSlice;
2099    use arrow::datatypes::{DataType, Schema};
2100    use arrow::error::Result as ArrowResult;
2101    use arrow::util::data_gen::create_random_array;
2102    use arrow::util::pretty::pretty_format_batches;
2103    use arrow::{array::*, buffer::Buffer};
2104    use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano, NullBuffer, OffsetBuffer, i256};
2105    use arrow_schema::Fields;
2106    use half::f16;
2107    use num_traits::{FromPrimitive, ToPrimitive};
2108    use tempfile::tempfile;
2109
2110    use crate::basic::Encoding;
2111    use crate::data_type::AsBytes;
2112    use crate::file::metadata::{ColumnChunkMetaData, ParquetMetaData, ParquetMetaDataReader};
2113    use crate::file::properties::{
2114        BloomFilterPosition, EnabledStatistics, ReaderProperties, WriterVersion,
2115    };
2116    use crate::file::serialized_reader::ReadOptionsBuilder;
2117    use crate::file::{
2118        reader::{FileReader, SerializedFileReader},
2119        statistics::Statistics,
2120    };
2121
2122    /// A [`PageStore`] that allocates *sparse, non-contiguous* handles and keeps
2123    /// blobs in a `HashMap` — nothing like the default `Vec<Bytes>`. Used to
2124    /// prove the writer relies only on the opaque-handle contract and never on
2125    /// handles being dense `Vec` indices. Records how many blobs were stored.
2126    #[derive(Debug, Default)]
2127    struct RecordingPageStore {
2128        next: u64,
2129        blobs: HashMap<u64, Bytes>,
2130        puts: Arc<std::sync::atomic::AtomicUsize>,
2131    }
2132
2133    impl PageStore for RecordingPageStore {
2134        fn put(&mut self, value: Bytes) -> Result<PageKey> {
2135            // Deliberately non-sequential, never-zero handles.
2136            let id = 100 + self.next * 7;
2137            self.next += 1;
2138            self.puts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2139            self.blobs.insert(id, value);
2140            Ok(PageKey::new(id))
2141        }
2142
2143        fn take(&mut self, key: PageKey) -> Result<Bytes> {
2144            self.blobs
2145                .remove(&key.get())
2146                .ok_or_else(|| ParquetError::General(format!("missing key {}", key.get())))
2147        }
2148    }
2149
2150    #[derive(Debug)]
2151    struct RecordingPageStoreFactory {
2152        puts: Arc<std::sync::atomic::AtomicUsize>,
2153    }
2154
2155    impl PageStoreFactory for RecordingPageStoreFactory {
2156        fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2157            Ok(Box::new(RecordingPageStore {
2158                puts: self.puts.clone(),
2159                ..Default::default()
2160            }))
2161        }
2162    }
2163
2164    /// A custom [`PageStore`] must produce byte-identical files to the in-memory
2165    /// default, across dictionary and non-dictionary columns and multiple row
2166    /// groups (so multiple store instances are exercised).
2167    #[test]
2168    fn custom_page_store_is_byte_identical_to_default() {
2169        let schema = Arc::new(Schema::new(vec![
2170            Field::new("i", DataType::Int32, true),
2171            // A low-cardinality string column to exercise the dictionary path.
2172            Field::new("s", DataType::Utf8, true),
2173        ]));
2174        let i = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5), Some(6)]);
2175        let s = StringArray::from(vec![
2176            Some("a"),
2177            Some("bb"),
2178            Some("a"),
2179            None,
2180            Some("bb"),
2181            Some("ccc"),
2182        ]);
2183        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(i), Arc::new(s)]).unwrap();
2184
2185        // Small row groups so multiple column chunks (hence multiple store
2186        // instances) are produced.
2187        let props = WriterProperties::builder()
2188            .set_max_row_group_row_count(Some(3))
2189            .build();
2190
2191        let write = |factory: Option<Arc<dyn PageStoreFactory>>| {
2192            let mut buffer = Vec::new();
2193            let mut opts = ArrowWriterOptions::new().with_properties(props.clone());
2194            if let Some(factory) = factory {
2195                opts = opts.with_page_store_factory(factory);
2196            }
2197            let mut writer =
2198                ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2199            writer.write(&batch).unwrap();
2200            writer.close().unwrap();
2201            buffer
2202        };
2203
2204        let default_bytes = write(None);
2205
2206        let puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2207        let custom_bytes = write(Some(Arc::new(RecordingPageStoreFactory {
2208            puts: puts.clone(),
2209        })));
2210
2211        assert!(
2212            puts.load(std::sync::atomic::Ordering::Relaxed) > 0,
2213            "custom PageStore was never written to"
2214        );
2215        assert_eq!(
2216            default_bytes, custom_bytes,
2217            "a custom PageStore must produce byte-identical output to the default"
2218        );
2219    }
2220
2221    /// A dictionary-encoded column written through the deferred-ordering Arrow
2222    /// path must round-trip correctly even with the offset index disabled, when
2223    /// only the chunk-level dictionary/data page offsets are rewritten (there is
2224    /// no offset index to rebuild). Spans multiple data pages so the
2225    /// dictionary-first reordering is exercised.
2226    #[test]
2227    #[cfg_attr(miri, ignore)] // Takes too long
2228    fn dictionary_column_round_trips_with_offset_index_disabled() {
2229        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2230
2231        // Low cardinality so the column stays dictionary-encoded; enough rows to
2232        // span several data pages within a single row group.
2233        let values: Vec<Option<i32>> = (0..50_000).map(|i| Some(i % 8)).collect();
2234        let array = Int32Array::from(values.clone());
2235        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2236
2237        let props = WriterProperties::builder()
2238            .set_offset_index_disabled(true)
2239            .set_data_page_row_count_limit(4096)
2240            .build();
2241        let opts = ArrowWriterOptions::new().with_properties(props);
2242
2243        let mut buffer = Vec::new();
2244        let mut writer =
2245            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2246        writer.write(&batch).unwrap();
2247        writer.close().unwrap();
2248
2249        let reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), values.len()).unwrap();
2250        let read: Vec<RecordBatch> = reader.collect::<ArrowResult<_>>().unwrap();
2251        let read_values: Vec<Option<i32>> = read
2252            .iter()
2253            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().iter())
2254            .collect();
2255        assert_eq!(read_values, values);
2256    }
2257
2258    /// The dictionary page is routed through the [`PageStore`] like any other
2259    /// page rather than held resident in memory, so a dictionary column chunk's
2260    /// *entire* serialized size — dictionary page included — passes through the
2261    /// store.
2262    #[test]
2263    fn dictionary_page_is_routed_through_the_store() {
2264        /// A store that sums the bytes handed to `put`.
2265        #[derive(Debug, Default)]
2266        struct SizeRecordingPageStore {
2267            blobs: Vec<Bytes>,
2268            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2269        }
2270        impl PageStore for SizeRecordingPageStore {
2271            fn put(&mut self, value: Bytes) -> Result<PageKey> {
2272                self.bytes_put
2273                    .fetch_add(value.len(), std::sync::atomic::Ordering::Relaxed);
2274                let key = PageKey::new(self.blobs.len() as u64);
2275                self.blobs.push(value);
2276                Ok(key)
2277            }
2278            fn take(&mut self, key: PageKey) -> Result<Bytes> {
2279                Ok(std::mem::take(&mut self.blobs[key.get() as usize]))
2280            }
2281        }
2282        #[derive(Debug)]
2283        struct Factory {
2284            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2285        }
2286        impl PageStoreFactory for Factory {
2287            fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2288                Ok(Box::new(SizeRecordingPageStore {
2289                    bytes_put: self.bytes_put.clone(),
2290                    ..Default::default()
2291                }))
2292            }
2293        }
2294
2295        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)]));
2296        // Low cardinality keeps the column dictionary-encoded with a real,
2297        // non-empty dictionary page.
2298        let values: Vec<&str> = (0..2048)
2299            .map(|i| ["alpha", "beta", "gamma", "delta"][i % 4])
2300            .collect();
2301        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(StringArray::from(values))])
2302            .unwrap();
2303
2304        let bytes_put = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2305        let opts = ArrowWriterOptions::new().with_page_store_factory(Arc::new(Factory {
2306            bytes_put: bytes_put.clone(),
2307        }));
2308
2309        // A single batch / single column means exactly one row group and one
2310        // store instance, so the bytes it saw map to one column chunk.
2311        let mut buffer = Vec::new();
2312        let mut writer =
2313            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2314        writer.write(&batch).unwrap();
2315        writer.close().unwrap();
2316
2317        let reader = SerializedFileReader::new(Bytes::from(buffer)).unwrap();
2318        let column = reader.metadata().row_group(0).column(0);
2319        assert!(
2320            column.dictionary_page_offset().is_some(),
2321            "expected the column to be dictionary-encoded"
2322        );
2323
2324        // The bytes the store was handed must account for the whole chunk,
2325        // dictionary page included. Holding the dictionary page apart from the
2326        // store would make this fall short by the dictionary page's size.
2327        assert_eq!(
2328            bytes_put.load(std::sync::atomic::Ordering::Relaxed) as i64,
2329            column.compressed_size(),
2330            "the dictionary page must pass through the store like any other page"
2331        );
2332    }
2333
2334    #[test]
2335    fn arrow_writer() {
2336        // define schema
2337        let schema = Schema::new(vec![
2338            Field::new("a", DataType::Int32, false),
2339            Field::new("b", DataType::Int32, true),
2340        ]);
2341
2342        // create some data
2343        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2344        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2345
2346        // build a record batch
2347        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)]).unwrap();
2348
2349        roundtrip(batch, Some(SMALL_SIZE / 2));
2350    }
2351
2352    fn get_bytes_after_close(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2353        let mut buffer = vec![];
2354
2355        let mut writer = ArrowWriter::try_new(&mut buffer, schema, None).unwrap();
2356        writer.write(expected_batch).unwrap();
2357        writer.close().unwrap();
2358
2359        buffer
2360    }
2361
2362    fn get_bytes_by_into_inner(schema: SchemaRef, expected_batch: &RecordBatch) -> Vec<u8> {
2363        let mut writer = ArrowWriter::try_new(Vec::new(), schema, None).unwrap();
2364        writer.write(expected_batch).unwrap();
2365        writer.into_inner().unwrap()
2366    }
2367
2368    #[test]
2369    fn roundtrip_bytes() {
2370        // define schema
2371        let schema = Arc::new(Schema::new(vec![
2372            Field::new("a", DataType::Int32, false),
2373            Field::new("b", DataType::Int32, true),
2374        ]));
2375
2376        // create some data
2377        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2378        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2379
2380        // build a record batch
2381        let expected_batch =
2382            RecordBatch::try_new(schema.clone(), vec![Arc::new(a), Arc::new(b)]).unwrap();
2383
2384        for buffer in [
2385            get_bytes_after_close(schema.clone(), &expected_batch),
2386            get_bytes_by_into_inner(schema, &expected_batch),
2387        ] {
2388            let cursor = Bytes::from(buffer);
2389            let mut record_batch_reader = ParquetRecordBatchReader::try_new(cursor, 1024).unwrap();
2390
2391            let actual_batch = record_batch_reader
2392                .next()
2393                .expect("No batch found")
2394                .expect("Unable to get batch");
2395
2396            assert_eq!(expected_batch.schema(), actual_batch.schema());
2397            assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
2398            assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
2399            for i in 0..expected_batch.num_columns() {
2400                let expected_data = expected_batch.column(i).to_data();
2401                let actual_data = actual_batch.column(i).to_data();
2402
2403                assert_eq!(expected_data, actual_data);
2404            }
2405        }
2406    }
2407
2408    #[test]
2409    #[cfg_attr(miri, ignore)] // Takes too long
2410    fn arrow_writer_non_null() {
2411        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2412        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2413
2414        RoundTripTest::new(Arc::new(a))
2415            .with_schema(Arc::new(schema))
2416            .run();
2417    }
2418
2419    #[test]
2420    #[cfg_attr(miri, ignore)] // Takes too long
2421    fn arrow_writer_list() {
2422        // define schema
2423        let schema = Schema::new(vec![Field::new(
2424            "a",
2425            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false))),
2426            true,
2427        )]);
2428
2429        // create some data
2430        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2431
2432        // Construct a buffer for value offsets, for the nested array:
2433        //  [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
2434        let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
2435
2436        // Construct a list array from the above two
2437        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
2438            DataType::Int32,
2439            false,
2440        ))))
2441        .len(5)
2442        .add_buffer(a_value_offsets)
2443        .add_child_data(a_values.into_data())
2444        .null_bit_buffer(Some(Buffer::from([0b00011011])))
2445        .build()
2446        .unwrap();
2447        let a = ListArray::from(a_list_data);
2448        assert_eq!(a.null_count(), 1);
2449
2450        RoundTripTest::new(Arc::new(a))
2451            .with_schema(Arc::new(schema))
2452            .run();
2453    }
2454
2455    #[test]
2456    #[cfg_attr(miri, ignore)] // Takes too long
2457    fn arrow_writer_list_non_null() {
2458        // define schema
2459        let schema = Schema::new(vec![Field::new(
2460            "a",
2461            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, false))),
2462            false,
2463        )]);
2464
2465        // create some data
2466        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2467
2468        // Construct a buffer for value offsets, for the nested array:
2469        //  [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
2470        let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
2471
2472        // Construct a list array from the above two
2473        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
2474            DataType::Int32,
2475            false,
2476        ))))
2477        .len(5)
2478        .add_buffer(a_value_offsets)
2479        .add_child_data(a_values.into_data())
2480        .build()
2481        .unwrap();
2482        let a = ListArray::from(a_list_data);
2483        assert_eq!(a.null_count(), 0);
2484
2485        RoundTripTest::new(Arc::new(a))
2486            .with_schema(Arc::new(schema))
2487            .run();
2488    }
2489
2490    #[test]
2491    #[cfg_attr(miri, ignore)] // Takes too long
2492    fn arrow_writer_list_view() {
2493        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2494        let schema = Schema::new(vec![Field::new(
2495            "a",
2496            DataType::ListView(list_field.clone()),
2497            true,
2498        )]);
2499
2500        //  [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
2501        let a = ListViewArray::new(
2502            list_field,
2503            vec![0, 1, 0, 3, 6].into(),
2504            vec![1, 2, 0, 3, 4].into(),
2505            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2506            Some(vec![true, true, false, true, true].into()),
2507        );
2508        assert_eq!(a.null_count(), 1);
2509
2510        RoundTripTest::new(Arc::new(a))
2511            .with_schema(Arc::new(schema))
2512            .run();
2513    }
2514
2515    #[test]
2516    #[cfg_attr(miri, ignore)] // Takes too long
2517    fn arrow_writer_list_view_non_null() {
2518        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2519        let schema = Schema::new(vec![Field::new(
2520            "a",
2521            DataType::ListView(list_field.clone()),
2522            false,
2523        )]);
2524
2525        //  [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
2526        let a = ListViewArray::new(
2527            list_field,
2528            vec![0, 1, 0, 3, 6].into(),
2529            vec![1, 2, 0, 3, 4].into(),
2530            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2531            None,
2532        );
2533        assert_eq!(a.null_count(), 0);
2534
2535        RoundTripTest::new(Arc::new(a))
2536            .with_schema(Arc::new(schema))
2537            .run();
2538    }
2539
2540    #[test]
2541    #[cfg_attr(miri, ignore)] // Takes too long
2542    fn arrow_writer_list_view_out_of_order() {
2543        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2544        let schema = Schema::new(vec![Field::new(
2545            "a",
2546            DataType::ListView(list_field.clone()),
2547            false,
2548        )]);
2549
2550        // [[1], [2, 3], [], [7, 8, 9, 10], [4, 5, 6]] - out of order offsets
2551        let a = ListViewArray::new(
2552            list_field,
2553            vec![0, 1, 0, 6, 3].into(),
2554            vec![1, 2, 0, 4, 3].into(),
2555            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2556            None,
2557        );
2558        assert_eq!(a.null_count(), 0);
2559
2560        RoundTripTest::new(Arc::new(a))
2561            .with_schema(Arc::new(schema))
2562            .run();
2563    }
2564
2565    #[test]
2566    #[cfg_attr(miri, ignore)] // Takes too long
2567    fn arrow_writer_large_list_view() {
2568        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
2569        let schema = Schema::new(vec![Field::new(
2570            "a",
2571            DataType::LargeListView(list_field.clone()),
2572            true,
2573        )]);
2574
2575        //  [[1], [2, 3], null, [4, 5, 6], [7, 8, 9, 10]]
2576        let a = LargeListViewArray::new(
2577            list_field,
2578            vec![0i64, 1, 0, 3, 6].into(),
2579            vec![1i64, 2, 0, 3, 4].into(),
2580            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10])),
2581            Some(vec![true, true, false, true, true].into()),
2582        );
2583        assert_eq!(a.null_count(), 1);
2584
2585        RoundTripTest::new(Arc::new(a))
2586            .with_schema(Arc::new(schema))
2587            .run();
2588    }
2589
2590    #[test]
2591    #[cfg_attr(miri, ignore)] // Takes too long
2592    fn arrow_writer_list_view_with_struct() {
2593        // Test ListView containing Struct: ListView<Struct<Int32, Utf8>>
2594        let struct_fields = Fields::from(vec![
2595            Field::new("id", DataType::Int32, false),
2596            Field::new("name", DataType::Utf8, false),
2597        ]);
2598        let struct_type = DataType::Struct(struct_fields.clone());
2599        let list_field = Arc::new(Field::new("item", struct_type.clone(), false));
2600
2601        let schema = Schema::new(vec![Field::new(
2602            "a",
2603            DataType::ListView(list_field.clone()),
2604            true,
2605        )]);
2606
2607        // Create struct values
2608        let id_array = Int32Array::from(vec![1, 2, 3, 4, 5]);
2609        let name_array = StringArray::from(vec!["a", "b", "c", "d", "e"]);
2610        let struct_array = StructArray::new(
2611            struct_fields,
2612            vec![Arc::new(id_array), Arc::new(name_array)],
2613            None,
2614        );
2615
2616        // Create ListView: [{1, "a"}, {2, "b"}], null, [{3, "c"}, {4, "d"}, {5, "e"}]
2617        let list_view = ListViewArray::new(
2618            list_field,
2619            vec![0, 2, 2].into(), // offsets
2620            vec![2, 0, 3].into(), // sizes
2621            Arc::new(struct_array),
2622            Some(vec![true, false, true].into()),
2623        );
2624        assert_eq!(list_view.null_count(), 1);
2625
2626        RoundTripTest::new(Arc::new(list_view))
2627            .with_schema(Arc::new(schema))
2628            .run();
2629    }
2630
2631    #[test]
2632    #[cfg_attr(miri, ignore)] // Takes too long
2633    fn arrow_writer_binary() {
2634        let raw_string_values = vec!["foo", "bar", "baz", "quux"];
2635        let raw_binary_values = [
2636            b"foo".to_vec(),
2637            b"bar".to_vec(),
2638            b"baz".to_vec(),
2639            b"quux".to_vec(),
2640        ];
2641        let raw_binary_value_refs = raw_binary_values
2642            .iter()
2643            .map(|x| x.as_slice())
2644            .collect::<Vec<_>>();
2645
2646        let string_values = StringArray::from(raw_string_values.clone());
2647        let binary_values = BinaryArray::from(raw_binary_value_refs);
2648        assert_eq!(string_values.null_count(), 0);
2649        assert_eq!(binary_values.null_count(), 0);
2650
2651        RoundTripTest::new(Arc::new(string_values)).run();
2652        RoundTripTest::new(Arc::new(binary_values)).run();
2653    }
2654
2655    #[test]
2656    #[cfg_attr(miri, ignore)] // Takes too long
2657    fn arrow_writer_binary_view() {
2658        let raw_string_values = vec!["foo", "bar", "large payload over 12 bytes", "lulu"];
2659        let raw_binary_values = vec![
2660            b"foo".to_vec(),
2661            b"bar".to_vec(),
2662            b"large payload over 12 bytes".to_vec(),
2663            b"lulu".to_vec(),
2664        ];
2665        let nullable_string_values =
2666            vec![Some("foo"), None, Some("large payload over 12 bytes"), None];
2667
2668        let string_view_values = StringViewArray::from(raw_string_values);
2669        let binary_view_values = BinaryViewArray::from_iter_values(raw_binary_values);
2670        let nullable_string_view_values = StringViewArray::from(nullable_string_values);
2671
2672        RoundTripTest::new(Arc::new(string_view_values)).run();
2673        RoundTripTest::new(Arc::new(binary_view_values)).run();
2674        RoundTripTest::new(Arc::new(nullable_string_view_values)).run();
2675    }
2676
2677    #[test]
2678    #[cfg_attr(miri, ignore)] // Takes too long
2679    fn arrow_writer_binary_view_long_value() {
2680        // There is special case validation for long values (greater than 128)
2681        // 128 encodes as 0x80 0x00 0x00 0x00 in little endian, which should
2682        // trigger the long-string UTF-8 validation branch in the plain decoder.
2683        let long = "a".repeat(128);
2684        let raw_string_values = vec!["foo", long.as_str(), "bar"];
2685        let raw_binary_values = vec![b"foo".to_vec(), long.as_bytes().to_vec(), b"bar".to_vec()];
2686
2687        let string_view_values: ArrayRef = Arc::new(StringViewArray::from(raw_string_values));
2688        let binary_view_values: ArrayRef =
2689            Arc::new(BinaryViewArray::from_iter_values(raw_binary_values));
2690
2691        RoundTripTest::new(Arc::clone(&string_view_values))
2692            .with_nullable(false)
2693            .run();
2694        RoundTripTest::new(Arc::clone(&binary_view_values))
2695            .with_nullable(false)
2696            .run();
2697    }
2698
2699    /// Test round-trip of Dictionary<UInt32, Utf8View> and
2700    /// Dictionary<UInt32, BinaryView> typed columns.
2701    #[test]
2702    fn arrow_writer_string_view_dictionary() {
2703        let raw_string_values = vec!["a", "b", "large payload over 12 bytes"];
2704        let raw_binary_values = vec![
2705            b"a".to_vec(),
2706            b"b".to_vec(),
2707            b"large payload over 12 bytes".to_vec(),
2708        ];
2709
2710        let keys = UInt32Array::from(vec![Some(0), None, Some(2), Some(1), None]);
2711
2712        let string_view_values = Arc::new(StringViewArray::from(raw_string_values));
2713        let string_dict: ArrayRef = Arc::new(
2714            DictionaryArray::<UInt32Type>::try_new(keys.clone(), string_view_values).unwrap(),
2715        );
2716
2717        let binary_view_values = Arc::new(BinaryViewArray::from_iter_values(raw_binary_values));
2718        let binary_dict: ArrayRef =
2719            Arc::new(DictionaryArray::<UInt32Type>::try_new(keys, binary_view_values).unwrap());
2720
2721        RoundTripTest::new(string_dict).run();
2722        RoundTripTest::new(binary_dict).run();
2723    }
2724
2725    fn get_decimal_batch(precision: u8, scale: i8) -> RecordBatch {
2726        let decimal_field = Field::new("a", DataType::Decimal128(precision, scale), false);
2727        let schema = Schema::new(vec![decimal_field]);
2728
2729        let decimal_values = vec![10_000, 50_000, 0, -100]
2730            .into_iter()
2731            .map(Some)
2732            .collect::<Decimal128Array>()
2733            .with_precision_and_scale(precision, scale)
2734            .unwrap();
2735
2736        RecordBatch::try_new(Arc::new(schema), vec![Arc::new(decimal_values)]).unwrap()
2737    }
2738
2739    #[test]
2740    fn arrow_writer_decimal() {
2741        // int32 to store the decimal value
2742        let batch_int32_decimal = get_decimal_batch(5, 2);
2743        roundtrip(batch_int32_decimal, Some(SMALL_SIZE / 2));
2744        // int64 to store the decimal value
2745        let batch_int64_decimal = get_decimal_batch(12, 2);
2746        roundtrip(batch_int64_decimal, Some(SMALL_SIZE / 2));
2747        // fixed_length_byte_array to store the decimal value
2748        let batch_fixed_len_byte_array_decimal = get_decimal_batch(30, 2);
2749        roundtrip(batch_fixed_len_byte_array_decimal, Some(SMALL_SIZE / 2));
2750    }
2751
2752    #[test]
2753    #[cfg_attr(miri, ignore)] // Takes too long
2754    fn arrow_writer_complex() {
2755        // define schema
2756        let struct_field_d = Arc::new(Field::new("d", DataType::Float64, true));
2757        let struct_field_f = Arc::new(Field::new("f", DataType::Float32, true));
2758        let struct_field_g = Arc::new(Field::new_list(
2759            "g",
2760            Field::new_list_field(DataType::Int16, true),
2761            false,
2762        ));
2763        let struct_field_h = Arc::new(Field::new_list(
2764            "h",
2765            Field::new_list_field(DataType::Int16, false),
2766            true,
2767        ));
2768        let struct_field_e = Arc::new(Field::new_struct(
2769            "e",
2770            vec![
2771                struct_field_f.clone(),
2772                struct_field_g.clone(),
2773                struct_field_h.clone(),
2774            ],
2775            false,
2776        ));
2777        let schema = Schema::new(vec![
2778            Field::new("a", DataType::Int32, false),
2779            Field::new("b", DataType::Int32, true),
2780            Field::new_struct(
2781                "c",
2782                vec![struct_field_d.clone(), struct_field_e.clone()],
2783                false,
2784            ),
2785        ]);
2786
2787        // create some data
2788        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2789        let b = Int32Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2790        let d = Float64Array::from(vec![None, None, None, Some(1.0), None]);
2791        let f = Float32Array::from(vec![Some(0.0), None, Some(333.3), None, Some(5.25)]);
2792
2793        let g_value = Int16Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2794
2795        // Construct a buffer for value offsets, for the nested array:
2796        //  [[1], [2, 3], [], [4, 5, 6], [7, 8, 9, 10]]
2797        let g_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
2798
2799        // Construct a list array from the above two
2800        let g_list_data = ArrayData::builder(struct_field_g.data_type().clone())
2801            .len(5)
2802            .add_buffer(g_value_offsets.clone())
2803            .add_child_data(g_value.to_data())
2804            .build()
2805            .unwrap();
2806        let g = ListArray::from(g_list_data);
2807        // The difference between g and h is that h has a null bitmap
2808        let h_list_data = ArrayData::builder(struct_field_h.data_type().clone())
2809            .len(5)
2810            .add_buffer(g_value_offsets)
2811            .add_child_data(g_value.to_data())
2812            .null_bit_buffer(Some(Buffer::from([0b00011011])))
2813            .build()
2814            .unwrap();
2815        let h = ListArray::from(h_list_data);
2816
2817        let e = StructArray::from(vec![
2818            (struct_field_f, Arc::new(f) as ArrayRef),
2819            (struct_field_g, Arc::new(g) as ArrayRef),
2820            (struct_field_h, Arc::new(h) as ArrayRef),
2821        ]);
2822
2823        let c = StructArray::from(vec![
2824            (struct_field_d, Arc::new(d) as ArrayRef),
2825            (struct_field_e, Arc::new(e) as ArrayRef),
2826        ]);
2827
2828        // build a record batch
2829        let batch = RecordBatch::try_new(
2830            Arc::new(schema),
2831            vec![Arc::new(a), Arc::new(b), Arc::new(c)],
2832        )
2833        .unwrap();
2834
2835        roundtrip(batch.clone(), Some(SMALL_SIZE / 2));
2836        roundtrip(batch, Some(SMALL_SIZE / 3));
2837    }
2838
2839    #[test]
2840    fn arrow_writer_complex_mixed() {
2841        // This test was added while investigating https://github.com/apache/arrow-rs/issues/244.
2842        // It was subsequently fixed while investigating https://github.com/apache/arrow-rs/issues/245.
2843
2844        // define schema
2845        let offset_field = Arc::new(Field::new("offset", DataType::Int32, false));
2846        let partition_field = Arc::new(Field::new("partition", DataType::Int64, true));
2847        let topic_field = Arc::new(Field::new("topic", DataType::Utf8, true));
2848        let schema = Schema::new(vec![Field::new(
2849            "some_nested_object",
2850            DataType::Struct(Fields::from(vec![
2851                offset_field.clone(),
2852                partition_field.clone(),
2853                topic_field.clone(),
2854            ])),
2855            false,
2856        )]);
2857
2858        // create some data
2859        let offset = Int32Array::from(vec![1, 2, 3, 4, 5]);
2860        let partition = Int64Array::from(vec![Some(1), None, None, Some(4), Some(5)]);
2861        let topic = StringArray::from(vec![Some("A"), None, Some("A"), Some(""), None]);
2862
2863        let some_nested_object = StructArray::from(vec![
2864            (offset_field, Arc::new(offset) as ArrayRef),
2865            (partition_field, Arc::new(partition) as ArrayRef),
2866            (topic_field, Arc::new(topic) as ArrayRef),
2867        ]);
2868
2869        // build a record batch
2870        let batch =
2871            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(some_nested_object)]).unwrap();
2872
2873        roundtrip(batch, Some(SMALL_SIZE / 2));
2874    }
2875
2876    #[test]
2877    fn arrow_writer_map() {
2878        // Note: we are using the JSON Arrow reader for brevity
2879        let json_content = r#"
2880        {"stocks":{"long": "$AAA", "short": "$BBB"}}
2881        {"stocks":{"long": null, "long": "$CCC", "short": null}}
2882        {"stocks":{"hedged": "$YYY", "long": null, "short": "$D"}}
2883        "#;
2884        let entries_struct_type = DataType::Struct(Fields::from(vec![
2885            Field::new(Field::MAP_KEY_FIELD_DEFAULT_NAME, DataType::Utf8, false),
2886            Field::new(Field::MAP_VALUE_FIELD_DEFAULT_NAME, DataType::Utf8, true),
2887        ]));
2888        let stocks_field = Field::new(
2889            "stocks",
2890            DataType::Map(
2891                Arc::new(Field::new(
2892                    Field::MAP_ENTRIES_FIELD_DEFAULT_NAME,
2893                    entries_struct_type,
2894                    false,
2895                )),
2896                false,
2897            ),
2898            true,
2899        );
2900        let schema = Arc::new(Schema::new(vec![stocks_field]));
2901        let builder = arrow::json::ReaderBuilder::new(schema).with_batch_size(64);
2902        let mut reader = builder.build(std::io::Cursor::new(json_content)).unwrap();
2903
2904        let batch = reader.next().unwrap().unwrap();
2905        roundtrip(batch, None);
2906    }
2907
2908    #[test]
2909    fn arrow_writer_2_level_struct() {
2910        // tests writing <struct<struct<primitive>>
2911        let field_c = Field::new("c", DataType::Int32, true);
2912        let field_b = Field::new("b", DataType::Struct(vec![field_c].into()), true);
2913        let type_a = DataType::Struct(vec![field_b.clone()].into());
2914        let field_a = Field::new("a", type_a, true);
2915        let schema = Schema::new(vec![field_a.clone()]);
2916
2917        // create data
2918        let c = Int32Array::from(vec![Some(1), None, Some(3), None, None, Some(6)]);
2919        let b_data = ArrayDataBuilder::new(field_b.data_type().clone())
2920            .len(6)
2921            .null_bit_buffer(Some(Buffer::from([0b00100111])))
2922            .add_child_data(c.into_data())
2923            .build()
2924            .unwrap();
2925        let b = StructArray::from(b_data);
2926        let a_data = ArrayDataBuilder::new(field_a.data_type().clone())
2927            .len(6)
2928            .null_bit_buffer(Some(Buffer::from([0b00101111])))
2929            .add_child_data(b.into_data())
2930            .build()
2931            .unwrap();
2932        let a = StructArray::from(a_data);
2933
2934        assert_eq!(a.null_count(), 1);
2935        assert_eq!(a.column(0).null_count(), 2);
2936
2937        // build a racord batch
2938        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
2939
2940        roundtrip(batch, Some(SMALL_SIZE / 2));
2941    }
2942
2943    #[test]
2944    fn arrow_writer_2_level_struct_non_null() {
2945        // tests writing <struct<struct<primitive>>
2946        let field_c = Field::new("c", DataType::Int32, false);
2947        let type_b = DataType::Struct(vec![field_c].into());
2948        let field_b = Field::new("b", type_b.clone(), false);
2949        let type_a = DataType::Struct(vec![field_b].into());
2950        let field_a = Field::new("a", type_a.clone(), false);
2951        let schema = Schema::new(vec![field_a]);
2952
2953        // create data
2954        let c = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
2955        let b_data = ArrayDataBuilder::new(type_b)
2956            .len(6)
2957            .add_child_data(c.into_data())
2958            .build()
2959            .unwrap();
2960        let b = StructArray::from(b_data);
2961        let a_data = ArrayDataBuilder::new(type_a)
2962            .len(6)
2963            .add_child_data(b.into_data())
2964            .build()
2965            .unwrap();
2966        let a = StructArray::from(a_data);
2967
2968        assert_eq!(a.null_count(), 0);
2969        assert_eq!(a.column(0).null_count(), 0);
2970
2971        // build a racord batch
2972        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
2973
2974        roundtrip(batch, Some(SMALL_SIZE / 2));
2975    }
2976
2977    #[test]
2978    fn arrow_writer_2_level_struct_mixed_null() {
2979        // tests writing <struct<struct<primitive>>
2980        let field_c = Field::new("c", DataType::Int32, false);
2981        let type_b = DataType::Struct(vec![field_c].into());
2982        let field_b = Field::new("b", type_b.clone(), true);
2983        let type_a = DataType::Struct(vec![field_b].into());
2984        let field_a = Field::new("a", type_a.clone(), false);
2985        let schema = Schema::new(vec![field_a]);
2986
2987        // create data
2988        let c = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
2989        let b_data = ArrayDataBuilder::new(type_b)
2990            .len(6)
2991            .null_bit_buffer(Some(Buffer::from([0b00100111])))
2992            .add_child_data(c.into_data())
2993            .build()
2994            .unwrap();
2995        let b = StructArray::from(b_data);
2996        // a intentionally has no null buffer, to test that this is handled correctly
2997        let a_data = ArrayDataBuilder::new(type_a)
2998            .len(6)
2999            .add_child_data(b.into_data())
3000            .build()
3001            .unwrap();
3002        let a = StructArray::from(a_data);
3003
3004        assert_eq!(a.null_count(), 0);
3005        assert_eq!(a.column(0).null_count(), 2);
3006
3007        // build a racord batch
3008        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
3009
3010        roundtrip(batch, Some(SMALL_SIZE / 2));
3011    }
3012
3013    #[test]
3014    fn arrow_writer_2_level_struct_mixed_null_2() {
3015        // tests writing <struct<struct<primitive>>, where the primitive columns are non-null.
3016        let field_c = Field::new("c", DataType::Int32, false);
3017        let field_d = Field::new("d", DataType::FixedSizeBinary(4), false);
3018        let field_e = Field::new(
3019            "e",
3020            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
3021            false,
3022        );
3023
3024        let field_b = Field::new(
3025            "b",
3026            DataType::Struct(vec![field_c, field_d, field_e].into()),
3027            false,
3028        );
3029        let type_a = DataType::Struct(vec![field_b.clone()].into());
3030        let field_a = Field::new("a", type_a, true);
3031        let schema = Schema::new(vec![field_a.clone()]);
3032
3033        // create data
3034        let c = Int32Array::from_iter_values(0..6);
3035        let d = FixedSizeBinaryArray::try_from_iter(
3036            ["aaaa", "bbbb", "cccc", "dddd", "eeee", "ffff"].into_iter(),
3037        )
3038        .expect("four byte values");
3039        let e = Int32DictionaryArray::from_iter(["one", "two", "three", "four", "five", "one"]);
3040        let b_data = ArrayDataBuilder::new(field_b.data_type().clone())
3041            .len(6)
3042            .add_child_data(c.into_data())
3043            .add_child_data(d.into_data())
3044            .add_child_data(e.into_data())
3045            .build()
3046            .unwrap();
3047        let b = StructArray::from(b_data);
3048        let a_data = ArrayDataBuilder::new(field_a.data_type().clone())
3049            .len(6)
3050            .null_bit_buffer(Some(Buffer::from([0b00100101])))
3051            .add_child_data(b.into_data())
3052            .build()
3053            .unwrap();
3054        let a = StructArray::from(a_data);
3055
3056        assert_eq!(a.null_count(), 3);
3057        assert_eq!(a.column(0).null_count(), 0);
3058
3059        // build a record batch
3060        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
3061
3062        roundtrip(batch, Some(SMALL_SIZE / 2));
3063    }
3064
3065    #[test]
3066    fn test_fixed_size_binary_in_dict() {
3067        fn test_fixed_size_binary_in_dict_inner<K>()
3068        where
3069            K: ArrowDictionaryKeyType,
3070            K::Native: FromPrimitive + ToPrimitive + TryFrom<u8>,
3071            <<K as arrow_array::ArrowPrimitiveType>::Native as TryFrom<u8>>::Error: std::fmt::Debug,
3072        {
3073            let field = Field::new(
3074                "a",
3075                DataType::Dictionary(
3076                    Box::new(K::DATA_TYPE),
3077                    Box::new(DataType::FixedSizeBinary(4)),
3078                ),
3079                false,
3080            );
3081            let schema = Schema::new(vec![field]);
3082
3083            let keys: Vec<K::Native> = vec![
3084                K::Native::try_from(0u8).unwrap(),
3085                K::Native::try_from(0u8).unwrap(),
3086                K::Native::try_from(1u8).unwrap(),
3087            ];
3088            let keys = PrimitiveArray::<K>::from_iter_values(keys);
3089            let values = FixedSizeBinaryArray::try_from_iter(
3090                vec![vec![0, 0, 0, 0], vec![1, 1, 1, 1]].into_iter(),
3091            )
3092            .unwrap();
3093
3094            let data = DictionaryArray::<K>::new(keys, Arc::new(values));
3095            let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(data)]).unwrap();
3096            roundtrip(batch, None);
3097        }
3098
3099        test_fixed_size_binary_in_dict_inner::<UInt8Type>();
3100        test_fixed_size_binary_in_dict_inner::<UInt16Type>();
3101        test_fixed_size_binary_in_dict_inner::<UInt32Type>();
3102        test_fixed_size_binary_in_dict_inner::<UInt16Type>();
3103        test_fixed_size_binary_in_dict_inner::<Int8Type>();
3104        test_fixed_size_binary_in_dict_inner::<Int16Type>();
3105        test_fixed_size_binary_in_dict_inner::<Int32Type>();
3106        test_fixed_size_binary_in_dict_inner::<Int64Type>();
3107    }
3108
3109    #[test]
3110    fn test_empty_dict() {
3111        let struct_fields = Fields::from(vec![Field::new(
3112            "dict",
3113            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
3114            false,
3115        )]);
3116
3117        let schema = Schema::new(vec![Field::new_struct(
3118            "struct",
3119            struct_fields.clone(),
3120            true,
3121        )]);
3122        let dictionary = Arc::new(DictionaryArray::new(
3123            Int32Array::new_null(5),
3124            Arc::new(StringArray::new_null(0)),
3125        ));
3126
3127        let s = StructArray::new(
3128            struct_fields,
3129            vec![dictionary],
3130            Some(NullBuffer::new_null(5)),
3131        );
3132
3133        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(s)]).unwrap();
3134        roundtrip(batch, None);
3135    }
3136    #[test]
3137    fn arrow_writer_page_size() {
3138        let schema = Arc::new(Schema::new(vec![Field::new("col", DataType::Utf8, false)]));
3139
3140        let mut builder = StringBuilder::with_capacity(100, 329 * 10_000);
3141
3142        // Generate an array of 10 unique 10 character string
3143        for i in 0..10 {
3144            let value = i
3145                .to_string()
3146                .repeat(10)
3147                .chars()
3148                .take(10)
3149                .collect::<String>();
3150
3151            builder.append_value(value);
3152        }
3153
3154        let array = Arc::new(builder.finish());
3155
3156        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
3157
3158        let file = tempfile::tempfile().unwrap();
3159
3160        // Set everything very low so we fallback to PLAIN encoding after the first row
3161        let props = WriterProperties::builder()
3162            .set_data_page_size_limit(1)
3163            .set_dictionary_page_size_limit(1)
3164            .set_write_batch_size(1)
3165            .build();
3166
3167        let mut writer =
3168            ArrowWriter::try_new(file.try_clone().unwrap(), batch.schema(), Some(props))
3169                .expect("Unable to write file");
3170        writer.write(&batch).unwrap();
3171        writer.close().unwrap();
3172
3173        let options = ReadOptionsBuilder::new().with_page_index().build();
3174        let reader =
3175            SerializedFileReader::new_with_options(file.try_clone().unwrap(), options).unwrap();
3176
3177        let column = reader.metadata().row_group(0).columns();
3178
3179        assert_eq!(column.len(), 1);
3180
3181        // We should write one row before falling back to PLAIN encoding so there should still be a
3182        // dictionary page.
3183        assert!(
3184            column[0].dictionary_page_offset().is_some(),
3185            "Expected a dictionary page"
3186        );
3187
3188        let page_index = reader
3189            .metadata()
3190            .page_index()
3191            .expect("page index should be present");
3192        let page_locations = page_index
3193            .page_locations(0, 0)
3194            .expect("page locations should exist");
3195
3196        // We should fallback to PLAIN encoding after the first row and our max page size is 1 bytes
3197        // so we expect one dictionary encoded page and then a page per row thereafter.
3198        assert_eq!(
3199            page_locations.len(),
3200            10,
3201            "Expected 10 pages but got {page_locations:#?}"
3202        );
3203    }
3204
3205    #[test]
3206    #[cfg_attr(miri, ignore)] // inline assembly is not supported
3207    fn arrow_writer_float_nans() {
3208        let f16_field = Field::new("a", DataType::Float16, false);
3209        let f32_field = Field::new("b", DataType::Float32, false);
3210        let f64_field = Field::new("c", DataType::Float64, false);
3211        let schema = Schema::new(vec![f16_field, f32_field, f64_field]);
3212
3213        let f16_values = (0..MEDIUM_SIZE)
3214            .map(|i| {
3215                Some(if i % 2 == 0 {
3216                    f16::NAN
3217                } else {
3218                    f16::from_f32(i as f32)
3219                })
3220            })
3221            .collect::<Float16Array>();
3222
3223        let f32_values = (0..MEDIUM_SIZE)
3224            .map(|i| Some(if i % 2 == 0 { f32::NAN } else { i as f32 }))
3225            .collect::<Float32Array>();
3226
3227        let f64_values = (0..MEDIUM_SIZE)
3228            .map(|i| Some(if i % 2 == 0 { f64::NAN } else { i as f64 }))
3229            .collect::<Float64Array>();
3230
3231        let batch = RecordBatch::try_new(
3232            Arc::new(schema),
3233            vec![
3234                Arc::new(f16_values),
3235                Arc::new(f32_values),
3236                Arc::new(f64_values),
3237            ],
3238        )
3239        .unwrap();
3240
3241        roundtrip(batch, None);
3242    }
3243
3244    const SMALL_SIZE: usize = 7;
3245    const MEDIUM_SIZE: usize = 63;
3246
3247    // Write the batch to parquet and read it back out, ensuring
3248    // that what comes out is the same as what was written in
3249    fn roundtrip(expected_batch: RecordBatch, max_row_group_size: Option<usize>) -> Vec<Bytes> {
3250        let mut files = vec![];
3251        for version in [WriterVersion::PARQUET_1_0, WriterVersion::PARQUET_2_0] {
3252            let mut props = WriterProperties::builder().set_writer_version(version);
3253
3254            if let Some(size) = max_row_group_size {
3255                props = props.set_max_row_group_row_count(Some(size))
3256            }
3257
3258            let props = props.build();
3259            files.push(roundtrip_opts(&expected_batch, props))
3260        }
3261        files
3262    }
3263
3264    // Round trip the specified record batch with the specified writer properties,
3265    // to an in-memory file, and validate the arrays using the specified function.
3266    // Returns the in-memory file.
3267    fn roundtrip_opts_with_array_validation<F>(
3268        expected_batch: &RecordBatch,
3269        props: WriterProperties,
3270        validate: F,
3271    ) -> Bytes
3272    where
3273        F: Fn(&ArrayData, &ArrayData),
3274    {
3275        let mut file = vec![];
3276
3277        let mut writer = ArrowWriter::try_new(&mut file, expected_batch.schema(), Some(props))
3278            .expect("Unable to write file");
3279        writer.write(expected_batch).unwrap();
3280        writer.close().unwrap();
3281
3282        let file = Bytes::from(file);
3283        let mut record_batch_reader =
3284            ParquetRecordBatchReader::try_new(file.clone(), 1024).unwrap();
3285
3286        let actual_batch = record_batch_reader
3287            .next()
3288            .expect("No batch found")
3289            .expect("Unable to get batch");
3290
3291        assert_eq!(expected_batch.schema(), actual_batch.schema());
3292        assert_eq!(expected_batch.num_columns(), actual_batch.num_columns());
3293        assert_eq!(expected_batch.num_rows(), actual_batch.num_rows());
3294        for i in 0..expected_batch.num_columns() {
3295            let expected_data = expected_batch.column(i).to_data();
3296            let actual_data = actual_batch.column(i).to_data();
3297            validate(&expected_data, &actual_data);
3298        }
3299
3300        file
3301    }
3302
3303    fn roundtrip_opts(expected_batch: &RecordBatch, props: WriterProperties) -> Bytes {
3304        roundtrip_opts_with_array_validation(expected_batch, props, |a, b| {
3305            a.validate_full().expect("valid expected data");
3306            b.validate_full().expect("valid actual data");
3307            assert_eq!(a, b)
3308        })
3309    }
3310
3311    /// Round trip testing fixture:
3312    ///
3313    /// Tests based on this fixture write data to parquet and then read it back.
3314    struct RoundTripTest {
3315        values: ArrayRef,
3316        /// Optionally supplied schema
3317        schema: Option<SchemaRef>,
3318        /// If the created schema should be nullable. Defaults to true. Ignored
3319        /// if schema is set to Some.
3320        nullable: bool,
3321        bloom_filter: bool,
3322        bloom_filter_ndv: Option<u64>,
3323        bloom_filter_position: BloomFilterPosition,
3324    }
3325
3326    impl RoundTripTest {
3327        /// Create a test for round tripping values with a nullable schema
3328        fn new(values: ArrayRef) -> Self {
3329            Self {
3330                values,
3331                schema: None,
3332                nullable: true,
3333                bloom_filter: false,
3334                bloom_filter_ndv: None,
3335                bloom_filter_position: BloomFilterPosition::AfterRowGroup,
3336            }
3337        }
3338
3339        /// Set the schema
3340        fn with_schema(mut self, schema: SchemaRef) -> Self {
3341            self.schema = Some(schema);
3342            self
3343        }
3344
3345        /// Set the nullable flag
3346        fn with_nullable(mut self, nullable: bool) -> Self {
3347            self.nullable = nullable;
3348            self
3349        }
3350
3351        /// Set bloom filter
3352        fn with_bloom_filter(mut self, bloom_filter: bool) -> Self {
3353            self.bloom_filter = bloom_filter;
3354            self
3355        }
3356
3357        /// Set bloom filter max ndv
3358        fn with_bloom_filter_ndv(mut self, bloom_filter_ndv: u64) -> Self {
3359            self.bloom_filter_ndv = Some(bloom_filter_ndv);
3360            self
3361        }
3362
3363        /// Set bloom filter position
3364        fn with_bloom_filter_position(
3365            mut self,
3366            bloom_filter_position: BloomFilterPosition,
3367        ) -> Self {
3368            self.bloom_filter_position = bloom_filter_position;
3369            self
3370        }
3371
3372        /// Run the test specified by the options, returning the encoded Parquet bytes
3373        fn run(self) -> Vec<Bytes> {
3374            let RoundTripTest {
3375                values,
3376                schema,
3377                nullable,
3378                bloom_filter,
3379                bloom_filter_ndv,
3380                bloom_filter_position,
3381            } = self;
3382
3383            let schema = schema.unwrap_or_else(|| {
3384                let data_type = values.data_type().clone();
3385                Arc::new(Schema::new(vec![Field::new("col", data_type, nullable)]))
3386            });
3387
3388            let encodings = match values.data_type() {
3389                DataType::Utf8 | DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary => {
3390                    vec![
3391                        Encoding::PLAIN,
3392                        Encoding::DELTA_BYTE_ARRAY,
3393                        Encoding::DELTA_LENGTH_BYTE_ARRAY,
3394                    ]
3395                }
3396                DataType::Int64
3397                | DataType::Int32
3398                | DataType::Int16
3399                | DataType::Int8
3400                | DataType::UInt64
3401                | DataType::UInt32
3402                | DataType::UInt16
3403                | DataType::UInt8 => vec![
3404                    Encoding::PLAIN,
3405                    Encoding::DELTA_BINARY_PACKED,
3406                    Encoding::BYTE_STREAM_SPLIT,
3407                ],
3408                DataType::Float32 | DataType::Float64 => {
3409                    vec![Encoding::PLAIN, Encoding::BYTE_STREAM_SPLIT]
3410                }
3411                _ => vec![Encoding::PLAIN],
3412            };
3413
3414            let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
3415
3416            let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
3417
3418            let mut files = vec![];
3419            for dictionary_size in [0, 1, 1024] {
3420                for encoding in &encodings {
3421                    for version in [WriterVersion::PARQUET_1_0, WriterVersion::PARQUET_2_0] {
3422                        for row_group_size in row_group_sizes {
3423                            let mut builder = WriterProperties::builder()
3424                                .set_writer_version(version)
3425                                .set_max_row_group_row_count(Some(row_group_size))
3426                                .set_dictionary_enabled(dictionary_size != 0)
3427                                .set_dictionary_page_size_limit(dictionary_size.max(1))
3428                                .set_encoding(*encoding)
3429                                .set_bloom_filter_enabled(bloom_filter)
3430                                .set_bloom_filter_position(bloom_filter_position);
3431                            if let Some(ndv) = bloom_filter_ndv {
3432                                builder = builder.set_bloom_filter_max_ndv(ndv);
3433                            }
3434                            let props = builder.build();
3435
3436                            files.push(roundtrip_opts(&expected_batch, props))
3437                        }
3438                    }
3439                }
3440            }
3441            files
3442        }
3443    }
3444
3445    fn values_required<A, I>(iter: I) -> Vec<Bytes>
3446    where
3447        A: From<Vec<I::Item>> + Array + 'static,
3448        I: IntoIterator,
3449    {
3450        let raw_values: Vec<_> = iter.into_iter().collect();
3451        let values = Arc::new(A::from(raw_values));
3452        RoundTripTest::new(values).with_nullable(false).run()
3453    }
3454
3455    fn values_optional<A, I>(iter: I) -> Vec<Bytes>
3456    where
3457        A: From<Vec<Option<I::Item>>> + Array + 'static,
3458        I: IntoIterator,
3459    {
3460        let optional_raw_values: Vec<_> = iter
3461            .into_iter()
3462            .enumerate()
3463            .map(|(i, v)| if i % 2 == 0 { None } else { Some(v) })
3464            .collect();
3465        let optional_values = Arc::new(A::from(optional_raw_values));
3466        RoundTripTest::new(optional_values).run()
3467    }
3468
3469    fn required_and_optional<A, I>(iter: I)
3470    where
3471        A: From<Vec<I::Item>> + From<Vec<Option<I::Item>>> + Array + 'static,
3472        I: IntoIterator + Clone,
3473    {
3474        values_required::<A, I>(iter.clone());
3475        values_optional::<A, I>(iter);
3476    }
3477
3478    fn check_bloom_filter<T: AsBytes>(
3479        files: Vec<Bytes>,
3480        file_column: String,
3481        positive_values: Vec<T>,
3482        negative_values: Vec<T>,
3483    ) {
3484        files.into_iter().take(1).for_each(|file| {
3485            let file_reader = SerializedFileReader::new_with_options(
3486                file,
3487                ReadOptionsBuilder::new()
3488                    .with_reader_properties(
3489                        ReaderProperties::builder()
3490                            .set_read_bloom_filter(true)
3491                            .build(),
3492                    )
3493                    .build(),
3494            )
3495            .expect("Unable to open file as Parquet");
3496            let metadata = file_reader.metadata();
3497
3498            // Gets bloom filters from all row groups.
3499            let mut bloom_filters: Vec<_> = vec![];
3500            for (ri, row_group) in metadata.row_groups().iter().enumerate() {
3501                if let Some((column_index, _)) = row_group
3502                    .columns()
3503                    .iter()
3504                    .enumerate()
3505                    .find(|(_, column)| column.column_path().string() == file_column)
3506                {
3507                    let row_group_reader = file_reader
3508                        .get_row_group(ri)
3509                        .expect("Unable to read row group");
3510                    if let Some(sbbf) = row_group_reader.get_column_bloom_filter(column_index) {
3511                        bloom_filters.push(sbbf.clone());
3512                    } else {
3513                        panic!("No bloom filter for column named {file_column} found");
3514                    }
3515                } else {
3516                    panic!("No column named {file_column} found");
3517                }
3518            }
3519
3520            positive_values.iter().for_each(|value| {
3521                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
3522                assert!(
3523                    found.is_some(),
3524                    "{}",
3525                    format!("Value {:?} should be in bloom filter", value.as_bytes())
3526                );
3527            });
3528
3529            negative_values.iter().for_each(|value| {
3530                let found = bloom_filters.iter().find(|sbbf| sbbf.check(value));
3531                assert!(
3532                    found.is_none(),
3533                    "{}",
3534                    format!("Value {:?} should not be in bloom filter", value.as_bytes())
3535                );
3536            });
3537        });
3538    }
3539
3540    #[test]
3541    #[cfg_attr(miri, ignore)] // Takes too long
3542    fn all_null_primitive_single_column() {
3543        let values = Arc::new(Int32Array::from(vec![None; SMALL_SIZE]));
3544        RoundTripTest::new(values).run();
3545    }
3546    #[test]
3547    #[cfg_attr(miri, ignore)] // Takes too long
3548    fn null_single_column() {
3549        let values = Arc::new(NullArray::new(SMALL_SIZE));
3550        RoundTripTest::new(values).run();
3551        // null arrays are always nullable, a test with non-nullable nulls fails
3552    }
3553
3554    #[test]
3555    #[cfg_attr(miri, ignore)] // Takes too long
3556    fn bool_single_column() {
3557        required_and_optional::<BooleanArray, _>(
3558            [true, false].iter().cycle().copied().take(SMALL_SIZE),
3559        );
3560    }
3561
3562    #[test]
3563    #[cfg_attr(miri, ignore)] // Takes too long
3564    fn bool_large_single_column() {
3565        let values = Arc::new(
3566            [None, Some(true), Some(false)]
3567                .iter()
3568                .cycle()
3569                .copied()
3570                .take(200_000)
3571                .collect::<BooleanArray>(),
3572        );
3573        let schema = Schema::new(vec![Field::new("col", values.data_type().clone(), true)]);
3574        let expected_batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
3575        let file = tempfile::tempfile().unwrap();
3576
3577        let mut writer =
3578            ArrowWriter::try_new(file.try_clone().unwrap(), expected_batch.schema(), None)
3579                .expect("Unable to write file");
3580        writer.write(&expected_batch).unwrap();
3581        writer.close().unwrap();
3582    }
3583
3584    #[test]
3585    fn check_page_offset_index_with_nan() {
3586        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
3587        let schema = Schema::new(vec![Field::new("col", DataType::Float64, true)]);
3588        let batch = RecordBatch::try_new(Arc::new(schema), vec![values]).unwrap();
3589
3590        let mut out = Vec::with_capacity(1024);
3591        let mut writer =
3592            ArrowWriter::try_new(&mut out, batch.schema(), None).expect("Unable to write file");
3593        writer.write(&batch).unwrap();
3594        let file_meta_data = writer.close().unwrap();
3595        for row_group in file_meta_data.row_groups() {
3596            for column in row_group.columns() {
3597                assert!(column.offset_index_offset().is_some());
3598                assert!(column.offset_index_length().is_some());
3599                assert!(column.column_index_offset().is_some());
3600                assert!(column.column_index_length().is_some());
3601            }
3602        }
3603        if let Some(page_index) = file_meta_data.page_index() {
3604            for rg in 0..file_meta_data.num_row_groups() {
3605                for col in 0..file_meta_data.row_group(rg).num_columns() {
3606                    let idx = page_index
3607                        .column_index(rg, col)
3608                        .expect("column index should exist");
3609                    assert!(idx.nan_counts().is_some());
3610                    let ColumnIndexMetaData::DOUBLE(float_idx) = idx else {
3611                        panic!("expected double statistics")
3612                    };
3613                    for i in 0..idx.num_pages() as usize {
3614                        assert_eq!(float_idx.nan_count(i), Some(10));
3615                        assert_eq!(
3616                            f64::NAN.total_cmp(float_idx.min_value(i).unwrap()),
3617                            Ordering::Equal
3618                        );
3619                        assert_eq!(
3620                            f64::NAN.total_cmp(float_idx.max_value(i).unwrap()),
3621                            Ordering::Equal
3622                        );
3623                    }
3624                }
3625            }
3626        } else {
3627            panic!("page index should be present");
3628        }
3629    }
3630
3631    #[test]
3632    fn check_page_offset_index_with_mixed_nan() {
3633        let schema = Arc::new(Schema::new(vec![Field::new(
3634            "col",
3635            DataType::Float64,
3636            true,
3637        )]));
3638
3639        let mut out = Vec::with_capacity(1024);
3640        let props = WriterProperties::builder()
3641            .set_data_page_row_count_limit(10)
3642            .build();
3643        let mut writer = ArrowWriter::try_new(&mut out, schema.clone(), Some(props))
3644            .expect("Unable to write file");
3645
3646        // write a page of all NaN (since batch min and max are NaN, global min/max are NaN)
3647        let values = Arc::new(Float64Array::from(vec![f64::NAN; 10]));
3648        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3649        writer.write(&batch).unwrap();
3650
3651        // write a page of all -NaN (batch min/max is -NaN, should update global min to -NaN)
3652        let values = Arc::new(Float64Array::from(vec![-f64::NAN; 10]));
3653        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3654        writer.write(&batch).unwrap();
3655
3656        // write a page of all 0 (non-NaN should override global min/max, now 0/0)
3657        let values = Arc::new(Float64Array::from(vec![0_f64; 10]));
3658        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3659        writer.write(&batch).unwrap();
3660
3661        // write a mixed page (should now have min -1, max 1)
3662        let values = Arc::new(Float64Array::from(vec![
3663            -1.0,
3664            0.0,
3665            f64::NAN,
3666            -f64::NAN,
3667            1.0,
3668        ]));
3669        let batch = RecordBatch::try_new(schema.clone(), vec![values]).unwrap();
3670        writer.write(&batch).unwrap();
3671
3672        let file_meta_data = writer.close().unwrap();
3673
3674        // check the column chunk stats are correct
3675        let col_stats = file_meta_data
3676            .row_group(0)
3677            .column(0)
3678            .statistics()
3679            .expect("missing column chunk statistics");
3680
3681        assert_eq!(col_stats.nan_count_opt(), Some(22));
3682        assert_eq!(col_stats.min_bytes_opt(), Some((-1.0f64).as_bytes()));
3683        assert_eq!(col_stats.max_bytes_opt(), Some(1.0f64.as_bytes()));
3684
3685        assert!(file_meta_data.page_index().is_some());
3686        let col_idx = &file_meta_data.page_index().unwrap().column_index(0, 0);
3687        assert_eq!(col_idx.as_ref().unwrap().num_pages(), 4);
3688
3689        // test each page
3690        let Some(ColumnIndexMetaData::DOUBLE(float_idx)) = col_idx else {
3691            panic!("expected double statistics")
3692        };
3693
3694        assert_eq!(float_idx.nan_counts, Some(vec![10, 10, 0, 2]));
3695        assert_eq!(
3696            f64::NAN.total_cmp(float_idx.min_value(0).unwrap()),
3697            Ordering::Equal
3698        );
3699        assert_eq!(
3700            f64::NAN.total_cmp(float_idx.max_value(0).unwrap()),
3701            Ordering::Equal
3702        );
3703        assert_eq!(
3704            (-f64::NAN).total_cmp(float_idx.min_value(1).unwrap()),
3705            Ordering::Equal
3706        );
3707        assert_eq!(
3708            (-f64::NAN).total_cmp(float_idx.max_value(1).unwrap()),
3709            Ordering::Equal
3710        );
3711        assert_eq!(float_idx.min_value(2), Some(&0.0));
3712        assert_eq!(float_idx.max_value(2), Some(&0.0));
3713        assert_eq!(float_idx.min_value(3), Some(&-1.0));
3714        assert_eq!(float_idx.max_value(3), Some(&1.0));
3715    }
3716
3717    #[test]
3718    #[cfg_attr(miri, ignore)] // Takes too long
3719    fn i8_single_column() {
3720        required_and_optional::<Int8Array, _>(0..SMALL_SIZE as i8);
3721    }
3722
3723    #[test]
3724    #[cfg_attr(miri, ignore)] // Takes too long
3725    fn i16_single_column() {
3726        required_and_optional::<Int16Array, _>(0..SMALL_SIZE as i16);
3727    }
3728
3729    #[test]
3730    #[cfg_attr(miri, ignore)] // Takes too long
3731    fn i32_single_column() {
3732        required_and_optional::<Int32Array, _>(0..SMALL_SIZE as i32);
3733    }
3734
3735    #[test]
3736    #[cfg_attr(miri, ignore)] // Takes too long
3737    fn i64_single_column() {
3738        required_and_optional::<Int64Array, _>(0..SMALL_SIZE as i64);
3739    }
3740
3741    #[test]
3742    #[cfg_attr(miri, ignore)] // Takes too long
3743    fn u8_single_column() {
3744        required_and_optional::<UInt8Array, _>(0..SMALL_SIZE as u8);
3745    }
3746
3747    #[test]
3748    #[cfg_attr(miri, ignore)] // Takes too long
3749    fn u16_single_column() {
3750        required_and_optional::<UInt16Array, _>(0..SMALL_SIZE as u16);
3751    }
3752
3753    #[test]
3754    #[cfg_attr(miri, ignore)] // Takes too long
3755    fn u32_single_column() {
3756        required_and_optional::<UInt32Array, _>(0..SMALL_SIZE as u32);
3757    }
3758
3759    #[test]
3760    #[cfg_attr(miri, ignore)] // Takes too long
3761    fn u64_single_column() {
3762        required_and_optional::<UInt64Array, _>(0..SMALL_SIZE as u64);
3763    }
3764
3765    #[test]
3766    #[cfg_attr(miri, ignore)] // Takes too long
3767    fn f32_single_column() {
3768        required_and_optional::<Float32Array, _>((0..SMALL_SIZE).map(|i| i as f32));
3769    }
3770
3771    #[test]
3772    #[cfg_attr(miri, ignore)] // Takes too long
3773    fn f64_single_column() {
3774        required_and_optional::<Float64Array, _>((0..SMALL_SIZE).map(|i| i as f64));
3775    }
3776
3777    // The timestamp array types don't implement From<Vec<T>> because they need the timezone
3778    // argument, and they also doesn't support building from a Vec<Option<T>>, so call
3779    // RoundTripTest manually instead of calling required_and_optional for these tests.
3780
3781    #[test]
3782    #[cfg_attr(miri, ignore)] // Takes too long
3783    fn timestamp_second_single_column() {
3784        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3785        let values = Arc::new(TimestampSecondArray::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_millisecond_single_column() {
3793        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3794        let values = Arc::new(TimestampMillisecondArray::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_microsecond_single_column() {
3802        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3803        let values = Arc::new(TimestampMicrosecondArray::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 timestamp_nanosecond_single_column() {
3811        let raw_values: Vec<_> = (0..SMALL_SIZE as i64).collect();
3812        let values = Arc::new(TimestampNanosecondArray::from(raw_values));
3813
3814        RoundTripTest::new(values).with_nullable(false).run();
3815    }
3816
3817    #[test]
3818    #[cfg_attr(miri, ignore)] // Takes too long
3819    fn date32_single_column() {
3820        required_and_optional::<Date32Array, _>(0..SMALL_SIZE as i32);
3821    }
3822
3823    #[test]
3824    #[cfg_attr(miri, ignore)] // Takes too long
3825    fn date64_single_column() {
3826        // Date64 must be a multiple of 86400000, see ARROW-10925
3827        required_and_optional::<Date64Array, _>(
3828            (0..(SMALL_SIZE as i64 * 86400000)).step_by(86400000),
3829        );
3830    }
3831
3832    #[test]
3833    #[cfg_attr(miri, ignore)] // Takes too long
3834    fn time32_second_single_column() {
3835        required_and_optional::<Time32SecondArray, _>(0..SMALL_SIZE as i32);
3836    }
3837
3838    #[test]
3839    #[cfg_attr(miri, ignore)] // Takes too long
3840    fn time32_millisecond_single_column() {
3841        required_and_optional::<Time32MillisecondArray, _>(0..SMALL_SIZE as i32);
3842    }
3843
3844    #[test]
3845    #[cfg_attr(miri, ignore)] // Takes too long
3846    fn time64_microsecond_single_column() {
3847        required_and_optional::<Time64MicrosecondArray, _>(0..SMALL_SIZE as i64);
3848    }
3849
3850    #[test]
3851    #[cfg_attr(miri, ignore)] // Takes too long
3852    fn time64_nanosecond_single_column() {
3853        required_and_optional::<Time64NanosecondArray, _>(0..SMALL_SIZE as i64);
3854    }
3855
3856    #[test]
3857    #[cfg_attr(miri, ignore)] // Takes too long
3858    fn duration_second_single_column() {
3859        required_and_optional::<DurationSecondArray, _>(0..SMALL_SIZE as i64);
3860    }
3861
3862    #[test]
3863    #[cfg_attr(miri, ignore)] // Takes too long
3864    fn duration_millisecond_single_column() {
3865        required_and_optional::<DurationMillisecondArray, _>(0..SMALL_SIZE as i64);
3866    }
3867
3868    #[test]
3869    #[cfg_attr(miri, ignore)] // Takes too long
3870    fn duration_microsecond_single_column() {
3871        required_and_optional::<DurationMicrosecondArray, _>(0..SMALL_SIZE as i64);
3872    }
3873
3874    #[test]
3875    #[cfg_attr(miri, ignore)] // Takes too long
3876    fn duration_nanosecond_single_column() {
3877        required_and_optional::<DurationNanosecondArray, _>(0..SMALL_SIZE as i64);
3878    }
3879
3880    #[test]
3881    #[cfg_attr(miri, ignore)] // Takes too long
3882    fn interval_year_month_single_column() {
3883        required_and_optional::<IntervalYearMonthArray, _>(0..SMALL_SIZE as i32);
3884    }
3885
3886    #[test]
3887    #[cfg_attr(miri, ignore)] // Takes too long
3888    fn interval_day_time_single_column() {
3889        required_and_optional::<IntervalDayTimeArray, _>(vec![
3890            IntervalDayTime::new(0, 1),
3891            IntervalDayTime::new(0, 3),
3892            IntervalDayTime::new(3, -2),
3893            IntervalDayTime::new(-200, 4),
3894        ]);
3895    }
3896
3897    #[test]
3898    #[should_panic(
3899        expected = "Attempting to write an Arrow interval type MonthDayNano to parquet that is not yet implemented"
3900    )]
3901    fn interval_month_day_nano_single_column() {
3902        required_and_optional::<IntervalMonthDayNanoArray, _>(vec![
3903            IntervalMonthDayNano::new(0, 1, 5),
3904            IntervalMonthDayNano::new(0, 3, 2),
3905            IntervalMonthDayNano::new(3, -2, -5),
3906            IntervalMonthDayNano::new(-200, 4, -1),
3907        ]);
3908    }
3909
3910    #[test]
3911    #[cfg_attr(miri, ignore)] // Takes too long
3912    fn binary_single_column() {
3913        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
3914        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
3915        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
3916
3917        // BinaryArrays can't be built from Vec<Option<&str>>, so only call `values_required`
3918        values_required::<BinaryArray, _>(many_vecs_iter);
3919    }
3920
3921    #[test]
3922    #[cfg_attr(miri, ignore)] // Takes too long
3923    fn binary_view_single_column() {
3924        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
3925        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
3926        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
3927
3928        // BinaryArrays can't be built from Vec<Option<&str>>, so only call `values_required`
3929        values_required::<BinaryViewArray, _>(many_vecs_iter);
3930    }
3931
3932    #[test]
3933    #[cfg_attr(miri, ignore)] // Takes too long
3934    fn i32_column_bloom_filter_at_end() {
3935        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3936        let files = RoundTripTest::new(array)
3937            .with_nullable(false)
3938            .with_bloom_filter(true)
3939            .with_bloom_filter_position(BloomFilterPosition::End)
3940            .run();
3941
3942        check_bloom_filter(
3943            files,
3944            "col".to_string(),
3945            (0..SMALL_SIZE as i32).collect(),
3946            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3947        );
3948    }
3949
3950    #[test]
3951    #[cfg_attr(miri, ignore)] // Takes too long
3952    fn i32_column_bloom_filter() {
3953        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3954        let files = RoundTripTest::new(array)
3955            .with_nullable(false)
3956            .with_bloom_filter(true)
3957            .run();
3958
3959        check_bloom_filter(
3960            files,
3961            "col".to_string(),
3962            (0..SMALL_SIZE as i32).collect(),
3963            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3964        );
3965    }
3966
3967    /// Test that bloom filter folding produces correct results even when
3968    /// the configured NDV differs significantly from actual NDV.
3969    /// A large NDV means a larger initial filter that gets folded down;
3970    /// a small NDV means a smaller initial filter.
3971    #[test]
3972    #[cfg_attr(miri, ignore)] // Takes too long
3973    fn i32_column_bloom_filter_fixed_ndv() {
3974        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
3975
3976        // NDV much larger than actual distinct values — tests folding a large filter down
3977        let files = RoundTripTest::new(array.clone())
3978            .with_nullable(false)
3979            .with_bloom_filter(true)
3980            .with_bloom_filter_ndv(1_000_000)
3981            .run();
3982
3983        check_bloom_filter(
3984            files,
3985            "col".to_string(),
3986            (0..SMALL_SIZE as i32).collect(),
3987            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
3988        );
3989
3990        // NDV smaller than actual distinct values — tests the underestimate path
3991        let files = RoundTripTest::new(array)
3992            .with_nullable(false)
3993            .with_bloom_filter(true)
3994            .with_bloom_filter_ndv(3)
3995            .run();
3996
3997        check_bloom_filter(
3998            files,
3999            "col".to_string(),
4000            (0..SMALL_SIZE as i32).collect(),
4001            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
4002        );
4003    }
4004
4005    #[test]
4006    #[cfg_attr(miri, ignore)] // Takes too long
4007    fn binary_column_bloom_filter() {
4008        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
4009        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
4010        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
4011
4012        let array = Arc::new(BinaryArray::from_iter_values(many_vecs_iter));
4013        let files = RoundTripTest::new(array)
4014            .with_nullable(false)
4015            .with_bloom_filter(true)
4016            .run();
4017
4018        check_bloom_filter(
4019            files,
4020            "col".to_string(),
4021            many_vecs,
4022            vec![vec![(SMALL_SIZE + 1) as u8]],
4023        );
4024    }
4025
4026    #[test]
4027    #[cfg_attr(miri, ignore)] // Takes too long
4028    fn empty_string_null_column_bloom_filter() {
4029        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4030        let raw_strs = raw_values.iter().map(|s| s.as_str());
4031
4032        let array = Arc::new(StringArray::from_iter_values(raw_strs));
4033        let files = RoundTripTest::new(array)
4034            .with_nullable(false)
4035            .with_bloom_filter(true)
4036            .run();
4037
4038        let optional_raw_values: Vec<_> = raw_values
4039            .iter()
4040            .enumerate()
4041            .filter_map(|(i, v)| if i % 2 == 0 { None } else { Some(v.as_str()) })
4042            .collect();
4043        // For null slots, empty string should not be in bloom filter.
4044        check_bloom_filter(files, "col".to_string(), optional_raw_values, vec![""]);
4045    }
4046
4047    #[test]
4048    #[cfg_attr(miri, ignore)] // Takes too long
4049    fn large_binary_single_column() {
4050        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
4051        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
4052        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
4053
4054        // LargeBinaryArrays can't be built from Vec<Option<&str>>, so only call `values_required`
4055        values_required::<LargeBinaryArray, _>(many_vecs_iter);
4056    }
4057
4058    #[test]
4059    #[cfg_attr(miri, ignore)] // Takes too long
4060    fn fixed_size_binary_single_column() {
4061        let mut builder = FixedSizeBinaryBuilder::new(4);
4062        builder.append_value(b"0123").unwrap();
4063        builder.append_null();
4064        builder.append_value(b"8910").unwrap();
4065        builder.append_value(b"1112").unwrap();
4066        let array = Arc::new(builder.finish());
4067
4068        RoundTripTest::new(array).run();
4069    }
4070
4071    #[test]
4072    #[cfg_attr(miri, ignore)] // Takes too long
4073    fn 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::<StringArray, _>(raw_strs);
4078    }
4079
4080    #[test]
4081    #[cfg_attr(miri, ignore)] // Takes too long
4082    fn large_string_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::<LargeStringArray, _>(raw_strs);
4087    }
4088
4089    #[test]
4090    #[cfg_attr(miri, ignore)] // Takes too long
4091    fn string_view_single_column() {
4092        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4093        let raw_strs = raw_values.iter().map(|s| s.as_str());
4094
4095        required_and_optional::<StringViewArray, _>(raw_strs);
4096    }
4097
4098    #[test]
4099    fn null_list_single_column() {
4100        let null_field = Field::new_list_field(DataType::Null, true);
4101        let list_field = Field::new("emptylist", DataType::List(Arc::new(null_field)), true);
4102
4103        let schema = Schema::new(vec![list_field]);
4104
4105        // Build [[], null, [null, null]]
4106        let a_values = NullArray::new(2);
4107        let a_value_offsets = arrow::buffer::Buffer::from([0, 0, 0, 2].to_byte_slice());
4108        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
4109            DataType::Null,
4110            true,
4111        ))))
4112        .len(3)
4113        .add_buffer(a_value_offsets)
4114        .null_bit_buffer(Some(Buffer::from([0b00000101])))
4115        .add_child_data(a_values.into_data())
4116        .build()
4117        .unwrap();
4118
4119        let a = ListArray::from(a_list_data);
4120
4121        assert!(a.is_valid(0));
4122        assert!(!a.is_valid(1));
4123        assert!(a.is_valid(2));
4124
4125        assert_eq!(a.value(0).len(), 0);
4126        assert_eq!(a.value(2).len(), 2);
4127        assert_eq!(a.value(2).logical_nulls().unwrap().null_count(), 2);
4128
4129        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
4130        roundtrip(batch, None);
4131    }
4132
4133    #[test]
4134    #[cfg_attr(miri, ignore)] // Takes too long
4135    fn list_single_column() {
4136        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4137        let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
4138        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
4139            DataType::Int32,
4140            false,
4141        ))))
4142        .len(5)
4143        .add_buffer(a_value_offsets)
4144        .null_bit_buffer(Some(Buffer::from([0b00011011])))
4145        .add_child_data(a_values.into_data())
4146        .build()
4147        .unwrap();
4148
4149        assert_eq!(a_list_data.null_count(), 1);
4150
4151        let a = ListArray::from(a_list_data);
4152        let values = Arc::new(a);
4153
4154        RoundTripTest::new(values).run();
4155    }
4156
4157    #[test]
4158    #[cfg_attr(miri, ignore)] // Takes too long
4159    fn large_list_single_column() {
4160        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4161        let a_value_offsets = arrow::buffer::Buffer::from([0i64, 1, 3, 3, 6, 10].to_byte_slice());
4162        let a_list_data = ArrayData::builder(DataType::LargeList(Arc::new(Field::new(
4163            "large_item",
4164            DataType::Int32,
4165            true,
4166        ))))
4167        .len(5)
4168        .add_buffer(a_value_offsets)
4169        .add_child_data(a_values.into_data())
4170        .null_bit_buffer(Some(Buffer::from([0b00011011])))
4171        .build()
4172        .unwrap();
4173
4174        // I think this setup is incorrect because this should pass
4175        assert_eq!(a_list_data.null_count(), 1);
4176
4177        let a = LargeListArray::from(a_list_data);
4178        let values = Arc::new(a);
4179
4180        RoundTripTest::new(values).run();
4181    }
4182
4183    #[test]
4184    #[cfg_attr(miri, ignore)] // Takes too long
4185    fn list_nested_nulls() {
4186        use arrow::datatypes::Int32Type;
4187        let data = vec![
4188            Some(vec![Some(1)]),
4189            Some(vec![Some(2), Some(3)]),
4190            None,
4191            Some(vec![Some(4), Some(5), None]),
4192            Some(vec![None]),
4193            Some(vec![Some(6), Some(7)]),
4194        ];
4195
4196        let list = ListArray::from_iter_primitive::<Int32Type, _, _>(data.clone());
4197        RoundTripTest::new(Arc::new(list)).run();
4198
4199        let list = LargeListArray::from_iter_primitive::<Int32Type, _, _>(data);
4200        RoundTripTest::new(Arc::new(list)).run();
4201    }
4202
4203    #[test]
4204    #[cfg_attr(miri, ignore)] // Takes too long
4205    fn list_utf8_view_selective_padding_roundtrip() {
4206        let item = Arc::new(Field::new_list_field(DataType::Utf8View, true));
4207        let mut builder = ListBuilder::new(StringViewBuilder::new()).with_field(item);
4208        builder.values().append_value("a");
4209        builder.values().append_null();
4210        builder.append(true);
4211        // The null parent list covers selective padding dropping values below
4212        // the list definition level while preserving the preceding item null.
4213        builder.append(false);
4214        // The long string covers the non-inlined Utf8View buffer path.
4215        builder.values().append_value("large payload over 12 bytes");
4216        builder.append(true);
4217
4218        RoundTripTest::new(Arc::new(builder.finish())).run();
4219    }
4220
4221    #[test]
4222    #[cfg_attr(miri, ignore)] // Takes too long
4223    fn struct_single_column() {
4224        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4225        let struct_field_a = Arc::new(Field::new("f", DataType::Int32, false));
4226        let s = StructArray::from(vec![(struct_field_a, Arc::new(a_values) as ArrayRef)]);
4227
4228        let values = Arc::new(s);
4229        RoundTripTest::new(values).with_nullable(false).run();
4230    }
4231
4232    #[test]
4233    fn list_and_map_coerced_names() {
4234        // Create map and list with non-Parquet naming
4235        let list_field =
4236            Field::new_list("my_list", Field::new("item", DataType::Int32, false), false);
4237        let map_field = Field::new_map(
4238            "my_map",
4239            "my_entries",
4240            Field::new("my_keys", DataType::Int32, false),
4241            Field::new("my_values", DataType::Int32, true),
4242            false,
4243            true,
4244        );
4245
4246        let list_array = create_random_array(&list_field, 100, 0.0, 0.0).unwrap();
4247        let map_array = create_random_array(&map_field, 100, 0.0, 0.0).unwrap();
4248
4249        let arrow_schema = Arc::new(Schema::new(vec![list_field, map_field]));
4250
4251        // Write data to Parquet but coerce names to match spec
4252        let props = Some(WriterProperties::builder().set_coerce_types(true).build());
4253        let file = tempfile::tempfile().unwrap();
4254        let mut writer =
4255            ArrowWriter::try_new(file.try_clone().unwrap(), arrow_schema.clone(), props).unwrap();
4256
4257        let batch = RecordBatch::try_new(arrow_schema, vec![list_array, map_array]).unwrap();
4258        writer.write(&batch).unwrap();
4259        let file_metadata = writer.close().unwrap();
4260
4261        let schema = file_metadata.file_metadata().schema();
4262        // Coerced name of "item" should be "element"
4263        let list_field = &schema.get_fields()[0].get_fields()[0];
4264        assert_eq!(list_field.get_fields()[0].name(), "element");
4265
4266        let map_field = &schema.get_fields()[1].get_fields()[0];
4267        // Coerced name of "entries" should be "key_value"
4268        assert_eq!(map_field.name(), "key_value");
4269        // Coerced name of "my_keys" should be "key"
4270        assert_eq!(map_field.get_fields()[0].name(), "key");
4271        // Coerced name of "my_values" should be "value"
4272        assert_eq!(map_field.get_fields()[1].name(), "value");
4273
4274        // Double check schema after reading from the file
4275        let reader = SerializedFileReader::new(file).unwrap();
4276        let file_schema = reader.metadata().file_metadata().schema();
4277        let fields = file_schema.get_fields();
4278        let list_field = &fields[0].get_fields()[0];
4279        assert_eq!(list_field.get_fields()[0].name(), "element");
4280        let map_field = &fields[1].get_fields()[0];
4281        assert_eq!(map_field.name(), "key_value");
4282        assert_eq!(map_field.get_fields()[0].name(), "key");
4283        assert_eq!(map_field.get_fields()[1].name(), "value");
4284    }
4285
4286    #[test]
4287    #[cfg_attr(miri, ignore)] // Takes too long
4288    fn fallback_flush_data_page() {
4289        //tests if the Fallback::flush_data_page clears all buffers correctly
4290        let raw_values: Vec<_> = (0..MEDIUM_SIZE).map(|i| i.to_string()).collect();
4291        let values = Arc::new(StringArray::from(raw_values));
4292        let encodings = vec![
4293            Encoding::DELTA_BYTE_ARRAY,
4294            Encoding::DELTA_LENGTH_BYTE_ARRAY,
4295        ];
4296        let data_type = values.data_type().clone();
4297        let schema = Arc::new(Schema::new(vec![Field::new("col", data_type, false)]));
4298        let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4299
4300        let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
4301        let data_page_size_limit: usize = 32;
4302        let write_batch_size: usize = 16;
4303
4304        for encoding in &encodings {
4305            for row_group_size in row_group_sizes {
4306                let props = WriterProperties::builder()
4307                    .set_writer_version(WriterVersion::PARQUET_2_0)
4308                    .set_max_row_group_row_count(Some(row_group_size))
4309                    .set_dictionary_enabled(false)
4310                    .set_encoding(*encoding)
4311                    .set_data_page_size_limit(data_page_size_limit)
4312                    .set_write_batch_size(write_batch_size)
4313                    .build();
4314
4315                roundtrip_opts_with_array_validation(&expected_batch, props, |a, b| {
4316                    let string_array_a = StringArray::from(a.clone());
4317                    let string_array_b = StringArray::from(b.clone());
4318                    let vec_a: Vec<&str> = string_array_a.iter().map(|v| v.unwrap()).collect();
4319                    let vec_b: Vec<&str> = string_array_b.iter().map(|v| v.unwrap()).collect();
4320                    assert_eq!(
4321                        vec_a, vec_b,
4322                        "failed for encoder: {encoding:?} and row_group_size: {row_group_size:?}"
4323                    );
4324                });
4325            }
4326        }
4327    }
4328
4329    #[test]
4330    #[cfg_attr(miri, ignore)] // Takes too long
4331    fn arrow_writer_string_dictionary() {
4332        // define schema
4333        #[expect(deprecated)]
4334        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4335            "dictionary",
4336            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4337            true,
4338            42,
4339            true,
4340        )]));
4341
4342        // create some data
4343        let d: Int32DictionaryArray = [Some("alpha"), None, Some("beta"), Some("alpha")]
4344            .iter()
4345            .copied()
4346            .collect();
4347
4348        // build a record batch
4349        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4350    }
4351
4352    #[test]
4353    fn arrow_writer_test_type_compatibility() {
4354        fn ensure_compatible_write<T1, T2>(array1: T1, array2: T2, expected_result: T1)
4355        where
4356            T1: Array + 'static,
4357            T2: Array + 'static,
4358        {
4359            let schema1 = Arc::new(Schema::new(vec![Field::new(
4360                "a",
4361                array1.data_type().clone(),
4362                false,
4363            )]));
4364
4365            let file = tempfile().unwrap();
4366            let mut writer =
4367                ArrowWriter::try_new(file.try_clone().unwrap(), schema1.clone(), None).unwrap();
4368
4369            let rb1 = RecordBatch::try_new(schema1.clone(), vec![Arc::new(array1)]).unwrap();
4370            writer.write(&rb1).unwrap();
4371
4372            let schema2 = Arc::new(Schema::new(vec![Field::new(
4373                "a",
4374                array2.data_type().clone(),
4375                false,
4376            )]));
4377            let rb2 = RecordBatch::try_new(schema2, vec![Arc::new(array2)]).unwrap();
4378            writer.write(&rb2).unwrap();
4379
4380            writer.close().unwrap();
4381
4382            let mut record_batch_reader =
4383                ParquetRecordBatchReader::try_new(file.try_clone().unwrap(), 1024).unwrap();
4384            let actual_batch = record_batch_reader.next().unwrap().unwrap();
4385
4386            let expected_batch =
4387                RecordBatch::try_new(schema1, vec![Arc::new(expected_result)]).unwrap();
4388            assert_eq!(actual_batch, expected_batch);
4389        }
4390
4391        // check compatibility between native and dictionaries
4392
4393        ensure_compatible_write(
4394            DictionaryArray::new(
4395                UInt8Array::from_iter_values(vec![0]),
4396                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4397            ),
4398            StringArray::from_iter_values(vec!["barquet"]),
4399            DictionaryArray::new(
4400                UInt8Array::from_iter_values(vec![0, 1]),
4401                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4402            ),
4403        );
4404
4405        ensure_compatible_write(
4406            StringArray::from_iter_values(vec!["parquet"]),
4407            DictionaryArray::new(
4408                UInt8Array::from_iter_values(vec![0]),
4409                Arc::new(StringArray::from_iter_values(vec!["barquet"])),
4410            ),
4411            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4412        );
4413
4414        // check compatibility between dictionaries with different key types
4415
4416        ensure_compatible_write(
4417            DictionaryArray::new(
4418                UInt8Array::from_iter_values(vec![0]),
4419                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4420            ),
4421            DictionaryArray::new(
4422                UInt16Array::from_iter_values(vec![0]),
4423                Arc::new(StringArray::from_iter_values(vec!["barquet"])),
4424            ),
4425            DictionaryArray::new(
4426                UInt8Array::from_iter_values(vec![0, 1]),
4427                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4428            ),
4429        );
4430
4431        // check compatibility between dictionaries with different value types
4432        ensure_compatible_write(
4433            DictionaryArray::new(
4434                UInt8Array::from_iter_values(vec![0]),
4435                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4436            ),
4437            DictionaryArray::new(
4438                UInt8Array::from_iter_values(vec![0]),
4439                Arc::new(LargeStringArray::from_iter_values(vec!["barquet"])),
4440            ),
4441            DictionaryArray::new(
4442                UInt8Array::from_iter_values(vec![0, 1]),
4443                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4444            ),
4445        );
4446
4447        // check compatibility between a dictionary and a native array with a different type
4448        ensure_compatible_write(
4449            DictionaryArray::new(
4450                UInt8Array::from_iter_values(vec![0]),
4451                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4452            ),
4453            LargeStringArray::from_iter_values(vec!["barquet"]),
4454            DictionaryArray::new(
4455                UInt8Array::from_iter_values(vec![0, 1]),
4456                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4457            ),
4458        );
4459
4460        // check compatibility for string types
4461
4462        ensure_compatible_write(
4463            StringArray::from_iter_values(vec!["parquet"]),
4464            LargeStringArray::from_iter_values(vec!["barquet"]),
4465            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4466        );
4467
4468        ensure_compatible_write(
4469            LargeStringArray::from_iter_values(vec!["parquet"]),
4470            StringArray::from_iter_values(vec!["barquet"]),
4471            LargeStringArray::from_iter_values(vec!["parquet", "barquet"]),
4472        );
4473
4474        ensure_compatible_write(
4475            StringArray::from_iter_values(vec!["parquet"]),
4476            StringViewArray::from_iter_values(vec!["barquet"]),
4477            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4478        );
4479
4480        ensure_compatible_write(
4481            StringViewArray::from_iter_values(vec!["parquet"]),
4482            StringArray::from_iter_values(vec!["barquet"]),
4483            StringViewArray::from_iter_values(vec!["parquet", "barquet"]),
4484        );
4485
4486        ensure_compatible_write(
4487            LargeStringArray::from_iter_values(vec!["parquet"]),
4488            StringViewArray::from_iter_values(vec!["barquet"]),
4489            LargeStringArray::from_iter_values(vec!["parquet", "barquet"]),
4490        );
4491
4492        ensure_compatible_write(
4493            StringViewArray::from_iter_values(vec!["parquet"]),
4494            LargeStringArray::from_iter_values(vec!["barquet"]),
4495            StringViewArray::from_iter_values(vec!["parquet", "barquet"]),
4496        );
4497
4498        // check compatibility for binary types
4499
4500        ensure_compatible_write(
4501            BinaryArray::from_iter_values(vec![b"parquet"]),
4502            LargeBinaryArray::from_iter_values(vec![b"barquet"]),
4503            BinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4504        );
4505
4506        ensure_compatible_write(
4507            LargeBinaryArray::from_iter_values(vec![b"parquet"]),
4508            BinaryArray::from_iter_values(vec![b"barquet"]),
4509            LargeBinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4510        );
4511
4512        ensure_compatible_write(
4513            BinaryArray::from_iter_values(vec![b"parquet"]),
4514            BinaryViewArray::from_iter_values(vec![b"barquet"]),
4515            BinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4516        );
4517
4518        ensure_compatible_write(
4519            BinaryViewArray::from_iter_values(vec![b"parquet"]),
4520            BinaryArray::from_iter_values(vec![b"barquet"]),
4521            BinaryViewArray::from_iter_values(vec![b"parquet", b"barquet"]),
4522        );
4523
4524        ensure_compatible_write(
4525            BinaryViewArray::from_iter_values(vec![b"parquet"]),
4526            LargeBinaryArray::from_iter_values(vec![b"barquet"]),
4527            BinaryViewArray::from_iter_values(vec![b"parquet", b"barquet"]),
4528        );
4529
4530        ensure_compatible_write(
4531            LargeBinaryArray::from_iter_values(vec![b"parquet"]),
4532            BinaryViewArray::from_iter_values(vec![b"barquet"]),
4533            LargeBinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4534        );
4535
4536        // check compatibility for list types
4537
4538        let list_field_metadata = HashMap::from_iter(vec![(
4539            PARQUET_FIELD_ID_META_KEY.to_string(),
4540            "1".to_string(),
4541        )]);
4542        let list_field = Field::new_list_field(DataType::Int32, false);
4543
4544        let values1 = Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4]));
4545        let offsets1 = OffsetBuffer::new(vec![0, 2, 5].into());
4546
4547        let values2 = Arc::new(Int32Array::from(vec![5, 6, 7, 8, 9]));
4548        let offsets2 = OffsetBuffer::new(vec![0, 3, 5].into());
4549
4550        let values_expected = Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4551        let offsets_expected = OffsetBuffer::new(vec![0, 2, 5, 8, 10].into());
4552
4553        ensure_compatible_write(
4554            // when the initial schema has the metadata ...
4555            ListArray::try_new(
4556                Arc::new(
4557                    list_field
4558                        .clone()
4559                        .with_metadata(list_field_metadata.clone()),
4560                ),
4561                offsets1,
4562                values1,
4563                None,
4564            )
4565            .unwrap(),
4566            // ... and some intermediate schema doesn't have the metadata
4567            ListArray::try_new(Arc::new(list_field.clone()), offsets2, values2, None).unwrap(),
4568            // ... the write will still go through, and the resulting schema will inherit the initial metadata
4569            ListArray::try_new(
4570                Arc::new(
4571                    list_field
4572                        .clone()
4573                        .with_metadata(list_field_metadata.clone()),
4574                ),
4575                offsets_expected,
4576                values_expected,
4577                None,
4578            )
4579            .unwrap(),
4580        );
4581    }
4582
4583    #[test]
4584    #[cfg_attr(miri, ignore)] // Takes too long
4585    fn arrow_writer_primitive_dictionary() {
4586        // define schema
4587        #[expect(deprecated)]
4588        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4589            "dictionary",
4590            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::UInt32)),
4591            true,
4592            42,
4593            true,
4594        )]));
4595
4596        // create some data
4597        let mut builder = PrimitiveDictionaryBuilder::<UInt8Type, UInt32Type>::new();
4598        builder.append(12345678).unwrap();
4599        builder.append_null();
4600        builder.append(22345678).unwrap();
4601        builder.append(12345678).unwrap();
4602        let d = builder.finish();
4603
4604        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4605    }
4606
4607    #[test]
4608    #[cfg_attr(miri, ignore)] // Takes too long
4609    fn arrow_writer_decimal32_dictionary() {
4610        let integers = vec![12345, 56789, 34567];
4611
4612        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4613
4614        let values = Decimal32Array::from(integers.clone())
4615            .with_precision_and_scale(5, 2)
4616            .unwrap();
4617
4618        let array = DictionaryArray::new(keys, Arc::new(values));
4619        RoundTripTest::new(Arc::new(array.clone())).run();
4620
4621        let values = Decimal32Array::from(integers)
4622            .with_precision_and_scale(9, 2)
4623            .unwrap();
4624
4625        let array = array.with_values(Arc::new(values));
4626        RoundTripTest::new(Arc::new(array)).run();
4627    }
4628
4629    #[test]
4630    #[cfg_attr(miri, ignore)] // Takes too long
4631    fn arrow_writer_decimal64_dictionary() {
4632        let integers = vec![12345, 56789, 34567];
4633
4634        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4635
4636        let values = Decimal64Array::from(integers.clone())
4637            .with_precision_and_scale(5, 2)
4638            .unwrap();
4639
4640        let array = DictionaryArray::new(keys, Arc::new(values));
4641        RoundTripTest::new(Arc::new(array.clone())).run();
4642
4643        let values = Decimal64Array::from(integers)
4644            .with_precision_and_scale(12, 2)
4645            .unwrap();
4646
4647        let array = array.with_values(Arc::new(values));
4648        RoundTripTest::new(Arc::new(array)).run();
4649    }
4650
4651    #[test]
4652    #[cfg_attr(miri, ignore)] // Takes too long
4653    fn arrow_writer_decimal128_dictionary() {
4654        let integers = vec![12345, 56789, 34567];
4655
4656        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4657
4658        let values = Decimal128Array::from(integers.clone())
4659            .with_precision_and_scale(5, 2)
4660            .unwrap();
4661
4662        let array = DictionaryArray::new(keys, Arc::new(values));
4663        RoundTripTest::new(Arc::new(array.clone())).run();
4664
4665        let values = Decimal128Array::from(integers)
4666            .with_precision_and_scale(12, 2)
4667            .unwrap();
4668
4669        let array = array.with_values(Arc::new(values));
4670        RoundTripTest::new(Arc::new(array)).run();
4671    }
4672
4673    #[test]
4674    #[cfg_attr(miri, ignore)] // Takes too long
4675    fn arrow_writer_decimal256_dictionary() {
4676        let integers = vec![
4677            i256::from_i128(12345),
4678            i256::from_i128(56789),
4679            i256::from_i128(34567),
4680        ];
4681
4682        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4683
4684        let values = Decimal256Array::from(integers.clone())
4685            .with_precision_and_scale(5, 2)
4686            .unwrap();
4687
4688        let array = DictionaryArray::new(keys, Arc::new(values));
4689        RoundTripTest::new(Arc::new(array.clone())).run();
4690
4691        let values = Decimal256Array::from(integers)
4692            .with_precision_and_scale(12, 2)
4693            .unwrap();
4694
4695        let array = array.with_values(Arc::new(values));
4696        RoundTripTest::new(Arc::new(array)).run();
4697    }
4698
4699    #[test]
4700    #[cfg_attr(miri, ignore)] // Takes too long
4701    fn arrow_writer_string_dictionary_unsigned_index() {
4702        // define schema
4703        #[expect(deprecated)]
4704        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4705            "dictionary",
4706            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
4707            true,
4708            42,
4709            true,
4710        )]));
4711
4712        // create some data
4713        let d: UInt8DictionaryArray = [Some("alpha"), None, Some("beta"), Some("alpha")]
4714            .iter()
4715            .copied()
4716            .collect();
4717
4718        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4719    }
4720
4721    #[test]
4722    #[cfg_attr(miri, ignore)] // Takes too long
4723    fn u32_min_max() {
4724        // check values roundtrip through parquet
4725        let src = [
4726            u32::MIN,
4727            1,
4728            (i32::MAX as u32) - 1,
4729            i32::MAX as u32,
4730            (i32::MAX as u32) + 1,
4731            u32::MAX - 1,
4732            u32::MAX,
4733        ];
4734        let values = Arc::new(UInt32Array::from_iter_values(src.iter().copied()));
4735        let files = RoundTripTest::new(values).with_nullable(false).run();
4736
4737        for file in files {
4738            // check statistics are valid
4739            let reader = SerializedFileReader::new(file).unwrap();
4740            let metadata = reader.metadata();
4741
4742            let mut row_offset = 0;
4743            for row_group in metadata.row_groups() {
4744                assert_eq!(row_group.num_columns(), 1);
4745                let column = row_group.column(0);
4746
4747                let num_values = column.num_values() as usize;
4748                let src_slice = &src[row_offset..row_offset + num_values];
4749                row_offset += column.num_values() as usize;
4750
4751                let stats = column.statistics().unwrap();
4752                if let Statistics::Int32(stats) = stats {
4753                    assert_eq!(
4754                        *stats.min_opt().unwrap() as u32,
4755                        *src_slice.iter().min().unwrap()
4756                    );
4757                    assert_eq!(
4758                        *stats.max_opt().unwrap() as u32,
4759                        *src_slice.iter().max().unwrap()
4760                    );
4761                } else {
4762                    panic!("Statistics::Int32 missing")
4763                }
4764            }
4765        }
4766    }
4767
4768    #[test]
4769    #[cfg_attr(miri, ignore)] // Takes too long
4770    fn u64_min_max() {
4771        // check values roundtrip through parquet
4772        let src = [
4773            u64::MIN,
4774            1,
4775            (i64::MAX as u64) - 1,
4776            i64::MAX as u64,
4777            (i64::MAX as u64) + 1,
4778            u64::MAX - 1,
4779            u64::MAX,
4780        ];
4781        let values = Arc::new(UInt64Array::from_iter_values(src.iter().copied()));
4782        let files = RoundTripTest::new(values).with_nullable(false).run();
4783
4784        for file in files {
4785            // check statistics are valid
4786            let reader = SerializedFileReader::new(file).unwrap();
4787            let metadata = reader.metadata();
4788
4789            let mut row_offset = 0;
4790            for row_group in metadata.row_groups() {
4791                assert_eq!(row_group.num_columns(), 1);
4792                let column = row_group.column(0);
4793
4794                let num_values = column.num_values() as usize;
4795                let src_slice = &src[row_offset..row_offset + num_values];
4796                row_offset += column.num_values() as usize;
4797
4798                let stats = column.statistics().unwrap();
4799                if let Statistics::Int64(stats) = stats {
4800                    assert_eq!(
4801                        *stats.min_opt().unwrap() as u64,
4802                        *src_slice.iter().min().unwrap()
4803                    );
4804                    assert_eq!(
4805                        *stats.max_opt().unwrap() as u64,
4806                        *src_slice.iter().max().unwrap()
4807                    );
4808                } else {
4809                    panic!("Statistics::Int64 missing")
4810                }
4811            }
4812        }
4813    }
4814
4815    #[test]
4816    #[cfg_attr(miri, ignore)] // Takes too long
4817    fn statistics_null_counts_only_nulls() {
4818        // check that null-count statistics for "only NULL"-columns are correct
4819        let values = Arc::new(UInt64Array::from(vec![None, None]));
4820        let files = RoundTripTest::new(values).run();
4821
4822        for file in files {
4823            // check statistics are valid
4824            let reader = SerializedFileReader::new(file).unwrap();
4825            let metadata = reader.metadata();
4826            assert_eq!(metadata.num_row_groups(), 1);
4827            let row_group = metadata.row_group(0);
4828            assert_eq!(row_group.num_columns(), 1);
4829            let column = row_group.column(0);
4830            let stats = column.statistics().unwrap();
4831            assert_eq!(stats.null_count_opt(), Some(2));
4832        }
4833    }
4834
4835    #[test]
4836    #[cfg_attr(miri, ignore)] // Takes too long
4837    fn test_list_of_struct_roundtrip() {
4838        // define schema
4839        let int_field = Field::new("a", DataType::Int32, true);
4840        let int_field2 = Field::new("b", DataType::Int32, true);
4841
4842        let int_builder = Int32Builder::with_capacity(10);
4843        let int_builder2 = Int32Builder::with_capacity(10);
4844
4845        let struct_builder = StructBuilder::new(
4846            vec![int_field, int_field2],
4847            vec![Box::new(int_builder), Box::new(int_builder2)],
4848        );
4849        let mut list_builder = ListBuilder::new(struct_builder);
4850
4851        // Construct the following array
4852        // [{a: 1, b: 2}], [], null, [null, null], [{a: null, b: 3}], [{a: 2, b: null}]
4853
4854        // [{a: 1, b: 2}]
4855        let values = list_builder.values();
4856        values
4857            .field_builder::<Int32Builder>(0)
4858            .unwrap()
4859            .append_value(1);
4860        values
4861            .field_builder::<Int32Builder>(1)
4862            .unwrap()
4863            .append_value(2);
4864        values.append(true);
4865        list_builder.append(true);
4866
4867        // []
4868        list_builder.append(true);
4869
4870        // null
4871        list_builder.append(false);
4872
4873        // [null, null]
4874        let values = list_builder.values();
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        values
4885            .field_builder::<Int32Builder>(0)
4886            .unwrap()
4887            .append_null();
4888        values
4889            .field_builder::<Int32Builder>(1)
4890            .unwrap()
4891            .append_null();
4892        values.append(false);
4893        list_builder.append(true);
4894
4895        // [{a: null, b: 3}]
4896        let values = list_builder.values();
4897        values
4898            .field_builder::<Int32Builder>(0)
4899            .unwrap()
4900            .append_null();
4901        values
4902            .field_builder::<Int32Builder>(1)
4903            .unwrap()
4904            .append_value(3);
4905        values.append(true);
4906        list_builder.append(true);
4907
4908        // [{a: 2, b: null}]
4909        let values = list_builder.values();
4910        values
4911            .field_builder::<Int32Builder>(0)
4912            .unwrap()
4913            .append_value(2);
4914        values
4915            .field_builder::<Int32Builder>(1)
4916            .unwrap()
4917            .append_null();
4918        values.append(true);
4919        list_builder.append(true);
4920
4921        let array = Arc::new(list_builder.finish());
4922
4923        RoundTripTest::new(array).run();
4924    }
4925
4926    fn row_group_sizes(metadata: &ParquetMetaData) -> Vec<i64> {
4927        metadata.row_groups().iter().map(|x| x.num_rows()).collect()
4928    }
4929
4930    #[test]
4931    fn test_aggregates_records() {
4932        let arrays = [
4933            Int32Array::from((0..100).collect::<Vec<_>>()),
4934            Int32Array::from((0..50).collect::<Vec<_>>()),
4935            Int32Array::from((200..500).collect::<Vec<_>>()),
4936        ];
4937
4938        let schema = Arc::new(Schema::new(vec![Field::new(
4939            "int",
4940            ArrowDataType::Int32,
4941            false,
4942        )]));
4943
4944        let file = tempfile::tempfile().unwrap();
4945
4946        let props = WriterProperties::builder()
4947            .set_max_row_group_row_count(Some(200))
4948            .build();
4949
4950        let mut writer =
4951            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
4952
4953        for array in arrays {
4954            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
4955            writer.write(&batch).unwrap();
4956        }
4957
4958        writer.close().unwrap();
4959
4960        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
4961        assert_eq!(&row_group_sizes(builder.metadata()), &[200, 200, 50]);
4962
4963        let batches = builder
4964            .with_batch_size(100)
4965            .build()
4966            .unwrap()
4967            .collect::<ArrowResult<Vec<_>>>()
4968            .unwrap();
4969
4970        assert_eq!(batches.len(), 5);
4971        assert!(batches.iter().all(|x| x.num_columns() == 1));
4972
4973        let batch_sizes: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
4974
4975        assert_eq!(&batch_sizes, &[100, 100, 100, 100, 50]);
4976
4977        let values: Vec<_> = batches
4978            .iter()
4979            .flat_map(|x| {
4980                x.column(0)
4981                    .as_any()
4982                    .downcast_ref::<Int32Array>()
4983                    .unwrap()
4984                    .values()
4985                    .iter()
4986                    .copied()
4987            })
4988            .collect();
4989
4990        let expected_values: Vec<_> = [0..100, 0..50, 200..500].into_iter().flatten().collect();
4991        assert_eq!(&values, &expected_values)
4992    }
4993
4994    #[test]
4995    fn complex_aggregate() {
4996        // Tests aggregating nested data
4997        let field_a = Arc::new(Field::new("leaf_a", DataType::Int32, false));
4998        let field_b = Arc::new(Field::new("leaf_b", DataType::Int32, true));
4999        let struct_a = Arc::new(Field::new(
5000            "struct_a",
5001            DataType::Struct(vec![field_a.clone(), field_b.clone()].into()),
5002            true,
5003        ));
5004
5005        let list_a = Arc::new(Field::new("list", DataType::List(struct_a), true));
5006        let struct_b = Arc::new(Field::new(
5007            "struct_b",
5008            DataType::Struct(vec![list_a.clone()].into()),
5009            false,
5010        ));
5011
5012        let schema = Arc::new(Schema::new(vec![struct_b]));
5013
5014        // create nested data
5015        let field_a_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
5016        let field_b_array =
5017            Int32Array::from_iter(vec![Some(1), None, Some(2), None, None, Some(6)]);
5018
5019        let struct_a_array = StructArray::from(vec![
5020            (field_a.clone(), Arc::new(field_a_array) as ArrayRef),
5021            (field_b.clone(), Arc::new(field_b_array) as ArrayRef),
5022        ]);
5023
5024        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
5025            .len(5)
5026            .add_buffer(Buffer::from_iter(vec![
5027                0_i32, 1_i32, 1_i32, 3_i32, 3_i32, 5_i32,
5028            ]))
5029            .null_bit_buffer(Some(Buffer::from_iter(vec![
5030                true, false, true, false, true,
5031            ])))
5032            .child_data(vec![struct_a_array.into_data()])
5033            .build()
5034            .unwrap();
5035
5036        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
5037        let struct_b_array = StructArray::from(vec![(list_a.clone(), list_a_array)]);
5038
5039        let batch1 =
5040            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
5041                .unwrap();
5042
5043        let field_a_array = Int32Array::from(vec![6, 7, 8, 9, 10]);
5044        let field_b_array = Int32Array::from_iter(vec![None, None, None, Some(1), None]);
5045
5046        let struct_a_array = StructArray::from(vec![
5047            (field_a, Arc::new(field_a_array) as ArrayRef),
5048            (field_b, Arc::new(field_b_array) as ArrayRef),
5049        ]);
5050
5051        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
5052            .len(2)
5053            .add_buffer(Buffer::from_iter(vec![0_i32, 4_i32, 5_i32]))
5054            .child_data(vec![struct_a_array.into_data()])
5055            .build()
5056            .unwrap();
5057
5058        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
5059        let struct_b_array = StructArray::from(vec![(list_a, list_a_array)]);
5060
5061        let batch2 =
5062            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
5063                .unwrap();
5064
5065        let batches = &[batch1, batch2];
5066
5067        // Verify data is as expected
5068
5069        let expected = r"
5070            +-------------------------------------------------------------------------------------------------------+
5071            | struct_b                                                                                              |
5072            +-------------------------------------------------------------------------------------------------------+
5073            | {list: [{leaf_a: 1, leaf_b: 1}]}                                                                      |
5074            | {list: }                                                                                              |
5075            | {list: [{leaf_a: 2, leaf_b: }, {leaf_a: 3, leaf_b: 2}]}                                               |
5076            | {list: }                                                                                              |
5077            | {list: [{leaf_a: 4, leaf_b: }, {leaf_a: 5, leaf_b: }]}                                                |
5078            | {list: [{leaf_a: 6, leaf_b: }, {leaf_a: 7, leaf_b: }, {leaf_a: 8, leaf_b: }, {leaf_a: 9, leaf_b: 1}]} |
5079            | {list: [{leaf_a: 10, leaf_b: }]}                                                                      |
5080            +-------------------------------------------------------------------------------------------------------+
5081        ".trim().split('\n').map(|x| x.trim()).collect::<Vec<_>>().join("\n");
5082
5083        let actual = pretty_format_batches(batches).unwrap().to_string();
5084        assert_eq!(actual, expected);
5085
5086        // Write data
5087        let file = tempfile::tempfile().unwrap();
5088        let props = WriterProperties::builder()
5089            .set_max_row_group_row_count(Some(6))
5090            .build();
5091
5092        let mut writer =
5093            ArrowWriter::try_new(file.try_clone().unwrap(), schema, Some(props)).unwrap();
5094
5095        for batch in batches {
5096            writer.write(batch).unwrap();
5097        }
5098        writer.close().unwrap();
5099
5100        // Read Data
5101        // Should have written entire first batch and first row of second to the first row group
5102        // leaving a single row in the second row group
5103
5104        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
5105        assert_eq!(&row_group_sizes(builder.metadata()), &[6, 1]);
5106
5107        let batches = builder
5108            .with_batch_size(2)
5109            .build()
5110            .unwrap()
5111            .collect::<ArrowResult<Vec<_>>>()
5112            .unwrap();
5113
5114        assert_eq!(batches.len(), 4);
5115        let batch_counts: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
5116        assert_eq!(&batch_counts, &[2, 2, 2, 1]);
5117
5118        let actual = pretty_format_batches(&batches).unwrap().to_string();
5119        assert_eq!(actual, expected);
5120    }
5121
5122    #[test]
5123    fn test_arrow_writer_metadata() {
5124        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5125        let file_schema = batch_schema.clone().with_metadata([("foo", "bar")]);
5126
5127        let batch = RecordBatch::try_new(
5128            Arc::new(batch_schema),
5129            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5130        )
5131        .unwrap();
5132
5133        let mut buf = Vec::with_capacity(1024);
5134        let mut writer = ArrowWriter::try_new(&mut buf, Arc::new(file_schema), None).unwrap();
5135        writer.write(&batch).unwrap();
5136        writer.close().unwrap();
5137    }
5138
5139    #[test]
5140    fn test_arrow_writer_nullable() {
5141        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5142        let file_schema = Schema::new(vec![Field::new("int32", DataType::Int32, true)]);
5143        let file_schema = Arc::new(file_schema);
5144
5145        let batch = RecordBatch::try_new(
5146            Arc::new(batch_schema),
5147            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5148        )
5149        .unwrap();
5150
5151        let mut buf = Vec::with_capacity(1024);
5152        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
5153        writer.write(&batch).unwrap();
5154        writer.close().unwrap();
5155
5156        let mut read = ParquetRecordBatchReader::try_new(Bytes::from(buf), 1024).unwrap();
5157        let back = read.next().unwrap().unwrap();
5158        assert_eq!(back.schema(), file_schema);
5159        assert_ne!(back.schema(), batch.schema());
5160        assert_eq!(back.column(0).as_ref(), batch.column(0).as_ref());
5161    }
5162
5163    #[test]
5164    fn in_progress_accounting() {
5165        // define schema
5166        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
5167
5168        // create some data
5169        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
5170
5171        // build a record batch
5172        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
5173
5174        let mut writer = ArrowWriter::try_new(vec![], batch.schema(), None).unwrap();
5175
5176        // starts empty
5177        assert_eq!(writer.in_progress_size(), 0);
5178        assert_eq!(writer.in_progress_rows(), 0);
5179        assert_eq!(writer.memory_size(), 0);
5180        assert_eq!(writer.bytes_written(), 4); // Initial header
5181        writer.write(&batch).unwrap();
5182
5183        // updated on write
5184        let initial_size = writer.in_progress_size();
5185        assert!(initial_size > 0);
5186        assert_eq!(writer.in_progress_rows(), 5);
5187        let initial_memory = writer.memory_size();
5188        assert!(initial_memory > 0);
5189        // memory estimate is larger than estimated encoded size
5190        assert!(
5191            initial_size <= initial_memory,
5192            "{initial_size} <= {initial_memory}"
5193        );
5194
5195        // updated on second write
5196        writer.write(&batch).unwrap();
5197        assert!(writer.in_progress_size() > initial_size);
5198        assert_eq!(writer.in_progress_rows(), 10);
5199        assert!(writer.memory_size() > initial_memory);
5200        assert!(
5201            writer.in_progress_size() <= writer.memory_size(),
5202            "in_progress_size {} <= memory_size {}",
5203            writer.in_progress_size(),
5204            writer.memory_size()
5205        );
5206
5207        // in progress tracking is cleared, but the overall data written is updated
5208        let pre_flush_bytes_written = writer.bytes_written();
5209        writer.flush().unwrap();
5210        assert_eq!(writer.in_progress_size(), 0);
5211        assert_eq!(writer.memory_size(), 0);
5212        assert!(writer.bytes_written() > pre_flush_bytes_written);
5213
5214        writer.close().unwrap();
5215    }
5216
5217    #[test]
5218    fn test_writer_all_null() {
5219        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
5220        let b = Int32Array::new(vec![0; 5].into(), Some(NullBuffer::new_null(5)));
5221        let batch = RecordBatch::try_from_iter(vec![
5222            ("a", Arc::new(a) as ArrayRef),
5223            ("b", Arc::new(b) as ArrayRef),
5224        ])
5225        .unwrap();
5226
5227        let mut buf = Vec::with_capacity(1024);
5228        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
5229        writer.write(&batch).unwrap();
5230        writer.close().unwrap();
5231
5232        let bytes = Bytes::from(buf);
5233        let options = ReadOptionsBuilder::new().with_page_index().build();
5234        let reader = SerializedFileReader::new_with_options(bytes, options).unwrap();
5235        let index = reader.metadata().page_index().unwrap();
5236
5237        assert_eq!(index.num_data_pages(0, 0), Some(1)); // 1 page
5238        assert_eq!(index.num_data_pages(0, 1), Some(1)); // 1 page
5239    }
5240
5241    #[test]
5242    fn test_disabled_statistics_with_page() {
5243        let file_schema = Schema::new(vec![
5244            Field::new("a", DataType::Utf8, true),
5245            Field::new("b", DataType::Utf8, true),
5246        ]);
5247        let file_schema = Arc::new(file_schema);
5248
5249        let batch = RecordBatch::try_new(
5250            file_schema.clone(),
5251            vec![
5252                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
5253                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
5254            ],
5255        )
5256        .unwrap();
5257
5258        let props = WriterProperties::builder()
5259            .set_statistics_enabled(EnabledStatistics::None)
5260            .set_column_statistics_enabled("a".into(), EnabledStatistics::Page)
5261            .build();
5262
5263        let mut buf = Vec::with_capacity(1024);
5264        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
5265        writer.write(&batch).unwrap();
5266
5267        let metadata = writer.close().unwrap();
5268        assert_eq!(metadata.num_row_groups(), 1);
5269        let row_group = metadata.row_group(0);
5270        assert_eq!(row_group.num_columns(), 2);
5271        // Column "a" has both offset and column index, as requested
5272        assert!(row_group.column(0).offset_index_offset().is_some());
5273        assert!(row_group.column(0).column_index_offset().is_some());
5274        // Column "b" should only have offset index
5275        assert!(row_group.column(1).offset_index_offset().is_some());
5276        assert!(row_group.column(1).column_index_offset().is_none());
5277
5278        let options = ReadOptionsBuilder::new().with_page_index().build();
5279        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
5280
5281        let row_group = reader.get_row_group(0).unwrap();
5282        let a_col = row_group.metadata().column(0);
5283        let b_col = row_group.metadata().column(1);
5284
5285        // Column chunk of column "a" should have chunk level statistics
5286        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
5287            let min = byte_array_stats.min_opt().unwrap();
5288            let max = byte_array_stats.max_opt().unwrap();
5289
5290            assert_eq!(min.as_bytes(), b"a");
5291            assert_eq!(max.as_bytes(), b"d");
5292        } else {
5293            panic!("expecting Statistics::ByteArray");
5294        }
5295
5296        // The column chunk for column "b" shouldn't have statistics
5297        assert!(b_col.statistics().is_none());
5298
5299        let page_index = reader.metadata().page_index().unwrap();
5300
5301        let a_idx = page_index.column_index(0, 0);
5302        assert!(
5303            matches!(a_idx, Some(ColumnIndexMetaData::BYTE_ARRAY(_))),
5304            "{a_idx:?}"
5305        );
5306        let b_idx = page_index.column_index(0, 1);
5307        assert!(b_idx.is_none(), "{b_idx:?}");
5308    }
5309
5310    #[test]
5311    fn test_disabled_statistics_with_chunk() {
5312        let file_schema = Schema::new(vec![
5313            Field::new("a", DataType::Utf8, true),
5314            Field::new("b", DataType::Utf8, true),
5315        ]);
5316        let file_schema = Arc::new(file_schema);
5317
5318        let batch = RecordBatch::try_new(
5319            file_schema.clone(),
5320            vec![
5321                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
5322                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
5323            ],
5324        )
5325        .unwrap();
5326
5327        let props = WriterProperties::builder()
5328            .set_statistics_enabled(EnabledStatistics::None)
5329            .set_column_statistics_enabled("a".into(), EnabledStatistics::Chunk)
5330            .build();
5331
5332        let mut buf = Vec::with_capacity(1024);
5333        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
5334        writer.write(&batch).unwrap();
5335
5336        let metadata = writer.close().unwrap();
5337        assert_eq!(metadata.num_row_groups(), 1);
5338        let row_group = metadata.row_group(0);
5339        assert_eq!(row_group.num_columns(), 2);
5340        // Column "a" should only have offset index
5341        assert!(row_group.column(0).offset_index_offset().is_some());
5342        assert!(row_group.column(0).column_index_offset().is_none());
5343        // Column "b" should only have offset index
5344        assert!(row_group.column(1).offset_index_offset().is_some());
5345        assert!(row_group.column(1).column_index_offset().is_none());
5346
5347        let options = ReadOptionsBuilder::new().with_page_index().build();
5348        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
5349
5350        let row_group = reader.get_row_group(0).unwrap();
5351        let a_col = row_group.metadata().column(0);
5352        let b_col = row_group.metadata().column(1);
5353
5354        // Column chunk of column "a" should have chunk level statistics
5355        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
5356            let min = byte_array_stats.min_opt().unwrap();
5357            let max = byte_array_stats.max_opt().unwrap();
5358
5359            assert_eq!(min.as_bytes(), b"a");
5360            assert_eq!(max.as_bytes(), b"d");
5361        } else {
5362            panic!("expecting Statistics::ByteArray");
5363        }
5364
5365        // The column chunk for column "b"  shouldn't have statistics
5366        assert!(b_col.statistics().is_none());
5367
5368        let page_index = reader.metadata().page_index().unwrap();
5369
5370        let a_idx = page_index.column_index(0, 0);
5371        assert!(a_idx.is_none(), "{a_idx:?}");
5372        let b_idx = page_index.column_index(0, 1);
5373        assert!(b_idx.is_none(), "{b_idx:?}");
5374    }
5375
5376    #[test]
5377    fn test_arrow_writer_skip_metadata() {
5378        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5379        let file_schema = Arc::new(batch_schema.clone());
5380
5381        let batch = RecordBatch::try_new(
5382            Arc::new(batch_schema),
5383            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5384        )
5385        .unwrap();
5386        let skip_options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
5387
5388        let mut buf = Vec::with_capacity(1024);
5389        let mut writer =
5390            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
5391        writer.write(&batch).unwrap();
5392        writer.close().unwrap();
5393
5394        let bytes = Bytes::from(buf);
5395        let reader_builder = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
5396        assert_eq!(file_schema, *reader_builder.schema());
5397        if let Some(key_value_metadata) = reader_builder
5398            .metadata()
5399            .file_metadata()
5400            .key_value_metadata()
5401        {
5402            assert!(
5403                !key_value_metadata
5404                    .iter()
5405                    .any(|kv| kv.key.as_str() == ARROW_SCHEMA_META_KEY)
5406            );
5407        }
5408    }
5409
5410    #[test]
5411    fn test_arrow_writer_skip_path_in_schema() {
5412        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5413        let file_schema = Arc::new(batch_schema.clone());
5414
5415        let batch = RecordBatch::try_new(
5416            Arc::new(batch_schema),
5417            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5418        )
5419        .unwrap();
5420
5421        // default options should still write path_in_schema
5422        let skip_options = ArrowWriterOptions::new();
5423
5424        let mut buf = Vec::with_capacity(1024);
5425        let mut writer =
5426            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
5427        writer.write(&batch).unwrap();
5428        writer.close().unwrap();
5429
5430        // override to not write path_in_schema
5431        let skip_options = ArrowWriterOptions::new().with_properties(
5432            WriterProperties::builder()
5433                .set_write_path_in_schema(false)
5434                .build(),
5435        );
5436
5437        let mut buf2 = Vec::with_capacity(1024);
5438        let mut writer =
5439            ArrowWriter::try_new_with_options(&mut buf2, file_schema.clone(), skip_options)
5440                .unwrap();
5441        writer.write(&batch).unwrap();
5442        writer.close().unwrap();
5443
5444        // buf2 should be a bit smaller due to lack of path_in_schema
5445        assert!(buf.len() > buf2.len());
5446    }
5447
5448    #[test]
5449    fn mismatched_schemas() {
5450        let batch_schema = Schema::new(vec![Field::new("count", DataType::Int32, false)]);
5451        let file_schema = Arc::new(Schema::new(vec![Field::new(
5452            "temperature",
5453            DataType::Float64,
5454            false,
5455        )]));
5456
5457        let batch = RecordBatch::try_new(
5458            Arc::new(batch_schema),
5459            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5460        )
5461        .unwrap();
5462
5463        let mut buf = Vec::with_capacity(1024);
5464        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
5465
5466        let err = writer.write(&batch).unwrap_err().to_string();
5467        assert_eq!(
5468            err,
5469            "Arrow: Incompatible type. Field 'temperature' has type Float64, array has type Int32"
5470        );
5471    }
5472
5473    #[test]
5474    // https://github.com/apache/arrow-rs/issues/6988
5475    fn test_roundtrip_empty_schema() {
5476        // create empty record batch with empty schema
5477        let empty_batch = RecordBatch::try_new_with_options(
5478            Arc::new(Schema::empty()),
5479            vec![],
5480            &RecordBatchOptions::default().with_row_count(Some(0)),
5481        )
5482        .unwrap();
5483
5484        // write to parquet
5485        let mut parquet_bytes: Vec<u8> = Vec::new();
5486        let mut writer =
5487            ArrowWriter::try_new(&mut parquet_bytes, empty_batch.schema(), None).unwrap();
5488        writer.write(&empty_batch).unwrap();
5489        writer.close().unwrap();
5490
5491        // read from parquet
5492        let bytes = Bytes::from(parquet_bytes);
5493        let reader = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
5494        assert_eq!(reader.schema(), &empty_batch.schema());
5495        let batches: Vec<_> = reader
5496            .build()
5497            .unwrap()
5498            .collect::<ArrowResult<Vec<_>>>()
5499            .unwrap();
5500        assert_eq!(batches.len(), 0);
5501    }
5502
5503    #[test]
5504    fn test_page_stats_not_written_by_default() {
5505        let string_field = Field::new("a", DataType::Utf8, false);
5506        let schema = Schema::new(vec![string_field]);
5507        let raw_string_values = vec!["Blart Versenwald III"];
5508        let string_values = StringArray::from(raw_string_values.clone());
5509        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
5510
5511        let props = WriterProperties::builder()
5512            .set_statistics_enabled(EnabledStatistics::Page)
5513            .set_dictionary_enabled(false)
5514            .set_encoding(Encoding::PLAIN)
5515            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5516            .build();
5517
5518        let file = roundtrip_opts(&batch, props);
5519
5520        // read file and decode page headers
5521        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5522
5523        // decode first page header
5524        let first_page = &file[4..];
5525        let mut prot = ThriftSliceInputProtocol::new(first_page);
5526        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5527        let stats = hdr.data_page_header.unwrap().statistics;
5528
5529        assert!(stats.is_none());
5530    }
5531
5532    #[test]
5533    fn test_page_stats_when_enabled() {
5534        let string_field = Field::new("a", DataType::Utf8, false);
5535        let schema = Schema::new(vec![string_field]);
5536        let raw_string_values = vec!["Blart Versenwald III", "Andrew Lamb"];
5537        let string_values = StringArray::from(raw_string_values.clone());
5538        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
5539
5540        let props = WriterProperties::builder()
5541            .set_statistics_enabled(EnabledStatistics::Page)
5542            .set_dictionary_enabled(false)
5543            .set_encoding(Encoding::PLAIN)
5544            .set_write_page_header_statistics(true)
5545            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5546            .build();
5547
5548        let file = roundtrip_opts(&batch, props);
5549
5550        // read file and decode page headers
5551        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5552
5553        // decode first page header
5554        let first_page = &file[4..];
5555        let mut prot = ThriftSliceInputProtocol::new(first_page);
5556        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5557        let stats = hdr.data_page_header.unwrap().statistics;
5558
5559        let stats = stats.unwrap();
5560        // check that min/max were actually written to the page
5561        assert!(stats.is_max_value_exact.unwrap());
5562        assert!(stats.is_min_value_exact.unwrap());
5563        assert_eq!(stats.max_value.unwrap(), b"Blart Versenwald III");
5564        assert_eq!(stats.min_value.unwrap(), b"Andrew Lamb");
5565    }
5566
5567    #[test]
5568    fn test_page_stats_truncation() {
5569        let string_field = Field::new("a", DataType::Utf8, false);
5570        let binary_field = Field::new("b", DataType::Binary, false);
5571        let schema = Schema::new(vec![string_field, binary_field]);
5572
5573        let raw_string_values = vec!["Blart Versenwald III"];
5574        let raw_binary_values = [b"Blart Versenwald III".to_vec()];
5575        let raw_binary_value_refs = raw_binary_values
5576            .iter()
5577            .map(|x| x.as_slice())
5578            .collect::<Vec<_>>();
5579
5580        let string_values = StringArray::from(raw_string_values.clone());
5581        let binary_values = BinaryArray::from(raw_binary_value_refs);
5582        let batch = RecordBatch::try_new(
5583            Arc::new(schema),
5584            vec![Arc::new(string_values), Arc::new(binary_values)],
5585        )
5586        .unwrap();
5587
5588        let props = WriterProperties::builder()
5589            .set_statistics_truncate_length(Some(2))
5590            .set_dictionary_enabled(false)
5591            .set_encoding(Encoding::PLAIN)
5592            .set_write_page_header_statistics(true)
5593            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5594            .build();
5595
5596        let file = roundtrip_opts(&batch, props);
5597
5598        // read file and decode page headers
5599        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5600
5601        // decode first page header
5602        let first_page = &file[4..];
5603        let mut prot = ThriftSliceInputProtocol::new(first_page);
5604        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5605        let stats = hdr.data_page_header.unwrap().statistics;
5606        assert!(stats.is_some());
5607        let stats = stats.unwrap();
5608        // check that min/max were properly truncated
5609        assert!(!stats.is_max_value_exact.unwrap());
5610        assert!(!stats.is_min_value_exact.unwrap());
5611        assert_eq!(stats.max_value.unwrap(), b"Bm");
5612        assert_eq!(stats.min_value.unwrap(), b"Bl");
5613
5614        // check second page now
5615        let second_page = &prot.as_slice()[hdr.compressed_page_size as usize..];
5616        let mut prot = ThriftSliceInputProtocol::new(second_page);
5617        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5618        let stats = hdr.data_page_header.unwrap().statistics;
5619        assert!(stats.is_some());
5620        let stats = stats.unwrap();
5621        // check that min/max were properly truncated
5622        assert!(!stats.is_max_value_exact.unwrap());
5623        assert!(!stats.is_min_value_exact.unwrap());
5624        assert_eq!(stats.max_value.unwrap(), b"Bm");
5625        assert_eq!(stats.min_value.unwrap(), b"Bl");
5626    }
5627
5628    #[test]
5629    fn test_page_encoding_statistics_roundtrip() {
5630        let batch_schema = Schema::new(vec![Field::new(
5631            "int32",
5632            arrow_schema::DataType::Int32,
5633            false,
5634        )]);
5635
5636        let batch = RecordBatch::try_new(
5637            Arc::new(batch_schema.clone()),
5638            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5639        )
5640        .unwrap();
5641
5642        let mut file: File = tempfile::tempfile().unwrap();
5643        let mut writer = ArrowWriter::try_new(&mut file, Arc::new(batch_schema), None).unwrap();
5644        writer.write(&batch).unwrap();
5645        let file_metadata = writer.close().unwrap();
5646
5647        assert_eq!(file_metadata.num_row_groups(), 1);
5648        assert_eq!(file_metadata.row_group(0).num_columns(), 1);
5649        assert!(
5650            file_metadata
5651                .row_group(0)
5652                .column(0)
5653                .page_encoding_stats()
5654                .is_some()
5655        );
5656        let chunk_page_stats = file_metadata
5657            .row_group(0)
5658            .column(0)
5659            .page_encoding_stats()
5660            .unwrap();
5661
5662        // check that the read metadata is also correct
5663        let options = ReadOptionsBuilder::new()
5664            .with_page_index()
5665            .with_encoding_stats_as_mask(false)
5666            .build();
5667        let reader = SerializedFileReader::new_with_options(file, options).unwrap();
5668
5669        let rowgroup = reader.get_row_group(0).expect("row group missing");
5670        assert_eq!(rowgroup.num_columns(), 1);
5671        let column = rowgroup.metadata().column(0);
5672        assert!(column.page_encoding_stats().is_some());
5673        let file_page_stats = column.page_encoding_stats().unwrap();
5674        assert_eq!(chunk_page_stats, file_page_stats);
5675    }
5676
5677    #[test]
5678    #[cfg_attr(miri, ignore)] // Takes too long
5679    fn test_different_dict_page_size_limit() {
5680        let array = Arc::new(Int64Array::from_iter(0..1024 * 1024));
5681        let schema = Arc::new(Schema::new(vec![
5682            Field::new("col0", arrow_schema::DataType::Int64, false),
5683            Field::new("col1", arrow_schema::DataType::Int64, false),
5684        ]));
5685        let batch =
5686            arrow_array::RecordBatch::try_new(schema.clone(), vec![array.clone(), array]).unwrap();
5687
5688        let props = WriterProperties::builder()
5689            .set_dictionary_page_size_limit(1024 * 1024)
5690            .set_column_dictionary_page_size_limit(ColumnPath::from("col1"), 1024 * 1024 * 4)
5691            .build();
5692        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5693        writer.write(&batch).unwrap();
5694        let data = Bytes::from(writer.into_inner().unwrap());
5695
5696        let mut metadata = ParquetMetaDataReader::new();
5697        metadata.try_parse(&data).unwrap();
5698        let metadata = metadata.finish().unwrap();
5699        let col0_meta = metadata.row_group(0).column(0);
5700        let col1_meta = metadata.row_group(0).column(1);
5701
5702        let get_dict_page_size = move |meta: &ColumnChunkMetaData| {
5703            let mut reader =
5704                SerializedPageReader::new(Arc::new(data.clone()), meta, 0, None).unwrap();
5705            let page = reader.get_next_page().unwrap().unwrap();
5706            match page {
5707                Page::DictionaryPage { buf, .. } => buf.len(),
5708                _ => panic!("expected DictionaryPage"),
5709            }
5710        };
5711
5712        assert_eq!(get_dict_page_size(col0_meta), 1024 * 1024);
5713        assert_eq!(get_dict_page_size(col1_meta), 1024 * 1024 * 4);
5714    }
5715
5716    #[test]
5717    #[cfg_attr(miri, ignore)] // Takes too long
5718    fn test_arrow_writer_granular_mode_roundtrip() {
5719        // Granular mode subdivides chunks and writes more pages than the
5720        // default batched path. Make sure the data we write back is
5721        // bit-identical to what went in — page-count assertions elsewhere
5722        // only prove pages were cut, not that the encoded data is correct.
5723        //
5724        // Mix value sizes so that the cumulative-byte-budget cutoff
5725        // lands mid-chunk, exercising both batched and granular paths
5726        // within the same `write_batch_internal` call.
5727        let small = "tiny".to_string();
5728        let big = "x".repeat(64 * 1024);
5729        let strings: Vec<String> = (0..256)
5730            .map(|i| {
5731                if i % 16 == 0 {
5732                    big.clone()
5733                } else {
5734                    small.clone()
5735                }
5736            })
5737            .collect();
5738
5739        let schema = Arc::new(Schema::new(vec![Field::new(
5740            "col",
5741            ArrowDataType::Utf8,
5742            false,
5743        )]));
5744        let batch = RecordBatch::try_new(
5745            schema.clone(),
5746            vec![Arc::new(StringArray::from(strings.clone())) as _],
5747        )
5748        .unwrap();
5749
5750        let props = WriterProperties::builder()
5751            .set_dictionary_enabled(false)
5752            .set_data_page_size_limit(16 * 1024)
5753            .build();
5754        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5755        writer.write(&batch).unwrap();
5756        let data = Bytes::from(writer.into_inner().unwrap());
5757
5758        let mut reader = ParquetRecordBatchReader::try_new(data, 1024).unwrap();
5759        let read = reader.next().unwrap().unwrap();
5760        assert!(reader.next().is_none(), "expected one batch");
5761        let col = read
5762            .column(0)
5763            .as_any()
5764            .downcast_ref::<StringArray>()
5765            .unwrap();
5766        assert_eq!(col.len(), strings.len());
5767        for (i, expected) in strings.iter().enumerate() {
5768            assert_eq!(
5769                col.value(i),
5770                expected.as_str(),
5771                "value mismatch at index {i}"
5772            );
5773        }
5774    }
5775
5776    #[test]
5777    fn test_arrow_writer_all_null_string_column() {
5778        // The `LevelDataRef::value_count` Uniform branch with
5779        // `value != max_def` (entirely-null chunk) must return 0 so the
5780        // sub-batch sizer short-circuits to batch mode without trying
5781        // to estimate byte budgets for non-existent values.
5782        let num_rows = 1024;
5783        let schema = Arc::new(Schema::new(vec![Field::new(
5784            "col",
5785            ArrowDataType::Utf8,
5786            true,
5787        )]));
5788        let nulls: Vec<Option<&str>> = vec![None; num_rows];
5789        let batch = RecordBatch::try_new(
5790            schema.clone(),
5791            vec![Arc::new(StringArray::from(nulls)) as _],
5792        )
5793        .unwrap();
5794
5795        let props = WriterProperties::builder()
5796            .set_dictionary_enabled(false)
5797            .set_data_page_size_limit(16 * 1024)
5798            .build();
5799        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5800        writer.write(&batch).unwrap();
5801        let data = Bytes::from(writer.into_inner().unwrap());
5802
5803        // Re-parse the file: row group has one column, every row is
5804        // null, all data pages report `num_rows / page_count` rows.
5805        let mut metadata = ParquetMetaDataReader::new();
5806        metadata.try_parse(&data).unwrap();
5807        let metadata = metadata.finish().unwrap();
5808        let row_group = metadata.row_group(0);
5809        let col_meta = row_group.column(0);
5810        assert_eq!(row_group.num_rows() as usize, num_rows);
5811        // Statistics record `null_count = num_rows` — proves every value
5812        // was written as null.
5813        if let Some(stats) = col_meta.statistics() {
5814            assert_eq!(
5815                stats.null_count_opt().unwrap_or(0) as usize,
5816                num_rows,
5817                "expected all-null column to report null_count = num_rows"
5818            );
5819        }
5820
5821        let mut reader =
5822            SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap();
5823        let mut total_values = 0u32;
5824        while let Some(page) = reader.get_next_page().unwrap() {
5825            if matches!(page, Page::DataPage { .. } | Page::DataPageV2 { .. }) {
5826                total_values += page.num_values();
5827            }
5828        }
5829        assert_eq!(
5830            total_values as usize, num_rows,
5831            "expected every level position to be represented in some page"
5832        );
5833    }
5834
5835    struct WriteBatchesShape {
5836        num_batches: usize,
5837        rows_per_batch: usize,
5838        row_size: usize,
5839    }
5840
5841    /// Helper function to write batches with the provided `WriteBatchesShape` into an `ArrowWriter`
5842    fn write_batches(
5843        WriteBatchesShape {
5844            num_batches,
5845            rows_per_batch,
5846            row_size,
5847        }: WriteBatchesShape,
5848        props: WriterProperties,
5849    ) -> ParquetRecordBatchReaderBuilder<File> {
5850        let schema = Arc::new(Schema::new(vec![Field::new(
5851            "str",
5852            ArrowDataType::Utf8,
5853            false,
5854        )]));
5855        let file = tempfile::tempfile().unwrap();
5856        let mut writer =
5857            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
5858
5859        for batch_idx in 0..num_batches {
5860            let strings: Vec<String> = (0..rows_per_batch)
5861                .map(|i| format!("{:0>width$}", batch_idx * 10 + i, width = row_size))
5862                .collect();
5863            let array = StringArray::from(strings);
5864            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
5865            writer.write(&batch).unwrap();
5866        }
5867        writer.close().unwrap();
5868        ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
5869    }
5870
5871    #[test]
5872    // When both limits are None, all data should go into a single row group
5873    fn test_row_group_limit_none_writes_single_row_group() {
5874        let props = WriterProperties::builder()
5875            .set_max_row_group_row_count(None)
5876            .set_max_row_group_bytes(None)
5877            .build();
5878
5879        let builder = write_batches(
5880            WriteBatchesShape {
5881                num_batches: 1,
5882                rows_per_batch: 1000,
5883                row_size: 4,
5884            },
5885            props,
5886        );
5887
5888        assert_eq!(
5889            &row_group_sizes(builder.metadata()),
5890            &[1000],
5891            "With no limits, all rows should be in a single row group"
5892        );
5893    }
5894
5895    #[test]
5896    // When only max_row_group_size is set, respect the row limit
5897    fn test_row_group_limit_rows_only() {
5898        let props = WriterProperties::builder()
5899            .set_max_row_group_row_count(Some(300))
5900            .set_max_row_group_bytes(None)
5901            .build();
5902
5903        let builder = write_batches(
5904            WriteBatchesShape {
5905                num_batches: 1,
5906                rows_per_batch: 1000,
5907                row_size: 4,
5908            },
5909            props,
5910        );
5911
5912        assert_eq!(
5913            &row_group_sizes(builder.metadata()),
5914            &[300, 300, 300, 100],
5915            "Row groups should be split by row count"
5916        );
5917    }
5918
5919    #[test]
5920    #[cfg_attr(miri, ignore)] // Takes too long
5921    // A row limit far smaller than the batch splits it many times over; the split must not
5922    // consume stack proportional to the number of row groups.
5923    fn test_row_group_limit_rows_only_many_splits() {
5924        let props = WriterProperties::builder()
5925            .set_max_row_group_row_count(Some(1))
5926            .set_max_row_group_bytes(None)
5927            .build();
5928
5929        let rows = 50_000;
5930        let builder = write_batches(
5931            WriteBatchesShape {
5932                num_batches: 1,
5933                rows_per_batch: rows,
5934                row_size: 4,
5935            },
5936            props,
5937        );
5938
5939        let sizes = row_group_sizes(builder.metadata());
5940        assert_eq!(sizes.len(), rows, "Every row should get its own row group");
5941        assert_eq!(
5942            sizes.iter().sum::<i64>(),
5943            rows as i64,
5944            "Total rows should be preserved"
5945        );
5946    }
5947
5948    #[test]
5949    // When only max_row_group_bytes is set, respect the byte limit
5950    fn test_row_group_limit_bytes_only() {
5951        let props = WriterProperties::builder()
5952            .set_max_row_group_row_count(None)
5953            // Set byte limit to approximately fit ~30 rows worth of data (~100 bytes each)
5954            .set_max_row_group_bytes(Some(3500))
5955            .build();
5956
5957        let builder = write_batches(
5958            WriteBatchesShape {
5959                num_batches: 10,
5960                rows_per_batch: 10,
5961                row_size: 100,
5962            },
5963            props,
5964        );
5965
5966        let sizes = row_group_sizes(builder.metadata());
5967
5968        assert!(
5969            sizes.len() > 1,
5970            "Should have multiple row groups due to byte limit, got {sizes:?}",
5971        );
5972
5973        let total_rows: i64 = sizes.iter().sum();
5974        assert_eq!(total_rows, 100, "Total rows should be preserved");
5975    }
5976
5977    #[test]
5978    // If an in-progress row group is already oversized, it should be flushed before writing more.
5979    fn test_row_group_limit_bytes_flushes_when_current_group_already_too_large() {
5980        let schema = Arc::new(Schema::new(vec![Field::new(
5981            "str",
5982            ArrowDataType::Utf8,
5983            false,
5984        )]));
5985        let file = tempfile::tempfile().unwrap();
5986
5987        // Start with no byte limit so we can intentionally build an oversized in-progress row group.
5988        let props = WriterProperties::builder()
5989            .set_max_row_group_row_count(None)
5990            .set_max_row_group_bytes(None)
5991            .build();
5992        let mut writer =
5993            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
5994
5995        let first_array = StringArray::from(
5996            (0..10)
5997                .map(|i| format!("{i:0>100}"))
5998                .collect::<Vec<String>>(),
5999        );
6000        let first_batch =
6001            RecordBatch::try_new(schema.clone(), vec![Arc::new(first_array)]).unwrap();
6002        writer.write(&first_batch).unwrap();
6003        assert_eq!(writer.in_progress_rows(), 10);
6004
6005        // Tighten the limit below the current in-progress bytes to exercise:
6006        // `if current_bytes >= max_bytes { self.flush()?; ... }`
6007        writer.max_row_group_bytes = Some(1);
6008
6009        let second_array = StringArray::from(vec!["x".to_string()]);
6010        let second_batch =
6011            RecordBatch::try_new(schema.clone(), vec![Arc::new(second_array)]).unwrap();
6012        writer.write(&second_batch).unwrap();
6013        writer.close().unwrap();
6014        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
6015
6016        assert_eq!(
6017            &row_group_sizes(builder.metadata()),
6018            &[10, 1],
6019            "The second write should flush an oversized in-progress row group first",
6020        );
6021    }
6022
6023    #[test]
6024    // When both limits are set, the row limit triggers first
6025    fn test_row_group_limit_both_row_wins_single_batch() {
6026        let props = WriterProperties::builder()
6027            .set_max_row_group_row_count(Some(200)) // Will trigger at 200 rows
6028            .set_max_row_group_bytes(Some(1024 * 1024)) // 1MB - won't trigger for small int data
6029            .build();
6030
6031        let builder = write_batches(
6032            WriteBatchesShape {
6033                num_batches: 1,
6034                row_size: 4,
6035                rows_per_batch: 1000,
6036            },
6037            props,
6038        );
6039
6040        assert_eq!(
6041            &row_group_sizes(builder.metadata()),
6042            &[200, 200, 200, 200, 200],
6043            "Row limit should trigger before byte limit"
6044        );
6045    }
6046
6047    #[test]
6048    // When both limits are set, the row limit triggers first
6049    fn test_row_group_limit_both_row_wins_multiple_batches() {
6050        let props = WriterProperties::builder()
6051            .set_max_row_group_row_count(Some(5)) // Will trigger every 5 rows
6052            .set_max_row_group_bytes(Some(9999)) // Won't trigger
6053            .build();
6054
6055        let builder = write_batches(
6056            WriteBatchesShape {
6057                num_batches: 10,
6058                rows_per_batch: 10,
6059                row_size: 100,
6060            },
6061            props,
6062        );
6063
6064        assert_eq!(
6065            &row_group_sizes(builder.metadata()),
6066            &[5; 20],
6067            "Row limit should trigger before byte limit"
6068        );
6069    }
6070
6071    #[test]
6072    // When both limits are set, the byte limit triggers first
6073    fn test_row_group_limit_both_bytes_wins() {
6074        let props = WriterProperties::builder()
6075            .set_max_row_group_row_count(Some(1000)) // Won't trigger for 100 rows
6076            .set_max_row_group_bytes(Some(3500)) // Will trigger at ~30-35 rows
6077            .build();
6078
6079        let builder = write_batches(
6080            WriteBatchesShape {
6081                num_batches: 10,
6082                rows_per_batch: 10,
6083                row_size: 100,
6084            },
6085            props,
6086        );
6087
6088        let sizes = row_group_sizes(builder.metadata());
6089
6090        assert!(
6091            sizes.len() > 1,
6092            "Byte limit should trigger before row limit, got {sizes:?}",
6093        );
6094
6095        assert!(
6096            sizes.iter().all(|&s| s < 1000),
6097            "No row group should hit the row limit"
6098        );
6099
6100        let total_rows: i64 = sizes.iter().sum();
6101        assert_eq!(total_rows, 100, "Total rows should be preserved");
6102    }
6103
6104    #[test]
6105    // Both limits can apply to the same batch: the row limit trims it to 5 rows, and the
6106    // byte limit then trims those 5 down to 4.
6107    fn test_row_group_limit_both_apply_to_same_batch() {
6108        let props = WriterProperties::builder()
6109            .set_max_row_group_row_count(Some(15))
6110            .set_max_row_group_bytes(Some(1500))
6111            .build();
6112
6113        let builder = write_batches(
6114            WriteBatchesShape {
6115                num_batches: 2,
6116                rows_per_batch: 10,
6117                row_size: 100,
6118            },
6119            props,
6120        );
6121
6122        assert_eq!(
6123            &row_group_sizes(builder.metadata()),
6124            &[14, 6],
6125            "Byte limit should still apply to a batch the row limit already split"
6126        );
6127    }
6128
6129    #[test]
6130    fn arrow_column_chunk_close_mut_drops_column_index() {
6131        use crate::arrow::ArrowSchemaConverter;
6132        use crate::file::writer::SerializedFileWriter;
6133
6134        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
6135        let props = Arc::new(
6136            WriterProperties::builder()
6137                .set_statistics_enabled(EnabledStatistics::Page)
6138                .build(),
6139        );
6140        let parquet_schema = ArrowSchemaConverter::new()
6141            .with_coerce_types(props.coerce_types())
6142            .convert(&schema)
6143            .unwrap();
6144
6145        let mut buf = Vec::with_capacity(1024);
6146        let mut writer =
6147            SerializedFileWriter::new(&mut buf, parquet_schema.root_schema_ptr(), props.clone())
6148                .unwrap();
6149
6150        let factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
6151        let mut col_writers = factory.create_column_writers(0).unwrap();
6152        let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..64));
6153        for leaves in compute_leaves(schema.field(0), &arr).unwrap() {
6154            col_writers[0].write(&leaves).unwrap();
6155        }
6156        let mut chunk = col_writers.pop().unwrap().close().unwrap();
6157
6158        // Immutable accessor exposes the close result produced at close time.
6159        assert!(
6160            chunk.close().column_index.is_some(),
6161            "EnabledStatistics::Page should produce a column_index"
6162        );
6163
6164        // Mutable accessor lets callers drop the page-level index before append.
6165        chunk.close_mut().column_index = None;
6166        assert!(chunk.close().column_index.is_none());
6167
6168        let mut rg = writer.next_row_group().unwrap();
6169        chunk.append_to_row_group(&mut rg).unwrap();
6170        rg.close().unwrap();
6171        let file_meta = writer.close().unwrap();
6172
6173        // After dropping column_index, the resulting file records no column
6174        // index offset/length for this chunk.
6175        let cc = file_meta.row_group(0).column(0);
6176        assert!(cc.column_index_range().is_none());
6177    }
6178
6179    /// Writes a single-column RecordBatch to an in-memory Parquet buffer.
6180    fn write_column_to_bytes(array: ArrayRef) -> Bytes {
6181        let schema = Arc::new(Schema::new(vec![Field::new(
6182            "col",
6183            array.data_type().clone(),
6184            true,
6185        )]));
6186        let buf = get_bytes_after_close(
6187            schema.clone(),
6188            &RecordBatch::try_new(schema, vec![array]).unwrap(),
6189        );
6190        Bytes::from(buf)
6191    }
6192
6193    /// Reads column 0 from a single-row-group Parquet buffer, projecting it with the given schema.
6194    /// Passing a flat schema when the buffer was written from a REE array lets callers decode
6195    /// the physical values without the run-end encoding wrapper.
6196    fn read_column_with_schema(bytes: Bytes, schema: SchemaRef) -> ArrayRef {
6197        let opts = crate::arrow::arrow_reader::ArrowReaderOptions::new().with_schema(schema);
6198        ParquetRecordBatchReaderBuilder::try_new_with_options(bytes, opts)
6199            .unwrap()
6200            .build()
6201            .unwrap()
6202            .next()
6203            .unwrap()
6204            .unwrap()
6205            .column(0)
6206            .clone()
6207    }
6208
6209    fn ree_write_read_roundtrip(ree: ArrayRef, flat: ArrayRef) {
6210        let flat_schema = Arc::new(Schema::new(vec![Field::new(
6211            "col",
6212            flat.data_type().clone(),
6213            true,
6214        )]));
6215        let ree_bytes = write_column_to_bytes(ree);
6216        let flat_bytes = write_column_to_bytes(flat.clone());
6217        assert_eq!(
6218            ree_bytes, flat_bytes,
6219            "REE and flat bytes should be identical"
6220        );
6221
6222        let decoded_ree = read_column_with_schema(ree_bytes, flat_schema.clone());
6223        let decoded_flat = read_column_with_schema(flat_bytes, flat_schema);
6224
6225        assert_eq!(decoded_ree.as_ref(), flat.as_ref());
6226        assert_eq!(decoded_ree.as_ref(), decoded_flat.as_ref());
6227    }
6228
6229    #[test]
6230    fn ree_string() {
6231        let ree: ArrayRef = Arc::new(
6232            [Some("a"), Some("a"), None, Some("b"), Some("b")]
6233                .into_iter()
6234                .collect::<Int32RunArray>(),
6235        );
6236        let flat: ArrayRef = Arc::new(StringArray::from(vec![
6237            Some("a"),
6238            Some("a"),
6239            None,
6240            Some("b"),
6241            Some("b"),
6242        ]));
6243        ree_write_read_roundtrip(ree, flat);
6244    }
6245
6246    #[test]
6247    fn ree_int32() {
6248        let mut b = PrimitiveRunBuilder::<Int32Type, Int32Type>::new();
6249        for v in [Some(1), Some(1), None, Some(2), Some(2)] {
6250            b.append_option(v);
6251        }
6252        let ree: ArrayRef = Arc::new(b.finish());
6253        let flat: ArrayRef = Arc::new(Int32Array::from(vec![
6254            Some(1),
6255            Some(1),
6256            None,
6257            Some(2),
6258            Some(2),
6259        ]));
6260        ree_write_read_roundtrip(ree, flat);
6261    }
6262
6263    #[test]
6264    fn ree_bool() {
6265        // run_ends [3, 5, 7] → [T,T,T, null,null, F,F]
6266        let ree: ArrayRef = Arc::new(
6267            RunArray::try_new(
6268                &Int32Array::from(vec![3, 5, 7]),
6269                &BooleanArray::from(vec![Some(true), None, Some(false)]),
6270            )
6271            .unwrap(),
6272        );
6273        let flat: ArrayRef = Arc::new(BooleanArray::from(vec![
6274            Some(true),
6275            Some(true),
6276            Some(true),
6277            None,
6278            None,
6279            Some(false),
6280            Some(false),
6281        ]));
6282        ree_write_read_roundtrip(ree, flat);
6283    }
6284
6285    #[test]
6286    fn ree_fixed_size_binary() {
6287        let mk = |vals: &[Option<&[u8]>]| -> FixedSizeBinaryArray {
6288            let mut b = FixedSizeBinaryBuilder::new(2);
6289            for v in vals {
6290                match v {
6291                    Some(x) => b.append_value(x).unwrap(),
6292                    None => b.append_null(),
6293                }
6294            }
6295            b.finish()
6296        };
6297        // run_ends [2, 4, 6] → [aa,aa, null,null, bb,bb]
6298        let ree: ArrayRef = Arc::new(
6299            RunArray::try_new(
6300                &Int32Array::from(vec![2, 4, 6]),
6301                &mk(&[Some(b"aa"), None, Some(b"bb")]),
6302            )
6303            .unwrap(),
6304        );
6305        let flat: ArrayRef = Arc::new(mk(&[
6306            Some(b"aa"),
6307            Some(b"aa"),
6308            None,
6309            None,
6310            Some(b"bb"),
6311            Some(b"bb"),
6312        ]));
6313        ree_write_read_roundtrip(ree, flat);
6314    }
6315
6316    #[test]
6317    fn ree_single_run() {
6318        let ree: ArrayRef = Arc::new(["x", "x", "x"].into_iter().collect::<Int32RunArray>());
6319        let flat: ArrayRef = Arc::new(StringArray::from(vec!["x", "x", "x"]));
6320        ree_write_read_roundtrip(ree, flat);
6321    }
6322
6323    #[test]
6324    fn ree_float32() {
6325        // run_ends [2, 4, 5] → [1.0, 1.0, null, null, 2.5]
6326        let ree: ArrayRef = Arc::new(
6327            RunArray::try_new(
6328                &Int32Array::from(vec![2, 4, 5]),
6329                &Float32Array::from(vec![Some(1.0_f32), None, Some(2.5_f32)]),
6330            )
6331            .unwrap(),
6332        );
6333        let flat: ArrayRef = Arc::new(Float32Array::from(vec![
6334            Some(1.0_f32),
6335            Some(1.0_f32),
6336            None,
6337            None,
6338            Some(2.5_f32),
6339        ]));
6340        ree_write_read_roundtrip(ree, flat);
6341    }
6342
6343    #[test]
6344    fn ree_sliced() {
6345        // A sliced (non-zero offset) REE array: verify that get_physical_index
6346        // correctly accounts for the logical offset when expanding.
6347        // Full array: run_ends [3, 5, 7] → [a,a,a, b,b, c,c]
6348        // After slice(2, 5) the logical view is [a, b, b, c, c].
6349        let full: ArrayRef = Arc::new(
6350            RunArray::try_new(
6351                &Int32Array::from(vec![3, 5, 7]),
6352                &StringArray::from(vec!["a", "b", "c"]),
6353            )
6354            .unwrap(),
6355        );
6356        let sliced = full.slice(2, 5);
6357        let flat: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "b", "c", "c"]));
6358        ree_write_read_roundtrip(sliced, flat);
6359    }
6360
6361    #[test]
6362    #[cfg_attr(miri, ignore)] // Takes too long
6363    fn test_number_distinct_values_exact_count() {
6364        // 50 distinct Int32 values repeated across 100k rows, with every 7th row null.
6365        // Nulls must not be counted as a distinct value.
6366        let cardinality = 50u32;
6367        let array: ArrayRef = Arc::new(Int32Array::from_iter((0..100_000u32).map(|i| {
6368            if i % 7 == 0 {
6369                None
6370            } else {
6371                Some((i % cardinality) as i32)
6372            }
6373        })));
6374        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, true)]));
6375        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
6376
6377        let props = WriterProperties::builder()
6378            .set_write_row_group_number_distinct_values(true)
6379            .build();
6380        let mut buf = Vec::new();
6381        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
6382        writer.write(&batch).unwrap();
6383        let metadata = writer.close().unwrap();
6384
6385        let count = metadata
6386            .row_group(0)
6387            .column(0)
6388            .statistics()
6389            .and_then(|s| s.distinct_count_opt())
6390            .expect("distinct_count should be set");
6391        // Must equal cardinality exactly; nulls must not inflate the count.
6392        assert_eq!(count, cardinality as u64);
6393    }
6394
6395    #[test]
6396    fn test_number_distinct_values_not_written_by_default() {
6397        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
6398        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)]));
6399        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
6400
6401        let mut buf = Vec::new();
6402        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
6403        writer.write(&batch).unwrap();
6404        let metadata = writer.close().unwrap();
6405
6406        let count = metadata
6407            .row_group(0)
6408            .column(0)
6409            .statistics()
6410            .and_then(|s| s.distinct_count_opt());
6411        assert!(count.is_none());
6412    }
6413
6414    #[test]
6415    fn ree_struct_with_ree_child() {
6416        // Struct with a REE string field and a REE int field — confirms
6417        // recursion visits every child and each collapses to the right leaf type.
6418        let run_ends = Int32Array::from(vec![2i32, 3, 5]);
6419
6420        let col_a: ArrayRef = Arc::new(
6421            RunArray::try_new(
6422                &run_ends,
6423                &StringArray::from(vec![Some("foo"), None, Some("bar")]),
6424            )
6425            .unwrap(),
6426        );
6427        let col_b: ArrayRef = Arc::new(
6428            RunArray::try_new(&run_ends, &Int32Array::from(vec![Some(1), None, Some(2)])).unwrap(),
6429        );
6430
6431        let struct_array: ArrayRef = Arc::new(StructArray::new(
6432            Fields::from(vec![
6433                Field::new("a", col_a.data_type().clone(), true),
6434                Field::new("b", col_b.data_type().clone(), true),
6435            ]),
6436            vec![col_a, col_b],
6437            None,
6438        ));
6439
6440        let schema = Arc::new(Schema::new(vec![Field::new(
6441            "row",
6442            struct_array.data_type().clone(),
6443            true,
6444        )]));
6445        let batch = RecordBatch::try_new(schema.clone(), vec![struct_array]).unwrap();
6446
6447        let mut buf = Vec::new();
6448        let mut writer = ArrowWriter::try_new(&mut buf, schema, None).unwrap();
6449        writer.write(&batch).unwrap();
6450        let metadata = writer.close().unwrap();
6451
6452        let parquet_schema = metadata.file_metadata().schema_descr();
6453        assert_eq!(parquet_schema.num_columns(), 2);
6454        assert_eq!(
6455            parquet_schema.column(0).physical_type(),
6456            crate::basic::Type::BYTE_ARRAY
6457        );
6458        assert_eq!(parquet_schema.column(0).path().string(), "row.a");
6459        assert_eq!(
6460            parquet_schema.column(1).physical_type(),
6461            crate::basic::Type::INT32
6462        );
6463        assert_eq!(parquet_schema.column(1).path().string(), "row.b");
6464    }
6465}