ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! MongoDB's document.
//!
//! The same assembly as the SQL family's, with three answers changed: the derives are serde's, the
//! column name rides on `#[serde(rename = "…")]`, and the emitted type is a DOCUMENT rather than a
//! row.
//!
//! No dialect parameter, and nothing shaped like one. MongoDB has no dialects — one driver, one
//! wire format, one collection vocabulary — so where the SQL family answers for three databases
//! this file answers for one. That is why the two are separate files rather than one with a switch
//! inside: the switch would be over a distinction only one side has.
//!
//! ## serde is reached through the `__private` shelf, in TWO halves
//!
//! A declaration that stores mongo documents needs serde nowhere in its own manifest: the derives
//! are `#krate::__private::serde::{Serialize, Deserialize}`, the framework's re-export of the crate
//! itself. What it asks of a consumer instead is `ingraph` carrying the shelf item — feature
//! `serde`, or the `mongodb`/`config` tiers that imply it.
//!
//! Both halves are load-bearing, and the first alone LOOKS done:
//!
//! 1. the derive path, which resolves the macro; and
//! 2. `#[serde(crate = "…::__private::serde")]`, which tells serde's OWN expansion where serde is.
//!    Without it the macro resolves and the code it writes still opens with `extern crate serde as
//!    _serde` — so a consumer without serde as a direct dependency still fails to compile, inside a
//!    generated item they cannot edit.
//!
//! The pair works because serde's derive takes a crate-path override at all (`serde_derive`'s
//! `internals::attr` parses `CRATE` into `custom_serde_path`, and `dummy::wrap_in_const` spends it
//! as `use <path> as _serde;`). `sqlx::FromRow` takes none, which is why the SQL family cannot
//! derive at all and emits its `FromRow` impl instead — see [`super::sql`]. Both families reach the
//! shelf; only this one gets there through a derive.
//!
//! The path is the DECLARER's: `#[ingraph(crate = "…")]` retargets it like every other shelf
//! reference, the string literal included.

use quote::quote;

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

/// MongoDB's answers to the four questions a row's emission asks.
pub(super) fn family(model: &RecordModel) -> Family {
  let serialize = model.framework(&["serde"], "Serialize");
  let deserialize = model.framework(&["serde"], "Deserialize");
  let serde = model.vendored("serde");
  // `#[serde(with = "…")]` takes a STRING, and serde parses it as a path and appends `::serialize`
  // and `::deserialize` — so what is built here is the shelf path spelled out, exactly as
  // `vendored` builds `crate = "…"`'s. The declarer's own `#[ingraph(crate = "…")]` retargets it
  // like every other reference; the string literal is why the token walk cannot see it, and why the
  // retargeting is pinned by a test of its own rather than by that walk.
  let via = model
    .framework(&["query", "mongo"], "via")
    .to_string()
    .replace(' ', "");
  Family {
    // `Eq`/`Hash` are absent for the reason they are absent from a SQL row — see `sql::family`, and
    // `PartialEq` has left this list for that file's second reason, the emitted fold standing in its
    // place on both families at once.
    //
    // `Deserialize` is STILL derived and is no longer what reads a queried document — see
    // [`from_document`]. It stays because it is the inverse of `Serialize` for anything that is not
    // this framework's read lane: a fixture written as extended JSON, a `bson::from_document` in a
    // consumer's own migration, a test that round-trips a document. Removing it would take a
    // capability away to make a point about which decode the engine uses.
    //
    // What CHANGED under the pair is what they ask of a field type. A derive demands `Serialize` and
    // `Deserialize` of every declared field type, which `regex::Regex` carries neither of and cannot
    // be given here — so the pair now crosses `via` below, and the demand becomes the two document
    // tables the field type already owed.
    derives: quote!(
      ::core::fmt::Debug,
      ::core::clone::Clone,
      #serialize,
      #deserialize
    ),
    attrs: quote!(#[serde(crate = #serde)]),
    // THE THIRD HALF of reaching serde through the shelf, after the derive path and `crate = "…"`:
    // where each FIELD crosses. It is `query::mongo::via`, whose two functions answer through
    // `MongoCarrier` and `MongoExtract` — the same tables `MongoWrite::document` and `from_document`
    // have always used — so the derived pair and the framework's own write can no longer disagree
    // about a document, and a field type owes serde nothing.
    via: Some(via),
    mapping: Mapping::AttributeAndDecode("serde", from_document),
    what: |_| "MongoDB",
    noun: "document",
  }
}

/// The EXTRACTION: a document's fields read back into the row, one at a time, under the names this
/// database spells them.
///
/// # It is the `FromRow` discipline's bson twin, and the reason it is emitted at all is the CELL
///
/// serde's derive can be shelved — [`family`] above still derives the pair — so the obvious answer
/// was `#[derive(Deserialize)]` plus `#[serde(deserialize_with = "…")]` for a declaration's own
/// conversions. It was measured and refused, and the measurement is about
/// `serde::de::Error::custom`: it takes a `Display` and hands back the FORMAT's error, so a
/// declared refusal reaches a caller as a `bson::de::Error` carrying a string, and the
/// `mongo(try_into(error = "…"))` cell holds nothing at all. This framework's standing
/// rule is that a declared error type is the one a caller matches on, and a decode that flattens
/// every refusal into a string is a decode that cannot keep it.
///
/// # An INHERENT method, where the SQL family writes a trait impl
///
/// `FromRow` is sqlx's, so emitting an impl of it binds a VENDORED trait and the era rule does not
/// reach it. The bson twin is the FRAMEWORK's, and the framework's trait layer is what that rule
/// exists over — so what lands here is an inherent `from_document`, which binds nothing, and the
/// engine binding that DELEGATES to it arrives with the rest of the query face.
///
/// # What it does NOT do, and where that work is
///
/// It applies no declared conversion. The row's fields are the STORED types, so a column's
/// `into`/`try_into` legs run in the `TryFrom<Row> for Record` beside it — which is where
/// [`DatabaseBackend::conversions`](super::DatabaseBackend::conversions) already puts them, through
/// the one `Conversion` authority, `error_with` escapes included. That is the same split
/// `from_row` makes: the decode reads the format and the crossing spends the declaration.
///
/// # The error is the FORMAT's, and it is `sqlx::Error`'s position
///
/// `from_row` answers with the driver's error and `SqlQuery::record` answers with the declared
/// cell — two homes, one each. This mirrors it: the extraction answers with `MongoExtractionError`,
/// which names the FIELD on every failure, and the crossing beside it answers with whatever the
/// declaration named. A caller who wants one type gets it at the engine seam, where both are boxed.
///
/// # It rides the GATE, and it is the second item that does
///
/// Every name it writes — `bson::Document`, the extraction and its refusal — exists only in a build
/// that compiled the MongoDB backend in, so an ungated one would make a declaration naming MongoDB
/// fail to compile wherever the feature is off. That is exactly the invariant the gate exists to
/// hold, and the storability audit beside it already rides the same one.
///
/// The SQL family's decode does not, and the asymmetry is a fact about the two SHELVES rather than a
/// decision here: `__private::sqlx` is gated on the family root, so a `FromRow` impl is already
/// unreachable without it and gating it would change nothing. Closing that is its own change.
fn from_document(database: &DatabaseBackend, model: &RecordModel) -> proc_macro2::TokenStream {
  // The predicate is `extracts` rather than a test written out here, because the method ENUMERATION
  // asks the same question and two spellings would be a name claimed in one place and not the other.
  // It is now the family alone: a flattened column used to take the extraction away, and a document
  // nests a held value under this field's key rather than flattening it.
  if !database.extracts() {
    return proc_macro2::TokenStream::new();
  }
  let row = database.name();
  let vis = &model.vis;
  let gate = model.framework(&["gate"], &database.kind().gate().to_string());
  let document = model.framework(&["bson"], "Document");
  let refusal = model.framework(&["query", "mongo"], "MongoExtractionError");
  let field = model.framework(&["query", "mongo"], "field");

  let reads = database.columns().iter().map(|column| {
    let name = column.name.safe();
    // The FIELD's type, which is what fixes the extraction's `T` and therefore which row of the
    // decode table runs — an `Option<…>` field is what makes a missing key an answer rather than a
    // refusal, and it is the declaration that decided the field is optional.
    let ty = database.row_field(model, column);
    let external = database.external(model, column);
    // The CONDITION, on the struct-expression field: a document holds a key for a field this build
    // declares and for no other. Named `condition` rather than `gate` because `gate` is the
    // FEATURE-gate macro this emission already writes with.
    let condition = model.gate(&column.source);
    quote!(#condition #name: #field::<#ty>(__ingraph_document, #external)?,)
  });

  let doc = super::leading(&format!(
    "Read a [`{row}`] back out of a queried document, each field under the key this database \
     spells it — which is `_id` for the record's own id."
  ));
  quote! {
    #gate! {
      impl #row {
        #[doc = #doc]
        #vis fn from_document(
          __ingraph_document: &#document,
        ) -> ::core::result::Result<Self, #refusal> {
          ::core::result::Result::Ok(Self { #(#reads)* })
        }
      }
    }
  }
}