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::Formatter;
5
6use prost::Message;
7use vortex_error::VortexExpect;
8use vortex_error::VortexResult;
9use vortex_error::vortex_err;
10use vortex_proto::expr as pb;
11use vortex_session::VortexSession;
12
13use crate::ArrayRef;
14use crate::arrays::StructArray;
15use crate::builtins::ArrayBuiltins;
16use crate::builtins::ExprBuiltins;
17use crate::dtype::DType;
18use crate::dtype::FieldName;
19use crate::dtype::FieldPath;
20use crate::dtype::Nullability;
21use crate::expr::Expression;
22use crate::expr::StatsCatalog;
23use crate::expr::lit;
24use crate::expr::stats::Stat;
25use crate::scalar_fn::Arity;
26use crate::scalar_fn::ChildName;
27use crate::scalar_fn::EmptyOptions;
28use crate::scalar_fn::ExecutionArgs;
29use crate::scalar_fn::ReduceCtx;
30use crate::scalar_fn::ReduceNode;
31use crate::scalar_fn::ReduceNodeRef;
32use crate::scalar_fn::ScalarFnId;
33use crate::scalar_fn::ScalarFnVTable;
34use crate::scalar_fn::ScalarFnVTableExt;
35use crate::scalar_fn::fns::literal::Literal;
36use crate::scalar_fn::fns::mask::Mask;
37use crate::scalar_fn::fns::pack::Pack;
38
39#[derive(Clone)]
40pub struct GetItem;
41
42impl ScalarFnVTable for GetItem {
43    type Options = FieldName;
44
45    fn id(&self) -> ScalarFnId {
46        ScalarFnId::from("vortex.get_item")
47    }
48
49    fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
50        Ok(Some(
51            pb::GetItemOpts {
52                path: instance.to_string(),
53            }
54            .encode_to_vec(),
55        ))
56    }
57
58    fn deserialize(
59        &self,
60        _metadata: &[u8],
61        _session: &VortexSession,
62    ) -> VortexResult<Self::Options> {
63        let opts = pb::GetItemOpts::decode(_metadata)?;
64        Ok(FieldName::from(opts.path))
65    }
66
67    fn arity(&self, _field_name: &FieldName) -> Arity {
68        Arity::Exact(1)
69    }
70
71    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
72        match child_idx {
73            0 => ChildName::from("input"),
74            _ => unreachable!("Invalid child index {} for GetItem expression", child_idx),
75        }
76    }
77
78    fn fmt_sql(
79        &self,
80        field_name: &FieldName,
81        expr: &Expression,
82        f: &mut Formatter<'_>,
83    ) -> std::fmt::Result {
84        expr.children()[0].fmt_sql(f)?;
85        write!(f, ".{}", field_name)
86    }
87
88    fn return_dtype(&self, field_name: &FieldName, arg_dtypes: &[DType]) -> VortexResult<DType> {
89        let struct_dtype = &arg_dtypes[0];
90        let field_dtype = struct_dtype
91            .as_struct_fields_opt()
92            .and_then(|st| st.field(field_name))
93            .ok_or_else(|| {
94                vortex_err!("Couldn't find the {} field in the input scope", field_name)
95            })?;
96
97        // Match here to avoid cloning the dtype if nullability doesn't need to change
98        if matches!(
99            (struct_dtype.nullability(), field_dtype.nullability()),
100            (Nullability::Nullable, Nullability::NonNullable)
101        ) {
102            return Ok(field_dtype.with_nullability(Nullability::Nullable));
103        }
104
105        Ok(field_dtype)
106    }
107
108    fn execute(&self, field_name: &FieldName, mut args: ExecutionArgs) -> VortexResult<ArrayRef> {
109        let input = args
110            .inputs
111            .pop()
112            .vortex_expect("missing input for GetItem expression")
113            .execute::<StructArray>(args.ctx)?;
114        let field = input.unmasked_field_by_name(field_name).cloned()?;
115
116        match input.dtype().nullability() {
117            Nullability::NonNullable => Ok(field),
118            Nullability::Nullable => field.mask(input.validity()?.to_array(input.len())),
119        }
120    }
121
122    fn reduce(
123        &self,
124        field_name: &FieldName,
125        node: &dyn ReduceNode,
126        ctx: &dyn ReduceCtx,
127    ) -> VortexResult<Option<ReduceNodeRef>> {
128        let child = node.child(0);
129        if let Some(child_fn) = child.scalar_fn()
130            && let Some(pack) = child_fn.as_opt::<Pack>()
131            && let Some(idx) = pack.names.find(field_name)
132        {
133            let mut field = child.child(idx);
134
135            // Possibly mask the field if the pack is nullable
136            if pack.nullability.is_nullable() {
137                field = ctx.new_node(
138                    Mask.bind(EmptyOptions),
139                    &[field, ctx.new_node(Literal.bind(true.into()), &[])?],
140                )?;
141            }
142
143            return Ok(Some(field));
144        }
145
146        Ok(None)
147    }
148
149    fn simplify_untyped(
150        &self,
151        field_name: &FieldName,
152        expr: &Expression,
153    ) -> VortexResult<Option<Expression>> {
154        let child = expr.child(0);
155
156        // If the child is a Pack expression, we can directly return the corresponding child.
157        if let Some(pack) = child.as_opt::<Pack>() {
158            let idx = pack
159                .names
160                .iter()
161                .position(|name| name == field_name)
162                .ok_or_else(|| {
163                    vortex_err!(
164                        "Cannot find field {} in pack fields {:?}",
165                        field_name,
166                        pack.names
167                    )
168                })?;
169
170            let mut field = child.child(idx).clone();
171
172            // It's useful to simplify this node without type info, but we need to make sure
173            // the nullability is correct. We cannot cast since we don't have the dtype info here,
174            // so instead we insert a Mask expression that we know converts a child's dtype to
175            // nullable.
176            if pack.nullability.is_nullable() {
177                // Mask with an all-true array to ensure the field DType is nullable.
178                field = field.mask(lit(true))?;
179            }
180
181            return Ok(Some(field));
182        }
183
184        Ok(None)
185    }
186
187    fn stat_expression(
188        &self,
189        field_name: &FieldName,
190        _expr: &Expression,
191        stat: Stat,
192        catalog: &dyn StatsCatalog,
193    ) -> Option<Expression> {
194        // TODO(ngates): I think we can do better here and support stats over nested fields.
195        //  It would be nice if delegating to our child would return a struct of statistics
196        //  matching the nested DType such that we can write:
197        //    `get_item(expr.child(0).stat_expression(...), expr.data().field_name())`
198
199        // TODO(ngates): this is a bug whereby we may return stats for a nested field of the same
200        //  name as a field in the root struct. This should be resolved with upcoming change to
201        //  falsify expressions, but for now I'm preserving the existing buggy behavior.
202        catalog.stats_ref(&FieldPath::from_name(field_name.clone()), stat)
203    }
204
205    // This will apply struct nullability field. We could add a dtype??
206    fn is_null_sensitive(&self, _field_name: &FieldName) -> bool {
207        true
208    }
209
210    fn is_fallible(&self, _field_name: &FieldName) -> bool {
211        // If this type-checks its infallible.
212        false
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use vortex_buffer::buffer;
219
220    use crate::Array;
221    use crate::IntoArray;
222    use crate::arrays::StructArray;
223    use crate::dtype::DType;
224    use crate::dtype::FieldNames;
225    use crate::dtype::Nullability;
226    use crate::dtype::Nullability::NonNullable;
227    use crate::dtype::PType;
228    use crate::dtype::StructFields;
229    use crate::expr::checked_add;
230    use crate::expr::get_item;
231    use crate::expr::lit;
232    use crate::expr::pack;
233    use crate::expr::root;
234    use crate::validity::Validity;
235
236    fn test_array() -> StructArray {
237        StructArray::from_fields(&[
238            ("a", buffer![0i32, 1, 2].into_array()),
239            ("b", buffer![4i64, 5, 6].into_array()),
240        ])
241        .unwrap()
242    }
243
244    #[test]
245    fn get_item_by_name() {
246        let st = test_array();
247        let get_item = get_item("a", root());
248        let item = st.to_array().apply(&get_item).unwrap();
249        assert_eq!(item.dtype(), &DType::from(PType::I32))
250    }
251
252    #[test]
253    fn get_item_by_name_none() {
254        let st = test_array();
255        let get_item = get_item("c", root());
256        assert!(st.to_array().apply(&get_item).is_err());
257    }
258
259    #[test]
260    #[ignore = "apply() has a bug with null propagation from struct validity to non-nullable child fields"]
261    fn get_nullable_field() {
262        let st = StructArray::try_new(
263            FieldNames::from(["a"]),
264            vec![buffer![1i32].into_array()],
265            1,
266            Validity::AllInvalid,
267        )
268        .unwrap()
269        .to_array();
270
271        let get_item_expr = get_item("a", root());
272        let item = st.apply(&get_item_expr).unwrap();
273        // The dtype should be nullable since it inherits struct validity
274        assert_eq!(
275            item.dtype(),
276            &DType::Primitive(PType::I32, Nullability::Nullable)
277        );
278    }
279
280    #[test]
281    fn test_pack_get_item_rule() {
282        // Create: pack(a: lit(1), b: lit(2)).get_item("b")
283        let pack_expr = pack([("a", lit(1)), ("b", lit(2))], NonNullable);
284        let get_item_expr = get_item("b", pack_expr);
285
286        let result = get_item_expr
287            .optimize_recursive(&DType::Struct(StructFields::empty(), NonNullable))
288            .unwrap();
289
290        assert_eq!(result, lit(2));
291    }
292
293    #[test]
294    fn test_multi_level_pack_get_item_simplify() {
295        let inner_pack = pack([("a", lit(1)), ("b", lit(2))], NonNullable);
296        let get_a = get_item("a", inner_pack);
297
298        let outer_pack = pack([("x", get_a), ("y", lit(3)), ("z", lit(4))], NonNullable);
299        let get_z = get_item("z", outer_pack);
300
301        let dtype = DType::Primitive(PType::I32, NonNullable);
302
303        let result = get_z.optimize_recursive(&dtype).unwrap();
304        assert_eq!(result, lit(4));
305    }
306
307    #[test]
308    fn test_deeply_nested_pack_get_item() {
309        let innermost = pack([("a", lit(42))], NonNullable);
310        let get_a = get_item("a", innermost);
311
312        let level2 = pack([("b", get_a)], NonNullable);
313        let get_b = get_item("b", level2);
314
315        let level3 = pack([("c", get_b)], NonNullable);
316        let get_c = get_item("c", level3);
317
318        let outermost = pack([("final", get_c)], NonNullable);
319        let get_final = get_item("final", outermost);
320
321        let dtype = DType::Primitive(PType::I32, NonNullable);
322
323        let result = get_final.optimize_recursive(&dtype).unwrap();
324        assert_eq!(result, lit(42));
325    }
326
327    #[test]
328    fn test_partial_pack_get_item_simplify() {
329        let inner_pack = pack([("x", lit(1)), ("y", lit(2))], NonNullable);
330        let get_x = get_item("x", inner_pack);
331        let add_expr = checked_add(get_x, lit(10));
332
333        let outer_pack = pack([("result", add_expr)], NonNullable);
334        let get_result = get_item("result", outer_pack);
335
336        let dtype = DType::Primitive(PType::I32, NonNullable);
337
338        let result = get_result.optimize_recursive(&dtype).unwrap();
339        let expected = checked_add(lit(1), lit(10));
340        assert_eq!(&result, &expected);
341    }
342
343    #[test]
344    fn get_item_filter_list_field() {
345        use vortex_mask::Mask;
346
347        use crate::arrays::BoolArray;
348        use crate::arrays::FilterArray;
349        use crate::arrays::ListArray;
350
351        let list = ListArray::try_new(
352            buffer![0f32, 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.].into_array(),
353            buffer![2u64, 4, 6, 8, 10, 12].into_array(),
354            Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()),
355        )
356        .unwrap();
357
358        let filtered = FilterArray::try_new(
359            list.into_array(),
360            Mask::from_iter([true, true, false, false, false]),
361        )
362        .unwrap();
363
364        let st = StructArray::try_new(
365            FieldNames::from(["data"]),
366            vec![filtered.into_array()],
367            2,
368            Validity::AllValid,
369        )
370        .unwrap();
371
372        st.to_array().apply(&get_item("data", root())).unwrap();
373    }
374}