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            #[cfg(feature = "postgres-range")]
1176            Value::Range(None) => buf.write_str("NULL")?,
1177            Value::Bool(Some(b)) => buf.write_str(if *b { "TRUE" } else { "FALSE" })?,
1178            Value::TinyInt(Some(v)) => {
1179                write_int(buf, *v);
1180            }
1181            Value::SmallInt(Some(v)) => {
1182                write_int(buf, *v);
1183            }
1184            Value::Int(Some(v)) => {
1185                write_int(buf, *v);
1186            }
1187            Value::BigInt(Some(v)) => {
1188                write_int(buf, *v);
1189            }
1190            Value::TinyUnsigned(Some(v)) => {
1191                write_int(buf, *v);
1192            }
1193            Value::SmallUnsigned(Some(v)) => {
1194                write_int(buf, *v);
1195            }
1196            Value::Unsigned(Some(v)) => {
1197                write_int(buf, *v);
1198            }
1199            Value::BigUnsigned(Some(v)) => {
1200                write_int(buf, *v);
1201            }
1202            Value::Float(Some(v)) => write!(buf, "{v}")?,
1203            Value::Double(Some(v)) => write!(buf, "{v}")?,
1204            Value::String(Some(v)) => self.write_string_quoted(v, buf),
1205            Value::Char(Some(v)) => {
1206                self.write_string_quoted(std::str::from_utf8(&[*v as u8]).unwrap(), buf)
1207            }
1208            Value::Bytes(Some(v)) => self.write_bytes(v, buf),
1209            #[cfg(feature = "with-json")]
1210            Value::Json(Some(v)) => self.write_string_quoted(&v.to_string(), buf),
1211            #[cfg(feature = "with-chrono")]
1212            Value::ChronoDate(Some(v)) => {
1213                buf.write_str("'")?;
1214                write!(buf, "{}", v.format("%Y-%m-%d"))?;
1215                buf.write_str("'")?;
1216            }
1217            #[cfg(feature = "with-chrono")]
1218            Value::ChronoTime(Some(v)) => {
1219                buf.write_str("'")?;
1220                write!(buf, "{}", v.format("%H:%M:%S%.6f"))?;
1221                buf.write_str("'")?;
1222            }
1223            #[cfg(feature = "with-chrono")]
1224            Value::ChronoDateTime(Some(v)) => {
1225                buf.write_str("'")?;
1226                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f"))?;
1227                buf.write_str("'")?;
1228            }
1229            #[cfg(feature = "with-chrono")]
1230            Value::ChronoDateTimeUtc(Some(v)) => {
1231                buf.write_str("'")?;
1232                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1233                buf.write_str("'")?;
1234            }
1235            #[cfg(feature = "with-chrono")]
1236            Value::ChronoDateTimeLocal(Some(v)) => {
1237                buf.write_str("'")?;
1238                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1239                buf.write_str("'")?;
1240            }
1241            #[cfg(feature = "with-chrono")]
1242            Value::ChronoDateTimeWithTimeZone(Some(v)) => {
1243                buf.write_str("'")?;
1244                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1245                buf.write_str("'")?;
1246            }
1247            #[cfg(feature = "with-time")]
1248            Value::TimeDate(Some(v)) => {
1249                buf.write_str("'")?;
1250                buf.write_str(&v.format(time_format::FORMAT_DATE).unwrap())?;
1251                buf.write_str("'")?;
1252            }
1253            #[cfg(feature = "with-time")]
1254            Value::TimeTime(Some(v)) => {
1255                buf.write_str("'")?;
1256                buf.write_str(&v.format(time_format::FORMAT_TIME).unwrap())?;
1257                buf.write_str("'")?;
1258            }
1259            #[cfg(feature = "with-time")]
1260            Value::TimeDateTime(Some(v)) => {
1261                buf.write_str("'")?;
1262                buf.write_str(&v.format(time_format::FORMAT_DATETIME).unwrap())?;
1263                buf.write_str("'")?;
1264            }
1265            #[cfg(feature = "with-time")]
1266            Value::TimeDateTimeWithTimeZone(Some(v)) => {
1267                buf.write_str("'")?;
1268                buf.write_str(&v.format(time_format::FORMAT_DATETIME_TZ).unwrap())?;
1269                buf.write_str("'")?;
1270            }
1271            // Jiff date and time dosen't need format string
1272            // The default behavior is what we want
1273            #[cfg(feature = "with-jiff")]
1274            Value::JiffDate(Some(v)) => {
1275                buf.write_str("'")?;
1276                write!(buf, "{v}")?;
1277                buf.write_str("'")?;
1278            }
1279            #[cfg(feature = "with-jiff")]
1280            Value::JiffTime(Some(v)) => {
1281                buf.write_str("'")?;
1282                write!(buf, "{v}")?;
1283                buf.write_str("'")?;
1284            }
1285            // Both JiffDateTime and JiffTimestamp map to timestamp
1286            #[cfg(feature = "with-jiff")]
1287            Value::JiffDateTime(Some(v)) => {
1288                use crate::with_jiff::JIFF_DATE_TIME_FMT_STR;
1289                buf.write_str("'")?;
1290                write!(buf, "{}", v.strftime(JIFF_DATE_TIME_FMT_STR))?;
1291                buf.write_str("'")?;
1292            }
1293            #[cfg(feature = "with-jiff")]
1294            Value::JiffTimestamp(Some(v)) => {
1295                use crate::with_jiff::JIFF_TIMESTAMP_FMT_STR;
1296                buf.write_str("'")?;
1297                write!(buf, "{}", v.strftime(JIFF_TIMESTAMP_FMT_STR))?;
1298                buf.write_str("'")?;
1299            }
1300            #[cfg(feature = "with-jiff")]
1301            // Zoned map to timestamp with timezone
1302            Value::JiffZoned(Some(v)) => {
1303                use crate::with_jiff::JIFF_ZONE_FMT_STR;
1304                buf.write_str("'")?;
1305                write!(buf, "{}", v.strftime(JIFF_ZONE_FMT_STR))?;
1306                buf.write_str("'")?;
1307            }
1308            #[cfg(feature = "with-rust_decimal")]
1309            Value::Decimal(Some(v)) => write!(buf, "{v}")?,
1310            #[cfg(feature = "with-bigdecimal")]
1311            Value::BigDecimal(Some(v)) => write!(buf, "{v}")?,
1312            #[cfg(feature = "with-uuid")]
1313            Value::Uuid(Some(v)) => {
1314                buf.write_str("'")?;
1315                write!(buf, "{v}")?;
1316                buf.write_str("'")?;
1317            }
1318            #[cfg(feature = "postgres-array")]
1319            Value::Array(_, Some(v)) => {
1320                if v.is_empty() {
1321                    buf.write_str("'{}'")?;
1322                } else {
1323                    buf.write_str("ARRAY [")?;
1324
1325                    let mut viter = v.iter();
1326
1327                    if let Some(element) = viter.next() {
1328                        self.write_value(buf, element)?;
1329                    }
1330
1331                    for element in viter {
1332                        buf.write_str(",")?;
1333                        self.write_value(buf, element)?;
1334                    }
1335                    buf.write_str("]")?;
1336                }
1337            }
1338            #[cfg(feature = "postgres-vector")]
1339            Value::Vector(Some(v)) => {
1340                buf.write_str("'[")?;
1341                let mut viter = v.as_slice().iter();
1342
1343                if let Some(element) = viter.next() {
1344                    write!(buf, "{element}")?;
1345                }
1346
1347                for element in viter {
1348                    buf.write_str(",")?;
1349                    write!(buf, "{element}")?;
1350                }
1351                buf.write_str("]'")?;
1352            }
1353            #[cfg(feature = "with-ipnetwork")]
1354            Value::IpNetwork(Some(v)) => {
1355                buf.write_str("'")?;
1356                write!(buf, "{v}")?;
1357                buf.write_str("'")?;
1358            }
1359            #[cfg(feature = "with-mac_address")]
1360            Value::MacAddress(Some(v)) => {
1361                buf.write_str("'")?;
1362                write!(buf, "{v}")?;
1363                buf.write_str("'")?;
1364            }
1365            #[cfg(feature = "postgres-range")]
1366            Value::Range(Some(v)) => {
1367                buf.write_str("'")?;
1368                write!(buf, "{v}")?;
1369                buf.write_str("'")?;
1370            }
1371        };
1372
1373        Ok(())
1374    }
1375
1376    #[doc(hidden)]
1377    /// Write ON CONFLICT expression
1378    fn prepare_on_conflict(&self, on_conflict: &Option<OnConflict>, sql: &mut impl SqlWriter) {
1379        if let Some(on_conflict) = on_conflict {
1380            self.prepare_on_conflict_keywords(sql);
1381            self.prepare_on_conflict_target(&on_conflict.targets, sql);
1382            self.prepare_on_conflict_condition(&on_conflict.target_where, sql);
1383            self.prepare_on_conflict_action(&on_conflict.action, sql);
1384            self.prepare_on_conflict_condition(&on_conflict.action_where, sql);
1385        }
1386    }
1387
1388    #[doc(hidden)]
1389    /// Write ON CONFLICT target
1390    fn prepare_on_conflict_target(
1391        &self,
1392        on_conflict_targets: &[OnConflictTarget],
1393        sql: &mut impl SqlWriter,
1394    ) {
1395        let mut targets = on_conflict_targets.iter();
1396        join_io!(
1397            targets,
1398            target,
1399            first {
1400                sql.write_str("(").unwrap();
1401            },
1402            join {
1403                sql.write_str(", ").unwrap();
1404            },
1405            do {
1406                match target {
1407                    OnConflictTarget::ConflictColumn(col) => {
1408                        self.prepare_iden(col, sql);
1409                    }
1410                    OnConflictTarget::ConflictExpr(expr) => {
1411                        self.prepare_expr(expr, sql);
1412                    }
1413                }
1414            },
1415            last {
1416                sql.write_str(")").unwrap();
1417            }
1418        );
1419    }
1420
1421    #[doc(hidden)]
1422    /// Write ON CONFLICT action
1423    fn prepare_on_conflict_action(
1424        &self,
1425        on_conflict_action: &Option<OnConflictAction>,
1426        sql: &mut impl SqlWriter,
1427    ) {
1428        self.prepare_on_conflict_action_common(on_conflict_action, sql);
1429    }
1430
1431    fn prepare_on_conflict_action_common(
1432        &self,
1433        on_conflict_action: &Option<OnConflictAction>,
1434        sql: &mut impl SqlWriter,
1435    ) {
1436        if let Some(action) = on_conflict_action {
1437            match action {
1438                OnConflictAction::DoNothing(_) => {
1439                    sql.write_str(" DO NOTHING").unwrap();
1440                }
1441                OnConflictAction::Update(update_strats) => {
1442                    self.prepare_on_conflict_do_update_keywords(sql);
1443                    let mut update_strats_iter = update_strats.iter();
1444                    join_io!(
1445                        update_strats_iter,
1446                        update_strat,
1447                        join {
1448                            sql.write_str(", ").unwrap();
1449                        },
1450                        do {
1451                            match update_strat {
1452                                OnConflictUpdate::Column(col) => {
1453                                    self.prepare_iden(col, sql);
1454                                    sql.write_str(" = ").unwrap();
1455                                    self.prepare_on_conflict_excluded_table(col, sql);
1456                                }
1457                                OnConflictUpdate::Expr(col, expr) => {
1458                                    self.prepare_iden(col, sql);
1459                                    sql.write_str(" = ").unwrap();
1460                                    self.prepare_expr(expr, sql);
1461                                }
1462                            }
1463                        }
1464                    );
1465                }
1466            }
1467        }
1468    }
1469
1470    #[doc(hidden)]
1471    /// Write ON CONFLICT keywords
1472    fn prepare_on_conflict_keywords(&self, sql: &mut impl SqlWriter) {
1473        sql.write_str(" ON CONFLICT ").unwrap();
1474    }
1475
1476    #[doc(hidden)]
1477    /// Write ON CONFLICT keywords
1478    fn prepare_on_conflict_do_update_keywords(&self, sql: &mut impl SqlWriter) {
1479        sql.write_str(" DO UPDATE SET ").unwrap();
1480    }
1481
1482    #[doc(hidden)]
1483    /// Write ON CONFLICT update action by retrieving value from the excluded table
1484    fn prepare_on_conflict_excluded_table(&self, col: &DynIden, sql: &mut impl SqlWriter) {
1485        sql.write_char(self.quote().left()).unwrap();
1486        sql.write_str("excluded").unwrap();
1487        sql.write_char(self.quote().right()).unwrap();
1488        sql.write_str(".").unwrap();
1489        self.prepare_iden(col, sql);
1490    }
1491
1492    #[doc(hidden)]
1493    /// Write ON CONFLICT conditions
1494    fn prepare_on_conflict_condition(
1495        &self,
1496        on_conflict_condition: &ConditionHolder,
1497        sql: &mut impl SqlWriter,
1498    ) {
1499        self.prepare_condition(on_conflict_condition, "WHERE", sql)
1500    }
1501
1502    #[doc(hidden)]
1503    /// Hook to insert "OUTPUT" expressions.
1504    fn prepare_output(&self, _returning: &Option<ReturningClause>, _sql: &mut impl SqlWriter) {}
1505
1506    #[doc(hidden)]
1507    /// Hook to insert "RETURNING" statements.
1508    fn prepare_returning(&self, returning: &Option<ReturningClause>, sql: &mut impl SqlWriter) {
1509        if let Some(returning) = returning {
1510            sql.write_str(" RETURNING ").unwrap();
1511            match &returning {
1512                ReturningClause::All => sql.write_str("*").unwrap(),
1513                ReturningClause::Columns(cols) => {
1514                    let mut cols_iter = cols.iter();
1515                    join_io!(
1516                        cols_iter,
1517                        column_ref,
1518                        join {
1519                            sql.write_str(", ").unwrap();
1520                        },
1521                        do {
1522                            self.prepare_column_ref(column_ref, sql);
1523                        }
1524                    );
1525                }
1526                ReturningClause::Exprs(exprs) => {
1527                    let mut exprs_iter = exprs.iter();
1528                    join_io!(
1529                        exprs_iter,
1530                        expr,
1531                        join {
1532                            sql.write_str(", ").unwrap();
1533                        },
1534                        do {
1535                            self.prepare_expr(expr, sql);
1536                        }
1537                    );
1538                }
1539            }
1540        }
1541    }
1542
1543    #[doc(hidden)]
1544    /// Translate a condition to a "WHERE" clause.
1545    fn prepare_condition(
1546        &self,
1547        condition: &ConditionHolder,
1548        keyword: &str,
1549        sql: &mut impl SqlWriter,
1550    ) {
1551        match &condition.contents {
1552            ConditionHolderContents::Empty => (),
1553            ConditionHolderContents::Chain(conditions) => {
1554                sql.write_str(" ").unwrap();
1555                sql.write_str(keyword).unwrap();
1556                sql.write_str(" ").unwrap();
1557                for (i, log_chain_oper) in conditions.iter().enumerate() {
1558                    self.prepare_logical_chain_oper(log_chain_oper, i, conditions.len(), sql);
1559                }
1560            }
1561            ConditionHolderContents::Condition(c) => {
1562                sql.write_str(" ").unwrap();
1563                sql.write_str(keyword).unwrap();
1564                sql.write_str(" ").unwrap();
1565                self.prepare_condition_where(c, sql);
1566            }
1567        }
1568    }
1569
1570    #[doc(hidden)]
1571    /// Translate part of a condition to part of a "WHERE" clause.
1572    fn prepare_condition_where(&self, condition: &Condition, sql: &mut impl SqlWriter) {
1573        let simple_expr = condition.clone().into();
1574        self.prepare_expr(&simple_expr, sql);
1575    }
1576
1577    #[doc(hidden)]
1578    /// Translate [`Frame`] into SQL statement.
1579    fn prepare_frame(&self, frame: &Frame, sql: &mut impl SqlWriter) {
1580        match *frame {
1581            Frame::UnboundedPreceding => sql.write_str("UNBOUNDED PRECEDING").unwrap(),
1582            Frame::Preceding(v) => {
1583                self.prepare_value(v.into(), sql);
1584                sql.write_str("PRECEDING").unwrap();
1585            }
1586            Frame::CurrentRow => sql.write_str("CURRENT ROW").unwrap(),
1587            Frame::Following(v) => {
1588                self.prepare_value(v.into(), sql);
1589                sql.write_str("FOLLOWING").unwrap();
1590            }
1591            Frame::UnboundedFollowing => sql.write_str("UNBOUNDED FOLLOWING").unwrap(),
1592        }
1593    }
1594
1595    #[doc(hidden)]
1596    /// Translate [`WindowStatement`] into SQL statement.
1597    fn prepare_window_statement(&self, window: &WindowStatement, sql: &mut impl SqlWriter) {
1598        let mut partition_iter = window.partition_by.iter();
1599        join_io!(
1600            partition_iter,
1601            expr,
1602            first {
1603                sql.write_str("PARTITION BY ").unwrap();
1604            },
1605            join {
1606                sql.write_str(", ").unwrap();
1607            },
1608            do {
1609                self.prepare_expr(expr, sql);
1610            }
1611        );
1612
1613        let mut order_iter = window.order_by.iter();
1614        join_io!(
1615            order_iter,
1616            expr,
1617            first {
1618                sql.write_str(" ORDER BY ").unwrap();
1619            },
1620            join {
1621                sql.write_str(", ").unwrap();
1622            },
1623            do {
1624                self.prepare_order_expr(expr, sql);
1625            }
1626        );
1627
1628        if let Some(frame) = &window.frame {
1629            match frame.r#type {
1630                FrameType::Range => sql.write_str(" RANGE ").unwrap(),
1631                FrameType::Rows => sql.write_str(" ROWS ").unwrap(),
1632            };
1633            if let Some(end) = &frame.end {
1634                sql.write_str("BETWEEN ").unwrap();
1635                self.prepare_frame(&frame.start, sql);
1636                sql.write_str(" AND ").unwrap();
1637                self.prepare_frame(end, sql);
1638            } else {
1639                self.prepare_frame(&frame.start, sql);
1640            }
1641        }
1642    }
1643
1644    #[doc(hidden)]
1645    /// Translate a binary expr to SQL.
1646    fn binary_expr(&self, left: &Expr, op: &BinOper, right: &Expr, sql: &mut impl SqlWriter) {
1647        // If left has higher precedence than op, we can drop parentheses around left
1648        let drop_left_higher_precedence =
1649            self.inner_expr_well_known_greater_precedence(left, &(*op).into());
1650
1651        // Figure out if left associativity rules allow us to drop the left parenthesis
1652        let drop_left_assoc = left.is_binary()
1653            && op == left.get_bin_oper().unwrap()
1654            && self.well_known_left_associative(op);
1655
1656        let left_paren = !drop_left_higher_precedence && !drop_left_assoc;
1657        if left_paren {
1658            sql.write_str("(").unwrap();
1659        }
1660        self.prepare_expr(left, sql);
1661        if left_paren {
1662            sql.write_str(")").unwrap();
1663        }
1664
1665        sql.write_str(" ").unwrap();
1666        self.prepare_bin_oper(op, sql);
1667        sql.write_str(" ").unwrap();
1668
1669        // If right has higher precedence than op, we can drop parentheses around right
1670        let drop_right_higher_precedence =
1671            self.inner_expr_well_known_greater_precedence(right, &(*op).into());
1672
1673        let op_as_oper = Oper::BinOper(*op);
1674        // Due to representation of trinary op between as nested binary ops.
1675        let drop_right_between_hack = op_as_oper.is_between()
1676            && right.is_binary()
1677            && matches!(right.get_bin_oper(), Some(&BinOper::And));
1678
1679        // Due to representation of trinary op like/not like with optional arg escape as nested binary ops.
1680        let drop_right_escape_hack = op_as_oper.is_like()
1681            && right.is_binary()
1682            && matches!(right.get_bin_oper(), Some(&BinOper::Escape));
1683
1684        // Due to custom representation of casting AS datatype
1685        let drop_right_as_hack = (op == &BinOper::As) && matches!(right, Expr::Custom(_));
1686
1687        let right_paren = !drop_right_higher_precedence
1688            && !drop_right_escape_hack
1689            && !drop_right_between_hack
1690            && !drop_right_as_hack;
1691        if right_paren {
1692            sql.write_str("(").unwrap();
1693        }
1694        self.prepare_expr(right, sql);
1695        if right_paren {
1696            sql.write_str(")").unwrap();
1697        }
1698    }
1699
1700    fn write_string_quoted(&self, string: &str, buffer: &mut impl Write) {
1701        buffer.write_str("'").unwrap();
1702        self.write_escaped(buffer, string);
1703        buffer.write_str("'").unwrap();
1704    }
1705
1706    #[doc(hidden)]
1707    /// Write bytes enclosed with engine specific byte syntax
1708    fn write_bytes(&self, bytes: &[u8], buffer: &mut impl Write) {
1709        buffer.write_str("x'").unwrap();
1710        for b in bytes {
1711            write!(buffer, "{b:02X}").unwrap()
1712        }
1713        buffer.write_str("'").unwrap();
1714    }
1715
1716    #[doc(hidden)]
1717    /// The name of the function that represents the "if null" condition.
1718    fn if_null_function(&self) -> &str {
1719        "IFNULL"
1720    }
1721
1722    #[doc(hidden)]
1723    /// The name of the function that represents the "greatest" function.
1724    fn greatest_function(&self) -> &str {
1725        "GREATEST"
1726    }
1727
1728    #[doc(hidden)]
1729    /// The name of the function that represents the "least" function.
1730    fn least_function(&self) -> &str {
1731        "LEAST"
1732    }
1733
1734    #[doc(hidden)]
1735    /// The name of the function that returns the char length.
1736    fn char_length_function(&self) -> &str {
1737        "CHAR_LENGTH"
1738    }
1739
1740    #[doc(hidden)]
1741    /// The name of the function that returns a random number
1742    fn random_function(&self) -> &str {
1743        // Returning it with parens as part of the name because the tuple preparer can't deal with empty lists
1744        "RANDOM"
1745    }
1746
1747    #[doc(hidden)]
1748    /// The name of the function that returns the lock phrase including the leading 'FOR'
1749    fn lock_phrase(&self, lock_type: LockType) -> &'static str {
1750        match lock_type {
1751            LockType::Update => "FOR UPDATE",
1752            LockType::NoKeyUpdate => "FOR NO KEY UPDATE",
1753            LockType::Share => "FOR SHARE",
1754            LockType::KeyShare => "FOR KEY SHARE",
1755        }
1756    }
1757
1758    /// The keywords for insert default row.
1759    fn insert_default_keyword(&self) -> &str {
1760        "(DEFAULT)"
1761    }
1762
1763    /// Write insert default rows expression.
1764    fn insert_default_values(&self, num_rows: u32, sql: &mut impl SqlWriter) {
1765        sql.write_str("VALUES ").unwrap();
1766        if num_rows > 0 {
1767            sql.write_str(self.insert_default_keyword()).unwrap();
1768
1769            for _ in 1..num_rows {
1770                sql.write_str(", ").unwrap();
1771                sql.write_str(self.insert_default_keyword()).unwrap();
1772            }
1773        }
1774    }
1775
1776    /// Write TRUE constant
1777    fn prepare_constant_true(&self, sql: &mut impl SqlWriter) {
1778        self.prepare_constant(&true.into(), sql);
1779    }
1780
1781    /// Write FALSE constant
1782    fn prepare_constant_false(&self, sql: &mut impl SqlWriter) {
1783        self.prepare_constant(&false.into(), sql);
1784    }
1785}
1786
1787impl SubQueryStatement {
1788    pub(crate) fn prepare_statement(
1789        &self,
1790        query_builder: &impl QueryBuilder,
1791        sql: &mut impl SqlWriter,
1792    ) {
1793        use SubQueryStatement::*;
1794        match self {
1795            SelectStatement(stmt) => query_builder.prepare_select_statement(stmt, sql),
1796            InsertStatement(stmt) => query_builder.prepare_insert_statement(stmt, sql),
1797            UpdateStatement(stmt) => query_builder.prepare_update_statement(stmt, sql),
1798            DeleteStatement(stmt) => query_builder.prepare_delete_statement(stmt, sql),
1799            WithStatement(stmt) => query_builder.prepare_with_query(stmt, sql),
1800        }
1801    }
1802}
1803
1804pub(crate) struct CommonSqlQueryBuilder;
1805
1806impl OperLeftAssocDecider for CommonSqlQueryBuilder {
1807    fn well_known_left_associative(&self, op: &BinOper) -> bool {
1808        common_well_known_left_associative(op)
1809    }
1810}
1811
1812impl PrecedenceDecider for CommonSqlQueryBuilder {
1813    fn inner_expr_well_known_greater_precedence(&self, inner: &Expr, outer_oper: &Oper) -> bool {
1814        common_inner_expr_well_known_greater_precedence(inner, outer_oper)
1815    }
1816}
1817
1818impl QueryBuilder for CommonSqlQueryBuilder {
1819    fn prepare_query_statement(&self, query: &SubQueryStatement, sql: &mut impl SqlWriter) {
1820        query.prepare_statement(self, sql);
1821    }
1822
1823    fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter) {
1824        sql.push_param(value, self as _);
1825    }
1826}
1827
1828impl QuotedBuilder for CommonSqlQueryBuilder {
1829    fn quote(&self) -> Quote {
1830        QUOTE
1831    }
1832}
1833
1834impl EscapeBuilder for CommonSqlQueryBuilder {}
1835
1836impl TableRefBuilder for CommonSqlQueryBuilder {}
1837
1838#[cfg_attr(
1839    feature = "option-more-parentheses",
1840    allow(unreachable_code, unused_variables)
1841)]
1842pub(crate) fn common_inner_expr_well_known_greater_precedence(
1843    inner: &Expr,
1844    outer_oper: &Oper,
1845) -> bool {
1846    match inner {
1847        // We only consider the case where an inner expression is contained in either a
1848        // unary or binary expression (with an outer_oper).
1849        // We do not need to wrap with parentheses:
1850        // Columns, tuples (already wrapped), constants, function calls, values,
1851        // keywords, subqueries (already wrapped), case (already wrapped)
1852        Expr::Column(_)
1853        | Expr::Tuple(_)
1854        | Expr::Constant(_)
1855        | Expr::FunctionCall(_)
1856        | Expr::Value(_)
1857        | Expr::Keyword(_)
1858        | Expr::Case(_)
1859        | Expr::SubQuery(_, _)
1860        | Expr::TypeName(_) => true,
1861        Expr::Binary(_, inner_oper, _) => {
1862            #[cfg(feature = "option-more-parentheses")]
1863            {
1864                return false;
1865            }
1866            let inner_oper: Oper = (*inner_oper).into();
1867            if inner_oper.is_arithmetic() || inner_oper.is_shift() {
1868                outer_oper.is_comparison()
1869                    || outer_oper.is_between()
1870                    || outer_oper.is_in()
1871                    || outer_oper.is_like()
1872                    || outer_oper.is_logical()
1873            } else if inner_oper.is_comparison()
1874                || inner_oper.is_in()
1875                || inner_oper.is_like()
1876                || inner_oper.is_is()
1877            {
1878                outer_oper.is_logical()
1879            } else {
1880                false
1881            }
1882        }
1883        _ => false,
1884    }
1885}
1886
1887pub(crate) fn common_well_known_left_associative(op: &BinOper) -> bool {
1888    matches!(
1889        op,
1890        BinOper::And | BinOper::Or | BinOper::Add | BinOper::Sub | BinOper::Mul | BinOper::Mod
1891    )
1892}
1893
1894macro_rules! join_io {
1895    ($iter:ident, $item:ident $(, first $first:expr)?, join $join:expr, do $do:expr $(, last $last:expr)?) => {
1896        if let Some($item) = $iter.next() {
1897            $($first)?
1898            $do
1899
1900            for $item in $iter {
1901                $join
1902                $do
1903            }
1904
1905            $($last)?
1906        }
1907    };
1908}
1909
1910pub(crate) use join_io;
1911
1912#[cfg(test)]
1913mod tests {
1914    #[cfg(feature = "with-chrono")]
1915    use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Utc};
1916
1917    #[cfg(feature = "with-chrono")]
1918    use crate::QueryBuilder;
1919
1920    /// [Postgresql reference](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-INPUT-TIMES)
1921    ///
1922    /// [Mysql reference](https://dev.mysql.com/doc/refman/8.4/en/fractional-seconds.html)
1923    ///
1924    /// [Sqlite reference](https://sqlite.org/lang_datefunc.html)
1925    #[test]
1926    #[cfg(feature = "with-chrono")]
1927    fn format_time_constant() {
1928        use crate::{MysqlQueryBuilder, PostgresQueryBuilder, QueryBuilder, SqliteQueryBuilder};
1929
1930        let time = NaiveTime::from_hms_micro_opt(1, 2, 3, 123456)
1931            .unwrap()
1932            .into();
1933
1934        let mut string = String::new();
1935        macro_rules! compare {
1936            ($a:ident, $b:literal) => {
1937                PostgresQueryBuilder.prepare_constant(&$a, &mut string);
1938                assert_eq!(string, $b);
1939
1940                string.clear();
1941
1942                MysqlQueryBuilder.prepare_constant(&$a, &mut string);
1943                assert_eq!(string, $b);
1944
1945                string.clear();
1946
1947                SqliteQueryBuilder.prepare_constant(&$a, &mut string);
1948                assert_eq!(string, $b);
1949
1950                string.clear();
1951            };
1952        }
1953
1954        compare!(time, "'01:02:03.123456'");
1955
1956        let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
1957        let t = NaiveTime::from_hms_micro_opt(12, 34, 56, 123456).unwrap();
1958
1959        let dt = NaiveDateTime::new(d, t);
1960
1961        let date_time = dt.into();
1962
1963        compare!(date_time, "'2015-06-03 12:34:56.123456'");
1964
1965        let date_time_utc = DateTime::<Utc>::from_naive_utc_and_offset(dt, Utc).into();
1966
1967        compare!(date_time_utc, "'2015-06-03 12:34:56.123456 +00:00'");
1968
1969        let date_time_tz = DateTime::<FixedOffset>::from_naive_utc_and_offset(
1970            dt,
1971            FixedOffset::east_opt(8 * 3600).unwrap(),
1972        )
1973        .into();
1974
1975        compare!(date_time_tz, "'2015-06-03 20:34:56.123456 +08:00'");
1976    }
1977}