datafusion_functions/math/
pi.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 std::any::Any;
19
20use arrow::datatypes::DataType;
21use arrow::datatypes::DataType::Float64;
22use datafusion_common::{internal_err, Result, ScalarValue};
23use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
24use datafusion_expr::{
25    ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
26    Volatility,
27};
28use datafusion_macros::user_doc;
29
30#[user_doc(
31    doc_section(label = "Math Functions"),
32    description = "Returns an approximate value of π.",
33    syntax_example = "pi()"
34)]
35#[derive(Debug)]
36pub struct PiFunc {
37    signature: Signature,
38}
39
40impl Default for PiFunc {
41    fn default() -> Self {
42        PiFunc::new()
43    }
44}
45
46impl PiFunc {
47    pub fn new() -> Self {
48        Self {
49            signature: Signature::nullary(Volatility::Immutable),
50        }
51    }
52}
53
54impl ScalarUDFImpl for PiFunc {
55    fn as_any(&self) -> &dyn Any {
56        self
57    }
58
59    fn name(&self) -> &str {
60        "pi"
61    }
62
63    fn signature(&self) -> &Signature {
64        &self.signature
65    }
66
67    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
68        Ok(Float64)
69    }
70
71    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
72        if !args.args.is_empty() {
73            return internal_err!("{} function does not accept arguments", self.name());
74        }
75        Ok(ColumnarValue::Scalar(ScalarValue::Float64(Some(
76            std::f64::consts::PI,
77        ))))
78    }
79
80    fn output_ordering(&self, _input: &[ExprProperties]) -> Result<SortProperties> {
81        // This function returns a constant value.
82        Ok(SortProperties::Singleton)
83    }
84
85    fn documentation(&self) -> Option<&Documentation> {
86        self.doc()
87    }
88}