klion26 commented on code in PR #10313:
URL: https://github.com/apache/arrow-rs/pull/10313#discussion_r3841121078
##########
parquet-variant-compute/src/variant_to_arrow.rs:
##########
@@ -701,6 +714,246 @@ impl<'a> StructVariantToArrowRowBuilder<'a> {
}
}
+/// Builder for converting variant values into a [`UnionArray`].
+///
+/// Each value is dispatched to the union field that most exactly represents
its runtime type
+/// (see [`union_child_rank`]), with ties broken by declaration order. Unions
have no top-level
+/// null buffer, so null rows -- and, in safe mode, values no field can
represent -- become a
+/// null in the [`DataType::Null`] child if the union declares one, otherwise
in the first child.
+pub(crate) struct UnionVariantToArrowRowBuilder<'a> {
+ fields: &'a UnionFields,
+ mode: UnionMode,
+ children: Vec<UnionChildBuilder<'a>>,
+ type_ids: Vec<i8>,
+ /// Dense mode only
+ offsets: Vec<i32>,
+ null_child: usize,
+ cast_options: &'a CastOptions<'a>,
+}
+
+struct UnionChildBuilder<'a> {
+ type_id: i8,
+ builder: VariantToArrowRowBuilder<'a>,
+ len: i32,
+}
+
+impl<'a> UnionVariantToArrowRowBuilder<'a> {
+ fn try_new(
+ fields: &'a UnionFields,
+ mode: UnionMode,
+ cast_options: &'a CastOptions<'a>,
+ capacity: usize,
+ ) -> Result<Self> {
+ // null rows need a child to land in
+ if fields.is_empty() {
+ return Err(ArrowError::InvalidArgumentError(
+ "Casting Variant to a union requires at least one union
field".to_string(),
+ ));
+ }
+ let mut children = Vec::with_capacity(fields.len());
+ for (type_id, field) in fields.iter() {
+ // Match the other typed builders: nullability is schema metadata
and does not
+ // override safe-cast behavior, which may append null for an
unrepresentable value.
+ children.push(UnionChildBuilder {
+ type_id,
+ builder: make_typed_variant_to_arrow_row_builder(
+ field.data_type(),
+ cast_options,
+ capacity,
+ false,
+ )?,
+ len: 0,
+ });
+ }
+ let null_child = fields
+ .iter()
+ .position(|(_, field)| field.data_type() == &DataType::Null)
+ .unwrap_or(0);
+ let offsets = match mode {
+ UnionMode::Dense => Vec::with_capacity(capacity),
+ UnionMode::Sparse => Vec::new(),
+ };
+ Ok(Self {
+ fields,
+ mode,
+ children,
+ type_ids: Vec::with_capacity(capacity),
+ offsets,
+ null_child,
+ cast_options,
+ })
+ }
+
+ fn append_null(&mut self) -> Result<()> {
+ self.append_to_child(self.null_child, None)?;
+ Ok(())
+ }
+
+ fn append_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
+ // `Variant::Null` becomes null even in strict mode, like in the other
builders
+ if matches!(value, Variant::Null) {
+ self.append_null()?;
+ return Ok(false);
+ }
+ match self.select_child(value) {
+ Some(index) => self.append_to_child(index, Some(value)),
+ None if self.cast_options.safe => {
+ self.append_null()?;
+ Ok(false)
+ }
+ None => Err(ArrowError::CastError(format!(
+ "Failed to cast variant {value:?} to union: no field can
represent it"
+ ))),
+ }
+ }
+
+ fn select_child(&self, value: &Variant<'_, '_>) -> Option<usize> {
+ let mut best: Option<(u8, usize)> = None;
+ for (index, (_, field)) in self.fields.iter().enumerate() {
+ let Some(rank) = union_child_rank(value, field.data_type()) else {
+ continue;
+ };
+ if best.is_none_or(|(best_rank, _)| rank < best_rank) {
+ best = Some((rank, index));
+ }
+ }
+ best.map(|(_, index)| index)
+ }
+
+ fn append_to_child(&mut self, index: usize, value: Option<&Variant<'_,
'_>>) -> Result<bool> {
+ self.type_ids.push(self.children[index].type_id);
+ match self.mode {
+ UnionMode::Dense => {
+ let child = &mut self.children[index];
+ self.offsets.push(child.len);
+ child.len = child.len.add_checked(1)?;
+ match value {
+ Some(value) => child.builder.append_value(value.clone()),
+ None => {
+ child.builder.append_null()?;
+ Ok(false)
+ }
+ }
+ }
+ UnionMode::Sparse => {
+ let mut appended = false;
+ for (child_index, child) in
self.children.iter_mut().enumerate() {
+ match value {
+ Some(value) if child_index == index => {
+ appended =
child.builder.append_value(value.clone())?;
+ }
+ _ => child.builder.append_null()?,
+ }
+ }
+ Ok(appended)
+ }
+ }
+ }
+
+ fn finish(self) -> Result<ArrayRef> {
+ let mut type_ids = Vec::with_capacity(self.children.len());
+ let mut fields = Vec::with_capacity(self.children.len());
+ let mut arrays = Vec::with_capacity(self.children.len());
+ for (child, (_, field)) in
self.children.into_iter().zip(self.fields.iter()) {
+ let array = child.builder.finish()?;
+ type_ids.push(child.type_id);
+ fields.push(
+ field
+ .as_ref()
+ .clone()
+ .with_data_type(array.data_type().clone()),
+ );
+ arrays.push(array);
+ }
+ let fields = UnionFields::try_new(type_ids, fields)?;
+ let offsets = (self.mode == UnionMode::Dense).then(||
ScalarBuffer::from(self.offsets));
+ let array =
+ UnionArray::try_new(fields, ScalarBuffer::from(self.type_ids),
offsets, arrays)?;
+ Ok(Arc::new(array))
+ }
+}
+
+/// Ranks how exactly a union child of type `data_type` can represent a
variant value's runtime
+/// type: 0 is the value's natural Arrow type, higher ranks are lossless
widenings, and `None`
+/// means the child cannot represent the value losslessly. Every pair admitted
here must be
+/// convertible by the corresponding row builder.
+fn union_child_rank(value: &Variant<'_, '_>, data_type: &DataType) ->
Option<u8> {
Review Comment:
Here we use type-based info to determine which target the current variant
should belong to. This seems incorrect
1. Variant::Int64(1) can't convert to DataType::Int8, but this should valid
when calling `variant_get`
2. The logic in the current code (json -> variant, and variant spec), treats
the exact number the same in Variant::Int64/Int32/Int16 etc(value has no strict
type in variant) (like the `Equivalence Class` in parquet variant spec)
##########
parquet-variant-compute/src/variant_to_arrow.rs:
##########
@@ -701,6 +714,246 @@ impl<'a> StructVariantToArrowRowBuilder<'a> {
}
}
+/// Builder for converting variant values into a [`UnionArray`].
+///
+/// Each value is dispatched to the union field that most exactly represents
its runtime type
+/// (see [`union_child_rank`]), with ties broken by declaration order. Unions
have no top-level
+/// null buffer, so null rows -- and, in safe mode, values no field can
represent -- become a
+/// null in the [`DataType::Null`] child if the union declares one, otherwise
in the first child.
+pub(crate) struct UnionVariantToArrowRowBuilder<'a> {
+ fields: &'a UnionFields,
+ mode: UnionMode,
+ children: Vec<UnionChildBuilder<'a>>,
+ type_ids: Vec<i8>,
+ /// Dense mode only
+ offsets: Vec<i32>,
+ null_child: usize,
+ cast_options: &'a CastOptions<'a>,
+}
+
+struct UnionChildBuilder<'a> {
+ type_id: i8,
+ builder: VariantToArrowRowBuilder<'a>,
+ len: i32,
+}
+
+impl<'a> UnionVariantToArrowRowBuilder<'a> {
+ fn try_new(
+ fields: &'a UnionFields,
+ mode: UnionMode,
+ cast_options: &'a CastOptions<'a>,
+ capacity: usize,
+ ) -> Result<Self> {
+ // null rows need a child to land in
+ if fields.is_empty() {
+ return Err(ArrowError::InvalidArgumentError(
+ "Casting Variant to a union requires at least one union
field".to_string(),
+ ));
+ }
+ let mut children = Vec::with_capacity(fields.len());
+ for (type_id, field) in fields.iter() {
+ // Match the other typed builders: nullability is schema metadata
and does not
+ // override safe-cast behavior, which may append null for an
unrepresentable value.
+ children.push(UnionChildBuilder {
+ type_id,
+ builder: make_typed_variant_to_arrow_row_builder(
+ field.data_type(),
+ cast_options,
+ capacity,
+ false,
+ )?,
+ len: 0,
+ });
+ }
+ let null_child = fields
+ .iter()
+ .position(|(_, field)| field.data_type() == &DataType::Null)
+ .unwrap_or(0);
+ let offsets = match mode {
+ UnionMode::Dense => Vec::with_capacity(capacity),
+ UnionMode::Sparse => Vec::new(),
+ };
+ Ok(Self {
+ fields,
+ mode,
+ children,
+ type_ids: Vec::with_capacity(capacity),
+ offsets,
+ null_child,
+ cast_options,
+ })
+ }
+
+ fn append_null(&mut self) -> Result<()> {
+ self.append_to_child(self.null_child, None)?;
+ Ok(())
+ }
+
+ fn append_value(&mut self, value: &Variant<'_, '_>) -> Result<bool> {
+ // `Variant::Null` becomes null even in strict mode, like in the other
builders
+ if matches!(value, Variant::Null) {
+ self.append_null()?;
+ return Ok(false);
+ }
+ match self.select_child(value) {
+ Some(index) => self.append_to_child(index, Some(value)),
+ None if self.cast_options.safe => {
+ self.append_null()?;
+ Ok(false)
+ }
+ None => Err(ArrowError::CastError(format!(
+ "Failed to cast variant {value:?} to union: no field can
represent it"
+ ))),
+ }
+ }
+
+ fn select_child(&self, value: &Variant<'_, '_>) -> Option<usize> {
+ let mut best: Option<(u8, usize)> = None;
+ for (index, (_, field)) in self.fields.iter().enumerate() {
+ let Some(rank) = union_child_rank(value, field.data_type()) else {
+ continue;
+ };
+ if best.is_none_or(|(best_rank, _)| rank < best_rank) {
+ best = Some((rank, index));
+ }
+ }
+ best.map(|(_, index)| index)
+ }
+
+ fn append_to_child(&mut self, index: usize, value: Option<&Variant<'_,
'_>>) -> Result<bool> {
+ self.type_ids.push(self.children[index].type_id);
+ match self.mode {
+ UnionMode::Dense => {
+ let child = &mut self.children[index];
+ self.offsets.push(child.len);
+ child.len = child.len.add_checked(1)?;
+ match value {
+ Some(value) => child.builder.append_value(value.clone()),
+ None => {
+ child.builder.append_null()?;
+ Ok(false)
+ }
+ }
+ }
+ UnionMode::Sparse => {
+ let mut appended = false;
+ for (child_index, child) in
self.children.iter_mut().enumerate() {
+ match value {
+ Some(value) if child_index == index => {
+ appended =
child.builder.append_value(value.clone())?;
+ }
+ _ => child.builder.append_null()?,
+ }
+ }
+ Ok(appended)
+ }
+ }
+ }
+
+ fn finish(self) -> Result<ArrayRef> {
+ let mut type_ids = Vec::with_capacity(self.children.len());
+ let mut fields = Vec::with_capacity(self.children.len());
+ let mut arrays = Vec::with_capacity(self.children.len());
+ for (child, (_, field)) in
self.children.into_iter().zip(self.fields.iter()) {
+ let array = child.builder.finish()?;
+ type_ids.push(child.type_id);
+ fields.push(
+ field
+ .as_ref()
+ .clone()
+ .with_data_type(array.data_type().clone()),
+ );
+ arrays.push(array);
+ }
+ let fields = UnionFields::try_new(type_ids, fields)?;
+ let offsets = (self.mode == UnionMode::Dense).then(||
ScalarBuffer::from(self.offsets));
+ let array =
+ UnionArray::try_new(fields, ScalarBuffer::from(self.type_ids),
offsets, arrays)?;
+ Ok(Arc::new(array))
+ }
+}
+
+/// Ranks how exactly a union child of type `data_type` can represent a
variant value's runtime
+/// type: 0 is the value's natural Arrow type, higher ranks are lossless
widenings, and `None`
+/// means the child cannot represent the value losslessly. Every pair admitted
here must be
+/// convertible by the corresponding row builder.
+fn union_child_rank(value: &Variant<'_, '_>, data_type: &DataType) ->
Option<u8> {
Review Comment:
Maybe we can sort the field in the Union, and try the target column in the
sorted order like we treat like the `json-> variant`(from_json.rs in
`parquet-variant-compute`)
--
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]