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: &Vec<(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                self.write_identifier(context, out, &v.join(self.separator()), false)
714            }
715            Operand::LitList(v) => self.write_list(
716                context,
717                out,
718                &mut v.iter().map(|v| v as &dyn Expression),
719                None,
720                false,
721            ),
722            Operand::LitTuple(v) => {
723                self.write_tuple(context, out, &mut v.iter().map(|v| v as &dyn Expression))
724            }
725            Operand::Type(v) => self.write_column_type(context, out, v),
726            Operand::Variable(v) => self.write_value(context, out, v),
727            Operand::Value(v) => self.write_value(context, out, v),
728            Operand::Call(f, args) => self.write_function(context, out, f, args),
729            Operand::Asterisk => drop(out.push('*')),
730            Operand::QuestionMark => self.write_question_mark(context, out),
731            Operand::CurrentTimestampMs => self.write_current_timestamp_ms(context, out),
732        };
733    }
734
735    fn write_question_mark(&self, context: &mut Context, out: &mut DynQuery) {
736        context.counter += 1;
737        out.push('?');
738    }
739
740    fn write_current_timestamp_ms(&self, _context: &mut Context, out: &mut DynQuery) {
741        out.push_str("NOW()");
742    }
743
744    fn write_unary_op(
745        &self,
746        context: &mut Context,
747        out: &mut DynQuery,
748        value: &UnaryOp<&dyn Expression>,
749    ) {
750        match value.op {
751            UnaryOpType::Negative => out.push('-'),
752            UnaryOpType::Not => out.push_str("NOT "),
753        };
754        possibly_parenthesized!(
755            out,
756            value.arg.precedence(self.as_dyn()) <= self.expression_unary_op_precedence(&value.op),
757            value.arg.write_query(self.as_dyn(), context, out)
758        );
759    }
760
761    /// Render binary operator expression handling precedence and parenthesis.
762    fn write_binary_op(
763        &self,
764        context: &mut Context,
765        out: &mut DynQuery,
766        value: &BinaryOp<&dyn Expression, &dyn Expression>,
767    ) {
768        if value.op == BinaryOpType::Alias && context.fragment == Fragment::SqlSelectOrderBy {
769            return value.lhs.write_query(self.as_dyn(), context, out);
770        }
771        let (prefix, infix, suffix, lhs_parenthesized, rhs_parenthesized) =
772            self.expression_binary_op_fragments(context, value.op);
773        let precedence = self.expression_binary_op_precedence(&value.op);
774        out.push_str(prefix);
775        possibly_parenthesized!(
776            out,
777            !lhs_parenthesized && value.lhs.precedence(self.as_dyn()) < precedence,
778            value.lhs.write_query(self.as_dyn(), context, out)
779        );
780        out.push_str(infix);
781        let mut context = context.switch_fragment(if value.op == BinaryOpType::Alias {
782            Fragment::Aliasing
783        } else {
784            context.fragment
785        });
786        possibly_parenthesized!(
787            out,
788            !rhs_parenthesized && value.rhs.precedence(self.as_dyn()) <= precedence,
789            value
790                .rhs
791                .write_query(self.as_dyn(), &mut context.current, out)
792        );
793        out.push_str(suffix);
794    }
795
796    fn write_cast(
797        &self,
798        context: &mut Context,
799        out: &mut DynQuery,
800        expr: &dyn Expression,
801        ty: &dyn Expression,
802    ) {
803        let mut context = context.switch_fragment(Fragment::Casting);
804        out.push_str("CAST(");
805        expr.write_query(self.as_dyn(), &mut context.current, out);
806        out.push_str(" AS ");
807        ty.write_query(self.as_dyn(), &mut context.current, out);
808        out.push(')');
809    }
810
811    /// Render ordered expression inside ORDER BY.
812    fn write_ordered(
813        &self,
814        context: &mut Context,
815        out: &mut DynQuery,
816        value: &Ordered<&dyn Expression>,
817    ) {
818        value.expression.write_query(self.as_dyn(), context, out);
819        if context.fragment == Fragment::SqlSelectOrderBy {
820            let _ = write!(
821                out,
822                " {}",
823                match value.order {
824                    Order::ASC => "ASC",
825                    Order::DESC => "DESC",
826                }
827            );
828        }
829    }
830
831    /// Render join keyword(s) for the given join type.
832    fn write_join_type(&self, _context: &mut Context, out: &mut DynQuery, join_type: &JoinType) {
833        out.push_str(match &join_type {
834            JoinType::Default => "JOIN",
835            JoinType::Inner => "INNER JOIN",
836            JoinType::Outer => "OUTER JOIN",
837            JoinType::Left => "LEFT JOIN",
838            JoinType::Right => "RIGHT JOIN",
839            JoinType::Cross => "CROSS JOIN",
840            JoinType::Natural => "NATURAL JOIN",
841        });
842    }
843
844    /// Render a JOIN clause.
845    fn write_join(
846        &self,
847        context: &mut Context,
848        out: &mut DynQuery,
849        join: &Join<&dyn Dataset, &dyn Dataset, &dyn Expression>,
850    ) {
851        let mut context = context.switch_fragment(Fragment::SqlJoin);
852        context.current.qualify_columns = true;
853        join.lhs
854            .write_query(self.as_dyn(), &mut context.current, out);
855        out.push(' ');
856        self.write_join_type(&mut context.current, out, &join.join);
857        out.push(' ');
858        join.rhs
859            .write_query(self.as_dyn(), &mut context.current, out);
860        if let Some(on) = &join.on {
861            out.push_str(" ON ");
862            on.write_query(self.as_dyn(), &mut context.current, out);
863        }
864    }
865
866    /// Emit BEGIN statement.
867    fn write_transaction_begin(&self, out: &mut DynQuery) {
868        out.push_str("BEGIN;");
869    }
870
871    /// Emit COMMIT statement.
872    fn write_transaction_commit(&self, out: &mut DynQuery) {
873        out.push_str("COMMIT;");
874    }
875
876    /// Emit ROLLBACK statement.
877    fn write_transaction_rollback(&self, out: &mut DynQuery) {
878        out.push_str("ROLLBACK;");
879    }
880
881    /// Emit CREATE SCHEMA.
882    fn write_create_schema<E>(&self, out: &mut DynQuery, if_not_exists: bool)
883    where
884        Self: Sized,
885        E: Entity,
886    {
887        let table = E::table();
888        out.buffer().reserve(32 + table.schema.len());
889        if !out.is_empty() {
890            out.push('\n');
891        }
892        out.push_str("CREATE SCHEMA ");
893        let mut context = Context::new(Fragment::SqlCreateSchema, E::qualified_columns());
894        if if_not_exists {
895            out.push_str("IF NOT EXISTS ");
896        }
897        self.write_identifier(&mut context, out, &table.schema, true);
898        out.push(';');
899    }
900
901    /// Emit DROP SCHEMA.
902    fn write_drop_schema<E>(&self, out: &mut DynQuery, if_exists: bool)
903    where
904        Self: Sized,
905        E: Entity,
906    {
907        let mut context = Context::new(Fragment::SqlDropSchema, E::qualified_columns());
908        let table = E::table();
909        out.buffer().reserve(32 + table.schema.len());
910        if !out.is_empty() {
911            out.push('\n');
912        }
913        out.push_str("DROP SCHEMA ");
914        if if_exists {
915            out.push_str("IF EXISTS ");
916        }
917        self.write_identifier(&mut context, out, &table.schema, true);
918        out.push(';');
919    }
920
921    /// Emit CREATE TABLE with columns, constraints & comments.
922    fn write_create_table<E>(&self, out: &mut DynQuery, if_not_exists: bool)
923    where
924        Self: Sized,
925        E: Entity,
926    {
927        let mut context = Context::new(Fragment::SqlCreateTable, E::qualified_columns());
928        let table = E::table();
929        let estimated = 128 + E::columns().len() * 64 + E::primary_key_def().len() * 24;
930        out.buffer().reserve(estimated);
931        if !out.is_empty() {
932            out.push('\n');
933        }
934        out.push_str("CREATE TABLE ");
935        if if_not_exists {
936            out.push_str("IF NOT EXISTS ");
937        }
938        self.write_table_ref(&mut context, out, table);
939        out.push_str(" (\n");
940        separated_by(
941            out,
942            E::columns(),
943            |out, col| {
944                self.write_create_table_column_fragment(&mut context, out, col);
945            },
946            ",\n",
947        );
948        let pk = E::primary_key_def();
949        if pk.len() > 1 {
950            self.write_create_table_primary_key_fragment(&mut context, out, pk.iter().map(|v| *v));
951        }
952        for unique in E::unique_defs() {
953            if unique.len() > 1 {
954                out.push_str(",\nUNIQUE (");
955                separated_by(
956                    out,
957                    unique,
958                    |out, col| {
959                        self.write_identifier(
960                            &mut context
961                                .switch_fragment(Fragment::SqlCreateTableUnique)
962                                .current,
963                            out,
964                            col.name(),
965                            true,
966                        );
967                    },
968                    ", ",
969                );
970                out.push(')');
971            }
972        }
973        let foreign_keys = E::columns().iter().filter(|c| c.references.is_some());
974        separated_by(
975            out,
976            foreign_keys,
977            |out, column| {
978                let references = column.references.as_ref().unwrap();
979                out.push_str(",\nFOREIGN KEY (");
980                self.write_identifier(&mut context, out, &column.name(), true);
981                out.push_str(") REFERENCES ");
982                self.write_table_ref(&mut context, out, &references.table());
983                out.push('(');
984                self.write_column_ref(&mut context, out, references);
985                out.push(')');
986                if let Some(on_delete) = &column.on_delete {
987                    out.push_str(" ON DELETE ");
988                    self.write_create_table_references_action(&mut context, out, on_delete);
989                }
990                if let Some(on_update) = &column.on_update {
991                    out.push_str(" ON UPDATE ");
992                    self.write_create_table_references_action(&mut context, out, on_update);
993                }
994            },
995            "",
996        );
997        out.push_str(");");
998        self.write_column_comments_statements::<E>(&mut context, out);
999    }
1000
1001    /// Emit single column definition fragment.
1002    fn write_create_table_column_fragment(
1003        &self,
1004        context: &mut Context,
1005        out: &mut DynQuery,
1006        column: &ColumnDef,
1007    ) where
1008        Self: Sized,
1009    {
1010        self.write_identifier(context, out, &column.name(), true);
1011        out.push(' ');
1012        let len = out.len();
1013        self.write_column_overridden_type(context, out, column, &column.column_type);
1014        let didnt_write_type = out.len() == len;
1015        if didnt_write_type {
1016            SqlWriter::write_column_type(self, context, out, &column.value);
1017        }
1018        if !column.nullable && column.primary_key == PrimaryKeyType::None {
1019            out.push_str(" NOT NULL");
1020        }
1021        if column.default.is_set() {
1022            out.push_str(" DEFAULT ");
1023            column.default.write_query(self.as_dyn(), context, out);
1024        }
1025        if column.primary_key == PrimaryKeyType::PrimaryKey {
1026            // Composite primary key will be printed elsewhere
1027            out.push_str(" PRIMARY KEY");
1028        }
1029        if column.unique && column.primary_key != PrimaryKeyType::PrimaryKey {
1030            out.push_str(" UNIQUE");
1031        }
1032        if !column.comment.is_empty() {
1033            self.write_column_comment_inline(context, out, column);
1034        }
1035    }
1036
1037    /// Write PRIMARY KEY constraint.
1038    fn write_create_table_primary_key_fragment<'a, It>(
1039        &self,
1040        context: &mut Context,
1041        out: &mut DynQuery,
1042        primary_key: It,
1043    ) where
1044        Self: Sized,
1045        It: IntoIterator<Item = &'a ColumnDef>,
1046        It::IntoIter: Clone,
1047    {
1048        out.push_str(",\nPRIMARY KEY (");
1049        separated_by(
1050            out,
1051            primary_key,
1052            |out, col| {
1053                self.write_identifier(
1054                    &mut context
1055                        .switch_fragment(Fragment::SqlCreateTablePrimaryKey)
1056                        .current,
1057                    out,
1058                    col.name(),
1059                    true,
1060                );
1061            },
1062            ", ",
1063        );
1064        out.push(')');
1065    }
1066
1067    /// Write referential action.
1068    fn write_create_table_references_action(
1069        &self,
1070        _context: &mut Context,
1071        out: &mut DynQuery,
1072        action: &Action,
1073    ) {
1074        out.push_str(match action {
1075            Action::NoAction => "NO ACTION",
1076            Action::Restrict => "RESTRICT",
1077            Action::Cascade => "CASCADE",
1078            Action::SetNull => "SET NULL",
1079            Action::SetDefault => "SET DEFAULT",
1080        });
1081    }
1082
1083    fn write_column_comment_inline(
1084        &self,
1085        _context: &mut Context,
1086        _out: &mut DynQuery,
1087        _column: &ColumnDef,
1088    ) where
1089        Self: Sized,
1090    {
1091    }
1092
1093    /// Write column comments.
1094    fn write_column_comments_statements<E>(&self, context: &mut Context, out: &mut DynQuery)
1095    where
1096        Self: Sized,
1097        E: Entity,
1098    {
1099        let mut context = context.switch_fragment(Fragment::SqlCommentOnColumn);
1100        context.current.qualify_columns = true;
1101        for c in E::columns().iter().filter(|c| !c.comment.is_empty()) {
1102            out.push_str("\nCOMMENT ON COLUMN ");
1103            self.write_column_ref(&mut context.current, out, c.into());
1104            out.push_str(" IS ");
1105            self.write_string(&mut context.current, out, c.comment);
1106            out.push(';');
1107        }
1108    }
1109
1110    /// Write DROP TABLE statement.
1111    fn write_drop_table<E>(&self, out: &mut DynQuery, if_exists: bool)
1112    where
1113        Self: Sized,
1114        E: Entity,
1115    {
1116        let table = E::table();
1117        out.buffer()
1118            .reserve(24 + table.schema.len() + table.name.len());
1119        if !out.is_empty() {
1120            out.push('\n');
1121        }
1122        out.push_str("DROP TABLE ");
1123        let mut context = Context::new(Fragment::SqlDropTable, E::qualified_columns());
1124        if if_exists {
1125            out.push_str("IF EXISTS ");
1126        }
1127        self.write_table_ref(&mut context, out, table);
1128        out.push(';');
1129    }
1130
1131    /// Write SELECT statement.
1132    fn write_select<'a, Data>(&self, out: &mut DynQuery, query: &impl SelectQuery<Data>)
1133    where
1134        Self: Sized,
1135        Data: Dataset + 'a,
1136    {
1137        let Some(from) = query.get_from() else {
1138            log::error!("The query does not have the FROM clause");
1139            return;
1140        };
1141        let columns = query.get_select();
1142        let columns_count = columns.clone().into_iter().count();
1143        out.buffer().reserve(128 + columns_count * 32);
1144        if !out.is_empty() {
1145            out.push('\n');
1146        }
1147        out.push_str("SELECT ");
1148        let mut context = Context::new(Fragment::SqlSelect, Data::qualified_columns());
1149        if columns_count != 0 {
1150            separated_by(
1151                out,
1152                columns.clone(),
1153                |out, col| {
1154                    col.write_query(self, &mut context, out);
1155                },
1156                ", ",
1157            );
1158        } else {
1159            out.push('*');
1160        }
1161        out.push_str("\nFROM ");
1162        from.write_query(
1163            self,
1164            &mut context.switch_fragment(Fragment::SqlSelectFrom).current,
1165            out,
1166        );
1167        if let Some(condition) = query.get_where()
1168            && !condition.accept_visitor(&mut IsTrue, self, &mut context, out)
1169        {
1170            out.push_str("\nWHERE ");
1171            condition.write_query(
1172                self,
1173                &mut context.switch_fragment(Fragment::SqlSelectWhere).current,
1174                out,
1175            );
1176        }
1177        let mut group_by = query.get_group_by().peekable();
1178        if group_by.peek().is_some() {
1179            out.push_str("\nGROUP BY ");
1180            let mut context = context.switch_fragment(Fragment::SqlSelectGroupBy);
1181            separated_by(
1182                out,
1183                group_by,
1184                |out, col| {
1185                    col.write_query(self, &mut context.current, out);
1186                },
1187                ", ",
1188            );
1189        }
1190        if let Some(having) = query.get_having() {
1191            out.push_str("\nHAVING ");
1192            having.write_query(
1193                self,
1194                &mut context.switch_fragment(Fragment::SqlSelectHaving).current,
1195                out,
1196            );
1197        }
1198        let mut order_by = query.get_order_by().peekable();
1199        if order_by.peek().is_some() {
1200            out.push_str("\nORDER BY ");
1201            let mut context = context.switch_fragment(Fragment::SqlSelectOrderBy);
1202            separated_by(
1203                out,
1204                order_by,
1205                |out, col| {
1206                    col.write_query(self, &mut context.current, out);
1207                },
1208                ", ",
1209            );
1210        }
1211        if let Some(limit) = query.get_limit() {
1212            let _ = write!(out, "\nLIMIT {limit}");
1213        }
1214        out.push(';');
1215    }
1216
1217    /// Write INSERT statement.
1218    fn write_insert<'b, E>(
1219        &self,
1220        out: &mut DynQuery,
1221        entities: impl IntoIterator<Item = &'b E>,
1222        update: bool,
1223    ) where
1224        Self: Sized,
1225        E: Entity + 'b,
1226    {
1227        let table = E::table();
1228        let mut entities = entities.into_iter().peekable();
1229        if entities.peek().is_none() {
1230            return;
1231        };
1232        let cols = E::columns().len();
1233        out.buffer().reserve(128 + cols * 32);
1234        if !out.is_empty() {
1235            out.push('\n');
1236        }
1237        out.push_str("INSERT INTO ");
1238        let mut context = Context::new(Fragment::SqlInsertInto, E::qualified_columns());
1239        self.write_table_ref(&mut context, out, table);
1240        out.push_str(" (");
1241        separated_by(
1242            out,
1243            E::columns().iter(),
1244            |out, col| {
1245                self.write_identifier(&mut context, out, col.name(), true);
1246            },
1247            ", ",
1248        );
1249        out.push_str(") VALUES");
1250        let mut context = context.switch_fragment(Fragment::SqlInsertIntoValues);
1251        separated_by(
1252            out,
1253            entities,
1254            |out, entity| {
1255                out.push_str("\n(");
1256                separated_by(
1257                    out,
1258                    entity.row_values(),
1259                    |out, value| self.write_value(&mut context.current, out, &value),
1260                    ", ",
1261                );
1262                out.push(')');
1263            },
1264            ",",
1265        );
1266        if update {
1267            self.write_insert_update_fragment::<E>(&mut context.current, out, E::columns().iter());
1268        }
1269        out.push(';');
1270    }
1271
1272    /// Write ON CONFLICT DO UPDATE fragment for upsert.
1273    fn write_insert_update_fragment<'a, E>(
1274        &self,
1275        context: &mut Context,
1276        out: &mut DynQuery,
1277        columns: impl Iterator<Item = &'a ColumnDef> + Clone,
1278    ) where
1279        Self: Sized,
1280        E: Entity,
1281    {
1282        let pk = E::primary_key_def();
1283        if pk.len() == 0 {
1284            return;
1285        }
1286        out.push_str("\nON CONFLICT");
1287        context.fragment = Fragment::SqlInsertIntoOnConflict;
1288        if pk.len() > 0 {
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        }
1300        let mut update_cols = columns
1301            .filter(|c| c.primary_key == PrimaryKeyType::None)
1302            .peekable();
1303        if update_cols.peek().is_some() {
1304            out.push_str(" DO UPDATE SET\n");
1305            separated_by(
1306                out,
1307                update_cols,
1308                |out, col| {
1309                    self.write_identifier(context, out, col.name(), true);
1310                    out.push_str(" = EXCLUDED.");
1311                    self.write_identifier(context, out, col.name(), true);
1312                },
1313                ",\n",
1314            );
1315        } else {
1316            out.push_str(" DO NOTHING");
1317        }
1318    }
1319
1320    /// Write DELETE statement.
1321    fn write_delete<E>(&self, out: &mut DynQuery, condition: impl Expression)
1322    where
1323        Self: Sized,
1324        E: Entity,
1325    {
1326        let table = E::table();
1327        out.buffer().reserve(128);
1328        if !out.is_empty() {
1329            out.push('\n');
1330        }
1331        out.push_str("DELETE FROM ");
1332        let mut context = Context::new(Fragment::SqlDeleteFrom, E::qualified_columns());
1333        self.write_table_ref(&mut context, out, table);
1334        out.push_str("\nWHERE ");
1335        condition.write_query(
1336            self,
1337            &mut context
1338                .switch_fragment(Fragment::SqlDeleteFromWhere)
1339                .current,
1340            out,
1341        );
1342        out.push(';');
1343    }
1344}
1345
1346/// Generic SQL writer.
1347pub struct GenericSqlWriter;
1348impl GenericSqlWriter {
1349    /// New generic writer.
1350    pub fn new() -> Self {
1351        Self {}
1352    }
1353}
1354impl SqlWriter for GenericSqlWriter {
1355    fn as_dyn(&self) -> &dyn SqlWriter {
1356        self
1357    }
1358}