use diesel::backend::RawValue; use diesel::deserialize::{self, FromSql, FromSqlRow}; use diesel::serialize::{self, IsNull, Output, ToSql}; use diesel::sql_types::Text; use diesel::sqlite::Sqlite; use diesel::AsExpression; use std::fmt; use std::fmt::{Display, Formatter}; use std::str; use uuid::{self, Uuid}; #[derive(Debug, Clone, Copy, FromSqlRow, AsExpression, Hash, Eq, PartialEq)] #[sql_type = "Text"] pub struct UUID(pub uuid::Uuid); impl UUID { pub fn random() -> Self { Self(uuid::Uuid::new_v4()) } pub fn parse_str(string: &str) -> Result { Uuid::parse_str(string).map(Self) } } impl From for uuid::Uuid { fn from(s: UUID) -> Self { s.0 } } impl Display for UUID { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl FromSql for UUID { fn from_sql(bytes: RawValue<'_, Sqlite>) -> deserialize::Result { let value = >::from_sql(bytes)?; let string = str::from_utf8(&value)?; Ok(UUID::parse_str(string)?) } } impl ToSql for UUID { fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result { out.set_value(self.0.to_string()); Ok(IsNull::No) } }