diesel/pg/types/
primitives.rs

1use std::io::prelude::*;
2
3use crate::deserialize::{self, FromSql, Queryable};
4use crate::pg::{Pg, PgValue};
5use crate::serialize::{self, IsNull, Output, ToSql};
6use crate::sql_types;
7
8#[cfg(feature = "postgres_backend")]
9impl FromSql<sql_types::Bool, Pg> for bool {
10    fn from_sql(bytes: PgValue<'_>) -> deserialize::Result<Self> {
11        Ok(bytes.as_bytes()[0] != 0)
12    }
13}
14
15#[cfg(feature = "postgres_backend")]
16impl ToSql<sql_types::Bool, Pg> for bool {
17    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
18        out.write_all(&[*self as u8])
19            .map(|_| IsNull::No)
20            .map_err(Into::into)
21    }
22}
23
24#[cfg(feature = "postgres_backend")]
25impl FromSql<sql_types::CChar, Pg> for u8 {
26    fn from_sql(bytes: PgValue<'_>) -> deserialize::Result<Self> {
27        Ok(bytes.as_bytes()[0])
28    }
29}
30
31#[cfg(feature = "postgres_backend")]
32impl ToSql<sql_types::CChar, Pg> for u8 {
33    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
34        out.write_all(&[*self])
35            .map(|_| IsNull::No)
36            .map_err(Into::into)
37    }
38}
39
40/// The returned pointer is *only* valid for the lifetime to the argument of
41/// `from_sql`. This impl is intended for uses where you want to write a new
42/// impl in terms of `String`, but don't want to allocate. We have to return a
43/// raw pointer instead of a reference with a lifetime due to the structure of
44/// `FromSql`
45#[cfg(feature = "postgres_backend")]
46impl FromSql<sql_types::Text, Pg> for *const str {
47    fn from_sql(value: PgValue<'_>) -> deserialize::Result<Self> {
48        use std::str;
49        let string = str::from_utf8(value.as_bytes())?;
50        Ok(string as *const _)
51    }
52}
53
54#[cfg(feature = "postgres_backend")]
55impl Queryable<sql_types::VarChar, Pg> for *const str {
56    type Row = Self;
57
58    fn build(row: Self::Row) -> deserialize::Result<Self> {
59        Ok(row)
60    }
61}
62
63#[cfg(feature = "postgres_backend")]
64impl ToSql<sql_types::Citext, Pg> for String {
65    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
66        out.write_all(self.as_bytes())?;
67        Ok(IsNull::No)
68    }
69}
70
71#[cfg(feature = "postgres_backend")]
72impl ToSql<sql_types::Citext, Pg> for str {
73    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Pg>) -> serialize::Result {
74        out.write_all(self.as_bytes())?;
75        Ok(IsNull::No)
76    }
77}
78
79#[cfg(feature = "postgres_backend")]
80impl FromSql<sql_types::Citext, Pg> for String {
81    fn from_sql(value: PgValue<'_>) -> deserialize::Result<Self> {
82        let string = String::from_utf8(value.as_bytes().to_vec())?;
83        Ok(string)
84    }
85}
86
87/// The returned pointer is *only* valid for the lifetime to the argument of
88/// `from_sql`. This impl is intended for uses where you want to write a new
89/// impl in terms of `Vec<u8>`, but don't want to allocate. We have to return a
90/// raw pointer instead of a reference with a lifetime due to the structure of
91/// `FromSql`
92#[cfg(feature = "postgres_backend")]
93impl FromSql<sql_types::Binary, Pg> for *const [u8] {
94    fn from_sql(value: PgValue<'_>) -> deserialize::Result<Self> {
95        Ok(value.as_bytes() as *const _)
96    }
97}
98
99#[cfg(feature = "postgres_backend")]
100impl Queryable<sql_types::Binary, Pg> for *const [u8] {
101    type Row = Self;
102
103    fn build(row: Self::Row) -> deserialize::Result<Self> {
104        Ok(row)
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[diesel_test_helper::test]
113    fn cchar_to_sql() {
114        use crate::query_builder::bind_collector::ByteWrapper;
115
116        let mut buffer = Vec::new();
117        let mut bytes = Output::test(ByteWrapper(&mut buffer));
118        ToSql::<sql_types::CChar, Pg>::to_sql(&b'A', &mut bytes).unwrap();
119        ToSql::<sql_types::CChar, Pg>::to_sql(&b'\xc4', &mut bytes).unwrap();
120        assert_eq!(buffer, vec![65u8, 196u8]);
121    }
122
123    #[diesel_test_helper::test]
124    fn cchar_from_sql() {
125        let result = <u8 as FromSql<sql_types::CChar, Pg>>::from_nullable_sql(None);
126        assert_eq!(
127            result.unwrap_err().to_string(),
128            "Unexpected null for non-null column"
129        );
130    }
131
132    #[diesel_test_helper::test]
133    fn bool_to_sql() {
134        use crate::query_builder::bind_collector::ByteWrapper;
135
136        let mut buffer = Vec::new();
137        let mut bytes = Output::test(ByteWrapper(&mut buffer));
138        ToSql::<sql_types::Bool, Pg>::to_sql(&true, &mut bytes).unwrap();
139        ToSql::<sql_types::Bool, Pg>::to_sql(&false, &mut bytes).unwrap();
140        assert_eq!(buffer, vec![1u8, 0u8]);
141    }
142
143    #[diesel_test_helper::test]
144    fn no_bool_from_sql() {
145        let result = <bool as FromSql<sql_types::Bool, Pg>>::from_nullable_sql(None);
146        assert_eq!(
147            result.unwrap_err().to_string(),
148            "Unexpected null for non-null column"
149        );
150    }
151}