-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathvariant_get.rs
More file actions
4472 lines (3936 loc) · 177 KB
/
variant_get.rs
File metadata and controls
4472 lines (3936 loc) · 177 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use arrow::{
array::{self, Array, ArrayRef, BinaryViewArray, StructArray, make_array},
buffer::NullBuffer,
compute::CastOptions,
datatypes::Field,
error::Result,
};
use arrow_schema::{ArrowError, DataType, FieldRef};
use parquet_variant::{VariantPath, VariantPathElement};
use crate::VariantArray;
use crate::variant_array::BorrowedShreddingState;
use crate::variant_to_arrow::make_variant_to_arrow_row_builder;
use arrow::array::AsArray;
use std::sync::Arc;
pub(crate) enum ShreddedPathStep<'a> {
/// Path step succeeded, return the new shredding state
Success(BorrowedShreddingState<'a>),
/// The path element is not present in the `typed_value` column and there is no `value` column,
/// so we know it does not exist. It, and all paths under it, are all-NULL.
Missing,
/// The path element is not present in the `typed_value` column and must be retrieved from the `value`
/// column instead. The caller should be prepared to handle any value, including the requested
/// type, an arbitrary "wrong" type, or `Variant::Null`.
NotShredded,
}
/// Given a shredded variant field -- a `(value?, typed_value?)` pair -- try to take one path step
/// deeper. For a `VariantPathElement::Field`, if there is no `typed_value` at this level, if
/// `typed_value` is not a struct, or if the requested field name does not exist, traversal returns
/// a missing-path step (`Missing` or `NotShredded` depending on whether `value` exists).
///
/// TODO: Support `VariantPathElement::Index`? It wouldn't be easy, and maybe not even possible.
pub(crate) fn follow_shredded_path_element<'a>(
shredding_state: &BorrowedShreddingState<'a>,
path_element: &VariantPathElement<'_>,
_cast_options: &CastOptions,
) -> Result<ShreddedPathStep<'a>> {
// If the requested path element is not present in `typed_value`, and `value` is missing, then
// we know it does not exist; it, and all paths under it, are all-NULL.
let missing_path_step = || match shredding_state.value_field() {
Some(_) => ShreddedPathStep::NotShredded,
None => ShreddedPathStep::Missing,
};
let Some(typed_value) = shredding_state.typed_value_field() else {
return Ok(missing_path_step());
};
match path_element {
VariantPathElement::Field { name } => {
// Try to step into the requested field name of a struct.
// First, try to downcast to StructArray
let Some(struct_array) = typed_value.as_any().downcast_ref::<StructArray>() else {
// Object field path step follows JSONPath semantics and returns missing path step (NotShredded/Missing) on non-struct path
return Ok(missing_path_step());
};
// Now try to find the column - missing column in a present struct is just missing data
let Some(field) = struct_array.column_by_name(name) else {
// Missing column in a present struct is just missing, not wrong - return Ok
return Ok(missing_path_step());
};
let struct_array = field.as_struct_opt().ok_or_else(|| {
// TODO: Should we blow up? Or just end the traversal and let the normal
// variant pathing code sort out the mess that it must anyway be
// prepared to handle?
ArrowError::InvalidArgumentError(format!(
"Expected Struct array while following path, got {}",
field.data_type(),
))
})?;
let state = BorrowedShreddingState::try_from(struct_array)?;
Ok(ShreddedPathStep::Success(state))
}
VariantPathElement::Index { .. } => {
// TODO: Support array indexing. Among other things, it will require slicing not
// only the array we have here, but also the corresponding metadata and null masks.
Err(ArrowError::NotYetImplemented(
"Pathing into shredded variant array index".into(),
))
}
}
}
/// Follows the given path as far as possible through shredded variant fields. If the path ends on a
/// shredded field, return it directly. Otherwise, use a row shredder to follow the rest of the path
/// and extract the requested value on a per-row basis.
fn shredded_get_path(
input: &VariantArray,
path: &[VariantPathElement<'_>],
as_field: Option<&Field>,
cast_options: &CastOptions,
) -> Result<ArrayRef> {
// Helper that creates a new VariantArray from the given nested value and typed_value columns,
// properly accounting for accumulated nulls from path traversal
let make_target_variant =
|value: Option<BinaryViewArray>,
typed_value: Option<ArrayRef>,
accumulated_nulls: Option<arrow::buffer::NullBuffer>| {
let metadata = input.metadata_field().clone();
VariantArray::from_parts(metadata, value, typed_value, accumulated_nulls)
};
// Helper that shreds a VariantArray to a specific type.
let shred_basic_variant =
|target: VariantArray, path: VariantPath<'_>, as_field: Option<&Field>| {
let as_type = as_field.map(|f| f.data_type());
let mut builder = make_variant_to_arrow_row_builder(
target.metadata_field(),
path,
as_type,
cast_options,
target.len(),
)?;
for i in 0..target.len() {
if target.is_null(i) {
builder.append_null()?;
} else if !cast_options.safe {
let value = target.try_value(i)?;
builder.append_value(value)?;
} else {
let _ = match target.try_value(i) {
Ok(v) => builder.append_value(v)?,
Err(_) => {
builder.append_null()?;
false // add this to make match arms have the same return type
}
};
}
}
builder.finish()
};
// Peel away the prefix of path elements that traverses the shredded parts of this variant
// column. Shredding will traverse the rest of the path on a per-row basis.
let mut shredding_state = input.shredding_state().borrow();
let mut accumulated_nulls = input.inner().nulls().cloned();
let mut path_index = 0;
for path_element in path {
match follow_shredded_path_element(&shredding_state, path_element, cast_options)? {
ShreddedPathStep::Success(state) => {
// Union nulls from the typed_value we just accessed
if let Some(typed_value) = shredding_state.typed_value_field() {
accumulated_nulls = arrow::buffer::NullBuffer::union(
accumulated_nulls.as_ref(),
typed_value.nulls(),
);
}
shredding_state = state;
path_index += 1;
continue;
}
ShreddedPathStep::Missing => {
let num_rows = input.len();
let arr = match as_field.map(|f| f.data_type()) {
Some(data_type) => array::new_null_array(data_type, num_rows),
None => Arc::new(array::NullArray::new(num_rows)) as _,
};
return Ok(arr);
}
ShreddedPathStep::NotShredded => {
let target = make_target_variant(
shredding_state.value_field().cloned(),
None,
accumulated_nulls,
);
return shred_basic_variant(target, path[path_index..].into(), as_field);
}
};
}
// Path exhausted! Create a new `VariantArray` for the location we landed on.
let target = make_target_variant(
shredding_state.value_field().cloned(),
shredding_state.typed_value_field().cloned(),
accumulated_nulls,
);
// If our caller did not request any specific type, we can just return whatever we landed on.
let Some(as_field) = as_field else {
return Ok(ArrayRef::from(target));
};
// Try to return the typed value directly when we have a perfect shredding match.
if let Some(shredded) = try_perfect_shredding(&target, as_field) {
return Ok(shredded);
}
// Structs are special.
//
// For fully unshredded targets (`typed_value` absent), delegate to the row builder so we
// preserve struct-level cast semantics:
// - safe mode: non-object rows become NULL structs
// - strict mode: non-object rows raise a cast error
//
// For shredded/partially-shredded targets (`typed_value` present), recurse into each field
// separately to take advantage of deeper shredding in child fields.
if let DataType::Struct(fields) = as_field.data_type() {
if target.typed_value_field().is_none() {
return shred_basic_variant(target, VariantPath::default(), Some(as_field));
}
let children = fields
.iter()
.map(|field| {
shredded_get_path(
&target,
&[VariantPathElement::from(field.name().as_str())],
Some(field),
cast_options,
)
})
.collect::<Result<Vec<_>>>()?;
let struct_nulls = target.nulls().cloned();
return Ok(Arc::new(StructArray::try_new(
fields.clone(),
children,
struct_nulls,
)?));
}
// Not a struct, so directly shred the variant as the requested type
shred_basic_variant(target, VariantPath::default(), Some(as_field))
}
fn try_perfect_shredding(variant_array: &VariantArray, as_field: &Field) -> Option<ArrayRef> {
// Try to return the typed value directly when we have a perfect shredding match.
if matches!(as_field.data_type(), DataType::Struct(_)) {
return None;
}
let typed_value = variant_array.typed_value_field()?;
if typed_value.data_type() == as_field.data_type()
&& variant_array
.value_field()
.is_none_or(|v| v.null_count() == v.len())
{
// Here we need to gate against the case where the `typed_value` is null but data is in the `value` column.
// 1. If the `value` column is null, or
// 2. If every row in the `value` column is null
// This is a perfect shredding, where the value is entirely shredded out,
// so we can just return the typed value after merging the accumulated nulls.
let parent_nulls = variant_array.nulls();
// If we have no nulls OR the shredded array is `Null`, which doesn't support external nulls.
let target_array = if parent_nulls.is_none() || typed_value.data_type().is_null() {
typed_value.clone()
} else {
let merged_nulls = NullBuffer::union(parent_nulls, typed_value.nulls());
let data = typed_value
.to_data()
.into_builder()
.nulls(merged_nulls)
.build()
.ok()?;
make_array(data)
};
return Some(target_array);
}
None
}
/// Returns an array with the specified path extracted from the variant values.
///
/// The return array type depends on the `as_type` field of the options parameter
/// 1. `as_type: None`: a VariantArray is returned. The values in this new VariantArray will point
/// to the specified path.
/// 2. `as_type: Some(<specific field>)`: an array of the specified type is returned.
///
/// TODO: How would a caller request a struct or list type where the fields/elements can be any
/// variant? Caller can pass None as the requested type to fetch a specific path, but it would
/// quickly become annoying (and inefficient) to call `variant_get` for each leaf value in a struct or
/// list and then try to assemble the results.
pub fn variant_get(input: &ArrayRef, options: GetOptions) -> Result<ArrayRef> {
let variant_array = VariantArray::try_new(input)?;
let GetOptions {
as_type,
path,
cast_options,
} = options;
shredded_get_path(&variant_array, &path, as_type.as_deref(), &cast_options)
}
/// Controls the action of the variant_get kernel.
#[derive(Debug, Clone, Default)]
pub struct GetOptions<'a> {
/// What path to extract
pub path: VariantPath<'a>,
/// if `as_type` is None, the returned array will itself be a VariantArray.
///
/// if `as_type` is `Some(type)` the field is returned as the specified type.
pub as_type: Option<FieldRef>,
/// Controls the casting behavior (e.g. error vs substituting null on cast error).
pub cast_options: CastOptions<'a>,
}
impl<'a> GetOptions<'a> {
/// Construct default options to get the specified path as a variant.
pub fn new() -> Self {
Default::default()
}
/// Construct options to get the specified path as a variant.
pub fn new_with_path(path: VariantPath<'a>) -> Self {
Self {
path,
as_type: None,
cast_options: Default::default(),
}
}
/// Specify the type to return.
pub fn with_as_type(mut self, as_type: Option<FieldRef>) -> Self {
self.as_type = as_type;
self
}
/// Specify the cast options to use when casting to the specified type.
pub fn with_cast_options(mut self, cast_options: CastOptions<'a>) -> Self {
self.cast_options = cast_options;
self
}
}
#[cfg(test)]
mod test {
use std::str::FromStr;
use std::sync::Arc;
use super::{GetOptions, variant_get};
use crate::variant_array::{ShreddedVariantFieldArray, StructArrayBuilder};
use crate::{
VariantArray, VariantArrayBuilder, cast_to_variant, json_to_variant, shred_variant,
};
use arrow::array::{
Array, ArrayRef, AsArray, BinaryArray, BinaryViewArray, BooleanArray, Date32Array,
Date64Array, Decimal32Array, Decimal64Array, Decimal128Array, Decimal256Array,
Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array,
LargeBinaryArray, LargeListArray, LargeListViewArray, LargeStringArray, ListArray,
ListViewArray, NullArray, NullBuilder, StringArray, StringViewArray, StructArray,
Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray,
};
use arrow::buffer::{NullBuffer, OffsetBuffer, ScalarBuffer};
use arrow::compute::CastOptions;
use arrow::datatypes::DataType::{Int16, Int32, Int64};
use arrow::datatypes::i256;
use arrow::util::display::FormatOptions;
use arrow_schema::DataType::{Boolean, Float32, Float64, Int8};
use arrow_schema::{DataType, Field, FieldRef, Fields, IntervalUnit, TimeUnit};
use chrono::DateTime;
use parquet_variant::{
EMPTY_VARIANT_METADATA_BYTES, Variant, VariantDecimal4, VariantDecimal8, VariantDecimal16,
VariantDecimalType, VariantPath,
};
fn single_variant_get_test(input_json: &str, path: VariantPath, expected_json: &str) {
// Create input array from JSON string
let input_array_ref: ArrayRef = Arc::new(StringArray::from(vec![Some(input_json)]));
let input_variant_array_ref = ArrayRef::from(json_to_variant(&input_array_ref).unwrap());
let result =
variant_get(&input_variant_array_ref, GetOptions::new_with_path(path)).unwrap();
// Create expected array from JSON string
let expected_array_ref: ArrayRef = Arc::new(StringArray::from(vec![Some(expected_json)]));
let expected_variant_array = json_to_variant(&expected_array_ref).unwrap();
let result_array = VariantArray::try_new(&result).unwrap();
assert_eq!(
result_array.len(),
1,
"Expected result array to have length 1"
);
assert!(
result_array.nulls().is_none(),
"Expected no nulls in result array"
);
let result_variant = result_array.value(0);
let expected_variant = expected_variant_array.value(0);
assert_eq!(
result_variant, expected_variant,
"Result variant does not match expected variant"
);
}
#[test]
fn get_primitive_variant_field() {
single_variant_get_test(
r#"{"some_field": 1234}"#,
VariantPath::try_from("some_field").unwrap(),
"1234",
);
}
#[test]
fn get_primitive_variant_list_index() {
single_variant_get_test("[1234, 5678]", VariantPath::from(0), "1234");
}
#[test]
fn get_primitive_variant_inside_object_of_object() {
single_variant_get_test(
r#"{"top_level_field": {"inner_field": 1234}}"#,
VariantPath::try_from("top_level_field")
.unwrap()
.join("inner_field"),
"1234",
);
}
#[test]
fn get_primitive_variant_inside_list_of_object() {
single_variant_get_test(
r#"[{"some_field": 1234}]"#,
VariantPath::from(0).join("some_field"),
"1234",
);
}
#[test]
fn get_primitive_variant_inside_object_of_list() {
single_variant_get_test(
r#"{"some_field": [1234]}"#,
VariantPath::try_from("some_field").unwrap().join(0),
"1234",
);
}
#[test]
fn get_complex_variant() {
single_variant_get_test(
r#"{"top_level_field": {"inner_field": 1234}}"#,
VariantPath::try_from("top_level_field").unwrap(),
r#"{"inner_field": 1234}"#,
);
}
/// Partial Shredding: extract a value as a VariantArray
macro_rules! numeric_partially_shredded_test {
($primitive_type:ty, $data_fn:ident) => {
let array = $data_fn();
let options = GetOptions::new();
let result = variant_get(&array, options).unwrap();
// expect the result is a VariantArray
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), 4);
// Expect the values are the same as the original values
assert_eq!(
result.value(0),
Variant::from(<$primitive_type>::try_from(34u8).unwrap())
);
assert!(!result.is_valid(1));
assert_eq!(result.value(2), Variant::from("n/a"));
assert_eq!(
result.value(3),
Variant::from(<$primitive_type>::try_from(100u8).unwrap())
);
};
}
/// Build a mixed input [typed, null, fallback, typed] and let shred_variant
/// generate the shredded fixture for the requested type.
macro_rules! partially_shredded_variant_array_gen {
($func_name:ident, $typed_value_array_gen: expr) => {
partially_shredded_variant_array_gen!(
$func_name,
$typed_value_array_gen,
Variant::from("n/a")
);
};
($func_name:ident, $typed_value_array_gen: expr, $fallback_variant:expr) => {
fn $func_name() -> ArrayRef {
let typed_value: ArrayRef = Arc::new($typed_value_array_gen());
let typed_as_variant = cast_to_variant(typed_value.as_ref())
.expect("should cast typed array to variant");
let mut input_builder = VariantArrayBuilder::new(typed_as_variant.len());
input_builder.append_variant(typed_as_variant.value(0));
input_builder.append_null();
input_builder.append_variant($fallback_variant);
input_builder.append_variant(typed_as_variant.value(3));
let variant_array = shred_variant(&input_builder.build(), typed_value.data_type())
.expect("should shred variant array");
ArrayRef::from(variant_array)
}
};
}
// Fixture definitions grouped with the partially-shredded tests.
macro_rules! numeric_partially_shredded_variant_array_fn {
($func:ident, $array_type:ident, $primitive_type:ty) => {
partially_shredded_variant_array_gen!($func, || $array_type::from(vec![
Some(<$primitive_type>::try_from(34u8).unwrap()),
None,
None,
Some(<$primitive_type>::try_from(100u8).unwrap()),
]));
};
}
numeric_partially_shredded_variant_array_fn!(
partially_shredded_int8_variant_array,
Int8Array,
i8
);
numeric_partially_shredded_variant_array_fn!(
partially_shredded_int16_variant_array,
Int16Array,
i16
);
numeric_partially_shredded_variant_array_fn!(
partially_shredded_int32_variant_array,
Int32Array,
i32
);
numeric_partially_shredded_variant_array_fn!(
partially_shredded_int64_variant_array,
Int64Array,
i64
);
numeric_partially_shredded_variant_array_fn!(
partially_shredded_float32_variant_array,
Float32Array,
f32
);
numeric_partially_shredded_variant_array_fn!(
partially_shredded_float64_variant_array,
Float64Array,
f64
);
partially_shredded_variant_array_gen!(partially_shredded_bool_variant_array, || {
arrow::array::BooleanArray::from(vec![Some(true), None, None, Some(false)])
});
partially_shredded_variant_array_gen!(
partially_shredded_utf8_variant_array,
|| { StringArray::from(vec![Some("hello"), None, None, Some("world")]) },
Variant::from(42i32)
);
partially_shredded_variant_array_gen!(partially_shredded_date32_variant_array, || {
Date32Array::from(vec![
Some(20348), // 2025-09-17
None,
None,
Some(20340), // 2025-09-09
])
});
#[test]
fn get_variant_partially_shredded_int8_as_variant() {
numeric_partially_shredded_test!(i8, partially_shredded_int8_variant_array);
}
#[test]
fn get_variant_partially_shredded_int16_as_variant() {
numeric_partially_shredded_test!(i16, partially_shredded_int16_variant_array);
}
#[test]
fn get_variant_partially_shredded_int32_as_variant() {
numeric_partially_shredded_test!(i32, partially_shredded_int32_variant_array);
}
#[test]
fn get_variant_partially_shredded_int64_as_variant() {
numeric_partially_shredded_test!(i64, partially_shredded_int64_variant_array);
}
#[test]
fn get_variant_partially_shredded_float32_as_variant() {
numeric_partially_shredded_test!(f32, partially_shredded_float32_variant_array);
}
#[test]
fn get_variant_partially_shredded_float64_as_variant() {
numeric_partially_shredded_test!(f64, partially_shredded_float64_variant_array);
}
#[test]
fn get_variant_partially_shredded_bool_as_variant() {
let array = partially_shredded_bool_variant_array();
let options = GetOptions::new();
let result = variant_get(&array, options).unwrap();
// expect the result is a VariantArray
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), 4);
// Expect the values are the same as the original values
assert_eq!(result.value(0), Variant::from(true));
assert!(!result.is_valid(1));
assert_eq!(result.value(2), Variant::from("n/a"));
assert_eq!(result.value(3), Variant::from(false));
}
#[test]
fn get_variant_partially_shredded_utf8_as_variant() {
let array = partially_shredded_utf8_variant_array();
let options = GetOptions::new();
let result = variant_get(&array, options).unwrap();
// expect the result is a VariantArray
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), 4);
// Expect the values are the same as the original values
assert_eq!(result.value(0), Variant::from("hello"));
assert!(!result.is_valid(1));
assert_eq!(result.value(2), Variant::from(42i32));
assert_eq!(result.value(3), Variant::from("world"));
}
partially_shredded_variant_array_gen!(partially_shredded_binary_view_variant_array, || {
BinaryViewArray::from(vec![
Some(&[1u8, 2u8, 3u8][..]), // row 0 is shredded
None, // row 1 is null
None, // row 2 is a string
Some(&[4u8, 5u8, 6u8][..]), // row 3 is shredded
])
});
#[test]
fn get_variant_partially_shredded_date32_as_variant() {
let array = partially_shredded_date32_variant_array();
let options = GetOptions::new();
let result = variant_get(&array, options).unwrap();
// expect the result is a VariantArray
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), 4);
// Expect the values are the same as the original values
use chrono::NaiveDate;
let date1 = NaiveDate::from_ymd_opt(2025, 9, 17).unwrap();
let date2 = NaiveDate::from_ymd_opt(2025, 9, 9).unwrap();
assert_eq!(result.value(0), Variant::from(date1));
assert!(!result.is_valid(1));
assert_eq!(result.value(2), Variant::from("n/a"));
assert_eq!(result.value(3), Variant::from(date2));
}
#[test]
fn get_variant_partially_shredded_binary_view_as_variant() {
let array = partially_shredded_binary_view_variant_array();
let options = GetOptions::new();
let result = variant_get(&array, options).unwrap();
// expect the result is a VariantArray
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), 4);
// Expect the values are the same as the original values
assert_eq!(result.value(0), Variant::from(&[1u8, 2u8, 3u8][..]));
assert!(!result.is_valid(1));
assert_eq!(result.value(2), Variant::from("n/a"));
assert_eq!(result.value(3), Variant::from(&[4u8, 5u8, 6u8][..]));
}
// Timestamp partially-shredded tests grouped with the other partially-shredded cases.
macro_rules! assert_variant_get_as_variant_array_with_default_option {
($variant_array: expr, $array_expected: expr) => {{
let options = GetOptions::new();
let array = $variant_array;
let result = variant_get(&array, options).unwrap();
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), $array_expected.len());
for (idx, item) in $array_expected.into_iter().enumerate() {
match item {
Some(item) => assert_eq!(result.value(idx), item),
None => assert!(result.is_null(idx)),
}
}
}};
}
partially_shredded_variant_array_gen!(
partially_shredded_timestamp_micro_ntz_variant_array,
|| {
arrow::array::TimestampMicrosecondArray::from(vec![
Some(-456000),
None,
None,
Some(1758602096000000),
])
}
);
#[test]
fn get_variant_partial_shredded_timestamp_micro_ntz_as_variant() {
let array = partially_shredded_timestamp_micro_ntz_variant_array();
assert_variant_get_as_variant_array_with_default_option!(
array,
vec![
Some(Variant::from(
DateTime::from_timestamp_micros(-456000i64)
.unwrap()
.naive_utc(),
)),
None,
Some(Variant::from("n/a")),
Some(Variant::from(
DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
.unwrap()
.naive_utc(),
)),
]
)
}
partially_shredded_variant_array_gen!(partially_shredded_timestamp_micro_variant_array, || {
arrow::array::TimestampMicrosecondArray::from(vec![
Some(-456000),
None,
None,
Some(1758602096000000),
])
.with_timezone("+00:00")
});
#[test]
fn get_variant_partial_shredded_timestamp_micro_as_variant() {
let array = partially_shredded_timestamp_micro_variant_array();
assert_variant_get_as_variant_array_with_default_option!(
array,
vec![
Some(Variant::from(
DateTime::from_timestamp_micros(-456000i64)
.unwrap()
.to_utc(),
)),
None,
Some(Variant::from("n/a")),
Some(Variant::from(
DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
.unwrap()
.to_utc(),
)),
]
)
}
partially_shredded_variant_array_gen!(
partially_shredded_timestamp_nano_ntz_variant_array,
|| {
arrow::array::TimestampNanosecondArray::from(vec![
Some(-4999999561),
None,
None,
Some(1758602096000000000),
])
}
);
#[test]
fn get_variant_partial_shredded_timestamp_nano_ntz_as_variant() {
let array = partially_shredded_timestamp_nano_ntz_variant_array();
assert_variant_get_as_variant_array_with_default_option!(
array,
vec![
Some(Variant::from(
DateTime::from_timestamp(-5, 439).unwrap().naive_utc()
)),
None,
Some(Variant::from("n/a")),
Some(Variant::from(
DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
.unwrap()
.naive_utc()
)),
]
)
}
partially_shredded_variant_array_gen!(partially_shredded_timestamp_nano_variant_array, || {
arrow::array::TimestampNanosecondArray::from(vec![
Some(-4999999561),
None,
None,
Some(1758602096000000000),
])
.with_timezone("+00:00")
});
#[test]
fn get_variant_partial_shredded_timestamp_nano_as_variant() {
let array = partially_shredded_timestamp_nano_variant_array();
assert_variant_get_as_variant_array_with_default_option!(
array,
vec![
Some(Variant::from(
DateTime::from_timestamp(-5, 439).unwrap().to_utc()
)),
None,
Some(Variant::from("n/a")),
Some(Variant::from(
DateTime::parse_from_rfc3339("2025-09-23T12:34:56+08:00")
.unwrap()
.to_utc()
)),
]
)
}
/// Shredding: extract a value as an Int32Array
#[test]
fn get_variant_shredded_int32_as_int32_safe_cast() {
// Extract the typed value as Int32Array
let array = partially_shredded_int32_variant_array();
// specify we want the typed value as Int32
let field = Field::new("typed_value", DataType::Int32, true);
let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
let result = variant_get(&array, options).unwrap();
let expected: ArrayRef = Arc::new(Int32Array::from(vec![
Some(34),
None,
None, // "n/a" is not an Int32 so converted to null
Some(100),
]));
assert_eq!(&result, &expected)
}
/// Shredding: extract a value as an Int32Array, unsafe cast (should error on "n/a")
#[test]
fn get_variant_shredded_int32_as_int32_unsafe_cast() {
// Extract the typed value as Int32Array
let array = partially_shredded_int32_variant_array();
let field = Field::new("typed_value", DataType::Int32, true);
let cast_options = CastOptions {
safe: false, // unsafe cast
..Default::default()
};
let options = GetOptions::new()
.with_as_type(Some(FieldRef::from(field)))
.with_cast_options(cast_options);
let err = variant_get(&array, options).unwrap_err();
// TODO make this error message nicer (not Debug format)
assert_eq!(
err.to_string(),
"Cast error: Failed to extract primitive of type Int32 from variant ShortString(ShortString(\"n/a\")) at path VariantPath([])"
);
}
/// Perfect Shredding: extract the typed value as a VariantArray
macro_rules! numeric_perfectly_shredded_test {
($primitive_type:ty, $data_fn:ident) => {
let array = $data_fn();
let options = GetOptions::new();
let result = variant_get(&array, options).unwrap();
// expect the result is a VariantArray
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), 3);
// Expect the values are the same as the original values
assert_eq!(
result.value(0),
Variant::from(<$primitive_type>::try_from(1u8).unwrap())
);
assert_eq!(
result.value(1),
Variant::from(<$primitive_type>::try_from(2u8).unwrap())
);
assert_eq!(
result.value(2),
Variant::from(<$primitive_type>::try_from(3u8).unwrap())
);
};
}
#[test]
fn get_variant_perfectly_shredded_int8_as_variant() {
numeric_perfectly_shredded_test!(i8, perfectly_shredded_int8_variant_array);
}
#[test]
fn get_variant_perfectly_shredded_int16_as_variant() {
numeric_perfectly_shredded_test!(i16, perfectly_shredded_int16_variant_array);
}
#[test]
fn get_variant_perfectly_shredded_int32_as_variant() {
numeric_perfectly_shredded_test!(i32, perfectly_shredded_int32_variant_array);
}
#[test]
fn get_variant_perfectly_shredded_int64_as_variant() {
numeric_perfectly_shredded_test!(i64, perfectly_shredded_int64_variant_array);
}
#[test]
fn get_variant_perfectly_shredded_float32_as_variant() {
numeric_perfectly_shredded_test!(f32, perfectly_shredded_float32_variant_array);
}
#[test]
fn get_variant_perfectly_shredded_float64_as_variant() {
numeric_perfectly_shredded_test!(f64, perfectly_shredded_float64_variant_array);
}
/// AllNull: extract a value as a VariantArray
#[test]
fn get_variant_all_null_as_variant() {
let array = all_null_variant_array();
let options = GetOptions::new();
let result = variant_get(&array, options).unwrap();
// expect the result is a VariantArray
let result = VariantArray::try_new(&result).unwrap();
assert_eq!(result.len(), 3);
// All values should be null
assert!(!result.is_valid(0));
assert!(!result.is_valid(1));
assert!(!result.is_valid(2));
}
/// AllNull: extract a value as an Int32Array
#[test]
fn get_variant_all_null_as_int32() {
let array = all_null_variant_array();
// specify we want the typed value as Int32
let field = Field::new("typed_value", DataType::Int32, true);
let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
let result = variant_get(&array, options).unwrap();
let expected: ArrayRef = Arc::new(Int32Array::from(vec![
Option::<i32>::None,
Option::<i32>::None,
Option::<i32>::None,
]));
assert_eq!(&result, &expected)
}
macro_rules! perfectly_shredded_to_arrow_primitive_test {
($name:ident, $primitive_type:expr, $perfectly_shredded_array_gen_fun:ident, $expected_array:expr) => {
#[test]
fn $name() {
let array = $perfectly_shredded_array_gen_fun();
let field = Field::new("typed_value", $primitive_type, true);
let options = GetOptions::new().with_as_type(Some(FieldRef::from(field)));
let result = variant_get(&array, options).unwrap();
let expected_array: ArrayRef = Arc::new($expected_array);
assert_eq!(&result, &expected_array);
}
};
}
perfectly_shredded_to_arrow_primitive_test!(
get_variant_perfectly_shredded_int18_as_int8,
Int8,
perfectly_shredded_int8_variant_array,
Int8Array::from(vec![Some(1), Some(2), Some(3)])
);
perfectly_shredded_to_arrow_primitive_test!(
get_variant_perfectly_shredded_int16_as_int16,
Int16,
perfectly_shredded_int16_variant_array,
Int16Array::from(vec![Some(1), Some(2), Some(3)])
);
perfectly_shredded_to_arrow_primitive_test!(
get_variant_perfectly_shredded_int32_as_int32,
Int32,
perfectly_shredded_int32_variant_array,
Int32Array::from(vec![Some(1), Some(2), Some(3)])
);