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 interval_notation: bool,
31 pub array_params: std::collections::BTreeMap<u32, ParamBinding>,
33 pub scalar_params: std::collections::BTreeSet<u32>,
35}
36
37impl<'a> Ctx<'a> {
38 pub fn new(opts: &'a Options, source: &'a str, target: &'a str) -> Self {
39 Ctx {
40 report: Report::default(),
41 opts,
42 scopes: crate::schema::Scopes::new(opts.schema.as_ref()),
43 source,
44 target,
45 max_param: 0,
46 param_order: Vec::new(),
47 in_upsert: false,
48 upsert_table: None,
49 agg_order: None,
50 interval_notation: false,
51 array_params: Default::default(),
52 scalar_params: Default::default(),
53 }
54 }
55
56 pub fn note(
59 &mut self,
60 construct: impl Into<String>,
61 tier: Tier,
62 note: impl Into<String>,
63 allowance: Option<Allowance>,
64 ) -> Result<(), Untranslatable> {
65 let construct = construct.into();
66 let note = note.into();
67 match tier {
68 Tier::Refused => Err(self.refuse(&construct, ¬e, &[])),
69 Tier::Conditional => {
70 let a = allowance.expect("a Conditional note must name its Allowance");
71 if self.source != self.target && !self.opts.allow.contains(&a) {
73 return Err(self.refuse(
74 &construct,
75 &format!("conditional: needs allowance `{}`: {}", a.name(), note),
76 &[],
77 ));
78 }
79 self.report.push(Entry {
80 construct,
81 tier,
82 note,
83 allowance: Some(a),
84 });
85 Ok(())
86 }
87 _ => {
88 self.report.push(Entry {
89 construct,
90 tier,
91 note,
92 allowance,
93 });
94 Ok(())
95 }
96 }
97 }
98
99 pub fn bind_array_param(&mut self, n: u32, binding: ParamBinding) {
101 self.array_params.insert(n, binding);
102 }
103
104 pub fn lenient_source(&self) -> bool {
107 matches!(self.source, "sqlite" | "mysql" | "mariadb")
108 }
109
110 pub fn refuse(&self, construct: &str, reason: &str, alternatives: &[&str]) -> Untranslatable {
111 Untranslatable {
112 construct: construct.to_string(),
113 source: self.source.to_string(),
114 target: self.target.to_string(),
115 reason: reason.to_string(),
116 alternatives: alternatives.iter().map(|s| s.to_string()).collect(),
117 }
118 }
119}
120
121type R<T> = Result<T, Untranslatable>;
122
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub enum StmtKind {
126 Insert,
127 Update,
128 Delete,
129}
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub enum Escape<'a> {
134 None,
136 Default,
138 Custom(&'a str),
140}
141
142pub trait Target {
144 fn name(&self) -> &'static str;
145
146 fn quote_ident(&self, s: &str) -> String {
147 format!("\"{}\"", s.replace('"', "\"\""))
148 }
149
150 fn string_literal(&self, s: &str) -> String {
151 format!("'{}'", s.replace('\'', "''"))
152 }
153
154 fn bytes_literal(&self, b: &[u8]) -> String {
156 let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
157 format!("'\\x{hex}'::bytea")
158 }
159
160 fn placeholder(&self, n: u32) -> String {
162 format!("${n}")
163 }
164
165 fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
166 Ok(if b { "TRUE" } else { "FALSE" }.to_string())
167 }
168
169 fn like(
171 &self,
172 lhs: &str,
173 rhs: &str,
174 negated: bool,
175 ci: bool,
176 esc: Escape<'_>,
177 ctx: &mut Ctx,
178 ) -> R<String> {
179 let kw = if ci { "ILIKE" } else { "LIKE" };
180 ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
181 let tail = match esc {
182 Escape::Default => String::new(), Escape::None => " ESCAPE ''".to_string(),
184 Escape::Custom(c) => format!(" ESCAPE {c}"),
185 };
186 Ok(format!(
187 "{lhs} {}{kw} {rhs}{tail}",
188 if negated { "NOT " } else { "" }
189 ))
190 }
191
192 fn regexp(&self, lhs: &str, rhs: &str, negated: bool, ctx: &mut Ctx) -> R<String> {
194 ctx.note(
195 "regexp",
196 Tier::Conditional,
197 "regular-expression syntax and case sensitivity differ between engines; exact only for \
198 patterns in the common subset",
199 Some(Allowance::RegexpFlavor),
200 )?;
201 Ok(format!("{lhs} {} {rhs}", if negated { "!~" } else { "~" }))
202 }
203
204 fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
206 if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
209 return Err(ctx.refuse(
210 &format!("fn:{}", f.name),
211 "no verified mapping for this function on this target yet",
212 &[],
213 ));
214 }
215 ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
216 let order = ctx.agg_order.take();
217 Ok(generic_call_ordered(
218 &f.name,
219 args,
220 f.distinct,
221 f.star,
222 order.as_deref(),
223 ))
224 }
225
226 fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
227 if ctx.lenient_source() {
228 ctx.note(
229 format!("cast.to_{}", ty.leaf()),
230 Tier::Conditional,
231 "the source casts leniently (a malformed value becomes 0); the target raises an error",
232 Some(Allowance::LenientCast),
233 )?;
234 } else {
235 ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
236 }
237 Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
238 }
239
240 fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
241 ctx.note("distinct_on", Tier::Exact, "", None)
242 }
243
244 fn group_by_rollup(&self, keys: &[String], ctx: &mut Ctx) -> R<String> {
247 ctx.note("group_by.rollup", Tier::Exact, "", None)?;
248 Ok(format!("ROLLUP ({})", keys.join(", ")))
249 }
250
251 fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
253 ctx.note("null_safe_eq", Tier::Exact, "", None)?;
254 Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
255 }
256
257 fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
260 ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
261 Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
262 }
263
264 fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
268 Ok(None)
269 }
270
271 fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
274 ctx.note("array_literal", Tier::Exact, "", None)?;
275 Ok(format!("ARRAY[{}]", items.join(", ")))
276 }
277
278 fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
282 ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
283 }
284
285 fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
288 ctx.note("at_time_zone", Tier::Exact, "", None)
289 }
290
291 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
294 ctx.note("array_subquery", Tier::Exact, "", None)
295 }
296
297 fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
301 ctx.note(with_leaf(kind), Tier::Exact, "", None)
302 }
303
304 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
307 ctx.note("cte.data_modifying", Tier::Exact, "", None)
308 }
309
310 fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
314 note_row_lock_leaves(lock, ctx)
315 }
316
317 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
318 ctx.note("returning", Tier::Exact, "", None)
319 }
320
321 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
323 let mut s = String::new();
324 if let Some(l) = limit {
325 s.push_str(&format!(" LIMIT {l}"));
326 ctx.note("limit", Tier::Exact, "", None)?;
327 }
328 if let Some(o) = offset {
329 s.push_str(&format!(" OFFSET {o}"));
330 ctx.note("offset", Tier::Exact, "", None)?;
331 }
332 Ok(s)
333 }
334
335 fn join_tier(&self, _kind: JoinKind) -> Tier {
337 Tier::Exact
338 }
339
340 fn update_from_tier(&self) -> Tier {
342 Tier::Exact
343 }
344
345 fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
348 Ok(None)
349 }
350
351 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
354 ctx.note(name, Tier::Exact, "", None)
355 }
356
357 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
359 ctx.note("trim", Tier::Exact, "", None)?;
360 Ok(match (side, chars) {
361 (TrimSide::Both, None) => format!("TRIM({expr})"),
362 (s, c) => {
363 let kw = match s {
364 TrimSide::Both => "BOTH",
365 TrimSide::Leading => "LEADING",
366 TrimSide::Trailing => "TRAILING",
367 };
368 match c {
369 Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
370 None => format!("TRIM({kw} FROM {expr})"),
371 }
372 }
373 })
374 }
375
376 fn interval_arith(
379 &self,
380 _minus: bool,
381 _left: &str,
382 _parts: &[(String, String)],
383 _ctx: &mut Ctx,
384 ) -> R<Option<String>> {
385 Ok(None)
386 }
387
388 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
390 ctx.note(
391 if text { "json_get_text" } else { "json_get" },
392 Tier::Exact,
393 "",
394 None,
395 )?;
396 Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
397 }
398
399 fn binary_override(
402 &self,
403 _op: BinaryOp,
404 _l: &str,
405 _r: &str,
406 _numeric: bool,
407 _ctx: &mut Ctx,
408 ) -> R<Option<String>> {
409 Ok(None)
410 }
411
412 fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
414 let mut s = expr.to_string();
415 if desc {
416 s.push_str(" DESC");
417 }
418 s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
419 Ok(s)
420 }
421
422 fn replace_keyword(&self) -> Option<&'static str> {
427 None
428 }
429
430 fn needs_conflict_key(&self) -> bool {
434 true
435 }
436
437 fn excluded_ref(&self, column_quoted: &str) -> String {
439 format!("EXCLUDED.{column_quoted}")
440 }
441
442 #[allow(clippy::too_many_arguments)]
444 fn upsert_clause(
445 &self,
446 conflict_cols: &[String],
447 do_nothing: bool,
448 set: &str,
449 where_: Option<&str>,
450 _first_insert_col: &str,
451 ctx: &mut Ctx,
452 ) -> R<String> {
453 if !do_nothing && conflict_cols.is_empty() {
454 return Err(ctx.refuse(
455 "upsert.no_conflict_key",
456 "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",
457 &["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)"],
458 ));
459 }
460 ctx.note(
461 if where_.is_some() {
462 "upsert_where"
463 } else {
464 "upsert"
465 },
466 Tier::Exact,
467 "",
468 None,
469 )?;
470 let mut s = String::from(" ON CONFLICT");
471 if !conflict_cols.is_empty() {
472 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
473 }
474 if do_nothing {
475 s.push_str(" DO NOTHING");
476 } else {
477 s.push_str(&format!(" DO UPDATE SET {set}"));
478 if let Some(w) = where_ {
479 s.push_str(&format!(" WHERE {w}"));
480 }
481 }
482 Ok(s)
483 }
484
485 fn array_membership(
489 &self,
490 _lhs: &str,
491 _ph: &str,
492 _negated: bool,
493 n: u32,
494 ctx: &mut Ctx,
495 ) -> R<String> {
496 Err(ctx.refuse(
497 "array_param",
498 &format!(
499 "target `{}` has no codec for an array parameter (${n})",
500 ctx.target
501 ),
502 &["expand the array into an IN (..) list in the application"],
503 ))
504 }
505
506 fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
509 Ok(())
510 }
511
512 fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
515 Ok(())
516 }
517
518 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
521 let default_first = desc;
523 ctx.note("null_ordering", Tier::Exact, "", None)?;
524 if nulls_first == default_first {
525 Ok(String::new())
526 } else {
527 Ok(if nulls_first {
528 " NULLS FIRST"
529 } else {
530 " NULLS LAST"
531 }
532 .to_string())
533 }
534 }
535}
536
537pub const PORTABLE_FUNCTIONS: &[&str] = &[
539 "count",
540 "sum",
541 "min",
542 "max",
543 "avg",
544 "coalesce",
545 "nullif",
546 "abs",
547 "lower",
548 "upper",
549 "length",
550 "replace",
551 "substr",
552 "row_number",
553 "rank",
554 "dense_rank",
555 "percent_rank",
556 "cume_dist",
557 "ntile",
558 "lag",
559 "lead",
560 "first_value",
561 "last_value",
562 "nth_value",
563 "strpos",
566 "ceil",
568 "floor",
569];
570
571pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
572 generic_call_ordered(name, args, distinct, star, None)
573}
574
575pub fn generic_call_ordered(
577 name: &str,
578 args: &[String],
579 distinct: bool,
580 star: bool,
581 order: Option<&str>,
582) -> String {
583 let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
584 if star {
585 return format!("{}(*)", name.to_uppercase());
586 }
587 format!(
588 "{}({}{}{})",
589 name.to_uppercase(),
590 if distinct { "DISTINCT " } else { "" },
591 args.join(", "),
592 ord
593 )
594}
595
596pub fn pg_type_name(ty: &SqlType) -> String {
598 match ty {
599 SqlType::SmallInt => "SMALLINT".into(),
600 SqlType::Integer => "INTEGER".into(),
601 SqlType::BigInt => "BIGINT".into(),
602 SqlType::Real => "REAL".into(),
603 SqlType::Double => "DOUBLE PRECISION".into(),
604 SqlType::Numeric {
605 precision: None, ..
606 } => "NUMERIC".into(),
607 SqlType::Numeric {
608 precision: Some(p),
609 scale: None,
610 } => format!("NUMERIC({p})"),
611 SqlType::Numeric {
612 precision: Some(p),
613 scale: Some(s),
614 } => format!("NUMERIC({p}, {s})"),
615 SqlType::Text => "TEXT".into(),
616 SqlType::Varchar(None) => "VARCHAR".into(),
617 SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
618 SqlType::Boolean => "BOOLEAN".into(),
619 SqlType::Date => "DATE".into(),
620 SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
621 SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
622 SqlType::Uuid => "UUID".into(),
623 SqlType::Bytes => "BYTEA".into(),
624 SqlType::Json => "JSON".into(),
625 SqlType::Jsonb => "JSONB".into(),
626 }
627}
628
629pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
631 match f.args.get(i) {
632 Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
633 _ => None,
634 }
635}
636
637pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
639 matches!(
640 f.args.get(i),
641 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
642 )
643}
644
645pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
648 match f.args.as_slice() {
649 [] => Some(0),
650 [FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
651 _ => None,
652 }
653}
654
655pub fn date_trunc_field(f: &Function) -> Option<String> {
657 if f.name != "date_trunc" {
658 return None;
659 }
660 match f.args.first() {
661 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
662 _ => None,
663 }
664}
665
666pub fn extract_leaf(field: &str, interval: bool) -> String {
669 if interval && field == "epoch" {
670 "extract.epoch.interval".to_string()
671 } else {
672 format!("extract.{field}")
673 }
674}
675
676pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
678 match lock.strength {
679 RowLock::Update => "row_lock",
680 RowLock::Share => "row_lock.share",
681 }
682}
683
684pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
686 ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
687 if lock.of.is_some() {
688 ctx.note("row_lock.of", Tier::Exact, "", None)?;
689 }
690 match lock.wait {
691 LockWait::Block => {}
692 LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
693 LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
694 }
695 Ok(())
696}
697
698pub fn with_leaf(kind: StmtKind) -> &'static str {
700 match kind {
701 StmtKind::Insert => "with.insert",
702 StmtKind::Update => "with.update",
703 StmtKind::Delete => "with.delete",
704 }
705}