sqlx_postgres/types/
bool.rs

1use crate::decode::Decode;
2use crate::encode::{Encode, IsNull};
3use crate::error::BoxDynError;
4use crate::types::Type;
5use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres};
6
7impl Type<Postgres> for bool {
8    fn type_info() -> PgTypeInfo {
9        PgTypeInfo::BOOL
10    }
11}
12
13impl PgHasArrayType for bool {
14    fn array_type_info() -> PgTypeInfo {
15        PgTypeInfo::BOOL_ARRAY
16    }
17}
18
19impl Encode<'_, Postgres> for bool {
20    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
21        buf.push(*self as u8);
22
23        Ok(IsNull::No)
24    }
25}
26
27impl Decode<'_, Postgres> for bool {
28    fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
29        Ok(match value.format() {
30            PgValueFormat::Binary => value.as_bytes()?[0] != 0,
31
32            PgValueFormat::Text => match value.as_str()? {
33                "t" => true,
34                "f" => false,
35
36                s => {
37                    return Err(format!("unexpected value {s:?} for boolean").into());
38                }
39            },
40        })
41    }
42}