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())]).unwrap();
21//! assert_eq!(out, Scalar::Text("hello".into()));
22//! ```
23
24#![forbid(unsafe_code)]
25#![warn(missing_docs)]
26
27mod datetime;
28mod datetime_fmt;
29mod logic;
30mod math;
31mod md5;
32mod regex_engine;
33mod regexp;
34mod nullfam;
35mod ops;
36mod strings;
37mod strings_slice;
38#[cfg(test)]
39mod tests;
40
41pub use logic::{cmp_op, logic_and, logic_not, logic_or, parse_pg_bool};
42pub use ops::binop;
43
44pub use datetime_fmt::{
45    parse_date, parse_interval, parse_timestamp, render_date, render_interval,
46    render_timestamp,
47};
48
49/// A typed scalar value — the closed set the function library speaks.
50///
51/// Deliberately narrower than SQL's type zoo: kevy's sql face maps
52/// bigint/int → `Int`, double/numeric-literal → `Float`, text/varchar
53/// → `Text`, boolean → `Bool`, and SQL `NULL` → `Null`. Types the
54/// engine refuses (money, inet, enum, …) never reach this crate.
55#[derive(Debug, Clone, PartialEq)]
56/// # Examples
57///
58/// ```
59/// use kevy_scalar::{Scalar, eval};
60/// // NULL is a value here, not an absence, and it PROPAGATES: a strict
61/// // function with a NULL argument answers NULL rather than erroring.
62/// assert_eq!(eval("upper", &[Scalar::Null]).unwrap(), Scalar::Null);
63/// assert_eq!(
64///     eval("upper", &[Scalar::Text("ada".into())]).unwrap(),
65///     Scalar::Text("ADA".into())
66/// );
67/// ```
68pub enum Scalar {
69    /// SQL NULL. Propagates: any strict function with a NULL argument
70    /// answers NULL (the null-family module documents its exceptions).
71    Null,
72    /// A 64-bit integer.
73    Int(i64),
74    /// A 64-bit float. PG's numeric literals fold through here; the
75    /// sql face renders results back with PG's trailing-zero rules.
76    Float(f64),
77    /// A UTF-8 string.
78    Text(String),
79    /// A boolean.
80    Bool(bool),
81    /// A timestamp (no time zone): microseconds since the Unix epoch.
82    /// Probe 38's lesson is baked in: `now()` and friends must be
83    /// TYPED, not text — the sql face rewrites them to this variant.
84    Timestamp(i64),
85    /// A calendar date: days since the Unix epoch.
86    Date(i64),
87    /// An interval in PG's three-component shape: months, days and
88    /// microseconds never mix (probe 10's `1 day - 12 hours` stays
89    /// `1 day -12:00:00` — no normalization across components). Month
90    /// arithmetic clamps to month ends; the other two are exact.
91    Interval {
92        /// Whole calendar months (12 per year).
93        months: i64,
94        /// Whole days — separate from micros because PG keeps them
95        /// separate (visible in rendering and component extraction).
96        days: i64,
97        /// Sub-day remainder in microseconds.
98        micros: i64,
99    },
100}
101
102impl Scalar {
103    /// Whether this is SQL NULL.
104    #[must_use]
105    /// # Examples
106    ///
107    /// ```
108    /// use kevy_scalar::Scalar;
109    /// assert!(Scalar::Null.is_null());
110    /// assert!(!Scalar::Int(0).is_null(), "zero is a value, not a NULL");
111    /// assert!(!Scalar::Text(String::new()).is_null(), "so is the empty string");
112    /// ```
113    pub fn is_null(&self) -> bool {
114        matches!(self, Scalar::Null)
115    }
116
117    /// PG's text output form for this value. `Null` renders as the
118    /// empty string here — a caller that needs a `NULL` marker (the
119    /// sqllogictest runner does) checks [`Scalar::is_null`] first.
120    #[must_use]
121    /// # Examples
122    ///
123    /// ```
124    /// use kevy_scalar::Scalar;
125    /// assert_eq!(Scalar::Int(42).render(), "42");
126    /// assert_eq!(Scalar::Text("ada".into()).render(), "ada");
127    /// assert_eq!(Scalar::Bool(true).render(), "t", "PG's boolean output");
128    /// ```
129    pub fn render(&self) -> String {
130        strings::to_text(self)
131    }
132}
133
134/// Why a call could not be evaluated.
135///
136/// `UnknownFunction` is the load-bearing variant: the sql face turns
137/// it into a *named refusal* (the funcgate contract says silent
138/// failure is itself a gate failure), so the message must carry the
139/// function name verbatim.
140#[derive(Debug, Clone, PartialEq, Eq)]
141/// # Examples
142///
143/// ```
144/// use kevy_scalar::{Scalar, ScalarError, eval};
145/// // A name this engine does not implement is refused BY NAME rather
146/// // than silently answering NULL.
147/// assert!(matches!(
148///     eval("no_such_fn", &[]),
149///     Err(ScalarError::UnknownFunction(_))
150/// ));
151/// // So is the wrong number of arguments.
152/// assert!(matches!(eval("md5", &[]), Err(ScalarError::Arity { .. })));
153/// ```
154pub enum ScalarError {
155    /// No function with this name in the library. Field = the name.
156    UnknownFunction(String),
157    /// The function exists but not with this argument count.
158    Arity {
159        /// Function name.
160        func: &'static str,
161        /// What the call supplied.
162        got: usize,
163    },
164    /// An argument had a type the function cannot take (PG would have
165    /// refused the cast at parse time; the sql face reports this with
166    /// the same vocabulary).
167    Type {
168        /// Function name.
169        func: &'static str,
170        /// 0-based argument position.
171        arg: usize,
172    },
173    /// Arithmetic that PG raises on: division by zero, sqrt of a
174    /// negative, integer overflow.
175    Domain {
176        /// Function name.
177        func: &'static str,
178        /// PG's error phrase, e.g. `division by zero`.
179        what: &'static str,
180    },
181}
182
183impl std::fmt::Display for ScalarError {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        match self {
186            ScalarError::UnknownFunction(name) => {
187                write!(f, "unknown function: {name}")
188            }
189            ScalarError::Arity { func, got } => {
190                write!(f, "{func}: wrong argument count ({got})")
191            }
192            ScalarError::Type { func, arg } => {
193                write!(f, "{func}: argument {n} has an unsupported type", n = arg + 1)
194            }
195            ScalarError::Domain { func, what } => write!(f, "{func}: {what}"),
196        }
197    }
198}
199
200impl std::error::Error for ScalarError {}
201
202/// Evaluate `func(args…)` with PG 18 semantics.
203///
204/// Function names are matched case-insensitively (PG folds unquoted
205/// identifiers). Strict NULL propagation is handled per-function in
206/// the modules: most functions answer `Null` when any argument is
207/// `Null`; `coalesce`/`greatest`/`least` and friends look through.
208/// # Examples
209///
210/// ```
211/// use kevy_scalar::{Scalar, eval};
212/// // Names fold case, as PG folds unquoted identifiers.
213/// assert_eq!(eval("UPPER", &[Scalar::Text("x".into())]).unwrap(), Scalar::Text("X".into()));
214///
215/// // Most functions are strict in NULL...
216/// assert_eq!(eval("length", &[Scalar::Null]).unwrap(), Scalar::Null);
217/// // ...and the null family looks through it, which is the point of it.
218/// assert_eq!(
219///     eval("coalesce", &[Scalar::Null, Scalar::Int(7)]).unwrap(),
220///     Scalar::Int(7)
221/// );
222///
223/// // The RFC 1321 vectors, lower-case hex as PG's md5() emits.
224/// assert_eq!(
225///     eval("md5", &[Scalar::Text(String::new())]).unwrap(),
226///     Scalar::Text("d41d8cd98f00b204e9800998ecf8427e".into())
227/// );
228/// assert_eq!(
229///     eval("md5", &[Scalar::Text("abc".into())]).unwrap(),
230///     Scalar::Text("900150983cd24fb0d6963f7d28e17f72".into())
231/// );
232/// ```
233pub fn eval(func: &str, args: &[Scalar]) -> Result<Scalar, ScalarError> {
234    let name = func.to_ascii_lowercase();
235    match name.as_str() {
236        // ── strings ──
237        "lower" | "upper" | "initcap" | "length" | "char_length" | "character_length"
238        | "concat" | "concat_ws" | "trim" | "btrim" | "ltrim" | "rtrim" | "replace"
239        | "split_part" | "repeat" | "lpad" | "rpad" | "strpos" | "position" | "left"
240        | "right" | "reverse" | "translate" | "substr" | "substring" | "format" => {
241            strings::eval(&name, args)
242        }
243        // ── math ──
244        "floor" | "ceil" | "ceiling" | "round" | "trunc" | "mod" | "power" | "pow"
245        | "sqrt" | "sign" | "abs" => math::eval(&name, args),
246        // ── null family ──
247        "coalesce" | "nullif" | "greatest" | "least" => nullfam::eval(&name, args),
248        // ── date/time ──
249        "extract" | "date_part" | "date_trunc" | "age" | "to_char" | "date_format"
250        | "unix_timestamp" | "from_unixtime" => datetime::eval(&name, args),
251        // ── regexp (vendored engine) ──
252        "regexp_replace" | "regexp_matches" | "regexp_split_to_array" => regexp::eval(&name, args),
253        // ── hash ──
254        "md5" => match args {
255            [Scalar::Null] => Ok(Scalar::Null),
256            [Scalar::Text(t)] => Ok(Scalar::Text(md5::md5_hex(t.as_bytes()))),
257            [_] => Err(ScalarError::Type { func: "md5", arg: 0 }),
258            _ => Err(ScalarError::Arity { func: "md5", got: args.len() }),
259        },
260        _ => Err(ScalarError::UnknownFunction(func.to_string())),
261    }
262}