Skip to main content

vortex_array/builders/
struct_.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5
6use itertools::Itertools;
7use vortex_buffer::BufferAllocatorRef;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_error::vortex_ensure_eq;
11use vortex_error::vortex_panic;
12
13use crate::ArrayRef;
14use crate::ExecutionCtx;
15use crate::IntoArray;
16use crate::array::ArrayView;
17use crate::arrays::Struct;
18use crate::arrays::StructArray;
19use crate::arrays::struct_::StructArrayExt;
20use crate::builders::ArrayBuilder;
21use crate::builders::ChildBuilder;
22use crate::builders::DEFAULT_BUILDER_CAPACITY;
23use crate::builders::ValidityBuilder;
24use crate::canonical::Canonical;
25use crate::dtype::DType;
26use crate::dtype::Nullability;
27use crate::dtype::StructFields;
28use crate::scalar::Scalar;
29use crate::scalar::StructScalar;
30
31/// The builder for building a [`StructArray`].
32pub struct StructBuilder {
33    dtype: DType,
34    builders: Vec<ChildBuilder>,
35    nulls: ValidityBuilder,
36}
37
38impl StructBuilder {
39    /// Creates a new `StructBuilder` with a capacity of [`DEFAULT_BUILDER_CAPACITY`].
40    #[deprecated(note = "use `new_in` with an explicit allocator")]
41    pub fn new(struct_dtype: StructFields, nullability: Nullability) -> Self {
42        Self::new_in(struct_dtype, nullability, BufferAllocatorRef::static_ref())
43    }
44
45    /// Creates a new `StructBuilder` with the default capacity using `allocator`.
46    pub fn new_in(
47        struct_dtype: StructFields,
48        nullability: Nullability,
49        allocator: &BufferAllocatorRef,
50    ) -> Self {
51        Self::with_capacity_in(
52            struct_dtype,
53            nullability,
54            DEFAULT_BUILDER_CAPACITY,
55            allocator,
56        )
57    }
58
59    /// Creates a new `StructBuilder` with the given `capacity`.
60    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
61    pub fn with_capacity(
62        struct_dtype: StructFields,
63        nullability: Nullability,
64        capacity: usize,
65    ) -> Self {
66        Self::with_capacity_in(
67            struct_dtype,
68            nullability,
69            capacity,
70            BufferAllocatorRef::static_ref(),
71        )
72    }
73
74    /// Creates a new `StructBuilder` with `capacity` using `allocator`.
75    pub fn with_capacity_in(
76        struct_dtype: StructFields,
77        nullability: Nullability,
78        capacity: usize,
79        allocator: &BufferAllocatorRef,
80    ) -> Self {
81        let builders = struct_dtype
82            .fields()
83            .map(|dt| ChildBuilder::with_capacity(&dt, capacity, allocator))
84            .collect();
85
86        Self {
87            builders,
88            nulls: ValidityBuilder::new(capacity, allocator),
89            dtype: DType::Struct(struct_dtype, nullability),
90        }
91    }
92
93    /// Appends a struct `value` to the builder.
94    pub fn append_value(&mut self, struct_scalar: StructScalar) -> VortexResult<()> {
95        if !self.dtype.is_nullable() && struct_scalar.is_null() {
96            vortex_bail!("Tried to append a null `StructScalar` to a non-nullable struct builder",);
97        }
98
99        if struct_scalar.struct_fields() != self.struct_fields() {
100            vortex_bail!(
101                "Tried to append a `StructScalar` with fields {} to a \
102                    struct builder with fields {}",
103                struct_scalar.struct_fields(),
104                self.struct_fields()
105            );
106        }
107
108        if let Some(fields) = struct_scalar.fields_iter() {
109            for (builder, field) in self.builders.iter_mut().zip_eq(fields) {
110                builder.append_scalar(&field)?;
111            }
112            self.nulls.append_non_null();
113        } else {
114            self.append_null()
115        }
116
117        Ok(())
118    }
119
120    /// Finishes the builder directly into a [`StructArray`].
121    pub fn finish_into_struct(&mut self) -> StructArray {
122        let len = self.len();
123        let fields = self
124            .builders
125            .iter_mut()
126            .map(|builder| builder.finish())
127            .collect::<Vec<_>>();
128
129        for (index, field) in fields.iter().enumerate() {
130            assert_eq!(
131                field.len(),
132                len,
133                "Field {index} does not have expected length {len}"
134            );
135        }
136
137        let validity = self.nulls.finish_with_nullability(self.dtype.nullability());
138
139        // SAFETY: each field is finished by the child builder this builder made for that field of
140        // the struct dtype, so the fields match the dtype in order, and the assert above pairs
141        // every one of them with the `len` rows the validity covers.
142        unsafe { StructArray::new_unchecked(fields, self.struct_fields().clone(), len, validity) }
143    }
144
145    /// The [`StructFields`] of this struct builder.
146    pub fn struct_fields(&self) -> &StructFields {
147        let DType::Struct(struct_fields, _) = &self.dtype else {
148            vortex_panic!("`StructBuilder` somehow had dtype {}", self.dtype);
149        };
150
151        struct_fields
152    }
153
154    /// Appends the values of a canonical [`StructArray`] to the builder, recursing into each
155    /// field's builder.
156    pub(crate) fn append_struct_array(
157        &mut self,
158        array: ArrayView<'_, Struct>,
159        ctx: &mut ExecutionCtx,
160    ) -> VortexResult<()> {
161        for (field, builder) in array
162            .iter_unmasked_fields()
163            .zip_eq(self.builders.iter_mut())
164        {
165            builder.append_array(field, ctx)?;
166        }
167
168        self.nulls.append_validity(array.validity()?, array.len());
169        Ok(())
170    }
171}
172
173impl ArrayBuilder for StructBuilder {
174    fn as_any(&self) -> &dyn Any {
175        self
176    }
177
178    fn as_any_mut(&mut self) -> &mut dyn Any {
179        self
180    }
181
182    fn dtype(&self) -> &DType {
183        &self.dtype
184    }
185
186    fn len(&self) -> usize {
187        self.nulls.len()
188    }
189
190    fn append_zeros(&mut self, n: usize) {
191        self.builders
192            .iter_mut()
193            .for_each(|builder| builder.append_zeros(n));
194        self.nulls.append_n_non_nulls(n);
195    }
196
197    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
198        self.builders
199            .iter_mut()
200            // We push zero values into our children when appending a null in case the children are
201            // themselves non-nullable.
202            .for_each(|builder| builder.append_defaults(n));
203        self.nulls.append_n_nulls(n);
204    }
205
206    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
207        vortex_ensure_eq!(
208            scalar.dtype(),
209            self.dtype(),
210            "StructBuilder received a scalar with the wrong dtype"
211        );
212
213        self.append_value(scalar.as_struct())
214    }
215
216    fn reserve_chunks(&mut self, additional: usize) {
217        self.builders.iter_mut().for_each(|builder| {
218            builder.reserve_chunks(additional);
219        });
220        self.nulls.reserve_runs(additional);
221    }
222
223    fn reserve_exact(&mut self, capacity: usize) {
224        self.builders.iter_mut().for_each(|builder| {
225            builder.reserve_exact(capacity);
226        });
227        self.nulls.reserve_exact(capacity);
228    }
229
230    fn finish(&mut self) -> ArrayRef {
231        self.finish_into_struct().into_array()
232    }
233
234    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
235        Canonical::Struct(self.finish_into_struct())
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use std::sync::LazyLock;
242
243    use vortex_buffer::BufferAllocatorRef;
244    use vortex_error::VortexResult;
245    use vortex_session::VortexSession;
246
247    use crate::IntoArray;
248    use crate::VortexSessionExecute;
249    use crate::arrays::NullArray;
250    use crate::arrays::PrimitiveArray;
251    use crate::arrays::VarBinArray;
252    use crate::assert_arrays_eq;
253    use crate::builders::ArrayBuilder;
254    use crate::builders::struct_::StructArray;
255    use crate::builders::struct_::StructBuilder;
256    use crate::dtype::DType;
257    use crate::dtype::Nullability;
258    use crate::dtype::PType::I32;
259    use crate::dtype::StructFields;
260    use crate::scalar::Scalar;
261    use crate::validity::Validity;
262
263    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
264
265    #[test]
266    fn test_struct_builder() {
267        let sdt = StructFields::new(["a", "b"].into(), vec![I32.into(), I32.into()]);
268        let dtype = DType::Struct(sdt.clone(), Nullability::NonNullable);
269        let mut builder = StructBuilder::with_capacity_in(
270            sdt,
271            Nullability::NonNullable,
272            0,
273            BufferAllocatorRef::static_ref(),
274        );
275
276        builder
277            .append_value(Scalar::struct_(dtype.clone(), vec![1.into(), 2.into()]).as_struct())
278            .unwrap();
279
280        let struct_ = builder.finish();
281        assert_eq!(struct_.len(), 1);
282        assert_eq!(struct_.dtype(), &dtype);
283        assert_eq!(
284            struct_
285                .execute_scalar(0, &mut SESSION.create_execution_ctx())
286                .unwrap(),
287            Scalar::struct_(dtype, vec![1i32.into(), 2i32.into()])
288        );
289    }
290
291    #[test]
292    fn test_append_nullable_struct() {
293        let sdt = StructFields::new(["a", "b"].into(), vec![I32.into(), I32.into()]);
294        let dtype = DType::Struct(sdt.clone(), Nullability::Nullable);
295        let mut builder = StructBuilder::with_capacity_in(
296            sdt,
297            Nullability::Nullable,
298            0,
299            BufferAllocatorRef::static_ref(),
300        );
301
302        builder
303            .append_value(Scalar::struct_(dtype.clone(), vec![1.into(), 2.into()]).as_struct())
304            .unwrap();
305
306        builder.append_nulls(2);
307
308        let struct_ = builder.finish();
309        assert_eq!(struct_.len(), 3);
310        assert_eq!(struct_.dtype(), &dtype);
311        assert_eq!(
312            struct_
313                .valid_count(&mut SESSION.create_execution_ctx())
314                .unwrap(),
315            1
316        );
317        let mut ctx = SESSION.create_execution_ctx();
318        assert_eq!(
319            struct_.execute_scalar(0, &mut ctx).unwrap(),
320            Scalar::struct_(dtype.clone(), vec![1i32.into(), 2i32.into()])
321        );
322        assert_eq!(
323            struct_.execute_scalar(1, &mut ctx).unwrap(),
324            Scalar::null(dtype.clone())
325        );
326        assert_eq!(
327            struct_.execute_scalar(2, &mut ctx).unwrap(),
328            Scalar::null(dtype)
329        );
330    }
331
332    #[test]
333    fn test_append_scalar() {
334        let mut ctx = SESSION.create_execution_ctx();
335        use crate::scalar::Scalar;
336
337        let dtype = DType::Struct(
338            StructFields::from_iter([
339                ("a", DType::Primitive(I32, Nullability::Nullable)),
340                ("b", DType::Utf8(Nullability::Nullable)),
341            ]),
342            Nullability::Nullable,
343        );
344
345        let struct_fields = match &dtype {
346            DType::Struct(fields, _) => fields.clone(),
347            _ => panic!("Expected struct dtype"),
348        };
349        let mut builder = StructBuilder::new_in(
350            struct_fields,
351            Nullability::Nullable,
352            BufferAllocatorRef::static_ref(),
353        );
354
355        // Test appending a valid struct value.
356        let struct_scalar1 = Scalar::struct_(
357            dtype.clone(),
358            vec![
359                Scalar::primitive(42i32, Nullability::Nullable),
360                Scalar::utf8("hello", Nullability::Nullable),
361            ],
362        );
363        builder.append_scalar(&struct_scalar1).unwrap();
364
365        // Test appending another struct value.
366        let struct_scalar2 = Scalar::struct_(
367            dtype.clone(),
368            vec![
369                Scalar::primitive(84i32, Nullability::Nullable),
370                Scalar::utf8("world", Nullability::Nullable),
371            ],
372        );
373        builder.append_scalar(&struct_scalar2).unwrap();
374
375        // Test appending null value.
376        let null_scalar = Scalar::null(dtype.clone());
377        builder.append_scalar(&null_scalar).unwrap();
378
379        let array = builder.finish_into_struct();
380
381        let expected = StructArray::try_from_iter_with_validity(
382            [
383                (
384                    "a",
385                    PrimitiveArray::from_option_iter([Some(42i32), Some(84), Some(123)])
386                        .into_array(),
387                ),
388                (
389                    "b",
390                    <VarBinArray as FromIterator<_>>::from_iter([
391                        Some("hello"),
392                        Some("world"),
393                        Some("x"),
394                    ])
395                    .into_array(),
396                ),
397            ],
398            Validity::from_iter([true, true, false]),
399        )
400        .unwrap();
401        assert_arrays_eq!(&array, &expected, &mut ctx);
402
403        // Test wrong dtype error.
404        let struct_fields = match &dtype {
405            DType::Struct(fields, _) => fields.clone(),
406            _ => panic!("Expected struct dtype"),
407        };
408        let mut builder = StructBuilder::new_in(
409            struct_fields,
410            Nullability::NonNullable,
411            BufferAllocatorRef::static_ref(),
412        );
413        let wrong_scalar = Scalar::from(42i32);
414        assert!(builder.append_scalar(&wrong_scalar).is_err());
415    }
416
417    #[test]
418    fn finish_with_null_child_after_mixed_appends() -> VortexResult<()> {
419        let mut ctx = SESSION.create_execution_ctx();
420        let source = StructArray::from_fields(&[
421            ("a", NullArray::new(1).into_array()),
422            ("b", PrimitiveArray::from_iter([7i32]).into_array()),
423        ])?;
424
425        let mut builder = StructBuilder::new_in(
426            source.dtype().as_struct_fields().clone(),
427            Nullability::NonNullable,
428            BufferAllocatorRef::static_ref(),
429        );
430        builder.append_scalar(&Scalar::default_value(builder.dtype()))?;
431        source
432            .into_array()
433            .append_to_builder(&mut builder, &mut ctx)?;
434
435        let finished = builder.finish_into_struct();
436        let expected = StructArray::from_fields(&[
437            ("a", NullArray::new(2).into_array()),
438            ("b", PrimitiveArray::from_iter([0i32, 7]).into_array()),
439        ])?;
440        assert_arrays_eq!(&finished, &expected, &mut ctx);
441        Ok(())
442    }
443}