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

vortex-data / vortex / 16831295910

08 Aug 2025 01:12PM UTC coverage: 84.935% (+0.9%) from 83.993%
16831295910

Pull #4155

github

web-flow
Merge 678cf8a5b into 0e62b585f
Pull Request #4155: chore[bench-website]: add back tpc-ds to query_bench

50657 of 59642 relevant lines covered (84.94%)

568262.85 hits per line

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

88.74
/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
static TO_ARROW_FN: LazyLock<ComputeFn> = LazyLock::new(|| {
10,290✔
24
    let compute = ComputeFn::new("to_arrow".into(), ArcRef::new_ref(&ToArrow));
10,290✔
25

26
    // Register the kernels we ship ourselves
27
    compute.register_kernel(ArcRef::new_ref(&canonical::ToArrowCanonical));
10,290✔
28
    compute.register_kernel(ArcRef::new_ref(&temporal::ToArrowTemporal));
10,290✔
29

30
    for kernel in inventory::iter::<ToArrowKernelRef> {
20,580✔
31
        compute.register_kernel(kernel.0.clone());
10,290✔
32
    }
10,290✔
33
    compute
10,290✔
34
});
10,290✔
35

36
/// Convert a Vortex array to an Arrow array with the encoding's preferred `DataType`.
37
///
38
/// For example, a `VarBinArray` will be converted to an Arrow `VarBin` array, instead of the
39
/// canonical `VarBinViewArray`.
40
///
41
/// Warning: do not use this to convert a Vortex [`crate::stream::ArrayStream`] since each array
42
/// may have a different preferred Arrow type. Use [`to_arrow`] instead.
43
pub fn to_arrow_preferred(array: &dyn Array) -> VortexResult<ArrowArrayRef> {
×
44
    to_arrow_opts(array, &ToArrowOptions { arrow_type: None })
×
45
}
×
46

47
/// Convert a Vortex array to an Arrow array of the given type.
48
pub fn to_arrow(array: &dyn Array, arrow_type: &DataType) -> VortexResult<ArrowArrayRef> {
1,436✔
49
    to_arrow_opts(
1,436✔
50
        array,
1,436✔
51
        &ToArrowOptions {
1,436✔
52
            arrow_type: Some(arrow_type.clone()),
1,436✔
53
        },
1,436✔
54
    )
55
}
1,436✔
56

57
pub fn to_arrow_opts(array: &dyn Array, options: &ToArrowOptions) -> VortexResult<ArrowArrayRef> {
518,446✔
58
    let arrow = TO_ARROW_FN
518,446✔
59
        .invoke(&InvocationArgs {
518,446✔
60
            inputs: &[array.into()],
518,446✔
61
            options,
518,446✔
62
        })?
518,446✔
63
        .unwrap_array()?
518,444✔
64
        .as_opt::<ArrowVTable>()
518,444✔
65
        .ok_or_else(|| vortex_err!("ToArrow compute kernels must return a Vortex ArrowArray"))?
518,444✔
66
        .inner()
518,444✔
67
        .clone();
518,444✔
68

69
    if let Some(arrow_type) = &options.arrow_type
518,444✔
70
        && arrow.data_type() != arrow_type
21,450✔
71
    {
72
        vortex_bail!(
×
73
            "Arrow array type mismatch: expected {:?}, got {:?}",
×
74
            &options.arrow_type,
×
75
            arrow.data_type()
×
76
        );
77
    }
518,444✔
78

79
    Ok(arrow)
518,444✔
80
}
518,446✔
81

82
pub struct ToArrowOptions {
83
    /// The Arrow data type to convert to, if specified.
84
    pub arrow_type: Option<DataType>,
85
}
86

87
impl Options for ToArrowOptions {
88
    fn as_any(&self) -> &dyn Any {
2,526,548✔
89
        self
2,526,548✔
90
    }
2,526,548✔
91
}
92

93
struct ToArrow;
94

95
impl ComputeFnVTable for ToArrow {
96
    fn invoke(
518,446✔
97
        &self,
518,446✔
98
        args: &InvocationArgs,
518,446✔
99
        kernels: &[ArcRef<dyn Kernel>],
518,446✔
100
    ) -> VortexResult<Output> {
518,446✔
101
        let ToArrowArgs { array, arrow_type } = ToArrowArgs::try_from(args)?;
518,446✔
102

103
        for kernel in kernels {
1,194,822✔
104
            if let Some(output) = kernel.invoke(args)? {
971,210✔
105
                return Ok(output);
294,832✔
106
            }
676,376✔
107
        }
108
        if let Some(output) = array.invoke(&TO_ARROW_FN, args)? {
223,612✔
109
            return Ok(output);
×
110
        }
223,612✔
111

112
        // Fall back to canonicalizing and then converting.
113
        if !array.is_canonical() {
223,612✔
114
            let canonical_array = array.to_canonical()?;
223,612✔
115
            let arrow_array = to_arrow_opts(
223,612✔
116
                canonical_array.as_ref(),
223,612✔
117
                &ToArrowOptions {
223,612✔
118
                    arrow_type: arrow_type.cloned(),
223,612✔
119
                },
223,612✔
120
            )?;
×
121
            return Ok(ArrowArray::new(arrow_array, array.dtype().nullability())
223,612✔
122
                .to_array()
223,612✔
123
                .into());
223,612✔
124
        }
×
125

126
        vortex_bail!(
×
127
            "Failed to convert array {} to Arrow {:?}",
×
128
            array.encoding_id(),
×
129
            arrow_type
130
        );
131
    }
518,446✔
132

133
    fn return_dtype(&self, args: &InvocationArgs) -> VortexResult<DType> {
518,446✔
134
        let ToArrowArgs { array, arrow_type } = ToArrowArgs::try_from(args)?;
518,446✔
135
        Ok(arrow_type
518,446✔
136
            .map(|arrow_type| DType::from_arrow((arrow_type, array.dtype().nullability())))
518,446✔
137
            .unwrap_or_else(|| array.dtype().clone()))
518,446✔
138
    }
518,446✔
139

140
    fn return_len(&self, args: &InvocationArgs) -> VortexResult<usize> {
518,446✔
141
        let ToArrowArgs { array, .. } = ToArrowArgs::try_from(args)?;
518,446✔
142
        Ok(array.len())
518,446✔
143
    }
518,446✔
144

145
    fn is_elementwise(&self) -> bool {
518,446✔
146
        false
518,446✔
147
    }
518,446✔
148
}
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> {
2,526,548✔
159
        if value.inputs.len() != 1 {
2,526,548✔
160
            vortex_bail!("Expected 1 input, found {}", value.inputs.len());
×
161
        }
2,526,548✔
162
        let array = value.inputs[0]
2,526,548✔
163
            .array()
2,526,548✔
164
            .ok_or_else(|| vortex_err!("Expected input 0 to be an array"))?;
2,526,548✔
165
        let options = value
2,526,548✔
166
            .options
2,526,548✔
167
            .as_any()
2,526,548✔
168
            .downcast_ref::<ToArrowOptions>()
2,526,548✔
169
            .vortex_expect("Expected options to be ToArrowOptions");
2,526,548✔
170

171
        Ok(ToArrowArgs {
2,526,548✔
172
            array,
2,526,548✔
173
            arrow_type: options.arrow_type.as_ref(),
2,526,548✔
174
        })
2,526,548✔
175
    }
2,526,548✔
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>> {
226,292✔
200
        let inputs = ToArrowArgs::try_from(args)?;
226,292✔
201
        let Some(array) = inputs.array.as_opt::<V>() else {
226,292✔
202
            return Ok(None);
223,534✔
203
        };
204

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

209
        Ok(Some(
2,680✔
210
            ArrowArray::new(arrow_array, array.dtype().nullability())
2,680✔
211
                .to_array()
2,680✔
212
                .into(),
2,680✔
213
        ))
2,680✔
214
    }
226,292✔
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