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