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 array_params: std::collections::BTreeMap<u32, ParamBinding>,
36 pub scalar_params: std::collections::BTreeSet<u32>,
38}
39
40impl<'a> Ctx<'a> {
41 pub fn new(opts: &'a Options, source: &'a str, target: &'a str) -> Self {
42 Ctx {
43 report: Report::default(),
44 opts,
45 scopes: crate::schema::Scopes::new(opts.schema.as_ref()),
46 source,
47 target,
48 max_param: 0,
49 param_order: Vec::new(),
50 in_upsert: false,
51 upsert_table: None,
52 agg_order: None,
53 order_non_text: false,
54 interval_notation: false,
55 array_params: Default::default(),
56 scalar_params: Default::default(),
57 }
58 }
59
60 pub fn note(
63 &mut self,
64 construct: impl Into<String>,
65 tier: Tier,
66 note: impl Into<String>,
67 allowance: Option<Allowance>,
68 ) -> Result<(), Untranslatable> {
69 let construct = construct.into();
70 let note = note.into();
71 match tier {
72 Tier::Refused => Err(self.refuse(&construct, ¬e, &[])),
73 Tier::Conditional => {
74 let a = allowance.expect("a Conditional note must name its Allowance");
75 if self.source != self.target && !self.opts.allow.contains(&a) {
77 return Err(self.refuse(
78 &construct,
79 &format!("conditional: needs allowance `{}`: {}", a.name(), note),
80 &[],
81 ));
82 }
83 self.report.push(Entry {
84 construct,
85 tier,
86 note,
87 allowance: Some(a),
88 });
89 Ok(())
90 }
91 _ => {
92 self.report.push(Entry {
93 construct,
94 tier,
95 note,
96 allowance,
97 });
98 Ok(())
99 }
100 }
101 }
102
103 pub fn bind_array_param(&mut self, n: u32, binding: ParamBinding) {
105 self.array_params.insert(n, binding);
106 }
107
108 pub fn lenient_source(&self) -> bool {
111 matches!(self.source, "sqlite" | "mysql" | "mariadb")
112 }
113
114 pub fn refuse(&self, construct: &str, reason: &str, alternatives: &[&str]) -> Untranslatable {
115 Untranslatable {
116 construct: construct.to_string(),
117 source: self.source.to_string(),
118 target: self.target.to_string(),
119 reason: reason.to_string(),
120 alternatives: alternatives.iter().map(|s| s.to_string()).collect(),
121 }
122 }
123}
124
125type R<T> = Result<T, Untranslatable>;
126
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum StmtKind {
130 Insert,
131 Update,
132 Delete,
133}
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub enum Escape<'a> {
138 None,
140 Default,
142 Custom(&'a str),
144}
145
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum DmlLimit {
150 Native,
152 RowIdSubquery(&'static str),
154}
155
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
158pub enum DmlSources {
159 FromClause,
161 Join,
163 UpdateFromOnly,
165}
166
167pub trait Target {
168 fn name(&self) -> &'static str;
169
170 fn quote_ident(&self, s: &str) -> String {
171 format!("\"{}\"", s.replace('"', "\"\""))
172 }
173
174 fn string_literal(&self, s: &str) -> String {
175 format!("'{}'", s.replace('\'', "''"))
176 }
177
178 fn bytes_literal(&self, b: &[u8]) -> String {
180 let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
181 format!("'\\x{hex}'::bytea")
182 }
183
184 fn placeholder(&self, n: u32) -> String {
186 format!("${n}")
187 }
188
189 fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
190 Ok(if b { "TRUE" } else { "FALSE" }.to_string())
191 }
192
193 fn like(
195 &self,
196 lhs: &str,
197 rhs: &str,
198 negated: bool,
199 ci: bool,
200 esc: Escape<'_>,
201 ctx: &mut Ctx,
202 ) -> R<String> {
203 let kw = if ci { "ILIKE" } else { "LIKE" };
204 ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
205 let tail = match esc {
206 Escape::Default => String::new(), Escape::None => " ESCAPE ''".to_string(),
208 Escape::Custom(c) => format!(" ESCAPE {c}"),
209 };
210 Ok(format!(
211 "{lhs} {}{kw} {rhs}{tail}",
212 if negated { "NOT " } else { "" }
213 ))
214 }
215
216 fn regexp(&self, lhs: &str, rhs: &str, negated: bool, ctx: &mut Ctx) -> R<String> {
218 ctx.note(
219 "regexp",
220 Tier::Conditional,
221 "regular-expression syntax and case sensitivity differ between engines; exact only for \
222 patterns in the common subset",
223 Some(Allowance::RegexpFlavor),
224 )?;
225 Ok(format!("{lhs} {} {rhs}", if negated { "!~" } else { "~" }))
226 }
227
228 fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
230 if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
233 return Err(ctx.refuse(
234 &format!("fn:{}", f.name),
235 "no verified mapping for this function on this target yet",
236 &[],
237 ));
238 }
239 ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
240 let order = ctx.agg_order.take();
241 Ok(generic_call_ordered(
242 &f.name,
243 args,
244 f.distinct,
245 f.star,
246 order.as_deref(),
247 ))
248 }
249
250 fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
251 if ctx.lenient_source() {
252 ctx.note(
253 format!("cast.to_{}", ty.leaf()),
254 Tier::Conditional,
255 "the source casts leniently (a malformed value becomes 0); the target raises an error",
256 Some(Allowance::LenientCast),
257 )?;
258 } else {
259 ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
260 }
261 Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
262 }
263
264 fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
265 ctx.note("distinct_on", Tier::Exact, "", None)
266 }
267
268 fn group_by_rollup(&self, keys: &[String], ctx: &mut Ctx) -> R<String> {
271 ctx.note("group_by.rollup", Tier::Exact, "", None)?;
272 Ok(format!("ROLLUP ({})", keys.join(", ")))
273 }
274
275 fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
277 ctx.note("null_safe_eq", Tier::Exact, "", None)?;
278 Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
279 }
280
281 fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
284 ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
285 Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
286 }
287
288 fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
292 Ok(None)
293 }
294
295 fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
298 Err(ctx.refuse(
299 "extract.epoch",
300 "no mapping for the per-call wall clock",
301 &["bind the time as a parameter"],
302 ))
303 }
304
305 fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
308 ctx.note("array_literal", Tier::Exact, "", None)?;
309 Ok(format!("ARRAY[{}]", items.join(", ")))
310 }
311
312 fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
316 ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
317 }
318
319 fn series_as_recursive_cte(&self) -> bool {
322 false
323 }
324
325 fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
328 ctx.note("at_time_zone", Tier::Exact, "", None)
329 }
330
331 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
334 ctx.note("array_subquery", Tier::Exact, "", None)
335 }
336
337 fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
341 ctx.note(with_leaf(kind), Tier::Exact, "", None)
342 }
343
344 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
347 ctx.note("cte.data_modifying", Tier::Exact, "", None)
348 }
349
350 fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
354 note_row_lock_leaves(lock, ctx)
355 }
356
357 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
358 ctx.note("returning", Tier::Exact, "", None)
359 }
360
361 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
363 let mut s = String::new();
364 if let Some(l) = limit {
365 s.push_str(&format!(" LIMIT {l}"));
366 ctx.note("limit", Tier::Exact, "", None)?;
367 }
368 if let Some(o) = offset {
369 s.push_str(&format!(" OFFSET {o}"));
370 ctx.note("offset", Tier::Exact, "", None)?;
371 }
372 Ok(s)
373 }
374
375 fn join_tier(&self, _kind: JoinKind) -> Tier {
377 Tier::Exact
378 }
379
380 fn dml_sources(&self) -> DmlSources {
382 DmlSources::FromClause
383 }
384
385 fn dml_limit(&self) -> DmlLimit {
388 DmlLimit::RowIdSubquery("ctid")
389 }
390
391 fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
394 Ok(None)
395 }
396
397 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
400 ctx.note(name, Tier::Exact, "", None)
401 }
402
403 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
405 ctx.note("trim", Tier::Exact, "", None)?;
406 Ok(match (side, chars) {
407 (TrimSide::Both, None) => format!("TRIM({expr})"),
408 (s, c) => {
409 let kw = match s {
410 TrimSide::Both => "BOTH",
411 TrimSide::Leading => "LEADING",
412 TrimSide::Trailing => "TRAILING",
413 };
414 match c {
415 Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
416 None => format!("TRIM({kw} FROM {expr})"),
417 }
418 }
419 })
420 }
421
422 fn interval_arith(
425 &self,
426 _minus: bool,
427 _left: &str,
428 _parts: &[(String, String)],
429 _ctx: &mut Ctx,
430 ) -> R<Option<String>> {
431 Ok(None)
432 }
433
434 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
436 ctx.note(
437 if text { "json_get_text" } else { "json_get" },
438 Tier::Exact,
439 "",
440 None,
441 )?;
442 Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
443 }
444
445 fn json_path_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
447 ctx.note(
448 if text { "json_path_text" } else { "json_path" },
449 Tier::Exact,
450 "",
451 None,
452 )?;
453 Ok(format!("{lhs} {} {rhs}", if text { "#>>" } else { "#>" }))
454 }
455
456 fn binary_override(
459 &self,
460 _op: BinaryOp,
461 _l: &str,
462 _r: &str,
463 _numeric: bool,
464 _ctx: &mut Ctx,
465 ) -> R<Option<String>> {
466 Ok(None)
467 }
468
469 fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
471 let mut s = expr.to_string();
472 if desc {
473 s.push_str(" DESC");
474 }
475 s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
476 Ok(s)
477 }
478
479 fn replace_keyword(&self) -> Option<&'static str> {
484 None
485 }
486
487 fn needs_conflict_key(&self) -> bool {
491 true
492 }
493
494 fn excluded_ref(&self, column_quoted: &str) -> String {
496 format!("EXCLUDED.{column_quoted}")
497 }
498
499 fn upsert_where_as_if(&self) -> bool {
502 false
503 }
504
505 #[allow(
507 clippy::too_many_arguments,
508 reason = "each argument is a distinct clause of the ON CONFLICT form; a parameter struct would only rename them"
509 )]
510 fn upsert_clause(
511 &self,
512 conflict_cols: &[String],
513 do_nothing: bool,
514 set: &str,
515 where_: Option<&str>,
516 _first_insert_col: &str,
517 ctx: &mut Ctx,
518 ) -> R<String> {
519 if !do_nothing && conflict_cols.is_empty() {
520 return Err(ctx.refuse(
521 "upsert.no_conflict_key",
522 "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",
523 &["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)"],
524 ));
525 }
526 ctx.note(
527 if where_.is_some() {
528 "upsert_where"
529 } else {
530 "upsert"
531 },
532 Tier::Exact,
533 "",
534 None,
535 )?;
536 let mut s = String::from(" ON CONFLICT");
537 if !conflict_cols.is_empty() {
538 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
539 }
540 if do_nothing {
541 s.push_str(" DO NOTHING");
542 } else {
543 s.push_str(&format!(" DO UPDATE SET {set}"));
544 if let Some(w) = where_ {
545 s.push_str(&format!(" WHERE {w}"));
546 }
547 }
548 Ok(s)
549 }
550
551 fn array_membership(
555 &self,
556 _lhs: &str,
557 _ph: &str,
558 _negated: bool,
559 n: u32,
560 ctx: &mut Ctx,
561 ) -> R<String> {
562 Err(ctx.refuse(
563 "array_param",
564 &format!(
565 "target `{}` has no codec for an array parameter (${n})",
566 ctx.target
567 ),
568 &["expand the array into an IN (..) list in the application"],
569 ))
570 }
571
572 fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
575 Ok(())
576 }
577
578 fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
581 Ok(())
582 }
583
584 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
587 let default_first = desc;
589 ctx.note("null_ordering", Tier::Exact, "", None)?;
590 if nulls_first == default_first {
591 Ok(String::new())
592 } else {
593 Ok(if nulls_first {
594 " NULLS FIRST"
595 } else {
596 " NULLS LAST"
597 }
598 .to_string())
599 }
600 }
601}
602
603pub const PORTABLE_FUNCTIONS: &[&str] = &[
605 "count",
606 "sum",
607 "min",
608 "max",
609 "avg",
610 "coalesce",
611 "nullif",
612 "abs",
613 "lower",
614 "upper",
615 "length",
616 "replace",
617 "substr",
618 "row_number",
619 "rank",
620 "dense_rank",
621 "percent_rank",
622 "cume_dist",
623 "ntile",
624 "lag",
625 "lead",
626 "first_value",
627 "last_value",
628 "nth_value",
629 "strpos",
632 "ceil",
634 "floor",
635];
636
637pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
638 generic_call_ordered(name, args, distinct, star, None)
639}
640
641pub fn generic_call_ordered(
643 name: &str,
644 args: &[String],
645 distinct: bool,
646 star: bool,
647 order: Option<&str>,
648) -> String {
649 let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
650 if star {
651 return format!("{}(*)", name.to_uppercase());
652 }
653 format!(
654 "{}({}{}{})",
655 name.to_uppercase(),
656 if distinct { "DISTINCT " } else { "" },
657 args.join(", "),
658 ord
659 )
660}
661
662pub fn pg_type_name(ty: &SqlType) -> String {
664 match ty {
665 SqlType::SmallInt => "SMALLINT".into(),
666 SqlType::Integer => "INTEGER".into(),
667 SqlType::BigInt => "BIGINT".into(),
668 SqlType::Real => "REAL".into(),
669 SqlType::Double => "DOUBLE PRECISION".into(),
670 SqlType::Numeric {
671 precision: None, ..
672 } => "NUMERIC".into(),
673 SqlType::Numeric {
674 precision: Some(p),
675 scale: None,
676 } => format!("NUMERIC({p})"),
677 SqlType::Numeric {
678 precision: Some(p),
679 scale: Some(s),
680 } => format!("NUMERIC({p}, {s})"),
681 SqlType::Text => "TEXT".into(),
682 SqlType::Varchar(None) => "VARCHAR".into(),
683 SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
684 SqlType::Boolean => "BOOLEAN".into(),
685 SqlType::Date => "DATE".into(),
686 SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
687 SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
688 SqlType::Uuid => "UUID".into(),
689 SqlType::Regclass => "REGCLASS".into(),
690 SqlType::Bytes => "BYTEA".into(),
691 SqlType::Json => "JSON".into(),
692 SqlType::Jsonb => "JSONB".into(),
693 }
694}
695
696pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
698 match f.args.get(i) {
699 Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
700 _ => None,
701 }
702}
703
704pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
706 matches!(
707 f.args.get(i),
708 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
709 )
710}
711
712pub fn literal_single_char_string(f: &Function, i: usize) -> bool {
714 matches!(
715 f.args.get(i),
716 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if s.chars().count() == 1
717 )
718}
719
720pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
723 match f.args.as_slice() {
724 [] => Some(0),
725 [FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
726 _ => None,
727 }
728}
729
730pub fn date_trunc_field(f: &Function) -> Option<String> {
732 if f.name != "date_trunc" {
733 return None;
734 }
735 match f.args.first() {
736 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
737 _ => None,
738 }
739}
740
741pub fn to_char_format(f: &Function, spec: [&str; 6]) -> Option<String> {
746 if f.name != "to_char" || f.args.len() != 2 {
747 return None;
748 }
749 let Some(FunctionArg::Expr(Expr::Literal(Literal::String(fmt)))) = f.args.get(1) else {
750 return None;
751 };
752 let mut out = String::new();
753 let mut rest = fmt.as_str();
754 while !rest.is_empty() {
755 let tokens = [
756 ("YYYY", spec[0]),
757 ("MM", spec[1]),
758 ("DD", spec[2]),
759 ("HH24", spec[3]),
760 ("MI", spec[4]),
761 ("SS", spec[5]),
762 ];
763 if let Some((tok, s)) = tokens.iter().find(|(t, _)| rest.starts_with(t)) {
764 out.push_str(s);
765 rest = &rest[tok.len()..];
766 } else {
767 let c = rest.chars().next()?;
768 if !matches!(c, '-' | '/' | ':' | '.' | ',' | ' ') {
769 return None;
770 }
771 out.push(c);
772 rest = &rest[1..];
773 }
774 }
775 Some(out)
776}
777
778pub fn extract_leaf(field: &str, interval: bool) -> String {
781 if interval && field == "epoch" {
782 "extract.epoch.interval".to_string()
783 } else {
784 format!("extract.{field}")
785 }
786}
787
788pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
790 match lock.strength {
791 RowLock::Update => "row_lock",
792 RowLock::Share => "row_lock.share",
793 }
794}
795
796pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
798 ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
799 if lock.of.is_some() {
800 ctx.note("row_lock.of", Tier::Exact, "", None)?;
801 }
802 match lock.wait {
803 LockWait::Block => {}
804 LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
805 LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
806 }
807 Ok(())
808}
809
810pub fn with_leaf(kind: StmtKind) -> &'static str {
812 match kind {
813 StmtKind::Insert => "with.insert",
814 StmtKind::Update => "with.update",
815 StmtKind::Delete => "with.delete",
816 }
817}