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

Add find_linked_recursive method to ModelTrait #2480

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
105 changes: 80 additions & 25 deletions src/entity/link.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use crate::{
join_tbl_on_condition, unpack_table_ref, EntityTrait, QuerySelect, RelationDef, Select,
};
use sea_query::{Alias, Condition, IntoIden, JoinType, SeaRc};
use sea_query::{
Alias, CommonTableExpression, Condition, IntoIden, IntoTableRef, JoinType, SeaRc, UnionType,
};

/// Same as [RelationDef]
pub type LinkDef = RelationDef;
Expand All @@ -19,30 +21,83 @@ pub trait Linked {

/// Find all the Entities that are linked to the Entity
fn find_linked(&self) -> Select<Self::ToEntity> {
let mut select = Select::new();
for (i, mut rel) in self.link().into_iter().rev().enumerate() {
let from_tbl = Alias::new(format!("r{i}")).into_iden();
let to_tbl = if i > 0 {
Alias::new(format!("r{}", i - 1)).into_iden()
} else {
unpack_table_ref(&rel.to_tbl)
};
let table_ref = rel.from_tbl;

let mut condition = Condition::all().add(join_tbl_on_condition(
SeaRc::clone(&from_tbl),
SeaRc::clone(&to_tbl),
rel.from_col,
rel.to_col,
));
if let Some(f) = rel.on_condition.take() {
condition = condition.add(f(SeaRc::clone(&from_tbl), SeaRc::clone(&to_tbl)));
}

select
.query()
.join_as(JoinType::InnerJoin, table_ref, from_tbl, condition);
find_linked(self.link().into_iter().rev(), JoinType::InnerJoin)
}

/// Find all the Entities that are linked to the Entity, in reverse
fn find_linked_rev(&self) -> Select<Self::FromEntity> {
find_linked(
self.link().into_iter().map(LinkDef::rev),
JoinType::LeftJoin,
)
}
}

pub(crate) fn find_linked<I, E>(links: I, join: JoinType) -> Select<E>
where
I: Iterator<Item = LinkDef>,
E: EntityTrait,
{
let mut select = Select::new();
for (i, mut rel) in links.enumerate() {
let from_tbl = Alias::new(format!("r{i}")).into_iden();
let to_tbl = if i > 0 {
Alias::new(format!("r{}", i - 1)).into_iden()
} else {
unpack_table_ref(&rel.to_tbl)
};
let table_ref = rel.from_tbl;

let mut condition = Condition::all().add(join_tbl_on_condition(
SeaRc::clone(&from_tbl),
SeaRc::clone(&to_tbl),
rel.from_col,
rel.to_col,
));
if let Some(f) = rel.on_condition.take() {
condition = condition.add(f(SeaRc::clone(&from_tbl), SeaRc::clone(&to_tbl)));
}
select

select.query().join_as(join, table_ref, from_tbl, condition);
}
select
}

pub(crate) fn find_linked_recursive<E>(
mut initial_query: Select<E>,
mut link: Vec<LinkDef>,
) -> Select<E>
where
E: EntityTrait,
{
let cte_name = Alias::new("cte");

let Some(last) = link.last_mut() else {
return initial_query;
};
last.from_tbl = cte_name.clone().into_table_ref();
let mut recursive_query: Select<E> =
find_linked(link.into_iter().rev(), JoinType::InnerJoin).select_only();
initial_query.query.exprs_mut_for_each(|expr| {
recursive_query.query.expr(expr.clone());
});

let mut cte_query = initial_query.query.clone();
cte_query.union(UnionType::All, recursive_query.query);

let cte = CommonTableExpression::new()
.table_name(cte_name.clone())
.query(cte_query)
.to_owned();

let mut select = E::find().select_only();
initial_query.query.exprs_mut_for_each(|expr| {
select.query.expr(expr.clone());
});
select
.query
.from_clear()
.from_as(cte_name, E::default())
.with_cte(cte);
select
}
50 changes: 43 additions & 7 deletions src/entity/model.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::{
ActiveModelBehavior, ActiveModelTrait, ConnectionTrait, DbErr, DeleteResult, EntityTrait,
IntoActiveModel, Linked, QueryFilter, QueryResult, Related, Select, SelectModel, SelectorRaw,
Statement,
find_linked, find_linked_recursive, ActiveModelBehavior, ActiveModelTrait, ConnectionTrait,
DbErr, DeleteResult, EntityTrait, IntoActiveModel, Linked, QueryFilter, QueryResult,
QuerySelect, Related, Select, SelectModel, SelectorRaw, Statement,
};
use async_trait::async_trait;
pub use sea_query::Value;
pub use sea_query::{JoinType, Value};
use std::fmt::Debug;

/// A Trait for a Model
Expand All @@ -25,16 +25,52 @@ pub trait ModelTrait: Clone + Send + Debug {
R: EntityTrait,
Self::Entity: Related<R>,
{
<Self::Entity as Related<R>>::find_related().belongs_to(self)
let mut select = Select::<R>::new();
if let Some(via) = <Self::Entity as Related<R>>::via() {
select = select.join_rev(JoinType::InnerJoin, via)
}
select.find_by_relation(<Self::Entity as Related<R>>::to(), self, None)
}

/// Find linked Models
fn find_linked<L>(&self, l: L) -> Select<L::ToEntity>
where
L: Linked<FromEntity = Self::Entity>,
{
let tbl_alias = &format!("r{}", l.link().len() - 1);
l.find_linked().belongs_to_tbl_alias(self, tbl_alias)
let mut link = l.link().into_iter().peekable();
match link.next_if(|rel| rel.on_condition.is_none()) {
Some(last) => {
let tbl_alias = if link.len() == 0 {
None
} else {
Some(format!("r{}", link.len() - 1))
};
find_linked(link.rev(), JoinType::InnerJoin).find_by_relation(last, self, tbl_alias)
}
None => {
let tbl_alias = &format!("r{}", link.len() - 1);
find_linked(link.rev(), JoinType::InnerJoin).belongs_to_tbl_alias(self, tbl_alias)
}
}
}

/// Find linked Models, recursively
fn find_linked_recursive<L>(&self, l: L) -> Select<L::ToEntity>
where
L: Linked<FromEntity = Self::Entity, ToEntity = Self::Entity>,
{
// Have to do this because L is not Clone
let link = l.link();
let initial_query = self.find_linked(l);
find_linked_recursive(initial_query, link)
}

/// Find self and linked Models, recursively
fn find_with_linked_recursive<L>(&self, l: L) -> Select<L::ToEntity>
where
L: Linked<FromEntity = Self::Entity, ToEntity = Self::Entity>,
{
Self::Entity::find().belongs_to(self).find_with_linked_recursive(l)
}

/// Delete a model
Expand Down
4 changes: 3 additions & 1 deletion src/entity/relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,9 @@ impl RelationDef {
is_owner: !self.is_owner,
on_delete: self.on_delete,
on_update: self.on_update,
on_condition: self.on_condition,
on_condition: self
.on_condition
.map(|f| Box::new(move |left, right| f(right, left)) as _),
fk_name: None,
condition_type: self.condition_type,
}
Expand Down
24 changes: 12 additions & 12 deletions src/executor/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -851,9 +851,9 @@ mod tests {
r#"SELECT "cake"."id" AS "A_id", "cake"."name" AS "A_name","#,
r#""r2"."id" AS "B_id", "r2"."name" AS "B_name""#,
r#"FROM "cake""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "cake"."id" = "r0"."cake_id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r0"."filling_id" = "r1"."id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r1"."vendor_id" = "r2"."id""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "r0"."cake_id" = "cake"."id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r1"."id" = "r0"."filling_id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r2"."id" = "r1"."vendor_id""#,
r#"WHERE "cake"."id" < $1 ORDER BY "cake"."id" ASC, "vendor"."id" ASC LIMIT $2"#,
]
.join(" ")
Expand Down Expand Up @@ -916,9 +916,9 @@ mod tests {
r#"SELECT "cake"."id" AS "A_id", "cake"."name" AS "A_name","#,
r#""r2"."id" AS "B_id", "r2"."name" AS "B_name""#,
r#"FROM "cake""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "cake"."id" = "r0"."cake_id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r0"."filling_id" = "r1"."id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r1"."vendor_id" = "r2"."id""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "r0"."cake_id" = "cake"."id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r1"."id" = "r0"."filling_id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r2"."id" = "r1"."vendor_id""#,
r#"WHERE "cake"."id" < $1 ORDER BY "cake"."id" ASC, "vendor"."id" ASC LIMIT $2"#,
]
.join(" ")
Expand Down Expand Up @@ -966,9 +966,9 @@ mod tests {
r#"SELECT "cake"."id" AS "A_id", "cake"."name" AS "A_name","#,
r#""r2"."id" AS "B_id", "r2"."name" AS "B_name""#,
r#"FROM "cake""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "cake"."id" = "r0"."cake_id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r0"."filling_id" = "r1"."id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r1"."vendor_id" = "r2"."id""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "r0"."cake_id" = "cake"."id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r1"."id" = "r0"."filling_id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r2"."id" = "r1"."vendor_id""#,
r#"WHERE "vendor"."id" < $1 ORDER BY "vendor"."id" ASC, "cake"."id" ASC LIMIT $2"#,
]
.join(" ")
Expand Down Expand Up @@ -1019,9 +1019,9 @@ mod tests {
r#"SELECT "cake"."id" AS "A_id", "cake"."name" AS "A_name","#,
r#""r2"."id" AS "B_id", "r2"."name" AS "B_name""#,
r#"FROM "cake""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "cake"."id" = "r0"."cake_id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r0"."filling_id" = "r1"."id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r1"."vendor_id" = "r2"."id""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "r0"."cake_id" = "cake"."id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r1"."id" = "r0"."filling_id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r2"."id" = "r1"."vendor_id""#,
r#"WHERE "vendor"."id" < $1 ORDER BY "vendor"."id" ASC, "cake"."id" ASC LIMIT $2"#,
]
.join(" ")
Expand Down
12 changes: 6 additions & 6 deletions src/executor/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1558,9 +1558,9 @@ mod tests {
r#"SELECT "cake"."id" AS "A_id", "cake"."name" AS "A_name","#,
r#""r2"."id" AS "B_id", "r2"."name" AS "B_name""#,
r#"FROM "cake""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "cake"."id" = "r0"."cake_id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r0"."filling_id" = "r1"."id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r1"."vendor_id" = "r2"."id""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "r0"."cake_id" = "cake"."id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r1"."id" = "r0"."filling_id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r2"."id" = "r1"."vendor_id""#,
]
.join(" ")
.as_str(),
Expand Down Expand Up @@ -1720,9 +1720,9 @@ mod tests {
[
r#"SELECT "cake"."id" AS "A_id", "cake"."name" AS "A_name","#,
r#""r2"."id" AS "B_id", "r2"."name" AS "B_name" FROM "cake""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "cake"."id" = "r0"."cake_id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r0"."filling_id" = "r1"."id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r1"."vendor_id" = "r2"."id""#,
r#"LEFT JOIN "cake_filling" AS "r0" ON "r0"."cake_id" = "cake"."id""#,
r#"LEFT JOIN "filling" AS "r1" ON "r1"."id" = "r0"."filling_id""#,
r#"LEFT JOIN "vendor" AS "r2" ON "r2"."id" = "r1"."vendor_id""#,
]
.join(" ")
.as_str(),
Expand Down
18 changes: 18 additions & 0 deletions src/query/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,24 @@ pub trait QueryFilter: Sized {
}
self
}

/// Perform a check to determine table belongs to a Model through a relation
fn find_by_relation<M>(mut self, rel: RelationDef, model: &M, tbl_alias: Option<String>) -> Self
where
M: ModelTrait,
{
let tbl_alias = tbl_alias.unwrap_or_else(|| unpack_table_ref(&rel.to_tbl).to_string());
for (from_col, to_col) in rel.from_col.into_iter().zip(rel.to_col.into_iter()) {
let column = from_col
.to_string()
.parse()
.ok()
.expect("RelationDef should refer to valid column name");
let expr = Expr::col((Alias::new(&tbl_alias), to_col)).eq(model.get(column));
self = self.filter(expr);
}
self
}
}

pub(crate) fn join_condition(mut rel: RelationDef) -> Condition {
Expand Down
Loading