use std::collections::HashSet;
use relate_names::SmallName;
use crate::search::SearchSpec;
use crate::walk::each_label_expr_child;
use crate::Bearing;
use crate::{
Clause, Expr, LabelExpr, OrderItem, PathPattern, Projection, Query, RemoveItem, SetItem,
};
mod pattern;
mod clause;
pub(crate) use clause::clause_patterns;
pub use clause::clause_read_vars;
use pattern::for_each_payload_field;
pub use pattern::{
any_pattern_payload, pattern_anchor_variables, pattern_node_anchor_variables,
walk_pattern_elements, walk_pattern_payloads, PatternPayload,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExprRole {
Read,
WriteTarget,
}
pub fn walk_query<'a>(
query: &'a Query,
on_clause: &mut impl FnMut(&'a Clause),
on_expr: &mut impl FnMut(&'a Expr),
) {
walk_query_with_roles(query, on_clause, &mut |expr, _role| on_expr(expr));
}
pub(crate) fn walk_query_with_roles<'a>(
query: &'a Query,
on_clause: &mut impl FnMut(&'a Clause),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
walk_query_at(
query,
false,
&mut |clause, _nested| on_clause(clause),
on_expr,
);
}
fn walk_query_at<'a>(
query: &'a Query,
nested: bool,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
for part in &query.parts {
walk_clauses_at(&part.clauses, nested, on_clause, on_expr);
}
if let Some(next) = query.next.as_deref() {
walk_query_at(next, nested, on_clause, on_expr);
}
}
pub fn walk_clauses<'a>(
clauses: &'a [Clause],
on_clause: &mut impl FnMut(&'a Clause),
on_expr: &mut impl FnMut(&'a Expr),
) {
walk_clauses_at(
clauses,
false,
&mut |clause, _nested| on_clause(clause),
&mut |expr, _role| on_expr(expr),
);
}
pub fn walk_clauses_with_roles<'a>(
clauses: &'a [Clause],
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
walk_clauses_at(clauses, false, on_clause, on_expr);
}
fn walk_clauses_at<'a>(
clauses: &'a [Clause],
nested: bool,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
for clause in clauses {
on_clause(clause, nested);
match clause {
Clause::Match {
patterns,
where_clause,
search,
..
} => {
for pattern in patterns {
walk_pattern(pattern, ExprRole::Read, on_clause, on_expr);
}
if let Some(where_clause) = where_clause {
walk_expr(where_clause, ExprRole::Read, on_clause, on_expr);
}
if let Some(search) = search {
if let Some(post_where) = &search.post_where {
walk_expr(post_where, ExprRole::Read, on_clause, on_expr);
}
walk_search_spec(&search.spec, on_clause, on_expr);
}
}
Clause::Create { patterns } => {
for pattern in patterns {
walk_pattern(pattern, ExprRole::WriteTarget, on_clause, on_expr);
}
}
Clause::Merge {
pattern,
on_create,
on_match,
} => {
walk_pattern(pattern, ExprRole::WriteTarget, on_clause, on_expr);
for item in on_create.iter().chain(on_match) {
walk_set_item(item, on_clause, on_expr);
}
}
Clause::Call {
args, where_clause, ..
} => {
for arg in args.args() {
walk_expr(arg, ExprRole::Read, on_clause, on_expr);
}
if let Some(where_clause) = where_clause {
walk_expr(where_clause, ExprRole::Read, on_clause, on_expr);
}
}
Clause::Delete { expressions, .. } => {
for expr in expressions {
walk_expr(expr, ExprRole::Read, on_clause, on_expr);
}
}
Clause::Set { items } => {
for item in items {
walk_set_item(item, on_clause, on_expr);
}
}
Clause::Remove { items } => {
for item in items {
walk_remove_item(item, on_clause, on_expr);
}
}
Clause::With {
items,
order,
skip,
limit,
where_clause,
group_by,
..
} => {
walk_projection(items, order, skip, limit, group_by, on_clause, on_expr);
if let Some(where_clause) = where_clause {
walk_expr(where_clause, ExprRole::Read, on_clause, on_expr);
}
}
Clause::Return {
items,
order,
skip,
limit,
group_by,
..
} => {
walk_projection(items, order, skip, limit, group_by, on_clause, on_expr);
}
Clause::Unwind { expression, .. } => {
walk_expr(expression, ExprRole::Read, on_clause, on_expr)
}
Clause::LoadCsv { url, .. } => walk_expr(url, ExprRole::Read, on_clause, on_expr),
Clause::CallSubquery {
query,
in_transactions,
..
} => {
walk_query_at(query, true, on_clause, on_expr);
if let Some(tx) = in_transactions {
for expr in tx.exprs() {
walk_expr(expr, ExprRole::Read, on_clause, on_expr);
}
}
}
Clause::Conditional {
branches,
else_query,
} => {
for (predicate, query) in branches {
walk_expr(predicate, ExprRole::Read, on_clause, on_expr);
walk_query_at(query, true, on_clause, on_expr);
}
if let Some(query) = else_query.as_deref() {
walk_query_at(query, true, on_clause, on_expr);
}
}
Clause::Foreach { list, clauses, .. } => {
walk_expr(list, ExprRole::Read, on_clause, on_expr);
walk_clauses_at(clauses, true, on_clause, on_expr);
}
Clause::Use { graph } => walk_expr(graph, ExprRole::Read, on_clause, on_expr),
Clause::Catalog(_)
| Clause::CreateIndex { .. }
| Clause::DropIndex { .. }
| Clause::ShowIndexes
| Clause::Finish => {}
}
}
}
fn walk_search_spec<'a>(
spec: &'a SearchSpec,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
for expr in spec.exprs() {
walk_expr(expr, ExprRole::Read, on_clause, on_expr);
}
}
pub(crate) fn walk_expr<'a>(
expr: &'a Expr,
role: ExprRole,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
on_expr(expr, role);
match expr.bearing() {
Some(Bearing::Subquery(query)) => {
walk_query_at(query, true, on_clause, on_expr);
return;
}
Some(Bearing::Pattern(path)) => {
walk_pattern(path, role, on_clause, on_expr);
return;
}
None => {}
}
expr.each_child(&mut |child| walk_expr(child, role, &mut *on_clause, &mut *on_expr));
}
fn walk_projection<'a>(
items: &'a [Projection],
order: &'a [OrderItem],
skip: &'a Option<Expr>,
limit: &'a Option<Expr>,
group_by: &'a Option<Vec<Expr>>,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
for item in items {
walk_expr(&item.expr, ExprRole::Read, on_clause, on_expr);
}
for item in order {
walk_expr(&item.expr, ExprRole::Read, on_clause, on_expr);
}
for expr in skip.iter().chain(limit) {
walk_expr(expr, ExprRole::Read, on_clause, on_expr);
}
if let Some(group_by) = group_by {
for expr in group_by {
walk_expr(expr, ExprRole::Read, on_clause, on_expr);
}
}
}
fn walk_set_item<'a>(
item: &'a SetItem,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
match item {
SetItem::Property { target, value }
| SetItem::ReplaceAll { target, value }
| SetItem::MergeMap { target, value }
| SetItem::LabelsFunction { target, value, .. } => {
walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr);
walk_expr(value, ExprRole::Read, on_clause, on_expr);
}
SetItem::Labels { target, labels } => {
walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr);
for label in labels {
walk_label_expr(label, ExprRole::WriteTarget, on_clause, on_expr);
}
}
}
}
fn walk_remove_item<'a>(
item: &'a RemoveItem,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
match item {
RemoveItem::Property { target } => {
walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr)
}
RemoveItem::Labels { target, labels } => {
walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr);
for label in labels {
walk_label_expr(label, ExprRole::WriteTarget, on_clause, on_expr);
}
}
}
}
fn walk_pattern<'a>(
pattern: &'a PathPattern,
role: ExprRole,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
walk_pattern_full(pattern, role, on_clause, on_expr, &mut |_| {});
}
fn walk_pattern_full<'a>(
pattern: &'a PathPattern,
role: ExprRole,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
on_binding: &mut impl FnMut(&'a SmallName),
) {
for name in pattern.path_names() {
on_binding(name);
}
walk_pattern_payloads(pattern, &mut |payload| {
for_each_payload_field(
payload,
&mut |expr| walk_expr(expr, role, on_clause, on_expr),
on_binding,
);
});
if let Some(where_clause) = pattern.where_clause.as_deref() {
walk_expr(where_clause, role, on_clause, on_expr);
}
}
pub fn path_pattern_mentions(path: &PathPattern, out: &mut HashSet<String>) {
let mut bindings = HashSet::new();
walk_pattern_full(
path,
ExprRole::Read,
&mut |_, _| {},
&mut |expr, _role| crate::expr_vars(expr, out),
&mut |name| {
bindings.insert(name.to_string());
},
);
out.extend(bindings);
}
fn walk_label_expr<'a>(
label_expr: &'a LabelExpr,
role: ExprRole,
on_clause: &mut impl FnMut(&'a Clause, bool),
on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
each_label_expr_child(label_expr, &mut |child| {
walk_expr(child, role, &mut *on_clause, &mut *on_expr)
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
Direction, DynamicLabelQuantifier, MatchMode, NodePattern, PatternElement,
QuantifiedPathPattern, RelPattern, SingleQuery,
};
fn var(name: &str) -> Expr {
Expr::Variable(name.into())
}
fn use_clause(name: &str) -> Clause {
Clause::Use {
graph: Expr::Variable(name.into()),
}
}
fn query(clauses: Vec<Clause>) -> Query {
Query {
parts: vec![SingleQuery { clauses }],
union_all: Vec::new(),
next: None,
}
}
fn dynamic_label(name: &str) -> LabelExpr {
LabelExpr::Dynamic {
expr: Box::new(Expr::CountSubquery {
query: query(vec![use_clause(name)]),
}),
quantifier: DynamicLabelQuantifier::Default,
}
}
fn seen_use_graphs(query: &Query) -> Vec<String> {
let mut seen = Vec::new();
walk_query(
query,
&mut |clause| {
if let Clause::Use {
graph: Expr::Variable(name),
} = clause
{
seen.push(name.to_string());
}
},
&mut |_| {},
);
seen
}
#[test]
fn walk_query_descends_into_set_and_remove_label_payloads() {
let top = query(vec![
Clause::Set {
items: vec![SetItem::Labels {
target: Expr::Variable("n".into()),
labels: vec![dynamic_label("set_inner")],
}],
},
Clause::Remove {
items: vec![RemoveItem::Labels {
target: Expr::Variable("n".into()),
labels: vec![dynamic_label("remove_inner")],
}],
},
]);
assert_eq!(
seen_use_graphs(&top),
vec!["set_inner".to_string(), "remove_inner".to_string()]
);
}
#[test]
fn walk_query_descends_into_pattern_element_label_exprs() {
fn node(label: Option<LabelExpr>) -> NodePattern {
NodePattern {
variable: None,
labels: Vec::new(),
label_expr: label,
properties: None,
prop_keys: Vec::new(),
where_clause: None,
force_scan: false,
}
}
let pattern = PathPattern {
variable: None,
subpath_variable: None,
nodes: Vec::new(),
rels: Vec::new(),
elements: vec![
PatternElement::Node(node(Some(dynamic_label("node_label")))),
PatternElement::Relationship(RelPattern {
variable: None,
types: Vec::new(),
type_expr: Some(dynamic_label("rel_type")),
direction: Direction::Outgoing,
properties: None,
prop_keys: Vec::new(),
var_length: false,
min_hops: 1,
max_hops: None,
where_clause: None,
quantified: false,
}),
PatternElement::Quantified(QuantifiedPathPattern {
subpath_variable: None,
elements: vec![PatternElement::Node(node(Some(dynamic_label(
"quantified_node",
))))],
where_clause: None,
min: 1,
max: None,
}),
],
where_clause: None,
mode: None,
selector: None,
is_shortest_path_function: false,
};
let top = query(vec![Clause::Match {
optional: false,
match_mode: MatchMode::DifferentRelationships,
patterns: vec![pattern],
where_clause: None,
using_index: Vec::new(),
using_join: Vec::new(),
search: None,
}]);
assert_eq!(
seen_use_graphs(&top),
vec![
"node_label".to_string(),
"rel_type".to_string(),
"quantified_node".to_string()
]
);
}
#[test]
fn walk_pattern_visits_compact_pattern_payloads_exactly_once() {
let node = NodePattern {
variable: None,
labels: Vec::new(),
label_expr: Some(dynamic_label("node_label")),
properties: None,
prop_keys: Vec::new(),
where_clause: None,
force_scan: false,
};
let pattern = PathPattern {
variable: None,
subpath_variable: None,
nodes: vec![node.clone()],
rels: Vec::new(),
elements: vec![PatternElement::Node(node)],
where_clause: None,
mode: None,
selector: None,
is_shortest_path_function: false,
};
let top = query(vec![Clause::Match {
optional: false,
match_mode: MatchMode::DifferentRelationships,
patterns: vec![pattern],
where_clause: None,
using_index: Vec::new(),
using_join: Vec::new(),
search: None,
}]);
assert_eq!(seen_use_graphs(&top), vec!["node_label".to_string()]);
}
#[test]
fn walk_query_descends_into_subqueries_and_next_stages() {
let mut top = query(vec![
Clause::CallSubquery {
query: Box::new(query(vec![use_clause("call_inner")])),
optional: false,
scope: crate::CallScope::Wildcard,
in_transactions: None,
},
Clause::Return {
distinct: false,
group_by: None,
items: vec![Projection {
expr: Expr::CountSubquery {
query: query(vec![use_clause("count_inner")]),
},
alias: None,
source_text: None,
}],
order: Vec::new(),
skip: None,
limit: None,
},
]);
top.next = Some(Box::new(query(vec![use_clause("next_stage")])));
let mut seen: Vec<String> = Vec::new();
walk_query(
&top,
&mut |clause| {
if let Clause::Use { graph } = clause {
seen.push(format!("{graph:?}"));
}
},
&mut |_| {},
);
assert_eq!(seen.len(), 3, "expected all three USE clauses: {seen:?}");
}
#[test]
fn path_pattern_mentions_covers_bindings_predicates_and_compact_view() {
let rel = |variable: Option<&str>, where_clause: Option<Expr>| RelPattern {
variable: variable.map(Into::into),
types: vec![],
type_expr: None,
direction: crate::Direction::Outgoing,
properties: None,
prop_keys: Vec::new(),
var_length: false,
min_hops: 1,
max_hops: None,
where_clause,
quantified: false,
};
let node = |variable: Option<&str>,
label_expr: Option<LabelExpr>,
properties: Option<Expr>,
where_clause: Option<Expr>| NodePattern {
variable: variable.map(Into::into),
labels: vec![],
label_expr,
properties,
prop_keys: Vec::new(),
where_clause,
force_scan: false,
};
let path = PathPattern {
variable: None,
subpath_variable: None,
elements: vec![],
nodes: vec![node(
Some("n"),
Some(LabelExpr::Dynamic {
expr: Box::new(var("lbl")),
quantifier: crate::DynamicLabelQuantifier::Default,
}),
Some(var("props")),
Some(var("nw")),
)],
rels: vec![rel(Some("r"), Some(var("rw")))],
where_clause: Some(Box::new(var("pw"))),
mode: None,
selector: None,
is_shortest_path_function: false,
};
let mut out = HashSet::new();
path_pattern_mentions(&path, &mut out);
for expected in ["n", "r", "lbl", "props", "nw", "rw", "pw"] {
assert!(out.contains(expected), "missing mention {expected}");
}
assert!(!out.contains("other"));
let path = PathPattern {
variable: None,
subpath_variable: None,
elements: vec![PatternElement::Quantified(crate::QuantifiedPathPattern {
subpath_variable: Some("q".into()),
elements: vec![PatternElement::Node(node(None, None, None, None))],
where_clause: Some(var("qw")),
min: 1,
max: None,
})],
nodes: vec![],
rels: vec![],
where_clause: None,
mode: None,
selector: None,
is_shortest_path_function: false,
};
let mut out = HashSet::new();
path_pattern_mentions(&path, &mut out);
for expected in ["q", "qw"] {
assert!(out.contains(expected), "missing mention {expected}");
}
assert!(!out.contains("n"));
}
}