1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
 * Trait to convert rust struct to [composite
 * type](https://www.postgresql.org/docs/current/rowtypes.html).
 */
pub trait Composite {
    /**
     * Composite type name.
     */
    fn name() -> &'static str;

    /**
     * Convert struct to a vector of SQL value.
     */
    fn to_vec(&self) -> Vec<&dyn crate::ToSql>;

    fn to_sql(&self) -> crate::Result<Option<Vec<u8>>> {
        crate::sql::record::vec_to_sql(&self.to_vec())
    }

    /**
     * Create a new struct from SQL result in text format.
     */
    fn from_text_values(ty: &crate::pq::Type, values: &[Option<&str>]) -> crate::Result<Box<Self>>;

    /**
     * Create a new struct from SQL result in binary format.
     */
    fn from_binary_values(
        ty: &crate::pq::Type,
        values: &[Option<&[u8]>],
    ) -> crate::Result<Box<Self>>;

    fn from_binary(ty: &crate::pq::Type, raw: Option<&[u8]>) -> crate::Result<Box<Self>> {
        let values = crate::sql::record::binary_to_vec(raw)?;

        Self::from_binary_values(ty, &values)
    }

    fn from_text(ty: &crate::pq::Type, raw: Option<&str>) -> crate::Result<Box<Self>> {
        let values = crate::sql::record::text_to_vec(raw)?;

        Self::from_text_values(ty, &values)
    }
}

impl<C: Composite> crate::ToSql for C {
    fn ty(&self) -> crate::pq::Type {
        crate::pq::types::Type {
            oid: 0,
            descr: Self::name(),
            name: Self::name(),
            kind: libpq::types::Kind::Composite,
        }
    }

    fn to_sql(&self) -> crate::Result<Option<Vec<u8>>> {
        self.to_sql()
    }
}

impl<C: Composite> crate::FromSql for C {
    fn from_text(ty: &crate::pq::Type, raw: Option<&str>) -> crate::Result<Self> {
        Self::from_text(ty, raw).map(|x| *x)
    }

    fn from_binary(ty: &crate::pq::Type, raw: Option<&[u8]>) -> crate::Result<Self> {
        Self::from_binary(ty, raw).map(|x| *x)
    }
}

#[cfg(test)]
mod test {
    #[derive(crate::Composite, Debug, PartialEq)]
    #[composite(internal)]
    struct CompFoo {
        f1: i32,
        f2: String,
    }

    crate::sql_test!(
        compfoo,
        super::CompFoo,
        [(
            "'(1,foo)'",
            super::CompFoo {
                f1: 1,
                f2: "foo".to_string()
            }
        )]
    );
}