You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "kazantsev-maksim (via GitHub)" <gi...@apache.org> on 2026/01/02 14:36:42 UTC
[PR] feat: Implement Spark function `space` [datafusion]
kazantsev-maksim opened a new pull request, #19610:
URL: https://github.com/apache/datafusion/pull/19610
## Which issue does this PR close?
N/A
## Rationale for this change
Add new function: https://spark.apache.org/docs/latest/api/sql/index.html#space
## What changes are included in this PR?
- Implementation
- Unit Tests
- SLT tests
## Are these changes tested?
Yes, tests added as part of this PR.
## Are there any user-facing changes?
No, these are new function.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#issuecomment-3707225410
@andygrove thanks for the review, еhe benchmark test result in Comet is still not ideal.
<img width="953" height="138" alt="space" src="https://github.com/user-attachments/assets/3e5194ab-9011-4e6d-b175-52525d32695f" />
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#discussion_r2659108649
##########
datafusion/spark/src/function/string/space.rs:
##########
@@ -0,0 +1,245 @@
+// 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.
+
+use arrow::array::{
+ Array, ArrayRef, DictionaryArray, Int32Array, StringArray, StringBuilder,
+ as_dictionary_array,
+};
+use arrow::datatypes::{DataType, Int32Type};
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{Result, ScalarValue, exec_err};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use std::any::Any;
+use std::sync::Arc;
+
+/// Spark-compatible `space` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#space>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkSpace {
+ signature: Signature,
+}
+
+impl Default for SparkSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkSpace {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::uniform(
+ 1,
+ vec![
+ DataType::Int32,
+ DataType::Dictionary(
+ Box::new(DataType::Int32),
+ Box::new(DataType::Int32),
+ ),
+ ],
+ Volatility::Immutable,
+ ),
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkSpace {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "space"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, args: &[DataType]) -> Result<DataType> {
+ let return_type = match &args[0] {
+ DataType::Dictionary(key_type, _) => {
+ DataType::Dictionary(key_type.clone(), Box::new(DataType::Utf8))
+ }
+ _ => DataType::Utf8,
+ };
+ Ok(return_type)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ spark_space(&args.args)
+ }
+}
+
+pub fn spark_space(args: &[ColumnarValue]) -> Result<ColumnarValue> {
+ if args.len() != 1 {
+ return exec_err!("space function takes exactly one argument");
+ }
+ match &args[0] {
+ ColumnarValue::Array(array) => {
+ let result = spark_space_array(array)?;
+ Ok(ColumnarValue::Array(result))
+ }
+ ColumnarValue::Scalar(scalar) => {
+ let result = spark_space_scalar(scalar)?;
+ Ok(ColumnarValue::Scalar(result))
+ }
+ }
+}
+
+fn spark_space_array(array: &ArrayRef) -> Result<ArrayRef> {
+ match array.data_type() {
+ DataType::Int32 => {
+ let array = as_int32_array(array)?;
+ Ok(Arc::new(spark_space_array_inner(array)))
+ }
+ DataType::Dictionary(_, _) => {
+ let dict = as_dictionary_array::<Int32Type>(array);
+ let values = spark_space_array(dict.values())?;
+ let result = DictionaryArray::try_new(dict.keys().clone(), values)?;
+ Ok(Arc::new(result))
+ }
+ other => {
+ exec_err!("Unsupported data type {other:?} for function `space`")
+ }
+ }
+}
+
+fn spark_space_scalar(scalar: &ScalarValue) -> Result<ScalarValue> {
+ match scalar {
+ ScalarValue::Int32(value) => {
+ let result = value.map(|v| {
+ if v <= 0 {
+ String::new()
+ } else {
+ " ".repeat(v as usize)
+ }
+ });
+ Ok(ScalarValue::Utf8(result))
+ }
+ other => {
+ exec_err!("Unsupported data type {other:?} for function `space`")
+ }
+ }
+}
+
+fn spark_space_array_inner(array: &Int32Array) -> StringArray {
+ let values = array.values();
+ let data_capacity = values
Review Comment:
Thanks @kazantsev-maksim just thinking aloud if we can iterate values only once?
```
fn spark_space_array_inner(array: &Int32Array) -> StringArray {
let mut builder = StringBuilder::new(array.len());
let mut space_buf = String::new();
for v in array.iter() {
match v {
None => builder.append_null(),
Some(l) if *l > 0 => {
let l = *l as usize;
if space_buf.len() < l {
space_buf = " ".repeat(l);
}
builder.append_value(&space_buf[..l]);
}
Some(_) => builder.append_value(""),
}
}
builder.finish()
}
```
something like that?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#issuecomment-3708446075
Thanks @kazantsev-maksim and @andygrove for the review
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#discussion_r2657908538
##########
datafusion/spark/src/function/string/space.rs:
##########
@@ -0,0 +1,178 @@
+// 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.
+
+use arrow::array::{ArrayRef, DictionaryArray, StringArray};
+use arrow::datatypes::{DataType, Int32Type};
+use datafusion_common::cast::{as_dictionary_array, as_int32_array};
+use datafusion_common::{Result, exec_err, plan_err};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use std::any::Any;
+use std::sync::Arc;
+
+/// Spark-compatible `space` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#space>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkSpace {
+ signature: Signature,
+}
+
+impl Default for SparkSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkSpace {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::uniform(
+ 1,
+ vec![
+ DataType::Int32,
+ DataType::Dictionary(
+ Box::new(DataType::Int32),
+ Box::new(DataType::Int32),
+ ),
+ ],
+ Volatility::Immutable,
+ ),
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkSpace {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "space"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, args: &[DataType]) -> Result<DataType> {
+ let return_type = match &args[0] {
+ DataType::Dictionary(key_type, _) => {
+ DataType::Dictionary(key_type.clone(), Box::new(DataType::Utf8))
+ }
+ _ => DataType::Utf8,
+ };
+ Ok(return_type)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ if args.args.len() != 1 {
+ return plan_err!("space expects exactly 1 argument");
+ }
+ make_scalar_function(spark_space, vec![])(&args.args)
Review Comment:
In fact, the return type in this case could be a scalar not an array
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#discussion_r2657943917
##########
datafusion/sqllogictest/test_files/spark/string/space.slt:
##########
@@ -0,0 +1,41 @@
+# 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.
+
+query T
+SELECT space(1::INT);
Review Comment:
Could you add tests that use array inputs. The tests currently only cover scalar inputs.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#discussion_r2657906973
##########
datafusion/spark/src/function/string/space.rs:
##########
@@ -0,0 +1,178 @@
+// 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.
+
+use arrow::array::{ArrayRef, DictionaryArray, StringArray};
+use arrow::datatypes::{DataType, Int32Type};
+use datafusion_common::cast::{as_dictionary_array, as_int32_array};
+use datafusion_common::{Result, exec_err, plan_err};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use std::any::Any;
+use std::sync::Arc;
+
+/// Spark-compatible `space` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#space>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkSpace {
+ signature: Signature,
+}
+
+impl Default for SparkSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkSpace {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::uniform(
+ 1,
+ vec![
+ DataType::Int32,
+ DataType::Dictionary(
+ Box::new(DataType::Int32),
+ Box::new(DataType::Int32),
+ ),
+ ],
+ Volatility::Immutable,
+ ),
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkSpace {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "space"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, args: &[DataType]) -> Result<DataType> {
+ let return_type = match &args[0] {
+ DataType::Dictionary(key_type, _) => {
+ DataType::Dictionary(key_type.clone(), Box::new(DataType::Utf8))
+ }
+ _ => DataType::Utf8,
+ };
+ Ok(return_type)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ if args.args.len() != 1 {
+ return plan_err!("space expects exactly 1 argument");
+ }
+ make_scalar_function(spark_space, vec![])(&args.args)
Review Comment:
I think that `space` is quite often invoked with a literl argument e.g. `space(2)`. The current implementation converts the scalar value into an array for each batch and then calls `" ".repeat(m as usize)` for each row, resulting in the exact same string being allocated each time. This could be optimized in the scalar case to build the string once rather than per-row and then append the same string to the builder repeatedly.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead merged PR #19610:
URL: https://github.com/apache/datafusion/pull/19610
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#discussion_r2659596647
##########
datafusion/spark/src/function/string/space.rs:
##########
@@ -0,0 +1,245 @@
+// 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.
+
+use arrow::array::{
+ Array, ArrayRef, DictionaryArray, Int32Array, StringArray, StringBuilder,
+ as_dictionary_array,
+};
+use arrow::datatypes::{DataType, Int32Type};
+use datafusion_common::cast::as_int32_array;
+use datafusion_common::{Result, ScalarValue, exec_err};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use std::any::Any;
+use std::sync::Arc;
+
+/// Spark-compatible `space` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#space>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkSpace {
+ signature: Signature,
+}
+
+impl Default for SparkSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkSpace {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::uniform(
+ 1,
+ vec![
+ DataType::Int32,
+ DataType::Dictionary(
+ Box::new(DataType::Int32),
+ Box::new(DataType::Int32),
+ ),
+ ],
+ Volatility::Immutable,
+ ),
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkSpace {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "space"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, args: &[DataType]) -> Result<DataType> {
+ let return_type = match &args[0] {
+ DataType::Dictionary(key_type, _) => {
+ DataType::Dictionary(key_type.clone(), Box::new(DataType::Utf8))
+ }
+ _ => DataType::Utf8,
+ };
+ Ok(return_type)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ spark_space(&args.args)
+ }
+}
+
+pub fn spark_space(args: &[ColumnarValue]) -> Result<ColumnarValue> {
+ if args.len() != 1 {
+ return exec_err!("space function takes exactly one argument");
+ }
+ match &args[0] {
+ ColumnarValue::Array(array) => {
+ let result = spark_space_array(array)?;
+ Ok(ColumnarValue::Array(result))
+ }
+ ColumnarValue::Scalar(scalar) => {
+ let result = spark_space_scalar(scalar)?;
+ Ok(ColumnarValue::Scalar(result))
+ }
+ }
+}
+
+fn spark_space_array(array: &ArrayRef) -> Result<ArrayRef> {
+ match array.data_type() {
+ DataType::Int32 => {
+ let array = as_int32_array(array)?;
+ Ok(Arc::new(spark_space_array_inner(array)))
+ }
+ DataType::Dictionary(_, _) => {
+ let dict = as_dictionary_array::<Int32Type>(array);
+ let values = spark_space_array(dict.values())?;
+ let result = DictionaryArray::try_new(dict.keys().clone(), values)?;
+ Ok(Arc::new(result))
+ }
+ other => {
+ exec_err!("Unsupported data type {other:?} for function `space`")
+ }
+ }
+}
+
+fn spark_space_scalar(scalar: &ScalarValue) -> Result<ScalarValue> {
+ match scalar {
+ ScalarValue::Int32(value) => {
+ let result = value.map(|v| {
+ if v <= 0 {
+ String::new()
+ } else {
+ " ".repeat(v as usize)
+ }
+ });
+ Ok(ScalarValue::Utf8(result))
+ }
+ other => {
+ exec_err!("Unsupported data type {other:?} for function `space`")
+ }
+ }
+}
+
+fn spark_space_array_inner(array: &Int32Array) -> StringArray {
+ let values = array.values();
+ let data_capacity = values
Review Comment:
@comphead thanks, performance has improved!
<img width="622" height="53" alt="bench" src="https://github.com/user-attachments/assets/e409c1c0-1303-4da5-940c-dcfbf294c1b3" />
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#discussion_r2657906973
##########
datafusion/spark/src/function/string/space.rs:
##########
@@ -0,0 +1,178 @@
+// 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.
+
+use arrow::array::{ArrayRef, DictionaryArray, StringArray};
+use arrow::datatypes::{DataType, Int32Type};
+use datafusion_common::cast::{as_dictionary_array, as_int32_array};
+use datafusion_common::{Result, exec_err, plan_err};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use std::any::Any;
+use std::sync::Arc;
+
+/// Spark-compatible `space` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#space>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkSpace {
+ signature: Signature,
+}
+
+impl Default for SparkSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkSpace {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::uniform(
+ 1,
+ vec![
+ DataType::Int32,
+ DataType::Dictionary(
+ Box::new(DataType::Int32),
+ Box::new(DataType::Int32),
+ ),
+ ],
+ Volatility::Immutable,
+ ),
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkSpace {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "space"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, args: &[DataType]) -> Result<DataType> {
+ let return_type = match &args[0] {
+ DataType::Dictionary(key_type, _) => {
+ DataType::Dictionary(key_type.clone(), Box::new(DataType::Utf8))
+ }
+ _ => DataType::Utf8,
+ };
+ Ok(return_type)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ if args.args.len() != 1 {
+ return plan_err!("space expects exactly 1 argument");
+ }
+ make_scalar_function(spark_space, vec![])(&args.args)
Review Comment:
I think that `space` is quite often invoked with a literal argument, e.g., `space(2)`. The current implementation converts the scalar value into an array for each batch and then calls `" ".repeat(m as usize)` for each row, resulting in the same string being allocated each time. This could be optimized in the scalar case to build the string once rather than per row and then append the same string to the builder repeatedly.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat: Implement Spark function `space` [datafusion]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #19610:
URL: https://github.com/apache/datafusion/pull/19610#discussion_r2657942992
##########
datafusion/spark/src/function/string/space.rs:
##########
@@ -0,0 +1,178 @@
+// 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.
+
+use arrow::array::{ArrayRef, DictionaryArray, StringArray};
+use arrow::datatypes::{DataType, Int32Type};
+use datafusion_common::cast::{as_dictionary_array, as_int32_array};
+use datafusion_common::{Result, exec_err, plan_err};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
+};
+use datafusion_functions::utils::make_scalar_function;
+use std::any::Any;
+use std::sync::Arc;
+
+/// Spark-compatible `space` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#space>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct SparkSpace {
+ signature: Signature,
+}
+
+impl Default for SparkSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SparkSpace {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::uniform(
+ 1,
+ vec![
+ DataType::Int32,
+ DataType::Dictionary(
+ Box::new(DataType::Int32),
+ Box::new(DataType::Int32),
+ ),
+ ],
+ Volatility::Immutable,
+ ),
+ }
+ }
+}
+
+impl ScalarUDFImpl for SparkSpace {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "space"
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, args: &[DataType]) -> Result<DataType> {
+ let return_type = match &args[0] {
+ DataType::Dictionary(key_type, _) => {
+ DataType::Dictionary(key_type.clone(), Box::new(DataType::Utf8))
+ }
+ _ => DataType::Utf8,
+ };
+ Ok(return_type)
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ if args.args.len() != 1 {
+ return plan_err!("space expects exactly 1 argument");
+ }
+ make_scalar_function(spark_space, vec![])(&args.args)
+ }
+}
+
+fn spark_space(args: &[ArrayRef]) -> Result<ArrayRef> {
+ let array = &args[0];
+ match array.data_type() {
+ DataType::Int32 => {
+ let result = space(array);
+ Ok(Arc::new(result))
+ }
+ DataType::Dictionary(_, v) if v.as_ref() == &DataType::Int32 => {
+ let dictionary_array = as_dictionary_array::<Int32Type>(array)?;
+ let values = Arc::new(space(dictionary_array.values()));
+ let result =
+ DictionaryArray::try_new(dictionary_array.keys().clone(), values)?;
+ Ok(Arc::new(result))
+ }
+ other => {
+ exec_err!("Unsupported data type {other:?} for function `space`")
+ }
+ }
+}
+
+fn space(array: &ArrayRef) -> StringArray {
+ as_int32_array(array)
+ .unwrap()
+ .iter()
+ .map(|n| {
+ n.map(|m| {
+ if m < 0 {
+ String::new()
+ } else {
+ " ".repeat(m as usize)
Review Comment:
This allocates a new string per row, which is discarded after being appended to the array. It would be more efficient for this function to build the string buffer and offsets directly.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org