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`][crate::extension::mysql::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`][crate::extension::postgres::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        match &cte.query {
916            CteQuery::SubQuery(sub_query) => self.prepare_query_statement(sub_query, sql),
917            CteQuery::Values(items) => self.prepare_values_rows(items, sql),
918        }
919
920        sql.write_str(") ").unwrap();
921    }
922
923    fn prepare_with_query_clause_materialization(
924        &self,
925        cte: &CommonTableExpression,
926        sql: &mut impl SqlWriter,
927    ) {
928        if let Some(materialized) = cte.materialized {
929            if !materialized {
930                sql.write_str("NOT MATERIALIZED ")
931            } else {
932                sql.write_str(" MATERIALIZED ")
933            }
934            .unwrap()
935        }
936    }
937
938    fn prepare_with_clause_start(&self, with_clause: &WithClause, sql: &mut impl SqlWriter) {
939        sql.write_str("WITH ").unwrap();
940
941        if with_clause.recursive {
942            sql.write_str("RECURSIVE ").unwrap();
943        }
944    }
945
946    fn prepare_insert(&self, replace: bool, sql: &mut impl SqlWriter) {
947        if replace {
948            sql.write_str("REPLACE").unwrap();
949        } else {
950            sql.write_str("INSERT").unwrap();
951        }
952    }
953
954    fn prepare_function_name(&self, function: &Func, sql: &mut impl SqlWriter) {
955        self.prepare_function_name_common(function, sql)
956    }
957
958    /// Translate [`TypeRef`] into an SQL statement.
959    fn prepare_type_ref(&self, type_name: &TypeRef, sql: &mut impl SqlWriter) {
960        let TypeRef(schema_name, r#type) = type_name;
961        if let Some(schema_name) = schema_name {
962            self.prepare_schema_name(schema_name, sql);
963            write!(sql, ".").unwrap();
964        }
965        self.prepare_iden(r#type, sql);
966    }
967
968    /// Translate [`JoinType`] into SQL statement.
969    fn prepare_join_type(&self, join_type: &JoinType, sql: &mut impl SqlWriter) {
970        self.prepare_join_type_common(join_type, sql)
971    }
972
973    fn prepare_join_type_common(&self, join_type: &JoinType, sql: &mut impl SqlWriter) {
974        sql.write_str(match join_type {
975            JoinType::Join => "JOIN",
976            JoinType::CrossJoin => "CROSS JOIN",
977            JoinType::InnerJoin => "INNER JOIN",
978            JoinType::LeftJoin => "LEFT JOIN",
979            JoinType::RightJoin => "RIGHT JOIN",
980            JoinType::FullOuterJoin => "FULL OUTER JOIN",
981            JoinType::StraightJoin => "STRAIGHT_JOIN",
982        })
983        .unwrap()
984    }
985
986    /// Translate [`OrderExpr`] into SQL statement.
987    fn prepare_order_expr(&self, order_expr: &OrderExpr, sql: &mut impl SqlWriter) {
988        if !matches!(order_expr.order, Order::Field(_)) {
989            self.prepare_expr(&order_expr.expr, sql);
990        }
991        self.prepare_order(order_expr, sql);
992    }
993
994    /// Translate [`JoinOn`] into SQL statement.
995    fn prepare_join_on(&self, join_on: &JoinOn, sql: &mut impl SqlWriter) {
996        match join_on {
997            JoinOn::Condition(c) => self.prepare_condition(c, "ON", sql),
998            JoinOn::Columns(_c) => unimplemented!(),
999        }
1000    }
1001
1002    /// Translate [`Order`] into SQL statement.
1003    fn prepare_order(&self, order_expr: &OrderExpr, sql: &mut impl SqlWriter) {
1004        match &order_expr.order {
1005            Order::Asc => sql.write_str(" ASC").unwrap(),
1006            Order::Desc => sql.write_str(" DESC").unwrap(),
1007            Order::Field(values) => self.prepare_field_order(order_expr, values, sql),
1008        }
1009    }
1010
1011    /// Translate [`Order::Field`] into SQL statement
1012    fn prepare_field_order(
1013        &self,
1014        order_expr: &OrderExpr,
1015        values: &Values,
1016        sql: &mut impl SqlWriter,
1017    ) {
1018        sql.write_str("CASE ").unwrap();
1019        let mut i = 0;
1020        for value in &values.0 {
1021            sql.write_str("WHEN ").unwrap();
1022            self.prepare_expr(&order_expr.expr, sql);
1023            sql.write_str("=").unwrap();
1024            self.write_value(sql, value).unwrap();
1025            sql.write_str(" THEN ").unwrap();
1026            write_int(sql, i);
1027            sql.write_str(" ").unwrap();
1028            i += 1;
1029        }
1030
1031        sql.write_str("ELSE ").unwrap();
1032        write_int(sql, i);
1033        sql.write_str(" END").unwrap();
1034    }
1035
1036    /// Write [`Value`] into SQL statement as parameter.
1037    fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter);
1038
1039    /// Write [`Value`] inline.
1040    fn prepare_constant(&self, value: &Value, sql: &mut impl SqlWriter) {
1041        self.write_value(sql, value).unwrap();
1042    }
1043
1044    /// Translate a `&[ValueTuple]` into a VALUES list.
1045    fn prepare_values_list(&self, value_tuples: &[ValueTuple], sql: &mut impl SqlWriter) {
1046        sql.write_str("VALUES ").unwrap();
1047        let mut tuples = value_tuples.iter();
1048        join_io!(
1049            tuples,
1050            value_tuple,
1051            join {
1052                sql.write_str(", ").unwrap();
1053            },
1054            do {
1055                sql.write_str(self.values_list_tuple_prefix()).unwrap();
1056                sql.write_str("(").unwrap();
1057
1058                let mut values = value_tuple.clone().into_iter();
1059                join_io!(
1060                    values,
1061                    value,
1062                    join {
1063                        sql.write_str(", ").unwrap();
1064                    },
1065                    do {
1066                        self.prepare_value(value, sql);
1067                    }
1068                );
1069
1070                sql.write_str(")").unwrap();
1071            }
1072        );
1073    }
1074
1075    fn prepare_values_rows(&self, values: &[Values], sql: &mut impl SqlWriter) {
1076        sql.write_str("VALUES ").unwrap();
1077        let mut rows = values.iter();
1078        join_io!(
1079            rows,
1080            row,
1081            join {
1082                sql.write_str(", ").unwrap();
1083            },
1084            do {
1085                sql.write_str("(").unwrap();
1086
1087                let mut vals = row.clone().into_iter();
1088                join_io!(
1089                    vals,
1090                    val,
1091                    join {
1092                        sql.write_str(", ").unwrap();
1093                    },
1094                    do {
1095                        self.prepare_value(val, sql);
1096                    }
1097                );
1098
1099                sql.write_str(")").unwrap();
1100            }
1101        );
1102    }
1103
1104    /// Translate [`Expr::Tuple`] into SQL statement.
1105    fn prepare_tuple(&self, exprs: &[Expr], sql: &mut impl SqlWriter) {
1106        sql.write_str("(").unwrap();
1107        for (i, expr) in exprs.iter().enumerate() {
1108            if i != 0 {
1109                sql.write_str(", ").unwrap();
1110            }
1111            self.prepare_expr(expr, sql);
1112        }
1113        sql.write_str(")").unwrap();
1114    }
1115
1116    /// Translate [`Keyword`] into SQL statement.
1117    fn prepare_keyword(&self, keyword: &Keyword, sql: &mut impl SqlWriter) {
1118        match keyword {
1119            Keyword::Null => sql.write_str("NULL").unwrap(),
1120            Keyword::CurrentDate => sql.write_str("CURRENT_DATE").unwrap(),
1121            Keyword::CurrentTime => sql.write_str("CURRENT_TIME").unwrap(),
1122            Keyword::CurrentTimestamp => sql.write_str("CURRENT_TIMESTAMP").unwrap(),
1123            Keyword::Default => sql.write_str("DEFAULT").unwrap(),
1124            Keyword::Custom(iden) => sql.write_str(&iden.0).unwrap(),
1125        }
1126    }
1127
1128    /// Convert a SQL value into syntax-specific string
1129    fn value_to_string(&self, v: &Value) -> String {
1130        self.value_to_string_common(v)
1131    }
1132
1133    fn value_to_string_common(&self, v: &Value) -> String {
1134        let mut s = String::new();
1135        self.write_value(&mut s, v).unwrap();
1136        s
1137    }
1138
1139    #[doc(hidden)]
1140    fn write_value(&self, buf: &mut impl Write, value: &Value) -> fmt::Result {
1141        self.write_value_common(buf, value)
1142    }
1143
1144    #[doc(hidden)]
1145    fn write_value_common(&self, buf: &mut impl Write, value: &Value) -> fmt::Result {
1146        match value {
1147            Value::Bool(None)
1148            | Value::TinyInt(None)
1149            | Value::SmallInt(None)
1150            | Value::Int(None)
1151            | Value::BigInt(None)
1152            | Value::TinyUnsigned(None)
1153            | Value::SmallUnsigned(None)
1154            | Value::Unsigned(None)
1155            | Value::BigUnsigned(None)
1156            | Value::Float(None)
1157            | Value::Double(None)
1158            | Value::String(None)
1159            | Value::Char(None)
1160            | Value::Bytes(None) => buf.write_str("NULL")?,
1161            #[cfg(feature = "with-json")]
1162            Value::Json(None) => buf.write_str("NULL")?,
1163            #[cfg(feature = "with-chrono")]
1164            Value::ChronoDate(None) => buf.write_str("NULL")?,
1165            #[cfg(feature = "with-chrono")]
1166            Value::ChronoTime(None) => buf.write_str("NULL")?,
1167            #[cfg(feature = "with-chrono")]
1168            Value::ChronoDateTime(None) => buf.write_str("NULL")?,
1169            #[cfg(feature = "with-chrono")]
1170            Value::ChronoDateTimeUtc(None) => buf.write_str("NULL")?,
1171            #[cfg(feature = "with-chrono")]
1172            Value::ChronoDateTimeLocal(None) => buf.write_str("NULL")?,
1173            #[cfg(feature = "with-chrono")]
1174            Value::ChronoDateTimeWithTimeZone(None) => buf.write_str("NULL")?,
1175            #[cfg(feature = "with-time")]
1176            Value::TimeDate(None) => buf.write_str("NULL")?,
1177            #[cfg(feature = "with-time")]
1178            Value::TimeTime(None) => buf.write_str("NULL")?,
1179            #[cfg(feature = "with-time")]
1180            Value::TimeDateTime(None) => buf.write_str("NULL")?,
1181            #[cfg(feature = "with-time")]
1182            Value::TimeDateTimeWithTimeZone(None) => buf.write_str("NULL")?,
1183            #[cfg(feature = "with-jiff")]
1184            Value::JiffDate(None) => buf.write_str("NULL")?,
1185            #[cfg(feature = "with-jiff")]
1186            Value::JiffTime(None) => buf.write_str("NULL")?,
1187            #[cfg(feature = "with-jiff")]
1188            Value::JiffDateTime(None) => buf.write_str("NULL")?,
1189            #[cfg(feature = "with-jiff")]
1190            Value::JiffTimestamp(None) => buf.write_str("NULL")?,
1191            #[cfg(feature = "with-jiff")]
1192            Value::JiffZoned(None) => buf.write_str("NULL")?,
1193            #[cfg(feature = "with-rust_decimal")]
1194            Value::Decimal(None) => buf.write_str("NULL")?,
1195            #[cfg(feature = "with-bigdecimal")]
1196            Value::BigDecimal(None) => buf.write_str("NULL")?,
1197            #[cfg(feature = "with-uuid")]
1198            Value::Uuid(None) => buf.write_str("NULL")?,
1199            #[cfg(feature = "with-ipnetwork")]
1200            Value::IpNetwork(None) => buf.write_str("NULL")?,
1201            #[cfg(feature = "with-mac_address")]
1202            Value::MacAddress(None) => buf.write_str("NULL")?,
1203            #[cfg(feature = "postgres-array")]
1204            Value::Array(_, None) => buf.write_str("NULL")?,
1205            #[cfg(feature = "postgres-vector")]
1206            Value::Vector(None) => buf.write_str("NULL")?,
1207            #[cfg(feature = "postgres-range")]
1208            Value::Range(None) => buf.write_str("NULL")?,
1209            Value::Bool(Some(b)) => buf.write_str(if *b { "TRUE" } else { "FALSE" })?,
1210            Value::TinyInt(Some(v)) => {
1211                write_int(buf, *v);
1212            }
1213            Value::SmallInt(Some(v)) => {
1214                write_int(buf, *v);
1215            }
1216            Value::Int(Some(v)) => {
1217                write_int(buf, *v);
1218            }
1219            Value::BigInt(Some(v)) => {
1220                write_int(buf, *v);
1221            }
1222            Value::TinyUnsigned(Some(v)) => {
1223                write_int(buf, *v);
1224            }
1225            Value::SmallUnsigned(Some(v)) => {
1226                write_int(buf, *v);
1227            }
1228            Value::Unsigned(Some(v)) => {
1229                write_int(buf, *v);
1230            }
1231            Value::BigUnsigned(Some(v)) => {
1232                write_int(buf, *v);
1233            }
1234            Value::Float(Some(v)) => write!(buf, "{v}")?,
1235            Value::Double(Some(v)) => write!(buf, "{v}")?,
1236            Value::String(Some(v)) => self.write_string_quoted(v, buf),
1237            Value::Char(Some(v)) => {
1238                self.write_string_quoted(std::str::from_utf8(&[*v as u8]).unwrap(), buf)
1239            }
1240            Value::Bytes(Some(v)) => self.write_bytes(v, buf),
1241            #[cfg(feature = "with-json")]
1242            Value::Json(Some(v)) => self.write_string_quoted(&v.to_string(), buf),
1243            #[cfg(feature = "with-chrono")]
1244            Value::ChronoDate(Some(v)) => {
1245                buf.write_str("'")?;
1246                write!(buf, "{}", v.format("%Y-%m-%d"))?;
1247                buf.write_str("'")?;
1248            }
1249            #[cfg(feature = "with-chrono")]
1250            Value::ChronoTime(Some(v)) => {
1251                buf.write_str("'")?;
1252                write!(buf, "{}", v.format("%H:%M:%S%.6f"))?;
1253                buf.write_str("'")?;
1254            }
1255            #[cfg(feature = "with-chrono")]
1256            Value::ChronoDateTime(Some(v)) => {
1257                buf.write_str("'")?;
1258                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f"))?;
1259                buf.write_str("'")?;
1260            }
1261            #[cfg(feature = "with-chrono")]
1262            Value::ChronoDateTimeUtc(Some(v)) => {
1263                buf.write_str("'")?;
1264                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1265                buf.write_str("'")?;
1266            }
1267            #[cfg(feature = "with-chrono")]
1268            Value::ChronoDateTimeLocal(Some(v)) => {
1269                buf.write_str("'")?;
1270                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1271                buf.write_str("'")?;
1272            }
1273            #[cfg(feature = "with-chrono")]
1274            Value::ChronoDateTimeWithTimeZone(Some(v)) => {
1275                buf.write_str("'")?;
1276                write!(buf, "{}", v.format("%Y-%m-%d %H:%M:%S%.6f %:z"))?;
1277                buf.write_str("'")?;
1278            }
1279            #[cfg(feature = "with-time")]
1280            Value::TimeDate(Some(v)) => {
1281                buf.write_str("'")?;
1282                buf.write_str(&v.format(time_format::FORMAT_DATE).unwrap())?;
1283                buf.write_str("'")?;
1284            }
1285            #[cfg(feature = "with-time")]
1286            Value::TimeTime(Some(v)) => {
1287                buf.write_str("'")?;
1288                buf.write_str(&v.format(time_format::FORMAT_TIME).unwrap())?;
1289                buf.write_str("'")?;
1290            }
1291            #[cfg(feature = "with-time")]
1292            Value::TimeDateTime(Some(v)) => {
1293                buf.write_str("'")?;
1294                buf.write_str(&v.format(time_format::FORMAT_DATETIME).unwrap())?;
1295                buf.write_str("'")?;
1296            }
1297            #[cfg(feature = "with-time")]
1298            Value::TimeDateTimeWithTimeZone(Some(v)) => {
1299                buf.write_str("'")?;
1300                buf.write_str(&v.format(time_format::FORMAT_DATETIME_TZ).unwrap())?;
1301                buf.write_str("'")?;
1302            }
1303            // Jiff date and time dosen't need format string
1304            // The default behavior is what we want
1305            #[cfg(feature = "with-jiff")]
1306            Value::JiffDate(Some(v)) => {
1307                buf.write_str("'")?;
1308                write!(buf, "{v}")?;
1309                buf.write_str("'")?;
1310            }
1311            #[cfg(feature = "with-jiff")]
1312            Value::JiffTime(Some(v)) => {
1313                buf.write_str("'")?;
1314                write!(buf, "{v}")?;
1315                buf.write_str("'")?;
1316            }
1317            // Both JiffDateTime and JiffTimestamp map to timestamp
1318            #[cfg(feature = "with-jiff")]
1319            Value::JiffDateTime(Some(v)) => {
1320                use crate::with_jiff::JIFF_DATE_TIME_FMT_STR;
1321                buf.write_str("'")?;
1322                write!(buf, "{}", v.strftime(JIFF_DATE_TIME_FMT_STR))?;
1323                buf.write_str("'")?;
1324            }
1325            #[cfg(feature = "with-jiff")]
1326            Value::JiffTimestamp(Some(v)) => {
1327                use crate::with_jiff::JIFF_TIMESTAMP_FMT_STR;
1328                buf.write_str("'")?;
1329                write!(buf, "{}", v.strftime(JIFF_TIMESTAMP_FMT_STR))?;
1330                buf.write_str("'")?;
1331            }
1332            #[cfg(feature = "with-jiff")]
1333            // Zoned map to timestamp with timezone
1334            Value::JiffZoned(Some(v)) => {
1335                use crate::with_jiff::JIFF_ZONE_FMT_STR;
1336                buf.write_str("'")?;
1337                write!(buf, "{}", v.strftime(JIFF_ZONE_FMT_STR))?;
1338                buf.write_str("'")?;
1339            }
1340            #[cfg(feature = "with-rust_decimal")]
1341            Value::Decimal(Some(v)) => write!(buf, "{v}")?,
1342            #[cfg(feature = "with-bigdecimal")]
1343            Value::BigDecimal(Some(v)) => write!(buf, "{v}")?,
1344            #[cfg(feature = "with-uuid")]
1345            Value::Uuid(Some(v)) => {
1346                buf.write_str("'")?;
1347                write!(buf, "{v}")?;
1348                buf.write_str("'")?;
1349            }
1350            #[cfg(feature = "postgres-array")]
1351            Value::Array(_, Some(v)) => {
1352                if v.is_empty() {
1353                    buf.write_str("'{}'")?;
1354                } else {
1355                    buf.write_str("ARRAY [")?;
1356
1357                    let mut viter = v.iter();
1358
1359                    if let Some(element) = viter.next() {
1360                        self.write_value(buf, element)?;
1361                    }
1362
1363                    for element in viter {
1364                        buf.write_str(",")?;
1365                        self.write_value(buf, element)?;
1366                    }
1367                    buf.write_str("]")?;
1368                }
1369            }
1370            #[cfg(feature = "postgres-vector")]
1371            Value::Vector(Some(v)) => {
1372                buf.write_str("'[")?;
1373                let mut viter = v.as_slice().iter();
1374
1375                if let Some(element) = viter.next() {
1376                    write!(buf, "{element}")?;
1377                }
1378
1379                for element in viter {
1380                    buf.write_str(",")?;
1381                    write!(buf, "{element}")?;
1382                }
1383                buf.write_str("]'")?;
1384            }
1385            #[cfg(feature = "with-ipnetwork")]
1386            Value::IpNetwork(Some(v)) => {
1387                buf.write_str("'")?;
1388                write!(buf, "{v}")?;
1389                buf.write_str("'")?;
1390            }
1391            #[cfg(feature = "with-mac_address")]
1392            Value::MacAddress(Some(v)) => {
1393                buf.write_str("'")?;
1394                write!(buf, "{v}")?;
1395                buf.write_str("'")?;
1396            }
1397            #[cfg(feature = "postgres-range")]
1398            Value::Range(Some(v)) => {
1399                buf.write_str("'")?;
1400                write!(buf, "{v}")?;
1401                buf.write_str("'")?;
1402            }
1403        };
1404
1405        Ok(())
1406    }
1407
1408    #[doc(hidden)]
1409    /// Write ON CONFLICT expression
1410    fn prepare_on_conflict(&self, on_conflict: &Option<OnConflict>, sql: &mut impl SqlWriter) {
1411        if let Some(on_conflict) = on_conflict {
1412            self.prepare_on_conflict_keywords(sql);
1413            self.prepare_on_conflict_target(&on_conflict.targets, sql);
1414            self.prepare_on_conflict_condition(&on_conflict.target_where, sql);
1415            self.prepare_on_conflict_action(&on_conflict.action, sql);
1416            self.prepare_on_conflict_condition(&on_conflict.action_where, sql);
1417        }
1418    }
1419
1420    #[doc(hidden)]
1421    /// Write ON CONFLICT target
1422    fn prepare_on_conflict_target(
1423        &self,
1424        on_conflict_targets: &OnConflictTarget,
1425        sql: &mut impl SqlWriter,
1426    ) {
1427        match on_conflict_targets {
1428            OnConflictTarget::Identifiers(identifiers) => {
1429                self.prepare_on_conflict_target_identifiers(identifiers, sql)
1430            }
1431            OnConflictTarget::Constraint(constraint) => {
1432                self.prepare_on_conflict_target_constraint(constraint, sql)
1433            }
1434        }
1435    }
1436
1437    #[doc(hidden)]
1438    /// Write ON CONFLICT target
1439    fn prepare_on_conflict_target_identifiers(
1440        &self,
1441        identifiers: &[OnConflictIdentifier],
1442        sql: &mut impl SqlWriter,
1443    ) {
1444        let mut targets = identifiers.iter();
1445        join_io!(
1446            targets,
1447            target,
1448            first {
1449                sql.write_str("(").unwrap();
1450            },
1451            join {
1452                sql.write_str(", ").unwrap();
1453            },
1454            do {
1455                match target {
1456                    OnConflictIdentifier::Column(col) => {
1457                        self.prepare_iden(col, sql);
1458                    }
1459                    OnConflictIdentifier::Expr(expr) => {
1460                        self.prepare_expr(expr, sql);
1461                    }
1462                }
1463            },
1464            last {
1465                sql.write_str(")").unwrap();
1466            }
1467        );
1468    }
1469
1470    #[doc(hidden)]
1471    fn prepare_on_conflict_target_constraint(&self, constraint: &str, sql: &mut impl SqlWriter) {
1472        sql.write_fmt(format_args!("ON CONSTRAINT \"{}\"", constraint))
1473            .unwrap();
1474    }
1475
1476    #[doc(hidden)]
1477    /// Write ON CONFLICT action
1478    fn prepare_on_conflict_action(
1479        &self,
1480        on_conflict_action: &Option<OnConflictAction>,
1481        sql: &mut impl SqlWriter,
1482    ) {
1483        self.prepare_on_conflict_action_common(on_conflict_action, sql);
1484    }
1485
1486    fn prepare_on_conflict_action_common(
1487        &self,
1488        on_conflict_action: &Option<OnConflictAction>,
1489        sql: &mut impl SqlWriter,
1490    ) {
1491        if let Some(action) = on_conflict_action {
1492            match action {
1493                OnConflictAction::DoNothing(_) => {
1494                    sql.write_str(" DO NOTHING").unwrap();
1495                }
1496                OnConflictAction::Update(update_strats) => {
1497                    self.prepare_on_conflict_do_update_keywords(sql);
1498                    let mut update_strats_iter = update_strats.iter();
1499                    join_io!(
1500                        update_strats_iter,
1501                        update_strat,
1502                        join {
1503                            sql.write_str(", ").unwrap();
1504                        },
1505                        do {
1506                            match update_strat {
1507                                OnConflictUpdate::Column(col) => {
1508                                    self.prepare_iden(col, sql);
1509                                    sql.write_str(" = ").unwrap();
1510                                    self.prepare_on_conflict_excluded_table(col, sql);
1511                                }
1512                                OnConflictUpdate::Expr(col, expr) => {
1513                                    self.prepare_iden(col, sql);
1514                                    sql.write_str(" = ").unwrap();
1515                                    self.prepare_expr(expr, sql);
1516                                }
1517                            }
1518                        }
1519                    );
1520                }
1521            }
1522        }
1523    }
1524
1525    #[doc(hidden)]
1526    /// Write ON CONFLICT keywords
1527    fn prepare_on_conflict_keywords(&self, sql: &mut impl SqlWriter) {
1528        sql.write_str(" ON CONFLICT ").unwrap();
1529    }
1530
1531    #[doc(hidden)]
1532    /// Write ON CONFLICT keywords
1533    fn prepare_on_conflict_do_update_keywords(&self, sql: &mut impl SqlWriter) {
1534        sql.write_str(" DO UPDATE SET ").unwrap();
1535    }
1536
1537    #[doc(hidden)]
1538    /// Write ON CONFLICT update action by retrieving value from the excluded table
1539    fn prepare_on_conflict_excluded_table(&self, col: &DynIden, sql: &mut impl SqlWriter) {
1540        sql.write_char(self.quote().left()).unwrap();
1541        sql.write_str("excluded").unwrap();
1542        sql.write_char(self.quote().right()).unwrap();
1543        sql.write_str(".").unwrap();
1544        self.prepare_iden(col, sql);
1545    }
1546
1547    #[doc(hidden)]
1548    /// Write ON CONFLICT conditions
1549    fn prepare_on_conflict_condition(
1550        &self,
1551        on_conflict_condition: &ConditionHolder,
1552        sql: &mut impl SqlWriter,
1553    ) {
1554        self.prepare_condition(on_conflict_condition, "WHERE", sql)
1555    }
1556
1557    #[doc(hidden)]
1558    /// Hook to insert "OUTPUT" expressions.
1559    fn prepare_output(&self, _returning: &Option<ReturningClause>, _sql: &mut impl SqlWriter) {}
1560
1561    #[doc(hidden)]
1562    /// Hook to insert "RETURNING" statements.
1563    fn prepare_returning(&self, returning: &Option<ReturningClause>, sql: &mut impl SqlWriter) {
1564        if let Some(returning) = returning {
1565            sql.write_str(" RETURNING ").unwrap();
1566            match &returning {
1567                ReturningClause::All => sql.write_str("*").unwrap(),
1568                ReturningClause::Columns(cols) => {
1569                    let mut cols_iter = cols.iter();
1570                    join_io!(
1571                        cols_iter,
1572                        column_ref,
1573                        join {
1574                            sql.write_str(", ").unwrap();
1575                        },
1576                        do {
1577                            self.prepare_column_ref(column_ref, sql);
1578                        }
1579                    );
1580                }
1581                ReturningClause::Exprs(exprs) => {
1582                    let mut exprs_iter = exprs.iter();
1583                    join_io!(
1584                        exprs_iter,
1585                        expr,
1586                        join {
1587                            sql.write_str(", ").unwrap();
1588                        },
1589                        do {
1590                            self.prepare_expr(expr, sql);
1591                        }
1592                    );
1593                }
1594            }
1595        }
1596    }
1597
1598    #[doc(hidden)]
1599    /// Translate a condition to a "WHERE" clause.
1600    fn prepare_condition(
1601        &self,
1602        condition: &ConditionHolder,
1603        keyword: &str,
1604        sql: &mut impl SqlWriter,
1605    ) {
1606        match &condition.contents {
1607            ConditionHolderContents::Empty => (),
1608            ConditionHolderContents::Chain(conditions) => {
1609                sql.write_str(" ").unwrap();
1610                sql.write_str(keyword).unwrap();
1611                sql.write_str(" ").unwrap();
1612                for (i, log_chain_oper) in conditions.iter().enumerate() {
1613                    self.prepare_logical_chain_oper(log_chain_oper, i, conditions.len(), sql);
1614                }
1615            }
1616            ConditionHolderContents::Condition(c) => {
1617                sql.write_str(" ").unwrap();
1618                sql.write_str(keyword).unwrap();
1619                sql.write_str(" ").unwrap();
1620                self.prepare_condition_where(c, sql);
1621            }
1622        }
1623    }
1624
1625    #[doc(hidden)]
1626    /// Translate part of a condition to part of a "WHERE" clause.
1627    fn prepare_condition_where(&self, condition: &Condition, sql: &mut impl SqlWriter) {
1628        let simple_expr = condition.clone().into();
1629        self.prepare_expr(&simple_expr, sql);
1630    }
1631
1632    #[doc(hidden)]
1633    /// Translate [`Frame`] into SQL statement.
1634    fn prepare_frame(&self, frame: &Frame, sql: &mut impl SqlWriter) {
1635        match *frame {
1636            Frame::UnboundedPreceding => sql.write_str("UNBOUNDED PRECEDING").unwrap(),
1637            Frame::Preceding(v) => {
1638                self.prepare_value(v.into(), sql);
1639                sql.write_str("PRECEDING").unwrap();
1640            }
1641            Frame::CurrentRow => sql.write_str("CURRENT ROW").unwrap(),
1642            Frame::Following(v) => {
1643                self.prepare_value(v.into(), sql);
1644                sql.write_str("FOLLOWING").unwrap();
1645            }
1646            Frame::UnboundedFollowing => sql.write_str("UNBOUNDED FOLLOWING").unwrap(),
1647        }
1648    }
1649
1650    #[doc(hidden)]
1651    /// Translate [`WindowStatement`] into SQL statement.
1652    fn prepare_window_statement(&self, window: &WindowStatement, sql: &mut impl SqlWriter) {
1653        let mut partition_iter = window.partition_by.iter();
1654        join_io!(
1655            partition_iter,
1656            expr,
1657            first {
1658                sql.write_str("PARTITION BY ").unwrap();
1659            },
1660            join {
1661                sql.write_str(", ").unwrap();
1662            },
1663            do {
1664                self.prepare_expr(expr, sql);
1665            }
1666        );
1667
1668        let mut order_iter = window.order_by.iter();
1669        join_io!(
1670            order_iter,
1671            expr,
1672            first {
1673                sql.write_str(" ORDER BY ").unwrap();
1674            },
1675            join {
1676                sql.write_str(", ").unwrap();
1677            },
1678            do {
1679                self.prepare_order_expr(expr, sql);
1680            }
1681        );
1682
1683        if let Some(frame) = &window.frame {
1684            match frame.r#type {
1685                FrameType::Range => sql.write_str(" RANGE ").unwrap(),
1686                FrameType::Rows => sql.write_str(" ROWS ").unwrap(),
1687            };
1688            if let Some(end) = &frame.end {
1689                sql.write_str("BETWEEN ").unwrap();
1690                self.prepare_frame(&frame.start, sql);
1691                sql.write_str(" AND ").unwrap();
1692                self.prepare_frame(end, sql);
1693            } else {
1694                self.prepare_frame(&frame.start, sql);
1695            }
1696        }
1697    }
1698
1699    #[doc(hidden)]
1700    /// Translate a binary expr to SQL.
1701    fn binary_expr(&self, left: &Expr, op: &BinOper, right: &Expr, sql: &mut impl SqlWriter) {
1702        // If left has higher precedence than op, we can drop parentheses around left
1703        let drop_left_higher_precedence =
1704            self.inner_expr_well_known_greater_precedence(left, &(*op).into());
1705
1706        // Figure out if left associativity rules allow us to drop the left parenthesis
1707        let drop_left_assoc = left.is_binary()
1708            && op == left.get_bin_oper().unwrap()
1709            && self.well_known_left_associative(op);
1710
1711        let left_paren = !drop_left_higher_precedence && !drop_left_assoc;
1712        if left_paren {
1713            sql.write_str("(").unwrap();
1714        }
1715        self.prepare_expr(left, sql);
1716        if left_paren {
1717            sql.write_str(")").unwrap();
1718        }
1719
1720        sql.write_str(" ").unwrap();
1721        self.prepare_bin_oper(op, sql);
1722        sql.write_str(" ").unwrap();
1723
1724        // If right has higher precedence than op, we can drop parentheses around right
1725        let drop_right_higher_precedence =
1726            self.inner_expr_well_known_greater_precedence(right, &(*op).into());
1727
1728        let op_as_oper = Oper::BinOper(*op);
1729        // Due to representation of trinary op between as nested binary ops.
1730        let drop_right_between_hack = op_as_oper.is_between()
1731            && right.is_binary()
1732            && matches!(right.get_bin_oper(), Some(&BinOper::And));
1733
1734        // Due to representation of trinary op like/not like with optional arg escape as nested binary ops.
1735        let drop_right_escape_hack = op_as_oper.is_like()
1736            && right.is_binary()
1737            && matches!(right.get_bin_oper(), Some(&BinOper::Escape));
1738
1739        // Due to custom representation of casting AS datatype
1740        let drop_right_as_hack = (op == &BinOper::As) && matches!(right, Expr::Custom(_));
1741
1742        let right_paren = !drop_right_higher_precedence
1743            && !drop_right_escape_hack
1744            && !drop_right_between_hack
1745            && !drop_right_as_hack;
1746        if right_paren {
1747            sql.write_str("(").unwrap();
1748        }
1749        self.prepare_expr(right, sql);
1750        if right_paren {
1751            sql.write_str(")").unwrap();
1752        }
1753    }
1754
1755    fn write_string_quoted(&self, string: &str, buffer: &mut impl Write) {
1756        buffer.write_str("'").unwrap();
1757        self.write_escaped(buffer, string);
1758        buffer.write_str("'").unwrap();
1759    }
1760
1761    #[doc(hidden)]
1762    /// Write bytes enclosed with engine specific byte syntax
1763    fn write_bytes(&self, bytes: &[u8], buffer: &mut impl Write) {
1764        buffer.write_str("x'").unwrap();
1765        for b in bytes {
1766            write!(buffer, "{b:02X}").unwrap()
1767        }
1768        buffer.write_str("'").unwrap();
1769    }
1770
1771    #[doc(hidden)]
1772    /// The name of the function that represents the "if null" condition.
1773    fn if_null_function(&self) -> &str {
1774        "IFNULL"
1775    }
1776
1777    #[doc(hidden)]
1778    /// The name of the function that represents the "greatest" function.
1779    fn greatest_function(&self) -> &str {
1780        "GREATEST"
1781    }
1782
1783    #[doc(hidden)]
1784    /// The name of the function that represents the "least" function.
1785    fn least_function(&self) -> &str {
1786        "LEAST"
1787    }
1788
1789    #[doc(hidden)]
1790    /// The name of the function that returns the char length.
1791    fn char_length_function(&self) -> &str {
1792        "CHAR_LENGTH"
1793    }
1794
1795    #[doc(hidden)]
1796    /// The name of the function that returns a random number
1797    fn random_function(&self) -> &str {
1798        // Returning it with parens as part of the name because the tuple preparer can't deal with empty lists
1799        "RANDOM"
1800    }
1801
1802    #[doc(hidden)]
1803    /// The name of the function that returns the lock phrase including the leading 'FOR'
1804    fn lock_phrase(&self, lock_type: LockType) -> &'static str {
1805        match lock_type {
1806            LockType::Update => "FOR UPDATE",
1807            LockType::NoKeyUpdate => "FOR NO KEY UPDATE",
1808            LockType::Share => "FOR SHARE",
1809            LockType::KeyShare => "FOR KEY SHARE",
1810        }
1811    }
1812
1813    /// The keywords for insert default row.
1814    fn insert_default_keyword(&self) -> &str {
1815        "(DEFAULT)"
1816    }
1817
1818    /// Write insert default rows expression.
1819    fn insert_default_values(&self, num_rows: u32, sql: &mut impl SqlWriter) {
1820        sql.write_str("VALUES ").unwrap();
1821        if num_rows > 0 {
1822            sql.write_str(self.insert_default_keyword()).unwrap();
1823
1824            for _ in 1..num_rows {
1825                sql.write_str(", ").unwrap();
1826                sql.write_str(self.insert_default_keyword()).unwrap();
1827            }
1828        }
1829    }
1830
1831    /// Write TRUE constant
1832    fn prepare_constant_true(&self, sql: &mut impl SqlWriter) {
1833        self.prepare_constant(&true.into(), sql);
1834    }
1835
1836    /// Write FALSE constant
1837    fn prepare_constant_false(&self, sql: &mut impl SqlWriter) {
1838        self.prepare_constant(&false.into(), sql);
1839    }
1840}
1841
1842impl SubQueryStatement {
1843    pub(crate) fn prepare_statement(
1844        &self,
1845        query_builder: &impl QueryBuilder,
1846        sql: &mut impl SqlWriter,
1847    ) {
1848        use SubQueryStatement::*;
1849        match self {
1850            SelectStatement(stmt) => query_builder.prepare_select_statement(stmt, sql),
1851            InsertStatement(stmt) => query_builder.prepare_insert_statement(stmt, sql),
1852            UpdateStatement(stmt) => query_builder.prepare_update_statement(stmt, sql),
1853            DeleteStatement(stmt) => query_builder.prepare_delete_statement(stmt, sql),
1854            WithStatement(stmt) => query_builder.prepare_with_query(stmt, sql),
1855        }
1856    }
1857}
1858
1859pub(crate) struct CommonSqlQueryBuilder;
1860
1861impl OperLeftAssocDecider for CommonSqlQueryBuilder {
1862    fn well_known_left_associative(&self, op: &BinOper) -> bool {
1863        common_well_known_left_associative(op)
1864    }
1865}
1866
1867impl PrecedenceDecider for CommonSqlQueryBuilder {
1868    fn inner_expr_well_known_greater_precedence(&self, inner: &Expr, outer_oper: &Oper) -> bool {
1869        common_inner_expr_well_known_greater_precedence(inner, outer_oper)
1870    }
1871}
1872
1873impl QueryBuilder for CommonSqlQueryBuilder {
1874    fn prepare_query_statement(&self, query: &SubQueryStatement, sql: &mut impl SqlWriter) {
1875        query.prepare_statement(self, sql);
1876    }
1877
1878    fn prepare_value(&self, value: Value, sql: &mut impl SqlWriter) {
1879        sql.push_param(value, self as _);
1880    }
1881}
1882
1883impl QuotedBuilder for CommonSqlQueryBuilder {
1884    fn quote(&self) -> Quote {
1885        QUOTE
1886    }
1887}
1888
1889impl EscapeBuilder for CommonSqlQueryBuilder {}
1890
1891impl TableRefBuilder for CommonSqlQueryBuilder {}
1892
1893#[cfg_attr(
1894    feature = "option-more-parentheses",
1895    allow(unreachable_code, unused_variables)
1896)]
1897pub(crate) fn common_inner_expr_well_known_greater_precedence(
1898    inner: &Expr,
1899    outer_oper: &Oper,
1900) -> bool {
1901    match inner {
1902        // We only consider the case where an inner expression is contained in either a
1903        // unary or binary expression (with an outer_oper).
1904        // We do not need to wrap with parentheses:
1905        // Columns, tuples (already wrapped), constants, function calls, values,
1906        // keywords, subqueries (already wrapped), case (already wrapped)
1907        Expr::Column(_)
1908        | Expr::Tuple(_)
1909        | Expr::Constant(_)
1910        | Expr::FunctionCall(_)
1911        | Expr::Value(_)
1912        | Expr::Keyword(_)
1913        | Expr::Case(_)
1914        | Expr::SubQuery(_, _)
1915        | Expr::TypeName(_) => true,
1916        Expr::Binary(_, inner_oper, _) => {
1917            #[cfg(feature = "option-more-parentheses")]
1918            {
1919                return false;
1920            }
1921            let inner_oper: Oper = (*inner_oper).into();
1922            if inner_oper.is_arithmetic() || inner_oper.is_shift() {
1923                outer_oper.is_comparison()
1924                    || outer_oper.is_between()
1925                    || outer_oper.is_in()
1926                    || outer_oper.is_like()
1927                    || outer_oper.is_logical()
1928            } else if inner_oper.is_comparison()
1929                || inner_oper.is_in()
1930                || inner_oper.is_like()
1931                || inner_oper.is_is()
1932            {
1933                outer_oper.is_logical()
1934            } else {
1935                false
1936            }
1937        }
1938        _ => false,
1939    }
1940}
1941
1942pub(crate) fn common_well_known_left_associative(op: &BinOper) -> bool {
1943    matches!(
1944        op,
1945        BinOper::And | BinOper::Or | BinOper::Add | BinOper::Sub | BinOper::Mul | BinOper::Mod
1946    )
1947}
1948
1949macro_rules! join_io {
1950    ($iter:ident, $item:ident $(, first $first:expr)?, join $join:expr, do $do:expr $(, last $last:expr)?) => {
1951        if let Some($item) = $iter.next() {
1952            $($first)?
1953            $do
1954
1955            for $item in $iter {
1956                $join
1957                $do
1958            }
1959
1960            $($last)?
1961        }
1962    };
1963}
1964
1965pub(crate) use join_io;
1966
1967#[cfg(test)]
1968mod tests {
1969    #[cfg(feature = "with-chrono")]
1970    use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, Utc};
1971
1972    #[cfg(feature = "with-chrono")]
1973    use crate::QueryBuilder;
1974
1975    /// [Postgresql reference](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-INPUT-TIMES)
1976    ///
1977    /// [Mysql reference](https://dev.mysql.com/doc/refman/8.4/en/fractional-seconds.html)
1978    ///
1979    /// [Sqlite reference](https://sqlite.org/lang_datefunc.html)
1980    #[test]
1981    #[cfg(feature = "with-chrono")]
1982    fn format_time_constant() {
1983        use crate::{MysqlQueryBuilder, PostgresQueryBuilder, QueryBuilder, SqliteQueryBuilder};
1984
1985        let time = NaiveTime::from_hms_micro_opt(1, 2, 3, 123456)
1986            .unwrap()
1987            .into();
1988
1989        let mut string = String::new();
1990        macro_rules! compare {
1991            ($a:ident, $b:literal) => {
1992                PostgresQueryBuilder.prepare_constant(&$a, &mut string);
1993                assert_eq!(string, $b);
1994
1995                string.clear();
1996
1997                MysqlQueryBuilder.prepare_constant(&$a, &mut string);
1998                assert_eq!(string, $b);
1999
2000                string.clear();
2001
2002                SqliteQueryBuilder.prepare_constant(&$a, &mut string);
2003                assert_eq!(string, $b);
2004
2005                string.clear();
2006            };
2007        }
2008
2009        compare!(time, "'01:02:03.123456'");
2010
2011        let d = NaiveDate::from_ymd_opt(2015, 6, 3).unwrap();
2012        let t = NaiveTime::from_hms_micro_opt(12, 34, 56, 123456).unwrap();
2013
2014        let dt = NaiveDateTime::new(d, t);
2015
2016        let date_time = dt.into();
2017
2018        compare!(date_time, "'2015-06-03 12:34:56.123456'");
2019
2020        let date_time_utc = DateTime::<Utc>::from_naive_utc_and_offset(dt, Utc).into();
2021
2022        compare!(date_time_utc, "'2015-06-03 12:34:56.123456 +00:00'");
2023
2024        let date_time_tz = DateTime::<FixedOffset>::from_naive_utc_and_offset(
2025            dt,
2026            FixedOffset::east_opt(8 * 3600).unwrap(),
2027        )
2028        .into();
2029
2030        compare!(date_time_tz, "'2015-06-03 20:34:56.123456 +08:00'");
2031    }
2032}