use std::collections::BTreeMap;
use relate_ir::{Direction, NodePattern, PathPattern, PatternElement, RelPattern};
use super::nfa::{compile, FrontierNfa, STATE_CEILING};
use crate::exec::test_support::{
named_node, one_hop_rel, path_pattern, patterns, quantified, var_length_rel,
};
use crate::graph::Graph;
use crate::pattern_engine::PatternEngine;
fn graph_with_types(names: &[&str]) -> Graph {
let graph = Graph::default();
graph.begin_write().unwrap();
let a = graph
.create_node(vec!["N".into()], BTreeMap::new())
.unwrap();
let b = graph
.create_node(vec!["N".into()], BTreeMap::new())
.unwrap();
for name in names {
graph
.create_rel(a, b, (*name).into(), BTreeMap::new())
.unwrap();
}
graph.commit_write();
graph
}
fn compiled(cypher: &str, names: &[&str]) -> (Graph, FrontierNfa) {
let graph = graph_with_types(names);
let pattern = &patterns(cypher)[0];
let nfa = compile(&graph, pattern, PatternEngine::Auto)
.unwrap_or_else(|| panic!("{cypher} should compile"));
(graph, nfa)
}
fn declines(cypher: &str, names: &[&str]) {
let graph = graph_with_types(names);
let pattern = &patterns(cypher)[0];
assert!(
compile(&graph, pattern, PatternEngine::Auto).is_none(),
"{cypher} should decline"
);
}
#[test]
fn hops_family_parity() {
let (graph, nfa) = compiled(
"MATCH p = (x:Person)-[:knows*1..]-(y) WHERE x.ID = 1 RETURN p LIMIT 100",
&["knows"],
);
assert_eq!((nfa.states, nfa.start), (1, 0));
assert_eq!((nfa.min_hops, nfa.max_hops), (1, None));
assert_eq!(nfa.accepting, vec![true]);
assert!(nfa.epsilons.is_empty());
assert_eq!(nfa.transitions.len(), 1);
let t = &nfa.transitions[0];
assert_eq!((t.from, t.to), (0, 0));
assert_eq!(t.types, vec![graph.rel_type_id("knows").unwrap()]);
assert_eq!(t.direction, Direction::Both);
assert!(t.accepts);
let (_, nfa) = compiled(
"MATCH p = (x:Person)-[:knows*0..]-(y) RETURN p LIMIT 100",
&["knows"],
);
assert_eq!((nfa.min_hops, nfa.max_hops), (0, None));
let (_, nfa) = compiled(
"MATCH p = (x:Person)-[:knows*2..5]-(y) RETURN p LIMIT 100",
&["knows"],
);
assert_eq!(nfa.states, 1);
assert_eq!((nfa.min_hops, nfa.max_hops), (2, Some(5)));
let (graph, nfa) = compiled(
"MATCH p = (x:Comment)-[:commentHasCreator|postHasCreator|commentIsLocatedIn|\
organisationIsLocatedIn|personIsLocatedIn|postIsLocatedIn*1..]-(y) \
WHERE x.ID = 1 RETURN p LIMIT 100",
&[
"commentHasCreator",
"postHasCreator",
"commentIsLocatedIn",
"organisationIsLocatedIn",
"personIsLocatedIn",
"postIsLocatedIn",
],
);
assert_eq!(nfa.states, 1);
assert_eq!(nfa.transitions.len(), 1);
assert_eq!(
nfa.transitions[0].types,
[
"commentHasCreator",
"postHasCreator",
"commentIsLocatedIn",
"organisationIsLocatedIn",
"personIsLocatedIn",
"postIsLocatedIn"
]
.iter()
.map(|name| graph.rel_type_id(name).unwrap())
.collect::<Vec<_>>()
);
}
#[test]
fn rounds_family_parity() {
let (graph, nfa) = compiled(
"MATCH p = (x:Person)((a)-[:likeComment|likePost]-(b)\
-[:commentHasCreator|postHasCreator]-(c)){1,}(y) WHERE x.ID = 1 RETURN p LIMIT 100",
&[
"likeComment",
"likePost",
"commentHasCreator",
"postHasCreator",
],
);
assert_eq!((nfa.states, nfa.start), (2, 0));
assert_eq!((nfa.min_hops, nfa.max_hops), (2, None));
assert_eq!(nfa.accepting, vec![true, false]);
assert!(nfa.epsilons.is_empty());
assert_eq!(nfa.transitions.len(), 2);
let (likes, has_creator) = (
[
graph.rel_type_id("likeComment").unwrap(),
graph.rel_type_id("likePost").unwrap(),
],
[
graph.rel_type_id("commentHasCreator").unwrap(),
graph.rel_type_id("postHasCreator").unwrap(),
],
);
assert_eq!((nfa.transitions[0].from, nfa.transitions[0].to), (0, 1));
assert_eq!(nfa.transitions[0].types, likes);
assert!(!nfa.transitions[0].accepts);
assert_eq!((nfa.transitions[1].from, nfa.transitions[1].to), (1, 0));
assert_eq!(nfa.transitions[1].types, has_creator);
assert!(nfa.transitions[1].accepts);
let (_, nfa) = compiled(
"MATCH p = (x:Person)((a)-[:likeComment]-(b)-[:postHasCreator]-(c)){2,4}(y) \
RETURN p LIMIT 100",
&["likeComment", "postHasCreator"],
);
assert_eq!(nfa.states, 2);
assert_eq!((nfa.min_hops, nfa.max_hops), (4, Some(8)));
assert!(nfa.epsilons.is_empty());
}
#[test]
fn concatenation_context_compiles() {
let (_, nfa) = compiled(
"MATCH p = (x:Person)-[:knows*1..]-()-[:studyAt]-(y) WHERE x.ID = 1 \
RETURN p LIMIT 100",
&["knows", "studyAt"],
);
assert_eq!(nfa.states, 2);
assert_eq!(nfa.accepting, vec![false, true]);
assert_eq!((nfa.min_hops, nfa.max_hops), (2, None));
assert_eq!(nfa.transitions.len(), 2);
assert_eq!((nfa.transitions[0].from, nfa.transitions[0].to), (0, 0));
assert!(!nfa.transitions[0].accepts);
assert_eq!((nfa.transitions[1].from, nfa.transitions[1].to), (0, 1));
assert!(nfa.transitions[1].accepts);
let (_, nfa) = compiled(
"MATCH p = (x:Person)-[:knows]-()-[:knows*1..]-(y) WHERE x.ID = 1 \
RETURN p LIMIT 100",
&["knows"],
);
assert_eq!(nfa.states, 2);
assert_eq!(nfa.accepting, vec![false, true]);
assert_eq!((nfa.min_hops, nfa.max_hops), (2, None));
assert_eq!(nfa.transitions.len(), 2);
assert_eq!((nfa.transitions[0].from, nfa.transitions[0].to), (0, 1));
assert!(nfa.transitions[0].accepts);
assert_eq!((nfa.transitions[1].from, nfa.transitions[1].to), (1, 1));
assert!(nfa.transitions[1].accepts);
}
#[test]
fn direction_tags_per_transition() {
let (_, nfa) = compiled(
"MATCH p = (x:Person)-[:knows*1..]->(y) RETURN p LIMIT 100",
&["knows"],
);
assert_eq!(nfa.transitions[0].direction, Direction::Outgoing);
let (_, nfa) = compiled(
"MATCH p = (x:Person)<-[:knows*1..]-(y) RETURN p LIMIT 100",
&["knows"],
);
assert_eq!(nfa.transitions[0].direction, Direction::Incoming);
let (_, nfa) = compiled(
"MATCH p = (x:Person)-[:knows*1..]-()-[:studyAt]->(y) RETURN p LIMIT 100",
&["knows", "studyAt"],
);
assert_eq!(nfa.transitions[0].direction, Direction::Both);
assert_eq!(nfa.transitions[1].direction, Direction::Outgoing);
}
fn compiled_ir(pattern: &PathPattern, names: &[&str]) -> FrontierNfa {
let graph = graph_with_types(names);
compile(&graph, pattern, PatternEngine::Auto)
.unwrap_or_else(|| panic!("{pattern:?} should compile"))
}
fn declines_ir(pattern: &PathPattern, names: &[&str]) {
let graph = graph_with_types(names);
assert!(
compile(&graph, pattern, PatternEngine::Auto).is_none(),
"{pattern:?} should decline"
);
}
#[test]
fn nested_exact_quantifier_is_the_rounds_family() {
let pattern = path_pattern(vec![
PatternElement::Node(named_node("x")),
PatternElement::Quantified(quantified(
vec![
PatternElement::Node(NodePattern::anonymous()),
PatternElement::Relationship(var_length_rel(&["knows"], 2, Some(2))),
PatternElement::Node(NodePattern::anonymous()),
],
1,
None,
)),
PatternElement::Node(named_node("y")),
]);
let nfa = compiled_ir(&pattern, &["knows"]);
assert_eq!((nfa.states, nfa.start), (2, 0));
assert_eq!((nfa.min_hops, nfa.max_hops), (2, None));
assert_eq!(nfa.accepting, vec![true, false]);
assert!(nfa.epsilons.is_empty());
assert_eq!(nfa.transitions.len(), 2);
assert_eq!((nfa.transitions[0].from, nfa.transitions[0].to), (0, 1));
assert_eq!((nfa.transitions[1].from, nfa.transitions[1].to), (1, 0));
assert!(nfa.transitions[1].accepts && !nfa.transitions[0].accepts);
}
#[test]
fn nested_bounded_quantifier_unrolls() {
let as_var_length = path_pattern(vec![
PatternElement::Node(named_node("x")),
PatternElement::Quantified(quantified(
vec![
PatternElement::Node(NodePattern::anonymous()),
PatternElement::Relationship(var_length_rel(&["knows"], 2, Some(3))),
PatternElement::Node(NodePattern::anonymous()),
],
2,
Some(4),
)),
PatternElement::Node(named_node("y")),
]);
let as_nested_group = path_pattern(vec![
PatternElement::Node(named_node("x")),
PatternElement::Quantified(quantified(
vec![
PatternElement::Node(NodePattern::anonymous()),
PatternElement::Quantified(quantified(
vec![
PatternElement::Node(NodePattern::anonymous()),
PatternElement::Relationship(one_hop_rel(&["knows"])),
PatternElement::Node(NodePattern::anonymous()),
],
2,
Some(3),
)),
PatternElement::Node(NodePattern::anonymous()),
],
2,
Some(4),
)),
PatternElement::Node(named_node("y")),
]);
let a = compiled_ir(&as_var_length, &["knows"]);
let b = compiled_ir(&as_nested_group, &["knows"]);
assert!(a.states <= STATE_CEILING);
assert_eq!(a.states, 13);
assert_eq!((a.min_hops, a.max_hops), (4, Some(12)));
assert_eq!(a.transitions.len(), 12);
assert_eq!(a.epsilons.len(), 6);
assert!(a.transitions.iter().all(|t| t.types.len() == 1));
assert!(a.accepting[12]);
assert!(a.accepting.iter().filter(|accept| **accept).count() >= 2);
let shape = |nfa: &FrontierNfa| {
nfa.transitions
.iter()
.map(|t| (t.from, t.to, t.types.clone(), t.accepts))
.collect::<Vec<_>>()
};
assert_eq!(shape(&a), shape(&b));
assert_eq!(a.epsilons, b.epsilons);
assert_eq!((b.states, b.min_hops, b.max_hops), (13, 4, Some(12)));
}
#[test]
fn declines_unsound_nested_quantifiers() {
let outer = |inner: RelPattern, min: u32, max: Option<u32>| {
path_pattern(vec![
PatternElement::Node(named_node("x")),
PatternElement::Quantified(quantified(
vec![
PatternElement::Node(NodePattern::anonymous()),
PatternElement::Relationship(inner),
PatternElement::Node(NodePattern::anonymous()),
],
min,
max,
)),
PatternElement::Node(named_node("y")),
])
};
declines_ir(
&outer(var_length_rel(&["knows"], 1, None), 2, Some(4)),
&["knows"],
);
declines_ir(
&outer(var_length_rel(&["knows"], 0, None), 1, None),
&["knows"],
);
declines_ir(
&outer(var_length_rel(&["knows"], 2, Some(3)), 1, None),
&["knows"],
);
}
#[test]
fn declines_above_the_state_ceiling() {
let group = |hops: usize| {
let mut body = String::from("((a)");
for _ in 0..hops {
body.push_str("-[:knows]-()");
}
format!("MATCH p = (x){body}){{1,}}(y) RETURN p LIMIT 100")
};
let (_, nfa) = compiled(&group(64), &["knows"]);
assert_eq!(nfa.states, STATE_CEILING);
assert_eq!((nfa.min_hops, nfa.max_hops), (64, None));
declines(&group(65), &["knows"]);
}
#[test]
fn declines_predicate_bearing_inner_rel() {
declines(
"MATCH p = (x)((a)-[:knows {since: 2010}]-(b)){1,}(y) RETURN p LIMIT 100",
&["knows"],
);
declines(
"MATCH p = (x)((a)-[r:knows WHERE r.since < 2010]-(b)){1,}(y) RETURN p LIMIT 100",
&["knows"],
);
}
#[test]
fn declines_selector() {
declines(
"MATCH p = ANY SHORTEST (x:Person)-[:knows*1..]-(y) RETURN p LIMIT 100",
&["knows"],
);
}
#[test]
fn declines_subpath_variable() {
let graph = graph_with_types(&["knows"]);
let mut qpp = quantified(
vec![
PatternElement::Node(named_node("a")),
PatternElement::Relationship(one_hop_rel(&["knows"])),
PatternElement::Node(named_node("b")),
],
1,
None,
);
qpp.subpath_variable = Some("r".into());
let pattern = path_pattern(vec![
PatternElement::Node(named_node("x")),
PatternElement::Quantified(qpp),
PatternElement::Node(named_node("y")),
]);
assert!(
compile(&graph, &pattern, PatternEngine::Auto).is_none(),
"a named quantified group should decline"
);
}
#[test]
fn compiles_empty_type_list_as_the_any_type_set() {
let (graph, nfa) = compiled(
"MATCH p = (x:Person)-[*1..]-(y) RETURN p LIMIT 100",
&["knows"],
);
assert!(!nfa.transitions.is_empty(), "the unrolled body emits hops");
for t in &nfa.transitions {
assert!(
t.types.is_empty(),
"the untyped hop carries no interned id, got {:?}",
t.types
);
}
assert!(graph.rel_type_id("knows").is_some());
}
#[test]
fn declines_out_of_vocabulary_shapes() {
declines(
"MATCH p = (x:Person)-[:knows*1..]-(m)-[:studyAt*1..]-(y) RETURN p LIMIT 100",
&["knows", "studyAt"],
);
declines(
"MATCH p = (x)((a)-[:knows]-(b) WHERE a.k > 1){1,}(y) RETURN p LIMIT 100",
&["knows"],
);
declines(
"MATCH p = (x)((a:Person)-[:knows]-(b)){1,}(y) RETURN p LIMIT 100",
&["knows"],
);
declines(
"MATCH p = (x:Person)-[:knows]-(m:Person)-[:studyAt*1..]-(y) RETURN p LIMIT 100",
&["knows", "studyAt"],
);
declines(
"MATCH p = (x:Person)-[:knows*1..]-(y) RETURN p LIMIT 100",
&["studyAt"],
);
declines(
"MATCH p = ((x:Person)-[:knows*1..]-(y) WHERE x.ID > 1) RETURN p LIMIT 100",
&["knows"],
);
}
mod forced;