Skip to main content

vortex_array/arrays/union/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexResult;
5use vortex_error::vortex_bail;
6use vortex_error::vortex_err;
7use vortex_error::vortex_panic;
8use vortex_session::registry::CachedId;
9
10use crate::ArrayRef;
11use crate::ExecutionCtx;
12use crate::ExecutionResult;
13use crate::array::Array;
14use crate::array::ArrayId;
15use crate::array::ArrayParts;
16use crate::array::ArrayView;
17use crate::array::EmptyArrayData;
18use crate::array::VTable;
19use crate::array::with_empty_buffers;
20use crate::arrays::union::UnionArrayExt;
21use crate::arrays::union::UnionSlots;
22use crate::buffer::BufferHandle;
23use crate::builders::ArrayBuilder;
24use crate::dtype::DType;
25
26mod operations;
27mod plugin;
28mod validate;
29mod validity;
30
31/// A canonical [`Union`]-encoded array.
32///
33/// This is similar to Arrow's "spase" union type.
34pub type UnionArray = Array<Union>;
35
36/// The canonical Union encoding.
37///
38/// This is similar to Arrow's "spase" union type.
39///
40/// # Serialized form
41///
42/// `vortex.union` has no buffers, and its metadata is a protobuf message with no fields yet. The
43/// children are `[type_ids, variant_0, ..., variant_{n-1}]`, where `n` is the number of variants
44/// in the union dtype, so every child's position follows from the dtype alone. Outer nulls live in the `type_ids` child, whose
45/// nullability is the union's, so there is no separate validity child.
46///
47/// Readers require at least `1 + n` children and ignore any that follow. A later writer may
48/// append a child under this ID only if decoding without it still yields the same values, such as
49/// a statistic or an index. A child or metadata field that changes the decoded values needs a new
50/// encoding ID. Readers ignore unknown metadata fields and reject malformed metadata and any
51/// buffers.
52#[derive(Clone, Debug)]
53pub struct Union;
54
55impl VTable for Union {
56    type TypedArrayData = EmptyArrayData;
57    type OperationsVTable = Self;
58    type ValidityVTable = Self;
59
60    fn id(&self) -> ArrayId {
61        static ID: CachedId = CachedId::new("vortex.union");
62        *ID
63    }
64
65    fn validate(
66        &self,
67        _data: &EmptyArrayData,
68        dtype: &DType,
69        len: usize,
70        slots: &[Option<ArrayRef>],
71    ) -> VortexResult<()> {
72        let type_ids = slots
73            .get(UnionSlots::TYPE_IDS)
74            .and_then(Option::as_ref)
75            .ok_or_else(|| vortex_err!("UnionArray is missing its type_ids slot"))?;
76        let variant_arrays = slots
77            .get(UnionSlots::CHILDREN_OFFSET..)
78            .unwrap_or_default()
79            .iter()
80            .enumerate()
81            .map(|(index, slot)| {
82                slot.as_ref()
83                    .ok_or_else(|| vortex_err!("UnionArray is missing child {index}"))
84            })
85            .collect::<VortexResult<Vec<_>>>()?;
86
87        validate::validate_union_components(type_ids, &variant_arrays, dtype, len)
88    }
89
90    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
91        0
92    }
93
94    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
95        vortex_panic!("UnionArray buffer index {idx} out of bounds")
96    }
97
98    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
99        vortex_panic!("UnionArray buffer_name index {idx} out of bounds")
100    }
101
102    fn with_buffers(
103        &self,
104        array: ArrayView<'_, Self>,
105        buffers: &[BufferHandle],
106    ) -> VortexResult<ArrayParts<Self>> {
107        with_empty_buffers(self, array, buffers)
108    }
109
110    fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String {
111        if idx == UnionSlots::TYPE_IDS {
112            "type_ids".to_string()
113        } else {
114            array.variants().names()[idx - UnionSlots::CHILDREN_OFFSET].to_string()
115        }
116    }
117
118    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
119        Ok(ExecutionResult::done(array))
120    }
121
122    fn append_to_builder(
123        _array: ArrayView<'_, Self>,
124        _builder: &mut dyn ArrayBuilder,
125        _ctx: &mut ExecutionCtx,
126    ) -> VortexResult<()> {
127        vortex_bail!("TODO(connor)[Union]: implement append_to_builder for Union arrays")
128    }
129}