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 `$sort` a written order becomes, and what it refuses before rendering anything.

use bson::doc;

use super::{MongoOrder, MongoSortError};
use crate::{
  FieldName, OrderDirection, OrderTerm, RecordAddress, TermName, Walk,
  comparison::mongo::Mongo,
  query::{
    Unpushable,
    mongo::{
      MongoQuery,
      tests::{ShotMongo, ShotOrder, by_cover_strip_label, by_cover_title, subjects, terms},
    },
    partition,
  },
};

/// The address every sort below is rendered against — the fixture's, so `id` maps to `_id` exactly
/// as it does in a real package.
const ADDRESS: RecordAddress = <ShotMongo as MongoQuery>::ADDRESS;

/// A completed order renders one entry per term, in the sequence they run, and the LAST of them is
/// the id — which is the tail that makes the order total.
///
/// The `_id: 1` at the end is the mutation pin: an assembly that rendered the client's WRITTEN
/// terms rather than the completed ones would produce this document without it, and every page over
/// a repeated sort value would then skip or repeat rows at the boundary with no error anywhere.
#[test]
fn a_completed_order_ends_with_the_id_ascending() {
  let terms = terms(&[ShotOrder::Title(OrderDirection::Asc)]);
  let order = MongoOrder::new(&terms).expect("two terms");

  assert_eq!(
    order.sort(&ADDRESS, Walk::Forward),
    doc! { "title": 1, "_id": 1 }
  );
}

/// A descending term renders `-1`, and the id tail keeps its own direction: the tail is what makes
/// the order total, not what the client asked for.
#[test]
fn each_term_renders_its_own_direction() {
  let terms = terms(&[
    ShotOrder::Title(OrderDirection::Desc),
    ShotOrder::Score(OrderDirection::Asc),
  ]);
  let order = MongoOrder::new(&terms).expect("three terms");

  assert_eq!(
    order.sort(&ADDRESS, Walk::Forward),
    doc! { "title": -1, "score": 1, "_id": 1 }
  );
}

/// A BACKWARD walk is the same order read from the far end: every term inverts, the id tail
/// included, and the documents are re-reversed after they come back.
#[test]
fn a_backward_walk_inverts_every_term() {
  let terms = terms(&[
    ShotOrder::Title(OrderDirection::Desc),
    ShotOrder::Score(OrderDirection::Asc),
  ]);
  let order = MongoOrder::new(&terms).expect("three terms");

  assert_eq!(
    order.sort(&ADDRESS, Walk::Backward),
    doc! { "title": 1, "score": -1, "_id": -1 }
  );
}

/// A term that already names the id MOVES it rather than repeating it, so a client ordering by the
/// id explicitly gets one entry and keeps their direction.
#[test]
fn an_order_naming_the_id_keeps_one_entry() {
  let terms = terms(&[ShotOrder::Id(OrderDirection::Desc)]);
  let order = MongoOrder::new(&terms).expect("one term");

  assert_eq!(order.sort(&ADDRESS, Walk::Forward), doc! { "_id": 1 });
  assert_eq!(order.terms().len(), 1);
}

/// There is no default order in this framework, so an order over nothing has no spelling.
#[test]
fn an_order_over_no_terms_is_refused() {
  assert_eq!(MongoOrder::new(&[]), Err(MongoSortError::Empty));
}

/// A `$sort` document holds ONE entry per field, so two terms naming one field would sort by the
/// second direction and page against the first — silently. SQL tolerates the same order as a
/// redundant term; a document cannot represent it at all.
#[test]
fn two_terms_naming_one_field_are_refused() {
  let repeated = [
    OrderTerm::new(
      TermName::new("title"),
      FieldName::new("title"),
      OrderDirection::Asc,
    ),
    OrderTerm::new(
      TermName::new("caption"),
      FieldName::new("title"),
      OrderDirection::Desc,
    ),
  ];

  assert_eq!(
    MongoOrder::new(&repeated),
    Err(MongoSortError::Repeated(TermName::new("caption")))
  );
}

/// The refusal is over the rendered FIELD rather than the identity, because the field is what a
/// document's key is: two identities renamed onto one column collide in the `$sort` and nowhere
/// else.
#[test]
fn the_collision_is_over_the_field_and_not_the_identity() {
  let distinct = [
    OrderTerm::new(
      TermName::new("title"),
      FieldName::new("title"),
      OrderDirection::Asc,
    ),
    OrderTerm::new(
      TermName::new("title"),
      FieldName::new("caption"),
      OrderDirection::Desc,
    ),
  ];

  assert!(MongoOrder::new(&distinct).is_ok());
}

/// **The row is what refuses.** This renderer takes exactly the orders
/// [`partition`](crate::query::partition) leaves whole for [`Mongo`], and refuses exactly the ones
/// it splits — so [`Mongo`]'s capability row is load-bearing rather than descriptive, and a row
/// that said [`Admitted`](crate::query::TermRepetition::Admitted) would red this rather than let a
/// `$sort` lose an entry.
#[test]
fn the_renderer_refuses_exactly_what_the_capability_row_splits() {
  let repeated = [
    OrderTerm::new(
      TermName::new("title"),
      FieldName::new("title"),
      OrderDirection::Asc,
    ),
    OrderTerm::new(
      TermName::new("caption"),
      FieldName::new("title"),
      OrderDirection::Desc,
    ),
  ];
  let split = partition::<Mongo>(&repeated);

  assert_eq!(split.cause(), Some(Unpushable::Repetition));
  assert!(MongoOrder::new(&repeated).is_err());
  assert!(
    MongoOrder::new(split.pushable()).is_ok(),
    "the prefix the frame leaves is exactly what this renders — the DEGRADE entry"
  );
}

/// A NULLABLE term is whole on this backend and the renderer takes it, which is the other half of
/// the row: MongoDB's own order puts a missing value where the framework pins it, so there is no
/// null verdict for this renderer to carry.
#[test]
fn a_nullable_term_needs_no_clause_and_no_refusal() {
  let terms = terms(&[ShotOrder::Score(OrderDirection::Desc)]);

  assert!(partition::<Mongo>(&terms).is_whole());
  assert_eq!(
    MongoOrder::new(&terms)
      .expect("two terms")
      .sort(&ADDRESS, Walk::Forward),
    doc! { "score": -1, "_id": 1 }
  );
}

/// A NESTED term sorts by the field the join stages materialized, never by the reference it
/// crosses — which is the same list the keyset reads, through the same authority.
///
/// `cover_id` appearing here instead would be a `$sort` over a foreign key: a perfectly good
/// aggregation, ordering the page by which keyframe a shot points at rather than by its title.
#[test]
fn a_nested_term_sorts_by_the_materialized_field() {
  let written = by_cover_title();
  let terms = terms(&written);
  let order = MongoOrder::new(&terms).expect("two terms");

  assert_eq!(
    order.sort_with(&ADDRESS, Walk::Forward, &subjects(&written)),
    doc! { "__ig_ord0__": 1, "_id": 1 }
  );
}

/// Depth changes the stages and not the `$sort`: however many references a term crosses, its value
/// lands under one field and the ordering names that one.
#[test]
fn a_deeper_nesting_sorts_by_the_same_one_field() {
  let written = by_cover_strip_label();
  let terms = terms(&written);
  let order = MongoOrder::new(&terms).expect("two terms");

  assert_eq!(
    order.sort_with(&ADDRESS, Walk::Backward, &subjects(&written)),
    doc! { "__ig_ord0__": -1, "_id": -1 }
  );
}

/// **A COLLECTION IS REFUSED, AND THE SENTENCE NAMES THE DISAGREEMENT.**
///
/// MongoDB really does keep a collection in a field of the document, so this is not *no such
/// column* — it is the engine meaning something else by the client's term. `$sort` over an array
/// field compares each document's SMALLEST element on an ascending term and its LARGEST on a
/// descending one, so `[9]` sorts after `[1, 99]` ascending, the two directions are not reverses of
/// one another, and neither is the framework's element-by-element rule.
///
/// Serving it anyway would order the documents in a sequence no other deployment of the same schema
/// produces, with no error anywhere — which is the same class of defect the repeated-field refusal
/// above prevents.
///
/// Mutation: answering `CollectionOrdering::Lexicographic` for `Mongo` makes this `Ok`, and
/// `only_postgres_orders_a_collection_the_framework_s_way` goes red beside it.
#[test]
fn a_collection_is_refused_by_the_rule_it_disagrees_with() {
  let terms = [
    OrderTerm::array(
      TermName::new("tags"),
      FieldName::new("tags"),
      OrderDirection::Asc,
    ),
    OrderTerm::new(
      TermName::new("id"),
      FieldName::new("_id"),
      OrderDirection::Asc,
    ),
  ];

  assert_eq!(
    MongoOrder::new(&terms),
    Err(MongoSortError::Collection(TermName::new("tags")))
  );
  assert_eq!(
    partition::<Mongo>(&terms).cause(),
    Some(Unpushable::CollectionSemantics),
    "and the refusal is the frame's verdict rather than a scan of this renderer's own"
  );

  let sentence = MongoSortError::Collection(TermName::new("tags")).to_string();
  assert!(
    sentence.contains("smallest element ascending") && sentence.contains("largest descending"),
    "the sentence names the rule this engine uses, not `unsupported`: {sentence}"
  );
}