flow/expr/relation/
accum.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
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
// Copyright 2023 Greptime Team
//
// Licensed 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.

//! Accumulators for aggregate functions that's is accumulatable. i.e. sum/count
//!
//! Accumulator will only be restore from row and being updated every time dataflow need process a new batch of rows.
//! So the overhead is acceptable.
//!
//! Currently support sum, count, any, all and min/max(with one caveat that min/max can't support delete with aggregate).
//! TODO: think of better ways to not ser/de every time a accum needed to be updated, since it's in a tight loop

use std::any::type_name;
use std::fmt::Display;

use common_decimal::Decimal128;
use datatypes::data_type::ConcreteDataType;
use datatypes::value::{OrderedF32, OrderedF64, OrderedFloat, Value};
use enum_dispatch::enum_dispatch;
use serde::{Deserialize, Serialize};
use snafu::ensure;

use crate::expr::error::{InternalSnafu, OverflowSnafu, TryFromValueSnafu, TypeMismatchSnafu};
use crate::expr::signature::GenericFn;
use crate::expr::{AggregateFunc, EvalError};
use crate::repr::Diff;

/// Accumulates values for the various types of accumulable aggregations.
#[enum_dispatch]
pub trait Accumulator: Sized {
    fn into_state(self) -> Vec<Value>;

    fn update(
        &mut self,
        aggr_fn: &AggregateFunc,
        value: Value,
        diff: Diff,
    ) -> Result<(), EvalError>;

    fn update_batch<I>(&mut self, aggr_fn: &AggregateFunc, value_diffs: I) -> Result<(), EvalError>
    where
        I: IntoIterator<Item = (Value, Diff)>,
    {
        for (v, d) in value_diffs {
            self.update(aggr_fn, v, d)?;
        }
        Ok(())
    }

    fn eval(&self, aggr_fn: &AggregateFunc) -> Result<Value, EvalError>;
}

/// Bool accumulator, used for `Any` `All` `Max/MinBool`
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Bool {
    /// The number of `true` values observed.
    trues: Diff,
    /// The number of `false` values observed.
    falses: Diff,
}

impl Bool {
    /// Expect two `Diff` type values, one for `true` and one for `false`.
    pub fn try_from_iter<I>(iter: &mut I) -> Result<Self, EvalError>
    where
        I: Iterator<Item = Value>,
    {
        Ok(Self {
            trues: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
            falses: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
        })
    }
}

impl TryFrom<Vec<Value>> for Bool {
    type Error = EvalError;

    fn try_from(state: Vec<Value>) -> Result<Self, Self::Error> {
        ensure!(
            state.len() == 2,
            InternalSnafu {
                reason: "Bool Accumulator state should have 2 values",
            }
        );
        let mut iter = state.into_iter();

        Self::try_from_iter(&mut iter)
    }
}

impl Accumulator for Bool {
    fn into_state(self) -> Vec<Value> {
        vec![self.trues.into(), self.falses.into()]
    }

    /// Null values are ignored
    fn update(
        &mut self,
        aggr_fn: &AggregateFunc,
        value: Value,
        diff: Diff,
    ) -> Result<(), EvalError> {
        ensure!(
            matches!(
                aggr_fn,
                AggregateFunc::Any
                    | AggregateFunc::All
                    | AggregateFunc::MaxBool
                    | AggregateFunc::MinBool
            ),
            InternalSnafu {
                reason: format!(
                    "Bool Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
        );

        match value {
            Value::Boolean(true) => self.trues += diff,
            Value::Boolean(false) => self.falses += diff,
            Value::Null => (), // ignore nulls
            x => {
                return Err(TypeMismatchSnafu {
                    expected: ConcreteDataType::boolean_datatype(),
                    actual: x.data_type(),
                }
                .build());
            }
        };
        Ok(())
    }

    fn eval(&self, aggr_fn: &AggregateFunc) -> Result<Value, EvalError> {
        match aggr_fn {
            AggregateFunc::Any => Ok(Value::from(self.trues > 0)),
            AggregateFunc::All => Ok(Value::from(self.falses == 0)),
            AggregateFunc::MaxBool => Ok(Value::from(self.trues > 0)),
            AggregateFunc::MinBool => Ok(Value::from(self.falses == 0)),
            _ => Err(InternalSnafu {
                reason: format!(
                    "Bool Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
            .build()),
        }
    }
}

/// Accumulates simple numeric values for sum over integer.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SimpleNumber {
    /// The accumulation of all non-NULL values observed.
    accum: i128,
    /// The number of non-NULL values observed.
    non_nulls: Diff,
}

impl SimpleNumber {
    /// Expect one `Decimal128` and one `Diff` type values.
    /// The `Decimal128` type is used to store the sum of all non-NULL values.
    /// The `Diff` type is used to count the number of non-NULL values.
    pub fn try_from_iter<I>(iter: &mut I) -> Result<Self, EvalError>
    where
        I: Iterator<Item = Value>,
    {
        Ok(Self {
            accum: Decimal128::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?
                .val(),
            non_nulls: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
        })
    }
}

impl TryFrom<Vec<Value>> for SimpleNumber {
    type Error = EvalError;

    fn try_from(state: Vec<Value>) -> Result<Self, Self::Error> {
        ensure!(
            state.len() == 2,
            InternalSnafu {
                reason: "Number Accumulator state should have 2 values",
            }
        );
        let mut iter = state.into_iter();
        Self::try_from_iter(&mut iter)
    }
}

impl Accumulator for SimpleNumber {
    fn into_state(self) -> Vec<Value> {
        vec![
            Value::Decimal128(Decimal128::new(self.accum, 38, 0)),
            self.non_nulls.into(),
        ]
    }

    fn update(
        &mut self,
        aggr_fn: &AggregateFunc,
        value: Value,
        diff: Diff,
    ) -> Result<(), EvalError> {
        ensure!(
            matches!(
                aggr_fn,
                AggregateFunc::SumInt16
                    | AggregateFunc::SumInt32
                    | AggregateFunc::SumInt64
                    | AggregateFunc::SumUInt16
                    | AggregateFunc::SumUInt32
                    | AggregateFunc::SumUInt64
            ),
            InternalSnafu {
                reason: format!(
                    "SimpleNumber Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
        );

        let v = match (aggr_fn, value) {
            (AggregateFunc::SumInt16, Value::Int16(x)) => i128::from(x),
            (AggregateFunc::SumInt32, Value::Int32(x)) => i128::from(x),
            (AggregateFunc::SumInt64, Value::Int64(x)) => i128::from(x),
            (AggregateFunc::SumUInt16, Value::UInt16(x)) => i128::from(x),
            (AggregateFunc::SumUInt32, Value::UInt32(x)) => i128::from(x),
            (AggregateFunc::SumUInt64, Value::UInt64(x)) => i128::from(x),
            (_f, Value::Null) => return Ok(()), // ignore null
            (f, v) => {
                let expected_datatype = f.signature().input;
                return Err(TypeMismatchSnafu {
                    expected: expected_datatype[0].clone(),
                    actual: v.data_type(),
                }
                .build())?;
            }
        };

        self.accum += v * i128::from(diff);

        self.non_nulls += diff;
        Ok(())
    }

    fn eval(&self, aggr_fn: &AggregateFunc) -> Result<Value, EvalError> {
        match aggr_fn {
            AggregateFunc::SumInt16 | AggregateFunc::SumInt32 | AggregateFunc::SumInt64 => {
                i64::try_from(self.accum)
                    .map_err(|_e| OverflowSnafu {}.build())
                    .map(Value::from)
            }
            AggregateFunc::SumUInt16 | AggregateFunc::SumUInt32 | AggregateFunc::SumUInt64 => {
                u64::try_from(self.accum)
                    .map_err(|_e| OverflowSnafu {}.build())
                    .map(Value::from)
            }
            _ => Err(InternalSnafu {
                reason: format!(
                    "SimpleNumber Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
            .build()),
        }
    }
}
/// Accumulates float values for sum over floating numbers.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Float {
    /// Accumulates non-special float values, i.e. not NaN, +inf, -inf.
    /// accum will be set to zero if `non_nulls` is zero.
    accum: OrderedF64,
    /// Counts +inf
    pos_infs: Diff,
    /// Counts -inf
    neg_infs: Diff,
    /// Counts NaNs
    nans: Diff,
    /// Counts non-NULL values
    non_nulls: Diff,
}

impl Float {
    /// Expect first value to be `OrderedF64` and the rest four values to be `Diff` type values.
    pub fn try_from_iter<I>(iter: &mut I) -> Result<Self, EvalError>
    where
        I: Iterator<Item = Value>,
    {
        let mut ret = Self {
            accum: OrderedF64::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
            pos_infs: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
            neg_infs: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
            nans: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
            non_nulls: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
        };

        // This prevent counter-intuitive behavior of summing over no values having non-zero results
        if ret.non_nulls == 0 {
            ret.accum = OrderedFloat::from(0.0);
        }

        Ok(ret)
    }
}

impl TryFrom<Vec<Value>> for Float {
    type Error = EvalError;

    fn try_from(state: Vec<Value>) -> Result<Self, Self::Error> {
        ensure!(
            state.len() == 5,
            InternalSnafu {
                reason: "Float Accumulator state should have 5 values",
            }
        );

        let mut iter = state.into_iter();

        let mut ret = Self {
            accum: OrderedF64::try_from(iter.next().unwrap()).map_err(err_try_from_val)?,
            pos_infs: Diff::try_from(iter.next().unwrap()).map_err(err_try_from_val)?,
            neg_infs: Diff::try_from(iter.next().unwrap()).map_err(err_try_from_val)?,
            nans: Diff::try_from(iter.next().unwrap()).map_err(err_try_from_val)?,
            non_nulls: Diff::try_from(iter.next().unwrap()).map_err(err_try_from_val)?,
        };

        // This prevent counter-intuitive behavior of summing over no values
        if ret.non_nulls == 0 {
            ret.accum = OrderedFloat::from(0.0);
        }

        Ok(ret)
    }
}

impl Accumulator for Float {
    fn into_state(self) -> Vec<Value> {
        vec![
            self.accum.into(),
            self.pos_infs.into(),
            self.neg_infs.into(),
            self.nans.into(),
            self.non_nulls.into(),
        ]
    }

    /// sum ignore null
    fn update(
        &mut self,
        aggr_fn: &AggregateFunc,
        value: Value,
        diff: Diff,
    ) -> Result<(), EvalError> {
        ensure!(
            matches!(
                aggr_fn,
                AggregateFunc::SumFloat32 | AggregateFunc::SumFloat64
            ),
            InternalSnafu {
                reason: format!(
                    "Float Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
        );

        let x = match (aggr_fn, value) {
            (AggregateFunc::SumFloat32, Value::Float32(x)) => OrderedF64::from(*x as f64),
            (AggregateFunc::SumFloat64, Value::Float64(x)) => OrderedF64::from(x),
            (_f, Value::Null) => return Ok(()), // ignore null
            (f, v) => {
                let expected_datatype = f.signature().input;
                return Err(TypeMismatchSnafu {
                    expected: expected_datatype[0].clone(),
                    actual: v.data_type(),
                }
                .build())?;
            }
        };

        if x.is_nan() {
            self.nans += diff;
        } else if x.is_infinite() {
            if x.is_sign_positive() {
                self.pos_infs += diff;
            } else {
                self.neg_infs += diff;
            }
        } else {
            self.accum += *(x * OrderedF64::from(diff as f64));
        }

        self.non_nulls += diff;
        Ok(())
    }

    fn eval(&self, aggr_fn: &AggregateFunc) -> Result<Value, EvalError> {
        match aggr_fn {
            AggregateFunc::SumFloat32 => Ok(Value::Float32(OrderedF32::from(self.accum.0 as f32))),
            AggregateFunc::SumFloat64 => Ok(Value::Float64(self.accum)),
            _ => Err(InternalSnafu {
                reason: format!(
                    "Float Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
            .build()),
        }
    }
}

/// Accumulates a single `Ord`ed `Value`, useful for min/max aggregations.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct OrdValue {
    val: Option<Value>,
    non_nulls: Diff,
}

impl OrdValue {
    pub fn try_from_iter<I>(iter: &mut I) -> Result<Self, EvalError>
    where
        I: Iterator<Item = Value>,
    {
        Ok(Self {
            val: {
                let v = iter.next().ok_or_else(fail_accum::<Self>)?;
                if v == Value::Null {
                    None
                } else {
                    Some(v)
                }
            },
            non_nulls: Diff::try_from(iter.next().ok_or_else(fail_accum::<Self>)?)
                .map_err(err_try_from_val)?,
        })
    }
}

impl TryFrom<Vec<Value>> for OrdValue {
    type Error = EvalError;

    fn try_from(state: Vec<Value>) -> Result<Self, Self::Error> {
        ensure!(
            state.len() == 2,
            InternalSnafu {
                reason: "OrdValue Accumulator state should have 2 values",
            }
        );

        let mut iter = state.into_iter();

        Ok(Self {
            val: {
                let v = iter.next().unwrap();
                if v == Value::Null {
                    None
                } else {
                    Some(v)
                }
            },
            non_nulls: Diff::try_from(iter.next().unwrap()).map_err(err_try_from_val)?,
        })
    }
}

impl Accumulator for OrdValue {
    fn into_state(self) -> Vec<Value> {
        vec![self.val.unwrap_or(Value::Null), self.non_nulls.into()]
    }

    /// min/max try to find results in all non-null values, if all values are null, the result is null.
    /// count(col_name) gives the number of non-null values, count(*) gives the number of rows including nulls.
    /// TODO(discord9): add count(*) as a aggr function
    fn update(
        &mut self,
        aggr_fn: &AggregateFunc,
        value: Value,
        diff: Diff,
    ) -> Result<(), EvalError> {
        ensure!(
            aggr_fn.is_max() || aggr_fn.is_min() || matches!(aggr_fn, AggregateFunc::Count),
            InternalSnafu {
                reason: format!(
                    "OrdValue Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
        );
        if diff <= 0 && (aggr_fn.is_max() || aggr_fn.is_min()) {
            return Err(InternalSnafu {
                reason: "OrdValue Accumulator does not support non-monotonic input for min/max aggregation".to_string(),
            }.build());
        }

        // if aggr_fn is count, the incoming value type doesn't matter in type checking
        // otherwise, type need to be the same or value can be null
        let check_type_aggr_fn_and_arg_value =
            ty_eq_without_precision(value.data_type(), aggr_fn.signature().input[0].clone())
                || matches!(aggr_fn, AggregateFunc::Count)
                || value.is_null();
        let check_type_aggr_fn_and_self_val = self
            .val
            .as_ref()
            .map(|zelf| {
                ty_eq_without_precision(zelf.data_type(), aggr_fn.signature().input[0].clone())
            })
            .unwrap_or(true)
            || matches!(aggr_fn, AggregateFunc::Count);

        if !check_type_aggr_fn_and_arg_value {
            return Err(TypeMismatchSnafu {
                expected: aggr_fn.signature().input[0].clone(),
                actual: value.data_type(),
            }
            .build());
        } else if !check_type_aggr_fn_and_self_val {
            return Err(TypeMismatchSnafu {
                expected: aggr_fn.signature().input[0].clone(),
                actual: self
                    .val
                    .as_ref()
                    .map(|v| v.data_type())
                    .unwrap_or(ConcreteDataType::null_datatype()),
            }
            .build());
        }

        let is_null = value.is_null();
        if is_null {
            return Ok(());
        }

        if !is_null {
            // compile count(*) to count(true) to include null/non-nulls
            // And the counts of non-null values are updated here
            self.non_nulls += diff;

            match aggr_fn.signature().generic_fn {
                GenericFn::Max => {
                    self.val = self
                        .val
                        .clone()
                        .map(|v| v.max(value.clone()))
                        .or_else(|| Some(value))
                }
                GenericFn::Min => {
                    self.val = self
                        .val
                        .clone()
                        .map(|v| v.min(value.clone()))
                        .or_else(|| Some(value))
                }

                GenericFn::Count => (),
                _ => unreachable!("already checked by ensure!"),
            }
        };
        // min/max ignore nulls

        Ok(())
    }

    fn eval(&self, aggr_fn: &AggregateFunc) -> Result<Value, EvalError> {
        if aggr_fn.is_max() || aggr_fn.is_min() {
            Ok(self.val.clone().unwrap_or(Value::Null))
        } else if matches!(aggr_fn, AggregateFunc::Count) {
            Ok(self.non_nulls.into())
        } else {
            Err(InternalSnafu {
                reason: format!(
                    "OrdValue Accumulator does not support this aggregation function: {:?}",
                    aggr_fn
                ),
            }
            .build())
        }
    }
}

/// Accumulates values for the various types of accumulable aggregations.
///
/// We assume that there are not more than 2^32 elements for the aggregation.
/// Thus we can perform a summation over i32 in an i64 accumulator
/// and not worry about exceeding its bounds.
///
/// The float accumulator performs accumulation with tolerance for floating point error.
///
/// TODO(discord9): check for overflowing
#[enum_dispatch(Accumulator)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Accum {
    /// Accumulates boolean values.
    Bool(Bool),
    /// Accumulates simple numeric values.
    SimpleNumber(SimpleNumber),
    /// Accumulates float values.
    Float(Float),
    /// Accumulate Values that impl `Ord`
    OrdValue(OrdValue),
}

impl Accum {
    /// create a new accumulator from given aggregate function
    pub fn new_accum(aggr_fn: &AggregateFunc) -> Result<Self, EvalError> {
        Ok(match aggr_fn {
            AggregateFunc::Any
            | AggregateFunc::All
            | AggregateFunc::MaxBool
            | AggregateFunc::MinBool => Self::from(Bool {
                trues: 0,
                falses: 0,
            }),
            AggregateFunc::SumInt16
            | AggregateFunc::SumInt32
            | AggregateFunc::SumInt64
            | AggregateFunc::SumUInt16
            | AggregateFunc::SumUInt32
            | AggregateFunc::SumUInt64 => Self::from(SimpleNumber {
                accum: 0,
                non_nulls: 0,
            }),
            AggregateFunc::SumFloat32 | AggregateFunc::SumFloat64 => Self::from(Float {
                accum: OrderedF64::from(0.0),
                pos_infs: 0,
                neg_infs: 0,
                nans: 0,
                non_nulls: 0,
            }),
            f if f.is_max() || f.is_min() || matches!(f, AggregateFunc::Count) => {
                Self::from(OrdValue {
                    val: None,
                    non_nulls: 0,
                })
            }
            f => {
                return Err(InternalSnafu {
                    reason: format!(
                        "Accumulator does not support this aggregation function: {:?}",
                        f
                    ),
                }
                .build());
            }
        })
    }

    pub fn try_from_iter(
        aggr_fn: &AggregateFunc,
        iter: &mut impl Iterator<Item = Value>,
    ) -> Result<Self, EvalError> {
        match aggr_fn {
            AggregateFunc::Any
            | AggregateFunc::All
            | AggregateFunc::MaxBool
            | AggregateFunc::MinBool => Ok(Self::from(Bool::try_from_iter(iter)?)),
            AggregateFunc::SumInt16
            | AggregateFunc::SumInt32
            | AggregateFunc::SumInt64
            | AggregateFunc::SumUInt16
            | AggregateFunc::SumUInt32
            | AggregateFunc::SumUInt64 => Ok(Self::from(SimpleNumber::try_from_iter(iter)?)),
            AggregateFunc::SumFloat32 | AggregateFunc::SumFloat64 => {
                Ok(Self::from(Float::try_from_iter(iter)?))
            }
            f if f.is_max() || f.is_min() || matches!(f, AggregateFunc::Count) => {
                Ok(Self::from(OrdValue::try_from_iter(iter)?))
            }
            f => Err(InternalSnafu {
                reason: format!(
                    "Accumulator does not support this aggregation function: {:?}",
                    f
                ),
            }
            .build()),
        }
    }

    /// try to convert a vector of value into given aggregate function's accumulator
    pub fn try_into_accum(aggr_fn: &AggregateFunc, state: Vec<Value>) -> Result<Self, EvalError> {
        match aggr_fn {
            AggregateFunc::Any
            | AggregateFunc::All
            | AggregateFunc::MaxBool
            | AggregateFunc::MinBool => Ok(Self::from(Bool::try_from(state)?)),
            AggregateFunc::SumInt16
            | AggregateFunc::SumInt32
            | AggregateFunc::SumInt64
            | AggregateFunc::SumUInt16
            | AggregateFunc::SumUInt32
            | AggregateFunc::SumUInt64 => Ok(Self::from(SimpleNumber::try_from(state)?)),
            AggregateFunc::SumFloat32 | AggregateFunc::SumFloat64 => {
                Ok(Self::from(Float::try_from(state)?))
            }
            f if f.is_max() || f.is_min() || matches!(f, AggregateFunc::Count) => {
                Ok(Self::from(OrdValue::try_from(state)?))
            }
            f => Err(InternalSnafu {
                reason: format!(
                    "Accumulator does not support this aggregation function: {:?}",
                    f
                ),
            }
            .build()),
        }
    }
}

fn fail_accum<T>() -> EvalError {
    InternalSnafu {
        reason: format!(
            "list of values exhausted before a accum of type {} can be build from it",
            type_name::<T>()
        ),
    }
    .build()
}

fn err_try_from_val<T: Display>(reason: T) -> EvalError {
    TryFromValueSnafu {
        msg: reason.to_string(),
    }
    .build()
}

/// compare type while ignore their precision, including `TimeStamp`, `Time`,
/// `Duration`, `Interval`
fn ty_eq_without_precision(left: ConcreteDataType, right: ConcreteDataType) -> bool {
    left == right
        || matches!(left, ConcreteDataType::Timestamp(..))
            && matches!(right, ConcreteDataType::Timestamp(..))
        || matches!(left, ConcreteDataType::Time(..)) && matches!(right, ConcreteDataType::Time(..))
        || matches!(left, ConcreteDataType::Duration(..))
            && matches!(right, ConcreteDataType::Duration(..))
        || matches!(left, ConcreteDataType::Interval(..))
            && matches!(right, ConcreteDataType::Interval(..))
}

#[allow(clippy::too_many_lines)]
#[cfg(test)]
mod test {
    use common_time::Timestamp;

    use super::*;

    #[test]
    fn test_accum() {
        let testcases = vec![
            (
                AggregateFunc::SumInt32,
                vec![(Value::Int32(1), 1), (Value::Null, 1)],
                (
                    Value::Int64(1),
                    vec![Value::Decimal128(Decimal128::new(1, 38, 0)), 1i64.into()],
                ),
            ),
            (
                AggregateFunc::SumFloat32,
                vec![(Value::Float32(OrderedF32::from(1.0)), 1), (Value::Null, 1)],
                (
                    Value::Float32(OrderedF32::from(1.0)),
                    vec![
                        Value::Float64(OrderedF64::from(1.0)),
                        0i64.into(),
                        0i64.into(),
                        0i64.into(),
                        1i64.into(),
                    ],
                ),
            ),
            (
                AggregateFunc::MaxInt32,
                vec![(Value::Int32(1), 1), (Value::Int32(2), 1), (Value::Null, 1)],
                (Value::Int32(2), vec![Value::Int32(2), 2i64.into()]),
            ),
            (
                AggregateFunc::MinInt32,
                vec![(Value::Int32(2), 1), (Value::Int32(1), 1), (Value::Null, 1)],
                (Value::Int32(1), vec![Value::Int32(1), 2i64.into()]),
            ),
            (
                AggregateFunc::MaxFloat32,
                vec![
                    (Value::Float32(OrderedF32::from(1.0)), 1),
                    (Value::Float32(OrderedF32::from(2.0)), 1),
                    (Value::Null, 1),
                ],
                (
                    Value::Float32(OrderedF32::from(2.0)),
                    vec![Value::Float32(OrderedF32::from(2.0)), 2i64.into()],
                ),
            ),
            (
                AggregateFunc::MaxDateTime,
                vec![
                    (Value::Timestamp(Timestamp::from(0)), 1),
                    (Value::Timestamp(Timestamp::from(1)), 1),
                    (Value::Null, 1),
                ],
                (
                    Value::Timestamp(Timestamp::from(1)),
                    vec![Value::Timestamp(Timestamp::from(1)), 2i64.into()],
                ),
            ),
            (
                AggregateFunc::Count,
                vec![
                    (Value::Int32(1), 1),
                    (Value::Int32(2), 1),
                    (Value::Null, 1),
                    (Value::Null, 1),
                ],
                (2i64.into(), vec![Value::Null, 2i64.into()]),
            ),
            (
                AggregateFunc::Any,
                vec![
                    (Value::Boolean(false), 1),
                    (Value::Boolean(false), 1),
                    (Value::Boolean(true), 1),
                    (Value::Null, 1),
                ],
                (
                    Value::Boolean(true),
                    vec![Value::from(1i64), Value::from(2i64)],
                ),
            ),
            (
                AggregateFunc::All,
                vec![
                    (Value::Boolean(false), 1),
                    (Value::Boolean(false), 1),
                    (Value::Boolean(true), 1),
                    (Value::Null, 1),
                ],
                (
                    Value::Boolean(false),
                    vec![Value::from(1i64), Value::from(2i64)],
                ),
            ),
            (
                AggregateFunc::MaxBool,
                vec![
                    (Value::Boolean(false), 1),
                    (Value::Boolean(false), 1),
                    (Value::Boolean(true), 1),
                    (Value::Null, 1),
                ],
                (
                    Value::Boolean(true),
                    vec![Value::from(1i64), Value::from(2i64)],
                ),
            ),
            (
                AggregateFunc::MinBool,
                vec![
                    (Value::Boolean(false), 1),
                    (Value::Boolean(false), 1),
                    (Value::Boolean(true), 1),
                    (Value::Null, 1),
                ],
                (
                    Value::Boolean(false),
                    vec![Value::from(1i64), Value::from(2i64)],
                ),
            ),
        ];

        for (aggr_fn, input, (eval_res, state)) in testcases {
            let create_and_insert = || -> Result<Accum, EvalError> {
                let mut acc = Accum::new_accum(&aggr_fn)?;
                acc.update_batch(&aggr_fn, input.clone())?;
                let row = acc.into_state();
                let acc = Accum::try_into_accum(&aggr_fn, row.clone())?;
                let alter_acc = Accum::try_from_iter(&aggr_fn, &mut row.into_iter())?;
                assert_eq!(acc, alter_acc);
                Ok(acc)
            };
            let acc = match create_and_insert() {
                Ok(acc) => acc,
                Err(err) => panic!(
                    "Failed to create accum for {:?} with input {:?} with error: {:?}",
                    aggr_fn, input, err
                ),
            };

            if acc.eval(&aggr_fn).unwrap() != eval_res {
                panic!(
                    "Failed to eval accum for {:?} with input {:?}, expect {:?}, got {:?}",
                    aggr_fn,
                    input,
                    eval_res,
                    acc.eval(&aggr_fn).unwrap()
                );
            }
            let actual_state = acc.into_state();
            if actual_state != state {
                panic!(
                    "Failed to cast into state from accum for {:?} with input {:?}, expect state {:?}, got state {:?}",
                    aggr_fn,
                    input,
                    state,
                    actual_state
                );
            }
        }
    }
    #[test]
    fn test_fail_path_accum() {
        {
            let bool_accum = Bool::try_from(vec![Value::Null]);
            assert!(matches!(bool_accum, Err(EvalError::Internal { .. })));
        }

        {
            let mut bool_accum = Bool::try_from(vec![1i64.into(), 1i64.into()]).unwrap();
            // serde
            let bool_accum_serde = serde_json::to_string(&bool_accum).unwrap();
            let bool_accum_de = serde_json::from_str::<Bool>(&bool_accum_serde).unwrap();
            assert_eq!(bool_accum, bool_accum_de);
            assert!(matches!(
                bool_accum.update(&AggregateFunc::MaxDate, 1.into(), 1),
                Err(EvalError::Internal { .. })
            ));
            assert!(matches!(
                bool_accum.update(&AggregateFunc::Any, 1.into(), 1),
                Err(EvalError::TypeMismatch { .. })
            ));
            assert!(matches!(
                bool_accum.eval(&AggregateFunc::MaxDate),
                Err(EvalError::Internal { .. })
            ));
        }

        {
            let ret = SimpleNumber::try_from(vec![Value::Null]);
            assert!(matches!(ret, Err(EvalError::Internal { .. })));
            let mut accum =
                SimpleNumber::try_from(vec![Decimal128::new(0, 38, 0).into(), 0i64.into()])
                    .unwrap();

            assert!(matches!(
                accum.update(&AggregateFunc::All, 0.into(), 1),
                Err(EvalError::Internal { .. })
            ));
            assert!(matches!(
                accum.update(&AggregateFunc::SumInt64, 0i32.into(), 1),
                Err(EvalError::TypeMismatch { .. })
            ));
            assert!(matches!(
                accum.eval(&AggregateFunc::All),
                Err(EvalError::Internal { .. })
            ));
            accum
                .update(&AggregateFunc::SumInt64, 1i64.into(), 1)
                .unwrap();
            accum
                .update(&AggregateFunc::SumInt64, i64::MAX.into(), 1)
                .unwrap();
            assert!(matches!(
                accum.eval(&AggregateFunc::SumInt64),
                Err(EvalError::Overflow { .. })
            ));
        }

        {
            let ret = Float::try_from(vec![2f64.into(), 0i64.into(), 0i64.into(), 0i64.into()]);
            assert!(matches!(ret, Err(EvalError::Internal { .. })));
            let mut accum = Float::try_from(vec![
                2f64.into(),
                0i64.into(),
                0i64.into(),
                0i64.into(),
                1i64.into(),
            ])
            .unwrap();
            accum
                .update(&AggregateFunc::SumFloat64, 2f64.into(), -1)
                .unwrap();
            assert!(matches!(
                accum.update(&AggregateFunc::All, 0.into(), 1),
                Err(EvalError::Internal { .. })
            ));
            assert!(matches!(
                accum.update(&AggregateFunc::SumFloat64, 0.0f32.into(), 1),
                Err(EvalError::TypeMismatch { .. })
            ));
            // no record, no accum
            assert_eq!(
                accum.eval(&AggregateFunc::SumFloat64).unwrap(),
                0.0f64.into()
            );

            assert!(matches!(
                accum.eval(&AggregateFunc::All),
                Err(EvalError::Internal { .. })
            ));

            accum
                .update(&AggregateFunc::SumFloat64, f64::INFINITY.into(), 1)
                .unwrap();
            accum
                .update(&AggregateFunc::SumFloat64, (-f64::INFINITY).into(), 1)
                .unwrap();
            accum
                .update(&AggregateFunc::SumFloat64, f64::NAN.into(), 1)
                .unwrap();
        }

        {
            let ret = OrdValue::try_from(vec![Value::Null]);
            assert!(matches!(ret, Err(EvalError::Internal { .. })));
            let mut accum = OrdValue::try_from(vec![Value::Null, 0i64.into()]).unwrap();
            assert!(matches!(
                accum.update(&AggregateFunc::All, 0.into(), 1),
                Err(EvalError::Internal { .. })
            ));
            accum
                .update(&AggregateFunc::MaxInt16, 1i16.into(), 1)
                .unwrap();
            assert!(matches!(
                accum.update(&AggregateFunc::MaxInt16, 0i32.into(), 1),
                Err(EvalError::TypeMismatch { .. })
            ));
            assert!(matches!(
                accum.update(&AggregateFunc::MaxInt16, 0i16.into(), -1),
                Err(EvalError::Internal { .. })
            ));
            accum
                .update(&AggregateFunc::MaxInt16, Value::Null, 1)
                .unwrap();
        }

        // insert uint64 into max_int64 should fail
        {
            let mut accum = OrdValue::try_from(vec![Value::Null, 0i64.into()]).unwrap();
            assert!(matches!(
                accum.update(&AggregateFunc::MaxInt64, 0u64.into(), 1),
                Err(EvalError::TypeMismatch { .. })
            ));
        }
    }
}