• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 16350502539

17 Jul 2025 04:22PM UTC coverage: 80.836% (-0.7%) from 81.557%
16350502539

Pull #3876

github

web-flow
Merge d8ff9e2c1 into d53d06603
Pull Request #3876: feat[layout]: replace register_splits with a layout splits stream

645 of 692 new or added lines in 17 files covered. (93.21%)

372 existing lines in 117 files now uncovered.

42316 of 52348 relevant lines covered (80.84%)

141734.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.82
/vortex-array/src/arrow/compute/to_arrow/mod.rs
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: Copyright the Vortex contributors
3

4
mod canonical;
5
mod temporal;
6
mod varbin;
7

8
use std::any::Any;
9
use std::sync::LazyLock;
10

11
use arcref::ArcRef;
12
use arrow_array::ArrayRef as ArrowArrayRef;
13
use arrow_schema::DataType;
14
use vortex_dtype::DType;
15
use vortex_dtype::arrow::FromArrowType;
16
use vortex_error::{VortexError, VortexExpect, VortexResult, vortex_bail, vortex_err};
17

18
use crate::Array;
19
use crate::arrow::array::{ArrowArray, ArrowVTable};
20
use crate::compute::{ComputeFn, ComputeFnVTable, InvocationArgs, Kernel, Options, Output};
21
use crate::vtable::VTable;
22

23
/// Convert a Vortex array to an Arrow array with the encoding's preferred `DataType`.
24
///
25
/// For example, a `VarBinArray` will be converted to an Arrow `VarBin` array, instead of the
26
/// canonical `VarBinViewArray`.
27
///
28
/// Warning: do not use this to convert a Vortex [`crate::stream::ArrayStream`] since each array
29
/// may have a different preferred Arrow type. Use [`to_arrow`] instead.
30
pub fn to_arrow_preferred(array: &dyn Array) -> VortexResult<ArrowArrayRef> {
×
31
    to_arrow_opts(array, &ToArrowOptions { arrow_type: None })
×
32
}
×
33

34
/// Convert a Vortex array to an Arrow array of the given type.
35
pub fn to_arrow(array: &dyn Array, arrow_type: &DataType) -> VortexResult<ArrowArrayRef> {
354✔
36
    to_arrow_opts(
354✔
37
        array,
354✔
38
        &ToArrowOptions {
354✔
39
            arrow_type: Some(arrow_type.clone()),
354✔
40
        },
354✔
41
    )
42
}
354✔
43

44
pub fn to_arrow_opts(array: &dyn Array, options: &ToArrowOptions) -> VortexResult<ArrowArrayRef> {
29,017✔
45
    let arrow = TO_ARROW_FN
29,017✔
46
        .invoke(&InvocationArgs {
29,017✔
47
            inputs: &[array.into()],
29,017✔
48
            options,
29,017✔
49
        })?
29,017✔
50
        .unwrap_array()?
29,015✔
51
        .as_opt::<ArrowVTable>()
29,015✔
52
        .ok_or_else(|| vortex_err!("ToArrow compute kernels must return a Vortex ArrowArray"))?
29,015✔
53
        .inner()
29,015✔
54
        .clone();
29,015✔
55

56
    if let Some(arrow_type) = &options.arrow_type {
29,015✔
57
        if arrow.data_type() != arrow_type {
3,810✔
58
            vortex_bail!(
×
59
                "Arrow array type mismatch: expected {:?}, got {:?}",
×
60
                &options.arrow_type,
×
61
                arrow.data_type()
×
62
            );
63
        }
3,810✔
64
    }
25,205✔
65

66
    Ok(arrow)
29,015✔
67
}
29,017✔
68

69
pub struct ToArrowOptions {
70
    /// The Arrow data type to convert to, if specified.
71
    pub arrow_type: Option<DataType>,
72
}
73

74
impl Options for ToArrowOptions {
75
    fn as_any(&self) -> &dyn Any {
139,970✔
76
        self
139,970✔
77
    }
139,970✔
78
}
79

80
struct ToArrow;
81

82
impl ComputeFnVTable for ToArrow {
83
    fn invoke(
29,017✔
84
        &self,
29,017✔
85
        args: &InvocationArgs,
29,017✔
86
        kernels: &[ArcRef<dyn Kernel>],
29,017✔
87
    ) -> VortexResult<Output> {
29,017✔
88
        let ToArrowArgs { array, arrow_type } = ToArrowArgs::try_from(args)?;
29,017✔
89

90
        for kernel in kernels {
63,168✔
91
            if let Some(output) = kernel.invoke(args)? {
52,919✔
92
                return Ok(output);
18,766✔
93
            }
34,151✔
94
        }
95
        if let Some(output) = array.invoke(&TO_ARROW_FN, args)? {
10,249✔
96
            return Ok(output);
×
97
        }
10,249✔
98

99
        // Fall back to canonicalizing and then converting.
100
        if !array.is_canonical() {
10,249✔
101
            let canonical_array = array.to_canonical()?;
10,249✔
102
            let arrow_array = to_arrow_opts(
10,249✔
103
                canonical_array.as_ref(),
10,249✔
104
                &ToArrowOptions {
10,249✔
105
                    arrow_type: arrow_type.cloned(),
10,249✔
106
                },
10,249✔
UNCOV
107
            )?;
×
108
            return Ok(ArrowArray::new(arrow_array, array.dtype().nullability())
10,249✔
109
                .to_array()
10,249✔
110
                .into());
10,249✔
111
        }
×
112

113
        vortex_bail!(
×
114
            "Failed to convert array {} to Arrow {:?}",
×
115
            array.encoding_id(),
×
116
            arrow_type
117
        );
118
    }
29,017✔
119

120
    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
29,017✔
121
        let ToArrowArgs { array, arrow_type } = ToArrowArgs::try_from(args)?;
29,017✔
122
        Ok(arrow_type
29,017✔
123
            .map(|arrow_type| DType::from_arrow((arrow_type, array.dtype().nullability())))
29,017✔
124
            .unwrap_or_else(|| array.dtype().clone()))
29,017✔
125
    }
29,017✔
126

127
    fn return_len(&self, args: &InvocationArgs) -> VortexResult<usize> {
29,017✔
128
        let ToArrowArgs { array, .. } = ToArrowArgs::try_from(args)?;
29,017✔
129
        Ok(array.len())
29,017✔
130
    }
29,017✔
131

132
    fn is_elementwise(&self) -> bool {
29,017✔
133
        false
29,017✔
134
    }
29,017✔
135
}
136

137
pub static TO_ARROW_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
3,196✔
138
    let compute = ComputeFn::new("to_arrow".into(), ArcRef::new_ref(&ToArrow));
3,196✔
139

140
    // Register the kernels we ship ourselves
141
    compute.register_kernel(ArcRef::new_ref(&canonical::ToArrowCanonical));
3,196✔
142
    compute.register_kernel(ArcRef::new_ref(&temporal::ToArrowTemporal));
3,196✔
143

144
    for kernel in inventory::iter::<ToArrowKernelRef> {
6,392✔
145
        compute.register_kernel(kernel.0.clone());
3,196✔
146
    }
3,196✔
147
    compute
3,196✔
148
});
3,196✔
149

150
pub struct ToArrowArgs<'a> {
151
    array: &'a dyn Array,
152
    arrow_type: Option<&'a DataType>,
153
}
154

155
impl<'a> TryFrom<&InvocationArgs<'a>> for ToArrowArgs<'a> {
156
    type Error = VortexError;
157

158
    fn try_from(value: &InvocationArgs<'a>) -> Result<Self, Self::Error> {
139,970✔
159
        if value.inputs.len() != 1 {
139,970✔
160
            vortex_bail!("Expected 1 input, found {}", value.inputs.len());
×
161
        }
139,970✔
162
        let array = value.inputs[0]
139,970✔
163
            .array()
139,970✔
164
            .ok_or_else(|| vortex_err!("Expected input 0 to be an array"))?;
139,970✔
165
        let options = value
139,970✔
166
            .options
139,970✔
167
            .as_any()
139,970✔
168
            .downcast_ref::<ToArrowOptions>()
139,970✔
169
            .vortex_expect("Expected options to be ToArrowOptions");
139,970✔
170

171
        Ok(ToArrowArgs {
139,970✔
172
            array,
139,970✔
173
            arrow_type: options.arrow_type.as_ref(),
139,970✔
174
        })
139,970✔
175
    }
139,970✔
176
}
177

178
pub struct ToArrowKernelRef(pub ArcRef<dyn Kernel>);
179
inventory::collect!(ToArrowKernelRef);
180

181
pub trait ToArrowKernel: VTable {
182
    fn to_arrow(
183
        &self,
184
        arr: &Self::Array,
185
        arrow_type: Option<&DataType>,
186
    ) -> VortexResult<Option<ArrowArrayRef>>;
187
}
188

189
#[derive(Debug)]
190
pub struct ToArrowKernelAdapter<V: VTable>(pub V);
191

192
impl<V: VTable + ToArrowKernel> ToArrowKernelAdapter<V> {
193
    pub const fn lift(&'static self) -> ToArrowKernelRef {
×
194
        ToArrowKernelRef(ArcRef::new_ref(self))
×
195
    }
×
196
}
197

198
impl<V: VTable + ToArrowKernel> Kernel for ToArrowKernelAdapter<V> {
199
    fn invoke(&self, args: &InvocationArgs) -> VortexResult<Option<Output>> {
11,936✔
200
        let inputs = ToArrowArgs::try_from(args)?;
11,936✔
201
        let Some(array) = inputs.array.as_opt::<V>() else {
11,936✔
202
            return Ok(None);
10,177✔
203
        };
204

205
        let Some(arrow_array) = V::to_arrow(&self.0, array, inputs.arrow_type)? else {
1,759✔
206
            return Ok(None);
72✔
207
        };
208

209
        Ok(Some(
1,687✔
210
            ArrowArray::new(arrow_array, array.dtype().nullability())
1,687✔
211
                .to_array()
1,687✔
212
                .into(),
1,687✔
213
        ))
1,687✔
214
    }
11,936✔
215
}
216

217
#[cfg(test)]
218
mod tests {
219
    use std::sync::Arc;
220

221
    use arrow_array::types::Int32Type;
222
    use arrow_array::{ArrayRef, PrimitiveArray, StringViewArray, StructArray};
223
    use arrow_buffer::NullBuffer;
224

225
    use super::to_arrow;
226
    use crate::{IntoArray, arrays};
227

228
    #[test]
229
    fn test_to_arrow() {
1✔
230
        let array = arrays::StructArray::from_fields(
1✔
231
            vec![
1✔
232
                (
1✔
233
                    "a",
1✔
234
                    arrays::PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2)])
1✔
235
                        .into_array(),
1✔
236
                ),
1✔
237
                (
1✔
238
                    "b",
1✔
239
                    arrays::VarBinViewArray::from_iter_str(vec!["a", "b", "c"]).into_array(),
1✔
240
                ),
1✔
241
            ]
1✔
242
            .as_slice(),
1✔
243
        )
244
        .unwrap();
1✔
245

246
        let arrow_array: ArrayRef = Arc::new(
1✔
247
            StructArray::try_from(vec![
1✔
248
                (
1✔
249
                    "a",
1✔
250
                    Arc::new(PrimitiveArray::<Int32Type>::from_iter_values_with_nulls(
1✔
251
                        vec![1, 0, 2],
1✔
252
                        Some(NullBuffer::from(vec![true, false, true])),
1✔
253
                    )) as ArrayRef,
1✔
254
                ),
1✔
255
                (
1✔
256
                    "b",
1✔
257
                    Arc::new(StringViewArray::from(vec![Some("a"), Some("b"), Some("c")])),
1✔
258
                ),
1✔
259
            ])
1✔
260
            .unwrap(),
1✔
261
        );
1✔
262

263
        assert_eq!(
1✔
264
            &to_arrow(array.as_ref(), &array.dtype().to_arrow_dtype().unwrap()).unwrap(),
1✔
265
            &arrow_array
1✔
266
        );
267
    }
1✔
268
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc