Uuid support for Sqlite.

Includes the same support for the Hyphenated adapter as the MySQL
Uuid support.
This commit is contained in:
James Tomlinson 2020-08-28 16:02:13 +01:00 committed by Ryan Leckey
parent 21661c2c9c
commit 40011f66df
No known key found for this signature in database
GPG Key ID: F8AA68C235AB08C9
2 changed files with 65 additions and 0 deletions

View File

@ -23,6 +23,15 @@
//! | `chrono::DateTime<Utc>` | DATETIME |
//! | `chrono::DateTime<Local>` | DATETIME |
//!
//! ### [`uuid`](https://crates.io/crates/uuid)
//!
//! Requires the `uuid` Cargo feature flag.
//!
//! | Rust type | Sqlite type(s) |
//! |---------------------------------------|------------------------------------------------------|
//! | `uuid::Uuid` | BLOB, TEXT |
//! | `uuid::adapter::Hyphenated` | TEXT |
//!
//! # Nullable
//!
//! In addition, `Option<T>` is supported where `T` implements `Type`. An `Option<T>` represents
@ -33,6 +42,8 @@ mod bool;
mod bytes;
#[cfg(feature = "chrono")]
mod chrono;
#[cfg(feature = "uuid")]
mod uuid;
mod float;
mod int;
#[cfg(feature = "json")]

View File

@ -0,0 +1,54 @@
use uuid::{adapter::Hyphenated, Uuid};
use std::borrow::Cow;
use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::sqlite::type_info::DataType;
use crate::sqlite::{Sqlite, SqliteArgumentValue, SqliteTypeInfo, SqliteValueRef};
use crate::types::Type;
impl Type<Sqlite> for Uuid {
fn type_info() -> SqliteTypeInfo {
SqliteTypeInfo(DataType::Blob)
}
fn compatible(ty: &SqliteTypeInfo) -> bool {
matches!(ty.0, DataType::Blob | DataType::Text)
}
}
impl<'q> Encode<'q, Sqlite> for &'q Uuid {
fn encode_by_ref(&self, args: &mut Vec<SqliteArgumentValue<'q>>) -> IsNull {
args.push(SqliteArgumentValue::Blob(Cow::Borrowed(self.as_bytes())));
IsNull::No
}
}
impl Decode<'_, Sqlite> for Uuid {
fn decode(value: SqliteValueRef<'_>) -> Result<Self, BoxDynError> {
// construct a Uuid from the returned bytes
Uuid::from_slice(value.blob()).map_err(Into::into)
}
}
impl Type<Sqlite> for Hyphenated {
fn type_info() -> SqliteTypeInfo {
SqliteTypeInfo(DataType::Text)
}
}
impl<'q> Encode<'q, Sqlite> for &'q Hyphenated {
fn encode_by_ref(&self, args: &mut Vec<SqliteArgumentValue<'q>>) -> IsNull {
args.push(SqliteArgumentValue::Text(Cow::Owned(self.to_string())));
IsNull::No
}
}
impl Decode<'_, Sqlite> for Hyphenated {
fn decode(value: SqliteValueRef<'_>) -> Result<Self, BoxDynError> {
let uuid: Result<Uuid, BoxDynError> = Uuid::parse_str(&value.text().map(ToOwned::to_owned)?).map_err(Into::into);
Ok(uuid?.to_hyphenated())
}
}