use super::{DbError, FromDb, Row};
use crate::money::{Currency, Money};
pub trait FromRow: Sized {
fn from_row(row: &Row) -> Result<Self, DbError>;
}
macro_rules! tuple {
($($t:ident $i:tt),+) => {
impl<$($t: FromDb),+> FromRow for ($($t,)+) {
fn from_row(row: &Row) -> Result<Self, DbError> {
Ok(($(row.try_get::<$t>($i)?,)+))
}
}
};
}
tuple!(A 0);
tuple!(A 0, B 1);
tuple!(A 0, B 1, C 2);
tuple!(A 0, B 1, C 2, D 3);
tuple!(A 0, B 1, C 2, D 3, E 4);
tuple!(A 0, B 1, C 2, D 3, E 4, F 5);
tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6);
impl Row {
pub fn try_get_money(&self, amount: &str, currency: &str) -> Result<Money, DbError> {
let minor: i64 = self.try_get(amount)?;
let code: String = self.try_get(currency)?;
money_from_parts(minor, &code, currency)
}
pub fn try_get_money_opt(
&self,
amount: &str,
currency: &str,
) -> Result<Option<Money>, DbError> {
let minor: Option<i64> = self.try_get(amount)?;
let code: Option<String> = self.try_get(currency)?;
match (minor, code) {
(None, None) => Ok(None),
(Some(minor), Some(code)) => money_from_parts(minor, &code, currency).map(Some),
_ => Err(decode_error(format!(
"`{amount}` and `{currency}` must be both set or both NULL"
))),
}
}
}
fn money_from_parts(minor: i64, code: &str, column: &str) -> Result<Money, DbError> {
let currency =
Currency::parse(code).map_err(|e| decode_error(format!("column `{column}`: {e}")))?;
Ok(Money { minor, currency })
}
fn decode_error(message: String) -> DbError {
DbError::from(sqlx::Error::Decode(message.into()))
}