Skip to main content

vortex_arrow/
import_nullability.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Apply declared nullability during Arrow array import.
5//!
6//! Leaf and container conversions share the [session's import rules]. Extension storage imports
7//! use a field derived from the storage dtype so they can apply those rules without rebuilding the
8//! Arrow array.
9//!
10//! [session's import rules]: crate::ArrowSession::from_arrow_array
11
12use std::sync::Arc;
13
14use arrow_buffer::NullBuffer;
15use arrow_schema::DataType;
16use arrow_schema::Field;
17use vortex_array::ArrayRef;
18use vortex_array::builtins::ArrayBuiltins;
19use vortex_array::dtype::DType;
20use vortex_array::scalar::Scalar;
21use vortex_array::validity::Validity;
22use vortex_error::VortexResult;
23use vortex_error::vortex_panic;
24
25use crate::convert::nulls;
26
27/// Build the leaf with the validity needed to defer any fill until execution.
28pub(crate) fn import_leaf(
29    arrow_nulls: Option<&NullBuffer>,
30    nullable: bool,
31    import: impl FnOnce(Validity) -> ArrayRef,
32) -> VortexResult<ArrayRef> {
33    let needs_fill = !nullable && arrow_nulls.is_some_and(|nulls| nulls.null_count() > 0);
34    let validity = nulls(arrow_nulls, nullable || needs_fill)?;
35    let array = import(validity);
36    if !needs_fill {
37        return Ok(array);
38    }
39
40    let zero = Scalar::zero_value(&array.dtype().as_nonnullable());
41    array.fill_null(zero)
42}
43
44/// Convert an Arrow null buffer for a container that keeps its storage.
45///
46/// See [`crate::ArrowSession::from_arrow_array`] for the nullability rules.
47pub fn level_validity(null_buffer: Option<&NullBuffer>, nullable: bool) -> VortexResult<Validity> {
48    if nullable {
49        nulls(null_buffer, true)
50    } else {
51        Ok(Validity::NonNullable)
52    }
53}
54
55/// Apply a compatible Vortex storage dtype's nullability to the Arrow import field.
56///
57/// Each extension importer owns its storage layout, so recursion stops at nested extension
58/// fields.
59pub(crate) fn storage_import_field(field: &Field, dtype: &DType) -> Field {
60    let field = field.clone().with_nullable(dtype.is_nullable());
61
62    let data_type = match (field.data_type(), dtype) {
63        (DataType::Struct(fields), DType::Struct(declared, _)) => DataType::Struct(
64            fields
65                .iter()
66                .zip(declared.fields())
67                .map(|(child, dtype)| storage_import_field(child, &dtype))
68                .collect(),
69        ),
70        (DataType::List(child), DType::List(element, _)) => {
71            DataType::List(Arc::new(storage_import_field(child, element)))
72        }
73        (DataType::LargeList(child), DType::List(element, _)) => {
74            DataType::LargeList(Arc::new(storage_import_field(child, element)))
75        }
76        (DataType::ListView(child), DType::List(element, _)) => {
77            DataType::ListView(Arc::new(storage_import_field(child, element)))
78        }
79        (DataType::LargeListView(child), DType::List(element, _)) => {
80            DataType::LargeListView(Arc::new(storage_import_field(child, element)))
81        }
82        (DataType::FixedSizeList(child, size), DType::FixedSizeList(element, ..)) => {
83            DataType::FixedSizeList(Arc::new(storage_import_field(child, element)), *size)
84        }
85        (DataType::Map(entries, keys_sorted), DType::Map(map, _)) => {
86            let DataType::Struct(fields) = entries.data_type() else {
87                vortex_panic!(
88                    "The Arrow storage dtype check requires struct map entries, got {}",
89                    entries.data_type()
90                );
91            };
92            let fields = [
93                Arc::new(storage_import_field(&fields[0], &map.key_dtype())),
94                Arc::new(storage_import_field(&fields[1], &map.value_dtype())),
95            ];
96            let entries = entries
97                .as_ref()
98                .clone()
99                .with_data_type(DataType::Struct(fields.into()));
100            DataType::Map(Arc::new(entries), *keys_sorted)
101        }
102        (DataType::Dictionary(key, value), _) => {
103            let value_field = field.clone().with_data_type(value.as_ref().clone());
104            let value = storage_import_field(&value_field, dtype);
105            DataType::Dictionary(key.clone(), Box::new(value.data_type().clone()))
106        }
107        (DataType::RunEndEncoded(ends, value), _) => DataType::RunEndEncoded(
108            Arc::clone(ends),
109            Arc::new(storage_import_field(value, dtype)),
110        ),
111        _ => return field,
112    };
113
114    field.with_data_type(data_type)
115}