fv-streams-sql 0.3.0

The SQL front door for FusionVault Streams: a streaming SQL statement parses to a small typed logical plan and lowers to the same topology the TOML frontend produces — one runtime, two front doors. No DataFusion planner, no fork; expressions compile through the value dialect as the steps already do.
Documentation
//! SQL scalar expression → **value-dialect string** (the string an `applyExpression`/`filter` step
//! carries, compiled through `fv-value-datafusion` exactly as the TOML frontend's expressions are).
//!
//! This is an *unparser*, not an evaluator: it re-renders the SQL AST in the value dialect's syntax
//! (`==`/`!=`/`&&`/`||`, single-quoted strings, `?:` for CASE). It does not depend on `fv-value`; the
//! only contract is that the emitted string is one the dialect accepts — which the SQL≡TOML anti-drift
//! gate (5c-iv) proves. Anything the dialect cannot express is rejected LOUDLY here.

use sqlparser::ast::{BinaryOperator, CaseWhen, Expr, UnaryOperator, Value};

/// Render `e` as a value-dialect expression string.
pub fn to_dialect(e: &Expr) -> Result<String, String> {
    match e {
        Expr::Identifier(id) => Ok(id.value.clone()),
        // a.b (table-qualified) reduces to the column — single-table queries in 5c-i.
        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::IsNotNull(inner) => Ok(format!("({} != null)", to_dialect(inner)?)),
        // sqlparser parses `SUBSTRING(x, from, for)` as a dedicated node, not a function call.
        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}`")),
    }
}

/// SQL binary operator → the value dialect's spelling.
fn binary_op(op: &BinaryOperator) -> Result<&'static str, String> {
    Ok(match op {
        BinaryOperator::Plus => "+",
        BinaryOperator::Minus => "-",
        BinaryOperator::Multiply => "*",
        BinaryOperator::Divide => "/",
        BinaryOperator::Modulo => "%",
        BinaryOperator::StringConcat => "+", // SQL `||` concat → the dialect's `+`
        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};
    // preserve the written case — the value dialect's functions are camelCase (`epochToIso`,
    // `splitPart`, `regexExtract`), case-sensitive; the user writes the dialect name.
    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,
            // count(*) — the dialect counts rows with `count` and no column.
            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(", ")))
}

/// `CASE [op] WHEN c THEN r … ELSE e END` → nested dialect ternary `(c ? r : (… : e))`.
fn case_to_ternary(operand: Option<&Expr>, whens: &[CaseWhen], else_result: Option<&Expr>) -> Result<String, String> {
    // build right-to-left so the first WHEN is outermost.
    let mut acc = match else_result {
        Some(e) => to_dialect(e)?,
        None => "null".into(),
    };
    for w in whens.iter().rev() {
        let test = match operand {
            // `CASE x WHEN v` → `x == v`
            Some(op) => format!("({} == {})", to_dialect(op)?, to_dialect(&w.condition)?),
            // `CASE WHEN cond` → `cond`
            None => to_dialect(&w.condition)?,
        };
        acc = format!("({test} ? {} : {acc})", to_dialect(&w.result)?);
    }
    Ok(acc)
}