Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Easy joins with MockDatabase #447 #455

Merged
merged 7 commits into from
Feb 6, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 52 additions & 3 deletions src/database/mock.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
error::*, DatabaseConnection, DbBackend, EntityTrait, ExecResult, ExecResultHolder, Iden,
Iterable, MockDatabaseConnection, MockDatabaseTrait, ModelTrait, QueryResult, QueryResultRow,
Statement,
IdenStatic, Iterable, MockDatabaseConnection, MockDatabaseTrait, ModelTrait, QueryResult,
QueryResultRow, Statement, SelectA, SelectB
};
use sea_query::{Value, ValueType, Values};
use std::{collections::BTreeMap, sync::Arc};
Expand Down Expand Up @@ -204,6 +204,33 @@ where
}
}

impl<M, N> IntoMockRow for (M, N)
where
M: ModelTrait,
N: ModelTrait,
{
fn into_mock_row(self) -> MockRow {
let mut mapped_join = BTreeMap::new();

for column in <<M as ModelTrait>::Entity as EntityTrait>::Column::iter() {
mapped_join.insert(format!("{}{}", SelectA.as_str(), column.as_str()), self.0.get(column));
}
for column in <<N as ModelTrait>::Entity as EntityTrait>::Column::iter() {
mapped_join.insert(format!("{}{}", SelectB.as_str(), column.as_str()), self.1.get(column));
}

mapped_join.into_mock_row()
}
}

impl IntoMockRow for BTreeMap<String, Value> {
fn into_mock_row(self) -> MockRow {
MockRow {
values: self.into_iter().map(|(k, v)| (k, v)).collect(),
}
}
}

impl IntoMockRow for BTreeMap<&str, Value> {
fn into_mock_row(self) -> MockRow {
MockRow {
Expand Down Expand Up @@ -312,7 +339,7 @@ impl OpenTransaction {
mod tests {
use crate::{
entity::*, tests_cfg::*, ConnectionTrait, DbBackend, DbErr, MockDatabase, Statement,
Transaction, TransactionError,
Transaction, TransactionError, IntoMockRow,
};
use pretty_assertions::assert_eq;

Expand Down Expand Up @@ -605,4 +632,26 @@ mod tests {

Ok(())
}

#[smol_potat::test]
async fn test_mocked_join() {
let mocked_row = (
cake::Model {
id: 1,
name: "Apple Cake".to_owned(),
},
fruit::Model {
id: 2,
name: "Apple".to_owned(),
cake_id: Some(1),
}
).into_mock_row();

let a_id = mocked_row.try_get::<i32>("A_id");
assert!(a_id.is_ok());
assert_eq!(1, a_id.unwrap());
let b_id = mocked_row.try_get::<i32>("B_id");
assert!(b_id.is_ok());
assert_eq!(2, b_id.unwrap());
}
}