ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The ORDER a client may write over an interface, and the entry point that spends it.
//!
//! # The terms are the SHARED columns, and that is the whole vocabulary
//!
//! A union projects the interface's own names, so a client ordering one has no member to name a
//! column of: what it may write is exactly what the contract promised. A member's private column is
//! unorderable here — not by a refusal, but because the interface never said every member had it,
//! and a total order over a column some arm cannot project is not a statement.
//!
//! # There is ONE spelling, where a record has one per database
//!
//! A record's order-by renders a per-database term, because a `persist(<db>(rename = "…"))` moves
//! the column a dialect sorts by. An interface's arms have ALREADY aliased every member's column to
//! the interface's own name, so what the `ORDER BY` names is that name in every database — one
//! `term`, no dialect in it, and no per-database method to keep in step.
//!
//! # The COMPUTED tier is absent, and its absence is the design
//!
//! A computed field is derived from a member's wire output; a statement sorts by a column. So the
//! terms are the STORED tier, and a declaration whose fields are all computed has an order-by with
//! no variants — which is the honest shape: its page is the tail alone.
//!
//! # A COLLECTION is a term, and every term over one carries `TermSubject::Edge`
//!
//! The record side opened this axis: a collection is orderable, and the meaning is PostgreSQL's own
//! element-by-element rule, which `ingraph`'s `query::compare_collections` states once. So a
//! collection field is a variant here at parity with a record's — the vocabulary opens on both sides
//! or a client writes one order against a record and cannot write it against the interface over the
//! same rows.
//!
//! What the term carries is the SUBJECT, and here there is only one answer to give. A record's term
//! is minted per database and asks `edge_stored`, which is the one authority on where THAT record
//! keeps THAT column. An interface has no such authority to ask: the storage form is the MEMBER's,
//! per element type and per dialect, and the derives cannot see each other — so an interface could
//! not name an array even where every member happens to keep one. Nor would it want to. The row
//! being ordered here is the UNION's derived table, and no arm selects a collection at all
//! ([`InterfaceModel::projected`](crate::interface::InterfaceModel::projected)), so *this collection
//! is kept in a table of its own and the row being ordered has no column for it* — the sentence
//! `Unpushable::CollectionTable` carries — is literally true of every backend here rather than
//! true of some.
//!
//! **The consequence is the degrade law's two rows, met by a lane that has only one.** An
//! interface's every lane is a PAGE — its order completes with `(…, __ig_kind__, id)`, which is what
//! makes a row of several tables addressable — so the law's first row, *cursorless, complete the
//! remainder in memory*, has no lane here to run in, and the second row is the whole of what a
//! collection term meets: `OrderPartition::paging` refuses before a row is read, and
//! `SqlQueryError::PageOrder` names the term and the cause. Which is exactly the record's own
//! answer to a PAGE over a collection — refused there too, on the backend that orders arrays
//! natively as much as on the ones that do not, because a cursor's slot is one stored value.
//!
//! So no cursor slot is invented for one, and none could be: `<I><Db>Cursor`'s variants are
//! `projected()` too.
//!
//! # …and the `sortable` word does not reach here either, which is why a PIN refuses it
//!
//! A record may ask for an ORDER-PRESERVING COMPANION COLUMN and take its collection order out of
//! the remainder. An interface cannot, and it is the same absence one step further along: a
//! companion is a column of ONE member's table, minted where that member's declaration is read, and
//! the union's derived table selects no such column from any arm. Projecting one would be a widening
//! of `projected()` on both the SELECT list and the cursor sum, which is the phase this framework
//! has not built.
//!
//! So a pin carrying the word is refused at the declaration, by name, with what it is waiting on —
//! `ingraph-derive`'s interface grammar is where, inside the pin's own `persist(…)`, the seat the
//! word took on a record — rather than accepted and silently meaning nothing. `TermSubject::Edge` stays the only answer this side gives.

use quote::quote;

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

impl InterfaceModel {
  /// `<I>OrderBy` — one term as a type, and the entry point per database.
  ///
  /// It writes NO binding of its own. The tie used to be an `Orderable` impl on the interface; that
  /// trait is retired, and what it bound was already bound one file over — `InterfaceModel::queries`
  /// writes `impl GraphqlInput for <I>GraphqlInput { type OrderBy = <I>OrderBy; }`, which is the
  /// wire face's own member and the one a client's order is reached through. The retirement
  /// therefore removed a duplicate rather than a seat.
  ///
  /// The ENUM and its `direction` are [`unit::order_by`](crate::unit::order_by)'s, shared with a
  /// record's order-by and a standalone `#[derive(ingraph::OrderBy)]`: one variant per orderable
  /// column, each CARRYING its direction, and the one question every term answers whatever a
  /// database does with it. What an interface supplies is the rows and their nouns — a SHARED
  /// column, or a shared COLLECTION and the paragraph saying what a page over one meets — and
  /// `term`, which is its own addition rather than a copy of anything.
  pub(crate) fn ordering(&self) -> proc_macro2::TokenStream {
    if !self.projects() {
      return quote!();
    }
    let vis = &self.vis;
    let interface = &self.name;
    let name = super::default_order_by_name(interface);
    let direction_ty = self.framework(&["graphql"], "OrderDirection");
    let order_term = self.framework(&["cursor"], "OrderTerm");
    let term_name = self.framework(&["cursor"], "TermName");
    let field_name = self.framework(&["field"], "FieldName");

    let stored: Vec<&InterfaceField> = self.stored().collect();
    let rows: Vec<unit::OrderColumn> = stored.iter().map(|field| order_row(field)).collect();
    let header = unit::UnitHeader {
      vis,
      name: name.clone(),
      subject: format!("[`{interface}`]"),
      note: Some(
        "The columns are the INTERFACE's own vocabulary and never a member's: a union projects the \
         interface's names, so those are the names a client may sort by. There is one rendering \
         whatever database answers, because every arm has already aliased its member's column to \
         the name this term carries."
          .to_owned(),
      ),
    };
    let (declaration, direction) = unit::order_by(&header, &direction_ty, &rows);

    // The TERM is the interface's own addition, where the enum above it is the unit's. WHICH
    // constructor its SUBJECT takes has one answer rather than a fork: no arm of the union selects
    // a collection, so the row being ordered has no column for one on any backend. See this
    // module's note — a record asks `edge_stored`, and an interface has no such authority to ask
    // and no array to name if it had.
    //
    // The variant is read off the unit's own ROW rather than derived a second time here, so an arm
    // and the variant it is written for cannot come to name different columns.
    let terms = stored.iter().zip(&rows).map(|(field, row)| {
      let variant = &row.variant;
      let external = field.name.to_string();
      let build = if field.collects() {
        quote!(#order_term::edge)
      } else {
        quote!(#order_term::new)
      };
      quote! {
        Self::#variant(__ingraph_direction) =>
          #build(#term_name::new(#external), #field_name::new(#external), __ingraph_direction),
      }
    });
    let term_doc = leading(
      "This term as a statement renders it: its rename-proof identity, the column the union \
       projects it under, and the direction. The identity and the column are ONE name here — an \
       interface's promise is the name, and no `persist(…)` can move it.",
    );
    let entries = self
      .sql_databases()
      .into_iter()
      .map(|kind| self.entry_point(kind, &name));

    // The SUBJECT PATH — what `Orderings`'s decode keys a client's written order on, so no two terms
    // of one document can name one column. The unit's own walk, over the same rows the variants were
    // built from, so a variant and the subject it names cannot drift.
    //
    // GATED ON NOTHING, which is `ToSubjectPath`'s own arrangement: generated code lives in the
    // DECLARING crate and cannot spell a feature of this one, so a trait an expansion names has to
    // exist in every build of it. It arrives with B-27 because the wire ORDER argument is what
    // spends it, and an interface had no root field to take one until now.
    let to_subject_path = self.framework(&["graphql"], "ToSubjectPath");
    let subject_path = self.framework(&["graphql"], "SubjectPath");
    let subject =
      unit::order_subject_path(&name, &to_subject_path, &subject_path, &term_name, &rows);

    quote! {
      #declaration

      #subject

      impl #name {
        #direction

        #[doc = #term_doc]
        #[inline]
        #[must_use]
        #vis const fn term(self) -> #order_term {
          match self {
            #(#terms)*
          }
        }
      }

      const _: () = {
        #(#entries)*
      };
    }
  }

  /// `<I>::find_<db>` — the typed face, one per SQL database and behind that database's gate.
  ///
  /// # It fixes the DATABASE, where a record's entry point fixes the ROW
  ///
  /// A record's `find_sqlite` names its own SQLite row and leaves the dialect open, because an
  /// expansion may not spell `sqlx::Sqlite` ungated. An interface's engine face names a CONCRETE
  /// backend already — its projection is per database, so its binding must — so the entry point does
  /// the same and rides the same gate.
  ///
  /// # There is no snapshot twin, and no flag
  ///
  /// An interface's call is bracketed ALWAYS, so the choice a record's `find_<db>_snapshot` offers
  /// does not exist here — see `InterfacePaging::fetch` for the transaction law, and `BeginRead` for
  /// what a caller's own transaction does to it.
  fn entry_point(&self, kind: DatabaseKind, order_by: &syn::Ident) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let interface = &self.name;
    let find = self.framework(&["query", "sql"], "InterfaceFind");
    let begin_read = self.framework(&["query", "sql"], "BeginRead");
    let acquire = self.framework(&["sqlx"], "Acquire");
    let gate = self.framework(&["gate"], &kind.gate().to_string());
    let (module, item) = kind.backend();
    let backend = self.framework(module, item);
    let name = kind.finder();
    let executor = crate::emit::parameter("EXEC");

    let doc = leading(&format!(
      "Page the [`{interface}`]s stored in {what} — every member's rows in ONE order, resumable \
       across the members.\n\nThe order is written as [`{order_by}`] terms and completed with the \
       tail that makes it total; the page is bracketed in this dialect's read transaction, or \
       passes through the one the surface already holds.",
      what = super::row::what(kind)
    ));
    quote! {
      #gate! {
        impl #interface {
          #[doc = #doc]
          #[inline]
          #vis fn #name<'__ingraph_a, '__ingraph_c, #executor>(
            executor: #executor,
          ) -> #find<'__ingraph_a, Self, #backend, #executor>
          where
            #executor: #acquire<'__ingraph_c, Database = #backend> + #begin_read,
          {
            #find::new(executor)
          }
        }
      }
    }
  }
}

/// ONE shared column, as the order-by unit reads it: the variant and the identity it derives, plus
/// the nouns this side of the framework owns.
///
/// A COLLECTION says so in its noun and carries the paragraph a page over it meets. The variant is
/// no longer computed here — [`unit::OrderColumn::of`] is the one place a member becomes a variant,
/// which is what the collapse onto the unit bought.
fn order_row(field: &InterfaceField) -> unit::OrderColumn {
  let name = &field.name;
  if !field.collects() {
    return unit::OrderColumn::of(name, format!("shared `{name}` column"));
  }
  unit::OrderColumn::of(name, format!("shared `{name}` collection")).with_note(
    "The order over a collection is element by element, shorter-is-less on a prefix, which is \
     `ingraph`'s one meaning for a collection's order. A PAGE over this term is refused before a \
     row is read: the union projects no column for a collection, so the term's subject is \
     `TermSubject::Edge` and the degrade law's second row answers it."
      .to_owned(),
  )
}