Fixes division by zero bug by returning NAN for divisions by zero? (#4402)

Co-authored-by: Emmanuel Keller <emmanuel.keller@surrealdb.com>
This commit is contained in:
Albert Marashi 2024-08-02 22:19:46 +09:30 committed by GitHub
parent 842c2aae93
commit e8f55b60f2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 62 additions and 2 deletions

View file

@ -329,7 +329,7 @@ impl Aggregator {
OptimisedAggregate::MathSum => self.math_sum.take().unwrap_or(Value::None),
OptimisedAggregate::MathMean => {
if let Some((v, i)) = self.math_mean.take() {
v.try_div(i.into())?
v.try_div(i.into()).unwrap_or(f64::NAN.into())
} else {
Value::None
}

View file

@ -57,7 +57,7 @@ pub fn mul(a: Value, b: Value) -> Result<Value, Error> {
}
pub fn div(a: Value, b: Value) -> Result<Value, Error> {
a.try_div(b)
Ok(a.try_div(b).unwrap_or(f64::NAN.into()))
}
pub fn rem(a: Value, b: Value) -> Result<Value, Error> {

View file

@ -674,3 +674,63 @@ async fn select_array_count_subquery_group_by() -> Result<(), Error> {
//
Ok(())
}
#[tokio::test]
async fn select_aggregate_mean_update() -> Result<(), Error> {
let sql = "
CREATE test:a SET a = 3;
DEFINE TABLE foo AS SELECT
math::mean(a) AS avg
FROM test
GROUP ALL;
UPDATE test:a SET a = 2;
SELECT avg FROM foo;
";
let dbs = new_ds().await?;
let ses = Session::owner().with_ns("test").with_db("test");
let res = &mut dbs.execute(sql, &ses, None).await?;
assert_eq!(res.len(), 4);
//
let tmp = res.remove(0).result?;
let val = Value::parse(
"[
{
id: test:a,
a: 3
}
]",
);
assert_eq!(tmp, val);
//
let tmp = res.remove(0).result?;
let val = Value::parse("None");
assert_eq!(tmp, val);
let tmp = res.remove(0).result?;
let val = Value::parse(
"[
{
id: test:a,
a: 2
}
]",
);
assert_eq!(tmp, val);
let tmp = res.remove(0).result?;
let val = Value::parse(
"[
{
avg: 2
}
]",
);
assert_eq!(tmp, val);
Ok(())
}