Skip to main content

sql_builder/backend/
query_builder.rs

1use std::{borrow::Cow, ops::Deref};
2
3use crate::*;
4
5const QUOTE: Quote = Quote(b'"', b'"');
6
7mod common;
8pub(crate) mod conflict;
9mod constants;
10pub(crate) mod expressions;
11pub(crate) mod functions;
12pub(crate) mod statements;
13pub(crate) mod values;
14pub(crate) use common::*;
15
16pub trait QueryBuilder:
17    QuotedBuilder + EscapeBuilder + TableRefBuilder + OperLeftAssocDecider + PrecedenceDecider + Sized
18{
19    /// The type of placeholder the builder uses for values, and whether it is numbered.
20    fn placeholder(&self) -> (&'static str, bool) {
21        statements::placeholder(self)
22    }
23
24    /// Whose lexical rules SQL text written for this builder follows: where
25    /// its strings, comments and markers begin and end.
26    fn lexer_dialect(&self) -> crate::lexer::Dialect;
27
28    /// Prefix for tuples in VALUES list (e.g. ROW for MySQL)
29    fn values_list_tuple_prefix(&self) -> &str {
30        statements::values_list_tuple_prefix(self)
31    }
32
33    fn prepare_union_statement(
34        &self,
35        union_type: UnionType,
36        select_statement: &SelectStatement,
37        sql: &mut impl SqlWriter,
38    ) -> Result<(), RenderError> {
39        statements::prepare_union_statement(self, union_type, select_statement, sql)
40    }
41
42    // Translate the LIMIT and OFFSET expression in [`SelectStatement`]
43    fn prepare_select_limit_offset(
44        &self,
45        select: &SelectStatement,
46        sql: &mut impl SqlWriter,
47    ) -> Result<(), RenderError> {
48        prepare_limit_offset(self, select, None, sql)
49    }
50
51    #[allow(unused_variables)]
52    fn prepare_update_join(
53        &self,
54        from: &[TableRef],
55        condition: &ConditionHolder,
56        sql: &mut impl SqlWriter,
57    ) -> Result<(), RenderError> {
58        // MySQL specific
59        Ok(())
60    }
61
62    fn prepare_update_from(
63        &self,
64        from: &[TableRef],
65        sql: &mut impl SqlWriter,
66    ) -> Result<(), RenderError> {
67        statements::prepare_update_from(self, from, sql)
68    }
69
70    fn prepare_update_column(
71        &self,
72        table: &Option<Box<TableRef>>,
73        from: &[TableRef],
74        column: &DynIden,
75        sql: &mut impl SqlWriter,
76    ) -> Result<(), RenderError> {
77        statements::prepare_update_column(self, table, from, column, sql)
78    }
79
80    fn prepare_update_condition(
81        &self,
82        from: &[TableRef],
83        condition: &ConditionHolder,
84        sql: &mut impl SqlWriter,
85    ) -> Result<(), RenderError> {
86        statements::prepare_update_condition(self, from, condition, sql)
87    }
88
89    /// Translate [`Expr`] into SQL statement.
90    fn prepare_expr(
91        &self,
92        simple_expr: &Expr,
93        sql: &mut impl SqlWriter,
94    ) -> Result<(), RenderError> {
95        expressions::prepare_expr(self, simple_expr, sql)
96    }
97
98    /// Translate [`SelectDistinct`] into SQL statement.
99    fn prepare_select_distinct(
100        &self,
101        select_distinct: &SelectDistinct,
102        sql: &mut impl SqlWriter,
103    ) -> Result<(), RenderError> {
104        expressions::prepare_select_distinct(self, select_distinct, sql)
105    }
106
107    /// Translate [`LockType`] into SQL statement.
108    fn prepare_select_lock(
109        &self,
110        lock: &LockClause,
111        sql: &mut impl SqlWriter,
112    ) -> Result<(), RenderError> {
113        expressions::prepare_select_lock(self, lock, sql)
114    }
115
116    /// Translate [`BinOper`] into SQL statement.
117    fn prepare_bin_oper(
118        &self,
119        bin_oper: &BinOper,
120        sql: &mut impl SqlWriter,
121    ) -> Result<(), RenderError> {
122        expressions::prepare_bin_oper(self, bin_oper, sql)
123    }
124
125    /// Translate [`SubQueryOper`] into SQL statement.
126    fn prepare_sub_query_oper(
127        &self,
128        oper: &SubQueryOper,
129        sql: &mut impl SqlWriter,
130    ) -> Result<(), RenderError> {
131        expressions::prepare_sub_query_oper(self, oper, sql);
132        Ok(())
133    }
134
135    /// Translate [`QueryStatement`] into SQL statement.
136    fn prepare_query_statement(
137        &self,
138        query: &SubQueryStatement,
139        sql: &mut impl SqlWriter,
140    ) -> Result<(), RenderError> {
141        query.prepare_statement(self, sql)
142    }
143
144    fn prepare_select_into(
145        &self,
146        into_table: &SelectInto,
147        sql: &mut impl SqlWriter,
148    ) -> Result<(), RenderError>;
149
150    fn prepare_with_query_clause_materialization(
151        &self,
152        cte: &CommonTableExpression,
153        sql: &mut impl SqlWriter,
154    ) -> Result<(), RenderError> {
155        functions::prepare_with_query_clause_materialization(self, cte, sql)
156    }
157
158    #[doc(hidden)]
159    /// Write the body of a common table expression
160    fn prepare_cte_query(
161        &self,
162        query: &SubQueryStatement,
163        sql: &mut impl SqlWriter,
164    ) -> Result<(), RenderError> {
165        functions::prepare_cte_query(self, query, sql)
166    }
167
168    #[doc(hidden)]
169    /// Write the WITH clause that precedes an INSERT
170    fn prepare_insert_with(
171        &self,
172        with: &WithClause,
173        sql: &mut impl SqlWriter,
174    ) -> Result<(), RenderError> {
175        functions::prepare_with_clause(self, with, sql)
176    }
177
178    fn prepare_function_name(
179        &self,
180        function: &Func,
181        sql: &mut impl SqlWriter,
182    ) -> Result<(), RenderError> {
183        functions::prepare_function_name_common(self, function, sql)
184    }
185
186    /// Translate [`JoinType`] into SQL statement.
187    fn prepare_join_type(
188        &self,
189        join_type: &JoinType,
190        sql: &mut impl SqlWriter,
191    ) -> Result<(), RenderError> {
192        functions::prepare_join_type_common(self, join_type, sql)
193    }
194
195    /// Translate [`OrderExpr`] into SQL statement.
196    fn prepare_order_expr(
197        &self,
198        order_expr: &OrderExpr,
199        sql: &mut impl SqlWriter,
200    ) -> Result<(), RenderError> {
201        functions::prepare_order_expr(self, order_expr, sql)
202    }
203
204    /// Write [`Value`] into SQL statement as parameter.
205    fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
206        sql.push_param(value, self)
207    }
208
209    #[doc(hidden)]
210    fn write_value(&self, buf: &mut impl SqlWriter, value: &Value) -> Result<(), RenderError> {
211        values::write_value(self, buf, value)
212    }
213
214    #[doc(hidden)]
215    /// Write ON CONFLICT target
216    fn prepare_on_conflict_target(
217        &self,
218        on_conflict_targets: &OnConflictTarget,
219        sql: &mut impl SqlWriter,
220    ) -> Result<(), RenderError> {
221        conflict::prepare_on_conflict_target(self, on_conflict_targets, sql)
222    }
223
224    #[doc(hidden)]
225    /// Write ON CONFLICT action
226    fn prepare_on_conflict_action(
227        &self,
228        on_conflict_action: &Option<OnConflictAction>,
229        sql: &mut impl SqlWriter,
230    ) -> Result<(), RenderError> {
231        conflict::prepare_on_conflict_action(self, on_conflict_action, sql)
232    }
233
234    #[doc(hidden)]
235    /// Write ON CONFLICT keywords
236    fn prepare_on_conflict_keywords(&self, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
237        conflict::prepare_on_conflict_keywords(self, sql);
238        Ok(())
239    }
240
241    #[doc(hidden)]
242    /// Write ON CONFLICT keywords
243    fn prepare_on_conflict_do_update_keywords(
244        &self,
245        sql: &mut impl SqlWriter,
246    ) -> Result<(), RenderError> {
247        conflict::prepare_on_conflict_do_update_keywords(self, sql);
248        Ok(())
249    }
250
251    #[doc(hidden)]
252    /// Write ON CONFLICT update action by retrieving value from the excluded table
253    fn prepare_on_conflict_excluded_table(
254        &self,
255        col: &DynIden,
256        sql: &mut impl SqlWriter,
257    ) -> Result<(), RenderError> {
258        conflict::prepare_on_conflict_excluded_table(self, col, sql)
259    }
260
261    #[doc(hidden)]
262    /// Write ON CONFLICT conditions
263    fn prepare_on_conflict_condition(
264        &self,
265        on_conflict_condition: &ConditionHolder,
266        sql: &mut impl SqlWriter,
267    ) -> Result<(), RenderError> {
268        conflict::prepare_on_conflict_condition(self, on_conflict_condition, sql)
269    }
270
271    #[doc(hidden)]
272    /// Write the WHERE of an ON CONFLICT action
273    fn prepare_on_conflict_action_condition(
274        &self,
275        condition: &ConditionHolder,
276        sql: &mut impl SqlWriter,
277    ) -> Result<(), RenderError> {
278        self.prepare_on_conflict_condition(condition, sql)
279    }
280
281    #[doc(hidden)]
282    /// Write `INSERT`, or `REPLACE` when `replace` is set
283    fn prepare_insert(&self, replace: bool, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
284        functions::prepare_insert(self, replace, sql);
285        Ok(())
286    }
287
288    #[doc(hidden)]
289    /// Write the ORDER BY and LIMIT of an UPDATE or DELETE
290    fn prepare_mutation_order_limit(
291        &self,
292        orders: &[OrderExpr],
293        limit: &Option<Value>,
294        sql: &mut impl SqlWriter,
295    ) -> Result<(), RenderError> {
296        statements::prepare_mutation_order_limit(self, orders, limit, sql)
297    }
298
299    #[doc(hidden)]
300    /// Write the ORDER BY and LIMIT of an UPDATE, which joins the `from` tables
301    fn prepare_update_order_limit(
302        &self,
303        _from: &[TableRef],
304        orders: &[OrderExpr],
305        limit: &Option<Value>,
306        sql: &mut impl SqlWriter,
307    ) -> Result<(), RenderError> {
308        self.prepare_mutation_order_limit(orders, limit, sql)
309    }
310
311    #[doc(hidden)]
312    /// Write the RETURNING clause of an UPDATE, which joins the `from` tables
313    fn prepare_update_returning(
314        &self,
315        _from: &[TableRef],
316        returning: &Option<ReturningClause>,
317        sql: &mut impl SqlWriter,
318    ) -> Result<(), RenderError> {
319        self.prepare_returning(returning, sql)
320    }
321
322    #[doc(hidden)]
323    /// Write the `FILTER (WHERE ..)` of an aggregate call
324    fn prepare_function_filter(
325        &self,
326        filter: &Condition,
327        sql: &mut impl SqlWriter,
328    ) -> Result<(), RenderError> {
329        functions::prepare_function_filter(self, filter, sql)
330    }
331
332    #[doc(hidden)]
333    /// Write the RETURNING clause of an INSERT, UPDATE or DELETE
334    fn prepare_returning(
335        &self,
336        returning: &Option<ReturningClause>,
337        sql: &mut impl SqlWriter,
338    ) -> Result<(), RenderError> {
339        conflict::prepare_returning(self, returning, sql)
340    }
341
342    fn write_string_quoted(&self, string: &str, buffer: &mut impl Write) {
343        constants::write_string_quoted(self, string, buffer);
344    }
345
346    #[doc(hidden)]
347    /// Write bytes enclosed with engine specific byte syntax
348    fn write_bytes(&self, bytes: &[u8], buffer: &mut impl Write) {
349        constants::write_bytes(self, bytes, buffer);
350    }
351
352    #[doc(hidden)]
353    /// The name of the function that represents the "if null" condition.
354    fn if_null_function(&self) -> &str {
355        constants::if_null_function(self)
356    }
357
358    #[doc(hidden)]
359    /// The name of the function that represents the "greatest" function.
360    fn greatest_function(&self) -> &str {
361        constants::greatest_function(self)
362    }
363
364    #[doc(hidden)]
365    /// The name of the function that represents the "least" function.
366    fn least_function(&self) -> &str {
367        constants::least_function(self)
368    }
369
370    #[doc(hidden)]
371    /// The name of the function that returns the char length.
372    fn char_length_function(&self) -> &str {
373        constants::char_length_function(self)
374    }
375
376    #[doc(hidden)]
377    /// The name of the function that returns a random number
378    fn random_function(&self) -> &str {
379        constants::random_function(self)
380    }
381
382    #[doc(hidden)]
383    /// The name of the function that returns the lock phrase including the leading 'FOR'
384    fn lock_phrase(&self, lock_type: LockType) -> &'static str {
385        constants::lock_phrase(self, lock_type)
386    }
387
388    /// The keywords for insert default row.
389    fn insert_default_keyword(&self) -> &str {
390        constants::insert_default_keyword(self)
391    }
392
393    /// Write insert default rows expression.
394    fn insert_default_values(
395        &self,
396        num_rows: usize,
397        sql: &mut impl SqlWriter,
398    ) -> Result<(), RenderError> {
399        constants::insert_default_values(self, num_rows, sql)
400    }
401}
402
403#[cfg(test)]
404#[path = "../../tests/unit/query_builder_tests.rs"]
405mod tests;