Skip to main content

datafusion_functions/math/
random.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::sync::Arc;
19
20use arrow::array::Float64Array;
21use arrow::datatypes::DataType;
22use arrow::datatypes::DataType::Float64;
23use rand::{Rng, rng};
24
25use datafusion_common::{Result, assert_or_internal_err};
26use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
27use datafusion_expr::{Documentation, ScalarUDFImpl, Signature, Volatility};
28use datafusion_macros::user_doc;
29
30#[user_doc(
31    doc_section(label = "Math Functions"),
32    description = r#"Returns a random float value in the range [0, 1).
33The random seed is unique to each row."#,
34    syntax_example = "random()",
35    sql_example = r#"```sql
36> SELECT random();
37+------------------+
38| random()         |
39+------------------+
40| 0.7389238902938  |
41+------------------+
42```"#
43)]
44#[derive(Debug, PartialEq, Eq, Hash)]
45pub struct RandomFunc {
46    signature: Signature,
47    aliases: Vec<String>,
48}
49
50impl Default for RandomFunc {
51    fn default() -> Self {
52        RandomFunc::new()
53    }
54}
55
56impl RandomFunc {
57    pub fn new() -> Self {
58        Self {
59            signature: Signature::nullary(Volatility::Volatile),
60            aliases: vec![String::from("rand")],
61        }
62    }
63}
64
65impl ScalarUDFImpl for RandomFunc {
66    fn name(&self) -> &str {
67        "random"
68    }
69
70    fn signature(&self) -> &Signature {
71        &self.signature
72    }
73
74    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
75        Ok(Float64)
76    }
77
78    fn aliases(&self) -> &[String] {
79        &self.aliases
80    }
81
82    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
83        assert_or_internal_err!(
84            args.args.is_empty(),
85            "{} function does not accept arguments",
86            self.name()
87        );
88        let mut rng = rng();
89        let mut values = vec![0.0; args.number_rows];
90        // Equivalent to set each element with rng.random_range(0.0..1.0), but more efficient
91        rng.fill(&mut values[..]);
92        let array = Float64Array::from(values);
93
94        Ok(ColumnarValue::Array(Arc::new(array)))
95    }
96
97    fn documentation(&self) -> Option<&Documentation> {
98        self.doc()
99    }
100}