Skip to main content

vortex_array/scalar_fn/builtin/cast/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod kernel;
5
6use std::fmt::Display;
7use std::fmt::Formatter;
8
9pub use kernel::*;
10use prost::Message;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_err;
14use vortex_session::VortexSession;
15use vortex_session::registry::CachedId;
16
17use crate::AnyColumnar;
18use crate::ArrayRef;
19use crate::ArrayView;
20use crate::Canonical;
21use crate::CanonicalView;
22use crate::ColumnarView;
23use crate::ExecutionCtx;
24use crate::IntoArray;
25use crate::arrays::Bool;
26use crate::arrays::Constant;
27use crate::arrays::Decimal;
28use crate::arrays::Extension;
29use crate::arrays::FixedSizeList;
30use crate::arrays::ListView;
31use crate::arrays::Map;
32use crate::arrays::Null;
33use crate::arrays::Primitive;
34use crate::arrays::ScalarFnArray;
35use crate::arrays::VarBinView;
36use crate::arrays::struct_::compute::cast::struct_cast;
37use crate::builtins::ArrayBuiltins;
38use crate::dtype::DType;
39use crate::dtype::StructFields;
40use crate::proto::expr as pb;
41use crate::scalar_fn::Arity;
42use crate::scalar_fn::ChildName;
43use crate::scalar_fn::ExecutionArgs;
44use crate::scalar_fn::ReduceNode;
45use crate::scalar_fn::ReduceNodeValidity;
46use crate::scalar_fn::ScalarFnId;
47use crate::scalar_fn::ScalarFnVTable;
48use crate::scalar_fn::ScalarFnVTableExt;
49use crate::scalar_fn::display::ExprDisplay;
50use crate::scalar_fn::is_not_null_node;
51
52/// Checks that a cast involving an extension dtype changes only its top-level nullability or
53/// creates typed nulls of a nullable dtype from an untyped [`DType::Null`].
54///
55/// The rule also holds for every extension dtype nested in a struct, list, fixed-size list, or
56/// map, which the cast pairs up the same way as its kernels do. Otherwise a cast could
57/// reinterpret a nested extension that the top-level dtypes do not show.
58///
59/// Use `vortex_functions::expr::ext_storage` to extract an extension array's storage.
60pub(crate) fn check_extension_cast(source: &DType, target: &DType) -> VortexResult<()> {
61    if source.is_extension() || target.is_extension() {
62        if !source.eq_ignore_nullability(target)
63            && !(*source == DType::Null && target.is_nullable())
64        {
65            vortex_bail!(
66                "Cannot cast {source} to {target}. Extension casts only allow changes to top-level nullability or creation of typed nulls from Null."
67            );
68        }
69        return Ok(());
70    }
71
72    match (source, target) {
73        (
74            DType::List(source, _) | DType::FixedSizeList(source, ..),
75            DType::List(target, _) | DType::FixedSizeList(target, ..),
76        ) => check_extension_cast(source, target),
77        (DType::Map(source, _), DType::Map(target, _)) => {
78            check_extension_cast(&source.key_dtype(), &target.key_dtype())?;
79            check_extension_cast(&source.value_dtype(), &target.value_dtype())
80        }
81        (DType::Struct(source, _), DType::Struct(target, _)) => {
82            check_struct_extension_cast(source, target)
83        }
84        _ => Ok(()),
85    }
86}
87
88/// [`check_extension_cast`] for each pair of fields that
89/// [`struct_cast_fields`](crate::arrays::struct_::compute::cast::struct_cast_fields) casts. A
90/// target field that the source lacks becomes nulls, so it reinterprets nothing.
91fn check_struct_extension_cast(source: &StructFields, target: &StructFields) -> VortexResult<()> {
92    if source.names() == target.names() {
93        for (source, target) in source.fields().zip(target.fields()) {
94            check_extension_cast(&source, &target)?;
95        }
96        return Ok(());
97    }
98
99    for (name, target) in target.names().iter().zip(target.fields()) {
100        if let Some(source) = source.field(name) {
101            check_extension_cast(&source, &target)?;
102        }
103    }
104    Ok(())
105}
106
107/// A cast expression that converts values to a target data type.
108#[derive(Clone)]
109pub struct Cast;
110
111impl Cast {
112    /// Creates a lazy cast of `input` to `target_dtype`.
113    ///
114    /// # Errors
115    ///
116    /// Returns an error if the source and target violate the extension cast rule.
117    pub fn try_new(input: ArrayRef, target_dtype: DType) -> VortexResult<ScalarFnArray> {
118        ScalarFnArray::try_new(Cast.bind(target_dtype), [input])
119    }
120}
121
122impl ScalarFnVTable for Cast {
123    type Options = DType;
124
125    fn id(&self) -> ScalarFnId {
126        static ID: CachedId = CachedId::new("vortex.cast");
127        *ID
128    }
129
130    fn serialize(&self, dtype: &DType) -> VortexResult<Option<Vec<u8>>> {
131        Ok(Some(
132            pb::CastOpts {
133                target: Some(dtype.try_into()?),
134            }
135            .encode_to_vec(),
136        ))
137    }
138
139    fn deserialize(
140        &self,
141        _metadata: &[u8],
142        session: &VortexSession,
143    ) -> VortexResult<Self::Options> {
144        let proto = pb::CastOpts::decode(_metadata)?.target;
145        DType::from_proto(
146            proto
147                .as_ref()
148                .ok_or_else(|| vortex_err!("Missing target dtype in Cast expression"))?,
149            session,
150        )
151    }
152
153    fn arity(&self, _options: &DType) -> Arity {
154        Arity::Exact(1)
155    }
156
157    fn child_name(&self, _instance: &DType, child_idx: usize) -> ChildName {
158        match child_idx {
159            0 => ChildName::from("input"),
160            _ => unreachable!("Invalid child index {} for Cast expression", child_idx),
161        }
162    }
163
164    fn fmt_sql(
165        &self,
166        dtype: &DType,
167        expr: &dyn ExprDisplay,
168        f: &mut Formatter<'_>,
169    ) -> std::fmt::Result {
170        write!(f, "cast(")?;
171        Display::fmt(expr.display_child(0), f)?;
172        write!(f, " as {}", dtype)?;
173        write!(f, ")")
174    }
175
176    fn return_dtype(&self, dtype: &DType, arg_dtypes: &[DType]) -> VortexResult<DType> {
177        check_extension_cast(&arg_dtypes[0], dtype)?;
178        Ok(dtype.clone())
179    }
180
181    fn execute(
182        &self,
183        target_dtype: &DType,
184        args: &dyn ExecutionArgs,
185        ctx: &mut ExecutionCtx,
186    ) -> VortexResult<ArrayRef> {
187        let input = args.get(0)?;
188
189        let Some(columnar) = input.as_opt::<AnyColumnar>() else {
190            return input.execute::<ArrayRef>(ctx)?.cast(target_dtype.clone());
191        };
192
193        match columnar {
194            ColumnarView::Canonical(canonical) => {
195                match cast_canonical(canonical, target_dtype, ctx)? {
196                    Some(result) => Ok(result),
197                    None => vortex_bail!(
198                        "No CastKernel to cast canonical array {} from {} to {}",
199                        canonical.to_array_ref().encoding_id(),
200                        canonical.to_array_ref().dtype(),
201                        target_dtype,
202                    ),
203                }
204            }
205            ColumnarView::Constant(constant) => match cast_constant(constant, target_dtype)? {
206                Some(result) => Ok(result),
207                // Some array conversions have no scalar cast.
208                None => input
209                    .execute::<Canonical>(ctx)?
210                    .into_array()
211                    .cast(target_dtype.clone()),
212            },
213        }
214    }
215
216    fn reduce<T: ReduceNode>(&self, target_dtype: &DType, node: &T) -> VortexResult<Option<T>> {
217        let child = node.child(0);
218        if &child.node_dtype()? == target_dtype {
219            return Ok(Some(child));
220        }
221        Ok(None)
222    }
223
224    fn simplify<T: ReduceNode>(&self, target_dtype: &DType, node: &T) -> VortexResult<Option<T>> {
225        let child = node.child(0);
226        if let Some(scalar) = child.as_constant() {
227            // A failing cast (e.g. null to a non-nullable dtype) is left in place so the error
228            // surfaces at execution time rather than during optimization.
229            return Ok(scalar
230                .cast(target_dtype)
231                .ok()
232                .map(|scalar| node.new_constant(scalar)));
233        }
234        // Collapse node if child is already the target type
235        if &child.node_dtype()? == target_dtype {
236            return Ok(Some(child));
237        }
238        Ok(None)
239    }
240
241    fn validity<T: ReduceNode>(
242        &self,
243        dtype: &DType,
244        node: &T,
245    ) -> VortexResult<ReduceNodeValidity<T>> {
246        Ok(ReduceNodeValidity::Reduced(if dtype.is_nullable() {
247            is_not_null_node(&node.child(0))?
248        } else {
249            node.new_constant(true.into())
250        }))
251    }
252
253    fn is_strict(&self, _instance: &DType) -> bool {
254        // Cast options can pin a non-nullable output dtype instead of propagating nullability.
255        false
256    }
257}
258
259/// Cast a canonical array to the target dtype by dispatching to the appropriate
260/// [`CastKernel`] for each canonical encoding.
261///
262/// Canonical encodings that can manipulate validity directly all implement [`CastKernel`] —
263/// the kernel is the execution-time complement of their [`CastReduce`] rule and can compute
264/// statistics (e.g. min of the validity array) when the reduce rule had to give up.
265/// Encodings that delegate to scalars or storage (e.g. [`Null`], [`Constant`], [`Extension`])
266/// only implement [`CastReduce`] because they never need execution-level information.
267fn cast_canonical(
268    canonical: CanonicalView<'_>,
269    dtype: &DType,
270    ctx: &mut ExecutionCtx,
271) -> VortexResult<Option<ArrayRef>> {
272    match canonical {
273        CanonicalView::Null(a) => <Null as CastReduce>::cast(a, dtype),
274        CanonicalView::Bool(a) => <Bool as CastKernel>::cast(a, dtype, ctx),
275        CanonicalView::Primitive(a) => <Primitive as CastKernel>::cast(a, dtype, ctx),
276        CanonicalView::Decimal(a) => <Decimal as CastKernel>::cast(a, dtype, ctx),
277        CanonicalView::VarBinView(a) => <VarBinView as CastKernel>::cast(a, dtype, ctx),
278        CanonicalView::List(a) => <ListView as CastKernel>::cast(a, dtype, ctx),
279        CanonicalView::Map(a) => <Map as CastKernel>::cast(a, dtype, ctx),
280        CanonicalView::FixedSizeList(a) => <FixedSizeList as CastKernel>::cast(a, dtype, ctx),
281        CanonicalView::Struct(a) => struct_cast(a, dtype, ctx),
282        CanonicalView::Union(_) => {
283            vortex_bail!(
284                "TODO(connor)[Union]: implement Union casting with conformance coverage for \
285                 outer nullability changes, including validation of nullable-to-nonnullable casts"
286            )
287        }
288        CanonicalView::Extension(a) => <Extension as CastReduce>::cast(a, dtype),
289        CanonicalView::Variant(_) => {
290            vortex_bail!("Variant arrays don't support casting")
291        }
292    }
293}
294
295/// Cast a constant array by dispatching to its [`CastReduce`] implementation.
296fn cast_constant(array: ArrayView<Constant>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
297    <Constant as CastReduce>::cast(array, dtype)
298}