ActiveModelBehavior

This commit is contained in:
Chris Tsang 2021-06-03 13:07:35 +08:00
parent c482b0cbc6
commit 6a26b8cc17
7 changed files with 44 additions and 6 deletions

View File

@ -31,11 +31,17 @@ pub fn expand_derive_active_model(ident: Ident, data: Data) -> syn::Result<Token
let ty: Vec<Type> = fields.into_iter().map(|Field { ty, .. }| ty).collect();
Ok(quote!(
#[derive(Clone, Debug, Default)]
#[derive(Clone, Debug)]
pub struct ActiveModel {
#(pub #field: sea_orm::ActiveValue<#ty>),*
}
impl Default for ActiveModel {
fn default() -> Self {
<Self as sea_orm::ActiveModelBehavior>::new()
}
}
impl From<#ident> for ActiveModel {
fn from(m: #ident) -> Self {
Self {
@ -70,6 +76,12 @@ pub fn expand_derive_active_model(ident: Ident, data: Data) -> syn::Result<Token
#(<Self::Entity as EntityTrait>::Column::#name => self.#field = sea_orm::ActiveValue::unset()),*
}
}
fn default() -> Self {
Self {
#(#field: sea_orm::ActiveValue::unset()),*
}
}
}
))
}

View File

@ -44,7 +44,7 @@ where
ActiveValue::unchanged(value)
}
pub trait ActiveModelTrait: Clone + Debug + Default {
pub trait ActiveModelTrait: Clone + Debug {
type Entity: EntityTrait;
fn take(&mut self, c: <Self::Entity as EntityTrait>::Column) -> ActiveValue<Value>;
@ -54,6 +54,16 @@ pub trait ActiveModelTrait: Clone + Debug + Default {
fn set(&mut self, c: <Self::Entity as EntityTrait>::Column, v: Value);
fn unset(&mut self, c: <Self::Entity as EntityTrait>::Column);
fn default() -> Self;
}
pub trait ActiveModelBehavior: ActiveModelTrait {
type Entity: EntityTrait;
fn new() -> Self {
<Self as ActiveModelTrait>::default()
}
}
impl<V> ActiveValue<V>

View File

@ -1,6 +1,6 @@
pub use crate::{
ActiveModelTrait, ColumnTrait, ColumnType, DeriveActiveModel, DeriveColumn, DeriveEntity,
DeriveModel, DerivePrimaryKey, EntityName, EntityTrait, EnumIter, Iden, IdenStatic, ModelTrait,
PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult, Related, RelationDef,
RelationTrait, Select, TypeErr, Value,
ActiveModelBehavior, ActiveModelTrait, ColumnTrait, ColumnType, DeriveActiveModel,
DeriveColumn, DeriveEntity, DeriveModel, DerivePrimaryKey, EntityName, EntityTrait, EnumIter,
Iden, IdenStatic, ModelTrait, PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult,
Related, RelationDef, RelationTrait, Select, TypeErr, Value,
};

View File

@ -74,3 +74,7 @@ impl Model {
Entity::find_related().belongs_to::<Entity>(self)
}
}
impl ActiveModelBehavior for ActiveModel {
type Entity = Entity;
}

View File

@ -54,3 +54,7 @@ impl RelationTrait for Relation {
}
}
}
impl ActiveModelBehavior for ActiveModel {
type Entity = Entity;
}

View File

@ -57,3 +57,7 @@ impl Model {
Entity::find_related().belongs_to::<Entity>(self)
}
}
impl ActiveModelBehavior for ActiveModel {
type Entity = Entity;
}

View File

@ -44,3 +44,7 @@ impl RelationTrait for Relation {
panic!()
}
}
impl ActiveModelBehavior for ActiveModel {
type Entity = Entity;
}