feldera-sqllib 0.331.0

SQL runtime library for Feldera
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
//! Support for SQL interval types.
//! Intervals are differences between dates and/or times

use crate::{
    Date, SqlDecimal, finite_or_null,
    operators::{eq, gt, gte, lt, lte, neq},
    plus_Date_Date_LongInterval__, sign, some_existing_operator, some_function1, some_function2,
    some_operator, some_polymorphic_function1, some_polymorphic_function2,
    some_polymorphic_null_function2,
    timestamp::{extract_epoch_Date, extract_quarter_Date},
};
use dbsp::{algebra::F64, num_entries_scalar};
use feldera_macros::IsNone;
use feldera_types::serde_with_context::{
    DeserializeWithContext, SerializeWithContext, SqlSerdeConfig,
};
use serde::{Deserialize, Serialize, de::Error as _, ser::Error as _};
use size_of::SizeOf;
use std::fmt;
use std::ops::{Add, Div, Mul, Neg, Sub};

#[cfg(doc)]
use crate::{Time, Timestamp};

/// A ShortInterval can express a difference between two [Time]
/// values, two [Date] values, or two [Timestamp] values.  The
/// representation is a (positive or negative) number of microseconds.
/// While there are functions that can extract nanosecond-precision
/// values from a ShortInterval, the precision is always limited to
/// microseconds.
#[derive(
    Debug,
    Default,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    SizeOf,
    rkyv::Archive,
    rkyv::Serialize,
    Serialize,
    Deserialize,
    IsNone,
)]
#[archive_attr(derive(Clone, Ord, Eq, PartialEq, PartialOrd))]
#[archive(compare(PartialEq, PartialOrd))]
#[serde(transparent)]
pub struct ShortInterval {
    microseconds: i64,
}

#[doc(hidden)]
pub fn reinterpret_ShortInterval(value: ShortInterval) -> i64 {
    value.milliseconds()
}

some_polymorphic_function1!(reinterpret, ShortInterval, ShortInterval, i64);

#[doc(hidden)]
impl<D> ::rkyv::Deserialize<ShortInterval, D> for ArchivedShortInterval
where
    D: ::rkyv::Fallible + ::core::any::Any,
{
    fn deserialize(&self, deserializer: &mut D) -> Result<ShortInterval, D::Error> {
        // The internal representation of ShortInterval changed from version 4 of the storage format
        const MILLISECOND_VERSION: u32 = 4;
        let version = (deserializer as &mut dyn ::core::any::Any)
            .downcast_mut::<::dbsp::storage::file::Deserializer>()
            .map(|deserializer| deserializer.version())
            .expect("Deserializer must be of type dbsp::storage::file::Deserializer");
        let value: i64 = self.microseconds.deserialize(deserializer)?;
        if version <= MILLISECOND_VERSION {
            Ok(ShortInterval::from_milliseconds(value))
        } else {
            Ok(ShortInterval::from_microseconds(value))
        }
    }
}

impl ShortInterval {
    /// Create a ShortInterval with a length specified in milliseconds.
    pub const fn from_milliseconds(milliseconds: i64) -> Self {
        Self {
            microseconds: milliseconds * 1000,
        }
    }

    /// Create a ShortInterval with a length specified in microseconds.
    pub const fn from_microseconds(microseconds: i64) -> Self {
        Self { microseconds }
    }

    /// Create a ShortInterval with a length specified in seconds.
    pub const fn from_seconds(seconds: i64) -> Self {
        Self::from_milliseconds(seconds * 1_000)
    }

    /// Extract the length of the interval in microseconds.  The
    /// result can be negative.
    pub fn microseconds(&self) -> i64 {
        self.microseconds
    }

    /// Extract the length of the interval in milliseconds.  The
    /// result can be negative.
    pub fn milliseconds(&self) -> i64 {
        self.microseconds / 1000
    }

    /// Extract the length of the interval in nanoseconds.  The result
    /// can be negative.  The granularity of the representation is
    /// actually microseconds, so this function will always return a
    /// number that is a multiple of 1000.
    pub fn nanoseconds(&self) -> i64 {
        self.microseconds * 1_000
    }

    /// Extract the length of the interval in milliseconds.  The
    /// result can be negative.
    pub fn seconds(&self) -> i64 {
        self.microseconds / 1_000_000
    }

    /// Extract the length of the interval in minutes.  The
    /// result can be negative.
    pub fn minutes(&self) -> i64 {
        self.microseconds / (60 * 1_000_000)
    }

    /// Extract the length of the interval in minutes.  The
    /// result can be negative.
    pub fn hours(&self) -> i64 {
        self.microseconds / (60 * 60 * 1_000_000i64)
    }

    /// Extract the length of the interval in minutes.  The
    /// result can be negative.
    pub fn days(&self) -> i64 {
        self.microseconds / (24 * 60 * 60 * 1_000_000i64)
    }
}

#[doc(hidden)]
pub fn abs_ShortInterval(value: ShortInterval) -> ShortInterval {
    ShortInterval::from_microseconds(num::abs(value.microseconds))
}

some_polymorphic_function1!(abs, ShortInterval, ShortInterval, ShortInterval);

#[doc(hidden)]
/// This function is used in rolling window computations, to compute a window bound.
/// Window bounds are always positive.
pub fn to_bound_ShortInterval_ShortInterval_u128(value: &ShortInterval) -> u128 {
    value.microseconds as u128
}

#[doc(hidden)]
/// This function is used in rolling window computations, to compute a window bound.
/// Window bounds are always positive.
pub fn to_bound_ShortInterval_Date_u128(value: &ShortInterval) -> u128 {
    // express value in days
    (value.microseconds / 1_000_000_i64 / 86400) as u128
}

#[doc(hidden)]
/// This function is used in rolling window computations, to compute a window bound.
/// Window bounds are always positive.
pub fn to_bound_ShortInterval_Date_u64(value: &ShortInterval) -> u64 {
    // express value in days
    (value.microseconds / 1_000_000_i64 / 86400) as u64
}

#[doc(hidden)]
/// This function is used in rolling window computations, to compute a window bound.
/// Window bounds are always positive.
pub fn to_bound_ShortInterval_Timestamp_u128(value: &ShortInterval) -> u128 {
    value.microseconds as u128
}

#[doc(hidden)]
/// This function is used in rolling window computations, to compute a window bound.
/// Window bounds are always positive.
pub fn to_bound_ShortInterval_Timestamp_u64(value: &ShortInterval) -> u64 {
    value.microseconds as u64
}

#[doc(hidden)]
/// This function is used in rolling window computations, to compute a window bound.
/// Window bounds are always positive.
pub fn to_bound_ShortInterval_Time_u128(value: &ShortInterval) -> u128 {
    // express value in nanoseconds
    (value.microseconds * 1_000) as u128
}

#[doc(hidden)]
/// This function is used in rolling window computations, to compute a window bound.
/// Window bounds are always positive.
pub fn to_bound_ShortInterval_Time_u64(value: &ShortInterval) -> u64 {
    // express value in nanoseconds
    (value.microseconds * 1_000) as u64
}

/// Multiply a `ShortInterval` by a numeric value, producing a `ShortInterval`.
impl Mul<i64> for ShortInterval {
    type Output = Self;

    /// Multiply a short interval by an long integer
    fn mul(self, rhs: i64) -> Self {
        Self {
            microseconds: self.microseconds * rhs,
        }
    }
}

/// Multiply a `ShortInterval` by a numeric value, producing a `ShortInterval`.
impl Mul<F64> for ShortInterval {
    type Output = Self;

    fn mul(self, rhs: F64) -> Self {
        Self {
            microseconds: (F64::from(self.microseconds as f64) * rhs).into_inner() as i64,
        }
    }
}

/// Multiply a `ShortInterval` by a numeric value, producing a `ShortInterval`.
impl<const P: usize, const S: usize> Mul<SqlDecimal<P, S>> for ShortInterval {
    type Output = Self;

    fn mul(self, rhs: SqlDecimal<P, S>) -> Self {
        let us = SqlDecimal::<38, 0>::try_from(self.microseconds).unwrap_or_else(|_| {
            panic!(
                "overflow in short interval multiplication while converting {} to DECIMAL",
                self
            )
        });
        let mul = us
            .checked_mul_generic::<P, S, 38, 0>(rhs)
            .unwrap_or_else(|| panic!("overflow in INTERVAL multiplication {} * {}", self, rhs));
        Self {
            microseconds: mul.try_into().unwrap_or_else(|_| {
                panic!("overflow in INTERVAL multiplication {} * {}", self, rhs)
            }),
        }
    }
}

/// Divide a `ShortInterval` by a numeric value, producing a `ShortInterval`.
impl Div<i64> for ShortInterval {
    type Output = Self;

    fn div(self, rhs: i64) -> Self {
        Self {
            microseconds: self.microseconds / rhs,
        }
    }
}

impl fmt::Display for ShortInterval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (sign, interval) = self.into_sign_and_magnitude();
        let days = extract_day_ShortInterval(interval);
        let hours = extract_hour_ShortInterval(interval);
        let minutes = extract_minute_ShortInterval(interval);
        let seconds = extract_second_ShortInterval(interval);
        let micro = interval.microseconds % 1_000_000;
        if micro == 0 {
            write!(
                f,
                "{sign}{} {:02}:{:02}:{:02}",
                days, hours, minutes, seconds
            )
        } else {
            write!(
                f,
                "{sign}{} {:02}:{:02}:{:02}.{:06}",
                days, hours, minutes, seconds, micro
            )
        }
    }
}

/// Divide a `ShortInterval` by a numeric value, producing a `ShortInterval`.
impl Div<F64> for ShortInterval {
    type Output = Self;
    fn div(self, rhs: F64) -> Self {
        let result = div_null_ShortInterval_d(self, rhs);
        match result {
            None => panic!(
                "overflow while dividing INTERVAL {} / {}",
                self,
                rhs.into_inner()
            ),
            Some(interval) => interval,
        }
    }
}

/// Divide a `ShortInterval` by a numeric value, producing a `ShortInterval`.
impl<const P: usize, const S: usize> Div<SqlDecimal<P, S>> for ShortInterval {
    type Output = Self;

    fn div(self, rhs: SqlDecimal<P, S>) -> Self {
        let us = SqlDecimal::<38, 0>::try_from(self.microseconds).unwrap_or_else(|_| {
            panic!(
                "overflow in short interval division while converting {} to DECIMAL",
                self
            )
        });
        let div = us
            .checked_div_generic::<P, S, 38, 0>(rhs)
            .unwrap_or_else(|| panic!("overflow in INTERVAL division {} / {}", self, rhs));
        Self {
            microseconds: div
                .try_into()
                .unwrap_or_else(|_| panic!("overflow in INTERVAL division {} / {}", self, rhs)),
        }
    }
}

/// Add two `ShortInterval`s
impl Add<ShortInterval> for ShortInterval {
    type Output = Self;

    fn add(self, rhs: ShortInterval) -> Self {
        Self {
            microseconds: self
                .microseconds
                .checked_add(rhs.microseconds)
                .unwrap_or_else(|| panic!("overflow in INTERVAL addition {} + {}", self, rhs)),
        }
    }
}

/// Subtract two `ShortInterval`s
impl Sub<ShortInterval> for ShortInterval {
    type Output = Self;

    fn sub(self, rhs: ShortInterval) -> Self {
        Self {
            microseconds: self
                .microseconds
                .checked_sub(rhs.microseconds)
                .unwrap_or_else(|| panic!("overflow in INTERVAL subtraction {} - {}", self, rhs)),
        }
    }
}

/// Negate a `ShortInterval`
impl Neg for ShortInterval {
    type Output = Self;

    fn neg(self) -> Self {
        Self {
            microseconds: self
                .microseconds
                .checked_neg()
                .unwrap_or_else(|| panic!("overflow in INTERVAL negation -{}", self)),
        }
    }
}

/// Serialize a `ShortInterval` with context.  See
/// [`SerializeWithContext`].
impl SerializeWithContext<SqlSerdeConfig> for ShortInterval {
    fn serialize_with_context<S>(
        &self,
        _serializer: S,
        _context: &SqlSerdeConfig,
    ) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        Err(S::Error::custom(
            "serialization is not implemented for the INTERVAL type",
        ))
    }
}

/// Deserialize a `ShortInterval` with context.  See
/// [`DeserializeWithContext`].
impl<'de> DeserializeWithContext<'de, SqlSerdeConfig, ()> for ShortInterval {
    fn deserialize_with_context<D>(
        _deserializer: D,
        _context: &'de SqlSerdeConfig,
    ) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Err(D::Error::custom(
            "deserialization is not implemented for the INTERVAL type",
        ))
    }
}

some_operator!(lt, ShortInterval, ShortInterval, bool);
some_operator!(gt, ShortInterval, ShortInterval, bool);
some_operator!(eq, ShortInterval, ShortInterval, bool);
some_operator!(neq, ShortInterval, ShortInterval, bool);
some_operator!(gte, ShortInterval, ShortInterval, bool);
some_operator!(lte, ShortInterval, ShortInterval, bool);

#[doc(hidden)]
pub fn div_ShortInterval_SqlDecimal<const P: usize, const S: usize>(
    left: ShortInterval,
    right: SqlDecimal<P, S>,
) -> ShortInterval {
    left / right
}

some_polymorphic_function2!(
    div [const P: usize, const S: usize],
    ShortInterval,
    ShortInterval,
    SqlDecimal,
    SqlDecimal<P, S>,
    ShortInterval
);

#[doc(hidden)]
pub fn div_null_ShortInterval_SqlDecimal<const P: usize, const S: usize>(
    left: ShortInterval,
    right: SqlDecimal<P, S>,
) -> Option<ShortInterval> {
    let us = SqlDecimal::<38, 0>::try_from(left.microseconds()).ok()?;
    let div = us.checked_div_generic::<P, S, 38, 0>(right)?;
    let micros: i64 = div.try_into().ok()?;
    Some(ShortInterval::from_microseconds(micros))
}

some_polymorphic_null_function2!(div_null [const P: usize, const S: usize], ShortInterval, ShortInterval, SqlDecimal, SqlDecimal<P, S>, ShortInterval);

#[doc(hidden)]
pub fn times_ShortInterval_i64(left: ShortInterval, right: i64) -> ShortInterval {
    left * right
}

some_polymorphic_function2!(times, ShortInterval, ShortInterval, i64, i64, ShortInterval);

#[doc(hidden)]
pub fn times_ShortInterval_d(left: ShortInterval, right: F64) -> ShortInterval {
    left * right
}

some_polymorphic_function2!(times, ShortInterval, ShortInterval, d, F64, ShortInterval);

#[doc(hidden)]
pub fn times_ShortInterval_SqlDecimal<const P: usize, const S: usize>(
    left: ShortInterval,
    right: SqlDecimal<P, S>,
) -> ShortInterval {
    left * right
}

some_polymorphic_function2!(
    times [const P: usize, const S: usize],
    ShortInterval,
    ShortInterval,
    SqlDecimal,
    SqlDecimal<P, S>,
    ShortInterval
);

#[doc(hidden)]
pub fn div_ShortInterval_d(left: ShortInterval, right: F64) -> ShortInterval {
    left / right
}

some_polymorphic_function2!(div, ShortInterval, ShortInterval, d, F64, ShortInterval);

#[doc(hidden)]
pub fn div_null_ShortInterval_d(left: ShortInterval, right: F64) -> Option<ShortInterval> {
    let div = (left.microseconds() as f64) / right.into_inner();
    let fin: f64 = finite_or_null(div)?;
    if fin < i64::MIN as f64 || fin > i64::MAX as f64 {
        return None;
    }
    Some(ShortInterval::from_microseconds(fin as i64))
}

some_polymorphic_null_function2!(
    div_null,
    ShortInterval,
    ShortInterval,
    d,
    F64,
    ShortInterval
);

#[doc(hidden)]
pub fn div_ShortInterval_i64(left: ShortInterval, right: i64) -> ShortInterval {
    left / right
}

some_polymorphic_function2!(div, ShortInterval, ShortInterval, i64, i64, ShortInterval);

#[doc(hidden)]
pub fn div_null_ShortInterval_i64(left: ShortInterval, right: i64) -> Option<ShortInterval> {
    left.microseconds()
        .checked_div(right)
        .map(ShortInterval::from_microseconds)
}

some_polymorphic_null_function2!(
    div_null,
    ShortInterval,
    ShortInterval,
    i64,
    i64,
    ShortInterval
);

#[doc(hidden)]
pub fn plus_ShortInterval_ShortInterval_ShortInterval__(
    left: ShortInterval,
    right: ShortInterval,
) -> ShortInterval {
    left + right
}

some_function2!(
    plus_ShortInterval_ShortInterval_ShortInterval,
    ShortInterval,
    ShortInterval,
    ShortInterval
);

#[doc(hidden)]
pub fn minus_ShortInterval_ShortInterval_ShortInterval__(
    left: ShortInterval,
    right: ShortInterval,
) -> ShortInterval {
    left - right
}

some_function2!(
    minus_ShortInterval_ShortInterval_ShortInterval,
    ShortInterval,
    ShortInterval,
    ShortInterval
);

/////////////////////////

/// A difference between two [Date]s expressed as a (positive or
/// negative) number of months.  The value of a LongInterval is not
/// absolute, but it is relative to the date the interval is applied
/// to.  For example, an interval of 3 months starting from March 1st
/// has size of 92 days, but starting from April 1st it has a size of
/// 91 days.
#[derive(
    Debug,
    Default,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    SizeOf,
    rkyv::Archive,
    rkyv::Serialize,
    rkyv::Deserialize,
    Serialize,
    Deserialize,
    IsNone,
)]
#[archive_attr(derive(Clone, Ord, Eq, PartialEq, PartialOrd))]
#[archive(compare(PartialEq, PartialOrd))]
#[serde(transparent)]
pub struct LongInterval {
    months: i32,
}

impl LongInterval {
    /// Create a new LongInterval from a number of months.
    pub const fn from_months(months: i32) -> Self {
        Self { months }
    }

    /// Retrieve the number of months in the long interval.
    pub fn months(&self) -> i32 {
        self.months
    }

    /// Retrieve the number of years in the long interval.
    pub fn years(&self) -> i32 {
        let (mul, months) = if self.months() < 0 {
            (-1, -self.months())
        } else {
            (1, self.months())
        };
        (months / 12) * mul
    }
}

impl fmt::Display for LongInterval {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let months = self.months();
        let sign = sign(months < 0);
        let years = months.unsigned_abs() / 12;
        let months = months.unsigned_abs() % 12;
        write!(f, "{sign}{years}-{months:02}")
    }
}

#[doc(hidden)]
pub fn reinterpret_LongInterval(value: LongInterval) -> i64 {
    value.months() as i64
}

some_polymorphic_function1!(reinterpret, LongInterval, LongInterval, i64);

#[doc(hidden)]
pub fn abs_LongInterval(value: LongInterval) -> LongInterval {
    LongInterval::from_months(num::abs(value.months))
}

some_polymorphic_function1!(abs, LongInterval, LongInterval, LongInterval);

/// Multiply a `LongInterval` by an integer producing a `LongInterval`
impl Mul<i32> for LongInterval {
    type Output = Self;

    fn mul(self, rhs: i32) -> Self {
        Self {
            months: self.months * rhs,
        }
    }
}

/// Multiply a `LongInterval` by a numeric value producing a `LongInterval`
impl Mul<F64> for LongInterval {
    type Output = Self;

    fn mul(self, rhs: F64) -> Self {
        Self {
            months: (F64::from(self.months as f64) * rhs).into_inner() as i32,
        }
    }
}

/// Multiply a `LongInterval` by a numeric value producing a `LongInterval`
impl<const P: usize, const S: usize> Mul<SqlDecimal<P, S>> for LongInterval {
    type Output = Self;

    fn mul(self, rhs: SqlDecimal<P, S>) -> Self {
        let months = SqlDecimal::<10, 0>::try_from(self.months).unwrap_or_else(|_| {
            panic!(
                "overflow in long interval multiplication while converting {} to DECIMAL",
                self
            )
        });
        let mul = months
            .checked_mul_generic::<P, S, 10, 0>(rhs)
            .unwrap_or_else(|| panic!("overflow in INTERVAL multiplication {} * {}", self, rhs));
        Self {
            months: mul.try_into().unwrap_or_else(|_| {
                panic!("overflow in INTERVAL multiplication {} * {}", self, rhs)
            }),
        }
    }
}

/// Divide a `LongInterval` by an integer producing a `LongInterval`
impl Div<i32> for LongInterval {
    type Output = Self;

    fn div(self, rhs: i32) -> Self {
        Self {
            months: self.months / rhs,
        }
    }
}

/// Divide a `LongInterval` by a numeric value producing a `LongInterval`
impl Div<F64> for LongInterval {
    type Output = Self;

    fn div(self, rhs: F64) -> Self {
        let result = div_null_LongInterval_d(self, rhs);
        match result {
            None => panic!(
                "overflow while dividing INTERVAL {} / {}",
                self,
                rhs.into_inner()
            ),
            Some(interval) => interval,
        }
    }
}

/// Divide a `LongInterval` by a numeric value producing a `LongInterval`
impl<const P: usize, const S: usize> Div<SqlDecimal<P, S>> for LongInterval {
    type Output = Self;

    fn div(self, rhs: SqlDecimal<P, S>) -> Self {
        let months = SqlDecimal::<10, 0>::try_from(self.months).unwrap_or_else(|_| {
            panic!(
                "overflow in short interval division while converting {} to DECIMAL",
                self
            )
        });
        let div = months
            .checked_div_generic::<P, S, 10, 0>(rhs)
            .unwrap_or_else(|| panic!("overflow in INTERVAL division {} / {}", self, rhs));
        Self {
            months: div
                .try_into()
                .unwrap_or_else(|_| panic!("overflow in INTERVAL division {} / {}", self, rhs)),
        }
    }
}

num_entries_scalar! {
    ShortInterval,
    LongInterval,
}

impl SerializeWithContext<SqlSerdeConfig> for LongInterval {
    fn serialize_with_context<S>(
        &self,
        _serializer: S,
        _context: &SqlSerdeConfig,
    ) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        Err(S::Error::custom(
            "serialization is not implemented for the INTERVAL type",
        ))
    }
}

impl<'de, AUX> DeserializeWithContext<'de, SqlSerdeConfig, AUX> for LongInterval {
    fn deserialize_with_context<D>(
        _deserializer: D,
        _context: &'de SqlSerdeConfig,
    ) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Err(D::Error::custom(
            "deserialization is not implemented for the INTERVAL type",
        ))
    }
}

/// Add two `LongInterval`s
impl Add<LongInterval> for LongInterval {
    type Output = Self;

    fn add(self, rhs: LongInterval) -> Self {
        Self {
            months: self
                .months
                .checked_add(rhs.months)
                .unwrap_or_else(|| panic!("overflow in INTERVAL addition {} + {}", self, rhs)),
        }
    }
}

/// Subtract two `LongInterval`s
impl Sub<LongInterval> for LongInterval {
    type Output = Self;

    fn sub(self, rhs: LongInterval) -> Self {
        Self {
            months: self
                .months
                .checked_sub(rhs.months)
                .unwrap_or_else(|| panic!("overflow in INTERVAL subtraction {} - {}", self, rhs)),
        }
    }
}

/// Negate a `LongInterval`
impl Neg for LongInterval {
    type Output = Self;

    fn neg(self) -> Self {
        Self {
            months: self
                .months
                .checked_neg()
                .unwrap_or_else(|| panic!("overflow in INTERVAL negation -{}", self)),
        }
    }
}

some_operator!(lt, LongInterval, LongInterval, bool);
some_operator!(gt, LongInterval, LongInterval, bool);
some_operator!(eq, LongInterval, LongInterval, bool);
some_operator!(neq, LongInterval, LongInterval, bool);
some_operator!(gte, LongInterval, LongInterval, bool);
some_operator!(lte, LongInterval, LongInterval, bool);

#[doc(hidden)]
pub fn times_LongInterval_i32(left: LongInterval, right: i32) -> LongInterval {
    left * right
}

some_polymorphic_function2!(times, LongInterval, LongInterval, i32, i32, LongInterval);

#[doc(hidden)]
pub fn times_LongInterval_d(left: LongInterval, right: F64) -> LongInterval {
    left * right
}

some_polymorphic_function2!(times, LongInterval, LongInterval, d, F64, LongInterval);

#[doc(hidden)]
pub fn times_LongInterval_SqlDecimal<const P: usize, const S: usize>(
    left: LongInterval,
    right: SqlDecimal<P, S>,
) -> LongInterval {
    left * right
}

some_polymorphic_function2!(
    times [const P: usize, const S: usize],
    LongInterval,
    LongInterval,
    SqlDecimal,
    SqlDecimal<P, S>,
    LongInterval
);

#[doc(hidden)]
pub fn div_LongInterval_i32(left: LongInterval, right: i32) -> LongInterval {
    left / right
}

some_polymorphic_function2!(div, LongInterval, LongInterval, i32, i32, LongInterval);

#[doc(hidden)]
pub fn div_null_LongInterval_i32(left: LongInterval, right: i32) -> Option<LongInterval> {
    left.months
        .checked_div(right)
        .map(LongInterval::from_months)
}

some_polymorphic_null_function2!(div_null, LongInterval, LongInterval, i32, i32, LongInterval);

#[doc(hidden)]
pub fn div_LongInterval_d(left: LongInterval, right: F64) -> LongInterval {
    left / right
}

some_polymorphic_function2!(div, LongInterval, LongInterval, d, F64, LongInterval);

#[doc(hidden)]
pub fn div_null_LongInterval_d(left: LongInterval, right: F64) -> Option<LongInterval> {
    let div: f64 = (left.months() as f64) / right.into_inner();
    let fin: f64 = finite_or_null(div)?;
    if fin < i32::MIN as f64 || fin > i32::MAX as f64 {
        return None;
    }
    Some(LongInterval::from_months(fin as i32))
}

some_polymorphic_null_function2!(div_null, LongInterval, LongInterval, d, F64, LongInterval);

#[doc(hidden)]
pub fn div_LongInterval_SqlDecimal<const P: usize, const S: usize>(
    left: LongInterval,
    right: SqlDecimal<P, S>,
) -> LongInterval {
    left / right
}

some_polymorphic_function2!(
    div [const P: usize, const S: usize],
    LongInterval,
    LongInterval,
    SqlDecimal,
    SqlDecimal<P, S>,
    LongInterval
);

#[doc(hidden)]
pub fn div_null_LongInterval_SqlDecimal<const P: usize, const S: usize>(
    left: LongInterval,
    right: SqlDecimal<P, S>,
) -> Option<LongInterval> {
    let m = SqlDecimal::<38, 0>::try_from(left.months()).ok()?;
    let div = m.checked_div_generic::<P, S, 38, 0>(right)?;
    let months: i32 = div.try_into().ok()?;
    Some(LongInterval::from_months(months))
}

some_polymorphic_null_function2!(div_null [const P: usize, const S: usize], LongInterval, LongInterval, SqlDecimal, SqlDecimal<P, S>, LongInterval);

#[doc(hidden)]
pub fn plus_LongInterval_LongInterval_LongInterval__(
    left: LongInterval,
    right: LongInterval,
) -> LongInterval {
    left + right
}

some_function2!(
    plus_LongInterval_LongInterval_LongInterval,
    LongInterval,
    LongInterval,
    LongInterval
);

#[doc(hidden)]
pub fn minus_LongInterval_LongInterval_LongInterval__(
    left: LongInterval,
    right: LongInterval,
) -> LongInterval {
    left - right
}

some_function2!(
    minus_LongInterval_LongInterval_LongInterval,
    LongInterval,
    LongInterval,
    LongInterval
);

#[doc(hidden)]
pub fn extract_year_LongInterval(value: LongInterval) -> i64 {
    (value.months / 12).into()
}

#[doc(hidden)]
pub fn extract_month_LongInterval(value: LongInterval) -> i64 {
    (value.months % 12).into()
}

#[doc(hidden)]
pub fn extract_quarter_LongInterval(value: LongInterval) -> i64 {
    let dt = Date::from_days(0);
    let dt = plus_Date_Date_LongInterval__(dt, value);
    extract_quarter_Date(dt)
}

#[doc(hidden)]
pub fn extract_decade_LongInterval(value: LongInterval) -> i64 {
    let year = extract_year_LongInterval(value);
    year / 10
}

#[doc(hidden)]
pub fn extract_millennium_LongInterval(value: LongInterval) -> i64 {
    let year = extract_year_LongInterval(value);
    year / 1000 // seems to be a different formula than dates
}

#[doc(hidden)]
pub fn extract_century_LongInterval(value: LongInterval) -> i64 {
    let year = extract_year_LongInterval(value);
    year / 100 // seems to be a different formula than dates
}

#[doc(hidden)]
pub fn extract_day_LongInterval(_value: LongInterval) -> i64 {
    0
}

#[doc(hidden)]
pub fn extract_epoch_LongInterval(value: LongInterval) -> i64 {
    let dt = Date::from_days(0);
    let dt = plus_Date_Date_LongInterval__(dt, value);
    // I think this is right and Postgres is wrong
    extract_epoch_Date(dt)
}

#[doc(hidden)]
pub fn extract_millisecond_LongInterval(_value: LongInterval) -> i64 {
    0
}

#[doc(hidden)]
pub fn extract_microsecond_LongInterval(_value: LongInterval) -> i64 {
    0
}

#[doc(hidden)]
pub fn extract_second_LongInterval(_value: LongInterval) -> i64 {
    0
}

#[doc(hidden)]
pub fn extract_minute_LongInterval(_value: LongInterval) -> i64 {
    0
}

#[doc(hidden)]
pub fn extract_hour_LongInterval(_value: LongInterval) -> i64 {
    0
}

#[doc(hidden)]
pub fn long_interval_to_integer_(value: LongInterval) -> i32 {
    value.months
}

some_function1!(long_interval_to_integer, LongInterval, i32);

#[doc(hidden)]
pub fn integer_to_long_interval_(value: i32) -> LongInterval {
    LongInterval::from_months(value)
}

some_function1!(integer_to_long_interval, i32, LongInterval);

///////////

#[doc(hidden)]
pub fn short_interval_to_integer_(value: ShortInterval) -> i64 {
    value.microseconds
}

some_function1!(short_interval_to_integer, ShortInterval, i64);

#[doc(hidden)]
pub fn integer_to_short_interval_(value: i64) -> ShortInterval {
    ShortInterval::from_microseconds(value)
}

some_function1!(integer_to_short_interval, i64, ShortInterval);

#[doc(hidden)]
pub fn extract_day_ShortInterval(value: ShortInterval) -> i64 {
    value.microseconds() / 86_400_000_000_i64
}

#[doc(hidden)]
pub fn extract_epoch_ShortInterval(value: ShortInterval) -> i64 {
    value.microseconds() / 1_000_000
}

#[doc(hidden)]
pub fn extract_millisecond_ShortInterval(value: ShortInterval) -> i64 {
    (value.microseconds() % 60_000_000_i64) / 1000
}

#[doc(hidden)]
pub fn extract_microsecond_ShortInterval(value: ShortInterval) -> i64 {
    value.microseconds() % 60_000_000_i64
}

#[doc(hidden)]
pub fn extract_second_ShortInterval(value: ShortInterval) -> i64 {
    (value.microseconds() / 1_000_000) % 60
}

#[doc(hidden)]
pub fn extract_minute_ShortInterval(value: ShortInterval) -> i64 {
    (value.microseconds() / 60_000_000_i64) % 60
}

#[doc(hidden)]
pub fn extract_hour_ShortInterval(value: ShortInterval) -> i64 {
    (value.microseconds() / (60 * 60 * 1000 * 1000i64)) % 24
}

some_polymorphic_function1!(extract_year, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_month, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_quarter, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_decade, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_century, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_millennium, LongInterval, LongInterval, i64);

some_polymorphic_function1!(extract_day, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_epoch, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_millisecond, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_microsecond, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_second, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_minute, LongInterval, LongInterval, i64);
some_polymorphic_function1!(extract_hour, LongInterval, LongInterval, i64);

some_polymorphic_function1!(extract_day, ShortInterval, ShortInterval, i64);
some_polymorphic_function1!(extract_epoch, ShortInterval, ShortInterval, i64);
some_polymorphic_function1!(extract_millisecond, ShortInterval, ShortInterval, i64);
some_polymorphic_function1!(extract_microsecond, ShortInterval, ShortInterval, i64);
some_polymorphic_function1!(extract_second, ShortInterval, ShortInterval, i64);
some_polymorphic_function1!(extract_minute, ShortInterval, ShortInterval, i64);
some_polymorphic_function1!(extract_hour, ShortInterval, ShortInterval, i64);