Skip to main content

tank_core/writer/
sql_writer.rs

1use crate::{
2    Action, BinaryOp, BinaryOpType, ColumnDef, ColumnRef, Dataset, DynQuery, Entity, Error,
3    Expression, Fragment, Interval, IsTrue, Join, JoinType, Operand, Order, Ordered,
4    PrimaryKeyType, SelectQuery, TableRef, UnaryOp, UnaryOpType, Value, possibly_parenthesized,
5    separated_by, write_escaped, writer::Context,
6};
7use core::f64;
8use std::{
9    collections::{BTreeMap, HashMap},
10    fmt::Write,
11    mem,
12};
13use time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
14use uuid::Uuid;
15
16macro_rules! write_integer_fn {
17    ($fn_name:ident, $ty:ty) => {
18        fn $fn_name(&self, context: &mut Context, out: &mut DynQuery, value: $ty) {
19            if context.fragment == Fragment::JsonKey {
20                out.push('"');
21            }
22            let mut buffer = itoa::Buffer::new();
23            out.push_str(buffer.format(value));
24            if context.fragment == Fragment::JsonKey {
25                out.push('"');
26            }
27        }
28    };
29}
30
31macro_rules! write_float_fn {
32    ($fn_name:ident, $ty:ty, $value_ty:expr) => {
33        fn $fn_name(&self, context: &mut Context, out: &mut DynQuery, value: $ty) {
34            let mut buffer = ryu::Buffer::new();
35            if value.is_infinite() {
36                self.write_binary_op(
37                    context,
38                    out,
39                    &BinaryOp {
40                        op: BinaryOpType::Cast,
41                        lhs: &Operand::LitStr(buffer.format(if value.is_sign_negative() {
42                            f64::NEG_INFINITY
43                        } else {
44                            f64::INFINITY
45                        })),
46                        rhs: &Operand::Type($value_ty),
47                    },
48                );
49            } else if value.is_nan() {
50                self.write_binary_op(
51                    context,
52                    out,
53                    &BinaryOp {
54                        op: BinaryOpType::Cast,
55                        lhs: &Operand::LitStr(buffer.format(f64::NAN)),
56                        rhs: &Operand::Type($value_ty),
57                    },
58                );
59            } else {
60                if context.fragment == Fragment::JsonKey {
61                    out.push('"');
62                }
63                out.push_str(buffer.format(value));
64                if context.fragment == Fragment::JsonKey {
65                    out.push('"');
66                }
67            }
68        }
69    };
70}
71
72/// SQL dialect printer.
73pub trait SqlWriter: Send {
74    /// Upcasts self to a distinct dynamic object.
75    fn as_dyn(&self) -> &dyn SqlWriter;
76
77    /// Separator used for qualified names (e.g., schema.table.column)
78    fn separator(&self) -> &str {
79        "."
80    }
81
82    /// Determines if the current SQL context supports alias declarations.
83    fn is_alias_declaration(&self, context: &mut Context) -> bool {
84        match context.fragment {
85            Fragment::SqlSelectFrom | Fragment::SqlJoin => true,
86            _ => false,
87        }
88    }
89
90    /// Writes an identifier (like a table or column name) to the query builder, optionally quoting it.
91    fn write_identifier(
92        &self,
93        _context: &mut Context,
94        out: &mut DynQuery,
95        value: &str,
96        quoted: bool,
97    ) {
98        if quoted {
99            out.push('"');
100            write_escaped(out, value, '"', "\"\"");
101            out.push('"');
102        } else {
103            out.push_str(value);
104        }
105    }
106
107    /// Write table reference.
108    fn write_table_ref(&self, context: &mut Context, out: &mut DynQuery, value: &TableRef) {
109        let alias_declaration = self.is_alias_declaration(context);
110        if alias_declaration || value.alias.is_empty() {
111            if !value.schema.is_empty() {
112                self.write_identifier(context, out, &value.schema, context.quote_identifiers);
113                out.push_str(self.separator());
114            }
115            self.write_identifier(context, out, &value.name, context.quote_identifiers);
116        }
117        if !value.alias.is_empty() {
118            if alias_declaration {
119                let _ = write!(out, " {}", value.alias);
120            } else {
121                out.push_str(&value.alias);
122            }
123        }
124    }
125
126    /// Write column reference.
127    fn write_column_ref(&self, context: &mut Context, out: &mut DynQuery, value: &ColumnRef) {
128        if context.qualify_columns {
129            let table_ref = mem::take(&mut context.table_ref);
130            let mut schema = &table_ref.schema;
131            if schema.is_empty() {
132                schema = &value.schema;
133            }
134            let mut table = &table_ref.alias;
135            if table.is_empty() {
136                table = &table_ref.name;
137            }
138            if table.is_empty() {
139                table = &value.table;
140            }
141            if !table.is_empty() {
142                if !schema.is_empty() {
143                    self.write_identifier(context, out, schema, context.quote_identifiers);
144                    out.push_str(self.separator());
145                }
146                self.write_identifier(context, out, table, context.quote_identifiers);
147                out.push_str(self.separator());
148            }
149            context.table_ref = table_ref
150        }
151        self.write_identifier(context, out, &value.name, context.quote_identifiers);
152    }
153
154    /// Write overridden type.
155    fn write_column_overridden_type(
156        &self,
157        _context: &mut Context,
158        out: &mut DynQuery,
159        _column: &ColumnDef,
160        types: &BTreeMap<&'static str, &'static str>,
161    ) {
162        if let Some(t) = types
163            .iter()
164            .find_map(|(k, v)| if *k == "" { Some(v) } else { None })
165        {
166            out.push_str(t);
167        }
168    }
169
170    /// Write SQL type name.
171    fn write_column_type(&self, context: &mut Context, out: &mut DynQuery, value: &Value) {
172        match value {
173            Value::Boolean(..) => out.push_str("BOOLEAN"),
174            Value::Int8(..) => out.push_str("TINYINT"),
175            Value::Int16(..) => out.push_str("SMALLINT"),
176            Value::Int32(..) => out.push_str("INTEGER"),
177            Value::Int64(..) => out.push_str("BIGINT"),
178            Value::Int128(..) => out.push_str("HUGEINT"),
179            Value::UInt8(..) => out.push_str("UTINYINT"),
180            Value::UInt16(..) => out.push_str("USMALLINT"),
181            Value::UInt32(..) => out.push_str("UINTEGER"),
182            Value::UInt64(..) => out.push_str("UBIGINT"),
183            Value::UInt128(..) => out.push_str("UHUGEINT"),
184            Value::Float32(..) => out.push_str("FLOAT"),
185            Value::Float64(..) => out.push_str("DOUBLE"),
186            Value::Decimal(.., precision, scale) => {
187                out.push_str("DECIMAL");
188                if (precision, scale) != (&0, &0) {
189                    let _ = write!(out, "({precision},{scale})");
190                }
191            }
192            Value::Char(..) => out.push_str("CHAR(1)"),
193            Value::Varchar(..) => out.push_str("VARCHAR"),
194            Value::Blob(..) => out.push_str("BLOB"),
195            Value::Date(..) => out.push_str("DATE"),
196            Value::Time(..) => out.push_str("TIME"),
197            Value::Timestamp(..) => out.push_str("TIMESTAMP"),
198            Value::TimestampWithTimezone(..) => out.push_str("TIMESTAMPTZ"),
199            Value::Interval(..) => out.push_str("INTERVAL"),
200            Value::Uuid(..) => out.push_str("UUID"),
201            Value::Array(.., inner, size) => {
202                self.write_column_type(context, out, inner);
203                let _ = write!(out, "[{size}]");
204            }
205            Value::List(.., inner) => {
206                self.write_column_type(context, out, inner);
207                out.push_str("[]");
208            }
209            Value::Map(.., key, value) => {
210                out.push_str("MAP(");
211                self.write_column_type(context, out, key);
212                out.push(',');
213                self.write_column_type(context, out, value);
214                out.push(')');
215            }
216            Value::Json(..) => out.push_str("JSON"),
217            _ => log::error!("Unexpected tank::Value, variant {value:?} is not supported"),
218        };
219    }
220
221    /// Write value.
222    fn write_value(&self, context: &mut Context, out: &mut DynQuery, value: &Value) {
223        let delimiter = if context.fragment == Fragment::JsonKey {
224            "\""
225        } else {
226            ""
227        };
228        match value {
229            v if v.is_null() => self.write_null(context, out),
230            Value::Boolean(Some(v), ..) => self.write_bool(context, out, *v),
231            Value::Int8(Some(v), ..) => self.write_value_i8(context, out, *v),
232            Value::Int16(Some(v), ..) => self.write_value_i16(context, out, *v),
233            Value::Int32(Some(v), ..) => self.write_value_i32(context, out, *v),
234            Value::Int64(Some(v), ..) => self.write_value_i64(context, out, *v),
235            Value::Int128(Some(v), ..) => self.write_value_i128(context, out, *v),
236            Value::UInt8(Some(v), ..) => self.write_value_u8(context, out, *v),
237            Value::UInt16(Some(v), ..) => self.write_value_u16(context, out, *v),
238            Value::UInt32(Some(v), ..) => self.write_value_u32(context, out, *v),
239            Value::UInt64(Some(v), ..) => self.write_value_u64(context, out, *v),
240            Value::UInt128(Some(v), ..) => self.write_value_u128(context, out, *v),
241            Value::Float32(Some(v), ..) => self.write_value_f32(context, out, *v),
242            Value::Float64(Some(v), ..) => self.write_value_f64(context, out, *v),
243            Value::Decimal(Some(v), ..) => drop(write!(out, "{delimiter}{v}{delimiter}")),
244            Value::Char(Some(v), ..) => {
245                let mut buf = [0u8; 4];
246                self.write_string(context, out, v.encode_utf8(&mut buf));
247            }
248            Value::Varchar(Some(v), ..) => self.write_string(context, out, v),
249            Value::Blob(Some(v), ..) => self.write_blob(context, out, v.as_ref()),
250            Value::Date(Some(v), ..) => self.write_date(context, out, v),
251            Value::Time(Some(v), ..) => self.write_time(context, out, v),
252            Value::Timestamp(Some(v), ..) => self.write_timestamp(context, out, v),
253            Value::TimestampWithTimezone(Some(v), ..) => self.write_timestamptz(context, out, v),
254            Value::Interval(Some(v), ..) => self.write_interval(context, out, v),
255            Value::Uuid(Some(v), ..) => self.write_uuid(context, out, v),
256            Value::Array(Some(..), elem_ty, ..) | Value::List(Some(..), elem_ty, ..) => match value
257            {
258                Value::Array(Some(v), ..) => self.write_list(
259                    context,
260                    out,
261                    &mut v.iter().map(|v| v as &dyn Expression),
262                    Some(&*elem_ty),
263                    true,
264                ),
265                Value::List(Some(v), ..) => self.write_list(
266                    context,
267                    out,
268                    &mut v.iter().map(|v| v as &dyn Expression),
269                    Some(&*elem_ty),
270                    false,
271                ),
272                _ => unreachable!(),
273            },
274            Value::Map(Some(v), ..) => self.write_map(context, out, v),
275            Value::Json(Some(v), ..) => self.write_json(context, out, v),
276            Value::Struct(Some(v), ..) => self.write_struct(context, out, v),
277            _ => {
278                log::error!("Cannot write {value:?}");
279            }
280        };
281    }
282
283    fn write_null(&self, context: &mut Context, out: &mut DynQuery) {
284        out.push_str(if context.fragment == Fragment::Json {
285            "null"
286        } else {
287            "NULL"
288        });
289    }
290
291    fn write_bool(&self, context: &mut Context, out: &mut DynQuery, value: bool) {
292        if context.fragment == Fragment::JsonKey {
293            out.push('"');
294        }
295        out.push_str(["false", "true"][value as usize]);
296        if context.fragment == Fragment::JsonKey {
297            out.push('"');
298        }
299    }
300
301    write_integer_fn!(write_value_i8, i8);
302    write_integer_fn!(write_value_i16, i16);
303    write_integer_fn!(write_value_i32, i32);
304    write_integer_fn!(write_value_i64, i64);
305    write_integer_fn!(write_value_i128, i128);
306    write_integer_fn!(write_value_u8, u8);
307    write_integer_fn!(write_value_u16, u16);
308    write_integer_fn!(write_value_u32, u32);
309    write_integer_fn!(write_value_u64, u64);
310    write_integer_fn!(write_value_u128, u128);
311
312    write_float_fn!(write_value_f32, f32, Value::Float32(None));
313    write_float_fn!(write_value_f64, f64, Value::Float64(None));
314
315    fn write_string(&self, context: &mut Context, out: &mut DynQuery, value: &str) {
316        if matches!(context.fragment, Fragment::Json | Fragment::JsonKey) {
317            match serde_json::to_string(value) {
318                Ok(s) => out.push_str(&s),
319                Err(e) => {
320                    let e = Error::new(e).context("Failed to serialize string as JSON");
321                    log::error!("{e:#}");
322                }
323            }
324            return;
325        }
326        let (delimiter, escaped) = match context.fragment {
327            Fragment::None | Fragment::ParameterBinding => (None, ""),
328            _ => (Some('\''), "''"),
329        };
330        if let Some(delimiter) = delimiter {
331            out.push(delimiter);
332            let mut pos = 0;
333            for (i, c) in value.char_indices() {
334                if c == delimiter {
335                    out.push_str(&value[pos..i]);
336                    out.push_str(escaped);
337                    pos = i + 1;
338                }
339            }
340            out.push_str(&value[pos..]);
341            out.push(delimiter);
342        } else {
343            out.push_str(value);
344        }
345    }
346
347    fn write_blob(&self, context: &mut Context, out: &mut DynQuery, value: &[u8]) {
348        let delimiter = match context.fragment {
349            Fragment::None | Fragment::ParameterBinding => "",
350            Fragment::Json | Fragment::JsonKey => "\"",
351            _ => "'",
352        };
353        out.push_str(delimiter);
354        for v in value {
355            let _ = write!(out, "\\x{:02X}", v);
356        }
357        out.push_str(delimiter);
358    }
359
360    fn write_date(&self, context: &mut Context, out: &mut DynQuery, value: &Date) {
361        let d = match context.fragment {
362            Fragment::None | Fragment::ParameterBinding | Fragment::Timestamp => "",
363            Fragment::Json | Fragment::JsonKey => "\"",
364            _ => "'",
365        };
366        let year = value.year();
367        let month = value.month() as u8;
368        let day = value.day();
369        let _ = write!(
370            out,
371            "{d}{}{:04}-{month:02}-{day:02}{d}",
372            if year < 0 { "-" } else { "" },
373            year.unsigned_abs()
374        );
375    }
376
377    fn write_time(&self, context: &mut Context, out: &mut DynQuery, value: &Time) {
378        let d = match context.fragment {
379            Fragment::None | Fragment::ParameterBinding | Fragment::Timestamp => "",
380            Fragment::Json | Fragment::JsonKey => "\"",
381            _ => "'",
382        };
383        let (h, m, s, ns) = value.as_hms_nano();
384        let mut subsecond = ns;
385        let mut width = 9;
386        while width > 1 && subsecond % 10 == 0 {
387            subsecond /= 10;
388            width -= 1;
389        }
390        let _ = write!(out, "{d}{h:02}:{m:02}:{s:02}.{subsecond:0width$}{d}");
391    }
392
393    fn write_timestamp(
394        &self,
395        context: &mut Context,
396        out: &mut DynQuery,
397        value: &PrimitiveDateTime,
398    ) {
399        let d = match context.fragment {
400            Fragment::None | Fragment::ParameterBinding | Fragment::Timestamp => "",
401            Fragment::Json | Fragment::JsonKey => "\"",
402            _ => "'",
403        };
404        let mut context = context.switch_fragment(Fragment::Timestamp);
405        out.push_str(d);
406        self.write_date(&mut context.current, out, &value.date());
407        out.push(' ');
408        self.write_time(&mut context.current, out, &value.time());
409        out.push_str(d);
410    }
411
412    fn write_timestamptz(&self, context: &mut Context, out: &mut DynQuery, value: &OffsetDateTime) {
413        let d = match context.fragment {
414            Fragment::None | Fragment::ParameterBinding => "",
415            Fragment::Json | Fragment::JsonKey => "\"",
416            _ => "'",
417        };
418        let mut context = context.switch_fragment(Fragment::Timestamp);
419        out.push_str(d);
420        self.write_timestamp(
421            &mut context.current,
422            out,
423            &PrimitiveDateTime::new(value.date(), value.time()),
424        );
425        let (h, m, s) = value.offset().as_hms();
426        if h != 0 || m != 0 || s != 0 {
427            let is_negative = h < 0 || (h == 0 && (m < 0 || (m == 0 && s < 0)));
428            out.push(if is_negative { '-' } else { '+' });
429            let _ = write!(out, "{:02}", h.unsigned_abs());
430            if m != 0 || s != 0 {
431                let _ = write!(out, ":{:02}", m.unsigned_abs());
432                if s != 0 {
433                    let _ = write!(out, ":{:02}", s.unsigned_abs());
434                }
435            }
436        }
437        out.push_str(d);
438    }
439
440    /// Units used to decompose intervals (notice the decreasing order).
441    fn value_interval_units(&self) -> &[(&str, i128)] {
442        static UNITS: &[(&str, i128)] = &[
443            ("DAY", Interval::NANOS_IN_DAY),
444            ("HOUR", Interval::NANOS_IN_SEC * 3600),
445            ("MINUTE", Interval::NANOS_IN_SEC * 60),
446            ("SECOND", Interval::NANOS_IN_SEC),
447            ("MICROSECOND", 1_000),
448            ("NANOSECOND", 1),
449        ];
450        UNITS
451    }
452
453    fn write_interval(&self, context: &mut Context, out: &mut DynQuery, value: &Interval) {
454        out.push_str("INTERVAL ");
455        let d = match context.fragment {
456            Fragment::None => "",
457            Fragment::Json | Fragment::JsonKey => "\"",
458            _ => "'",
459        };
460        out.push_str(d);
461        if value.is_zero() {
462            out.push_str("0 SECONDS");
463        }
464        macro_rules! write_unit {
465            ($out:ident, $len:ident, $val:expr, $unit:expr) => {
466                if $out.len() > $len {
467                    $out.push(' ');
468                    $len = $out.len();
469                }
470                let _ = write!(
471                    $out,
472                    "{} {}{}",
473                    $val,
474                    $unit,
475                    if $val != 1 && $val != -1 { "S" } else { "" }
476                );
477            };
478        }
479        let mut months = value.months;
480        let mut nanos = value.nanos + value.days as i128 * Interval::NANOS_IN_DAY;
481        let mut len = out.len();
482        if months != 0 {
483            if months.abs() > 48 || months % 12 == 0 {
484                write_unit!(out, len, months / 12, "YEAR");
485                months = months % 12;
486            }
487            if months != 0 {
488                write_unit!(out, len, months, "MONTH");
489            }
490        }
491        for &(name, factor) in self.value_interval_units() {
492            let rem = nanos % factor;
493            if rem == 0 || (rem != 0 && factor / rem.abs() > 1_000_000) {
494                let value = nanos / factor;
495                if value != 0 {
496                    write_unit!(out, len, value, name);
497                    nanos = rem;
498                    if nanos == 0 {
499                        break;
500                    }
501                }
502            }
503        }
504        out.push_str(d);
505    }
506
507    fn write_uuid(&self, context: &mut Context, out: &mut DynQuery, value: &Uuid) {
508        let d = match context.fragment {
509            Fragment::None => "",
510            Fragment::Json | Fragment::JsonKey => "\"",
511            _ => "'",
512        };
513        let _ = write!(out, "{d}{value}{d}");
514    }
515
516    fn write_list(
517        &self,
518        context: &mut Context,
519        out: &mut DynQuery,
520        value: &mut dyn Iterator<Item = &dyn Expression>,
521        _ty: Option<&Value>,
522        _is_array: bool,
523    ) {
524        out.push('[');
525        separated_by(
526            out,
527            value,
528            |out, v| {
529                v.write_query(self.as_dyn(), context, out);
530            },
531            ",",
532        );
533        out.push(']');
534    }
535
536    fn write_tuple(
537        &self,
538        context: &mut Context,
539        out: &mut DynQuery,
540        value: &mut dyn Iterator<Item = &dyn Expression>,
541    ) {
542        out.push('(');
543        separated_by(
544            out,
545            value,
546            |out, v| {
547                v.write_query(self.as_dyn(), context, out);
548            },
549            ",",
550        );
551        out.push(')');
552    }
553
554    fn write_map(&self, context: &mut Context, out: &mut DynQuery, value: &HashMap<Value, Value>) {
555        out.push('{');
556        separated_by(
557            out,
558            value,
559            |out, (k, v)| {
560                self.write_value(context, out, k);
561                out.push(':');
562                self.write_value(context, out, v);
563            },
564            ",",
565        );
566        out.push('}');
567    }
568
569    fn write_json(&self, context: &mut Context, out: &mut DynQuery, value: &serde_json::Value) {
570        self.write_string(context, out, &value.to_string());
571    }
572
573    fn write_struct(
574        &self,
575        context: &mut Context,
576        out: &mut DynQuery,
577        value: &[(String, Value)],
578    ) {
579        out.push('{');
580        separated_by(
581            out,
582            value,
583            |out, (k, v)| {
584                self.write_string(context, out, k);
585                out.push(':');
586                self.write_value(context, out, v);
587            },
588            ",",
589        );
590        out.push('}');
591    }
592
593    fn write_function(
594        &self,
595        context: &mut Context,
596        out: &mut DynQuery,
597        function: &str,
598        args: &[&dyn Expression],
599    ) {
600        out.push_str(function);
601        out.push('(');
602        separated_by(
603            out,
604            args,
605            |out, expr| {
606                expr.write_query(self.as_dyn(), context, out);
607            },
608            ",",
609        );
610        out.push(')');
611    }
612
613    /// Precedence table for unary operators.
614    fn expression_unary_op_precedence(&self, value: &UnaryOpType) -> i32 {
615        match value {
616            UnaryOpType::Negative => 1250,
617            UnaryOpType::Not => 250,
618        }
619    }
620
621    /// Precedence table for binary operators.
622    fn expression_binary_op_precedence(&self, value: &BinaryOpType) -> i32 {
623        match value {
624            BinaryOpType::Or => 100,
625            BinaryOpType::And => 200,
626            BinaryOpType::Equal => 300,
627            BinaryOpType::NotEqual => 300,
628            BinaryOpType::Less => 300,
629            BinaryOpType::Greater => 300,
630            BinaryOpType::LessEqual => 300,
631            BinaryOpType::GreaterEqual => 300,
632            BinaryOpType::In => 400,
633            BinaryOpType::NotIn => 400,
634            BinaryOpType::Is => 400,
635            BinaryOpType::IsNot => 400,
636            BinaryOpType::Like => 400,
637            BinaryOpType::NotLike => 400,
638            BinaryOpType::Regexp => 400,
639            BinaryOpType::NotRegexp => 400,
640            BinaryOpType::Glob => 400,
641            BinaryOpType::NotGlob => 400,
642            BinaryOpType::BitwiseOr => 500,
643            BinaryOpType::BitwiseAnd => 600,
644            BinaryOpType::ShiftLeft => 700,
645            BinaryOpType::ShiftRight => 700,
646            BinaryOpType::Subtraction => 800,
647            BinaryOpType::Addition => 800,
648            BinaryOpType::Multiplication => 900,
649            BinaryOpType::Division => 900,
650            BinaryOpType::Remainder => 900,
651            BinaryOpType::Indexing => 1000,
652            BinaryOpType::Cast => 1100,
653            BinaryOpType::Alias => 1200,
654        }
655    }
656
657    fn expression_binary_op_fragments(
658        &self,
659        context: &mut Context,
660        op_type: BinaryOpType,
661    ) -> (&str, &str, &str, bool, bool) {
662        match op_type {
663            BinaryOpType::Indexing => ("", "[", "]", false, true),
664            BinaryOpType::Cast => {
665                context.switch_fragment(Fragment::Casting);
666                ("CAST(", " AS ", ")", true, true)
667            }
668            BinaryOpType::Multiplication => ("", " * ", "", false, false),
669            BinaryOpType::Division => ("", " / ", "", false, false),
670            BinaryOpType::Remainder => ("", " % ", "", false, false),
671            BinaryOpType::Addition => ("", " + ", "", false, false),
672            BinaryOpType::Subtraction => ("", " - ", "", false, false),
673            BinaryOpType::ShiftLeft => ("", " << ", "", false, false),
674            BinaryOpType::ShiftRight => ("", " >> ", "", false, false),
675            BinaryOpType::BitwiseAnd => ("", " & ", "", false, false),
676            BinaryOpType::BitwiseOr => ("", " | ", "", false, false),
677            BinaryOpType::In => ("", " IN ", "", false, false),
678            BinaryOpType::NotIn => ("", " NOT IN ", "", false, false),
679            BinaryOpType::Is => ("", " IS ", "", false, false),
680            BinaryOpType::IsNot => ("", " IS NOT ", "", false, false),
681            BinaryOpType::Like => ("", " LIKE ", "", false, false),
682            BinaryOpType::NotLike => ("", " NOT LIKE ", "", false, false),
683            BinaryOpType::Regexp => ("", " REGEXP ", "", false, false),
684            BinaryOpType::NotRegexp => ("", " NOT REGEXP ", "", false, false),
685            BinaryOpType::Glob => ("", " GLOB ", "", false, false),
686            BinaryOpType::NotGlob => ("", " NOT GLOB ", "", false, false),
687            BinaryOpType::Equal => ("", " = ", "", false, false),
688            BinaryOpType::NotEqual => ("", " != ", "", false, false),
689            BinaryOpType::Less => ("", " < ", "", false, false),
690            BinaryOpType::LessEqual => ("", " <= ", "", false, false),
691            BinaryOpType::Greater => ("", " > ", "", false, false),
692            BinaryOpType::GreaterEqual => ("", " >= ", "", false, false),
693            BinaryOpType::And => ("", " AND ", "", false, false),
694            BinaryOpType::Or => ("", " OR ", "", false, false),
695            BinaryOpType::Alias => {
696                context.switch_fragment(Fragment::Aliasing);
697                ("", " AS ", "", false, false)
698            }
699        }
700    }
701
702    fn write_operand(&self, context: &mut Context, out: &mut DynQuery, value: &Operand) {
703        match value {
704            Operand::Null => self.write_null(context, out),
705            Operand::LitBool(v) => self.write_bool(context, out, *v),
706            Operand::LitInt(v) => self.write_value_i128(context, out, *v),
707            Operand::LitFloat(v) => self.write_value_f64(context, out, *v),
708            Operand::LitStr(v) => self.write_string(context, out, v),
709            Operand::LitIdent(v) => {
710                self.write_identifier(context, out, v, context.fragment == Fragment::Aliasing)
711            }
712            Operand::LitField(v) => {
713                let separator = self.separator();
714                for (i, part) in v.iter().enumerate() {
715                    if i > 0 {
716                        out.push_str(separator);
717                    }
718                    out.push_str(part);
719                }
720            }
721            Operand::LitList(v) => self.write_list(
722                context,
723                out,
724                &mut v.iter().map(|v| v as &dyn Expression),
725                None,
726                false,
727            ),
728            Operand::LitTuple(v) => {
729                self.write_tuple(context, out, &mut v.iter().map(|v| v as &dyn Expression))
730            }
731            Operand::Type(v) => self.write_column_type(context, out, v),
732            Operand::Variable(v) => self.write_value(context, out, v),
733            Operand::Value(v) => self.write_value(context, out, v),
734            Operand::Call(f, args) => self.write_function(context, out, f, args),
735            Operand::Asterisk => drop(out.push('*')),
736            Operand::QuestionMark => self.write_question_mark(context, out),
737            Operand::CurrentTimestampMs => self.write_current_timestamp_ms(context, out),
738        };
739    }
740
741    fn write_question_mark(&self, context: &mut Context, out: &mut DynQuery) {
742        context.counter += 1;
743        out.push('?');
744    }
745
746    fn write_current_timestamp_ms(&self, _context: &mut Context, out: &mut DynQuery) {
747        out.push_str("NOW()");
748    }
749
750    fn write_unary_op(
751        &self,
752        context: &mut Context,
753        out: &mut DynQuery,
754        value: &UnaryOp<&dyn Expression>,
755    ) {
756        match value.op {
757            UnaryOpType::Negative => out.push('-'),
758            UnaryOpType::Not => out.push_str("NOT "),
759        };
760        possibly_parenthesized!(
761            out,
762            value.arg.precedence(self.as_dyn()) <= self.expression_unary_op_precedence(&value.op),
763            value.arg.write_query(self.as_dyn(), context, out)
764        );
765    }
766
767    /// Render binary operator expression handling precedence and parenthesis.
768    fn write_binary_op(
769        &self,
770        context: &mut Context,
771        out: &mut DynQuery,
772        value: &BinaryOp<&dyn Expression, &dyn Expression>,
773    ) {
774        if value.op == BinaryOpType::Alias && context.fragment == Fragment::SqlSelectOrderBy {
775            return value.lhs.write_query(self.as_dyn(), context, out);
776        }
777        let (prefix, infix, suffix, lhs_parenthesized, rhs_parenthesized) =
778            self.expression_binary_op_fragments(context, value.op);
779        let precedence = self.expression_binary_op_precedence(&value.op);
780        out.push_str(prefix);
781        possibly_parenthesized!(
782            out,
783            !lhs_parenthesized && value.lhs.precedence(self.as_dyn()) < precedence,
784            value.lhs.write_query(self.as_dyn(), context, out)
785        );
786        out.push_str(infix);
787        let mut context = context.switch_fragment(if value.op == BinaryOpType::Alias {
788            Fragment::Aliasing
789        } else {
790            context.fragment
791        });
792        possibly_parenthesized!(
793            out,
794            !rhs_parenthesized && value.rhs.precedence(self.as_dyn()) <= precedence,
795            value
796                .rhs
797                .write_query(self.as_dyn(), &mut context.current, out)
798        );
799        out.push_str(suffix);
800    }
801
802    fn write_cast(
803        &self,
804        context: &mut Context,
805        out: &mut DynQuery,
806        expr: &dyn Expression,
807        ty: &dyn Expression,
808    ) {
809        let mut context = context.switch_fragment(Fragment::Casting);
810        out.push_str("CAST(");
811        expr.write_query(self.as_dyn(), &mut context.current, out);
812        out.push_str(" AS ");
813        ty.write_query(self.as_dyn(), &mut context.current, out);
814        out.push(')');
815    }
816
817    /// Render ordered expression inside ORDER BY.
818    fn write_ordered(
819        &self,
820        context: &mut Context,
821        out: &mut DynQuery,
822        value: &Ordered<&dyn Expression>,
823    ) {
824        value.expression.write_query(self.as_dyn(), context, out);
825        if context.fragment == Fragment::SqlSelectOrderBy {
826            let _ = write!(
827                out,
828                " {}",
829                match value.order {
830                    Order::ASC => "ASC",
831                    Order::DESC => "DESC",
832                }
833            );
834        }
835    }
836
837    /// Render join keyword(s) for the given join type.
838    fn write_join_type(&self, _context: &mut Context, out: &mut DynQuery, join_type: &JoinType) {
839        out.push_str(match &join_type {
840            JoinType::Default => "JOIN",
841            JoinType::Inner => "INNER JOIN",
842            JoinType::Outer => "OUTER JOIN",
843            JoinType::Left => "LEFT JOIN",
844            JoinType::Right => "RIGHT JOIN",
845            JoinType::Cross => "CROSS JOIN",
846            JoinType::Natural => "NATURAL JOIN",
847        });
848    }
849
850    /// Render a JOIN clause.
851    fn write_join(
852        &self,
853        context: &mut Context,
854        out: &mut DynQuery,
855        join: &Join<&dyn Dataset, &dyn Dataset, &dyn Expression>,
856    ) {
857        let mut context = context.switch_fragment(Fragment::SqlJoin);
858        context.current.qualify_columns = true;
859        join.lhs
860            .write_table_name(self.as_dyn(), &mut context.current, out);
861        out.push(' ');
862        self.write_join_type(&mut context.current, out, &join.join);
863        out.push(' ');
864        join.rhs
865            .write_table_name(self.as_dyn(), &mut context.current, out);
866        if let Some(on) = &join.on {
867            out.push_str(" ON ");
868            on.write_query(self.as_dyn(), &mut context.current, out);
869        }
870    }
871
872    /// Emit BEGIN statement.
873    fn write_transaction_begin(&self, out: &mut DynQuery) {
874        out.push_str("BEGIN;");
875    }
876
877    /// Emit COMMIT statement.
878    fn write_transaction_commit(&self, out: &mut DynQuery) {
879        out.push_str("COMMIT;");
880    }
881
882    /// Emit ROLLBACK statement.
883    fn write_transaction_rollback(&self, out: &mut DynQuery) {
884        out.push_str("ROLLBACK;");
885    }
886
887    /// Emit CREATE SCHEMA.
888    fn write_create_schema<E>(&self, out: &mut DynQuery, if_not_exists: bool)
889    where
890        Self: Sized,
891        E: Entity,
892    {
893        let table = E::table();
894        out.buffer().reserve(32 + table.schema.len());
895        if !out.is_empty() {
896            out.push('\n');
897        }
898        out.push_str("CREATE SCHEMA ");
899        let mut context = Context::new(Fragment::SqlCreateSchema, E::qualified_columns());
900        if if_not_exists {
901            out.push_str("IF NOT EXISTS ");
902        }
903        self.write_identifier(&mut context, out, &table.schema, true);
904        out.push(';');
905    }
906
907    /// Emit DROP SCHEMA.
908    fn write_drop_schema<E>(&self, out: &mut DynQuery, if_exists: bool)
909    where
910        Self: Sized,
911        E: Entity,
912    {
913        let mut context = Context::new(Fragment::SqlDropSchema, E::qualified_columns());
914        let table = E::table();
915        out.buffer().reserve(32 + table.schema.len());
916        if !out.is_empty() {
917            out.push('\n');
918        }
919        out.push_str("DROP SCHEMA ");
920        if if_exists {
921            out.push_str("IF EXISTS ");
922        }
923        self.write_identifier(&mut context, out, &table.schema, true);
924        out.push(';');
925    }
926
927    /// Emit CREATE TABLE with columns, constraints & comments.
928    fn write_create_table<E>(&self, out: &mut DynQuery, if_not_exists: bool)
929    where
930        Self: Sized,
931        E: Entity,
932    {
933        let mut context = Context::new(Fragment::SqlCreateTable, E::qualified_columns());
934        let table = E::table();
935        let estimated = 128 + E::columns().len() * 64 + E::primary_key_def().len() * 24;
936        out.buffer().reserve(estimated);
937        if !out.is_empty() {
938            out.push('\n');
939        }
940        out.push_str("CREATE TABLE ");
941        if if_not_exists {
942            out.push_str("IF NOT EXISTS ");
943        }
944        self.write_table_ref(&mut context, out, table);
945        out.push_str(" (\n");
946        separated_by(
947            out,
948            E::columns(),
949            |out, col| {
950                self.write_create_table_column_fragment(&mut context, out, col);
951            },
952            ",\n",
953        );
954        let pk = E::primary_key_def();
955        if pk.len() > 1 {
956            self.write_create_table_primary_key_fragment(&mut context, out, pk.iter().map(|v| *v));
957        }
958        for unique in E::unique_defs() {
959            if unique.len() > 1 {
960                out.push_str(",\nUNIQUE (");
961                separated_by(
962                    out,
963                    unique,
964                    |out, col| {
965                        self.write_identifier(
966                            &mut context
967                                .switch_fragment(Fragment::SqlCreateTableUnique)
968                                .current,
969                            out,
970                            col.name(),
971                            true,
972                        );
973                    },
974                    ", ",
975                );
976                out.push(')');
977            }
978        }
979        let foreign_keys = E::columns().iter().filter(|c| c.references.is_some());
980        separated_by(
981            out,
982            foreign_keys,
983            |out, column| {
984                let references = column.references.as_ref().unwrap();
985                out.push_str(",\nFOREIGN KEY (");
986                self.write_identifier(&mut context, out, &column.name(), true);
987                out.push_str(") REFERENCES ");
988                self.write_table_ref(&mut context, out, &references.table());
989                out.push('(');
990                self.write_column_ref(&mut context, out, references);
991                out.push(')');
992                if let Some(on_delete) = &column.on_delete {
993                    out.push_str(" ON DELETE ");
994                    self.write_create_table_references_action(&mut context, out, on_delete);
995                }
996                if let Some(on_update) = &column.on_update {
997                    out.push_str(" ON UPDATE ");
998                    self.write_create_table_references_action(&mut context, out, on_update);
999                }
1000            },
1001            "",
1002        );
1003        out.push_str(");");
1004        self.write_column_comments_statements::<E>(&mut context, out);
1005    }
1006
1007    /// Emit single column definition fragment.
1008    fn write_create_table_column_fragment(
1009        &self,
1010        context: &mut Context,
1011        out: &mut DynQuery,
1012        column: &ColumnDef,
1013    ) where
1014        Self: Sized,
1015    {
1016        self.write_identifier(context, out, &column.name(), true);
1017        out.push(' ');
1018        let len = out.len();
1019        self.write_column_overridden_type(context, out, column, &column.column_type);
1020        let didnt_write_type = out.len() == len;
1021        if didnt_write_type {
1022            SqlWriter::write_column_type(self, context, out, &column.value);
1023        }
1024        if !column.nullable && column.primary_key == PrimaryKeyType::None {
1025            out.push_str(" NOT NULL");
1026        }
1027        if column.default.is_set() {
1028            out.push_str(" DEFAULT ");
1029            column.default.write_query(self.as_dyn(), context, out);
1030        }
1031        if column.primary_key == PrimaryKeyType::PrimaryKey {
1032            // Composite primary key will be printed elsewhere
1033            out.push_str(" PRIMARY KEY");
1034        }
1035        if column.unique && column.primary_key != PrimaryKeyType::PrimaryKey {
1036            out.push_str(" UNIQUE");
1037        }
1038        if !column.comment.is_empty() {
1039            self.write_column_comment_inline(context, out, column);
1040        }
1041    }
1042
1043    /// Write PRIMARY KEY constraint.
1044    fn write_create_table_primary_key_fragment<'a, It>(
1045        &self,
1046        context: &mut Context,
1047        out: &mut DynQuery,
1048        primary_key: It,
1049    ) where
1050        Self: Sized,
1051        It: IntoIterator<Item = &'a ColumnDef>,
1052        It::IntoIter: Clone,
1053    {
1054        out.push_str(",\nPRIMARY KEY (");
1055        separated_by(
1056            out,
1057            primary_key,
1058            |out, col| {
1059                self.write_identifier(
1060                    &mut context
1061                        .switch_fragment(Fragment::SqlCreateTablePrimaryKey)
1062                        .current,
1063                    out,
1064                    col.name(),
1065                    true,
1066                );
1067            },
1068            ", ",
1069        );
1070        out.push(')');
1071    }
1072
1073    /// Write referential action.
1074    fn write_create_table_references_action(
1075        &self,
1076        _context: &mut Context,
1077        out: &mut DynQuery,
1078        action: &Action,
1079    ) {
1080        out.push_str(match action {
1081            Action::NoAction => "NO ACTION",
1082            Action::Restrict => "RESTRICT",
1083            Action::Cascade => "CASCADE",
1084            Action::SetNull => "SET NULL",
1085            Action::SetDefault => "SET DEFAULT",
1086        });
1087    }
1088
1089    fn write_column_comment_inline(
1090        &self,
1091        _context: &mut Context,
1092        _out: &mut DynQuery,
1093        _column: &ColumnDef,
1094    ) where
1095        Self: Sized,
1096    {
1097    }
1098
1099    /// Write column comments.
1100    fn write_column_comments_statements<E>(&self, context: &mut Context, out: &mut DynQuery)
1101    where
1102        Self: Sized,
1103        E: Entity,
1104    {
1105        let mut context = context.switch_fragment(Fragment::SqlCommentOnColumn);
1106        context.current.qualify_columns = true;
1107        for c in E::columns().iter().filter(|c| !c.comment.is_empty()) {
1108            out.push_str("\nCOMMENT ON COLUMN ");
1109            self.write_column_ref(&mut context.current, out, c.into());
1110            out.push_str(" IS ");
1111            self.write_string(&mut context.current, out, c.comment);
1112            out.push(';');
1113        }
1114    }
1115
1116    /// Write DROP TABLE statement.
1117    fn write_drop_table<E>(&self, out: &mut DynQuery, if_exists: bool)
1118    where
1119        Self: Sized,
1120        E: Entity,
1121    {
1122        let table = E::table();
1123        out.buffer()
1124            .reserve(24 + table.schema.len() + table.name.len());
1125        if !out.is_empty() {
1126            out.push('\n');
1127        }
1128        out.push_str("DROP TABLE ");
1129        let mut context = Context::new(Fragment::SqlDropTable, E::qualified_columns());
1130        if if_exists {
1131            out.push_str("IF EXISTS ");
1132        }
1133        self.write_table_ref(&mut context, out, table);
1134        out.push(';');
1135    }
1136
1137    /// Write SELECT statement.
1138    fn write_select<'a, Data>(&self, out: &mut DynQuery, query: &impl SelectQuery<Data>)
1139    where
1140        Self: Sized,
1141        Data: Dataset + 'a,
1142    {
1143        let Some(from) = query.get_from() else {
1144            log::error!("The query does not have the FROM clause");
1145            return;
1146        };
1147        let columns = query.get_select();
1148        let columns_count = columns.clone().into_iter().count();
1149        out.buffer().reserve(128 + columns_count * 32);
1150        if !out.is_empty() {
1151            out.push('\n');
1152        }
1153        out.push_str("SELECT ");
1154        let mut context = Context::new(Fragment::SqlSelect, Data::qualified_columns());
1155        if columns_count != 0 {
1156            separated_by(
1157                out,
1158                columns.clone(),
1159                |out, col| {
1160                    col.write_query(self, &mut context, out);
1161                },
1162                ", ",
1163            );
1164        } else {
1165            out.push('*');
1166        }
1167        out.push_str("\nFROM ");
1168        from.write_table_name(
1169            self,
1170            &mut context.switch_fragment(Fragment::SqlSelectFrom).current,
1171            out,
1172        );
1173        if let Some(condition) = query.get_where()
1174            && !condition.accept_visitor(&mut IsTrue, self, &mut context, out)
1175        {
1176            out.push_str("\nWHERE ");
1177            condition.write_query(
1178                self,
1179                &mut context.switch_fragment(Fragment::SqlSelectWhere).current,
1180                out,
1181            );
1182        }
1183        let mut group_by = query.get_group_by().peekable();
1184        if group_by.peek().is_some() {
1185            out.push_str("\nGROUP BY ");
1186            let mut context = context.switch_fragment(Fragment::SqlSelectGroupBy);
1187            separated_by(
1188                out,
1189                group_by,
1190                |out, col| {
1191                    col.write_query(self, &mut context.current, out);
1192                },
1193                ", ",
1194            );
1195        }
1196        if let Some(having) = query.get_having() {
1197            out.push_str("\nHAVING ");
1198            having.write_query(
1199                self,
1200                &mut context.switch_fragment(Fragment::SqlSelectHaving).current,
1201                out,
1202            );
1203        }
1204        let mut order_by = query.get_order_by().peekable();
1205        if order_by.peek().is_some() {
1206            out.push_str("\nORDER BY ");
1207            let mut context = context.switch_fragment(Fragment::SqlSelectOrderBy);
1208            separated_by(
1209                out,
1210                order_by,
1211                |out, col| {
1212                    col.write_query(self, &mut context.current, out);
1213                },
1214                ", ",
1215            );
1216        }
1217        if let Some(limit) = query.get_limit() {
1218            let _ = write!(out, "\nLIMIT {limit}");
1219        }
1220        out.push(';');
1221    }
1222
1223    /// Write INSERT statement.
1224    fn write_insert<'b, E>(
1225        &self,
1226        out: &mut DynQuery,
1227        entities: impl IntoIterator<Item = &'b E>,
1228        update: bool,
1229    ) where
1230        Self: Sized,
1231        E: Entity + 'b,
1232    {
1233        let table = E::table();
1234        let mut entities = entities.into_iter().peekable();
1235        if entities.peek().is_none() {
1236            return;
1237        };
1238        let cols = E::columns().len();
1239        out.buffer().reserve(128 + cols * 32);
1240        if !out.is_empty() {
1241            out.push('\n');
1242        }
1243        out.push_str("INSERT INTO ");
1244        let mut context = Context::new(Fragment::SqlInsertInto, E::qualified_columns());
1245        self.write_table_ref(&mut context, out, table);
1246        out.push_str(" (");
1247        separated_by(
1248            out,
1249            E::columns().iter(),
1250            |out, col| {
1251                self.write_identifier(&mut context, out, col.name(), true);
1252            },
1253            ", ",
1254        );
1255        out.push_str(") VALUES");
1256        let mut context = context.switch_fragment(Fragment::SqlInsertIntoValues);
1257        separated_by(
1258            out,
1259            entities,
1260            |out, entity| {
1261                out.push_str("\n(");
1262                entity.write_query(self.as_dyn(), &mut context.current, out);
1263                out.push(')');
1264            },
1265            ",",
1266        );
1267        if update {
1268            self.write_insert_update_fragment::<E>(&mut context.current, out, E::columns().iter());
1269        }
1270        out.push(';');
1271    }
1272
1273    /// Write ON CONFLICT DO UPDATE fragment for upsert.
1274    fn write_insert_update_fragment<'a, E>(
1275        &self,
1276        context: &mut Context,
1277        out: &mut DynQuery,
1278        columns: impl Iterator<Item = &'a ColumnDef> + Clone,
1279    ) where
1280        Self: Sized,
1281        E: Entity,
1282    {
1283        let pk = E::primary_key_def();
1284        if pk.is_empty() {
1285            return;
1286        }
1287        out.push_str("\nON CONFLICT");
1288        context.fragment = Fragment::SqlInsertIntoOnConflict;
1289        out.push_str(" (");
1290        separated_by(
1291            out,
1292            pk,
1293            |out, col| {
1294                self.write_identifier(context, out, col.name(), true);
1295            },
1296            ", ",
1297        );
1298        out.push(')');
1299        let mut update_cols = columns
1300            .filter(|c| c.primary_key == PrimaryKeyType::None)
1301            .peekable();
1302        if update_cols.peek().is_some() {
1303            out.push_str(" DO UPDATE SET\n");
1304            separated_by(
1305                out,
1306                update_cols,
1307                |out, col| {
1308                    self.write_identifier(context, out, col.name(), true);
1309                    out.push_str(" = EXCLUDED.");
1310                    self.write_identifier(context, out, col.name(), true);
1311                },
1312                ",\n",
1313            );
1314        } else {
1315            out.push_str(" DO NOTHING");
1316        }
1317    }
1318
1319    /// Write DELETE statement.
1320    fn write_delete<E>(&self, out: &mut DynQuery, condition: impl Expression)
1321    where
1322        Self: Sized,
1323        E: Entity,
1324    {
1325        let table = E::table();
1326        out.buffer().reserve(128);
1327        if !out.is_empty() {
1328            out.push('\n');
1329        }
1330        out.push_str("DELETE FROM ");
1331        let mut context = Context::new(Fragment::SqlDeleteFrom, E::qualified_columns());
1332        self.write_table_ref(&mut context, out, table);
1333        out.push_str("\nWHERE ");
1334        condition.write_query(
1335            self,
1336            &mut context
1337                .switch_fragment(Fragment::SqlDeleteFromWhere)
1338                .current,
1339            out,
1340        );
1341        out.push(';');
1342    }
1343}
1344
1345/// Generic SQL writer.
1346pub struct GenericSqlWriter;
1347impl GenericSqlWriter {
1348    /// New generic writer.
1349    pub fn new() -> Self {
1350        Self {}
1351    }
1352}
1353impl SqlWriter for GenericSqlWriter {
1354    fn as_dyn(&self) -> &dyn SqlWriter {
1355        self
1356    }
1357}