Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Aliases for ScalarUDF #8360

Merged
merged 2 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions datafusion/core/src/execution/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -811,8 +811,14 @@ impl SessionContext {
/// - `SELECT MY_FUNC(x)...` will look for a function named `"my_func"`
/// - `SELECT "my_FUNC"(x)` will look for a function named `"my_FUNC"`
pub fn register_udf(&self, f: ScalarUDF) {
self.state
.write()
let mut state = self.state.write();
let aliases = f.aliases();
for alias in aliases {
state
.scalar_functions
.insert(alias.to_string(), Arc::new(f.clone()));
alamb marked this conversation as resolved.
Show resolved Hide resolved
}
state
.scalar_functions
.insert(f.name().to_string(), Arc::new(f));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,43 @@ async fn case_sensitive_identifiers_user_defined_functions() -> Result<()> {
Ok(())
}

#[tokio::test]
async fn test_user_defined_functions_with_alias() -> Result<()> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe useful to test again the case where you create a udf1 with an alias and then a different udf with the same alias? I don't know what's the expected behavior there

Copy link
Contributor Author

@Veeupup Veeupup Nov 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the behavior will be like HashMap::insert, the old value of the same alias will be updated with the new udf

let ctx = SessionContext::new();
let arr = Int32Array::from(vec![1]);
let batch = RecordBatch::try_from_iter(vec![("i", Arc::new(arr) as _)])?;
ctx.register_batch("t", batch).unwrap();

let myfunc = |args: &[ArrayRef]| Ok(Arc::clone(&args[0]));
let myfunc = make_scalar_function(myfunc);

let udf = create_udf(
"dummy",
vec![DataType::Int32],
Arc::new(DataType::Int32),
Volatility::Immutable,
myfunc,
)
.with_aliases(vec!["dummy_alias"]);

ctx.register_udf(udf);

let expected = [
"+------------+",
"| dummy(t.i) |",
"+------------+",
"| 1 |",
"+------------+",
];
let result = plan_and_collect(&ctx, "SELECT dummy(i) FROM t").await?;
assert_batches_eq!(expected, &result);

let alias_result = plan_and_collect(&ctx, "SELECT dummy_alias(i) FROM t").await?;
assert_batches_eq!(expected, &alias_result);

Ok(())
}

fn create_udf_context() -> SessionContext {
let ctx = SessionContext::new();
// register a custom UDF
Expand Down
34 changes: 34 additions & 0 deletions datafusion/expr/src/udf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ pub struct ScalarUDF {
/// the batch's row count (so that the generative zero-argument function can know
/// the result array size).
fun: ScalarFunctionImplementation,
/// Optional aliases for the function
Veeupup marked this conversation as resolved.
Show resolved Hide resolved
aliases: Vec<String>,
}

impl Debug for ScalarUDF {
Expand Down Expand Up @@ -89,6 +91,34 @@ impl ScalarUDF {
signature: signature.clone(),
return_type: return_type.clone(),
fun: fun.clone(),
aliases: vec![],
}
}

/// Create a new ScalarUDF with aliases
pub fn new_with_aliases(
Veeupup marked this conversation as resolved.
Show resolved Hide resolved
name: &str,
signature: &Signature,
return_type: &ReturnTypeFunction,
fun: &ScalarFunctionImplementation,
aliases: Vec<String>,
) -> Self {
Self {
name: name.to_owned(),
signature: signature.clone(),
return_type: return_type.clone(),
fun: fun.clone(),
aliases,
}
}

pub fn with_aliases(self, aliases: Vec<&str>) -> Self {
Self {
name: self.name,
signature: self.signature,
return_type: self.return_type,
fun: self.fun,
aliases: aliases.iter().map(|s| s.to_string()).collect(),
}
Veeupup marked this conversation as resolved.
Show resolved Hide resolved
}

Expand All @@ -106,6 +136,10 @@ impl ScalarUDF {
&self.name
}

pub fn aliases(&self) -> &[String] {
Veeupup marked this conversation as resolved.
Show resolved Hide resolved
&self.aliases
}

/// Returns this function's signature (what input types are accepted)
pub fn signature(&self) -> &Signature {
&self.signature
Expand Down