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 at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
322 ctx.note("at_time_zone", Tier::Exact, "", None)
323 }
324
325 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
328 ctx.note("array_subquery", Tier::Exact, "", None)
329 }
330
331 fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
335 ctx.note(with_leaf(kind), Tier::Exact, "", None)
336 }
337
338 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
341 ctx.note("cte.data_modifying", Tier::Exact, "", None)
342 }
343
344 fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
348 note_row_lock_leaves(lock, ctx)
349 }
350
351 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
352 ctx.note("returning", Tier::Exact, "", None)
353 }
354
355 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
357 let mut s = String::new();
358 if let Some(l) = limit {
359 s.push_str(&format!(" LIMIT {l}"));
360 ctx.note("limit", Tier::Exact, "", None)?;
361 }
362 if let Some(o) = offset {
363 s.push_str(&format!(" OFFSET {o}"));
364 ctx.note("offset", Tier::Exact, "", None)?;
365 }
366 Ok(s)
367 }
368
369 fn join_tier(&self, _kind: JoinKind) -> Tier {
371 Tier::Exact
372 }
373
374 fn dml_sources(&self) -> DmlSources {
376 DmlSources::FromClause
377 }
378
379 fn dml_limit(&self) -> DmlLimit {
382 DmlLimit::RowIdSubquery("ctid")
383 }
384
385 fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
388 Ok(None)
389 }
390
391 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
394 ctx.note(name, Tier::Exact, "", None)
395 }
396
397 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
399 ctx.note("trim", Tier::Exact, "", None)?;
400 Ok(match (side, chars) {
401 (TrimSide::Both, None) => format!("TRIM({expr})"),
402 (s, c) => {
403 let kw = match s {
404 TrimSide::Both => "BOTH",
405 TrimSide::Leading => "LEADING",
406 TrimSide::Trailing => "TRAILING",
407 };
408 match c {
409 Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
410 None => format!("TRIM({kw} FROM {expr})"),
411 }
412 }
413 })
414 }
415
416 fn interval_arith(
419 &self,
420 _minus: bool,
421 _left: &str,
422 _parts: &[(String, String)],
423 _ctx: &mut Ctx,
424 ) -> R<Option<String>> {
425 Ok(None)
426 }
427
428 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
430 ctx.note(
431 if text { "json_get_text" } else { "json_get" },
432 Tier::Exact,
433 "",
434 None,
435 )?;
436 Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
437 }
438
439 fn binary_override(
442 &self,
443 _op: BinaryOp,
444 _l: &str,
445 _r: &str,
446 _numeric: bool,
447 _ctx: &mut Ctx,
448 ) -> R<Option<String>> {
449 Ok(None)
450 }
451
452 fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
454 let mut s = expr.to_string();
455 if desc {
456 s.push_str(" DESC");
457 }
458 s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
459 Ok(s)
460 }
461
462 fn replace_keyword(&self) -> Option<&'static str> {
467 None
468 }
469
470 fn needs_conflict_key(&self) -> bool {
474 true
475 }
476
477 fn excluded_ref(&self, column_quoted: &str) -> String {
479 format!("EXCLUDED.{column_quoted}")
480 }
481
482 #[allow(clippy::too_many_arguments)]
484 fn upsert_clause(
485 &self,
486 conflict_cols: &[String],
487 do_nothing: bool,
488 set: &str,
489 where_: Option<&str>,
490 _first_insert_col: &str,
491 ctx: &mut Ctx,
492 ) -> R<String> {
493 if !do_nothing && conflict_cols.is_empty() {
494 return Err(ctx.refuse(
495 "upsert.no_conflict_key",
496 "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",
497 &["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)"],
498 ));
499 }
500 ctx.note(
501 if where_.is_some() {
502 "upsert_where"
503 } else {
504 "upsert"
505 },
506 Tier::Exact,
507 "",
508 None,
509 )?;
510 let mut s = String::from(" ON CONFLICT");
511 if !conflict_cols.is_empty() {
512 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
513 }
514 if do_nothing {
515 s.push_str(" DO NOTHING");
516 } else {
517 s.push_str(&format!(" DO UPDATE SET {set}"));
518 if let Some(w) = where_ {
519 s.push_str(&format!(" WHERE {w}"));
520 }
521 }
522 Ok(s)
523 }
524
525 fn array_membership(
529 &self,
530 _lhs: &str,
531 _ph: &str,
532 _negated: bool,
533 n: u32,
534 ctx: &mut Ctx,
535 ) -> R<String> {
536 Err(ctx.refuse(
537 "array_param",
538 &format!(
539 "target `{}` has no codec for an array parameter (${n})",
540 ctx.target
541 ),
542 &["expand the array into an IN (..) list in the application"],
543 ))
544 }
545
546 fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
549 Ok(())
550 }
551
552 fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
555 Ok(())
556 }
557
558 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
561 let default_first = desc;
563 ctx.note("null_ordering", Tier::Exact, "", None)?;
564 if nulls_first == default_first {
565 Ok(String::new())
566 } else {
567 Ok(if nulls_first {
568 " NULLS FIRST"
569 } else {
570 " NULLS LAST"
571 }
572 .to_string())
573 }
574 }
575}
576
577pub const PORTABLE_FUNCTIONS: &[&str] = &[
579 "count",
580 "sum",
581 "min",
582 "max",
583 "avg",
584 "coalesce",
585 "nullif",
586 "abs",
587 "lower",
588 "upper",
589 "length",
590 "replace",
591 "substr",
592 "row_number",
593 "rank",
594 "dense_rank",
595 "percent_rank",
596 "cume_dist",
597 "ntile",
598 "lag",
599 "lead",
600 "first_value",
601 "last_value",
602 "nth_value",
603 "strpos",
606 "ceil",
608 "floor",
609];
610
611pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
612 generic_call_ordered(name, args, distinct, star, None)
613}
614
615pub fn generic_call_ordered(
617 name: &str,
618 args: &[String],
619 distinct: bool,
620 star: bool,
621 order: Option<&str>,
622) -> String {
623 let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
624 if star {
625 return format!("{}(*)", name.to_uppercase());
626 }
627 format!(
628 "{}({}{}{})",
629 name.to_uppercase(),
630 if distinct { "DISTINCT " } else { "" },
631 args.join(", "),
632 ord
633 )
634}
635
636pub fn pg_type_name(ty: &SqlType) -> String {
638 match ty {
639 SqlType::SmallInt => "SMALLINT".into(),
640 SqlType::Integer => "INTEGER".into(),
641 SqlType::BigInt => "BIGINT".into(),
642 SqlType::Real => "REAL".into(),
643 SqlType::Double => "DOUBLE PRECISION".into(),
644 SqlType::Numeric {
645 precision: None, ..
646 } => "NUMERIC".into(),
647 SqlType::Numeric {
648 precision: Some(p),
649 scale: None,
650 } => format!("NUMERIC({p})"),
651 SqlType::Numeric {
652 precision: Some(p),
653 scale: Some(s),
654 } => format!("NUMERIC({p}, {s})"),
655 SqlType::Text => "TEXT".into(),
656 SqlType::Varchar(None) => "VARCHAR".into(),
657 SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
658 SqlType::Boolean => "BOOLEAN".into(),
659 SqlType::Date => "DATE".into(),
660 SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
661 SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
662 SqlType::Uuid => "UUID".into(),
663 SqlType::Bytes => "BYTEA".into(),
664 SqlType::Json => "JSON".into(),
665 SqlType::Jsonb => "JSONB".into(),
666 }
667}
668
669pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
671 match f.args.get(i) {
672 Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
673 _ => None,
674 }
675}
676
677pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
679 matches!(
680 f.args.get(i),
681 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
682 )
683}
684
685pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
688 match f.args.as_slice() {
689 [] => Some(0),
690 [FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
691 _ => None,
692 }
693}
694
695pub fn date_trunc_field(f: &Function) -> Option<String> {
697 if f.name != "date_trunc" {
698 return None;
699 }
700 match f.args.first() {
701 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
702 _ => None,
703 }
704}
705
706pub fn extract_leaf(field: &str, interval: bool) -> String {
709 if interval && field == "epoch" {
710 "extract.epoch.interval".to_string()
711 } else {
712 format!("extract.{field}")
713 }
714}
715
716pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
718 match lock.strength {
719 RowLock::Update => "row_lock",
720 RowLock::Share => "row_lock.share",
721 }
722}
723
724pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
726 ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
727 if lock.of.is_some() {
728 ctx.note("row_lock.of", Tier::Exact, "", None)?;
729 }
730 match lock.wait {
731 LockWait::Block => {}
732 LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
733 LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
734 }
735 Ok(())
736}
737
738pub fn with_leaf(kind: StmtKind) -> &'static str {
740 match kind {
741 StmtKind::Insert => "with.insert",
742 StmtKind::Update => "with.update",
743 StmtKind::Delete => "with.delete",
744 }
745}