alamb commented on code in PR #9973:
URL: https://github.com/apache/arrow-datafusion/pull/9973#discussion_r1555005836
##########
datafusion/sqllogictest/test_files/functions.slt:
##########
@@ -954,6 +955,14 @@ SELECT str, n, substring_index(str, '.', n) AS c FROM
) AS occurrences(n)
ORDER BY str DESC, n;
----
+NULL -100 NULL
Review Comment:
💯 thank you
##########
datafusion/functions/src/unicode/substrindex.rs:
##########
@@ -101,38 +101,151 @@ pub fn substr_index<T: OffsetSizeTrait>(args:
&[ArrayRef]) -> Result<ArrayRef> {
let delimiter_array = as_generic_string_array::<T>(&args[1])?;
let count_array = as_int64_array(&args[2])?;
- let result = string_array
+ let mut builder = StringBuilder::new();
+ string_array
.iter()
.zip(delimiter_array.iter())
.zip(count_array.iter())
- .map(|((string, delimiter), n)| match (string, delimiter, n) {
+ .for_each(|((string, delimiter), n)| match (string, delimiter, n) {
(Some(string), Some(delimiter), Some(n)) => {
// In MySQL, these cases will return an empty string.
if n == 0 || string.is_empty() || delimiter.is_empty() {
- return Some(String::new());
+ builder.append_value("");
+ return;
}
- let splitted: Box<dyn Iterator<Item = _>> = if n > 0 {
- Box::new(string.split(delimiter))
+ let occurrences =
usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX);
+ let length = if n > 0 {
+ let splitted = string.split(delimiter);
+ splitted
+ .take(occurrences)
+ .map(|s| s.len() + delimiter.len())
+ .sum::<usize>()
+ - delimiter.len()
} else {
- Box::new(string.rsplit(delimiter))
+ let splitted = string.rsplit(delimiter);
+ splitted
+ .take(occurrences)
+ .map(|s| s.len() + delimiter.len())
+ .sum::<usize>()
+ - delimiter.len()
};
- let occurrences =
usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX);
- // The length of the substring covered by substr_index.
- let length = splitted
- .take(occurrences) // at least 1 element, since n != 0
- .map(|s| s.len() + delimiter.len())
- .sum::<usize>()
- - delimiter.len();
if n > 0 {
- Some(string[..length].to_owned())
+ match string.get(..length) {
+ Some(substring) => builder.append_value(substring),
+ None => builder.append_null(),
+ }
} else {
- Some(string[string.len() - length..].to_owned())
+ match string.get(string.len().saturating_sub(length)..) {
+ Some(substring) => builder.append_value(substring),
+ None => builder.append_null(),
+ }
}
}
- _ => None,
- })
- .collect::<GenericStringArray<T>>();
+ _ => builder.append_null(),
+ });
+
+ Ok(Arc::new(builder.finish()) as ArrayRef)
Review Comment:
👨🍳 👌 -- very nice
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]