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#[derive(Debug)]
27pub struct Folded {
28    /// One value per SELECT column.
29    pub columns: Vec<kevy_scalar::Scalar>,
30}
31
32/// Evaluate a table-free `SELECT expr[, expr…];` against the given
33/// clock (epoch microseconds). Refusals are [`SqlError`]s whose text
34/// names the construct — never a silent wrong answer.
35pub fn fold_select(sql: &str, now_micros: i64) -> Result<Folded, SqlError> {
36    let toks = lex(sql)?;
37    let mut p = Parser { t: &toks, i: 0, now: now_micros };
38    p.expect_kw("select")?;
39    let mut columns = Vec::new();
40    loop {
41        columns.push(p.expr()?);
42        if !p.eat_sym(',') {
43            break;
44        }
45    }
46    p.eat_sym(';');
47    let t = p.peek();
48    if !matches!(t.tok, Tok::Eof) {
49        return Err(SqlError::at(
50            t.line,
51            t.col,
52            match &t.tok {
53                Tok::Ident(w) if w == "from" => {
54                    "FROM is not foldable — a table query compiles through the plan face; \
55                     only table-free SELECT folds here"
56                        .to_string()
57                }
58                other => format!("unexpected {other:?} after the select list"),
59            },
60        ));
61    }
62    Ok(Folded { columns })
63}
64
65pub(crate) struct Parser<'a> {
66    pub(crate) t: &'a [Token],
67    pub(crate) i: usize,
68    pub(crate) now: i64,
69}
70
71impl<'a> Parser<'a> {
72    pub(crate) fn peek(&self) -> &'a Token {
73        &self.t[self.i.min(self.t.len() - 1)]
74    }
75
76    pub(crate) fn bump(&mut self) -> &'a Token {
77        let t = &self.t[self.i.min(self.t.len() - 1)];
78        self.i += 1;
79        t
80    }
81
82    pub(crate) fn eat_sym(&mut self, c: char) -> bool {
83        if matches!(self.peek().tok, Tok::Sym(s) if s == c) {
84            self.i += 1;
85            return true;
86        }
87        false
88    }
89
90    pub(crate) fn eat_kw(&mut self, kw: &str) -> bool {
91        if matches!(&self.peek().tok, Tok::Ident(w) if w == kw) {
92            self.i += 1;
93            return true;
94        }
95        false
96    }
97
98    pub(crate) fn expect_kw(&mut self, kw: &str) -> Result<(), SqlError> {
99        let t = self.peek();
100        if self.eat_kw(kw) {
101            return Ok(());
102        }
103        Err(SqlError::at(t.line, t.col, format!("expected {}", kw.to_uppercase())))
104    }
105
106    pub(crate) fn expect_sym(&mut self, c: char) -> Result<(), SqlError> {
107        let t = self.peek();
108        if self.eat_sym(c) {
109            return Ok(());
110        }
111        Err(SqlError::at(t.line, t.col, format!("expected '{c}'")))
112    }
113
114    /// `expr := and_expr (OR and_expr)*` — the top of the operator
115    /// pyramid (PG precedence: OR < AND < NOT < comparison < `+ -` <
116    /// `* /`), three-valued logic in kevy-scalar.
117    pub(crate) fn expr(&mut self) -> Result<Scalar, SqlError> {
118        let mut acc = self.and_expr()?;
119        while self.eat_kw("or") {
120            let rhs = self.and_expr()?;
121            acc =
122                kevy_scalar::logic_or(&acc, &rhs).map_err(|e| SqlError::at(0, 0, e.to_string()))?;
123        }
124        Ok(acc)
125    }
126
127    fn and_expr(&mut self) -> Result<Scalar, SqlError> {
128        let mut acc = self.not_expr()?;
129        while self.eat_kw("and") {
130            let rhs = self.not_expr()?;
131            acc = kevy_scalar::logic_and(&acc, &rhs)
132                .map_err(|e| SqlError::at(0, 0, e.to_string()))?;
133        }
134        Ok(acc)
135    }
136
137    fn not_expr(&mut self) -> Result<Scalar, SqlError> {
138        if self.eat_kw("not") {
139            let v = self.not_expr()?;
140            return kevy_scalar::logic_not(&v).map_err(|e| SqlError::at(0, 0, e.to_string()));
141        }
142        self.cmp_expr()
143    }
144
145    /// One optional comparison: `add (op add)?` — SQL comparisons do
146    /// not chain (`a < b < c` is a type error in PG too). The lexer
147    /// already folds the two-character forms into single Op tokens.
148    fn cmp_expr(&mut self) -> Result<Scalar, SqlError> {
149        let lhs = self.add_expr()?;
150        let t = self.peek();
151        let (line, col) = (t.line, t.col);
152        let op: &str = match t.tok {
153            Tok::Op(o @ ("=" | "<" | ">" | "<=" | ">=" | "<>" | "!=")) => o,
154            _ => return Ok(lhs),
155        };
156        self.i += 1;
157        let rhs = self.add_expr()?;
158        kevy_scalar::cmp_op(op, &lhs, &rhs).map_err(|e| SqlError::at(line, col, e.to_string()))
159    }
160
161    /// `add_expr := concat (('+'|'-') concat)*` — evaluated left to
162    /// right; `||` binds tighter (PG precedence), `* /` one level below.
163    fn add_expr(&mut self) -> Result<Scalar, SqlError> {
164        let mut acc = self.concat_expr()?;
165        loop {
166            let t = self.peek();
167            let op = match t.tok {
168                Tok::Sym(c @ ('+' | '-')) => c,
169                _ => return Ok(acc),
170            };
171            let (line, col) = (t.line, t.col);
172            self.i += 1;
173            let rhs = self.concat_expr()?;
174            acc = kevy_scalar::binop(op, &acc, &rhs)
175                .map_err(|e| SqlError::at(line, col, e.to_string()))?;
176        }
177    }
178
179    /// `concat := term ('||' term)*` — SQL string concatenation with
180    /// strict NULL propagation ('a' || NULL is NULL, unlike concat()).
181    fn concat_expr(&mut self) -> Result<Scalar, SqlError> {
182        let mut acc = self.term()?;
183        while matches!(self.peek().tok, Tok::Op("||")) {
184            self.i += 1;
185            let rhs = self.term()?;
186            acc = match (&acc, &rhs) {
187                (Scalar::Null, _) | (_, Scalar::Null) => Scalar::Null,
188                (a, b) => Scalar::Text(format!("{}{}", a.render(), b.render())),
189            };
190        }
191        Ok(acc)
192    }
193
194    fn term(&mut self) -> Result<Scalar, SqlError> {
195        let mut acc = fold_parse::primary(self)?;
196        loop {
197            let t = self.peek();
198            let op = match t.tok {
199                Tok::Sym(c @ ('*' | '/')) => c,
200                _ => return Ok(acc),
201            };
202            let (line, col) = (t.line, t.col);
203            self.i += 1;
204            let rhs = fold_parse::primary(self)?;
205            acc = kevy_scalar::binop(op, &acc, &rhs)
206                .map_err(|e| SqlError::at(line, col, e.to_string()))?;
207        }
208    }
209}