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 core::fmt::Display;

use jiff::{civil, tz};

use crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, FieldName, RecordAddress, ScalarFilter,
  Temporal, ToDatabaseComparison, TryFromFilter,
  comparison::sql::{SqlConjunction, SqlLoweringError},
};

use super::{LocalTimestamp, LocalTimestampFilter, SqlLocalTimestampComparison, StoredLocal};

const ROW: RecordAddress = RecordAddress::new(FieldName::new("shots"), &[FieldName::new("id")]);

/// The dialect the lowering renders against — Postgres, whose NUMBERED placeholders say which
/// operand reached which column, where a `?` dialect can only say how many there were.
type Dialect = sqlx::Postgres;

/// The `Db` a crossing test names: nothing on the crossing is dialect-specific, so an uninhabited
/// marker stands for every dialect at once.
enum AnyDialect {}

/// The crossing row, DISCHARGED rather than assumed — a bound the impl needs and this list forgets
/// is `E0277` at the signature.
#[expect(
  dead_code,
  reason = "the signature is the assertion; instantiating it would name one dialect"
)]
fn assert_the_filter_maps_to_the_comparison<Db>()
where
  Db: sqlx::Database
    + BindCeiling
    + for<'q> Backend<Builder<'q> = SqlConjunction<'q, Db>, Error = SqlLoweringError, Buffer: Display>,
  bool: Carrier<Db>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  StoredLocal: Carrier<Db>,
  Temporal<i32>: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  fn crosses<Db: Backend, C>()
  where
    LocalTimestampFilter: ToDatabaseComparison<LocalTimestamp, Db, Comparison = C>,
  {
  }

  crosses::<Db, SqlLocalTimestampComparison<Db>>();
}

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

fn instant(text: &str) -> crate::Timestamp {
  text.parse().expect("the fixture parses")
}

fn cross(filter: LocalTimestampFilter) -> SqlLocalTimestampComparison<AnyDialect> {
  SqlLocalTimestampComparison::try_from_filter(filter).expect("the crossing is infallible")
}

fn lower(filter: LocalTimestampFilter) -> SqlLocalTimestampComparison<Dialect> {
  SqlLocalTimestampComparison::try_from_filter(filter).expect("the crossing is infallible")
}

fn render(comparison: &SqlLocalTimestampComparison<Dialect>, field: &str) -> (String, usize) {
  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  let column = At::new(&ROW).frame(FieldName::new(field));
  let written = {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison
      .apply(column.at(), out)
      .expect("the operands are few and meet no ceiling")
      .written()
  };

  (qb.sql().as_str().to_owned(), written)
}

/// **Both whole-value groups land on ONE column** — the derived instant, in the one unit every
/// stored value that has an instant shares.
#[test]
fn every_whole_value_operator_crosses_into_the_derived_column() {
  let comparison = cross(
    LocalTimestampFilter::new()
      .with_eq(instant("2021-08-14T07:45:09Z"))
      .with_ne(instant("1970-01-01T00:00:00Z"))
      .with_gt(instant("1970-01-01T00:00:01Z"))
      .with_gte(instant("1970-01-01T00:00:02Z"))
      .with_lt(instant("1970-01-01T00:00:03Z"))
      .with_lte(instant("1970-01-01T00:00:04Z"))
      .with_in_(vec![instant("1970-01-01T00:00:00.000000001Z")])
      .with_not_in(vec![instant("1970-01-01T00:00:00.000000002Z")]),
  );

  assert_eq!(comparison.utc().eq(), Some(&1_628_927_109_000_000_000));
  assert_eq!(comparison.utc().ne(), Some(&0));
  assert_eq!(comparison.utc().gt(), Some(&1_000_000_000));
  assert_eq!(comparison.utc().gte(), Some(&2_000_000_000));
  assert_eq!(comparison.utc().lt(), Some(&3_000_000_000));
  assert_eq!(comparison.utc().lte(), Some(&4_000_000_000));
  assert_eq!(comparison.utc().in_(), Some([1].as_slice()));
  assert_eq!(comparison.utc().not_in(), Some([2].as_slice()));
  assert_eq!(comparison.conjuncts(), 8);
}

/// **An operand past the nanosecond ceiling SATURATES rather than refusing**, and both readings of
/// the clamp are the reading the client asked for — see [`nanos_of`](super::nanos_of), where the two
/// are argued.
///
/// The whole crossing is [`Infallible`](core::convert::Infallible) because of it, which the type
/// system states here rather than a comment.
#[test]
fn an_operand_past_the_ceiling_saturates_and_nothing_refuses() {
  let comparison = cross(
    LocalTimestampFilter::new()
      .with_lt(crate::Timestamp::MAX)
      .with_gt(crate::Timestamp::MIN),
  );

  assert_eq!(comparison.utc().lt(), Some(&i64::MAX));
  assert_eq!(comparison.utc().gt(), Some(&i64::MIN));

  let _: Result<SqlLocalTimestampComparison<AnyDialect>, core::convert::Infallible> =
    SqlLocalTimestampComparison::try_from_filter(LocalTimestampFilter::new());
}

/// **THE STRUCTURAL FACET WALKS THE THREE VALUE COLUMNS**, and it is the only facet that reaches an
/// UNZONED row.
#[test]
fn the_structural_facet_renders_the_three_value_columns() {
  let (sql, written) = render(
    &lower(
      LocalTimestampFilter::new().with_exact(LocalTimestamp::at(wall(), tz::Offset::constant(9))),
    ),
    "shot_at",
  );

  assert_eq!(
    sql,
    r#""shot_at_local" = $1 AND "shot_at_offset_seconds" = $2 AND "shot_at_offset_stated" = $3"#
  );
  assert_eq!(written, 3);
}

/// The same facet over a value that stated NO zone — the columns are the same three and the flag is
/// what differs, which is exactly the distinction two independent fields could not hold.
#[test]
fn the_structural_facet_reaches_an_unzoned_value() {
  let unzoned = cross(LocalTimestampFilter::new().with_exact(LocalTimestamp::wall(wall())));
  let utc =
    cross(LocalTimestampFilter::new().with_exact(LocalTimestamp::at(wall(), tz::Offset::UTC)));

  assert_ne!(
    unzoned, utc,
    "a file that said +00:00 and a file that said nothing are two operands"
  );
  assert_eq!(unzoned.conjuncts(), 3);
}

/// **THE OFFSET COMPONENT CARRIES ITS GUARD**, so `offset: { eq: "+00" }` selects the values that
/// said UTC rather than the values that said nothing.
#[test]
fn the_offset_component_renders_its_stated_guard() {
  let (sql, written) = render(
    &lower(LocalTimestampFilter::new().with_offset(ScalarFilter::new().with_eq(tz::Offset::UTC))),
    "shot_at",
  );

  assert_eq!(
    sql, r#""shot_at_offset_stated" = $1 AND "shot_at_offset_seconds" = $2"#,
    "the guard comes first — the question before the answer"
  );
  assert_eq!(
    written, 2,
    "one conjunct for the operator and one for the guard"
  );
}

/// The presence bit asked on its own is ONE conjunct and carries no guard of its own — it IS the
/// guard's column.
#[test]
fn the_zoned_slot_renders_the_presence_column() {
  let (sql, written) = render(
    &lower(LocalTimestampFilter::new().with_zoned(false)),
    "shot_at",
  );

  assert_eq!(sql, r#""shot_at_offset_stated" = $1"#);
  assert_eq!(written, 1);
}

/// The wall-clock component reaches its own column, and it is the question EVERY value can answer —
/// including the ones with no instant.
#[test]
fn the_local_component_renders_the_wall_clock_column() {
  let (sql, written) = render(
    &lower(
      LocalTimestampFilter::new().with_local(
        ScalarFilter::new()
          .with_gte(civil::date(2021, 8, 14).at(0, 0, 0, 0))
          .with_lt(civil::date(2021, 8, 15).at(0, 0, 0, 0)),
      ),
    ),
    "shot_at",
  );

  assert_eq!(
    sql, r#""shot_at_local" >= $1 AND "shot_at_local" < $2"#,
    "a wall-clock range is two bounds on one column"
  );
  assert_eq!(written, 2);
}

/// **THE WHOLE FAN, IN THE ORDER THE SEGMENTS LIST IT** — and the conjunct count is the arithmetic
/// this comparison publishes, held against the rendering that actually happens.
#[test]
fn the_four_facets_render_in_segment_order_and_count_themselves() {
  let comparison = lower(
    LocalTimestampFilter::new()
      .with_exact(LocalTimestamp::at(wall(), tz::Offset::constant(9)))
      .with_zoned(true)
      .with_local(ScalarFilter::new().with_gte(wall()))
      .with_offset(ScalarFilter::new().with_gt(tz::Offset::UTC))
      .with_gte(instant("2021-01-01T00:00:00Z")),
  );
  let (sql, written) = render(&comparison, "shot_at");

  assert_eq!(
    sql,
    r#""shot_at_local" = $1 AND "shot_at_offset_seconds" = $2 AND "shot_at_offset_stated" = $3 AND "shot_at_offset_stated" = $4 AND "shot_at_offset_stated" = $5 AND "shot_at_local" >= $6 AND "shot_at_offset_seconds" > $7 AND "shot_at_utc_nanos" >= $8"#
  );
  assert_eq!(written, 8);
  assert_eq!(
    ComplexComparison::<Dialect>::conjuncts(&comparison),
    8,
    "the published arithmetic and the rendering agree"
  );
}

/// The empty comparison writes nothing and counts nothing, which is what an absent field means.
#[test]
fn an_empty_comparison_renders_nothing() {
  let comparison = lower(LocalTimestampFilter::new());
  assert!(comparison.is_empty());
  assert_eq!(comparison.conjuncts(), 0);
  assert_eq!(render(&comparison, "shot_at"), (String::new(), 0));
}