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
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
//! Every method an emission declares, and the ONE place a derived name is shaped.
//!
//! A method's name comes from a COLUMN's — `x`, `x_ref`, `x_slice`, `set_x`, `with_x` — and a few
//! are fixed beside them: the positional `new` on each address type and on each comparison, and
//! one order-by resolver per database. Nothing about Rust keeps two of those apart. A `copy`
//! column called `new` gives its address type a second `new`; a `copy` column called `set_x`
//! beside a column called `x` gives the record two `set_x`; and a column called `x_ref` beside one
//! called `set_x` gives it two `set_x_ref` with no marker involved at all.
//!
//! Each is `E0592`, and each lands INSIDE the expansion — the span is `#[ingraph::record(…)]`, which
//! the author cannot edit, and the message never says which column caused it. So a front end
//! refuses the declaration instead, and this module is what it asks.
//!
//! **A LIST of derived shapes kept in the front end would be a second copy of what [`crate::emit`]
//! writes, and two copies of a derived-name list is how one of them drifts** — the same reason
//! `ingraph-derive`'s column fence is a namespace rather than a list. Here the shapes have one
//! home each: [`Member::name`] for the accessor family's suffixes, [`wire_method`] for the
//! `__async_graphql_` prefix an emitted `#[Object]` face's functions wear, and — for the names a
//! DERIVED INDEX mints from a field of its own — [`fan_door`], [`fold_accessor`] and [`Door::name`].
//! Every emitter site calls one of them to build the ident it emits; nothing spells a suffix or a
//! prefix anywhere else.
//!
//! What a shared function cannot fix is MEMBERSHIP — which of those names a given type really
//! declares — because that follows the emitter's walk rather than any one name's shape. So it is
//! not written twice either: it is asserted against the emission itself by
//! `tests::the_enumeration_names_exactly_the_methods_the_emission_declares` — and by the derived
//! index's own twin in [`crate::index`]'s `audits` — which read every inherent method back out of
//! the tokens and demand the same list in the same order. A name the emitter grows and this module
//! does not know about fails there.
//!
//! The enumeration is a STATEMENT ABOUT THE EMISSION, which is this crate's subject; the refusal
//! is the front end's, which holds the spans to report at. That is the split [`crate::model`]
//! already draws, and it is why nothing here pushes an error.

use core::fmt;

use quote::format_ident;

use crate::model::{Column, DatabaseKind, Projection, RecordModel};

#[cfg(test)]
mod prefix_tests;

/// Which member of a column's method family a name belongs to.
///
/// The whole vocabulary of derived names. A caller names one rather than spelling a suffix,
/// because a suffix written twice is a suffix that can be written differently.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Member {
  /// `x` — the by-value accessor a `copy` column gets IN ADDITION to its borrow.
  Value,
  /// `x_ref` — the borrow.
  Borrow,
  /// `x_slice` — a `repeated` column's slice.
  Slice,
  /// `set_x` — the in-place setter.
  Set,
  /// `with_x` — the chaining builder.
  With,
}

impl Member {
  /// What this member is called over a column named `column`.
  pub fn name(self, column: &syn::Ident) -> syn::Ident {
    match self {
      Self::Value => column.clone(),
      Self::Borrow => format_ident!("{column}_ref"),
      Self::Slice => format_ident!("{column}_slice"),
      Self::Set => format_ident!("set_{column}"),
      Self::With => format_ident!("with_{column}"),
    }
  }

  /// What this member IS, for a message that has to tell two colliding names apart.
  pub const fn what(self) -> &'static str {
    match self {
      Self::Value => "value accessor",
      Self::Borrow => "borrow accessor",
      Self::Slice => "slice accessor",
      Self::Set => "setter",
      Self::With => "builder",
    }
  }
}

/// The `__async_graphql_` prefix every FUNCTION an emitted `#[Object]` face declares wears — and
/// every ARGUMENT such a function takes.
///
/// # The prefix names the BACKEND, and that is the ruling rather than a decoration
///
/// The user's ruling of 2026-08-13: *async-graphql 的都要加前缀,通过 rename 避免冲突,前缀用
/// `__async_graphql_xxx` 因为以后可能支持更多 graphql 后端*.
///
/// So the Rust namespace is PER BACKEND. A second GraphQL binding mounted on the same emitted type
/// mints `__smear_<name>` beside `__async_graphql_<name>` and the two cannot meet — where a shared
/// `__<name>` would have made the first backend's face the reason the second one cannot be written,
/// reported as `E0592` inside an expansion whose author cannot edit either half. The prefix is not
/// the collision-proofing alone; it is WHOSE face this is, spelled into the ident.
///
/// The WIRE face is unmoved by any of it: the name a CLIENT reads is written beside the ident as
/// `#[graphql(name = "…")]`, per item and never derived from a spelling — see `emit::wire`'s own
/// note — so the ident is free to carry the backend's name and a schema cannot tell that it does.
///
/// # Why the wire face's Rust names are ugly on purpose
///
/// A method inside `#[Object]` is not a Rust API: nothing outside the expansion calls it, and it is
/// reached through the schema. So the ident is free to be defensive, and it is: the prefix puts
/// every generated function and argument in a namespace no declaration writes — the same vaccine
/// the emission's own `__ingraph_*` locals already carry, applied at the one position that had
/// none. `emit::wire`'s prelude note records what the class costs when it is not taken: a foreign
/// macro's bare `None` captured by a declarer's `struct None`, reported at a `#[record(…)]` naming
/// a type nobody in that file mentions.
///
/// Those LOCALS keep `__ingraph_` and are not swept into the backend's namespace, because they are
/// a different question: a local is scoped to the body it is written in, so two backends' bodies
/// cannot collide however they spell theirs, and what the prefix answers there is *whose crate
/// wrote this*, which is the framework's rather than any binding's.
///
/// TYPES take no prefix, and that is the ruled other half: `<E>GraphqlOutput` and `<E>KeyOutput` are
/// visible vocabulary a declaration names and an application mounts, so a mangled one would be an
/// emitter's convention leaking into somebody else's code.
///
/// Here rather than beside either emitter, for this module's own reason: a derived name has ONE
/// home, and a prefix written twice is a prefix that can be written differently. Every emitted face
/// calls this — `emit::wire`'s two objects, `emit::queries`' three legs and their arguments,
/// `interface::queries`' leg — so a change to the shape moves all of them at once, which is what
/// made this sweep a one-line edit under a walk rather than a rename across the corpus.
pub fn wire_method(name: &syn::Ident) -> syn::Ident {
  // A prefixed name is never a keyword, so nothing has to put a raw prefix back — which is what
  // makes `where` an argument this can be handed at all: `Ident::new` takes a keyword (a keyword is
  // a legal identifier lexically), and `__async_graphql_where` is an ordinary ident.
  //
  // **A CORRECTION, measured.** This claimed `format_ident!` renders an `Ident` through
  // `IdentFragment`, which drops a raw prefix, so a column called `r#type` would arrive as
  // `__type`. It does not, at quote 1.0.47: the macro routes through
  // `quote::__private::ident_maybe_raw`, which re-attaches the `r#` it stripped and hands
  // `"__async_graphql_r#type"` to `Ident::new`, whose panic is *not a valid identifier* — measured
  // by handing this function `Ident::new_raw("where", …)` and reading the panic at the
  // `#[record(…)]`. So a RAW ident must not reach here; a caller that has one hands the plain
  // spelling, which is what every caller does.
  format_ident!("__async_graphql_{name}")
}

/// The `fan_<field>` WRITE DOOR a `fanout`-marked field of a derived index gets — one name, here
/// rather than beside the emitter, for [`wire_method`]'s reason.
///
/// It is the ONE name the engine grammar mints into a declaration's own inherent impl, and it is
/// derived from a FIELD, which is what puts it in this module: a `copy` field called `fan_title`
/// beside a fanned `title` gives the index two `fan_title`, at a span the declaration cannot edit.
/// The enumeration below is what lets a front end say so first, and it reads this function.
pub fn fan_door(field: &syn::Ident) -> syn::Ident {
  format_ident!("fan_{field}")
}

/// The `fold_by_<field>` accessor a SET election gets — what `semantics(fold = "…")` is spent on.
///
/// Beside [`fan_door`] and for its reason: a derived name has one home, and this one is derived from
/// an elected field, so a `copy` field spelled like it collides on the declaration's own type.
pub fn fold_accessor(field: &syn::Ident) -> syn::Ident {
  format_ident!("fold_by_{field}")
}

/// WHICH of a derived index's RETRIEVE doors a name belongs to — the vocabulary the emitted read
/// surface is spelled from.
///
/// [`Member`] one family over: a column's accessors are derived from a column's name, and these are
/// derived from an ELECTION's, so the same rule applies to both — the suffix has one home, and a
/// caller names a door rather than spelling `retrieve_keys_by_`. Every one of them lands on the
/// declaration's own type, so every one of them can be reached by a field a declaration chose.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Door {
  /// TIER A — `retrieve_keys_by_<field>`, or `retrieve_keys` for the unelected full-text subject.
  Keys,
  /// TIER B — `retrieve_by_<field>`, or `retrieve` for that same subject.
  Whole,
  /// BY KEY — `get_<field>`, this entity's own stored embedding, checked.
  Own,
  /// BY EXAMPLE — `retrieve_similar_by_<field>`.
  Similar,
  /// SET-SIMILARITY — `retrieve_keys_by_<field>_with`, the door a `list(embedding)` election gets.
  Set,
  /// SET-SIMILARITY BY EXAMPLE — `retrieve_similar_by_<field>_with`, the by-example door asked
  /// with the example's WHOLE SET.
  SimilarSet,
  /// FUSED — `vector_fuse`, every route of one modality asked at once. UNELECTED, because the door
  /// is the TIER's rather than any one route's.
  Fused,
  /// FUSED BY EXAMPLE — `vector_fuse_similar`, at the tier's own key.
  FusedSimilar,
  /// FUSED, ONE FANNED SLOT — `vector_fuse_by_<field>`, every LEG of one election asked at once.
  ///
  /// ELECTED where [`Fused`](Self::Fused) is not, and that is the fractal read one level down: this
  /// door is one FIELD's, its routes being the stores that field is written to rather than the
  /// fields a declaration elected.
  FusedLegs,
  /// FUSED, ONE FANNED SLOT, BY EXAMPLE — `vector_fuse_similar_by_<field>`.
  FusedLegsSimilar,
}

impl Door {
  /// What this door is called over the election named `election`.
  pub fn name(self, election: &syn::Ident) -> syn::Ident {
    match self {
      Self::Keys => format_ident!("retrieve_keys_by_{election}"),
      Self::Whole => format_ident!("retrieve_by_{election}"),
      Self::Own => format_ident!("get_{election}"),
      Self::Similar => format_ident!("retrieve_similar_by_{election}"),
      // The SET door is the tier-A name plus one suffix, which is how the emission writes it: the
      // two are one road asked with `m` vectors instead of one, and a reader scanning the impl sees
      // the pair rather than two unrelated spellings.
      Self::Set => format_ident!("{}_with", Self::Keys.name(election)),
      // The same suffix, over the by-example name — so the two `_with` doors read as one word
      // spent twice rather than as two spellings a caller has to learn separately.
      Self::SimilarSet => format_ident!("{}_with", Self::Similar.name(election)),
      // The two fused doors take NO suffix, because they are not about one election. `name` is
      // still where they are spelled, so a collision reports them like every other door.
      Self::Fused => format_ident!("vector_fuse"),
      Self::FusedSimilar => format_ident!("vector_fuse_similar"),
      // The SLOT-grain fused pair takes the `_by_<field>` suffix every per-election door takes,
      // because it IS about one election — a fanned slot is a tier whose routes are stores, and the
      // field it is about is exactly what tells one of these doors from another.
      Self::FusedLegs => format_ident!("vector_fuse_by_{election}"),
      Self::FusedLegsSimilar => format_ident!("vector_fuse_similar_by_{election}"),
    }
  }

  /// The TIER PAIR over one subject: an election's, or the ONE subject a full-text index answers
  /// under — which is UNSUFFIXED, because a slot is `(field × engine)` and is therefore already the
  /// answer to *which field*.
  ///
  /// The pair is the only part of this vocabulary with an unelected spelling, and it is written as a
  /// PAIR rather than as a per-variant answer for exactly that reason: the four doors below it are
  /// minted per election — a by-key read names the column it reads — so a shape that admitted `None`
  /// there would be a partial function with no total caller.
  pub fn pair(election: Option<&syn::Ident>) -> (syn::Ident, syn::Ident) {
    match election {
      Some(field) => (Self::Keys.name(field), Self::Whole.name(field)),
      None => (format_ident!("retrieve_keys"), format_ident!("retrieve")),
    }
  }

  /// What this door IS, for a message that has to tell two colliding names apart.
  const fn what(self) -> &'static str {
    match self {
      Self::Keys => "ranked-keys door",
      Self::Whole => "whole-entities door",
      Self::Own => "by-key read",
      Self::Similar => "by-example door",
      Self::Set => "set-similarity door",
      Self::SimilarSet => "set-similarity by-example door",
      Self::Fused => "fused door",
      Self::FusedSimilar => "fused by-example door",
      Self::FusedLegs => "fanned-slot fused door",
      Self::FusedLegsSimilar => "fanned-slot fused by-example door",
    }
  }
}

/// The payload of [`Origin::Door`]: which door, and the election it answers about.
///
/// The election is [`None`] for the ONE unelected subject — a full-text index's unsuffixed pair —
/// and [`Some`] everywhere else, which is exactly the split [`Door::pair`] draws.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DoorOrigin {
  /// Which door.
  pub door: Door,
  /// The election it answers about, or [`None`] for the unelected pair.
  pub election: Option<syn::Ident>,
}

/// The payload of [`Origin::Column`]: which column, and which member of its family.
///
/// One member of one column's family, under the name that column carries IN THE OWNING TYPE: a
/// scoped rename moves the method with the column it renames.
///
/// Named for the origin rather than sharing the variant's name, because [`Column`] is the model's
/// own type and this module reads it. Fields are `pub` and constructed by literal, which is what
/// every model struct this crate carries does — [`Emitted`] below is the nearest one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnOrigin {
  /// The column, as its own type names it.
  pub column: syn::Ident,
  /// Which of the family this is.
  pub member: Member,
}

/// What produced an emitted method's name.
///
/// Comparable, because two emitted methods with the same origin are the downstream of a DUPLICATE
/// COLUMN NAME rather than of two columns meeting: every member of the two families collides at
/// once, so a front end that reported them would repeat another rule's finding five times over.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Origin {
  /// The type's own positional `new` — a name the emitter fixes rather than one a declaration
  /// chose.
  Constructor,
  /// A derived index's `key_ref` — the borrow of the upstream key it carries, and a fixed name for
  /// the reason the constructor's is.
  BorrowedKey,
  /// One member of one column's family — see [`ColumnOrigin`].
  Column(ColumnOrigin),
  /// One name of the FUSE family — a package accessor, a question row or the column vocabulary's
  /// projection, on the type the tier minted it for. See [`FuseOrigin`].
  Fuse(FuseOrigin),
  /// One database's order-by resolver — `sqlite_column`.
  Resolver(DatabaseKind),
  /// The order-by's `direction` — its other half, and the half no database refines.
  Direction,
  /// One database's order-by LOWERING — `sqlite_order_by`, which consumes both halves above.
  Lowering(DatabaseKind),
  /// The order-by's rename-proof IDENTITY — the name a per-database rename cannot move, and the
  /// only input a cursor's signature takes from a term.
  Identity,
  /// One database's order-by TERM — `sqlite_term`, which pairs the identity with this database's
  /// column, the direction and the column's nullability.
  Term(DatabaseKind),
  /// The order-by's id TAIL — `complete`, which is no database's, because which column holds the id
  /// is the record's and no rename moves it.
  Complete,
  /// One database's plural entry point — `find_sqlite`.
  Finder(DatabaseKind),
  /// One database's plural entry point inside a read transaction — `find_sqlite_snapshot`.
  Snapshot(DatabaseKind),
  /// One database's single entry point — `get_sqlite`.
  Getter(DatabaseKind),
  /// One database's plain WRITE — `insert_sqlite`.
  Inserter(DatabaseKind),
  /// One database's KEYED REPLACE — `upsert_sqlite`.
  Upserter(DatabaseKind),
  /// One database's REMOVAL at an address — `delete_sqlite`.
  Deleter(DatabaseKind),
  /// One database's REMOVAL over a predicate — `delete_sqlite_where`.
  ///
  /// Beside the getter's road rather than beside it in name, and that is the roster's own grammar:
  /// the address door and the predicate door are two verbs on the read side too — `get_<db>` and
  /// `find_<db>` — so the removal half has two as well.
  Purger(DatabaseKind),
  /// The wire OUTPUT object's own two members — the row's id, and its whole address. Fixed names
  /// rather than a declaration's, as the constructor's is.
  Address,
  /// One member of the wire ARGUMENT object — the filter, the ceiling, the order, a page argument.
  /// Fixed names too: they mirror the engine's find surface, which no declaration renames.
  Argument,
  /// The QUERY UNIT's own root FIELDS — the single and the list. Fixed names, built from the
  /// record's own, so no declaration chooses either.
  RootField,
  /// A `fanout` field's WRITE DOOR — `fan_<field>`, named after the field whose engines it writes.
  ///
  /// The FIELD rides the variant because the sentence has to name it: two names meeting here are a
  /// declaration's own field and another of its fields' fan, and a message that said only *the fan
  /// door* would leave the reader to find out whose.
  Fan(syn::Ident),
  /// A SET election's DECLARED FOLD — `fold_by_<field>`, likewise named after its election.
  Fold(syn::Ident),
  /// One of a derived index's RETRIEVE doors — see [`DoorOrigin`].
  Door(DoorOrigin),
  /// One `delegate(fn …)` entry — the method the DECLARATION restated, at the name it wrote.
  ///
  /// The ident rides the variant and IS the declared token, which is what makes this the one derived
  /// family whose refusal points at an author's own word rather than at the field it was built from:
  /// a delegate's name is not derived from anything, it is restated, so the caret belongs on the
  /// restatement.
  Delegate(syn::Ident),
  /// A vocabulary MIRROR's restated-variant roster — `VARIANTS`.
  ///
  /// An associated CONST rather than a method, and it is enumerated all the same: Rust's value
  /// namespace holds consts and functions together, so a `fn VARIANTS` beside it is a duplicate
  /// definition exactly as a second `fn remote` would be. What the enumeration is FOR is the names
  /// an expansion puts in a scope, and this is one of them.
  Roster,
  /// A vocabulary MIRROR's single materialization gate — `remote()`.
  ///
  /// A fixed name rather than a declaration's, as the constructor's is: every rendering, every bind
  /// and every delegated call reads through it, so the mode has one word for it and no knob moves it.
  Materialization,
  /// ONE variant's predicate on a vocabulary — `is_rgb24`, built from the variant's own name.
  ///
  /// The VARIANT rides the variant because the sentence has to name it: a delegated entry meeting
  /// `is_bayer` has met a specific variant's question, and a message saying only *a predicate* would
  /// leave the reader to work out whose.
  Predicate(syn::Ident),
  /// A MongoDB document's own EXTRACTION — `from_document`, the bson twin of the `FromRow` impl the
  /// SQL family emits.
  ///
  /// It is here and its SQL counterpart is not, and the difference is the ITEM rather than the
  /// backend: `from_row` lands in a TRAIT impl, which this enumeration does not walk, where the bson
  /// twin is INHERENT — the trait it would implement is the framework's, and the era rule is what
  /// that is over. So it occupies a name in the declaring scope and has to be enumerated like every
  /// other name the emission puts there.
  Extraction,
}

impl Origin {
  /// The DECLARED token a refusal about this name points at, or `None` for a name no declaration
  /// chose.
  ///
  /// The method's own ident is not that token: [`Member::name`] builds it through `format_ident!`,
  /// whose span is the macro's call site — which is exactly the span `E0592` already reports at
  /// and the reason this rule exists.
  pub const fn column(&self) -> Option<&syn::Ident> {
    match self {
      Self::Column(origin) => Some(&origin.column),
      // The one derived family whose ident IS an author's token: a delegate's name is RESTATED
      // rather than built, so the caret belongs on the restatement the declaration wrote.
      Self::Delegate(method) => Some(method),
      Self::Constructor
      | Self::BorrowedKey
      | Self::Resolver(_)
      | Self::Direction
      | Self::Lowering(_)
      | Self::Identity
      | Self::Term(_)
      | Self::Complete
      | Self::Finder(_)
      | Self::Snapshot(_)
      | Self::Getter(_)
      | Self::Inserter(_)
      | Self::Upserter(_)
      | Self::Deleter(_)
      | Self::Purger(_)
      | Self::Address
      | Self::Argument
      | Self::RootField
      // The three a derived index adds are fixed names too, and their idents carry a declared span
      // for a reason that does NOT make them this token: `fan_title` is derived FROM `title`, so a
      // caret on `title` would send an author to rename the field whose fan is correct. The other
      // side of such a collision is a column, and the front end reads its token instead.
      | Self::Fan(_)
      | Self::Fold(_)
      | Self::Door(_)
      | Self::Extraction
      // The vocabulary tier's three, by the same argument. `VARIANTS` and `remote` are fixed words
      // no declaration chose; `is_rgb24` is derived FROM the variant `Rgb24`, so a caret there would
      // send an author to rename the variant whose predicate is correct. The other side of such a
      // collision is a DELEGATED entry, whose ident is a restatement the author wrote — and the
      // reader below takes that one instead.
      | Self::Roster
      | Self::Materialization
      | Self::Predicate(_)
      // A fuse name is derived from the index and a knob's fixed word — the same argument as the
      // fan's: no declared token IS the name.
      | Self::Fuse(_) => None,
    }
  }
}

impl fmt::Display for Origin {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Constructor => f.write_str("the type's own constructor"),
      Self::BorrowedKey => f.write_str("the borrow of the upstream key it carries"),
      Self::Column(origin) => write!(
        f,
        "the `{}` column's {}",
        origin.column,
        origin.member.what()
      ),
      Self::Resolver(kind) => write!(f, "the `{}` order-by resolver", kind.as_str()),
      Self::Direction => f.write_str("the order-by's direction accessor"),
      Self::Lowering(kind) => write!(f, "the `{}` ordering lowering", kind.as_str()),
      Self::Identity => f.write_str("the order-by's identity accessor"),
      Self::Term(kind) => write!(f, "the `{}` ordering term", kind.as_str()),
      Self::Complete => f.write_str("the order-by's id tail"),
      Self::Finder(kind) => write!(f, "the `{}` plural query", kind.as_str()),
      Self::Snapshot(kind) => write!(
        f,
        "the `{}` plural query in a read transaction",
        kind.as_str()
      ),
      Self::Getter(kind) => write!(f, "the `{}` single query", kind.as_str()),
      Self::Inserter(kind) => write!(f, "the `{}` insert", kind.as_str()),
      Self::Upserter(kind) => write!(f, "the `{}` keyed replace", kind.as_str()),
      Self::Deleter(kind) => write!(f, "the `{}` removal at an address", kind.as_str()),
      Self::Purger(kind) => write!(f, "the `{}` removal over a predicate", kind.as_str()),
      Self::Address => f.write_str("the output object's own address member"),
      Self::Argument => f.write_str("the argument object's own member"),
      Self::RootField => f.write_str("the query unit's own root field"),
      Self::Fan(field) => write!(f, "the `{field}` field's fan door"),
      Self::Fold(field) => write!(f, "the `{field}` election's declared fold"),
      Self::Door(origin) => match &origin.election {
        Some(field) => write!(f, "the `{field}` election's {}", origin.door.what()),
        None => write!(f, "the {}", origin.door.what()),
      },
      Self::Delegate(method) => write!(f, "the delegated `{method}`"),
      Self::Roster => f.write_str("the mirror's own restated-variant roster"),
      Self::Materialization => f.write_str("the mirror's own upstream materialization"),
      Self::Predicate(variant) => write!(f, "the `{variant}` variant's predicate"),
      Self::Extraction => f.write_str("the document's own extraction"),
      Self::Fuse(origin) => write!(
        f,
        "the fuse family's `{}` on `{}`",
        origin.member, origin.on
      ),
    }
  }
}

/// The payload of [`Origin::Fuse`]: WHICH minted type carries the name, and the member it is.
///
/// The type is named because the fuse family mints many packages beside one declaration, and a
/// collision message that said only "the fuse family's `ceiling`" could not say which package's.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FuseOrigin {
  /// The minted type the method sits on.
  pub on: syn::Ident,
  /// The member the method reads, writes or constructs.
  pub member: syn::Ident,
}

/// Which of a record's emitted types a method lands on.
///
/// An IDENTITY rather than a name, and the distinction is load-bearing: a `row(rename = "…")` can
/// give a row the record's own name, at which point grouping by name would merge two types' method
/// sets and report their columns as colliding with each other. That collision is a different rule,
/// with a refusal of its own, and this keeps the two apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Owner {
  /// The `*Key`.
  Key,
  /// The `*Lineage`, for a record that has one.
  Lineage,
  /// The DECLARATION itself — the record a node's expansion sits on, the value an entity's does,
  /// the fragment a field tier's does, or the enum a vocabulary's does. One variant for all of them,
  /// because what it distinguishes is the declared type from the types an expansion mints beside it,
  /// and every emitted type here is one of those.
  Record,
  /// One database's row.
  Row(DatabaseKind),
  /// One database's comparison.
  Comparison(DatabaseKind),
  /// The wire argument object.
  Input,
  /// One type of the FUSE FAMILY — an options package, a question package or the column
  /// vocabulary; the row's `owner_name` says which, and is the namespace the collision walk keys.
  Fuse,
  /// The wire output object.
  Output,
  /// The wire ADDRESS object — `<E>KeyOutput`, whose wire face's methods sit beside its accessors.
  KeyOutput,
  /// The wire QUERY UNIT — `<E>Queries`, whose only methods are the root fields it answers.
  Queries,
  /// The wire filter.
  Filter,
  /// The wire order-by.
  OrderBy,
}

/// One method an emission declares, on one emitted type.
#[derive(Debug, Clone)]
pub struct Emitted {
  /// Which type the method lands on.
  pub owner: Owner,
  /// What that type is CALLED, for the sentence a refusal writes.
  pub owner_name: syn::Ident,
  /// What the method is called.
  pub name: syn::Ident,
  /// What produced the name.
  pub origin: Origin,
}

/// The members ONE column's family declares at one site.
///
/// A struct of options rather than a list, because the emitter needs each name in its own token
/// position and looking one up by tag would need a fallible read of an infallible fact. Adding a
/// member is a change every site that DESTRUCTURES this has to acknowledge, which is the property
/// worth having.
pub(crate) struct Family {
  /// The by-value accessor, for a `copy` column.
  pub(crate) value: Option<syn::Ident>,
  /// The borrow, for every projection but `repeated`.
  pub(crate) borrow: Option<syn::Ident>,
  /// The slice, for a `repeated` column.
  pub(crate) slice: Option<syn::Ident>,
  /// The setter, where the site admits mutation.
  pub(crate) set: Option<syn::Ident>,
  /// The builder, likewise.
  pub(crate) with: Option<syn::Ident>,
}

impl Family {
  /// Every member this family really declares, in emission order.
  pub(crate) fn members(self) -> impl Iterator<Item = (Member, syn::Ident)> {
    [
      (Member::Value, self.value),
      (Member::Borrow, self.borrow),
      (Member::Slice, self.slice),
      (Member::Set, self.set),
      (Member::With, self.with),
    ]
    .into_iter()
    .filter_map(|(member, name)| name.map(|name| (member, name)))
  }
}

impl Column {
  /// The members this column's family declares at a site that does or does not admit mutation.
  ///
  /// The one answer to that question. [`Column::methods`](crate::emit) destructures this value and
  /// writes the idents it finds, so a check over these names is a check over the names really
  /// emitted rather than over a second reading of the same rule.
  pub(crate) fn family(&self, mutable: bool) -> Family {
    let name = &self.name;
    let repeated = matches!(self.project, Projection::Repeated);
    Family {
      value: self.project.copies().then(|| Member::Value.name(name)),
      borrow: (!repeated).then(|| Member::Borrow.name(name)),
      slice: repeated.then(|| Member::Slice.name(name)),
      set: mutable.then(|| Member::Set.name(name)),
      with: mutable.then(|| Member::With.name(name)),
    }
  }

  /// This column's family as the methods it declares on the type called `owner_name`.
  pub(crate) fn emitted(
    &self,
    owner: Owner,
    owner_name: &syn::Ident,
    mutable: bool,
  ) -> Vec<Emitted> {
    self
      .family(mutable)
      .members()
      .map(|(member, name)| Emitted {
        owner,
        owner_name: owner_name.clone(),
        name,
        origin: Origin::Column(ColumnOrigin {
          column: self.name.clone(),
          member,
        }),
      })
      .collect()
  }
}

impl DatabaseKind {
  /// The order-by resolver this database's column names are answered through — `sqlite_column`.
  pub(crate) fn order_resolver(self) -> syn::Ident {
    format_ident!("{}_column", self.as_str())
  }

  /// The ordering LOWERING for this database — `sqlite_order_by`, which walks the terms a query
  /// wrote and ends them with the key.
  ///
  /// Named for the database rather than typed by a dialect, exactly as the resolver above is: what
  /// the name picks is which column NAMES are rendered, and `<db>(rename)` is the whole of
  /// what makes two databases differ about that. The dialect the text is bracketed for stays a
  /// parameter, so this reads the same way an emitted `<Row>Comparison<DB>` does.
  pub(crate) fn order_lowering(self) -> syn::Ident {
    format_ident!("{}_order_by", self.as_str())
  }

  /// The ordering TERM for this database — `sqlite_term`, which is what a page renders its
  /// `ORDER BY` and its keyset from.
  ///
  /// Per database like the resolver, and for its reason: what the name picks is which column names
  /// are rendered, and NULLABILITY rides with them because it is a schema fact per database too.
  pub(crate) fn order_term(self) -> syn::Ident {
    format_ident!("{}_term", self.as_str())
  }

  /// This database's plural entry point — `find_sqlite`.
  pub(crate) fn finder(self) -> syn::Ident {
    format_ident!("find_{}", self.as_str())
  }

  /// This database's plural entry point inside a read transaction — `find_sqlite_snapshot`.
  pub(crate) fn snapshot_finder(self) -> syn::Ident {
    format_ident!("find_{}_snapshot", self.as_str())
  }

  /// This database's single entry point — `get_sqlite`.
  pub(crate) fn getter(self) -> syn::Ident {
    format_ident!("get_{}", self.as_str())
  }

  /// This database's plain WRITE — `insert_sqlite`.
  pub(crate) fn inserter(self) -> syn::Ident {
    format_ident!("insert_{}", self.as_str())
  }

  /// This database's KEYED REPLACE — `upsert_sqlite`.
  pub(crate) fn upserter(self) -> syn::Ident {
    format_ident!("upsert_{}", self.as_str())
  }

  /// This database's REMOVAL at an address — `delete_sqlite`.
  pub(crate) fn deleter(self) -> syn::Ident {
    format_ident!("delete_{}", self.as_str())
  }

  /// This database's REMOVAL over a predicate — `delete_sqlite_where`.
  ///
  /// The suffix rides the deleter's own name for the reason the SET door's `_with` rides the
  /// ranked-keys door's: the two are one verb asked about a predicate instead of an address, and a
  /// reader scanning the impl should see the pair rather than two unrelated spellings. It is the
  /// same shape [`snapshot_finder`](Self::snapshot_finder) already has one verb over.
  pub(crate) fn purger(self) -> syn::Ident {
    format_ident!("{}_where", self.deleter())
  }

  /// The CONDITIONAL-EXPANSION gate this database's CONCRETE impls ride — `if_sqlite`, reached on
  /// `ingraph`'s `__private::gate` shelf.
  ///
  /// The shelf and never the public name the same macro also carries, for the reason every framework
  /// name is reached there: an emission depends on the shelf rather than on where an item lives.
  ///
  /// Mechanical from [`as_str`](Self::as_str), which is the word the declaration writes and the word
  /// the framework's feature carries, so the three cannot drift into naming different backends. What
  /// a gate does — and why an emitted `#[cfg]` asks a different question — is `ingraph`'s crate note,
  /// under *The four gates*.
  pub(crate) fn gate(self) -> syn::Ident {
    format_ident!("if_{}", self.as_str())
  }
}

impl RecordModel {
  /// Every method this model's emission declares, in EMISSION ORDER.
  ///
  /// The order is the emitter's own walk — the key, the lineage, the record, then each database's
  /// row and comparison, then the wire faces — so a front end reporting a collision can name the
  /// earlier of the two as the one already there.
  ///
  /// Types are told apart by [`Owner`] rather than by name, for the reason that enum records.
  pub fn emitted_methods(&self) -> Vec<Emitted> {
    let constructor = |owner: Owner, owner_name: &syn::Ident| Emitted {
      owner,
      owner_name: owner_name.clone(),
      name: format_ident!("new"),
      origin: Origin::Constructor,
    };
    let mut emitted = vec![constructor(Owner::Key, &self.key.name)];
    // An address is being BUILT, so its columns take the mutator pair whether or not they bear
    // identity on the record.
    emitted.extend(
      self
        .key
        .columns()
        .flat_map(|column| column.emitted(Owner::Key, &self.key.name, true)),
    );
    // A lineage that is a CHOICE declares neither: an enum is built by naming a variant, so there
    // is no `new` to collide with and no column to reach an accessor. `Lineage::path` is empty for
    // one, which is what makes this one walk rather than two.
    if let Some(lineage) = self
      .lineage
      .as_ref()
      .filter(|lineage| !lineage.path().is_empty())
    {
      emitted.push(constructor(Owner::Lineage, &lineage.name));
      emitted.extend(
        lineage
          .path()
          .iter()
          .flat_map(|column| column.emitted(Owner::Lineage, &lineage.name, true)),
      );
    }
    // The record carries NO constructor, and its identity-bearing fields carry no mutators. A
    // REWRITE declares a family of its own — one reader per manifest field and no mutator, since
    // nothing here can assign into a foreign type — so the enumeration forks where the emission
    // does, on the same predicate and through the same `Family`.
    emitted.extend(self.fields.iter().flat_map(|field| {
      if self.remote.is_some() {
        return crate::remote::wrapped_family(field)
          .members()
          .map(|(member, name)| Emitted {
            owner: Owner::Record,
            owner_name: self.record.clone(),
            name,
            origin: Origin::Column(ColumnOrigin {
              column: field.column.name.clone(),
              member,
            }),
          })
          .collect::<Vec<_>>();
      }
      field
        .column
        .emitted(Owner::Record, &self.record, !field.identity)
    }));
    for database in self.persist.iter().flat_map(|persist| &persist.backends) {
      let kind = database.kind();
      let row = database.name();
      emitted.extend(
        database
          .columns()
          .iter()
          .flat_map(|column| column.as_column().emitted(Owner::Row(kind), row, false)),
      );
      // The EXTRACTION, after the row's own accessors and before its comparison — the emitter's own
      // walk, where the decode is appended to the row's inherent impl. MongoDB's alone: the SQL
      // family's decode is a `FromRow` impl, which is a trait item and occupies no name in the
      // declaring scope. `extracts` is the one predicate, asked here and at the emission.
      if database.extracts() {
        emitted.push(Emitted {
          owner: Owner::Row(kind),
          owner_name: row.clone(),
          name: format_ident!("from_document"),
          origin: Origin::Extraction,
        });
      }
      let comparison = database.comparison_name();
      emitted.push(constructor(Owner::Comparison(kind), comparison));
      // The comparison's members are LAYER 1 — the record field's name — so this enumeration reads
      // the same ident the emission does. It used to read the per-database column name, which made
      // a `<db>(rename)` move a method the emitter no longer moves.
      emitted.extend(database.compared(self).into_iter().map(|column| {
        let column = column.member().clone();
        Emitted {
          owner: Owner::Comparison(kind),
          owner_name: comparison.clone(),
          name: Member::Borrow.name(&column),
          origin: Origin::Column(ColumnOrigin {
            column,
            member: Member::Borrow,
          }),
        }
      }));
    }
    emitted.extend(self.order_by_methods());
    emitted.extend(self.wire_methods());
    // The typed FACE, last, because it is emitted last: an entry point names the row and the
    // comparison the walk above has already declared. One set per SQL database that can carry a
    // query — [`RecordModel::queryable`] is the one place that decides which, and it decides for the
    // WRITE verbs too: `SqlWrite` is `SqlQuery`'s subtrait, so a row with no query face has no write
    // face either.
    emitted.extend(self.queryable().into_iter().flat_map(|database| {
      let kind = database.kind();
      [
        (kind.finder(), Origin::Finder(kind)),
        (kind.snapshot_finder(), Origin::Snapshot(kind)),
        (kind.getter(), Origin::Getter(kind)),
        (kind.inserter(), Origin::Inserter(kind)),
        (kind.upserter(), Origin::Upserter(kind)),
        (kind.deleter(), Origin::Deleter(kind)),
        (kind.purger(), Origin::Purger(kind)),
      ]
      .map(|(name, origin)| Emitted {
        owner: Owner::Record,
        owner_name: self.record.clone(),
        name,
        origin,
      })
    }));
    emitted
  }

  /// The methods the ORDER-BY declares — none at all for a record stored nowhere.
  ///
  /// Split out of [`wire_methods`](Self::wire_methods) with the type itself: an ordering term is a
  /// fact about the STORED columns, so a record with no wire face declares every one of these and a
  /// record with no `persist(…)` declares none. See `emit::graphql`'s `RecordModel::ordering` for
  /// what each half is gated on.
  fn order_by_methods(&self) -> Vec<Emitted> {
    let mut emitted = Vec::new();
    if self.persist.is_none() {
      return emitted;
    }
    let order_by = self.order_by.safe();
    emitted.extend(
      self
        .persist
        .iter()
        .flat_map(|persist| &persist.backends)
        .map(|database| Emitted {
          owner: Owner::OrderBy,
          owner_name: order_by.clone(),
          name: database.kind().order_resolver(),
          origin: Origin::Resolver(database.kind()),
        }),
    );
    // Unconditional where the resolvers are per database, and last where they are first, because
    // that is the emitter's own walk: a term's column is what storage renames and its direction is
    // not, so the direction is emitted once whether a record declares three databases or none.
    emitted.push(Emitted {
      owner: Owner::OrderBy,
      owner_name: order_by.clone(),
      name: format_ident!("direction"),
      origin: Origin::Direction,
    });
    // The PAGE vocabulary, in the emitter's own walk: the identity, then one term per SQL database,
    // then the id tail. All three ride the same law as the lowering below — a written order can be
    // completed only where the id is stored, and only the SQL family has a clause machine to render
    // it — so a record missing either gets the resolver and the direction and nothing else.
    let paged = self.id_column_stored().is_some()
      && self
        .persist
        .iter()
        .flat_map(|persist| &persist.backends)
        .any(|database| database.kind().is_sql());
    if paged {
      emitted.push(Emitted {
        owner: Owner::OrderBy,
        owner_name: order_by.clone(),
        name: format_ident!("identity"),
        origin: Origin::Identity,
      });
      emitted.extend(
        self
          .persist
          .iter()
          .flat_map(|persist| &persist.backends)
          .filter(|database| database.kind().is_sql())
          .map(|database| Emitted {
            owner: Owner::OrderBy,
            owner_name: order_by.clone(),
            name: database.kind().order_term(),
            origin: Origin::Term(database.kind()),
          }),
      );
      emitted.push(Emitted {
        owner: Owner::OrderBy,
        owner_name: order_by.clone(),
        name: format_ident!("complete"),
        origin: Origin::Complete,
      });
    }
    // The LOWERING, last, because it consumes both halves above. SQL only — the clause machine it
    // walks is the SQL family's — and only where the id is stored, which
    // [`RecordModel::id_column_stored`] is the one place that decides.
    if self.id_column_stored().is_some() {
      emitted.extend(
        self
          .persist
          .iter()
          .flat_map(|persist| &persist.backends)
          .filter(|database| database.kind().is_sql())
          .map(|database| Emitted {
            owner: Owner::OrderBy,
            owner_name: order_by.clone(),
            name: database.kind().order_lowering(),
            origin: Origin::Lowering(database.kind()),
          }),
      );
    }
    emitted
  }

  /// The methods the WIRE faces declare — none at all for a record with no `graphql(…)`.
  ///
  /// The filter's names are the field's INPUT face where one is exposed and the column's own
  /// otherwise, because that is what the emitter writes. A check that read the record's Rust names
  /// instead would miss every collision an input rename opens and invent ones it closes.
  ///
  /// The OUTPUT object's are [`GraphqlField::accessor`](crate::model::GraphqlField::accessor) —
  /// LAYER 2, the one layer a wire word moves — for the same reason stated the other way round: a
  /// schema rename moves no accessor, and the emitted MEMBER is layer 1 and moves for nothing, so a
  /// check on either would be about a method the emission does not declare.
  fn wire_methods(&self) -> Vec<Emitted> {
    let mut emitted = Vec::new();
    let Some(graphql) = &self.graphql else {
      return emitted;
    };
    let Some(backend) = graphql.backends.first() else {
      return emitted;
    };
    let output = graphql.output.safe();
    // The object's own address members lead, because the emission writes them first — and they carry
    // an origin of their own, so a field landing on either name is a COLLISION reported at the
    // declaration rather than a duplicate `id_ref` inside the expansion. The `id` member is the
    // framework's only where the declaration writes none: see `RecordModel::wire_writes_id`.
    let address: &[&str] = if self.wire_writes_id() {
      &["id", "key"]
    } else {
      &["key"]
    };
    emitted.extend(address.iter().map(|member| Emitted {
      owner: Owner::Output,
      owner_name: output.clone(),
      name: Member::Borrow.name(&format_ident!("{member}")),
      origin: Origin::Address,
    }));
    emitted.extend(backend.fields().iter().map(|field| {
      let column = field.accessor().clone();
      Emitted {
        owner: Owner::Output,
        owner_name: output.clone(),
        name: Member::Borrow.name(&column),
        origin: Origin::Column(ColumnOrigin {
          column,
          member: Member::Borrow,
        }),
      }
    }));
    // The ARGUMENT object, between the output and the filter because that is where its impl sits.
    // Its ORDER pair leads, and rides the same predicate the type's `order` field does: a record
    // with no term type has no order to write and no page to ask for.
    let input = graphql.input.safe();
    let argument = |name: &syn::Ident, member: Member| Emitted {
      owner: Owner::Input,
      owner_name: input.clone(),
      name: member.name(name),
      origin: Origin::Argument,
    };
    let paged: &[&str] = if self.orderable() {
      let order = format_ident!("order");
      emitted.extend([
        argument(&order, Member::With),
        argument(&order, Member::Slice),
      ]);
      &["first", "last", "after", "before", "skip"]
    } else {
      &[]
    };
    for name in ["filter", "limit"].iter().chain(paged) {
      let name = format_ident!("{name}");
      emitted.extend([
        argument(&name, Member::With),
        argument(&name, Member::Borrow),
      ]);
    }
    let filter = graphql.filter.safe();
    for column in self.stored_columns() {
      let (rust, _, _) = backend.filter_field(column);
      emitted.extend([Member::With, Member::Borrow].map(|member| Emitted {
        owner: Owner::Filter,
        owner_name: filter.clone(),
        name: member.name(&rust),
        origin: Origin::Column(ColumnOrigin {
          column: rust.clone(),
          member,
        }),
      }));
    }
    // The ADDRESS object's ACCESSORS — layer 2, the Rust read road, under the members' own domain
    // names, and the one family this face never had: a caller outside the declaring crate could not
    // read a key's members in Rust at all, the substrate being `pub(crate)` and the wire methods
    // being the wire's.
    //
    // HERE rather than beside the wire methods below, because that is the emitter's own walk: an
    // accessor is an ordinary inherent impl and lands with the faces, where the `#[Object]` blocks
    // ride the binding gate after them. No rename word reaches a key column, so a name here is the
    // column's own and the family is the column's own — a `copy` one gets its value accessor beside
    // the borrow.
    let key_output = graphql.key_output.safe();
    emitted.extend(
      self
        .key
        .columns()
        .flat_map(|column| column.emitted(Owner::KeyOutput, key_output, false)),
    );
    // **LAYER 1 ON THE WIRE, UNDER THE PREFIX**, last because the two `#[Object]` blocks are emitted
    // last — and the whole reason this enumeration has to carry them is the collision rule: the
    // output object's wire methods are named after the MEMBERS, so a declaration exposing a field
    // called `key` beside the framework's address member is a duplicate method inside an expansion
    // its author cannot edit, and this list is what lets the front end name the pair at the
    // declaration instead.
    //
    // [`wire_method`] is what the emitter spells them through, so it is what this reads them back
    // as: the prefix is INJECTIVE, so which declarations collide does not move — but a refusal has
    // to name the method rustc would have reported, and after the pin that method is
    // `__async_graphql_key`.
    //
    // They cannot collide with the ACCESSORS above, and that is the three-layer law holding rather
    // than luck: layer 2 wears the borrow suffix and no prefix, so `__async_graphql_checksum`
    // sits beside `checksum_ref` whatever either was renamed to.
    emitted.extend(address.iter().map(|member| Emitted {
      owner: Owner::Output,
      owner_name: output.clone(),
      name: wire_method(&format_ident!("{member}")),
      origin: Origin::Address,
    }));
    emitted.extend(backend.fields().iter().map(|field| {
      // The SOURCE and not the accessor: a wire method is layer 1, which no word moves.
      let column = field.source.clone();
      Emitted {
        owner: Owner::Output,
        owner_name: output.clone(),
        name: wire_method(&column),
        origin: Origin::Column(ColumnOrigin {
          column,
          member: Member::Value,
        }),
      }
    }));
    // The ADDRESS object's own wire methods, which cannot collide with the accessors above: those
    // are layer 2 under the borrow suffix and wear no prefix, so `__async_graphql_media_id` sits
    // beside `media_id_ref`.
    emitted.extend(self.key.columns().map(|column| Emitted {
      owner: Owner::KeyOutput,
      owner_name: key_output.clone(),
      name: wire_method(&column.name),
      origin: Origin::Column(ColumnOrigin {
        column: column.name.clone(),
        member: Member::Value,
      }),
    }));
    // The QUERY UNIT's root fields, last because the unit is emitted last — and only where one is
    // emitted at all, `RecordModel::wire_query_row` being the one place that decides. Its two names
    // are built from the RECORD's own rather than from any column, so nothing a declaration writes
    // can land on either; they are enumerated for the reason every other emitted name is, which is
    // that this list is a statement about the emission rather than about the collisions it happens
    // to be able to have.
    emitted.extend(self.root_field_methods());
    emitted
  }

  /// The two methods a query unit declares — the single always, the list where the record has an
  /// order to page by.
  ///
  /// The predicates are `emit::queries`' own, read here rather than restated: a name this enumerates
  /// and the emission does not write fails
  /// `tests::the_enumeration_names_exactly_the_methods_the_emission_declares`, which is what keeps
  /// the two in step.
  fn root_field_methods(&self) -> Vec<Emitted> {
    use heck::ToSnakeCase as _;

    if self.wire_query_row().is_none() {
      return Vec::new();
    }
    let owner_name = crate::model::default_queries_name(&self.record);
    let snake = self.record.to_string().to_snake_case();
    let mut emitted = vec![Emitted {
      owner: Owner::Queries,
      owner_name: owner_name.clone(),
      name: wire_method(&format_ident!("{snake}")),
      origin: Origin::RootField,
    }];
    if self.orderable() && !self.ordered_columns().is_empty() {
      emitted.push(Emitted {
        owner: Owner::Queries,
        owner_name,
        name: wire_method(&format_ident!("{snake}_list")),
        origin: Origin::RootField,
      });
    }
    emitted
  }
}