Skip to main content

renox_core/db/
from_row.rs

1use super::{DbError, FromDb, Row};
2use crate::money::{Currency, Money};
3
4/// A type read from a query's rows: models (`derive(Model)`), structs with
5/// `#[derive(FromRow)]`, and tuples of columns by position.
6///
7/// ```
8/// # use renox::prelude::*;
9/// # async fn demo(db: Db) -> Result {
10/// #[derive(renox::FromRow, serde::Serialize)]
11/// struct Sales {
12///     category: String,
13///     total: i64,
14/// }
15///
16/// let sales: Vec<Sales> = renox::db::sql(
17///     "SELECT c.name AS category, CAST(SUM(p.price) AS BIGINT) AS total \
18///      FROM products p JOIN categories c ON c.id = p.category_id GROUP BY c.name",
19/// )
20/// .fetch_as(&db)
21/// .await?;
22/// let pairs: Vec<(i64, String)> = renox::db::sql("SELECT id, name FROM products")
23///     .fetch_as(&db)
24///     .await?;
25/// # let _ = (sales, pairs); Ok(()) }
26/// ```
27pub trait FromRow: Sized {
28    /// Decodes one row, by column name or position.
29    fn from_row(row: &Row) -> Result<Self, DbError>;
30}
31
32macro_rules! tuple {
33    ($($t:ident $i:tt),+) => {
34        impl<$($t: FromDb),+> FromRow for ($($t,)+) {
35            fn from_row(row: &Row) -> Result<Self, DbError> {
36                Ok(($(row.try_get::<$t>($i)?,)+))
37            }
38        }
39    };
40}
41
42tuple!(A 0);
43tuple!(A 0, B 1);
44tuple!(A 0, B 1, C 2);
45tuple!(A 0, B 1, C 2, D 3);
46tuple!(A 0, B 1, C 2, D 3, E 4);
47tuple!(A 0, B 1, C 2, D 3, E 4, F 5);
48tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6);
49
50impl Row {
51    /// Reads a [`Money`] from two columns: the amount in minor units
52    /// (`BIGINT`) and its ISO 4217 code (`TEXT`). A code that is not a known
53    /// currency is a decode error.
54    ///
55    /// ```
56    /// # use renox::prelude::*;
57    /// # async fn demo(db: Db) -> Result {
58    /// let row = renox::db::sql("SELECT 1250 AS total, 'USD' AS total_currency")
59    ///     .fetch_one(&db)
60    ///     .await?;
61    /// let total = row.try_get_money("total", "total_currency")?;
62    /// assert_eq!(total, renox::money::Money::usd(1250));
63    /// # Ok(()) }
64    /// ```
65    pub fn try_get_money(&self, amount: &str, currency: &str) -> Result<Money, DbError> {
66        let minor: i64 = self.try_get(amount)?;
67        let code: String = self.try_get(currency)?;
68        money_from_parts(minor, &code, currency)
69    }
70
71    /// Like [`Row::try_get_money`] for a nullable pair: `None` when both
72    /// columns are `NULL`, an error when only one of them is.
73    pub fn try_get_money_opt(
74        &self,
75        amount: &str,
76        currency: &str,
77    ) -> Result<Option<Money>, DbError> {
78        let minor: Option<i64> = self.try_get(amount)?;
79        let code: Option<String> = self.try_get(currency)?;
80        match (minor, code) {
81            (None, None) => Ok(None),
82            (Some(minor), Some(code)) => money_from_parts(minor, &code, currency).map(Some),
83            _ => Err(decode_error(format!(
84                "`{amount}` and `{currency}` must be both set or both NULL"
85            ))),
86        }
87    }
88}
89
90fn money_from_parts(minor: i64, code: &str, column: &str) -> Result<Money, DbError> {
91    let currency =
92        Currency::parse(code).map_err(|e| decode_error(format!("column `{column}`: {e}")))?;
93    Ok(Money { minor, currency })
94}
95
96fn decode_error(message: String) -> DbError {
97    DbError::from(sqlx::Error::Decode(message.into()))
98}