ingraph_codegen/emit.rs
1//! Model in, tokens out.
2//!
3//! **Twenty-three AUTHORISED framework trait implementations, and no other.** The rule was *none of any
4//! kind*, because the framework's trait layer was moving and an expansion that named a half-settled
5//! trait would owe every consumer a revision the day it settled. That layer has settled for
6//! `ToDatabaseComparison`, the type-level map from a filter to the comparison it crosses into, so
7//! the rule lifted for that item; and the map's own ITEM BOUND — `Comparison: ComplexComparison<Db>`
8//! — then made the lowering the second, because an expansion that names the map has to keep the
9//! promise the map makes. INHERENT impls were never covered by the rule: they bind nothing in the
10//! framework and are stable whatever that layer becomes, so `new` and the accessors are emitted.
11//!
12//! `Transformer` is the third, and it settled differently from the other two: what it binds is
13//! entirely the emitter's OWN output. Its faces are the `*Key` written here, the `*Lineage` beside
14//! it and the record itself — no consumer type, no backend type, nothing this emission does not also
15//! declare or sit on. An expansion naming it therefore owes a revision to nobody the emission was
16//! not already going to move.
17//!
18//! `Record` is the fourth and stands on the third's ground: it is the settled VOCABULARY the entity
19//! binding's row-form member answers, and what an impl of it binds is the `<Row>Comparison` this
20//! emission also declares. It differs in one way that matters — its argument is a CONCRETE backend,
21//! the only one the emission names — and that is what makes it the storability audit and what makes
22//! it ride a gate. See [`DatabaseBackend::vocabulary`].
23//!
24//! `Related<Target>` and `Reference` are the fifth and sixth, admitted on the third's ground and
25//! on one more of their own: a relation is declared in TWO derives that cannot see each other, so
26//! the pairing is the only way a reverse declaration's audit can reach the forward one's fields.
27//! What they bind is the emission's own artifacts and the paths the declaration itself wrote. See
28//! [`relate`].
29//!
30//! `Identifiable` is the seventh and the eighth — the SAME trait twice, because it is admitted on
31//! two self types and the allowlist is a (trait, self type) pair rather than a trait. It is
32//! `Transformer`'s supertrait, so an expansion naming the entity binding has to name it or the
33//! binding is not well formed, and what it binds is the declared type of the key's last column: the
34//! third's ground, one member of it. One impl is on the RECORD and one on the `*Key` — the two types
35//! the emission gives that column to. See [`RecordModel::binding`].
36//!
37//! `KeySegments` is the ninth, and it is on the `*Key` — the second impl that type carries. What it
38//! binds is the third's ground again: the key written here, walked into a sink the framework owns,
39//! with nothing named that this emission did not also declare. It is the filesystem blob store's
40//! own key requirement, and it is emitted because the store's seam says so — that seam KEEPS the
41//! full key, since a directory tree nested by lineage is browsable where a flat one is not. The
42//! sentence in `ingraph`'s `store::fs` promising the derive emits it is what this makes true. See
43//! [`RecordModel::address_segments`].
44//!
45//! The ORDER is not a tenth impl. It was one — `Orderable` on the RECORD, with a condition of its
46//! own where the nine before it ride whatever condition already emitted the type they bind — and it
47//! is retired: the order is a MEMBER of the `Record<Db>` vocabulary now, so it rides that impl's
48//! condition and a record stored nowhere has neither the row, the comparison nor the order. See
49//! [`DatabaseBackend::vocabulary`], which is where all three are bound.
50//!
51//! `Implements<Interface>` is the fourteenth, on the RECORD, admitted on the fifth and sixth's
52//! ground alone: a membership is declared in two derives that cannot see each other, so the record's
53//! `implements(…)` is the only way an interface's expansion can know its member agreed. It carries
54//! nothing — a relation needs the referring fields crossing that boundary, and a membership needs
55//! only the fact — and what it binds is a path the declaration itself wrote. See [`relate`].
56//!
57//! `Graphql`, `GraphqlInput` and `GraphqlOutput` are the eleventh, twelfth and thirteenth, admitted
58//! on the third's ground and on the fifth and sixth's: the two halves' impls are on CARRIERS this
59//! emission mints, exactly as the pairing's are on artifacts it mints, and an expansion that writes
60//! the face has to write them or the face names types answering nothing. What they bind is the
61//! filter, the key output and the order-by this emission also declares. Conditional like the tenth,
62//! on the block's presence. See [`RecordModel::wire_binding`].
63//!
64//! The TOPOLOGY family is the fifteenth through nineteenth, and it stands on the third's ground with
65//! one addition of its own: `Emits<N>` and `SoleProduct` on the RECORD are how a node states what it
66//! puts on an edge, which is the ONE fact a downstream declaration cannot read for itself — the
67//! fifth and sixth's argument seen from the other end of the edge. `Products` and `ProductKind` are
68//! on the product sum and its vocabulary, and `Sink<Out>` is on the DOWNSTREAM: all three are types
69//! this emission declares, so what they bind is its own output. Conditional on `emits` naming
70//! several, exactly as the tenth is conditional on its block. See [`topology`].
71//!
72//! `Describe<Db>` is the TWENTY-THIRD, on the RECORD, and it stands on the fourth's ground with the
73//! fourth's own argument: the SCHEMA a migration creates this record's storage from, built out of
74//! what the row's `SqlQuery` binding already publishes — its address and its column shapes — with
75//! each field's `StoredAs<Db>` word and its nullability beside them. It names the backend
76//! CONCRETELY and rides that dialect's gate for `Record<Db>`'s reason, and it carries one condition
77//! of its own on top of the query face's: a collection this database keeps in a COLUMN has no word
78//! to be declared at, so that database gets no blueprint. See [`query`], where the roster is.
79//!
80//! `Declared` is the TWENTIETH, on the RECORD, and it is the only one on this list whose reason is
81//! a party OUTSIDE the declaration that emits it. What it binds is nothing at all — an effect, a
82//! lane, a table of upstreams, an options path and a shelf — but a graph root sees a field's TYPE
83//! and no more, so a node's own facts have to reach it as an impl or the root's entry can name none
84//! of them. It is the other side of the same wall the fifth and sixth cross, one organ up: those
85//! carry a fact between two node declarations, and this carries one from a node to the root that
86//! mounts it. See [`declared`].
87//!
88//! The line is not left to memory. `tests::the_emission_declares_only_the_authorised_trait_impl`
89//! reads the emission back and fails on any framework trait impl that is not
90//! `ToDatabaseComparison<Row, Db>` on the record's own filter, keyed on a row a declared database
91//! really stores, `ComplexComparison<Db>` on a comparison that same model names, `Transformer` on
92//! the record itself, `Record<Db>` on it keyed on a backend a declared database really is,
93//! `Related<Target>` on the record at a target the model's own `ref` names, `Reference` on an
94//! artifact the emitter mints for one of those fields, `Identifiable` on the record or on the
95//! `*Key` the model names, `KeySegments` on that same `*Key`, `Graphql` on the
96//! record, or `GraphqlInput`/`GraphqlOutput` on the carrier the emitter mints for each half — self
97//! type and argument both checked against the MODEL, so an authorised trait on the wrong type is
98//! refused exactly as a fourteenth would be. The walk OPENS the gates first, so wrapping an impl in
99//! one is not a way past the rule.
100//!
101//! **`TryFromFilter` is the one that stays absent HERE, and the reason is the DIALECT.** A record's
102//! comparison is generic in its database and stays that way, so the crossing would need a bound on
103//! `<F as ToDatabaseComparison<V, Db>>::Comparison` that no item bound carries — see
104//! [`DatabaseBackend::comparison_traits`] for what was measured, and why the LOWERING is reachable
105//! where the crossing is not.
106//!
107//! An INTERFACE's expansion writes it, and nothing about the wall moved: an interface's engine face
108//! is per database already — the row equations, `SqlInterface` and the hydration all name a concrete
109//! backend and ride its gate — so its crossing is stated at that backend, where every projection
110//! normalises and the bound is not owed. See `crate::interface::cross`. Whether a RECORD could be
111//! given the same treatment is a real question this does not answer: its comparison is generic on
112//! purpose, so the crossing would have to be per dialect where the type is not.
113//!
114//! ## What is emitted
115//!
116//! Three inherent impls at most: the `*Key`'s, the `*Lineage`'s, and the RECORD's own. The first
117//! two come with a struct each; the record already exists — the derive only adds methods to it.
118//!
119//! The record also gets its ENTITY BINDING — `impl Transformer for Record` — naming those two
120//! emitted types, the row form the declaration asked for and the wire face it declared, with
121//! `impl Identifiable` beside it on the record and on the `*Key`, each binding the id column's
122//! declared type. Every record has all three, a root included: a root has no `*Lineage` to name, so
123//! it binds `()`; a record that persists nowhere binds `()` for its row form; and a record with no
124//! `graphql(…)` block binds `()` for its wire face. The `*Lineage` is identified by nothing — a
125//! chain of ancestors has no one id.
126//!
127//! ONE CONDITIONAL binding rides beside that total one, and it is conditional because what it names
128//! is. An EXPOSED record gets `impl Graphql for Record` with a carrier per half — `<E>GraphqlInput`
129//! naming the filter and the order-by, `<E>GraphqlOutput` naming the key output — minted in the
130//! const on the relation artifacts' terms. The STORED half of the pair this used to describe is no
131//! longer a binding of its own: a stored record's order rides its `Record<Db>` impl. A record
132//! meeting neither condition implements neither, which is what a
133//! projection through the missing impl refuses on.
134//!
135//! The `*Key` gets one more of its own: `impl KeySegments`, walking its columns into a path, root
136//! first and the id last. That is the address the local filesystem blob store nests directories by,
137//! and it is emitted for every declaration rather than for the ones that store bytes — see
138//! [`RecordModel::address_segments`] for why, and for the vocabulary bound it lands under.
139//!
140//! A declaration stating RELATIONS gets more, all of it inside the same const: one id equation per
141//! `ref` field, one pairing per target it names, an artifact per referring field, and one audit per
142//! `derived(…)` position. [`relate`] carries the whole of that story.
143//!
144//! Each emitted type also gets a PAIR of conversions from the record: `From<Record>`, which moves
145//! its columns out, and `From<&Record>`, which clones them. Two rather than one because the choice
146//! is the caller's and should be visible at the call site — `TrackAddress::from(track)` gives the
147//! record up, `TrackAddress::from(&track)` pays for a clone and keeps it. Neither can be `const`;
148//! a trait method cannot be. They need no bound of their own: the emitted struct derives `Clone`,
149//! so its column types are `Clone` by construction.
150//!
151//! **No constructor on the record.** A real aggregate has twenty-odd fields, so a positional `new`
152//! would be unusable and transposition-prone; and the product schema hand-writes VALIDATING
153//! constructors (`try_new` rejecting nil ids) that a macro cannot replicate from a declaration.
154//! The application keeps its own constructor; this emits accessors and mutators only.
155//!
156//! A declaration that WRAPS a foreign type gets one family more, and two of the above change their
157//! bodies rather than their shape: the reference family and the two conversions over the wrapped
158//! type, and readers and a raise that go through that type's own accessors and constructor. All of
159//! it is `crate::remote`'s, including why none of it lands on this list — the family is `core`'s
160//! traits over a type the declaration names, and the allowlist above is about the FRAMEWORK's.
161//!
162//! ## The shape of an emitted type, and why
163//!
164//! **Private fields, with accessors.** A key is a value type with a construction path, not a
165//! transparent carrier whose representation is the API.
166//!
167//! **One `new`, positional, in key order** — lineage root-first, then the id. A key has exactly
168//! one unsurprising way to be built, so there are no named constructors and no builder: a builder
169//! guards invariants, and a key has none — every combination of ids is a valid address, whether or
170//! not a row lives at it. No `Default` either; a default key is a nil address. `new` is `const`
171//! for every column shape, because moving a value into a struct drops nothing.
172//!
173//! **The mutators are the repository's pair**: `set_x(&mut self, T) -> &mut Self` to change one in
174//! place and chain, `with_x(mut self, T) -> Self` to derive a neighbouring key from this one.
175//! `with_*` carries `#[must_use]` — it returns the change rather than applying it, so dropping the
176//! result is always a mistake. There is no `clear_*` and no `*_mut`: a key's columns are all
177//! required, and handing out `&mut` to one would let a caller mutate a live map key in place.
178//!
179//! Both take `T` rather than `impl Into<T>`. A `const fn` cannot call `Into::into`, so an
180//! `Into`-taking setter could not be `const` for a marked column — and splitting the signature by
181//! markedness would make the two forms differ in more than constness, which is the one axis the
182//! marker is meant to control. This is a deliberate divergence from the hand-written style in the
183//! product schema.
184//!
185//! ## How a field is handed out
186//!
187//! The projections are the product schema's, reproduced rather than invented (`mediaschema`
188//! `video/facet.rs`, `media.rs`):
189//!
190//! | field type | accessor | schema |
191//! |---|---|---|
192//! | `#[ingraph(repeated)]` | `x_slice(&self) -> &[<T as Repeated>::Item]` | `video/facet.rs:115` |
193//! | `#[ingraph(optional)]` | `x_ref(&self) -> Option<&<T as Optional>::Item>` | `media.rs:197` |
194//! | unmarked | `x_ref(&self) -> &T` | `video/facet.rs:121` |
195//! | `#[ingraph(copy)]` | `x(&self) -> T`, IN ADDITION to the borrow | `video/facet.rs:110` |
196//!
197//! A many-valued or optional field gets the PROJECTED shape — `&[T]` and `Option<&T>` — rather
198//! than `&Vec<T>` and `&Option<T>`, because those are what a caller can use without a second step.
199//!
200//! The projection is chosen by the declaration's MARKER, and the field's declared type is written
201//! verbatim into a trait qualification: `&[<Ids as Repeated>::Item]`. Nothing pattern-matches the
202//! type's spelling, so a type ALIAS projects exactly as the type it names would.
203//!
204//! That is a bug fix, not a preference. The emitter used to match `Vec<…>`/`Option<…>` on the
205//! written type, and a field declared `files: Ids` was silently handed back as `&Ids` with nothing
206//! to catch it. A macro sees tokens, not resolved types — so the resolution is left to the
207//! compiler, which has the type.
208//!
209//! Nothing is INFERRED either: an unmarked field takes the plain borrow. Removing a marker changes
210//! an accessor's shape, and that should be a visible source change rather than a silent one.
211//!
212//! A marked accessor is NOT `const`: it calls a trait method, and const trait methods are
213//! unstable. The plain and `copy` accessors, which touch no trait, stay `const`.
214//!
215//! ## `copy`, and what the marker changes
216//!
217//! Every column gets `x_ref(&self) -> &T`. A column marked `copy` gets `x(&self) -> T` **as well**,
218//! and its mutators become `const`.
219//!
220//! The marker is ADDITIVE, which is the point: adding it adds `x()`, removing it removes `x()`, and
221//! neither renames anything — so toggling `copy` on a column never breaks a caller that was
222//! borrowing it through `x_ref()`. A shape where the bare name switched between a copy and a borrow
223//! would rename the accessor at every call site instead.
224//!
225//! It also makes the NAME state the return shape uniformly: `x()` is always a copy and `x_ref()`
226//! always a borrow, whatever the column's type. The accessor convention's default is not to demand
227//! `_ref` for every borrow, and this departs from it deliberately — a reader of generated code
228//! cannot see the emission to check, so predictability outranks terseness here, and additivity is
229//! what it buys.
230//!
231//! The CONSTNESS asymmetry is the marker's whole reason. `set_x` assigns over the column's previous
232//! value and therefore drops it; a `const` destructor is unstable, so an unmarked column's mutators
233//! cannot be `const`. A `Copy` value drops nothing, so a marked column's can. The product schema
234//! already draws exactly this line by hand — a `u32` setter is `const fn`, a `Vec<Id>` setter is
235//! not — and the marker automates it.
236//!
237//! Whether a type really is `Copy` is NOT checkable here: a model carries names and types, not
238//! trait implementations. A wrongly marked column produces an emission that does not compile,
239//! reported at the generated accessor as "cannot move out of `self.x`", which names the column.
240//!
241//! ## Every `std` name an expansion writes is QUALIFIED
242//!
243//! An expansion lands in a module the framework does not control, and a bare path resolves THERE. A
244//! user with their own `trait Debug` in scope would capture `#[derive(Debug)]` on every emitted
245//! type at once, and a `struct Option` would break every projected accessor — with an error inside
246//! generated code the author cannot edit.
247//!
248//! The anonymous const does **not** help. It scopes `use` statements; it does not change how a bare
249//! path in the enclosing module resolves. So every `std` item an expansion writes is spelled at its
250//! real path — `::core::fmt::Debug`, `::core::option::Option`, `::core::convert::From` — derive
251//! macros included, which accept a path exactly as a trait bound does.
252//!
253//! Not left to habit: `fixtures::shadowed` declares its own `Debug`, `Clone`, `Option`, `Result`
254//! and the rest, and derives the whole shape inside that module. If any bare path survived, that
255//! module would not compile.
256//!
257//! ## Where the impls sit
258//!
259//! Every emitted impl goes inside ONE anonymous `const _: () = { … };` per record — serde's
260//! hygiene shape. The block is a scope, so the `use` statements the impl era will need (the
261//! framework traits, reached through the model's `krate` path) can sit beside the impls without
262//! leaking a single name into the caller's namespace. Today it holds only the inherent impls; the
263//! imports arrive with the traits.
264//!
265//! The STRUCTS stay at top level — they are the API. Inherent impls inside the block remain fully
266//! reachable from another crate, `const` contexts included (verified cross-crate), so nothing about
267//! `Key::new(7)`, `.id()` or `.id_ref()` changes for a caller.
268//!
269//! Note for whoever reads the emission back: an impl-walking check that looks only at
270//! `syn::File::items` finds NOTHING now and passes vacuously. `tests::impls` descends into the
271//! block, and `tests::the_impl_walk_descends_into_the_const_wrapper` pins that it does.
272//!
273//! **No `#[automatically_derived]`.** It is valid on TRAIT impls only — on an inherent impl this
274//! toolchain warns "can only be applied to trait impl blocks … will become a hard error in a
275//! future release". The current emission has no trait impl, so the attribute has no valid subject
276//! and nothing is emitted. It belongs on each emitted trait impl, and lands with impl-era emission.
277//!
278//! ## `#[inline]`, not `#[inline(always)]`
279//!
280//! Every emitted method carries `#[inline]`. These are one-line cross-crate wrappers, which is the
281//! case the repository's `rust-type-conventions` reference names for plain `#[inline]`, and it
282//! records that `#[inline(always)]` is NOT a house default. The product schema writes
283//! `#[inline(always)]` by hand throughout (`mediaschema` `video/facet.rs:109`, `:114`, `:120`).
284//!
285//! The divergence is deliberate, with both citations here so that neither side is "fixed" into the
286//! other by someone who has only read one of them.
287//!
288//! **Not `#[non_exhaustive]`** — a decision, not an oversight. Nothing outside would be able to
289//! call `new`.
290//!
291//! **Not `Ord`, not `Copy`.** `Ord` waits for a consumer; sorted output and `BTreeMap` keys are
292//! the case that will want it, and neither exists yet. `Copy` cannot be decided here at all — the
293//! field types come from the declaration, a macro cannot know whether they are `Copy`, and a
294//! derive cannot be conditional.
295
296mod cross;
297mod graphql;
298mod mongo;
299mod queries;
300mod query;
301mod relate;
302mod sql;
303pub(crate) mod wire;
304
305pub(crate) use graphql::upper_camel;
306use quote::{format_ident, quote, quote_spanned};
307
308mod channel;
309mod declared;
310mod grant;
311mod poll;
312mod topology;
313
314/// The BATCHING seam's emission half — the single leg's two lanes, and the five bounds an id owes.
315/// Beside the emitters it reads, for the reason the three suites below are.
316#[cfg(test)]
317mod batching_tests;
318/// The `indexed` word's own emission suite — the builder a collection's edge table carries, and the
319/// two shapes that get nothing. Beside `sortable_tests`, which is the sibling word's.
320#[cfg(test)]
321mod indexed_tests;
322/// The `sortable` word's CURSOR half — the slot a companion joins and the arm that reads it back.
323/// Beside the suite above, which is the same word's write half.
324#[cfg(test)]
325mod shadow_cursor_tests;
326/// The `sortable` word's own emission suite — the write plan's companion entry and the term that
327/// renders it. Beside the emitters it reads, for the reason the suite below is.
328#[cfg(test)]
329mod sortable_tests;
330/// The `tracing(level = …)` word's own emission suite — the level const and the instrumented query
331/// entries. Beside the emitters it reads rather than in `crate::tests`, which keeps the ROSTERS.
332#[cfg(test)]
333mod tracing_tests;
334
335pub use topology::PAIRED;
336
337use crate::{
338 method,
339 model::{
340 Column, Conversion, Crossing, DatabaseBackend, DatabaseKind, Kind, PersistColumn, Projection,
341 RecordModel, Shape, Upstreams, fanned_lineage, fanned_lineage_column, one_storage_marker,
342 },
343};
344
345/// What one database FAMILY answers differently about a row.
346///
347/// Four questions and no more, which is the measure of how much the two families really differ:
348/// what the row derives, what those derives need said at the container, how a column's external
349/// name reaches the field that holds it, and what to call the thing in a doc comment. Everything
350/// else about a row — its fields, its accessors, its conversions — is the same on both sides and is
351/// assembled once, in [`DatabaseBackend::row`].
352struct Family {
353 /// The derive list, verbatim.
354 derives: proc_macro2::TokenStream,
355 /// What the derives need told at the CONTAINER — empty for a family whose derives need nothing.
356 /// Mongo's is `#[serde(crate = "…")]`, which is half of reaching serde through the shelf.
357 attrs: proc_macro2::TokenStream,
358 /// The module EVERY field of this family's row crosses, for a derive that would otherwise demand a
359 /// foreign trait OF A DECLARED FIELD TYPE.
360 ///
361 /// Mongo's is `…::query::mongo::via`, spelled as the string a `#[serde(with = "…")]` takes. [`None`]
362 /// for a family whose derives ask nothing of a field type — which the SQL family's do not, its
363 /// decode being emitted rather than derived.
364 ///
365 /// # ONE path for every column, which is what keeps this emitter from reading a type's SPELLING
366 ///
367 /// The module's two functions are generic over the field's own type and answer through this
368 /// crate's per-type document tables, so WHICH row runs is the compiler's answer to the tokens the
369 /// declaration wrote. A per-type `with` path — one module for a pattern, another for everything
370 /// else — would have had to match `Regex` in the tokens, which is the one thing `graphql`'s own
371 /// `written_option` note says this emitter does not do outside the one seat that names it.
372 via: Option<String>,
373 /// How a column's external name is bound to the field that carries it.
374 mapping: Mapping,
375 /// The database's name, for a doc comment.
376 what: fn(DatabaseKind) -> &'static str,
377 /// What the emitted type IS: a "row", or a "document".
378 noun: &'static str,
379}
380
381/// How a family binds a stored column's EXTERNAL name to the Rust field that holds it.
382///
383/// # It was two ALTERNATIVES, and the second backend's read lane made it three
384///
385/// A family either hands the mapping to a vendored derive through a field attribute, or writes the
386/// decode itself and spells each column's name at the read that fetches it — and the choice was not
387/// a preference, it followed whether the vendored derive can be TOLD where the framework keeps its
388/// crate. serde's can, so [`mongo`] shelved the derive; sqlx's cannot, so [`sql`] writes the
389/// `FromRow` impl and the attribute disappeared with the derive that was its only reader.
390///
391/// [`AttributeAndDecode`](Self::AttributeAndDecode) is the case that argument did not cover: a
392/// family whose derive CAN be shelved and whose DECODE is refused anyway. Nothing about a
393/// `Serialize` erases a typed refusal — there is none to erase — but a `Deserialize` refuses through
394/// `serde::de::Error::custom`, which takes a `Display` and hands back the FORMAT's error, so every
395/// declared refusal would reach a caller as a `bson::de::Error` carrying a string and the
396/// `mongo(try_into(error = "…"))` cell would hold nothing. So the write side keeps the
397/// derive and the read side is emitted.
398///
399/// # It puts the external name in TWO places, and that is the cost
400///
401/// A `#[serde(rename = "…")]` and a read under the same string are two spellings of one fact, which
402/// is exactly what this enum's original note said not to do. What holds them together is that both
403/// come from [`DatabaseBackend::external`] — ONE function, called twice — so the two cannot differ
404/// without that function changing, and `tests::the_mongo_document_reads_the_id_out_of_underscore_id`
405/// is what reads them back beside each other.
406enum Mapping {
407 /// The attribute a shelved derive reads the name from — mongo's `#[serde(rename = "…")]`, or its
408 /// `flatten` where the column has no key of its own.
409 ///
410 /// No family uses it ALONE today, and it stays a variant of its own rather than being folded into
411 /// the pair below: it is the shape a family with a shelvable derive on BOTH sides takes, which is
412 /// what mongo was before the read lane and what a future format with a redirectable decode would
413 /// be again.
414 #[allow(dead_code)]
415 Attribute(&'static str),
416 /// The decode the family emits ITSELF, naming each column at the read that fetches it.
417 Decode(fn(&DatabaseBackend, &RecordModel) -> proc_macro2::TokenStream),
418 /// BOTH — the attribute for the derive that survives, and the decode for the direction that could
419 /// not be left to one.
420 AttributeAndDecode(
421 &'static str,
422 fn(&DatabaseBackend, &RecordModel) -> proc_macro2::TokenStream,
423 ),
424}
425
426/// One conversion, in whichever of the two shapes its fallibility calls for.
427///
428/// **One shape or the other, never both.** `core` carries `impl<T, U: Into<T>> TryFrom<U> for T`, so
429/// an emitted `From` ALREADY yields the `TryFrom` — writing both is `E0119`, and writing the
430/// fallible one where the infallible would do costs a caller nothing, since `try_into()` resolves
431/// either way.
432fn conversion(
433 from: proc_macro2::TokenStream,
434 into: &syn::Ident,
435 binding: &syn::Ident,
436 body: proc_macro2::TokenStream,
437 error: Option<&proc_macro2::TokenStream>,
438 doc: &str,
439) -> proc_macro2::TokenStream {
440 let doc = leading(doc);
441 if let Some(error) = error {
442 return quote! {
443 #[automatically_derived]
444 impl ::core::convert::TryFrom<#from> for #into {
445 type Error = #error;
446
447 #[doc = #doc]
448 #[inline]
449 fn try_from(#binding: #from) -> ::core::result::Result<Self, Self::Error> {
450 ::core::result::Result::Ok(#body)
451 }
452 }
453 };
454 }
455 quote! {
456 #[automatically_derived]
457 impl ::core::convert::From<#from> for #into {
458 #[doc = #doc]
459 #[inline]
460 fn from(#binding: #from) -> Self {
461 #body
462 }
463 }
464 }
465}
466
467/// The leading space a `///` comment desugars to, so an expansion a human reads back looks like
468/// the hand-written code it stands in for.
469pub(crate) fn leading(doc: &str) -> String {
470 format!(" {doc}")
471}
472
473/// A generic TYPE parameter an expansion introduces, under a name a declaration cannot collide
474/// with.
475///
476/// A proc macro has no hygiene for types. `Span::mixed_site` covers local bindings and `$crate`;
477/// a type or a path still resolves at the CALL SITE, so a parameter spelled `Db` shadows a
478/// declaration's own `Db` inside every item that declares it. What follows is silent rather than
479/// loud: `<Db as DefaultMarker>::Marker` in a field's type then names the parameter, the crossing
480/// the struct assumes makes it well formed anyway, and the emitted crossing resolves for no
481/// database at all — with nothing reported at the declaration.
482///
483/// `__NAME__` is the namespace the framework already reserves: `ingraph-derive` refuses a COLUMN
484/// whose name has `__` at both ends, so one rule covers a parameter shadowing a type and a column
485/// colliding with the framework's own.
486///
487/// Every parameter emitted code introduces takes this shape. LIFETIMES do not, and need not: the
488/// derive refuses a generic declaration outright, so no lifetime of a declarer's is ever in scope
489/// where an emitted `'a` or `'q` is bound, and a lifetime cannot shadow a type in any case.
490/// The shelf path to one framework item, from a crate root rather than from a model.
491///
492/// The RULE lives at [`RecordModel::framework`], which is the reader every emission goes through
493/// and where the `__private` law is written down. This is the same assembly with the root spelled,
494/// for the emissions whose owner is not a record — a column's accessor family reaches the
495/// projection traits and does not know what declared it.
496pub(crate) fn framework(
497 krate: &syn::Path,
498 module: &[&str],
499 name: &str,
500) -> proc_macro2::TokenStream {
501 let module = module.iter().map(|segment| format_ident!("{segment}"));
502 let name = format_ident!("{name}");
503 quote!(#krate::__private #(:: #module)* :: #name)
504}
505
506/// The shelf path to a whole VENDORED crate, from a crate root rather than from a model — the free
507/// twin of [`RecordModel::vendored`], which is where the rule is written down.
508/// A published TYPE name as a root FIELD names it: the same word with a lower-case initial.
509///
510/// GraphQL's own convention, and the one rename a root field performs. It is NOT
511/// [`wire::wire_member`]'s camelCase, which turns a snake-cased Rust member into a camel-cased
512/// field: what arrives here is already a type name in upper camel case, and lowering its initial is
513/// the whole transformation. A declared `output(rename = "…")` or `plural = "…"` therefore reaches
514/// the field verbatim but for that initial.
515///
516/// In `emit` rather than beside one front end's legs, because BOTH root-field emitters spend it —
517/// a record's trio and an interface's list leg — and one word resolved twice is one word two
518/// answers can disagree about.
519pub(crate) fn lower_initial(published: &str) -> String {
520 let mut characters = published.chars();
521 match characters.next() {
522 Some(first) => first.to_lowercase().chain(characters).collect(),
523 None => published.to_owned(),
524 }
525}
526
527/// The same word as a TYPE name spells it: an upper-case initial, and not one other letter touched.
528///
529/// [`lower_initial`]'s exact inverse, written the same way for the same reason — so
530/// `plural = "Corpora"` and `plural = "corpora"` reach ONE field and ONE pair of page names,
531/// whichever way a declaration wrote the word.
532///
533/// `heck`'s `UpperCamelCase` is what this is NOT, and the difference is not cosmetic: it re-cases
534/// the WHOLE word, so a `plural = "IPTCRecords"` would reach a schema as `IptcRecords`.
535/// `wire::wire_type` states the law this obeys — a name a declaration chose is a name it chose, and
536/// no convention of this emitter may move it — and raising one initial is the least this position
537/// can do while still handing GraphQL a type name.
538pub(crate) fn raise_initial(published: &str) -> String {
539 let mut characters = published.chars();
540 match characters.next() {
541 Some(first) => first.to_uppercase().chain(characters).collect(),
542 None => published.to_owned(),
543 }
544}
545
546/// A declared type's name in snake case — what an emitted function ident is built from before the
547/// `__async_graphql_` prefix.
548///
549/// The RUST side only. What a client reads is written out per item, so this never reaches a schema
550/// and a rename of the published type moves the field without moving the ident.
551/// Every token in a stream, moved to one span.
552///
553/// The origin layer's respanning, generalised from an ident to a path: a `where` predicate is
554/// reported at the span its tokens carry, and a predicate whose trait path came from the emitter
555/// would report a broken hop at the macro. Only the REPORT moves — resolution is unaffected, the
556/// span being a real one from the file the declaration is in.
557///
558/// Here rather than in one emitter, because the tower's head pin and the recipe's BINDING are the
559/// same move at two grains: both mint a projection out of a declaration's own words and both have to
560/// report it at the word rather than at the attribute.
561pub(crate) fn respan(
562 tokens: proc_macro2::TokenStream,
563 at: proc_macro2::Span,
564) -> proc_macro2::TokenStream {
565 tokens
566 .into_iter()
567 .map(|token| match token {
568 proc_macro2::TokenTree::Group(group) => {
569 let mut respanned = proc_macro2::Group::new(group.delimiter(), respan(group.stream(), at));
570 respanned.set_span(at);
571 proc_macro2::TokenTree::Group(respanned)
572 }
573 mut other => {
574 other.set_span(at);
575 other
576 }
577 })
578 .collect()
579}
580
581pub(crate) fn snake(name: &str) -> String {
582 use heck::ToSnakeCase as _;
583
584 name.to_snake_case()
585}
586
587/// THE ROOT FAMILY'S NAME, read off the root key's own TYPE.
588///
589/// `MediaId` is the family `media`, `TrackId` is `track`, and `u64` is `u64`. The rule is the type's
590/// last path segment, snake-cased, with one trailing `Id` taken off — which is what makes the two
591/// records that share a root agree without either of them saying so: a `Keyframe` whose lineage root
592/// is `MediaId` and the `Media` whose own id is `MediaId` are ONE family, exactly as
593/// [`Registry`](../ingraph/struct.Registry.html) already makes them one table.
594///
595/// Reading the TYPE rather than the column name is what makes that true. A column name is scoped and
596/// renameable — one record may call its root step `media` and another `owner` — while the type is
597/// the same fact the registry keys its tables by, so a name derived from it cannot disagree with the
598/// table it names.
599///
600/// A root whose type is not a path — a tuple, a reference — has no name to read and answers the
601/// empty string, which the registry already means *unnamed, read the defaults*.
602pub(crate) fn family(ty: &syn::Type) -> String {
603 let syn::Type::Path(path) = ty else {
604 return String::new();
605 };
606 let Some(last) = path.path.segments.last() else {
607 return String::new();
608 };
609 let name = last.ident.to_string();
610 let stem = name.strip_suffix("Id").filter(|rest| !rest.is_empty());
611 snake(stem.unwrap_or(&name))
612}
613
614/// The POSITIONS a list occupies once the compiler has answered its members' predicates — one
615/// `const` per member, each the previous plus that member's own presence.
616///
617/// # A count is not a thing a macro may know
618///
619/// Every ordinal an emission writes into a `#[cfg]`-carrying list is an index into a list the
620/// predicates CONTRACT: an array element is a legal attribute position, so a build that removes the
621/// second entry makes the third's position `1`. An expansion that had written `2` there would name a
622/// position that build has not got — and a macro cannot evaluate a predicate, so it cannot write the
623/// right literal either.
624///
625/// What it CAN write is the arithmetic. `1` or `0` per member is a `const` the compiler folds after
626/// stripping (see [`Condition::present`](crate::model::Condition::present)), the running sum of them
627/// is the position, and a `const` is a legal pattern — so one expansion serves every configuration
628/// and K conditional members cost K constants rather than 2ᴷ expansions.
629///
630/// A list with NO conditional member gets the literals back and no constants at all, which is what
631/// keeps an ordinary declaration's expansion identical to the one before this seat existed.
632///
633/// `declared` is one entry per member, in the list's own order — the [`Condition`] it was declared
634/// under, or [`None`] for a member no condition seat covers. It lives here rather than beside either
635/// caller because a record's row and a fragment's segment list ask one question, and two copies of a
636/// running sum is how one of them starts at the wrong index.
637///
638/// [`Condition`]: crate::model::Condition
639pub(crate) fn positions(
640 declared: &[Option<&crate::model::Condition>],
641) -> (proc_macro2::TokenStream, Vec<proc_macro2::TokenStream>) {
642 if declared
643 .iter()
644 .all(|condition| condition.is_none_or(crate::model::Condition::always_present))
645 {
646 return (
647 proc_macro2::TokenStream::new(),
648 (0..declared.len()).map(|at| quote!(#at)).collect(),
649 );
650 }
651 let names: Vec<syn::Ident> = (0..declared.len())
652 .map(|at| format_ident!("__INGRAPH_AT_{at}"))
653 .collect();
654 let mut places = proc_macro2::TokenStream::new();
655 for (at, name) in names.iter().enumerate() {
656 let place = match at.checked_sub(1) {
657 None => quote!(0usize),
658 Some(before) => {
659 let previous = &names[before];
660 let term =
661 declared[before].map_or_else(|| quote!(1usize), crate::model::Condition::present);
662 quote!(#previous + #term)
663 }
664 };
665 places.extend(quote!(const #name: ::core::primitive::usize = #place;));
666 }
667 (places, names.iter().map(|name| quote!(#name)).collect())
668}
669
670pub(crate) fn vendored(krate: &syn::Path, name: &str) -> String {
671 let name = format_ident!("{name}");
672 quote!(#krate::__private::#name)
673 .to_string()
674 .replace(' ', "")
675}
676
677/// WHICH of a reading's two filters a door is asking for — the 2026-08-22 *each face tells its own
678/// truth* ruling, read at the one seam that spells a filter type.
679///
680/// A composite's predicate depends on the host kind: a row-holding host may compare only what it
681/// stores, and a rowless one asks about the whole value. Every other reading answers both with one
682/// type, so a door that picked the wrong face would be invisible until a fragment activated for both
683/// kinds arrived — which is why the fact is a PARAMETER here rather than a default anywhere.
684///
685/// The rule at a call site is mechanical rather than a judgement: a filter that is projected into a
686/// `ToDatabaseComparison` takes [`FilterFace::Column`], that row existing on the stored face alone.
687/// Everything else takes [`FilterFace::Full`].
688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
689pub(crate) enum FilterFace {
690 /// What a ROWLESS host publishes: every field the value declares.
691 Full,
692 /// What a ROW-HOLDING host publishes: the columns the value is actually stored in.
693 Column,
694}
695
696impl FilterFace {
697 /// The associated type this face resolves through on `ToGraphqlFilter`.
698 fn item(self) -> syn::Ident {
699 match self {
700 Self::Full => format_ident!("Filter"),
701 Self::Column => format_ident!("ColumnFilter"),
702 }
703 }
704}
705
706/// The FILTER one declared position is asked for by: the WORD's own marker where one was written,
707/// and the type's own registry row where none was.
708///
709/// # Two declarations, one routing
710///
711/// A record's field and an interface's PIN both carry an interpretation word now, and the filter
712/// KIND is what the word decides — `list(scalar)` over a `Vec<u64>` resolves to the sequence filter
713/// whatever that type's own row says, and a field naming nothing takes the row. Written once here so
714/// the two front ends cannot come to route differently: a filter asked for twice is a filter two
715/// answers can disagree about, and between those two there is no conversion.
716///
717/// `face` says WHICH of the reading's two filters — see [`FilterFace`] — and it rides the same
718/// routing for the same reason: two doors asking about one field must not come to ask different
719/// questions of it.
720///
721/// `krate` rather than a model, for [`Marker::resolved`](crate::model::Marker)'s reason.
722pub(crate) fn filter_of(
723 krate: &syn::Path,
724 ty: &syn::Type,
725 marker: Option<&crate::model::Marker>,
726 face: FilterFace,
727) -> proc_macro2::TokenStream {
728 let to_filter = framework(krate, &["graphql"], "ToGraphqlFilter");
729 let item = face.item();
730 let Some(marker) = marker else {
731 let inferred = framework(krate, &["marker"], "DefaultMarker");
732 return quote!(<<#ty as #inferred>::Marker as #to_filter>::#item);
733 };
734 let resolved = marker.resolved(krate, ty);
735 quote!(<#resolved as #to_filter>::#item)
736}
737
738pub(super) fn parameter(name: &str) -> syn::Ident {
739 format_ident!("__INGRAPH_{name}__")
740}
741
742/// What a WIDE emitted signature carries — the sites whose parameter count the emitter cannot
743/// reduce without giving up the shape.
744///
745/// Two kinds, and the second is why this is not called `wide_constructor` any more:
746///
747/// - the POSITIONAL constructors, whose arity is the DECLARATION's — an address type's `new`, which
748/// takes a key's or a lineage path's columns, and a comparison's, which takes one predicate per
749/// stored column;
750/// - the emitted LIST RESOLVER, whose arity is the EMITTER's own and is eight: a context, an order,
751/// four page arguments and a predicate. Nothing there is a column, and the count is fixed for
752/// every record that has the leg at all.
753///
754/// `clippy::too_many_arguments` warns above seven, so either kind makes the DECLARING crate fail its
755/// own `-D warnings` build — reported at `#[ingraph::record(…)]`, inside an expansion its author
756/// cannot edit. A real aggregate reaches eight columns routinely and the list leg reaches eight
757/// always, so the attribute rides every one of these rather than being chosen by a count here: an
758/// emitter that counted would have clippy's threshold written into it, and a consumer may configure
759/// that threshold to anything.
760///
761/// `allow` rather than `expect`, and the difference is load-bearing: an unfulfilled `expect` is
762/// itself a warning, so `expect` would fail every declaration NARROWER than the threshold — which
763/// is most of them. An `allow` over code no lint fires on costs nothing.
764pub(crate) fn wide_signature() -> proc_macro2::TokenStream {
765 quote!(#[allow(clippy::too_many_arguments)])
766}
767
768/// The visibility an emitted type's MEMBERS carry — layer 1 of the three-layer naming law.
769///
770/// `pub(crate)` and never `pub`, and never private either, because the member is a SUBSTRATE rather
771/// than a face:
772///
773/// - **not private**, because emitted-to-emitted reads spend the FIELD. A crossing, a row equation,
774/// a gather and an audit each read a member of a type some OTHER expansion wrote, and an expansion
775/// lands where its declaration is written — so two declarations in two modules of one crate have
776/// to be able to see each other's members. Private is visible to the declaring module and its
777/// descendants alone, which makes that a fact about where an author happened to put a `mod`.
778/// - **not `pub`**, because a member is not API. What a downstream crate is offered is the ACCESSOR
779/// face beside it, which is the layer a rename word may move; publishing the representation would
780/// make every field name a compatibility promise and leave the accessors decorative.
781///
782/// One spelling in one place, because a visibility written at each emission site is a visibility
783/// that can be written differently at one of them.
784pub(crate) fn substrate() -> proc_macro2::TokenStream {
785 quote!(pub(crate))
786}
787
788impl RecordModel {
789 /// A record's key type, plus its lineage type when it has a lineage.
790 ///
791 /// The key is FLAT — `lineage ⊕ id`, root-first, one struct with no nesting — because every use of
792 /// it is columnar: a row's key columns, a prefix range scan, a leading-column attribution.
793 ///
794 /// A root record gets NO lineage type. An empty path has no type worth naming, and its absence is
795 /// what tells a reader the record is a root.
796 ///
797 /// Both names come from the MODEL. Whether they are the convention's or an author's rename was
798 /// settled before this point, so there is exactly one place a name can be decided.
799 pub fn emit(&self) -> proc_macro2::TokenStream {
800 let record = &self.record;
801 let (key_doc, new_doc) = match self.lineage {
802 Some(_) => (
803 format!("The address of a [`{record}`] row: its lineage path followed by its own id."),
804 "Construct an address from its lineage path and the row's own id.".to_owned(),
805 ),
806 None => (
807 format!("The address of a [`{record}`] row: its own id."),
808 "Construct an address from the row's own id.".to_owned(),
809 ),
810 };
811 let (key_type, key_impl) = self.address_type(
812 &self.key.name,
813 &key_doc,
814 &new_doc,
815 self.key.columns(),
816 Some(&self.key.id),
817 );
818 let key_from = self.address_conversions(&self.key.name, self.key.columns());
819 let (lineage_type, lineage_impl, lineage_from) = match self
820 .lineage
821 .as_ref()
822 .map(|lineage| (lineage, &lineage.shape))
823 {
824 Some((lineage, Shape::Path(columns))) => {
825 let (declaration, methods) = self.address_type(
826 &lineage.name,
827 &format!("The path from the root to a [`{record}`] row, root-first."),
828 "Construct a path from its steps, root-first.",
829 columns.iter(),
830 None,
831 );
832 (
833 Some(declaration),
834 Some(methods),
835 Some(self.address_conversions(&lineage.name, columns.iter())),
836 )
837 }
838 Some((lineage, Shape::Kinds(kinds))) => {
839 let (declaration, conversions) = self.lineage_kinds(&lineage.name, kinds);
840 (Some(declaration), None, Some(conversions))
841 }
842 None => (None, None, None),
843 };
844 let storage_marker = self.storage_marker();
845 let (topology_types, topology_impls) = self.topology();
846 let declared = self.declared();
847 // The `receipt` word's SIBLING impl, and `None` on every declaration that wrote no word — see
848 // [`receipts`](RecordModel::receipts) for why it is not a member of the facts trait.
849 let receipts = self.receipts();
850 let (poll_types, poll_impls) = self.poll_face();
851 let (grant_types, grant_impls) = self.polling_face();
852 let (channel_types, channel_impls) = self.channel_face();
853 let subscription = self.subscription();
854 let goodbye = self.goodbye();
855 let face = self.face();
856 let key_parent = self.key_parent();
857 // THE ROOT PROJECTION, on EVERY record: a key is root-first, so every declaration has a root
858 // and every one of them gets the impl that names it — see `root_projection`.
859 let root_projection = self.root_projection();
860 let record_impl = self.methods();
861 let binding = self.binding();
862 let wire_binding = self.wire_binding();
863 let hydration_binding = self.hydration_binding();
864 let address_segments = self.address_segments();
865 let relations = self.relations();
866 let (row_types, row_impls) = self.rows();
867 let (wire_types, wire_impls) = self
868 .graphql
869 .as_ref()
870 .map_or_else(Default::default, |graphql| graphql.faces(self));
871 // The BINDING, behind the binding gate: what makes an emitted type a SCHEMA type rather than a
872 // structure. It joins the anonymous const because every item in it is an impl — see [`wire`],
873 // where the split from the shapes is stated, and where the one face that ships today is.
874 let wire = self.wire();
875 let queries_type = self.queries_type();
876 // THE REWRITE's two blocks, empty on every ordinary declaration: the bridge every manifest read
877 // crosses, and the reference family that makes a wrapper usable where the wrapped type was.
878 let remote_prelude = self.remote_prelude();
879 let remote_family = self.remote_family();
880 quote! {
881 #key_type
882 #lineage_type
883 #row_types
884 #wire_types
885 #queries_type
886 #topology_types
887 #poll_types
888 #grant_types
889 #channel_types
890
891 #storage_marker
892
893 const _: () = {
894 #remote_prelude
895 #remote_family
896 #key_impl
897 #lineage_impl
898 #record_impl
899 #binding
900 #wire_binding
901 #hydration_binding
902 #address_segments
903 #relations
904 #key_from
905 #lineage_from
906 #row_impls
907 #wire_impls
908 #wire
909 #subscription
910 #topology_impls
911 #declared
912 #receipts
913 #root_projection
914 #poll_impls
915 #grant_impls
916 #channel_impls
917 #goodbye
918 #face
919 #key_parent
920 };
921 }
922 }
923
924 /// The GOODBYE audit — what the `teardown` word buys at the declaration.
925 ///
926 /// The word enrols the constructed value in the shutdown's chain, and the chain is the LAUNCH's
927 /// to walk: nothing about it can be emitted here, because the value does not exist until a
928 /// deployment builds one. What CAN be said here is the thing an author would otherwise learn at
929 /// start-up — that the type has a goodbye at all — so the expansion states the bound, and a
930 /// declaration that opted in without an impl is `E0277` at its own name.
931 ///
932 /// It is [`subscription`](Self::subscription)'s shape for the same reason: the monomorphised
933 /// function item is what discharges the bound, an initialiser is where naming it is legal, and
934 /// neither leaks a name into the declarer's scope.
935 fn goodbye(&self) -> Option<proc_macro2::TokenStream> {
936 if !self.teardown {
937 return None;
938 }
939 let record = &self.record;
940 let teardown = self.framework(&["drive"], "AsyncTeardown");
941 Some(quote! {
942 const _: () = {
943 fn __ig_says_goodbye<__INGRAPH_NODE__: #teardown>() {}
944 const _: fn() = __ig_says_goodbye::<#record>;
945 };
946 })
947 }
948
949 /// The FACE audit — what the `async` and `stream` words buy at the declaration, and where a
950 /// mismatch lands.
951 ///
952 /// A word is a CLAIM about the body, so the expansion checks it: an `async` declaration whose type
953 /// carries the blocking `Operator` instead is `E0277`, WITH THE CARET ON THE WORD. That span is
954 /// the point of keeping the path rather than a `bool` — [`goodbye`](Self::goodbye) blames the
955 /// whole attribute because `teardown` collapses to a `bool` before it gets here, and this one has
956 /// somewhere better to point.
957 ///
958 /// # TWO AXES, four cells, one audit
959 ///
960 /// `stream` picks the PAIR and `async` picks the HALF, so the trait this demands is the cell the
961 /// two words select together:
962 ///
963 /// | words | the face the bound demands |
964 /// |---|---|
965 /// | *(none)* | nothing is demanded — see below |
966 /// | `async` | `AsyncOperator` |
967 /// | `stream` | `StreamOperator` |
968 /// | `stream, async` | `AsyncStreamOperator` |
969 /// | `autonomous` | `AutonomousOperator` |
970 /// | `autonomous, async` | `AsyncAutonomousOperator` |
971 ///
972 /// `stream` and `autonomous` are values of ONE axis and the grammar refuses them together, so the
973 /// two halves of the table never compete: what multiplies is the MODE word, which cuts across
974 /// both.
975 ///
976 /// The CARET goes on `async` where it was written and on `stream` otherwise, which is the same
977 /// rule read twice: blame the word that names the half a reader has to change, and where only the
978 /// pair was written the pair's word is that word.
979 ///
980 /// A BARE declaration emits nothing, and that asymmetry is deliberate rather than a gap: a
981 /// declaration is not required to have an operator impl at all — a great many exist only to be
982 /// expanded — so demanding one of every silent node would refuse the ordinary case. What catches
983 /// a bare declaration over an awaited body is the LAUNCH, whose per-node bound is spelled through
984 /// the same const the mode word sets: `Driven<Selected<{ … }>>` is `Driven<Block>` there, and an
985 /// `AsyncOperator`-only type does not satisfy it.
986 ///
987 /// A `stream` declaration is never bare in that sense — the word IS a claim — so the streaming
988 /// rows are audited at both halves and a `stream` node with no streaming face at all is refused
989 /// here rather than at whatever first tried to mount it. An `autonomous` one is a claim in
990 /// exactly the same way and is audited exactly the same way.
991 fn face(&self) -> Option<proc_macro2::TokenStream> {
992 // The `async` word where it was written, and the `stream` word where it was the only one: the
993 // caret sits on the half a reader changes, and the pair's word is that half where no mode word
994 // was written.
995 let word = self
996 .asynchronous
997 .as_ref()
998 .or(self.streaming.as_ref())
999 .or(self.autonomous.as_ref())?;
1000 let named = match (
1001 self.streaming.is_some(),
1002 self.autonomous.is_some(),
1003 self.asynchronous.is_some(),
1004 ) {
1005 (true, _, true) => "AsyncStreamOperator",
1006 (true, _, false) => "StreamOperator",
1007 (false, true, true) => "AsyncAutonomousOperator",
1008 (false, true, false) => "AutonomousOperator",
1009 // `(false, false, false)` is unreachable: `word` above is `None` there and this function has
1010 // already returned. The pair words are refused together by the grammar, so the first two arms
1011 // never compete with the second two.
1012 (false, false, _) => "AsyncOperator",
1013 };
1014 let operator = self.framework(&["operator"], named);
1015 // The NODE's name, respanned onto the word — and only it. The bound's own tokens stay at the
1016 // call site, because a generic parameter carrying a user span is linted as if the author had
1017 // written its name (`non_camel_case_types` on `__INGRAPH_NODE__`, at the word). Respanning the
1018 // instantiated type instead moves the E0277's primary span without moving anything a lint reads.
1019 let mut node = self.record.clone();
1020 node.set_span(syn::spanned::Spanned::span(word));
1021 Some(quote! {
1022 const _: () = {
1023 fn __ig_awaits<__INGRAPH_NODE__: #operator>() {}
1024 const _: fn() = __ig_awaits::<#node>;
1025 };
1026 })
1027 }
1028
1029 /// The ONE-STORAGE MARKER, for a node that holds a storage — see [`one_storage_marker`] for the
1030 /// collision it exists to make.
1031 ///
1032 /// It is emitted at MODULE SCOPE and cannot be anywhere else: each derive writes its own
1033 /// `const _: () = { … }`, so two markers placed inside two of those would be two items in two
1034 /// distinct scopes, colliding with nothing. The whole mechanism is one scope holding one name
1035 /// twice.
1036 ///
1037 /// An [`Operator`](crate::model::NodeKind::Operator) emits none, and the absence is the same
1038 /// shape the rest of this model uses for a thing it does not have: a node with no storage has no
1039 /// second storage to refuse.
1040 fn storage_marker(&self) -> Option<proc_macro2::TokenStream> {
1041 self.kind.stores().then(|| {
1042 let marker = one_storage_marker(&self.prefix, &self.record);
1043 quote! {
1044 #[doc(hidden)]
1045 #[allow(dead_code, non_upper_case_globals)]
1046 const #marker: () = ();
1047 }
1048 })
1049 }
1050
1051 /// The SUBSCRIPTION audit — every upstream this node names, emitted so that the compiler resolves
1052 /// it.
1053 ///
1054 /// One path where `subscribe = "path::To::Upstream"` was written, and one per `upstream(…)` entry
1055 /// where the node fuses several. Both spellings reach the same audit because the claim is the
1056 /// same one: this path names a node.
1057 ///
1058 /// The derive resolves nothing here and could not: the upstream is another declaration's, and two
1059 /// derives cannot see each other. What it can do is put the path where rustc will read it, under a
1060 /// bound that says what a subscribe target has to BE — so a path naming nothing is `E0412` and a
1061 /// path naming something that is not a node is `E0277`, both at the string the author wrote.
1062 ///
1063 /// The bound is [`Transformer`], and the choice is worth naming rather than assuming: the design
1064 /// record's own table writes the refusal as *missing `Node` impl*, and no `Node` trait exists. The
1065 /// entity binding is what every node derive emits and nothing else does, so *implements
1066 /// `Transformer`* is what *is a node* means in the shipped crate. A `Node` trait arriving later
1067 /// moves one path in this function.
1068 ///
1069 /// A `const` item inside the anonymous const rather than a statement: the monomorphised function
1070 /// item is what discharges the bound, an initialiser is where naming it is legal, and neither
1071 /// leaks a name into the declarer's scope.
1072 fn subscription(&self) -> Option<proc_macro2::TokenStream> {
1073 let upstreams: Vec<&syn::Path> = self
1074 .subscribe
1075 .iter()
1076 .chain(self.upstreams.iter().flat_map(Upstreams::upstreams))
1077 .collect();
1078 if upstreams.is_empty() {
1079 return None;
1080 }
1081 let transformer = self.framework(&["transform"], "Transformer");
1082 Some(quote! {
1083 const _: () = {
1084 fn __ig_subscribes_to<__INGRAPH_UPSTREAM__: #transformer>() {}
1085 #(const _: fn() = __ig_subscribes_to::<#upstreams>;)*
1086 };
1087 })
1088 }
1089
1090 /// A lineage that is a CHOICE: the enum, and the two conversions off the record.
1091 ///
1092 /// ```text
1093 /// pub enum CaptionLineage {
1094 /// Frame(<media::Frame as Transformer>::Key),
1095 /// Segment(<asr::Segment as Transformer>::Key),
1096 /// }
1097 /// ```
1098 ///
1099 /// One variant per upstream, each carrying that upstream's WHOLE key — so a row's ancestry is
1100 /// exactly the address of the message it came from, with nothing restated and nothing to keep in
1101 /// step. The payload is a PROJECTION rather than a named type for the reason every upstream
1102 /// reference in this crate is: two expansions cannot see each other, so the compiler resolves it
1103 /// at the string the declaration wrote, and a path naming something that is not a node is `E0277`
1104 /// there.
1105 ///
1106 /// # No constructor, no accessors, and that is the shape rather than an omission
1107 ///
1108 /// An enum is built by naming a variant and read by matching on one. A `new` would have to pick a
1109 /// variant for its caller, and an accessor family would be a fallible read of a value that may not
1110 /// be there — both of which the language already spells better. What IS emitted beside it is the
1111 /// pair of conversions off the record, so a caller reaches a row's ancestry the same way it
1112 /// reaches a path's.
1113 fn lineage_kinds(
1114 &self,
1115 name: &syn::Ident,
1116 kinds: &[Kind],
1117 ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
1118 let record = &self.record;
1119 let vis = &self.vis;
1120 let injected = fanned_lineage(&self.prefix);
1121 let transformer = self.framework(&["transform"], "Transformer");
1122 let doc = leading(&format!(
1123 "Which upstream a [`{record}`] row descends from, and that message's own address."
1124 ));
1125 let variants = kinds.iter().map(|kind| {
1126 let (variant, node) = (&kind.variant, &kind.node);
1127 let doc = leading(&format!("Descended from a `{variant}` message."));
1128 quote! {
1129 #[doc = #doc]
1130 #variant(<#node as #transformer>::Key),
1131 }
1132 });
1133 let declaration = quote! {
1134 #[doc = #doc]
1135 #[derive(
1136 ::core::fmt::Debug,
1137 ::core::clone::Clone,
1138 ::core::cmp::PartialEq,
1139 ::core::cmp::Eq,
1140 ::core::hash::Hash
1141 )]
1142 #vis enum #name {
1143 #(#variants)*
1144 }
1145 };
1146 let conversions = quote! {
1147 #[automatically_derived]
1148 impl ::core::convert::From<#record> for #name {
1149 #[inline]
1150 fn from(record: #record) -> Self {
1151 record.#injected
1152 }
1153 }
1154
1155 #[automatically_derived]
1156 impl<'a> ::core::convert::From<&'a #record> for #name {
1157 #[inline]
1158 fn from(record: &'a #record) -> Self {
1159 ::core::clone::Clone::clone(&record.#injected)
1160 }
1161 }
1162 };
1163 (declaration, conversions)
1164 }
1165
1166 /// The KEY-PARENT EQUATION — *this node's lineage IS the designated parent's key*, written as the
1167 /// one thing the compiler can check it as: a function from that key to this lineage.
1168 ///
1169 /// ```text
1170 /// const _: fn(<Parent as Transformer>::Key) -> CaptionLineage =
1171 /// |k| CaptionLineage { media: k.media, frame: k.id };
1172 /// ```
1173 ///
1174 /// A STRUCT LITERAL and not a cast, because a literal is what makes each half of the claim fail
1175 /// separately and by name: a parent that renamed a key column is `E0609` naming the field that is
1176 /// gone, a column whose type drifted is `E0308` naming that column, and a lineage column with no
1177 /// mapping at all is `E0063`. Every one of them lands at the declaration that wrote the mapping.
1178 ///
1179 /// # Why a fusion DECLARES its mirror and a derived index is INJECTED with one
1180 ///
1181 /// The boundary is *indexes inject, records declare*, and it is about who reads the columns. A
1182 /// derived index's key has one consumer — the engine addressing its documents — so a carried field
1183 /// the expansion mints is the whole of what anyone needs, and the declaration is spared writing
1184 /// it. A fusing node's lineage columns are first-class query surface: filters name them, order
1185 /// tails end in them, cursors carry them and foreign keys point at them. A column a user's query
1186 /// spells is a column that user's declaration must have spelled.
1187 ///
1188 /// # The parent's id collides with this node's, and the rename is the feature
1189 ///
1190 /// A parent's key ends in ITS id, so a child mirroring the whole key would want a column called
1191 /// `id` — which the child's own `#[ingraph(id)]` field already is. The collision is refused where
1192 /// every field-name collision is, at the declaration, and the way out is a DOMAIN name for what
1193 /// the column means here: a caption's parent frame is `frame`, mapped with `frame(source = "id")`.
1194 /// The grammar forces a reader of the child's table to be told which id each column holds.
1195 fn key_parent(&self) -> Option<proc_macro2::TokenStream> {
1196 let fusion = self.upstreams.as_ref()?.fused()?;
1197 let lineage = &self.lineage.as_ref()?.name;
1198 let parent = &fusion.parent;
1199 let transformer = self.framework(&["transform"], "Transformer");
1200 // Each read is spanned AT THE MAPPING — the `source = "…"` string where one was written, and the
1201 // name inside `fields(…)` where the two agree. That is what decides where the type half of the
1202 // claim is reported: without it the whole expression is `call_site`, and a column whose type
1203 // drifted underlines the macro invocation instead of the mapping the author can edit.
1204 let mirrors = fusion.mirrors.iter().map(|mirror| {
1205 let (column, from) = (&mirror.column, &mirror.from);
1206 let read = quote_spanned!(from.span() => __ingraph_key.#from);
1207 quote!(#column: #read,)
1208 });
1209 Some(quote! {
1210 const _: fn(<#parent as #transformer>::Key) -> #lineage = |__ingraph_key| #lineage {
1211 #(#mirrors)*
1212 };
1213 })
1214 }
1215
1216 /// **THE ROOT PROJECTION**: which root key a record of this type descends from, as the
1217 /// [`Attributes`](crate::drive) impl the root-key registry reads it through.
1218 ///
1219 /// ```text
1220 /// impl Attributes<Keyframe> for RootProjection<Keyframe> {
1221 /// const FAMILY: &'static str = "media";
1222 /// type Root = MediaId;
1223 /// fn root(&self, record: &Keyframe) -> MediaId { Clone::clone(&record.media) }
1224 /// fn observe(&self, _: &MediaId, _: &NodeName, _: &Arrival) {}
1225 /// }
1226 /// ```
1227 ///
1228 /// # The root is the key's FIRST column, and that is derived rather than declared
1229 ///
1230 /// A declared key is `lineage ⊕ id`, flat and ROOT-FIRST, so the root of a record is its leading
1231 /// lineage step — and, for a record with no lineage at all, its own id. Nothing is written for it
1232 /// and nothing could be: a declared root would be a second statement about a fact the key already
1233 /// carries, and two statements can disagree.
1234 ///
1235 /// # Why the impl is on a FRAMEWORK type and not on the record
1236 ///
1237 /// [`Attributes`] is implemented BY THE ATTRIBUTION, for the output type — the projection is a
1238 /// hook a node wires, not a method a record has — so an impl of it needs a self type. Writing one
1239 /// on the record would mean *a record attributes things*, which is not what a record is;
1240 /// `RootProjection<T>` is the framework's own zero-sized seat for exactly this, and the impl is
1241 /// legal in a declaring crate because its self type carries that crate's own record.
1242 ///
1243 /// # EVERY record gets one, and that is the point
1244 ///
1245 /// Unlike [`receipts`](Self::receipts), this is not opt-in. A record's root is not something a
1246 /// declaration chooses to have — it has one the moment it has a key — so there is no word to
1247 /// write, no silence to interpret, and no declaration that could be surprised by acquiring it.
1248 ///
1249 /// # What INSTALLS it, and why that is a different question
1250 ///
1251 /// The impl makes the projection SPELLABLE; what puts one on a node is the `attributed` word, one
1252 /// module over in [`declared_attribution`](RecordModel::declared_attribution). The two are
1253 /// separate because they answer different questions: a record HAS a root the moment it has a key,
1254 /// and whether a NODE attributes its outputs to one depends on what that node emits — which may
1255 /// be somebody else's record, or a `String`.
1256 ///
1257 /// It could not have been the GRAPH root's expansion, and that is the wall this pair is shaped
1258 /// around: a root sees a node's output only as a type it can name and cannot ask whether that type
1259 /// is a declared record at all, so an unconditional install written there would refuse to compile
1260 /// for every node emitting a `String` or a `u64`. The seat crosses that wall, `()` is what the
1261 /// silent declaration puts in it, and the walk installs whatever it finds.
1262 fn root_projection(&self) -> proc_macro2::TokenStream {
1263 let record = &self.record;
1264 let root = self
1265 .key
1266 .columns()
1267 .next()
1268 .expect("a key always has its id, so it always has a first column");
1269 let ty = &root.ty;
1270 let family = family(ty);
1271 let attributes = self.framework(&["drive"], "Attributes");
1272 let projection = self.framework(&["drive"], "RootProjection");
1273 let node_name = self.framework(&["drive"], "NodeName");
1274 let arrival = self.framework(&["drive"], "Arrival");
1275 let binding = format_ident!("record");
1276 let source = &root.source;
1277 // A REWRITE reads through the wrapped type's accessors, exactly as its key conversion does —
1278 // there is no field to reach on a wrapper.
1279 let read = if self.remote.is_some() {
1280 self.remote_read(&binding, source)
1281 } else {
1282 quote!(::core::clone::Clone::clone(&record.#source))
1283 };
1284 let doc = leading(&format!(
1285 "Which root key a [`{record}`] descends from — its key's FIRST column, which is the \
1286 `{source}` field. The root-key registry tables one machine per family, and this is what \
1287 tells it which family a record of this type belongs to."
1288 ));
1289 let family_doc = leading(
1290 "This root family's own name, read off the root type rather than off a column name so that \
1291 every record sharing a root agrees on it without saying so.",
1292 );
1293 quote! {
1294 #[automatically_derived]
1295 impl #attributes<#record> for #projection<#record> {
1296 #[doc = #family_doc]
1297 const FAMILY: &'static str = #family;
1298
1299 #[doc = #doc]
1300 type Root = #ty;
1301
1302 #[inline]
1303 fn root(&self, record: &#record) -> Self::Root {
1304 #read
1305 }
1306
1307 // THE EMPTY PROGRAM, and it is the honest state of this seat rather than a stub: what an
1308 // observation is COUNTED into is the resident's own registries handle, which the projection
1309 // does not hold and is not the party to join.
1310 #[inline]
1311 fn observe(&self, _root: &Self::Root, _worker: &#node_name, _arrival: &#arrival) {}
1312 }
1313 }
1314 }
1315
1316 /// One row per declared database, split the way [`RecordModel::emit`] places them: the structs are
1317 /// the API and stay at top level, the impls join the record's anonymous const.
1318 ///
1319 /// A record with no `persist(…)` emits nothing here, and that is the whole of the check — a
1320 /// pure-compute record is `None` on the model rather than an empty list to walk.
1321 fn rows(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
1322 let mut types = proc_macro2::TokenStream::new();
1323 let mut impls = proc_macro2::TokenStream::new();
1324 for database in self.persist.iter().flat_map(|persist| &persist.backends) {
1325 let (declaration, methods) = database.row(self);
1326 types.extend(declaration);
1327 impls.extend(methods);
1328 // The comparison rides beside the row, always: it is the storage form of a PREDICATE, and a
1329 // programmatic query needs one whether or not the record has a wire face. Only the conversion
1330 // FROM a filter depends on `graphql(…)` being declared.
1331 let (declaration, methods) = database.comparison(self);
1332 types.extend(declaration);
1333 impls.extend(methods);
1334 impls.extend(database.comparison_traits(self));
1335 // The CROSSING beside the map, and gated where the map is not: it names the backend
1336 // concretely, so it rides the dialect's own gate and exists per DECLARED ∩ COMPILED-IN
1337 // database. See `emit::cross` for why a concrete backend is what makes it writable at all.
1338 impls.extend(database.filter_crossing(self));
1339 impls.extend(database.vocabulary(self));
1340 impls.extend(database.column_fence(self));
1341 }
1342 // The ORDER-BY, once per record and beside the comparisons: its content is mechanical from the
1343 // stored columns and its lowering is pure SQL, so nothing about it is a wire fact — see
1344 // [`RecordModel::ordering`] for the gap that closes.
1345 let (order_type, order_impls) = self.ordering();
1346 types.extend(order_type);
1347 impls.extend(order_impls);
1348 let (query_types, query_impls) = self.query();
1349 types.extend(query_types);
1350 impls.extend(query_impls);
1351 (types, impls)
1352 }
1353
1354 /// The RECORD's own inherent impl: an accessor family for every field it declares, and mutators
1355 /// for the ones that do not bear identity.
1356 ///
1357 /// No constructor — see the module doc.
1358 fn methods(&self) -> proc_macro2::TokenStream {
1359 // A REWRITE's fields are a MANIFEST rather than storage, so its readers are the remote's own
1360 // accessors crossed by `Into` — a different family, written where that mode is written.
1361 if self.remote.is_some() {
1362 return self.remote_methods();
1363 }
1364 let record = &self.record;
1365 let families = self.fields.iter().map(|field| {
1366 // The CONDITION, on the reader family of the field that wrote it: the echoed field really
1367 // disappears under the predicate, so an ungated accessor would be `E0609` on a field that is
1368 // not there. See [`Condition`](crate::model::Condition).
1369 field.column.methods(
1370 &self.vis,
1371 &self.krate,
1372 &format!("`{}` field of this [`{record}`]", field.column.name),
1373 !field.identity,
1374 &field.condition.gate(),
1375 )
1376 });
1377 quote! {
1378 impl #record {
1379 #(#families)*
1380 }
1381 }
1382 }
1383
1384 /// The record's ENTITY BINDING: `Transformer`, tying the record to the types this emission
1385 /// already declares and to the row form the declaration asked for — with `Identifiable`, its
1386 /// supertrait, on the two types that carry the id.
1387 ///
1388 /// Every face is the emitter's OWN output or the declaration's own type, which is what makes
1389 /// naming these traits different from naming a still-moving one. `Key` is the `*Key` struct
1390 /// written above, `Lineage` the `*Lineage` beside it, `Id` the declared type of the key's last
1391 /// column, carried through verbatim — so an alias stays an alias, as it does everywhere else here
1392 /// — and `Record` the record itself.
1393 ///
1394 /// TWO `Identifiable` impls, and they are the trait's whole reason for existing separately: the
1395 /// RECORD borrows the id out of its own column, and the `*Key` borrows it out of the last step of
1396 /// the address. Same type both times, read from two places — which is why the id is the supertrait
1397 /// rather than a member of the entity set, since a key is no entity.
1398 ///
1399 /// The `*Lineage` gets NONE. A path from the root is a chain of ancestors' ids and no single one
1400 /// of them addresses the row, so there is nothing for the member to bind.
1401 ///
1402 /// A ROOT binds `()` for its lineage. The model has no [`Lineage`](crate::model::Lineage) for one
1403 /// and this emits no type for it, so there is nothing named to bind; the empty product is what an
1404 /// empty path is.
1405 ///
1406 /// A record that persists NOWHERE binds `()` for its row form, by the same argument one level
1407 /// over: it becomes no row, and the empty product is what becoming nothing is. The model is the
1408 /// check — a pure-compute record is `None` there rather than an empty list of databases, which is
1409 /// exactly what [`rows`](Self::rows) reads — so the binding and the rows cannot disagree about
1410 /// whether a declaration is stored.
1411 ///
1412 /// A record with NO `graphql(…)` block binds `()` for its wire face, by the same argument again,
1413 /// and a record with one binds `Self` — the [`wire_binding`](Self::wire_binding) beside this is
1414 /// where the face's own types are written, and the record is what carries them, so a bundle type
1415 /// named here would be a second name for the record. The predicate is `graphql.is_some()`, which
1416 /// is the same one [`Graphql::faces`] emits those types under.
1417 ///
1418 /// Neither QUERY FACE is a member of this set. The filter rides the wire face above; the ORDER
1419 /// rides [`DatabaseBackend::vocabulary`], an impl written under a DIFFERENT predicate — the
1420 /// record persists in that database. A declaration meeting one condition and not the other is
1421 /// what makes them two, and this is where that shows: a persist-only declaration gets a real
1422 /// order on its `Record<Db>` beside a `Graphql` of `()`.
1423 ///
1424 /// `key` is the borrowing conversion, which [`address_conversions`](Self::address_conversions)
1425 /// has already emitted: a key is built from the record's columns, and `From<&Record>` is that
1426 /// build. Writing the field reads by hand would be the same body twice, and the two would drift
1427 /// the first time a scoped rename moved a column.
1428 ///
1429 /// `id_ref` cannot borrow through that conversion and does not try: the field reads are ONE
1430 /// expression each, and the two sites read different structs — the record's own field on one side,
1431 /// the key's column on the other. Both names come from the model's id column, so a scoped rename
1432 /// moves them together.
1433 ///
1434 /// # The ID's FIVE BOUNDS are instantiated here, and that is the ruling's *强制*
1435 ///
1436 /// *id有这些属性应该是必须的* — `Hash + Eq + Clone + Send + Sync`. The obligation rides
1437 /// [`ids_are_keys`](../../../ingraph/fn.ids_are_keys.html) as `const _: fn() = …::<Id>;`, the
1438 /// same shape [`relate`](super::relate)'s forward equation takes, and it is emitted UNCONDITIONALLY
1439 /// — beside the impl that names the id rather than beside the batching seam that first wanted
1440 /// them, because a mandate conditional on a consumer is not a mandate. A record that persists
1441 /// nowhere, publishes no wire face and is never batched still owes them, and finds out at its own
1442 /// `id` field.
1443 ///
1444 /// It costs the corpus nothing: the sealed id vocabulary satisfies all five, measured before the
1445 /// rule was written. What it buys is that the FIRST declaration whose id would not answer is
1446 /// refused where it is written.
1447 fn binding(&self) -> proc_macro2::TokenStream {
1448 let record = &self.record;
1449 let key = &self.key.name;
1450 let id = &self.key.id.ty;
1451 let field = &self.key.id.source;
1452 let column = &self.key.id.name;
1453 let lineage = match &self.lineage {
1454 Some(lineage) => {
1455 let name = &lineage.name;
1456 quote!(#name)
1457 }
1458 None => quote!(()),
1459 };
1460 let row = if self.persist.is_some() {
1461 quote!(Self)
1462 } else {
1463 quote!(())
1464 };
1465 let wire = if self.graphql.is_some() {
1466 quote!(Self)
1467 } else {
1468 quote!(())
1469 };
1470 let transformer = self.framework(&["transform"], "Transformer");
1471 let identifiable = self.framework(&["transform"], "Identifiable");
1472 // THE FIVE BOUNDS, instantiated at the declaration — see [`Self::binding`]'s note. Beside the
1473 // impl that NAMES the id rather than in a family of its own, so the obligation and the type it
1474 // is about are one item apart.
1475 let keyable = self.framework(&["transform"], "ids_are_keys");
1476 // A REWRITE has no field to borrow out of: the id is behind the wrapped type's own accessor,
1477 // which this seat requires to hand it back BY REFERENCE. See [`crate::remote`].
1478 let id_read = if self.remote.is_some() {
1479 self.remote_id_ref()
1480 } else {
1481 quote!(&self.#field)
1482 };
1483 quote! {
1484 const _: fn() = #keyable::<#id>;
1485
1486 #[automatically_derived]
1487 impl #identifiable for #record {
1488 type Id = #id;
1489
1490 #[inline]
1491 fn id_ref(&self) -> &#id {
1492 #id_read
1493 }
1494 }
1495
1496 #[automatically_derived]
1497 impl #transformer for #record {
1498 type Key = #key;
1499 type Lineage = #lineage;
1500 type Record = #row;
1501 type Graphql = #wire;
1502
1503 #[inline]
1504 fn key(&self) -> #key {
1505 <#key as ::core::convert::From<&#record>>::from(self)
1506 }
1507 }
1508
1509 #[automatically_derived]
1510 impl #identifiable for #key {
1511 type Id = #id;
1512
1513 #[inline]
1514 fn id_ref(&self) -> &#id {
1515 &self.#column
1516 }
1517 }
1518 }
1519 }
1520
1521 /// The record's WIRE FACE: `Graphql` on the record, and the two carriers its halves are — NOTHING
1522 /// at all where the declaration wrote no `graphql(…)` block.
1523 ///
1524 /// The predicate is the block's presence, which is what [`Graphql::faces`] emits the three wire
1525 /// types under, so no impl here can name a type this emission never wrote.
1526 ///
1527 /// # The halves used to be CARRIERS, and they are the OBJECTS now
1528 ///
1529 /// A face's half is a BUNDLE, so binding one to a NEIGHBOURING wire type would have made that
1530 /// type the namespace for its siblings: `Input = <E>Filter` reads *the filter's filter is itself*.
1531 /// What that argument never required was that the bundle be EMPTY — and both halves have their own
1532 /// content now, so each names its siblings from a type that is one of the things it is about. The
1533 /// output object HAS a key; the argument object HAS a filter and an order.
1534 ///
1535 /// With content they are API, so they leave the anonymous const for the top level, take the
1536 /// RECORD's visibility — an associated type binding on a public record's impl is public interface
1537 /// and anything less visible is `E0446` — and join
1538 /// [`emitted_types`](RecordModel::emitted_types), which is what the collision rule reads. That
1539 /// last is a real change: an author who wrote a `<E>GraphqlInput` of their own was not refused
1540 /// while the carrier hid in the const, and is now, because the name lands in their scope.
1541 ///
1542 /// [`Graphql::faces`] writes both types; this writes only what BINDS them, which is why the two
1543 /// sit apart.
1544 ///
1545 /// # `Input::OrderBy` is the STORAGE term, and one type is the law rather than a shortcut
1546 ///
1547 /// The order a client asks for and the order a page is resumed from are one type because every
1548 /// variant a client can name has to be one the engine can PUSH into the statement — a wire variant
1549 /// honoured in memory would put a sort between the database's `LIMIT` and the page's delivery. So
1550 /// this names [`RecordModel::ordering`]'s enum where it exists, and `()` where it does not: a
1551 /// declaration with a wire face and no `persist(…)` block has no column to order by, and the two
1552 /// predicates part exactly there.
1553 fn wire_binding(&self) -> proc_macro2::TokenStream {
1554 let Some(graphql) = &self.graphql else {
1555 return proc_macro2::TokenStream::new();
1556 };
1557 let record = &self.record;
1558 let input = graphql.input.safe();
1559 let output = graphql.output.safe();
1560 let filter = graphql.filter.safe();
1561 let key_output = graphql.key_output.safe();
1562 let order_by = if self.orderable() {
1563 let name = self.order_by.safe();
1564 quote!(#name)
1565 } else {
1566 quote!(())
1567 };
1568 // The QUERY UNIT where this record has root fields, and `()` where it has none — the same shape
1569 // `order_by` above takes, and the same kind of statement: a record whose store carries no query
1570 // face has nothing a root could mount, and the empty product is what a fold measures its
1571 // membership against.
1572 let queries = match self.wire_query_row() {
1573 Some(_) => {
1574 let name = crate::model::default_queries_name(record);
1575 quote!(#name)
1576 }
1577 None => quote!(()),
1578 };
1579 let face = self.framework(&["transform"], "Graphql");
1580 let input_face = self.framework(&["transform"], "GraphqlInput");
1581 let output_face = self.framework(&["transform"], "GraphqlOutput");
1582 quote! {
1583 #[automatically_derived]
1584 impl #input_face for #input {
1585 type Filter = #filter;
1586 type OrderBy = #order_by;
1587 }
1588
1589 #[automatically_derived]
1590 impl #output_face for #output {
1591 type Key = #key_output;
1592 }
1593
1594 #[automatically_derived]
1595 impl #face for #record {
1596 type Input = #input;
1597 type Output = #output;
1598 type Query = #queries;
1599 }
1600 }
1601 }
1602
1603 /// The record's HYDRATION PROJECTION: `Hydrates`, naming the database a hydrated read of this
1604 /// record's rows runs against — and NOTHING at all where there is no such database.
1605 ///
1606 /// # It is [`wire_query_row`](Self::wire_query_row)'s answer, and never a first-declared computed
1607 /// again
1608 ///
1609 /// That function is already the authority on where this record's ROOT FIELDS read — the first
1610 /// declared database with a query face whose row raises onto the wire — and its own note carries
1611 /// the law: *a client must never see a field that varies with a deployment's storage choice*. A
1612 /// record answering `reel(id:)` out of one store and a hydrated hit out of another would be that
1613 /// variance one road over, and a schema installing one `SqlDoor` per store would have to install
1614 /// two for one record. Reading the one function is what makes the two identical by construction;
1615 /// two independent walks agreeing today is what would let them stop agreeing.
1616 ///
1617 /// It also settles the PRESENCE question for free. `wire_query_row` is `None` for a record with no
1618 /// `graphql(…)` block, for one with no queryable database, and for one whose row does not raise —
1619 /// a record with no `persist(…)` block being an instance of the second — so there is no separate
1620 /// condition here to keep in step, and the projection cannot be well formed where
1621 /// [`queries_type`](Self::queries_type) minted no unit.
1622 ///
1623 /// # It rides the DATABASE's gate, where the entity binding beside it rides none
1624 ///
1625 /// [`binding`](Self::binding) and [`wire_binding`](Self::wire_binding) name only this emission's
1626 /// own types, so they exist in every build. This one binds [`DatabaseBackend::backend_type`], which is the one place an
1627 /// expansion names a backend CONCRETELY — so it takes the same gate
1628 /// [`vocabulary`](DatabaseBackend::vocabulary) takes, and for that impl's reason: ungated, a
1629 /// declaration naming Postgres would fail to compile in a build with no Postgres driver.
1630 ///
1631 /// What a shut gate costs is stated rather than hidden: a build carrying the SQL family but not
1632 /// THIS record's dialect has no impl, so a derived index over it is `E0277` at the road that
1633 /// hydrates — the same refusal a record with no `persist(…)` block gets, at the same span, and one
1634 /// a build that compiled the dialect its declaration named never sees.
1635 fn hydration_binding(&self) -> proc_macro2::TokenStream {
1636 let Some(database) = self.wire_query_row() else {
1637 return proc_macro2::TokenStream::new();
1638 };
1639 let record = &self.record;
1640 let backend = database.backend_type(self);
1641 let hydrates = self.framework(&["transform"], "Hydrates");
1642 let gate = self.framework(&["gate"], &database.kind().gate().to_string());
1643 quote! {
1644 #gate! {
1645 #[automatically_derived]
1646 impl #hydrates for #record {
1647 type Db = #backend;
1648 }
1649 }
1650 }
1651 }
1652
1653 /// The `*Key`'s FILESYSTEM face: `KeySegments`, walking the key's columns into the sink one
1654 /// segment each, lineage root-first and the id last.
1655 ///
1656 /// It is the address the local blob store nests directories by, so the order IS the tree — the
1657 /// parents are the directories and the id is the file. A root has one column, so it pushes one
1658 /// segment and the file sits directly under the slot; no branch here says so, because
1659 /// [`Key::columns`](crate::model::Key::columns) already hands back the whole key in that order
1660 /// and a root's whole key is its id.
1661 ///
1662 /// Emitted for EVERY declaration rather than for the ones that store bytes, and that is the
1663 /// choice worth stating: a declaration carries no word saying which stores will hold it, and the
1664 /// trait is satisfied by the key's shape alone. What it costs a record that never becomes a file
1665 /// is one impl; what it buys is that no declaration has to be revisited the day something asks
1666 /// for its blobs.
1667 ///
1668 /// The bound it lands under is the sealed identity VOCABULARY: `Segments::push` takes a
1669 /// `Segment`, which is the framework's `Id` plus a rendering the framework owns, so a key column
1670 /// of a type that vocabulary never admitted is `E0277` at the `#[ingraph::record(…)]`. That is the
1671 /// storability audit's shape one layer over — the refusal lands at the declaration that wrote
1672 /// the column rather than at the first store that could not address it.
1673 ///
1674 /// Every column is pushed BY REFERENCE, `copy` marked or not. `push` takes `&I` whatever the
1675 /// column's projection is, so the marker — which decides what an accessor hands back — changes
1676 /// nothing here, and there is no second spelling for the walk to pick between.
1677 ///
1678 /// The field names are the KEY's, so a `key(rename = "…")` reaches the walk as it reaches the
1679 /// struct: the segment order is the key's own column order and the reads are its own fields.
1680 fn address_segments(&self) -> proc_macro2::TokenStream {
1681 let key = &self.key.name;
1682 let key_segments = self.framework(&["store"], "KeySegments");
1683 let segments = self.framework(&["store"], "Segments");
1684 // A lineage that is a CHOICE is not a column the vocabulary can render — it is a whole address
1685 // of its own — so it walks rather than pushes, and the walk is emitted beside this one.
1686 let fanned = self.fanned_lineage_name();
1687 let columns = self.key.columns().map(|column| {
1688 let name = &column.name;
1689 if fanned.is_some_and(|_| name == &fanned_lineage_column()) {
1690 quote!(#key_segments::segments(&self.#name, out);)
1691 } else {
1692 quote!(out.push(&self.#name);)
1693 }
1694 });
1695 let choice = fanned.map(|(name, kinds)| {
1696 let arms = kinds.iter().map(|kind| {
1697 let variant = &kind.variant;
1698 let word = variant.to_string();
1699 quote! {
1700 Self::#variant(__ingraph_key) => {
1701 out.push_word(#word);
1702 #key_segments::segments(__ingraph_key, out);
1703 }
1704 }
1705 });
1706 quote! {
1707 #[automatically_derived]
1708 impl #key_segments for #name {
1709 #[inline]
1710 fn segments(&self, out: &mut #segments) {
1711 match self { #(#arms)* }
1712 }
1713 }
1714 }
1715 });
1716 quote! {
1717 #[automatically_derived]
1718 impl #key_segments for #key {
1719 #[inline]
1720 fn segments(&self, out: &mut #segments) {
1721 #(#columns)*
1722 }
1723 }
1724
1725 #choice
1726 }
1727 }
1728
1729 /// This node's lineage where it is a CHOICE: the emitted enum's name, and its variants.
1730 fn fanned_lineage_name(&self) -> Option<(&syn::Ident, &[Kind])> {
1731 let lineage = self.lineage.as_ref()?;
1732 match &lineage.shape {
1733 Shape::Kinds(kinds) => Some((&lineage.name, kinds)),
1734 Shape::Path(_) => None,
1735 }
1736 }
1737
1738 /// One emitted type, as two pieces the caller places separately: the STRUCT, which is the API and
1739 /// stays at top level, and its inherent IMPL, which goes inside the record's anonymous const.
1740 ///
1741 /// The type and its methods are exactly as visible as the record — a private record's key must not
1742 /// leak into its crate's public API — and the FIELDS carry `pub(crate)` whatever that visibility
1743 /// is, which is [`crate::host`]'s stamp one type over: an address's columns are read by the
1744 /// emitted code and by the crate around it, and they are never wider than the crate, so a public
1745 /// record's key still hands its columns out through the accessors alone.
1746 ///
1747 /// The stamp is what the KEY-PARENT EQUATION is written against. A fusing node reads its parent's
1748 /// key COLUMN BY NAME, and a private field would make every such read `E0616` at a span the author
1749 /// cannot act on — so the error an author sees is the one the ruling names, `E0609` for a column
1750 /// that moved. Fusion across CRATES is out of reach by the same rule, and deliberately: widening
1751 /// to `pub` would put a declaration's columns in its crate's public API without anyone writing
1752 /// the word.
1753 ///
1754 /// Every item `missing_docs` covers is documented, because a consumer that denies the lint cannot
1755 /// edit a generated type to satisfy it. Crate-visible fields are not covered, and are left to the
1756 /// accessor that projects them rather than described twice.
1757 fn address_type<'a>(
1758 &self,
1759 name: &syn::Ident,
1760 doc: &str,
1761 new_doc: &str,
1762 columns: impl Iterator<Item = &'a Column> + Clone,
1763 id: Option<&Column>,
1764 ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
1765 let vis = &self.vis;
1766 let (names, types): (Vec<&syn::Ident>, Vec<&syn::Type>) = columns
1767 .clone()
1768 .map(|column| (&column.name, &column.ty))
1769 .unzip();
1770 let families = columns.map(|column| {
1771 // Identity by IDENTITY, not by name: a scoped rename can give a lineage step the same name the
1772 // id carries in another type, and comparing strings would mis-describe it.
1773 let subject = if id.is_some_and(|id| core::ptr::eq(id, column)) {
1774 "row\'s own id".to_owned()
1775 } else {
1776 format!("`{}` step of the lineage path", column.name)
1777 };
1778 // NO gate: a key column is the row's own address, and `identity is not conditional` is a
1779 // refusal at the front end — see `ingraph_derive::attribute`.
1780 column.methods(
1781 &self.vis,
1782 &self.krate,
1783 &subject,
1784 true,
1785 &proc_macro2::TokenStream::new(),
1786 )
1787 });
1788 let doc = leading(doc);
1789 let new_doc = leading(new_doc);
1790 let declaration = quote! {
1791 #[doc = #doc]
1792 #[derive(
1793 ::core::fmt::Debug,
1794 ::core::clone::Clone,
1795 ::core::cmp::PartialEq,
1796 ::core::cmp::Eq,
1797 ::core::hash::Hash
1798 )]
1799 #vis struct #name {
1800 #(pub(crate) #names: #types,)*
1801 }
1802 };
1803 let arity = wide_signature();
1804 let methods = quote! {
1805 impl #name {
1806 #[doc = #new_doc]
1807 #arity
1808 #[inline]
1809 #vis const fn new(#(#names: #types,)*) -> Self {
1810 Self { #(#names,)* }
1811 }
1812
1813 #(#families)*
1814 }
1815 };
1816 (declaration, methods)
1817 }
1818
1819 /// One emitted type's pair of conversions from the record.
1820 ///
1821 /// `#[automatically_derived]` belongs on these and only on these: it is valid on a TRAIT impl and
1822 /// warns on an inherent one, so the inherent impls beside them carry nothing.
1823 ///
1824 /// The borrowing one clones through `Clone::clone(&…)` rather than `….clone()`. That is not
1825 /// style: `clone_on_copy` is a default-on clippy lint, and a generated `.clone()` on a `Copy`
1826 /// column would fail any consumer building under `-D warnings` — which a macro cannot avoid, since
1827 /// it cannot know whether a column's type is `Copy`. The call form it does not fire on is the one
1828 /// to keep.
1829 fn address_conversions<'a>(
1830 &self,
1831 name: &syn::Ident,
1832 columns: impl Iterator<Item = &'a Column> + Clone,
1833 ) -> proc_macro2::TokenStream {
1834 let record = &self.record;
1835 let (names, sources): (Vec<&syn::Ident>, Vec<&syn::Ident>) =
1836 columns.map(|column| (&column.name, &column.source)).unzip();
1837 // A REWRITE reads its columns through the wrapped type's accessors, so the two bodies collapse
1838 // into one: there is nothing to move OUT of a wrapper, and the borrowing read is the only read.
1839 let binding = format_ident!("record");
1840 let (moved, borrowed): (Vec<_>, Vec<_>) = if self.remote.is_some() {
1841 let reads: Vec<proc_macro2::TokenStream> = sources
1842 .iter()
1843 .map(|source| self.remote_read(&binding, source))
1844 .collect();
1845 (reads.clone(), reads)
1846 } else {
1847 (
1848 sources
1849 .iter()
1850 .map(|source| quote!(record.#source))
1851 .collect(),
1852 sources
1853 .iter()
1854 .map(|source| quote!(::core::clone::Clone::clone(&record.#source)))
1855 .collect(),
1856 )
1857 };
1858 quote! {
1859 #[automatically_derived]
1860 impl ::core::convert::From<#record> for #name {
1861 #[inline]
1862 fn from(record: #record) -> Self {
1863 Self { #(#names: #moved,)* }
1864 }
1865 }
1866
1867 #[automatically_derived]
1868 impl<'a> ::core::convert::From<&'a #record> for #name {
1869 #[inline]
1870 fn from(record: &'a #record) -> Self {
1871 Self { #(#names: #borrowed,)* }
1872 }
1873 }
1874 }
1875 }
1876
1877 /// A path to one of the names the framework SHELVES, reached the ONE way emitted code is allowed
1878 /// to reach them: the model's crate path, then `__private`, then the module the item lives in.
1879 ///
1880 /// Emitted code depends on that shelf rather than on where the framework keeps an item, so the
1881 /// framework can move or rename one without regenerating anyone's expansion. The shelf mirrors the
1882 /// crate's modules rather than flattening them, which is why the module segments are here: a glob
1883 /// per module needs no maintenance as the crate grows, and two modules that each define a `Column`
1884 /// stay apart.
1885 ///
1886 /// **The module is a PATH, not one segment.** Mirroring is recursive, so a family that is a module
1887 /// inside a module is shelved that way too and is named that way here:
1888 /// `framework(&["comparison", "sql"], "SqlScalarComparison")` is
1889 /// `#krate::__private::comparison::sql::SqlScalarComparison`. Flattening the shelf to keep the
1890 /// segment single would give up exactly what mirroring buys — two modules that each define a
1891 /// `Column` would collide — so the depth belongs here rather than in the shelf's shape.
1892 ///
1893 /// A SLICE rather than a `"comparison::sql"` string: every element becomes one identifier, so
1894 /// nothing here parses `::` and no element can carry a separator that a later ident would choke
1895 /// on. An empty slice would name an item directly beneath `__private`, which is the flattened
1896 /// shape the guard below refuses.
1897 ///
1898 /// A VENDORED crate the framework re-exports takes that segment under its OWN name, so
1899 /// `framework(&["serde"], "Serialize")` is `#krate::__private::serde::Serialize`. The shape is the
1900 /// same, which is what lets one rule and one check cover both.
1901 ///
1902 /// The rule is not left to habit — `tests::every_framework_path_goes_through_a_private_module`
1903 /// walks the emission's tokens and fails on any path rooted at the crate that skips `__private`
1904 /// OR names an item directly beneath it.
1905 pub(crate) fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
1906 framework(&self.krate, module, name)
1907 }
1908
1909 /// The shelf path to a whole VENDORED crate — `#krate::__private::serde` — as the string a derive
1910 /// that takes a crate-path override wants.
1911 ///
1912 /// A `String` rather than tokens because its only use is inside a string literal: serde's
1913 /// `#[serde(crate = "…")]` is spelled that way, and the derive parses the string back into a path.
1914 /// The token walk cannot see a literal, so the emitted one is pinned by a test of its own
1915 /// (`tests::the_mongo_document_reaches_serde_through_the_shelf`).
1916 ///
1917 /// A path a DECLARER wrote (`#[ingraph(crate = "…")]`) is carried through verbatim, so whatever
1918 /// prefix that path uses has to work in a `use` statement as well as in type position — serde
1919 /// binds its internal `_serde` to it with one. `::krate` and `self::path::to::krate` both do.
1920 pub(crate) fn vendored(&self, krate: &str) -> String {
1921 vendored(&self.krate, krate)
1922 }
1923}
1924
1925impl DatabaseBackend {
1926 /// Whether this database keeps `column`'s elements in an EDGE TABLE — the one question that
1927 /// decides whether the column is a value of this row or a second table correlated to it.
1928 ///
1929 /// Two facts and no inference. The DECLARATION classified the column a collection (the word, read
1930 /// by [`RecordModel::collects`]), which alone answers nothing — a scalar is a scalar in every
1931 /// dialect. And the strategy is stated, by one of the two parties that can state it:
1932 ///
1933 /// * the DIALECT, where it has no choice — [`DatabaseKind::edge_collections`], which is
1934 /// `ingraph`'s `CollectionStorage` read one layer up, and true for the two dialects with no
1935 /// array type;
1936 /// * the DECLARATION, where it has — [`PersistColumn::edge`], Postgres's optional word, the
1937 /// element-level fact a macro holding tokens cannot read out of a trait row.
1938 ///
1939 /// An `or` rather than a branch, and it is not a shortcut: `ingraph-derive` refuses `edge` in
1940 /// every block but Postgres's, so the two halves are disjoint by construction and neither can
1941 /// quietly cover for the other.
1942 pub(crate) fn edge_stored(&self, model: &RecordModel, column: &PersistColumn) -> bool {
1943 (self.kind().edge_collections() || column.edge) && model.collects(&column.source)
1944 }
1945
1946 /// This database's own entry for the record field `source`, or [`None`] where the declaration
1947 /// narrowed the column out of this database.
1948 ///
1949 /// The ONE lookup every per-database reader goes through, and it is by SOURCE rather than by
1950 /// position for a reason a position cannot express: the shared list is the DECLARATION's, so it is
1951 /// the widest of them, and a database that narrowed a column has a shorter one. An index read off
1952 /// the shared list would name a different column here, or run off the end.
1953 pub(crate) fn stores(&self, source: &syn::Ident) -> Option<&PersistColumn> {
1954 self
1955 .columns()
1956 .iter()
1957 .find(|column| column.source == *source)
1958 }
1959
1960 /// The columns the wire face publishes AND THIS DATABASE STORES, at this database's own names,
1961 /// types and refinements.
1962 ///
1963 /// [`RecordModel::queried_columns`] states the schema's vocabulary; this is the STORAGE-true
1964 /// subset of it, and the two now differ. It is what the comparison's members, its `where` clause
1965 /// and its lowering walk — a member for a column this table has not got would render a predicate
1966 /// naming a column no statement can name.
1967 ///
1968 /// # The CROSSING joins the two lists rather than zipping them
1969 ///
1970 /// The filter's rows are the declaration's and this list is this database's, so a narrowing
1971 /// database's comparison has FEWER members than the filter has fields. The crossing therefore
1972 /// walks the filter's rows and asks [`stores`](Self::stores) for each — a row whose column is here
1973 /// crosses as before, and one whose column is not answers with `ColumnNotStored` where the client
1974 /// wrote an operand and with nothing at all where it wrote none. See
1975 /// `DatabaseBackend::filter_crossing`, which is the one place the join is spelled.
1976 pub(crate) fn compared(&self, model: &RecordModel) -> Vec<&PersistColumn> {
1977 model
1978 .queried_columns()
1979 .into_iter()
1980 .filter_map(|(_, shared)| self.stores(&shared.source))
1981 .collect()
1982 }
1983
1984 /// Whether this database MIRRORS `column` into an order-preserving companion column — the join of
1985 /// the DECLARATION's `sortable` word and this database's storage form.
1986 ///
1987 /// Two facts and no inference, exactly as [`edge_stored`](Self::edge_stored) is two: the word was
1988 /// written, and this database keeps the collection in a table of its own. A dialect with a native
1989 /// array orders the collection itself, so there is nothing for a companion to carry and none is
1990 /// emitted — which is the ruled per-backend answer rather than a per-database knob a declaration
1991 /// could turn.
1992 ///
1993 /// It reads [`edge_stored`](Self::edge_stored) rather than restating it, so the column a write
1994 /// fills, the column a `CREATE TABLE` declares and the column an `ORDER BY` renders cannot
1995 /// disagree about which collections have one.
1996 pub(crate) fn mirrors(&self, model: &RecordModel, column: &PersistColumn) -> bool {
1997 self.edge_stored(model, column) && model.sortable(&column.source)
1998 }
1999
2000 /// Whether this database gives `column` the VALUE-LED ACCESS PATH on its ELEMENTS' OWN TABLE — the
2001 /// join of the DECLARATION's `indexed` word and this database's storage form.
2002 ///
2003 /// [`mirrors`](Self::mirrors)' shape one word over, and it reads
2004 /// [`edge_stored`](Self::edge_stored) for that method's reason: the party that declares the edge
2005 /// table and the party that asks it for a second index cannot disagree about which collections
2006 /// have one.
2007 ///
2008 /// # The OTHER storage form's half is not emitted from here, and cannot be
2009 ///
2010 /// A collection this database keeps in a COLUMN is a Postgres array, and a record carrying one
2011 /// gets no blueprint at all: `Vec<T>` has no `StoredAs` row, deliberately — a `CREATE TABLE`
2012 /// spells that column `bigint[]` and `information_schema` answers `ARRAY`, and one `const` cannot
2013 /// be both — so `RecordModel::describable` subtracts the database and there is nothing for
2014 /// `Table::with_collection_indexes` to be written onto. See this module's own roster note, where
2015 /// the subtraction is measured. The word is carried on the FIELD either way, so the day that wall
2016 /// comes down is the day the array half starts rendering; the framework's side of it is written
2017 /// already.
2018 pub(crate) fn seeks_by_value(&self, model: &RecordModel, column: &PersistColumn) -> bool {
2019 self.edge_stored(model, column) && model.indexed(&column.source)
2020 }
2021
2022 /// The name this database's companion column for `column` wears.
2023 ///
2024 /// The mint is [`alias::sort_column`](crate::alias::sort_column) and this is the one call to it
2025 /// from an emission: it takes the column's EXTERNAL name — what a rename left it called here — so
2026 /// a companion follows the column it is the order of.
2027 ///
2028 /// It also takes THIS database's resolved namespace, for the reason the mint states: the fence a
2029 /// declaration is held to is the union of what its databases declared, so a record that moved the
2030 /// prefix everywhere may legally declare a column in the framework's own namespace — and a
2031 /// companion minted there anyway would be the collision the fence exists to make impossible.
2032 pub(crate) fn sort_column(&self, model: &RecordModel, column: &PersistColumn) -> String {
2033 crate::alias::sort_column(
2034 self.storage().aliases.prefix_in(&model.prefix),
2035 &self.external(model, column),
2036 )
2037 }
2038
2039 /// Whether this database materializes `column` as a correlated AGGREGATE on the page statement
2040 /// rather than as a gather of its own.
2041 ///
2042 /// The dialect with a native array is the dialect that can aggregate into one, so the split is
2043 /// exactly [`DatabaseKind::edge_collections`]'s: a dialect that has no array has nothing to
2044 /// `array_agg` INTO, and its edge-stored collections take the second statement. Postgres's
2045 /// edge-stored ones take the subselect, which is one statement and no tear — see the engine's own
2046 /// `query::sql::hydrate`, where both materializations live.
2047 pub(crate) fn aggregates(&self, model: &RecordModel, column: &PersistColumn) -> bool {
2048 self.edge_stored(model, column) && !self.kind().edge_collections()
2049 }
2050
2051 /// Whether this database's row carries an EXTRACTION — the emitted `from_document`, which is
2052 /// MongoDB's alone.
2053 ///
2054 /// ONE condition, and it used to be two. A flattened column took the extraction away: its type's
2055 /// keys were the document's own, so a read at the column's name found nothing whatever the
2056 /// document held, and a partial extraction would have left a field unset. `flatten` is a SQL
2057 /// family's word now — a document NESTS a held value, which is the composite form the server
2058 /// indexes — so a mongo row has no flattened column to be defeated by and the condition went with
2059 /// the word.
2060 ///
2061 /// It is here rather than inside that emitter because TWO parties ask: the emission, and the
2062 /// method enumeration that has to name every method the emission declares. Two predicates would be
2063 /// a declaration refused for a name it does not get, or a name nothing knew was taken.
2064 pub(crate) fn extracts(&self) -> bool {
2065 !self.kind().is_sql()
2066 }
2067
2068 /// The name `column` is stored under in this database — the ONE authority on an external name,
2069 /// wherever an emission writes one.
2070 ///
2071 /// It is the column's own name everywhere except ONE row: MongoDB stores a record's id as `_id`.
2072 /// That is the server's name rather than this framework's — MongoDB mints an `_id` for every
2073 /// document that arrives without one and indexes it uniquely, so a document carrying both the
2074 /// minted one and a declared `id` would be one row with two identities, with the wrong one
2075 /// indexed.
2076 ///
2077 /// The declaration and the wire face still say `id`, so the mapping lives in exactly two places
2078 /// and this is one of them: the derive's `rename` and the emitted extraction's read BOTH come
2079 /// through here, so they cannot differ. The other is `ingraph`'s own `field_key`, which is where
2080 /// every RENDERED field path goes — a filter's key, a `$sort` entry, a keyset arm — and the two
2081 /// agree because both are keyed on the id COLUMN rather than on the word `id`.
2082 ///
2083 /// The column is identified by its SOURCE field rather than by its name, for the reason every
2084 /// other identity check in this emitter is: a `<db>(rename)` moves the name, and a
2085 /// comparison on the string would then map a column that is not the id or fail to map the one
2086 /// that is.
2087 pub(crate) fn external(&self, model: &RecordModel, column: &PersistColumn) -> String {
2088 if self.kind().is_sql() || column.source != model.key.id.source {
2089 return column.name.to_string();
2090 }
2091 crate::model::MONGO_ID.to_owned()
2092 }
2093
2094 /// The type this database's row FIELD carries for `column`.
2095 ///
2096 /// The stored type as declared, except for an edge-stored collection: there the declared type is
2097 /// ONE ELEMENT's — which is what the comparison layer already reads it as, since a collection
2098 /// operand binds one member at a time — and the row holds the LIST of them, which is what a
2099 /// materialization fills and what the record is rebuilt from.
2100 ///
2101 /// So a column declared `sqlite(type = "BeU128")` under `list(scalar)` is
2102 /// `::std::vec::Vec<BeU128>` on the row and `BeU128` in the predicate, from one declaration. The
2103 /// crossing the declaration names is the whole collection's — domain in, `Vec<element>` out —
2104 /// because that is the one place an `Option<Vec<…>>` collapse and an element conversion can both
2105 /// be written, and it is where the declaration already puts every other column's crossing.
2106 pub(crate) fn row_field(
2107 &self,
2108 model: &RecordModel,
2109 column: &PersistColumn,
2110 ) -> proc_macro2::TokenStream {
2111 let ty = column.ty();
2112 if self.kind().is_sql() && model.collects(&column.source) {
2113 return quote!(::std::vec::Vec<#ty>);
2114 }
2115 quote!(#ty)
2116 }
2117
2118 /// One self's projection of a record: the struct, and its impls.
2119 ///
2120 /// **No constructor.** The argument is the record's own, at the top of this module: a real
2121 /// aggregate has twenty-odd fields, so a positional `new` would be unusable and
2122 /// transposition-prone. A row also has two construction paths already — the conversion from the
2123 /// record, and the decode a database reads it back through (`FromRow`, emitted here;
2124 /// `Deserialize`, derived) — so a third would be the only one that could put the columns in the
2125 /// wrong order.
2126 ///
2127 /// **Accessors only, no mutators.** A key gets `set_*`/`with_*` because stepping to a neighbouring
2128 /// key has a consumer; nothing edits a row in place. It is produced by a conversion or a decode and
2129 /// consumed by a write or a conversion, and the accessors are what those need.
2130 ///
2131 /// Every column's external name is written out UNIFORMLY, not only when the name had to be
2132 /// mangled — so the mapping never depends on how a derive happens to treat an identifier, and a
2133 /// reader of the expansion can see each column's real name without knowing the mangling rule.
2134 /// WHERE it is written is the family's answer: a `rename` attribute on the field, or the read
2135 /// inside the decode the family emits. See [`Mapping`].
2136 ///
2137 /// **Every column carries a name here, including a held value's**, and the family that maps by
2138 /// ATTRIBUTE is the one where that is the whole story: a document nests a held value under this
2139 /// field's own key, so the name is the key and nothing is flattened. The FLATTENING entry that
2140 /// used to stand in `flatten`'s place is gone with the word, which is now the SQL family's.
2141 ///
2142 /// A family that maps by DECODE is where the gap still is, and it is worth stating plainly: a
2143 /// decode reads ONE column per field under one name, so a held value spanning several columns is
2144 /// stored today as one column of its own type — which is what the SQL predicate over it does NOT
2145 /// assume, since that renders `rate_num`/`rate_den` from the segments it walks. The two disagree,
2146 /// the disagreement predates `flatten` in either position, and what closes it is statement
2147 /// emission reading `CompositeComparison::SEGMENTS`. See that trait for the measurement.
2148 pub(crate) fn row(
2149 &self,
2150 model: &RecordModel,
2151 ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
2152 let family = &self.kind().family(model);
2153 let vis = &model.vis;
2154 let record = &model.record;
2155 let name = self.name();
2156 let derives = &family.derives;
2157 let attrs = &family.attrs;
2158 let what = (family.what)(self.kind());
2159 let noun = family.noun;
2160
2161 let fields = self.columns().iter().map(|column| {
2162 let field = column.name.safe();
2163 let ty = self.row_field(model, column);
2164 let naming = match family.mapping {
2165 Mapping::Attribute(attribute) | Mapping::AttributeAndDecode(attribute, _) => {
2166 let attribute = format_ident!("{attribute}");
2167 let external = self.external(model, column);
2168 // The VIA rides the same attribute as the name, one list rather than two, because it is
2169 // the same derive being told two things about one field — and it is written for EVERY
2170 // column or for none, which is what keeps the choice out of this emitter's hands. See
2171 // [`Family::via`].
2172 family.via.as_ref().map_or_else(
2173 || Some(quote!(#[#attribute(rename = #external)])),
2174 |via| Some(quote!(#[#attribute(rename = #external, with = #via)])),
2175 )
2176 }
2177 Mapping::Decode(_) => None,
2178 };
2179 // The CONDITION on the ROW's field, read off the record field this column projects: a record
2180 // that loses a field loses its column, and a row holding a column for a field the build
2181 // removed is exactly the orphan the seat exists to close.
2182 let gate = model.gate(&column.source);
2183 quote! {
2184 #gate
2185 #naming
2186 #field: #ty,
2187 }
2188 });
2189 let families = self.columns().iter().map(|column| {
2190 let subject = format!("`{}` column", column.name);
2191 let mut shaped = column.as_column();
2192 // The accessor hands back what the FIELD holds, which for an edge-stored collection is the
2193 // list rather than one element — see [`row_field`](Self::row_field).
2194 let held = self.row_field(model, column);
2195 shaped.ty = syn::parse2(held).expect("a field type is a type");
2196 shaped.methods(
2197 &model.vis,
2198 &model.krate,
2199 &subject,
2200 false,
2201 &model.gate(&column.source),
2202 )
2203 });
2204
2205 // WHAT THE ROW DOES NOT HOLD, said on the row itself. A reader who finds a declared field
2206 // missing here has one question, and the doc answers it at the type rather than at the
2207 // declaration: the word is on the field, and the consequence is here.
2208 //
2209 // TWO absences, and the sentence tells them apart because the reader's next question differs.
2210 // A `skip`ped field is missing from EVERY row of this record; a narrowed one is missing from
2211 // this row and is a column of the record's other databases, which is a fact a reader holding
2212 // one row type cannot find out anywhere else.
2213 let withheld: Vec<String> = model
2214 .fields
2215 .iter()
2216 .filter(|field| field.skip.is_some())
2217 .map(|field| format!("`{}`", field.column.source))
2218 .collect();
2219 let narrowed: Vec<String> = self
2220 .storage()
2221 .fills
2222 .iter()
2223 .map(|filled| format!("`{}`", filled.source))
2224 .collect();
2225 let mut omissions = String::new();
2226 if !withheld.is_empty() {
2227 omissions.push_str(&format!(
2228 "\n\n# Omitted\n\nThe declaration wears `skip` for {list}, so no row of this record \
2229 mints a column for {them} — a read fills {them} from `Default::default()`, or from the \
2230 function `skip(default = \"…\")` named.",
2231 list = withheld.join(", "),
2232 them = if withheld.len() == 1 { "it" } else { "them" },
2233 ));
2234 }
2235 if !narrowed.is_empty() {
2236 omissions.push_str(&format!(
2237 "\n\n# Narrowed out of this database\n\n{list} {are} {a}columns of this record's other \
2238 databases and not of `{db}`, so this row mints none — a read supplies {them} from the \
2239 function `{db}(skip(default = \"…\"))` named.",
2240 list = narrowed.join(", "),
2241 are = if narrowed.len() == 1 { "is" } else { "are" },
2242 a = if narrowed.len() == 1 { "a " } else { "" },
2243 them = if narrowed.len() == 1 { "it" } else { "them" },
2244 db = self.kind().as_str(),
2245 ));
2246 }
2247 let doc = leading(&format!(
2248 "The {what} {noun} a [`{record}`] is stored as.{omissions}"
2249 ));
2250 let declaration = quote! {
2251 #[doc = #doc]
2252 #[derive(#derives)]
2253 #attrs
2254 #vis struct #name {
2255 #(#fields)*
2256 }
2257 };
2258 let conversions = self.conversions(model);
2259 let decode = match family.mapping {
2260 Mapping::Attribute(_) => proc_macro2::TokenStream::new(),
2261 Mapping::Decode(emit) | Mapping::AttributeAndDecode(_, emit) => emit(self, model),
2262 };
2263 let equality = self.equality(model);
2264 let methods = quote! {
2265 impl #name {
2266 #(#families)*
2267 }
2268
2269 // AFTER the conversions, which is where the derive it replaced effectively sat: a derive is
2270 // expanded at the container and the conversions are the first impls written by hand, so a
2271 // reader walking this expansion — and a test finding "the first impl on the row" — sees the
2272 // same item it always did.
2273 #conversions
2274 #equality
2275 #decode
2276 };
2277 (declaration, methods)
2278 }
2279
2280 /// **THE ROW'S `PartialEq`, WRITTEN RATHER THAN DERIVED** — one `ColumnEq` call per stored column,
2281 /// folded.
2282 ///
2283 /// # Why the derive left, and what did NOT leave with it
2284 ///
2285 /// `#[derive(PartialEq)]` demands `PartialEq` of every declared field type, and that demand is
2286 /// made by generated code an author cannot edit. `regex::Regex` implements none and cannot be
2287 /// given one outside `regex` itself — both the trait and the type are foreign, so the impl is
2288 /// `E0117` here and in every other crate — which made a pattern column `E0369` raised inside an
2289 /// expansion, pointing at a field the author wrote and at code the author cannot reach.
2290 ///
2291 /// What replaces it is not a weaker row but the SAME row with its obligation moved: this fold asks
2292 /// each field type for [`ColumnEq`], whose answer is `self == other` for every type that has a
2293 /// `PartialEq` and is the pattern TEXT for the one that has not. So a record that compared before
2294 /// compares identically, field for field, and one that could not compile now does.
2295 ///
2296 /// # The gate is `Condition::either`'s, because a folded `&&` is the seat an attribute cannot sit
2297 /// in
2298 ///
2299 /// `#[cfg]` on a TERM of an expression is `stmt_expr_attributes` and unstable, so a per-column
2300 /// predicate cannot ride the `&&` chain the way it rides a struct-expression field or an array
2301 /// element. [`Condition::either`] is the crate's own answer: the fork moves one grain out into a
2302 /// block of two `let` STATEMENTS, and a column the build removed contributes the identity for
2303 /// `&&` rather than a term. An unconditional field pays not one token for the seat.
2304 ///
2305 /// # The SPAN is the field's, which is the whole of the refusal seat
2306 ///
2307 /// The call is [`quote_spanned!`] at the record field this column projects, exactly as the
2308 /// storability audit's `StoredAs` projection is: a type with no `ColumnEq` row is `E0277` naming
2309 /// the trait, with the caret on the token the AUTHOR wrote, not on a fold inside an expansion.
2310 /// `ColumnEq`'s own `#[diagnostic::on_unimplemented]` says the rest.
2311 ///
2312 /// # It is ungated, as the row it sits beside is
2313 ///
2314 /// `ColumnEq` names no backend, so nothing here rides a dialect's feature — the same discipline
2315 /// the cursor codec's rows keep by naming `cursor::dialect` markers rather than `sqlx` ones.
2316 ///
2317 /// [`ColumnEq`]: https://docs.rs/ingraph
2318 /// [`Condition::either`]: crate::model::Condition::either
2319 fn equality(&self, model: &RecordModel) -> proc_macro2::TokenStream {
2320 let name = self.name();
2321 let column_eq = model.framework(&["column"], "ColumnEq");
2322 let same = quote!(true);
2323 let comparisons: Vec<proc_macro2::TokenStream> = self
2324 .columns()
2325 .iter()
2326 .map(|column| {
2327 let field = column.name.safe();
2328 let ty = self.row_field(model, column);
2329 let at = column.source.span();
2330 let compared = quote_spanned! {at=>
2331 <#ty as #column_eq>::column_eq(&self.#field, &__ingraph_other.#field)
2332 };
2333 model
2334 .condition(&column.source)
2335 .map_or(compared.clone(), |condition| {
2336 condition.either(&compared, &same)
2337 })
2338 })
2339 .collect();
2340 // A row with no stored columns at all is a row whose values are all equal, which is what an
2341 // empty `&&` fold means — spelled as the literal rather than reached by folding nothing.
2342 let body = if comparisons.is_empty() {
2343 same
2344 } else {
2345 quote!(#(#comparisons)&&*)
2346 };
2347 quote! {
2348 #[automatically_derived]
2349 impl ::core::cmp::PartialEq for #name {
2350 #[inline]
2351 fn eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
2352 #body
2353 }
2354 }
2355 }
2356 }
2357
2358 /// The conversions between a record and one self's row — one per direction, and never two.
2359 ///
2360 /// **`From` when every conversion is infallible, `TryFrom` when any is fallible, never both.** That
2361 /// is not a preference: `core` carries `impl<T, U: Into<T>> TryFrom<U> for T`, so an emitted `From`
2362 /// ALREADY yields a `TryFrom`, and emitting both would collide under coherence. Which is also why
2363 /// emitting the fallible one costs a caller nothing — `try_into()` resolves either way, so calling
2364 /// code does not have to know which was emitted.
2365 ///
2366 /// The error type is `Box<dyn Error + Send + Sync>` because a row's columns may each fail
2367 /// differently and there is no type that names all of them. `?` converts through `core`'s blanket
2368 /// `From<E: Error + Send + Sync + 'static>`, so a conversion function returning any ordinary error
2369 /// works unchanged. A generated per-row error enum is the better long-term answer and belongs with
2370 /// the trait layer.
2371 ///
2372 /// **The verb rule decides which declaration fills which direction: `from` BUILDS the row and
2373 /// `into` LEAVES it.** So `<db>(from)` is the write and `<db>(into)` is the read, and
2374 /// the emitted impl reads literally — `impl From<VideoTrack> for VideoTrackPostgres` is the row
2375 /// FROM the domain. It is relative to the PROJECTION, not to the domain, which is what makes one
2376 /// rule serve the rows, the wire faces and the comparisons alike.
2377 ///
2378 /// The REVERSE direction — the row back to the record — is emitted only when it can be: field-wise
2379 /// when the row carries EVERY field of the record, and otherwise only when the database declared a
2380 /// conversion for the whole row. A partial row cannot rebuild a record it does not carry, and the
2381 /// container conversion is exactly the seam for supplying what it is missing. Nothing is emitted
2382 /// that would not compile, and nothing is silently invented.
2383 fn conversions(&self, model: &RecordModel) -> proc_macro2::TokenStream {
2384 let record = &model.record;
2385 let row = self.name();
2386
2387 // WHERE a column's value comes from — the record's own field, or, under a rewrite, the wrapped
2388 // type's accessor crossed by `Into`. One seam, so the write leg cannot read a wrapper the way
2389 // it reads a struct.
2390 let binding = format_ident!("record");
2391 let writes = self.columns().iter().map(|column| {
2392 let field = column.name.safe();
2393 let source = &column.source;
2394 let read = if model.remote.is_some() {
2395 model.remote_read(&binding, source)
2396 } else {
2397 quote!(record.#source)
2398 };
2399 let value = column.from.apply(read, column.stored.is_some());
2400 // The struct-expression field carries the gate, which is a stable attribute position — so the
2401 // write leg builds exactly the row this build declares.
2402 let gate = model.gate(source);
2403 quote!(#gate #field: #value,)
2404 });
2405 let write = match self.from() {
2406 Conversion::Default => quote!(Self { #(#writes)* }),
2407 declared => declared.apply(quote!(record), false),
2408 };
2409 // The fallibility of what is ACTUALLY emitted: a container conversion replaces the field-wise
2410 // body, so the columns' own conversions say nothing about it — read through
2411 // [`writes_fallibly`](Self::writes_fallibly) rather than decided here, so the query face's own
2412 // crossing cannot call `From` where a `TryFrom` was written.
2413 let write_fallible = self.writes_fallibly();
2414 // The WRITE leg's own cell — `<db>(try_from(error = "…"))` — or the boxed refusal. It
2415 // was held while nothing stored a record; what types it now is the impl the write lane crosses
2416 // through, which is this very conversion.
2417 let write_error = model.error(Crossing::PersistWrite, self.kind());
2418 let to_row = conversion(
2419 quote!(#record),
2420 row,
2421 &format_ident!("record"),
2422 write,
2423 write_fallible.then_some(&write_error),
2424 &format!("Project a [`{record}`] into the row that stores it."),
2425 );
2426
2427 // ONE VALUE PER FIELD the raise supplies, gathered as `(field, expression)` before either body
2428 // is written: a struct literal spells them as members and a rewrite's BUILDER spells them as
2429 // the wrapped type's own constructor arguments, and both need the same pairs.
2430 let mut values: Vec<(syn::Ident, proc_macro2::TokenStream)> = self
2431 .columns()
2432 .iter()
2433 .map(|column| {
2434 let field = column.name.safe();
2435 let value = column
2436 .into
2437 .apply(quote!(row.#field), column.stored.is_some());
2438 (column.source.clone(), value)
2439 })
2440 .collect();
2441 // THE FILLS — every field this raise has no column to read, each from the word that said so.
2442 // Two absences and one walk: the record's own `skip`, which is every database's, and this
2443 // database's own narrowing. Spanned at the word, so a type with no `Default` is `E0277` where
2444 // the author can act on it.
2445 values.extend(self.fills(model));
2446 let members = values.iter().map(|(source, value)| {
2447 let gate = model.gate(source);
2448 quote!(#gate #source: #value,)
2449 });
2450 let read = match self.into() {
2451 Conversion::Default if self.carries_every_field(model) => {
2452 if model.remote.is_some() {
2453 model.remote_build(&values)
2454 } else {
2455 quote!(Self { #(#members)* })
2456 }
2457 }
2458 Conversion::Default => return to_row,
2459 declared => declared.apply(quote!(row), false),
2460 };
2461 // READ rather than decided here, so the impl this emits and every binding that crosses through
2462 // it cannot disagree about which of `From` and `TryFrom` was written.
2463 let read_fallible = self.reads_fallibly(model);
2464 // The READ leg's own cell — `<db>(try_into(error = "…"))` — or the boxed refusal.
2465 let read_error = model.error(Crossing::PersistRead, self.kind());
2466 let to_record = conversion(
2467 quote!(#row),
2468 record,
2469 &format_ident!("row"),
2470 read,
2471 read_fallible.then_some(&read_error),
2472 &format!("Raise a stored row back into the [`{record}`] it came from."),
2473 );
2474
2475 quote! {
2476 #to_row
2477 #to_record
2478 }
2479 }
2480
2481 /// Whether projecting the record INTO this row can fail — the answer
2482 /// [`conversions`](Self::conversions) shapes the forward direction from, so an emitted write
2483 /// binding cannot call `From` where a `TryFrom` was written.
2484 ///
2485 /// It takes no model where its twin below does, and the asymmetry is the row's: a write is emitted
2486 /// field-wise or through a container conversion whatever the row carries, where a READ field-wise
2487 /// needs every field of the record to be there.
2488 pub(crate) fn writes_fallibly(&self) -> bool {
2489 match self.from() {
2490 Conversion::Default => self.columns().iter().any(|column| column.from.fallible()),
2491 container => container.fallible(),
2492 }
2493 }
2494
2495 /// Whether raising this row back into the record can FAIL — the same answer
2496 /// [`conversions`](Self::conversions) shapes the reverse direction from, read rather than decided
2497 /// again, so an emitted binding cannot call `From` where a `TryFrom` was written.
2498 /// # A REWRITE has one source of failure that is not a column's
2499 ///
2500 /// `builder(fallible)` says the wrapped type's terminal construction step hands back a `Result`,
2501 /// so the raise carries a `?` and the impl has to be the `TryFrom` that `?` is legal inside. It
2502 /// is joined here rather than beside the emitted body precisely so that the query face's own
2503 /// crossing sees it: a reader that knew only about the columns would call `From` on a record no
2504 /// `From` was written for. See
2505 /// [`Construction::fallible`](crate::construct::Construction::fallible) for which step is the
2506 /// terminal one and which error road its `Err` joins.
2507 pub(crate) fn reads_fallibly(&self, model: &RecordModel) -> bool {
2508 // The FILLS are infallible by construction — a `Default` and a `fn() -> T` each hand back a
2509 // value or do not exist — so they say nothing here, and only the columns a row actually carries
2510 // and the protocol that reassembles them decide which conversion is written.
2511 match self.into() {
2512 Conversion::Default if self.carries_every_field(model) => {
2513 self.columns().iter().any(|column| column.into.fallible())
2514 || (model.remote.is_some() && model.construction.fallible)
2515 }
2516 Conversion::Default => false,
2517 container => container.fallible(),
2518 }
2519 }
2520
2521 /// Every field this raise supplies rather than reads, as the struct-literal members that supply
2522 /// it — the `skip` family's own half of the field-wise body.
2523 ///
2524 /// # TWO absences, one walk, and the second is why this takes `&self`
2525 ///
2526 /// A field wearing the bare `skip` is a column of NO database, so every raise supplies it from the
2527 /// one fill that word named and the answer does not vary — that half is read off the record's own
2528 /// fields. The participation model adds the other: a field that is a column of the record's other
2529 /// databases and not of THIS one, whose fill is this database's own and whose absence is invisible
2530 /// from anywhere else.
2531 ///
2532 /// The two cannot collide. A field wearing `skip` is in no database's column list and in no
2533 /// database's [`Storage::fills`] either — the narrowing words are refused beside the word at the
2534 /// declaration — so the concatenation names each field at most once.
2535 ///
2536 /// The method stays here rather than on the model so that the raise which spends it and the raise
2537 /// which decides it are one walk.
2538 ///
2539 /// [`Storage::fills`]: crate::model::Storage::fills
2540 fn fills(&self, model: &RecordModel) -> Vec<(syn::Ident, proc_macro2::TokenStream)> {
2541 let withheld = model.fields.iter().filter_map(|field| {
2542 let fill = field.skip.as_ref()?;
2543 let source = &field.column.source;
2544 let value = fill.value(&field.column.ty);
2545 Some((source.clone(), value))
2546 });
2547 // SPANNED at this database's own `skip` word, which is where an author reads the demand: a fill
2548 // whose named function does not answer the field's type reports at the database that asked for
2549 // it rather than inside the raise.
2550 let narrowed = self.storage().fills.iter().map(|filled| {
2551 let ty = model
2552 .fields
2553 .iter()
2554 .find(|field| field.column.source == filled.source)
2555 .map(|field| &field.column.ty)
2556 .expect("a filled field is one the record declares");
2557 (filled.source.clone(), filled.fill.value(ty))
2558 });
2559 withheld.chain(narrowed).collect()
2560 }
2561
2562 /// Whether this row can be turned back into the record FIELD BY FIELD — every field the record
2563 /// declares is either a column of this row or one the `skip` word answered for.
2564 ///
2565 /// # The word is what turns an absence into an answer
2566 ///
2567 /// A field carrying neither `persist` nor `skip` leaves the row PARTIAL, and a partial row rebuilds
2568 /// nothing: the reverse conversion is not emitted, `raises` is false, and the whole SQL query face
2569 /// goes with it. That is unchanged and deliberate — a field nobody spoke about is a field this
2570 /// emission will not invent a value for.
2571 ///
2572 /// What `skip` adds is the DECLARATION. A skipped field is answered for — `Default::default()`, or
2573 /// the function the word named — so the row carries every field it is answerable for and the query
2574 /// face survives. Which is the whole of L12: an engine-resident `Embedding` wears the word, and the
2575 /// record it lives on keeps its rows, its filter, its order and its pages.
2576 ///
2577 /// The PARTIAL absence answers here through the same door and per database: a field this database
2578 /// alone does not carry is answered for by this database's own fill, so a narrowed record keeps
2579 /// its field-wise read in every store rather than losing the query face in the narrowed one.
2580 pub(crate) fn carries_every_field(&self, model: &RecordModel) -> bool {
2581 model
2582 .fields
2583 .iter()
2584 .all(|field| field.skip.is_some() || self.supplies(&field.column.source))
2585 }
2586
2587 /// Whether a READ of this database hands back a value for the record field `source` — a column of
2588 /// this row, or the fill this database's own narrowing word named.
2589 ///
2590 /// The RAISE's question, asked in one place so the parties that decide whether a database can
2591 /// answer a read cannot disagree: `carries_every_field` above, and
2592 /// [`RecordModel::wire_rows`](crate::model::RecordModel::wire_rows), which is the wire's own.
2593 /// Storing and supplying are two different questions and `stores` is the other one — a per-column
2594 /// lowering asks that, and a read asks this.
2595 pub(crate) fn supplies(&self, source: &syn::Ident) -> bool {
2596 self.stores(source).is_some()
2597 || self
2598 .storage()
2599 .fills
2600 .iter()
2601 .any(|filled| filled.source == *source)
2602 }
2603
2604 /// The CONCRETE backend type this database is — `sqlx::Sqlite` for the three dialects, and this
2605 /// crate's own uninhabited `Mongo` for the second family.
2606 ///
2607 /// It is the ONE place in the emission that names a backend concretely, and everywhere else
2608 /// deliberately does not: a row, a comparison and a query binding all keep the dialect a
2609 /// parameter, so a declaration naming one database does not need that database's driver to
2610 /// COMPILE. What buys the exception here is the gate — see [`vocabulary`](Self::vocabulary).
2611 pub(crate) fn backend_type(&self, model: &RecordModel) -> proc_macro2::TokenStream {
2612 let (module, name) = self.kind().backend();
2613 model.framework(module, name)
2614 }
2615
2616 /// The record's VOCABULARY row for this database: `Record<Db>`, naming the row this record becomes
2617 /// in it and the comparison a predicate over that row takes.
2618 ///
2619 /// # It is a STORABILITY AUDIT, and that is the point rather than a side effect
2620 ///
2621 /// Every other emitted item keeps the dialect a parameter, so its column crossings are obligations
2622 /// deferred to a call site. This one names the backend concretely, and well-formedness at a
2623 /// concrete impl is checked THERE — so writing `<Row>Comparison<Sqlite>` here discharges every
2624 /// column's crossing at SQLite, at the `#[ingraph::record(…)]` that declared it. A column whose type
2625 /// has no carrier row in a database the declaration names is a compile error where the declaration
2626 /// is written, rather than at whatever call site first asked for a comparison.
2627 ///
2628 /// # The gate is what keeps DECLARE-MANY/BUILD-ONE
2629 ///
2630 /// Ungated, the audit would also make a declaration naming Postgres fail to compile in a build
2631 /// without the Postgres driver — the invariant `ingraph`'s `query::sql` states from the other
2632 /// side. Wrapped in `ingraph`'s conditional-expansion gate, the impl — and therefore the audit —
2633 /// exists per DECLARED ∩ COMPILED-IN backend: a declaration naming three databases in a build
2634 /// carrying one is audited against the one, and the other two have no impl at all, which is
2635 /// `E0277` for a party that asks and silence for one that does not.
2636 ///
2637 /// A build carrying TWO engines and choosing between them by an options file at runtime is the
2638 /// case this shape exists for: both gates are open, so both audits run, and every record it may
2639 /// store is proved storable in both before the process starts.
2640 ///
2641 /// # `Row` is what a NEIGHBOUR'S expansion reads, and it is why the member exists
2642 ///
2643 /// Every other name in this impl is reachable from the declaration that wrote it. The row's is not
2644 /// reachable from any OTHER declaration: it is per database and `<db>(row(rename = "…"))`
2645 /// moves it, so a record nesting through a `ref` holds a path to the target and nothing that names
2646 /// the target's row. Binding it here is what turns that into a projection —
2647 /// `<Target as Record<Sqlite>>::Row` — instead of a suffix an emitter would have to guess.
2648 ///
2649 /// # The era rule
2650 ///
2651 /// The same ground the entity binding stands on, plus one step. `Record` is the framework's
2652 /// vocabulary for what a `Transformer`'s row-form member answers, and it is settled; what the impl
2653 /// BINDS is the emitter's own output — the row and the `<Row>Comparison` written beside it — and
2654 /// the backend type, which is the declaration's own choice of database. Nothing here is a consumer
2655 /// type.
2656 fn vocabulary(&self, model: &RecordModel) -> proc_macro2::TokenStream {
2657 let record = &model.record;
2658 let row = self.name();
2659 let comparison = self.comparison_name();
2660 let backend = self.backend_type(model);
2661 let vocabulary = model.framework(&["transform"], "Record");
2662 let gate = model.framework(&["gate"], &self.kind().gate().to_string());
2663 // The ORDER this database sorts by. It is emitted HERE rather than on a capability trait of its
2664 // own, which is where the retired `Orderable` put it: a record's storability is ONE fact, and
2665 // stating it twice meant two predicates an emitter had to keep in step. This impl exists exactly
2666 // where the record persists, so the order's absence is the row's absence and there is no second
2667 // condition to drift.
2668 //
2669 // What it binds is the record's own order-by enum — the same type the wire face names — and the
2670 // per-database seat is what makes the word count and the LEVEL count two different numbers: a
2671 // term of that enum lowers through `<db>_term` into this database's `OrderTerm`, which
2672 // `OrderTerm::levels` then expands into the levels this dialect really sorts by. A citizen's one
2673 // word becomes four levels at a table family and stays one word on the wire, which is the
2674 // full-form law at this seam; a database-free type could not hold both readings.
2675 let order_by = model.order_by.safe();
2676 // A doc comment cannot ride a macro INVOCATION — `unused_doc_comments` refuses one, since
2677 // rustdoc documents no such item — so what this impl has to say is said here and the emission
2678 // carries only `#[automatically_derived]`, as every other trait impl does.
2679 quote! {
2680 #gate! {
2681 #[automatically_derived]
2682 impl #vocabulary<#backend> for #record {
2683 type Row = #row;
2684 type Comparison = #comparison<#backend>;
2685 type OrderBy = #order_by;
2686 }
2687 }
2688 }
2689 }
2690}
2691
2692impl PersistColumn {
2693 /// A row self as the accessor emitter reads a self.
2694 ///
2695 /// The row's name is the SAFE face — an accessor is Rust and a self called `bit-rate` has to
2696 /// reach one — and the projection is the DATABASE's `copy` claim rather than the domain field's.
2697 /// The two are different claims about different types: the same field may be a `BeU64` on one
2698 /// backend and a `Vec<u8>` on another, and a macro has no type information to bridge them.
2699 ///
2700 /// `Repeated` and `Optional` never appear. Those project a domain field through a framework trait;
2701 /// a stored self is whatever the database holds, and nullability is the schema's business rather
2702 /// than the accessor's.
2703 pub(crate) fn as_column(&self) -> Column {
2704 Column {
2705 name: self.name.safe().clone(),
2706 source: self.source.clone(),
2707 ty: self.ty().clone(),
2708 project: if self.copy {
2709 Projection::Copied
2710 } else {
2711 Projection::Borrowed
2712 },
2713 }
2714 }
2715}
2716
2717impl Column {
2718 /// One self's whole method family: its accessors, then — when the site allows it — its two
2719 /// mutators.
2720 ///
2721 /// `subject` is the noun phrase every doc line is built from, so the same shapes read correctly on
2722 /// a key ("the `media_id` step of the lineage path") and on a record ("the `tracks` field of this
2723 /// \[`Video`\]" — the brackets are escaped HERE and written literally THERE, since the link
2724 /// resolves in the consumer's crate, where `Video` exists).
2725 ///
2726 /// `mutable` is FALSE for a record's identity-bearing fields, which are set at construction. It is
2727 /// true everywhere else, key columns included — those are addresses being built.
2728 ///
2729 /// The two things it takes from its OWNER are spelled rather than reached through a model: the
2730 /// visibility to mirror, and the crate the projection traits are rooted at. What owns a column is
2731 /// not always a record — the value tier declares columns and no record at all — and a parameter
2732 /// that named one would have made this family a record's rather than a column's.
2733 ///
2734 /// `gate` is the field's own CONDITION, and it rides EVERY member rather than the group: an
2735 /// attribute governs the ONE item after it, so a `#[cfg]` written once in front of four methods
2736 /// would take the first away and leave three behind. See
2737 /// [`Condition::gate`](crate::model::Condition::gate); it is empty for every column that wrote no
2738 /// condition, which is what keeps an unconditional expansion identical to the one before the seat
2739 /// existed.
2740 pub(crate) fn methods(
2741 &self,
2742 vis: &syn::Visibility,
2743 krate: &syn::Path,
2744 subject: &str,
2745 mutable: bool,
2746 gate: &proc_macro2::TokenStream,
2747 ) -> proc_macro2::TokenStream {
2748 let Column {
2749 name, ty, project, ..
2750 } = self;
2751 // The names, from the one place they are shaped — see [`crate::method`] for why they are not
2752 // spelled here. A DESTRUCTURE rather than a value read field by field, so a member added there
2753 // is one this site has to acknowledge.
2754 let method::Family {
2755 value,
2756 borrow,
2757 slice,
2758 set,
2759 with,
2760 } = self.family(mutable);
2761
2762 // The projection the DECLARATION asked for. Nothing is inferred from the type's spelling — see
2763 // the module doc for why that had to stop.
2764 let accessors = match project {
2765 Projection::Repeated => slice.map(|slice| {
2766 let doc = leading(&format!("The {subject}, as a slice."));
2767 let repeated = framework(krate, &["project"], "Repeated");
2768 quote! {
2769 #gate
2770 #[doc = #doc]
2771 #[inline]
2772 #vis fn #slice(&self) -> &[<#ty as #repeated>::Item] {
2773 #repeated::as_slice(&self.#name)
2774 }
2775 }
2776 }),
2777 Projection::Optional => borrow.map(|borrow| {
2778 let doc = leading(&format!("The {subject}, by reference."));
2779 let optional = framework(krate, &["project"], "Optional");
2780 quote! {
2781 #gate
2782 #[doc = #doc]
2783 #[inline]
2784 #vis fn #borrow(&self) -> ::core::option::Option<&<#ty as #optional>::Item> {
2785 #optional::as_option(&self.#name)
2786 }
2787 }
2788 }),
2789 Projection::Borrowed | Projection::Copied => borrow.map(|borrow| {
2790 let doc = leading(&format!("The {subject}, by reference."));
2791 // Emitted only for a marked self, and only ever IN ADDITION to the borrow.
2792 let value = value.map(|value| {
2793 let doc = leading(&format!("The {subject}."));
2794 quote! {
2795 #gate
2796 #[doc = #doc]
2797 #[inline]
2798 #vis const fn #value(&self) -> #ty {
2799 self.#name
2800 }
2801 }
2802 });
2803 quote! {
2804 #value
2805
2806 #gate
2807 #[doc = #doc]
2808 #[inline]
2809 #vis const fn #borrow(&self) -> &#ty {
2810 &self.#name
2811 }
2812 }
2813 }),
2814 };
2815
2816 // A `copy` self's assignment drops nothing, so its mutators may be `const`.
2817 let constness = project.copies().then(|| quote!(const));
2818 let mutators = set.zip(with).map(|(set, with)| {
2819 let set_doc = leading(&format!("Set the {subject}."));
2820 let with_doc = leading(&format!("The same value with a different `{name}`."));
2821 quote! {
2822 #gate
2823 #[doc = #set_doc]
2824 #[inline]
2825 #vis #constness fn #set(&mut self, value: #ty) -> &mut Self {
2826 self.#name = value;
2827 self
2828 }
2829
2830 #gate
2831 #[doc = #with_doc]
2832 #[must_use]
2833 #[inline]
2834 #vis #constness fn #with(mut self, value: #ty) -> Self {
2835 self.#name = value;
2836 self
2837 }
2838 }
2839 });
2840
2841 quote! {
2842 #accessors
2843 #mutators
2844 }
2845 }
2846}
2847
2848impl Conversion {
2849 /// One column's value, as the declaration says to obtain it.
2850 ///
2851 /// `Into::into` appears only when the STORED type differs from the domain one. With no override
2852 /// the two are the same type, and a reflexive self would be noise a reader has to look
2853 /// through — and a `useless_conversion` lint for anyone whose build sees it.
2854 pub(crate) fn apply(
2855 &self,
2856 value: proc_macro2::TokenStream,
2857 converted: bool,
2858 ) -> proc_macro2::TokenStream {
2859 match self {
2860 Conversion::Infallible(path) => quote!(#path(#value)),
2861 // A plain `?`, so the record's declared error absorbs the function's through `From` — and a
2862 // pair that cannot is `E0277` AT THE `?`, naming that function's error. The ESCAPE is for
2863 // where that bound genuinely cannot hold; it is applied at the crossing, so a map whose
2864 // signature does not line up is `E0308` at the call rather than anywhere further along.
2865 Conversion::Fallible(fallible) => {
2866 let path = &fallible.path;
2867 match &fallible.escape {
2868 None => quote!(#path(#value)?),
2869 Some(escape) => quote! {
2870 ::core::result::Result::map_err(#path(#value), #escape)?
2871 },
2872 }
2873 }
2874 Conversion::Default if converted => quote!(::core::convert::Into::into(#value)),
2875 Conversion::Default => value,
2876 }
2877 }
2878}
2879
2880impl DatabaseKind {
2881 /// What this database's FAMILY answers differently about a row.
2882 ///
2883 /// The dispatch is here and the answers are in the two family modules, which is the split those
2884 /// files were always for. What it REPLACES is four functions: `sql::row` and `mongo::document`
2885 /// were the same function differing only in this value, and `sql::owns`/`mongo::owns` were a
2886 /// wrapper around [`DatabaseKind::is_sql`] and its negation. A database knows its own family, so
2887 /// nothing has to ask on its behalf.
2888 ///
2889 /// Only MONGO's answers depend on the model, and only for one reason: its derives are reached
2890 /// through the declarer's own crate path, which is a value the model carries. The SQL family
2891 /// reaches sqlx through that same path — but from inside a [`Mapping::Decode`] emitter, which is
2892 /// handed the model when it runs, so its own answers need nothing from the declaration.
2893 fn family(self, model: &RecordModel) -> Family {
2894 if self.is_sql() {
2895 sql::family()
2896 } else {
2897 mongo::family(model)
2898 }
2899 }
2900}