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

Represent several relations between same types #104

Merged
merged 9 commits into from
Sep 3, 2021
Merged
Show file tree
Hide file tree
Changes from 7 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
2 changes: 1 addition & 1 deletion src/entity/column.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::str::FromStr;
use crate::{EntityName, IdenStatic, Iterable};
use sea_query::{DynIden, Expr, SeaRc, SelectStatement, SimpleExpr, Value};
use std::str::FromStr;

#[derive(Debug, Clone)]
pub struct ColumnDef {
Expand Down
9 changes: 8 additions & 1 deletion src/entity/model.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{DbErr, EntityTrait, QueryFilter, QueryResult, Related, Select};
use crate::{DbErr, EntityTrait, Linked, QueryFilter, QueryResult, Related, Select};
pub use sea_query::Value;
use std::fmt::Debug;

Expand All @@ -16,6 +16,13 @@ pub trait ModelTrait: Clone + Debug {
{
<Self::Entity as Related<R>>::find_related().belongs_to(self)
}

fn find_linked<L>(&self, l: L) -> Select<L::ToEntity>
where
L: Linked<FromEntity = Self::Entity>,
{
l.find_linked()
}
}

pub trait FromQueryResult {
Expand Down
6 changes: 3 additions & 3 deletions src/entity/prelude.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
pub use crate::{
error::*, ActiveModelBehavior, ActiveModelTrait, ColumnDef, ColumnTrait, ColumnType,
DeriveActiveModel, DeriveActiveModelBehavior, DeriveColumn, DeriveCustomColumn, DeriveEntity,
DeriveModel, DerivePrimaryKey, EntityName, EntityTrait, EnumIter, Iden, IdenStatic, ModelTrait,
PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult, Related, RelationDef,
RelationTrait, Select, Value,
DeriveModel, DerivePrimaryKey, EntityName, EntityTrait, EnumIter, Iden, IdenStatic, Linked,
ModelTrait, PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult, Related,
RelationDef, RelationTrait, Select, Value,
};

#[cfg(feature = "with-json")]
Expand Down
16 changes: 16 additions & 0 deletions src/entity/relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ where
}
}

pub trait Linked {
type FromEntity: EntityTrait;

type ToEntity: EntityTrait;

fn link(&self) -> Vec<RelationDef>;

fn find_linked(&self) -> Select<Self::ToEntity> {
let mut select = Select::new();
for rel in self.link().into_iter().rev() {
select = select.join_rev(JoinType::InnerJoin, rel);
}
select
}
}

pub struct RelationDef {
pub rel_type: RelationType,
pub from_tbl: TableRef,
Expand Down
2 changes: 1 addition & 1 deletion src/executor/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ where
E: EntityTrait,
F: EntityTrait,
{
fn into_model<M, N>(self) -> Selector<SelectTwoModel<M, N>>
pub fn into_model<M, N>(self) -> Selector<SelectTwoModel<M, N>>
where
M: FromQueryResult,
N: FromQueryResult,
Expand Down
29 changes: 28 additions & 1 deletion src/query/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
RelationDef,
};
use sea_query::{
Alias, Expr, IntoCondition, SeaRc, SelectExpr, SelectStatement, SimpleExpr, TableRef,
Alias, Expr, Iden, IntoCondition, SeaRc, SelectExpr, SelectStatement, SimpleExpr, TableRef,
};
pub use sea_query::{Condition, ConditionalStatement, DynIden, JoinType, Order, OrderedStatement};

Expand Down Expand Up @@ -66,6 +66,33 @@ pub trait QuerySelect: Sized {
self
}

/// Add a select column with prefixed alias
/// ```
/// use sea_orm::{entity::*, query::*, tests_cfg::cake, DbBackend};
///
/// assert_eq!(
/// cake::Entity::find()
/// .select_only()
/// .column_as_prefixed(cake::Column::Id.count(), "A_", cake::Column::Id)
/// .build(DbBackend::Postgres)
/// .to_string(),
/// r#"SELECT COUNT("cake"."id") AS "A_id" FROM "cake""#
/// );
/// ```
fn column_as_prefixed<C, I>(mut self, col: C, prefix: &str, alias: I) -> Self
where
C: IntoSimpleExpr,
I: Iden,
{
self.query().expr(SelectExpr {
expr: col.into_simple_expr(),
alias: Some(SeaRc::new(Alias::new(
vec![prefix, alias.to_string().as_str()].join("").as_str(),
))),
});
self
}

/// Add a group by column
/// ```
/// use sea_orm::{entity::*, query::*, tests_cfg::cake, DbBackend};
Expand Down
55 changes: 54 additions & 1 deletion src/query/join.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{EntityTrait, QuerySelect, Related, Select, SelectTwo, SelectTwoMany};
use crate::{EntityTrait, Linked, QuerySelect, Related, Select, SelectTwo, SelectTwoMany};
pub use sea_query::JoinType;

impl<E> Select<E>
Expand Down Expand Up @@ -57,6 +57,19 @@ where
{
self.left_join(r).select_with(r)
}

/// Left Join with a Linked Entity and select both Entity.
pub fn find_also_linked<L, T>(self, l: L) -> SelectTwo<E, T>
where
L: Linked<FromEntity = E, ToEntity = T>,
T: EntityTrait,
{
let mut slf = self;
for rel in l.link() {
slf = slf.join(JoinType::LeftJoin, rel);
}
slf.select_also(T::default())
}
}

#[cfg(test)]
Expand Down Expand Up @@ -220,4 +233,44 @@ mod tests {
.join(" ")
);
}

#[test]
fn join_10() {
let cake_model = cake::Model {
id: 12,
name: "".to_owned(),
};

assert_eq!(
cake_model
.find_linked(cake::CakeToFilling)
.build(DbBackend::MySql)
.to_string(),
[
r#"SELECT `filling`.`id`, `filling`.`name`"#,
r#"FROM `filling`"#,
r#"INNER JOIN `cake_filling` ON `cake_filling`.`filling_id` = `filling`.`id`"#,
r#"INNER JOIN `cake` ON `cake`.`id` = `cake_filling`.`cake_id`"#,
]
.join(" ")
);
}

#[test]
fn join_11() {
assert_eq!(
cake::Entity::find()
.find_also_linked(cake::CakeToFilling)
.build(DbBackend::MySql)
.to_string(),
[
r#"SELECT `cake`.`id` AS `A_id`, `cake`.`name` AS `A_name`,"#,
r#"`filling`.`id` AS `B_id`, `filling`.`name` AS `B_name`"#,
r#"FROM `cake`"#,
r#"LEFT JOIN `cake_filling` ON `cake`.`id` = `cake_filling`.`cake_id`"#,
r#"LEFT JOIN `filling` ON `cake_filling`.`filling_id` = `filling`.`id`"#,
]
.join(" ")
);
}
}
15 changes: 15 additions & 0 deletions src/tests_cfg/cake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,19 @@ impl Related<super::filling::Entity> for Entity {
}
}

pub struct CakeToFilling;

impl Linked for CakeToFilling {
type FromEntity = Entity;

type ToEntity = super::filling::Entity;

fn link(&self) -> Vec<RelationDef> {
vec![
super::cake_filling::Relation::Cake.def().rev(),
super::cake_filling::Relation::Filling.def(),
]
}
}

impl ActiveModelBehavior for ActiveModel {}
18 changes: 18 additions & 0 deletions tests/common/bakery_chain/baker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,22 @@ impl Related<super::cake::Entity> for Entity {
}
}

pub struct BakedForCustomer;

impl Linked for BakedForCustomer {
type FromEntity = Entity;

type ToEntity = super::customer::Entity;

fn link(&self) -> Vec<RelationDef> {
vec![
super::cakes_bakers::Relation::Baker.def().rev(),
super::cakes_bakers::Relation::Cake.def(),
super::lineitem::Relation::Cake.def().rev(),
super::lineitem::Relation::Order.def(),
super::order::Relation::Customer.def(),
]
}
}

impl ActiveModelBehavior for ActiveModel {}
Loading