Test inner join

This commit is contained in:
Sam Samai 2021-07-15 22:16:01 +10:00
parent c1eddc4887
commit 1526bb2b3b

View File

@ -11,6 +11,7 @@ pub use common::{bakery_chain::*, setup::*, TestContext};
async fn main() {
test_left_join().await;
test_right_join().await;
test_inner_join().await;
}
pub async fn test_left_join() {
@ -160,3 +161,86 @@ pub async fn test_right_join() {
ctx.delete().await;
}
pub async fn test_inner_join() {
let ctx = TestContext::new("mysql://root:@localhost", "test_inner_join").await;
let bakery = bakery::ActiveModel {
name: Set("SeaSide Bakery".to_owned()),
profit_margin: Set(10.4),
..Default::default()
}
.save(&ctx.db)
.await
.expect("could not insert bakery");
let customer_kate = customer::ActiveModel {
name: Set("Kate".to_owned()),
..Default::default()
}
.save(&ctx.db)
.await
.expect("could not insert customer");
let _customer_jim = customer::ActiveModel {
name: Set("Jim".to_owned()),
..Default::default()
}
.save(&ctx.db)
.await
.expect("could not insert customer");
let kate_order_1 = order::ActiveModel {
bakery_id: Set(Some(bakery.id.clone().unwrap())),
customer_id: Set(Some(customer_kate.id.clone().unwrap())),
total: Set(dec!(15.10)),
placed_at: Set(Utc::now().naive_utc()),
..Default::default()
}
.save(&ctx.db)
.await
.expect("could not insert order");
let kate_order_2 = order::ActiveModel {
bakery_id: Set(Some(bakery.id.clone().unwrap())),
customer_id: Set(Some(customer_kate.id.clone().unwrap())),
total: Set(dec!(100.00)),
placed_at: Set(Utc::now().naive_utc()),
..Default::default()
}
.save(&ctx.db)
.await
.expect("could not insert order");
#[derive(Debug, FromQueryResult)]
struct SelectResult {
name: String,
order_total: Option<Decimal>,
}
let select = order::Entity::find()
.inner_join(customer::Entity)
.select_only()
.column(customer::Column::Name)
.column_as(order::Column::Total, "order_total");
let results = select
.into_model::<SelectResult>()
.all(&ctx.db)
.await
.unwrap();
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())));
assert!((&results)
.into_iter()
.any(|result| result.name == customer_kate.name.clone().unwrap()
&& result.order_total == Some(kate_order_2.total.clone().unwrap())));
ctx.delete().await;
}