Skip to main content

vortex_array/scalar_fn/fns/
get_item.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6use std::slice;
7
8use prost::Message;
9use vortex_error::VortexResult;
10use vortex_error::vortex_err;
11use vortex_session::VortexSession;
12use vortex_session::registry::CachedId;
13
14use crate::ArrayRef;
15use crate::ExecutionCtx;
16use crate::IntoArray;
17use crate::arrays::Constant;
18use crate::arrays::ConstantArray;
19use crate::arrays::ScalarFnArray;
20use crate::arrays::StructArray;
21use crate::arrays::struct_::StructArrayExt;
22use crate::builtins::ArrayBuiltins;
23use crate::dtype::DType;
24use crate::dtype::FieldName;
25use crate::dtype::Nullability;
26use crate::expr::display::ExprDisplay;
27use crate::proto::expr as pb;
28use crate::scalar::Scalar;
29use crate::scalar_fn::Arity;
30use crate::scalar_fn::ChildName;
31use crate::scalar_fn::EmptyOptions;
32use crate::scalar_fn::ExecutionArgs;
33use crate::scalar_fn::ReduceNode;
34use crate::scalar_fn::ScalarFnId;
35use crate::scalar_fn::ScalarFnVTable;
36use crate::scalar_fn::ScalarFnVTableExt;
37use crate::scalar_fn::fns::mask::Mask;
38use crate::scalar_fn::fns::pack::Pack;
39
40#[derive(Clone)]
41pub struct GetItem;
42
43impl GetItem {
44    /// Creates a lazy projection of `field_name` from `input`.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error if `input` is not a struct or does not contain `field_name`.
49    pub fn try_new(
50        input: ArrayRef,
51        field_name: impl Into<FieldName>,
52    ) -> VortexResult<ScalarFnArray> {
53        ScalarFnArray::try_new(GetItem.bind(field_name.into()), [input])
54    }
55
56    /// Read `field_name` out of `struct_node`, without a `get_item` node where possible.
57    ///
58    /// Rules that read a field out of their own child use this instead of building the
59    /// `get_item` node themselves. The optimizer visits children before their parent, so a
60    /// `get_item` that a rule introduces is never simplified again. Removing it here keeps the
61    /// output of the rule a fixed point.
62    pub(crate) fn apply_now<T: ReduceNode>(
63        struct_node: &T,
64        field_name: &FieldName,
65    ) -> VortexResult<T> {
66        if let Some(field) = Self::maybe_apply_now(struct_node, field_name)? {
67            return Ok(field);
68        }
69
70        struct_node.new_node(
71            GetItem.bind(field_name.clone()),
72            slice::from_ref(struct_node),
73        )
74    }
75
76    /// Read `field_name` straight out of a `pack` node, which holds each field as a child.
77    ///
78    /// Returns `None` if `struct_node` is not a `pack`, or does not hold `field_name`.
79    fn maybe_apply_now<T: ReduceNode>(
80        struct_node: &T,
81        field_name: &FieldName,
82    ) -> VortexResult<Option<T>> {
83        let Some(pack) = struct_node
84            .scalar_fn()
85            .and_then(|scalar_fn| scalar_fn.as_opt::<Pack>())
86        else {
87            return Ok(None);
88        };
89        let Some(idx) = pack.names.find(field_name) else {
90            return Ok(None);
91        };
92
93        let field = struct_node.child(idx);
94        if !pack.nullability.is_nullable() {
95            return Ok(Some(field));
96        }
97
98        // A nullable pack intersects its validity into the field, so mask the field with an
99        // all-true constant to make its dtype nullable.
100        Ok(Some(struct_node.new_node(
101            Mask.bind(EmptyOptions),
102            &[field, struct_node.new_constant(true.into())],
103        )?))
104    }
105}
106
107impl ScalarFnVTable for GetItem {
108    type Options = FieldName;
109
110    fn id(&self) -> ScalarFnId {
111        static ID: CachedId = CachedId::new("vortex.get_item");
112        *ID
113    }
114
115    fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
116        Ok(Some(
117            pb::GetItemOpts {
118                path: instance.to_string(),
119            }
120            .encode_to_vec(),
121        ))
122    }
123
124    fn deserialize(
125        &self,
126        _metadata: &[u8],
127        _session: &VortexSession,
128    ) -> VortexResult<Self::Options> {
129        let opts = pb::GetItemOpts::decode(_metadata)?;
130        Ok(FieldName::from(opts.path))
131    }
132
133    fn arity(&self, _field_name: &FieldName) -> Arity {
134        Arity::Exact(1)
135    }
136
137    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
138        match child_idx {
139            0 => ChildName::from("input"),
140            _ => unreachable!("Invalid child index {} for GetItem expression", child_idx),
141        }
142    }
143
144    fn fmt_sql(
145        &self,
146        field_name: &FieldName,
147        expr: &dyn ExprDisplay,
148        f: &mut Formatter<'_>,
149    ) -> std::fmt::Result {
150        Display::fmt(expr.display_child(0), f)?;
151        write!(f, ".{}", field_name)
152    }
153
154    fn return_dtype(&self, field_name: &FieldName, arg_dtypes: &[DType]) -> VortexResult<DType> {
155        let struct_dtype = &arg_dtypes[0];
156        let field_dtype = struct_dtype
157            .as_struct_fields_opt()
158            .and_then(|st| st.field(field_name))
159            .ok_or_else(|| {
160                vortex_err!("Couldn't find the {} field in the input scope", field_name)
161            })?;
162
163        // Match here to avoid cloning the dtype if nullability doesn't need to change
164        if matches!(
165            (struct_dtype.nullability(), field_dtype.nullability()),
166            (Nullability::Nullable, Nullability::NonNullable)
167        ) {
168            return Ok(field_dtype.with_nullability(Nullability::Nullable));
169        }
170
171        Ok(field_dtype)
172    }
173
174    fn execute(
175        &self,
176        field_name: &FieldName,
177        args: &dyn ExecutionArgs,
178        ctx: &mut ExecutionCtx,
179    ) -> VortexResult<ArrayRef> {
180        let input = args.get(0)?;
181        if let Some(constant) = input.as_opt::<Constant>() {
182            let dtype = self.return_dtype(field_name, &[input.dtype().clone()])?;
183            let scalar = if constant.scalar().is_null() {
184                Scalar::null(dtype)
185            } else {
186                constant
187                    .scalar()
188                    .as_struct()
189                    .field(field_name)
190                    .ok_or_else(|| {
191                        vortex_err!(
192                            "Field '{}' missing from constant struct array {}",
193                            field_name,
194                            input.dtype()
195                        )
196                    })?
197                    .cast(&dtype)?
198            };
199
200            return Ok(ConstantArray::new(scalar, input.len()).into_array());
201        }
202
203        let input = input.execute::<StructArray>(ctx)?;
204        let field = input.unmasked_field_by_name(field_name).cloned()?;
205
206        match input.dtype().nullability() {
207            Nullability::NonNullable => Ok(field),
208            Nullability::Nullable => field.mask(input.validity()?.to_array(input.len())),
209        }
210    }
211
212    fn reduce<T: ReduceNode>(&self, field_name: &FieldName, node: &T) -> VortexResult<Option<T>> {
213        Self::maybe_apply_now(&node.child(0), field_name)
214    }
215
216    fn is_strict(&self, _field_name: &FieldName) -> bool {
217        true
218    }
219
220    fn is_infallible(&self, _field_name: &FieldName) -> bool {
221        // If this type-checks, it is infallible.
222        true
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use vortex_buffer::buffer;
229    use vortex_error::VortexResult;
230
231    use super::GetItem;
232    use crate::ArrayRef;
233    use crate::IntoArray;
234    use crate::VortexSessionExecute;
235    use crate::arrays::Constant;
236    use crate::arrays::ConstantArray;
237    use crate::arrays::Filter;
238    use crate::arrays::Primitive;
239    use crate::arrays::PrimitiveArray;
240    use crate::arrays::ScalarFn;
241    use crate::arrays::Slice;
242    use crate::assert_arrays_eq;
243    use crate::builtins::ArrayBuiltins;
244    use crate::dtype::DType;
245    use crate::dtype::FieldName;
246    use crate::dtype::FieldNames;
247    use crate::dtype::Nullability;
248    use crate::dtype::Nullability::NonNullable;
249    use crate::dtype::PType;
250    use crate::dtype::StructFields;
251    use crate::expr::checked_add;
252    use crate::expr::get_item;
253    use crate::expr::lit;
254    use crate::expr::pack;
255    use crate::expr::root;
256    use crate::scalar::Scalar;
257    use crate::scalar_fn::fns::get_item::StructArray;
258    use crate::validity::Validity;
259
260    fn test_array() -> StructArray {
261        StructArray::from_fields(&[
262            ("a", buffer![0i32, 1, 2].into_array()),
263            ("b", buffer![4i64, 5, 6].into_array()),
264        ])
265        .unwrap()
266    }
267
268    #[test]
269    fn get_item_by_name() {
270        let st = test_array();
271        let get_item = get_item("a", root());
272        assert!(
273            get_item
274                .as_scalar()
275                .is_some_and(|f| f.signature().is_strict())
276        );
277        let item = st.into_array().apply(&get_item).unwrap();
278        assert_eq!(item.dtype(), &DType::from(PType::I32));
279        assert_arrays_eq!(
280            item,
281            buffer![0i32, 1, 2].into_array(),
282            &mut crate::array_session().create_execution_ctx()
283        );
284    }
285
286    #[test]
287    fn get_item_by_name_none() {
288        let st = test_array();
289        let get_item = get_item("c", root());
290        assert!(st.into_array().apply(&get_item).is_err());
291    }
292
293    #[test]
294    fn get_nullable_field() {
295        let st = StructArray::try_new(
296            FieldNames::from(["a"]),
297            vec![buffer![1i32].into_array()],
298            1,
299            Validity::AllInvalid,
300        )
301        .unwrap()
302        .into_array();
303
304        let get_item_expr = get_item("a", root());
305        let item = st.apply(&get_item_expr).unwrap();
306        // The dtype should be nullable since it inherits struct validity
307        assert_eq!(
308            item.dtype(),
309            &DType::Primitive(PType::I32, Nullability::Nullable)
310        );
311        assert_arrays_eq!(
312            item,
313            PrimitiveArray::from_option_iter([None::<i32>]),
314            &mut crate::array_session().create_execution_ctx()
315        );
316    }
317
318    #[test]
319    fn get_non_nullable_field_from_all_valid_nullable_struct() -> VortexResult<()> {
320        let st = StructArray::try_new(
321            FieldNames::from(["a"]),
322            vec![buffer![1i32].into_array()],
323            1,
324            Validity::AllValid,
325        )?
326        .into_array();
327
328        let item = st.apply(&get_item("a", root()))?;
329        assert_eq!(
330            item.dtype(),
331            &DType::Primitive(PType::I32, Nullability::Nullable)
332        );
333        assert_arrays_eq!(
334            item,
335            PrimitiveArray::from_option_iter([Some(1i32)]),
336            &mut crate::array_session().create_execution_ctx()
337        );
338        Ok(())
339    }
340
341    #[test]
342    fn execute_constant_struct_stays_constant() -> VortexResult<()> {
343        let field_count = 128usize;
344        let selected_idx = 97i32;
345        let names = (0..field_count)
346            .map(|idx| FieldName::from(format!("f{idx}")))
347            .collect::<Vec<_>>();
348        let dtypes = vec![DType::Primitive(PType::I32, NonNullable); field_count];
349        let fields = StructFields::new(FieldNames::from(names), dtypes);
350        let scalar = Scalar::struct_(
351            DType::Struct(fields, NonNullable),
352            (0..128).map(|idx| Scalar::primitive(idx, NonNullable)),
353        );
354        let array = ConstantArray::new(scalar, 1_000_000).into_array();
355        let mut ctx = crate::array_session().create_execution_ctx();
356
357        let item: ArrayRef = GetItem::try_new(array, "f97")?
358            .into_array()
359            .execute(&mut ctx)?;
360
361        let constant = item.as_::<Constant>();
362        assert_eq!(constant.len(), 1_000_000);
363        assert_eq!(
364            constant.scalar(),
365            &Scalar::primitive(selected_idx, NonNullable)
366        );
367        Ok(())
368    }
369
370    #[test]
371    fn get_item_pushes_through_filter() -> VortexResult<()> {
372        use vortex_mask::Mask;
373
374        let filtered = test_array()
375            .into_array()
376            .filter(Mask::from_iter([true, false, true]))?;
377
378        let item = filtered.get_item("a")?;
379
380        assert!(item.is::<Filter>());
381        assert!(!item.is::<ScalarFn>());
382        assert_arrays_eq!(
383            item,
384            buffer![0i32, 2].into_array(),
385            &mut crate::array_session().create_execution_ctx()
386        );
387        Ok(())
388    }
389
390    #[test]
391    fn get_item_pushes_through_slice() -> VortexResult<()> {
392        let sliced = test_array().into_array().slice(1..3)?;
393
394        let item = sliced.get_item("a")?;
395
396        assert!(item.is::<Primitive>());
397        assert!(!item.is::<Slice>());
398        assert!(!item.is::<ScalarFn>());
399        assert_arrays_eq!(
400            item,
401            buffer![1i32, 2].into_array(),
402            &mut crate::array_session().create_execution_ctx()
403        );
404        Ok(())
405    }
406
407    #[test]
408    fn get_item_pushes_through_masked() -> VortexResult<()> {
409        let masked = test_array()
410            .into_array()
411            .mask(Validity::from_iter([true, false, true]).to_array(3))?;
412
413        let item = masked.get_item("a")?;
414
415        assert!(item.is::<Primitive>());
416        assert_eq!(
417            item.dtype(),
418            &DType::Primitive(PType::I32, Nullability::Nullable)
419        );
420        assert!(!item.is::<ScalarFn>());
421        assert_arrays_eq!(
422            item,
423            PrimitiveArray::from_option_iter([Some(0i32), None, Some(2)]),
424            &mut crate::array_session().create_execution_ctx()
425        );
426        Ok(())
427    }
428
429    #[test]
430    fn test_pack_get_item_rule() {
431        // Create: pack(a: lit(1), b: lit(2)).get_item("b")
432        let pack_expr = pack([("a", lit(1)), ("b", lit(2))], NonNullable);
433        let get_item_expr = get_item("b", pack_expr);
434
435        let dtype = DType::Struct(StructFields::empty(), NonNullable);
436        let result = get_item_expr
437            .bind(&dtype)
438            .and_then(|expr| expr.optimize_recursive())
439            .unwrap();
440
441        assert_eq!(result, lit(2).bind(&dtype).unwrap());
442    }
443
444    #[test]
445    fn test_multi_level_pack_get_item_simplify() {
446        let inner_pack = pack([("a", lit(1)), ("b", lit(2))], NonNullable);
447        let get_a = get_item("a", inner_pack);
448
449        let outer_pack = pack([("x", get_a), ("y", lit(3)), ("z", lit(4))], NonNullable);
450        let get_z = get_item("z", outer_pack);
451
452        let dtype = DType::Primitive(PType::I32, NonNullable);
453
454        let result = get_z.bind(&dtype).unwrap().optimize_recursive().unwrap();
455        assert_eq!(result, lit(4).bind(&dtype).unwrap());
456    }
457
458    #[test]
459    fn test_deeply_nested_pack_get_item() {
460        let innermost = pack([("a", lit(42))], NonNullable);
461        let get_a = get_item("a", innermost);
462
463        let level2 = pack([("b", get_a)], NonNullable);
464        let get_b = get_item("b", level2);
465
466        let level3 = pack([("c", get_b)], NonNullable);
467        let get_c = get_item("c", level3);
468
469        let outermost = pack([("final", get_c)], NonNullable);
470        let get_final = get_item("final", outermost);
471
472        let dtype = DType::Primitive(PType::I32, NonNullable);
473
474        let result = get_final
475            .bind(&dtype)
476            .unwrap()
477            .optimize_recursive()
478            .unwrap();
479        assert_eq!(result, lit(42).bind(&dtype).unwrap());
480    }
481
482    #[test]
483    fn test_partial_pack_get_item_simplify() {
484        let inner_pack = pack([("x", lit(1)), ("y", lit(2))], NonNullable);
485        let get_x = get_item("x", inner_pack);
486        let add_expr = checked_add(get_x, lit(10));
487
488        let outer_pack = pack([("result", add_expr)], NonNullable);
489        let get_result = get_item("result", outer_pack);
490
491        let dtype = DType::Primitive(PType::I32, NonNullable);
492
493        let result = get_result
494            .bind(&dtype)
495            .unwrap()
496            .optimize_recursive()
497            .unwrap();
498        let expected = checked_add(lit(1), lit(10)).bind(&dtype).unwrap();
499        assert_eq!(&result, &expected);
500    }
501
502    #[test]
503    fn get_item_filter_list_field() {
504        use vortex_mask::Mask;
505
506        use crate::arrays::BoolArray;
507        use crate::arrays::FilterArray;
508        use crate::arrays::ListArray;
509
510        let list = ListArray::try_new(
511            buffer![0f32, 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.].into_array(),
512            buffer![2u64, 4, 6, 8, 10, 12].into_array(),
513            Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()),
514        )
515        .unwrap();
516
517        let filtered = FilterArray::try_new(
518            list.into_array(),
519            Mask::from_iter([true, true, false, false, false]),
520        )
521        .unwrap();
522
523        let st = StructArray::try_new(
524            FieldNames::from(["data"]),
525            vec![filtered.into_array()],
526            2,
527            Validity::AllValid,
528        )
529        .unwrap();
530
531        let result = st.into_array().apply(&get_item("data", root())).unwrap();
532        let expected = ListArray::try_new(
533            buffer![2f32, 3., 4., 5.].into_array(),
534            buffer![0u64, 2, 4].into_array(),
535            Validity::AllValid,
536        )
537        .unwrap();
538        assert_arrays_eq!(
539            result,
540            expected,
541            &mut crate::array_session().create_execution_ctx()
542        );
543    }
544}