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 2025/12/28 13:38:42 UTC
[PR] Feat: to_csv [datafusion-comet]
kazantsev-maksim opened a new pull request, #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004
## Which issue does this PR close?
## Rationale for this change
## What changes are included in this PR?
## How are these changes tested?
--
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: to_csv [datafusion-comet]
Posted by "parthchandra (via GitHub)" <gi...@apache.org>.
parthchandra commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2691756142
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
Review Comment:
If not ignoring leading/trailing whitespace then the string should be quoted if there is a leading/trailing whitespace.
Also if there are newlines.
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2700867020
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
Review Comment:
For case of newlines you are absolutley right - fixed 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.
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: to_csv [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#issuecomment-3863096670
@kazantsev-maksim oops, I was going through the PR queue and saw that this one had two approvals, and I went ahead and merged before noticing that you had continued working on this. It looks like the expression is already marked as incompatible, so this shouldn't be an issue.
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2700860122
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
Review Comment:
Spark don't quoting string with leading or trailing whitespaces if quoteAll option is disabled. This edge case is covered by unit tests
`sql(s"insert` into $table values(' abc ')")`
```sql
checkSparkAnswerAndOperator(
df.select(
to_csv(
struct(col("col"), lit(1)),
Map(
"delimiter" -> ";",
"ignoreLeadingWhiteSpace" -> "false",
"ignoreTrailingWhiteSpace" -> "false").asJava)))
```
--
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: to_csv [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2712739043
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,223 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote_char = write_options.quote.chars().next().unwrap_or('"');
+ let escape_char = write_options.escape.chars().next().unwrap_or('\\');
Review Comment:
Does Spark limit these to chars, or can they be multi-character strings?
--
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: to_csv [datafusion-comet]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#issuecomment-3746608928
## [Codecov](https://app.codecov.io/gh/apache/datafusion-comet/pull/3004?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `9.75610%` with `37 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 21.08%. Comparing base ([`f09f8af`](https://app.codecov.io/gh/apache/datafusion-comet/commit/f09f8af64c6599255e116a376f4f008f2fd63b43?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`cf544c7`](https://app.codecov.io/gh/apache/datafusion-comet/commit/cf544c7d85ddd1723bcf73450d94bfa29e7af6d5?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 845 commits behind head on main.
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion-comet/pull/3004?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...rc/main/scala/org/apache/comet/serde/structs.scala](https://app.codecov.io/gh/apache/datafusion-comet/pull/3004?src=pr&el=tree&filepath=spark%2Fsrc%2Fmain%2Fscala%2Forg%2Fapache%2Fcomet%2Fserde%2Fstructs.scala&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3Bhcmsvc3JjL21haW4vc2NhbGEvb3JnL2FwYWNoZS9jb21ldC9zZXJkZS9zdHJ1Y3RzLnNjYWxh) | 5.12% | [37 Missing :warning: ](https://app.codecov.io/gh/apache/datafusion-comet/pull/3004?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #3004 +/- ##
=============================================
- Coverage 56.12% 21.08% -35.04%
+ Complexity 976 471 -505
=============================================
Files 119 167 +48
Lines 11743 15562 +3819
Branches 2251 2577 +326
=============================================
- Hits 6591 3282 -3309
- Misses 4012 11746 +7734
+ Partials 1140 534 -606
```
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/datafusion-comet/pull/3004?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
</details>
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2700860122
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
Review Comment:
Spark don't quoting string with leading or trailing whitespaces if quoteAll option is disabled. This edge case is covered by unit tests
`sql(s"insert` into $table values(' abc ')")
checkSparkAnswerAndOperator(
df.select(
to_csv(
struct(col("col"), lit(1)),
Map(
"delimiter" -> ";",
"ignoreLeadingWhiteSpace" -> "false",
"ignoreTrailingWhiteSpace" -> "false").asJava)))`
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#issuecomment-3763012831
@parthchandra could you take another look when you have time?
--
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: to_csv [datafusion-comet]
Posted by "parthchandra (via GitHub)" <gi...@apache.org>.
parthchandra commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2688138893
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
+ || value.contains(quote)
+ || value.is_empty()));
+
+ let needs_escaping = is_string_field && needs_quoting;
+ if needs_quoting {
+ csv_string.push_str(quote);
+ }
+ if needs_escaping {
+ escape_value(value, quote, &write_options.escape, &mut csv_string);
+ } else {
+ csv_string.push_str(value);
+ }
+ if needs_quoting {
+ csv_string.push_str(quote);
+ }
+ }
+ builder.append_value(&csv_string);
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+}
+
+#[inline]
+fn escape_value(value: &str, quote: &str, escape: &str, output: &mut String) {
+ for ch in value.chars() {
+ let ch_str = ch.to_string();
+ if ch_str == quote || ch_str == escape {
Review Comment:
The CSV spec does not have any special escape for escape and the preferred way to escape the double quote is another double quote (but only if the string is enclosed in a double quote!). - https://datatracker.ietf.org/doc/html/rfc4180#section-2
Not sure what Spark does here.
--
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: to_csv [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove merged PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2700891153
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
+ || value.contains(quote)
+ || value.is_empty()));
+
+ let needs_escaping = is_string_field && needs_quoting;
+ if needs_quoting {
+ csv_string.push_str(quote);
+ }
+ if needs_escaping {
+ escape_value(value, quote, &write_options.escape, &mut csv_string);
+ } else {
+ csv_string.push_str(value);
+ }
+ if needs_quoting {
+ csv_string.push_str(quote);
+ }
+ }
+ builder.append_value(&csv_string);
+ }
+ }
+ Ok(Arc::new(builder.finish()))
+}
+
+#[inline]
+fn escape_value(value: &str, quote: &str, escape: &str, output: &mut String) {
+ for ch in value.chars() {
+ let ch_str = ch.to_string();
+ if ch_str == quote || ch_str == escape {
Review Comment:
This necessary for case:
```sql
sql(s"""insert into $table values('a\\\\b')""")
```
```sql
checkSparkAnswerAndOperator(
df.select(to_csv(struct(col("col"), lit(1)), Map("quoteAll" -> "true").asJava)))
```
This may seem insignificant, but I want to cover the maximum number of edge cases.
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#issuecomment-3863653319
Thanks @andygrove. I think I'll be able to continue working on the function as part of the issue: https://github.com/apache/datafusion-comet/issues/3232
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#issuecomment-3779167421
Thanks @andygrove . I will continue working on this function to achieve full compatibility with Spark.
--
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: to_csv [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2712715515
##########
native/spark-expr/src/csv_funcs/csv_write_options.rs:
##########
@@ -0,0 +1,61 @@
+// 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 std::fmt::{Display, Formatter};
+
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+pub struct CsvWriteOptions {
+ pub delimiter: String,
+ pub quote: String,
+ pub escape: String,
+ pub null_value: String,
+ pub quote_all: bool,
+ pub ignore_leading_white_space: bool,
+ pub ignore_trailing_white_space: bool,
+}
+
+impl Display for CsvWriteOptions {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
Review Comment:
nit: should `delimiter` also be shown here?
--
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: to_csv [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2712728394
##########
spark/src/main/scala/org/apache/comet/serde/structs.scala:
##########
@@ -230,3 +232,68 @@ object CometJsonToStructs extends CometExpressionSerde[JsonToStructs] {
}
}
}
+
+object CometStructsToCsv extends CometExpressionSerde[StructsToCsv] {
+
+ private val incompatibleDataTypes = Seq(DateType, TimestampType, TimestampNTZType, BinaryType)
+
+ override def getSupportLevel(expr: StructsToCsv): SupportLevel = {
+ val dataTypes = expr.inputSchema.fields.map(_.dataType)
+ val containsComplexType = dataTypes.exists(DataTypeSupport.isComplexType)
+ if (containsComplexType) {
+ return Unsupported(
+ Some(
+ s"The schema ${expr.inputSchema} is not supported because it includes a complex type"))
+ }
+ val containsIncompatibleDataTypes = dataTypes.exists(incompatibleDataTypes.contains)
+ if (containsIncompatibleDataTypes) {
+ return Incompatible(
+ Some(
+ s"The schema ${expr.inputSchema} is not supported because " +
+ s"it includes a incompatible data types: $incompatibleDataTypes"))
+ }
+ Compatible()
Review Comment:
Can we guarantee full compatibility with the `UnivocityGenerator` that Spark uses? Perhaps this should be marked as incompatible for now until we have sufficient fuzz testing to confirm compatibility?
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#issuecomment-3754950130
Tanks @parthchandra for the review. I'll try to resolve conversions them 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.
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2700860122
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
Review Comment:
Spark don't quoting string with leading or trailing whitespaces if quoteAll option is disabled. This edge case is covered by unit tests
```sql
sql(s"insert` into $table values(' abc ')")
```
```sql
checkSparkAnswerAndOperator(
df.select(
to_csv(
struct(col("col"), lit(1)),
Map(
"delimiter" -> ";",
"ignoreLeadingWhiteSpace" -> "false",
"ignoreTrailingWhiteSpace" -> "false").asJava)))
```
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2700860122
##########
native/spark-expr/src/csv_funcs/to_csv.rs:
##########
@@ -0,0 +1,208 @@
+// 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 crate::csv_funcs::csv_write_options::CsvWriteOptions;
+use crate::{spark_cast, EvalMode, SparkCastOptions};
+use arrow::array::{as_string_array, as_struct_array, Array, ArrayRef, StringArray, StringBuilder};
+use arrow::array::{RecordBatch, StructArray};
+use arrow::datatypes::{DataType, Schema};
+use datafusion::common::Result;
+use datafusion::logical_expr::ColumnarValue;
+use datafusion::physical_expr::PhysicalExpr;
+use std::any::Any;
+use std::fmt::{Display, Formatter};
+use std::hash::Hash;
+use std::sync::Arc;
+
+/// to_csv spark function
+#[derive(Debug, Eq)]
+pub struct ToCsv {
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: String,
+ csv_write_options: CsvWriteOptions,
+}
+
+impl Hash for ToCsv {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ self.timezone.hash(state);
+ self.csv_write_options.hash(state);
+ }
+}
+
+impl PartialEq for ToCsv {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr)
+ && self.timezone.eq(&other.timezone)
+ && self.csv_write_options.eq(&other.csv_write_options)
+ }
+}
+
+impl ToCsv {
+ pub fn new(
+ expr: Arc<dyn PhysicalExpr>,
+ timezone: &str,
+ csv_write_options: CsvWriteOptions,
+ ) -> Self {
+ Self {
+ expr,
+ timezone: timezone.to_owned(),
+ csv_write_options,
+ }
+ }
+}
+
+impl Display for ToCsv {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "to_csv({}, timezone={}, csv_write_options={})",
+ self.expr, self.timezone, self.csv_write_options
+ )
+ }
+}
+
+impl PhysicalExpr for ToCsv {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(DataType::Utf8)
+ }
+
+ fn nullable(&self, input_schema: &Schema) -> Result<bool> {
+ self.expr.nullable(input_schema)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input_array = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ let mut cast_options = SparkCastOptions::new(EvalMode::Legacy, &self.timezone, false);
+ cast_options.null_string = self.csv_write_options.null_value.clone();
+ let struct_array = as_struct_array(&input_array);
+
+ let csv_array = to_csv_inner(struct_array, &cast_options, &self.csv_write_options)?;
+
+ Ok(ColumnarValue::Array(csv_array))
+ }
+
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ vec![&self.expr]
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ &self.timezone,
+ self.csv_write_options.clone(),
+ )))
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+}
+
+pub fn to_csv_inner(
+ array: &StructArray,
+ cast_options: &SparkCastOptions,
+ write_options: &CsvWriteOptions,
+) -> Result<ArrayRef> {
+ let string_arrays: Vec<ArrayRef> = as_struct_array(&array)
+ .columns()
+ .iter()
+ .map(|array| {
+ spark_cast(
+ ColumnarValue::Array(Arc::clone(array)),
+ &DataType::Utf8,
+ cast_options,
+ )?
+ .into_array(array.len())
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let string_arrays: Vec<&StringArray> = string_arrays
+ .iter()
+ .map(|array| as_string_array(array))
+ .collect();
+ let is_string: Vec<bool> = array
+ .fields()
+ .iter()
+ .map(|f| matches!(f.data_type(), DataType::Utf8 | DataType::LargeUtf8))
+ .collect();
+
+ let mut builder = StringBuilder::with_capacity(array.len(), array.len() * 16);
+ let mut csv_string = String::with_capacity(array.len() * 16);
+
+ let quote = write_options.quote.as_ref();
+ for row_idx in 0..array.len() {
+ if array.is_null(row_idx) {
+ builder.append_null();
+ } else {
+ csv_string.clear();
+ for (col_idx, column) in string_arrays.iter().enumerate() {
+ if col_idx > 0 {
+ csv_string.push_str(&write_options.delimiter);
+ }
+ let mut value = column.value(row_idx);
+ let is_string_field = is_string[col_idx];
+ if is_string_field {
+ if write_options.ignore_leading_white_space {
+ value = value.trim_start();
+ }
+ if write_options.ignore_trailing_white_space {
+ value = value.trim_end();
+ }
+ }
+ let needs_quoting = write_options.quote_all
+ || (is_string_field
+ && !string_arrays[col_idx].is_null(row_idx)
+ && (value.contains(&write_options.delimiter)
Review Comment:
Spark don't quoting string with leading or trailing whitespaces if quoteAll option is disabled. This edge case is covered by unit tests
`sql(s"insert` into $table values(' abc ')")
checkSparkAnswerAndOperator(
df.select(
to_csv(
struct(col("col"), lit(1)),
Map(
"delimiter" -> ";",
"ignoreLeadingWhiteSpace" -> "false",
"ignoreTrailingWhiteSpace" -> "false").asJava)))
`
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2713418900
##########
native/spark-expr/src/csv_funcs/csv_write_options.rs:
##########
@@ -0,0 +1,61 @@
+// 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 std::fmt::{Display, Formatter};
+
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+pub struct CsvWriteOptions {
+ pub delimiter: String,
+ pub quote: String,
+ pub escape: String,
+ pub null_value: String,
+ pub quote_all: bool,
+ pub ignore_leading_white_space: bool,
+ pub ignore_trailing_white_space: bool,
+}
+
+impl Display for CsvWriteOptions {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
Review Comment:
Thanks, fixed.
##########
spark/src/main/scala/org/apache/comet/serde/structs.scala:
##########
@@ -230,3 +232,68 @@ object CometJsonToStructs extends CometExpressionSerde[JsonToStructs] {
}
}
}
+
+object CometStructsToCsv extends CometExpressionSerde[StructsToCsv] {
+
+ private val incompatibleDataTypes = Seq(DateType, TimestampType, TimestampNTZType, BinaryType)
+
+ override def getSupportLevel(expr: StructsToCsv): SupportLevel = {
+ val dataTypes = expr.inputSchema.fields.map(_.dataType)
+ val containsComplexType = dataTypes.exists(DataTypeSupport.isComplexType)
+ if (containsComplexType) {
+ return Unsupported(
+ Some(
+ s"The schema ${expr.inputSchema} is not supported because it includes a complex type"))
+ }
+ val containsIncompatibleDataTypes = dataTypes.exists(incompatibleDataTypes.contains)
+ if (containsIncompatibleDataTypes) {
+ return Incompatible(
+ Some(
+ s"The schema ${expr.inputSchema} is not supported because " +
+ s"it includes a incompatible data types: $incompatibleDataTypes"))
+ }
+ Compatible()
Review Comment:
Thanks, fixed.
--
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: to_csv [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#issuecomment-3778330760
@kazantsev-maksim This looks great, thank you! My only concern is that we are claiming full compatibility with Spark and I'm not sure that the tests are comprehensive enough to prove that. I am going to do some testing with this PR and see if I can suggest more tests to add.
--
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: to_csv [datafusion-comet]
Posted by "kazantsev-maksim (via GitHub)" <gi...@apache.org>.
kazantsev-maksim commented on code in PR #3004:
URL: https://github.com/apache/datafusion-comet/pull/3004#discussion_r2676428474
##########
native/proto/src/proto/expr.proto:
##########
@@ -275,6 +276,22 @@ message FromJson {
string timezone = 3;
}
+message ToCsv {
+ Expr child = 1;
+ CsvWriteOptions options = 2;
+}
+
+message CsvWriteOptions {
Review Comment:
All settings: https://spark.apache.org/docs/latest/sql-data-sources-csv.html
--
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