use super::hub_join::{take_hub_join_engagements, with_hub_join_disabled};
use super::pivot::{take_pivot_backward_hops, with_pivot_disabled};
use super::test_support::exec_cypher;
use super::*;
use crate::graph::Graph;
fn pair_graph() -> Graph {
let g = Graph::default();
g.begin_write().unwrap();
let users: Vec<_> = (0..3)
.map(|i| {
g.create_node(
vec!["User".into()],
BTreeMap::from([("name".into(), Value::String(format!("u{i}").into()))]),
)
.unwrap()
})
.collect();
let questions: Vec<_> = (0..2)
.map(|i| {
g.create_node(
vec!["Question".into()],
BTreeMap::from([("title".into(), Value::String(format!("q{i}").into()))]),
)
.unwrap()
})
.collect();
for (u, q) in [(0, 0), (1, 0), (2, 1)] {
let c = g
.create_node(vec!["Comment".into()], BTreeMap::new())
.unwrap();
g.create_rel(users[u], c, "COMMENTED".into(), BTreeMap::new())
.unwrap();
g.create_rel(c, questions[q], "COMMENTED_ON".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
g
}
const PAIR_QUERY: &str =
"MATCH p1=(u1:User)-[:COMMENTED]->(c1:Comment)-[:COMMENTED_ON]-(q:Question) \
MATCH p2=(u2:User)-[:COMMENTED]->(c2:Comment)-[:COMMENTED_ON]-(q) \
WHERE id(u1) < id(u2) \
RETURN id(u1) AS i1, id(u2) AS i2, id(q) AS iq, p2 AS p2 \
ORDER BY i1, i2";
#[test]
fn pivot_pairs_match_the_index_zero_expansion() {
let g = pair_graph();
let _ = take_pivot_backward_hops();
let pivoted = exec_cypher(&g, PAIR_QUERY);
let plain = with_pivot_disabled(|| exec_cypher(&g, PAIR_QUERY));
assert_eq!(pivoted.rows, plain.rows);
assert_eq!(pivoted.rows.len(), 1);
let row = &pivoted.rows[0];
let Value::Path(p2) = &row[3] else {
panic!("p2 must be a path: {:?}", row[3]);
};
let (i1, i2, iq) = (
row[0].as_int().unwrap(),
row[1].as_int().unwrap(),
row[2].as_int().unwrap(),
);
assert_eq!((i1, i2, iq), (0, 1, 3));
let ids: Vec<_> = p2.nodes.iter().map(|n| n.id).collect();
assert_eq!((ids[0], ids[2]), (i2, iq));
assert_eq!(p2.rels.len(), 2);
assert_eq!(p2.rels[0].rel_type, "COMMENTED");
assert_eq!(p2.rels[1].rel_type, "COMMENTED_ON");
for (r, (a, b)) in p2.rels.iter().zip(ids.iter().zip(ids.iter().skip(1))) {
assert!((r.start == *a && r.end == *b) || (r.start == *b && r.end == *a));
}
}
#[test]
fn pivot_engages_on_the_bound_tail() {
let g = pair_graph();
let _ = take_pivot_backward_hops();
let _ = exec_cypher(&g, PAIR_QUERY);
assert!(take_pivot_backward_hops() > 0);
let _ = with_pivot_disabled(|| exec_cypher(&g, PAIR_QUERY));
assert_eq!(take_pivot_backward_hops(), 0);
}
#[test]
fn var_length_prefix_keeps_the_index_zero_start() {
let g = pair_graph();
let query = "MATCH (u2:User)-[:COMMENTED*1..1]->(c2:Comment)-[:COMMENTED_ON]-(q:Question) \
RETURN id(u2) AS i2, id(c2) AS ic, id(q) AS iq \
ORDER BY i2, ic, iq";
let _ = take_pivot_backward_hops();
let varlen = exec_cypher(&g, query);
assert_eq!(take_pivot_backward_hops(), 0);
let plain = with_pivot_disabled(|| exec_cypher(&g, query));
assert_eq!(varlen.rows, plain.rows);
assert_eq!(varlen.rows.len(), 3);
}
fn q19_graph(comments: usize) -> Graph {
let g = Graph::default();
g.begin_write().unwrap();
let comments: Vec<_> = (0..comments)
.map(|i| {
g.create_node(
vec!["Comment".into()],
BTreeMap::from([("ID".into(), Value::Int(i as i64))]),
)
.unwrap()
})
.collect();
let tags: Vec<_> = ["Copernicus", "Kepler"]
.iter()
.map(|name| {
g.create_node(
vec!["Tag".into()],
BTreeMap::from([("name".into(), Value::String((*name).into()))]),
)
.unwrap()
})
.collect();
let places: Vec<_> = (0..2)
.map(|i| {
g.create_node(
vec!["Place".into()],
BTreeMap::from([("name".into(), Value::String(format!("place{i}").into()))]),
)
.unwrap()
})
.collect();
for (i, c) in comments.iter().enumerate() {
g.create_rel(*c, tags[0], "commentHasTag".into(), BTreeMap::new())
.unwrap();
g.create_rel(
*c,
places[i % 2],
"commentIsLocatedIn".into(),
BTreeMap::new(),
)
.unwrap();
}
g.commit_write();
g
}
const Q19_QUERY: &str = "MATCH (c:Comment)-[:commentHasTag]->(t:Tag), \
(c)-[:commentIsLocatedIn]->(l:Place) \
WHERE t.name CONTAINS 'Copernicus' \
RETURN l.name AS place, sum(c.ID) AS n ORDER BY n DESC, place";
#[test]
fn cheapest_element_start_matches_the_index_zero_expansion() {
let g = q19_graph(100);
let _ = take_pivot_backward_hops();
let _ = take_hub_join_engagements();
let selected = exec_cypher(&g, Q19_QUERY);
assert_eq!(take_hub_join_engagements(), 0);
with_pivot_disabled(|| {
let unpivoted = exec_cypher(&g, Q19_QUERY);
assert_eq!(unpivoted.rows, selected.rows);
});
assert!(take_pivot_backward_hops() > 0);
assert_eq!(selected.rows.len(), 2);
}
#[test]
fn hub_join_matches_the_nested_loop_rows() {
let g = q19_graph(200);
let _ = take_hub_join_engagements();
let joined = exec_cypher(&g, Q19_QUERY);
assert_eq!(take_hub_join_engagements(), 1);
with_hub_join_disabled(|| {
let _ = take_hub_join_engagements();
let nested = exec_cypher(&g, Q19_QUERY);
assert_eq!(take_hub_join_engagements(), 0);
assert_eq!(nested.rows, joined.rows);
});
assert_eq!(joined.rows.len(), 2);
}
#[test]
fn cheapest_element_start_not_taken_when_index_zero_is_cheapest() {
let g = q19_graph(200);
let _ = take_pivot_backward_hops();
let r = exec_cypher(
&g,
"MATCH (t:Tag)<-[:commentHasTag]-(c:Comment) RETURN count(t) AS n",
);
assert_eq!(r.rows[0][0], Value::Int(200));
assert_eq!(take_pivot_backward_hops(), 0);
}
#[test]
fn cheapest_start_displaces_onto_the_range_filtered_element() {
let g = test_support::range_start_graph("x", &(0..100).map(Value::Int).collect::<Vec<_>>());
test_support::exec_autocommit(&g, "CREATE INDEX FOR (q:Q) ON (q.x)").unwrap();
let query = "MATCH (p:P)-[:LINKS]->(q:Q) WHERE q.x < 4 \
RETURN id(p) AS p, id(q) AS q ORDER BY p, q";
let _ = take_pivot_backward_hops();
let _ = take_walk_start();
let displaced = exec_cypher(&g, query);
assert!(
take_pivot_backward_hops() > 0,
"the walk started at the range-filtered element"
);
let start = take_walk_start().expect("the walk recorded its start");
assert_eq!(
(start.element, start.reason),
(1, crate::ctx::StartReason::Cheapest),
"the LABS-369 walk start names the index-selected start: the range-filtered element, cheapest class"
);
assert_eq!(displaced.rows.len(), 4);
assert_eq!(
(displaced.rows[0][0].clone(), displaced.rows[0][1].clone()),
(Value::Int(0), Value::Int(20)),
"the first row pairs the first P with its window Q"
);
with_pivot_disabled(|| {
let plain = exec_cypher(&g, query);
assert_eq!(plain.rows, displaced.rows);
});
}
#[test]
fn property_bearing_element_zero_is_never_displaced() {
let g = Graph::default();
g.begin_write().unwrap();
let tagged = g.create_node(vec!["Tag".into()], BTreeMap::new()).unwrap();
for i in 0..5 {
let c = g
.create_node(
vec!["Comment".into()],
BTreeMap::from([("id".into(), Value::Int(i))]),
)
.unwrap();
g.create_rel(c, tagged, "commentHasTag".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
test_support::exec_autocommit(&g, "CREATE INDEX FOR (c:Comment) ON (c.id)").unwrap();
let _ = take_pivot_backward_hops();
let r = exec_cypher(
&g,
"MATCH (c:Comment {id: 1})-[:commentHasTag]->(t:Tag) RETURN count(c) AS n",
);
assert_eq!(r.rows[0][0], Value::Int(1));
assert_eq!(take_pivot_backward_hops(), 0);
}
#[test]
fn peer_referenced_prefix_predicate_keeps_the_index_zero_start() {
let g = Graph::default();
g.begin_write().unwrap();
for (id, name) in [(0, "u0"), (1, "u1")] {
let u = g
.create_node(
vec!["User".into()],
BTreeMap::from([
("id".into(), Value::Int(id)),
("name".into(), Value::String(name.into())),
]),
)
.unwrap();
let c = g
.create_node(
vec!["Comment".into()],
BTreeMap::from([("seen".into(), Value::String(name.into()))]),
)
.unwrap();
let q = g
.create_node(vec!["Question".into()], BTreeMap::new())
.unwrap();
g.create_rel(u, c, "COMMENTED".into(), BTreeMap::new())
.unwrap();
g.create_rel(c, q, "COMMENTED_ON".into(), BTreeMap::new())
.unwrap();
}
g.commit_write();
let query = "MATCH (q:Question)<-[:COMMENTED_ON]-(first:Comment) \
MATCH (u2:User)-[:COMMENTED]->(c2:Comment {seen: u2.name})-[:COMMENTED_ON]->(q) \
RETURN u2.name AS name ORDER BY name";
let _ = take_pivot_backward_hops();
let rows = exec_cypher(&g, query);
assert_eq!(take_pivot_backward_hops(), 0);
let names: Vec<String> = rows
.rows
.iter()
.map(|r| r[0].as_string().unwrap().to_string())
.collect();
assert_eq!(names, vec!["u0".to_string(), "u1".to_string()]);
}
mod gate {
fn referencing_pattern() -> PathPattern {
path(vec![
node(Some("a"), None),
node(
Some("m"),
Some(Expr::Map(vec![(
"v".to_string(),
Expr::Property {
key_id: Default::default(),
expr: Box::new(Expr::Variable(SmallName::from_name("a"))),
key: SmallName::from_name("marker"),
},
)])),
),
])
}
use super::super::pivot::pattern_self_contained;
use crate::row::Row;
use relate_ir::Direction;
use relate_ir::{Expr, NodePattern, PathPattern, RelPattern};
use relate_names::SmallName;
fn node(variable: Option<&str>, properties: Option<Expr>) -> NodePattern {
NodePattern {
variable: variable.map(SmallName::from_name),
labels: Vec::new(),
label_expr: None,
properties,
prop_keys: Vec::new(),
where_clause: None,
force_scan: false,
}
}
fn plain_rel() -> RelPattern {
RelPattern {
variable: None,
types: Vec::new(),
type_expr: None,
direction: Direction::Outgoing,
properties: None,
prop_keys: Vec::new(),
var_length: false,
min_hops: 1,
max_hops: Some(1),
where_clause: None,
quantified: false,
}
}
fn path(nodes: Vec<NodePattern>) -> PathPattern {
let rels = vec![plain_rel(); nodes.len().saturating_sub(1)];
PathPattern {
variable: None,
subpath_variable: None,
elements: Vec::new(),
nodes,
rels,
where_clause: None,
mode: None,
selector: None,
is_shortest_path_function: false,
}
}
#[test]
fn peer_referenced_property_map_is_not_self_contained() {
let p = referencing_pattern();
assert!(!pattern_self_contained(&p, &Row::new()));
}
#[test]
fn entry_bound_reference_is_self_contained() {
let p = referencing_pattern();
let mut row = Row::new();
row.insert("a".to_string(), relate_core::Value::Int(1));
assert!(pattern_self_contained(&p, &row));
}
#[test]
fn plain_pattern_is_self_contained() {
let p = path(vec![node(Some("a"), None), node(Some("m"), None)]);
assert!(pattern_self_contained(&p, &Row::new()));
}
}