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