Blanket IntoActiveValue implementations so custom db types are supported (#833)

* Add blanket implementations of IntoActiveValue for optional values

* Add a compile test for DeriveIntoActiveModel
This commit is contained in:
wdcocq 2022-10-11 17:47:17 +02:00 committed by GitHub
parent 0f8b4bd1fa
commit 880147c596
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 65 additions and 18 deletions

View File

@ -641,6 +641,30 @@ where
fn into_active_value(self) -> ActiveValue<V>;
}
impl<V> IntoActiveValue<Option<V>> for Option<V>
where
V: IntoActiveValue<V> + Into<Value> + Nullable,
{
fn into_active_value(self) -> ActiveValue<Option<V>> {
match self {
Some(value) => Set(Some(value)),
None => NotSet,
}
}
}
impl<V> IntoActiveValue<Option<V>> for Option<Option<V>>
where
V: IntoActiveValue<V> + Into<Value> + Nullable,
{
fn into_active_value(self) -> ActiveValue<Option<V>> {
match self {
Some(value) => Set(value),
None => NotSet,
}
}
}
macro_rules! impl_into_active_value {
($ty: ty) => {
impl IntoActiveValue<$ty> for $ty {
@ -648,24 +672,6 @@ macro_rules! impl_into_active_value {
Set(self)
}
}
impl IntoActiveValue<Option<$ty>> for Option<$ty> {
fn into_active_value(self) -> ActiveValue<Option<$ty>> {
match self {
Some(value) => Set(Some(value)),
None => NotSet,
}
}
}
impl IntoActiveValue<Option<$ty>> for Option<Option<$ty>> {
fn into_active_value(self) -> ActiveValue<Option<$ty>> {
match self {
Some(value) => Set(value),
None => NotSet,
}
}
}
};
}

View File

@ -0,0 +1,40 @@
use super::sea_orm_active_enums::*;
use sea_orm::entity::prelude::*;
use sea_orm::{ActiveValue, IntoActiveValue};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[cfg_attr(feature = "sqlx-postgres", sea_orm(schema_name = "public"))]
#[sea_orm(table_name = "custom_active_model")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub weight: Option<f32>,
pub amount: Option<i32>,
pub category: Option<Category>,
pub color: Option<Color>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
#[derive(Clone, Debug, PartialEq, DeriveIntoActiveModel)]
pub struct CustomActiveModel {
pub weight: Option<f32>,
pub amount: Option<Option<i32>>,
pub category: Option<Category>,
pub color: Option<Option<Color>>,
}
impl IntoActiveValue<Category> for Category {
fn into_active_value(self) -> ActiveValue<Category> {
ActiveValue::set(self)
}
}
impl IntoActiveValue<Color> for Color {
fn into_active_value(self) -> ActiveValue<Color> {
ActiveValue::set(self)
}
}

View File

@ -2,6 +2,7 @@ pub mod active_enum;
pub mod active_enum_child;
pub mod applog;
pub mod byte_primary_key;
pub mod custom_active_model;
pub mod insert_default;
pub mod json_struct;
pub mod json_vec;