Lines
100 %
Functions
85 %
Branches
//! A stored commodity as the commodity-edit form holds it: every tag, the
//! `symbol` and `name` tags 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 a commodity edit whose expected revision no longer matches.
pub const STALE_COMMODITY: &str = "the commodity changed since it was loaded; reload it";
#[derive(Debug, Clone)]
pub struct StoredCommodity {
/// Every tag of the commodity, sorted by name and value.
pub tags: Vec<Tag>,
}
impl StoredCommodity {
/// Digest of the tags with their descriptions.
#[must_use]
pub fn revision(&self) -> String {
hex_digest(
self.tags
.iter()
.map(|tag| {
format!(
"tag {:?}",
(&tag.tag_name, &tag.tag_value, &tag.description)
)
})
.collect(),
/// The commodity as stored, `None` when the user has no such commodity.
pub(crate) async fn read_commodity(
conn: &mut PgConnection,
commodity_id: Uuid,
) -> Result<Option<StoredCommodity>, sqlx::Error> {
if sqlx::query_file!("sql/select/commodities/by_id.sql", commodity_id)
.fetch_optional(&mut *conn)
.await?
.is_none()
{
return Ok(None);
let mut tags = sqlx::query_file_as!(Tag, "sql/select/tags/by_commodity.sql", commodity_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(StoredCommodity { tags }))
impl User {
/// The commodity's tags as of one instant; `None` when the user has no
/// such commodity.
///
/// # Errors
/// The connection or a query failing.
pub async fn commodity_snapshot(
&self,
) -> Result<Option<StoredCommodity>, 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 commodity = read_commodity(&mut tx, commodity_id)
tx.rollback().await.map_err(db_error)?;
Ok(commodity)