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)]
56pub enum Scalar {
57 /// SQL NULL. Propagates: any strict function with a NULL argument
58 /// answers NULL (the null-family module documents its exceptions).
59 Null,
60 /// A 64-bit integer.
61 Int(i64),
62 /// A 64-bit float. PG's numeric literals fold through here; the
63 /// sql face renders results back with PG's trailing-zero rules.
64 Float(f64),
65 /// A UTF-8 string.
66 Text(String),
67 /// A boolean.
68 Bool(bool),
69 /// A timestamp (no time zone): microseconds since the Unix epoch.
70 /// Probe 38's lesson is baked in: `now()` and friends must be
71 /// TYPED, not text — the sql face rewrites them to this variant.
72 Timestamp(i64),
73 /// A calendar date: days since the Unix epoch.
74 Date(i64),
75 /// An interval in PG's three-component shape: months, days and
76 /// microseconds never mix (probe 10's `1 day - 12 hours` stays
77 /// `1 day -12:00:00` — no normalization across components). Month
78 /// arithmetic clamps to month ends; the other two are exact.
79 Interval {
80 /// Whole calendar months (12 per year).
81 months: i64,
82 /// Whole days — separate from micros because PG keeps them
83 /// separate (visible in rendering and component extraction).
84 days: i64,
85 /// Sub-day remainder in microseconds.
86 micros: i64,
87 },
88}
89
90impl Scalar {
91 /// Whether this is SQL NULL.
92 #[must_use]
93 pub fn is_null(&self) -> bool {
94 matches!(self, Scalar::Null)
95 }
96
97 /// PG's text output form for this value. `Null` renders as the
98 /// empty string here — a caller that needs a `NULL` marker (the
99 /// sqllogictest runner does) checks [`Scalar::is_null`] first.
100 #[must_use]
101 pub fn render(&self) -> String {
102 strings::to_text(self)
103 }
104}
105
106/// Why a call could not be evaluated.
107///
108/// `UnknownFunction` is the load-bearing variant: the sql face turns
109/// it into a *named refusal* (the funcgate contract says silent
110/// failure is itself a gate failure), so the message must carry the
111/// function name verbatim.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum ScalarError {
114 /// No function with this name in the library. Field = the name.
115 UnknownFunction(String),
116 /// The function exists but not with this argument count.
117 Arity {
118 /// Function name.
119 func: &'static str,
120 /// What the call supplied.
121 got: usize,
122 },
123 /// An argument had a type the function cannot take (PG would have
124 /// refused the cast at parse time; the sql face reports this with
125 /// the same vocabulary).
126 Type {
127 /// Function name.
128 func: &'static str,
129 /// 0-based argument position.
130 arg: usize,
131 },
132 /// Arithmetic that PG raises on: division by zero, sqrt of a
133 /// negative, integer overflow.
134 Domain {
135 /// Function name.
136 func: &'static str,
137 /// PG's error phrase, e.g. `division by zero`.
138 what: &'static str,
139 },
140}
141
142impl std::fmt::Display for ScalarError {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144 match self {
145 ScalarError::UnknownFunction(name) => {
146 write!(f, "unknown function: {name}")
147 }
148 ScalarError::Arity { func, got } => {
149 write!(f, "{func}: wrong argument count ({got})")
150 }
151 ScalarError::Type { func, arg } => {
152 write!(f, "{func}: argument {n} has an unsupported type", n = arg + 1)
153 }
154 ScalarError::Domain { func, what } => write!(f, "{func}: {what}"),
155 }
156 }
157}
158
159impl std::error::Error for ScalarError {}
160
161/// Evaluate `func(args…)` with PG 18 semantics.
162///
163/// Function names are matched case-insensitively (PG folds unquoted
164/// identifiers). Strict NULL propagation is handled per-function in
165/// the modules: most functions answer `Null` when any argument is
166/// `Null`; `coalesce`/`greatest`/`least` and friends look through.
167pub fn eval(func: &str, args: &[Scalar]) -> Result<Scalar, ScalarError> {
168 let name = func.to_ascii_lowercase();
169 match name.as_str() {
170 // ── strings ──
171 "lower" | "upper" | "initcap" | "length" | "char_length" | "character_length"
172 | "concat" | "concat_ws" | "trim" | "btrim" | "ltrim" | "rtrim" | "replace"
173 | "split_part" | "repeat" | "lpad" | "rpad" | "strpos" | "position" | "left"
174 | "right" | "reverse" | "translate" | "substr" | "substring" | "format" => {
175 strings::eval(&name, args)
176 }
177 // ── math ──
178 "floor" | "ceil" | "ceiling" | "round" | "trunc" | "mod" | "power" | "pow"
179 | "sqrt" | "sign" | "abs" => math::eval(&name, args),
180 // ── null family ──
181 "coalesce" | "nullif" | "greatest" | "least" => nullfam::eval(&name, args),
182 // ── date/time ──
183 "extract" | "date_part" | "date_trunc" | "age" | "to_char" | "date_format"
184 | "unix_timestamp" | "from_unixtime" => datetime::eval(&name, args),
185 // ── regexp (vendored engine) ──
186 "regexp_replace" | "regexp_matches" | "regexp_split_to_array" => regexp::eval(&name, args),
187 // ── hash ──
188 "md5" => match args {
189 [Scalar::Null] => Ok(Scalar::Null),
190 [Scalar::Text(t)] => Ok(Scalar::Text(md5::md5_hex(t.as_bytes()))),
191 [_] => Err(ScalarError::Type { func: "md5", arg: 0 }),
192 _ => Err(ScalarError::Arity { func: "md5", got: args.len() }),
193 },
194 _ => Err(ScalarError::UnknownFunction(func.to_string())),
195 }
196}