ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! What a page of an interface BECOMES: the wire output every member answers as, and the gather
//! that fills one.
//!
//! # A page is two moments, and this is the second
//!
//! The union answers with the interface's own projection — the shared columns, the discriminant and
//! the address — and nothing else, because that is all a statement over several tables can promise.
//! What a client asked for is each member's WHOLE object, which lives in that member's own table. So
//! hydration is one gather per member, keyed on the addresses the page returned.
//!
//! ```text
//! MediaKind::Video ─► [MediaId::Video(1), MediaId::Video(7)]
//!                       │
//!                       ├─ the member's id-gather lane: SELECT … WHERE ("id") IN ((?), (?))
//!                       ├─ <Video as Record<Db>>::Row, one per row that came back
//!                       ├─ the member's OWN crossing onto the wire, which is minted from the ROW
//!                       └─ MediaGraphqlOutput::Video(…)
//! ```
//!
//! # Every name in it is a FAMILY PROJECTION
//!
//! `<M as Record<Db>>::Row`, `<<M as Transformer>::Graphql as Graphql>::Output`,
//! `<M as Identifiable>::Id`. Not one of them is a name this crate builds — which is the referencing
//! law the contract and the equations already follow, and it is what lets a member rename its row,
//! its output or its id without this expansion knowing.
//!
//! # The gather answers in the ENGINE's order, and the ids are what put it back
//!
//! A membership names a set, so the rows arrive in whatever sequence the plan chose. Each row is
//! asked for its own address — [`SqlQuery::id`], the dual of the predicate that fetched it — and
//! placed at the position the caller asked for it in. So the answer is in the CALLER's order, which
//! for a page's caller is the statement's.
//!
//! The placement is a linear scan per row, which is quadratic in the batch. A page is bounded by
//! `MAX_PAGE_SIZE`, so the worst case is a few tens of thousands of comparisons of one id — and an
//! index would need `Hash` or `Ord` on an id type the declaration owns, which is a bound this
//! crossing has no other reason to ask for.
//!
//! # A row the union answered with and the gather missed is REPORTED
//!
//! Two statements are two moments, so a row can be deleted between them — unless both ran inside one
//! read, which is what `BeginRead`'s passthrough is for. Outside one the gap is real, and it is
//! reported rather than papered over with a shorter list: a page that silently loses rows is a page
//! whose `hasNextPage` is a lie.

use quote::{format_ident, quote};

use crate::{
  emit::{leading, parameter},
  interface::InterfaceModel,
  model::DatabaseKind,
};

impl InterfaceModel {
  /// The wire OUTPUT every member of this interface answers as.
  ///
  /// A sum over `<<M as Transformer>::Graphql as Graphql>::Output`, which is the same projection
  /// `<I>Derivations` is declared to be implemented on — so the type a member's hand-written
  /// derivations land on and the type this variant carries are one type by construction.
  pub(crate) fn output(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let interface = &self.name;
    let name = super::default_output_name(interface);
    let transformer = self.framework(&["transform"], "Transformer");
    let graphql = self.framework(&["transform"], "Graphql");

    let variants = self.members.iter().map(|member| {
      let (variant, ty) = (&member.ident, &member.ty);
      let doc = leading(&format!(
        "A [`{}`], as that member's own declaration publishes it.",
        quote!(#ty)
      ));
      quote! {
        #[doc = #doc]
        #variant(<<#ty as #transformer>::Graphql as #graphql>::Output),
      }
    });
    let doc = leading(&format!(
      "One answer to a query over [`{interface}`] — whichever member the row came from, as that \
       member's own wire object.\n\nThe payload is reached as a family projection and never as a \
       name this crate builds, so a member that renames its output moves this variant with it."
    ));
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone)]
      #vis enum #name {
        #(#variants)*
      }
    }
  }

  /// ONE database's hydration: `<I>::hydrate_<db>`, inside that database's gate.
  ///
  /// The backend is CONCRETE here, exactly as the query binding's is and for the same reason — an
  /// interface's engine face is per database, so the method that reads a member's table names the
  /// database it reads. Ungated it would make a declaration naming Postgres fail to compile in a
  /// build without the Postgres driver.
  pub(crate) fn hydration(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let interface = &self.name;
    let vocabulary = super::default_kind_name(interface);
    let address = super::default_id_name(interface);
    let output = super::default_output_name(interface);
    let error = self.hydration_error(kind);

    let record = self.framework(&["transform"], "Record");
    let transformer = self.framework(&["transform"], "Transformer");
    let graphql = self.framework(&["transform"], "Graphql");
    let sql_query = self.framework(&["query", "sql"], "SqlQuery");
    let rows = self.framework(&["query", "sql"], "rows");
    let begin_read = self.framework(&["query", "sql"], "BeginRead");
    let hydration_error = self.framework(&["interface"], "HydrationError");
    let acquire = self.framework(&["sqlx"], "Acquire");
    let capability = self.framework(&["interface"], "InterfaceKind");
    let query_error = self.framework(&["query", "sql"], "SqlQueryError");
    let crossing = self.framework(&["query", "sql"], "CrossingError");
    let (module, item) = kind.backend();
    let backend = self.framework(module, item);
    let executor = parameter("EXEC");
    let interface_name = interface.to_string();

    let arms = self.members.iter().map(|member| {
      let (variant, ty) = (&member.ident, &member.ty);
      let word = crate::union::word(&member.ident).to_string();
      let row = quote!(<#ty as #record<#backend>>::Row);
      let member_output = quote!(<<#ty as #transformer>::Graphql as #graphql>::Output);
      quote! {
        #vocabulary::#variant => {
          let mut __ingraph_asked = ::std::vec::Vec::with_capacity(<[#address]>::len(ids));
          for __ingraph_address in ids {
            match __ingraph_address {
              #address::#variant(__ingraph_id) => ::std::vec::Vec::push(
                &mut __ingraph_asked,
                ::core::clone::Clone::clone(__ingraph_id),
              ),
              // An address of ANOTHER member: refused rather than skipped, a skipped address being
              // a row that silently leaves the page.
              __ingraph_other => {
                let __ingraph_why = #hydration_error::Foreign {
                  interface: #interface_name,
                  asked: #word,
                  held: #capability::as_str(#address::kind(__ingraph_other)),
                };
                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
              }
            }
          }
          // Every refusal on this path is bound to a NAMED type before it is converted, which is
          // what makes the declared error's obligations legible: a cell that cannot absorb one of
          // the three is `E0277` here, naming which.
          let __ingraph_rows: ::std::vec::Vec<#row> =
            match #rows::<#row, #backend, #executor>(executor, &__ingraph_asked).await {
              ::core::result::Result::Ok(__ingraph_rows) => __ingraph_rows,
              ::core::result::Result::Err(__ingraph_why) => {
                let __ingraph_why: #query_error = __ingraph_why;
                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
              }
            };
          let mut __ingraph_found: ::std::vec::Vec<::core::option::Option<#output>> =
            ::std::vec::Vec::with_capacity(<[#address]>::len(ids));
          for _ in 0..<[#address]>::len(ids) {
            ::std::vec::Vec::push(&mut __ingraph_found, ::core::option::Option::None);
          }
          for __ingraph_row in __ingraph_rows {
            let __ingraph_id = match #sql_query::<#backend>::id(&__ingraph_row) {
              ::core::result::Result::Ok(__ingraph_id) => #address::#variant(__ingraph_id),
              ::core::result::Result::Err(__ingraph_why) => {
                let __ingraph_why: #crossing = __ingraph_why;
                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
              }
            };
            // A row whose address was never asked for cannot arrive — the membership binds exactly
            // the ids above — and it is ANSWERED rather than asserted, the engine being a seam.
            let ::core::option::Option::Some(__ingraph_at) =
              <[#address]>::iter(ids).position(|__ingraph_held| *__ingraph_held == __ingraph_id)
            else {
              continue;
            };
            let __ingraph_raised = match <#member_output as ::core::convert::TryFrom<#row>>::try_from(
              __ingraph_row,
            ) {
              ::core::result::Result::Ok(__ingraph_raised) => __ingraph_raised,
              ::core::result::Result::Err(__ingraph_why) => {
                let __ingraph_why:
                  <#member_output as ::core::convert::TryFrom<#row>>::Error = __ingraph_why;
                return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
              }
            };
            __ingraph_found[__ingraph_at] =
              ::core::option::Option::Some(#output::#variant(__ingraph_raised));
          }
          let __ingraph_missing = ::core::iter::Iterator::count(::core::iter::Iterator::filter(
            <[::core::option::Option<#output>]>::iter(&__ingraph_found),
            |__ingraph_slot| ::core::option::Option::is_none(*__ingraph_slot),
          ));
          if __ingraph_missing > 0 {
            let __ingraph_why = #hydration_error::Missing {
              interface: #interface_name,
              member: #word,
              missing: __ingraph_missing,
            };
            return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
          }
          ::core::result::Result::Ok(::core::iter::Iterator::collect(
            ::core::iter::Iterator::flatten(::std::vec::Vec::into_iter(__ingraph_found)),
          ))
        }
      }
    });

    let name = format_ident!("hydrate_{}", kind.as_str());
    let doc = leading(&format!(
      "Read `kind`'s member's rows at `ids` out of {what}, each as that member's own wire \
       object.\n\nThe answer is in the order `ids` were asked in, which for a page's caller is the \
       statement's — a gather answers in the engine's order and every row is asked for its own \
       address to be put back.\n\nHanded the same `&mut Transaction` the page ran on, this sees \
       exactly the rows that page answered with; handed a pool it opens a read of its own, and the \
       gap between the two moments is what the coherence refusal reports.",
      what = super::row::what(kind)
    ));
    let errors_doc = leading(&format!(
      "# Errors\n[`{error}`] — a driver refusal, a member's own row-to-wire crossing, an address of \
       another member, or rows the union answered with that this member's table no longer holds.",
      error = super::contract::tight(&error)
    ));
    quote! {
      impl #interface {
        #[doc = #doc]
        #[doc = ""]
        #[doc = #errors_doc]
        #vis async fn #name<'__ingraph_c, #executor>(
          kind: #vocabulary,
          ids: &[#address],
          executor: #executor,
        ) -> ::core::result::Result<::std::vec::Vec<#output>, #error>
        where
          #executor: #acquire<'__ingraph_c, Database = #backend> + #begin_read,
        {
          use #capability as _;
          match kind {
            #(#arms)*
          }
        }
      }
    }
  }
}