vortex_array/arrays/variant/vtable/
mod.rs1mod operations;
5mod plugin;
6mod validity;
7
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_ensure_eq;
13use vortex_error::vortex_panic;
14use vortex_session::registry::CachedId;
15use vortex_utils::aliases::hash_set::HashSet;
16
17use crate::ArrayRef;
18use crate::ExecutionCtx;
19use crate::ExecutionResult;
20use crate::array::Array;
21use crate::array::ArrayId;
22use crate::array::ArrayParts;
23use crate::array::ArrayView;
24use crate::array::EmptyArrayData;
25use crate::array::VTable;
26use crate::array::with_empty_buffers;
27use crate::arrays::variant::VariantSlots;
28use crate::buffer::BufferHandle;
29use crate::builders::ArrayBuilder;
30use crate::builders::VariantBuilder;
31use crate::dtype::DType;
32use crate::dtype::FieldName;
33use crate::dtype::FieldNames;
34use crate::dtype::Nullability;
35use crate::dtype::StructFields;
36use crate::proto::dtype as pb;
37use crate::scalar::Scalar;
38use crate::scalar::ScalarValue;
39
40pub type VariantArray = Array<Variant>;
42
43#[derive(Clone, Debug)]
44pub struct Variant;
45
46#[derive(Clone, prost::Message)]
47struct VariantMetadataProto {
48 #[prost(message, optional, tag = "1")]
49 pub(crate) shredded_dtype: Option<pb::DType>,
50}
51
52impl VTable for Variant {
53 type TypedArrayData = EmptyArrayData;
54
55 type OperationsVTable = Self;
56
57 type ValidityVTable = Self;
58
59 fn id(&self) -> ArrayId {
60 static ID: CachedId = CachedId::new("vortex.variant");
61 *ID
62 }
63
64 fn validate(
65 &self,
66 _data: &Self::TypedArrayData,
67 dtype: &DType,
68 len: usize,
69 slots: &[Option<ArrayRef>],
70 ) -> VortexResult<()> {
71 vortex_ensure_eq!(slots.len(), VariantSlots::COUNT);
72 vortex_ensure!(
73 slots[VariantSlots::CORE_STORAGE].is_some(),
74 "VariantArray core_storage slot must be present"
75 );
76 let core_storage = slots[VariantSlots::CORE_STORAGE]
77 .as_ref()
78 .vortex_expect("validated core_storage slot presence");
79 vortex_ensure!(
80 matches!(dtype, DType::Variant(_)),
81 "Expected Variant DType, got {dtype}"
82 );
83 vortex_ensure_eq!(
84 core_storage.dtype(),
85 dtype,
86 "VariantArray core_storage dtype does not match outer dtype",
87 );
88 vortex_ensure_eq!(
89 core_storage.len(),
90 len,
91 "VariantArray core_storage length does not match outer length",
92 );
93 if let Some(shredded) = slots[VariantSlots::SHREDDED].as_ref() {
94 vortex_ensure_eq!(
95 shredded.len(),
96 len,
97 "VariantArray shredded length does not match outer length",
98 );
99 }
100 Ok(())
101 }
102
103 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
104 0
105 }
106
107 fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
108 vortex_panic!("VariantArray buffer index {idx} out of bounds")
109 }
110
111 fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
112 None
113 }
114
115 fn with_buffers(
116 &self,
117 array: ArrayView<'_, Self>,
118 buffers: &[BufferHandle],
119 ) -> VortexResult<ArrayParts<Self>> {
120 with_empty_buffers(self, array, buffers)
121 }
122
123 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
124 match VariantSlots::NAMES.get(idx) {
125 Some(name) => (*name).to_string(),
126 None => vortex_panic!("VariantArray slot_name index {idx} out of bounds"),
127 }
128 }
129
130 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
131 Ok(ExecutionResult::done(array))
132 }
133
134 fn append_to_builder(
135 array: ArrayView<'_, Self>,
136 builder: &mut dyn ArrayBuilder,
137 ctx: &mut ExecutionCtx,
138 ) -> VortexResult<()> {
139 let Some(builder) = builder.as_any_mut().downcast_mut::<VariantBuilder>() else {
140 vortex_bail!("append_to_builder for a Variant requires a VariantBuilder");
141 };
142 builder.append_variant_array(&array.into_owned(), ctx)
143 }
144}
145
146pub fn merge_typed_scalar_as_variant(
149 typed_scalar: Scalar,
150 fallback_scalar: Option<Scalar>,
151 dtype: &DType,
152) -> VortexResult<Scalar> {
153 let scalar = if typed_scalar.is_null() {
154 fallback_scalar.unwrap_or_else(|| Scalar::null(dtype.clone()))
155 } else if matches!(
156 typed_scalar.dtype(),
157 DType::List(..) | DType::FixedSizeList(..)
158 ) {
159 Scalar::variant(typed_list_as_variant_payload(typed_scalar)?)
160 } else if typed_scalar.dtype().is_struct() {
161 merge_typed_object_as_variant(typed_scalar, fallback_scalar)?
162 } else if typed_scalar.dtype().is_variant() {
163 typed_scalar
164 } else {
165 Scalar::variant(typed_scalar)
166 };
167
168 if scalar.dtype() == dtype {
169 Ok(scalar)
170 } else {
171 scalar.cast(dtype)
172 }
173}
174
175fn typed_list_as_variant_payload(typed_scalar: Scalar) -> VortexResult<Scalar> {
176 let list = typed_scalar.as_list();
177 let elements = list
178 .elements()
179 .unwrap_or_default()
180 .into_iter()
181 .map(|element| {
182 if element.dtype().is_variant() {
183 element
184 } else {
185 Scalar::variant(element)
186 }
187 })
188 .collect();
189 Ok(Scalar::list(
190 DType::Variant(Nullability::NonNullable),
191 elements,
192 Nullability::NonNullable,
193 ))
194}
195
196fn merge_typed_object_as_variant(
197 typed_scalar: Scalar,
198 fallback_scalar: Option<Scalar>,
199) -> VortexResult<Scalar> {
200 let fallback_inner = fallback_scalar
201 .as_ref()
202 .and_then(|scalar| scalar.as_variant().value())
203 .filter(|scalar| scalar.dtype().is_struct() && !scalar.is_null());
204 let Some(fallback_inner) = fallback_inner else {
205 return Ok(Scalar::variant(typed_scalar));
206 };
207
208 merge_struct_payload(&typed_scalar, Some(fallback_inner)).map(Scalar::variant)
209}
210
211fn merge_struct_payload(typed: &Scalar, raw: Option<&Scalar>) -> VortexResult<Scalar> {
212 let typed_struct = typed.as_struct();
213 let raw_struct = raw
214 .filter(|scalar| scalar.dtype().is_struct() && !scalar.is_null())
215 .map(Scalar::as_struct);
216 let mut present_typed_fields = HashSet::new();
217 let mut names = Vec::new();
218 let mut values = Vec::new();
219
220 for name in typed_struct.names().iter() {
221 let Some(typed_field) = typed_struct.field(name.as_ref()) else {
222 continue;
223 };
224 if typed_field.is_null() {
225 continue;
226 }
227
228 let raw_field = raw_struct.and_then(|raw_struct| raw_struct.field(name.as_ref()));
229 let raw_payload = raw_field.as_ref().and_then(|scalar| {
230 if scalar.dtype().is_variant() {
231 scalar.as_variant().value()
232 } else {
233 Some(scalar)
234 }
235 });
236 let field = if typed_field.dtype().is_struct()
237 && raw_payload.is_some_and(|raw| raw.dtype().is_struct() && !raw.is_null())
238 {
239 Scalar::variant(merge_struct_payload(&typed_field, raw_payload)?)
240 } else if typed_field.dtype().is_variant() {
241 typed_field.cast(&DType::Variant(Nullability::NonNullable))?
242 } else {
243 Scalar::variant(typed_field)
244 };
245
246 present_typed_fields.insert(name.as_ref().to_string());
247 names.push(FieldName::from(name.as_ref()));
248 values.push(field.into_value());
249 }
250
251 if let Some(raw_struct) = raw_struct {
252 for name in raw_struct.names().iter() {
253 if present_typed_fields.contains(name.as_ref()) {
254 continue;
255 }
256 let Some(raw_field) = raw_struct.field(name.as_ref()) else {
257 continue;
258 };
259 if raw_field.is_null() {
260 continue;
261 }
262 let raw_field = if raw_field.dtype().is_variant() {
263 raw_field.cast(&DType::Variant(Nullability::NonNullable))?
264 } else {
265 Scalar::variant(raw_field)
266 };
267 names.push(FieldName::from(name.as_ref()));
268 values.push(raw_field.into_value());
269 }
270 }
271
272 let fields = StructFields::new(
273 FieldNames::from(names),
274 vec![DType::Variant(Nullability::NonNullable); values.len()],
275 );
276 Scalar::try_new(
277 DType::Struct(fields, Nullability::NonNullable),
278 Some(ScalarValue::Tuple(values)),
279 )
280}
281
282#[cfg(test)]
283mod tests {}