Skip to main content

kevy_scalar/
lib.rs

1//! kevy-scalar — PG-canonical scalar function evaluation.
2//!
3//! The function library behind kevy's sql face (the V1 scalar
4//! surface): `SELECT lower('X')`-shaped constant folding and the
5//! query-card projection epilogue both call [`eval`]. Nothing here
6//! ever runs inside a serving engine process — evaluation stays in
7//! the sql face by design (Law 3), which is why this crate knows
8//! nothing about kevy: it maps a function name and [`Scalar`]
9//! arguments to a [`Scalar`] result, PG 18 semantics, and that is the
10//! whole contract.
11//!
12//! Semantics ground truth: the pg_regress-derived probe corpus
13//! (`bench/funcgate-corpus/`). The tests in this crate are transcribed
14//! from those files — where PG is surprising (floor toward −infinity,
15//! `trim` strips a character SET not a substring, NULL propagates
16//! through almost everything), the probe line is cited.
17//!
18//! ```
19//! use kevy_scalar::{eval, Scalar};
20//! let out = eval("lower", &[Scalar::Text("HeLLo".into())])?;
21//! assert_eq!(out, Scalar::Text("hello".into()));
22//! # Ok::<(), kevy_scalar::ScalarError>(())
23//! ```
24
25#![forbid(unsafe_code)]
26#![warn(missing_docs)]
27
28mod datetime;
29mod datetime_fmt;
30mod logic;
31mod math;
32mod md5;
33mod nullfam;
34mod ops;
35mod regex_engine;
36mod regexp;
37mod strings;
38mod strings_slice;
39#[cfg(test)]
40mod tests;
41
42pub use logic::{cmp_op, logic_and, logic_not, logic_or, parse_pg_bool};
43pub use ops::binop;
44
45pub use datetime_fmt::{
46    parse_date, parse_interval, parse_timestamp, render_date, render_interval, render_timestamp,
47};
48
49// Send and Sync are part of the public contract: a change that loses
50// either fails to compile here rather than in a caller.
51const _: () = {
52    const fn send_sync<T: Send + Sync>() {}
53    send_sync::<Scalar>();
54    send_sync::<ScalarError>();
55};
56
57/// A typed scalar value — the closed set the function library speaks.
58///
59/// Deliberately narrower than SQL's type zoo: kevy's sql face maps
60/// bigint/int → `Int`, double/numeric-literal → `Float`, text/varchar
61/// → `Text`, boolean → `Bool`, and SQL `NULL` → `Null`. Types the
62/// engine refuses (money, inet, enum, …) never reach this crate.
63#[derive(Debug, Clone, PartialEq)]
64#[non_exhaustive]
65/// # Examples
66///
67/// ```
68/// use kevy_scalar::{Scalar, eval};
69/// // NULL is a value here, not an absence, and it PROPAGATES: a strict
70/// // function with a NULL argument answers NULL rather than erroring.
71/// assert_eq!(eval("upper", &[Scalar::Null]).unwrap(), Scalar::Null);
72/// assert_eq!(
73///     eval("upper", &[Scalar::Text("ada".into())]).unwrap(),
74///     Scalar::Text("ADA".into())
75/// );
76/// ```
77pub enum Scalar {
78    /// SQL NULL. Propagates: any strict function with a NULL argument
79    /// answers NULL (the null-family module documents its exceptions).
80    ///
81    /// ```
82    /// use kevy_scalar::{Scalar, eval};
83    /// assert_eq!(eval("lower", &[Scalar::Null])?, Scalar::Null);
84    /// assert_eq!(eval("coalesce", &[Scalar::Null, Scalar::Int(1)])?, Scalar::Int(1));
85    /// # Ok::<(), kevy_scalar::ScalarError>(())
86    /// ```
87    Null,
88    /// A 64-bit integer.
89    ///
90    /// ```
91    /// use kevy_scalar::{Scalar, eval};
92    /// assert_eq!(eval("length", &[Scalar::Text("kevy".into())])?, Scalar::Int(4));
93    /// assert_eq!(Scalar::Int(-7).render(), "-7");
94    /// # Ok::<(), kevy_scalar::ScalarError>(())
95    /// ```
96    Int(i64),
97    /// A 64-bit float. PG's numeric literals fold through here; the
98    /// sql face renders results back with PG's trailing-zero rules.
99    ///
100    /// ```
101    /// use kevy_scalar::{Scalar, binop};
102    /// let half = binop('/', &Scalar::Float(1.0), &Scalar::Int(2))?;
103    /// assert_eq!(half, Scalar::Float(0.5));
104    /// assert_eq!(half.render(), "0.5");
105    /// # Ok::<(), kevy_scalar::ScalarError>(())
106    /// ```
107    Float(f64),
108    /// A UTF-8 string.
109    ///
110    /// ```
111    /// use kevy_scalar::{Scalar, eval};
112    /// let out = eval("initcap", &[Scalar::Text("hello world".into())])?;
113    /// assert_eq!(out, Scalar::Text("Hello World".into()));
114    /// # Ok::<(), kevy_scalar::ScalarError>(())
115    /// ```
116    Text(String),
117    /// A boolean.
118    ///
119    /// ```
120    /// use kevy_scalar::{Scalar, logic_not};
121    /// assert_eq!(logic_not(&Scalar::Bool(true))?, Scalar::Bool(false));
122    /// assert_eq!(Scalar::Bool(false).render(), "f");
123    /// # Ok::<(), kevy_scalar::ScalarError>(())
124    /// ```
125    Bool(bool),
126    /// A timestamp (no time zone): microseconds since the Unix epoch.
127    /// Probe 38's lesson is baked in: `now()` and friends must be
128    /// TYPED, not text — the sql face rewrites them to this variant.
129    ///
130    /// ```
131    /// use kevy_scalar::{Scalar, parse_timestamp};
132    /// let us = parse_timestamp("1970-01-02 00:00:00").unwrap();
133    /// assert_eq!(us, 86_400_000_000);
134    /// assert_eq!(Scalar::Timestamp(us).render(), "1970-01-02 00:00:00");
135    /// ```
136    Timestamp(i64),
137    /// A calendar date: days since the Unix epoch.
138    ///
139    /// ```
140    /// use kevy_scalar::{Scalar, binop, parse_date};
141    /// let d = Scalar::Date(parse_date("2024-02-28").unwrap());
142    /// let next = binop('+', &d, &Scalar::Int(1))?;
143    /// assert_eq!(next.render(), "2024-02-29");
144    /// # Ok::<(), kevy_scalar::ScalarError>(())
145    /// ```
146    Date(i64),
147    /// An interval in PG's three-component shape: months, days and
148    /// microseconds never mix (probe 10's `1 day - 12 hours` stays
149    /// `1 day -12:00:00` — no normalization across components). Month
150    /// arithmetic clamps to month ends; the other two are exact.
151    ///
152    /// ```
153    /// use kevy_scalar::{Scalar, binop, parse_date};
154    /// let jan31 = Scalar::Date(parse_date("2024-01-31").unwrap());
155    /// let month = Scalar::Interval { months: 1, days: 0, micros: 0 };
156    /// // clamped to the last day of February
157    /// assert_eq!(binop('+', &jan31, &month)?.render(), "2024-02-29 00:00:00");
158    /// # Ok::<(), kevy_scalar::ScalarError>(())
159    /// ```
160    Interval {
161        /// Whole calendar months (12 per year).
162        ///
163        /// ```
164        /// use kevy_scalar::{Scalar, parse_interval};
165        /// let (months, _, _) = parse_interval("1 year 2 mons").unwrap();
166        /// assert_eq!(months, 14);
167        /// let iv = Scalar::Interval { months, days: 0, micros: 0 };
168        /// assert_eq!(iv.render(), "1 year 2 mons");
169        /// ```
170        months: i64,
171        /// Whole days — separate from micros because PG keeps them
172        /// separate (visible in rendering and component extraction).
173        ///
174        /// ```
175        /// use kevy_scalar::Scalar;
176        /// // 1 day minus 12 hours stays as two components
177        /// let iv = Scalar::Interval { months: 0, days: 1, micros: -43_200_000_000 };
178        /// assert_eq!(iv.render(), "1 day -12:00:00");
179        /// ```
180        days: i64,
181        /// Sub-day remainder in microseconds.
182        ///
183        /// ```
184        /// use kevy_scalar::Scalar;
185        /// let iv = Scalar::Interval { months: 0, days: 0, micros: 5_400_000_000 };
186        /// assert_eq!(iv.render(), "01:30:00");
187        /// ```
188        micros: i64,
189    },
190}
191
192impl Scalar {
193    /// Whether this is SQL NULL.
194    #[must_use]
195    /// # Examples
196    ///
197    /// ```
198    /// use kevy_scalar::Scalar;
199    /// assert!(Scalar::Null.is_null());
200    /// assert!(!Scalar::Int(0).is_null(), "zero is a value, not a NULL");
201    /// assert!(!Scalar::Text(String::new()).is_null(), "so is the empty string");
202    /// ```
203    pub fn is_null(&self) -> bool {
204        matches!(self, Scalar::Null)
205    }
206
207    /// PG's text output form for this value. `Null` renders as the
208    /// empty string here — a caller that needs a `NULL` marker (the
209    /// sqllogictest runner does) checks [`Scalar::is_null`] first.
210    #[must_use]
211    /// # Examples
212    ///
213    /// ```
214    /// use kevy_scalar::Scalar;
215    /// assert_eq!(Scalar::Int(42).render(), "42");
216    /// assert_eq!(Scalar::Text("ada".into()).render(), "ada");
217    /// assert_eq!(Scalar::Bool(true).render(), "t", "PG's boolean output");
218    /// ```
219    pub fn render(&self) -> String {
220        strings::to_text(self)
221    }
222}
223
224/// Why a call could not be evaluated.
225///
226/// `UnknownFunction` is the load-bearing variant: the sql face turns
227/// it into a *named refusal* (the funcgate contract says silent
228/// failure is itself a gate failure), so the message must carry the
229/// function name verbatim.
230#[derive(Debug, Clone, PartialEq, Eq, Hash)]
231#[non_exhaustive]
232/// # Examples
233///
234/// ```
235/// use kevy_scalar::{Scalar, ScalarError, eval};
236/// // A name this engine does not implement is refused BY NAME rather
237/// // than silently answering NULL.
238/// assert!(matches!(
239///     eval("no_such_fn", &[]),
240///     Err(ScalarError::UnknownFunction(_))
241/// ));
242/// // So is the wrong number of arguments.
243/// assert!(matches!(eval("md5", &[]), Err(ScalarError::Arity { .. })));
244/// ```
245pub enum ScalarError {
246    /// No function with this name in the library. Field = the name.
247    ///
248    /// ```
249    /// use kevy_scalar::{ScalarError, eval};
250    /// let err = eval("frobnicate", &[]).unwrap_err();
251    /// assert_eq!(err, ScalarError::UnknownFunction("frobnicate".into()));
252    /// assert_eq!(err.to_string(), "unknown function: frobnicate");
253    /// ```
254    UnknownFunction(String),
255    /// The function exists but not with this argument count.
256    ///
257    /// ```
258    /// use kevy_scalar::{Scalar, ScalarError, eval};
259    /// let two = [Scalar::Text("a".into()), Scalar::Text("b".into())];
260    /// assert_eq!(eval("md5", &two), Err(ScalarError::Arity { func: "md5", got: 2 }));
261    /// ```
262    Arity {
263        /// Function name.
264        ///
265        /// ```
266        /// use kevy_scalar::{ScalarError, eval};
267        /// let Err(ScalarError::Arity { func, .. }) = eval("MD5", &[]) else { panic!() };
268        /// assert_eq!(func, "md5");
269        /// ```
270        func: &'static str,
271        /// What the call supplied.
272        ///
273        /// ```
274        /// use kevy_scalar::{ScalarError, eval};
275        /// let Err(ScalarError::Arity { got, .. }) = eval("md5", &[]) else { panic!() };
276        /// assert_eq!(got, 0);
277        /// ```
278        got: usize,
279    },
280    /// An argument had a type the function cannot take (PG would have
281    /// refused the cast at parse time; the sql face reports this with
282    /// the same vocabulary).
283    ///
284    /// ```
285    /// use kevy_scalar::{Scalar, ScalarError, eval};
286    /// let err = eval("md5", &[Scalar::Int(1)]).unwrap_err();
287    /// assert_eq!(err, ScalarError::Type { func: "md5", arg: 0 });
288    /// assert_eq!(err.to_string(), "md5: argument 1 has an unsupported type");
289    /// ```
290    Type {
291        /// Function name.
292        ///
293        /// ```
294        /// use kevy_scalar::{Scalar, ScalarError, eval};
295        /// let Err(ScalarError::Type { func, .. }) = eval("md5", &[Scalar::Bool(true)]) else {
296        ///     panic!()
297        /// };
298        /// assert_eq!(func, "md5");
299        /// ```
300        func: &'static str,
301        /// 0-based argument position.
302        ///
303        /// ```
304        /// use kevy_scalar::{Scalar, ScalarError, eval};
305        /// let Err(ScalarError::Type { arg, .. }) = eval("md5", &[Scalar::Int(1)]) else {
306        ///     panic!()
307        /// };
308        /// assert_eq!(arg, 0, "the first argument");
309        /// ```
310        arg: usize,
311    },
312    /// Arithmetic that PG raises on: division by zero, sqrt of a
313    /// negative, integer overflow.
314    ///
315    /// ```
316    /// use kevy_scalar::{Scalar, ScalarError, binop};
317    /// let err = binop('/', &Scalar::Int(1), &Scalar::Int(0)).unwrap_err();
318    /// assert_eq!(err, ScalarError::Domain { func: "/", what: "division by zero" });
319    /// assert_eq!(err.to_string(), "/: division by zero");
320    /// ```
321    Domain {
322        /// Function name.
323        ///
324        /// ```
325        /// use kevy_scalar::{Scalar, ScalarError, binop};
326        /// let Err(ScalarError::Domain { func, .. }) = binop('/', &Scalar::Int(1), &Scalar::Int(0))
327        /// else {
328        ///     panic!()
329        /// };
330        /// assert_eq!(func, "/");
331        /// ```
332        func: &'static str,
333        /// PG's error phrase, e.g. `division by zero`.
334        ///
335        /// ```
336        /// use kevy_scalar::{Scalar, ScalarError, binop};
337        /// let Err(ScalarError::Domain { what, .. }) = binop('/', &Scalar::Int(1), &Scalar::Int(0))
338        /// else {
339        ///     panic!()
340        /// };
341        /// assert_eq!(what, "division by zero");
342        /// ```
343        what: &'static str,
344    },
345}
346
347impl std::fmt::Display for ScalarError {
348    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349        match self {
350            ScalarError::UnknownFunction(name) => {
351                write!(f, "unknown function: {name}")
352            }
353            ScalarError::Arity { func, got } => {
354                write!(f, "{func}: wrong argument count ({got})")
355            }
356            ScalarError::Type { func, arg } => {
357                write!(f, "{func}: argument {n} has an unsupported type", n = arg + 1)
358            }
359            ScalarError::Domain { func, what } => write!(f, "{func}: {what}"),
360        }
361    }
362}
363
364impl std::error::Error for ScalarError {}
365
366/// Evaluate `func(args…)` with PG 18 semantics.
367///
368/// Function names are matched case-insensitively (PG folds unquoted
369/// identifiers). Strict NULL propagation is handled per-function in
370/// the modules: most functions answer `Null` when any argument is
371/// `Null`; `coalesce`/`greatest`/`least` and friends look through.
372/// # Examples
373///
374/// ```
375/// use kevy_scalar::{Scalar, eval};
376/// // Names fold case, as PG folds unquoted identifiers.
377/// assert_eq!(eval("UPPER", &[Scalar::Text("x".into())]).unwrap(), Scalar::Text("X".into()));
378///
379/// // Most functions are strict in NULL...
380/// assert_eq!(eval("length", &[Scalar::Null]).unwrap(), Scalar::Null);
381/// // ...and the null family looks through it, which is the point of it.
382/// assert_eq!(
383///     eval("coalesce", &[Scalar::Null, Scalar::Int(7)]).unwrap(),
384///     Scalar::Int(7)
385/// );
386///
387/// // The RFC 1321 vectors, lower-case hex as PG's md5() emits.
388/// assert_eq!(
389///     eval("md5", &[Scalar::Text(String::new())]).unwrap(),
390///     Scalar::Text("d41d8cd98f00b204e9800998ecf8427e".into())
391/// );
392/// assert_eq!(
393///     eval("md5", &[Scalar::Text("abc".into())]).unwrap(),
394///     Scalar::Text("900150983cd24fb0d6963f7d28e17f72".into())
395/// );
396/// ```
397pub fn eval(func: &str, args: &[Scalar]) -> Result<Scalar, ScalarError> {
398    let name = func.to_ascii_lowercase();
399    match name.as_str() {
400        // ── strings ──
401        "lower" | "upper" | "initcap" | "length" | "char_length" | "character_length"
402        | "concat" | "concat_ws" | "trim" | "btrim" | "ltrim" | "rtrim" | "replace"
403        | "split_part" | "repeat" | "lpad" | "rpad" | "strpos" | "position" | "left" | "right"
404        | "reverse" | "translate" | "substr" | "substring" | "format" => strings::eval(&name, args),
405        // ── math ──
406        "floor" | "ceil" | "ceiling" | "round" | "trunc" | "mod" | "power" | "pow" | "sqrt"
407        | "sign" | "abs" => math::eval(&name, args),
408        // ── null family ──
409        "coalesce" | "nullif" | "greatest" | "least" => nullfam::eval(&name, args),
410        // ── date/time ──
411        "extract" | "date_part" | "date_trunc" | "age" | "to_char" | "date_format"
412        | "unix_timestamp" | "from_unixtime" => datetime::eval(&name, args),
413        // ── regexp (vendored engine) ──
414        "regexp_replace" | "regexp_matches" | "regexp_split_to_array" => regexp::eval(&name, args),
415        // ── hash ──
416        "md5" => match args {
417            [Scalar::Null] => Ok(Scalar::Null),
418            [Scalar::Text(t)] => Ok(Scalar::Text(md5::md5_hex(t.as_bytes()))),
419            [_] => Err(ScalarError::Type { func: "md5", arg: 0 }),
420            _ => Err(ScalarError::Arity { func: "md5", got: args.len() }),
421        },
422        _ => Err(ScalarError::UnknownFunction(func.to_string())),
423    }
424}