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::convert::Infallible;

use super::SqlBytesComparison;
use crate::{BytesFilter, FixedBytesFilter, comparison::TryFromFilter};

/// A blob column kept as lowercase hex TEXT — the crossing that changes the operand rather than only
/// its type, so a pass-through mutation shows in the operand and not only in the SQL.
fn hex(bytes: Vec<u8>) -> Result<String, Infallible> {
  Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}

#[test]
fn a_crossing_replaces_the_operand_with_its_stored_form() {
  let filter = BytesFilter::<Vec<u8>>::new()
    .with_eq(vec![0x89, 0x50])
    .with_contains(vec![0x0d])
    .with_in_([vec![0xff], vec![0x00]]);

  let crossed = SqlBytesComparison::<String, ()>::try_from_filter_with(filter, hex).unwrap();

  assert_eq!(crossed.eq().map(String::as_str), Some("8950"));
  assert_eq!(crossed.contains().map(String::as_str), Some("0d"));
  assert_eq!(crossed.in_().unwrap(), ["ff".to_owned(), "00".to_owned()]);
}

/// **THE REFUSAL THIS FAMILY USED TO OWN IS GONE, AND THE ABSENCE IS A TYPE.**
///
/// A fixed-width column's `contains` was refused at the crossing, off `K::SUBSTRING`; the operator
/// is not a field of [`FixedBytesFilter`] at all now, so there is nothing to set and nothing to
/// answer. `E0599` is the assertion — a runtime one could only be written by first constructing the
/// state the split makes unconstructible:
///
/// ```compile_fail,E0599
/// let _ = ingraph::FixedBytesFilter::<Vec<u8>, 4>::new().with_contains(vec![0x89]);
/// ```
///
/// Its twin must COMPILE, for the reason every `compile_fail` pair in this crate has one: stable
/// rustdoc runs the negative block just far enough to see it fail and never checks why.
///
/// ```
/// let _ = ingraph::FixedBytesFilter::<Vec<u8>, 4>::new().with_eq(vec![0x89]);
/// ```
#[test]
fn a_fixed_column_has_no_substring_operator_to_be_refused() {
  // Every OTHER operator crosses, and now with no error type of the crossing's own: a hash column
  // compares and enumerates like any other.
  let crossed: Result<SqlBytesComparison<Vec<u8>, ()>, Infallible> =
    SqlBytesComparison::try_from_filter(
      FixedBytesFilter::<Vec<u8>, 4>::new()
        .with_eq(vec![0x89])
        .with_in_([vec![0x01], vec![0x02]]),
    );
  let crossed = crossed.unwrap();
  assert_eq!(crossed.conjuncts(), 2);
  // The two slots the fixed kind cannot fill arrive empty, which is what lets ONE comparison type
  // hold both kinds.
  assert_eq!(crossed.contains(), None);
  assert_eq!(crossed.not_contains(), None);
}

/// The same operators on a VARIABLE column cross — the absence is the fixed KIND's, not the
/// operator's.
#[test]
fn a_variable_column_takes_the_substring_operators() {
  let crossed = SqlBytesComparison::<Vec<u8>, ()>::try_from_filter(
    BytesFilter::<Vec<u8>>::new()
      .with_contains(vec![0x89])
      .with_not_contains(vec![0x50]),
  )
  .unwrap();

  assert_eq!(crossed.conjuncts(), 2);
  assert_eq!(crossed.contains(), Some(&vec![0x89]));
}

/// **THE ERROR IS THE CONVERTER'S**, for both kinds — the crossing has no refusal left to add.
///
/// The annotations are the assertion. `BytesCrossingError<Infallible>` used to keep a second
/// inhabited variant whatever the shape, so a blob's identity crossing could not fail and the type
/// would not say so; `Infallible` says it now, and the fixed kind says the same for the first time.
#[test]
fn the_identity_crossing_of_either_kind_is_infallible() {
  let blob: Result<SqlBytesComparison<Vec<u8>, ()>, Infallible> =
    SqlBytesComparison::try_from_filter(BytesFilter::<Vec<u8>>::new().with_contains(vec![0x89]));
  assert_eq!(blob.unwrap().contains(), Some(&vec![0x89]));

  let hash: Result<SqlBytesComparison<Vec<u8>, ()>, Infallible> =
    SqlBytesComparison::try_from_filter(FixedBytesFilter::<Vec<u8>, 4>::new().with_eq(vec![0x89]));
  assert_eq!(hash.unwrap().eq(), Some(&vec![0x89]));
}

/// A DECLARED converter's own refusal reaches the caller unwrapped, where it used to arrive inside
/// `BytesCrossingError::Operand`.
#[test]
fn a_declared_converter_reports_its_own_error() {
  let refused =
    SqlBytesComparison::<u8, ()>::try_from_filter(FixedBytesFilter::<u64, 8>::new().with_eq(999));
  assert!(refused.is_err());
}

#[cfg(feature = "sqlite")]
mod sqlite {
  use core::cell::RefCell;

  use super::SqlBytesComparison;
  use crate::{
    BytesFilter,
    comparison::{
      TryFromFilter,
      sql::tests::{Probe, render, threaded},
    },
  };

  #[test]
  fn every_operator_renders_its_own_conjunct() {
    let filter = BytesFilter::<Vec<u8>>::new()
      .with_eq(vec![1])
      .with_ne(vec![2])
      .with_gt(vec![3])
      .with_gte(vec![4])
      .with_lt(vec![5])
      .with_lte(vec![6])
      .with_contains(vec![7])
      .with_not_contains(vec![8])
      .with_in_([vec![9], vec![10]])
      .with_not_in([vec![11]]);
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::Sqlite>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 10);
    assert_eq!(
      render::<sqlx::Sqlite, _>("h", &crossed),
      (
        "\"h\" = ? AND NOT ( \"h\" = ? ) AND \"h\" > ? AND \"h\" >= ? AND \"h\" < ? AND \
         \"h\" <= ? AND instr(\"h\", ?) > 0 AND NOT ( instr(\"h\", ?) > 0 ) AND \
         \"h\" IN (?, ?) AND NOT ( \"h\" IN (?) )"
          .to_owned(),
        11
      )
    );
  }

  /// The threaded lowering reaches THIS dialect's leaf: `instr` with the COLUMN first, which is the
  /// reverse of what the other two write. Getting the order backwards asks about the wrong side and
  /// never fails, so which dialect's spelling this impl carries is the assertion.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::Sqlite>::try_from_filter(
      BytesFilter::<Vec<u8>>::new()
        .with_eq(vec![1])
        .with_contains(vec![7])
        .with_in_([vec![9], vec![10]]),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::Sqlite, _>("h", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE \"h\" = ? AND instr(\"h\", ?) > 0 AND \"h\" IN (?, ?)"
    );
  }

  /// Every operand the comparison holds reaches the builder, in slot order — the assertion the SQL
  /// cannot make, since a `?` says nothing about which operand filled it.
  #[test]
  fn every_operand_the_comparison_holds_is_bound() {
    let bound = RefCell::new(Vec::new());
    let crossed = SqlBytesComparison::<Probe<'_>, sqlx::Sqlite>::try_from_filter_with(
      BytesFilter::<i64>::new()
        .with_eq(1)
        .with_contains(2)
        .with_not_contains(3)
        .with_in_([4, 5]),
      |value| {
        Ok::<_, core::convert::Infallible>(Probe {
          value,
          bound: &bound,
        })
      },
    )
    .unwrap();

    threaded::<sqlx::Sqlite, _>("h", &crossed);

    assert_eq!(*bound.borrow(), [1, 2, 3, 4, 5]);
  }
}

/// The two remaining dialects put the operand FIRST — `position(? in col)` and `LOCATE(?, col)` —
/// where SQLite's `instr(col, ?)` puts the column first. Getting that order backwards is a
/// predicate that answers about the wrong side and never fails.
#[cfg(feature = "postgres")]
mod postgres {
  use super::SqlBytesComparison;
  use crate::{
    BytesFilter,
    comparison::{
      TryFromFilter,
      sql::tests::{render, threaded},
    },
  };

  #[test]
  fn a_byte_substring_is_position_with_the_operand_first() {
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::Postgres>::try_from_filter(
      BytesFilter::<Vec<u8>>::new().with_not_contains(vec![0x89]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("h", &crossed),
      ("NOT ( position($1 in \"h\") > 0 )".to_owned(), 1)
    );
  }

  /// The WHOLE walk, on this dialect's own impl. The six comparison operators and the two membership
  /// lists come from a shared body and the byte match does not, so a rendering assertion that
  /// covered only the leaf would not notice the shared half being wired into one impl and not
  /// another.
  #[test]
  fn every_operator_renders_its_own_conjunct() {
    let filter = BytesFilter::<Vec<u8>>::new()
      .with_eq(vec![1])
      .with_ne(vec![2])
      .with_gt(vec![3])
      .with_gte(vec![4])
      .with_lt(vec![5])
      .with_lte(vec![6])
      .with_contains(vec![7])
      .with_not_contains(vec![8])
      .with_in_([vec![9], vec![10]])
      .with_not_in([vec![11]]);
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::Postgres>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 10);
    assert_eq!(
      render::<sqlx::Postgres, _>("h", &crossed),
      (
        "\"h\" = $1 AND NOT ( \"h\" = $2 ) AND \"h\" > $3 AND \"h\" >= $4 AND \"h\" < $5 AND \
         \"h\" <= $6 AND position($7 in \"h\") > 0 AND NOT ( position($8 in \"h\") > 0 ) AND \
         \"h\" IN ($9, $10) AND NOT ( \"h\" IN ($11) )"
          .to_owned(),
        11
      )
    );
  }

  /// The threaded lowering reaches THIS dialect's leaf: `position`, with the operand FIRST.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::Postgres>::try_from_filter(
      BytesFilter::<Vec<u8>>::new()
        .with_eq(vec![1])
        .with_contains(vec![7])
        .with_in_([vec![9], vec![10]]),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::Postgres, _>("h", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE \"h\" = $1 AND position($2 in \"h\") > 0 AND \
       \"h\" IN ($3, $4)"
    );
  }
}

#[cfg(feature = "mysql")]
mod mysql {
  use super::SqlBytesComparison;
  use crate::{
    BytesFilter,
    comparison::{
      TryFromFilter,
      sql::tests::{render, threaded},
    },
  };

  #[test]
  fn a_byte_substring_is_locate_with_the_operand_first() {
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::MySql>::try_from_filter(
      BytesFilter::<Vec<u8>>::new().with_contains(vec![0x89]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::MySql, _>("h", &crossed),
      ("LOCATE(?, `h`) > 0".to_owned(), 1)
    );
  }

  /// The WHOLE walk, on this dialect's own impl — see the Postgres twin for what a leaf-only
  /// assertion would miss.
  #[test]
  fn every_operator_renders_its_own_conjunct() {
    let filter = BytesFilter::<Vec<u8>>::new()
      .with_eq(vec![1])
      .with_ne(vec![2])
      .with_gt(vec![3])
      .with_gte(vec![4])
      .with_lt(vec![5])
      .with_lte(vec![6])
      .with_contains(vec![7])
      .with_not_contains(vec![8])
      .with_in_([vec![9], vec![10]])
      .with_not_in([vec![11]]);
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::MySql>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 10);
    assert_eq!(
      render::<sqlx::MySql, _>("h", &crossed),
      (
        "`h` = ? AND NOT ( `h` = ? ) AND `h` > ? AND `h` >= ? AND `h` < ? AND `h` <= ? AND \
         LOCATE(?, `h`) > 0 AND NOT ( LOCATE(?, `h`) > 0 ) AND `h` IN (?, ?) AND \
         NOT ( `h` IN (?) )"
          .to_owned(),
        11
      )
    );
  }

  /// The threaded lowering reaches THIS dialect's leaf: `LOCATE`, with the operand FIRST.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = SqlBytesComparison::<Vec<u8>, sqlx::MySql>::try_from_filter(
      BytesFilter::<Vec<u8>>::new()
        .with_eq(vec![1])
        .with_contains(vec![7])
        .with_in_([vec![9], vec![10]]),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::MySql, _>("h", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE `h` = ? AND LOCATE(?, `h`) > 0 AND `h` IN (?, ?)"
    );
  }
}