richox commented on code in PR #2112: URL: https://github.com/apache/auron/pull/2112#discussion_r2975036400
########## native-engine/datafusion-ext-plans/src/flink/serde/json_deserializer.rs: ########## @@ -0,0 +1,1043 @@ +// 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::{collections::HashMap, sync::Arc}; + +use arrow::array::{ + Array, ArrayRef, BinaryArray, BinaryBuilder, BooleanBuilder, Float32Builder, Float64Builder, + Int32Array, Int32Builder, Int64Array, Int64Builder, RecordBatch, RecordBatchOptions, + StringBuilder, StructArray, TimestampMillisecondBuilder, UInt32Builder, UInt64Builder, + new_null_array, +}; +use arrow_schema::{DataType, Field, Fields, Schema, SchemaRef, TimeUnit}; +use datafusion::error::DataFusionError; +use datafusion_ext_commons::{df_execution_err, downcast_any}; +use sonic_rs::{JsonContainerTrait, JsonValueTrait, Value}; + +use crate::flink::serde::{ + flink_deserializer::FlinkDeserializer, pb_deserializer::ensure_output_array_builders_size, + shared_array_builder::SharedArrayBuilder, shared_list_array_builder::SharedListArrayBuilder, + shared_map_array_builder::SharedMapArrayBuilder, + shared_struct_array_builder::SharedStructArrayBuilder, +}; + +type ValueHandler = Box<dyn Fn(&Value) -> datafusion::error::Result<()> + Send>; + +pub struct JsonDeserializer { + output_schema: SchemaRef, + output_schema_without_meta: SchemaRef, + json_schema: SchemaRef, + output_array_builders: Vec<SharedArrayBuilder>, + ensure_size: Box<dyn FnMut(usize) + Send>, + value_handlers: Vec<(String, ValueHandler)>, + msg_mapping: Vec<Vec<usize>>, +} + +impl FlinkDeserializer for JsonDeserializer { + fn parse_messages_with_kafka_meta( + &mut self, + messages: &BinaryArray, + kafka_partition: &Int32Array, + kafka_offset: &Int64Array, + kafka_timestamp: &Int64Array, + ) -> datafusion::common::Result<RecordBatch> { + for (row_idx, msg_bytes) in messages.iter().enumerate() { + let msg = msg_bytes.expect("message bytes must not be null"); + let json_value: Value = sonic_rs::from_slice(msg).map_err(|e| { + DataFusionError::Execution(format!("Failed to parse JSON message: {e}")) + })?; + + if let Some(obj) = json_value.as_object() { + for (field_name, handler) in &self.value_handlers { + if let Some(value) = obj.get(field_name) { + handler(value)?; + } + } + } + + let ensure_size = &mut self.ensure_size; + ensure_size(row_idx + 1); + } + + let root_struct = StructArray::from({ + RecordBatch::try_new_with_options( + self.json_schema.clone(), + self.output_array_builders + .iter() + .map(|builder| builder.get_dyn_mut().finish()) + .collect(), + &RecordBatchOptions::new().with_row_count(Some(messages.len())), + )? + }); + + let mut output_arrays: Vec<ArrayRef> = Vec::new(); + output_arrays.push(Arc::new(kafka_partition.clone())); + output_arrays.push(Arc::new(kafka_offset.clone())); + output_arrays.push(Arc::new(kafka_timestamp.clone())); + + for (field_idx, field) in self.output_schema_without_meta.fields().iter().enumerate() { + let array_ref: ArrayRef = get_output_array(&root_struct, &self.msg_mapping[field_idx])?; + if array_ref.null_count() == array_ref.len() { + output_arrays.push(new_null_array(field.data_type(), array_ref.len())); + } else { + output_arrays.push( + datafusion_ext_commons::arrow::cast::cast(&array_ref, field.data_type()) Review Comment: use `?` instead of `.except(..)` ########## native-engine/datafusion-ext-plans/src/flink/serde/json_deserializer.rs: ########## @@ -0,0 +1,1043 @@ +// 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::{collections::HashMap, sync::Arc}; + +use arrow::array::{ + Array, ArrayRef, BinaryArray, BinaryBuilder, BooleanBuilder, Float32Builder, Float64Builder, + Int32Array, Int32Builder, Int64Array, Int64Builder, RecordBatch, RecordBatchOptions, + StringBuilder, StructArray, TimestampMillisecondBuilder, UInt32Builder, UInt64Builder, + new_null_array, +}; +use arrow_schema::{DataType, Field, Fields, Schema, SchemaRef, TimeUnit}; +use datafusion::error::DataFusionError; +use datafusion_ext_commons::{df_execution_err, downcast_any}; +use sonic_rs::{JsonContainerTrait, JsonValueTrait, Value}; + +use crate::flink::serde::{ + flink_deserializer::FlinkDeserializer, pb_deserializer::ensure_output_array_builders_size, + shared_array_builder::SharedArrayBuilder, shared_list_array_builder::SharedListArrayBuilder, + shared_map_array_builder::SharedMapArrayBuilder, + shared_struct_array_builder::SharedStructArrayBuilder, +}; + +type ValueHandler = Box<dyn Fn(&Value) -> datafusion::error::Result<()> + Send>; + +pub struct JsonDeserializer { + output_schema: SchemaRef, + output_schema_without_meta: SchemaRef, + json_schema: SchemaRef, + output_array_builders: Vec<SharedArrayBuilder>, + ensure_size: Box<dyn FnMut(usize) + Send>, + value_handlers: Vec<(String, ValueHandler)>, + msg_mapping: Vec<Vec<usize>>, +} + +impl FlinkDeserializer for JsonDeserializer { + fn parse_messages_with_kafka_meta( + &mut self, + messages: &BinaryArray, + kafka_partition: &Int32Array, + kafka_offset: &Int64Array, + kafka_timestamp: &Int64Array, + ) -> datafusion::common::Result<RecordBatch> { + for (row_idx, msg_bytes) in messages.iter().enumerate() { + let msg = msg_bytes.expect("message bytes must not be null"); + let json_value: Value = sonic_rs::from_slice(msg).map_err(|e| { + DataFusionError::Execution(format!("Failed to parse JSON message: {e}")) + })?; + + if let Some(obj) = json_value.as_object() { + for (field_name, handler) in &self.value_handlers { + if let Some(value) = obj.get(field_name) { + handler(value)?; + } + } + } + + let ensure_size = &mut self.ensure_size; + ensure_size(row_idx + 1); + } + + let root_struct = StructArray::from({ + RecordBatch::try_new_with_options( + self.json_schema.clone(), + self.output_array_builders + .iter() + .map(|builder| builder.get_dyn_mut().finish()) + .collect(), + &RecordBatchOptions::new().with_row_count(Some(messages.len())), + )? + }); + + let mut output_arrays: Vec<ArrayRef> = Vec::new(); + output_arrays.push(Arc::new(kafka_partition.clone())); + output_arrays.push(Arc::new(kafka_offset.clone())); + output_arrays.push(Arc::new(kafka_timestamp.clone())); + + for (field_idx, field) in self.output_schema_without_meta.fields().iter().enumerate() { + let array_ref: ArrayRef = get_output_array(&root_struct, &self.msg_mapping[field_idx])?; + if array_ref.null_count() == array_ref.len() { + output_arrays.push(new_null_array(field.data_type(), array_ref.len())); + } else { + output_arrays.push( + datafusion_ext_commons::arrow::cast::cast(&array_ref, field.data_type()) + .expect("Failed to cast array"), + ); + } + } + + let batch = RecordBatch::try_new_with_options( + self.output_schema.clone(), + output_arrays, + &RecordBatchOptions::new().with_row_count(Some(messages.len())), + )?; + Ok(batch) + } +} + +impl JsonDeserializer { + pub fn new( + output_schema: SchemaRef, + nested_msg_mapping: &HashMap<String, String>, + ) -> datafusion::error::Result<Self> { Review Comment: can be simplified with `use datafusion::error::Result` -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
