Skip to main content

ingraph_codegen/interface/
page.rs

1//! What an interface's PAGE is made of: the cursor value one resumes at, and the predicate one is
2//! filtered by.
3//!
4//! # Both are per DATABASE, for the projection row's reason
5//!
6//! A cursor slot holds a STORED value and a predicate compares one, so both are about the types this
7//! database keeps the shared columns at — which is the interface's own pin, the very thing
8//! [`equations`](super::equations) discharged at every member's row. So there is one of each per SQL
9//! database, exactly as there is one projection row.
10//!
11//! # The cursor's two SYNTHESIZED slots wear a fence a declaration cannot reach
12//!
13//! A record's cursor is a variant per stored column. An interface's is that plus TWO: the
14//! discriminant and the address, which are the tail of every interface's total order. Their variants
15//! are `__IgKind` and `__IgAddress`, and the leading underscores are load-bearing —
16//! [`upper_camel`](crate::emit::upper_camel) never produces one, because it treats `_` as a case
17//! break and drops it, so no declared field's variant can be spelled either way. That closes a hole
18//! the ROW deliberately leaves open: a shared field called `id` collides with the row's address
19//! field, as two columns of one name collide anywhere, and it collides with nothing here.
20//!
21//! # The ADDRESS slot is one variant carrying `<I>Id`, and never one per member
22//!
23//! The members disagree about what an id IS, and `<I>Id` is already the sum that says so. Folding
24//! its variants into the cursor would be that sum written twice — and the codec's tag would then
25//! encode WHICH MEMBER in a byte the framework owns, where `<I>Id`'s own codec is the one place a
26//! member's id is written and read.
27//!
28//! # What a HETEROGENEOUS address costs, and which dialect pays
29//!
30//! `UNION ALL` requires the arms' columns to have compatible types. SQLite has no such rule — a
31//! column's type is a value's — so an integer id beside a text one is one union there. PostgreSQL
32//! and MySQL refuse it AT THE STATEMENT. Nothing here narrows the sum, because the sum is what the
33//! declaration said; what it means is that an interface whose members are keyed differently is a
34//! SQLite interface, and the refusal is the engine's own and arrives with the statement.
35
36use quote::{format_ident, quote};
37
38use crate::{
39  emit::{leading, parameter},
40  interface::{InterfaceField, InterfaceModel},
41  model::DatabaseKind,
42  unit,
43};
44
45/// The cursor variant the DISCRIMINANT rides in.
46///
47/// A leading `__` is what a declared field's variant cannot have — see the module note.
48const KIND_VARIANT: &str = "__IgKind";
49
50/// The cursor variant the ADDRESS rides in.
51const ADDRESS_VARIANT: &str = "__IgAddress";
52
53impl InterfaceModel {
54  /// What one database's CURSOR VALUE is called: `<I><Db>Cursor`.
55  #[must_use]
56  pub fn cursor_name(&self, kind: DatabaseKind) -> syn::Ident {
57    format_ident!("{}{}Cursor", self.name, kind.suffix())
58  }
59
60  /// What one database's PREDICATE is called: `<I><Db>Comparison`.
61  #[must_use]
62  pub fn comparison_name(&self, kind: DatabaseKind) -> syn::Ident {
63    format_ident!("{}{}Comparison", self.name, kind.suffix())
64  }
65
66  /// The page's two types per SQL database, plus the address sum's own codec and binding.
67  pub(crate) fn page(&self) -> proc_macro2::TokenStream {
68    if !self.projects() {
69      return quote!();
70    }
71    let address = self.address_carrier();
72    let databases = self.sql_databases().into_iter().map(|kind| {
73      let cursor = self.cursor_value(kind);
74      let comparison = self.comparison(kind);
75      quote! {
76        #cursor
77        #comparison
78      }
79    });
80    quote! {
81      #address
82      #(#databases)*
83    }
84  }
85
86  /// `<I>Id`'s own codec and binding — how the ADDRESS slot of a cursor is written, read and bound.
87  ///
88  /// DB-LESS for the codec and generic for the binding, which is the shape the sum has: what a
89  /// member's id encodes to is the member's own business and the same in every database, and what it
90  /// BINDS as is the dialect's. One tag per member, in declaration order, and a tag naming no member
91  /// is refused rather than read as the nearest one — the bytes are a client's.
92  fn address_carrier(&self) -> proc_macro2::TokenStream {
93    let name = super::default_id_name(&self.name);
94    let identifiable = self.framework(&["transform"], "Identifiable");
95    let cursor_value = self.framework(&["cursor"], "CursorValue");
96    let carrier = self.framework(&["comparison", "sql"], "Carrier");
97    let database = self.framework(&["sqlx"], "Database");
98    let held = self.framework(&["sqlx"], "QueryBuilder");
99    let db = parameter("DB");
100
101    let writes = self.members.iter().enumerate().map(|(tag, member)| {
102      let variant = &member.ident;
103      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
104      quote! {
105        Self::#variant(__ingraph_value) => {
106          __ingraph_out.push(#tag);
107          #cursor_value::write_cursor(__ingraph_value, __ingraph_out);
108        }
109      }
110    });
111    let reads = self.members.iter().enumerate().map(|(tag, member)| {
112      let (variant, ty) = (&member.ident, &member.ty);
113      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
114      quote! {
115        #tag => ::core::option::Option::map(
116          <<#ty as #identifiable>::Id as #cursor_value>::read_cursor(__ingraph_rest),
117          Self::#variant,
118        ),
119      }
120    });
121    let binds = self.members.iter().map(|member| {
122      let variant = &member.ident;
123      quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
124    });
125    let codecs = self.members.iter().map(|member| {
126      let ty = &member.ty;
127      quote!(<#ty as #identifiable>::Id: #cursor_value,)
128    });
129    let bounds = self.members.iter().map(|member| {
130      let ty = &member.ty;
131      quote!(<#ty as #identifiable>::Id: #carrier<#db>,)
132    });
133
134    let write_doc = leading("Append this address's member tag and that member's own id bytes.");
135    let read_doc = leading("The address `bytes` hold, or `None` where they name no member.");
136    let bind_doc = leading("Bind this address, in the type its own member's table stores.");
137    quote! {
138      #[automatically_derived]
139      impl #cursor_value for #name
140      where
141        #(#codecs)*
142      {
143        #[doc = #write_doc]
144        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
145          match self {
146            #(#writes)*
147          }
148        }
149
150        #[doc = #read_doc]
151        fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
152          let (__ingraph_tag, __ingraph_rest) =
153            <[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
154          match *__ingraph_tag {
155            #(#reads)*
156            _ => ::core::option::Option::None,
157          }
158        }
159      }
160
161      #[automatically_derived]
162      impl<#db> #carrier<#db> for #name
163      where
164        #db: #database,
165        #(#bounds)*
166      {
167        #[doc = #bind_doc]
168        fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
169          match self {
170            #(#binds)*
171          }
172        }
173      }
174    }
175  }
176
177  /// `<I><Db>Cursor` — one slot of a cursor over this interface's page in one database.
178  ///
179  /// A variant per SHARED column at the type this database pins it to, then the two the framework
180  /// synthesizes. The tag is the variant's POSITION, so a slot read back carries which column it was
181  /// written from and a forged frame cannot move a text value into an integer column's slot.
182  ///
183  /// The DISCRIMINANT's slot holds the vocabulary rather than its word, and writes the word: what a
184  /// statement compares is the projected string, so the codec and the bind are both over
185  /// `as_str`, and reading one back goes through `parse` — a word naming no member is refused there
186  /// exactly as it is at the row's decode.
187  fn cursor_value(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
188    let vis = &self.vis;
189    let interface = &self.name;
190    let name = self.cursor_name(kind);
191    let vocabulary = super::default_kind_name(interface);
192    let address = super::default_id_name(interface);
193    let kind_variant = format_ident!("{KIND_VARIANT}");
194    let address_variant = format_ident!("{ADDRESS_VARIANT}");
195
196    let cursor_value = self.framework(&["cursor"], "CursorValue");
197    // The SLOT is reached at THIS dialect — see `emit::query`'s own note for the ruling: a page
198    // cursor is session-lived state, so a value's bytes may be the engine's. The blanket over
199    // `CursorValue` answers for everything whose bytes are the same everywhere, which is every slot
200    // this seat had before the seam existed.
201    let dialect_cursor = self.framework(&["cursor"], "DialectCursor");
202    let (module, item) = kind.dialect();
203    let backend = self.framework(module, item);
204    let carrier = self.framework(&["comparison", "sql"], "Carrier");
205    let capability = self.framework(&["interface"], "InterfaceKind");
206    let database = self.framework(&["sqlx"], "Database");
207    let held = self.framework(&["sqlx"], "QueryBuilder");
208    let db = parameter("DB");
209
210    // [`InterfaceModel::projected`] and not the whole stored tier: a cursor's slot is a value the
211    // statement can hand back and the carrier can bind, and a COLLECTION is neither here. It is the
212    // same fence `DatabaseBackend::paged_columns` states for a record's own cursor, WITHOUT that
213    // one's per-dialect fork: a record asks `edge_stored` and may answer *array*, where an
214    // interface's collection is edge-form on every backend, so no arm of a union can project one.
215    // Here it is not even a narrowing of what the union hands back: a collection is no column of
216    // the union's output either, so there is nothing decoded for a slot to hold.
217    let stored: Vec<&InterfaceField> = self.projected().collect();
218    let variants = stored.iter().map(|field| {
219      let variant = variant_of(field);
220      let ty = self.stored_at(field, kind);
221      let doc = leading(&format!("The `{}` column's value.", field.name));
222      quote! {
223        #[doc = #doc]
224        #variant(#ty),
225      }
226    });
227    let writes = stored.iter().enumerate().map(|(tag, field)| {
228      let variant = variant_of(field);
229      let ty = self.stored_at(field, kind);
230      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
231      quote! {
232        Self::#variant(__ingraph_value) => {
233          __ingraph_out.push(#tag);
234          <#ty as #dialect_cursor<#backend>>::write_cursor_at(__ingraph_value, __ingraph_out);
235        }
236      }
237    });
238    let reads = stored.iter().enumerate().map(|(tag, field)| {
239      let variant = variant_of(field);
240      let ty = self.stored_at(field, kind);
241      let tag = u8::try_from(tag).unwrap_or(u8::MAX);
242      quote! {
243        #tag => ::core::option::Option::map(
244          <#ty as #dialect_cursor<#backend>>::read_cursor_at(__ingraph_rest),
245          Self::#variant,
246        ),
247      }
248    });
249    let binds = stored.iter().map(|field| {
250      let variant = variant_of(field);
251      quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
252    });
253    let codecs = stored.iter().map(|field| {
254      let ty = self.stored_at(field, kind);
255      quote!(#ty: #dialect_cursor<#backend>,)
256    });
257    let bounds = stored.iter().map(|field| {
258      let ty = self.stored_at(field, kind);
259      quote!(#ty: #carrier<#db>,)
260    });
261    // The two synthesized tags sit ABOVE the shared columns', so adding a field to the contract
262    // moves no existing slot's tag and every cursor a deployment already handed out still reads.
263    let kind_tag = u8::try_from(stored.len()).unwrap_or(u8::MAX);
264    let address_tag = kind_tag.saturating_add(1);
265
266    let what = super::row::what(kind);
267    let doc = leading(&format!(
268      "One slot of a cursor over a page of [`{interface}`] in {what} — which column, and the value \
269       it held at the boundary row.\n\nThe last two are the framework's own: an interface's total \
270       order ends `…, __ig_kind__, id`, because an id is `UNIQUE` only within its own member's \
271       table and the discriminant is what tells two members' rows apart."
272    ));
273    let kind_doc = leading(
274      "The DISCRIMINANT the boundary row carried. Minted from the address rather than carried \
275       beside it, so the pair cannot disagree.",
276    );
277    let address_doc =
278      leading("The boundary row's ADDRESS — which member, and that member's own id.");
279    let write_doc = leading("Append this slot's tag and its value's own bytes.");
280    let read_doc = leading("The slot `bytes` hold, or `None` where they name no column.");
281    let bind_doc = leading("Bind this slot's value, in the type this database stores.");
282    quote! {
283      #[doc = #doc]
284      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
285      #vis enum #name {
286        #(#variants)*
287        #[doc = #kind_doc]
288        #kind_variant(#vocabulary),
289        #[doc = #address_doc]
290        #address_variant(#address),
291      }
292
293      #[automatically_derived]
294      impl #cursor_value for #name
295      where
296        #(#codecs)*
297        #address: #cursor_value,
298      {
299        #[doc = #write_doc]
300        fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
301          match self {
302            #(#writes)*
303            Self::#kind_variant(__ingraph_value) => {
304              __ingraph_out.push(#kind_tag);
305              #cursor_value::write_cursor(
306                &::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
307                __ingraph_out,
308              );
309            }
310            Self::#address_variant(__ingraph_value) => {
311              __ingraph_out.push(#address_tag);
312              #cursor_value::write_cursor(__ingraph_value, __ingraph_out);
313            }
314          }
315        }
316
317        #[doc = #read_doc]
318        fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
319          let (__ingraph_tag, __ingraph_rest) =
320            <[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
321          match *__ingraph_tag {
322            #(#reads)*
323            #kind_tag => ::core::option::Option::map(
324              ::core::result::Result::ok(<#vocabulary as #capability>::parse(
325                &<::std::string::String as #cursor_value>::read_cursor(__ingraph_rest)?,
326              )),
327              Self::#kind_variant,
328            ),
329            #address_tag => ::core::option::Option::map(
330              <#address as #cursor_value>::read_cursor(__ingraph_rest),
331              Self::#address_variant,
332            ),
333            _ => ::core::option::Option::None,
334          }
335        }
336      }
337
338      #[automatically_derived]
339      impl<#db> #carrier<#db> for #name
340      where
341        #db: #database,
342        #(#bounds)*
343        ::std::string::String: #carrier<#db>,
344        #address: #carrier<#db>,
345      {
346        #[doc = #bind_doc]
347        fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
348          match self {
349            #(#binds)*
350            // The WORD rather than the vocabulary, because the word is what the arms project and
351            // therefore what the resume predicate compares against.
352            Self::#kind_variant(__ingraph_value) => #carrier::push_bind(
353              &::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
354              __ingraph_qb,
355            ),
356            Self::#address_variant(__ingraph_value) =>
357              #carrier::push_bind(__ingraph_value, __ingraph_qb),
358          }
359        }
360      }
361    }
362  }
363
364  /// `<I><Db>Comparison` — a predicate over the interface's OWN vocabulary, in the types this
365  /// database stores.
366  ///
367  /// It is [`unit::comparison`](crate::unit::comparison) and
368  /// [`unit::comparison_lowering`](crate::unit::comparison_lowering)'s own walks and no longer a
369  /// second copy of them. The struct, the constructor, the borrow per column and the
370  /// `ComplexComparison` half are ONE emitter, shared with a record's predicate and a standalone
371  /// `#[derive(ingraph::Comparison)]`; what an interface supplies is the rows, the noun that says
372  /// each column is a SHARED one, and the paragraph a contract's predicate carries where a record's
373  /// has nothing to add.
374  ///
375  /// **Two ROW LISTS rather than one walk with a mode in it**, which is what let the collapse
376  /// happen at all: the struct's list is `stored()` and the lowering's is `projected()`, a subset,
377  /// and the lowering unit already takes its own list rather than narrowing the struct's — see the
378  /// two walks below.
379  ///
380  /// One field per shared column, each the comparison that column's filter crosses into — the record
381  /// comparison's shape exactly, over the contract's fields instead of a row's columns. What differs
382  /// is where it is APPLIED: a record's lands at its own table, and this one lands at the union's
383  /// derived table, where every arm has already aliased its member's column to the name this
384  /// predicate speaks.
385  fn comparison(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
386    let interface = &self.name;
387    let name = self.comparison_name(kind);
388    let db = parameter("DB");
389
390    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
391    let crossings = self.crossings(kind);
392
393    // The WHOLE stored tier holds a field here, collections included: a predicate over one is a real
394    // question and the crossing that builds it is the same crossing every other column takes. What
395    // differs is WHERE it is applied — see the two walks below.
396    let rows: Vec<unit::ComparisonColumn> = self
397      .stored()
398      .map(|field| {
399        let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
400        unit::ComparisonColumn {
401          // An INTERFACE's fields carry no condition seat — the `#[cfg]` word is the
402          // record family's, and this model has no field to hold one.
403          gate: proc_macro2::TokenStream::new(),
404          member: field.name.clone(),
405          name: format!("shared `{}` column", field.name),
406          held: quote!(<#filter as #to_comparison<#stored, #db>>::Comparison),
407        }
408      })
409      .collect();
410    let header = unit::UnitHeader {
411      vis: &self.vis,
412      name: name.clone(),
413      subject: format!("[`{interface}`]"),
414      note: Some(
415        "Written in the INTERFACE's vocabulary and lowered ONCE, above the union — a member that \
416         calls a shared column something else has already aliased it in its own arm, so one \
417         predicate answers whichever member the row came from."
418          .to_owned(),
419      ),
420    };
421    let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
422
423    // `ComplexComparison` is the ABOVE-THE-UNION half and it counts and renders the PROJECTED
424    // columns alone. A collection has no column in the union's output to compare — no backend keeps
425    // every collection in a column of the row, and the choice is the MEMBER's — so its conjuncts are
426    // rendered per ARM, at that member's own edge table, through `SqlInterface::collections`. Two
427    // walks over one struct, and the struct is the whole predicate either way.
428    let seats = unit::LoweringSeats {
429      backend: self.framework(&["comparison"], "Backend"),
430      complex: self.framework(&["comparison"], "ComplexComparison"),
431      frame: self.framework(&["comparison"], "Frame"),
432      at: self.framework(&["comparison"], "At"),
433      field_name: self.framework(&["field"], "FieldName"),
434    };
435    // `flatten` is FALSE at every column and is not a fork this side has: the word that sets it is a
436    // record's `persist(flatten)`, over a column whose comparison occupies more than one of its
437    // table's. An interface owns no table, and what it renders against is the union's derived one —
438    // where a column exists because an arm aliased it, which is one name and one segment.
439    let lowered: Vec<unit::LoweringColumn> = self
440      .projected()
441      .map(|field| unit::LoweringColumn {
442        // An INTERFACE's fields carry no condition seat — the `#[cfg]` word is the
443        // record family's, and this model has no field to hold one.
444        gate: proc_macro2::TokenStream::new(),
445        member: field.name.clone(),
446        rendered: field.name.to_string(),
447        flatten: false,
448        through: None,
449      })
450      .collect();
451    let lowering = unit::comparison_lowering(&name, &db, &crossings, &seats, &lowered);
452
453    quote! {
454      #declaration
455      #methods
456      #lowering
457    }
458  }
459
460  /// What a predicate over these shared columns ASSUMES, and what every item naming it repeats
461  /// verbatim: that the database is a backend at all, and that each column's filter crosses into
462  /// something for it.
463  ///
464  /// One function rather than one per item, for the record comparison's reason: the struct's `where`
465  /// clause is the whole of what makes its field types well formed, so an impl asserting anything
466  /// more would report a missing crossing twice.
467  fn crossings(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
468    let db = parameter("DB");
469    let backend = self.framework(&["comparison"], "Backend");
470    let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
471    let crossings = self.stored().map(|field| {
472      let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
473      quote!(#filter: #to_comparison<#stored, #db>,)
474    });
475    quote! {
476      #db: #backend,
477      #(#crossings)*
478    }
479  }
480
481  /// The FILTER one shared field is asked for by — the PIN's own word where the declaration wrote
482  /// one, and the type's own registry row where it did not. Never a name this crate builds.
483  ///
484  /// The interface grammar carries interpretation words now, so both paths a record's emission has
485  /// are here and they are the SAME function: [`crate::emit::filter_of`], which is where the routing
486  /// is written down once. A pin with no word takes the type's row, and a type with no row is
487  /// `E0277` at the declaration naming it.
488  ///
489  /// THREE readers, and that is what makes the crossing writable at all: the predicate's own field
490  /// types, the wire filter's, and the leg that carries one into the other. A filter asked for twice
491  /// is a filter two answers can disagree about, and between those two there is no conversion.
492  pub(super) fn filter_of(&self, field: &InterfaceField) -> proc_macro2::TokenStream {
493    // The STORED face: an interface's own filter is projected into `ToDatabaseComparison` at
494    // three seats, and that row is the column face's alone.
495    crate::emit::filter_of(
496      &self.krate,
497      &field.ty,
498      field.marker.as_ref(),
499      crate::emit::FilterFace::Column,
500    )
501  }
502}
503
504/// The cursor variant ONE shared column rides in — the field's name in upper camel case, which is
505/// the record cursor's own convention read through the contract's fields instead of a row's columns.
506fn variant_of(field: &InterfaceField) -> syn::Ident {
507  crate::emit::upper_camel(&field.name.to_string())
508}