razeri_plugin_contract/sid_spelling.rs
1// Copyright (C) 2026 Gabriel Shea
2// Licensed under either of the Apache License, Version 2.0 or the MIT
3// license, at your option.
4
5//! **How this engine spells a surrogate key** — the one thing about the key a
6//! dialect decides.
7//!
8//! Razeri derives every surrogate key one way:
9//!
10//! ```text
11//! guard( hash( part₁ ) ) one column
12//! guard( hash( escape(part₁) ‖ '|' ‖ … ‖ escape(partₙ) ) ) two or more
13//! ```
14//!
15//! That derivation is Razeri's and is composed in one place
16//! ([`crate::sid`]). What varies between engines is only the **vocabulary** —
17//! how this engine writes a replacement and a Unicode literal, what it calls
18//! `TRIM`, how it joins strings, how it casts a value to text, and how it
19//! spells a 64-bit hash. [`SidSpelling`] is that vocabulary, and a dialect
20//! states it by overriding
21//! [`SqlRenderer::sid_spelling`](crate::SqlRenderer::sid_spelling).
22//!
23//! Two expressions built from this struct differ **only** in these fields,
24//! which is what makes *"provably the same key on every engine"* a proof
25//! rather than an assumption.
26//!
27//! # If your engine has no 64-bit hash
28//!
29//! Say so rather than reaching for the nearest-looking function. A hash that is
30//! deterministic *within* one warehouse and equal to nothing outside it is the
31//! exact lock-in a portable key exists to end — a warehouse keyed with it
32//! reconciles against nothing. The honest answers are an artifact your dialect
33//! installs (name it in [`SidSpelling::hash`] and emit its definition from your
34//! prerequisites), or a refusal that says what the reader should do instead.
35
36/// The [`SidSpelling::platform`] of a dialect that has not stated its spelling.
37///
38/// The default [`SidSpelling`] is ANSI's vocabulary, which is a **guess** and
39/// not a claim about any platform. It has to exist — a dialect must render
40/// *something* — and it has to be distinguishable from the agnostic renderer's
41/// answer, which is ANSI on purpose. Otherwise an unspelled platform gets ANSI
42/// everywhere, every producer agrees, and Razeri's cross-checks pass over a
43/// platform nobody has spelled: a check that cannot see its own blind spot.
44///
45/// **A dialect that leaves this value in place is telling Razeri it has not
46/// decided**, and the conformance kit reports it as an unanswered obligation.
47pub const UNKNOWN_PLATFORM: &str = "unknown";
48
49/// **How this engine writes a replacement and a Unicode literal**, and what
50/// it calls `LOWER`.
51///
52/// The key changes no letter: it is the hash of the value as the table stores
53/// it. These words are read where a value's characters are replaced or
54/// matched one by one — the escape inside a composite key
55/// ([`crate::sid::escape_part`]), a column's `clean: lowercase` and
56/// `clean: uppercase` steps (through [`AsciiFold::Replacements`]), and the
57/// reading of an amount the source wrote its own way.
58///
59/// # A replacement that matches by collation
60///
61/// An engine whose replacement matches a pattern under the value's own
62/// collation, rather than by the character, has to say so: under a
63/// case-insensitive collation a replacement of one letter also replaces its
64/// other case. Measured on SQL Server 2022 with its default collation, cured
65/// by [`Lower::match_collation`].
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct Lower {
68 /// The platform's lowercase function, in its own casing — `LOWER` on most
69 /// engines, `lowerUTF8` on one. The key does not call it.
70 pub function: &'static str,
71 /// The platform's three-argument string-replacement function — `REPLACE` on
72 /// most engines, `replaceAll` on one.
73 pub replace: &'static str,
74 /// **How this engine spells a Unicode string literal** — what goes in front
75 /// of the opening quote, where that differs from an ordinary literal. Empty
76 /// on every engine whose ordinary literal is already Unicode; `"N"` on
77 /// T-SQL, where a bare literal is narrowed to the database's code page and
78 /// the two Greek letters do not survive it.
79 ///
80 /// A literal has to survive the trip whole: the equality gate substitutes
81 /// probe values where a column reference stands, and a bare `'ΟΔΟΣ'`
82 /// reaches a T-SQL hash as `???S`. Anything that writes one of the
83 /// corpus's values into this engine as a literal reads this field.
84 pub pattern_literal_prefix: &'static str,
85 /// The collation a replacement's subject is pinned to, where this engine
86 /// matches a replacement pattern **under the subject's collation** rather
87 /// than by code point.
88 ///
89 /// `None` on every engine whose replacement is already by code point.
90 /// Name a **binary** collation where it is not: under an accent- or
91 /// case-insensitive one, a replacement of one character also replaces the
92 /// characters the collation calls equal to it.
93 pub match_collation: Option<&'static str>,
94}
95
96/// How a dialect casts one call-site argument to text.
97///
98/// The hash is a hash **of a string** and a call-site argument is a raw column
99/// of its own declared type, so the cast is not optional.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum TextCast {
102 /// `CAST(x AS <type>)` — the cast propagates NULL, so Razeri's NULL
103 /// sentinel is reached with the statement intact.
104 Direct(&'static str),
105 /// `assumeNotNull(CAST(x AS Nullable(<type>)))` — `ClickHouse`, whose
106 /// `CAST` to a non-`Nullable` type **raises** instead of propagating
107 /// (*"Cannot convert NULL to a non-nullable type"*).
108 ///
109 /// `ClickHouse` evaluates both arms of a `CASE`, so the sentinel cannot
110 /// save the statement: the emitted key expression failed outright on any
111 /// NULL natural-key part rather than returning the sentinel. That is not a
112 /// wrong key — it is a dimension load that does not run. The wrapper makes
113 /// the unreachable arm total; which value it would produce is irrelevant,
114 /// because the sentinel has already answered.
115 ClickHouseNullTolerant(&'static str),
116}
117
118/// How a dialect spells `TRIM`.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum Trim {
121 /// `TRIM(x)`, in the platform's own casing.
122 Function(&'static str),
123 /// `LTRIM(RTRIM(x))` — T-SQL, whose `TRIM` requires SQL Server 2017. The
124 /// pair removes the same leading and trailing spaces.
125 LtrimRtrim,
126 /// `TRIM(x, ' ')` — the engines whose **bare** `TRIM` removes every
127 /// whitespace character rather than the ASCII space alone.
128 ///
129 /// The canonical trim is the ASCII space (`U+0020`) and nothing else, which
130 /// is why a tab-padded and a newline-padded probe are in the corpus and are
131 /// *not* expected to be taken off. `BigQuery` is the measured member:
132 /// `LENGTH(TRIM('\tBoston\t'))` is 6 there — the tab gone and the key moved
133 /// — while `LENGTH(TRIM('\tBoston\t', ' '))` is 8, and a non-breaking space
134 /// survives the second form and not the first.
135 ///
136 /// The explicit set is not a repair of the engine; it is the canonical
137 /// clause written in an engine whose default set is wider. `TRIM(x, ' ')`
138 /// and `TRIM(x)` are the same function on every platform whose bare form
139 /// already strips the space alone, so the variant states a difference
140 /// rather than introducing one.
141 ///
142 /// **Only a tab-padded probe on your engine tells you which variant is
143 /// yours** — run the corpus on the engine itself. An emulator can give the
144 /// opposite answer: the community `BigQuery` emulator strips the space
145 /// alone.
146 FunctionWithSpaceSet(&'static str),
147}
148
149/// How a dialect joins the parts of a composite key.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum Concat {
152 /// `CONCAT(a, '|', b)`, in the platform's own casing.
153 Function(&'static str),
154 /// `CONCAT(CONCAT(a, '|'), b)` — the engines whose `CONCAT` takes
155 /// **exactly two arguments**, in the platform's own casing.
156 ///
157 /// Rendered by nesting pairwise, left to right, one call per pair: three
158 /// parts read `CONCAT(CONCAT(a, b), c)` where a variadic engine reads
159 /// `CONCAT(a, b, c)`. Db2 is the engine that needs it, and older Oracle
160 /// releases are the same shape.
161 ///
162 /// The distinction is not cosmetic. On such an engine the variadic
163 /// spelling is not a wider call to the same function, it is a call to a
164 /// function that is not there, so the first composite key stops the load
165 /// rather than reading oddly in review.
166 ///
167 /// The nesting joins the same parts with the same separator in the same
168 /// order, so the string that reaches the hash — and therefore the key — is
169 /// the one every other engine hashes. What differs is only how many calls
170 /// it takes to spell it.
171 FunctionBinary(&'static str),
172 /// `a + '|' + b` — T-SQL's string operator. Equal to `CONCAT` for non-NULL
173 /// operands, which Razeri's NULL sentinel is what guarantees: `+`
174 /// propagates NULL where `CONCAT` swallows it, and a swallowed NULL
175 /// silently collapses `('boston', NULL)` and `('boston', '')` into one
176 /// member.
177 Plus,
178 /// `a || '|' || b` — the engines that join strings with an operator, in
179 /// the operator's own spelling. `||` is the standard's, and the one an
180 /// engine with no `CONCAT` function usually takes.
181 ///
182 /// Rendered left to right, the operator between each part and the
183 /// separator: `Operator("||")` over three parts reads
184 /// `a || '|' || b || '|' || c`. One expression, whatever the number of
185 /// parts, and no function the warehouse has to hold.
186 ///
187 /// Like [`Plus`](Self::Plus), the operator propagates NULL where `CONCAT`
188 /// swallows it, and Razeri's NULL sentinel is what makes that safe: a key
189 /// with a NULL part is answered before the join is reached.
190 Operator(&'static str),
191}
192
193/// **How a column's `clean:` step changes the case of a letter** — on this
194/// engine, for the twenty-six ASCII letters and nothing else.
195///
196/// A fold is never the engine's `LOWER` or `UPPER`: what they do to a letter
197/// outside `a` to `z` belongs to the database's collation, so the same value
198/// would be stored two ways on two databases. The default spells the fold in
199/// plain SQL that no collation reads, twenty-six nested replacements. An engine
200/// that holds a function doing exactly that fold names it here, and the step is
201/// one call.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum AsciiFold {
204 /// `REPLACE(… REPLACE(x, 'a', 'A') …, 'z', 'Z')`: one replacement per
205 /// letter, written with [`Lower::replace`] over the value pinned to
206 /// [`Lower::match_collation`]. Every engine with a three-argument replace
207 /// can run it, which is why it is the default.
208 ///
209 /// The nesting is twenty-six calls deep, and a parser can refuse that depth
210 /// inside some statements. `SQLite` 3.45 is the measured case: a
211 /// `parser stack overflow` inside an `UPDATE` or an `INSERT … SELECT`,
212 /// while the same expression runs in a plain `SELECT`.
213 Replacements,
214 /// One call to a function the engine holds: `to_upper(x)` changes `a` to
215 /// `z` into `A` to `Z`, `to_lower(x)` changes `A` to `Z` into `a` to `z`,
216 /// and both leave every other character as it is.
217 ///
218 /// The function is the dialect's to install, from its prerequisites or an
219 /// extension it ships. It must answer exactly what the replacements
220 /// answer for every value, including a letter outside ASCII, which it
221 /// leaves alone; measure it against them before you ship it.
222 Functions {
223 /// The function that folds to capitals.
224 to_upper: &'static str,
225 /// The function that folds to small letters.
226 to_lower: &'static str,
227 },
228}
229
230/// One platform's vocabulary for the surrogate-key derivation — the only thing
231/// that varies between engines.
232#[derive(Debug, Clone, Copy)]
233pub struct SidSpelling {
234 /// The name this dialect answers under. [`UNKNOWN_PLATFORM`] means the
235 /// dialect has not stated a spelling and is taking ANSI's guess.
236 pub platform: &'static str,
237 /// How this engine writes a replacement and a Unicode literal.
238 pub lower: Lower,
239 /// The `TRIM` function, or the pair that stands in for it.
240 pub trim: Trim,
241 /// The join used for composite keys.
242 pub concat: Concat,
243 /// The platform's hash of a text expression, as the
244 /// text before and after it. `("CAST(xxHash64(", ") AS Int64)")` reads
245 /// `CAST(xxHash64(x) AS Int64)`.
246 pub hash: (&'static str, &'static str),
247 /// The CAST that turns one argument into text. The hash is a hash OF A
248 /// STRING, and at the inline call sites the argument is a raw column of its
249 /// own declared type — `TRIM(DATE)` is a binder error, not a value.
250 pub cast_type: TextCast,
251 /// Whether the load path reaches the hash through Razeri's emitted helper
252 /// function instead of inlining it: `false` where the platform's own
253 /// function is already the derivation, or where a dialect chooses to write
254 /// the hash at every call site.
255 pub through_helper: bool,
256 /// How a column's `clean:` step changes the case of a letter here — the
257 /// twenty-six replacements, or one function the engine holds.
258 pub ascii_fold: AsciiFold,
259}
260
261/// **ANSI's vocabulary** — the spelling a dialect inherits until it states its
262/// own, and the agnostic renderer's answer on purpose.
263///
264/// A dialect building its own arm should start from this and change only the
265/// fields its engine actually spells differently:
266///
267/// ```
268/// use razeri_plugin_contract::{ANSI_SID_SPELLING, SidSpelling, TextCast};
269///
270/// const MY_ENGINE: SidSpelling = SidSpelling {
271/// platform: "my-engine",
272/// hash: ("my_xxhash64(", ")"),
273/// cast_type: TextCast::Direct("STRING"),
274/// through_helper: false,
275/// ..ANSI_SID_SPELLING
276/// };
277/// ```
278pub const ANSI_SID_SPELLING: SidSpelling = SidSpelling {
279 platform: "ansi",
280 lower: Lower {
281 function: "LOWER",
282 replace: "REPLACE",
283 pattern_literal_prefix: "",
284 match_collation: None,
285 },
286 trim: Trim::Function("TRIM"),
287 concat: Concat::Function("CONCAT"),
288 hash: ("xxhash64(", ")"),
289 cast_type: TextCast::Direct("TEXT"),
290 through_helper: true,
291 ascii_fold: AsciiFold::Replacements,
292};
293
294/// **The language a surrogate-key helper's body is written in**, where that
295/// body is not SQL.
296///
297/// The two named languages are the ones Razeri's function renderers already
298/// spell a `LANGUAGE` clause for. Anything else is [`Named`](Self::Named),
299/// which carries the keyword through unchanged.
300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub enum SidHelperLanguage {
302 /// JavaScript.
303 JavaScript,
304 /// Python.
305 Python,
306 /// A language keyword this contract does not name, spelled exactly as the
307 /// engine's `LANGUAGE` clause takes it.
308 Named(&'static str),
309}
310
311/// **The whole body of the surrogate-key helper, supplied by the dialect.**
312///
313/// Razeri normally builds the helper's body itself: it is the one derivation,
314/// composed from this engine's [`SidSpelling`] in this engine's own SQL. A
315/// dialect answers with this type only when that is impossible — the engine has
316/// no 64-bit hash in any SQL spelling, so there is no vocabulary to compose
317/// from and the definition has to be written in another language.
318///
319/// Answering here does **not** change the key. The body must compute XXH64 with
320/// seed 0 over the UTF-8 bytes of its single argument, as given, and
321/// return it as a signed 64-bit integer — the same number every other engine
322/// returns for the same input. A body that computes something else keys a
323/// warehouse to numbers nothing else reproduces, which is the lock-in a
324/// portable key exists to end. Measure it against the canonical number before
325/// you ship it.
326///
327/// The body is the function's inner text only: Razeri writes the `CREATE
328/// FUNCTION` envelope, the parameter, the return type and the `LANGUAGE`
329/// clause around it.
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
331pub struct SidHelperBody {
332 /// What the body is written in.
333 pub language: SidHelperLanguage,
334 /// The body itself.
335 pub body: &'static str,
336}
337
338/// The spelling a dialect that has decided nothing renders — ANSI's vocabulary
339/// under the name that says it is a guess.
340pub const UNSPELLED_SID: SidSpelling =
341 SidSpelling { platform: UNKNOWN_PLATFORM, ..ANSI_SID_SPELLING };
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 #[test]
348 fn the_unspelled_default_differs_from_ansi_only_in_its_name() {
349 assert_eq!(UNSPELLED_SID.platform, UNKNOWN_PLATFORM);
350 assert_eq!(UNSPELLED_SID.hash, ANSI_SID_SPELLING.hash);
351 assert_eq!(UNSPELLED_SID.lower, ANSI_SID_SPELLING.lower);
352 assert_eq!(UNSPELLED_SID.trim, ANSI_SID_SPELLING.trim);
353 assert_eq!(UNSPELLED_SID.concat, ANSI_SID_SPELLING.concat);
354 assert_eq!(UNSPELLED_SID.cast_type, ANSI_SID_SPELLING.cast_type);
355 assert_eq!(UNSPELLED_SID.through_helper, ANSI_SID_SPELLING.through_helper);
356 assert_eq!(UNSPELLED_SID.ascii_fold, ANSI_SID_SPELLING.ascii_fold);
357 }
358}