use crate::ast::*;
use crate::report::{Allowance, Entry, Options, ParamBinding, Report, Tier, Untranslatable};
pub struct Ctx<'a> {
pub report: Report,
pub opts: &'a Options,
pub scopes: crate::schema::Scopes<'a>,
pub source: &'a str,
pub target: &'a str,
pub max_param: u32,
pub param_order: Vec<u32>,
pub in_upsert: bool,
pub(crate) upsert_table: Option<String>,
pub agg_order: Option<String>,
pub order_non_text: bool,
pub interval_notation: bool,
pub array_params: std::collections::BTreeMap<u32, ParamBinding>,
pub scalar_params: std::collections::BTreeSet<u32>,
}
impl<'a> Ctx<'a> {
pub fn new(opts: &'a Options, source: &'a str, target: &'a str) -> Self {
Ctx {
report: Report::default(),
opts,
scopes: crate::schema::Scopes::new(opts.schema.as_ref()),
source,
target,
max_param: 0,
param_order: Vec::new(),
in_upsert: false,
upsert_table: None,
agg_order: None,
order_non_text: false,
interval_notation: false,
array_params: Default::default(),
scalar_params: Default::default(),
}
}
pub fn note(
&mut self,
construct: impl Into<String>,
tier: Tier,
note: impl Into<String>,
allowance: Option<Allowance>,
) -> Result<(), Untranslatable> {
let construct = construct.into();
let note = note.into();
match tier {
Tier::Refused => Err(self.refuse(&construct, ¬e, &[])),
Tier::Conditional => {
let a = allowance.expect("a Conditional note must name its Allowance");
if self.source != self.target && !self.opts.allow.contains(&a) {
return Err(self.refuse(
&construct,
&format!("conditional: needs allowance `{}`: {}", a.name(), note),
&[],
));
}
self.report.push(Entry {
construct,
tier,
note,
allowance: Some(a),
});
Ok(())
}
_ => {
self.report.push(Entry {
construct,
tier,
note,
allowance,
});
Ok(())
}
}
}
pub fn bind_array_param(&mut self, n: u32, binding: ParamBinding) {
self.array_params.insert(n, binding);
}
pub fn lenient_source(&self) -> bool {
matches!(self.source, "sqlite" | "mysql" | "mariadb")
}
pub fn refuse(&self, construct: &str, reason: &str, alternatives: &[&str]) -> Untranslatable {
Untranslatable {
construct: construct.to_string(),
source: self.source.to_string(),
target: self.target.to_string(),
reason: reason.to_string(),
alternatives: alternatives.iter().map(|s| s.to_string()).collect(),
}
}
}
type R<T> = Result<T, Untranslatable>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StmtKind {
Insert,
Update,
Delete,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Escape<'a> {
None,
Default,
Custom(&'a str),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DmlLimit {
Native,
RowIdSubquery(&'static str),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DmlSources {
FromClause,
Join,
UpdateFromOnly,
}
pub trait Target {
fn name(&self) -> &'static str;
fn quote_ident(&self, s: &str) -> String {
format!("\"{}\"", s.replace('"', "\"\""))
}
fn string_literal(&self, s: &str) -> String {
format!("'{}'", s.replace('\'', "''"))
}
fn bytes_literal(&self, b: &[u8]) -> String {
let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
format!("'\\x{hex}'::bytea")
}
fn placeholder(&self, n: u32) -> String {
format!("${n}")
}
fn bool_literal(&self, b: bool, _ctx: &mut Ctx) -> R<String> {
Ok(if b { "TRUE" } else { "FALSE" }.to_string())
}
fn like(
&self,
lhs: &str,
rhs: &str,
negated: bool,
ci: bool,
esc: Escape<'_>,
ctx: &mut Ctx,
) -> R<String> {
let kw = if ci { "ILIKE" } else { "LIKE" };
ctx.note(if ci { "ilike" } else { "like" }, Tier::Exact, "", None)?;
let tail = match esc {
Escape::Default => String::new(), Escape::None => " ESCAPE ''".to_string(),
Escape::Custom(c) => format!(" ESCAPE {c}"),
};
Ok(format!(
"{lhs} {}{kw} {rhs}{tail}",
if negated { "NOT " } else { "" }
))
}
fn regexp(&self, lhs: &str, rhs: &str, negated: bool, ctx: &mut Ctx) -> R<String> {
ctx.note(
"regexp",
Tier::Conditional,
"regular-expression syntax and case sensitivity differ between engines; exact only for \
patterns in the common subset",
Some(Allowance::RegexpFlavor),
)?;
Ok(format!("{lhs} {} {rhs}", if negated { "!~" } else { "~" }))
}
fn function(&self, f: &Function, args: &[String], ctx: &mut Ctx) -> R<String> {
if ctx.source != self.name() && !PORTABLE_FUNCTIONS.contains(&f.name.as_str()) {
return Err(ctx.refuse(
&format!("fn:{}", f.name),
"no verified mapping for this function on this target yet",
&[],
));
}
ctx.note(format!("fn:{}", f.name), Tier::Exact, "", None)?;
let order = ctx.agg_order.take();
Ok(generic_call_ordered(
&f.name,
args,
f.distinct,
f.star,
order.as_deref(),
))
}
fn cast(&self, expr: &str, ty: &SqlType, ctx: &mut Ctx) -> R<String> {
if ctx.lenient_source() {
ctx.note(
format!("cast.to_{}", ty.leaf()),
Tier::Conditional,
"the source casts leniently (a malformed value becomes 0); the target raises an error",
Some(Allowance::LenientCast),
)?;
} else {
ctx.note(format!("cast.to_{}", ty.leaf()), Tier::Exact, "", None)?;
}
Ok(format!("CAST({expr} AS {})", pg_type_name(ty)))
}
fn distinct_on(&self, ctx: &mut Ctx) -> R<()> {
ctx.note("distinct_on", Tier::Exact, "", None)
}
fn group_by_rollup(&self, keys: &[String], ctx: &mut Ctx) -> R<String> {
ctx.note("group_by.rollup", Tier::Exact, "", None)?;
Ok(format!("ROLLUP ({})", keys.join(", ")))
}
fn null_safe_eq(&self, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
ctx.note("null_safe_eq", Tier::Exact, "", None)?;
Ok(format!("{lhs} IS NOT DISTINCT FROM {rhs}"))
}
fn extract(&self, field: &str, expr: &str, interval: bool, ctx: &mut Ctx) -> R<String> {
ctx.note(extract_leaf(field, interval), Tier::Exact, "", None)?;
Ok(format!("EXTRACT({} FROM {expr})", field.to_uppercase()))
}
fn epoch_of_difference(&self, _a: &str, _b: &str, _ctx: &mut Ctx) -> R<Option<String>> {
Ok(None)
}
fn epoch_of_clock(&self, ctx: &mut Ctx) -> R<String> {
Err(ctx.refuse(
"extract.epoch",
"no mapping for the per-call wall clock",
&["bind the time as a parameter"],
))
}
fn array_literal(&self, items: &[String], ctx: &mut Ctx) -> R<String> {
ctx.note("array_literal", Tier::Exact, "", None)?;
Ok(format!("ARRAY[{}]", items.join(", ")))
}
fn table_function(&self, name: &str, ctx: &mut Ctx) -> R<()> {
ctx.note(format!("table_function.{name}"), Tier::Exact, "", None)
}
fn series_as_recursive_cte(&self) -> bool {
false
}
fn at_time_zone(&self, ctx: &mut Ctx) -> R<()> {
ctx.note("at_time_zone", Tier::Exact, "", None)
}
fn array_subquery(&self, ctx: &mut Ctx) -> R<()> {
ctx.note("array_subquery", Tier::Exact, "", None)
}
fn with_statement(&self, kind: StmtKind, ctx: &mut Ctx) -> R<()> {
ctx.note(with_leaf(kind), Tier::Exact, "", None)
}
fn data_modifying_cte(&self, ctx: &mut Ctx) -> R<()> {
ctx.note("cte.data_modifying", Tier::Exact, "", None)
}
fn row_lock(&self, lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
note_row_lock_leaves(lock, ctx)
}
fn returning(&self, _kind: StmtKind, ctx: &mut Ctx) -> R<()> {
ctx.note("returning", Tier::Exact, "", None)
}
fn limit_offset(&self, limit: Option<&str>, offset: Option<&str>, ctx: &mut Ctx) -> R<String> {
let mut s = String::new();
if let Some(l) = limit {
s.push_str(&format!(" LIMIT {l}"));
ctx.note("limit", Tier::Exact, "", None)?;
}
if let Some(o) = offset {
s.push_str(&format!(" OFFSET {o}"));
ctx.note("offset", Tier::Exact, "", None)?;
}
Ok(s)
}
fn join_tier(&self, _kind: JoinKind) -> Tier {
Tier::Exact
}
fn dml_sources(&self) -> DmlSources {
DmlSources::FromClause
}
fn dml_limit(&self) -> DmlLimit {
DmlLimit::RowIdSubquery("ctid")
}
fn rewrite_query(&self, _q: &Query, _ctx: &mut Ctx) -> R<Option<Query>> {
Ok(None)
}
fn feature(&self, name: &'static str, ctx: &mut Ctx) -> R<()> {
ctx.note(name, Tier::Exact, "", None)
}
fn trim(&self, side: TrimSide, expr: &str, chars: Option<&str>, ctx: &mut Ctx) -> R<String> {
ctx.note("trim", Tier::Exact, "", None)?;
Ok(match (side, chars) {
(TrimSide::Both, None) => format!("TRIM({expr})"),
(s, c) => {
let kw = match s {
TrimSide::Both => "BOTH",
TrimSide::Leading => "LEADING",
TrimSide::Trailing => "TRAILING",
};
match c {
Some(c) => format!("TRIM({kw} {c} FROM {expr})"),
None => format!("TRIM({kw} FROM {expr})"),
}
}
})
}
fn interval_arith(
&self,
_minus: bool,
_left: &str,
_parts: &[(String, String)],
_ctx: &mut Ctx,
) -> R<Option<String>> {
Ok(None)
}
fn json_access(&self, text: bool, lhs: &str, rhs: &str, ctx: &mut Ctx) -> R<String> {
ctx.note(
if text { "json_get_text" } else { "json_get" },
Tier::Exact,
"",
None,
)?;
Ok(format!("{lhs} {} {rhs}", if text { "->>" } else { "->" }))
}
fn binary_override(
&self,
_op: BinaryOp,
_l: &str,
_r: &str,
_numeric: bool,
_ctx: &mut Ctx,
) -> R<Option<String>> {
Ok(None)
}
fn order_item(&self, expr: &str, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
let mut s = expr.to_string();
if desc {
s.push_str(" DESC");
}
s.push_str(&self.nulls_order(desc, nulls_first, ctx)?);
Ok(s)
}
fn replace_keyword(&self) -> Option<&'static str> {
None
}
fn needs_conflict_key(&self) -> bool {
true
}
fn excluded_ref(&self, column_quoted: &str) -> String {
format!("EXCLUDED.{column_quoted}")
}
fn upsert_where_as_if(&self) -> bool {
false
}
#[allow(clippy::too_many_arguments)]
fn upsert_clause(
&self,
conflict_cols: &[String],
do_nothing: bool,
set: &str,
where_: Option<&str>,
_first_insert_col: &str,
ctx: &mut Ctx,
) -> R<String> {
if !do_nothing && conflict_cols.is_empty() {
return Err(ctx.refuse(
"upsert.no_conflict_key",
"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",
&["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)"],
));
}
ctx.note(
if where_.is_some() {
"upsert_where"
} else {
"upsert"
},
Tier::Exact,
"",
None,
)?;
let mut s = String::from(" ON CONFLICT");
if !conflict_cols.is_empty() {
s.push_str(&format!(" ({})", conflict_cols.join(", ")));
}
if do_nothing {
s.push_str(" DO NOTHING");
} else {
s.push_str(&format!(" DO UPDATE SET {set}"));
if let Some(w) = where_ {
s.push_str(&format!(" WHERE {w}"));
}
}
Ok(s)
}
fn array_membership(
&self,
_lhs: &str,
_ph: &str,
_negated: bool,
n: u32,
ctx: &mut Ctx,
) -> R<String> {
Err(ctx.refuse(
"array_param",
&format!(
"target `{}` has no codec for an array parameter (${n})",
ctx.target
),
&["expand the array into an IN (..) list in the application"],
))
}
fn between(&self, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
Ok(())
}
fn binary_op(&self, _op: BinaryOp, _numeric: bool, _ctx: &mut Ctx) -> R<()> {
Ok(())
}
fn nulls_order(&self, desc: bool, nulls_first: bool, ctx: &mut Ctx) -> R<String> {
let default_first = desc;
ctx.note("null_ordering", Tier::Exact, "", None)?;
if nulls_first == default_first {
Ok(String::new())
} else {
Ok(if nulls_first {
" NULLS FIRST"
} else {
" NULLS LAST"
}
.to_string())
}
}
}
pub const PORTABLE_FUNCTIONS: &[&str] = &[
"count",
"sum",
"min",
"max",
"avg",
"coalesce",
"nullif",
"abs",
"lower",
"upper",
"length",
"replace",
"substr",
"row_number",
"rank",
"dense_rank",
"percent_rank",
"cume_dist",
"ntile",
"lag",
"lead",
"first_value",
"last_value",
"nth_value",
"strpos",
"ceil",
"floor",
];
pub fn generic_call(name: &str, args: &[String], distinct: bool, star: bool) -> String {
generic_call_ordered(name, args, distinct, star, None)
}
pub fn generic_call_ordered(
name: &str,
args: &[String],
distinct: bool,
star: bool,
order: Option<&str>,
) -> String {
let ord = order.map(|o| format!(" ORDER BY {o}")).unwrap_or_default();
if star {
return format!("{}(*)", name.to_uppercase());
}
format!(
"{}({}{}{})",
name.to_uppercase(),
if distinct { "DISTINCT " } else { "" },
args.join(", "),
ord
)
}
pub fn pg_type_name(ty: &SqlType) -> String {
match ty {
SqlType::SmallInt => "SMALLINT".into(),
SqlType::Integer => "INTEGER".into(),
SqlType::BigInt => "BIGINT".into(),
SqlType::Real => "REAL".into(),
SqlType::Double => "DOUBLE PRECISION".into(),
SqlType::Numeric {
precision: None, ..
} => "NUMERIC".into(),
SqlType::Numeric {
precision: Some(p),
scale: None,
} => format!("NUMERIC({p})"),
SqlType::Numeric {
precision: Some(p),
scale: Some(s),
} => format!("NUMERIC({p}, {s})"),
SqlType::Text => "TEXT".into(),
SqlType::Varchar(None) => "VARCHAR".into(),
SqlType::Varchar(Some(n)) => format!("VARCHAR({n})"),
SqlType::Boolean => "BOOLEAN".into(),
SqlType::Date => "DATE".into(),
SqlType::Timestamp { with_tz: false } => "TIMESTAMP".into(),
SqlType::Timestamp { with_tz: true } => "TIMESTAMPTZ".into(),
SqlType::Uuid => "UUID".into(),
SqlType::Regclass => "REGCLASS".into(),
SqlType::Bytes => "BYTEA".into(),
SqlType::Json => "JSON".into(),
SqlType::Jsonb => "JSONB".into(),
}
}
pub fn literal_count(f: &Function, i: usize) -> Option<u64> {
match f.args.get(i) {
Some(FunctionArg::Expr(Expr::Literal(Literal::Number(n)))) => n.parse().ok(),
_ => None,
}
}
pub fn literal_nonempty_string(f: &Function, i: usize) -> bool {
matches!(
f.args.get(i),
Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) if !s.is_empty()
)
}
pub fn utc_timestamp_precision(f: &Function) -> Option<u32> {
match f.args.as_slice() {
[] => Some(0),
[FunctionArg::Expr(Expr::Literal(Literal::Number(n)))] => n.parse().ok(),
_ => None,
}
}
pub fn date_trunc_field(f: &Function) -> Option<String> {
if f.name != "date_trunc" {
return None;
}
match f.args.first() {
Some(FunctionArg::Expr(Expr::Literal(Literal::String(s)))) => Some(s.to_ascii_lowercase()),
_ => None,
}
}
pub fn to_char_format(f: &Function, spec: [&str; 6]) -> Option<String> {
if f.name != "to_char" || f.args.len() != 2 {
return None;
}
let Some(FunctionArg::Expr(Expr::Literal(Literal::String(fmt)))) = f.args.get(1) else {
return None;
};
let mut out = String::new();
let mut rest = fmt.as_str();
while !rest.is_empty() {
let tokens = [
("YYYY", spec[0]),
("MM", spec[1]),
("DD", spec[2]),
("HH24", spec[3]),
("MI", spec[4]),
("SS", spec[5]),
];
if let Some((tok, s)) = tokens.iter().find(|(t, _)| rest.starts_with(t)) {
out.push_str(s);
rest = &rest[tok.len()..];
} else {
let c = rest.chars().next()?;
if !matches!(c, '-' | '/' | ':' | '.' | ',' | ' ') {
return None;
}
out.push(c);
rest = &rest[1..];
}
}
Some(out)
}
pub fn extract_leaf(field: &str, interval: bool) -> String {
if interval && field == "epoch" {
"extract.epoch.interval".to_string()
} else {
format!("extract.{field}")
}
}
pub fn row_lock_leaf(lock: &RowLockClause) -> &'static str {
match lock.strength {
RowLock::Update => "row_lock",
RowLock::Share => "row_lock.share",
}
}
pub fn note_row_lock_leaves(lock: &RowLockClause, ctx: &mut Ctx) -> R<()> {
ctx.note(row_lock_leaf(lock), Tier::Exact, "", None)?;
if lock.of.is_some() {
ctx.note("row_lock.of", Tier::Exact, "", None)?;
}
match lock.wait {
LockWait::Block => {}
LockWait::NoWait => ctx.note("row_lock.nowait", Tier::Exact, "", None)?,
LockWait::SkipLocked => ctx.note("row_lock.skip_locked", Tier::Exact, "", None)?,
}
Ok(())
}
pub fn with_leaf(kind: StmtKind) -> &'static str {
match kind {
StmtKind::Insert => "with.insert",
StmtKind::Update => "with.update",
StmtKind::Delete => "with.delete",
}
}