Last active
October 23, 2022 09:32
-
-
Save brookman/6fa007b46f87c71cb5ca4eca6073b428 to your computer and use it in GitHub Desktop.
Attempt to store/load a UUID in Sqlite with diesel.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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<Self, uuid::Error> { | |
| Uuid::parse_str(string).map(Self) | |
| } | |
| } | |
| impl From<UUID> 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<Text, Sqlite> for UUID { | |
| fn from_sql(bytes: RawValue<'_, Sqlite>) -> deserialize::Result<Self> { | |
| let value = <Vec<u8>>::from_sql(bytes)?; | |
| let string = str::from_utf8(&value)?; | |
| Ok(UUID::parse_str(string)?) | |
| } | |
| } | |
| impl ToSql<Text, Sqlite> 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) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment