Skip to main content

ingraph_codegen/emit/
queries.rs

1//! The QUERY UNIT: `<E>Queries`, the root fields one record answers, as one mountable type.
2//!
3//! ```text
4//! type Query {                    # the graph root's fold
5//!   reel(id: Int!): Reel          # the SINGLE   — ReelQueries::__async_graphql_reel
6//!   reels(orderBy: […], first: Int, …, where: ReelFilter): ReelsConnection
7//!                                 # the LIST     — ReelQueries::__async_graphql_reel_list
8//!   takeLineage(reelId: Int!, orderBy: […], first: Int, …, where: TakeFilter): TakesConnection
9//!                                 # the LINEAGE  — TakeQueries::__async_graphql_take_lineage
10//! }
11//! ```
12//!
13//! # Why a UNIT rather than fields on some root
14//!
15//! Two derives cannot read each other's tokens, and the root is written by a third. So the record's
16//! own expansion writes what only it knows — which columns, which row, which database, which order
17//! terms — onto a type of its own, and the ROOT folds units. `MergedObject` is what makes the fold a
18//! GraphQL object again: a member's fields land at the root's level, so the schema a client reads has
19//! no unit in it at all.
20//!
21//! The join between the two ends is [`Graphql::Query`](../../../ingraph/trait.Graphql.html), which
22//! this file binds and `graph::query` projects. Nobody parses anybody's declaration.
23//!
24//! # THE DOOR, and why the resolver holds no connection
25//!
26//! `wire_trio.rs` measured the wall to its floor: async-graphql demands `Send` of every resolver
27//! future, sqlx implements `Acquire<'c>` for `&'c mut Connection` at ONE lifetime, and a
28//! `Send`-bounded future asks for it at two — so a resolver that reaches a borrowed connection is
29//! *implementation of `sqlx::Acquire` is not general enough*, at any database, behind any number of
30//! helpers. `&Pool` is the surface that passes.
31//!
32//! So the emitted resolver takes `ingraph`'s `SqlDoor<Db>` out of `ctx.data` and hands the engine
33//! `door.pool()`. The door is found by its TYPE, which is why the emission spells the database the
34//! record's own `persist(…)` block named: a schema serving two stores installs two doors and each
35//! record reaches its own.
36//!
37//! # The ID argument crosses, and it has to
38//!
39//! `id:` is the framework's only typed INPUT here, and the declaration's id type may have no wire
40//! form of its own — the corpus alone carries eleven records whose id is a `u128`, which no crate
41//! gives an `InputType`. So the argument is `<IdTy as ToGraphqlInput>::Input` and the body crosses
42//! it back, exactly as the output object returns `<Ty as ToGraphqlOutput>::Output<'_>`. Both maps
43//! are keyed on the TYPE, so `type Uuid7 = u128` reaches the carrier through the alias and the form
44//! a client SENDS is the form the same row is RETURNED as.
45//!
46//! The map is the CARRIER AXIS's, which is where it belongs: a wide id is the same operand a wide
47//! COLUMN is, and a declaring crate that gave its own id type a filter face has already written the
48//! row this position reads.
49//!
50//! # What each leg is CONDITIONAL on, and what is HELD
51//!
52//! | leg | emitted when | why |
53//! |---|---|---|
54//! | single | the record has a wire face AND a queryable row that raises onto the wire | it is the gather lane, which every stored record has |
55//! | list | the same, plus an `<E>OrderBy` face | a page needs a written order, and the order-by input object is what a client writes one with |
56//! | either leg's `where` | the same — [`RecordModel::wire_filters`] IS that condition, read once | the argument the predicate rides on, and the face and crossing that resolve it |
57//! | lineage | the same, plus a lineage whose every step is a stored column | the ancestry is the argument list, and a step no table holds is one no predicate can name |
58//!
59//! The `where` argument rides BOTH paged legs, and on one condition rather than two: the face and
60//! the crossing it needs are the record's, so a record that can be filtered at all can be filtered
61//! under an ancestry as well.
62//!
63//! **The LINEAGE leg's two walls are both down, and the second fell where nobody was looking.** A
64//! lineage walk is a read under a PREDICATE — *the takes whose `reel_id` is 1* — and the machinery it
65//! needs was the `where` leg's:
66//!
67//! * ~~the record's own `<E>Filter` → `<E><Db>Comparison` crossing is not emitted~~ **it is**, at the
68//!   concrete backend and inside its gate — see [`super::cross`], which is what ruled the shape
69//!   `comparison_traits` ended on;
70//! * ~~the filter kinds hold their operands `pub(crate)` and publish no builder~~ — **the operands
71//!   are `pub(crate)` and the BUILDER was always public.** Every kind ships `new()`, a `Default` and
72//!   a `with_*` per slot, and an external crate already spends them. What was actually missing is one
73//!   surface narrower: a filter reaches an emitter as the PROJECTION
74//!   `<<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter`, and an inherent builder is
75//!   unreachable through a name the emitter is forbidden to resolve — the projection layer is
76//!   type-blind on purpose, and `ScalarFilter<T>` and `Nullable<ScalarFilter<T>>` take an equality
77//!   operand through different expressions. `ingraph`'s `EqualsFilter` is the one line that serves
78//!   both, and it is what this leg mints its predicate with.
79//!
80//! `ingraph/tests/wire_trio.rs` keeps its hand-written witness — the semantic executed against a real
81//! store before there was an emitter to ask for it — and `ingraph/tests/wire_lineage.rs` is the same
82//! walk through the EMITTED leg.
83//!
84//! # The naming — both fields are the PUBLISHED name, one of them in the plural
85//!
86//! The single is `<camel>` — the ruled spelling, with no `ById` suffix — over the record's PUBLISHED
87//! output type name, so `output(rename = "…")` moves the field with the object it returns.
88//!
89//! The LIST is that same published name PLURALISED and lowered at its initial: `Reel` ⇒ `reels`,
90//! `VideoTrack` ⇒ `videoTracks`. The word is English rather than a suffix — `<camel>List` was this
91//! emitter's holding spelling and is gone — and it comes from [`crate::plural`], a compile-time
92//! pluraliser on the expansion side, because `heck` knows casing and nothing knows language. The
93//! table name, which IS a plural a declaration already wrote, stays out of it: that is a STORAGE
94//! fact, and a schema that read it would vary with a deployment's storage choice.
95//!
96//! A declaration that disagrees with the pluraliser corrects the WORD, not the field:
97//! `graphql(plural = "corpora")` states this entity's plural, so the next reader of it — a
98//! connection, an aggregate — inherits one correction rather than asking for a second.
99//!
100//! # The one refusal the plural brings, and the silence it is about
101//!
102//! A derived plural can come back as the word it was given: `Media`, `Series`, `Dimensions` have no
103//! distinct plural in the pluraliser's answer. Emitting it would publish the PAGE under the SINGLE's
104//! own name, and that is not a compile error anywhere downstream — measured against async-graphql
105//! 7.2.1, two fields of one object sharing a name build a schema in which the SDL carries the last
106//! registration and the resolver answers from the first, so a client reads one type and receives
107//! another.
108//!
109//! So the derived case is refused by name at the declaration, through
110//! [`RecordModel::degenerate_plural`], and the refusal teaches the word. A DECLARED plural equal to
111//! the singular is not refused: the rule guards silence, not choice.
112//!
113//! # The PAGE has two names of its own, and they are a THREE-TIER TOWER over the plural
114//!
115//! The user's ruling of 2026-08-13: *跟着复数走, 有层级关系, 如果用户主动 rename connection 的名字,
116//! 那么 connection 的名字用用户指定的, 我们是 tiered, 一层覆盖一层* — the page names FOLLOW THE
117//! PLURAL, in tiers, each layer covering the one below it.
118//!
119//! | tier | the word | who writes it |
120//! |---|---|---|
121//! | base | the derived plural — `Reel` ⇒ `ReelsConnection` / `ReelsEdge` | the pluraliser |
122//! | over it | `graphql(plural = "corpora")` ⇒ `CorporaConnection` / `CorporaEdge` | the declaration, ONCE |
123//! | on top | `graphql(connection(rename = "CorpusPage"))` ⇒ `CorpusPage` | the declaration, per name |
124//!
125//! **One word moves three names**, which is the whole of what the middle tier buys — the user's
126//! *一起跟*. `plural = "corpora"` is read by the list FIELD, by the connection and by the edge, so a
127//! declaration that corrects English once gets `corpora(…): CorporaConnection` and never
128//! `corpora(…): CorpusesConnection`. That is one authority rather than three readers of it: the word
129//! is [`super::wire::published_plural`]'s, resolved in one place, and this file spells it in two
130//! cases (a field's lowered initial, a type's raised one) rather than deriving it twice.
131//!
132//! The base is the PLURAL and not the Relay Cursor Connections specification's `<Node>Connection`,
133//! and the trade is real: tooling that finds a page by the NODE's stem sees a name it does not
134//! recognise. The ruling made that trade once, for every record, and each emitted marker's own doc
135//! is where it is priced.
136//!
137//! The TOP tier is unchanged in mechanism — `graphql(connection(rename = "…"), edge(rename = "…"))`
138//! over async-graphql's `ConnectionNameType`/`EdgeNameType` hooks, per record, each independent of
139//! the other.
140//!
141//! What the tower costs the rest of this file is one thing worth naming: `DefaultConnectionName`
142//! renders the SINGULAR-based word, so there is no declaration whose page this emitter can leave to
143//! the library, and [`page_names`](RecordModel::page_names) now mints a marker pair for every record
144//! that HAS a page. That is not vocabulary growth — what it writes is private to the face's own
145//! `const _: () = { … }`, the two paged legs' return types being the only things that ever name a
146//! marker. So the tower adds nothing to a declaring scope and nothing to the emitted-name refusal.
147//!
148//! # The `__async_graphql_` pins apply here first
149//!
150//! Every function and every ARGUMENT wears the backend's prefix through
151//! [`wire_method`](crate::method::wire_method) — this is the emission that gives the argument half of
152//! that pin its first violator to guard against — and every wire-visible name is written out as
153//! `#[graphql(name = "…")]`, per item, never derived from an ident.
154
155use quote::{format_ident, quote};
156
157use crate::{
158  method::wire_method,
159  model::{DatabaseBackend, Graphql, RecordModel, default_queries_name},
160};
161
162#[cfg(test)]
163mod batch_lane_tests;
164#[cfg(test)]
165mod page_name_tests;
166#[cfg(test)]
167mod page_tower_tests;
168#[cfg(test)]
169mod tests;
170
171/// One ancestry column, as the LINEAGE leg spends it: an argument, and the operand that argument
172/// becomes.
173///
174/// Five spellings of one column, and each is read from its own source rather than derived from a
175/// neighbour — the same discipline [`super::graphql::FilterRow`] states, because these are the same
176/// three layers. What a client writes, what the Rust parameter is called, which builder sets it,
177/// what the operand is held at, and what guards it are five different questions about one column.
178struct LineageStep {
179  /// The name a client writes this step under — the filter face's own name for the column, so a
180  /// document scoping by an ancestry and one filtering on it spell the column identically.
181  field: String,
182  /// The Rust parameter, `__async_graphql_`-pinned like every other argument this file emits.
183  parameter: syn::Ident,
184  /// The `<E>Filter` builder that sets this column.
185  with: syn::Ident,
186  /// The filter guarding this column, already projected through the marker layer — the type
187  /// `EqualsFilter` is asked of.
188  filter: proc_macro2::TokenStream,
189  /// The type the operand is held at: the column's declared wire type, which is both what the
190  /// argument crosses into and the parameter `EqualsFilter` is spelled at.
191  wire: syn::Type,
192}
193
194/// A published TYPE name as a root FIELD names it — [`crate::emit::lower_initial`], re-exported into
195/// this file's own vocabulary so the two page names and the field read as one tower.
196use crate::emit::{lower_initial as root_field, raise_initial as page_type};
197
198impl RecordModel {
199  /// The database this record's ROOT FIELDS are served from, and `None` where it has none.
200  ///
201  /// Two conditions, and each is a thing a resolver could not otherwise do: the database carries a
202  /// QUERY face — [`queryable`](Self::queryable) is the one place that decides which do — and its
203  /// row RAISES onto the wire, [`wire_rows`](Self::wire_rows) being the one place that decides that.
204  /// A record stored only in MongoDB has the second and not the first, and a record with a wire face
205  /// and no `persist(…)` block has neither.
206  ///
207  /// The FIRST such database rather than all of them, and the choice is the schema's own law: a
208  /// client must never see a field that varies with a deployment's storage choice, so a record
209  /// stored in two databases answers its root fields from one — the one its declaration wrote first.
210  pub(crate) fn wire_query_row(&self) -> Option<&DatabaseBackend> {
211    self.graphql.as_ref()?;
212    let raises = self.wire_rows();
213    self
214      .queryable()
215      .into_iter()
216      .find(|database| raises.iter().any(|row| row.kind() == database.kind()))
217  }
218
219  /// Whether this record's `<E>Filter` is SPENT on the wire — the one predicate the filter's face,
220  /// its crossing and the `where` argument are each emitted under.
221  ///
222  /// # The face rides the leg that spends it, and that is the whole of the condition
223  ///
224  /// `<E>Filter` names the DECLARATION's own types at every field, so its wire face demands
225  /// `InputType` of each one — and [`super::wire`]'s note carries what such a demand costs when it
226  /// cannot be made conditional: a `where` clause naming only concrete types is a trivial bound,
227  /// which stable rustc refuses at the item declaring it, so there is no way to write *this impl
228  /// applies where it can hold*. What is left is to emit it exactly where something ASKS for it.
229  ///
230  /// Nothing is lost by that. async-graphql registers the types REACHABLE from the schema root, so
231  /// an input object no argument names never reaches an SDL at all — a face emitted for a record
232  /// with no list resolver would be an obligation with no reader. And the crossing is the same
233  /// question one layer down: a column whose operand cannot enter storage without a converter the
234  /// declaration did not write is `E0277` at the crossing, and a record nothing queries has no
235  /// business being asked.
236  ///
237  /// So the condition is the LIST leg's, read here rather than restated: the record answers a page
238  /// from some database, and it has an order to write that page in.
239  pub(crate) fn wire_filters(&self) -> bool {
240    self.wire_query_row().is_some() && self.orderable() && !self.ordered_columns().is_empty()
241  }
242
243  /// The name the PAGE would be published under when it is the SINGLE's own name and no declaration
244  /// chose it — the silence a front end refuses, and `None` when there is nothing to refuse.
245  ///
246  /// # What the answer is, and why it is a name rather than a `bool`
247  ///
248  /// `Some(field)` is *both root fields would be called `field`*, so the refusal can quote the word
249  /// a client would have read. The front end writes the sentence, this answers the fact — the
250  /// division [`RecordModel::emitted_types`](crate::model::RecordModel::emitted_types) already
251  /// draws, and for its reason: a list of what an emission does kept on the other side of the crate
252  /// boundary is a copy, and copies drift.
253  ///
254  /// # THREE conditions, and each one is load-bearing
255  ///
256  /// * **the list leg is EMITTED** — [`Self::wire_filters`], whose own note carries that this
257  ///   predicate IS the leg's, read once rather than restated. A record with no page has no plural
258  ///   to spend, and demanding a word for a field nobody emits would tax a declaration for a
259  ///   schema it does not publish. What that leaves open is the DECLARATION carrying a degenerate
260  ///   word into a later reader — a connection, an aggregate — and that reader will ask this same
261  ///   question when it lands, because the condition is what moves rather than the rule.
262  /// * **nothing was DECLARED** — a written `plural = "media"` is a choice, and the rule guards
263  ///   silence. The user's ruling states it in those words: the refusal is about a word nobody
264  ///   chose, not about a word somebody did.
265  /// * **the two fields would COLLIDE** — asked on the emitted field NAMES rather than on the words
266  ///   behind them, because the collision is a fact about the schema. The initial is lowered on both
267  ///   sides by the same act, so this compares what a client would actually read.
268  pub fn degenerate_plural(&self) -> Option<String> {
269    let graphql = self.graphql.as_ref()?;
270    if graphql.plural.is_some() || !self.wire_filters() {
271      return None;
272    }
273    let single = root_field(&super::wire::published_output(graphql, self));
274    let page = root_field(&super::wire::published_plural(graphql, self));
275    (page == single).then_some(single)
276  }
277
278  /// The unit's DECLARATION — outside the binding gate, like every other emitted wire type.
279  ///
280  /// It has to be: `Graphql::Query` is bound in an UNGATED impl, so a type that existed only where
281  /// async-graphql does would leave that binding naming nothing in every other build. The face —
282  /// the `#[Object]` impl — is what rides the gate, which is the same split
283  /// [`super::wire`] already draws for the output object.
284  ///
285  /// `Default` because the ROOT is built from one: an emitted `<Root>Query` derives its own, and a
286  /// derive over a tuple of units is what makes `Schema::build(<Root>Query::default(), …)` the whole
287  /// of an application's construction. `Copy` and `Debug` beside it are the unit's free ones.
288  pub(super) fn queries_type(&self) -> proc_macro2::TokenStream {
289    if self.graphql.is_none() || self.wire_query_row().is_none() {
290      return proc_macro2::TokenStream::new();
291    }
292    let vis = &self.vis;
293    let record = &self.record;
294    let name = default_queries_name(record);
295    let doc = super::leading(&format!(
296      "The root fields a [`{record}`] answers — one row by its id, and a page of them.\n\nMounted by \
297       folding it into a graph's root query; it holds nothing and reads its store through the door \
298       the schema was built with."
299    ));
300    quote! {
301      #[doc = #doc]
302      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::marker::Copy, ::core::default::Default)]
303      #vis struct #name;
304    }
305  }
306
307  /// The unit's FACE: `#[Object]` over the trio's shipped legs, inside the binding gate AND this
308  /// database's own.
309  ///
310  /// Both gates, because both halves are named: `#[Object]` is async-graphql's and the engine call
311  /// names one dialect's row, its cursor value and its finder. A build with the binding and without
312  /// the dialect has the unit and no face, and the root that mounts it says so — `E0277` at the
313  /// projection, naming the trait the fold demands.
314  pub(super) fn queries_face(&self) -> proc_macro2::TokenStream {
315    let Some(graphql) = self.graphql.as_ref() else {
316      return proc_macro2::TokenStream::new();
317    };
318    let Some(database) = self.wire_query_row() else {
319      return proc_macro2::TokenStream::new();
320    };
321    let name = default_queries_name(&self.record);
322    let ag = self.framework(&[], "async_graphql");
323    let shelf = self.vendored("async_graphql");
324    let single = self.single_leg(graphql, database);
325    let list = self.list_leg(graphql, database);
326    let lineage = self.lineage_leg(graphql, database);
327    // The markers ride the PAGED LEGS, and the legs themselves are what say so: a record with no
328    // page has nothing that could name one, and a marker nobody names is `dead_code` inside an
329    // expansion its author cannot edit. Asking the emitted legs rather than re-deriving their
330    // conditions is what keeps the two from ever disagreeing.
331    //
332    // BOTH are asked, though the lineage's guards are the list's plus an ancestry, so a non-empty
333    // lineage implies a non-empty list today. Stating the disjunction anyway costs nothing and
334    // removes the reasoning step: a later round that loosens the list leg's condition finds the
335    // markers already following whatever names them.
336    let names = self.page_names(graphql, !list.is_empty() || !lineage.is_empty());
337    let sdl = name.to_string();
338    let gate = self.framework(&["gate"], &database.kind().gate().to_string());
339    let prelude = super::wire::prelude();
340    quote! {
341      #gate! {
342        const _: () = {
343          #prelude
344
345          #names
346
347          #[#ag::Object(crate = #shelf, name = #sdl)]
348          impl #name {
349            #single
350            #list
351            #lineage
352          }
353        };
354      }
355    }
356  }
357
358  /// The Rust markers the page's two SDL names are spelled through — `<E>ConnectionName` and
359  /// `<E>EdgeName` — for every record that HAS a page, and nothing where there is none.
360  ///
361  /// `paged` is EITHER paged leg's own presence, handed in by the caller that has just emitted them
362  /// rather than re-derived here. A record with no page could still have written the words — the
363  /// entries are parsed for every wire face — and a marker nothing names is `dead_code` reported
364  /// inside an expansion its author cannot edit.
365  ///
366  /// # The word is the TOWER's, and this is the one place it is resolved
367  ///
368  /// Three tiers, each covering the one below — the module note carries the ruling in the user's own
369  /// words. The BASE is [`published_plural`](super::wire::published_plural) with its initial raised:
370  /// the same resolved word the list FIELD is named from, read from the same function, so a
371  /// `plural = "corpora"` moves the field and both type names together and there is no second
372  /// derivation to drift. The TOP is the declaration's own `connection`/`edge` word, which wins
373  /// outright and independently — a record may move the page and leave the edge on the tower's base.
374  ///
375  /// # Minted ALWAYS now, and `#222`'s L-4 is why that is still honest
376  ///
377  /// That ruling refused to mint markers *nothing names* — the vocabulary's first zombie. Both
378  /// conditions it named are met and neither was weakened: the paged legs NAME these, and the
379  /// unconditional minting is forced rather than chosen — `DefaultConnectionName` renders
380  /// `<Node>Connection` over the node's SINGULAR type name, which the tower's base is not, so there
381  /// is no declaration this emitter can leave to the library. What changed is the emission's default
382  /// word; what did not change is that every marker written here has a reader in the same const.
383  ///
384  /// # They are PRIVATE TO THIS CONST, and that is the whole of their scoping story
385  ///
386  /// The only things that ever name one are the two paged legs' return types, inside the same
387  /// `const _: () = { … }`. So they are not vocabulary a declaring crate can see, cannot collide with
388  /// a declaration's types, and need no entry in [`emitted_types`](RecordModel::emitted_types) —
389  /// which is the list of what an expansion puts into a scope, and these go into no scope at all. The
390  /// `__async_graphql_` pin has nothing to say about them either: it governs emitted FUNCTIONS and
391  /// ARGUMENTS, and
392  /// the emitted TYPES it exempts are exempt because they are visible vocabulary — these are the
393  /// opposite case, invisible entirely.
394  fn page_names(&self, graphql: &Graphql, paged: bool) -> proc_macro2::TokenStream {
395    if !paged {
396      return proc_macro2::TokenStream::new();
397    }
398    let ag = self.framework(&[], "async_graphql");
399    // THE TOWER'S BASE, resolved once for both names: the list field's own plural, raised at its
400    // initial. Asking `published_plural` here rather than re-pluralising the record is what makes
401    // one `plural = "…"` move the field, the page and the edge together.
402    let base = page_type(&super::wire::published_plural(graphql, self));
403    let marker = |declared: Option<&String>, word_suffix: &str, hook: &str, what: &str| {
404      let word = declared.map_or_else(|| format!("{base}{word_suffix}"), ToOwned::to_owned);
405      let name = format_ident!("{}{word_suffix}Name", self.record);
406      let hook = self.framework(&["graphql"], hook);
407      let doc = super::leading(&if declared.is_some() {
408        format!(
409          "What the schema calls {what} of [`{record}`]s — `{word}`, the word the declaration \
410           wrote.\n\nThis is the naming tower's TOP: it covers the plural-built word outright, so a \
411           `plural = \"…\"` beside it moves the other names and not this one. It also exits the \
412           Relay Cursor Connections spelling, and with it the automatic recognition Relay, Apollo \
413           and schema codegen give a page: those tools find a connection by the \
414           `<Node>Connection`/`<Node>Edge` shape rather than by its fields. That is the trade the \
415           knob exists to make, and it is made per record.",
416          record = self.record
417        )
418      } else {
419        format!(
420          "What the schema calls {what} of [`{record}`]s — `{word}`, built from this record's \
421           PLURAL, which is the one word its list field is named from as well.\n\nThe Relay Cursor \
422           Connections specification spells this over the NODE's name; this framework spells it over \
423           the plural, so one declaration's page reads as one phrase and a `plural = \"…\"` \
424           correcting the English moves the field and both type names at once. Tooling that finds a \
425           page by the node's stem rather than by its fields sees a name it does not recognise: that \
426           is the trade, made once for every record. `connection(rename = \"…\")` and \
427           `edge(rename = \"…\")` are the tier above this one.",
428          record = self.record
429        )
430      });
431      // The NODE parameter is unused, and it has to be: the hook hands a node's type in so a name
432      // can be built from it AT RUNTIME, and this emitter has already resolved one at expansion
433      // time — out of the record's plural, which a node's type name does not carry. It is still
434      // NAMED rather than `_`, so the signature reads as the trait's own.
435      quote! {
436        #[doc = #doc]
437        struct #name;
438
439        impl #hook for #name {
440          fn type_name<__IngraphNode: #ag::OutputType>() -> ::std::string::String {
441            ::std::borrow::ToOwned::to_owned(#word)
442          }
443        }
444      }
445    };
446    let connection = marker(
447      graphql.connection.as_ref(),
448      "Connection",
449      "ConnectionNameType",
450      "a page",
451    );
452    let edge = marker(graphql.edge.as_ref(), "Edge", "EdgeNameType", "one edge");
453    quote!(#connection #edge)
454  }
455
456  /// The two type arguments a paged leg's `Connection<…>` closes with — this record's own pair of
457  /// markers, always.
458  ///
459  /// ALWAYS, and the library's `DefaultConnectionName`/`DefaultEdgeName` are named nowhere in this
460  /// file any more: they render `<Node>Connection` over the node's SINGULAR type name, and the ruled
461  /// default is the PLURAL. So the emission names the tower's resolution in every case, and
462  /// [`Self::page_names`] is the one place the word inside it is decided.
463  ///
464  /// ONE pair per RECORD rather than one per leg, which is a correctness property and not a saving:
465  /// the list and the lineage page the same record, so they must return the same two SDL types. The
466  /// lineage leg closed on the library's defaults before this round — invisible while the default
467  /// was the singular and both legs agreed on it, and a second page type for one record the moment
468  /// a declaration renamed anything.
469  fn page_name_arguments(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
470    let connection = format_ident!("{}ConnectionName", self.record);
471    let edge = format_ident!("{}EdgeName", self.record);
472    (quote!(#connection), quote!(#edge))
473  }
474
475  /// **THE SINGLE** — `<camel>(id:)`, in TWO LANES, and a miss is `null` rather than a refusal.
476  ///
477  /// It reads through the ID-GATHER lane rather than through `get`, and the difference is what the
478  /// batch costs: `rows` takes a SLICE of ids and answers in one statement, so a loader asking for a
479  /// hundred keys asks the question this asks for one. `get` would have been the same statement
480  /// behind a signature that cannot batch.
481  ///
482  /// The engine answers `Ok(None)` on every miss path, so the wire face carries that answer rather
483  /// than inventing a word for it — and a refusal that IS one crosses with the word its own type
484  /// names, through `refused`.
485  ///
486  /// # The two lanes, and why the branch is a RUNTIME one
487  ///
488  /// The user's ruling of 2026-08-12: *走B吧, 不装loader 就慢一些呗* — the loader is OPTIONAL.
489  ///
490  /// ```text
491  /// ctx.data_opt::<BatchDoor<Id, Row>>()
492  ///   Some(door) → door.one(id)                      ← N keys, ONE statement
493  ///   None       → rows(door.pool(), &[id])          ← today's lane, unchanged
494  /// ```
495  ///
496  /// `data_opt` and not `data`, so ABSENCE DEGRADES rather than refusing: a build that installs
497  /// nothing answers exactly what it answered before, at exactly the cost it cost before.
498  /// `wire_batching.rs` is that number — three aliased singles, three statements — and
499  /// `wire_batched.rs` is the same document with a door installed, at one.
500  ///
501  /// **The emission is UNCONDITIONAL**, and that is what makes the seam's feature independent: the
502  /// door type is this framework's own and exists in every build, so nothing here asks whether the
503  /// coalescing engine was compiled. What the `dataloader` feature gates is a BINDING an
504  /// application reaches for when it mints a door, and no expansion names it.
505  ///
506  /// # The read door moved INTO the absent lane, and the ordering is preserved deliberately
507  ///
508  /// A resolver answering out of a batch never touches the pool, so a schema that installs a batch
509  /// door and no read door is now a working configuration rather than a runtime error. That is the
510  /// only behaviour change in the absent lane's neighbourhood, and the absent lane itself is
511  /// byte-for-byte what it was: the door lookup is still the FIRST thing it does, ahead of the id
512  /// crossing, so a request that is wrong in both ways still reads the door's refusal first. The
513  /// crossing is written in both arms rather than hoisted above the match, which is what buys that.
514  fn single_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
515    let ag = self.framework(&[], "async_graphql");
516    let door = self.framework(&["graphql"], "SqlDoor");
517    let batch = self.framework(&["graphql"], "BatchDoor");
518    let refused = self.framework(&["graphql"], "refused");
519    let rows = self.framework(&["query", "sql"], "rows");
520    let crossing = self.framework(&["graphql"], "ToGraphqlInput");
521    let refused_address = self.framework(&["graphql"], "refused_address");
522    let output = graphql.output.safe();
523    let row = database.name();
524    let backend = database.backend_type(self);
525    let id_ty = &self.key.id.ty;
526    let field = root_field(&super::wire::published_output(graphql, self));
527    let method = wire_method(&format_ident!("{}", self.snake()));
528    let ctx = wire_method(&format_ident!("ctx"));
529    let id = wire_method(&format_ident!("id"));
530    let raise = self.wire_crossing(graphql, database);
531    quote! {
532      #[graphql(name = #field)]
533      async fn #method(
534        &self,
535        #ctx: &#ag::Context<'_>,
536        #[graphql(name = "id")] #id: <#id_ty as #crossing>::Input,
537      ) -> #ag::Result<::core::option::Option<#output>> {
538        let __ingraph_hit = match #ag::Context::data_opt::<#batch<#id_ty, #row>>(#ctx) {
539          // THE BATCHED LANE. The refusal is the batch's one refusal, carrying the word whoever
540          // raised it chose — so `refused` attaches the same code the per-row lane's would, and a
541          // client cannot tell which lane answered it.
542          ::core::option::Option::Some(__ingraph_batch) => {
543            let __ingraph_id = <#id_ty as #crossing>::cross(#id)
544              .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
545            #batch::one(__ingraph_batch, __ingraph_id)
546              .await
547              .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?
548          }
549          // THE PER-ROW LANE, unchanged.
550          ::core::option::Option::None => {
551            let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
552            let __ingraph_id = <#id_ty as #crossing>::cross(#id)
553              .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
554            let __ingraph_rows = #rows::<#row, #backend, _>(
555              #door::pool(__ingraph_door),
556              ::core::slice::from_ref(&__ingraph_id),
557            )
558            .await
559            .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
560            ::core::iter::Iterator::next(
561              &mut ::core::iter::IntoIterator::into_iter(__ingraph_rows),
562            )
563          }
564        };
565        match __ingraph_hit {
566          ::core::option::Option::Some(__ingraph_row) => ::core::result::Result::Ok(
567            ::core::option::Option::Some(#raise?),
568          ),
569          ::core::option::Option::None => {
570            ::core::result::Result::Ok(::core::option::Option::None)
571          }
572        }
573      }
574    }
575  }
576
577  /// **THE LIST** — the relay arguments, an OPTIONAL `orderBy`, and the connection they describe.
578  ///
579  /// Nothing at all where the record has no order-by face: a page needs a written order, the
580  /// order-by input object is what a client writes one with, and a record with no orderable column
581  /// has neither. The single stands alone there, which is exactly the query such a record can answer.
582  ///
583  /// The two refusals a client can raise are raised from the ARGUMENTS, at `PageRequest::of` — the
584  /// one door, so there is no second place a page is checked — and each crosses as its ratified word.
585  /// An absent `orderBy` is not a refusal: `Orderings::default` is the empty order and the emitted
586  /// `complete` puts the record's key at the end of every order, so the empty one IS the key
587  /// ascending — total, and therefore pageable.
588  ///
589  /// # `where` — the argument that WAS not here, and the widening it was promised as
590  ///
591  /// It names `<E>Filter`, whose wire face was held behind the carrier axis. That axis landed, the
592  /// face is emitted beside this leg under one condition ([`Self::wire_filters`]), and the promise
593  /// this note carried is what the argument cashes: it is OPTIONAL and it is LAST, so a document
594  /// that does not write it renders the query it always rendered and an SDL that gains it gains
595  /// nothing but a suffix. An absent `where` is not the empty filter but no `filter(…)` call at all
596  /// — which is the same predicate and one less clause for the engine to render.
597  ///
598  /// The CROSSING is `emit::cross`'s, reached at this database's concrete backend, and a refusal
599  /// from it is `UNSUPPORTED_FILTER`: the schema is backend-neutral by design, so it offers operands
600  /// a compiled store may not be able to hold.
601  ///
602  /// The condition [`Self::wire_filters`] states IS this leg's own two guards plus the database
603  /// `queries_face` already found, so inside this function it holds by construction — which is why
604  /// nothing here re-asks it.
605  fn list_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
606    if !self.orderable() || self.ordered_columns().is_empty() {
607      return proc_macro2::TokenStream::new();
608    }
609    let ag = self.framework(&[], "async_graphql");
610    let door = self.framework(&["graphql"], "SqlDoor");
611    let orderings = self.framework(&["graphql"], "Orderings");
612    let connection = self.framework(&["graphql"], "Connection");
613    let output = graphql.output.safe();
614    let order_by = self.order_by.safe();
615    let cursor = database.cursor_name();
616    let backend = database.backend_type(self);
617    let field = root_field(&super::wire::published_plural(graphql, self));
618    let method = wire_method(&format_ident!("{}_list", self.snake()));
619    let ctx = wire_method(&format_ident!("ctx"));
620    let (order, first, last, after, before) = (
621      wire_method(&format_ident!("order_by")),
622      wire_method(&format_ident!("first")),
623      wire_method(&format_ident!("last")),
624      wire_method(&format_ident!("after")),
625      wire_method(&format_ident!("before")),
626    );
627    let filter = graphql.filter.safe();
628    let comparison = database.comparison_name();
629    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
630    let refused_filter = self.framework(&["graphql"], "refused_filter");
631    // `where` is a Rust KEYWORD and `Ident::new` takes one — a keyword is a legal identifier
632    // lexically, which is exactly the distinction `Ident::new_raw` exists on the other side of — so
633    // the base is the plain ident and the prefix makes it spellable: `__async_graphql_where` is not
634    // a keyword, so the parameter needs no `r#` and the emission carries none.
635    //
636    // The RAW spelling would panic here rather than work. `format_ident!` routes through
637    // `quote::__private::ident_maybe_raw`, which re-attaches the `r#` it found and hands
638    // `"__async_graphql_r#where"` to `Ident::new` — measured at quote 1.0.47, against
639    // `method::wire_method`'s own note claiming the prefix is dropped. That note is corrected
640    // there.
641    let predicate = wire_method(&format_ident!("where"));
642    // EIGHT parameters, which is one past clippy's threshold — see [`super::wide_signature`], where
643    // the rule and the reason a consumer cannot edit around it are written down. The arity is this
644    // emitter's own here rather than a declaration's, and it is the same eight for every record that
645    // has the leg.
646    let arity = super::wide_signature();
647    let walk = self.page_walk(graphql, database);
648    // The page's two SDL names. A return type is the only position that ever names a marker, which
649    // is what keeps them private to this expansion's own const — and the LINEAGE leg closes on this
650    // same pair, because the two legs page one record and one record has one page type.
651    let (connection_name, edge_name) = self.page_name_arguments();
652    quote! {
653      #[graphql(name = #field)]
654      #arity
655      async fn #method(
656        &self,
657        #ctx: &#ag::Context<'_>,
658        #[graphql(name = "orderBy")] #order: ::core::option::Option<#orderings<#order_by>>,
659        #[graphql(name = "first")] #first: ::core::option::Option<u32>,
660        #[graphql(name = "last")] #last: ::core::option::Option<u32>,
661        #[graphql(name = "after")] #after: ::core::option::Option<::std::string::String>,
662        #[graphql(name = "before")] #before: ::core::option::Option<::std::string::String>,
663        // LAST, and that placement is the widening law rather than a preference: the SDL renders
664        // arguments in declaration order, so an argument appended leaves every byte before it where
665        // it was.
666        #[graphql(name = "where")] #predicate: ::core::option::Option<#filter>,
667      ) -> #ag::Result<#connection<#output, #cursor, #connection_name, #edge_name>> {
668        let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
669        // A LOCAL rather than an inline expression, because `Find::filter` BORROWS the predicate
670        // for the whole walk — the tie `ComplexComparison::apply` already spells — so it has to
671        // outlive the builder it is handed to. WHERE it sits among the argument checks buys
672        // nothing and is not claimed to: no statement is rendered until `rows()`, so every refusal
673        // below is raised before the store is touched whatever the order.
674        let __ingraph_predicate = match #predicate {
675          ::core::option::Option::Some(__ingraph_written) => ::core::option::Option::Some(
676            <#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_written)
677              .map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
678          ),
679          ::core::option::Option::None => ::core::option::Option::None,
680        };
681        // The list leg attaches NOTHING of its own: a page over a record is the whole record, and
682        // the client's `where` is the only narrowing there is. The binding is written out rather
683        // than left to the walk so that the walk has one shape instead of two.
684        let __ingraph_scope: ::core::option::Option<#comparison<#backend>> =
685          ::core::option::Option::None;
686        #walk
687      }
688    }
689  }
690
691  /// **THE PAGE WALK** — everything a paged leg does once its predicate is decided, written once for
692  /// the two legs that page.
693  ///
694  /// # Its contract, which is three names
695  ///
696  /// It reads `__ingraph_door`, `__ingraph_predicate` and `__ingraph_scope` — the latter two both
697  /// `Option<<E><Db>Comparison<Backend>>` — and it reads the five relay arguments by the idents
698  /// [`wire_method`] gives them. Everything else it brings. That is a narrow contract to state in a
699  /// comment rather than in a signature, and stating it is what a token-level factoring costs: the
700  /// alternative is the same forty lines in two emitters, where a fix to one is a divergence.
701  ///
702  /// The two predicates are the two PARTIES: `__ingraph_predicate` is what a client wrote and
703  /// `__ingraph_scope` is what the leg attached. Both legs now bind both — the list leg's scope is
704  /// `None` — so the shape here is one walk rather than a walk per leg.
705  ///
706  /// The factoring is [`Graphql::filter_rows`]'s own rule one layer up — a walk asked for twice is a
707  /// walk two answers can disagree about — and what it protects here is the PAGE semantics: an
708  /// absent order being the key ascending, both cursor directions, and the connection assembled
709  /// without a re-wrap. A lineage leg that drifted on any of those would be a second pager nobody
710  /// meant to write.
711  ///
712  /// The PREDICATES are deliberately outside it. What each leg BINDS is the whole of the difference
713  /// between them: the list leg receives a filter and scopes nothing, the lineage leg does both.
714  fn page_walk(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
715    let refused = self.framework(&["graphql"], "refused");
716    let orderings = self.framework(&["graphql"], "Orderings");
717    let page_request = self.framework(&["graphql"], "PageRequest");
718    let door = self.framework(&["graphql"], "SqlDoor");
719    let order_by = self.order_by.safe();
720    let cursor = database.cursor_name();
721    let record = &self.record;
722    let finder = database.kind().finder();
723    let crossing = self.wire_crossing(graphql, database);
724    let (order, first, last, after, before) = (
725      wire_method(&format_ident!("order_by")),
726      wire_method(&format_ident!("first")),
727      wire_method(&format_ident!("last")),
728      wire_method(&format_ident!("after")),
729      wire_method(&format_ident!("before")),
730    );
731    quote! {
732      let __ingraph_request = <#page_request<#cursor>>::of(
733        #first,
734        #last,
735        ::core::option::Option::as_deref(&#after),
736        ::core::option::Option::as_deref(&#before),
737      )
738      .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
739      // The KEY DEFAULT's one door: an absent argument and `orderBy: []` reach the same empty
740      // order, and the emitted `complete` is what makes the empty one total.
741      let __ingraph_terms: ::std::vec::Vec<#order_by> = ::core::iter::Iterator::collect(
742        ::core::iter::Iterator::cloned(
743          #orderings::terms(&::core::option::Option::unwrap_or_default(#order)),
744        ),
745      );
746      let __ingraph_found = #record::#finder(#door::pool(__ingraph_door));
747      // An absent predicate is NO `filter(…)` call, not the empty one: the two ask for the same
748      // rows, and only one of them leaves the builder's own `Option` alone.
749      let __ingraph_found = match &__ingraph_predicate {
750        ::core::option::Option::Some(__ingraph_narrowing) => {
751          __ingraph_found.filter(__ingraph_narrowing)
752        }
753        ::core::option::Option::None => __ingraph_found,
754      };
755      // The SERVER's predicate, on the slot of its own, ANDed with the client's by the engine —
756      // never merged into it. `Find::scope` carries why a merge could not hold both operands of a
757      // column the two of them name together.
758      let __ingraph_found = match &__ingraph_scope {
759        ::core::option::Option::Some(__ingraph_scoping) => __ingraph_found.scope(__ingraph_scoping),
760        ::core::option::Option::None => __ingraph_found,
761      };
762      let __ingraph_found = __ingraph_found.order(&__ingraph_terms);
763      let __ingraph_page = match &__ingraph_request {
764        #page_request::Forward { after: __ingraph_at, .. } => {
765          let __ingraph_walk = __ingraph_found.first(#page_request::size(&__ingraph_request));
766          match __ingraph_at {
767            ::core::option::Option::Some(__ingraph_cursor) => {
768              __ingraph_walk.after(__ingraph_cursor).rows().await
769            }
770            ::core::option::Option::None => __ingraph_walk.rows().await,
771          }
772        }
773        #page_request::Backward { before: __ingraph_at, .. } => {
774          let __ingraph_walk = __ingraph_found.last(#page_request::size(&__ingraph_request));
775          match __ingraph_at {
776            ::core::option::Option::Some(__ingraph_cursor) => {
777              __ingraph_walk.before(__ingraph_cursor).rows().await
778            }
779            ::core::option::Option::None => __ingraph_walk.rows().await,
780          }
781        }
782      }
783      .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
784      // The connection IS the answer, with nothing unwrapped and re-wrapped around it: the
785      // crossing already refuses in the resolver's own error type, so an `Ok(…?)` here would be
786      // `clippy::needless_question_mark` inside an expansion its author cannot edit.
787      __ingraph_page.into_connection(|__ingraph_row| #crossing)
788    }
789  }
790
791  /// **THE LINEAGE** — `<camel>Lineage(<step>: …, …)`, the rows under ONE ancestry, paged.
792  ///
793  /// # A walk is a read under a predicate, and this is the leg that BUILDS one
794  ///
795  /// The list leg receives a filter, the client having written it. This one MINTS one as well: the
796  /// ancestry arrives as ARGUMENTS — one per lineage step, root-first, exactly as the key carries
797  /// them — and a predicate is built from them. That is the whole difference between the two legs,
798  /// and everything after the predicates is [`Self::page_walk`]'s.
799  ///
800  /// # It takes a `where` TOO, and the two predicates are ANDed rather than merged
801  ///
802  /// The ruling is a plain conjunction: a client's filter narrows INSIDE the ancestry, and a filter
803  /// that contradicts the scope answers with no rows by set law rather than with a refusal. So the
804  /// leg binds both — the ancestry to `__ingraph_scope`, the client's `where` to
805  /// `__ingraph_predicate` — and the engine's two slots keep them apart all the way to the one
806  /// `WHERE` they render into.
807  ///
808  /// **They are two VALUES because one could not hold them.** Merging the client's filter with the
809  /// ancestry means writing both into one `<E>Filter`, whose column slot holds ONE operand — so
810  /// `takeLineage(reelId: 1, where: { reelId: { eq: 2 } })` would silently become whichever of the
811  /// two was written last, and answer reel 1's rows or reel 2's instead of neither. The same is true
812  /// one layer down, since a comparison struct is a column-per-field mirror of the filter. Two
813  /// values applied to one accumulator is the only shape that can express its own contradiction, and
814  /// [`Find::scope`](../../../ingraph/query/sql/struct.Find.html#method.scope) is where that is
815  /// written down.
816  ///
817  /// The client's half crosses EXACTLY as the list leg's does — same `TryFromFilter`, same
818  /// `UNSUPPORTED_FILTER` — because it is the same argument on a second field, and a second crossing
819  /// would be a second thing to keep in step.
820  ///
821  /// The minting is one line per step: [`EqualsFilter`] at the column's own declared type, into the
822  /// filter struct's own `with_*` builder. Neither call names a filter KIND, which is what makes it
823  /// writable at all — the projection layer is type-blind, so a column's filter reaches here as
824  /// `<<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter` and not as a spelling. A step whose
825  /// filter has no equality row is `E0277` naming that pair, which is the crossing's own posture one
826  /// layer down.
827  ///
828  /// # What it is emitted for, and what each absence means
829  ///
830  /// A record with NO lineage gets no leg, and that is the whole of the refusal: a root's ancestry
831  /// is the empty path, so there is no argument to take and no scope to name. Presence is the
832  /// enablement, exactly as the list leg's order-by face is.
833  ///
834  /// A FAN-IN's lineage gets none either, and [`Lineage::path`] is where that falls out rather than
835  /// a rule written twice: its columns vary between ROWS — which upstream a row came from decides
836  /// what it carries — so there is no one set of arguments that scopes such a walk, and `path()`
837  /// answers a fan-in with nothing.
838  ///
839  /// A step that is not a STORED column gets none, and for the reason the filter has no field for
840  /// it: `<E>Filter` is mechanical from the stored columns, and a lineage a declaration keeps out of
841  /// its tables is an ancestry no predicate can name. The corpus carries such a record —
842  /// `fixtures.rs`'s `VideoTrack`, whose `media_id` is `copy` and not `persist`.
843  ///
844  /// # The ARGUMENTS come first, and the relay arguments follow them
845  ///
846  /// Root-first among themselves, because that is the order the key walks and the order the address
847  /// object publishes; before the page arguments, because the single puts its `id:` first and this
848  /// is the same act — an address is named, then the page over it is described.
849  fn lineage_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
850    let steps = self.lineage_steps(graphql);
851    if steps.is_empty() || !self.orderable() || self.ordered_columns().is_empty() {
852      return proc_macro2::TokenStream::new();
853    }
854    let ag = self.framework(&[], "async_graphql");
855    let door = self.framework(&["graphql"], "SqlDoor");
856    let orderings = self.framework(&["graphql"], "Orderings");
857    let connection = self.framework(&["graphql"], "Connection");
858    let equals = self.framework(&["graphql"], "EqualsFilter");
859    let crossing = self.framework(&["graphql"], "ToGraphqlInput");
860    let refused_address = self.framework(&["graphql"], "refused_address");
861    let refused_filter = self.framework(&["graphql"], "refused_filter");
862    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
863    let output = graphql.output.safe();
864    let order_by = self.order_by.safe();
865    let filter = graphql.filter.safe();
866    let comparison = database.comparison_name();
867    let cursor = database.cursor_name();
868    let backend = database.backend_type(self);
869    let field = format!(
870      "{}Lineage",
871      root_field(&super::wire::published_output(graphql, self))
872    );
873    let method = wire_method(&format_ident!("{}_lineage", self.snake()));
874    let ctx = wire_method(&format_ident!("ctx"));
875    let (order, first, last, after, before) = (
876      wire_method(&format_ident!("order_by")),
877      wire_method(&format_ident!("first")),
878      wire_method(&format_ident!("last")),
879      wire_method(&format_ident!("after")),
880      wire_method(&format_ident!("before")),
881    );
882    let parameters = steps.iter().map(|step| {
883      let (name, ident, wire) = (&step.field, &step.parameter, &step.wire);
884      quote!(#[graphql(name = #name)] #ident: <#wire as #crossing>::Input,)
885    });
886    // Each step CROSSES exactly as the single's `id:` does, and refuses under the same word: a
887    // lineage argument IS an address, one segment of the root-first path the key publishes, so
888    // `UNUSABLE_ADDRESS` is the fact rather than a second word for it.
889    let ancestry = steps.iter().map(|step| {
890      let (ident, wire, with, guard) = (&step.parameter, &step.wire, &step.with, &step.filter);
891      quote! {
892        .#with(<#guard as #equals<#wire>>::equals(
893          <#wire as #crossing>::cross(#ident)
894            .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?,
895        ))
896      }
897    });
898    // `where` is a Rust KEYWORD, and the prefix is what makes it spellable — `list_leg`'s own note
899    // carries why the RAW spelling would panic here rather than work.
900    let predicate = wire_method(&format_ident!("where"));
901    // The step count is a DECLARATION's — the corpus carries a seven-step path — so this signature's
902    // arity is unbounded from here, where the other two legs' are the emitter's own.
903    let arity = super::wide_signature();
904    let walk = self.page_walk(graphql, database);
905    // The SAME pair the list leg closes on. A page over a record IS the record's page whichever leg
906    // asked for it, so the two return types name one connection and one edge — and the alternative
907    // is not a tidiness question: a lineage leg on the library's defaults publishes a SECOND page
908    // type for one record the moment the record's names are anything but `<Node>Connection`, which
909    // under the plural base is every record.
910    let (connection_name, edge_name) = self.page_name_arguments();
911    quote! {
912      #[graphql(name = #field)]
913      #arity
914      async fn #method(
915        &self,
916        #ctx: &#ag::Context<'_>,
917        #(#parameters)*
918        #[graphql(name = "orderBy")] #order: ::core::option::Option<#orderings<#order_by>>,
919        #[graphql(name = "first")] #first: ::core::option::Option<u32>,
920        #[graphql(name = "last")] #last: ::core::option::Option<u32>,
921        #[graphql(name = "after")] #after: ::core::option::Option<::std::string::String>,
922        #[graphql(name = "before")] #before: ::core::option::Option<::std::string::String>,
923        // LAST, and for the list leg's own reason: the SDL renders arguments in declaration order,
924        // so an argument appended leaves every byte before it where it was. This leg's widening is
925        // therefore the same one its neighbour already proved.
926        #[graphql(name = "where")] #predicate: ::core::option::Option<#filter>,
927      ) -> #ag::Result<#connection<#output, #cursor, #connection_name, #edge_name>> {
928        let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
929        // Through the record's OWN filter and its own crossing, rather than into the comparison
930        // directly: a declared operand converter is the crossing's business, so a lineage step that
931        // stores through one takes the same road its `where` counterpart does and the two cannot
932        // come to disagree about a column.
933        let __ingraph_ancestry = <#filter as ::core::default::Default>::default() #(#ancestry)*;
934        let __ingraph_scope = ::core::option::Option::Some(
935          <#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_ancestry)
936            .map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
937        );
938        // The CLIENT's half, crossed exactly as the list leg crosses its own — and held apart from
939        // the scope rather than folded into it, which is what lets the two contradict.
940        let __ingraph_predicate = match #predicate {
941          ::core::option::Option::Some(__ingraph_written) => ::core::option::Option::Some(
942            <#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_written)
943              .map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
944          ),
945          ::core::option::Option::None => ::core::option::Option::None,
946        };
947        #walk
948      }
949    }
950  }
951
952  /// The lineage path as the LEG reads it: one step per ancestry column, root-first, and nothing at
953  /// all where any of the three conditions [`Self::lineage_leg`] states does not hold.
954  ///
955  /// The two lists are joined on the RECORD FIELD, which is the only name both carry: a lineage
956  /// column wears the name its own type gave it — `lineage(rename = "…")` moves it — and a stored
957  /// column wears its database's. `source` is what neither rename touches.
958  fn lineage_steps(&self, graphql: &Graphql) -> Vec<LineageStep> {
959    let Some(lineage) = self.lineage.as_ref() else {
960      return Vec::new();
961    };
962    let path = lineage.path();
963    if path.is_empty() {
964      return Vec::new();
965    }
966    let rows = graphql.filter_rows(self);
967    let steps: Vec<LineageStep> = path
968      .iter()
969      .filter_map(|step| {
970        // Found by MEMBER rather than at an index: a filter row's member IS the record field the
971        // column projects, and the two lists have never been index-aligned — `graphql(skip)`
972        // compacts the rows and the shared list is the declaration's, so a position read off one
973        // would name another step or none.
974        let row = rows.iter().find(|row| row.member == step.source)?;
975        Some(LineageStep {
976          field: super::wire::wire_field(&row.declared, &row.member),
977          parameter: wire_method(&row.member),
978          with: crate::method::Member::With.name(&row.member),
979          wire: row.wire.clone(),
980          filter: row.filter.clone(),
981        })
982      })
983      .collect();
984    // ALL of them or none: a walk scoped by some of an ancestry is a walk over the wrong set, and
985    // silently answering a narrower question than the field's name promises is worse than not
986    // offering the field.
987    if steps.len() == path.len() {
988      steps
989    } else {
990      Vec::new()
991    }
992  }
993
994  /// One ROW raised onto the wire, as an expression over `__ingraph_row` answering
995  /// `Result<Output, async_graphql::Error>`.
996  ///
997  /// `TryFrom` at both arms, and that is what lets ONE expression serve a crossing that may or may
998  /// not be fallible: std's blanket gives every `From` a `TryFrom` whose error is `Infallible`, so a
999  /// record with no declared conversion takes the same shape as one whose `output(<db>(from = …))`
1000  /// can refuse, and neither is spelled twice here.
1001  ///
1002  /// The refusal crosses as `UNREADABLE_ROW` through `refused_row` — the word the ENGINE's own
1003  /// crossing already answers under, and the same nothing asked of the client.
1004  fn wire_crossing(
1005    &self,
1006    graphql: &Graphql,
1007    database: &DatabaseBackend,
1008  ) -> proc_macro2::TokenStream {
1009    let output = graphql.output.safe();
1010    let row = database.name();
1011    let refused_row = self.framework(&["graphql"], "refused_row");
1012    quote! {
1013      <#output as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row)
1014        .map_err(|__ingraph_refusal| #refused_row(&__ingraph_refusal))
1015    }
1016  }
1017
1018  /// The record's own name in snake case — what the emitted function idents are built from before
1019  /// the `__async_graphql_` prefix.
1020  ///
1021  /// The RUST side only. What a client reads is written out per item, so this never reaches a schema
1022  /// and a rename of the published type moves the field without moving the ident.
1023  fn snake(&self) -> String {
1024    use heck::ToSnakeCase as _;
1025
1026    self.record.to_string().to_snake_case()
1027  }
1028}