use crate::{
Expr, PartitionEvaluator, PartitionEvaluatorFactory, ReturnTypeFunction, Signature,
WindowFrame,
};
use arrow::datatypes::DataType;
use datafusion_common::Result;
use std::{
fmt::{self, Debug, Display, Formatter},
sync::Arc,
};
#[derive(Clone)]
pub struct WindowUDF {
name: String,
signature: Signature,
return_type: ReturnTypeFunction,
partition_evaluator_factory: PartitionEvaluatorFactory,
}
impl Debug for WindowUDF {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("WindowUDF")
.field("name", &self.name)
.field("signature", &self.signature)
.field("return_type", &"<func>")
.field("partition_evaluator_factory", &"<func>")
.finish_non_exhaustive()
}
}
impl Display for WindowUDF {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
impl PartialEq for WindowUDF {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.signature == other.signature
}
}
impl Eq for WindowUDF {}
impl std::hash::Hash for WindowUDF {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.name.hash(state);
self.signature.hash(state);
}
}
impl WindowUDF {
pub fn new(
name: &str,
signature: &Signature,
return_type: &ReturnTypeFunction,
partition_evaluator_factory: &PartitionEvaluatorFactory,
) -> Self {
Self {
name: name.to_string(),
signature: signature.clone(),
return_type: return_type.clone(),
partition_evaluator_factory: partition_evaluator_factory.clone(),
}
}
pub fn call(
&self,
args: Vec<Expr>,
partition_by: Vec<Expr>,
order_by: Vec<Expr>,
window_frame: WindowFrame,
) -> Expr {
let fun = crate::WindowFunction::WindowUDF(Arc::new(self.clone()));
Expr::WindowFunction(crate::expr::WindowFunction {
fun,
args,
partition_by,
order_by,
window_frame,
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn signature(&self) -> &Signature {
&self.signature
}
pub fn return_type(&self, args: &[DataType]) -> Result<DataType> {
let res = (self.return_type)(args)?;
Ok(res.as_ref().clone())
}
pub fn partition_evaluator_factory(&self) -> Result<Box<dyn PartitionEvaluator>> {
(self.partition_evaluator_factory)()
}
}