Skip to main content

datafusion_expr/
expr_schema.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use 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
34/// Trait to allow expr to typable with respect to a schema
35pub trait ExprSchemable {
36    /// Given a schema, return the type of the expr
37    ///
38    /// `CASE` expressions infer a common type from all `THEN` and `ELSE`
39    /// branches without inserting casts. Incompatible branches retain a
40    /// provisional type until analysis.
41    fn get_type(&self, schema: &dyn ExprSchema) -> Result<DataType>;
42
43    /// Given a schema, return the nullability of the expr
44    fn nullable(&self, input_schema: &dyn ExprSchema) -> Result<bool>;
45
46    /// Given a schema, return the expr's optional metadata
47    fn metadata(&self, schema: &dyn ExprSchema) -> Result<FieldMetadata>;
48
49    /// Convert to a field with respect to a schema
50    fn to_field(
51        &self,
52        input_schema: &dyn ExprSchema,
53    ) -> Result<(Option<TableReference>, Arc<Field>)>;
54
55    /// Cast to a type with respect to a schema
56    fn cast_to(self, cast_to_type: &DataType, schema: &dyn ExprSchema) -> Result<Expr>;
57
58    /// Given a schema, return the type and nullability of the expr
59    #[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
67/// Derives the output field for a cast expression from the source and target fields.
68///
69/// Metadata handling:
70/// - Type-only casts (i.e., target_field == DataType::SomeDataType.into_nullable_field())
71///   propagate non extension-type metadata from the source. This is for backward compatibility
72///   (casts have propagated source metadata for many if not all previous versions), recognizing
73///   that the return type of `<some extension type>::<some non extension type>` should have the
74///   return type of `<some non extension type>` (e.g., casting arrow.json to utf8).
75/// - All other casts preserve target metadata exactly. This ensures in particular that output
76///   metadata when casting to an extension type contains the extension information in the
77///   output field. Callers that wish to have some mix of source and target metadata can use
78///   Alias or construct an output field themselves (whose metadata will be used directly).
79///
80/// For `TryCast`, `force_nullable` is `true` since a failed cast returns NULL.
81fn cast_output_field(
82    source_field: &FieldRef,
83    target_field: &FieldRef,
84    force_nullable: bool,
85) -> Arc<Field> {
86    // Check if this is a "type-only" cast (target_field == DataType::X.into_nullable_field())
87    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        // Type-only cast: propagate source metadata, stripping extension type keys
93        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        // Explicit target field: use target metadata exactly
99        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    /// Returns the [arrow::datatypes::DataType] of the expression
135    /// based on [ExprSchema]
136    ///
137    /// Note: [`DFSchema`] implements [ExprSchema].
138    ///
139    /// [`DFSchema`]: datafusion_common::DFSchema
140    ///
141    /// # Examples
142    ///
143    /// Get the type of an expression that adds 2 columns. Adding an Int32
144    /// and Float32 results in Float32 type
145    ///
146    /// ```
147    /// # use arrow::datatypes::{DataType, Field};
148    /// # use datafusion_common::DFSchema;
149    /// # use datafusion_expr::{col, ExprSchemable};
150    /// # use std::collections::HashMap;
151    ///
152    /// fn main() {
153    ///     let expr = col("c1") + col("c2");
154    ///     let schema = DFSchema::from_unqualified_fields(
155    ///         vec![
156    ///             Field::new("c1", DataType::Int32, true),
157    ///             Field::new("c2", DataType::Float32, true),
158    ///         ]
159    ///         .into(),
160    ///         HashMap::new(),
161    ///     )
162    ///     .unwrap();
163    ///     assert_eq!("Float32", format!("{}", expr.get_type(&schema).unwrap()));
164    /// }
165    /// ```
166    ///
167    /// # Errors
168    ///
169    /// This function errors when it is not possible to compute its
170    /// [arrow::datatypes::DataType].  This happens when e.g. the
171    /// expression refers to a column that does not exist in the
172    /// schema, or when the expression is incorrectly typed
173    /// (e.g. `[utf8] + [bool]`).
174    #[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                // If the branches have no common type, keep the old provisional
196                // type. The analyzer reports the error.
197                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                // Unnest's output type is the inner type of the list
214                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                    // If the placeholder's type hasn't been specified, treat it as
265                    // null (unspecified placeholders generate an error during planning)
266                    Ok(DataType::Null)
267                }
268            }
269            #[expect(deprecated)]
270            Expr::Wildcard { .. } => Ok(DataType::Null),
271            Expr::GroupingSet(_) => {
272                // Grouping sets do not really have a type and do not appear in projections
273                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                // If the lambda variable's field hasn't been specified, treat it as
282                // null (unspecified lambda variables generate an error during planning)
283                None => Ok(DataType::Null),
284            },
285        }
286    }
287
288    /// Returns the nullability of the expression based on [ExprSchema].
289    ///
290    /// Note: [`DFSchema`] implements [ExprSchema].
291    ///
292    /// [`DFSchema`]: datafusion_common::DFSchema
293    ///
294    /// # Errors
295    ///
296    /// This function errors when it is not possible to compute its
297    /// nullability.  This happens when the expression refers to a
298    /// column that does not exist in the schema.
299    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                // Avoid inspecting too many expressions.
307                const MAX_INSPECT_LIMIT: usize = 6;
308                // Stop if a nullable expression is found or an error occurs.
309                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                    // If a nullable subexpression is found, the result may also be nullable.
320                    Some(_) => true,
321                    // If the list is too long, we assume it is nullable.
322                    None if list.len() + 1 > MAX_INSPECT_LIMIT => true,
323                    // All the subexpressions are non-nullable, so the result must be non-nullable.
324                    _ => 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                    // Branches with a then expression that is not nullable do not impact the
345                    // nullability of the case expression.
346                    if !is_nullable {
347                        return None;
348                    }
349
350                    // For case-with-expression assume all 'then' expressions are reachable
351                    if case.expr.is_some() {
352                        return Some(Ok(()));
353                    }
354
355                    // For branches with a nullable 'then' expression, try to determine
356                    // if the 'then' expression is ever reachable in the situation where
357                    // it would evaluate to null.
358                    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                        // If the derived 'when' expression can never evaluate to true, the
375                        // 'then' expression is not reachable when it would evaluate to NULL.
376                        // The most common pattern for this is `WHEN x IS NOT NULL THEN x`.
377                        None
378                    } else {
379                        // The branch might be taken
380                        Some(Ok(()))
381                    }
382                });
383
384                if let Some(nullable_then) = nullable_then {
385                    // There is at least one reachable nullable 'then' expression, so the case
386                    // expression itself is nullable.
387                    // Use `Result::map` to propagate the error from `nullable_then` if there is one.
388                    nullable_then.map(|_| true)
389                } else if let Some(e) = &case.else_expr {
390                    // There are no reachable nullable 'then' expressions, so all we still need to
391                    // check is the 'else' expression's nullability.
392                    e.nullable(input_schema)
393                } else {
394                    // CASE produces NULL if there is no `else` expr
395                    // (aka when none of the `when_then_exprs` match)
396                    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                // A multi-column `(a, b) IN (SELECT x, y ...)` is UNKNOWN when
417                // any element or subquery column is NULL. The tuple is a
418                // `struct` call, which itself is never NULL, so its elements
419                // and every subquery column count.
420                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                // Grouping sets do not really have the concept of nullable and do not appear
453                // in projections
454                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                // If the lambda variable's field hasn't been specified, treat it as
463                // null (unspecified lambda variables generate an error during planning)
464                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    /// Returns the datatype and nullability of the expression based on [ExprSchema].
475    ///
476    /// Note: [`DFSchema`] implements [ExprSchema].
477    ///
478    /// [`DFSchema`]: datafusion_common::DFSchema
479    ///
480    /// # Errors
481    ///
482    /// This function errors when it is not possible to compute its
483    /// datatype or nullability.
484    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    /// Returns a [arrow::datatypes::Field] compatible with this expression.
494    ///
495    /// This function converts an expression into a field with appropriate metadata
496    /// and nullability based on the expression type and context. It is the primary
497    /// mechanism for determining field-level schemas.
498    ///
499    /// # Field Property Resolution
500    ///
501    /// For each expression, the following properties are determined:
502    ///
503    /// ## Data Type Resolution
504    /// - **Column references**: Data type from input schema field
505    /// - **Literals**: Data type inferred from literal value
506    /// - **Aliases**: Data type inherited from the underlying expression (the aliased expression)
507    /// - **Binary expressions**: Result type from type coercion rules
508    /// - **Boolean expressions**: Always a boolean type
509    /// - **Cast expressions**: Target data type from cast operation
510    /// - **Function calls**: Return type based on function signature and argument types
511    ///
512    /// ## Nullability Determination
513    /// - **Column references**: Inherit nullability from input schema field
514    /// - **Literals**: Nullable only if literal value is NULL
515    /// - **Aliases**: Inherit nullability from the underlying expression (the aliased expression)
516    /// - **Binary expressions**: Nullable if either operand is nullable
517    /// - **Boolean expressions**: Always non-nullable (IS NULL, EXISTS, etc.)
518    /// - **Cast expressions**: determined by the input expression's nullability rules
519    /// - **Function calls**: Based on function nullability rules and input nullability
520    ///
521    /// ## Metadata Handling
522    /// - **Column references**: Preserve original field metadata from input schema
523    /// - **Literals**: Use explicitly provided metadata, otherwise empty
524    /// - **Aliases**: Merge underlying expr metadata with alias-specific metadata, preferring the alias metadata
525    /// - **List unnesting**: Preserve the element field metadata
526    /// - **Binary expressions**: field metadata is empty
527    /// - **Boolean expressions**: field metadata is empty
528    /// - **Cast expressions**: Type-only casts pass through source metadata (stripping extension
529    ///   type keys); casts with explicit target fields use target metadata exactly
530    /// - **Scalar functions**: Generate metadata via function's [`return_field_from_args`] method,
531    ///   with the default implementation returning empty field metadata
532    /// - **Aggregate functions**: Generate metadata via function's [`return_field`] method,
533    ///   with the default implementation returning empty field metadata
534    /// - **Window functions**: field metadata follows the function's return field
535    ///
536    /// ## Table Reference Scoping
537    /// - Establishes proper qualified field references when columns belong to specific tables
538    /// - Maintains table context for accurate field resolution in multi-table scenarios
539    ///
540    /// So for example, a projected expression `col(c1) + col(c2)` is
541    /// placed in an output field **named** col("c1 + c2")
542    ///
543    /// [`return_field_from_args`]: crate::ScalarUDF::return_field_from_args
544    /// [`return_field`]: crate::AggregateUDF::return_field
545    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            // _ => Ok((self.get_type(schema)?, self.nullable(schema)?)),
672            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                            // use the name of the lambda instead of just the body to help with debugging
730                            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            // todo avoid this rename / use the name above
766            field.renamed(&schema_name),
767        ))
768    }
769
770    /// Wraps this expression in a cast to a target [arrow::datatypes::DataType].
771    ///
772    /// # Errors
773    ///
774    /// This function errors when it is impossible to cast the
775    /// expression to the target [arrow::datatypes::DataType].
776    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        // TODO(kszucs): Most of the operations do not validate the type correctness
783        // like all of the binary expressions below. Perhaps Expr should track the
784        // type of the expression?
785
786        // Special handling for struct-to-struct casts with name-based field matching
787        let can_cast = match (&this_type, cast_to_type) {
788            (DataType::Struct(_), DataType::Struct(_)) => {
789                // Always allow struct-to-struct casts; field matching happens at runtime
790                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
808/// Verify that function is invoked with correct number and type of arguments as
809/// defined in `TypeSignature`.
810fn 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
835/// Returns the innermost [Expr] that is provably null if `expr` is null.
836fn 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
845/// Returns whether a scalar subquery may evaluate to NULL.
846///
847/// This is the case if the subquery's projected field is nullable, or if the
848/// subquery may return no rows: a scalar subquery that produces no rows
849/// evaluates to NULL regardless of the nullability of its projected field.
850fn scalar_subquery_nullable(subquery: &Subquery) -> bool {
851    subquery.subquery.schema().field(0).is_nullable() || subquery.subquery.min_rows() == 0
852}
853
854/// Cast subquery in InSubquery/ScalarSubquery to a given type.
855///
856/// 1. **Projection plan**: If the subquery is a projection (i.e. a SELECT statement with specific
857///    columns), it casts the first expression in the projection to the target type and creates a
858///    new projection with the casted expression.
859/// 2. **Non-projection plan**: If the subquery isn't a projection, it adds a projection to the plan
860///    with the casted first column.
861pub 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
865/// Cast the leading columns of a subquery to the given types, one per column,
866/// like [`cast_subquery`] does for its first column. The result keeps only
867/// the `cast_to_types.len()` leading columns.
868///
869/// Used by a multi-column `(a, b) IN (SELECT x, y ...)`, whose tuple elements
870/// are coerced column by column.
871pub 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        // CASE WHEN x IS NOT NULL THEN x ELSE 0
1088        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, &not_nullable_schema);
1091
1092        // CASE WHEN NOT x IS NULL THEN x ELSE 0
1093        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, &not_nullable_schema);
1096
1097        // CASE WHEN X = 5 THEN x ELSE 0
1098        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, &not_nullable_schema);
1101
1102        // CASE WHEN x IS NOT NULL AND x = 5 THEN x ELSE 0
1103        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, &not_nullable_schema);
1107
1108        // CASE WHEN x = 5 AND x IS NOT NULL THEN x ELSE 0
1109        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, &not_nullable_schema);
1113
1114        // CASE WHEN x IS NOT NULL OR x = 5 THEN x ELSE 0
1115        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, &not_nullable_schema);
1119
1120        // CASE WHEN x = 5 OR x IS NOT NULL THEN x ELSE 0
1121        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, &not_nullable_schema);
1125
1126        // CASE WHEN (x = 5 AND x IS NOT NULL) OR (x = bar AND x IS NOT NULL) THEN x ELSE 0
1127        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, &not_nullable_schema);
1137
1138        // CASE WHEN x = 5 OR x IS NULL THEN x ELSE 0
1139        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, &not_nullable_schema);
1143
1144        // CASE WHEN x IS TRUE THEN x ELSE 0
1145        let e = when(col("x").is_true(), col("x")).otherwise(lit(0))?;
1146        assert_not_nullable(&e, &nullable_schema);
1147        assert_not_nullable(&e, &not_nullable_schema);
1148
1149        // CASE WHEN x IS NOT TRUE THEN x ELSE 0
1150        let e = when(col("x").is_not_true(), col("x")).otherwise(lit(0))?;
1151        assert_nullable(&e, &nullable_schema);
1152        assert_not_nullable(&e, &not_nullable_schema);
1153
1154        // CASE WHEN x IS FALSE THEN x ELSE 0
1155        let e = when(col("x").is_false(), col("x")).otherwise(lit(0))?;
1156        assert_not_nullable(&e, &nullable_schema);
1157        assert_not_nullable(&e, &not_nullable_schema);
1158
1159        // CASE WHEN x IS NOT FALSE THEN x ELSE 0
1160        let e = when(col("x").is_not_false(), col("x")).otherwise(lit(0))?;
1161        assert_nullable(&e, &nullable_schema);
1162        assert_not_nullable(&e, &not_nullable_schema);
1163
1164        // CASE WHEN x IS UNKNOWN THEN x ELSE 0
1165        let e = when(col("x").is_unknown(), col("x")).otherwise(lit(0))?;
1166        assert_nullable(&e, &nullable_schema);
1167        assert_not_nullable(&e, &not_nullable_schema);
1168
1169        // CASE WHEN x IS NOT UNKNOWN THEN x ELSE 0
1170        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, &not_nullable_schema);
1173
1174        // CASE WHEN x LIKE 'x' THEN x ELSE 0
1175        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, &not_nullable_schema);
1178
1179        // CASE WHEN 0 THEN x ELSE 0
1180        let e = when(lit(0), col("x")).otherwise(lit(0))?;
1181        assert_not_nullable(&e, &nullable_schema);
1182        assert_not_nullable(&e, &not_nullable_schema);
1183
1184        // CASE WHEN 1 THEN x ELSE 0
1185        let e = when(lit(1), col("x")).otherwise(lit(0))?;
1186        assert_nullable(&e, &nullable_schema);
1187        assert_not_nullable(&e, &not_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        // Testing nullable() returns an error.
1204        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        // Testing on long list
1214        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        // col, alias, and cast should be metadata-preserving
1255        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        // verify to_field method populates metadata
1273        assert_eq!(meta, expr.metadata(&schema).unwrap());
1274
1275        // outer ref constructed by `out_ref_col_with_metadata` should be metadata-preserving
1276        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        // Non-nullable placeholder field should remain non-nullable
1394        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        // A UNION arm computes the type of `$1 AS a` against the input of the
1415        // projection, which does not have a column `a`.
1416        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    /// A scan of `t`, whose single column `a` has the given nullability.
1475    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        // `x IN (SELECT a FROM t)` evaluates to NULL when `x` is NULL, and when `x`
1484        // matches no row while `a` contains a NULL. So it is nullable exactly when
1485        // either the compared expression or the subquery's output column is.
1486        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        // `DISTINCT` carries no expressions of its own, but its output column is still
1509        // nullable, so the `IN` expression must be nullable too.
1510        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        // A computed projection's expressions reference `t.a`, which does not appear in
1521        // the subquery's output schema, so nullability must be read off that schema's
1522        // single column rather than by resolving the projection's expressions against it.
1523        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        // Helper to build either Cast or TryCast expression
1603        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        // Run the same test logic for both Cast and TryCast
1622        for use_try_cast in [false, true] {
1623            let cast_name = if use_try_cast { "TryCast" } else { "Cast" };
1624
1625            // Create a schema with a field that has extension type metadata
1626            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            // Test 1: Cast to a type without extension metadata strips extension metadata
1641            // but preserves non-extension metadata
1642            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            // Test 2: Cast to a field with explicit metadata uses target metadata exactly
1669            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            // Incompatible raw types retain a provisional type for the analyzer.
1723            (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}