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 placeholder(&self, n: u32) -> String {
156 format!("${n}")
157 }
158
159 fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
160 Ok(if b { "TRUE" } else { "FALSE" }.to_string())
161 }
162
163 fn like(
165 &self,
166 lhs: &str,
167 rhs: &str,
168 negated: bool,
169 ci: bool,
170 esc: Escape<'_>,
171 ctx: &mut Ctx,
172 ) -> R<String> {
173 let kw = if ci { "ILIKE" } else { "LIKE" };
174 ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
175 let tail = match esc {
176 Escape::Default => String::new(), Escape::None => " ESCAPE ''".to_string(),
178 Escape::Custom(c) => format!(" ESCAPE {c}"),
179 };
180 Ok(format!(
181 "{lhs} {}{kw} {rhs}{tail}",
182 if negated { "NOT " } else { "" }
183 ))
184 }
185
186 fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
188 if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
191 return Err(ctx.refuse(
192 &format!("fn:{}", f.name),
193 "no verified mapping for this function on this target yet",
194 &[],
195 ));
196 }
197 ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
198 let order = ctx.agg_order.take();
199 Ok(generic_call_ordered(
200 &f.name,
201 args,
202 f.distinct,
203 f.star,
204 order.as_deref(),
205 ))
206 }
207
208 fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
209 if ctx.lenient_source() {
210 ctx.note(
211 format!("cast.to_{}", ty.leaf()),
212 Tier::Conditional,
213 "the source casts leniently (a malformed value becomes 0); the target raises an error",
214 Some(Allowance::LenientCast),
215 )?;
216 } else {
217 ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
218 }
219 Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
220 }
221
222 fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
223 ctx.note("distinct_on", Tier::Exact, "", None)
224 }
225
226 fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
228 ctx.note("null_safe_eq", Tier::Exact, "", None)?;
229 Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
230 }
231
232 fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
235 ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
236 Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
237 }
238
239 fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
243 Ok(None)
244 }
245
246 fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
249 ctx.note("array_literal", Tier::Exact, "", None)?;
250 Ok(format!("ARRAY[{}]", items.join(", ")))
251 }
252
253 fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
257 ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
258 }
259
260 fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
263 ctx.note("at_time_zone", Tier::Exact, "", None)
264 }
265
266 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
269 ctx.note("array_subquery", Tier::Exact, "", None)
270 }
271
272 fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
276 ctx.note(with_leaf(kind), Tier::Exact, "", None)
277 }
278
279 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
282 ctx.note("cte.data_modifying", Tier::Exact, "", None)
283 }
284
285 fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
289 note_row_lock_leaves(lock, ctx)
290 }
291
292 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
293 ctx.note("returning", Tier::Exact, "", None)
294 }
295
296 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
298 let mut s = String::new();
299 if let Some(l) = limit {
300 s.push_str(&format!(" LIMIT {l}"));
301 ctx.note("limit", Tier::Exact, "", None)?;
302 }
303 if let Some(o) = offset {
304 s.push_str(&format!(" OFFSET {o}"));
305 ctx.note("offset", Tier::Exact, "", None)?;
306 }
307 Ok(s)
308 }
309
310 fn join_tier(&self, _kind: JoinKind) -> Tier {
312 Tier::Exact
313 }
314
315 fn update_from_tier(&self) -> Tier {
317 Tier::Exact
318 }
319
320 fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
323 Ok(None)
324 }
325
326 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
329 ctx.note(name, Tier::Exact, "", None)
330 }
331
332 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
334 ctx.note("trim", Tier::Exact, "", None)?;
335 Ok(match (side, chars) {
336 (TrimSide::Both, None) => format!("TRIM({expr})"),
337 (s, c) => {
338 let kw = match s {
339 TrimSide::Both => "BOTH",
340 TrimSide::Leading => "LEADING",
341 TrimSide::Trailing => "TRAILING",
342 };
343 match c {
344 Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
345 None => format!("TRIM({kw} FROM {expr})"),
346 }
347 }
348 })
349 }
350
351 fn interval_arith(
354 &self,
355 _minus: bool,
356 _left: &str,
357 _parts: &[(String, String)],
358 _ctx: &mut Ctx,
359 ) -> R<Option<String>> {
360 Ok(None)
361 }
362
363 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
365 ctx.note(
366 if text { "json_get_text" } else { "json_get" },
367 Tier::Exact,
368 "",
369 None,
370 )?;
371 Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
372 }
373
374 fn binary_override(
377 &self,
378 _op: BinaryOp,
379 _l: &str,
380 _r: &str,
381 _numeric: bool,
382 _ctx: &mut Ctx,
383 ) -> R<Option<String>> {
384 Ok(None)
385 }
386
387 fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
389 let mut s = expr.to_string();
390 if desc {
391 s.push_str(" DESC");
392 }
393 s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
394 Ok(s)
395 }
396
397 fn replace_keyword(&self) -> Option<&'static str> {
402 None
403 }
404
405 fn needs_conflict_key(&self) -> bool {
409 true
410 }
411
412 fn excluded_ref(&self, column_quoted: &str) -> String {
414 format!("EXCLUDED.{column_quoted}")
415 }
416
417 #[allow(clippy::too_many_arguments)]
419 fn upsert_clause(
420 &self,
421 conflict_cols: &[String],
422 do_nothing: bool,
423 set: &str,
424 where_: Option<&str>,
425 _first_insert_col: &str,
426 ctx: &mut Ctx,
427 ) -> R<String> {
428 if !do_nothing && conflict_cols.is_empty() {
429 return Err(ctx.refuse(
430 "upsert.no_conflict_key",
431 "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",
432 &["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)"],
433 ));
434 }
435 ctx.note(
436 if where_.is_some() {
437 "upsert_where"
438 } else {
439 "upsert"
440 },
441 Tier::Exact,
442 "",
443 None,
444 )?;
445 let mut s = String::from(" ON CONFLICT");
446 if !conflict_cols.is_empty() {
447 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
448 }
449 if do_nothing {
450 s.push_str(" DO NOTHING");
451 } else {
452 s.push_str(&format!(" DO UPDATE SET {set}"));
453 if let Some(w) = where_ {
454 s.push_str(&format!(" WHERE {w}"));
455 }
456 }
457 Ok(s)
458 }
459
460 fn array_membership(
464 &self,
465 _lhs: &str,
466 _ph: &str,
467 _negated: bool,
468 n: u32,
469 ctx: &mut Ctx,
470 ) -> R<String> {
471 Err(ctx.refuse(
472 "array_param",
473 &format!(
474 "target `{}` has no codec for an array parameter (${n})",
475 ctx.target
476 ),
477 &["expand the array into an IN (..) list in the application"],
478 ))
479 }
480
481 fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
484 Ok(())
485 }
486
487 fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
490 Ok(())
491 }
492
493 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
496 let default_first = desc;
498 ctx.note("null_ordering", Tier::Exact, "", None)?;
499 if nulls_first == default_first {
500 Ok(String::new())
501 } else {
502 Ok(if nulls_first {
503 " NULLS FIRST"
504 } else {
505 " NULLS LAST"
506 }
507 .to_string())
508 }
509 }
510}
511
512pub const PORTABLE_FUNCTIONS: &[&str] = &[
514 "count",
515 "sum",
516 "min",
517 "max",
518 "avg",
519 "coalesce",
520 "nullif",
521 "abs",
522 "lower",
523 "upper",
524 "length",
525 "replace",
526 "substr",
527 "row_number",
528 "rank",
529 "dense_rank",
530 "percent_rank",
531 "cume_dist",
532 "ntile",
533 "lag",
534 "lead",
535 "first_value",
536 "last_value",
537 "nth_value",
538];
539
540pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
541 generic_call_ordered(name, args, distinct, star, None)
542}
543
544pub fn generic_call_ordered(
546 name: &str,
547 args: &[String],
548 distinct: bool,
549 star: bool,
550 order: Option<&str>,
551) -> String {
552 let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
553 if star {
554 return format!("{}(*)", name.to_uppercase());
555 }
556 format!(
557 "{}({}{}{})",
558 name.to_uppercase(),
559 if distinct { "DISTINCT " } else { "" },
560 args.join(", "),
561 ord
562 )
563}
564
565pub fn pg_type_name(ty: &SqlType) -> String {
567 match ty {
568 SqlType::SmallInt => "SMALLINT".into(),
569 SqlType::Integer => "INTEGER".into(),
570 SqlType::BigInt => "BIGINT".into(),
571 SqlType::Real => "REAL".into(),
572 SqlType::Double => "DOUBLE PRECISION".into(),
573 SqlType::Numeric {
574 precision: None, ..
575 } => "NUMERIC".into(),
576 SqlType::Numeric {
577 precision: Some(p),
578 scale: None,
579 } => format!("NUMERIC({p})"),
580 SqlType::Numeric {
581 precision: Some(p),
582 scale: Some(s),
583 } => format!("NUMERIC({p}, {s})"),
584 SqlType::Text => "TEXT".into(),
585 SqlType::Varchar(None) => "VARCHAR".into(),
586 SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
587 SqlType::Boolean => "BOOLEAN".into(),
588 SqlType::Date => "DATE".into(),
589 SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
590 SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
591 SqlType::Uuid => "UUID".into(),
592 SqlType::Bytes => "BYTEA".into(),
593 SqlType::Json => "JSON".into(),
594 SqlType::Jsonb => "JSONB".into(),
595 }
596}
597
598pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
600 match f.args.get(i) {
601 Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
602 _ => None,
603 }
604}
605
606pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
608 matches!(
609 f.args.get(i),
610 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
611 )
612}
613
614pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
617 match f.args.as_slice() {
618 [] => Some(0),
619 [FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
620 _ => None,
621 }
622}
623
624pub fn date_trunc_field(f: &Function) -> Option<String> {
626 if f.name != "date_trunc" {
627 return None;
628 }
629 match f.args.first() {
630 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
631 _ => None,
632 }
633}
634
635pub fn extract_leaf(field: &str, interval: bool) -> String {
638 if interval && field == "epoch" {
639 "extract.epoch.interval".to_string()
640 } else {
641 format!("extract.{field}")
642 }
643}
644
645pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
647 match lock.strength {
648 RowLock::Update => "row_lock",
649 RowLock::Share => "row_lock.share",
650 }
651}
652
653pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
655 ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
656 if lock.of.is_some() {
657 ctx.note("row_lock.of", Tier::Exact, "", None)?;
658 }
659 match lock.wait {
660 LockWait::Block => {}
661 LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
662 LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
663 }
664 Ok(())
665}
666
667pub fn with_leaf(kind: StmtKind) -> &'static str {
669 match kind {
670 StmtKind::Insert => "with.insert",
671 StmtKind::Update => "with.update",
672 StmtKind::Delete => "with.delete",
673 }
674}