QuakeWang commented on code in PR #225:
URL: https://github.com/apache/paimon-rust/pull/225#discussion_r3045316984


##########
crates/paimon/src/arrow/format/avro.rs:
##########
@@ -0,0 +1,543 @@
+// 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 super::{FilePredicates, FormatFileReader};
+use crate::arrow::build_target_arrow_schema;
+use crate::io::FileRead;
+use crate::spec::{DataField, DataType};
+use crate::table::{ArrowRecordBatchStream, RowRange};
+use crate::Error;
+use arrow_array::{
+    BinaryArray, BooleanArray, Date32Array, Decimal128Array, Float32Array, 
Float64Array,
+    Int16Array, Int32Array, Int64Array, Int8Array, RecordBatch, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+};
+use arrow_schema::SchemaRef;
+use async_stream::try_stream;
+use async_trait::async_trait;
+use futures::StreamExt;
+use serde_json::Value;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+pub(crate) struct AvroFormatReader;
+
+const DEFAULT_BATCH_SIZE: usize = 8192;
+
+#[async_trait]
+impl FormatFileReader for AvroFormatReader {
+    async fn read_batch_stream(
+        &self,
+        reader: Box<dyn FileRead>,
+        file_size: u64,
+        read_fields: &[DataField],
+        _predicates: Option<&FilePredicates>,
+        batch_size: Option<usize>,
+        row_selection: Option<Vec<RowRange>>,
+    ) -> crate::Result<ArrowRecordBatchStream> {
+        // NOTE: Avro OCF requires sequential reading, so we load the entire 
file into memory.
+        // This is fine for typical Paimon data files but may be problematic 
for very large files.
+        let file_bytes = reader.read(0..file_size).await?;
+
+        let read_fields = read_fields.to_vec();
+        let target_schema = build_target_arrow_schema(&read_fields)?;
+        let batch_size = batch_size.unwrap_or(DEFAULT_BATCH_SIZE);
+
+        // Deserialize all Avro records from the OCF file.
+        let mut reader =
+            
serde_avro_fast::object_container_file_encoding::Reader::from_slice(&file_bytes)
+                .map_err(|e| Error::UnexpectedError {
+                    message: format!("Failed to open Avro file: {e}"),
+                    source: Some(Box::new(e)),
+                })?;
+
+        let mut all_records: Vec<HashMap<String, Value>> = Vec::new();
+        for result in reader.deserialize_borrowed::<HashMap<String, Value>>() {
+            let record = result.map_err(|e| Error::UnexpectedError {
+                message: format!("Failed to deserialize Avro record: {e}"),
+                source: Some(Box::new(e)),
+            })?;
+            all_records.push(record);
+        }
+
+        // Apply row selection filtering.
+        let records: Vec<HashMap<String, Value>> = match row_selection {
+            Some(ref ranges) => {
+                let total_rows = all_records.len();
+                let mask = ranges_to_mask(total_rows, ranges);
+                all_records
+                    .into_iter()
+                    .enumerate()
+                    .filter(|(i, _)| mask[*i])
+                    .map(|(_, r)| r)
+                    .collect()
+            }
+            None => all_records,
+        };
+
+        Ok(try_stream! {
+            for chunk in records.chunks(batch_size) {
+                let batch = records_to_batch(chunk, &read_fields, 
&target_schema)?;
+                yield batch;
+            }
+        }
+        .boxed())
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Row ranges → boolean mask
+// ---------------------------------------------------------------------------
+
+fn ranges_to_mask(total_rows: usize, ranges: &[RowRange]) -> Vec<bool> {
+    let mut mask = vec![false; total_rows];
+    let file_end = total_rows as i64 - 1;
+    for r in ranges {
+        let from = r.from().max(0) as usize;
+        let to = (r.to().min(file_end) as usize).min(total_rows - 1);
+        for item in mask.iter_mut().take(to + 1).skip(from) {
+            *item = true;
+        }
+    }
+    mask
+}
+
+// ---------------------------------------------------------------------------
+// Avro records → Arrow RecordBatch conversion
+// ---------------------------------------------------------------------------
+
+fn records_to_batch(
+    records: &[HashMap<String, Value>],
+    fields: &[DataField],
+    schema: &SchemaRef,
+) -> crate::Result<RecordBatch> {
+    let num_rows = records.len();
+    let mut columns: Vec<Arc<dyn arrow_array::Array>> = 
Vec::with_capacity(fields.len());
+
+    for field in fields {
+        let col = build_column(records, field.name(), field.data_type(), 
num_rows)?;
+        columns.push(col);
+    }
+
+    if columns.is_empty() {
+        RecordBatch::try_new_with_options(
+            schema.clone(),
+            columns,
+            
&arrow_array::RecordBatchOptions::new().with_row_count(Some(num_rows)),
+        )
+    } else {
+        RecordBatch::try_new(schema.clone(), columns)
+    }
+    .map_err(|e| Error::UnexpectedError {
+        message: format!("Failed to build Avro RecordBatch: {e}"),
+        source: Some(Box::new(e)),
+    })
+}
+
+fn build_column(
+    records: &[HashMap<String, Value>],
+    name: &str,
+    data_type: &DataType,
+    num_rows: usize,
+) -> crate::Result<Arc<dyn arrow_array::Array>> {
+    Ok(match data_type {
+        DataType::Boolean(_) => {
+            let arr: BooleanArray = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| 
v.as_bool()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::TinyInt(_) => {
+            let arr: Int8Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_i64())
+                        .map(|v| v as i8)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::SmallInt(_) => {
+            let arr: Int16Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_i64())
+                        .map(|v| v as i16)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Int(_) => {
+            let arr: Int32Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_i64())
+                        .map(|v| v as i32)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::BigInt(_) => {
+            let arr: Int64Array = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| v.as_i64()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Float(_) => {
+            let arr: Float32Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_f64())
+                        .map(|v| v as f32)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Double(_) => {
+            let arr: Float64Array = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| v.as_f64()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Char(_) | DataType::VarChar(_) => {
+            let arr: StringArray = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| v.as_str()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Binary(_) | DataType::VarBinary(_) => {

Review Comment:
   Binary values do not look correct on this path either. `bytes` and `fixed` 
should stay as raw bytes, but this branch assumes they come in as 
`Value::String`. That can either fail during deserialization or lose the 
original bytes semantics.



##########
crates/paimon/src/arrow/format/avro.rs:
##########
@@ -0,0 +1,543 @@
+// 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 super::{FilePredicates, FormatFileReader};
+use crate::arrow::build_target_arrow_schema;
+use crate::io::FileRead;
+use crate::spec::{DataField, DataType};
+use crate::table::{ArrowRecordBatchStream, RowRange};
+use crate::Error;
+use arrow_array::{
+    BinaryArray, BooleanArray, Date32Array, Decimal128Array, Float32Array, 
Float64Array,
+    Int16Array, Int32Array, Int64Array, Int8Array, RecordBatch, StringArray,
+    TimestampMicrosecondArray, TimestampMillisecondArray, 
TimestampNanosecondArray,
+};
+use arrow_schema::SchemaRef;
+use async_stream::try_stream;
+use async_trait::async_trait;
+use futures::StreamExt;
+use serde_json::Value;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+pub(crate) struct AvroFormatReader;
+
+const DEFAULT_BATCH_SIZE: usize = 8192;
+
+#[async_trait]
+impl FormatFileReader for AvroFormatReader {
+    async fn read_batch_stream(
+        &self,
+        reader: Box<dyn FileRead>,
+        file_size: u64,
+        read_fields: &[DataField],
+        _predicates: Option<&FilePredicates>,
+        batch_size: Option<usize>,
+        row_selection: Option<Vec<RowRange>>,
+    ) -> crate::Result<ArrowRecordBatchStream> {
+        // NOTE: Avro OCF requires sequential reading, so we load the entire 
file into memory.
+        // This is fine for typical Paimon data files but may be problematic 
for very large files.
+        let file_bytes = reader.read(0..file_size).await?;
+
+        let read_fields = read_fields.to_vec();
+        let target_schema = build_target_arrow_schema(&read_fields)?;
+        let batch_size = batch_size.unwrap_or(DEFAULT_BATCH_SIZE);
+
+        // Deserialize all Avro records from the OCF file.
+        let mut reader =
+            
serde_avro_fast::object_container_file_encoding::Reader::from_slice(&file_bytes)
+                .map_err(|e| Error::UnexpectedError {
+                    message: format!("Failed to open Avro file: {e}"),
+                    source: Some(Box::new(e)),
+                })?;
+
+        let mut all_records: Vec<HashMap<String, Value>> = Vec::new();
+        for result in reader.deserialize_borrowed::<HashMap<String, Value>>() {
+            let record = result.map_err(|e| Error::UnexpectedError {
+                message: format!("Failed to deserialize Avro record: {e}"),
+                source: Some(Box::new(e)),
+            })?;
+            all_records.push(record);
+        }
+
+        // Apply row selection filtering.
+        let records: Vec<HashMap<String, Value>> = match row_selection {
+            Some(ref ranges) => {
+                let total_rows = all_records.len();
+                let mask = ranges_to_mask(total_rows, ranges);
+                all_records
+                    .into_iter()
+                    .enumerate()
+                    .filter(|(i, _)| mask[*i])
+                    .map(|(_, r)| r)
+                    .collect()
+            }
+            None => all_records,
+        };
+
+        Ok(try_stream! {
+            for chunk in records.chunks(batch_size) {
+                let batch = records_to_batch(chunk, &read_fields, 
&target_schema)?;
+                yield batch;
+            }
+        }
+        .boxed())
+    }
+}
+
+// ---------------------------------------------------------------------------
+// Row ranges → boolean mask
+// ---------------------------------------------------------------------------
+
+fn ranges_to_mask(total_rows: usize, ranges: &[RowRange]) -> Vec<bool> {
+    let mut mask = vec![false; total_rows];
+    let file_end = total_rows as i64 - 1;
+    for r in ranges {
+        let from = r.from().max(0) as usize;
+        let to = (r.to().min(file_end) as usize).min(total_rows - 1);
+        for item in mask.iter_mut().take(to + 1).skip(from) {
+            *item = true;
+        }
+    }
+    mask
+}
+
+// ---------------------------------------------------------------------------
+// Avro records → Arrow RecordBatch conversion
+// ---------------------------------------------------------------------------
+
+fn records_to_batch(
+    records: &[HashMap<String, Value>],
+    fields: &[DataField],
+    schema: &SchemaRef,
+) -> crate::Result<RecordBatch> {
+    let num_rows = records.len();
+    let mut columns: Vec<Arc<dyn arrow_array::Array>> = 
Vec::with_capacity(fields.len());
+
+    for field in fields {
+        let col = build_column(records, field.name(), field.data_type(), 
num_rows)?;
+        columns.push(col);
+    }
+
+    if columns.is_empty() {
+        RecordBatch::try_new_with_options(
+            schema.clone(),
+            columns,
+            
&arrow_array::RecordBatchOptions::new().with_row_count(Some(num_rows)),
+        )
+    } else {
+        RecordBatch::try_new(schema.clone(), columns)
+    }
+    .map_err(|e| Error::UnexpectedError {
+        message: format!("Failed to build Avro RecordBatch: {e}"),
+        source: Some(Box::new(e)),
+    })
+}
+
+fn build_column(
+    records: &[HashMap<String, Value>],
+    name: &str,
+    data_type: &DataType,
+    num_rows: usize,
+) -> crate::Result<Arc<dyn arrow_array::Array>> {
+    Ok(match data_type {
+        DataType::Boolean(_) => {
+            let arr: BooleanArray = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| 
v.as_bool()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::TinyInt(_) => {
+            let arr: Int8Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_i64())
+                        .map(|v| v as i8)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::SmallInt(_) => {
+            let arr: Int16Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_i64())
+                        .map(|v| v as i16)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Int(_) => {
+            let arr: Int32Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_i64())
+                        .map(|v| v as i32)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::BigInt(_) => {
+            let arr: Int64Array = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| v.as_i64()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Float(_) => {
+            let arr: Float32Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_f64())
+                        .map(|v| v as f32)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Double(_) => {
+            let arr: Float64Array = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| v.as_f64()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Char(_) | DataType::VarChar(_) => {
+            let arr: StringArray = (0..num_rows)
+                .map(|i| get_field(&records[i], name).and_then(|v| v.as_str()))
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Binary(_) | DataType::VarBinary(_) => {
+            let values: Vec<Option<&[u8]>> = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name).and_then(|v| match v {
+                        Value::String(s) => Some(s.as_bytes()),
+                        _ => None,
+                    })
+                })
+                .collect();
+            let arr: BinaryArray = values.into_iter().collect();
+            Arc::new(arr)
+        }
+        DataType::Date(_) => {
+            let arr: Date32Array = (0..num_rows)
+                .map(|i| {
+                    get_field(&records[i], name)
+                        .and_then(|v| v.as_i64())
+                        .map(|v| v as i32)
+                })
+                .collect();
+            Arc::new(arr)
+        }
+        DataType::Decimal(d) => {

Review Comment:
   This decimal path is not safe. By the time we get here, the Avro value has 
already been converted into `serde_json::Value`, so `as_i64()` can silently 
turn valid decimal values into nulls. We should decode the decimal with a typed 
path instead of going through JSON values 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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to