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 at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
251 ctx.note("at_time_zone", Tier::Exact, "", None)
252 }
253
254 fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
257 ctx.note("array_subquery", Tier::Exact, "", None)
258 }
259
260 fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
264 ctx.note(with_leaf(kind), Tier::Exact, "", None)
265 }
266
267 fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
270 ctx.note("cte.data_modifying", Tier::Exact, "", None)
271 }
272
273 fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
277 note_row_lock_leaves(lock, ctx)
278 }
279
280 fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
281 ctx.note("returning", Tier::Exact, "", None)
282 }
283
284 fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
286 let mut s = String::new();
287 if let Some(l) = limit {
288 s.push_str(&format!(" LIMIT {l}"));
289 ctx.note("limit", Tier::Exact, "", None)?;
290 }
291 if let Some(o) = offset {
292 s.push_str(&format!(" OFFSET {o}"));
293 ctx.note("offset", Tier::Exact, "", None)?;
294 }
295 Ok(s)
296 }
297
298 fn join_tier(&self, _kind: JoinKind) -> Tier {
300 Tier::Exact
301 }
302
303 fn update_from_tier(&self) -> Tier {
305 Tier::Exact
306 }
307
308 fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
311 Ok(None)
312 }
313
314 fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
317 ctx.note(name, Tier::Exact, "", None)
318 }
319
320 fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
322 ctx.note("trim", Tier::Exact, "", None)?;
323 Ok(match (side, chars) {
324 (TrimSide::Both, None) => format!("TRIM({expr})"),
325 (s, c) => {
326 let kw = match s {
327 TrimSide::Both => "BOTH",
328 TrimSide::Leading => "LEADING",
329 TrimSide::Trailing => "TRAILING",
330 };
331 match c {
332 Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
333 None => format!("TRIM({kw} FROM {expr})"),
334 }
335 }
336 })
337 }
338
339 fn interval_arith(
342 &self,
343 _minus: bool,
344 _left: &str,
345 _parts: &[(String, String)],
346 _ctx: &mut Ctx,
347 ) -> R<Option<String>> {
348 Ok(None)
349 }
350
351 fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
353 ctx.note(
354 if text { "json_get_text" } else { "json_get" },
355 Tier::Exact,
356 "",
357 None,
358 )?;
359 Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
360 }
361
362 fn binary_override(
365 &self,
366 _op: BinaryOp,
367 _l: &str,
368 _r: &str,
369 _numeric: bool,
370 _ctx: &mut Ctx,
371 ) -> R<Option<String>> {
372 Ok(None)
373 }
374
375 fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
377 let mut s = expr.to_string();
378 if desc {
379 s.push_str(" DESC");
380 }
381 s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
382 Ok(s)
383 }
384
385 fn excluded_ref(&self, column_quoted: &str) -> String {
387 format!("EXCLUDED.{column_quoted}")
388 }
389
390 #[allow(clippy::too_many_arguments)]
392 fn upsert_clause(
393 &self,
394 conflict_cols: &[String],
395 do_nothing: bool,
396 set: &str,
397 where_: Option<&str>,
398 _first_insert_col: &str,
399 ctx: &mut Ctx,
400 ) -> R<String> {
401 if !do_nothing && conflict_cols.is_empty() {
402 return Err(ctx.refuse(
403 "upsert.no_conflict_key",
404 "the source upsert names no conflict key (MySQL ON DUPLICATE KEY UPDATE fires on any unique key); this target needs the key columns",
405 &["state the conflict key columns in the statement"],
406 ));
407 }
408 ctx.note(
409 if where_.is_some() {
410 "upsert_where"
411 } else {
412 "upsert"
413 },
414 Tier::Exact,
415 "",
416 None,
417 )?;
418 let mut s = String::from(" ON CONFLICT");
419 if !conflict_cols.is_empty() {
420 s.push_str(&format!(" ({})", conflict_cols.join(", ")));
421 }
422 if do_nothing {
423 s.push_str(" DO NOTHING");
424 } else {
425 s.push_str(&format!(" DO UPDATE SET {set}"));
426 if let Some(w) = where_ {
427 s.push_str(&format!(" WHERE {w}"));
428 }
429 }
430 Ok(s)
431 }
432
433 fn array_membership(
437 &self,
438 _lhs: &str,
439 _ph: &str,
440 _negated: bool,
441 n: u32,
442 ctx: &mut Ctx,
443 ) -> R<String> {
444 Err(ctx.refuse(
445 "array_param",
446 &format!(
447 "target `{}` has no codec for an array parameter (${n})",
448 ctx.target
449 ),
450 &["expand the array into an IN (..) list in the application"],
451 ))
452 }
453
454 fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
457 Ok(())
458 }
459
460 fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
463 Ok(())
464 }
465
466 fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
469 let default_first = desc;
471 ctx.note("null_ordering", Tier::Exact, "", None)?;
472 if nulls_first == default_first {
473 Ok(String::new())
474 } else {
475 Ok(if nulls_first {
476 " NULLS FIRST"
477 } else {
478 " NULLS LAST"
479 }
480 .to_string())
481 }
482 }
483}
484
485pub const PORTABLE_FUNCTIONS: &[&str] = &[
487 "count",
488 "sum",
489 "min",
490 "max",
491 "avg",
492 "coalesce",
493 "nullif",
494 "abs",
495 "lower",
496 "upper",
497 "length",
498 "replace",
499 "substr",
500 "row_number",
501 "rank",
502 "dense_rank",
503 "percent_rank",
504 "cume_dist",
505 "ntile",
506 "lag",
507 "lead",
508 "first_value",
509 "last_value",
510 "nth_value",
511];
512
513pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
514 generic_call_ordered(name, args, distinct, star, None)
515}
516
517pub fn generic_call_ordered(
519 name: &str,
520 args: &[String],
521 distinct: bool,
522 star: bool,
523 order: Option<&str>,
524) -> String {
525 let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
526 if star {
527 return format!("{}(*)", name.to_uppercase());
528 }
529 format!(
530 "{}({}{}{})",
531 name.to_uppercase(),
532 if distinct { "DISTINCT " } else { "" },
533 args.join(", "),
534 ord
535 )
536}
537
538pub fn pg_type_name(ty: &SqlType) -> String {
540 match ty {
541 SqlType::SmallInt => "SMALLINT".into(),
542 SqlType::Integer => "INTEGER".into(),
543 SqlType::BigInt => "BIGINT".into(),
544 SqlType::Real => "REAL".into(),
545 SqlType::Double => "DOUBLE PRECISION".into(),
546 SqlType::Numeric {
547 precision: None, ..
548 } => "NUMERIC".into(),
549 SqlType::Numeric {
550 precision: Some(p),
551 scale: None,
552 } => format!("NUMERIC({p})"),
553 SqlType::Numeric {
554 precision: Some(p),
555 scale: Some(s),
556 } => format!("NUMERIC({p}, {s})"),
557 SqlType::Text => "TEXT".into(),
558 SqlType::Varchar(None) => "VARCHAR".into(),
559 SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
560 SqlType::Boolean => "BOOLEAN".into(),
561 SqlType::Date => "DATE".into(),
562 SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
563 SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
564 SqlType::Uuid => "UUID".into(),
565 SqlType::Bytes => "BYTEA".into(),
566 SqlType::Json => "JSON".into(),
567 SqlType::Jsonb => "JSONB".into(),
568 }
569}
570
571pub fn date_trunc_field(f: &Function) -> Option<String> {
573 if f.name != "date_trunc" {
574 return None;
575 }
576 match f.args.first() {
577 Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
578 _ => None,
579 }
580}
581
582pub fn extract_leaf(field: &str, interval: bool) -> String {
585 if interval && field == "epoch" {
586 "extract.epoch.interval".to_string()
587 } else {
588 format!("extract.{field}")
589 }
590}
591
592pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
594 match lock.strength {
595 RowLock::Update => "row_lock",
596 RowLock::Share => "row_lock.share",
597 }
598}
599
600pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
602 ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
603 if lock.of.is_some() {
604 ctx.note("row_lock.of", Tier::Exact, "", None)?;
605 }
606 match lock.wait {
607 LockWait::Block => {}
608 LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
609 LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
610 }
611 Ok(())
612}
613
614pub fn with_leaf(kind: StmtKind) -> &'static str {
616 match kind {
617 StmtKind::Insert => "with.insert",
618 StmtKind::Update => "with.update",
619 StmtKind::Delete => "with.delete",
620 }
621}