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
//! **Ordering by a collection whose elements are COMPOSITE, on every backend that has a row.**
//!
//! ```text
//! subject      TermSubject::Edge          on every SQL dialect and on MongoDB
//! pushable     no                         Unpushable::CollectionTable
//! remainder    OrderPartition::apply      the lexicographic PIN, in memory
//! paging       PagingOrderError           by name, carrying that same cause
//! ```
//!
//! # The parity is that there is NO fork, and that is the whole finding
//!
//! A SCALAR collection forks: PostgreSQL keeps one in a native array, so its term is
//! [`TermSubject::Array`](crate::TermSubject) and its ordering is pushable and bindable, where SQLite
//! and MySQL send it to an edge table and take the remainder path. A COMPOSITE element has no array
//! anywhere — the Postgres delegation is scalar-only, an array of two columns not being a thing any
//! dialect here has — so every backend's term is [`TermSubject::Edge`](crate::TermSubject) and every
//! backend takes the same path, for the one reason no capability row decides: the row being ordered
//! has no column for it.
//!
//! So the assertions in `backends` are per backend and the expected answer is the same four times.
//! That is worth running rather than reasoning about, because the shape of the mistake it catches is
//! a capability row growing an opinion about a column it is not being handed.
//!
//! # The PIN is the element's own `Ord`, unrestated
//!
//! [`compare_collections`](crate::query::compare_collections) is `Iterator::cmp`, so a collection of
//! a type orders however a column of that type already orders. What a composite element adds is
//! nothing at all: [`Timestamp`](crate::Timestamp)'s own `Ord` is the pair's, so the lexicographic
//! pin over instants is the pin over anything, and the test below is what says the framework did not
//! acquire a second opinion about a value it holds two columns of.
//!
//! That half names no backend, so it is here rather than in the gated module — a pin is a fact about
//! the FRAMEWORK's meaning, and a build with no database at all still has one.

use core::cmp::Ordering;

use crate::{
  FieldName, OrderDirection, OrderTerm, TermName, TermSubject, Timestamp,
  query::compare_collections,
};

/// The collection term this module is about — an edge-stored one, which is what a composite element
/// takes on every backend.
fn stamps() -> OrderTerm {
  OrderTerm::edge(
    TermName::new("stamps"),
    FieldName::new("stamps"),
    OrderDirection::Asc,
  )
}

/// A plain term beside it, so a SPLIT has a pushable prefix to keep.
fn id() -> OrderTerm {
  OrderTerm::new(
    TermName::new("id"),
    FieldName::new("id"),
    OrderDirection::Asc,
  )
}

fn at(second: i64, nanosecond: i32) -> Timestamp {
  Timestamp::from_parts(second, nanosecond).expect("a legal instant")
}

/// The subject a composite collection's term carries is EDGE, and that is the storage fact every
/// backend reads.
#[test]
fn a_composite_collection_is_an_edge_subject() {
  assert_eq!(stamps().subject(), TermSubject::Edge);
  assert!(stamps().subject().is_collection());
  assert_eq!(
    stamps().width(),
    1,
    "a collection is ONE subject however many columns one of its elements is"
  );
  assert_eq!(id().width(), 1, "and so is a scalar");
}

/// **The lexicographic PIN over composite elements is the element's own `Ord`, and nothing here
/// restates it.**
///
/// The three rules the PostgreSQL walk showed, over instants instead of integers: the empty
/// collection is least, a prefix is below what extends it, and the first differing element decides
/// whatever the lengths are. The last case is the one a composite could get wrong — `(10, 250)`
/// against `(10, 0)` differs only in the SECOND segment, so an ordering that compared the leading
/// column alone would call them equal and fall through to the lengths.
#[test]
fn the_pin_over_composite_elements_is_the_elements_own_order() {
  assert_eq!(
    compare_collections::<[Timestamp; 0], _>([], [at(1, 0)]),
    Ordering::Less
  );
  assert_eq!(
    compare_collections([at(1, 0), at(2, 0)], [at(1, 0), at(2, 0), at(3, 0)]),
    Ordering::Less
  );
  assert_eq!(
    compare_collections([at(2, 0)], [at(1, 0), at(9, 0)]),
    Ordering::Greater
  );
  assert_eq!(
    compare_collections([at(10, 250)], [at(10, 0), at(99, 0)]),
    Ordering::Greater,
    "the first difference is in the SECOND segment, and it decides the whole comparison"
  );
}

/// The half that names a BACKEND, gated on there being one.
///
/// Every assertion here reads a capability row, and a build carrying no database has none — so the
/// partition, its refusal and the in-memory completion live behind the gate while the pin and the
/// subject above stay in every build.
#[cfg(any(
  feature = "sqlite",
  feature = "postgres",
  feature = "mysql",
  feature = "mongo"
))]
mod backends {
  use super::{id, stamps};
  use crate::{
    TermName,
    query::{Unpushable, partition},
  };

  /// **The parity, per backend: every one of them splits, and every one of them names the same
  /// cause.**
  macro_rules! remainder_row {
    ($name:ident, $backend:ty, $feature:literal) => {
      #[cfg(feature = $feature)]
      #[test]
      fn $name() {
        let terms = [id(), stamps()];
        let split = partition::<$backend>(&terms);

        assert!(
          !split.is_whole(),
          "an edge-stored collection is not pushable"
        );
        assert_eq!(split.pushable().len(), 1, "the prefix the statement keeps");
        assert_eq!(
          split.remainder().len(),
          1,
          "and the term it could not carry"
        );
        assert_eq!(split.cause(), Some(Unpushable::CollectionTable));

        // And a PAGE over it is refused by name rather than degraded, which is the degrade law's
        // second row: a cursorless query completes in memory and a paging one cannot.
        let refused = split
          .paging::<$backend>()
          .expect_err("a page over an edge-stored collection has no boundary to resume at");
        assert_eq!(refused.term(), TermName::new("stamps"));
        assert_eq!(refused.cause(), Unpushable::CollectionTable);
      }
    };
  }

  remainder_row!(sqlite_takes_the_edge_remainder, sqlx::Sqlite, "sqlite");
  remainder_row!(
    postgres_takes_the_edge_remainder,
    sqlx::Postgres,
    "postgres"
  );
  remainder_row!(mysql_takes_the_edge_remainder, sqlx::MySql, "mysql");
  remainder_row!(mongo_takes_the_edge_remainder, crate::Mongo, "mongo");

  /// **PostgreSQL's array row does NOT reach a composite element**, and this is the pair that says
  /// the four answers above are about the SUBJECT rather than about the backends agreeing by
  /// accident.
  ///
  /// The same dialect, the same partition, one term apart: an ARRAY subject is pushable there and an
  /// EDGE subject is not.
  #[cfg(feature = "postgres")]
  #[test]
  fn postgres_pushes_an_array_and_not_an_edge() {
    use crate::{FieldName, OrderDirection, OrderTerm};

    let array = [OrderTerm::array(
      TermName::new("tags"),
      FieldName::new("tags"),
      OrderDirection::Asc,
    )];
    assert!(partition::<sqlx::Postgres>(&array).is_whole());
    assert!(!partition::<sqlx::Postgres>(&[stamps()]).is_whole());
  }

  /// **The remainder really sorts, and it sorts by the pin.**
  ///
  /// [`OrderPartition::apply`](crate::query::OrderPartition::apply) walks the WHOLE order — the
  /// pushable prefix first — so the statement's own sequence is not silently reordered by a stable
  /// sort over the remainder alone. What the rows carry here is the collection itself, which is what
  /// makes `V: Ord` the pin arriving through the caller's own value.
  #[cfg(feature = "sqlite")]
  #[test]
  fn the_remainder_sorts_the_collections_in_memory() {
    use crate::Timestamp;

    use super::at;

    #[derive(Debug, PartialEq, Eq)]
    struct Row {
      id: i64,
      stamps: Vec<Timestamp>,
    }

    /// One term's value, as a sum over what the two terms hold — the shape a record's own cursor
    /// value takes, and what makes the two comparable under one `Ord`.
    #[derive(PartialEq, Eq, PartialOrd, Ord)]
    enum Value {
      Id(i64),
      Stamps(Vec<Timestamp>),
    }

    let terms = [id(), stamps()];
    let split = partition::<sqlx::Sqlite>(&terms);
    let mut rows = [
      Row {
        id: 1,
        stamps: vec![at(10, 250)],
      },
      Row {
        id: 1,
        stamps: vec![at(10, 0), at(99, 0)],
      },
      Row {
        id: 1,
        stamps: Vec::new(),
      },
    ];

    split.apply(&mut rows, |row, term| {
      if term.identity() == TermName::new("id") {
        return Some(Value::Id(row.id));
      }
      Some(Value::Stamps(row.stamps.clone()))
    });

    assert_eq!(
      rows.iter().map(|row| row.stamps.len()).collect::<Vec<_>>(),
      [0, 2, 1],
      "empty is least, then the collection whose first element is lower, whatever the lengths"
    );
  }

  /// A WHOLE partition pages, and the refusal above is therefore about the TERM rather than about
  /// the lane — which is what keeps a record with no collection order free of any of this.
  #[cfg(feature = "sqlite")]
  #[test]
  fn an_order_without_a_collection_pages() {
    let terms = [id()];
    let split = partition::<sqlx::Sqlite>(&terms);
    assert!(split.is_whole());
    assert_eq!(
      split
        .paging::<sqlx::Sqlite>()
        .expect("no collection, no refusal")
        .len(),
      1
    );
  }

  /// The refusal's own text, so a deployment reading a log sees which term stopped the page and why.
  #[cfg(feature = "sqlite")]
  #[test]
  fn the_paging_refusal_names_the_term_and_the_cause() {
    let terms = [id(), stamps()];
    let split = partition::<sqlx::Sqlite>(&terms);
    let refused: crate::query::PagingOrderError = split
      .paging::<sqlx::Sqlite>()
      .expect_err("an edge-stored collection has no boundary");
    assert_eq!(
      refused.to_string(),
      "a page's order lives entirely in the statement and `stamps` cannot be put in one: this \
       collection is kept in a table of its own, so the row being ordered has no column for it"
    );
  }
}