ingraph_codegen/alias.rs
1//! The SQL table aliases a record's rows are addressed by inside a nested statement, minted HERE
2//! rather than at the moment one is rendered.
3//!
4//! # Why an expansion computes them and the engine only indexes
5//!
6//! An alias is a pure function of two compile-time facts — the table's name, and the nesting DEPTH
7//! of the scope wearing it — so there is nothing about it a running statement knows that a macro
8//! does not. Minting at render time therefore bought nothing and cost a `Utf8BytesMut` per
9//! occurrence per statement, on the one path this family is arranged to keep allocation off.
10//!
11//! What the engine gets instead is `&'static [&'static str]` beside the row's address: an index, a
12//! slice bound, and no string built at all.
13//!
14//! # Both halves are a DECLARATION's to move, and the defaults are what most of them keep
15//!
16//! [`ALIAS_PREFIX`] and [`DEPTH_CEILING`] are the answers a record that names nothing gets.
17//! `<db>(alias(prefix = "__mine", depth = 16))` is the record that names one, and the knob
18//! is per DATABASE because the emitted table is: `ALIASES` rides one `SqlQuery<Db>` impl, so two
19//! databases of one record already carry two of them and nothing had to be widened to let them
20//! differ.
21//!
22//! # The DEPTH is the axis, and it is the only one that separates anything
23//!
24//! An alias is scoped to the subquery that states it, so two SIBLING subqueries may each call their
25//! row source the same thing and neither can see the other's. What has to differ is a name and the
26//! name it NESTS inside — and nesting depth is exactly that, which is why the array is indexed by it
27//! and why a per-occurrence counter would have been both unobtainable and unnecessary.
28//!
29//! # No parity, and no alternating pair
30//!
31//! Two alternating names — one for even depths, one for odd — would be enough for a reference that
32//! never reaches two levels, and that is the whole objection: it is correct until a declaration
33//! nests a relation inside a relation over the same table, at which point the third level silently
34//! takes the first level's name, SQL resolves every reference to the inner scope, and the statement
35//! answers from the wrong row source with no error anywhere. A scheme that fails silently at a
36//! reachable depth is not a smaller version of this one. The ceiling is a REFUSAL for the same
37//! reason: past it the engine says so.
38
39use crate::prefix::FRAMEWORK_LEAD;
40
41/// The framework's DEFAULT identifier namespace — the four characters a minted alias begins with
42/// where the declaration named no other, and the prefix `ingraph-derive` refuses a declared table or
43/// column name for taking wherever any database still defaults.
44///
45/// It is deliberately SHORT. An alias competes for the same sixty-three bytes an engine keeps of an
46/// identifier as the table name inside it does, so every character the prefix spends is a character
47/// the name it stands for loses before the clamp starts cutting — which is also the whole cost of
48/// spending a longer one through `alias(prefix = "…")`.
49///
50/// Pinned against `ingraph`'s own `ALIAS_PREFIX` and against `ingraph-derive`'s fence — three
51/// crates hold this string because the dependency edges do not let one of them hold it for the
52/// others, and each pair that CAN see both is a test.
53///
54/// It is also the mark [`EmissionPrefix::INGRAPH`](crate::prefix::EmissionPrefix::INGRAPH) is
55/// built from, so a platform's own namespace and this default are one type with one string behind
56/// the framework arm rather than two spellings that have to be kept level.
57pub const ALIAS_PREFIX: &str = "__ig";
58
59/// The ORDER-PRESERVING COMPANION COLUMN one `sortable` collection is mirrored into.
60///
61/// ```text
62/// tags → __ig_tags_sort__
63/// ```
64///
65/// **The ONE mint**, and three parties spell it from here: the order-by term that renders it, the
66/// write plan that fills it, and the descriptor that creates it. A companion is unlike an edge
67/// table, whose name every party DERIVES — it is a real column of a real table, so it is minted once
68/// and carried, which is the arrangement a provenance table's name already has.
69///
70/// # It is inside the SYNTHESIZED-COLUMN fence, and that is what makes it collision-proof
71///
72/// `__ig_` in front and `__` behind — the shape `ingraph`'s own `interface::KIND` states the law
73/// for, and one `ingraph-derive` refuses a DECLARED column for taking. So no record can spell this
74/// name, including one whose field is actually called `tags_sort`: that field's own companion is
75/// `__ig_tags_sort_sort__`, and neither is a name a declaration could have written.
76///
77/// The join is INJECTIVE for the same reason: the field is everything between a fixed prefix and a
78/// fixed suffix, so two fields cannot reach one companion.
79///
80/// It takes the column's EXTERNAL name — what `<db>(rename)` left it called in the database
81/// being emitted for — because the companion is a column of THAT table beside it.
82///
83/// # It takes the RESOLVED namespace, and that is a fix rather than a widening
84///
85/// `prefix` is the mark this DATABASE mints in — `<db>(alias(prefix = …))` where the declaration
86/// named one, the model's own [`EmissionPrefix`](crate::prefix::EmissionPrefix) where it did not.
87/// It is the caller's to resolve, exactly as [`alias`] takes it. Spelling the framework's own constant
88/// here instead was a real collision: a record that overrode the prefix on every database it names
89/// has had `__ig*` HANDED BACK by `ingraph-derive`'s fence and may declare a column called
90/// `__ig_tags_sort__`, which is precisely the name the companion for `tags` used to take.
91#[must_use]
92pub fn sort_column(prefix: &str, external: &str) -> String {
93 format!("{prefix}_{external}_sort__")
94}
95
96/// How deep a record's aliases are minted where its declaration names no number, and therefore how
97/// deep a relation over such a record may nest before the engine refuses.
98///
99/// # A DEFAULT rather than a wall, and the array is what the refusal reads
100///
101/// The aliases are emitted as a SLICE beside the row's address, so the length is a fact about one
102/// (record, database) pair rather than part of a trait item's type — and `ingraph`'s
103/// `RelationDepthError` carries that slice's own length. So a declaration whose filters nest deeper
104/// writes `<db>(alias(depth = 16))` and gets sixteen, refusing at sixteen and saying so,
105/// with no engine holding a second copy of the number.
106///
107/// Eight is chosen against what a relation predicate actually nests: each level is a subquery inside
108/// a subquery over the same statement, and a filter written by hand or generated from a wire query
109/// reaches two or three. The cost of the unused tail is eight `&'static str` per record per
110/// database, which is a pointer pair each in the binary's read-only data and nothing at all at
111/// runtime.
112///
113/// Past whatever was minted the lowering REFUSES, naming the table and both numbers — see
114/// `ingraph`'s `SqlLoweringError::RelationDepth`. Refusing is the whole point of having a number at
115/// all: the alternative to a depth is not "no limit" but a name reused at some depth nobody chose,
116/// which SQL resolves to the inner scope without complaining.
117pub const DEPTH_CEILING: usize = 8;
118
119/// The shallowest alias table this mint will write: one depth.
120///
121/// `depth = 0` is refused rather than accepted as the empty table, because an alias array with no
122/// depths aliases nothing — [`aliases`] would answer `[]`, and the emitted `ALIASES` would be a
123/// slice no index can be inside. Every value from one up is a real answer, `1` included: it mints
124/// the depth-zero entry the outermost `FROM` never wears and refuses every nested relation, which is
125/// *this row is never nested* stated in the one place that can hold it. Zero states nothing at all.
126const MINIMUM_DEPTH: usize = 1;
127
128/// The longest alias every shipped engine keeps WHOLE: PostgreSQL's sixty-three bytes, which is one
129/// below MySQL's sixty-four and unbounded on SQLite.
130///
131/// The LOWER of the two, because what an engine past its limit does is TRUNCATE rather than refuse.
132/// Two aliases differing only past the cut arrive at the server as one name, and the statement is
133/// then well-formed over a row source that is not the one it was built for — the same silent class
134/// [`ALIAS_PREFIX`] exists to close, reached by a different road.
135const ALIAS_CEILING: usize = 63;
136
137/// The hexadecimal digits a clamped name's digest is rendered in.
138const DIGEST_WIDTH: usize = 8;
139
140/// Every alias one table wears in one database, indexed by the depth of the scope wearing it.
141///
142/// `depth` is how many the declaration asked for — [`DEPTH_CEILING`] where it asked for nothing —
143/// and `prefix` the namespace they are minted in, [`ALIAS_PREFIX`] by the same rule. Both are the
144/// caller's to resolve, so this function has no defaulting of its own to disagree with anybody
145/// else's; [`refused`] is where the pair is held to what the mint can actually spend.
146///
147/// `ALIASES[0]` is minted like the rest and is never WORN: the outermost `FROM` names the real
148/// table, so depth zero has no alias to take. It is present because the array is indexed by depth
149/// and an array that started at depth one would need every use site to subtract, which is an
150/// arithmetic step each of them could get wrong and none of them could get caught at.
151pub fn aliases(prefix: &str, table: &str, depth: usize) -> Vec<String> {
152 (0..depth).map(|at| alias(prefix, table, at)).collect()
153}
154
155/// `<prefix>_<table>_<depth>__`, clamped to what every shipped engine stores whole.
156///
157/// # A long name is CLAMPED, and the clamp cannot re-collide two names
158///
159/// Past [`ALIAS_CEILING`] the prefix and the depth are the parts that must survive, so the TABLE is
160/// what gives way — and a plain truncation is exactly the silent re-collision the ceiling exists to
161/// avoid, since two tables sharing a long leading run would cut to one string. So a clamped name
162/// keeps what fits and ends in a digest of the WHOLE name, which differs wherever the names do.
163///
164/// # The budget is the PREFIX's to spend, which is why a declared one is bounded
165///
166/// Every byte the prefix takes is a byte the table loses before the clamp starts cutting, so a long
167/// enough prefix would leave nothing for the name to be recognisable by — and, further out, nothing
168/// for the digest either, which is subtraction below zero rather than a bad name. [`refused`] is
169/// what holds a declared prefix above that line, and it is checked where the declaration is read
170/// rather than here: this function is the mint, and a mint that answered a refusal would have two
171/// jobs.
172pub fn alias(prefix: &str, table: &str, depth: usize) -> String {
173 let digits = depth.to_string();
174 let budget = budget(prefix, digits.len());
175 let mut alias = String::with_capacity(ALIAS_CEILING);
176 alias.push_str(prefix);
177 alias.push('_');
178 if table.len() <= budget {
179 alias.push_str(table);
180 } else {
181 // Saturating rather than checked, and the floor is unreachable through a declaration: `refused`
182 // admits no pair leaving fewer than `DIGEST_WIDTH + 2` bytes here. What it buys is that this
183 // function stays TOTAL for a caller that reached it another way — a mint that panicked would do
184 // so inside an expansion, where the report is a compiler crash rather than a refusal.
185 let keep = budget.saturating_sub(DIGEST_WIDTH + 1);
186 alias.push_str(&table[..floor_char_boundary(table, keep)]);
187 alias.push('_');
188 alias.push_str(&digest(table));
189 }
190 alias.push('_');
191 alias.push_str(&digits);
192 alias.push_str("__");
193 alias
194}
195
196/// How many bytes of TABLE fit inside one alias: the ceiling, less the prefix, the depth's digits
197/// and the three separators plus the closing pair.
198///
199/// Saturating, because the caller that has not been through [`refused`] is the one asking whether a
200/// prefix fits at all — and the honest answer there is zero rather than a panic in a macro
201/// expansion, which is a compiler crash where a refusal was wanted.
202const fn budget(prefix: &str, digits: usize) -> usize {
203 ALIAS_CEILING.saturating_sub(prefix.len() + digits + 4)
204}
205
206/// Why this (prefix, depth) pair cannot be minted, or [`None`] where it can.
207///
208/// The RULE lives here rather than in `ingraph-derive` because the mint is here: the shapes a prefix
209/// must have are the shapes [`alias`] spends it in, and a second copy of them one crate over is the
210/// copy that drifts the day the mint's own shape moves. What the derive adds is the span — this
211/// answers in prose and knows nothing about tokens.
212///
213/// Both halves are already resolved: a caller passes what it will actually mint with, so a
214/// declaration that named only `depth` asks about [`ALIAS_PREFIX`] beside it and gets the same
215/// answer the emission will.
216#[must_use]
217pub fn refused(prefix: &str, depth: usize) -> Option<String> {
218 if depth < MINIMUM_DEPTH {
219 return Some(format!(
220 "`depth = {depth}` mints an alias array with no depths, which aliases nothing — every \
221 relation predicate over this row would refuse at depth one. `depth = 1` is the shallowest \
222 table that says something: it is *this row is never nested*"
223 ));
224 }
225 if prefix.is_empty() {
226 return Some(
227 "`prefix` names the namespace every alias over this row is minted in, and an empty one names \
228 none — the minted names would begin with the table's own, where a real table of that name \
229 resolves to the inner scope and the statement answers from the wrong row source"
230 .to_owned(),
231 );
232 }
233 if !prefix.starts_with(FRAMEWORK_LEAD) {
234 return Some(format!(
235 "`prefix = \"{prefix}\"` does not begin `{FRAMEWORK_LEAD}` — a prefix is FENCED as well as \
236 minted in, so every column and table name starting with it stops being declarable, and a \
237 bare word would confiscate a namespace this schema's own author is using. Lead with \
238 `{FRAMEWORK_LEAD}`, which is the shape a reader already reads as the framework's"
239 ));
240 }
241 if let Some(stray) = prefix.chars().find(|char| !legal_in_prefix(*char)) {
242 return Some(format!(
243 "`prefix = \"{prefix}\"` holds `{stray}`, which an alias cannot carry — a minted name is \
244 joined with `_` and read back by eye at a `FROM`, so the namespace is ASCII letters, digits \
245 and `_`. A dialect would quote anything, and what it cannot do is make it recognisable"
246 ));
247 }
248 // The DEEPEST entry is the one whose digits are widest, so a pair that fits there fits at every
249 // shallower depth — and a table clamped to nothing is a name that stands for no table.
250 let deepest = (depth - 1).to_string().len();
251 let budget = budget(prefix, deepest);
252 if budget < DIGEST_WIDTH + 2 {
253 return Some(format!(
254 "`prefix = \"{prefix}\"` with `depth = {depth}` leaves {budget} bytes for the table's own \
255 name, where a clamped one needs {needed} — the prefix, the depth and the digest that keeps \
256 two long tables apart all have to survive inside the {ALIAS_CEILING} bytes every shipped \
257 engine stores whole. Shorten the prefix",
258 needed = DIGEST_WIDTH + 2,
259 ));
260 }
261 None
262}
263
264/// Whether a character may appear in a declared prefix.
265///
266/// Shared with [`EmissionPrefix::refused`](crate::prefix::EmissionPrefix::refused), which holds a
267/// PLATFORM to the same alphabet a declaration is held to: both spend a mark as one identifier
268/// joined with `_`, so a rule either of them relaxed alone would admit a name the other could not
269/// spell.
270pub(crate) const fn legal_in_prefix(char: char) -> bool {
271 char.is_ascii_alphanumeric() || char == '_'
272}
273
274/// The largest index at or below `at` that does not split a character.
275///
276/// A ceiling is counted in BYTES — it is the engine's, and every one of them counts storage — while
277/// a cut inside a multi-byte character produces no string at all. `str::floor_char_boundary` says
278/// exactly this and is unstable, so it is written here rather than waited for.
279fn floor_char_boundary(name: &str, at: usize) -> usize {
280 let mut at = at.min(name.len());
281 while at > 0 && !name.is_char_boundary(at) {
282 at -= 1;
283 }
284 at
285}
286
287/// FNV-1a over the whole name, low thirty-two bits, lowercase hex — the tail that keeps two clamped
288/// names apart.
289///
290/// A hash rather than a counter, because the clamp has to be a pure function of the name it cuts:
291/// a table's alias is minted in one expansion and read by a statement built somewhere else, and the
292/// two share no state to count in.
293///
294/// FNV-1a rather than the standard hasher, which is seeded per process — an expansion is a build
295/// artefact, so a name that varied per compilation would spell one table two ways across two builds
296/// of the same source.
297fn digest(name: &str) -> String {
298 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
299 for byte in name.as_bytes() {
300 hash ^= u64::from(*byte);
301 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
302 }
303 #[expect(
304 clippy::cast_possible_truncation,
305 reason = "the low half is the digest"
306 )]
307 let folded = hash as u32;
308 format!("{folded:0>width$x}", width = DIGEST_WIDTH)
309}
310
311#[cfg(test)]
312mod tests;