Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 60 additions & 7 deletions arrow-cast/src/cast/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use crate::cast::*;
use arrow_buffer::ScalarBuffer;
use arrow_buffer::{NullBuffer, ScalarBuffer};
use arrow_select::filter::filter;

/// Converts a non-list array to a list array where every element is a single element
/// list. `NULL`s in the original array become `[NULL]` (i.e. output list array
Expand Down Expand Up @@ -55,17 +56,69 @@ pub(crate) fn cast_values_to_list_view<O: OffsetSizeTrait>(
Ok(Arc::new(list))
}

/// Cast fixed size list array to inner values type, essentially flattening the
/// lists.
///
/// For example: `FixedSizeList<Int32, 2>([[1, 2], [3, 4]]) -> Int32([1, 2, 3, 4])`
/// Cast a size-one fixed-size list to its child type, preserving null rows.
pub(crate) fn cast_single_element_fixed_size_list_to_values(
array: &dyn Array,
to: &DataType,
cast_options: &CastOptions,
) -> Result<ArrayRef, ArrowError> {
let values = array.as_fixed_size_list().values();
cast_with_options(values, to, cast_options)
let array = array.as_fixed_size_list();
let values = array.values();
let Some(nulls) = array.nulls().filter(|nulls| nulls.null_count() != 0) else {
return cast_with_options(values, to, cast_options);
};

if !cast_options.safe && values.data_type() != to {
return cast_valid_values_and_take(values.as_ref(), nulls, to, cast_options);
}

match cast_with_options(values, to, cast_options) {
Ok(values) => apply_null_mask(values, nulls),
Err(_) if values.data_type() != to => {
// Even in safe mode, casting a masked child row can fail (e.g. a non-nullable
// field inside a masked Struct). Fall back to filtering out null list rows first.
cast_valid_values_and_take(values.as_ref(), nulls, to, cast_options)
}
Err(err) => Err(err),
}
}

fn cast_valid_values_and_take(
values: &dyn Array,
nulls: &NullBuffer,
to: &DataType,
cast_options: &CastOptions,
) -> Result<ArrayRef, ArrowError> {
// Skip masked child values so a cast cannot fail on a null list row.
let valid = BooleanArray::new(nulls.inner().clone(), None);
let values = filter(values, &valid)?;
let values = cast_with_options(values.as_ref(), to, cast_options)?;
let mut valid_indices = 0_u64..;
let indices: UInt64Array = nulls
.iter()
.map(|valid| if valid { valid_indices.next() } else { None })
.collect();
take(values.as_ref(), &indices, None)
}

fn apply_null_mask(values: ArrayRef, nulls: &NullBuffer) -> Result<ArrayRef, ArrowError> {
match values.data_type() {
DataType::Null => Ok(values),
DataType::RunEndEncoded(_, _) | DataType::Union(_, _) => {
let indices: UInt64Array = nulls
.iter()
.enumerate()
.map(|(index, valid)| valid.then_some(index as u64))
.collect();
take(values.as_ref(), &indices, None)
}
_ => {
let merged = NullBuffer::union(Some(nulls), values.nulls());
let data = values.to_data().into_builder().nulls(merged);
// SAFETY: Only adding nulls to a data type whose layout supports a null buffer.
Ok(make_array(unsafe { data.build_unchecked() }))
}
}
}

fn cast_fixed_size_list_to_list_inner<OffsetSize: OffsetSizeTrait, const IS_LIST_VIEW: bool>(
Expand Down
202 changes: 202 additions & 0 deletions arrow-cast/tests/cast/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1801,3 +1801,205 @@ fn test_first_last_none() {
)) as ArrayRef;
assert_eq!(*fixed_array, *r);
}

#[test]
fn test_cast_single_element_fixed_size_list_preserves_nulls() {
let values = StringArray::from(vec![
Some("skip"),
Some("10"),
Some("99"),
Some("invalid"),
None,
Some("20"),
]);
let array = FixedSizeListArray::new(
Arc::new(Field::new_list_field(DataType::Utf8, true)),
1,
Arc::new(values),
Some(NullBuffer::from(vec![true, true, false, false, true, true])),
)
.slice(1, 5);

let expected = Int32Array::from(vec![Some(10), None, None, None, Some(20)]);
for safe in [true, false] {
let options = CastOptions {
safe,
..Default::default()
};
let casted = cast_with_options(&array, &DataType::Int32, &options).unwrap();
assert_eq!(casted.as_primitive::<Int32Type>(), &expected);
}

// Same-type unwrap with masked non-null child values under null list rows (including sliced).
let int_array = FixedSizeListArray::new(
Arc::new(Field::new_list_field(DataType::Int32, false)),
1,
Arc::new(Int32Array::from(vec![0, 1, 999, 3])),
Some(NullBuffer::from(vec![true, true, false, true])),
)
.slice(1, 3);
for safe in [true, false] {
let options = CastOptions {
safe,
..Default::default()
};
let unwrapped = cast_with_options(&int_array, &DataType::Int32, &options).unwrap();
assert_eq!(
unwrapped.as_primitive::<Int32Type>(),
&Int32Array::from(vec![Some(1), None, Some(3)])
);
}

// All-null single-element fixed-size list.
let all_null = FixedSizeListArray::new(
Arc::new(Field::new_list_field(DataType::Int32, false)),
1,
Arc::new(Int32Array::from(vec![7, 8])),
Some(NullBuffer::from(vec![false, false])),
);
let unwrapped_all_null = cast(&all_null, &DataType::Int32).unwrap();
assert_eq!(
unwrapped_all_null.as_primitive::<Int32Type>(),
&Int32Array::from(vec![None, None])
);

// Struct child with a non-nullable field under a null list row.
let struct_fields = arrow_schema::Fields::from(vec![Field::new("x", DataType::Int32, false)]);
let struct_values = arrow_array::StructArray::try_new(
struct_fields.clone(),
vec![Arc::new(Int32Array::from(vec![10, 999])) as ArrayRef],
None,
)
.unwrap();
let struct_list = FixedSizeListArray::new(
Arc::new(Field::new_list_field(
DataType::Struct(struct_fields.clone()),
true,
)),
1,
Arc::new(struct_values),
Some(NullBuffer::from(vec![true, false])),
);
let casted_struct = cast(&struct_list, &DataType::Struct(struct_fields)).unwrap();
assert!(casted_struct.is_valid(0));
assert!(casted_struct.is_null(1));
assert_eq!(
casted_struct
.as_struct()
.column(0)
.as_primitive::<Int32Type>()
.value(0),
10
);

// Casting through a dictionary target preserves parent nulls in both safe and strict modes.
let dict_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Int32));
for safe in [true, false] {
let options = CastOptions {
safe,
..Default::default()
};
let casted_dict = cast_with_options(&array, &dict_type, &options).unwrap();
let roundtrip = cast(&casted_dict, &DataType::Int32).unwrap();
assert_eq!(roundtrip.as_primitive::<Int32Type>(), &expected);
}

// Null child array unwraps cleanly without attaching a null buffer.
let null_list = FixedSizeListArray::new(
Arc::new(Field::new_list_field(DataType::Null, true)),
1,
Arc::new(arrow_array::NullArray::new(2)),
Some(NullBuffer::from(vec![true, false])),
);
let unwrapped_null = cast(&null_list, &DataType::Null).unwrap();
assert_eq!(unwrapped_null.data_type(), &DataType::Null);
assert_eq!(unwrapped_null.len(), 2);
assert!(unwrapped_null.nulls().is_none());
assert_eq!(unwrapped_null.logical_null_count(), 2);

// Strict cast still fails when an invalid child value is in a valid row.
let bad_row = FixedSizeListArray::new(
Arc::new(Field::new_list_field(DataType::Utf8, true)),
1,
Arc::new(StringArray::from(vec![Some("invalid"), Some("20")])),
Some(NullBuffer::from(vec![true, false])),
);
let strict = CastOptions {
safe: false,
..Default::default()
};
assert!(cast_with_options(&bad_row, &DataType::Int32, &strict).is_err());
let safe_invalid = cast(&bad_row, &DataType::Int32).unwrap();
assert_eq!(
safe_invalid.as_primitive::<Int32Type>(),
&Int32Array::from(vec![None, None])
);

// Safe and strict casts of a masked invalid non-nullable struct child succeed.
let src_fields = arrow_schema::Fields::from(vec![Field::new("number", DataType::Utf8, false)]);
let dst_fields = arrow_schema::Fields::from(vec![Field::new("number", DataType::Int32, false)]);
let src_type = DataType::Struct(src_fields.clone());
let dst_type = DataType::Struct(dst_fields);
let src_struct = arrow_array::StructArray::try_new(
src_fields.clone(),
vec![Arc::new(StringArray::from(vec!["2", "invalid"])) as ArrayRef],
None,
)
.unwrap();
let masked_struct_list = FixedSizeListArray::new(
Arc::new(Field::new_list_field(src_type.clone(), true)),
1,
Arc::new(src_struct),
Some(NullBuffer::from(vec![true, false])),
);
for safe in [true, false] {
let options = CastOptions {
safe,
..Default::default()
};
let casted = cast_with_options(&masked_struct_list, &dst_type, &options).unwrap();
assert!(casted.is_valid(0));
assert!(casted.is_null(1));
assert_eq!(
casted
.as_struct()
.column(0)
.as_primitive::<Int32Type>()
.value(0),
2
);
}

// All-null masked invalid non-nullable struct child also succeeds.
let all_null_src_struct = arrow_array::StructArray::try_new(
src_fields.clone(),
vec![Arc::new(StringArray::from(vec!["bad1", "bad2"])) as ArrayRef],
None,
)
.unwrap();
let all_null_struct_list = FixedSizeListArray::new(
Arc::new(Field::new_list_field(src_type.clone(), true)),
1,
Arc::new(all_null_src_struct),
Some(NullBuffer::from(vec![false, false])),
);
let casted_all_null = cast(&all_null_struct_list, &dst_type).unwrap();
assert_eq!(casted_all_null.len(), 2);
assert!(casted_all_null.is_null(0));
assert!(casted_all_null.is_null(1));

// An invalid non-nullable struct child in a valid row still fails in safe mode.
let invalid_valid_row_struct = arrow_array::StructArray::try_new(
src_fields,
vec![Arc::new(StringArray::from(vec!["invalid", "2"])) as ArrayRef],
None,
)
.unwrap();
let invalid_valid_row_list = FixedSizeListArray::new(
Arc::new(Field::new_list_field(src_type, true)),
1,
Arc::new(invalid_valid_row_struct),
Some(NullBuffer::from(vec![true, false])),
);
assert!(cast(&invalid_valid_row_list, &dst_type).is_err());
}