ingraph_codegen/method.rs
1//! Every method an emission declares, and the ONE place a derived name is shaped.
2//!
3//! A method's name comes from a COLUMN's — `x`, `x_ref`, `x_slice`, `set_x`, `with_x` — and a few
4//! are fixed beside them: the positional `new` on each address type and on each comparison, and
5//! one order-by resolver per database. Nothing about Rust keeps two of those apart. A `copy`
6//! column called `new` gives its address type a second `new`; a `copy` column called `set_x`
7//! beside a column called `x` gives the record two `set_x`; and a column called `x_ref` beside one
8//! called `set_x` gives it two `set_x_ref` with no marker involved at all.
9//!
10//! Each is `E0592`, and each lands INSIDE the expansion — the span is `#[ingraph::record(…)]`, which
11//! the author cannot edit, and the message never says which column caused it. So a front end
12//! refuses the declaration instead, and this module is what it asks.
13//!
14//! **A LIST of derived shapes kept in the front end would be a second copy of what [`crate::emit`]
15//! writes, and two copies of a derived-name list is how one of them drifts** — the same reason
16//! `ingraph-derive`'s column fence is a namespace rather than a list. Here the shapes have one
17//! home each: [`Member::name`] for the accessor family's suffixes, [`wire_method`] for the
18//! `__async_graphql_` prefix an emitted `#[Object]` face's functions wear, and — for the names a
19//! DERIVED INDEX mints from a field of its own — [`fan_door`], [`fold_accessor`] and [`Door::name`].
20//! Every emitter site calls one of them to build the ident it emits; nothing spells a suffix or a
21//! prefix anywhere else.
22//!
23//! What a shared function cannot fix is MEMBERSHIP — which of those names a given type really
24//! declares — because that follows the emitter's walk rather than any one name's shape. So it is
25//! not written twice either: it is asserted against the emission itself by
26//! `tests::the_enumeration_names_exactly_the_methods_the_emission_declares` — and by the derived
27//! index's own twin in [`crate::index`]'s `audits` — which read every inherent method back out of
28//! the tokens and demand the same list in the same order. A name the emitter grows and this module
29//! does not know about fails there.
30//!
31//! The enumeration is a STATEMENT ABOUT THE EMISSION, which is this crate's subject; the refusal
32//! is the front end's, which holds the spans to report at. That is the split [`crate::model`]
33//! already draws, and it is why nothing here pushes an error.
34
35use core::fmt;
36
37use quote::format_ident;
38
39use crate::model::{Column, DatabaseKind, Projection, RecordModel};
40
41#[cfg(test)]
42mod prefix_tests;
43
44/// Which member of a column's method family a name belongs to.
45///
46/// The whole vocabulary of derived names. A caller names one rather than spelling a suffix,
47/// because a suffix written twice is a suffix that can be written differently.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum Member {
50 /// `x` — the by-value accessor a `copy` column gets IN ADDITION to its borrow.
51 Value,
52 /// `x_ref` — the borrow.
53 Borrow,
54 /// `x_slice` — a `repeated` column's slice.
55 Slice,
56 /// `set_x` — the in-place setter.
57 Set,
58 /// `with_x` — the chaining builder.
59 With,
60}
61
62impl Member {
63 /// What this member is called over a column named `column`.
64 pub fn name(self, column: &syn::Ident) -> syn::Ident {
65 match self {
66 Self::Value => column.clone(),
67 Self::Borrow => format_ident!("{column}_ref"),
68 Self::Slice => format_ident!("{column}_slice"),
69 Self::Set => format_ident!("set_{column}"),
70 Self::With => format_ident!("with_{column}"),
71 }
72 }
73
74 /// What this member IS, for a message that has to tell two colliding names apart.
75 pub const fn what(self) -> &'static str {
76 match self {
77 Self::Value => "value accessor",
78 Self::Borrow => "borrow accessor",
79 Self::Slice => "slice accessor",
80 Self::Set => "setter",
81 Self::With => "builder",
82 }
83 }
84}
85
86/// The `__async_graphql_` prefix every FUNCTION an emitted `#[Object]` face declares wears — and
87/// every ARGUMENT such a function takes.
88///
89/// # The prefix names the BACKEND, and that is the ruling rather than a decoration
90///
91/// The user's ruling of 2026-08-13: *async-graphql 的都要加前缀,通过 rename 避免冲突,前缀用
92/// `__async_graphql_xxx` 因为以后可能支持更多 graphql 后端*.
93///
94/// So the Rust namespace is PER BACKEND. A second GraphQL binding mounted on the same emitted type
95/// mints `__smear_<name>` beside `__async_graphql_<name>` and the two cannot meet — where a shared
96/// `__<name>` would have made the first backend's face the reason the second one cannot be written,
97/// reported as `E0592` inside an expansion whose author cannot edit either half. The prefix is not
98/// the collision-proofing alone; it is WHOSE face this is, spelled into the ident.
99///
100/// The WIRE face is unmoved by any of it: the name a CLIENT reads is written beside the ident as
101/// `#[graphql(name = "…")]`, per item and never derived from a spelling — see `emit::wire`'s own
102/// note — so the ident is free to carry the backend's name and a schema cannot tell that it does.
103///
104/// # Why the wire face's Rust names are ugly on purpose
105///
106/// A method inside `#[Object]` is not a Rust API: nothing outside the expansion calls it, and it is
107/// reached through the schema. So the ident is free to be defensive, and it is: the prefix puts
108/// every generated function and argument in a namespace no declaration writes — the same vaccine
109/// the emission's own `__ingraph_*` locals already carry, applied at the one position that had
110/// none. `emit::wire`'s prelude note records what the class costs when it is not taken: a foreign
111/// macro's bare `None` captured by a declarer's `struct None`, reported at a `#[record(…)]` naming
112/// a type nobody in that file mentions.
113///
114/// Those LOCALS keep `__ingraph_` and are not swept into the backend's namespace, because they are
115/// a different question: a local is scoped to the body it is written in, so two backends' bodies
116/// cannot collide however they spell theirs, and what the prefix answers there is *whose crate
117/// wrote this*, which is the framework's rather than any binding's.
118///
119/// TYPES take no prefix, and that is the ruled other half: `<E>GraphqlOutput` and `<E>KeyOutput` are
120/// visible vocabulary a declaration names and an application mounts, so a mangled one would be an
121/// emitter's convention leaking into somebody else's code.
122///
123/// Here rather than beside either emitter, for this module's own reason: a derived name has ONE
124/// home, and a prefix written twice is a prefix that can be written differently. Every emitted face
125/// calls this — `emit::wire`'s two objects, `emit::queries`' three legs and their arguments,
126/// `interface::queries`' leg — so a change to the shape moves all of them at once, which is what
127/// made this sweep a one-line edit under a walk rather than a rename across the corpus.
128pub fn wire_method(name: &syn::Ident) -> syn::Ident {
129 // A prefixed name is never a keyword, so nothing has to put a raw prefix back — which is what
130 // makes `where` an argument this can be handed at all: `Ident::new` takes a keyword (a keyword is
131 // a legal identifier lexically), and `__async_graphql_where` is an ordinary ident.
132 //
133 // **A CORRECTION, measured.** This claimed `format_ident!` renders an `Ident` through
134 // `IdentFragment`, which drops a raw prefix, so a column called `r#type` would arrive as
135 // `__type`. It does not, at quote 1.0.47: the macro routes through
136 // `quote::__private::ident_maybe_raw`, which re-attaches the `r#` it stripped and hands
137 // `"__async_graphql_r#type"` to `Ident::new`, whose panic is *not a valid identifier* — measured
138 // by handing this function `Ident::new_raw("where", …)` and reading the panic at the
139 // `#[record(…)]`. So a RAW ident must not reach here; a caller that has one hands the plain
140 // spelling, which is what every caller does.
141 format_ident!("__async_graphql_{name}")
142}
143
144/// The `fan_<field>` WRITE DOOR a `fanout`-marked field of a derived index gets — one name, here
145/// rather than beside the emitter, for [`wire_method`]'s reason.
146///
147/// It is the ONE name the engine grammar mints into a declaration's own inherent impl, and it is
148/// derived from a FIELD, which is what puts it in this module: a `copy` field called `fan_title`
149/// beside a fanned `title` gives the index two `fan_title`, at a span the declaration cannot edit.
150/// The enumeration below is what lets a front end say so first, and it reads this function.
151pub fn fan_door(field: &syn::Ident) -> syn::Ident {
152 format_ident!("fan_{field}")
153}
154
155/// The `fold_by_<field>` accessor a SET election gets — what `semantics(fold = "…")` is spent on.
156///
157/// Beside [`fan_door`] and for its reason: a derived name has one home, and this one is derived from
158/// an elected field, so a `copy` field spelled like it collides on the declaration's own type.
159pub fn fold_accessor(field: &syn::Ident) -> syn::Ident {
160 format_ident!("fold_by_{field}")
161}
162
163/// WHICH of a derived index's RETRIEVE doors a name belongs to — the vocabulary the emitted read
164/// surface is spelled from.
165///
166/// [`Member`] one family over: a column's accessors are derived from a column's name, and these are
167/// derived from an ELECTION's, so the same rule applies to both — the suffix has one home, and a
168/// caller names a door rather than spelling `retrieve_keys_by_`. Every one of them lands on the
169/// declaration's own type, so every one of them can be reached by a field a declaration chose.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum Door {
172 /// TIER A — `retrieve_keys_by_<field>`, or `retrieve_keys` for the unelected full-text subject.
173 Keys,
174 /// TIER B — `retrieve_by_<field>`, or `retrieve` for that same subject.
175 Whole,
176 /// BY KEY — `get_<field>`, this entity's own stored embedding, checked.
177 Own,
178 /// BY EXAMPLE — `retrieve_similar_by_<field>`.
179 Similar,
180 /// SET-SIMILARITY — `retrieve_keys_by_<field>_with`, the door a `list(embedding)` election gets.
181 Set,
182 /// SET-SIMILARITY BY EXAMPLE — `retrieve_similar_by_<field>_with`, the by-example door asked
183 /// with the example's WHOLE SET.
184 SimilarSet,
185 /// FUSED — `vector_fuse`, every route of one modality asked at once. UNELECTED, because the door
186 /// is the TIER's rather than any one route's.
187 Fused,
188 /// FUSED BY EXAMPLE — `vector_fuse_similar`, at the tier's own key.
189 FusedSimilar,
190 /// FUSED, ONE FANNED SLOT — `vector_fuse_by_<field>`, every LEG of one election asked at once.
191 ///
192 /// ELECTED where [`Fused`](Self::Fused) is not, and that is the fractal read one level down: this
193 /// door is one FIELD's, its routes being the stores that field is written to rather than the
194 /// fields a declaration elected.
195 FusedLegs,
196 /// FUSED, ONE FANNED SLOT, BY EXAMPLE — `vector_fuse_similar_by_<field>`.
197 FusedLegsSimilar,
198}
199
200impl Door {
201 /// What this door is called over the election named `election`.
202 pub fn name(self, election: &syn::Ident) -> syn::Ident {
203 match self {
204 Self::Keys => format_ident!("retrieve_keys_by_{election}"),
205 Self::Whole => format_ident!("retrieve_by_{election}"),
206 Self::Own => format_ident!("get_{election}"),
207 Self::Similar => format_ident!("retrieve_similar_by_{election}"),
208 // The SET door is the tier-A name plus one suffix, which is how the emission writes it: the
209 // two are one road asked with `m` vectors instead of one, and a reader scanning the impl sees
210 // the pair rather than two unrelated spellings.
211 Self::Set => format_ident!("{}_with", Self::Keys.name(election)),
212 // The same suffix, over the by-example name — so the two `_with` doors read as one word
213 // spent twice rather than as two spellings a caller has to learn separately.
214 Self::SimilarSet => format_ident!("{}_with", Self::Similar.name(election)),
215 // The two fused doors take NO suffix, because they are not about one election. `name` is
216 // still where they are spelled, so a collision reports them like every other door.
217 Self::Fused => format_ident!("vector_fuse"),
218 Self::FusedSimilar => format_ident!("vector_fuse_similar"),
219 // The SLOT-grain fused pair takes the `_by_<field>` suffix every per-election door takes,
220 // because it IS about one election — a fanned slot is a tier whose routes are stores, and the
221 // field it is about is exactly what tells one of these doors from another.
222 Self::FusedLegs => format_ident!("vector_fuse_by_{election}"),
223 Self::FusedLegsSimilar => format_ident!("vector_fuse_similar_by_{election}"),
224 }
225 }
226
227 /// The TIER PAIR over one subject: an election's, or the ONE subject a full-text index answers
228 /// under — which is UNSUFFIXED, because a slot is `(field × engine)` and is therefore already the
229 /// answer to *which field*.
230 ///
231 /// The pair is the only part of this vocabulary with an unelected spelling, and it is written as a
232 /// PAIR rather than as a per-variant answer for exactly that reason: the four doors below it are
233 /// minted per election — a by-key read names the column it reads — so a shape that admitted `None`
234 /// there would be a partial function with no total caller.
235 pub fn pair(election: Option<&syn::Ident>) -> (syn::Ident, syn::Ident) {
236 match election {
237 Some(field) => (Self::Keys.name(field), Self::Whole.name(field)),
238 None => (format_ident!("retrieve_keys"), format_ident!("retrieve")),
239 }
240 }
241
242 /// What this door IS, for a message that has to tell two colliding names apart.
243 const fn what(self) -> &'static str {
244 match self {
245 Self::Keys => "ranked-keys door",
246 Self::Whole => "whole-entities door",
247 Self::Own => "by-key read",
248 Self::Similar => "by-example door",
249 Self::Set => "set-similarity door",
250 Self::SimilarSet => "set-similarity by-example door",
251 Self::Fused => "fused door",
252 Self::FusedSimilar => "fused by-example door",
253 Self::FusedLegs => "fanned-slot fused door",
254 Self::FusedLegsSimilar => "fanned-slot fused by-example door",
255 }
256 }
257}
258
259/// The payload of [`Origin::Door`]: which door, and the election it answers about.
260///
261/// The election is [`None`] for the ONE unelected subject — a full-text index's unsuffixed pair —
262/// and [`Some`] everywhere else, which is exactly the split [`Door::pair`] draws.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct DoorOrigin {
265 /// Which door.
266 pub door: Door,
267 /// The election it answers about, or [`None`] for the unelected pair.
268 pub election: Option<syn::Ident>,
269}
270
271/// The payload of [`Origin::Column`]: which column, and which member of its family.
272///
273/// One member of one column's family, under the name that column carries IN THE OWNING TYPE: a
274/// scoped rename moves the method with the column it renames.
275///
276/// Named for the origin rather than sharing the variant's name, because [`Column`] is the model's
277/// own type and this module reads it. Fields are `pub` and constructed by literal, which is what
278/// every model struct this crate carries does — [`Emitted`] below is the nearest one.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub struct ColumnOrigin {
281 /// The column, as its own type names it.
282 pub column: syn::Ident,
283 /// Which of the family this is.
284 pub member: Member,
285}
286
287/// What produced an emitted method's name.
288///
289/// Comparable, because two emitted methods with the same origin are the downstream of a DUPLICATE
290/// COLUMN NAME rather than of two columns meeting: every member of the two families collides at
291/// once, so a front end that reported them would repeat another rule's finding five times over.
292#[derive(Debug, Clone, PartialEq, Eq)]
293pub enum Origin {
294 /// The type's own positional `new` — a name the emitter fixes rather than one a declaration
295 /// chose.
296 Constructor,
297 /// A derived index's `key_ref` — the borrow of the upstream key it carries, and a fixed name for
298 /// the reason the constructor's is.
299 BorrowedKey,
300 /// One member of one column's family — see [`ColumnOrigin`].
301 Column(ColumnOrigin),
302 /// One name of the FUSE family — a package accessor, a question row or the column vocabulary's
303 /// projection, on the type the tier minted it for. See [`FuseOrigin`].
304 Fuse(FuseOrigin),
305 /// One database's order-by resolver — `sqlite_column`.
306 Resolver(DatabaseKind),
307 /// The order-by's `direction` — its other half, and the half no database refines.
308 Direction,
309 /// One database's order-by LOWERING — `sqlite_order_by`, which consumes both halves above.
310 Lowering(DatabaseKind),
311 /// The order-by's rename-proof IDENTITY — the name a per-database rename cannot move, and the
312 /// only input a cursor's signature takes from a term.
313 Identity,
314 /// One database's order-by TERM — `sqlite_term`, which pairs the identity with this database's
315 /// column, the direction and the column's nullability.
316 Term(DatabaseKind),
317 /// The order-by's id TAIL — `complete`, which is no database's, because which column holds the id
318 /// is the record's and no rename moves it.
319 Complete,
320 /// One database's plural entry point — `find_sqlite`.
321 Finder(DatabaseKind),
322 /// One database's plural entry point inside a read transaction — `find_sqlite_snapshot`.
323 Snapshot(DatabaseKind),
324 /// One database's single entry point — `get_sqlite`.
325 Getter(DatabaseKind),
326 /// One database's plain WRITE — `insert_sqlite`.
327 Inserter(DatabaseKind),
328 /// One database's KEYED REPLACE — `upsert_sqlite`.
329 Upserter(DatabaseKind),
330 /// One database's REMOVAL at an address — `delete_sqlite`.
331 Deleter(DatabaseKind),
332 /// One database's REMOVAL over a predicate — `delete_sqlite_where`.
333 ///
334 /// Beside the getter's road rather than beside it in name, and that is the roster's own grammar:
335 /// the address door and the predicate door are two verbs on the read side too — `get_<db>` and
336 /// `find_<db>` — so the removal half has two as well.
337 Purger(DatabaseKind),
338 /// The wire OUTPUT object's own two members — the row's id, and its whole address. Fixed names
339 /// rather than a declaration's, as the constructor's is.
340 Address,
341 /// One member of the wire ARGUMENT object — the filter, the ceiling, the order, a page argument.
342 /// Fixed names too: they mirror the engine's find surface, which no declaration renames.
343 Argument,
344 /// The QUERY UNIT's own root FIELDS — the single and the list. Fixed names, built from the
345 /// record's own, so no declaration chooses either.
346 RootField,
347 /// A `fanout` field's WRITE DOOR — `fan_<field>`, named after the field whose engines it writes.
348 ///
349 /// The FIELD rides the variant because the sentence has to name it: two names meeting here are a
350 /// declaration's own field and another of its fields' fan, and a message that said only *the fan
351 /// door* would leave the reader to find out whose.
352 Fan(syn::Ident),
353 /// A SET election's DECLARED FOLD — `fold_by_<field>`, likewise named after its election.
354 Fold(syn::Ident),
355 /// One of a derived index's RETRIEVE doors — see [`DoorOrigin`].
356 Door(DoorOrigin),
357 /// One `delegate(fn …)` entry — the method the DECLARATION restated, at the name it wrote.
358 ///
359 /// The ident rides the variant and IS the declared token, which is what makes this the one derived
360 /// family whose refusal points at an author's own word rather than at the field it was built from:
361 /// a delegate's name is not derived from anything, it is restated, so the caret belongs on the
362 /// restatement.
363 Delegate(syn::Ident),
364 /// A vocabulary MIRROR's restated-variant roster — `VARIANTS`.
365 ///
366 /// An associated CONST rather than a method, and it is enumerated all the same: Rust's value
367 /// namespace holds consts and functions together, so a `fn VARIANTS` beside it is a duplicate
368 /// definition exactly as a second `fn remote` would be. What the enumeration is FOR is the names
369 /// an expansion puts in a scope, and this is one of them.
370 Roster,
371 /// A vocabulary MIRROR's single materialization gate — `remote()`.
372 ///
373 /// A fixed name rather than a declaration's, as the constructor's is: every rendering, every bind
374 /// and every delegated call reads through it, so the mode has one word for it and no knob moves it.
375 Materialization,
376 /// ONE variant's predicate on a vocabulary — `is_rgb24`, built from the variant's own name.
377 ///
378 /// The VARIANT rides the variant because the sentence has to name it: a delegated entry meeting
379 /// `is_bayer` has met a specific variant's question, and a message saying only *a predicate* would
380 /// leave the reader to work out whose.
381 Predicate(syn::Ident),
382 /// A MongoDB document's own EXTRACTION — `from_document`, the bson twin of the `FromRow` impl the
383 /// SQL family emits.
384 ///
385 /// It is here and its SQL counterpart is not, and the difference is the ITEM rather than the
386 /// backend: `from_row` lands in a TRAIT impl, which this enumeration does not walk, where the bson
387 /// twin is INHERENT — the trait it would implement is the framework's, and the era rule is what
388 /// that is over. So it occupies a name in the declaring scope and has to be enumerated like every
389 /// other name the emission puts there.
390 Extraction,
391}
392
393impl Origin {
394 /// The DECLARED token a refusal about this name points at, or `None` for a name no declaration
395 /// chose.
396 ///
397 /// The method's own ident is not that token: [`Member::name`] builds it through `format_ident!`,
398 /// whose span is the macro's call site — which is exactly the span `E0592` already reports at
399 /// and the reason this rule exists.
400 pub const fn column(&self) -> Option<&syn::Ident> {
401 match self {
402 Self::Column(origin) => Some(&origin.column),
403 // The one derived family whose ident IS an author's token: a delegate's name is RESTATED
404 // rather than built, so the caret belongs on the restatement the declaration wrote.
405 Self::Delegate(method) => Some(method),
406 Self::Constructor
407 | Self::BorrowedKey
408 | Self::Resolver(_)
409 | Self::Direction
410 | Self::Lowering(_)
411 | Self::Identity
412 | Self::Term(_)
413 | Self::Complete
414 | Self::Finder(_)
415 | Self::Snapshot(_)
416 | Self::Getter(_)
417 | Self::Inserter(_)
418 | Self::Upserter(_)
419 | Self::Deleter(_)
420 | Self::Purger(_)
421 | Self::Address
422 | Self::Argument
423 | Self::RootField
424 // The three a derived index adds are fixed names too, and their idents carry a declared span
425 // for a reason that does NOT make them this token: `fan_title` is derived FROM `title`, so a
426 // caret on `title` would send an author to rename the field whose fan is correct. The other
427 // side of such a collision is a column, and the front end reads its token instead.
428 | Self::Fan(_)
429 | Self::Fold(_)
430 | Self::Door(_)
431 | Self::Extraction
432 // The vocabulary tier's three, by the same argument. `VARIANTS` and `remote` are fixed words
433 // no declaration chose; `is_rgb24` is derived FROM the variant `Rgb24`, so a caret there would
434 // send an author to rename the variant whose predicate is correct. The other side of such a
435 // collision is a DELEGATED entry, whose ident is a restatement the author wrote — and the
436 // reader below takes that one instead.
437 | Self::Roster
438 | Self::Materialization
439 | Self::Predicate(_)
440 // A fuse name is derived from the index and a knob's fixed word — the same argument as the
441 // fan's: no declared token IS the name.
442 | Self::Fuse(_) => None,
443 }
444 }
445}
446
447impl fmt::Display for Origin {
448 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
449 match self {
450 Self::Constructor => f.write_str("the type's own constructor"),
451 Self::BorrowedKey => f.write_str("the borrow of the upstream key it carries"),
452 Self::Column(origin) => write!(
453 f,
454 "the `{}` column's {}",
455 origin.column,
456 origin.member.what()
457 ),
458 Self::Resolver(kind) => write!(f, "the `{}` order-by resolver", kind.as_str()),
459 Self::Direction => f.write_str("the order-by's direction accessor"),
460 Self::Lowering(kind) => write!(f, "the `{}` ordering lowering", kind.as_str()),
461 Self::Identity => f.write_str("the order-by's identity accessor"),
462 Self::Term(kind) => write!(f, "the `{}` ordering term", kind.as_str()),
463 Self::Complete => f.write_str("the order-by's id tail"),
464 Self::Finder(kind) => write!(f, "the `{}` plural query", kind.as_str()),
465 Self::Snapshot(kind) => write!(
466 f,
467 "the `{}` plural query in a read transaction",
468 kind.as_str()
469 ),
470 Self::Getter(kind) => write!(f, "the `{}` single query", kind.as_str()),
471 Self::Inserter(kind) => write!(f, "the `{}` insert", kind.as_str()),
472 Self::Upserter(kind) => write!(f, "the `{}` keyed replace", kind.as_str()),
473 Self::Deleter(kind) => write!(f, "the `{}` removal at an address", kind.as_str()),
474 Self::Purger(kind) => write!(f, "the `{}` removal over a predicate", kind.as_str()),
475 Self::Address => f.write_str("the output object's own address member"),
476 Self::Argument => f.write_str("the argument object's own member"),
477 Self::RootField => f.write_str("the query unit's own root field"),
478 Self::Fan(field) => write!(f, "the `{field}` field's fan door"),
479 Self::Fold(field) => write!(f, "the `{field}` election's declared fold"),
480 Self::Door(origin) => match &origin.election {
481 Some(field) => write!(f, "the `{field}` election's {}", origin.door.what()),
482 None => write!(f, "the {}", origin.door.what()),
483 },
484 Self::Delegate(method) => write!(f, "the delegated `{method}`"),
485 Self::Roster => f.write_str("the mirror's own restated-variant roster"),
486 Self::Materialization => f.write_str("the mirror's own upstream materialization"),
487 Self::Predicate(variant) => write!(f, "the `{variant}` variant's predicate"),
488 Self::Extraction => f.write_str("the document's own extraction"),
489 Self::Fuse(origin) => write!(
490 f,
491 "the fuse family's `{}` on `{}`",
492 origin.member, origin.on
493 ),
494 }
495 }
496}
497
498/// The payload of [`Origin::Fuse`]: WHICH minted type carries the name, and the member it is.
499///
500/// The type is named because the fuse family mints many packages beside one declaration, and a
501/// collision message that said only "the fuse family's `ceiling`" could not say which package's.
502#[derive(Debug, Clone, PartialEq, Eq)]
503pub struct FuseOrigin {
504 /// The minted type the method sits on.
505 pub on: syn::Ident,
506 /// The member the method reads, writes or constructs.
507 pub member: syn::Ident,
508}
509
510/// Which of a record's emitted types a method lands on.
511///
512/// An IDENTITY rather than a name, and the distinction is load-bearing: a `row(rename = "…")` can
513/// give a row the record's own name, at which point grouping by name would merge two types' method
514/// sets and report their columns as colliding with each other. That collision is a different rule,
515/// with a refusal of its own, and this keeps the two apart.
516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
517pub enum Owner {
518 /// The `*Key`.
519 Key,
520 /// The `*Lineage`, for a record that has one.
521 Lineage,
522 /// The DECLARATION itself — the record a node's expansion sits on, the value an entity's does,
523 /// the fragment a field tier's does, or the enum a vocabulary's does. One variant for all of them,
524 /// because what it distinguishes is the declared type from the types an expansion mints beside it,
525 /// and every emitted type here is one of those.
526 Record,
527 /// One database's row.
528 Row(DatabaseKind),
529 /// One database's comparison.
530 Comparison(DatabaseKind),
531 /// The wire argument object.
532 Input,
533 /// One type of the FUSE FAMILY — an options package, a question package or the column
534 /// vocabulary; the row's `owner_name` says which, and is the namespace the collision walk keys.
535 Fuse,
536 /// The wire output object.
537 Output,
538 /// The wire ADDRESS object — `<E>KeyOutput`, whose wire face's methods sit beside its accessors.
539 KeyOutput,
540 /// The wire QUERY UNIT — `<E>Queries`, whose only methods are the root fields it answers.
541 Queries,
542 /// The wire filter.
543 Filter,
544 /// The wire order-by.
545 OrderBy,
546}
547
548/// One method an emission declares, on one emitted type.
549#[derive(Debug, Clone)]
550pub struct Emitted {
551 /// Which type the method lands on.
552 pub owner: Owner,
553 /// What that type is CALLED, for the sentence a refusal writes.
554 pub owner_name: syn::Ident,
555 /// What the method is called.
556 pub name: syn::Ident,
557 /// What produced the name.
558 pub origin: Origin,
559}
560
561/// The members ONE column's family declares at one site.
562///
563/// A struct of options rather than a list, because the emitter needs each name in its own token
564/// position and looking one up by tag would need a fallible read of an infallible fact. Adding a
565/// member is a change every site that DESTRUCTURES this has to acknowledge, which is the property
566/// worth having.
567pub(crate) struct Family {
568 /// The by-value accessor, for a `copy` column.
569 pub(crate) value: Option<syn::Ident>,
570 /// The borrow, for every projection but `repeated`.
571 pub(crate) borrow: Option<syn::Ident>,
572 /// The slice, for a `repeated` column.
573 pub(crate) slice: Option<syn::Ident>,
574 /// The setter, where the site admits mutation.
575 pub(crate) set: Option<syn::Ident>,
576 /// The builder, likewise.
577 pub(crate) with: Option<syn::Ident>,
578}
579
580impl Family {
581 /// Every member this family really declares, in emission order.
582 pub(crate) fn members(self) -> impl Iterator<Item = (Member, syn::Ident)> {
583 [
584 (Member::Value, self.value),
585 (Member::Borrow, self.borrow),
586 (Member::Slice, self.slice),
587 (Member::Set, self.set),
588 (Member::With, self.with),
589 ]
590 .into_iter()
591 .filter_map(|(member, name)| name.map(|name| (member, name)))
592 }
593}
594
595impl Column {
596 /// The members this column's family declares at a site that does or does not admit mutation.
597 ///
598 /// The one answer to that question. [`Column::methods`](crate::emit) destructures this value and
599 /// writes the idents it finds, so a check over these names is a check over the names really
600 /// emitted rather than over a second reading of the same rule.
601 pub(crate) fn family(&self, mutable: bool) -> Family {
602 let name = &self.name;
603 let repeated = matches!(self.project, Projection::Repeated);
604 Family {
605 value: self.project.copies().then(|| Member::Value.name(name)),
606 borrow: (!repeated).then(|| Member::Borrow.name(name)),
607 slice: repeated.then(|| Member::Slice.name(name)),
608 set: mutable.then(|| Member::Set.name(name)),
609 with: mutable.then(|| Member::With.name(name)),
610 }
611 }
612
613 /// This column's family as the methods it declares on the type called `owner_name`.
614 pub(crate) fn emitted(
615 &self,
616 owner: Owner,
617 owner_name: &syn::Ident,
618 mutable: bool,
619 ) -> Vec<Emitted> {
620 self
621 .family(mutable)
622 .members()
623 .map(|(member, name)| Emitted {
624 owner,
625 owner_name: owner_name.clone(),
626 name,
627 origin: Origin::Column(ColumnOrigin {
628 column: self.name.clone(),
629 member,
630 }),
631 })
632 .collect()
633 }
634}
635
636impl DatabaseKind {
637 /// The order-by resolver this database's column names are answered through — `sqlite_column`.
638 pub(crate) fn order_resolver(self) -> syn::Ident {
639 format_ident!("{}_column", self.as_str())
640 }
641
642 /// The ordering LOWERING for this database — `sqlite_order_by`, which walks the terms a query
643 /// wrote and ends them with the key.
644 ///
645 /// Named for the database rather than typed by a dialect, exactly as the resolver above is: what
646 /// the name picks is which column NAMES are rendered, and `<db>(rename)` is the whole of
647 /// what makes two databases differ about that. The dialect the text is bracketed for stays a
648 /// parameter, so this reads the same way an emitted `<Row>Comparison<DB>` does.
649 pub(crate) fn order_lowering(self) -> syn::Ident {
650 format_ident!("{}_order_by", self.as_str())
651 }
652
653 /// The ordering TERM for this database — `sqlite_term`, which is what a page renders its
654 /// `ORDER BY` and its keyset from.
655 ///
656 /// Per database like the resolver, and for its reason: what the name picks is which column names
657 /// are rendered, and NULLABILITY rides with them because it is a schema fact per database too.
658 pub(crate) fn order_term(self) -> syn::Ident {
659 format_ident!("{}_term", self.as_str())
660 }
661
662 /// This database's plural entry point — `find_sqlite`.
663 pub(crate) fn finder(self) -> syn::Ident {
664 format_ident!("find_{}", self.as_str())
665 }
666
667 /// This database's plural entry point inside a read transaction — `find_sqlite_snapshot`.
668 pub(crate) fn snapshot_finder(self) -> syn::Ident {
669 format_ident!("find_{}_snapshot", self.as_str())
670 }
671
672 /// This database's single entry point — `get_sqlite`.
673 pub(crate) fn getter(self) -> syn::Ident {
674 format_ident!("get_{}", self.as_str())
675 }
676
677 /// This database's plain WRITE — `insert_sqlite`.
678 pub(crate) fn inserter(self) -> syn::Ident {
679 format_ident!("insert_{}", self.as_str())
680 }
681
682 /// This database's KEYED REPLACE — `upsert_sqlite`.
683 pub(crate) fn upserter(self) -> syn::Ident {
684 format_ident!("upsert_{}", self.as_str())
685 }
686
687 /// This database's REMOVAL at an address — `delete_sqlite`.
688 pub(crate) fn deleter(self) -> syn::Ident {
689 format_ident!("delete_{}", self.as_str())
690 }
691
692 /// This database's REMOVAL over a predicate — `delete_sqlite_where`.
693 ///
694 /// The suffix rides the deleter's own name for the reason the SET door's `_with` rides the
695 /// ranked-keys door's: the two are one verb asked about a predicate instead of an address, and a
696 /// reader scanning the impl should see the pair rather than two unrelated spellings. It is the
697 /// same shape [`snapshot_finder`](Self::snapshot_finder) already has one verb over.
698 pub(crate) fn purger(self) -> syn::Ident {
699 format_ident!("{}_where", self.deleter())
700 }
701
702 /// The CONDITIONAL-EXPANSION gate this database's CONCRETE impls ride — `if_sqlite`, reached on
703 /// `ingraph`'s `__private::gate` shelf.
704 ///
705 /// The shelf and never the public name the same macro also carries, for the reason every framework
706 /// name is reached there: an emission depends on the shelf rather than on where an item lives.
707 ///
708 /// Mechanical from [`as_str`](Self::as_str), which is the word the declaration writes and the word
709 /// the framework's feature carries, so the three cannot drift into naming different backends. What
710 /// a gate does — and why an emitted `#[cfg]` asks a different question — is `ingraph`'s crate note,
711 /// under *The four gates*.
712 pub(crate) fn gate(self) -> syn::Ident {
713 format_ident!("if_{}", self.as_str())
714 }
715}
716
717impl RecordModel {
718 /// Every method this model's emission declares, in EMISSION ORDER.
719 ///
720 /// The order is the emitter's own walk — the key, the lineage, the record, then each database's
721 /// row and comparison, then the wire faces — so a front end reporting a collision can name the
722 /// earlier of the two as the one already there.
723 ///
724 /// Types are told apart by [`Owner`] rather than by name, for the reason that enum records.
725 pub fn emitted_methods(&self) -> Vec<Emitted> {
726 let constructor = |owner: Owner, owner_name: &syn::Ident| Emitted {
727 owner,
728 owner_name: owner_name.clone(),
729 name: format_ident!("new"),
730 origin: Origin::Constructor,
731 };
732 let mut emitted = vec![constructor(Owner::Key, &self.key.name)];
733 // An address is being BUILT, so its columns take the mutator pair whether or not they bear
734 // identity on the record.
735 emitted.extend(
736 self
737 .key
738 .columns()
739 .flat_map(|column| column.emitted(Owner::Key, &self.key.name, true)),
740 );
741 // A lineage that is a CHOICE declares neither: an enum is built by naming a variant, so there
742 // is no `new` to collide with and no column to reach an accessor. `Lineage::path` is empty for
743 // one, which is what makes this one walk rather than two.
744 if let Some(lineage) = self
745 .lineage
746 .as_ref()
747 .filter(|lineage| !lineage.path().is_empty())
748 {
749 emitted.push(constructor(Owner::Lineage, &lineage.name));
750 emitted.extend(
751 lineage
752 .path()
753 .iter()
754 .flat_map(|column| column.emitted(Owner::Lineage, &lineage.name, true)),
755 );
756 }
757 // The record carries NO constructor, and its identity-bearing fields carry no mutators. A
758 // REWRITE declares a family of its own — one reader per manifest field and no mutator, since
759 // nothing here can assign into a foreign type — so the enumeration forks where the emission
760 // does, on the same predicate and through the same `Family`.
761 emitted.extend(self.fields.iter().flat_map(|field| {
762 if self.remote.is_some() {
763 return crate::remote::wrapped_family(field)
764 .members()
765 .map(|(member, name)| Emitted {
766 owner: Owner::Record,
767 owner_name: self.record.clone(),
768 name,
769 origin: Origin::Column(ColumnOrigin {
770 column: field.column.name.clone(),
771 member,
772 }),
773 })
774 .collect::<Vec<_>>();
775 }
776 field
777 .column
778 .emitted(Owner::Record, &self.record, !field.identity)
779 }));
780 for database in self.persist.iter().flat_map(|persist| &persist.backends) {
781 let kind = database.kind();
782 let row = database.name();
783 emitted.extend(
784 database
785 .columns()
786 .iter()
787 .flat_map(|column| column.as_column().emitted(Owner::Row(kind), row, false)),
788 );
789 // The EXTRACTION, after the row's own accessors and before its comparison — the emitter's own
790 // walk, where the decode is appended to the row's inherent impl. MongoDB's alone: the SQL
791 // family's decode is a `FromRow` impl, which is a trait item and occupies no name in the
792 // declaring scope. `extracts` is the one predicate, asked here and at the emission.
793 if database.extracts() {
794 emitted.push(Emitted {
795 owner: Owner::Row(kind),
796 owner_name: row.clone(),
797 name: format_ident!("from_document"),
798 origin: Origin::Extraction,
799 });
800 }
801 let comparison = database.comparison_name();
802 emitted.push(constructor(Owner::Comparison(kind), comparison));
803 // The comparison's members are LAYER 1 — the record field's name — so this enumeration reads
804 // the same ident the emission does. It used to read the per-database column name, which made
805 // a `<db>(rename)` move a method the emitter no longer moves.
806 emitted.extend(database.compared(self).into_iter().map(|column| {
807 let column = column.member().clone();
808 Emitted {
809 owner: Owner::Comparison(kind),
810 owner_name: comparison.clone(),
811 name: Member::Borrow.name(&column),
812 origin: Origin::Column(ColumnOrigin {
813 column,
814 member: Member::Borrow,
815 }),
816 }
817 }));
818 }
819 emitted.extend(self.order_by_methods());
820 emitted.extend(self.wire_methods());
821 // The typed FACE, last, because it is emitted last: an entry point names the row and the
822 // comparison the walk above has already declared. One set per SQL database that can carry a
823 // query — [`RecordModel::queryable`] is the one place that decides which, and it decides for the
824 // WRITE verbs too: `SqlWrite` is `SqlQuery`'s subtrait, so a row with no query face has no write
825 // face either.
826 emitted.extend(self.queryable().into_iter().flat_map(|database| {
827 let kind = database.kind();
828 [
829 (kind.finder(), Origin::Finder(kind)),
830 (kind.snapshot_finder(), Origin::Snapshot(kind)),
831 (kind.getter(), Origin::Getter(kind)),
832 (kind.inserter(), Origin::Inserter(kind)),
833 (kind.upserter(), Origin::Upserter(kind)),
834 (kind.deleter(), Origin::Deleter(kind)),
835 (kind.purger(), Origin::Purger(kind)),
836 ]
837 .map(|(name, origin)| Emitted {
838 owner: Owner::Record,
839 owner_name: self.record.clone(),
840 name,
841 origin,
842 })
843 }));
844 emitted
845 }
846
847 /// The methods the ORDER-BY declares — none at all for a record stored nowhere.
848 ///
849 /// Split out of [`wire_methods`](Self::wire_methods) with the type itself: an ordering term is a
850 /// fact about the STORED columns, so a record with no wire face declares every one of these and a
851 /// record with no `persist(…)` declares none. See `emit::graphql`'s `RecordModel::ordering` for
852 /// what each half is gated on.
853 fn order_by_methods(&self) -> Vec<Emitted> {
854 let mut emitted = Vec::new();
855 if self.persist.is_none() {
856 return emitted;
857 }
858 let order_by = self.order_by.safe();
859 emitted.extend(
860 self
861 .persist
862 .iter()
863 .flat_map(|persist| &persist.backends)
864 .map(|database| Emitted {
865 owner: Owner::OrderBy,
866 owner_name: order_by.clone(),
867 name: database.kind().order_resolver(),
868 origin: Origin::Resolver(database.kind()),
869 }),
870 );
871 // Unconditional where the resolvers are per database, and last where they are first, because
872 // that is the emitter's own walk: a term's column is what storage renames and its direction is
873 // not, so the direction is emitted once whether a record declares three databases or none.
874 emitted.push(Emitted {
875 owner: Owner::OrderBy,
876 owner_name: order_by.clone(),
877 name: format_ident!("direction"),
878 origin: Origin::Direction,
879 });
880 // The PAGE vocabulary, in the emitter's own walk: the identity, then one term per SQL database,
881 // then the id tail. All three ride the same law as the lowering below — a written order can be
882 // completed only where the id is stored, and only the SQL family has a clause machine to render
883 // it — so a record missing either gets the resolver and the direction and nothing else.
884 let paged = self.id_column_stored().is_some()
885 && self
886 .persist
887 .iter()
888 .flat_map(|persist| &persist.backends)
889 .any(|database| database.kind().is_sql());
890 if paged {
891 emitted.push(Emitted {
892 owner: Owner::OrderBy,
893 owner_name: order_by.clone(),
894 name: format_ident!("identity"),
895 origin: Origin::Identity,
896 });
897 emitted.extend(
898 self
899 .persist
900 .iter()
901 .flat_map(|persist| &persist.backends)
902 .filter(|database| database.kind().is_sql())
903 .map(|database| Emitted {
904 owner: Owner::OrderBy,
905 owner_name: order_by.clone(),
906 name: database.kind().order_term(),
907 origin: Origin::Term(database.kind()),
908 }),
909 );
910 emitted.push(Emitted {
911 owner: Owner::OrderBy,
912 owner_name: order_by.clone(),
913 name: format_ident!("complete"),
914 origin: Origin::Complete,
915 });
916 }
917 // The LOWERING, last, because it consumes both halves above. SQL only — the clause machine it
918 // walks is the SQL family's — and only where the id is stored, which
919 // [`RecordModel::id_column_stored`] is the one place that decides.
920 if self.id_column_stored().is_some() {
921 emitted.extend(
922 self
923 .persist
924 .iter()
925 .flat_map(|persist| &persist.backends)
926 .filter(|database| database.kind().is_sql())
927 .map(|database| Emitted {
928 owner: Owner::OrderBy,
929 owner_name: order_by.clone(),
930 name: database.kind().order_lowering(),
931 origin: Origin::Lowering(database.kind()),
932 }),
933 );
934 }
935 emitted
936 }
937
938 /// The methods the WIRE faces declare — none at all for a record with no `graphql(…)`.
939 ///
940 /// The filter's names are the field's INPUT face where one is exposed and the column's own
941 /// otherwise, because that is what the emitter writes. A check that read the record's Rust names
942 /// instead would miss every collision an input rename opens and invent ones it closes.
943 ///
944 /// The OUTPUT object's are [`GraphqlField::accessor`](crate::model::GraphqlField::accessor) —
945 /// LAYER 2, the one layer a wire word moves — for the same reason stated the other way round: a
946 /// schema rename moves no accessor, and the emitted MEMBER is layer 1 and moves for nothing, so a
947 /// check on either would be about a method the emission does not declare.
948 fn wire_methods(&self) -> Vec<Emitted> {
949 let mut emitted = Vec::new();
950 let Some(graphql) = &self.graphql else {
951 return emitted;
952 };
953 let Some(backend) = graphql.backends.first() else {
954 return emitted;
955 };
956 let output = graphql.output.safe();
957 // The object's own address members lead, because the emission writes them first — and they carry
958 // an origin of their own, so a field landing on either name is a COLLISION reported at the
959 // declaration rather than a duplicate `id_ref` inside the expansion. The `id` member is the
960 // framework's only where the declaration writes none: see `RecordModel::wire_writes_id`.
961 let address: &[&str] = if self.wire_writes_id() {
962 &["id", "key"]
963 } else {
964 &["key"]
965 };
966 emitted.extend(address.iter().map(|member| Emitted {
967 owner: Owner::Output,
968 owner_name: output.clone(),
969 name: Member::Borrow.name(&format_ident!("{member}")),
970 origin: Origin::Address,
971 }));
972 emitted.extend(backend.fields().iter().map(|field| {
973 let column = field.accessor().clone();
974 Emitted {
975 owner: Owner::Output,
976 owner_name: output.clone(),
977 name: Member::Borrow.name(&column),
978 origin: Origin::Column(ColumnOrigin {
979 column,
980 member: Member::Borrow,
981 }),
982 }
983 }));
984 // The ARGUMENT object, between the output and the filter because that is where its impl sits.
985 // Its ORDER pair leads, and rides the same predicate the type's `order` field does: a record
986 // with no term type has no order to write and no page to ask for.
987 let input = graphql.input.safe();
988 let argument = |name: &syn::Ident, member: Member| Emitted {
989 owner: Owner::Input,
990 owner_name: input.clone(),
991 name: member.name(name),
992 origin: Origin::Argument,
993 };
994 let paged: &[&str] = if self.orderable() {
995 let order = format_ident!("order");
996 emitted.extend([
997 argument(&order, Member::With),
998 argument(&order, Member::Slice),
999 ]);
1000 &["first", "last", "after", "before", "skip"]
1001 } else {
1002 &[]
1003 };
1004 for name in ["filter", "limit"].iter().chain(paged) {
1005 let name = format_ident!("{name}");
1006 emitted.extend([
1007 argument(&name, Member::With),
1008 argument(&name, Member::Borrow),
1009 ]);
1010 }
1011 let filter = graphql.filter.safe();
1012 for column in self.stored_columns() {
1013 let (rust, _, _) = backend.filter_field(column);
1014 emitted.extend([Member::With, Member::Borrow].map(|member| Emitted {
1015 owner: Owner::Filter,
1016 owner_name: filter.clone(),
1017 name: member.name(&rust),
1018 origin: Origin::Column(ColumnOrigin {
1019 column: rust.clone(),
1020 member,
1021 }),
1022 }));
1023 }
1024 // The ADDRESS object's ACCESSORS — layer 2, the Rust read road, under the members' own domain
1025 // names, and the one family this face never had: a caller outside the declaring crate could not
1026 // read a key's members in Rust at all, the substrate being `pub(crate)` and the wire methods
1027 // being the wire's.
1028 //
1029 // HERE rather than beside the wire methods below, because that is the emitter's own walk: an
1030 // accessor is an ordinary inherent impl and lands with the faces, where the `#[Object]` blocks
1031 // ride the binding gate after them. No rename word reaches a key column, so a name here is the
1032 // column's own and the family is the column's own — a `copy` one gets its value accessor beside
1033 // the borrow.
1034 let key_output = graphql.key_output.safe();
1035 emitted.extend(
1036 self
1037 .key
1038 .columns()
1039 .flat_map(|column| column.emitted(Owner::KeyOutput, key_output, false)),
1040 );
1041 // **LAYER 1 ON THE WIRE, UNDER THE PREFIX**, last because the two `#[Object]` blocks are emitted
1042 // last — and the whole reason this enumeration has to carry them is the collision rule: the
1043 // output object's wire methods are named after the MEMBERS, so a declaration exposing a field
1044 // called `key` beside the framework's address member is a duplicate method inside an expansion
1045 // its author cannot edit, and this list is what lets the front end name the pair at the
1046 // declaration instead.
1047 //
1048 // [`wire_method`] is what the emitter spells them through, so it is what this reads them back
1049 // as: the prefix is INJECTIVE, so which declarations collide does not move — but a refusal has
1050 // to name the method rustc would have reported, and after the pin that method is
1051 // `__async_graphql_key`.
1052 //
1053 // They cannot collide with the ACCESSORS above, and that is the three-layer law holding rather
1054 // than luck: layer 2 wears the borrow suffix and no prefix, so `__async_graphql_checksum`
1055 // sits beside `checksum_ref` whatever either was renamed to.
1056 emitted.extend(address.iter().map(|member| Emitted {
1057 owner: Owner::Output,
1058 owner_name: output.clone(),
1059 name: wire_method(&format_ident!("{member}")),
1060 origin: Origin::Address,
1061 }));
1062 emitted.extend(backend.fields().iter().map(|field| {
1063 // The SOURCE and not the accessor: a wire method is layer 1, which no word moves.
1064 let column = field.source.clone();
1065 Emitted {
1066 owner: Owner::Output,
1067 owner_name: output.clone(),
1068 name: wire_method(&column),
1069 origin: Origin::Column(ColumnOrigin {
1070 column,
1071 member: Member::Value,
1072 }),
1073 }
1074 }));
1075 // The ADDRESS object's own wire methods, which cannot collide with the accessors above: those
1076 // are layer 2 under the borrow suffix and wear no prefix, so `__async_graphql_media_id` sits
1077 // beside `media_id_ref`.
1078 emitted.extend(self.key.columns().map(|column| Emitted {
1079 owner: Owner::KeyOutput,
1080 owner_name: key_output.clone(),
1081 name: wire_method(&column.name),
1082 origin: Origin::Column(ColumnOrigin {
1083 column: column.name.clone(),
1084 member: Member::Value,
1085 }),
1086 }));
1087 // The QUERY UNIT's root fields, last because the unit is emitted last — and only where one is
1088 // emitted at all, `RecordModel::wire_query_row` being the one place that decides. Its two names
1089 // are built from the RECORD's own rather than from any column, so nothing a declaration writes
1090 // can land on either; they are enumerated for the reason every other emitted name is, which is
1091 // that this list is a statement about the emission rather than about the collisions it happens
1092 // to be able to have.
1093 emitted.extend(self.root_field_methods());
1094 emitted
1095 }
1096
1097 /// The two methods a query unit declares — the single always, the list where the record has an
1098 /// order to page by.
1099 ///
1100 /// The predicates are `emit::queries`' own, read here rather than restated: a name this enumerates
1101 /// and the emission does not write fails
1102 /// `tests::the_enumeration_names_exactly_the_methods_the_emission_declares`, which is what keeps
1103 /// the two in step.
1104 fn root_field_methods(&self) -> Vec<Emitted> {
1105 use heck::ToSnakeCase as _;
1106
1107 if self.wire_query_row().is_none() {
1108 return Vec::new();
1109 }
1110 let owner_name = crate::model::default_queries_name(&self.record);
1111 let snake = self.record.to_string().to_snake_case();
1112 let mut emitted = vec![Emitted {
1113 owner: Owner::Queries,
1114 owner_name: owner_name.clone(),
1115 name: wire_method(&format_ident!("{snake}")),
1116 origin: Origin::RootField,
1117 }];
1118 if self.orderable() && !self.ordered_columns().is_empty() {
1119 emitted.push(Emitted {
1120 owner: Owner::Queries,
1121 owner_name,
1122 name: wire_method(&format_ident!("{snake}_list")),
1123 origin: Origin::RootField,
1124 });
1125 }
1126 emitted
1127 }
1128}