Lines
100 %
Functions
85 %
Branches
//! A stored account as the account-edit form holds it: its parent and every
//! tag, the `name` tag among them, with the revision digesting them.
use finance::tag::Tag;
use sqlx::{Connection, PgConnection, types::Uuid};
use crate::error::ServerError;
use crate::logical::hex_digest;
use crate::snapshot::db_error;
use crate::user::User;
/// The error text of an account edit whose expected revision no longer matches.
pub const STALE_ACCOUNT: &str = "the account changed since it was loaded; reload it";
#[derive(Debug, Clone)]
pub struct StoredAccount {
pub parent: Option<Uuid>,
/// Every tag of the account, sorted by name and value.
pub tags: Vec<Tag>,
}
impl StoredAccount {
/// Digest of the parent and the tags, the name tag included.
#[must_use]
pub fn revision(&self) -> String {
let tags = self.tags.iter().map(|tag| {
format!(
"tag {:?}",
(&tag.tag_name, &tag.tag_value, &tag.description)
)
});
hex_digest(
std::iter::once(format!("parent {:?}", self.parent))
.chain(tags)
.collect(),
/// The account as stored, `None` when the user has no such account.
pub(crate) async fn read_account(
conn: &mut PgConnection,
account_id: Uuid,
) -> Result<Option<StoredAccount>, sqlx::Error> {
let Some(row) = sqlx::query_file!("sql/select/accounts/by_id.sql", account_id)
.fetch_optional(&mut *conn)
.await?
else {
return Ok(None);
};
let mut tags: Vec<Tag> =
sqlx::query_file_as!(Tag, "sql/select/tags/by_account.sql", account_id)
.fetch_all(conn)
.await?;
tags.sort_by(|a, b| (&a.tag_name, &a.tag_value).cmp(&(&b.tag_name, &b.tag_value)));
Ok(Some(StoredAccount {
parent: row.parent,
tags,
}))
impl User {
/// The account's parent and tags as of one instant; `None` when the user
/// has no such account.
///
/// # Errors
/// The connection or a query failing.
pub async fn account_snapshot(
&self,
) -> Result<Option<StoredAccount>, ServerError> {
let mut conn = self.get_connection().await?;
let mut tx = conn
.begin_with("BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY")
.await
.map_err(db_error)?;
let account = read_account(&mut tx, account_id).await.map_err(db_error)?;
tx.rollback().await.map_err(db_error)?;
Ok(account)