Skip to content
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions cot/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,50 @@ impl ToDbValue for PasswordHash {
}
}

#[cfg(feature = "db")]
impl FromDbValue for Option<PasswordHash> {
#[cfg(feature = "sqlite")]
fn from_sqlite(value: crate::db::impl_sqlite::SqliteValueRef<'_>) -> cot::db::Result<Self> {
value
.get::<Option<String>>()
.map(|op_str| op_str.map(PasswordHash::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

#[cfg(feature = "postgres")]
fn from_postgres(
value: crate::db::impl_postgres::PostgresValueRef<'_>,
) -> cot::db::Result<Self> {
value
.get::<Option<String>>()
.map(|op_str| op_str.map(PasswordHash::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

#[cfg(feature = "mysql")]
fn from_mysql(value: crate::db::impl_mysql::MySqlValueRef<'_>) -> crate::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|op_str| op_str.map(PasswordHash::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}
}

impl ToDbValue for Option<PasswordHash> {
fn to_db_value(&self) -> DbValue {
match self {
Some(hash) => hash.to_db_value(),
None => <Option<String>>::None.to_db_value(),
}
}
}

/// Authentication helper structure.
///
/// This is an object that provides methods to sign users in and out, by using
Expand Down
84 changes: 84 additions & 0 deletions cot/src/common_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,47 @@ impl FromDbValue for Url {
}
}

impl FromDbValue for Option<Url> {
fn from_sqlite(value: SqliteValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Url::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_postgres(value: PostgresValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Url::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_mysql(value: MySqlValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Url::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}
}

impl ToDbValue for Option<Url> {
fn to_db_value(&self) -> DbValue {
self.clone().map(|url| url.into_string()).into()
}
}

#[cfg(feature = "db")]
impl DatabaseField for Url {
const TYPE: ColumnType = ColumnType::Text;
Expand Down Expand Up @@ -683,6 +724,49 @@ impl FromDbValue for Email {
}
}

#[cfg(feature = "db")]
impl ToDbValue for Option<Email> {
fn to_db_value(&self) -> DbValue {
self.clone().map(|email| email.email()).into()
}
}

#[cfg(feature = "db")]
impl FromDbValue for Option<Email> {
fn from_sqlite(value: SqliteValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Email::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_postgres(value: PostgresValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Email::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_mysql(value: MySqlValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Email::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}
}

/// Defines the database field type for `Email`.
///
/// Emails are stored as strings with a maximum length of 254 characters,
Expand Down
29 changes: 29 additions & 0 deletions cot/src/db/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,35 @@ impl<const LIMIT: u32> ToDbValue for Option<LimitedString<LIMIT>> {
}
}

impl<const LIMIT: u32> FromDbValue for Option<LimitedString<LIMIT>> {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's very arguable that duplication of impl code can be abstracted into the impl_db_field macro. I'm still accessing this. My main concern is prioritizing code readability and reducing the number of special cases when improving the macro to support most cases.

#[cfg(feature = "sqlite")]
fn from_sqlite(value: SqliteValueRef<'_>) -> Result<Self> {
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(LimitedString::new))?
.transpose()
.map_err(DatabaseError::value_decode)
}

#[cfg(feature = "postgres")]
fn from_postgres(value: PostgresValueRef<'_>) -> Result<Self> {
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(LimitedString::new))?
.transpose()
.map_err(DatabaseError::value_decode)
}

#[cfg(feature = "mysql")]
fn from_mysql(value: MySqlValueRef<'_>) -> Result<Self> {
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(LimitedString::new))?
.transpose()
.map_err(DatabaseError::value_decode)
}
}

impl<T: Model + Send + Sync> DatabaseField for ForeignKey<T> {
const NULLABLE: bool = T::PrimaryKey::NULLABLE;
const TYPE: ColumnType = T::PrimaryKey::TYPE;
Expand Down
67 changes: 67 additions & 0 deletions cot/tests/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ struct AllFieldsModel {
field_blob: Vec<u8>,
field_option: Option<String>,
field_limited_string: LimitedString<10>,
field_option_limited_string: Option<LimitedString<10>>,
#[dummy(faker = "WeekdaySetFaker")]
field_weekday_set: chrono::WeekdaySet,
}
Expand Down Expand Up @@ -254,6 +255,7 @@ const CREATE_ALL_FIELDS_MODEL: Operation = Operation::create_model()
all_fields_migration_field!(blob, Vec<u8>),
all_fields_migration_field!(option, Option<String>),
all_fields_migration_field!(limited_string, LimitedString<10>),
all_fields_migration_field!(option_limited_string, Option<LimitedString<10>>),
all_fields_migration_field!(weekday_set, chrono::WeekdaySet),
])
.build();
Expand Down Expand Up @@ -315,6 +317,71 @@ macro_rules! run_migrations {
};
}

#[cot_macros::dbtest]
async fn option_limited_string_field(db: &mut TestDatabase) {
#[derive(Debug, Clone, PartialEq)]
#[model]
struct OptionalLimitedStringModel {
#[model(primary_key)]
id: Auto<i32>,
name: Option<LimitedString<10>>,
}

const CREATE_OPTIONAL_LIMITED_STRING_MODEL: Operation = Operation::create_model()
.table_name(Identifier::new("cot__optional_limited_string_model"))
.fields(&[
Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
.primary_key()
.auto(),
Field::new(
Identifier::new("name"),
<Option<LimitedString<10>> as DatabaseField>::TYPE,
)
.set_null(<Option<LimitedString<10>> as DatabaseField>::NULLABLE),
])
.build();

run_migrations!(db, CREATE_OPTIONAL_LIMITED_STRING_MODEL);

let mut with_name = OptionalLimitedStringModel {
id: Auto::auto(),
name: Some(LimitedString::new("named").unwrap()),
};
with_name.save(&**db).await.unwrap();

let mut without_name = OptionalLimitedStringModel {
id: Auto::auto(),
name: None,
};
without_name.save(&**db).await.unwrap();

let models = OptionalLimitedStringModel::objects()
.all(&**db)
.await
.unwrap();

assert_eq!(models.len(), 2);
assert!(models.contains(&with_name));
assert!(models.contains(&without_name));

let with_name_from_db = query!(OptionalLimitedStringModel, $id == with_name.id)
.get(&**db)
.await
.unwrap()
.unwrap();
assert_eq!(
with_name_from_db.name,
Some(LimitedString::new("named").unwrap())
);

let without_name_from_db = query!(OptionalLimitedStringModel, $id == without_name.id)
.get(&**db)
.await
.unwrap()
.unwrap();
assert_eq!(without_name_from_db.name, None);
}

#[cot_macros::dbtest]
async fn foreign_keys(db: &mut TestDatabase) {
#[derive(Debug, Clone, PartialEq)]
Expand Down
Loading