Example aggregate allows for NULLs
@@ -26,8 +26,10 @@ impl IntegerAvgState {
mut current: <Self as Aggregate>::State,
arg: <Self as Aggregate>::Args,
) -> <Self as Aggregate>::State {
- current.sum += arg;
+ arg.map(|a| {
+ current.sum += a;
current.n += 1;
+ });
current
}
@@ -70,7 +72,7 @@ impl PgVarlenaInOutFuncs for IntegerAvgState {
#[pg_aggregate]
impl Aggregate for IntegerAvgState {
type State = PgVarlena<Self>;
- type Args = pgx::name!(value, i32);
+ type Args = pgx::name!(value, Option<i32>);
const NAME: &'static str = "DEMOAVG";
const INITIAL_CONDITION: Option<&'static str> = Some("0,0");
@@ -146,9 +148,9 @@ mod tests {
#[pg_test]
fn test_integer_avg_state() {
let avg_state = PgVarlena::<IntegerAvgState>::default();
- let avg_state = IntegerAvgState::state(avg_state, 1);
- let avg_state = IntegerAvgState::state(avg_state, 2);
- let avg_state = IntegerAvgState::state(avg_state, 3);
+ let avg_state = IntegerAvgState::state(avg_state, Some(1));
+ let avg_state = IntegerAvgState::state(avg_state, Some(2));
+ let avg_state = IntegerAvgState::state(avg_state, Some(3));
assert_eq!(2, IntegerAvgState::finalize(avg_state),);
}
@@ -160,6 +162,14 @@ mod tests {
.expect("SQL select failed");
assert_eq!(retval, 2);
}
+ #[pg_test]
+ fn test_integer_avg_with_null() {
+ Spi::run("CREATE TABLE demo_table (value INTEGER);");
+ Spi::run("INSERT INTO demo_table (value) VALUES (1), (NULL), (3);");
+ let retval = Spi::get_one::<i32>("SELECT DEMOAVG(value) FROM demo_table;")
+ .expect("SQL select failed");
+ assert_eq!(retval, 2);
+ }
}
#[cfg(test)]
