Skip to content

Commit

Permalink
Example aggregate allows for NULLs (#638)
Browse files Browse the repository at this point in the history
  • Loading branch information
willmurnane authored Aug 26, 2022
1 parent 559da11 commit d43bc07
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions pgx-examples/aggregate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ impl IntegerAvgState {
mut current: <Self as Aggregate>::State,
arg: <Self as Aggregate>::Args,
) -> <Self as Aggregate>::State {
current.sum += arg;
current.n += 1;
arg.map(|a| {
current.sum += a;
current.n += 1;
});
current
}

Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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),);
}

Expand All @@ -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)]
Expand Down

0 comments on commit d43bc07

Please sign in to comment.