#![allow(dead_code)]
use std::collections::BTreeMap;
use crate::cypher::ast::{
CallSubquery, Expression, MatchClause, Operand, OrderItem, Pattern, Predicate, ProcedureCall,
Query, ReturnExpression, ReturnItem, ReturnProjection, RowCount, UnwindClause, WithProjection,
};
use crate::cypher::procedure::{resolve as resolve_procedure, ProcedureMode};
use crate::error::{Error, Result};
#[derive(Clone, Debug, PartialEq)]
pub struct Plan {
pub has_initial_match: bool,
pub optional_match: bool,
pub pattern: Pattern,
pub patterns: Vec<Pattern>,
pub predicate: Option<Predicate>,
pub extra_matches: Vec<MatchClause>,
pub unwinds: Vec<UnwindClause>,
pub post_unwind_matches: Vec<MatchClause>,
pub procedure_calls: Vec<PlannedProcedureCall>,
pub post_procedure_unwinds: Vec<UnwindClause>,
pub post_procedure_matches: Vec<MatchClause>,
pub with: Option<PlannedWithProjection>,
pub with_predicate: Option<Predicate>,
pub with_order_by: Vec<OrderItem>,
pub with_skip: Option<RowCount>,
pub with_limit: Option<RowCount>,
pub post_with_unwinds: Vec<UnwindClause>,
pub post_with_matches: Vec<MatchClause>,
pub post_with_procedure_calls: Vec<PlannedProcedureCall>,
pub post_with_procedure_unwinds: Vec<UnwindClause>,
pub post_with_procedure_matches: Vec<MatchClause>,
pub post_with_with: Option<PlannedWithProjection>,
pub post_with_with_predicate: Option<Predicate>,
pub post_with_with_order_by: Vec<OrderItem>,
pub post_with_with_skip: Option<RowCount>,
pub post_with_with_limit: Option<RowCount>,
pub post_with_with_unwinds: Vec<UnwindClause>,
pub post_with_with_matches: Vec<MatchClause>,
pub post_with_with_procedure_calls: Vec<PlannedProcedureCall>,
pub post_with_with_procedure_unwinds: Vec<UnwindClause>,
pub post_with_with_procedure_matches: Vec<MatchClause>,
pub post_with_with_calls: Vec<PlannedCallSubquery>,
pub calls: Vec<PlannedCallSubquery>,
pub post_call_unwinds: Vec<UnwindClause>,
pub post_call_matches: Vec<MatchClause>,
pub post_call_with: Option<PlannedWithProjection>,
pub post_call_with_predicate: Option<Predicate>,
pub post_call_with_order_by: Vec<OrderItem>,
pub post_call_with_skip: Option<RowCount>,
pub post_call_with_limit: Option<RowCount>,
pub post_call_with_unwinds: Vec<UnwindClause>,
pub post_call_with_matches: Vec<MatchClause>,
pub distinct: bool,
pub returns: Vec<ReturnItem>,
pub order_by: Vec<OrderItem>,
pub skip: Option<RowCount>,
pub limit: Option<RowCount>,
pub bound_variables: Vec<String>,
}
#[cfg(test)]
mod procedure_planner_tests {
use super::plan;
use crate::cypher::parser::parse_query;
use crate::error::Error;
#[test]
fn plans_ping_outputs_and_validates_signature() {
let standalone =
plan(parse_query("CALL db.ping()").expect("parse call")).expect("plan standalone call");
assert_eq!(standalone.procedure_calls[0].name, "db.ping");
assert_eq!(standalone.returns.len(), 1);
let aliased =
plan(parse_query("CALL db.ping() YIELD success AS ok RETURN ok").expect("parse call"))
.expect("plan aliased call");
assert_eq!(aliased.procedure_calls[0].yields[0].binding, "ok");
assert!(matches!(
plan(parse_query("CALL db.ping(1)").expect("parse call")),
Err(Error::InvalidProcedureCall { .. })
));
assert!(matches!(
plan(parse_query("CALL db.ping() YIELD missing RETURN missing").expect("parse call")),
Err(Error::InvalidProcedureCall { .. })
));
let after_with = plan(
parse_query("UNWIND [1] AS n WITH n CALL db.ping() YIELD success RETURN n, success")
.unwrap(),
)
.unwrap();
assert_eq!(after_with.post_with_procedure_calls[0].name, "db.ping");
let after_call = plan(
parse_query(
"CALL db.ping() YIELD success AS ok UNWIND [1, 2] AS n \
MATCH (person) RETURN n, ok, person",
)
.unwrap(),
)
.unwrap();
assert_eq!(after_call.post_procedure_unwinds[0].variable, "n");
assert_eq!(after_call.post_procedure_matches.len(), 1);
assert!(after_call.bound_variables.contains(&"ok".to_owned()));
assert!(after_call.bound_variables.contains(&"n".to_owned()));
assert!(after_call.bound_variables.contains(&"person".to_owned()));
let write_after_with =
plan(parse_query("UNWIND [1] AS n WITH n CALL db.createLabel('Late')").unwrap())
.unwrap();
assert_eq!(
write_after_with.post_with_procedure_calls[0].mode,
crate::cypher::procedure::ProcedureMode::Write
);
let write_after_second_with = plan(
parse_query("UNWIND [1] AS n WITH n WITH n CALL db.createProperty('Later') RETURN n")
.unwrap(),
)
.unwrap();
assert_eq!(
write_after_second_with.post_with_with_procedure_calls[0].mode,
crate::cypher::procedure::ProcedureMode::Write
);
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PlannedProcedureCall {
pub name: String,
pub mode: ProcedureMode,
pub arguments: Vec<Expression>,
pub yields: Vec<PlannedProcedureYield>,
pub predicate: Option<Predicate>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlannedProcedureYield {
pub field: String,
pub binding: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PlannedWithProjection {
pub distinct: bool,
pub items: Vec<ReturnItem>,
pub predicate: Option<Predicate>,
pub order_by: Vec<OrderItem>,
pub skip: Option<RowCount>,
pub limit: Option<RowCount>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PlannedCallSubquery {
pub imports: Vec<String>,
pub predicate: Option<Predicate>,
pub unwinds: Vec<UnwindClause>,
pub matches: Vec<MatchClause>,
pub post_match_unwinds: Vec<UnwindClause>,
pub with: Option<PlannedWithProjection>,
pub post_with_unwinds: Vec<UnwindClause>,
pub post_with_matches: Vec<MatchClause>,
pub post_with_with: Option<PlannedWithProjection>,
pub post_with_with_unwinds: Vec<UnwindClause>,
pub post_with_with_matches: Vec<MatchClause>,
pub items: Vec<ReturnItem>,
pub order_by: Vec<OrderItem>,
pub skip: Option<RowCount>,
pub limit: Option<RowCount>,
}
pub fn plan(query: Query) -> Result<Plan> {
let pre_with_match_clauses = query_pre_with_match_clauses(&query);
let match_bound_variables = collect_match_bound_variables(&pre_with_match_clauses)?;
let unwind_bound_variables = plan_unwinds(&query.unwinds, &match_bound_variables)?;
let unwind_bound_variables =
collect_match_bound_variables_from(&query.post_unwind_matches, unwind_bound_variables)?;
let (procedure_calls, procedure_bound_variables) =
plan_procedure_calls(&query.procedure_calls, &unwind_bound_variables)?;
let post_procedure_unwind_bound_variables =
plan_unwinds(&query.post_procedure_unwinds, &procedure_bound_variables)?;
let post_procedure_bound_variables = collect_match_bound_variables_from(
&query.post_procedure_matches,
post_procedure_unwind_bound_variables.clone(),
)?;
let (with, bound_variables) = plan_with_projection(
query.with.as_ref(),
query.with_predicate.as_ref(),
&query.with_order_by,
query.with_skip.as_ref(),
query.with_limit.as_ref(),
&post_procedure_bound_variables,
)?;
let post_with_unwind_bound_variables =
plan_unwinds(&query.post_with_unwinds, &bound_variables)?;
let post_with_match_bound_variables = collect_match_bound_variables_from(
&query.post_with_matches,
post_with_unwind_bound_variables.clone(),
)?;
let (post_with_procedure_calls, post_with_procedure_bound_variables) = plan_procedure_calls(
&query.post_with_procedure_calls,
&post_with_match_bound_variables,
)?;
let post_with_procedure_unwind_bound_variables = plan_unwinds(
&query.post_with_procedure_unwinds,
&post_with_procedure_bound_variables,
)?;
let post_with_procedure_bound_variables = collect_match_bound_variables_from(
&query.post_with_procedure_matches,
post_with_procedure_unwind_bound_variables.clone(),
)?;
let (calls, after_first_call_bound_variables) =
plan_call_subqueries(&query.calls, &post_with_procedure_bound_variables)?;
let (post_with_with, post_with_with_bound_variables) = plan_with_projection(
query.post_with_with.as_ref(),
query.post_with_with_predicate.as_ref(),
&query.post_with_with_order_by,
query.post_with_with_skip.as_ref(),
query.post_with_with_limit.as_ref(),
&after_first_call_bound_variables,
)?;
let post_with_with_unwind_bound_variables = plan_unwinds(
&query.post_with_with_unwinds,
&post_with_with_bound_variables,
)?;
let post_second_with_match_bound_variables = collect_match_bound_variables_from(
&query.post_with_with_matches,
post_with_with_unwind_bound_variables.clone(),
)?;
let (post_with_with_procedure_calls, bound_variables) = plan_procedure_calls(
&query.post_with_with_procedure_calls,
&post_second_with_match_bound_variables,
)?;
let post_with_with_procedure_unwind_bound_variables =
plan_unwinds(&query.post_with_with_procedure_unwinds, &bound_variables)?;
let post_with_with_procedure_bound_variables = collect_match_bound_variables_from(
&query.post_with_with_procedure_matches,
post_with_with_procedure_unwind_bound_variables.clone(),
)?;
let (post_with_with_calls, after_call_bound_variables) = plan_call_subqueries(
&query.post_with_with_calls,
&post_with_with_procedure_bound_variables,
)?;
let after_call_bound_variables =
plan_unwinds(&query.post_call_unwinds, &after_call_bound_variables)?;
let post_call_match_bound_variables = collect_match_bound_variables_from(
&query.post_call_matches,
after_call_bound_variables.clone(),
)?;
let (post_call_with, post_call_with_bound_variables) = plan_with_projection(
query.post_call_with.as_ref(),
query.post_call_with_predicate.as_ref(),
&query.post_call_with_order_by,
query.post_call_with_skip.as_ref(),
query.post_call_with_limit.as_ref(),
&post_call_match_bound_variables,
)?;
let post_call_with_unwind_bound_variables = plan_unwinds(
&query.post_call_with_unwinds,
&post_call_with_bound_variables,
)?;
let bound_variables = collect_match_bound_variables_from(
&query.post_call_with_matches,
post_call_with_unwind_bound_variables.clone(),
)?;
validate_match_predicates_from(&pre_with_match_clauses, Vec::new(), BTreeMap::new())?;
validate_match_predicates_from(
&query.post_unwind_matches,
plan_unwinds(&query.unwinds, &match_bound_variables)?,
BTreeMap::new(),
)?;
validate_match_predicates_from(
&query.post_procedure_matches,
post_procedure_unwind_bound_variables,
BTreeMap::new(),
)?;
validate_match_predicates_from(
&query.post_with_matches,
post_with_unwind_bound_variables,
with_bindings(query.with.as_ref(), &procedure_bound_variables)?,
)?;
validate_match_predicates_from(
&query.post_with_procedure_matches,
post_with_procedure_unwind_bound_variables,
with_bindings(query.with.as_ref(), &post_procedure_bound_variables)?,
)?;
validate_match_predicates_from(
&query.post_with_with_matches,
post_with_with_unwind_bound_variables,
with_bindings(
query.post_with_with.as_ref(),
&after_first_call_bound_variables,
)?,
)?;
validate_match_predicates_from(
&query.post_with_with_procedure_matches,
post_with_with_procedure_unwind_bound_variables,
with_bindings(
query.post_with_with.as_ref(),
&after_first_call_bound_variables,
)?,
)?;
validate_match_predicates_from(
&query.post_call_matches,
after_call_bound_variables,
BTreeMap::new(),
)?;
validate_match_predicates_from(
&query.post_call_with_matches,
post_call_with_unwind_bound_variables,
with_bindings(
query.post_call_with.as_ref(),
&post_call_match_bound_variables,
)?,
)?;
let returns = if query.implicit_return {
expanded_star_items(&bound_variables)
} else {
expand_returns(&query.returns, &bound_variables)
};
for return_item in &returns {
validate_return_item(return_item, &bound_variables)?;
}
validate_order_by(&query.order_by, &returns, &bound_variables, false)?;
validate_row_count("WITH SKIP", query.with_skip.as_ref())?;
validate_row_count("WITH LIMIT", query.with_limit.as_ref())?;
validate_row_count("WITH SKIP", query.post_with_with_skip.as_ref())?;
validate_row_count("WITH LIMIT", query.post_with_with_limit.as_ref())?;
validate_row_count("WITH SKIP", query.post_call_with_skip.as_ref())?;
validate_row_count("WITH LIMIT", query.post_call_with_limit.as_ref())?;
validate_row_count("SKIP", query.skip.as_ref())?;
validate_row_count("LIMIT", query.limit.as_ref())?;
Ok(Plan {
has_initial_match: query.has_initial_match,
optional_match: query.optional_match,
pattern: query.pattern,
patterns: query.patterns,
predicate: query.predicate,
extra_matches: query.extra_matches,
unwinds: query.unwinds,
post_unwind_matches: query.post_unwind_matches,
procedure_calls,
post_procedure_unwinds: query.post_procedure_unwinds,
post_procedure_matches: query.post_procedure_matches,
with,
with_predicate: query.with_predicate,
with_order_by: query.with_order_by,
with_skip: query.with_skip,
with_limit: query.with_limit,
post_with_unwinds: query.post_with_unwinds,
post_with_matches: query.post_with_matches,
post_with_procedure_calls,
post_with_procedure_unwinds: query.post_with_procedure_unwinds,
post_with_procedure_matches: query.post_with_procedure_matches,
post_with_with,
post_with_with_predicate: query.post_with_with_predicate,
post_with_with_order_by: query.post_with_with_order_by,
post_with_with_skip: query.post_with_with_skip,
post_with_with_limit: query.post_with_with_limit,
post_with_with_unwinds: query.post_with_with_unwinds,
post_with_with_matches: query.post_with_with_matches,
post_with_with_procedure_calls,
post_with_with_procedure_unwinds: query.post_with_with_procedure_unwinds,
post_with_with_procedure_matches: query.post_with_with_procedure_matches,
post_with_with_calls,
calls,
post_call_unwinds: query.post_call_unwinds,
post_call_matches: query.post_call_matches,
post_call_with,
post_call_with_predicate: query.post_call_with_predicate,
post_call_with_order_by: query.post_call_with_order_by,
post_call_with_skip: query.post_call_with_skip,
post_call_with_limit: query.post_call_with_limit,
post_call_with_unwinds: query.post_call_with_unwinds,
post_call_with_matches: query.post_call_with_matches,
distinct: query.distinct,
returns,
order_by: query.order_by,
skip: query.skip,
limit: query.limit,
bound_variables,
})
}
fn plan_procedure_calls(
calls: &[ProcedureCall],
bound_variables: &[String],
) -> Result<(Vec<PlannedProcedureCall>, Vec<String>)> {
let mut bound_variables = bound_variables.to_vec();
let mut planned = Vec::with_capacity(calls.len());
for call in calls {
let signature = resolve_procedure(&call.name)?;
if matches!(signature.mode, ProcedureMode::Schema | ProcedureMode::Dbms) {
return Err(Error::UnsupportedProcedureMode {
name: call.name.clone(),
mode: signature.mode.to_string(),
});
}
let required = signature
.arguments
.iter()
.filter(|argument| argument.default.is_none())
.count();
if call.arguments.len() < required || call.arguments.len() > signature.arguments.len() {
return Err(Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!(
"expected {}..={} arguments, received {}",
required,
signature.arguments.len(),
call.arguments.len()
),
});
}
for (argument, expected) in call.arguments.iter().zip(signature.arguments) {
validate_expression(argument, &bound_variables)?;
if let Expression::Literal(value) = argument {
if matches!(value, crate::value::Value::Null) && !expected.nullable {
return Err(Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!("argument `{}` cannot be null", expected.name),
});
}
if !matches!(value, crate::value::Value::Null)
&& !expected.value_type.accepts(value)
{
return Err(Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!("argument `{}` has the wrong type", expected.name),
});
}
}
}
let requested_yields = if call.yields.is_empty() {
signature
.outputs
.iter()
.map(|output| (output.name.to_owned(), output.name.to_owned()))
.collect::<Vec<_>>()
} else {
call.yields
.iter()
.map(|item| (item.field.clone(), item.binding().to_owned()))
.collect()
};
let mut yields = Vec::with_capacity(requested_yields.len());
for (field, binding) in requested_yields {
if !signature.outputs.iter().any(|output| output.name == field) {
return Err(Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!("unknown YIELD field `{field}`"),
});
}
if yields
.iter()
.any(|item: &PlannedProcedureYield| item.binding == binding)
{
return Err(Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!("duplicate YIELD binding `{binding}`"),
});
}
if bound_variables.iter().any(|variable| variable == &binding) {
return Err(Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!("YIELD binding `{binding}` is already declared"),
});
}
yields.push(PlannedProcedureYield { field, binding });
}
let mut predicate_variables = bound_variables.clone();
predicate_variables.extend(yields.iter().map(|item| item.binding.clone()));
if let Some(predicate) = &call.predicate {
validate_predicate(predicate, &predicate_variables)?;
}
bound_variables = predicate_variables;
planned.push(PlannedProcedureCall {
name: call.name.clone(),
mode: signature.mode,
arguments: call.arguments.clone(),
yields,
predicate: call.predicate.clone(),
});
}
Ok((planned, bound_variables))
}
fn plan_call_subqueries(
calls: &[CallSubquery],
bound_variables: &[String],
) -> Result<(Vec<PlannedCallSubquery>, Vec<String>)> {
let mut outer_bound_variables = bound_variables.to_vec();
let mut planned_calls = Vec::new();
for call in calls {
for import in &call.imports {
validate_return_variable(import, &outer_bound_variables)?;
}
let call_import_variables = if call.imports.is_empty() {
outer_bound_variables.clone()
} else {
call.imports.clone()
};
if let Some(predicate) = &call.predicate {
validate_predicate(predicate, &call_import_variables)?;
}
let call_unwind_bound_variables = plan_unwinds(&call.unwinds, &call_import_variables)?;
let call_match_bound_variables =
collect_match_bound_variables_from(&call.matches, call_unwind_bound_variables.clone())?;
let call_bound_variables =
plan_unwinds(&call.post_match_unwinds, &call_match_bound_variables)?;
let (call_with, call_with_bound_variables) = plan_with_projection(
call.with.as_ref(),
call.with_predicate.as_ref(),
&call.with_order_by,
call.with_skip.as_ref(),
call.with_limit.as_ref(),
&call_bound_variables,
)?;
let call_post_with_unwind_bound_variables =
plan_unwinds(&call.post_with_unwinds, &call_with_bound_variables)?;
let call_post_with_match_bound_variables = collect_match_bound_variables_from(
&call.post_with_matches,
call_post_with_unwind_bound_variables.clone(),
)?;
let (call_post_with_with, call_post_with_with_bound_variables) = plan_with_projection(
call.post_with_with.as_ref(),
call.post_with_with_predicate.as_ref(),
&call.post_with_with_order_by,
call.post_with_with_skip.as_ref(),
call.post_with_with_limit.as_ref(),
&call_post_with_match_bound_variables,
)?;
let call_post_with_with_unwind_bound_variables = plan_unwinds(
&call.post_with_with_unwinds,
&call_post_with_with_bound_variables,
)?;
let call_return_bound_variables = collect_match_bound_variables_from(
&call.post_with_with_matches,
call_post_with_with_unwind_bound_variables.clone(),
)?;
validate_match_predicates_from(
&call.matches,
call_unwind_bound_variables,
call_import_variables
.iter()
.cloned()
.map(|variable| (variable, BindingKind::Node))
.collect(),
)?;
validate_match_predicates_from(
&call.post_with_matches,
call_post_with_unwind_bound_variables,
with_bindings(call.with.as_ref(), &call_bound_variables)?,
)?;
validate_match_predicates_from(
&call.post_with_with_matches,
call_post_with_with_unwind_bound_variables,
with_bindings(
call.post_with_with.as_ref(),
&call_post_with_match_bound_variables,
)?,
)?;
let items = expand_returns(&call.returns, &call_return_bound_variables);
for item in &items {
validate_return_item(item, &call_return_bound_variables)?;
}
validate_order_by(&call.order_by, &items, &call_return_bound_variables, true)?;
validate_row_count("CALL WITH SKIP", call.with_skip.as_ref())?;
validate_row_count("CALL WITH LIMIT", call.with_limit.as_ref())?;
validate_row_count("CALL WITH SKIP", call.post_with_with_skip.as_ref())?;
validate_row_count("CALL WITH LIMIT", call.post_with_with_limit.as_ref())?;
validate_row_count("CALL SKIP", call.skip.as_ref())?;
validate_row_count("CALL LIMIT", call.limit.as_ref())?;
for item in &items {
let output = call_output_variable(item)?;
if !outer_bound_variables.iter().any(|bound| bound == &output) {
outer_bound_variables.push(output);
}
}
planned_calls.push(PlannedCallSubquery {
imports: call.imports.clone(),
predicate: call.predicate.clone(),
unwinds: call.unwinds.clone(),
matches: call.matches.clone(),
post_match_unwinds: call.post_match_unwinds.clone(),
with: call_with,
post_with_unwinds: call.post_with_unwinds.clone(),
post_with_matches: call.post_with_matches.clone(),
post_with_with: call_post_with_with,
post_with_with_unwinds: call.post_with_with_unwinds.clone(),
post_with_with_matches: call.post_with_with_matches.clone(),
items,
order_by: call.order_by.clone(),
skip: call.skip.clone(),
limit: call.limit.clone(),
});
}
Ok((planned_calls, outer_bound_variables))
}
fn call_output_variable(item: &ReturnItem) -> Result<String> {
if let Some(alias) = &item.alias {
return Ok(alias.clone());
}
match &item.expression {
ReturnExpression::Variable(variable) => Ok(variable.clone()),
ReturnExpression::CountStar
| ReturnExpression::CountDistinctStar
| ReturnExpression::CountVariable(_)
| ReturnExpression::CountDistinctVariable(_)
| ReturnExpression::CountProperty { .. }
| ReturnExpression::CountDistinctProperty { .. }
| ReturnExpression::CountExpression(_)
| ReturnExpression::CountDistinctExpression(_)
| ReturnExpression::SumProperty { .. }
| ReturnExpression::AvgProperty { .. }
| ReturnExpression::MinProperty { .. }
| ReturnExpression::MaxProperty { .. }
| ReturnExpression::SumExpression(_)
| ReturnExpression::AvgExpression(_)
| ReturnExpression::SumDistinctExpression(_)
| ReturnExpression::AvgDistinctExpression(_)
| ReturnExpression::MinExpression(_)
| ReturnExpression::MaxExpression(_)
| ReturnExpression::MinDistinctExpression(_)
| ReturnExpression::MaxDistinctExpression(_)
| ReturnExpression::CollectVariable(_)
| ReturnExpression::CollectProperty { .. }
| ReturnExpression::CollectDistinctVariable(_)
| ReturnExpression::CollectDistinctProperty { .. }
| ReturnExpression::CollectExpression(_)
| ReturnExpression::CollectDistinctExpression(_)
| ReturnExpression::Labels(_)
| ReturnExpression::Type(_)
| ReturnExpression::Properties(_)
| ReturnExpression::Keys(_)
| ReturnExpression::ElementId(_)
| ReturnExpression::Id(_)
| ReturnExpression::StartNode(_)
| ReturnExpression::EndNode(_)
| ReturnExpression::Nodes(_)
| ReturnExpression::Relationships(_)
| ReturnExpression::Length(_) => Ok(return_column(item)),
ReturnExpression::Property { .. }
| ReturnExpression::PropertyWildcard(_)
| ReturnExpression::Scalar(_) => Ok(return_column(item)),
_ => Err(Error::UnsupportedQueryFeature(
"CALL subquery currently supports variable, property, and scalar returns".to_string(),
)),
}
}
fn plan_unwinds(unwinds: &[UnwindClause], bound_variables: &[String]) -> Result<Vec<String>> {
let mut bound_variables = bound_variables.to_vec();
for unwind in unwinds {
validate_expression(&unwind.expression, &bound_variables)?;
if !bound_variables
.iter()
.any(|bound| bound == &unwind.variable)
{
bound_variables.push(unwind.variable.clone());
}
}
Ok(bound_variables)
}
fn plan_with_projection(
with: Option<&WithProjection>,
predicate: Option<&Predicate>,
order_by: &[OrderItem],
skip: Option<&RowCount>,
limit: Option<&RowCount>,
bound_variables: &[String],
) -> Result<(Option<PlannedWithProjection>, Vec<String>)> {
let Some(with) = with else {
return Ok((None, bound_variables.to_vec()));
};
let items = expand_returns(&with.projection, bound_variables);
let mut projected_variables = Vec::new();
for item in &items {
match &item.expression {
ReturnExpression::Variable(variable) => {
validate_return_variable(variable, bound_variables)?;
projected_variables.push(item.alias.clone().unwrap_or_else(|| variable.clone()));
}
ReturnExpression::Property { variable, .. } => {
validate_return_variable(variable, bound_variables)?;
let alias = item.alias.as_ref().ok_or_else(|| {
Error::Validation("WITH property projections require an alias".to_string())
})?;
projected_variables.push(alias.clone());
}
ReturnExpression::Scalar(expression) => {
validate_expression(expression, bound_variables)?;
let alias = item.alias.as_ref().ok_or_else(|| {
Error::Validation("WITH scalar projections require an alias".to_string())
})?;
projected_variables.push(alias.clone());
}
ReturnExpression::CountStar
| ReturnExpression::CountDistinctStar
| ReturnExpression::CountVariable(_)
| ReturnExpression::CountDistinctVariable(_)
| ReturnExpression::CountProperty { .. }
| ReturnExpression::CountDistinctProperty { .. }
| ReturnExpression::CountExpression(_)
| ReturnExpression::CountDistinctExpression(_)
| ReturnExpression::SumProperty { .. }
| ReturnExpression::AvgProperty { .. }
| ReturnExpression::MinProperty { .. }
| ReturnExpression::MaxProperty { .. }
| ReturnExpression::SumExpression(_)
| ReturnExpression::AvgExpression(_)
| ReturnExpression::SumDistinctExpression(_)
| ReturnExpression::AvgDistinctExpression(_)
| ReturnExpression::MinExpression(_)
| ReturnExpression::MaxExpression(_)
| ReturnExpression::MinDistinctExpression(_)
| ReturnExpression::MaxDistinctExpression(_)
| ReturnExpression::CollectVariable(_)
| ReturnExpression::CollectProperty { .. }
| ReturnExpression::CollectDistinctVariable(_)
| ReturnExpression::CollectDistinctProperty { .. }
| ReturnExpression::CollectExpression(_)
| ReturnExpression::CollectDistinctExpression(_) => {
validate_return_item(item, bound_variables)?;
let alias = item.alias.as_ref().ok_or_else(|| {
Error::Validation("WITH aggregate projections require an alias".to_string())
})?;
projected_variables.push(alias.clone());
}
ReturnExpression::Labels(_)
| ReturnExpression::Type(_)
| ReturnExpression::Properties(_)
| ReturnExpression::Keys(_)
| ReturnExpression::ElementId(_)
| ReturnExpression::Id(_)
| ReturnExpression::StartNode(_)
| ReturnExpression::EndNode(_)
| ReturnExpression::Nodes(_)
| ReturnExpression::Relationships(_)
| ReturnExpression::Length(_) => {
validate_return_item(item, bound_variables)?;
let alias = item.alias.as_ref().ok_or_else(|| {
Error::Validation(
"WITH graph function projections require an alias".to_string(),
)
})?;
projected_variables.push(alias.clone());
}
_ => {
return Err(Error::UnsupportedQueryFeature(
"WITH currently supports variables, properties, scalar literals, count, and *"
.to_string(),
))
}
};
}
if let Some(predicate) = predicate {
validate_predicate(predicate, &projected_variables)?;
}
validate_order_by(order_by, &items, &projected_variables, true)?;
Ok((
Some(PlannedWithProjection {
distinct: with.distinct,
items,
predicate: predicate.cloned(),
order_by: order_by.to_vec(),
skip: skip.cloned(),
limit: limit.cloned(),
}),
projected_variables,
))
}
fn query_pre_with_match_clauses(query: &Query) -> Vec<MatchClause> {
let mut clauses = if query.has_initial_match {
vec![MatchClause {
optional_match: query.optional_match,
pattern: query.pattern.clone(),
patterns: query.patterns.clone(),
predicate: query.predicate.clone(),
}]
} else {
Vec::new()
};
clauses.extend(query.extra_matches.clone());
clauses
}
fn expand_returns(returns: &ReturnProjection, bound_variables: &[String]) -> Vec<ReturnItem> {
match returns {
ReturnProjection::Items(items) => items
.iter()
.flat_map(|item| match item.expression {
ReturnExpression::Star => expanded_star_items(bound_variables),
_ => vec![item.clone()],
})
.collect(),
ReturnProjection::Star => expanded_star_items(bound_variables),
}
}
fn expanded_star_items(bound_variables: &[String]) -> Vec<ReturnItem> {
bound_variables
.iter()
.filter(|variable| !is_internal_variable(variable))
.cloned()
.map(|variable| ReturnItem {
expression: ReturnExpression::Variable(variable),
alias: None,
})
.collect()
}
fn validate_return_item(item: &ReturnItem, bound_variables: &[String]) -> Result<()> {
match &item.expression {
ReturnExpression::Star => Ok(()),
ReturnExpression::Variable(variable)
| ReturnExpression::Property { variable, .. }
| ReturnExpression::PropertyWildcard(variable) => {
validate_return_variable(variable, bound_variables)
}
ReturnExpression::Labels(variable)
| ReturnExpression::Type(variable)
| ReturnExpression::Properties(variable)
| ReturnExpression::Keys(variable)
| ReturnExpression::ElementId(variable)
| ReturnExpression::Id(variable)
| ReturnExpression::StartNode(variable)
| ReturnExpression::EndNode(variable)
| ReturnExpression::Nodes(variable)
| ReturnExpression::Relationships(variable)
| ReturnExpression::Length(variable) => validate_return_variable(variable, bound_variables),
ReturnExpression::Scalar(expression)
| ReturnExpression::CountExpression(expression)
| ReturnExpression::CountDistinctExpression(expression)
| ReturnExpression::SumExpression(expression)
| ReturnExpression::AvgExpression(expression)
| ReturnExpression::SumDistinctExpression(expression)
| ReturnExpression::AvgDistinctExpression(expression)
| ReturnExpression::MinExpression(expression)
| ReturnExpression::MaxExpression(expression)
| ReturnExpression::MinDistinctExpression(expression)
| ReturnExpression::MaxDistinctExpression(expression)
| ReturnExpression::CollectExpression(expression)
| ReturnExpression::CollectDistinctExpression(expression) => {
validate_expression(expression, bound_variables)
}
ReturnExpression::CountStar | ReturnExpression::CountDistinctStar => Ok(()),
ReturnExpression::CountVariable(variable) => {
validate_return_variable(variable, bound_variables)
}
ReturnExpression::CountDistinctVariable(variable) => {
validate_return_variable(variable, bound_variables)
}
ReturnExpression::CountProperty { variable, .. } => {
validate_return_variable(variable, bound_variables)
}
ReturnExpression::CountDistinctProperty { variable, .. } => {
validate_return_variable(variable, bound_variables)
}
ReturnExpression::SumProperty { variable, .. }
| ReturnExpression::AvgProperty { variable, .. }
| ReturnExpression::MinProperty { variable, .. }
| ReturnExpression::MaxProperty { variable, .. }
| ReturnExpression::CollectProperty { variable, .. }
| ReturnExpression::CollectDistinctProperty { variable, .. } => {
validate_return_variable(variable, bound_variables)
}
ReturnExpression::CollectVariable(variable)
| ReturnExpression::CollectDistinctVariable(variable) => {
validate_return_variable(variable, bound_variables)
}
}
}
fn return_item_is_aggregate(item: &ReturnItem) -> bool {
return_expression_is_count(&item.expression)
}
fn return_expression_is_count(expression: &ReturnExpression) -> bool {
matches!(
expression,
ReturnExpression::CountStar
| ReturnExpression::CountDistinctStar
| ReturnExpression::CountVariable(_)
| ReturnExpression::CountDistinctVariable(_)
| ReturnExpression::CountProperty { .. }
| ReturnExpression::CountDistinctProperty { .. }
| ReturnExpression::CountExpression(_)
| ReturnExpression::CountDistinctExpression(_)
| ReturnExpression::SumProperty { .. }
| ReturnExpression::AvgProperty { .. }
| ReturnExpression::MinProperty { .. }
| ReturnExpression::MaxProperty { .. }
| ReturnExpression::SumExpression(_)
| ReturnExpression::AvgExpression(_)
| ReturnExpression::SumDistinctExpression(_)
| ReturnExpression::AvgDistinctExpression(_)
| ReturnExpression::MinExpression(_)
| ReturnExpression::MaxExpression(_)
| ReturnExpression::MinDistinctExpression(_)
| ReturnExpression::MaxDistinctExpression(_)
| ReturnExpression::CollectVariable(_)
| ReturnExpression::CollectProperty { .. }
| ReturnExpression::CollectDistinctVariable(_)
| ReturnExpression::CollectDistinctProperty { .. }
| ReturnExpression::CollectExpression(_)
| ReturnExpression::CollectDistinctExpression(_)
)
}
fn validate_return_variable(variable: &str, bound_variables: &[String]) -> Result<()> {
if bound_variables.iter().any(|bound| bound == variable) {
Ok(())
} else {
Err(Error::Validation(format!(
"RETURN variable `{variable}` is not bound by the MATCH pattern"
)))
}
}
fn validate_order_by(
order_by: &[OrderItem],
returns: &[ReturnItem],
bound_variables: &[String],
require_projected_order_items: bool,
) -> Result<()> {
for order_item in order_by {
let matches_alias = order_by_matches_alias(&order_item.item, returns);
if !matches_alias {
validate_order_expression(&order_item.item.expression, bound_variables)?;
}
let matches_return = returns
.iter()
.any(|return_item| return_expression_matches(return_item, &order_item.item));
let allowed_non_projected_aggregate =
return_expression_is_count(&order_item.item.expression)
&& returns.iter().all(return_item_is_aggregate);
let is_non_projected = !matches_alias && !matches_return;
let disallowed_non_projected_contextless_scalar = require_projected_order_items
&& is_non_projected
&& matches!(
order_item.item.expression,
crate::cypher::ast::ReturnExpression::Scalar(
crate::cypher::ast::Expression::Literal(_)
| crate::cypher::ast::Expression::Parameter(_)
)
);
let disallowed_non_projected_aggregate = is_non_projected
&& return_expression_is_count(&order_item.item.expression)
&& !allowed_non_projected_aggregate;
let disallowed_non_projected_graph_function = require_projected_order_items
&& is_non_projected
&& matches!(
order_item.item.expression,
ReturnExpression::Labels(_)
| ReturnExpression::Type(_)
| ReturnExpression::Properties(_)
| ReturnExpression::Keys(_)
| ReturnExpression::ElementId(_)
| ReturnExpression::Id(_)
| ReturnExpression::StartNode(_)
| ReturnExpression::EndNode(_)
| ReturnExpression::Nodes(_)
| ReturnExpression::Relationships(_)
| ReturnExpression::Length(_)
);
if disallowed_non_projected_contextless_scalar
|| disallowed_non_projected_aggregate
|| disallowed_non_projected_graph_function
{
return Err(Error::Validation(format!(
"ORDER BY item `{}` must also appear in RETURN",
return_column(&order_item.item)
)));
}
}
Ok(())
}
fn return_expression_matches(left: &ReturnItem, right: &ReturnItem) -> bool {
left.expression == right.expression
}
fn order_by_matches_alias(order_item: &ReturnItem, returns: &[ReturnItem]) -> bool {
let ReturnExpression::Variable(alias) = &order_item.expression else {
return false;
};
returns
.iter()
.any(|return_item| return_item.alias.as_deref() == Some(alias.as_str()))
}
fn validate_order_expression(
expression: &ReturnExpression,
bound_variables: &[String],
) -> Result<()> {
match expression {
ReturnExpression::Star => Err(Error::Validation("ORDER BY * is not supported".to_string())),
ReturnExpression::Variable(variable)
| ReturnExpression::Property { variable, .. }
| ReturnExpression::PropertyWildcard(variable) => {
if bound_variables.iter().any(|bound| bound == variable) {
Ok(())
} else {
Err(Error::Validation(format!(
"ORDER BY variable `{variable}` is not bound by the MATCH pattern"
)))
}
}
ReturnExpression::Scalar(expression) => validate_expression(expression, bound_variables),
ReturnExpression::Labels(_)
| ReturnExpression::Type(_)
| ReturnExpression::Properties(_)
| ReturnExpression::Keys(_)
| ReturnExpression::ElementId(_)
| ReturnExpression::Id(_)
| ReturnExpression::StartNode(_)
| ReturnExpression::EndNode(_)
| ReturnExpression::Nodes(_)
| ReturnExpression::Relationships(_)
| ReturnExpression::Length(_) => validate_order_graph_function(expression, bound_variables),
ReturnExpression::CountStar
| ReturnExpression::CountDistinctStar
| ReturnExpression::CountVariable(_)
| ReturnExpression::CountDistinctVariable(_)
| ReturnExpression::CountProperty { .. }
| ReturnExpression::CountDistinctProperty { .. }
| ReturnExpression::CountExpression(_)
| ReturnExpression::CountDistinctExpression(_)
| ReturnExpression::SumProperty { .. }
| ReturnExpression::AvgProperty { .. }
| ReturnExpression::MinProperty { .. }
| ReturnExpression::MaxProperty { .. }
| ReturnExpression::SumExpression(_)
| ReturnExpression::AvgExpression(_)
| ReturnExpression::SumDistinctExpression(_)
| ReturnExpression::AvgDistinctExpression(_)
| ReturnExpression::MinExpression(_)
| ReturnExpression::MaxExpression(_)
| ReturnExpression::MinDistinctExpression(_)
| ReturnExpression::MaxDistinctExpression(_)
| ReturnExpression::CollectVariable(_)
| ReturnExpression::CollectProperty { .. }
| ReturnExpression::CollectDistinctVariable(_)
| ReturnExpression::CollectDistinctProperty { .. }
| ReturnExpression::CollectExpression(_)
| ReturnExpression::CollectDistinctExpression(_) => {
validate_order_count_expression(expression, bound_variables)
}
}
}
fn validate_order_graph_function(
expression: &ReturnExpression,
bound_variables: &[String],
) -> Result<()> {
let variable = match expression {
ReturnExpression::Labels(variable)
| ReturnExpression::Type(variable)
| ReturnExpression::Properties(variable)
| ReturnExpression::Keys(variable)
| ReturnExpression::ElementId(variable)
| ReturnExpression::Id(variable)
| ReturnExpression::StartNode(variable)
| ReturnExpression::EndNode(variable)
| ReturnExpression::Nodes(variable)
| ReturnExpression::Relationships(variable)
| ReturnExpression::Length(variable) => variable,
_ => {
return Err(Error::Execution(
"non-graph function passed to graph function validation".to_string(),
))
}
};
if bound_variables.iter().any(|bound| bound == variable) {
Ok(())
} else {
Err(Error::Validation(format!(
"ORDER BY variable `{variable}` is not bound by the MATCH pattern"
)))
}
}
fn validate_order_count_expression(
expression: &ReturnExpression,
bound_variables: &[String],
) -> Result<()> {
match expression {
ReturnExpression::CountStar | ReturnExpression::CountDistinctStar => Ok(()),
ReturnExpression::CountExpression(expression)
| ReturnExpression::CountDistinctExpression(expression)
| ReturnExpression::SumExpression(expression)
| ReturnExpression::AvgExpression(expression)
| ReturnExpression::SumDistinctExpression(expression)
| ReturnExpression::AvgDistinctExpression(expression)
| ReturnExpression::MinExpression(expression)
| ReturnExpression::MaxExpression(expression)
| ReturnExpression::MinDistinctExpression(expression)
| ReturnExpression::MaxDistinctExpression(expression)
| ReturnExpression::CollectExpression(expression)
| ReturnExpression::CollectDistinctExpression(expression) => {
validate_expression(expression, bound_variables)
}
ReturnExpression::CountVariable(variable)
| ReturnExpression::CountDistinctVariable(variable)
| ReturnExpression::CollectVariable(variable)
| ReturnExpression::CollectDistinctVariable(variable) => {
if bound_variables.iter().any(|bound| bound == variable) {
Ok(())
} else {
Err(Error::Validation(format!(
"ORDER BY variable `{variable}` is not bound by the MATCH pattern"
)))
}
}
ReturnExpression::CountProperty { variable, .. }
| ReturnExpression::CountDistinctProperty { variable, .. }
| ReturnExpression::SumProperty { variable, .. }
| ReturnExpression::AvgProperty { variable, .. }
| ReturnExpression::MinProperty { variable, .. }
| ReturnExpression::MaxProperty { variable, .. }
| ReturnExpression::CollectProperty { variable, .. }
| ReturnExpression::CollectDistinctProperty { variable, .. } => {
if bound_variables.iter().any(|bound| bound == variable) {
Ok(())
} else {
Err(Error::Validation(format!(
"ORDER BY variable `{variable}` is not bound by the MATCH pattern"
)))
}
}
_ => Err(Error::Execution(
"non-count expression passed to count validation".to_string(),
)),
}
}
fn validate_row_count(name: &str, row_count: Option<&RowCount>) -> Result<()> {
if let Some(row_count) = row_count {
match row_count {
RowCount::Literal(value) if *value < 0 => {
return Err(Error::Validation(format!(
"{name} literal must be a non-negative integer"
)))
}
RowCount::InvalidLiteral(value) => {
return Err(Error::Validation(format!(
"{name} literal `{value}` must be a non-negative integer"
)))
}
RowCount::Expression(expression) => validate_static_expression(expression)?,
RowCount::Literal(_) | RowCount::Parameter(_) => {}
}
}
Ok(())
}
fn validate_static_expression(expression: &crate::cypher::ast::Expression) -> Result<()> {
match expression {
crate::cypher::ast::Expression::Literal(_)
| crate::cypher::ast::Expression::Parameter(_) => Ok(()),
crate::cypher::ast::Expression::Operand(operand) => match operand {
Operand::Literal(_) | Operand::Parameter(_) => Ok(()),
Operand::Variable(variable) => Err(Error::Validation(format!(
"row count expression cannot reference variable `{variable}`"
))),
Operand::Property { variable, .. } | Operand::DynamicProperty { variable, .. } => {
Err(Error::Validation(format!(
"row count expression cannot reference variable `{variable}`"
)))
}
},
crate::cypher::ast::Expression::Add(left, right)
| crate::cypher::ast::Expression::Subtract(left, right)
| crate::cypher::ast::Expression::Multiply(left, right)
| crate::cypher::ast::Expression::Divide(left, right)
| crate::cypher::ast::Expression::Modulo(left, right) => {
validate_static_expression(left)?;
validate_static_expression(right)
}
crate::cypher::ast::Expression::ToLower(expression)
| crate::cypher::ast::Expression::ToUpper(expression)
| crate::cypher::ast::Expression::ToString(expression)
| crate::cypher::ast::Expression::ToInteger(expression)
| crate::cypher::ast::Expression::ToFloat(expression)
| crate::cypher::ast::Expression::ToBoolean(expression)
| crate::cypher::ast::Expression::ToStringOrNull(expression)
| crate::cypher::ast::Expression::ToIntegerOrNull(expression)
| crate::cypher::ast::Expression::ToFloatOrNull(expression)
| crate::cypher::ast::Expression::ToBooleanOrNull(expression)
| crate::cypher::ast::Expression::IsEmpty(expression)
| crate::cypher::ast::Expression::Head(expression)
| crate::cypher::ast::Expression::Last(expression)
| crate::cypher::ast::Expression::Tail(expression)
| crate::cypher::ast::Expression::Size(expression) => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::Range { start, end, step } => {
validate_static_expression(start)?;
validate_static_expression(end)?;
if let Some(step) = step {
validate_static_expression(step)?;
}
Ok(())
}
crate::cypher::ast::Expression::ListIndex { value, index } => {
validate_static_expression(value)?;
validate_static_expression(index)
}
crate::cypher::ast::Expression::ListSlice { value, start, end } => {
validate_static_expression(value)?;
if let Some(start) = start {
validate_static_expression(start)?;
}
if let Some(end) = end {
validate_static_expression(end)?;
}
Ok(())
}
crate::cypher::ast::Expression::Substring {
value,
start,
length,
} => {
validate_static_expression(value)?;
validate_static_expression(start)?;
if let Some(length) = length {
validate_static_expression(length)?;
}
Ok(())
}
crate::cypher::ast::Expression::Replace {
value,
search,
replacement,
} => {
validate_static_expression(value)?;
validate_static_expression(search)?;
validate_static_expression(replacement)
}
crate::cypher::ast::Expression::Trim { expression, .. } => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::Split { value, delimiter } => {
validate_static_expression(value)?;
validate_static_expression(delimiter)
}
crate::cypher::ast::Expression::StringSlice { value, length, .. } => {
validate_static_expression(value)?;
validate_static_expression(length)
}
crate::cypher::ast::Expression::Reverse(expression) => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::Abs(expression) => validate_static_expression(expression),
crate::cypher::ast::Expression::Rounding { expression, .. } => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::Sign(expression) => validate_static_expression(expression),
crate::cypher::ast::Expression::Sqrt(expression) => validate_static_expression(expression),
crate::cypher::ast::Expression::Round(expression) => validate_static_expression(expression),
crate::cypher::ast::Expression::Log(expression) => validate_static_expression(expression),
crate::cypher::ast::Expression::Log10(expression) => validate_static_expression(expression),
crate::cypher::ast::Expression::Exp(expression) => validate_static_expression(expression),
crate::cypher::ast::Expression::AngleConversion { expression, .. } => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::Trigonometric { expression, .. } => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::InverseTrigonometric { expression, .. } => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::Atan2 { y, x } => {
validate_static_expression(y)?;
validate_static_expression(x)
}
crate::cypher::ast::Expression::Haversin(expression) => {
validate_static_expression(expression)
}
crate::cypher::ast::Expression::Pi | crate::cypher::ast::Expression::E => Ok(()),
crate::cypher::ast::Expression::List(items) => {
for item in items {
validate_static_expression(item)?;
}
Ok(())
}
crate::cypher::ast::Expression::Map(entries) => {
for value in entries.values() {
validate_static_expression(value)?;
}
Ok(())
}
crate::cypher::ast::Expression::MapProjection { .. } => Err(Error::Validation(
"row count expressions cannot depend on map projections".to_string(),
)),
crate::cypher::ast::Expression::Coalesce(items) => {
for item in items {
validate_static_expression(item)?;
}
Ok(())
}
crate::cypher::ast::Expression::ListPredicate { .. }
| crate::cypher::ast::Expression::ListComprehension { .. }
| crate::cypher::ast::Expression::PatternComprehension { .. } => Err(Error::Validation(
"row count expression must be a non-negative integer".to_string(),
)),
crate::cypher::ast::Expression::Reduce { .. } => Err(Error::Validation(
"row count expression must be a non-negative integer".to_string(),
)),
crate::cypher::ast::Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
validate_predicate(&alternative.predicate, &[])?;
validate_static_expression(&alternative.expression)?;
}
validate_static_expression(else_expression)
}
crate::cypher::ast::Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
validate_static_expression(operand)?;
for alternative in alternatives {
validate_static_expression(&alternative.value)?;
validate_static_expression(&alternative.expression)?;
}
validate_static_expression(else_expression)
}
crate::cypher::ast::Expression::Predicate(predicate) => validate_predicate(predicate, &[]),
}
}
fn return_column(item: &ReturnItem) -> String {
item.alias
.as_ref()
.map_or_else(|| return_expression_column(&item.expression), Clone::clone)
}
fn return_expression_column(expression: &ReturnExpression) -> String {
match expression {
ReturnExpression::Star => "*".to_string(),
ReturnExpression::Variable(variable) => variable.clone(),
ReturnExpression::Property { variable, key } => format!("{variable}.{key}"),
ReturnExpression::PropertyWildcard(variable) => format!("{variable}.*"),
ReturnExpression::Scalar(expression) => scalar_expression_column(expression),
ReturnExpression::Labels(variable) => format!("labels({variable})"),
ReturnExpression::Type(variable) => format!("type({variable})"),
ReturnExpression::Properties(variable) => format!("properties({variable})"),
ReturnExpression::Keys(variable) => format!("keys({variable})"),
ReturnExpression::ElementId(variable) => format!("elementId({variable})"),
ReturnExpression::Id(variable) => format!("id({variable})"),
ReturnExpression::StartNode(variable) => format!("startNode({variable})"),
ReturnExpression::EndNode(variable) => format!("endNode({variable})"),
ReturnExpression::Nodes(variable) => format!("nodes({variable})"),
ReturnExpression::Relationships(variable) => format!("relationships({variable})"),
ReturnExpression::Length(variable) => format!("length({variable})"),
ReturnExpression::CountStar => "count(*)".to_string(),
ReturnExpression::CountDistinctStar => "count(DISTINCT *)".to_string(),
ReturnExpression::CountVariable(variable) => format!("count({variable})"),
ReturnExpression::CountDistinctVariable(variable) => format!("count(DISTINCT {variable})"),
ReturnExpression::CountProperty { variable, key } => format!("count({variable}.{key})"),
ReturnExpression::CountDistinctProperty { variable, key } => {
format!("count(DISTINCT {variable}.{key})")
}
ReturnExpression::CountExpression(expression) => {
format!("count({})", scalar_expression_column(expression))
}
ReturnExpression::CountDistinctExpression(expression) => {
format!("count(DISTINCT {})", scalar_expression_column(expression))
}
ReturnExpression::SumProperty { variable, key } => format!("sum({variable}.{key})"),
ReturnExpression::AvgProperty { variable, key } => format!("avg({variable}.{key})"),
ReturnExpression::MinProperty { variable, key } => format!("min({variable}.{key})"),
ReturnExpression::MaxProperty { variable, key } => format!("max({variable}.{key})"),
ReturnExpression::SumExpression(expression) => {
format!("sum({})", scalar_expression_column(expression))
}
ReturnExpression::AvgExpression(expression) => {
format!("avg({})", scalar_expression_column(expression))
}
ReturnExpression::SumDistinctExpression(expression) => {
format!("sum(DISTINCT {})", scalar_expression_column(expression))
}
ReturnExpression::AvgDistinctExpression(expression) => {
format!("avg(DISTINCT {})", scalar_expression_column(expression))
}
ReturnExpression::MinExpression(expression) => {
format!("min({})", scalar_expression_column(expression))
}
ReturnExpression::MaxExpression(expression) => {
format!("max({})", scalar_expression_column(expression))
}
ReturnExpression::MinDistinctExpression(expression) => {
format!("min(DISTINCT {})", scalar_expression_column(expression))
}
ReturnExpression::MaxDistinctExpression(expression) => {
format!("max(DISTINCT {})", scalar_expression_column(expression))
}
ReturnExpression::CollectVariable(variable) => format!("collect({variable})"),
ReturnExpression::CollectProperty { variable, key } => {
format!("collect({variable}.{key})")
}
ReturnExpression::CollectDistinctVariable(variable) => {
format!("collect(DISTINCT {variable})")
}
ReturnExpression::CollectDistinctProperty { variable, key } => {
format!("collect(DISTINCT {variable}.{key})")
}
ReturnExpression::CollectExpression(expression) => {
format!("collect({})", scalar_expression_column(expression))
}
ReturnExpression::CollectDistinctExpression(expression) => {
format!("collect(DISTINCT {})", scalar_expression_column(expression))
}
}
}
fn scalar_expression_column(expression: &crate::cypher::ast::Expression) -> String {
match expression {
crate::cypher::ast::Expression::Literal(value) => scalar_literal_column(value),
crate::cypher::ast::Expression::Parameter(name) => format!("${name}"),
crate::cypher::ast::Expression::Operand(operand) => operand_column(operand),
crate::cypher::ast::Expression::Add(left, right) => {
format!(
"{} + {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
crate::cypher::ast::Expression::Subtract(left, right) => {
format!(
"{} - {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
crate::cypher::ast::Expression::Multiply(left, right) => {
format!(
"{} * {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
crate::cypher::ast::Expression::Divide(left, right) => {
format!(
"{} / {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
crate::cypher::ast::Expression::Modulo(left, right) => {
format!(
"{} % {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
crate::cypher::ast::Expression::List(items) => {
let items = items
.iter()
.map(scalar_expression_column)
.collect::<Vec<_>>()
.join(", ");
format!("[{items}]")
}
crate::cypher::ast::Expression::Map(entries) => {
let entries = entries
.iter()
.map(|(key, value)| format!("{key}: {}", scalar_expression_column(value)))
.collect::<Vec<_>>()
.join(", ");
format!("{{{entries}}}")
}
crate::cypher::ast::Expression::MapProjection { variable, items } => {
let items = items
.iter()
.map(|item| match item {
crate::cypher::ast::MapProjectionItem::AllProperties => ".*".to_string(),
crate::cypher::ast::MapProjectionItem::Property(key) => format!(".{key}"),
crate::cypher::ast::MapProjectionItem::Variable(variable) => variable.clone(),
crate::cypher::ast::MapProjectionItem::Expression { key, expression } => {
format!("{key}: {}", scalar_expression_column(expression))
}
})
.collect::<Vec<_>>()
.join(", ");
format!("{variable} {{ {items} }}")
}
crate::cypher::ast::Expression::PatternComprehension { projection, .. } => {
format!("[pattern | {}]", scalar_expression_column(projection))
}
crate::cypher::ast::Expression::Coalesce(items) => {
let items = items
.iter()
.map(scalar_expression_column)
.collect::<Vec<_>>()
.join(", ");
format!("coalesce({items})")
}
crate::cypher::ast::Expression::ToLower(expression) => {
format!("toLower({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToUpper(expression) => {
format!("toUpper({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToString(expression) => {
format!("toString({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToInteger(expression) => {
format!("toInteger({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToFloat(expression) => {
format!("toFloat({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToBoolean(expression) => {
format!("toBoolean({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToStringOrNull(expression) => {
format!("toStringOrNull({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToIntegerOrNull(expression) => {
format!("toIntegerOrNull({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToFloatOrNull(expression) => {
format!("toFloatOrNull({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ToBooleanOrNull(expression) => {
format!("toBooleanOrNull({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::IsEmpty(expression) => {
format!("isEmpty({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Head(expression) => {
format!("head({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Last(expression) => {
format!("last({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Tail(expression) => {
format!("tail({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Range { start, end, step } => {
let start = scalar_expression_column(start);
let end = scalar_expression_column(end);
match step {
Some(step) => format!("range({start}, {end}, {})", scalar_expression_column(step)),
None => format!("range({start}, {end})"),
}
}
crate::cypher::ast::Expression::ListIndex { value, index } => {
format!(
"{}[{}]",
scalar_expression_column(value),
scalar_expression_column(index)
)
}
crate::cypher::ast::Expression::ListSlice { value, start, end } => {
let start = start
.as_ref()
.map(|start| scalar_expression_column(start))
.unwrap_or_default();
let end = end
.as_ref()
.map(|end| scalar_expression_column(end))
.unwrap_or_default();
format!("{}[{start}..{end}]", scalar_expression_column(value))
}
crate::cypher::ast::Expression::Size(expression) => {
format!("size({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Substring {
value,
start,
length,
} => {
let mut items = vec![
scalar_expression_column(value),
scalar_expression_column(start),
];
if let Some(length) = length {
items.push(scalar_expression_column(length));
}
format!("substring({})", items.join(", "))
}
crate::cypher::ast::Expression::Replace {
value,
search,
replacement,
} => format!(
"replace({}, {}, {})",
scalar_expression_column(value),
scalar_expression_column(search),
scalar_expression_column(replacement)
),
crate::cypher::ast::Expression::Trim { mode, expression } => {
let function = match mode {
crate::cypher::ast::TrimMode::Both => "trim",
crate::cypher::ast::TrimMode::Left => "lTrim",
crate::cypher::ast::TrimMode::Right => "rTrim",
};
format!("{function}({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Split { value, delimiter } => format!(
"split({}, {})",
scalar_expression_column(value),
scalar_expression_column(delimiter)
),
crate::cypher::ast::Expression::StringSlice {
mode,
value,
length,
} => {
let function = match mode {
crate::cypher::ast::StringSliceMode::Left => "left",
crate::cypher::ast::StringSliceMode::Right => "right",
};
format!(
"{function}({}, {})",
scalar_expression_column(value),
scalar_expression_column(length)
)
}
crate::cypher::ast::Expression::Reverse(expression) => {
format!("reverse({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Abs(expression) => {
format!("abs({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Rounding { mode, expression } => {
let function = match mode {
crate::cypher::ast::RoundingMode::Ceil => "ceil",
crate::cypher::ast::RoundingMode::Floor => "floor",
};
format!("{function}({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Sign(expression) => {
format!("sign({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Sqrt(expression) => {
format!("sqrt({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Round(expression) => {
format!("round({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Log(expression) => {
format!("log({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Log10(expression) => {
format!("log10({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Exp(expression) => {
format!("exp({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::AngleConversion { mode, expression } => {
let function = match mode {
crate::cypher::ast::AngleConversionMode::Degrees => "degrees",
crate::cypher::ast::AngleConversionMode::Radians => "radians",
};
format!("{function}({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Trigonometric { mode, expression } => {
let function = match mode {
crate::cypher::ast::TrigonometricMode::Sin => "sin",
crate::cypher::ast::TrigonometricMode::Cos => "cos",
crate::cypher::ast::TrigonometricMode::Tan => "tan",
crate::cypher::ast::TrigonometricMode::Cot => "cot",
};
format!("{function}({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::InverseTrigonometric { mode, expression } => {
let function = match mode {
crate::cypher::ast::InverseTrigonometricMode::Acos => "acos",
crate::cypher::ast::InverseTrigonometricMode::Asin => "asin",
crate::cypher::ast::InverseTrigonometricMode::Atan => "atan",
};
format!("{function}({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::Atan2 { y, x } => format!(
"atan2({}, {})",
scalar_expression_column(y),
scalar_expression_column(x)
),
crate::cypher::ast::Expression::Haversin(expression) => {
format!("haversin({})", scalar_expression_column(expression))
}
crate::cypher::ast::Expression::ListPredicate {
mode,
variable,
list,
..
} => {
let function = match mode {
crate::cypher::ast::ListPredicateMode::All => "all",
crate::cypher::ast::ListPredicateMode::Any => "any",
crate::cypher::ast::ListPredicateMode::None => "none",
crate::cypher::ast::ListPredicateMode::Single => "single",
};
format!(
"{function}({variable} IN {} WHERE predicate)",
scalar_expression_column(list)
)
}
crate::cypher::ast::Expression::ListComprehension {
variable,
list,
predicate,
projection,
} => {
let predicate = if predicate.is_some() {
" WHERE predicate"
} else {
""
};
format!(
"[{variable} IN {}{predicate} | {}]",
scalar_expression_column(list),
scalar_expression_column(projection)
)
}
crate::cypher::ast::Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => format!(
"reduce({accumulator} = {}, {variable} IN {} | {})",
scalar_expression_column(initial),
scalar_expression_column(list),
scalar_expression_column(expression)
),
crate::cypher::ast::Expression::Pi => "pi()".to_string(),
crate::cypher::ast::Expression::E => "e()".to_string(),
crate::cypher::ast::Expression::Case { .. }
| crate::cypher::ast::Expression::SimpleCase { .. } => "CASE".to_string(),
crate::cypher::ast::Expression::Predicate(_) => "predicate".to_string(),
}
}
fn operand_column(operand: &Operand) -> String {
match operand {
Operand::Literal(value) => scalar_literal_column(value),
Operand::Parameter(name) => format!("${name}"),
Operand::Property { variable, key } => format!("{variable}.{key}"),
Operand::DynamicProperty { variable, key } => {
format!("{variable}[{}]", scalar_expression_column(key))
}
Operand::Variable(variable) => variable.clone(),
}
}
fn scalar_literal_column(value: &crate::value::Value) -> String {
match value {
crate::value::Value::Null => "null".to_string(),
crate::value::Value::Boolean(value) => value.to_string(),
crate::value::Value::Integer(value) => value.to_string(),
crate::value::Value::Float(value) => value.to_string(),
crate::value::Value::String(value) => quoted_string_column(value),
crate::value::Value::List(_)
| crate::value::Value::Map(_)
| crate::value::Value::Node(_)
| crate::value::Value::Relationship(_)
| crate::value::Value::Path(_) => format!("{value:?}"),
}
}
fn quoted_string_column(value: &str) -> String {
let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
format!("'{escaped}'")
}
fn validate_predicate_variables(
predicate: Option<&Predicate>,
bound_variables: &[String],
) -> Result<()> {
if let Some(predicate) = predicate {
validate_predicate(predicate, bound_variables)?;
}
Ok(())
}
fn validate_match_predicates(match_clauses: &[MatchClause]) -> Result<()> {
validate_match_predicates_from(match_clauses, Vec::new(), BTreeMap::new())
}
fn validate_match_predicates_from(
match_clauses: &[MatchClause],
mut bound_variables: Vec<String>,
mut bindings: BTreeMap<String, BindingKind>,
) -> Result<()> {
for variable in &bound_variables {
bindings
.entry(variable.clone())
.or_insert(BindingKind::Node);
}
for clause in match_clauses {
for pattern in &clause.patterns {
bind_pattern_variables(pattern, &mut bound_variables, &mut bindings)?;
}
validate_predicate_variables(clause.predicate.as_ref(), &bound_variables)?;
}
Ok(())
}
fn with_bound_variables(
with: Option<&WithProjection>,
bound_variables: &[String],
) -> Result<Vec<String>> {
Ok(plan_with_projection(with, None, &[], None, None, bound_variables)?.1)
}
fn with_bindings(
with: Option<&WithProjection>,
bound_variables: &[String],
) -> Result<BTreeMap<String, BindingKind>> {
Ok(with_bound_variables(with, bound_variables)?
.into_iter()
.map(|variable| (variable, BindingKind::Node))
.collect())
}
fn validate_predicate(predicate: &Predicate, bound_variables: &[String]) -> Result<()> {
match predicate {
Predicate::Comparison { left, right, .. } => {
validate_expression(left, bound_variables)?;
validate_expression(right, bound_variables)
}
Predicate::In { item, list } => {
validate_expression(item, bound_variables)?;
validate_expression(list, bound_variables)
}
Predicate::StringMatch { left, right, .. } => {
validate_expression(left, bound_variables)?;
validate_expression(right, bound_variables)
}
Predicate::And(left, right) | Predicate::Or(left, right) | Predicate::Xor(left, right) => {
validate_predicate(left, bound_variables)?;
validate_predicate(right, bound_variables)
}
Predicate::Not(inner) => validate_predicate(inner, bound_variables),
Predicate::Pattern(pattern) => validate_pattern_predicate(pattern, bound_variables),
Predicate::IsNull(expression) | Predicate::IsNotNull(expression) => {
validate_expression(expression, bound_variables)
}
Predicate::Exists(operand) => validate_operand(operand, bound_variables),
Predicate::ExistsSubquery(matches) => validate_exists_subquery(matches, bound_variables),
Predicate::Boolean(expression) => validate_expression(expression, bound_variables),
}
}
fn validate_exists_subquery(matches: &[MatchClause], bound_variables: &[String]) -> Result<()> {
let bindings = bound_variables
.iter()
.cloned()
.map(|variable| (variable, BindingKind::Node))
.collect();
validate_match_predicates_from(matches, bound_variables.to_vec(), bindings)
}
fn validate_pattern_predicate(pattern: &Pattern, bound_variables: &[String]) -> Result<()> {
if pattern.variable.is_some() || pattern.shortest_path.is_some() || pattern.chains.len() != 1 {
return Err(Error::UnsupportedQueryFeature(
"WHERE pattern predicates currently support a single relationship pattern".to_string(),
));
}
let chain = &pattern.chains[0];
if chain.relationship.variable_length {
return Err(Error::UnsupportedQueryFeature(
"WHERE pattern predicates currently support typed single-hop relationships".to_string(),
));
}
for property in &chain.relationship.properties {
validate_expression(&property.expression, bound_variables)?;
}
let variables = [
pattern.start.variable.as_deref(),
chain.relationship.variable.as_deref(),
chain.node.variable.as_deref(),
];
if variables.iter().all(|variable| variable.is_none()) {
return Err(Error::Validation(
"WHERE pattern predicate must contain at least one bound endpoint variable".to_string(),
));
}
for variable in variables.into_iter().flatten() {
if !bound_variables.iter().any(|bound| bound == variable) {
return Err(Error::Validation(format!(
"WHERE pattern predicate variable `{variable}` is not bound by the MATCH pattern"
)));
}
}
Ok(())
}
fn validate_operand(operand: &Operand, bound_variables: &[String]) -> Result<()> {
let variable = match operand {
Operand::Property { variable, .. }
| Operand::DynamicProperty { variable, .. }
| Operand::Variable(variable) => Some(variable),
Operand::Literal(_) | Operand::Parameter(_) => None,
};
if let Some(variable) = variable {
if !bound_variables.iter().any(|bound| bound == variable) {
return Err(Error::Validation(format!(
"WHERE variable `{variable}` is not bound by the MATCH pattern"
)));
}
}
if let Operand::DynamicProperty { key, .. } = operand {
validate_expression(key, bound_variables)?;
}
Ok(())
}
fn validate_expression(
expression: &crate::cypher::ast::Expression,
bound_variables: &[String],
) -> Result<()> {
match expression {
crate::cypher::ast::Expression::Literal(_)
| crate::cypher::ast::Expression::Parameter(_) => Ok(()),
crate::cypher::ast::Expression::Operand(operand) => {
validate_operand(operand, bound_variables)
}
crate::cypher::ast::Expression::Add(left, right) => {
validate_expression(left, bound_variables)?;
validate_expression(right, bound_variables)
}
crate::cypher::ast::Expression::Subtract(left, right)
| crate::cypher::ast::Expression::Multiply(left, right)
| crate::cypher::ast::Expression::Divide(left, right)
| crate::cypher::ast::Expression::Modulo(left, right) => {
validate_expression(left, bound_variables)?;
validate_expression(right, bound_variables)
}
crate::cypher::ast::Expression::ToLower(expression)
| crate::cypher::ast::Expression::ToUpper(expression)
| crate::cypher::ast::Expression::ToString(expression)
| crate::cypher::ast::Expression::ToInteger(expression)
| crate::cypher::ast::Expression::ToFloat(expression)
| crate::cypher::ast::Expression::ToBoolean(expression)
| crate::cypher::ast::Expression::ToStringOrNull(expression)
| crate::cypher::ast::Expression::ToIntegerOrNull(expression)
| crate::cypher::ast::Expression::ToFloatOrNull(expression)
| crate::cypher::ast::Expression::ToBooleanOrNull(expression)
| crate::cypher::ast::Expression::IsEmpty(expression)
| crate::cypher::ast::Expression::Head(expression)
| crate::cypher::ast::Expression::Last(expression)
| crate::cypher::ast::Expression::Tail(expression)
| crate::cypher::ast::Expression::Size(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Range { start, end, step } => {
validate_expression(start, bound_variables)?;
validate_expression(end, bound_variables)?;
if let Some(step) = step {
validate_expression(step, bound_variables)?;
}
Ok(())
}
crate::cypher::ast::Expression::ListPredicate {
variable,
list,
predicate,
..
} => {
validate_expression(list, bound_variables)?;
let mut local_bound_variables = bound_variables.to_vec();
local_bound_variables.push(variable.clone());
validate_predicate(predicate, &local_bound_variables)
}
crate::cypher::ast::Expression::ListComprehension {
variable,
list,
predicate,
projection,
} => {
validate_expression(list, bound_variables)?;
let mut local_bound_variables = bound_variables.to_vec();
local_bound_variables.push(variable.clone());
if let Some(predicate) = predicate {
validate_predicate(predicate, &local_bound_variables)?;
}
validate_expression(projection, &local_bound_variables)
}
crate::cypher::ast::Expression::PatternComprehension {
pattern,
predicate,
projection,
} => {
let local_bound_variables =
pattern_comprehension_bound_variables(pattern, bound_variables)?;
if let Some(predicate) = predicate {
validate_predicate(predicate, &local_bound_variables)?;
}
validate_expression(projection, &local_bound_variables)
}
crate::cypher::ast::Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => {
validate_expression(initial, bound_variables)?;
validate_expression(list, bound_variables)?;
let mut local_bound_variables = bound_variables.to_vec();
local_bound_variables.push(accumulator.clone());
local_bound_variables.push(variable.clone());
validate_expression(expression, &local_bound_variables)
}
crate::cypher::ast::Expression::ListIndex { value, index } => {
validate_expression(value, bound_variables)?;
validate_expression(index, bound_variables)
}
crate::cypher::ast::Expression::ListSlice { value, start, end } => {
validate_expression(value, bound_variables)?;
if let Some(start) = start {
validate_expression(start, bound_variables)?;
}
if let Some(end) = end {
validate_expression(end, bound_variables)?;
}
Ok(())
}
crate::cypher::ast::Expression::Substring {
value,
start,
length,
} => {
validate_expression(value, bound_variables)?;
validate_expression(start, bound_variables)?;
if let Some(length) = length {
validate_expression(length, bound_variables)?;
}
Ok(())
}
crate::cypher::ast::Expression::Replace {
value,
search,
replacement,
} => {
validate_expression(value, bound_variables)?;
validate_expression(search, bound_variables)?;
validate_expression(replacement, bound_variables)
}
crate::cypher::ast::Expression::Trim { expression, .. } => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Split { value, delimiter } => {
validate_expression(value, bound_variables)?;
validate_expression(delimiter, bound_variables)
}
crate::cypher::ast::Expression::StringSlice { value, length, .. } => {
validate_expression(value, bound_variables)?;
validate_expression(length, bound_variables)
}
crate::cypher::ast::Expression::Reverse(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Abs(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Rounding { expression, .. } => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Sign(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Sqrt(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Round(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Log(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Log10(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Exp(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::AngleConversion { expression, .. } => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Trigonometric { expression, .. } => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::InverseTrigonometric { expression, .. } => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Atan2 { y, x } => {
validate_expression(y, bound_variables)?;
validate_expression(x, bound_variables)
}
crate::cypher::ast::Expression::Haversin(expression) => {
validate_expression(expression, bound_variables)
}
crate::cypher::ast::Expression::Pi | crate::cypher::ast::Expression::E => Ok(()),
crate::cypher::ast::Expression::List(items) => {
for item in items {
validate_expression(item, bound_variables)?;
}
Ok(())
}
crate::cypher::ast::Expression::Map(entries) => {
for value in entries.values() {
validate_expression(value, bound_variables)?;
}
Ok(())
}
crate::cypher::ast::Expression::MapProjection { variable, items } => {
validate_return_variable(variable, bound_variables)?;
for item in items {
match item {
crate::cypher::ast::MapProjectionItem::Variable(variable) => {
validate_return_variable(variable, bound_variables)?;
}
crate::cypher::ast::MapProjectionItem::Expression { expression, .. } => {
validate_expression(expression, bound_variables)?;
}
crate::cypher::ast::MapProjectionItem::AllProperties
| crate::cypher::ast::MapProjectionItem::Property(_) => {}
}
}
Ok(())
}
crate::cypher::ast::Expression::Coalesce(items) => {
for item in items {
validate_expression(item, bound_variables)?;
}
Ok(())
}
crate::cypher::ast::Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
validate_predicate(&alternative.predicate, bound_variables)?;
validate_expression(&alternative.expression, bound_variables)?;
}
validate_expression(else_expression, bound_variables)
}
crate::cypher::ast::Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
validate_expression(operand, bound_variables)?;
for alternative in alternatives {
validate_expression(&alternative.value, bound_variables)?;
validate_expression(&alternative.expression, bound_variables)?;
}
validate_expression(else_expression, bound_variables)
}
crate::cypher::ast::Expression::Predicate(predicate) => {
validate_predicate(predicate, bound_variables)
}
}
}
fn collect_bound_variables(pattern: &Pattern) -> Result<Vec<String>> {
let mut bound_variables = Vec::new();
let mut bindings = BTreeMap::new();
bind_pattern_variables(pattern, &mut bound_variables, &mut bindings)?;
Ok(bound_variables)
}
fn pattern_comprehension_bound_variables(
pattern: &Pattern,
bound_variables: &[String],
) -> Result<Vec<String>> {
let mut local_bound_variables = bound_variables.to_vec();
let mut bindings = BTreeMap::new();
for variable in &local_bound_variables {
bindings.insert(variable.clone(), BindingKind::Node);
}
bind_pattern_variables(pattern, &mut local_bound_variables, &mut bindings)?;
Ok(local_bound_variables)
}
fn collect_match_bound_variables(match_clauses: &[MatchClause]) -> Result<Vec<String>> {
collect_match_bound_variables_from(match_clauses, Vec::new())
}
fn collect_match_bound_variables_from(
match_clauses: &[MatchClause],
initial_bound_variables: Vec<String>,
) -> Result<Vec<String>> {
let mut bound_variables = initial_bound_variables;
let mut bindings = BTreeMap::new();
for variable in &bound_variables {
bindings.insert(variable.clone(), BindingKind::Node);
}
for clause in match_clauses {
for pattern in &clause.patterns {
bind_pattern_variables(pattern, &mut bound_variables, &mut bindings)?;
}
}
Ok(bound_variables)
}
fn bind_pattern_variables(
pattern: &Pattern,
bound_variables: &mut Vec<String>,
bindings: &mut BTreeMap<String, BindingKind>,
) -> Result<()> {
bind_variable(
bound_variables,
bindings,
pattern.variable.as_ref(),
BindingKind::Path,
)?;
bind_variable(
bound_variables,
bindings,
pattern.start.variable.as_ref(),
BindingKind::Node,
)?;
for chain in &pattern.chains {
if !chain.relationship.variable_length {
bind_variable(
bound_variables,
bindings,
chain.relationship.variable.as_ref(),
BindingKind::Relationship,
)?;
}
bind_variable(
bound_variables,
bindings,
chain.node.variable.as_ref(),
BindingKind::Node,
)?;
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BindingKind {
Node,
Relationship,
Path,
}
fn bind_variable(
bound_variables: &mut Vec<String>,
bindings: &mut BTreeMap<String, BindingKind>,
variable: Option<&String>,
kind: BindingKind,
) -> Result<()> {
if let Some(variable) = variable {
if let Some(existing) = bindings.get(variable) {
if existing != &kind {
return Err(Error::Validation(format!(
"variable `{variable}` cannot bind multiple incompatible values"
)));
}
} else {
bindings.insert(variable.clone(), kind);
bound_variables.push(variable.clone());
}
}
Ok(())
}
fn is_internal_variable(variable: &str) -> bool {
variable.starts_with("__littlegraph_anon_")
}
#[cfg(all(test, any()))]
mod tests {
use crate::cypher::ast::{Predicate, ReturnExpression, ReturnItem, RowCount};
use crate::cypher::parser::parse_query;
use crate::error::Error;
use super::plan;
fn variable_expression(item: &ReturnItem) -> &str {
match &item.expression {
ReturnExpression::Variable(variable) => variable,
expression => panic!("expected variable return expression, got {expression:?}"),
}
}
fn property_expression(item: &ReturnItem) -> (&str, &str) {
match &item.expression {
ReturnExpression::Property { variable, key } => (variable, key),
expression => panic!("expected property return expression, got {expression:?}"),
}
}
#[test]
fn rejects_return_variable_not_bound_by_pattern() {
let query = parse_query("MATCH (person:Person) RETURN other").expect("parse query");
let error = plan(query).expect_err("unbound return variable should fail validation");
assert!(matches!(error, Error::Validation(message) if message.contains("other")));
}
#[test]
fn accepts_static_return_without_match() {
let plan = plan(parse_query("RETURN 1 AS one").expect("parse query")).expect("plan query");
assert!(!plan.has_initial_match);
assert!(plan.bound_variables.is_empty());
assert_eq!(plan.returns.len(), 1);
}
#[test]
fn rejects_unbound_variable_return_without_match() {
let query = parse_query("RETURN n").expect("parse query");
let error = plan(query).expect_err("unbound return variable should fail validation");
assert!(matches!(error, Error::Validation(message) if message.contains("n")));
}
#[test]
fn accepts_bound_node_relationship_variables_and_property_projection() {
let query = parse_query("MATCH (a)-[r:KNOWS]->(b)<-[:LIKES]-() RETURN a, r, b.name")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.bound_variables, vec!["a", "r", "b"]);
assert_eq!(variable_expression(&plan.returns[0]), "a");
assert_eq!(variable_expression(&plan.returns[1]), "r");
assert_eq!(property_expression(&plan.returns[2]), ("b", "name"));
}
#[test]
fn carries_optional_match_into_plan() {
let query = parse_query("OPTIONAL MATCH (n:Person) RETURN n").expect("parse query");
let plan = plan(query).expect("plan optional match");
assert!(plan.optional_match);
assert_eq!(plan.bound_variables, vec!["n"]);
}
#[test]
fn accepts_variable_length_relationship_without_binding_relationship_variable() {
let query = parse_query("MATCH (a)-[r*]->(b) RETURN a, b").expect("parse query");
let plan = plan(query).expect("plan variable length query");
assert_eq!(plan.bound_variables, vec!["a".to_string(), "b".to_string()]);
}
#[test]
fn rejects_returning_variable_length_relationship_variable() {
let query = parse_query("MATCH (a)-[r*]->(b) RETURN r").expect("parse query");
let error = plan(query).expect_err("variable-length relationship variable is unbound");
assert!(matches!(error, Error::Validation(message) if message.contains("r")));
}
#[test]
fn expands_return_star_to_bound_variables() {
let query = parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN *").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(
plan.returns
.iter()
.map(variable_expression)
.collect::<Vec<_>>(),
vec!["a", "r", "b"]
);
assert!(plan.returns.iter().all(|item| matches!(
item.expression,
ReturnExpression::Variable(_)
) && item.alias.is_none()));
}
#[test]
fn expands_mixed_return_star_in_item_order() {
let query = parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN a.name, *, type(r) AS rel_type")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(property_expression(&plan.returns[0]), ("a", "name"));
assert_eq!(
plan.returns
.iter()
.skip(1)
.take(3)
.map(variable_expression)
.collect::<Vec<_>>(),
vec!["a", "r", "b"]
);
assert!(matches!(
plan.returns[4].expression,
ReturnExpression::Type(_)
));
assert_eq!(plan.returns[4].alias.as_deref(), Some("rel_type"));
}
#[test]
fn accepts_order_by_expanded_return_star_variable() {
let query =
parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN * ORDER BY a").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_expanded_mixed_return_star_variable() {
let query = parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN a.name, * ORDER BY b")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_return_count_expressions() {
let star = plan(parse_query("MATCH (n:Person) RETURN count(*)").expect("parse query"))
.expect("plan count star");
let variable =
plan(parse_query("MATCH (n:Person) RETURN count(n) AS total").expect("parse query"))
.expect("plan count variable");
let distinct = plan(
parse_query("MATCH (n:Person) RETURN count(DISTINCT n) AS total").expect("parse query"),
)
.expect("plan count distinct variable");
let property = plan(
parse_query("MATCH (n:Person) RETURN count(n.name) AS total").expect("parse query"),
)
.expect("plan count property");
let distinct_property = plan(
parse_query("MATCH (n:Person) RETURN count(DISTINCT n.name) AS total")
.expect("parse query"),
)
.expect("plan count distinct property");
assert_eq!(star.returns.len(), 1);
assert_eq!(variable.returns.len(), 1);
assert_eq!(distinct.returns.len(), 1);
assert_eq!(property.returns.len(), 1);
assert_eq!(distinct_property.returns.len(), 1);
}
#[test]
fn accepts_return_scalar_expressions() {
let query = parse_query("MATCH (n:Person) RETURN n.name, 1 AS one, $tag AS tag")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.returns.len(), 3);
}
#[test]
fn accepts_return_graph_functions() {
let query =
parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN labels(a) AS labels, type(r) AS rel_type")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_return_properties_function() {
let query = parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN properties(a), properties(r)")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_return_keys_function() {
let query =
parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN keys(a), keys(r)").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_return_element_id_function() {
let query = parse_query("MATCH (a)-[r:KNOWS]->(b) RETURN elementId(a), elementId(r)")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_order_by_returned_scalar_literal_expression() {
let query =
parse_query("MATCH (n:Person) RETURN n.name, 1 ORDER BY 1").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_returned_scalar_parameter_expression() {
let query =
parse_query("MATCH (n:Person) RETURN n.name, $tag ORDER BY $tag").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_scalar_expression_not_returned() {
let query = parse_query("MATCH (n:Person) RETURN n.name ORDER BY 1").expect("parse query");
let plan = plan(query).expect("ORDER BY scalar expression not returned");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_parameter() {
let query =
parse_query("MATCH (n:Person) RETURN n.name ORDER BY $tag").expect("parse query");
let plan = plan(query).expect("ORDER BY parameter");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_graph_function_expression() {
let query = parse_query("MATCH (n:Person) RETURN n.name ORDER BY elementId(n) DESC")
.expect("parse query");
let plan = plan(query).expect("ORDER BY graph function not returned");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_properties_expression() {
let query = parse_query("MATCH (n:Person) RETURN n.name ORDER BY properties(n)")
.expect("parse query");
let plan = plan(query).expect("ORDER BY properties not returned");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_keys_expression() {
let query =
parse_query("MATCH (n:Person) RETURN n.name ORDER BY keys(n)").expect("parse query");
let plan = plan(query).expect("ORDER BY keys not returned");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_element_id_expression() {
let query = parse_query("MATCH (n:Person) RETURN n.name ORDER BY elementId(n)")
.expect("parse query");
let plan = plan(query).expect("ORDER BY elementId not returned");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_returned_graph_function_expression() {
let query = parse_query("MATCH (n:Person) RETURN elementId(n) ORDER BY elementId(n)")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_graph_function_not_returned() {
let query = parse_query("MATCH (n:Person) RETURN n.name ORDER BY elementId(n)")
.expect("parse query");
let plan = plan(query).expect("ORDER BY graph function not returned");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_grouped_count_with_supported_group_key_returns() {
for query in [
"MATCH (n:Person) RETURN count(n), 1",
"MATCH (n:Person) RETURN count(n), labels(n)",
"MATCH (n:Person) RETURN count(n), properties(n)",
"MATCH (n:Person) RETURN count(n), n.*",
"MATCH (n:Person) RETURN count(n), keys(n)",
"MATCH (n:Person) RETURN count(n), elementId(n)",
] {
let plan = plan(parse_query(query).expect("parse query")).expect("plan query");
assert_eq!(plan.returns.len(), 2);
}
}
#[test]
fn rejects_return_graph_function_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN labels(m)").expect("parse query");
let error = plan(query).expect_err("unbound graph function variable");
assert!(matches!(error, Error::Validation(message) if message.contains("RETURN")));
}
#[test]
fn rejects_return_properties_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN properties(m)").expect("parse query");
let error = plan(query).expect_err("unbound properties variable");
assert!(matches!(error, Error::Validation(message) if message.contains("RETURN")));
}
#[test]
fn accepts_return_property_wildcard_bound_variable() {
let query = parse_query("MATCH (n:Person) RETURN n.*").expect("parse query");
let plan = plan(query).expect("plan query");
assert!(matches!(
plan.returns[0].expression,
ReturnExpression::PropertyWildcard(_)
));
}
#[test]
fn rejects_return_property_wildcard_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN m.*").expect("parse query");
let error = plan(query).expect_err("unbound property wildcard variable");
assert!(matches!(error, Error::Validation(message) if message.contains("m")));
}
#[test]
fn rejects_return_keys_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN keys(m)").expect("parse query");
let error = plan(query).expect_err("unbound keys variable");
assert!(matches!(error, Error::Validation(message) if message.contains("RETURN")));
}
#[test]
fn rejects_return_element_id_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN elementId(m)").expect("parse query");
let error = plan(query).expect_err("unbound elementId variable");
assert!(matches!(error, Error::Validation(message) if message.contains("RETURN")));
}
#[test]
fn rejects_return_count_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN count(m)").expect("parse query");
let error = plan(query).expect_err("unbound count variable");
assert!(matches!(error, Error::Validation(message) if message.contains("m")));
}
#[test]
fn rejects_return_count_distinct_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN count(DISTINCT m)").expect("parse query");
let error = plan(query).expect_err("unbound count distinct variable");
assert!(matches!(error, Error::Validation(message) if message.contains("m")));
}
#[test]
fn rejects_return_count_property_unbound_variable() {
let query = parse_query("MATCH (n:Person) RETURN count(m.name)").expect("parse query");
let error = plan(query).expect_err("unbound count property variable");
assert!(matches!(error, Error::Validation(message) if message.contains("m")));
}
#[test]
fn rejects_return_count_distinct_property_unbound_variable() {
let query =
parse_query("MATCH (n:Person) RETURN count(DISTINCT m.name)").expect("parse query");
let error = plan(query).expect_err("unbound count distinct property variable");
assert!(matches!(error, Error::Validation(message) if message.contains("m")));
}
#[test]
fn accepts_grouped_count_and_variable_returns() {
let query = parse_query("MATCH (n:Person) RETURN count(n), n").expect("parse query");
let plan = plan(query).expect("plan grouped aggregate return");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_grouped_count_distinct_and_variable_returns() {
let query =
parse_query("MATCH (n:Person) RETURN count(DISTINCT n), n").expect("parse query");
let plan = plan(query).expect("plan grouped aggregate return");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_grouped_count_property_and_variable_returns() {
let query = parse_query("MATCH (n:Person) RETURN count(n.name), n").expect("parse query");
let plan = plan(query).expect("plan grouped aggregate return");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_grouped_count_distinct_property_and_variable_returns() {
let query =
parse_query("MATCH (n:Person) RETURN count(DISTINCT n.name), n").expect("parse query");
let plan = plan(query).expect("plan grouped aggregate return");
assert_eq!(plan.returns.len(), 2);
}
#[test]
fn accepts_multiple_count_returns() {
let query = parse_query(
"MATCH (n:Person) RETURN count(*), count(n), count(n.name), count(DISTINCT n.name)",
)
.expect("parse query");
let plan = plan(query).expect("plan multiple aggregate return");
assert_eq!(plan.returns.len(), 4);
}
#[test]
fn accepts_non_projected_order_by_count_expression_for_aggregate_returns() {
let query =
parse_query("MATCH (n:Person) RETURN count(n) ORDER BY count(*)").expect("parse query");
let plan = plan(query).expect("plan aggregate order");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_non_projected_order_by_count_forms_for_aggregate_returns() {
for query in [
"MATCH (n:Person) RETURN count(*) ORDER BY count(n)",
"MATCH (n:Person) RETURN count(*) ORDER BY count(DISTINCT n)",
"MATCH (n:Person) RETURN count(*) ORDER BY count(n.name)",
"MATCH (n:Person) RETURN count(*) ORDER BY count(DISTINCT n.name)",
] {
let plan = plan(parse_query(query).expect("parse query")).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
}
#[test]
fn rejects_non_projected_order_by_count_expression_for_non_aggregate_returns() {
let query =
parse_query("MATCH (n:Person) RETURN n.name ORDER BY count(*)").expect("parse query");
let error = plan(query).expect_err("ORDER BY aggregate expression");
assert!(matches!(error, Error::Validation(message) if message.contains("ORDER BY")));
}
#[test]
fn accepts_order_by_returned_count_expressions() {
let star =
parse_query("MATCH (n:Person) RETURN count(*) ORDER BY count(*)").expect("parse query");
let variable =
parse_query("MATCH (n:Person) RETURN count(n) ORDER BY count(n)").expect("parse query");
let distinct =
parse_query("MATCH (n:Person) RETURN count(DISTINCT n) ORDER BY count(DISTINCT n)")
.expect("parse query");
let property = parse_query("MATCH (n:Person) RETURN count(n.name) ORDER BY count(n.name)")
.expect("parse query");
let distinct_property = parse_query(
"MATCH (n:Person) RETURN count(DISTINCT n.name) ORDER BY count(DISTINCT n.name)",
)
.expect("parse query");
let star_plan = plan(star).expect("plan count star order");
let variable_plan = plan(variable).expect("plan count variable order");
let distinct_plan = plan(distinct).expect("plan count distinct variable order");
let property_plan = plan(property).expect("plan count property order");
let distinct_property_plan =
plan(distinct_property).expect("plan count distinct property order");
assert_eq!(star_plan.order_by.len(), 1);
assert_eq!(variable_plan.order_by.len(), 1);
assert_eq!(distinct_plan.order_by.len(), 1);
assert_eq!(property_plan.order_by.len(), 1);
assert_eq!(distinct_property_plan.order_by.len(), 1);
}
#[test]
fn rejects_order_by_count_unbound_variable() {
let query =
parse_query("MATCH (n:Person) RETURN count(n) ORDER BY count(m)").expect("parse query");
let error = plan(query).expect_err("ORDER BY count unbound variable");
assert!(matches!(error, Error::Validation(message) if message.contains("ORDER BY")));
}
#[test]
fn accepts_order_by_property_with_return_star() {
let query = parse_query("MATCH (n:Person) RETURN * ORDER BY n.name").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_where_variables_bound_by_pattern() {
let query =
parse_query("MATCH (n)-[r]->(m) WHERE n.age >= 18 AND r.since IS NOT NULL RETURN m")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert!(plan.predicate.is_some());
}
#[test]
fn accepts_where_in_bound_property_and_parameter_list() {
let query = parse_query("MATCH (n:Person) WHERE n.name IN $names RETURN n.name")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert!(matches!(plan.predicate, Some(Predicate::In { .. })));
}
#[test]
fn accepts_where_string_predicate_bound_operands() {
let query = parse_query("MATCH (n:Person) WHERE n.name STARTS WITH $prefix RETURN n.name")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert!(matches!(
plan.predicate,
Some(Predicate::StringMatch { .. })
));
}
#[test]
fn rejects_where_string_predicate_unbound_variable() {
let query = parse_query("MATCH (n:Person) WHERE missing.name CONTAINS 'A' RETURN n.name")
.expect("parse query");
let error = plan(query).expect_err("unbound string predicate variable");
assert!(matches!(error, Error::Validation(message) if message.contains("missing")));
}
#[test]
fn rejects_where_in_unbound_left_variable() {
let query = parse_query("MATCH (n:Person) WHERE missing.name IN ['Alice'] RETURN n.name")
.expect("parse query");
let error = plan(query).expect_err("unbound IN left variable");
assert!(matches!(error, Error::Validation(message) if message.contains("missing")));
}
#[test]
fn rejects_where_property_variable_not_bound_by_pattern() {
let query =
parse_query("MATCH (n) WHERE missing.name = 'Alice' RETURN n").expect("parse query");
let error = plan(query).expect_err("unbound WHERE variable");
assert!(matches!(error, Error::Validation(message) if message.contains("missing")));
}
#[test]
fn rejects_where_entity_variable_not_bound_by_pattern() {
let query = parse_query("MATCH (n) WHERE missing IS NULL RETURN n").expect("parse query");
let error = plan(query).expect_err("unbound WHERE variable");
assert!(matches!(error, Error::Validation(message) if message.contains("missing")));
}
#[test]
fn accepts_order_by_returned_items_and_limit() {
let query = parse_query(
"MATCH (n:Person) RETURN n.name, n.age ORDER BY n.age DESC, n.name ASC LIMIT 2",
)
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 2);
assert!(plan.limit.is_some());
}
#[test]
fn carries_return_distinct_into_plan() {
let query = parse_query("MATCH (n:Person) RETURN DISTINCT n.name").expect("parse query");
let plan = plan(query).expect("plan query");
assert!(plan.distinct);
}
#[test]
fn validates_order_by_alias_with_return_distinct() {
let query = parse_query("MATCH (n:Person) RETURN DISTINCT n.name AS name ORDER BY name")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert!(plan.distinct);
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_return_alias() {
let query = parse_query("MATCH (n:Person) RETURN n.name AS name ORDER BY name")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_order_by_original_expression_when_return_has_alias() {
let query = parse_query("MATCH (n:Person) RETURN n.name AS name ORDER BY n.name")
.expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn rejects_unknown_order_by_alias() {
let query = parse_query("MATCH (n:Person) RETURN n.name AS name ORDER BY missing")
.expect("parse query");
let error = plan(query).expect_err("unknown alias");
assert!(matches!(error, Error::Validation(message) if message.contains("ORDER BY")));
}
#[test]
fn accepts_non_projected_order_by_item_for_non_distinct_return() {
let query =
parse_query("MATCH (n:Person) RETURN n.name ORDER BY n.age").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn accepts_non_projected_order_by_item_for_distinct_return() {
let query = parse_query("MATCH (n:Person) RETURN DISTINCT n.name ORDER BY n.age")
.expect("parse query");
let plan = plan(query).expect("DISTINCT ORDER BY item must be returned");
assert_eq!(plan.order_by.len(), 1);
}
#[test]
fn rejects_order_by_variable_not_bound_by_pattern() {
let query = parse_query("MATCH (n:Person) RETURN n.name ORDER BY missing.name")
.expect("parse query");
let error = plan(query).expect_err("unbound ORDER BY variable");
assert!(matches!(error, Error::Validation(message) if message.contains("missing")));
}
#[test]
fn rejects_negative_literal_limit() {
let query = parse_query("MATCH (n:Person) RETURN n.name LIMIT -1").expect("parse query");
let error = plan(query).expect_err("negative limit");
assert!(matches!(error, Error::Validation(message) if message.contains("LIMIT")));
}
#[test]
fn rejects_invalid_literal_limit_types_as_validation_errors() {
for query in [
"MATCH (n:Person) RETURN n.name LIMIT 1.5",
"MATCH (n:Person) RETURN n.name LIMIT true",
"MATCH (n:Person) RETURN n.name LIMIT null",
"MATCH (n:Person) RETURN n.name LIMIT 'two'",
] {
let query = parse_query(query).expect("parse query");
let error = plan(query).expect_err("invalid limit literal");
assert!(matches!(error, Error::Validation(message) if message.contains("LIMIT")));
}
}
#[test]
fn accepts_non_negative_literal_skip() {
let query = parse_query("MATCH (n:Person) RETURN n.name SKIP 1").expect("parse query");
let plan = plan(query).expect("plan query");
assert_eq!(plan.skip, Some(RowCount::Literal(1)));
}
#[test]
fn rejects_negative_literal_skip() {
let query = parse_query("MATCH (n:Person) RETURN n.name SKIP -1").expect("parse query");
let error = plan(query).expect_err("negative skip");
assert!(matches!(error, Error::Validation(message) if message.contains("SKIP")));
}
#[test]
fn rejects_invalid_literal_skip_types_as_validation_errors() {
for query in [
"MATCH (n:Person) RETURN n.name SKIP 1.5",
"MATCH (n:Person) RETURN n.name SKIP true",
"MATCH (n:Person) RETURN n.name SKIP null",
"MATCH (n:Person) RETURN n.name SKIP 'two'",
] {
let query = parse_query(query).expect("parse query");
let error = plan(query).expect_err("invalid skip literal");
assert!(matches!(error, Error::Validation(message) if message.contains("SKIP")));
}
}
#[test]
fn rejects_reusing_variable_for_node_and_relationship() {
let query = parse_query("MATCH (a)-[a]->(b) RETURN a").expect("parse query");
let error = plan(query).expect_err("same variable cannot bind node and relationship");
assert!(matches!(error, Error::Validation(message) if message.contains("a")));
}
}