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 super::{super::MediaInstantBound, MediaTimestampCrossingError, SqlMediaTimestampComparison};
use crate::primitives::mediatime::{
  MediaTimestampFilter, TimebaseFilter,
  tests::{timebase, timestamp},
};

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

/// The dialect the lowering renders against — Postgres, whose NUMBERED placeholders say which
/// operand reached which column. See the timebase citizen's own note for the whole argument.
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>,
  i32: Carrier<Db>,
  i64: Carrier<Db>,
  for<'a> &'a str: sqlx::Encode<'a, Db> + sqlx::Type<Db>,
{
  fn crosses<Db: Backend, C>()
  where
    MediaTimestampFilter: ToDatabaseComparison<i64, Db, Comparison = C>,
  {
  }

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

fn cross(
  filter: MediaTimestampFilter,
) -> Result<SqlMediaTimestampComparison<AnyDialect>, MediaTimestampCrossingError> {
  SqlMediaTimestampComparison::try_from_filter(filter)
}

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

fn render(comparison: &SqlMediaTimestampComparison<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**, in the one unit every stored row shares — and
/// each operand goes through `to_nanos`, which is the function the write path binds with.
///
/// `12345 @ 1/90000` is 137 166 666 ns and not 137 166 667: the rescale truncates toward zero, and
/// the write path truncates the same value the same way.
#[test]
fn every_whole_value_operator_crosses_into_the_derived_column() {
  let comparison = cross(
    MediaTimestampFilter::new()
      .with_eq(timestamp(12_345, 1, 90_000))
      .with_ne(timestamp(1, 1, 1))
      .with_gt(MediaInstantBound::new(timestamp(0, 1, 1)))
      .with_gte(MediaInstantBound::new(timestamp(1, 1, 1_000)))
      .with_lt(MediaInstantBound::new(timestamp(10, 1, 1)))
      .with_lte(MediaInstantBound::new(timestamp(11, 1, 1)))
      .with_in_(vec![timestamp(1, 1, 1_000_000_000)])
      .with_not_in(vec![timestamp(2, 1, 1_000_000_000)]),
  )
  .expect("every operand has a position");

  assert_eq!(comparison.nanos().eq(), Some(&137_166_666));
  assert_eq!(comparison.nanos().ne(), Some(&1_000_000_000));
  assert_eq!(comparison.nanos().gt(), Some(&0));
  assert_eq!(comparison.nanos().gte(), Some(&1_000_000));
  assert_eq!(comparison.nanos().lt(), Some(&10_000_000_000));
  assert_eq!(comparison.nanos().lte(), Some(&11_000_000_000));
  assert_eq!(comparison.nanos().in_(), Some([1].as_slice()));
  assert_eq!(comparison.nanos().not_in(), Some([2].as_slice()));
  assert_eq!(comparison.conjuncts(), 8);
}

/// Two timestamps the domain calls EQUAL cross to one position, whatever timebase each was counted
/// in — which is what makes the derived column answer an ordering at all.
#[test]
fn equal_instants_cross_to_one_position() {
  let millis =
    cross(MediaTimestampFilter::new().with_eq(timestamp(100, 1, 1_000))).expect("a position");
  let micros = cross(MediaTimestampFilter::new().with_eq(timestamp(100_000, 1, 1_000_000)))
    .expect("a position");

  assert_eq!(millis, micros);
  assert_eq!(millis.nanos().eq(), Some(&100_000_000));
}

/// An operand past ±292 years is REFUSED rather than clamped: a bound at the ceiling is a different
/// bound, and it would admit rows nobody asked for while reporting success.
#[test]
fn an_operand_with_no_position_is_refused() {
  let refused =
    cross(MediaTimestampFilter::new().with_gt(MediaInstantBound::new(timestamp(i64::MAX, 1, 1))))
      .unwrap_err();

  assert!(matches!(refused, MediaTimestampCrossingError::Overflow(_)));
  assert!(refused.to_string().contains("does not fit an i64"));
  assert!(core::error::Error::source(&refused).is_some());
}

/// The nested citizen's refusal arrives WHOLE, so a client hears which part of the timebase filter
/// was unanswerable rather than that "the timestamp" was.
#[test]
fn the_nested_citizens_refusal_passes_through() {
  let refused = cross(
    MediaTimestampFilter::new()
      .with_timebase(TimebaseFilter::new().with_contains(smol_bytes::Utf8Bytes::from("50%"))),
  )
  .unwrap_err();

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

/// **Three facets, three frames, one address** — and the nested citizen pushes its own two segments
/// below the frame it was handed.
#[test]
fn the_lowering_reaches_every_column_from_one_address() {
  let comparison = lower(
    MediaTimestampFilter::new()
      .with_gte(MediaInstantBound::new(timestamp(0, 1, 1)))
      .with_pts(ScalarFilter::new().with_gt(0))
      .with_timebase(TimebaseFilter::new().with_eq(timebase(1, 90_000))),
  );
  let (sql, written) = render(&comparison, "at");

  assert_eq!(
    sql,
    concat!(
      r#""at_pts" > $1"#,
      r#" AND "at_timebase_num" = $2 AND "at_timebase_den" = $3"#,
      r#" AND "at_nanos" >= $4"#
    )
  );
  assert_eq!(written, 4);
  assert_eq!(comparison.conjuncts(), written);
}

/// At the TOP LEVEL every segment renders bare, the nested citizen's included — the empty path being
/// what a prefix has no spelling for.
#[test]
fn the_top_level_renders_every_segment_bare() {
  let comparison = lower(
    MediaTimestampFilter::new()
      .with_eq(timestamp(1, 1, 1))
      .with_timebase(TimebaseFilter::new().with_eq(timebase(1, 90_000))),
  );

  let mut qb = sqlx::QueryBuilder::<Dialect>::default();
  {
    let out = SqlConjunction::with_lead(&mut qb, "");
    comparison.apply(At::new(&ROW), out).unwrap();
  }

  assert_eq!(
    qb.sql(),
    r#""timebase_num" = $1 AND "timebase_den" = $2 AND "nanos" = $3"#
  );
}

/// 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(MediaTimestampFilter::new()).expect("an empty filter is crossable");

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

/// A PRESENT but empty membership list survives the crossing: `in: []` asks for no rows where an
/// absent `in_` asks for every row.
#[test]
fn an_empty_membership_list_survives_the_crossing() {
  let comparison =
    cross(MediaTimestampFilter::new().with_in_(Vec::new())).expect("no operand to refuse");

  assert_eq!(comparison.nanos().in_(), Some([].as_slice()));
  assert!(!comparison.is_empty());
  assert_eq!(comparison.conjuncts(), 1);
}

/// **`exact` reaches the VALUE columns, `eq` the derived one** — one operand, two identities, and
/// the SQL is where the difference is visible.
///
/// Three conjuncts against one, and the numbered placeholders say which operand landed where: the
/// count, then the two reduced timebase halves.
#[test]
fn the_structural_identity_binds_the_value_columns() {
  let comparison = lower(MediaTimestampFilter::new().with_exact(timestamp(12_345, 1, 90_000)));
  let (sql, written) = render(&comparison, "at");

  assert_eq!(
    sql,
    r#""at_pts" = $1 AND "at_timebase_num" = $2 AND "at_timebase_den" = $3"#
  );
  assert_eq!(written, 3);
  assert_eq!(comparison.conjuncts(), written);
  assert_eq!(comparison.exact(), Some((12_345, 1, 90_000)));

  // The semantic twin, over the SAME operand, reaches one column and a different number.
  let semantic = lower(MediaTimestampFilter::new().with_eq(timestamp(12_345, 1, 90_000)));
  assert_eq!(render(&semantic, "at").0, r#""at_nanos" = $1"#);
  assert_eq!(semantic.nanos().eq(), Some(&137_166_666));
  assert_eq!(semantic.exact(), None);
}

/// The structural facet REDUCES its timebase half, because that is what the column holds — so two
/// spellings of one timebase are one operand here, exactly as they are one row.
#[test]
fn the_structural_identity_reduces_the_timebase_half() {
  let declared = cross(MediaTimestampFilter::new().with_exact(timestamp(2, 2, 180_000)))
    .expect("a structural operand needs no conversion");
  let reduced =
    cross(MediaTimestampFilter::new().with_exact(timestamp(2, 1, 90_000))).expect("its twin");

  assert_eq!(declared, reduced);
  assert_eq!(declared.exact(), Some((2, 1, 90_000)));
}

/// **The structural facet meets NO ceiling**, which is the one thing it can do that the semantic one
/// cannot: an instant past ±292 years has no position, and is still findable by the encoding that
/// wrote it.
#[test]
fn an_unplaceable_instant_is_still_findable_by_its_encoding() {
  let extreme = timestamp(i64::MAX, 1, 1);
  assert!(extreme.to_nanos().is_err(), "no position exists");

  let comparison =
    cross(MediaTimestampFilter::new().with_exact(extreme)).expect("the value columns hold it");
  assert_eq!(comparison.exact(), Some((i64::MAX, 1, 1)));

  // The same operand through the semantic door is refused, which is the pair stated as behaviour.
  assert!(matches!(
    cross(MediaTimestampFilter::new().with_eq(extreme)).unwrap_err(),
    MediaTimestampCrossingError::Overflow(_)
  ));
}

/// `exact` shares no slot with the components, so a filter naming both renders both — no conflict to
/// refuse, and a contradiction returns no rows rather than an error.
#[test]
fn the_structural_identity_composes_with_every_other_facet() {
  let comparison = lower(
    MediaTimestampFilter::new()
      .with_exact(timestamp(30, 1001, 30_000))
      .with_gte(MediaInstantBound::new(timestamp(0, 1, 1)))
      .with_pts(ScalarFilter::new().with_lt(100))
      .with_timebase(TimebaseFilter::new().with_contains(smol_bytes::Utf8Bytes::from("/30000"))),
  );
  let (sql, written) = render(&comparison, "at");

  assert_eq!(
    sql,
    concat!(
      r#""at_pts" = $1 AND "at_timebase_num" = $2 AND "at_timebase_den" = $3"#,
      r#" AND "at_pts" < $4"#,
      r#" AND CONCAT("at_timebase_num", '/', "at_timebase_den") LIKE $5"#,
      r#" AND "at_nanos" >= $6"#
    )
  );
  assert_eq!(written, 6);
  assert_eq!(comparison.conjuncts(), written);

  // Two equalities over one column: valid SQL that returns nothing, which is the honest answer.
  let contradiction = lower(
    MediaTimestampFilter::new()
      .with_exact(timestamp(30, 1, 1))
      .with_pts(ScalarFilter::new().with_eq(31)),
  );
  assert_eq!(
    render(&contradiction, "at").0,
    r#""at_pts" = $1 AND "at_timebase_num" = $2 AND "at_timebase_den" = $3 AND "at_pts" = $4"#
  );
}