You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "andygrove (via GitHub)" <gi...@apache.org> on 2025/12/18 15:35:52 UTC
[PR] feat: Add partial support for `from_json` [WIP] [datafusion-comet]
andygrove opened a new pull request, #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
N/A
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
`from_json` is a widely used Spark SQL function.
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
Add very basic support for `from_json` for a handful of primitive types.
## How are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
New tests.
--
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: Add partial support for `from_json` [datafusion-comet]
Posted by "mbutrovich (via GitHub)" <gi...@apache.org>.
mbutrovich commented on code in PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#discussion_r2632006238
##########
spark/src/main/scala/org/apache/comet/serde/structs.scala:
##########
@@ -167,3 +167,67 @@ object CometStructsToJson extends CometExpressionSerde[StructsToJson] {
}
}
}
+
+object CometJsonToStructs extends CometExpressionSerde[JsonToStructs] {
+
+ override def getSupportLevel(expr: JsonToStructs): SupportLevel = {
+ // this feature is partially implemented and not comprehensively tested yet
Review Comment:
Do you have criteria for when this would change? You allude to arrays, maps, and fuzz tests in the PR description.
##########
native/spark-expr/src/json_funcs/from_json.rs:
##########
@@ -0,0 +1,652 @@
+// 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, BooleanBuilder, Float32Builder, Float64Builder, Int32Builder, Int64Builder,
+ RecordBatch, StringBuilder, StructArray,
+};
+use arrow::datatypes::{DataType, Field, Schema};
+use datafusion::common::Result;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::ColumnarValue;
+use std::any::Any;
+use std::fmt::{Debug, Display, Formatter};
+use std::sync::Arc;
+
+/// from_json function - parses JSON strings into structured types
+#[derive(Debug, Eq)]
+pub struct FromJson {
+ /// The JSON string input expression
+ expr: Arc<dyn PhysicalExpr>,
+ /// Target schema for parsing
+ schema: DataType,
+ /// Timezone for timestamp parsing (future use)
+ timezone: String,
+}
+
+impl PartialEq for FromJson {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr) && self.schema == other.schema && self.timezone == other.timezone
+ }
+}
+
+impl std::hash::Hash for FromJson {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ // Note: DataType doesn't implement Hash, so we hash its debug representation
+ format!("{:?}", self.schema).hash(state);
+ self.timezone.hash(state);
+ }
+}
+
+impl FromJson {
+ pub fn new(expr: Arc<dyn PhysicalExpr>, schema: DataType, timezone: &str) -> Self {
+ Self {
+ expr,
+ schema,
+ timezone: timezone.to_owned(),
+ }
+ }
+}
+
+impl Display for FromJson {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "from_json({}, schema={:?}, timezone={})",
+ self.expr, self.schema, self.timezone
+ )
+ }
+}
+
+impl PartialEq<dyn Any> for FromJson {
+ fn eq(&self, other: &dyn Any) -> bool {
+ if let Some(other) = other.downcast_ref::<FromJson>() {
+ self.expr.eq(&other.expr)
+ && self.schema == other.schema
+ && self.timezone == other.timezone
+ } else {
+ false
+ }
+ }
+}
+
+impl PhysicalExpr for FromJson {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(self.schema.clone())
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ // Always nullable - parse errors return null in PERMISSIVE mode
+ Ok(true)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ Ok(ColumnarValue::Array(json_string_to_struct(
+ &input,
+ &self.schema,
+ )?))
+ }
+
+ 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>> {
+ assert!(children.len() == 1);
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ self.schema.clone(),
+ &self.timezone,
+ )))
+ }
+}
+
+/// Parse JSON string array into struct array
+fn json_string_to_struct(arr: &Arc<dyn Array>, schema: &DataType) -> Result<ArrayRef> {
+ use arrow::array::StringArray;
+ use arrow::buffer::NullBuffer;
+
+ // Input must be string array
+ let string_array = arr.as_any().downcast_ref::<StringArray>().ok_or_else(|| {
+ datafusion::common::DataFusionError::Execution("from_json expects string input".to_string())
+ })?;
+
+ // Schema must be struct
+ let DataType::Struct(fields) = schema else {
+ return Err(datafusion::common::DataFusionError::Execution(
+ "from_json requires struct schema".to_string(),
+ ));
+ };
+
+ // Build struct array by parsing each JSON string
+ let num_rows = string_array.len();
+
+ // Create builders for each field
Review Comment:
"What" not "why" comment is not needed IMO.
##########
native/spark-expr/src/json_funcs/from_json.rs:
##########
@@ -0,0 +1,652 @@
+// 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, BooleanBuilder, Float32Builder, Float64Builder, Int32Builder, Int64Builder,
+ RecordBatch, StringBuilder, StructArray,
+};
+use arrow::datatypes::{DataType, Field, Schema};
+use datafusion::common::Result;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::ColumnarValue;
+use std::any::Any;
+use std::fmt::{Debug, Display, Formatter};
+use std::sync::Arc;
+
+/// from_json function - parses JSON strings into structured types
+#[derive(Debug, Eq)]
+pub struct FromJson {
+ /// The JSON string input expression
+ expr: Arc<dyn PhysicalExpr>,
+ /// Target schema for parsing
+ schema: DataType,
+ /// Timezone for timestamp parsing (future use)
+ timezone: String,
+}
+
+impl PartialEq for FromJson {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr) && self.schema == other.schema && self.timezone == other.timezone
+ }
+}
+
+impl std::hash::Hash for FromJson {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ // Note: DataType doesn't implement Hash, so we hash its debug representation
+ format!("{:?}", self.schema).hash(state);
+ self.timezone.hash(state);
+ }
+}
+
+impl FromJson {
+ pub fn new(expr: Arc<dyn PhysicalExpr>, schema: DataType, timezone: &str) -> Self {
+ Self {
+ expr,
+ schema,
+ timezone: timezone.to_owned(),
+ }
+ }
+}
+
+impl Display for FromJson {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "from_json({}, schema={:?}, timezone={})",
+ self.expr, self.schema, self.timezone
+ )
+ }
+}
+
+impl PartialEq<dyn Any> for FromJson {
+ fn eq(&self, other: &dyn Any) -> bool {
+ if let Some(other) = other.downcast_ref::<FromJson>() {
+ self.expr.eq(&other.expr)
+ && self.schema == other.schema
+ && self.timezone == other.timezone
+ } else {
+ false
+ }
+ }
+}
+
+impl PhysicalExpr for FromJson {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(self.schema.clone())
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ // Always nullable - parse errors return null in PERMISSIVE mode
+ Ok(true)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ Ok(ColumnarValue::Array(json_string_to_struct(
+ &input,
+ &self.schema,
+ )?))
+ }
+
+ 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>> {
+ assert!(children.len() == 1);
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ self.schema.clone(),
+ &self.timezone,
+ )))
+ }
+}
+
+/// Parse JSON string array into struct array
+fn json_string_to_struct(arr: &Arc<dyn Array>, schema: &DataType) -> Result<ArrayRef> {
+ use arrow::array::StringArray;
+ use arrow::buffer::NullBuffer;
+
+ // Input must be string array
+ let string_array = arr.as_any().downcast_ref::<StringArray>().ok_or_else(|| {
+ datafusion::common::DataFusionError::Execution("from_json expects string input".to_string())
+ })?;
+
+ // Schema must be struct
+ let DataType::Struct(fields) = schema else {
+ return Err(datafusion::common::DataFusionError::Execution(
+ "from_json requires struct schema".to_string(),
+ ));
+ };
+
+ // Build struct array by parsing each JSON string
+ let num_rows = string_array.len();
+
+ // Create builders for each field
+ let mut field_builders = create_field_builders(fields, num_rows)?;
+
+ // Track which rows should be null at the struct level
+ let mut struct_nulls = vec![true; num_rows];
+
+ // Parse each row
+ for (row_idx, struct_null) in struct_nulls.iter_mut().enumerate() {
+ if string_array.is_null(row_idx) {
+ // Null input -> null struct
+ *struct_null = false;
+ append_null_to_all_builders(&mut field_builders);
+ } else {
+ let json_str = string_array.value(row_idx);
+
+ // Parse JSON (PERMISSIVE mode: return null fields on error)
+ match serde_json::from_str::<serde_json::Value>(json_str) {
+ Ok(json_value) => {
+ if let serde_json::Value::Object(obj) = json_value {
+ // Struct is not null, extract each field
+ *struct_null = true;
+ for (field, builder) in fields.iter().zip(field_builders.iter_mut()) {
+ let field_value = obj.get(field.name());
+ append_field_value(builder, field, field_value)?;
+ }
+ } else {
+ // Not an object -> struct with null fields
+ *struct_null = true;
+ append_null_to_all_builders(&mut field_builders);
+ }
+ }
+ Err(_) => {
+ // Parse error -> struct with null fields (PERMISSIVE mode)
+ *struct_null = true;
+ append_null_to_all_builders(&mut field_builders);
+ }
+ }
+ }
+ }
+
+ // Finish builders
+ let arrays: Vec<ArrayRef> = field_builders
+ .into_iter()
+ .map(finish_builder)
+ .collect::<Result<Vec<_>>>()?;
+
+ // Create null buffer from struct_nulls
Review Comment:
"what" not "why"
##########
native/core/src/execution/expressions/strings.rs:
##########
@@ -98,3 +99,28 @@ impl ExpressionBuilder for RlikeBuilder {
}
}
}
+
+/// Builder for FromJson expressions
Review Comment:
Not a terribly useful comment IMO. Code is already self-documenting.
##########
native/spark-expr/src/json_funcs/from_json.rs:
##########
@@ -0,0 +1,652 @@
+// 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, BooleanBuilder, Float32Builder, Float64Builder, Int32Builder, Int64Builder,
+ RecordBatch, StringBuilder, StructArray,
+};
+use arrow::datatypes::{DataType, Field, Schema};
+use datafusion::common::Result;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::ColumnarValue;
+use std::any::Any;
+use std::fmt::{Debug, Display, Formatter};
+use std::sync::Arc;
+
+/// from_json function - parses JSON strings into structured types
+#[derive(Debug, Eq)]
+pub struct FromJson {
+ /// The JSON string input expression
+ expr: Arc<dyn PhysicalExpr>,
+ /// Target schema for parsing
+ schema: DataType,
+ /// Timezone for timestamp parsing (future use)
+ timezone: String,
+}
+
+impl PartialEq for FromJson {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr) && self.schema == other.schema && self.timezone == other.timezone
+ }
+}
+
+impl std::hash::Hash for FromJson {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ // Note: DataType doesn't implement Hash, so we hash its debug representation
+ format!("{:?}", self.schema).hash(state);
+ self.timezone.hash(state);
+ }
+}
+
+impl FromJson {
+ pub fn new(expr: Arc<dyn PhysicalExpr>, schema: DataType, timezone: &str) -> Self {
+ Self {
+ expr,
+ schema,
+ timezone: timezone.to_owned(),
+ }
+ }
+}
+
+impl Display for FromJson {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "from_json({}, schema={:?}, timezone={})",
+ self.expr, self.schema, self.timezone
+ )
+ }
+}
+
+impl PartialEq<dyn Any> for FromJson {
+ fn eq(&self, other: &dyn Any) -> bool {
+ if let Some(other) = other.downcast_ref::<FromJson>() {
+ self.expr.eq(&other.expr)
+ && self.schema == other.schema
+ && self.timezone == other.timezone
+ } else {
+ false
+ }
+ }
+}
+
+impl PhysicalExpr for FromJson {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(self.schema.clone())
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ // Always nullable - parse errors return null in PERMISSIVE mode
+ Ok(true)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ Ok(ColumnarValue::Array(json_string_to_struct(
+ &input,
+ &self.schema,
+ )?))
+ }
+
+ 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>> {
+ assert!(children.len() == 1);
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ self.schema.clone(),
+ &self.timezone,
+ )))
+ }
+}
+
+/// Parse JSON string array into struct array
+fn json_string_to_struct(arr: &Arc<dyn Array>, schema: &DataType) -> Result<ArrayRef> {
+ use arrow::array::StringArray;
+ use arrow::buffer::NullBuffer;
+
+ // Input must be string array
+ let string_array = arr.as_any().downcast_ref::<StringArray>().ok_or_else(|| {
+ datafusion::common::DataFusionError::Execution("from_json expects string input".to_string())
+ })?;
+
+ // Schema must be struct
+ let DataType::Struct(fields) = schema else {
+ return Err(datafusion::common::DataFusionError::Execution(
+ "from_json requires struct schema".to_string(),
+ ));
+ };
+
+ // Build struct array by parsing each JSON string
+ let num_rows = string_array.len();
+
+ // Create builders for each field
+ let mut field_builders = create_field_builders(fields, num_rows)?;
+
+ // Track which rows should be null at the struct level
+ let mut struct_nulls = vec![true; num_rows];
+
+ // Parse each row
+ for (row_idx, struct_null) in struct_nulls.iter_mut().enumerate() {
+ if string_array.is_null(row_idx) {
+ // Null input -> null struct
+ *struct_null = false;
+ append_null_to_all_builders(&mut field_builders);
+ } else {
+ let json_str = string_array.value(row_idx);
+
+ // Parse JSON (PERMISSIVE mode: return null fields on error)
+ match serde_json::from_str::<serde_json::Value>(json_str) {
+ Ok(json_value) => {
+ if let serde_json::Value::Object(obj) = json_value {
+ // Struct is not null, extract each field
+ *struct_null = true;
+ for (field, builder) in fields.iter().zip(field_builders.iter_mut()) {
+ let field_value = obj.get(field.name());
+ append_field_value(builder, field, field_value)?;
+ }
+ } else {
+ // Not an object -> struct with null fields
+ *struct_null = true;
+ append_null_to_all_builders(&mut field_builders);
+ }
+ }
+ Err(_) => {
+ // Parse error -> struct with null fields (PERMISSIVE mode)
+ *struct_null = true;
+ append_null_to_all_builders(&mut field_builders);
+ }
+ }
+ }
+ }
+
+ // Finish builders
Review Comment:
"what" not "why"
##########
native/spark-expr/src/json_funcs/from_json.rs:
##########
@@ -0,0 +1,652 @@
+// 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, BooleanBuilder, Float32Builder, Float64Builder, Int32Builder, Int64Builder,
+ RecordBatch, StringBuilder, StructArray,
+};
+use arrow::datatypes::{DataType, Field, Schema};
+use datafusion::common::Result;
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::ColumnarValue;
+use std::any::Any;
+use std::fmt::{Debug, Display, Formatter};
+use std::sync::Arc;
+
+/// from_json function - parses JSON strings into structured types
+#[derive(Debug, Eq)]
+pub struct FromJson {
+ /// The JSON string input expression
+ expr: Arc<dyn PhysicalExpr>,
+ /// Target schema for parsing
+ schema: DataType,
+ /// Timezone for timestamp parsing (future use)
+ timezone: String,
+}
+
+impl PartialEq for FromJson {
+ fn eq(&self, other: &Self) -> bool {
+ self.expr.eq(&other.expr) && self.schema == other.schema && self.timezone == other.timezone
+ }
+}
+
+impl std::hash::Hash for FromJson {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.expr.hash(state);
+ // Note: DataType doesn't implement Hash, so we hash its debug representation
+ format!("{:?}", self.schema).hash(state);
+ self.timezone.hash(state);
+ }
+}
+
+impl FromJson {
+ pub fn new(expr: Arc<dyn PhysicalExpr>, schema: DataType, timezone: &str) -> Self {
+ Self {
+ expr,
+ schema,
+ timezone: timezone.to_owned(),
+ }
+ }
+}
+
+impl Display for FromJson {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "from_json({}, schema={:?}, timezone={})",
+ self.expr, self.schema, self.timezone
+ )
+ }
+}
+
+impl PartialEq<dyn Any> for FromJson {
+ fn eq(&self, other: &dyn Any) -> bool {
+ if let Some(other) = other.downcast_ref::<FromJson>() {
+ self.expr.eq(&other.expr)
+ && self.schema == other.schema
+ && self.timezone == other.timezone
+ } else {
+ false
+ }
+ }
+}
+
+impl PhysicalExpr for FromJson {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn fmt_sql(&self, _: &mut Formatter<'_>) -> std::fmt::Result {
+ unimplemented!()
+ }
+
+ fn data_type(&self, _: &Schema) -> Result<DataType> {
+ Ok(self.schema.clone())
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ // Always nullable - parse errors return null in PERMISSIVE mode
+ Ok(true)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let input = self.expr.evaluate(batch)?.into_array(batch.num_rows())?;
+ Ok(ColumnarValue::Array(json_string_to_struct(
+ &input,
+ &self.schema,
+ )?))
+ }
+
+ 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>> {
+ assert!(children.len() == 1);
+ Ok(Arc::new(Self::new(
+ Arc::clone(&children[0]),
+ self.schema.clone(),
+ &self.timezone,
+ )))
+ }
+}
+
+/// Parse JSON string array into struct array
+fn json_string_to_struct(arr: &Arc<dyn Array>, schema: &DataType) -> Result<ArrayRef> {
+ use arrow::array::StringArray;
+ use arrow::buffer::NullBuffer;
+
+ // Input must be string array
+ let string_array = arr.as_any().downcast_ref::<StringArray>().ok_or_else(|| {
+ datafusion::common::DataFusionError::Execution("from_json expects string input".to_string())
+ })?;
+
+ // Schema must be struct
+ let DataType::Struct(fields) = schema else {
+ return Err(datafusion::common::DataFusionError::Execution(
+ "from_json requires struct schema".to_string(),
+ ));
+ };
+
+ // Build struct array by parsing each JSON string
Review Comment:
Possible misplaced comment, or just generally refers to block of code below.
--
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: Add partial support for `from_json` [datafusion-comet]
Posted by "coderfender (via GitHub)" <gi...@apache.org>.
coderfender commented on PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#issuecomment-3671274874
I believe we have an unwanted cargo.lock file in the PR @andygrove
--
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: Add partial support for `from_json` [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#issuecomment-3672026376
> Thanks @andygrove great start, it doesn't support nested structs?
It does support nested structs. See `test("from_json - nested struct")`.
--
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: Add partial support for `from_json` [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#issuecomment-3671386973
> This is awesome ! I believe we have an unwanted cargo.lock file in the PR @andygrove
The `cargo.lock` file has been updated due to the new dependency on `serde_json`.
--
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: Add partial support for `from_json` [WIP] [datafusion-comet]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#issuecomment-3671153781
## [Codecov](https://app.codecov.io/gh/apache/datafusion-comet/pull/2934?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 `0%` with `34 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 10.06%. 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 ([`195b981`](https://app.codecov.io/gh/apache/datafusion-comet/commit/195b981f2fd0aaed54ac1b3ec962941c3ac2b61b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 775 commits behind head on main.
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion-comet/pull/2934?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/2934?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) | 0.00% | [33 Missing :warning: ](https://app.codecov.io/gh/apache/datafusion-comet/pull/2934?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [.../scala/org/apache/comet/serde/QueryPlanSerde.scala](https://app.codecov.io/gh/apache/datafusion-comet/pull/2934?src=pr&el=tree&filepath=spark%2Fsrc%2Fmain%2Fscala%2Forg%2Fapache%2Fcomet%2Fserde%2FQueryPlanSerde.scala&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3Bhcmsvc3JjL21haW4vc2NhbGEvb3JnL2FwYWNoZS9jb21ldC9zZXJkZS9RdWVyeVBsYW5TZXJkZS5zY2FsYQ==) | 0.00% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/datafusion-comet/pull/2934?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 #2934 +/- ##
=============================================
- Coverage 56.12% 10.06% -46.07%
+ Complexity 976 234 -742
=============================================
Files 119 167 +48
Lines 11743 15373 +3630
Branches 2251 2531 +280
=============================================
- Hits 6591 1547 -5044
- Misses 4012 13649 +9637
+ Partials 1140 177 -963
```
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/datafusion-comet/pull/2934?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: Add partial support for `from_json` [datafusion-comet]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#issuecomment-3671946468
Thanks @andygrove great start, it doesn't support nested structs?
--
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: Add partial support for `from_json` [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#issuecomment-3677907211
Thanks for the reviews @mbutrovich and @comphead. I went ahead and merged despite the Spark 4 / hive-1 test failure which is happening on many PRs now. I filed https://github.com/apache/datafusion-comet/issues/2946 to get this resolved. The test is not related to `from_json` support.
--
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: Add partial support for `from_json` [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove commented on code in PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934#discussion_r2632019480
##########
spark/src/main/scala/org/apache/comet/serde/structs.scala:
##########
@@ -167,3 +167,67 @@ object CometStructsToJson extends CometExpressionSerde[StructsToJson] {
}
}
}
+
+object CometJsonToStructs extends CometExpressionSerde[JsonToStructs] {
+
+ override def getSupportLevel(expr: JsonToStructs): SupportLevel = {
+ // this feature is partially implemented and not comprehensively tested yet
Review Comment:
This is mostly about testing. I mostly only have tests for the happy path so far i.e. correctly formatted JSON. Spark is very forgiving when parsing JSON.
--
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: Add partial support for `from_json` [datafusion-comet]
Posted by "andygrove (via GitHub)" <gi...@apache.org>.
andygrove merged PR #2934:
URL: https://github.com/apache/datafusion-comet/pull/2934
--
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