use std::any::Any;
use std::sync::Arc;
use arrow::array::Float64Array;
use arrow::datatypes::DataType;
use arrow::datatypes::DataType::Float64;
use rand::{thread_rng, Rng};
use datafusion_common::{not_impl_err, Result};
use datafusion_expr::ColumnarValue;
use datafusion_expr::{ScalarUDFImpl, Signature, Volatility};
#[derive(Debug)]
pub struct RandomFunc {
signature: Signature,
}
impl Default for RandomFunc {
fn default() -> Self {
RandomFunc::new()
}
}
impl RandomFunc {
pub fn new() -> Self {
Self {
signature: Signature::exact(vec![], Volatility::Volatile),
}
}
}
impl ScalarUDFImpl for RandomFunc {
fn as_any(&self) -> &dyn Any {
self
}
fn name(&self) -> &str {
"random"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
Ok(Float64)
}
fn invoke(&self, _args: &[ColumnarValue]) -> Result<ColumnarValue> {
not_impl_err!("{} function does not accept arguments", self.name())
}
fn invoke_no_args(&self, num_rows: usize) -> Result<ColumnarValue> {
let mut rng = thread_rng();
let values = std::iter::repeat_with(|| rng.gen_range(0.0..1.0)).take(num_rows);
let array = Float64Array::from_iter_values(values);
Ok(ColumnarValue::Array(Arc::new(array)))
}
}