quill_sql/function/aggregate/
avg.rs

1use crate::catalog::DataType;
2use crate::error::{QuillSQLError, QuillSQLResult};
3use crate::function::aggregate::Accumulator;
4use crate::utils::scalar::ScalarValue;
5
6#[derive(Debug, Clone)]
7pub struct AvgAccumulator {
8    sum: Option<f64>,
9    count: u64,
10}
11
12impl AvgAccumulator {
13    pub fn new() -> Self {
14        Self {
15            sum: None,
16            count: 0,
17        }
18    }
19}
20
21impl Accumulator for AvgAccumulator {
22    fn update_value(&mut self, value: &ScalarValue) -> QuillSQLResult<()> {
23        if !value.is_null() {
24            let value = match value.cast_to(&DataType::Float64)? {
25                ScalarValue::Float64(Some(v)) => v,
26                _ => {
27                    return Err(QuillSQLError::Internal(format!(
28                        "Failed to cast value {} to float64",
29                        value
30                    )))
31                }
32            };
33
34            match self.sum {
35                Some(sum) => self.sum = Some(sum + value),
36                None => self.sum = Some(value),
37            }
38            self.count += 1;
39        }
40        Ok(())
41    }
42
43    fn evaluate(&self) -> QuillSQLResult<ScalarValue> {
44        Ok(ScalarValue::Float64(
45            self.sum.map(|f| f / self.count as f64),
46        ))
47    }
48}