Skip to main content

vortex_array/arrays/struct_/compute/
cast.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use itertools::Itertools;
5use vortex_error::VortexResult;
6use vortex_error::vortex_ensure;
7
8use crate::ArrayRef;
9use crate::ExecutionCtx;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::arrays::ConstantArray;
13use crate::arrays::Struct;
14use crate::arrays::StructArray;
15use crate::arrays::struct_::StructArrayExt;
16use crate::builtins::ArrayBuiltins;
17use crate::dtype::DType;
18use crate::scalar::Scalar;
19use crate::scalar_fn::fns::cast::CastKernel;
20
21impl CastKernel for Struct {
22    fn cast(
23        array: ArrayView<'_, Struct>,
24        dtype: &DType,
25        _ctx: &mut ExecutionCtx,
26    ) -> VortexResult<Option<ArrayRef>> {
27        let Some(target_sdtype) = dtype.as_struct_fields_opt() else {
28            return Ok(None);
29        };
30
31        let source_sdtype = array.struct_fields();
32
33        let fields_match_order = target_sdtype.nfields() == source_sdtype.nfields()
34            && target_sdtype
35                .names()
36                .iter()
37                .zip(source_sdtype.names().iter())
38                .all(|(f1, f2)| f1 == f2);
39
40        let mut cast_fields = Vec::with_capacity(target_sdtype.nfields());
41        if fields_match_order {
42            for (field, target_type) in array.iter_unmasked_fields().zip_eq(target_sdtype.fields())
43            {
44                let cast_field = field.cast(target_type)?;
45                cast_fields.push(cast_field);
46            }
47        } else {
48            // Re-order, handle fields by value instead.
49            for (target_name, target_type) in
50                target_sdtype.names().iter().zip_eq(target_sdtype.fields())
51            {
52                match source_sdtype.find(target_name) {
53                    None => {
54                        // No source field with this name => evolve the schema compatibly.
55                        // If the field is nullable, we add a new ConstantArray field with the type.
56                        vortex_ensure!(
57                            target_type.is_nullable(),
58                            "CAST for struct only supports added nullable fields"
59                        );
60
61                        cast_fields.push(
62                            ConstantArray::new(Scalar::null(target_type), array.len()).into_array(),
63                        );
64                    }
65                    Some(src_field_idx) => {
66                        // Field exists in source field. Cast it to the target type.
67                        let cast_field = array.unmasked_field(src_field_idx).cast(target_type)?;
68                        cast_fields.push(cast_field);
69                    }
70                }
71            }
72        }
73
74        let validity = array
75            .validity()?
76            .cast_nullability(dtype.nullability(), array.len())?;
77
78        StructArray::try_new(
79            target_sdtype.names().clone(),
80            cast_fields,
81            array.len(),
82            validity,
83        )
84        .map(|a| Some(a.into_array()))
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use rstest::rstest;
91    use vortex_buffer::buffer;
92
93    use crate::IntoArray;
94    use crate::ToCanonical;
95    use crate::arrays::PrimitiveArray;
96    use crate::arrays::StructArray;
97    use crate::arrays::VarBinArray;
98    use crate::arrays::struct_::StructArrayExt;
99    use crate::builtins::ArrayBuiltins;
100    use crate::compute::conformance::cast::test_cast_conformance;
101    use crate::dtype::DType;
102    use crate::dtype::DecimalDType;
103    use crate::dtype::FieldNames;
104    use crate::dtype::Nullability;
105    use crate::dtype::PType;
106    use crate::validity::Validity;
107
108    #[rstest]
109    #[case(create_test_struct(false))]
110    #[case(create_test_struct(true))]
111    #[case(create_nested_struct())]
112    #[case(create_simple_struct())]
113    fn test_cast_struct_conformance(#[case] array: StructArray) {
114        test_cast_conformance(&array.into_array());
115    }
116
117    fn create_test_struct(nullable: bool) -> StructArray {
118        let names = FieldNames::from(["a", "b"]);
119
120        let a = buffer![1i32, 2, 3].into_array();
121        let b = VarBinArray::from_iter(
122            vec![Some("x"), None, Some("z")],
123            DType::Utf8(Nullability::Nullable),
124        )
125        .into_array();
126
127        StructArray::try_new(
128            names,
129            vec![a, b],
130            3,
131            if nullable {
132                Validity::AllValid
133            } else {
134                Validity::NonNullable
135            },
136        )
137        .unwrap()
138    }
139
140    fn create_nested_struct() -> StructArray {
141        // Create inner struct
142        let inner_names = FieldNames::from(["x", "y"]);
143
144        let x = buffer![1.0f32, 2.0, 3.0].into_array();
145        let y = buffer![4.0f32, 5.0, 6.0].into_array();
146        let inner_struct = StructArray::try_new(inner_names, vec![x, y], 3, Validity::NonNullable)
147            .unwrap()
148            .into_array();
149
150        // Create outer struct with inner struct as a field
151        let outer_names: FieldNames = ["id", "point"].into();
152        // Outer struct would have fields: id (I64) and point (inner struct)
153
154        let ids = buffer![100i64, 200, 300].into_array();
155
156        StructArray::try_new(
157            outer_names,
158            vec![ids, inner_struct],
159            3,
160            Validity::NonNullable,
161        )
162        .unwrap()
163    }
164
165    fn create_simple_struct() -> StructArray {
166        let names = FieldNames::from(["value"]);
167        // Simple struct with a single U8 field
168
169        let values = buffer![42u8].into_array();
170
171        StructArray::try_new(names, vec![values], 1, Validity::NonNullable).unwrap()
172    }
173
174    #[test]
175    fn cast_nullable_all_invalid() {
176        let empty_struct = StructArray::try_new(
177            FieldNames::from(["a"]),
178            vec![PrimitiveArray::new::<i32>(buffer![], Validity::AllInvalid).into_array()],
179            0,
180            Validity::AllInvalid,
181        )
182        .unwrap()
183        .into_array();
184
185        let target_dtype = DType::struct_(
186            [("a", DType::Primitive(PType::I32, Nullability::NonNullable))],
187            Nullability::NonNullable,
188        );
189
190        let result = empty_struct.cast(target_dtype.clone()).unwrap();
191        assert_eq!(result.dtype(), &target_dtype);
192        assert_eq!(result.len(), 0);
193    }
194
195    #[test]
196    fn cast_duplicate_field_names_to_nullable() {
197        let names = FieldNames::from(["a", "a"]);
198        let field1 = buffer![1i32, 2, 3].into_array();
199        let field2 = buffer![10i64, 20, 30].into_array();
200
201        let struct_array =
202            StructArray::try_new(names, vec![field1, field2], 3, Validity::NonNullable).unwrap();
203
204        let target_dtype = struct_array.dtype().as_nullable();
205
206        let result = struct_array
207            .into_array()
208            .cast(target_dtype.clone())
209            .unwrap();
210        assert_eq!(result.dtype(), &target_dtype);
211        assert_eq!(result.len(), 3);
212        assert_eq!(result.to_struct().struct_fields().nfields(), 2);
213    }
214
215    #[test]
216    fn cast_add_fields() {
217        let names = FieldNames::from(["a", "b"]);
218        let field1 = buffer![1i32, 2, 3].into_array();
219        let field2 = buffer![10i64, 20, 30].into_array();
220        let target_dtype = DType::struct_(
221            [
222                ("a", field1.dtype().clone()),
223                ("b", field2.dtype().clone()),
224                (
225                    "c",
226                    DType::Decimal(DecimalDType::new(38, 10), Nullability::Nullable),
227                ),
228            ],
229            Nullability::NonNullable,
230        );
231
232        let struct_array =
233            StructArray::try_new(names, vec![field1, field2], 3, Validity::NonNullable).unwrap();
234
235        let result = struct_array
236            .into_array()
237            .cast(target_dtype.clone())
238            .unwrap();
239        assert_eq!(result.dtype(), &target_dtype);
240        assert_eq!(result.len(), 3);
241        assert_eq!(result.to_struct().struct_fields().nfields(), 3);
242    }
243}