Skip to main content

kevy_sql/
fold.rs

1//! `fold` — evaluate a table-free `SELECT` to literal rows.
2//!
3//! The V1 scalar-function face: `SELECT f(args…)`
4//! with no FROM clause is a pure expression, and the whole probe
5//! corpus' scalar block has exactly that shape. Evaluation delegates
6//! to kevy-scalar; this module owns only the SYNTAX — function-call
7//! grammar, literals, `::` casts, `INTERVAL` literals, the
8//! `extract(field FROM x)` / `position(a IN b)` special forms, and
9//! `+ - * /`.
10//!
11//! The clock never reaches kevy-scalar: `now()` / `current_timestamp`
12//! / `current_date` are rewritten HERE to the literal the caller
13//! supplies (the probe-08 precedent — spg pins its test clock the
14//! same way). A statement with FROM/WHERE/anything wider is a named
15//! refusal, not an error of this module's business: the caller routes
16//! those to the plan face.
17
18use crate::lex::{Tok, Token, lex};
19use crate::{SqlError, fold_parse};
20use kevy_scalar::Scalar;
21
22/// One folded statement: the column values of the single result row.
23/// Typed, not pre-rendered — the CLI prints PG text forms while the
24/// probe runner follows sqllogictest's conventions (booleans as 1/0),
25/// and neither should pay for the other's rendering.
26///
27/// ```
28/// let f = kevy_sql::fold_select("SELECT lower('AB');", 0)?;
29/// assert_eq!(f.columns, [kevy_sql::Scalar::Text("ab".into())]);
30/// # Ok::<(), kevy_sql::SqlError>(())
31/// ```
32#[derive(Debug, Clone, PartialEq)]
33#[non_exhaustive]
34pub struct Folded {
35    /// One value per SELECT column.
36    ///
37    /// ```
38    /// let f = kevy_sql::fold_select("SELECT 1 + 2, upper('a');", 0)?;
39    /// assert_eq!(f.columns, [kevy_sql::Scalar::Int(3), kevy_sql::Scalar::Text("A".into())]);
40    /// # Ok::<(), kevy_sql::SqlError>(())
41    /// ```
42    pub columns: Vec<kevy_scalar::Scalar>,
43}
44
45/// Evaluate a table-free `SELECT expr[, expr…];` against the given
46/// clock (epoch microseconds). Refusals are [`SqlError`]s whose text
47/// names the construct — never a silent wrong answer.
48///
49/// ```
50/// let f = kevy_sql::fold_select("SELECT length('kevy') * 2;", 0)?;
51/// assert_eq!(f.columns, [kevy_sql::Scalar::Int(8)]);
52///
53/// // a table query is refused by name rather than folded
54/// let e = kevy_sql::fold_select("SELECT 1 FROM t;", 0).unwrap_err();
55/// assert!(e.message.starts_with("FROM is not foldable"));
56/// # Ok::<(), kevy_sql::SqlError>(())
57/// ```
58pub fn fold_select(sql: &str, now_micros: i64) -> Result<Folded, SqlError> {
59    let toks = lex(sql)?;
60    let mut p = Parser { t: &toks, i: 0, now: now_micros };
61    p.expect_kw("select")?;
62    let mut columns = Vec::new();
63    loop {
64        columns.push(p.expr()?);
65        if !p.eat_sym(',') {
66            break;
67        }
68    }
69    p.eat_sym(';');
70    let t = p.peek();
71    if !matches!(t.tok, Tok::Eof) {
72        return Err(SqlError::at(
73            t.line,
74            t.col,
75            match &t.tok {
76                Tok::Ident(w) if w == "from" => {
77                    "FROM is not foldable — a table query compiles through the plan face; \
78                     only table-free SELECT folds here"
79                        .to_string()
80                }
81                other => format!("unexpected {other:?} after the select list"),
82            },
83        ));
84    }
85    Ok(Folded { columns })
86}
87
88pub(crate) struct Parser<'a> {
89    pub(crate) t: &'a [Token],
90    pub(crate) i: usize,
91    pub(crate) now: i64,
92}
93
94impl<'a> Parser<'a> {
95    pub(crate) fn peek(&self) -> &'a Token {
96        &self.t[self.i.min(self.t.len() - 1)]
97    }
98
99    pub(crate) fn bump(&mut self) -> &'a Token {
100        let t = &self.t[self.i.min(self.t.len() - 1)];
101        self.i += 1;
102        t
103    }
104
105    pub(crate) fn eat_sym(&mut self, c: char) -> bool {
106        if matches!(self.peek().tok, Tok::Sym(s) if s == c) {
107            self.i += 1;
108            return true;
109        }
110        false
111    }
112
113    pub(crate) fn eat_kw(&mut self, kw: &str) -> bool {
114        if matches!(&self.peek().tok, Tok::Ident(w) if w == kw) {
115            self.i += 1;
116            return true;
117        }
118        false
119    }
120
121    pub(crate) fn expect_kw(&mut self, kw: &str) -> Result<(), SqlError> {
122        let t = self.peek();
123        if self.eat_kw(kw) {
124            return Ok(());
125        }
126        Err(SqlError::at(t.line, t.col, format!("expected {}", kw.to_uppercase())))
127    }
128
129    pub(crate) fn expect_sym(&mut self, c: char) -> Result<(), SqlError> {
130        let t = self.peek();
131        if self.eat_sym(c) {
132            return Ok(());
133        }
134        Err(SqlError::at(t.line, t.col, format!("expected '{c}'")))
135    }
136
137    /// `expr := and_expr (OR and_expr)*` — the top of the operator
138    /// pyramid (PG precedence: OR < AND < NOT < comparison < `+ -` <
139    /// `* /`), three-valued logic in kevy-scalar.
140    pub(crate) fn expr(&mut self) -> Result<Scalar, SqlError> {
141        let mut acc = self.and_expr()?;
142        while self.eat_kw("or") {
143            let rhs = self.and_expr()?;
144            acc =
145                kevy_scalar::logic_or(&acc, &rhs).map_err(|e| SqlError::at(0, 0, e.to_string()))?;
146        }
147        Ok(acc)
148    }
149
150    fn and_expr(&mut self) -> Result<Scalar, SqlError> {
151        let mut acc = self.not_expr()?;
152        while self.eat_kw("and") {
153            let rhs = self.not_expr()?;
154            acc = kevy_scalar::logic_and(&acc, &rhs)
155                .map_err(|e| SqlError::at(0, 0, e.to_string()))?;
156        }
157        Ok(acc)
158    }
159
160    fn not_expr(&mut self) -> Result<Scalar, SqlError> {
161        if self.eat_kw("not") {
162            let v = self.not_expr()?;
163            return kevy_scalar::logic_not(&v).map_err(|e| SqlError::at(0, 0, e.to_string()));
164        }
165        self.cmp_expr()
166    }
167
168    /// One optional comparison: `add (op add)?` — SQL comparisons do
169    /// not chain (`a < b < c` is a type error in PG too). The lexer
170    /// already folds the two-character forms into single Op tokens.
171    fn cmp_expr(&mut self) -> Result<Scalar, SqlError> {
172        let lhs = self.add_expr()?;
173        let t = self.peek();
174        let (line, col) = (t.line, t.col);
175        let op: &str = match t.tok {
176            Tok::Op(o @ ("=" | "<" | ">" | "<=" | ">=" | "<>" | "!=")) => o,
177            _ => return Ok(lhs),
178        };
179        self.i += 1;
180        let rhs = self.add_expr()?;
181        kevy_scalar::cmp_op(op, &lhs, &rhs).map_err(|e| SqlError::at(line, col, e.to_string()))
182    }
183
184    /// `add_expr := concat (('+'|'-') concat)*` — evaluated left to
185    /// right; `||` binds tighter (PG precedence), `* /` one level below.
186    fn add_expr(&mut self) -> Result<Scalar, SqlError> {
187        let mut acc = self.concat_expr()?;
188        loop {
189            let t = self.peek();
190            let op = match t.tok {
191                Tok::Sym(c @ ('+' | '-')) => c,
192                _ => return Ok(acc),
193            };
194            let (line, col) = (t.line, t.col);
195            self.i += 1;
196            let rhs = self.concat_expr()?;
197            acc = kevy_scalar::binop(op, &acc, &rhs)
198                .map_err(|e| SqlError::at(line, col, e.to_string()))?;
199        }
200    }
201
202    /// `concat := term ('||' term)*` — SQL string concatenation with
203    /// strict NULL propagation ('a' || NULL is NULL, unlike concat()).
204    fn concat_expr(&mut self) -> Result<Scalar, SqlError> {
205        let mut acc = self.term()?;
206        while matches!(self.peek().tok, Tok::Op("||")) {
207            self.i += 1;
208            let rhs = self.term()?;
209            acc = match (&acc, &rhs) {
210                (Scalar::Null, _) | (_, Scalar::Null) => Scalar::Null,
211                (a, b) => Scalar::Text(format!("{}{}", a.render(), b.render())),
212            };
213        }
214        Ok(acc)
215    }
216
217    fn term(&mut self) -> Result<Scalar, SqlError> {
218        let mut acc = fold_parse::primary(self)?;
219        loop {
220            let t = self.peek();
221            let op = match t.tok {
222                Tok::Sym(c @ ('*' | '/')) => c,
223                _ => return Ok(acc),
224            };
225            let (line, col) = (t.line, t.col);
226            self.i += 1;
227            let rhs = fold_parse::primary(self)?;
228            acc = kevy_scalar::binop(op, &acc, &rhs)
229                .map_err(|e| SqlError::at(line, col, e.to_string()))?;
230        }
231    }
232}