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::SqlTextComparison;
use crate::{TextFilter, comparison::TryFromFilter};

/// A column stored case-folded — 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 folded(text: String) -> Result<String, Infallible> {
  Ok(text.to_lowercase())
}

/// The crossing carries DOMAIN values in and leaves STORAGE values behind, and it does so for all
/// twenty slots — the substring operands are not a separate vocabulary.
#[test]
fn a_crossing_replaces_every_operand_with_its_stored_form() {
  let filter = TextFilter::<String>::new()
    .with_eq("Camera".to_owned())
    .with_starts_with("Cam".to_owned())
    .with_not_ends_with_nocase("RAW".to_owned())
    .with_in_(["A".to_owned(), "B".to_owned()]);

  let crossed = SqlTextComparison::<String, ()>::try_from_filter_with(filter, folded).unwrap();

  assert_eq!(crossed.eq().map(String::as_str), Some("camera"));
  assert_eq!(crossed.starts_with().map(String::as_str), Some("cam"));
  assert_eq!(
    crossed.not_ends_with_nocase().map(String::as_str),
    Some("raw")
  );
  assert_eq!(crossed.in_().unwrap(), ["a".to_owned(), "b".to_owned()]);
}

/// The identity crossing keeps its promise in the TYPE, and stops compiling the moment the crossing
/// acquires a way to fail.
#[test]
fn the_identity_crossing_cannot_fail() {
  let crossed: Result<SqlTextComparison<String, ()>, Infallible> =
    SqlTextComparison::try_from_filter(TextFilter::<String>::new().with_contains("cam".to_owned()));
  assert_eq!(crossed.unwrap().contains().map(String::as_str), Some("cam"));
}

/// Every one of the twenty slots is its own conjunct, and an absent operator is none.
#[test]
fn each_set_operator_is_one_conjunct() {
  let empty =
    SqlTextComparison::<String, ()>::try_from_filter(TextFilter::<String>::new()).unwrap();
  assert!(empty.is_empty());
  assert_eq!(empty.conjuncts(), 0);

  let three = SqlTextComparison::<String, ()>::try_from_filter(
    TextFilter::<String>::new()
      .with_gte("a".to_owned())
      .with_contains_nocase("b".to_owned())
      .with_not_in(["c".to_owned()]),
  )
  .unwrap();
  assert_eq!(three.conjuncts(), 3);
}

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

  use super::{SqlTextComparison, folded};
  use crate::{
    TextFilter,
    comparison::{
      TryFromFilter,
      sql::tests::{Probe, render, threaded},
    },
  };

  #[test]
  fn every_operator_renders_its_own_conjunct() {
    let filter = TextFilter::<String>::new()
      .with_eq("a".to_owned())
      .with_ne("b".to_owned())
      .with_gt("c".to_owned())
      .with_gte("d".to_owned())
      .with_lt("e".to_owned())
      .with_lte("f".to_owned())
      .with_contains("g".to_owned())
      .with_contains_nocase("h".to_owned())
      .with_not_contains("i".to_owned())
      .with_not_contains_nocase("j".to_owned())
      .with_starts_with("k".to_owned())
      .with_starts_with_nocase("l".to_owned())
      .with_not_starts_with("m".to_owned())
      .with_not_starts_with_nocase("n".to_owned())
      .with_ends_with("o".to_owned())
      .with_ends_with_nocase("p".to_owned())
      .with_not_ends_with("q".to_owned())
      .with_not_ends_with_nocase("r".to_owned())
      .with_in_(["s".to_owned(), "t".to_owned()])
      .with_not_in(["u".to_owned()]);
    let crossed = SqlTextComparison::<String, sqlx::Sqlite>::try_from_filter(filter).unwrap();

    assert_eq!(crossed.conjuncts(), 20);
    // The affix binds are why the count outruns the conjuncts: a prefix or a suffix measures the
    // operand and then compares it, so each binds TWICE.
    let (sql, binds) = render::<sqlx::Sqlite, _>("n", &crossed);
    assert_eq!(binds, 6 + 4 + 8 * 2 + 3);
    assert_eq!(
      sql,
      "\"n\" = ? AND NOT ( \"n\" = ? ) AND \"n\" > ? AND \"n\" >= ? AND \"n\" < ? AND \
       \"n\" <= ? AND instr(\"n\", ?) > 0 AND instr(lower(\"n\"), lower(?)) > 0 AND \
       NOT ( instr(\"n\", ?) > 0 ) AND NOT ( instr(lower(\"n\"), lower(?)) > 0 ) AND \
       substr(\"n\", 1, length(?)) = ? AND substr(lower(\"n\"), 1, length(lower(?))) = lower(?) AND \
       NOT ( substr(\"n\", 1, length(?)) = ? ) AND \
       NOT ( substr(lower(\"n\"), 1, length(lower(?))) = lower(?) ) AND \
       substr(\"n\", -length(?)) = ? AND substr(lower(\"n\"), -length(lower(?))) = lower(?) AND \
       NOT ( substr(\"n\", -length(?)) = ? ) AND \
       NOT ( substr(lower(\"n\"), -length(lower(?))) = lower(?) ) AND \
       \"n\" IN (?, ?) AND NOT ( \"n\" IN (?) )"
    );
  }

  /// Case folding is applied to BOTH sides or to neither. A comparison between a folded column and
  /// an unfolded operand is not case-insensitivity — it is a query that misses every row whose
  /// operand had a capital in it.
  #[test]
  fn a_case_insensitive_match_folds_both_sides() {
    let plain = SqlTextComparison::<String, sqlx::Sqlite>::try_from_filter(
      TextFilter::<String>::new().with_contains("cam".to_owned()),
    )
    .unwrap();
    let folding = SqlTextComparison::<String, sqlx::Sqlite>::try_from_filter(
      TextFilter::<String>::new().with_contains_nocase("cam".to_owned()),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &plain),
      ("instr(\"n\", ?) > 0".to_owned(), 1)
    );
    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &folding),
      ("instr(lower(\"n\"), lower(?)) > 0".to_owned(), 1)
    );
  }

  /// The declared-converter path and the trait path reach the same builder.
  #[test]
  fn a_declared_converter_renders_what_the_trait_path_does() {
    let declared = SqlTextComparison::<String, sqlx::Sqlite>::try_from_filter_with(
      TextFilter::<String>::new().with_eq("CAMERA".to_owned()),
      folded,
    )
    .unwrap();
    let plain = SqlTextComparison::<String, sqlx::Sqlite>::try_from_filter(
      TextFilter::<String>::new().with_eq("camera".to_owned()),
    )
    .unwrap();

    assert_eq!(declared, plain);
  }

  /// A borrowed operand is the same struct with a different `V`: `&String` is `Carrier` through the
  /// reference blanket and `AsRef<str>` through `String`'s own, so the borrowed text comparison
  /// needs no lifetime and no parallel family.
  #[test]
  fn a_borrowed_operand_lowers_as_the_owned_one_does() {
    let owned = SqlTextComparison::<String, sqlx::Sqlite>::try_from_filter(
      TextFilter::<String>::new().with_starts_with("cam".to_owned()),
    )
    .unwrap();
    let value = "cam".to_owned();
    let borrowed = SqlTextComparison::<&String, sqlx::Sqlite>::try_from_filter(
      TextFilter::<&String>::new().with_starts_with(&value),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Sqlite, _>("n", &owned),
      render::<sqlx::Sqlite, _>("n", &borrowed)
    );
  }

  /// The threaded lowering reaches THIS dialect's leaf — `instr`, not either `LIKE` — and its
  /// conjuncts land in the accumulator it was handed, whose lead opened the clause.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = SqlTextComparison::<String, sqlx::Sqlite>::try_from_filter(
      TextFilter::<String>::new()
        .with_eq("a".to_owned())
        .with_contains("c".to_owned())
        .with_starts_with("d".to_owned())
        .with_in_(["e".to_owned(), "f".to_owned()]),
    )
    .unwrap();

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

  /// Every operand the comparison holds reaches the builder, in slot order — and the affix operand
  /// twice, because this dialect's prefix form measures it and then compares it. The SQL says only
  /// that a `?` is there; which operand went into it is what a threaded walk can silently change.
  #[test]
  fn every_operand_the_comparison_holds_is_bound() {
    let bound = RefCell::new(Vec::new());
    let crossed = SqlTextComparison::<Probe<'_>, sqlx::Sqlite>::try_from_filter_with(
      TextFilter::<i64>::new()
        .with_eq(1i64)
        .with_contains(2i64)
        .with_starts_with(3i64)
        .with_in_([4i64, 5]),
      |value| {
        Ok::<_, Infallible>(Probe {
          value,
          bound: &bound,
        })
      },
    )
    .unwrap();

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

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

/// The `LIKE` dialects render the three affixes BYTE-IDENTICALLY and differ only in the bound
/// pattern, which the rendered text cannot show — so this asserts what it can (the operator, the
/// escape clause, the bind count) and `dialect::tests` asserts the pattern.
#[cfg(feature = "postgres")]
mod postgres {
  use super::SqlTextComparison;
  use crate::{
    TextFilter,
    comparison::{
      TryFromFilter,
      sql::tests::{render, threaded},
    },
  };

  #[test]
  fn the_three_affixes_render_one_form_and_differ_in_the_operand() {
    for filter in [
      TextFilter::<String>::new().with_contains("cam".to_owned()),
      TextFilter::<String>::new().with_starts_with("cam".to_owned()),
      TextFilter::<String>::new().with_ends_with("cam".to_owned()),
    ] {
      let crossed = SqlTextComparison::<String, sqlx::Postgres>::try_from_filter(filter).unwrap();
      assert_eq!(
        render::<sqlx::Postgres, _>("n", &crossed),
        ("\"n\" LIKE $1 ESCAPE '\\'".to_owned(), 1)
      );
    }
  }

  /// The shared half and this dialect's leaf in ONE rendering. The six comparison operators and the
  /// two membership lists come from a slot walk every impl calls and the affix does not, so a
  /// leaf-only assertion cannot tell a walk wired into this impl from one wired into none.
  #[test]
  fn the_shared_slots_render_beside_the_dialect_leaf() {
    let crossed = SqlTextComparison::<String, sqlx::Postgres>::try_from_filter(
      TextFilter::<String>::new()
        .with_eq("a".to_owned())
        .with_gte("b".to_owned())
        .with_contains("c".to_owned())
        .with_in_(["d".to_owned(), "e".to_owned()]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("n", &crossed),
      (
        "\"n\" = $1 AND \"n\" >= $2 AND \"n\" LIKE $3 ESCAPE '\\' AND \"n\" IN ($4, $5)".to_owned(),
        5
      )
    );
  }

  /// Case insensitivity is a second OPERATOR here rather than a fold, and negation still wraps.
  #[test]
  fn case_insensitivity_is_ilike_and_negation_still_wraps() {
    let nocase = SqlTextComparison::<String, sqlx::Postgres>::try_from_filter(
      TextFilter::<String>::new().with_not_contains_nocase("cam".to_owned()),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::Postgres, _>("n", &nocase),
      ("NOT ( \"n\" ILIKE $1 ESCAPE '\\' )".to_owned(), 1)
    );
  }

  /// The threaded lowering reaches THIS dialect's leaf — `ILIKE` for the case-insensitive form,
  /// which is an operator no other dialect here spells.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = SqlTextComparison::<String, sqlx::Postgres>::try_from_filter(
      TextFilter::<String>::new()
        .with_eq("a".to_owned())
        .with_contains("c".to_owned())
        .with_contains_nocase("d".to_owned()),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::Postgres, _>("n", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE \"n\" = $1 AND \"n\" LIKE $2 ESCAPE '\\' AND \
       \"n\" ILIKE $3 ESCAPE '\\'"
    );
  }
}

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

  /// MySQL folds with `LOWER` on both sides rather than with a second operator, and its `ESCAPE`
  /// literal carries a DOUBLED backslash — MySQL parses backslash escapes inside string literals,
  /// which Postgres does not.
  #[test]
  fn the_escape_literal_is_doubled_and_the_fold_is_a_function() {
    let plain = SqlTextComparison::<String, sqlx::MySql>::try_from_filter(
      TextFilter::<String>::new().with_contains("cam".to_owned()),
    )
    .unwrap();
    let nocase = SqlTextComparison::<String, sqlx::MySql>::try_from_filter(
      TextFilter::<String>::new().with_contains_nocase("cam".to_owned()),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::MySql, _>("n", &plain),
      ("`n` LIKE ? ESCAPE '\\\\'".to_owned(), 1)
    );
    assert_eq!(
      render::<sqlx::MySql, _>("n", &nocase),
      ("LOWER(`n`) LIKE LOWER(?) ESCAPE '\\\\'".to_owned(), 1)
    );
  }

  /// The shared half and this dialect's leaf in ONE rendering — see the Postgres twin for what a
  /// leaf-only assertion would miss.
  #[test]
  fn the_shared_slots_render_beside_the_dialect_leaf() {
    let crossed = SqlTextComparison::<String, sqlx::MySql>::try_from_filter(
      TextFilter::<String>::new()
        .with_eq("a".to_owned())
        .with_gte("b".to_owned())
        .with_contains("c".to_owned())
        .with_in_(["d".to_owned(), "e".to_owned()]),
    )
    .unwrap();

    assert_eq!(
      render::<sqlx::MySql, _>("n", &crossed),
      (
        "`n` = ? AND `n` >= ? AND `n` LIKE ? ESCAPE '\\\\' AND `n` IN (?, ?)".to_owned(),
        5
      )
    );
  }

  /// The threaded lowering reaches THIS dialect's leaf — the doubled `ESCAPE` literal and the
  /// `LOWER` fold, neither of which any other dialect here writes.
  #[test]
  fn the_threaded_lowering_renders_this_dialect_leaf() {
    let crossed = SqlTextComparison::<String, sqlx::MySql>::try_from_filter(
      TextFilter::<String>::new()
        .with_eq("a".to_owned())
        .with_contains("c".to_owned())
        .with_contains_nocase("d".to_owned()),
    )
    .unwrap();

    assert_eq!(
      threaded::<sqlx::MySql, _>("n", &crossed),
      "SELECT \"id\" FROM \"t\" WHERE `n` = ? AND `n` LIKE ? ESCAPE '\\\\' AND \
       LOWER(`n`) LIKE LOWER(?) ESCAPE '\\\\'"
    );
  }
}