forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
5901 lines (5501 loc) · 222 KB
/
mod.rs
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.
//! [`ScalarValue`]: stores single values
mod struct_builder;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::{HashSet, VecDeque};
use std::convert::{Infallible, TryFrom, TryInto};
use std::fmt;
use std::hash::Hash;
use std::iter::repeat;
use std::str::FromStr;
use std::sync::Arc;
use crate::cast::{
as_decimal128_array, as_decimal256_array, as_dictionary_array,
as_fixed_size_binary_array, as_fixed_size_list_array,
};
use crate::error::{DataFusionError, Result, _internal_err, _not_impl_err};
use crate::hash_utils::create_hashes;
use crate::utils::{
array_into_fixed_size_list_array, array_into_large_list_array, array_into_list_array,
};
use arrow::compute::kernels::numeric::*;
use arrow::util::display::{array_value_to_string, ArrayFormatter, FormatOptions};
use arrow::{
array::*,
compute::kernels::cast::{cast_with_options, CastOptions},
datatypes::{
i256, ArrowDictionaryKeyType, ArrowNativeType, ArrowTimestampType, DataType,
Field, Float32Type, Int16Type, Int32Type, Int64Type, Int8Type,
IntervalDayTimeType, IntervalMonthDayNanoType, IntervalUnit,
IntervalYearMonthType, TimeUnit, TimestampMicrosecondType,
TimestampMillisecondType, TimestampNanosecondType, TimestampSecondType,
UInt16Type, UInt32Type, UInt64Type, UInt8Type, DECIMAL128_MAX_PRECISION,
},
};
use arrow_array::{ArrowNativeTypeOp, Scalar};
pub use struct_builder::ScalarStructBuilder;
/// A dynamically typed, nullable single value.
///
/// While an arrow [`Array`]) stores one or more values of the same type, in a
/// single column, a `ScalarValue` stores a single value of a single type, the
/// equivalent of 1 row and one column.
///
/// ```text
/// ┌────────┐
/// │ value1 │
/// │ value2 │ ┌────────┐
/// │ value3 │ │ value2 │
/// │ ... │ └────────┘
/// │ valueN │
/// └────────┘
///
/// Array ScalarValue
///
/// stores multiple, stores a single,
/// possibly null, values of possible null, value
/// the same type
/// ```
///
/// # Performance
///
/// In general, performance will be better using arrow [`Array`]s rather than
/// [`ScalarValue`], as it is far more efficient to process multiple values at
/// once (vectorized processing).
///
/// # Example
/// ```
/// # use datafusion_common::ScalarValue;
/// // Create single scalar value for an Int32 value
/// let s1 = ScalarValue::Int32(Some(10));
///
/// // You can also create values using the From impl:
/// let s2 = ScalarValue::from(10i32);
/// assert_eq!(s1, s2);
/// ```
///
/// # Null Handling
///
/// `ScalarValue` represents null values in the same way as Arrow. Nulls are
/// "typed" in the sense that a null value in an [`Int32Array`] is different
/// than a null value in a [`Float64Array`], and is different than the values in
/// a [`NullArray`].
///
/// ```
/// # fn main() -> datafusion_common::Result<()> {
/// # use std::collections::hash_set::Difference;
/// # use datafusion_common::ScalarValue;
/// # use arrow::datatypes::DataType;
/// // You can create a 'null' Int32 value directly:
/// let s1 = ScalarValue::Int32(None);
///
/// // You can also create a null value for a given datatype:
/// let s2 = ScalarValue::try_from(&DataType::Int32)?;
/// assert_eq!(s1, s2);
///
/// // Note that this is DIFFERENT than a `ScalarValue::Null`
/// let s3 = ScalarValue::Null;
/// assert_ne!(s1, s3);
/// # Ok(())
/// # }
/// ```
///
/// # Nested Types
///
/// `List` / `LargeList` / `FixedSizeList` / `Struct` are represented as a
/// single element array of the corresponding type.
///
/// ## Example: Creating [`ScalarValue::Struct`] using [`ScalarStructBuilder`]
/// ```
/// # use std::sync::Arc;
/// # use arrow::datatypes::{DataType, Field};
/// # use datafusion_common::{ScalarValue, scalar::ScalarStructBuilder};
/// // Build a struct like: {a: 1, b: "foo"}
/// let field_a = Field::new("a", DataType::Int32, false);
/// let field_b = Field::new("b", DataType::Utf8, false);
///
/// let s1 = ScalarStructBuilder::new()
/// .with_scalar(field_a, ScalarValue::from(1i32))
/// .with_scalar(field_b, ScalarValue::from("foo"))
/// .build();
/// ```
///
/// ## Example: Creating a null [`ScalarValue::Struct`] using [`ScalarStructBuilder`]
/// ```
/// # use std::sync::Arc;
/// # use arrow::datatypes::{DataType, Field};
/// # use datafusion_common::{ScalarValue, scalar::ScalarStructBuilder};
/// // Build a struct representing a NULL value
/// let fields = vec![
/// Field::new("a", DataType::Int32, false),
/// Field::new("b", DataType::Utf8, false),
/// ];
///
/// let s1 = ScalarStructBuilder::new_null(fields);
/// ```
///
/// ## Example: Creating [`ScalarValue::Struct`] directly
/// ```
/// # use std::sync::Arc;
/// # use arrow::datatypes::{DataType, Field, Fields};
/// # use arrow_array::{ArrayRef, Int32Array, StructArray, StringArray};
/// # use datafusion_common::ScalarValue;
/// // Build a struct like: {a: 1, b: "foo"}
/// // Field description
/// let fields = Fields::from(vec![
/// Field::new("a", DataType::Int32, false),
/// Field::new("b", DataType::Utf8, false),
/// ]);
/// // one row arrays for each field
/// let arrays: Vec<ArrayRef> = vec![
/// Arc::new(Int32Array::from(vec![1])),
/// Arc::new(StringArray::from(vec!["foo"])),
/// ];
/// // no nulls for this array
/// let nulls = None;
/// let arr = StructArray::new(fields, arrays, nulls);
///
/// // Create a ScalarValue::Struct directly
/// let s1 = ScalarValue::Struct(Arc::new(arr));
/// ```
///
///
/// # Further Reading
/// See [datatypes](https://arrow.apache.org/docs/python/api/datatypes.html) for
/// details on datatypes and the [format](https://github.com/apache/arrow/blob/master/format/Schema.fbs#L354-L375)
/// for the definitive reference.
#[derive(Clone)]
pub enum ScalarValue {
/// represents `DataType::Null` (castable to/from any other type)
Null,
/// true or false value
Boolean(Option<bool>),
/// 32bit float
Float32(Option<f32>),
/// 64bit float
Float64(Option<f64>),
/// 128bit decimal, using the i128 to represent the decimal, precision scale
Decimal128(Option<i128>, u8, i8),
/// 256bit decimal, using the i256 to represent the decimal, precision scale
Decimal256(Option<i256>, u8, i8),
/// signed 8bit int
Int8(Option<i8>),
/// signed 16bit int
Int16(Option<i16>),
/// signed 32bit int
Int32(Option<i32>),
/// signed 64bit int
Int64(Option<i64>),
/// unsigned 8bit int
UInt8(Option<u8>),
/// unsigned 16bit int
UInt16(Option<u16>),
/// unsigned 32bit int
UInt32(Option<u32>),
/// unsigned 64bit int
UInt64(Option<u64>),
/// utf-8 encoded string.
Utf8(Option<String>),
/// utf-8 encoded string representing a LargeString's arrow type.
LargeUtf8(Option<String>),
/// binary
Binary(Option<Vec<u8>>),
/// fixed size binary
FixedSizeBinary(i32, Option<Vec<u8>>),
/// large binary
LargeBinary(Option<Vec<u8>>),
/// Fixed size list scalar.
///
/// The array must be a FixedSizeListArray with length 1.
FixedSizeList(Arc<FixedSizeListArray>),
/// Represents a single element of a [`ListArray`] as an [`ArrayRef`]
///
/// The array must be a ListArray with length 1.
List(Arc<ListArray>),
/// The array must be a LargeListArray with length 1.
LargeList(Arc<LargeListArray>),
/// Represents a single element [`StructArray`] as an [`ArrayRef`]. See
/// [`ScalarValue`] for examples of how to create instances of this type.
Struct(Arc<StructArray>),
/// Date stored as a signed 32bit int days since UNIX epoch 1970-01-01
Date32(Option<i32>),
/// Date stored as a signed 64bit int milliseconds since UNIX epoch 1970-01-01
Date64(Option<i64>),
/// Time stored as a signed 32bit int as seconds since midnight
Time32Second(Option<i32>),
/// Time stored as a signed 32bit int as milliseconds since midnight
Time32Millisecond(Option<i32>),
/// Time stored as a signed 64bit int as microseconds since midnight
Time64Microsecond(Option<i64>),
/// Time stored as a signed 64bit int as nanoseconds since midnight
Time64Nanosecond(Option<i64>),
/// Timestamp Second
TimestampSecond(Option<i64>, Option<Arc<str>>),
/// Timestamp Milliseconds
TimestampMillisecond(Option<i64>, Option<Arc<str>>),
/// Timestamp Microseconds
TimestampMicrosecond(Option<i64>, Option<Arc<str>>),
/// Timestamp Nanoseconds
TimestampNanosecond(Option<i64>, Option<Arc<str>>),
/// Number of elapsed whole months
IntervalYearMonth(Option<i32>),
/// Number of elapsed days and milliseconds (no leap seconds)
/// stored as 2 contiguous 32-bit signed integers
IntervalDayTime(Option<i64>),
/// A triple of the number of elapsed months, days, and nanoseconds.
/// Months and days are encoded as 32-bit signed integers.
/// Nanoseconds is encoded as a 64-bit signed integer (no leap seconds).
IntervalMonthDayNano(Option<i128>),
/// Duration in seconds
DurationSecond(Option<i64>),
/// Duration in milliseconds
DurationMillisecond(Option<i64>),
/// Duration in microseconds
DurationMicrosecond(Option<i64>),
/// Duration in nanoseconds
DurationNanosecond(Option<i64>),
/// Dictionary type: index type and value
Dictionary(Box<DataType>, Box<ScalarValue>),
}
// manual implementation of `PartialEq`
impl PartialEq for ScalarValue {
fn eq(&self, other: &Self) -> bool {
use ScalarValue::*;
// This purposely doesn't have a catch-all "(_, _)" so that
// any newly added enum variant will require editing this list
// or else face a compile error
match (self, other) {
(Decimal128(v1, p1, s1), Decimal128(v2, p2, s2)) => {
v1.eq(v2) && p1.eq(p2) && s1.eq(s2)
}
(Decimal128(_, _, _), _) => false,
(Decimal256(v1, p1, s1), Decimal256(v2, p2, s2)) => {
v1.eq(v2) && p1.eq(p2) && s1.eq(s2)
}
(Decimal256(_, _, _), _) => false,
(Boolean(v1), Boolean(v2)) => v1.eq(v2),
(Boolean(_), _) => false,
(Float32(v1), Float32(v2)) => match (v1, v2) {
(Some(f1), Some(f2)) => f1.to_bits() == f2.to_bits(),
_ => v1.eq(v2),
},
(Float32(_), _) => false,
(Float64(v1), Float64(v2)) => match (v1, v2) {
(Some(f1), Some(f2)) => f1.to_bits() == f2.to_bits(),
_ => v1.eq(v2),
},
(Float64(_), _) => false,
(Int8(v1), Int8(v2)) => v1.eq(v2),
(Int8(_), _) => false,
(Int16(v1), Int16(v2)) => v1.eq(v2),
(Int16(_), _) => false,
(Int32(v1), Int32(v2)) => v1.eq(v2),
(Int32(_), _) => false,
(Int64(v1), Int64(v2)) => v1.eq(v2),
(Int64(_), _) => false,
(UInt8(v1), UInt8(v2)) => v1.eq(v2),
(UInt8(_), _) => false,
(UInt16(v1), UInt16(v2)) => v1.eq(v2),
(UInt16(_), _) => false,
(UInt32(v1), UInt32(v2)) => v1.eq(v2),
(UInt32(_), _) => false,
(UInt64(v1), UInt64(v2)) => v1.eq(v2),
(UInt64(_), _) => false,
(Utf8(v1), Utf8(v2)) => v1.eq(v2),
(Utf8(_), _) => false,
(LargeUtf8(v1), LargeUtf8(v2)) => v1.eq(v2),
(LargeUtf8(_), _) => false,
(Binary(v1), Binary(v2)) => v1.eq(v2),
(Binary(_), _) => false,
(FixedSizeBinary(_, v1), FixedSizeBinary(_, v2)) => v1.eq(v2),
(FixedSizeBinary(_, _), _) => false,
(LargeBinary(v1), LargeBinary(v2)) => v1.eq(v2),
(LargeBinary(_), _) => false,
(FixedSizeList(v1), FixedSizeList(v2)) => v1.eq(v2),
(FixedSizeList(_), _) => false,
(List(v1), List(v2)) => v1.eq(v2),
(List(_), _) => false,
(LargeList(v1), LargeList(v2)) => v1.eq(v2),
(LargeList(_), _) => false,
(Struct(v1), Struct(v2)) => v1.eq(v2),
(Struct(_), _) => false,
(Date32(v1), Date32(v2)) => v1.eq(v2),
(Date32(_), _) => false,
(Date64(v1), Date64(v2)) => v1.eq(v2),
(Date64(_), _) => false,
(Time32Second(v1), Time32Second(v2)) => v1.eq(v2),
(Time32Second(_), _) => false,
(Time32Millisecond(v1), Time32Millisecond(v2)) => v1.eq(v2),
(Time32Millisecond(_), _) => false,
(Time64Microsecond(v1), Time64Microsecond(v2)) => v1.eq(v2),
(Time64Microsecond(_), _) => false,
(Time64Nanosecond(v1), Time64Nanosecond(v2)) => v1.eq(v2),
(Time64Nanosecond(_), _) => false,
(TimestampSecond(v1, _), TimestampSecond(v2, _)) => v1.eq(v2),
(TimestampSecond(_, _), _) => false,
(TimestampMillisecond(v1, _), TimestampMillisecond(v2, _)) => v1.eq(v2),
(TimestampMillisecond(_, _), _) => false,
(TimestampMicrosecond(v1, _), TimestampMicrosecond(v2, _)) => v1.eq(v2),
(TimestampMicrosecond(_, _), _) => false,
(TimestampNanosecond(v1, _), TimestampNanosecond(v2, _)) => v1.eq(v2),
(TimestampNanosecond(_, _), _) => false,
(DurationSecond(v1), DurationSecond(v2)) => v1.eq(v2),
(DurationSecond(_), _) => false,
(DurationMillisecond(v1), DurationMillisecond(v2)) => v1.eq(v2),
(DurationMillisecond(_), _) => false,
(DurationMicrosecond(v1), DurationMicrosecond(v2)) => v1.eq(v2),
(DurationMicrosecond(_), _) => false,
(DurationNanosecond(v1), DurationNanosecond(v2)) => v1.eq(v2),
(DurationNanosecond(_), _) => false,
(IntervalYearMonth(v1), IntervalYearMonth(v2)) => v1.eq(v2),
(IntervalYearMonth(_), _) => false,
(IntervalDayTime(v1), IntervalDayTime(v2)) => v1.eq(v2),
(IntervalDayTime(_), _) => false,
(IntervalMonthDayNano(v1), IntervalMonthDayNano(v2)) => v1.eq(v2),
(IntervalMonthDayNano(_), _) => false,
(Dictionary(k1, v1), Dictionary(k2, v2)) => k1.eq(k2) && v1.eq(v2),
(Dictionary(_, _), _) => false,
(Null, Null) => true,
(Null, _) => false,
}
}
}
// manual implementation of `PartialOrd`
impl PartialOrd for ScalarValue {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
use ScalarValue::*;
// This purposely doesn't have a catch-all "(_, _)" so that
// any newly added enum variant will require editing this list
// or else face a compile error
match (self, other) {
(Decimal128(v1, p1, s1), Decimal128(v2, p2, s2)) => {
if p1.eq(p2) && s1.eq(s2) {
v1.partial_cmp(v2)
} else {
// Two decimal values can be compared if they have the same precision and scale.
None
}
}
(Decimal128(_, _, _), _) => None,
(Decimal256(v1, p1, s1), Decimal256(v2, p2, s2)) => {
if p1.eq(p2) && s1.eq(s2) {
v1.partial_cmp(v2)
} else {
// Two decimal values can be compared if they have the same precision and scale.
None
}
}
(Decimal256(_, _, _), _) => None,
(Boolean(v1), Boolean(v2)) => v1.partial_cmp(v2),
(Boolean(_), _) => None,
(Float32(v1), Float32(v2)) => match (v1, v2) {
(Some(f1), Some(f2)) => Some(f1.total_cmp(f2)),
_ => v1.partial_cmp(v2),
},
(Float32(_), _) => None,
(Float64(v1), Float64(v2)) => match (v1, v2) {
(Some(f1), Some(f2)) => Some(f1.total_cmp(f2)),
_ => v1.partial_cmp(v2),
},
(Float64(_), _) => None,
(Int8(v1), Int8(v2)) => v1.partial_cmp(v2),
(Int8(_), _) => None,
(Int16(v1), Int16(v2)) => v1.partial_cmp(v2),
(Int16(_), _) => None,
(Int32(v1), Int32(v2)) => v1.partial_cmp(v2),
(Int32(_), _) => None,
(Int64(v1), Int64(v2)) => v1.partial_cmp(v2),
(Int64(_), _) => None,
(UInt8(v1), UInt8(v2)) => v1.partial_cmp(v2),
(UInt8(_), _) => None,
(UInt16(v1), UInt16(v2)) => v1.partial_cmp(v2),
(UInt16(_), _) => None,
(UInt32(v1), UInt32(v2)) => v1.partial_cmp(v2),
(UInt32(_), _) => None,
(UInt64(v1), UInt64(v2)) => v1.partial_cmp(v2),
(UInt64(_), _) => None,
(Utf8(v1), Utf8(v2)) => v1.partial_cmp(v2),
(Utf8(_), _) => None,
(LargeUtf8(v1), LargeUtf8(v2)) => v1.partial_cmp(v2),
(LargeUtf8(_), _) => None,
(Binary(v1), Binary(v2)) => v1.partial_cmp(v2),
(Binary(_), _) => None,
(FixedSizeBinary(_, v1), FixedSizeBinary(_, v2)) => v1.partial_cmp(v2),
(FixedSizeBinary(_, _), _) => None,
(LargeBinary(v1), LargeBinary(v2)) => v1.partial_cmp(v2),
(LargeBinary(_), _) => None,
// ScalarValue::List / ScalarValue::FixedSizeList / ScalarValue::LargeList are ensure to have length 1
(List(arr1), List(arr2)) => partial_cmp_list(arr1.as_ref(), arr2.as_ref()),
(FixedSizeList(arr1), FixedSizeList(arr2)) => {
partial_cmp_list(arr1.as_ref(), arr2.as_ref())
}
(LargeList(arr1), LargeList(arr2)) => {
partial_cmp_list(arr1.as_ref(), arr2.as_ref())
}
(List(_), _) | (LargeList(_), _) | (FixedSizeList(_), _) => None,
(Struct(struct_arr1), Struct(struct_arr2)) => {
partial_cmp_struct(struct_arr1, struct_arr2)
}
(Struct(_), _) => None,
(Date32(v1), Date32(v2)) => v1.partial_cmp(v2),
(Date32(_), _) => None,
(Date64(v1), Date64(v2)) => v1.partial_cmp(v2),
(Date64(_), _) => None,
(Time32Second(v1), Time32Second(v2)) => v1.partial_cmp(v2),
(Time32Second(_), _) => None,
(Time32Millisecond(v1), Time32Millisecond(v2)) => v1.partial_cmp(v2),
(Time32Millisecond(_), _) => None,
(Time64Microsecond(v1), Time64Microsecond(v2)) => v1.partial_cmp(v2),
(Time64Microsecond(_), _) => None,
(Time64Nanosecond(v1), Time64Nanosecond(v2)) => v1.partial_cmp(v2),
(Time64Nanosecond(_), _) => None,
(TimestampSecond(v1, _), TimestampSecond(v2, _)) => v1.partial_cmp(v2),
(TimestampSecond(_, _), _) => None,
(TimestampMillisecond(v1, _), TimestampMillisecond(v2, _)) => {
v1.partial_cmp(v2)
}
(TimestampMillisecond(_, _), _) => None,
(TimestampMicrosecond(v1, _), TimestampMicrosecond(v2, _)) => {
v1.partial_cmp(v2)
}
(TimestampMicrosecond(_, _), _) => None,
(TimestampNanosecond(v1, _), TimestampNanosecond(v2, _)) => {
v1.partial_cmp(v2)
}
(TimestampNanosecond(_, _), _) => None,
(IntervalYearMonth(v1), IntervalYearMonth(v2)) => v1.partial_cmp(v2),
(IntervalYearMonth(_), _) => None,
(IntervalDayTime(v1), IntervalDayTime(v2)) => v1.partial_cmp(v2),
(IntervalDayTime(_), _) => None,
(IntervalMonthDayNano(v1), IntervalMonthDayNano(v2)) => v1.partial_cmp(v2),
(IntervalMonthDayNano(_), _) => None,
(DurationSecond(v1), DurationSecond(v2)) => v1.partial_cmp(v2),
(DurationSecond(_), _) => None,
(DurationMillisecond(v1), DurationMillisecond(v2)) => v1.partial_cmp(v2),
(DurationMillisecond(_), _) => None,
(DurationMicrosecond(v1), DurationMicrosecond(v2)) => v1.partial_cmp(v2),
(DurationMicrosecond(_), _) => None,
(DurationNanosecond(v1), DurationNanosecond(v2)) => v1.partial_cmp(v2),
(DurationNanosecond(_), _) => None,
(Dictionary(k1, v1), Dictionary(k2, v2)) => {
// Don't compare if the key types don't match (it is effectively a different datatype)
if k1 == k2 {
v1.partial_cmp(v2)
} else {
None
}
}
(Dictionary(_, _), _) => None,
(Null, Null) => Some(Ordering::Equal),
(Null, _) => None,
}
}
}
/// List/LargeList/FixedSizeList scalars always have a single element
/// array. This function returns that array
fn first_array_for_list(arr: &dyn Array) -> ArrayRef {
assert_eq!(arr.len(), 1);
if let Some(arr) = arr.as_list_opt::<i32>() {
arr.value(0)
} else if let Some(arr) = arr.as_list_opt::<i64>() {
arr.value(0)
} else if let Some(arr) = arr.as_fixed_size_list_opt() {
arr.value(0)
} else {
unreachable!("Since only List / LargeList / FixedSizeList are supported, this should never happen")
}
}
/// Compares two List/LargeList/FixedSizeList scalars
fn partial_cmp_list(arr1: &dyn Array, arr2: &dyn Array) -> Option<Ordering> {
if arr1.data_type() != arr2.data_type() {
return None;
}
let arr1 = first_array_for_list(arr1);
let arr2 = first_array_for_list(arr2);
let lt_res = arrow::compute::kernels::cmp::lt(&arr1, &arr2).ok()?;
let eq_res = arrow::compute::kernels::cmp::eq(&arr1, &arr2).ok()?;
for j in 0..lt_res.len() {
if lt_res.is_valid(j) && lt_res.value(j) {
return Some(Ordering::Less);
}
if eq_res.is_valid(j) && !eq_res.value(j) {
return Some(Ordering::Greater);
}
}
Some(Ordering::Equal)
}
fn partial_cmp_struct(s1: &Arc<StructArray>, s2: &Arc<StructArray>) -> Option<Ordering> {
if s1.len() != s2.len() {
return None;
}
if s1.data_type() != s2.data_type() {
return None;
}
for col_index in 0..s1.num_columns() {
let arr1 = s1.column(col_index);
let arr2 = s2.column(col_index);
let lt_res = arrow::compute::kernels::cmp::lt(arr1, arr2).ok()?;
let eq_res = arrow::compute::kernels::cmp::eq(arr1, arr2).ok()?;
for j in 0..lt_res.len() {
if lt_res.is_valid(j) && lt_res.value(j) {
return Some(Ordering::Less);
}
if eq_res.is_valid(j) && !eq_res.value(j) {
return Some(Ordering::Greater);
}
}
}
Some(Ordering::Equal)
}
impl Eq for ScalarValue {}
//Float wrapper over f32/f64. Just because we cannot build std::hash::Hash for floats directly we have to do it through type wrapper
struct Fl<T>(T);
macro_rules! hash_float_value {
($(($t:ty, $i:ty)),+) => {
$(impl std::hash::Hash for Fl<$t> {
#[inline]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
state.write(&<$i>::from_ne_bytes(self.0.to_ne_bytes()).to_ne_bytes())
}
})+
};
}
hash_float_value!((f64, u64), (f32, u32));
// manual implementation of `Hash`
//
// # Panics
//
// Panics if there is an error when creating hash values for rows
impl std::hash::Hash for ScalarValue {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
use ScalarValue::*;
match self {
Decimal128(v, p, s) => {
v.hash(state);
p.hash(state);
s.hash(state)
}
Decimal256(v, p, s) => {
v.hash(state);
p.hash(state);
s.hash(state)
}
Boolean(v) => v.hash(state),
Float32(v) => v.map(Fl).hash(state),
Float64(v) => v.map(Fl).hash(state),
Int8(v) => v.hash(state),
Int16(v) => v.hash(state),
Int32(v) => v.hash(state),
Int64(v) => v.hash(state),
UInt8(v) => v.hash(state),
UInt16(v) => v.hash(state),
UInt32(v) => v.hash(state),
UInt64(v) => v.hash(state),
Utf8(v) => v.hash(state),
LargeUtf8(v) => v.hash(state),
Binary(v) => v.hash(state),
FixedSizeBinary(_, v) => v.hash(state),
LargeBinary(v) => v.hash(state),
List(arr) => {
hash_nested_array(arr.to_owned() as ArrayRef, state);
}
LargeList(arr) => {
hash_nested_array(arr.to_owned() as ArrayRef, state);
}
FixedSizeList(arr) => {
hash_nested_array(arr.to_owned() as ArrayRef, state);
}
Struct(arr) => {
hash_nested_array(arr.to_owned() as ArrayRef, state);
}
Date32(v) => v.hash(state),
Date64(v) => v.hash(state),
Time32Second(v) => v.hash(state),
Time32Millisecond(v) => v.hash(state),
Time64Microsecond(v) => v.hash(state),
Time64Nanosecond(v) => v.hash(state),
TimestampSecond(v, _) => v.hash(state),
TimestampMillisecond(v, _) => v.hash(state),
TimestampMicrosecond(v, _) => v.hash(state),
TimestampNanosecond(v, _) => v.hash(state),
DurationSecond(v) => v.hash(state),
DurationMillisecond(v) => v.hash(state),
DurationMicrosecond(v) => v.hash(state),
DurationNanosecond(v) => v.hash(state),
IntervalYearMonth(v) => v.hash(state),
IntervalDayTime(v) => v.hash(state),
IntervalMonthDayNano(v) => v.hash(state),
Dictionary(k, v) => {
k.hash(state);
v.hash(state);
}
// stable hash for Null value
Null => 1.hash(state),
}
}
}
fn hash_nested_array<H: std::hash::Hasher>(arr: ArrayRef, state: &mut H) {
let arrays = vec![arr.to_owned()];
let hashes_buffer = &mut vec![0; arr.len()];
let random_state = ahash::RandomState::with_seeds(0, 0, 0, 0);
let hashes = create_hashes(&arrays, &random_state, hashes_buffer).unwrap();
// Hash back to std::hash::Hasher
hashes.hash(state);
}
/// Return a reference to the values array and the index into it for a
/// dictionary array
///
/// # Errors
///
/// Errors if the array cannot be downcasted to DictionaryArray
#[inline]
pub fn get_dict_value<K: ArrowDictionaryKeyType>(
array: &dyn Array,
index: usize,
) -> Result<(&ArrayRef, Option<usize>)> {
let dict_array = as_dictionary_array::<K>(array)?;
Ok((dict_array.values(), dict_array.key(index)))
}
/// Create a dictionary array representing `value` repeated `size`
/// times
fn dict_from_scalar<K: ArrowDictionaryKeyType>(
value: &ScalarValue,
size: usize,
) -> Result<ArrayRef> {
// values array is one element long (the value)
let values_array = value.to_array_of_size(1)?;
// Create a key array with `size` elements, each of 0
let key_array: PrimitiveArray<K> = std::iter::repeat(Some(K::default_value()))
.take(size)
.collect();
// create a new DictionaryArray
//
// Note: this path could be made faster by using the ArrayData
// APIs and skipping validation, if it every comes up in
// performance traces.
Ok(Arc::new(
DictionaryArray::<K>::try_new(key_array, values_array)?, // should always be valid by construction above
))
}
/// Create a dictionary array representing all the values in values
fn dict_from_values<K: ArrowDictionaryKeyType>(
values_array: ArrayRef,
) -> Result<ArrayRef> {
// Create a key array with `size` elements of 0..array_len for all
// non-null value elements
let key_array: PrimitiveArray<K> = (0..values_array.len())
.map(|index| {
if values_array.is_valid(index) {
let native_index = K::Native::from_usize(index).ok_or_else(|| {
DataFusionError::Internal(format!(
"Can not create index of type {} from value {}",
K::DATA_TYPE,
index
))
})?;
Ok(Some(native_index))
} else {
Ok(None)
}
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.collect();
// create a new DictionaryArray
//
// Note: this path could be made faster by using the ArrayData
// APIs and skipping validation, if it every comes up in
// performance traces.
let dict_array = DictionaryArray::<K>::try_new(key_array, values_array)?;
Ok(Arc::new(dict_array))
}
macro_rules! typed_cast_tz {
($array:expr, $index:expr, $ARRAYTYPE:ident, $SCALAR:ident, $TZ:expr) => {{
use std::any::type_name;
let array = $array
.as_any()
.downcast_ref::<$ARRAYTYPE>()
.ok_or_else(|| {
DataFusionError::Internal(format!(
"could not cast value to {}",
type_name::<$ARRAYTYPE>()
))
})?;
Ok::<ScalarValue, DataFusionError>(ScalarValue::$SCALAR(
match array.is_null($index) {
true => None,
false => Some(array.value($index).into()),
},
$TZ.clone(),
))
}};
}
macro_rules! typed_cast {
($array:expr, $index:expr, $ARRAYTYPE:ident, $SCALAR:ident) => {{
use std::any::type_name;
let array = $array
.as_any()
.downcast_ref::<$ARRAYTYPE>()
.ok_or_else(|| {
DataFusionError::Internal(format!(
"could not cast value to {}",
type_name::<$ARRAYTYPE>()
))
})?;
Ok::<ScalarValue, DataFusionError>(ScalarValue::$SCALAR(
match array.is_null($index) {
true => None,
false => Some(array.value($index).into()),
},
))
}};
}
macro_rules! build_array_from_option {
($DATA_TYPE:ident, $ARRAY_TYPE:ident, $EXPR:expr, $SIZE:expr) => {{
match $EXPR {
Some(value) => Arc::new($ARRAY_TYPE::from_value(*value, $SIZE)),
None => new_null_array(&DataType::$DATA_TYPE, $SIZE),
}
}};
($DATA_TYPE:ident, $ENUM:expr, $ARRAY_TYPE:ident, $EXPR:expr, $SIZE:expr) => {{
match $EXPR {
Some(value) => Arc::new($ARRAY_TYPE::from_value(*value, $SIZE)),
None => new_null_array(&DataType::$DATA_TYPE($ENUM), $SIZE),
}
}};
}
macro_rules! build_timestamp_array_from_option {
($TIME_UNIT:expr, $TZ:expr, $ARRAY_TYPE:ident, $EXPR:expr, $SIZE:expr) => {
match $EXPR {
Some(value) => {
Arc::new($ARRAY_TYPE::from_value(*value, $SIZE).with_timezone_opt($TZ))
}
None => new_null_array(&DataType::Timestamp($TIME_UNIT, $TZ), $SIZE),
}
};
}
macro_rules! eq_array_primitive {
($array:expr, $index:expr, $ARRAYTYPE:ident, $VALUE:expr) => {{
use std::any::type_name;
let array = $array
.as_any()
.downcast_ref::<$ARRAYTYPE>()
.ok_or_else(|| {
DataFusionError::Internal(format!(
"could not cast value to {}",
type_name::<$ARRAYTYPE>()
))
})?;
let is_valid = array.is_valid($index);
Ok::<bool, DataFusionError>(match $VALUE {
Some(val) => is_valid && &array.value($index) == val,
None => !is_valid,
})
}};
}
impl ScalarValue {
/// Create a [`Result<ScalarValue>`] with the provided value and datatype
///
/// # Panics
///
/// Panics if d is not compatible with T
pub fn new_primitive<T: ArrowPrimitiveType>(
a: Option<T::Native>,
d: &DataType,
) -> Result<Self> {
match a {
None => d.try_into(),
Some(v) => {
let array = PrimitiveArray::<T>::new(vec![v].into(), None)
.with_data_type(d.clone());
Self::try_from_array(&array, 0)
}
}
}
/// Create a decimal Scalar from value/precision and scale.
pub fn try_new_decimal128(value: i128, precision: u8, scale: i8) -> Result<Self> {
// make sure the precision and scale is valid
if precision <= DECIMAL128_MAX_PRECISION && scale.unsigned_abs() <= precision {
return Ok(ScalarValue::Decimal128(Some(value), precision, scale));
}
_internal_err!(
"Can not new a decimal type ScalarValue for precision {precision} and scale {scale}"
)
}
/// Returns a [`ScalarValue::Utf8`] representing `val`
pub fn new_utf8(val: impl Into<String>) -> Self {
ScalarValue::from(val.into())
}
/// Returns a [`ScalarValue::IntervalYearMonth`] representing
/// `years` years and `months` months
pub fn new_interval_ym(years: i32, months: i32) -> Self {
let val = IntervalYearMonthType::make_value(years, months);
ScalarValue::IntervalYearMonth(Some(val))
}
/// Returns a [`ScalarValue::IntervalDayTime`] representing
/// `days` days and `millis` milliseconds
pub fn new_interval_dt(days: i32, millis: i32) -> Self {
let val = IntervalDayTimeType::make_value(days, millis);
Self::IntervalDayTime(Some(val))
}
/// Returns a [`ScalarValue::IntervalMonthDayNano`] representing
/// `months` months and `days` days, and `nanos` nanoseconds
pub fn new_interval_mdn(months: i32, days: i32, nanos: i64) -> Self {
let val = IntervalMonthDayNanoType::make_value(months, days, nanos);
ScalarValue::IntervalMonthDayNano(Some(val))
}
/// Returns a [`ScalarValue`] representing
/// `value` and `tz_opt` timezone
pub fn new_timestamp<T: ArrowTimestampType>(
value: Option<i64>,
tz_opt: Option<Arc<str>>,
) -> Self {
match T::UNIT {
TimeUnit::Second => ScalarValue::TimestampSecond(value, tz_opt),
TimeUnit::Millisecond => ScalarValue::TimestampMillisecond(value, tz_opt),
TimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(value, tz_opt),
TimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(value, tz_opt),
}
}
/// Create a zero value in the given type.
pub fn new_zero(datatype: &DataType) -> Result<ScalarValue> {
Ok(match datatype {
DataType::Boolean => ScalarValue::Boolean(Some(false)),
DataType::Int8 => ScalarValue::Int8(Some(0)),
DataType::Int16 => ScalarValue::Int16(Some(0)),
DataType::Int32 => ScalarValue::Int32(Some(0)),
DataType::Int64 => ScalarValue::Int64(Some(0)),
DataType::UInt8 => ScalarValue::UInt8(Some(0)),
DataType::UInt16 => ScalarValue::UInt16(Some(0)),
DataType::UInt32 => ScalarValue::UInt32(Some(0)),
DataType::UInt64 => ScalarValue::UInt64(Some(0)),
DataType::Float32 => ScalarValue::Float32(Some(0.0)),
DataType::Float64 => ScalarValue::Float64(Some(0.0)),
DataType::Timestamp(TimeUnit::Second, tz) => {
ScalarValue::TimestampSecond(Some(0), tz.clone())
}
DataType::Timestamp(TimeUnit::Millisecond, tz) => {
ScalarValue::TimestampMillisecond(Some(0), tz.clone())
}
DataType::Timestamp(TimeUnit::Microsecond, tz) => {
ScalarValue::TimestampMicrosecond(Some(0), tz.clone())
}
DataType::Timestamp(TimeUnit::Nanosecond, tz) => {
ScalarValue::TimestampNanosecond(Some(0), tz.clone())
}
DataType::Interval(IntervalUnit::YearMonth) => {
ScalarValue::IntervalYearMonth(Some(0))
}
DataType::Interval(IntervalUnit::DayTime) => {
ScalarValue::IntervalDayTime(Some(0))
}
DataType::Interval(IntervalUnit::MonthDayNano) => {
ScalarValue::IntervalMonthDayNano(Some(0))
}
DataType::Duration(TimeUnit::Second) => ScalarValue::DurationSecond(Some(0)),
DataType::Duration(TimeUnit::Millisecond) => {
ScalarValue::DurationMillisecond(Some(0))
}
DataType::Duration(TimeUnit::Microsecond) => {
ScalarValue::DurationMicrosecond(Some(0))
}
DataType::Duration(TimeUnit::Nanosecond) => {
ScalarValue::DurationNanosecond(Some(0))
}
_ => {
return _not_impl_err!(
"Can't create a zero scalar from data_type \"{datatype:?}\""
);
}
})
}
/// Create an one value in the given type.
pub fn new_one(datatype: &DataType) -> Result<ScalarValue> {
assert!(datatype.is_primitive());
Ok(match datatype {
DataType::Int8 => ScalarValue::Int8(Some(1)),
DataType::Int16 => ScalarValue::Int16(Some(1)),
DataType::Int32 => ScalarValue::Int32(Some(1)),
DataType::Int64 => ScalarValue::Int64(Some(1)),
DataType::UInt8 => ScalarValue::UInt8(Some(1)),
DataType::UInt16 => ScalarValue::UInt16(Some(1)),
DataType::UInt32 => ScalarValue::UInt32(Some(1)),
DataType::UInt64 => ScalarValue::UInt64(Some(1)),
DataType::Float32 => ScalarValue::Float32(Some(1.0)),
DataType::Float64 => ScalarValue::Float64(Some(1.0)),
_ => {
return _not_impl_err!(
"Can't create an one scalar from data_type \"{datatype:?}\""
);
}
})
}
/// Create a negative one value in the given type.
pub fn new_negative_one(datatype: &DataType) -> Result<ScalarValue> {
assert!(datatype.is_primitive());
Ok(match datatype {
DataType::Int8 | DataType::UInt8 => ScalarValue::Int8(Some(-1)),
DataType::Int16 | DataType::UInt16 => ScalarValue::Int16(Some(-1)),
DataType::Int32 | DataType::UInt32 => ScalarValue::Int32(Some(-1)),
DataType::Int64 | DataType::UInt64 => ScalarValue::Int64(Some(-1)),