use super::selector::apply_gpm_selector;
use super::*;
use crate::exec::test_support::{build, column, exec_cypher, int_cell, path_value, Builder};
use crate::graph::Graph;
use crate::test_support::ints;
use relate_ir::{PathCount, PathMode, PathSelector};
use std::sync::Arc;
fn selector_state(start: NodeId, end: NodeId, length: usize) -> GpmState {
GpmState {
row: Row::new(),
used: UsedSet::default(),
current: end,
nodes: vec![start, end],
rels: (0..length).map(|index| index as RelId).collect(),
}
}
fn rel_type_r(_: RelId) -> Arc<str> {
Arc::from("R")
}
#[test]
fn gpm_shortest_groups_are_partitioned_by_endpoints() {
let states = vec![
selector_state(1, 2, 1),
selector_state(1, 2, 2),
selector_state(1, 2, 2),
selector_state(3, 4, 3),
selector_state(3, 4, 4),
];
let selected = apply_gpm_selector(
states,
Some(&PathSelector::Shortest {
count: Some(PathCount::Literal(2)),
group: true,
}),
&BTreeMap::new(),
rel_type_r,
)
.unwrap();
assert_eq!(
selected
.iter()
.map(|state| state.rels.len())
.collect::<Vec<_>>(),
vec![1, 2, 2, 3, 4]
);
}
#[test]
fn any_keeps_the_shortest_members() {
let states = || {
vec![
selector_state(1, 2, 3),
selector_state(1, 2, 1),
selector_state(1, 2, 2),
]
};
let one = apply_gpm_selector(
states(),
Some(&PathSelector::Any(None)),
&BTreeMap::new(),
rel_type_r,
)
.unwrap();
assert_eq!(
one.iter().map(|state| state.rels.len()).collect::<Vec<_>>(),
vec![1]
);
let two = apply_gpm_selector(
states(),
Some(&PathSelector::Any(Some(PathCount::Literal(2)))),
&BTreeMap::new(),
rel_type_r,
)
.unwrap();
assert_eq!(
two.iter().map(|state| state.rels.len()).collect::<Vec<_>>(),
vec![1, 2]
);
}
#[test]
fn selector_output_is_ordered_by_start_then_length() {
let states = vec![
selector_state(1, 2, 1),
selector_state(1, 1, 3),
selector_state(1, 3, 1),
selector_state(2, 3, 1),
selector_state(2, 1, 2),
];
let selected = apply_gpm_selector(
states,
Some(&PathSelector::AnyShortest),
&BTreeMap::new(),
rel_type_r,
)
.unwrap();
let shape: Vec<(NodeId, NodeId, usize)> = selected
.iter()
.map(|state| (state.nodes[0], state.nodes[1], state.rels.len()))
.collect();
assert_eq!(
shape,
vec![(1, 2, 1), (1, 3, 1), (1, 1, 3), (2, 3, 1), (2, 1, 2)]
);
}
#[test]
fn gpm_acyclic_and_simple_apply_distinct_node_rules() {
let cycle: [NodeId; 3] = [1, 2, 1];
assert!(!gpm_path_mode_allows(
Some(PathMode::Acyclic),
cycle.into_iter(),
[]
));
assert!(gpm_path_mode_allows(
Some(PathMode::Simple),
cycle.into_iter(),
[]
));
let repeated_interior: [NodeId; 4] = [1, 2, 2, 3];
assert!(!gpm_path_mode_allows(
Some(PathMode::Simple),
repeated_interior.into_iter(),
[]
));
}
fn query_rows(graph: &Graph, q: &str) -> Vec<Vec<Value>> {
exec_cypher(graph, q).rows
}
fn list_of_ints(lists: &[&[i64]]) -> Vec<Vec<Value>> {
vec![vec![Value::List(
lists.iter().map(|l| ints(l)).collect::<Vec<_>>().into(),
)]]
}
fn postfilter_graph() -> Graph {
build(
&[&["A"], &[], &["B"], &[], &[], &[], &[], &[]],
&[
(0, 1, "R"),
(1, 2, "X"),
(0, 3, "R"),
(3, 4, "R"),
(4, 2, "R"),
(0, 5, "R"),
(5, 6, "R"),
(6, 7, "R"),
(7, 2, "R"),
],
)
.graph
}
#[test]
fn predicate_outside_a_selective_path_pattern_is_a_postfilter() {
let graph = postfilter_graph();
let count = |selector: &str| {
query_rows(
&graph,
&format!(
"MATCH p = {selector} (:A)-->*(:B) \
WHERE none(r IN relationships(p) WHERE r:X) \
RETURN count(*) AS result"
),
)[0][0]
.clone()
};
assert_eq!(count("ANY SHORTEST"), Value::Int(0));
assert_eq!(count("SHORTEST 1"), Value::Int(0));
assert_eq!(count("SHORTEST 2"), Value::Int(1));
assert_eq!(count("SHORTEST 3"), Value::Int(2));
assert_eq!(count("ALL SHORTEST"), Value::Int(0));
assert_eq!(count("ANY"), Value::Int(0));
assert_eq!(count("ANY 1"), Value::Int(0));
assert_eq!(count("ANY 2"), Value::Int(1));
assert_eq!(count("ANY 3"), Value::Int(2));
}
fn disjoint_graph() -> Graph {
build(
&[&["A"], &["X"], &["B"], &[], &[], &["X"], &[], &[]],
&[
(0, 1, "R"),
(1, 2, "R"),
(0, 3, "R"),
(3, 2, "R"),
(0, 4, "R"),
(4, 5, "R"),
(5, 2, "R"),
(0, 6, "R"),
(6, 7, "R"),
(7, 2, "R"),
],
)
.graph
}
fn disjoint_query(selector: &str) -> String {
format!(
"MATCH {selector} (p = (:A)-->+(:B) WHERE none(n IN nodes(p) WHERE n:X)) \
MATCH {selector} (q = (:A)-->+(:B) WHERE q <> p AND length(p) = length(q)) \
WITH length(p) AS pathLength, \
size([n IN nodes(p) WHERE n:X]) AS pxCount, \
size([n IN nodes(q) WHERE n:X]) AS qxCount \
ORDER BY pathLength \
RETURN collect([pathLength, pxCount, qxCount]) AS result"
)
}
#[test]
fn disjoint_shortest_selectors_return_the_distinct_second_path() {
let graph = disjoint_graph();
let disjoint = |selector: &str| query_rows(&graph, &disjoint_query(selector));
assert_eq!(disjoint("ANY SHORTEST"), list_of_ints(&[&[2, 0, 1]]));
assert_eq!(disjoint("SHORTEST 1"), list_of_ints(&[&[2, 0, 1]]));
assert_eq!(
disjoint("SHORTEST 2"),
list_of_ints(&[&[2, 0, 1], &[3, 0, 1]])
);
assert_eq!(disjoint("ANY"), list_of_ints(&[&[2, 0, 1]]));
assert_eq!(disjoint("ANY 1"), list_of_ints(&[&[2, 0, 1]]));
assert_eq!(disjoint("ANY 2"), list_of_ints(&[&[2, 0, 1], &[3, 0, 1]]));
}
#[test]
fn parameterized_any_on_disjoint_selectors_matches_shortest() {
let graph = disjoint_graph();
let params = BTreeMap::from([
("one".to_string(), Value::Int(1)),
("two".to_string(), Value::Int(2)),
]);
let disjoint = |selector: &str, params: &BTreeMap<String, Value>| {
crate::exec::test_support::try_exec_cypher_params(&graph, &disjoint_query(selector), params)
.unwrap()
.rows
};
assert_eq!(
disjoint("SHORTEST $two", ¶ms),
list_of_ints(&[&[2, 0, 1], &[3, 0, 1]])
);
assert_eq!(
disjoint("ANY $two", ¶ms),
list_of_ints(&[&[2, 0, 1], &[3, 0, 1]])
);
assert_eq!(disjoint("ANY $one", ¶ms), list_of_ints(&[&[2, 0, 1]]));
}
#[test]
fn a_path_pattern_predicate_restricts_before_the_selector_picks() {
let graph = disjoint_graph();
let rows = query_rows(
&graph,
"MATCH SHORTEST 1 (p = (:A)-->+(:B) WHERE none(n IN nodes(p) WHERE n:X)) \
RETURN length(p) AS len",
);
assert_eq!(rows, vec![vec![Value::Int(2)]]);
}
#[test]
fn any_selects_the_same_paths_as_shortest() {
let graph = build(
&[&["L"], &[], &["L"], &["L"], &[], &[]],
&[
(0, 1, "R"),
(1, 2, "R"),
(2, 3, "R"),
(3, 5, "R"),
(5, 4, "R"),
(4, 0, "R"),
],
)
.graph;
let lengths = |selector: &str| {
query_rows(
&graph,
&format!(
"MATCH {selector} (p = (:L)--+(:L)) \
WITH length(p) AS pathLength, count(*) AS count ORDER BY pathLength \
RETURN collect([pathLength, count]) AS result"
),
)
};
let shortest = lengths("ANY SHORTEST");
assert_eq!(
shortest,
list_of_ints(&[&[1, 2], &[2, 2], &[3, 2], &[6, 3]])
);
assert_eq!(lengths("ANY"), shortest);
assert_eq!(lengths("ANY 1"), shortest);
let second = lengths("SHORTEST 2");
assert_eq!(
second,
list_of_ints(&[&[1, 2], &[2, 2], &[3, 4], &[4, 2], &[5, 2], &[6, 6]])
);
assert_eq!(lengths("ANY 2"), second);
}
#[test]
fn a_null_prebound_rel_variable_is_not_rebound_by_the_classic_walker() {
let graph = build(&[&["A"], &["B"], &["C"]], &[(0, 1, "R"), (0, 2, "R")]).graph;
let targets = |pattern: &str| {
let result = exec_cypher(
&graph,
&format!(
"MATCH (x:A) OPTIONAL MATCH (x)-[r:R]->(y:B) WHERE y.id = 99 \
MATCH (x)-[{pattern}]->(z) RETURN z.id AS z"
),
);
let mut ids = column(&result, "z", int_cell);
ids.sort_unstable();
ids
};
assert_eq!(targets("r:R"), Vec::<i64>::new());
assert_eq!(targets("r WHERE r.k >= 0"), vec![1, 2]);
}
#[test]
fn a_null_prebound_end_variable_is_rebound_by_the_gpm_engine() {
let graph = build(&[&["A"], &["B"], &["C"]], &[(0, 1, "R"), (0, 2, "R")]).graph;
let targets = |second: &str| {
let result = exec_cypher(
&graph,
&format!(
"MATCH (x:A) OPTIONAL MATCH (x)-[q:R]->(y:B) WHERE y.id = 99 \
MATCH {second} RETURN y.id AS z"
),
);
let mut ids = column(&result, "z", int_cell);
ids.sort_unstable();
ids
};
assert_eq!(targets("(x)-[r2:R]->(y)"), Vec::<i64>::new());
assert_eq!(targets("p = shortestPath((x)-[*]->(y))"), vec![1, 2]);
}
#[test]
fn the_gpm_walk_counts_its_traversed_rels() {
let graph = build(&[&["A"], &["B"], &["C"]], &[(0, 1, "R"), (0, 2, "R")]).graph;
let _ = super::super::take_neighbor_walks();
exec_cypher(
&graph,
"MATCH (x:A)-[r WHERE r.k >= 0]->(z) RETURN z.id AS z",
);
let walks = super::super::take_neighbor_walks();
assert_eq!(walks, 2, "one neighbor walk per traversed rel");
}
fn subpath_group_graph() -> Graph {
let b = Builder::new();
let n99 = b.node("n99", &["X"]);
let n1 = b.node("n1", &["A"]);
let n2 = b.prop_node("n2", &["A", "B"], &[("h", Value::Int(3))]);
let n3 = b.prop_node("n3", &["A", "B"], &[("h", Value::Int(4))]);
b.rel(n99, n1, "R", &[]);
b.rel(n1, n2, "R", &[]);
b.rel(n2, n3, "R", &[]);
b.done()
}
#[test]
fn quantified_subpath_group_binds_one_schema_across_its_stops() {
let graph = subpath_group_graph();
let stops = query_rows(
&graph,
"MATCH p1 = (a:X)-[b]->(c)(p2 = (x:A)-[:R]->(z:B WHERE z.h > 2))* \
RETURN size(x) AS n, [q IN p2 | length(q)] AS lens \
ORDER BY n",
);
assert_eq!(
stops,
vec![
vec![Value::Int(0), Value::List(Vec::new().into())],
vec![Value::Int(1), ints(&[1])],
vec![Value::Int(2), ints(&[1, 1])],
],
"every stop binds its group lists, the zero-rep empty ones included"
);
assert_eq!(
query_rows(
&graph,
"MATCH p1 = (a:X)-[b]->(c)(p2 = (x:A)-[:R]->(z:B WHERE z.h > 2))* \
WHERE size(x) = 2 \
RETURN [q IN p2 | length(q)] AS lens"
),
vec![vec![ints(&[1, 1])]],
"the filtered spelling completes on the same one-schema rows"
);
}
fn lazy_chain_graph() -> Graph {
let b = Builder::new();
let a = b.prop_node("a", &["N"], &[("name", Value::String("A".into()))]);
let m = b.prop_node("b", &["N"], &[("name", Value::String("B".into()))]);
let c = b.prop_node("c", &["N"], &[("name", Value::String("C".into()))]);
b.rel(a, m, "R", &[("w", Value::Int(1))]);
b.rel(m, c, "R", &[("w", Value::Int(2))]);
b.done()
}
fn carried_prop(value: &Value, key: &str) -> Option<Value> {
match value {
Value::Node(node) => node.properties.get(key).cloned(),
Value::Relationship(rel) => rel.properties.get(key).cloned(),
other => panic!("not an entity: {other:?}"),
}
}
#[test]
fn var_length_observed_values_carry_full_records() {
let graph = lazy_chain_graph();
let rows = query_rows(
&graph,
"MATCH p = (x:N {id: 'a'})-[r:R*1..2]->(y) RETURN p, r, y ORDER BY length(p)",
);
assert_eq!(rows.len(), 2);
let names = ["B", "C"];
for (row, end_name) in rows.iter().zip(names) {
let path = path_value(&row[0]).expect("p is a path");
let path_names: Vec<Value> = path
.nodes
.iter()
.map(|node| {
node.properties
.get("name")
.cloned()
.expect("path node name")
})
.collect();
assert_eq!(path_names.len(), path.rels.len() + 1);
assert_eq!(path_names.last(), Some(&Value::String(end_name.into())));
for rel in &path.rels {
assert!(rel.properties.get("w").is_some(), "path rel carries w");
}
let Value::List(rels) = &row[1] else {
panic!("r is a list: {:?}", row[1]);
};
assert_eq!(rels.len(), path.rels.len());
for (index, rel) in rels.iter().enumerate() {
assert_eq!(
carried_prop(rel, "w"),
Some(Value::Int(index as i64 + 1)),
"a returned trail rel is the full record"
);
}
assert_eq!(
carried_prop(&row[2], "name"),
Some(Value::String(end_name.into())),
"the end node is the full record"
);
}
}
#[test]
fn quantified_subpath_values_carry_full_records() {
let graph = lazy_chain_graph();
let rows = query_rows(
&graph,
"MATCH (x:N {id: 'a'}) (q = (s)-[e:R]->(t)){2} (y) \
RETURN [seg IN q | [n IN nodes(seg) | n.name]] AS hops, \
[seg IN q | relationships(seg)[0].w] AS ws",
);
assert_eq!(
rows,
vec![vec![
Value::List(
vec![
Value::List(vec![Value::String("A".into()), Value::String("B".into())].into()),
Value::List(vec![Value::String("B".into()), Value::String("C".into())].into()),
]
.into()
),
ints(&[1, 2]),
]]
);
}
#[test]
fn var_length_rel_admission_reads_wanted_properties() {
let graph = lazy_chain_graph();
assert_eq!(
query_rows(
&graph,
"MATCH (x:N {id: 'a'})-[:R*1..2 {w: 1}]->(y) RETURN y.id AS id",
),
vec![vec![Value::String("b".into())]]
);
assert_eq!(
query_rows(
&graph,
"MATCH (x:N {id: 'a'})-[:R*1..2 {missing: 1}]->(y) RETURN y.id AS id",
),
Vec::<Vec<Value>>::new()
);
assert_eq!(
query_rows(
&graph,
"MATCH (x:N {id: 'a'}) ((s)-[e:R WHERE e.w >= 1]->(t)){1,2} (y) \
RETURN y.id AS id ORDER BY id",
),
vec![
vec![Value::String("b".into())],
vec![Value::String("c".into())]
]
);
}
#[test]
fn pattern_comprehension_node_admission_reads_wanted_properties() {
let graph = lazy_chain_graph();
assert_eq!(
query_rows(
&graph,
"MATCH (x:N {id: 'a'}) \
RETURN [(x)-[:R]->(m:N {name: 'B'}) | m.id] AS hit, \
[(x)-[:R]->(m:N {name: 'Z'}) | m.id] AS miss, \
[(x)-[:R]->(m {name: 'B'}) | m.id] AS unlabeled",
),
vec![vec![
Value::List(vec![Value::String("b".into())].into()),
Value::List(Vec::new().into()),
Value::List(vec![Value::String("b".into())].into()),
]]
);
}
fn projected_ws(graph: &Graph, q: &str) -> Vec<i64> {
let result = exec_cypher(graph, q);
let mut ws = column(&result, "props", |value| match value {
Value::Map(m) => match m.get("w") {
Some(Value::Int(w)) => Some(*w),
_ => None,
},
_ => None,
});
ws.sort_unstable();
ws
}
#[test]
fn var_length_all_properties_projection_reads_the_store() {
let graph = lazy_chain_graph();
assert_eq!(
projected_ws(
&graph,
"MATCH (x:N {id: 'a'})-[r:R*1..2]->(y) UNWIND r AS e RETURN e{.*} AS props"
),
vec![1, 1, 2]
);
assert_eq!(
projected_ws(
&graph,
"MATCH TRAIL (x:N {id: 'a'})-[r:R]->{1,2}(y) UNWIND r AS e \
RETURN e{.*} AS props"
),
vec![1, 1, 2]
);
}
#[test]
fn shortest_route_all_properties_projection_reads_the_store() {
let graph = lazy_chain_graph();
assert_eq!(
projected_ws(
&graph,
"MATCH ANY SHORTEST (x:N {id: 'a'})-[r:R*1..2]->(y:N {id: 'c'}) \
UNWIND r AS e RETURN e{.*} AS props"
),
vec![1, 2]
);
assert_eq!(
projected_ws(
&graph,
"MATCH p = ANY SHORTEST (x:N {id: 'a'})-[r:R]->+(y:N {id: 'c'}) \
UNWIND r AS e RETURN e{.*} AS props"
),
vec![1, 2]
);
assert_eq!(
projected_ws(
&graph,
"MATCH TRAIL (x:N {id: 'a'})-[r:R]->(y) RETURN r{.*} AS props"
),
vec![1]
);
}