ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The SQL family's rows: SQLite, Postgres and MySQL.
//!
//! One CONCRETE type per declared database — `VideoTrackSqlite`, `VideoTrackPostgres` — rather than
//! a generic `Row<DB>`. A generic row was probed and works; the ruling is concrete, for three
//! reasons that all point the same way: a stored type may differ per backend, so the parameter
//! would have to carry the columns as well as the dialect; the derives differ per family; and a
//! compiler error that names `VideoTrackPostgres` says what went wrong, where one naming a
//! projection of a type parameter makes the reader do the substitution.
//!
//! What is family-specific lives here: the derive list, how a column's external name reaches the
//! field that holds it, and which [`DatabaseKind`]s the file answers for. The mechanical assembly —
//! the fields, the accessors, the conversions — is [`super::DatabaseBackend::row`]'s, and mongo's
//! file passes it different answers to the same questions.
//!
//! ## The `FromRow` impl is WRITTEN here, not derived
//!
//! A declaration that stores SQL rows needs `sqlx` nowhere in its own manifest: every sqlx name the
//! emission writes goes through the framework's `__private` shelf, exactly as mongo's serde derives
//! do. What it asks of a consumer instead is `ingraph` carrying the shelf item — feature `sqlx`, or
//! any SQL backend tier that implies it.
//!
//! Reaching it by shelving the DERIVE was tried and cannot work, and that is the derive vendor's
//! doing rather than a matter of effort. `sqlx_macros_core` 0.9's `derives::row` writes `::sqlx::`
//! ABSOLUTELY — nine distinct items over 38 occurrences: `Row`, `Result`, `FromRow`, `ColumnIndex`,
//! `decode::Decode`, `types::Type`, `types::Json`, `Error::ColumnDecode`, `Error::ColumnNotFound` —
//! and neither `SqlxContainerAttributes` (`transparent`, `type_name`, `rename_all`, `repr`,
//! `no_pg_array`, `default`) nor `SqlxChildAttributes` (`rename`, `default`, `flatten`, `try_from`,
//! `skip`, `json`) carries a crate-path key to redirect them. A leading `::` resolves against the
//! EXTERN PRELUDE, so no `use` and no shelf path can reach one: `#[derive(#krate::__private::sqlx::
//! FromRow)]` would have moved one resolution and left the other nine — and where the declarer's
//! sqlx did not unify with the framework's it would have been actively worse, one expansion naming
//! two different sqlx crates at once. serde's derive takes `#[serde(crate = "…")]` and binds its
//! whole expansion to it, which is why [`super::mongo`] can go on deriving.
//!
//! Writing the impl is what works, because the emitter already owns every column name and the
//! emission used exactly ONE sqlx attribute — `rename` — and none of
//! `flatten`/`json`/`try_from`/`default`/`skip`. That is what bounds the job: only SIX of the
//! derive's nine items are reachable without those attributes (`Json` needs `json`, and both `Error`
//! variants need `try_from` or `default`), and the decode reaches THREE of the six — `FromRow`,
//! `Row` and `Result`. `Decode`, `Type` and `ColumnIndex` moved behind the framework's own read
//! seam; see below.
//!
//! ## What it mirrors, and the three places it departs
//!
//! [`from_row`] keeps `sqlx_macros_core`'s named-struct SHAPE rather than inventing one: generic
//! over the ROW with its own `'a`, one read per field in column order, and the reads bound to a
//! `where` clause the caller discharges at a concrete dialect. Staying generic over the row is a
//! decision and not an inheritance: binding each row to its dialect's concrete `Row` would arguably
//! be more type-safe, and it would change what a consumer can write, so it is a separate question
//! from this one.
//!
//! The parameter is not SPELLED `R`, which is the one place the shape departs on purpose. A bare
//! `R` shadows a declaration's own type of that name, so a column declared `R` would be bounded and
//! decoded as the parameter — see [`super::parameter`], which every emitted parameter goes through.
//!
//! Error behaviour is INHERITED rather than reimplemented. `Row::try_get` is what produces
//! `ColumnNotFound` (from the `&str` index) and `ColumnDecode` (from an incompatible type or a
//! failed decode); the read seam forwards both unchanged, so nothing here constructs an error and a
//! caller sees the same variants the derive would have handed them.
//!
//! Three departures:
//!
//! - **A read is one per FIELD and not one per column**, and it goes through `ingraph`'s `Assemble`
//!   rather than through `try_get` directly. The derive's model is one column per field, which
//!   cannot read a field whose TYPE spans several: `tb: Timebase` occupies `tb_num` and `tb_den`,
//!   and neither name exists anywhere — both are joined while a statement is written, from the
//!   nested list `SqlQuery::COLUMNS` holds. So the read descends the same list, and the type that
//!   answers its own width is the type that reads its own columns back. The emission judges nothing
//!   about width here for the same reason it judges nothing in `COLUMNS`: `tb: Timebase` and
//!   `title: String` are the same tokens. One spelling per field, and the compiler selects.
//!
//!   The `Decode`/`Type` pair per column goes with it. What a field costs the `where` clause is one
//!   predicate — `Assemble<'a, Row>` — and what that predicate needs of the dialect is the seam's to
//!   state, which is what keeps a composite's own requirements out of an emission that cannot see
//!   them. `ColumnIndex` goes the same way: nothing in the body indexes a row any more.
//!
//! - An EDGE-STORED COLLECTION is not read at all. A collection kept in a second table has no
//!   column of this row to name, so the decode binds the EMPTY collection and the materialization
//!   pass fills it. That is the collapse the engine states — a parent with no elements and a parent
//!   absent from the gather are one answer — held here by what the decode writes rather than by a
//!   case anything tests for. Its predicate goes with it: a column that is never read needs none.
//!
//! - `from_row` carries no `#[inline]`, where every other emitted method carries one. That rule's
//!   stated reason is "a one-line cross-crate wrapper", which a decode of N columns is not — and
//!   sqlx does not inline its own either.
//!
//! ## What the change costs the row's fields
//!
//! `#[sqlx(rename = "…")]` is GONE from a SQL row, and not as a tidy-up: a helper attribute is only
//! legal where a derive on the same item registers it, so a row keeping the attribute without the
//! derive would not compile at all. The column's external name moves to the read that fetches it —
//! the same string in the same emission, so a reader of the expansion still sees each column's real
//! name, at the read rather than at the field.
//!
//! A `flatten` column is the one field with no name to write, which is the same fact its comparison
//! states by pushing no segment and its `COLUMNS` entry states by lending none: its type's segments
//! ARE the holder's columns. It reads through the seam's other entry point, and the two spellings
//! are one word apart exactly as the column list's are.

use quote::quote;

use super::{Family, Mapping};
use crate::model::{DatabaseBackend, DatabaseKind, RecordModel};

/// The SQL family's answers to the questions a row's emission asks — among them what the derives
/// need told at the container, which for a plain `Debug`/`Clone` pair is nothing.
pub(super) fn family() -> Family {
  Family {
    // NOT `Eq` and NOT `Hash`, which the key and lineage types both derive. A key's columns are
    // ids; a row's are whatever the record stores, and `f64` is neither `Eq` nor `Hash`. Deriving
    // them would make a perfectly ordinary column a compile error in generated code the author
    // cannot edit.
    //
    // AND NOT `PartialEq`, which stood here until the pattern column arrived and is now EMITTED
    // beside the row — see [`DatabaseBackend::equality`](super::DatabaseBackend::equality). That is
    // the sentence above read one trait earlier: `regex::Regex` implements no `PartialEq` and cannot
    // be given one anywhere but in `regex`'s own crate, so a pattern column was `E0369` raised
    // inside an expansion. Row equality is not dropped — the emitted impl folds each field's own
    // `ColumnEq` row, which is `==` for every type that has one, so every record compares exactly as
    // it did.
    derives: quote!(::core::fmt::Debug, ::core::clone::Clone),
    attrs: proc_macro2::TokenStream::new(),
    // Nothing to route: this family's derives ask a field type for `Debug` and `Clone`, which every
    // storage type carries, and its decode is emitted rather than derived.
    via: None,
    mapping: Mapping::Decode(from_row),
    what: |kind| match kind {
      DatabaseKind::Sqlite => "SQLite",
      DatabaseKind::Postgres => "PostgreSQL",
      DatabaseKind::Mysql => "MySQL",
      DatabaseKind::Mongo => "MongoDB",
    },
    noun: "row",
  }
}

/// The `FromRow` impl `#[derive(sqlx::FromRow)]` would have written, emitted so that every sqlx name
/// in it can go through the shelf — see the module doc for why the derive could not, and for what
/// the read seam changed about its shape.
///
/// Every read is under the column's EXTERNAL name, which is what makes the decode name-addressed
/// rather than positional: a `SELECT` may hand the columns back in any order, and two columns of one
/// type are a transposition waiting to happen if position decides. A composite's segments are named
/// UNDER that one, by the walk rather than by anything written here.
fn from_row(database: &DatabaseBackend, model: &RecordModel) -> proc_macro2::TokenStream {
  let row = database.name();
  let from_row = model.framework(&["sqlx"], "FromRow");
  let row_trait = model.framework(&["sqlx"], "Row");
  let result = model.framework(&["sqlx"], "Result");
  let assemble = model.framework(&["column"], "Assemble");
  let assembled = model.framework(&["column"], "assembled");
  let assembled_flattened = model.framework(&["column"], "assembled_flattened");
  let field_name = model.framework(&["field"], "FieldName");

  // The row parameter is NAMED rather than spelled `R`, for the reason every emitted parameter is:
  // a bare one shadows a declaration's own type of that name inside this impl, and a column
  // declared `R` would then bound and decode the parameter instead of itself. See
  // [`super::parameter`].
  let row_parameter = super::parameter("ROW");

  // ONE predicate per column, in column order. What the read needs of the DIALECT — a `Decode`, a
  // `Type`, an index — is the seam's own to ask for, which is what lets a composite state
  // requirements this emission cannot see: `tb: Timebase` and `title: String` are the same tokens.
  let bounds = database
    .columns()
    .iter()
    .filter(|column| !database.edge_stored(model, column))
    .map(|column| {
      // The FIELD's type and not the declared one, because they differ for a collection the row
      // holds: `type` names one element and the field holds the list of them, and it is the list
      // that crosses the driver — a Postgres `text[]` decodes as `Vec<String>`.
      let ty = database.row_field(model, column);
      quote!(#ty: #assemble<'a, #row_parameter>)
    });
  let reads = database.columns().iter().map(|column| {
    let field = column.name.safe();
    // The CONDITION on the `let`, which is a statement and therefore an attribute position — so a
    // column the build removed is a value this body never reads and never binds.
    let gate = model.gate(&column.source);
    // An edge-stored collection has NO column here to read. Its elements are rows of a second
    // table, and what a decode can honestly give it is the EMPTY collection: materialization only
    // ever appends, so the empty one is what a parent with no elements keeps — the collapse the
    // engine's `distribute` holds by the shape of its loop rather than by a branch.
    if database.edge_stored(model, column) {
      return quote!(#gate let #field = ::std::vec::Vec::new(););
    }
    let ty = database.row_field(model, column);
    // The annotation is load-bearing: it is what fixes which `Assemble` row runs — so it is the
    // FIELD's type, which for a collection riding the row is the list.
    //
    // A `flatten` column lends NO name, so its type's segments are read in the holder's own
    // namespace: `num` and `den` where the same field unmarked reads `tb_num` and `tb_den`. The two
    // spellings are one word apart here exactly as they are in `SqlQuery::COLUMNS`.
    if column.flatten {
      return quote!(
        #gate
        let #field: #ty = #assembled_flattened(__row, ::core::option::Option::None)?;
      );
    }
    // Through `external` rather than off the column, so BOTH families read one authority on what a
    // stored name is. It answers the column's own name for every SQL row and always will — the one
    // row that differs is MongoDB's id — and routing this through it is what keeps the two backends
    // from having two ideas about where an external name comes from.
    let external = database.external(model, column);
    quote! {
      #gate
      let #field: #ty =
        #assembled(__row, #field_name::new(#external), ::core::option::Option::None)?;
    }
  });
  let fields = database.columns().iter().map(|column| {
    let (gate, field) = (model.gate(&column.source), column.name.safe());
    quote!(#gate #field,)
  });

  let doc = super::leading(&format!(
    "Read a [`{row}`] back out of a database row, each field under its own name — and a field whose \
     type spans several columns out of every one of them."
  ));
  quote! {
    #[automatically_derived]
    impl<'a, #row_parameter: #row_trait> #from_row<'a, #row_parameter> for #row
    where
      #(#bounds,)*
    {
      #[doc = #doc]
      fn from_row(__row: &'a #row_parameter) -> #result<Self> {
        #(#reads)*
        ::core::result::Result::Ok(Self { #(#fields)* })
      }
    }
  }
}