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 agg_order: Option<String>,
24 pub interval_notation: bool,
27 pub array_params: std::collections::BTreeMap<u32, ParamBinding>,
29 pub scalar_params: std::collections::BTreeSet<u32>,
31}
32
33impl<'a> Ctx<'a> {
34 pub fn new(opts: &'a Options, source: &'a str, target: &'a str) -> Self {
35 Ctx {
36 report: Report::default(),
37 opts,
38 scopes: crate::schema::Scopes::new(opts.schema.as_ref()),
39 source,
40 target,
41 max_param: 0,
42 param_order: Vec::new(),
43 in_upsert: false,
44 agg_order: None,
45 interval_notation: false,
46 array_params: Default::default(),
47 scalar_params: Default::default(),
48 }
49 }
50
51 pub fn note(
54 &mut self,
55 construct: impl Into<String>,
56 tier: Tier,
57 note: impl Into<String>,
58 allowance: Option<Allowance>,
59 ) -> Result<(), Untranslatable> {
60 let construct = construct.into();
61 let note = note.into();
62 match tier {
63 Tier::Refused => Err(self.refuse(&construct, ¬e, &[])),
64 Tier::Conditional => {
65 let a = allowance.expect("a Conditional note must name its Allowance");
66 if self.source != self.target && !self.opts.allow.contains(&a) {
68 return Err(self.refuse(
69 &construct,
70 &format!("conditional: needs allowance `{}`: {}", a.name(), note),
71 &[],
72 ));
73 }
74 self.report.push(Entry {
75 construct,
76 tier,
77 note,
78 allowance: Some(a),
79 });
80 Ok(())
81 }
82 _ => {
83 self.report.push(Entry {
84 construct,
85 tier,
86 note,
87 allowance,
88 });
89 Ok(())
90 }
91 }
92 }
93
94 pub fn bind_array_param(&mut self, n: u32, binding: ParamBinding) {
96 self.array_params.insert(n, binding);
97 }
98
99 pub fn lenient_source(&self) -> bool {
102 matches!(self.source, "sqlite" | "mysql" | "mariadb")
103 }
104
105 pub fn refuse(&self, construct: &str, reason: &str, alternatives: &[&str]) -> Untranslatable {
106 Untranslatable {
107 construct: construct.to_string(),
108 source: self.source.to_string(),
109 target: self.target.to_string(),
110 reason: reason.to_string(),
111 alternatives: alternatives.iter().map(|s| s.to_string()).collect(),
112 }
113 }
114}
115
116type R<T> = Result<T, Untranslatable>;
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub enum StmtKind {
121 Insert,
122 Update,
123 Delete,
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub enum Escape<'a> {
129 None,
131 Default,
133 Custom(&'a str),
135}
136
137pub trait Target {
139 fn name(&self) -> &'static str;
140
141 fn quote_ident(&self, s: &str) -> String {
142 format!("\"{}\"", s.replace('"', "\"\""))
143 }
144
145 fn string_literal(&self, s: &str) -> String {
146 format!("'{}'", s.replace('\'', "''"))
147 }
148
149 fn placeholder(&self, n: u32) -> String {
151 format!("${n}")
152 }
153
154 fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
155 Ok(if b { "TRUE" } else { "FALSE" }.to_string())
156 }
157
158 fn like(
160 &self,
161 lhs: &str,
162 rhs: &str,
163 negated: bool,
164 ci: bool,
165 esc: Escape<'_>,
166 ctx: &mut Ctx,
167 ) -> R<String> {
168 let kw = if ci { "ILIKE" } else { "LIKE" };
169 ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
170 let tail = match esc {
171 Escape::Default => String::new(), Escape::None => " ESCAPE ''".to_string(),
173 Escape::Custom(c) => format!(" ESCAPE {c}"),
174 };
175 Ok(format!(
176 "{lhs} {}{kw} {rhs}{tail}",
177 if negated { "NOT " } else { "" }
178 ))
179 }
180
181 fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
183 if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
186 return Err(ctx.refuse(
187 &format!("fn:{}", f.name),
188 "no verified mapping for this function on this target yet",
189 &[],
190 ));
191 }
192 ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
193 let order = ctx.agg_order.take();
194 Ok(generic_call_ordered(
195 &f.name,
196 args,
197 f.distinct,
198 f.star,
199 order.as_deref(),
200 ))
201 }
202
203 fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
204 if ctx.lenient_source() {
205 ctx.note(
206 format!("cast.to_{}", ty.leaf()),
207 Tier::Conditional,
208 "the source casts leniently (a malformed value becomes 0); the target raises an error",
209 Some(Allowance::LenientCast),
210 )?;
211 } else {
212 ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
213 }
214 Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
215 }
216
217 fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
218 ctx.note("distinct_on", Tier::Exact, "", None)
219 }
220
221 fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
223 ctx.note("null_safe_eq", Tier::Exact, "", None)?;
224 Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
225 }
226
227 fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
230 ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
231 Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
232 }
233
234 fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
238 Ok(None)
239 }
240
241 fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
244 ctx.note("array_literal", Tier::Exact, "", None)?;
245 Ok(format!("ARRAY[{}]", items.join(", ")))
246 }
247
248 fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
252 ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
253 }
254
255 fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
258 ctx.note("at_time_zone", Tier::Exact, "", None)
259 }
260
261 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
264 ctx.note("array_subquery", Tier::Exact, "", None)
265 }
266
267 fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
271 ctx.note(with_leaf(kind), Tier::Exact, "", None)
272 }
273
274 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
277 ctx.note("cte.data_modifying", Tier::Exact, "", None)
278 }
279
280 fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
284 note_row_lock_leaves(lock, ctx)
285 }
286
287 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
288 ctx.note("returning", Tier::Exact, "", None)
289 }
290
291 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
293 let mut s = String::new();
294 if let Some(l) = limit {
295 s.push_str(&format!(" LIMIT {l}"));
296 ctx.note("limit", Tier::Exact, "", None)?;
297 }
298 if let Some(o) = offset {
299 s.push_str(&format!(" OFFSET {o}"));
300 ctx.note("offset", Tier::Exact, "", None)?;
301 }
302 Ok(s)
303 }
304
305 fn join_tier(&self, _kind: JoinKind) -> Tier {
307 Tier::Exact
308 }
309
310 fn update_from_tier(&self) -> Tier {
312 Tier::Exact
313 }
314
315 fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
318 Ok(None)
319 }
320
321 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
324 ctx.note(name, Tier::Exact, "", None)
325 }
326
327 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
329 ctx.note("trim", Tier::Exact, "", None)?;
330 Ok(match (side, chars) {
331 (TrimSide::Both, None) => format!("TRIM({expr})"),
332 (s, c) => {
333 let kw = match s {
334 TrimSide::Both => "BOTH",
335 TrimSide::Leading => "LEADING",
336 TrimSide::Trailing => "TRAILING",
337 };
338 match c {
339 Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
340 None => format!("TRIM({kw} FROM {expr})"),
341 }
342 }
343 })
344 }
345
346 fn interval_arith(
349 &self,
350 _minus: bool,
351 _left: &str,
352 _parts: &[(String, String)],
353 _ctx: &mut Ctx,
354 ) -> R<Option<String>> {
355 Ok(None)
356 }
357
358 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
360 ctx.note(
361 if text { "json_get_text" } else { "json_get" },
362 Tier::Exact,
363 "",
364 None,
365 )?;
366 Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
367 }
368
369 fn binary_override(
372 &self,
373 _op: BinaryOp,
374 _l: &str,
375 _r: &str,
376 _numeric: bool,
377 _ctx: &mut Ctx,
378 ) -> R<Option<String>> {
379 Ok(None)
380 }
381
382 fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
384 let mut s = expr.to_string();
385 if desc {
386 s.push_str(" DESC");
387 }
388 s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
389 Ok(s)
390 }
391
392 fn excluded_ref(&self, column_quoted: &str) -> String {
394 format!("EXCLUDED.{column_quoted}")
395 }
396
397 #[allow(clippy::too_many_arguments)]
399 fn upsert_clause(
400 &self,
401 conflict_cols: &[String],
402 do_nothing: bool,
403 set: &str,
404 where_: Option<&str>,
405 _first_insert_col: &str,
406 ctx: &mut Ctx,
407 ) -> R<String> {
408 if !do_nothing && conflict_cols.is_empty() {
409 return Err(ctx.refuse(
410 "upsert.no_conflict_key",
411 "the source upsert names no conflict key (MySQL ON DUPLICATE KEY UPDATE fires on any unique key); this target needs the key columns",
412 &["state the conflict key columns in the statement"],
413 ));
414 }
415 ctx.note(
416 if where_.is_some() {
417 "upsert_where"
418 } else {
419 "upsert"
420 },
421 Tier::Exact,
422 "",
423 None,
424 )?;
425 let mut s = String::from(" ON CONFLICT");
426 if !conflict_cols.is_empty() {
427 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
428 }
429 if do_nothing {
430 s.push_str(" DO NOTHING");
431 } else {
432 s.push_str(&format!(" DO UPDATE SET {set}"));
433 if let Some(w) = where_ {
434 s.push_str(&format!(" WHERE {w}"));
435 }
436 }
437 Ok(s)
438 }
439
440 fn array_membership(
444 &self,
445 _lhs: &str,
446 _ph: &str,
447 _negated: bool,
448 n: u32,
449 ctx: &mut Ctx,
450 ) -> R<String> {
451 Err(ctx.refuse(
452 "array_param",
453 &format!(
454 "target `{}` has no codec for an array parameter (${n})",
455 ctx.target
456 ),
457 &["expand the array into an IN (..) list in the application"],
458 ))
459 }
460
461 fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
464 Ok(())
465 }
466
467 fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
470 Ok(())
471 }
472
473 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
476 let default_first = desc;
478 ctx.note("null_ordering", Tier::Exact, "", None)?;
479 if nulls_first == default_first {
480 Ok(String::new())
481 } else {
482 Ok(if nulls_first {
483 " NULLS FIRST"
484 } else {
485 " NULLS LAST"
486 }
487 .to_string())
488 }
489 }
490}
491
492pub const PORTABLE_FUNCTIONS: &[&str] = &[
494 "count",
495 "sum",
496 "min",
497 "max",
498 "avg",
499 "coalesce",
500 "nullif",
501 "abs",
502 "lower",
503 "upper",
504 "length",
505 "replace",
506 "substr",
507 "row_number",
508 "rank",
509 "dense_rank",
510 "percent_rank",
511 "cume_dist",
512 "ntile",
513 "lag",
514 "lead",
515 "first_value",
516 "last_value",
517 "nth_value",
518];
519
520pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
521 generic_call_ordered(name, args, distinct, star, None)
522}
523
524pub fn generic_call_ordered(
526 name: &str,
527 args: &[String],
528 distinct: bool,
529 star: bool,
530 order: Option<&str>,
531) -> String {
532 let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
533 if star {
534 return format!("{}(*)", name.to_uppercase());
535 }
536 format!(
537 "{}({}{}{})",
538 name.to_uppercase(),
539 if distinct { "DISTINCT " } else { "" },
540 args.join(", "),
541 ord
542 )
543}
544
545pub fn pg_type_name(ty: &SqlType) -> String {
547 match ty {
548 SqlType::SmallInt => "SMALLINT".into(),
549 SqlType::Integer => "INTEGER".into(),
550 SqlType::BigInt => "BIGINT".into(),
551 SqlType::Real => "REAL".into(),
552 SqlType::Double => "DOUBLE PRECISION".into(),
553 SqlType::Numeric {
554 precision: None, ..
555 } => "NUMERIC".into(),
556 SqlType::Numeric {
557 precision: Some(p),
558 scale: None,
559 } => format!("NUMERIC({p})"),
560 SqlType::Numeric {
561 precision: Some(p),
562 scale: Some(s),
563 } => format!("NUMERIC({p}, {s})"),
564 SqlType::Text => "TEXT".into(),
565 SqlType::Varchar(None) => "VARCHAR".into(),
566 SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
567 SqlType::Boolean => "BOOLEAN".into(),
568 SqlType::Date => "DATE".into(),
569 SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
570 SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
571 SqlType::Uuid => "UUID".into(),
572 SqlType::Bytes => "BYTEA".into(),
573 SqlType::Json => "JSON".into(),
574 SqlType::Jsonb => "JSONB".into(),
575 }
576}
577
578pub fn date_trunc_field(f: &Function) -> Option<String> {
580 if f.name != "date_trunc" {
581 return None;
582 }
583 match f.args.first() {
584 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
585 _ => None,
586 }
587}
588
589pub fn extract_leaf(field: &str, interval: bool) -> String {
592 if interval && field == "epoch" {
593 "extract.epoch.interval".to_string()
594 } else {
595 format!("extract.{field}")
596 }
597}
598
599pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
601 match lock.strength {
602 RowLock::Update => "row_lock",
603 RowLock::Share => "row_lock.share",
604 }
605}
606
607pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
609 ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
610 if lock.of.is_some() {
611 ctx.note("row_lock.of", Tier::Exact, "", None)?;
612 }
613 match lock.wait {
614 LockWait::Block => {}
615 LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
616 LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
617 }
618 Ok(())
619}
620
621pub fn with_leaf(kind: StmtKind) -> &'static str {
623 match kind {
624 StmtKind::Insert => "with.insert",
625 StmtKind::Update => "with.update",
626 StmtKind::Delete => "with.delete",
627 }
628}