crates/kleene-datalog/tests/id_relations.rs
//! The id relations of the core from the Datalog side: a vertex table's `(row, id)` by
//! arithmetic ([`IdShift`]), the rows of a table whose ids lie in a range ([`IdRanges`] in
//! rows mode) and the ids a name index gives ([`NameHits`]), each joined in a rule; against
//! plain loops.
use std::collections::BTreeSet;
use std::sync::Arc;
use kleene_datalog::{
Engine, Facts, IdRanges, IdShift, Inputs, NameHits, NameIndex, Program, Term, ge,
};
use kleene_sparse::{CpuBackend, CpuDevice};
const BASE: u64 = 500;
const ROWS: u64 = 40;
fn name(r: u64) -> String {
format!("n{}", r % 7)
}
#[derive(Debug)]
struct Names;
impl NameIndex for Names {
fn nodes(&self, s: &str, out: &mut dyn FnMut(u32)) -> kleene_datalog::Result<()> {
for r in 0..ROWS {
if name(r) == s {
out((BASE + r) as u32);
}
}
Ok(())
}
}
#[tokio::test]
async fn rows_ids_and_names_as_relations() {
let mut p = Program::new();
// size(Row, S): a table's column by row
let size = p.input::<2>("size");
let shift = p.external::<2>("id of row");
let window = p.external::<1>("rows of ids 510..=519");
let named = p.external::<1>("ids named n3, n5");
let by_id = p.derived::<2>("by_id");
let some = p.derived::<2>("some");
let both = p.derived::<1>("both");
let [r, i, s] = ["R", "I", "S"].map(|n| p.var(n));
// by_id(I, S) :- size(R, S), id_of_row(R, I), S >= 10.
p.rule(
by_id.at([i, s]),
[
size.at([r, s]).into(),
shift.at([r, i]).into(),
ge(s, Term::Const(10)),
],
)
.unwrap();
// some(R, S) :- rows_of_ids(R), size(R, S).
p.rule(some.at([r, s]), [window.at([r]), size.at([r, s])])
.unwrap();
// both(I) :- named(I), by_id(I, S).
p.rule(both.at([i]), [named.at([i]), by_id.at([i, s])])
.unwrap();
let mut inputs = Inputs::new();
inputs
.facts(
&size,
Facts::from_rows(2, (0..ROWS).map(|r| [r, (r * 3) % 17])).unwrap(),
)
.unwrap();
inputs
.external(&shift, Arc::new(IdShift::new(BASE, Some(ROWS))))
.unwrap();
inputs
.external(
&window,
Arc::new(IdRanges::new([(BASE, ROWS)], [(BASE + 10, BASE + 19)]).rows()),
)
.unwrap();
inputs
.external(
&named,
Arc::new(NameHits::new(
Arc::new(Names),
vec!["n3".into(), "n5".into()],
)),
)
.unwrap();
let out = Engine::<CpuBackend>::new(CpuDevice::new(2))
.run(&p, &inputs)
.await
.unwrap();
let rows =
|f: Option<&kleene_datalog::Facts>| -> BTreeSet<Vec<u64>> { f.unwrap().rows().collect() };
let want_by_id: BTreeSet<Vec<u64>> = (0..ROWS)
.filter(|r| (r * 3) % 17 >= 10)
.map(|r| vec![BASE + r, (r * 3) % 17])
.collect();
assert_eq!(rows(out.get(&by_id)), want_by_id);
let want_some: BTreeSet<Vec<u64>> = (10..20).map(|r| vec![r, (r * 3) % 17]).collect();
assert_eq!(rows(out.get(&some)), want_some);
let want_both: BTreeSet<Vec<u64>> = want_by_id
.iter()
.filter(|x| ["n3", "n5"].contains(&name(x[0] - BASE).as_str()))
.map(|x| vec![x[0]])
.collect();
assert!(!want_both.is_empty());
assert_eq!(rows(out.get(&both)), want_both);
}