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) -> 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        Ok(())
79    }
80
81    fn prepare_update_condition(
82        &self,
83        from: &[TableRef],
84        condition: &ConditionHolder,
85        sql: &mut impl SqlWriter,
86    ) -> Result<(), RenderError> {
87        statements::prepare_update_condition(self, from, condition, sql)
88    }
89
90    /// Translate [`Expr`] into SQL statement.
91    fn prepare_expr(
92        &self,
93        simple_expr: &Expr,
94        sql: &mut impl SqlWriter,
95    ) -> Result<(), RenderError> {
96        expressions::prepare_expr(self, simple_expr, sql)
97    }
98
99    /// Translate [`SelectDistinct`] into SQL statement.
100    fn prepare_select_distinct(
101        &self,
102        select_distinct: &SelectDistinct,
103        sql: &mut impl SqlWriter,
104    ) -> Result<(), RenderError> {
105        expressions::prepare_select_distinct(self, select_distinct, sql)
106    }
107
108    /// Translate [`LockType`] into SQL statement.
109    fn prepare_select_lock(
110        &self,
111        lock: &LockClause,
112        sql: &mut impl SqlWriter,
113    ) -> Result<(), RenderError> {
114        expressions::prepare_select_lock(self, lock, sql)
115    }
116
117    /// Translate [`BinOper`] into SQL statement.
118    fn prepare_bin_oper(
119        &self,
120        bin_oper: &BinOper,
121        sql: &mut impl SqlWriter,
122    ) -> Result<(), RenderError> {
123        expressions::prepare_bin_oper(self, bin_oper, sql)
124    }
125
126    /// Translate [`SubQueryOper`] into SQL statement.
127    fn prepare_sub_query_oper(
128        &self,
129        oper: &SubQueryOper,
130        sql: &mut impl SqlWriter,
131    ) -> Result<(), RenderError> {
132        expressions::prepare_sub_query_oper(self, oper, sql);
133        Ok(())
134    }
135
136    /// Translate [`QueryStatement`] into SQL statement.
137    fn prepare_query_statement(
138        &self,
139        query: &SubQueryStatement,
140        sql: &mut impl SqlWriter,
141    ) -> Result<(), RenderError> {
142        query.prepare_statement(self, sql)
143    }
144
145    fn prepare_select_into(
146        &self,
147        into_table: &SelectInto,
148        sql: &mut impl SqlWriter,
149    ) -> Result<(), RenderError>;
150
151    fn prepare_with_query_clause_materialization(
152        &self,
153        cte: &CommonTableExpression,
154        sql: &mut impl SqlWriter,
155    ) -> Result<(), RenderError> {
156        functions::prepare_with_query_clause_materialization(self, cte, sql);
157        Ok(())
158    }
159
160    #[doc(hidden)]
161    /// Write the body of a common table expression
162    fn prepare_cte_query(
163        &self,
164        query: &SubQueryStatement,
165        sql: &mut impl SqlWriter,
166    ) -> Result<(), RenderError> {
167        functions::prepare_cte_query(self, query, sql)
168    }
169
170    #[doc(hidden)]
171    /// Write the WITH clause that precedes an INSERT
172    fn prepare_insert_with(
173        &self,
174        with: &WithClause,
175        sql: &mut impl SqlWriter,
176    ) -> Result<(), RenderError> {
177        functions::prepare_with_clause(self, with, sql)
178    }
179
180    fn prepare_function_name(
181        &self,
182        function: &Func,
183        sql: &mut impl SqlWriter,
184    ) -> Result<(), RenderError> {
185        functions::prepare_function_name_common(self, function, sql)
186    }
187
188    /// Translate [`JoinType`] into SQL statement.
189    fn prepare_join_type(
190        &self,
191        join_type: &JoinType,
192        sql: &mut impl SqlWriter,
193    ) -> Result<(), RenderError> {
194        functions::prepare_join_type_common(self, join_type, sql)
195    }
196
197    /// Translate [`OrderExpr`] into SQL statement.
198    fn prepare_order_expr(
199        &self,
200        order_expr: &OrderExpr,
201        sql: &mut impl SqlWriter,
202    ) -> Result<(), RenderError> {
203        functions::prepare_order_expr(self, order_expr, sql)
204    }
205
206    /// Write [`Value`] into SQL statement as parameter.
207    fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
208        sql.push_param(value, self)
209    }
210
211    #[doc(hidden)]
212    fn write_value(&self, buf: &mut impl SqlWriter, value: &Value) -> Result<(), RenderError> {
213        values::write_value(self, buf, value)
214    }
215
216    #[doc(hidden)]
217    /// Write ON CONFLICT target
218    fn prepare_on_conflict_target(
219        &self,
220        on_conflict_targets: &OnConflictTarget,
221        sql: &mut impl SqlWriter,
222    ) -> Result<(), RenderError> {
223        conflict::prepare_on_conflict_target(self, on_conflict_targets, sql)
224    }
225
226    #[doc(hidden)]
227    /// Write ON CONFLICT action
228    fn prepare_on_conflict_action(
229        &self,
230        on_conflict_action: &Option<OnConflictAction>,
231        sql: &mut impl SqlWriter,
232    ) -> Result<(), RenderError> {
233        conflict::prepare_on_conflict_action(self, on_conflict_action, sql)
234    }
235
236    #[doc(hidden)]
237    /// Write ON CONFLICT keywords
238    fn prepare_on_conflict_keywords(&self, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
239        conflict::prepare_on_conflict_keywords(self, sql);
240        Ok(())
241    }
242
243    #[doc(hidden)]
244    /// Write ON CONFLICT keywords
245    fn prepare_on_conflict_do_update_keywords(
246        &self,
247        sql: &mut impl SqlWriter,
248    ) -> Result<(), RenderError> {
249        conflict::prepare_on_conflict_do_update_keywords(self, sql);
250        Ok(())
251    }
252
253    #[doc(hidden)]
254    /// Write ON CONFLICT update action by retrieving value from the excluded table
255    fn prepare_on_conflict_excluded_table(
256        &self,
257        col: &DynIden,
258        sql: &mut impl SqlWriter,
259    ) -> Result<(), RenderError> {
260        conflict::prepare_on_conflict_excluded_table(self, col, sql);
261        Ok(())
262    }
263
264    #[doc(hidden)]
265    /// Write ON CONFLICT conditions
266    fn prepare_on_conflict_condition(
267        &self,
268        on_conflict_condition: &ConditionHolder,
269        sql: &mut impl SqlWriter,
270    ) -> Result<(), RenderError> {
271        conflict::prepare_on_conflict_condition(self, on_conflict_condition, sql)
272    }
273
274    #[doc(hidden)]
275    /// Write the WHERE of an ON CONFLICT action
276    fn prepare_on_conflict_action_condition(
277        &self,
278        condition: &ConditionHolder,
279        sql: &mut impl SqlWriter,
280    ) -> Result<(), RenderError> {
281        self.prepare_on_conflict_condition(condition, sql)
282    }
283
284    #[doc(hidden)]
285    /// Write `INSERT`, or `REPLACE` when `replace` is set
286    fn prepare_insert(&self, replace: bool, sql: &mut impl SqlWriter) -> Result<(), RenderError> {
287        functions::prepare_insert(self, replace, sql);
288        Ok(())
289    }
290
291    #[doc(hidden)]
292    /// Write the ORDER BY and LIMIT of an UPDATE or DELETE
293    fn prepare_mutation_order_limit(
294        &self,
295        orders: &[OrderExpr],
296        limit: &Option<Value>,
297        sql: &mut impl SqlWriter,
298    ) -> Result<(), RenderError> {
299        statements::prepare_mutation_order_limit(self, orders, limit, sql)
300    }
301
302    #[doc(hidden)]
303    /// Write the ORDER BY and LIMIT of an UPDATE, which joins the `from` tables
304    fn prepare_update_order_limit(
305        &self,
306        _from: &[TableRef],
307        orders: &[OrderExpr],
308        limit: &Option<Value>,
309        sql: &mut impl SqlWriter,
310    ) -> Result<(), RenderError> {
311        self.prepare_mutation_order_limit(orders, limit, sql)
312    }
313
314    #[doc(hidden)]
315    /// Write the RETURNING clause of an UPDATE, which joins the `from` tables
316    fn prepare_update_returning(
317        &self,
318        _from: &[TableRef],
319        returning: &Option<ReturningClause>,
320        sql: &mut impl SqlWriter,
321    ) -> Result<(), RenderError> {
322        self.prepare_returning(returning, sql)
323    }
324
325    #[doc(hidden)]
326    /// Write the `FILTER (WHERE ..)` of an aggregate call
327    fn prepare_function_filter(
328        &self,
329        filter: &Condition,
330        sql: &mut impl SqlWriter,
331    ) -> Result<(), RenderError> {
332        functions::prepare_function_filter(self, filter, sql)
333    }
334
335    #[doc(hidden)]
336    /// Write the RETURNING clause of an INSERT, UPDATE or DELETE
337    fn prepare_returning(
338        &self,
339        returning: &Option<ReturningClause>,
340        sql: &mut impl SqlWriter,
341    ) -> Result<(), RenderError> {
342        conflict::prepare_returning(self, returning, sql)
343    }
344
345    fn write_string_quoted(&self, string: &str, buffer: &mut impl Write) {
346        constants::write_string_quoted(self, string, buffer);
347    }
348
349    #[doc(hidden)]
350    /// Write bytes enclosed with engine specific byte syntax
351    fn write_bytes(&self, bytes: &[u8], buffer: &mut impl Write) {
352        constants::write_bytes(self, bytes, buffer);
353    }
354
355    #[doc(hidden)]
356    /// The name of the function that represents the "if null" condition.
357    fn if_null_function(&self) -> &str {
358        constants::if_null_function(self)
359    }
360
361    #[doc(hidden)]
362    /// The name of the function that represents the "greatest" function.
363    fn greatest_function(&self) -> &str {
364        constants::greatest_function(self)
365    }
366
367    #[doc(hidden)]
368    /// The name of the function that represents the "least" function.
369    fn least_function(&self) -> &str {
370        constants::least_function(self)
371    }
372
373    #[doc(hidden)]
374    /// The name of the function that returns the char length.
375    fn char_length_function(&self) -> &str {
376        constants::char_length_function(self)
377    }
378
379    #[doc(hidden)]
380    /// The name of the function that returns a random number
381    fn random_function(&self) -> &str {
382        constants::random_function(self)
383    }
384
385    #[doc(hidden)]
386    /// The name of the function that returns the lock phrase including the leading 'FOR'
387    fn lock_phrase(&self, lock_type: LockType) -> &'static str {
388        constants::lock_phrase(self, lock_type)
389    }
390
391    /// The keywords for insert default row.
392    fn insert_default_keyword(&self) -> &str {
393        constants::insert_default_keyword(self)
394    }
395
396    /// Write insert default rows expression.
397    fn insert_default_values(
398        &self,
399        num_rows: usize,
400        sql: &mut impl SqlWriter,
401    ) -> Result<(), RenderError> {
402        constants::insert_default_values(self, num_rows, sql);
403        Ok(())
404    }
405}
406
407#[cfg(test)]
408#[path = "../../tests/unit/query_builder_tests.rs"]
409mod tests;