datafusion_functions/math/
random.rs1use std::any::Any;
19use std::sync::Arc;
20
21use arrow::array::Float64Array;
22use arrow::datatypes::DataType;
23use arrow::datatypes::DataType::Float64;
24use rand::{thread_rng, Rng};
25
26use datafusion_common::{internal_err, Result};
27use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
28use datafusion_expr::{Documentation, ScalarUDFImpl, Signature, Volatility};
29use datafusion_macros::user_doc;
30
31#[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}
41
42impl Default for RandomFunc {
43 fn default() -> Self {
44 RandomFunc::new()
45 }
46}
47
48impl RandomFunc {
49 pub fn new() -> Self {
50 Self {
51 signature: Signature::nullary(Volatility::Volatile),
52 }
53 }
54}
55
56impl ScalarUDFImpl for RandomFunc {
57 fn as_any(&self) -> &dyn Any {
58 self
59 }
60
61 fn name(&self) -> &str {
62 "random"
63 }
64
65 fn signature(&self) -> &Signature {
66 &self.signature
67 }
68
69 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
70 Ok(Float64)
71 }
72
73 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
74 if !args.args.is_empty() {
75 return internal_err!("{} function does not accept arguments", self.name());
76 }
77 let mut rng = thread_rng();
78 let mut values = vec![0.0; args.number_rows];
79 rng.fill(&mut values[..]);
81 let array = Float64Array::from(values);
82
83 Ok(ColumnarValue::Array(Arc::new(array)))
84 }
85
86 fn documentation(&self) -> Option<&Documentation> {
87 self.doc()
88 }
89}