Skip to main content

prax_postgres/
row.rs

1//! PostgreSQL row types and deserialization.
2
3use tokio_postgres::Row;
4
5use crate::error::{PgError, PgResult};
6
7/// Extension trait for PostgreSQL rows.
8pub trait PgRow {
9    /// Get a column value by name.
10    fn get_value<T>(&self, column: &str) -> PgResult<T>
11    where
12        T: for<'a> tokio_postgres::types::FromSql<'a>;
13
14    /// Get an optional column value by name.
15    fn get_opt<T>(&self, column: &str) -> PgResult<Option<T>>
16    where
17        T: for<'a> tokio_postgres::types::FromSql<'a>;
18
19    /// Try to get a column value, returning None if the column doesn't exist.
20    fn try_get<T>(&self, column: &str) -> Option<T>
21    where
22        T: for<'a> tokio_postgres::types::FromSql<'a>;
23}
24
25impl PgRow for Row {
26    fn get_value<T>(&self, column: &str) -> PgResult<T>
27    where
28        T: for<'a> tokio_postgres::types::FromSql<'a>,
29    {
30        self.try_get(column).map_err(|e| {
31            PgError::deserialization(format!("failed to get column '{}': {}", column, e))
32        })
33    }
34
35    fn get_opt<T>(&self, column: &str) -> PgResult<Option<T>>
36    where
37        T: for<'a> tokio_postgres::types::FromSql<'a>,
38    {
39        // Decoding through `Option<T>` makes SQL NULL yield `None` natively,
40        // so any error here is a genuine failure (type mismatch, missing
41        // column) and must propagate rather than be pattern-matched away.
42        self.try_get(column).map_err(|e| {
43            PgError::deserialization(format!("failed to get column '{}': {}", column, e))
44        })
45    }
46
47    fn try_get<T>(&self, column: &str) -> Option<T>
48    where
49        T: for<'a> tokio_postgres::types::FromSql<'a>,
50    {
51        Row::try_get(self, column).ok()
52    }
53}
54
55/// Trait for deserializing a PostgreSQL row into a type.
56pub trait FromPgRow: Sized {
57    /// Deserialize from a PostgreSQL row.
58    fn from_row(row: &Row) -> PgResult<Self>;
59}
60
61/// Macro to implement FromPgRow for simple structs.
62///
63/// Usage:
64/// ```rust,ignore
65/// impl_from_row!(User {
66///     id: i32,
67///     email: String,
68///     name: Option<String>,
69/// });
70/// ```
71#[macro_export]
72macro_rules! impl_from_row {
73    ($type:ident { $($field:ident : $field_type:ty),* $(,)? }) => {
74        impl $crate::row::FromPgRow for $type {
75            fn from_row(row: &tokio_postgres::Row) -> $crate::error::PgResult<Self> {
76                use $crate::row::PgRow;
77                Ok(Self {
78                    $(
79                        $field: row.get_value(stringify!($field))?,
80                    )*
81                })
82            }
83        }
84    };
85}
86
87#[cfg(test)]
88mod tests {
89    // Row tests require integration testing with a real database
90}