vortex_array/arrays/struct_/array.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::iter::once;
6use std::sync::Arc;
7
8use vortex_dtype::DType;
9use vortex_dtype::FieldName;
10use vortex_dtype::FieldNames;
11use vortex_dtype::StructFields;
12use vortex_error::VortexExpect;
13use vortex_error::VortexResult;
14use vortex_error::vortex_bail;
15use vortex_error::vortex_err;
16
17use crate::Array;
18use crate::ArrayRef;
19use crate::IntoArray;
20use crate::stats::ArrayStats;
21use crate::validity::Validity;
22use crate::vtable::ValidityHelper;
23
24/// A struct array that stores multiple named fields as columns, similar to a database row.
25///
26/// This mirrors the Apache Arrow Struct array encoding and provides a columnar representation
27/// of structured data where each row contains multiple named fields of potentially different types.
28///
29/// ## Data Layout
30///
31/// The struct array uses a columnar layout where:
32/// - Each field is stored as a separate child array
33/// - All fields must have the same length (number of rows)
34/// - Field names and types are defined in the struct's dtype
35/// - An optional validity mask indicates which entire rows are null
36///
37/// ## Row-level nulls
38///
39/// The StructArray contains its own top-level nulls, which are superimposed on top of the
40/// field-level validity values. This can be the case even if the fields themselves are non-nullable,
41/// accessing a particular row can yield nulls even if all children are valid at that position.
42///
43/// ```
44/// use vortex_array::arrays::{StructArray, BoolArray};
45/// use vortex_array::validity::Validity;
46/// use vortex_array::IntoArray;
47/// use vortex_dtype::FieldNames;
48/// use vortex_buffer::buffer;
49///
50/// // Create struct with all non-null fields but struct-level nulls
51/// let struct_array = StructArray::try_new(
52/// FieldNames::from(["a", "b", "c"]),
53/// vec![
54/// buffer![1i32, 2i32].into_array(), // non-null field a
55/// buffer![10i32, 20i32].into_array(), // non-null field b
56/// buffer![100i32, 200i32].into_array(), // non-null field c
57/// ],
58/// 2,
59/// Validity::Array(BoolArray::from_iter([true, false]).into_array()), // row 1 is null
60/// ).unwrap();
61///
62/// // Row 0 is valid - returns a struct scalar with field values
63/// let row0 = struct_array.scalar_at(0);
64/// assert!(!row0.is_null());
65///
66/// // Row 1 is null at struct level - returns null even though fields have values
67/// let row1 = struct_array.scalar_at(1);
68/// assert!(row1.is_null());
69/// ```
70///
71/// ## Name uniqueness
72///
73/// It is valid for a StructArray to have multiple child columns that have the same name. In this
74/// case, any accessors that use column names will find the first column in sequence with the name.
75///
76/// ```
77/// use vortex_array::arrays::StructArray;
78/// use vortex_array::validity::Validity;
79/// use vortex_array::IntoArray;
80/// use vortex_dtype::FieldNames;
81/// use vortex_buffer::buffer;
82///
83/// // Create struct with duplicate "data" field names
84/// let struct_array = StructArray::try_new(
85/// FieldNames::from(["data", "data"]),
86/// vec![
87/// buffer![1i32, 2i32].into_array(), // first "data"
88/// buffer![3i32, 4i32].into_array(), // second "data"
89/// ],
90/// 2,
91/// Validity::NonNullable,
92/// ).unwrap();
93///
94/// // field_by_name returns the FIRST "data" field
95/// let first_data = struct_array.field_by_name("data").unwrap();
96/// assert_eq!(first_data.scalar_at(0), 1i32.into());
97/// ```
98///
99/// ## Field Operations
100///
101/// Struct arrays support efficient column operations:
102/// - **Projection**: Select/reorder fields without copying data
103/// - **Field access**: Get columns by name or index
104/// - **Column addition**: Add new fields to create extended structs
105/// - **Column removal**: Remove fields to create narrower structs
106///
107/// ## Validity Semantics
108///
109/// - Row-level nulls are tracked in the struct's validity child
110/// - Individual field nulls are tracked in each field's own validity
111/// - A null struct row means all fields in that row are conceptually null
112/// - Field-level nulls can exist independently of struct-level nulls
113///
114/// # Examples
115///
116/// ```
117/// use vortex_array::arrays::{StructArray, PrimitiveArray};
118/// use vortex_array::validity::Validity;
119/// use vortex_array::IntoArray;
120/// use vortex_dtype::FieldNames;
121/// use vortex_buffer::buffer;
122///
123/// // Create arrays for each field
124/// let ids = PrimitiveArray::new(buffer![1i32, 2, 3], Validity::NonNullable);
125/// let names = PrimitiveArray::new(buffer![100u64, 200, 300], Validity::NonNullable);
126///
127/// // Create struct array with named fields
128/// let struct_array = StructArray::try_new(
129/// FieldNames::from(["id", "score"]),
130/// vec![ids.into_array(), names.into_array()],
131/// 3,
132/// Validity::NonNullable,
133/// ).unwrap();
134///
135/// assert_eq!(struct_array.len(), 3);
136/// assert_eq!(struct_array.names().len(), 2);
137///
138/// // Access field by name
139/// let id_field = struct_array.field_by_name("id").unwrap();
140/// assert_eq!(id_field.len(), 3);
141/// ```
142#[derive(Clone, Debug)]
143pub struct StructArray {
144 pub(super) len: usize,
145 pub(super) dtype: DType,
146 pub(super) fields: Arc<[ArrayRef]>,
147 pub(super) validity: Validity,
148 pub(super) stats_set: ArrayStats,
149}
150
151impl StructArray {
152 pub fn fields(&self) -> &Arc<[ArrayRef]> {
153 &self.fields
154 }
155
156 pub fn field_by_name(&self, name: impl AsRef<str>) -> VortexResult<&ArrayRef> {
157 let name = name.as_ref();
158 self.field_by_name_opt(name).ok_or_else(|| {
159 vortex_err!(
160 "Field {name} not found in struct array with names {:?}",
161 self.names()
162 )
163 })
164 }
165
166 pub fn field_by_name_opt(&self, name: impl AsRef<str>) -> Option<&ArrayRef> {
167 let name = name.as_ref();
168 self.struct_fields().find(name).map(|idx| &self.fields[idx])
169 }
170
171 pub fn names(&self) -> &FieldNames {
172 self.struct_fields().names()
173 }
174
175 pub fn struct_fields(&self) -> &StructFields {
176 let Some(struct_dtype) = &self.dtype.as_struct_fields_opt() else {
177 unreachable!(
178 "struct arrays must have be a DType::Struct, this is likely an internal bug."
179 )
180 };
181 struct_dtype
182 }
183
184 /// Create a new `StructArray` with the given length, but without any fields.
185 pub fn new_fieldless_with_len(len: usize) -> Self {
186 Self::try_new(
187 FieldNames::default(),
188 Vec::new(),
189 len,
190 Validity::NonNullable,
191 )
192 .vortex_expect("StructArray::new_with_len should not fail")
193 }
194
195 /// Creates a new [`StructArray`].
196 ///
197 /// # Panics
198 ///
199 /// Panics if the provided components do not satisfy the invariants documented
200 /// in [`StructArray::new_unchecked`].
201 pub fn new(
202 names: FieldNames,
203 fields: impl Into<Arc<[ArrayRef]>>,
204 length: usize,
205 validity: Validity,
206 ) -> Self {
207 Self::try_new(names, fields, length, validity)
208 .vortex_expect("StructArray construction failed")
209 }
210
211 /// Constructs a new `StructArray`.
212 ///
213 /// See [`StructArray::new_unchecked`] for more information.
214 ///
215 /// # Errors
216 ///
217 /// Returns an error if the provided components do not satisfy the invariants documented in
218 /// [`StructArray::new_unchecked`].
219 pub fn try_new(
220 names: FieldNames,
221 fields: impl Into<Arc<[ArrayRef]>>,
222 length: usize,
223 validity: Validity,
224 ) -> VortexResult<Self> {
225 let fields = fields.into();
226 let field_dtypes: Vec<_> = fields.iter().map(|d| d.dtype()).cloned().collect();
227 let dtype = StructFields::new(names, field_dtypes);
228
229 Self::validate(&fields, &dtype, length, &validity)?;
230
231 // SAFETY: validate ensures all invariants are met.
232 Ok(unsafe { Self::new_unchecked(fields, dtype, length, validity) })
233 }
234
235 /// Creates a new [`StructArray`] without validation from these components:
236 ///
237 /// * `fields` is a vector of arrays, one for each field in the struct.
238 /// * `dtype` contains the field names and types.
239 /// * `length` is the number of struct rows.
240 /// * `validity` holds the null values.
241 ///
242 /// # Safety
243 ///
244 /// The caller must ensure all of the following invariants are satisfied:
245 ///
246 /// ## Field Requirements
247 ///
248 /// - `fields.len()` must exactly equal `dtype.names().len()`.
249 /// - Every field array in `fields` must have length exactly equal to `length`.
250 /// - For each index `i`, `fields[i].dtype()` must exactly match `dtype.fields()[i]`.
251 ///
252 /// ## Type Requirements
253 ///
254 /// - Field names in `dtype` may be duplicated (this is explicitly allowed).
255 /// - The nullability of `dtype` must match the nullability of `validity`.
256 ///
257 /// ## Validity Requirements
258 ///
259 /// - If `validity` is [`Validity::Array`], its length must exactly equal `length`.
260 pub unsafe fn new_unchecked(
261 fields: impl Into<Arc<[ArrayRef]>>,
262 dtype: StructFields,
263 length: usize,
264 validity: Validity,
265 ) -> Self {
266 let fields = fields.into();
267
268 #[cfg(debug_assertions)]
269 Self::validate(&fields, &dtype, length, &validity)
270 .vortex_expect("[Debug Assertion]: Invalid `StructArray` parameters");
271
272 Self {
273 len: length,
274 dtype: DType::Struct(dtype, validity.nullability()),
275 fields,
276 validity,
277 stats_set: Default::default(),
278 }
279 }
280
281 /// Validates the components that would be used to create a [`StructArray`].
282 ///
283 /// This function checks all the invariants required by [`StructArray::new_unchecked`].
284 pub fn validate(
285 fields: &[ArrayRef],
286 dtype: &StructFields,
287 length: usize,
288 validity: &Validity,
289 ) -> VortexResult<()> {
290 // Check field count matches
291 if fields.len() != dtype.names().len() {
292 vortex_bail!(
293 "Got {} fields but dtype has {} names",
294 fields.len(),
295 dtype.names().len()
296 );
297 }
298
299 // Check each field's length and dtype
300 for (i, (field, struct_dt)) in fields.iter().zip(dtype.fields()).enumerate() {
301 if field.len() != length {
302 vortex_bail!(
303 "Field {} has length {} but expected {}",
304 i,
305 field.len(),
306 length
307 );
308 }
309
310 if field.dtype() != &struct_dt {
311 vortex_bail!(
312 "Field {} has dtype {} but expected {}",
313 i,
314 field.dtype(),
315 struct_dt
316 );
317 }
318 }
319
320 // Check validity length
321 if let Some(validity_len) = validity.maybe_len()
322 && validity_len != length
323 {
324 vortex_bail!(
325 "Validity has length {} but expected {}",
326 validity_len,
327 length
328 );
329 }
330
331 Ok(())
332 }
333
334 pub fn try_new_with_dtype(
335 fields: impl Into<Arc<[ArrayRef]>>,
336 dtype: StructFields,
337 length: usize,
338 validity: Validity,
339 ) -> VortexResult<Self> {
340 let fields = fields.into();
341 Self::validate(&fields, &dtype, length, &validity)?;
342
343 // SAFETY: validate ensures all invariants are met.
344 Ok(unsafe { Self::new_unchecked(fields, dtype, length, validity) })
345 }
346
347 pub fn from_fields<N: AsRef<str>>(items: &[(N, ArrayRef)]) -> VortexResult<Self> {
348 Self::try_from_iter(items.iter().map(|(a, b)| (a, b.to_array())))
349 }
350
351 pub fn try_from_iter_with_validity<
352 N: AsRef<str>,
353 A: IntoArray,
354 T: IntoIterator<Item = (N, A)>,
355 >(
356 iter: T,
357 validity: Validity,
358 ) -> VortexResult<Self> {
359 let (names, fields): (Vec<FieldName>, Vec<ArrayRef>) = iter
360 .into_iter()
361 .map(|(name, fields)| (FieldName::from(name.as_ref()), fields.into_array()))
362 .unzip();
363 let len = fields
364 .first()
365 .map(|f| f.len())
366 .ok_or_else(|| vortex_err!("StructArray cannot be constructed from an empty slice of arrays because the length is unspecified"))?;
367
368 Self::try_new(FieldNames::from_iter(names), fields, len, validity)
369 }
370
371 pub fn try_from_iter<N: AsRef<str>, A: IntoArray, T: IntoIterator<Item = (N, A)>>(
372 iter: T,
373 ) -> VortexResult<Self> {
374 Self::try_from_iter_with_validity(iter, Validity::NonNullable)
375 }
376
377 // TODO(aduffy): Add equivalent function to support field masks for nested column access.
378 /// Return a new StructArray with the given projection applied.
379 ///
380 /// Projection does not copy data arrays. Projection is defined by an ordinal array slice
381 /// which specifies the new ordering of columns in the struct. The projection can be used to
382 /// perform column re-ordering, deletion, or duplication at a logical level, without any data
383 /// copying.
384 pub fn project(&self, projection: &[FieldName]) -> VortexResult<Self> {
385 let mut children = Vec::with_capacity(projection.len());
386 let mut names = Vec::with_capacity(projection.len());
387
388 let fields = self.fields();
389 for f_name in projection.iter() {
390 let idx = self
391 .names()
392 .iter()
393 .position(|name| name == f_name)
394 .ok_or_else(|| vortex_err!("Unknown field {f_name}"))?;
395
396 names.push(self.names()[idx].clone());
397 children.push(fields[idx].clone());
398 }
399
400 StructArray::try_new(
401 FieldNames::from(names.as_slice()),
402 children,
403 self.len(),
404 self.validity().clone(),
405 )
406 }
407
408 /// Removes and returns a column from the struct array by name.
409 /// If the column does not exist, returns `None`.
410 pub fn remove_column(&mut self, name: impl Into<FieldName>) -> Option<ArrayRef> {
411 let name = name.into();
412
413 let struct_dtype = self.struct_fields().clone();
414
415 let position = struct_dtype
416 .names()
417 .iter()
418 .position(|field_name| field_name.as_ref() == name.as_ref())?;
419
420 let field = self.fields[position].clone();
421 let new_fields: Arc<[ArrayRef]> = self
422 .fields
423 .iter()
424 .enumerate()
425 .filter(|(i, _)| *i != position)
426 .map(|(_, f)| f.clone())
427 .collect();
428
429 if let Ok(new_dtype) = struct_dtype.without_field(position) {
430 self.fields = new_fields;
431 self.dtype = DType::Struct(new_dtype, self.dtype.nullability());
432 return Some(field);
433 }
434 None
435 }
436
437 /// Create a new StructArray by appending a new column onto the existing array.
438 pub fn with_column(&self, name: impl Into<FieldName>, array: ArrayRef) -> VortexResult<Self> {
439 let name = name.into();
440 let struct_dtype = self.struct_fields().clone();
441
442 let names = struct_dtype.names().iter().cloned().chain(once(name));
443 let types = struct_dtype.fields().chain(once(array.dtype().clone()));
444 let new_fields = StructFields::new(names.collect(), types.collect());
445
446 let children: Arc<[ArrayRef]> = self.fields.iter().cloned().chain(once(array)).collect();
447
448 Self::try_new_with_dtype(children, new_fields, self.len, self.validity.clone())
449 }
450}