Skip to content

Commit 89a0769

Browse files
committed
Remove sum() from SQL
Instead perform the sum in rust. TODO: to avoid math performed outside of rust, propose a change to stream amounts from the storage and perform all math outside of the storage layer, effectively in rust (wallet or mint)
1 parent a04ee46 commit 89a0769

2 files changed

Lines changed: 10 additions & 13 deletions

File tree

crates/cdk-sql-common/src/stmt.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ impl Statement {
367367
Ok(self)
368368
}
369369

370-
/// Executes a query and returns the affected rows
370+
/// Fetches the first row and column from a query
371371
pub async fn pluck<C>(self, conn: &C) -> Result<Option<Value>, Error>
372372
where
373373
C: DatabaseExecutor,

crates/cdk-sql-common/src/wallet/mod.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -583,21 +583,18 @@ where
583583
}
584584

585585
let balance = q
586-
.pluck(&*conn)
586+
.fetch_all(&*conn)
587587
.await?
588-
.map(|n| {
588+
.into_iter()
589+
.map(|row| {
589590
// SQLite SUM returns INTEGER which we need to convert to u64
590-
match n {
591-
crate::stmt::Column::Integer(i) => Ok(i as u64),
592-
crate::stmt::Column::Real(f) => Ok(f as u64),
593-
_ => Err(Error::Database(Box::new(std::io::Error::new(
594-
std::io::ErrorKind::InvalidData,
595-
"Invalid balance type",
596-
)))),
597-
}
591+
unpack_into!(let (amount) = row);
592+
let r: u64 = column_as_number!(amount);
593+
Ok::<_, Error>(r)
598594
})
599-
.transpose()?
600-
.unwrap_or(0);
595+
.collect::<Result<Vec<_>, _>>()?
596+
.into_iter()
597+
.sum();
601598

602599
Ok(balance)
603600
}

0 commit comments

Comments
 (0)