sql_builder/query/with.rs
1mod query;
2
3pub use query::*;
4
5use crate::{
6 ColumnRef, DynIden, Expr, IdenList, IntoIden, QueryBuilder, QueryStatementBuilder, SelectExpr,
7 SelectStatement, SqlWriter, SubQueryStatement, TableName, TableRef, Values,
8};
9
10#[derive(Debug, Clone, PartialEq)]
11pub(crate) enum CteQuery {
12 SubQuery(Box<SubQueryStatement>),
13 Values(Vec<Values>),
14}
15
16impl Default for CteQuery {
17 fn default() -> Self {
18 Self::Values(vec![])
19 }
20}
21
22/// A table definition inside a WITH clause ([WithClause]).
23///
24/// A WITH clause can contain one or multiple common table expressions ([CommonTableExpression]).
25///
26/// These named queries can act as a "query local table" that are materialized during execution and
27/// then can be used by the query prefixed with the WITH clause.
28///
29/// A WITH clause can contain multiple of these [CommonTableExpression]. (Except in the case of
30/// recursive WITH query which can only contain one [CommonTableExpression]).
31///
32/// A [CommonTableExpression] is a name, column names and a query returning data for those columns.
33///
34/// Some databases (like sqlite) restrict the acceptable kinds of queries inside of the WITH clause
35/// common table expressions. These databases only allow [SelectStatement]s to form a common table
36/// expression.
37///
38/// Other databases like postgres allow modification queries (UPDATE, DELETE) inside of the WITH
39/// clause but they have to return a table. (They must have a RETURNING clause).
40///
41/// tideorm-sql-builder doesn't check this or restrict the kind of [CommonTableExpression] that you can create
42/// in rust. This means that you can put an UPDATE or DELETE queries into WITH clause and tideorm-sql-builder
43/// will succeed in generating that kind of sql query but the execution inside the database will
44/// fail because they are invalid.
45///
46/// It is your responsibility to ensure that the kind of WITH clause that you put together makes
47/// sense and valid for that database that you are using.
48///
49/// NOTE that for recursive WITH queries (in sql: "WITH RECURSIVE") you can only have a
50/// single [CommonTableExpression] inside of the WITH clause. That query must match certain
51/// requirements:
52/// * It is a query of UNION or UNION ALL of two queries.
53/// * The first part of the query (the left side of the UNION) must be executable first in itself.
54/// It must be non-recursive. (Cannot contain self reference)
55/// * The self reference must appear in the right hand side of the UNION.
56/// * The query can only have a single self-reference.
57/// * Recursive data-modifying statements are not supported, but you can use the results of a
58/// recursive SELECT query in a data-modifying statement. (like so: WITH RECURSIVE
59/// cte_name(a,b,c,d) AS (SELECT ... UNION SELECT ... FROM ... JOIN cte_name ON ... WHERE ...)
60/// DELETE FROM table WHERE table.a = cte_name.a)
61///
62/// It is mandatory to set the [Self::table_name] and the [Self::query].
63#[derive(Debug, Clone, Default, PartialEq)]
64pub struct CommonTableExpression {
65 pub(crate) table_name: Option<DynIden>,
66 pub(crate) cols: Vec<DynIden>,
67 pub(crate) query: CteQuery,
68 pub(crate) materialized: Option<bool>,
69}
70
71impl CommonTableExpression {
72 /// Construct a new [`CommonTableExpression`]
73 pub fn new() -> CommonTableExpression {
74 Self::default()
75 }
76
77 /// Sets the CTE table name of the query.
78 pub fn table_name<T>(&mut self, table_name: T) -> &mut Self
79 where
80 T: IntoIden,
81 {
82 self.table_name = Some(table_name.into_iden());
83 self
84 }
85
86 /// Sets the CTE VALUES clause.
87 ///
88 /// It overwrites the query if it is already set for the CTE.
89 pub fn values(&mut self, values: Vec<Values>) -> &mut Self {
90 self.query = CteQuery::Values(values);
91 self
92 }
93
94 /// Adds a named column to the CTE table definition.
95 pub fn column<C>(&mut self, col: C) -> &mut Self
96 where
97 C: IntoIden,
98 {
99 self.cols.push(col.into_iden());
100 self
101 }
102
103 /// Adds a named columns to the CTE table definition.
104 pub fn columns<T, I>(&mut self, cols: I) -> &mut Self
105 where
106 T: IntoIden,
107 I: IntoIterator<Item = T>,
108 {
109 self.cols
110 .extend(cols.into_iter().map(|col| col.into_iden()));
111 self
112 }
113
114 /// Some databases allow you to put "MATERIALIZED" or "NOT MATERIALIZED" in the CTE definition.
115 /// This will affect how during the execution of [WithQuery] the CTE in the [WithClause] will be
116 /// executed. If the database doesn't support this syntax this option specified here will be
117 /// ignored and not appear in the generated sql.
118 pub fn materialized(&mut self, materialized: bool) -> &mut Self {
119 self.materialized = Some(materialized);
120 self
121 }
122
123 /// Set the query generating the CTE content. The query's result must match the defined
124 /// columns.
125 ///
126 /// It overwrites the values if it is already set for the CTE.
127 pub fn query<Q>(&mut self, query: Q) -> &mut Self
128 where
129 Q: Into<SubQueryStatement>,
130 {
131 self.query = CteQuery::SubQuery(Box::new(query.into()));
132 self
133 }
134
135 /// Create a CTE from a [SelectStatement] if the selections are named columns then this will
136 /// return a [CommonTableExpression] that has the column names set. The [Self::table_name] is
137 /// set if the [SelectStatement] from clause contains at least one table.
138 pub fn from_select(select: SelectStatement) -> Self {
139 let mut cte = Self::default();
140 cte.try_set_cols_from_selects(&select.selects);
141 if let Some(from) = select.from.first() {
142 match from {
143 TableRef::Table(_, Some(alias)) => cte.set_table_name_from_select(alias),
144 TableRef::Table(TableName(_, tbl), None) => cte.set_table_name_from_select(tbl),
145 _ => {}
146 }
147 }
148 cte.query = CteQuery::SubQuery(Box::new(select.into()));
149 cte
150 }
151
152 fn set_table_name_from_select(&mut self, iden: &DynIden) {
153 self.table_name = Some(format!("cte_{iden}").into_iden())
154 }
155
156 /// Set up the columns of the CTE to match the given [SelectStatement] selected columns.
157 /// This will fail if the select contains non named columns like expressions of wildcards.
158 ///
159 /// Returns true if the column setup from the select query was successful. If the returned
160 /// value is false the columns are untouched.
161 pub fn try_set_cols_from_select(&mut self, select: &SelectStatement) -> bool {
162 self.try_set_cols_from_selects(&select.selects)
163 }
164
165 fn try_set_cols_from_selects(&mut self, selects: &[SelectExpr]) -> bool {
166 let vec: Option<Vec<DynIden>> = selects
167 .iter()
168 .map(|select| {
169 if let Some(ident) = &select.alias {
170 Some(ident.clone())
171 } else {
172 match &select.expr {
173 Expr::Column(ColumnRef::Column(column_name)) => {
174 // We could depend on `itertools` instead of joining manually.
175 let mut joined_column_name = String::new();
176 for part in column_name.clone().into_iter() {
177 joined_column_name.push_str(&part.0);
178 joined_column_name.push('_');
179 }
180 // Remove the trailing underscore after the column name.
181 joined_column_name.pop();
182 Some(joined_column_name.into_iden())
183 }
184 _ => None,
185 }
186 }
187 })
188 .collect();
189
190 if let Some(c) = vec {
191 self.cols = c;
192 return true;
193 }
194
195 false
196 }
197}