Skip to main content

datafusion_expr/type_coercion/
other.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use arrow::datatypes::DataType;
19
20use super::binary::{comparison_coercion, type_union_coercion};
21
22/// Fold `coerce_fn` over `types`, starting from `initial_type`.
23fn fold_coerce(
24    initial_type: &DataType,
25    types: &[DataType],
26    coerce_fn: fn(&DataType, &DataType) -> Option<DataType>,
27) -> Option<DataType> {
28    types
29        .iter()
30        .try_fold(initial_type.clone(), |left_type, right_type| {
31            coerce_fn(&left_type, right_type)
32        })
33}
34
35/// Attempts to coerce the types of `list_types` to be comparable with the
36/// `expr_type` for IN list predicates.
37/// Returns the common data type for `expr_type` and `list_types`.
38///
39/// Uses comparison coercion because `x IN (a, b)` is semantically equivalent
40/// to `x = a OR x = b`.
41pub fn get_coerce_type_for_list(
42    expr_type: &DataType,
43    list_types: &[DataType],
44) -> Option<DataType> {
45    fold_coerce(expr_type, list_types, comparison_coercion)
46}
47
48/// Find a common coerceable type for `CASE expr WHEN val1 WHEN val2 ...`
49/// conditions. Returns the common type for `case_type` and all `when_types`.
50///
51/// Uses comparison coercion because `CASE expr WHEN val` is semantically
52/// equivalent to `expr = val`.
53pub fn get_coerce_type_for_case_when(
54    when_types: &[DataType],
55    case_type: &DataType,
56) -> Option<DataType> {
57    fold_coerce(case_type, when_types, comparison_coercion)
58}
59
60/// Find a common coerceable type for CASE THEN/ELSE result expressions.
61/// Returns the common data type for `then_types` and `else_type`.
62///
63/// Uses type union coercion because the result branches must be brought to a
64/// common type (like UNION), not compared.
65pub fn get_coerce_type_for_case_expression(
66    then_types: &[DataType],
67    else_type: Option<&DataType>,
68) -> Option<DataType> {
69    let (initial_type, remaining) = match else_type {
70        None => then_types.split_first()?,
71        Some(data_type) => (data_type, then_types),
72    };
73    fold_coerce(initial_type, remaining, type_union_coercion)
74}