Skip to main content

sql_builder/query/with/
query.rs

1use super::*;
2use crate::{RenderError, functions, query_statement_writer};
3
4/// A WITH clause can contain one or multiple common table expressions ([CommonTableExpression]).
5///
6/// You can use this to generate [WithQuery] by calling [WithClause::query].
7///
8/// These named queries can act as a "query local table" that are materialized during execution and
9/// then can be used by the query prefixed with the WITH clause.
10///
11/// A WITH clause can contain multiple of these [CommonTableExpression]. (Except in the case of
12/// recursive WITH query which can only contain one [CommonTableExpression]).
13///
14/// A [CommonTableExpression] is a name, column names and a query returning data for those columns.
15///
16/// Some databases (like sqlite) restrict the acceptable kinds of queries inside of the WITH clause
17/// common table expressions. These databases only allow [SelectStatement]s to form a common table
18/// expression.
19///
20/// Other databases like postgres allow modification queries (UPDATE, DELETE) inside of the WITH
21/// clause but they have to return a table. (They must have a RETURNING clause).
22///
23/// tideorm-sql-builder doesn't check this or restrict the kind of [CommonTableExpression] that you can create
24/// in rust. This means that you can put an UPDATE or DELETE queries into WITH clause and tideorm-sql-builder
25/// will succeed in generating that kind of sql query but the execution inside the database will
26/// fail because they are invalid.
27///
28/// It is your responsibility to ensure that the kind of WITH clause that you put together makes
29/// sense and valid for that database that you are using.
30///
31/// NOTE that for recursive WITH queries (in sql: "WITH RECURSIVE") you can only have a
32/// single [CommonTableExpression] inside of the WITH clause. That query must match certain
33/// requirements:
34///   * It is a query of UNION or UNION ALL of two queries.
35///   * The first part of the query (the left side of the UNION) must be executable first in itself.
36///     It must be non-recursive. (Cannot contain self reference)
37///   * The self reference must appear in the right hand side of the UNION.
38///   * The query can only have a single self-reference.
39///   * Recursive data-modifying statements are not supported, but you can use the results of a
40///     recursive SELECT query in a data-modifying statement. (like so: WITH RECURSIVE
41///     cte_name(a,b,c,d) AS (SELECT ... UNION SELECT ... FROM ... JOIN cte_name ON ... WHERE ...)
42///     DELETE FROM table WHERE table.a = cte_name.a)
43///
44/// It is mandatory to set the [Self::cte]. With queries must have at least one CTE.
45/// Recursive with query generation will panic if you specify more than one CTE.
46///
47/// # Examples
48///
49/// ```
50/// use sql_builder::{*, IntoCondition, IntoIden};
51///
52/// let base_query = SelectStatement::new()
53///                     .column("id")
54///                     .expr(1i32)
55///                     .column("next")
56///                     .column("value")
57///                     .from("table")
58///                     .to_owned();
59///
60/// let cte_referencing = SelectStatement::new()
61///                             .column("id")
62///                             .expr(Expr::col("depth").add(1i32))
63///                             .column("next")
64///                             .column("value")
65///                             .from("table")
66///                             .join(
67///                                 JoinType::InnerJoin,
68///                                 "cte_traversal",
69///                                 Expr::col(("cte_traversal", "next")).equals(("table", "id"))
70///                             )
71///                             .to_owned();
72///
73/// let common_table_expression = CommonTableExpression::new()
74///             .query(
75///                 base_query.clone().union(UnionType::All, cte_referencing).to_owned()
76///             )
77///             .column("id")
78///             .column("depth")
79///             .column("next")
80///             .column("value")
81///             .table_name("cte_traversal")
82///             .to_owned();
83///
84/// let select = SelectStatement::new()
85///         .column(Asterisk)
86///         .from("cte_traversal")
87///         .to_owned();
88///
89/// let with_clause = WithClause::new()
90///         .recursive(true)
91///         .cte(common_table_expression)
92///         .to_owned();
93///
94/// let query = select.with(with_clause).to_owned();
95///
96/// assert_eq!(
97///     query.to_string(MysqlQueryBuilder).unwrap(),
98///     r#"WITH RECURSIVE `cte_traversal` (`id`, `depth`, `next`, `value`) AS (SELECT `id`, 1, `next`, `value` FROM `table` UNION ALL (SELECT `id`, `depth` + 1, `next`, `value` FROM `table` INNER JOIN `cte_traversal` ON `cte_traversal`.`next` = `table`.`id`)) SELECT * FROM `cte_traversal`"#
99/// );
100/// assert_eq!(
101///     query.to_string(PostgresQueryBuilder).unwrap(),
102///     r#"WITH RECURSIVE "cte_traversal" ("id", "depth", "next", "value") AS (SELECT "id", 1, "next", "value" FROM "table" UNION ALL (SELECT "id", "depth" + 1, "next", "value" FROM "table" INNER JOIN "cte_traversal" ON "cte_traversal"."next" = "table"."id")) SELECT * FROM "cte_traversal""#
103/// );
104/// assert_eq!(
105///     query.to_string(SqliteQueryBuilder).unwrap(),
106///     r#"WITH RECURSIVE "cte_traversal" ("id", "depth", "next", "value") AS (SELECT "id", 1, "next", "value" FROM "table" UNION ALL SELECT "id", "depth" + 1, "next", "value" FROM "table" INNER JOIN "cte_traversal" ON "cte_traversal"."next" = "table"."id") SELECT * FROM "cte_traversal""#
107/// );
108/// ```
109#[derive(Debug, Clone, Default, PartialEq)]
110pub struct WithClause {
111    pub(crate) recursive: bool,
112    pub(crate) cte_expressions: Vec<CommonTableExpression>,
113}
114
115impl WithClause {
116    /// Constructs a new [WithClause].
117    pub fn new() -> Self {
118        Self::default()
119    }
120
121    /// Sets whether this clause is a recursive with clause of not.
122    /// If set to true it will generate a 'WITH RECURSIVE' query.
123    ///
124    /// You can only specify a single [CommonTableExpression] containing a union query
125    /// if this is set to true.
126    pub fn recursive(&mut self, recursive: bool) -> &mut Self {
127        self.recursive = recursive;
128        self
129    }
130
131    /// Add a [CommonTableExpression] to this with clause.
132    pub fn cte(&mut self, cte: CommonTableExpression) -> &mut Self {
133        self.cte_expressions.push(cte);
134        self
135    }
136
137    /// You can turn this into a [WithQuery] using this function. The resulting WITH query will
138    /// execute the argument query with this WITH clause.
139    pub fn query<T>(self, query: T) -> WithQuery
140    where
141        T: Into<SubQueryStatement>,
142    {
143        WithQuery::new().with_clause(self).query(query).to_owned()
144    }
145}
146
147impl From<CommonTableExpression> for WithClause {
148    fn from(cte: CommonTableExpression) -> WithClause {
149        WithClause::new().cte(cte).to_owned()
150    }
151}
152
153/// A WITH query. A simple SQL query that has a WITH clause ([WithClause]).
154///
155/// The [WithClause] can contain one or multiple common table expressions ([CommonTableExpression]).
156///
157/// These named queries can act as a "query local table" that are materialized during execution and
158/// then can be used by the query prefixed with the WITH clause.
159///
160/// A WITH clause can contain multiple of these [CommonTableExpression]. (Except in the case of
161/// recursive WITH query which can only contain one [CommonTableExpression]).
162///
163/// A [CommonTableExpression] is a name, column names and a query returning data for those columns.
164///
165/// Some databases (like sqlite) restrict the acceptable kinds of queries inside of the WITH clause
166/// common table expressions. These databases only allow [SelectStatement]s to form a common table
167/// expression.
168///
169/// Other databases like postgres allow modification queries (UPDATE, DELETE) inside of the WITH
170/// clause but they have to return a table. (They must have a RETURNING clause).
171///
172/// tideorm-sql-builder doesn't check this or restrict the kind of [CommonTableExpression] that you can create
173/// in rust. This means that you can put an UPDATE or DELETE queries into WITH clause and tideorm-sql-builder
174/// will succeed in generating that kind of sql query but the execution inside the database will
175/// fail because they are invalid.
176///
177/// It is your responsibility to ensure that the kind of WITH clause that you put together makes
178/// sense and valid for that database that you are using.
179///
180/// NOTE that for recursive WITH queries (in sql: "WITH RECURSIVE") you can only have a
181/// single [CommonTableExpression] inside of the WITH clause. That query must match certain
182/// requirements:
183///   * It is a query of UNION or UNION ALL of two queries.
184///   * The first part of the query (the left side of the UNION) must be executable first in itself.
185///     It must be non-recursive. (Cannot contain self reference)
186///   * The self reference must appear in the right hand side of the UNION.
187///   * The query can only have a single self-reference.
188///   * Recursive data-modifying statements are not supported, but you can use the results of a
189///     recursive SELECT query in a data-modifying statement. (like so: WITH RECURSIVE
190///     cte_name(a,b,c,d) AS (SELECT ... UNION SELECT ... FROM ... JOIN cte_name ON ... WHERE ...)
191///     DELETE FROM table WHERE table.a = cte_name.a)
192///
193/// It is mandatory to set the [Self::cte] and the [Self::query].
194#[derive(Debug, Clone, Default, PartialEq)]
195pub struct WithQuery {
196    pub(crate) with_clause: WithClause,
197    pub(crate) query: Option<Box<SubQueryStatement>>,
198}
199
200impl WithQuery {
201    /// Constructs a new empty [WithQuery].
202    pub fn new() -> Self {
203        Self::default()
204    }
205
206    /// Set the whole [WithClause].
207    pub fn with_clause(&mut self, with_clause: WithClause) -> &mut Self {
208        self.with_clause = with_clause;
209        self
210    }
211
212    /// Set the [WithClause::recursive]. See that method for more information.
213    pub fn recursive(&mut self, recursive: bool) -> &mut Self {
214        self.with_clause.recursive = recursive;
215        self
216    }
217
218    /// Add a [CommonTableExpression] to the with clause. See [WithClause::cte].
219    pub fn cte(&mut self, cte: CommonTableExpression) -> &mut Self {
220        self.with_clause.cte_expressions.push(cte);
221        self
222    }
223
224    /// Set the query that you execute with the [WithClause].
225    pub fn query<T>(&mut self, query: T) -> &mut Self
226    where
227        T: Into<SubQueryStatement>,
228    {
229        self.query = Some(Box::new(query.into()));
230        self
231    }
232}
233
234impl QueryStatementBuilder for WithQuery {
235    fn build_collect_any_into(
236        &self,
237        query_builder: &impl QueryBuilder,
238        sql: &mut impl SqlWriter,
239    ) -> Result<(), RenderError> {
240        functions::prepare_with_query(query_builder, self, sql)
241    }
242}
243
244impl From<WithQuery> for SubQueryStatement {
245    fn from(s: WithQuery) -> Self {
246        Self::WithStatement(s)
247    }
248}
249
250query_statement_writer!(WithQuery);