forked from vortex-data/vortex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct_.rs
More file actions
410 lines (371 loc) · 13.5 KB
/
Copy pathstruct_.rs
File metadata and controls
410 lines (371 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
use std::sync::Arc;
use arrow_array::ArrayRef as ArrowArrayRef;
use arrow_array::StructArray as ArrowStructArray;
use arrow_buffer::NullBuffer;
use arrow_schema::Field;
use arrow_schema::Fields;
use itertools::Itertools;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure;
use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::arrays::Chunked;
use crate::arrays::ScalarFnVTable;
use crate::arrays::Struct;
use crate::arrays::StructArray;
use crate::arrays::scalar_fn::ScalarFnArrayExt;
use crate::arrays::struct_::StructDataParts;
use crate::arrow::ArrowArrayExecutor;
use crate::arrow::executor::validity::to_arrow_null_buffer;
use crate::builtins::ArrayBuiltins;
use crate::dtype::DType;
use crate::dtype::FieldNames;
use crate::dtype::StructFields;
use crate::dtype::arrow::FromArrowType;
use crate::scalar_fn::fns::pack::Pack;
pub(super) fn to_arrow_struct(
array: ArrayRef,
target_fields: Option<&Fields>,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
let len = array.len();
// If the array is chunked, then we invert the chunk-of-struct to struct-of-chunk.
let array = match array.try_downcast::<Chunked>() {
Ok(array) => {
// NOTE(ngates): this currently uses the old into_canonical code path, but we should
// just call directly into the swizzle-chunks function.
array.into_array().execute::<StructArray>(ctx)?.into_array()
}
Err(array) => array,
};
// Attempt to short-circuit if the array is already a Struct and the target
// fields match (same count). When target_fields has fewer fields (e.g., due
// to nested field pruning), we skip the fast path and fall through to the
// cast path which can handle field selection.
let array = match array.try_downcast::<Struct>() {
Ok(array) => {
let n_struct_fields = match array.dtype() {
DType::Struct(sf, _) => sf.nfields(),
_ => 0,
};
// Skip the fast path only when target has strictly fewer fields
// (nested field pruning). When target has same or more fields,
// use the fast path which will validate the count.
let can_fast_path = match target_fields {
None => true,
Some(fields) => fields.len() >= n_struct_fields,
};
if can_fast_path {
let StructDataParts {
validity,
fields,
struct_fields,
..
} = array.into_data_parts();
let validity = to_arrow_null_buffer(validity, len, ctx)?;
return create_from_fields(
target_fields.ok_or_else(|| struct_fields.names().clone()),
&fields,
validity,
len,
ctx,
);
}
// Field count mismatch — fall through to cast path.
array.into_array()
}
Err(array) => array,
};
// We can also short-circuit if the array is a `pack` scalar function:
if let Some(array) = array.as_opt::<ScalarFnVTable>()
&& let Some(_pack_options) = array.scalar_fn().as_opt::<Pack>()
{
let DType::Struct(struct_fields, _) = array.dtype() else {
unreachable!("Pack must have Struct dtype");
};
return create_from_fields(
target_fields.ok_or_else(|| struct_fields.names().clone()),
&array.children(),
None, // Pack is never null,
len,
ctx,
);
}
// Otherwise, we fall back to executing to a StructArray.
let array = if let Some(fields) = target_fields {
let vx_fields = StructFields::from_arrow(fields);
// We apply a cast to ensure we push down casting where possible into the struct fields.
array.cast(DType::Struct(
vx_fields,
crate::dtype::Nullability::Nullable,
))?
} else {
array
};
let struct_array = array.execute::<StructArray>(ctx)?;
let StructDataParts {
validity,
fields,
struct_fields,
..
} = struct_array.into_data_parts();
let validity = to_arrow_null_buffer(validity, len, ctx)?;
create_from_fields(
target_fields.ok_or_else(|| struct_fields.names().clone()),
&fields,
validity,
len,
ctx,
)
}
fn create_from_fields(
fields: Result<&Fields, FieldNames>,
vortex_fields: &[ArrayRef],
null_buffer: Option<NullBuffer>,
len: usize,
ctx: &mut ExecutionCtx,
) -> VortexResult<ArrowArrayRef> {
match fields {
Ok(fields) => {
vortex_ensure!(
vortex_fields.len() == fields.len(),
"StructArray has {} fields, but target Arrow type has {} fields",
vortex_fields.len(),
fields.len()
);
let mut arrow_arrays = Vec::with_capacity(vortex_fields.len());
for (field, vx_field) in fields.iter().zip_eq(vortex_fields.iter()) {
let arrow_field = vx_field
.clone()
.execute_arrow(Some(field.data_type()), ctx)?;
vortex_ensure!(
field.is_nullable() || arrow_field.null_count() == 0,
"Cannot convert field '{}' to non-nullable Arrow field because it contains nulls",
field.name()
);
arrow_arrays.push(arrow_field);
}
Ok(Arc::new(unsafe {
ArrowStructArray::new_unchecked_with_length(
fields.clone(),
arrow_arrays,
null_buffer,
len,
)
}))
}
Err(names) => {
// No target fields specified - use preferred types for each child
let mut arrow_arrays = Vec::with_capacity(vortex_fields.len());
for vx_field in vortex_fields.iter() {
let arrow_array = vx_field.clone().execute_arrow(None, ctx)?;
arrow_arrays.push(arrow_array);
}
// Build the Arrow fields from the resulting arrays
let arrow_fields: Fields = names
.iter()
.zip_eq(arrow_arrays.iter())
.zip_eq(vortex_fields.iter().map(|f| f.dtype().is_nullable()))
.map(|((name, arr), vx_nullable)| {
Arc::new(Field::new(
name.as_ref(),
arr.data_type().clone(),
vx_nullable,
))
})
.collect();
Ok(Arc::new(unsafe {
ArrowStructArray::new_unchecked_with_length(
arrow_fields,
arrow_arrays,
null_buffer,
len,
)
}))
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use arrow_array::ArrayRef;
use arrow_array::PrimitiveArray as ArrowPrimitiveArray;
use arrow_array::StringViewArray;
use arrow_array::StructArray as ArrowStructArray;
use arrow_array::types::Int32Type;
use arrow_buffer::NullBuffer;
use arrow_schema::DataType;
use arrow_schema::Field;
use vortex_buffer::buffer;
use vortex_error::VortexResult;
use crate::IntoArray;
use crate::LEGACY_SESSION;
use crate::VortexSessionExecute;
use crate::array;
use crate::arrays;
use crate::arrays::PrimitiveArray;
use crate::arrays::StructArray;
use crate::arrow::ArrowArrayExecutor;
use crate::arrow::FromArrowArray;
use crate::arrow::IntoArrowArray;
use crate::dtype::FieldNames;
use crate::validity::Validity;
#[test]
fn struct_nullable_non_null_to_arrow() -> VortexResult<()> {
let xs = PrimitiveArray::new(buffer![0i64, 1, 2, 3, 4], Validity::AllValid);
let struct_a = StructArray::try_new(
FieldNames::from(["xs"]),
vec![xs.into_array()],
5,
Validity::AllValid,
)?;
let fields = vec![Field::new("xs", DataType::Int64, false)];
let arrow_dt = DataType::Struct(fields.into());
struct_a.into_array().into_arrow(&arrow_dt)?;
Ok(())
}
#[test]
fn struct_nullable_with_nulls_to_arrow() -> VortexResult<()> {
let xs =
PrimitiveArray::from_option_iter(vec![Some(0_i64), Some(1), Some(2), None, Some(3)]);
let struct_a = StructArray::try_new(
FieldNames::from(["xs"]),
vec![xs.into_array()],
5,
Validity::AllValid,
)?;
let fields = vec![Field::new("xs", DataType::Int64, false)];
let arrow_dt = DataType::Struct(fields.into());
assert!(struct_a.into_array().into_arrow(&arrow_dt).is_err());
Ok(())
}
#[test]
fn struct_to_arrow_with_schema_mismatch() -> VortexResult<()> {
let xs = PrimitiveArray::new(buffer![0i64, 1, 2, 3, 4], Validity::AllValid);
let struct_a = StructArray::try_new(
FieldNames::from(["xs"]),
vec![xs.into_array()],
5,
Validity::AllValid,
)?;
let fields = vec![
Field::new("xs", DataType::Int8, false),
Field::new("ys", DataType::Int64, false),
];
let arrow_dt = DataType::Struct(fields.into());
let err = struct_a.into_array().into_arrow(&arrow_dt).err().unwrap();
assert!(
err.to_string()
.contains("StructArray has 1 fields, but target Arrow type has 2 fields")
);
Ok(())
}
#[test]
fn test_to_arrow() -> VortexResult<()> {
let array = StructArray::from_fields(
vec![
(
"a",
PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2)]).into_array(),
),
(
"b",
arrays::varbinview::VarBinViewArray::from_iter_str(vec!["a", "b", "c"])
.into_array(),
),
]
.as_slice(),
)?;
let arrow_array: ArrayRef = Arc::new(ArrowStructArray::try_from(vec![
(
"a",
Arc::new(
ArrowPrimitiveArray::<Int32Type>::from_iter_values_with_nulls(
vec![1, 0, 2],
Some(NullBuffer::from(vec![true, false, true])),
),
) as ArrayRef,
),
(
"b",
Arc::new(StringViewArray::from(vec![Some("a"), Some("b"), Some("c")])),
),
])?);
let arrow_dtype = array.dtype().to_arrow_dtype()?;
assert_eq!(
&array.into_array().execute_arrow(
Some(&arrow_dtype),
&mut LEGACY_SESSION.create_execution_ctx()
)?,
&arrow_array
);
Ok(())
}
/// Test that converting a struct to Arrow with fewer target fields (field
/// pruning) works by falling through to the cast path.
#[test]
fn struct_to_arrow_with_field_pruning() -> VortexResult<()> {
let array = StructArray::from_fields(
vec![
(
"a",
PrimitiveArray::new(buffer![1i32, 2, 3], Validity::AllValid).into_array(),
),
(
"b",
arrays::varbinview::VarBinViewArray::from_iter_str(vec!["x", "y", "z"])
.into_array(),
),
(
"c",
PrimitiveArray::new(buffer![10i64, 20, 30], Validity::AllValid).into_array(),
),
]
.as_slice(),
)?;
// Request only field "b" — fewer fields than the struct has.
let target_fields = vec![Field::new("b", DataType::Utf8View, true)];
let arrow_dt = DataType::Struct(target_fields.into());
let result = array.into_array().into_arrow(&arrow_dt)?;
let struct_arr = result
.as_any()
.downcast_ref::<ArrowStructArray>()
.expect("should be a StructArray");
assert_eq!(struct_arr.num_columns(), 1);
assert_eq!(struct_arr.column_names(), vec!["b"]);
let col = struct_arr
.column(0)
.as_any()
.downcast_ref::<StringViewArray>()
.expect("should be StringViewArray");
assert_eq!(col.value(0), "x");
assert_eq!(col.value(1), "y");
assert_eq!(col.value(2), "z");
Ok(())
}
#[test]
fn to_arrow_with_non_nullable_fields() -> VortexResult<()> {
let array = StructArray::from_fields(
vec![
(
"a",
PrimitiveArray::from_option_iter(vec![Some(1), None, Some(2)]).into_array(),
),
(
"b",
arrays::varbinview::VarBinViewArray::from_iter_str(vec!["a", "b", "c"])
.into_array(),
),
]
.as_slice(),
)?;
let orig_dtype = array.dtype().clone();
let arrow_array = array.into_array().into_arrow_preferred()?;
let from_arrow = array::ArrayRef::from_arrow(arrow_array.as_ref(), false)?;
assert_eq!(&orig_dtype, from_arrow.dtype());
Ok(())
}
}