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.
1718use std::any::Any;
19use std::sync::Arc;
2021use arrow::array::Float64Array;
22use arrow::datatypes::DataType;
23use arrow::datatypes::DataType::Float64;
24use rand::{rng, Rng};
2526use datafusion_common::{internal_err, Result};
27use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
28use datafusion_expr::{Documentation, ScalarUDFImpl, Signature, Volatility};
29use datafusion_macros::user_doc;
3031#[user_doc(
32 doc_section(label = "Math Functions"),
33 description = r#"Returns a random float value in the range [0, 1).
34The random seed is unique to each row."#,
35 syntax_example = "random()"
36)]
37#[derive(Debug)]
38pub struct RandomFunc {
39 signature: Signature,
40}
4142impl Default for RandomFunc {
43fn default() -> Self {
44 RandomFunc::new()
45 }
46}
4748impl RandomFunc {
49pub fn new() -> Self {
50Self {
51 signature: Signature::nullary(Volatility::Volatile),
52 }
53 }
54}
5556impl ScalarUDFImpl for RandomFunc {
57fn as_any(&self) -> &dyn Any {
58self
59}
6061fn name(&self) -> &str {
62"random"
63}
6465fn signature(&self) -> &Signature {
66&self.signature
67 }
6869fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
70Ok(Float64)
71 }
7273fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
74if !args.args.is_empty() {
75return internal_err!("{} function does not accept arguments", self.name());
76 }
77let mut rng = rng();
78let mut values = vec![0.0; args.number_rows];
79// Equivalent to set each element with rng.random_range(0.0..1.0), but more efficient
80rng.fill(&mut values[..]);
81let array = Float64Array::from(values);
8283Ok(ColumnarValue::Array(Arc::new(array)))
84 }
8586fn documentation(&self) -> Option<&Documentation> {
87self.doc()
88 }
89}