use crate::ast::*;
use crate::report::{Allowance, Options, ParamBinding, Tier, Translation, Untranslatable};
use crate::target::{Ctx, DmlLimit, DmlSources, Escape, StmtKind, Target};
type R<T> = Result<T, Untranslatable>;
pub fn write(
stmt: &Statement,
source: &str,
target: &dyn Target,
opts: &Options,
) -> Result<Translation, Untranslatable> {
let mut ctx = Ctx::new(opts, source, target.name());
let sql = Printer { t: target }.statement(stmt, &mut ctx)?;
let have: std::collections::BTreeSet<String> = ctx
.report
.entries
.iter()
.map(|e| e.construct.clone())
.collect();
for need in crate::needs::constructs(stmt) {
if !have.contains(&need) {
ctx.report.push(crate::report::Entry {
construct: need,
tier: crate::report::Tier::Exact,
note: String::new(),
allowance: None,
});
}
}
if let Some(n) = ctx
.array_params
.keys()
.find(|n| ctx.scalar_params.contains(n))
{
return Err(ctx.refuse(
"array_param",
&format!("parameter ${n} is used both as an array and as a single value"),
&[],
));
}
let param_bindings = (1..=ctx.max_param)
.map(|n| {
ctx.array_params
.get(&n)
.copied()
.unwrap_or(ParamBinding::Scalar)
})
.collect();
Ok(Translation {
sql,
param_count: ctx.max_param,
param_order: ctx.param_order,
param_bindings,
report: ctx.report,
})
}
struct Printer<'t> {
t: &'t dyn Target,
}
impl Printer<'_> {
fn id(&self, s: &str) -> String {
self.t.quote_ident(s)
}
fn name(&self, n: &Name) -> String {
n.0.iter().map(|p| self.id(p)).collect::<Vec<_>>().join(".")
}
fn statement(&self, s: &Statement, c: &mut Ctx) -> R<String> {
match s {
Statement::Query(q) => self.query(q, c),
Statement::With(w) => {
let kind = match &*w.stmt {
Statement::Insert(_) => StmtKind::Insert,
Statement::Update(_) => StmtKind::Update,
_ => StmtKind::Delete,
};
self.t.with_statement(kind, c)?;
let head = self.with_clause(w.recursive, &w.ctes, c)?;
Ok(format!("{head}{}", self.statement(&w.stmt, c)?))
}
Statement::Insert(i) => self.insert(i, c),
Statement::Update(u) => self.update(u, c),
Statement::Delete(d) => self.delete(d, c),
}
}
fn with_clause(&self, recursive: bool, ctes: &[Cte], c: &mut Ctx) -> R<String> {
let mut out = String::from("WITH ");
if recursive {
self.t.feature("recursive_cte", c)?;
out.push_str("RECURSIVE ");
}
let mut parts = Vec::new();
for cte in ctes {
let cols = if cte.columns.is_empty() {
String::new()
} else {
format!(
" ({})",
cte.columns
.iter()
.map(|x| self.id(x))
.collect::<Vec<_>>()
.join(", ")
)
};
let inner = match &cte.body {
CteBody::Query(q) => self.query(q, c)?,
CteBody::Dml(st) => {
self.t.data_modifying_cte(c)?;
self.statement(st, c)?
}
};
parts.push(format!("{}{} AS ({inner})", self.id(&cte.name), cols));
}
out.push_str(&parts.join(", "));
out.push(' ');
Ok(out)
}
fn query(&self, q: &Query, c: &mut Ctx) -> R<String> {
let saved = (c.in_upsert, c.upsert_table.take());
c.in_upsert = false;
let out = self.query_inner(q, c);
(c.in_upsert, c.upsert_table) = saved;
out
}
fn query_inner(&self, q: &Query, c: &mut Ctx) -> R<String> {
if let Some(q2) = self.t.rewrite_query(q, c)? {
return self.query(&q2, c);
}
let mut out = String::new();
if !q.with.is_empty() {
out.push_str(&self.with_clause(q.recursive, &q.with, c)?);
}
out.push_str(&self.set_expr(&q.body, c)?);
if !q.order_by.is_empty() {
out.push_str(" ORDER BY ");
let from = match &q.body {
SetExpr::Select(sel) => Some(&sel.from),
SetExpr::SetOp { .. } => None,
};
if let Some(f) = from {
c.scopes.push_from(f);
}
let items = self.order_items(&q.order_by, c);
if from.is_some() {
c.scopes.pop();
}
out.push_str(&items?);
}
let limit = q.limit.as_ref().map(|e| self.expr(e, c)).transpose()?;
let offset = q.offset.as_ref().map(|e| self.expr(e, c)).transpose()?;
out.push_str(
&self
.t
.limit_offset(limit.as_deref(), offset.as_deref(), c)?,
);
if let SetExpr::Select(sel) = &q.body
&& let Some(l) = &sel.lock
{
out.push_str(&self.lock_clause(l, c)?);
}
Ok(out)
}
fn lock_clause(&self, l: &RowLockClause, c: &mut Ctx) -> R<String> {
self.t.row_lock(l, c)?;
let mut out = String::from(match l.strength {
RowLock::Update => " FOR UPDATE",
RowLock::Share => " FOR SHARE",
});
if let Some(of) = &l.of {
let parts: Vec<String> = of.0.iter().map(|p| self.id(p)).collect();
out.push_str(&format!(" OF {}", parts.join(".")));
}
out.push_str(match l.wait {
LockWait::Block => "",
LockWait::NoWait => " NOWAIT",
LockWait::SkipLocked => " SKIP LOCKED",
});
Ok(out)
}
fn collation_note(&self, construct: &str, operands: &[&Expr], c: &mut Ctx) -> R<()> {
if c.source == c.target {
return Ok(());
}
for e in operands {
if let Some(name) = c.scopes.non_bytewise_collation(e) {
c.note(
construct,
Tier::Conditional,
format!(
"the column's collation `{name}` compares and orders text by locale rules; \
the target compares bytes"
),
Some(Allowance::SourceCollationNotBytewise),
)?;
}
}
Ok(())
}
fn order_items(&self, items: &[OrderItem], c: &mut Ctx) -> R<String> {
let mut parts = Vec::new();
for it in items {
self.collation_note("order_by", &[&it.expr], c)?;
let e = self.expr(&it.expr, c)?;
let nf = it.nulls_first.unwrap_or(it.desc);
c.order_non_text = c.scopes.is_non_text_column(&it.expr);
let item = self.t.order_item(&e, it.desc, nf, c);
c.order_non_text = false;
parts.push(item?);
}
Ok(parts.join(", "))
}
fn set_expr(&self, s: &SetExpr, c: &mut Ctx) -> R<String> {
match s {
SetExpr::Select(sel) => self.select(sel, c),
SetExpr::SetOp {
op,
all,
left,
right,
} => {
let kw = match op {
SetOp::Union => "UNION",
SetOp::Intersect => "INTERSECT",
SetOp::Except => "EXCEPT",
};
Ok(format!(
"{} {}{} {}",
self.set_expr(left, c)?,
kw,
if *all { " ALL" } else { "" },
self.set_expr(right, c)?
))
}
}
}
fn select(&self, s: &Select, c: &mut Ctx) -> R<String> {
c.scopes.push_from(&s.from);
let r = self.select_in_scope(s, c);
c.scopes.pop();
r
}
fn select_in_scope(&self, s: &Select, c: &mut Ctx) -> R<String> {
let mut out = String::from("SELECT ");
match &s.distinct {
Distinct::No => {}
Distinct::Yes => out.push_str("DISTINCT "),
Distinct::On(exprs) => {
self.t.distinct_on(c)?;
let e = exprs
.iter()
.map(|e| self.expr(e, c))
.collect::<R<Vec<_>>>()?;
out.push_str(&format!("DISTINCT ON ({}) ", e.join(", ")));
}
}
out.push_str(&self.select_items(&s.projection, c)?);
if !s.from.is_empty() {
let f = s
.from
.iter()
.map(|t| self.table_ref(t, c))
.collect::<R<Vec<_>>>()?;
out.push_str(&format!(" FROM {}", f.join(", ")));
}
if let Some(w) = &s.where_ {
out.push_str(&format!(" WHERE {}", self.expr(w, c)?));
}
if !s.group_by.is_empty() {
let g = s
.group_by
.iter()
.map(|e| self.expr(e, c))
.collect::<R<Vec<_>>>()?;
if s.group_by_rollup {
out.push_str(&format!(" GROUP BY {}", self.t.group_by_rollup(&g, c)?));
} else {
out.push_str(&format!(" GROUP BY {}", g.join(", ")));
}
}
if let Some(h) = &s.having {
out.push_str(&format!(" HAVING {}", self.expr(h, c)?));
}
Ok(out)
}
fn select_items(&self, items: &[SelectItem], c: &mut Ctx) -> R<String> {
let mut parts = Vec::new();
for it in items {
parts.push(match it {
SelectItem::Wildcard => "*".to_string(),
SelectItem::QualifiedWildcard(n) => format!("{}.*", self.name(n)),
SelectItem::Expr { expr, alias } => {
let e = self.expr(expr, c)?;
match alias {
Some(a) => format!("{e} AS {}", self.id(a)),
None => e,
}
}
});
}
Ok(parts.join(", "))
}
fn series_cte(
&self,
name: &str,
args: &[Expr],
alias: Option<&str>,
c: &mut Ctx,
) -> R<Option<String>> {
if !name.eq_ignore_ascii_case("generate_series") || !self.t.series_as_recursive_cte() {
return Ok(None);
}
let Some(alias) = alias else {
return Err(c.refuse(
"table_function.generate_series.alias",
"generate_series() without an alias names its column generate_series",
&["add an alias: generate_series(1, 3) AS g"],
));
};
let (start, stop, step) = match series_bounds(args) {
Some(b) => b,
None => {
return Err(c.refuse(
"table_function.generate_series.args",
"generate_series() is mapped only for two or three integer literal arguments, step not 0",
&["write the bounds as integer literals, or generate the rows in the application"],
));
}
};
c.note(
"table_function.generate_series",
Tier::Emulated,
"-> a derived table over WITH RECURSIVE, integer literal bounds only",
None,
)?;
self.t.feature("recursive_cte", c)?;
let g = self.id(alias);
let (cmp, keep) = if step > 0 { ("<", "<=") } else { (">", ">=") };
Ok(Some(format!(
"(WITH RECURSIVE {g} ({g}) AS (SELECT {start} UNION ALL SELECT {g} + ({step}) FROM {g} WHERE {g} {cmp} {stop}) SELECT {g} FROM {g} WHERE {g} {keep} {stop}) AS {g}"
)))
}
fn table_ref(&self, t: &TableRef, c: &mut Ctx) -> R<String> {
match t {
TableRef::Table { name, alias } => Ok(match alias {
Some(a) => format!("{} AS {}", self.name(name), self.id(a)),
None => self.name(name),
}),
TableRef::Subquery { query, alias } => {
Ok(format!("({}) AS {}", self.query(query, c)?, self.id(alias)))
}
TableRef::Function { name, args, alias } => {
if let Some(s) = self.series_cte(name, args, alias.as_deref(), c)? {
return Ok(s);
}
self.t.table_function(name, c)?;
let a = args
.iter()
.map(|x| self.expr(x, c))
.collect::<R<Vec<_>>>()?;
let call = format!("{}({})", name.to_uppercase(), a.join(", "));
Ok(match alias {
Some(al) => format!("{call} AS {}", self.id(al)),
None => call,
})
}
TableRef::Join {
left,
right,
kind,
on,
using,
natural,
} => {
let kw = match kind {
JoinKind::Inner => "INNER JOIN",
JoinKind::Left => "LEFT JOIN",
JoinKind::Right => "RIGHT JOIN",
JoinKind::Full => "FULL JOIN",
JoinKind::Cross => "CROSS JOIN",
};
if *natural {
c.note("join.natural", Tier::Exact, "", None)?;
}
if !using.is_empty() {
c.note("join.using", Tier::Exact, "", None)?;
}
c.note(
format!("join:{}", kw.to_lowercase().replace(' ', "_")),
self.t.join_tier(*kind),
"",
None,
)?;
let kw = if *natural {
format!("NATURAL {}", kw.replace("INNER ", ""))
} else {
kw.to_string()
};
let mut s = format!(
"{} {} {}",
self.table_ref(left, c)?,
kw,
self.table_ref(right, c)?
);
if let Some(on) = on {
s.push_str(&format!(" ON {}", self.expr(on, c)?));
}
if !using.is_empty() {
let cols = using.iter().map(|u| self.id(u)).collect::<Vec<_>>();
s.push_str(&format!(" USING ({})", cols.join(", ")));
}
Ok(s)
}
}
}
fn returning(&self, items: &[SelectItem], kind: StmtKind, c: &mut Ctx) -> R<String> {
if items.is_empty() {
return Ok(String::new());
}
self.t.returning(kind, c)?;
Ok(format!(" RETURNING {}", self.select_items(items, c)?))
}
fn insert(&self, i: &Insert, c: &mut Ctx) -> R<String> {
let replace_native = if i.replace {
self.t.replace_keyword()
} else {
None
};
let mut out = format!(
"{} {}",
replace_native.unwrap_or("INSERT INTO"),
self.name(&i.table)
);
if !i.columns.is_empty() {
out.push_str(&format!(
" ({})",
i.columns
.iter()
.map(|x| self.id(x))
.collect::<Vec<_>>()
.join(", ")
));
}
match &i.source {
InsertSource::DefaultValues => out.push_str(" DEFAULT VALUES"),
InsertSource::Query(q) => out.push_str(&format!(" {}", self.query(q, c)?)),
InsertSource::Values(rows) => {
let mut rs = Vec::new();
for r in rows {
let es = r.iter().map(|e| self.expr(e, c)).collect::<R<Vec<_>>>()?;
rs.push(format!("({})", es.join(", ")));
}
out.push_str(&format!(" VALUES {}", rs.join(", ")));
}
}
if i.replace && replace_native.is_some() {
c.note("replace_into", Tier::Exact, "", None)?;
} else if i.replace {
let table_cols = c.scopes.complete_columns(&i.table);
let key = match c.scopes.unique_keys(&i.table) {
Some([k]) => Some(k),
_ => None,
};
let (Some(all), Some(key)) = (table_cols, key) else {
return Err(c.refuse(
"replace_into",
"REPLACE INTO deletes conflicting rows; this target has no such statement. It can be \
written as an upsert only when the schema states the table's complete column list and \
exactly one unique key",
&["give the schema the table (schema_from_ddl)", "or write the upsert yourself"],
));
};
c.note(
"replace_into",
Tier::Conditional,
"written as an upsert setting every column: the old row is updated in place, not deleted",
Some(Allowance::ReplaceIsUpsert),
)?;
let cols: Vec<String> = key.iter().map(|x| self.id(x)).collect();
let set: Vec<String> = all
.iter()
.filter(|col| !key.iter().any(|k| k == *col))
.map(|col| {
let q = self.id(col);
format!("{q} = {}", self.t.excluded_ref(&q))
})
.collect();
let first = i.columns.first().map(|x| self.id(x)).unwrap_or_default();
out.push_str(&self.t.upsert_clause(
&cols,
set.is_empty(),
&set.join(", "),
None,
&first,
c,
)?);
}
if let Some(oc) = &i.on_conflict {
let mut cols: Vec<String> = oc.target.iter().map(|x| self.id(x)).collect();
if oc.target.is_empty()
&& matches!(oc.action, ConflictAction::DoUpdate { .. })
&& self.t.needs_conflict_key()
&& let Some([key]) = c.scopes.unique_keys(&i.table)
{
cols = key.iter().map(|x| self.id(x)).collect();
c.note(
"upsert.key_from_schema",
Tier::Exact,
"conflict key taken from the schema's only unique key of the table",
None,
)?;
}
let first = i.columns.first().map(|x| self.id(x)).unwrap_or_default();
let (do_nothing, set, where_) = match &oc.action {
ConflictAction::DoNothing => (true, String::new(), None),
ConflictAction::DoUpdate {
set,
where_: Some(w),
} if self.t.upsert_where_as_if() => {
c.in_upsert = true;
c.upsert_table = Some(self.id(i.table.last()));
c.scopes.push_upsert(&i.table);
let s = self.upsert_set_if(set, w, c);
c.scopes.pop();
c.in_upsert = false;
c.upsert_table = None;
(false, s?, None)
}
ConflictAction::DoUpdate { set, where_ } => {
c.in_upsert = true;
c.upsert_table = Some(self.id(i.table.last()));
c.scopes.push_upsert(&i.table);
let s = self.assignments(set, None, c);
let w = where_.as_ref().map(|w| self.expr(w, c)).transpose();
c.scopes.pop();
c.in_upsert = false;
c.upsert_table = None;
(false, s?, w?)
}
};
out.push_str(&self.t.upsert_clause(
&cols,
do_nothing,
&set,
where_.as_deref(),
&first,
c,
)?);
}
out.push_str(&self.returning(&i.returning, StmtKind::Insert, c)?);
Ok(out)
}
fn upsert_set_if(&self, set: &[Assignment], w: &Expr, c: &mut Ctx) -> R<String> {
c.note(
"upsert_where",
Tier::Conditional,
"ON DUPLICATE KEY UPDATE has no WHERE: written as IF() in each SET expression; rows affected is 1 inserted, 2 updated, 0 kept or unchanged",
Some(Allowance::UpsertWhereAsIf),
)?;
let mark = c.param_order.len();
let probe = self.expr(w, c)?;
c.param_order.truncate(mark);
let (read, rest): (Vec<_>, Vec<_>) = set
.iter()
.partition(|a| probe.contains(&self.id(&a.column)));
if read.len() > 1 {
return Err(c.refuse(
"upsert_where.two_columns",
"the WHERE reads more than one column the upsert sets; MySQL assigns left to right, so no order keeps each condition on the old row",
&["make the condition read one assigned column", "or run an UPDATE .. WHERE in the same transaction"],
));
}
let mut parts = Vec::new();
for a in rest.into_iter().chain(read) {
let col = self.id(&a.column);
let cond = self.expr(w, c)?;
let new = self.expr(&a.value, c)?;
parts.push(format!("{col} = IF({cond}, {new}, {col})"));
}
Ok(parts.join(", "))
}
fn assignments(&self, set: &[Assignment], qualifier: Option<&str>, c: &mut Ctx) -> R<String> {
let mut parts = Vec::new();
for a in set {
let col = match qualifier {
Some(q) => format!("{}.{}", self.id(q), self.id(&a.column)),
None => self.id(&a.column),
};
parts.push(format!("{col} = {}", self.expr(&a.value, c)?));
}
Ok(parts.join(", "))
}
fn update(&self, u: &Update, c: &mut Ctx) -> R<String> {
c.scopes.push_target(&u.table, u.alias.as_deref(), &u.from);
let r = self.update_in_scope(u, c);
c.scopes.pop();
r
}
fn update_in_scope(&self, u: &Update, c: &mut Ctx) -> R<String> {
let mut out = format!("UPDATE {}", self.name(&u.table));
if let Some(a) = &u.alias {
out.push_str(&format!(" AS {}", self.id(a)));
}
let join_form = !u.from.is_empty() && self.t.dml_sources() == DmlSources::Join;
let sources = if u.from.is_empty() {
Vec::new()
} else {
c.note("update_from", Tier::Exact, "", None)?;
u.from
.iter()
.map(|t| self.table_ref(t, c))
.collect::<R<Vec<_>>>()?
};
if join_form {
out.push_str(&format!(", {}", sources.join(", ")));
}
let qualifier = if join_form {
u.alias.as_deref().or(u.table.0.last().map(String::as_str))
} else {
None
};
out.push_str(&format!(" SET {}", self.assignments(&u.set, qualifier, c)?));
if !sources.is_empty() && !join_form {
out.push_str(&format!(" FROM {}", sources.join(", ")));
}
out.push_str(&self.dml_filter(
"update_limit",
&u.table,
u.alias.as_deref(),
u.from.is_empty(),
u.where_.as_ref(),
&u.order_by,
u.limit.as_ref(),
c,
)?);
out.push_str(&self.returning(&u.returning, StmtKind::Update, c)?);
Ok(out)
}
fn delete(&self, d: &Delete, c: &mut Ctx) -> R<String> {
c.scopes.push_target(&d.table, d.alias.as_deref(), &d.using);
let r = self.delete_in_scope(d, c);
c.scopes.pop();
r
}
fn delete_in_scope(&self, d: &Delete, c: &mut Ctx) -> R<String> {
let mut out = String::new();
if d.using.is_empty() {
out.push_str(&format!("DELETE FROM {}", self.name(&d.table)));
if let Some(a) = &d.alias {
out.push_str(&format!(" AS {}", self.id(a)));
}
} else {
let sources = d
.using
.iter()
.map(|t| self.table_ref(t, c))
.collect::<R<Vec<_>>>()?;
match self.t.dml_sources() {
DmlSources::UpdateFromOnly => {
return Err(c.refuse(
"delete_using",
"this target has no multi-table DELETE",
&["rewrite with a subquery: DELETE FROM t WHERE id IN (SELECT ..)"],
));
}
DmlSources::FromClause => {
c.note("delete_using", Tier::Exact, "", None)?;
out.push_str(&format!("DELETE FROM {}", self.name(&d.table)));
if let Some(a) = &d.alias {
out.push_str(&format!(" AS {}", self.id(a)));
}
out.push_str(&format!(" USING {}", sources.join(", ")));
}
DmlSources::Join => {
c.note("delete_using", Tier::Exact, "", None)?;
let target = d.alias.as_deref().or(d.table.0.last().map(String::as_str));
out.push_str(&format!(
"DELETE {} FROM {}",
self.id(target.unwrap_or_default()),
self.name(&d.table)
));
if let Some(a) = &d.alias {
out.push_str(&format!(" AS {}", self.id(a)));
}
out.push_str(&format!(", {}", sources.join(", ")));
}
}
}
out.push_str(&self.dml_filter(
"delete_limit",
&d.table,
d.alias.as_deref(),
d.using.is_empty(),
d.where_.as_ref(),
&d.order_by,
d.limit.as_ref(),
c,
)?);
out.push_str(&self.returning(&d.returning, StmtKind::Delete, c)?);
Ok(out)
}
#[allow(clippy::too_many_arguments)]
fn dml_filter(
&self,
leaf: &str,
table: &Name,
alias: Option<&str>,
single_table: bool,
where_: Option<&Expr>,
order_by: &[OrderItem],
limit: Option<&Expr>,
c: &mut Ctx,
) -> R<String> {
let w = where_.map(|w| self.expr(w, c)).transpose()?;
if order_by.is_empty() && limit.is_none() {
return Ok(w.map(|w| format!(" WHERE {w}")).unwrap_or_default());
}
let order = if order_by.is_empty() {
String::new()
} else {
format!(" ORDER BY {}", self.order_items(order_by, c)?)
};
let lim = match limit {
Some(l) => format!(" LIMIT {}", self.expr(l, c)?),
None => String::new(),
};
let wh = w.map(|w| format!(" WHERE {w}")).unwrap_or_default();
match self.t.dml_limit() {
DmlLimit::Native => {
if !single_table {
return Err(c.refuse(
leaf,
"ORDER BY/LIMIT on a statement with FROM/USING tables",
&["pick the rows in a subquery: WHERE id IN (SELECT id FROM .. ORDER BY .. LIMIT n)"],
));
}
c.note(leaf, Tier::Exact, "", None)?;
Ok(format!("{wh}{order}{lim}"))
}
DmlLimit::RowIdSubquery(id) => {
if !single_table {
return Err(c.refuse(
leaf,
"ORDER BY/LIMIT on a statement with FROM/USING tables",
&["pick the rows in a subquery: WHERE id IN (SELECT id FROM .. ORDER BY .. LIMIT n)"],
));
}
if limit.is_none() {
c.note(leaf, Tier::Exact, "", None)?;
return Ok(wh);
}
c.note(
leaf,
Tier::Emulated,
format!(
"no direct form: rows are picked by `{id}` in a subquery, which needs an ordinary table with a physical row identifier"
),
None,
)?;
let a = alias
.map(|a| format!(" AS {}", self.id(a)))
.unwrap_or_default();
Ok(format!(
" WHERE {id} IN (SELECT {id} FROM {}{a}{wh}{order}{lim})",
self.name(table)
))
}
}
}
fn operand(&self, e: &Expr, c: &mut Ctx) -> R<String> {
let s = self.expr(e, c)?;
Ok(match e {
Expr::Binary { .. }
| Expr::Unary { .. }
| Expr::IsNull { .. }
| Expr::IsBool { .. }
| Expr::InList { .. }
| Expr::InSubquery { .. }
| Expr::Between { .. }
| Expr::Regexp { .. }
| Expr::Like { .. } => format!("({s})"),
Expr::Nested(inner) => self.operand(inner, c)?,
_ => s,
})
}
fn window(&self, w: &Window, c: &mut Ctx) -> R<String> {
let mut parts = Vec::new();
if !w.partition_by.is_empty() {
let p = w
.partition_by
.iter()
.map(|e| self.expr(e, c))
.collect::<R<Vec<_>>>()?;
parts.push(format!("PARTITION BY {}", p.join(", ")));
}
if !w.order_by.is_empty() {
parts.push(format!("ORDER BY {}", self.order_items(&w.order_by, c)?));
}
if let Some(f) = &w.frame {
let u = match f.units {
FrameUnits::Rows => "ROWS",
FrameUnits::Range => "RANGE",
FrameUnits::Groups => "GROUPS",
};
let b = |x: &FrameBound, c: &mut Ctx| -> R<String> {
Ok(match x {
FrameBound::CurrentRow => "CURRENT ROW".to_string(),
FrameBound::Preceding(None) => "UNBOUNDED PRECEDING".to_string(),
FrameBound::Following(None) => "UNBOUNDED FOLLOWING".to_string(),
FrameBound::Preceding(Some(e)) => format!("{} PRECEDING", self.expr(e, c)?),
FrameBound::Following(Some(e)) => format!("{} FOLLOWING", self.expr(e, c)?),
})
};
let s = match &f.end {
None => format!("{u} {}", b(&f.start, c)?),
Some(e) => format!("{u} BETWEEN {} AND {}", b(&f.start, c)?, b(e, c)?),
};
parts.push(s);
}
Ok(parts.join(" "))
}
fn expr(&self, e: &Expr, c: &mut Ctx) -> R<String> {
Ok(match e {
Expr::Column(n) if c.in_upsert && n.0.len() == 2 && n.0[0] == "excluded" => {
self.t.excluded_ref(&self.id(&n.0[1]))
}
Expr::Column(n)
if c.in_upsert
&& n.0.len() == 1
&& matches!(c.source, "mysql" | "mariadb")
&& c.upsert_table.is_some() =>
{
format!(
"{}.{}",
c.upsert_table.as_deref().unwrap_or(""),
self.id(&n.0[0])
)
}
Expr::Column(n) => self.name(n),
Expr::Literal(l) => match l {
Literal::Null => "NULL".to_string(),
Literal::Bool(b) => self.t.bool_literal(*b, c)?,
Literal::Number(n) => n.clone(),
Literal::String(s) => self.t.string_literal(s),
Literal::Bytes(b) => self.t.bytes_literal(b),
},
Expr::Param(n) => {
c.max_param = c.max_param.max(*n);
c.param_order.push(*n);
c.scalar_params.insert(*n);
self.t.placeholder(*n)
}
Expr::AnyParam {
expr,
param,
negated,
} => {
let lhs = self.operand(expr, c)?;
c.max_param = c.max_param.max(*param);
c.param_order.push(*param);
let ph = self.t.placeholder(*param);
self.t.array_membership(&lhs, &ph, *negated, *param, c)?
}
Expr::Nested(inner) => self.expr(inner, c)?,
Expr::Unary { op, expr } => {
let o = self.operand(expr, c)?;
match op {
UnaryOp::Not => format!("NOT {o}"),
UnaryOp::Minus => format!("-{o}"),
UnaryOp::Plus => format!("+{o}"),
}
}
Expr::Binary {
op: op @ (BinaryOp::JsonGet | BinaryOp::JsonGetText),
left,
right,
} => {
let l = self.operand(left, c)?;
let r = self.operand(right, c)?;
self.t
.json_access(*op == BinaryOp::JsonGetText, &l, &r, c)?
}
Expr::Binary {
op: op @ (BinaryOp::Plus | BinaryOp::Minus),
left,
right,
} if matches!(&**right, Expr::Function(f) if f.name == "make_interval") => {
let Expr::Function(f) = &**right else {
unreachable!()
};
let mut parts = Vec::new();
for a in &f.args {
match a {
FunctionArg::Named { name, value } => {
parts.push((name.clone(), self.expr(value, c)?))
}
FunctionArg::Expr(_) => {
return Err(c.refuse(
"fn:make_interval",
"positional make_interval arguments are not in the IR; use named notation",
&[],
));
}
}
}
let l = self.operand(left, c)?;
let minus = *op == BinaryOp::Minus;
match self.t.interval_arith(minus, &l, &parts, c)? {
Some(text) => text,
None => {
c.interval_notation = true;
let r = self.expr(right, c);
c.interval_notation = false;
let r = r?;
format!("{l} {} {r}", if minus { "-" } else { "+" })
}
}
}
Expr::Binary {
op: BinaryOp::NullSafeEq,
left,
right,
} => {
let l = self.operand(left, c)?;
let r = self.operand(right, c)?;
let text = self.t.null_safe_eq(&l, &r, c)?;
format!("({text})")
}
Expr::Binary { op, left, right } => {
let sym = match op {
BinaryOp::Eq => "=",
BinaryOp::NotEq => "<>",
BinaryOp::Lt => "<",
BinaryOp::LtEq => "<=",
BinaryOp::Gt => ">",
BinaryOp::GtEq => ">=",
BinaryOp::And => "AND",
BinaryOp::Or => "OR",
BinaryOp::Plus => "+",
BinaryOp::Minus => "-",
BinaryOp::Multiply => "*",
BinaryOp::Divide => "/",
BinaryOp::Modulo => "%",
BinaryOp::Concat => "||",
BinaryOp::IntDivide => "/",
BinaryOp::BitAnd => "&",
BinaryOp::BitOr => "|",
BinaryOp::BitXor => "#",
BinaryOp::ShiftLeft => "<<",
BinaryOp::ShiftRight => ">>",
BinaryOp::Xor => "<>",
BinaryOp::JsonGet | BinaryOp::JsonGetText => unreachable!("handled above"),
BinaryOp::NullSafeEq => unreachable!("handled above"),
};
let numeric = is_numeric(left)
|| is_numeric(right)
|| c.scopes.is_non_text_column(left)
|| c.scopes.is_non_text_column(right);
if !numeric
&& matches!(
op,
BinaryOp::Eq
| BinaryOp::NotEq
| BinaryOp::Lt
| BinaryOp::LtEq
| BinaryOp::Gt
| BinaryOp::GtEq
)
{
self.collation_note("text_comparison", &[left, right], c)?;
}
self.t.binary_op(*op, numeric, c)?;
let (l, r) = (self.operand(left, c)?, self.operand(right, c)?);
match self.t.binary_override(*op, &l, &r, numeric, c)? {
Some(text) => text,
None => format!("{l} {sym} {r}"),
}
}
Expr::IsNull { expr, negated } => {
format!(
"{} IS {}NULL",
self.operand(expr, c)?,
if *negated { "NOT " } else { "" }
)
}
Expr::IsBool {
expr,
value,
negated,
} => {
format!(
"{} IS {}{}",
self.operand(expr, c)?,
if *negated { "NOT " } else { "" },
if *value { "TRUE" } else { "FALSE" }
)
}
Expr::InList {
expr,
list,
negated,
} => {
let l = list
.iter()
.map(|x| self.expr(x, c))
.collect::<R<Vec<_>>>()?;
format!(
"{} {}IN ({})",
self.operand(expr, c)?,
if *negated { "NOT " } else { "" },
l.join(", ")
)
}
Expr::InSubquery {
expr,
query,
negated,
} => format!(
"{} {}IN ({})",
self.operand(expr, c)?,
if *negated { "NOT " } else { "" },
self.query(query, c)?
),
Expr::Between {
expr,
low,
high,
negated,
} => {
if !(is_numeric(low)
|| is_numeric(high)
|| is_numeric(expr)
|| c.scopes.is_non_text_column(low)
|| c.scopes.is_non_text_column(high)
|| c.scopes.is_non_text_column(expr))
{
self.collation_note("text_comparison", &[expr, low, high], c)?;
}
self.t.between(
is_numeric(low)
|| is_numeric(high)
|| is_numeric(expr)
|| c.scopes.is_non_text_column(low)
|| c.scopes.is_non_text_column(high)
|| c.scopes.is_non_text_column(expr),
c,
)?;
format!(
"{} {}BETWEEN {} AND {}",
self.operand(expr, c)?,
if *negated { "NOT " } else { "" },
self.operand(low, c)?,
self.operand(high, c)?
)
}
Expr::Like {
expr,
pattern,
negated,
case_insensitive,
escape,
} => {
let l = self.operand(expr, c)?;
let r = self.operand(pattern, c)?;
let esc_txt = match escape {
Some(e) if !is_backslash(e) => Some(self.expr(e, c)?),
_ => None,
};
let esc = match (escape, &esc_txt) {
(None, _) => Escape::None,
(Some(e), _) if is_backslash(e) => Escape::Default,
(Some(_), Some(t)) => Escape::Custom(t),
(Some(_), None) => Escape::None,
};
self.t.like(&l, &r, *negated, *case_insensitive, esc, c)?
}
Expr::Regexp {
expr,
pattern,
negated,
} => {
let l = self.operand(expr, c)?;
let r = self.operand(pattern, c)?;
self.t.regexp(&l, &r, *negated, c)?
}
Expr::Case {
operand,
branches,
else_,
} => {
let mut s = String::from("CASE");
if let Some(o) = operand {
s.push_str(&format!(" {}", self.operand(o, c)?));
}
for (w, t) in branches {
s.push_str(&format!(
" WHEN {} THEN {}",
self.expr(w, c)?,
self.expr(t, c)?
));
}
if let Some(e) = else_ {
s.push_str(&format!(" ELSE {}", self.expr(e, c)?));
}
s.push_str(" END");
s
}
Expr::Cast { expr, ty } => {
let inner = self.expr(expr, c)?;
self.t.cast(&inner, ty, c)?
}
Expr::Function(f) => {
let mut args = Vec::new();
for a in &f.args {
args.push(match a {
FunctionArg::Expr(e) => self.expr(e, c)?,
FunctionArg::Named { name, value } => {
if !c.interval_notation {
self.t.feature("named_arg", c)?;
}
format!("{} => {}", self.id(name), self.expr(value, c)?)
}
});
}
if !f.order_by.is_empty() {
c.agg_order = Some(self.order_items(&f.order_by, c)?);
}
let s = self.t.function(f, &args, c);
if c.agg_order.take().is_some() && s.is_ok() {
return Err(c.refuse(
&format!("fn:{}.order_by", f.name),
"this target cannot honour an ORDER BY inside this aggregate",
&["order in a subquery", "use string_agg, which is translated"],
));
}
let mut s = s?;
if !f.order_by.is_empty() {
c.note(format!("fn:{}.order_by", f.name), Tier::Exact, "", None)?;
}
if let Some(flt) = &f.filter {
self.t.feature("filter_clause", c)?;
s.push_str(&format!(" FILTER (WHERE {})", self.expr(flt, c)?));
}
if let Some(w) = &f.over {
self.t.feature("window_function", c)?;
s.push_str(&format!(" OVER ({})", self.window(w, c)?));
}
s
}
Expr::Trim { expr, side, chars } => {
let e = self.expr(expr, c)?;
let ch = chars.as_ref().map(|x| self.expr(x, c)).transpose()?;
self.t.trim(*side, &e, ch.as_deref(), c)?
}
Expr::Extract { field, expr } => {
if field == "epoch" && is_clock_call(expr) {
return self.t.epoch_of_clock(c);
}
if field == "epoch"
&& let Some((a, b)) = difference_operands(expr)
{
let (l, r) = (self.operand(a, c)?, self.operand(b, c)?);
if let Some(text) = self.t.epoch_of_difference(&l, &r, c)? {
return Ok(text);
}
}
let e = self.expr(expr, c)?;
self.t.extract(field, &e, is_difference(expr), c)?
}
Expr::ArrayLiteral(items) => {
let parts = items
.iter()
.map(|x| self.expr(x, c))
.collect::<R<Vec<_>>>()?;
self.t.array_literal(&parts, c)?
}
Expr::AtTimeZone { expr, zone } => {
self.t.at_time_zone(c)?;
format!(
"({} AT TIME ZONE {})",
self.expr(expr, c)?,
self.expr(zone, c)?
)
}
Expr::ArraySubquery(q) => {
self.t.array_subquery(c)?;
format!("ARRAY({})", self.query(q, c)?)
}
Expr::Subquery(q) => format!("({})", self.query(q, c)?),
Expr::Exists { query, negated } => format!(
"{}EXISTS ({})",
if *negated { "NOT " } else { "" },
self.query(query, c)?
),
})
}
}
pub(crate) fn is_numeric(e: &Expr) -> bool {
match e {
Expr::Literal(Literal::Number(_)) => true,
Expr::Nested(x) => is_numeric(x),
Expr::Unary {
op: UnaryOp::Minus | UnaryOp::Plus,
expr,
} => is_numeric(expr),
Expr::Binary {
op:
BinaryOp::Plus
| BinaryOp::Minus
| BinaryOp::Multiply
| BinaryOp::Divide
| BinaryOp::Modulo,
..
} => true,
Expr::Function(f) => matches!(
f.name.as_str(),
"count" | "sum" | "avg" | "length" | "char_length" | "abs"
),
Expr::Cast { ty, .. } => matches!(
ty,
SqlType::SmallInt
| SqlType::Integer
| SqlType::BigInt
| SqlType::Real
| SqlType::Double
| SqlType::Numeric { .. }
),
_ => false,
}
}
fn difference_operands(e: &Expr) -> Option<(&Expr, &Expr)> {
match e {
Expr::Nested(x) => difference_operands(x),
Expr::Binary {
op: BinaryOp::Minus,
left,
right,
} => Some((left, right)),
_ => None,
}
}
pub(crate) fn is_clock_call(e: &Expr) -> bool {
match e {
Expr::Nested(x) => is_clock_call(x),
Expr::Function(f) => {
f.name == "clock_timestamp"
&& f.args.is_empty()
&& !f.distinct
&& !f.star
&& f.filter.is_none()
&& f.over.is_none()
}
_ => false,
}
}
pub(crate) fn is_difference(e: &Expr) -> bool {
match e {
Expr::Nested(x) => is_difference(x),
Expr::Binary {
op: BinaryOp::Minus,
..
} => true,
_ => false,
}
}
fn is_backslash(e: &Expr) -> bool {
matches!(e, Expr::Literal(Literal::String(s)) if s == "\\")
}