Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement native support StringView for REPEAT #11962

Merged
merged 3 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 72 additions & 12 deletions datafusion/functions/src/string/repeat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@
use std::any::Any;
use std::sync::Arc;

use arrow::array::{ArrayRef, GenericStringArray, OffsetSizeTrait};
use arrow::array::{ArrayRef, GenericStringArray, OffsetSizeTrait, StringArray};
use arrow::datatypes::DataType;

use datafusion_common::cast::{as_generic_string_array, as_int64_array};
use datafusion_common::cast::{
as_generic_string_array, as_int64_array, as_string_view_array,
};
use datafusion_common::{exec_err, Result};
use datafusion_expr::TypeSignature::*;
use datafusion_expr::{ColumnarValue, Volatility};
Expand All @@ -45,7 +47,14 @@ impl RepeatFunc {
use DataType::*;
Self {
signature: Signature::one_of(
vec![Exact(vec![Utf8, Int64]), Exact(vec![LargeUtf8, Int64])],
vec![
// Planner attempts coercion to the target type starting with the most preferred candidate.
// For example, given input `(Utf8View, Int64)`, it first tries coercing to `(Utf8View, Int64)`.
// If that fails, it proceeds to `(Utf8, Int64)`.
Exact(vec![Utf8View, Int64]),
Exact(vec![Utf8, Int64]),
Exact(vec![LargeUtf8, Int64]),
],
Volatility::Immutable,
),
}
Expand All @@ -71,9 +80,10 @@ impl ScalarUDFImpl for RepeatFunc {

fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> {
match args[0].data_type() {
DataType::Utf8View => make_scalar_function(repeat_utf8view, vec![])(args),
DataType::Utf8 => make_scalar_function(repeat::<i32>, vec![])(args),
DataType::LargeUtf8 => make_scalar_function(repeat::<i64>, vec![])(args),
other => exec_err!("Unsupported data type {other:?} for function repeat"),
other => exec_err!("Unsupported data type {other:?} for function repeat. Expected Utf8, Utf8View or LargeUtf8"),
}
}
}
Expand All @@ -87,18 +97,35 @@ fn repeat<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
let result = string_array
.iter()
.zip(number_array.iter())
.map(|(string, number)| match (string, number) {
(Some(string), Some(number)) if number >= 0 => {
Some(string.repeat(number as usize))
}
(Some(_), Some(_)) => Some("".to_string()),
_ => None,
})
.map(|(string, number)| repeat_common(string, number))
.collect::<GenericStringArray<T>>();

Ok(Arc::new(result) as ArrayRef)
}

fn repeat_utf8view(args: &[ArrayRef]) -> Result<ArrayRef> {
let string_view_array = as_string_view_array(&args[0])?;
let number_array = as_int64_array(&args[1])?;

let result = string_view_array
.iter()
.zip(number_array.iter())
.map(|(string, number)| repeat_common(string, number))
.collect::<StringArray>();

Ok(Arc::new(result) as ArrayRef)
}

fn repeat_common(string: Option<&str>, number: Option<i64>) -> Option<String> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you could make this perform much better by avoiding the String and instead building the output directly with StringViewBuilder

https://docs.rs/arrow/latest/arrow/array/type.StringViewBuilder.html

here is an example of how to use them: apache/arrow-rs#6240

I realize this just follows the same model as was here. However, if we are messing with the code it might be nice to make it faster while we are at it

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alamb thanks so much for reviewing. I will take a look!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you -- I filed #11990 to track the idea

match (string, number) {
(Some(string), Some(number)) if number >= 0 => {
Some(string.repeat(number as usize))
}
(Some(_), Some(_)) => Some("".to_string()),
_ => None,
}
}

#[cfg(test)]
mod tests {
use arrow::array::{Array, StringArray};
Expand All @@ -124,7 +151,6 @@ mod tests {
Utf8,
StringArray
);

test_function!(
RepeatFunc::new(),
&[
Expand All @@ -148,6 +174,40 @@ mod tests {
StringArray
);

test_function!(
RepeatFunc::new(),
&[
ColumnarValue::Scalar(ScalarValue::Utf8View(Some(String::from("Pg")))),
ColumnarValue::Scalar(ScalarValue::Int64(Some(4))),
],
Ok(Some("PgPgPgPg")),
&str,
Utf8,
StringArray
);
test_function!(
RepeatFunc::new(),
&[
ColumnarValue::Scalar(ScalarValue::Utf8View(None)),
ColumnarValue::Scalar(ScalarValue::Int64(Some(4))),
],
Ok(None),
&str,
Utf8,
StringArray
);
test_function!(
RepeatFunc::new(),
&[
ColumnarValue::Scalar(ScalarValue::Utf8View(Some(String::from("Pg")))),
ColumnarValue::Scalar(ScalarValue::Int64(None)),
],
Ok(None),
&str,
Utf8,
StringArray
);

Ok(())
}
}
3 changes: 1 addition & 2 deletions datafusion/sqllogictest/test_files/string_view.slt
Original file line number Diff line number Diff line change
Expand Up @@ -860,14 +860,13 @@ logical_plan


## Ensure no casts for REPEAT
## TODO file ticket
query TT
EXPLAIN SELECT
REPEAT(column1_utf8view, 2) as c1
FROM test;
----
logical_plan
01)Projection: repeat(CAST(test.column1_utf8view AS Utf8), Int64(2)) AS c1
01)Projection: repeat(test.column1_utf8view, Int64(2)) AS c1
02)--TableScan: test projection=[column1_utf8view]

## Ensure no casts for REPLACE
Expand Down