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