findepi commented on code in PR #14513:
URL: https://github.com/apache/datafusion/pull/14513#discussion_r1943188641


##########
datafusion/functions/src/utils.rs:
##########
@@ -18,10 +18,50 @@
 use arrow::array::ArrayRef;
 use arrow::datatypes::DataType;
 
-use datafusion_common::{Result, ScalarValue};
+use datafusion_common::{exec_datafusion_err, Result, ScalarValue};
 use datafusion_expr::function::Hint;
 use datafusion_expr::ColumnarValue;
 
+/// Converts a collection of function arguments into an fixed-size array of 
length N
+/// producing a reasonable error message in case of unexpected number of 
arguments.
+///
+/// # Example
+/// ```
+/// # use datafusion_common::ScalarValue;
+/// # use datafusion_common::Result;
+/// # use datafusion_expr_common::columnar_value::ColumnarValue;
+/// fn my_function(args: &[ColumnarValue]) -> Result<()> {
+///   // function expects 2 args, so create a 2-element array
+///   let [arg1, arg2] = take_function_args("my_function", args)?;
+///   // ... do stuff..
+///   Ok(())
+/// }
+///
+/// // Calling the function with 1 argument produces an error:
+/// let ten = ColumnarValue::from(ScalarValue::from(10i32));
+/// let twenty = ColumnarValue::from(ScalarValue::from(20i32));
+/// let args = vec![ten.clone()];
+///  let err = my_function(&args).unwrap_err();
+/// assert_eq!(err.to_string(), "my_function function requires 2 arguments, 
got 1");
+/// // Calling the function with 2 arguments works great
+/// let args = vec![ten, twenty];
+/// my_function(&args).unwrap();
+/// ```
+pub fn take_function_args<const N: usize, T>(
+    function_name: &str,
+    args: impl IntoIterator<Item = T>,
+) -> Result<[T; N]> {
+    let args = args.into_iter().collect::<Vec<_>>();
+    args.try_into().map_err(|v: Vec<T>| {
+        exec_datafusion_err!(
+            "{} function requires {} arguments, got {}",
+            function_name,
+            N,

Review Comment:
   BTW generally the error messages should start with a constant prefix string, 
with variable part pushed as late as possible. for example "Invalid argument 
count for function {}: expected {}, got {}".
   this makes them more findable in the code.
   
   i didn't do this in this PR to maintain compat with existing tests asserting 
a particular error string
   to be revisited in the future



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to