use sqlparser::ast::{BinaryOperator, CaseWhen, Expr, UnaryOperator, Value};
pub fn to_dialect(e: &Expr) -> Result<String, String> {
match e {
Expr::Identifier(id) => Ok(id.value.clone()),
Expr::CompoundIdentifier(parts) => parts
.last()
.map(|p| p.value.clone())
.ok_or_else(|| "empty compound identifier".into()),
Expr::Value(v) => literal(&v.value),
Expr::Nested(inner) => Ok(format!("({})", to_dialect(inner)?)),
Expr::UnaryOp { op, expr } => {
let inner = to_dialect(expr)?;
match op {
UnaryOperator::Not => Ok(format!("!({inner})")),
UnaryOperator::Minus => Ok(format!("(-{inner})")),
UnaryOperator::Plus => Ok(inner),
other => Err(format!("unsupported unary operator `{other}`")),
}
}
Expr::BinaryOp { left, op, right } => {
let l = to_dialect(left)?;
let r = to_dialect(right)?;
let o = binary_op(op)?;
Ok(format!("({l} {o} {r})"))
}
Expr::Function(f) => function(f),
Expr::Case {
operand,
conditions,
else_result,
..
} => case_to_ternary(operand.as_deref(), conditions, else_result.as_deref()),
Expr::IsNull(inner) => Ok(format!("({} == null)", to_dialect(inner)?)),
Expr::InList { expr, list, negated } => {
let items = list.iter().map(to_dialect).collect::<Result<Vec<_>, _>>()?.join(", ");
let e = format!("({} in [{items}])", to_dialect(expr)?);
Ok(if *negated { format!("!{e}") } else { e })
}
Expr::Between { expr, negated, low, high } => {
let x = to_dialect(expr)?;
let e = format!("(({x} >= {}) && ({x} <= {}))", to_dialect(low)?, to_dialect(high)?);
Ok(if *negated { format!("!{e}") } else { e })
}
Expr::Like { negated, expr, pattern, .. } => like(expr, pattern, *negated, false),
Expr::ILike { negated, expr, pattern, .. } => like(expr, pattern, *negated, true),
Expr::IsNotNull(inner) => Ok(format!("({} != null)", to_dialect(inner)?)),
Expr::Substring { expr, substring_from, substring_for, .. } => {
let s = to_dialect(expr)?;
match (substring_from, substring_for) {
(Some(from), Some(len)) => {
Ok(format!("substring({s}, {}, {})", to_dialect(from)?, to_dialect(len)?))
}
(Some(from), None) => Ok(format!("substring({s}, {})", to_dialect(from)?)),
_ => Err("SUBSTRING needs a start position (`SUBSTRING(x, start, length)`)".into()),
}
}
other => Err(format!(
"unsupported expression `{other}` — supported: columns, literals, arithmetic/comparison/boolean operators, function calls, CASE, IS [NOT] NULL"
)),
}
}
fn literal(v: &Value) -> Result<String, String> {
match v {
Value::Number(n, _) => Ok(n.clone()),
Value::SingleQuotedString(s) | Value::DoubleQuotedString(s) => Ok(format!("'{}'", s.replace('\'', "\\'"))),
Value::Boolean(b) => Ok(b.to_string()),
Value::Null => Ok("null".into()),
other => Err(format!("unsupported literal `{other}`")),
}
}
fn binary_op(op: &BinaryOperator) -> Result<&'static str, String> {
Ok(match op {
BinaryOperator::Plus => "+",
BinaryOperator::Minus => "-",
BinaryOperator::Multiply => "*",
BinaryOperator::Divide => "/",
BinaryOperator::Modulo => "%",
BinaryOperator::StringConcat => "+", BinaryOperator::Eq => "==",
BinaryOperator::NotEq => "!=",
BinaryOperator::Lt => "<",
BinaryOperator::LtEq => "<=",
BinaryOperator::Gt => ">",
BinaryOperator::GtEq => ">=",
BinaryOperator::And => "&&",
BinaryOperator::Or => "||",
other => return Err(format!("unsupported binary operator `{other}`")),
})
}
fn function(f: &sqlparser::ast::Function) -> Result<String, String> {
use sqlparser::ast::{FunctionArg, FunctionArgExpr, FunctionArguments};
let name = f.name.to_string();
let args = match &f.args {
FunctionArguments::List(list) => &list.args,
FunctionArguments::None => {
return Ok(format!("{name}()"));
}
FunctionArguments::Subquery(_) => {
return Err(format!("function `{name}` with a subquery argument is not supported"))
}
};
let mut rendered = Vec::with_capacity(args.len());
for a in args {
let e = match a {
FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => e,
FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => {
rendered.push(String::new());
continue;
}
_ => return Err(format!("unsupported argument to `{name}` (named / wildcard args)")),
};
rendered.push(to_dialect(e)?);
}
Ok(format!("{name}({})", rendered.join(", ")))
}
fn case_to_ternary(operand: Option<&Expr>, whens: &[CaseWhen], else_result: Option<&Expr>) -> Result<String, String> {
let mut acc = match else_result {
Some(e) => to_dialect(e)?,
None => "null".into(),
};
for w in whens.iter().rev() {
let test = match operand {
Some(op) => format!("({} == {})", to_dialect(op)?, to_dialect(&w.condition)?),
None => to_dialect(&w.condition)?,
};
acc = format!("({test} ? {} : {acc})", to_dialect(&w.result)?);
}
Ok(acc)
}
fn like(expr: &Expr, pattern: &Expr, negated: bool, ci: bool) -> Result<String, String> {
let pat = match pattern {
Expr::Value(v) => match &v.value {
Value::SingleQuotedString(s) => s.clone(),
other => return Err(format!("LIKE needs a string-literal pattern, got `{other}`")),
},
other => return Err(format!("LIKE needs a string-literal pattern, got `{other}`")),
};
let mut re = String::with_capacity(pat.len() + 8);
re.push('^');
if ci {
re.insert_str(0, "(?i)");
}
for c in pat.chars() {
match c {
'%' => re.push_str(".*"),
'_' => re.push('.'),
c if "\\.+*?()[]{}|^$".contains(c) => {
re.push('\\');
re.push(c);
}
c => re.push(c),
}
}
re.push('$');
let e = format!("regexMatch({}, '{}')", to_dialect(expr)?, re.replace('\'', "\\'"));
Ok(if negated { format!("!{e}") } else { e })
}