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

Union proposal #128

Merged
merged 2 commits into from
Sep 10, 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
10 changes: 10 additions & 0 deletions src/backend/query_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@ pub trait QueryBuilder: QuotedBuilder {

self.prepare_condition(&select.having, "HAVING", sql, collector);

if !select.unions.is_empty() {
select.unions.iter().for_each(|(union_type, query)| {
match union_type {
UnionType::Distinct => write!(sql, " UNION ").unwrap(),
UnionType::All => write!(sql, " UNION ALL ").unwrap(),
}
self.prepare_select_statement(query, sql, collector);
});
}

if !select.orders.is_empty() {
write!(sql, " ORDER BY ").unwrap();
select.orders.iter().fold(true, |first, expr| {
Expand Down
90 changes: 90 additions & 0 deletions src/query/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ pub struct SelectStatement {
pub(crate) wherei: ConditionHolder,
pub(crate) groups: Vec<SimpleExpr>,
pub(crate) having: ConditionHolder,
pub(crate) unions: Vec<(UnionType, SelectStatement)>,
pub(crate) orders: Vec<OrderExpr>,
pub(crate) limit: Option<Value>,
pub(crate) offset: Option<Value>,
Expand Down Expand Up @@ -82,6 +83,13 @@ pub enum LockType {
Exclusive,
}

/// List of lock types that can be used in select statement
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnionType {
Distinct,
All,
}

#[allow(clippy::from_over_into)]
impl Into<SelectExpr> for SimpleExpr {
fn into(self) -> SelectExpr {
Expand Down Expand Up @@ -109,6 +117,7 @@ impl SelectStatement {
wherei: ConditionHolder::new(),
groups: Vec::new(),
having: ConditionHolder::new(),
unions: Vec::new(),
orders: Vec::new(),
limit: None,
offset: None,
Expand All @@ -126,6 +135,7 @@ impl SelectStatement {
wherei: std::mem::replace(&mut self.wherei, ConditionHolder::new()),
groups: std::mem::take(&mut self.groups),
having: std::mem::replace(&mut self.having, ConditionHolder::new()),
unions: std::mem::take(&mut self.unions),
orders: std::mem::take(&mut self.orders),
limit: self.limit.take(),
offset: self.offset.take(),
Expand Down Expand Up @@ -1458,6 +1468,86 @@ impl SelectStatement {
self.lock = Some(LockType::Exclusive);
self
}

/// Union with another SelectStatement that must have the same selected fields.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::select()
/// .column(Char::Character)
/// .from(Char::Table)
/// .and_where(Expr::col(Char::FontId).eq(5))
/// .union(UnionType::All, Query::select()
/// .column(Char::Character)
/// .from(Char::Table)
/// .and_where(Expr::col(Char::FontId).eq(4))
/// .to_owned()
/// )
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"SELECT `character` FROM `character` WHERE `font_id` = 5 UNION ALL SELECT `character` FROM `character` WHERE `font_id` = 4"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"SELECT "character" FROM "character" WHERE "font_id" = 5 UNION ALL SELECT "character" FROM "character" WHERE "font_id" = 4"#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"SELECT `character` FROM `character` WHERE `font_id` = 5 UNION ALL SELECT `character` FROM `character` WHERE `font_id` = 4"#
/// );
/// ```
pub fn union(&mut self, union_type: UnionType, query: SelectStatement) -> &mut Self {
self.unions.push((union_type, query));
self
}

/// Union with multiple SelectStatement that must have the same selected fields.
///
/// # Examples
///
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let query = Query::select()
/// .column(Char::Character)
/// .from(Char::Table)
/// .and_where(Expr::col(Char::FontId).eq(5))
/// .unions(vec![
/// (UnionType::All, Query::select()
/// .column(Char::Character)
/// .from(Char::Table)
/// .and_where(Expr::col(Char::FontId).eq(4))
/// .to_owned()),
/// (UnionType::All, Query::select()
/// .column(Char::Character)
/// .from(Char::Table)
/// .and_where(Expr::col(Char::FontId).eq(3))
/// .to_owned()),
/// ])
/// .to_owned();
///
/// assert_eq!(
/// query.to_string(MysqlQueryBuilder),
/// r#"SELECT `character` FROM `character` WHERE `font_id` = 5 UNION ALL SELECT `character` FROM `character` WHERE `font_id` = 4 UNION ALL SELECT `character` FROM `character` WHERE `font_id` = 3"#
/// );
/// assert_eq!(
/// query.to_string(PostgresQueryBuilder),
/// r#"SELECT "character" FROM "character" WHERE "font_id" = 5 UNION ALL SELECT "character" FROM "character" WHERE "font_id" = 4 UNION ALL SELECT "character" FROM "character" WHERE "font_id" = 3"#
/// );
/// assert_eq!(
/// query.to_string(SqliteQueryBuilder),
/// r#"SELECT `character` FROM `character` WHERE `font_id` = 5 UNION ALL SELECT `character` FROM `character` WHERE `font_id` = 4 UNION ALL SELECT `character` FROM `character` WHERE `font_id` = 3"#
/// );
/// ```
pub fn unions<T: IntoIterator<Item=(UnionType, SelectStatement)>>(&mut self, unions: T) -> &mut Self {
self.unions.extend(unions);
self
}
}

impl QueryStatementBuilder for SelectStatement {
Expand Down