sea_query/backend/
query_builder.rs

1use std::{fmt, ops::Deref};
2
3use crate::*;
4
5const QUOTE: Quote = Quote(b'"', b'"');
6
7pub trait QueryBuilder:
8    QuotedBuilder + EscapeBuilder + TableRefBuilder + OperLeftAssocDecider + PrecedenceDecider + Sized
9{
10    /// The type of placeholder the builder uses for values, and whether it is numbered.
11    fn placeholder(&self) -> (&'static str, bool) {
12        ("?", false)
13    }
14
15    /// Prefix for tuples in VALUES list (e.g. ROW for MySQL)
16    fn values_list_tuple_prefix(&self) -> &str {
17        ""
18    }
19
20    /// Translate [`InsertStatement`] into SQL statement.
21    fn prepare_insert_statement(&self, insert: &InsertStatement, sql: &mut impl SqlWriter) {
22        if let Some(with) = &insert.with {
23            self.prepare_with_clause(with, sql);
24        }
25
26        self.prepare_insert(insert.replace, sql);
27
28        if let Some(table) = &insert.table {
29            sql.write_str(" INTO ").unwrap();
30
31            self.prepare_table_ref(table, sql);
32        }
33
34        if insert.default_values.unwrap_or_default() != 0
35            && insert.columns.is_empty()
36            && insert.source.is_none()
37        {
38            self.prepare_output(&insert.returning, sql);
39            sql.write_str(" ").unwrap();
40            let num_rows = insert.default_values.unwrap();
41            self.insert_default_values(num_rows, sql);
42        } else {
43            sql.write_str(" (").unwrap();
44            let mut cols = insert.columns.iter();
45            join_io!(
46                cols,
47                col,
48                join {
49                    sql.write_str(", ").unwrap();
50                },
51                do {
52                    self.prepare_iden(col, sql);
53                }
54            );
55
56            sql.write_str(")").unwrap();
57
58            self.prepare_output(&insert.returning, sql);
59
60            if let Some(source) = &insert.source {
61                sql.write_str(" ").unwrap();
62                match source {
63                    InsertValueSource::Values(values) => {
64                        sql.write_str("VALUES ").unwrap();
65                        let mut vals = values.iter();
66                        join_io!(
67                            vals,
68                            row,
69                            join {
70                                sql.write_str(", ").unwrap();
71                            },
72                            do {
73                                sql.write_str("(").unwrap();
74                                let mut cols = row.iter();
75                                join_io!(
76                                    cols,
77                                    col,
78                                    join {
79                                        sql.write_str(", ").unwrap();
80                                    },
81                                    do {
82                                        self.prepare_expr(col, sql);
83                                    }
84                                );
85
86                                sql.write_str(")").unwrap();
87                            }
88                        );
89                    }
90                    InsertValueSource::Select(select_query) => {
91                        self.prepare_select_statement(select_query.deref(), sql);
92                    }
93                }
94            }
95        }
96
97        self.prepare_on_conflict(&insert.on_conflict, sql);
98
99        self.prepare_returning(&insert.returning, sql);
100    }
101
102    fn prepare_union_statement(
103        &self,
104        union_type: UnionType,
105        select_statement: &SelectStatement,
106        sql: &mut impl SqlWriter,
107    ) {
108        match union_type {
109            UnionType::Intersect => sql.write_str(" INTERSECT (").unwrap(),
110            UnionType::Distinct => sql.write_str(" UNION (").unwrap(),
111            UnionType::Except => sql.write_str(" EXCEPT (").unwrap(),
112            UnionType::All => sql.write_str(" UNION ALL (").unwrap(),
113        }
114        self.prepare_select_statement(select_statement, sql);
115        sql.write_str(")").unwrap();
116    }
117
118    /// Translate [`SelectStatement`] into SQL statement.
119    fn prepare_select_statement(&self, select: &SelectStatement, sql: &mut impl SqlWriter) {
120        if let Some(with) = &select.with {
121            self.prepare_with_clause(with, sql);
122        }
123
124        sql.write_str("SELECT ").unwrap();
125
126        if let Some(distinct) = &select.distinct {
127            self.prepare_select_distinct(distinct, sql);
128            sql.write_str(" ").unwrap();
129        }
130
131        let mut selects = select.selects.iter();
132        join_io!(
133            selects,
134            expr,
135            join {
136                sql.write_str(", ").unwrap();
137            },
138            do {
139                self.prepare_select_expr(expr, sql);
140            }
141        );
142
143        let mut from_tables = select.from.iter();
144        join_io!(
145            from_tables,
146            table_ref,
147            first {
148                sql.write_str(" FROM ").unwrap();
149            },
150            join {
151                sql.write_str(", ").unwrap();
152            },
153            do {
154                self.prepare_table_ref(table_ref, sql);
155                self.prepare_index_hints(table_ref,select, sql);
156            },
157            last {
158                self.prepare_table_sample(select, sql);
159            }
160        );
161
162        for expr in &select.join {
163            sql.write_str(" ").unwrap();
164            self.prepare_join_expr(expr, sql);
165        }
166
167        self.prepare_condition(&select.r#where, "WHERE", sql);
168
169        let mut groups = select.groups.iter();
170        join_io!(
171            groups,
172            expr,
173            first {
174                sql.write_str(" GROUP BY ").unwrap();
175            },
176            join {
177                sql.write_str(", ").unwrap();
178            },
179            do {
180                self.prepare_expr(expr, sql);
181            }
182        );
183
184        self.prepare_condition(&select.having, "HAVING", sql);
185
186        if !select.unions.is_empty() {
187            select.unions.iter().for_each(|(union_type, query)| {
188                self.prepare_union_statement(*union_type, query, sql);
189            });
190        }
191
192        let mut orders = select.orders.iter();
193        join_io!(
194            orders,
195            expr,
196            first {
197                sql.write_str(" ORDER BY ").unwrap();
198            },
199            join {
200                sql.write_str(", ").unwrap();
201            },
202            do {
203                self.prepare_order_expr(expr, sql);
204            }
205        );
206
207        self.prepare_select_limit_offset(select, sql);
208
209        if let Some(lock) = &select.lock {
210            sql.write_str(" ").unwrap();
211            self.prepare_select_lock(lock, sql);
212        }
213
214        if let Some((name, query)) = &select.window {
215            sql.write_str(" WINDOW ").unwrap();
216            self.prepare_iden(name, sql);
217            sql.write_str(" AS (").unwrap();
218            self.prepare_window_statement(query, sql);
219            sql.write_str(")").unwrap();
220        }
221    }
222
223    // Translate the LIMIT and OFFSET expression in [`SelectStatement`]
224    fn prepare_select_limit_offset(&self, select: &SelectStatement, sql: &mut impl SqlWriter) {
225        if let Some(limit) = &select.limit {
226            sql.write_str(" LIMIT ").unwrap();
227            self.prepare_value(limit.clone(), sql);
228        }
229
230        if let Some(offset) = &select.offset {
231            sql.write_str(" OFFSET ").unwrap();
232            self.prepare_value(offset.clone(), sql);
233        }
234    }
235
236    /// Translate [`UpdateStatement`] into SQL statement.
237    fn prepare_update_statement(&self, update: &UpdateStatement, sql: &mut impl SqlWriter) {
238        if let Some(with) = &update.with {
239            self.prepare_with_clause(with, sql);
240        }
241
242        sql.write_str("UPDATE ").unwrap();
243
244        if let Some(table) = &update.table {
245            self.prepare_table_ref(table, sql);
246        }
247
248        self.prepare_update_join(&update.from, &update.r#where, sql);
249
250        sql.write_str(" SET ").unwrap();
251
252        let mut values = update.values.iter();
253        join_io!(
254            values,
255            row,
256            join {
257                sql.write_str(", ").unwrap();
258            },
259            do {
260                let (col, v) = row;
261                self.prepare_update_column(&update.table, &update.from, col, sql);
262                sql.write_str(" = ").unwrap();
263                self.prepare_expr(v, sql);
264            }
265        );
266
267        self.prepare_update_from(&update.from, sql);
268
269        self.prepare_output(&update.returning, sql);
270
271        self.prepare_update_condition(&update.from, &update.r#where, sql);
272
273        self.prepare_update_order_by(update, sql);
274
275        self.prepare_update_limit(update, sql);
276
277        self.prepare_returning(&update.returning, sql);
278    }
279
280    fn prepare_update_join(&self, _: &[TableRef], _: &ConditionHolder, _: &mut impl SqlWriter) {
281        // MySQL specific
282    }
283
284    fn prepare_update_from(&self, from: &[TableRef], sql: &mut impl SqlWriter) {
285        let mut from_iter = from.iter();
286        join_io!(
287            from_iter,
288            table_ref,
289            first {
290                sql.write_str(" FROM ").unwrap();
291            },
292            join {
293                sql.write_str(", ").unwrap();
294            },
295            do {
296                self.prepare_table_ref(table_ref, sql);
297            }
298        );
299    }
300
301    fn prepare_update_column(
302        &self,
303        _: &Option<Box<TableRef>>,
304        _: &[TableRef],
305        column: &DynIden,
306        sql: &mut impl SqlWriter,
307    ) {
308        self.prepare_iden(column, sql);
309    }
310
311    fn prepare_update_condition(
312        &self,
313        _: &[TableRef],
314        condition: &ConditionHolder,
315        sql: &mut impl SqlWriter,
316    ) {
317        self.prepare_condition(condition, "WHERE", sql);
318    }
319
320    /// Translate ORDER BY expression in [`UpdateStatement`].
321    fn prepare_update_order_by(&self, update: &UpdateStatement, sql: &mut impl SqlWriter) {
322        let mut orders = update.orders.iter();
323        join_io!(
324            orders,
325            expr,
326            first {
327                sql.write_str(" ORDER BY ").unwrap();
328            },
329            join {
330                sql.write_str(", ").unwrap();
331            },
332            do {
333                self.prepare_order_expr(expr, sql);
334            }
335        );
336    }
337
338    /// Translate LIMIT expression in [`UpdateStatement`].
339    fn prepare_update_limit(&self, update: &UpdateStatement, sql: &mut impl SqlWriter) {
340        if let Some(limit) = &update.limit {
341            sql.write_str(" LIMIT ").unwrap();
342            self.prepare_value(limit.clone(), sql);
343        }
344    }
345
346    /// Translate [`DeleteStatement`] into SQL statement.
347    fn prepare_delete_statement(&self, delete: &DeleteStatement, sql: &mut impl SqlWriter) {
348        if let Some(with) = &delete.with {
349            self.prepare_with_clause(with, sql);
350        }
351
352        sql.write_str("DELETE ").unwrap();
353
354        if let Some(table) = &delete.table {
355            sql.write_str("FROM ").unwrap();
356            self.prepare_table_ref(table, sql);
357        }
358
359        self.prepare_output(&delete.returning, sql);
360
361        self.prepare_condition(&delete.r#where, "WHERE", sql);
362
363        self.prepare_delete_order_by(delete, sql);
364
365        self.prepare_delete_limit(delete, sql);
366
367        self.prepare_returning(&delete.returning, sql);
368    }
369
370    /// Translate ORDER BY expression in [`DeleteStatement`].
371    fn prepare_delete_order_by(&self, delete: &DeleteStatement, sql: &mut impl SqlWriter) {
372        let mut orders = delete.orders.iter();
373        join_io!(
374            orders,
375            expr,
376            first {
377                sql.write_str(" ORDER BY ").unwrap();
378            },
379            join {
380                sql.write_str(", ").unwrap();
381            },
382            do {
383                self.prepare_order_expr(expr, sql);
384            }
385        );
386    }
387
388    /// Translate LIMIT expression in [`DeleteStatement`].
389    fn prepare_delete_limit(&self, delete: &DeleteStatement, sql: &mut impl SqlWriter) {
390        if let Some(limit) = &delete.limit {
391            sql.write_str(" LIMIT ").unwrap();
392            self.prepare_value(limit.clone(), sql);
393        }
394    }
395
396    /// Translate [`Expr`] into SQL statement.
397    fn prepare_expr(&self, simple_expr: &Expr, sql: &mut impl SqlWriter) {
398        self.prepare_expr_common(simple_expr, sql);
399    }
400
401    fn prepare_expr_common(&self, simple_expr: &Expr, sql: &mut impl SqlWriter) {
402        match simple_expr {
403            Expr::Column(column_ref) => {
404                self.prepare_column_ref(column_ref, sql);
405            }
406            Expr::Tuple(exprs) => {
407                self.prepare_tuple(exprs, sql);
408            }
409            Expr::Unary(op, expr) => {
410                self.prepare_un_oper(op, sql);
411                sql.write_str(" ").unwrap();
412                let drop_expr_paren =
413                    self.inner_expr_well_known_greater_precedence(expr, &(*op).into());
414                if !drop_expr_paren {
415                    sql.write_str("(").unwrap();
416                }
417                self.prepare_expr(expr, sql);
418                if !drop_expr_paren {
419                    sql.write_str(")").unwrap();
420                }
421            }
422            Expr::FunctionCall(func) => {
423                self.prepare_function_name(&func.func, sql);
424                self.prepare_function_arguments(func, sql);
425            }
426            Expr::Binary(left, op, right) => match (op, right.as_ref()) {
427                (BinOper::In, Expr::Tuple(t)) if t.is_empty() => {
428                    self.binary_expr(&1i32.into(), &BinOper::Equal, &2i32.into(), sql)
429                }
430                (BinOper::NotIn, Expr::Tuple(t)) if t.is_empty() => {
431                    self.binary_expr(&1i32.into(), &BinOper::Equal, &1i32.into(), sql)
432                }
433                _ => self.binary_expr(left, op, right, sql),
434            },
435            Expr::SubQuery(oper, sel) => {
436                if let Some(oper) = oper {
437                    self.prepare_sub_query_oper(oper, sql);
438                }
439                sql.write_str("(").unwrap();
440                self.prepare_query_statement(sel.deref(), sql);
441                sql.write_str(")").unwrap();
442            }
443            Expr::Value(val) => {
444                self.prepare_value(val.clone(), sql);
445            }
446            Expr::Values(list) => {
447                sql.write_str("(").unwrap();
448                let mut iter = list.iter();
449                join_io!(
450                    iter,
451                    val,
452                    join {
453                        sql.write_str(", ").unwrap();
454                    },
455                    do {
456                        self.prepare_value(val.clone(), sql);
457                    }
458                );
459                sql.write_str(")").unwrap();
460            }
461            Expr::Custom(s) => {
462                sql.write_str(s).unwrap();
463            }
464            Expr::CustomWithExpr(expr, values) => {
465                let (placeholder, numbered) = self.placeholder();
466                let mut tokenizer = Tokenizer::new(expr).iter().peekable();
467                let mut count = 0;
468                while let Some(token) = tokenizer.next() {
469                    match token {
470                        Token::Punctuation(mark) if mark == placeholder => match tokenizer.peek() {
471                            Some(Token::Punctuation(next_mark)) if next_mark == &placeholder => {
472                                sql.write_str(next_mark).unwrap();
473                                tokenizer.next();
474                            }
475                            Some(Token::Unquoted(tok)) if numbered => {
476                                if let Ok(num) = tok.parse::<usize>() {
477                                    self.prepare_expr(&values[num - 1], sql);
478                                }
479                                tokenizer.next();
480                            }
481                            _ => {
482                                self.prepare_expr(&values[count], sql);
483                                count += 1;
484                            }
485                        },
486                        _ => sql.write_str(token.as_str()).unwrap(),
487                    };
488                }
489            }
490            Expr::Keyword(keyword) => {
491                self.prepare_keyword(keyword, sql);
492            }
493            Expr::AsEnum(_, expr) => {
494                self.prepare_expr(expr, sql);
495            }
496            Expr::Case(case_stmt) => {
497                self.prepare_case_statement(case_stmt, sql);
498            }
499            Expr::Constant(val) => {
500                self.prepare_constant(val, sql);
501            }
502            Expr::TypeName(type_name) => {
503                self.prepare_type_ref(type_name, sql);
504            }
505        }
506    }
507
508    /// Translate [`CaseStatement`] into SQL statement.
509    fn prepare_case_statement(&self, stmts: &CaseStatement, sql: &mut impl SqlWriter) {
510        sql.write_str("(CASE").unwrap();
511
512        let CaseStatement { when, r#else } = stmts;
513
514        for case in when.iter() {
515            sql.write_str(" WHEN (").unwrap();
516            self.prepare_condition_where(&case.condition, sql);
517            sql.write_str(") THEN ").unwrap();
518
519            self.prepare_expr(&case.result, sql);
520        }
521        if let Some(r#else) = r#else {
522            sql.write_str(" ELSE ").unwrap();
523            self.prepare_expr(r#else, sql);
524        }
525
526        sql.write_str(" END)").unwrap();
527    }
528
529    /// Translate [`SelectDistinct`] into SQL statement.
530    fn prepare_select_distinct(&self, select_distinct: &SelectDistinct, sql: &mut impl SqlWriter) {
531        match select_distinct {
532            SelectDistinct::All => sql.write_str("ALL").unwrap(),
533            SelectDistinct::Distinct => sql.write_str("DISTINCT").unwrap(),
534            _ => {}
535        }
536    }
537
538    /// Translate [`IndexHint`] into SQL statement.
539    fn prepare_index_hints(
540        &self,
541        _table_ref: &TableRef,
542        _select: &SelectStatement,
543        _sql: &mut impl SqlWriter,
544    ) {
545    }
546
547    /// Translate [`TableSample`] into SQL statement.
548    fn prepare_table_sample(&self, _select: &SelectStatement, _sql: &mut impl SqlWriter) {}
549
550    /// Translate [`LockType`] into SQL statement.
551    fn prepare_select_lock(&self, lock: &LockClause, sql: &mut impl SqlWriter) {
552        sql.write_str(self.lock_phrase(lock.r#type)).unwrap();
553        let mut tables = lock.tables.iter();
554        join_io!(
555            tables,
556            table_ref,
557            first {
558                sql.write_str(" OF ").unwrap();
559            },
560            join {
561                sql.write_str(", ").unwrap();
562            },
563            do {
564                self.prepare_table_ref(table_ref, sql);
565            }
566        );
567
568        if let Some(behavior) = lock.behavior {
569            match behavior {
570                LockBehavior::Nowait => sql.write_str(" NOWAIT").unwrap(),
571                LockBehavior::SkipLocked => sql.write_str(" SKIP LOCKED").unwrap(),
572            }
573        }
574    }
575
576    /// Translate [`SelectExpr`] into SQL statement.
577    fn prepare_select_expr(&self, select_expr: &SelectExpr, sql: &mut impl SqlWriter) {
578        self.prepare_expr(&select_expr.expr, sql);
579        match &select_expr.window {
580            Some(WindowSelectType::Name(name)) => {
581                sql.write_str(" OVER ").unwrap();
582                self.prepare_iden(name, sql);
583            }
584            Some(WindowSelectType::Query(window)) => {
585                sql.write_str(" OVER ").unwrap();
586                sql.write_str("( ").unwrap();
587                self.prepare_window_statement(window, sql);
588                sql.write_str(" )").unwrap();
589            }
590            None => {}
591        };
592
593        if let Some(alias) = &select_expr.alias {
594            sql.write_str(" AS ").unwrap();
595            self.prepare_iden(alias, sql);
596        };
597    }
598
599    /// Translate [`JoinExpr`] into SQL statement.
600    fn prepare_join_expr(&self, join_expr: &JoinExpr, sql: &mut impl SqlWriter) {
601        self.prepare_join_type(&join_expr.join, sql);
602        sql.write_str(" ").unwrap();
603        self.prepare_join_table_ref(join_expr, sql);
604        if let Some(on) = &join_expr.on {
605            self.prepare_join_on(on, sql);
606        }
607    }
608
609    fn prepare_join_table_ref(&self, join_expr: &JoinExpr, sql: &mut impl SqlWriter) {
610        if join_expr.lateral {
611            sql.write_str("LATERAL ").unwrap();
612        }
613        self.prepare_table_ref(&join_expr.table, sql);
614    }
615
616    /// Translate [`TableRef`] into SQL statement.
617    fn prepare_table_ref(&self, table_ref: &TableRef, sql: &mut impl SqlWriter) {
618        match table_ref {
619            TableRef::SubQuery(query, alias) => {
620                sql.write_str("(").unwrap();
621                self.prepare_select_statement(query, sql);
622                sql.write_str(")").unwrap();
623                sql.write_str(" AS ").unwrap();
624                self.prepare_iden(alias, sql);
625            }
626            TableRef::ValuesList(values, alias) => {
627                sql.write_str("(").unwrap();
628                self.prepare_values_list(values, sql);
629                sql.write_str(")").unwrap();
630                sql.write_str(" AS ").unwrap();
631                self.prepare_iden(alias, sql);
632            }
633            TableRef::FunctionCall(func, alias) => {
634                self.prepare_function_name(&func.func, sql);
635                self.prepare_function_arguments(func, sql);
636                sql.write_str(" AS ").unwrap();
637                self.prepare_iden(alias, sql);
638            }
639            _ => self.prepare_table_ref_iden(table_ref, sql),
640        }
641    }
642
643    fn prepare_column_ref(&self, column_ref: &ColumnRef, sql: &mut impl SqlWriter) {
644        match column_ref {
645            ColumnRef::Column(ColumnName(table_name, column)) => {
646                if let Some(table_name) = table_name {
647                    self.prepare_table_name(table_name, sql);
648                    sql.write_str(".").unwrap();
649                }
650                self.prepare_iden(column, sql);
651            }
652            ColumnRef::Asterisk(table_name) => {
653                if let Some(table_name) = table_name {
654                    self.prepare_table_name(table_name, sql);
655                    sql.write_str(".").unwrap();
656                }
657                sql.write_str("*").unwrap();
658            }
659        }
660    }
661
662    /// Translate [`UnOper`] into SQL statement.
663    fn prepare_un_oper(&self, un_oper: &UnOper, sql: &mut impl SqlWriter) {
664        sql.write_str(match un_oper {
665            UnOper::Not => "NOT",
666        })
667        .unwrap();
668    }
669
670    fn prepare_bin_oper_common(&self, bin_oper: &BinOper, sql: &mut impl SqlWriter) {
671        sql.write_str(match bin_oper {
672            BinOper::And => "AND",
673            BinOper::Or => "OR",
674            BinOper::Like => "LIKE",
675            BinOper::NotLike => "NOT LIKE",
676            BinOper::Is => "IS",
677            BinOper::IsNot => "IS NOT",
678            BinOper::In => "IN",
679            BinOper::NotIn => "NOT IN",
680            BinOper::Between => "BETWEEN",
681            BinOper::NotBetween => "NOT BETWEEN",
682            BinOper::Equal => "=",
683            BinOper::NotEqual => "<>",
684            BinOper::SmallerThan => "<",
685            BinOper::GreaterThan => ">",
686            BinOper::SmallerThanOrEqual => "<=",
687            BinOper::GreaterThanOrEqual => ">=",
688            BinOper::Add => "+",
689            BinOper::Sub => "-",
690            BinOper::Mul => "*",
691            BinOper::Div => "/",
692            BinOper::Mod => "%",
693            BinOper::LShift => "<<",
694            BinOper::RShift => ">>",
695            BinOper::As => "AS",
696            BinOper::Escape => "ESCAPE",
697            BinOper::Custom(raw) => raw,
698            BinOper::BitAnd => "&",
699            BinOper::BitOr => "|",
700            #[allow(unreachable_patterns)]
701            _ => unimplemented!(),
702        })
703        .unwrap();
704    }
705
706    /// Translate [`BinOper`] into SQL statement.
707    fn prepare_bin_oper(&self, bin_oper: &BinOper, sql: &mut impl SqlWriter) {
708        self.prepare_bin_oper_common(bin_oper, sql);
709    }
710
711    /// Translate [`SubQueryOper`] into SQL statement.
712    fn prepare_sub_query_oper(&self, oper: &SubQueryOper, sql: &mut impl SqlWriter) {
713        sql.write_str(match oper {
714            SubQueryOper::Exists => "EXISTS",
715            SubQueryOper::Any => "ANY",
716            SubQueryOper::Some => "SOME",
717            SubQueryOper::All => "ALL",
718        })
719        .unwrap();
720    }
721
722    /// Translate [`LogicalChainOper`] into SQL statement.
723    fn prepare_logical_chain_oper(
724        &self,
725        log_chain_oper: &LogicalChainOper,
726        i: usize,
727        length: usize,
728        sql: &mut impl SqlWriter,
729    ) {
730        let (simple_expr, oper) = match log_chain_oper {
731            LogicalChainOper::And(simple_expr) => (simple_expr, "AND"),
732            LogicalChainOper::Or(simple_expr) => (simple_expr, "OR"),
733        };
734        if i > 0 {
735            sql.write_str(" ").unwrap();
736            sql.write_str(oper).unwrap();
737            sql.write_str(" ").unwrap();
738        }
739        let both_binary = match simple_expr {
740            Expr::Binary(_, _, right) => {
741                matches!(right.as_ref(), Expr::Binary(_, _, _))
742            }
743            _ => false,
744        };
745        let need_parentheses = length > 1 && both_binary;
746        if need_parentheses {
747            sql.write_str("(").unwrap();
748        }
749        self.prepare_expr(simple_expr, sql);
750        if need_parentheses {
751            sql.write_str(")").unwrap();
752        }
753    }
754
755    /// Translate [`Function`] into SQL statement.
756    fn prepare_function_name_common(&self, function: &Func, sql: &mut impl SqlWriter) {
757        if let Func::Custom(iden) = function {
758            sql.write_str(&iden.0)
759        } else {
760            sql.write_str(match function {
761                Func::Max => "MAX",
762                Func::Min => "MIN",
763                Func::Sum => "SUM",
764                Func::Avg => "AVG",
765                Func::Abs => "ABS",
766                Func::Coalesce => "COALESCE",
767                Func::Count => "COUNT",
768                Func::IfNull => self.if_null_function(),
769                Func::Greatest => self.greatest_function(),
770                Func::Least => self.least_function(),
771                Func::CharLength => self.char_length_function(),
772                Func::Cast => "CAST",
773                Func::Lower => "LOWER",
774                Func::Upper => "UPPER",
775                Func::BitAnd => "BIT_AND",
776                Func::BitOr => "BIT_OR",
777                Func::Custom(_) => "",
778                Func::Random => self.random_function(),
779                Func::Round => "ROUND",
780                Func::Md5 => "MD5",
781                #[cfg(feature = "backend-postgres")]
782                Func::PgFunction(_) => unimplemented!(),
783            })
784        }
785        .unwrap();
786    }
787
788    fn prepare_function_arguments(&self, func: &FunctionCall, sql: &mut impl SqlWriter) {
789        sql.write_str("(").unwrap();
790        let mut args = func.args.iter().zip(func.mods.iter());
791
792        if let Some((arg, modifier)) = args.next() {
793            if modifier.distinct {
794                sql.write_str("DISTINCT ").unwrap();
795            }
796            self.prepare_expr(arg, sql);
797        }
798
799        for (arg, modifier) in args {
800            sql.write_str(", ").unwrap();
801            if modifier.distinct {
802                sql.write_str("DISTINCT ").unwrap();
803            }
804            self.prepare_expr(arg, sql);
805        }
806
807        sql.write_str(")").unwrap();
808    }
809
810    /// Translate [`QueryStatement`] into SQL statement.
811    fn prepare_query_statement(&self, query: &SubQueryStatement, sql: &mut impl SqlWriter);
812
813    fn prepare_with_query(&self, query: &WithQuery, sql: &mut impl SqlWriter) {
814        self.prepare_with_clause(&query.with_clause, sql);
815        self.prepare_query_statement(query.query.as_ref().unwrap().deref(), sql);
816    }
817
818    fn prepare_with_clause(&self, with_clause: &WithClause, sql: &mut impl SqlWriter) {
819        self.prepare_with_clause_start(with_clause, sql);
820        self.prepare_with_clause_common_tables(with_clause, sql);
821        if with_clause.recursive {
822            self.prepare_with_clause_recursive_options(with_clause, sql);
823        }
824    }
825
826    fn prepare_with_clause_recursive_options(
827        &self,
828        with_clause: &WithClause,
829        sql: &mut impl SqlWriter,
830    ) {
831        if with_clause.recursive {
832            if let Some(search) = &with_clause.search {
833                sql.write_str("SEARCH ").unwrap();
834                sql.write_str(match &search.order.as_ref().unwrap() {
835                    SearchOrder::BREADTH => "BREADTH",
836                    SearchOrder::DEPTH => "DEPTH",
837                })
838                .unwrap();
839                sql.write_str(" FIRST BY ").unwrap();
840
841                self.prepare_expr(&search.expr.as_ref().unwrap().expr, sql);
842
843                sql.write_str(" SET ").unwrap();
844
845                self.prepare_iden(search.expr.as_ref().unwrap().alias.as_ref().unwrap(), sql);
846                sql.write_str(" ").unwrap();
847            }
848            if let Some(cycle) = &with_clause.cycle {
849                sql.write_str("CYCLE ").unwrap();
850
851                self.prepare_expr(cycle.expr.as_ref().unwrap(), sql);
852
853                sql.write_str(" SET ").unwrap();
854
855                self.prepare_iden(cycle.set_as.as_ref().unwrap(), sql);
856                sql.write_str(" USING ").unwrap();
857                self.prepare_iden(cycle.using.as_ref().unwrap(), sql);
858                sql.write_str(" ").unwrap();
859            }
860        }
861    }
862
863    fn prepare_with_clause_common_tables(
864        &self,
865        with_clause: &WithClause,
866        sql: &mut impl SqlWriter,
867    ) {
868        let mut cte_first = true;
869        assert_ne!(
870            with_clause.cte_expressions.len(),
871            0,
872            "Cannot build a with query that has no common table expression!"
873        );
874
875        for cte in &with_clause.cte_expressions {
876            if !cte_first {
877                sql.write_str(", ").unwrap();
878            }
879            cte_first = false;
880
881            self.prepare_with_query_clause_common_table(cte, sql);
882        }
883    }
884
885    fn prepare_with_query_clause_common_table(
886        &self,
887        cte: &CommonTableExpression,
888        sql: &mut impl SqlWriter,
889    ) {
890        self.prepare_iden(cte.table_name.as_ref().unwrap(), sql);
891
892        if cte.cols.is_empty() {
893            sql.write_str(" ").unwrap();
894        } else {
895            sql.write_str(" (").unwrap();
896
897            let mut col_first = true;
898            for col in &cte.cols {
899                if !col_first {
900                    sql.write_str(", ").unwrap();
901                }
902                col_first = false;
903                self.prepare_iden(col, sql);
904            }
905
906            sql.write_str(") ").unwrap();
907        }
908
909        sql.write_str("AS ").unwrap();
910
911        self.prepare_with_query_clause_materialization(cte, sql);
912
913        sql.write_str("(").unwrap();
914
915        self.prepare_query_statement(cte.query.as_ref().unwrap().deref(), sql);
916
917        sql.write_str(") ").unwrap();
918    }
919
920    fn prepare_with_query_clause_materialization(
921        &self,
922        cte: &CommonTableExpression,
923        sql: &mut impl SqlWriter,
924    ) {
925        if let Some(materialized) = cte.materialized {
926            if !materialized {
927                sql.write_str("NOT MATERIALIZED ")
928            } else {
929                sql.write_str(" MATERIALIZED ")
930            }
931            .unwrap()
932        }
933    }
934
935    fn prepare_with_clause_start(&self, with_clause: &WithClause, sql: &mut impl SqlWriter) {
936        sql.write_str("WITH ").unwrap();
937
938        if with_clause.recursive {
939            sql.write_str("RECURSIVE ").unwrap();
940        }
941    }
942
943    fn prepare_insert(&self, replace: bool, sql: &mut impl SqlWriter) {
944        if replace {
945            sql.write_str("REPLACE").unwrap();
946        } else {
947            sql.write_str("INSERT").unwrap();
948        }
949    }
950
951    fn prepare_function_name(&self, function: &Func, sql: &mut impl SqlWriter) {
952        self.prepare_function_name_common(function, sql)
953    }
954
955    /// Translate [`TypeRef`] into an SQL statement.
956    fn prepare_type_ref(&self, type_name: &TypeRef, sql: &mut impl SqlWriter) {
957        let TypeRef(schema_name, r#type) = type_name;
958        if let Some(schema_name) = schema_name {
959            self.prepare_schema_name(schema_name, sql);
960            write!(sql, ".").unwrap();
961        }
962        self.prepare_iden(r#type, sql);
963    }
964
965    /// Translate [`JoinType`] into SQL statement.
966    fn prepare_join_type(&self, join_type: &JoinType, sql: &mut impl SqlWriter) {
967        self.prepare_join_type_common(join_type, sql)
968    }
969
970    fn prepare_join_type_common(&self, join_type: &JoinType, sql: &mut impl SqlWriter) {
971        sql.write_str(match join_type {
972            JoinType::Join => "JOIN",
973            JoinType::CrossJoin => "CROSS JOIN",
974            JoinType::InnerJoin => "INNER JOIN",
975            JoinType::LeftJoin => "LEFT JOIN",
976            JoinType::RightJoin => "RIGHT JOIN",
977            JoinType::FullOuterJoin => "FULL OUTER JOIN",
978            JoinType::StraightJoin => "STRAIGHT_JOIN",
979        })
980        .unwrap()
981    }
982
983    /// Translate [`OrderExpr`] into SQL statement.
984    fn prepare_order_expr(&self, order_expr: &OrderExpr, sql: &mut impl SqlWriter) {
985        if !matches!(order_expr.order, Order::Field(_)) {
986            self.prepare_expr(&order_expr.expr, sql);
987        }
988        self.prepare_order(order_expr, sql);
989    }
990
991    /// Translate [`JoinOn`] into SQL statement.
992    fn prepare_join_on(&self, join_on: &JoinOn, sql: &mut impl SqlWriter) {
993        match join_on {
994            JoinOn::Condition(c) => self.prepare_condition(c, "ON", sql),
995            JoinOn::Columns(_c) => unimplemented!(),
996        }
997    }
998
999    /// Translate [`Order`] into SQL statement.
1000    fn prepare_order(&self, order_expr: &OrderExpr, sql: &mut impl SqlWriter) {
1001        match &order_expr.order {
1002            Order::Asc => sql.write_str(" ASC").unwrap(),
1003            Order::Desc => sql.write_str(" DESC").unwrap(),
1004            Order::Field(values) => self.prepare_field_order(order_expr, values, sql),
1005        }
1006    }
1007
1008    /// Translate [`Order::Field`] into SQL statement
1009    fn prepare_field_order(
1010        &self,
1011        order_expr: &OrderExpr,
1012        values: &Values,
1013        sql: &mut impl SqlWriter,
1014    ) {
1015        sql.write_str("CASE ").unwrap();
1016        let mut i = 0;
1017        for value in &values.0 {
1018            sql.write_str("WHEN ").unwrap();
1019            self.prepare_expr(&order_expr.expr, sql);
1020            sql.write_str("=").unwrap();
1021            self.write_value(sql, value).unwrap();
1022            sql.write_str(" THEN ").unwrap();
1023            write_int(sql, i);
1024            sql.write_str(" ").unwrap();
1025            i += 1;
1026        }
1027
1028        sql.write_str("ELSE ").unwrap();
1029        write_int(sql, i);
1030        sql.write_str(" END").unwrap();
1031    }
1032
1033    /// Write [`Value`] into SQL statement as parameter.
1034    fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter);
1035
1036    /// Write [`Value`] inline.
1037    fn prepare_constant(&self, value: &Value, sql: &mut impl SqlWriter) {
1038        self.write_value(sql, value).unwrap();
1039    }
1040
1041    /// Translate a `&[ValueTuple]` into a VALUES list.
1042    fn prepare_values_list(&self, value_tuples: &[ValueTuple], sql: &mut impl SqlWriter) {
1043        sql.write_str("VALUES ").unwrap();
1044        let mut tuples = value_tuples.iter();
1045        join_io!(
1046            tuples,
1047            value_tuple,
1048            join {
1049                sql.write_str(", ").unwrap();
1050            },
1051            do {
1052                sql.write_str(self.values_list_tuple_prefix()).unwrap();
1053                sql.write_str("(").unwrap();
1054
1055                let mut values = value_tuple.clone().into_iter();
1056                join_io!(
1057                    values,
1058                    value,
1059                    join {
1060                        sql.write_str(", ").unwrap();
1061                    },
1062                    do {
1063                        self.prepare_value(value, sql);
1064                    }
1065                );
1066
1067                sql.write_str(")").unwrap();
1068            }
1069        );
1070    }
1071
1072    /// Translate [`Expr::Tuple`] into SQL statement.
1073    fn prepare_tuple(&self, exprs: &[Expr], sql: &mut impl SqlWriter) {
1074        sql.write_str("(").unwrap();
1075        for (i, expr) in exprs.iter().enumerate() {
1076            if i != 0 {
1077                sql.write_str(", ").unwrap();
1078            }
1079            self.prepare_expr(expr, sql);
1080        }
1081        sql.write_str(")").unwrap();
1082    }
1083
1084    /// Translate [`Keyword`] into SQL statement.
1085    fn prepare_keyword(&self, keyword: &Keyword, sql: &mut impl SqlWriter) {
1086        match keyword {
1087            Keyword::Null => sql.write_str("NULL").unwrap(),
1088            Keyword::CurrentDate => sql.write_str("CURRENT_DATE").unwrap(),
1089            Keyword::CurrentTime => sql.write_str("CURRENT_TIME").unwrap(),
1090            Keyword::CurrentTimestamp => sql.write_str("CURRENT_TIMESTAMP").unwrap(),
1091            Keyword::Default => sql.write_str("DEFAULT").unwrap(),
1092            Keyword::Custom(iden) => sql.write_str(&iden.0).unwrap(),
1093        }
1094    }
1095
1096    /// Convert a SQL value into syntax-specific string
1097    fn value_to_string(&self, v: &Value) -> String {
1098        self.value_to_string_common(v)
1099    }
1100
1101    fn value_to_string_common(&self, v: &Value) -> String {
1102        let mut s = String::new();
1103        self.write_value(&mut s, v).unwrap();
1104        s
1105    }
1106
1107    #[doc(hidden)]
1108    fn write_value(&self, buf: &mut impl Write, value: &Value) -> fmt::Result {
1109        self.write_value_common(buf, value)
1110    }
1111
1112    #[doc(hidden)]
1113    fn write_value_common(&self, buf: &mut impl Write, value: &Value) -> fmt::Result {
1114        match value {
1115            Value::Bool(None)
1116            | Value::TinyInt(None)
1117            | Value::SmallInt(None)
1118            | Value::Int(None)
1119            | Value::BigInt(None)
1120            | Value::TinyUnsigned(None)
1121            | Value::SmallUnsigned(None)
1122            | Value::Unsigned(None)
1123            | Value::BigUnsigned(None)
1124            | Value::Float(None)
1125            | Value::Double(None)
1126            | Value::String(None)
1127            | Value::Char(None)
1128            | Value::Bytes(None) => buf.write_str("NULL")?,
1129            #[cfg(feature = "with-json")]
1130            Value::Json(None) => buf.write_str("NULL")?,
1131            #[cfg(feature = "with-chrono")]
1132            Value::ChronoDate(None) => buf.write_str("NULL")?,
1133            #[cfg(feature = "with-chrono")]
1134            Value::ChronoTime(None) => buf.write_str("NULL")?,
1135            #[cfg(feature = "with-chrono")]
1136            Value::ChronoDateTime(None) => buf.write_str("NULL")?,
1137            #[cfg(feature = "with-chrono")]
1138            Value::ChronoDateTimeUtc(None) => buf.write_str("NULL")?,
1139            #[cfg(feature = "with-chrono")]
1140            Value::ChronoDateTimeLocal(None) => buf.write_str("NULL")?,
1141            #[cfg(feature = "with-chrono")]
1142            Value::ChronoDateTimeWithTimeZone(None) => buf.write_str("NULL")?,
1143            #[cfg(feature = "with-time")]
1144            Value::TimeDate(None) => buf.write_str("NULL")?,
1145            #[cfg(feature = "with-time")]
1146            Value::TimeTime(None) => buf.write_str("NULL")?,
1147            #[cfg(feature = "with-time")]
1148            Value::TimeDateTime(None) => buf.write_str("NULL")?,
1149            #[cfg(feature = "with-time")]
1150            Value::TimeDateTimeWithTimeZone(None) => buf.write_str("NULL")?,
1151            #[cfg(feature = "with-jiff")]
1152            Value::JiffDate(None) => buf.write_str("NULL")?,
1153            #[cfg(feature = "with-jiff")]
1154            Value::JiffTime(None) => buf.write_str("NULL")?,
1155            #[cfg(feature = "with-jiff")]
1156            Value::JiffDateTime(None) => buf.write_str("NULL")?,
1157            #[cfg(feature = "with-jiff")]
1158            Value::JiffTimestamp(None) => buf.write_str("NULL")?,
1159            #[cfg(feature = "with-jiff")]
1160            Value::JiffZoned(None) => buf.write_str("NULL")?,
1161            #[cfg(feature = "with-rust_decimal")]
1162            Value::Decimal(None) => buf.write_str("NULL")?,
1163            #[cfg(feature = "with-bigdecimal")]
1164            Value::BigDecimal(None) => buf.write_str("NULL")?,
1165            #[cfg(feature = "with-uuid")]
1166            Value::Uuid(None) => buf.write_str("NULL")?,
1167            #[cfg(feature = "with-ipnetwork")]
1168            Value::IpNetwork(None) => buf.write_str("NULL")?,
1169            #[cfg(feature = "with-mac_address")]
1170            Value::MacAddress(None) => buf.write_str("NULL")?,
1171            #[cfg(feature = "postgres-array")]
1172            Value::Array(_, None) => buf.write_str("NULL")?,
1173            #[cfg(feature = "postgres-vector")]
1174            Value::Vector(None) => buf.write_str("NULL")?,
1175            Value::Bool(Some(b)) => buf.write_str(if *b { "TRUE" } else { "FALSE" })?,
1176            Value::TinyInt(Some(v)) => {
1177                write_int(buf, *v);
1178            }
1179            Value::SmallInt(Some(v)) => {
1180                write_int(buf, *v);
1181            }
1182            Value::Int(Some(v)) => {
1183                write_int(buf, *v);
1184            }
1185            Value::BigInt(Some(v)) => {
1186                write_int(buf, *v);
1187            }
1188            Value::TinyUnsigned(Some(v)) => {
1189                write_int(buf, *v);
1190            }
1191            Value::SmallUnsigned(Some(v)) => {
1192                write_int(buf, *v);
1193            }
1194            Value::Unsigned(Some(v)) => {
1195                write_int(buf, *v);
1196            }
1197            Value::BigUnsigned(Some(v)) => {
1198                write_int(buf, *v);
1199            }
1200            Value::Float(Some(v)) => write!(buf, "{v}")?,
1201            Value::Double(Some(v)) => write!(buf, "{v}")?,
1202            Value::String(Some(v)) => self.write_string_quoted(v, buf),
1203            Value::Char(Some(v)) => {
1204                self.write_string_quoted(std::str::from_utf8(&[*v as u8]).unwrap(), buf)
1205            }
1206            Value::Bytes(Some(v)) => self.write_bytes(v, buf),
1207            #[cfg(feature = "with-json")]
1208            Value::Json(Some(v)) => self.write_string_quoted(&v.to_string(), buf),
1209            #[cfg(feature = "with-chrono")]
1210            Value::ChronoDate(Some(v)) => {
1211                buf.write_str("'")?;
1212                write!(buf, "{}", v.format("%Y-%m-%d"))?;
1213                buf.write_str("'")?;
1214            }
1215            #[cfg(feature = "with-chrono")]
1216            Value::ChronoTime(Some(v)) => {
1217                buf.write_str("'")?;
1218                write!(buf, "{}", v.format("%H:%M:%S%.6f"))?;
1219                buf.write_str("'")?;
1220            }
1221            #[cfg(feature = "with-chrono")]
1222            Value::ChronoDateTime(Some(v)) => {
1223                buf.write_str("'")?;
1224                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f"))?;
1225                buf.write_str("'")?;
1226            }
1227            #[cfg(feature = "with-chrono")]
1228            Value::ChronoDateTimeUtc(Some(v)) => {
1229                buf.write_str("'")?;
1230                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1231                buf.write_str("'")?;
1232            }
1233            #[cfg(feature = "with-chrono")]
1234            Value::ChronoDateTimeLocal(Some(v)) => {
1235                buf.write_str("'")?;
1236                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1237                buf.write_str("'")?;
1238            }
1239            #[cfg(feature = "with-chrono")]
1240            Value::ChronoDateTimeWithTimeZone(Some(v)) => {
1241                buf.write_str("'")?;
1242                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1243                buf.write_str("'")?;
1244            }
1245            #[cfg(feature = "with-time")]
1246            Value::TimeDate(Some(v)) => {
1247                buf.write_str("'")?;
1248                buf.write_str(&v.format(time_format::FORMAT_DATE).unwrap())?;
1249                buf.write_str("'")?;
1250            }
1251            #[cfg(feature = "with-time")]
1252            Value::TimeTime(Some(v)) => {
1253                buf.write_str("'")?;
1254                buf.write_str(&v.format(time_format::FORMAT_TIME).unwrap())?;
1255                buf.write_str("'")?;
1256            }
1257            #[cfg(feature = "with-time")]
1258            Value::TimeDateTime(Some(v)) => {
1259                buf.write_str("'")?;
1260                buf.write_str(&v.format(time_format::FORMAT_DATETIME).unwrap())?;
1261                buf.write_str("'")?;
1262            }
1263            #[cfg(feature = "with-time")]
1264            Value::TimeDateTimeWithTimeZone(Some(v)) => {
1265                buf.write_str("'")?;
1266                buf.write_str(&v.format(time_format::FORMAT_DATETIME_TZ).unwrap())?;
1267                buf.write_str("'")?;
1268            }
1269            // Jiff date and time dosen't need format string
1270            // The default behavior is what we want
1271            #[cfg(feature = "with-jiff")]
1272            Value::JiffDate(Some(v)) => {
1273                buf.write_str("'")?;
1274                write!(buf, "{v}")?;
1275                buf.write_str("'")?;
1276            }
1277            #[cfg(feature = "with-jiff")]
1278            Value::JiffTime(Some(v)) => {
1279                buf.write_str("'")?;
1280                write!(buf, "{v}")?;
1281                buf.write_str("'")?;
1282            }
1283            // Both JiffDateTime and JiffTimestamp map to timestamp
1284            #[cfg(feature = "with-jiff")]
1285            Value::JiffDateTime(Some(v)) => {
1286                use crate::with_jiff::JIFF_DATE_TIME_FMT_STR;
1287                buf.write_str("'")?;
1288                write!(buf, "{}", v.strftime(JIFF_DATE_TIME_FMT_STR))?;
1289                buf.write_str("'")?;
1290            }
1291            #[cfg(feature = "with-jiff")]
1292            Value::JiffTimestamp(Some(v)) => {
1293                use crate::with_jiff::JIFF_TIMESTAMP_FMT_STR;
1294                buf.write_str("'")?;
1295                write!(buf, "{}", v.strftime(JIFF_TIMESTAMP_FMT_STR))?;
1296                buf.write_str("'")?;
1297            }
1298            #[cfg(feature = "with-jiff")]
1299            // Zoned map to timestamp with timezone
1300            Value::JiffZoned(Some(v)) => {
1301                use crate::with_jiff::JIFF_ZONE_FMT_STR;
1302                buf.write_str("'")?;
1303                write!(buf, "{}", v.strftime(JIFF_ZONE_FMT_STR))?;
1304                buf.write_str("'")?;
1305            }
1306            #[cfg(feature = "with-rust_decimal")]
1307            Value::Decimal(Some(v)) => write!(buf, "{v}")?,
1308            #[cfg(feature = "with-bigdecimal")]
1309            Value::BigDecimal(Some(v)) => write!(buf, "{v}")?,
1310            #[cfg(feature = "with-uuid")]
1311            Value::Uuid(Some(v)) => {
1312                buf.write_str("'")?;
1313                write!(buf, "{v}")?;
1314                buf.write_str("'")?;
1315            }
1316            #[cfg(feature = "postgres-array")]
1317            Value::Array(_, Some(v)) => {
1318                if v.is_empty() {
1319                    buf.write_str("'{}'")?;
1320                } else {
1321                    buf.write_str("ARRAY [")?;
1322
1323                    let mut viter = v.iter();
1324
1325                    if let Some(element) = viter.next() {
1326                        self.write_value(buf, element)?;
1327                    }
1328
1329                    for element in viter {
1330                        buf.write_str(",")?;
1331                        self.write_value(buf, element)?;
1332                    }
1333                    buf.write_str("]")?;
1334                }
1335            }
1336            #[cfg(feature = "postgres-vector")]
1337            Value::Vector(Some(v)) => {
1338                buf.write_str("'[")?;
1339                let mut viter = v.as_slice().iter();
1340
1341                if let Some(element) = viter.next() {
1342                    write!(buf, "{element}")?;
1343                }
1344
1345                for element in viter {
1346                    buf.write_str(",")?;
1347                    write!(buf, "{element}")?;
1348                }
1349                buf.write_str("]'")?;
1350            }
1351            #[cfg(feature = "with-ipnetwork")]
1352            Value::IpNetwork(Some(v)) => {
1353                buf.write_str("'")?;
1354                write!(buf, "{v}")?;
1355                buf.write_str("'")?;
1356            }
1357            #[cfg(feature = "with-mac_address")]
1358            Value::MacAddress(Some(v)) => {
1359                buf.write_str("'")?;
1360                write!(buf, "{v}")?;
1361                buf.write_str("'")?;
1362            }
1363        };
1364
1365        Ok(())
1366    }
1367
1368    #[doc(hidden)]
1369    /// Write ON CONFLICT expression
1370    fn prepare_on_conflict(&self, on_conflict: &Option<OnConflict>, sql: &mut impl SqlWriter) {
1371        if let Some(on_conflict) = on_conflict {
1372            self.prepare_on_conflict_keywords(sql);
1373            self.prepare_on_conflict_target(&on_conflict.targets, sql);
1374            self.prepare_on_conflict_condition(&on_conflict.target_where, sql);
1375            self.prepare_on_conflict_action(&on_conflict.action, sql);
1376            self.prepare_on_conflict_condition(&on_conflict.action_where, sql);
1377        }
1378    }
1379
1380    #[doc(hidden)]
1381    /// Write ON CONFLICT target
1382    fn prepare_on_conflict_target(
1383        &self,
1384        on_conflict_targets: &[OnConflictTarget],
1385        sql: &mut impl SqlWriter,
1386    ) {
1387        let mut targets = on_conflict_targets.iter();
1388        join_io!(
1389            targets,
1390            target,
1391            first {
1392                sql.write_str("(").unwrap();
1393            },
1394            join {
1395                sql.write_str(", ").unwrap();
1396            },
1397            do {
1398                match target {
1399                    OnConflictTarget::ConflictColumn(col) => {
1400                        self.prepare_iden(col, sql);
1401                    }
1402                    OnConflictTarget::ConflictExpr(expr) => {
1403                        self.prepare_expr(expr, sql);
1404                    }
1405                }
1406            },
1407            last {
1408                sql.write_str(")").unwrap();
1409            }
1410        );
1411    }
1412
1413    #[doc(hidden)]
1414    /// Write ON CONFLICT action
1415    fn prepare_on_conflict_action(
1416        &self,
1417        on_conflict_action: &Option<OnConflictAction>,
1418        sql: &mut impl SqlWriter,
1419    ) {
1420        self.prepare_on_conflict_action_common(on_conflict_action, sql);
1421    }
1422
1423    fn prepare_on_conflict_action_common(
1424        &self,
1425        on_conflict_action: &Option<OnConflictAction>,
1426        sql: &mut impl SqlWriter,
1427    ) {
1428        if let Some(action) = on_conflict_action {
1429            match action {
1430                OnConflictAction::DoNothing(_) => {
1431                    sql.write_str(" DO NOTHING").unwrap();
1432                }
1433                OnConflictAction::Update(update_strats) => {
1434                    self.prepare_on_conflict_do_update_keywords(sql);
1435                    let mut update_strats_iter = update_strats.iter();
1436                    join_io!(
1437                        update_strats_iter,
1438                        update_strat,
1439                        join {
1440                            sql.write_str(", ").unwrap();
1441                        },
1442                        do {
1443                            match update_strat {
1444                                OnConflictUpdate::Column(col) => {
1445                                    self.prepare_iden(col, sql);
1446                                    sql.write_str(" = ").unwrap();
1447                                    self.prepare_on_conflict_excluded_table(col, sql);
1448                                }
1449                                OnConflictUpdate::Expr(col, expr) => {
1450                                    self.prepare_iden(col, sql);
1451                                    sql.write_str(" = ").unwrap();
1452                                    self.prepare_expr(expr, sql);
1453                                }
1454                            }
1455                        }
1456                    );
1457                }
1458            }
1459        }
1460    }
1461
1462    #[doc(hidden)]
1463    /// Write ON CONFLICT keywords
1464    fn prepare_on_conflict_keywords(&self, sql: &mut impl SqlWriter) {
1465        sql.write_str(" ON CONFLICT ").unwrap();
1466    }
1467
1468    #[doc(hidden)]
1469    /// Write ON CONFLICT keywords
1470    fn prepare_on_conflict_do_update_keywords(&self, sql: &mut impl SqlWriter) {
1471        sql.write_str(" DO UPDATE SET ").unwrap();
1472    }
1473
1474    #[doc(hidden)]
1475    /// Write ON CONFLICT update action by retrieving value from the excluded table
1476    fn prepare_on_conflict_excluded_table(&self, col: &DynIden, sql: &mut impl SqlWriter) {
1477        sql.write_char(self.quote().left()).unwrap();
1478        sql.write_str("excluded").unwrap();
1479        sql.write_char(self.quote().right()).unwrap();
1480        sql.write_str(".").unwrap();
1481        self.prepare_iden(col, sql);
1482    }
1483
1484    #[doc(hidden)]
1485    /// Write ON CONFLICT conditions
1486    fn prepare_on_conflict_condition(
1487        &self,
1488        on_conflict_condition: &ConditionHolder,
1489        sql: &mut impl SqlWriter,
1490    ) {
1491        self.prepare_condition(on_conflict_condition, "WHERE", sql)
1492    }
1493
1494    #[doc(hidden)]
1495    /// Hook to insert "OUTPUT" expressions.
1496    fn prepare_output(&self, _returning: &Option<ReturningClause>, _sql: &mut impl SqlWriter) {}
1497
1498    #[doc(hidden)]
1499    /// Hook to insert "RETURNING" statements.
1500    fn prepare_returning(&self, returning: &Option<ReturningClause>, sql: &mut impl SqlWriter) {
1501        if let Some(returning) = returning {
1502            sql.write_str(" RETURNING ").unwrap();
1503            match &returning {
1504                ReturningClause::All => sql.write_str("*").unwrap(),
1505                ReturningClause::Columns(cols) => {
1506                    let mut cols_iter = cols.iter();
1507                    join_io!(
1508                        cols_iter,
1509                        column_ref,
1510                        join {
1511                            sql.write_str(", ").unwrap();
1512                        },
1513                        do {
1514                            self.prepare_column_ref(column_ref, sql);
1515                        }
1516                    );
1517                }
1518                ReturningClause::Exprs(exprs) => {
1519                    let mut exprs_iter = exprs.iter();
1520                    join_io!(
1521                        exprs_iter,
1522                        expr,
1523                        join {
1524                            sql.write_str(", ").unwrap();
1525                        },
1526                        do {
1527                            self.prepare_expr(expr, sql);
1528                        }
1529                    );
1530                }
1531            }
1532        }
1533    }
1534
1535    #[doc(hidden)]
1536    /// Translate a condition to a "WHERE" clause.
1537    fn prepare_condition(
1538        &self,
1539        condition: &ConditionHolder,
1540        keyword: &str,
1541        sql: &mut impl SqlWriter,
1542    ) {
1543        match &condition.contents {
1544            ConditionHolderContents::Empty => (),
1545            ConditionHolderContents::Chain(conditions) => {
1546                sql.write_str(" ").unwrap();
1547                sql.write_str(keyword).unwrap();
1548                sql.write_str(" ").unwrap();
1549                for (i, log_chain_oper) in conditions.iter().enumerate() {
1550                    self.prepare_logical_chain_oper(log_chain_oper, i, conditions.len(), sql);
1551                }
1552            }
1553            ConditionHolderContents::Condition(c) => {
1554                sql.write_str(" ").unwrap();
1555                sql.write_str(keyword).unwrap();
1556                sql.write_str(" ").unwrap();
1557                self.prepare_condition_where(c, sql);
1558            }
1559        }
1560    }
1561
1562    #[doc(hidden)]
1563    /// Translate part of a condition to part of a "WHERE" clause.
1564    fn prepare_condition_where(&self, condition: &Condition, sql: &mut impl SqlWriter) {
1565        let simple_expr = condition.clone().into();
1566        self.prepare_expr(&simple_expr, sql);
1567    }
1568
1569    #[doc(hidden)]
1570    /// Translate [`Frame`] into SQL statement.
1571    fn prepare_frame(&self, frame: &Frame, sql: &mut impl SqlWriter) {
1572        match *frame {
1573            Frame::UnboundedPreceding => sql.write_str("UNBOUNDED PRECEDING").unwrap(),
1574            Frame::Preceding(v) => {
1575                self.prepare_value(v.into(), sql);
1576                sql.write_str("PRECEDING").unwrap();
1577            }
1578            Frame::CurrentRow => sql.write_str("CURRENT ROW").unwrap(),
1579            Frame::Following(v) => {
1580                self.prepare_value(v.into(), sql);
1581                sql.write_str("FOLLOWING").unwrap();
1582            }
1583            Frame::UnboundedFollowing => sql.write_str("UNBOUNDED FOLLOWING").unwrap(),
1584        }
1585    }
1586
1587    #[doc(hidden)]
1588    /// Translate [`WindowStatement`] into SQL statement.
1589    fn prepare_window_statement(&self, window: &WindowStatement, sql: &mut impl SqlWriter) {
1590        let mut partition_iter = window.partition_by.iter();
1591        join_io!(
1592            partition_iter,
1593            expr,
1594            first {
1595                sql.write_str("PARTITION BY ").unwrap();
1596            },
1597            join {
1598                sql.write_str(", ").unwrap();
1599            },
1600            do {
1601                self.prepare_expr(expr, sql);
1602            }
1603        );
1604
1605        let mut order_iter = window.order_by.iter();
1606        join_io!(
1607            order_iter,
1608            expr,
1609            first {
1610                sql.write_str(" ORDER BY ").unwrap();
1611            },
1612            join {
1613                sql.write_str(", ").unwrap();
1614            },
1615            do {
1616                self.prepare_order_expr(expr, sql);
1617            }
1618        );
1619
1620        if let Some(frame) = &window.frame {
1621            match frame.r#type {
1622                FrameType::Range => sql.write_str(" RANGE ").unwrap(),
1623                FrameType::Rows => sql.write_str(" ROWS ").unwrap(),
1624            };
1625            if let Some(end) = &frame.end {
1626                sql.write_str("BETWEEN ").unwrap();
1627                self.prepare_frame(&frame.start, sql);
1628                sql.write_str(" AND ").unwrap();
1629                self.prepare_frame(end, sql);
1630            } else {
1631                self.prepare_frame(&frame.start, sql);
1632            }
1633        }
1634    }
1635
1636    #[doc(hidden)]
1637    /// Translate a binary expr to SQL.
1638    fn binary_expr(&self, left: &Expr, op: &BinOper, right: &Expr, sql: &mut impl SqlWriter) {
1639        // If left has higher precedence than op, we can drop parentheses around left
1640        let drop_left_higher_precedence =
1641            self.inner_expr_well_known_greater_precedence(left, &(*op).into());
1642
1643        // Figure out if left associativity rules allow us to drop the left parenthesis
1644        let drop_left_assoc = left.is_binary()
1645            && op == left.get_bin_oper().unwrap()
1646            && self.well_known_left_associative(op);
1647
1648        let left_paren = !drop_left_higher_precedence && !drop_left_assoc;
1649        if left_paren {
1650            sql.write_str("(").unwrap();
1651        }
1652        self.prepare_expr(left, sql);
1653        if left_paren {
1654            sql.write_str(")").unwrap();
1655        }
1656
1657        sql.write_str(" ").unwrap();
1658        self.prepare_bin_oper(op, sql);
1659        sql.write_str(" ").unwrap();
1660
1661        // If right has higher precedence than op, we can drop parentheses around right
1662        let drop_right_higher_precedence =
1663            self.inner_expr_well_known_greater_precedence(right, &(*op).into());
1664
1665        let op_as_oper = Oper::BinOper(*op);
1666        // Due to representation of trinary op between as nested binary ops.
1667        let drop_right_between_hack = op_as_oper.is_between()
1668            && right.is_binary()
1669            && matches!(right.get_bin_oper(), Some(&BinOper::And));
1670
1671        // Due to representation of trinary op like/not like with optional arg escape as nested binary ops.
1672        let drop_right_escape_hack = op_as_oper.is_like()
1673            && right.is_binary()
1674            && matches!(right.get_bin_oper(), Some(&BinOper::Escape));
1675
1676        // Due to custom representation of casting AS datatype
1677        let drop_right_as_hack = (op == &BinOper::As) && matches!(right, Expr::Custom(_));
1678
1679        let right_paren = !drop_right_higher_precedence
1680            && !drop_right_escape_hack
1681            && !drop_right_between_hack
1682            && !drop_right_as_hack;
1683        if right_paren {
1684            sql.write_str("(").unwrap();
1685        }
1686        self.prepare_expr(right, sql);
1687        if right_paren {
1688            sql.write_str(")").unwrap();
1689        }
1690    }
1691
1692    fn write_string_quoted(&self, string: &str, buffer: &mut impl Write) {
1693        buffer.write_str("'").unwrap();
1694        self.write_escaped(buffer, string);
1695        buffer.write_str("'").unwrap();
1696    }
1697
1698    #[doc(hidden)]
1699    /// Write bytes enclosed with engine specific byte syntax
1700    fn write_bytes(&self, bytes: &[u8], buffer: &mut impl Write) {
1701        buffer.write_str("x'").unwrap();
1702        for b in bytes {
1703            write!(buffer, "{b:02X}").unwrap()
1704        }
1705        buffer.write_str("'").unwrap();
1706    }
1707
1708    #[doc(hidden)]
1709    /// The name of the function that represents the "if null" condition.
1710    fn if_null_function(&self) -> &str {
1711        "IFNULL"
1712    }
1713
1714    #[doc(hidden)]
1715    /// The name of the function that represents the "greatest" function.
1716    fn greatest_function(&self) -> &str {
1717        "GREATEST"
1718    }
1719
1720    #[doc(hidden)]
1721    /// The name of the function that represents the "least" function.
1722    fn least_function(&self) -> &str {
1723        "LEAST"
1724    }
1725
1726    #[doc(hidden)]
1727    /// The name of the function that returns the char length.
1728    fn char_length_function(&self) -> &str {
1729        "CHAR_LENGTH"
1730    }
1731
1732    #[doc(hidden)]
1733    /// The name of the function that returns a random number
1734    fn random_function(&self) -> &str {
1735        // Returning it with parens as part of the name because the tuple preparer can't deal with empty lists
1736        "RANDOM"
1737    }
1738
1739    #[doc(hidden)]
1740    /// The name of the function that returns the lock phrase including the leading 'FOR'
1741    fn lock_phrase(&self, lock_type: LockType) -> &'static str {
1742        match lock_type {
1743            LockType::Update => "FOR UPDATE",
1744            LockType::NoKeyUpdate => "FOR NO KEY UPDATE",
1745            LockType::Share => "FOR SHARE",
1746            LockType::KeyShare => "FOR KEY SHARE",
1747        }
1748    }
1749
1750    /// The keywords for insert default row.
1751    fn insert_default_keyword(&self) -> &str {
1752        "(DEFAULT)"
1753    }
1754
1755    /// Write insert default rows expression.
1756    fn insert_default_values(&self, num_rows: u32, sql: &mut impl SqlWriter) {
1757        sql.write_str("VALUES ").unwrap();
1758        if num_rows > 0 {
1759            sql.write_str(self.insert_default_keyword()).unwrap();
1760
1761            for _ in 1..num_rows {
1762                sql.write_str(", ").unwrap();
1763                sql.write_str(self.insert_default_keyword()).unwrap();
1764            }
1765        }
1766    }
1767
1768    /// Write TRUE constant
1769    fn prepare_constant_true(&self, sql: &mut impl SqlWriter) {
1770        self.prepare_constant(&true.into(), sql);
1771    }
1772
1773    /// Write FALSE constant
1774    fn prepare_constant_false(&self, sql: &mut impl SqlWriter) {
1775        self.prepare_constant(&false.into(), sql);
1776    }
1777}
1778
1779impl SubQueryStatement {
1780    pub(crate) fn prepare_statement(
1781        &self,
1782        query_builder: &impl QueryBuilder,
1783        sql: &mut impl SqlWriter,
1784    ) {
1785        use SubQueryStatement::*;
1786        match self {
1787            SelectStatement(stmt) => query_builder.prepare_select_statement(stmt, sql),
1788            InsertStatement(stmt) => query_builder.prepare_insert_statement(stmt, sql),
1789            UpdateStatement(stmt) => query_builder.prepare_update_statement(stmt, sql),
1790            DeleteStatement(stmt) => query_builder.prepare_delete_statement(stmt, sql),
1791            WithStatement(stmt) => query_builder.prepare_with_query(stmt, sql),
1792        }
1793    }
1794}
1795
1796pub(crate) struct CommonSqlQueryBuilder;
1797
1798impl OperLeftAssocDecider for CommonSqlQueryBuilder {
1799    fn well_known_left_associative(&self, op: &BinOper) -> bool {
1800        common_well_known_left_associative(op)
1801    }
1802}
1803
1804impl PrecedenceDecider for CommonSqlQueryBuilder {
1805    fn inner_expr_well_known_greater_precedence(&self, inner: &Expr, outer_oper: &Oper) -> bool {
1806        common_inner_expr_well_known_greater_precedence(inner, outer_oper)
1807    }
1808}
1809
1810impl QueryBuilder for CommonSqlQueryBuilder {
1811    fn prepare_query_statement(&self, query: &SubQueryStatement, sql: &mut impl SqlWriter) {
1812        query.prepare_statement(self, sql);
1813    }
1814
1815    fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter) {
1816        sql.push_param(value, self as _);
1817    }
1818}
1819
1820impl QuotedBuilder for CommonSqlQueryBuilder {
1821    fn quote(&self) -> Quote {
1822        QUOTE
1823    }
1824}
1825
1826impl EscapeBuilder for CommonSqlQueryBuilder {}
1827
1828impl TableRefBuilder for CommonSqlQueryBuilder {}
1829
1830#[cfg_attr(
1831    feature = "option-more-parentheses",
1832    allow(unreachable_code, unused_variables)
1833)]
1834pub(crate) fn common_inner_expr_well_known_greater_precedence(
1835    inner: &Expr,
1836    outer_oper: &Oper,
1837) -> bool {
1838    match inner {
1839        // We only consider the case where an inner expression is contained in either a
1840        // unary or binary expression (with an outer_oper).
1841        // We do not need to wrap with parentheses:
1842        // Columns, tuples (already wrapped), constants, function calls, values,
1843        // keywords, subqueries (already wrapped), case (already wrapped)
1844        Expr::Column(_)
1845        | Expr::Tuple(_)
1846        | Expr::Constant(_)
1847        | Expr::FunctionCall(_)
1848        | Expr::Value(_)
1849        | Expr::Keyword(_)
1850        | Expr::Case(_)
1851        | Expr::SubQuery(_, _)
1852        | Expr::TypeName(_) => true,
1853        Expr::Binary(_, inner_oper, _) => {
1854            #[cfg(feature = "option-more-parentheses")]
1855            {
1856                return false;
1857            }
1858            let inner_oper: Oper = (*inner_oper).into();
1859            if inner_oper.is_arithmetic() || inner_oper.is_shift() {
1860                outer_oper.is_comparison()
1861                    || outer_oper.is_between()
1862                    || outer_oper.is_in()
1863                    || outer_oper.is_like()
1864                    || outer_oper.is_logical()
1865            } else if inner_oper.is_comparison()
1866                || inner_oper.is_in()
1867                || inner_oper.is_like()
1868                || inner_oper.is_is()
1869            {
1870                outer_oper.is_logical()
1871            } else {
1872                false
1873            }
1874        }
1875        _ => false,
1876    }
1877}
1878
1879pub(crate) fn common_well_known_left_associative(op: &BinOper) -> bool {
1880    matches!(
1881        op,
1882        BinOper::And | BinOper::Or | BinOper::Add | BinOper::Sub | BinOper::Mul | BinOper::Mod
1883    )
1884}
1885
1886macro_rules! join_io {
1887    ($iter:ident, $item:ident $(, first $first:expr)?, join $join:expr, do $do:expr $(, last $last:expr)?) => {
1888        if let Some($item) = $iter.next() {
1889            $($first)?
1890            $do
1891
1892            for $item in $iter {
1893                $join
1894                $do
1895            }
1896
1897            $($last)?
1898        }
1899    };
1900}
1901
1902pub(crate) use join_io;
1903
1904#[cfg(test)]
1905mod tests {
1906    #[cfg(feature = "with-chrono")]
1907    use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Utc};
1908
1909    #[cfg(feature = "with-chrono")]
1910    use crate::{MysqlQueryBuilder, PostgresQueryBuilder, QueryBuilder, SqliteQueryBuilder};
1911
1912    /// [Postgresql reference](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-INPUT-TIMES)
1913    ///
1914    /// [Mysql reference](https://dev.mysql.com/doc/refman/8.4/en/fractional-seconds.html)
1915    ///
1916    /// [Sqlite reference](https://sqlite.org/lang_datefunc.html)
1917    #[test]
1918    #[cfg(feature = "with-chrono")]
1919    fn format_time_constant() {
1920        use crate::{MysqlQueryBuilder, PostgresQueryBuilder, QueryBuilder, SqliteQueryBuilder};
1921
1922        let time = NaiveTime::from_hms_micro_opt(1, 2, 3, 123456)
1923            .unwrap()
1924            .into();
1925
1926        let mut string = String::new();
1927        macro_rules! compare {
1928            ($a:ident, $b:literal) => {
1929                PostgresQueryBuilder.prepare_constant(&$a, &mut string);
1930                assert_eq!(string, $b);
1931
1932                string.clear();
1933
1934                MysqlQueryBuilder.prepare_constant(&$a, &mut string);
1935                assert_eq!(string, $b);
1936
1937                string.clear();
1938
1939                SqliteQueryBuilder.prepare_constant(&$a, &mut string);
1940                assert_eq!(string, $b);
1941
1942                string.clear();
1943            };
1944        }
1945
1946        compare!(time, "'01:02:03.123456'");
1947
1948        let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
1949        let t = NaiveTime::from_hms_micro_opt(12, 34, 56, 123456).unwrap();
1950
1951        let dt = NaiveDateTime::new(d, t);
1952
1953        let date_time = dt.into();
1954
1955        compare!(date_time, "'2015-06-03 12:34:56.123456'");
1956
1957        let date_time_utc = DateTime::<Utc>::from_naive_utc_and_offset(dt, Utc).into();
1958
1959        compare!(date_time_utc, "'2015-06-03 12:34:56.123456 +00:00'");
1960
1961        let date_time_tz = DateTime::<FixedOffset>::from_naive_utc_and_offset(
1962            dt,
1963            FixedOffset::east_opt(8 * 3600).unwrap(),
1964        )
1965        .into();
1966
1967        compare!(date_time_tz, "'2015-06-03 20:34:56.123456 +08:00'");
1968    }
1969}