1use crate::ast::*;
7use crate::report::{Allowance, Entry, Options, ParamBinding, Report, Tier, Untranslatable};
8
9pub struct Ctx<'a> {
11 pub report: Report,
12 pub opts: &'a Options,
13 pub scopes: crate::schema::Scopes<'a>,
15 pub source: &'a str,
16 pub target: &'a str,
17 pub max_param: u32,
18 pub param_order: Vec<u32>,
19 pub in_upsert: bool,
21 pub(crate) upsert_table: Option<String>,
25 pub agg_order: Option<String>,
28 pub order_non_text: bool,
31 pub interval_notation: bool,
34 pub epoch_now: bool,
37 pub array_params: std::collections::BTreeMap<u32, ParamBinding>,
39 pub scalar_params: std::collections::BTreeSet<u32>,
41}
42
43impl<'a> Ctx<'a> {
44 pub fn new(opts: &'a Options, source: &'a str, target: &'a str) -> Self {
45 Ctx {
46 report: Report::default(),
47 opts,
48 scopes: crate::schema::Scopes::new(opts.schema.as_ref()),
49 source,
50 target,
51 max_param: 0,
52 param_order: Vec::new(),
53 in_upsert: false,
54 upsert_table: None,
55 agg_order: None,
56 order_non_text: false,
57 interval_notation: false,
58 epoch_now: false,
59 array_params: Default::default(),
60 scalar_params: Default::default(),
61 }
62 }
63
64 pub fn note(
67 &mut self,
68 construct: impl Into<String>,
69 tier: Tier,
70 note: impl Into<String>,
71 allowance: Option<Allowance>,
72 ) -> Result<(), Untranslatable> {
73 let construct = construct.into();
74 let note = note.into();
75 match tier {
76 Tier::Refused => Err(self.refuse(&construct, ¬e, &[])),
77 Tier::Conditional => {
78 let a = allowance.expect("a Conditional note must name its Allowance");
79 if self.source != self.target && !self.opts.allow.contains(&a) {
81 return Err(self.refuse(
82 &construct,
83 &format!("conditional: needs allowance `{}`: {}", a.name(), note),
84 &[],
85 ));
86 }
87 self.report.push(Entry {
88 construct,
89 tier,
90 note,
91 allowance: Some(a),
92 });
93 Ok(())
94 }
95 _ => {
96 self.report.push(Entry {
97 construct,
98 tier,
99 note,
100 allowance,
101 });
102 Ok(())
103 }
104 }
105 }
106
107 pub fn bind_array_param(&mut self, n: u32, binding: ParamBinding) {
109 self.array_params.insert(n, binding);
110 }
111
112 pub fn lenient_source(&self) -> bool {
115 matches!(self.source, "sqlite" | "mysql" | "mariadb")
116 }
117
118 pub fn refuse(&self, construct: &str, reason: &str, alternatives: &[&str]) -> Untranslatable {
119 Untranslatable {
120 construct: construct.to_string(),
121 source: self.source.to_string(),
122 target: self.target.to_string(),
123 reason: reason.to_string(),
124 alternatives: alternatives.iter().map(|s| s.to_string()).collect(),
125 }
126 }
127}
128
129type R<T> = Result<T, Untranslatable>;
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub enum StmtKind {
134 Insert,
135 Update,
136 Delete,
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub enum Escape<'a> {
142 None,
144 Default,
146 Custom(&'a str),
148}
149
150#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub enum DmlLimit {
154 Native,
156 RowIdSubquery(&'static str),
158}
159
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162pub enum DmlSources {
163 FromClause,
165 Join,
167 UpdateFromOnly,
169}
170
171pub trait Target {
172 fn name(&self) -> &'static str;
173
174 fn quote_ident(&self, s: &str) -> String {
175 format!("\"{}\"", s.replace('"', "\"\""))
176 }
177
178 fn string_literal(&self, s: &str) -> String {
179 format!("'{}'", s.replace('\'', "''"))
180 }
181
182 fn bytes_literal(&self, b: &[u8]) -> String {
184 let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
185 format!("'\\x{hex}'::bytea")
186 }
187
188 fn placeholder(&self, n: u32) -> String {
190 format!("${n}")
191 }
192
193 fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
194 Ok(if b { "TRUE" } else { "FALSE" }.to_string())
195 }
196
197 fn like(
199 &self,
200 lhs: &str,
201 rhs: &str,
202 negated: bool,
203 ci: bool,
204 esc: Escape<'_>,
205 ctx: &mut Ctx,
206 ) -> R<String> {
207 let kw = if ci { "ILIKE" } else { "LIKE" };
208 ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
209 let tail = match esc {
210 Escape::Default => String::new(), Escape::None => " ESCAPE ''".to_string(),
212 Escape::Custom(c) => format!(" ESCAPE {c}"),
213 };
214 Ok(format!(
215 "{lhs} {}{kw} {rhs}{tail}",
216 if negated { "NOT " } else { "" }
217 ))
218 }
219
220 fn regexp(&self, lhs: &str, rhs: &str, negated: bool, ctx: &mut Ctx) -> R<String> {
222 ctx.note(
223 "regexp",
224 Tier::Conditional,
225 "regular-expression syntax and case sensitivity differ between engines; exact only for \
226 patterns in the common subset",
227 Some(Allowance::RegexpFlavor),
228 )?;
229 Ok(format!("{lhs} {} {rhs}", if negated { "!~" } else { "~" }))
230 }
231
232 fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
234 if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
237 return Err(ctx.refuse(
238 &format!("fn:{}", f.name),
239 "no verified mapping for this function on this target yet",
240 &[],
241 ));
242 }
243 ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
244 let order = ctx.agg_order.take();
245 Ok(generic_call_ordered(
246 &f.name,
247 args,
248 f.distinct,
249 f.star,
250 order.as_deref(),
251 ))
252 }
253
254 fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
255 if ctx.lenient_source() {
256 ctx.note(
257 format!("cast.to_{}", ty.leaf()),
258 Tier::Conditional,
259 "the source casts leniently (a malformed value becomes 0); the target raises an error",
260 Some(Allowance::LenientCast),
261 )?;
262 } else {
263 ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
264 }
265 Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
266 }
267
268 fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
269 ctx.note("distinct_on", Tier::Exact, "", None)
270 }
271
272 fn group_by_rollup(&self, keys: &[String], ctx: &mut Ctx) -> R<String> {
275 ctx.note("group_by.rollup", Tier::Exact, "", None)?;
276 Ok(format!("ROLLUP ({})", keys.join(", ")))
277 }
278
279 fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
281 ctx.note("null_safe_eq", Tier::Exact, "", None)?;
282 Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
283 }
284
285 fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
288 ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
289 Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
290 }
291
292 fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
296 Ok(None)
297 }
298
299 fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
302 Err(ctx.refuse(
303 "extract.epoch",
304 "no mapping for the per-call wall clock",
305 &["bind the time as a parameter"],
306 ))
307 }
308
309 fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
312 ctx.note("array_literal", Tier::Exact, "", None)?;
313 Ok(format!("ARRAY[{}]", items.join(", ")))
314 }
315
316 fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
320 ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
321 }
322
323 fn series_as_recursive_cte(&self) -> bool {
326 false
327 }
328
329 fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
332 ctx.note("at_time_zone", Tier::Exact, "", None)
333 }
334
335 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
338 ctx.note("array_subquery", Tier::Exact, "", None)
339 }
340
341 fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
345 ctx.note(with_leaf(kind), Tier::Exact, "", None)
346 }
347
348 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
351 ctx.note("cte.data_modifying", Tier::Exact, "", None)
352 }
353
354 fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
358 note_row_lock_leaves(lock, ctx)
359 }
360
361 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
362 ctx.note("returning", Tier::Exact, "", None)
363 }
364
365 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
367 let mut s = String::new();
368 if let Some(l) = limit {
369 s.push_str(&format!(" LIMIT {l}"));
370 ctx.note("limit", Tier::Exact, "", None)?;
371 }
372 if let Some(o) = offset {
373 s.push_str(&format!(" OFFSET {o}"));
374 ctx.note("offset", Tier::Exact, "", None)?;
375 }
376 Ok(s)
377 }
378
379 fn join_tier(&self, _kind: JoinKind) -> Tier {
381 Tier::Exact
382 }
383
384 fn dml_sources(&self) -> DmlSources {
386 DmlSources::FromClause
387 }
388
389 fn dml_limit(&self) -> DmlLimit {
392 DmlLimit::RowIdSubquery("ctid")
393 }
394
395 fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
398 Ok(None)
399 }
400
401 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
404 ctx.note(name, Tier::Exact, "", None)
405 }
406
407 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
409 ctx.note("trim", Tier::Exact, "", None)?;
410 Ok(match (side, chars) {
411 (TrimSide::Both, None) => format!("TRIM({expr})"),
412 (s, c) => {
413 let kw = match s {
414 TrimSide::Both => "BOTH",
415 TrimSide::Leading => "LEADING",
416 TrimSide::Trailing => "TRAILING",
417 };
418 match c {
419 Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
420 None => format!("TRIM({kw} FROM {expr})"),
421 }
422 }
423 })
424 }
425
426 fn interval_arith(
429 &self,
430 _minus: bool,
431 _left: &str,
432 _parts: &[(String, String)],
433 _ctx: &mut Ctx,
434 ) -> R<Option<String>> {
435 Ok(None)
436 }
437
438 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
440 ctx.note(
441 if text { "json_get_text" } else { "json_get" },
442 Tier::Exact,
443 "",
444 None,
445 )?;
446 Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
447 }
448
449 fn json_path_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
451 ctx.note(
452 if text { "json_path_text" } else { "json_path" },
453 Tier::Exact,
454 "",
455 None,
456 )?;
457 Ok(format!("{lhs} {} {rhs}", if text { "#>>" } else { "#>" }))
458 }
459
460 fn binary_override(
463 &self,
464 _op: BinaryOp,
465 _l: &str,
466 _r: &str,
467 _numeric: bool,
468 _ctx: &mut Ctx,
469 ) -> R<Option<String>> {
470 Ok(None)
471 }
472
473 fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
475 let mut s = expr.to_string();
476 if desc {
477 s.push_str(" DESC");
478 }
479 s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
480 Ok(s)
481 }
482
483 fn replace_keyword(&self) -> Option<&'static str> {
488 None
489 }
490
491 fn needs_conflict_key(&self) -> bool {
495 true
496 }
497
498 fn excluded_ref(&self, column_quoted: &str) -> String {
500 format!("EXCLUDED.{column_quoted}")
501 }
502
503 fn upsert_where_as_if(&self) -> bool {
506 false
507 }
508
509 #[allow(
511 clippy::too_many_arguments,
512 reason = "each argument is a distinct clause of the ON CONFLICT form; a parameter struct would only rename them"
513 )]
514 fn upsert_clause(
515 &self,
516 conflict_cols: &[String],
517 do_nothing: bool,
518 set: &str,
519 where_: Option<&str>,
520 _first_insert_col: &str,
521 ctx: &mut Ctx,
522 ) -> R<String> {
523 if !do_nothing && conflict_cols.is_empty() {
524 return Err(ctx.refuse(
525 "upsert.no_conflict_key",
526 "the source upsert names no conflict key (MySQL ON DUPLICATE KEY UPDATE fires on any unique key); this target needs the key columns, and the schema does not state exactly one unique key for the table",
527 &["state the conflict key columns in the statement", "or give the schema the table's unique key (Schema::with_unique_key, or schema_from_ddl)"],
528 ));
529 }
530 ctx.note(
531 if where_.is_some() {
532 "upsert_where"
533 } else {
534 "upsert"
535 },
536 Tier::Exact,
537 "",
538 None,
539 )?;
540 let mut s = String::from(" ON CONFLICT");
541 if !conflict_cols.is_empty() {
542 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
543 }
544 if do_nothing {
545 s.push_str(" DO NOTHING");
546 } else {
547 s.push_str(&format!(" DO UPDATE SET {set}"));
548 if let Some(w) = where_ {
549 s.push_str(&format!(" WHERE {w}"));
550 }
551 }
552 Ok(s)
553 }
554
555 fn array_membership(
559 &self,
560 _lhs: &str,
561 _ph: &str,
562 _negated: bool,
563 n: u32,
564 ctx: &mut Ctx,
565 ) -> R<String> {
566 Err(ctx.refuse(
567 "array_param",
568 &format!(
569 "target `{}` has no codec for an array parameter (${n})",
570 ctx.target
571 ),
572 &["expand the array into an IN (..) list in the application"],
573 ))
574 }
575
576 fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
579 Ok(())
580 }
581
582 fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
585 Ok(())
586 }
587
588 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
591 let default_first = desc;
593 ctx.note("null_ordering", Tier::Exact, "", None)?;
594 if nulls_first == default_first {
595 Ok(String::new())
596 } else {
597 Ok(if nulls_first {
598 " NULLS FIRST"
599 } else {
600 " NULLS LAST"
601 }
602 .to_string())
603 }
604 }
605}
606
607pub const PORTABLE_FUNCTIONS: &[&str] = &[
609 "count",
610 "sum",
611 "min",
612 "max",
613 "avg",
614 "coalesce",
615 "nullif",
616 "abs",
617 "lower",
618 "upper",
619 "length",
620 "replace",
621 "substr",
622 "row_number",
623 "rank",
624 "dense_rank",
625 "percent_rank",
626 "cume_dist",
627 "ntile",
628 "lag",
629 "lead",
630 "first_value",
631 "last_value",
632 "nth_value",
633 "strpos",
636 "ceil",
638 "floor",
639];
640
641pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
642 generic_call_ordered(name, args, distinct, star, None)
643}
644
645pub fn generic_call_ordered(
647 name: &str,
648 args: &[String],
649 distinct: bool,
650 star: bool,
651 order: Option<&str>,
652) -> String {
653 let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
654 if star {
655 return format!("{}(*)", name.to_uppercase());
656 }
657 format!(
658 "{}({}{}{})",
659 name.to_uppercase(),
660 if distinct { "DISTINCT " } else { "" },
661 args.join(", "),
662 ord
663 )
664}
665
666pub fn pg_type_name(ty: &SqlType) -> String {
668 match ty {
669 SqlType::SmallInt => "SMALLINT".into(),
670 SqlType::Integer => "INTEGER".into(),
671 SqlType::BigInt => "BIGINT".into(),
672 SqlType::Real => "REAL".into(),
673 SqlType::Double => "DOUBLE PRECISION".into(),
674 SqlType::Numeric {
675 precision: None, ..
676 } => "NUMERIC".into(),
677 SqlType::Numeric {
678 precision: Some(p),
679 scale: None,
680 } => format!("NUMERIC({p})"),
681 SqlType::Numeric {
682 precision: Some(p),
683 scale: Some(s),
684 } => format!("NUMERIC({p}, {s})"),
685 SqlType::Text => "TEXT".into(),
686 SqlType::Varchar(None) => "VARCHAR".into(),
687 SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
688 SqlType::Boolean => "BOOLEAN".into(),
689 SqlType::Date => "DATE".into(),
690 SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
691 SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
692 SqlType::Uuid => "UUID".into(),
693 SqlType::Regclass => "REGCLASS".into(),
694 SqlType::Bytes => "BYTEA".into(),
695 SqlType::Json => "JSON".into(),
696 SqlType::Jsonb => "JSONB".into(),
697 }
698}
699
700pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
702 match f.args.get(i) {
703 Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
704 _ => None,
705 }
706}
707
708pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
710 matches!(
711 f.args.get(i),
712 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
713 )
714}
715
716pub fn literal_single_char_string(f: &Function, i: usize) -> bool {
718 matches!(
719 f.args.get(i),
720 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if s.chars().count() == 1
721 )
722}
723
724pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
727 match f.args.as_slice() {
728 [] => Some(0),
729 [FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
730 _ => None,
731 }
732}
733
734pub fn date_trunc_field(f: &Function) -> Option<String> {
736 if f.name != "date_trunc" {
737 return None;
738 }
739 match f.args.first() {
740 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
741 _ => None,
742 }
743}
744
745pub fn to_char_format(f: &Function, spec: [&str; 6]) -> Option<String> {
750 if f.name != "to_char" || f.args.len() != 2 {
751 return None;
752 }
753 let Some(FunctionArg::Expr(Expr::Literal(Literal::String(fmt)))) = f.args.get(1) else {
754 return None;
755 };
756 let mut out = String::new();
757 let mut rest = fmt.as_str();
758 while !rest.is_empty() {
759 let tokens = [
760 ("YYYY", spec[0]),
761 ("MM", spec[1]),
762 ("DD", spec[2]),
763 ("HH24", spec[3]),
764 ("MI", spec[4]),
765 ("SS", spec[5]),
766 ];
767 if let Some((tok, s)) = tokens.iter().find(|(t, _)| rest.starts_with(t)) {
768 out.push_str(s);
769 rest = &rest[tok.len()..];
770 } else {
771 let c = rest.chars().next()?;
772 if !matches!(c, '-' | '/' | ':' | '.' | ',' | ' ') {
773 return None;
774 }
775 out.push(c);
776 rest = &rest[1..];
777 }
778 }
779 Some(out)
780}
781
782pub fn extract_leaf(field: &str, interval: bool) -> String {
785 if interval && field == "epoch" {
786 "extract.epoch.interval".to_string()
787 } else {
788 format!("extract.{field}")
789 }
790}
791
792pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
794 match lock.strength {
795 RowLock::Update => "row_lock",
796 RowLock::Share => "row_lock.share",
797 }
798}
799
800pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
802 ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
803 if lock.of.is_some() {
804 ctx.note("row_lock.of", Tier::Exact, "", None)?;
805 }
806 match lock.wait {
807 LockWait::Block => {}
808 LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
809 LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
810 }
811 Ok(())
812}
813
814pub fn with_leaf(kind: StmtKind) -> &'static str {
816 match kind {
817 StmtKind::Insert => "with.insert",
818 StmtKind::Update => "with.update",
819 StmtKind::Delete => "with.delete",
820 }
821}