crates/kleene-gql/tests/ids.rs
//! `id(n)` lookups in a catalog of one id space whose labels are blocks of ids
//! ([`Catalog::id_block`]): an equality, a range, an OR of ids and an id beyond the last
//! label list the ids from the numbers, no label read (each label's source counts the rows
//! it gives), against a plain filter over every id.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use kleene_gql::{Catalog, Params, lower_with, parse};
use kleene_plan::{Engine, External, Source, Value};
use kleene_sparse::{CpuBackend, CpuDevice};
/// The ids `base..base + count`, counting the rows it gives.
#[derive(Debug)]
struct Ids {
base: u64,
count: u64,
read: Arc<AtomicUsize>,
}
impl External for Ids {
fn arity(&self) -> usize {
1
}
fn can(&self, _bound: u64) -> bool {
true
}
fn lookup(
&self,
bound: u64,
keys: &[&[Value]],
n: usize,
out: &mut dyn FnMut(usize, &[Value]),
) -> kleene_plan::Result<()> {
let range = self.base..self.base + self.count;
for k in 0..n {
for id in range.clone() {
if bound & 1 == 0 || keys[0].get(k) == Some(&id) {
self.read.fetch_add(1, Ordering::Relaxed);
out(k, &[id]);
}
}
}
Ok(())
}
}
/// Person 0..3, Pet 3..7, Place 7..9.
const TYPES: [(&str, u64, u64); 3] = [("Person", 0, 3), ("Pet", 3, 4), ("Place", 7, 2)];
fn catalog(read: &Arc<AtomicUsize>) -> Catalog {
let mut c = Catalog::new();
for (t, base, count) in TYPES {
let src = Ids {
base,
count,
read: read.clone(),
};
c.label(t, Source::External(Arc::new(src)));
c.id_block(t, base, count);
}
c
}
fn label_of(id: u64) -> Option<&'static str> {
TYPES
.iter()
.find(|t| id >= t.1 && id < t.1 + t.2)
.map(|t| t.0)
}
#[tokio::test]
async fn id_lookups_read_no_label() {
let e: Engine<CpuBackend> = Engine::new(CpuDevice::new(2));
let cases: [(&str, &dyn Fn(u64) -> bool); 8] = [
("MATCH (n) WHERE id(n) = 4 RETURN id(n)", &|i| i == 4),
(
"MATCH (n) WHERE id(n) >= 2 AND id(n) < 8 RETURN id(n)",
&|i| (2..8).contains(&i),
),
(
"MATCH (n) WHERE id(n) = 1 OR id(n) = 8 OR id(n) = 5 RETURN id(n)",
&|i| [1, 8, 5].contains(&i),
),
("MATCH (n) WHERE id(n) = 9 RETURN id(n)", &|_| false),
("MATCH (n) WHERE id(n) > 100 RETURN id(n)", &|_| false),
("MATCH (n:Pet) WHERE id(n) = 1 RETURN id(n)", &|_| false),
("MATCH (n:Pet) WHERE id(n) <= 4 RETURN id(n)", &|i| {
(3..=4).contains(&i)
}),
(
"MATCH (n:Person|Place) WHERE id(n) >= 2 RETURN id(n)",
&|i| i >= 2 && matches!(label_of(i), Some("Person" | "Place")),
),
];
for (q, keep) in cases {
let read = Arc::new(AtomicUsize::new(0));
let l = lower_with(&parse(q).unwrap(), &catalog(&read), &Params::new()).unwrap();
let ex = l.explain().unwrap();
assert!(ex.contains("(n): id range"), "{q}: {ex}");
assert!(!ex.contains("label scan"), "{q}: {ex}");
let got = l.run(&e).await.unwrap().rows;
let want: Vec<Vec<u64>> = (0..20)
.filter(|&i| label_of(i).is_some() && keep(i))
.map(|i| vec![i])
.collect();
assert_eq!(got, want, "{q}");
assert_eq!(
read.load(Ordering::Relaxed),
0,
"{q}: rows read from labels"
);
}
}