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