Skip to content
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
18 changes: 17 additions & 1 deletion src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1032,7 +1032,7 @@ pub trait QueryBuilder:
fn prepare_join_on(&self, join_on: &JoinOn, sql: &mut impl SqlWriter) {
match join_on {
JoinOn::Condition(c) => self.prepare_condition(c, "ON", sql),
JoinOn::Columns(_c) => unimplemented!(),
JoinOn::Columns(c) => self.prepare_using(c, sql),
}
}

Expand Down Expand Up @@ -1661,6 +1661,22 @@ pub trait QueryBuilder:
}
}

fn prepare_using(&self, using: &[Expr], sql: &mut impl SqlWriter) {
sql.write_str(" USING (").unwrap();
let mut using_iter = using.iter();
join_io!(
using_iter,
expr,
join {
sql.write_str(", ").unwrap();
},
do {
self.prepare_expr(expr, sql);
}
);
sql.write_str(")").unwrap();
}

#[doc(hidden)]
/// Translate part of a condition to part of a "WHERE" clause.
fn prepare_condition_where(&self, condition: &Condition, sql: &mut impl SqlWriter) {
Expand Down
41 changes: 41 additions & 0 deletions src/query/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1925,6 +1925,47 @@ impl SelectStatement {
)
}

/// Join with a "USING" clause.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::select()
/// .column(Char::Character)
/// .from(Char::Table)
/// .join_using(
/// JoinType::LeftJoin,
/// Font::Table,
/// [Char::FontId],
/// )
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"SELECT `character` FROM `character` LEFT JOIN `font` USING (`font_id`)"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"SELECT "character" FROM "character" LEFT JOIN "font" USING ("font_id")"#
/// );
/// ```
pub fn join_using<R, T, I>(&mut self, join: JoinType, tbl_ref: R, columns: I) -> &mut Self
where
R: IntoTableRef,
T: IntoColumnRef,
I: IntoIterator<Item = T>,
Comment on lines +1954 to +1958

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub fn join_using<R, T, I>(&mut self, join: JoinType, tbl_ref: R, columns: I) -> &mut Self
where
R: IntoTableRef,
T: IntoColumnRef,
I: IntoIterator<Item = T>,
pub fn join_using(&mut self, join: JoinType, tbl_ref: impl IntoTableRef, columns: impl IntoIterator<Item = impl IntoColumnRef>) -> &mut Self

Does this work on sea-query's MSRV?

{
let columns = columns
.into_iter()
.map(IntoColumnRef::into_column_ref)
.map(Expr::from)
.collect();

self.push_join(join, tbl_ref.into(), JoinOn::Columns(columns), false)
}

fn push_join(
&mut self,
join: JoinType,
Expand Down
Loading