alamb commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589789458



##########
File path: rust/datafusion/src/physical_plan/functions.rs
##########
@@ -494,6 +532,27 @@ pub fn return_type(
                 ));
             }
         }),
+        BuiltinScalarFunction::SplitPart => Ok(match arg_types[0] {
+            DataType::LargeUtf8 => DataType::LargeUtf8,
+            DataType::Utf8 => DataType::Utf8,
+            _ => {
+                // this error is internal as `data_types` should have captured 
this.
+                return Err(DataFusionError::Internal(
+                    "The split_part function can only accept 
strings.".to_string(),
+                ));
+            }
+        }),
+        BuiltinScalarFunction::StartsWith => Ok(DataType::Boolean),

Review comment:
       I wonder if there is a reason not to check the arg types of 
`starts_with` given we are checking all the others?

##########
File path: rust/datafusion/src/physical_plan/regex_expressions.rs
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Some of these functions reference the Postgres documentation
+// or implementation to ensure compatibility and are subject to
+// the Postgres license.
+
+//! Regex expressions
+
+use std::any::type_name;
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use arrow::array::{ArrayRef, GenericStringArray, StringOffsetSizeTrait};
+use hashbrown::HashMap;
+use regex::Regex;
+
+macro_rules! downcast_string_arg {
+    ($ARG:expr, $NAME:expr, $T:ident) => {{
+        $ARG.as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "could not cast {} to {}",
+                    $NAME,
+                    type_name::<GenericStringArray<T>>()
+                ))
+            })?
+    }};
+}
+
+/// replace POSIX capture groups (like \1) with Rust Regex group (like ${1})
+/// used by regexp_replace
+fn regex_replace_posix_groups(replacement: &str) -> String {
+    lazy_static! {
+        static ref CAPTURE_GROUPS_RE: Regex = 
Regex::new("(\\\\)(\\d*)").unwrap();
+    }
+    CAPTURE_GROUPS_RE
+        .replace_all(replacement, "$${$2}")
+        .into_owned()
+}
+
+/// Replaces substring(s) matching a POSIX regular expression
+/// regexp_replace('Thomas', '.[mN]a.', 'M') = 'ThM'
+pub fn regexp_replace<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {
+    // creating Regex is expensive so create hashmap for memoization
+    let mut patterns: HashMap<String, Regex> = HashMap::new();

Review comment:
       👍 

##########
File path: rust/datafusion/Cargo.toml
##########
@@ -40,10 +40,12 @@ name = "datafusion-cli"
 path = "src/bin/main.rs"
 
 [features]
-default = ["cli", "crypto_expressions"]
+default = ["cli", "crypto_expressions", "regex_expressions", 
"unicode_expressions"]
 cli = ["rustyline"]
 simd = ["arrow/simd"]
 crypto_expressions = ["md-5", "sha2"]
+regex_expressions = ["regex", "lazy_static"]
+unicode_expressions = ["unicode-segmentation"]

Review comment:
       ❤️ 

##########
File path: rust/datafusion/src/physical_plan/unicode_expressions.rs
##########
@@ -0,0 +1,537 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Some of these functions reference the Postgres documentation
+// or implementation to ensure compatibility and are subject to
+// the Postgres license.
+
+//! Unicode expressions
+
+use std::any::type_name;
+use std::cmp::Ordering;
+use std::str::from_utf8;
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use arrow::{
+    array::{
+        ArrayRef, GenericStringArray, Int64Array, PrimitiveArray, 
StringOffsetSizeTrait,
+    },
+    datatypes::{ArrowNativeType, ArrowPrimitiveType},
+};
+use hashbrown::HashMap;
+use unicode_segmentation::UnicodeSegmentation;
+
+macro_rules! downcast_string_arg {
+    ($ARG:expr, $NAME:expr, $T:ident) => {{
+        $ARG.as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "could not cast {} to {}",
+                    $NAME,
+                    type_name::<GenericStringArray<T>>()
+                ))
+            })?
+    }};
+}
+
+macro_rules! downcast_arg {
+    ($ARG:expr, $NAME:expr, $ARRAY_TYPE:ident) => {{
+        $ARG.as_any().downcast_ref::<$ARRAY_TYPE>().ok_or_else(|| {
+            DataFusionError::Internal(format!(
+                "could not cast {} to {}",
+                $NAME,
+                type_name::<$ARRAY_TYPE>()
+            ))
+        })?
+    }};
+}
+
+/// Returns number of characters in the string.
+/// character_length('josé') = 4
+pub fn character_length<T: ArrowPrimitiveType>(args: &[ArrayRef]) -> 
Result<ArrayRef>
+where
+    T::Native: StringOffsetSizeTrait,
+{
+    let string_array: &GenericStringArray<T::Native> = args[0]
+        .as_any()
+        .downcast_ref::<GenericStringArray<T::Native>>()
+        .ok_or_else(|| {
+            DataFusionError::Internal("could not cast string to 
StringArray".to_string())
+        })?;
+
+    let result = string_array
+        .iter()
+        .map(|string| {
+            string.map(|string: &str| {
+                T::Native::from_usize(string.graphemes(true).count()).unwrap()
+            })
+        })
+        .collect::<PrimitiveArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// Returns first n characters in the string, or when n is negative, returns 
all but last |n| characters.
+/// left('abcde', 2) = 'ab'
+pub fn left<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+    let n_array = downcast_arg!(args[1], "n", Int64Array);
+
+    let result = string_array
+        .iter()
+        .zip(n_array.iter())
+        .map(|(string, n)| match (string, n) {
+            (None, _) => None,
+            (_, None) => None,
+            (Some(string), Some(n)) => match n.cmp(&0) {
+                Ordering::Equal => Some(""),
+                Ordering::Greater => Some(
+                    string
+                        .grapheme_indices(true)
+                        .nth(n as usize)
+                        .map_or(string, |(i, _)| {
+                            &from_utf8(&string.as_bytes()[..i]).unwrap()
+                        }),
+                ),
+                Ordering::Less => Some(
+                    string
+                        .grapheme_indices(true)
+                        .rev()
+                        .nth(n.abs() as usize - 1)
+                        .map_or("", |(i, _)| {
+                            &from_utf8(&string.as_bytes()[..i]).unwrap()
+                        }),
+                ),
+            },
+        })
+        .collect::<GenericStringArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// 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).
+/// lpad('hi', 5, 'xy') = 'xyxhi'
+pub fn lpad<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    match args.len() {
+        2 => {
+            let string_array = downcast_string_arg!(args[0], "string", T);
+            let length_array = downcast_arg!(args[1], "length", Int64Array);
+
+            let result = string_array
+                .iter()
+                .zip(length_array.iter())
+                .map(|(string, length)| match (string, length) {
+                    (None, _) => None,
+                    (_, None) => None,
+                    (Some(string), Some(length)) => {
+                        let length = length as usize;
+                        if length == 0 {
+                            Some("".to_string())
+                        } else {
+                            let graphemes = 
string.graphemes(true).collect::<Vec<&str>>();
+                            if length < graphemes.len() {
+                                Some(graphemes[..length].concat())
+                            } else {
+                                let mut s = string.to_string();
+                                s.insert_str(
+                                    0,
+                                    " ".repeat(length - 
graphemes.len()).as_str(),
+                                );
+                                Some(s)
+                            }
+                        }
+                    }
+                })
+                .collect::<GenericStringArray<T>>();
+
+            Ok(Arc::new(result) as ArrayRef)
+        }
+        3 => {
+            let string_array = downcast_string_arg!(args[0], "string", T);
+            let length_array = downcast_arg!(args[1], "length", Int64Array);
+            let fill_array = downcast_string_arg!(args[2], "fill", T);
+
+            let result = string_array
+                .iter()
+                .zip(length_array.iter())
+                .zip(fill_array.iter())
+                .map(|((string, length), fill)| match (string, length, fill) {
+                    (None, _, _) => None,
+                    (_, None, _) => None,
+                    (_, _, None) => None,
+                    (Some(string), Some(length), Some(fill)) => {
+                        let length = length as usize;
+
+                        if length == 0 {
+                            Some("".to_string())
+                        } else {
+                            let graphemes = 
string.graphemes(true).collect::<Vec<&str>>();
+                            let fill_chars = 
fill.chars().collect::<Vec<char>>();
+
+                            if length < graphemes.len() {
+                                Some(graphemes[..length].concat())
+                            } else if fill_chars.is_empty() {
+                                Some(string.to_string())
+                            } else {
+                                let mut s = string.to_string();
+                                let mut char_vector =
+                                    Vec::<char>::with_capacity(length - 
graphemes.len());
+                                for l in 0..length - graphemes.len() {
+                                    char_vector.push(
+                                        *fill_chars.get(l % 
fill_chars.len()).unwrap(),
+                                    );
+                                }
+                                s.insert_str(
+                                    0,
+                                    
char_vector.iter().collect::<String>().as_str(),
+                                );
+                                Some(s)
+                            }
+                        }
+                    }
+                })
+                .collect::<GenericStringArray<T>>();
+
+            Ok(Arc::new(result) as ArrayRef)
+        }
+        other => Err(DataFusionError::Internal(format!(
+            "lpad was called with {} arguments. It requires at least 2 and at 
most 3.",
+            other
+        ))),
+    }
+}
+
+/// Reverses the order of the characters in the string.
+/// reverse('abcde') = 'edcba'
+pub fn reverse<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+
+    let result = string_array
+        .iter()
+        .map(|string| {
+            string.map(|string: &str| 
string.graphemes(true).rev().collect::<String>())
+        })
+        .collect::<GenericStringArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// Returns last n characters in the string, or when n is negative, returns 
all but first |n| characters.
+/// right('abcde', 2) = 'de'
+pub fn right<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+    let n_array = downcast_arg!(args[1], "n", Int64Array);
+
+    let result = string_array
+        .iter()
+        .zip(n_array.iter())
+        .map(|(string, n)| match (string, n) {
+            (None, _) => None,
+            (_, None) => None,
+            (Some(string), Some(n)) => match n.cmp(&0) {
+                Ordering::Equal => Some(""),
+                Ordering::Greater => Some(
+                    string
+                        .grapheme_indices(true)
+                        .rev()
+                        .nth(n as usize - 1)
+                        .map_or(string, |(i, _)| {
+                            &from_utf8(&string.as_bytes()[i..]).unwrap()

Review comment:
       here is another use of unwrap because of trying to find grapheme 
boundaries based on `grapheme_indicies` -- if we could use character length 
math rather than byte boundaries we might be able to avoid the unwraps

##########
File path: rust/datafusion/src/physical_plan/unicode_expressions.rs
##########
@@ -0,0 +1,537 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Some of these functions reference the Postgres documentation
+// or implementation to ensure compatibility and are subject to
+// the Postgres license.
+
+//! Unicode expressions
+
+use std::any::type_name;
+use std::cmp::Ordering;
+use std::str::from_utf8;
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use arrow::{
+    array::{
+        ArrayRef, GenericStringArray, Int64Array, PrimitiveArray, 
StringOffsetSizeTrait,
+    },
+    datatypes::{ArrowNativeType, ArrowPrimitiveType},
+};
+use hashbrown::HashMap;
+use unicode_segmentation::UnicodeSegmentation;
+
+macro_rules! downcast_string_arg {
+    ($ARG:expr, $NAME:expr, $T:ident) => {{
+        $ARG.as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "could not cast {} to {}",
+                    $NAME,
+                    type_name::<GenericStringArray<T>>()
+                ))
+            })?
+    }};
+}
+
+macro_rules! downcast_arg {
+    ($ARG:expr, $NAME:expr, $ARRAY_TYPE:ident) => {{
+        $ARG.as_any().downcast_ref::<$ARRAY_TYPE>().ok_or_else(|| {
+            DataFusionError::Internal(format!(
+                "could not cast {} to {}",
+                $NAME,
+                type_name::<$ARRAY_TYPE>()
+            ))
+        })?
+    }};
+}
+
+/// Returns number of characters in the string.
+/// character_length('josé') = 4
+pub fn character_length<T: ArrowPrimitiveType>(args: &[ArrayRef]) -> 
Result<ArrayRef>
+where
+    T::Native: StringOffsetSizeTrait,
+{
+    let string_array: &GenericStringArray<T::Native> = args[0]
+        .as_any()
+        .downcast_ref::<GenericStringArray<T::Native>>()
+        .ok_or_else(|| {
+            DataFusionError::Internal("could not cast string to 
StringArray".to_string())
+        })?;
+
+    let result = string_array
+        .iter()
+        .map(|string| {
+            string.map(|string: &str| {
+                T::Native::from_usize(string.graphemes(true).count()).unwrap()
+            })
+        })
+        .collect::<PrimitiveArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// Returns first n characters in the string, or when n is negative, returns 
all but last |n| characters.
+/// left('abcde', 2) = 'ab'
+pub fn left<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+    let n_array = downcast_arg!(args[1], "n", Int64Array);
+
+    let result = string_array
+        .iter()
+        .zip(n_array.iter())
+        .map(|(string, n)| match (string, n) {
+            (None, _) => None,
+            (_, None) => None,
+            (Some(string), Some(n)) => match n.cmp(&0) {
+                Ordering::Equal => Some(""),
+                Ordering::Greater => Some(
+                    string
+                        .grapheme_indices(true)
+                        .nth(n as usize)
+                        .map_or(string, |(i, _)| {
+                            &from_utf8(&string.as_bytes()[..i]).unwrap()
+                        }),
+                ),
+                Ordering::Less => Some(
+                    string
+                        .grapheme_indices(true)
+                        .rev()
+                        .nth(n.abs() as usize - 1)
+                        .map_or("", |(i, _)| {
+                            &from_utf8(&string.as_bytes()[..i]).unwrap()
+                        }),
+                ),
+            },
+        })
+        .collect::<GenericStringArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// 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).

Review comment:
       ```suggestion
   /// 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).
   ```

##########
File path: rust/datafusion/src/physical_plan/string_expressions.rs
##########
@@ -621,139 +463,28 @@ pub fn repeat<T: StringOffsetSizeTrait>(args: 
&[ArrayRef]) -> Result<ArrayRef> {
     Ok(Arc::new(result) as ArrayRef)
 }
 
-/// Reverses the order of the characters in the string.
-/// reverse('abcde') = 'edcba'
-pub fn reverse<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {
+/// Replaces all occurrences in string of substring from with substring to.
+/// replace('abcdefabcdef', 'cd', 'XX') = 'abXXefabXXef'
+pub fn replace<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {
     let string_array = downcast_string_arg!(args[0], "string", T);
+    let from_array = downcast_string_arg!(args[1], "from", T);
+    let to_array = downcast_string_arg!(args[2], "to", T);
 
     let result = string_array
         .iter()
-        .map(|string| {
-            string.map(|string: &str| 
string.graphemes(true).rev().collect::<String>())
+        .zip(from_array.iter())
+        .zip(to_array.iter())
+        .map(|((string, from), to)| match (string, from, to) {
+            (None, _, _) => None,

Review comment:
       same applies to `regex_replace` if you want to use a different pattern

##########
File path: rust/datafusion/tests/sql.rs
##########
@@ -2273,35 +2192,178 @@ async fn test_interval_expressions() -> Result<()> {
 }
 
 #[tokio::test]
-#[cfg_attr(not(feature = "crypto_expressions"), ignore)]
-async fn test_crypto_expressions() -> Result<()> {
-    test_expression!("md5('tom')", "34b7da764b21d298ef307d04d8152dc5");
-    test_expression!("md5('')", "d41d8cd98f00b204e9800998ecf8427e");
-    test_expression!("md5(NULL)", "NULL");
-    test_expression!(
-        "sha224('tom')",
-        "0bf6cb62649c42a9ae3876ab6f6d92ad36cb5414e495f8873292be4d"
-    );
+async fn test_string_expressions() -> Result<()> {

Review comment:
       the test cases look really good, as always

##########
File path: rust/datafusion/src/physical_plan/regex_expressions.rs
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Some of these functions reference the Postgres documentation
+// or implementation to ensure compatibility and are subject to
+// the Postgres license.
+
+//! Regex expressions
+
+use std::any::type_name;
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use arrow::array::{ArrayRef, GenericStringArray, StringOffsetSizeTrait};
+use hashbrown::HashMap;
+use regex::Regex;
+
+macro_rules! downcast_string_arg {
+    ($ARG:expr, $NAME:expr, $T:ident) => {{
+        $ARG.as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "could not cast {} to {}",
+                    $NAME,
+                    type_name::<GenericStringArray<T>>()
+                ))
+            })?
+    }};
+}
+
+/// replace POSIX capture groups (like \1) with Rust Regex group (like ${1})
+/// used by regexp_replace
+fn regex_replace_posix_groups(replacement: &str) -> String {
+    lazy_static! {
+        static ref CAPTURE_GROUPS_RE: Regex = 
Regex::new("(\\\\)(\\d*)").unwrap();
+    }
+    CAPTURE_GROUPS_RE
+        .replace_all(replacement, "$${$2}")
+        .into_owned()
+}
+
+/// Replaces substring(s) matching a POSIX regular expression
+/// regexp_replace('Thomas', '.[mN]a.', 'M') = 'ThM'
+pub fn regexp_replace<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {
+    // creating Regex is expensive so create hashmap for memoization
+    let mut patterns: HashMap<String, Regex> = HashMap::new();
+
+    match args.len() {
+        3 => {
+            let string_array = downcast_string_arg!(args[0], "string", T);
+            let pattern_array = downcast_string_arg!(args[1], "pattern", T);
+            let replacement_array = downcast_string_arg!(args[2], 
"replacement", T);
+
+            let result = string_array
+            .iter()
+            .zip(pattern_array.iter())
+            .zip(replacement_array.iter())
+            .map(|((string, pattern), replacement)| match (string, pattern, 
replacement) {
+                (None, _, _) => Ok(None),
+                (_, None, _) => Ok(None),
+                (_, _, None) => Ok(None),
+                (Some(string), Some(pattern), Some(replacement)) => {
+                    let replacement = regex_replace_posix_groups(replacement);
+
+                    // if patterns hashmap already has regexp then use else 
else create and return
+                    let re = match patterns.get(pattern) {
+                        Some(re) => Ok(re.clone()),
+                        None => {
+                            match Regex::new(pattern) {
+                                Ok(re) => {
+                                    patterns.insert(pattern.to_string(), 
re.clone());
+                                    Ok(re)
+                                },
+                                Err(err) => 
Err(DataFusionError::Execution(err.to_string())),
+                            }
+                        }
+                    };
+
+                    Some(re.map(|re| re.replace(string, 
replacement.as_str()))).transpose()
+                }
+            })
+            .collect::<Result<GenericStringArray<T>>>()?;
+
+            Ok(Arc::new(result) as ArrayRef)
+        }
+        4 => {
+            let string_array = downcast_string_arg!(args[0], "string", T);
+            let pattern_array = downcast_string_arg!(args[1], "pattern", T);
+            let replacement_array = downcast_string_arg!(args[2], 
"replacement", T);
+            let flags_array = downcast_string_arg!(args[3], "flags", T);
+
+            let result = string_array
+            .iter()
+            .zip(pattern_array.iter())
+            .zip(replacement_array.iter())
+            .zip(flags_array.iter())
+            .map(|(((string, pattern), replacement), flags)| match (string, 
pattern, replacement, flags) {
+                (None, _, _, _) => Ok(None),
+                (_, None, _, _) => Ok(None),
+                (_, _, None, _) => Ok(None),
+                (_, _, _, None) => Ok(None),
+                (Some(string), Some(pattern), Some(replacement), Some(flags)) 
=> {
+                    let replacement = regex_replace_posix_groups(replacement);
+
+                    // format flags into rust pattern
+                    let (pattern, replace_all) = if flags == "g" {
+                        (pattern.to_string(), true)
+                    } else if flags.contains('g') {
+                        (format!("(?{}){}", flags.to_string().replace("g", 
""), pattern), true)
+                    } else {
+                        (format!("(?{}){}", flags, pattern), false)
+                    };
+
+                    // if patterns hashmap already has regexp then use else 
else create and return
+                    let re = match patterns.get(&pattern) {

Review comment:
       I was worried that the key into the hashmap might not include the flags, 
but that seems not the be the case 
   
   This clause seems basically copy/paste from the `3` case above -- maybe (in 
a future PR) or something we could consolidate them into a helper or something

##########
File path: rust/datafusion/src/physical_plan/unicode_expressions.rs
##########
@@ -0,0 +1,537 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Some of these functions reference the Postgres documentation
+// or implementation to ensure compatibility and are subject to
+// the Postgres license.
+
+//! Unicode expressions
+
+use std::any::type_name;
+use std::cmp::Ordering;
+use std::str::from_utf8;
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use arrow::{
+    array::{
+        ArrayRef, GenericStringArray, Int64Array, PrimitiveArray, 
StringOffsetSizeTrait,
+    },
+    datatypes::{ArrowNativeType, ArrowPrimitiveType},
+};
+use hashbrown::HashMap;
+use unicode_segmentation::UnicodeSegmentation;
+
+macro_rules! downcast_string_arg {
+    ($ARG:expr, $NAME:expr, $T:ident) => {{
+        $ARG.as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "could not cast {} to {}",
+                    $NAME,
+                    type_name::<GenericStringArray<T>>()
+                ))
+            })?
+    }};
+}
+
+macro_rules! downcast_arg {
+    ($ARG:expr, $NAME:expr, $ARRAY_TYPE:ident) => {{
+        $ARG.as_any().downcast_ref::<$ARRAY_TYPE>().ok_or_else(|| {
+            DataFusionError::Internal(format!(
+                "could not cast {} to {}",
+                $NAME,
+                type_name::<$ARRAY_TYPE>()
+            ))
+        })?
+    }};
+}
+
+/// Returns number of characters in the string.
+/// character_length('josé') = 4
+pub fn character_length<T: ArrowPrimitiveType>(args: &[ArrayRef]) -> 
Result<ArrayRef>
+where
+    T::Native: StringOffsetSizeTrait,
+{
+    let string_array: &GenericStringArray<T::Native> = args[0]
+        .as_any()
+        .downcast_ref::<GenericStringArray<T::Native>>()
+        .ok_or_else(|| {
+            DataFusionError::Internal("could not cast string to 
StringArray".to_string())
+        })?;
+
+    let result = string_array
+        .iter()
+        .map(|string| {
+            string.map(|string: &str| {
+                T::Native::from_usize(string.graphemes(true).count()).unwrap()
+            })
+        })
+        .collect::<PrimitiveArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// Returns first n characters in the string, or when n is negative, returns 
all but last |n| characters.
+/// left('abcde', 2) = 'ab'
+pub fn left<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+    let n_array = downcast_arg!(args[1], "n", Int64Array);
+
+    let result = string_array
+        .iter()
+        .zip(n_array.iter())
+        .map(|(string, n)| match (string, n) {
+            (None, _) => None,
+            (_, None) => None,
+            (Some(string), Some(n)) => match n.cmp(&0) {
+                Ordering::Equal => Some(""),
+                Ordering::Greater => Some(
+                    string
+                        .grapheme_indices(true)
+                        .nth(n as usize)
+                        .map_or(string, |(i, _)| {
+                            &from_utf8(&string.as_bytes()[..i]).unwrap()

Review comment:
       I spent some time poking around in 
https://docs.rs/unicode-segmentation/1.7.1/unicode_segmentation/trait.UnicodeSegmentation.html#tymethod.graphemes
   
   I couldn't find anything that would let you get back a `&str` from the 
grapheme indices. I wonder if it might be possible to use the `graphemes()` 
call itself and count up the lengths of the `&str` that came back
   
   
https://docs.rs/unicode-segmentation/1.7.1/unicode_segmentation/trait.UnicodeSegmentation.html#tymethod.graphemes
   
   Something like (untested)
   
   ```rust
   let i = strings
     .graphemes()
     .limit(n as usize)
     .map(|s| s.len())
     .sum()
   
   string[..i]
   ```
   
   Or something like that. I am not sure how important this is
   

##########
File path: rust/datafusion/src/physical_plan/regex_expressions.rs
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Some of these functions reference the Postgres documentation
+// or implementation to ensure compatibility and are subject to
+// the Postgres license.
+
+//! Regex expressions
+
+use std::any::type_name;
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use arrow::array::{ArrayRef, GenericStringArray, StringOffsetSizeTrait};
+use hashbrown::HashMap;
+use regex::Regex;
+
+macro_rules! downcast_string_arg {
+    ($ARG:expr, $NAME:expr, $T:ident) => {{
+        $ARG.as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "could not cast {} to {}",
+                    $NAME,
+                    type_name::<GenericStringArray<T>>()
+                ))
+            })?
+    }};
+}
+
+/// replace POSIX capture groups (like \1) with Rust Regex group (like ${1})
+/// used by regexp_replace
+fn regex_replace_posix_groups(replacement: &str) -> String {
+    lazy_static! {
+        static ref CAPTURE_GROUPS_RE: Regex = 
Regex::new("(\\\\)(\\d*)").unwrap();
+    }
+    CAPTURE_GROUPS_RE
+        .replace_all(replacement, "$${$2}")
+        .into_owned()
+}
+
+/// Replaces substring(s) matching a POSIX regular expression
+/// regexp_replace('Thomas', '.[mN]a.', 'M') = 'ThM'
+pub fn regexp_replace<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {

Review comment:
       Yeah -- it might be worth a discussion on the mailing list of what 
functions belong in datafusion and what are more "core" and broadly applicable 
to bring them into the core arrow kernels

##########
File path: rust/datafusion/src/physical_plan/unicode_expressions.rs
##########
@@ -0,0 +1,537 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Some of these functions reference the Postgres documentation
+// or implementation to ensure compatibility and are subject to
+// the Postgres license.
+
+//! Unicode expressions
+
+use std::any::type_name;
+use std::cmp::Ordering;
+use std::str::from_utf8;
+use std::sync::Arc;
+
+use crate::error::{DataFusionError, Result};
+use arrow::{
+    array::{
+        ArrayRef, GenericStringArray, Int64Array, PrimitiveArray, 
StringOffsetSizeTrait,
+    },
+    datatypes::{ArrowNativeType, ArrowPrimitiveType},
+};
+use hashbrown::HashMap;
+use unicode_segmentation::UnicodeSegmentation;
+
+macro_rules! downcast_string_arg {
+    ($ARG:expr, $NAME:expr, $T:ident) => {{
+        $ARG.as_any()
+            .downcast_ref::<GenericStringArray<T>>()
+            .ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "could not cast {} to {}",
+                    $NAME,
+                    type_name::<GenericStringArray<T>>()
+                ))
+            })?
+    }};
+}
+
+macro_rules! downcast_arg {
+    ($ARG:expr, $NAME:expr, $ARRAY_TYPE:ident) => {{
+        $ARG.as_any().downcast_ref::<$ARRAY_TYPE>().ok_or_else(|| {
+            DataFusionError::Internal(format!(
+                "could not cast {} to {}",
+                $NAME,
+                type_name::<$ARRAY_TYPE>()
+            ))
+        })?
+    }};
+}
+
+/// Returns number of characters in the string.
+/// character_length('josé') = 4
+pub fn character_length<T: ArrowPrimitiveType>(args: &[ArrayRef]) -> 
Result<ArrayRef>
+where
+    T::Native: StringOffsetSizeTrait,
+{
+    let string_array: &GenericStringArray<T::Native> = args[0]
+        .as_any()
+        .downcast_ref::<GenericStringArray<T::Native>>()
+        .ok_or_else(|| {
+            DataFusionError::Internal("could not cast string to 
StringArray".to_string())
+        })?;
+
+    let result = string_array
+        .iter()
+        .map(|string| {
+            string.map(|string: &str| {
+                T::Native::from_usize(string.graphemes(true).count()).unwrap()
+            })
+        })
+        .collect::<PrimitiveArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// Returns first n characters in the string, or when n is negative, returns 
all but last |n| characters.
+/// left('abcde', 2) = 'ab'
+pub fn left<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+    let n_array = downcast_arg!(args[1], "n", Int64Array);
+
+    let result = string_array
+        .iter()
+        .zip(n_array.iter())
+        .map(|(string, n)| match (string, n) {
+            (None, _) => None,
+            (_, None) => None,
+            (Some(string), Some(n)) => match n.cmp(&0) {
+                Ordering::Equal => Some(""),
+                Ordering::Greater => Some(
+                    string
+                        .grapheme_indices(true)
+                        .nth(n as usize)
+                        .map_or(string, |(i, _)| {
+                            &from_utf8(&string.as_bytes()[..i]).unwrap()
+                        }),
+                ),
+                Ordering::Less => Some(
+                    string
+                        .grapheme_indices(true)
+                        .rev()
+                        .nth(n.abs() as usize - 1)
+                        .map_or("", |(i, _)| {
+                            &from_utf8(&string.as_bytes()[..i]).unwrap()
+                        }),
+                ),
+            },
+        })
+        .collect::<GenericStringArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// 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).
+/// lpad('hi', 5, 'xy') = 'xyxhi'
+pub fn lpad<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    match args.len() {
+        2 => {
+            let string_array = downcast_string_arg!(args[0], "string", T);
+            let length_array = downcast_arg!(args[1], "length", Int64Array);
+
+            let result = string_array
+                .iter()
+                .zip(length_array.iter())
+                .map(|(string, length)| match (string, length) {
+                    (None, _) => None,
+                    (_, None) => None,
+                    (Some(string), Some(length)) => {
+                        let length = length as usize;
+                        if length == 0 {
+                            Some("".to_string())
+                        } else {
+                            let graphemes = 
string.graphemes(true).collect::<Vec<&str>>();
+                            if length < graphemes.len() {
+                                Some(graphemes[..length].concat())
+                            } else {
+                                let mut s = string.to_string();
+                                s.insert_str(
+                                    0,
+                                    " ".repeat(length - 
graphemes.len()).as_str(),
+                                );
+                                Some(s)
+                            }
+                        }
+                    }
+                })
+                .collect::<GenericStringArray<T>>();
+
+            Ok(Arc::new(result) as ArrayRef)
+        }
+        3 => {
+            let string_array = downcast_string_arg!(args[0], "string", T);
+            let length_array = downcast_arg!(args[1], "length", Int64Array);
+            let fill_array = downcast_string_arg!(args[2], "fill", T);
+
+            let result = string_array
+                .iter()
+                .zip(length_array.iter())
+                .zip(fill_array.iter())
+                .map(|((string, length), fill)| match (string, length, fill) {
+                    (None, _, _) => None,
+                    (_, None, _) => None,
+                    (_, _, None) => None,
+                    (Some(string), Some(length), Some(fill)) => {
+                        let length = length as usize;
+
+                        if length == 0 {
+                            Some("".to_string())
+                        } else {
+                            let graphemes = 
string.graphemes(true).collect::<Vec<&str>>();
+                            let fill_chars = 
fill.chars().collect::<Vec<char>>();
+
+                            if length < graphemes.len() {
+                                Some(graphemes[..length].concat())
+                            } else if fill_chars.is_empty() {
+                                Some(string.to_string())
+                            } else {
+                                let mut s = string.to_string();
+                                let mut char_vector =
+                                    Vec::<char>::with_capacity(length - 
graphemes.len());
+                                for l in 0..length - graphemes.len() {
+                                    char_vector.push(
+                                        *fill_chars.get(l % 
fill_chars.len()).unwrap(),
+                                    );
+                                }
+                                s.insert_str(
+                                    0,
+                                    
char_vector.iter().collect::<String>().as_str(),
+                                );
+                                Some(s)
+                            }
+                        }
+                    }
+                })
+                .collect::<GenericStringArray<T>>();
+
+            Ok(Arc::new(result) as ArrayRef)
+        }
+        other => Err(DataFusionError::Internal(format!(
+            "lpad was called with {} arguments. It requires at least 2 and at 
most 3.",
+            other
+        ))),
+    }
+}
+
+/// Reverses the order of the characters in the string.
+/// reverse('abcde') = 'edcba'
+pub fn reverse<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> 
Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+
+    let result = string_array
+        .iter()
+        .map(|string| {
+            string.map(|string: &str| 
string.graphemes(true).rev().collect::<String>())
+        })
+        .collect::<GenericStringArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// Returns last n characters in the string, or when n is negative, returns 
all but first |n| characters.
+/// right('abcde', 2) = 'de'
+pub fn right<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+    let string_array = downcast_string_arg!(args[0], "string", T);
+    let n_array = downcast_arg!(args[1], "n", Int64Array);
+
+    let result = string_array
+        .iter()
+        .zip(n_array.iter())
+        .map(|(string, n)| match (string, n) {
+            (None, _) => None,
+            (_, None) => None,
+            (Some(string), Some(n)) => match n.cmp(&0) {
+                Ordering::Equal => Some(""),
+                Ordering::Greater => Some(
+                    string
+                        .grapheme_indices(true)
+                        .rev()
+                        .nth(n as usize - 1)
+                        .map_or(string, |(i, _)| {
+                            &from_utf8(&string.as_bytes()[i..]).unwrap()
+                        }),
+                ),
+                Ordering::Less => Some(
+                    string
+                        .grapheme_indices(true)
+                        .nth(n.abs() as usize)
+                        .map_or("", |(i, _)| {
+                            &from_utf8(&string.as_bytes()[i..]).unwrap()
+                        }),
+                ),
+            },
+        })
+        .collect::<GenericStringArray<T>>();
+
+    Ok(Arc::new(result) as ArrayRef)
+}
+
+/// 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.

Review comment:
       ```suggestion
   /// 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.
   ```




----------------------------------------------------------------
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.

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


Reply via email to