Merge pull request #210 from SeaQL/active-model-behavior

Update `ActiveModelBehavior` API
This commit is contained in:
Chris Tsang 2021-10-13 17:47:13 +08:00 committed by GitHub
commit 6defdaf616
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 35 additions and 26 deletions

View File

@ -10,8 +10,7 @@ pub struct ActiveValue<V>
where where
V: Into<Value>, V: Into<Value>,
{ {
// Don't want to call ActiveValue::unwrap() and cause panic value: Option<V>,
pub(self) value: Option<V>,
state: ActiveValueState, state: ActiveValueState,
} }
@ -74,7 +73,7 @@ pub trait ActiveModelTrait: Clone + Debug {
macro_rules! next { macro_rules! next {
() => { () => {
if let Some(col) = cols.next() { if let Some(col) = cols.next() {
if let Some(val) = self.get(col.into_column()).value { if let Some(val) = self.get(col.into_column()).into_value() {
val val
} else { } else {
return None; return None;
@ -107,12 +106,11 @@ pub trait ActiveModelTrait: Clone + Debug {
async fn insert<'a, C>(self, db: &'a C) -> Result<Self, DbErr> async fn insert<'a, C>(self, db: &'a C) -> Result<Self, DbErr>
where where
<Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>, <Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>,
Self: ActiveModelBehavior + 'a,
C: ConnectionTrait<'a>, C: ConnectionTrait<'a>,
Self: 'a,
{ {
let am = self; let am = ActiveModelBehavior::before_save(self, true)?;
let exec = <Self::Entity as EntityTrait>::insert(am).exec(db); let res = <Self::Entity as EntityTrait>::insert(am).exec(db).await?;
let res = exec.await?;
let found = <Self::Entity as EntityTrait>::find_by_id(res.last_insert_id) let found = <Self::Entity as EntityTrait>::find_by_id(res.last_insert_id)
.one(db) .one(db)
.await?; .await?;
@ -124,23 +122,23 @@ pub trait ActiveModelTrait: Clone + Debug {
async fn update<'a, C>(self, db: &'a C) -> Result<Self, DbErr> async fn update<'a, C>(self, db: &'a C) -> Result<Self, DbErr>
where where
Self: ActiveModelBehavior + 'a,
C: ConnectionTrait<'a>, C: ConnectionTrait<'a>,
Self: 'a,
{ {
let exec = Self::Entity::update(self).exec(db); let am = ActiveModelBehavior::before_save(self, false)?;
exec.await let am = Self::Entity::update(am).exec(db).await?;
ActiveModelBehavior::after_save(am, false)
} }
/// Insert the model if primary key is unset, update otherwise. /// Insert the model if primary key is unset, update otherwise.
/// Only works if the entity has auto increment primary key. /// Only works if the entity has auto increment primary key.
async fn save<'a, C>(self, db: &'a C) -> Result<Self, DbErr> async fn save<'a, C>(self, db: &'a C) -> Result<Self, DbErr>
where where
Self: ActiveModelBehavior + 'a,
<Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>, <Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>,
Self: ActiveModelBehavior + 'a,
C: ConnectionTrait<'a>, C: ConnectionTrait<'a>,
{ {
let mut am = self; let mut am = self;
am = ActiveModelBehavior::before_save(am);
let mut is_update = true; let mut is_update = true;
for key in <Self::Entity as EntityTrait>::PrimaryKey::iter() { for key in <Self::Entity as EntityTrait>::PrimaryKey::iter() {
let col = key.into_column(); let col = key.into_column();
@ -154,7 +152,6 @@ pub trait ActiveModelTrait: Clone + Debug {
} else { } else {
am = am.update(db).await?; am = am.update(db).await?;
} }
am = ActiveModelBehavior::after_save(am);
Ok(am) Ok(am)
} }
@ -164,14 +161,16 @@ pub trait ActiveModelTrait: Clone + Debug {
Self: ActiveModelBehavior + 'a, Self: ActiveModelBehavior + 'a,
C: ConnectionTrait<'a>, C: ConnectionTrait<'a>,
{ {
let mut am = self; let am = ActiveModelBehavior::before_delete(self)?;
am = ActiveModelBehavior::before_delete(am); let am_clone = am.clone();
let exec = Self::Entity::delete(am).exec(db); let delete_res = Self::Entity::delete(am).exec(db).await?;
exec.await ActiveModelBehavior::after_delete(am_clone)?;
Ok(delete_res)
} }
} }
/// Behaviors for users to override /// Behaviors for users to override
#[allow(unused_variables)]
pub trait ActiveModelBehavior: ActiveModelTrait { pub trait ActiveModelBehavior: ActiveModelTrait {
/// Create a new ActiveModel with default values. Also used by `Default::default()`. /// Create a new ActiveModel with default values. Also used by `Default::default()`.
fn new() -> Self { fn new() -> Self {
@ -179,18 +178,23 @@ pub trait ActiveModelBehavior: ActiveModelTrait {
} }
/// Will be called before saving /// Will be called before saving
fn before_save(self) -> Self { fn before_save(self, insert: bool) -> Result<Self, DbErr> {
self Ok(self)
} }
/// Will be called after saving /// Will be called after saving
fn after_save(self) -> Self { fn after_save(self, insert: bool) -> Result<Self, DbErr> {
self Ok(self)
} }
/// Will be called before deleting /// Will be called before deleting
fn before_delete(self) -> Self { fn before_delete(self) -> Result<Self, DbErr> {
self Ok(self)
}
/// Will be called after deleting
fn after_delete(self) -> Result<Self, DbErr> {
Ok(self)
} }
} }

View File

@ -1,8 +1,8 @@
pub use crate::{ pub use crate::{
error::*, ActiveModelBehavior, ActiveModelTrait, ColumnDef, ColumnTrait, ColumnType, error::*, ActiveModelBehavior, ActiveModelTrait, ColumnDef, ColumnTrait, ColumnType,
EntityName, EntityTrait, EnumIter, ForeignKeyAction, Iden, IdenStatic, Linked, ModelTrait, DatabaseConnection, DbConn, EntityName, EntityTrait, EnumIter, ForeignKeyAction, Iden,
PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult, Related, RelationDef, IdenStatic, Linked, ModelTrait, PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult,
RelationTrait, Select, Value, Related, RelationDef, RelationTrait, Select, Value,
}; };
#[cfg(feature = "macros")] #[cfg(feature = "macros")]

View File

@ -4,6 +4,7 @@ pub enum DbErr {
Exec(String), Exec(String),
Query(String), Query(String),
RecordNotFound(String), RecordNotFound(String),
Custom(String),
} }
impl std::error::Error for DbErr {} impl std::error::Error for DbErr {}
@ -15,6 +16,7 @@ impl std::fmt::Display for DbErr {
Self::Exec(s) => write!(f, "Execution Error: {}", s), Self::Exec(s) => write!(f, "Execution Error: {}", s),
Self::Query(s) => write!(f, "Query Error: {}", s), Self::Query(s) => write!(f, "Query Error: {}", s),
Self::RecordNotFound(s) => write!(f, "RecordNotFound Error: {}", s), Self::RecordNotFound(s) => write!(f, "RecordNotFound Error: {}", s),
Self::Custom(s) => write!(f, "Custom Error: {}", s),
} }
} }
} }

View File

@ -5,6 +5,7 @@ use sea_orm::entity::prelude::*;
pub struct Model { pub struct Model {
#[sea_orm(primary_key)] #[sea_orm(primary_key)]
pub id: i32, pub id: i32,
pub action: String,
pub json: Json, pub json: Json,
pub created_at: DateTimeWithTimeZone, pub created_at: DateTimeWithTimeZone,
} }

View File

@ -306,6 +306,7 @@ pub async fn create_log_table(db: &DbConn) -> Result<ExecResult, DbErr> {
.auto_increment() .auto_increment()
.primary_key(), .primary_key(),
) )
.col(ColumnDef::new(applog::Column::Action).string().not_null())
.col(ColumnDef::new(applog::Column::Json).json().not_null()) .col(ColumnDef::new(applog::Column::Json).json().not_null())
.col( .col(
ColumnDef::new(applog::Column::CreatedAt) ColumnDef::new(applog::Column::CreatedAt)

View File

@ -16,6 +16,7 @@ async fn main() -> Result<(), DbErr> {
pub async fn create_applog(db: &DatabaseConnection) -> Result<(), DbErr> { pub async fn create_applog(db: &DatabaseConnection) -> Result<(), DbErr> {
let log = applog::Model { let log = applog::Model {
id: 1, id: 1,
action: "Testing".to_owned(),
json: Json::String("HI".to_owned()), json: Json::String("HI".to_owned()),
created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(), created_at: "2021-09-17T17:50:20+08:00".parse().unwrap(),
}; };