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 SQL gather, live: what one composed statement answers, in what order, and the one thing
//! about it that renders as valid SQL either way.

#![cfg(feature = "sqlite")]

use sqlx::{Connection as _, Sqlite};

use super::SqlGather;
use crate::{
  Carrier, ColumnName, ColumnShape, ComplexComparison, FieldName, Identifiable, Record,
  RecordAddress, ScalarFilter, Transformer,
  comparison::{
    At, Backend, Frame, TryFromFilter,
    sql::{SqlKeyIn, SqlLoweringError, SqlScalarComparison},
  },
  query::sql::{CrossingError, SqlQuery},
  retrieve::AsyncGather,
};

/// A shot inside a reel, addressed by BOTH columns — the compound-`Id` layout the framework does
/// not emit and the seam stays open to.
///
/// It is the fixture the cartesian pin needs: an address of one column cannot express the defect,
/// because there is no second column for a per-column `IN` to cross with.
#[derive(Debug, Clone, PartialEq)]
struct Shot {
  /// The composite address held as ONE value, so the record can lend it — which is what
  /// `Identifiable::id_ref` asks of a layout whose address is two columns.
  id: ShotId,
  slate: String,
}

/// The composite address. `Identifiable::Id` is unbounded on purpose, and a physical layout named by
/// two columns states that here.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ShotId {
  reel: i64,
  ordinal: i64,
}

impl Identifiable for Shot {
  type Id = ShotId;

  fn id_ref(&self) -> &ShotId {
    &self.id
  }
}

/// The KEY, which is what a retrieve deduped and what the gather crosses into an address.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ShotKey(ShotId);

impl Identifiable for ShotKey {
  type Id = ShotId;

  fn id_ref(&self) -> &ShotId {
    &self.0
  }
}

fn shot_key(reel: i64, ordinal: i64) -> ShotKey {
  ShotKey(ShotId { reel, ordinal })
}

impl Transformer for Shot {
  type Key = ShotKey;
  type Lineage = i64;
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> ShotKey {
    ShotKey(self.id.clone())
  }
}

#[derive(Debug, Clone, PartialEq)]
struct ShotRow {
  reel: i64,
  ordinal: i64,
  slate: String,
}

impl<'r, R> sqlx::FromRow<'r, R> for ShotRow
where
  R: sqlx::Row,
  i64: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  String: sqlx::Decode<'r, R::Database> + sqlx::Type<R::Database>,
  for<'a> &'a str: sqlx::ColumnIndex<R>,
{
  fn from_row(row: &'r R) -> Result<Self, sqlx::Error> {
    Ok(Self {
      reel: row.try_get("reel_id")?,
      ordinal: row.try_get("ordinal")?,
      slate: row.try_get("slate")?,
    })
  }
}

struct ShotFilter<Db> {
  slate: SqlScalarComparison<String, Db>,
}

impl<Db> ComplexComparison<Db> for ShotFilter<Db>
where
  Db: Backend<Error = SqlLoweringError>,
  SqlScalarComparison<String, Db>: ComplexComparison<Db>,
{
  fn conjuncts(&self) -> usize {
    ComplexComparison::<Db>::conjuncts(&self.slate)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    builder: <Db as Backend>::Builder<'q>,
  ) -> Result<<Db as Backend>::Builder<'q>, <Db as Backend>::Error> {
    let frame = At::frame(at, FieldName::new("slate"));
    ComplexComparison::<Db>::apply(&self.slate, Frame::at(&frame), builder)
  }
}

fn slated(slate: &str) -> ShotFilter<Sqlite> {
  ShotFilter {
    slate: SqlScalarComparison::try_from_filter(
      ScalarFilter::<std::string::String>::new().with_eq(slate.to_owned()),
    )
    .expect("a text equality crosses into SQLite"),
  }
}

impl<Db> Record<Db> for Shot
where
  Db: Backend,
  ShotFilter<Db>: ComplexComparison<Db>,
{
  type Row = ShotRow;
  type Comparison = ShotFilter<Db>;
  type OrderBy = ();
}

impl<Db> SqlQuery<Db> for ShotRow
where
  Db: Backend + sqlx::Database,
  ShotFilter<Db>: ComplexComparison<Db>,
  SqlKeyIn<i64, Db, 2>: ComplexComparison<Db>,
  i64: Carrier<Db>,
  for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'r> String: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
  for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
{
  type Record = Shot;
  /// WIDTH TWO — the row-value membership over a compound address.
  type Address = SqlKeyIn<i64, Db, 2>;

  const ADDRESS: RecordAddress = RecordAddress::new(
    FieldName::new("shot"),
    &[FieldName::new("reel_id"), FieldName::new("ordinal")],
  );
  const ALIASES: &'static [&'static str] = &["__ig_shot_0__", "__ig_shot_1__"];
  const COLUMNS: &'static [ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("reel_id")),
    ColumnShape::Plain(ColumnName::new("ordinal")),
    ColumnShape::Plain(ColumnName::new("slate")),
  ];

  /// The ROW-VALUE spelling: `("reel_id", "ordinal") IN ((?, ?), (?, ?))`.
  ///
  /// **The mutation this line is the pin for** is replacing it with a per-column membership —
  /// `"reel_id" IN (?, ?) AND "ordinal" IN (?, ?)`. That renders, binds the same four operands, and
  /// answers the CARTESIAN PRODUCT. See
  /// [`SqlKeyIn`](crate::comparison::sql::SqlKeyIn), which exists as a type so the two spellings
  /// cannot be confused, and `a_compound_key_gather_is_not_the_cartesian_product` below, which is
  /// what goes red.
  fn addresses(ids: &[ShotId]) -> Result<Self::Address, CrossingError> {
    Ok(SqlKeyIn::new(
      ["reel_id", "ordinal"],
      ids
        .iter()
        .map(|id| [id.reel, id.ordinal])
        .collect::<Vec<_>>(),
    ))
  }

  fn id(&self) -> Result<ShotId, CrossingError> {
    Ok(ShotId {
      reel: self.reel,
      ordinal: self.ordinal,
    })
  }

  fn record(self) -> Result<Shot, CrossingError> {
    Ok(Shot {
      id: ShotId {
        reel: self.reel,
        ordinal: self.ordinal,
      },
      slate: self.slate,
    })
  }
}

/// Four shots over two reels — every pairing of `{1, 2} × {10, 20}`, which is exactly what makes
/// the cartesian defect visible: the two keys asked for and the two nobody asked for are all present
/// in the table.
async fn store() -> sqlx::sqlite::SqliteConnection {
  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  sqlx::query(
    r#"CREATE TABLE "shot" ("reel_id" INTEGER NOT NULL, "ordinal" INTEGER NOT NULL,
       "slate" TEXT NOT NULL, PRIMARY KEY ("reel_id", "ordinal"))"#,
  )
  .execute(&mut db)
  .await
  .expect("the table");
  for (reel, ordinal, slate) in [
    (1_i64, 10_i64, "alpha"),
    (1, 20, "bravo"),
    (2, 10, "charlie"),
    (2, 20, "delta"),
  ] {
    sqlx::query(r#"INSERT INTO "shot" VALUES (?, ?, ?)"#)
      .bind(reel)
      .bind(ordinal)
      .bind(slate)
      .execute(&mut db)
      .await
      .expect("a shot");
  }
  db
}

fn slates(found: &[Option<Shot>]) -> Vec<Option<&str>> {
  found
    .iter()
    .map(|slot| slot.as_ref().map(|shot| shot.slate.as_str()))
    .collect()
}

/// **MUTATION PIN — the keys half is the ROW-VALUE membership, never a per-column `IN`.**
///
/// Two keys are asked for: `(1, 10)` and `(2, 20)`. The per-column spelling would also answer
/// `(1, 20)` and `(2, 10)` — rows nobody asked for, returned by well-formed SQL that binds the same
/// four operands. Nothing in the rendered text or the bind count separates the two, which is why
/// this assertion is on the ANSWER: four slots back instead of two, with the wrong entities in
/// them.
#[tokio::test]
async fn a_compound_key_gather_is_not_the_cartesian_product() {
  let mut db = store().await;
  let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);

  let found = gather
    .gather(&[shot_key(1, 10), shot_key(2, 20)], None)
    .await
    .expect("the gather runs");

  assert_eq!(slates(&found), vec![Some("alpha"), Some("delta")]);
}

/// The answer is POSITIONAL: one slot per key, in the KEY LIST's order, whatever order the plan
/// chose to answer in. The keys here are asked for in the reverse of their stored order, so a
/// gather handing back the plan's sequence would be visible.
#[tokio::test]
async fn the_answer_is_in_the_key_lists_order() {
  let mut db = store().await;
  let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);

  let found = gather
    .gather(&[shot_key(2, 20), shot_key(1, 10), shot_key(2, 10)], None)
    .await
    .expect("the gather runs");

  assert_eq!(
    slates(&found),
    vec![Some("delta"), Some("alpha"), Some("charlie")]
  );
}

/// The FILTER rides the same statement: one call, one round trip, and the pruned key comes back as
/// an empty slot rather than as a row the caller has to drop.
#[tokio::test]
async fn the_filter_prunes_inside_the_one_composed_statement() {
  let mut db = store().await;
  let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);
  let only = slated("delta");

  let found = gather
    .gather(&[shot_key(1, 10), shot_key(2, 20)], Some(&only))
    .await
    .expect("the gather runs");

  assert_eq!(slates(&found), vec![None, Some("delta")]);
}

/// A key the store has NO row for is an empty slot — the same shape a prune takes, because the fill
/// loop does the same thing with either.
#[tokio::test]
async fn a_key_with_no_row_is_an_empty_slot() {
  let mut db = store().await;
  let mut gather = SqlGather::<ShotRow, Sqlite>::new(&mut db);

  let found = gather
    .gather(&[shot_key(1, 10), shot_key(9, 99)], None)
    .await
    .expect("the gather runs");

  assert_eq!(slates(&found), vec![Some("alpha"), None]);
}

/// No keys is a membership of nothing, which asks for no rows — an operand rather than an absence,
/// and not a statement that answers the whole table.
#[tokio::test]
async fn an_empty_batch_asks_for_no_rows() {
  let mut db = store().await;
  let mut gather: SqlGather<'_, ShotRow, Sqlite> = SqlGather::new(&mut db);

  let found: Vec<Option<Shot>> = gather
    .gather(&[] as &[ShotKey], None)
    .await
    .expect("the gather runs");

  assert!(found.is_empty());
}