Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
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