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::VortexResult;
8use vortex_error::vortex_err;
9use vortex_proto::expr as pb;
10use vortex_session::VortexSession;
11
12use crate::ArrayRef;
13use crate::ExecutionCtx;
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(
109        &self,
110        field_name: &FieldName,
111        args: &dyn ExecutionArgs,
112        ctx: &mut ExecutionCtx,
113    ) -> VortexResult<ArrayRef> {
114        let input = args.get(0)?.execute::<StructArray>(ctx)?;
115        let field = input.unmasked_field_by_name(field_name).cloned()?;
116
117        match input.dtype().nullability() {
118            Nullability::NonNullable => Ok(field),
119            Nullability::Nullable => field.mask(input.validity()?.to_array(input.len())),
120        }
121    }
122
123    fn reduce(
124        &self,
125        field_name: &FieldName,
126        node: &dyn ReduceNode,
127        ctx: &dyn ReduceCtx,
128    ) -> VortexResult<Option<ReduceNodeRef>> {
129        let child = node.child(0);
130        if let Some(child_fn) = child.scalar_fn()
131            && let Some(pack) = child_fn.as_opt::<Pack>()
132            && let Some(idx) = pack.names.find(field_name)
133        {
134            let mut field = child.child(idx);
135
136            // Possibly mask the field if the pack is nullable
137            if pack.nullability.is_nullable() {
138                field = ctx.new_node(
139                    Mask.bind(EmptyOptions),
140                    &[field, ctx.new_node(Literal.bind(true.into()), &[])?],
141                )?;
142            }
143
144            return Ok(Some(field));
145        }
146
147        Ok(None)
148    }
149
150    fn simplify_untyped(
151        &self,
152        field_name: &FieldName,
153        expr: &Expression,
154    ) -> VortexResult<Option<Expression>> {
155        let child = expr.child(0);
156
157        // If the child is a Pack expression, we can directly return the corresponding child.
158        if let Some(pack) = child.as_opt::<Pack>() {
159            let idx = pack
160                .names
161                .iter()
162                .position(|name| name == field_name)
163                .ok_or_else(|| {
164                    vortex_err!(
165                        "Cannot find field {} in pack fields {:?}",
166                        field_name,
167                        pack.names
168                    )
169                })?;
170
171            let mut field = child.child(idx).clone();
172
173            // It's useful to simplify this node without type info, but we need to make sure
174            // the nullability is correct. We cannot cast since we don't have the dtype info here,
175            // so instead we insert a Mask expression that we know converts a child's dtype to
176            // nullable.
177            if pack.nullability.is_nullable() {
178                // Mask with an all-true array to ensure the field DType is nullable.
179                field = field.mask(lit(true))?;
180            }
181
182            return Ok(Some(field));
183        }
184
185        Ok(None)
186    }
187
188    fn stat_expression(
189        &self,
190        field_name: &FieldName,
191        _expr: &Expression,
192        stat: Stat,
193        catalog: &dyn StatsCatalog,
194    ) -> Option<Expression> {
195        // TODO(ngates): I think we can do better here and support stats over nested fields.
196        //  It would be nice if delegating to our child would return a struct of statistics
197        //  matching the nested DType such that we can write:
198        //    `get_item(expr.child(0).stat_expression(...), expr.data().field_name())`
199
200        // TODO(ngates): this is a bug whereby we may return stats for a nested field of the same
201        //  name as a field in the root struct. This should be resolved with upcoming change to
202        //  falsify expressions, but for now I'm preserving the existing buggy behavior.
203        catalog.stats_ref(&FieldPath::from_name(field_name.clone()), stat)
204    }
205
206    // This will apply struct nullability field. We could add a dtype??
207    fn is_null_sensitive(&self, _field_name: &FieldName) -> bool {
208        true
209    }
210
211    fn is_fallible(&self, _field_name: &FieldName) -> bool {
212        // If this type-checks its infallible.
213        false
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use vortex_buffer::buffer;
220
221    use crate::Array;
222    use crate::IntoArray;
223    use crate::arrays::StructArray;
224    use crate::dtype::DType;
225    use crate::dtype::FieldNames;
226    use crate::dtype::Nullability;
227    use crate::dtype::Nullability::NonNullable;
228    use crate::dtype::PType;
229    use crate::dtype::StructFields;
230    use crate::expr::checked_add;
231    use crate::expr::get_item;
232    use crate::expr::lit;
233    use crate::expr::pack;
234    use crate::expr::root;
235    use crate::validity::Validity;
236
237    fn test_array() -> StructArray {
238        StructArray::from_fields(&[
239            ("a", buffer![0i32, 1, 2].into_array()),
240            ("b", buffer![4i64, 5, 6].into_array()),
241        ])
242        .unwrap()
243    }
244
245    #[test]
246    fn get_item_by_name() {
247        let st = test_array();
248        let get_item = get_item("a", root());
249        let item = st.to_array().apply(&get_item).unwrap();
250        assert_eq!(item.dtype(), &DType::from(PType::I32))
251    }
252
253    #[test]
254    fn get_item_by_name_none() {
255        let st = test_array();
256        let get_item = get_item("c", root());
257        assert!(st.to_array().apply(&get_item).is_err());
258    }
259
260    #[test]
261    #[ignore = "apply() has a bug with null propagation from struct validity to non-nullable child fields"]
262    fn get_nullable_field() {
263        let st = StructArray::try_new(
264            FieldNames::from(["a"]),
265            vec![buffer![1i32].into_array()],
266            1,
267            Validity::AllInvalid,
268        )
269        .unwrap()
270        .to_array();
271
272        let get_item_expr = get_item("a", root());
273        let item = st.apply(&get_item_expr).unwrap();
274        // The dtype should be nullable since it inherits struct validity
275        assert_eq!(
276            item.dtype(),
277            &DType::Primitive(PType::I32, Nullability::Nullable)
278        );
279    }
280
281    #[test]
282    fn test_pack_get_item_rule() {
283        // Create: pack(a: lit(1), b: lit(2)).get_item("b")
284        let pack_expr = pack([("a", lit(1)), ("b", lit(2))], NonNullable);
285        let get_item_expr = get_item("b", pack_expr);
286
287        let result = get_item_expr
288            .optimize_recursive(&DType::Struct(StructFields::empty(), NonNullable))
289            .unwrap();
290
291        assert_eq!(result, lit(2));
292    }
293
294    #[test]
295    fn test_multi_level_pack_get_item_simplify() {
296        let inner_pack = pack([("a", lit(1)), ("b", lit(2))], NonNullable);
297        let get_a = get_item("a", inner_pack);
298
299        let outer_pack = pack([("x", get_a), ("y", lit(3)), ("z", lit(4))], NonNullable);
300        let get_z = get_item("z", outer_pack);
301
302        let dtype = DType::Primitive(PType::I32, NonNullable);
303
304        let result = get_z.optimize_recursive(&dtype).unwrap();
305        assert_eq!(result, lit(4));
306    }
307
308    #[test]
309    fn test_deeply_nested_pack_get_item() {
310        let innermost = pack([("a", lit(42))], NonNullable);
311        let get_a = get_item("a", innermost);
312
313        let level2 = pack([("b", get_a)], NonNullable);
314        let get_b = get_item("b", level2);
315
316        let level3 = pack([("c", get_b)], NonNullable);
317        let get_c = get_item("c", level3);
318
319        let outermost = pack([("final", get_c)], NonNullable);
320        let get_final = get_item("final", outermost);
321
322        let dtype = DType::Primitive(PType::I32, NonNullable);
323
324        let result = get_final.optimize_recursive(&dtype).unwrap();
325        assert_eq!(result, lit(42));
326    }
327
328    #[test]
329    fn test_partial_pack_get_item_simplify() {
330        let inner_pack = pack([("x", lit(1)), ("y", lit(2))], NonNullable);
331        let get_x = get_item("x", inner_pack);
332        let add_expr = checked_add(get_x, lit(10));
333
334        let outer_pack = pack([("result", add_expr)], NonNullable);
335        let get_result = get_item("result", outer_pack);
336
337        let dtype = DType::Primitive(PType::I32, NonNullable);
338
339        let result = get_result.optimize_recursive(&dtype).unwrap();
340        let expected = checked_add(lit(1), lit(10));
341        assert_eq!(&result, &expected);
342    }
343
344    #[test]
345    fn get_item_filter_list_field() {
346        use vortex_mask::Mask;
347
348        use crate::arrays::BoolArray;
349        use crate::arrays::FilterArray;
350        use crate::arrays::ListArray;
351
352        let list = ListArray::try_new(
353            buffer![0f32, 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11.].into_array(),
354            buffer![2u64, 4, 6, 8, 10, 12].into_array(),
355            Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()),
356        )
357        .unwrap();
358
359        let filtered = FilterArray::try_new(
360            list.into_array(),
361            Mask::from_iter([true, true, false, false, false]),
362        )
363        .unwrap();
364
365        let st = StructArray::try_new(
366            FieldNames::from(["data"]),
367            vec![filtered.into_array()],
368            2,
369            Validity::AllValid,
370        )
371        .unwrap();
372
373        st.to_array().apply(&get_item("data", root())).unwrap();
374    }
375}