Insert & Update Return Model (#339)

* Update insert & update API

* Update test cases

* Update README

* Fix clippy warnings

* Fixup

* Fixup
This commit is contained in:
Billy Chan 2021-12-18 14:30:10 +08:00 committed by GitHub
parent acf8eac441
commit 5104cd3573
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 160 additions and 145 deletions

View File

@ -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());

View File

@ -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);

View File

@ -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!(
@ -247,17 +245,17 @@ pub trait ActiveModelTrait: Clone + Debug {
/// # Ok(())
/// # }
/// ```
async fn insert<'a, C>(self, db: &'a C) -> Result<Self, DbErr>
async fn insert<'a, C>(self, db: &'a C) -> Result<<Self::Entity as EntityTrait>::Model, DbErr>
where
<Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>,
Self: ActiveModelBehavior + 'a,
C: ConnectionTrait<'a>,
{
let am = ActiveModelBehavior::before_save(self, true)?;
let am = <Self::Entity as EntityTrait>::insert(am)
let model = <Self::Entity as EntityTrait>::insert(am)
.exec_with_returning(db)
.await?;
ActiveModelBehavior::after_save(am, true)
Self::after_save(model, true)
}
/// Perform the `UPDATE` operation on an ActiveModel
@ -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!(
@ -371,26 +367,26 @@ pub trait ActiveModelTrait: Clone + Debug {
/// # Ok(())
/// # }
/// ```
async fn update<'a, C>(self, db: &'a C) -> Result<Self, DbErr>
async fn update<'a, C>(self, db: &'a C) -> Result<<Self::Entity as EntityTrait>::Model, DbErr>
where
<Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>,
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: <Self::Entity as EntityTrait>::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<Self, DbErr>
async fn save<'a, C>(self, db: &'a C) -> Result<<Self::Entity as EntityTrait>::Model, DbErr>
where
<Self::Entity as EntityTrait>::Model: IntoActiveModel<Self>,
Self: ActiveModelBehavior + 'a,
C: ConnectionTrait<'a>,
{
let mut am = self;
let am = self;
let mut is_update = true;
for key in <Self::Entity as EntityTrait>::PrimaryKey::iter() {
let col = key.into_column();
@ -400,11 +396,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 +498,11 @@ pub trait ActiveModelBehavior: ActiveModelTrait {
}
/// Will be called after saving
fn after_save(self, insert: bool) -> Result<Self, DbErr> {
Ok(self)
fn after_save(
model: <Self::Entity as EntityTrait>::Model,
insert: bool,
) -> Result<<Self::Entity as EntityTrait>::Model, DbErr> {
Ok(model)
}
/// Will be called before deleting

View File

@ -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!(

View File

@ -55,7 +55,7 @@ where
pub fn exec_with_returning<'a, C>(
self,
db: &'a C,
) -> impl Future<Output = Result<A, DbErr>> + '_
) -> impl Future<Output = Result<<A::Entity as EntityTrait>::Model, DbErr>> + '_
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
C: ConnectionTrait<'a>,
@ -92,13 +92,13 @@ where
pub fn exec_with_returning<'a, C>(
self,
db: &'a C,
) -> impl Future<Output = Result<A, DbErr>> + '_
) -> impl Future<Output = Result<<A::Entity as EntityTrait>::Model, DbErr>> + '_
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
C: ConnectionTrait<'a>,
A: 'a,
{
exec_insert_with_returning(self.primary_key, self.query, db)
exec_insert_with_returning::<A, _>(self.primary_key, self.query, db)
}
}
@ -140,7 +140,7 @@ async fn exec_insert_with_returning<'a, A, C>(
primary_key: Option<ValueTuple>,
mut insert_statement: InsertStatement,
db: &'a C,
) -> Result<A, DbErr>
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
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())),
}
}

View File

@ -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<A, DbErr>
pub async fn exec<'b, C>(self, db: &'b C) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
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<A, DbErr>
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
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())),
}
}
@ -196,7 +194,6 @@ mod tests {
id: 1,
name: "Cheese Cake".to_owned(),
}
.into_active_model()
);
let model = cake::Model {

View File

@ -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());
//!

View File

@ -27,25 +27,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()
@ -58,11 +58,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?;
@ -89,7 +89,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);
@ -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?;

View File

@ -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());

View File

@ -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()

View File

@ -70,15 +70,15 @@ impl ActiveModelBehavior for ActiveModel {
}
}
fn after_save(self, insert: bool) -> Result<Self, DbErr> {
fn after_save(model: Model, insert: bool) -> Result<Model, DbErr> {
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)
}
}

View File

@ -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(),

View File

@ -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::Model> = 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::Model> = Bakery::find_by_id(bakery_insert_res.last_insert_id)
@ -109,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.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),
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::Model> = Customer::find_by_id(customer_id.clone().unwrap())
let customer: Option<customer::Model> = Customer::find_by_id(customer_id)
.one(db)
.await
.expect("could not find customer");

View File

@ -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;
}

View File

@ -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)
@ -124,8 +124,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()),
@ -210,8 +210,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()),
@ -222,8 +222,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()),
@ -254,12 +254,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;
}
@ -292,8 +292,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()),
@ -304,8 +304,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()),
@ -345,27 +345,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;
}
@ -399,8 +387,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()),
@ -411,8 +399,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()),
@ -431,8 +419,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()),
@ -443,8 +431,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()),
@ -474,11 +462,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;
}

View File

@ -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(),

View File

@ -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;

View File

@ -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(())
}

View File

@ -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()))
);

View File

@ -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(())
}