crates/kleene-datalog/tests/wide.rs
//! Several columns of one node type as one relation by name: `L@(k1, k2, ..)` = (id, k1..kn)
//! (kleene-plan's `Catalog::columns`), one relation over the type's columns side by side,
//! read with `input ... from cat` and bound by `Inputs::bind`. The answer checked against the
//! same rule over one relation per column and a plain loop; the refusals by name.
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::sync::Arc;
use arrow_array::{ArrayRef, UInt64Array};
use graphar::mapped::{IntColumn, IntGraphWriter};
use kleene_datalog::{Catalog, Engine, Inputs, Program, Source, Type, datalog};
use kleene_gar::GarGraph;
use kleene_sparse::{CpuBackend, CpuDevice};
const N: u32 = 40;
const NAMES: [&str; 4] = ["ann", "bo", "cy", "di"];
/// Column `a` of row `r`, and `b`.
fn a(r: u64) -> u64 {
r * 7 % 10
}
fn b(r: u64) -> u64 {
r * 3 % 11
}
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn set(test: &str) -> TempDir {
let dir =
std::env::temp_dir().join(format!("kleene-datalog-wide-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut w = IntGraphWriter::new(&dir, "X").unwrap();
let col = |f: fn(u64) -> u64| IntColumn::U32((0..N as u64).map(|r| f(r) as u32).collect());
let mut offsets = vec![0u32];
let mut bytes = Vec::new();
for r in 0..N as usize {
bytes.extend_from_slice(NAMES[r % 4].as_bytes());
offsets.push(bytes.len() as u32);
}
w.vertices(
"t",
N,
vec![
("a".to_string(), col(a)),
("b".to_string(), col(b)),
("name".to_string(), IntColumn::Bytes { offsets, bytes }),
],
)
.unwrap();
w.vertices("u", 3, vec![]).unwrap();
w.finish().unwrap();
TempDir(dir)
}
async fn rows<const K: usize>(
p: &Program,
cat: &Catalog,
rel: kleene_datalog::Rel<K>,
) -> BTreeSet<Vec<u64>> {
let mut inputs = Inputs::new();
inputs.bind(p, cat).unwrap();
let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
let out = e.run(p, &inputs).await.unwrap();
out.get(&rel).unwrap().rows().collect()
}
mod names {
pub const T_AB: &str = "t@(a, b)";
}
#[tokio::test]
async fn columns_side_by_side_as_one_relation_by_name() {
let dir = set("one");
let g = GarGraph::open(&dir.0).unwrap();
let cat = g.catalog().unwrap();
let base = g.id_space().unwrap().base("t").unwrap();
let mut p = Program::new();
let r = datalog!(&mut p =>
input t_ab/3 from cat "t@(a, b)", t_ba/3 from cat {names::T_AB}.
input t_an/3 (u64, u64, str) from cat "t@(a,name)".
derived w/3, f/2.
w(I, A, B) :- t_ab(I, A, B).
f(I, B) :- t_ba(I, A, B), A == 7.
)
.unwrap();
assert_eq!(p.relation_info(r.t_ab.id()).name, "t@(a, b)");
assert_eq!(p.types(r.t_an.id()), [Type::U64, Type::U64, Type::Str]);
let wide = rows(&p, &cat, r.w).await;
let filtered = rows(&p, &cat, r.f).await;
// the same rules over one relation per column
let mut q = Program::new();
let s = datalog!(&mut q =>
input ta/2 from cat "t.a", tb/2 from cat "t.b".
derived w/3, f/2.
w(I, A, B) :- ta(I, A), tb(I, B).
f(I, B) :- ta(I, A), tb(I, B), A == 7.
)
.unwrap();
assert_eq!(wide, rows(&q, &cat, s.w).await);
assert_eq!(filtered, rows(&q, &cat, s.f).await);
// the plain loop
let want: BTreeSet<Vec<u64>> = (0..N as u64).map(|r| vec![base + r, a(r), b(r)]).collect();
assert_eq!(wide, want);
let want_f: BTreeSet<Vec<u64>> = (0..N as u64)
.filter(|&r| a(r) == 7)
.map(|r| vec![base + r, b(r)])
.collect();
assert_eq!(filtered, want_f);
assert_eq!(want_f.len(), 4);
}
#[test]
fn what_is_not_one_relation_is_refused_by_name() {
let dir = set("refused");
let cat = GarGraph::open(&dir.0).unwrap().catalog().unwrap();
let err = |name: &str| cat.relation(name).unwrap_err().to_string();
for (name, says) in [
("t@(a, zz)", "zz"),
("t@(a, a)", "twice"),
("t@()", "no column"),
("nope@(a)", "nope"),
("u@(a)", "property `a`"),
] {
let e = err(name);
assert!(e.contains(says), "{name}: {e}");
}
assert!(cat.relation("t@(a, b").is_err());
// two properties whose ids are not one array: not side by side
let ids = |v: Vec<u64>| -> ArrayRef { Arc::new(UInt64Array::from(v)) };
let mut c = Catalog::new();
c.label("p", Source::Columns(vec![ids(vec![0, 1])]));
c.property(
"p",
"x",
Source::Columns(vec![ids(vec![0, 1]), ids(vec![5, 6])]),
);
c.property(
"p",
"y",
Source::Columns(vec![ids(vec![0, 1]), ids(vec![7, 8])]),
);
let e = c.relation("p@(x, y)").unwrap_err().to_string();
assert!(e.contains("side by side"), "{e}");
let shared = ids(vec![0, 1]);
c.property(
"p",
"x",
Source::Columns(vec![shared.clone(), ids(vec![5, 6])]),
);
c.property("p", "y", Source::Columns(vec![shared, ids(vec![7, 8])]));
let (_, types) = c.relation("p@(x, y)").unwrap();
assert_eq!(types, [Type::U64, Type::U64, Type::U64]);
}