datafusion_expr/type_coercion/other.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use arrow::datatypes::{DataType, Field};
6use datafusion_common::{Result, plan_datafusion_err, plan_err};
7
8use super::binary::{comparison_coercion, type_union_coercion};
9
10/// Fold `coerce_fn` over `types`, starting from `initial_type`.
11fn fold_coerce(
12 initial_type: &DataType,
13 types: &[DataType],
14 coerce_fn: fn(&DataType, &DataType) -> Option<DataType>,
15) -> Option<DataType> {
16 types
17 .iter()
18 .try_fold(initial_type.clone(), |left_type, right_type| {
19 coerce_fn(&left_type, right_type)
20 })
21}
22
23/// Infer a common output type for one UNION column, in input order.
24///
25/// Field names are used only to report incompatible inputs. This does not
26/// insert casts or require input expressions to have been analyzed.
27pub fn coerce_union_type<'a>(
28 fields: impl IntoIterator<Item = &'a Field>,
29) -> Result<DataType> {
30 let mut fields = fields.into_iter();
31 let Some(first) = fields.next() else {
32 return plan_err!("UNION requires at least one input field");
33 };
34 fields.try_fold(first.data_type().clone(), |data_type, field| {
35 type_union_coercion(&data_type, field.data_type()).ok_or_else(|| {
36 plan_datafusion_err!(
37 "Incompatible inputs for Union: Previous inputs were \
38 of type {}, but got incompatible type {} on column '{}'",
39 data_type,
40 field.data_type(),
41 field.name()
42 )
43 })
44 })
45}
46
47/// Attempts to coerce the types of `list_types` to be comparable with the
48/// `expr_type` for IN list predicates.
49/// Returns the common data type for `expr_type` and `list_types`.
50///
51/// Uses comparison coercion because `x IN (a, b)` is semantically equivalent
52/// to `x = a OR x = b`.
53///
54/// # Deprecated
55///
56/// This no longer matches how the planner coerces `IN`: `=` reads a
57/// timezone-naive timestamp in `datafusion.execution.time_zone` when it is
58/// compared against a timezone-aware one, and this function cannot, because it
59/// has nowhere to take that setting from. Fold
60/// [`comparison_coercion_with_session_timezone`] over the values instead:
61///
62/// ```
63/// # use arrow::datatypes::DataType;
64/// # use datafusion_expr::type_coercion::binary::comparison_coercion_with_session_timezone;
65/// # let expr_type = DataType::Int32;
66/// # let list_types = [DataType::Int64];
67/// # let session_time_zone = Some("+08:00");
68/// let coerced = list_types.iter().try_fold(expr_type, |left, right| {
69/// comparison_coercion_with_session_timezone(&left, right, session_time_zone)
70/// });
71/// # assert_eq!(coerced, Some(DataType::Int64));
72/// ```
73///
74/// [`comparison_coercion_with_session_timezone`]: super::binary::comparison_coercion_with_session_timezone
75#[deprecated(
76 since = "56.0.0",
77 note = "Fold `comparison_coercion_with_session_timezone` over the values instead, so `IN` coerces exactly as `=` does"
78)]
79pub fn get_coerce_type_for_list(
80 expr_type: &DataType,
81 list_types: &[DataType],
82) -> Option<DataType> {
83 fold_coerce(expr_type, list_types, comparison_coercion)
84}
85
86/// Find a common coerceable type for `CASE expr WHEN val1 WHEN val2 ...`
87/// conditions. Returns the common type for `case_type` and all `when_types`.
88///
89/// Uses comparison coercion because `CASE expr WHEN val` is semantically
90/// equivalent to `expr = val`.
91///
92/// # Deprecated
93///
94/// Deprecated for the same reason as [`get_coerce_type_for_list`]: it cannot
95/// apply the `datafusion.execution.time_zone` rule that `=` applies. Fold
96/// [`comparison_coercion_with_session_timezone`] over `when_types` instead.
97///
98/// [`comparison_coercion_with_session_timezone`]: super::binary::comparison_coercion_with_session_timezone
99#[deprecated(
100 since = "56.0.0",
101 note = "Fold `comparison_coercion_with_session_timezone` over the values instead, so `CASE expr WHEN` coerces exactly as `=` does"
102)]
103pub fn get_coerce_type_for_case_when(
104 when_types: &[DataType],
105 case_type: &DataType,
106) -> Option<DataType> {
107 fold_coerce(case_type, when_types, comparison_coercion)
108}
109
110/// Find a common coerceable type for CASE THEN/ELSE result expressions.
111/// Returns the common data type for `then_types` and `else_type`.
112///
113/// Uses type union coercion because the result branches must be brought to a
114/// common type (like UNION), not compared.
115pub fn get_coerce_type_for_case_expression(
116 then_types: &[DataType],
117 else_type: Option<&DataType>,
118) -> Option<DataType> {
119 let (initial_type, remaining) = match else_type {
120 None => then_types.split_first()?,
121 Some(data_type) => (data_type, then_types),
122 };
123 fold_coerce(initial_type, remaining, type_union_coercion)
124}