Skip to main content

datafusion_spark/function/math/
pow.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
18//! Spark-compatible `pow` / `power` function.
19//!
20//! Unlike the default DataFusion (PostgreSQL) implementation, Spark returns
21//! `Infinity` for `pow(0, <negative>)` rather than raising an error.
22
23use std::sync::Arc;
24
25use arrow::array::{Array, ArrayRef, Float64Array};
26use arrow::datatypes::DataType;
27
28use datafusion_common::utils::take_function_args;
29use datafusion_common::{Result, ScalarValue};
30use datafusion_expr::{
31    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
32};
33use datafusion_functions::math::power::PowerFunc;
34
35/// Spark-compatible implementation of `pow` / `power`.
36///
37/// Behavioural difference from the DataFusion default:
38/// - `pow(0, <negative>)` → `Infinity`  (IEEE 754 / Spark semantics)
39///   The default raises `"zero raised to a negative power is undefined"` to
40///   match PostgreSQL.
41#[derive(Debug, PartialEq, Eq, Hash)]
42pub struct SparkPow {
43    inner: PowerFunc,
44    aliases: Vec<String>,
45}
46
47impl Default for SparkPow {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl SparkPow {
54    pub fn new() -> Self {
55        Self {
56            inner: PowerFunc::new(),
57            // SparkPow is named "pow"; expose "power" as an alias so that
58            // both names resolve to Spark semantics when this crate is active.
59            aliases: vec!["power".to_string()],
60        }
61    }
62}
63
64impl ScalarUDFImpl for SparkPow {
65    fn name(&self) -> &str {
66        "pow"
67    }
68
69    fn aliases(&self) -> &[String] {
70        &self.aliases
71    }
72
73    fn signature(&self) -> &Signature {
74        self.inner.signature()
75    }
76
77    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
78        self.inner.return_type(arg_types)
79    }
80
81    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
82        // Only Float64 × Float64 needs the Spark override.
83        // Decimal / integer / mixed-type paths are delegated to the standard
84        // PowerFunc which already handles them correctly (decimal can't
85        // represent Infinity anyway).
86        match args.args.as_slice() {
87            [base, exponent]
88                if matches!(base.data_type(), DataType::Float64)
89                    && matches!(exponent.data_type(), DataType::Float64) => {}
90            _ => return self.inner.invoke_with_args(args),
91        }
92
93        let num_rows = args.number_rows;
94
95        // ── Scalar × Scalar fast path ────────────────────────────────────────
96        // Pattern-match on the slice to avoid any ownership issues.
97        if let [
98            ColumnarValue::Scalar(ScalarValue::Float64(base)),
99            ColumnarValue::Scalar(ScalarValue::Float64(exp)),
100        ] = args.args.as_slice()
101        {
102            // base and exp are &Option<f64>; Option<f64> is Copy.
103            let result = (*base).zip(*exp).map(|(base, exp)| {
104                if base == 0.0 && exp < 0.0 {
105                    f64::INFINITY
106                } else {
107                    base.powf(exp)
108                }
109            });
110            return Ok(ColumnarValue::Scalar(ScalarValue::Float64(result)));
111        }
112
113        // ── Array path ───────────────────────────────────────────────────────
114        let [base, exponent] = take_function_args(self.name(), &args.args)?;
115
116        let base_arr: ArrayRef = base.to_array(num_rows)?;
117        let exp_arr: ArrayRef = exponent.to_array(num_rows)?;
118
119        let base_f64 = base_arr
120            .as_any()
121            .downcast_ref::<Float64Array>()
122            .expect("base must be Float64Array");
123        let exp_f64 = exp_arr
124            .as_any()
125            .downcast_ref::<Float64Array>()
126            .expect("exponent must be Float64Array");
127
128        // Spark: 0^negative = +Infinity (covers both 0.0 and -0.0)
129        // IEEE 754: 0.0^-1.0 = +Infinity, -0.0^-1.0 = -Infinity
130        // Thus we need an explicit guard for base == 0.0 to ensure +Infinity.
131        let result: Float64Array = base_f64
132            .iter()
133            .zip(exp_f64.iter())
134            .map(|(base, exp)| match (base, exp) {
135                (Some(base), Some(exp)) => {
136                    if base == 0.0 && exp < 0.0 {
137                        Some(f64::INFINITY)
138                    } else {
139                        Some(base.powf(exp))
140                    }
141                }
142                _ => None,
143            })
144            .collect();
145
146        Ok(ColumnarValue::Array(Arc::new(result)))
147    }
148
149    fn documentation(&self) -> Option<&Documentation> {
150        self.inner.documentation()
151    }
152}