Skip to main content

vortex_functions/
select.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use itertools::Itertools;
8use prost::Message;
9use vortex_array::ArrayRef;
10use vortex_array::ExecutionCtx;
11use vortex_array::IntoArray;
12use vortex_array::arrays::Constant;
13use vortex_array::arrays::ConstantArray;
14use vortex_array::arrays::StructArray;
15use vortex_array::arrays::struct_::StructArrayExt;
16use vortex_array::dtype::DType;
17use vortex_array::dtype::FieldName;
18use vortex_array::dtype::FieldNames;
19use vortex_array::proto::expr::FieldNames as ProtoFieldNames;
20use vortex_array::proto::expr::SelectOpts;
21use vortex_array::proto::expr::select_opts::Opts;
22use vortex_array::scalar_fn::Arity;
23use vortex_array::scalar_fn::ChildName;
24use vortex_array::scalar_fn::ExecutionArgs;
25use vortex_array::scalar_fn::ReduceNode;
26use vortex_array::scalar_fn::ScalarFnId;
27use vortex_array::scalar_fn::ScalarFnVTable;
28use vortex_array::scalar_fn::ScalarFnVTableExt;
29use vortex_array::scalar_fn::builtin::pack::Pack;
30use vortex_array::scalar_fn::builtin::pack::PackOptions;
31use vortex_array::scalar_fn::display::ExprDisplay;
32use vortex_error::VortexError;
33use vortex_error::VortexExpect;
34use vortex_error::VortexResult;
35use vortex_error::vortex_bail;
36use vortex_error::vortex_err;
37use vortex_session::VortexSession;
38use vortex_session::registry::CachedId;
39use vortex_utils::aliases::hash_set::HashSet;
40
41use crate::field::DisplayFieldNames;
42
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub enum FieldSelection {
45    Include(FieldNames),
46    Exclude(FieldNames),
47}
48
49#[derive(Clone)]
50pub struct Select;
51
52impl ScalarFnVTable for Select {
53    type Options = FieldSelection;
54
55    fn id(&self) -> ScalarFnId {
56        static ID: CachedId = CachedId::new("vortex.select");
57        *ID
58    }
59
60    fn serialize(&self, instance: &FieldSelection) -> VortexResult<Option<Vec<u8>>> {
61        let opts = match instance {
62            FieldSelection::Include(fields) => Opts::Include(ProtoFieldNames {
63                names: fields.iter().map(|f| f.as_ref().to_owned()).collect(),
64            }),
65            FieldSelection::Exclude(fields) => Opts::Exclude(ProtoFieldNames {
66                names: fields.iter().map(|f| f.as_ref().to_owned()).collect(),
67            }),
68        };
69
70        let select_opts = SelectOpts { opts: Some(opts) };
71        Ok(Some(select_opts.encode_to_vec()))
72    }
73
74    fn deserialize(
75        &self,
76        _metadata: &[u8],
77        _session: &VortexSession,
78    ) -> VortexResult<FieldSelection> {
79        let prost_metadata = SelectOpts::decode(_metadata)?;
80
81        let select_opts = prost_metadata
82            .opts
83            .ok_or_else(|| vortex_err!("SelectOpts missing opts field"))?;
84
85        let field_selection = match select_opts {
86            Opts::Include(field_names) => FieldSelection::Include(FieldNames::from_iter(
87                field_names.names.iter().map(|s| s.as_str()),
88            )),
89            Opts::Exclude(field_names) => FieldSelection::Exclude(FieldNames::from_iter(
90                field_names.names.iter().map(|s| s.as_str()),
91            )),
92        };
93
94        Ok(field_selection)
95    }
96
97    fn arity(&self, _options: &FieldSelection) -> Arity {
98        Arity::Exact(1)
99    }
100
101    fn child_name(&self, _instance: &FieldSelection, child_idx: usize) -> ChildName {
102        match child_idx {
103            0 => ChildName::from("child"),
104            _ => unreachable!(),
105        }
106    }
107
108    fn fmt_sql(
109        &self,
110        selection: &FieldSelection,
111        expr: &dyn ExprDisplay,
112        f: &mut Formatter<'_>,
113    ) -> std::fmt::Result {
114        Display::fmt(expr.display_child(0), f)?;
115        match selection {
116            FieldSelection::Include(fields) => {
117                write!(f, "{{{}}}", DisplayFieldNames(fields))
118            }
119            FieldSelection::Exclude(fields) => {
120                write!(f, "{{~ {}}}", DisplayFieldNames(fields))
121            }
122        }
123    }
124
125    fn return_dtype(
126        &self,
127        selection: &FieldSelection,
128        arg_dtypes: &[DType],
129    ) -> VortexResult<DType> {
130        let child_dtype = &arg_dtypes[0];
131        let child_struct_dtype = child_dtype
132            .as_struct_fields_opt()
133            .ok_or_else(|| vortex_err!("Select child not a struct dtype"))?;
134
135        let projected = match selection {
136            FieldSelection::Include(fields) => child_struct_dtype.project(fields.as_ref())?,
137            FieldSelection::Exclude(fields) => child_struct_dtype
138                .names()
139                .iter()
140                .cloned()
141                .zip_eq(child_struct_dtype.fields())
142                .filter(|(name, _)| !fields.as_ref().contains(name))
143                .collect(),
144        };
145
146        Ok(DType::Struct(projected, child_dtype.nullability()))
147    }
148
149    fn execute(
150        &self,
151        selection: &FieldSelection,
152        args: &dyn ExecutionArgs,
153        ctx: &mut ExecutionCtx,
154    ) -> VortexResult<ArrayRef> {
155        let child = args.get(0)?;
156        if let Some(constant) = child.as_opt::<Constant>() {
157            let child_struct_dtype = child
158                .dtype()
159                .as_struct_fields_opt()
160                .ok_or_else(|| vortex_err!("Select child not a struct dtype"))?;
161            let included = selection.normalize_to_included_fields(child_struct_dtype.names())?;
162            let scalar = constant.scalar().as_struct().project(included.as_ref())?;
163
164            return Ok(ConstantArray::new(scalar, child.len()).into_array());
165        }
166
167        let child = child.execute::<StructArray>(ctx)?;
168
169        let result = match selection {
170            FieldSelection::Include(f) => child.project(f.as_ref()),
171            FieldSelection::Exclude(names) => {
172                let included_names = child
173                    .names()
174                    .iter()
175                    .filter(|&f| !names.as_ref().contains(f))
176                    .cloned()
177                    .collect::<Vec<_>>();
178                child.project(included_names.as_slice())
179            }
180        }?;
181
182        result.into_array().execute(ctx)
183    }
184
185    fn simplify<T: ReduceNode>(
186        &self,
187        selection: &FieldSelection,
188        node: &T,
189    ) -> VortexResult<Option<T>> {
190        let child_struct = node.child(0);
191        let struct_dtype = child_struct.node_dtype()?;
192        let struct_nullability = struct_dtype.nullability();
193
194        let struct_fields = struct_dtype.as_struct_fields_opt().ok_or_else(|| {
195            vortex_err!(
196                "Select child must return a struct dtype, however it was a {}",
197                struct_dtype
198            )
199        })?;
200
201        // "Mask" out the unwanted fields of the child struct `DType`.
202        let included_fields = selection.normalize_to_included_fields(struct_fields.names())?;
203        let all_included_fields_are_nullable = included_fields.iter().all(|name| {
204            struct_fields
205                .field(name)
206                .vortex_expect(
207                    "`normalize_to_included_fields` checks that the included fields already exist \
208                     in `struct_fields`",
209                )
210                .is_nullable()
211        });
212
213        // If no fields are included, we can trivially reduce to a pack node.
214        // NOTE(ngates): we do this knowing that our layout expression partitioning logic has
215        //  special-casing for pack, but not for select. We will fix this up when we revisit the
216        //  layout APIs.
217        if included_fields.is_empty() {
218            return Ok(Some(node.new_node(
219                Pack.bind(PackOptions {
220                    names: FieldNames::empty(),
221                    nullability: struct_nullability,
222                }),
223                &[],
224            )?));
225        }
226
227        // We cannot always convert a `select` into a projection of its child fields. This is
228        // because reading a field does a validity intersection of the struct validity with the
229        // field, which is not the same as just "masking" out the unwanted fields (a selection).
230        //
231        // We can, however, make this reduction when the child of the `select` is already a
232        // `pack` and we know that reading a field will do no validity intersections.
233        //
234        // The intersection only happens when the struct is nullable but the field is not. That
235        // would change the semantics of a `select`, so we can only reduce when it won't happen.
236        let would_intersect_validity =
237            struct_nullability.is_nullable() && !all_included_fields_are_nullable;
238
239        if let Some(child_pack) = child_struct.scalar_fn().and_then(|f| f.as_opt::<Pack>())
240            && !would_intersect_validity
241        {
242            // Take the field nodes straight out of the child `pack` rather than wrap the
243            // `pack` in `get_item`. The guard above proves the two are equivalent here, and the
244            // optimizer visits children before their parent, so a `get_item` introduced now
245            // would never be reduced away.
246            let fields: Vec<T> = included_fields
247                .iter()
248                .map(|name| {
249                    let idx = child_pack.names.find(name).ok_or_else(|| {
250                        vortex_err!(
251                            "Cannot find field {} in pack fields {:?}",
252                            name,
253                            child_pack.names
254                        )
255                    })?;
256
257                    Ok(child_struct.child(idx))
258                })
259                .try_collect::<_, _, VortexError>()?;
260
261            return Ok(Some(node.new_node(
262                Pack.bind(PackOptions {
263                    names: included_fields,
264                    nullability: struct_nullability,
265                }),
266                &fields,
267            )?));
268        }
269
270        Ok(None)
271    }
272
273    fn is_strict(&self, _options: &FieldSelection) -> bool {
274        true
275    }
276
277    fn is_infallible(&self, _instance: &FieldSelection) -> bool {
278        // If this type-checks, it is infallible.
279        true
280    }
281
282    fn forwarded_field(&self, selection: &FieldSelection, field: &FieldName) -> Option<usize> {
283        // The selection keeps the child's validity, so every field it keeps is the child's field.
284        let kept = match selection {
285            FieldSelection::Include(fields) => fields.as_ref().contains(field),
286            FieldSelection::Exclude(fields) => !fields.as_ref().contains(field),
287        };
288        kept.then_some(0)
289    }
290}
291
292impl FieldSelection {
293    pub fn include(columns: FieldNames) -> Self {
294        assert_eq!(columns.iter().unique().collect_vec().len(), columns.len());
295        Self::Include(columns)
296    }
297
298    pub fn exclude(columns: FieldNames) -> Self {
299        assert_eq!(columns.iter().unique().collect_vec().len(), columns.len());
300        Self::Exclude(columns)
301    }
302
303    pub fn is_include(&self) -> bool {
304        matches!(self, Self::Include(_))
305    }
306
307    pub fn is_exclude(&self) -> bool {
308        matches!(self, Self::Exclude(_))
309    }
310
311    pub fn field_names(&self) -> &FieldNames {
312        let (FieldSelection::Include(fields) | FieldSelection::Exclude(fields)) = self;
313
314        fields
315    }
316
317    pub fn normalize_to_included_fields(
318        &self,
319        available_fields: &FieldNames,
320    ) -> VortexResult<FieldNames> {
321        // Hash the available fields so that wide selections stay linear.
322        let available: HashSet<&FieldName> = available_fields.iter().collect();
323
324        // Check that all of the field names exist in the available fields.
325        if self.field_names().iter().any(|f| !available.contains(f)) {
326            vortex_bail!(
327                "Select fields {:?} must be a subset of child fields {:?}",
328                self,
329                available_fields
330            );
331        }
332
333        match self {
334            FieldSelection::Include(fields) => Ok(fields.clone()),
335            FieldSelection::Exclude(exc_fields) => {
336                let excluded: HashSet<&FieldName> = exc_fields.iter().collect();
337                Ok(available_fields
338                    .iter()
339                    .filter(|f| !excluded.contains(f))
340                    .cloned()
341                    .collect())
342            }
343        }
344    }
345}
346
347impl Display for FieldSelection {
348    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
349        match self {
350            FieldSelection::Include(fields) => write!(f, "{{{}}}", DisplayFieldNames(fields)),
351            FieldSelection::Exclude(fields) => write!(f, "~{{{}}}", DisplayFieldNames(fields)),
352        }
353    }
354}