ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! THE SHIPPED PROVIDER: the id-gather lane as a [`AsyncBatchLoad`].
//!
//! # There is no new engine here, and that is the whole point
//!
//! `#222`'s L-5 recorded the batch as *proved and hostless*: `query::sql::rows` already takes a
//! SLICE of ids and answers them in ONE statement, and has since the interface hydration needed it.
//! What was missing was a seam to reach it from. So this file is the adapter and not the lane —
//! every line of statement rendering, binding and decoding is the one the per-row lane runs, asked
//! for `k` keys instead of one.
//!
//! # It reads through the DOOR, not around it
//!
//! [`SqlDoor`] rather than a `Pool`, and that is a correctness property rather than convenience: an
//! application's own [`SqlSource`](super::super::SqlSource) may route by tenant, hold the pool
//! inside a larger handle, or count reaches. A loader that took the pool directly would be the one
//! read path in the framework that bypassed the seam an application answered — and it would be
//! invisible, since it answers the same rows. `ingraph/tests/wire_batched.rs` measures the batch
//! through exactly that seam, which it can only do because this file spends it.
//!
//! # Lining the answer back up
//!
//! A gather over `k` ids answers in whatever sequence the plan chose, so each row is asked for its
//! OWN id — [`SqlQuery::id`], the dual of the `addresses` this statement was built from, so a
//! declaration that converts or renames its id moves both ends at once. Absent keys simply do not
//! appear, which is the seam's own contract.

use core::marker::PhantomData;

use super::{AsyncBatchLoad, BatchError};
use crate::{
  graphql::SqlDoor,
  query::sql::{SqlQuery, rows},
  transform::Identifiable,
};

/// The SHIPPED [`AsyncBatchLoad`]: `k` ids of one table, in one statement, through a read door.
///
/// # Two parameters, and they are the two the emission already knows
///
/// `Row` names the record AND the database — a row type is minted per record per declared backend —
/// so the pair `(Row, Db)` is exactly the granularity a batch has. It is the same pair
/// [`BatchDoor`](super::BatchDoor) is keyed on one layer out, which is what lets an application
/// install this without naming a type the emission would have to agree with by hand.
///
/// `Row` is held as [`PhantomData<fn() -> Row>`](PhantomData) rather than `PhantomData<Row>`, the
/// spelling every marker in this crate uses: the parameter contributes neither an auto-trait nor a
/// variance obligation, so a row that is not [`Send`] does not make the loader un-`Send` on paper
/// when the loader holds no row at all.
pub struct SqlRows<Row, Db>
where
  Db: sqlx::Database,
{
  door: SqlDoor<Db>,
  row: PhantomData<fn() -> Row>,
}

impl<Row, Db> SqlRows<Row, Db>
where
  Db: sqlx::Database,
{
  /// A loader reading through `door`.
  ///
  /// The door is [`Clone`] and cheap, so the per-request idiom the module note recommends clones
  /// one the application already holds rather than opening anything.
  #[must_use]
  #[inline]
  pub const fn new(door: SqlDoor<Db>) -> Self {
    Self {
      door,
      row: PhantomData,
    }
  }

  /// The door this loader reads through.
  #[must_use]
  #[inline]
  pub const fn door(&self) -> &SqlDoor<Db> {
    &self.door
  }
}

/// Written out rather than derived, for [`SqlDoor`]'s own reason: a derive would bound `Row: Clone`
/// and `Db: Clone`, and neither is ever a value here.
impl<Row, Db> Clone for SqlRows<Row, Db>
where
  Db: sqlx::Database,
{
  #[inline]
  fn clone(&self) -> Self {
    Self {
      door: self.door.clone(),
      row: PhantomData,
    }
  }
}

impl<Row, Db> core::fmt::Debug for SqlRows<Row, Db>
where
  Db: sqlx::Database,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlRows")
      .field("row", &core::any::type_name::<Row>())
      .field("door", &self.door)
      .finish()
  }
}

impl<Row, Db> AsyncBatchLoad<<Row::Record as Identifiable>::Id> for SqlRows<Row, Db>
where
  Row: SqlQuery<Db> + for<'r> sqlx::FromRow<'r, Db::Row> + Send + Sync,
  Db: crate::query::sql::SqlDialect,
  Db::Arguments: sqlx::IntoArguments<Db>,
  for<'e> &'e mut Db::Connection: sqlx::Executor<'e, Database = Db>,
  for<'p> &'p sqlx::Pool<Db>: crate::query::sql::BeginRead,
  <Row::Record as Identifiable>::Id: Send + Sync,
{
  type Value = Row;

  #[allow(
    clippy::manual_async_fn,
    reason = "the seam declares `+ Send` and an `async fn`'s future does not prove it from outside \
              — the engine spawns this one"
  )]
  fn load(
    &self,
    keys: &[<Row::Record as Identifiable>::Id],
  ) -> impl core::future::Future<
    Output = Result<Vec<(<Row::Record as Identifiable>::Id, Row)>, BatchError>,
  > + Send {
    async move {
      // ONE reach through the source, for the whole batch. This is the call
      // `ingraph/tests/wire_batched.rs` counts, and it is why that file's number is one where
      // `wire_batching.rs`'s is three.
      let gathered = rows::<Row, Db, _>(self.door.pool(), keys)
        .await
        .map_err(BatchError::new)?;
      gathered
        .into_iter()
        .map(|row| {
          // The row says which id it IS — the dual read, so an id the declaration converts is
          // converted back by the declaration's own converter. A refusal here is the crossing's
          // and takes the crossing's word, through the engine lane's own error.
          let id = row
            .id()
            .map_err(|refusal| BatchError::new(crate::query::sql::SqlQueryError::from(refusal)))?;
          Ok((id, row))
        })
        .collect()
    }
  }
}