1use super::{Between, Expr, Like, predicate_bounds};
6use crate::ValueOrLambda;
7use crate::expr::{
8 AggregateFunction, AggregateFunctionParams, Alias, BinaryExpr, Cast, InList,
9 InSubquery, Lambda, Placeholder, ScalarFunction, TryCast, Unnest, WindowFunction,
10 WindowFunctionParams, in_subquery_tuple_values,
11};
12use crate::expr::{FieldMetadata, LambdaVariable};
13use crate::higher_order_function::HigherOrderReturnFieldArgs;
14use crate::type_coercion::functions::value_fields_with_higher_order_udf_and_lambdas;
15use crate::type_coercion::functions::{UDFCoercionExt, fields_with_udf};
16use crate::type_coercion::other::get_coerce_type_for_case_expression;
17use crate::udf::ReturnFieldArgs;
18use crate::{
19 LogicalPlan, Operator, Projection, Subquery, WindowFunctionDefinition, utils,
20};
21use arrow::compute::can_cast_types;
22use arrow::datatypes::FieldRef;
23use arrow::datatypes::{DataType, Field};
24use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
25use datafusion_common::datatype::FieldExt;
26use datafusion_common::{
27 Column, DataFusionError, ExprSchema, Result, ScalarValue, Spans, TableReference,
28 not_impl_err, plan_datafusion_err, plan_err,
29};
30use datafusion_expr_common::type_coercion::binary::BinaryTypeCoercer;
31use datafusion_functions_window_common::field::WindowUDFFieldArgs;
32use std::sync::Arc;
33
34pub trait ExprSchemable {
36 fn get_type(&self, schema: &dyn ExprSchema) -> Result<DataType>;
42
43 fn nullable(&self, input_schema: &dyn ExprSchema) -> Result<bool>;
45
46 fn metadata(&self, schema: &dyn ExprSchema) -> Result<FieldMetadata>;
48
49 fn to_field(
51 &self,
52 input_schema: &dyn ExprSchema,
53 ) -> Result<(Option<TableReference>, Arc<Field>)>;
54
55 fn cast_to(self, cast_to_type: &DataType, schema: &dyn ExprSchema) -> Result<Expr>;
57
58 #[deprecated(
60 since = "51.0.0",
61 note = "Use `to_field().1.is_nullable` and `to_field().1.data_type()` directly instead"
62 )]
63 fn data_type_and_nullable(&self, schema: &dyn ExprSchema)
64 -> Result<(DataType, bool)>;
65}
66
67fn cast_output_field(
82 source_field: &FieldRef,
83 target_field: &FieldRef,
84 force_nullable: bool,
85) -> Arc<Field> {
86 let is_type_only = target_field.name().is_empty()
88 && target_field.is_nullable()
89 && target_field.metadata().is_empty();
90
91 let metadata = if is_type_only {
92 let mut meta = source_field.metadata().clone();
94 meta.remove(EXTENSION_TYPE_NAME_KEY);
95 meta.remove(EXTENSION_TYPE_METADATA_KEY);
96 meta
97 } else {
98 target_field.metadata().clone()
100 };
101
102 let mut f = source_field
103 .as_ref()
104 .clone()
105 .with_data_type(target_field.data_type().clone())
106 .with_metadata(metadata);
107 if force_nullable {
108 f = f.with_nullable(true);
109 }
110 Arc::new(f)
111}
112
113fn scalar_arguments_for_fields(
114 args: &[Expr],
115 arg_fields: &[FieldRef],
116) -> Vec<Option<ScalarValue>> {
117 args.iter()
118 .zip(arg_fields)
119 .map(|(expr, field)| scalar_argument_for_field(expr, field))
120 .collect()
121}
122
123fn scalar_argument_for_field(expr: &Expr, arg_field: &FieldRef) -> Option<ScalarValue> {
124 match expr {
125 Expr::Literal(sv, _) => Some(
126 sv.cast_to(arg_field.data_type())
127 .unwrap_or_else(|_| sv.clone()),
128 ),
129 _ => None,
130 }
131}
132
133impl ExprSchemable for Expr {
134 #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
175 fn get_type(&self, schema: &dyn ExprSchema) -> Result<DataType> {
176 match self {
177 Expr::Alias(Alias { expr, .. }) | Expr::Negative(expr) => {
178 expr.get_type(schema)
179 }
180 Expr::Column(c) => Ok(schema.data_type(c)?.clone()),
181 Expr::OuterReferenceColumn(field, _) => Ok(field.data_type().clone()),
182 Expr::ScalarVariable(field, _) => Ok(field.data_type().clone()),
183 Expr::Literal(l, _) => Ok(l.data_type()),
184 Expr::Case(case) => {
185 let then_types = case
186 .when_then_expr
187 .iter()
188 .map(|(_, expr)| expr.get_type(schema))
189 .collect::<Result<Vec<_>>>()?;
190 let else_type = case
191 .else_expr
192 .as_ref()
193 .map(|expr| expr.get_type(schema))
194 .transpose()?;
195 let common_type =
198 get_coerce_type_for_case_expression(&then_types, else_type.as_ref());
199 let result_type = common_type.unwrap_or_else(|| {
200 then_types
201 .into_iter()
202 .find(|t| !t.is_null())
203 .or(else_type)
204 .unwrap_or(DataType::Null)
205 });
206 Ok(result_type)
207 }
208 Expr::Cast(Cast { field, .. }) | Expr::TryCast(TryCast { field, .. }) => {
209 Ok(field.data_type().clone())
210 }
211 Expr::Unnest(Unnest { expr, .. }) => {
212 let arg_data_type = expr.get_type(schema)?;
213 match arg_data_type {
215 DataType::List(field)
216 | DataType::LargeList(field)
217 | DataType::FixedSizeList(field, _)
218 | DataType::ListView(field)
219 | DataType::LargeListView(field) => Ok(field.data_type().clone()),
220 DataType::Struct(_) => Ok(arg_data_type),
221 DataType::Null => {
222 not_impl_err!("unnest() does not support null yet")
223 }
224 _ => {
225 plan_err!(
226 "unnest() can only be applied to array, struct and null"
227 )
228 }
229 }
230 }
231 Expr::ScalarFunction(_)
232 | Expr::WindowFunction(_)
233 | Expr::AggregateFunction(_) => {
234 Ok(self.to_field(schema)?.1.data_type().clone())
235 }
236 Expr::Not(_)
237 | Expr::IsNull(_)
238 | Expr::Exists { .. }
239 | Expr::InSubquery(_)
240 | Expr::SetComparison(_)
241 | Expr::Between { .. }
242 | Expr::InList { .. }
243 | Expr::IsNotNull(_)
244 | Expr::IsTrue(_)
245 | Expr::IsFalse(_)
246 | Expr::IsUnknown(_)
247 | Expr::IsNotTrue(_)
248 | Expr::IsNotFalse(_)
249 | Expr::IsNotUnknown(_) => Ok(DataType::Boolean),
250 Expr::ScalarSubquery(subquery) => {
251 Ok(subquery.subquery.schema().field(0).data_type().clone())
252 }
253 Expr::BinaryExpr(BinaryExpr { left, right, op }) => BinaryTypeCoercer::new(
254 &left.get_type(schema)?,
255 op,
256 &right.get_type(schema)?,
257 )
258 .get_result_type(),
259 Expr::Like { .. } | Expr::SimilarTo { .. } => Ok(DataType::Boolean),
260 Expr::Placeholder(Placeholder { field, .. }) => {
261 if let Some(field) = field {
262 Ok(field.data_type().clone())
263 } else {
264 Ok(DataType::Null)
267 }
268 }
269 #[expect(deprecated)]
270 Expr::Wildcard { .. } => Ok(DataType::Null),
271 Expr::GroupingSet(_) => {
272 Ok(DataType::Null)
274 }
275 Expr::HigherOrderFunction(_func) => {
276 Ok(self.to_field(schema)?.1.data_type().clone())
277 }
278 Expr::Lambda(_lambda) => Ok(DataType::Null),
279 Expr::LambdaVariable(LambdaVariable { field, .. }) => match field {
280 Some(f) => Ok(f.data_type().clone()),
281 None => Ok(DataType::Null),
284 },
285 }
286 }
287
288 fn nullable(&self, input_schema: &dyn ExprSchema) -> Result<bool> {
300 match self {
301 Expr::Alias(Alias { expr, .. }) | Expr::Not(expr) | Expr::Negative(expr) => {
302 expr.nullable(input_schema)
303 }
304
305 Expr::InList(InList { expr, list, .. }) => {
306 const MAX_INSPECT_LIMIT: usize = 6;
308 let has_nullable = std::iter::once(expr.as_ref())
310 .chain(list)
311 .take(MAX_INSPECT_LIMIT)
312 .find_map(|e| {
313 e.nullable(input_schema)
314 .map(|nullable| if nullable { Some(()) } else { None })
315 .transpose()
316 })
317 .transpose()?;
318 Ok(match has_nullable {
319 Some(_) => true,
321 None if list.len() + 1 > MAX_INSPECT_LIMIT => true,
323 _ => false,
325 })
326 }
327
328 Expr::Between(Between {
329 expr, low, high, ..
330 }) => Ok(expr.nullable(input_schema)?
331 || low.nullable(input_schema)?
332 || high.nullable(input_schema)?),
333
334 Expr::Column(c) => input_schema.nullable(c),
335 Expr::OuterReferenceColumn(field, _) => Ok(field.is_nullable()),
336 Expr::Literal(value, _) => Ok(value.is_null()),
337 Expr::Case(case) => {
338 let nullable_then = case.when_then_expr.iter().find_map(|(w, t)| {
339 let is_nullable = match t.nullable(input_schema) {
340 Err(e) => return Some(Err(e)),
341 Ok(n) => n,
342 };
343
344 if !is_nullable {
347 return None;
348 }
349
350 if case.expr.is_some() {
352 return Some(Ok(()));
353 }
354
355 let bounds = match predicate_bounds::evaluate_bounds(
359 w,
360 Some(unwrap_certainly_null_expr(t)),
361 input_schema,
362 ) {
363 Err(e) => return Some(Err(e)),
364 Ok(b) => b,
365 };
366
367 let can_be_true =
368 match bounds.contains_value(ScalarValue::Boolean(Some(true))) {
369 Err(e) => return Some(Err(e)),
370 Ok(b) => b,
371 };
372
373 if !can_be_true {
374 None
378 } else {
379 Some(Ok(()))
381 }
382 });
383
384 if let Some(nullable_then) = nullable_then {
385 nullable_then.map(|_| true)
389 } else if let Some(e) = &case.else_expr {
390 e.nullable(input_schema)
393 } else {
394 Ok(true)
397 }
398 }
399 Expr::Cast(Cast { expr, .. }) => expr.nullable(input_schema),
400 Expr::ScalarFunction(_)
401 | Expr::AggregateFunction(_)
402 | Expr::WindowFunction(_) => Ok(self.to_field(input_schema)?.1.is_nullable()),
403 Expr::ScalarVariable(field, _) => Ok(field.is_nullable()),
404 Expr::TryCast { .. } | Expr::Unnest(_) | Expr::Placeholder(_) => Ok(true),
405 Expr::IsNull(_)
406 | Expr::IsNotNull(_)
407 | Expr::IsTrue(_)
408 | Expr::IsFalse(_)
409 | Expr::IsUnknown(_)
410 | Expr::IsNotTrue(_)
411 | Expr::IsNotFalse(_)
412 | Expr::IsNotUnknown(_)
413 | Expr::Exists { .. } => Ok(false),
414 Expr::SetComparison(_) => Ok(true),
415 Expr::InSubquery(InSubquery { expr, subquery, .. }) => {
416 if let Some(values) = in_subquery_tuple_values(expr, &subquery.subquery)?
421 {
422 let mut nullable = subquery
423 .subquery
424 .schema()
425 .fields()
426 .iter()
427 .any(|field| field.is_nullable());
428 for value in values.iter() {
429 nullable |= value.nullable(input_schema)?;
430 }
431 return Ok(nullable);
432 }
433 let expr_nullable = expr.nullable(input_schema)?;
434 let subquery_nullable = subquery.subquery.schema().fields().first().ok_or_else(|| {
435 plan_datafusion_err!("subquery must return exactly one column of data to compare against")
436 })?.is_nullable();
437
438 Ok(expr_nullable | subquery_nullable)
439 }
440 Expr::ScalarSubquery(subquery) => Ok(scalar_subquery_nullable(subquery)),
441 Expr::BinaryExpr(BinaryExpr { left, right, op }) => match op {
442 Operator::IsDistinctFrom | Operator::IsNotDistinctFrom => Ok(false),
443 _ => Ok(left.nullable(input_schema)? || right.nullable(input_schema)?),
444 },
445 Expr::Like(Like { expr, pattern, .. })
446 | Expr::SimilarTo(Like { expr, pattern, .. }) => {
447 Ok(expr.nullable(input_schema)? || pattern.nullable(input_schema)?)
448 }
449 #[expect(deprecated)]
450 Expr::Wildcard { .. } => Ok(false),
451 Expr::GroupingSet(_) => {
452 Ok(true)
455 }
456 Expr::HigherOrderFunction(_func) => {
457 Ok(self.to_field(input_schema)?.1.is_nullable())
458 }
459 Expr::Lambda(_lambda) => Ok(true),
460 Expr::LambdaVariable(LambdaVariable { field, .. }) => match field {
461 Some(f) => Ok(f.is_nullable()),
462 None => Ok(true),
465 },
466 }
467 }
468
469 fn metadata(&self, schema: &dyn ExprSchema) -> Result<FieldMetadata> {
470 self.to_field(schema)
471 .map(|(_, field)| FieldMetadata::from(field.metadata()))
472 }
473
474 fn data_type_and_nullable(
485 &self,
486 schema: &dyn ExprSchema,
487 ) -> Result<(DataType, bool)> {
488 let field = self.to_field(schema)?.1;
489
490 Ok((field.data_type().clone(), field.is_nullable()))
491 }
492
493 fn to_field(
546 &self,
547 schema: &dyn ExprSchema,
548 ) -> Result<(Option<TableReference>, Arc<Field>)> {
549 let (relation, schema_name) = self.qualified_name();
550 #[expect(deprecated)]
551 let field = match self {
552 Expr::Alias(Alias {
553 expr,
554 name: _,
555 metadata,
556 ..
557 }) => {
558 let field = expr.to_field(schema)?.1;
559 let mut combined_metadata = FieldMetadata::from(field.metadata());
560 if let Some(metadata) = metadata {
561 combined_metadata.extend(metadata.clone());
562 }
563
564 Ok(field.with_field_metadata(&combined_metadata))
565 }
566 Expr::Negative(expr) => expr.to_field(schema).map(|(_, f)| f),
567 Expr::Column(c) => schema.field_from_column(c).map(Arc::clone),
568 Expr::OuterReferenceColumn(field, _) => {
569 Ok(Arc::clone(field).renamed(&schema_name))
570 }
571 Expr::ScalarVariable(field, _) => Ok(Arc::clone(field).renamed(&schema_name)),
572 Expr::Literal(l, metadata) => Ok(Arc::new(
573 Field::new(&schema_name, l.data_type(), l.is_null())
574 .with_field_metadata_opt(metadata.as_ref()),
575 )),
576 Expr::IsNull(_)
577 | Expr::IsNotNull(_)
578 | Expr::IsTrue(_)
579 | Expr::IsFalse(_)
580 | Expr::IsUnknown(_)
581 | Expr::IsNotTrue(_)
582 | Expr::IsNotFalse(_)
583 | Expr::IsNotUnknown(_)
584 | Expr::Exists { .. } => {
585 Ok(Arc::new(Field::new(&schema_name, DataType::Boolean, false)))
586 }
587 Expr::ScalarSubquery(subquery) => {
588 let field = subquery.subquery.schema().field(0);
589 Ok(Arc::new(
590 field
591 .as_ref()
592 .clone()
593 .with_nullable(scalar_subquery_nullable(subquery)),
594 ))
595 }
596 Expr::BinaryExpr(BinaryExpr { left, right, op }) => {
597 let (left_field, right_field) =
598 (left.to_field(schema)?.1, right.to_field(schema)?.1);
599
600 let (lhs_type, lhs_nullable) =
601 (left_field.data_type(), left_field.is_nullable());
602 let (rhs_type, rhs_nullable) =
603 (right_field.data_type(), right_field.is_nullable());
604 let mut coercer = BinaryTypeCoercer::new(lhs_type, op, rhs_type);
605 coercer.set_lhs_spans(left.spans().cloned().unwrap_or_default());
606 coercer.set_rhs_spans(right.spans().cloned().unwrap_or_default());
607 let nullable = match op {
608 Operator::IsDistinctFrom | Operator::IsNotDistinctFrom => false,
609 _ => lhs_nullable || rhs_nullable,
610 };
611 Ok(Arc::new(Field::new(
612 &schema_name,
613 coercer.get_result_type()?,
614 nullable,
615 )))
616 }
617 Expr::WindowFunction(window_function) => {
618 let WindowFunction {
619 fun,
620 params: WindowFunctionParams { args, .. },
621 } = window_function.as_ref();
622
623 let fields = args
624 .iter()
625 .map(|e| e.to_field(schema).map(|(_, f)| f))
626 .collect::<Result<Vec<_>>>()?;
627 match fun {
628 WindowFunctionDefinition::AggregateUDF(udaf) => {
629 let new_fields =
630 verify_function_arguments(udaf.as_ref(), &fields)?;
631 let return_field = udaf.return_field(&new_fields)?;
632 Ok(return_field)
633 }
634 WindowFunctionDefinition::WindowUDF(udwf) => {
635 let new_fields =
636 verify_function_arguments(udwf.as_ref(), &fields)?;
637 let return_field = udwf
638 .field(WindowUDFFieldArgs::new(&new_fields, &schema_name))?;
639 Ok(return_field)
640 }
641 }
642 }
643 Expr::AggregateFunction(AggregateFunction {
644 func,
645 params: AggregateFunctionParams { args, .. },
646 }) => {
647 let fields = args
648 .iter()
649 .map(|e| e.to_field(schema).map(|(_, f)| f))
650 .collect::<Result<Vec<_>>>()?;
651 let new_fields = verify_function_arguments(func.as_ref(), &fields)?;
652 func.return_field(&new_fields)
653 }
654 Expr::ScalarFunction(ScalarFunction { func, args }) => {
655 let fields = args
656 .iter()
657 .map(|e| e.to_field(schema).map(|(_, f)| f))
658 .collect::<Result<Vec<_>>>()?;
659 let new_fields = verify_function_arguments(func.as_ref(), &fields)?;
660
661 let arguments = scalar_arguments_for_fields(args, &new_fields);
662 let argument_refs =
663 arguments.iter().map(Option::as_ref).collect::<Vec<_>>();
664 let args = ReturnFieldArgs {
665 arg_fields: &new_fields,
666 scalar_arguments: &argument_refs,
667 };
668
669 func.return_field_from_args(args)
670 }
671 Expr::Cast(Cast { expr, field }) => expr
673 .to_field(schema)
674 .map(|(_table_ref, src)| cast_output_field(&src, field, false)),
675 Expr::Placeholder(Placeholder {
676 id: _,
677 field: Some(field),
678 }) => Ok(Arc::clone(field).renamed(&schema_name)),
679 Expr::TryCast(TryCast { expr, field }) => expr
680 .to_field(schema)
681 .map(|(_table_ref, src)| cast_output_field(&src, field, true)),
682 Expr::LambdaVariable(LambdaVariable {
683 field: Some(field), ..
684 }) => Ok(Arc::clone(field).renamed(&schema_name)),
685 Expr::Unnest(Unnest { expr, .. }) => {
686 let nullable = self.nullable(schema)?;
687 match expr.get_type(schema)? {
688 DataType::List(field)
689 | DataType::LargeList(field)
690 | DataType::FixedSizeList(field, _)
691 | DataType::ListView(field)
692 | DataType::LargeListView(field) => Ok(Arc::new(
693 field
694 .as_ref()
695 .clone()
696 .with_name(&schema_name)
697 .with_nullable(nullable),
698 )),
699 _ => Ok(Arc::new(Field::new(
700 &schema_name,
701 self.get_type(schema)?,
702 nullable,
703 ))),
704 }
705 }
706 Expr::Like(_)
707 | Expr::SimilarTo(_)
708 | Expr::Not(_)
709 | Expr::Between(_)
710 | Expr::Case(_)
711 | Expr::InList(_)
712 | Expr::InSubquery(_)
713 | Expr::SetComparison(_)
714 | Expr::Wildcard { .. }
715 | Expr::GroupingSet(_)
716 | Expr::Placeholder(_)
717 | Expr::Lambda(_)
718 | Expr::LambdaVariable(_) => Ok(Arc::new(Field::new(
719 &schema_name,
720 self.get_type(schema)?,
721 self.nullable(schema)?,
722 ))),
723 Expr::HigherOrderFunction(func) => {
724 let arg_fields = func
725 .args
726 .iter()
727 .map(|arg| match arg {
728 Expr::Lambda(Lambda { params: _, body }) => {
729 Ok(ValueOrLambda::Lambda(Arc::new(Field::new(
731 arg.qualified_name().1,
732 body.get_type(schema)?,
733 body.nullable(schema)?,
734 ))))
735 }
736 _ => Ok(ValueOrLambda::Value(arg.to_field(schema)?.1)),
737 })
738 .collect::<Result<Vec<_>>>()?;
739
740 let new_fields = value_fields_with_higher_order_udf_and_lambdas(
741 &arg_fields,
742 func.func.as_ref(),
743 )?;
744
745 let arguments = func
746 .args
747 .iter()
748 .map(|e| match e {
749 Expr::Literal(sv, _) => Some(sv),
750 _ => None,
751 })
752 .collect::<Vec<_>>();
753
754 let args = HigherOrderReturnFieldArgs {
755 arg_fields: &new_fields,
756 scalar_arguments: &arguments,
757 };
758
759 func.func.return_field_from_args(args)
760 }
761 }?;
762
763 Ok((
764 relation,
765 field.renamed(&schema_name),
767 ))
768 }
769
770 fn cast_to(self, cast_to_type: &DataType, schema: &dyn ExprSchema) -> Result<Expr> {
777 let this_type = self.get_type(schema)?;
778 if this_type == *cast_to_type {
779 return Ok(self);
780 }
781
782 let can_cast = match (&this_type, cast_to_type) {
788 (DataType::Struct(_), DataType::Struct(_)) => {
789 true
791 }
792 _ => can_cast_types(&this_type, cast_to_type),
793 };
794
795 if can_cast {
796 match self {
797 Expr::ScalarSubquery(subquery) => {
798 Ok(Expr::ScalarSubquery(cast_subquery(subquery, cast_to_type)?))
799 }
800 _ => Ok(Expr::Cast(Cast::new(Box::new(self), cast_to_type.clone()))),
801 }
802 } else {
803 plan_err!("Cannot automatically convert {this_type} to {cast_to_type}")
804 }
805 }
806}
807
808fn verify_function_arguments<F: UDFCoercionExt>(
811 function: &F,
812 input_fields: &[FieldRef],
813) -> Result<Vec<FieldRef>> {
814 fields_with_udf(input_fields, function).map_err(|err| {
815 let data_types = input_fields
816 .iter()
817 .map(|f| f.data_type())
818 .cloned()
819 .collect::<Vec<_>>();
820 plan_datafusion_err!(
821 "{}. {}",
822 match err {
823 DataFusionError::Plan(msg) => msg,
824 err => err.to_string(),
825 },
826 utils::generate_signature_error_message(
827 function.name(),
828 function.signature(),
829 &data_types
830 )
831 )
832 })
833}
834
835fn unwrap_certainly_null_expr(expr: &Expr) -> &Expr {
837 match expr {
838 Expr::Not(e) => unwrap_certainly_null_expr(e),
839 Expr::Negative(e) => unwrap_certainly_null_expr(e),
840 Expr::Cast(e) => unwrap_certainly_null_expr(e.expr.as_ref()),
841 _ => expr,
842 }
843}
844
845fn scalar_subquery_nullable(subquery: &Subquery) -> bool {
851 subquery.subquery.schema().field(0).is_nullable() || subquery.subquery.min_rows() == 0
852}
853
854pub fn cast_subquery(subquery: Subquery, cast_to_type: &DataType) -> Result<Subquery> {
862 cast_subquery_columns(subquery, std::slice::from_ref(cast_to_type))
863}
864
865pub fn cast_subquery_columns(
872 subquery: Subquery,
873 cast_to_types: &[DataType],
874) -> Result<Subquery> {
875 let schema = subquery.subquery.schema();
876 if schema
877 .fields()
878 .iter()
879 .zip(cast_to_types)
880 .all(|(field, cast_to_type)| field.data_type() == cast_to_type)
881 {
882 return Ok(subquery);
883 }
884
885 let plan = subquery.subquery.as_ref();
886 let new_plan = match plan {
887 LogicalPlan::Projection(projection) => {
888 let cast_exprs = projection
889 .expr
890 .iter()
891 .zip(cast_to_types)
892 .map(|(expr, cast_to_type)| {
893 expr.clone()
894 .cast_to(cast_to_type, projection.input.schema())
895 })
896 .collect::<Result<Vec<_>>>()?;
897 LogicalPlan::Projection(Projection::try_new(
898 cast_exprs,
899 Arc::clone(&projection.input),
900 )?)
901 }
902 _ => {
903 let cast_exprs = cast_to_types
904 .iter()
905 .enumerate()
906 .map(|(i, cast_to_type)| {
907 Expr::Column(Column::from(plan.schema().qualified_field(i)))
908 .cast_to(cast_to_type, subquery.subquery.schema())
909 })
910 .collect::<Result<Vec<_>>>()?;
911 LogicalPlan::Projection(Projection::try_new(
912 cast_exprs,
913 Arc::clone(&subquery.subquery),
914 )?)
915 }
916 };
917 Ok(Subquery {
918 subquery: Arc::new(new_plan),
919 outer_ref_columns: subquery.outer_ref_columns,
920 spans: Spans::new(),
921 })
922}
923
924#[cfg(test)]
925mod tests {
926 use std::collections::HashMap;
927
928 use super::*;
929 use crate::logical_plan::builder::LogicalTableSource;
930 use crate::test::function_stub::count;
931 use crate::{
932 LogicalPlanBuilder, and, col, in_subquery, lit, not, or,
933 out_ref_col_with_metadata, scalar_subquery, when,
934 };
935
936 use arrow::datatypes::Schema;
937 use datafusion_common::{DFSchema, assert_or_internal_err};
938
939 macro_rules! test_is_expr_nullable {
940 ($EXPR_TYPE:ident) => {{
941 let expr = lit(ScalarValue::Null).$EXPR_TYPE();
942 assert!(!expr.nullable(&MockExprSchema::new()).unwrap());
943 }};
944 }
945
946 #[test]
947 fn scalar_arguments_match_coerced_fields() {
948 let int16_field: FieldRef = Field::new("arg", DataType::Int16, true).into();
949
950 assert_eq!(
951 scalar_argument_for_field(&lit(1_i64), &int16_field),
952 Some(ScalarValue::Int16(Some(1)))
953 );
954 assert_eq!(
955 scalar_argument_for_field(&lit(ScalarValue::Null), &int16_field),
956 Some(ScalarValue::Int16(None))
957 );
958
959 let int32_list = ScalarValue::List(ScalarValue::new_list(
960 &[ScalarValue::Int32(Some(1))],
961 &DataType::Int32,
962 true,
963 ));
964 let int64_list_type = DataType::new_list(DataType::Int64, true);
965 let int64_list_field: FieldRef =
966 Field::new("arg", int64_list_type.clone(), true).into();
967 assert_eq!(
968 scalar_argument_for_field(&lit(int32_list.clone()), &int64_list_field),
969 Some(int32_list.cast_to(&int64_list_type).unwrap())
970 );
971 }
972
973 #[test]
974 fn scalar_arguments_exclude_expression_casts_and_preserve_invalid_values() {
975 let int16_field: FieldRef = Field::new("arg", DataType::Int16, true).into();
976 let int32_field: FieldRef = Field::new("arg", DataType::Int32, true).into();
977 let explicit_cast = Expr::Cast(Cast::new(Box::new(lit(1_i64)), DataType::Int16));
978 let explicit_try_cast =
979 Expr::TryCast(TryCast::new(Box::new(lit(1_i64)), DataType::Int16));
980 let out_of_i32_range = i64::from(i32::MAX) + 1;
981
982 assert_eq!(
983 scalar_argument_for_field(&explicit_cast, &int16_field),
984 None
985 );
986 assert_eq!(
987 scalar_argument_for_field(&explicit_try_cast, &int16_field),
988 None
989 );
990 assert_eq!(
991 scalar_argument_for_field(&lit("not an integer"), &int16_field),
992 Some(ScalarValue::Utf8(Some("not an integer".to_string())))
993 );
994 assert_eq!(
995 scalar_argument_for_field(&lit(out_of_i32_range), &int32_field),
996 Some(ScalarValue::Int64(Some(out_of_i32_range)))
997 );
998 }
999
1000 #[test]
1001 fn expr_schema_nullability() {
1002 let cases = [
1003 (Operator::Eq, false, false),
1004 (Operator::Eq, true, true),
1005 (Operator::IsDistinctFrom, true, false),
1006 (Operator::IsNotDistinctFrom, true, false),
1007 ];
1008
1009 for (op, input_nullable, expected) in cases {
1010 let expr = Expr::BinaryExpr(BinaryExpr::new(
1011 Box::new(col("foo")),
1012 op,
1013 Box::new(col("bar")),
1014 ));
1015 let schema = MockExprSchema::new()
1016 .with_data_type(DataType::Boolean)
1017 .with_nullable(input_nullable);
1018
1019 assert_eq!(expr.nullable(&schema).unwrap(), expected, "{op}");
1020 assert_eq!(
1021 expr.to_field(&schema).unwrap().1.is_nullable(),
1022 expected,
1023 "{op}"
1024 );
1025 }
1026
1027 test_is_expr_nullable!(is_null);
1028 test_is_expr_nullable!(is_not_null);
1029 test_is_expr_nullable!(is_true);
1030 test_is_expr_nullable!(is_not_true);
1031 test_is_expr_nullable!(is_false);
1032 test_is_expr_nullable!(is_not_false);
1033 test_is_expr_nullable!(is_unknown);
1034 test_is_expr_nullable!(is_not_unknown);
1035 }
1036
1037 #[test]
1038 fn test_between_nullability() {
1039 let get_schema = |nullable| {
1040 MockExprSchema::new()
1041 .with_data_type(DataType::Int32)
1042 .with_nullable(nullable)
1043 };
1044
1045 let expr = col("foo").between(lit(1), lit(2));
1046 assert!(!expr.nullable(&get_schema(false)).unwrap());
1047 assert!(expr.nullable(&get_schema(true)).unwrap());
1048
1049 let null = lit(ScalarValue::Int32(None));
1050
1051 let expr = col("foo").between(null.clone(), lit(2));
1052 assert!(expr.nullable(&get_schema(false)).unwrap());
1053
1054 let expr = col("foo").between(lit(1), null.clone());
1055 assert!(expr.nullable(&get_schema(false)).unwrap());
1056
1057 let expr = col("foo").between(null.clone(), null);
1058 assert!(expr.nullable(&get_schema(false)).unwrap());
1059 }
1060
1061 fn assert_nullability(expr: &Expr, schema: &dyn ExprSchema, expected: bool) {
1062 assert_eq!(
1063 expr.nullable(schema).unwrap(),
1064 expected,
1065 "Nullability of '{expr}' should be {expected}"
1066 );
1067 }
1068
1069 fn assert_not_nullable(expr: &Expr, schema: &dyn ExprSchema) {
1070 assert_nullability(expr, schema, false);
1071 }
1072
1073 fn assert_nullable(expr: &Expr, schema: &dyn ExprSchema) {
1074 assert_nullability(expr, schema, true);
1075 }
1076
1077 #[test]
1078 fn test_case_expression_nullability() -> Result<()> {
1079 let nullable_schema = MockExprSchema::new()
1080 .with_data_type(DataType::Int32)
1081 .with_nullable(true);
1082
1083 let not_nullable_schema = MockExprSchema::new()
1084 .with_data_type(DataType::Int32)
1085 .with_nullable(false);
1086
1087 let e = when(col("x").is_not_null(), col("x")).otherwise(lit(0))?;
1089 assert_not_nullable(&e, &nullable_schema);
1090 assert_not_nullable(&e, ¬_nullable_schema);
1091
1092 let e = when(not(col("x").is_null()), col("x")).otherwise(lit(0))?;
1094 assert_not_nullable(&e, &nullable_schema);
1095 assert_not_nullable(&e, ¬_nullable_schema);
1096
1097 let e = when(col("x").eq(lit(5)), col("x")).otherwise(lit(0))?;
1099 assert_not_nullable(&e, &nullable_schema);
1100 assert_not_nullable(&e, ¬_nullable_schema);
1101
1102 let e = when(and(col("x").is_not_null(), col("x").eq(lit(5))), col("x"))
1104 .otherwise(lit(0))?;
1105 assert_not_nullable(&e, &nullable_schema);
1106 assert_not_nullable(&e, ¬_nullable_schema);
1107
1108 let e = when(and(col("x").eq(lit(5)), col("x").is_not_null()), col("x"))
1110 .otherwise(lit(0))?;
1111 assert_not_nullable(&e, &nullable_schema);
1112 assert_not_nullable(&e, ¬_nullable_schema);
1113
1114 let e = when(or(col("x").is_not_null(), col("x").eq(lit(5))), col("x"))
1116 .otherwise(lit(0))?;
1117 assert_not_nullable(&e, &nullable_schema);
1118 assert_not_nullable(&e, ¬_nullable_schema);
1119
1120 let e = when(or(col("x").eq(lit(5)), col("x").is_not_null()), col("x"))
1122 .otherwise(lit(0))?;
1123 assert_not_nullable(&e, &nullable_schema);
1124 assert_not_nullable(&e, ¬_nullable_schema);
1125
1126 let e = when(
1128 or(
1129 and(col("x").eq(lit(5)), col("x").is_not_null()),
1130 and(col("x").eq(col("bar")), col("x").is_not_null()),
1131 ),
1132 col("x"),
1133 )
1134 .otherwise(lit(0))?;
1135 assert_not_nullable(&e, &nullable_schema);
1136 assert_not_nullable(&e, ¬_nullable_schema);
1137
1138 let e = when(or(col("x").eq(lit(5)), col("x").is_null()), col("x"))
1140 .otherwise(lit(0))?;
1141 assert_nullable(&e, &nullable_schema);
1142 assert_not_nullable(&e, ¬_nullable_schema);
1143
1144 let e = when(col("x").is_true(), col("x")).otherwise(lit(0))?;
1146 assert_not_nullable(&e, &nullable_schema);
1147 assert_not_nullable(&e, ¬_nullable_schema);
1148
1149 let e = when(col("x").is_not_true(), col("x")).otherwise(lit(0))?;
1151 assert_nullable(&e, &nullable_schema);
1152 assert_not_nullable(&e, ¬_nullable_schema);
1153
1154 let e = when(col("x").is_false(), col("x")).otherwise(lit(0))?;
1156 assert_not_nullable(&e, &nullable_schema);
1157 assert_not_nullable(&e, ¬_nullable_schema);
1158
1159 let e = when(col("x").is_not_false(), col("x")).otherwise(lit(0))?;
1161 assert_nullable(&e, &nullable_schema);
1162 assert_not_nullable(&e, ¬_nullable_schema);
1163
1164 let e = when(col("x").is_unknown(), col("x")).otherwise(lit(0))?;
1166 assert_nullable(&e, &nullable_schema);
1167 assert_not_nullable(&e, ¬_nullable_schema);
1168
1169 let e = when(col("x").is_not_unknown(), col("x")).otherwise(lit(0))?;
1171 assert_not_nullable(&e, &nullable_schema);
1172 assert_not_nullable(&e, ¬_nullable_schema);
1173
1174 let e = when(col("x").like(lit("x")), col("x")).otherwise(lit(0))?;
1176 assert_not_nullable(&e, &nullable_schema);
1177 assert_not_nullable(&e, ¬_nullable_schema);
1178
1179 let e = when(lit(0), col("x")).otherwise(lit(0))?;
1181 assert_not_nullable(&e, &nullable_schema);
1182 assert_not_nullable(&e, ¬_nullable_schema);
1183
1184 let e = when(lit(1), col("x")).otherwise(lit(0))?;
1186 assert_nullable(&e, &nullable_schema);
1187 assert_not_nullable(&e, ¬_nullable_schema);
1188
1189 Ok(())
1190 }
1191
1192 #[test]
1193 fn test_inlist_nullability() {
1194 let get_schema = |nullable| {
1195 MockExprSchema::new()
1196 .with_data_type(DataType::Int32)
1197 .with_nullable(nullable)
1198 };
1199
1200 let expr = col("foo").in_list(vec![lit(1); 5], false);
1201 assert!(!expr.nullable(&get_schema(false)).unwrap());
1202 assert!(expr.nullable(&get_schema(true)).unwrap());
1203 assert!(
1205 expr.nullable(&get_schema(false).with_error_on_nullable(true))
1206 .is_err()
1207 );
1208
1209 let null = lit(ScalarValue::Int32(None));
1210 let expr = col("foo").in_list(vec![null, lit(1)], false);
1211 assert!(expr.nullable(&get_schema(false)).unwrap());
1212
1213 let expr = col("foo").in_list(vec![lit(1); 6], false);
1215 assert!(expr.nullable(&get_schema(false)).unwrap());
1216 }
1217
1218 #[test]
1219 fn test_like_nullability() {
1220 let get_schema = |nullable| {
1221 MockExprSchema::new()
1222 .with_data_type(DataType::Utf8)
1223 .with_nullable(nullable)
1224 };
1225
1226 let expr = col("foo").like(lit("bar"));
1227 assert!(!expr.nullable(&get_schema(false)).unwrap());
1228 assert!(expr.nullable(&get_schema(true)).unwrap());
1229
1230 let expr = col("foo").like(lit(ScalarValue::Utf8(None)));
1231 assert!(expr.nullable(&get_schema(false)).unwrap());
1232 }
1233
1234 #[test]
1235 fn expr_schema_data_type() {
1236 let expr = col("foo");
1237 assert_eq!(
1238 DataType::Utf8,
1239 expr.get_type(&MockExprSchema::new().with_data_type(DataType::Utf8))
1240 .unwrap()
1241 );
1242 }
1243
1244 #[test]
1245 fn test_expr_metadata() {
1246 let mut meta = HashMap::new();
1247 meta.insert("bar".to_string(), "buzz".to_string());
1248 let meta = FieldMetadata::from(meta);
1249 let expr = col("foo");
1250 let schema = MockExprSchema::new()
1251 .with_data_type(DataType::Int32)
1252 .with_metadata(meta.clone());
1253
1254 assert_eq!(meta, expr.metadata(&schema).unwrap());
1256 assert_eq!(meta, expr.clone().alias("bar").metadata(&schema).unwrap());
1257 assert_eq!(
1258 meta,
1259 expr.clone()
1260 .cast_to(&DataType::Int64, &schema)
1261 .unwrap()
1262 .metadata(&schema)
1263 .unwrap()
1264 );
1265
1266 let schema = DFSchema::from_unqualified_fields(
1267 vec![meta.add_to_field(Field::new("foo", DataType::Int32, true))].into(),
1268 HashMap::new(),
1269 )
1270 .unwrap();
1271
1272 assert_eq!(meta, expr.metadata(&schema).unwrap());
1274
1275 let outer_ref = out_ref_col_with_metadata(
1277 DataType::Int32,
1278 meta.to_hashmap(),
1279 Column::from_name("foo"),
1280 );
1281 assert_eq!(meta, outer_ref.metadata(&schema).unwrap());
1282 }
1283
1284 #[test]
1285 fn test_alias_metadata_is_preserved_in_field_metadata() {
1286 let schema = MockExprSchema::new().with_data_type(DataType::Int32);
1287 let alias_metadata = FieldMetadata::from(HashMap::from([(
1288 "some_key".to_string(),
1289 "some_value".to_string(),
1290 )]));
1291
1292 let Expr::Alias(alias) = col("foo").alias("alias") else {
1293 unreachable!();
1294 };
1295 let expr = Expr::Alias(alias.with_metadata(Some(alias_metadata.clone())));
1296
1297 let field = expr.to_field(&schema).unwrap().1;
1298 assert_eq!(
1299 field.metadata().get("some_key"),
1300 Some(&"some_value".to_string())
1301 );
1302 assert_eq!(expr.metadata(&schema).unwrap(), alias_metadata);
1303 }
1304
1305 #[test]
1306 fn test_nested_alias_resolves_child_field_once() -> Result<()> {
1307 #[derive(Debug)]
1308 struct CountingSchema {
1309 field: FieldRef,
1310 lookups: std::cell::Cell<usize>,
1311 }
1312
1313 impl ExprSchema for CountingSchema {
1314 fn nullable(&self, _col: &Column) -> Result<bool> {
1315 Ok(self.field.is_nullable())
1316 }
1317
1318 fn field_from_column(&self, _col: &Column) -> Result<&FieldRef> {
1319 self.lookups.set(self.lookups.get() + 1);
1320 Ok(&self.field)
1321 }
1322 }
1323
1324 let schema = CountingSchema {
1325 field: Arc::new(Field::new("value", DataType::Int32, false).with_metadata(
1326 HashMap::from([
1327 ("override".to_string(), "base".to_string()),
1328 ("keep".to_string(), "base".to_string()),
1329 ]),
1330 )),
1331 lookups: std::cell::Cell::new(0),
1332 };
1333 let mut expr = col("value");
1334 for index in 0..12 {
1335 let metadata = Some(FieldMetadata::from(HashMap::from([(
1336 "override".to_string(),
1337 index.to_string(),
1338 )])));
1339 expr = if index == 11 {
1340 expr.alias_qualified_with_metadata(
1341 Some("outer"),
1342 format!("alias_{index}"),
1343 metadata,
1344 )
1345 } else {
1346 expr.alias_with_metadata(format!("alias_{index}"), metadata)
1347 };
1348 }
1349
1350 let (relation, field) = expr.to_field(&schema)?;
1351 assert_eq!(schema.lookups.get(), 1);
1352 assert_eq!(relation, Some(TableReference::bare("outer")));
1353 assert_eq!(field.name(), "alias_11");
1354 assert_eq!(field.data_type(), &DataType::Int32);
1355 assert!(!field.is_nullable());
1356 assert_eq!(field.metadata().get("override"), Some(&"11".to_string()));
1357 assert_eq!(field.metadata().get("keep"), Some(&"base".to_string()));
1358 Ok(())
1359 }
1360
1361 #[test]
1362 fn test_expr_placeholder() {
1363 let schema = MockExprSchema::new();
1364
1365 let mut placeholder_meta = HashMap::new();
1366 placeholder_meta.insert("bar".to_string(), "buzz".to_string());
1367 let placeholder_meta = FieldMetadata::from(placeholder_meta);
1368
1369 let expr = Expr::Placeholder(Placeholder::new_with_field(
1370 "".to_string(),
1371 Some(
1372 Field::new("", DataType::Utf8, true)
1373 .with_metadata(placeholder_meta.to_hashmap())
1374 .into(),
1375 ),
1376 ));
1377
1378 let field = expr.to_field(&schema).unwrap().1;
1379 assert_eq!(
1380 (field.data_type(), field.is_nullable()),
1381 (&DataType::Utf8, true)
1382 );
1383 assert_eq!(placeholder_meta, expr.metadata(&schema).unwrap());
1384
1385 let expr_alias = expr.alias("a placeholder by any other name");
1386 let expr_alias_field = expr_alias.to_field(&schema).unwrap().1;
1387 assert_eq!(
1388 (expr_alias_field.data_type(), expr_alias_field.is_nullable()),
1389 (&DataType::Utf8, true)
1390 );
1391 assert_eq!(placeholder_meta, expr_alias.metadata(&schema).unwrap());
1392
1393 let expr = Expr::Placeholder(Placeholder::new_with_field(
1395 "".to_string(),
1396 Some(Field::new("", DataType::Utf8, false).into()),
1397 ));
1398 let expr_field = expr.to_field(&schema).unwrap().1;
1399 assert_eq!(
1400 (expr_field.data_type(), expr_field.is_nullable()),
1401 (&DataType::Utf8, false)
1402 );
1403
1404 let expr_alias = expr.alias("a placeholder by any other name");
1405 let expr_alias_field = expr_alias.to_field(&schema).unwrap().1;
1406 assert_eq!(
1407 (expr_alias_field.data_type(), expr_alias_field.is_nullable()),
1408 (&DataType::Utf8, false)
1409 );
1410 }
1411
1412 #[test]
1413 fn test_untyped_aliased_placeholder_in_empty_schema() {
1414 let schema = DFSchema::empty();
1417 let expr = Expr::Placeholder(Placeholder::new_with_field("$1".to_string(), None))
1418 .alias("a");
1419
1420 assert_eq!(expr.get_type(&schema).unwrap(), DataType::Null);
1421 assert_eq!(
1422 expr.to_field(&schema).unwrap().1.data_type(),
1423 &DataType::Null
1424 );
1425 }
1426
1427 #[derive(Debug)]
1428 struct MockExprSchema {
1429 field: FieldRef,
1430 error_on_nullable: bool,
1431 }
1432
1433 impl MockExprSchema {
1434 fn new() -> Self {
1435 Self {
1436 field: Arc::new(Field::new("mock_field", DataType::Null, false)),
1437 error_on_nullable: false,
1438 }
1439 }
1440
1441 fn with_nullable(mut self, nullable: bool) -> Self {
1442 Arc::make_mut(&mut self.field).set_nullable(nullable);
1443 self
1444 }
1445
1446 fn with_data_type(mut self, data_type: DataType) -> Self {
1447 Arc::make_mut(&mut self.field).set_data_type(data_type);
1448 self
1449 }
1450
1451 fn with_error_on_nullable(mut self, error_on_nullable: bool) -> Self {
1452 self.error_on_nullable = error_on_nullable;
1453 self
1454 }
1455
1456 fn with_metadata(mut self, metadata: FieldMetadata) -> Self {
1457 self.field =
1458 Arc::new(metadata.add_to_field(Arc::unwrap_or_clone(self.field)));
1459 self
1460 }
1461 }
1462
1463 impl ExprSchema for MockExprSchema {
1464 fn nullable(&self, _col: &Column) -> Result<bool> {
1465 assert_or_internal_err!(!self.error_on_nullable, "nullable error");
1466 Ok(self.field.is_nullable())
1467 }
1468
1469 fn field_from_column(&self, _col: &Column) -> Result<&FieldRef> {
1470 Ok(&self.field)
1471 }
1472 }
1473
1474 fn scan_t(a_nullable: bool) -> LogicalPlanBuilder {
1476 let schema = Schema::new(vec![Field::new("a", DataType::Int32, a_nullable)]);
1477 let source = Arc::new(LogicalTableSource::new(Arc::new(schema)));
1478 LogicalPlanBuilder::scan("t", source, None).unwrap()
1479 }
1480
1481 #[test]
1482 fn in_subquery_nullability() {
1483 let cases = [
1487 (false, false, false),
1488 (false, true, true),
1489 (true, false, true),
1490 (true, true, true),
1491 ];
1492
1493 for (x_nullable, a_nullable, expected) in cases {
1494 let subquery = scan_t(a_nullable)
1495 .project(vec![col("a")])
1496 .unwrap()
1497 .build()
1498 .unwrap();
1499 let expr = in_subquery(col("x"), Arc::new(subquery));
1500 let schema = MockExprSchema::new().with_nullable(x_nullable);
1501
1502 assert_eq!(expr.nullable(&schema).unwrap(), expected);
1503 }
1504 }
1505
1506 #[test]
1507 fn in_subquery_nullability_uses_subquery_output_schema() {
1508 let subquery = scan_t(true)
1511 .project(vec![col("a")])
1512 .unwrap()
1513 .distinct()
1514 .unwrap()
1515 .build()
1516 .unwrap();
1517 let expr = in_subquery(col("x"), Arc::new(subquery));
1518 assert!(expr.nullable(&MockExprSchema::new()).unwrap());
1519
1520 let subquery = scan_t(false)
1524 .project(vec![col("a") + lit(1)])
1525 .unwrap()
1526 .build()
1527 .unwrap();
1528 let expr = in_subquery(col("x"), Arc::new(subquery));
1529 assert!(!expr.nullable(&MockExprSchema::new()).unwrap());
1530 }
1531
1532 #[test]
1533 fn in_subquery_nullability_errors_for_no_subquery_columns() {
1534 let subquery = LogicalPlanBuilder::empty(false).build().unwrap();
1535 let expr = in_subquery(col("x"), Arc::new(subquery));
1536
1537 let err = expr.nullable(&MockExprSchema::new()).unwrap_err();
1538 assert_eq!(
1539 err.strip_backtrace(),
1540 "Error during planning: subquery must return exactly one column of data to compare against"
1541 );
1542 }
1543
1544 #[test]
1545 fn scalar_subquery_nullability_accounts_for_min_rows() {
1546 let possibly_empty = LogicalPlanBuilder::empty(false)
1547 .project(vec![lit(1)])
1548 .unwrap()
1549 .build()
1550 .unwrap();
1551 assert!(!possibly_empty.schema().field(0).is_nullable());
1552
1553 let expr = scalar_subquery(Arc::new(possibly_empty));
1554 assert!(expr.nullable(&MockExprSchema::new()).unwrap());
1555
1556 let field = expr.to_field(&MockExprSchema::new()).unwrap().1;
1557 assert_eq!(field.data_type(), &DataType::Int32);
1558 assert!(field.is_nullable());
1559
1560 let always_one = LogicalPlanBuilder::empty(false)
1561 .aggregate(Vec::<Expr>::new(), vec![count(lit(1))])
1562 .unwrap()
1563 .build()
1564 .unwrap();
1565 assert!(!always_one.schema().field(0).is_nullable());
1566
1567 let expr = scalar_subquery(Arc::new(always_one));
1568 assert!(!expr.nullable(&MockExprSchema::new()).unwrap());
1569 assert!(
1570 !expr
1571 .to_field(&MockExprSchema::new())
1572 .unwrap()
1573 .1
1574 .is_nullable()
1575 );
1576 }
1577
1578 #[test]
1579 fn test_scalar_variable() {
1580 let mut meta = HashMap::new();
1581 meta.insert("bar".to_string(), "buzz".to_string());
1582 let meta = FieldMetadata::from(meta);
1583
1584 let field = Field::new("foo", DataType::Int32, true);
1585 let field = meta.add_to_field(field);
1586 let field = Arc::new(field);
1587
1588 let expr = Expr::ScalarVariable(field, vec!["foo".to_string()]);
1589
1590 let schema = MockExprSchema::new();
1591
1592 assert_eq!(meta, expr.metadata(&schema).unwrap());
1593 }
1594
1595 #[test]
1596 fn test_cast_and_try_cast_extension_type_metadata() {
1597 use crate::expr::{Cast, TryCast};
1598 use arrow_schema::extension::{
1599 EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY,
1600 };
1601
1602 fn make_cast_expr(
1604 expr: Expr,
1605 target_field: FieldRef,
1606 use_try_cast: bool,
1607 ) -> Expr {
1608 if use_try_cast {
1609 Expr::TryCast(TryCast {
1610 expr: Box::new(expr),
1611 field: target_field,
1612 })
1613 } else {
1614 Expr::Cast(Cast {
1615 expr: Box::new(expr),
1616 field: target_field,
1617 })
1618 }
1619 }
1620
1621 for use_try_cast in [false, true] {
1623 let cast_name = if use_try_cast { "TryCast" } else { "Cast" };
1624
1625 let mut source_meta = HashMap::new();
1627 source_meta.insert(
1628 EXTENSION_TYPE_NAME_KEY.to_string(),
1629 "arrow.uuid".to_string(),
1630 );
1631 source_meta.insert("custom_key".to_string(), "custom_value".to_string());
1632
1633 let source_field = Field::new("foo", DataType::FixedSizeBinary(16), false)
1634 .with_metadata(source_meta);
1635
1636 let schema = MockExprSchema::new()
1637 .with_data_type(DataType::FixedSizeBinary(16))
1638 .with_metadata(FieldMetadata::from(source_field.metadata().clone()));
1639
1640 let cast_expr = make_cast_expr(
1643 col("foo"),
1644 Arc::new(Field::new("", DataType::Utf8, true)),
1645 use_try_cast,
1646 );
1647
1648 let (_, result_field) = cast_expr.to_field(&schema).unwrap();
1649 assert!(
1650 result_field
1651 .metadata()
1652 .get(EXTENSION_TYPE_NAME_KEY)
1653 .is_none(),
1654 "{cast_name}: Extension type name should be stripped when target has no extension metadata"
1655 );
1656 assert_eq!(
1657 result_field.metadata().get("custom_key"),
1658 Some(&"custom_value".to_string()),
1659 "{cast_name}: Non-extension metadata should be preserved"
1660 );
1661 if use_try_cast {
1662 assert!(
1663 result_field.is_nullable(),
1664 "TryCast result should be nullable"
1665 );
1666 }
1667
1668 let mut target_meta = HashMap::new();
1670 target_meta.insert(
1671 EXTENSION_TYPE_NAME_KEY.to_string(),
1672 "arrow.json".to_string(),
1673 );
1674 target_meta.insert(EXTENSION_TYPE_METADATA_KEY.to_string(), "{}".to_string());
1675
1676 let target_field =
1677 Field::new("", DataType::Utf8, true).with_metadata(target_meta);
1678
1679 let cast_expr =
1680 make_cast_expr(col("foo"), Arc::new(target_field), use_try_cast);
1681
1682 let (_, result_field) = cast_expr.to_field(&schema).unwrap();
1683 assert_eq!(
1684 result_field.metadata().get(EXTENSION_TYPE_NAME_KEY),
1685 Some(&"arrow.json".to_string()),
1686 "{cast_name}: Extension type name should come from target field"
1687 );
1688 assert_eq!(
1689 result_field.metadata().get(EXTENSION_TYPE_METADATA_KEY),
1690 Some(&"{}".to_string()),
1691 "{cast_name}: Extension type metadata should come from target field"
1692 );
1693 assert!(
1694 result_field.metadata().get("custom_key").is_none(),
1695 "{cast_name}: Source metadata should NOT propagate when target has explicit metadata"
1696 );
1697 if use_try_cast {
1698 assert!(
1699 result_field.is_nullable(),
1700 "TryCast result should be nullable"
1701 );
1702 }
1703 }
1704 }
1705
1706 #[test]
1707 fn case_infers_all_result_types_without_casting() -> Result<()> {
1708 use crate::expr::Case;
1709 let schema = DFSchema::empty();
1710 let nested = Expr::Case(Case::new(
1711 None,
1712 vec![(Box::new(lit(false)), Box::new(lit(1_i64)))],
1713 Some(Box::new(lit(2.5))),
1714 ));
1715 for (then_values, else_value, expected) in [
1716 (vec![lit(1_i64)], Some(lit(2.5)), DataType::Float64),
1717 (vec![lit(1_i64), lit(2.5)], None, DataType::Float64),
1718 (vec![lit(2.5), lit(1_i64)], None, DataType::Float64),
1719 (vec![lit(2.5)], Some(lit(1_i64)), DataType::Float64),
1720 (vec![lit(3_i64)], Some(nested), DataType::Float64),
1721 (vec![lit(ScalarValue::Null)], None, DataType::Null),
1722 (vec![lit(true)], Some(lit("a")), DataType::Boolean),
1724 ] {
1725 let when_then = then_values
1726 .into_iter()
1727 .map(|value| (Box::new(lit(true)), Box::new(value)))
1728 .collect();
1729 let expr = Expr::Case(Case::new(None, when_then, else_value.map(Box::new)));
1730 assert_eq!(expr.get_type(&schema)?, expected);
1731 }
1732 Ok(())
1733 }
1734}