crates/kleene-gql/tests/cypher.rs
//! The common read shapes of Cypher queries on one small graph of one label (`User`) and
//! one edge type (`FOLLOWS`), each answer checked against a plain loop over the same
//! lists: WITH, subqueries, UNWIND and arithmetic, id(n), whole nodes and edges.
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use arrow_array::{ArrayRef, BooleanArray, Float64Array, Int64Array, StringArray, UInt64Array};
use kleene_gql::{Catalog, Param, Params, Table, TypedTable, lower_with, parse};
use kleene_plan::{Datum, Engine, External, Facts, Source, Type};
use kleene_sparse::{CpuBackend, CpuDevice};
/// Users `0..8`: (name, age); user 7 follows no one and no one follows it.
const USERS: [(&str, Option<i64>); 8] = [
("ann", Some(31)),
("bo", Some(25)),
("cy", None),
("di", Some(40)),
("ed", Some(31)),
("fi", Some(19)),
("gu", Some(52)),
("hal", Some(27)),
];
/// (follower, followed, weight).
const FOLLOWS: [(u64, u64, u64); 10] = [
(0, 1, 3),
(0, 2, 1),
(1, 2, 4),
(2, 3, 2),
(3, 4, 5),
(1, 4, 1),
(4, 5, 2),
(5, 6, 7),
(6, 4, 1),
(2, 5, 6),
];
/// Typed properties of each FOLLOWS edge, in the order of [`FOLLOWS`].
const SINCE: [Option<i64>; 10] = [
Some(2019),
Some(2021),
None,
Some(2018),
Some(-5),
Some(2022),
Some(2017),
None,
Some(2023),
Some(2016),
];
const SCORE: [Option<f64>; 10] = [
Some(0.5),
Some(2.25),
Some(1.0),
Some(-0.75),
Some(3.5),
Some(1.5),
None,
Some(2.0),
Some(4.25),
Some(1.25),
];
const TAG: [Option<&str>; 10] = [
Some("x"),
Some("y"),
Some("x"),
None,
Some("z"),
Some("y"),
Some("x"),
Some("z"),
Some("y"),
Some("x"),
];
const MUTUAL: [Option<bool>; 10] = [
Some(true),
Some(false),
Some(true),
Some(true),
None,
Some(false),
Some(true),
Some(false),
Some(true),
Some(false),
];
/// (from, to, value) columns of an edge property of FOLLOWS.
fn edge_cols(values: ArrayRef) -> Source {
let from: ArrayRef = Arc::new(UInt64Array::from_iter_values(FOLLOWS.iter().map(|e| e.0)));
let to: ArrayRef = Arc::new(UInt64Array::from_iter_values(FOLLOWS.iter().map(|e| e.1)));
Source::Columns(vec![from, to, values])
}
/// A user's `id` property: its node id plus 100.
fn uid(n: u64) -> u64 {
n + 100
}
fn catalog() -> Catalog {
let n = USERS.len() as u64;
let ids = || -> ArrayRef { Arc::new(UInt64Array::from_iter_values(0..n)) };
let mut c = Catalog::new();
c.label(
"User",
Source::Facts(Facts::from_rows(1, (0..n).map(|x| [x])).unwrap()),
)
.edge(
"FOLLOWS",
Source::Facts(Facts::from_rows(2, FOLLOWS.iter().map(|e| [e.0, e.1])).unwrap()),
)
.edge_property(
"FOLLOWS",
"w",
Source::Facts(Facts::from_rows(3, FOLLOWS.iter().map(|e| [e.0, e.1, e.2])).unwrap()),
)
.typed_edge_property(
"FOLLOWS",
"since",
edge_cols(Arc::new(Int64Array::from(SINCE.to_vec()))),
Type::I64,
)
.typed_edge_property(
"FOLLOWS",
"score",
edge_cols(Arc::new(Float64Array::from(SCORE.to_vec()))),
Type::F64,
)
.typed_edge_property(
"FOLLOWS",
"tag",
edge_cols(Arc::new(StringArray::from(TAG.to_vec()))),
Type::Str,
)
.typed_edge_property(
"FOLLOWS",
"mutual",
edge_cols(Arc::new(BooleanArray::from(MUTUAL.to_vec()))),
Type::Bool,
)
.property(
"User",
"id",
Source::Facts(Facts::from_rows(2, (0..n).map(|x| [x, uid(x)])).unwrap()),
)
.typed_property(
"User",
"name",
Source::Columns(vec![
ids(),
Arc::new(StringArray::from_iter_values(USERS.iter().map(|u| u.0))),
]),
Type::Str,
)
.typed_property(
"User",
"age",
Source::Columns(vec![
ids(),
Arc::new(Int64Array::from(
USERS.iter().map(|u| u.1).collect::<Vec<_>>(),
)),
]),
Type::I64,
);
c
}
fn engine() -> Engine<CpuBackend> {
Engine::new(CpuDevice::new(2))
}
fn params(ps: &[(&str, u64)]) -> Params {
ps.iter().map(|&(k, v)| (k.to_string(), v.into())).collect()
}
async fn run_p(q: &str, ps: &[(&str, u64)]) -> Table {
let l = lower_with(
&parse(q).unwrap_or_else(|e| panic!("{q}: {e}")),
&catalog(),
¶ms(ps),
)
.unwrap_or_else(|e| panic!("{q}: {e}"));
l.run(&engine())
.await
.unwrap_or_else(|e| panic!("{q}: {e}"))
}
async fn run(q: &str) -> Table {
run_p(q, &[]).await
}
async fn typed_p(q: &str, ps: &[(&str, u64)]) -> TypedTable {
let l = lower_with(
&parse(q).unwrap_or_else(|e| panic!("{q}: {e}")),
&catalog(),
¶ms(ps),
)
.unwrap_or_else(|e| panic!("{q}: {e}"));
l.run_typed(&engine())
.await
.unwrap_or_else(|e| panic!("{q}: {e}"))
}
/// The error lowering (or parsing) `q` gives.
fn refused(q: &str) -> String {
match parse(q) {
Err(e) => e.to_string(),
Ok(ast) => match lower_with(&ast, &catalog(), &Params::new()) {
Err(e) => e.to_string(),
Ok(_) => panic!("{q}: lowered"),
},
}
}
fn sorted<T: Ord>(mut v: Vec<T>) -> Vec<T> {
v.sort();
v
}
fn out(a: u64) -> impl Iterator<Item = u64> {
FOLLOWS.iter().filter(move |e| e.0 == a).map(|e| e.1)
}
/// Edges from `s` to each user a walk of one or more edges reaches.
fn bfs(s: u64) -> BTreeMap<u64, u64> {
let mut d = BTreeMap::new();
let mut q = VecDeque::from([(s, 0u64)]);
while let Some((v, k)) = q.pop_front() {
for w in out(v) {
if let std::collections::btree_map::Entry::Vacant(e) = d.entry(w) {
e.insert(k + 1);
q.push_back((w, k + 1));
}
}
}
d
}
// ---- (a) WITH ----
#[tokio::test]
async fn with_pipes_rows_into_the_next_match() {
// Each (a, b, c) walk once, the WITH's WHERE on b.
let t = run(
"MATCH (a:User)-[:FOLLOWS]->(b:User) WITH a, b WHERE b.id > 103 \
MATCH (b)-[:FOLLOWS]->(c:User) RETURN a.id, c.id",
)
.await;
let mut want = Vec::new();
for &(a, b, _) in &FOLLOWS {
if uid(b) > 103 {
want.extend(out(b).map(|c| vec![uid(a), uid(c)]));
}
}
assert_eq!(sorted(t.rows), sorted(want));
// A WITH that leaves a node out keeps a row per match (the node a hidden column).
let t = run("MATCH (a:User)-[:FOLLOWS]->(b:User) WITH a RETURN a.id").await;
let want: Vec<Vec<u64>> = FOLLOWS.iter().map(|e| vec![uid(e.0)]).collect();
assert_eq!(sorted(t.rows), sorted(want));
// WITH DISTINCT: each b once, then its edges.
let t = run("MATCH (a:User)-[:FOLLOWS]->(b:User) WITH DISTINCT b \
MATCH (b)-[:FOLLOWS]->(c:User) RETURN b.id, c.id")
.await;
let bs: BTreeSet<u64> = FOLLOWS.iter().map(|e| e.1).collect();
let want: Vec<Vec<u64>> = bs
.iter()
.flat_map(|&b| out(b).map(move |c| vec![uid(b), uid(c)]))
.collect();
assert_eq!(sorted(t.rows), sorted(want));
// Typed values through a WITH, its WHERE on one of them.
let t = typed_p(
"MATCH (a:User) WITH a.name AS name, a.age AS age WHERE age > 30 RETURN name, age",
&[],
)
.await;
let want: Vec<Vec<Datum>> = USERS
.iter()
.filter(|u| u.1.is_some_and(|x| x > 30))
.map(|u| vec![Datum::Str(u.0.into()), Datum::I64(u.1.unwrap())])
.collect();
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
}
fn sorted_datums(mut v: Vec<Vec<Datum>>) -> Vec<Vec<Datum>> {
v.sort_by_key(|r| format!("{r:?}"));
v
}
#[tokio::test]
async fn with_a_path_function_aliased_and_its_length() {
// A shortest path as a WITH item: its length goes on; no path is null and fails the
// WHERE.
// (a length that may be null is a signed value)
let want: Vec<Vec<Datum>> = bfs(0)
.values()
.map(|&d| vec![Datum::I64(d as i64)])
.collect();
for q in [
"MATCH (s:User), (t:User) WHERE s.id = 100 \
WITH shortestPath((s)-[:FOLLOWS*]->(t)) AS p WHERE length(p) > 0 RETURN length(p)",
"MATCH (s:User), (t:User) WHERE s.id = 100 \
WITH shortestPath((s)-[*]->(t)) AS p WHERE length(p) > 0 RETURN length(p) AS d",
] {
let t = typed_p(q, &[]).await;
assert_eq!(sorted_datums(t.rows), sorted_datums(want.clone()), "{q}");
}
// Without the WHERE: a row per t, null where no path leads there.
let t = typed_p(
"MATCH (s:User), (t:User) WHERE s.id = 100 \
WITH shortestPath((s)-[:FOLLOWS*]->(t)) AS p, t RETURN t.id, length(p)",
&[],
)
.await;
let d = bfs(0);
let want: Vec<Vec<Datum>> = (0..8u64)
.map(|t| {
vec![
Datum::U64(uid(t)),
d.get(&t).map_or(Datum::Null, |&x| Datum::I64(x as i64)),
]
})
.collect();
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
let e = refused(
"MATCH (s:User), (t:User) WITH shortestPath((s)-[:FOLLOWS*]->(t)) AS p RETURN nodes(p)",
);
assert!(e.contains("length only"), "{e}");
}
#[tokio::test]
async fn with_order_by_limit_and_aggregates() {
// The three users with the most followed, ties by id; then a WHERE on the count.
let t = run(
"MATCH (a:User)-[:FOLLOWS]->(b:User) WITH a.id AS id, count(b) AS n \
ORDER BY n DESC, id LIMIT 3 WHERE n >= 2 RETURN id, n ORDER BY id",
)
.await;
let mut per: Vec<(u64, u64)> = (0..8u64)
.map(|a| (uid(a), out(a).count() as u64))
.filter(|x| x.1 > 0)
.collect();
per.sort_by(|x, y| y.1.cmp(&x.1).then(x.0.cmp(&y.0)));
let mut want: Vec<Vec<u64>> = per
.iter()
.take(3)
.filter(|x| x.1 >= 2)
.map(|x| vec![x.0, x.1])
.collect();
want.sort();
assert_eq!(t.rows, want);
// ORDER BY and LIMIT of a WITH on a node's property.
let t = run("MATCH (a:User) WITH a ORDER BY a.id DESC LIMIT 2 RETURN a.id").await;
assert_eq!(sorted(t.rows), vec![vec![uid(6)], vec![uid(7)]]);
// RETURN DISTINCT.
let t = run("MATCH (a:User)-[:FOLLOWS]->(b:User) RETURN DISTINCT b.id").await;
let bs: BTreeSet<u64> = FOLLOWS.iter().map(|e| uid(e.1)).collect();
assert_eq!(t.rows, bs.iter().map(|&b| vec![b]).collect::<Vec<_>>());
}
// ---- (b) subqueries ----
#[tokio::test]
async fn call_subqueries_per_outer_row() {
let t = run_p(
"MATCH (a:User {id: $id}) CALL { WITH a MATCH (a)-[:FOLLOWS]->(b:User) RETURN b.id AS bid } \
RETURN bid",
&[("id", uid(1))],
)
.await;
assert_eq!(
sorted(t.rows),
sorted(out(1).map(|b| vec![uid(b)]).collect())
);
// An aggregate per outer row: one row each, 0 for none.
let t = run(
"MATCH (a:User) CALL { WITH a MATCH (a)-[:FOLLOWS]->(b:User) RETURN count(b) AS n } \
RETURN a.id, n",
)
.await;
let want: Vec<Vec<u64>> = (0..8u64)
.map(|a| vec![uid(a), out(a).count() as u64])
.collect();
assert_eq!(sorted(t.rows), want);
// Outer names after the subquery, and a WHERE inside it.
let t = run(
"MATCH (a:User)-[:FOLLOWS]->(m:User) CALL { WITH m MATCH (m)-[:FOLLOWS]->(c:User) \
WHERE c.id <> 104 RETURN c } RETURN a.id, m.id, c.id",
)
.await;
let mut want = Vec::new();
for &(a, m, _) in &FOLLOWS {
for c in out(m).filter(|&c| uid(c) != 104) {
want.push(vec![uid(a), uid(m), uid(c)]);
}
}
assert_eq!(sorted(t.rows), sorted(want));
let e = refused(
"MATCH (a:User) CALL { WITH a MATCH (a)-[:FOLLOWS]->(b) RETURN b LIMIT 1 } RETURN b",
);
assert!(e.contains("per outer row"), "{e}");
}
// ---- (c) UNWIND and arithmetic ----
async fn typed_params(q: &str, ps: Params) -> TypedTable {
let l = lower_with(
&parse(q).unwrap_or_else(|e| panic!("{q}: {e}")),
&catalog(),
&ps,
)
.unwrap_or_else(|e| panic!("{q}: {e}"));
l.run_typed(&engine())
.await
.unwrap_or_else(|e| panic!("{q}: {e}"))
}
#[tokio::test]
async fn unwind_lists_into_rows() {
// Items over a bound value (an unsigned id and signed sums: signed together).
let t = typed_p(
"MATCH (n:User {id: $id}) UNWIND [n.id, n.id + 1, n.id + 2] AS x RETURN x",
&[("id", uid(3))],
)
.await;
let want: Vec<Vec<Datum>> = (0..3)
.map(|k| vec![Datum::I64(uid(3) as i64 + k)])
.collect();
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
// A literal list alone: a row per item (a repeat a row of its own), or DISTINCT.
let t = run("UNWIND [3, 1, 2, 3] AS x RETURN x").await;
assert_eq!(t.rows, vec![vec![1], vec![2], vec![3], vec![3]]);
let t = run("UNWIND [3, 1, 2, 3] AS x RETURN DISTINCT x").await;
assert_eq!(t.rows, vec![vec![1], vec![2], vec![3]]);
// A list parameter, then a MATCH on each item.
let mut ps = Params::new();
ps.insert("ids".into(), Param::List(vec![uid(1), uid(5), 999]));
let t = typed_params(
"UNWIND $ids AS i MATCH (u:User) WHERE u.id = i RETURN i, u.name",
ps,
)
.await;
assert_eq!(
sorted_datums(t.rows),
vec![
vec![Datum::U64(uid(1)), Datum::Str("bo".into())],
vec![Datum::U64(uid(5)), Datum::Str("fi".into())],
]
);
// Each row of a MATCH once per item.
let t = run("MATCH (a:User)-[:FOLLOWS]->(b:User) UNWIND [1, 2] AS k RETURN a.id, k").await;
let want: Vec<Vec<u64>> = FOLLOWS
.iter()
.flat_map(|e| [vec![uid(e.0), 1], vec![uid(e.0), 2]])
.collect();
assert_eq!(sorted(t.rows), sorted(want));
let e = refused("UNWIND [1, 'a'] AS x RETURN x");
assert!(e.contains("one type"), "{e}");
}
#[tokio::test]
async fn arithmetic_on_integers_and_floats_with_nulls() {
let t = typed_p(
"MATCH (a:User) RETURN a.id, a.age + 1 AS n, a.age * 2 - 3 AS m, a.age / 0 AS z, \
a.age % 7 AS r, a.id * 1.5 AS f",
&[],
)
.await;
let want: Vec<Vec<Datum>> = USERS
.iter()
.enumerate()
.map(|(i, u)| {
let age = |f: &dyn Fn(i64) -> i64| u.1.map_or(Datum::Null, |a| Datum::I64(f(a)));
vec![
Datum::U64(uid(i as u64)),
age(&|a| a + 1),
age(&|a| a * 2 - 3),
Datum::Null,
age(&|a| a % 7),
Datum::F64(uid(i as u64) as f64 * 1.5),
]
})
.collect();
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
// In a WHERE: a null difference is not true.
let t =
run("MATCH (a:User)-[:FOLLOWS]->(b:User) WHERE a.age - b.age > 5 RETURN a.id, b.id").await;
let age = |n: u64| USERS[n as usize].1;
let want: Vec<Vec<u64>> = FOLLOWS
.iter()
.filter(|e| matches!((age(e.0), age(e.1)), (Some(x), Some(y)) if x - y > 5))
.map(|e| vec![uid(e.0), uid(e.1)])
.collect();
assert_eq!(sorted(t.rows), sorted(want));
// Brackets and the order of operators.
let t = typed_p(
"MATCH (a:User {id: 100}) RETURN (a.id - 98) * 3 % 4 AS v, a.id - 98 * 3 AS w",
&[],
)
.await;
assert_eq!(
t.rows,
vec![vec![
Datum::I64((100 - 98) * 3 % 4),
Datum::I64(100 - 98 * 3)
]]
);
}
#[tokio::test]
async fn bit_functions_and_unary_minus_on_the_core_computed_values() {
let t = typed_p(
"MATCH (a:User) RETURN a.id, bitand(a.age, 12) AS b, bitor(a.id, 3) AS o, \
bitxor(a.age, a.id) AS x, bitnot(a.age) AS n, shiftleft(a.age, 2) AS l, \
shiftright(a.id, 1) AS r, -a.age AS m, -(a.age + 1) * 2 AS k, shiftleft(a.id, 64) AS z",
&[],
)
.await;
let want: Vec<Vec<Datum>> = USERS
.iter()
.enumerate()
.map(|(i, u)| {
let id = uid(i as u64) as i64;
let age = |f: &dyn Fn(i64) -> i64| u.1.map_or(Datum::Null, |a| Datum::I64(f(a)));
vec![
Datum::U64(id as u64),
age(&|a| a & 12),
Datum::I64(id | 3),
age(&|a| a ^ id),
age(&|a| !a),
age(&|a| a << 2),
Datum::I64(id >> 1),
age(&|a| -a),
age(&|a| -(a + 1) * 2),
Datum::Null,
]
})
.collect();
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
// In a WHERE, and refused on a float.
let t = run("MATCH (a:User) WHERE bitand(a.age, 1) = 1 RETURN a.id").await;
let want: Vec<Vec<u64>> = (0..USERS.len() as u64)
.filter(|&i| USERS[i as usize].1.is_some_and(|a| a & 1 == 1))
.map(|i| vec![uid(i)])
.collect();
assert_eq!(sorted(t.rows), sorted(want));
let e = refused("MATCH (a:User) RETURN bitor(a.age, 1.5)");
assert!(e.contains("integers only"), "{e}");
}
// ---- (f) a property against a property, an OR of equalities by the index ----
/// (lo, hi, node): a range index over the users' `id` property, counting its lookups.
#[derive(Debug)]
struct IdRange(Arc<AtomicUsize>);
impl External for IdRange {
fn arity(&self) -> usize {
3
}
fn can(&self, bound: u64) -> bool {
bound & 0b11 == 0b11
}
fn lookup(
&self,
_bound: u64,
keys: &[&[u64]],
n: usize,
out: &mut dyn FnMut(usize, &[u64]),
) -> kleene_plan::Result<()> {
for (k, (&lo, &hi)) in keys[0].iter().zip(keys[1]).enumerate().take(n) {
self.0.fetch_add(1, Ordering::Relaxed);
for u in 0..USERS.len() as u64 {
if (lo..=hi).contains(&uid(u)) {
out(k, &[lo, hi, u]);
}
}
}
Ok(())
}
}
#[tokio::test]
async fn property_against_property_and_an_or_by_the_index() {
// Two nodes' properties compared (a null age equals nothing).
let t =
run("MATCH (a:User), (b:User) WHERE a.age = b.age AND a.id < b.id RETURN a.id, b.id").await;
let mut want = Vec::new();
for (i, x) in USERS.iter().enumerate() {
for (j, y) in USERS.iter().enumerate() {
if x.1.is_some() && x.1 == y.1 && i < j {
want.push(vec![uid(i as u64), uid(j as u64)]);
}
}
}
assert!(!want.is_empty());
assert_eq!(sorted(t.rows), sorted(want));
let t = run("MATCH (a:User)-[:FOLLOWS]->(b:User) WHERE a.age < b.age RETURN a.id, b.id").await;
let want: Vec<Vec<u64>> = FOLLOWS
.iter()
.filter(|e| matches!((USERS[e.0 as usize].1, USERS[e.1 as usize].1), (Some(x), Some(y)) if x < y))
.map(|e| vec![uid(e.0), uid(e.1)])
.collect();
assert_eq!(sorted(t.rows), sorted(want));
// `u.id = $a OR u.id = $b` with an index on `id`: a lookup per value, no scan.
let asked = Arc::new(AtomicUsize::new(0));
let mut c = catalog();
c.property_index(
"User",
"id",
Source::External(Arc::new(IdRange(asked.clone()))),
);
let q = "MATCH (u:User) WHERE u.id = $a OR u.id = $b RETURN u.name";
let ps = params(&[("a", uid(1)), ("b", uid(6))]);
let l = lower_with(&parse(q).unwrap(), &c, &ps).unwrap();
let ex = l.explain().unwrap();
assert!(ex.contains("(u): index lookup User.id at 101, 106"), "{ex}");
let t = l.run_typed(&engine()).await.unwrap();
assert_eq!(
sorted_datums(t.rows),
vec![vec![Datum::Str("bo".into())], vec![Datum::Str("gu".into())]]
);
assert_eq!(asked.load(Ordering::Relaxed), 2);
}
// ---- (g1) typed edge properties ----
#[tokio::test]
async fn typed_edge_properties_on_a_single_edge() {
let id = |n: u64| Datum::U64(uid(n));
let edges = || FOLLOWS.iter().enumerate();
// WHERE on a signed value (a null is not >=), RETURN it typed.
let t = typed_p(
"MATCH (a:User)-[r:FOLLOWS]->(b:User) WHERE r.since >= 2019 RETURN a.id, b.id, r.since",
&[],
)
.await;
let want: Vec<Vec<Datum>> = edges()
.filter(|(i, _)| SINCE[*i].is_some_and(|y| y >= 2019))
.map(|(i, e)| vec![id(e.0), id(e.1), Datum::I64(SINCE[i].unwrap())])
.collect();
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
// A float, a string and a boolean together; IS NULL.
let t = run(
"MATCH (a:User)-[r:FOLLOWS]->(b:User) WHERE r.score > 1.0 AND r.tag = 'y' AND r.mutual = TRUE \
RETURN a.id, b.id",
)
.await;
let want: Vec<Vec<u64>> = edges()
.filter(|(i, _)| {
SCORE[*i].is_some_and(|x| x > 1.0) && TAG[*i] == Some("y") && MUTUAL[*i] == Some(true)
})
.map(|(_, e)| vec![uid(e.0), uid(e.1)])
.collect();
assert!(!want.is_empty());
assert_eq!(sorted(t.rows), sorted(want));
let t = run("MATCH (a:User)-[r:FOLLOWS]->(b:User) WHERE r.since IS NULL OR r.tag IS NULL RETURN a.id, b.id").await;
let want: Vec<Vec<u64>> = edges()
.filter(|(i, _)| SINCE[*i].is_none() || TAG[*i].is_none())
.map(|(_, e)| vec![uid(e.0), uid(e.1)])
.collect();
assert_eq!(sorted(t.rows), sorted(want));
// ORDER BY a float, falling (nulls first falling), LIMIT.
let t = typed_p(
"MATCH (a:User)-[r:FOLLOWS]->(b:User) RETURN a.id, b.id, r.score ORDER BY r.score DESC LIMIT 3",
&[],
)
.await;
// falling: the null first, then the largest
let mut by: Vec<usize> = (0..FOLLOWS.len()).collect();
by.sort_by(|&x, &y| match (SCORE[x], SCORE[y]) {
(None, _) => std::cmp::Ordering::Less,
(_, None) => std::cmp::Ordering::Greater,
(Some(p), Some(q)) => q.partial_cmp(&p).unwrap(),
});
let want: Vec<Vec<Datum>> = by
.iter()
.take(3)
.map(|&i| {
let e = FOLLOWS[i];
vec![id(e.0), id(e.1), SCORE[i].map_or(Datum::Null, Datum::F64)]
})
.collect();
assert_eq!(t.rows, want);
// Aggregates per follower: nulls skipped.
let t = typed_p(
"MATCH (a:User)-[r:FOLLOWS]->(b:User) RETURN a.id, count(r.since) AS n, min(r.since) AS first, sum(r.score) AS s",
&[],
)
.await;
let mut want: Vec<Vec<Datum>> = Vec::new();
for a in 0..USERS.len() as u64 {
let mine: Vec<usize> = edges().filter(|(_, e)| e.0 == a).map(|(i, _)| i).collect();
if mine.is_empty() {
continue;
}
let since: Vec<i64> = mine.iter().filter_map(|&i| SINCE[i]).collect();
let score: Vec<f64> = mine.iter().filter_map(|&i| SCORE[i]).collect();
want.push(vec![
id(a),
Datum::U64(since.len() as u64),
since.iter().min().map_or(Datum::Null, |&m| Datum::I64(m)),
if score.is_empty() {
Datum::Null
} else {
Datum::F64(score.iter().sum())
},
]);
}
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
// Either way: the edge's own values from both ends.
let t = typed_p(
"MATCH (a:User)-[r:FOLLOWS]-(b:User) WHERE a.id = 104 RETURN b.id, r.tag",
&[],
)
.await;
let want: Vec<Vec<Datum>> = edges()
.filter(|(_, e)| e.0 == 4 || e.1 == 4)
.map(|(i, e)| {
let other = if e.0 == 4 { e.1 } else { e.0 };
vec![
id(other),
TAG[i].map_or(Datum::Null, |t| Datum::Str(t.into())),
]
})
.collect();
assert_eq!(sorted_datums(t.rows), sorted_datums(want));
}
// ---- (g2) predicates over the edges of a variable-length path ----
/// The ends of walks from `s` of `min..=max` edges (no bound: `None`) over the FOLLOWS
/// edges `keep` takes, by their index.
fn walk_ends(s: u64, min: u64, max: Option<u64>, keep: &dyn Fn(usize) -> bool) -> Vec<Vec<u64>> {
let mut ends = BTreeSet::new();
let mut seen = BTreeSet::from([(s, 0u64)]);
let mut q = VecDeque::from([(s, 0u64)]);
let cap = max.unwrap_or(FOLLOWS.len() as u64 * 2 + 2);
while let Some((v, k)) = q.pop_front() {
if k >= min {
ends.insert(v);
}
if k == cap {
continue;
}
for (i, e) in FOLLOWS.iter().enumerate() {
if e.0 == v && keep(i) && seen.insert((e.1, k + 1)) {
q.push_back((e.1, k + 1));
}
}
}
ends.into_iter().map(|b| vec![uid(b)]).collect()
}
/// The ends of walks of one edge or more from `s` with at least one (`exactly`: exactly
/// one) edge `hit` takes; under `exactly`, every other edge one `miss` takes.
fn flagged_ends(
s: u64,
exactly: bool,
hit: &dyn Fn(usize) -> bool,
miss: &dyn Fn(usize) -> bool,
) -> Vec<Vec<u64>> {
let mut seen = BTreeSet::from([(s, false)]);
let mut q = VecDeque::from([(s, false)]);
while let Some((v, f)) = q.pop_front() {
for (i, e) in FOLLOWS.iter().enumerate() {
if e.0 != v {
continue;
}
let next = match (exactly, f, hit(i)) {
(_, false, true) => Some(true),
(true, true, true) => None,
(true, _, false) if !miss(i) => None,
(_, f, _) => Some(f),
};
if let Some(n) = next
&& seen.insert((e.1, n))
{
q.push_back((e.1, n));
}
}
}
seen.into_iter()
.filter(|x| x.1)
.map(|x| vec![uid(x.0)])
.collect::<BTreeSet<_>>()
.into_iter()
.collect()
}
#[tokio::test]
async fn predicates_over_the_edges_of_a_path() {
let w = |i: usize| FOLLOWS[i].2;
let min = 2;
let want = walk_ends(0, 1, Some(3), &|i| w(i) >= min);
assert!(!want.is_empty());
// all(...), the short form and none(...) of the negation: one answer, and the walk runs
// over the edges the predicate keeps.
for q in [
"MATCH (a:User)-[r:FOLLOWS*1..3]->(b:User) WHERE a.id = 100 AND all(x IN r WHERE x.w >= $min) RETURN b.id",
"MATCH (a:User)-[r:FOLLOWS*1..3]->(b:User) WHERE a.id = 100 AND r.w >= $min RETURN b.id",
"MATCH (a:User)-[r:FOLLOWS*1..3]->(b:User) WHERE a.id = 100 AND none(x IN r WHERE x.w < $min) RETURN b.id",
] {
let t = run_p(q, &[("min", min)]).await;
assert_eq!(sorted(t.rows), want, "{q}");
let ex = explain_of(q, &[("min", min)]);
assert!(ex.contains("(r): the walk keeps the edges where"), "{ex}");
}
// A typed property with nulls (a null edge is no step), no bound on the length
// (Cypher's `*`: one edge or more).
let t = run("MATCH (a:User)-[r:FOLLOWS*]->(b:User) WHERE a.id = 101 AND all(e IN r WHERE e.score > 0.9 AND e.tag <> 'z') RETURN b.id").await;
let keep = |i: usize| SCORE[i].is_some_and(|x| x > 0.9) && TAG[i].is_some_and(|t| t != "z");
assert_eq!(sorted(t.rows), walk_ends(1, 1, None, &keep));
// any(...) and single(...) over a walk of no bound: an edge that passes somewhere
// along it (exactly one, the others failing).
let heavy = |i: usize| w(i) >= 5;
let light = |i: usize| w(i) < 5;
let t = run("MATCH (a:User)-[r:FOLLOWS*]->(b:User) WHERE a.id = 100 AND any(x IN r WHERE x.w >= 5) RETURN b.id").await;
assert_eq!(sorted(t.rows), flagged_ends(0, false, &heavy, &light));
let t = run("MATCH (a:User)-[r:FOLLOWS]->+(b:User) WHERE a.id = 101 AND single(x IN r WHERE x.w >= 5) RETURN b.id").await;
assert_eq!(sorted(t.rows), flagged_ends(1, true, &heavy, &light));
// Refused by name: any / single over a bounded length, a predicate that is not a
// comparison of the edge's properties with constants.
let e = refused(
"MATCH (a:User)-[r:FOLLOWS*1..3]->(b:User) WHERE any(x IN r WHERE x.w >= 5) RETURN b",
);
assert!(e.contains("any(") && e.contains("bound"), "{e}");
let e = refused(
"MATCH (a:User)-[r:FOLLOWS*]->(b:User) WHERE all(x IN r WHERE x.w >= a.age) RETURN b",
);
assert!(e.contains("all(") && e.contains("constant"), "{e}");
}
fn explain_of(q: &str, ps: &[(&str, u64)]) -> String {
lower_with(&parse(q).unwrap(), &catalog(), ¶ms(ps))
.unwrap()
.explain()
.unwrap()
}
// ---- counts over rows that differ only in a nullable value ----
/// Nodes `0..4` of label N (`name` "x" for all, `h` nullable), an edge `0 -> 1` of label T
/// with two rows of its property `p` (`p0`, `p1`: the edge read twice, once per value).
fn twin_catalog(p: [Option<i64>; 2], h: [Option<i64>; 4]) -> Catalog {
let mut c = Catalog::new();
let ids = || -> ArrayRef { Arc::new(UInt64Array::from_iter_values(0..4)) };
c.label("N", Source::Columns(vec![ids()]))
.edge(
"T",
Source::Facts(Facts::from_rows(2, [[0u64, 1]]).unwrap()),
)
.typed_edge_property(
"T",
"p",
Source::Columns(vec![
Arc::new(UInt64Array::from(vec![0u64, 0])),
Arc::new(UInt64Array::from(vec![1u64, 1])),
Arc::new(Int64Array::from(p.to_vec())),
]),
Type::I64,
)
.typed_property(
"N",
"name",
Source::Columns(vec![ids(), Arc::new(StringArray::from(vec!["x"; 4]))]),
Type::Str,
)
.typed_property(
"N",
"h",
Source::Columns(vec![ids(), Arc::new(Int64Array::from(h.to_vec()))]),
Type::I64,
);
c
}
async fn twin_rows(c: &Catalog, q: &str) -> Vec<Vec<Datum>> {
let l = lower_with(
&parse(q).unwrap_or_else(|e| panic!("{q}: {e}")),
c,
&Params::new(),
)
.unwrap_or_else(|e| panic!("{q}: {e}"));
l.run_typed(&engine())
.await
.unwrap_or_else(|e| panic!("{q}: {e}"))
.rows
}
/// A count equals the number of rows the same match returns without the aggregate, when
/// two rows differ only in a nullable value (two values, or one value and a null).
#[tokio::test]
async fn counts_keep_rows_that_differ_only_in_a_nullable_value() {
for p in [[Some(3), Some(5)], [Some(3), None]] {
let c = twin_catalog(p, [Some(3), Some(5), None, Some(5)]);
let rows = twin_rows(&c, "MATCH (a:N)-[r:T]->(b:N) RETURN a, b, r.p").await;
assert_eq!(rows.len(), 2, "{p:?}");
let n = Datum::U64(2);
let present = p.iter().flatten().count() as u64;
let top = Datum::I64(*p.iter().flatten().max().unwrap());
// grouped and ungrouped: count(*), count(r), count(r.p) beside another aggregate
// of the nullable value
let cases: [(&str, Vec<Datum>); 7] = [
(
"MATCH (a:N)-[r:T]->(b:N) RETURN a, count(*) AS n, max(r.p) AS m",
vec![Datum::U64(0), n.clone(), top.clone()],
),
(
"MATCH (a:N)-[r:T]->(b:N) RETURN count(*) AS n, max(r.p) AS m",
vec![n.clone(), top.clone()],
),
(
"MATCH (a:N)-[r:T]->(b:N) RETURN a, count(b) AS n, min(r.p) AS m",
vec![
Datum::U64(0),
n.clone(),
Datum::I64(*p.iter().flatten().min().unwrap()),
],
),
(
"MATCH (a:N)-[r:T]->(b:N) RETURN a, count(r.p) AS n",
vec![Datum::U64(0), Datum::U64(present)],
),
(
"MATCH (a:N)-[r:T]->(b:N) RETURN count(r.p) AS n, max(r.p) AS m",
vec![Datum::U64(present), top.clone()],
),
(
"MATCH (a:N)-[r:T]->(b:N) RETURN b, count(a) AS n, sum(r.p) AS s",
vec![
Datum::U64(1),
n.clone(),
Datum::I64(p.iter().flatten().sum()),
],
),
(
"MATCH (a:N)-[r:T]->(b:N) RETURN a, count(r) AS n, max(r.p) AS m",
vec![Datum::U64(0), n.clone(), top.clone()],
),
];
for (q, want) in cases {
assert_eq!(twin_rows(&c, q).await, vec![want], "{q} {p:?}");
}
}
// Two nodes that differ only in a nullable property: count(n), count(*).
for h in [
[Some(3), Some(5), None, Some(5)],
[Some(3), None, Some(7), Some(5)],
] {
let c = twin_catalog([Some(3), Some(5)], h);
let q = "MATCH (n:N) WHERE n.name = 'x' AND n < 2 RETURN n.name, n.h";
assert_eq!(twin_rows(&c, q).await.len(), 2);
let present = h[..2].iter().flatten().count() as u64;
let q = "MATCH (n:N) WHERE n < 2 RETURN n.name, count(n) AS c, count(*) AS s, count(n.h) AS k, max(n.h) AS m";
let got = twin_rows(&c, q).await;
assert_eq!(got.len(), 1, "{q}");
assert_eq!(
&got[0][..4],
&[
Datum::Str("x".into()),
Datum::U64(2),
Datum::U64(2),
Datum::U64(present)
],
"{h:?}"
);
}
}