Skip to main content

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( normalize(part₁) ‖ '|' ‖ … ‖ normalize(partₙ) ) )
12//! ```
13//!
14//! That derivation is Razeri's and is composed in one place. What varies
15//! between engines is only the **vocabulary** — what this engine calls `LOWER`,
16//! what it calls `TRIM`, how it joins strings, how it casts a value to text,
17//! and how it spells a 64-bit hash. [`SidSpelling`] is that vocabulary, and a
18//! dialect states it by overriding
19//! [`SqlRenderer::sid_spelling`](crate::SqlRenderer::sid_spelling).
20//!
21//! Two expressions built from this struct differ **only** in these fields,
22//! which is what makes *"provably the same key on every engine"* a proof
23//! rather than an assumption.
24//!
25//! # If your engine has no 64-bit hash
26//!
27//! Say so rather than reaching for the nearest-looking function. A hash that is
28//! deterministic *within* one warehouse and equal to nothing outside it is the
29//! exact lock-in a portable key exists to end — a warehouse keyed with it
30//! reconciles against nothing. The honest answers are an artifact your dialect
31//! installs (name it in [`SidSpelling::hash`] and emit its definition from your
32//! prerequisites), or a refusal that says what the reader should do instead.
33
34/// The [`SidSpelling::platform`] of a dialect that has not stated its spelling.
35///
36/// The default [`SidSpelling`] is ANSI's vocabulary, which is a **guess** and
37/// not a claim about any platform. It has to exist — a dialect must render
38/// *something* — and it has to be distinguishable from the agnostic renderer's
39/// answer, which is ANSI on purpose. Otherwise an unspelled platform gets ANSI
40/// everywhere, every producer agrees, and Razeri's cross-checks pass over a
41/// platform nobody has spelled: a check that cannot see its own blind spot.
42///
43/// **A dialect that leaves this value in place is telling Razeri it has not
44/// decided**, and the conformance kit reports it as an unanswered obligation.
45pub const UNKNOWN_PLATFORM: &str = "unknown";
46
47/// How a dialect spells `LOWER`.
48///
49/// The canonical lowercase is fixed as **locale-independent simple case
50/// mapping, one code point to one code point, with no combining mark
51/// introduced by the operation**. Some engines' `LOWER` is exactly that;
52/// [`Lower::SimpleFoldViaReplace`] is for the ones whose `LOWER` is the
53/// **full** mapping instead, which is measurably a different function.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Lower {
56    /// `LOWER(x)`, in the platform's own casing. Measured against the canonical
57    /// reference on `DuckDB`, `PostgreSQL`, Citus and `MariaDB`: all four fold
58    /// `İ` (U+0130) to a bare `i` and lower the rest of the BMP, which is the
59    /// canonical mapping.
60    Function(&'static str),
61    /// `<lower>(<replace>(<replace>(x, 'İ', 'I'), 'Σ', 'σ'))` — the
62    /// **full**-fold engines, whose Unicode-aware lowercase is a different
63    /// function from the canonical simple case mapping on two code points, for
64    /// **two different reasons**. The reasons do not merge, and stating them as
65    /// one would round the evidence up:
66    ///
67    /// - **`İ` (U+0130) — the unconditional divergence.** Its full lowercase is
68    ///   `i` + U+0307, a combining mark the canonical mapping excludes by name,
69    ///   and it is the **only** code point whose simple and full mappings
70    ///   differ with no context at all. Replacing it with `I` first makes the
71    ///   composition exactly the simple mapping;
72    /// - **`Σ` (U+03A3) — the conditional divergence.** Its full lowercase is
73    ///   `σ` *except* word-finally, where Unicode's `Final_Sigma` condition
74    ///   makes it `ς` (U+03C2). No enumeration of unconditional mappings can
75    ///   see this: a different quantifier hides a different letter. Replacing
76    ///   every `Σ` with an already-lowercase `σ` first removes the context the
77    ///   rule reads, and `LOWER` then leaves it alone.
78    ///
79    /// With both applied the composition is the simple mapping over the whole
80    /// scalar space — an exact rendering of the canonical clause in the
81    /// platform's own vocabulary, never a local approximation. The reason this
82    /// is one variant rather than a per-platform arm is that the *reasoning* is
83    /// one reasoning; only the two function names differ.
84    ///
85    /// **Three engines have been measured needing it** — `ClickHouse`
86    /// (`lowerUTF8` / `replaceAll`), Snowflake (`LOWER` / `REPLACE`) and
87    /// Databricks (`LOWER` / `REPLACE`) — and every one of the three was found
88    /// by *executing* a Turkish and a Greek probe, never by reading a manual.
89    /// If you have not run those two probes on your engine, you do not yet know
90    /// which variant is yours.
91    SimpleFoldViaReplace {
92        /// The platform's full-fold lowercase function.
93        lower: &'static str,
94        /// The platform's three-argument string-replacement function.
95        replace: &'static str,
96    },
97}
98
99/// How a dialect casts one call-site argument to text.
100///
101/// The hash is a hash **of a string** and a call-site argument is a raw column
102/// of its own declared type, so the cast is not optional.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum TextCast {
105    /// `CAST(x AS <type>)` — the cast propagates NULL, so Razeri's NULL
106    /// sentinel is reached with the statement intact.
107    Direct(&'static str),
108    /// `assumeNotNull(CAST(x AS Nullable(<type>)))` — `ClickHouse`, whose
109    /// `CAST` to a non-`Nullable` type **raises** instead of propagating
110    /// (*"Cannot convert NULL to a non-nullable type"*).
111    ///
112    /// `ClickHouse` evaluates both arms of a `CASE`, so the sentinel cannot
113    /// save the statement: the emitted key expression failed outright on any
114    /// NULL natural-key part rather than returning the sentinel. That is not a
115    /// wrong key — it is a dimension load that does not run. The wrapper makes
116    /// the unreachable arm total; which value it would produce is irrelevant,
117    /// because the sentinel has already answered.
118    ClickHouseNullTolerant(&'static str),
119}
120
121/// How a dialect spells `TRIM`.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum Trim {
124    /// `TRIM(x)`, in the platform's own casing.
125    Function(&'static str),
126    /// `LTRIM(RTRIM(x))` — T-SQL, whose `TRIM` requires SQL Server 2017. The
127    /// pair removes the same leading and trailing spaces.
128    LtrimRtrim,
129    /// `TRIM(x, ' ')` — the engines whose **bare** `TRIM` removes every
130    /// whitespace character rather than the ASCII space alone.
131    ///
132    /// The canonical trim is the ASCII space (`U+0020`) and nothing else, which
133    /// is why a tab-padded and a newline-padded probe are in the corpus and are
134    /// *not* expected to normalize away. `BigQuery` is the measured member:
135    /// `LENGTH(TRIM('\tBoston\t'))` is 6 there — the tab gone and the key moved
136    /// — while `LENGTH(TRIM('\tBoston\t', ' '))` is 8, and a non-breaking space
137    /// survives the second form and not the first.
138    ///
139    /// The explicit set is not a repair of the engine; it is the canonical
140    /// clause written in an engine whose default set is wider. `TRIM(x, ' ')`
141    /// and `TRIM(x)` are the same function on every platform whose bare form
142    /// already strips the space alone, so the variant states a difference
143    /// rather than introducing one.
144    ///
145    /// **If you have not run a tab-padded probe on your engine, you do not yet
146    /// know which variant is yours** — this one was found by executing the
147    /// corpus on the service, and by nothing else. The community emulator this
148    /// dialect was built against strips the space alone, which is the opposite
149    /// answer.
150    FunctionWithSpaceSet(&'static str),
151}
152
153/// How a dialect joins the normalized parts of a composite key.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum Concat {
156    /// `CONCAT(a, '|', b)`, in the platform's own casing.
157    Function(&'static str),
158    /// `a + '|' + b` — T-SQL's string operator. Equal to `CONCAT` for non-NULL
159    /// operands, which Razeri's NULL sentinel is what guarantees: `+`
160    /// propagates NULL where `CONCAT` swallows it, and a swallowed NULL
161    /// silently collapses `('boston', NULL)` and `('boston', '')` into one
162    /// member.
163    Plus,
164}
165
166/// One platform's vocabulary for the surrogate-key derivation — the only thing
167/// that varies between engines.
168#[derive(Debug, Clone, Copy)]
169pub struct SidSpelling {
170    /// The name this dialect answers under. [`UNKNOWN_PLATFORM`] means the
171    /// dialect has not stated a spelling and is taking ANSI's guess.
172    pub platform: &'static str,
173    /// The `LOWER` function, or the composition that stands in for it.
174    pub lower: Lower,
175    /// The `TRIM` function, or the pair that stands in for it.
176    pub trim: Trim,
177    /// The join used for composite keys.
178    pub concat: Concat,
179    /// The platform's hash of an already-normalized text expression, as the
180    /// text before and after it. `("CAST(xxHash64(", ") AS Int64)")` reads
181    /// `CAST(xxHash64(x) AS Int64)`.
182    pub hash: (&'static str, &'static str),
183    /// The CAST that turns one argument into text. The hash is a hash OF A
184    /// STRING, and at the inline call sites the argument is a raw column of its
185    /// own declared type — `TRIM(DATE)` is a binder error, not a value.
186    pub cast_type: TextCast,
187    /// Whether the load path reaches the hash through Razeri's emitted helper
188    /// function instead of inlining it. Inlining is forced where a UDF cannot
189    /// call another UDF (`DuckDB` macros, `ClickHouse` lambdas) and chosen
190    /// where the platform's own function is already the derivation.
191    pub through_helper: bool,
192}
193
194/// **ANSI's vocabulary** — the spelling a dialect inherits until it states its
195/// own, and the agnostic renderer's answer on purpose.
196///
197/// A dialect building its own arm should start from this and change only the
198/// fields its engine actually spells differently:
199///
200/// ```
201/// use razeri_plugin_contract::{ANSI_SID_SPELLING, SidSpelling, TextCast};
202///
203/// const MY_ENGINE: SidSpelling = SidSpelling {
204///     platform: "my-engine",
205///     hash: ("my_xxhash64(", ")"),
206///     cast_type: TextCast::Direct("STRING"),
207///     through_helper: false,
208///     ..ANSI_SID_SPELLING
209/// };
210/// ```
211pub const ANSI_SID_SPELLING: SidSpelling = SidSpelling {
212    platform: "ansi",
213    lower: Lower::Function("LOWER"),
214    trim: Trim::Function("TRIM"),
215    concat: Concat::Function("CONCAT"),
216    hash: ("xxhash64(", ")"),
217    cast_type: TextCast::Direct("TEXT"),
218    through_helper: true,
219};
220
221/// The spelling a dialect that has decided nothing renders — ANSI's vocabulary
222/// under the name that says it is a guess.
223pub const UNSPELLED_SID: SidSpelling =
224    SidSpelling { platform: UNKNOWN_PLATFORM, ..ANSI_SID_SPELLING };
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn the_unspelled_default_differs_from_ansi_only_in_its_name() {
232        assert_eq!(UNSPELLED_SID.platform, UNKNOWN_PLATFORM);
233        assert_eq!(UNSPELLED_SID.hash, ANSI_SID_SPELLING.hash);
234        assert_eq!(UNSPELLED_SID.lower, ANSI_SID_SPELLING.lower);
235        assert_eq!(UNSPELLED_SID.trim, ANSI_SID_SPELLING.trim);
236        assert_eq!(UNSPELLED_SID.concat, ANSI_SID_SPELLING.concat);
237        assert_eq!(UNSPELLED_SID.cast_type, ANSI_SID_SPELLING.cast_type);
238        assert_eq!(UNSPELLED_SID.through_helper, ANSI_SID_SPELLING.through_helper);
239    }
240}