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

vortex-data / vortex / 16593958537

29 Jul 2025 10:48AM UTC coverage: 82.285% (+0.5%) from 81.796%
16593958537

Pull #4036

github

web-flow
Merge 04147cb0f into 348079fc3
Pull Request #4036: varbinview builder buffer deduplication

146 of 154 new or added lines in 2 files covered. (94.81%)

348 existing lines in 26 files now uncovered.

44470 of 54044 relevant lines covered (82.28%)

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

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

30
    for kernel in inventory::iter::<ToArrowKernelRef> {
7,276✔
31
        compute.register_kernel(kernel.0.clone());
3,638✔
32
    }
3,638✔
33
    compute
3,638✔
34
});
3,638✔
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.
UNCOV
43
pub fn to_arrow_preferred(array: &dyn Array) -> VortexResult<ArrowArrayRef> {
×
UNCOV
44
    to_arrow_opts(array, &ToArrowOptions { arrow_type: None })
×
UNCOV
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> {
978✔
49
    to_arrow_opts(
978✔
50
        array,
978✔
51
        &ToArrowOptions {
978✔
52
            arrow_type: Some(arrow_type.clone()),
978✔
53
        },
978✔
54
    )
55
}
978✔
56

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

69
    if let Some(arrow_type) = &options.arrow_type {
48,182✔
70
        if arrow.data_type() != arrow_type {
11,380✔
UNCOV
71
            vortex_bail!(
×
UNCOV
72
                "Arrow array type mismatch: expected {:?}, got {:?}",
×
UNCOV
73
                &options.arrow_type,
×
UNCOV
74
                arrow.data_type()
×
75
            );
76
        }
11,380✔
77
    }
36,802✔
78

79
    Ok(arrow)
48,182✔
80
}
48,184✔
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 {
230,654✔
89
        self
230,654✔
90
    }
230,654✔
91
}
92

93
struct ToArrow;
94

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

103
        for kernel in kernels {
103,296✔
104
            if let Some(output) = kernel.invoke(args)? {
86,102✔
105
                return Ok(output);
30,988✔
106
            }
55,112✔
107
        }
108
        if let Some(output) = array.invoke(&TO_ARROW_FN, args)? {
17,194✔
UNCOV
109
            return Ok(output);
×
110
        }
17,194✔
111

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

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

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

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

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

171
        Ok(ToArrowArgs {
230,654✔
172
            array,
230,654✔
173
            arrow_type: options.arrow_type.as_ref(),
230,654✔
174
        })
230,654✔
175
    }
230,654✔
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>> {
18,899✔
200
        let inputs = ToArrowArgs::try_from(args)?;
18,899✔
201
        let Some(array) = inputs.array.as_opt::<V>() else {
18,899✔
202
            return Ok(None);
17,118✔
203
        };
204

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

209
        Ok(Some(
1,705✔
210
            ArrowArray::new(arrow_array, array.dtype().nullability())
1,705✔
211
                .to_array()
1,705✔
212
                .into(),
1,705✔
213
        ))
1,705✔
214
    }
18,899✔
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