JingsongLi commented on code in PR #1518:
URL: https://github.com/apache/paimon-rust/pull/1518#discussion_r4665118941


##########
bindings/c/src/table/variant.rs:
##########
@@ -0,0 +1,333 @@
+// 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.
+
+//! Canonical Arrow representation of Paimon VARIANT at the C Data boundary.
+use arrow::buffer::NullBuffer;
+use arrow_array::{Array, ArrayRef, BinaryArray, ListArray, MapArray, 
RecordBatch, StructArray};
+use arrow_schema::{DataType as ArrowDataType, Schema as ArrowSchema};
+use paimon::spec::{DataField, DataType};
+use std::sync::Arc;
+
+fn contains_variant(data_type: &DataType) -> bool {
+    match data_type {
+        DataType::Variant(_) => true,
+        DataType::Array(array) => contains_variant(array.element_type()),
+        DataType::Map(map) => {
+            contains_variant(map.key_type()) || 
contains_variant(map.value_type())
+        }
+        DataType::Row(row) => row
+            .fields()
+            .iter()
+            .any(|field| contains_variant(field.data_type())),
+        _ => false,
+    }
+}
+
+fn invalid_array(path: &str, expected: &str, actual: &ArrowDataType) -> 
paimon::Error {
+    paimon::Error::DataInvalid {
+        message: format!("Expected {expected} for Paimon column '{path}', got 
{actual:?}"),
+        source: None,
+    }
+}
+
+fn normalize_variant_array(array: &ArrayRef, path: &str) -> 
paimon::Result<ArrayRef> {
+    let input = array
+        .as_any()
+        .downcast_ref::<StructArray>()
+        .ok_or_else(|| invalid_array(path, "StructArray", array.data_type()))?;
+    if input.num_columns() != 2 {
+        return Err(invalid_array(
+            path,
+            "two-field Variant struct",
+            array.data_type(),
+        ));
+    }
+    let values = input
+        .column_by_name("value")
+        .and_then(|column| column.as_any().downcast_ref::<BinaryArray>())
+        .ok_or_else(|| invalid_array(path, "BinaryArray Variant.value", 
array.data_type()))?;
+    let metadata = input
+        .column_by_name("metadata")
+        .and_then(|column| column.as_any().downcast_ref::<BinaryArray>())
+        .ok_or_else(|| invalid_array(path, "BinaryArray Variant.metadata", 
array.data_type()))?;
+
+    // Keep the native payload byte-for-byte: JSON loses Variant scalar types.
+    // Only canonicalize the child schema and legacy Java SQL-null encoding.
+    let canonical_type = paimon::arrow::variant_arrow_type();
+    let mut rebuild = input.data_type() != &canonical_type;
+    let mut validity = Vec::with_capacity(input.len());
+    for row in 0..input.len() {
+        let value_is_empty = values.is_null(row) || 
values.value(row).is_empty();
+        let metadata_is_empty = metadata.is_null(row) || 
metadata.value(row).is_empty();
+        if input.is_null(row) || (value_is_empty && metadata_is_empty) {
+            validity.push(false);
+            rebuild |= input.is_valid(row) || values.is_null(row) || 
metadata.is_null(row);
+            continue;
+        }
+        if value_is_empty || metadata_is_empty {
+            return Err(paimon::Error::DataInvalid {
+                message: format!("Incomplete Variant payload in column 
'{path}' at row {row}"),
+                source: None,
+            });
+        }
+        paimon::variant::validate_payload(values.value(row), 
metadata.value(row))?;
+        validity.push(true);
+    }
+    if !rebuild {
+        return Ok(Arc::clone(array));
+    }
+    let children: Vec<ArrayRef> = [values, metadata]
+        .into_iter()
+        .map(|child| {
+            Arc::new(BinaryArray::from_iter_values((0..input.len()).map(|row| {
+                if validity[row] {
+                    child.value(row)
+                } else {
+                    &[]
+                }
+            }))) as ArrayRef
+        })
+        .collect();
+    let ArrowDataType::Struct(fields) = canonical_type else {
+        unreachable!("Variant Arrow type is a struct");
+    };
+    let nulls = validity
+        .iter()
+        .any(|valid| !valid)
+        .then(|| NullBuffer::from(validity));
+    StructArray::try_new(fields, children, nulls)
+        .map(|array| Arc::new(array) as ArrayRef)
+        .map_err(|error| paimon::Error::UnexpectedError {
+            message: format!("Failed to normalize Variant column '{path}': 
{error}"),
+            source: Some(Box::new(error)),
+        })
+}
+
+fn canonicalize_variants(
+    array: &ArrayRef,
+    data_type: &DataType,
+    path: &str,
+) -> paimon::Result<ArrayRef> {
+    // Do not reinterpret an ordinary ROW<value BINARY, metadata BINARY> as a
+    // Variant just because its physical shape happens to match.
+    if !contains_variant(data_type) {
+        return Ok(Arc::clone(array));
+    }
+
+    match data_type {
+        DataType::Variant(_) => normalize_variant_array(array, path),
+        DataType::Array(array_type) => {
+            let input = array
+                .as_any()
+                .downcast_ref::<ListArray>()
+                .ok_or_else(|| invalid_array(path, "ListArray", 
array.data_type()))?;
+            let values = canonicalize_variants(
+                input.values(),

Review Comment:
   [P2] Limit ARRAY and MAP normalization to entries visible in the current 
batch. Arrow slices keep their backing child arrays, and merged Data Evolution 
reads emit slices of source columns. A two-row ListArray with an incomplete 
Variant only in the second row failed normalization when I passed a slice 
containing just the valid first row. Use the active offsets and parent validity 
when traversing children, like Core's nested evolution logic. This also avoids 
revalidating the full source array for each emitted slice.



##########
bindings/c/src/table/variant.rs:
##########
@@ -0,0 +1,333 @@
+// 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.
+
+//! Canonical Arrow representation of Paimon VARIANT at the C Data boundary.
+use arrow::buffer::NullBuffer;
+use arrow_array::{Array, ArrayRef, BinaryArray, ListArray, MapArray, 
RecordBatch, StructArray};
+use arrow_schema::{DataType as ArrowDataType, Schema as ArrowSchema};
+use paimon::spec::{DataField, DataType};
+use std::sync::Arc;
+
+fn contains_variant(data_type: &DataType) -> bool {
+    match data_type {
+        DataType::Variant(_) => true,
+        DataType::Array(array) => contains_variant(array.element_type()),
+        DataType::Map(map) => {
+            contains_variant(map.key_type()) || 
contains_variant(map.value_type())
+        }
+        DataType::Row(row) => row
+            .fields()
+            .iter()
+            .any(|field| contains_variant(field.data_type())),
+        _ => false,

Review Comment:
   [P2] Normalize VARIANT nested inside MULTISET elements. Paimon's Arrow 
mapping stores a multiset as a map whose key is the element type. I wrote and 
read a Parquet table with `MULTISET<ROW<v VARIANT>>` through the C API. The 
empty-pair SQL NULL and the encoded Variant null both came back valid inside 
the key. Recurse through the multiset key, leaving the count unchanged.



-- 
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