From d698e5e5648449e1407898d1e94736b2b5e3292c Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Tue, 30 Nov 2021 18:59:48 +0800 Subject: [PATCH 1/6] Update insert & update API --- src/entity/active_model.rs | 28 +++++++++++++++------------- src/executor/insert.rs | 10 +++++----- src/executor/update.rs | 14 ++++++-------- 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/entity/active_model.rs b/src/entity/active_model.rs index 06e01fcbe..8282b91c2 100644 --- a/src/entity/active_model.rs +++ b/src/entity/active_model.rs @@ -247,17 +247,17 @@ pub trait ActiveModelTrait: Clone + Debug { /// # Ok(()) /// # } /// ``` - async fn insert<'a, C>(self, db: &'a C) -> Result + async fn insert<'a, C>(self, db: &'a C) -> Result<::Model, DbErr> where ::Model: IntoActiveModel, Self: ActiveModelBehavior + 'a, C: ConnectionTrait<'a>, { let am = ActiveModelBehavior::before_save(self, true)?; - let am = ::insert(am) + let model = ::insert(am) .exec_with_returning(db) .await?; - ActiveModelBehavior::after_save(am, true) + Self::after_save(model, true) } /// Perform the `UPDATE` operation on an ActiveModel @@ -371,26 +371,26 @@ pub trait ActiveModelTrait: Clone + Debug { /// # Ok(()) /// # } /// ``` - async fn update<'a, C>(self, db: &'a C) -> Result + async fn update<'a, C>(self, db: &'a C) -> Result<::Model, DbErr> where ::Model: IntoActiveModel, Self: ActiveModelBehavior + 'a, C: ConnectionTrait<'a>, { let am = ActiveModelBehavior::before_save(self, false)?; - let am = Self::Entity::update(am).exec(db).await?; - ActiveModelBehavior::after_save(am, false) + let model: ::Model = Self::Entity::update(am).exec(db).await?; + Self::after_save(model, false) } /// Insert the model if primary key is unset, update otherwise. /// Only works if the entity has auto increment primary key. - async fn save<'a, C>(self, db: &'a C) -> Result + async fn save<'a, C>(self, db: &'a C) -> Result<::Model, DbErr> where ::Model: IntoActiveModel, Self: ActiveModelBehavior + 'a, C: ConnectionTrait<'a>, { - let mut am = self; + let am = self; let mut is_update = true; for key in ::PrimaryKey::iter() { let col = key.into_column(); @@ -400,11 +400,10 @@ pub trait ActiveModelTrait: Clone + Debug { } } if !is_update { - am = am.insert(db).await?; + am.insert(db).await } else { - am = am.update(db).await?; + am.update(db).await } - Ok(am) } /// Delete an active model by its primary key @@ -503,8 +502,11 @@ pub trait ActiveModelBehavior: ActiveModelTrait { } /// Will be called after saving - fn after_save(self, insert: bool) -> Result { - Ok(self) + fn after_save( + model: ::Model, + insert: bool, + ) -> Result<::Model, DbErr> { + Ok(model) } /// Will be called before deleting diff --git a/src/executor/insert.rs b/src/executor/insert.rs index a6dbcbd53..1d9f74423 100644 --- a/src/executor/insert.rs +++ b/src/executor/insert.rs @@ -55,7 +55,7 @@ where pub fn exec_with_returning<'a, C>( self, db: &'a C, - ) -> impl Future> + '_ + ) -> impl Future::Model, DbErr>> + '_ where ::Model: IntoActiveModel, C: ConnectionTrait<'a>, @@ -92,13 +92,13 @@ where pub fn exec_with_returning<'a, C>( self, db: &'a C, - ) -> impl Future> + '_ + ) -> impl Future::Model, DbErr>> + '_ where ::Model: IntoActiveModel, C: ConnectionTrait<'a>, A: 'a, { - exec_insert_with_returning(self.primary_key, self.query, db) + exec_insert_with_returning::(self.primary_key, self.query, db) } } @@ -140,7 +140,7 @@ async fn exec_insert_with_returning<'a, A, C>( primary_key: Option, mut insert_statement: InsertStatement, db: &'a C, -) -> Result +) -> Result<::Model, DbErr> where ::Model: IntoActiveModel, C: ConnectionTrait<'a>, @@ -175,7 +175,7 @@ where } }; match found { - Some(model) => Ok(model.into_active_model()), + Some(model) => Ok(model), None => Err(DbErr::Exec("Failed to find inserted item".to_owned())), } } diff --git a/src/executor/update.rs b/src/executor/update.rs index 44db7a7d7..3e7df14b4 100644 --- a/src/executor/update.rs +++ b/src/executor/update.rs @@ -1,6 +1,6 @@ use crate::{ - error::*, ActiveModelTrait, ColumnTrait, ConnectionTrait, EntityTrait, IntoActiveModel, - Iterable, SelectModel, SelectorRaw, Statement, UpdateMany, UpdateOne, + error::*, ActiveModelTrait, ColumnTrait, ConnectionTrait, EntityTrait, Iterable, SelectModel, + SelectorRaw, Statement, UpdateMany, UpdateOne, }; use sea_query::{Alias, Expr, FromValueTuple, Query, UpdateStatement}; use std::future::Future; @@ -24,9 +24,8 @@ where A: ActiveModelTrait, { /// Execute an update operation on an ActiveModel - pub async fn exec<'b, C>(self, db: &'b C) -> Result + pub async fn exec<'b, C>(self, db: &'b C) -> Result<::Model, DbErr> where - ::Model: IntoActiveModel, C: ConnectionTrait<'b>, { // so that self is dropped before entering await @@ -84,9 +83,8 @@ async fn exec_update_and_return_updated<'a, A, C>( mut query: UpdateStatement, model: A, db: &'a C, -) -> Result +) -> Result<::Model, DbErr> where - ::Model: IntoActiveModel, A: ActiveModelTrait, C: ConnectionTrait<'a>, { @@ -112,7 +110,7 @@ where .await?; // If we got `None` then we are updating a row that does not exist. match found { - Some(model) => Ok(model.into_active_model()), + Some(model) => Ok(model), None => Err(DbErr::RecordNotFound( "None of the database rows are affected".to_owned(), )), @@ -130,7 +128,7 @@ where .await?; // If we cannot select the updated row from db by the cached primary key match found { - Some(model) => Ok(model.into_active_model()), + Some(model) => Ok(model), None => Err(DbErr::Exec("Failed to find inserted item".to_owned())), } } From dd32711e89be668b3b41a95fa56f74a2eb9c5ff2 Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Tue, 30 Nov 2021 19:00:10 +0800 Subject: [PATCH 2/6] Update test cases --- src/entity/active_model.rs | 4 -- src/entity/base_entity.rs | 2 - src/executor/update.rs | 1 - tests/active_enum_tests.rs | 34 +++++++-------- tests/basic.rs | 6 +-- tests/byte_primary_key_tests.rs | 10 ++++- tests/common/bakery_chain/cake.rs | 6 +-- tests/crud/deletes.rs | 12 +++++- tests/crud/updates.rs | 11 +++-- tests/query_tests.rs | 6 +-- tests/relational_tests.rs | 71 ++++++++++++------------------- tests/sequential_op_tests.rs | 23 +++++----- tests/stream_tests.rs | 4 +- tests/string_primary_key_tests.rs | 34 ++++++++++++--- tests/transaction_tests.rs | 4 +- tests/uuid_tests.rs | 7 ++- 16 files changed, 125 insertions(+), 110 deletions(-) diff --git a/src/entity/active_model.rs b/src/entity/active_model.rs index 8282b91c2..ba02a914b 100644 --- a/src/entity/active_model.rs +++ b/src/entity/active_model.rs @@ -172,7 +172,6 @@ pub trait ActiveModelTrait: Clone + Debug { /// id: 15, /// name: "Apple Pie".to_owned(), /// } - /// .into_active_model() /// ); /// /// assert_eq!( @@ -225,7 +224,6 @@ pub trait ActiveModelTrait: Clone + Debug { /// id: 15, /// name: "Apple Pie".to_owned(), /// } - /// .into_active_model() /// ); /// /// assert_eq!( @@ -296,7 +294,6 @@ pub trait ActiveModelTrait: Clone + Debug { /// name: "Orange".to_owned(), /// cake_id: None, /// } - /// .into_active_model() /// ); /// /// assert_eq!( @@ -351,7 +348,6 @@ pub trait ActiveModelTrait: Clone + Debug { /// name: "Orange".to_owned(), /// cake_id: None, /// } - /// .into_active_model() /// ); /// /// assert_eq!( diff --git a/src/entity/base_entity.rs b/src/entity/base_entity.rs index e6247d352..418b31306 100644 --- a/src/entity/base_entity.rs +++ b/src/entity/base_entity.rs @@ -505,7 +505,6 @@ pub trait EntityTrait: EntityName { /// name: "Orange".to_owned(), /// cake_id: None, /// } - /// .into_active_model(), /// ); /// /// assert_eq!( @@ -563,7 +562,6 @@ pub trait EntityTrait: EntityName { /// name: "Orange".to_owned(), /// cake_id: None, /// } - /// .into_active_model(), /// ); /// /// assert_eq!( diff --git a/src/executor/update.rs b/src/executor/update.rs index 3e7df14b4..eb997f13d 100644 --- a/src/executor/update.rs +++ b/src/executor/update.rs @@ -194,7 +194,6 @@ mod tests { id: 1, name: "Cheese Cake".to_owned(), } - .into_active_model() ); let model = cake::Model { diff --git a/tests/active_enum_tests.rs b/tests/active_enum_tests.rs index aaad419b2..c6295328f 100644 --- a/tests/active_enum_tests.rs +++ b/tests/active_enum_tests.rs @@ -21,25 +21,25 @@ async fn main() -> Result<(), DbErr> { pub async fn insert_active_enum(db: &DatabaseConnection) -> Result<(), DbErr> { use active_enum::*; - let am = ActiveModel { - category: Set(None), - color: Set(None), - tea: Set(None), - ..Default::default() - } - .insert(db) - .await?; + let model = Model { + id: 1, + category: None, + color: None, + tea: None, + }; - let model = Entity::find().one(db).await?.unwrap(); assert_eq!( model, - Model { - id: 1, - category: None, - color: None, - tea: None, + ActiveModel { + category: Set(None), + color: Set(None), + tea: Set(None), + ..Default::default() } + .insert(db) + .await? ); + assert_eq!(model, Entity::find().one(db).await?.unwrap()); assert_eq!( model, Entity::find() @@ -52,11 +52,11 @@ pub async fn insert_active_enum(db: &DatabaseConnection) -> Result<(), DbErr> { .unwrap() ); - let am = ActiveModel { + let _ = ActiveModel { category: Set(Some(Category::Big)), color: Set(Some(Color::Black)), tea: Set(Some(Tea::EverydayTea)), - ..am + ..model.into_active_model() } .save(db) .await?; @@ -83,7 +83,7 @@ pub async fn insert_active_enum(db: &DatabaseConnection) -> Result<(), DbErr> { .unwrap() ); - let res = am.delete(db).await?; + let res = model.into_active_model().delete(db).await?; assert_eq!(res.rows_affected, 1); assert_eq!(Entity::find().one(db).await?, None); diff --git a/tests/basic.rs b/tests/basic.rs index ef379779e..96eed084a 100644 --- a/tests/basic.rs +++ b/tests/basic.rs @@ -45,17 +45,17 @@ async fn crud_cake(db: &DbConn) -> Result<(), DbErr> { ..Default::default() }; - let mut apple = apple.save(db).await?; + let mut apple = apple.save(db).await?.into_active_model(); println!(); println!("Inserted: {:?}", apple); assert_eq!( + apple, cake::ActiveModel { id: Set(1), name: Set("Apple Pie".to_owned()), - }, - apple + } ); apple.name = Set("Lemon Tart".to_owned()); diff --git a/tests/byte_primary_key_tests.rs b/tests/byte_primary_key_tests.rs index 173efc93f..2f66a13a8 100644 --- a/tests/byte_primary_key_tests.rs +++ b/tests/byte_primary_key_tests.rs @@ -52,12 +52,18 @@ pub async fn create_and_update(db: &DatabaseConnection) -> Result<(), DbErr> { )) ); - let update_res = Entity::update(updated_active_model.clone()) + let update_res = Entity::update(updated_active_model) .filter(Column::Id.eq(vec![1, 2, 3])) .exec(db) .await?; - assert_eq!(update_res, updated_active_model); + assert_eq!( + update_res, + Model { + id: vec![1, 2, 3], + value: "First Row (Updated)".to_owned(), + } + ); assert_eq!( Entity::find() diff --git a/tests/common/bakery_chain/cake.rs b/tests/common/bakery_chain/cake.rs index 0ecaf5de6..fe380d740 100644 --- a/tests/common/bakery_chain/cake.rs +++ b/tests/common/bakery_chain/cake.rs @@ -70,15 +70,15 @@ impl ActiveModelBehavior for ActiveModel { } } - fn after_save(self, insert: bool) -> Result { + fn after_save(model: Model, insert: bool) -> Result { use rust_decimal_macros::dec; - if self.price.as_ref() < &dec!(0) { + if model.price < dec!(0) { Err(DbErr::Custom(format!( "[after_save] Invalid Price, insert: {}", insert ))) } else { - Ok(self) + Ok(model) } } diff --git a/tests/crud/deletes.rs b/tests/crud/deletes.rs index 4c34d36b1..01cfc7c20 100644 --- a/tests/crud/deletes.rs +++ b/tests/crud/deletes.rs @@ -29,7 +29,11 @@ pub async fn test_delete_cake(db: &DbConn) { let cakes = Cake::find().all(db).await.unwrap(); assert_eq!(cakes.len(), initial_cakes + 1); - let _result = cake.delete(db).await.expect("failed to delete cake"); + let _result = cake + .into_active_model() + .delete(db) + .await + .expect("failed to delete cake"); let cakes = Cake::find().all(db).await.unwrap(); assert_eq!(cakes.len(), initial_cakes); @@ -52,7 +56,11 @@ pub async fn test_delete_bakery(db: &DbConn) { initial_bakeries + 1 ); - let _result = bakery.delete(db).await.expect("failed to delete bakery"); + let _result = bakery + .into_active_model() + .delete(db) + .await + .expect("failed to delete bakery"); assert_eq!( Bakery::find().all(db).await.unwrap().len(), diff --git a/tests/crud/updates.rs b/tests/crud/updates.rs index 55af604e0..3a19746a9 100644 --- a/tests/crud/updates.rs +++ b/tests/crud/updates.rs @@ -43,8 +43,7 @@ pub async fn test_update_cake(db: &DbConn) { cake_am.name = Set("Extra chocolate mud cake".to_owned()); cake_am.price = Set(dec!(20.00)); - let _cake_update_res: cake::ActiveModel = - cake_am.update(db).await.expect("could not update cake"); + let _cake_update_res: cake::Model = cake_am.update(db).await.expect("could not update cake"); let cake: Option = Cake::find_by_id(cake_insert_res.last_insert_id) .one(db) @@ -80,7 +79,7 @@ pub async fn test_update_bakery(db: &DbConn) { bakery_am.name = Set("SeaBreeze Bakery".to_owned()); bakery_am.profit_margin = Set(12.00); - let _bakery_update_res: bakery::ActiveModel = + let _bakery_update_res: bakery::Model = bakery_am.update(db).await.expect("could not update bakery"); let bakery: Option = Bakery::find_by_id(bakery_insert_res.last_insert_id) @@ -111,11 +110,11 @@ pub async fn test_update_deleted_customer(db: &DbConn) { let customer_id = customer.id.clone(); - let _ = customer.delete(db).await; + let _ = customer.into_active_model().delete(db).await; assert_eq!(Customer::find().count(db).await.unwrap(), init_n_customers); let customer = customer::ActiveModel { - id: customer_id.clone(), + id: Set(customer_id.clone()), name: Set("John 2".to_owned()), ..Default::default() }; @@ -131,7 +130,7 @@ pub async fn test_update_deleted_customer(db: &DbConn) { assert_eq!(Customer::find().count(db).await.unwrap(), init_n_customers); - let customer: Option = Customer::find_by_id(customer_id.clone().unwrap()) + let customer: Option = Customer::find_by_id(customer_id.clone()) .one(db) .await .expect("could not find customer"); diff --git a/tests/query_tests.rs b/tests/query_tests.rs index 9d22c7b04..e8b3c0daf 100644 --- a/tests/query_tests.rs +++ b/tests/query_tests.rs @@ -43,7 +43,7 @@ pub async fn find_one_with_result() { let result = Bakery::find().one(&ctx.db).await.unwrap().unwrap(); - assert_eq!(result.id, bakery.id.unwrap()); + assert_eq!(result.id, bakery.id); ctx.delete().await; } @@ -83,13 +83,13 @@ pub async fn find_by_id_with_result() { .await .expect("could not insert bakery"); - let result = Bakery::find_by_id(bakery.id.clone().unwrap()) + let result = Bakery::find_by_id(bakery.id.clone()) .one(&ctx.db) .await .unwrap() .unwrap(); - assert_eq!(result.id, bakery.id.unwrap()); + assert_eq!(result.id, bakery.id); ctx.delete().await; } diff --git a/tests/relational_tests.rs b/tests/relational_tests.rs index ed5e92f5c..74444e2cf 100644 --- a/tests/relational_tests.rs +++ b/tests/relational_tests.rs @@ -35,7 +35,7 @@ pub async fn left_join() { "home": "0395555555", "address": "12 Test St, Testville, Vic, Australia" })), - bakery_id: Set(Some(bakery.id.clone().unwrap())), + bakery_id: Set(Some(bakery.id.clone())), ..Default::default() } .save(&ctx.db) @@ -123,8 +123,8 @@ pub async fn right_join() { .expect("could not insert customer"); let _order = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(15.10)), placed_at: Set(Utc::now().naive_utc()), @@ -209,8 +209,8 @@ pub async fn inner_join() { .expect("could not insert customer"); let kate_order_1 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(15.10)), placed_at: Set(Utc::now().naive_utc()), @@ -221,8 +221,8 @@ pub async fn inner_join() { .expect("could not insert order"); let kate_order_2 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(100.00)), placed_at: Set(Utc::now().naive_utc()), @@ -253,12 +253,12 @@ pub async fn inner_join() { assert_eq!(results.len(), 2); assert!((&results) .into_iter() - .any(|result| result.name == customer_kate.name.clone().unwrap() - && result.order_total == Some(kate_order_1.total.clone().unwrap()))); + .any(|result| result.name == customer_kate.name.clone() + && result.order_total == Some(kate_order_1.total.clone()))); assert!((&results) .into_iter() - .any(|result| result.name == customer_kate.name.clone().unwrap() - && result.order_total == Some(kate_order_2.total.clone().unwrap()))); + .any(|result| result.name == customer_kate.name.clone() + && result.order_total == Some(kate_order_2.total.clone()))); ctx.delete().await; } @@ -291,8 +291,8 @@ pub async fn group_by() { .expect("could not insert customer"); let kate_order_1 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(99.95)), placed_at: Set(Utc::now().naive_utc()), @@ -303,8 +303,8 @@ pub async fn group_by() { .expect("could not insert order"); let kate_order_2 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(200.00)), placed_at: Set(Utc::now().naive_utc()), @@ -343,27 +343,15 @@ pub async fn group_by() { assert_eq!(result.number_orders, Some(2)); assert_eq!( result.total_spent, - Some(kate_order_1.total.clone().unwrap() + kate_order_2.total.clone().unwrap()) + Some(kate_order_1.total.clone() + kate_order_2.total.clone()) ); assert_eq!( result.min_spent, - Some( - kate_order_1 - .total - .clone() - .unwrap() - .min(kate_order_2.total.clone().unwrap()) - ) + Some(kate_order_1.total.clone().min(kate_order_2.total.clone())) ); assert_eq!( result.max_spent, - Some( - kate_order_1 - .total - .clone() - .unwrap() - .max(kate_order_2.total.clone().unwrap()) - ) + Some(kate_order_1.total.clone().max(kate_order_2.total.clone())) ); ctx.delete().await; } @@ -397,8 +385,8 @@ pub async fn having() { .expect("could not insert customer"); let kate_order_1 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(100.00)), placed_at: Set(Utc::now().naive_utc()), @@ -409,8 +397,8 @@ pub async fn having() { .expect("could not insert order"); let _kate_order_2 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(12.00)), placed_at: Set(Utc::now().naive_utc()), @@ -429,8 +417,8 @@ pub async fn having() { .expect("could not insert customer"); let _bob_order_1 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_bob.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_bob.id.clone()), total: Set(dec!(50.0)), placed_at: Set(Utc::now().naive_utc()), @@ -441,8 +429,8 @@ pub async fn having() { .expect("could not insert order"); let _bob_order_2 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_bob.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_bob.id.clone()), total: Set(dec!(50.0)), placed_at: Set(Utc::now().naive_utc()), @@ -472,11 +460,8 @@ pub async fn having() { .unwrap(); assert_eq!(results.len(), 1); - assert_eq!(results[0].name, customer_kate.name.clone().unwrap()); - assert_eq!( - results[0].order_total, - Some(kate_order_1.total.clone().unwrap()) - ); + assert_eq!(results[0].name, customer_kate.name.clone()); + assert_eq!(results[0].order_total, Some(kate_order_1.total.clone())); ctx.delete().await; } diff --git a/tests/sequential_op_tests.rs b/tests/sequential_op_tests.rs index 30d9b0417..8c7120c09 100644 --- a/tests/sequential_op_tests.rs +++ b/tests/sequential_op_tests.rs @@ -42,7 +42,7 @@ async fn seed_data(db: &DatabaseConnection) { let baker_1 = baker::ActiveModel { name: Set("Baker 1".to_owned()), contact_details: Set(serde_json::json!({})), - bakery_id: Set(Some(bakery.id.clone().unwrap())), + bakery_id: Set(Some(bakery.id.clone())), ..Default::default() } .save(db) @@ -52,7 +52,7 @@ async fn seed_data(db: &DatabaseConnection) { let _baker_2 = baker::ActiveModel { name: Set("Baker 2".to_owned()), contact_details: Set(serde_json::json!({})), - bakery_id: Set(Some(bakery.id.clone().unwrap())), + bakery_id: Set(Some(bakery.id.clone())), ..Default::default() } .save(db) @@ -64,7 +64,7 @@ async fn seed_data(db: &DatabaseConnection) { price: Set(dec!(10.25)), gluten_free: Set(false), serial: Set(Uuid::new_v4()), - bakery_id: Set(Some(bakery.id.clone().unwrap())), + bakery_id: Set(Some(bakery.id.clone())), ..Default::default() }; @@ -75,7 +75,7 @@ async fn seed_data(db: &DatabaseConnection) { let cake_baker = cakes_bakers::ActiveModel { cake_id: Set(cake_insert_res.last_insert_id as i32), - baker_id: Set(baker_1.id.clone().unwrap()), + baker_id: Set(baker_1.id.clone()), ..Default::default() }; @@ -97,8 +97,8 @@ async fn seed_data(db: &DatabaseConnection) { .expect("could not insert customer"); let kate_order_1 = order::ActiveModel { - bakery_id: Set(bakery.id.clone().unwrap()), - customer_id: Set(customer_kate.id.clone().unwrap()), + bakery_id: Set(bakery.id.clone()), + customer_id: Set(customer_kate.id.clone()), total: Set(dec!(99.95)), placed_at: Set(Utc::now().naive_utc()), @@ -112,7 +112,7 @@ async fn seed_data(db: &DatabaseConnection) { cake_id: Set(cake_insert_res.last_insert_id as i32), price: Set(dec!(10.00)), quantity: Set(12), - order_id: Set(kate_order_1.id.clone().unwrap()), + order_id: Set(kate_order_1.id.clone()), ..Default::default() } .save(db) @@ -123,7 +123,7 @@ async fn seed_data(db: &DatabaseConnection) { cake_id: Set(cake_insert_res.last_insert_id as i32), price: Set(dec!(50.00)), quantity: Set(2), - order_id: Set(kate_order_1.id.clone().unwrap()), + order_id: Set(kate_order_1.id.clone()), ..Default::default() } .save(db) @@ -243,7 +243,7 @@ async fn create_order(db: &DatabaseConnection, cake: cake::Model) { let order = order::ActiveModel { bakery_id: Set(cake.bakery_id.unwrap()), - customer_id: Set(another_customer.id.clone().unwrap()), + customer_id: Set(another_customer.id.clone()), total: Set(dec!(200.00)), placed_at: Set(Utc::now().naive_utc()), @@ -257,7 +257,7 @@ async fn create_order(db: &DatabaseConnection, cake: cake::Model) { cake_id: Set(cake.id), price: Set(dec!(10.00)), quantity: Set(300), - order_id: Set(order.id.clone().unwrap()), + order_id: Set(order.id.clone()), ..Default::default() } .save(db) @@ -276,7 +276,8 @@ pub async fn test_delete_bakery(db: &DatabaseConnection) { } .save(db) .await - .expect("could not insert bakery"); + .expect("could not insert bakery") + .into_active_model(); assert_eq!( Bakery::find().all(db).await.unwrap().len(), diff --git a/tests/stream_tests.rs b/tests/stream_tests.rs index 37e6c21d9..ba0705414 100644 --- a/tests/stream_tests.rs +++ b/tests/stream_tests.rs @@ -24,14 +24,14 @@ pub async fn stream() -> Result<(), DbErr> { .save(&ctx.db) .await?; - let result = Bakery::find_by_id(bakery.id.clone().unwrap()) + let result = Bakery::find_by_id(bakery.id.clone()) .stream(&ctx.db) .await? .next() .await .unwrap()?; - assert_eq!(result.id, bakery.id.unwrap()); + assert_eq!(result.id, bakery.id); ctx.delete().await; diff --git a/tests/string_primary_key_tests.rs b/tests/string_primary_key_tests.rs index c2e8d2db6..56496bdc4 100644 --- a/tests/string_primary_key_tests.rs +++ b/tests/string_primary_key_tests.rs @@ -29,9 +29,17 @@ pub async fn insert_repository(db: &DatabaseConnection) -> Result<(), DbErr> { } .into_active_model(); - let result = repository.clone().insert(db).await?; + let result = repository.insert(db).await?; - assert_eq!(repository, result); + assert_eq!( + result, + repository::Model { + id: "unique-id-001".to_owned(), + owner: "GC".to_owned(), + name: "G.C.".to_owned(), + description: None, + } + ); Ok(()) } @@ -69,12 +77,20 @@ pub async fn create_and_update_repository(db: &DatabaseConnection) -> Result<(), )) ); - let update_res = Repository::update(updated_active_model.clone()) + let update_res = Repository::update(updated_active_model) .filter(repository::Column::Id.eq("unique-id-002".to_owned())) .exec(db) .await?; - assert_eq!(update_res, updated_active_model); + assert_eq!( + update_res, + repository::Model { + id: "unique-id-002".to_owned(), + owner: "GC".to_owned(), + name: "G.C.".to_owned(), + description: Some("description...".to_owned()), + } + ); let updated_active_model = repository::ActiveModel { description: Set(None), @@ -86,7 +102,15 @@ pub async fn create_and_update_repository(db: &DatabaseConnection) -> Result<(), .exec(db) .await?; - assert_eq!(update_res, updated_active_model); + assert_eq!( + update_res, + repository::Model { + id: "unique-id-002".to_owned(), + owner: "GC".to_owned(), + name: "G.C.".to_owned(), + description: None, + } + ); Ok(()) } diff --git a/tests/transaction_tests.rs b/tests/transaction_tests.rs index 7845843e0..34b8df22f 100644 --- a/tests/transaction_tests.rs +++ b/tests/transaction_tests.rs @@ -408,7 +408,7 @@ pub async fn transaction_with_active_model_behaviour() -> Result<(), DbErr> { assert_eq!(cake::Entity::find().all(&txn).await?.len(), 2); assert_eq!( - readonly_cake_1.delete(&txn).await.err(), + readonly_cake_1.into_active_model().delete(&txn).await.err(), Some(DbErr::Custom( "[before_delete] Cannot be deleted".to_owned() )) @@ -428,7 +428,7 @@ pub async fn transaction_with_active_model_behaviour() -> Result<(), DbErr> { assert_eq!(cake::Entity::find().all(&txn).await?.len(), 3); assert_eq!( - readonly_cake_2.delete(&txn).await.err(), + readonly_cake_2.into_active_model().delete(&txn).await.err(), Some(DbErr::Custom("[after_delete] Cannot be deleted".to_owned())) ); diff --git a/tests/uuid_tests.rs b/tests/uuid_tests.rs index cdda344b8..1053bb55f 100644 --- a/tests/uuid_tests.rs +++ b/tests/uuid_tests.rs @@ -28,12 +28,11 @@ pub async fn insert_metadata(db: &DatabaseConnection) -> Result<(), DbErr> { bytes: vec![1, 2, 3], date: Some(Date::from_ymd(2021, 9, 27)), time: Some(Time::from_hms(11, 32, 55)), - } - .into_active_model(); + }; - let result = metadata.clone().insert(db).await?; + let result = metadata.clone().into_active_model().insert(db).await?; - assert_eq!(metadata, result); + assert_eq!(result, metadata); Ok(()) } From 1290becd763b4eab56c18c722160f500e64834d5 Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Tue, 30 Nov 2021 19:00:19 +0800 Subject: [PATCH 3/6] Update README --- README.md | 4 ++-- src/lib.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 61bba222f..6e785e9cc 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ let mut pear: fruit::ActiveModel = pear.unwrap().into(); pear.name = Set("Sweet pear".to_owned()); // update one -let pear: fruit::ActiveModel = pear.update(db).await?; +let pear: fruit::Model = pear.update(db).await?; // update many: UPDATE "fruit" SET "cake_id" = NULL WHERE "fruit"."name" LIKE '%Apple%' Fruit::update_many() @@ -142,7 +142,7 @@ let banana = fruit::ActiveModel { }; // create, because primary key `id` is `Unset` -let mut banana = banana.save(db).await?; +let mut banana = banana.save(db).await?.into_active_model(); banana.name = Set("Banana Mongo".to_owned()); diff --git a/src/lib.rs b/src/lib.rs index 469619f03..27944dc6b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -184,7 +184,7 @@ //! pear.name = Set("Sweet pear".to_owned()); //! //! // update one -//! let pear: fruit::ActiveModel = pear.update(db).await?; +//! let pear: fruit::Model = pear.update(db).await?; //! //! // update many: UPDATE "fruit" SET "cake_id" = NULL WHERE "fruit"."name" LIKE '%Apple%' //! Fruit::update_many() @@ -207,7 +207,7 @@ //! }; //! //! // create, because primary key `id` is `Unset` -//! let mut banana = banana.save(db).await?; +//! let mut banana = banana.save(db).await?.into_active_model(); //! //! banana.name = Set("Banana Mongo".to_owned()); //! From 597529aac074471e507cc9d1f7de9ceb759e3a3a Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Tue, 30 Nov 2021 19:05:45 +0800 Subject: [PATCH 4/6] Fix clippy warnings --- tests/crud/updates.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/crud/updates.rs b/tests/crud/updates.rs index 3a19746a9..b8ea6eb7d 100644 --- a/tests/crud/updates.rs +++ b/tests/crud/updates.rs @@ -108,13 +108,13 @@ pub async fn test_update_deleted_customer(db: &DbConn) { init_n_customers + 1 ); - let customer_id = customer.id.clone(); + let customer_id = customer.id; let _ = customer.into_active_model().delete(db).await; assert_eq!(Customer::find().count(db).await.unwrap(), init_n_customers); let customer = customer::ActiveModel { - id: Set(customer_id.clone()), + id: Set(customer_id), name: Set("John 2".to_owned()), ..Default::default() }; @@ -130,7 +130,7 @@ pub async fn test_update_deleted_customer(db: &DbConn) { assert_eq!(Customer::find().count(db).await.unwrap(), init_n_customers); - let customer: Option = Customer::find_by_id(customer_id.clone()) + let customer: Option = Customer::find_by_id(customer_id) .one(db) .await .expect("could not find customer"); From 48c6e3677a7981ccb9b36f1a398623d494e608c2 Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Tue, 30 Nov 2021 19:15:45 +0800 Subject: [PATCH 5/6] Fixup --- examples/basic/src/operation.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/basic/src/operation.rs b/examples/basic/src/operation.rs index 49d239190..4b84da15a 100644 --- a/examples/basic/src/operation.rs +++ b/examples/basic/src/operation.rs @@ -33,7 +33,7 @@ pub async fn insert_and_update(db: &DbConn) -> Result<(), DbErr> { let mut pear: fruit::ActiveModel = pear.unwrap().into(); pear.name = Set("Sweet pear".to_owned()); - let pear: fruit::ActiveModel = pear.update(db).await?; + let pear: fruit::Model = pear.update(db).await?; println!(); println!("Updated: {:?}\n", pear); @@ -46,14 +46,14 @@ pub async fn save_active_model(db: &DbConn) -> Result<(), DbErr> { name: Set("Banana".to_owned()), ..Default::default() }; - let mut banana = banana.save(db).await?; + let mut banana: fruit::ActiveModel = banana.save(db).await?.into_active_model(); println!(); println!("Inserted: {:?}\n", banana); banana.name = Set("Banana Mongo".to_owned()); - let banana = banana.save(db).await?; + let banana: fruit::ActiveModel = banana.save(db).await?.into_active_model(); println!(); println!("Updated: {:?}\n", banana); From 998e1267d49d2e3457ff594b1a0258a1ab9a441b Mon Sep 17 00:00:00 2001 From: Billy Chan Date: Wed, 15 Dec 2021 14:27:46 +0800 Subject: [PATCH 6/6] Fixup --- tests/active_enum_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/active_enum_tests.rs b/tests/active_enum_tests.rs index 9291538a7..eaf940db8 100644 --- a/tests/active_enum_tests.rs +++ b/tests/active_enum_tests.rs @@ -146,7 +146,7 @@ pub async fn insert_active_enum_child(db: &DatabaseConnection) -> Result<(), DbE category: Set(Some(Category::Big)), color: Set(Some(Color::Black)), tea: Set(Some(Tea::EverydayTea)), - ..am + ..am.into_active_model() } .save(db) .await?;