ingraph_codegen/newtype.rs
1//! The NEWTYPE DEVICE's model: what `#[derive(ingraph::NewType)]` emits for a single-field struct
2//! this crate declares — one citizenship row per KIT the declaration opted into, every one of them a
3//! pass-through to the type inside.
4//!
5//! # What it is, beside the three devices that already existed
6//!
7//! | device | the type it equips | what it knows about that type |
8//! |---|---|---|
9//! | `#[derive(ingraph::Enum)] #[ingraph(remote = "…")]` | a vocabulary SOMEBODY ELSE declared | its variants, restated |
10//! | `#[ingraph::entity(remote = "…")]` / `record(remote)` | a struct SOMEBODY ELSE declared | its fields, restated |
11//! | `#[derive(ingraph::Filter)] #[ingraph(operator(<family>))]` | a value THIS crate declares | that it is one operand — and it MINTS the filter |
12//! | **this** | a value THIS crate declares | that it WRAPS one, and which faces it wants |
13//!
14//! The line between the last two is the CONSTRUCTION CONTRACT. The element mode mints a filter type
15//! and gives the element the citizenship that filter needs, whole and unchosen; this device chooses,
16//! and every face it writes is the INNER type's answer wearing the outer type's name. So a newtype
17//! that wants a filter and nothing else takes two words, and one that wants to be a column in two
18//! dialects and never crosses a wire takes two others.
19//!
20//! # THE EMISSION LAW: every pass-through is FULLY QUALIFIED
21//!
22//! `<Inner as Trait>::method(&self.0, …)`, never `self.0.method(…)`, and the associated types and
23//! consts alike. Four things follow from it, and the fourth is the one that decides it:
24//!
25//! - **method resolution is pinned.** A bare `self.0.push_bind(qb)` resolves by autoref and by
26//! inherent-before-trait, so an inner type growing an INHERENT method of that name silently takes
27//! the call away from the trait the row is implementing.
28//! - **the obligation's landing point IS the diagnostic's.** The row carries `Inner: Trait` in its
29//! `where` clause, so a missing kit on the inner type is `E0277` naming that type and that trait,
30//! at the declaration — rather than a method-not-found inside an expansion.
31//! - **it is the house's own absolute-path doctrine**, one grain in: an emission spells every
32//! framework name from a root, and a delegation spells every callee from its trait.
33//! - **one spelling serves every receiver and every carrier.** `&self`, `self`, no receiver at all,
34//! an associated const, a GAT — the qualified form is the same shape for all of them, and it is
35//! the only shape that is also correct where the inner type is a GENERIC PARAMETER. `self.0.cmp(…)`
36//! on a `Confidence<S>` cannot say which `S`'s row it meant; `<S as Trait>::cmp(&self.0, …)` can.
37//!
38//! # The GATE is one source, and every READ path is spent on it
39//!
40//! A newtype that carries an invariant has exactly one door — `scalar(parse = "…")` for a value read
41//! WIDE out of text, `scalar(check = "…")` for one anchored in a range — and the device spends that
42//! door on every path a value ARRIVES on: the scalar's `parse`, its `is_valid`, the cursor's
43//! `read_cursor`, and the dialect decode. What has no gate to spend passes straight through.
44//!
45//! The asymmetry is the point. A WRITE is a value the type already holds, so nothing can be wrong
46//! with it and the inner's own row is the whole answer. A READ is bytes somebody else wrote — a
47//! client's cursor, a column another writer filled, a JSON operand — and a newtype whose type says
48//! `[0.0, 1.0]` must not be handed a `1.5` because it came back from a column.
49
50use quote::{format_ident, quote};
51use syn::ext::IdentExt as _;
52
53use crate::{element::ElementFamily, model::DatabaseKind};
54
55#[cfg(test)]
56mod tests;
57
58/// The DOOR a declaration put in front of its own values — `scalar(parse = "…")` or
59/// `scalar(check = "…")`, and never both.
60///
61/// Both name a free function returning `Result<Self, E>` with `E: Display`. What differs is the
62/// SHAPE the function is handed, and the difference is the whole reason there are two words: a text
63/// door reads spellings and folds them, a check door takes the carrier's own value and says whether
64/// it is in range.
65#[derive(Clone)]
66pub enum Gate {
67 /// `parse = "…"` — `fn(&str) -> Result<Self, E>`. Text in, WIDE: the function owns the grammar,
68 /// the folds and the refusal.
69 Parse(syn::Path),
70 /// `check = "…"` — `fn(Inner) -> Result<Self, E>`. The carrier's own value, ANCHORED: an
71 /// interval, a normalisation, a domain the width admits and the type does not.
72 Check(syn::Path),
73}
74
75/// The `scalar` kit, as a declaration wrote it.
76#[derive(Clone, Default)]
77pub struct ScalarKit {
78 /// `rename = "…"` — the name a SCHEMA writes, where the Rust one is not it.
79 pub rename: Option<String>,
80 /// The door, where the declaration put one in front of its values.
81 pub gate: Option<Gate>,
82}
83
84/// Every kit a declaration opted into.
85///
86/// PLAIN, for [`ElementModel`](crate::element::ElementModel)'s reason — public fields, no
87/// constructor, no validation. What is checked is checked at the FRONT END, where the tokens an
88/// author wrote are still in hand and a refusal can point at one.
89#[derive(Default)]
90pub struct Kits {
91 /// `graphql(async_graphql(scalar(…)))` — the type's own GraphQL scalar.
92 pub scalar: Option<ScalarKit>,
93 /// `graphql(async_graphql(input))` — [`ToGraphqlInput`].
94 pub input: bool,
95 /// `graphql(async_graphql(output))` — [`ToGraphqlOutput`].
96 pub output: bool,
97 /// `marker(<family>)` — the interpretation a FIELD of this type is read under.
98 pub marker: Option<ElementFamily>,
99 /// `filter` — the family's filter, reached through a reading this device mints.
100 pub filter: bool,
101 /// `cursor` — [`CursorValue`], a keyset position.
102 pub cursor: bool,
103 /// `sqlite` / `postgres` / `mysql` — the dialects this type is a column in.
104 pub databases: Vec<DatabaseKind>,
105}
106
107impl Kits {
108 /// Whether the declaration asked for ANYTHING.
109 #[must_use]
110 pub fn is_empty(&self) -> bool {
111 self.scalar.is_none()
112 && !self.input
113 && !self.output
114 && self.marker.is_none()
115 && !self.filter
116 && !self.cursor
117 && self.databases.is_empty()
118 }
119
120 /// The door, where one was declared — `scalar`'s, since that is the only block it lives in.
121 #[must_use]
122 pub fn gate(&self) -> Option<&Gate> {
123 self.scalar.as_ref().and_then(|scalar| scalar.gate.as_ref())
124 }
125}
126
127/// A declared NEWTYPE, as the device reads it.
128pub struct NewTypeModel {
129 /// The declaration's own visibility, which a minted reading takes.
130 pub vis: syn::Visibility,
131 /// The newtype the faces are OF.
132 pub subject: syn::Ident,
133 /// Its parameters, carried onto every emitted row.
134 pub generics: syn::Generics,
135 /// The `ingraph` root the expansion spells its shelf through.
136 pub krate: syn::Path,
137 /// The single field the value is held in — positional or named.
138 pub member: syn::Member,
139 /// That field's type, which every pass-through delegates to.
140 pub inner: syn::Type,
141 /// The kits the declaration opted into.
142 pub kits: Kits,
143}
144
145impl NewTypeModel {
146 /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
147 /// them.
148 fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
149 crate::emit::framework(&self.krate, module, name)
150 }
151
152 /// A whole VENDORED crate on that shelf, as the string an attribute's `crate = …` takes.
153 fn vendored(&self, name: &str) -> String {
154 crate::emit::vendored(&self.krate, name)
155 }
156
157 /// This newtype's name as a SCHEMA writes it.
158 ///
159 /// The Rust name unraw'd, unless `rename = "…"` moved it. The knob exists where
160 /// `#[derive(ingraph::Enum)]` has none, and the difference is which name is DERIVED: a vocabulary
161 /// publishes the name of a type somebody else declared, so a rename there would be this crate
162 /// renaming a foreign schema entity. A newtype is THIS crate's, and the wire name it publishes is
163 /// its own commitment to make.
164 fn sdl(&self) -> String {
165 self
166 .kits
167 .scalar
168 .as_ref()
169 .and_then(|scalar| scalar.rename.clone())
170 .unwrap_or_else(|| self.subject.unraw().to_string())
171 }
172
173 /// The reading this device mints for the filter kit — `<Name>Wire`.
174 #[must_use]
175 pub fn reading_name(&self) -> syn::Ident {
176 format_ident!("{}Wire", self.subject)
177 }
178
179 /// What the minted filter is PUBLISHED as — the operand's schema name, then `Filter`.
180 ///
181 /// The framework's own naming law, applied where the framework cannot see the type: every filter
182 /// this crate publishes is `<the operand's schema name>Filter`, and a reading that spelled its own
183 /// would be free to disagree with the name the operand already publishes.
184 fn filter_sdl(&self) -> String {
185 format!("{}Filter", self.sdl())
186 }
187
188 /// The subject as a TYPE — its name with its own parameters, which is what every row is written
189 /// `for`.
190 fn subject_type(&self) -> proc_macro2::TokenStream {
191 let subject = &self.subject;
192 let (_, ty_generics, _) = self.generics.split_for_impl();
193 quote!(#subject #ty_generics)
194 }
195
196 /// `Self`, built from one inner value — the shape the field's spelling decides.
197 fn build(&self, value: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
198 match &self.member {
199 syn::Member::Named(ident) => quote!(Self { #ident: #value }),
200 syn::Member::Unnamed(_) => quote!(Self(#value)),
201 }
202 }
203
204 /// This declaration's generics with `extra` in FRONT and `predicates` added.
205 ///
206 /// In front because Rust orders a parameter list lifetimes-then-types and every extra a row here
207 /// introduces is one or the other in that order; added rather than replaced because a
208 /// declaration's own bounds are its own — a `Confidence<S: ConfidenceCarrier>` stays one in every
209 /// row this device writes.
210 fn generics_with(
211 &self,
212 extra: &[syn::GenericParam],
213 predicates: &[syn::WherePredicate],
214 ) -> syn::Generics {
215 let mut generics = self.generics.clone();
216 for (at, param) in extra.iter().enumerate() {
217 generics.params.insert(at, param.clone());
218 }
219 if !predicates.is_empty() {
220 let clause = generics.make_where_clause();
221 for predicate in predicates {
222 clause.predicates.push(predicate.clone());
223 }
224 }
225 generics
226 }
227
228 /// The predicate `Inner: <trait>` — the OBLIGATION every pass-through carries, and the reason a
229 /// missing kit on the inner type is `E0277` naming that type rather than a resolution failure
230 /// inside an expansion.
231 fn owes(&self, bound: &proc_macro2::TokenStream) -> syn::WherePredicate {
232 let inner = &self.inner;
233 syn::parse_quote!(#inner: #bound)
234 }
235
236 /// What a TEXT door demands of the WRAPPED type on a read path, and nothing where there is no
237 /// text door.
238 ///
239 /// A door declared `parse = "…"` reads SPELLINGS, and what a cursor or a column hands back is the
240 /// inner type — so the read is routed through that type's own rendering, which is the same text
241 /// `to_value` writes out. One predicate rather than a bare call, for [`owes`](Self::owes)' reason.
242 fn rendering(&self) -> Option<syn::WherePredicate> {
243 match self.kits.gate() {
244 Some(Gate::Parse(_)) => Some(self.owes("e!(::core::fmt::Display))),
245 Some(Gate::Check(_)) | None => None,
246 }
247 }
248
249 /// The whole device, emitted.
250 ///
251 /// TWO scopes, and the split is the one every emitter here draws: a name the declaring scope has
252 /// to be able to WRITE goes outside — the minted reading is named by an associated type a
253 /// downstream crate resolves — and everything else goes inside an anonymous `const`, which is
254 /// where an emission puts what it owes the declaring scope no name for.
255 #[must_use]
256 pub fn emit(&self) -> proc_macro2::TokenStream {
257 let reading = self.reading();
258 let markers = self.markers();
259 let crossings = self.crossings();
260 let cursor = self.cursor();
261 let column = self.column();
262 let stored = self.stored();
263 let read = self.read();
264 let key = self.key_delegation();
265 let id_column = self.id_column_delegation();
266 let storage = self
267 .kits
268 .databases
269 .iter()
270 .map(|database| self.storage(*database));
271 let scalar = self.scalar();
272 quote! {
273 #reading
274
275 const _: () = {
276 #markers
277 #crossings
278 #cursor
279 #column
280 #stored
281 #read
282 #key
283 #id_column
284 #(#storage)*
285 };
286
287 #scalar
288 }
289 }
290
291 /// KEY ADMISSION — the one row this device writes that NO kit word asks for.
292 ///
293 /// Every other row here is opted into: a declaration names `cursor` and gets a keyset position,
294 /// names `sqlite` and gets a column. This one is unconditional, and the asymmetry is deliberate.
295 /// The others are FACES a newtype may or may not want; this is a FACT about what a newtype IS —
296 /// it wraps one value and adds nothing — and a fact does not need asking for. It is also the row
297 /// with no hand-written alternative from outside the framework: the id vocabulary is sealed, and a
298 /// declaring crate reaches it through this trait or not at all.
299 ///
300 /// # Unconditional and yet harmless, because ADMISSION is a consequence rather than this row
301 ///
302 /// `DelegatesId::Inner` carries no bound: the row says *this type is its inner value* and nothing
303 /// more, and [`Id`] is granted only where that inner is itself a member. So a
304 /// `#[derive(ingraph::NewType)] struct Ratio<S>(S)` over a float states the true thing about
305 /// itself, is not an id, and compiles — where a row that demanded membership here would refuse the
306 /// declaration outright, and a row spelled `where Inner: Id` would refuse a CONCRETE non-member
307 /// inner as an unsatisfied trivial bound. Unconditional is the only shape that is additive.
308 ///
309 /// The `where` clause is the declaration's own, unchanged, for the reason every row here carries
310 /// it: a `Confidence<S: ConfidenceCarrier>` stays one in this row too.
311 fn key_delegation(&self) -> proc_macro2::TokenStream {
312 let subject = self.subject_type();
313 let inner = &self.inner;
314 let member = &self.member;
315 let delegates = self.framework(&["id"], "DelegatesId");
316 let (impl_generics, _, where_clause) = self.generics.split_for_impl();
317 quote! {
318 // SAFETY: a newtype holds EXACTLY ONE value — the device refuses a declaration with any other
319 // count — and this row hands that value back by reference and does nothing else. There is no
320 // second field, no tag and no width of the outer type's own, so two values are equal exactly
321 // when their inners are, and every id duty reading the wrapper reads the inner.
322 #[automatically_derived]
323 unsafe impl #impl_generics #delegates for #subject #where_clause {
324 type Inner = #inner;
325
326 #[inline]
327 fn delegate(&self) -> &#inner {
328 &self.#member
329 }
330 }
331 }
332 }
333
334 /// **THE STORAGE SEAM, READ ONE LAYER OUT** — `ingraph::IdColumn<Db>`, delegating to the value
335 /// this newtype wraps.
336 ///
337 /// The second row this device writes that NO kit word asks for, beside
338 /// [`key_delegation`](Self::key_delegation) — and the SAME reasoning admits it: `IdColumn` is a
339 /// FACT about what a newtype IS transparent to (its stored form, exactly as `DelegatesId` states
340 /// its identity), not a face an author chooses, so it costs nothing to emit unconditionally. A
341 /// `#[derive(ingraph::NewType)] struct Ratio<S>(S)` over a type with no `IdColumn` row of its own
342 /// simply is not one — `E0277` naming that type at whatever declaration tries to wrap `Ratio` in
343 /// an id — exactly the shape `key_delegation`'s own note walks through for `DelegatesId` and
344 /// `Id`.
345 ///
346 /// # Mirrors `#[derive(ingraph::Id)]`'s OWN row for an id over an id
347 ///
348 /// That device's `storage` emission already reads the seam one layer out — its own module note
349 /// calls the row "the seam read one layer out: an id over an id stores, resolving to whichever
350 /// member the chain grounds in" — so that a `#[derive(ingraph::Id)]` wrapper over ANOTHER
351 /// `#[derive(ingraph::Id)]` wrapper needs no row of its own. A wrapper over a
352 /// `#[derive(ingraph::NewType)]` value used to be the one gap that note named directly: "That
353 /// device is deliberately not touched here". This row is that gap closed, mirrored rather than
354 /// reinvented — same shape, same `#inner: IdColumn<Db>` obligation, same bare delegation through
355 /// `to_stored`/`from_stored`.
356 ///
357 /// # Stored form follows the inner, unconditionally
358 ///
359 /// `type Stored = <Inner as IdColumn<Db>>::Stored` — a newtype over a `u64` rides the big-endian
360 /// blob road the 2026-08-30 ruling put `u64` on, with no word at the newtype's own declaration; a
361 /// newtype over a member still on the text road keeps riding it. The newtype contributes no
362 /// encoding of its own, exactly as it contributes none to `DelegatesId`.
363 ///
364 /// # Why the check/parse GATE plays NO part here, when every other read path spends it
365 ///
366 /// [`cursor`](Self::cursor)'s `read_cursor` and [`storage`](Self::storage)'s dialect `Decode` both
367 /// route a freshly-read inner through [`gated_read`](Self::gated_read), because those two paths
368 /// are handed bytes a CLIENT or a hand-edited row could have written, and the module note's own
369 /// law is that the gate is spent on every path a value ARRIVES on. This row does not, and the
370 /// reason is `IdColumn`'s OWN contract read closely rather than an oversight: its trait note
371 /// states the obligation as "the round trip and nothing else… `from_stored` has to recover every
372 /// value `to_stored` produced… **nothing else is asked**." A newtype's domain check is additional
373 /// to that contract, not part of it — the same posture `key_delegation` already takes, which
374 /// constructs no value and asserts no check either.
375 fn id_column_delegation(&self) -> proc_macro2::TokenStream {
376 let subject = self.subject_type();
377 let inner = &self.inner;
378 let member = &self.member;
379 let id_column = self.framework(&["id"], "IdColumn");
380 let db = crate::emit::parameter("DB");
381 let seam = quote!(#id_column<#db>);
382 let stored = quote!(<#inner as #seam>::Stored);
383 let built = self.build("e!(__ingraph_inner));
384 let generics = self.generics_with(&[syn::parse_quote!(#db)], &[self.owes(&seam)]);
385 let (impl_generics, _, where_clause) = generics.split_for_impl();
386 quote! {
387 #[automatically_derived]
388 impl #impl_generics #seam for #subject #where_clause {
389 type Stored = #stored;
390 type Refusal = <#inner as #seam>::Refusal;
391
392 #[inline]
393 fn to_stored(&self) -> Self::Stored {
394 <#inner as #seam>::to_stored(&self.#member)
395 }
396
397 #[inline]
398 fn from_stored(
399 __ingraph_stored: Self::Stored,
400 ) -> ::core::result::Result<Self, Self::Refusal> {
401 ::core::result::Result::map(
402 <#inner as #seam>::from_stored(__ingraph_stored),
403 |__ingraph_inner| #built,
404 )
405 }
406 }
407 }
408 }
409
410 // ---------------------------------------------------------------------------------------------
411 // The filter/marker domain
412 // ---------------------------------------------------------------------------------------------
413
414 /// The READING the filter kit is reached through — `<Name>Wire`, and the row that says what one
415 /// operand of this newtype crosses on.
416 ///
417 /// # Why a reading and not a MINT
418 ///
419 /// The element mode mints `<Name>Filter`, because it had to: `impl async_graphql::InputType for
420 /// TextFilter<Tag>` is `E0117` in a declaring crate. The framework's carrier axis opened the other
421 /// road — one generic wire face over the MARKER — so a declaring crate reaches
422 /// `ScalarFilter<Name, NameWire>` whole by writing the reading below, and this device takes that
423 /// road: one uninhabited enum and one impl where a mint writes a type, an inherent face, an
424 /// emptiness contract, a lowering map, an operand map and an input object.
425 ///
426 /// # The ENUM family has no reading, and the absence is the framework's shape
427 ///
428 /// `EnumFilter<T>` carries no carrier parameter — a closed vocabulary's operands cross as
429 /// themselves — so `marker(enum)` names the filter directly and mints nothing.
430 fn reading(&self) -> proc_macro2::TokenStream {
431 let (Some(family), true) = (self.kits.marker, self.kits.filter) else {
432 return quote!();
433 };
434 let Some(wire) = family_reading(family) else {
435 return quote!();
436 };
437 let vis = &self.vis;
438 let name = self.reading_name();
439 let subject = self.subject_type();
440 let subject_name = &self.subject;
441 let reading = self.framework(&["graphql"], wire);
442 let published = self.filter_sdl();
443 let (impl_generics, _, where_clause) = self.generics.split_for_impl();
444 let carrier = self.carrier_form();
445 let (cross, carry) = self.crossing_bodies();
446 let doc = format!(
447 " What a filter over [`{subject_name}`] is PUBLISHED as, and what one of its operands crosses \
448 on.\n\n Uninhabited: a reading is a place to hang a row, never a value. It is this crate's \
449 own type, which is what puts `{published}` inside the orphan rule rather than outside it."
450 );
451 quote! {
452 #[doc = #doc]
453 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
454 #vis enum #name {}
455
456 #[automatically_derived]
457 impl #impl_generics #reading<#subject> for #name #where_clause {
458 const NAME: &'static ::core::primitive::str = #published;
459
460 type Carrier = #carrier;
461 type Error = ::core::convert::Infallible;
462
463 #[inline]
464 fn cross(
465 __ingraph_carrier: Self::Carrier,
466 ) -> ::core::result::Result<#subject, ::core::convert::Infallible> {
467 #cross
468 }
469
470 #[inline]
471 fn carry(__ingraph_operand: &#subject) -> Self::Carrier {
472 #carry
473 }
474 }
475 }
476 }
477
478 /// The three INTERPRETATION rows a field of this newtype resolves through.
479 ///
480 /// What `to_filter!` writes for a type the framework itself registers, written here for one it
481 /// cannot see: the family the value is read under, the filter that family carries, and what a
482 /// `Vec` of it means. The `Vec` reading is the LIST, which is the framework's own default for
483 /// every element that does not say otherwise — and a field's own word still beats it.
484 fn markers(&self) -> proc_macro2::TokenStream {
485 let Some(family) = self.kits.marker else {
486 return quote!();
487 };
488 let subject = self.subject_type();
489 let marker = self.framework(&["marker"], family_marker(family));
490 let default_marker = self.framework(&["marker"], "DefaultMarker");
491 let default_vec_marker = self.framework(&["marker"], "DefaultVecMarker");
492 let list_marker = self.framework(&["marker"], "ListMarker");
493 let (impl_generics, _, where_clause) = self.generics.split_for_impl();
494 let filter = self.filter_row(family);
495 quote! {
496 #[automatically_derived]
497 impl #impl_generics #default_marker for #subject #where_clause {
498 type Marker = #marker<#subject>;
499 }
500
501 #[automatically_derived]
502 impl #impl_generics #default_vec_marker for #subject #where_clause {
503 type Marker = #list_marker<::std::vec::Vec<#subject>, #marker<#subject>>;
504 }
505
506 #filter
507 }
508 }
509
510 /// The FILTER row: which of the framework's kinds guards a column of this newtype.
511 fn filter_row(&self, family: ElementFamily) -> proc_macro2::TokenStream {
512 if !self.kits.filter {
513 return quote!();
514 }
515 let subject = self.subject_type();
516 let reading = self.framework(&["marker"], family_filter_marker(family));
517 let kind = self.framework(&["graphql"], family_filter(family));
518 let (impl_generics, _, where_clause) = self.generics.split_for_impl();
519 let held = match family_reading(family) {
520 Some(_) => {
521 let wire = self.reading_name();
522 quote!(#kind<#subject, #wire>)
523 }
524 None => quote!(#kind<#subject>),
525 };
526 quote! {
527 #[automatically_derived]
528 impl #impl_generics #reading for #subject #where_clause {
529 type Filter = #held;
530 }
531 }
532 }
533
534 // ---------------------------------------------------------------------------------------------
535 // The wire domain
536 // ---------------------------------------------------------------------------------------------
537
538 /// The form ONE operand of this newtype crosses on — the fork the whole wire domain turns on.
539 ///
540 /// A declaration that publishes a SCALAR of its own crosses as ITSELF: the door below is the form,
541 /// and a second one beside it would be a grammar the schema does not name. One that publishes no
542 /// scalar crosses as whatever its inner type crosses as — the newtype is transparent on the wire,
543 /// which is what a pure operand wrapper is FOR.
544 fn carrier_form(&self) -> proc_macro2::TokenStream {
545 if self.kits.scalar.is_some() {
546 return self.subject_type();
547 }
548 let inner = &self.inner;
549 let crossing = self.framework(&["graphql"], "ToGraphqlInput");
550 quote!(<#inner as #crossing>::Input)
551 }
552
553 /// The two bodies of a crossing at [`carrier_form`](Self::carrier_form) — identity where the type
554 /// is its own form, delegation where it is not.
555 fn crossing_bodies(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
556 if self.kits.scalar.is_some() {
557 return (
558 quote!(::core::result::Result::Ok(__ingraph_carrier)),
559 quote!(::core::clone::Clone::clone(__ingraph_operand)),
560 );
561 }
562 let inner = &self.inner;
563 let member = &self.member;
564 let crossing = self.framework(&["graphql"], "ToGraphqlInput");
565 let built = self.build("e!(__ingraph_inner));
566 (
567 quote! {
568 match <#inner as #crossing>::cross(__ingraph_carrier) {
569 ::core::result::Result::Ok(__ingraph_inner) => ::core::result::Result::Ok(#built),
570 // The inner crossing's refusal, propagated rather than re-worded: a form this type never
571 // saw was refused by the type that owns the form, and a second sentence here would
572 // describe a grammar this device does not have.
573 ::core::result::Result::Err(__ingraph_refused) => {
574 ::core::result::Result::Err(__ingraph_refused)
575 }
576 }
577 },
578 quote!(<#inner as #crossing>::carry(&__ingraph_operand.#member)),
579 )
580 }
581
582 /// The two CROSSINGS — what an operand of this newtype looks like on the way in, and what a wire
583 /// face returns it as on the way out.
584 ///
585 /// UNGATED, both of them, because the traits are: a crossing says which FORM an operand takes and
586 /// asks nothing about who parses that form. The face that spends it rides the binding gate; this
587 /// pair is a fact about the type.
588 fn crossings(&self) -> proc_macro2::TokenStream {
589 let input = self.input_crossing();
590 let output = self.output_crossing();
591 quote! {
592 #input
593 #output
594 }
595 }
596
597 /// [`ToGraphqlInput`] — the identity where a scalar was declared, the inner's own form where none
598 /// was.
599 fn input_crossing(&self) -> proc_macro2::TokenStream {
600 if !self.kits.input {
601 return quote!();
602 }
603 let subject = self.subject_type();
604 let inner = &self.inner;
605 let crossing = self.framework(&["graphql"], "ToGraphqlInput");
606 let carrier = self.carrier_form();
607 let (cross, carry) = self.crossing_bodies();
608 let (error, predicates): (proc_macro2::TokenStream, Vec<syn::WherePredicate>) =
609 if self.kits.scalar.is_some() {
610 (quote!(::core::convert::Infallible), Vec::new())
611 } else {
612 (
613 quote!(<#inner as #crossing>::Error),
614 vec![self.owes(&crossing)],
615 )
616 };
617 let generics = self.generics_with(&[], &predicates);
618 let (impl_generics, _, where_clause) = generics.split_for_impl();
619 quote! {
620 #[automatically_derived]
621 impl #impl_generics #crossing for #subject #where_clause {
622 type Input = #carrier;
623 type Error = #error;
624
625 #[inline]
626 fn cross(
627 __ingraph_carrier: Self::Input,
628 ) -> ::core::result::Result<Self, Self::Error> {
629 #cross
630 }
631
632 #[inline]
633 fn carry(__ingraph_operand: &Self) -> Self::Input {
634 #carry
635 }
636 }
637 }
638 }
639
640 /// [`ToGraphqlOutput`] — by REFERENCE where a scalar was declared, and the inner's own output form
641 /// where none was.
642 fn output_crossing(&self) -> proc_macro2::TokenStream {
643 if !self.kits.output {
644 return quote!();
645 }
646 let subject = self.subject_type();
647 let inner = &self.inner;
648 let member = &self.member;
649 let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
650 if self.kits.scalar.is_some() {
651 let (impl_generics, _, where_clause) = self.generics.split_for_impl();
652 return quote! {
653 #[automatically_derived]
654 impl #impl_generics #crossing for #subject #where_clause {
655 type Output<'__ingraph>
656 = &'__ingraph Self
657 where
658 Self: '__ingraph;
659
660 #[inline]
661 fn to_graphql_output(__ingraph_value: &Self) -> &Self {
662 __ingraph_value
663 }
664 }
665 };
666 }
667 let generics = self.generics_with(&[], &[self.owes(&crossing)]);
668 let (impl_generics, _, where_clause) = generics.split_for_impl();
669 quote! {
670 #[automatically_derived]
671 impl #impl_generics #crossing for #subject #where_clause {
672 type Output<'__ingraph>
673 = <#inner as #crossing>::Output<'__ingraph>
674 where
675 Self: '__ingraph;
676
677 #[inline]
678 fn to_graphql_output(__ingraph_value: &Self) -> Self::Output<'_> {
679 <#inner as #crossing>::to_graphql_output(&__ingraph_value.#member)
680 }
681 }
682 }
683 }
684
685 /// The newtype's own SCALAR — the half only a declaring crate can write.
686 ///
687 /// async-graphql's own attribute over an `impl ScalarType`, which is the shape a declaring crate
688 /// wrote by hand before this door existed. Spending the library's macro rather than writing the
689 /// two faces out settles the OUTPUT leg's `boxed-trait` question by not asking it, and keeps the
690 /// registry entry the library's own.
691 ///
692 /// # The three bodies, and which of them the GATE moves
693 ///
694 /// `parse` and `is_valid` share ONE notion of validity, which is the corpus's standing rule: a
695 /// scalar narrowing in `parse` alone ships a validator admitting what its own parser rejects, and
696 /// the refusal then lands at execution rather than at validation, where a client is looking.
697 /// `to_value` is the WRITE, and a write has nothing to check.
698 fn scalar(&self) -> proc_macro2::TokenStream {
699 let Some(scalar) = self.kits.scalar.as_ref() else {
700 return quote!();
701 };
702 let subject = self.subject_type();
703 let inner = &self.inner;
704 let member = &self.member;
705 let ag = self.framework(&[], "async_graphql");
706 let gate = self.framework(&["gate"], "if_async_graphql");
707 let shelf = self.vendored("async_graphql");
708 let sdl = self.sdl();
709 let build = self.build("e!(__ingraph_inner));
710 // THE OBLIGATION, on the impl rather than at the call. A text door renders through `Display`
711 // and the other two legs read through the carrier's own `InputType`, and stating each as a
712 // `where` predicate is what lands the refusal at the DECLARATION naming the type that owes it
713 // — where a bare call would report a missing method inside an expansion, and would not compile
714 // at all for a wrapped type that is a PARAMETER.
715 let obligation: syn::WherePredicate = match scalar.gate.as_ref() {
716 Some(Gate::Parse(_)) => {
717 let subject_type = self.subject_type();
718 syn::parse_quote!(#subject_type: ::core::fmt::Display)
719 }
720 Some(Gate::Check(_)) | None => {
721 let bound = quote!(#ag::InputType);
722 self.owes(&bound)
723 }
724 };
725 let generics = self.generics_with(&[], &[obligation]);
726 let (impl_generics, _, where_clause) = generics.split_for_impl();
727
728 let (parse, valid, render) = match scalar.gate.as_ref() {
729 // TEXT IN, WIDE: a JSON string, handed to the declaration's own door. What spellings are
730 // admitted is that function's business and there is no second grammar here to keep in step;
731 // what this layer adds is the JSON SHAPE, and the refusal a client gets for anything else.
732 Some(Gate::Parse(door)) => (
733 quote! {
734 match &__ingraph_value {
735 #ag::Value::String(__ingraph_text) => ::core::result::Result::map_err(
736 #door(__ingraph_text),
737 #ag::InputValueError::custom,
738 ),
739 _ => ::core::result::Result::Err(
740 #ag::InputValueError::expected_type(::core::clone::Clone::clone(&__ingraph_value)),
741 ),
742 }
743 },
744 quote! {
745 match __ingraph_value {
746 #ag::Value::String(__ingraph_text) => ::core::result::Result::is_ok(&#door(__ingraph_text)),
747 _ => false,
748 }
749 },
750 // STRICT OUT: the canonical rendering, whichever spelling came in. `Display` is where a
751 // text door's canonical form lives — the door folds, so the value this holds is already the
752 // one spelling this type admits back.
753 quote!(#ag::Value::String(::std::string::ToString::to_string(self))),
754 ),
755 // THE CARRIER'S OWN FORM, ANCHORED: the inner type reads the JSON — a number is a number — and
756 // the door says whether the value it read is one of this type's.
757 Some(Gate::Check(door)) => (
758 quote! {
759 match <#inner as #ag::InputType>::parse(::core::option::Option::Some(
760 ::core::clone::Clone::clone(&__ingraph_value),
761 )) {
762 ::core::result::Result::Ok(__ingraph_inner) => ::core::result::Result::map_err(
763 #door(__ingraph_inner),
764 #ag::InputValueError::custom,
765 ),
766 ::core::result::Result::Err(__ingraph_refused) => ::core::result::Result::Err(
767 #ag::InputValueError::propagate(__ingraph_refused),
768 ),
769 }
770 },
771 quote! {
772 match <#inner as #ag::InputType>::parse(::core::option::Option::Some(
773 ::core::clone::Clone::clone(__ingraph_value),
774 )) {
775 ::core::result::Result::Ok(__ingraph_inner) => {
776 ::core::result::Result::is_ok(&#door(__ingraph_inner))
777 }
778 ::core::result::Result::Err(_) => false,
779 }
780 },
781 quote!(<#inner as #ag::InputType>::to_value(&self.#member)),
782 ),
783 // NO DOOR: the wire grammar is the INNER type's, under this type's name. An inner type with no
784 // wire face of its own is `E0277` naming that type.
785 None => (
786 quote! {
787 ::core::result::Result::map_err(
788 ::core::result::Result::map(
789 <#inner as #ag::InputType>::parse(::core::option::Option::Some(__ingraph_value)),
790 |__ingraph_inner| #build,
791 ),
792 #ag::InputValueError::propagate,
793 )
794 },
795 quote! {
796 ::core::result::Result::is_ok(&<#inner as #ag::InputType>::parse(
797 ::core::option::Option::Some(::core::clone::Clone::clone(__ingraph_value)),
798 ))
799 },
800 quote!(<#inner as #ag::InputType>::to_value(&self.#member)),
801 ),
802 };
803
804 quote! {
805 #gate! {
806 #[#ag::Scalar(crate = #shelf, name = #sdl)]
807 impl #impl_generics #ag::ScalarType for #subject #where_clause {
808 fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
809 #parse
810 }
811
812 fn is_valid(__ingraph_value: &#ag::Value) -> ::core::primitive::bool {
813 #valid
814 }
815
816 fn to_value(&self) -> #ag::Value {
817 #render
818 }
819 }
820 }
821 }
822 }
823
824 // ---------------------------------------------------------------------------------------------
825 // The page and storage domains
826 // ---------------------------------------------------------------------------------------------
827
828 /// [`CursorValue`] — the keyset position, WRITTEN as the inner type writes it and READ back
829 /// through this type's own door.
830 ///
831 /// The read RE-VALIDATES wherever a door was declared, and that is not belt and braces: a cursor
832 /// is a string a CLIENT hands back, so a forged position is refused rather than turned into a
833 /// value whose type says it cannot exist. Where no door was declared there is no invariant to
834 /// keep, and the inner's own `read_cursor` is the whole check — its width, its charset and its
835 /// domain.
836 fn cursor(&self) -> proc_macro2::TokenStream {
837 if !self.kits.cursor {
838 return quote!();
839 }
840 let subject = self.subject_type();
841 let inner = &self.inner;
842 let member = &self.member;
843 let cursor_value = self.framework(&["cursor"], "CursorValue");
844 let read = self.gated_read("e!(__ingraph_inner), ReadFailure::None);
845 let mut predicates = vec![self.owes(&cursor_value)];
846 predicates.extend(self.rendering());
847 let generics = self.generics_with(&[], &predicates);
848 let (impl_generics, _, where_clause) = generics.split_for_impl();
849 quote! {
850 #[automatically_derived]
851 impl #impl_generics #cursor_value for #subject #where_clause {
852 #[inline]
853 fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
854 <#inner as #cursor_value>::write_cursor(&self.#member, __ingraph_out)
855 }
856
857 fn read_cursor(
858 __ingraph_bytes: &[::core::primitive::u8],
859 ) -> ::core::option::Option<Self> {
860 match <#inner as #cursor_value>::read_cursor(__ingraph_bytes) {
861 ::core::option::Option::Some(__ingraph_inner) => #read,
862 ::core::option::Option::None => ::core::option::Option::None,
863 }
864 }
865 }
866 }
867 }
868
869 /// [`ColumnKind`] — what this newtype spans beneath the field that names it.
870 ///
871 /// The inner type's answer, which is the whole content of a transparent wrapper's width: a
872 /// newtype over a `u64` is one column and a newtype over a two-column composite is two, and
873 /// nothing here decides which.
874 ///
875 /// UNGATED, as the trait is: a width names no database. It is emitted wherever a DIALECT was named
876 /// — that being the one place the fact is spent — and a declaration that names none has no column
877 /// to have a width.
878 ///
879 /// The SAMENESS row beside it is emitted UNCONDITIONALLY, and the asymmetry is where each is
880 /// spent: a width is read by a row, and a row exists only where a dialect was named, but a
881 /// `ColumnEq` is folded by a PAGE CURSOR too — and by the `#[derive(ingraph::Id)]` wrapper this
882 /// value may be the inner of, which names its own databases rather than inheriting these. That is
883 /// the posture `id`'s device already takes for the same reason, and the row costs a declaration
884 /// nothing it does not already owe: its obligation is the INNER's `ColumnEq`, stated in a `where`
885 /// clause and therefore proved only where something actually compares one.
886 fn column(&self) -> proc_macro2::TokenStream {
887 let subject = self.subject_type();
888 let inner = &self.inner;
889 let column_eq = self.framework(&["column"], "ColumnEq");
890 let eq_generics = self.generics_with(&[], &[self.owes(&column_eq)]);
891 let (eq_impl_generics, _, eq_where_clause) = eq_generics.split_for_impl();
892 // The SAMENESS row, on the width row's own argument read one face over: a transparent wrapper
893 // IS the value it wraps, so two of them are one column value exactly when the two inners are. It
894 // owes the inner's `ColumnEq` rather than a `PartialEq`, which is what lets a newtype over a
895 // type whose sameness is not `==` be stored without this device knowing which type that is.
896 let sameness = quote! {
897 #[automatically_derived]
898 impl #eq_impl_generics #column_eq for #subject #eq_where_clause {
899 #[inline]
900 fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
901 <#inner as #column_eq>::column_eq(&self.0, &__ingraph_other.0)
902 }
903 }
904 };
905 if self.kits.databases.is_empty() {
906 return sameness;
907 }
908 let column_kind = self.framework(&["column"], "ColumnKind");
909 let shape = self.framework(&["column"], "ColumnShape");
910 let generics = self.generics_with(&[], &[self.owes(&column_kind)]);
911 let (impl_generics, _, where_clause) = generics.split_for_impl();
912 quote! {
913 #[automatically_derived]
914 impl #impl_generics #column_kind for #subject #where_clause {
915 const SEGMENTS: &'static [#shape] = <#inner as #column_kind>::SEGMENTS;
916 }
917
918 #sameness
919 }
920 }
921
922 /// [`StoredAs`] — the WORD a dialect's `CREATE TABLE` declares this newtype's columns with.
923 ///
924 /// [`column`](Self::column)'s twin, one face over and by the same argument: a transparent wrapper
925 /// is declared exactly as the thing it wraps, so a newtype over a `u64` takes `BIGINT` where that
926 /// `u64` does and one over a composite takes its whole list. Nothing here chooses a word.
927 ///
928 /// ONE impl over every dialect at once, for the reason `ColumnKind`'s is one impl over every
929 /// width: the parameter is the trait's, the inner type's obligation is stated at it, and a dialect
930 /// the inner type has no row in is `E0277` naming that type at the call site that asked. `Db`
931 /// carries no bound here because the trait carries none — a downstream target that is no
932 /// `sqlx::Database` joins by writing rows, and a wrapper over a type that joined must follow.
933 fn stored(&self) -> proc_macro2::TokenStream {
934 if self.kits.databases.is_empty() {
935 return quote!();
936 }
937 let subject = self.subject_type();
938 let inner = &self.inner;
939 let stored_as = self.framework(&["column"], "StoredAs");
940 let db = crate::emit::parameter("DB");
941 let generics = self.generics_with(
942 &[syn::parse_quote!(#db)],
943 &[self.owes("e!(#stored_as<#db>))],
944 );
945 let (impl_generics, _, where_clause) = generics.split_for_impl();
946 quote! {
947 #[automatically_derived]
948 impl #impl_generics #stored_as<#db> for #subject #where_clause {
949 const WORDS: &'static [&'static ::core::primitive::str] =
950 <#inner as #stored_as<#db>>::WORDS;
951 }
952 }
953 }
954
955 /// [`Assemble`] — how a holder's row reads one of these back.
956 ///
957 /// Generic over the ROW and stated ONCE, where the bind rows are per dialect: what varies per
958 /// dialect is the `Decode` this delegates through, and stating it as an obligation on the INNER
959 /// type is what lets one impl serve every dialect the declaration's own rows cover.
960 ///
961 /// The FAMILY gate rather than a dialect's, and rather than none: the trait is `sqlx::Row`'s
962 /// vocabulary, so a build with no SQL family has no trait for this to implement — while a build
963 /// with two would get this impl twice if it rode the per-dialect gates the bind rows ride.
964 fn read(&self) -> proc_macro2::TokenStream {
965 if self.kits.databases.is_empty() {
966 return quote!();
967 }
968 let subject = self.subject_type();
969 let inner = &self.inner;
970 let gate = self.framework(&["gate"], "if_sqlx");
971 let assemble = self.framework(&["column"], "Assemble");
972 let path = self.framework(&["comparison"], "Path");
973 let result = self.framework(&["sqlx"], "Result");
974 let row = crate::emit::parameter("ROW");
975 let bound = quote!(#assemble<'__ingraph, #row>);
976 let read = self.gated_read("e!(__ingraph_inner), ReadFailure::Decode);
977 let mut predicates = vec![self.owes(&bound)];
978 predicates.extend(self.rendering());
979 let generics = self.generics_with(
980 &[
981 syn::parse_quote!('__ingraph),
982 syn::GenericParam::Type(syn::TypeParam::from(row.clone())),
983 ],
984 &predicates,
985 );
986 let (impl_generics, _, where_clause) = generics.split_for_impl();
987 quote! {
988 #gate! {
989 #[automatically_derived]
990 impl #impl_generics #assemble<'__ingraph, #row> for #subject #where_clause {
991 fn assemble(
992 __ingraph_row: &'__ingraph #row,
993 __ingraph_under: ::core::option::Option<&#path<'_>>,
994 ) -> #result<Self> {
995 let __ingraph_inner =
996 <#inner as #bound>::assemble(__ingraph_row, __ingraph_under)?;
997 #read
998 }
999 }
1000 }
1001 }
1002 }
1003
1004 /// ONE dialect's rows: the three sqlx halves and the framework's own bind.
1005 ///
1006 /// All four DELEGATE, and `Encode` delegates in FULL — `encode`, `encode_by_ref`, `produces` and
1007 /// `size_hint`. [`produces`](sqlx::Encode::produces) is the one that would matter quietly: it is
1008 /// the per-VALUE type override, consulted ahead of `Type::type_info`, so a default `None` here
1009 /// would discard an inner type's answer with nothing to see.
1010 fn storage(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
1011 let subject = self.subject_type();
1012 let inner = &self.inner;
1013 let member = &self.member;
1014 let gate = self.framework(&["gate"], &database.gate().to_string());
1015 let (segments, item) = database.backend();
1016 let backend = self.framework(segments, item);
1017 let carrier = self.framework(&["comparison", "sql"], "Carrier");
1018 let query_builder = self.framework(&["sqlx"], "QueryBuilder");
1019 let sqlx_type = self.framework(&["sqlx"], "Type");
1020 let encode = self.framework(&["sqlx"], "Encode");
1021 let decode = self.framework(&["sqlx"], "Decode");
1022 let database_trait = self.framework(&["sqlx"], "Database");
1023 let is_null = self.framework(&["sqlx", "encode"], "IsNull");
1024 let error = self.framework(&["sqlx", "error"], "BoxDynError");
1025
1026 let type_bound = quote!(#sqlx_type<#backend>);
1027 let type_generics = self.generics_with(&[], &[self.owes(&type_bound)]);
1028 let (type_impl, _, type_where) = type_generics.split_for_impl();
1029
1030 let encode_bound = quote!(#encode<'__ingraph, #backend>);
1031 let encode_generics = self.generics_with(
1032 &[syn::parse_quote!('__ingraph)],
1033 &[self.owes(&encode_bound)],
1034 );
1035 let (encode_impl, _, encode_where) = encode_generics.split_for_impl();
1036
1037 let decode_bound = quote!(#decode<'__ingraph, #backend>);
1038 let mut decode_predicates = vec![self.owes(&decode_bound)];
1039 decode_predicates.extend(self.rendering());
1040 let decode_generics = self.generics_with(&[syn::parse_quote!('__ingraph)], &decode_predicates);
1041 let (decode_impl, _, decode_where) = decode_generics.split_for_impl();
1042 let decoded = self.gated_read("e!(__ingraph_inner), ReadFailure::Boxed);
1043
1044 let carrier_bound = quote!(#carrier<#backend>);
1045 let carrier_generics = self.generics_with(&[], &[self.owes(&carrier_bound)]);
1046 let (carrier_impl, _, carrier_where) = carrier_generics.split_for_impl();
1047
1048 let taken = match &self.member {
1049 syn::Member::Named(ident) => quote!(self.#ident),
1050 syn::Member::Unnamed(index) => quote!(self.#index),
1051 };
1052
1053 quote! {
1054 #gate! {
1055 #[automatically_derived]
1056 impl #type_impl #sqlx_type<#backend> for #subject #type_where {
1057 fn type_info() -> <#backend as #database_trait>::TypeInfo {
1058 <#inner as #type_bound>::type_info()
1059 }
1060
1061 fn compatible(
1062 __ingraph_info: &<#backend as #database_trait>::TypeInfo,
1063 ) -> ::core::primitive::bool {
1064 <#inner as #type_bound>::compatible(__ingraph_info)
1065 }
1066 }
1067
1068 #[automatically_derived]
1069 impl #encode_impl #encode<'__ingraph, #backend> for #subject #encode_where {
1070 fn encode(
1071 self,
1072 __ingraph_buf: &mut <#backend as #database_trait>::ArgumentBuffer,
1073 ) -> ::core::result::Result<#is_null, #error> {
1074 <#inner as #encode_bound>::encode(#taken, __ingraph_buf)
1075 }
1076
1077 fn encode_by_ref(
1078 &self,
1079 __ingraph_buf: &mut <#backend as #database_trait>::ArgumentBuffer,
1080 ) -> ::core::result::Result<#is_null, #error> {
1081 <#inner as #encode_bound>::encode_by_ref(&self.#member, __ingraph_buf)
1082 }
1083
1084 fn produces(
1085 &self,
1086 ) -> ::core::option::Option<<#backend as #database_trait>::TypeInfo> {
1087 <#inner as #encode_bound>::produces(&self.#member)
1088 }
1089
1090 fn size_hint(&self) -> ::core::primitive::usize {
1091 <#inner as #encode_bound>::size_hint(&self.#member)
1092 }
1093 }
1094
1095 #[automatically_derived]
1096 impl #decode_impl #decode<'__ingraph, #backend> for #subject #decode_where {
1097 fn decode(
1098 __ingraph_value: <#backend as #database_trait>::ValueRef<'__ingraph>,
1099 ) -> ::core::result::Result<Self, #error> {
1100 let __ingraph_inner = <#inner as #decode_bound>::decode(__ingraph_value)?;
1101 #decoded
1102 }
1103 }
1104
1105 #[automatically_derived]
1106 impl #carrier_impl #carrier<#backend> for #subject #carrier_where {
1107 fn push_bind(&self, __ingraph_qb: &mut #query_builder<#backend>) {
1108 <#inner as #carrier_bound>::push_bind(&self.#member, __ingraph_qb)
1109 }
1110 }
1111 }
1112 }
1113 }
1114
1115 /// One READ path's tail: the door where one was declared, the plain wrap where none was.
1116 ///
1117 /// `failure` is what a refused door becomes at that position, which is the only thing the three
1118 /// read paths differ in — a cursor answers [`None`], a decode answers its own error type. The
1119 /// DOOR is the same door at all three, which is the whole of *one source*.
1120 fn gated_read(
1121 &self,
1122 inner: &proc_macro2::TokenStream,
1123 failure: ReadFailure,
1124 ) -> proc_macro2::TokenStream {
1125 let built = self.build(inner);
1126 let Some(gate) = self.kits.gate() else {
1127 return match failure {
1128 ReadFailure::None => quote!(::core::option::Option::Some(#built)),
1129 ReadFailure::Decode | ReadFailure::Boxed => quote!(::core::result::Result::Ok(#built)),
1130 };
1131 };
1132 let call = match gate {
1133 // A text door reads SPELLINGS, and a stored value or a cursor's bytes have already been read
1134 // back as the inner type — so the door is reached through that type's own text form, which is
1135 // the one rendering `to_value` wrote out.
1136 Gate::Parse(door) => {
1137 let text = quote!(::std::string::ToString::to_string(&#inner));
1138 quote!(#door(&#text))
1139 }
1140 Gate::Check(door) => quote!(#door(#inner)),
1141 };
1142 match failure {
1143 ReadFailure::None => quote! {
1144 match #call {
1145 ::core::result::Result::Ok(__ingraph_value) => ::core::option::Option::Some(__ingraph_value),
1146 ::core::result::Result::Err(_) => ::core::option::Option::None,
1147 }
1148 },
1149 ReadFailure::Decode => {
1150 let sqlx_error = self.framework(&["sqlx"], "Error");
1151 quote! {
1152 match #call {
1153 ::core::result::Result::Ok(__ingraph_value) => ::core::result::Result::Ok(__ingraph_value),
1154 ::core::result::Result::Err(__ingraph_refused) => ::core::result::Result::Err(
1155 #sqlx_error::Decode(::std::boxed::Box::new(__ingraph_refused)),
1156 ),
1157 }
1158 }
1159 }
1160 ReadFailure::Boxed => quote! {
1161 match #call {
1162 ::core::result::Result::Ok(__ingraph_value) => ::core::result::Result::Ok(__ingraph_value),
1163 ::core::result::Result::Err(__ingraph_refused) => {
1164 ::core::result::Result::Err(::std::convert::From::from(__ingraph_refused))
1165 }
1166 }
1167 },
1168 }
1169 }
1170}
1171
1172/// What a refused door becomes at ONE read position.
1173#[derive(Clone, Copy)]
1174enum ReadFailure {
1175 /// A cursor: a forged position is [`None`], and there is no sentence to carry.
1176 None,
1177 /// A row decode: `sqlx::Error::Decode`, carrying the door's own refusal.
1178 Decode,
1179 /// A value decode: `sqlx::error::BoxDynError`, reached through `From`.
1180 Boxed,
1181}
1182
1183/// The marker one family is spelled as, which a field of the newtype resolves to by default.
1184const fn family_marker(family: ElementFamily) -> &'static str {
1185 match family {
1186 ElementFamily::Scalar => "ScalarMarker",
1187 ElementFamily::String => "StringMarker",
1188 ElementFamily::Bytes => "BytesMarker",
1189 ElementFamily::Enum => "EnumMarker",
1190 }
1191}
1192
1193/// The family trait that carries this family's filter — the map a field's reading resolves through.
1194const fn family_filter_marker(family: ElementFamily) -> &'static str {
1195 match family {
1196 ElementFamily::Scalar => "ScalarFilterMarker",
1197 ElementFamily::String => "StringFilterMarker",
1198 ElementFamily::Bytes => "BytesFilterMarker",
1199 ElementFamily::Enum => "EnumFilterMarker",
1200 }
1201}
1202
1203/// The framework filter one family's reading names.
1204const fn family_filter(family: ElementFamily) -> &'static str {
1205 match family {
1206 ElementFamily::Scalar => "ScalarFilter",
1207 ElementFamily::String => "TextFilter",
1208 ElementFamily::Bytes => "BytesFilter",
1209 ElementFamily::Enum => "EnumFilter",
1210 }
1211}
1212
1213/// The CARRIER READING one family is reached through, where it has one.
1214///
1215/// The enumeration has none, and the absence is the framework's shape rather than a gap:
1216/// `EnumFilter<T>` takes no carrier parameter, a closed vocabulary's operands crossing as
1217/// themselves — so `marker(enum)` names the filter directly and there is no reading to mint.
1218const fn family_reading(family: ElementFamily) -> Option<&'static str> {
1219 match family {
1220 ElementFamily::Scalar => Some("ScalarWire"),
1221 ElementFamily::String => Some("TextWire"),
1222 ElementFamily::Bytes => Some("BytesWire"),
1223 ElementFamily::Enum => None,
1224 }
1225}