93 lines
2.6 KiB
Rust
93 lines
2.6 KiB
Rust
use ext_calckey_model_migration::{Alias, Expr, IntoIden, SelectExpr, SelectStatement, TableRef};
|
|
use sea_orm::{ColumnTrait, Condition, EntityTrait, Iden, Iterable, JoinType, RelationDef};
|
|
|
|
pub(crate) trait SelectColumnsExt {
|
|
fn add_aliased_columns<T: EntityTrait>(&mut self, alias: &str) -> &mut Self;
|
|
|
|
fn join_columns<I: IntoIden>(
|
|
&mut self,
|
|
join: JoinType,
|
|
rel: RelationDef,
|
|
alias: I,
|
|
) -> &mut Self;
|
|
}
|
|
|
|
pub(crate) fn join_columns_default(rel: RelationDef) -> Condition {
|
|
let tbl_id = |tbl: &TableRef| {
|
|
match tbl {
|
|
TableRef::Table(id) => id,
|
|
TableRef::TableAlias(_, id) => id,
|
|
_ => unreachable!(),
|
|
}
|
|
.clone()
|
|
};
|
|
|
|
let mut cond = Condition::all();
|
|
for (owner_key, foreign_key) in rel.from_col.into_iter().zip(rel.to_col.into_iter()) {
|
|
cond = cond.add(
|
|
Expr::col((tbl_id(&rel.from_tbl), owner_key))
|
|
.equals((tbl_id(&rel.to_tbl), foreign_key)),
|
|
);
|
|
}
|
|
cond
|
|
}
|
|
|
|
impl SelectColumnsExt for SelectStatement {
|
|
fn add_aliased_columns<T: EntityTrait>(&mut self, iden: &str) -> &mut Self {
|
|
for col in T::Column::iter() {
|
|
let column: &T::Column = &col;
|
|
|
|
let alias = format!("{}{}", iden, col.to_string());
|
|
|
|
let column_ref = Expr::col((Alias::new(iden), column.as_column_ref().1));
|
|
|
|
self.expr(SelectExpr {
|
|
expr: col.select_as(column_ref),
|
|
alias: Some(Alias::new(&alias).into_iden()),
|
|
window: None,
|
|
});
|
|
}
|
|
|
|
self
|
|
}
|
|
|
|
fn join_columns<I: IntoIden>(
|
|
&mut self,
|
|
join: JoinType,
|
|
mut rel: RelationDef,
|
|
alias: I,
|
|
) -> &mut Self {
|
|
let alias = alias.into_iden();
|
|
rel.to_tbl = rel.to_tbl.alias(alias);
|
|
self.join(join, rel.to_tbl.clone(), join_columns_default(rel));
|
|
self
|
|
}
|
|
}
|
|
|
|
pub(crate) fn joined_prefix_str(prefix: &str, suffix: &str) -> String {
|
|
format!("{prefix}{suffix}")
|
|
}
|
|
|
|
pub(crate) fn joined_prefix_alias(prefix: &str, suffix: &str) -> Alias {
|
|
Alias::new(joined_prefix_str(prefix, suffix))
|
|
}
|
|
|
|
pub(crate) fn joined_prefix(prefix: &str, suffix: &str) -> impl IntoIden {
|
|
joined_prefix_alias(prefix, suffix).into_iden()
|
|
}
|
|
|
|
pub(crate) trait EntityPrefixExt {
|
|
fn base_prefix_str(&self) -> String;
|
|
fn base_prefix(&self) -> impl IntoIden;
|
|
}
|
|
|
|
impl<T: EntityTrait> EntityPrefixExt for T {
|
|
fn base_prefix_str(&self) -> String {
|
|
format!("{}.", self.table_name())
|
|
}
|
|
|
|
fn base_prefix(&self) -> impl IntoIden {
|
|
Alias::new(self.base_prefix_str()).into_iden()
|
|
}
|
|
}
|