From 7ad526caf140f7eb76ec541c903027d49693b58f Mon Sep 17 00:00:00 2001 From: Michael-J-Ward Date: Wed, 1 May 2024 13:33:10 -0500 Subject: [PATCH] feat: migrate functions.rs `datafusion` completed an Epic that ported many of the `BuiltInFunctions` enum to `SclarUDF`. I created new macros to simplify the port, and used these macros to refactor a few existing functions. Ref: https://github.com/apache/datafusion/issues/9285 --- src/functions.rs | 394 +++++++++++++++++++++++++++++------------------ 1 file changed, 244 insertions(+), 150 deletions(-) diff --git a/src/functions.rs b/src/functions.rs index 069b88da..7f6b1a87 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -24,7 +24,7 @@ use crate::expr::window::PyWindowFrame; use crate::expr::PyExpr; use datafusion::execution::FunctionRegistry; use datafusion::functions; -use datafusion_common::{Column, TableReference}; +use datafusion_common::{Column, ScalarValue, TableReference}; use datafusion_expr::expr::Alias; use datafusion_expr::{ aggregate_function, @@ -36,56 +36,85 @@ use datafusion_expr::{ }; #[pyfunction] -pub fn isnan(expr: PyExpr) -> PyExpr { - functions::expr_fn::isnan(expr.into()).into() +fn in_list(expr: PyExpr, value: Vec, negated: bool) -> PyExpr { + datafusion_expr::in_list( + expr.expr, + value.into_iter().map(|x| x.expr).collect::>(), + negated, + ) + .into() } #[pyfunction] -pub fn nullif(expr1: PyExpr, expr2: PyExpr) -> PyExpr { - functions::expr_fn::nullif(expr1.into(), expr2.into()).into() +#[pyo3(signature = (*exprs))] +fn make_array(exprs: Vec) -> PyExpr { + datafusion_functions_array::expr_fn::make_array(exprs.into_iter().map(|x| x.into()).collect()) + .into() } #[pyfunction] -pub fn encode(input: PyExpr, encoding: PyExpr) -> PyExpr { - functions::expr_fn::encode(input.into(), encoding.into()).into() +#[pyo3(signature = (*exprs))] +fn array(exprs: Vec) -> PyExpr { + // alias for make_array + make_array(exprs) } #[pyfunction] -pub fn decode(input: PyExpr, encoding: PyExpr) -> PyExpr { - functions::expr_fn::decode(input.into(), encoding.into()).into() +#[pyo3(signature = (*exprs))] +fn array_concat(exprs: Vec) -> PyExpr { + let exprs = exprs.into_iter().map(|x| x.into()).collect(); + datafusion_functions_array::expr_fn::array_concat(exprs).into() } #[pyfunction] -pub fn array_to_string(expr: PyExpr, delim: PyExpr) -> PyExpr { - datafusion_functions_array::expr_fn::array_to_string(expr.into(), delim.into()).into() +#[pyo3(signature = (*exprs))] +fn array_cat(exprs: Vec) -> PyExpr { + array_concat(exprs) } #[pyfunction] -pub fn array_join(expr: PyExpr, delim: PyExpr) -> PyExpr { - // alias for array_to_string - array_to_string(expr, delim) +#[pyo3(signature = (array, element, index = 1))] +fn array_position(array: PyExpr, element: PyExpr, index: Option) -> PyExpr { + let index = ScalarValue::Int64(index); + let index = Expr::Literal(index); + datafusion_functions_array::expr_fn::array_position(array.into(), element.into(), index).into() } #[pyfunction] -pub fn list_to_string(expr: PyExpr, delim: PyExpr) -> PyExpr { - // alias for array_to_string - array_to_string(expr, delim) +#[pyo3(signature = (array, element, index = 1))] +fn array_indexof(array: PyExpr, element: PyExpr, index: Option) -> PyExpr { + // alias of array_position + array_position(array, element, index) } #[pyfunction] -pub fn list_join(expr: PyExpr, delim: PyExpr) -> PyExpr { - // alias for array_to_string - array_to_string(expr, delim) +#[pyo3(signature = (array, element, index = 1))] +fn list_position(array: PyExpr, element: PyExpr, index: Option) -> PyExpr { + // alias of array_position + array_position(array, element, index) } #[pyfunction] -fn in_list(expr: PyExpr, value: Vec, negated: bool) -> PyExpr { - datafusion_expr::in_list( - expr.expr, - value.into_iter().map(|x| x.expr).collect::>(), - negated, - ) - .into() +#[pyo3(signature = (array, element, index = 1))] +fn list_indexof(array: PyExpr, element: PyExpr, index: Option) -> PyExpr { + // alias of array_position + array_position(array, element, index) +} + +#[pyfunction] +#[pyo3(signature = (array, begin, end, stride = 1))] +fn array_slice(array: PyExpr, begin: PyExpr, end: PyExpr, stride: Option) -> PyExpr { + let stride = ScalarValue::Int64(stride); + let stride = Expr::Literal(stride); + datafusion_functions_array::expr_fn::array_slice(array.into(), begin.into(), end.into(), stride) + .into() +} + +#[pyfunction] +#[pyo3(signature = (array, begin, end, stride = 1))] +fn list_slice(array: PyExpr, begin: PyExpr, end: PyExpr, stride: Option) -> PyExpr { + // alias of array_slice + array_slice(array, begin, end, stride) } /// Computes a binary hash of the given data. type is the algorithm to use. @@ -95,7 +124,7 @@ fn in_list(expr: PyExpr, value: Vec, negated: bool) -> PyExpr { #[pyo3(signature = (value, method))] fn digest(value: PyExpr, method: PyExpr) -> PyExpr { PyExpr { - expr: datafusion_expr::digest(value.expr, method.expr), + expr: functions::expr_fn::digest(value.expr, method.expr), } } @@ -265,40 +294,117 @@ macro_rules! aggregate_function { }; } -scalar_function!(abs, Abs); -scalar_function!(acos, Acos); +/// Generates a [pyo3] wrapper for [datafusion::functions::expr_fn] +/// +/// These functions have explicit named arguments. +macro_rules! expr_fn { + ($NAME: ident) => { + expr_fn!($NAME, $NAME, , stringify!($NAME)); + }; + ($NAME:ident, $($arg:ident)*) => { + expr_fn!($NAME, $NAME, $($arg)*, stringify!($FUNC)); + }; + ($NAME:ident, $FUNC:ident, $($arg:ident)*) => { + expr_fn!($NAME, $FUNC, $($arg)*, stringify!($FUNC)); + }; + ($NAME: ident, $DOC: expr) => { + expr_fn!($NAME, $NAME, ,$DOC); + }; + ($NAME: ident, $($arg:ident)*, $DOC: expr) => { + expr_fn!($NAME, $NAME, $($arg)* ,$DOC); + }; + ($NAME: ident, $FUNC: ident, $($arg:ident)*, $DOC: expr) => { + #[doc = $DOC] + #[pyfunction] + fn $NAME($($arg: PyExpr),*) -> PyExpr { + functions::expr_fn::$FUNC($($arg.into()),*).into() + } + }; +} + +/// Generates a [pyo3] wrapper for [datafusion::functions::expr_fn] +/// +/// These functions take a single `Vec` argument using `pyo3(signature = (*args))`. +macro_rules! expr_fn_vec { + ($NAME: ident) => { + expr_fn_vec!($NAME, $NAME, stringify!($NAME)); + }; + ($NAME: ident, $DOC: expr) => { + expr_fn_vec!($NAME, $NAME, $DOC); + }; + ($NAME: ident, $FUNC: ident, $DOC: expr) => { + #[doc = $DOC] + #[pyfunction] + #[pyo3(signature = (*args))] + fn $NAME(args: Vec) -> PyExpr { + let args = args.into_iter().map(|e| e.into()).collect::>(); + functions::expr_fn::$FUNC(args).into() + } + }; +} + +/// Generates a [pyo3] wrapper for [datafusion_functions_array::expr_fn] +/// +/// These functions have explicit named arguments. +macro_rules! array_fn { + ($NAME: ident) => { + array_fn!($NAME, $NAME, , stringify!($NAME)); + }; + ($NAME:ident, $($arg:ident)*) => { + array_fn!($NAME, $NAME, $($arg)*, stringify!($FUNC)); + }; + ($NAME: ident, $FUNC:ident, $($arg:ident)*) => { + array_fn!($NAME, $FUNC, $($arg)*, stringify!($FUNC)); + }; + ($NAME: ident, $DOC: expr) => { + array_fn!($NAME, $NAME, , $DOC); + }; + ($NAME: ident, $FUNC:ident, $($arg:ident)*, $DOC:expr) => { + #[doc = $DOC] + #[pyfunction] + fn $NAME($($arg: PyExpr),*) -> PyExpr { + datafusion_functions_array::expr_fn::$FUNC($($arg.into()),*).into() + } + }; +} + +expr_fn!(abs, num); +expr_fn!(acos, num); scalar_function!(acosh, Acosh); -scalar_function!(ascii, Ascii, "Returns the numeric code of the first character of the argument. In UTF8 encoding, returns the Unicode code point of the character. In other multibyte encodings, the argument must be an ASCII character."); -scalar_function!(asin, Asin); +expr_fn!(ascii, arg1, "Returns the numeric code of the first character of the argument. In UTF8 encoding, returns the Unicode code point of the character. In other multibyte encodings, the argument must be an ASCII character."); +expr_fn!(asin, num); scalar_function!(asinh, Asinh); scalar_function!(atan, Atan); scalar_function!(atanh, Atanh); scalar_function!(atan2, Atan2); -scalar_function!( +expr_fn!( bit_length, - BitLength, + arg, "Returns number of bits in the string (8 times the octet_length)." ); -scalar_function!(btrim, Btrim, "Removes the longest string containing only characters in characters (a space by default) from the start and end of string."); +expr_fn_vec!(btrim, "Removes the longest string containing only characters in characters (a space by default) from the start and end of string."); scalar_function!(cbrt, Cbrt); scalar_function!(ceil, Ceil); -scalar_function!( +expr_fn!( character_length, - CharacterLength, + string, "Returns number of characters in the string." ); -scalar_function!(length, CharacterLength); -scalar_function!(char_length, CharacterLength); -scalar_function!(chr, Chr, "Returns the character with the given code."); +expr_fn!(length, string); +expr_fn!(char_length, string); +expr_fn!(chr, arg, "Returns the character with the given code."); scalar_function!(coalesce, Coalesce); scalar_function!(cos, Cos); scalar_function!(cosh, Cosh); scalar_function!(degrees, Degrees); +expr_fn!(decode, input encoding); +expr_fn!(encode, input encoding); scalar_function!(exp, Exp); scalar_function!(factorial, Factorial); scalar_function!(floor, Floor); scalar_function!(gcd, Gcd); scalar_function!(initcap, InitCap, "Converts the first letter of each word to upper case and the rest to lower case. Words are sequences of alphanumeric characters separated by non-alphanumeric characters."); +expr_fn!(isnan, num); scalar_function!(iszero, Iszero); scalar_function!(lcm, Lcm); scalar_function!(left, Left, "Returns first n characters in the string, or when n is negative, returns all but last |n| characters."); @@ -306,12 +412,12 @@ scalar_function!(ln, Ln); scalar_function!(log, Log); scalar_function!(log10, Log10); scalar_function!(log2, Log2); -scalar_function!(lower, Lower, "Converts the string to all lower case"); +expr_fn!(lower, arg1, "Converts the string to all lower case"); scalar_function!(lpad, Lpad, "Extends the string to length length by prepending the characters fill (a space by default). If the string is already longer than length then it is truncated (on the right)."); -scalar_function!(ltrim, Ltrim, "Removes the longest string containing only characters in characters (a space by default) from the start of string."); -scalar_function!( +expr_fn_vec!(ltrim, "Removes the longest string containing only characters in characters (a space by default) from the start of string."); +expr_fn!( md5, - MD5, + input_arg, "Computes the MD5 hash of the argument, with the result written in hexadecimal." ); scalar_function!( @@ -319,25 +425,22 @@ scalar_function!( Nanvl, "Returns x if x is not NaN otherwise returns y." ); -scalar_function!(octet_length, OctetLength, "Returns number of bytes in the string. Since this version of the function accepts type character directly, it will not strip trailing spaces."); +expr_fn!(nullif, arg_1 arg_2); +expr_fn_vec!(octet_length, "Returns number of bytes in the string. Since this version of the function accepts type character directly, it will not strip trailing spaces."); scalar_function!(pi, Pi); scalar_function!(power, Power); scalar_function!(pow, Power); scalar_function!(radians, Radians); -scalar_function!(regexp_match, RegexpMatch); -scalar_function!( +expr_fn!(regexp_match, input_arg1 input_arg2); +expr_fn!( regexp_replace, - RegexpReplace, - "Replaces substring(s) matching a POSIX regular expression" + arg1 arg2 arg3 arg4, + "Replaces substring(s) matching a POSIX regular expression." ); -scalar_function!( - repeat, - Repeat, - "Repeats string the specified number of times." -); -scalar_function!( +expr_fn!(repeat, string n, "Repeats string the specified number of times."); +expr_fn!( replace, - Replace, + string from to, "Replaces all occurrences in string of substring from with substring to." ); scalar_function!( @@ -348,117 +451,108 @@ scalar_function!( scalar_function!(right, Right, "Returns last n characters in the string, or when n is negative, returns all but first |n| characters."); scalar_function!(round, Round); scalar_function!(rpad, Rpad, "Extends the string to length length by appending the characters fill (a space by default). If the string is already longer than length then it is truncated."); -scalar_function!(rtrim, Rtrim, "Removes the longest string containing only characters in characters (a space by default) from the end of string."); -scalar_function!(sha224, SHA224); -scalar_function!(sha256, SHA256); -scalar_function!(sha384, SHA384); -scalar_function!(sha512, SHA512); +expr_fn_vec!(rtrim, "Removes the longest string containing only characters in characters (a space by default) from the end of string."); +expr_fn!(sha224, input_arg1); +expr_fn!(sha256, input_arg1); +expr_fn!(sha384, input_arg1); +expr_fn!(sha512, input_arg1); scalar_function!(signum, Signum); scalar_function!(sin, Sin); scalar_function!(sinh, Sinh); -scalar_function!( +expr_fn!( split_part, - SplitPart, + string delimiter index, "Splits string at occurrences of delimiter and returns the n'th field (counting from one)." ); scalar_function!(sqrt, Sqrt); -scalar_function!( - starts_with, - StartsWith, - "Returns true if string starts with prefix." -); +expr_fn!(starts_with, arg1 arg2, "Returns true if string starts with prefix."); scalar_function!(strpos, Strpos, "Returns starting index of specified substring within string, or zero if it's not present. (Same as position(substring in string), but note the reversed argument order.)"); scalar_function!(substr, Substr); -scalar_function!(tan, Tan); -scalar_function!(tanh, Tanh); -scalar_function!( +expr_fn!(tan, num); +expr_fn!(tanh, num); +expr_fn!( to_hex, - ToHex, + arg1, "Converts the number to its equivalent hexadecimal representation." ); -scalar_function!(now, Now); -scalar_function!(to_timestamp, ToTimestamp); -scalar_function!(to_timestamp_millis, ToTimestampMillis); -scalar_function!(to_timestamp_micros, ToTimestampMicros); -scalar_function!(to_timestamp_seconds, ToTimestampSeconds); -scalar_function!(current_date, CurrentDate); -scalar_function!(current_time, CurrentTime); -scalar_function!(datepart, DatePart); -scalar_function!(date_part, DatePart); -scalar_function!(date_trunc, DateTrunc); -scalar_function!(datetrunc, DateTrunc); -scalar_function!(date_bin, DateBin); +expr_fn!(now); +expr_fn_vec!(to_timestamp); +expr_fn_vec!(to_timestamp_millis); +expr_fn_vec!(to_timestamp_micros); +expr_fn_vec!(to_timestamp_seconds); +expr_fn!(current_date); +expr_fn!(current_time); +expr_fn!(date_part, part date); +expr_fn!(datepart, date_part, part date); +expr_fn!(date_trunc, part date); +expr_fn!(datetrunc, date_trunc, part date); +expr_fn!(date_bin, stride source origin); + scalar_function!(translate, Translate, "Replaces each character in string that matches a character in the from set with the corresponding character in the to set. If from is longer than to, occurrences of the extra characters in from are deleted."); -scalar_function!(trim, Trim, "Removes the longest string containing only characters in characters (a space by default) from the start, end, or both ends (BOTH is the default) of string."); +expr_fn_vec!(trim, "Removes the longest string containing only characters in characters (a space by default) from the start, end, or both ends (BOTH is the default) of string."); scalar_function!(trunc, Trunc); -scalar_function!(upper, Upper, "Converts the string to all upper case."); -scalar_function!(make_array, MakeArray); -scalar_function!(array, MakeArray); -scalar_function!(range, Range); -scalar_function!(uuid, Uuid); -scalar_function!(r#struct, Struct); // Use raw identifier since struct is a keyword -scalar_function!(from_unixtime, FromUnixtime); -scalar_function!(arrow_typeof, ArrowTypeof); +expr_fn!(upper, arg1, "Converts the string to all upper case."); +expr_fn!(uuid); +expr_fn!(r#struct, args); // Use raw identifier since struct is a keyword +expr_fn!(from_unixtime, unixtime); +expr_fn!(arrow_typeof, arg_1); scalar_function!(random, Random); // Array Functions -scalar_function!(array_append, ArrayAppend); -scalar_function!(array_push_back, ArrayAppend); -scalar_function!(list_append, ArrayAppend); -scalar_function!(list_push_back, ArrayAppend); -scalar_function!(array_concat, ArrayConcat); -scalar_function!(array_cat, ArrayConcat); -scalar_function!(array_dims, ArrayDims); -scalar_function!(array_distinct, ArrayDistinct); -scalar_function!(list_distinct, ArrayDistinct); -scalar_function!(list_dims, ArrayDims); -scalar_function!(array_element, ArrayElement); -scalar_function!(array_extract, ArrayElement); -scalar_function!(list_element, ArrayElement); -scalar_function!(list_extract, ArrayElement); -scalar_function!(array_length, ArrayLength); -scalar_function!(list_length, ArrayLength); -scalar_function!(array_has, ArrayHas); -scalar_function!(array_has_all, ArrayHasAll); -scalar_function!(array_has_any, ArrayHasAny); -scalar_function!(array_position, ArrayPosition); -scalar_function!(array_indexof, ArrayPosition); -scalar_function!(list_position, ArrayPosition); -scalar_function!(list_indexof, ArrayPosition); -scalar_function!(array_positions, ArrayPositions); -scalar_function!(list_positions, ArrayPositions); -scalar_function!(array_ndims, ArrayNdims); -scalar_function!(list_ndims, ArrayNdims); -scalar_function!(array_prepend, ArrayPrepend); -scalar_function!(array_push_front, ArrayPrepend); -scalar_function!(list_prepend, ArrayPrepend); -scalar_function!(list_push_front, ArrayPrepend); -scalar_function!(array_pop_back, ArrayPopBack); -scalar_function!(array_pop_front, ArrayPopFront); -scalar_function!(array_remove, ArrayRemove); -scalar_function!(list_remove, ArrayRemove); -scalar_function!(array_remove_n, ArrayRemoveN); -scalar_function!(list_remove_n, ArrayRemoveN); -scalar_function!(array_remove_all, ArrayRemoveAll); -scalar_function!(list_remove_all, ArrayRemoveAll); -scalar_function!(array_repeat, ArrayRepeat); -scalar_function!(array_replace, ArrayReplace); -scalar_function!(list_replace, ArrayReplace); -scalar_function!(array_replace_n, ArrayReplaceN); -scalar_function!(list_replace_n, ArrayReplaceN); -scalar_function!(array_replace_all, ArrayReplaceAll); -scalar_function!(list_replace_all, ArrayReplaceAll); -scalar_function!(array_slice, ArraySlice); -scalar_function!(list_slice, ArraySlice); -scalar_function!(array_intersect, ArrayIntersect); -scalar_function!(list_intersect, ArrayIntersect); -scalar_function!(array_union, ArrayUnion); -scalar_function!(list_union, ArrayUnion); -scalar_function!(array_except, ArrayExcept); -scalar_function!(list_except, ArrayExcept); -scalar_function!(array_resize, ArrayResize); -scalar_function!(list_resize, ArrayResize); -scalar_function!(flatten, Flatten); +array_fn!(array_append, array element); +array_fn!(array_push_back, array_append, array element); +array_fn!(array_to_string, array delimiter); +array_fn!(array_join, array_to_string, array delimiter); +array_fn!(list_to_string, array_to_string, array delimiter); +array_fn!(list_join, array_to_string, array delimiter); +array_fn!(list_append, array_append, array element); +array_fn!(list_push_back, array_append, array element); +array_fn!(array_dims, array); +array_fn!(array_distinct, array); +array_fn!(list_distinct, array_distinct, array); +array_fn!(list_dims, array_dims, array); +array_fn!(array_element, array element); +array_fn!(array_extract, array_element, array element); +array_fn!(list_element, array_element, array element); +array_fn!(list_extract, array_element, array element); +array_fn!(array_length, array); +array_fn!(list_length, array_length, array); +array_fn!(array_has, first_array second_array); +array_fn!(array_has_all, first_array second_array); +array_fn!(array_has_any, first_array second_array); +array_fn!(array_positions, array_positions, array element); +array_fn!(list_positions, array_positions, array element); +array_fn!(array_ndims, array); +array_fn!(list_ndims, array_ndims, array); +array_fn!(array_prepend, element array); +array_fn!(array_push_front, array_prepend, element array); +array_fn!(list_prepend, array_prepend, element array); +array_fn!(list_push_front, array_prepend, element array); +array_fn!(array_pop_back, array); +array_fn!(array_pop_front, array); +array_fn!(array_remove, array element); +array_fn!(list_remove, array_remove, array element); +array_fn!(array_remove_n, array element max); +array_fn!(list_remove_n, array_remove_n, array element max); +array_fn!(array_remove_all, array element); +array_fn!(list_remove_all, array_remove_all, array element); +array_fn!(array_repeat, element count); +array_fn!(array_replace, array from to); +array_fn!(list_replace, array_replace, array from to); +array_fn!(array_replace_n, array from to max); +array_fn!(list_replace_n, array_replace_n, array from to max); +array_fn!(array_replace_all, array from to); +array_fn!(list_replace_all, array_replace_all, array from to); +array_fn!(array_intersect, first_array second_array); +array_fn!(list_intersect, array_intersect, first_array second_array); +array_fn!(array_union, array1 array2); +array_fn!(list_union, array_union, array1 array2); +array_fn!(array_except, first_array second_array); +array_fn!(list_except, array_except, first_array second_array); +array_fn!(array_resize, array size value); +array_fn!(list_resize, array_resize, array size value); +array_fn!(flatten, array); +array_fn!(range, start stop step); aggregate_function!(approx_distinct, ApproxDistinct); aggregate_function!(approx_median, ApproxMedian);