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 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
34 changes: 33 additions & 1 deletion src/entity/identity.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{ColumnTrait, EntityTrait, IdenStatic};
use sea_query::{DynIden, IntoIden};
use sea_query::{Alias, DynIden, Iden, IntoIden, SeaRc};
use std::fmt;

#[derive(Debug, Clone)]
pub enum Identity {
Expand All @@ -8,6 +9,25 @@ pub enum Identity {
Ternary(DynIden, DynIden, DynIden),
}

impl Iden for Identity {
fn unquoted(&self, s: &mut dyn fmt::Write) {
match self {
Identity::Unary(iden) => {
write!(s, "{}", iden.to_string()).unwrap();
}
Identity::Binary(iden1, iden2) => {
write!(s, "{}", iden1.to_string()).unwrap();
write!(s, "{}", iden2.to_string()).unwrap();
}
Identity::Ternary(iden1, iden2, iden3) => {
write!(s, "{}", iden1.to_string()).unwrap();
write!(s, "{}", iden2.to_string()).unwrap();
write!(s, "{}", iden3.to_string()).unwrap();
}
}
}
}

pub trait IntoIdentity {
fn into_identity(self) -> Identity;
}
Expand All @@ -19,6 +39,18 @@ where
fn identity_of(self) -> Identity;
}

impl IntoIdentity for String {
fn into_identity(self) -> Identity {
self.as_str().into_identity()
}
}

impl IntoIdentity for &str {
fn into_identity(self) -> Identity {
Identity::Unary(SeaRc::new(Alias::new(self)))
}
}

impl<T> IntoIdentity for T
where
T: IdenStatic,
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
4 changes: 2 additions & 2 deletions src/entity/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ pub use crate::{
error::*, ActiveModelBehavior, ActiveModelTrait, ColumnDef, ColumnTrait, ColumnType,
DeriveActiveModel, DeriveActiveModelBehavior, DeriveColumn, DeriveCustomColumn, DeriveEntity,
DeriveModel, DerivePrimaryKey, EntityName, EntityTrait, EnumIter, ForeignKeyAction, Iden,
IdenStatic, ModelTrait, PrimaryKeyToColumn, PrimaryKeyTrait, QueryFilter, QueryResult, Related,
RelationDef, RelationTrait, Select, Value,
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 @@ -30,6 +30,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
9 changes: 6 additions & 3 deletions src/executor/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,9 +264,12 @@ impl TryGetable for Decimal {
.map_err(|e| TryGetError::DbErr(crate::sqlx_error_to_query_err(e)))?;
use rust_decimal::prelude::FromPrimitive;
match val {
Some(v) => Decimal::from_f64(v)
.ok_or_else(|| TryGetError::DbErr(DbErr::Query("Failed to convert f64 into Decimal".to_owned()))),
None => Err(TryGetError::Null)
Some(v) => Decimal::from_f64(v).ok_or_else(|| {
TryGetError::DbErr(DbErr::Query(
"Failed to convert f64 into Decimal".to_owned(),
))
}),
None => Err(TryGetError::Null),
}
}
#[cfg(feature = "mock")]
Expand Down
10 changes: 5 additions & 5 deletions src/executor/select.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
error::*, query::combine, DatabaseConnection, EntityTrait, FromQueryResult, Iterable,
JsonValue, ModelTrait, Paginator, PrimaryKeyToColumn, QueryResult, Select, SelectTwo,
error::*, DatabaseConnection, EntityTrait, FromQueryResult, IdenStatic, Iterable, JsonValue,
ModelTrait, Paginator, PrimaryKeyToColumn, QueryResult, Select, SelectA, SelectB, SelectTwo,
SelectTwoMany, Statement,
};
use sea_query::SelectStatement;
Expand Down Expand Up @@ -66,8 +66,8 @@ where

fn from_raw_query_result(res: QueryResult) -> Result<Self::Item, DbErr> {
Ok((
M::from_query_result(&res, combine::SELECT_A)?,
N::from_query_result_optional(&res, combine::SELECT_B)?,
M::from_query_result(&res, SelectA.as_str())?,
N::from_query_result_optional(&res, SelectB.as_str())?,
))
}
}
Expand Down 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
33 changes: 27 additions & 6 deletions src/query/combine.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,31 @@
use crate::{EntityTrait, IntoSimpleExpr, Iterable, QueryTrait, Select, SelectTwo, SelectTwoMany};
use crate::{
EntityTrait, IdenStatic, IntoSimpleExpr, Iterable, QueryTrait, Select, SelectTwo, SelectTwoMany,
};
use core::marker::PhantomData;
pub use sea_query::JoinType;
use sea_query::{Alias, ColumnRef, Iden, Order, SeaRc, SelectExpr, SelectStatement, SimpleExpr};

pub const SELECT_A: &str = "A_";
pub const SELECT_B: &str = "B_";
macro_rules! select_def {
( $ident: ident, $str: expr ) => {
#[derive(Debug, Clone, Copy)]
pub struct $ident;

impl Iden for $ident {
fn unquoted(&self, s: &mut dyn std::fmt::Write) {
write!(s, "{}", self.as_str()).unwrap();
}
}

impl IdenStatic for $ident {
fn as_str(&self) -> &str {
$str
}
}
};
}

select_def!(SelectA, "A_");
select_def!(SelectB, "B_");

impl<E> Select<E>
where
Expand Down Expand Up @@ -37,15 +58,15 @@ where
where
F: EntityTrait,
{
self = self.apply_alias(SELECT_A);
self = self.apply_alias(SelectA.as_str());
SelectTwo::new(self.into_query())
}

pub fn select_with<F>(mut self, _: F) -> SelectTwoMany<E, F>
where
F: EntityTrait,
{
self = self.apply_alias(SELECT_A);
self = self.apply_alias(SelectA.as_str());
SelectTwoMany::new(self.into_query())
}
}
Expand Down Expand Up @@ -102,7 +123,7 @@ where
S: QueryTrait<QueryStatement = SelectStatement>,
{
for col in <F::Column as Iterable>::iter() {
let alias = format!("{}{}", SELECT_B, col.to_string().as_str());
let alias = format!("{}{}", SelectB.as_str(), col.as_str());
selector.query().expr(SelectExpr {
expr: col.into_simple_expr(),
alias: Some(SeaRc::new(Alias::new(&alias))),
Expand Down
13 changes: 6 additions & 7 deletions src/query/helper.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use crate::{
ColumnTrait, EntityTrait, Identity, IntoSimpleExpr, Iterable, ModelTrait, PrimaryKeyToColumn,
RelationDef,
};
use sea_query::{
Alias, Expr, IntoCondition, SeaRc, SelectExpr, SelectStatement, SimpleExpr, TableRef,
ColumnTrait, EntityTrait, Identity, IntoIdentity, IntoSimpleExpr, Iterable, ModelTrait,
PrimaryKeyToColumn, RelationDef,
};
pub use sea_query::{Condition, ConditionalStatement, DynIden, JoinType, Order, OrderedStatement};
use sea_query::{Expr, IntoCondition, SeaRc, SelectExpr, SelectStatement, SimpleExpr, TableRef};

// LINT: when the column does not appear in tables selected from
// LINT: when there is a group by clause, but some columns don't have aggregate functions
Expand Down Expand Up @@ -55,13 +53,14 @@ pub trait QuerySelect: Sized {
/// r#"SELECT COUNT("cake"."id") AS "count" FROM "cake""#
/// );
/// ```
fn column_as<C>(mut self, col: C, alias: &str) -> Self
fn column_as<C, I>(mut self, col: C, alias: I) -> Self
where
C: IntoSimpleExpr,
I: IntoIdentity,
{
self.query().expr(SelectExpr {
expr: col.into_simple_expr(),
alias: Some(SeaRc::new(Alias::new(alias))),
alias: Some(SeaRc::new(alias.into_identity())),
});
self
}
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(" ")
);
}
}
2 changes: 1 addition & 1 deletion src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod select;
mod traits;
mod update;

// pub use combine::*;
pub use combine::{SelectA, SelectB};
pub use delete::*;
pub use helper::*;
pub use insert::*;
Expand Down
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 @@ -83,4 +83,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