miomiocat commented on code in PR #1512:
URL: https://github.com/apache/paimon-rust/pull/1512#discussion_r4679185953


##########
crates/paimon/src/arrow/format/mosaic.rs:
##########
@@ -897,18 +894,111 @@ fn ensure_schema(batch: RecordBatch, target_schema: 
&SchemaRef) -> crate::Result
         return Ok(batch);
     }
 
+    if batch.num_columns() != target_schema.fields().len() {
+        return Err(Error::DataInvalid {
+            message: format!(
+                "Mosaic returned {} columns for {} projected fields",
+                batch.num_columns(),
+                target_schema.fields().len()
+            ),
+            source: None,
+        });
+    }
     if batch.num_columns() == 0 {
         return empty_batch(target_schema.clone(), batch.num_rows());
     }
 
-    RecordBatch::try_new(target_schema.clone(), 
batch.columns().to_vec()).map_err(|e| {
-        Error::UnexpectedError {
-            message: format!("Failed to align Mosaic RecordBatch schema: {e}"),
-            source: Some(Box::new(e)),
-        }
+    let columns = target_schema
+        .fields()
+        .iter()
+        .map(|field| {
+            let column = batch
+                .column_by_name(field.name())
+                .ok_or_else(|| Error::DataInvalid {
+                    message: format!("Missing projected Mosaic field '{}'", 
field.name()),
+                    source: None,
+                })?;
+            align_array_type(column, field.data_type())
+        })
+        .collect::<crate::Result<Vec<_>>>()?;
+
+    RecordBatch::try_new(target_schema.clone(), columns).map_err(|e| 
Error::UnexpectedError {
+        message: format!("Failed to align Mosaic RecordBatch schema: {e}"),
+        source: Some(Box::new(e)),
     })
 }
 
+/// Rebuild an Arrow array with the logical schema's nested field metadata 
while
+/// retaining the physical buffers. Arrow includes List/Map/Struct child field
+/// names in data-type equality, but Mosaic writers use different internal 
names
+/// (for example `$data$`) than Paimon's logical Arrow schema (`element`).
+fn align_array_type(array: &ArrayRef, target_type: &ArrowDataType) -> 
crate::Result<ArrayRef> {
+    if array.data_type() == target_type {
+        return Ok(array.clone());
+    }
+
+    let data = align_array_data(array.to_data(), target_type, false)?;
+    Ok(make_array(data))
+}
+
+fn align_array_data(
+    data: ArrayData,
+    target: &ArrowDataType,
+    map_entries: bool,
+) -> crate::Result<ArrayData> {
+    use ArrowDataType::{FixedSizeList, LargeList, List, Map, Struct};
+    let source = data.data_type();
+    if source == target {
+        return Ok(data);
+    }
+    let children: Vec<_> = match (source, target) {
+        (List(_), List(field)) | (LargeList(_), LargeList(field)) => {
+            vec![(field.data_type(), false)]
+        }
+        (FixedSizeList(_, a), FixedSizeList(field, b)) if a == b => {
+            vec![(field.data_type(), false)]
+        }
+        // Arrow MAP fixes key and value by position, regardless of their 
field names.
+        (Map(_, a), Map(entries, b)) if a == b => vec![(entries.data_type(), 
true)],
+        (Struct(input), Struct(output))
+            if input.len() == output.len()
+                && (map_entries
+                    || input
+                        .iter()
+                        .zip(output.iter())
+                        .all(|(a, b)| a.name() == b.name())) =>
+        {
+            output
+                .iter()
+                .map(|field| (field.data_type(), false))
+                .collect()
+        }
+        _ => {
+            return Err(Error::DataInvalid {
+                message: format!(
+                    "Cannot align incompatible Mosaic Arrow type {source:?} to 
{target:?}"
+                ),
+                source: None,
+            })
+        }
+    };
+    let children = data
+        .child_data()
+        .iter()

Review Comment:
   Thanks for the concrete example. In b300dc38, list alignment now takes the 
child span between the first and last visible offsets, rebases those offsets, 
and then applies the projected child type. List, LargeList and Map use the same 
rule. I added a Mosaic file regression that reads [42] and [7] past a [NULL] 
list, selects two disjoint ranges around another [NULL], and checks that 
selecting the null element still produces an error. The regression compiles 
with `cargo check --locked -p paimon --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: [email protected]

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

Reply via email to