Lines
100 %
Functions
76.67 %
Branches
//! Reading the splits of a transaction and their tags.
use std::collections::HashMap;
use finance::split::Split;
use finance::tag::Tag;
use sqlx::PgConnection;
use sqlx::types::Uuid;
use crate::db::DBError;
use crate::error::ServerError;
use crate::user::User;
/// Every stored tag of each split by split id, ordered by name and value; a
/// name with two values keeps both.
///
/// # Errors
/// A query failing.
pub(crate) async fn split_tags_of(
conn: &mut PgConnection,
splits: &[Split],
) -> Result<HashMap<Uuid, Vec<Tag>>, sqlx::Error> {
let mut all = HashMap::with_capacity(splits.len());
for split in splits {
all.insert(split.id, tags_of_split(conn, split.id).await?);
}
Ok(all)
/// The tags of one split on a held connection, in the order of [`split_tags_of`].
/// The query failing.
pub(crate) async fn tags_of_split(
split_id: Uuid,
) -> Result<Vec<Tag>, sqlx::Error> {
sqlx::query_file_as!(Tag, "sql/select/tags/by_split.sql", split_id)
.fetch_all(conn)
.await
/// Logging is left to the caller's boundary, which knows a missing row from a fault.
fn db_error(err: sqlx::Error) -> ServerError {
ServerError::DB(DBError::Sqlx(err))
impl User {
/// Confirms the transaction exists.
/// `RowNotFound` when it does not, or a failing query.
pub async fn require_transaction(&self, tx_id: Uuid) -> Result<(), ServerError> {
let mut conn = self.get_connection().await?;
sqlx::query_file!("sql/select/transactions/by_id.sql", tx_id)
.fetch_one(&mut *conn)
.map_err(db_error)?;
Ok(())
/// Confirms the split exists.
pub async fn require_split(&self, split_id: Uuid) -> Result<(), ServerError> {
sqlx::query_file!("sql/select/splits/tx_id_by_id.sql", &split_id)
/// The splits of a transaction, without their tags.
/// The connection or the query failing.
pub async fn get_transaction_splits(&self, tx_id: Uuid) -> Result<Vec<Split>, ServerError> {
sqlx::query_file_as!(Split, "sql/select/splits/by_transaction.sql", tx_id)
.fetch_all(&mut *conn)
.map_err(db_error)
/// Every stored tag of each of `splits`, as `split_tags_of` reads them.
/// The connection or a query failing.
pub async fn split_tags_of(
&self,
) -> Result<HashMap<Uuid, Vec<Tag>>, ServerError> {
split_tags_of(&mut conn, splits).await.map_err(db_error)
#[cfg(test)]
#[path = "split_tests.rs"]
mod tests;