vortex_array/scalar_fn/builtin/cast/
mod.rs1mod 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
54pub(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
95fn extension_cast_hint(source: &DType, target: &DType) -> Option<&'static str> {
97 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
105fn 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#[derive(Clone)]
126pub struct Cast;
127
128impl Cast {
129 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 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 return Ok(scalar
253 .cast(target_dtype)
254 .ok()
255 .map(|scalar| node.new_constant(scalar)));
256 }
257 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 false
279 }
280}
281
282fn 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
318fn cast_constant(array: ArrayView<Constant>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
320 <Constant as CastReduce>::cast(array, dtype)
321}