1use tokio_postgres::Row;
4
5use crate::error::{PgError, PgResult};
6
7pub trait PgRow {
9 fn get_value<T>(&self, column: &str) -> PgResult<T>
11 where
12 T: for<'a> tokio_postgres::types::FromSql<'a>;
13
14 fn get_opt<T>(&self, column: &str) -> PgResult<Option<T>>
16 where
17 T: for<'a> tokio_postgres::types::FromSql<'a>;
18
19 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 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
55pub trait FromPgRow: Sized {
57 fn from_row(row: &Row) -> PgResult<Self>;
59}
60
61#[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 }