Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
45 changes: 45 additions & 0 deletions cot/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,51 @@ 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)
}
}

#[cfg(feature = "db")]
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
92 changes: 92 additions & 0 deletions cot/src/common_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,52 @@ impl FromDbValue for Url {
}
}

#[cfg(feature = "db")]
impl FromDbValue for Option<Url> {
#[cfg(feature = "sqlite")]
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)
}

#[cfg(feature = "postgres")]
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)
}

#[cfg(feature = "mysql")]
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)
}
}

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

#[cfg(feature = "db")]
impl DatabaseField for Url {
const TYPE: ColumnType = ColumnType::Text;
Expand Down Expand Up @@ -683,6 +729,52 @@ 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> {
#[cfg(feature = "sqlite")]
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)
}

#[cfg(feature = "postgres")]
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)
}

#[cfg(feature = "mysql")]
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
88 changes: 88 additions & 0 deletions cot/tests/db.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#![cfg(feature = "fake")]
#![cfg_attr(miri, ignore)]

use cot::auth::PasswordHash;
use cot::common_types::{Email, Password, Url};
use cot::db::migrations::{Field, Operation};
use cot::db::query::ExprEq;
use cot::db::{
Expand Down Expand Up @@ -39,6 +41,31 @@ impl Dummy<WeekdaySetFaker> for chrono::WeekdaySet {
}
}

struct EmailFaker;

impl Dummy<EmailFaker> for Email {
fn dummy_with_rng<R: fake::rand::Rng + ?Sized>(_: &EmailFaker, rng: &mut R) -> Self {
let username: String = (0..10)
.map(|_| (0x61u8 + (rng.next_u32() % 26) as u8) as char)
.collect();
let domain: String = (0..10)
.map(|_| (0x61u8 + (rng.next_u32() % 26) as u8) as char)
.collect();
Email::new(format!("{username}@{domain}.com")).expect("Generated email should be valid")
}
}

struct UrlFaker;

impl Dummy<UrlFaker> for Url {
fn dummy_with_rng<R: RngExt + ?Sized>(_config: &UrlFaker, rng: &mut R) -> Self {
let domain: String = (0..10)
.map(|_| (0x61u8 + (rng.next_u32() % 26) as u8) as char)
.collect();
Url::new(format!("https://{domain}.com")).expect("Generated URL should be valid")
}
}

#[derive(Debug, PartialEq)]
#[model]
struct TestModel {
Expand Down Expand Up @@ -221,8 +248,17 @@ 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,
#[dummy(faker = "EmailFaker")]
field_email: Email,
#[dummy(faker = "EmailFaker")]
field_option_email: Option<Email>,
#[dummy(faker = "UrlFaker")]
field_url: Url,
#[dummy(faker = "UrlFaker")]
field_option_url: Option<Url>,
}

async fn migrate_all_fields_model(db: &Database) {
Expand Down Expand Up @@ -254,7 +290,13 @@ 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),
all_fields_migration_field!(email, Email),
all_fields_migration_field!(option_email, Option<Email>),
all_fields_migration_field!(url, Url),
all_fields_migration_field!(option_url, Option<Url>),
all_fields_migration_field!(option_password_hash, Option<PasswordHash>),
])
.build();

Expand Down Expand Up @@ -315,6 +357,52 @@ macro_rules! run_migrations {
};
}

#[cot_macros::dbtest]
async fn password_hash_field(db: &TestDatabase) {
#[derive(Debug, Clone)]
#[model]
struct OptionPasswordHashModel {
#[model(primary_key)]
id: Auto<i32>,
password: Option<PasswordHash>,
}

const CREATE_OPTIONAL_PASSWORD_HASH_MODEL: Operation = Operation::create_model()
.table_name(Identifier::new("cot__option_password_hash_model"))
.fields(&[
Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
.primary_key()
.auto(),
Field::new(
Identifier::new("password"),
<Option<PasswordHash> as DatabaseField>::TYPE,
)
.set_null(<Option<PasswordHash> as DatabaseField>::NULLABLE),
])
.build();

run_migrations!(db, CREATE_OPTIONAL_PASSWORD_HASH_MODEL);

let generated_password: String = Faker.fake();
let mut with_password = OptionPasswordHashModel {
id: Auto::auto(),
password: Some(PasswordHash::from_password(&Password::new(
&generated_password,
))),
};
with_password.save(&**db).await.unwrap();

let mut without_password = OptionPasswordHashModel {
id: Auto::auto(),
password: None,
};
without_password.save(&**db).await.unwrap();

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

assert_eq!(models.len(), 2);
}

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