Skip to main content

vortex_functions/variant_get/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod variant;
5use std::fmt;
6use std::fmt::Display;
7use std::fmt::Formatter;
8
9use prost::Message;
10use vortex_array::ArrayRef;
11use vortex_array::ExecutionCtx;
12use vortex_array::IntoArray;
13use vortex_array::arrays::ScalarFn;
14use vortex_array::arrays::ScalarFnArray;
15use vortex_array::arrays::scalar_fn::ScalarFnArrayExt;
16use vortex_array::builders::VariantBuilder;
17use vortex_array::builders::builder_with_capacity_in;
18use vortex_array::builtins::ArrayBuiltins;
19use vortex_array::dtype::DType;
20use vortex_array::dtype::FieldName;
21use vortex_array::dtype::Nullability;
22use vortex_array::proto::expr as pb;
23use vortex_array::proto::expr::variant_path_element;
24use vortex_array::scalar::Scalar;
25use vortex_array::scalar_fn::Arity;
26use vortex_array::scalar_fn::ChildName;
27use vortex_array::scalar_fn::ExecutionArgs;
28use vortex_array::scalar_fn::ScalarFnId;
29use vortex_array::scalar_fn::ScalarFnVTable;
30use vortex_array::scalar_fn::ScalarFnVTableExt;
31use vortex_array::scalar_fn::builtin::mask::Mask;
32use vortex_array::scalar_fn::display::ExprDisplay;
33use vortex_array::scalar_fn::session::ScalarFnSessionExt;
34use vortex_error::VortexResult;
35use vortex_error::vortex_ensure;
36use vortex_error::vortex_err;
37use vortex_session::VortexSession;
38use vortex_session::registry::CachedId;
39use vortex_utils::aliases::StringEscape;
40
41/// Registers [`VariantGet`] and its kernel for canonical variant arrays.
42pub(crate) fn initialize(session: &VortexSession) {
43    session.scalar_fns().register(VariantGet);
44    variant::initialize(session);
45}
46
47/// Extracts a field/index path from Variant values.
48///
49/// Missing paths, type mismatches while traversing, and failed casts produce nulls. Without a
50/// requested dtype, results are returned as nullable Variant values; with one, results are cast to
51/// that dtype with nullable nullability. Encodings may serve perfectly shredded paths directly,
52/// but must fall back to the core Variant value for paths not represented by shredded storage.
53#[derive(Clone)]
54pub struct VariantGet;
55
56impl VariantGet {
57    /// Creates a lazy extraction from Variant `input`.
58    ///
59    /// # Errors
60    ///
61    /// Returns an error if `input` is not Variant data.
62    pub fn try_new(input: ArrayRef, options: VariantGetOptions) -> VortexResult<ScalarFnArray> {
63        ScalarFnArray::try_new(VariantGet.bind(options), [input])
64    }
65}
66
67impl ScalarFnVTable for VariantGet {
68    type Options = VariantGetOptions;
69
70    fn id(&self) -> ScalarFnId {
71        static ID: CachedId = CachedId::new("vortex.variant_get");
72        *ID
73    }
74
75    fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
76        let path = options
77            .path()
78            .elements()
79            .iter()
80            .map(VariantPathElement::to_proto)
81            .collect();
82        let dtype = options.dtype().map(TryInto::try_into).transpose()?;
83
84        Ok(Some(pb::VariantGetOpts { path, dtype }.encode_to_vec()))
85    }
86
87    fn deserialize(&self, metadata: &[u8], session: &VortexSession) -> VortexResult<Self::Options> {
88        let opts = pb::VariantGetOpts::decode(metadata)?;
89        let path = opts
90            .path
91            .into_iter()
92            .map(VariantPathElement::from_proto)
93            .collect::<VortexResult<_>>()?;
94        let dtype = opts
95            .dtype
96            .as_ref()
97            .map(|dtype| DType::from_proto(dtype, session))
98            .transpose()?;
99
100        Ok(VariantGetOptions::new(path, dtype))
101    }
102
103    fn arity(&self, _options: &Self::Options) -> Arity {
104        Arity::Exact(1)
105    }
106
107    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
108        match child_idx {
109            0 => ChildName::from("input"),
110            _ => unreachable!("Invalid child index {child_idx} for VariantGet expression"),
111        }
112    }
113
114    fn fmt_sql(
115        &self,
116        options: &Self::Options,
117        expr: &dyn ExprDisplay,
118        f: &mut Formatter<'_>,
119    ) -> fmt::Result {
120        write!(f, "variant_get(")?;
121        Display::fmt(expr.display_child(0), f)?;
122        let path = options.path().to_string();
123        write!(f, ", \"{}\"", StringEscape(&path))?;
124        if let Some(dtype) = options.dtype() {
125            write!(f, ", {dtype}")?;
126        }
127        write!(f, ")")
128    }
129
130    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
131        let input_dtype = &arg_dtypes[0];
132        vortex_ensure!(
133            matches!(input_dtype, DType::Variant(_)),
134            "VariantGet input must be Variant, found {input_dtype}"
135        );
136
137        // Missing paths, traversal mismatches, and cast failures all produce nulls.
138        Ok(options
139            .dtype()
140            .map_or(DType::Variant(Nullability::Nullable), DType::as_nullable))
141    }
142
143    fn execute(
144        &self,
145        options: &Self::Options,
146        args: &dyn ExecutionArgs,
147        ctx: &mut ExecutionCtx,
148    ) -> VortexResult<ArrayRef> {
149        let input = args.get(0)?;
150        // Missing paths, traversal mismatches, and cast failures all produce nulls.
151        let dtype = options
152            .dtype()
153            .map_or(DType::Variant(Nullability::Nullable), DType::as_nullable);
154
155        // A mask only nulls rows out, so it commutes with extraction.
156        if let Some(masked) = input.as_opt::<ScalarFn>()
157            && masked.scalar_fn().id() == Mask.id()
158        {
159            return VariantGet::try_new(masked.child_at(0).clone(), options.clone())?
160                .into_array()
161                .execute::<ArrayRef>(ctx)?
162                .mask(masked.child_at(1).clone())?
163                .execute::<ArrayRef>(ctx);
164        }
165
166        if !dtype.is_variant() {
167            let mut builder = builder_with_capacity_in(&dtype, input.len(), ctx.allocator());
168            for idx in 0..input.len() {
169                let scalar = input.execute_scalar(idx, ctx)?;
170                let output = variant_get_scalar(&scalar, options, &dtype)?;
171                builder.append_scalar(&output)?;
172            }
173
174            return Ok(builder.finish());
175        }
176
177        let mut builder = VariantBuilder::new(dtype.nullability());
178        for idx in 0..input.len() {
179            let scalar = input.execute_scalar(idx, ctx)?;
180            builder.append_n_scalars(&variant_get_scalar(&scalar, options, &dtype)?, 1)?;
181        }
182        builder.finish_into_variant().map(IntoArray::into_array)
183    }
184
185    fn is_strict(&self, _options: &Self::Options) -> bool {
186        true
187    }
188}
189
190fn variant_get_scalar(
191    scalar: &Scalar,
192    options: &VariantGetOptions,
193    output_dtype: &DType,
194) -> VortexResult<Scalar> {
195    let Some(value) = variant_path_scalar(scalar, options.path().elements())? else {
196        return Ok(Scalar::null(output_dtype.clone()));
197    };
198
199    if options.dtype().is_none_or(DType::is_variant) {
200        return Scalar::variant(value).cast(output_dtype);
201    }
202
203    if value.is_null() {
204        return Ok(Scalar::null(output_dtype.clone()));
205    }
206
207    value
208        .cast(output_dtype)
209        .or_else(|_| Ok(Scalar::null(output_dtype.clone())))
210}
211
212fn variant_path_scalar(
213    scalar: &Scalar,
214    path: &[VariantPathElement],
215) -> VortexResult<Option<Scalar>> {
216    let mut current = match variant_payload(scalar.clone()) {
217        Some(value) => value,
218        None => return Ok(None),
219    };
220
221    for element in path {
222        current = match variant_payload(current) {
223            Some(value) => value,
224            None => return Ok(None),
225        };
226
227        if current.is_null() {
228            return Ok(None);
229        }
230
231        current = match element {
232            VariantPathElement::Field(name) => {
233                let Some(struct_scalar) = current.as_struct_opt() else {
234                    return Ok(None);
235                };
236                if struct_scalar.is_null() {
237                    return Ok(None);
238                }
239                let Some(field) = struct_scalar.field(name.as_ref()) else {
240                    return Ok(None);
241                };
242                field
243            }
244            VariantPathElement::Index(index) => {
245                let Ok(index) = usize::try_from(*index) else {
246                    return Ok(None);
247                };
248                let Some(list_scalar) = current.as_list_opt() else {
249                    return Ok(None);
250                };
251                let Some(element) = list_scalar.element(index) else {
252                    return Ok(None);
253                };
254                element
255            }
256        };
257    }
258
259    Ok(variant_payload(current))
260}
261
262fn variant_payload(scalar: Scalar) -> Option<Scalar> {
263    if scalar.dtype().is_variant() {
264        scalar.as_variant().value().cloned()
265    } else {
266        Some(scalar)
267    }
268}
269
270/// Options for [`VariantGet`].
271#[derive(Clone, Debug, PartialEq, Eq, Hash)]
272pub struct VariantGetOptions {
273    path: VariantPath,
274    dtype: Option<DType>,
275}
276
277impl VariantGetOptions {
278    /// Creates options for extracting `path`, returning Variant values when `dtype` is `None`.
279    pub fn new(path: VariantPath, dtype: Option<DType>) -> Self {
280        Self { path, dtype }
281    }
282
283    /// Returns the path to extract.
284    pub fn path(&self) -> &VariantPath {
285        &self.path
286    }
287
288    /// Returns the requested output dtype, if any.
289    pub fn dtype(&self) -> Option<&DType> {
290        self.dtype.as_ref()
291    }
292}
293
294impl Display for VariantGetOptions {
295    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
296        write!(f, "{}", self.path)?;
297        if let Some(dtype) = &self.dtype {
298            write!(f, " as {dtype}")?;
299        }
300        Ok(())
301    }
302}
303
304/// A strict Variant path made from object fields and list indexes.
305#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
306pub struct VariantPath(Vec<VariantPathElement>);
307
308impl VariantPath {
309    /// Creates a path from explicit elements.
310    pub fn new(elements: impl IntoIterator<Item = VariantPathElement>) -> Self {
311        Self(elements.into_iter().collect())
312    }
313
314    /// Creates the root path.
315    pub fn root() -> Self {
316        Self::default()
317    }
318
319    /// Creates a path containing one object field.
320    pub fn field(field: impl Into<FieldName>) -> Self {
321        Self(vec![VariantPathElement::field(field)])
322    }
323
324    /// Returns the path elements.
325    pub fn elements(&self) -> &[VariantPathElement] {
326        &self.0
327    }
328
329    /// Returns whether this path references the root Variant value.
330    pub fn is_root(&self) -> bool {
331        self.0.is_empty()
332    }
333}
334
335impl FromIterator<VariantPathElement> for VariantPath {
336    fn from_iter<T: IntoIterator<Item = VariantPathElement>>(iter: T) -> Self {
337        Self(iter.into_iter().collect())
338    }
339}
340
341impl From<VariantPathElement> for VariantPath {
342    fn from(value: VariantPathElement) -> Self {
343        Self(vec![value])
344    }
345}
346
347impl Display for VariantPath {
348    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
349        write!(f, "$")?;
350        for element in self.elements() {
351            match element {
352                VariantPathElement::Field(name) => write!(f, ".{name}")?,
353                VariantPathElement::Index(index) => write!(f, "[{index}]")?,
354            }
355        }
356        Ok(())
357    }
358}
359
360/// A single field or index step in a [`VariantPath`].
361#[derive(Clone, Debug, PartialEq, Eq, Hash)]
362pub enum VariantPathElement {
363    /// Select an object field by name.
364    Field(FieldName),
365    /// Select a list element by zero-based index.
366    Index(u64),
367}
368
369impl VariantPathElement {
370    /// Creates an object-field path element.
371    pub fn field(field: impl Into<FieldName>) -> Self {
372        Self::Field(field.into())
373    }
374
375    /// Creates a list-index path element.
376    pub fn index(index: u64) -> Self {
377        Self::Index(index)
378    }
379
380    /// Decodes a path element from its protobuf representation.
381    pub fn from_proto(value: pb::VariantPathElement) -> VortexResult<Self> {
382        match value
383            .element
384            .ok_or_else(|| vortex_err!("Variant path element missing value"))?
385        {
386            variant_path_element::Element::Field(field) => Ok(Self::field(field)),
387            variant_path_element::Element::Index(index) => Ok(Self::index(index)),
388        }
389    }
390
391    /// Encodes this path element into its protobuf representation.
392    pub fn to_proto(&self) -> pb::VariantPathElement {
393        match self {
394            VariantPathElement::Field(name) => pb::VariantPathElement {
395                element: Some(variant_path_element::Element::Field(
396                    name.as_ref().to_string(),
397                )),
398            },
399            VariantPathElement::Index(index) => pb::VariantPathElement {
400                element: Some(variant_path_element::Element::Index(*index)),
401            },
402        }
403    }
404}
405
406impl From<FieldName> for VariantPathElement {
407    fn from(value: FieldName) -> Self {
408        Self::field(value)
409    }
410}
411
412impl From<&str> for VariantPathElement {
413    fn from(value: &str) -> Self {
414        Self::field(value)
415    }
416}
417
418impl From<u64> for VariantPathElement {
419    fn from(value: u64) -> Self {
420        Self::index(value)
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use std::sync::LazyLock;
427
428    use vortex_array::ArrayRef;
429    use vortex_array::Canonical;
430    use vortex_array::IntoArray;
431    use vortex_array::VortexSessionExecute;
432    use vortex_array::arrays::Chunked;
433    use vortex_array::arrays::ChunkedArray;
434    use vortex_array::arrays::ConstantArray;
435    use vortex_array::arrays::PrimitiveArray;
436    use vortex_array::arrays::StructArray;
437    use vortex_array::arrays::VariantArray;
438    use vortex_array::arrays::variant::VariantArraySlotsExt;
439    use vortex_array::assert_arrays_eq;
440    use vortex_array::assert_nth_scalar_is_null;
441    use vortex_array::dtype::DType;
442    use vortex_array::dtype::FieldName;
443    use vortex_array::dtype::FieldNames;
444    use vortex_array::dtype::Nullability;
445    use vortex_array::dtype::PType;
446    use vortex_array::dtype::StructFields;
447    use vortex_array::optimizer::ArrayOptimizer;
448    use vortex_array::scalar::Scalar;
449    use vortex_array::scalar::ScalarValue;
450    use vortex_array::scalar_fn::ScalarFnVTable;
451    use vortex_error::VortexResult;
452    use vortex_error::vortex_bail;
453    use vortex_error::vortex_ensure;
454    use vortex_error::vortex_err;
455    use vortex_expr::ArrayExprExt;
456    use vortex_expr::Expression;
457    use vortex_expr::proto::ExprSerializeProtoExt;
458    use vortex_expr::root;
459    use vortex_session::VortexSession;
460
461    use crate::expr::variant_get;
462    use crate::variant_get::VariantGet;
463    use crate::variant_get::VariantGetOptions;
464    use crate::variant_get::VariantPath;
465    use crate::variant_get::VariantPathElement;
466
467    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
468        let session = VortexSession::empty();
469
470        vortex_array::initialize(&session);
471
472        crate::initialize(&session);
473
474        session
475    });
476
477    fn variant_object(fields: impl IntoIterator<Item = (&'static str, Scalar)>) -> Scalar {
478        let fields = fields.into_iter().collect::<Vec<_>>();
479        let names = FieldNames::from_iter(fields.iter().map(|(name, _)| FieldName::from(*name)));
480        let dtypes = vec![DType::Variant(Nullability::NonNullable); fields.len()];
481        let values = fields
482            .into_iter()
483            .map(|(_, value)| Scalar::variant(value).into_value())
484            .collect();
485        Scalar::try_new(
486            DType::Struct(StructFields::new(names, dtypes), Nullability::NonNullable),
487            Some(ScalarValue::Tuple(values)),
488        )
489        .unwrap()
490    }
491
492    fn variant_rows(rows: impl IntoIterator<Item = Scalar>) -> VortexResult<ArrayRef> {
493        let dtype = DType::Variant(Nullability::Nullable);
494        let chunks = rows
495            .into_iter()
496            .map(|row| ConstantArray::new(row.cast(&dtype).unwrap(), 1).into_array());
497        ChunkedArray::try_new(chunks, dtype.clone()).map(|array| array.into_array())
498    }
499
500    /// Test-only syntax for keeping `variant_get` cases compact without committing
501    /// to a public string grammar yet.
502    fn parse_path(path: &str) -> VortexResult<VariantPath> {
503        if path.is_empty() || path == "$" {
504            return Ok(VariantPath::root());
505        }
506
507        let mut elements = Vec::new();
508        let mut pos = usize::from(path.as_bytes().first() == Some(&b'$'));
509        if pos == 1
510            && path
511                .as_bytes()
512                .get(pos)
513                .is_some_and(|byte| !matches!(byte, b'.' | b'['))
514        {
515            vortex_bail!("Invalid Variant path {path:?}: expected '.' or '[' after '$'");
516        }
517
518        while pos < path.len() {
519            match path.as_bytes()[pos] {
520                b'.' => {
521                    pos += 1;
522                    let (field, next_pos) = parse_field(path, pos)?;
523                    elements.push(VariantPathElement::field(field));
524                    pos = next_pos;
525                }
526                b'[' => {
527                    let (index, next_pos) = parse_index(path, pos + 1)?;
528                    elements.push(VariantPathElement::index(index));
529                    pos = next_pos;
530                }
531                _ if pos == 0 => {
532                    let (field, next_pos) = parse_field(path, pos)?;
533                    elements.push(VariantPathElement::field(field));
534                    pos = next_pos;
535                }
536                _ => {
537                    vortex_bail!("Invalid Variant path {path:?}: expected '.', '[', or end of path")
538                }
539            }
540        }
541
542        Ok(VariantPath::new(elements))
543    }
544
545    fn parse_field(path: &str, start: usize) -> VortexResult<(&str, usize)> {
546        let mut pos = start;
547        while path
548            .as_bytes()
549            .get(pos)
550            .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
551        {
552            pos += 1;
553        }
554        vortex_ensure!(
555            pos > start,
556            "Invalid Variant path {path:?}: expected field name"
557        );
558        Ok((&path[start..pos], pos))
559    }
560
561    fn parse_index(path: &str, start: usize) -> VortexResult<(u64, usize)> {
562        let mut pos = start;
563        while path
564            .as_bytes()
565            .get(pos)
566            .is_some_and(|byte| byte.is_ascii_digit())
567        {
568            pos += 1;
569        }
570        vortex_ensure!(
571            pos > start,
572            "Invalid Variant path {path:?}: expected list index"
573        );
574        vortex_ensure!(
575            path.as_bytes().get(pos) == Some(&b']'),
576            "Invalid Variant path {path:?}: expected closing ']'"
577        );
578        let index = path[start..pos]
579            .parse()
580            .map_err(|_| vortex_err!("Invalid Variant path {path:?}: list index is too large"))?;
581        Ok((index, pos + 1))
582    }
583
584    fn execute_variant_get(
585        array: ArrayRef,
586        path: &str,
587        dtype: Option<DType>,
588    ) -> VortexResult<ArrayRef> {
589        let expr = variant_get(root(), parse_path(path)?, dtype);
590        array
591            .apply(&expr)?
592            .optimize_ctx(&SESSION)?
593            .execute::<ArrayRef>(&mut SESSION.create_execution_ctx())
594    }
595
596    #[test]
597    fn variant_get_path_parse_and_display() {
598        let path = parse_path("$.data[1].a").unwrap();
599        assert_eq!(
600            path.elements(),
601            &[
602                VariantPathElement::field("data"),
603                VariantPathElement::index(1),
604                VariantPathElement::field("a")
605            ]
606        );
607        assert_eq!(path.to_string(), "$.data[1].a");
608
609        let bare_path = parse_path("data[2]").unwrap();
610        assert_eq!(bare_path.to_string(), "$.data[2]");
611    }
612
613    #[test]
614    fn variant_get_return_dtype_is_nullable_variant_without_requested_dtype() {
615        let expr = variant_get(root(), VariantPath::field("data"), None);
616        let dtype = expr
617            .return_dtype(&DType::Variant(Nullability::NonNullable))
618            .unwrap();
619
620        assert_eq!(dtype, DType::Variant(Nullability::Nullable));
621    }
622
623    #[test]
624    fn variant_get_return_dtype_makes_requested_dtype_nullable() {
625        let requested = DType::Primitive(PType::I64, Nullability::NonNullable);
626        let expr = variant_get(root(), VariantPath::field("data"), Some(requested));
627        let dtype = expr
628            .return_dtype(&DType::Variant(Nullability::NonNullable))
629            .unwrap();
630
631        assert_eq!(dtype, DType::Primitive(PType::I64, Nullability::Nullable));
632    }
633
634    #[test]
635    fn variant_get_rejects_non_variant_input() {
636        let expr = variant_get(root(), VariantPath::field("data"), None);
637        let err = expr
638            .return_dtype(&DType::Utf8(Nullability::NonNullable))
639            .unwrap_err();
640
641        assert!(err.to_string().contains("VariantGet input must be Variant"));
642    }
643
644    #[test]
645    fn variant_get_formats_sql() {
646        let expr = variant_get(
647            root(),
648            parse_path("$.data[1].a").unwrap(),
649            Some(DType::Utf8(Nullability::NonNullable)),
650        );
651
652        assert_eq!(expr.to_string(), "variant_get($, \"$.data[1].a\", utf8)");
653    }
654
655    #[test]
656    fn variant_get_options_roundtrip_serialization() {
657        let options = VariantGetOptions::new(
658            VariantPath::new([
659                VariantPathElement::field("data"),
660                VariantPathElement::index(1),
661                VariantPathElement::field("a"),
662            ]),
663            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
664        );
665        let metadata = VariantGet.serialize(&options).unwrap().unwrap();
666        let actual = VariantGet.deserialize(&metadata, &SESSION).unwrap();
667
668        assert_eq!(actual, options);
669    }
670
671    #[test]
672    fn variant_get_expression_roundtrip_serialization() {
673        let expr: Expression = variant_get(
674            root(),
675            parse_path("$.data[1].a").unwrap(),
676            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
677        );
678        let proto = expr.serialize_proto().unwrap();
679        let actual = Expression::from_proto(&proto, &SESSION).unwrap();
680
681        assert_eq!(actual, expr);
682    }
683
684    #[test]
685    fn variant_get_generic_fallback_extracts_field_and_list_index() -> VortexResult<()> {
686        let items = Scalar::list(
687            DType::Variant(Nullability::NonNullable),
688            vec![
689                Scalar::variant(Scalar::primitive(10i32, Nullability::NonNullable)),
690                Scalar::variant(Scalar::primitive(20i32, Nullability::NonNullable)),
691            ],
692            Nullability::NonNullable,
693        );
694        let array = variant_rows([
695            Scalar::variant(variant_object([("items", items)])),
696            Scalar::variant(variant_object([(
697                "items",
698                Scalar::list_empty(
699                    DType::Variant(Nullability::NonNullable).into(),
700                    Nullability::NonNullable,
701                ),
702            )])),
703            Scalar::variant(variant_object([(
704                "items",
705                Scalar::list(
706                    DType::Variant(Nullability::NonNullable),
707                    vec![
708                        Scalar::variant(Scalar::utf8("x", Nullability::NonNullable)),
709                        Scalar::variant(Scalar::utf8("wrong", Nullability::NonNullable)),
710                    ],
711                    Nullability::NonNullable,
712                ),
713            )])),
714        ])?;
715
716        let result = execute_variant_get(
717            array,
718            "$.items[1]",
719            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
720        )?;
721        let mut ctx = SESSION.create_execution_ctx();
722
723        assert_arrays_eq!(
724            result,
725            PrimitiveArray::from_option_iter([Some(20i32), None, None]),
726            &mut ctx
727        );
728        Ok(())
729    }
730
731    #[test]
732    fn variant_get_reads_chunked_variant_input() -> VortexResult<()> {
733        let array = variant_rows([
734            Scalar::variant(variant_object([(
735                "a",
736                Scalar::primitive(10i32, Nullability::NonNullable),
737            )])),
738            Scalar::variant(variant_object([(
739                "b",
740                Scalar::primitive(20i32, Nullability::NonNullable),
741            )])),
742            Scalar::variant(variant_object([(
743                "a",
744                Scalar::primitive(30i32, Nullability::NonNullable),
745            )])),
746            Scalar::null(DType::Variant(Nullability::Nullable)),
747        ])?;
748        assert!(array.is::<Chunked>());
749
750        let result = execute_variant_get(
751            array,
752            "$.a",
753            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
754        )?;
755        let mut ctx = SESSION.create_execution_ctx();
756
757        assert_arrays_eq!(
758            result,
759            PrimitiveArray::from_option_iter([Some(10i32), None, Some(30), None]),
760            &mut ctx
761        );
762        Ok(())
763    }
764
765    #[test]
766    fn variant_get_fallback_typed_output_is_contiguous() -> VortexResult<()> {
767        let array = variant_rows([
768            Scalar::variant(variant_object([(
769                "a",
770                Scalar::primitive(10i32, Nullability::NonNullable),
771            )])),
772            Scalar::variant(variant_object([(
773                "a",
774                Scalar::primitive(20i32, Nullability::NonNullable),
775            )])),
776            Scalar::variant(variant_object([(
777                "b",
778                Scalar::primitive(30i32, Nullability::NonNullable),
779            )])),
780        ])?;
781
782        let result = execute_variant_get(
783            array,
784            "$.a",
785            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
786        )?;
787
788        assert!(!result.is::<Chunked>());
789        let mut ctx = SESSION.create_execution_ctx();
790        assert_arrays_eq!(
791            result,
792            PrimitiveArray::from_option_iter([Some(10i32), Some(20), None]),
793            &mut ctx
794        );
795        Ok(())
796    }
797
798    #[test]
799    fn variant_get_generic_fallback_preserves_variant_null() -> VortexResult<()> {
800        let array = variant_rows([
801            Scalar::variant(variant_object([(
802                "a",
803                Scalar::utf8("ok", Nullability::NonNullable),
804            )])),
805            Scalar::null(DType::Variant(Nullability::Nullable)),
806            Scalar::variant(variant_object([("a", Scalar::null(DType::Null))])),
807            Scalar::variant(variant_object([(
808                "b",
809                Scalar::primitive(2i32, Nullability::NonNullable),
810            )])),
811        ])?;
812
813        let result = execute_variant_get(array, "$.a", None)?;
814
815        let mut ctx = SESSION.create_execution_ctx();
816        let row0 = result.execute_scalar(0, &mut ctx)?;
817        assert_eq!(
818            row0.as_variant()
819                .value()
820                .and_then(|value| value.as_utf8().value())
821                .map(|value| value.as_str()),
822            Some("ok")
823        );
824        assert_nth_scalar_is_null!(result, 1, &mut ctx);
825        assert_eq!(
826            result
827                .execute_scalar(2, &mut ctx)?
828                .as_variant()
829                .is_variant_null(),
830            Some(true)
831        );
832        assert_nth_scalar_is_null!(result, 3, &mut ctx);
833        Ok(())
834    }
835
836    #[test]
837    fn variant_get_fallback_variant_output_canonicalizes() -> VortexResult<()> {
838        let array = variant_rows([
839            Scalar::variant(variant_object([(
840                "a",
841                Scalar::primitive(10i32, Nullability::NonNullable),
842            )])),
843            Scalar::variant(variant_object([(
844                "a",
845                Scalar::primitive(20i32, Nullability::NonNullable),
846            )])),
847        ])?;
848
849        let result = execute_variant_get(array, "$.a", None)?;
850        let variant = result
851            .clone()
852            .execute::<VariantArray>(&mut SESSION.create_execution_ctx())?;
853        let canonical = result.execute::<Canonical>(&mut SESSION.create_execution_ctx())?;
854        let Canonical::Variant(canonical_variant) = canonical else {
855            vortex_bail!("expected Variant canonical array");
856        };
857
858        assert_eq!(variant.len(), 2);
859        assert_eq!(canonical_variant.len(), 2);
860        assert_eq!(variant.core_storage().dtype(), variant.dtype());
861        assert_eq!(variant.core_storage().len(), variant.len());
862
863        let mut ctx = SESSION.create_execution_ctx();
864        for array in [variant, canonical_variant] {
865            assert_eq!(array.dtype(), &DType::Variant(Nullability::Nullable));
866            for (idx, expected) in [10i32, 20].into_iter().enumerate() {
867                let scalar = array.execute_scalar(idx, &mut ctx)?;
868                let actual = scalar
869                    .as_variant()
870                    .value()
871                    .and_then(|value| value.as_primitive().as_::<i32>());
872                assert_eq!(actual, Some(expected), "row {idx}");
873            }
874        }
875        Ok(())
876    }
877
878    fn row_storage(values: impl IntoIterator<Item = i32>) -> VortexResult<ArrayRef> {
879        Ok(ChunkedArray::try_new(
880            values.into_iter().map(|value| {
881                ConstantArray::new(
882                    Scalar::variant(Scalar::primitive(value, Nullability::NonNullable)),
883                    1,
884                )
885                .into_array()
886            }),
887            DType::Variant(Nullability::NonNullable),
888        )?
889        .into_array())
890    }
891
892    #[test]
893    fn variant_get_keeps_valid_shredded_rows_for_matching_dtype() -> VortexResult<()> {
894        let mut ctx = SESSION.create_execution_ctx();
895        let core_storage = row_storage([1, 2, 3])?;
896        let shredded = StructArray::try_from_iter([(
897            "a",
898            PrimitiveArray::from_iter([10i32, 20, 30]).into_array(),
899        )])?;
900        let variant = VariantArray::try_new(core_storage, Some(shredded.into_array()))?;
901        let expr = variant_get(
902            root(),
903            VariantPath::field("a"),
904            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
905        );
906
907        let result = variant.into_array().apply(&expr)?;
908
909        assert_arrays_eq!(
910            result,
911            PrimitiveArray::from_option_iter([Some(10i32), Some(20), Some(30)]),
912            &mut ctx
913        );
914        Ok(())
915    }
916
917    #[test]
918    fn variant_get_treats_value_and_typed_value_as_logical_field_names() -> VortexResult<()> {
919        let mut ctx = SESSION.create_execution_ctx();
920        let core_storage = row_storage([1, 2, 3])?;
921        let shredded = StructArray::try_from_iter([
922            (
923                "value",
924                PrimitiveArray::from_iter([10i32, 20, 30]).into_array(),
925            ),
926            (
927                "typed_value",
928                PrimitiveArray::from_iter([40i32, 50, 60]).into_array(),
929            ),
930        ])?;
931        let variant = VariantArray::try_new(core_storage, Some(shredded.into_array()))?;
932
933        let value_expr = variant_get(
934            root(),
935            VariantPath::field("value"),
936            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
937        );
938        let value_result = variant.clone().into_array().apply(&value_expr)?;
939        assert_arrays_eq!(
940            value_result,
941            PrimitiveArray::from_option_iter([Some(10i32), Some(20), Some(30)]),
942            &mut ctx
943        );
944
945        let typed_value_expr = variant_get(
946            root(),
947            VariantPath::field("typed_value"),
948            Some(DType::Primitive(PType::I32, Nullability::NonNullable)),
949        );
950        let typed_value_result = variant.into_array().apply(&typed_value_expr)?;
951        assert_arrays_eq!(
952            typed_value_result,
953            PrimitiveArray::from_option_iter([Some(40i32), Some(50), Some(60)]),
954            &mut ctx
955        );
956        Ok(())
957    }
958}