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::{Rng, rng};
25
26use datafusion_common::{Result, assert_or_internal_err};
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 sql_example = r#"```sql
37> SELECT random();
38+------------------+
39| random() |
40+------------------+
41| 0.7389238902938 |
42+------------------+
43```"#
44)]
45#[derive(Debug, PartialEq, Eq, Hash)]
46pub struct RandomFunc {
47 signature: Signature,
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 }
61 }
62}
63
64impl ScalarUDFImpl for RandomFunc {
65 fn as_any(&self) -> &dyn Any {
66 self
67 }
68
69 fn name(&self) -> &str {
70 "random"
71 }
72
73 fn signature(&self) -> &Signature {
74 &self.signature
75 }
76
77 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
78 Ok(Float64)
79 }
80
81 fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
82 assert_or_internal_err!(
83 args.args.is_empty(),
84 "{} function does not accept arguments",
85 self.name()
86 );
87 let mut rng = rng();
88 let mut values = vec![0.0; args.number_rows];
89 rng.fill(&mut values[..]);
91 let array = Float64Array::from(values);
92
93 Ok(ColumnarValue::Array(Arc::new(array)))
94 }
95
96 fn documentation(&self) -> Option<&Documentation> {
97 self.doc()
98 }
99}