crates/kleene-gql/tests/kinds.rs
//! Labels of some of a label's nodes (kind labels, [`Catalog::sub_label`]): their nodes'
//! properties are the label's, `labels(n)` lists them for a node found by the label, and a
//! node with no label is found by the property indexes of every label holding the key.
//! Each answer against a plain loop over the rows.
use std::collections::BTreeSet;
use std::sync::Arc;
use arrow_array::{ArrayRef, StringArray, UInt64Array};
use kleene_gql::{Catalog, Entity, NameIndex, Params, lower_with, parse};
use kleene_plan::{Datum, Engine, External, Facts, Source, Type, Value};
use kleene_sparse::{CpuBackend, CpuDevice};
/// Functions, ids 0..6: (name, kind).
const FUNCS: [(&str, u64); 6] = [
("main", 0),
("lex", 1),
("parse", 2),
("lex", 1),
("eval", 2),
("emit", 0),
];
/// Files, ids 6..8: kind.
const FILES: [u64; 2] = [1, 3];
/// Calls between functions.
const CALLS: [(u64, u64); 5] = [(0, 1), (0, 2), (2, 3), (2, 4), (4, 5)];
/// (id, value) answered for a range of values: a property index.
#[derive(Debug)]
struct Range(Vec<(u64, u64)>);
impl External for Range {
fn arity(&self) -> usize {
3
}
fn can(&self, bound: u64) -> bool {
bound & 0b11 == 0b11
}
fn lookup(
&self,
_bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> kleene_plan::Result<()> {
for (k, (&lo, &hi)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
for &(id, v) in &self.0 {
if (lo..=hi).contains(&v) {
out(k, &[lo, hi, id]);
}
}
}
Ok(())
}
}
/// The functions by name: a name index.
#[derive(Debug)]
struct Names;
impl NameIndex for Names {
fn nodes(&self, name: &str, out: &mut dyn FnMut(u32)) -> kleene_plan::Result<()> {
for (i, f) in FUNCS.iter().enumerate() {
if f.0 == name {
out(i as u32);
}
}
Ok(())
}
}
fn ids(xs: impl IntoIterator<Item = u64>) -> ArrayRef {
Arc::new(UInt64Array::from_iter_values(xs))
}
/// One id space; with `file_index`, files' kinds have a range index too.
fn catalog(file_index: bool) -> Catalog {
let mut c = Catalog::new();
let kinds: Vec<(u64, u64)> = FUNCS
.iter()
.enumerate()
.map(|(i, f)| (i as u64, f.1))
.collect();
c.label("func", Source::Columns(vec![ids(0..6)]))
.label("file", Source::Columns(vec![ids(6..8)]))
.typed_property(
"func",
"name",
Source::Columns(vec![
ids(0..6),
Arc::new(StringArray::from_iter_values(FUNCS.iter().map(|f| f.0))),
]),
Type::Str,
)
.property(
"func",
"kind",
Source::Columns(vec![ids(0..6), ids(FUNCS.iter().map(|f| f.1))]),
)
.property("file", "kind", Source::Columns(vec![ids(6..8), ids(FILES)]))
.property_index("func", "kind", Source::External(Arc::new(Range(kinds))))
.name_index("func", "name", Arc::new(Names))
.edge(
"calls",
Source::Facts(Facts::from_rows(2, CALLS.iter().map(|&(a, b)| [a, b])).unwrap()),
);
if file_index {
let files: Vec<(u64, u64)> = FILES
.iter()
.enumerate()
.map(|(i, &k)| (6 + i as u64, k))
.collect();
c.property_index("file", "kind", Source::External(Arc::new(Range(files))));
}
for k in 0..3 {
let label = format!("func_kind_{k}");
let of: Vec<u64> = (0..6).filter(|&i| FUNCS[i as usize].1 == k).collect();
c.label(&label, Source::Columns(vec![ids(of)]));
c.sub_label(&label, "func");
}
c
}
fn engine() -> Engine<CpuBackend> {
Engine::new(CpuDevice::new(2))
}
async fn rows(c: &Catalog, text: &str) -> (Vec<Vec<u64>>, String) {
let l = lower_with(&parse(text).unwrap(), c, &Params::new())
.unwrap_or_else(|e| panic!("{text}: {e}"));
let explain = l.explain().unwrap();
let t = l.run(&engine()).await.unwrap();
(t.rows, explain)
}
#[tokio::test]
async fn a_kind_label_s_nodes_have_the_label_s_properties() {
let c = catalog(true);
let l = lower_with(
&parse("MATCH (f:func_kind_1) RETURN f.kind, f.name, f").unwrap(),
&c,
&Params::new(),
)
.unwrap();
let t = l.run_typed(&engine()).await.unwrap();
let mut want = Vec::new();
for (i, f) in FUNCS.iter().enumerate().filter(|f| f.1.1 == 1) {
want.push(vec![Datum::U64(f.1), Datum::Str(f.0.into())]);
let _ = i;
}
let got: Vec<Vec<Datum>> = t.rows.iter().map(|r| r[..2].to_vec()).collect();
assert_eq!(got, want);
// the whole node: its label and the kind label, the label's properties
for (r, (i, f)) in FUNCS.iter().enumerate().filter(|f| f.1.1 == 1).enumerate() {
assert_eq!(
t.entity(r, 2),
Some(&Entity::Node {
id: i as u64,
labels: vec!["func".into(), "func_kind_1".into()],
properties: vec![
("kind".into(), Datum::U64(f.1)),
("name".into(), Datum::Str(f.0.into())),
],
})
);
}
// a condition on such a property, and the kind label's nodes only
let (got, _) = rows(
&c,
"MATCH (f:func_kind_2) WHERE f.name <> 'eval' RETURN id(f)",
)
.await;
let want: Vec<Vec<u64>> = (0..6)
.filter(|&i| FUNCS[i as usize].1 == 2 && FUNCS[i as usize].0 != "eval")
.map(|i| vec![i])
.collect();
assert_eq!(got, want);
let (got, _) = rows(&c, "MATCH (f:func_kind_1 {name: 'lex'}) RETURN count(*)").await;
assert_eq!(got, vec![vec![2]]);
let (got, _) = rows(&c, "MATCH (f:func_kind_0 {name: 'lex'}) RETURN count(*)").await;
assert_eq!(got, vec![vec![0]]);
}
#[tokio::test]
async fn labels_of_a_node_found_by_its_label_list_its_kind_labels() {
// In a catalog of vertex tables: Book rows 0..3, kind labels of some of them.
let mut c = Catalog::new();
let rows32 = |xs: &[u32]| -> Source {
Source::Columns(vec![Arc::new(arrow_array::UInt32Array::from(xs.to_vec()))])
};
c.label("Book", rows32(&[0, 1, 2]))
.vertex_table("Book", 0, 3)
.label("Book_kind_1", rows32(&[0, 2]))
.id_base("Book_kind_1", 0)
.sub_label("Book_kind_1", "Book")
.label("Book_kind_2", rows32(&[1]))
.id_base("Book_kind_2", 0)
.sub_label("Book_kind_2", "Book");
let t = lower_with(
&parse("MATCH (b:Book) RETURN labels(b)").unwrap(),
&c,
&Params::new(),
)
.unwrap()
.run(&engine())
.await
.unwrap();
let got: Vec<Entity> = (0..3).map(|r| t.entity(r, 0).unwrap().clone()).collect();
let want: Vec<Entity> = ["Book_kind_1", "Book_kind_2", "Book_kind_1"]
.iter()
.map(|k| Entity::Labels(vec!["Book".into(), k.to_string()]))
.collect();
assert_eq!(got, want);
}
#[tokio::test]
async fn a_node_with_no_label_is_found_by_the_indexes_of_its_key() {
let c = catalog(true);
let kind_of = |id: u64| -> u64 {
if id < 6 {
FUNCS[id as usize].1
} else {
FILES[id as usize - 6]
}
};
for k in 0..4 {
let (got, explain) = rows(&c, &format!("MATCH (n) WHERE n.kind = {k} RETURN id(n)")).await;
let want: Vec<Vec<u64>> = (0..8)
.filter(|&i| kind_of(i) == k)
.map(|i| vec![i])
.collect();
assert_eq!(got, want, "kind {k}");
assert!(
explain.contains("(n): index lookup file|func.kind in"),
"{explain}"
);
}
let (got, explain) = rows(
&c,
"MATCH (n) WHERE n.kind >= 1 AND n.kind < 3 RETURN id(n)",
)
.await;
let want: Vec<Vec<u64>> = (0..8)
.filter(|&i| (1..3).contains(&kind_of(i)))
.map(|i| vec![i])
.collect();
assert_eq!(got, want);
assert!(
explain.contains("index lookup file|func.kind in 1..=2"),
"{explain}"
);
// At an edge's end, with no label.
let (got, explain) = rows(
&c,
"MATCH (a)-[:calls]->(n) WHERE n.kind = 2 RETURN id(a), id(n)",
)
.await;
let want: Vec<Vec<u64>> = CALLS
.iter()
.filter(|e| kind_of(e.1) == 2)
.map(|&(a, b)| vec![a, b])
.collect();
assert_eq!(got, want);
assert!(
explain.contains("(n): index lookup file|func.kind"),
"{explain}"
);
// A string key only functions have: their name index.
let (got, explain) = rows(&c, "MATCH (n {name: 'lex'}) RETURN id(n)").await;
let want: Vec<Vec<u64>> = (0..6)
.filter(|&i| FUNCS[i as usize].0 == "lex")
.map(|i| vec![i])
.collect();
assert_eq!(got, want);
assert!(explain.contains("(n): name index func.name"), "{explain}");
// A label holding the key with no index: no index lookup, the same rows.
let c = catalog(false);
let (got, explain) = rows(&c, "MATCH (n) WHERE n.kind = 1 RETURN id(n)").await;
let want: BTreeSet<u64> = (0..8).filter(|&i| kind_of(i) == 1).collect();
assert_eq!(got, want.iter().map(|&i| vec![i]).collect::<Vec<_>>());
assert!(!explain.contains("index lookup"), "{explain}");
}