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