Skip to main content

vortex_array/scalar_fn/builtin/
pack.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::hash::Hash;
7use std::sync::Arc;
8
9use itertools::Itertools as _;
10use prost::Message;
11use vortex_error::VortexResult;
12use vortex_session::VortexSession;
13use vortex_session::registry::CachedId;
14
15use crate::ArrayRef;
16use crate::ExecutionCtx;
17use crate::IntoArray;
18use crate::arrays::StructArray;
19use crate::dtype::DType;
20use crate::dtype::FieldName;
21use crate::dtype::FieldNames;
22use crate::dtype::Nullability;
23use crate::dtype::StructFields;
24use crate::proto::expr as pb;
25use crate::scalar_fn::Arity;
26use crate::scalar_fn::ChildName;
27use crate::scalar_fn::ExecutionArgs;
28use crate::scalar_fn::ReduceNode;
29use crate::scalar_fn::ReduceNodeValidity;
30use crate::scalar_fn::ScalarFnId;
31use crate::scalar_fn::ScalarFnVTable;
32use crate::scalar_fn::display::ExprDisplay;
33use crate::validity::Validity;
34
35/// Pack zero or more expressions into a structure with named fields.
36#[derive(Clone)]
37pub struct Pack;
38
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct PackOptions {
41    pub names: FieldNames,
42    pub nullability: Nullability,
43}
44
45impl Display for PackOptions {
46    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47        write!(
48            f,
49            "names: [{}], nullability: {:#}",
50            self.names.iter().join(", "),
51            self.nullability
52        )
53    }
54}
55
56impl ScalarFnVTable for Pack {
57    type Options = PackOptions;
58
59    fn id(&self) -> ScalarFnId {
60        static ID: CachedId = CachedId::new("vortex.pack");
61        *ID
62    }
63
64    fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
65        Ok(Some(
66            pb::PackOpts {
67                paths: instance
68                    .names
69                    .iter()
70                    .map(|n| n.as_ref().to_owned())
71                    .collect(),
72                nullable: instance.nullability.into(),
73            }
74            .encode_to_vec(),
75        ))
76    }
77
78    fn deserialize(
79        &self,
80        _metadata: &[u8],
81        _session: &VortexSession,
82    ) -> VortexResult<Self::Options> {
83        let opts = pb::PackOpts::decode(_metadata)?;
84        let names: FieldNames = opts
85            .paths
86            .iter()
87            .map(|name| FieldName::from(name.as_str()))
88            .collect();
89        Ok(PackOptions {
90            names,
91            nullability: opts.nullable.into(),
92        })
93    }
94
95    fn arity(&self, options: &Self::Options) -> Arity {
96        Arity::Exact(options.names.len())
97    }
98
99    fn child_name(&self, instance: &Self::Options, child_idx: usize) -> ChildName {
100        match instance.names.get(child_idx) {
101            Some(name) => ChildName::from(Arc::clone(name.inner())),
102            None => unreachable!(
103                "Invalid child index {} for Pack expression with {} fields",
104                child_idx,
105                instance.names.len()
106            ),
107        }
108    }
109
110    fn fmt_sql(
111        &self,
112        options: &Self::Options,
113        expr: &dyn ExprDisplay,
114        f: &mut Formatter<'_>,
115    ) -> std::fmt::Result {
116        write!(f, "pack(")?;
117        for (i, name) in options.names.iter().enumerate() {
118            write!(f, "{}: ", name)?;
119            Display::fmt(expr.display_child(i), f)?;
120            if i + 1 < options.names.len() {
121                write!(f, ", ")?;
122            }
123        }
124        write!(f, "){}", options.nullability)
125    }
126
127    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
128        Ok(DType::Struct(
129            StructFields::new(options.names.clone(), arg_dtypes.to_vec()),
130            options.nullability,
131        ))
132    }
133
134    fn validity<T: ReduceNode>(
135        &self,
136        _options: &Self::Options,
137        node: &T,
138    ) -> VortexResult<ReduceNodeValidity<T>> {
139        Ok(ReduceNodeValidity::Reduced(node.new_constant(true.into())))
140    }
141
142    fn execute(
143        &self,
144        options: &Self::Options,
145        args: &dyn ExecutionArgs,
146        ctx: &mut ExecutionCtx,
147    ) -> VortexResult<ArrayRef> {
148        let len = args.row_count();
149        let value_arrays: Vec<ArrayRef> = (0..args.num_inputs())
150            .map(|i| args.get(i))
151            .collect::<VortexResult<_>>()?;
152        let validity: Validity = options.nullability.into();
153        StructArray::try_new(options.names.clone(), value_arrays, len, validity)?
154            .into_array()
155            .execute(ctx)
156    }
157
158    fn is_strict(&self, _instance: &Self::Options) -> bool {
159        // A null field value does not force the packed struct row to be null.
160        false
161    }
162
163    fn is_infallible(&self, _instance: &Self::Options) -> bool {
164        true
165    }
166}