Skip to main content

datafusion_optimizer/analyzer/
type_coercion.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
5//! Optimizer rule for type validation and coercion
6
7use arrow::compute::can_cast_types;
8use datafusion_expr::binary::BinaryTypeCoercer;
9use itertools::Itertools as _;
10use std::sync::{Arc, LazyLock};
11
12use crate::analyzer::AnalyzerRule;
13use crate::utils::{NamePreserver, merge_into_schema};
14
15use arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit};
16use arrow::temporal_conversions::SECONDS_IN_DAY;
17use datafusion_common::config::ConfigOptions;
18use datafusion_common::metadata::merge_metadata_for_union;
19use datafusion_common::tree_node::{
20    Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
21};
22use datafusion_common::{
23    Column, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue, TableReference,
24    exec_err, internal_datafusion_err, internal_err, not_impl_err, plan_datafusion_err,
25    plan_err,
26};
27use datafusion_expr::expr::{
28    self, AggregateFunctionParams, Alias, Between, BinaryExpr, Case, Exists,
29    HigherOrderFunction, InList, InSubquery, Like, ScalarFunction, SetComparison, Sort,
30    WindowFunction, in_subquery_tuple_values,
31};
32use datafusion_expr::expr_rewriter::coerce_plan_expr_for_schema;
33use datafusion_expr::expr_schema::{cast_subquery, cast_subquery_columns};
34use datafusion_expr::logical_plan::Subquery;
35use datafusion_expr::type_coercion::binary::{
36    comparison_coercion_with_session_timezone, like_coercion, regex_coercion,
37};
38use datafusion_expr::type_coercion::functions::{
39    UDFCoercionExt, fields_with_udf, value_fields_with_higher_order_udf_and_lambdas,
40};
41use datafusion_expr::type_coercion::other::{
42    coerce_union_type, get_coerce_type_for_case_expression,
43};
44use datafusion_expr::type_coercion::{
45    is_datetime, is_interval, is_signed_numeric, is_timestamp,
46};
47use datafusion_expr::utils::merge_schema;
48use datafusion_expr::{
49    AsOfJoin, AsOfMatch, Cast, DmlStatement, Expr, ExprSchemable, Join, Limit,
50    LogicalPlan, MaterializedCte, MaterializedCteId, MaterializedCtePlan,
51    MaterializedCteScan, Operator, Projection, Union, ValueOrLambda, WindowFrame,
52    WindowFrameBound, WindowFrameUnits, WriteOp, is_false, is_not_false, is_not_true,
53    is_not_unknown, is_true, is_unknown, lit, not,
54};
55
56/// Performs type coercion by determining the schema
57/// and performing the expression rewrites.
58#[derive(Default, Debug)]
59pub struct TypeCoercion {}
60
61impl TypeCoercion {
62    pub fn new() -> Self {
63        Self {}
64    }
65}
66
67/// Coerce output schema based upon optimizer config.
68fn coerce_output(plan: LogicalPlan, config: &ConfigOptions) -> Result<LogicalPlan> {
69    if !config.optimizer.expand_views_at_output {
70        return Ok(plan);
71    }
72
73    let outer_refs = plan.expressions();
74    if outer_refs.is_empty() {
75        return Ok(plan);
76    }
77
78    if let Some(dfschema) = transform_schema_to_nonview(plan.schema()) {
79        coerce_plan_expr_for_schema(plan, &dfschema?)
80    } else {
81        Ok(plan)
82    }
83}
84
85impl AnalyzerRule for TypeCoercion {
86    fn name(&self) -> &str {
87        "type_coercion"
88    }
89
90    fn analyze(&self, plan: LogicalPlan, config: &ConfigOptions) -> Result<LogicalPlan> {
91        // Record bare row-count parameter types before coercion makes them indistinguishable
92        // from explicit casts. A type inferred elsewhere takes precedence over the default.
93        let parameter_fields = plan.get_parameter_fields()?;
94        let plan = plan
95            .transform_up_with_subqueries(|plan| {
96                if !matches!(plan, LogicalPlan::Limit(_)) {
97                    return Ok(Transformed::no(plan));
98                }
99                plan.map_expressions(|expr| match expr {
100                    Expr::Placeholder(mut placeholder) if placeholder.field.is_none() => {
101                        placeholder.field =
102                            parameter_fields.get(&placeholder.id).cloned().flatten();
103                        Ok(Transformed::yes(Expr::Placeholder(placeholder)))
104                    }
105                    expr => Ok(Transformed::no(expr)),
106                })
107            })?
108            .data;
109
110        // recurse
111        let transformed_plan = coerce_plan_and_subqueries(plan, config)?;
112
113        // finish
114        coerce_output(transformed_plan, config)
115    }
116}
117
118/// Coerce each node of `plan` and of its subqueries, from the leaves up.
119fn coerce_plan_and_subqueries(
120    plan: LogicalPlan,
121    config: &ConfigOptions,
122) -> Result<LogicalPlan> {
123    static EMPTY_SCHEMA: LazyLock<DFSchema> = LazyLock::new(DFSchema::empty);
124
125    plan.transform_down_up_with_subqueries(
126        |plan| match plan {
127            // Coercion can change the types of the body, for example the type
128            // of a `NULL` column of a `UNION`. Coerce the body first, and give
129            // its new schema to the scans before the continuation is coerced.
130            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
131                let body =
132                    coerce_plan_and_subqueries(Arc::unwrap_or_clone(cte.cte), config)?;
133                let continuation = with_materialized_cte_scan_schema(
134                    Arc::unwrap_or_clone(cte.continuation),
135                    cte.id,
136                    body.schema(),
137                )?;
138                let continuation = coerce_plan_and_subqueries(continuation, config)?;
139                Ok(Transformed::new(
140                    LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
141                        MaterializedCte {
142                            cte: Arc::new(body),
143                            continuation: Arc::new(continuation),
144                            ..cte
145                        },
146                    )),
147                    true,
148                    TreeNodeRecursion::Jump,
149                ))
150            }
151            _ => Ok(Transformed::no(plan)),
152        },
153        |plan| {
154            analyze_internal(
155                &EMPTY_SCHEMA,
156                plan,
157                config.execution.time_zone.as_ref().map(|tz| tz.as_str()),
158            )
159        },
160    )
161    .map(|t| t.data)
162}
163
164/// Give the fields of `body_schema` to each scan of the materialized CTE `id`
165/// in `continuation`, also in subquery expressions. A scan keeps its
166/// qualifiers.
167fn with_materialized_cte_scan_schema(
168    continuation: LogicalPlan,
169    id: MaterializedCteId,
170    body_schema: &DFSchemaRef,
171) -> Result<LogicalPlan> {
172    continuation
173        .transform_down_with_subqueries(|node| match node {
174            // A nested occurrence of the same CTE owns the scans below it.
175            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref nested))
176                if nested.id == id =>
177            {
178                Ok(Transformed::new(node, false, TreeNodeRecursion::Jump))
179            }
180            LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan))
181                if scan.id == id && scan.schema.inner() != body_schema.inner() =>
182            {
183                let qualifiers = scan.schema.iter().map(|(q, _)| q.cloned()).collect();
184                let schema = DFSchema::from_field_specific_qualified_schema(
185                    qualifiers,
186                    body_schema.inner(),
187                )?
188                .with_functional_dependencies(
189                    body_schema.functional_dependencies().clone(),
190                )?;
191                Ok(Transformed::yes(LogicalPlan::MaterializedCte(
192                    MaterializedCtePlan::Scan(MaterializedCteScan {
193                        schema: Arc::new(schema),
194                        ..scan
195                    }),
196                )))
197            }
198            _ => Ok(Transformed::no(node)),
199        })
200        .map(|t| t.data)
201}
202
203/// use the external schema to handle the correlated subqueries case
204///
205/// Assumes that children have already been optimized
206fn analyze_internal(
207    external_schema: &DFSchema,
208    plan: LogicalPlan,
209    session_time_zone: Option<&str>,
210) -> Result<Transformed<LogicalPlan>> {
211    // get schema representing all available input fields. This is used for data type
212    // resolution only, so order does not matter here
213    let mut schema = merge_schema(&plan.inputs());
214
215    if let LogicalPlan::TableScan(ts) = &plan {
216        let source_schema = DFSchema::try_from_qualified_schema(
217            ts.table_name.clone(),
218            &ts.source.schema(),
219        )?;
220        schema.merge(&source_schema);
221    }
222
223    // MERGE expressions (ON / WHEN clauses) reference the target table, which
224    // is not one of `plan.inputs()`. Use the operation's visible qualifier
225    // when adding its target schema.
226    if let Some(merge_schema) = merge_into_schema(&plan)? {
227        schema = merge_schema;
228    }
229
230    // merge the outer schema for correlated subqueries
231    // like case:
232    // select t2.c2 from t1 where t1.c1 in (select t2.c1 from t2 where t2.c2=t1.c3)
233    schema.merge(external_schema);
234
235    // Coerce filter predicates to boolean (handles `WHERE NULL`)
236    let plan = if let LogicalPlan::Filter(mut filter) = plan {
237        filter.predicate = filter.predicate.cast_to(&DataType::Boolean, &schema)?;
238        LogicalPlan::Filter(filter)
239    } else {
240        plan
241    };
242
243    let mut expr_rewrite =
244        TypeCoercionRewriter::new(&schema).with_session_time_zone(session_time_zone);
245
246    let name_preserver = NamePreserver::new(&plan);
247    let mut coerce_expr = |expr: Expr| {
248        let original_name = name_preserver.save(&expr);
249
250        // A lambda variable carries the field recorded when the plan was built, which
251        // need not be the one its function derives from the arguments. Resolve them
252        // before coercing, so lambda bodies are coerced against the types they receive.
253        let expr = if expr.exists(|e| Ok(matches!(e, Expr::HigherOrderFunction(_))))? {
254            expr.resolve_lambda_variables(&schema)?.data
255        } else {
256            expr
257        };
258
259        expr.rewrite(&mut expr_rewrite)
260            .map(|transformed| transformed.update_data(|e| original_name.restore(e)))
261    };
262
263    // apply coercion rewrite all expressions in the plan individually
264    plan.map_expressions(|expr| {
265        // Preserve the names of grouping set members, not of the grouping set itself.
266        // An aliased grouping set is no longer recognized as a grouping set.
267        if let Expr::GroupingSet(_) = &expr {
268            expr.map_children(&mut coerce_expr)
269        } else {
270            coerce_expr(expr)
271        }
272    })?
273    // some plans need extra coercion after their expressions are coerced
274    .map_data(|plan| expr_rewrite.coerce_plan(plan))?
275    // recompute the schema after the expressions have been rewritten as the types may have changed
276    .map_data(|plan| plan.recompute_schema())
277}
278
279/// Rewrite expressions to apply type coercion.
280pub struct TypeCoercionRewriter<'a> {
281    pub(crate) schema: &'a DFSchema,
282    session_time_zone: Option<&'a str>,
283}
284
285impl<'a> TypeCoercionRewriter<'a> {
286    /// Create a new [`TypeCoercionRewriter`] with a provided schema
287    /// representing both the inputs and output of the [`LogicalPlan`] node.
288    pub fn new(schema: &'a DFSchema) -> Self {
289        Self {
290            schema,
291            session_time_zone: None,
292        }
293    }
294
295    pub(crate) fn with_session_time_zone(
296        mut self,
297        session_time_zone: Option<&'a str>,
298    ) -> Self {
299        self.session_time_zone = session_time_zone;
300        self
301    }
302
303    /// Coerce the [`LogicalPlan`].
304    ///
305    /// Refer to [`TypeCoercionRewriter::coerce_join`] and [`TypeCoercionRewriter::coerce_union`]
306    /// for type-coercion approach.
307    pub fn coerce_plan(&mut self, plan: LogicalPlan) -> Result<LogicalPlan> {
308        match plan {
309            LogicalPlan::Join(join) => self.coerce_join(join),
310            LogicalPlan::AsOfJoin(join) => self.coerce_asof_join(join),
311            LogicalPlan::Union(union) => Self::coerce_union(union),
312            LogicalPlan::Limit(limit) => Self::coerce_limit(limit),
313            LogicalPlan::Dml(dml) => self.coerce_dml(dml),
314            _ => Ok(plan),
315        }
316    }
317
318    fn coerce_dml(&self, mut dml: DmlStatement) -> Result<LogicalPlan> {
319        let WriteOp::MergeInto(merge_op) = &dml.op else {
320            return Ok(LogicalPlan::Dml(dml));
321        };
322
323        let target_schema = DFSchema::try_from_qualified_schema(
324            dml.table_name.clone(),
325            &dml.target.schema(),
326        )?;
327        let mut merge_op = (**merge_op).clone();
328        merge_op.on = self.coerce_predicate(merge_op.on, "MERGE ON condition")?;
329        for clause in &mut merge_op.clauses {
330            clause.predicate = clause
331                .predicate
332                .take()
333                .map(|expr| self.coerce_predicate(expr, "MERGE WHEN condition"))
334                .transpose()?;
335
336            match &mut clause.action {
337                datafusion_expr::dml::MergeIntoAction::Update(assignments) => {
338                    for (column, value) in assignments {
339                        let field = target_schema.field_with_unqualified_name(column)?;
340                        *value = value.clone().cast_to(field.data_type(), self.schema)?;
341                    }
342                }
343                datafusion_expr::dml::MergeIntoAction::Insert { columns, values } => {
344                    if columns.is_empty() {
345                        for (value, field) in
346                            values.iter_mut().zip(target_schema.fields())
347                        {
348                            *value =
349                                value.clone().cast_to(field.data_type(), self.schema)?;
350                        }
351                    } else {
352                        for (column, value) in columns.iter().zip(values) {
353                            let field =
354                                target_schema.field_with_unqualified_name(column)?;
355                            *value =
356                                value.clone().cast_to(field.data_type(), self.schema)?;
357                        }
358                    }
359                }
360                datafusion_expr::dml::MergeIntoAction::Delete => {}
361            }
362        }
363        dml.op = WriteOp::MergeInto(Box::new(merge_op));
364        Ok(LogicalPlan::Dml(dml))
365    }
366
367    /// Coerce join equality expressions and join filter
368    ///
369    /// Joins must be treated specially as their equality expressions are stored
370    /// as a parallel list of left and right expressions, rather than a single
371    /// equality expression
372    ///
373    /// For example, on_exprs like `t1.a = t2.b AND t1.x = t2.y` will be stored
374    /// as a list of `(t1.a, t2.b), (t1.x, t2.y)`
375    pub fn coerce_join(&mut self, mut join: Join) -> Result<LogicalPlan> {
376        join.on = join
377            .on
378            .into_iter()
379            .map(|(lhs, rhs)| {
380                // coerce the arguments as though they were a single binary equality
381                // expression
382                let left_schema = join.left.schema();
383                let right_schema = join.right.schema();
384                let (lhs, rhs) = self.coerce_binary_op(
385                    lhs,
386                    left_schema,
387                    Operator::Eq,
388                    rhs,
389                    right_schema,
390                )?;
391                Ok((lhs, rhs))
392            })
393            .collect::<Result<Vec<_>>>()?;
394
395        // Join filter must be boolean
396        join.filter = join
397            .filter
398            .map(|expr| self.coerce_predicate(expr, "Join condition"))
399            .transpose()?;
400
401        Ok(LogicalPlan::Join(join))
402    }
403
404    /// Coerce ASOF equality and ordered match expressions across input schemas.
405    pub fn coerce_asof_join(&mut self, mut join: AsOfJoin) -> Result<LogicalPlan> {
406        join.on = join
407            .on
408            .into_iter()
409            .map(|(left, right)| {
410                self.coerce_binary_op(
411                    left,
412                    join.left.schema(),
413                    Operator::Eq,
414                    right,
415                    join.right.schema(),
416                )
417            })
418            .collect::<Result<_>>()?;
419        let (left, right) = self.coerce_binary_op(
420            join.match_condition.left,
421            join.left.schema(),
422            join.match_condition.op,
423            join.match_condition.right,
424            join.right.schema(),
425        )?;
426        join.match_condition = Box::new(AsOfMatch {
427            left,
428            op: join.match_condition.op,
429            right,
430        });
431        Ok(LogicalPlan::AsOfJoin(join))
432    }
433
434    /// Coerce the union’s inputs to a common schema compatible with all inputs.
435    /// This occurs after wildcard expansion and the coercion of the input expressions.
436    pub fn coerce_union(union_plan: Union) -> Result<LogicalPlan> {
437        let union_schema = Arc::new(coerce_union_schema_with_schema(
438            &union_plan.inputs,
439            &union_plan.schema,
440        )?);
441        let new_inputs = union_plan
442            .inputs
443            .into_iter()
444            .map(|p| {
445                let plan =
446                    coerce_plan_expr_for_schema(Arc::unwrap_or_clone(p), &union_schema)?;
447                match plan {
448                    LogicalPlan::Projection(Projection { expr, input, .. }) => {
449                        Ok(Arc::new(project_with_column_index(
450                            expr,
451                            input,
452                            Arc::clone(&union_schema),
453                        )?))
454                    }
455                    other_plan => Ok(Arc::new(other_plan)),
456                }
457            })
458            .collect::<Result<Vec<_>>>()?;
459        Ok(LogicalPlan::Union(Union {
460            inputs: new_inputs,
461            schema: union_schema,
462        }))
463    }
464
465    /// Coerce the fetch and skip expression to Int64 type.
466    fn coerce_limit(limit: Limit) -> Result<LogicalPlan> {
467        fn coerce_limit_expr(
468            expr: Expr,
469            schema: &DFSchema,
470            expr_name: &str,
471        ) -> Result<Expr> {
472            let dt = expr.get_type(schema)?;
473            if dt.is_integer() || dt.is_null() {
474                expr.cast_to(&DataType::Int64, schema)
475            } else {
476                plan_err!("Expected {expr_name} to be an integer or null, but got {dt}")
477            }
478        }
479
480        let empty_schema = DFSchema::empty();
481        let new_fetch = limit
482            .fetch
483            .map(|expr| coerce_limit_expr(*expr, &empty_schema, "LIMIT"))
484            .transpose()?;
485        let new_skip = limit
486            .skip
487            .map(|expr| coerce_limit_expr(*expr, &empty_schema, "OFFSET"))
488            .transpose()?;
489        Ok(LogicalPlan::Limit(Limit {
490            input: limit.input,
491            fetch: new_fetch.map(Box::new),
492            skip: new_skip.map(Box::new),
493        }))
494    }
495
496    fn coerce_predicate(&self, expr: Expr, description: &str) -> Result<Expr> {
497        let expr_type = expr.get_type(self.schema)?;
498        match expr_type {
499            DataType::Boolean => Ok(expr),
500            DataType::Null => expr.cast_to(&DataType::Boolean, self.schema),
501            other => {
502                plan_err!("{description} must be boolean type, but got {other:?}")
503            }
504        }
505    }
506
507    fn coerce_binary_op(
508        &self,
509        left: Expr,
510        left_schema: &DFSchema,
511        op: Operator,
512        right: Expr,
513        right_schema: &DFSchema,
514    ) -> Result<(Expr, Expr)> {
515        let left_data_type = left.get_type(left_schema)?;
516        let right_data_type = right.get_type(right_schema)?;
517        let (left_type, right_type) =
518            BinaryTypeCoercer::new(&left_data_type, &op, &right_data_type)
519                .with_session_time_zone(self.session_time_zone)
520                .get_input_types()?;
521        let left_cast_ok = can_cast_types(&left_data_type, &left_type);
522        let right_cast_ok = can_cast_types(&right_data_type, &right_type);
523
524        // handle special cases for
525        // * Date +/- int => Date
526        // * Date + time => Timestamp
527        let left_expr = if !left_cast_ok {
528            Self::coerce_date_time_math_op(
529                left,
530                &op,
531                &left_data_type,
532                &left_type,
533                &right_type,
534            )?
535        } else {
536            left.cast_to(&left_type, left_schema)?
537        };
538
539        let right_expr = if !right_cast_ok {
540            Self::coerce_date_time_math_op(
541                right,
542                &op,
543                &right_data_type,
544                &right_type,
545                &left_type,
546            )?
547        } else {
548            right.cast_to(&right_type, right_schema)?
549        };
550
551        Ok((left_expr, right_expr))
552    }
553
554    fn coerce_date_time_math_op(
555        expr: Expr,
556        op: &Operator,
557        left_current_type: &DataType,
558        left_target_type: &DataType,
559        right_target_type: &DataType,
560    ) -> Result<Expr, DataFusionError> {
561        use DataType::*;
562
563        fn cast(expr: Expr, target_type: DataType) -> Expr {
564            Expr::Cast(Cast::new(Box::new(expr), target_type))
565        }
566
567        fn time_to_nanos(
568            expr: Expr,
569            expr_type: &DataType,
570        ) -> Result<Expr, DataFusionError> {
571            let expr = match expr_type {
572                Time32(TimeUnit::Second) => {
573                    cast(cast(expr, Int32), Int64)
574                        * lit(ScalarValue::Int64(Some(1_000_000_000)))
575                }
576                Time32(TimeUnit::Millisecond) => {
577                    cast(cast(expr, Int32), Int64)
578                        * lit(ScalarValue::Int64(Some(1_000_000)))
579                }
580                Time64(TimeUnit::Microsecond) => {
581                    cast(expr, Int64) * lit(ScalarValue::Int64(Some(1_000)))
582                }
583                Time64(TimeUnit::Nanosecond) => cast(expr, Int64),
584                t => return internal_err!("Unexpected time data type {t}"),
585            };
586
587            Ok(expr)
588        }
589
590        let e = match (
591            &op,
592            &left_current_type,
593            &left_target_type,
594            &right_target_type,
595        ) {
596            // int +/- date => date
597            (
598                Operator::Plus | Operator::Minus,
599                Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64,
600                Interval(IntervalUnit::MonthDayNano),
601                Date32 | Date64,
602            ) => {
603                // cast to i64 first
604                let expr = match *left_current_type {
605                    Int64 => expr,
606                    _ => cast(expr, Int64),
607                };
608                // next, multiply by 86400 to get seconds
609                let expr = expr * lit(ScalarValue::from(SECONDS_IN_DAY));
610                // cast to duration
611                let expr = cast(expr, Duration(TimeUnit::Second));
612                // finally cast to interval
613                cast(expr, Interval(IntervalUnit::MonthDayNano))
614            }
615            // These might seem to be a bit convoluted, however for arrow to do date + time arithmetic
616            // date must be cast to Timestamp(Nanosecond) and time cast to Duration(Nanosecond)
617            // (they must be the same timeunit).
618            //
619            // For Time32/64 we first need to cast to an Int64, convert that to nanoseconds based
620            // on the time unit, then cast that to duration.
621            //
622            // Time + date -> timestamp or
623            (
624                Operator::Plus | Operator::Minus,
625                Time32(_) | Time64(_),
626                Duration(TimeUnit::Nanosecond),
627                Timestamp(TimeUnit::Nanosecond, None),
628            ) => {
629                // cast to int64, convert to nanoseconds
630                let expr = time_to_nanos(expr, left_current_type)?;
631                // cast to duration
632                cast(expr, Duration(TimeUnit::Nanosecond))
633            }
634            // Similar to above, for arrow to do time - time we need to convert to an interval.
635            // To do that we first need to cast to an Int64, convert that to nanoseconds based
636            // on the time unit, then cast that to duration, then finally cast to an interval.
637            //
638            // Time - time -> timestamp
639            (
640                Operator::Plus | Operator::Minus,
641                Time32(_) | Time64(_),
642                Interval(IntervalUnit::MonthDayNano),
643                Interval(IntervalUnit::MonthDayNano),
644            ) => {
645                // cast to int64, convert to nanoseconds
646                let expr = time_to_nanos(expr, left_current_type)?;
647                // cast to duration
648                let expr = cast(expr, Duration(TimeUnit::Nanosecond));
649                // finally cast to interval
650                cast(expr, Interval(IntervalUnit::MonthDayNano))
651            }
652            _ => {
653                return plan_err!(
654                    "Cannot automatically convert {left_current_type} to {left_target_type}"
655                );
656            }
657        };
658
659        Ok(e)
660    }
661
662    /// Coerce the value and pattern expressions of a string pattern matching
663    /// expression (`LIKE`, `ILIKE` or `SIMILAR TO`) to a common type using
664    /// the provided coercion rules. `LIKE` can preserve a dictionary-encoded
665    /// value expression, while regex array kernels require both operands to
666    /// have the same physical string type.
667    fn coerce_like_operands(
668        &self,
669        expr: Expr,
670        pattern: Expr,
671        coercion: fn(&DataType, &DataType) -> Option<DataType>,
672        op_name: &str,
673        preserve_utf8_dictionary: bool,
674    ) -> Result<(Box<Expr>, Box<Expr>)> {
675        let left_type = expr.get_type(self.schema)?;
676        let right_type = pattern.get_type(self.schema)?;
677        let coerced_type = coercion(&left_type, &right_type).ok_or_else(|| {
678            plan_datafusion_err!(
679                "There isn't a common type to coerce {left_type} and {right_type} in {op_name} expression"
680            )
681        })?;
682        let expr = match left_type {
683            DataType::Dictionary(_, inner)
684                if preserve_utf8_dictionary && *inner == DataType::Utf8 =>
685            {
686                Box::new(expr)
687            }
688            _ => Box::new(expr.cast_to(&coerced_type, self.schema)?),
689        };
690        let pattern = Box::new(pattern.cast_to(&coerced_type, self.schema)?);
691        Ok((expr, pattern))
692    }
693}
694
695impl TreeNodeRewriter for TypeCoercionRewriter<'_> {
696    type Node = Expr;
697
698    fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
699        match expr {
700            Expr::Unnest(_) => not_impl_err!(
701                "Unnest should be rewritten to LogicalPlan::Unnest before type coercion"
702            ),
703            Expr::ScalarSubquery(Subquery {
704                subquery,
705                outer_ref_columns,
706                spans,
707            }) => {
708                let new_plan = analyze_internal(
709                    self.schema,
710                    Arc::unwrap_or_clone(subquery),
711                    self.session_time_zone,
712                )?
713                .data;
714                Ok(Transformed::yes(Expr::ScalarSubquery(Subquery {
715                    subquery: Arc::new(new_plan),
716                    outer_ref_columns,
717                    spans,
718                })))
719            }
720            Expr::Exists(Exists { subquery, negated }) => {
721                let new_plan = analyze_internal(
722                    self.schema,
723                    Arc::unwrap_or_clone(subquery.subquery),
724                    self.session_time_zone,
725                )?
726                .data;
727                Ok(Transformed::yes(Expr::Exists(Exists {
728                    subquery: Subquery {
729                        subquery: Arc::new(new_plan),
730                        outer_ref_columns: subquery.outer_ref_columns,
731                        spans: subquery.spans,
732                    },
733                    negated,
734                })))
735            }
736            Expr::InSubquery(InSubquery {
737                expr,
738                subquery,
739                negated,
740            }) => {
741                let new_plan = analyze_internal(
742                    self.schema,
743                    Arc::unwrap_or_clone(subquery.subquery),
744                    self.session_time_zone,
745                )?
746                .data;
747                let new_subquery = Subquery {
748                    subquery: Arc::new(new_plan),
749                    outer_ref_columns: subquery.outer_ref_columns,
750                    spans: subquery.spans,
751                };
752                let is_tuple =
753                    in_subquery_tuple_values(&expr, &new_subquery.subquery)?.is_some();
754                match *expr {
755                    // Multi-column `(a, b) IN (SELECT x, y ...)`: the tuple is
756                    // planned as a `struct` call whose arguments are compared
757                    // pairwise with the subquery columns, so coerce each pair.
758                    Expr::ScalarFunction(func) if is_tuple => {
759                        let (expr, subquery) = coerce_multi_column_in_subquery(
760                            func,
761                            new_subquery,
762                            self.schema,
763                            self.session_time_zone,
764                        )?;
765                        Ok(Transformed::yes(Expr::InSubquery(InSubquery::new(
766                            Box::new(expr),
767                            subquery,
768                            negated,
769                        ))))
770                    }
771                    expr => {
772                        let expr_type = expr.get_type(self.schema)?;
773                        let subquery_type =
774                            new_subquery.subquery.schema().field(0).data_type();
775                        let common_type = comparison_coercion_with_session_timezone(
776                            &expr_type,
777                            subquery_type,
778                            self.session_time_zone,
779                        )
780                        .ok_or(plan_datafusion_err!(
781                            "expr type {expr_type} can't cast to {subquery_type} in InSubquery"
782                        ))?;
783                        Ok(Transformed::yes(Expr::InSubquery(InSubquery::new(
784                            Box::new(expr.cast_to(&common_type, self.schema)?),
785                            cast_subquery(new_subquery, &common_type)?,
786                            negated,
787                        ))))
788                    }
789                }
790            }
791            Expr::SetComparison(SetComparison {
792                expr,
793                subquery,
794                op,
795                quantifier,
796            }) => {
797                let new_plan = analyze_internal(
798                    self.schema,
799                    Arc::unwrap_or_clone(subquery.subquery),
800                    self.session_time_zone,
801                )?
802                .data;
803                let expr_type = expr.get_type(self.schema)?;
804                let subquery_type = new_plan.schema().field(0).data_type();
805                if (expr_type.is_numeric() && subquery_type.is_string())
806                    || (subquery_type.is_numeric() && expr_type.is_string())
807                {
808                    return plan_err!(
809                        "expr type {expr_type} can't cast to {subquery_type} in SetComparison"
810                    );
811                }
812                let common_type = comparison_coercion_with_session_timezone(
813                    &expr_type,
814                    subquery_type,
815                    self.session_time_zone,
816                )
817                .ok_or(plan_datafusion_err!(
818                    "expr type {expr_type} can't cast to {subquery_type} in SetComparison"
819                ))?;
820                let new_subquery = Subquery {
821                    subquery: Arc::new(new_plan),
822                    outer_ref_columns: subquery.outer_ref_columns,
823                    spans: subquery.spans,
824                };
825                Ok(Transformed::yes(Expr::SetComparison(SetComparison::new(
826                    Box::new(expr.cast_to(&common_type, self.schema)?),
827                    cast_subquery(new_subquery, &common_type)?,
828                    op,
829                    quantifier,
830                ))))
831            }
832            Expr::Not(expr) => Ok(Transformed::yes(not(get_casted_expr_for_bool_op(
833                *expr,
834                self.schema,
835            )?))),
836            Expr::IsTrue(expr) => Ok(Transformed::yes(is_true(
837                get_casted_expr_for_bool_op(*expr, self.schema)?,
838            ))),
839            Expr::IsNotTrue(expr) => Ok(Transformed::yes(is_not_true(
840                get_casted_expr_for_bool_op(*expr, self.schema)?,
841            ))),
842            Expr::IsFalse(expr) => Ok(Transformed::yes(is_false(
843                get_casted_expr_for_bool_op(*expr, self.schema)?,
844            ))),
845            Expr::IsNotFalse(expr) => Ok(Transformed::yes(is_not_false(
846                get_casted_expr_for_bool_op(*expr, self.schema)?,
847            ))),
848            Expr::IsUnknown(expr) => Ok(Transformed::yes(is_unknown(
849                get_casted_expr_for_bool_op(*expr, self.schema)?,
850            ))),
851            Expr::IsNotUnknown(expr) => Ok(Transformed::yes(is_not_unknown(
852                get_casted_expr_for_bool_op(*expr, self.schema)?,
853            ))),
854            Expr::Negative(expr) => {
855                let data_type = expr.get_type(self.schema)?;
856                if data_type.is_null()
857                    || is_signed_numeric(&data_type)
858                    || is_interval(&data_type)
859                    || is_timestamp(&data_type)
860                {
861                    Ok(Transformed::no(Expr::Negative(expr)))
862                } else {
863                    plan_err!(
864                        "Negation only supports numeric, interval and timestamp types"
865                    )
866                }
867            }
868            Expr::Like(Like {
869                negated,
870                expr,
871                pattern,
872                escape_char,
873                case_insensitive,
874            }) => {
875                let op_name = if case_insensitive { "ILIKE" } else { "LIKE" };
876                let (expr, pattern) = self.coerce_like_operands(
877                    *expr,
878                    *pattern,
879                    like_coercion,
880                    op_name,
881                    true,
882                )?;
883                Ok(Transformed::yes(Expr::Like(Like::new(
884                    negated,
885                    expr,
886                    pattern,
887                    escape_char,
888                    case_insensitive,
889                ))))
890            }
891            Expr::SimilarTo(Like {
892                negated,
893                expr,
894                pattern,
895                escape_char,
896                case_insensitive,
897            }) => {
898                // `SIMILAR TO` is planned as a regex operator, so its operands
899                // must be coerced to a common string type using the same
900                // coercion rules as the physical regex operators. Otherwise
901                // mismatched operand types panic during execution.
902                let (expr, pattern) = self.coerce_like_operands(
903                    *expr,
904                    *pattern,
905                    regex_coercion,
906                    "SIMILAR TO",
907                    false,
908                )?;
909                Ok(Transformed::yes(Expr::SimilarTo(Like::new(
910                    negated,
911                    expr,
912                    pattern,
913                    escape_char,
914                    case_insensitive,
915                ))))
916            }
917            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
918                let (left, right) =
919                    self.coerce_binary_op(*left, self.schema, op, *right, self.schema)?;
920                Ok(Transformed::yes(Expr::BinaryExpr(BinaryExpr::new(
921                    Box::new(left),
922                    op,
923                    Box::new(right),
924                ))))
925            }
926            Expr::Between(Between {
927                expr,
928                negated,
929                low,
930                high,
931            }) => {
932                let expr_type = expr.get_type(self.schema)?;
933                let low_type = low.get_type(self.schema)?;
934                let low_coerced_type = comparison_coercion_with_session_timezone(
935                    &expr_type,
936                    &low_type,
937                    self.session_time_zone,
938                )
939                .ok_or_else(|| {
940                    internal_datafusion_err!(
941                        "Failed to coerce types {expr_type} and {low_type} in BETWEEN expression"
942                    )
943                })?;
944                let high_type = high.get_type(self.schema)?;
945                let coercion_type = comparison_coercion_with_session_timezone(
946                    &low_coerced_type,
947                    &high_type,
948                    self.session_time_zone,
949                )
950                    .ok_or_else(|| {
951                        internal_datafusion_err!(
952                            "Failed to coerce types {expr_type}, {low_type} and {high_type} in BETWEEN expression"
953                        )
954                    })?;
955                Ok(Transformed::yes(Expr::Between(Between::new(
956                    Box::new(expr.cast_to(&coercion_type, self.schema)?),
957                    negated,
958                    Box::new(low.cast_to(&coercion_type, self.schema)?),
959                    Box::new(high.cast_to(&coercion_type, self.schema)?),
960                ))))
961            }
962            Expr::InList(InList {
963                expr,
964                list,
965                negated,
966            }) => {
967                let expr_data_type = expr.get_type(self.schema)?;
968                let list_data_types = list
969                    .iter()
970                    .map(|list_expr| list_expr.get_type(self.schema))
971                    .collect::<Result<Vec<_>>>()?;
972                let result_type = list_data_types.iter().try_fold(
973                    expr_data_type.clone(),
974                    |coerced_type, list_data_type| {
975                        comparison_coercion_with_session_timezone(
976                            &coerced_type,
977                            list_data_type,
978                            self.session_time_zone,
979                        )
980                    },
981                );
982                match result_type {
983                    None => plan_err!(
984                        "Can not find compatible types to compare {expr_data_type} with [{}]",
985                        list_data_types.iter().join(", ")
986                    ),
987                    Some(coerced_type) => {
988                        // find the coerced type
989                        let cast_expr = expr.cast_to(&coerced_type, self.schema)?;
990                        let cast_list_expr = list
991                            .into_iter()
992                            .map(|list_expr| {
993                                list_expr.cast_to(&coerced_type, self.schema)
994                            })
995                            .collect::<Result<Vec<_>>>()?;
996                        Ok(Transformed::yes(Expr::InList(InList::new(
997                            Box::new(cast_expr),
998                            cast_list_expr,
999                            negated,
1000                        ))))
1001                    }
1002                }
1003            }
1004            Expr::Case(case) => {
1005                let case =
1006                    coerce_case_expression(case, self.schema, self.session_time_zone)?;
1007                Ok(Transformed::yes(Expr::Case(case)))
1008            }
1009            Expr::ScalarFunction(ScalarFunction { func, args }) => {
1010                let new_expr = coerce_scalar_function_arguments_for_signature(
1011                    args,
1012                    self.schema,
1013                    func.as_ref(),
1014                )?;
1015                Ok(Transformed::yes(Expr::ScalarFunction(
1016                    ScalarFunction::new_udf(func, new_expr),
1017                )))
1018            }
1019            Expr::AggregateFunction(expr::AggregateFunction {
1020                func,
1021                params:
1022                    AggregateFunctionParams {
1023                        args,
1024                        distinct,
1025                        filter,
1026                        order_by,
1027                        null_treatment,
1028                    },
1029            }) => {
1030                let new_expr =
1031                    coerce_arguments_for_signature(args, self.schema, func.as_ref())?;
1032
1033                let filter = filter
1034                    .map(|filter| filter.cast_to(&DataType::Boolean, self.schema))
1035                    .transpose()?
1036                    .map(Box::new);
1037
1038                Ok(Transformed::yes(Expr::AggregateFunction(
1039                    expr::AggregateFunction::new_udf(
1040                        func,
1041                        new_expr,
1042                        distinct,
1043                        filter,
1044                        order_by,
1045                        null_treatment,
1046                    ),
1047                )))
1048            }
1049            Expr::WindowFunction(window_fun) => {
1050                let WindowFunction {
1051                    fun,
1052                    params:
1053                        expr::WindowFunctionParams {
1054                            args,
1055                            partition_by,
1056                            order_by,
1057                            window_frame,
1058                            filter,
1059                            null_treatment,
1060                            distinct,
1061                        },
1062                } = *window_fun;
1063                let window_frame =
1064                    coerce_window_frame(window_frame, self.schema, &order_by)?;
1065
1066                let args = match &fun {
1067                    expr::WindowFunctionDefinition::AggregateUDF(udf) => {
1068                        coerce_arguments_for_signature(args, self.schema, udf.as_ref())?
1069                    }
1070                    expr::WindowFunctionDefinition::WindowUDF(udf) => {
1071                        coerce_arguments_for_signature(args, self.schema, udf.as_ref())?
1072                    }
1073                };
1074
1075                let filter = filter
1076                    .map(|filter| filter.cast_to(&DataType::Boolean, self.schema))
1077                    .transpose()?
1078                    .map(Box::new);
1079
1080                let new_expr = Expr::from(WindowFunction {
1081                    fun,
1082                    params: expr::WindowFunctionParams {
1083                        args,
1084                        partition_by,
1085                        order_by,
1086                        window_frame,
1087                        filter,
1088                        null_treatment,
1089                        distinct,
1090                    },
1091                });
1092                Ok(Transformed::yes(new_expr))
1093            }
1094            Expr::HigherOrderFunction(HigherOrderFunction { func, args }) => {
1095                let current_fields = args
1096                    .iter()
1097                    .map(|arg| match arg {
1098                        Expr::Lambda(lambda) => Ok(ValueOrLambda::Lambda(
1099                            lambda.body.to_field(self.schema)?.1,
1100                        )),
1101                        _ => Ok(ValueOrLambda::Value(arg.to_field(self.schema)?.1)),
1102                    })
1103                    .collect::<Result<Vec<_>>>()?;
1104
1105                let new_fields = value_fields_with_higher_order_udf_and_lambdas(
1106                    &current_fields,
1107                    func.as_ref(),
1108                )?;
1109
1110                let new_args = std::iter::zip(args, new_fields)
1111                    .map(|(arg, new_field)| match (&arg, new_field) {
1112                        (Expr::Lambda(_lambda), ValueOrLambda::Lambda(_)) => Ok(arg),
1113                        (Expr::Lambda(_lambda), ValueOrLambda::Value(_)) => internal_err!("value_fields_with_higher_order_udf returned a value for a lambda argument"),
1114                        (_, ValueOrLambda::Value(new_field)) => arg.cast_to(new_field.data_type(), self.schema),
1115                        (_, ValueOrLambda::Lambda(_)) => internal_err!("value_fields_with_higher_order_udf returned a lambda for a value argument"),
1116                    })
1117                    .collect::<Result<_>>()?;
1118
1119                Ok(Transformed::yes(Expr::HigherOrderFunction(
1120                    HigherOrderFunction::new(func, new_args),
1121                )))
1122            }
1123            // TODO: remove the next line after `Expr::Wildcard` is removed
1124            #[expect(deprecated)]
1125            Expr::Alias(_)
1126            | Expr::Column(_)
1127            | Expr::ScalarVariable(_, _)
1128            | Expr::Literal(_, _)
1129            | Expr::IsNotNull(_)
1130            | Expr::IsNull(_)
1131            | Expr::Cast(_)
1132            | Expr::TryCast(_)
1133            | Expr::Wildcard { .. }
1134            | Expr::GroupingSet(_)
1135            | Expr::Placeholder(_)
1136            | Expr::OuterReferenceColumn(_, _)
1137            | Expr::Lambda(_)
1138            | Expr::LambdaVariable(_) => Ok(Transformed::no(expr)),
1139        }
1140    }
1141}
1142
1143/// Transform a schema to use non-view types for Utf8View and BinaryView
1144fn transform_schema_to_nonview(dfschema: &DFSchemaRef) -> Option<Result<DFSchema>> {
1145    let metadata = dfschema.as_arrow().metadata.clone();
1146    let mut transformed = false;
1147
1148    let (qualifiers, transformed_fields): (Vec<Option<TableReference>>, Vec<Arc<Field>>) =
1149        dfschema
1150            .iter()
1151            .map(|(qualifier, field)| match field.data_type() {
1152                DataType::Utf8View => {
1153                    transformed = true;
1154                    (
1155                        qualifier.cloned() as Option<TableReference>,
1156                        Arc::new(Field::new(
1157                            field.name(),
1158                            DataType::LargeUtf8,
1159                            field.is_nullable(),
1160                        )),
1161                    )
1162                }
1163                DataType::BinaryView => {
1164                    transformed = true;
1165                    (
1166                        qualifier.cloned() as Option<TableReference>,
1167                        Arc::new(Field::new(
1168                            field.name(),
1169                            DataType::LargeBinary,
1170                            field.is_nullable(),
1171                        )),
1172                    )
1173                }
1174                _ => (
1175                    qualifier.cloned() as Option<TableReference>,
1176                    Arc::clone(field),
1177                ),
1178            })
1179            .unzip();
1180
1181    if !transformed {
1182        return None;
1183    }
1184
1185    let schema = Schema::new_with_metadata(transformed_fields, metadata);
1186    Some(DFSchema::from_field_specific_qualified_schema(
1187        qualifiers,
1188        &Arc::new(schema),
1189    ))
1190}
1191
1192/// Casts the given `value` to `target_type`. Note that this function
1193/// only considers `Null` or `Utf8` values.
1194fn coerce_scalar(target_type: &DataType, value: &ScalarValue) -> Result<ScalarValue> {
1195    match value {
1196        // Coerce Utf8 values:
1197        ScalarValue::Utf8(Some(val)) => {
1198            ScalarValue::try_from_string(val.clone(), target_type)
1199        }
1200        s => {
1201            if s.is_null() {
1202                // Coerce `Null` values:
1203                ScalarValue::try_from(target_type)
1204            } else {
1205                // Values except `Utf8`/`Null` variants already have the right type
1206                // (casted before) since we convert `sqlparser` outputs to `Utf8`
1207                // for all possible cases. Therefore, we return a clone here.
1208                Ok(s.clone())
1209            }
1210        }
1211    }
1212}
1213
1214/// This function coerces `value` to `target_type` in a range-aware fashion.
1215/// If the coercion is successful, we return an `Ok` value with the result.
1216/// If the coercion fails because `target_type` is not wide enough (i.e. we
1217/// can not coerce to `target_type`, but we can to a wider type in the same
1218/// family), we return a `Null` value of this type to signal this situation.
1219/// Downstream code uses this signal to treat these values as *unbounded*.
1220fn coerce_scalar_range_aware(
1221    target_type: &DataType,
1222    value: &ScalarValue,
1223) -> Result<ScalarValue> {
1224    coerce_scalar(target_type, value).or_else(|err| {
1225        // If type coercion fails, check if the largest type in family works:
1226        if let Some(largest_type) = get_widest_type_in_family(target_type) {
1227            coerce_scalar(largest_type, value).map_or_else(
1228                |_| exec_err!("Cannot cast {value} to {target_type}"),
1229                |_| ScalarValue::try_from(target_type),
1230            )
1231        } else {
1232            Err(err)
1233        }
1234    })
1235}
1236
1237/// This function returns the widest type in the family of `given_type`.
1238/// If the given type is already the widest type, it returns `None`.
1239/// For example, if `given_type` is `Int8`, it returns `Int64`.
1240fn get_widest_type_in_family(given_type: &DataType) -> Option<&DataType> {
1241    match given_type {
1242        DataType::UInt8 | DataType::UInt16 | DataType::UInt32 => Some(&DataType::UInt64),
1243        DataType::Int8 | DataType::Int16 | DataType::Int32 => Some(&DataType::Int64),
1244        DataType::Float16 | DataType::Float32 => Some(&DataType::Float64),
1245        _ => None,
1246    }
1247}
1248
1249/// Coerces the given (window frame) `bound` to `target_type`.
1250fn coerce_frame_bound(
1251    target_type: &DataType,
1252    bound: WindowFrameBound,
1253) -> Result<WindowFrameBound> {
1254    match bound {
1255        WindowFrameBound::Preceding(v) => {
1256            coerce_scalar_range_aware(target_type, &v).map(WindowFrameBound::Preceding)
1257        }
1258        WindowFrameBound::CurrentRow => Ok(WindowFrameBound::CurrentRow),
1259        WindowFrameBound::Following(v) => {
1260            coerce_scalar_range_aware(target_type, &v).map(WindowFrameBound::Following)
1261        }
1262    }
1263}
1264
1265/// The type that RANGE frame offsets are coerced to for an ORDER BY column of
1266/// `col_type`, or `None` if there is no offset type to coerce to (the column
1267/// type has no arithmetic). `None` does not mean the type is unusable in a
1268/// RANGE frame: a free frame has no offsets, see `supports_free_range_frame`.
1269fn extract_window_frame_target_type(col_type: &DataType) -> Option<DataType> {
1270    if col_type.is_numeric()
1271        || col_type.is_string()
1272        || col_type.is_binary()
1273        || col_type.is_null()
1274        || matches!(
1275            col_type,
1276            DataType::List(_)
1277                | DataType::LargeList(_)
1278                | DataType::FixedSizeList(_, _)
1279                | DataType::Boolean
1280                | DataType::Time32(_)
1281                | DataType::Time64(_)
1282        )
1283    {
1284        Some(col_type.clone())
1285    } else if is_datetime(col_type) {
1286        Some(DataType::Interval(IntervalUnit::MonthDayNano))
1287    } else if let DataType::Dictionary(_, value_type) = col_type {
1288        extract_window_frame_target_type(value_type)
1289    } else if let DataType::RunEndEncoded(_, value_type) = col_type {
1290        extract_window_frame_target_type(value_type.data_type())
1291    } else {
1292        None
1293    }
1294}
1295
1296/// Whether a free RANGE frame (all bounds `UNBOUNDED` or `CURRENT ROW`) can
1297/// run over an ORDER BY column of `col_type` even though the type has no
1298/// arithmetic for finite offsets.
1299///
1300/// This fallback admits durations and intervals, including encoded values.
1301/// Admission remains conservative: Arrow peer comparison also supports nested
1302/// types, but admitting structs and maps requires separate validation.
1303fn supports_free_range_frame(col_type: &DataType) -> bool {
1304    match col_type {
1305        DataType::Duration(_) | DataType::Interval(_) => true,
1306        DataType::Dictionary(_, value_type) => supports_free_range_frame(value_type),
1307        DataType::RunEndEncoded(_, value_type) => {
1308            supports_free_range_frame(value_type.data_type())
1309        }
1310        _ => false,
1311    }
1312}
1313
1314/// Whether `col_type` is a list, possibly behind dictionary or run-end
1315/// encoding. Free-range fallback still excludes lists conservatively, although
1316/// Arrow can now find peers for supported list keys.
1317fn is_list_type(col_type: &DataType) -> bool {
1318    match col_type {
1319        DataType::List(_) | DataType::LargeList(_) | DataType::FixedSizeList(_, _) => {
1320            true
1321        }
1322        DataType::Dictionary(_, value_type) => is_list_type(value_type),
1323        DataType::RunEndEncoded(_, value_type) => is_list_type(value_type.data_type()),
1324        _ => false,
1325    }
1326}
1327
1328/// Errors if any ORDER BY expression has a type not supported in a free RANGE
1329/// frame: a type with neither an offset target nor support in the free-range
1330/// fallback, or a list (see `is_list_type`). These conservative admission rules
1331/// can be relaxed separately from the nested peer-comparison fix.
1332fn check_free_range_order_by_types(
1333    expressions: &[Sort],
1334    schema: &DFSchema,
1335) -> Result<()> {
1336    for sort in expressions {
1337        let t = sort.expr.get_type(schema)?;
1338        let supported = supports_free_range_frame(&t)
1339            || (extract_window_frame_target_type(&t).is_some() && !is_list_type(&t));
1340        if !supported {
1341            return plan_err!(
1342                "RANGE window frames are not supported for ORDER BY type {t}"
1343            );
1344        }
1345    }
1346    Ok(())
1347}
1348
1349// Coerces the given `window_frame` to use appropriate natural types.
1350// For example, ROWS and GROUPS frames use `UInt64` during calculations.
1351fn coerce_window_frame(
1352    window_frame: WindowFrame,
1353    schema: &DFSchema,
1354    expressions: &[Sort],
1355) -> Result<WindowFrame> {
1356    let mut window_frame = window_frame;
1357    let target_type = match window_frame.units {
1358        WindowFrameUnits::Range => {
1359            let current_types = expressions
1360                .first()
1361                .map(|s| s.expr.get_type(schema))
1362                .transpose()?;
1363            if let Some(col_type) = current_types {
1364                let target_type = match extract_window_frame_target_type(&col_type) {
1365                    Some(target_type) => {
1366                        if window_frame.free_range() {
1367                            // The first key established the target type above, but
1368                            // every later key also participates in peer comparison.
1369                            check_free_range_order_by_types(&expressions[1..], schema)?;
1370                        }
1371                        target_type
1372                    }
1373                    // A free range frame has no offsets to coerce. Check whether
1374                    // its ORDER BY types are supported by the free-range fallback.
1375                    None if window_frame.free_range() => {
1376                        check_free_range_order_by_types(expressions, schema)?;
1377                        return Ok(window_frame);
1378                    }
1379                    None => {
1380                        return plan_err!(
1381                            "RANGE window frames are not supported for ORDER BY type {col_type}"
1382                        );
1383                    }
1384                };
1385                // A finite offset bound (e.g. `5 PRECEDING`) is computed as
1386                // `current_value ± offset`, so it is only meaningful for target
1387                // types that support arithmetic. Other orderable target types can
1388                // still use free range frames, whose bounds require comparison only.
1389                // REE arrays are not supported by arrow's numeric kernesl.
1390                // Tracked at https://github.com/apache/arrow-rs/issues/10891).
1391                let supports_offset_arithmetic =
1392                    !matches!(col_type, DataType::RunEndEncoded(_, _))
1393                        && (target_type.is_numeric() || is_interval(&target_type));
1394                if !supports_offset_arithmetic && !window_frame.free_range() {
1395                    return plan_err!(
1396                        "RANGE with offset PRECEDING/FOLLOWING is not supported for ORDER BY type {target_type}"
1397                    );
1398                }
1399                target_type
1400            } else {
1401                return internal_err!("ORDER BY column cannot be empty");
1402            }
1403        }
1404        WindowFrameUnits::Rows | WindowFrameUnits::Groups => DataType::UInt64,
1405    };
1406    window_frame.start_bound =
1407        coerce_frame_bound(&target_type, window_frame.start_bound)?;
1408    window_frame.end_bound = coerce_frame_bound(&target_type, window_frame.end_bound)?;
1409    Ok(window_frame)
1410}
1411
1412// Support the `IsTrue` `IsNotTrue` `IsFalse` `IsNotFalse` type coercion.
1413// The above op will be rewrite to the binary op when creating the physical op.
1414fn get_casted_expr_for_bool_op(expr: Expr, schema: &DFSchema) -> Result<Expr> {
1415    let left_type = expr.get_type(schema)?;
1416    BinaryTypeCoercer::new(&left_type, &Operator::IsDistinctFrom, &DataType::Boolean)
1417        .get_input_types()?;
1418    expr.cast_to(&DataType::Boolean, schema)
1419}
1420
1421/// Returns `expressions` coerced to types compatible with
1422/// `signature`, if possible.
1423///
1424/// See the module level documentation for more detail on coercion.
1425fn coerce_arguments_for_signature<F: UDFCoercionExt>(
1426    expressions: Vec<Expr>,
1427    schema: &DFSchema,
1428    func: &F,
1429) -> Result<Vec<Expr>> {
1430    let coerced_types = coerced_argument_types(&expressions, schema, func)?;
1431
1432    expressions
1433        .into_iter()
1434        .zip(coerced_types)
1435        .map(|(expr, data_type)| expr.cast_to(&data_type, schema))
1436        .collect()
1437}
1438
1439/// Coerces scalar function arguments while materializing successful implicit
1440/// casts of literals. This preserves the literal for subsequent calls to
1441/// `return_field_from_args` without treating user-written `Cast` or `TryCast`
1442/// expressions as scalar arguments.
1443fn coerce_scalar_function_arguments_for_signature<F: UDFCoercionExt>(
1444    expressions: Vec<Expr>,
1445    schema: &DFSchema,
1446    func: &F,
1447) -> Result<Vec<Expr>> {
1448    let coerced_types = coerced_argument_types(&expressions, schema, func)?;
1449
1450    expressions
1451        .into_iter()
1452        .zip(coerced_types)
1453        .map(|(expr, data_type)| {
1454            coerce_scalar_function_argument(expr, &data_type, schema)
1455        })
1456        .collect()
1457}
1458
1459fn coerced_argument_types<F: UDFCoercionExt>(
1460    expressions: &[Expr],
1461    schema: &DFSchema,
1462    func: &F,
1463) -> Result<Vec<DataType>> {
1464    let current_fields = expressions
1465        .iter()
1466        .map(|e| e.to_field(schema).map(|(_, f)| f))
1467        .collect::<Result<Vec<_>>>()?;
1468
1469    fields_with_udf(&current_fields, func).map(|fields| {
1470        fields
1471            .into_iter()
1472            .map(|field| field.data_type().clone())
1473            .collect()
1474    })
1475}
1476
1477fn coerce_scalar_function_argument(
1478    expr: Expr,
1479    data_type: &DataType,
1480    schema: &DFSchema,
1481) -> Result<Expr> {
1482    if matches!(&expr, Expr::Cast(_) | Expr::TryCast(_))
1483        && expr.get_type(schema)? == *data_type
1484    {
1485        return Ok(expr);
1486    }
1487
1488    let Expr::Literal(value, metadata) = expr else {
1489        return expr.cast_to(data_type, schema);
1490    };
1491
1492    if value.data_type() != *data_type
1493        && let Ok(value) = value.cast_to(data_type)
1494    {
1495        return Ok(Expr::Literal(value, metadata));
1496    }
1497
1498    // A failed value cast remains an expression cast so execution produces the
1499    // same error as before. Since it is no longer a literal at the coerced type,
1500    // it is reported as `None` in `ReturnFieldArgs::scalar_arguments`.
1501    Expr::Literal(value, metadata).cast_to(data_type, schema)
1502}
1503
1504fn coerce_case_expression(
1505    case: Case,
1506    schema: &DFSchema,
1507    session_time_zone: Option<&str>,
1508) -> Result<Case> {
1509    // Given expressions like:
1510    //
1511    // CASE a1
1512    //   WHEN a2 THEN b1
1513    //   WHEN a3 THEN b2
1514    //   ELSE b3
1515    // END
1516    //
1517    // or:
1518    //
1519    // CASE
1520    //   WHEN x1 THEN b1
1521    //   WHEN x2 THEN b2
1522    //   ELSE b3
1523    // END
1524    //
1525    // Then all aN (a1, a2, a3) must be converted to a common data type in the first example
1526    // (case-when expression coercion)
1527    //
1528    // All xN (x1, x2) must be converted to a boolean data type in the second example
1529    // (when-boolean expression coercion)
1530    //
1531    // And all bN (b1, b2, b3) must be converted to a common data type in both examples
1532    // (then-else expression coercion)
1533    //
1534    // If any fail to find and cast to a common/specific data type, will return error
1535    //
1536    // Note that case-when and when-boolean expression coercions are mutually exclusive
1537    // Only one or the other can occur for a case expression, whilst then-else expression coercion will always occur
1538
1539    // prepare types
1540    let case_type = case
1541        .expr
1542        .as_ref()
1543        .map(|expr| expr.get_type(schema))
1544        .transpose()?;
1545    let then_types = case
1546        .when_then_expr
1547        .iter()
1548        .map(|(_when, then)| then.get_type(schema))
1549        .collect::<Result<Vec<_>>>()?;
1550    let else_type = case
1551        .else_expr
1552        .as_ref()
1553        .map(|expr| expr.get_type(schema))
1554        .transpose()?;
1555
1556    // find common coercible types
1557    let case_when_coerce_type = case_type
1558        .as_ref()
1559        .map(|case_type| {
1560            let when_types = case
1561                .when_then_expr
1562                .iter()
1563                .map(|(when, _then)| when.get_type(schema))
1564                .collect::<Result<Vec<_>>>()?;
1565            let coerced_type = when_types.iter().try_fold(
1566                case_type.clone(),
1567                |coerced_type, when_type| {
1568                    comparison_coercion_with_session_timezone(
1569                        &coerced_type,
1570                        when_type,
1571                        session_time_zone,
1572                    )
1573                },
1574            );
1575            coerced_type.ok_or_else(|| {
1576                plan_datafusion_err!(
1577                    "Failed to coerce case ({case_type}) and when ({}) \
1578                     to common types in CASE WHEN expression",
1579                    when_types.iter().join(", ")
1580                )
1581            })
1582        })
1583        .transpose()?;
1584    let then_else_coerce_type =
1585        get_coerce_type_for_case_expression(&then_types, else_type.as_ref()).ok_or_else(
1586            || {
1587                if let Some(else_type) = else_type {
1588                    plan_datafusion_err!(
1589                        "Failed to coerce then ({}) and else ({else_type}) \
1590                         to common types in CASE WHEN expression",
1591                        then_types.iter().join(", ")
1592                    )
1593                } else {
1594                    plan_datafusion_err!(
1595                        "Failed to coerce then ({}) and else (None) \
1596                         to common types in CASE WHEN expression",
1597                        then_types.iter().join(", ")
1598                    )
1599                }
1600            },
1601        )?;
1602
1603    // do cast if found common coercible types
1604    let case_expr = case
1605        .expr
1606        .zip(case_when_coerce_type.as_ref())
1607        .map(|(case_expr, coercible_type)| case_expr.cast_to(coercible_type, schema))
1608        .transpose()?
1609        .map(Box::new);
1610    let when_then = case
1611        .when_then_expr
1612        .into_iter()
1613        .map(|(when, then)| {
1614            let when_type = case_when_coerce_type.as_ref().unwrap_or(&DataType::Boolean);
1615            let when = when.cast_to(when_type, schema).map_err(|e| {
1616                DataFusionError::Context(
1617                    format!(
1618                        "WHEN expressions in CASE couldn't be \
1619                         converted to common type ({when_type})"
1620                    ),
1621                    Box::new(e),
1622                )
1623            })?;
1624            let then = then.cast_to(&then_else_coerce_type, schema)?;
1625            Ok((Box::new(when), Box::new(then)))
1626        })
1627        .collect::<Result<Vec<_>>>()?;
1628    let else_expr = case
1629        .else_expr
1630        .map(|expr| expr.cast_to(&then_else_coerce_type, schema))
1631        .transpose()?
1632        .map(Box::new);
1633
1634    Ok(Case::new(case_expr, when_then, else_expr))
1635}
1636
1637/// Get a common schema that is compatible with all inputs of UNION.
1638///
1639/// This method presumes that the wildcard expansion is unneeded, or has already
1640/// been applied.
1641///
1642/// ## Schema and Field Handling in Union Coercion
1643///
1644/// **Processing order**: The function starts with the base schema (first input) and then
1645/// processes remaining inputs sequentially, with later inputs taking precedence in merging.
1646///
1647/// **Schema-level metadata merging**: Later schemas take precedence for duplicate keys.
1648///
1649/// **Field-level metadata merging**: Later fields take precedence for duplicate metadata keys.
1650///
1651/// **Type coercion precedence**: The coerced type is determined by iteratively applying
1652/// `type_union_coercion()` between the accumulated type and each new input's type. The
1653/// result follows the input order, which can matter for dictionary and nested types.
1654///
1655/// **Nullability merging**: Nullability is accumulated using logical OR (`||`).
1656/// Once any input field is nullable, the result field becomes nullable permanently.
1657/// Later inputs can make a field nullable but cannot make it non-nullable.
1658///
1659/// **Field precedence**: Field names come from the first (base) schema, but the field properties
1660/// (nullability and field-level metadata) have later schemas taking precedence.
1661///
1662/// **Example**:
1663/// ```sql
1664/// SELECT a, b FROM table1  -- a: Int32, metadata {"source": "t1"}, nullable=false
1665/// UNION
1666/// SELECT a, b FROM table2  -- a: Int64, metadata {"source": "t2"}, nullable=true
1667/// UNION
1668/// SELECT a, b FROM table3  -- a: Int32, metadata {"encoding": "utf8"}, nullable=false
1669/// -- Result:
1670/// -- a: Int64 (from type coercion), nullable=true (from table2),
1671/// -- metadata: {"source": "t2", "encoding": "utf8"} (later inputs take precedence)
1672/// ```
1673///
1674/// **Precedence Summary**:
1675/// - **Datatypes**: Folded in input order using `type_union_coercion()`
1676/// - **Nullability**: Later inputs can add nullability but cannot remove it (logical OR)
1677/// - **Metadata**: Later inputs take precedence for same keys (HashMap::extend semantics)
1678pub fn coerce_union_schema(inputs: &[Arc<LogicalPlan>]) -> Result<DFSchema> {
1679    let Some(first) = inputs.first() else {
1680        return plan_err!("UNION requires at least one input");
1681    };
1682    coerce_union_schema_with_schema(inputs, first.schema())
1683}
1684fn coerce_union_schema_with_schema(
1685    inputs: &[Arc<LogicalPlan>],
1686    base_schema: &DFSchemaRef,
1687) -> Result<DFSchema> {
1688    for (i, plan) in inputs.iter().enumerate() {
1689        if plan.schema().fields().len() != base_schema.fields().len() {
1690            return plan_err!(
1691                "Union schemas have different number of fields: \
1692                query 1 has {} fields whereas query {} has {} fields",
1693                base_schema.fields().len(),
1694                i + 1,
1695                plan.schema().fields().len()
1696            );
1697        }
1698    }
1699
1700    let all_schemas = std::iter::once(base_schema)
1701        .chain(inputs.iter().map(|p| p.schema()))
1702        .collect::<Vec<_>>();
1703
1704    let union_qualified_fields = base_schema
1705        .fields()
1706        .iter()
1707        .enumerate()
1708        .map(|(i, field)| {
1709            // The stored schema may already contain an inferred common type. Feeding
1710            // it back into coercion can change the result, notably for dictionaries.
1711            let datatype = coerce_union_type(
1712                inputs.iter().map(|plan| plan.schema().field(i).as_ref()),
1713            )?;
1714            let nullable = field.is_nullable()
1715                || inputs
1716                    .iter()
1717                    .any(|plan| plan.schema().field(i).is_nullable());
1718            let mut field = Field::new(field.name().clone(), datatype, nullable);
1719            field.set_metadata(merge_metadata_for_union(
1720                all_schemas.iter().map(|schema| schema.field(i).metadata()),
1721            ));
1722            Ok((None, field.into()))
1723        })
1724        .collect::<Result<Vec<_>>>()?;
1725
1726    let metadata =
1727        merge_metadata_for_union(all_schemas.iter().map(|schema| schema.metadata()));
1728    DFSchema::new_with_metadata(union_qualified_fields, metadata)
1729}
1730
1731/// See `<https://github.com/apache/datafusion/pull/2108>`
1732fn project_with_column_index(
1733    expr: Vec<Expr>,
1734    input: Arc<LogicalPlan>,
1735    schema: DFSchemaRef,
1736) -> Result<LogicalPlan> {
1737    let alias_expr = expr
1738        .into_iter()
1739        .enumerate()
1740        .map(|(i, e)| match e {
1741            Expr::Alias(Alias { ref name, .. }) if name != schema.field(i).name() => {
1742                Ok(e.unalias().alias(schema.field(i).name()))
1743            }
1744            Expr::Column(Column {
1745                relation: _,
1746                ref name,
1747                spans: _,
1748            }) if name != schema.field(i).name() => Ok(e.alias(schema.field(i).name())),
1749            Expr::Alias { .. } | Expr::Column { .. } => Ok(e),
1750            #[expect(deprecated)]
1751            Expr::Wildcard { .. } => {
1752                plan_err!("Wildcard should be expanded before type coercion")
1753            }
1754            _ => Ok(e.alias(schema.field(i).name())),
1755        })
1756        .collect::<Result<Vec<_>>>()?;
1757
1758    Projection::try_new_with_schema(alias_expr, input, schema)
1759        .map(LogicalPlan::Projection)
1760}
1761
1762/// Coerces a multi-column `(a, b, ...) IN (SELECT x, y, ...)`.
1763///
1764/// Each tuple element and the subquery column at the same position are cast
1765/// to their common comparison type, like the single-column form does for its
1766/// one pair.
1767fn coerce_multi_column_in_subquery(
1768    func: ScalarFunction,
1769    subquery: Subquery,
1770    schema: &DFSchema,
1771    session_time_zone: Option<&str>,
1772) -> Result<(Expr, Subquery)> {
1773    let subquery_schema = Arc::clone(subquery.subquery.schema());
1774    let mut common_types = Vec::with_capacity(func.args.len());
1775    let mut args = Vec::with_capacity(func.args.len());
1776    for (arg, field) in func.args.into_iter().zip(subquery_schema.fields()) {
1777        let expr_type = arg.get_type(schema)?;
1778        let subquery_type = field.data_type();
1779        let common_type = comparison_coercion_with_session_timezone(
1780            &expr_type,
1781            subquery_type,
1782            session_time_zone,
1783        )
1784        .ok_or(plan_datafusion_err!(
1785            "expr type {expr_type} can't cast to {subquery_type} in InSubquery"
1786        ))?;
1787        args.push(arg.cast_to(&common_type, schema)?);
1788        common_types.push(common_type);
1789    }
1790    Ok((
1791        Expr::ScalarFunction(ScalarFunction::new_udf(func.func, args)),
1792        cast_subquery_columns(subquery, &common_types)?,
1793    ))
1794}
1795
1796#[cfg(test)]
1797mod test {
1798
1799    use std::sync::Arc;
1800
1801    use arrow::datatypes::DataType::Utf8;
1802    use arrow::datatypes::{DataType, Field, Schema, SchemaBuilder, TimeUnit};
1803    use insta::assert_snapshot;
1804
1805    use crate::analyzer::type_coercion::{
1806        TypeCoercion, TypeCoercionRewriter, coerce_case_expression,
1807    };
1808    use crate::analyzer::{Analyzer, AnalyzerRule};
1809    use crate::assert_analyzed_plan_with_config_eq_snapshot;
1810    use datafusion_common::config::ConfigOptions;
1811    use datafusion_common::tree_node::{TransformedResult, TreeNode};
1812    use datafusion_common::{
1813        DFSchema, DFSchemaRef, Result, ScalarValue, Spans, TableReference,
1814    };
1815    use datafusion_expr::expr::{
1816        self, InSubquery, Like, ScalarFunction, SetComparison, SetQuantifier,
1817    };
1818    use datafusion_expr::logical_plan::{EmptyRelation, Projection, Sort, table_scan};
1819    use datafusion_expr::test::function_stub::avg_udaf;
1820    use datafusion_expr::{
1821        AccumulatorFactoryFunction, AggregateUDF, BinaryExpr, Case, ColumnarValue, Expr,
1822        ExprSchemable, Filter, Limit, LogicalPlan, Operator, ScalarFunctionArgs,
1823        ScalarUDF, ScalarUDFImpl, Signature, SimpleAggregateUDF, Subquery, Union,
1824        Volatility, cast, col, create_udaf, grouping_set, is_true, lit, placeholder,
1825    };
1826    use datafusion_functions_aggregate::average::AvgAccumulator;
1827
1828    fn empty() -> Arc<LogicalPlan> {
1829        Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
1830            produce_one_row: false,
1831            schema: Arc::new(DFSchema::empty()),
1832        }))
1833    }
1834
1835    fn empty_with_type(data_type: DataType) -> Arc<LogicalPlan> {
1836        Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
1837            produce_one_row: false,
1838            schema: Arc::new(
1839                DFSchema::from_unqualified_fields(
1840                    vec![Field::new("a", data_type, true)].into(),
1841                    std::collections::HashMap::new(),
1842                )
1843                .unwrap(),
1844            ),
1845        }))
1846    }
1847
1848    macro_rules! assert_analyzed_plan_eq {
1849        (
1850            $plan: expr,
1851            @ $expected: literal $(,)?
1852        ) => {{
1853            let options = ConfigOptions::default();
1854            let rule = Arc::new(TypeCoercion::new());
1855            assert_analyzed_plan_with_config_eq_snapshot!(
1856                options,
1857                rule,
1858                $plan,
1859                @ $expected,
1860            )
1861            }};
1862    }
1863
1864    macro_rules! coerce_on_output_if_viewtype {
1865        (
1866            $is_viewtype: expr,
1867            $plan: expr,
1868            @ $expected: literal $(,)?
1869        ) => {{
1870            let mut options = ConfigOptions::default();
1871            // coerce on output
1872            if $is_viewtype {options.optimizer.expand_views_at_output = true;}
1873            let rule = Arc::new(TypeCoercion::new());
1874
1875            assert_analyzed_plan_with_config_eq_snapshot!(
1876                options,
1877                rule,
1878                $plan,
1879                @ $expected,
1880            )
1881        }};
1882    }
1883
1884    fn assert_type_coercion_error(
1885        plan: LogicalPlan,
1886        expected_substr: &str,
1887    ) -> Result<()> {
1888        let options = ConfigOptions::default();
1889        let analyzer = Analyzer::with_rules(vec![Arc::new(TypeCoercion::new())]);
1890
1891        match analyzer.execute_and_check(plan, &options, |_, _| {}) {
1892            Ok(succeeded_plan) => {
1893                panic!(
1894                    "Expected a type coercion error, but analysis succeeded: \n{succeeded_plan:#?}"
1895                );
1896            }
1897            Err(e) => {
1898                let msg = e.to_string();
1899                assert!(
1900                    msg.contains(expected_substr),
1901                    "Error did not contain expected substring.\n  expected to find: `{expected_substr}`\n  actual error: `{msg}`"
1902                );
1903            }
1904        }
1905
1906        Ok(())
1907    }
1908
1909    #[test]
1910    fn untyped_limit_parameter_remains_inferable_after_coercion() -> Result<()> {
1911        let plan = LogicalPlan::Limit(Limit {
1912            input: empty(),
1913            fetch: Some(Box::new(placeholder("$1"))),
1914            skip: None,
1915        });
1916        let analyzed = TypeCoercion::new().analyze(plan, &ConfigOptions::default())?;
1917
1918        assert_eq!(analyzed.get_parameter_types()?["$1"], Some(DataType::Int64));
1919        Ok(())
1920    }
1921
1922    #[test]
1923    fn simple_case() -> Result<()> {
1924        let expr = col("a").lt(lit(2_u32));
1925        let empty = empty_with_type(DataType::Float64);
1926        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
1927
1928        assert_analyzed_plan_eq!(
1929            plan,
1930            @r"
1931        Projection: a < CAST(UInt32(2) AS Float64)
1932          EmptyRelation: rows=0
1933        "
1934        )
1935    }
1936
1937    #[test]
1938    fn negative_expr_wrapped_by_is_null_errors() -> Result<()> {
1939        let predicate = Expr::IsNull(Box::new(Expr::Negative(Box::new(lit("a")))));
1940        let plan = LogicalPlan::Filter(Filter::try_new(predicate, empty())?);
1941
1942        assert_type_coercion_error(
1943            plan,
1944            "Negation only supports numeric, interval and timestamp types",
1945        )
1946    }
1947
1948    #[test]
1949    fn union_schema_validates_input_shapes() -> Result<()> {
1950        use super::coerce_union_schema;
1951        assert!(coerce_union_schema(&[]).is_err());
1952        let input = empty_with_type(DataType::Int32);
1953        let schema = coerce_union_schema(&[Arc::clone(&input)])?;
1954        assert_eq!(schema.field(0).data_type(), &DataType::Int32);
1955        let incompatible_width = empty();
1956        assert!(coerce_union_schema(&[input, incompatible_width]).is_err());
1957        Ok(())
1958    }
1959
1960    #[test]
1961    fn test_coerce_union() -> Result<()> {
1962        let left_plan = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
1963            produce_one_row: false,
1964            schema: Arc::new(
1965                DFSchema::try_from_qualified_schema(
1966                    TableReference::full("datafusion", "test", "foo"),
1967                    &Schema::new(vec![Field::new("a", DataType::Int32, false)]),
1968                )
1969                .unwrap(),
1970            ),
1971        }));
1972        let right_plan = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
1973            produce_one_row: false,
1974            schema: Arc::new(
1975                DFSchema::try_from_qualified_schema(
1976                    TableReference::full("datafusion", "test", "foo"),
1977                    &Schema::new(vec![Field::new("a", DataType::Int64, false)]),
1978                )
1979                .unwrap(),
1980            ),
1981        }));
1982        let union = LogicalPlan::Union(Union::try_new_with_loose_types(vec![
1983            left_plan, right_plan,
1984        ])?);
1985        let analyzed_union = Analyzer::with_rules(vec![Arc::new(TypeCoercion::new())])
1986            .execute_and_check(union, &ConfigOptions::default(), |_, _| {})?;
1987        let top_level_plan = LogicalPlan::Projection(Projection::try_new(
1988            vec![col("a")],
1989            Arc::new(analyzed_union),
1990        )?);
1991
1992        assert_analyzed_plan_eq!(
1993            top_level_plan,
1994            @r"
1995        Projection: a
1996          Union
1997            Projection: CAST(datafusion.test.foo.a AS Int64) AS a
1998              EmptyRelation: rows=0
1999            EmptyRelation: rows=0
2000        "
2001        )
2002    }
2003
2004    #[test]
2005    fn merge_into_resolves_and_coerces_target_and_source_columns() -> Result<()> {
2006        use datafusion_expr::dml::{
2007            MergeIntoAction, MergeIntoClause, MergeIntoClauseKind, MergeIntoOp,
2008        };
2009        use datafusion_expr::logical_plan::table_scan;
2010        use datafusion_expr::{DmlStatement, WriteOp};
2011
2012        // Target table `target(id: UInt32)`.
2013        let target_table_name = TableReference::bare("target");
2014        let target_arrow_schema =
2015            Schema::new(vec![Field::new("id", DataType::UInt32, false)]);
2016        let target_plan =
2017            table_scan(Some(target_table_name.clone()), &target_arrow_schema, None)?
2018                .build()?;
2019        let target_source = match &target_plan {
2020            LogicalPlan::TableScan(ts) => Arc::clone(&ts.source),
2021            _ => unreachable!("table_scan() always builds a TableScan"),
2022        };
2023
2024        // Source plan `source(id: Int64)` — deliberately a different numeric
2025        // type than `target.id` so the `ON` comparison needs a CAST.
2026        let source_arrow_schema =
2027            Schema::new(vec![Field::new("id", DataType::Int64, false)]);
2028        let source_plan =
2029            table_scan(Some("source"), &source_arrow_schema, None)?.build()?;
2030
2031        // `ON target.id = source.id`. Resolving `target.id` requires the
2032        // target schema to be visible to the analyzer, which only sees
2033        // `plan.inputs()` (the source plan) by default.
2034        let on = col("target.id").eq(col("source.id"));
2035        let merge_op = MergeIntoOp::new(
2036            "target",
2037            on,
2038            vec![
2039                MergeIntoClause {
2040                    kind: MergeIntoClauseKind::Matched,
2041                    predicate: None,
2042                    action: MergeIntoAction::Update(vec![(
2043                        "id".to_string(),
2044                        col("source.id"),
2045                    )]),
2046                },
2047                MergeIntoClause {
2048                    kind: MergeIntoClauseKind::NotMatched,
2049                    predicate: None,
2050                    action: MergeIntoAction::Insert {
2051                        columns: vec!["id".to_string()],
2052                        values: vec![col("source.id")],
2053                    },
2054                },
2055            ],
2056        );
2057        let plan = LogicalPlan::Dml(DmlStatement::new(
2058            target_table_name,
2059            target_source,
2060            WriteOp::MergeInto(Box::new(merge_op)),
2061            Arc::new(source_plan),
2062        ));
2063
2064        let analyzed = Analyzer::with_rules(vec![Arc::new(TypeCoercion::new())])
2065            .execute_and_check(plan, &ConfigOptions::default(), |_, _| {})?;
2066        let LogicalPlan::Dml(dml) = analyzed else {
2067            panic!("expected Dml");
2068        };
2069        let WriteOp::MergeInto(merge_op) = dml.op else {
2070            panic!("expected MergeInto");
2071        };
2072        assert_eq!(
2073            merge_op.on.to_string(),
2074            "CAST(target.id AS Int64) = source.id"
2075        );
2076        let MergeIntoAction::Update(assignments) = &merge_op.clauses[0].action else {
2077            panic!("expected UPDATE");
2078        };
2079        assert_eq!(assignments[0].1.to_string(), "CAST(source.id AS UInt32)");
2080        let MergeIntoAction::Insert { values, .. } = &merge_op.clauses[1].action else {
2081            panic!("expected INSERT");
2082        };
2083        assert_eq!(values[0].to_string(), "CAST(source.id AS UInt32)");
2084        Ok(())
2085    }
2086
2087    #[test]
2088    fn coerce_utf8view_output() -> Result<()> {
2089        // Plan A
2090        // scenario: outermost utf8view projection
2091        let expr = col("a");
2092        let empty = empty_with_type(DataType::Utf8View);
2093        let plan = LogicalPlan::Projection(Projection::try_new(
2094            vec![expr.clone()],
2095            Arc::clone(&empty),
2096        )?);
2097
2098        // Plan A: no coerce
2099        coerce_on_output_if_viewtype!(
2100            false,
2101            plan.clone(),
2102            @r"
2103        Projection: a
2104          EmptyRelation: rows=0
2105        "
2106        )?;
2107
2108        // Plan A: coerce requested: Utf8View => LargeUtf8
2109        coerce_on_output_if_viewtype!(
2110            true,
2111            plan.clone(),
2112            @r"
2113        Projection: CAST(a AS LargeUtf8) AS a
2114          EmptyRelation: rows=0
2115        "
2116        )?;
2117
2118        // Plan B
2119        // scenario: outermost bool projection
2120        let bool_expr = col("a").lt(lit("foo"));
2121        let bool_plan = LogicalPlan::Projection(Projection::try_new(
2122            vec![bool_expr],
2123            Arc::clone(&empty),
2124        )?);
2125        // Plan B: no coerce
2126        coerce_on_output_if_viewtype!(
2127            false,
2128            bool_plan.clone(),
2129            @r#"
2130        Projection: a < CAST(Utf8("foo") AS Utf8View)
2131          EmptyRelation: rows=0
2132        "#
2133        )?;
2134
2135        coerce_on_output_if_viewtype!(
2136            false,
2137            plan.clone(),
2138            @r"
2139        Projection: a
2140          EmptyRelation: rows=0
2141        "
2142        )?;
2143
2144        // Plan B: coerce requested: no coercion applied
2145        coerce_on_output_if_viewtype!(
2146            true,
2147            plan.clone(),
2148            @r"
2149        Projection: CAST(a AS LargeUtf8) AS a
2150          EmptyRelation: rows=0
2151        "
2152        )?;
2153
2154        // Plan C
2155        // scenario: with a non-projection root logical plan node
2156        let sort_expr = expr.sort(true, true);
2157        let sort_plan = LogicalPlan::Sort(Sort {
2158            expr: vec![sort_expr],
2159            input: Arc::new(plan),
2160            fetch: None,
2161        });
2162
2163        // Plan C: no coerce
2164        coerce_on_output_if_viewtype!(
2165            false,
2166            sort_plan.clone(),
2167            @r"
2168        Sort: a ASC NULLS FIRST
2169          Projection: a
2170            EmptyRelation: rows=0
2171        "
2172        )?;
2173
2174        // Plan C: coerce requested: Utf8View => LargeUtf8
2175        coerce_on_output_if_viewtype!(
2176            true,
2177            sort_plan.clone(),
2178            @r"
2179        Projection: CAST(a AS LargeUtf8) AS a
2180          Sort: a ASC NULLS FIRST
2181            Projection: a
2182              EmptyRelation: rows=0
2183        "
2184        )?;
2185
2186        // Plan D
2187        // scenario: two layers of projections with view types
2188        let plan = LogicalPlan::Projection(Projection::try_new(
2189            vec![col("a")],
2190            Arc::new(sort_plan),
2191        )?);
2192        // Plan D: no coerce
2193        coerce_on_output_if_viewtype!(
2194            false,
2195            plan.clone(),
2196            @r"
2197        Projection: a
2198          Sort: a ASC NULLS FIRST
2199            Projection: a
2200              EmptyRelation: rows=0
2201        "
2202        )?;
2203        // Plan B: coerce requested: Utf8View => LargeUtf8 only on outermost
2204        coerce_on_output_if_viewtype!(
2205            true,
2206            plan.clone(),
2207            @r"
2208        Projection: CAST(a AS LargeUtf8) AS a
2209          Sort: a ASC NULLS FIRST
2210            Projection: a
2211              EmptyRelation: rows=0
2212        "
2213        )?;
2214
2215        Ok(())
2216    }
2217
2218    #[test]
2219    fn coerce_binaryview_output() -> Result<()> {
2220        // Plan A
2221        // scenario: outermost binaryview projection
2222        let expr = col("a");
2223        let empty = empty_with_type(DataType::BinaryView);
2224        let plan = LogicalPlan::Projection(Projection::try_new(
2225            vec![expr.clone()],
2226            Arc::clone(&empty),
2227        )?);
2228
2229        // Plan A: no coerce
2230        coerce_on_output_if_viewtype!(
2231            false,
2232            plan.clone(),
2233            @r"
2234        Projection: a
2235          EmptyRelation: rows=0
2236        "
2237        )?;
2238
2239        // Plan A: coerce requested: BinaryView => LargeBinary
2240        coerce_on_output_if_viewtype!(
2241            true,
2242            plan.clone(),
2243            @r"
2244        Projection: CAST(a AS LargeBinary) AS a
2245          EmptyRelation: rows=0
2246        "
2247        )?;
2248
2249        // Plan B
2250        // scenario: outermost bool projection
2251        let bool_expr = col("a").lt(lit(vec![8, 1, 8, 1]));
2252        let bool_plan = LogicalPlan::Projection(Projection::try_new(
2253            vec![bool_expr],
2254            Arc::clone(&empty),
2255        )?);
2256
2257        // Plan B: no coerce
2258        coerce_on_output_if_viewtype!(
2259            false,
2260            bool_plan.clone(),
2261            @r#"
2262        Projection: a < CAST(Binary("8,1,8,1") AS BinaryView)
2263          EmptyRelation: rows=0
2264        "#
2265        )?;
2266
2267        // Plan B: coerce requested: no coercion applied
2268        coerce_on_output_if_viewtype!(
2269            true,
2270            bool_plan.clone(),
2271            @r#"
2272        Projection: a < CAST(Binary("8,1,8,1") AS BinaryView)
2273          EmptyRelation: rows=0
2274        "#
2275        )?;
2276
2277        // Plan C
2278        // scenario: with a non-projection root logical plan node
2279        let sort_expr = expr.sort(true, true);
2280        let sort_plan = LogicalPlan::Sort(Sort {
2281            expr: vec![sort_expr],
2282            input: Arc::new(plan),
2283            fetch: None,
2284        });
2285
2286        // Plan C: no coerce
2287        coerce_on_output_if_viewtype!(
2288            false,
2289            sort_plan.clone(),
2290            @r"
2291        Sort: a ASC NULLS FIRST
2292          Projection: a
2293            EmptyRelation: rows=0
2294        "
2295        )?;
2296        // Plan C: coerce requested: BinaryView => LargeBinary
2297        coerce_on_output_if_viewtype!(
2298            true,
2299            sort_plan.clone(),
2300            @r"
2301        Projection: CAST(a AS LargeBinary) AS a
2302          Sort: a ASC NULLS FIRST
2303            Projection: a
2304              EmptyRelation: rows=0
2305        "
2306        )?;
2307
2308        // Plan D
2309        // scenario: two layers of projections with view types
2310        let plan = LogicalPlan::Projection(Projection::try_new(
2311            vec![col("a")],
2312            Arc::new(sort_plan),
2313        )?);
2314
2315        // Plan D: no coerce
2316        coerce_on_output_if_viewtype!(
2317            false,
2318            plan.clone(),
2319            @r"
2320        Projection: a
2321          Sort: a ASC NULLS FIRST
2322            Projection: a
2323              EmptyRelation: rows=0
2324        "
2325        )?;
2326
2327        // Plan B: coerce requested: BinaryView => LargeBinary only on outermost
2328        coerce_on_output_if_viewtype!(
2329            true,
2330            plan.clone(),
2331            @r"
2332        Projection: CAST(a AS LargeBinary) AS a
2333          Sort: a ASC NULLS FIRST
2334            Projection: a
2335              EmptyRelation: rows=0
2336        "
2337        )?;
2338
2339        Ok(())
2340    }
2341
2342    #[test]
2343    fn nested_case() -> Result<()> {
2344        let expr = col("a").lt(lit(2_u32));
2345        let empty = empty_with_type(DataType::Float64);
2346
2347        let plan = LogicalPlan::Projection(Projection::try_new(
2348            vec![expr.clone().or(expr)],
2349            empty,
2350        )?);
2351
2352        assert_analyzed_plan_eq!(
2353            plan,
2354            @r"
2355        Projection: a < CAST(UInt32(2) AS Float64) OR a < CAST(UInt32(2) AS Float64)
2356          EmptyRelation: rows=0
2357        "
2358        )
2359    }
2360
2361    #[derive(Debug, PartialEq, Eq, Hash)]
2362    struct TestScalarUDF {
2363        signature: Signature,
2364    }
2365
2366    impl ScalarUDFImpl for TestScalarUDF {
2367        fn name(&self) -> &str {
2368            "TestScalarUDF"
2369        }
2370
2371        fn signature(&self) -> &Signature {
2372            &self.signature
2373        }
2374
2375        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
2376            Ok(Utf8)
2377        }
2378
2379        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
2380            Ok(ColumnarValue::Scalar(ScalarValue::from("a")))
2381        }
2382    }
2383
2384    #[derive(Debug, Hash, PartialEq, Eq)]
2385    struct TestArrayElementUDF;
2386
2387    impl ScalarUDFImpl for TestArrayElementUDF {
2388        fn name(&self) -> &str {
2389            "TestArrayElementUDF"
2390        }
2391
2392        fn signature(&self) -> &Signature {
2393            static SIGNATURE: std::sync::LazyLock<Signature> =
2394                std::sync::LazyLock::new(|| {
2395                    Signature::array_and_index(Volatility::Immutable)
2396                });
2397            &SIGNATURE
2398        }
2399
2400        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
2401            Ok(Utf8)
2402        }
2403
2404        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
2405            Ok(ColumnarValue::Scalar(ScalarValue::from("a")))
2406        }
2407    }
2408
2409    #[test]
2410    fn scalar_udf() -> Result<()> {
2411        let empty = empty();
2412
2413        let udf = ScalarUDF::from(TestScalarUDF {
2414            signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
2415        })
2416        .call(vec![lit(123_i32)]);
2417        let plan = LogicalPlan::Projection(Projection::try_new(vec![udf], empty)?);
2418
2419        assert_analyzed_plan_eq!(
2420            plan,
2421            @r"
2422        Projection: TestScalarUDF(Float32(123)) AS TestScalarUDF(Int32(123))
2423          EmptyRelation: rows=0
2424        "
2425        )
2426    }
2427
2428    #[test]
2429    fn scalar_udf_in_grouping_set() -> Result<()> {
2430        let udf = ScalarUDF::from(TestScalarUDF {
2431            signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
2432        })
2433        .call(vec![lit(123_i32)]);
2434        let schema = Schema::new(vec![Field::new("a", Utf8, false)]);
2435        let plan = table_scan(Some("t"), &schema, None)?
2436            .aggregate(
2437                vec![grouping_set(vec![
2438                    vec![col("t.a"), udf.clone()],
2439                    vec![udf],
2440                    vec![],
2441                ])],
2442                Vec::<Expr>::new(),
2443            )?
2444            .build()?;
2445
2446        // Each renamed member is aliased to its original name, not the grouping set
2447        let analyzed = TypeCoercion::new().analyze(plan, &ConfigOptions::default())?;
2448        assert_snapshot!(
2449            analyzed,
2450            @r#"
2451        Aggregate: groupBy=[[GROUPING SETS ((t.a, TestScalarUDF(Float32(123)) AS TestScalarUDF(Int32(123))), (TestScalarUDF(Float32(123)) AS TestScalarUDF(Int32(123))), ())]], aggr=[[]]
2452          TableScan: t
2453        "#
2454        );
2455
2456        // A second pass leaves the plan unchanged
2457        let reanalyzed =
2458            TypeCoercion::new().analyze(analyzed.clone(), &ConfigOptions::default())?;
2459        assert_eq!(analyzed, reanalyzed);
2460        Ok(())
2461    }
2462
2463    #[test]
2464    fn scalar_udf_invalid_input() -> Result<()> {
2465        let empty = empty();
2466        let udf = ScalarUDF::from(TestScalarUDF {
2467            signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
2468        })
2469        .call(vec![lit("Apple")]);
2470        Projection::try_new(vec![udf], empty)
2471            .expect_err("Expected an error due to incorrect function input");
2472
2473        Ok(())
2474    }
2475
2476    #[test]
2477    fn scalar_function() -> Result<()> {
2478        // test that automatic argument type coercion for scalar functions work
2479        let empty = empty();
2480        let lit_expr = lit(10i64);
2481        let fun = ScalarUDF::new_from_impl(TestScalarUDF {
2482            signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
2483        });
2484        let scalar_function_expr =
2485            Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![lit_expr]));
2486        let plan = LogicalPlan::Projection(Projection::try_new(
2487            vec![scalar_function_expr],
2488            empty,
2489        )?);
2490
2491        assert_analyzed_plan_eq!(
2492            plan,
2493            @r"
2494        Projection: TestScalarUDF(Float32(10)) AS TestScalarUDF(Int64(10))
2495          EmptyRelation: rows=0
2496        "
2497        )
2498    }
2499
2500    #[test]
2501    fn agg_udaf() -> Result<()> {
2502        let empty = empty();
2503        let my_avg = create_udaf(
2504            "MY_AVG",
2505            vec![DataType::Float64],
2506            Arc::new(DataType::Float64),
2507            Volatility::Immutable,
2508            Arc::new(|_| Ok(Box::<AvgAccumulator>::default())),
2509            Arc::new(vec![DataType::UInt64, DataType::Float64]),
2510        );
2511        let udaf = Expr::AggregateFunction(expr::AggregateFunction::new_udf(
2512            Arc::new(my_avg),
2513            vec![lit(10i64)],
2514            false,
2515            None,
2516            vec![],
2517            None,
2518        ));
2519        let plan = LogicalPlan::Projection(Projection::try_new(vec![udaf], empty)?);
2520
2521        assert_analyzed_plan_eq!(
2522            plan,
2523            @r"
2524        Projection: MY_AVG(CAST(Int64(10) AS Float64))
2525          EmptyRelation: rows=0
2526        "
2527        )
2528    }
2529
2530    #[test]
2531    fn agg_udaf_invalid_input() -> Result<()> {
2532        let empty = empty();
2533        let return_type = DataType::Float64;
2534        let accumulator: AccumulatorFactoryFunction =
2535            Arc::new(|_| Ok(Box::<AvgAccumulator>::default()));
2536        let my_avg = AggregateUDF::from(SimpleAggregateUDF::new_with_signature(
2537            "MY_AVG",
2538            Signature::uniform(1, vec![DataType::Float64], Volatility::Immutable),
2539            return_type,
2540            accumulator,
2541            vec![
2542                Field::new("count", DataType::UInt64, true).into(),
2543                Field::new("avg", DataType::Float64, true).into(),
2544            ],
2545        ));
2546        let udaf = Expr::AggregateFunction(expr::AggregateFunction::new_udf(
2547            Arc::new(my_avg),
2548            vec![lit("10")],
2549            false,
2550            None,
2551            vec![],
2552            None,
2553        ));
2554
2555        let err = Projection::try_new(vec![udaf], empty).err().unwrap();
2556        assert!(
2557            err.strip_backtrace().starts_with("Error during planning: Failed to coerce arguments to satisfy a call to 'MY_AVG' function: coercion from Utf8 to the signature Uniform(1, [Float64]) failed")
2558        );
2559        Ok(())
2560    }
2561
2562    #[test]
2563    fn agg_function_case() -> Result<()> {
2564        let empty = empty();
2565        let agg_expr = Expr::AggregateFunction(expr::AggregateFunction::new_udf(
2566            avg_udaf(),
2567            vec![lit(12f64)],
2568            false,
2569            None,
2570            vec![],
2571            None,
2572        ));
2573        let plan = LogicalPlan::Projection(Projection::try_new(vec![agg_expr], empty)?);
2574
2575        assert_analyzed_plan_eq!(
2576            plan,
2577            @r"
2578        Projection: avg(Float64(12))
2579          EmptyRelation: rows=0
2580        "
2581        )?;
2582
2583        let empty = empty_with_type(DataType::Int32);
2584        let agg_expr = Expr::AggregateFunction(expr::AggregateFunction::new_udf(
2585            avg_udaf(),
2586            vec![cast(col("a"), DataType::Float64)],
2587            false,
2588            None,
2589            vec![],
2590            None,
2591        ));
2592        let plan = LogicalPlan::Projection(Projection::try_new(vec![agg_expr], empty)?);
2593
2594        assert_analyzed_plan_eq!(
2595            plan,
2596            @r"
2597        Projection: avg(CAST(a AS Float64))
2598          EmptyRelation: rows=0
2599        "
2600        )
2601    }
2602
2603    #[test]
2604    fn agg_function_invalid_input_avg() -> Result<()> {
2605        let empty = empty();
2606        let agg_expr = Expr::AggregateFunction(expr::AggregateFunction::new_udf(
2607            avg_udaf(),
2608            vec![lit("1")],
2609            false,
2610            None,
2611            vec![],
2612            None,
2613        ));
2614        let err = Projection::try_new(vec![agg_expr], empty)
2615            .err()
2616            .unwrap()
2617            .strip_backtrace();
2618        assert!(
2619            err.contains("Function 'avg' failed to match any signature"),
2620            "Err: {err:?}"
2621        );
2622        Ok(())
2623    }
2624
2625    #[test]
2626    fn binary_op_date32_op_interval() -> Result<()> {
2627        // CAST(Utf8("1998-03-18") AS Date32) + IntervalDayTime("...")
2628        let expr = cast(lit("1998-03-18"), DataType::Date32)
2629            + lit(ScalarValue::new_interval_dt(123, 456));
2630        let empty = empty();
2631        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
2632
2633        assert_analyzed_plan_eq!(
2634            plan,
2635            @r#"
2636        Projection: CAST(Utf8("1998-03-18") AS Date32) + IntervalDayTime("IntervalDayTime { days: 123, milliseconds: 456 }")
2637          EmptyRelation: rows=0
2638        "#
2639        )
2640    }
2641
2642    #[test]
2643    fn inlist_case() -> Result<()> {
2644        // a in (1,4,8), a is int64
2645        let expr = col("a").in_list(vec![lit(1_i32), lit(4_i8), lit(8_i64)], false);
2646        let empty = empty_with_type(DataType::Int64);
2647        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
2648        assert_analyzed_plan_eq!(
2649            plan,
2650            @r"
2651        Projection: a IN ([CAST(Int32(1) AS Int64), CAST(Int8(4) AS Int64), Int64(8)])
2652          EmptyRelation: rows=0
2653        ")?;
2654
2655        // a in (1,4,8), a is decimal
2656        let expr = col("a").in_list(vec![lit(1_i32), lit(4_i8), lit(8_i64)], false);
2657        let empty = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
2658            produce_one_row: false,
2659            schema: Arc::new(DFSchema::from_unqualified_fields(
2660                vec![Field::new("a", DataType::Decimal128(12, 4), true)].into(),
2661                std::collections::HashMap::new(),
2662            )?),
2663        }));
2664        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
2665        assert_analyzed_plan_eq!(
2666            plan,
2667            @r"
2668        Projection: CAST(a AS Decimal128(24, 4)) IN ([CAST(Int32(1) AS Decimal128(24, 4)), CAST(Int8(4) AS Decimal128(24, 4)), CAST(Int64(8) AS Decimal128(24, 4))])
2669          EmptyRelation: rows=0
2670        ")
2671    }
2672
2673    #[test]
2674    fn between_case() -> Result<()> {
2675        let expr = col("a").between(
2676            lit("2002-05-08"),
2677            // (cast('2002-05-08' as date) + interval '1 months')
2678            cast(lit("2002-05-08"), DataType::Date32)
2679                + lit(ScalarValue::new_interval_ym(0, 1)),
2680        );
2681        let empty = empty_with_type(Utf8);
2682        let plan = LogicalPlan::Filter(Filter::try_new(expr, empty)?);
2683
2684        assert_analyzed_plan_eq!(
2685            plan,
2686            @r#"
2687        Filter: CAST(a AS Date32) BETWEEN CAST(Utf8("2002-05-08") AS Date32) AND CAST(Utf8("2002-05-08") AS Date32) + IntervalYearMonth("1")
2688          EmptyRelation: rows=0
2689        "#
2690        )
2691    }
2692
2693    #[test]
2694    fn between_infer_cheap_type() -> Result<()> {
2695        let expr = col("a").between(
2696            // (cast('2002-05-08' as date) + interval '1 months')
2697            cast(lit("2002-05-08"), DataType::Date32)
2698                + lit(ScalarValue::new_interval_ym(0, 1)),
2699            lit("2002-12-08"),
2700        );
2701        let empty = empty_with_type(Utf8);
2702        let plan = LogicalPlan::Filter(Filter::try_new(expr, empty)?);
2703
2704        // TODO: we should cast col(a).
2705        assert_analyzed_plan_eq!(
2706            plan,
2707            @r#"
2708        Filter: CAST(a AS Date32) BETWEEN CAST(Utf8("2002-05-08") AS Date32) + IntervalYearMonth("1") AND CAST(Utf8("2002-12-08") AS Date32)
2709          EmptyRelation: rows=0
2710        "#
2711        )
2712    }
2713
2714    #[test]
2715    fn between_null() -> Result<()> {
2716        let expr = lit(ScalarValue::Null).between(lit(ScalarValue::Null), lit(2i64));
2717        let empty = empty();
2718        let plan = LogicalPlan::Filter(Filter::try_new(expr, empty)?);
2719
2720        assert_analyzed_plan_eq!(
2721            plan,
2722            @r"
2723        Filter: CAST(NULL AS Int64) BETWEEN CAST(NULL AS Int64) AND Int64(2)
2724          EmptyRelation: rows=0
2725        "
2726        )
2727    }
2728
2729    #[test]
2730    fn is_bool_for_type_coercion() -> Result<()> {
2731        // is true
2732        let expr = col("a").is_true();
2733        let empty = empty_with_type(DataType::Boolean);
2734        let plan =
2735            LogicalPlan::Projection(Projection::try_new(vec![expr.clone()], empty)?);
2736
2737        assert_analyzed_plan_eq!(
2738            plan,
2739            @r"
2740        Projection: a IS TRUE
2741          EmptyRelation: rows=0
2742        "
2743        )?;
2744
2745        let empty = empty_with_type(DataType::Int64);
2746        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
2747        assert_type_coercion_error(
2748            plan,
2749            "Cannot infer common argument type for comparison operation Int64 IS DISTINCT FROM Boolean",
2750        )?;
2751
2752        // is not true
2753        let expr = col("a").is_not_true();
2754        let empty = empty_with_type(DataType::Boolean);
2755        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
2756
2757        assert_analyzed_plan_eq!(
2758            plan,
2759            @r"
2760        Projection: a IS NOT TRUE
2761          EmptyRelation: rows=0
2762        "
2763        )?;
2764
2765        // is false
2766        let expr = col("a").is_false();
2767        let empty = empty_with_type(DataType::Boolean);
2768        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
2769
2770        assert_analyzed_plan_eq!(
2771            plan,
2772            @r"
2773        Projection: a IS FALSE
2774          EmptyRelation: rows=0
2775        "
2776        )?;
2777
2778        // is not false
2779        let expr = col("a").is_not_false();
2780        let empty = empty_with_type(DataType::Boolean);
2781        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
2782
2783        assert_analyzed_plan_eq!(
2784            plan,
2785            @r"
2786        Projection: a IS NOT FALSE
2787          EmptyRelation: rows=0
2788        "
2789        )
2790    }
2791
2792    #[test]
2793    fn like_for_type_coercion() -> Result<()> {
2794        // like : utf8 like "abc"
2795        let expr = Box::new(col("a"));
2796        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2797        let like_expr = Expr::Like(Like::new(false, expr, pattern, None, false));
2798        let empty = empty_with_type(Utf8);
2799        let plan = LogicalPlan::Projection(Projection::try_new(vec![like_expr], empty)?);
2800
2801        assert_analyzed_plan_eq!(
2802            plan,
2803            @r#"
2804        Projection: a LIKE Utf8("abc")
2805          EmptyRelation: rows=0
2806        "#
2807        )?;
2808
2809        let expr = Box::new(col("a"));
2810        let pattern = Box::new(lit(ScalarValue::Null));
2811        let like_expr = Expr::Like(Like::new(false, expr, pattern, None, false));
2812        let empty = empty_with_type(Utf8);
2813        let plan = LogicalPlan::Projection(Projection::try_new(vec![like_expr], empty)?);
2814
2815        assert_analyzed_plan_eq!(
2816            plan,
2817            @r"
2818        Projection: a LIKE CAST(NULL AS Utf8)
2819          EmptyRelation: rows=0
2820        "
2821        )?;
2822
2823        let expr = Box::new(col("a"));
2824        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2825        let like_expr = Expr::Like(Like::new(false, expr, pattern, None, false));
2826        let empty = empty_with_type(DataType::Int64);
2827        let plan = LogicalPlan::Projection(Projection::try_new(vec![like_expr], empty)?);
2828        assert_type_coercion_error(
2829            plan,
2830            "There isn't a common type to coerce Int64 and Utf8 in LIKE expression",
2831        )?;
2832
2833        // ilike
2834        let expr = Box::new(col("a"));
2835        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2836        let ilike_expr = Expr::Like(Like::new(false, expr, pattern, None, true));
2837        let empty = empty_with_type(Utf8);
2838        let plan = LogicalPlan::Projection(Projection::try_new(vec![ilike_expr], empty)?);
2839
2840        assert_analyzed_plan_eq!(
2841            plan,
2842            @r#"
2843        Projection: a ILIKE Utf8("abc")
2844          EmptyRelation: rows=0
2845        "#
2846        )?;
2847
2848        let expr = Box::new(col("a"));
2849        let pattern = Box::new(lit(ScalarValue::Null));
2850        let ilike_expr = Expr::Like(Like::new(false, expr, pattern, None, true));
2851        let empty = empty_with_type(Utf8);
2852        let plan = LogicalPlan::Projection(Projection::try_new(vec![ilike_expr], empty)?);
2853
2854        assert_analyzed_plan_eq!(
2855            plan,
2856            @r"
2857        Projection: a ILIKE CAST(NULL AS Utf8)
2858          EmptyRelation: rows=0
2859        "
2860        )?;
2861
2862        let expr = Box::new(col("a"));
2863        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2864        let ilike_expr = Expr::Like(Like::new(false, expr, pattern, None, true));
2865        let empty = empty_with_type(DataType::Int64);
2866        let plan = LogicalPlan::Projection(Projection::try_new(vec![ilike_expr], empty)?);
2867        assert_type_coercion_error(
2868            plan,
2869            "There isn't a common type to coerce Int64 and Utf8 in ILIKE expression",
2870        )?;
2871
2872        Ok(())
2873    }
2874
2875    #[test]
2876    fn similar_to_for_type_coercion() -> Result<()> {
2877        // similar to : utf8 similar to "abc"
2878        let expr = Box::new(col("a"));
2879        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2880        let similar_to_expr =
2881            Expr::SimilarTo(Like::new(false, expr, pattern, None, false));
2882        let empty = empty_with_type(Utf8);
2883        let plan =
2884            LogicalPlan::Projection(Projection::try_new(vec![similar_to_expr], empty)?);
2885
2886        assert_analyzed_plan_eq!(
2887            plan,
2888            @r#"
2889        Projection: a SIMILAR TO Utf8("abc")
2890          EmptyRelation: rows=0
2891        "#
2892        )?;
2893
2894        // NULL pattern is coerced to a typed NULL instead of panicking
2895        // (https://github.com/apache/datafusion/issues/22886)
2896        let expr = Box::new(col("a"));
2897        let pattern = Box::new(lit(ScalarValue::Null));
2898        let similar_to_expr =
2899            Expr::SimilarTo(Like::new(false, expr, pattern, None, false));
2900        let empty = empty_with_type(Utf8);
2901        let plan =
2902            LogicalPlan::Projection(Projection::try_new(vec![similar_to_expr], empty)?);
2903
2904        assert_analyzed_plan_eq!(
2905            plan,
2906            @r"
2907        Projection: a SIMILAR TO CAST(NULL AS Utf8)
2908          EmptyRelation: rows=0
2909        "
2910        )?;
2911
2912        // Utf8View value and Utf8 pattern are coerced to Utf8View
2913        let expr = Box::new(col("a"));
2914        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2915        let similar_to_expr =
2916            Expr::SimilarTo(Like::new(false, expr, pattern, None, false));
2917        let empty = empty_with_type(DataType::Utf8View);
2918        let plan =
2919            LogicalPlan::Projection(Projection::try_new(vec![similar_to_expr], empty)?);
2920
2921        assert_analyzed_plan_eq!(
2922            plan,
2923            @r#"
2924        Projection: a SIMILAR TO CAST(Utf8("abc") AS Utf8View)
2925          EmptyRelation: rows=0
2926        "#
2927        )?;
2928
2929        // Utf8 value and Utf8View pattern are coerced to Utf8View
2930        let expr = Box::new(col("a"));
2931        let pattern = Box::new(lit(ScalarValue::Utf8View(Some("abc".to_string()))));
2932        let similar_to_expr =
2933            Expr::SimilarTo(Like::new(false, expr, pattern, None, false));
2934        let empty = empty_with_type(Utf8);
2935        let plan =
2936            LogicalPlan::Projection(Projection::try_new(vec![similar_to_expr], empty)?);
2937
2938        assert_analyzed_plan_eq!(
2939            plan,
2940            @r#"
2941        Projection: CAST(a AS Utf8View) SIMILAR TO Utf8View("abc")
2942          EmptyRelation: rows=0
2943        "#
2944        )?;
2945
2946        // Dictionary values are coerced to the common regex operand type
2947        let expr = Box::new(col("a"));
2948        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2949        let similar_to_expr =
2950            Expr::SimilarTo(Like::new(false, expr, pattern, None, false));
2951        let empty = empty_with_type(DataType::Dictionary(
2952            Box::new(DataType::Int32),
2953            Box::new(Utf8),
2954        ));
2955        let plan =
2956            LogicalPlan::Projection(Projection::try_new(vec![similar_to_expr], empty)?);
2957
2958        assert_analyzed_plan_eq!(
2959            plan,
2960            @r#"
2961        Projection: CAST(a AS Utf8) SIMILAR TO Utf8("abc")
2962          EmptyRelation: rows=0
2963        "#
2964        )?;
2965
2966        // incompatible types are a planning error, not a panic
2967        let expr = Box::new(col("a"));
2968        let pattern = Box::new(lit(ScalarValue::new_utf8("abc")));
2969        let similar_to_expr =
2970            Expr::SimilarTo(Like::new(false, expr, pattern, None, false));
2971        let empty = empty_with_type(DataType::Int64);
2972        let plan =
2973            LogicalPlan::Projection(Projection::try_new(vec![similar_to_expr], empty)?);
2974        assert_type_coercion_error(
2975            plan,
2976            "There isn't a common type to coerce Int64 and Utf8 in SIMILAR TO expression",
2977        )?;
2978
2979        Ok(())
2980    }
2981
2982    #[test]
2983    fn unknown_for_type_coercion() -> Result<()> {
2984        // unknown
2985        let expr = col("a").is_unknown();
2986        let empty = empty_with_type(DataType::Boolean);
2987        let plan =
2988            LogicalPlan::Projection(Projection::try_new(vec![expr.clone()], empty)?);
2989
2990        assert_analyzed_plan_eq!(
2991            plan,
2992            @r"
2993        Projection: a IS UNKNOWN
2994          EmptyRelation: rows=0
2995        "
2996        )?;
2997
2998        let empty = empty_with_type(Utf8);
2999        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
3000        assert_type_coercion_error(
3001            plan,
3002            "Cannot infer common argument type for comparison operation Utf8 IS DISTINCT FROM Boolean",
3003        )?;
3004
3005        // is not unknown
3006        let expr = col("a").is_not_unknown();
3007        let empty = empty_with_type(DataType::Boolean);
3008        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
3009
3010        assert_analyzed_plan_eq!(
3011            plan,
3012            @r"
3013        Projection: a IS NOT UNKNOWN
3014          EmptyRelation: rows=0
3015        "
3016        )
3017    }
3018
3019    #[test]
3020    fn concat_for_type_coercion() -> Result<()> {
3021        let empty = empty_with_type(Utf8);
3022        let args = [col("a"), lit("b"), lit(true), lit(false), lit(13)];
3023
3024        // concat-type signature
3025        let expr = ScalarUDF::new_from_impl(TestScalarUDF {
3026            signature: Signature::variadic(vec![Utf8], Volatility::Immutable),
3027        })
3028        .call(args.to_vec());
3029        let plan =
3030            LogicalPlan::Projection(Projection::try_new(vec![expr], Arc::clone(&empty))?);
3031        assert_analyzed_plan_eq!(
3032            plan,
3033            @r#"
3034        Projection: TestScalarUDF(a, Utf8("b"), Utf8("true"), Utf8("false"), Utf8("13")) AS TestScalarUDF(a,Utf8("b"),Boolean(true),Boolean(false),Int32(13))
3035          EmptyRelation: rows=0
3036        "#
3037        )
3038    }
3039
3040    #[test]
3041    fn test_type_coercion_rewrite() -> Result<()> {
3042        // gt
3043        let schema = Arc::new(DFSchema::from_unqualified_fields(
3044            vec![Field::new("a", DataType::Int64, true)].into(),
3045            std::collections::HashMap::new(),
3046        )?);
3047        let mut rewriter = TypeCoercionRewriter::new(&schema);
3048        let expr = is_true(lit(12i32).gt(lit(13i64)));
3049        let expected = is_true(cast(lit(12i32), DataType::Int64).gt(lit(13i64)));
3050        let result = expr.rewrite(&mut rewriter).data()?;
3051        assert_eq!(expected, result);
3052
3053        // eq
3054        let schema = Arc::new(DFSchema::from_unqualified_fields(
3055            vec![Field::new("a", DataType::Int64, true)].into(),
3056            std::collections::HashMap::new(),
3057        )?);
3058        let mut rewriter = TypeCoercionRewriter::new(&schema);
3059        let expr = is_true(lit(12i32).eq(lit(13i64)));
3060        let expected = is_true(cast(lit(12i32), DataType::Int64).eq(lit(13i64)));
3061        let result = expr.rewrite(&mut rewriter).data()?;
3062        assert_eq!(expected, result);
3063
3064        // lt
3065        let schema = Arc::new(DFSchema::from_unqualified_fields(
3066            vec![Field::new("a", DataType::Int64, true)].into(),
3067            std::collections::HashMap::new(),
3068        )?);
3069        let mut rewriter = TypeCoercionRewriter::new(&schema);
3070        let expr = is_true(lit(12i32).lt(lit(13i64)));
3071        let expected = is_true(cast(lit(12i32), DataType::Int64).lt(lit(13i64)));
3072        let result = expr.rewrite(&mut rewriter).data()?;
3073        assert_eq!(expected, result);
3074
3075        Ok(())
3076    }
3077
3078    #[test]
3079    fn binary_op_date32_eq_ts() -> Result<()> {
3080        let expr = cast(
3081            lit("1998-03-18"),
3082            DataType::Timestamp(TimeUnit::Nanosecond, None),
3083        )
3084        .eq(cast(lit("1998-03-18"), DataType::Date32));
3085        let empty = empty();
3086        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
3087
3088        assert_analyzed_plan_eq!(
3089            plan,
3090            @r#"
3091        Projection: CAST(Utf8("1998-03-18") AS Timestamp(ns)) = CAST(CAST(Utf8("1998-03-18") AS Date32) AS Timestamp(ns))
3092          EmptyRelation: rows=0
3093        "#
3094        )
3095    }
3096
3097    #[expect(
3098        clippy::unnecessary_box_returns,
3099        reason = "`Case` stores boxed expressions, so returning the box reuses the allocation"
3100    )]
3101    fn cast_if_not_same_type(
3102        expr: Box<Expr>,
3103        data_type: &DataType,
3104        schema: &DFSchemaRef,
3105    ) -> Box<Expr> {
3106        if &expr.get_type(schema).unwrap() != data_type {
3107            Box::new(cast(*expr, data_type.clone()))
3108        } else {
3109            expr
3110        }
3111    }
3112
3113    fn cast_helper(
3114        case: Case,
3115        case_when_type: &DataType,
3116        then_else_type: &DataType,
3117        schema: &DFSchemaRef,
3118    ) -> Case {
3119        let expr = case
3120            .expr
3121            .map(|e| cast_if_not_same_type(e, case_when_type, schema));
3122        let when_then_expr = case
3123            .when_then_expr
3124            .into_iter()
3125            .map(|(when, then)| {
3126                (
3127                    cast_if_not_same_type(when, case_when_type, schema),
3128                    cast_if_not_same_type(then, then_else_type, schema),
3129                )
3130            })
3131            .collect::<Vec<_>>();
3132        let else_expr = case
3133            .else_expr
3134            .map(|e| cast_if_not_same_type(e, then_else_type, schema));
3135
3136        Case {
3137            expr,
3138            when_then_expr,
3139            else_expr,
3140        }
3141    }
3142
3143    #[test]
3144    fn test_case_expression_coercion() -> Result<()> {
3145        let schema = Arc::new(DFSchema::from_unqualified_fields(
3146            vec![
3147                Field::new("boolean", DataType::Boolean, true),
3148                Field::new("integer", DataType::Int32, true),
3149                Field::new("float", DataType::Float32, true),
3150                Field::new(
3151                    "timestamp",
3152                    DataType::Timestamp(TimeUnit::Nanosecond, None),
3153                    true,
3154                ),
3155                Field::new("date", DataType::Date32, true),
3156                Field::new(
3157                    "interval",
3158                    DataType::Interval(arrow::datatypes::IntervalUnit::MonthDayNano),
3159                    true,
3160                ),
3161                Field::new("binary", DataType::Binary, true),
3162                Field::new("string", Utf8, true),
3163                Field::new("decimal", DataType::Decimal128(10, 10), true),
3164            ]
3165            .into(),
3166            std::collections::HashMap::new(),
3167        )?);
3168
3169        let case = Case {
3170            expr: None,
3171            when_then_expr: vec![
3172                (Box::new(col("boolean")), Box::new(col("integer"))),
3173                (Box::new(col("integer")), Box::new(col("float"))),
3174                (Box::new(col("string")), Box::new(col("string"))),
3175            ],
3176            else_expr: None,
3177        };
3178        let case_when_common_type = DataType::Boolean;
3179        let then_else_common_type = Utf8;
3180        let expected = cast_helper(
3181            case.clone(),
3182            &case_when_common_type,
3183            &then_else_common_type,
3184            &schema,
3185        );
3186        let actual = coerce_case_expression(case, &schema, None)?;
3187        assert_eq!(expected, actual);
3188
3189        // CASE string WHEN float/integer/string: comparison coercion
3190        // prefers numeric, so the common type for the CASE expr and
3191        // WHEN values is Float32.
3192        let case = Case {
3193            expr: Some(Box::new(col("string"))),
3194            when_then_expr: vec![
3195                (Box::new(col("float")), Box::new(col("integer"))),
3196                (Box::new(col("integer")), Box::new(col("float"))),
3197                (Box::new(col("string")), Box::new(col("string"))),
3198            ],
3199            else_expr: Some(Box::new(col("string"))),
3200        };
3201        let case_when_common_type = DataType::Float32;
3202        let then_else_common_type = Utf8;
3203        let expected = cast_helper(
3204            case.clone(),
3205            &case_when_common_type,
3206            &then_else_common_type,
3207            &schema,
3208        );
3209        let actual = coerce_case_expression(case, &schema, None)?;
3210        assert_eq!(expected, actual);
3211
3212        let case = Case {
3213            expr: Some(Box::new(col("interval"))),
3214            when_then_expr: vec![
3215                (Box::new(col("float")), Box::new(col("integer"))),
3216                (Box::new(col("binary")), Box::new(col("float"))),
3217                (Box::new(col("string")), Box::new(col("string"))),
3218            ],
3219            else_expr: Some(Box::new(col("string"))),
3220        };
3221        let err = coerce_case_expression(case, &schema, None).unwrap_err();
3222        assert_snapshot!(
3223            err.strip_backtrace(),
3224            @"Error during planning: Failed to coerce case (Interval(MonthDayNano)) and when (Float32, Binary, Utf8) to common types in CASE WHEN expression"
3225        );
3226
3227        let case = Case {
3228            expr: Some(Box::new(col("string"))),
3229            when_then_expr: vec![
3230                (Box::new(col("float")), Box::new(col("date"))),
3231                (Box::new(col("string")), Box::new(col("float"))),
3232                (Box::new(col("string")), Box::new(col("binary"))),
3233            ],
3234            else_expr: Some(Box::new(col("timestamp"))),
3235        };
3236        let err = coerce_case_expression(case, &schema, None).unwrap_err();
3237        assert_snapshot!(
3238            err.strip_backtrace(),
3239            @"Error during planning: Failed to coerce then (Date32, Float32, Binary) and else (Timestamp(ns)) to common types in CASE WHEN expression"
3240        );
3241
3242        Ok(())
3243    }
3244
3245    macro_rules! test_case_expression {
3246        ($expr:expr, $when_then:expr, $case_when_type:expr, $then_else_type:expr, $schema:expr) => {
3247            let case = Case {
3248                expr: $expr.map(|e| Box::new(col(e))),
3249                when_then_expr: $when_then,
3250                else_expr: None,
3251            };
3252
3253            let expected =
3254                cast_helper(case.clone(), &$case_when_type, &$then_else_type, &$schema);
3255
3256            let actual = coerce_case_expression(case, &$schema, None)?;
3257            assert_eq!(expected, actual);
3258        };
3259    }
3260
3261    #[test]
3262    fn tes_case_when_list() -> Result<()> {
3263        let inner_field = Arc::new(Field::new_list_field(DataType::Int64, true));
3264        let schema = Arc::new(DFSchema::from_unqualified_fields(
3265            vec![
3266                Field::new(
3267                    "large_list",
3268                    DataType::LargeList(Arc::clone(&inner_field)),
3269                    true,
3270                ),
3271                Field::new(
3272                    "fixed_list",
3273                    DataType::FixedSizeList(Arc::clone(&inner_field), 3),
3274                    true,
3275                ),
3276                Field::new("list", DataType::List(inner_field), true),
3277            ]
3278            .into(),
3279            std::collections::HashMap::new(),
3280        )?);
3281
3282        test_case_expression!(
3283            Some("list"),
3284            vec![(Box::new(col("large_list")), Box::new(lit("1")))],
3285            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3286            Utf8,
3287            schema
3288        );
3289
3290        test_case_expression!(
3291            Some("large_list"),
3292            vec![(Box::new(col("list")), Box::new(lit("1")))],
3293            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3294            Utf8,
3295            schema
3296        );
3297
3298        test_case_expression!(
3299            Some("list"),
3300            vec![(Box::new(col("fixed_list")), Box::new(lit("1")))],
3301            DataType::List(Arc::new(Field::new_list_field(DataType::Int64, true))),
3302            Utf8,
3303            schema
3304        );
3305
3306        test_case_expression!(
3307            Some("fixed_list"),
3308            vec![(Box::new(col("list")), Box::new(lit("1")))],
3309            DataType::List(Arc::new(Field::new_list_field(DataType::Int64, true))),
3310            Utf8,
3311            schema
3312        );
3313
3314        test_case_expression!(
3315            Some("fixed_list"),
3316            vec![(Box::new(col("large_list")), Box::new(lit("1")))],
3317            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3318            Utf8,
3319            schema
3320        );
3321
3322        test_case_expression!(
3323            Some("large_list"),
3324            vec![(Box::new(col("fixed_list")), Box::new(lit("1")))],
3325            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3326            Utf8,
3327            schema
3328        );
3329        Ok(())
3330    }
3331
3332    #[test]
3333    fn test_then_else_list() -> Result<()> {
3334        let inner_field = Arc::new(Field::new_list_field(DataType::Int64, true));
3335        let schema = Arc::new(DFSchema::from_unqualified_fields(
3336            vec![
3337                Field::new("boolean", DataType::Boolean, true),
3338                Field::new(
3339                    "large_list",
3340                    DataType::LargeList(Arc::clone(&inner_field)),
3341                    true,
3342                ),
3343                Field::new(
3344                    "fixed_list",
3345                    DataType::FixedSizeList(Arc::clone(&inner_field), 3),
3346                    true,
3347                ),
3348                Field::new("list", DataType::List(inner_field), true),
3349            ]
3350            .into(),
3351            std::collections::HashMap::new(),
3352        )?);
3353
3354        // large list and list
3355        test_case_expression!(
3356            None::<String>,
3357            vec![
3358                (Box::new(col("boolean")), Box::new(col("large_list"))),
3359                (Box::new(col("boolean")), Box::new(col("list")))
3360            ],
3361            DataType::Boolean,
3362            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3363            schema
3364        );
3365
3366        test_case_expression!(
3367            None::<String>,
3368            vec![
3369                (Box::new(col("boolean")), Box::new(col("list"))),
3370                (Box::new(col("boolean")), Box::new(col("large_list")))
3371            ],
3372            DataType::Boolean,
3373            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3374            schema
3375        );
3376
3377        // fixed list and list
3378        test_case_expression!(
3379            None::<String>,
3380            vec![
3381                (Box::new(col("boolean")), Box::new(col("fixed_list"))),
3382                (Box::new(col("boolean")), Box::new(col("list")))
3383            ],
3384            DataType::Boolean,
3385            DataType::List(Arc::new(Field::new_list_field(DataType::Int64, true))),
3386            schema
3387        );
3388
3389        test_case_expression!(
3390            None::<String>,
3391            vec![
3392                (Box::new(col("boolean")), Box::new(col("list"))),
3393                (Box::new(col("boolean")), Box::new(col("fixed_list")))
3394            ],
3395            DataType::Boolean,
3396            DataType::List(Arc::new(Field::new_list_field(DataType::Int64, true))),
3397            schema
3398        );
3399
3400        // fixed list and large list
3401        test_case_expression!(
3402            None::<String>,
3403            vec![
3404                (Box::new(col("boolean")), Box::new(col("fixed_list"))),
3405                (Box::new(col("boolean")), Box::new(col("large_list")))
3406            ],
3407            DataType::Boolean,
3408            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3409            schema
3410        );
3411
3412        test_case_expression!(
3413            None::<String>,
3414            vec![
3415                (Box::new(col("boolean")), Box::new(col("large_list"))),
3416                (Box::new(col("boolean")), Box::new(col("fixed_list")))
3417            ],
3418            DataType::Boolean,
3419            DataType::LargeList(Arc::new(Field::new_list_field(DataType::Int64, true))),
3420            schema
3421        );
3422        Ok(())
3423    }
3424
3425    #[test]
3426    fn test_map_with_diff_name() -> Result<()> {
3427        let mut builder = SchemaBuilder::new();
3428        builder.push(Field::new("key", Utf8, false));
3429        builder.push(Field::new("value", DataType::Float64, true));
3430        let struct_fields = builder.finish().fields;
3431
3432        let fields =
3433            Field::new("entries", DataType::Struct(struct_fields.clone()), false);
3434        let map_type_entries = DataType::Map(Arc::new(fields), false);
3435
3436        let fields = Field::new("key_value", DataType::Struct(struct_fields), false);
3437        let may_type_custom = DataType::Map(Arc::new(fields), false);
3438
3439        let expr = col("a").eq(cast(col("a"), may_type_custom));
3440        let empty = empty_with_type(map_type_entries);
3441        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
3442
3443        assert_analyzed_plan_eq!(
3444            plan,
3445            @r#"
3446        Projection: a = CAST(CAST(a AS Map("key_value": non-null Struct("key": non-null Utf8, "value": Float64), unsorted)) AS Map("entries": non-null Struct("key": non-null Utf8, "value": Float64), unsorted))
3447          EmptyRelation: rows=0
3448        "#
3449        )
3450    }
3451
3452    #[test]
3453    fn array_element_preserves_parquet_list_field_name() -> Result<()> {
3454        let list_type = DataType::List(Arc::new(Field::new(
3455            "element",
3456            DataType::Struct(
3457                vec![
3458                    Field::new("id", Utf8, true),
3459                    Field::new("prim", DataType::Boolean, true),
3460                ]
3461                .into(),
3462            ),
3463            true,
3464        )));
3465
3466        let expr = ScalarUDF::from(TestArrayElementUDF).call(vec![col("a"), lit(1_i64)]);
3467        let empty = empty_with_type(list_type);
3468        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
3469
3470        assert_analyzed_plan_eq!(
3471            plan,
3472            @r#"
3473        Projection: TestArrayElementUDF(a, Int64(1))
3474          EmptyRelation: rows=0
3475        "#
3476        )
3477    }
3478
3479    #[test]
3480    fn interval_plus_timestamp() -> Result<()> {
3481        // SELECT INTERVAL '1' YEAR + '2000-01-01T00:00:00'::timestamp;
3482        let expr = Expr::BinaryExpr(BinaryExpr::new(
3483            Box::new(lit(ScalarValue::IntervalYearMonth(Some(12)))),
3484            Operator::Plus,
3485            Box::new(cast(
3486                lit("2000-01-01T00:00:00"),
3487                DataType::Timestamp(TimeUnit::Nanosecond, None),
3488            )),
3489        ));
3490        let empty = empty();
3491        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
3492
3493        assert_analyzed_plan_eq!(
3494            plan,
3495            @r#"
3496        Projection: IntervalYearMonth("12") + CAST(Utf8("2000-01-01T00:00:00") AS Timestamp(ns))
3497          EmptyRelation: rows=0
3498        "#
3499        )
3500    }
3501
3502    #[test]
3503    fn timestamp_subtract_timestamp() -> Result<()> {
3504        let expr = Expr::BinaryExpr(BinaryExpr::new(
3505            Box::new(cast(
3506                lit("1998-03-18"),
3507                DataType::Timestamp(TimeUnit::Nanosecond, None),
3508            )),
3509            Operator::Minus,
3510            Box::new(cast(
3511                lit("1998-03-18"),
3512                DataType::Timestamp(TimeUnit::Nanosecond, None),
3513            )),
3514        ));
3515        let empty = empty();
3516        let plan = LogicalPlan::Projection(Projection::try_new(vec![expr], empty)?);
3517
3518        assert_analyzed_plan_eq!(
3519            plan,
3520            @r#"
3521        Projection: CAST(Utf8("1998-03-18") AS Timestamp(ns)) - CAST(Utf8("1998-03-18") AS Timestamp(ns))
3522          EmptyRelation: rows=0
3523        "#
3524        )
3525    }
3526
3527    #[test]
3528    fn timestamp_subtraction_uses_session_timezone() -> Result<()> {
3529        let schema = DFSchema::from_unqualified_fields(
3530            vec![
3531                Field::new(
3532                    "tstz",
3533                    DataType::Timestamp(
3534                        TimeUnit::Second,
3535                        Some("America/New_York".into()),
3536                    ),
3537                    true,
3538                ),
3539                Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),
3540            ]
3541            .into(),
3542            std::collections::HashMap::new(),
3543        )?;
3544        let input = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
3545            produce_one_row: false,
3546            schema: Arc::new(schema),
3547        }));
3548        let subtract = |left, right| {
3549            Expr::BinaryExpr(BinaryExpr::new(
3550                Box::new(col(left)),
3551                Operator::Minus,
3552                Box::new(col(right)),
3553            ))
3554        };
3555        let plan = LogicalPlan::Projection(Projection::try_new(
3556            vec![subtract("tstz", "ts"), subtract("ts", "tstz")],
3557            input,
3558        )?);
3559
3560        let mut options = ConfigOptions::default();
3561        options.execution.time_zone = Some("+08:00".parse()?);
3562        let rule = Arc::new(TypeCoercion::new());
3563        assert_analyzed_plan_with_config_eq_snapshot!(
3564            options,
3565            rule,
3566            plan,
3567            @r#"
3568        Projection: CAST(tstz AS Timestamp(ns, "+08:00")) - CAST(ts AS Timestamp(ns, "+08:00")), CAST(ts AS Timestamp(ns, "+08:00")) - CAST(tstz AS Timestamp(ns, "+08:00"))
3569          EmptyRelation: rows=0
3570        "#,
3571        )
3572    }
3573
3574    #[test]
3575    fn in_subquery_cast_subquery() -> Result<()> {
3576        let empty_int32 = empty_with_type(DataType::Int32);
3577        let empty_int64 = empty_with_type(DataType::Int64);
3578
3579        let in_subquery_expr = Expr::InSubquery(InSubquery::new(
3580            Box::new(col("a")),
3581            Subquery {
3582                subquery: empty_int32,
3583                outer_ref_columns: vec![],
3584                spans: Spans::new(),
3585            },
3586            false,
3587        ));
3588        let plan = LogicalPlan::Filter(Filter::try_new(in_subquery_expr, empty_int64)?);
3589        // add cast for subquery
3590
3591        assert_analyzed_plan_eq!(
3592            plan,
3593            @r"
3594        Filter: a IN (<subquery>)
3595          Subquery:
3596            Projection: CAST(a AS Int64)
3597              EmptyRelation: rows=0
3598          EmptyRelation: rows=0
3599        "
3600        )
3601    }
3602
3603    #[test]
3604    fn in_subquery_cast_expr() -> Result<()> {
3605        let empty_int32 = empty_with_type(DataType::Int32);
3606        let empty_int64 = empty_with_type(DataType::Int64);
3607
3608        let in_subquery_expr = Expr::InSubquery(InSubquery::new(
3609            Box::new(col("a")),
3610            Subquery {
3611                subquery: empty_int64,
3612                outer_ref_columns: vec![],
3613                spans: Spans::new(),
3614            },
3615            false,
3616        ));
3617        let plan = LogicalPlan::Filter(Filter::try_new(in_subquery_expr, empty_int32)?);
3618
3619        // add cast for subquery
3620        assert_analyzed_plan_eq!(
3621            plan,
3622            @r"
3623        Filter: CAST(a AS Int64) IN (<subquery>)
3624          Subquery:
3625            EmptyRelation: rows=0
3626          EmptyRelation: rows=0
3627        "
3628        )
3629    }
3630
3631    #[test]
3632    fn in_subquery_cast_all() -> Result<()> {
3633        let empty_inside = empty_with_type(DataType::Decimal128(10, 5));
3634        let empty_outside = empty_with_type(DataType::Decimal128(8, 8));
3635
3636        let in_subquery_expr = Expr::InSubquery(InSubquery::new(
3637            Box::new(col("a")),
3638            Subquery {
3639                subquery: empty_inside,
3640                outer_ref_columns: vec![],
3641                spans: Spans::new(),
3642            },
3643            false,
3644        ));
3645        let plan = LogicalPlan::Filter(Filter::try_new(in_subquery_expr, empty_outside)?);
3646
3647        // add cast for subquery
3648        assert_analyzed_plan_eq!(
3649            plan,
3650            @r"
3651        Filter: CAST(a AS Decimal128(13, 8)) IN (<subquery>)
3652          Subquery:
3653            Projection: CAST(a AS Decimal128(13, 8))
3654              EmptyRelation: rows=0
3655          EmptyRelation: rows=0
3656        "
3657        )
3658    }
3659
3660    #[test]
3661    fn timestamp_set_comparison_uses_session_timezone() -> Result<()> {
3662        let outer = empty_with_type(DataType::Timestamp(
3663            TimeUnit::Second,
3664            Some("America/New_York".into()),
3665        ));
3666        let subquery = empty_with_type(DataType::Timestamp(TimeUnit::Nanosecond, None));
3667        let set_comparison = Expr::SetComparison(SetComparison::new(
3668            Box::new(col("a")),
3669            Subquery {
3670                subquery,
3671                outer_ref_columns: vec![],
3672                spans: Spans::new(),
3673            },
3674            Operator::Eq,
3675            SetQuantifier::Any,
3676        ));
3677        let plan = LogicalPlan::Filter(Filter::try_new(set_comparison, outer)?);
3678
3679        let mut options = ConfigOptions::default();
3680        options.execution.time_zone = Some("+08:00".parse()?);
3681        let rule = Arc::new(TypeCoercion::new());
3682        assert_analyzed_plan_with_config_eq_snapshot!(
3683            options,
3684            rule,
3685            plan,
3686            @r#"
3687        Filter: CAST(a AS Timestamp(ns, "+08:00")) = ANY (<subquery>)
3688          Subquery:
3689            Projection: CAST(a AS Timestamp(ns, "+08:00"))
3690              EmptyRelation: rows=0
3691          EmptyRelation: rows=0
3692        "#,
3693        )
3694    }
3695}