sqlx_sqlite/types/
uuid.rs

1use crate::decode::Decode;
2use crate::encode::{Encode, IsNull};
3use crate::error::BoxDynError;
4use crate::type_info::DataType;
5use crate::types::Type;
6use crate::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef};
7use std::borrow::Cow;
8use uuid::{
9    fmt::{Hyphenated, Simple},
10    Uuid,
11};
12
13impl Type<Sqlite> for Uuid {
14    fn type_info() -> SqliteTypeInfo {
15        SqliteTypeInfo(DataType::Blob)
16    }
17
18    fn compatible(ty: &SqliteTypeInfo) -> bool {
19        matches!(ty.0, DataType::Blob | DataType::Text)
20    }
21}
22
23impl<'q> Encode<'q, Sqlite> for Uuid {
24    fn encode_by_ref(
25        &self,
26        args: &mut Vec<SqliteArgumentValue<'q>>,
27    ) -> Result<IsNull, BoxDynError> {
28        args.push(SqliteArgumentValue::Blob(Cow::Owned(
29            self.as_bytes().to_vec(),
30        )));
31
32        Ok(IsNull::No)
33    }
34}
35
36impl Decode<'_, Sqlite> for Uuid {
37    fn decode(value: SqliteValueRef<'_>) -> Result<Self, BoxDynError> {
38        // construct a Uuid from the returned bytes
39        Uuid::from_slice(value.blob()).map_err(Into::into)
40    }
41}
42
43impl Type<Sqlite> for Hyphenated {
44    fn type_info() -> SqliteTypeInfo {
45        SqliteTypeInfo(DataType::Text)
46    }
47}
48
49impl<'q> Encode<'q, Sqlite> for Hyphenated {
50    fn encode_by_ref(
51        &self,
52        args: &mut Vec<SqliteArgumentValue<'q>>,
53    ) -> Result<IsNull, BoxDynError> {
54        args.push(SqliteArgumentValue::Text(Cow::Owned(self.to_string())));
55
56        Ok(IsNull::No)
57    }
58}
59
60impl Decode<'_, Sqlite> for Hyphenated {
61    fn decode(value: SqliteValueRef<'_>) -> Result<Self, BoxDynError> {
62        let uuid: Result<Uuid, BoxDynError> =
63            Uuid::parse_str(&value.text().map(ToOwned::to_owned)?).map_err(Into::into);
64
65        Ok(uuid?.hyphenated())
66    }
67}
68
69impl Type<Sqlite> for Simple {
70    fn type_info() -> SqliteTypeInfo {
71        SqliteTypeInfo(DataType::Text)
72    }
73}
74
75impl<'q> Encode<'q, Sqlite> for Simple {
76    fn encode_by_ref(
77        &self,
78        args: &mut Vec<SqliteArgumentValue<'q>>,
79    ) -> Result<IsNull, BoxDynError> {
80        args.push(SqliteArgumentValue::Text(Cow::Owned(self.to_string())));
81
82        Ok(IsNull::No)
83    }
84}
85
86impl Decode<'_, Sqlite> for Simple {
87    fn decode(value: SqliteValueRef<'_>) -> Result<Self, BoxDynError> {
88        let uuid: Result<Uuid, BoxDynError> =
89            Uuid::parse_str(&value.text().map(ToOwned::to_owned)?).map_err(Into::into);
90
91        Ok(uuid?.simple())
92    }
93}