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 crate::{
  At, Backend, BindCeiling, Carrier, ComplexComparison, FieldName, RecordAddress, ScalarFilter,
  ToDatabaseComparison, TryFromFilter,
  comparison::sql::{SqlConjunction, SqlLoweringError},
};
use mediatime as mt;

use super::{MediaTimeRangeCrossingError, SqlMediaTimeRangeComparison};
use crate::primitives::mediatime::{
  MediaContained, MediaContainedOperand, MediaDurationBound, MediaInstantBound,
  MediaSpanDurationFilter, MediaTimeRangeFilter, MediaTimeRangeOperand, TimebaseFilter,
  tests::{range, timebase, timestamp},
};

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

type Dialect = sqlx::Postgres;

enum AnyDialect {}

/// The crossing row, DISCHARGED rather than assumed.
#[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>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  fn crosses<Db: Backend, C>()
  where
    MediaTimeRangeFilter: ToDatabaseComparison<i64, Db, Comparison = C>,
  {
  }

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

fn cross(
  filter: MediaTimeRangeFilter,
) -> Result<SqlMediaTimeRangeComparison<AnyDialect>, MediaTimeRangeCrossingError> {
  SqlMediaTimeRangeComparison::try_from_filter(filter)
}

fn lower(filter: MediaTimeRangeFilter) -> SqlMediaTimeRangeComparison<Dialect> {
  SqlMediaTimeRangeComparison::try_from_filter(filter).expect("the filter is crossable")
}

fn render(comparison: &SqlMediaTimeRangeComparison<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)
}

/// One second, as a length operand.
fn seconds(count: i64) -> MediaDurationBound {
  MediaDurationBound::new(mt::SignedDuration::new(
    count * 1_000_000_000,
    mt::Timebase::NANOS,
  ))
}

/// **Every member of the algebra renders the inequalities its predicate states**, and the
/// half-openness is visible in which of them are strict.
///
/// One case per operator, each on its own, because what is being pinned is the SQL of a predicate —
/// and the operators share no slot, so a case that mixed them would not say which one wrote what.
#[test]
fn each_relation_renders_the_predicate_it_names() {
  let point = timestamp(1, 1, 1);
  let span = range(1, 2, 1, 1);

  for (filter, expected) in [
    (
      MediaTimeRangeFilter::new()
        .with_contains(MediaContainedOperand::new(MediaContained::Instant(point))),
      r#""span_start_nanos" <= $1 AND "span_end_nanos" > $2"#,
    ),
    (
      MediaTimeRangeFilter::new()
        .with_contains(MediaContainedOperand::new(MediaContained::Span(span))),
      r#""span_start_nanos" <= $1 AND "span_end_nanos" >= $2"#,
    ),
    (
      MediaTimeRangeFilter::new().with_overlaps(span),
      r#""span_start_nanos" < $1 AND "span_end_nanos" > $2"#,
    ),
    (
      MediaTimeRangeFilter::new().with_within(span),
      r#""span_start_nanos" >= $1 AND "span_end_nanos" <= $2"#,
    ),
    (
      MediaTimeRangeFilter::new().with_before(MediaInstantBound::new(point)),
      r#""span_end_nanos" <= $1"#,
    ),
    (
      MediaTimeRangeFilter::new().with_after(MediaInstantBound::new(point)),
      r#""span_start_nanos" >= $1"#,
    ),
  ] {
    let comparison = lower(filter);
    let (sql, written) = render(&comparison, "span");

    assert_eq!(sql, expected);
    assert_eq!(written, comparison.conjuncts(), "{sql}");
  }
}

/// **`overlaps` binds the operand's endpoints CROSSWISE**, which is what its predicate says: the
/// stored start is compared against the operand's END and the stored end against its START.
///
/// The numbered placeholders are what make that assertable — with `?` on both sides the text would
/// be identical for a lowering that bound them the right way round and one that did not.
#[test]
fn overlaps_binds_the_operand_endpoints_crosswise() {
  let comparison = lower(MediaTimeRangeFilter::new().with_overlaps(range(1, 2, 1, 1)));

  assert_eq!(
    comparison,
    lower(MediaTimeRangeFilter::new().with_overlaps(range(1, 2, 1, 1)))
  );

  // The crossing holds the pair in the order the operand declares it; the RENDERING is where the
  // swap happens, so the comparison keeps `(start, end)` and the SQL compares against the other one.
  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  let column = At::new(&ROW).frame(FieldName::new("span"));
  {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison.apply(column.at(), out).unwrap();
  }
  assert_eq!(
    qb.sql(),
    r#""span_start_nanos" < $1 AND "span_end_nanos" > $2"#
  );
}

/// **Two relations that want the same column do not collide**, which is the whole reason the algebra
/// renders its own conjuncts instead of routing through two scalar comparisons.
///
/// `contains` and `overlaps` both bound the end column; a slotted lowering would have to refuse the
/// pair or keep whichever was written last.
#[test]
fn two_relations_over_one_column_both_render() {
  let comparison = lower(
    MediaTimeRangeFilter::new()
      .with_contains(MediaContainedOperand::new(MediaContained::Instant(
        timestamp(1, 1, 1),
      )))
      .with_overlaps(range(0, 5, 1, 1)),
  );
  let (sql, written) = render(&comparison, "span");

  assert_eq!(
    sql,
    concat!(
      r#""span_start_nanos" <= $1 AND "span_end_nanos" > $2"#,
      r#" AND "span_start_nanos" < $3 AND "span_end_nanos" > $4"#
    )
  );
  assert_eq!(written, 4);
  assert_eq!(comparison.conjuncts(), written);
}

/// **The duration facet is an EXPRESSION over both columns**, and its four bounds render in the
/// order the facet declares them.
#[test]
fn the_duration_facet_compares_the_difference() {
  let comparison = lower(
    MediaTimeRangeFilter::new().with_duration(
      MediaSpanDurationFilter::new()
        .with_gt(seconds(1))
        .with_lte(seconds(10)),
    ),
  );
  let (sql, written) = render(&comparison, "span");

  assert_eq!(
    sql,
    concat!(
      r#"("span_end_nanos" - "span_start_nanos") > $1"#,
      r#" AND ("span_end_nanos" - "span_start_nanos") <= $2"#
    )
  );
  assert_eq!(written, 2);
  assert_eq!(comparison.conjuncts(), written);
}

/// A length operand crosses through the same rescale a position does, so `-1500 @ MILLIS` is
/// −1 500 000 000 nanoseconds and a length past the ceiling is refused with its OWN variant.
#[test]
fn a_length_crosses_through_the_rescale_and_meets_its_own_ceiling() {
  let comparison = lower(MediaTimeRangeFilter::new().with_duration(
    MediaSpanDurationFilter::new().with_gte(MediaDurationBound::new(mt::SignedDuration::new(
      -1500,
      mt::Timebase::MILLIS,
    ))),
  ));
  assert_eq!(render(&comparison, "span").1, 1);

  let refused = cross(MediaTimeRangeFilter::new().with_duration(
    MediaSpanDurationFilter::new().with_gt(MediaDurationBound::new(mt::SignedDuration::new(
      i64::MAX,
      mt::Timebase::SECONDS,
    ))),
  ))
  .unwrap_err();

  assert_eq!(refused, MediaTimeRangeCrossingError::DurationOverflow);
  assert!(refused.to_string().contains("292 years"));
  assert!(
    core::error::Error::source(&refused).is_none(),
    "a length ceiling has no leaf beneath it"
  );
}

/// The components and the nested citizen render after the algebra, each under its own segment.
#[test]
fn the_components_reach_their_own_columns() {
  let comparison = lower(
    MediaTimeRangeFilter::new()
      .with_start_pts(ScalarFilter::new().with_gte(0))
      .with_end_pts(ScalarFilter::new().with_lt(1000))
      .with_timebase(TimebaseFilter::new().with_eq(timebase(1, 90_000))),
  );
  let (sql, written) = render(&comparison, "span");

  assert_eq!(
    sql,
    concat!(
      r#""span_start_pts" >= $1 AND "span_end_pts" < $2"#,
      r#" AND "span_timebase_num" = $3 AND "span_timebase_den" = $4"#
    )
  );
  assert_eq!(written, 4);
}

/// An instant or endpoint past the ceiling is refused, and the variant says it was a POSITION rather
/// than a length.
#[test]
fn an_endpoint_with_no_position_is_refused() {
  let refused = cross(
    MediaTimeRangeFilter::new().with_after(MediaInstantBound::new(timestamp(i64::MAX, 1, 1))),
  )
  .unwrap_err();

  assert!(matches!(refused, MediaTimeRangeCrossingError::Overflow(_)));
  assert!(core::error::Error::source(&refused).is_some());
}

/// The nested citizen's refusal passes through whole, as it does one type up.
#[test]
fn the_nested_citizens_refusal_passes_through() {
  let refused = cross(
    MediaTimeRangeFilter::new()
      .with_timebase(TimebaseFilter::new().with_starts_with(smol_bytes::Utf8Bytes::from("_"))),
  )
  .unwrap_err();

  assert!(matches!(refused, MediaTimeRangeCrossingError::Timebase(_)));
  assert!(refused.to_string().contains("digits and a slash"));
}

/// The empty filter crosses to the empty comparison, and `Default` is `new()`.
#[test]
fn the_empty_filter_crosses_to_the_empty_comparison() {
  let comparison = cross(MediaTimeRangeFilter::new()).expect("an empty filter is crossable");

  assert!(comparison.is_empty());
  assert_eq!(comparison.conjuncts(), 0);
  assert_eq!(comparison, SqlMediaTimeRangeComparison::new());
  assert_eq!(
    SqlMediaTimeRangeComparison::<AnyDialect>::default(),
    SqlMediaTimeRangeComparison::new()
  );
}

/// **The conjunct count is what the accumulator opened**, asserted against it rather than against
/// itself — with every facet set at once, which is where a count could go wrong by a slot.
#[test]
fn the_conjunct_count_is_what_the_lowering_opens() {
  let comparison = lower(
    MediaTimeRangeFilter::new()
      .with_contains(MediaContainedOperand::new(MediaContained::Instant(
        timestamp(1, 1, 1),
      )))
      .with_overlaps(range(0, 5, 1, 1))
      .with_within(range(0, 100, 1, 1))
      .with_before(MediaInstantBound::new(timestamp(50, 1, 1)))
      .with_after(MediaInstantBound::new(timestamp(0, 1, 1)))
      .with_duration(
        MediaSpanDurationFilter::new()
          .with_gt(seconds(1))
          .with_gte(seconds(1))
          .with_lt(seconds(9))
          .with_lte(seconds(9)),
      )
      .with_start_pts(ScalarFilter::new().with_gte(0))
      .with_end_pts(ScalarFilter::new().with_lt(1000))
      .with_timebase(TimebaseFilter::new().with_eq(timebase(1, 90_000))),
  );
  let (sql, written) = render(&comparison, "span");

  // 2 + 2 + 2 + 1 + 1 + 4 + 1 + 1 + 2
  assert_eq!(comparison.conjuncts(), 16, "{sql}");
  assert_eq!(written, 16, "{sql}");
  assert_eq!(sql.matches(" AND ").count(), 15, "{sql}");
}

/// **`exact` binds the FOUR value columns** — the range's only whole-value identity, and it touches
/// neither derived position.
#[test]
fn the_structural_identity_binds_the_value_columns() {
  let comparison = lower(
    MediaTimeRangeFilter::new().with_exact(MediaTimeRangeOperand::new(range(100, 250, 1, 90_000))),
  );
  let (sql, written) = render(&comparison, "span");

  assert_eq!(
    sql,
    concat!(
      r#""span_start_pts" = $1 AND "span_end_pts" = $2"#,
      r#" AND "span_timebase_num" = $3 AND "span_timebase_den" = $4"#
    )
  );
  assert_eq!(written, 4);
  assert_eq!(comparison.conjuncts(), written);
  assert_eq!(comparison.exact(), Some((100, 250, 1, 90_000)));
}

/// It reduces its timebase half and meets no ceiling — the timestamp facet's two properties, at this
/// arity.
#[test]
fn the_structural_identity_reduces_and_meets_no_ceiling() {
  let declared = cross(
    MediaTimeRangeFilter::new().with_exact(MediaTimeRangeOperand::new(range(1, 2, 2, 180_000))),
  )
  .expect("a range");
  let reduced = cross(
    MediaTimeRangeFilter::new().with_exact(MediaTimeRangeOperand::new(range(1, 2, 1, 90_000))),
  )
  .expect("its twin");
  assert_eq!(declared, reduced);
  assert_eq!(declared.exact(), Some((1, 2, 1, 90_000)));

  let extreme = range(0, i64::MAX, 1, 1);
  assert!(extreme.end().to_nanos().is_err(), "no position exists");
  assert_eq!(
    cross(MediaTimeRangeFilter::new().with_exact(MediaTimeRangeOperand::new(extreme)))
      .expect("the value columns hold it")
      .exact(),
    Some((0, i64::MAX, 1, 1))
  );
}

/// It composes with the algebra and the components without sharing a slot with either.
#[test]
fn the_structural_identity_composes_with_the_algebra() {
  let comparison = lower(
    MediaTimeRangeFilter::new()
      .with_exact(MediaTimeRangeOperand::new(range(0, 90_000, 1, 90_000)))
      .with_after(MediaInstantBound::new(timestamp(0, 1, 1)))
      .with_start_pts(ScalarFilter::new().with_lt(10)),
  );
  let (sql, written) = render(&comparison, "span");

  assert_eq!(
    sql,
    concat!(
      r#""span_start_pts" = $1 AND "span_end_pts" = $2"#,
      r#" AND "span_timebase_num" = $3 AND "span_timebase_den" = $4"#,
      r#" AND "span_start_nanos" >= $5"#,
      r#" AND "span_start_pts" < $6"#
    )
  );
  assert_eq!(written, 6);
  assert_eq!(comparison.conjuncts(), written);
}