Skip to main content

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