Skip to main content

arrow_array/array/
struct_array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::array::print_long_array;
6use crate::{Array, ArrayRef, RecordBatch, make_array, new_null_array};
7use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer};
8use arrow_data::{ArrayData, ArrayDataBuilder};
9use arrow_schema::{ArrowError, DataType, Field, FieldRef, Fields};
10use std::sync::Arc;
11use std::{any::Any, ops::Index};
12
13/// An array of [structs](https://arrow.apache.org/docs/format/Columnar.html#struct-layout)
14///
15/// Each child (called *field*) is represented by a separate array.
16///
17/// # Comparison with [RecordBatch]
18///
19/// Both [`RecordBatch`] and [`StructArray`] represent a collection of columns / arrays with the
20/// same length.
21///
22/// However, there are a couple of key differences:
23///
24/// * [`StructArray`] can be nested within other [`Array`], including itself
25/// * [`RecordBatch`] can contain top-level metadata on its associated [`Schema`][arrow_schema::Schema]
26/// * [`StructArray`] can contain top-level nulls, i.e. `null`
27/// * [`RecordBatch`] can only represent nulls in its child columns, i.e. `{"field": null}`
28///
29/// [`StructArray`] is therefore a more general data container than [`RecordBatch`], and as such
30/// code that needs to handle both will typically share an implementation in terms of
31/// [`StructArray`] and convert to/from [`RecordBatch`] as necessary.
32///
33/// [`From`] implementations are provided to facilitate this conversion, however, converting
34/// from a [`StructArray`] containing top-level nulls to a [`RecordBatch`] will panic, as there
35/// is no way to preserve them.
36///
37/// # Example: Create an array from a vector of fields
38///
39/// ```
40/// use std::sync::Arc;
41/// use arrow_array::{Array, ArrayRef, BooleanArray, Int32Array, StructArray};
42/// use arrow_schema::{DataType, Field};
43///
44/// let boolean = Arc::new(BooleanArray::from(vec![false, false, true, true]));
45/// let int = Arc::new(Int32Array::from(vec![42, 28, 19, 31]));
46///
47/// let struct_array = StructArray::from(vec![
48///     (
49///         Arc::new(Field::new("b", DataType::Boolean, false)),
50///         boolean.clone() as ArrayRef,
51///     ),
52///     (
53///         Arc::new(Field::new("c", DataType::Int32, false)),
54///         int.clone() as ArrayRef,
55///     ),
56/// ]);
57/// assert_eq!(struct_array.column(0).as_ref(), boolean.as_ref());
58/// assert_eq!(struct_array.column(1).as_ref(), int.as_ref());
59/// assert_eq!(4, struct_array.len());
60/// assert_eq!(0, struct_array.null_count());
61/// assert_eq!(0, struct_array.offset());
62/// ```
63#[derive(Clone)]
64pub struct StructArray {
65    len: usize,
66    data_type: DataType,
67    nulls: Option<NullBuffer>,
68    fields: Vec<ArrayRef>,
69}
70
71impl StructArray {
72    /// Create a new [`StructArray`] from the provided parts, panicking on failure
73    ///
74    /// # Panics
75    ///
76    /// Panics if [`Self::try_new`] returns an error
77    pub fn new(fields: Fields, arrays: Vec<ArrayRef>, nulls: Option<NullBuffer>) -> Self {
78        Self::try_new(fields, arrays, nulls).unwrap()
79    }
80
81    /// Create a new [`StructArray`] from the provided parts, returning an error on failure
82    ///
83    /// The length will be inferred from the length of the child arrays.  Returns an error if
84    /// there are no child arrays.  Consider using [`Self::try_new_with_length`] if the length
85    /// is known to avoid this.
86    ///
87    /// # Errors
88    ///
89    /// Errors if
90    ///
91    /// * `fields.len() == 0`
92    /// * Any reason that [`Self::try_new_with_length`] would error
93    pub fn try_new(
94        fields: Fields,
95        arrays: Vec<ArrayRef>,
96        nulls: Option<NullBuffer>,
97    ) -> Result<Self, ArrowError> {
98        let len = arrays.first().map(|x| x.len()).ok_or_else(||ArrowError::InvalidArgumentError("use StructArray::try_new_with_length or StructArray::new_empty_fields to create a struct array with no fields so that the length can be set correctly".to_string()))?;
99
100        Self::try_new_with_length(fields, arrays, nulls, len)
101    }
102
103    /// Create a new [`StructArray`] from the provided parts, returning an error on failure
104    ///
105    /// # Errors
106    ///
107    /// Errors if
108    ///
109    /// * `fields.len() != arrays.len()`
110    /// * `fields[i].data_type() != arrays[i].data_type()`
111    /// * `arrays[i].len() != arrays[j].len()`
112    /// * `arrays[i].len() != nulls.len()`
113    /// * `!fields[i].is_nullable() && !nulls.contains(arrays[i].nulls())`
114    pub fn try_new_with_length(
115        fields: Fields,
116        arrays: Vec<ArrayRef>,
117        nulls: Option<NullBuffer>,
118        len: usize,
119    ) -> Result<Self, ArrowError> {
120        if fields.len() != arrays.len() {
121            return Err(ArrowError::InvalidArgumentError(format!(
122                "Incorrect number of arrays for StructArray fields, expected {} got {}",
123                fields.len(),
124                arrays.len()
125            )));
126        }
127
128        if let Some(n) = nulls.as_ref()
129            && n.len() != len
130        {
131            return Err(ArrowError::InvalidArgumentError(format!(
132                "Incorrect number of nulls for StructArray, expected {len} got {}",
133                n.len(),
134            )));
135        }
136
137        for (f, a) in fields.iter().zip(&arrays) {
138            if f.data_type() != a.data_type() {
139                return Err(ArrowError::InvalidArgumentError(format!(
140                    "Incorrect datatype for StructArray field {:?}, expected {} got {}",
141                    f.name(),
142                    f.data_type(),
143                    a.data_type()
144                )));
145            }
146
147            if a.len() != len {
148                return Err(ArrowError::InvalidArgumentError(format!(
149                    "Incorrect array length for StructArray field {:?}, expected {} got {}",
150                    f.name(),
151                    len,
152                    a.len()
153                )));
154            }
155
156            if !f.is_nullable() {
157                let unmasked = match nulls.as_ref() {
158                    None => a.logical_null_count() > 0,
159                    Some(n) => a.logical_nulls().is_some_and(|ln| !n.contains(&ln)),
160                };
161                if unmasked {
162                    return Err(ArrowError::InvalidArgumentError(format!(
163                        "Found unmasked nulls for non-nullable StructArray field {:?}",
164                        f.name()
165                    )));
166                }
167            }
168        }
169
170        Ok(Self {
171            len,
172            data_type: DataType::Struct(fields),
173            nulls: nulls.filter(|n| n.null_count() > 0),
174            fields: arrays,
175        })
176    }
177
178    /// Create a new [`StructArray`] of length `len` where all values are null
179    pub fn new_null(fields: Fields, len: usize) -> Self {
180        let arrays = fields
181            .iter()
182            .map(|f| new_null_array(f.data_type(), len))
183            .collect();
184
185        Self {
186            len,
187            data_type: DataType::Struct(fields),
188            nulls: Some(NullBuffer::new_null(len)),
189            fields: arrays,
190        }
191    }
192
193    /// Create a new [`StructArray`] from the provided parts without validation
194    ///
195    /// The length will be inferred from the length of the child arrays.  Panics if there are no
196    /// child arrays.  Consider using [`Self::new_unchecked_with_length`] if the length is known
197    /// to avoid this.
198    ///
199    /// # Safety
200    ///
201    /// Safe if [`Self::new`] would not panic with the given arguments
202    pub unsafe fn new_unchecked(
203        fields: Fields,
204        arrays: Vec<ArrayRef>,
205        nulls: Option<NullBuffer>,
206    ) -> Self {
207        if cfg!(feature = "force_validate") {
208            return Self::new(fields, arrays, nulls);
209        }
210
211        let len = arrays.first().map(|x| x.len()).expect(
212            "cannot use StructArray::new_unchecked if there are no fields, length is unknown",
213        );
214        Self {
215            len,
216            data_type: DataType::Struct(fields),
217            nulls,
218            fields: arrays,
219        }
220    }
221
222    /// Create a new [`StructArray`] from the provided parts without validation
223    ///
224    /// # Safety
225    ///
226    /// Safe if [`Self::new`] would not panic with the given arguments
227    pub unsafe fn new_unchecked_with_length(
228        fields: Fields,
229        arrays: Vec<ArrayRef>,
230        nulls: Option<NullBuffer>,
231        len: usize,
232    ) -> Self {
233        if cfg!(feature = "force_validate") {
234            return Self::try_new_with_length(fields, arrays, nulls, len).unwrap();
235        }
236
237        Self {
238            len,
239            data_type: DataType::Struct(fields),
240            nulls,
241            fields: arrays,
242        }
243    }
244
245    /// Create a new [`StructArray`] containing no fields
246    ///
247    /// # Panics
248    ///
249    /// If `len != nulls.len()`
250    pub fn new_empty_fields(len: usize, nulls: Option<NullBuffer>) -> Self {
251        if let Some(n) = &nulls {
252            assert_eq!(len, n.len())
253        }
254        Self {
255            len,
256            data_type: DataType::Struct(Fields::empty()),
257            fields: vec![],
258            nulls,
259        }
260    }
261
262    /// Deconstruct this array into its constituent parts
263    pub fn into_parts(self) -> (Fields, Vec<ArrayRef>, Option<NullBuffer>) {
264        let DataType::Struct(f) = self.data_type else {
265            unreachable!()
266        };
267        (f, self.fields, self.nulls)
268    }
269
270    /// Returns the field at `pos`.
271    ///
272    /// # Panics
273    /// Panics if `pos` is out of bounds
274    pub fn column(&self, pos: usize) -> &ArrayRef {
275        &self.fields[pos]
276    }
277
278    /// Return the number of fields in this struct array
279    pub fn num_columns(&self) -> usize {
280        self.fields.len()
281    }
282
283    /// Returns the fields of the struct array
284    pub fn columns(&self) -> &[ArrayRef] {
285        &self.fields
286    }
287
288    /// Return field names in this struct array
289    pub fn column_names(&self) -> Vec<&str> {
290        match self.data_type() {
291            DataType::Struct(fields) => fields
292                .iter()
293                .map(|f| f.name().as_str())
294                .collect::<Vec<&str>>(),
295            _ => unreachable!("Struct array's data type is not struct!"),
296        }
297    }
298
299    /// Returns the [`Fields`] of this [`StructArray`]
300    pub fn fields(&self) -> &Fields {
301        match self.data_type() {
302            DataType::Struct(f) => f,
303            _ => unreachable!(),
304        }
305    }
306
307    /// Return child array whose field name equals to column_name
308    ///
309    /// Note: A schema can currently have duplicate field names, in which case
310    /// the first field will always be selected.
311    /// This issue will be addressed in [#9205](https://github.com/apache/arrow-rs/issues/9205)
312    pub fn column_by_name(&self, column_name: &str) -> Option<&ArrayRef> {
313        self.fields()
314            .find(column_name)
315            .map(|(pos, _)| self.column(pos))
316    }
317
318    /// Returns the [`FieldRef`] at `pos`.
319    pub fn field(&self, pos: usize) -> &FieldRef {
320        &self.fields()[pos]
321    }
322
323    /// Return the [`FieldRef`] whose name equals to `field_name`
324    ///
325    /// Note: A schema can currently have duplicate field names, in which case
326    /// the first field will always be selected.
327    /// This issue will be addressed in [#9205](https://github.com/apache/arrow-rs/issues/9205)
328    pub fn field_by_name(&self, field_name: &str) -> Option<&FieldRef> {
329        self.fields().find(field_name).map(|(_, field)| field)
330    }
331
332    /// Returns a zero-copy slice of this array with the indicated offset and length.
333    ///
334    /// # Panics
335    /// Panics if `offset + len > self.len()`
336    pub fn slice(&self, offset: usize, len: usize) -> Self {
337        assert!(
338            offset.saturating_add(len) <= self.len,
339            "the length + offset of the sliced StructArray cannot exceed the existing length"
340        );
341
342        let fields = self.fields.iter().map(|a| a.slice(offset, len)).collect();
343
344        Self {
345            len,
346            data_type: self.data_type.clone(),
347            nulls: self.nulls.as_ref().map(|n| n.slice(offset, len)),
348            fields,
349        }
350    }
351
352    /// Returns the children of this [`StructArray`] with the struct's validity
353    /// bitmap AND'd into each child's validity bitmap.
354    ///
355    /// This ensures that positions where the struct itself is null are also
356    /// null in each returned child array. Fields that were non-nullable are
357    /// marked nullable in the returned [`Fields`] when the struct has nulls.
358    ///
359    /// If the struct has no nulls, children and fields are returned as-is.
360    ///
361    /// This mirrors the semantics of C++ Arrow's `StructArray::Flatten`.
362    ///
363    /// # Example
364    ///
365    /// ```
366    /// # use std::sync::Arc;
367    /// # use arrow_array::{Array, ArrayRef, Int32Array, StructArray};
368    /// # use arrow_buffer::{BooleanBuffer, NullBuffer};
369    /// # use arrow_schema::{DataType, Field, Fields};
370    /// let child = Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef;
371    /// let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, false, true]));
372    /// let sa = StructArray::new(
373    ///     Fields::from(vec![Field::new("a", DataType::Int32, false)]),
374    ///     vec![child],
375    ///     Some(struct_nulls),
376    /// );
377    /// let (fields, columns) = sa.flatten();
378    /// assert!(fields[0].is_nullable());
379    /// assert!(columns[0].is_null(1));
380    /// ```
381    pub fn flatten(&self) -> (Fields, Vec<ArrayRef>) {
382        let schema_fields = self.fields();
383
384        let Some(struct_nulls) = &self.nulls else {
385            return (schema_fields.clone(), self.fields.clone());
386        };
387
388        let new_fields: Fields = schema_fields
389            .iter()
390            .map(|f| {
391                if f.is_nullable() {
392                    Arc::clone(f)
393                } else {
394                    Arc::new(f.as_ref().clone().with_nullable(true))
395                }
396            })
397            .collect::<Vec<_>>()
398            .into();
399
400        let new_columns = self
401            .fields
402            .iter()
403            .map(|child| {
404                let merged = NullBuffer::union(Some(struct_nulls), child.nulls());
405                // SAFETY: We only make the null buffer more restrictive (adding nulls).
406                // All data buffers and child data remain unchanged.
407                let data = child.to_data().into_builder().nulls(merged);
408                make_array(unsafe { data.build_unchecked() })
409            })
410            .collect();
411
412        (new_fields, new_columns)
413    }
414}
415
416impl From<ArrayData> for StructArray {
417    fn from(data: ArrayData) -> Self {
418        let (data_type, len, nulls, offset, _buffers, child_data) = data.into_parts();
419
420        let parent_offset = offset;
421        let parent_len = len;
422
423        let fields = child_data
424            .into_iter()
425            .map(|cd| {
426                if parent_offset != 0 || parent_len != cd.len() {
427                    make_array(cd.sliced(parent_offset, parent_len))
428                } else {
429                    make_array(cd)
430                }
431            })
432            .collect();
433
434        Self {
435            len,
436            data_type,
437            nulls,
438            fields,
439        }
440    }
441}
442
443impl From<StructArray> for ArrayData {
444    fn from(array: StructArray) -> Self {
445        let builder = ArrayDataBuilder::new(array.data_type)
446            .len(array.len)
447            .nulls(array.nulls)
448            .child_data(array.fields.iter().map(|x| x.to_data()).collect());
449
450        unsafe { builder.build_unchecked() }
451    }
452}
453
454impl TryFrom<Vec<(&str, ArrayRef)>> for StructArray {
455    type Error = ArrowError;
456
457    /// builds a StructArray from a vector of names and arrays.
458    fn try_from(values: Vec<(&str, ArrayRef)>) -> Result<Self, ArrowError> {
459        let (fields, arrays): (Vec<_>, _) = values
460            .into_iter()
461            .map(|(name, array)| {
462                (
463                    Field::new(name, array.data_type().clone(), array.is_nullable()),
464                    array,
465                )
466            })
467            .unzip();
468
469        StructArray::try_new(fields.into(), arrays, None)
470    }
471}
472
473/// SAFETY: Correctly implements the contract of Arrow Arrays
474unsafe impl Array for StructArray {
475    fn as_any(&self) -> &dyn Any {
476        self
477    }
478
479    fn to_arc(&self) -> ArrayRef {
480        Arc::new(self.clone())
481    }
482
483    fn to_data(&self) -> ArrayData {
484        self.clone().into()
485    }
486
487    fn into_data(self) -> ArrayData {
488        self.into()
489    }
490
491    fn data_type(&self) -> &DataType {
492        &self.data_type
493    }
494
495    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
496        Arc::new(self.slice(offset, length))
497    }
498
499    fn len(&self) -> usize {
500        self.len
501    }
502
503    fn is_empty(&self) -> bool {
504        self.len == 0
505    }
506
507    fn shrink_to_fit(&mut self) {
508        if let Some(nulls) = &mut self.nulls {
509            nulls.shrink_to_fit();
510        }
511        self.fields.iter_mut().for_each(|n| n.shrink_to_fit());
512    }
513
514    fn offset(&self) -> usize {
515        0
516    }
517
518    fn nulls(&self) -> Option<&NullBuffer> {
519        self.nulls.as_ref()
520    }
521
522    fn logical_null_count(&self) -> usize {
523        // More efficient that the default implementation
524        self.null_count()
525    }
526
527    fn get_buffer_memory_size(&self) -> usize {
528        let mut size = self.fields.iter().map(|a| a.get_buffer_memory_size()).sum();
529        if let Some(n) = self.nulls.as_ref() {
530            size += n.buffer().capacity();
531        }
532        size
533    }
534
535    fn get_array_memory_size(&self) -> usize {
536        let mut size = self.fields.iter().map(|a| a.get_array_memory_size()).sum();
537        size += std::mem::size_of::<Self>();
538        if let Some(n) = self.nulls.as_ref() {
539            size += n.buffer().capacity();
540        }
541        size
542    }
543
544    #[cfg(feature = "pool")]
545    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
546        for field in &self.fields {
547            field.claim(pool);
548        }
549        if let Some(nulls) = &self.nulls {
550            nulls.claim(pool);
551        }
552    }
553}
554
555impl From<Vec<(FieldRef, ArrayRef)>> for StructArray {
556    fn from(v: Vec<(FieldRef, ArrayRef)>) -> Self {
557        let (fields, arrays): (Vec<_>, _) = v.into_iter().unzip();
558        StructArray::new(fields.into(), arrays, None)
559    }
560}
561
562impl std::fmt::Debug for StructArray {
563    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
564        writeln!(f, "StructArray")?;
565        writeln!(f, "-- validity:")?;
566        writeln!(f, "[")?;
567        print_long_array(self, f, &mut |_index, f| write!(f, "valid"))?;
568        writeln!(f, "]\n[")?;
569        for (child_index, name) in self.column_names().iter().enumerate() {
570            let column = self.column(child_index);
571            writeln!(
572                f,
573                "-- child {}: \"{}\" ({:?})",
574                child_index,
575                name,
576                column.data_type()
577            )?;
578            std::fmt::Debug::fmt(column, f)?;
579            writeln!(f)?;
580        }
581        write!(f, "]")
582    }
583}
584
585impl From<(Vec<(FieldRef, ArrayRef)>, Buffer)> for StructArray {
586    fn from(pair: (Vec<(FieldRef, ArrayRef)>, Buffer)) -> Self {
587        let len = pair.0.first().map(|x| x.1.len()).unwrap_or_default();
588        let (fields, arrays): (Vec<_>, Vec<_>) = pair.0.into_iter().unzip();
589        let nulls = NullBuffer::new(BooleanBuffer::new(pair.1, 0, len));
590        Self::new(fields.into(), arrays, Some(nulls))
591    }
592}
593
594impl From<RecordBatch> for StructArray {
595    fn from(value: RecordBatch) -> Self {
596        Self {
597            len: value.num_rows(),
598            data_type: DataType::Struct(value.schema().fields().clone()),
599            nulls: None,
600            fields: value.columns().to_vec(),
601        }
602    }
603}
604
605impl Index<&str> for StructArray {
606    type Output = ArrayRef;
607
608    /// Get a reference to a column's array by name.
609    ///
610    /// Note: A schema can currently have duplicate field names, in which case
611    /// the first field will always be selected.
612    /// This issue will be addressed in [ARROW-11178](https://issues.apache.org/jira/browse/ARROW-11178)
613    ///
614    /// # Panics
615    ///
616    /// Panics if the name is not in the schema.
617    fn index(&self, name: &str) -> &Self::Output {
618        self.column_by_name(name).unwrap()
619    }
620}
621
622#[cfg(test)]
623mod tests {
624    use super::*;
625
626    use crate::{
627        BooleanArray, Float32Array, Float64Array, Int32Array, Int64Array, NullArray, StringArray,
628        cast::AsArray, types::Int32Type,
629    };
630    use arrow_buffer::ToByteSlice;
631
632    #[test]
633    fn test_struct_array_builder() {
634        let boolean_array = BooleanArray::from(vec![false, false, true, true]);
635        let int_array = Int64Array::from(vec![42, 28, 19, 31]);
636
637        let fields = vec![
638            Field::new("a", DataType::Boolean, false),
639            Field::new("b", DataType::Int64, false),
640        ];
641        let struct_array_data = ArrayData::builder(DataType::Struct(fields.into()))
642            .len(4)
643            .add_child_data(boolean_array.to_data())
644            .add_child_data(int_array.to_data())
645            .build()
646            .unwrap();
647        let struct_array = StructArray::from(struct_array_data);
648
649        assert_eq!(struct_array.column(0).as_ref(), &boolean_array);
650        assert_eq!(struct_array.column(1).as_ref(), &int_array);
651    }
652
653    #[test]
654    fn test_struct_array_from() {
655        let boolean = Arc::new(BooleanArray::from(vec![false, false, true, true]));
656        let int = Arc::new(Int32Array::from(vec![42, 28, 19, 31]));
657
658        let struct_array = StructArray::from(vec![
659            (
660                Arc::new(Field::new("b", DataType::Boolean, false)),
661                boolean.clone() as ArrayRef,
662            ),
663            (
664                Arc::new(Field::new("c", DataType::Int32, false)),
665                int.clone() as ArrayRef,
666            ),
667        ]);
668        assert_eq!(struct_array.column(0).as_ref(), boolean.as_ref());
669        assert_eq!(struct_array.column(1).as_ref(), int.as_ref());
670        assert_eq!(4, struct_array.len());
671        assert_eq!(0, struct_array.null_count());
672        assert_eq!(0, struct_array.offset());
673    }
674
675    #[test]
676    fn test_struct_array_from_data_with_offset_and_length() {
677        // Various ways to make the struct array:
678        //
679        // [{x: 2}, {x: 3}, None]
680        //
681        // from slicing larger buffers/arrays with offsets and lengths
682        let int_arr = Int32Array::from(vec![1, 2, 3, 4, 5]);
683        let int_field = Field::new("x", DataType::Int32, false);
684        let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, true, false]));
685        let int_data = int_arr.to_data();
686        // Case 1: Offset + length, nulls are not sliced
687        let case1 = ArrayData::builder(DataType::Struct(Fields::from(vec![int_field.clone()])))
688            .len(3)
689            .offset(1)
690            .nulls(Some(struct_nulls))
691            .add_child_data(int_data.clone())
692            .build()
693            .unwrap();
694
695        // Case 2: Offset + length, nulls are sliced
696        let struct_nulls =
697            NullBuffer::new(BooleanBuffer::from(vec![true, true, true, false, true]).slice(1, 3));
698        let case2 = ArrayData::builder(DataType::Struct(Fields::from(vec![int_field.clone()])))
699            .len(3)
700            .offset(1)
701            .nulls(Some(struct_nulls.clone()))
702            .add_child_data(int_data.clone())
703            .build()
704            .unwrap();
705
706        // Case 3: struct length is smaller than child length but no offset
707        let offset_int_data = int_data.slice(1, 4);
708        let case3 = ArrayData::builder(DataType::Struct(Fields::from(vec![int_field.clone()])))
709            .len(3)
710            .nulls(Some(struct_nulls))
711            .add_child_data(offset_int_data)
712            .build()
713            .unwrap();
714
715        let expected = StructArray::new(
716            Fields::from(vec![int_field.clone()]),
717            vec![Arc::new(int_arr)],
718            Some(NullBuffer::new(BooleanBuffer::from(vec![
719                true, true, true, false, true,
720            ]))),
721        )
722        .slice(1, 3);
723
724        for case in [case1, case2, case3] {
725            let struct_arr_from_data = StructArray::from(case);
726            assert_eq!(struct_arr_from_data, expected);
727            assert_eq!(struct_arr_from_data.column(0), expected.column(0));
728        }
729    }
730
731    #[test]
732    fn test_struct_array_data_slice() {
733        // Slicing a struct's `ArrayData` and rebuilding an array from it has to
734        // apply the offset to the children exactly once (#7595, #7750).
735        let x = Int32Array::from(vec![Some(0), Some(1), Some(2), Some(3), None, Some(5)]);
736        let struct_array = StructArray::new(
737            Fields::from(vec![Field::new("x", DataType::Int32, true)]),
738            vec![Arc::new(x.clone())],
739            Some(NullBuffer::from(vec![true, true, true, false, true, true])),
740        )
741        .into_data();
742        let sliced = struct_array.slice(1, 4);
743
744        let arr = make_array(sliced);
745        assert_eq!(
746            arr.as_struct().column(0).as_primitive::<Int32Type>(),
747            &x.slice(1, 4)
748        );
749
750        // A struct whose top-level `ArrayData` carries a non-zero offset over
751        // full-length children is how the C++ implementation of Arrow (and the
752        // C data interface) represents a sliced struct: the offset/length live
753        // on the struct, not on the children. arrow-rs must decode it to the
754        // same logical array its own `StructArray::slice` produces.
755        let x = Int32Array::from(vec![Some(0), Some(1), Some(2), Some(3), None, Some(5)]);
756        let y = Int32Array::from(vec![Some(5), Some(6), None, Some(8), Some(9), Some(10)]);
757        let struct_array = StructArray::new(
758            Fields::from(vec![
759                Field::new("x", DataType::Int32, true),
760                Field::new("y", DataType::Int32, true),
761            ]),
762            vec![Arc::new(x), Arc::new(y)],
763            Some(NullBuffer::from(vec![true, true, true, false, true, true])),
764        );
765        let struct_array = StructArray::new(
766            Fields::from(vec![Field::new(
767                "inner",
768                struct_array.data_type().clone(),
769                true,
770            )]),
771            vec![Arc::new(struct_array)],
772            Some(NullBuffer::from(vec![true, false, true, true, true, true])),
773        );
774
775        let cpp_sliced_array = make_array(
776            struct_array
777                .to_data()
778                .into_builder()
779                .offset(1)
780                .len(4)
781                .nulls(Some(NullBuffer::from(vec![false, true, true, true])))
782                .build()
783                .unwrap(),
784        );
785
786        assert_eq!(cpp_sliced_array.as_struct(), &struct_array.slice(1, 4));
787    }
788
789    #[test]
790    fn test_make_array_sliced_struct_data() {
791        // Exact reproducer from #7750: `make_array` on a sliced struct's
792        // `ArrayData`.
793        let strings: ArrayRef = Arc::new(StringArray::from(vec![
794            Some("joe"),
795            None,
796            None,
797            Some("mark"),
798            Some("doe"),
799        ]));
800        let ints: ArrayRef = Arc::new(Int32Array::from(vec![
801            Some(1),
802            Some(2),
803            Some(3),
804            Some(4),
805            Some(5),
806        ]));
807
808        let array = StructArray::try_from(vec![("f1", strings.clone()), ("f2", ints.clone())])
809            .unwrap()
810            .into_data()
811            .slice(1, 3);
812
813        let arr = make_array(array);
814        let expected = StructArray::try_from(vec![("f1", strings), ("f2", ints)])
815            .unwrap()
816            .slice(1, 3);
817        assert_eq!(arr.as_struct(), &expected);
818    }
819
820    #[test]
821    fn test_slice_struct_data_with_existing_offset() {
822        // Slicing a struct whose `ArrayData` already carries a non-zero offset
823        // over full-length children, which is how the C data interface hands us
824        // a sliced struct. The cumulative offset has to end up on the children
825        // only: anything left on the parent gets applied a second time by
826        // `From<ArrayData> for StructArray`.
827        let x = Int32Array::from(vec![Some(0), Some(1), Some(2), Some(3), None, Some(5)]);
828        let struct_array = StructArray::new(
829            Fields::from(vec![Field::new("x", DataType::Int32, true)]),
830            vec![Arc::new(x.clone())],
831            Some(NullBuffer::from(vec![true, true, true, false, true, true])),
832        );
833
834        let offset_data = struct_array
835            .to_data()
836            .into_builder()
837            .offset(1)
838            .len(5)
839            .nulls(Some(NullBuffer::from(vec![true, true, false, true, true])))
840            .build()
841            .unwrap();
842
843        let sliced = offset_data.slice(1, 3);
844        // The cumulative offset (1 + 1) lands on the child; the parent's own
845        // offset is reset to 0 so nothing re-applies it.
846        assert_eq!(sliced.offset(), 0);
847        assert_eq!(sliced.len(), 3);
848        assert_eq!(sliced.child_data()[0].offset(), 2);
849        assert_eq!(sliced.child_data()[0].len(), 3);
850
851        let arr = make_array(sliced);
852        assert_eq!(
853            arr.as_struct().column(0).as_primitive::<Int32Type>(),
854            &x.slice(2, 3)
855        );
856        assert_eq!(arr.as_struct(), &struct_array.slice(2, 3));
857    }
858
859    #[test]
860    fn test_struct_array_from_data_with_offset_and_length_error() {
861        let int_arr = Int32Array::from(vec![1, 2, 3, 4, 5]);
862        let int_field = Field::new("x", DataType::Int32, false);
863        let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, true, false]));
864        let int_data = int_arr.to_data();
865        // If parent offset is 3 and len is 3 then child must have 6 items
866        let err = ArrayData::builder(DataType::Struct(Fields::from(vec![int_field.clone()])))
867            .len(3)
868            .offset(3)
869            .nulls(Some(struct_nulls))
870            .add_child_data(int_data)
871            .build()
872            .unwrap_err()
873            .to_string();
874
875        assert!(err.contains(
876            "child array #0 for field x has length smaller than expected for struct array (5 < 6)"
877        ));
878    }
879
880    /// validates that struct can be accessed using `column_name` as index i.e. `struct_array["column_name"]`.
881    #[test]
882    fn test_struct_array_index_access() {
883        let boolean = Arc::new(BooleanArray::from(vec![false, false, true, true]));
884        let int = Arc::new(Int32Array::from(vec![42, 28, 19, 31]));
885
886        let struct_array = StructArray::from(vec![
887            (
888                Arc::new(Field::new("b", DataType::Boolean, false)),
889                boolean.clone() as ArrayRef,
890            ),
891            (
892                Arc::new(Field::new("c", DataType::Int32, false)),
893                int.clone() as ArrayRef,
894            ),
895        ]);
896        assert_eq!(struct_array["b"].as_ref(), boolean.as_ref());
897        assert_eq!(struct_array["c"].as_ref(), int.as_ref());
898    }
899
900    #[test]
901    fn test_struct_array_field_access() {
902        let boolean = Arc::new(BooleanArray::from(vec![false, false, true, true]));
903        let int = Arc::new(Int32Array::from(vec![42, 28, 19, 31]));
904
905        let b_field = Arc::new(Field::new("b", DataType::Boolean, false));
906        let c_field = Arc::new(Field::new("c", DataType::Int32, false));
907
908        let struct_array = StructArray::from(vec![
909            (b_field.clone(), boolean as ArrayRef),
910            (c_field.clone(), int as ArrayRef),
911        ]);
912
913        assert_eq!(struct_array.field(0), &b_field);
914        assert_eq!(struct_array.field(1), &c_field);
915
916        assert_eq!(struct_array.field_by_name("b"), Some(&b_field));
917        assert_eq!(struct_array.field_by_name("c"), Some(&c_field));
918        assert_eq!(struct_array.field_by_name("d"), None);
919    }
920
921    /// validates that the in-memory representation follows [the spec](https://arrow.apache.org/docs/format/Columnar.html#struct-layout)
922    #[test]
923    fn test_struct_array_from_vec() {
924        let strings: ArrayRef = Arc::new(StringArray::from(vec![
925            Some("joe"),
926            None,
927            None,
928            Some("mark"),
929        ]));
930        let ints: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), Some(2), None, Some(4)]));
931
932        let arr =
933            StructArray::try_from(vec![("f1", strings.clone()), ("f2", ints.clone())]).unwrap();
934
935        let struct_data = arr.into_data();
936        assert_eq!(4, struct_data.len());
937        assert_eq!(0, struct_data.null_count());
938
939        let expected_string_data = ArrayData::builder(DataType::Utf8)
940            .len(4)
941            .null_bit_buffer(Some(Buffer::from(&[9_u8])))
942            .add_buffer(Buffer::from([0, 3, 3, 3, 7].to_byte_slice()))
943            .add_buffer(Buffer::from(b"joemark"))
944            .build()
945            .unwrap();
946
947        let expected_int_data = ArrayData::builder(DataType::Int32)
948            .len(4)
949            .null_bit_buffer(Some(Buffer::from(&[11_u8])))
950            .add_buffer(Buffer::from([1, 2, 0, 4].to_byte_slice()))
951            .build()
952            .unwrap();
953
954        assert_eq!(expected_string_data, struct_data.child_data()[0]);
955        assert_eq!(expected_int_data, struct_data.child_data()[1]);
956    }
957
958    #[test]
959    fn test_struct_array_from_vec_error() {
960        let strings: ArrayRef = Arc::new(StringArray::from(vec![
961            Some("joe"),
962            None,
963            None,
964            // 3 elements, not 4
965        ]));
966        let ints: ArrayRef = Arc::new(Int32Array::from(vec![Some(1), Some(2), None, Some(4)]));
967
968        let err = StructArray::try_from(vec![("f1", strings.clone()), ("f2", ints.clone())])
969            .unwrap_err()
970            .to_string();
971
972        assert_eq!(
973            err,
974            "Invalid argument error: Incorrect array length for StructArray field \"f2\", expected 3 got 4"
975        )
976    }
977
978    #[test]
979    #[should_panic(
980        expected = "Incorrect datatype for StructArray field \\\"b\\\", expected Int16 got Boolean"
981    )]
982    fn test_struct_array_from_mismatched_types_single() {
983        drop(StructArray::from(vec![(
984            Arc::new(Field::new("b", DataType::Int16, false)),
985            Arc::new(BooleanArray::from(vec![false, false, true, true])) as Arc<dyn Array>,
986        )]));
987    }
988
989    #[test]
990    #[should_panic(
991        expected = "Incorrect datatype for StructArray field \\\"b\\\", expected Int16 got Boolean"
992    )]
993    fn test_struct_array_from_mismatched_types_multiple() {
994        drop(StructArray::from(vec![
995            (
996                Arc::new(Field::new("b", DataType::Int16, false)),
997                Arc::new(BooleanArray::from(vec![false, false, true, true])) as Arc<dyn Array>,
998            ),
999            (
1000                Arc::new(Field::new("c", DataType::Utf8, false)),
1001                Arc::new(Int32Array::from(vec![42, 28, 19, 31])),
1002            ),
1003        ]));
1004    }
1005
1006    #[test]
1007    fn test_struct_array_slice() {
1008        let boolean_data = ArrayData::builder(DataType::Boolean)
1009            .len(5)
1010            .add_buffer(Buffer::from([0b00010000]))
1011            .null_bit_buffer(Some(Buffer::from([0b00010001])))
1012            .build()
1013            .unwrap();
1014        let int_data = ArrayData::builder(DataType::Int32)
1015            .len(5)
1016            .add_buffer(Buffer::from([0, 28, 42, 0, 0].to_byte_slice()))
1017            .null_bit_buffer(Some(Buffer::from([0b00000110])))
1018            .build()
1019            .unwrap();
1020
1021        let field_types = vec![
1022            Field::new("a", DataType::Boolean, true),
1023            Field::new("b", DataType::Int32, true),
1024        ];
1025        let struct_array_data = ArrayData::builder(DataType::Struct(field_types.into()))
1026            .len(5)
1027            .add_child_data(boolean_data.clone())
1028            .add_child_data(int_data.clone())
1029            .null_bit_buffer(Some(Buffer::from([0b00010111])))
1030            .build()
1031            .unwrap();
1032        let struct_array = StructArray::from(struct_array_data);
1033
1034        assert_eq!(5, struct_array.len());
1035        assert_eq!(1, struct_array.null_count());
1036        assert!(struct_array.is_valid(0));
1037        assert!(struct_array.is_valid(1));
1038        assert!(struct_array.is_valid(2));
1039        assert!(struct_array.is_null(3));
1040        assert!(struct_array.is_valid(4));
1041        assert_eq!(boolean_data, struct_array.column(0).to_data());
1042        assert_eq!(int_data, struct_array.column(1).to_data());
1043
1044        let c0 = struct_array.column(0);
1045        let c0 = c0.as_any().downcast_ref::<BooleanArray>().unwrap();
1046        assert_eq!(5, c0.len());
1047        assert_eq!(3, c0.null_count());
1048        assert!(c0.is_valid(0));
1049        assert!(!c0.value(0));
1050        assert!(c0.is_null(1));
1051        assert!(c0.is_null(2));
1052        assert!(c0.is_null(3));
1053        assert!(c0.is_valid(4));
1054        assert!(c0.value(4));
1055
1056        let c1 = struct_array.column(1);
1057        let c1 = c1.as_any().downcast_ref::<Int32Array>().unwrap();
1058        assert_eq!(5, c1.len());
1059        assert_eq!(3, c1.null_count());
1060        assert!(c1.is_null(0));
1061        assert!(c1.is_valid(1));
1062        assert_eq!(28, c1.value(1));
1063        assert!(c1.is_valid(2));
1064        assert_eq!(42, c1.value(2));
1065        assert!(c1.is_null(3));
1066        assert!(c1.is_null(4));
1067
1068        let sliced_array = struct_array.slice(2, 3);
1069        let sliced_array = sliced_array.as_any().downcast_ref::<StructArray>().unwrap();
1070        assert_eq!(3, sliced_array.len());
1071        assert_eq!(1, sliced_array.null_count());
1072        assert!(sliced_array.is_valid(0));
1073        assert!(sliced_array.is_null(1));
1074        assert!(sliced_array.is_valid(2));
1075
1076        let sliced_c0 = sliced_array.column(0);
1077        let sliced_c0 = sliced_c0.as_any().downcast_ref::<BooleanArray>().unwrap();
1078        assert_eq!(3, sliced_c0.len());
1079        assert!(sliced_c0.is_null(0));
1080        assert!(sliced_c0.is_null(1));
1081        assert!(sliced_c0.is_valid(2));
1082        assert!(sliced_c0.value(2));
1083
1084        let sliced_c1 = sliced_array.column(1);
1085        let sliced_c1 = sliced_c1.as_any().downcast_ref::<Int32Array>().unwrap();
1086        assert_eq!(3, sliced_c1.len());
1087        assert!(sliced_c1.is_valid(0));
1088        assert_eq!(42, sliced_c1.value(0));
1089        assert!(sliced_c1.is_null(1));
1090        assert!(sliced_c1.is_null(2));
1091    }
1092
1093    #[test]
1094    #[should_panic(
1095        expected = "Incorrect array length for StructArray field \\\"c\\\", expected 1 got 2"
1096    )]
1097    fn test_invalid_struct_child_array_lengths() {
1098        drop(StructArray::from(vec![
1099            (
1100                Arc::new(Field::new("b", DataType::Float32, false)),
1101                Arc::new(Float32Array::from(vec![1.1])) as Arc<dyn Array>,
1102            ),
1103            (
1104                Arc::new(Field::new("c", DataType::Float64, false)),
1105                Arc::new(Float64Array::from(vec![2.2, 3.3])),
1106            ),
1107        ]));
1108    }
1109
1110    #[test]
1111    #[should_panic(expected = "use StructArray::try_new_with_length")]
1112    fn test_struct_array_from_empty() {
1113        // This can't work because we don't know how many rows the array should have.  Previously we inferred 0 but
1114        // that often led to bugs.
1115        let _ = StructArray::from(vec![]);
1116    }
1117
1118    #[test]
1119    fn test_empty_struct_array() {
1120        assert!(StructArray::try_new(Fields::empty(), vec![], None).is_err());
1121
1122        let arr = StructArray::new_empty_fields(10, None);
1123        assert_eq!(arr.len(), 10);
1124        assert_eq!(arr.null_count(), 0);
1125        assert_eq!(arr.num_columns(), 0);
1126
1127        let arr2 = StructArray::try_new_with_length(Fields::empty(), vec![], None, 10).unwrap();
1128        assert_eq!(arr2.len(), 10);
1129
1130        let arr = StructArray::new_empty_fields(10, Some(NullBuffer::new_null(10)));
1131        assert_eq!(arr.len(), 10);
1132        assert_eq!(arr.null_count(), 10);
1133        assert_eq!(arr.num_columns(), 0);
1134
1135        let arr2 = StructArray::try_new_with_length(
1136            Fields::empty(),
1137            vec![],
1138            Some(NullBuffer::new_null(10)),
1139            10,
1140        )
1141        .unwrap();
1142        assert_eq!(arr2.len(), 10);
1143    }
1144
1145    #[test]
1146    #[should_panic(expected = "Found unmasked nulls for non-nullable StructArray field \\\"c\\\"")]
1147    fn test_struct_array_from_mismatched_nullability() {
1148        drop(StructArray::from(vec![(
1149            Arc::new(Field::new("c", DataType::Int32, false)),
1150            Arc::new(Int32Array::from(vec![Some(42), None, Some(19)])) as ArrayRef,
1151        )]));
1152    }
1153
1154    #[test]
1155    fn test_struct_array_non_nullable_null_array_with_max_length() {
1156        // A non-nullable field backed by a NullArray of `usize::MAX` length
1157        // should be rejected with an error, not panic trying to materialize
1158        // a null buffer of ~2.3 EB
1159        let fields = Fields::from(vec![Field::new("a", DataType::Null, false)]);
1160        let array = Arc::new(NullArray::new(usize::MAX)) as ArrayRef;
1161
1162        let err =
1163            StructArray::try_new_with_length(fields, vec![array], None, usize::MAX).unwrap_err();
1164        assert_eq!(
1165            err.to_string(),
1166            "Invalid argument error: Found unmasked nulls for non-nullable StructArray field \"a\"",
1167        );
1168    }
1169
1170    #[test]
1171    fn test_struct_array_fmt_debug() {
1172        let arr = StructArray::new(
1173            vec![Arc::new(Field::new("c", DataType::Int32, true))].into(),
1174            vec![Arc::new(Int32Array::from((0..30).collect::<Vec<_>>())) as ArrayRef],
1175            Some(NullBuffer::new(BooleanBuffer::from(
1176                (0..30).map(|i| i % 2 == 0).collect::<Vec<_>>(),
1177            ))),
1178        );
1179        assert_eq!(
1180            format!("{arr:?}"),
1181            "StructArray\n-- validity:\n[\n  valid,\n  null,\n  valid,\n  null,\n  valid,\n  null,\n  valid,\n  null,\n  valid,\n  null,\n  ...10 elements...,\n  valid,\n  null,\n  valid,\n  null,\n  valid,\n  null,\n  valid,\n  null,\n  valid,\n  null,\n]\n[\n-- child 0: \"c\" (Int32)\nPrimitiveArray<Int32>\n[\n  0,\n  1,\n  2,\n  3,\n  4,\n  5,\n  6,\n  7,\n  8,\n  9,\n  ...10 elements...,\n  20,\n  21,\n  22,\n  23,\n  24,\n  25,\n  26,\n  27,\n  28,\n  29,\n]\n]"
1182        )
1183    }
1184
1185    #[test]
1186    fn test_struct_array_logical_nulls() {
1187        // Field is non-nullable
1188        let field = Field::new("a", DataType::Int32, false);
1189        let values = vec![1, 2, 3];
1190        // Create a NullBuffer with all bits set to valid (true)
1191        let nulls = NullBuffer::from(vec![true, true, true]);
1192        let array = Int32Array::new(values.into(), Some(nulls));
1193        let child = Arc::new(array) as ArrayRef;
1194        assert!(child.logical_nulls().is_some());
1195        assert_eq!(child.logical_nulls().unwrap().null_count(), 0);
1196
1197        let fields = Fields::from(vec![field]);
1198        let arrays = vec![child];
1199        let nulls = None;
1200
1201        StructArray::try_new(fields, arrays, nulls).expect("should not error");
1202    }
1203
1204    #[test]
1205    fn test_flatten_no_nulls() {
1206        let child = Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef;
1207        let sa = StructArray::from(vec![(
1208            Arc::new(Field::new("a", DataType::Int32, false)),
1209            child,
1210        )]);
1211
1212        let (fields, columns) = sa.flatten();
1213
1214        assert_eq!(columns.len(), 1);
1215        assert!(!fields[0].is_nullable());
1216        assert_eq!(columns[0].null_count(), 0);
1217        assert_eq!(columns[0].len(), 3);
1218    }
1219
1220    #[test]
1221    fn test_flatten_struct_nulls_child_no_nulls() {
1222        let child = Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef;
1223        let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, false, true]));
1224        let sa = StructArray::new(
1225            Fields::from(vec![Field::new("a", DataType::Int32, false)]),
1226            vec![child],
1227            Some(struct_nulls),
1228        );
1229
1230        let (fields, columns) = sa.flatten();
1231
1232        assert!(fields[0].is_nullable());
1233        assert!(columns[0].is_valid(0));
1234        assert!(columns[0].is_null(1));
1235        assert!(columns[0].is_valid(2));
1236        assert_eq!(columns[0].null_count(), 1);
1237    }
1238
1239    #[test]
1240    fn test_flatten_both_have_nulls() {
1241        // struct validity: [valid, null,  valid, valid]
1242        // child validity:  [valid, valid, null,  valid]
1243        // expected:        [valid, null,  null,  valid]
1244        let child = Arc::new(Int32Array::from(vec![Some(1), Some(2), None, Some(4)])) as ArrayRef;
1245        let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, false, true, true]));
1246        let sa = StructArray::new(
1247            Fields::from(vec![Field::new("a", DataType::Int32, true)]),
1248            vec![child],
1249            Some(struct_nulls),
1250        );
1251
1252        let (fields, columns) = sa.flatten();
1253
1254        assert!(fields[0].is_nullable());
1255        assert!(columns[0].is_valid(0));
1256        assert!(columns[0].is_null(1));
1257        assert!(columns[0].is_null(2));
1258        assert!(columns[0].is_valid(3));
1259        assert_eq!(columns[0].null_count(), 2);
1260    }
1261
1262    #[test]
1263    fn test_flatten_sliced_struct() {
1264        let child = Arc::new(Int32Array::from(vec![1, 2, 3, 4])) as ArrayRef;
1265        let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, false, true, false]));
1266        let sa = StructArray::new(
1267            Fields::from(vec![Field::new("a", DataType::Int32, false)]),
1268            vec![child],
1269            Some(struct_nulls),
1270        );
1271        let sliced = sa.slice(1, 2);
1272
1273        let (fields, columns) = sliced.flatten();
1274
1275        assert!(fields[0].is_nullable());
1276        assert_eq!(columns[0].len(), 2);
1277        assert!(columns[0].is_null(0));
1278        assert!(columns[0].is_valid(1));
1279    }
1280
1281    #[test]
1282    fn test_flatten_multiple_children() {
1283        let int_child = Arc::new(Int32Array::from(vec![Some(1), Some(2), None])) as ArrayRef;
1284        let str_child = Arc::new(StringArray::from(vec![Some("a"), None, Some("c")])) as ArrayRef;
1285        let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, false, true]));
1286        let sa = StructArray::new(
1287            Fields::from(vec![
1288                Field::new("ints", DataType::Int32, true),
1289                Field::new("strs", DataType::Utf8, true),
1290            ]),
1291            vec![int_child, str_child],
1292            Some(struct_nulls),
1293        );
1294
1295        let (fields, columns) = sa.flatten();
1296
1297        assert_eq!(fields.len(), 2);
1298        // int: [valid, null(struct), null(child)] => null_count=2
1299        assert_eq!(columns[0].null_count(), 2);
1300        assert!(columns[0].is_valid(0));
1301        assert!(columns[0].is_null(1));
1302        assert!(columns[0].is_null(2));
1303        // str: [valid, null(struct+child), valid] => null_count=1
1304        assert_eq!(columns[1].null_count(), 1);
1305        assert!(columns[1].is_valid(0));
1306        assert!(columns[1].is_null(1));
1307        assert!(columns[1].is_valid(2));
1308    }
1309
1310    #[test]
1311    fn test_flatten_empty_struct() {
1312        let sa = StructArray::new_empty_fields(5, Some(NullBuffer::new_null(5)));
1313
1314        let (fields, columns) = sa.flatten();
1315
1316        assert_eq!(fields.len(), 0);
1317        assert_eq!(columns.len(), 0);
1318    }
1319
1320    #[test]
1321    fn test_flatten_field_nullability_update() {
1322        let non_null_child = Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef;
1323        let nullable_child = Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])) as ArrayRef;
1324        let struct_nulls = NullBuffer::new(BooleanBuffer::from(vec![true, true, false]));
1325        let sa = StructArray::new(
1326            Fields::from(vec![
1327                Field::new("non_null", DataType::Int32, false),
1328                Field::new("nullable", DataType::Int32, true),
1329            ]),
1330            vec![non_null_child, nullable_child],
1331            Some(struct_nulls),
1332        );
1333
1334        let (fields, _columns) = sa.flatten();
1335
1336        assert!(fields[0].is_nullable()); // was false, now true
1337        assert!(fields[1].is_nullable()); // was true, stays true
1338    }
1339}