You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2021/03/07 23:25:48 UTC
[GitHub] [arrow] seddonm1 opened a new pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
seddonm1 opened a new pull request #9654:
URL: https://github.com/apache/arrow/pull/9654
@alamb the last one (for now).
This PR does a few things:
- adds `regexp_replace`, `replace`, `split_part`, `starts_with`, `strpos` and `translate`.
- adds feature flag `unicode_expressions` and moves anything that depends on `unicode-segmentation` crate into it.
- adds feature flag `regex_expressions` and adds `regex` and `lazy_static` crates to it.
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] alamb commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r590734861
##########
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 see -- I took a closer look and I see now that `graphemes` is an iterator -- so we are `clone()` ing an iterator, which I guess feels right to me -- the code has to effectively scan the input to figure out how many graphemes long it is and then scan it again to create the output.
Sorry for my confusion!
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589816050
##########
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:
👍
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-793107168
Truly looks great @seddonm1 I added some comments
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589813852
##########
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:
There is definitely more work to be done with regex but we have feature flagged it so we should easily be able to add more here then promote them up.
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-794486991
@alamb I have removed the `std::str::from_utf8`. We should be good to go. 🥳
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-794452222
Thanks @alamb. I will make some more tweaks to these unicode functions to try to remove `std::str::from_utf8` then let you know.
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] alamb commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
alamb commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-793121615
Integration test failure looked like https://issues.apache.org/jira/browse/ARROW-11908 so I retriggered the CI checks
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] alamb commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
alamb commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-792833070
Thanks @seddonm1 -- I'll plan to look at this later today or tomorrow
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-796178701
@alamb hitting some CICD issues - nothing to do with this change.
```==========================================================
Testing file auth:basic_proto
==========================================================
################# FAILURES #################
FAILED TEST: auth:basic_proto Rust producing, C++ consuming
1 failures
Traceback (most recent call last):
File "/arrow/dev/archery/archery/integration/util.py", line 139, in run_cmd
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
File "/opt/conda/envs/arrow/lib/python3.8/subprocess.py", line 415, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/opt/conda/envs/arrow/lib/python3.8/subprocess.py", line 516, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/build/cpp/debug/flight-test-integration-client', '-host', 'localhost', '-port=43311', '-scenario', 'auth:basic_proto']' died with <Signals.SIGABRT: 6>.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/arrow/dev/archery/archery/integration/runner.py", line 308, in _run_flight_test_case
consumer.flight_request(port, **client_args)
File "/arrow/dev/archery/archery/integration/tester_cpp.py", line 116, in flight_request
run_cmd(cmd)
File "/arrow/dev/archery/archery/integration/util.py", line 148, in run_cmd
raise RuntimeError(sio.getvalue())
RuntimeError: Command failed: /build/cpp/debug/flight-test-integration-client -host localhost -port=43311 -scenario auth:basic_proto
With output:
--------------
-- Arrow Fatal Error --
Invalid: Expected UNAUTHENTICATED but got Unavailable
```
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589848722
##########
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:
@alamb I have refactored just the `left` function to demonstrate how it could be done:
https://github.com/apache/arrow/blob/7e40d25c8980102de48b26b88c04258b7fa04109/rust/datafusion/src/physical_plan/unicode_expressions.rs#L98
I think this is nicer so if you agree I can apply to the rest of the code?
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589759764
##########
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:
For any `unwrap()` I think it makes sense to put a comment why the unwrap is ok, and/or use `.expect`
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589814645
##########
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:
The code at line 115 does overload `pattern` (the key) with the flags. There is going to be opportunity to make some helper functions to manage these flags as we add more functions.
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589815674
##########
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:
:+1:
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589762868
##########
File path: rust/datafusion/src/physical_plan/string_expressions.rs
##########
@@ -794,85 +525,57 @@ pub fn rtrim<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
}
}
-/// Extracts the substring of string starting at the start'th character, and extending for count characters if that is specified. (Same as substring(string from start for count).)
-/// substr('alphabet', 3) = 'phabet'
-/// substr('alphabet', 3, 2) = 'ph'
-pub fn substr<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
- match args.len() {
- 2 => {
- let string_array = downcast_string_arg!(args[0], "string", T);
- let start_array = downcast_arg!(args[1], "start", Int64Array);
+/// Splits string at occurrences of delimiter and returns the n'th field (counting from one).
+/// split_part('abc~@~def~@~ghi', '~@~', 2) = 'def'
+pub fn split_part<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+ let string_array = downcast_string_arg!(args[0], "string", T);
+ let delimiter_array = downcast_string_arg!(args[1], "delimiter", T);
+ let n_array = downcast_arg!(args[2], "n", Int64Array);
- let result = string_array
- .iter()
- .zip(start_array.iter())
- .map(|(string, start)| match (string, start) {
- (None, _) => None,
- (_, None) => None,
- (Some(string), Some(start)) => {
- if start <= 0 {
- Some(string.to_string())
- } else {
- let graphemes = string.graphemes(true).collect::<Vec<&str>>();
- let start_pos = start as usize - 1;
- if graphemes.len() < start_pos {
- Some("".to_string())
- } else {
- Some(graphemes[start_pos..].concat())
- }
- }
+ let result = string_array
+ .iter()
+ .zip(delimiter_array.iter())
+ .zip(n_array.iter())
+ .map(|((string, delimiter), n)| match (string, delimiter, n) {
+ (None, _, _) => Ok(None),
+ (_, None, _) => Ok(None),
+ (_, _, None) => Ok(None),
+ (Some(string), Some(delimiter), Some(n)) => {
+ if n <= 0 {
+ Err(DataFusionError::Execution(
+ "field position must be greater than zero".to_string(),
+ ))
+ } else {
+ let split_string: Vec<&str> = string.split(delimiter).collect();
+ match split_string.get(n as usize - 1) {
+ Some(s) => Ok(Some(*s)),
+ None => Ok(Some("")),
}
- })
- .collect::<GenericStringArray<T>>();
+ }
+ }
+ })
+ .collect::<Result<GenericStringArray<T>>>()?;
- Ok(Arc::new(result) as ArrayRef)
- }
- 3 => {
- let string_array = downcast_string_arg!(args[0], "string", T);
- let start_array = downcast_arg!(args[1], "start", Int64Array);
- let count_array = downcast_arg!(args[2], "count", Int64Array);
+ Ok(Arc::new(result) as ArrayRef)
+}
- let result = string_array
- .iter()
- .zip(start_array.iter())
- .zip(count_array.iter())
- .map(|((string, start), count)| match (string, start, count) {
- (None, _, _) => Ok(None),
- (_, None, _) => Ok(None),
- (_, _, None) => Ok(None),
- (Some(string), Some(start), Some(count)) => {
- if count < 0 {
- Err(DataFusionError::Execution(
- "negative substring length not allowed".to_string(),
- ))
- } else if start <= 0 {
- Ok(Some(string.to_string()))
- } else {
- let graphemes = string.graphemes(true).collect::<Vec<&str>>();
- let start_pos = start as usize - 1;
- let count_usize = count as usize;
- if graphemes.len() < start_pos {
- Ok(Some("".to_string()))
- } else if graphemes.len() < start_pos + count_usize {
- Ok(Some(graphemes[start_pos..].concat()))
- } else {
- Ok(Some(
- graphemes[start_pos..start_pos + count_usize]
- .concat(),
- ))
- }
- }
- }
- })
- .collect::<Result<GenericStringArray<T>>>()?;
+/// Returns true if string starts with prefix.
+/// starts_with('alphabet', 'alph') = 't'
+pub fn starts_with<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+ let string_array = downcast_string_arg!(args[0], "string", T);
+ let prefix_array = downcast_string_arg!(args[1], "prefix", T);
- Ok(Arc::new(result) as ArrayRef)
- }
- other => Err(DataFusionError::Internal(format!(
- "substr was called with {} arguments. It requires 2 or 3.",
- other
- ))),
- }
+ let result = string_array
+ .iter()
+ .zip(prefix_array.iter())
+ .map(|(string, prefix)| match (string, prefix) {
+ (None, _) => None,
+ (_, None) => None,
Review comment:
Same as above
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589813533
##########
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:
Because this is just the return type and will always be Boolean whereas something like `InitCap` will return either `Utf8` or `LargeUtf8` depending on input 😁
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589765978
##########
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:
I think at some point this could be in arrow (and more parts of your string contributions).
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589816670
##########
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())
Review comment:
I'm hitting issues with the borrow checker so I think that the `String` allocation is required.
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589762510
##########
File path: rust/datafusion/src/physical_plan/string_expressions.rs
##########
@@ -794,85 +525,57 @@ pub fn rtrim<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
}
}
-/// Extracts the substring of string starting at the start'th character, and extending for count characters if that is specified. (Same as substring(string from start for count).)
-/// substr('alphabet', 3) = 'phabet'
-/// substr('alphabet', 3, 2) = 'ph'
-pub fn substr<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
- match args.len() {
- 2 => {
- let string_array = downcast_string_arg!(args[0], "string", T);
- let start_array = downcast_arg!(args[1], "start", Int64Array);
+/// Splits string at occurrences of delimiter and returns the n'th field (counting from one).
+/// split_part('abc~@~def~@~ghi', '~@~', 2) = 'def'
+pub fn split_part<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+ let string_array = downcast_string_arg!(args[0], "string", T);
+ let delimiter_array = downcast_string_arg!(args[1], "delimiter", T);
+ let n_array = downcast_arg!(args[2], "n", Int64Array);
- let result = string_array
- .iter()
- .zip(start_array.iter())
- .map(|(string, start)| match (string, start) {
- (None, _) => None,
- (_, None) => None,
- (Some(string), Some(start)) => {
- if start <= 0 {
- Some(string.to_string())
- } else {
- let graphemes = string.graphemes(true).collect::<Vec<&str>>();
- let start_pos = start as usize - 1;
- if graphemes.len() < start_pos {
- Some("".to_string())
- } else {
- Some(graphemes[start_pos..].concat())
- }
- }
+ let result = string_array
+ .iter()
+ .zip(delimiter_array.iter())
+ .zip(n_array.iter())
+ .map(|((string, delimiter), n)| match (string, delimiter, n) {
+ (None, _, _) => Ok(None),
Review comment:
Here the same, could be `_ -> Ok(None)`
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] alamb commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589762510
##########
File path: rust/datafusion/src/physical_plan/string_expressions.rs
##########
@@ -794,85 +525,57 @@ pub fn rtrim<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
}
}
-/// Extracts the substring of string starting at the start'th character, and extending for count characters if that is specified. (Same as substring(string from start for count).)
-/// substr('alphabet', 3) = 'phabet'
-/// substr('alphabet', 3, 2) = 'ph'
-pub fn substr<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
- match args.len() {
- 2 => {
- let string_array = downcast_string_arg!(args[0], "string", T);
- let start_array = downcast_arg!(args[1], "start", Int64Array);
+/// Splits string at occurrences of delimiter and returns the n'th field (counting from one).
+/// split_part('abc~@~def~@~ghi', '~@~', 2) = 'def'
+pub fn split_part<T: StringOffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
+ let string_array = downcast_string_arg!(args[0], "string", T);
+ let delimiter_array = downcast_string_arg!(args[1], "delimiter", T);
+ let n_array = downcast_arg!(args[2], "n", Int64Array);
- let result = string_array
- .iter()
- .zip(start_array.iter())
- .map(|(string, start)| match (string, start) {
- (None, _) => None,
- (_, None) => None,
- (Some(string), Some(start)) => {
- if start <= 0 {
- Some(string.to_string())
- } else {
- let graphemes = string.graphemes(true).collect::<Vec<&str>>();
- let start_pos = start as usize - 1;
- if graphemes.len() < start_pos {
- Some("".to_string())
- } else {
- Some(graphemes[start_pos..].concat())
- }
- }
+ let result = string_array
+ .iter()
+ .zip(delimiter_array.iter())
+ .zip(n_array.iter())
+ .map(|((string, delimiter), n)| match (string, delimiter, n) {
+ (None, _, _) => Ok(None),
Review comment:
Here the same, could be `_ -> None`
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589757540
##########
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())
Review comment:
Is `String` necessary or could we use `&str` in those iterators? (to avoid an extra allocation per item)
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] alamb commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
alamb commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-796282689
The integration test looks like https://issues.apache.org/jira/browse/ARROW-11908 so merging this one in. THanks again @seddonm1 !
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r590721947
##########
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:
The borrow checker is identifying that the second use of `graphemes` is using a moved value without the clone. If you can help resolve that it would help me learn.
```
use of moved value: `graphemes` value used here after move
```
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] alamb closed pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
alamb closed pull request #9654:
URL: https://github.com/apache/arrow/pull/9654
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] alamb commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
alamb commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r590715186
##########
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 like it a lot 👍 Thanks @seddonm1
I am not sure why this `clone` is needed, but that is a minor point and can be cleaned up later
```
let len = graphemes.clone().count() as i64;
```
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589763204
##########
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,
Review comment:
You got the idea 😃
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] seddonm1 commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
seddonm1 commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589817132
##########
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:
Let me have a look and see if we can do this.
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] Dandandan commented on a change in pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
Dandandan commented on a change in pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#discussion_r589762124
##########
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:
Those cases can be converted to one wildcard case below
----------------------------------------------------------------
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:
users@infra.apache.org
[GitHub] [arrow] github-actions[bot] commented on pull request #9654: ARROW-11656: [Rust][DataFusion] Remaining Postgres String functions
Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #9654:
URL: https://github.com/apache/arrow/pull/9654#issuecomment-792373859
https://issues.apache.org/jira/browse/ARROW-11656
----------------------------------------------------------------
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:
users@infra.apache.org