-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathscalar.rs
6186 lines (5820 loc) · 237 KB
/
scalar.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.
//! This module provides ScalarValue, an enum that can be used for storage of single elements
use std::borrow::Borrow;
use std::cmp::{max, Ordering};
use std::collections::HashSet;
use std::convert::{Infallible, TryInto};
use std::ops::{Add, Sub};
use std::str::FromStr;
use std::{convert::TryFrom, fmt, iter::repeat, sync::Arc};
use crate::cast::{
as_decimal128_array, as_dictionary_array, as_fixed_size_binary_array,
as_fixed_size_list_array, as_list_array, as_struct_array,
};
use crate::delta::shift_months;
use crate::error::{DataFusionError, Result};
use arrow::buffer::NullBuffer;
use arrow::compute::nullif;
use arrow::datatypes::{FieldRef, Fields, SchemaBuilder};
use arrow::{
array::*,
compute::kernels::cast::{cast_with_options, CastOptions},
datatypes::{
ArrowDictionaryKeyType, ArrowNativeType, DataType, Field, Float32Type,
Float64Type, Int16Type, Int32Type, Int64Type, Int8Type, IntervalDayTimeType,
IntervalMonthDayNanoType, IntervalUnit, IntervalYearMonthType, TimeUnit,
TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType,
TimestampSecondType, UInt16Type, UInt32Type, UInt64Type, UInt8Type,
DECIMAL128_MAX_PRECISION,
},
};
use arrow_array::timezone::Tz;
use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime};
// Constants we use throughout this file:
const MILLISECS_IN_ONE_DAY: i64 = 86_400_000;
const NANOSECS_IN_ONE_DAY: i64 = 86_400_000_000_000;
const SECS_IN_ONE_MONTH: i64 = 2_592_000; // assuming 30 days.
const MILLISECS_IN_ONE_MONTH: i64 = 2_592_000_000; // assuming 30 days.
const MICROSECS_IN_ONE_MONTH: i64 = 2_592_000_000_000; // assuming 30 days.
const NANOSECS_IN_ONE_MONTH: i128 = 2_592_000_000_000_000; // assuming 30 days.
/// Represents a dynamically typed, nullable single value.
/// This is the single-valued counter-part to arrow's [`Array`].
///
/// 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),
/// 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>>),
/// list of nested ScalarValue
List(Option<Vec<ScalarValue>>, FieldRef),
/// 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>),
/// struct of nested ScalarValue
Struct(Option<Vec<ScalarValue>>, Fields),
/// 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,
(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,
(List(v1, t1), List(v2, t2)) => v1.eq(v2) && t1.eq(t2),
(List(_, _), _) => 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,
(IntervalYearMonth(v1), IntervalYearMonth(v2)) => v1.eq(v2),
(IntervalYearMonth(v1), IntervalDayTime(v2)) => {
ym_to_milli(v1).eq(&dt_to_milli(v2))
}
(IntervalYearMonth(v1), IntervalMonthDayNano(v2)) => {
ym_to_nano(v1).eq(&mdn_to_nano(v2))
}
(IntervalYearMonth(_), _) => false,
(IntervalDayTime(v1), IntervalDayTime(v2)) => v1.eq(v2),
(IntervalDayTime(v1), IntervalYearMonth(v2)) => {
dt_to_milli(v1).eq(&ym_to_milli(v2))
}
(IntervalDayTime(v1), IntervalMonthDayNano(v2)) => {
dt_to_nano(v1).eq(&mdn_to_nano(v2))
}
(IntervalDayTime(_), _) => false,
(IntervalMonthDayNano(v1), IntervalMonthDayNano(v2)) => v1.eq(v2),
(IntervalMonthDayNano(v1), IntervalYearMonth(v2)) => {
mdn_to_nano(v1).eq(&ym_to_nano(v2))
}
(IntervalMonthDayNano(v1), IntervalDayTime(v2)) => {
mdn_to_nano(v1).eq(&dt_to_nano(v2))
}
(IntervalMonthDayNano(_), _) => false,
(Struct(v1, t1), Struct(v2, t2)) => v1.eq(v2) && t1.eq(t2),
(Struct(_, _), _) => 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,
(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,
(List(v1, t1), List(v2, t2)) => {
if t1.eq(t2) {
v1.partial_cmp(v2)
} else {
None
}
}
(List(_, _), _) => 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(v1), IntervalDayTime(v2)) => {
ym_to_milli(v1).partial_cmp(&dt_to_milli(v2))
}
(IntervalYearMonth(v1), IntervalMonthDayNano(v2)) => {
ym_to_nano(v1).partial_cmp(&mdn_to_nano(v2))
}
(IntervalYearMonth(_), _) => None,
(IntervalDayTime(v1), IntervalDayTime(v2)) => v1.partial_cmp(v2),
(IntervalDayTime(v1), IntervalYearMonth(v2)) => {
dt_to_milli(v1).partial_cmp(&ym_to_milli(v2))
}
(IntervalDayTime(v1), IntervalMonthDayNano(v2)) => {
dt_to_nano(v1).partial_cmp(&mdn_to_nano(v2))
}
(IntervalDayTime(_), _) => None,
(IntervalMonthDayNano(v1), IntervalMonthDayNano(v2)) => v1.partial_cmp(v2),
(IntervalMonthDayNano(v1), IntervalYearMonth(v2)) => {
mdn_to_nano(v1).partial_cmp(&ym_to_nano(v2))
}
(IntervalMonthDayNano(v1), IntervalDayTime(v2)) => {
mdn_to_nano(v1).partial_cmp(&dt_to_nano(v2))
}
(IntervalMonthDayNano(_), _) => None,
(Struct(v1, t1), Struct(v2, t2)) => {
if t1.eq(t2) {
v1.partial_cmp(v2)
} else {
None
}
}
(Struct(_, _), _) => 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,
}
}
}
/// This function computes the duration (in milliseconds) of the given
/// year-month-interval.
#[inline]
pub fn ym_to_sec(val: &Option<i32>) -> Option<i64> {
val.map(|value| (value as i64) * SECS_IN_ONE_MONTH)
}
/// This function computes the duration (in milliseconds) of the given
/// year-month-interval.
#[inline]
pub fn ym_to_milli(val: &Option<i32>) -> Option<i64> {
val.map(|value| (value as i64) * MILLISECS_IN_ONE_MONTH)
}
/// This function computes the duration (in milliseconds) of the given
/// year-month-interval.
#[inline]
pub fn ym_to_micro(val: &Option<i32>) -> Option<i64> {
val.map(|value| (value as i64) * MICROSECS_IN_ONE_MONTH)
}
/// This function computes the duration (in nanoseconds) of the given
/// year-month-interval.
#[inline]
pub fn ym_to_nano(val: &Option<i32>) -> Option<i128> {
val.map(|value| (value as i128) * NANOSECS_IN_ONE_MONTH)
}
/// This function computes the duration (in seconds) of the given
/// daytime-interval.
#[inline]
pub fn dt_to_sec(val: &Option<i64>) -> Option<i64> {
val.map(|val| {
let (days, millis) = IntervalDayTimeType::to_parts(val);
(days as i64) * MILLISECS_IN_ONE_DAY + (millis as i64 / 1_000)
})
}
/// This function computes the duration (in milliseconds) of the given
/// daytime-interval.
#[inline]
pub fn dt_to_milli(val: &Option<i64>) -> Option<i64> {
val.map(|val| {
let (days, millis) = IntervalDayTimeType::to_parts(val);
(days as i64) * MILLISECS_IN_ONE_DAY + (millis as i64)
})
}
/// This function computes the duration (in microseconds) of the given
/// daytime-interval.
#[inline]
pub fn dt_to_micro(val: &Option<i64>) -> Option<i128> {
val.map(|val| {
let (days, millis) = IntervalDayTimeType::to_parts(val);
(days as i128) * (NANOSECS_IN_ONE_DAY as i128) + (millis as i128) * 1_000
})
}
/// This function computes the duration (in nanoseconds) of the given
/// daytime-interval.
#[inline]
pub fn dt_to_nano(val: &Option<i64>) -> Option<i128> {
val.map(|val| {
let (days, millis) = IntervalDayTimeType::to_parts(val);
(days as i128) * (NANOSECS_IN_ONE_DAY as i128) + (millis as i128) * 1_000_000
})
}
/// This function computes the duration (in seconds) of the given
/// month-day-nano-interval. Assumes a month is 30 days long.
#[inline]
pub fn mdn_to_sec(val: &Option<i128>) -> Option<i128> {
val.map(|val| {
let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(val);
(months as i128) * NANOSECS_IN_ONE_MONTH
+ (days as i128) * (NANOSECS_IN_ONE_DAY as i128)
+ (nanos as i128) / 1_000_000_000
})
}
/// This function computes the duration (in milliseconds) of the given
/// month-day-nano-interval. Assumes a month is 30 days long.
#[inline]
pub fn mdn_to_milli(val: &Option<i128>) -> Option<i128> {
val.map(|val| {
let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(val);
(months as i128) * NANOSECS_IN_ONE_MONTH
+ (days as i128) * (NANOSECS_IN_ONE_DAY as i128)
+ (nanos as i128) / 1_000_000
})
}
/// This function computes the duration (in microseconds) of the given
/// month-day-nano-interval. Assumes a month is 30 days long.
#[inline]
pub fn mdn_to_micro(val: &Option<i128>) -> Option<i128> {
val.map(|val| {
let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(val);
(months as i128) * NANOSECS_IN_ONE_MONTH
+ (days as i128) * (NANOSECS_IN_ONE_DAY as i128)
+ (nanos as i128) / 1_000
})
}
/// This function computes the duration (in nanoseconds) of the given
/// month-day-nano-interval. Assumes a month is 30 days long.
#[inline]
pub fn mdn_to_nano(val: &Option<i128>) -> Option<i128> {
val.map(|val| {
let (months, days, nanos) = IntervalMonthDayNanoType::to_parts(val);
(months as i128) * NANOSECS_IN_ONE_MONTH
+ (days as i128) * (NANOSECS_IN_ONE_DAY as i128)
+ (nanos as i128)
})
}
impl Eq for ScalarValue {}
// TODO implement this in arrow-rs with simd
// https://github.com/apache/arrow-rs/issues/1010
macro_rules! decimal_op {
($LHS:expr, $RHS:expr, $PRECISION:expr, $LHS_SCALE:expr, $RHS_SCALE:expr, $OPERATION:tt) => {{
let (difference, side) = if $LHS_SCALE > $RHS_SCALE {
($LHS_SCALE - $RHS_SCALE, true)
} else {
($RHS_SCALE - $LHS_SCALE, false)
};
let scale = max($LHS_SCALE, $RHS_SCALE);
Ok(match ($LHS, $RHS, difference) {
(None, None, _) => ScalarValue::Decimal128(None, $PRECISION, scale),
(lhs, None, 0) => ScalarValue::Decimal128(*lhs, $PRECISION, scale),
(Some(lhs_value), None, _) => {
let mut new_value = *lhs_value;
if !side {
new_value *= 10_i128.pow(difference as u32)
}
ScalarValue::Decimal128(Some(new_value), $PRECISION, scale)
}
(None, Some(rhs_value), 0) => {
let value = decimal_right!(*rhs_value, $OPERATION);
ScalarValue::Decimal128(Some(value), $PRECISION, scale)
}
(None, Some(rhs_value), _) => {
let mut new_value = decimal_right!(*rhs_value, $OPERATION);
if side {
new_value *= 10_i128.pow(difference as u32)
};
ScalarValue::Decimal128(Some(new_value), $PRECISION, scale)
}
(Some(lhs_value), Some(rhs_value), 0) => {
decimal_binary_op!(lhs_value, rhs_value, $OPERATION, $PRECISION, scale)
}
(Some(lhs_value), Some(rhs_value), _) => {
let (left_arg, right_arg) = if side {
(*lhs_value, rhs_value * 10_i128.pow(difference as u32))
} else {
(lhs_value * 10_i128.pow(difference as u32), *rhs_value)
};
decimal_binary_op!(left_arg, right_arg, $OPERATION, $PRECISION, scale)
}
})
}};
}
macro_rules! decimal_binary_op {
($LHS:expr, $RHS:expr, $OPERATION:tt, $PRECISION:expr, $SCALE:expr) => {
// TODO: This simple implementation loses precision for calculations like
// multiplication and division. Improve this implementation for such
// operations.
ScalarValue::Decimal128(Some($LHS $OPERATION $RHS), $PRECISION, $SCALE)
};
}
macro_rules! decimal_right {
($TERM:expr, +) => {
$TERM
};
($TERM:expr, *) => {
$TERM
};
($TERM:expr, -) => {
-$TERM
};
($TERM:expr, /) => {
Err(DataFusionError::NotImplemented(format!(
"Decimal reciprocation not yet supported",
)))
};
}
// Returns the result of applying operation to two scalar values.
macro_rules! primitive_op {
($LEFT:expr, $RIGHT:expr, $SCALAR:ident, $OPERATION:tt) => {
match ($LEFT, $RIGHT) {
(lhs, None) => Ok(ScalarValue::$SCALAR(*lhs)),
#[allow(unused_variables)]
(None, Some(b)) => { primitive_right!(*b, $OPERATION, $SCALAR) },
(Some(a), Some(b)) => Ok(ScalarValue::$SCALAR(Some(*a $OPERATION *b))),
}
};
}
macro_rules! primitive_checked_op {
($LEFT:expr, $RIGHT:expr, $SCALAR:ident, $FUNCTION:ident, $OPERATION:tt) => {
match ($LEFT, $RIGHT) {
(lhs, None) => Ok(ScalarValue::$SCALAR(*lhs)),
#[allow(unused_variables)]
(None, Some(b)) => {
primitive_checked_right!(*b, $OPERATION, $SCALAR)
}
(Some(a), Some(b)) => {
if let Some(value) = (*a).$FUNCTION(*b) {
Ok(ScalarValue::$SCALAR(Some(value)))
} else {
Err(DataFusionError::Execution(
"Overflow while calculating ScalarValue.".to_string(),
))
}
}
}
};
}
macro_rules! primitive_checked_right {
($TERM:expr, -, $SCALAR:ident) => {
if let Some(value) = $TERM.checked_neg() {
Ok(ScalarValue::$SCALAR(Some(value)))
} else {
Err(DataFusionError::Execution(
"Overflow while calculating ScalarValue.".to_string(),
))
}
};
($TERM:expr, $OPERATION:tt, $SCALAR:ident) => {
primitive_right!($TERM, $OPERATION, $SCALAR)
};
}
macro_rules! primitive_right {
($TERM:expr, +, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some($TERM)))
};
($TERM:expr, *, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some($TERM)))
};
($TERM:expr, -, UInt64) => {
unsigned_subtraction_error!("UInt64")
};
($TERM:expr, -, UInt32) => {
unsigned_subtraction_error!("UInt32")
};
($TERM:expr, -, UInt16) => {
unsigned_subtraction_error!("UInt16")
};
($TERM:expr, -, UInt8) => {
unsigned_subtraction_error!("UInt8")
};
($TERM:expr, -, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some(-$TERM)))
};
($TERM:expr, /, Float64) => {
Ok(ScalarValue::$SCALAR(Some($TERM.recip())))
};
($TERM:expr, /, Float32) => {
Ok(ScalarValue::$SCALAR(Some($TERM.recip())))
};
($TERM:expr, /, $SCALAR:ident) => {
Err(DataFusionError::Internal(format!(
"Can not divide an uninitialized value to a non-floating point value",
)))
};
($TERM:expr, &, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some($TERM)))
};
($TERM:expr, |, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some($TERM)))
};
($TERM:expr, ^, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some($TERM)))
};
($TERM:expr, &&, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some($TERM)))
};
($TERM:expr, ||, $SCALAR:ident) => {
Ok(ScalarValue::$SCALAR(Some($TERM)))
};
}
macro_rules! unsigned_subtraction_error {
($SCALAR:expr) => {{
let msg = format!(
"Can not subtract a {} value from an uninitialized value",
$SCALAR
);
Err(DataFusionError::Internal(msg))
}};
}
macro_rules! impl_checked_op {
($LHS:expr, $RHS:expr, $FUNCTION:ident, $OPERATION:tt) => {
// Only covering primitive types that support checked_* operands, and fall back to raw operation for other types.
match ($LHS, $RHS) {
(ScalarValue::UInt64(lhs), ScalarValue::UInt64(rhs)) => {
primitive_checked_op!(lhs, rhs, UInt64, $FUNCTION, $OPERATION)
},
(ScalarValue::Int64(lhs), ScalarValue::Int64(rhs)) => {
primitive_checked_op!(lhs, rhs, Int64, $FUNCTION, $OPERATION)
},
(ScalarValue::UInt32(lhs), ScalarValue::UInt32(rhs)) => {
primitive_checked_op!(lhs, rhs, UInt32, $FUNCTION, $OPERATION)
},
(ScalarValue::Int32(lhs), ScalarValue::Int32(rhs)) => {
primitive_checked_op!(lhs, rhs, Int32, $FUNCTION, $OPERATION)
},
(ScalarValue::UInt16(lhs), ScalarValue::UInt16(rhs)) => {
primitive_checked_op!(lhs, rhs, UInt16, $FUNCTION, $OPERATION)
},
(ScalarValue::Int16(lhs), ScalarValue::Int16(rhs)) => {
primitive_checked_op!(lhs, rhs, Int16, $FUNCTION, $OPERATION)
},
(ScalarValue::UInt8(lhs), ScalarValue::UInt8(rhs)) => {
primitive_checked_op!(lhs, rhs, UInt8, $FUNCTION, $OPERATION)
},
(ScalarValue::Int8(lhs), ScalarValue::Int8(rhs)) => {
primitive_checked_op!(lhs, rhs, Int8, $FUNCTION, $OPERATION)
},
_ => {
impl_op!($LHS, $RHS, $OPERATION)
}
}
};
}
macro_rules! impl_op {
($LHS:expr, $RHS:expr, +) => {
impl_op_arithmetic!($LHS, $RHS, +)
};
($LHS:expr, $RHS:expr, -) => {
match ($LHS, $RHS) {
(
ScalarValue::TimestampSecond(Some(ts_lhs), tz_lhs),
ScalarValue::TimestampSecond(Some(ts_rhs), tz_rhs),
) => {
let err = || {
DataFusionError::Execution(
"Overflow while converting seconds to milliseconds".to_string(),
)
};
ts_sub_to_interval::<MILLISECOND_MODE>(
ts_lhs.checked_mul(1_000).ok_or_else(err)?,
ts_rhs.checked_mul(1_000).ok_or_else(err)?,
tz_lhs.as_deref(),
tz_rhs.as_deref(),
)
},
(
ScalarValue::TimestampMillisecond(Some(ts_lhs), tz_lhs),
ScalarValue::TimestampMillisecond(Some(ts_rhs), tz_rhs),
) => ts_sub_to_interval::<MILLISECOND_MODE>(
*ts_lhs,
*ts_rhs,
tz_lhs.as_deref(),
tz_rhs.as_deref(),
),
(
ScalarValue::TimestampMicrosecond(Some(ts_lhs), tz_lhs),
ScalarValue::TimestampMicrosecond(Some(ts_rhs), tz_rhs),
) => {
let err = || {
DataFusionError::Execution(
"Overflow while converting microseconds to nanoseconds".to_string(),
)
};
ts_sub_to_interval::<NANOSECOND_MODE>(
ts_lhs.checked_mul(1_000).ok_or_else(err)?,
ts_rhs.checked_mul(1_000).ok_or_else(err)?,
tz_lhs.as_deref(),
tz_rhs.as_deref(),
)
},
(
ScalarValue::TimestampNanosecond(Some(ts_lhs), tz_lhs),
ScalarValue::TimestampNanosecond(Some(ts_rhs), tz_rhs),
) => ts_sub_to_interval::<NANOSECOND_MODE>(
*ts_lhs,
*ts_rhs,
tz_lhs.as_deref(),
tz_rhs.as_deref(),
),
_ => impl_op_arithmetic!($LHS, $RHS, -)
}
};
($LHS:expr, $RHS:expr, &) => {
impl_bit_op_arithmetic!($LHS, $RHS, &)
};
($LHS:expr, $RHS:expr, |) => {
impl_bit_op_arithmetic!($LHS, $RHS, |)
};
($LHS:expr, $RHS:expr, ^) => {
impl_bit_op_arithmetic!($LHS, $RHS, ^)
};
($LHS:expr, $RHS:expr, &&) => {
impl_bool_op_arithmetic!($LHS, $RHS, &&)
};
($LHS:expr, $RHS:expr, ||) => {
impl_bool_op_arithmetic!($LHS, $RHS, ||)
};
}
macro_rules! impl_bit_op_arithmetic {
($LHS:expr, $RHS:expr, $OPERATION:tt) => {
match ($LHS, $RHS) {
(ScalarValue::UInt64(lhs), ScalarValue::UInt64(rhs)) => {
primitive_op!(lhs, rhs, UInt64, $OPERATION)
}
(ScalarValue::Int64(lhs), ScalarValue::Int64(rhs)) => {
primitive_op!(lhs, rhs, Int64, $OPERATION)
}
(ScalarValue::UInt32(lhs), ScalarValue::UInt32(rhs)) => {
primitive_op!(lhs, rhs, UInt32, $OPERATION)
}
(ScalarValue::Int32(lhs), ScalarValue::Int32(rhs)) => {
primitive_op!(lhs, rhs, Int32, $OPERATION)
}
(ScalarValue::UInt16(lhs), ScalarValue::UInt16(rhs)) => {
primitive_op!(lhs, rhs, UInt16, $OPERATION)
}
(ScalarValue::Int16(lhs), ScalarValue::Int16(rhs)) => {
primitive_op!(lhs, rhs, Int16, $OPERATION)
}
(ScalarValue::UInt8(lhs), ScalarValue::UInt8(rhs)) => {
primitive_op!(lhs, rhs, UInt8, $OPERATION)
}
(ScalarValue::Int8(lhs), ScalarValue::Int8(rhs)) => {
primitive_op!(lhs, rhs, Int8, $OPERATION)
}
_ => Err(DataFusionError::Internal(format!(
"Operator {} is not implemented for types {:?} and {:?}",
stringify!($OPERATION),
$LHS,
$RHS
))),
}
};
}
macro_rules! impl_bool_op_arithmetic {
($LHS:expr, $RHS:expr, $OPERATION:tt) => {
match ($LHS, $RHS) {
(ScalarValue::Boolean(lhs), ScalarValue::Boolean(rhs)) => {
primitive_op!(lhs, rhs, Boolean, $OPERATION)
}
_ => Err(DataFusionError::Internal(format!(
"Operator {} is not implemented for types {:?} and {:?}",
stringify!($OPERATION),
$LHS,
$RHS
))),
}
};
}
macro_rules! impl_op_arithmetic {
($LHS:expr, $RHS:expr, $OPERATION:tt) => {
match ($LHS, $RHS) {
// Binary operations on arguments with the same type:
(
ScalarValue::Decimal128(v1, p1, s1),
ScalarValue::Decimal128(v2, p2, s2),
) => {
decimal_op!(v1, v2, *p1.max(p2), *s1, *s2, $OPERATION)
}
(ScalarValue::Float64(lhs), ScalarValue::Float64(rhs)) => {
primitive_op!(lhs, rhs, Float64, $OPERATION)
}
(ScalarValue::Float32(lhs), ScalarValue::Float32(rhs)) => {
primitive_op!(lhs, rhs, Float32, $OPERATION)
}
(ScalarValue::UInt64(lhs), ScalarValue::UInt64(rhs)) => {
primitive_op!(lhs, rhs, UInt64, $OPERATION)
}
(ScalarValue::Int64(lhs), ScalarValue::Int64(rhs)) => {
primitive_op!(lhs, rhs, Int64, $OPERATION)
}
(ScalarValue::UInt32(lhs), ScalarValue::UInt32(rhs)) => {
primitive_op!(lhs, rhs, UInt32, $OPERATION)
}
(ScalarValue::Int32(lhs), ScalarValue::Int32(rhs)) => {
primitive_op!(lhs, rhs, Int32, $OPERATION)
}
(ScalarValue::UInt16(lhs), ScalarValue::UInt16(rhs)) => {
primitive_op!(lhs, rhs, UInt16, $OPERATION)
}
(ScalarValue::Int16(lhs), ScalarValue::Int16(rhs)) => {
primitive_op!(lhs, rhs, Int16, $OPERATION)
}
(ScalarValue::UInt8(lhs), ScalarValue::UInt8(rhs)) => {
primitive_op!(lhs, rhs, UInt8, $OPERATION)
}
(ScalarValue::Int8(lhs), ScalarValue::Int8(rhs)) => {
primitive_op!(lhs, rhs, Int8, $OPERATION)
}
(
ScalarValue::IntervalYearMonth(Some(lhs)),
ScalarValue::IntervalYearMonth(Some(rhs)),
) => Ok(ScalarValue::IntervalYearMonth(Some(op_ym(
*lhs,
*rhs,
get_sign!($OPERATION),
)))),
(
ScalarValue::IntervalDayTime(Some(lhs)),
ScalarValue::IntervalDayTime(Some(rhs)),
) => Ok(ScalarValue::IntervalDayTime(Some(op_dt(
*lhs,
*rhs,
get_sign!($OPERATION),
)))),
(
ScalarValue::IntervalMonthDayNano(Some(lhs)),
ScalarValue::IntervalMonthDayNano(Some(rhs)),
) => Ok(ScalarValue::IntervalMonthDayNano(Some(op_mdn(
*lhs,
*rhs,
get_sign!($OPERATION),
)))),
// Binary operations on arguments with different types:
(ScalarValue::Date32(Some(days)), _) => {
let value = date32_op(*days, $RHS, get_sign!($OPERATION))?;
Ok(ScalarValue::Date32(Some(value)))
}
(ScalarValue::Date64(Some(ms)), _) => {
let value = date64_op(*ms, $RHS, get_sign!($OPERATION))?;
Ok(ScalarValue::Date64(Some(value)))
}
(ScalarValue::TimestampSecond(Some(ts_s), zone), _) => {
let value = seconds_add(*ts_s, $RHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampSecond(Some(value), zone.clone()))
}
(_, ScalarValue::TimestampSecond(Some(ts_s), zone)) => {
let value = seconds_add(*ts_s, $LHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampSecond(Some(value), zone.clone()))
}
(ScalarValue::TimestampMillisecond(Some(ts_ms), zone), _) => {
let value = milliseconds_add(*ts_ms, $RHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampMillisecond(Some(value), zone.clone()))
}
(_, ScalarValue::TimestampMillisecond(Some(ts_ms), zone)) => {
let value = milliseconds_add(*ts_ms, $LHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampMillisecond(Some(value), zone.clone()))
}
(ScalarValue::TimestampMicrosecond(Some(ts_us), zone), _) => {
let value = microseconds_add(*ts_us, $RHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampMicrosecond(Some(value), zone.clone()))
}
(_, ScalarValue::TimestampMicrosecond(Some(ts_us), zone)) => {
let value = microseconds_add(*ts_us, $LHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampMicrosecond(Some(value), zone.clone()))
}
(ScalarValue::TimestampNanosecond(Some(ts_ns), zone), _) => {
let value = nanoseconds_add(*ts_ns, $RHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampNanosecond(Some(value), zone.clone()))
}
(_, ScalarValue::TimestampNanosecond(Some(ts_ns), zone)) => {
let value = nanoseconds_add(*ts_ns, $LHS, get_sign!($OPERATION))?;
Ok(ScalarValue::TimestampNanosecond(Some(value), zone.clone()))
}
(
ScalarValue::IntervalYearMonth(Some(lhs)),
ScalarValue::IntervalDayTime(Some(rhs)),
) => Ok(ScalarValue::IntervalMonthDayNano(Some(op_ym_dt(
*lhs,
*rhs,
get_sign!($OPERATION),
false,
)))),
(
ScalarValue::IntervalYearMonth(Some(lhs)),
ScalarValue::IntervalMonthDayNano(Some(rhs)),
) => Ok(ScalarValue::IntervalMonthDayNano(Some(op_ym_mdn(
*lhs,
*rhs,
get_sign!($OPERATION),
false,
)))),
(
ScalarValue::IntervalDayTime(Some(lhs)),
ScalarValue::IntervalYearMonth(Some(rhs)),
) => Ok(ScalarValue::IntervalMonthDayNano(Some(op_ym_dt(
*rhs,
*lhs,
get_sign!($OPERATION),
true,
)))),
(
ScalarValue::IntervalDayTime(Some(lhs)),
ScalarValue::IntervalMonthDayNano(Some(rhs)),
) => Ok(ScalarValue::IntervalMonthDayNano(Some(op_dt_mdn(
*lhs,
*rhs,
get_sign!($OPERATION),
false,
)))),
(
ScalarValue::IntervalMonthDayNano(Some(lhs)),
ScalarValue::IntervalYearMonth(Some(rhs)),
) => Ok(ScalarValue::IntervalMonthDayNano(Some(op_ym_mdn(
*rhs,
*lhs,
get_sign!($OPERATION),
true,
)))),
(
ScalarValue::IntervalMonthDayNano(Some(lhs)),
ScalarValue::IntervalDayTime(Some(rhs)),
) => Ok(ScalarValue::IntervalMonthDayNano(Some(op_dt_mdn(
*rhs,
*lhs,
get_sign!($OPERATION),