miomiocat commented on code in PR #1518: URL: https://github.com/apache/paimon-rust/pull/1518#discussion_r4674977255
########## 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: Fixed in 7f4f02ce. The C reader now shares Core's visible-list and visible-map helpers. It rebases sliced offsets and skips physical entries owned only by null parents before validating payloads. The regressions place malformed values outside a slice and behind a null map row. ########## 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: Fixed in 7f4f02ce. The multiset branch normalizes its map keys according to the element type and carries the corresponding counts through unchanged. The regression uses `MULTISET<ROW<v VARIANT>>` and distinguishes an empty payload pair from an encoded Variant null. -- 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]
