Skip to main content

vortex_array/scalar_fn/builtin/
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::ConstantArray;
18use crate::arrays::ScalarFnArray;
19use crate::arrays::StructArray;
20use crate::arrays::struct_::StructArrayExt;
21use crate::builtins::ArrayBuiltins;
22use crate::dtype::DType;
23use crate::dtype::FieldName;
24use crate::dtype::Nullability;
25use crate::proto::expr as pb;
26use crate::scalar::Scalar;
27use crate::scalar_fn::Arity;
28use crate::scalar_fn::ChildName;
29use crate::scalar_fn::EmptyOptions;
30use crate::scalar_fn::ExecutionArgs;
31use crate::scalar_fn::ReduceNode;
32use crate::scalar_fn::ScalarFnId;
33use crate::scalar_fn::ScalarFnVTable;
34use crate::scalar_fn::ScalarFnVTableExt;
35use crate::scalar_fn::builtin::mask::Mask;
36use crate::scalar_fn::builtin::pack::Pack;
37use crate::scalar_fn::display::ExprDisplay;
38
39#[derive(Clone)]
40pub struct GetItem;
41
42impl GetItem {
43    /// Creates a lazy projection of `field_name` from `input`.
44    ///
45    /// # Errors
46    ///
47    /// Returns an error if `input` is not a struct or does not contain `field_name`.
48    pub fn try_new(
49        input: ArrayRef,
50        field_name: impl Into<FieldName>,
51    ) -> VortexResult<ScalarFnArray> {
52        ScalarFnArray::try_new(GetItem.bind(field_name.into()), [input])
53    }
54
55    /// Read `field_name` out of `struct_node`, without a `get_item` node where possible.
56    ///
57    /// Rules that read a field out of their own child use this instead of building the
58    /// `get_item` node themselves. The optimizer visits children before their parent, so a
59    /// `get_item` that a rule introduces is never simplified again. Removing it here keeps the
60    /// output of the rule a fixed point.
61    pub fn apply_now<T: ReduceNode>(struct_node: &T, field_name: &FieldName) -> VortexResult<T> {
62        if let Some(field) = Self::maybe_apply_now(struct_node, field_name)? {
63            return Ok(field);
64        }
65
66        struct_node.new_node(
67            GetItem.bind(field_name.clone()),
68            slice::from_ref(struct_node),
69        )
70    }
71
72    /// Extract a constant field, read through a function that forwards the field, or read a field
73    /// directly from a pack.
74    fn maybe_apply_now<T: ReduceNode>(
75        struct_node: &T,
76        field_name: &FieldName,
77    ) -> VortexResult<Option<T>> {
78        if let Some(scalar) = struct_node.as_constant() {
79            return Ok(Some(
80                struct_node.new_constant(Self::constant_field(scalar, field_name)?),
81            ));
82        }
83
84        if let Some(child_idx) = struct_node
85            .scalar_fn()
86            .and_then(|scalar_fn| scalar_fn.signature().forwarded_field(field_name))
87        {
88            return Self::apply_now(&struct_node.child(child_idx), field_name).map(Some);
89        }
90
91        let Some(pack) = struct_node
92            .scalar_fn()
93            .and_then(|scalar_fn| scalar_fn.as_opt::<Pack>())
94        else {
95            return Ok(None);
96        };
97        let Some(idx) = pack.names.find(field_name) else {
98            return Ok(None);
99        };
100
101        let field = struct_node.child(idx);
102        if !pack.nullability.is_nullable() {
103            return Ok(Some(field));
104        }
105
106        // A nullable pack intersects its validity into the field, so mask the field with an
107        // all-true constant to make its dtype nullable.
108        Ok(Some(struct_node.new_node(
109            Mask.bind(EmptyOptions),
110            &[field, struct_node.new_constant(true.into())],
111        )?))
112    }
113
114    fn constant_field(scalar: &Scalar, field_name: &FieldName) -> VortexResult<Scalar> {
115        let dtype = Self.return_dtype(field_name, &[scalar.dtype().clone()])?;
116        if scalar.is_null() {
117            return Ok(Scalar::null(dtype));
118        }
119        scalar
120            .as_struct()
121            .field(field_name)
122            .ok_or_else(|| {
123                vortex_err!(
124                    "Field '{}' missing from constant struct array {}",
125                    field_name,
126                    scalar.dtype()
127                )
128            })?
129            .cast(&dtype)
130    }
131}
132
133impl ScalarFnVTable for GetItem {
134    type Options = FieldName;
135
136    fn id(&self) -> ScalarFnId {
137        static ID: CachedId = CachedId::new("vortex.get_item");
138        *ID
139    }
140
141    fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
142        Ok(Some(
143            pb::GetItemOpts {
144                path: instance.as_ref().to_owned(),
145            }
146            .encode_to_vec(),
147        ))
148    }
149
150    fn deserialize(
151        &self,
152        _metadata: &[u8],
153        _session: &VortexSession,
154    ) -> VortexResult<Self::Options> {
155        let opts = pb::GetItemOpts::decode(_metadata)?;
156        Ok(FieldName::from(opts.path))
157    }
158
159    fn arity(&self, _field_name: &FieldName) -> Arity {
160        Arity::Exact(1)
161    }
162
163    fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
164        match child_idx {
165            0 => ChildName::from("input"),
166            _ => unreachable!("Invalid child index {} for GetItem expression", child_idx),
167        }
168    }
169
170    fn fmt_sql(
171        &self,
172        field_name: &FieldName,
173        expr: &dyn ExprDisplay,
174        f: &mut Formatter<'_>,
175    ) -> std::fmt::Result {
176        Display::fmt(expr.display_child(0), f)?;
177        write!(f, ".{}", field_name)
178    }
179
180    fn return_dtype(&self, field_name: &FieldName, arg_dtypes: &[DType]) -> VortexResult<DType> {
181        let struct_dtype = &arg_dtypes[0];
182        let field_dtype = struct_dtype
183            .as_struct_fields_opt()
184            .and_then(|st| st.field(field_name))
185            .ok_or_else(|| {
186                vortex_err!("Couldn't find the {} field in the input scope", field_name)
187            })?;
188
189        // Match here to avoid cloning the dtype if nullability doesn't need to change
190        if matches!(
191            (struct_dtype.nullability(), field_dtype.nullability()),
192            (Nullability::Nullable, Nullability::NonNullable)
193        ) {
194            return Ok(field_dtype.with_nullability(Nullability::Nullable));
195        }
196
197        Ok(field_dtype)
198    }
199
200    fn execute(
201        &self,
202        field_name: &FieldName,
203        args: &dyn ExecutionArgs,
204        ctx: &mut ExecutionCtx,
205    ) -> VortexResult<ArrayRef> {
206        let input = args.get(0)?;
207        if let Some(scalar) = input.as_constant() {
208            return Ok(
209                ConstantArray::new(Self::constant_field(scalar, field_name)?, input.len())
210                    .into_array(),
211            );
212        }
213
214        let input = input.execute::<StructArray>(ctx)?;
215        let field = input.unmasked_field_by_name(field_name).cloned()?;
216
217        match input.dtype().nullability() {
218            Nullability::NonNullable => Ok(field),
219            Nullability::Nullable => field.mask(input.validity()?.to_array(input.len())),
220        }
221    }
222
223    fn reduce<T: ReduceNode>(&self, field_name: &FieldName, node: &T) -> VortexResult<Option<T>> {
224        Self::maybe_apply_now(&node.child(0), field_name)
225    }
226
227    fn is_strict(&self, _field_name: &FieldName) -> bool {
228        true
229    }
230
231    fn is_infallible(&self, _field_name: &FieldName) -> bool {
232        // If this type-checks, it is infallible.
233        true
234    }
235}