Skip to main content

datafusion_functions_nested/
planner.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//! SQL planning extensions like [`NestedFunctionPlanner`] and [`FieldAccessPlanner`]
6
7use arrow::datatypes::DataType;
8use datafusion_common::{DFSchema, Result, plan_err, utils::list_ndims};
9use datafusion_expr::AggregateUDF;
10use datafusion_expr::expr::ScalarFunction;
11use datafusion_expr::expr::{AggregateFunction, AggregateFunctionParams};
12#[cfg(feature = "sql")]
13use datafusion_expr::sqlparser::ast::BinaryOperator;
14use datafusion_expr::{
15    Expr, ExprSchemable, GetFieldAccess,
16    planner::{ExprPlanner, PlannerResult, RawBinaryExpr, RawFieldAccessExpr},
17};
18#[cfg(not(feature = "sql"))]
19use datafusion_expr_common::operator::Operator as BinaryOperator;
20use datafusion_functions::core::get_field as get_field_inner;
21use datafusion_functions::expr_fn::get_field;
22use datafusion_functions_aggregate::nth_value::nth_value_udaf;
23use std::sync::Arc;
24
25use crate::map::map_udf;
26use crate::{
27    array_has::array_has_all,
28    expr_fn::{array_append, array_concat, array_prepend},
29    extract::{array_element, array_slice},
30    make_array::make_array,
31};
32
33#[derive(Debug)]
34pub struct NestedFunctionPlanner;
35
36impl ExprPlanner for NestedFunctionPlanner {
37    fn plan_binary_op(
38        &self,
39        expr: RawBinaryExpr,
40        schema: &DFSchema,
41    ) -> Result<PlannerResult<RawBinaryExpr>> {
42        let RawBinaryExpr { op, left, right } = expr;
43
44        if op == BinaryOperator::StringConcat {
45            let left_type = left.get_type(schema)?;
46            let right_type = right.get_type(schema)?;
47            let left_list_ndims = list_ndims(&left_type);
48            let right_list_ndims = list_ndims(&right_type);
49
50            // Rewrite string concat operator to function based on types
51            // if we get list || list then we rewrite it to array_concat()
52            // if we get list || non-list then we rewrite it to array_append()
53            // if we get non-list || list then we rewrite it to array_prepend()
54            // if we get string || string then we rewrite it to concat()
55
56            // We determine the target function to rewrite based on the list n-dimension, the check is not exact but sufficient.
57            // The exact validity check is handled in the actual function, so even if there is 3d list appended with 1d list, it is also fine to rewrite.
58            if left_list_ndims + right_list_ndims == 0 {
59                // TODO: concat function ignore null, but string concat takes null into consideration
60                // we can rewrite it to concat if we can configure the behaviour of concat function to the one like `string concat operator`
61            } else if left_list_ndims == right_list_ndims {
62                return Ok(PlannerResult::Planned(array_concat(vec![left, right])));
63            } else if left_list_ndims > right_list_ndims {
64                return Ok(PlannerResult::Planned(array_append(left, right)));
65            } else if left_list_ndims < right_list_ndims {
66                return Ok(PlannerResult::Planned(array_prepend(left, right)));
67            }
68        } else if matches!(op, BinaryOperator::AtArrow | BinaryOperator::ArrowAt) {
69            let left_type = left.get_type(schema)?;
70            let right_type = right.get_type(schema)?;
71            let left_list_ndims = list_ndims(&left_type);
72            let right_list_ndims = list_ndims(&right_type);
73            // if both are list
74            if left_list_ndims > 0 && right_list_ndims > 0 {
75                if op == BinaryOperator::AtArrow {
76                    // array1 @> array2 -> array_has_all(array1, array2)
77                    return Ok(PlannerResult::Planned(array_has_all(left, right)));
78                } else {
79                    // array1 <@ array2 -> array_has_all(array2, array1)
80                    return Ok(PlannerResult::Planned(array_has_all(right, left)));
81                }
82            }
83        }
84
85        Ok(PlannerResult::Original(RawBinaryExpr { op, left, right }))
86    }
87
88    fn plan_array_literal(
89        &self,
90        exprs: Vec<Expr>,
91        _schema: &DFSchema,
92    ) -> Result<PlannerResult<Vec<Expr>>> {
93        Ok(PlannerResult::Planned(make_array(exprs)))
94    }
95
96    fn plan_make_map(&self, args: Vec<Expr>) -> Result<PlannerResult<Vec<Expr>>> {
97        if !args.len().is_multiple_of(2) {
98            return plan_err!("make_map requires an even number of arguments");
99        }
100
101        let (keys, values): (Vec<_>, Vec<_>) =
102            args.into_iter().enumerate().partition(|(i, _)| i % 2 == 0);
103        let keys = make_array(keys.into_iter().map(|(_, e)| e).collect());
104        let values = make_array(values.into_iter().map(|(_, e)| e).collect());
105
106        Ok(PlannerResult::Planned(Expr::ScalarFunction(
107            ScalarFunction::new_udf(map_udf(), vec![keys, values]),
108        )))
109    }
110}
111
112#[derive(Debug)]
113pub struct FieldAccessPlanner;
114impl ExprPlanner for FieldAccessPlanner {
115    fn plan_field_access(
116        &self,
117        expr: RawFieldAccessExpr,
118        schema: &DFSchema,
119    ) -> Result<PlannerResult<RawFieldAccessExpr>> {
120        let RawFieldAccessExpr { expr, field_access } = expr;
121
122        match field_access {
123            // expr["field"] => get_field(expr, "field")
124            // Nested accesses like expr["a"]["b"] create nested get_field calls,
125            // which are then merged by the SimplifyExpressions optimizer pass via
126            // the GetFieldFunc::simplify() method.
127            GetFieldAccess::NamedStructField { name } => {
128                Ok(PlannerResult::Planned(get_field(expr, name)))
129            }
130            // expr[idx] ==> array_element(expr, idx)
131            GetFieldAccess::ListIndex { key: index } => {
132                match expr {
133                    // Special case for array_agg(expr)[index] to NTH_VALUE(expr, index)
134                    Expr::AggregateFunction(AggregateFunction {
135                        func,
136                        params:
137                            AggregateFunctionParams {
138                                args,
139                                distinct,
140                                filter,
141                                order_by,
142                                null_treatment,
143                            },
144                    }) if is_array_agg(&func) => Ok(PlannerResult::Planned(
145                        Expr::AggregateFunction(AggregateFunction::new_udf(
146                            nth_value_udaf(),
147                            args.into_iter().chain(std::iter::once(*index)).collect(),
148                            distinct,
149                            filter,
150                            order_by,
151                            null_treatment,
152                        )),
153                    )),
154                    // special case for map access with
155                    _ if matches!(expr.get_type(schema)?, DataType::Map(_, _)) => {
156                        Ok(PlannerResult::Planned(Expr::ScalarFunction(
157                            ScalarFunction::new_udf(
158                                get_field_inner(),
159                                vec![expr, *index],
160                            ),
161                        )))
162                    }
163                    _ => Ok(PlannerResult::Planned(array_element(expr, *index))),
164                }
165            }
166            // expr[start, stop, stride] ==> array_slice(expr, start, stop, stride)
167            GetFieldAccess::ListRange {
168                start,
169                stop,
170                stride,
171            } => Ok(PlannerResult::Planned(array_slice(
172                expr,
173                *start,
174                *stop,
175                Some(*stride),
176            ))),
177        }
178    }
179}
180
181fn is_array_agg(func: &Arc<AggregateUDF>) -> bool {
182    func.name() == "array_agg"
183}