Skip to main content

arrow_array/builder/
struct_array_assembler.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::{ArrayRef, StructArray};
6use arrow_buffer::NullBuffer;
7use arrow_schema::{ArrowError, Field, FieldRef, Fields};
8use std::sync::Arc;
9
10/// Assembles a [`StructArray`] from completed child arrays.
11///
12/// Unlike [`StructBuilder`](super::StructBuilder), which incrementally builds
13/// child arrays, this assembler combines arrays that have already been built.
14///
15/// # Example
16///
17/// ```
18/// # use std::sync::Arc;
19/// # use arrow_array::builder::StructArrayAssembler;
20/// # use arrow_array::{Array, ArrayRef, Int32Array, StringArray};
21///
22/// let names = Arc::new(StringArray::from(vec!["one", "two"])) as ArrayRef;
23/// let values = Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef;
24/// // Create struct array with `{name: ..., value: ...}` rows
25/// let array = StructArrayAssembler::new()
26///     .with_field("name", names, false)
27///     .with_field("value", values, false)
28///     .build()
29///     .unwrap();
30///
31/// assert_eq!(array.len(), 2);
32/// ```
33#[derive(Debug, Default, Clone)]
34pub struct StructArrayAssembler {
35    fields: Vec<FieldRef>,
36    arrays: Vec<ArrayRef>,
37    nulls: Option<NullBuffer>,
38}
39
40impl StructArrayAssembler {
41    /// Creates a new empty [`StructArrayAssembler`].
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    /// Adds an array with a field constructed from its data type.
47    pub fn with_field(
48        mut self,
49        field_name: impl Into<String>,
50        array: ArrayRef,
51        nullable: bool,
52    ) -> Self {
53        self.fields.push(Arc::new(Field::new(
54            field_name,
55            array.data_type().clone(),
56            nullable,
57        )));
58        self.arrays.push(array);
59        self
60    }
61
62    /// Adds an array using a caller-supplied field.
63    ///
64    /// This preserves field metadata that would be lost if the field were
65    /// constructed from the array's data type alone.
66    pub fn with_field_ref(mut self, field: FieldRef, array: ArrayRef) -> Self {
67        self.fields.push(field);
68        self.arrays.push(array);
69        self
70    }
71
72    /// Sets the top-level null buffer for the struct array.
73    pub fn with_nulls(mut self, nulls: NullBuffer) -> Self {
74        self.nulls = Some(nulls);
75        self
76    }
77
78    /// Builds the [`StructArray`].
79    ///
80    /// # Errors
81    ///
82    /// Returns an error if the fields, child arrays, or null buffer have
83    /// incompatible data types or lengths.
84    pub fn build(self) -> Result<StructArray, ArrowError> {
85        StructArray::try_new(Fields::from(self.fields), self.arrays, self.nulls)
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::{Array, Int32Array, StringArray};
93    use arrow_schema::DataType;
94    use std::collections::HashMap;
95
96    #[test]
97    fn build_from_completed_arrays() {
98        let names = Arc::new(StringArray::from(vec!["one", "two"])) as ArrayRef;
99        let values = Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef;
100        let metadata = HashMap::from([("key".to_string(), "value".to_string())]);
101        let value_field =
102            Arc::new(Field::new("value", DataType::Int32, false).with_metadata(metadata.clone()));
103        let nulls = NullBuffer::from(vec![true, false]);
104
105        let array = StructArrayAssembler::new()
106            .with_field("name", names, false)
107            .with_field_ref(value_field, values)
108            .with_nulls(nulls.clone())
109            .build()
110            .unwrap();
111
112        assert_eq!(array.len(), 2);
113        assert_eq!(array.column_names(), &["name", "value"]);
114        assert_eq!(array.fields()[1].metadata(), &metadata);
115        assert_eq!(array.nulls(), Some(&nulls));
116    }
117
118    #[test]
119    fn build_errors_on_mismatched_child_lengths() {
120        let names = Arc::new(StringArray::from(vec!["one", "two"])) as ArrayRef;
121        let values = Arc::new(Int32Array::from(vec![1])) as ArrayRef;
122
123        let err = StructArrayAssembler::new()
124            .with_field("name", names, false)
125            .with_field("value", values, false)
126            .build()
127            .unwrap_err();
128
129        assert_eq!(
130            err.to_string(),
131            "Invalid argument error: Incorrect array length for StructArray field \"value\", expected 2 got 1"
132        );
133    }
134
135    #[test]
136    fn build_errors_on_mismatched_field_data_type() {
137        let value_field = Arc::new(Field::new("value", DataType::Int64, false));
138        let values = Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef;
139
140        let err = StructArrayAssembler::new()
141            .with_field_ref(value_field, values)
142            .build()
143            .unwrap_err();
144
145        assert_eq!(
146            err.to_string(),
147            "Invalid argument error: Incorrect datatype for StructArray field \"value\", expected Int64 got Int32"
148        );
149    }
150}