Skip to content

Apache DataFusion SQL Query Engine

ARROW-9892: [Rust] [DataFusion] Added concat of utf8

Jorge C. Leitao7313f7e1970e
diff --git a/rust/datafusion/README.md b/rust/datafusion/README.md
index 8dd8e37b51..5cb5fb6c4b 100644
--- a/rust/datafusion/README.md
+++ b/rust/datafusion/README.md
@@ -55,7 +55,8 @@ DataFusion includes a simple command-line interactive SQL utility. See the [CLI
- [x] UDFs
- [x] Common math functions
- String functions
- - [x] Length of the string
+ - [x] Length
+ - [x] Concatenate
- [ ] Common date/time functions
- [x] Sorting
- [ ] Nested types
diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rs
index 4cb0c095ef..72727dea6c 100644
--- a/rust/datafusion/src/logical_plan/mod.rs
+++ b/rust/datafusion/src/logical_plan/mod.rs
@@ -668,6 +668,14 @@ pub fn length(e: Expr) -> Expr {
}
}
+/// returns the concatenation of string expressions
+pub fn concat(args: Vec<Expr>) -> Expr {
+ Expr::ScalarFunction {
+ fun: functions::ScalarFunction::Concat,
+ args,
+ }
+}
+
/// Create an aggregate expression
pub fn aggregate_expr(name: &str, expr: Expr) -> Expr {
Expr::AggregateFunction {
diff --git a/rust/datafusion/src/physical_plan/functions.rs b/rust/datafusion/src/physical_plan/functions.rs
index 1a9e2062f2..abd6a32555 100644
--- a/rust/datafusion/src/physical_plan/functions.rs
+++ b/rust/datafusion/src/physical_plan/functions.rs
@@ -35,6 +35,7 @@ use super::{
};
use crate::error::{ExecutionError, Result};
use crate::physical_plan::math_expressions;
+use crate::physical_plan::string_expressions;
use crate::physical_plan::udf;
use arrow::{
compute::kernels::length::length,
@@ -98,6 +99,8 @@ pub enum ScalarFunction {
Signum,
/// length
Length,
+ /// concat
+ Concat,
}
impl fmt::Display for ScalarFunction {
@@ -129,6 +132,7 @@ impl FromStr for ScalarFunction {
"abs" => ScalarFunction::Abs,
"signum" => ScalarFunction::Signum,
"length" => ScalarFunction::Length,
+ "concat" => ScalarFunction::Concat,
_ => {
return Err(ExecutionError::General(format!(
"There is no built-in function named {}",
@@ -147,11 +151,20 @@ pub fn return_type(fun: &ScalarFunction, arg_types: &Vec<DataType>) -> Result<Da
// verify that this is a valid set of data types for this function
data_types(&arg_types, &signature(fun))?;
+ if arg_types.len() == 0 {
+ // functions currently cannot be evaluated without arguments, as they can't
+ // know the number of rows to return.
+ return Err(ExecutionError::General(
+ format!("Function '{}' requires at least one argument", fun).to_string(),
+ ));
+ }
+
// the return type after coercion.
// for now, this is type-independent, but there will be built-in functions whose return type
// depends on the incoming type.
match fun {
ScalarFunction::Length => Ok(DataType::UInt32),
+ ScalarFunction::Concat => Ok(DataType::Utf8),
_ => Ok(DataType::Float64),
}
}
@@ -182,6 +195,9 @@ pub fn create_physical_expr(
ScalarFunction::Abs => math_expressions::abs,
ScalarFunction::Signum => math_expressions::signum,
ScalarFunction::Length => |args| Ok(Arc::new(length(args[0].as_ref())?)),
+ ScalarFunction::Concat => {
+ |args| Ok(Arc::new(string_expressions::concatenate(args)?))
+ }
});
// coerce
let args = coerce(args, input_schema, &signature(fun))?;
@@ -206,6 +222,7 @@ fn signature(fun: &ScalarFunction) -> Signature {
// for now, the list is small, as we do not have many built-in functions.
match fun {
ScalarFunction::Length => Signature::Uniform(1, vec![DataType::Utf8]),
+ ScalarFunction::Concat => Signature::Variadic(vec![DataType::Utf8]),
// math expressions expect 1 argument of type f64 or f32
// priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we
// return the best approximation for it (in f64).
@@ -222,7 +239,7 @@ mod tests {
error::Result, logical_plan::ScalarValue, physical_plan::expressions::lit,
};
use arrow::{
- array::{ArrayRef, Float64Array, Int32Array},
+ array::{ArrayRef, Float64Array, Int32Array, StringArray},
datatypes::Field,
record_batch::RecordBatch,
};
@@ -264,4 +281,49 @@ mod tests {
generic_test_math(ScalarValue::Float32(1f32), exp_f32)?;
Ok(())
}
+
+ fn test_concat(value: ScalarValue, expected: &str) -> Result<()> {
+ // any type works here: we evaluate against a literal of `value`
+ let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
+ let columns: Vec<ArrayRef> = vec![Arc::new(Int32Array::from(vec![1]))];
+
+ // concat(value, value)
+ let expr = create_physical_expr(
+ &ScalarFunction::Concat,
+ &vec![lit(value.clone()), lit(value)],
+ &schema,
+ )?;
+
+ // type is correct
+ assert_eq!(expr.data_type(&schema)?, DataType::Utf8);
+
+ // evaluate works
+ let result =
+ expr.evaluate(&RecordBatch::try_new(Arc::new(schema.clone()), columns)?)?;
+
+ // downcast works
+ let result = result.as_any().downcast_ref::<StringArray>().unwrap();
+
+ // value is correct
+ assert_eq!(format!("{}", result.value(0)), expected);
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_concat_utf8() -> Result<()> {
+ test_concat(ScalarValue::Utf8("aa".to_string()), "aaaa")
+ }
+
+ #[test]
+ fn test_concat_error() -> Result<()> {
+ let result = return_type(&ScalarFunction::Concat, &vec![]);
+ if let Ok(_) = result {
+ Err(ExecutionError::General(
+ "Function 'concat' cannot accept zero arguments".to_string(),
+ ))
+ } else {
+ Ok(())
+ }
+ }
}
diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rs
index bc7c820c85..4977ae3b9a 100644
--- a/rust/datafusion/src/physical_plan/mod.rs
+++ b/rust/datafusion/src/physical_plan/mod.rs
@@ -146,5 +146,6 @@ pub mod parquet;
pub mod planner;
pub mod projection;
pub mod sort;
+pub mod string_expressions;
pub mod type_coercion;
pub mod udf;
diff --git a/rust/datafusion/src/physical_plan/string_expressions.rs b/rust/datafusion/src/physical_plan/string_expressions.rs
new file mode 100644
index 0000000000..89e06f03bc
--- /dev/null
+++ b/rust/datafusion/src/physical_plan/string_expressions.rs
@@ -0,0 +1,68 @@
+// 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.
+
+//! String expressions
+
+use crate::error::{ExecutionError, Result};
+use arrow::array::{Array, ArrayRef, StringArray, StringBuilder};
+
+macro_rules! downcast_vec {
+ ($ARGS:expr, $ARRAY_TYPE:ident) => {{
+ $ARGS
+ .iter()
+ .map(|e| match e.as_any().downcast_ref::<$ARRAY_TYPE>() {
+ Some(array) => Ok(array),
+ _ => Err(ExecutionError::General("failed to downcast".to_string())),
+ })
+ }};
+}
+
+/// concatenate string columns together.
+pub fn concatenate(args: &[ArrayRef]) -> Result<StringArray> {
+ // downcast all arguments to strings
+ let args = downcast_vec!(args, StringArray).collect::<Result<Vec<&StringArray>>>()?;
+ // do not accept 0 arguments.
+ if args.len() == 0 {
+ return Err(ExecutionError::InternalError(
+ "Concatenate was called with 0 arguments. It requires at least one."
+ .to_string(),
+ ));
+ }
+
+ let mut builder = StringBuilder::new(args.len());
+ // for each entry in the array
+ for index in 0..args[0].len() {
+ let mut owned_string: String = "".to_owned();
+
+ // if any is null, the result is null
+ let mut is_null = false;
+ for arg in &args {
+ if arg.is_null(index) {
+ is_null = true;
+ break; // short-circuit as we already know the result
+ } else {
+ owned_string.push_str(&arg.value(index));
+ }
+ }
+ if is_null {
+ builder.append_null()?;
+ } else {
+ builder.append_value(&owned_string)?;
+ }
+ }
+ Ok(builder.finish())
+}
diff --git a/rust/datafusion/src/prelude.rs b/rust/datafusion/src/prelude.rs
index effc814760..25e5dd366f 100644
--- a/rust/datafusion/src/prelude.rs
+++ b/rust/datafusion/src/prelude.rs
@@ -27,5 +27,5 @@
pub use crate::dataframe::DataFrame;
pub use crate::execution::context::{ExecutionConfig, ExecutionContext};
-pub use crate::logical_plan::{avg, col, count, lit, max, min, sum};
+pub use crate::logical_plan::{avg, col, concat, count, length, lit, max, min, sum};
pub use crate::physical_plan::csv::CsvReadOptions;
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index 345ab894f7..852a060f1f 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -656,7 +656,11 @@ fn result_str(results: &[RecordBatch]) -> Vec<String> {
DataType::Utf8 => {
let array =
column.as_any().downcast_ref::<StringArray>().unwrap();
- let s = array.value(row_index);
+ let s = if array.is_null(row_index) {
+ "NULL"
+ } else {
+ array.value(row_index)
+ };
str.push_str(&format!("{:?}", s));
}
@@ -696,6 +700,32 @@ fn query_length() -> Result<()> {
Ok(())
}
+#[test]
+fn query_concat() -> Result<()> {
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("c1", DataType::Utf8, false),
+ Field::new("c2", DataType::Int32, true),
+ ]));
+
+ let data = RecordBatch::try_new(
+ schema.clone(),
+ vec![
+ Arc::new(StringArray::from(vec!["", "a", "aa", "aaa"])),
+ Arc::new(Int32Array::from(vec![Some(0), Some(1), None, Some(3)])),
+ ],
+ )?;
+
+ let table = MemTable::new(schema, vec![vec![data]])?;
+
+ let mut ctx = ExecutionContext::new();
+ ctx.register_table("test", Box::new(table));
+ let sql = "SELECT concat(c1, '-hi-', cast(c2 as varchar)) FROM test";
+ let actual = execute(&mut ctx, sql);
+ let expected = vec!["\"-hi-0\"", "\"a-hi-1\"", "\"NULL\"", "\"aaa-hi-3\""];
+ assert_eq!(expected, actual);
+ Ok(())
+}
+
#[test]
fn csv_query_sum_cast() {
let mut ctx = ExecutionContext::new();