//! Combine queries using a combinator like `UNION`, `INTERSECT` or `EXPECT` //! with or without `ALL` rule for duplicates //! //! Within this module, types commonly use the following abbreviations: //! //! O: Order By Clause //! L: Limit Clause //! Of: Offset Clause //! LOf: Limit Offset Clause use crate::backend::{Backend, DieselReserveSpecialization}; use crate::dsl::AsExprOf; use crate::expression::subselect::ValidSubselect; use crate::expression::IntoSql; use crate::expression::NonAggregate; use crate::query_builder::insert_statement::InsertFromSelect; use crate::query_builder::limit_clause::{LimitClause, NoLimitClause}; use crate::query_builder::limit_offset_clause::LimitOffsetClause; use crate::query_builder::offset_clause::{NoOffsetClause, OffsetClause}; use crate::query_builder::order_clause::{NoOrderClause, OrderClause}; use crate::query_builder::{AsQuery, AstPass, Query, QueryFragment, QueryId, SelectQuery}; use crate::query_dsl::methods::*; use crate::query_dsl::positional_order_dsl::{IntoPositionalOrderExpr, PositionalOrderDsl}; use crate::sql_types::BigInt; use crate::{CombineDsl, Insertable, QueryDsl, QueryResult, RunQueryDsl, Table}; #[derive(Debug, Copy, Clone, QueryId)] #[must_use = "Queries are only executed when calling `load`, `get_result` or similar."] /// Combine queries using a combinator like `UNION`, `INTERSECT` or `EXPECT` /// with or without `ALL` rule for duplicates pub struct CombinationClause< Combinator, Rule, Source, Rhs, Order = NoOrderClause, LimitOffset = LimitOffsetClause, > { combinator: Combinator, duplicate_rule: Rule, source: ParenthesisWrapper, rhs: ParenthesisWrapper, /// The order clause of the query order: Order, /// The combined limit/offset clause of the query limit_offset: LimitOffset, } impl CombinationClause { /// Create a new combination pub(crate) fn new( combinator: Combinator, duplicate_rule: Rule, source: Source, rhs: Rhs, ) -> Self { CombinationClause { combinator, duplicate_rule, source: ParenthesisWrapper { inner: source }, rhs: ParenthesisWrapper { inner: rhs }, order: NoOrderClause, limit_offset: LimitOffsetClause { limit_clause: NoLimitClause, offset_clause: NoOffsetClause, }, } } } impl QueryDsl for CombinationClause { } impl Query for CombinationClause where Source: Query, Rhs: Query, { type SqlType = Source::SqlType; } impl SelectQuery for CombinationClause where Source: SelectQuery, Rhs: SelectQuery, { type SqlType = Source::SqlType; } impl ValidSubselect for CombinationClause where Source: ValidSubselect, Rhs: ValidSubselect, { } impl RunQueryDsl for CombinationClause { } impl Insertable for CombinationClause where T: Table, T::AllColumns: NonAggregate, Self: Query, { type Values = InsertFromSelect; fn values(self) -> Self::Values { InsertFromSelect::new(self) } } impl CombineDsl for CombinationClause where Self: Query, { type Query = Self; fn union(self, rhs: Rhs) -> crate::dsl::Union where Rhs: AsQuery::SqlType>, { CombinationClause::new(Union, Distinct, self, rhs.as_query()) } fn union_all(self, rhs: Rhs) -> crate::dsl::UnionAll where Rhs: AsQuery::SqlType>, { CombinationClause::new(Union, All, self, rhs.as_query()) } fn intersect(self, rhs: Rhs) -> crate::dsl::Intersect where Rhs: AsQuery::SqlType>, { CombinationClause::new(Intersect, Distinct, self, rhs.as_query()) } fn intersect_all(self, rhs: Rhs) -> crate::dsl::IntersectAll where Rhs: AsQuery::SqlType>, { CombinationClause::new(Intersect, All, self, rhs.as_query()) } fn except(self, rhs: Rhs) -> crate::dsl::Except where Rhs: AsQuery::SqlType>, { CombinationClause::new(Except, Distinct, self, rhs.as_query()) } fn except_all(self, rhs: Rhs) -> crate::dsl::ExceptAll where Rhs: AsQuery::SqlType>, { CombinationClause::new(Except, All, self, rhs.as_query()) } } impl QueryFragment for CombinationClause where Combinator: QueryFragment, Rule: QueryFragment, ParenthesisWrapper: QueryFragment, ParenthesisWrapper: QueryFragment, O: QueryFragment, LOf: QueryFragment, DB: Backend + SupportsCombinationClause + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { self.source.walk_ast(out.reborrow())?; self.combinator.walk_ast(out.reborrow())?; self.duplicate_rule.walk_ast(out.reborrow())?; self.rhs.walk_ast(out.reborrow())?; self.order.walk_ast(out.reborrow())?; self.limit_offset.walk_ast(out) } } impl PositionalOrderDsl for CombinationClause where Self: SelectQuery, CombinationClause, LOf>: SelectQuery, RawExpr: IntoPositionalOrderExpr, { type Output = CombinationClause, LOf>; fn positional_order_by(self, expr: RawExpr) -> Self::Output { let order = OrderClause(expr.into_positional_expr()); CombinationClause { combinator: self.combinator, duplicate_rule: self.duplicate_rule, source: self.source, rhs: self.rhs, order, limit_offset: self.limit_offset, } } } #[doc(hidden)] type Limit = AsExprOf; impl LimitDsl for CombinationClause> where Self: SelectQuery, CombinationClause, Of>>: SelectQuery, { type Output = CombinationClause< Combinator, Rule, Source, Rhs, O, LimitOffsetClause, Of>, >; fn limit(self, limit: i64) -> Self::Output { let limit_clause = LimitClause(limit.into_sql::()); CombinationClause { combinator: self.combinator, duplicate_rule: self.duplicate_rule, source: self.source, rhs: self.rhs, order: self.order, limit_offset: LimitOffsetClause { limit_clause, offset_clause: self.limit_offset.offset_clause, }, } } } #[doc(hidden)] type Offset = Limit; impl OffsetDsl for CombinationClause> where Self: SelectQuery, CombinationClause>>: SelectQuery, { type Output = CombinationClause< Combinator, Rule, Source, Rhs, O, LimitOffsetClause>, >; fn offset(self, offset: i64) -> Self::Output { let offset_clause = OffsetClause(offset.into_sql::()); CombinationClause { combinator: self.combinator, duplicate_rule: self.duplicate_rule, source: self.source, rhs: self.rhs, order: self.order, limit_offset: LimitOffsetClause { limit_clause: self.limit_offset.limit_clause, offset_clause, }, } } } #[derive(Debug, Copy, Clone, QueryId)] /// Computes the set union of the rows returned by the involved `SELECT` statements using SQL `UNION` pub struct Union; impl QueryFragment for Union where DB: Backend + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { out.push_sql(" UNION "); Ok(()) } } #[derive(Debug, Copy, Clone, QueryId)] /// Computes the set intersection of the rows returned by the involved `SELECT` statements using SQL `INTERSECT` pub struct Intersect; impl QueryFragment for Intersect where DB: Backend + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { out.push_sql(" INTERSECT "); Ok(()) } } #[derive(Debug, Copy, Clone, QueryId)] /// Computes the set difference of the rows returned by the involved `SELECT` statements using SQL `EXCEPT` pub struct Except; impl QueryFragment for Except where DB: Backend + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { out.push_sql(" EXCEPT "); Ok(()) } } #[derive(Debug, Copy, Clone, QueryId)] /// Remove duplicate rows in the result, this is the default behavior of `UNION`, `INTERSECT` and `EXCEPT` pub struct Distinct; impl QueryFragment for Distinct where DB: Backend + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, _: AstPass<'_, 'b, DB>) -> QueryResult<()> { Ok(()) } } #[derive(Debug, Copy, Clone, QueryId)] /// Keep duplicate rows in the result pub struct All; impl QueryFragment for All where DB: Backend + DieselReserveSpecialization, { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> { out.push_sql("ALL "); Ok(()) } } /// Marker trait used to indicate whenever a backend supports given combination pub trait SupportsCombinationClause {} #[derive(Debug, Copy, Clone, QueryId)] /// Wrapper used to wrap rhs sql in parenthesis when supported by backend #[diesel_derives::__diesel_public_if( feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes", public_fields(inner) )] pub struct ParenthesisWrapper { /// the inner parenthesis definition #[allow(dead_code)] inner: T, } #[cfg(feature = "postgres_backend")] mod postgres { use super::*; use crate::pg::Pg; impl> QueryFragment for ParenthesisWrapper { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Pg>) -> QueryResult<()> { out.push_sql("("); self.inner.walk_ast(out.reborrow())?; out.push_sql(")"); Ok(()) } } impl SupportsCombinationClause for Pg {} impl SupportsCombinationClause for Pg {} impl SupportsCombinationClause for Pg {} impl SupportsCombinationClause for Pg {} impl SupportsCombinationClause for Pg {} impl SupportsCombinationClause for Pg {} } #[cfg(feature = "mysql_backend")] mod mysql { use super::*; use crate::mysql::Mysql; impl> QueryFragment for ParenthesisWrapper { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Mysql>) -> QueryResult<()> { out.push_sql("("); self.inner.walk_ast(out.reborrow())?; out.push_sql(")"); Ok(()) } } impl SupportsCombinationClause for Mysql {} impl SupportsCombinationClause for Mysql {} } #[cfg(feature = "sqlite")] mod sqlite { use super::*; use crate::sqlite::Sqlite; impl> QueryFragment for ParenthesisWrapper { fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Sqlite>) -> QueryResult<()> { // SQLite does not support parenthesis around this clause // we can emulate this by construct a fake outer // SELECT * FROM (inner_query) statement out.push_sql("SELECT * FROM ("); self.inner.walk_ast(out.reborrow())?; out.push_sql(")"); Ok(()) } } impl SupportsCombinationClause for Sqlite {} impl SupportsCombinationClause for Sqlite {} impl SupportsCombinationClause for Sqlite {} impl SupportsCombinationClause for Sqlite {} }