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, EncodingMask};
2111    use crate::data_type::AsBytes;
2112    use crate::file::metadata::{ColumnChunkMetaData, ParquetMetaData, ParquetMetaDataReader};
2113    use crate::file::properties::{
2114        BloomFilterPosition, EnabledStatistics, ReaderProperties, WriterVersion,
2115    };
2116    use crate::file::serialized_reader::ReadOptionsBuilder;
2117    use crate::file::{
2118        reader::{FileReader, SerializedFileReader},
2119        statistics::Statistics,
2120    };
2121
2122    /// A [`PageStore`] that allocates *sparse, non-contiguous* handles and keeps
2123    /// blobs in a `HashMap` — nothing like the default `Vec<Bytes>`. Used to
2124    /// prove the writer relies only on the opaque-handle contract and never on
2125    /// handles being dense `Vec` indices. Records how many blobs were stored.
2126    #[derive(Debug, Default)]
2127    struct RecordingPageStore {
2128        next: u64,
2129        blobs: HashMap<u64, Bytes>,
2130        puts: Arc<std::sync::atomic::AtomicUsize>,
2131    }
2132
2133    impl PageStore for RecordingPageStore {
2134        fn put(&mut self, value: Bytes) -> Result<PageKey> {
2135            // Deliberately non-sequential, never-zero handles.
2136            let id = 100 + self.next * 7;
2137            self.next += 1;
2138            self.puts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2139            self.blobs.insert(id, value);
2140            Ok(PageKey::new(id))
2141        }
2142
2143        fn take(&mut self, key: PageKey) -> Result<Bytes> {
2144            self.blobs
2145                .remove(&key.get())
2146                .ok_or_else(|| ParquetError::General(format!("missing key {}", key.get())))
2147        }
2148    }
2149
2150    #[derive(Debug)]
2151    struct RecordingPageStoreFactory {
2152        puts: Arc<std::sync::atomic::AtomicUsize>,
2153    }
2154
2155    impl PageStoreFactory for RecordingPageStoreFactory {
2156        fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2157            Ok(Box::new(RecordingPageStore {
2158                puts: self.puts.clone(),
2159                ..Default::default()
2160            }))
2161        }
2162    }
2163
2164    /// A custom [`PageStore`] must produce byte-identical files to the in-memory
2165    /// default, across dictionary and non-dictionary columns and multiple row
2166    /// groups (so multiple store instances are exercised).
2167    #[test]
2168    fn custom_page_store_is_byte_identical_to_default() {
2169        let schema = Arc::new(Schema::new(vec![
2170            Field::new("i", DataType::Int32, true),
2171            // A low-cardinality string column to exercise the dictionary path.
2172            Field::new("s", DataType::Utf8, true),
2173        ]));
2174        let i = Int32Array::from(vec![Some(1), None, Some(3), Some(4), Some(5), Some(6)]);
2175        let s = StringArray::from(vec![
2176            Some("a"),
2177            Some("bb"),
2178            Some("a"),
2179            None,
2180            Some("bb"),
2181            Some("ccc"),
2182        ]);
2183        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(i), Arc::new(s)]).unwrap();
2184
2185        // Small row groups so multiple column chunks (hence multiple store
2186        // instances) are produced.
2187        let props = WriterProperties::builder()
2188            .set_max_row_group_row_count(Some(3))
2189            .build();
2190
2191        let write = |factory: Option<Arc<dyn PageStoreFactory>>| {
2192            let mut buffer = Vec::new();
2193            let mut opts = ArrowWriterOptions::new().with_properties(props.clone());
2194            if let Some(factory) = factory {
2195                opts = opts.with_page_store_factory(factory);
2196            }
2197            let mut writer =
2198                ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2199            writer.write(&batch).unwrap();
2200            writer.close().unwrap();
2201            buffer
2202        };
2203
2204        let default_bytes = write(None);
2205
2206        let puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2207        let custom_bytes = write(Some(Arc::new(RecordingPageStoreFactory {
2208            puts: puts.clone(),
2209        })));
2210
2211        assert!(
2212            puts.load(std::sync::atomic::Ordering::Relaxed) > 0,
2213            "custom PageStore was never written to"
2214        );
2215        assert_eq!(
2216            default_bytes, custom_bytes,
2217            "a custom PageStore must produce byte-identical output to the default"
2218        );
2219    }
2220
2221    /// A dictionary-encoded column written through the deferred-ordering Arrow
2222    /// path must round-trip correctly even with the offset index disabled, when
2223    /// only the chunk-level dictionary/data page offsets are rewritten (there is
2224    /// no offset index to rebuild). Spans multiple data pages so the
2225    /// dictionary-first reordering is exercised.
2226    #[test]
2227    #[cfg_attr(miri, ignore)] // Takes too long
2228    fn dictionary_column_round_trips_with_offset_index_disabled() {
2229        let schema = Arc::new(Schema::new(vec![Field::new("k", DataType::Int32, true)]));
2230
2231        // Low cardinality so the column stays dictionary-encoded; enough rows to
2232        // span several data pages within a single row group.
2233        let values: Vec<Option<i32>> = (0..50_000).map(|i| Some(i % 8)).collect();
2234        let array = Int32Array::from(values.clone());
2235        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
2236
2237        let props = WriterProperties::builder()
2238            .set_offset_index_disabled(true)
2239            .set_data_page_row_count_limit(4096)
2240            .build();
2241        let opts = ArrowWriterOptions::new().with_properties(props);
2242
2243        let mut buffer = Vec::new();
2244        let mut writer =
2245            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2246        writer.write(&batch).unwrap();
2247        writer.close().unwrap();
2248
2249        let reader = ParquetRecordBatchReader::try_new(Bytes::from(buffer), values.len()).unwrap();
2250        let read: Vec<RecordBatch> = reader.collect::<ArrowResult<_>>().unwrap();
2251        let read_values: Vec<Option<i32>> = read
2252            .iter()
2253            .flat_map(|b| b.column(0).as_primitive::<Int32Type>().iter())
2254            .collect();
2255        assert_eq!(read_values, values);
2256    }
2257
2258    /// The dictionary page is routed through the [`PageStore`] like any other
2259    /// page rather than held resident in memory, so a dictionary column chunk's
2260    /// *entire* serialized size — dictionary page included — passes through the
2261    /// store.
2262    #[test]
2263    fn dictionary_page_is_routed_through_the_store() {
2264        /// A store that sums the bytes handed to `put`.
2265        #[derive(Debug, Default)]
2266        struct SizeRecordingPageStore {
2267            blobs: Vec<Bytes>,
2268            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2269        }
2270        impl PageStore for SizeRecordingPageStore {
2271            fn put(&mut self, value: Bytes) -> Result<PageKey> {
2272                self.bytes_put
2273                    .fetch_add(value.len(), std::sync::atomic::Ordering::Relaxed);
2274                let key = PageKey::new(self.blobs.len() as u64);
2275                self.blobs.push(value);
2276                Ok(key)
2277            }
2278            fn take(&mut self, key: PageKey) -> Result<Bytes> {
2279                Ok(std::mem::take(&mut self.blobs[key.get() as usize]))
2280            }
2281        }
2282        #[derive(Debug)]
2283        struct Factory {
2284            bytes_put: Arc<std::sync::atomic::AtomicUsize>,
2285        }
2286        impl PageStoreFactory for Factory {
2287            fn create(&self, _args: &PageStoreArgs<'_>) -> Result<Box<dyn PageStore>> {
2288                Ok(Box::new(SizeRecordingPageStore {
2289                    bytes_put: self.bytes_put.clone(),
2290                    ..Default::default()
2291                }))
2292            }
2293        }
2294
2295        let schema = Arc::new(Schema::new(vec![Field::new("s", DataType::Utf8, false)]));
2296        // Low cardinality keeps the column dictionary-encoded with a real,
2297        // non-empty dictionary page.
2298        let values: Vec<&str> = (0..2048)
2299            .map(|i| ["alpha", "beta", "gamma", "delta"][i % 4])
2300            .collect();
2301        let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(StringArray::from(values))])
2302            .unwrap();
2303
2304        let bytes_put = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2305        let opts = ArrowWriterOptions::new().with_page_store_factory(Arc::new(Factory {
2306            bytes_put: bytes_put.clone(),
2307        }));
2308
2309        // A single batch / single column means exactly one row group and one
2310        // store instance, so the bytes it saw map to one column chunk.
2311        let mut buffer = Vec::new();
2312        let mut writer =
2313            ArrowWriter::try_new_with_options(&mut buffer, schema.clone(), opts).unwrap();
2314        writer.write(&batch).unwrap();
2315        writer.close().unwrap();
2316
2317        let reader = SerializedFileReader::new(Bytes::from(buffer)).unwrap();
2318        let column = reader.metadata().row_group(0).column(0);
2319        assert!(
2320            column.dictionary_page_offset().is_some(),
2321            "expected the column to be dictionary-encoded"
2322        );
2323
2324        // The bytes the store was handed must account for the whole chunk,
2325        // dictionary page included. Holding the dictionary page apart from the
2326        // store would make this fall short by the dictionary page's size.
2327        assert_eq!(
2328            bytes_put.load(std::sync::atomic::Ordering::Relaxed) as i64,
2329            column.compressed_size(),
2330            "the dictionary page must pass through the store like any other page"
2331        );
2332    }
2333
2334    #[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, Encoding::ALP]
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    fn write_with_bloom_filter(array: ArrayRef, dictionary_page_size_limit: usize) -> Bytes {
3968        let schema = Arc::new(Schema::new(vec![Field::new(
3969            "col",
3970            array.data_type().clone(),
3971            false,
3972        )]));
3973        let batch = RecordBatch::try_new(schema.clone(), vec![array]).unwrap();
3974        let props = WriterProperties::builder()
3975            .set_dictionary_enabled(true)
3976            .set_dictionary_page_size_limit(dictionary_page_size_limit)
3977            .set_write_batch_size(256)
3978            .set_bloom_filter_enabled(true)
3979            .build();
3980        let mut buf = Vec::new();
3981        let mut writer = ArrowWriter::try_new(&mut buf, schema, Some(props)).unwrap();
3982        writer.write(&batch).unwrap();
3983        writer.close().unwrap();
3984        Bytes::from(buf)
3985    }
3986
3987    fn data_page_encoding_mask(file: &Bytes) -> EncodingMask {
3988        let metadata = ParquetMetaDataReader::new().parse_and_finish(file).unwrap();
3989        *metadata
3990            .row_group(0)
3991            .column(0)
3992            .page_encoding_stats_mask()
3993            .unwrap()
3994    }
3995
3996    /// While a column is dictionary encoded the bloom filter is populated from the dictionary
3997    /// when it is flushed, so a chunk that stays dictionary encoded must still contain every value.
3998    #[test]
3999    fn string_column_bloom_filter_populated_from_dictionary() {
4000        let values: Vec<String> = (0..2000).map(|i| format!("value-{}", i % 10)).collect();
4001        let array = Arc::new(StringArray::from_iter_values(&values));
4002        let file = write_with_bloom_filter(array, 1024 * 1024);
4003        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
4004
4005        check_bloom_filter(
4006            vec![file],
4007            "col".to_string(),
4008            (0..10).map(|i| format!("value-{i}").into_bytes()).collect(),
4009            (10..20)
4010                .map(|i| format!("value-{i}").into_bytes())
4011                .collect(),
4012        );
4013    }
4014
4015    /// After falling back from dictionary encoding the filter holds the dictionary's values
4016    /// and every value written plain afterwards.
4017    #[test]
4018    fn string_column_bloom_filter_across_dictionary_fallback() {
4019        let values: Vec<String> = (0..2000).map(|i| format!("value-{i}")).collect();
4020        let array = Arc::new(StringArray::from_iter_values(&values));
4021        let file = write_with_bloom_filter(array, 1024);
4022        let encodings = data_page_encoding_mask(&file);
4023        assert!(
4024            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
4025            "expected dictionary and plain data pages, got {encodings:?}"
4026        );
4027
4028        check_bloom_filter(
4029            vec![file],
4030            "col".to_string(),
4031            values.into_iter().map(String::into_bytes).collect(),
4032            (2000..2010)
4033                .map(|i| format!("value-{i}").into_bytes())
4034                .collect(),
4035        );
4036    }
4037
4038    #[test]
4039    fn i64_column_bloom_filter_populated_from_dictionary() {
4040        let array = Arc::new(Int64Array::from_iter_values((0..2000).map(|i| i % 10)));
4041        let file = write_with_bloom_filter(array, 1024 * 1024);
4042        assert!(data_page_encoding_mask(&file).is_only(Encoding::RLE_DICTIONARY));
4043
4044        check_bloom_filter(
4045            vec![file],
4046            "col".to_string(),
4047            (0..10i64).collect(),
4048            (10..20i64).collect(),
4049        );
4050    }
4051
4052    #[test]
4053    fn i64_column_bloom_filter_across_dictionary_fallback() {
4054        let array = Arc::new(Int64Array::from_iter_values(0..2000i64));
4055        let file = write_with_bloom_filter(array, 1024);
4056        let encodings = data_page_encoding_mask(&file);
4057        assert!(
4058            encodings.is_set(Encoding::RLE_DICTIONARY) && encodings.is_set(Encoding::PLAIN),
4059            "expected dictionary and plain data pages, got {encodings:?}"
4060        );
4061
4062        check_bloom_filter(
4063            vec![file],
4064            "col".to_string(),
4065            (0..2000i64).collect(),
4066            (2000..2010i64).collect(),
4067        );
4068    }
4069
4070    /// Test that bloom filter folding produces correct results even when
4071    /// the configured NDV differs significantly from actual NDV.
4072    /// A large NDV means a larger initial filter that gets folded down;
4073    /// a small NDV means a smaller initial filter.
4074    #[test]
4075    #[cfg_attr(miri, ignore)] // Takes too long
4076    fn i32_column_bloom_filter_fixed_ndv() {
4077        let array = Arc::new(Int32Array::from_iter(0..SMALL_SIZE as i32));
4078
4079        // NDV much larger than actual distinct values — tests folding a large filter down
4080        let files = RoundTripTest::new(array.clone())
4081            .with_nullable(false)
4082            .with_bloom_filter(true)
4083            .with_bloom_filter_ndv(1_000_000)
4084            .run();
4085
4086        check_bloom_filter(
4087            files,
4088            "col".to_string(),
4089            (0..SMALL_SIZE as i32).collect(),
4090            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
4091        );
4092
4093        // NDV smaller than actual distinct values — tests the underestimate path
4094        let files = RoundTripTest::new(array)
4095            .with_nullable(false)
4096            .with_bloom_filter(true)
4097            .with_bloom_filter_ndv(3)
4098            .run();
4099
4100        check_bloom_filter(
4101            files,
4102            "col".to_string(),
4103            (0..SMALL_SIZE as i32).collect(),
4104            (SMALL_SIZE as i32 + 1..SMALL_SIZE as i32 + 10).collect(),
4105        );
4106    }
4107
4108    #[test]
4109    #[cfg_attr(miri, ignore)] // Takes too long
4110    fn binary_column_bloom_filter() {
4111        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
4112        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
4113        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
4114
4115        let array = Arc::new(BinaryArray::from_iter_values(many_vecs_iter));
4116        let files = RoundTripTest::new(array)
4117            .with_nullable(false)
4118            .with_bloom_filter(true)
4119            .run();
4120
4121        check_bloom_filter(
4122            files,
4123            "col".to_string(),
4124            many_vecs,
4125            vec![vec![(SMALL_SIZE + 1) as u8]],
4126        );
4127    }
4128
4129    #[test]
4130    #[cfg_attr(miri, ignore)] // Takes too long
4131    fn empty_string_null_column_bloom_filter() {
4132        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4133        let raw_strs = raw_values.iter().map(|s| s.as_str());
4134
4135        let array = Arc::new(StringArray::from_iter_values(raw_strs));
4136        let files = RoundTripTest::new(array)
4137            .with_nullable(false)
4138            .with_bloom_filter(true)
4139            .run();
4140
4141        let optional_raw_values: Vec<_> = raw_values
4142            .iter()
4143            .enumerate()
4144            .filter_map(|(i, v)| if i % 2 == 0 { None } else { Some(v.as_str()) })
4145            .collect();
4146        // For null slots, empty string should not be in bloom filter.
4147        check_bloom_filter(files, "col".to_string(), optional_raw_values, vec![""]);
4148    }
4149
4150    #[test]
4151    #[cfg_attr(miri, ignore)] // Takes too long
4152    fn large_binary_single_column() {
4153        let one_vec: Vec<u8> = (0..SMALL_SIZE as u8).collect();
4154        let many_vecs: Vec<_> = std::iter::repeat_n(one_vec, SMALL_SIZE).collect();
4155        let many_vecs_iter = many_vecs.iter().map(|v| v.as_slice());
4156
4157        // LargeBinaryArrays can't be built from Vec<Option<&str>>, so only call `values_required`
4158        values_required::<LargeBinaryArray, _>(many_vecs_iter);
4159    }
4160
4161    #[test]
4162    #[cfg_attr(miri, ignore)] // Takes too long
4163    fn fixed_size_binary_single_column() {
4164        let mut builder = FixedSizeBinaryBuilder::new(4);
4165        builder.append_value(b"0123").unwrap();
4166        builder.append_null();
4167        builder.append_value(b"8910").unwrap();
4168        builder.append_value(b"1112").unwrap();
4169        let array = Arc::new(builder.finish());
4170
4171        RoundTripTest::new(array).run();
4172    }
4173
4174    #[test]
4175    #[cfg_attr(miri, ignore)] // Takes too long
4176    fn string_single_column() {
4177        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4178        let raw_strs = raw_values.iter().map(|s| s.as_str());
4179
4180        required_and_optional::<StringArray, _>(raw_strs);
4181    }
4182
4183    #[test]
4184    #[cfg_attr(miri, ignore)] // Takes too long
4185    fn large_string_single_column() {
4186        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4187        let raw_strs = raw_values.iter().map(|s| s.as_str());
4188
4189        required_and_optional::<LargeStringArray, _>(raw_strs);
4190    }
4191
4192    #[test]
4193    #[cfg_attr(miri, ignore)] // Takes too long
4194    fn string_view_single_column() {
4195        let raw_values: Vec<_> = (0..SMALL_SIZE).map(|i| i.to_string()).collect();
4196        let raw_strs = raw_values.iter().map(|s| s.as_str());
4197
4198        required_and_optional::<StringViewArray, _>(raw_strs);
4199    }
4200
4201    #[test]
4202    fn null_list_single_column() {
4203        let null_field = Field::new_list_field(DataType::Null, true);
4204        let list_field = Field::new("emptylist", DataType::List(Arc::new(null_field)), true);
4205
4206        let schema = Schema::new(vec![list_field]);
4207
4208        // Build [[], null, [null, null]]
4209        let a_values = NullArray::new(2);
4210        let a_value_offsets = arrow::buffer::Buffer::from([0, 0, 0, 2].to_byte_slice());
4211        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
4212            DataType::Null,
4213            true,
4214        ))))
4215        .len(3)
4216        .add_buffer(a_value_offsets)
4217        .null_bit_buffer(Some(Buffer::from([0b00000101])))
4218        .add_child_data(a_values.into_data())
4219        .build()
4220        .unwrap();
4221
4222        let a = ListArray::from(a_list_data);
4223
4224        assert!(a.is_valid(0));
4225        assert!(!a.is_valid(1));
4226        assert!(a.is_valid(2));
4227
4228        assert_eq!(a.value(0).len(), 0);
4229        assert_eq!(a.value(2).len(), 2);
4230        assert_eq!(a.value(2).logical_nulls().unwrap().null_count(), 2);
4231
4232        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
4233        roundtrip(batch, None);
4234    }
4235
4236    #[test]
4237    #[cfg_attr(miri, ignore)] // Takes too long
4238    fn list_single_column() {
4239        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4240        let a_value_offsets = arrow::buffer::Buffer::from([0, 1, 3, 3, 6, 10].to_byte_slice());
4241        let a_list_data = ArrayData::builder(DataType::List(Arc::new(Field::new_list_field(
4242            DataType::Int32,
4243            false,
4244        ))))
4245        .len(5)
4246        .add_buffer(a_value_offsets)
4247        .null_bit_buffer(Some(Buffer::from([0b00011011])))
4248        .add_child_data(a_values.into_data())
4249        .build()
4250        .unwrap();
4251
4252        assert_eq!(a_list_data.null_count(), 1);
4253
4254        let a = ListArray::from(a_list_data);
4255        let values = Arc::new(a);
4256
4257        RoundTripTest::new(values).run();
4258    }
4259
4260    #[test]
4261    #[cfg_attr(miri, ignore)] // Takes too long
4262    fn large_list_single_column() {
4263        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4264        let a_value_offsets = arrow::buffer::Buffer::from([0i64, 1, 3, 3, 6, 10].to_byte_slice());
4265        let a_list_data = ArrayData::builder(DataType::LargeList(Arc::new(Field::new(
4266            "large_item",
4267            DataType::Int32,
4268            true,
4269        ))))
4270        .len(5)
4271        .add_buffer(a_value_offsets)
4272        .add_child_data(a_values.into_data())
4273        .null_bit_buffer(Some(Buffer::from([0b00011011])))
4274        .build()
4275        .unwrap();
4276
4277        // I think this setup is incorrect because this should pass
4278        assert_eq!(a_list_data.null_count(), 1);
4279
4280        let a = LargeListArray::from(a_list_data);
4281        let values = Arc::new(a);
4282
4283        RoundTripTest::new(values).run();
4284    }
4285
4286    #[test]
4287    #[cfg_attr(miri, ignore)] // Takes too long
4288    fn list_nested_nulls() {
4289        use arrow::datatypes::Int32Type;
4290        let data = vec![
4291            Some(vec![Some(1)]),
4292            Some(vec![Some(2), Some(3)]),
4293            None,
4294            Some(vec![Some(4), Some(5), None]),
4295            Some(vec![None]),
4296            Some(vec![Some(6), Some(7)]),
4297        ];
4298
4299        let list = ListArray::from_iter_primitive::<Int32Type, _, _>(data.clone());
4300        RoundTripTest::new(Arc::new(list)).run();
4301
4302        let list = LargeListArray::from_iter_primitive::<Int32Type, _, _>(data);
4303        RoundTripTest::new(Arc::new(list)).run();
4304    }
4305
4306    #[test]
4307    #[cfg_attr(miri, ignore)] // Takes too long
4308    fn list_utf8_view_selective_padding_roundtrip() {
4309        let item = Arc::new(Field::new_list_field(DataType::Utf8View, true));
4310        let mut builder = ListBuilder::new(StringViewBuilder::new()).with_field(item);
4311        builder.values().append_value("a");
4312        builder.values().append_null();
4313        builder.append(true);
4314        // The null parent list covers selective padding dropping values below
4315        // the list definition level while preserving the preceding item null.
4316        builder.append(false);
4317        // The long string covers the non-inlined Utf8View buffer path.
4318        builder.values().append_value("large payload over 12 bytes");
4319        builder.append(true);
4320
4321        RoundTripTest::new(Arc::new(builder.finish())).run();
4322    }
4323
4324    #[test]
4325    #[cfg_attr(miri, ignore)] // Takes too long
4326    fn struct_single_column() {
4327        let a_values = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
4328        let struct_field_a = Arc::new(Field::new("f", DataType::Int32, false));
4329        let s = StructArray::from(vec![(struct_field_a, Arc::new(a_values) as ArrayRef)]);
4330
4331        let values = Arc::new(s);
4332        RoundTripTest::new(values).with_nullable(false).run();
4333    }
4334
4335    #[test]
4336    fn list_and_map_coerced_names() {
4337        // Create map and list with non-Parquet naming
4338        let list_field =
4339            Field::new_list("my_list", Field::new("item", DataType::Int32, false), false);
4340        let map_field = Field::new_map(
4341            "my_map",
4342            "my_entries",
4343            Field::new("my_keys", DataType::Int32, false),
4344            Field::new("my_values", DataType::Int32, true),
4345            false,
4346            true,
4347        );
4348
4349        let list_array = create_random_array(&list_field, 100, 0.0, 0.0).unwrap();
4350        let map_array = create_random_array(&map_field, 100, 0.0, 0.0).unwrap();
4351
4352        let arrow_schema = Arc::new(Schema::new(vec![list_field, map_field]));
4353
4354        // Write data to Parquet but coerce names to match spec
4355        let props = Some(WriterProperties::builder().set_coerce_types(true).build());
4356        let file = tempfile::tempfile().unwrap();
4357        let mut writer =
4358            ArrowWriter::try_new(file.try_clone().unwrap(), arrow_schema.clone(), props).unwrap();
4359
4360        let batch = RecordBatch::try_new(arrow_schema, vec![list_array, map_array]).unwrap();
4361        writer.write(&batch).unwrap();
4362        let file_metadata = writer.close().unwrap();
4363
4364        let schema = file_metadata.file_metadata().schema();
4365        // Coerced name of "item" should be "element"
4366        let list_field = &schema.get_fields()[0].get_fields()[0];
4367        assert_eq!(list_field.get_fields()[0].name(), "element");
4368
4369        let map_field = &schema.get_fields()[1].get_fields()[0];
4370        // Coerced name of "entries" should be "key_value"
4371        assert_eq!(map_field.name(), "key_value");
4372        // Coerced name of "my_keys" should be "key"
4373        assert_eq!(map_field.get_fields()[0].name(), "key");
4374        // Coerced name of "my_values" should be "value"
4375        assert_eq!(map_field.get_fields()[1].name(), "value");
4376
4377        // Double check schema after reading from the file
4378        let reader = SerializedFileReader::new(file).unwrap();
4379        let file_schema = reader.metadata().file_metadata().schema();
4380        let fields = file_schema.get_fields();
4381        let list_field = &fields[0].get_fields()[0];
4382        assert_eq!(list_field.get_fields()[0].name(), "element");
4383        let map_field = &fields[1].get_fields()[0];
4384        assert_eq!(map_field.name(), "key_value");
4385        assert_eq!(map_field.get_fields()[0].name(), "key");
4386        assert_eq!(map_field.get_fields()[1].name(), "value");
4387    }
4388
4389    #[test]
4390    #[cfg_attr(miri, ignore)] // Takes too long
4391    fn fallback_flush_data_page() {
4392        //tests if the Fallback::flush_data_page clears all buffers correctly
4393        let raw_values: Vec<_> = (0..MEDIUM_SIZE).map(|i| i.to_string()).collect();
4394        let values = Arc::new(StringArray::from(raw_values));
4395        let encodings = vec![
4396            Encoding::DELTA_BYTE_ARRAY,
4397            Encoding::DELTA_LENGTH_BYTE_ARRAY,
4398        ];
4399        let data_type = values.data_type().clone();
4400        let schema = Arc::new(Schema::new(vec![Field::new("col", data_type, false)]));
4401        let expected_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4402
4403        let row_group_sizes = [1024, SMALL_SIZE, SMALL_SIZE / 2, SMALL_SIZE / 2 + 1, 10];
4404        let data_page_size_limit: usize = 32;
4405        let write_batch_size: usize = 16;
4406
4407        for encoding in &encodings {
4408            for row_group_size in row_group_sizes {
4409                let props = WriterProperties::builder()
4410                    .set_writer_version(WriterVersion::PARQUET_2_0)
4411                    .set_max_row_group_row_count(Some(row_group_size))
4412                    .set_dictionary_enabled(false)
4413                    .set_encoding(*encoding)
4414                    .set_data_page_size_limit(data_page_size_limit)
4415                    .set_write_batch_size(write_batch_size)
4416                    .build();
4417
4418                roundtrip_opts_with_array_validation(&expected_batch, props, |a, b| {
4419                    let string_array_a = StringArray::from(a.clone());
4420                    let string_array_b = StringArray::from(b.clone());
4421                    let vec_a: Vec<&str> = string_array_a.iter().map(|v| v.unwrap()).collect();
4422                    let vec_b: Vec<&str> = string_array_b.iter().map(|v| v.unwrap()).collect();
4423                    assert_eq!(
4424                        vec_a, vec_b,
4425                        "failed for encoder: {encoding:?} and row_group_size: {row_group_size:?}"
4426                    );
4427                });
4428            }
4429        }
4430    }
4431
4432    #[test]
4433    #[cfg_attr(miri, ignore)] // Takes too long
4434    fn arrow_writer_string_dictionary() {
4435        // define schema
4436        #[expect(deprecated)]
4437        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4438            "dictionary",
4439            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4440            true,
4441            42,
4442            true,
4443        )]));
4444
4445        // create some data
4446        let d: Int32DictionaryArray = [Some("alpha"), None, Some("beta"), Some("alpha")]
4447            .iter()
4448            .copied()
4449            .collect();
4450
4451        // build a record batch
4452        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4453    }
4454
4455    #[test]
4456    fn arrow_writer_test_type_compatibility() {
4457        fn ensure_compatible_write<T1, T2>(array1: T1, array2: T2, expected_result: T1)
4458        where
4459            T1: Array + 'static,
4460            T2: Array + 'static,
4461        {
4462            let schema1 = Arc::new(Schema::new(vec![Field::new(
4463                "a",
4464                array1.data_type().clone(),
4465                false,
4466            )]));
4467
4468            let file = tempfile().unwrap();
4469            let mut writer =
4470                ArrowWriter::try_new(file.try_clone().unwrap(), schema1.clone(), None).unwrap();
4471
4472            let rb1 = RecordBatch::try_new(schema1.clone(), vec![Arc::new(array1)]).unwrap();
4473            writer.write(&rb1).unwrap();
4474
4475            let schema2 = Arc::new(Schema::new(vec![Field::new(
4476                "a",
4477                array2.data_type().clone(),
4478                false,
4479            )]));
4480            let rb2 = RecordBatch::try_new(schema2, vec![Arc::new(array2)]).unwrap();
4481            writer.write(&rb2).unwrap();
4482
4483            writer.close().unwrap();
4484
4485            let mut record_batch_reader =
4486                ParquetRecordBatchReader::try_new(file.try_clone().unwrap(), 1024).unwrap();
4487            let actual_batch = record_batch_reader.next().unwrap().unwrap();
4488
4489            let expected_batch =
4490                RecordBatch::try_new(schema1, vec![Arc::new(expected_result)]).unwrap();
4491            assert_eq!(actual_batch, expected_batch);
4492        }
4493
4494        // check compatibility between native and dictionaries
4495
4496        ensure_compatible_write(
4497            DictionaryArray::new(
4498                UInt8Array::from_iter_values(vec![0]),
4499                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4500            ),
4501            StringArray::from_iter_values(vec!["barquet"]),
4502            DictionaryArray::new(
4503                UInt8Array::from_iter_values(vec![0, 1]),
4504                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4505            ),
4506        );
4507
4508        ensure_compatible_write(
4509            StringArray::from_iter_values(vec!["parquet"]),
4510            DictionaryArray::new(
4511                UInt8Array::from_iter_values(vec![0]),
4512                Arc::new(StringArray::from_iter_values(vec!["barquet"])),
4513            ),
4514            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4515        );
4516
4517        // check compatibility between dictionaries with different key types
4518
4519        ensure_compatible_write(
4520            DictionaryArray::new(
4521                UInt8Array::from_iter_values(vec![0]),
4522                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4523            ),
4524            DictionaryArray::new(
4525                UInt16Array::from_iter_values(vec![0]),
4526                Arc::new(StringArray::from_iter_values(vec!["barquet"])),
4527            ),
4528            DictionaryArray::new(
4529                UInt8Array::from_iter_values(vec![0, 1]),
4530                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4531            ),
4532        );
4533
4534        // check compatibility between dictionaries with different value types
4535        ensure_compatible_write(
4536            DictionaryArray::new(
4537                UInt8Array::from_iter_values(vec![0]),
4538                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4539            ),
4540            DictionaryArray::new(
4541                UInt8Array::from_iter_values(vec![0]),
4542                Arc::new(LargeStringArray::from_iter_values(vec!["barquet"])),
4543            ),
4544            DictionaryArray::new(
4545                UInt8Array::from_iter_values(vec![0, 1]),
4546                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4547            ),
4548        );
4549
4550        // check compatibility between a dictionary and a native array with a different type
4551        ensure_compatible_write(
4552            DictionaryArray::new(
4553                UInt8Array::from_iter_values(vec![0]),
4554                Arc::new(StringArray::from_iter_values(vec!["parquet"])),
4555            ),
4556            LargeStringArray::from_iter_values(vec!["barquet"]),
4557            DictionaryArray::new(
4558                UInt8Array::from_iter_values(vec![0, 1]),
4559                Arc::new(StringArray::from_iter_values(vec!["parquet", "barquet"])),
4560            ),
4561        );
4562
4563        // check compatibility for string types
4564
4565        ensure_compatible_write(
4566            StringArray::from_iter_values(vec!["parquet"]),
4567            LargeStringArray::from_iter_values(vec!["barquet"]),
4568            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4569        );
4570
4571        ensure_compatible_write(
4572            LargeStringArray::from_iter_values(vec!["parquet"]),
4573            StringArray::from_iter_values(vec!["barquet"]),
4574            LargeStringArray::from_iter_values(vec!["parquet", "barquet"]),
4575        );
4576
4577        ensure_compatible_write(
4578            StringArray::from_iter_values(vec!["parquet"]),
4579            StringViewArray::from_iter_values(vec!["barquet"]),
4580            StringArray::from_iter_values(vec!["parquet", "barquet"]),
4581        );
4582
4583        ensure_compatible_write(
4584            StringViewArray::from_iter_values(vec!["parquet"]),
4585            StringArray::from_iter_values(vec!["barquet"]),
4586            StringViewArray::from_iter_values(vec!["parquet", "barquet"]),
4587        );
4588
4589        ensure_compatible_write(
4590            LargeStringArray::from_iter_values(vec!["parquet"]),
4591            StringViewArray::from_iter_values(vec!["barquet"]),
4592            LargeStringArray::from_iter_values(vec!["parquet", "barquet"]),
4593        );
4594
4595        ensure_compatible_write(
4596            StringViewArray::from_iter_values(vec!["parquet"]),
4597            LargeStringArray::from_iter_values(vec!["barquet"]),
4598            StringViewArray::from_iter_values(vec!["parquet", "barquet"]),
4599        );
4600
4601        // check compatibility for binary types
4602
4603        ensure_compatible_write(
4604            BinaryArray::from_iter_values(vec![b"parquet"]),
4605            LargeBinaryArray::from_iter_values(vec![b"barquet"]),
4606            BinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4607        );
4608
4609        ensure_compatible_write(
4610            LargeBinaryArray::from_iter_values(vec![b"parquet"]),
4611            BinaryArray::from_iter_values(vec![b"barquet"]),
4612            LargeBinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4613        );
4614
4615        ensure_compatible_write(
4616            BinaryArray::from_iter_values(vec![b"parquet"]),
4617            BinaryViewArray::from_iter_values(vec![b"barquet"]),
4618            BinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4619        );
4620
4621        ensure_compatible_write(
4622            BinaryViewArray::from_iter_values(vec![b"parquet"]),
4623            BinaryArray::from_iter_values(vec![b"barquet"]),
4624            BinaryViewArray::from_iter_values(vec![b"parquet", b"barquet"]),
4625        );
4626
4627        ensure_compatible_write(
4628            BinaryViewArray::from_iter_values(vec![b"parquet"]),
4629            LargeBinaryArray::from_iter_values(vec![b"barquet"]),
4630            BinaryViewArray::from_iter_values(vec![b"parquet", b"barquet"]),
4631        );
4632
4633        ensure_compatible_write(
4634            LargeBinaryArray::from_iter_values(vec![b"parquet"]),
4635            BinaryViewArray::from_iter_values(vec![b"barquet"]),
4636            LargeBinaryArray::from_iter_values(vec![b"parquet", b"barquet"]),
4637        );
4638
4639        // check compatibility for list types
4640
4641        let list_field_metadata = HashMap::from_iter(vec![(
4642            PARQUET_FIELD_ID_META_KEY.to_string(),
4643            "1".to_string(),
4644        )]);
4645        let list_field = Field::new_list_field(DataType::Int32, false);
4646
4647        let values1 = Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4]));
4648        let offsets1 = OffsetBuffer::new(vec![0, 2, 5].into());
4649
4650        let values2 = Arc::new(Int32Array::from(vec![5, 6, 7, 8, 9]));
4651        let offsets2 = OffsetBuffer::new(vec![0, 3, 5].into());
4652
4653        let values_expected = Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4654        let offsets_expected = OffsetBuffer::new(vec![0, 2, 5, 8, 10].into());
4655
4656        ensure_compatible_write(
4657            // when the initial schema has the metadata ...
4658            ListArray::try_new(
4659                Arc::new(
4660                    list_field
4661                        .clone()
4662                        .with_metadata(list_field_metadata.clone()),
4663                ),
4664                offsets1,
4665                values1,
4666                None,
4667            )
4668            .unwrap(),
4669            // ... and some intermediate schema doesn't have the metadata
4670            ListArray::try_new(Arc::new(list_field.clone()), offsets2, values2, None).unwrap(),
4671            // ... the write will still go through, and the resulting schema will inherit the initial metadata
4672            ListArray::try_new(
4673                Arc::new(
4674                    list_field
4675                        .clone()
4676                        .with_metadata(list_field_metadata.clone()),
4677                ),
4678                offsets_expected,
4679                values_expected,
4680                None,
4681            )
4682            .unwrap(),
4683        );
4684    }
4685
4686    #[test]
4687    #[cfg_attr(miri, ignore)] // Takes too long
4688    fn arrow_writer_primitive_dictionary() {
4689        // define schema
4690        #[expect(deprecated)]
4691        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4692            "dictionary",
4693            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::UInt32)),
4694            true,
4695            42,
4696            true,
4697        )]));
4698
4699        // create some data
4700        let mut builder = PrimitiveDictionaryBuilder::<UInt8Type, UInt32Type>::new();
4701        builder.append(12345678).unwrap();
4702        builder.append_null();
4703        builder.append(22345678).unwrap();
4704        builder.append(12345678).unwrap();
4705        let d = builder.finish();
4706
4707        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4708    }
4709
4710    #[test]
4711    #[cfg_attr(miri, ignore)] // Takes too long
4712    fn arrow_writer_decimal32_dictionary() {
4713        let integers = vec![12345, 56789, 34567];
4714
4715        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4716
4717        let values = Decimal32Array::from(integers.clone())
4718            .with_precision_and_scale(5, 2)
4719            .unwrap();
4720
4721        let array = DictionaryArray::new(keys, Arc::new(values));
4722        RoundTripTest::new(Arc::new(array.clone())).run();
4723
4724        let values = Decimal32Array::from(integers)
4725            .with_precision_and_scale(9, 2)
4726            .unwrap();
4727
4728        let array = array.with_values(Arc::new(values));
4729        RoundTripTest::new(Arc::new(array)).run();
4730    }
4731
4732    #[test]
4733    #[cfg_attr(miri, ignore)] // Takes too long
4734    fn arrow_writer_decimal64_dictionary() {
4735        let integers = vec![12345, 56789, 34567];
4736
4737        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4738
4739        let values = Decimal64Array::from(integers.clone())
4740            .with_precision_and_scale(5, 2)
4741            .unwrap();
4742
4743        let array = DictionaryArray::new(keys, Arc::new(values));
4744        RoundTripTest::new(Arc::new(array.clone())).run();
4745
4746        let values = Decimal64Array::from(integers)
4747            .with_precision_and_scale(12, 2)
4748            .unwrap();
4749
4750        let array = array.with_values(Arc::new(values));
4751        RoundTripTest::new(Arc::new(array)).run();
4752    }
4753
4754    #[test]
4755    #[cfg_attr(miri, ignore)] // Takes too long
4756    fn arrow_writer_decimal128_dictionary() {
4757        let integers = vec![12345, 56789, 34567];
4758
4759        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4760
4761        let values = Decimal128Array::from(integers.clone())
4762            .with_precision_and_scale(5, 2)
4763            .unwrap();
4764
4765        let array = DictionaryArray::new(keys, Arc::new(values));
4766        RoundTripTest::new(Arc::new(array.clone())).run();
4767
4768        let values = Decimal128Array::from(integers)
4769            .with_precision_and_scale(12, 2)
4770            .unwrap();
4771
4772        let array = array.with_values(Arc::new(values));
4773        RoundTripTest::new(Arc::new(array)).run();
4774    }
4775
4776    #[test]
4777    #[cfg_attr(miri, ignore)] // Takes too long
4778    fn arrow_writer_decimal256_dictionary() {
4779        let integers = vec![
4780            i256::from_i128(12345),
4781            i256::from_i128(56789),
4782            i256::from_i128(34567),
4783        ];
4784
4785        let keys = UInt8Array::from(vec![Some(0), None, Some(1), Some(2), Some(1)]);
4786
4787        let values = Decimal256Array::from(integers.clone())
4788            .with_precision_and_scale(5, 2)
4789            .unwrap();
4790
4791        let array = DictionaryArray::new(keys, Arc::new(values));
4792        RoundTripTest::new(Arc::new(array.clone())).run();
4793
4794        let values = Decimal256Array::from(integers)
4795            .with_precision_and_scale(12, 2)
4796            .unwrap();
4797
4798        let array = array.with_values(Arc::new(values));
4799        RoundTripTest::new(Arc::new(array)).run();
4800    }
4801
4802    #[test]
4803    #[cfg_attr(miri, ignore)] // Takes too long
4804    fn arrow_writer_string_dictionary_unsigned_index() {
4805        // define schema
4806        #[expect(deprecated)]
4807        let schema = Arc::new(Schema::new(vec![Field::new_dict(
4808            "dictionary",
4809            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
4810            true,
4811            42,
4812            true,
4813        )]));
4814
4815        // create some data
4816        let d: UInt8DictionaryArray = [Some("alpha"), None, Some("beta"), Some("alpha")]
4817            .iter()
4818            .copied()
4819            .collect();
4820
4821        RoundTripTest::new(Arc::new(d)).with_schema(schema).run();
4822    }
4823
4824    #[test]
4825    #[cfg_attr(miri, ignore)] // Takes too long
4826    fn u32_min_max() {
4827        // check values roundtrip through parquet
4828        let src = [
4829            u32::MIN,
4830            1,
4831            (i32::MAX as u32) - 1,
4832            i32::MAX as u32,
4833            (i32::MAX as u32) + 1,
4834            u32::MAX - 1,
4835            u32::MAX,
4836        ];
4837        let values = Arc::new(UInt32Array::from_iter_values(src.iter().copied()));
4838        let files = RoundTripTest::new(values).with_nullable(false).run();
4839
4840        for file in files {
4841            // check statistics are valid
4842            let reader = SerializedFileReader::new(file).unwrap();
4843            let metadata = reader.metadata();
4844
4845            let mut row_offset = 0;
4846            for row_group in metadata.row_groups() {
4847                assert_eq!(row_group.num_columns(), 1);
4848                let column = row_group.column(0);
4849
4850                let num_values = column.num_values() as usize;
4851                let src_slice = &src[row_offset..row_offset + num_values];
4852                row_offset += column.num_values() as usize;
4853
4854                let stats = column.statistics().unwrap();
4855                if let Statistics::Int32(stats) = stats {
4856                    assert_eq!(
4857                        *stats.min_opt().unwrap() as u32,
4858                        *src_slice.iter().min().unwrap()
4859                    );
4860                    assert_eq!(
4861                        *stats.max_opt().unwrap() as u32,
4862                        *src_slice.iter().max().unwrap()
4863                    );
4864                } else {
4865                    panic!("Statistics::Int32 missing")
4866                }
4867            }
4868        }
4869    }
4870
4871    #[test]
4872    #[cfg_attr(miri, ignore)] // Takes too long
4873    fn u64_min_max() {
4874        // check values roundtrip through parquet
4875        let src = [
4876            u64::MIN,
4877            1,
4878            (i64::MAX as u64) - 1,
4879            i64::MAX as u64,
4880            (i64::MAX as u64) + 1,
4881            u64::MAX - 1,
4882            u64::MAX,
4883        ];
4884        let values = Arc::new(UInt64Array::from_iter_values(src.iter().copied()));
4885        let files = RoundTripTest::new(values).with_nullable(false).run();
4886
4887        for file in files {
4888            // check statistics are valid
4889            let reader = SerializedFileReader::new(file).unwrap();
4890            let metadata = reader.metadata();
4891
4892            let mut row_offset = 0;
4893            for row_group in metadata.row_groups() {
4894                assert_eq!(row_group.num_columns(), 1);
4895                let column = row_group.column(0);
4896
4897                let num_values = column.num_values() as usize;
4898                let src_slice = &src[row_offset..row_offset + num_values];
4899                row_offset += column.num_values() as usize;
4900
4901                let stats = column.statistics().unwrap();
4902                if let Statistics::Int64(stats) = stats {
4903                    assert_eq!(
4904                        *stats.min_opt().unwrap() as u64,
4905                        *src_slice.iter().min().unwrap()
4906                    );
4907                    assert_eq!(
4908                        *stats.max_opt().unwrap() as u64,
4909                        *src_slice.iter().max().unwrap()
4910                    );
4911                } else {
4912                    panic!("Statistics::Int64 missing")
4913                }
4914            }
4915        }
4916    }
4917
4918    #[test]
4919    #[cfg_attr(miri, ignore)] // Takes too long
4920    fn statistics_null_counts_only_nulls() {
4921        // check that null-count statistics for "only NULL"-columns are correct
4922        let values = Arc::new(UInt64Array::from(vec![None, None]));
4923        let files = RoundTripTest::new(values).run();
4924
4925        for file in files {
4926            // check statistics are valid
4927            let reader = SerializedFileReader::new(file).unwrap();
4928            let metadata = reader.metadata();
4929            assert_eq!(metadata.num_row_groups(), 1);
4930            let row_group = metadata.row_group(0);
4931            assert_eq!(row_group.num_columns(), 1);
4932            let column = row_group.column(0);
4933            let stats = column.statistics().unwrap();
4934            assert_eq!(stats.null_count_opt(), Some(2));
4935        }
4936    }
4937
4938    #[test]
4939    #[cfg_attr(miri, ignore)] // Takes too long
4940    fn test_list_of_struct_roundtrip() {
4941        // define schema
4942        let int_field = Field::new("a", DataType::Int32, true);
4943        let int_field2 = Field::new("b", DataType::Int32, true);
4944
4945        let int_builder = Int32Builder::with_capacity(10);
4946        let int_builder2 = Int32Builder::with_capacity(10);
4947
4948        let struct_builder = StructBuilder::new(
4949            vec![int_field, int_field2],
4950            vec![Box::new(int_builder), Box::new(int_builder2)],
4951        );
4952        let mut list_builder = ListBuilder::new(struct_builder);
4953
4954        // Construct the following array
4955        // [{a: 1, b: 2}], [], null, [null, null], [{a: null, b: 3}], [{a: 2, b: null}]
4956
4957        // [{a: 1, b: 2}]
4958        let values = list_builder.values();
4959        values
4960            .field_builder::<Int32Builder>(0)
4961            .unwrap()
4962            .append_value(1);
4963        values
4964            .field_builder::<Int32Builder>(1)
4965            .unwrap()
4966            .append_value(2);
4967        values.append(true);
4968        list_builder.append(true);
4969
4970        // []
4971        list_builder.append(true);
4972
4973        // null
4974        list_builder.append(false);
4975
4976        // [null, null]
4977        let values = list_builder.values();
4978        values
4979            .field_builder::<Int32Builder>(0)
4980            .unwrap()
4981            .append_null();
4982        values
4983            .field_builder::<Int32Builder>(1)
4984            .unwrap()
4985            .append_null();
4986        values.append(false);
4987        values
4988            .field_builder::<Int32Builder>(0)
4989            .unwrap()
4990            .append_null();
4991        values
4992            .field_builder::<Int32Builder>(1)
4993            .unwrap()
4994            .append_null();
4995        values.append(false);
4996        list_builder.append(true);
4997
4998        // [{a: null, b: 3}]
4999        let values = list_builder.values();
5000        values
5001            .field_builder::<Int32Builder>(0)
5002            .unwrap()
5003            .append_null();
5004        values
5005            .field_builder::<Int32Builder>(1)
5006            .unwrap()
5007            .append_value(3);
5008        values.append(true);
5009        list_builder.append(true);
5010
5011        // [{a: 2, b: null}]
5012        let values = list_builder.values();
5013        values
5014            .field_builder::<Int32Builder>(0)
5015            .unwrap()
5016            .append_value(2);
5017        values
5018            .field_builder::<Int32Builder>(1)
5019            .unwrap()
5020            .append_null();
5021        values.append(true);
5022        list_builder.append(true);
5023
5024        let array = Arc::new(list_builder.finish());
5025
5026        RoundTripTest::new(array).run();
5027    }
5028
5029    fn row_group_sizes(metadata: &ParquetMetaData) -> Vec<i64> {
5030        metadata.row_groups().iter().map(|x| x.num_rows()).collect()
5031    }
5032
5033    #[test]
5034    fn test_aggregates_records() {
5035        let arrays = [
5036            Int32Array::from((0..100).collect::<Vec<_>>()),
5037            Int32Array::from((0..50).collect::<Vec<_>>()),
5038            Int32Array::from((200..500).collect::<Vec<_>>()),
5039        ];
5040
5041        let schema = Arc::new(Schema::new(vec![Field::new(
5042            "int",
5043            ArrowDataType::Int32,
5044            false,
5045        )]));
5046
5047        let file = tempfile::tempfile().unwrap();
5048
5049        let props = WriterProperties::builder()
5050            .set_max_row_group_row_count(Some(200))
5051            .build();
5052
5053        let mut writer =
5054            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
5055
5056        for array in arrays {
5057            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
5058            writer.write(&batch).unwrap();
5059        }
5060
5061        writer.close().unwrap();
5062
5063        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
5064        assert_eq!(&row_group_sizes(builder.metadata()), &[200, 200, 50]);
5065
5066        let batches = builder
5067            .with_batch_size(100)
5068            .build()
5069            .unwrap()
5070            .collect::<ArrowResult<Vec<_>>>()
5071            .unwrap();
5072
5073        assert_eq!(batches.len(), 5);
5074        assert!(batches.iter().all(|x| x.num_columns() == 1));
5075
5076        let batch_sizes: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
5077
5078        assert_eq!(&batch_sizes, &[100, 100, 100, 100, 50]);
5079
5080        let values: Vec<_> = batches
5081            .iter()
5082            .flat_map(|x| {
5083                x.column(0)
5084                    .as_any()
5085                    .downcast_ref::<Int32Array>()
5086                    .unwrap()
5087                    .values()
5088                    .iter()
5089                    .copied()
5090            })
5091            .collect();
5092
5093        let expected_values: Vec<_> = [0..100, 0..50, 200..500].into_iter().flatten().collect();
5094        assert_eq!(&values, &expected_values)
5095    }
5096
5097    #[test]
5098    fn complex_aggregate() {
5099        // Tests aggregating nested data
5100        let field_a = Arc::new(Field::new("leaf_a", DataType::Int32, false));
5101        let field_b = Arc::new(Field::new("leaf_b", DataType::Int32, true));
5102        let struct_a = Arc::new(Field::new(
5103            "struct_a",
5104            DataType::Struct(vec![field_a.clone(), field_b.clone()].into()),
5105            true,
5106        ));
5107
5108        let list_a = Arc::new(Field::new("list", DataType::List(struct_a), true));
5109        let struct_b = Arc::new(Field::new(
5110            "struct_b",
5111            DataType::Struct(vec![list_a.clone()].into()),
5112            false,
5113        ));
5114
5115        let schema = Arc::new(Schema::new(vec![struct_b]));
5116
5117        // create nested data
5118        let field_a_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
5119        let field_b_array =
5120            Int32Array::from_iter(vec![Some(1), None, Some(2), None, None, Some(6)]);
5121
5122        let struct_a_array = StructArray::from(vec![
5123            (field_a.clone(), Arc::new(field_a_array) as ArrayRef),
5124            (field_b.clone(), Arc::new(field_b_array) as ArrayRef),
5125        ]);
5126
5127        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
5128            .len(5)
5129            .add_buffer(Buffer::from_iter(vec![
5130                0_i32, 1_i32, 1_i32, 3_i32, 3_i32, 5_i32,
5131            ]))
5132            .null_bit_buffer(Some(Buffer::from_iter(vec![
5133                true, false, true, false, true,
5134            ])))
5135            .child_data(vec![struct_a_array.into_data()])
5136            .build()
5137            .unwrap();
5138
5139        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
5140        let struct_b_array = StructArray::from(vec![(list_a.clone(), list_a_array)]);
5141
5142        let batch1 =
5143            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
5144                .unwrap();
5145
5146        let field_a_array = Int32Array::from(vec![6, 7, 8, 9, 10]);
5147        let field_b_array = Int32Array::from_iter(vec![None, None, None, Some(1), None]);
5148
5149        let struct_a_array = StructArray::from(vec![
5150            (field_a, Arc::new(field_a_array) as ArrayRef),
5151            (field_b, Arc::new(field_b_array) as ArrayRef),
5152        ]);
5153
5154        let list_data = ArrayDataBuilder::new(list_a.data_type().clone())
5155            .len(2)
5156            .add_buffer(Buffer::from_iter(vec![0_i32, 4_i32, 5_i32]))
5157            .child_data(vec![struct_a_array.into_data()])
5158            .build()
5159            .unwrap();
5160
5161        let list_a_array = Arc::new(ListArray::from(list_data)) as ArrayRef;
5162        let struct_b_array = StructArray::from(vec![(list_a, list_a_array)]);
5163
5164        let batch2 =
5165            RecordBatch::try_from_iter(vec![("struct_b", Arc::new(struct_b_array) as ArrayRef)])
5166                .unwrap();
5167
5168        let batches = &[batch1, batch2];
5169
5170        // Verify data is as expected
5171
5172        let expected = r"
5173            +-------------------------------------------------------------------------------------------------------+
5174            | struct_b                                                                                              |
5175            +-------------------------------------------------------------------------------------------------------+
5176            | {list: [{leaf_a: 1, leaf_b: 1}]}                                                                      |
5177            | {list: }                                                                                              |
5178            | {list: [{leaf_a: 2, leaf_b: }, {leaf_a: 3, leaf_b: 2}]}                                               |
5179            | {list: }                                                                                              |
5180            | {list: [{leaf_a: 4, leaf_b: }, {leaf_a: 5, leaf_b: }]}                                                |
5181            | {list: [{leaf_a: 6, leaf_b: }, {leaf_a: 7, leaf_b: }, {leaf_a: 8, leaf_b: }, {leaf_a: 9, leaf_b: 1}]} |
5182            | {list: [{leaf_a: 10, leaf_b: }]}                                                                      |
5183            +-------------------------------------------------------------------------------------------------------+
5184        ".trim().split('\n').map(|x| x.trim()).collect::<Vec<_>>().join("\n");
5185
5186        let actual = pretty_format_batches(batches).unwrap().to_string();
5187        assert_eq!(actual, expected);
5188
5189        // Write data
5190        let file = tempfile::tempfile().unwrap();
5191        let props = WriterProperties::builder()
5192            .set_max_row_group_row_count(Some(6))
5193            .build();
5194
5195        let mut writer =
5196            ArrowWriter::try_new(file.try_clone().unwrap(), schema, Some(props)).unwrap();
5197
5198        for batch in batches {
5199            writer.write(batch).unwrap();
5200        }
5201        writer.close().unwrap();
5202
5203        // Read Data
5204        // Should have written entire first batch and first row of second to the first row group
5205        // leaving a single row in the second row group
5206
5207        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
5208        assert_eq!(&row_group_sizes(builder.metadata()), &[6, 1]);
5209
5210        let batches = builder
5211            .with_batch_size(2)
5212            .build()
5213            .unwrap()
5214            .collect::<ArrowResult<Vec<_>>>()
5215            .unwrap();
5216
5217        assert_eq!(batches.len(), 4);
5218        let batch_counts: Vec<_> = batches.iter().map(|x| x.num_rows()).collect();
5219        assert_eq!(&batch_counts, &[2, 2, 2, 1]);
5220
5221        let actual = pretty_format_batches(&batches).unwrap().to_string();
5222        assert_eq!(actual, expected);
5223    }
5224
5225    #[test]
5226    fn test_arrow_writer_metadata() {
5227        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5228        let file_schema = batch_schema.clone().with_metadata([("foo", "bar")]);
5229
5230        let batch = RecordBatch::try_new(
5231            Arc::new(batch_schema),
5232            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5233        )
5234        .unwrap();
5235
5236        let mut buf = Vec::with_capacity(1024);
5237        let mut writer = ArrowWriter::try_new(&mut buf, Arc::new(file_schema), None).unwrap();
5238        writer.write(&batch).unwrap();
5239        writer.close().unwrap();
5240    }
5241
5242    #[test]
5243    fn test_arrow_writer_nullable() {
5244        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5245        let file_schema = Schema::new(vec![Field::new("int32", DataType::Int32, true)]);
5246        let file_schema = Arc::new(file_schema);
5247
5248        let batch = RecordBatch::try_new(
5249            Arc::new(batch_schema),
5250            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5251        )
5252        .unwrap();
5253
5254        let mut buf = Vec::with_capacity(1024);
5255        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
5256        writer.write(&batch).unwrap();
5257        writer.close().unwrap();
5258
5259        let mut read = ParquetRecordBatchReader::try_new(Bytes::from(buf), 1024).unwrap();
5260        let back = read.next().unwrap().unwrap();
5261        assert_eq!(back.schema(), file_schema);
5262        assert_ne!(back.schema(), batch.schema());
5263        assert_eq!(back.column(0).as_ref(), batch.column(0).as_ref());
5264    }
5265
5266    #[test]
5267    fn in_progress_accounting() {
5268        // define schema
5269        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
5270
5271        // create some data
5272        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
5273
5274        // build a record batch
5275        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap();
5276
5277        let mut writer = ArrowWriter::try_new(vec![], batch.schema(), None).unwrap();
5278
5279        // starts empty
5280        assert_eq!(writer.in_progress_size(), 0);
5281        assert_eq!(writer.in_progress_rows(), 0);
5282        assert_eq!(writer.memory_size(), 0);
5283        assert_eq!(writer.bytes_written(), 4); // Initial header
5284        writer.write(&batch).unwrap();
5285
5286        // updated on write
5287        let initial_size = writer.in_progress_size();
5288        assert!(initial_size > 0);
5289        assert_eq!(writer.in_progress_rows(), 5);
5290        let initial_memory = writer.memory_size();
5291        assert!(initial_memory > 0);
5292        // memory estimate is larger than estimated encoded size
5293        assert!(
5294            initial_size <= initial_memory,
5295            "{initial_size} <= {initial_memory}"
5296        );
5297
5298        // updated on second write
5299        writer.write(&batch).unwrap();
5300        assert!(writer.in_progress_size() > initial_size);
5301        assert_eq!(writer.in_progress_rows(), 10);
5302        assert!(writer.memory_size() > initial_memory);
5303        assert!(
5304            writer.in_progress_size() <= writer.memory_size(),
5305            "in_progress_size {} <= memory_size {}",
5306            writer.in_progress_size(),
5307            writer.memory_size()
5308        );
5309
5310        // in progress tracking is cleared, but the overall data written is updated
5311        let pre_flush_bytes_written = writer.bytes_written();
5312        writer.flush().unwrap();
5313        assert_eq!(writer.in_progress_size(), 0);
5314        assert_eq!(writer.memory_size(), 0);
5315        assert!(writer.bytes_written() > pre_flush_bytes_written);
5316
5317        writer.close().unwrap();
5318    }
5319
5320    #[test]
5321    fn test_writer_all_null() {
5322        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
5323        let b = Int32Array::new(vec![0; 5].into(), Some(NullBuffer::new_null(5)));
5324        let batch = RecordBatch::try_from_iter(vec![
5325            ("a", Arc::new(a) as ArrayRef),
5326            ("b", Arc::new(b) as ArrayRef),
5327        ])
5328        .unwrap();
5329
5330        let mut buf = Vec::with_capacity(1024);
5331        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
5332        writer.write(&batch).unwrap();
5333        writer.close().unwrap();
5334
5335        let bytes = Bytes::from(buf);
5336        let options = ReadOptionsBuilder::new().with_page_index().build();
5337        let reader = SerializedFileReader::new_with_options(bytes, options).unwrap();
5338        let index = reader.metadata().page_index().unwrap();
5339
5340        assert_eq!(index.num_data_pages(0, 0), Some(1)); // 1 page
5341        assert_eq!(index.num_data_pages(0, 1), Some(1)); // 1 page
5342    }
5343
5344    #[test]
5345    fn test_disabled_statistics_with_page() {
5346        let file_schema = Schema::new(vec![
5347            Field::new("a", DataType::Utf8, true),
5348            Field::new("b", DataType::Utf8, true),
5349        ]);
5350        let file_schema = Arc::new(file_schema);
5351
5352        let batch = RecordBatch::try_new(
5353            file_schema.clone(),
5354            vec![
5355                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
5356                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
5357            ],
5358        )
5359        .unwrap();
5360
5361        let props = WriterProperties::builder()
5362            .set_statistics_enabled(EnabledStatistics::None)
5363            .set_column_statistics_enabled("a".into(), EnabledStatistics::Page)
5364            .build();
5365
5366        let mut buf = Vec::with_capacity(1024);
5367        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
5368        writer.write(&batch).unwrap();
5369
5370        let metadata = writer.close().unwrap();
5371        assert_eq!(metadata.num_row_groups(), 1);
5372        let row_group = metadata.row_group(0);
5373        assert_eq!(row_group.num_columns(), 2);
5374        // Column "a" has both offset and column index, as requested
5375        assert!(row_group.column(0).offset_index_offset().is_some());
5376        assert!(row_group.column(0).column_index_offset().is_some());
5377        // Column "b" should only have offset index
5378        assert!(row_group.column(1).offset_index_offset().is_some());
5379        assert!(row_group.column(1).column_index_offset().is_none());
5380
5381        let options = ReadOptionsBuilder::new().with_page_index().build();
5382        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
5383
5384        let row_group = reader.get_row_group(0).unwrap();
5385        let a_col = row_group.metadata().column(0);
5386        let b_col = row_group.metadata().column(1);
5387
5388        // Column chunk of column "a" should have chunk level statistics
5389        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
5390            let min = byte_array_stats.min_opt().unwrap();
5391            let max = byte_array_stats.max_opt().unwrap();
5392
5393            assert_eq!(min.as_bytes(), b"a");
5394            assert_eq!(max.as_bytes(), b"d");
5395        } else {
5396            panic!("expecting Statistics::ByteArray");
5397        }
5398
5399        // The column chunk for column "b" shouldn't have statistics
5400        assert!(b_col.statistics().is_none());
5401
5402        let page_index = reader.metadata().page_index().unwrap();
5403
5404        let a_idx = page_index.column_index(0, 0);
5405        assert!(
5406            matches!(a_idx, Some(ColumnIndexMetaData::BYTE_ARRAY(_))),
5407            "{a_idx:?}"
5408        );
5409        let b_idx = page_index.column_index(0, 1);
5410        assert!(b_idx.is_none(), "{b_idx:?}");
5411    }
5412
5413    #[test]
5414    fn test_disabled_statistics_with_chunk() {
5415        let file_schema = Schema::new(vec![
5416            Field::new("a", DataType::Utf8, true),
5417            Field::new("b", DataType::Utf8, true),
5418        ]);
5419        let file_schema = Arc::new(file_schema);
5420
5421        let batch = RecordBatch::try_new(
5422            file_schema.clone(),
5423            vec![
5424                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])) as _,
5425                Arc::new(StringArray::from(vec!["w", "x", "y", "z"])) as _,
5426            ],
5427        )
5428        .unwrap();
5429
5430        let props = WriterProperties::builder()
5431            .set_statistics_enabled(EnabledStatistics::None)
5432            .set_column_statistics_enabled("a".into(), EnabledStatistics::Chunk)
5433            .build();
5434
5435        let mut buf = Vec::with_capacity(1024);
5436        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), Some(props)).unwrap();
5437        writer.write(&batch).unwrap();
5438
5439        let metadata = writer.close().unwrap();
5440        assert_eq!(metadata.num_row_groups(), 1);
5441        let row_group = metadata.row_group(0);
5442        assert_eq!(row_group.num_columns(), 2);
5443        // Column "a" should only have offset index
5444        assert!(row_group.column(0).offset_index_offset().is_some());
5445        assert!(row_group.column(0).column_index_offset().is_none());
5446        // Column "b" should only have offset index
5447        assert!(row_group.column(1).offset_index_offset().is_some());
5448        assert!(row_group.column(1).column_index_offset().is_none());
5449
5450        let options = ReadOptionsBuilder::new().with_page_index().build();
5451        let reader = SerializedFileReader::new_with_options(Bytes::from(buf), options).unwrap();
5452
5453        let row_group = reader.get_row_group(0).unwrap();
5454        let a_col = row_group.metadata().column(0);
5455        let b_col = row_group.metadata().column(1);
5456
5457        // Column chunk of column "a" should have chunk level statistics
5458        if let Statistics::ByteArray(byte_array_stats) = a_col.statistics().unwrap() {
5459            let min = byte_array_stats.min_opt().unwrap();
5460            let max = byte_array_stats.max_opt().unwrap();
5461
5462            assert_eq!(min.as_bytes(), b"a");
5463            assert_eq!(max.as_bytes(), b"d");
5464        } else {
5465            panic!("expecting Statistics::ByteArray");
5466        }
5467
5468        // The column chunk for column "b"  shouldn't have statistics
5469        assert!(b_col.statistics().is_none());
5470
5471        let page_index = reader.metadata().page_index().unwrap();
5472
5473        let a_idx = page_index.column_index(0, 0);
5474        assert!(a_idx.is_none(), "{a_idx:?}");
5475        let b_idx = page_index.column_index(0, 1);
5476        assert!(b_idx.is_none(), "{b_idx:?}");
5477    }
5478
5479    #[test]
5480    fn test_arrow_writer_skip_metadata() {
5481        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5482        let file_schema = Arc::new(batch_schema.clone());
5483
5484        let batch = RecordBatch::try_new(
5485            Arc::new(batch_schema),
5486            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5487        )
5488        .unwrap();
5489        let skip_options = ArrowWriterOptions::new().with_skip_arrow_metadata(true);
5490
5491        let mut buf = Vec::with_capacity(1024);
5492        let mut writer =
5493            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
5494        writer.write(&batch).unwrap();
5495        writer.close().unwrap();
5496
5497        let bytes = Bytes::from(buf);
5498        let reader_builder = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
5499        assert_eq!(file_schema, *reader_builder.schema());
5500        if let Some(key_value_metadata) = reader_builder
5501            .metadata()
5502            .file_metadata()
5503            .key_value_metadata()
5504        {
5505            assert!(
5506                !key_value_metadata
5507                    .iter()
5508                    .any(|kv| kv.key.as_str() == ARROW_SCHEMA_META_KEY)
5509            );
5510        }
5511    }
5512
5513    #[test]
5514    fn test_arrow_writer_skip_path_in_schema() {
5515        let batch_schema = Schema::new(vec![Field::new("int32", DataType::Int32, false)]);
5516        let file_schema = Arc::new(batch_schema.clone());
5517
5518        let batch = RecordBatch::try_new(
5519            Arc::new(batch_schema),
5520            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5521        )
5522        .unwrap();
5523
5524        // default options should still write path_in_schema
5525        let skip_options = ArrowWriterOptions::new();
5526
5527        let mut buf = Vec::with_capacity(1024);
5528        let mut writer =
5529            ArrowWriter::try_new_with_options(&mut buf, file_schema.clone(), skip_options).unwrap();
5530        writer.write(&batch).unwrap();
5531        writer.close().unwrap();
5532
5533        // override to not write path_in_schema
5534        let skip_options = ArrowWriterOptions::new().with_properties(
5535            WriterProperties::builder()
5536                .set_write_path_in_schema(false)
5537                .build(),
5538        );
5539
5540        let mut buf2 = Vec::with_capacity(1024);
5541        let mut writer =
5542            ArrowWriter::try_new_with_options(&mut buf2, file_schema.clone(), skip_options)
5543                .unwrap();
5544        writer.write(&batch).unwrap();
5545        writer.close().unwrap();
5546
5547        // buf2 should be a bit smaller due to lack of path_in_schema
5548        assert!(buf.len() > buf2.len());
5549    }
5550
5551    #[test]
5552    fn mismatched_schemas() {
5553        let batch_schema = Schema::new(vec![Field::new("count", DataType::Int32, false)]);
5554        let file_schema = Arc::new(Schema::new(vec![Field::new(
5555            "temperature",
5556            DataType::Float64,
5557            false,
5558        )]));
5559
5560        let batch = RecordBatch::try_new(
5561            Arc::new(batch_schema),
5562            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5563        )
5564        .unwrap();
5565
5566        let mut buf = Vec::with_capacity(1024);
5567        let mut writer = ArrowWriter::try_new(&mut buf, file_schema.clone(), None).unwrap();
5568
5569        let err = writer.write(&batch).unwrap_err().to_string();
5570        assert_eq!(
5571            err,
5572            "Arrow: Incompatible type. Field 'temperature' has type Float64, array has type Int32"
5573        );
5574    }
5575
5576    #[test]
5577    // https://github.com/apache/arrow-rs/issues/6988
5578    fn test_roundtrip_empty_schema() {
5579        // create empty record batch with empty schema
5580        let empty_batch = RecordBatch::try_new_with_options(
5581            Arc::new(Schema::empty()),
5582            vec![],
5583            &RecordBatchOptions::default().with_row_count(Some(0)),
5584        )
5585        .unwrap();
5586
5587        // write to parquet
5588        let mut parquet_bytes: Vec<u8> = Vec::new();
5589        let mut writer =
5590            ArrowWriter::try_new(&mut parquet_bytes, empty_batch.schema(), None).unwrap();
5591        writer.write(&empty_batch).unwrap();
5592        writer.close().unwrap();
5593
5594        // read from parquet
5595        let bytes = Bytes::from(parquet_bytes);
5596        let reader = ParquetRecordBatchReaderBuilder::try_new(bytes).unwrap();
5597        assert_eq!(reader.schema(), &empty_batch.schema());
5598        let batches: Vec<_> = reader
5599            .build()
5600            .unwrap()
5601            .collect::<ArrowResult<Vec<_>>>()
5602            .unwrap();
5603        assert_eq!(batches.len(), 0);
5604    }
5605
5606    #[test]
5607    fn test_page_stats_not_written_by_default() {
5608        let string_field = Field::new("a", DataType::Utf8, false);
5609        let schema = Schema::new(vec![string_field]);
5610        let raw_string_values = vec!["Blart Versenwald III"];
5611        let string_values = StringArray::from(raw_string_values.clone());
5612        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
5613
5614        let props = WriterProperties::builder()
5615            .set_statistics_enabled(EnabledStatistics::Page)
5616            .set_dictionary_enabled(false)
5617            .set_encoding(Encoding::PLAIN)
5618            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5619            .build();
5620
5621        let file = roundtrip_opts(&batch, props);
5622
5623        // read file and decode page headers
5624        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5625
5626        // decode first page header
5627        let first_page = &file[4..];
5628        let mut prot = ThriftSliceInputProtocol::new(first_page);
5629        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5630        let stats = hdr.data_page_header.unwrap().statistics;
5631
5632        assert!(stats.is_none());
5633    }
5634
5635    #[test]
5636    fn test_page_stats_when_enabled() {
5637        let string_field = Field::new("a", DataType::Utf8, false);
5638        let schema = Schema::new(vec![string_field]);
5639        let raw_string_values = vec!["Blart Versenwald III", "Andrew Lamb"];
5640        let string_values = StringArray::from(raw_string_values.clone());
5641        let batch = RecordBatch::try_new(Arc::new(schema), vec![Arc::new(string_values)]).unwrap();
5642
5643        let props = WriterProperties::builder()
5644            .set_statistics_enabled(EnabledStatistics::Page)
5645            .set_dictionary_enabled(false)
5646            .set_encoding(Encoding::PLAIN)
5647            .set_write_page_header_statistics(true)
5648            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5649            .build();
5650
5651        let file = roundtrip_opts(&batch, props);
5652
5653        // read file and decode page headers
5654        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5655
5656        // decode first page header
5657        let first_page = &file[4..];
5658        let mut prot = ThriftSliceInputProtocol::new(first_page);
5659        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5660        let stats = hdr.data_page_header.unwrap().statistics;
5661
5662        let stats = stats.unwrap();
5663        // check that min/max were actually written to the page
5664        assert!(stats.is_max_value_exact.unwrap());
5665        assert!(stats.is_min_value_exact.unwrap());
5666        assert_eq!(stats.max_value.unwrap(), b"Blart Versenwald III");
5667        assert_eq!(stats.min_value.unwrap(), b"Andrew Lamb");
5668    }
5669
5670    #[test]
5671    fn test_page_stats_truncation() {
5672        let string_field = Field::new("a", DataType::Utf8, false);
5673        let binary_field = Field::new("b", DataType::Binary, false);
5674        let schema = Schema::new(vec![string_field, binary_field]);
5675
5676        let raw_string_values = vec!["Blart Versenwald III"];
5677        let raw_binary_values = [b"Blart Versenwald III".to_vec()];
5678        let raw_binary_value_refs = raw_binary_values
5679            .iter()
5680            .map(|x| x.as_slice())
5681            .collect::<Vec<_>>();
5682
5683        let string_values = StringArray::from(raw_string_values.clone());
5684        let binary_values = BinaryArray::from(raw_binary_value_refs);
5685        let batch = RecordBatch::try_new(
5686            Arc::new(schema),
5687            vec![Arc::new(string_values), Arc::new(binary_values)],
5688        )
5689        .unwrap();
5690
5691        let props = WriterProperties::builder()
5692            .set_statistics_truncate_length(Some(2))
5693            .set_dictionary_enabled(false)
5694            .set_encoding(Encoding::PLAIN)
5695            .set_write_page_header_statistics(true)
5696            .set_compression(crate::basic::Compression::UNCOMPRESSED)
5697            .build();
5698
5699        let file = roundtrip_opts(&batch, props);
5700
5701        // read file and decode page headers
5702        // Note: use the thrift API as there is no Rust API to access the statistics in the page headers
5703
5704        // decode first page header
5705        let first_page = &file[4..];
5706        let mut prot = ThriftSliceInputProtocol::new(first_page);
5707        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5708        let stats = hdr.data_page_header.unwrap().statistics;
5709        assert!(stats.is_some());
5710        let stats = stats.unwrap();
5711        // check that min/max were properly truncated
5712        assert!(!stats.is_max_value_exact.unwrap());
5713        assert!(!stats.is_min_value_exact.unwrap());
5714        assert_eq!(stats.max_value.unwrap(), b"Bm");
5715        assert_eq!(stats.min_value.unwrap(), b"Bl");
5716
5717        // check second page now
5718        let second_page = &prot.as_slice()[hdr.compressed_page_size as usize..];
5719        let mut prot = ThriftSliceInputProtocol::new(second_page);
5720        let hdr = PageHeader::read_thrift(&mut prot).unwrap();
5721        let stats = hdr.data_page_header.unwrap().statistics;
5722        assert!(stats.is_some());
5723        let stats = stats.unwrap();
5724        // check that min/max were properly truncated
5725        assert!(!stats.is_max_value_exact.unwrap());
5726        assert!(!stats.is_min_value_exact.unwrap());
5727        assert_eq!(stats.max_value.unwrap(), b"Bm");
5728        assert_eq!(stats.min_value.unwrap(), b"Bl");
5729    }
5730
5731    #[test]
5732    fn test_page_encoding_statistics_roundtrip() {
5733        let batch_schema = Schema::new(vec![Field::new(
5734            "int32",
5735            arrow_schema::DataType::Int32,
5736            false,
5737        )]);
5738
5739        let batch = RecordBatch::try_new(
5740            Arc::new(batch_schema.clone()),
5741            vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as _],
5742        )
5743        .unwrap();
5744
5745        let mut file: File = tempfile::tempfile().unwrap();
5746        let mut writer = ArrowWriter::try_new(&mut file, Arc::new(batch_schema), None).unwrap();
5747        writer.write(&batch).unwrap();
5748        let file_metadata = writer.close().unwrap();
5749
5750        assert_eq!(file_metadata.num_row_groups(), 1);
5751        assert_eq!(file_metadata.row_group(0).num_columns(), 1);
5752        assert!(
5753            file_metadata
5754                .row_group(0)
5755                .column(0)
5756                .page_encoding_stats()
5757                .is_some()
5758        );
5759        let chunk_page_stats = file_metadata
5760            .row_group(0)
5761            .column(0)
5762            .page_encoding_stats()
5763            .unwrap();
5764
5765        // check that the read metadata is also correct
5766        let options = ReadOptionsBuilder::new()
5767            .with_page_index()
5768            .with_encoding_stats_as_mask(false)
5769            .build();
5770        let reader = SerializedFileReader::new_with_options(file, options).unwrap();
5771
5772        let rowgroup = reader.get_row_group(0).expect("row group missing");
5773        assert_eq!(rowgroup.num_columns(), 1);
5774        let column = rowgroup.metadata().column(0);
5775        assert!(column.page_encoding_stats().is_some());
5776        let file_page_stats = column.page_encoding_stats().unwrap();
5777        assert_eq!(chunk_page_stats, file_page_stats);
5778    }
5779
5780    #[test]
5781    #[cfg_attr(miri, ignore)] // Takes too long
5782    fn test_different_dict_page_size_limit() {
5783        let array = Arc::new(Int64Array::from_iter(0..1024 * 1024));
5784        let schema = Arc::new(Schema::new(vec![
5785            Field::new("col0", arrow_schema::DataType::Int64, false),
5786            Field::new("col1", arrow_schema::DataType::Int64, false),
5787        ]));
5788        let batch =
5789            arrow_array::RecordBatch::try_new(schema.clone(), vec![array.clone(), array]).unwrap();
5790
5791        let props = WriterProperties::builder()
5792            .set_dictionary_page_size_limit(1024 * 1024)
5793            .set_column_dictionary_page_size_limit(ColumnPath::from("col1"), 1024 * 1024 * 4)
5794            .build();
5795        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5796        writer.write(&batch).unwrap();
5797        let data = Bytes::from(writer.into_inner().unwrap());
5798
5799        let mut metadata = ParquetMetaDataReader::new();
5800        metadata.try_parse(&data).unwrap();
5801        let metadata = metadata.finish().unwrap();
5802        let col0_meta = metadata.row_group(0).column(0);
5803        let col1_meta = metadata.row_group(0).column(1);
5804
5805        let get_dict_page_size = move |meta: &ColumnChunkMetaData| {
5806            let mut reader =
5807                SerializedPageReader::new(Arc::new(data.clone()), meta, 0, None).unwrap();
5808            let page = reader.get_next_page().unwrap().unwrap();
5809            match page {
5810                Page::DictionaryPage { buf, .. } => buf.len(),
5811                _ => panic!("expected DictionaryPage"),
5812            }
5813        };
5814
5815        assert_eq!(get_dict_page_size(col0_meta), 1024 * 1024);
5816        assert_eq!(get_dict_page_size(col1_meta), 1024 * 1024 * 4);
5817    }
5818
5819    #[test]
5820    #[cfg_attr(miri, ignore)] // Takes too long
5821    fn test_arrow_writer_granular_mode_roundtrip() {
5822        // Granular mode subdivides chunks and writes more pages than the
5823        // default batched path. Make sure the data we write back is
5824        // bit-identical to what went in — page-count assertions elsewhere
5825        // only prove pages were cut, not that the encoded data is correct.
5826        //
5827        // Mix value sizes so that the cumulative-byte-budget cutoff
5828        // lands mid-chunk, exercising both batched and granular paths
5829        // within the same `write_batch_internal` call.
5830        let small = "tiny".to_string();
5831        let big = "x".repeat(64 * 1024);
5832        let strings: Vec<String> = (0..256)
5833            .map(|i| {
5834                if i % 16 == 0 {
5835                    big.clone()
5836                } else {
5837                    small.clone()
5838                }
5839            })
5840            .collect();
5841
5842        let schema = Arc::new(Schema::new(vec![Field::new(
5843            "col",
5844            ArrowDataType::Utf8,
5845            false,
5846        )]));
5847        let batch = RecordBatch::try_new(
5848            schema.clone(),
5849            vec![Arc::new(StringArray::from(strings.clone())) as _],
5850        )
5851        .unwrap();
5852
5853        let props = WriterProperties::builder()
5854            .set_dictionary_enabled(false)
5855            .set_data_page_size_limit(16 * 1024)
5856            .build();
5857        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5858        writer.write(&batch).unwrap();
5859        let data = Bytes::from(writer.into_inner().unwrap());
5860
5861        let mut reader = ParquetRecordBatchReader::try_new(data, 1024).unwrap();
5862        let read = reader.next().unwrap().unwrap();
5863        assert!(reader.next().is_none(), "expected one batch");
5864        let col = read
5865            .column(0)
5866            .as_any()
5867            .downcast_ref::<StringArray>()
5868            .unwrap();
5869        assert_eq!(col.len(), strings.len());
5870        for (i, expected) in strings.iter().enumerate() {
5871            assert_eq!(
5872                col.value(i),
5873                expected.as_str(),
5874                "value mismatch at index {i}"
5875            );
5876        }
5877    }
5878
5879    #[test]
5880    fn test_arrow_writer_all_null_string_column() {
5881        // The `LevelDataRef::value_count` Uniform branch with
5882        // `value != max_def` (entirely-null chunk) must return 0 so the
5883        // sub-batch sizer short-circuits to batch mode without trying
5884        // to estimate byte budgets for non-existent values.
5885        let num_rows = 1024;
5886        let schema = Arc::new(Schema::new(vec![Field::new(
5887            "col",
5888            ArrowDataType::Utf8,
5889            true,
5890        )]));
5891        let nulls: Vec<Option<&str>> = vec![None; num_rows];
5892        let batch = RecordBatch::try_new(
5893            schema.clone(),
5894            vec![Arc::new(StringArray::from(nulls)) as _],
5895        )
5896        .unwrap();
5897
5898        let props = WriterProperties::builder()
5899            .set_dictionary_enabled(false)
5900            .set_data_page_size_limit(16 * 1024)
5901            .build();
5902        let mut writer = ArrowWriter::try_new(Vec::new(), schema, Some(props)).unwrap();
5903        writer.write(&batch).unwrap();
5904        let data = Bytes::from(writer.into_inner().unwrap());
5905
5906        // Re-parse the file: row group has one column, every row is
5907        // null, all data pages report `num_rows / page_count` rows.
5908        let mut metadata = ParquetMetaDataReader::new();
5909        metadata.try_parse(&data).unwrap();
5910        let metadata = metadata.finish().unwrap();
5911        let row_group = metadata.row_group(0);
5912        let col_meta = row_group.column(0);
5913        assert_eq!(row_group.num_rows() as usize, num_rows);
5914        // Statistics record `null_count = num_rows` — proves every value
5915        // was written as null.
5916        if let Some(stats) = col_meta.statistics() {
5917            assert_eq!(
5918                stats.null_count_opt().unwrap_or(0) as usize,
5919                num_rows,
5920                "expected all-null column to report null_count = num_rows"
5921            );
5922        }
5923
5924        let mut reader =
5925            SerializedPageReader::new(Arc::new(data.clone()), col_meta, num_rows, None).unwrap();
5926        let mut total_values = 0u32;
5927        while let Some(page) = reader.get_next_page().unwrap() {
5928            if matches!(page, Page::DataPage { .. } | Page::DataPageV2 { .. }) {
5929                total_values += page.num_values();
5930            }
5931        }
5932        assert_eq!(
5933            total_values as usize, num_rows,
5934            "expected every level position to be represented in some page"
5935        );
5936    }
5937
5938    struct WriteBatchesShape {
5939        num_batches: usize,
5940        rows_per_batch: usize,
5941        row_size: usize,
5942    }
5943
5944    /// Helper function to write batches with the provided `WriteBatchesShape` into an `ArrowWriter`
5945    fn write_batches(
5946        WriteBatchesShape {
5947            num_batches,
5948            rows_per_batch,
5949            row_size,
5950        }: WriteBatchesShape,
5951        props: WriterProperties,
5952    ) -> ParquetRecordBatchReaderBuilder<File> {
5953        let schema = Arc::new(Schema::new(vec![Field::new(
5954            "str",
5955            ArrowDataType::Utf8,
5956            false,
5957        )]));
5958        let file = tempfile::tempfile().unwrap();
5959        let mut writer =
5960            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
5961
5962        for batch_idx in 0..num_batches {
5963            let strings: Vec<String> = (0..rows_per_batch)
5964                .map(|i| format!("{:0>width$}", batch_idx * 10 + i, width = row_size))
5965                .collect();
5966            let array = StringArray::from(strings);
5967            let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array)]).unwrap();
5968            writer.write(&batch).unwrap();
5969        }
5970        writer.close().unwrap();
5971        ParquetRecordBatchReaderBuilder::try_new(file).unwrap()
5972    }
5973
5974    #[test]
5975    // When both limits are None, all data should go into a single row group
5976    fn test_row_group_limit_none_writes_single_row_group() {
5977        let props = WriterProperties::builder()
5978            .set_max_row_group_row_count(None)
5979            .set_max_row_group_bytes(None)
5980            .build();
5981
5982        let builder = write_batches(
5983            WriteBatchesShape {
5984                num_batches: 1,
5985                rows_per_batch: 1000,
5986                row_size: 4,
5987            },
5988            props,
5989        );
5990
5991        assert_eq!(
5992            &row_group_sizes(builder.metadata()),
5993            &[1000],
5994            "With no limits, all rows should be in a single row group"
5995        );
5996    }
5997
5998    #[test]
5999    // When only max_row_group_size is set, respect the row limit
6000    fn test_row_group_limit_rows_only() {
6001        let props = WriterProperties::builder()
6002            .set_max_row_group_row_count(Some(300))
6003            .set_max_row_group_bytes(None)
6004            .build();
6005
6006        let builder = write_batches(
6007            WriteBatchesShape {
6008                num_batches: 1,
6009                rows_per_batch: 1000,
6010                row_size: 4,
6011            },
6012            props,
6013        );
6014
6015        assert_eq!(
6016            &row_group_sizes(builder.metadata()),
6017            &[300, 300, 300, 100],
6018            "Row groups should be split by row count"
6019        );
6020    }
6021
6022    #[test]
6023    #[cfg_attr(miri, ignore)] // Takes too long
6024    // A row limit far smaller than the batch splits it many times over; the split must not
6025    // consume stack proportional to the number of row groups.
6026    fn test_row_group_limit_rows_only_many_splits() {
6027        let props = WriterProperties::builder()
6028            .set_max_row_group_row_count(Some(1))
6029            .set_max_row_group_bytes(None)
6030            .build();
6031
6032        let rows = 50_000;
6033        let builder = write_batches(
6034            WriteBatchesShape {
6035                num_batches: 1,
6036                rows_per_batch: rows,
6037                row_size: 4,
6038            },
6039            props,
6040        );
6041
6042        let sizes = row_group_sizes(builder.metadata());
6043        assert_eq!(sizes.len(), rows, "Every row should get its own row group");
6044        assert_eq!(
6045            sizes.iter().sum::<i64>(),
6046            rows as i64,
6047            "Total rows should be preserved"
6048        );
6049    }
6050
6051    #[test]
6052    // When only max_row_group_bytes is set, respect the byte limit
6053    fn test_row_group_limit_bytes_only() {
6054        let props = WriterProperties::builder()
6055            .set_max_row_group_row_count(None)
6056            // Set byte limit to approximately fit ~30 rows worth of data (~100 bytes each)
6057            .set_max_row_group_bytes(Some(3500))
6058            .build();
6059
6060        let builder = write_batches(
6061            WriteBatchesShape {
6062                num_batches: 10,
6063                rows_per_batch: 10,
6064                row_size: 100,
6065            },
6066            props,
6067        );
6068
6069        let sizes = row_group_sizes(builder.metadata());
6070
6071        assert!(
6072            sizes.len() > 1,
6073            "Should have multiple row groups due to byte limit, got {sizes:?}",
6074        );
6075
6076        let total_rows: i64 = sizes.iter().sum();
6077        assert_eq!(total_rows, 100, "Total rows should be preserved");
6078    }
6079
6080    #[test]
6081    // If an in-progress row group is already oversized, it should be flushed before writing more.
6082    fn test_row_group_limit_bytes_flushes_when_current_group_already_too_large() {
6083        let schema = Arc::new(Schema::new(vec![Field::new(
6084            "str",
6085            ArrowDataType::Utf8,
6086            false,
6087        )]));
6088        let file = tempfile::tempfile().unwrap();
6089
6090        // Start with no byte limit so we can intentionally build an oversized in-progress row group.
6091        let props = WriterProperties::builder()
6092            .set_max_row_group_row_count(None)
6093            .set_max_row_group_bytes(None)
6094            .build();
6095        let mut writer =
6096            ArrowWriter::try_new(file.try_clone().unwrap(), schema.clone(), Some(props)).unwrap();
6097
6098        let first_array = StringArray::from(
6099            (0..10)
6100                .map(|i| format!("{i:0>100}"))
6101                .collect::<Vec<String>>(),
6102        );
6103        let first_batch =
6104            RecordBatch::try_new(schema.clone(), vec![Arc::new(first_array)]).unwrap();
6105        writer.write(&first_batch).unwrap();
6106        assert_eq!(writer.in_progress_rows(), 10);
6107
6108        // Tighten the limit below the current in-progress bytes to exercise:
6109        // `if current_bytes >= max_bytes { self.flush()?; ... }`
6110        writer.max_row_group_bytes = Some(1);
6111
6112        let second_array = StringArray::from(vec!["x".to_string()]);
6113        let second_batch =
6114            RecordBatch::try_new(schema.clone(), vec![Arc::new(second_array)]).unwrap();
6115        writer.write(&second_batch).unwrap();
6116        writer.close().unwrap();
6117        let builder = ParquetRecordBatchReaderBuilder::try_new(file).unwrap();
6118
6119        assert_eq!(
6120            &row_group_sizes(builder.metadata()),
6121            &[10, 1],
6122            "The second write should flush an oversized in-progress row group first",
6123        );
6124    }
6125
6126    #[test]
6127    // When both limits are set, the row limit triggers first
6128    fn test_row_group_limit_both_row_wins_single_batch() {
6129        let props = WriterProperties::builder()
6130            .set_max_row_group_row_count(Some(200)) // Will trigger at 200 rows
6131            .set_max_row_group_bytes(Some(1024 * 1024)) // 1MB - won't trigger for small int data
6132            .build();
6133
6134        let builder = write_batches(
6135            WriteBatchesShape {
6136                num_batches: 1,
6137                row_size: 4,
6138                rows_per_batch: 1000,
6139            },
6140            props,
6141        );
6142
6143        assert_eq!(
6144            &row_group_sizes(builder.metadata()),
6145            &[200, 200, 200, 200, 200],
6146            "Row limit should trigger before byte limit"
6147        );
6148    }
6149
6150    #[test]
6151    // When both limits are set, the row limit triggers first
6152    fn test_row_group_limit_both_row_wins_multiple_batches() {
6153        let props = WriterProperties::builder()
6154            .set_max_row_group_row_count(Some(5)) // Will trigger every 5 rows
6155            .set_max_row_group_bytes(Some(9999)) // Won't trigger
6156            .build();
6157
6158        let builder = write_batches(
6159            WriteBatchesShape {
6160                num_batches: 10,
6161                rows_per_batch: 10,
6162                row_size: 100,
6163            },
6164            props,
6165        );
6166
6167        assert_eq!(
6168            &row_group_sizes(builder.metadata()),
6169            &[5; 20],
6170            "Row limit should trigger before byte limit"
6171        );
6172    }
6173
6174    #[test]
6175    // When both limits are set, the byte limit triggers first
6176    fn test_row_group_limit_both_bytes_wins() {
6177        let props = WriterProperties::builder()
6178            .set_max_row_group_row_count(Some(1000)) // Won't trigger for 100 rows
6179            .set_max_row_group_bytes(Some(3500)) // Will trigger at ~30-35 rows
6180            .build();
6181
6182        let builder = write_batches(
6183            WriteBatchesShape {
6184                num_batches: 10,
6185                rows_per_batch: 10,
6186                row_size: 100,
6187            },
6188            props,
6189        );
6190
6191        let sizes = row_group_sizes(builder.metadata());
6192
6193        assert!(
6194            sizes.len() > 1,
6195            "Byte limit should trigger before row limit, got {sizes:?}",
6196        );
6197
6198        assert!(
6199            sizes.iter().all(|&s| s < 1000),
6200            "No row group should hit the row limit"
6201        );
6202
6203        let total_rows: i64 = sizes.iter().sum();
6204        assert_eq!(total_rows, 100, "Total rows should be preserved");
6205    }
6206
6207    #[test]
6208    // Both limits can apply to the same batch: the row limit trims it to 5 rows, and the
6209    // byte limit then trims those 5 down to 4.
6210    fn test_row_group_limit_both_apply_to_same_batch() {
6211        let props = WriterProperties::builder()
6212            .set_max_row_group_row_count(Some(15))
6213            .set_max_row_group_bytes(Some(1500))
6214            .build();
6215
6216        let builder = write_batches(
6217            WriteBatchesShape {
6218                num_batches: 2,
6219                rows_per_batch: 10,
6220                row_size: 100,
6221            },
6222            props,
6223        );
6224
6225        assert_eq!(
6226            &row_group_sizes(builder.metadata()),
6227            &[14, 6],
6228            "Byte limit should still apply to a batch the row limit already split"
6229        );
6230    }
6231
6232    #[test]
6233    fn arrow_column_chunk_close_mut_drops_column_index() {
6234        use crate::arrow::ArrowSchemaConverter;
6235        use crate::file::writer::SerializedFileWriter;
6236
6237        let schema = Arc::new(Schema::new(vec![Field::new("i", DataType::Int32, false)]));
6238        let props = Arc::new(
6239            WriterProperties::builder()
6240                .set_statistics_enabled(EnabledStatistics::Page)
6241                .build(),
6242        );
6243        let parquet_schema = ArrowSchemaConverter::new()
6244            .with_coerce_types(props.coerce_types())
6245            .convert(&schema)
6246            .unwrap();
6247
6248        let mut buf = Vec::with_capacity(1024);
6249        let mut writer =
6250            SerializedFileWriter::new(&mut buf, parquet_schema.root_schema_ptr(), props.clone())
6251                .unwrap();
6252
6253        let factory = ArrowRowGroupWriterFactory::new(&writer, Arc::clone(&schema));
6254        let mut col_writers = factory.create_column_writers(0).unwrap();
6255        let arr: ArrayRef = Arc::new(Int32Array::from_iter_values(0..64));
6256        for leaves in compute_leaves(schema.field(0), &arr).unwrap() {
6257            col_writers[0].write(&leaves).unwrap();
6258        }
6259        let mut chunk = col_writers.pop().unwrap().close().unwrap();
6260
6261        // Immutable accessor exposes the close result produced at close time.
6262        assert!(
6263            chunk.close().column_index.is_some(),
6264            "EnabledStatistics::Page should produce a column_index"
6265        );
6266
6267        // Mutable accessor lets callers drop the page-level index before append.
6268        chunk.close_mut().column_index = None;
6269        assert!(chunk.close().column_index.is_none());
6270
6271        let mut rg = writer.next_row_group().unwrap();
6272        chunk.append_to_row_group(&mut rg).unwrap();
6273        rg.close().unwrap();
6274        let file_meta = writer.close().unwrap();
6275
6276        // After dropping column_index, the resulting file records no column
6277        // index offset/length for this chunk.
6278        let cc = file_meta.row_group(0).column(0);
6279        assert!(cc.column_index_range().is_none());
6280    }
6281
6282    /// Writes a single-column RecordBatch to an in-memory Parquet buffer.
6283    fn write_column_to_bytes(array: ArrayRef) -> Bytes {
6284        let schema = Arc::new(Schema::new(vec![Field::new(
6285            "col",
6286            array.data_type().clone(),
6287            true,
6288        )]));
6289        let buf = get_bytes_after_close(
6290            schema.clone(),
6291            &RecordBatch::try_new(schema, vec![array]).unwrap(),
6292        );
6293        Bytes::from(buf)
6294    }
6295
6296    /// Reads column 0 from a single-row-group Parquet buffer, projecting it with the given schema.
6297    /// Passing a flat schema when the buffer was written from a REE array lets callers decode
6298    /// the physical values without the run-end encoding wrapper.
6299    fn read_column_with_schema(bytes: Bytes, schema: SchemaRef) -> ArrayRef {
6300        let opts = crate::arrow::arrow_reader::ArrowReaderOptions::new().with_schema(schema);
6301        ParquetRecordBatchReaderBuilder::try_new_with_options(bytes, opts)
6302            .unwrap()
6303            .build()
6304            .unwrap()
6305            .next()
6306            .unwrap()
6307            .unwrap()
6308            .column(0)
6309            .clone()
6310    }
6311
6312    fn ree_write_read_roundtrip(ree: ArrayRef, flat: ArrayRef) {
6313        let flat_schema = Arc::new(Schema::new(vec![Field::new(
6314            "col",
6315            flat.data_type().clone(),
6316            true,
6317        )]));
6318        let ree_bytes = write_column_to_bytes(ree);
6319        let flat_bytes = write_column_to_bytes(flat.clone());
6320        assert_eq!(
6321            ree_bytes, flat_bytes,
6322            "REE and flat bytes should be identical"
6323        );
6324
6325        let decoded_ree = read_column_with_schema(ree_bytes, flat_schema.clone());
6326        let decoded_flat = read_column_with_schema(flat_bytes, flat_schema);
6327
6328        assert_eq!(decoded_ree.as_ref(), flat.as_ref());
6329        assert_eq!(decoded_ree.as_ref(), decoded_flat.as_ref());
6330    }
6331
6332    #[test]
6333    fn ree_string() {
6334        let ree: ArrayRef = Arc::new(
6335            [Some("a"), Some("a"), None, Some("b"), Some("b")]
6336                .into_iter()
6337                .collect::<Int32RunArray>(),
6338        );
6339        let flat: ArrayRef = Arc::new(StringArray::from(vec![
6340            Some("a"),
6341            Some("a"),
6342            None,
6343            Some("b"),
6344            Some("b"),
6345        ]));
6346        ree_write_read_roundtrip(ree, flat);
6347    }
6348
6349    #[test]
6350    fn ree_int32() {
6351        let mut b = PrimitiveRunBuilder::<Int32Type, Int32Type>::new();
6352        for v in [Some(1), Some(1), None, Some(2), Some(2)] {
6353            b.append_option(v);
6354        }
6355        let ree: ArrayRef = Arc::new(b.finish());
6356        let flat: ArrayRef = Arc::new(Int32Array::from(vec![
6357            Some(1),
6358            Some(1),
6359            None,
6360            Some(2),
6361            Some(2),
6362        ]));
6363        ree_write_read_roundtrip(ree, flat);
6364    }
6365
6366    #[test]
6367    fn ree_bool() {
6368        // run_ends [3, 5, 7] → [T,T,T, null,null, F,F]
6369        let ree: ArrayRef = Arc::new(
6370            RunArray::try_new(
6371                &Int32Array::from(vec![3, 5, 7]),
6372                &BooleanArray::from(vec![Some(true), None, Some(false)]),
6373            )
6374            .unwrap(),
6375        );
6376        let flat: ArrayRef = Arc::new(BooleanArray::from(vec![
6377            Some(true),
6378            Some(true),
6379            Some(true),
6380            None,
6381            None,
6382            Some(false),
6383            Some(false),
6384        ]));
6385        ree_write_read_roundtrip(ree, flat);
6386    }
6387
6388    #[test]
6389    fn ree_fixed_size_binary() {
6390        let mk = |vals: &[Option<&[u8]>]| -> FixedSizeBinaryArray {
6391            let mut b = FixedSizeBinaryBuilder::new(2);
6392            for v in vals {
6393                match v {
6394                    Some(x) => b.append_value(x).unwrap(),
6395                    None => b.append_null(),
6396                }
6397            }
6398            b.finish()
6399        };
6400        // run_ends [2, 4, 6] → [aa,aa, null,null, bb,bb]
6401        let ree: ArrayRef = Arc::new(
6402            RunArray::try_new(
6403                &Int32Array::from(vec![2, 4, 6]),
6404                &mk(&[Some(b"aa"), None, Some(b"bb")]),
6405            )
6406            .unwrap(),
6407        );
6408        let flat: ArrayRef = Arc::new(mk(&[
6409            Some(b"aa"),
6410            Some(b"aa"),
6411            None,
6412            None,
6413            Some(b"bb"),
6414            Some(b"bb"),
6415        ]));
6416        ree_write_read_roundtrip(ree, flat);
6417    }
6418
6419    #[test]
6420    fn ree_single_run() {
6421        let ree: ArrayRef = Arc::new(["x", "x", "x"].into_iter().collect::<Int32RunArray>());
6422        let flat: ArrayRef = Arc::new(StringArray::from(vec!["x", "x", "x"]));
6423        ree_write_read_roundtrip(ree, flat);
6424    }
6425
6426    #[test]
6427    fn ree_float32() {
6428        // run_ends [2, 4, 5] → [1.0, 1.0, null, null, 2.5]
6429        let ree: ArrayRef = Arc::new(
6430            RunArray::try_new(
6431                &Int32Array::from(vec![2, 4, 5]),
6432                &Float32Array::from(vec![Some(1.0_f32), None, Some(2.5_f32)]),
6433            )
6434            .unwrap(),
6435        );
6436        let flat: ArrayRef = Arc::new(Float32Array::from(vec![
6437            Some(1.0_f32),
6438            Some(1.0_f32),
6439            None,
6440            None,
6441            Some(2.5_f32),
6442        ]));
6443        ree_write_read_roundtrip(ree, flat);
6444    }
6445
6446    #[test]
6447    fn ree_sliced() {
6448        // A sliced (non-zero offset) REE array: verify that get_physical_index
6449        // correctly accounts for the logical offset when expanding.
6450        // Full array: run_ends [3, 5, 7] → [a,a,a, b,b, c,c]
6451        // After slice(2, 5) the logical view is [a, b, b, c, c].
6452        let full: ArrayRef = Arc::new(
6453            RunArray::try_new(
6454                &Int32Array::from(vec![3, 5, 7]),
6455                &StringArray::from(vec!["a", "b", "c"]),
6456            )
6457            .unwrap(),
6458        );
6459        let sliced = full.slice(2, 5);
6460        let flat: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "b", "c", "c"]));
6461        ree_write_read_roundtrip(sliced, flat);
6462    }
6463
6464    #[test]
6465    #[cfg_attr(miri, ignore)] // Takes too long
6466    fn test_number_distinct_values_exact_count() {
6467        // 50 distinct Int32 values repeated across 100k rows, with every 7th row null.
6468        // Nulls must not be counted as a distinct value.
6469        let cardinality = 50u32;
6470        let array: ArrayRef = Arc::new(Int32Array::from_iter((0..100_000u32).map(|i| {
6471            if i % 7 == 0 {
6472                None
6473            } else {
6474                Some((i % cardinality) as i32)
6475            }
6476        })));
6477        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, true)]));
6478        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
6479
6480        let props = WriterProperties::builder()
6481            .set_write_row_group_number_distinct_values(true)
6482            .build();
6483        let mut buf = Vec::new();
6484        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), Some(props)).unwrap();
6485        writer.write(&batch).unwrap();
6486        let metadata = writer.close().unwrap();
6487
6488        let count = metadata
6489            .row_group(0)
6490            .column(0)
6491            .statistics()
6492            .and_then(|s| s.distinct_count_opt())
6493            .expect("distinct_count should be set");
6494        // Must equal cardinality exactly; nulls must not inflate the count.
6495        assert_eq!(count, cardinality as u64);
6496    }
6497
6498    #[test]
6499    fn test_number_distinct_values_not_written_by_default() {
6500        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
6501        let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)]));
6502        let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
6503
6504        let mut buf = Vec::new();
6505        let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None).unwrap();
6506        writer.write(&batch).unwrap();
6507        let metadata = writer.close().unwrap();
6508
6509        let count = metadata
6510            .row_group(0)
6511            .column(0)
6512            .statistics()
6513            .and_then(|s| s.distinct_count_opt());
6514        assert!(count.is_none());
6515    }
6516
6517    #[test]
6518    fn ree_struct_with_ree_child() {
6519        // Struct with a REE string field and a REE int field — confirms
6520        // recursion visits every child and each collapses to the right leaf type.
6521        let run_ends = Int32Array::from(vec![2i32, 3, 5]);
6522
6523        let col_a: ArrayRef = Arc::new(
6524            RunArray::try_new(
6525                &run_ends,
6526                &StringArray::from(vec![Some("foo"), None, Some("bar")]),
6527            )
6528            .unwrap(),
6529        );
6530        let col_b: ArrayRef = Arc::new(
6531            RunArray::try_new(&run_ends, &Int32Array::from(vec![Some(1), None, Some(2)])).unwrap(),
6532        );
6533
6534        let struct_array: ArrayRef = Arc::new(StructArray::new(
6535            Fields::from(vec![
6536                Field::new("a", col_a.data_type().clone(), true),
6537                Field::new("b", col_b.data_type().clone(), true),
6538            ]),
6539            vec![col_a, col_b],
6540            None,
6541        ));
6542
6543        let schema = Arc::new(Schema::new(vec![Field::new(
6544            "row",
6545            struct_array.data_type().clone(),
6546            true,
6547        )]));
6548        let batch = RecordBatch::try_new(schema.clone(), vec![struct_array]).unwrap();
6549
6550        let mut buf = Vec::new();
6551        let mut writer = ArrowWriter::try_new(&mut buf, schema, None).unwrap();
6552        writer.write(&batch).unwrap();
6553        let metadata = writer.close().unwrap();
6554
6555        let parquet_schema = metadata.file_metadata().schema_descr();
6556        assert_eq!(parquet_schema.num_columns(), 2);
6557        assert_eq!(
6558            parquet_schema.column(0).physical_type(),
6559            crate::basic::Type::BYTE_ARRAY
6560        );
6561        assert_eq!(parquet_schema.column(0).path().string(), "row.a");
6562        assert_eq!(
6563            parquet_schema.column(1).physical_type(),
6564            crate::basic::Type::INT32
6565        );
6566        assert_eq!(parquet_schema.column(1).path().string(), "row.b");
6567    }
6568}