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
use jiff::{civil, tz};

use crate::{ColumnKind, ColumnShape, CursorValue, OrderLeaves};

use super::{
  LOCAL, LocalTimestamp, LocalTimestampLeaf, LocalTimestampPartsError, OFFSET_SECONDS,
  OFFSET_STATED, ORDER, SEGMENTS, UTC_NANOS, civil_of, offset_of,
};

fn wall() -> civil::DateTime {
  civil::date(2021, 8, 14).at(16, 45, 9, 123_456_789)
}

fn tokyo() -> LocalTimestamp {
  LocalTimestamp::at(wall(), tz::Offset::constant(9))
}

/// **THE FOUR WORDS' TRUTH TABLE for this citizen**, read off the segments rather than off any one
/// reader — three leaves that are the VALUE and one that is an INDEX.
///
/// The row that earns the assertion is the third: `offset_stated` is [`Plain`](ColumnShape::Plain)
/// and therefore `NOT NULL` under a required field, which is the two-leaf spelling's whole reason —
/// see the module note, where the missing fourth corner of the shape vocabulary is argued.
#[test]
fn three_leaves_are_the_value_and_the_derived_one_is_not() {
  let table: Vec<_> = SEGMENTS
    .iter()
    .map(|shape| (shape.holds_value(), shape.self_nullable()))
    .collect();

  assert_eq!(
    table,
    [(true, false), (true, false), (true, false), (false, true)],
    "local, offset_seconds and offset_stated are the VALUE; utc_nanos is a nullable INDEX"
  );

  assert_eq!(crate::width(SEGMENTS), 4);
  assert_eq!(crate::value_width(SEGMENTS), 3);
  assert_eq!(
    SEGMENTS.iter().filter_map(ColumnShape::field).count(),
    4,
    "every leaf names a field, both derived and not"
  );
}

/// The names, in the order the columns are written — which is what a `CREATE TABLE`, a bind list and
/// a `SELECT` list are all indexed by.
#[test]
fn the_segments_are_named_as_the_module_documents_them() {
  assert_eq!(
    SEGMENTS
      .iter()
      .filter_map(ColumnShape::field)
      .map(|field| field.stored().as_str().to_owned())
      .collect::<Vec<_>>(),
    ["local", "offset_seconds", "offset_stated", "utc_nanos"]
  );
  assert_eq!(LOCAL.as_str(), "local");
  assert_eq!(OFFSET_SECONDS.as_str(), "offset_seconds");
  assert_eq!(OFFSET_STATED.as_str(), "offset_stated");
  assert_eq!(UTC_NANOS.as_str(), "utc_nanos");
}

/// **THE ORDER LEADS WITH THE DERIVED LEAF**, then the value leaves as the determinism tail.
#[test]
fn the_order_is_utc_led_and_covers_every_leaf() {
  assert_eq!(
    ORDER.iter().map(|level| level.leaf()).collect::<Vec<_>>(),
    [3, 0, 1, 2]
  );
  assert_eq!(
    <LocalTimestamp as ColumnKind>::ORDER.len(),
    crate::width(SEGMENTS),
    "every leaf sits in exactly one level"
  );
}

/// The leaf vocabulary, one member per leaf and the derived one RECOMPUTED at the call.
#[test]
fn the_leaves_answer_the_value_then_the_recomputed_position() {
  let capture = tokyo();

  assert_eq!(capture.leaf(0), Some(LocalTimestampLeaf::Local(wall())));
  assert_eq!(
    capture.leaf(1),
    Some(LocalTimestampLeaf::OffsetSeconds(32_400))
  );
  assert_eq!(
    capture.leaf(2),
    Some(LocalTimestampLeaf::OffsetStated(true))
  );
  assert_eq!(
    capture.leaf(3),
    Some(LocalTimestampLeaf::UtcNanos(1_628_927_109_123_456_789))
  );
  assert_eq!(capture.leaf(4), None, "there is no fifth leaf");
}

/// **AN UNZONED VALUE HAS EVERY VALUE LEAF AND NO POSITION** — which is the `NULL` the write binds,
/// read at the leaf where a cursor meets it.
#[test]
fn an_unzoned_value_answers_none_at_the_derived_level_only() {
  let capture = LocalTimestamp::wall(wall());

  assert_eq!(capture.leaf(0), Some(LocalTimestampLeaf::Local(wall())));
  assert_eq!(capture.leaf(1), Some(LocalTimestampLeaf::OffsetSeconds(0)));
  assert_eq!(
    capture.leaf(2),
    Some(LocalTimestampLeaf::OffsetStated(false)),
    "the presence bit is a VALUE leaf and is never absent"
  );
  assert_eq!(capture.leaf(3), None, "and there is no position");
}

/// The whole value's cursor is the three VALUE leaves and never the derived key, so an unzoned value
/// has a boundary exactly as a zoned one does.
#[test]
fn the_cursor_carries_the_value_leaves_and_round_trips_both_shapes() {
  for capture in [tokyo(), LocalTimestamp::wall(wall())] {
    let mut bytes = Vec::new();
    capture.write_cursor(&mut bytes);
    assert_eq!(
      bytes.len(),
      16,
      "eleven civil bytes, four seconds, one flag"
    );
    assert_eq!(
      <LocalTimestamp as CursorValue>::read_cursor(&bytes),
      Some(capture)
    );
  }
}

/// FIXED WIDTH, so a client's fifteen or seventeen bytes are refused rather than zero-extended into
/// a plausible capture time.
#[test]
fn a_cursor_of_the_wrong_width_is_refused() {
  let mut bytes = Vec::new();
  tokyo().write_cursor(&mut bytes);

  assert!(<LocalTimestamp as CursorValue>::read_cursor(&bytes[..15]).is_none());
  let mut wide = bytes.clone();
  wide.push(0);
  assert!(<LocalTimestamp as CursorValue>::read_cursor(&wide).is_none());
}

/// **A FORGED CURSOR NAMING AN IMPOSSIBLE VALUE IS REFUSED**, at both of the two places one can be
/// forged: a month jiff does not admit, and the `stated = false` beside a displacement that the
/// decode refuses too.
#[test]
fn a_forged_cursor_is_refused_by_the_same_rules_the_decode_uses() {
  let mut bytes = Vec::new();
  tokyo().write_cursor(&mut bytes);

  let mut month = bytes.clone();
  month[2] = 13;
  assert!(<LocalTimestamp as CursorValue>::read_cursor(&month).is_none());

  // The flag turned off with the seconds left in place — the one arrangement two columns admit and
  // one `Option` does not.
  let mut unstated = bytes.clone();
  unstated[15] = 0;
  assert!(<LocalTimestamp as CursorValue>::read_cursor(&unstated).is_none());
}

/// Each leaf's own slot carries its tag and its value, and a byte naming no leaf is refused rather
/// than read as the nearest one.
#[test]
fn a_leaf_slot_round_trips_and_refuses_an_unknown_tag() {
  for leaf in [
    LocalTimestampLeaf::Local(wall()),
    LocalTimestampLeaf::OffsetSeconds(-16_200),
    LocalTimestampLeaf::OffsetStated(false),
    LocalTimestampLeaf::UtcNanos(1_628_927_109_123_456_789),
  ] {
    let mut bytes = Vec::new();
    leaf.write_cursor(&mut bytes);
    assert_eq!(
      <LocalTimestampLeaf as CursorValue>::read_cursor(&bytes),
      Some(leaf)
    );
  }

  assert!(<LocalTimestampLeaf as CursorValue>::read_cursor(&[9, 0, 0, 0, 0]).is_none());
  assert!(<LocalTimestampLeaf as CursorValue>::read_cursor(&[]).is_none());
}

/// The offset pair back into the `Option` it spells, and the ONE arrangement it refuses.
#[test]
fn the_offset_pair_reads_back_and_refuses_the_arrangement_the_type_cannot_hold() {
  assert_eq!(offset_of(0, false).expect("a silent file"), None);
  assert_eq!(
    offset_of(32_400, true).expect("a Tokyo file"),
    Some(tz::Offset::constant(9))
  );
  assert_eq!(
    offset_of(0, true).expect("a file that said UTC"),
    Some(tz::Offset::UTC)
  );

  assert!(matches!(
    offset_of(32_400, false),
    Err(LocalTimestampPartsError::Unstated { seconds: 32_400 })
  ));
  assert!(matches!(
    offset_of(93_600, true),
    Err(LocalTimestampPartsError::Offset(_))
  ));
}

/// The REVERSE crossing, which the temporal trait does not state — and it is the identity over the
/// forward one, which is the pairing a round trip rests on.
#[test]
fn the_reverse_crossing_is_the_forward_ones_inverse() {
  use crate::TemporalStorage as _;

  for local in [
    civil::DateTime::MIN,
    civil::DateTime::MAX,
    wall(),
    civil::date(-4000, 2, 29).at(23, 59, 59, 999_999_999),
  ] {
    assert_eq!(
      civil_of(local.to_storage()).expect("the span is the same on both sides"),
      local
    );
  }
}

/// The DDL words, read off the leaf types' own rows so that a dialect renaming any of them moves
/// this declaration with it.
#[cfg(feature = "sqlite")]
#[test]
fn the_declared_words_are_the_leaf_types_own() {
  use crate::StoredAs;

  assert_eq!(
    <LocalTimestamp as StoredAs<sqlx::Sqlite>>::WORDS,
    [
      <time::PrimitiveDateTime as StoredAs<sqlx::Sqlite>>::WORDS[0],
      <i32 as StoredAs<sqlx::Sqlite>>::WORDS[0],
      <bool as StoredAs<sqlx::Sqlite>>::WORDS[0],
      <i64 as StoredAs<sqlx::Sqlite>>::WORDS[0],
    ]
  );
}

/// The BSON form: four keys, the derived one first and `null` where there is none, and the read
/// takes the three value keys back through the SQL decode's own refusals.
#[cfg(feature = "mongo")]
#[test]
fn the_bson_document_writes_four_keys_and_reads_three_back() {
  use crate::{MongoCarrier, query::mongo::MongoExtract};

  for capture in [tokyo(), LocalTimestamp::wall(wall())] {
    let written = capture.to_bson();
    let bson::Bson::Document(held) = &written else {
      panic!("a capture time is a sub-document");
    };

    assert_eq!(
      held.keys().map(String::as_str).collect::<Vec<_>>(),
      ["utc_nanos", "local", "offset_seconds", "offset_stated"],
      "written in the order the ORDER means them"
    );
    assert_eq!(
      held.get("utc_nanos").expect("the derived key is written"),
      &match capture.to_utc_nanos() {
        Ok(nanos) => bson::Bson::Int64(nanos),
        Err(_) => bson::Bson::Null,
      }
    );
    assert_eq!(
      <LocalTimestamp as MongoExtract>::extract(Some(&written)).expect("it reads back"),
      capture
    );
  }
}

/// The same refusal the SQL decode makes, in the MongoDB family's own vocabulary.
#[cfg(feature = "mongo")]
#[test]
fn a_bson_document_naming_an_impossible_pair_is_refused() {
  use crate::query::mongo::{MongoExtract, MongoTypeError};

  let mut held = bson::Document::new();
  held.insert("utc_nanos", bson::Bson::Null);
  held.insert("local", "2021-08-14T16:45:09");
  held.insert("offset_seconds", 32_400);
  held.insert("offset_stated", false);

  assert!(matches!(
    <LocalTimestamp as MongoExtract>::extract(Some(&bson::Bson::Document(held))),
    Err(MongoTypeError::Range(_))
  ));
}