ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
//! The QUERY UNIT: `<E>Queries`, the root fields one record answers, as one mountable type.
//!
//! ```text
//! type Query {                    # the graph root's fold
//!   reel(id: Int!): Reel          # the SINGLE   — ReelQueries::__async_graphql_reel
//!   reels(orderBy: […], first: Int, …, where: ReelFilter): ReelsConnection
//!                                 # the LIST     — ReelQueries::__async_graphql_reel_list
//!   takeLineage(reelId: Int!, orderBy: […], first: Int, …, where: TakeFilter): TakesConnection
//!                                 # the LINEAGE  — TakeQueries::__async_graphql_take_lineage
//! }
//! ```
//!
//! # Why a UNIT rather than fields on some root
//!
//! Two derives cannot read each other's tokens, and the root is written by a third. So the record's
//! own expansion writes what only it knows — which columns, which row, which database, which order
//! terms — onto a type of its own, and the ROOT folds units. `MergedObject` is what makes the fold a
//! GraphQL object again: a member's fields land at the root's level, so the schema a client reads has
//! no unit in it at all.
//!
//! The join between the two ends is [`Graphql::Query`](../../../ingraph/trait.Graphql.html), which
//! this file binds and `graph::query` projects. Nobody parses anybody's declaration.
//!
//! # THE DOOR, and why the resolver holds no connection
//!
//! `wire_trio.rs` measured the wall to its floor: async-graphql demands `Send` of every resolver
//! future, sqlx implements `Acquire<'c>` for `&'c mut Connection` at ONE lifetime, and a
//! `Send`-bounded future asks for it at two — so a resolver that reaches a borrowed connection is
//! *implementation of `sqlx::Acquire` is not general enough*, at any database, behind any number of
//! helpers. `&Pool` is the surface that passes.
//!
//! So the emitted resolver takes `ingraph`'s `SqlDoor<Db>` out of `ctx.data` and hands the engine
//! `door.pool()`. The door is found by its TYPE, which is why the emission spells the database the
//! record's own `persist(…)` block named: a schema serving two stores installs two doors and each
//! record reaches its own.
//!
//! # The ID argument crosses, and it has to
//!
//! `id:` is the framework's only typed INPUT here, and the declaration's id type may have no wire
//! form of its own — the corpus alone carries eleven records whose id is a `u128`, which no crate
//! gives an `InputType`. So the argument is `<IdTy as ToGraphqlInput>::Input` and the body crosses
//! it back, exactly as the output object returns `<Ty as ToGraphqlOutput>::Output<'_>`. Both maps
//! are keyed on the TYPE, so `type Uuid7 = u128` reaches the carrier through the alias and the form
//! a client SENDS is the form the same row is RETURNED as.
//!
//! The map is the CARRIER AXIS's, which is where it belongs: a wide id is the same operand a wide
//! COLUMN is, and a declaring crate that gave its own id type a filter face has already written the
//! row this position reads.
//!
//! # What each leg is CONDITIONAL on, and what is HELD
//!
//! | leg | emitted when | why |
//! |---|---|---|
//! | 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 |
//! | 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 |
//! | 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 |
//! | 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 |
//!
//! The `where` argument rides BOTH paged legs, and on one condition rather than two: the face and
//! the crossing it needs are the record's, so a record that can be filtered at all can be filtered
//! under an ancestry as well.
//!
//! **The LINEAGE leg's two walls are both down, and the second fell where nobody was looking.** A
//! lineage walk is a read under a PREDICATE — *the takes whose `reel_id` is 1* — and the machinery it
//! needs was the `where` leg's:
//!
//! * ~~the record's own `<E>Filter` → `<E><Db>Comparison` crossing is not emitted~~ **it is**, at the
//!   concrete backend and inside its gate — see [`super::cross`], which is what ruled the shape
//!   `comparison_traits` ended on;
//! * ~~the filter kinds hold their operands `pub(crate)` and publish no builder~~ — **the operands
//!   are `pub(crate)` and the BUILDER was always public.** Every kind ships `new()`, a `Default` and
//!   a `with_*` per slot, and an external crate already spends them. What was actually missing is one
//!   surface narrower: a filter reaches an emitter as the PROJECTION
//!   `<<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter`, and an inherent builder is
//!   unreachable through a name the emitter is forbidden to resolve — the projection layer is
//!   type-blind on purpose, and `ScalarFilter<T>` and `Nullable<ScalarFilter<T>>` take an equality
//!   operand through different expressions. `ingraph`'s `EqualsFilter` is the one line that serves
//!   both, and it is what this leg mints its predicate with.
//!
//! `ingraph/tests/wire_trio.rs` keeps its hand-written witness — the semantic executed against a real
//! store before there was an emitter to ask for it — and `ingraph/tests/wire_lineage.rs` is the same
//! walk through the EMITTED leg.
//!
//! # The naming — both fields are the PUBLISHED name, one of them in the plural
//!
//! The single is `<camel>` — the ruled spelling, with no `ById` suffix — over the record's PUBLISHED
//! output type name, so `output(rename = "…")` moves the field with the object it returns.
//!
//! The LIST is that same published name PLURALISED and lowered at its initial: `Reel` ⇒ `reels`,
//! `VideoTrack` ⇒ `videoTracks`. The word is English rather than a suffix — `<camel>List` was this
//! emitter's holding spelling and is gone — and it comes from [`crate::plural`], a compile-time
//! pluraliser on the expansion side, because `heck` knows casing and nothing knows language. The
//! table name, which IS a plural a declaration already wrote, stays out of it: that is a STORAGE
//! fact, and a schema that read it would vary with a deployment's storage choice.
//!
//! A declaration that disagrees with the pluraliser corrects the WORD, not the field:
//! `graphql(plural = "corpora")` states this entity's plural, so the next reader of it — a
//! connection, an aggregate — inherits one correction rather than asking for a second.
//!
//! # The one refusal the plural brings, and the silence it is about
//!
//! A derived plural can come back as the word it was given: `Media`, `Series`, `Dimensions` have no
//! distinct plural in the pluraliser's answer. Emitting it would publish the PAGE under the SINGLE's
//! own name, and that is not a compile error anywhere downstream — measured against async-graphql
//! 7.2.1, two fields of one object sharing a name build a schema in which the SDL carries the last
//! registration and the resolver answers from the first, so a client reads one type and receives
//! another.
//!
//! So the derived case is refused by name at the declaration, through
//! [`RecordModel::degenerate_plural`], and the refusal teaches the word. A DECLARED plural equal to
//! the singular is not refused: the rule guards silence, not choice.
//!
//! # The PAGE has two names of its own, and they are a THREE-TIER TOWER over the plural
//!
//! The user's ruling of 2026-08-13: *跟着复数走, 有层级关系, 如果用户主动 rename connection 的名字,
//! 那么 connection 的名字用用户指定的, 我们是 tiered, 一层覆盖一层* — the page names FOLLOW THE
//! PLURAL, in tiers, each layer covering the one below it.
//!
//! | tier | the word | who writes it |
//! |---|---|---|
//! | base | the derived plural — `Reel` ⇒ `ReelsConnection` / `ReelsEdge` | the pluraliser |
//! | over it | `graphql(plural = "corpora")` ⇒ `CorporaConnection` / `CorporaEdge` | the declaration, ONCE |
//! | on top | `graphql(connection(rename = "CorpusPage"))` ⇒ `CorpusPage` | the declaration, per name |
//!
//! **One word moves three names**, which is the whole of what the middle tier buys — the user's
//! *一起跟*. `plural = "corpora"` is read by the list FIELD, by the connection and by the edge, so a
//! declaration that corrects English once gets `corpora(…): CorporaConnection` and never
//! `corpora(…): CorpusesConnection`. That is one authority rather than three readers of it: the word
//! is [`super::wire::published_plural`]'s, resolved in one place, and this file spells it in two
//! cases (a field's lowered initial, a type's raised one) rather than deriving it twice.
//!
//! The base is the PLURAL and not the Relay Cursor Connections specification's `<Node>Connection`,
//! and the trade is real: tooling that finds a page by the NODE's stem sees a name it does not
//! recognise. The ruling made that trade once, for every record, and each emitted marker's own doc
//! is where it is priced.
//!
//! The TOP tier is unchanged in mechanism — `graphql(connection(rename = "…"), edge(rename = "…"))`
//! over async-graphql's `ConnectionNameType`/`EdgeNameType` hooks, per record, each independent of
//! the other.
//!
//! What the tower costs the rest of this file is one thing worth naming: `DefaultConnectionName`
//! renders the SINGULAR-based word, so there is no declaration whose page this emitter can leave to
//! the library, and [`page_names`](RecordModel::page_names) now mints a marker pair for every record
//! that HAS a page. That is not vocabulary growth — what it writes is private to the face's own
//! `const _: () = { … }`, the two paged legs' return types being the only things that ever name a
//! marker. So the tower adds nothing to a declaring scope and nothing to the emitted-name refusal.
//!
//! # The `__async_graphql_` pins apply here first
//!
//! Every function and every ARGUMENT wears the backend's prefix through
//! [`wire_method`](crate::method::wire_method) — this is the emission that gives the argument half of
//! that pin its first violator to guard against — and every wire-visible name is written out as
//! `#[graphql(name = "…")]`, per item, never derived from an ident.

use quote::{format_ident, quote};

use crate::{
  method::wire_method,
  model::{DatabaseBackend, Graphql, RecordModel, default_queries_name},
};

#[cfg(test)]
mod batch_lane_tests;
#[cfg(test)]
mod page_name_tests;
#[cfg(test)]
mod page_tower_tests;
#[cfg(test)]
mod tests;

/// One ancestry column, as the LINEAGE leg spends it: an argument, and the operand that argument
/// becomes.
///
/// Five spellings of one column, and each is read from its own source rather than derived from a
/// neighbour — the same discipline [`super::graphql::FilterRow`] states, because these are the same
/// three layers. What a client writes, what the Rust parameter is called, which builder sets it,
/// what the operand is held at, and what guards it are five different questions about one column.
struct LineageStep {
  /// The name a client writes this step under — the filter face's own name for the column, so a
  /// document scoping by an ancestry and one filtering on it spell the column identically.
  field: String,
  /// The Rust parameter, `__async_graphql_`-pinned like every other argument this file emits.
  parameter: syn::Ident,
  /// The `<E>Filter` builder that sets this column.
  with: syn::Ident,
  /// The filter guarding this column, already projected through the marker layer — the type
  /// `EqualsFilter` is asked of.
  filter: proc_macro2::TokenStream,
  /// The type the operand is held at: the column's declared wire type, which is both what the
  /// argument crosses into and the parameter `EqualsFilter` is spelled at.
  wire: syn::Type,
}

/// A published TYPE name as a root FIELD names it — [`crate::emit::lower_initial`], re-exported into
/// this file's own vocabulary so the two page names and the field read as one tower.
use crate::emit::{lower_initial as root_field, raise_initial as page_type};

impl RecordModel {
  /// The database this record's ROOT FIELDS are served from, and `None` where it has none.
  ///
  /// Two conditions, and each is a thing a resolver could not otherwise do: the database carries a
  /// QUERY face — [`queryable`](Self::queryable) is the one place that decides which do — and its
  /// row RAISES onto the wire, [`wire_rows`](Self::wire_rows) being the one place that decides that.
  /// A record stored only in MongoDB has the second and not the first, and a record with a wire face
  /// and no `persist(…)` block has neither.
  ///
  /// The FIRST such database rather than all of them, and the choice is the schema's own law: a
  /// client must never see a field that varies with a deployment's storage choice, so a record
  /// stored in two databases answers its root fields from one — the one its declaration wrote first.
  pub(crate) fn wire_query_row(&self) -> Option<&DatabaseBackend> {
    self.graphql.as_ref()?;
    let raises = self.wire_rows();
    self
      .queryable()
      .into_iter()
      .find(|database| raises.iter().any(|row| row.kind() == database.kind()))
  }

  /// Whether this record's `<E>Filter` is SPENT on the wire — the one predicate the filter's face,
  /// its crossing and the `where` argument are each emitted under.
  ///
  /// # The face rides the leg that spends it, and that is the whole of the condition
  ///
  /// `<E>Filter` names the DECLARATION's own types at every field, so its wire face demands
  /// `InputType` of each one — and [`super::wire`]'s note carries what such a demand costs when it
  /// cannot be made conditional: a `where` clause naming only concrete types is a trivial bound,
  /// which stable rustc refuses at the item declaring it, so there is no way to write *this impl
  /// applies where it can hold*. What is left is to emit it exactly where something ASKS for it.
  ///
  /// Nothing is lost by that. async-graphql registers the types REACHABLE from the schema root, so
  /// an input object no argument names never reaches an SDL at all — a face emitted for a record
  /// with no list resolver would be an obligation with no reader. And the crossing is the same
  /// question one layer down: a column whose operand cannot enter storage without a converter the
  /// declaration did not write is `E0277` at the crossing, and a record nothing queries has no
  /// business being asked.
  ///
  /// So the condition is the LIST leg's, read here rather than restated: the record answers a page
  /// from some database, and it has an order to write that page in.
  pub(crate) fn wire_filters(&self) -> bool {
    self.wire_query_row().is_some() && self.orderable() && !self.ordered_columns().is_empty()
  }

  /// The name the PAGE would be published under when it is the SINGLE's own name and no declaration
  /// chose it — the silence a front end refuses, and `None` when there is nothing to refuse.
  ///
  /// # What the answer is, and why it is a name rather than a `bool`
  ///
  /// `Some(field)` is *both root fields would be called `field`*, so the refusal can quote the word
  /// a client would have read. The front end writes the sentence, this answers the fact — the
  /// division [`RecordModel::emitted_types`](crate::model::RecordModel::emitted_types) already
  /// draws, and for its reason: a list of what an emission does kept on the other side of the crate
  /// boundary is a copy, and copies drift.
  ///
  /// # THREE conditions, and each one is load-bearing
  ///
  /// * **the list leg is EMITTED** — [`Self::wire_filters`], whose own note carries that this
  ///   predicate IS the leg's, read once rather than restated. A record with no page has no plural
  ///   to spend, and demanding a word for a field nobody emits would tax a declaration for a
  ///   schema it does not publish. What that leaves open is the DECLARATION carrying a degenerate
  ///   word into a later reader — a connection, an aggregate — and that reader will ask this same
  ///   question when it lands, because the condition is what moves rather than the rule.
  /// * **nothing was DECLARED** — a written `plural = "media"` is a choice, and the rule guards
  ///   silence. The user's ruling states it in those words: the refusal is about a word nobody
  ///   chose, not about a word somebody did.
  /// * **the two fields would COLLIDE** — asked on the emitted field NAMES rather than on the words
  ///   behind them, because the collision is a fact about the schema. The initial is lowered on both
  ///   sides by the same act, so this compares what a client would actually read.
  pub fn degenerate_plural(&self) -> Option<String> {
    let graphql = self.graphql.as_ref()?;
    if graphql.plural.is_some() || !self.wire_filters() {
      return None;
    }
    let single = root_field(&super::wire::published_output(graphql, self));
    let page = root_field(&super::wire::published_plural(graphql, self));
    (page == single).then_some(single)
  }

  /// The unit's DECLARATION — outside the binding gate, like every other emitted wire type.
  ///
  /// It has to be: `Graphql::Query` is bound in an UNGATED impl, so a type that existed only where
  /// async-graphql does would leave that binding naming nothing in every other build. The face —
  /// the `#[Object]` impl — is what rides the gate, which is the same split
  /// [`super::wire`] already draws for the output object.
  ///
  /// `Default` because the ROOT is built from one: an emitted `<Root>Query` derives its own, and a
  /// derive over a tuple of units is what makes `Schema::build(<Root>Query::default(), …)` the whole
  /// of an application's construction. `Copy` and `Debug` beside it are the unit's free ones.
  pub(super) fn queries_type(&self) -> proc_macro2::TokenStream {
    if self.graphql.is_none() || self.wire_query_row().is_none() {
      return proc_macro2::TokenStream::new();
    }
    let vis = &self.vis;
    let record = &self.record;
    let name = default_queries_name(record);
    let doc = super::leading(&format!(
      "The root fields a [`{record}`] answers — one row by its id, and a page of them.\n\nMounted by \
       folding it into a graph's root query; it holds nothing and reads its store through the door \
       the schema was built with."
    ));
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::marker::Copy, ::core::default::Default)]
      #vis struct #name;
    }
  }

  /// The unit's FACE: `#[Object]` over the trio's shipped legs, inside the binding gate AND this
  /// database's own.
  ///
  /// Both gates, because both halves are named: `#[Object]` is async-graphql's and the engine call
  /// names one dialect's row, its cursor value and its finder. A build with the binding and without
  /// the dialect has the unit and no face, and the root that mounts it says so — `E0277` at the
  /// projection, naming the trait the fold demands.
  pub(super) fn queries_face(&self) -> proc_macro2::TokenStream {
    let Some(graphql) = self.graphql.as_ref() else {
      return proc_macro2::TokenStream::new();
    };
    let Some(database) = self.wire_query_row() else {
      return proc_macro2::TokenStream::new();
    };
    let name = default_queries_name(&self.record);
    let ag = self.framework(&[], "async_graphql");
    let shelf = self.vendored("async_graphql");
    let single = self.single_leg(graphql, database);
    let list = self.list_leg(graphql, database);
    let lineage = self.lineage_leg(graphql, database);
    // The markers ride the PAGED LEGS, and the legs themselves are what say so: a record with no
    // page has nothing that could name one, and a marker nobody names is `dead_code` inside an
    // expansion its author cannot edit. Asking the emitted legs rather than re-deriving their
    // conditions is what keeps the two from ever disagreeing.
    //
    // BOTH are asked, though the lineage's guards are the list's plus an ancestry, so a non-empty
    // lineage implies a non-empty list today. Stating the disjunction anyway costs nothing and
    // removes the reasoning step: a later round that loosens the list leg's condition finds the
    // markers already following whatever names them.
    let names = self.page_names(graphql, !list.is_empty() || !lineage.is_empty());
    let sdl = name.to_string();
    let gate = self.framework(&["gate"], &database.kind().gate().to_string());
    let prelude = super::wire::prelude();
    quote! {
      #gate! {
        const _: () = {
          #prelude

          #names

          #[#ag::Object(crate = #shelf, name = #sdl)]
          impl #name {
            #single
            #list
            #lineage
          }
        };
      }
    }
  }

  /// The Rust markers the page's two SDL names are spelled through — `<E>ConnectionName` and
  /// `<E>EdgeName` — for every record that HAS a page, and nothing where there is none.
  ///
  /// `paged` is EITHER paged leg's own presence, handed in by the caller that has just emitted them
  /// rather than re-derived here. A record with no page could still have written the words — the
  /// entries are parsed for every wire face — and a marker nothing names is `dead_code` reported
  /// inside an expansion its author cannot edit.
  ///
  /// # The word is the TOWER's, and this is the one place it is resolved
  ///
  /// Three tiers, each covering the one below — the module note carries the ruling in the user's own
  /// words. The BASE is [`published_plural`](super::wire::published_plural) with its initial raised:
  /// the same resolved word the list FIELD is named from, read from the same function, so a
  /// `plural = "corpora"` moves the field and both type names together and there is no second
  /// derivation to drift. The TOP is the declaration's own `connection`/`edge` word, which wins
  /// outright and independently — a record may move the page and leave the edge on the tower's base.
  ///
  /// # Minted ALWAYS now, and `#222`'s L-4 is why that is still honest
  ///
  /// That ruling refused to mint markers *nothing names* — the vocabulary's first zombie. Both
  /// conditions it named are met and neither was weakened: the paged legs NAME these, and the
  /// unconditional minting is forced rather than chosen — `DefaultConnectionName` renders
  /// `<Node>Connection` over the node's SINGULAR type name, which the tower's base is not, so there
  /// is no declaration this emitter can leave to the library. What changed is the emission's default
  /// word; what did not change is that every marker written here has a reader in the same const.
  ///
  /// # They are PRIVATE TO THIS CONST, and that is the whole of their scoping story
  ///
  /// The only things that ever name one are the two paged legs' return types, inside the same
  /// `const _: () = { … }`. So they are not vocabulary a declaring crate can see, cannot collide with
  /// a declaration's types, and need no entry in [`emitted_types`](RecordModel::emitted_types) —
  /// which is the list of what an expansion puts into a scope, and these go into no scope at all. The
  /// `__async_graphql_` pin has nothing to say about them either: it governs emitted FUNCTIONS and
  /// ARGUMENTS, and
  /// the emitted TYPES it exempts are exempt because they are visible vocabulary — these are the
  /// opposite case, invisible entirely.
  fn page_names(&self, graphql: &Graphql, paged: bool) -> proc_macro2::TokenStream {
    if !paged {
      return proc_macro2::TokenStream::new();
    }
    let ag = self.framework(&[], "async_graphql");
    // THE TOWER'S BASE, resolved once for both names: the list field's own plural, raised at its
    // initial. Asking `published_plural` here rather than re-pluralising the record is what makes
    // one `plural = "…"` move the field, the page and the edge together.
    let base = page_type(&super::wire::published_plural(graphql, self));
    let marker = |declared: Option<&String>, word_suffix: &str, hook: &str, what: &str| {
      let word = declared.map_or_else(|| format!("{base}{word_suffix}"), ToOwned::to_owned);
      let name = format_ident!("{}{word_suffix}Name", self.record);
      let hook = self.framework(&["graphql"], hook);
      let doc = super::leading(&if declared.is_some() {
        format!(
          "What the schema calls {what} of [`{record}`]s — `{word}`, the word the declaration \
           wrote.\n\nThis is the naming tower's TOP: it covers the plural-built word outright, so a \
           `plural = \"…\"` beside it moves the other names and not this one. It also exits the \
           Relay Cursor Connections spelling, and with it the automatic recognition Relay, Apollo \
           and schema codegen give a page: those tools find a connection by the \
           `<Node>Connection`/`<Node>Edge` shape rather than by its fields. That is the trade the \
           knob exists to make, and it is made per record.",
          record = self.record
        )
      } else {
        format!(
          "What the schema calls {what} of [`{record}`]s — `{word}`, built from this record's \
           PLURAL, which is the one word its list field is named from as well.\n\nThe Relay Cursor \
           Connections specification spells this over the NODE's name; this framework spells it over \
           the plural, so one declaration's page reads as one phrase and a `plural = \"…\"` \
           correcting the English moves the field and both type names at once. Tooling that finds a \
           page by the node's stem rather than by its fields sees a name it does not recognise: that \
           is the trade, made once for every record. `connection(rename = \"…\")` and \
           `edge(rename = \"…\")` are the tier above this one.",
          record = self.record
        )
      });
      // The NODE parameter is unused, and it has to be: the hook hands a node's type in so a name
      // can be built from it AT RUNTIME, and this emitter has already resolved one at expansion
      // time — out of the record's plural, which a node's type name does not carry. It is still
      // NAMED rather than `_`, so the signature reads as the trait's own.
      quote! {
        #[doc = #doc]
        struct #name;

        impl #hook for #name {
          fn type_name<__IngraphNode: #ag::OutputType>() -> ::std::string::String {
            ::std::borrow::ToOwned::to_owned(#word)
          }
        }
      }
    };
    let connection = marker(
      graphql.connection.as_ref(),
      "Connection",
      "ConnectionNameType",
      "a page",
    );
    let edge = marker(graphql.edge.as_ref(), "Edge", "EdgeNameType", "one edge");
    quote!(#connection #edge)
  }

  /// The two type arguments a paged leg's `Connection<…>` closes with — this record's own pair of
  /// markers, always.
  ///
  /// ALWAYS, and the library's `DefaultConnectionName`/`DefaultEdgeName` are named nowhere in this
  /// file any more: they render `<Node>Connection` over the node's SINGULAR type name, and the ruled
  /// default is the PLURAL. So the emission names the tower's resolution in every case, and
  /// [`Self::page_names`] is the one place the word inside it is decided.
  ///
  /// ONE pair per RECORD rather than one per leg, which is a correctness property and not a saving:
  /// the list and the lineage page the same record, so they must return the same two SDL types. The
  /// lineage leg closed on the library's defaults before this round — invisible while the default
  /// was the singular and both legs agreed on it, and a second page type for one record the moment
  /// a declaration renamed anything.
  fn page_name_arguments(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let connection = format_ident!("{}ConnectionName", self.record);
    let edge = format_ident!("{}EdgeName", self.record);
    (quote!(#connection), quote!(#edge))
  }

  /// **THE SINGLE** — `<camel>(id:)`, in TWO LANES, and a miss is `null` rather than a refusal.
  ///
  /// It reads through the ID-GATHER lane rather than through `get`, and the difference is what the
  /// batch costs: `rows` takes a SLICE of ids and answers in one statement, so a loader asking for a
  /// hundred keys asks the question this asks for one. `get` would have been the same statement
  /// behind a signature that cannot batch.
  ///
  /// The engine answers `Ok(None)` on every miss path, so the wire face carries that answer rather
  /// than inventing a word for it — and a refusal that IS one crosses with the word its own type
  /// names, through `refused`.
  ///
  /// # The two lanes, and why the branch is a RUNTIME one
  ///
  /// The user's ruling of 2026-08-12: *走B吧, 不装loader 就慢一些呗* — the loader is OPTIONAL.
  ///
  /// ```text
  /// ctx.data_opt::<BatchDoor<Id, Row>>()
  ///   Some(door) → door.one(id)                      ← N keys, ONE statement
  ///   None       → rows(door.pool(), &[id])          ← today's lane, unchanged
  /// ```
  ///
  /// `data_opt` and not `data`, so ABSENCE DEGRADES rather than refusing: a build that installs
  /// nothing answers exactly what it answered before, at exactly the cost it cost before.
  /// `wire_batching.rs` is that number — three aliased singles, three statements — and
  /// `wire_batched.rs` is the same document with a door installed, at one.
  ///
  /// **The emission is UNCONDITIONAL**, and that is what makes the seam's feature independent: the
  /// door type is this framework's own and exists in every build, so nothing here asks whether the
  /// coalescing engine was compiled. What the `dataloader` feature gates is a BINDING an
  /// application reaches for when it mints a door, and no expansion names it.
  ///
  /// # The read door moved INTO the absent lane, and the ordering is preserved deliberately
  ///
  /// A resolver answering out of a batch never touches the pool, so a schema that installs a batch
  /// door and no read door is now a working configuration rather than a runtime error. That is the
  /// only behaviour change in the absent lane's neighbourhood, and the absent lane itself is
  /// byte-for-byte what it was: the door lookup is still the FIRST thing it does, ahead of the id
  /// crossing, so a request that is wrong in both ways still reads the door's refusal first. The
  /// crossing is written in both arms rather than hoisted above the match, which is what buys that.
  fn single_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
    let ag = self.framework(&[], "async_graphql");
    let door = self.framework(&["graphql"], "SqlDoor");
    let batch = self.framework(&["graphql"], "BatchDoor");
    let refused = self.framework(&["graphql"], "refused");
    let rows = self.framework(&["query", "sql"], "rows");
    let crossing = self.framework(&["graphql"], "ToGraphqlInput");
    let refused_address = self.framework(&["graphql"], "refused_address");
    let output = graphql.output.safe();
    let row = database.name();
    let backend = database.backend_type(self);
    let id_ty = &self.key.id.ty;
    let field = root_field(&super::wire::published_output(graphql, self));
    let method = wire_method(&format_ident!("{}", self.snake()));
    let ctx = wire_method(&format_ident!("ctx"));
    let id = wire_method(&format_ident!("id"));
    let raise = self.wire_crossing(graphql, database);
    quote! {
      #[graphql(name = #field)]
      async fn #method(
        &self,
        #ctx: &#ag::Context<'_>,
        #[graphql(name = "id")] #id: <#id_ty as #crossing>::Input,
      ) -> #ag::Result<::core::option::Option<#output>> {
        let __ingraph_hit = match #ag::Context::data_opt::<#batch<#id_ty, #row>>(#ctx) {
          // THE BATCHED LANE. The refusal is the batch's one refusal, carrying the word whoever
          // raised it chose — so `refused` attaches the same code the per-row lane's would, and a
          // client cannot tell which lane answered it.
          ::core::option::Option::Some(__ingraph_batch) => {
            let __ingraph_id = <#id_ty as #crossing>::cross(#id)
              .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
            #batch::one(__ingraph_batch, __ingraph_id)
              .await
              .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?
          }
          // THE PER-ROW LANE, unchanged.
          ::core::option::Option::None => {
            let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
            let __ingraph_id = <#id_ty as #crossing>::cross(#id)
              .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
            let __ingraph_rows = #rows::<#row, #backend, _>(
              #door::pool(__ingraph_door),
              ::core::slice::from_ref(&__ingraph_id),
            )
            .await
            .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
            ::core::iter::Iterator::next(
              &mut ::core::iter::IntoIterator::into_iter(__ingraph_rows),
            )
          }
        };
        match __ingraph_hit {
          ::core::option::Option::Some(__ingraph_row) => ::core::result::Result::Ok(
            ::core::option::Option::Some(#raise?),
          ),
          ::core::option::Option::None => {
            ::core::result::Result::Ok(::core::option::Option::None)
          }
        }
      }
    }
  }

  /// **THE LIST** — the relay arguments, an OPTIONAL `orderBy`, and the connection they describe.
  ///
  /// Nothing at all where the record has no order-by face: a page needs a written order, the
  /// order-by input object is what a client writes one with, and a record with no orderable column
  /// has neither. The single stands alone there, which is exactly the query such a record can answer.
  ///
  /// The two refusals a client can raise are raised from the ARGUMENTS, at `PageRequest::of` — the
  /// one door, so there is no second place a page is checked — and each crosses as its ratified word.
  /// An absent `orderBy` is not a refusal: `Orderings::default` is the empty order and the emitted
  /// `complete` puts the record's key at the end of every order, so the empty one IS the key
  /// ascending — total, and therefore pageable.
  ///
  /// # `where` — the argument that WAS not here, and the widening it was promised as
  ///
  /// It names `<E>Filter`, whose wire face was held behind the carrier axis. That axis landed, the
  /// face is emitted beside this leg under one condition ([`Self::wire_filters`]), and the promise
  /// this note carried is what the argument cashes: it is OPTIONAL and it is LAST, so a document
  /// that does not write it renders the query it always rendered and an SDL that gains it gains
  /// nothing but a suffix. An absent `where` is not the empty filter but no `filter(…)` call at all
  /// — which is the same predicate and one less clause for the engine to render.
  ///
  /// The CROSSING is `emit::cross`'s, reached at this database's concrete backend, and a refusal
  /// from it is `UNSUPPORTED_FILTER`: the schema is backend-neutral by design, so it offers operands
  /// a compiled store may not be able to hold.
  ///
  /// The condition [`Self::wire_filters`] states IS this leg's own two guards plus the database
  /// `queries_face` already found, so inside this function it holds by construction — which is why
  /// nothing here re-asks it.
  fn list_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
    if !self.orderable() || self.ordered_columns().is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let ag = self.framework(&[], "async_graphql");
    let door = self.framework(&["graphql"], "SqlDoor");
    let orderings = self.framework(&["graphql"], "Orderings");
    let connection = self.framework(&["graphql"], "Connection");
    let output = graphql.output.safe();
    let order_by = self.order_by.safe();
    let cursor = database.cursor_name();
    let backend = database.backend_type(self);
    let field = root_field(&super::wire::published_plural(graphql, self));
    let method = wire_method(&format_ident!("{}_list", self.snake()));
    let ctx = wire_method(&format_ident!("ctx"));
    let (order, first, last, after, before) = (
      wire_method(&format_ident!("order_by")),
      wire_method(&format_ident!("first")),
      wire_method(&format_ident!("last")),
      wire_method(&format_ident!("after")),
      wire_method(&format_ident!("before")),
    );
    let filter = graphql.filter.safe();
    let comparison = database.comparison_name();
    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
    let refused_filter = self.framework(&["graphql"], "refused_filter");
    // `where` is a Rust KEYWORD and `Ident::new` takes one — a keyword is a legal identifier
    // lexically, which is exactly the distinction `Ident::new_raw` exists on the other side of — so
    // the base is the plain ident and the prefix makes it spellable: `__async_graphql_where` is not
    // a keyword, so the parameter needs no `r#` and the emission carries none.
    //
    // The RAW spelling would panic here rather than work. `format_ident!` routes through
    // `quote::__private::ident_maybe_raw`, which re-attaches the `r#` it found and hands
    // `"__async_graphql_r#where"` to `Ident::new` — measured at quote 1.0.47, against
    // `method::wire_method`'s own note claiming the prefix is dropped. That note is corrected
    // there.
    let predicate = wire_method(&format_ident!("where"));
    // EIGHT parameters, which is one past clippy's threshold — see [`super::wide_signature`], where
    // the rule and the reason a consumer cannot edit around it are written down. The arity is this
    // emitter's own here rather than a declaration's, and it is the same eight for every record that
    // has the leg.
    let arity = super::wide_signature();
    let walk = self.page_walk(graphql, database);
    // The page's two SDL names. A return type is the only position that ever names a marker, which
    // is what keeps them private to this expansion's own const — and the LINEAGE leg closes on this
    // same pair, because the two legs page one record and one record has one page type.
    let (connection_name, edge_name) = self.page_name_arguments();
    quote! {
      #[graphql(name = #field)]
      #arity
      async fn #method(
        &self,
        #ctx: &#ag::Context<'_>,
        #[graphql(name = "orderBy")] #order: ::core::option::Option<#orderings<#order_by>>,
        #[graphql(name = "first")] #first: ::core::option::Option<u32>,
        #[graphql(name = "last")] #last: ::core::option::Option<u32>,
        #[graphql(name = "after")] #after: ::core::option::Option<::std::string::String>,
        #[graphql(name = "before")] #before: ::core::option::Option<::std::string::String>,
        // LAST, and that placement is the widening law rather than a preference: the SDL renders
        // arguments in declaration order, so an argument appended leaves every byte before it where
        // it was.
        #[graphql(name = "where")] #predicate: ::core::option::Option<#filter>,
      ) -> #ag::Result<#connection<#output, #cursor, #connection_name, #edge_name>> {
        let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
        // A LOCAL rather than an inline expression, because `Find::filter` BORROWS the predicate
        // for the whole walk — the tie `ComplexComparison::apply` already spells — so it has to
        // outlive the builder it is handed to. WHERE it sits among the argument checks buys
        // nothing and is not claimed to: no statement is rendered until `rows()`, so every refusal
        // below is raised before the store is touched whatever the order.
        let __ingraph_predicate = match #predicate {
          ::core::option::Option::Some(__ingraph_written) => ::core::option::Option::Some(
            <#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_written)
              .map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
          ),
          ::core::option::Option::None => ::core::option::Option::None,
        };
        // The list leg attaches NOTHING of its own: a page over a record is the whole record, and
        // the client's `where` is the only narrowing there is. The binding is written out rather
        // than left to the walk so that the walk has one shape instead of two.
        let __ingraph_scope: ::core::option::Option<#comparison<#backend>> =
          ::core::option::Option::None;
        #walk
      }
    }
  }

  /// **THE PAGE WALK** — everything a paged leg does once its predicate is decided, written once for
  /// the two legs that page.
  ///
  /// # Its contract, which is three names
  ///
  /// It reads `__ingraph_door`, `__ingraph_predicate` and `__ingraph_scope` — the latter two both
  /// `Option<<E><Db>Comparison<Backend>>` — and it reads the five relay arguments by the idents
  /// [`wire_method`] gives them. Everything else it brings. That is a narrow contract to state in a
  /// comment rather than in a signature, and stating it is what a token-level factoring costs: the
  /// alternative is the same forty lines in two emitters, where a fix to one is a divergence.
  ///
  /// The two predicates are the two PARTIES: `__ingraph_predicate` is what a client wrote and
  /// `__ingraph_scope` is what the leg attached. Both legs now bind both — the list leg's scope is
  /// `None` — so the shape here is one walk rather than a walk per leg.
  ///
  /// The factoring is [`Graphql::filter_rows`]'s own rule one layer up — a walk asked for twice is a
  /// walk two answers can disagree about — and what it protects here is the PAGE semantics: an
  /// absent order being the key ascending, both cursor directions, and the connection assembled
  /// without a re-wrap. A lineage leg that drifted on any of those would be a second pager nobody
  /// meant to write.
  ///
  /// The PREDICATES are deliberately outside it. What each leg BINDS is the whole of the difference
  /// between them: the list leg receives a filter and scopes nothing, the lineage leg does both.
  fn page_walk(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
    let refused = self.framework(&["graphql"], "refused");
    let orderings = self.framework(&["graphql"], "Orderings");
    let page_request = self.framework(&["graphql"], "PageRequest");
    let door = self.framework(&["graphql"], "SqlDoor");
    let order_by = self.order_by.safe();
    let cursor = database.cursor_name();
    let record = &self.record;
    let finder = database.kind().finder();
    let crossing = self.wire_crossing(graphql, database);
    let (order, first, last, after, before) = (
      wire_method(&format_ident!("order_by")),
      wire_method(&format_ident!("first")),
      wire_method(&format_ident!("last")),
      wire_method(&format_ident!("after")),
      wire_method(&format_ident!("before")),
    );
    quote! {
      let __ingraph_request = <#page_request<#cursor>>::of(
        #first,
        #last,
        ::core::option::Option::as_deref(&#after),
        ::core::option::Option::as_deref(&#before),
      )
      .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
      // The KEY DEFAULT's one door: an absent argument and `orderBy: []` reach the same empty
      // order, and the emitted `complete` is what makes the empty one total.
      let __ingraph_terms: ::std::vec::Vec<#order_by> = ::core::iter::Iterator::collect(
        ::core::iter::Iterator::cloned(
          #orderings::terms(&::core::option::Option::unwrap_or_default(#order)),
        ),
      );
      let __ingraph_found = #record::#finder(#door::pool(__ingraph_door));
      // An absent predicate is NO `filter(…)` call, not the empty one: the two ask for the same
      // rows, and only one of them leaves the builder's own `Option` alone.
      let __ingraph_found = match &__ingraph_predicate {
        ::core::option::Option::Some(__ingraph_narrowing) => {
          __ingraph_found.filter(__ingraph_narrowing)
        }
        ::core::option::Option::None => __ingraph_found,
      };
      // The SERVER's predicate, on the slot of its own, ANDed with the client's by the engine —
      // never merged into it. `Find::scope` carries why a merge could not hold both operands of a
      // column the two of them name together.
      let __ingraph_found = match &__ingraph_scope {
        ::core::option::Option::Some(__ingraph_scoping) => __ingraph_found.scope(__ingraph_scoping),
        ::core::option::Option::None => __ingraph_found,
      };
      let __ingraph_found = __ingraph_found.order(&__ingraph_terms);
      let __ingraph_page = match &__ingraph_request {
        #page_request::Forward { after: __ingraph_at, .. } => {
          let __ingraph_walk = __ingraph_found.first(#page_request::size(&__ingraph_request));
          match __ingraph_at {
            ::core::option::Option::Some(__ingraph_cursor) => {
              __ingraph_walk.after(__ingraph_cursor).rows().await
            }
            ::core::option::Option::None => __ingraph_walk.rows().await,
          }
        }
        #page_request::Backward { before: __ingraph_at, .. } => {
          let __ingraph_walk = __ingraph_found.last(#page_request::size(&__ingraph_request));
          match __ingraph_at {
            ::core::option::Option::Some(__ingraph_cursor) => {
              __ingraph_walk.before(__ingraph_cursor).rows().await
            }
            ::core::option::Option::None => __ingraph_walk.rows().await,
          }
        }
      }
      .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
      // The connection IS the answer, with nothing unwrapped and re-wrapped around it: the
      // crossing already refuses in the resolver's own error type, so an `Ok(…?)` here would be
      // `clippy::needless_question_mark` inside an expansion its author cannot edit.
      __ingraph_page.into_connection(|__ingraph_row| #crossing)
    }
  }

  /// **THE LINEAGE** — `<camel>Lineage(<step>: …, …)`, the rows under ONE ancestry, paged.
  ///
  /// # A walk is a read under a predicate, and this is the leg that BUILDS one
  ///
  /// The list leg receives a filter, the client having written it. This one MINTS one as well: the
  /// ancestry arrives as ARGUMENTS — one per lineage step, root-first, exactly as the key carries
  /// them — and a predicate is built from them. That is the whole difference between the two legs,
  /// and everything after the predicates is [`Self::page_walk`]'s.
  ///
  /// # It takes a `where` TOO, and the two predicates are ANDed rather than merged
  ///
  /// The ruling is a plain conjunction: a client's filter narrows INSIDE the ancestry, and a filter
  /// that contradicts the scope answers with no rows by set law rather than with a refusal. So the
  /// leg binds both — the ancestry to `__ingraph_scope`, the client's `where` to
  /// `__ingraph_predicate` — and the engine's two slots keep them apart all the way to the one
  /// `WHERE` they render into.
  ///
  /// **They are two VALUES because one could not hold them.** Merging the client's filter with the
  /// ancestry means writing both into one `<E>Filter`, whose column slot holds ONE operand — so
  /// `takeLineage(reelId: 1, where: { reelId: { eq: 2 } })` would silently become whichever of the
  /// two was written last, and answer reel 1's rows or reel 2's instead of neither. The same is true
  /// one layer down, since a comparison struct is a column-per-field mirror of the filter. Two
  /// values applied to one accumulator is the only shape that can express its own contradiction, and
  /// [`Find::scope`](../../../ingraph/query/sql/struct.Find.html#method.scope) is where that is
  /// written down.
  ///
  /// The client's half crosses EXACTLY as the list leg's does — same `TryFromFilter`, same
  /// `UNSUPPORTED_FILTER` — because it is the same argument on a second field, and a second crossing
  /// would be a second thing to keep in step.
  ///
  /// The minting is one line per step: [`EqualsFilter`] at the column's own declared type, into the
  /// filter struct's own `with_*` builder. Neither call names a filter KIND, which is what makes it
  /// writable at all — the projection layer is type-blind, so a column's filter reaches here as
  /// `<<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter` and not as a spelling. A step whose
  /// filter has no equality row is `E0277` naming that pair, which is the crossing's own posture one
  /// layer down.
  ///
  /// # What it is emitted for, and what each absence means
  ///
  /// A record with NO lineage gets no leg, and that is the whole of the refusal: a root's ancestry
  /// is the empty path, so there is no argument to take and no scope to name. Presence is the
  /// enablement, exactly as the list leg's order-by face is.
  ///
  /// A FAN-IN's lineage gets none either, and [`Lineage::path`] is where that falls out rather than
  /// a rule written twice: its columns vary between ROWS — which upstream a row came from decides
  /// what it carries — so there is no one set of arguments that scopes such a walk, and `path()`
  /// answers a fan-in with nothing.
  ///
  /// A step that is not a STORED column gets none, and for the reason the filter has no field for
  /// it: `<E>Filter` is mechanical from the stored columns, and a lineage a declaration keeps out of
  /// its tables is an ancestry no predicate can name. The corpus carries such a record —
  /// `fixtures.rs`'s `VideoTrack`, whose `media_id` is `copy` and not `persist`.
  ///
  /// # The ARGUMENTS come first, and the relay arguments follow them
  ///
  /// Root-first among themselves, because that is the order the key walks and the order the address
  /// object publishes; before the page arguments, because the single puts its `id:` first and this
  /// is the same act — an address is named, then the page over it is described.
  fn lineage_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
    let steps = self.lineage_steps(graphql);
    if steps.is_empty() || !self.orderable() || self.ordered_columns().is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let ag = self.framework(&[], "async_graphql");
    let door = self.framework(&["graphql"], "SqlDoor");
    let orderings = self.framework(&["graphql"], "Orderings");
    let connection = self.framework(&["graphql"], "Connection");
    let equals = self.framework(&["graphql"], "EqualsFilter");
    let crossing = self.framework(&["graphql"], "ToGraphqlInput");
    let refused_address = self.framework(&["graphql"], "refused_address");
    let refused_filter = self.framework(&["graphql"], "refused_filter");
    let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
    let output = graphql.output.safe();
    let order_by = self.order_by.safe();
    let filter = graphql.filter.safe();
    let comparison = database.comparison_name();
    let cursor = database.cursor_name();
    let backend = database.backend_type(self);
    let field = format!(
      "{}Lineage",
      root_field(&super::wire::published_output(graphql, self))
    );
    let method = wire_method(&format_ident!("{}_lineage", self.snake()));
    let ctx = wire_method(&format_ident!("ctx"));
    let (order, first, last, after, before) = (
      wire_method(&format_ident!("order_by")),
      wire_method(&format_ident!("first")),
      wire_method(&format_ident!("last")),
      wire_method(&format_ident!("after")),
      wire_method(&format_ident!("before")),
    );
    let parameters = steps.iter().map(|step| {
      let (name, ident, wire) = (&step.field, &step.parameter, &step.wire);
      quote!(#[graphql(name = #name)] #ident: <#wire as #crossing>::Input,)
    });
    // Each step CROSSES exactly as the single's `id:` does, and refuses under the same word: a
    // lineage argument IS an address, one segment of the root-first path the key publishes, so
    // `UNUSABLE_ADDRESS` is the fact rather than a second word for it.
    let ancestry = steps.iter().map(|step| {
      let (ident, wire, with, guard) = (&step.parameter, &step.wire, &step.with, &step.filter);
      quote! {
        .#with(<#guard as #equals<#wire>>::equals(
          <#wire as #crossing>::cross(#ident)
            .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?,
        ))
      }
    });
    // `where` is a Rust KEYWORD, and the prefix is what makes it spellable — `list_leg`'s own note
    // carries why the RAW spelling would panic here rather than work.
    let predicate = wire_method(&format_ident!("where"));
    // The step count is a DECLARATION's — the corpus carries a seven-step path — so this signature's
    // arity is unbounded from here, where the other two legs' are the emitter's own.
    let arity = super::wide_signature();
    let walk = self.page_walk(graphql, database);
    // The SAME pair the list leg closes on. A page over a record IS the record's page whichever leg
    // asked for it, so the two return types name one connection and one edge — and the alternative
    // is not a tidiness question: a lineage leg on the library's defaults publishes a SECOND page
    // type for one record the moment the record's names are anything but `<Node>Connection`, which
    // under the plural base is every record.
    let (connection_name, edge_name) = self.page_name_arguments();
    quote! {
      #[graphql(name = #field)]
      #arity
      async fn #method(
        &self,
        #ctx: &#ag::Context<'_>,
        #(#parameters)*
        #[graphql(name = "orderBy")] #order: ::core::option::Option<#orderings<#order_by>>,
        #[graphql(name = "first")] #first: ::core::option::Option<u32>,
        #[graphql(name = "last")] #last: ::core::option::Option<u32>,
        #[graphql(name = "after")] #after: ::core::option::Option<::std::string::String>,
        #[graphql(name = "before")] #before: ::core::option::Option<::std::string::String>,
        // LAST, and for the list leg's own reason: the SDL renders arguments in declaration order,
        // so an argument appended leaves every byte before it where it was. This leg's widening is
        // therefore the same one its neighbour already proved.
        #[graphql(name = "where")] #predicate: ::core::option::Option<#filter>,
      ) -> #ag::Result<#connection<#output, #cursor, #connection_name, #edge_name>> {
        let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
        // Through the record's OWN filter and its own crossing, rather than into the comparison
        // directly: a declared operand converter is the crossing's business, so a lineage step that
        // stores through one takes the same road its `where` counterpart does and the two cannot
        // come to disagree about a column.
        let __ingraph_ancestry = <#filter as ::core::default::Default>::default() #(#ancestry)*;
        let __ingraph_scope = ::core::option::Option::Some(
          <#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_ancestry)
            .map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
        );
        // The CLIENT's half, crossed exactly as the list leg crosses its own — and held apart from
        // the scope rather than folded into it, which is what lets the two contradict.
        let __ingraph_predicate = match #predicate {
          ::core::option::Option::Some(__ingraph_written) => ::core::option::Option::Some(
            <#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_written)
              .map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
          ),
          ::core::option::Option::None => ::core::option::Option::None,
        };
        #walk
      }
    }
  }

  /// The lineage path as the LEG reads it: one step per ancestry column, root-first, and nothing at
  /// all where any of the three conditions [`Self::lineage_leg`] states does not hold.
  ///
  /// The two lists are joined on the RECORD FIELD, which is the only name both carry: a lineage
  /// column wears the name its own type gave it — `lineage(rename = "…")` moves it — and a stored
  /// column wears its database's. `source` is what neither rename touches.
  fn lineage_steps(&self, graphql: &Graphql) -> Vec<LineageStep> {
    let Some(lineage) = self.lineage.as_ref() else {
      return Vec::new();
    };
    let path = lineage.path();
    if path.is_empty() {
      return Vec::new();
    }
    let rows = graphql.filter_rows(self);
    let steps: Vec<LineageStep> = path
      .iter()
      .filter_map(|step| {
        // Found by MEMBER rather than at an index: a filter row's member IS the record field the
        // column projects, and the two lists have never been index-aligned — `graphql(skip)`
        // compacts the rows and the shared list is the declaration's, so a position read off one
        // would name another step or none.
        let row = rows.iter().find(|row| row.member == step.source)?;
        Some(LineageStep {
          field: super::wire::wire_field(&row.declared, &row.member),
          parameter: wire_method(&row.member),
          with: crate::method::Member::With.name(&row.member),
          wire: row.wire.clone(),
          filter: row.filter.clone(),
        })
      })
      .collect();
    // ALL of them or none: a walk scoped by some of an ancestry is a walk over the wrong set, and
    // silently answering a narrower question than the field's name promises is worse than not
    // offering the field.
    if steps.len() == path.len() {
      steps
    } else {
      Vec::new()
    }
  }

  /// One ROW raised onto the wire, as an expression over `__ingraph_row` answering
  /// `Result<Output, async_graphql::Error>`.
  ///
  /// `TryFrom` at both arms, and that is what lets ONE expression serve a crossing that may or may
  /// not be fallible: std's blanket gives every `From` a `TryFrom` whose error is `Infallible`, so a
  /// record with no declared conversion takes the same shape as one whose `output(<db>(from = …))`
  /// can refuse, and neither is spelled twice here.
  ///
  /// The refusal crosses as `UNREADABLE_ROW` through `refused_row` — the word the ENGINE's own
  /// crossing already answers under, and the same nothing asked of the client.
  fn wire_crossing(
    &self,
    graphql: &Graphql,
    database: &DatabaseBackend,
  ) -> proc_macro2::TokenStream {
    let output = graphql.output.safe();
    let row = database.name();
    let refused_row = self.framework(&["graphql"], "refused_row");
    quote! {
      <#output as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row)
        .map_err(|__ingraph_refusal| #refused_row(&__ingraph_refusal))
    }
  }

  /// The record's own name in snake case — what the emitted function idents are built from before
  /// the `__async_graphql_` prefix.
  ///
  /// The RUST side only. What a client reads is written out per item, so this never reaches a schema
  /// and a rename of the published type moves the field without moving the ident.
  fn snake(&self) -> String {
    use heck::ToSnakeCase as _;

    self.record.to_string().to_snake_case()
  }
}